HWPOISON: Add simple debugfs interface to inject hwpoison on arbitary PFNs
[linux-2.6.git] / mm / page_alloc.c
blob9faa7ad95ac536ad34f16bf16996261554705fc3
1 /*
2 * linux/mm/page_alloc.c
4 * Manages the free list, the system allocates free pages here.
5 * Note that kmalloc() lives in slab.c
7 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
8 * Swap reorganised 29.12.95, Stephen Tweedie
9 * Support of BIGMEM added by Gerhard Wichert, Siemens AG, July 1999
10 * Reshaped it to be a zoned allocator, Ingo Molnar, Red Hat, 1999
11 * Discontiguous memory support, Kanoj Sarcar, SGI, Nov 1999
12 * Zone balancing, Kanoj Sarcar, SGI, Jan 2000
13 * Per cpu hot/cold page lists, bulk allocation, Martin J. Bligh, Sept 2002
14 * (lots of bits borrowed from Ingo Molnar & Andrew Morton)
17 #include <linux/stddef.h>
18 #include <linux/mm.h>
19 #include <linux/swap.h>
20 #include <linux/interrupt.h>
21 #include <linux/pagemap.h>
22 #include <linux/jiffies.h>
23 #include <linux/bootmem.h>
24 #include <linux/compiler.h>
25 #include <linux/kernel.h>
26 #include <linux/kmemcheck.h>
27 #include <linux/module.h>
28 #include <linux/suspend.h>
29 #include <linux/pagevec.h>
30 #include <linux/blkdev.h>
31 #include <linux/slab.h>
32 #include <linux/oom.h>
33 #include <linux/notifier.h>
34 #include <linux/topology.h>
35 #include <linux/sysctl.h>
36 #include <linux/cpu.h>
37 #include <linux/cpuset.h>
38 #include <linux/memory_hotplug.h>
39 #include <linux/nodemask.h>
40 #include <linux/vmalloc.h>
41 #include <linux/mempolicy.h>
42 #include <linux/stop_machine.h>
43 #include <linux/sort.h>
44 #include <linux/pfn.h>
45 #include <linux/backing-dev.h>
46 #include <linux/fault-inject.h>
47 #include <linux/page-isolation.h>
48 #include <linux/page_cgroup.h>
49 #include <linux/debugobjects.h>
50 #include <linux/kmemleak.h>
52 #include <asm/tlbflush.h>
53 #include <asm/div64.h>
54 #include "internal.h"
57 * Array of node states.
59 nodemask_t node_states[NR_NODE_STATES] __read_mostly = {
60 [N_POSSIBLE] = NODE_MASK_ALL,
61 [N_ONLINE] = { { [0] = 1UL } },
62 #ifndef CONFIG_NUMA
63 [N_NORMAL_MEMORY] = { { [0] = 1UL } },
64 #ifdef CONFIG_HIGHMEM
65 [N_HIGH_MEMORY] = { { [0] = 1UL } },
66 #endif
67 [N_CPU] = { { [0] = 1UL } },
68 #endif /* NUMA */
70 EXPORT_SYMBOL(node_states);
72 unsigned long totalram_pages __read_mostly;
73 unsigned long totalreserve_pages __read_mostly;
74 unsigned long highest_memmap_pfn __read_mostly;
75 int percpu_pagelist_fraction;
76 gfp_t gfp_allowed_mask __read_mostly = GFP_BOOT_MASK;
78 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
79 int pageblock_order __read_mostly;
80 #endif
82 static void __free_pages_ok(struct page *page, unsigned int order);
85 * results with 256, 32 in the lowmem_reserve sysctl:
86 * 1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
87 * 1G machine -> (16M dma, 784M normal, 224M high)
88 * NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
89 * HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
90 * HIGHMEM allocation will (224M+784M)/256 of ram reserved in ZONE_DMA
92 * TBD: should special case ZONE_DMA32 machines here - in those we normally
93 * don't need any ZONE_NORMAL reservation
95 int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES-1] = {
96 #ifdef CONFIG_ZONE_DMA
97 256,
98 #endif
99 #ifdef CONFIG_ZONE_DMA32
100 256,
101 #endif
102 #ifdef CONFIG_HIGHMEM
104 #endif
108 EXPORT_SYMBOL(totalram_pages);
110 static char * const zone_names[MAX_NR_ZONES] = {
111 #ifdef CONFIG_ZONE_DMA
112 "DMA",
113 #endif
114 #ifdef CONFIG_ZONE_DMA32
115 "DMA32",
116 #endif
117 "Normal",
118 #ifdef CONFIG_HIGHMEM
119 "HighMem",
120 #endif
121 "Movable",
124 int min_free_kbytes = 1024;
126 unsigned long __meminitdata nr_kernel_pages;
127 unsigned long __meminitdata nr_all_pages;
128 static unsigned long __meminitdata dma_reserve;
130 #ifdef CONFIG_ARCH_POPULATES_NODE_MAP
132 * MAX_ACTIVE_REGIONS determines the maximum number of distinct
133 * ranges of memory (RAM) that may be registered with add_active_range().
134 * Ranges passed to add_active_range() will be merged if possible
135 * so the number of times add_active_range() can be called is
136 * related to the number of nodes and the number of holes
138 #ifdef CONFIG_MAX_ACTIVE_REGIONS
139 /* Allow an architecture to set MAX_ACTIVE_REGIONS to save memory */
140 #define MAX_ACTIVE_REGIONS CONFIG_MAX_ACTIVE_REGIONS
141 #else
142 #if MAX_NUMNODES >= 32
143 /* If there can be many nodes, allow up to 50 holes per node */
144 #define MAX_ACTIVE_REGIONS (MAX_NUMNODES*50)
145 #else
146 /* By default, allow up to 256 distinct regions */
147 #define MAX_ACTIVE_REGIONS 256
148 #endif
149 #endif
151 static struct node_active_region __meminitdata early_node_map[MAX_ACTIVE_REGIONS];
152 static int __meminitdata nr_nodemap_entries;
153 static unsigned long __meminitdata arch_zone_lowest_possible_pfn[MAX_NR_ZONES];
154 static unsigned long __meminitdata arch_zone_highest_possible_pfn[MAX_NR_ZONES];
155 static unsigned long __initdata required_kernelcore;
156 static unsigned long __initdata required_movablecore;
157 static unsigned long __meminitdata zone_movable_pfn[MAX_NUMNODES];
159 /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
160 int movable_zone;
161 EXPORT_SYMBOL(movable_zone);
162 #endif /* CONFIG_ARCH_POPULATES_NODE_MAP */
164 #if MAX_NUMNODES > 1
165 int nr_node_ids __read_mostly = MAX_NUMNODES;
166 int nr_online_nodes __read_mostly = 1;
167 EXPORT_SYMBOL(nr_node_ids);
168 EXPORT_SYMBOL(nr_online_nodes);
169 #endif
171 int page_group_by_mobility_disabled __read_mostly;
173 static void set_pageblock_migratetype(struct page *page, int migratetype)
176 if (unlikely(page_group_by_mobility_disabled))
177 migratetype = MIGRATE_UNMOVABLE;
179 set_pageblock_flags_group(page, (unsigned long)migratetype,
180 PB_migrate, PB_migrate_end);
183 bool oom_killer_disabled __read_mostly;
185 #ifdef CONFIG_DEBUG_VM
186 static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
188 int ret = 0;
189 unsigned seq;
190 unsigned long pfn = page_to_pfn(page);
192 do {
193 seq = zone_span_seqbegin(zone);
194 if (pfn >= zone->zone_start_pfn + zone->spanned_pages)
195 ret = 1;
196 else if (pfn < zone->zone_start_pfn)
197 ret = 1;
198 } while (zone_span_seqretry(zone, seq));
200 return ret;
203 static int page_is_consistent(struct zone *zone, struct page *page)
205 if (!pfn_valid_within(page_to_pfn(page)))
206 return 0;
207 if (zone != page_zone(page))
208 return 0;
210 return 1;
213 * Temporary debugging check for pages not lying within a given zone.
215 static int bad_range(struct zone *zone, struct page *page)
217 if (page_outside_zone_boundaries(zone, page))
218 return 1;
219 if (!page_is_consistent(zone, page))
220 return 1;
222 return 0;
224 #else
225 static inline int bad_range(struct zone *zone, struct page *page)
227 return 0;
229 #endif
231 static void bad_page(struct page *page)
233 static unsigned long resume;
234 static unsigned long nr_shown;
235 static unsigned long nr_unshown;
237 /* Don't complain about poisoned pages */
238 if (PageHWPoison(page)) {
239 __ClearPageBuddy(page);
240 return;
244 * Allow a burst of 60 reports, then keep quiet for that minute;
245 * or allow a steady drip of one report per second.
247 if (nr_shown == 60) {
248 if (time_before(jiffies, resume)) {
249 nr_unshown++;
250 goto out;
252 if (nr_unshown) {
253 printk(KERN_ALERT
254 "BUG: Bad page state: %lu messages suppressed\n",
255 nr_unshown);
256 nr_unshown = 0;
258 nr_shown = 0;
260 if (nr_shown++ == 0)
261 resume = jiffies + 60 * HZ;
263 printk(KERN_ALERT "BUG: Bad page state in process %s pfn:%05lx\n",
264 current->comm, page_to_pfn(page));
265 printk(KERN_ALERT
266 "page:%p flags:%p count:%d mapcount:%d mapping:%p index:%lx\n",
267 page, (void *)page->flags, page_count(page),
268 page_mapcount(page), page->mapping, page->index);
270 dump_stack();
271 out:
272 /* Leave bad fields for debug, except PageBuddy could make trouble */
273 __ClearPageBuddy(page);
274 add_taint(TAINT_BAD_PAGE);
278 * Higher-order pages are called "compound pages". They are structured thusly:
280 * The first PAGE_SIZE page is called the "head page".
282 * The remaining PAGE_SIZE pages are called "tail pages".
284 * All pages have PG_compound set. All pages have their ->private pointing at
285 * the head page (even the head page has this).
287 * The first tail page's ->lru.next holds the address of the compound page's
288 * put_page() function. Its ->lru.prev holds the order of allocation.
289 * This usage means that zero-order pages may not be compound.
292 static void free_compound_page(struct page *page)
294 __free_pages_ok(page, compound_order(page));
297 void prep_compound_page(struct page *page, unsigned long order)
299 int i;
300 int nr_pages = 1 << order;
302 set_compound_page_dtor(page, free_compound_page);
303 set_compound_order(page, order);
304 __SetPageHead(page);
305 for (i = 1; i < nr_pages; i++) {
306 struct page *p = page + i;
308 __SetPageTail(p);
309 p->first_page = page;
313 static int destroy_compound_page(struct page *page, unsigned long order)
315 int i;
316 int nr_pages = 1 << order;
317 int bad = 0;
319 if (unlikely(compound_order(page) != order) ||
320 unlikely(!PageHead(page))) {
321 bad_page(page);
322 bad++;
325 __ClearPageHead(page);
327 for (i = 1; i < nr_pages; i++) {
328 struct page *p = page + i;
330 if (unlikely(!PageTail(p) || (p->first_page != page))) {
331 bad_page(page);
332 bad++;
334 __ClearPageTail(p);
337 return bad;
340 static inline void prep_zero_page(struct page *page, int order, gfp_t gfp_flags)
342 int i;
345 * clear_highpage() will use KM_USER0, so it's a bug to use __GFP_ZERO
346 * and __GFP_HIGHMEM from hard or soft interrupt context.
348 VM_BUG_ON((gfp_flags & __GFP_HIGHMEM) && in_interrupt());
349 for (i = 0; i < (1 << order); i++)
350 clear_highpage(page + i);
353 static inline void set_page_order(struct page *page, int order)
355 set_page_private(page, order);
356 __SetPageBuddy(page);
359 static inline void rmv_page_order(struct page *page)
361 __ClearPageBuddy(page);
362 set_page_private(page, 0);
366 * Locate the struct page for both the matching buddy in our
367 * pair (buddy1) and the combined O(n+1) page they form (page).
369 * 1) Any buddy B1 will have an order O twin B2 which satisfies
370 * the following equation:
371 * B2 = B1 ^ (1 << O)
372 * For example, if the starting buddy (buddy2) is #8 its order
373 * 1 buddy is #10:
374 * B2 = 8 ^ (1 << 1) = 8 ^ 2 = 10
376 * 2) Any buddy B will have an order O+1 parent P which
377 * satisfies the following equation:
378 * P = B & ~(1 << O)
380 * Assumption: *_mem_map is contiguous at least up to MAX_ORDER
382 static inline struct page *
383 __page_find_buddy(struct page *page, unsigned long page_idx, unsigned int order)
385 unsigned long buddy_idx = page_idx ^ (1 << order);
387 return page + (buddy_idx - page_idx);
390 static inline unsigned long
391 __find_combined_index(unsigned long page_idx, unsigned int order)
393 return (page_idx & ~(1 << order));
397 * This function checks whether a page is free && is the buddy
398 * we can do coalesce a page and its buddy if
399 * (a) the buddy is not in a hole &&
400 * (b) the buddy is in the buddy system &&
401 * (c) a page and its buddy have the same order &&
402 * (d) a page and its buddy are in the same zone.
404 * For recording whether a page is in the buddy system, we use PG_buddy.
405 * Setting, clearing, and testing PG_buddy is serialized by zone->lock.
407 * For recording page's order, we use page_private(page).
409 static inline int page_is_buddy(struct page *page, struct page *buddy,
410 int order)
412 if (!pfn_valid_within(page_to_pfn(buddy)))
413 return 0;
415 if (page_zone_id(page) != page_zone_id(buddy))
416 return 0;
418 if (PageBuddy(buddy) && page_order(buddy) == order) {
419 VM_BUG_ON(page_count(buddy) != 0);
420 return 1;
422 return 0;
426 * Freeing function for a buddy system allocator.
428 * The concept of a buddy system is to maintain direct-mapped table
429 * (containing bit values) for memory blocks of various "orders".
430 * The bottom level table contains the map for the smallest allocatable
431 * units of memory (here, pages), and each level above it describes
432 * pairs of units from the levels below, hence, "buddies".
433 * At a high level, all that happens here is marking the table entry
434 * at the bottom level available, and propagating the changes upward
435 * as necessary, plus some accounting needed to play nicely with other
436 * parts of the VM system.
437 * At each level, we keep a list of pages, which are heads of continuous
438 * free pages of length of (1 << order) and marked with PG_buddy. Page's
439 * order is recorded in page_private(page) field.
440 * So when we are allocating or freeing one, we can derive the state of the
441 * other. That is, if we allocate a small block, and both were
442 * free, the remainder of the region must be split into blocks.
443 * If a block is freed, and its buddy is also free, then this
444 * triggers coalescing into a block of larger size.
446 * -- wli
449 static inline void __free_one_page(struct page *page,
450 struct zone *zone, unsigned int order,
451 int migratetype)
453 unsigned long page_idx;
455 if (unlikely(PageCompound(page)))
456 if (unlikely(destroy_compound_page(page, order)))
457 return;
459 VM_BUG_ON(migratetype == -1);
461 page_idx = page_to_pfn(page) & ((1 << MAX_ORDER) - 1);
463 VM_BUG_ON(page_idx & ((1 << order) - 1));
464 VM_BUG_ON(bad_range(zone, page));
466 while (order < MAX_ORDER-1) {
467 unsigned long combined_idx;
468 struct page *buddy;
470 buddy = __page_find_buddy(page, page_idx, order);
471 if (!page_is_buddy(page, buddy, order))
472 break;
474 /* Our buddy is free, merge with it and move up one order. */
475 list_del(&buddy->lru);
476 zone->free_area[order].nr_free--;
477 rmv_page_order(buddy);
478 combined_idx = __find_combined_index(page_idx, order);
479 page = page + (combined_idx - page_idx);
480 page_idx = combined_idx;
481 order++;
483 set_page_order(page, order);
484 list_add(&page->lru,
485 &zone->free_area[order].free_list[migratetype]);
486 zone->free_area[order].nr_free++;
489 #ifdef CONFIG_HAVE_MLOCKED_PAGE_BIT
491 * free_page_mlock() -- clean up attempts to free and mlocked() page.
492 * Page should not be on lru, so no need to fix that up.
493 * free_pages_check() will verify...
495 static inline void free_page_mlock(struct page *page)
497 __dec_zone_page_state(page, NR_MLOCK);
498 __count_vm_event(UNEVICTABLE_MLOCKFREED);
500 #else
501 static void free_page_mlock(struct page *page) { }
502 #endif
504 static inline int free_pages_check(struct page *page)
506 if (unlikely(page_mapcount(page) |
507 (page->mapping != NULL) |
508 (atomic_read(&page->_count) != 0) |
509 (page->flags & PAGE_FLAGS_CHECK_AT_FREE))) {
510 bad_page(page);
511 return 1;
513 if (page->flags & PAGE_FLAGS_CHECK_AT_PREP)
514 page->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
515 return 0;
519 * Frees a list of pages.
520 * Assumes all pages on list are in same zone, and of same order.
521 * count is the number of pages to free.
523 * If the zone was previously in an "all pages pinned" state then look to
524 * see if this freeing clears that state.
526 * And clear the zone's pages_scanned counter, to hold off the "all pages are
527 * pinned" detection logic.
529 static void free_pages_bulk(struct zone *zone, int count,
530 struct list_head *list, int order)
532 spin_lock(&zone->lock);
533 zone_clear_flag(zone, ZONE_ALL_UNRECLAIMABLE);
534 zone->pages_scanned = 0;
536 __mod_zone_page_state(zone, NR_FREE_PAGES, count << order);
537 while (count--) {
538 struct page *page;
540 VM_BUG_ON(list_empty(list));
541 page = list_entry(list->prev, struct page, lru);
542 /* have to delete it as __free_one_page list manipulates */
543 list_del(&page->lru);
544 __free_one_page(page, zone, order, page_private(page));
546 spin_unlock(&zone->lock);
549 static void free_one_page(struct zone *zone, struct page *page, int order,
550 int migratetype)
552 spin_lock(&zone->lock);
553 zone_clear_flag(zone, ZONE_ALL_UNRECLAIMABLE);
554 zone->pages_scanned = 0;
556 __mod_zone_page_state(zone, NR_FREE_PAGES, 1 << order);
557 __free_one_page(page, zone, order, migratetype);
558 spin_unlock(&zone->lock);
561 static void __free_pages_ok(struct page *page, unsigned int order)
563 unsigned long flags;
564 int i;
565 int bad = 0;
566 int wasMlocked = TestClearPageMlocked(page);
568 kmemcheck_free_shadow(page, order);
570 for (i = 0 ; i < (1 << order) ; ++i)
571 bad += free_pages_check(page + i);
572 if (bad)
573 return;
575 if (!PageHighMem(page)) {
576 debug_check_no_locks_freed(page_address(page),PAGE_SIZE<<order);
577 debug_check_no_obj_freed(page_address(page),
578 PAGE_SIZE << order);
580 arch_free_page(page, order);
581 kernel_map_pages(page, 1 << order, 0);
583 local_irq_save(flags);
584 if (unlikely(wasMlocked))
585 free_page_mlock(page);
586 __count_vm_events(PGFREE, 1 << order);
587 free_one_page(page_zone(page), page, order,
588 get_pageblock_migratetype(page));
589 local_irq_restore(flags);
593 * permit the bootmem allocator to evade page validation on high-order frees
595 void __meminit __free_pages_bootmem(struct page *page, unsigned int order)
597 if (order == 0) {
598 __ClearPageReserved(page);
599 set_page_count(page, 0);
600 set_page_refcounted(page);
601 __free_page(page);
602 } else {
603 int loop;
605 prefetchw(page);
606 for (loop = 0; loop < BITS_PER_LONG; loop++) {
607 struct page *p = &page[loop];
609 if (loop + 1 < BITS_PER_LONG)
610 prefetchw(p + 1);
611 __ClearPageReserved(p);
612 set_page_count(p, 0);
615 set_page_refcounted(page);
616 __free_pages(page, order);
622 * The order of subdivision here is critical for the IO subsystem.
623 * Please do not alter this order without good reasons and regression
624 * testing. Specifically, as large blocks of memory are subdivided,
625 * the order in which smaller blocks are delivered depends on the order
626 * they're subdivided in this function. This is the primary factor
627 * influencing the order in which pages are delivered to the IO
628 * subsystem according to empirical testing, and this is also justified
629 * by considering the behavior of a buddy system containing a single
630 * large block of memory acted on by a series of small allocations.
631 * This behavior is a critical factor in sglist merging's success.
633 * -- wli
635 static inline void expand(struct zone *zone, struct page *page,
636 int low, int high, struct free_area *area,
637 int migratetype)
639 unsigned long size = 1 << high;
641 while (high > low) {
642 area--;
643 high--;
644 size >>= 1;
645 VM_BUG_ON(bad_range(zone, &page[size]));
646 list_add(&page[size].lru, &area->free_list[migratetype]);
647 area->nr_free++;
648 set_page_order(&page[size], high);
653 * This page is about to be returned from the page allocator
655 static inline int check_new_page(struct page *page)
657 if (unlikely(page_mapcount(page) |
658 (page->mapping != NULL) |
659 (atomic_read(&page->_count) != 0) |
660 (page->flags & PAGE_FLAGS_CHECK_AT_PREP))) {
661 bad_page(page);
662 return 1;
664 return 0;
667 static int prep_new_page(struct page *page, int order, gfp_t gfp_flags)
669 int i;
671 for (i = 0; i < (1 << order); i++) {
672 struct page *p = page + i;
673 if (unlikely(check_new_page(p)))
674 return 1;
677 set_page_private(page, 0);
678 set_page_refcounted(page);
680 arch_alloc_page(page, order);
681 kernel_map_pages(page, 1 << order, 1);
683 if (gfp_flags & __GFP_ZERO)
684 prep_zero_page(page, order, gfp_flags);
686 if (order && (gfp_flags & __GFP_COMP))
687 prep_compound_page(page, order);
689 return 0;
693 * Go through the free lists for the given migratetype and remove
694 * the smallest available page from the freelists
696 static inline
697 struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
698 int migratetype)
700 unsigned int current_order;
701 struct free_area * area;
702 struct page *page;
704 /* Find a page of the appropriate size in the preferred list */
705 for (current_order = order; current_order < MAX_ORDER; ++current_order) {
706 area = &(zone->free_area[current_order]);
707 if (list_empty(&area->free_list[migratetype]))
708 continue;
710 page = list_entry(area->free_list[migratetype].next,
711 struct page, lru);
712 list_del(&page->lru);
713 rmv_page_order(page);
714 area->nr_free--;
715 expand(zone, page, order, current_order, area, migratetype);
716 return page;
719 return NULL;
724 * This array describes the order lists are fallen back to when
725 * the free lists for the desirable migrate type are depleted
727 static int fallbacks[MIGRATE_TYPES][MIGRATE_TYPES-1] = {
728 [MIGRATE_UNMOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE, MIGRATE_RESERVE },
729 [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE, MIGRATE_MOVABLE, MIGRATE_RESERVE },
730 [MIGRATE_MOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_RESERVE },
731 [MIGRATE_RESERVE] = { MIGRATE_RESERVE, MIGRATE_RESERVE, MIGRATE_RESERVE }, /* Never used */
735 * Move the free pages in a range to the free lists of the requested type.
736 * Note that start_page and end_pages are not aligned on a pageblock
737 * boundary. If alignment is required, use move_freepages_block()
739 static int move_freepages(struct zone *zone,
740 struct page *start_page, struct page *end_page,
741 int migratetype)
743 struct page *page;
744 unsigned long order;
745 int pages_moved = 0;
747 #ifndef CONFIG_HOLES_IN_ZONE
749 * page_zone is not safe to call in this context when
750 * CONFIG_HOLES_IN_ZONE is set. This bug check is probably redundant
751 * anyway as we check zone boundaries in move_freepages_block().
752 * Remove at a later date when no bug reports exist related to
753 * grouping pages by mobility
755 BUG_ON(page_zone(start_page) != page_zone(end_page));
756 #endif
758 for (page = start_page; page <= end_page;) {
759 /* Make sure we are not inadvertently changing nodes */
760 VM_BUG_ON(page_to_nid(page) != zone_to_nid(zone));
762 if (!pfn_valid_within(page_to_pfn(page))) {
763 page++;
764 continue;
767 if (!PageBuddy(page)) {
768 page++;
769 continue;
772 order = page_order(page);
773 list_del(&page->lru);
774 list_add(&page->lru,
775 &zone->free_area[order].free_list[migratetype]);
776 page += 1 << order;
777 pages_moved += 1 << order;
780 return pages_moved;
783 static int move_freepages_block(struct zone *zone, struct page *page,
784 int migratetype)
786 unsigned long start_pfn, end_pfn;
787 struct page *start_page, *end_page;
789 start_pfn = page_to_pfn(page);
790 start_pfn = start_pfn & ~(pageblock_nr_pages-1);
791 start_page = pfn_to_page(start_pfn);
792 end_page = start_page + pageblock_nr_pages - 1;
793 end_pfn = start_pfn + pageblock_nr_pages - 1;
795 /* Do not cross zone boundaries */
796 if (start_pfn < zone->zone_start_pfn)
797 start_page = page;
798 if (end_pfn >= zone->zone_start_pfn + zone->spanned_pages)
799 return 0;
801 return move_freepages(zone, start_page, end_page, migratetype);
804 /* Remove an element from the buddy allocator from the fallback list */
805 static inline struct page *
806 __rmqueue_fallback(struct zone *zone, int order, int start_migratetype)
808 struct free_area * area;
809 int current_order;
810 struct page *page;
811 int migratetype, i;
813 /* Find the largest possible block of pages in the other list */
814 for (current_order = MAX_ORDER-1; current_order >= order;
815 --current_order) {
816 for (i = 0; i < MIGRATE_TYPES - 1; i++) {
817 migratetype = fallbacks[start_migratetype][i];
819 /* MIGRATE_RESERVE handled later if necessary */
820 if (migratetype == MIGRATE_RESERVE)
821 continue;
823 area = &(zone->free_area[current_order]);
824 if (list_empty(&area->free_list[migratetype]))
825 continue;
827 page = list_entry(area->free_list[migratetype].next,
828 struct page, lru);
829 area->nr_free--;
832 * If breaking a large block of pages, move all free
833 * pages to the preferred allocation list. If falling
834 * back for a reclaimable kernel allocation, be more
835 * agressive about taking ownership of free pages
837 if (unlikely(current_order >= (pageblock_order >> 1)) ||
838 start_migratetype == MIGRATE_RECLAIMABLE ||
839 page_group_by_mobility_disabled) {
840 unsigned long pages;
841 pages = move_freepages_block(zone, page,
842 start_migratetype);
844 /* Claim the whole block if over half of it is free */
845 if (pages >= (1 << (pageblock_order-1)) ||
846 page_group_by_mobility_disabled)
847 set_pageblock_migratetype(page,
848 start_migratetype);
850 migratetype = start_migratetype;
853 /* Remove the page from the freelists */
854 list_del(&page->lru);
855 rmv_page_order(page);
857 if (current_order == pageblock_order)
858 set_pageblock_migratetype(page,
859 start_migratetype);
861 expand(zone, page, order, current_order, area, migratetype);
862 return page;
866 return NULL;
870 * Do the hard work of removing an element from the buddy allocator.
871 * Call me with the zone->lock already held.
873 static struct page *__rmqueue(struct zone *zone, unsigned int order,
874 int migratetype)
876 struct page *page;
878 retry_reserve:
879 page = __rmqueue_smallest(zone, order, migratetype);
881 if (unlikely(!page) && migratetype != MIGRATE_RESERVE) {
882 page = __rmqueue_fallback(zone, order, migratetype);
885 * Use MIGRATE_RESERVE rather than fail an allocation. goto
886 * is used because __rmqueue_smallest is an inline function
887 * and we want just one call site
889 if (!page) {
890 migratetype = MIGRATE_RESERVE;
891 goto retry_reserve;
895 return page;
899 * Obtain a specified number of elements from the buddy allocator, all under
900 * a single hold of the lock, for efficiency. Add them to the supplied list.
901 * Returns the number of new pages which were placed at *list.
903 static int rmqueue_bulk(struct zone *zone, unsigned int order,
904 unsigned long count, struct list_head *list,
905 int migratetype, int cold)
907 int i;
909 spin_lock(&zone->lock);
910 for (i = 0; i < count; ++i) {
911 struct page *page = __rmqueue(zone, order, migratetype);
912 if (unlikely(page == NULL))
913 break;
916 * Split buddy pages returned by expand() are received here
917 * in physical page order. The page is added to the callers and
918 * list and the list head then moves forward. From the callers
919 * perspective, the linked list is ordered by page number in
920 * some conditions. This is useful for IO devices that can
921 * merge IO requests if the physical pages are ordered
922 * properly.
924 if (likely(cold == 0))
925 list_add(&page->lru, list);
926 else
927 list_add_tail(&page->lru, list);
928 set_page_private(page, migratetype);
929 list = &page->lru;
931 __mod_zone_page_state(zone, NR_FREE_PAGES, -(i << order));
932 spin_unlock(&zone->lock);
933 return i;
936 #ifdef CONFIG_NUMA
938 * Called from the vmstat counter updater to drain pagesets of this
939 * currently executing processor on remote nodes after they have
940 * expired.
942 * Note that this function must be called with the thread pinned to
943 * a single processor.
945 void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp)
947 unsigned long flags;
948 int to_drain;
950 local_irq_save(flags);
951 if (pcp->count >= pcp->batch)
952 to_drain = pcp->batch;
953 else
954 to_drain = pcp->count;
955 free_pages_bulk(zone, to_drain, &pcp->list, 0);
956 pcp->count -= to_drain;
957 local_irq_restore(flags);
959 #endif
962 * Drain pages of the indicated processor.
964 * The processor must either be the current processor and the
965 * thread pinned to the current processor or a processor that
966 * is not online.
968 static void drain_pages(unsigned int cpu)
970 unsigned long flags;
971 struct zone *zone;
973 for_each_populated_zone(zone) {
974 struct per_cpu_pageset *pset;
975 struct per_cpu_pages *pcp;
977 pset = zone_pcp(zone, cpu);
979 pcp = &pset->pcp;
980 local_irq_save(flags);
981 free_pages_bulk(zone, pcp->count, &pcp->list, 0);
982 pcp->count = 0;
983 local_irq_restore(flags);
988 * Spill all of this CPU's per-cpu pages back into the buddy allocator.
990 void drain_local_pages(void *arg)
992 drain_pages(smp_processor_id());
996 * Spill all the per-cpu pages from all CPUs back into the buddy allocator
998 void drain_all_pages(void)
1000 on_each_cpu(drain_local_pages, NULL, 1);
1003 #ifdef CONFIG_HIBERNATION
1005 void mark_free_pages(struct zone *zone)
1007 unsigned long pfn, max_zone_pfn;
1008 unsigned long flags;
1009 int order, t;
1010 struct list_head *curr;
1012 if (!zone->spanned_pages)
1013 return;
1015 spin_lock_irqsave(&zone->lock, flags);
1017 max_zone_pfn = zone->zone_start_pfn + zone->spanned_pages;
1018 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
1019 if (pfn_valid(pfn)) {
1020 struct page *page = pfn_to_page(pfn);
1022 if (!swsusp_page_is_forbidden(page))
1023 swsusp_unset_page_free(page);
1026 for_each_migratetype_order(order, t) {
1027 list_for_each(curr, &zone->free_area[order].free_list[t]) {
1028 unsigned long i;
1030 pfn = page_to_pfn(list_entry(curr, struct page, lru));
1031 for (i = 0; i < (1UL << order); i++)
1032 swsusp_set_page_free(pfn_to_page(pfn + i));
1035 spin_unlock_irqrestore(&zone->lock, flags);
1037 #endif /* CONFIG_PM */
1040 * Free a 0-order page
1042 static void free_hot_cold_page(struct page *page, int cold)
1044 struct zone *zone = page_zone(page);
1045 struct per_cpu_pages *pcp;
1046 unsigned long flags;
1047 int wasMlocked = TestClearPageMlocked(page);
1049 kmemcheck_free_shadow(page, 0);
1051 if (PageAnon(page))
1052 page->mapping = NULL;
1053 if (free_pages_check(page))
1054 return;
1056 if (!PageHighMem(page)) {
1057 debug_check_no_locks_freed(page_address(page), PAGE_SIZE);
1058 debug_check_no_obj_freed(page_address(page), PAGE_SIZE);
1060 arch_free_page(page, 0);
1061 kernel_map_pages(page, 1, 0);
1063 pcp = &zone_pcp(zone, get_cpu())->pcp;
1064 set_page_private(page, get_pageblock_migratetype(page));
1065 local_irq_save(flags);
1066 if (unlikely(wasMlocked))
1067 free_page_mlock(page);
1068 __count_vm_event(PGFREE);
1070 if (cold)
1071 list_add_tail(&page->lru, &pcp->list);
1072 else
1073 list_add(&page->lru, &pcp->list);
1074 pcp->count++;
1075 if (pcp->count >= pcp->high) {
1076 free_pages_bulk(zone, pcp->batch, &pcp->list, 0);
1077 pcp->count -= pcp->batch;
1079 local_irq_restore(flags);
1080 put_cpu();
1083 void free_hot_page(struct page *page)
1085 free_hot_cold_page(page, 0);
1088 void free_cold_page(struct page *page)
1090 free_hot_cold_page(page, 1);
1094 * split_page takes a non-compound higher-order page, and splits it into
1095 * n (1<<order) sub-pages: page[0..n]
1096 * Each sub-page must be freed individually.
1098 * Note: this is probably too low level an operation for use in drivers.
1099 * Please consult with lkml before using this in your driver.
1101 void split_page(struct page *page, unsigned int order)
1103 int i;
1105 VM_BUG_ON(PageCompound(page));
1106 VM_BUG_ON(!page_count(page));
1108 #ifdef CONFIG_KMEMCHECK
1110 * Split shadow pages too, because free(page[0]) would
1111 * otherwise free the whole shadow.
1113 if (kmemcheck_page_is_tracked(page))
1114 split_page(virt_to_page(page[0].shadow), order);
1115 #endif
1117 for (i = 1; i < (1 << order); i++)
1118 set_page_refcounted(page + i);
1122 * Really, prep_compound_page() should be called from __rmqueue_bulk(). But
1123 * we cheat by calling it from here, in the order > 0 path. Saves a branch
1124 * or two.
1126 static inline
1127 struct page *buffered_rmqueue(struct zone *preferred_zone,
1128 struct zone *zone, int order, gfp_t gfp_flags,
1129 int migratetype)
1131 unsigned long flags;
1132 struct page *page;
1133 int cold = !!(gfp_flags & __GFP_COLD);
1134 int cpu;
1136 again:
1137 cpu = get_cpu();
1138 if (likely(order == 0)) {
1139 struct per_cpu_pages *pcp;
1141 pcp = &zone_pcp(zone, cpu)->pcp;
1142 local_irq_save(flags);
1143 if (!pcp->count) {
1144 pcp->count = rmqueue_bulk(zone, 0,
1145 pcp->batch, &pcp->list,
1146 migratetype, cold);
1147 if (unlikely(!pcp->count))
1148 goto failed;
1151 /* Find a page of the appropriate migrate type */
1152 if (cold) {
1153 list_for_each_entry_reverse(page, &pcp->list, lru)
1154 if (page_private(page) == migratetype)
1155 break;
1156 } else {
1157 list_for_each_entry(page, &pcp->list, lru)
1158 if (page_private(page) == migratetype)
1159 break;
1162 /* Allocate more to the pcp list if necessary */
1163 if (unlikely(&page->lru == &pcp->list)) {
1164 pcp->count += rmqueue_bulk(zone, 0,
1165 pcp->batch, &pcp->list,
1166 migratetype, cold);
1167 page = list_entry(pcp->list.next, struct page, lru);
1170 list_del(&page->lru);
1171 pcp->count--;
1172 } else {
1173 if (unlikely(gfp_flags & __GFP_NOFAIL)) {
1175 * __GFP_NOFAIL is not to be used in new code.
1177 * All __GFP_NOFAIL callers should be fixed so that they
1178 * properly detect and handle allocation failures.
1180 * We most definitely don't want callers attempting to
1181 * allocate greater than order-1 page units with
1182 * __GFP_NOFAIL.
1184 WARN_ON_ONCE(order > 1);
1186 spin_lock_irqsave(&zone->lock, flags);
1187 page = __rmqueue(zone, order, migratetype);
1188 __mod_zone_page_state(zone, NR_FREE_PAGES, -(1 << order));
1189 spin_unlock(&zone->lock);
1190 if (!page)
1191 goto failed;
1194 __count_zone_vm_events(PGALLOC, zone, 1 << order);
1195 zone_statistics(preferred_zone, zone);
1196 local_irq_restore(flags);
1197 put_cpu();
1199 VM_BUG_ON(bad_range(zone, page));
1200 if (prep_new_page(page, order, gfp_flags))
1201 goto again;
1202 return page;
1204 failed:
1205 local_irq_restore(flags);
1206 put_cpu();
1207 return NULL;
1210 /* The ALLOC_WMARK bits are used as an index to zone->watermark */
1211 #define ALLOC_WMARK_MIN WMARK_MIN
1212 #define ALLOC_WMARK_LOW WMARK_LOW
1213 #define ALLOC_WMARK_HIGH WMARK_HIGH
1214 #define ALLOC_NO_WATERMARKS 0x04 /* don't check watermarks at all */
1216 /* Mask to get the watermark bits */
1217 #define ALLOC_WMARK_MASK (ALLOC_NO_WATERMARKS-1)
1219 #define ALLOC_HARDER 0x10 /* try to alloc harder */
1220 #define ALLOC_HIGH 0x20 /* __GFP_HIGH set */
1221 #define ALLOC_CPUSET 0x40 /* check for correct cpuset */
1223 #ifdef CONFIG_FAIL_PAGE_ALLOC
1225 static struct fail_page_alloc_attr {
1226 struct fault_attr attr;
1228 u32 ignore_gfp_highmem;
1229 u32 ignore_gfp_wait;
1230 u32 min_order;
1232 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
1234 struct dentry *ignore_gfp_highmem_file;
1235 struct dentry *ignore_gfp_wait_file;
1236 struct dentry *min_order_file;
1238 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
1240 } fail_page_alloc = {
1241 .attr = FAULT_ATTR_INITIALIZER,
1242 .ignore_gfp_wait = 1,
1243 .ignore_gfp_highmem = 1,
1244 .min_order = 1,
1247 static int __init setup_fail_page_alloc(char *str)
1249 return setup_fault_attr(&fail_page_alloc.attr, str);
1251 __setup("fail_page_alloc=", setup_fail_page_alloc);
1253 static int should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
1255 if (order < fail_page_alloc.min_order)
1256 return 0;
1257 if (gfp_mask & __GFP_NOFAIL)
1258 return 0;
1259 if (fail_page_alloc.ignore_gfp_highmem && (gfp_mask & __GFP_HIGHMEM))
1260 return 0;
1261 if (fail_page_alloc.ignore_gfp_wait && (gfp_mask & __GFP_WAIT))
1262 return 0;
1264 return should_fail(&fail_page_alloc.attr, 1 << order);
1267 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
1269 static int __init fail_page_alloc_debugfs(void)
1271 mode_t mode = S_IFREG | S_IRUSR | S_IWUSR;
1272 struct dentry *dir;
1273 int err;
1275 err = init_fault_attr_dentries(&fail_page_alloc.attr,
1276 "fail_page_alloc");
1277 if (err)
1278 return err;
1279 dir = fail_page_alloc.attr.dentries.dir;
1281 fail_page_alloc.ignore_gfp_wait_file =
1282 debugfs_create_bool("ignore-gfp-wait", mode, dir,
1283 &fail_page_alloc.ignore_gfp_wait);
1285 fail_page_alloc.ignore_gfp_highmem_file =
1286 debugfs_create_bool("ignore-gfp-highmem", mode, dir,
1287 &fail_page_alloc.ignore_gfp_highmem);
1288 fail_page_alloc.min_order_file =
1289 debugfs_create_u32("min-order", mode, dir,
1290 &fail_page_alloc.min_order);
1292 if (!fail_page_alloc.ignore_gfp_wait_file ||
1293 !fail_page_alloc.ignore_gfp_highmem_file ||
1294 !fail_page_alloc.min_order_file) {
1295 err = -ENOMEM;
1296 debugfs_remove(fail_page_alloc.ignore_gfp_wait_file);
1297 debugfs_remove(fail_page_alloc.ignore_gfp_highmem_file);
1298 debugfs_remove(fail_page_alloc.min_order_file);
1299 cleanup_fault_attr_dentries(&fail_page_alloc.attr);
1302 return err;
1305 late_initcall(fail_page_alloc_debugfs);
1307 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
1309 #else /* CONFIG_FAIL_PAGE_ALLOC */
1311 static inline int should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
1313 return 0;
1316 #endif /* CONFIG_FAIL_PAGE_ALLOC */
1319 * Return 1 if free pages are above 'mark'. This takes into account the order
1320 * of the allocation.
1322 int zone_watermark_ok(struct zone *z, int order, unsigned long mark,
1323 int classzone_idx, int alloc_flags)
1325 /* free_pages my go negative - that's OK */
1326 long min = mark;
1327 long free_pages = zone_page_state(z, NR_FREE_PAGES) - (1 << order) + 1;
1328 int o;
1330 if (alloc_flags & ALLOC_HIGH)
1331 min -= min / 2;
1332 if (alloc_flags & ALLOC_HARDER)
1333 min -= min / 4;
1335 if (free_pages <= min + z->lowmem_reserve[classzone_idx])
1336 return 0;
1337 for (o = 0; o < order; o++) {
1338 /* At the next order, this order's pages become unavailable */
1339 free_pages -= z->free_area[o].nr_free << o;
1341 /* Require fewer higher order pages to be free */
1342 min >>= 1;
1344 if (free_pages <= min)
1345 return 0;
1347 return 1;
1350 #ifdef CONFIG_NUMA
1352 * zlc_setup - Setup for "zonelist cache". Uses cached zone data to
1353 * skip over zones that are not allowed by the cpuset, or that have
1354 * been recently (in last second) found to be nearly full. See further
1355 * comments in mmzone.h. Reduces cache footprint of zonelist scans
1356 * that have to skip over a lot of full or unallowed zones.
1358 * If the zonelist cache is present in the passed in zonelist, then
1359 * returns a pointer to the allowed node mask (either the current
1360 * tasks mems_allowed, or node_states[N_HIGH_MEMORY].)
1362 * If the zonelist cache is not available for this zonelist, does
1363 * nothing and returns NULL.
1365 * If the fullzones BITMAP in the zonelist cache is stale (more than
1366 * a second since last zap'd) then we zap it out (clear its bits.)
1368 * We hold off even calling zlc_setup, until after we've checked the
1369 * first zone in the zonelist, on the theory that most allocations will
1370 * be satisfied from that first zone, so best to examine that zone as
1371 * quickly as we can.
1373 static nodemask_t *zlc_setup(struct zonelist *zonelist, int alloc_flags)
1375 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1376 nodemask_t *allowednodes; /* zonelist_cache approximation */
1378 zlc = zonelist->zlcache_ptr;
1379 if (!zlc)
1380 return NULL;
1382 if (time_after(jiffies, zlc->last_full_zap + HZ)) {
1383 bitmap_zero(zlc->fullzones, MAX_ZONES_PER_ZONELIST);
1384 zlc->last_full_zap = jiffies;
1387 allowednodes = !in_interrupt() && (alloc_flags & ALLOC_CPUSET) ?
1388 &cpuset_current_mems_allowed :
1389 &node_states[N_HIGH_MEMORY];
1390 return allowednodes;
1394 * Given 'z' scanning a zonelist, run a couple of quick checks to see
1395 * if it is worth looking at further for free memory:
1396 * 1) Check that the zone isn't thought to be full (doesn't have its
1397 * bit set in the zonelist_cache fullzones BITMAP).
1398 * 2) Check that the zones node (obtained from the zonelist_cache
1399 * z_to_n[] mapping) is allowed in the passed in allowednodes mask.
1400 * Return true (non-zero) if zone is worth looking at further, or
1401 * else return false (zero) if it is not.
1403 * This check -ignores- the distinction between various watermarks,
1404 * such as GFP_HIGH, GFP_ATOMIC, PF_MEMALLOC, ... If a zone is
1405 * found to be full for any variation of these watermarks, it will
1406 * be considered full for up to one second by all requests, unless
1407 * we are so low on memory on all allowed nodes that we are forced
1408 * into the second scan of the zonelist.
1410 * In the second scan we ignore this zonelist cache and exactly
1411 * apply the watermarks to all zones, even it is slower to do so.
1412 * We are low on memory in the second scan, and should leave no stone
1413 * unturned looking for a free page.
1415 static int zlc_zone_worth_trying(struct zonelist *zonelist, struct zoneref *z,
1416 nodemask_t *allowednodes)
1418 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1419 int i; /* index of *z in zonelist zones */
1420 int n; /* node that zone *z is on */
1422 zlc = zonelist->zlcache_ptr;
1423 if (!zlc)
1424 return 1;
1426 i = z - zonelist->_zonerefs;
1427 n = zlc->z_to_n[i];
1429 /* This zone is worth trying if it is allowed but not full */
1430 return node_isset(n, *allowednodes) && !test_bit(i, zlc->fullzones);
1434 * Given 'z' scanning a zonelist, set the corresponding bit in
1435 * zlc->fullzones, so that subsequent attempts to allocate a page
1436 * from that zone don't waste time re-examining it.
1438 static void zlc_mark_zone_full(struct zonelist *zonelist, struct zoneref *z)
1440 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1441 int i; /* index of *z in zonelist zones */
1443 zlc = zonelist->zlcache_ptr;
1444 if (!zlc)
1445 return;
1447 i = z - zonelist->_zonerefs;
1449 set_bit(i, zlc->fullzones);
1452 #else /* CONFIG_NUMA */
1454 static nodemask_t *zlc_setup(struct zonelist *zonelist, int alloc_flags)
1456 return NULL;
1459 static int zlc_zone_worth_trying(struct zonelist *zonelist, struct zoneref *z,
1460 nodemask_t *allowednodes)
1462 return 1;
1465 static void zlc_mark_zone_full(struct zonelist *zonelist, struct zoneref *z)
1468 #endif /* CONFIG_NUMA */
1471 * get_page_from_freelist goes through the zonelist trying to allocate
1472 * a page.
1474 static struct page *
1475 get_page_from_freelist(gfp_t gfp_mask, nodemask_t *nodemask, unsigned int order,
1476 struct zonelist *zonelist, int high_zoneidx, int alloc_flags,
1477 struct zone *preferred_zone, int migratetype)
1479 struct zoneref *z;
1480 struct page *page = NULL;
1481 int classzone_idx;
1482 struct zone *zone;
1483 nodemask_t *allowednodes = NULL;/* zonelist_cache approximation */
1484 int zlc_active = 0; /* set if using zonelist_cache */
1485 int did_zlc_setup = 0; /* just call zlc_setup() one time */
1487 classzone_idx = zone_idx(preferred_zone);
1488 zonelist_scan:
1490 * Scan zonelist, looking for a zone with enough free.
1491 * See also cpuset_zone_allowed() comment in kernel/cpuset.c.
1493 for_each_zone_zonelist_nodemask(zone, z, zonelist,
1494 high_zoneidx, nodemask) {
1495 if (NUMA_BUILD && zlc_active &&
1496 !zlc_zone_worth_trying(zonelist, z, allowednodes))
1497 continue;
1498 if ((alloc_flags & ALLOC_CPUSET) &&
1499 !cpuset_zone_allowed_softwall(zone, gfp_mask))
1500 goto try_next_zone;
1502 BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK);
1503 if (!(alloc_flags & ALLOC_NO_WATERMARKS)) {
1504 unsigned long mark;
1505 int ret;
1507 mark = zone->watermark[alloc_flags & ALLOC_WMARK_MASK];
1508 if (zone_watermark_ok(zone, order, mark,
1509 classzone_idx, alloc_flags))
1510 goto try_this_zone;
1512 if (zone_reclaim_mode == 0)
1513 goto this_zone_full;
1515 ret = zone_reclaim(zone, gfp_mask, order);
1516 switch (ret) {
1517 case ZONE_RECLAIM_NOSCAN:
1518 /* did not scan */
1519 goto try_next_zone;
1520 case ZONE_RECLAIM_FULL:
1521 /* scanned but unreclaimable */
1522 goto this_zone_full;
1523 default:
1524 /* did we reclaim enough */
1525 if (!zone_watermark_ok(zone, order, mark,
1526 classzone_idx, alloc_flags))
1527 goto this_zone_full;
1531 try_this_zone:
1532 page = buffered_rmqueue(preferred_zone, zone, order,
1533 gfp_mask, migratetype);
1534 if (page)
1535 break;
1536 this_zone_full:
1537 if (NUMA_BUILD)
1538 zlc_mark_zone_full(zonelist, z);
1539 try_next_zone:
1540 if (NUMA_BUILD && !did_zlc_setup && nr_online_nodes > 1) {
1542 * we do zlc_setup after the first zone is tried but only
1543 * if there are multiple nodes make it worthwhile
1545 allowednodes = zlc_setup(zonelist, alloc_flags);
1546 zlc_active = 1;
1547 did_zlc_setup = 1;
1551 if (unlikely(NUMA_BUILD && page == NULL && zlc_active)) {
1552 /* Disable zlc cache for second zonelist scan */
1553 zlc_active = 0;
1554 goto zonelist_scan;
1556 return page;
1559 static inline int
1560 should_alloc_retry(gfp_t gfp_mask, unsigned int order,
1561 unsigned long pages_reclaimed)
1563 /* Do not loop if specifically requested */
1564 if (gfp_mask & __GFP_NORETRY)
1565 return 0;
1568 * In this implementation, order <= PAGE_ALLOC_COSTLY_ORDER
1569 * means __GFP_NOFAIL, but that may not be true in other
1570 * implementations.
1572 if (order <= PAGE_ALLOC_COSTLY_ORDER)
1573 return 1;
1576 * For order > PAGE_ALLOC_COSTLY_ORDER, if __GFP_REPEAT is
1577 * specified, then we retry until we no longer reclaim any pages
1578 * (above), or we've reclaimed an order of pages at least as
1579 * large as the allocation's order. In both cases, if the
1580 * allocation still fails, we stop retrying.
1582 if (gfp_mask & __GFP_REPEAT && pages_reclaimed < (1 << order))
1583 return 1;
1586 * Don't let big-order allocations loop unless the caller
1587 * explicitly requests that.
1589 if (gfp_mask & __GFP_NOFAIL)
1590 return 1;
1592 return 0;
1595 static inline struct page *
1596 __alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order,
1597 struct zonelist *zonelist, enum zone_type high_zoneidx,
1598 nodemask_t *nodemask, struct zone *preferred_zone,
1599 int migratetype)
1601 struct page *page;
1603 /* Acquire the OOM killer lock for the zones in zonelist */
1604 if (!try_set_zone_oom(zonelist, gfp_mask)) {
1605 schedule_timeout_uninterruptible(1);
1606 return NULL;
1610 * Go through the zonelist yet one more time, keep very high watermark
1611 * here, this is only to catch a parallel oom killing, we must fail if
1612 * we're still under heavy pressure.
1614 page = get_page_from_freelist(gfp_mask|__GFP_HARDWALL, nodemask,
1615 order, zonelist, high_zoneidx,
1616 ALLOC_WMARK_HIGH|ALLOC_CPUSET,
1617 preferred_zone, migratetype);
1618 if (page)
1619 goto out;
1621 /* The OOM killer will not help higher order allocs */
1622 if (order > PAGE_ALLOC_COSTLY_ORDER && !(gfp_mask & __GFP_NOFAIL))
1623 goto out;
1625 /* Exhausted what can be done so it's blamo time */
1626 out_of_memory(zonelist, gfp_mask, order);
1628 out:
1629 clear_zonelist_oom(zonelist, gfp_mask);
1630 return page;
1633 /* The really slow allocator path where we enter direct reclaim */
1634 static inline struct page *
1635 __alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order,
1636 struct zonelist *zonelist, enum zone_type high_zoneidx,
1637 nodemask_t *nodemask, int alloc_flags, struct zone *preferred_zone,
1638 int migratetype, unsigned long *did_some_progress)
1640 struct page *page = NULL;
1641 struct reclaim_state reclaim_state;
1642 struct task_struct *p = current;
1644 cond_resched();
1646 /* We now go into synchronous reclaim */
1647 cpuset_memory_pressure_bump();
1650 * The task's cpuset might have expanded its set of allowable nodes
1652 p->flags |= PF_MEMALLOC;
1653 lockdep_set_current_reclaim_state(gfp_mask);
1654 reclaim_state.reclaimed_slab = 0;
1655 p->reclaim_state = &reclaim_state;
1657 *did_some_progress = try_to_free_pages(zonelist, order, gfp_mask, nodemask);
1659 p->reclaim_state = NULL;
1660 lockdep_clear_current_reclaim_state();
1661 p->flags &= ~PF_MEMALLOC;
1663 cond_resched();
1665 if (order != 0)
1666 drain_all_pages();
1668 if (likely(*did_some_progress))
1669 page = get_page_from_freelist(gfp_mask, nodemask, order,
1670 zonelist, high_zoneidx,
1671 alloc_flags, preferred_zone,
1672 migratetype);
1673 return page;
1677 * This is called in the allocator slow-path if the allocation request is of
1678 * sufficient urgency to ignore watermarks and take other desperate measures
1680 static inline struct page *
1681 __alloc_pages_high_priority(gfp_t gfp_mask, unsigned int order,
1682 struct zonelist *zonelist, enum zone_type high_zoneidx,
1683 nodemask_t *nodemask, struct zone *preferred_zone,
1684 int migratetype)
1686 struct page *page;
1688 do {
1689 page = get_page_from_freelist(gfp_mask, nodemask, order,
1690 zonelist, high_zoneidx, ALLOC_NO_WATERMARKS,
1691 preferred_zone, migratetype);
1693 if (!page && gfp_mask & __GFP_NOFAIL)
1694 congestion_wait(BLK_RW_ASYNC, HZ/50);
1695 } while (!page && (gfp_mask & __GFP_NOFAIL));
1697 return page;
1700 static inline
1701 void wake_all_kswapd(unsigned int order, struct zonelist *zonelist,
1702 enum zone_type high_zoneidx)
1704 struct zoneref *z;
1705 struct zone *zone;
1707 for_each_zone_zonelist(zone, z, zonelist, high_zoneidx)
1708 wakeup_kswapd(zone, order);
1711 static inline int
1712 gfp_to_alloc_flags(gfp_t gfp_mask)
1714 struct task_struct *p = current;
1715 int alloc_flags = ALLOC_WMARK_MIN | ALLOC_CPUSET;
1716 const gfp_t wait = gfp_mask & __GFP_WAIT;
1718 /* __GFP_HIGH is assumed to be the same as ALLOC_HIGH to save a branch. */
1719 BUILD_BUG_ON(__GFP_HIGH != ALLOC_HIGH);
1722 * The caller may dip into page reserves a bit more if the caller
1723 * cannot run direct reclaim, or if the caller has realtime scheduling
1724 * policy or is asking for __GFP_HIGH memory. GFP_ATOMIC requests will
1725 * set both ALLOC_HARDER (!wait) and ALLOC_HIGH (__GFP_HIGH).
1727 alloc_flags |= (gfp_mask & __GFP_HIGH);
1729 if (!wait) {
1730 alloc_flags |= ALLOC_HARDER;
1732 * Ignore cpuset if GFP_ATOMIC (!wait) rather than fail alloc.
1733 * See also cpuset_zone_allowed() comment in kernel/cpuset.c.
1735 alloc_flags &= ~ALLOC_CPUSET;
1736 } else if (unlikely(rt_task(p)))
1737 alloc_flags |= ALLOC_HARDER;
1739 if (likely(!(gfp_mask & __GFP_NOMEMALLOC))) {
1740 if (!in_interrupt() &&
1741 ((p->flags & PF_MEMALLOC) ||
1742 unlikely(test_thread_flag(TIF_MEMDIE))))
1743 alloc_flags |= ALLOC_NO_WATERMARKS;
1746 return alloc_flags;
1749 static inline struct page *
1750 __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order,
1751 struct zonelist *zonelist, enum zone_type high_zoneidx,
1752 nodemask_t *nodemask, struct zone *preferred_zone,
1753 int migratetype)
1755 const gfp_t wait = gfp_mask & __GFP_WAIT;
1756 struct page *page = NULL;
1757 int alloc_flags;
1758 unsigned long pages_reclaimed = 0;
1759 unsigned long did_some_progress;
1760 struct task_struct *p = current;
1763 * In the slowpath, we sanity check order to avoid ever trying to
1764 * reclaim >= MAX_ORDER areas which will never succeed. Callers may
1765 * be using allocators in order of preference for an area that is
1766 * too large.
1768 if (order >= MAX_ORDER) {
1769 WARN_ON_ONCE(!(gfp_mask & __GFP_NOWARN));
1770 return NULL;
1774 * GFP_THISNODE (meaning __GFP_THISNODE, __GFP_NORETRY and
1775 * __GFP_NOWARN set) should not cause reclaim since the subsystem
1776 * (f.e. slab) using GFP_THISNODE may choose to trigger reclaim
1777 * using a larger set of nodes after it has established that the
1778 * allowed per node queues are empty and that nodes are
1779 * over allocated.
1781 if (NUMA_BUILD && (gfp_mask & GFP_THISNODE) == GFP_THISNODE)
1782 goto nopage;
1784 wake_all_kswapd(order, zonelist, high_zoneidx);
1787 * OK, we're below the kswapd watermark and have kicked background
1788 * reclaim. Now things get more complex, so set up alloc_flags according
1789 * to how we want to proceed.
1791 alloc_flags = gfp_to_alloc_flags(gfp_mask);
1793 restart:
1794 /* This is the last chance, in general, before the goto nopage. */
1795 page = get_page_from_freelist(gfp_mask, nodemask, order, zonelist,
1796 high_zoneidx, alloc_flags & ~ALLOC_NO_WATERMARKS,
1797 preferred_zone, migratetype);
1798 if (page)
1799 goto got_pg;
1801 rebalance:
1802 /* Allocate without watermarks if the context allows */
1803 if (alloc_flags & ALLOC_NO_WATERMARKS) {
1804 page = __alloc_pages_high_priority(gfp_mask, order,
1805 zonelist, high_zoneidx, nodemask,
1806 preferred_zone, migratetype);
1807 if (page)
1808 goto got_pg;
1811 /* Atomic allocations - we can't balance anything */
1812 if (!wait)
1813 goto nopage;
1815 /* Avoid recursion of direct reclaim */
1816 if (p->flags & PF_MEMALLOC)
1817 goto nopage;
1819 /* Avoid allocations with no watermarks from looping endlessly */
1820 if (test_thread_flag(TIF_MEMDIE) && !(gfp_mask & __GFP_NOFAIL))
1821 goto nopage;
1823 /* Try direct reclaim and then allocating */
1824 page = __alloc_pages_direct_reclaim(gfp_mask, order,
1825 zonelist, high_zoneidx,
1826 nodemask,
1827 alloc_flags, preferred_zone,
1828 migratetype, &did_some_progress);
1829 if (page)
1830 goto got_pg;
1833 * If we failed to make any progress reclaiming, then we are
1834 * running out of options and have to consider going OOM
1836 if (!did_some_progress) {
1837 if ((gfp_mask & __GFP_FS) && !(gfp_mask & __GFP_NORETRY)) {
1838 if (oom_killer_disabled)
1839 goto nopage;
1840 page = __alloc_pages_may_oom(gfp_mask, order,
1841 zonelist, high_zoneidx,
1842 nodemask, preferred_zone,
1843 migratetype);
1844 if (page)
1845 goto got_pg;
1848 * The OOM killer does not trigger for high-order
1849 * ~__GFP_NOFAIL allocations so if no progress is being
1850 * made, there are no other options and retrying is
1851 * unlikely to help.
1853 if (order > PAGE_ALLOC_COSTLY_ORDER &&
1854 !(gfp_mask & __GFP_NOFAIL))
1855 goto nopage;
1857 goto restart;
1861 /* Check if we should retry the allocation */
1862 pages_reclaimed += did_some_progress;
1863 if (should_alloc_retry(gfp_mask, order, pages_reclaimed)) {
1864 /* Wait for some write requests to complete then retry */
1865 congestion_wait(BLK_RW_ASYNC, HZ/50);
1866 goto rebalance;
1869 nopage:
1870 if (!(gfp_mask & __GFP_NOWARN) && printk_ratelimit()) {
1871 printk(KERN_WARNING "%s: page allocation failure."
1872 " order:%d, mode:0x%x\n",
1873 p->comm, order, gfp_mask);
1874 dump_stack();
1875 show_mem();
1877 return page;
1878 got_pg:
1879 if (kmemcheck_enabled)
1880 kmemcheck_pagealloc_alloc(page, order, gfp_mask);
1881 return page;
1886 * This is the 'heart' of the zoned buddy allocator.
1888 struct page *
1889 __alloc_pages_nodemask(gfp_t gfp_mask, unsigned int order,
1890 struct zonelist *zonelist, nodemask_t *nodemask)
1892 enum zone_type high_zoneidx = gfp_zone(gfp_mask);
1893 struct zone *preferred_zone;
1894 struct page *page;
1895 int migratetype = allocflags_to_migratetype(gfp_mask);
1897 gfp_mask &= gfp_allowed_mask;
1899 lockdep_trace_alloc(gfp_mask);
1901 might_sleep_if(gfp_mask & __GFP_WAIT);
1903 if (should_fail_alloc_page(gfp_mask, order))
1904 return NULL;
1907 * Check the zones suitable for the gfp_mask contain at least one
1908 * valid zone. It's possible to have an empty zonelist as a result
1909 * of GFP_THISNODE and a memoryless node
1911 if (unlikely(!zonelist->_zonerefs->zone))
1912 return NULL;
1914 /* The preferred zone is used for statistics later */
1915 first_zones_zonelist(zonelist, high_zoneidx, nodemask, &preferred_zone);
1916 if (!preferred_zone)
1917 return NULL;
1919 /* First allocation attempt */
1920 page = get_page_from_freelist(gfp_mask|__GFP_HARDWALL, nodemask, order,
1921 zonelist, high_zoneidx, ALLOC_WMARK_LOW|ALLOC_CPUSET,
1922 preferred_zone, migratetype);
1923 if (unlikely(!page))
1924 page = __alloc_pages_slowpath(gfp_mask, order,
1925 zonelist, high_zoneidx, nodemask,
1926 preferred_zone, migratetype);
1928 return page;
1930 EXPORT_SYMBOL(__alloc_pages_nodemask);
1933 * Common helper functions.
1935 unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order)
1937 struct page * page;
1938 page = alloc_pages(gfp_mask, order);
1939 if (!page)
1940 return 0;
1941 return (unsigned long) page_address(page);
1944 EXPORT_SYMBOL(__get_free_pages);
1946 unsigned long get_zeroed_page(gfp_t gfp_mask)
1948 struct page * page;
1951 * get_zeroed_page() returns a 32-bit address, which cannot represent
1952 * a highmem page
1954 VM_BUG_ON((gfp_mask & __GFP_HIGHMEM) != 0);
1956 page = alloc_pages(gfp_mask | __GFP_ZERO, 0);
1957 if (page)
1958 return (unsigned long) page_address(page);
1959 return 0;
1962 EXPORT_SYMBOL(get_zeroed_page);
1964 void __pagevec_free(struct pagevec *pvec)
1966 int i = pagevec_count(pvec);
1968 while (--i >= 0)
1969 free_hot_cold_page(pvec->pages[i], pvec->cold);
1972 void __free_pages(struct page *page, unsigned int order)
1974 if (put_page_testzero(page)) {
1975 if (order == 0)
1976 free_hot_page(page);
1977 else
1978 __free_pages_ok(page, order);
1982 EXPORT_SYMBOL(__free_pages);
1984 void free_pages(unsigned long addr, unsigned int order)
1986 if (addr != 0) {
1987 VM_BUG_ON(!virt_addr_valid((void *)addr));
1988 __free_pages(virt_to_page((void *)addr), order);
1992 EXPORT_SYMBOL(free_pages);
1995 * alloc_pages_exact - allocate an exact number physically-contiguous pages.
1996 * @size: the number of bytes to allocate
1997 * @gfp_mask: GFP flags for the allocation
1999 * This function is similar to alloc_pages(), except that it allocates the
2000 * minimum number of pages to satisfy the request. alloc_pages() can only
2001 * allocate memory in power-of-two pages.
2003 * This function is also limited by MAX_ORDER.
2005 * Memory allocated by this function must be released by free_pages_exact().
2007 void *alloc_pages_exact(size_t size, gfp_t gfp_mask)
2009 unsigned int order = get_order(size);
2010 unsigned long addr;
2012 addr = __get_free_pages(gfp_mask, order);
2013 if (addr) {
2014 unsigned long alloc_end = addr + (PAGE_SIZE << order);
2015 unsigned long used = addr + PAGE_ALIGN(size);
2017 split_page(virt_to_page((void *)addr), order);
2018 while (used < alloc_end) {
2019 free_page(used);
2020 used += PAGE_SIZE;
2024 return (void *)addr;
2026 EXPORT_SYMBOL(alloc_pages_exact);
2029 * free_pages_exact - release memory allocated via alloc_pages_exact()
2030 * @virt: the value returned by alloc_pages_exact.
2031 * @size: size of allocation, same value as passed to alloc_pages_exact().
2033 * Release the memory allocated by a previous call to alloc_pages_exact.
2035 void free_pages_exact(void *virt, size_t size)
2037 unsigned long addr = (unsigned long)virt;
2038 unsigned long end = addr + PAGE_ALIGN(size);
2040 while (addr < end) {
2041 free_page(addr);
2042 addr += PAGE_SIZE;
2045 EXPORT_SYMBOL(free_pages_exact);
2047 static unsigned int nr_free_zone_pages(int offset)
2049 struct zoneref *z;
2050 struct zone *zone;
2052 /* Just pick one node, since fallback list is circular */
2053 unsigned int sum = 0;
2055 struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL);
2057 for_each_zone_zonelist(zone, z, zonelist, offset) {
2058 unsigned long size = zone->present_pages;
2059 unsigned long high = high_wmark_pages(zone);
2060 if (size > high)
2061 sum += size - high;
2064 return sum;
2068 * Amount of free RAM allocatable within ZONE_DMA and ZONE_NORMAL
2070 unsigned int nr_free_buffer_pages(void)
2072 return nr_free_zone_pages(gfp_zone(GFP_USER));
2074 EXPORT_SYMBOL_GPL(nr_free_buffer_pages);
2077 * Amount of free RAM allocatable within all zones
2079 unsigned int nr_free_pagecache_pages(void)
2081 return nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE));
2084 static inline void show_node(struct zone *zone)
2086 if (NUMA_BUILD)
2087 printk("Node %d ", zone_to_nid(zone));
2090 void si_meminfo(struct sysinfo *val)
2092 val->totalram = totalram_pages;
2093 val->sharedram = 0;
2094 val->freeram = global_page_state(NR_FREE_PAGES);
2095 val->bufferram = nr_blockdev_pages();
2096 val->totalhigh = totalhigh_pages;
2097 val->freehigh = nr_free_highpages();
2098 val->mem_unit = PAGE_SIZE;
2101 EXPORT_SYMBOL(si_meminfo);
2103 #ifdef CONFIG_NUMA
2104 void si_meminfo_node(struct sysinfo *val, int nid)
2106 pg_data_t *pgdat = NODE_DATA(nid);
2108 val->totalram = pgdat->node_present_pages;
2109 val->freeram = node_page_state(nid, NR_FREE_PAGES);
2110 #ifdef CONFIG_HIGHMEM
2111 val->totalhigh = pgdat->node_zones[ZONE_HIGHMEM].present_pages;
2112 val->freehigh = zone_page_state(&pgdat->node_zones[ZONE_HIGHMEM],
2113 NR_FREE_PAGES);
2114 #else
2115 val->totalhigh = 0;
2116 val->freehigh = 0;
2117 #endif
2118 val->mem_unit = PAGE_SIZE;
2120 #endif
2122 #define K(x) ((x) << (PAGE_SHIFT-10))
2125 * Show free area list (used inside shift_scroll-lock stuff)
2126 * We also calculate the percentage fragmentation. We do this by counting the
2127 * memory on each free list with the exception of the first item on the list.
2129 void show_free_areas(void)
2131 int cpu;
2132 struct zone *zone;
2134 for_each_populated_zone(zone) {
2135 show_node(zone);
2136 printk("%s per-cpu:\n", zone->name);
2138 for_each_online_cpu(cpu) {
2139 struct per_cpu_pageset *pageset;
2141 pageset = zone_pcp(zone, cpu);
2143 printk("CPU %4d: hi:%5d, btch:%4d usd:%4d\n",
2144 cpu, pageset->pcp.high,
2145 pageset->pcp.batch, pageset->pcp.count);
2149 printk("Active_anon:%lu active_file:%lu inactive_anon:%lu\n"
2150 " inactive_file:%lu"
2151 " unevictable:%lu"
2152 " dirty:%lu writeback:%lu unstable:%lu\n"
2153 " free:%lu slab:%lu mapped:%lu pagetables:%lu bounce:%lu\n",
2154 global_page_state(NR_ACTIVE_ANON),
2155 global_page_state(NR_ACTIVE_FILE),
2156 global_page_state(NR_INACTIVE_ANON),
2157 global_page_state(NR_INACTIVE_FILE),
2158 global_page_state(NR_UNEVICTABLE),
2159 global_page_state(NR_FILE_DIRTY),
2160 global_page_state(NR_WRITEBACK),
2161 global_page_state(NR_UNSTABLE_NFS),
2162 global_page_state(NR_FREE_PAGES),
2163 global_page_state(NR_SLAB_RECLAIMABLE) +
2164 global_page_state(NR_SLAB_UNRECLAIMABLE),
2165 global_page_state(NR_FILE_MAPPED),
2166 global_page_state(NR_PAGETABLE),
2167 global_page_state(NR_BOUNCE));
2169 for_each_populated_zone(zone) {
2170 int i;
2172 show_node(zone);
2173 printk("%s"
2174 " free:%lukB"
2175 " min:%lukB"
2176 " low:%lukB"
2177 " high:%lukB"
2178 " active_anon:%lukB"
2179 " inactive_anon:%lukB"
2180 " active_file:%lukB"
2181 " inactive_file:%lukB"
2182 " unevictable:%lukB"
2183 " present:%lukB"
2184 " pages_scanned:%lu"
2185 " all_unreclaimable? %s"
2186 "\n",
2187 zone->name,
2188 K(zone_page_state(zone, NR_FREE_PAGES)),
2189 K(min_wmark_pages(zone)),
2190 K(low_wmark_pages(zone)),
2191 K(high_wmark_pages(zone)),
2192 K(zone_page_state(zone, NR_ACTIVE_ANON)),
2193 K(zone_page_state(zone, NR_INACTIVE_ANON)),
2194 K(zone_page_state(zone, NR_ACTIVE_FILE)),
2195 K(zone_page_state(zone, NR_INACTIVE_FILE)),
2196 K(zone_page_state(zone, NR_UNEVICTABLE)),
2197 K(zone->present_pages),
2198 zone->pages_scanned,
2199 (zone_is_all_unreclaimable(zone) ? "yes" : "no")
2201 printk("lowmem_reserve[]:");
2202 for (i = 0; i < MAX_NR_ZONES; i++)
2203 printk(" %lu", zone->lowmem_reserve[i]);
2204 printk("\n");
2207 for_each_populated_zone(zone) {
2208 unsigned long nr[MAX_ORDER], flags, order, total = 0;
2210 show_node(zone);
2211 printk("%s: ", zone->name);
2213 spin_lock_irqsave(&zone->lock, flags);
2214 for (order = 0; order < MAX_ORDER; order++) {
2215 nr[order] = zone->free_area[order].nr_free;
2216 total += nr[order] << order;
2218 spin_unlock_irqrestore(&zone->lock, flags);
2219 for (order = 0; order < MAX_ORDER; order++)
2220 printk("%lu*%lukB ", nr[order], K(1UL) << order);
2221 printk("= %lukB\n", K(total));
2224 printk("%ld total pagecache pages\n", global_page_state(NR_FILE_PAGES));
2226 show_swap_cache_info();
2229 static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref)
2231 zoneref->zone = zone;
2232 zoneref->zone_idx = zone_idx(zone);
2236 * Builds allocation fallback zone lists.
2238 * Add all populated zones of a node to the zonelist.
2240 static int build_zonelists_node(pg_data_t *pgdat, struct zonelist *zonelist,
2241 int nr_zones, enum zone_type zone_type)
2243 struct zone *zone;
2245 BUG_ON(zone_type >= MAX_NR_ZONES);
2246 zone_type++;
2248 do {
2249 zone_type--;
2250 zone = pgdat->node_zones + zone_type;
2251 if (populated_zone(zone)) {
2252 zoneref_set_zone(zone,
2253 &zonelist->_zonerefs[nr_zones++]);
2254 check_highest_zone(zone_type);
2257 } while (zone_type);
2258 return nr_zones;
2263 * zonelist_order:
2264 * 0 = automatic detection of better ordering.
2265 * 1 = order by ([node] distance, -zonetype)
2266 * 2 = order by (-zonetype, [node] distance)
2268 * If not NUMA, ZONELIST_ORDER_ZONE and ZONELIST_ORDER_NODE will create
2269 * the same zonelist. So only NUMA can configure this param.
2271 #define ZONELIST_ORDER_DEFAULT 0
2272 #define ZONELIST_ORDER_NODE 1
2273 #define ZONELIST_ORDER_ZONE 2
2275 /* zonelist order in the kernel.
2276 * set_zonelist_order() will set this to NODE or ZONE.
2278 static int current_zonelist_order = ZONELIST_ORDER_DEFAULT;
2279 static char zonelist_order_name[3][8] = {"Default", "Node", "Zone"};
2282 #ifdef CONFIG_NUMA
2283 /* The value user specified ....changed by config */
2284 static int user_zonelist_order = ZONELIST_ORDER_DEFAULT;
2285 /* string for sysctl */
2286 #define NUMA_ZONELIST_ORDER_LEN 16
2287 char numa_zonelist_order[16] = "default";
2290 * interface for configure zonelist ordering.
2291 * command line option "numa_zonelist_order"
2292 * = "[dD]efault - default, automatic configuration.
2293 * = "[nN]ode - order by node locality, then by zone within node
2294 * = "[zZ]one - order by zone, then by locality within zone
2297 static int __parse_numa_zonelist_order(char *s)
2299 if (*s == 'd' || *s == 'D') {
2300 user_zonelist_order = ZONELIST_ORDER_DEFAULT;
2301 } else if (*s == 'n' || *s == 'N') {
2302 user_zonelist_order = ZONELIST_ORDER_NODE;
2303 } else if (*s == 'z' || *s == 'Z') {
2304 user_zonelist_order = ZONELIST_ORDER_ZONE;
2305 } else {
2306 printk(KERN_WARNING
2307 "Ignoring invalid numa_zonelist_order value: "
2308 "%s\n", s);
2309 return -EINVAL;
2311 return 0;
2314 static __init int setup_numa_zonelist_order(char *s)
2316 if (s)
2317 return __parse_numa_zonelist_order(s);
2318 return 0;
2320 early_param("numa_zonelist_order", setup_numa_zonelist_order);
2323 * sysctl handler for numa_zonelist_order
2325 int numa_zonelist_order_handler(ctl_table *table, int write,
2326 struct file *file, void __user *buffer, size_t *length,
2327 loff_t *ppos)
2329 char saved_string[NUMA_ZONELIST_ORDER_LEN];
2330 int ret;
2332 if (write)
2333 strncpy(saved_string, (char*)table->data,
2334 NUMA_ZONELIST_ORDER_LEN);
2335 ret = proc_dostring(table, write, file, buffer, length, ppos);
2336 if (ret)
2337 return ret;
2338 if (write) {
2339 int oldval = user_zonelist_order;
2340 if (__parse_numa_zonelist_order((char*)table->data)) {
2342 * bogus value. restore saved string
2344 strncpy((char*)table->data, saved_string,
2345 NUMA_ZONELIST_ORDER_LEN);
2346 user_zonelist_order = oldval;
2347 } else if (oldval != user_zonelist_order)
2348 build_all_zonelists();
2350 return 0;
2354 #define MAX_NODE_LOAD (nr_online_nodes)
2355 static int node_load[MAX_NUMNODES];
2358 * find_next_best_node - find the next node that should appear in a given node's fallback list
2359 * @node: node whose fallback list we're appending
2360 * @used_node_mask: nodemask_t of already used nodes
2362 * We use a number of factors to determine which is the next node that should
2363 * appear on a given node's fallback list. The node should not have appeared
2364 * already in @node's fallback list, and it should be the next closest node
2365 * according to the distance array (which contains arbitrary distance values
2366 * from each node to each node in the system), and should also prefer nodes
2367 * with no CPUs, since presumably they'll have very little allocation pressure
2368 * on them otherwise.
2369 * It returns -1 if no node is found.
2371 static int find_next_best_node(int node, nodemask_t *used_node_mask)
2373 int n, val;
2374 int min_val = INT_MAX;
2375 int best_node = -1;
2376 const struct cpumask *tmp = cpumask_of_node(0);
2378 /* Use the local node if we haven't already */
2379 if (!node_isset(node, *used_node_mask)) {
2380 node_set(node, *used_node_mask);
2381 return node;
2384 for_each_node_state(n, N_HIGH_MEMORY) {
2386 /* Don't want a node to appear more than once */
2387 if (node_isset(n, *used_node_mask))
2388 continue;
2390 /* Use the distance array to find the distance */
2391 val = node_distance(node, n);
2393 /* Penalize nodes under us ("prefer the next node") */
2394 val += (n < node);
2396 /* Give preference to headless and unused nodes */
2397 tmp = cpumask_of_node(n);
2398 if (!cpumask_empty(tmp))
2399 val += PENALTY_FOR_NODE_WITH_CPUS;
2401 /* Slight preference for less loaded node */
2402 val *= (MAX_NODE_LOAD*MAX_NUMNODES);
2403 val += node_load[n];
2405 if (val < min_val) {
2406 min_val = val;
2407 best_node = n;
2411 if (best_node >= 0)
2412 node_set(best_node, *used_node_mask);
2414 return best_node;
2419 * Build zonelists ordered by node and zones within node.
2420 * This results in maximum locality--normal zone overflows into local
2421 * DMA zone, if any--but risks exhausting DMA zone.
2423 static void build_zonelists_in_node_order(pg_data_t *pgdat, int node)
2425 int j;
2426 struct zonelist *zonelist;
2428 zonelist = &pgdat->node_zonelists[0];
2429 for (j = 0; zonelist->_zonerefs[j].zone != NULL; j++)
2431 j = build_zonelists_node(NODE_DATA(node), zonelist, j,
2432 MAX_NR_ZONES - 1);
2433 zonelist->_zonerefs[j].zone = NULL;
2434 zonelist->_zonerefs[j].zone_idx = 0;
2438 * Build gfp_thisnode zonelists
2440 static void build_thisnode_zonelists(pg_data_t *pgdat)
2442 int j;
2443 struct zonelist *zonelist;
2445 zonelist = &pgdat->node_zonelists[1];
2446 j = build_zonelists_node(pgdat, zonelist, 0, MAX_NR_ZONES - 1);
2447 zonelist->_zonerefs[j].zone = NULL;
2448 zonelist->_zonerefs[j].zone_idx = 0;
2452 * Build zonelists ordered by zone and nodes within zones.
2453 * This results in conserving DMA zone[s] until all Normal memory is
2454 * exhausted, but results in overflowing to remote node while memory
2455 * may still exist in local DMA zone.
2457 static int node_order[MAX_NUMNODES];
2459 static void build_zonelists_in_zone_order(pg_data_t *pgdat, int nr_nodes)
2461 int pos, j, node;
2462 int zone_type; /* needs to be signed */
2463 struct zone *z;
2464 struct zonelist *zonelist;
2466 zonelist = &pgdat->node_zonelists[0];
2467 pos = 0;
2468 for (zone_type = MAX_NR_ZONES - 1; zone_type >= 0; zone_type--) {
2469 for (j = 0; j < nr_nodes; j++) {
2470 node = node_order[j];
2471 z = &NODE_DATA(node)->node_zones[zone_type];
2472 if (populated_zone(z)) {
2473 zoneref_set_zone(z,
2474 &zonelist->_zonerefs[pos++]);
2475 check_highest_zone(zone_type);
2479 zonelist->_zonerefs[pos].zone = NULL;
2480 zonelist->_zonerefs[pos].zone_idx = 0;
2483 static int default_zonelist_order(void)
2485 int nid, zone_type;
2486 unsigned long low_kmem_size,total_size;
2487 struct zone *z;
2488 int average_size;
2490 * ZONE_DMA and ZONE_DMA32 can be very small area in the sytem.
2491 * If they are really small and used heavily, the system can fall
2492 * into OOM very easily.
2493 * This function detect ZONE_DMA/DMA32 size and confgigures zone order.
2495 /* Is there ZONE_NORMAL ? (ex. ppc has only DMA zone..) */
2496 low_kmem_size = 0;
2497 total_size = 0;
2498 for_each_online_node(nid) {
2499 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
2500 z = &NODE_DATA(nid)->node_zones[zone_type];
2501 if (populated_zone(z)) {
2502 if (zone_type < ZONE_NORMAL)
2503 low_kmem_size += z->present_pages;
2504 total_size += z->present_pages;
2508 if (!low_kmem_size || /* there are no DMA area. */
2509 low_kmem_size > total_size/2) /* DMA/DMA32 is big. */
2510 return ZONELIST_ORDER_NODE;
2512 * look into each node's config.
2513 * If there is a node whose DMA/DMA32 memory is very big area on
2514 * local memory, NODE_ORDER may be suitable.
2516 average_size = total_size /
2517 (nodes_weight(node_states[N_HIGH_MEMORY]) + 1);
2518 for_each_online_node(nid) {
2519 low_kmem_size = 0;
2520 total_size = 0;
2521 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
2522 z = &NODE_DATA(nid)->node_zones[zone_type];
2523 if (populated_zone(z)) {
2524 if (zone_type < ZONE_NORMAL)
2525 low_kmem_size += z->present_pages;
2526 total_size += z->present_pages;
2529 if (low_kmem_size &&
2530 total_size > average_size && /* ignore small node */
2531 low_kmem_size > total_size * 70/100)
2532 return ZONELIST_ORDER_NODE;
2534 return ZONELIST_ORDER_ZONE;
2537 static void set_zonelist_order(void)
2539 if (user_zonelist_order == ZONELIST_ORDER_DEFAULT)
2540 current_zonelist_order = default_zonelist_order();
2541 else
2542 current_zonelist_order = user_zonelist_order;
2545 static void build_zonelists(pg_data_t *pgdat)
2547 int j, node, load;
2548 enum zone_type i;
2549 nodemask_t used_mask;
2550 int local_node, prev_node;
2551 struct zonelist *zonelist;
2552 int order = current_zonelist_order;
2554 /* initialize zonelists */
2555 for (i = 0; i < MAX_ZONELISTS; i++) {
2556 zonelist = pgdat->node_zonelists + i;
2557 zonelist->_zonerefs[0].zone = NULL;
2558 zonelist->_zonerefs[0].zone_idx = 0;
2561 /* NUMA-aware ordering of nodes */
2562 local_node = pgdat->node_id;
2563 load = nr_online_nodes;
2564 prev_node = local_node;
2565 nodes_clear(used_mask);
2567 memset(node_order, 0, sizeof(node_order));
2568 j = 0;
2570 while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
2571 int distance = node_distance(local_node, node);
2574 * If another node is sufficiently far away then it is better
2575 * to reclaim pages in a zone before going off node.
2577 if (distance > RECLAIM_DISTANCE)
2578 zone_reclaim_mode = 1;
2581 * We don't want to pressure a particular node.
2582 * So adding penalty to the first node in same
2583 * distance group to make it round-robin.
2585 if (distance != node_distance(local_node, prev_node))
2586 node_load[node] = load;
2588 prev_node = node;
2589 load--;
2590 if (order == ZONELIST_ORDER_NODE)
2591 build_zonelists_in_node_order(pgdat, node);
2592 else
2593 node_order[j++] = node; /* remember order */
2596 if (order == ZONELIST_ORDER_ZONE) {
2597 /* calculate node order -- i.e., DMA last! */
2598 build_zonelists_in_zone_order(pgdat, j);
2601 build_thisnode_zonelists(pgdat);
2604 /* Construct the zonelist performance cache - see further mmzone.h */
2605 static void build_zonelist_cache(pg_data_t *pgdat)
2607 struct zonelist *zonelist;
2608 struct zonelist_cache *zlc;
2609 struct zoneref *z;
2611 zonelist = &pgdat->node_zonelists[0];
2612 zonelist->zlcache_ptr = zlc = &zonelist->zlcache;
2613 bitmap_zero(zlc->fullzones, MAX_ZONES_PER_ZONELIST);
2614 for (z = zonelist->_zonerefs; z->zone; z++)
2615 zlc->z_to_n[z - zonelist->_zonerefs] = zonelist_node_idx(z);
2619 #else /* CONFIG_NUMA */
2621 static void set_zonelist_order(void)
2623 current_zonelist_order = ZONELIST_ORDER_ZONE;
2626 static void build_zonelists(pg_data_t *pgdat)
2628 int node, local_node;
2629 enum zone_type j;
2630 struct zonelist *zonelist;
2632 local_node = pgdat->node_id;
2634 zonelist = &pgdat->node_zonelists[0];
2635 j = build_zonelists_node(pgdat, zonelist, 0, MAX_NR_ZONES - 1);
2638 * Now we build the zonelist so that it contains the zones
2639 * of all the other nodes.
2640 * We don't want to pressure a particular node, so when
2641 * building the zones for node N, we make sure that the
2642 * zones coming right after the local ones are those from
2643 * node N+1 (modulo N)
2645 for (node = local_node + 1; node < MAX_NUMNODES; node++) {
2646 if (!node_online(node))
2647 continue;
2648 j = build_zonelists_node(NODE_DATA(node), zonelist, j,
2649 MAX_NR_ZONES - 1);
2651 for (node = 0; node < local_node; node++) {
2652 if (!node_online(node))
2653 continue;
2654 j = build_zonelists_node(NODE_DATA(node), zonelist, j,
2655 MAX_NR_ZONES - 1);
2658 zonelist->_zonerefs[j].zone = NULL;
2659 zonelist->_zonerefs[j].zone_idx = 0;
2662 /* non-NUMA variant of zonelist performance cache - just NULL zlcache_ptr */
2663 static void build_zonelist_cache(pg_data_t *pgdat)
2665 pgdat->node_zonelists[0].zlcache_ptr = NULL;
2668 #endif /* CONFIG_NUMA */
2670 /* return values int ....just for stop_machine() */
2671 static int __build_all_zonelists(void *dummy)
2673 int nid;
2675 #ifdef CONFIG_NUMA
2676 memset(node_load, 0, sizeof(node_load));
2677 #endif
2678 for_each_online_node(nid) {
2679 pg_data_t *pgdat = NODE_DATA(nid);
2681 build_zonelists(pgdat);
2682 build_zonelist_cache(pgdat);
2684 return 0;
2687 void build_all_zonelists(void)
2689 set_zonelist_order();
2691 if (system_state == SYSTEM_BOOTING) {
2692 __build_all_zonelists(NULL);
2693 mminit_verify_zonelist();
2694 cpuset_init_current_mems_allowed();
2695 } else {
2696 /* we have to stop all cpus to guarantee there is no user
2697 of zonelist */
2698 stop_machine(__build_all_zonelists, NULL, NULL);
2699 /* cpuset refresh routine should be here */
2701 vm_total_pages = nr_free_pagecache_pages();
2703 * Disable grouping by mobility if the number of pages in the
2704 * system is too low to allow the mechanism to work. It would be
2705 * more accurate, but expensive to check per-zone. This check is
2706 * made on memory-hotadd so a system can start with mobility
2707 * disabled and enable it later
2709 if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES))
2710 page_group_by_mobility_disabled = 1;
2711 else
2712 page_group_by_mobility_disabled = 0;
2714 printk("Built %i zonelists in %s order, mobility grouping %s. "
2715 "Total pages: %ld\n",
2716 nr_online_nodes,
2717 zonelist_order_name[current_zonelist_order],
2718 page_group_by_mobility_disabled ? "off" : "on",
2719 vm_total_pages);
2720 #ifdef CONFIG_NUMA
2721 printk("Policy zone: %s\n", zone_names[policy_zone]);
2722 #endif
2726 * Helper functions to size the waitqueue hash table.
2727 * Essentially these want to choose hash table sizes sufficiently
2728 * large so that collisions trying to wait on pages are rare.
2729 * But in fact, the number of active page waitqueues on typical
2730 * systems is ridiculously low, less than 200. So this is even
2731 * conservative, even though it seems large.
2733 * The constant PAGES_PER_WAITQUEUE specifies the ratio of pages to
2734 * waitqueues, i.e. the size of the waitq table given the number of pages.
2736 #define PAGES_PER_WAITQUEUE 256
2738 #ifndef CONFIG_MEMORY_HOTPLUG
2739 static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
2741 unsigned long size = 1;
2743 pages /= PAGES_PER_WAITQUEUE;
2745 while (size < pages)
2746 size <<= 1;
2749 * Once we have dozens or even hundreds of threads sleeping
2750 * on IO we've got bigger problems than wait queue collision.
2751 * Limit the size of the wait table to a reasonable size.
2753 size = min(size, 4096UL);
2755 return max(size, 4UL);
2757 #else
2759 * A zone's size might be changed by hot-add, so it is not possible to determine
2760 * a suitable size for its wait_table. So we use the maximum size now.
2762 * The max wait table size = 4096 x sizeof(wait_queue_head_t). ie:
2764 * i386 (preemption config) : 4096 x 16 = 64Kbyte.
2765 * ia64, x86-64 (no preemption): 4096 x 20 = 80Kbyte.
2766 * ia64, x86-64 (preemption) : 4096 x 24 = 96Kbyte.
2768 * The maximum entries are prepared when a zone's memory is (512K + 256) pages
2769 * or more by the traditional way. (See above). It equals:
2771 * i386, x86-64, powerpc(4K page size) : = ( 2G + 1M)byte.
2772 * ia64(16K page size) : = ( 8G + 4M)byte.
2773 * powerpc (64K page size) : = (32G +16M)byte.
2775 static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
2777 return 4096UL;
2779 #endif
2782 * This is an integer logarithm so that shifts can be used later
2783 * to extract the more random high bits from the multiplicative
2784 * hash function before the remainder is taken.
2786 static inline unsigned long wait_table_bits(unsigned long size)
2788 return ffz(~size);
2791 #define LONG_ALIGN(x) (((x)+(sizeof(long))-1)&~((sizeof(long))-1))
2794 * Mark a number of pageblocks as MIGRATE_RESERVE. The number
2795 * of blocks reserved is based on min_wmark_pages(zone). The memory within
2796 * the reserve will tend to store contiguous free pages. Setting min_free_kbytes
2797 * higher will lead to a bigger reserve which will get freed as contiguous
2798 * blocks as reclaim kicks in
2800 static void setup_zone_migrate_reserve(struct zone *zone)
2802 unsigned long start_pfn, pfn, end_pfn;
2803 struct page *page;
2804 unsigned long reserve, block_migratetype;
2806 /* Get the start pfn, end pfn and the number of blocks to reserve */
2807 start_pfn = zone->zone_start_pfn;
2808 end_pfn = start_pfn + zone->spanned_pages;
2809 reserve = roundup(min_wmark_pages(zone), pageblock_nr_pages) >>
2810 pageblock_order;
2812 for (pfn = start_pfn; pfn < end_pfn; pfn += pageblock_nr_pages) {
2813 if (!pfn_valid(pfn))
2814 continue;
2815 page = pfn_to_page(pfn);
2817 /* Watch out for overlapping nodes */
2818 if (page_to_nid(page) != zone_to_nid(zone))
2819 continue;
2821 /* Blocks with reserved pages will never free, skip them. */
2822 if (PageReserved(page))
2823 continue;
2825 block_migratetype = get_pageblock_migratetype(page);
2827 /* If this block is reserved, account for it */
2828 if (reserve > 0 && block_migratetype == MIGRATE_RESERVE) {
2829 reserve--;
2830 continue;
2833 /* Suitable for reserving if this block is movable */
2834 if (reserve > 0 && block_migratetype == MIGRATE_MOVABLE) {
2835 set_pageblock_migratetype(page, MIGRATE_RESERVE);
2836 move_freepages_block(zone, page, MIGRATE_RESERVE);
2837 reserve--;
2838 continue;
2842 * If the reserve is met and this is a previous reserved block,
2843 * take it back
2845 if (block_migratetype == MIGRATE_RESERVE) {
2846 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
2847 move_freepages_block(zone, page, MIGRATE_MOVABLE);
2853 * Initially all pages are reserved - free ones are freed
2854 * up by free_all_bootmem() once the early boot process is
2855 * done. Non-atomic initialization, single-pass.
2857 void __meminit memmap_init_zone(unsigned long size, int nid, unsigned long zone,
2858 unsigned long start_pfn, enum memmap_context context)
2860 struct page *page;
2861 unsigned long end_pfn = start_pfn + size;
2862 unsigned long pfn;
2863 struct zone *z;
2865 if (highest_memmap_pfn < end_pfn - 1)
2866 highest_memmap_pfn = end_pfn - 1;
2868 z = &NODE_DATA(nid)->node_zones[zone];
2869 for (pfn = start_pfn; pfn < end_pfn; pfn++) {
2871 * There can be holes in boot-time mem_map[]s
2872 * handed to this function. They do not
2873 * exist on hotplugged memory.
2875 if (context == MEMMAP_EARLY) {
2876 if (!early_pfn_valid(pfn))
2877 continue;
2878 if (!early_pfn_in_nid(pfn, nid))
2879 continue;
2881 page = pfn_to_page(pfn);
2882 set_page_links(page, zone, nid, pfn);
2883 mminit_verify_page_links(page, zone, nid, pfn);
2884 init_page_count(page);
2885 reset_page_mapcount(page);
2886 SetPageReserved(page);
2888 * Mark the block movable so that blocks are reserved for
2889 * movable at startup. This will force kernel allocations
2890 * to reserve their blocks rather than leaking throughout
2891 * the address space during boot when many long-lived
2892 * kernel allocations are made. Later some blocks near
2893 * the start are marked MIGRATE_RESERVE by
2894 * setup_zone_migrate_reserve()
2896 * bitmap is created for zone's valid pfn range. but memmap
2897 * can be created for invalid pages (for alignment)
2898 * check here not to call set_pageblock_migratetype() against
2899 * pfn out of zone.
2901 if ((z->zone_start_pfn <= pfn)
2902 && (pfn < z->zone_start_pfn + z->spanned_pages)
2903 && !(pfn & (pageblock_nr_pages - 1)))
2904 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
2906 INIT_LIST_HEAD(&page->lru);
2907 #ifdef WANT_PAGE_VIRTUAL
2908 /* The shift won't overflow because ZONE_NORMAL is below 4G. */
2909 if (!is_highmem_idx(zone))
2910 set_page_address(page, __va(pfn << PAGE_SHIFT));
2911 #endif
2915 static void __meminit zone_init_free_lists(struct zone *zone)
2917 int order, t;
2918 for_each_migratetype_order(order, t) {
2919 INIT_LIST_HEAD(&zone->free_area[order].free_list[t]);
2920 zone->free_area[order].nr_free = 0;
2924 #ifndef __HAVE_ARCH_MEMMAP_INIT
2925 #define memmap_init(size, nid, zone, start_pfn) \
2926 memmap_init_zone((size), (nid), (zone), (start_pfn), MEMMAP_EARLY)
2927 #endif
2929 static int zone_batchsize(struct zone *zone)
2931 #ifdef CONFIG_MMU
2932 int batch;
2935 * The per-cpu-pages pools are set to around 1000th of the
2936 * size of the zone. But no more than 1/2 of a meg.
2938 * OK, so we don't know how big the cache is. So guess.
2940 batch = zone->present_pages / 1024;
2941 if (batch * PAGE_SIZE > 512 * 1024)
2942 batch = (512 * 1024) / PAGE_SIZE;
2943 batch /= 4; /* We effectively *= 4 below */
2944 if (batch < 1)
2945 batch = 1;
2948 * Clamp the batch to a 2^n - 1 value. Having a power
2949 * of 2 value was found to be more likely to have
2950 * suboptimal cache aliasing properties in some cases.
2952 * For example if 2 tasks are alternately allocating
2953 * batches of pages, one task can end up with a lot
2954 * of pages of one half of the possible page colors
2955 * and the other with pages of the other colors.
2957 batch = rounddown_pow_of_two(batch + batch/2) - 1;
2959 return batch;
2961 #else
2962 /* The deferral and batching of frees should be suppressed under NOMMU
2963 * conditions.
2965 * The problem is that NOMMU needs to be able to allocate large chunks
2966 * of contiguous memory as there's no hardware page translation to
2967 * assemble apparent contiguous memory from discontiguous pages.
2969 * Queueing large contiguous runs of pages for batching, however,
2970 * causes the pages to actually be freed in smaller chunks. As there
2971 * can be a significant delay between the individual batches being
2972 * recycled, this leads to the once large chunks of space being
2973 * fragmented and becoming unavailable for high-order allocations.
2975 return 0;
2976 #endif
2979 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch)
2981 struct per_cpu_pages *pcp;
2983 memset(p, 0, sizeof(*p));
2985 pcp = &p->pcp;
2986 pcp->count = 0;
2987 pcp->high = 6 * batch;
2988 pcp->batch = max(1UL, 1 * batch);
2989 INIT_LIST_HEAD(&pcp->list);
2993 * setup_pagelist_highmark() sets the high water mark for hot per_cpu_pagelist
2994 * to the value high for the pageset p.
2997 static void setup_pagelist_highmark(struct per_cpu_pageset *p,
2998 unsigned long high)
3000 struct per_cpu_pages *pcp;
3002 pcp = &p->pcp;
3003 pcp->high = high;
3004 pcp->batch = max(1UL, high/4);
3005 if ((high/4) > (PAGE_SHIFT * 8))
3006 pcp->batch = PAGE_SHIFT * 8;
3010 #ifdef CONFIG_NUMA
3012 * Boot pageset table. One per cpu which is going to be used for all
3013 * zones and all nodes. The parameters will be set in such a way
3014 * that an item put on a list will immediately be handed over to
3015 * the buddy list. This is safe since pageset manipulation is done
3016 * with interrupts disabled.
3018 * Some NUMA counter updates may also be caught by the boot pagesets.
3020 * The boot_pagesets must be kept even after bootup is complete for
3021 * unused processors and/or zones. They do play a role for bootstrapping
3022 * hotplugged processors.
3024 * zoneinfo_show() and maybe other functions do
3025 * not check if the processor is online before following the pageset pointer.
3026 * Other parts of the kernel may not check if the zone is available.
3028 static struct per_cpu_pageset boot_pageset[NR_CPUS];
3031 * Dynamically allocate memory for the
3032 * per cpu pageset array in struct zone.
3034 static int __cpuinit process_zones(int cpu)
3036 struct zone *zone, *dzone;
3037 int node = cpu_to_node(cpu);
3039 node_set_state(node, N_CPU); /* this node has a cpu */
3041 for_each_populated_zone(zone) {
3042 zone_pcp(zone, cpu) = kmalloc_node(sizeof(struct per_cpu_pageset),
3043 GFP_KERNEL, node);
3044 if (!zone_pcp(zone, cpu))
3045 goto bad;
3047 setup_pageset(zone_pcp(zone, cpu), zone_batchsize(zone));
3049 if (percpu_pagelist_fraction)
3050 setup_pagelist_highmark(zone_pcp(zone, cpu),
3051 (zone->present_pages / percpu_pagelist_fraction));
3054 return 0;
3055 bad:
3056 for_each_zone(dzone) {
3057 if (!populated_zone(dzone))
3058 continue;
3059 if (dzone == zone)
3060 break;
3061 kfree(zone_pcp(dzone, cpu));
3062 zone_pcp(dzone, cpu) = &boot_pageset[cpu];
3064 return -ENOMEM;
3067 static inline void free_zone_pagesets(int cpu)
3069 struct zone *zone;
3071 for_each_zone(zone) {
3072 struct per_cpu_pageset *pset = zone_pcp(zone, cpu);
3074 /* Free per_cpu_pageset if it is slab allocated */
3075 if (pset != &boot_pageset[cpu])
3076 kfree(pset);
3077 zone_pcp(zone, cpu) = &boot_pageset[cpu];
3081 static int __cpuinit pageset_cpuup_callback(struct notifier_block *nfb,
3082 unsigned long action,
3083 void *hcpu)
3085 int cpu = (long)hcpu;
3086 int ret = NOTIFY_OK;
3088 switch (action) {
3089 case CPU_UP_PREPARE:
3090 case CPU_UP_PREPARE_FROZEN:
3091 if (process_zones(cpu))
3092 ret = NOTIFY_BAD;
3093 break;
3094 case CPU_UP_CANCELED:
3095 case CPU_UP_CANCELED_FROZEN:
3096 case CPU_DEAD:
3097 case CPU_DEAD_FROZEN:
3098 free_zone_pagesets(cpu);
3099 break;
3100 default:
3101 break;
3103 return ret;
3106 static struct notifier_block __cpuinitdata pageset_notifier =
3107 { &pageset_cpuup_callback, NULL, 0 };
3109 void __init setup_per_cpu_pageset(void)
3111 int err;
3113 /* Initialize per_cpu_pageset for cpu 0.
3114 * A cpuup callback will do this for every cpu
3115 * as it comes online
3117 err = process_zones(smp_processor_id());
3118 BUG_ON(err);
3119 register_cpu_notifier(&pageset_notifier);
3122 #endif
3124 static noinline __init_refok
3125 int zone_wait_table_init(struct zone *zone, unsigned long zone_size_pages)
3127 int i;
3128 struct pglist_data *pgdat = zone->zone_pgdat;
3129 size_t alloc_size;
3132 * The per-page waitqueue mechanism uses hashed waitqueues
3133 * per zone.
3135 zone->wait_table_hash_nr_entries =
3136 wait_table_hash_nr_entries(zone_size_pages);
3137 zone->wait_table_bits =
3138 wait_table_bits(zone->wait_table_hash_nr_entries);
3139 alloc_size = zone->wait_table_hash_nr_entries
3140 * sizeof(wait_queue_head_t);
3142 if (!slab_is_available()) {
3143 zone->wait_table = (wait_queue_head_t *)
3144 alloc_bootmem_node(pgdat, alloc_size);
3145 } else {
3147 * This case means that a zone whose size was 0 gets new memory
3148 * via memory hot-add.
3149 * But it may be the case that a new node was hot-added. In
3150 * this case vmalloc() will not be able to use this new node's
3151 * memory - this wait_table must be initialized to use this new
3152 * node itself as well.
3153 * To use this new node's memory, further consideration will be
3154 * necessary.
3156 zone->wait_table = vmalloc(alloc_size);
3158 if (!zone->wait_table)
3159 return -ENOMEM;
3161 for(i = 0; i < zone->wait_table_hash_nr_entries; ++i)
3162 init_waitqueue_head(zone->wait_table + i);
3164 return 0;
3167 static __meminit void zone_pcp_init(struct zone *zone)
3169 int cpu;
3170 unsigned long batch = zone_batchsize(zone);
3172 for (cpu = 0; cpu < NR_CPUS; cpu++) {
3173 #ifdef CONFIG_NUMA
3174 /* Early boot. Slab allocator not functional yet */
3175 zone_pcp(zone, cpu) = &boot_pageset[cpu];
3176 setup_pageset(&boot_pageset[cpu],0);
3177 #else
3178 setup_pageset(zone_pcp(zone,cpu), batch);
3179 #endif
3181 if (zone->present_pages)
3182 printk(KERN_DEBUG " %s zone: %lu pages, LIFO batch:%lu\n",
3183 zone->name, zone->present_pages, batch);
3186 __meminit int init_currently_empty_zone(struct zone *zone,
3187 unsigned long zone_start_pfn,
3188 unsigned long size,
3189 enum memmap_context context)
3191 struct pglist_data *pgdat = zone->zone_pgdat;
3192 int ret;
3193 ret = zone_wait_table_init(zone, size);
3194 if (ret)
3195 return ret;
3196 pgdat->nr_zones = zone_idx(zone) + 1;
3198 zone->zone_start_pfn = zone_start_pfn;
3200 mminit_dprintk(MMINIT_TRACE, "memmap_init",
3201 "Initialising map node %d zone %lu pfns %lu -> %lu\n",
3202 pgdat->node_id,
3203 (unsigned long)zone_idx(zone),
3204 zone_start_pfn, (zone_start_pfn + size));
3206 zone_init_free_lists(zone);
3208 return 0;
3211 #ifdef CONFIG_ARCH_POPULATES_NODE_MAP
3213 * Basic iterator support. Return the first range of PFNs for a node
3214 * Note: nid == MAX_NUMNODES returns first region regardless of node
3216 static int __meminit first_active_region_index_in_nid(int nid)
3218 int i;
3220 for (i = 0; i < nr_nodemap_entries; i++)
3221 if (nid == MAX_NUMNODES || early_node_map[i].nid == nid)
3222 return i;
3224 return -1;
3228 * Basic iterator support. Return the next active range of PFNs for a node
3229 * Note: nid == MAX_NUMNODES returns next region regardless of node
3231 static int __meminit next_active_region_index_in_nid(int index, int nid)
3233 for (index = index + 1; index < nr_nodemap_entries; index++)
3234 if (nid == MAX_NUMNODES || early_node_map[index].nid == nid)
3235 return index;
3237 return -1;
3240 #ifndef CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID
3242 * Required by SPARSEMEM. Given a PFN, return what node the PFN is on.
3243 * Architectures may implement their own version but if add_active_range()
3244 * was used and there are no special requirements, this is a convenient
3245 * alternative
3247 int __meminit __early_pfn_to_nid(unsigned long pfn)
3249 int i;
3251 for (i = 0; i < nr_nodemap_entries; i++) {
3252 unsigned long start_pfn = early_node_map[i].start_pfn;
3253 unsigned long end_pfn = early_node_map[i].end_pfn;
3255 if (start_pfn <= pfn && pfn < end_pfn)
3256 return early_node_map[i].nid;
3258 /* This is a memory hole */
3259 return -1;
3261 #endif /* CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID */
3263 int __meminit early_pfn_to_nid(unsigned long pfn)
3265 int nid;
3267 nid = __early_pfn_to_nid(pfn);
3268 if (nid >= 0)
3269 return nid;
3270 /* just returns 0 */
3271 return 0;
3274 #ifdef CONFIG_NODES_SPAN_OTHER_NODES
3275 bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
3277 int nid;
3279 nid = __early_pfn_to_nid(pfn);
3280 if (nid >= 0 && nid != node)
3281 return false;
3282 return true;
3284 #endif
3286 /* Basic iterator support to walk early_node_map[] */
3287 #define for_each_active_range_index_in_nid(i, nid) \
3288 for (i = first_active_region_index_in_nid(nid); i != -1; \
3289 i = next_active_region_index_in_nid(i, nid))
3292 * free_bootmem_with_active_regions - Call free_bootmem_node for each active range
3293 * @nid: The node to free memory on. If MAX_NUMNODES, all nodes are freed.
3294 * @max_low_pfn: The highest PFN that will be passed to free_bootmem_node
3296 * If an architecture guarantees that all ranges registered with
3297 * add_active_ranges() contain no holes and may be freed, this
3298 * this function may be used instead of calling free_bootmem() manually.
3300 void __init free_bootmem_with_active_regions(int nid,
3301 unsigned long max_low_pfn)
3303 int i;
3305 for_each_active_range_index_in_nid(i, nid) {
3306 unsigned long size_pages = 0;
3307 unsigned long end_pfn = early_node_map[i].end_pfn;
3309 if (early_node_map[i].start_pfn >= max_low_pfn)
3310 continue;
3312 if (end_pfn > max_low_pfn)
3313 end_pfn = max_low_pfn;
3315 size_pages = end_pfn - early_node_map[i].start_pfn;
3316 free_bootmem_node(NODE_DATA(early_node_map[i].nid),
3317 PFN_PHYS(early_node_map[i].start_pfn),
3318 size_pages << PAGE_SHIFT);
3322 void __init work_with_active_regions(int nid, work_fn_t work_fn, void *data)
3324 int i;
3325 int ret;
3327 for_each_active_range_index_in_nid(i, nid) {
3328 ret = work_fn(early_node_map[i].start_pfn,
3329 early_node_map[i].end_pfn, data);
3330 if (ret)
3331 break;
3335 * sparse_memory_present_with_active_regions - Call memory_present for each active range
3336 * @nid: The node to call memory_present for. If MAX_NUMNODES, all nodes will be used.
3338 * If an architecture guarantees that all ranges registered with
3339 * add_active_ranges() contain no holes and may be freed, this
3340 * function may be used instead of calling memory_present() manually.
3342 void __init sparse_memory_present_with_active_regions(int nid)
3344 int i;
3346 for_each_active_range_index_in_nid(i, nid)
3347 memory_present(early_node_map[i].nid,
3348 early_node_map[i].start_pfn,
3349 early_node_map[i].end_pfn);
3353 * get_pfn_range_for_nid - Return the start and end page frames for a node
3354 * @nid: The nid to return the range for. If MAX_NUMNODES, the min and max PFN are returned.
3355 * @start_pfn: Passed by reference. On return, it will have the node start_pfn.
3356 * @end_pfn: Passed by reference. On return, it will have the node end_pfn.
3358 * It returns the start and end page frame of a node based on information
3359 * provided by an arch calling add_active_range(). If called for a node
3360 * with no available memory, a warning is printed and the start and end
3361 * PFNs will be 0.
3363 void __meminit get_pfn_range_for_nid(unsigned int nid,
3364 unsigned long *start_pfn, unsigned long *end_pfn)
3366 int i;
3367 *start_pfn = -1UL;
3368 *end_pfn = 0;
3370 for_each_active_range_index_in_nid(i, nid) {
3371 *start_pfn = min(*start_pfn, early_node_map[i].start_pfn);
3372 *end_pfn = max(*end_pfn, early_node_map[i].end_pfn);
3375 if (*start_pfn == -1UL)
3376 *start_pfn = 0;
3380 * This finds a zone that can be used for ZONE_MOVABLE pages. The
3381 * assumption is made that zones within a node are ordered in monotonic
3382 * increasing memory addresses so that the "highest" populated zone is used
3384 static void __init find_usable_zone_for_movable(void)
3386 int zone_index;
3387 for (zone_index = MAX_NR_ZONES - 1; zone_index >= 0; zone_index--) {
3388 if (zone_index == ZONE_MOVABLE)
3389 continue;
3391 if (arch_zone_highest_possible_pfn[zone_index] >
3392 arch_zone_lowest_possible_pfn[zone_index])
3393 break;
3396 VM_BUG_ON(zone_index == -1);
3397 movable_zone = zone_index;
3401 * The zone ranges provided by the architecture do not include ZONE_MOVABLE
3402 * because it is sized independant of architecture. Unlike the other zones,
3403 * the starting point for ZONE_MOVABLE is not fixed. It may be different
3404 * in each node depending on the size of each node and how evenly kernelcore
3405 * is distributed. This helper function adjusts the zone ranges
3406 * provided by the architecture for a given node by using the end of the
3407 * highest usable zone for ZONE_MOVABLE. This preserves the assumption that
3408 * zones within a node are in order of monotonic increases memory addresses
3410 static void __meminit adjust_zone_range_for_zone_movable(int nid,
3411 unsigned long zone_type,
3412 unsigned long node_start_pfn,
3413 unsigned long node_end_pfn,
3414 unsigned long *zone_start_pfn,
3415 unsigned long *zone_end_pfn)
3417 /* Only adjust if ZONE_MOVABLE is on this node */
3418 if (zone_movable_pfn[nid]) {
3419 /* Size ZONE_MOVABLE */
3420 if (zone_type == ZONE_MOVABLE) {
3421 *zone_start_pfn = zone_movable_pfn[nid];
3422 *zone_end_pfn = min(node_end_pfn,
3423 arch_zone_highest_possible_pfn[movable_zone]);
3425 /* Adjust for ZONE_MOVABLE starting within this range */
3426 } else if (*zone_start_pfn < zone_movable_pfn[nid] &&
3427 *zone_end_pfn > zone_movable_pfn[nid]) {
3428 *zone_end_pfn = zone_movable_pfn[nid];
3430 /* Check if this whole range is within ZONE_MOVABLE */
3431 } else if (*zone_start_pfn >= zone_movable_pfn[nid])
3432 *zone_start_pfn = *zone_end_pfn;
3437 * Return the number of pages a zone spans in a node, including holes
3438 * present_pages = zone_spanned_pages_in_node() - zone_absent_pages_in_node()
3440 static unsigned long __meminit zone_spanned_pages_in_node(int nid,
3441 unsigned long zone_type,
3442 unsigned long *ignored)
3444 unsigned long node_start_pfn, node_end_pfn;
3445 unsigned long zone_start_pfn, zone_end_pfn;
3447 /* Get the start and end of the node and zone */
3448 get_pfn_range_for_nid(nid, &node_start_pfn, &node_end_pfn);
3449 zone_start_pfn = arch_zone_lowest_possible_pfn[zone_type];
3450 zone_end_pfn = arch_zone_highest_possible_pfn[zone_type];
3451 adjust_zone_range_for_zone_movable(nid, zone_type,
3452 node_start_pfn, node_end_pfn,
3453 &zone_start_pfn, &zone_end_pfn);
3455 /* Check that this node has pages within the zone's required range */
3456 if (zone_end_pfn < node_start_pfn || zone_start_pfn > node_end_pfn)
3457 return 0;
3459 /* Move the zone boundaries inside the node if necessary */
3460 zone_end_pfn = min(zone_end_pfn, node_end_pfn);
3461 zone_start_pfn = max(zone_start_pfn, node_start_pfn);
3463 /* Return the spanned pages */
3464 return zone_end_pfn - zone_start_pfn;
3468 * Return the number of holes in a range on a node. If nid is MAX_NUMNODES,
3469 * then all holes in the requested range will be accounted for.
3471 static unsigned long __meminit __absent_pages_in_range(int nid,
3472 unsigned long range_start_pfn,
3473 unsigned long range_end_pfn)
3475 int i = 0;
3476 unsigned long prev_end_pfn = 0, hole_pages = 0;
3477 unsigned long start_pfn;
3479 /* Find the end_pfn of the first active range of pfns in the node */
3480 i = first_active_region_index_in_nid(nid);
3481 if (i == -1)
3482 return 0;
3484 prev_end_pfn = min(early_node_map[i].start_pfn, range_end_pfn);
3486 /* Account for ranges before physical memory on this node */
3487 if (early_node_map[i].start_pfn > range_start_pfn)
3488 hole_pages = prev_end_pfn - range_start_pfn;
3490 /* Find all holes for the zone within the node */
3491 for (; i != -1; i = next_active_region_index_in_nid(i, nid)) {
3493 /* No need to continue if prev_end_pfn is outside the zone */
3494 if (prev_end_pfn >= range_end_pfn)
3495 break;
3497 /* Make sure the end of the zone is not within the hole */
3498 start_pfn = min(early_node_map[i].start_pfn, range_end_pfn);
3499 prev_end_pfn = max(prev_end_pfn, range_start_pfn);
3501 /* Update the hole size cound and move on */
3502 if (start_pfn > range_start_pfn) {
3503 BUG_ON(prev_end_pfn > start_pfn);
3504 hole_pages += start_pfn - prev_end_pfn;
3506 prev_end_pfn = early_node_map[i].end_pfn;
3509 /* Account for ranges past physical memory on this node */
3510 if (range_end_pfn > prev_end_pfn)
3511 hole_pages += range_end_pfn -
3512 max(range_start_pfn, prev_end_pfn);
3514 return hole_pages;
3518 * absent_pages_in_range - Return number of page frames in holes within a range
3519 * @start_pfn: The start PFN to start searching for holes
3520 * @end_pfn: The end PFN to stop searching for holes
3522 * It returns the number of pages frames in memory holes within a range.
3524 unsigned long __init absent_pages_in_range(unsigned long start_pfn,
3525 unsigned long end_pfn)
3527 return __absent_pages_in_range(MAX_NUMNODES, start_pfn, end_pfn);
3530 /* Return the number of page frames in holes in a zone on a node */
3531 static unsigned long __meminit zone_absent_pages_in_node(int nid,
3532 unsigned long zone_type,
3533 unsigned long *ignored)
3535 unsigned long node_start_pfn, node_end_pfn;
3536 unsigned long zone_start_pfn, zone_end_pfn;
3538 get_pfn_range_for_nid(nid, &node_start_pfn, &node_end_pfn);
3539 zone_start_pfn = max(arch_zone_lowest_possible_pfn[zone_type],
3540 node_start_pfn);
3541 zone_end_pfn = min(arch_zone_highest_possible_pfn[zone_type],
3542 node_end_pfn);
3544 adjust_zone_range_for_zone_movable(nid, zone_type,
3545 node_start_pfn, node_end_pfn,
3546 &zone_start_pfn, &zone_end_pfn);
3547 return __absent_pages_in_range(nid, zone_start_pfn, zone_end_pfn);
3550 #else
3551 static inline unsigned long __meminit zone_spanned_pages_in_node(int nid,
3552 unsigned long zone_type,
3553 unsigned long *zones_size)
3555 return zones_size[zone_type];
3558 static inline unsigned long __meminit zone_absent_pages_in_node(int nid,
3559 unsigned long zone_type,
3560 unsigned long *zholes_size)
3562 if (!zholes_size)
3563 return 0;
3565 return zholes_size[zone_type];
3568 #endif
3570 static void __meminit calculate_node_totalpages(struct pglist_data *pgdat,
3571 unsigned long *zones_size, unsigned long *zholes_size)
3573 unsigned long realtotalpages, totalpages = 0;
3574 enum zone_type i;
3576 for (i = 0; i < MAX_NR_ZONES; i++)
3577 totalpages += zone_spanned_pages_in_node(pgdat->node_id, i,
3578 zones_size);
3579 pgdat->node_spanned_pages = totalpages;
3581 realtotalpages = totalpages;
3582 for (i = 0; i < MAX_NR_ZONES; i++)
3583 realtotalpages -=
3584 zone_absent_pages_in_node(pgdat->node_id, i,
3585 zholes_size);
3586 pgdat->node_present_pages = realtotalpages;
3587 printk(KERN_DEBUG "On node %d totalpages: %lu\n", pgdat->node_id,
3588 realtotalpages);
3591 #ifndef CONFIG_SPARSEMEM
3593 * Calculate the size of the zone->blockflags rounded to an unsigned long
3594 * Start by making sure zonesize is a multiple of pageblock_order by rounding
3595 * up. Then use 1 NR_PAGEBLOCK_BITS worth of bits per pageblock, finally
3596 * round what is now in bits to nearest long in bits, then return it in
3597 * bytes.
3599 static unsigned long __init usemap_size(unsigned long zonesize)
3601 unsigned long usemapsize;
3603 usemapsize = roundup(zonesize, pageblock_nr_pages);
3604 usemapsize = usemapsize >> pageblock_order;
3605 usemapsize *= NR_PAGEBLOCK_BITS;
3606 usemapsize = roundup(usemapsize, 8 * sizeof(unsigned long));
3608 return usemapsize / 8;
3611 static void __init setup_usemap(struct pglist_data *pgdat,
3612 struct zone *zone, unsigned long zonesize)
3614 unsigned long usemapsize = usemap_size(zonesize);
3615 zone->pageblock_flags = NULL;
3616 if (usemapsize)
3617 zone->pageblock_flags = alloc_bootmem_node(pgdat, usemapsize);
3619 #else
3620 static void inline setup_usemap(struct pglist_data *pgdat,
3621 struct zone *zone, unsigned long zonesize) {}
3622 #endif /* CONFIG_SPARSEMEM */
3624 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
3626 /* Return a sensible default order for the pageblock size. */
3627 static inline int pageblock_default_order(void)
3629 if (HPAGE_SHIFT > PAGE_SHIFT)
3630 return HUGETLB_PAGE_ORDER;
3632 return MAX_ORDER-1;
3635 /* Initialise the number of pages represented by NR_PAGEBLOCK_BITS */
3636 static inline void __init set_pageblock_order(unsigned int order)
3638 /* Check that pageblock_nr_pages has not already been setup */
3639 if (pageblock_order)
3640 return;
3643 * Assume the largest contiguous order of interest is a huge page.
3644 * This value may be variable depending on boot parameters on IA64
3646 pageblock_order = order;
3648 #else /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
3651 * When CONFIG_HUGETLB_PAGE_SIZE_VARIABLE is not set, set_pageblock_order()
3652 * and pageblock_default_order() are unused as pageblock_order is set
3653 * at compile-time. See include/linux/pageblock-flags.h for the values of
3654 * pageblock_order based on the kernel config
3656 static inline int pageblock_default_order(unsigned int order)
3658 return MAX_ORDER-1;
3660 #define set_pageblock_order(x) do {} while (0)
3662 #endif /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
3665 * Set up the zone data structures:
3666 * - mark all pages reserved
3667 * - mark all memory queues empty
3668 * - clear the memory bitmaps
3670 static void __paginginit free_area_init_core(struct pglist_data *pgdat,
3671 unsigned long *zones_size, unsigned long *zholes_size)
3673 enum zone_type j;
3674 int nid = pgdat->node_id;
3675 unsigned long zone_start_pfn = pgdat->node_start_pfn;
3676 int ret;
3678 pgdat_resize_init(pgdat);
3679 pgdat->nr_zones = 0;
3680 init_waitqueue_head(&pgdat->kswapd_wait);
3681 pgdat->kswapd_max_order = 0;
3682 pgdat_page_cgroup_init(pgdat);
3684 for (j = 0; j < MAX_NR_ZONES; j++) {
3685 struct zone *zone = pgdat->node_zones + j;
3686 unsigned long size, realsize, memmap_pages;
3687 enum lru_list l;
3689 size = zone_spanned_pages_in_node(nid, j, zones_size);
3690 realsize = size - zone_absent_pages_in_node(nid, j,
3691 zholes_size);
3694 * Adjust realsize so that it accounts for how much memory
3695 * is used by this zone for memmap. This affects the watermark
3696 * and per-cpu initialisations
3698 memmap_pages =
3699 PAGE_ALIGN(size * sizeof(struct page)) >> PAGE_SHIFT;
3700 if (realsize >= memmap_pages) {
3701 realsize -= memmap_pages;
3702 if (memmap_pages)
3703 printk(KERN_DEBUG
3704 " %s zone: %lu pages used for memmap\n",
3705 zone_names[j], memmap_pages);
3706 } else
3707 printk(KERN_WARNING
3708 " %s zone: %lu pages exceeds realsize %lu\n",
3709 zone_names[j], memmap_pages, realsize);
3711 /* Account for reserved pages */
3712 if (j == 0 && realsize > dma_reserve) {
3713 realsize -= dma_reserve;
3714 printk(KERN_DEBUG " %s zone: %lu pages reserved\n",
3715 zone_names[0], dma_reserve);
3718 if (!is_highmem_idx(j))
3719 nr_kernel_pages += realsize;
3720 nr_all_pages += realsize;
3722 zone->spanned_pages = size;
3723 zone->present_pages = realsize;
3724 #ifdef CONFIG_NUMA
3725 zone->node = nid;
3726 zone->min_unmapped_pages = (realsize*sysctl_min_unmapped_ratio)
3727 / 100;
3728 zone->min_slab_pages = (realsize * sysctl_min_slab_ratio) / 100;
3729 #endif
3730 zone->name = zone_names[j];
3731 spin_lock_init(&zone->lock);
3732 spin_lock_init(&zone->lru_lock);
3733 zone_seqlock_init(zone);
3734 zone->zone_pgdat = pgdat;
3736 zone->prev_priority = DEF_PRIORITY;
3738 zone_pcp_init(zone);
3739 for_each_lru(l) {
3740 INIT_LIST_HEAD(&zone->lru[l].list);
3741 zone->lru[l].nr_saved_scan = 0;
3743 zone->reclaim_stat.recent_rotated[0] = 0;
3744 zone->reclaim_stat.recent_rotated[1] = 0;
3745 zone->reclaim_stat.recent_scanned[0] = 0;
3746 zone->reclaim_stat.recent_scanned[1] = 0;
3747 zap_zone_vm_stats(zone);
3748 zone->flags = 0;
3749 if (!size)
3750 continue;
3752 set_pageblock_order(pageblock_default_order());
3753 setup_usemap(pgdat, zone, size);
3754 ret = init_currently_empty_zone(zone, zone_start_pfn,
3755 size, MEMMAP_EARLY);
3756 BUG_ON(ret);
3757 memmap_init(size, nid, j, zone_start_pfn);
3758 zone_start_pfn += size;
3762 static void __init_refok alloc_node_mem_map(struct pglist_data *pgdat)
3764 /* Skip empty nodes */
3765 if (!pgdat->node_spanned_pages)
3766 return;
3768 #ifdef CONFIG_FLAT_NODE_MEM_MAP
3769 /* ia64 gets its own node_mem_map, before this, without bootmem */
3770 if (!pgdat->node_mem_map) {
3771 unsigned long size, start, end;
3772 struct page *map;
3775 * The zone's endpoints aren't required to be MAX_ORDER
3776 * aligned but the node_mem_map endpoints must be in order
3777 * for the buddy allocator to function correctly.
3779 start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1);
3780 end = pgdat->node_start_pfn + pgdat->node_spanned_pages;
3781 end = ALIGN(end, MAX_ORDER_NR_PAGES);
3782 size = (end - start) * sizeof(struct page);
3783 map = alloc_remap(pgdat->node_id, size);
3784 if (!map)
3785 map = alloc_bootmem_node(pgdat, size);
3786 pgdat->node_mem_map = map + (pgdat->node_start_pfn - start);
3788 #ifndef CONFIG_NEED_MULTIPLE_NODES
3790 * With no DISCONTIG, the global mem_map is just set as node 0's
3792 if (pgdat == NODE_DATA(0)) {
3793 mem_map = NODE_DATA(0)->node_mem_map;
3794 #ifdef CONFIG_ARCH_POPULATES_NODE_MAP
3795 if (page_to_pfn(mem_map) != pgdat->node_start_pfn)
3796 mem_map -= (pgdat->node_start_pfn - ARCH_PFN_OFFSET);
3797 #endif /* CONFIG_ARCH_POPULATES_NODE_MAP */
3799 #endif
3800 #endif /* CONFIG_FLAT_NODE_MEM_MAP */
3803 void __paginginit free_area_init_node(int nid, unsigned long *zones_size,
3804 unsigned long node_start_pfn, unsigned long *zholes_size)
3806 pg_data_t *pgdat = NODE_DATA(nid);
3808 pgdat->node_id = nid;
3809 pgdat->node_start_pfn = node_start_pfn;
3810 calculate_node_totalpages(pgdat, zones_size, zholes_size);
3812 alloc_node_mem_map(pgdat);
3813 #ifdef CONFIG_FLAT_NODE_MEM_MAP
3814 printk(KERN_DEBUG "free_area_init_node: node %d, pgdat %08lx, node_mem_map %08lx\n",
3815 nid, (unsigned long)pgdat,
3816 (unsigned long)pgdat->node_mem_map);
3817 #endif
3819 free_area_init_core(pgdat, zones_size, zholes_size);
3822 #ifdef CONFIG_ARCH_POPULATES_NODE_MAP
3824 #if MAX_NUMNODES > 1
3826 * Figure out the number of possible node ids.
3828 static void __init setup_nr_node_ids(void)
3830 unsigned int node;
3831 unsigned int highest = 0;
3833 for_each_node_mask(node, node_possible_map)
3834 highest = node;
3835 nr_node_ids = highest + 1;
3837 #else
3838 static inline void setup_nr_node_ids(void)
3841 #endif
3844 * add_active_range - Register a range of PFNs backed by physical memory
3845 * @nid: The node ID the range resides on
3846 * @start_pfn: The start PFN of the available physical memory
3847 * @end_pfn: The end PFN of the available physical memory
3849 * These ranges are stored in an early_node_map[] and later used by
3850 * free_area_init_nodes() to calculate zone sizes and holes. If the
3851 * range spans a memory hole, it is up to the architecture to ensure
3852 * the memory is not freed by the bootmem allocator. If possible
3853 * the range being registered will be merged with existing ranges.
3855 void __init add_active_range(unsigned int nid, unsigned long start_pfn,
3856 unsigned long end_pfn)
3858 int i;
3860 mminit_dprintk(MMINIT_TRACE, "memory_register",
3861 "Entering add_active_range(%d, %#lx, %#lx) "
3862 "%d entries of %d used\n",
3863 nid, start_pfn, end_pfn,
3864 nr_nodemap_entries, MAX_ACTIVE_REGIONS);
3866 mminit_validate_memmodel_limits(&start_pfn, &end_pfn);
3868 /* Merge with existing active regions if possible */
3869 for (i = 0; i < nr_nodemap_entries; i++) {
3870 if (early_node_map[i].nid != nid)
3871 continue;
3873 /* Skip if an existing region covers this new one */
3874 if (start_pfn >= early_node_map[i].start_pfn &&
3875 end_pfn <= early_node_map[i].end_pfn)
3876 return;
3878 /* Merge forward if suitable */
3879 if (start_pfn <= early_node_map[i].end_pfn &&
3880 end_pfn > early_node_map[i].end_pfn) {
3881 early_node_map[i].end_pfn = end_pfn;
3882 return;
3885 /* Merge backward if suitable */
3886 if (start_pfn < early_node_map[i].end_pfn &&
3887 end_pfn >= early_node_map[i].start_pfn) {
3888 early_node_map[i].start_pfn = start_pfn;
3889 return;
3893 /* Check that early_node_map is large enough */
3894 if (i >= MAX_ACTIVE_REGIONS) {
3895 printk(KERN_CRIT "More than %d memory regions, truncating\n",
3896 MAX_ACTIVE_REGIONS);
3897 return;
3900 early_node_map[i].nid = nid;
3901 early_node_map[i].start_pfn = start_pfn;
3902 early_node_map[i].end_pfn = end_pfn;
3903 nr_nodemap_entries = i + 1;
3907 * remove_active_range - Shrink an existing registered range of PFNs
3908 * @nid: The node id the range is on that should be shrunk
3909 * @start_pfn: The new PFN of the range
3910 * @end_pfn: The new PFN of the range
3912 * i386 with NUMA use alloc_remap() to store a node_mem_map on a local node.
3913 * The map is kept near the end physical page range that has already been
3914 * registered. This function allows an arch to shrink an existing registered
3915 * range.
3917 void __init remove_active_range(unsigned int nid, unsigned long start_pfn,
3918 unsigned long end_pfn)
3920 int i, j;
3921 int removed = 0;
3923 printk(KERN_DEBUG "remove_active_range (%d, %lu, %lu)\n",
3924 nid, start_pfn, end_pfn);
3926 /* Find the old active region end and shrink */
3927 for_each_active_range_index_in_nid(i, nid) {
3928 if (early_node_map[i].start_pfn >= start_pfn &&
3929 early_node_map[i].end_pfn <= end_pfn) {
3930 /* clear it */
3931 early_node_map[i].start_pfn = 0;
3932 early_node_map[i].end_pfn = 0;
3933 removed = 1;
3934 continue;
3936 if (early_node_map[i].start_pfn < start_pfn &&
3937 early_node_map[i].end_pfn > start_pfn) {
3938 unsigned long temp_end_pfn = early_node_map[i].end_pfn;
3939 early_node_map[i].end_pfn = start_pfn;
3940 if (temp_end_pfn > end_pfn)
3941 add_active_range(nid, end_pfn, temp_end_pfn);
3942 continue;
3944 if (early_node_map[i].start_pfn >= start_pfn &&
3945 early_node_map[i].end_pfn > end_pfn &&
3946 early_node_map[i].start_pfn < end_pfn) {
3947 early_node_map[i].start_pfn = end_pfn;
3948 continue;
3952 if (!removed)
3953 return;
3955 /* remove the blank ones */
3956 for (i = nr_nodemap_entries - 1; i > 0; i--) {
3957 if (early_node_map[i].nid != nid)
3958 continue;
3959 if (early_node_map[i].end_pfn)
3960 continue;
3961 /* we found it, get rid of it */
3962 for (j = i; j < nr_nodemap_entries - 1; j++)
3963 memcpy(&early_node_map[j], &early_node_map[j+1],
3964 sizeof(early_node_map[j]));
3965 j = nr_nodemap_entries - 1;
3966 memset(&early_node_map[j], 0, sizeof(early_node_map[j]));
3967 nr_nodemap_entries--;
3972 * remove_all_active_ranges - Remove all currently registered regions
3974 * During discovery, it may be found that a table like SRAT is invalid
3975 * and an alternative discovery method must be used. This function removes
3976 * all currently registered regions.
3978 void __init remove_all_active_ranges(void)
3980 memset(early_node_map, 0, sizeof(early_node_map));
3981 nr_nodemap_entries = 0;
3984 /* Compare two active node_active_regions */
3985 static int __init cmp_node_active_region(const void *a, const void *b)
3987 struct node_active_region *arange = (struct node_active_region *)a;
3988 struct node_active_region *brange = (struct node_active_region *)b;
3990 /* Done this way to avoid overflows */
3991 if (arange->start_pfn > brange->start_pfn)
3992 return 1;
3993 if (arange->start_pfn < brange->start_pfn)
3994 return -1;
3996 return 0;
3999 /* sort the node_map by start_pfn */
4000 static void __init sort_node_map(void)
4002 sort(early_node_map, (size_t)nr_nodemap_entries,
4003 sizeof(struct node_active_region),
4004 cmp_node_active_region, NULL);
4007 /* Find the lowest pfn for a node */
4008 static unsigned long __init find_min_pfn_for_node(int nid)
4010 int i;
4011 unsigned long min_pfn = ULONG_MAX;
4013 /* Assuming a sorted map, the first range found has the starting pfn */
4014 for_each_active_range_index_in_nid(i, nid)
4015 min_pfn = min(min_pfn, early_node_map[i].start_pfn);
4017 if (min_pfn == ULONG_MAX) {
4018 printk(KERN_WARNING
4019 "Could not find start_pfn for node %d\n", nid);
4020 return 0;
4023 return min_pfn;
4027 * find_min_pfn_with_active_regions - Find the minimum PFN registered
4029 * It returns the minimum PFN based on information provided via
4030 * add_active_range().
4032 unsigned long __init find_min_pfn_with_active_regions(void)
4034 return find_min_pfn_for_node(MAX_NUMNODES);
4038 * early_calculate_totalpages()
4039 * Sum pages in active regions for movable zone.
4040 * Populate N_HIGH_MEMORY for calculating usable_nodes.
4042 static unsigned long __init early_calculate_totalpages(void)
4044 int i;
4045 unsigned long totalpages = 0;
4047 for (i = 0; i < nr_nodemap_entries; i++) {
4048 unsigned long pages = early_node_map[i].end_pfn -
4049 early_node_map[i].start_pfn;
4050 totalpages += pages;
4051 if (pages)
4052 node_set_state(early_node_map[i].nid, N_HIGH_MEMORY);
4054 return totalpages;
4058 * Find the PFN the Movable zone begins in each node. Kernel memory
4059 * is spread evenly between nodes as long as the nodes have enough
4060 * memory. When they don't, some nodes will have more kernelcore than
4061 * others
4063 static void __init find_zone_movable_pfns_for_nodes(unsigned long *movable_pfn)
4065 int i, nid;
4066 unsigned long usable_startpfn;
4067 unsigned long kernelcore_node, kernelcore_remaining;
4068 /* save the state before borrow the nodemask */
4069 nodemask_t saved_node_state = node_states[N_HIGH_MEMORY];
4070 unsigned long totalpages = early_calculate_totalpages();
4071 int usable_nodes = nodes_weight(node_states[N_HIGH_MEMORY]);
4074 * If movablecore was specified, calculate what size of
4075 * kernelcore that corresponds so that memory usable for
4076 * any allocation type is evenly spread. If both kernelcore
4077 * and movablecore are specified, then the value of kernelcore
4078 * will be used for required_kernelcore if it's greater than
4079 * what movablecore would have allowed.
4081 if (required_movablecore) {
4082 unsigned long corepages;
4085 * Round-up so that ZONE_MOVABLE is at least as large as what
4086 * was requested by the user
4088 required_movablecore =
4089 roundup(required_movablecore, MAX_ORDER_NR_PAGES);
4090 corepages = totalpages - required_movablecore;
4092 required_kernelcore = max(required_kernelcore, corepages);
4095 /* If kernelcore was not specified, there is no ZONE_MOVABLE */
4096 if (!required_kernelcore)
4097 goto out;
4099 /* usable_startpfn is the lowest possible pfn ZONE_MOVABLE can be at */
4100 find_usable_zone_for_movable();
4101 usable_startpfn = arch_zone_lowest_possible_pfn[movable_zone];
4103 restart:
4104 /* Spread kernelcore memory as evenly as possible throughout nodes */
4105 kernelcore_node = required_kernelcore / usable_nodes;
4106 for_each_node_state(nid, N_HIGH_MEMORY) {
4108 * Recalculate kernelcore_node if the division per node
4109 * now exceeds what is necessary to satisfy the requested
4110 * amount of memory for the kernel
4112 if (required_kernelcore < kernelcore_node)
4113 kernelcore_node = required_kernelcore / usable_nodes;
4116 * As the map is walked, we track how much memory is usable
4117 * by the kernel using kernelcore_remaining. When it is
4118 * 0, the rest of the node is usable by ZONE_MOVABLE
4120 kernelcore_remaining = kernelcore_node;
4122 /* Go through each range of PFNs within this node */
4123 for_each_active_range_index_in_nid(i, nid) {
4124 unsigned long start_pfn, end_pfn;
4125 unsigned long size_pages;
4127 start_pfn = max(early_node_map[i].start_pfn,
4128 zone_movable_pfn[nid]);
4129 end_pfn = early_node_map[i].end_pfn;
4130 if (start_pfn >= end_pfn)
4131 continue;
4133 /* Account for what is only usable for kernelcore */
4134 if (start_pfn < usable_startpfn) {
4135 unsigned long kernel_pages;
4136 kernel_pages = min(end_pfn, usable_startpfn)
4137 - start_pfn;
4139 kernelcore_remaining -= min(kernel_pages,
4140 kernelcore_remaining);
4141 required_kernelcore -= min(kernel_pages,
4142 required_kernelcore);
4144 /* Continue if range is now fully accounted */
4145 if (end_pfn <= usable_startpfn) {
4148 * Push zone_movable_pfn to the end so
4149 * that if we have to rebalance
4150 * kernelcore across nodes, we will
4151 * not double account here
4153 zone_movable_pfn[nid] = end_pfn;
4154 continue;
4156 start_pfn = usable_startpfn;
4160 * The usable PFN range for ZONE_MOVABLE is from
4161 * start_pfn->end_pfn. Calculate size_pages as the
4162 * number of pages used as kernelcore
4164 size_pages = end_pfn - start_pfn;
4165 if (size_pages > kernelcore_remaining)
4166 size_pages = kernelcore_remaining;
4167 zone_movable_pfn[nid] = start_pfn + size_pages;
4170 * Some kernelcore has been met, update counts and
4171 * break if the kernelcore for this node has been
4172 * satisified
4174 required_kernelcore -= min(required_kernelcore,
4175 size_pages);
4176 kernelcore_remaining -= size_pages;
4177 if (!kernelcore_remaining)
4178 break;
4183 * If there is still required_kernelcore, we do another pass with one
4184 * less node in the count. This will push zone_movable_pfn[nid] further
4185 * along on the nodes that still have memory until kernelcore is
4186 * satisified
4188 usable_nodes--;
4189 if (usable_nodes && required_kernelcore > usable_nodes)
4190 goto restart;
4192 /* Align start of ZONE_MOVABLE on all nids to MAX_ORDER_NR_PAGES */
4193 for (nid = 0; nid < MAX_NUMNODES; nid++)
4194 zone_movable_pfn[nid] =
4195 roundup(zone_movable_pfn[nid], MAX_ORDER_NR_PAGES);
4197 out:
4198 /* restore the node_state */
4199 node_states[N_HIGH_MEMORY] = saved_node_state;
4202 /* Any regular memory on that node ? */
4203 static void check_for_regular_memory(pg_data_t *pgdat)
4205 #ifdef CONFIG_HIGHMEM
4206 enum zone_type zone_type;
4208 for (zone_type = 0; zone_type <= ZONE_NORMAL; zone_type++) {
4209 struct zone *zone = &pgdat->node_zones[zone_type];
4210 if (zone->present_pages)
4211 node_set_state(zone_to_nid(zone), N_NORMAL_MEMORY);
4213 #endif
4217 * free_area_init_nodes - Initialise all pg_data_t and zone data
4218 * @max_zone_pfn: an array of max PFNs for each zone
4220 * This will call free_area_init_node() for each active node in the system.
4221 * Using the page ranges provided by add_active_range(), the size of each
4222 * zone in each node and their holes is calculated. If the maximum PFN
4223 * between two adjacent zones match, it is assumed that the zone is empty.
4224 * For example, if arch_max_dma_pfn == arch_max_dma32_pfn, it is assumed
4225 * that arch_max_dma32_pfn has no pages. It is also assumed that a zone
4226 * starts where the previous one ended. For example, ZONE_DMA32 starts
4227 * at arch_max_dma_pfn.
4229 void __init free_area_init_nodes(unsigned long *max_zone_pfn)
4231 unsigned long nid;
4232 int i;
4234 /* Sort early_node_map as initialisation assumes it is sorted */
4235 sort_node_map();
4237 /* Record where the zone boundaries are */
4238 memset(arch_zone_lowest_possible_pfn, 0,
4239 sizeof(arch_zone_lowest_possible_pfn));
4240 memset(arch_zone_highest_possible_pfn, 0,
4241 sizeof(arch_zone_highest_possible_pfn));
4242 arch_zone_lowest_possible_pfn[0] = find_min_pfn_with_active_regions();
4243 arch_zone_highest_possible_pfn[0] = max_zone_pfn[0];
4244 for (i = 1; i < MAX_NR_ZONES; i++) {
4245 if (i == ZONE_MOVABLE)
4246 continue;
4247 arch_zone_lowest_possible_pfn[i] =
4248 arch_zone_highest_possible_pfn[i-1];
4249 arch_zone_highest_possible_pfn[i] =
4250 max(max_zone_pfn[i], arch_zone_lowest_possible_pfn[i]);
4252 arch_zone_lowest_possible_pfn[ZONE_MOVABLE] = 0;
4253 arch_zone_highest_possible_pfn[ZONE_MOVABLE] = 0;
4255 /* Find the PFNs that ZONE_MOVABLE begins at in each node */
4256 memset(zone_movable_pfn, 0, sizeof(zone_movable_pfn));
4257 find_zone_movable_pfns_for_nodes(zone_movable_pfn);
4259 /* Print out the zone ranges */
4260 printk("Zone PFN ranges:\n");
4261 for (i = 0; i < MAX_NR_ZONES; i++) {
4262 if (i == ZONE_MOVABLE)
4263 continue;
4264 printk(" %-8s %0#10lx -> %0#10lx\n",
4265 zone_names[i],
4266 arch_zone_lowest_possible_pfn[i],
4267 arch_zone_highest_possible_pfn[i]);
4270 /* Print out the PFNs ZONE_MOVABLE begins at in each node */
4271 printk("Movable zone start PFN for each node\n");
4272 for (i = 0; i < MAX_NUMNODES; i++) {
4273 if (zone_movable_pfn[i])
4274 printk(" Node %d: %lu\n", i, zone_movable_pfn[i]);
4277 /* Print out the early_node_map[] */
4278 printk("early_node_map[%d] active PFN ranges\n", nr_nodemap_entries);
4279 for (i = 0; i < nr_nodemap_entries; i++)
4280 printk(" %3d: %0#10lx -> %0#10lx\n", early_node_map[i].nid,
4281 early_node_map[i].start_pfn,
4282 early_node_map[i].end_pfn);
4284 /* Initialise every node */
4285 mminit_verify_pageflags_layout();
4286 setup_nr_node_ids();
4287 for_each_online_node(nid) {
4288 pg_data_t *pgdat = NODE_DATA(nid);
4289 free_area_init_node(nid, NULL,
4290 find_min_pfn_for_node(nid), NULL);
4292 /* Any memory on that node */
4293 if (pgdat->node_present_pages)
4294 node_set_state(nid, N_HIGH_MEMORY);
4295 check_for_regular_memory(pgdat);
4299 static int __init cmdline_parse_core(char *p, unsigned long *core)
4301 unsigned long long coremem;
4302 if (!p)
4303 return -EINVAL;
4305 coremem = memparse(p, &p);
4306 *core = coremem >> PAGE_SHIFT;
4308 /* Paranoid check that UL is enough for the coremem value */
4309 WARN_ON((coremem >> PAGE_SHIFT) > ULONG_MAX);
4311 return 0;
4315 * kernelcore=size sets the amount of memory for use for allocations that
4316 * cannot be reclaimed or migrated.
4318 static int __init cmdline_parse_kernelcore(char *p)
4320 return cmdline_parse_core(p, &required_kernelcore);
4324 * movablecore=size sets the amount of memory for use for allocations that
4325 * can be reclaimed or migrated.
4327 static int __init cmdline_parse_movablecore(char *p)
4329 return cmdline_parse_core(p, &required_movablecore);
4332 early_param("kernelcore", cmdline_parse_kernelcore);
4333 early_param("movablecore", cmdline_parse_movablecore);
4335 #endif /* CONFIG_ARCH_POPULATES_NODE_MAP */
4338 * set_dma_reserve - set the specified number of pages reserved in the first zone
4339 * @new_dma_reserve: The number of pages to mark reserved
4341 * The per-cpu batchsize and zone watermarks are determined by present_pages.
4342 * In the DMA zone, a significant percentage may be consumed by kernel image
4343 * and other unfreeable allocations which can skew the watermarks badly. This
4344 * function may optionally be used to account for unfreeable pages in the
4345 * first zone (e.g., ZONE_DMA). The effect will be lower watermarks and
4346 * smaller per-cpu batchsize.
4348 void __init set_dma_reserve(unsigned long new_dma_reserve)
4350 dma_reserve = new_dma_reserve;
4353 #ifndef CONFIG_NEED_MULTIPLE_NODES
4354 struct pglist_data __refdata contig_page_data = { .bdata = &bootmem_node_data[0] };
4355 EXPORT_SYMBOL(contig_page_data);
4356 #endif
4358 void __init free_area_init(unsigned long *zones_size)
4360 free_area_init_node(0, zones_size,
4361 __pa(PAGE_OFFSET) >> PAGE_SHIFT, NULL);
4364 static int page_alloc_cpu_notify(struct notifier_block *self,
4365 unsigned long action, void *hcpu)
4367 int cpu = (unsigned long)hcpu;
4369 if (action == CPU_DEAD || action == CPU_DEAD_FROZEN) {
4370 drain_pages(cpu);
4373 * Spill the event counters of the dead processor
4374 * into the current processors event counters.
4375 * This artificially elevates the count of the current
4376 * processor.
4378 vm_events_fold_cpu(cpu);
4381 * Zero the differential counters of the dead processor
4382 * so that the vm statistics are consistent.
4384 * This is only okay since the processor is dead and cannot
4385 * race with what we are doing.
4387 refresh_cpu_vm_stats(cpu);
4389 return NOTIFY_OK;
4392 void __init page_alloc_init(void)
4394 hotcpu_notifier(page_alloc_cpu_notify, 0);
4398 * calculate_totalreserve_pages - called when sysctl_lower_zone_reserve_ratio
4399 * or min_free_kbytes changes.
4401 static void calculate_totalreserve_pages(void)
4403 struct pglist_data *pgdat;
4404 unsigned long reserve_pages = 0;
4405 enum zone_type i, j;
4407 for_each_online_pgdat(pgdat) {
4408 for (i = 0; i < MAX_NR_ZONES; i++) {
4409 struct zone *zone = pgdat->node_zones + i;
4410 unsigned long max = 0;
4412 /* Find valid and maximum lowmem_reserve in the zone */
4413 for (j = i; j < MAX_NR_ZONES; j++) {
4414 if (zone->lowmem_reserve[j] > max)
4415 max = zone->lowmem_reserve[j];
4418 /* we treat the high watermark as reserved pages. */
4419 max += high_wmark_pages(zone);
4421 if (max > zone->present_pages)
4422 max = zone->present_pages;
4423 reserve_pages += max;
4426 totalreserve_pages = reserve_pages;
4430 * setup_per_zone_lowmem_reserve - called whenever
4431 * sysctl_lower_zone_reserve_ratio changes. Ensures that each zone
4432 * has a correct pages reserved value, so an adequate number of
4433 * pages are left in the zone after a successful __alloc_pages().
4435 static void setup_per_zone_lowmem_reserve(void)
4437 struct pglist_data *pgdat;
4438 enum zone_type j, idx;
4440 for_each_online_pgdat(pgdat) {
4441 for (j = 0; j < MAX_NR_ZONES; j++) {
4442 struct zone *zone = pgdat->node_zones + j;
4443 unsigned long present_pages = zone->present_pages;
4445 zone->lowmem_reserve[j] = 0;
4447 idx = j;
4448 while (idx) {
4449 struct zone *lower_zone;
4451 idx--;
4453 if (sysctl_lowmem_reserve_ratio[idx] < 1)
4454 sysctl_lowmem_reserve_ratio[idx] = 1;
4456 lower_zone = pgdat->node_zones + idx;
4457 lower_zone->lowmem_reserve[j] = present_pages /
4458 sysctl_lowmem_reserve_ratio[idx];
4459 present_pages += lower_zone->present_pages;
4464 /* update totalreserve_pages */
4465 calculate_totalreserve_pages();
4469 * setup_per_zone_wmarks - called when min_free_kbytes changes
4470 * or when memory is hot-{added|removed}
4472 * Ensures that the watermark[min,low,high] values for each zone are set
4473 * correctly with respect to min_free_kbytes.
4475 void setup_per_zone_wmarks(void)
4477 unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
4478 unsigned long lowmem_pages = 0;
4479 struct zone *zone;
4480 unsigned long flags;
4482 /* Calculate total number of !ZONE_HIGHMEM pages */
4483 for_each_zone(zone) {
4484 if (!is_highmem(zone))
4485 lowmem_pages += zone->present_pages;
4488 for_each_zone(zone) {
4489 u64 tmp;
4491 spin_lock_irqsave(&zone->lock, flags);
4492 tmp = (u64)pages_min * zone->present_pages;
4493 do_div(tmp, lowmem_pages);
4494 if (is_highmem(zone)) {
4496 * __GFP_HIGH and PF_MEMALLOC allocations usually don't
4497 * need highmem pages, so cap pages_min to a small
4498 * value here.
4500 * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN)
4501 * deltas controls asynch page reclaim, and so should
4502 * not be capped for highmem.
4504 int min_pages;
4506 min_pages = zone->present_pages / 1024;
4507 if (min_pages < SWAP_CLUSTER_MAX)
4508 min_pages = SWAP_CLUSTER_MAX;
4509 if (min_pages > 128)
4510 min_pages = 128;
4511 zone->watermark[WMARK_MIN] = min_pages;
4512 } else {
4514 * If it's a lowmem zone, reserve a number of pages
4515 * proportionate to the zone's size.
4517 zone->watermark[WMARK_MIN] = tmp;
4520 zone->watermark[WMARK_LOW] = min_wmark_pages(zone) + (tmp >> 2);
4521 zone->watermark[WMARK_HIGH] = min_wmark_pages(zone) + (tmp >> 1);
4522 setup_zone_migrate_reserve(zone);
4523 spin_unlock_irqrestore(&zone->lock, flags);
4526 /* update totalreserve_pages */
4527 calculate_totalreserve_pages();
4531 * The inactive anon list should be small enough that the VM never has to
4532 * do too much work, but large enough that each inactive page has a chance
4533 * to be referenced again before it is swapped out.
4535 * The inactive_anon ratio is the target ratio of ACTIVE_ANON to
4536 * INACTIVE_ANON pages on this zone's LRU, maintained by the
4537 * pageout code. A zone->inactive_ratio of 3 means 3:1 or 25% of
4538 * the anonymous pages are kept on the inactive list.
4540 * total target max
4541 * memory ratio inactive anon
4542 * -------------------------------------
4543 * 10MB 1 5MB
4544 * 100MB 1 50MB
4545 * 1GB 3 250MB
4546 * 10GB 10 0.9GB
4547 * 100GB 31 3GB
4548 * 1TB 101 10GB
4549 * 10TB 320 32GB
4551 void calculate_zone_inactive_ratio(struct zone *zone)
4553 unsigned int gb, ratio;
4555 /* Zone size in gigabytes */
4556 gb = zone->present_pages >> (30 - PAGE_SHIFT);
4557 if (gb)
4558 ratio = int_sqrt(10 * gb);
4559 else
4560 ratio = 1;
4562 zone->inactive_ratio = ratio;
4565 static void __init setup_per_zone_inactive_ratio(void)
4567 struct zone *zone;
4569 for_each_zone(zone)
4570 calculate_zone_inactive_ratio(zone);
4574 * Initialise min_free_kbytes.
4576 * For small machines we want it small (128k min). For large machines
4577 * we want it large (64MB max). But it is not linear, because network
4578 * bandwidth does not increase linearly with machine size. We use
4580 * min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
4581 * min_free_kbytes = sqrt(lowmem_kbytes * 16)
4583 * which yields
4585 * 16MB: 512k
4586 * 32MB: 724k
4587 * 64MB: 1024k
4588 * 128MB: 1448k
4589 * 256MB: 2048k
4590 * 512MB: 2896k
4591 * 1024MB: 4096k
4592 * 2048MB: 5792k
4593 * 4096MB: 8192k
4594 * 8192MB: 11584k
4595 * 16384MB: 16384k
4597 static int __init init_per_zone_wmark_min(void)
4599 unsigned long lowmem_kbytes;
4601 lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
4603 min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
4604 if (min_free_kbytes < 128)
4605 min_free_kbytes = 128;
4606 if (min_free_kbytes > 65536)
4607 min_free_kbytes = 65536;
4608 setup_per_zone_wmarks();
4609 setup_per_zone_lowmem_reserve();
4610 setup_per_zone_inactive_ratio();
4611 return 0;
4613 module_init(init_per_zone_wmark_min)
4616 * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
4617 * that we can call two helper functions whenever min_free_kbytes
4618 * changes.
4620 int min_free_kbytes_sysctl_handler(ctl_table *table, int write,
4621 struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
4623 proc_dointvec(table, write, file, buffer, length, ppos);
4624 if (write)
4625 setup_per_zone_wmarks();
4626 return 0;
4629 #ifdef CONFIG_NUMA
4630 int sysctl_min_unmapped_ratio_sysctl_handler(ctl_table *table, int write,
4631 struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
4633 struct zone *zone;
4634 int rc;
4636 rc = proc_dointvec_minmax(table, write, file, buffer, length, ppos);
4637 if (rc)
4638 return rc;
4640 for_each_zone(zone)
4641 zone->min_unmapped_pages = (zone->present_pages *
4642 sysctl_min_unmapped_ratio) / 100;
4643 return 0;
4646 int sysctl_min_slab_ratio_sysctl_handler(ctl_table *table, int write,
4647 struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
4649 struct zone *zone;
4650 int rc;
4652 rc = proc_dointvec_minmax(table, write, file, buffer, length, ppos);
4653 if (rc)
4654 return rc;
4656 for_each_zone(zone)
4657 zone->min_slab_pages = (zone->present_pages *
4658 sysctl_min_slab_ratio) / 100;
4659 return 0;
4661 #endif
4664 * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
4665 * proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
4666 * whenever sysctl_lowmem_reserve_ratio changes.
4668 * The reserve ratio obviously has absolutely no relation with the
4669 * minimum watermarks. The lowmem reserve ratio can only make sense
4670 * if in function of the boot time zone sizes.
4672 int lowmem_reserve_ratio_sysctl_handler(ctl_table *table, int write,
4673 struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
4675 proc_dointvec_minmax(table, write, file, buffer, length, ppos);
4676 setup_per_zone_lowmem_reserve();
4677 return 0;
4681 * percpu_pagelist_fraction - changes the pcp->high for each zone on each
4682 * cpu. It is the fraction of total pages in each zone that a hot per cpu pagelist
4683 * can have before it gets flushed back to buddy allocator.
4686 int percpu_pagelist_fraction_sysctl_handler(ctl_table *table, int write,
4687 struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
4689 struct zone *zone;
4690 unsigned int cpu;
4691 int ret;
4693 ret = proc_dointvec_minmax(table, write, file, buffer, length, ppos);
4694 if (!write || (ret == -EINVAL))
4695 return ret;
4696 for_each_populated_zone(zone) {
4697 for_each_online_cpu(cpu) {
4698 unsigned long high;
4699 high = zone->present_pages / percpu_pagelist_fraction;
4700 setup_pagelist_highmark(zone_pcp(zone, cpu), high);
4703 return 0;
4706 int hashdist = HASHDIST_DEFAULT;
4708 #ifdef CONFIG_NUMA
4709 static int __init set_hashdist(char *str)
4711 if (!str)
4712 return 0;
4713 hashdist = simple_strtoul(str, &str, 0);
4714 return 1;
4716 __setup("hashdist=", set_hashdist);
4717 #endif
4720 * allocate a large system hash table from bootmem
4721 * - it is assumed that the hash table must contain an exact power-of-2
4722 * quantity of entries
4723 * - limit is the number of hash buckets, not the total allocation size
4725 void *__init alloc_large_system_hash(const char *tablename,
4726 unsigned long bucketsize,
4727 unsigned long numentries,
4728 int scale,
4729 int flags,
4730 unsigned int *_hash_shift,
4731 unsigned int *_hash_mask,
4732 unsigned long limit)
4734 unsigned long long max = limit;
4735 unsigned long log2qty, size;
4736 void *table = NULL;
4738 /* allow the kernel cmdline to have a say */
4739 if (!numentries) {
4740 /* round applicable memory size up to nearest megabyte */
4741 numentries = nr_kernel_pages;
4742 numentries += (1UL << (20 - PAGE_SHIFT)) - 1;
4743 numentries >>= 20 - PAGE_SHIFT;
4744 numentries <<= 20 - PAGE_SHIFT;
4746 /* limit to 1 bucket per 2^scale bytes of low memory */
4747 if (scale > PAGE_SHIFT)
4748 numentries >>= (scale - PAGE_SHIFT);
4749 else
4750 numentries <<= (PAGE_SHIFT - scale);
4752 /* Make sure we've got at least a 0-order allocation.. */
4753 if (unlikely((numentries * bucketsize) < PAGE_SIZE))
4754 numentries = PAGE_SIZE / bucketsize;
4756 numentries = roundup_pow_of_two(numentries);
4758 /* limit allocation size to 1/16 total memory by default */
4759 if (max == 0) {
4760 max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
4761 do_div(max, bucketsize);
4764 if (numentries > max)
4765 numentries = max;
4767 log2qty = ilog2(numentries);
4769 do {
4770 size = bucketsize << log2qty;
4771 if (flags & HASH_EARLY)
4772 table = alloc_bootmem_nopanic(size);
4773 else if (hashdist)
4774 table = __vmalloc(size, GFP_ATOMIC, PAGE_KERNEL);
4775 else {
4777 * If bucketsize is not a power-of-two, we may free
4778 * some pages at the end of hash table which
4779 * alloc_pages_exact() automatically does
4781 if (get_order(size) < MAX_ORDER) {
4782 table = alloc_pages_exact(size, GFP_ATOMIC);
4783 kmemleak_alloc(table, size, 1, GFP_ATOMIC);
4786 } while (!table && size > PAGE_SIZE && --log2qty);
4788 if (!table)
4789 panic("Failed to allocate %s hash table\n", tablename);
4791 printk(KERN_INFO "%s hash table entries: %d (order: %d, %lu bytes)\n",
4792 tablename,
4793 (1U << log2qty),
4794 ilog2(size) - PAGE_SHIFT,
4795 size);
4797 if (_hash_shift)
4798 *_hash_shift = log2qty;
4799 if (_hash_mask)
4800 *_hash_mask = (1 << log2qty) - 1;
4802 return table;
4805 /* Return a pointer to the bitmap storing bits affecting a block of pages */
4806 static inline unsigned long *get_pageblock_bitmap(struct zone *zone,
4807 unsigned long pfn)
4809 #ifdef CONFIG_SPARSEMEM
4810 return __pfn_to_section(pfn)->pageblock_flags;
4811 #else
4812 return zone->pageblock_flags;
4813 #endif /* CONFIG_SPARSEMEM */
4816 static inline int pfn_to_bitidx(struct zone *zone, unsigned long pfn)
4818 #ifdef CONFIG_SPARSEMEM
4819 pfn &= (PAGES_PER_SECTION-1);
4820 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
4821 #else
4822 pfn = pfn - zone->zone_start_pfn;
4823 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
4824 #endif /* CONFIG_SPARSEMEM */
4828 * get_pageblock_flags_group - Return the requested group of flags for the pageblock_nr_pages block of pages
4829 * @page: The page within the block of interest
4830 * @start_bitidx: The first bit of interest to retrieve
4831 * @end_bitidx: The last bit of interest
4832 * returns pageblock_bits flags
4834 unsigned long get_pageblock_flags_group(struct page *page,
4835 int start_bitidx, int end_bitidx)
4837 struct zone *zone;
4838 unsigned long *bitmap;
4839 unsigned long pfn, bitidx;
4840 unsigned long flags = 0;
4841 unsigned long value = 1;
4843 zone = page_zone(page);
4844 pfn = page_to_pfn(page);
4845 bitmap = get_pageblock_bitmap(zone, pfn);
4846 bitidx = pfn_to_bitidx(zone, pfn);
4848 for (; start_bitidx <= end_bitidx; start_bitidx++, value <<= 1)
4849 if (test_bit(bitidx + start_bitidx, bitmap))
4850 flags |= value;
4852 return flags;
4856 * set_pageblock_flags_group - Set the requested group of flags for a pageblock_nr_pages block of pages
4857 * @page: The page within the block of interest
4858 * @start_bitidx: The first bit of interest
4859 * @end_bitidx: The last bit of interest
4860 * @flags: The flags to set
4862 void set_pageblock_flags_group(struct page *page, unsigned long flags,
4863 int start_bitidx, int end_bitidx)
4865 struct zone *zone;
4866 unsigned long *bitmap;
4867 unsigned long pfn, bitidx;
4868 unsigned long value = 1;
4870 zone = page_zone(page);
4871 pfn = page_to_pfn(page);
4872 bitmap = get_pageblock_bitmap(zone, pfn);
4873 bitidx = pfn_to_bitidx(zone, pfn);
4874 VM_BUG_ON(pfn < zone->zone_start_pfn);
4875 VM_BUG_ON(pfn >= zone->zone_start_pfn + zone->spanned_pages);
4877 for (; start_bitidx <= end_bitidx; start_bitidx++, value <<= 1)
4878 if (flags & value)
4879 __set_bit(bitidx + start_bitidx, bitmap);
4880 else
4881 __clear_bit(bitidx + start_bitidx, bitmap);
4885 * This is designed as sub function...plz see page_isolation.c also.
4886 * set/clear page block's type to be ISOLATE.
4887 * page allocater never alloc memory from ISOLATE block.
4890 int set_migratetype_isolate(struct page *page)
4892 struct zone *zone;
4893 unsigned long flags;
4894 int ret = -EBUSY;
4896 zone = page_zone(page);
4897 spin_lock_irqsave(&zone->lock, flags);
4899 * In future, more migrate types will be able to be isolation target.
4901 if (get_pageblock_migratetype(page) != MIGRATE_MOVABLE)
4902 goto out;
4903 set_pageblock_migratetype(page, MIGRATE_ISOLATE);
4904 move_freepages_block(zone, page, MIGRATE_ISOLATE);
4905 ret = 0;
4906 out:
4907 spin_unlock_irqrestore(&zone->lock, flags);
4908 if (!ret)
4909 drain_all_pages();
4910 return ret;
4913 void unset_migratetype_isolate(struct page *page)
4915 struct zone *zone;
4916 unsigned long flags;
4917 zone = page_zone(page);
4918 spin_lock_irqsave(&zone->lock, flags);
4919 if (get_pageblock_migratetype(page) != MIGRATE_ISOLATE)
4920 goto out;
4921 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
4922 move_freepages_block(zone, page, MIGRATE_MOVABLE);
4923 out:
4924 spin_unlock_irqrestore(&zone->lock, flags);
4927 #ifdef CONFIG_MEMORY_HOTREMOVE
4929 * All pages in the range must be isolated before calling this.
4931 void
4932 __offline_isolated_pages(unsigned long start_pfn, unsigned long end_pfn)
4934 struct page *page;
4935 struct zone *zone;
4936 int order, i;
4937 unsigned long pfn;
4938 unsigned long flags;
4939 /* find the first valid pfn */
4940 for (pfn = start_pfn; pfn < end_pfn; pfn++)
4941 if (pfn_valid(pfn))
4942 break;
4943 if (pfn == end_pfn)
4944 return;
4945 zone = page_zone(pfn_to_page(pfn));
4946 spin_lock_irqsave(&zone->lock, flags);
4947 pfn = start_pfn;
4948 while (pfn < end_pfn) {
4949 if (!pfn_valid(pfn)) {
4950 pfn++;
4951 continue;
4953 page = pfn_to_page(pfn);
4954 BUG_ON(page_count(page));
4955 BUG_ON(!PageBuddy(page));
4956 order = page_order(page);
4957 #ifdef CONFIG_DEBUG_VM
4958 printk(KERN_INFO "remove from free list %lx %d %lx\n",
4959 pfn, 1 << order, end_pfn);
4960 #endif
4961 list_del(&page->lru);
4962 rmv_page_order(page);
4963 zone->free_area[order].nr_free--;
4964 __mod_zone_page_state(zone, NR_FREE_PAGES,
4965 - (1UL << order));
4966 for (i = 0; i < (1 << order); i++)
4967 SetPageReserved((page+i));
4968 pfn += (1 << order);
4970 spin_unlock_irqrestore(&zone->lock, flags);
4972 #endif