GUI: Fix Tomato RAF theme for all builds. Compilation typo.
[tomato.git] / release / src-rt-6.x.4708 / linux / linux-2.6.36 / mm / page_alloc.c
blobf7afe88a332e478a93a9f3f1a02e8331473e5d1a
1 /* Modified by Broadcom Corp. Portions Copyright (c) Broadcom Corp, 2012. */
2 /*
3 * linux/mm/page_alloc.c
5 * Manages the free list, the system allocates free pages here.
6 * Note that kmalloc() lives in slab.c
8 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
9 * Swap reorganised 29.12.95, Stephen Tweedie
10 * Support of BIGMEM added by Gerhard Wichert, Siemens AG, July 1999
11 * Reshaped it to be a zoned allocator, Ingo Molnar, Red Hat, 1999
12 * Discontiguous memory support, Kanoj Sarcar, SGI, Nov 1999
13 * Zone balancing, Kanoj Sarcar, SGI, Jan 2000
14 * Per cpu hot/cold page lists, bulk allocation, Martin J. Bligh, Sept 2002
15 * (lots of bits borrowed from Ingo Molnar & Andrew Morton)
18 #include <linux/stddef.h>
19 #include <linux/mm.h>
20 #include <linux/swap.h>
21 #include <linux/interrupt.h>
22 #include <linux/pagemap.h>
23 #include <linux/jiffies.h>
24 #include <linux/bootmem.h>
25 #include <linux/compiler.h>
26 #include <linux/kernel.h>
27 #include <linux/kmemcheck.h>
28 #include <linux/module.h>
29 #include <linux/suspend.h>
30 #include <linux/pagevec.h>
31 #include <linux/blkdev.h>
32 #include <linux/slab.h>
33 #include <linux/oom.h>
34 #include <linux/notifier.h>
35 #include <linux/topology.h>
36 #include <linux/sysctl.h>
37 #include <linux/cpu.h>
38 #include <linux/cpuset.h>
39 #include <linux/memory_hotplug.h>
40 #include <linux/nodemask.h>
41 #include <linux/vmalloc.h>
42 #include <linux/mempolicy.h>
43 #include <linux/stop_machine.h>
44 #include <linux/sort.h>
45 #include <linux/pfn.h>
46 #include <linux/backing-dev.h>
47 #include <linux/fault-inject.h>
48 #include <linux/page-isolation.h>
49 #include <linux/page_cgroup.h>
50 #include <linux/debugobjects.h>
51 #include <linux/kmemleak.h>
52 #include <linux/memory.h>
53 #include <linux/compaction.h>
54 #include <trace/events/kmem.h>
55 #include <linux/ftrace_event.h>
57 #include <asm/tlbflush.h>
58 #include <asm/div64.h>
59 #include "internal.h"
61 #include <typedefs.h>
62 #include <bcmdefs.h>
64 #ifdef CONFIG_USE_PERCPU_NUMA_NODE_ID
65 DEFINE_PER_CPU(int, numa_node);
66 EXPORT_PER_CPU_SYMBOL(numa_node);
67 #endif
69 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
71 * N.B., Do NOT reference the '_numa_mem_' per cpu variable directly.
72 * It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined.
73 * Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem()
74 * defined in <linux/topology.h>.
76 DEFINE_PER_CPU(int, _numa_mem_); /* Kernel "local memory" node */
77 EXPORT_PER_CPU_SYMBOL(_numa_mem_);
78 #endif
81 * Array of node states.
83 nodemask_t node_states[NR_NODE_STATES] __read_mostly = {
84 [N_POSSIBLE] = NODE_MASK_ALL,
85 [N_ONLINE] = { { [0] = 1UL } },
86 #ifndef CONFIG_NUMA
87 [N_NORMAL_MEMORY] = { { [0] = 1UL } },
88 #ifdef CONFIG_HIGHMEM
89 [N_HIGH_MEMORY] = { { [0] = 1UL } },
90 #endif
91 [N_CPU] = { { [0] = 1UL } },
92 #endif /* NUMA */
94 EXPORT_SYMBOL(node_states);
96 unsigned long totalram_pages __read_mostly;
97 unsigned long totalreserve_pages __read_mostly;
98 int percpu_pagelist_fraction;
99 gfp_t gfp_allowed_mask __read_mostly = GFP_BOOT_MASK;
101 #ifdef CONFIG_PM_SLEEP
103 * The following functions are used by the suspend/hibernate code to temporarily
104 * change gfp_allowed_mask in order to avoid using I/O during memory allocations
105 * while devices are suspended. To avoid races with the suspend/hibernate code,
106 * they should always be called with pm_mutex held (gfp_allowed_mask also should
107 * only be modified with pm_mutex held, unless the suspend/hibernate code is
108 * guaranteed not to run in parallel with that modification).
111 static gfp_t saved_gfp_mask;
113 void pm_restore_gfp_mask(void)
115 WARN_ON(!mutex_is_locked(&pm_mutex));
116 if (saved_gfp_mask) {
117 gfp_allowed_mask = saved_gfp_mask;
118 saved_gfp_mask = 0;
122 void pm_restrict_gfp_mask(void)
124 WARN_ON(!mutex_is_locked(&pm_mutex));
125 WARN_ON(saved_gfp_mask);
126 saved_gfp_mask = gfp_allowed_mask;
127 gfp_allowed_mask &= ~GFP_IOFS;
129 #endif /* CONFIG_PM_SLEEP */
131 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
132 int pageblock_order __read_mostly;
133 #endif
135 static void __free_pages_ok(struct page *page, unsigned int order);
138 * results with 256, 32 in the lowmem_reserve sysctl:
139 * 1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
140 * 1G machine -> (16M dma, 784M normal, 224M high)
141 * NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
142 * HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
143 * HIGHMEM allocation will (224M+784M)/256 of ram reserved in ZONE_DMA
145 * TBD: should special case ZONE_DMA32 machines here - in those we normally
146 * don't need any ZONE_NORMAL reservation
148 int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES-1] = {
149 #ifdef CONFIG_ZONE_DMA
150 256,
151 #endif
152 #ifdef CONFIG_ZONE_DMA32
153 256,
154 #endif
155 #ifdef CONFIG_HIGHMEM
157 #endif
161 EXPORT_SYMBOL(totalram_pages);
163 static char * const zone_names[MAX_NR_ZONES] = {
164 #ifdef CONFIG_ZONE_DMA
165 "DMA",
166 #endif
167 #ifdef CONFIG_ZONE_DMA32
168 "DMA32",
169 #endif
170 "Normal",
171 #ifdef CONFIG_HIGHMEM
172 "HighMem",
173 #endif
174 "Movable",
177 int min_free_kbytes = 1024;
179 static unsigned long __meminitdata nr_kernel_pages;
180 static unsigned long __meminitdata nr_all_pages;
181 static unsigned long __meminitdata dma_reserve;
183 #ifdef CONFIG_ARCH_POPULATES_NODE_MAP
185 * MAX_ACTIVE_REGIONS determines the maximum number of distinct
186 * ranges of memory (RAM) that may be registered with add_active_range().
187 * Ranges passed to add_active_range() will be merged if possible
188 * so the number of times add_active_range() can be called is
189 * related to the number of nodes and the number of holes
191 #ifdef CONFIG_MAX_ACTIVE_REGIONS
192 /* Allow an architecture to set MAX_ACTIVE_REGIONS to save memory */
193 #define MAX_ACTIVE_REGIONS CONFIG_MAX_ACTIVE_REGIONS
194 #else
195 #if MAX_NUMNODES >= 32
196 /* If there can be many nodes, allow up to 50 holes per node */
197 #define MAX_ACTIVE_REGIONS (MAX_NUMNODES*50)
198 #else
199 /* By default, allow up to 256 distinct regions */
200 #define MAX_ACTIVE_REGIONS 256
201 #endif
202 #endif
204 static struct node_active_region __meminitdata early_node_map[MAX_ACTIVE_REGIONS];
205 static int __meminitdata nr_nodemap_entries;
206 static unsigned long __meminitdata arch_zone_lowest_possible_pfn[MAX_NR_ZONES];
207 static unsigned long __meminitdata arch_zone_highest_possible_pfn[MAX_NR_ZONES];
208 static unsigned long __initdata required_kernelcore;
209 static unsigned long __initdata required_movablecore;
210 static unsigned long __meminitdata zone_movable_pfn[MAX_NUMNODES];
212 /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
213 int movable_zone;
214 EXPORT_SYMBOL(movable_zone);
215 #endif /* CONFIG_ARCH_POPULATES_NODE_MAP */
217 #if MAX_NUMNODES > 1
218 int nr_node_ids __read_mostly = MAX_NUMNODES;
219 int nr_online_nodes __read_mostly = 1;
220 EXPORT_SYMBOL(nr_node_ids);
221 EXPORT_SYMBOL(nr_online_nodes);
222 #endif
224 int page_group_by_mobility_disabled __read_mostly;
226 static void set_pageblock_migratetype(struct page *page, int migratetype)
229 if (unlikely(page_group_by_mobility_disabled))
230 migratetype = MIGRATE_UNMOVABLE;
232 set_pageblock_flags_group(page, (unsigned long)migratetype,
233 PB_migrate, PB_migrate_end);
236 bool oom_killer_disabled __read_mostly;
238 #ifdef CONFIG_DEBUG_VM
239 static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
241 int ret = 0;
242 unsigned seq;
243 unsigned long pfn = page_to_pfn(page);
245 do {
246 seq = zone_span_seqbegin(zone);
247 if (pfn >= zone->zone_start_pfn + zone->spanned_pages)
248 ret = 1;
249 else if (pfn < zone->zone_start_pfn)
250 ret = 1;
251 } while (zone_span_seqretry(zone, seq));
253 return ret;
256 static int page_is_consistent(struct zone *zone, struct page *page)
258 if (!pfn_valid_within(page_to_pfn(page)))
259 return 0;
260 if (zone != page_zone(page))
261 return 0;
263 return 1;
266 * Temporary debugging check for pages not lying within a given zone.
268 static int bad_range(struct zone *zone, struct page *page)
270 if (page_outside_zone_boundaries(zone, page))
271 return 1;
272 if (!page_is_consistent(zone, page))
273 return 1;
275 return 0;
277 #else
278 static inline int bad_range(struct zone *zone, struct page *page)
280 return 0;
282 #endif
284 static void bad_page(struct page *page)
286 static unsigned long resume;
287 static unsigned long nr_shown;
288 static unsigned long nr_unshown;
290 /* Don't complain about poisoned pages */
291 if (PageHWPoison(page)) {
292 __ClearPageBuddy(page);
293 return;
297 * Allow a burst of 60 reports, then keep quiet for that minute;
298 * or allow a steady drip of one report per second.
300 if (nr_shown == 60) {
301 if (time_before(jiffies, resume)) {
302 nr_unshown++;
303 goto out;
305 if (nr_unshown) {
306 printk(KERN_ALERT
307 "BUG: Bad page state: %lu messages suppressed\n",
308 nr_unshown);
309 nr_unshown = 0;
311 nr_shown = 0;
313 if (nr_shown++ == 0)
314 resume = jiffies + 60 * HZ;
316 printk(KERN_ALERT "BUG: Bad page state in process %s pfn:%05lx\n",
317 current->comm, page_to_pfn(page));
318 dump_page(page);
320 dump_stack();
321 out:
322 /* Leave bad fields for debug, except PageBuddy could make trouble */
323 __ClearPageBuddy(page);
324 add_taint(TAINT_BAD_PAGE);
328 * Higher-order pages are called "compound pages". They are structured thusly:
330 * The first PAGE_SIZE page is called the "head page".
332 * The remaining PAGE_SIZE pages are called "tail pages".
334 * All pages have PG_compound set. All pages have their ->private pointing at
335 * the head page (even the head page has this).
337 * The first tail page's ->lru.next holds the address of the compound page's
338 * put_page() function. Its ->lru.prev holds the order of allocation.
339 * This usage means that zero-order pages may not be compound.
342 static void free_compound_page(struct page *page)
344 __free_pages_ok(page, compound_order(page));
347 void prep_compound_page(struct page *page, unsigned long order)
349 int i;
350 int nr_pages = 1 << order;
352 set_compound_page_dtor(page, free_compound_page);
353 set_compound_order(page, order);
354 __SetPageHead(page);
355 for (i = 1; i < nr_pages; i++) {
356 struct page *p = page + i;
358 __SetPageTail(p);
359 p->first_page = page;
363 static int destroy_compound_page(struct page *page, unsigned long order)
365 int i;
366 int nr_pages = 1 << order;
367 int bad = 0;
369 if (unlikely(compound_order(page) != order) ||
370 unlikely(!PageHead(page))) {
371 bad_page(page);
372 bad++;
375 __ClearPageHead(page);
377 for (i = 1; i < nr_pages; i++) {
378 struct page *p = page + i;
380 if (unlikely(!PageTail(p) || (p->first_page != page))) {
381 bad_page(page);
382 bad++;
384 __ClearPageTail(p);
387 return bad;
390 static inline void prep_zero_page(struct page *page, int order, gfp_t gfp_flags)
392 int i;
395 * clear_highpage() will use KM_USER0, so it's a bug to use __GFP_ZERO
396 * and __GFP_HIGHMEM from hard or soft interrupt context.
398 VM_BUG_ON((gfp_flags & __GFP_HIGHMEM) && in_interrupt());
399 for (i = 0; i < (1 << order); i++)
400 clear_highpage(page + i);
403 static inline void set_page_order(struct page *page, int order)
405 set_page_private(page, order);
406 __SetPageBuddy(page);
409 static inline void rmv_page_order(struct page *page)
411 __ClearPageBuddy(page);
412 set_page_private(page, 0);
416 * Locate the struct page for both the matching buddy in our
417 * pair (buddy1) and the combined O(n+1) page they form (page).
419 * 1) Any buddy B1 will have an order O twin B2 which satisfies
420 * the following equation:
421 * B2 = B1 ^ (1 << O)
422 * For example, if the starting buddy (buddy2) is #8 its order
423 * 1 buddy is #10:
424 * B2 = 8 ^ (1 << 1) = 8 ^ 2 = 10
426 * 2) Any buddy B will have an order O+1 parent P which
427 * satisfies the following equation:
428 * P = B & ~(1 << O)
430 * Assumption: *_mem_map is contiguous at least up to MAX_ORDER
432 static inline struct page *
433 __page_find_buddy(struct page *page, unsigned long page_idx, unsigned int order)
435 unsigned long buddy_idx = page_idx ^ (1 << order);
437 return page + (buddy_idx - page_idx);
440 static inline unsigned long
441 __find_combined_index(unsigned long page_idx, unsigned int order)
443 return (page_idx & ~(1 << order));
447 * This function checks whether a page is free && is the buddy
448 * we can do coalesce a page and its buddy if
449 * (a) the buddy is not in a hole &&
450 * (b) the buddy is in the buddy system &&
451 * (c) a page and its buddy have the same order &&
452 * (d) a page and its buddy are in the same zone.
454 * For recording whether a page is in the buddy system, we use PG_buddy.
455 * Setting, clearing, and testing PG_buddy is serialized by zone->lock.
457 * For recording page's order, we use page_private(page).
459 static inline int page_is_buddy(struct page *page, struct page *buddy,
460 int order)
462 if (!pfn_valid_within(page_to_pfn(buddy)))
463 return 0;
465 if (page_zone_id(page) != page_zone_id(buddy))
466 return 0;
468 if (PageBuddy(buddy) && page_order(buddy) == order) {
469 VM_BUG_ON(page_count(buddy) != 0);
470 return 1;
472 return 0;
476 * Freeing function for a buddy system allocator.
478 * The concept of a buddy system is to maintain direct-mapped table
479 * (containing bit values) for memory blocks of various "orders".
480 * The bottom level table contains the map for the smallest allocatable
481 * units of memory (here, pages), and each level above it describes
482 * pairs of units from the levels below, hence, "buddies".
483 * At a high level, all that happens here is marking the table entry
484 * at the bottom level available, and propagating the changes upward
485 * as necessary, plus some accounting needed to play nicely with other
486 * parts of the VM system.
487 * At each level, we keep a list of pages, which are heads of continuous
488 * free pages of length of (1 << order) and marked with PG_buddy. Page's
489 * order is recorded in page_private(page) field.
490 * So when we are allocating or freeing one, we can derive the state of the
491 * other. That is, if we allocate a small block, and both were
492 * free, the remainder of the region must be split into blocks.
493 * If a block is freed, and its buddy is also free, then this
494 * triggers coalescing into a block of larger size.
496 * -- wli
499 static inline void __free_one_page(struct page *page,
500 struct zone *zone, unsigned int order,
501 int migratetype)
503 unsigned long page_idx;
504 unsigned long combined_idx;
505 struct page *buddy;
507 if (unlikely(PageCompound(page)))
508 if (unlikely(destroy_compound_page(page, order)))
509 return;
511 VM_BUG_ON(migratetype == -1);
513 page_idx = page_to_pfn(page) & ((1 << MAX_ORDER) - 1);
515 VM_BUG_ON(page_idx & ((1 << order) - 1));
516 VM_BUG_ON(bad_range(zone, page));
518 while (order < MAX_ORDER-1) {
519 buddy = __page_find_buddy(page, page_idx, order);
520 if (!page_is_buddy(page, buddy, order))
521 break;
523 /* Our buddy is free, merge with it and move up one order. */
524 list_del(&buddy->lru);
525 zone->free_area[order].nr_free--;
526 rmv_page_order(buddy);
527 combined_idx = __find_combined_index(page_idx, order);
528 page = page + (combined_idx - page_idx);
529 page_idx = combined_idx;
530 order++;
532 set_page_order(page, order);
535 * If this is not the largest possible page, check if the buddy
536 * of the next-highest order is free. If it is, it's possible
537 * that pages are being freed that will coalesce soon. In case,
538 * that is happening, add the free page to the tail of the list
539 * so it's less likely to be used soon and more likely to be merged
540 * as a higher order page
542 if ((order < MAX_ORDER-2) && pfn_valid_within(page_to_pfn(buddy))) {
543 struct page *higher_page, *higher_buddy;
544 combined_idx = __find_combined_index(page_idx, order);
545 higher_page = page + combined_idx - page_idx;
546 higher_buddy = __page_find_buddy(higher_page, combined_idx, order + 1);
547 if (page_is_buddy(higher_page, higher_buddy, order + 1)) {
548 list_add_tail(&page->lru,
549 &zone->free_area[order].free_list[migratetype]);
550 goto out;
554 list_add(&page->lru, &zone->free_area[order].free_list[migratetype]);
555 out:
556 zone->free_area[order].nr_free++;
560 * free_page_mlock() -- clean up attempts to free and mlocked() page.
561 * Page should not be on lru, so no need to fix that up.
562 * free_pages_check() will verify...
564 static inline void free_page_mlock(struct page *page)
566 __dec_zone_page_state(page, NR_MLOCK);
567 __count_vm_event(UNEVICTABLE_MLOCKFREED);
570 static inline int free_pages_check(struct page *page)
572 if (unlikely(page_mapcount(page) |
573 (page->mapping != NULL) |
574 (atomic_read(&page->_count) != 0) |
575 (page->flags & PAGE_FLAGS_CHECK_AT_FREE))) {
576 bad_page(page);
577 return 1;
579 if (page->flags & PAGE_FLAGS_CHECK_AT_PREP)
580 page->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
581 return 0;
585 * Frees a number of pages from the PCP lists
586 * Assumes all pages on list are in same zone, and of same order.
587 * count is the number of pages to free.
589 * If the zone was previously in an "all pages pinned" state then look to
590 * see if this freeing clears that state.
592 * And clear the zone's pages_scanned counter, to hold off the "all pages are
593 * pinned" detection logic.
595 static void free_pcppages_bulk(struct zone *zone, int count,
596 struct per_cpu_pages *pcp)
598 int migratetype = 0;
599 int batch_free = 0;
600 int to_free = count;
602 spin_lock(&zone->lock);
603 zone->all_unreclaimable = 0;
604 zone->pages_scanned = 0;
606 while (to_free) {
607 struct page *page;
608 struct list_head *list;
611 * Remove pages from lists in a round-robin fashion. A
612 * batch_free count is maintained that is incremented when an
613 * empty list is encountered. This is so more pages are freed
614 * off fuller lists instead of spinning excessively around empty
615 * lists
617 do {
618 batch_free++;
619 if (++migratetype == MIGRATE_PCPTYPES)
620 migratetype = 0;
621 list = &pcp->lists[migratetype];
622 } while (list_empty(list));
624 do {
625 page = list_entry(list->prev, struct page, lru);
626 /* must delete as __free_one_page list manipulates */
627 list_del(&page->lru);
628 /* MIGRATE_MOVABLE list may include MIGRATE_RESERVEs */
629 __free_one_page(page, zone, 0, page_private(page));
630 trace_mm_page_pcpu_drain(page, 0, page_private(page));
631 } while (--to_free && --batch_free && !list_empty(list));
633 __mod_zone_page_state(zone, NR_FREE_PAGES, count);
634 spin_unlock(&zone->lock);
637 static void free_one_page(struct zone *zone, struct page *page, int order,
638 int migratetype)
640 spin_lock(&zone->lock);
641 zone->all_unreclaimable = 0;
642 zone->pages_scanned = 0;
644 __free_one_page(page, zone, order, migratetype);
645 __mod_zone_page_state(zone, NR_FREE_PAGES, 1 << order);
646 spin_unlock(&zone->lock);
649 static bool free_pages_prepare(struct page *page, unsigned int order)
651 int i;
652 int bad = 0;
654 trace_mm_page_free_direct(page, order);
655 kmemcheck_free_shadow(page, order);
657 for (i = 0; i < (1 << order); i++) {
658 struct page *pg = page + i;
660 if (PageAnon(pg))
661 pg->mapping = NULL;
662 bad += free_pages_check(pg);
664 if (bad)
665 return false;
667 if (!PageHighMem(page)) {
668 debug_check_no_locks_freed(page_address(page),PAGE_SIZE<<order);
669 debug_check_no_obj_freed(page_address(page),
670 PAGE_SIZE << order);
672 arch_free_page(page, order);
673 kernel_map_pages(page, 1 << order, 0);
675 return true;
678 static void __free_pages_ok(struct page *page, unsigned int order)
680 unsigned long flags;
681 int wasMlocked = __TestClearPageMlocked(page);
683 if (!free_pages_prepare(page, order))
684 return;
686 local_irq_save(flags);
687 if (unlikely(wasMlocked))
688 free_page_mlock(page);
689 __count_vm_events(PGFREE, 1 << order);
690 free_one_page(page_zone(page), page, order,
691 get_pageblock_migratetype(page));
692 local_irq_restore(flags);
696 * permit the bootmem allocator to evade page validation on high-order frees
698 void __meminit __free_pages_bootmem(struct page *page, unsigned int order)
700 if (order == 0) {
701 __ClearPageReserved(page);
702 set_page_count(page, 0);
703 set_page_refcounted(page);
704 __free_page(page);
705 } else {
706 int loop;
708 prefetchw(page);
709 for (loop = 0; loop < BITS_PER_LONG; loop++) {
710 struct page *p = &page[loop];
712 if (loop + 1 < BITS_PER_LONG)
713 prefetchw(p + 1);
714 __ClearPageReserved(p);
715 set_page_count(p, 0);
718 set_page_refcounted(page);
719 __free_pages(page, order);
725 * The order of subdivision here is critical for the IO subsystem.
726 * Please do not alter this order without good reasons and regression
727 * testing. Specifically, as large blocks of memory are subdivided,
728 * the order in which smaller blocks are delivered depends on the order
729 * they're subdivided in this function. This is the primary factor
730 * influencing the order in which pages are delivered to the IO
731 * subsystem according to empirical testing, and this is also justified
732 * by considering the behavior of a buddy system containing a single
733 * large block of memory acted on by a series of small allocations.
734 * This behavior is a critical factor in sglist merging's success.
736 * -- wli
738 static inline void expand(struct zone *zone, struct page *page,
739 int low, int high, struct free_area *area,
740 int migratetype)
742 unsigned long size = 1 << high;
744 while (high > low) {
745 area--;
746 high--;
747 size >>= 1;
748 VM_BUG_ON(bad_range(zone, &page[size]));
749 list_add(&page[size].lru, &area->free_list[migratetype]);
750 area->nr_free++;
751 set_page_order(&page[size], high);
756 * This page is about to be returned from the page allocator
758 static inline int check_new_page(struct page *page)
760 if (unlikely(page_mapcount(page) |
761 (page->mapping != NULL) |
762 (atomic_read(&page->_count) != 0) |
763 (page->flags & PAGE_FLAGS_CHECK_AT_PREP))) {
764 bad_page(page);
765 return 1;
767 return 0;
770 static int prep_new_page(struct page *page, int order, gfp_t gfp_flags)
772 int i;
774 for (i = 0; i < (1 << order); i++) {
775 struct page *p = page + i;
776 if (unlikely(check_new_page(p)))
777 return 1;
780 set_page_private(page, 0);
781 set_page_refcounted(page);
783 arch_alloc_page(page, order);
784 kernel_map_pages(page, 1 << order, 1);
786 if (gfp_flags & __GFP_ZERO)
787 prep_zero_page(page, order, gfp_flags);
789 if (order && (gfp_flags & __GFP_COMP))
790 prep_compound_page(page, order);
792 return 0;
796 * Go through the free lists for the given migratetype and remove
797 * the smallest available page from the freelists
799 static inline
800 struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
801 int migratetype)
803 unsigned int current_order;
804 struct free_area * area;
805 struct page *page;
807 /* Find a page of the appropriate size in the preferred list */
808 for (current_order = order; current_order < MAX_ORDER; ++current_order) {
809 area = &(zone->free_area[current_order]);
810 if (list_empty(&area->free_list[migratetype]))
811 continue;
813 page = list_entry(area->free_list[migratetype].next,
814 struct page, lru);
815 list_del(&page->lru);
816 rmv_page_order(page);
817 area->nr_free--;
818 expand(zone, page, order, current_order, area, migratetype);
819 return page;
822 return NULL;
827 * This array describes the order lists are fallen back to when
828 * the free lists for the desirable migrate type are depleted
830 static int fallbacks[MIGRATE_TYPES][MIGRATE_TYPES-1] = {
831 [MIGRATE_UNMOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE, MIGRATE_RESERVE },
832 [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE, MIGRATE_MOVABLE, MIGRATE_RESERVE },
833 [MIGRATE_MOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_RESERVE },
834 [MIGRATE_RESERVE] = { MIGRATE_RESERVE, MIGRATE_RESERVE, MIGRATE_RESERVE }, /* Never used */
838 * Move the free pages in a range to the free lists of the requested type.
839 * Note that start_page and end_pages are not aligned on a pageblock
840 * boundary. If alignment is required, use move_freepages_block()
842 static int move_freepages(struct zone *zone,
843 struct page *start_page, struct page *end_page,
844 int migratetype)
846 struct page *page;
847 unsigned long order;
848 int pages_moved = 0;
850 #ifndef CONFIG_HOLES_IN_ZONE
852 * page_zone is not safe to call in this context when
853 * CONFIG_HOLES_IN_ZONE is set. This bug check is probably redundant
854 * anyway as we check zone boundaries in move_freepages_block().
855 * Remove at a later date when no bug reports exist related to
856 * grouping pages by mobility
858 BUG_ON(page_zone(start_page) != page_zone(end_page));
859 #endif
861 for (page = start_page; page <= end_page;) {
862 /* Make sure we are not inadvertently changing nodes */
863 VM_BUG_ON(page_to_nid(page) != zone_to_nid(zone));
865 if (!pfn_valid_within(page_to_pfn(page))) {
866 page++;
867 continue;
870 if (!PageBuddy(page)) {
871 page++;
872 continue;
875 order = page_order(page);
876 list_del(&page->lru);
877 list_add(&page->lru,
878 &zone->free_area[order].free_list[migratetype]);
879 page += 1 << order;
880 pages_moved += 1 << order;
883 return pages_moved;
886 static int move_freepages_block(struct zone *zone, struct page *page,
887 int migratetype)
889 unsigned long start_pfn, end_pfn;
890 struct page *start_page, *end_page;
892 start_pfn = page_to_pfn(page);
893 start_pfn = start_pfn & ~(pageblock_nr_pages-1);
894 start_page = pfn_to_page(start_pfn);
895 end_page = start_page + pageblock_nr_pages - 1;
896 end_pfn = start_pfn + pageblock_nr_pages - 1;
898 /* Do not cross zone boundaries */
899 if (start_pfn < zone->zone_start_pfn)
900 start_page = page;
901 if (end_pfn >= zone->zone_start_pfn + zone->spanned_pages)
902 return 0;
904 return move_freepages(zone, start_page, end_page, migratetype);
907 static void change_pageblock_range(struct page *pageblock_page,
908 int start_order, int migratetype)
910 int nr_pageblocks = 1 << (start_order - pageblock_order);
912 while (nr_pageblocks--) {
913 set_pageblock_migratetype(pageblock_page, migratetype);
914 pageblock_page += pageblock_nr_pages;
918 /* Remove an element from the buddy allocator from the fallback list */
919 static inline struct page *
920 __rmqueue_fallback(struct zone *zone, int order, int start_migratetype)
922 struct free_area * area;
923 int current_order;
924 struct page *page;
925 int migratetype, i;
927 /* Find the largest possible block of pages in the other list */
928 for (current_order = MAX_ORDER-1; current_order >= order;
929 --current_order) {
930 for (i = 0; i < MIGRATE_TYPES - 1; i++) {
931 migratetype = fallbacks[start_migratetype][i];
933 /* MIGRATE_RESERVE handled later if necessary */
934 if (migratetype == MIGRATE_RESERVE)
935 continue;
937 area = &(zone->free_area[current_order]);
938 if (list_empty(&area->free_list[migratetype]))
939 continue;
941 page = list_entry(area->free_list[migratetype].next,
942 struct page, lru);
943 area->nr_free--;
946 * If breaking a large block of pages, move all free
947 * pages to the preferred allocation list. If falling
948 * back for a reclaimable kernel allocation, be more
949 * agressive about taking ownership of free pages
951 if (unlikely(current_order >= (pageblock_order >> 1)) ||
952 start_migratetype == MIGRATE_RECLAIMABLE ||
953 page_group_by_mobility_disabled) {
954 unsigned long pages;
955 pages = move_freepages_block(zone, page,
956 start_migratetype);
958 /* Claim the whole block if over half of it is free */
959 if (pages >= (1 << (pageblock_order-1)) ||
960 page_group_by_mobility_disabled)
961 set_pageblock_migratetype(page,
962 start_migratetype);
964 migratetype = start_migratetype;
967 /* Remove the page from the freelists */
968 list_del(&page->lru);
969 rmv_page_order(page);
971 /* Take ownership for orders >= pageblock_order */
972 if (current_order >= pageblock_order)
973 change_pageblock_range(page, current_order,
974 start_migratetype);
976 expand(zone, page, order, current_order, area, migratetype);
978 trace_mm_page_alloc_extfrag(page, order, current_order,
979 start_migratetype, migratetype);
981 return page;
985 return NULL;
989 * Do the hard work of removing an element from the buddy allocator.
990 * Call me with the zone->lock already held.
992 static struct page *__rmqueue(struct zone *zone, unsigned int order,
993 int migratetype)
995 struct page *page;
997 retry_reserve:
998 page = __rmqueue_smallest(zone, order, migratetype);
1000 if (unlikely(!page) && migratetype != MIGRATE_RESERVE) {
1001 page = __rmqueue_fallback(zone, order, migratetype);
1004 * Use MIGRATE_RESERVE rather than fail an allocation. goto
1005 * is used because __rmqueue_smallest is an inline function
1006 * and we want just one call site
1008 if (!page) {
1009 migratetype = MIGRATE_RESERVE;
1010 goto retry_reserve;
1014 trace_mm_page_alloc_zone_locked(page, order, migratetype);
1015 return page;
1019 * Obtain a specified number of elements from the buddy allocator, all under
1020 * a single hold of the lock, for efficiency. Add them to the supplied list.
1021 * Returns the number of new pages which were placed at *list.
1023 static int rmqueue_bulk(struct zone *zone, unsigned int order,
1024 unsigned long count, struct list_head *list,
1025 int migratetype, int cold)
1027 int i;
1029 spin_lock(&zone->lock);
1030 for (i = 0; i < count; ++i) {
1031 struct page *page = __rmqueue(zone, order, migratetype);
1032 if (unlikely(page == NULL))
1033 break;
1036 * Split buddy pages returned by expand() are received here
1037 * in physical page order. The page is added to the callers and
1038 * list and the list head then moves forward. From the callers
1039 * perspective, the linked list is ordered by page number in
1040 * some conditions. This is useful for IO devices that can
1041 * merge IO requests if the physical pages are ordered
1042 * properly.
1044 if (likely(cold == 0))
1045 list_add(&page->lru, list);
1046 else
1047 list_add_tail(&page->lru, list);
1048 set_page_private(page, migratetype);
1049 list = &page->lru;
1051 __mod_zone_page_state(zone, NR_FREE_PAGES, -(i << order));
1052 spin_unlock(&zone->lock);
1053 return i;
1056 #ifdef CONFIG_NUMA
1058 * Called from the vmstat counter updater to drain pagesets of this
1059 * currently executing processor on remote nodes after they have
1060 * expired.
1062 * Note that this function must be called with the thread pinned to
1063 * a single processor.
1065 void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp)
1067 unsigned long flags;
1068 int to_drain;
1070 local_irq_save(flags);
1071 if (pcp->count >= pcp->batch)
1072 to_drain = pcp->batch;
1073 else
1074 to_drain = pcp->count;
1075 free_pcppages_bulk(zone, to_drain, pcp);
1076 pcp->count -= to_drain;
1077 local_irq_restore(flags);
1079 #endif
1082 * Drain pages of the indicated processor.
1084 * The processor must either be the current processor and the
1085 * thread pinned to the current processor or a processor that
1086 * is not online.
1088 static void drain_pages(unsigned int cpu)
1090 unsigned long flags;
1091 struct zone *zone;
1093 for_each_populated_zone(zone) {
1094 struct per_cpu_pageset *pset;
1095 struct per_cpu_pages *pcp;
1097 local_irq_save(flags);
1098 pset = per_cpu_ptr(zone->pageset, cpu);
1100 pcp = &pset->pcp;
1101 free_pcppages_bulk(zone, pcp->count, pcp);
1102 pcp->count = 0;
1103 local_irq_restore(flags);
1108 * Spill all of this CPU's per-cpu pages back into the buddy allocator.
1110 void drain_local_pages(void *arg)
1112 drain_pages(smp_processor_id());
1116 * Spill all the per-cpu pages from all CPUs back into the buddy allocator
1118 void drain_all_pages(void)
1120 on_each_cpu(drain_local_pages, NULL, 1);
1123 #ifdef CONFIG_HIBERNATION
1125 void mark_free_pages(struct zone *zone)
1127 unsigned long pfn, max_zone_pfn;
1128 unsigned long flags;
1129 int order, t;
1130 struct list_head *curr;
1132 if (!zone->spanned_pages)
1133 return;
1135 spin_lock_irqsave(&zone->lock, flags);
1137 max_zone_pfn = zone->zone_start_pfn + zone->spanned_pages;
1138 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
1139 if (pfn_valid(pfn)) {
1140 struct page *page = pfn_to_page(pfn);
1142 if (!swsusp_page_is_forbidden(page))
1143 swsusp_unset_page_free(page);
1146 for_each_migratetype_order(order, t) {
1147 list_for_each(curr, &zone->free_area[order].free_list[t]) {
1148 unsigned long i;
1150 pfn = page_to_pfn(list_entry(curr, struct page, lru));
1151 for (i = 0; i < (1UL << order); i++)
1152 swsusp_set_page_free(pfn_to_page(pfn + i));
1155 spin_unlock_irqrestore(&zone->lock, flags);
1157 #endif /* CONFIG_PM */
1160 * Free a 0-order page
1161 * cold == 1 ? free a cold page : free a hot page
1163 void free_hot_cold_page(struct page *page, int cold)
1165 struct zone *zone = page_zone(page);
1166 struct per_cpu_pages *pcp;
1167 unsigned long flags;
1168 int migratetype;
1169 int wasMlocked = __TestClearPageMlocked(page);
1171 if (!free_pages_prepare(page, 0))
1172 return;
1174 migratetype = get_pageblock_migratetype(page);
1175 set_page_private(page, migratetype);
1176 local_irq_save(flags);
1177 if (unlikely(wasMlocked))
1178 free_page_mlock(page);
1179 __count_vm_event(PGFREE);
1182 * We only track unmovable, reclaimable and movable on pcp lists.
1183 * Free ISOLATE pages back to the allocator because they are being
1184 * offlined but treat RESERVE as movable pages so we can get those
1185 * areas back if necessary. Otherwise, we may have to free
1186 * excessively into the page allocator
1188 if (migratetype >= MIGRATE_PCPTYPES) {
1189 if (unlikely(migratetype == MIGRATE_ISOLATE)) {
1190 free_one_page(zone, page, 0, migratetype);
1191 goto out;
1193 migratetype = MIGRATE_MOVABLE;
1196 pcp = &this_cpu_ptr(zone->pageset)->pcp;
1197 if (cold)
1198 list_add_tail(&page->lru, &pcp->lists[migratetype]);
1199 else
1200 list_add(&page->lru, &pcp->lists[migratetype]);
1201 pcp->count++;
1202 if (pcp->count >= pcp->high) {
1203 free_pcppages_bulk(zone, pcp->batch, pcp);
1204 pcp->count -= pcp->batch;
1207 out:
1208 local_irq_restore(flags);
1212 * split_page takes a non-compound higher-order page, and splits it into
1213 * n (1<<order) sub-pages: page[0..n]
1214 * Each sub-page must be freed individually.
1216 * Note: this is probably too low level an operation for use in drivers.
1217 * Please consult with lkml before using this in your driver.
1219 void split_page(struct page *page, unsigned int order)
1221 int i;
1223 VM_BUG_ON(PageCompound(page));
1224 VM_BUG_ON(!page_count(page));
1226 #ifdef CONFIG_KMEMCHECK
1228 * Split shadow pages too, because free(page[0]) would
1229 * otherwise free the whole shadow.
1231 if (kmemcheck_page_is_tracked(page))
1232 split_page(virt_to_page(page[0].shadow), order);
1233 #endif
1235 for (i = 1; i < (1 << order); i++)
1236 set_page_refcounted(page + i);
1240 * Similar to split_page except the page is already free. As this is only
1241 * being used for migration, the migratetype of the block also changes.
1242 * As this is called with interrupts disabled, the caller is responsible
1243 * for calling arch_alloc_page() and kernel_map_page() after interrupts
1244 * are enabled.
1246 * Note: this is probably too low level an operation for use in drivers.
1247 * Please consult with lkml before using this in your driver.
1249 int split_free_page(struct page *page)
1251 unsigned int order;
1252 unsigned long watermark;
1253 struct zone *zone;
1255 BUG_ON(!PageBuddy(page));
1257 zone = page_zone(page);
1258 order = page_order(page);
1260 /* Obey watermarks as if the page was being allocated */
1261 watermark = low_wmark_pages(zone) + (1 << order);
1262 if (!zone_watermark_ok(zone, 0, watermark, 0, 0))
1263 return 0;
1265 /* Remove page from free list */
1266 list_del(&page->lru);
1267 zone->free_area[order].nr_free--;
1268 rmv_page_order(page);
1269 __mod_zone_page_state(zone, NR_FREE_PAGES, -(1UL << order));
1271 /* Split into individual pages */
1272 set_page_refcounted(page);
1273 split_page(page, order);
1275 if (order >= pageblock_order - 1) {
1276 struct page *endpage = page + (1 << order) - 1;
1277 for (; page < endpage; page += pageblock_nr_pages)
1278 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
1281 return 1 << order;
1285 * Really, prep_compound_page() should be called from __rmqueue_bulk(). But
1286 * we cheat by calling it from here, in the order > 0 path. Saves a branch
1287 * or two.
1289 static inline
1290 struct page *buffered_rmqueue(struct zone *preferred_zone,
1291 struct zone *zone, int order, gfp_t gfp_flags,
1292 int migratetype)
1294 unsigned long flags;
1295 struct page *page;
1296 int cold = !!(gfp_flags & __GFP_COLD);
1298 again:
1299 if (likely(order == 0)) {
1300 struct per_cpu_pages *pcp;
1301 struct list_head *list;
1303 local_irq_save(flags);
1304 pcp = &this_cpu_ptr(zone->pageset)->pcp;
1305 list = &pcp->lists[migratetype];
1306 if (list_empty(list)) {
1307 pcp->count += rmqueue_bulk(zone, 0,
1308 pcp->batch, list,
1309 migratetype, cold);
1310 if (unlikely(list_empty(list)))
1311 goto failed;
1314 if (cold)
1315 page = list_entry(list->prev, struct page, lru);
1316 else
1317 page = list_entry(list->next, struct page, lru);
1319 list_del(&page->lru);
1320 pcp->count--;
1321 } else {
1322 if (unlikely(gfp_flags & __GFP_NOFAIL)) {
1324 * __GFP_NOFAIL is not to be used in new code.
1326 * All __GFP_NOFAIL callers should be fixed so that they
1327 * properly detect and handle allocation failures.
1329 * We most definitely don't want callers attempting to
1330 * allocate greater than order-1 page units with
1331 * __GFP_NOFAIL.
1333 WARN_ON_ONCE(order > 1);
1335 spin_lock_irqsave(&zone->lock, flags);
1336 page = __rmqueue(zone, order, migratetype);
1337 spin_unlock(&zone->lock);
1338 if (!page)
1339 goto failed;
1340 __mod_zone_page_state(zone, NR_FREE_PAGES, -(1 << order));
1343 __count_zone_vm_events(PGALLOC, zone, 1 << order);
1344 zone_statistics(preferred_zone, zone);
1345 local_irq_restore(flags);
1347 VM_BUG_ON(bad_range(zone, page));
1348 if (prep_new_page(page, order, gfp_flags))
1349 goto again;
1350 return page;
1352 failed:
1353 local_irq_restore(flags);
1354 return NULL;
1357 /* The ALLOC_WMARK bits are used as an index to zone->watermark */
1358 #define ALLOC_WMARK_MIN WMARK_MIN
1359 #define ALLOC_WMARK_LOW WMARK_LOW
1360 #define ALLOC_WMARK_HIGH WMARK_HIGH
1361 #define ALLOC_NO_WATERMARKS 0x04 /* don't check watermarks at all */
1363 /* Mask to get the watermark bits */
1364 #define ALLOC_WMARK_MASK (ALLOC_NO_WATERMARKS-1)
1366 #define ALLOC_HARDER 0x10 /* try to alloc harder */
1367 #define ALLOC_HIGH 0x20 /* __GFP_HIGH set */
1368 #define ALLOC_CPUSET 0x40 /* check for correct cpuset */
1370 #ifdef CONFIG_FAIL_PAGE_ALLOC
1372 static struct fail_page_alloc_attr {
1373 struct fault_attr attr;
1375 u32 ignore_gfp_highmem;
1376 u32 ignore_gfp_wait;
1377 u32 min_order;
1379 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
1381 struct dentry *ignore_gfp_highmem_file;
1382 struct dentry *ignore_gfp_wait_file;
1383 struct dentry *min_order_file;
1385 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
1387 } fail_page_alloc = {
1388 .attr = FAULT_ATTR_INITIALIZER,
1389 .ignore_gfp_wait = 1,
1390 .ignore_gfp_highmem = 1,
1391 .min_order = 1,
1394 static int __init setup_fail_page_alloc(char *str)
1396 return setup_fault_attr(&fail_page_alloc.attr, str);
1398 __setup("fail_page_alloc=", setup_fail_page_alloc);
1400 static int should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
1402 if (order < fail_page_alloc.min_order)
1403 return 0;
1404 if (gfp_mask & __GFP_NOFAIL)
1405 return 0;
1406 if (fail_page_alloc.ignore_gfp_highmem && (gfp_mask & __GFP_HIGHMEM))
1407 return 0;
1408 if (fail_page_alloc.ignore_gfp_wait && (gfp_mask & __GFP_WAIT))
1409 return 0;
1411 return should_fail(&fail_page_alloc.attr, 1 << order);
1414 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
1416 static int __init fail_page_alloc_debugfs(void)
1418 mode_t mode = S_IFREG | S_IRUSR | S_IWUSR;
1419 struct dentry *dir;
1420 int err;
1422 err = init_fault_attr_dentries(&fail_page_alloc.attr,
1423 "fail_page_alloc");
1424 if (err)
1425 return err;
1426 dir = fail_page_alloc.attr.dentries.dir;
1428 fail_page_alloc.ignore_gfp_wait_file =
1429 debugfs_create_bool("ignore-gfp-wait", mode, dir,
1430 &fail_page_alloc.ignore_gfp_wait);
1432 fail_page_alloc.ignore_gfp_highmem_file =
1433 debugfs_create_bool("ignore-gfp-highmem", mode, dir,
1434 &fail_page_alloc.ignore_gfp_highmem);
1435 fail_page_alloc.min_order_file =
1436 debugfs_create_u32("min-order", mode, dir,
1437 &fail_page_alloc.min_order);
1439 if (!fail_page_alloc.ignore_gfp_wait_file ||
1440 !fail_page_alloc.ignore_gfp_highmem_file ||
1441 !fail_page_alloc.min_order_file) {
1442 err = -ENOMEM;
1443 debugfs_remove(fail_page_alloc.ignore_gfp_wait_file);
1444 debugfs_remove(fail_page_alloc.ignore_gfp_highmem_file);
1445 debugfs_remove(fail_page_alloc.min_order_file);
1446 cleanup_fault_attr_dentries(&fail_page_alloc.attr);
1449 return err;
1452 late_initcall(fail_page_alloc_debugfs);
1454 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
1456 #else /* CONFIG_FAIL_PAGE_ALLOC */
1458 static inline int should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
1460 return 0;
1463 #endif /* CONFIG_FAIL_PAGE_ALLOC */
1466 * Return true if free pages are above 'mark'. This takes into account the order
1467 * of the allocation.
1469 static bool __zone_watermark_ok(struct zone *z, int order, unsigned long mark,
1470 int classzone_idx, int alloc_flags, long free_pages)
1472 /* free_pages my go negative - that's OK */
1473 long min = mark;
1474 int o;
1476 free_pages -= (1 << order) + 1;
1477 if (alloc_flags & ALLOC_HIGH)
1478 min -= min / 2;
1479 if (alloc_flags & ALLOC_HARDER)
1480 min -= min / 4;
1482 if (free_pages <= min + z->lowmem_reserve[classzone_idx])
1483 return false;
1484 for (o = 0; o < order; o++) {
1485 /* At the next order, this order's pages become unavailable */
1486 free_pages -= z->free_area[o].nr_free << o;
1488 /* Require fewer higher order pages to be free */
1489 min >>= 1;
1491 if (free_pages <= min)
1492 return false;
1494 return true;
1497 bool zone_watermark_ok(struct zone *z, int order, unsigned long mark,
1498 int classzone_idx, int alloc_flags)
1500 return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
1501 zone_page_state(z, NR_FREE_PAGES));
1504 bool zone_watermark_ok_safe(struct zone *z, int order, unsigned long mark,
1505 int classzone_idx, int alloc_flags)
1507 long free_pages = zone_page_state(z, NR_FREE_PAGES);
1509 if (z->percpu_drift_mark && free_pages < z->percpu_drift_mark)
1510 free_pages = zone_page_state_snapshot(z, NR_FREE_PAGES);
1512 return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
1513 free_pages);
1516 #ifdef CONFIG_NUMA
1518 * zlc_setup - Setup for "zonelist cache". Uses cached zone data to
1519 * skip over zones that are not allowed by the cpuset, or that have
1520 * been recently (in last second) found to be nearly full. See further
1521 * comments in mmzone.h. Reduces cache footprint of zonelist scans
1522 * that have to skip over a lot of full or unallowed zones.
1524 * If the zonelist cache is present in the passed in zonelist, then
1525 * returns a pointer to the allowed node mask (either the current
1526 * tasks mems_allowed, or node_states[N_HIGH_MEMORY].)
1528 * If the zonelist cache is not available for this zonelist, does
1529 * nothing and returns NULL.
1531 * If the fullzones BITMAP in the zonelist cache is stale (more than
1532 * a second since last zap'd) then we zap it out (clear its bits.)
1534 * We hold off even calling zlc_setup, until after we've checked the
1535 * first zone in the zonelist, on the theory that most allocations will
1536 * be satisfied from that first zone, so best to examine that zone as
1537 * quickly as we can.
1539 static nodemask_t *zlc_setup(struct zonelist *zonelist, int alloc_flags)
1541 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1542 nodemask_t *allowednodes; /* zonelist_cache approximation */
1544 zlc = zonelist->zlcache_ptr;
1545 if (!zlc)
1546 return NULL;
1548 if (time_after(jiffies, zlc->last_full_zap + HZ)) {
1549 bitmap_zero(zlc->fullzones, MAX_ZONES_PER_ZONELIST);
1550 zlc->last_full_zap = jiffies;
1553 allowednodes = !in_interrupt() && (alloc_flags & ALLOC_CPUSET) ?
1554 &cpuset_current_mems_allowed :
1555 &node_states[N_HIGH_MEMORY];
1556 return allowednodes;
1560 * Given 'z' scanning a zonelist, run a couple of quick checks to see
1561 * if it is worth looking at further for free memory:
1562 * 1) Check that the zone isn't thought to be full (doesn't have its
1563 * bit set in the zonelist_cache fullzones BITMAP).
1564 * 2) Check that the zones node (obtained from the zonelist_cache
1565 * z_to_n[] mapping) is allowed in the passed in allowednodes mask.
1566 * Return true (non-zero) if zone is worth looking at further, or
1567 * else return false (zero) if it is not.
1569 * This check -ignores- the distinction between various watermarks,
1570 * such as GFP_HIGH, GFP_ATOMIC, PF_MEMALLOC, ... If a zone is
1571 * found to be full for any variation of these watermarks, it will
1572 * be considered full for up to one second by all requests, unless
1573 * we are so low on memory on all allowed nodes that we are forced
1574 * into the second scan of the zonelist.
1576 * In the second scan we ignore this zonelist cache and exactly
1577 * apply the watermarks to all zones, even it is slower to do so.
1578 * We are low on memory in the second scan, and should leave no stone
1579 * unturned looking for a free page.
1581 static int zlc_zone_worth_trying(struct zonelist *zonelist, struct zoneref *z,
1582 nodemask_t *allowednodes)
1584 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1585 int i; /* index of *z in zonelist zones */
1586 int n; /* node that zone *z is on */
1588 zlc = zonelist->zlcache_ptr;
1589 if (!zlc)
1590 return 1;
1592 i = z - zonelist->_zonerefs;
1593 n = zlc->z_to_n[i];
1595 /* This zone is worth trying if it is allowed but not full */
1596 return node_isset(n, *allowednodes) && !test_bit(i, zlc->fullzones);
1600 * Given 'z' scanning a zonelist, set the corresponding bit in
1601 * zlc->fullzones, so that subsequent attempts to allocate a page
1602 * from that zone don't waste time re-examining it.
1604 static void zlc_mark_zone_full(struct zonelist *zonelist, struct zoneref *z)
1606 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1607 int i; /* index of *z in zonelist zones */
1609 zlc = zonelist->zlcache_ptr;
1610 if (!zlc)
1611 return;
1613 i = z - zonelist->_zonerefs;
1615 set_bit(i, zlc->fullzones);
1618 #else /* CONFIG_NUMA */
1620 static nodemask_t *zlc_setup(struct zonelist *zonelist, int alloc_flags)
1622 return NULL;
1625 static int zlc_zone_worth_trying(struct zonelist *zonelist, struct zoneref *z,
1626 nodemask_t *allowednodes)
1628 return 1;
1631 static void zlc_mark_zone_full(struct zonelist *zonelist, struct zoneref *z)
1634 #endif /* CONFIG_NUMA */
1637 * get_page_from_freelist goes through the zonelist trying to allocate
1638 * a page.
1640 static struct page * BCMFASTPATH_HOST
1641 get_page_from_freelist(gfp_t gfp_mask, nodemask_t *nodemask, unsigned int order,
1642 struct zonelist *zonelist, int high_zoneidx, int alloc_flags,
1643 struct zone *preferred_zone, int migratetype)
1645 struct zoneref *z;
1646 struct page *page = NULL;
1647 int classzone_idx;
1648 struct zone *zone;
1649 nodemask_t *allowednodes = NULL;/* zonelist_cache approximation */
1650 int zlc_active = 0; /* set if using zonelist_cache */
1651 int did_zlc_setup = 0; /* just call zlc_setup() one time */
1653 classzone_idx = zone_idx(preferred_zone);
1654 zonelist_scan:
1656 * Scan zonelist, looking for a zone with enough free.
1657 * See also cpuset_zone_allowed() comment in kernel/cpuset.c.
1659 for_each_zone_zonelist_nodemask(zone, z, zonelist,
1660 high_zoneidx, nodemask) {
1661 if (NUMA_BUILD && zlc_active &&
1662 !zlc_zone_worth_trying(zonelist, z, allowednodes))
1663 continue;
1664 if ((alloc_flags & ALLOC_CPUSET) &&
1665 !cpuset_zone_allowed_softwall(zone, gfp_mask))
1666 goto try_next_zone;
1668 BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK);
1669 if (!(alloc_flags & ALLOC_NO_WATERMARKS)) {
1670 unsigned long mark;
1671 int ret;
1673 mark = zone->watermark[alloc_flags & ALLOC_WMARK_MASK];
1674 if (zone_watermark_ok(zone, order, mark,
1675 classzone_idx, alloc_flags))
1676 goto try_this_zone;
1678 if (zone_reclaim_mode == 0)
1679 goto this_zone_full;
1681 ret = zone_reclaim(zone, gfp_mask, order);
1682 switch (ret) {
1683 case ZONE_RECLAIM_NOSCAN:
1684 /* did not scan */
1685 goto try_next_zone;
1686 case ZONE_RECLAIM_FULL:
1687 /* scanned but unreclaimable */
1688 goto this_zone_full;
1689 default:
1690 /* did we reclaim enough */
1691 if (!zone_watermark_ok(zone, order, mark,
1692 classzone_idx, alloc_flags))
1693 goto this_zone_full;
1697 try_this_zone:
1698 page = buffered_rmqueue(preferred_zone, zone, order,
1699 gfp_mask, migratetype);
1700 if (page)
1701 break;
1702 this_zone_full:
1703 if (NUMA_BUILD)
1704 zlc_mark_zone_full(zonelist, z);
1705 try_next_zone:
1706 if (NUMA_BUILD && !did_zlc_setup && nr_online_nodes > 1) {
1708 * we do zlc_setup after the first zone is tried but only
1709 * if there are multiple nodes make it worthwhile
1711 allowednodes = zlc_setup(zonelist, alloc_flags);
1712 zlc_active = 1;
1713 did_zlc_setup = 1;
1717 if (unlikely(NUMA_BUILD && page == NULL && zlc_active)) {
1718 /* Disable zlc cache for second zonelist scan */
1719 zlc_active = 0;
1720 goto zonelist_scan;
1722 return page;
1725 static inline int
1726 should_alloc_retry(gfp_t gfp_mask, unsigned int order,
1727 unsigned long pages_reclaimed)
1729 /* Do not loop if specifically requested */
1730 if (gfp_mask & __GFP_NORETRY)
1731 return 0;
1734 * In this implementation, order <= PAGE_ALLOC_COSTLY_ORDER
1735 * means __GFP_NOFAIL, but that may not be true in other
1736 * implementations.
1738 if (order <= PAGE_ALLOC_COSTLY_ORDER)
1739 return 1;
1742 * For order > PAGE_ALLOC_COSTLY_ORDER, if __GFP_REPEAT is
1743 * specified, then we retry until we no longer reclaim any pages
1744 * (above), or we've reclaimed an order of pages at least as
1745 * large as the allocation's order. In both cases, if the
1746 * allocation still fails, we stop retrying.
1748 if (gfp_mask & __GFP_REPEAT && pages_reclaimed < (1 << order))
1749 return 1;
1752 * Don't let big-order allocations loop unless the caller
1753 * explicitly requests that.
1755 if (gfp_mask & __GFP_NOFAIL)
1756 return 1;
1758 return 0;
1761 static inline struct page *
1762 __alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order,
1763 struct zonelist *zonelist, enum zone_type high_zoneidx,
1764 nodemask_t *nodemask, struct zone *preferred_zone,
1765 int migratetype)
1767 struct page *page;
1769 /* Acquire the OOM killer lock for the zones in zonelist */
1770 if (!try_set_zonelist_oom(zonelist, gfp_mask)) {
1771 schedule_timeout_uninterruptible(1);
1772 return NULL;
1776 * Go through the zonelist yet one more time, keep very high watermark
1777 * here, this is only to catch a parallel oom killing, we must fail if
1778 * we're still under heavy pressure.
1780 page = get_page_from_freelist(gfp_mask|__GFP_HARDWALL, nodemask,
1781 order, zonelist, high_zoneidx,
1782 ALLOC_WMARK_HIGH|ALLOC_CPUSET,
1783 preferred_zone, migratetype);
1784 if (page)
1785 goto out;
1787 if (!(gfp_mask & __GFP_NOFAIL)) {
1788 /* The OOM killer will not help higher order allocs */
1789 if (order > PAGE_ALLOC_COSTLY_ORDER)
1790 goto out;
1791 /* The OOM killer does not needlessly kill tasks for lowmem */
1792 if (high_zoneidx < ZONE_NORMAL)
1793 goto out;
1795 * GFP_THISNODE contains __GFP_NORETRY and we never hit this.
1796 * Sanity check for bare calls of __GFP_THISNODE, not real OOM.
1797 * The caller should handle page allocation failure by itself if
1798 * it specifies __GFP_THISNODE.
1799 * Note: Hugepage uses it but will hit PAGE_ALLOC_COSTLY_ORDER.
1801 if (gfp_mask & __GFP_THISNODE)
1802 goto out;
1804 /* Exhausted what can be done so it's blamo time */
1805 out_of_memory(zonelist, gfp_mask, order, nodemask);
1807 out:
1808 clear_zonelist_oom(zonelist, gfp_mask);
1809 return page;
1812 #ifdef CONFIG_COMPACTION
1813 /* Try memory compaction for high-order allocations before reclaim */
1814 static struct page *
1815 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
1816 struct zonelist *zonelist, enum zone_type high_zoneidx,
1817 nodemask_t *nodemask, int alloc_flags, struct zone *preferred_zone,
1818 int migratetype, unsigned long *did_some_progress)
1820 struct page *page;
1822 if (!order || compaction_deferred(preferred_zone))
1823 return NULL;
1825 *did_some_progress = try_to_compact_pages(zonelist, order, gfp_mask,
1826 nodemask);
1827 if (*did_some_progress != COMPACT_SKIPPED) {
1829 /* Page migration frees to the PCP lists but we want merging */
1830 drain_pages(get_cpu());
1831 put_cpu();
1833 page = get_page_from_freelist(gfp_mask, nodemask,
1834 order, zonelist, high_zoneidx,
1835 alloc_flags, preferred_zone,
1836 migratetype);
1837 if (page) {
1838 preferred_zone->compact_considered = 0;
1839 preferred_zone->compact_defer_shift = 0;
1840 count_vm_event(COMPACTSUCCESS);
1841 return page;
1845 * It's bad if compaction run occurs and fails.
1846 * The most likely reason is that pages exist,
1847 * but not enough to satisfy watermarks.
1849 count_vm_event(COMPACTFAIL);
1850 defer_compaction(preferred_zone);
1852 cond_resched();
1855 return NULL;
1857 #else
1858 static inline struct page *
1859 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
1860 struct zonelist *zonelist, enum zone_type high_zoneidx,
1861 nodemask_t *nodemask, int alloc_flags, struct zone *preferred_zone,
1862 int migratetype, unsigned long *did_some_progress)
1864 return NULL;
1866 #endif /* CONFIG_COMPACTION */
1868 /* The really slow allocator path where we enter direct reclaim */
1869 static inline struct page *
1870 __alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order,
1871 struct zonelist *zonelist, enum zone_type high_zoneidx,
1872 nodemask_t *nodemask, int alloc_flags, struct zone *preferred_zone,
1873 int migratetype, unsigned long *did_some_progress)
1875 struct page *page = NULL;
1876 struct reclaim_state reclaim_state;
1877 struct task_struct *p = current;
1878 bool drained = false;
1880 cond_resched();
1882 /* We now go into synchronous reclaim */
1883 cpuset_memory_pressure_bump();
1884 p->flags |= PF_MEMALLOC;
1885 lockdep_set_current_reclaim_state(gfp_mask);
1886 reclaim_state.reclaimed_slab = 0;
1887 p->reclaim_state = &reclaim_state;
1889 *did_some_progress = try_to_free_pages(zonelist, order, gfp_mask, nodemask);
1891 p->reclaim_state = NULL;
1892 lockdep_clear_current_reclaim_state();
1893 p->flags &= ~PF_MEMALLOC;
1895 cond_resched();
1897 if (unlikely(!(*did_some_progress)))
1898 return NULL;
1900 retry:
1901 page = get_page_from_freelist(gfp_mask, nodemask, order,
1902 zonelist, high_zoneidx,
1903 alloc_flags, preferred_zone,
1904 migratetype);
1907 * If an allocation failed after direct reclaim, it could be because
1908 * pages are pinned on the per-cpu lists. Drain them and try again
1910 if (!page && !drained) {
1911 drain_all_pages();
1912 drained = true;
1913 goto retry;
1916 return page;
1920 * This is called in the allocator slow-path if the allocation request is of
1921 * sufficient urgency to ignore watermarks and take other desperate measures
1923 static inline struct page *
1924 __alloc_pages_high_priority(gfp_t gfp_mask, unsigned int order,
1925 struct zonelist *zonelist, enum zone_type high_zoneidx,
1926 nodemask_t *nodemask, struct zone *preferred_zone,
1927 int migratetype)
1929 struct page *page;
1931 do {
1932 page = get_page_from_freelist(gfp_mask, nodemask, order,
1933 zonelist, high_zoneidx, ALLOC_NO_WATERMARKS,
1934 preferred_zone, migratetype);
1936 if (!page && gfp_mask & __GFP_NOFAIL)
1937 congestion_wait(BLK_RW_ASYNC, HZ/50);
1938 } while (!page && (gfp_mask & __GFP_NOFAIL));
1940 return page;
1943 static inline
1944 void wake_all_kswapd(unsigned int order, struct zonelist *zonelist,
1945 enum zone_type high_zoneidx)
1947 struct zoneref *z;
1948 struct zone *zone;
1950 for_each_zone_zonelist(zone, z, zonelist, high_zoneidx)
1951 wakeup_kswapd(zone, order);
1954 static inline int
1955 gfp_to_alloc_flags(gfp_t gfp_mask)
1957 struct task_struct *p = current;
1958 int alloc_flags = ALLOC_WMARK_MIN | ALLOC_CPUSET;
1959 const gfp_t wait = gfp_mask & __GFP_WAIT;
1961 /* __GFP_HIGH is assumed to be the same as ALLOC_HIGH to save a branch. */
1962 BUILD_BUG_ON(__GFP_HIGH != ALLOC_HIGH);
1965 * The caller may dip into page reserves a bit more if the caller
1966 * cannot run direct reclaim, or if the caller has realtime scheduling
1967 * policy or is asking for __GFP_HIGH memory. GFP_ATOMIC requests will
1968 * set both ALLOC_HARDER (!wait) and ALLOC_HIGH (__GFP_HIGH).
1970 alloc_flags |= (gfp_mask & __GFP_HIGH);
1972 if (!wait) {
1973 alloc_flags |= ALLOC_HARDER;
1975 * Ignore cpuset if GFP_ATOMIC (!wait) rather than fail alloc.
1976 * See also cpuset_zone_allowed() comment in kernel/cpuset.c.
1978 alloc_flags &= ~ALLOC_CPUSET;
1979 } else if (unlikely(rt_task(p)) && !in_interrupt())
1980 alloc_flags |= ALLOC_HARDER;
1982 if (likely(!(gfp_mask & __GFP_NOMEMALLOC))) {
1983 if (!in_interrupt() &&
1984 ((p->flags & PF_MEMALLOC) ||
1985 unlikely(test_thread_flag(TIF_MEMDIE))))
1986 alloc_flags |= ALLOC_NO_WATERMARKS;
1989 return alloc_flags;
1992 static inline struct page *
1993 __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order,
1994 struct zonelist *zonelist, enum zone_type high_zoneidx,
1995 nodemask_t *nodemask, struct zone *preferred_zone,
1996 int migratetype)
1998 const gfp_t wait = gfp_mask & __GFP_WAIT;
1999 struct page *page = NULL;
2000 int alloc_flags;
2001 unsigned long pages_reclaimed = 0;
2002 unsigned long did_some_progress;
2003 struct task_struct *p = current;
2006 * In the slowpath, we sanity check order to avoid ever trying to
2007 * reclaim >= MAX_ORDER areas which will never succeed. Callers may
2008 * be using allocators in order of preference for an area that is
2009 * too large.
2011 if (order >= MAX_ORDER) {
2012 WARN_ON_ONCE(!(gfp_mask & __GFP_NOWARN));
2013 return NULL;
2017 * GFP_THISNODE (meaning __GFP_THISNODE, __GFP_NORETRY and
2018 * __GFP_NOWARN set) should not cause reclaim since the subsystem
2019 * (f.e. slab) using GFP_THISNODE may choose to trigger reclaim
2020 * using a larger set of nodes after it has established that the
2021 * allowed per node queues are empty and that nodes are
2022 * over allocated.
2024 if (NUMA_BUILD && (gfp_mask & GFP_THISNODE) == GFP_THISNODE)
2025 goto nopage;
2027 restart:
2028 wake_all_kswapd(order, zonelist, high_zoneidx);
2031 * OK, we're below the kswapd watermark and have kicked background
2032 * reclaim. Now things get more complex, so set up alloc_flags according
2033 * to how we want to proceed.
2035 alloc_flags = gfp_to_alloc_flags(gfp_mask);
2037 /* This is the last chance, in general, before the goto nopage. */
2038 page = get_page_from_freelist(gfp_mask, nodemask, order, zonelist,
2039 high_zoneidx, alloc_flags & ~ALLOC_NO_WATERMARKS,
2040 preferred_zone, migratetype);
2041 if (page)
2042 goto got_pg;
2044 rebalance:
2045 /* Allocate without watermarks if the context allows */
2046 if (alloc_flags & ALLOC_NO_WATERMARKS) {
2047 page = __alloc_pages_high_priority(gfp_mask, order,
2048 zonelist, high_zoneidx, nodemask,
2049 preferred_zone, migratetype);
2050 if (page)
2051 goto got_pg;
2054 /* Atomic allocations - we can't balance anything */
2055 if (!wait)
2056 goto nopage;
2058 /* Avoid recursion of direct reclaim */
2059 if (p->flags & PF_MEMALLOC)
2060 goto nopage;
2062 /* Avoid allocations with no watermarks from looping endlessly */
2063 if (test_thread_flag(TIF_MEMDIE) && !(gfp_mask & __GFP_NOFAIL))
2064 goto nopage;
2066 /* Try direct compaction */
2067 page = __alloc_pages_direct_compact(gfp_mask, order,
2068 zonelist, high_zoneidx,
2069 nodemask,
2070 alloc_flags, preferred_zone,
2071 migratetype, &did_some_progress);
2072 if (page)
2073 goto got_pg;
2075 /* Try direct reclaim and then allocating */
2076 page = __alloc_pages_direct_reclaim(gfp_mask, order,
2077 zonelist, high_zoneidx,
2078 nodemask,
2079 alloc_flags, preferred_zone,
2080 migratetype, &did_some_progress);
2081 if (page)
2082 goto got_pg;
2085 * If we failed to make any progress reclaiming, then we are
2086 * running out of options and have to consider going OOM
2088 if (!did_some_progress) {
2089 if ((gfp_mask & __GFP_FS) && !(gfp_mask & __GFP_NORETRY)) {
2090 if (oom_killer_disabled)
2091 goto nopage;
2092 page = __alloc_pages_may_oom(gfp_mask, order,
2093 zonelist, high_zoneidx,
2094 nodemask, preferred_zone,
2095 migratetype);
2096 if (page)
2097 goto got_pg;
2099 if (!(gfp_mask & __GFP_NOFAIL)) {
2101 * The oom killer is not called for high-order
2102 * allocations that may fail, so if no progress
2103 * is being made, there are no other options and
2104 * retrying is unlikely to help.
2106 if (order > PAGE_ALLOC_COSTLY_ORDER)
2107 goto nopage;
2109 * The oom killer is not called for lowmem
2110 * allocations to prevent needlessly killing
2111 * innocent tasks.
2113 if (high_zoneidx < ZONE_NORMAL)
2114 goto nopage;
2117 goto restart;
2121 /* Check if we should retry the allocation */
2122 pages_reclaimed += did_some_progress;
2123 if (should_alloc_retry(gfp_mask, order, pages_reclaimed)) {
2124 /* Wait for some write requests to complete then retry */
2125 congestion_wait(BLK_RW_ASYNC, HZ/50);
2126 goto rebalance;
2129 nopage:
2130 if (!(gfp_mask & __GFP_NOWARN) && printk_ratelimit()) {
2131 printk(KERN_WARNING "%s: page allocation failure."
2132 " order:%d, mode:0x%x\n",
2133 p->comm, order, gfp_mask);
2134 dump_stack();
2135 show_mem();
2137 return page;
2138 got_pg:
2139 if (kmemcheck_enabled)
2140 kmemcheck_pagealloc_alloc(page, order, gfp_mask);
2141 return page;
2146 * This is the 'heart' of the zoned buddy allocator.
2148 struct page *
2149 __alloc_pages_nodemask(gfp_t gfp_mask, unsigned int order,
2150 struct zonelist *zonelist, nodemask_t *nodemask)
2152 enum zone_type high_zoneidx = gfp_zone(gfp_mask);
2153 struct zone *preferred_zone;
2154 struct page *page;
2155 int migratetype = allocflags_to_migratetype(gfp_mask);
2157 gfp_mask &= gfp_allowed_mask;
2159 lockdep_trace_alloc(gfp_mask);
2161 might_sleep_if(gfp_mask & __GFP_WAIT);
2163 if (should_fail_alloc_page(gfp_mask, order))
2164 return NULL;
2167 * Check the zones suitable for the gfp_mask contain at least one
2168 * valid zone. It's possible to have an empty zonelist as a result
2169 * of GFP_THISNODE and a memoryless node
2171 if (unlikely(!zonelist->_zonerefs->zone))
2172 return NULL;
2174 get_mems_allowed();
2175 /* The preferred zone is used for statistics later */
2176 first_zones_zonelist(zonelist, high_zoneidx, nodemask, &preferred_zone);
2177 if (!preferred_zone) {
2178 put_mems_allowed();
2179 return NULL;
2182 /* First allocation attempt */
2183 page = get_page_from_freelist(gfp_mask|__GFP_HARDWALL, nodemask, order,
2184 zonelist, high_zoneidx, ALLOC_WMARK_LOW|ALLOC_CPUSET,
2185 preferred_zone, migratetype);
2186 if (unlikely(!page))
2187 page = __alloc_pages_slowpath(gfp_mask, order,
2188 zonelist, high_zoneidx, nodemask,
2189 preferred_zone, migratetype);
2190 put_mems_allowed();
2192 trace_mm_page_alloc(page, order, gfp_mask, migratetype);
2193 return page;
2195 EXPORT_SYMBOL(__alloc_pages_nodemask);
2198 * Common helper functions.
2200 unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order)
2202 struct page *page;
2205 * __get_free_pages() returns a 32-bit address, which cannot represent
2206 * a highmem page
2208 VM_BUG_ON((gfp_mask & __GFP_HIGHMEM) != 0);
2210 page = alloc_pages(gfp_mask, order);
2211 if (!page)
2212 return 0;
2213 return (unsigned long) page_address(page);
2215 EXPORT_SYMBOL(__get_free_pages);
2217 unsigned long get_zeroed_page(gfp_t gfp_mask)
2219 return __get_free_pages(gfp_mask | __GFP_ZERO, 0);
2221 EXPORT_SYMBOL(get_zeroed_page);
2223 void __pagevec_free(struct pagevec *pvec)
2225 int i = pagevec_count(pvec);
2227 while (--i >= 0) {
2228 trace_mm_pagevec_free(pvec->pages[i], pvec->cold);
2229 free_hot_cold_page(pvec->pages[i], pvec->cold);
2233 void __free_pages(struct page *page, unsigned int order)
2235 if (put_page_testzero(page)) {
2236 if (order == 0)
2237 free_hot_cold_page(page, 0);
2238 else
2239 __free_pages_ok(page, order);
2243 EXPORT_SYMBOL(__free_pages);
2245 void free_pages(unsigned long addr, unsigned int order)
2247 if (addr != 0) {
2248 VM_BUG_ON(!virt_addr_valid((void *)addr));
2249 __free_pages(virt_to_page((void *)addr), order);
2253 EXPORT_SYMBOL(free_pages);
2256 * alloc_pages_exact - allocate an exact number physically-contiguous pages.
2257 * @size: the number of bytes to allocate
2258 * @gfp_mask: GFP flags for the allocation
2260 * This function is similar to alloc_pages(), except that it allocates the
2261 * minimum number of pages to satisfy the request. alloc_pages() can only
2262 * allocate memory in power-of-two pages.
2264 * This function is also limited by MAX_ORDER.
2266 * Memory allocated by this function must be released by free_pages_exact().
2268 void *alloc_pages_exact(size_t size, gfp_t gfp_mask)
2270 unsigned int order = get_order(size);
2271 unsigned long addr;
2273 addr = __get_free_pages(gfp_mask, order);
2274 if (addr) {
2275 unsigned long alloc_end = addr + (PAGE_SIZE << order);
2276 unsigned long used = addr + PAGE_ALIGN(size);
2278 split_page(virt_to_page((void *)addr), order);
2279 while (used < alloc_end) {
2280 free_page(used);
2281 used += PAGE_SIZE;
2285 return (void *)addr;
2287 EXPORT_SYMBOL(alloc_pages_exact);
2290 * free_pages_exact - release memory allocated via alloc_pages_exact()
2291 * @virt: the value returned by alloc_pages_exact.
2292 * @size: size of allocation, same value as passed to alloc_pages_exact().
2294 * Release the memory allocated by a previous call to alloc_pages_exact.
2296 void free_pages_exact(void *virt, size_t size)
2298 unsigned long addr = (unsigned long)virt;
2299 unsigned long end = addr + PAGE_ALIGN(size);
2301 while (addr < end) {
2302 free_page(addr);
2303 addr += PAGE_SIZE;
2306 EXPORT_SYMBOL(free_pages_exact);
2308 static unsigned int nr_free_zone_pages(int offset)
2310 struct zoneref *z;
2311 struct zone *zone;
2313 /* Just pick one node, since fallback list is circular */
2314 unsigned int sum = 0;
2316 struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL);
2318 for_each_zone_zonelist(zone, z, zonelist, offset) {
2319 unsigned long size = zone->present_pages;
2320 unsigned long high = high_wmark_pages(zone);
2321 if (size > high)
2322 sum += size - high;
2325 return sum;
2329 * Amount of free RAM allocatable within ZONE_DMA and ZONE_NORMAL
2331 unsigned int nr_free_buffer_pages(void)
2333 return nr_free_zone_pages(gfp_zone(GFP_USER));
2335 EXPORT_SYMBOL_GPL(nr_free_buffer_pages);
2338 * Amount of free RAM allocatable within all zones
2340 unsigned int nr_free_pagecache_pages(void)
2342 return nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE));
2345 static inline void show_node(struct zone *zone)
2347 if (NUMA_BUILD)
2348 printk("Node %d ", zone_to_nid(zone));
2351 void si_meminfo(struct sysinfo *val)
2353 val->totalram = totalram_pages;
2354 val->sharedram = 0;
2355 val->freeram = global_page_state(NR_FREE_PAGES);
2356 val->bufferram = nr_blockdev_pages();
2357 val->totalhigh = totalhigh_pages;
2358 val->freehigh = nr_free_highpages();
2359 val->mem_unit = PAGE_SIZE;
2362 EXPORT_SYMBOL(si_meminfo);
2364 #ifdef CONFIG_NUMA
2365 void si_meminfo_node(struct sysinfo *val, int nid)
2367 pg_data_t *pgdat = NODE_DATA(nid);
2369 val->totalram = pgdat->node_present_pages;
2370 val->freeram = node_page_state(nid, NR_FREE_PAGES);
2371 #ifdef CONFIG_HIGHMEM
2372 val->totalhigh = pgdat->node_zones[ZONE_HIGHMEM].present_pages;
2373 val->freehigh = zone_page_state(&pgdat->node_zones[ZONE_HIGHMEM],
2374 NR_FREE_PAGES);
2375 #else
2376 val->totalhigh = 0;
2377 val->freehigh = 0;
2378 #endif
2379 val->mem_unit = PAGE_SIZE;
2381 #endif
2383 #define K(x) ((x) << (PAGE_SHIFT-10))
2386 * Show free area list (used inside shift_scroll-lock stuff)
2387 * We also calculate the percentage fragmentation. We do this by counting the
2388 * memory on each free list with the exception of the first item on the list.
2390 void show_free_areas(void)
2392 int cpu;
2393 struct zone *zone;
2395 for_each_populated_zone(zone) {
2396 show_node(zone);
2397 printk("%s per-cpu:\n", zone->name);
2399 for_each_online_cpu(cpu) {
2400 struct per_cpu_pageset *pageset;
2402 pageset = per_cpu_ptr(zone->pageset, cpu);
2404 printk("CPU %4d: hi:%5d, btch:%4d usd:%4d\n",
2405 cpu, pageset->pcp.high,
2406 pageset->pcp.batch, pageset->pcp.count);
2410 printk("active_anon:%lu inactive_anon:%lu isolated_anon:%lu\n"
2411 " active_file:%lu inactive_file:%lu isolated_file:%lu\n"
2412 " unevictable:%lu"
2413 " dirty:%lu writeback:%lu unstable:%lu\n"
2414 " free:%lu slab_reclaimable:%lu slab_unreclaimable:%lu\n"
2415 " mapped:%lu shmem:%lu pagetables:%lu bounce:%lu\n",
2416 global_page_state(NR_ACTIVE_ANON),
2417 global_page_state(NR_INACTIVE_ANON),
2418 global_page_state(NR_ISOLATED_ANON),
2419 global_page_state(NR_ACTIVE_FILE),
2420 global_page_state(NR_INACTIVE_FILE),
2421 global_page_state(NR_ISOLATED_FILE),
2422 global_page_state(NR_UNEVICTABLE),
2423 global_page_state(NR_FILE_DIRTY),
2424 global_page_state(NR_WRITEBACK),
2425 global_page_state(NR_UNSTABLE_NFS),
2426 global_page_state(NR_FREE_PAGES),
2427 global_page_state(NR_SLAB_RECLAIMABLE),
2428 global_page_state(NR_SLAB_UNRECLAIMABLE),
2429 global_page_state(NR_FILE_MAPPED),
2430 global_page_state(NR_SHMEM),
2431 global_page_state(NR_PAGETABLE),
2432 global_page_state(NR_BOUNCE));
2434 for_each_populated_zone(zone) {
2435 int i;
2437 show_node(zone);
2438 printk("%s"
2439 " free:%lukB"
2440 " min:%lukB"
2441 " low:%lukB"
2442 " high:%lukB"
2443 " active_anon:%lukB"
2444 " inactive_anon:%lukB"
2445 " active_file:%lukB"
2446 " inactive_file:%lukB"
2447 " unevictable:%lukB"
2448 " isolated(anon):%lukB"
2449 " isolated(file):%lukB"
2450 " present:%lukB"
2451 " mlocked:%lukB"
2452 " dirty:%lukB"
2453 " writeback:%lukB"
2454 " mapped:%lukB"
2455 " shmem:%lukB"
2456 " slab_reclaimable:%lukB"
2457 " slab_unreclaimable:%lukB"
2458 " kernel_stack:%lukB"
2459 " pagetables:%lukB"
2460 " unstable:%lukB"
2461 " bounce:%lukB"
2462 " writeback_tmp:%lukB"
2463 " pages_scanned:%lu"
2464 " all_unreclaimable? %s"
2465 "\n",
2466 zone->name,
2467 K(zone_page_state(zone, NR_FREE_PAGES)),
2468 K(min_wmark_pages(zone)),
2469 K(low_wmark_pages(zone)),
2470 K(high_wmark_pages(zone)),
2471 K(zone_page_state(zone, NR_ACTIVE_ANON)),
2472 K(zone_page_state(zone, NR_INACTIVE_ANON)),
2473 K(zone_page_state(zone, NR_ACTIVE_FILE)),
2474 K(zone_page_state(zone, NR_INACTIVE_FILE)),
2475 K(zone_page_state(zone, NR_UNEVICTABLE)),
2476 K(zone_page_state(zone, NR_ISOLATED_ANON)),
2477 K(zone_page_state(zone, NR_ISOLATED_FILE)),
2478 K(zone->present_pages),
2479 K(zone_page_state(zone, NR_MLOCK)),
2480 K(zone_page_state(zone, NR_FILE_DIRTY)),
2481 K(zone_page_state(zone, NR_WRITEBACK)),
2482 K(zone_page_state(zone, NR_FILE_MAPPED)),
2483 K(zone_page_state(zone, NR_SHMEM)),
2484 K(zone_page_state(zone, NR_SLAB_RECLAIMABLE)),
2485 K(zone_page_state(zone, NR_SLAB_UNRECLAIMABLE)),
2486 zone_page_state(zone, NR_KERNEL_STACK) *
2487 THREAD_SIZE / 1024,
2488 K(zone_page_state(zone, NR_PAGETABLE)),
2489 K(zone_page_state(zone, NR_UNSTABLE_NFS)),
2490 K(zone_page_state(zone, NR_BOUNCE)),
2491 K(zone_page_state(zone, NR_WRITEBACK_TEMP)),
2492 zone->pages_scanned,
2493 (zone->all_unreclaimable ? "yes" : "no")
2495 printk("lowmem_reserve[]:");
2496 for (i = 0; i < MAX_NR_ZONES; i++)
2497 printk(" %lu", zone->lowmem_reserve[i]);
2498 printk("\n");
2501 for_each_populated_zone(zone) {
2502 unsigned long nr[MAX_ORDER], flags, order, total = 0;
2504 show_node(zone);
2505 printk("%s: ", zone->name);
2507 spin_lock_irqsave(&zone->lock, flags);
2508 for (order = 0; order < MAX_ORDER; order++) {
2509 nr[order] = zone->free_area[order].nr_free;
2510 total += nr[order] << order;
2512 spin_unlock_irqrestore(&zone->lock, flags);
2513 for (order = 0; order < MAX_ORDER; order++)
2514 printk("%lu*%lukB ", nr[order], K(1UL) << order);
2515 printk("= %lukB\n", K(total));
2518 printk("%ld total pagecache pages\n", global_page_state(NR_FILE_PAGES));
2520 show_swap_cache_info();
2523 static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref)
2525 zoneref->zone = zone;
2526 zoneref->zone_idx = zone_idx(zone);
2530 * Builds allocation fallback zone lists.
2532 * Add all populated zones of a node to the zonelist.
2534 static int build_zonelists_node(pg_data_t *pgdat, struct zonelist *zonelist,
2535 int nr_zones, enum zone_type zone_type)
2537 struct zone *zone;
2539 BUG_ON(zone_type >= MAX_NR_ZONES);
2540 zone_type++;
2542 do {
2543 zone_type--;
2544 zone = pgdat->node_zones + zone_type;
2545 if (populated_zone(zone)) {
2546 zoneref_set_zone(zone,
2547 &zonelist->_zonerefs[nr_zones++]);
2548 check_highest_zone(zone_type);
2551 } while (zone_type);
2552 return nr_zones;
2557 * zonelist_order:
2558 * 0 = automatic detection of better ordering.
2559 * 1 = order by ([node] distance, -zonetype)
2560 * 2 = order by (-zonetype, [node] distance)
2562 * If not NUMA, ZONELIST_ORDER_ZONE and ZONELIST_ORDER_NODE will create
2563 * the same zonelist. So only NUMA can configure this param.
2565 #define ZONELIST_ORDER_DEFAULT 0
2566 #define ZONELIST_ORDER_NODE 1
2567 #define ZONELIST_ORDER_ZONE 2
2569 /* zonelist order in the kernel.
2570 * set_zonelist_order() will set this to NODE or ZONE.
2572 static int current_zonelist_order = ZONELIST_ORDER_DEFAULT;
2573 static char zonelist_order_name[3][8] = {"Default", "Node", "Zone"};
2576 #ifdef CONFIG_NUMA
2577 /* The value user specified ....changed by config */
2578 static int user_zonelist_order = ZONELIST_ORDER_DEFAULT;
2579 /* string for sysctl */
2580 #define NUMA_ZONELIST_ORDER_LEN 16
2581 char numa_zonelist_order[16] = "default";
2584 * interface for configure zonelist ordering.
2585 * command line option "numa_zonelist_order"
2586 * = "[dD]efault - default, automatic configuration.
2587 * = "[nN]ode - order by node locality, then by zone within node
2588 * = "[zZ]one - order by zone, then by locality within zone
2591 static int __parse_numa_zonelist_order(char *s)
2593 if (*s == 'd' || *s == 'D') {
2594 user_zonelist_order = ZONELIST_ORDER_DEFAULT;
2595 } else if (*s == 'n' || *s == 'N') {
2596 user_zonelist_order = ZONELIST_ORDER_NODE;
2597 } else if (*s == 'z' || *s == 'Z') {
2598 user_zonelist_order = ZONELIST_ORDER_ZONE;
2599 } else {
2600 printk(KERN_WARNING
2601 "Ignoring invalid numa_zonelist_order value: "
2602 "%s\n", s);
2603 return -EINVAL;
2605 return 0;
2608 static __init int setup_numa_zonelist_order(char *s)
2610 if (s)
2611 return __parse_numa_zonelist_order(s);
2612 return 0;
2614 early_param("numa_zonelist_order", setup_numa_zonelist_order);
2617 * sysctl handler for numa_zonelist_order
2619 int numa_zonelist_order_handler(ctl_table *table, int write,
2620 void __user *buffer, size_t *length,
2621 loff_t *ppos)
2623 char saved_string[NUMA_ZONELIST_ORDER_LEN];
2624 int ret;
2625 static DEFINE_MUTEX(zl_order_mutex);
2627 mutex_lock(&zl_order_mutex);
2628 if (write)
2629 strcpy(saved_string, (char*)table->data);
2630 ret = proc_dostring(table, write, buffer, length, ppos);
2631 if (ret)
2632 goto out;
2633 if (write) {
2634 int oldval = user_zonelist_order;
2635 if (__parse_numa_zonelist_order((char*)table->data)) {
2637 * bogus value. restore saved string
2639 strncpy((char*)table->data, saved_string,
2640 NUMA_ZONELIST_ORDER_LEN);
2641 user_zonelist_order = oldval;
2642 } else if (oldval != user_zonelist_order) {
2643 mutex_lock(&zonelists_mutex);
2644 build_all_zonelists(NULL);
2645 mutex_unlock(&zonelists_mutex);
2648 out:
2649 mutex_unlock(&zl_order_mutex);
2650 return ret;
2654 #define MAX_NODE_LOAD (nr_online_nodes)
2655 static int node_load[MAX_NUMNODES];
2658 * find_next_best_node - find the next node that should appear in a given node's fallback list
2659 * @node: node whose fallback list we're appending
2660 * @used_node_mask: nodemask_t of already used nodes
2662 * We use a number of factors to determine which is the next node that should
2663 * appear on a given node's fallback list. The node should not have appeared
2664 * already in @node's fallback list, and it should be the next closest node
2665 * according to the distance array (which contains arbitrary distance values
2666 * from each node to each node in the system), and should also prefer nodes
2667 * with no CPUs, since presumably they'll have very little allocation pressure
2668 * on them otherwise.
2669 * It returns -1 if no node is found.
2671 static int find_next_best_node(int node, nodemask_t *used_node_mask)
2673 int n, val;
2674 int min_val = INT_MAX;
2675 int best_node = -1;
2676 const struct cpumask *tmp = cpumask_of_node(0);
2678 /* Use the local node if we haven't already */
2679 if (!node_isset(node, *used_node_mask)) {
2680 node_set(node, *used_node_mask);
2681 return node;
2684 for_each_node_state(n, N_HIGH_MEMORY) {
2686 /* Don't want a node to appear more than once */
2687 if (node_isset(n, *used_node_mask))
2688 continue;
2690 /* Use the distance array to find the distance */
2691 val = node_distance(node, n);
2693 /* Penalize nodes under us ("prefer the next node") */
2694 val += (n < node);
2696 /* Give preference to headless and unused nodes */
2697 tmp = cpumask_of_node(n);
2698 if (!cpumask_empty(tmp))
2699 val += PENALTY_FOR_NODE_WITH_CPUS;
2701 /* Slight preference for less loaded node */
2702 val *= (MAX_NODE_LOAD*MAX_NUMNODES);
2703 val += node_load[n];
2705 if (val < min_val) {
2706 min_val = val;
2707 best_node = n;
2711 if (best_node >= 0)
2712 node_set(best_node, *used_node_mask);
2714 return best_node;
2719 * Build zonelists ordered by node and zones within node.
2720 * This results in maximum locality--normal zone overflows into local
2721 * DMA zone, if any--but risks exhausting DMA zone.
2723 static void build_zonelists_in_node_order(pg_data_t *pgdat, int node)
2725 int j;
2726 struct zonelist *zonelist;
2728 zonelist = &pgdat->node_zonelists[0];
2729 for (j = 0; zonelist->_zonerefs[j].zone != NULL; j++)
2731 j = build_zonelists_node(NODE_DATA(node), zonelist, j,
2732 MAX_NR_ZONES - 1);
2733 zonelist->_zonerefs[j].zone = NULL;
2734 zonelist->_zonerefs[j].zone_idx = 0;
2738 * Build gfp_thisnode zonelists
2740 static void build_thisnode_zonelists(pg_data_t *pgdat)
2742 int j;
2743 struct zonelist *zonelist;
2745 zonelist = &pgdat->node_zonelists[1];
2746 j = build_zonelists_node(pgdat, zonelist, 0, MAX_NR_ZONES - 1);
2747 zonelist->_zonerefs[j].zone = NULL;
2748 zonelist->_zonerefs[j].zone_idx = 0;
2752 * Build zonelists ordered by zone and nodes within zones.
2753 * This results in conserving DMA zone[s] until all Normal memory is
2754 * exhausted, but results in overflowing to remote node while memory
2755 * may still exist in local DMA zone.
2757 static int node_order[MAX_NUMNODES];
2759 static void build_zonelists_in_zone_order(pg_data_t *pgdat, int nr_nodes)
2761 int pos, j, node;
2762 int zone_type; /* needs to be signed */
2763 struct zone *z;
2764 struct zonelist *zonelist;
2766 zonelist = &pgdat->node_zonelists[0];
2767 pos = 0;
2768 for (zone_type = MAX_NR_ZONES - 1; zone_type >= 0; zone_type--) {
2769 for (j = 0; j < nr_nodes; j++) {
2770 node = node_order[j];
2771 z = &NODE_DATA(node)->node_zones[zone_type];
2772 if (populated_zone(z)) {
2773 zoneref_set_zone(z,
2774 &zonelist->_zonerefs[pos++]);
2775 check_highest_zone(zone_type);
2779 zonelist->_zonerefs[pos].zone = NULL;
2780 zonelist->_zonerefs[pos].zone_idx = 0;
2783 static int default_zonelist_order(void)
2785 int nid, zone_type;
2786 unsigned long low_kmem_size,total_size;
2787 struct zone *z;
2788 int average_size;
2790 * ZONE_DMA and ZONE_DMA32 can be very small area in the system.
2791 * If they are really small and used heavily, the system can fall
2792 * into OOM very easily.
2793 * This function detect ZONE_DMA/DMA32 size and configures zone order.
2795 /* Is there ZONE_NORMAL ? (ex. ppc has only DMA zone..) */
2796 low_kmem_size = 0;
2797 total_size = 0;
2798 for_each_online_node(nid) {
2799 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
2800 z = &NODE_DATA(nid)->node_zones[zone_type];
2801 if (populated_zone(z)) {
2802 if (zone_type < ZONE_NORMAL)
2803 low_kmem_size += z->present_pages;
2804 total_size += z->present_pages;
2805 } else if (zone_type == ZONE_NORMAL) {
2807 * If any node has only lowmem, then node order
2808 * is preferred to allow kernel allocations
2809 * locally; otherwise, they can easily infringe
2810 * on other nodes when there is an abundance of
2811 * lowmem available to allocate from.
2813 return ZONELIST_ORDER_NODE;
2817 if (!low_kmem_size || /* there are no DMA area. */
2818 low_kmem_size > total_size/2) /* DMA/DMA32 is big. */
2819 return ZONELIST_ORDER_NODE;
2821 * look into each node's config.
2822 * If there is a node whose DMA/DMA32 memory is very big area on
2823 * local memory, NODE_ORDER may be suitable.
2825 average_size = total_size /
2826 (nodes_weight(node_states[N_HIGH_MEMORY]) + 1);
2827 for_each_online_node(nid) {
2828 low_kmem_size = 0;
2829 total_size = 0;
2830 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
2831 z = &NODE_DATA(nid)->node_zones[zone_type];
2832 if (populated_zone(z)) {
2833 if (zone_type < ZONE_NORMAL)
2834 low_kmem_size += z->present_pages;
2835 total_size += z->present_pages;
2838 if (low_kmem_size &&
2839 total_size > average_size && /* ignore small node */
2840 low_kmem_size > total_size * 70/100)
2841 return ZONELIST_ORDER_NODE;
2843 return ZONELIST_ORDER_ZONE;
2846 static void set_zonelist_order(void)
2848 if (user_zonelist_order == ZONELIST_ORDER_DEFAULT)
2849 current_zonelist_order = default_zonelist_order();
2850 else
2851 current_zonelist_order = user_zonelist_order;
2854 static void build_zonelists(pg_data_t *pgdat)
2856 int j, node, load;
2857 enum zone_type i;
2858 nodemask_t used_mask;
2859 int local_node, prev_node;
2860 struct zonelist *zonelist;
2861 int order = current_zonelist_order;
2863 /* initialize zonelists */
2864 for (i = 0; i < MAX_ZONELISTS; i++) {
2865 zonelist = pgdat->node_zonelists + i;
2866 zonelist->_zonerefs[0].zone = NULL;
2867 zonelist->_zonerefs[0].zone_idx = 0;
2870 /* NUMA-aware ordering of nodes */
2871 local_node = pgdat->node_id;
2872 load = nr_online_nodes;
2873 prev_node = local_node;
2874 nodes_clear(used_mask);
2876 memset(node_order, 0, sizeof(node_order));
2877 j = 0;
2879 while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
2880 int distance = node_distance(local_node, node);
2883 * If another node is sufficiently far away then it is better
2884 * to reclaim pages in a zone before going off node.
2886 if (distance > RECLAIM_DISTANCE)
2887 zone_reclaim_mode = 1;
2890 * We don't want to pressure a particular node.
2891 * So adding penalty to the first node in same
2892 * distance group to make it round-robin.
2894 if (distance != node_distance(local_node, prev_node))
2895 node_load[node] = load;
2897 prev_node = node;
2898 load--;
2899 if (order == ZONELIST_ORDER_NODE)
2900 build_zonelists_in_node_order(pgdat, node);
2901 else
2902 node_order[j++] = node; /* remember order */
2905 if (order == ZONELIST_ORDER_ZONE) {
2906 /* calculate node order -- i.e., DMA last! */
2907 build_zonelists_in_zone_order(pgdat, j);
2910 build_thisnode_zonelists(pgdat);
2913 /* Construct the zonelist performance cache - see further mmzone.h */
2914 static void build_zonelist_cache(pg_data_t *pgdat)
2916 struct zonelist *zonelist;
2917 struct zonelist_cache *zlc;
2918 struct zoneref *z;
2920 zonelist = &pgdat->node_zonelists[0];
2921 zonelist->zlcache_ptr = zlc = &zonelist->zlcache;
2922 bitmap_zero(zlc->fullzones, MAX_ZONES_PER_ZONELIST);
2923 for (z = zonelist->_zonerefs; z->zone; z++)
2924 zlc->z_to_n[z - zonelist->_zonerefs] = zonelist_node_idx(z);
2927 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
2929 * Return node id of node used for "local" allocations.
2930 * I.e., first node id of first zone in arg node's generic zonelist.
2931 * Used for initializing percpu 'numa_mem', which is used primarily
2932 * for kernel allocations, so use GFP_KERNEL flags to locate zonelist.
2934 int local_memory_node(int node)
2936 struct zone *zone;
2938 (void)first_zones_zonelist(node_zonelist(node, GFP_KERNEL),
2939 gfp_zone(GFP_KERNEL),
2940 NULL,
2941 &zone);
2942 return zone->node;
2944 #endif
2946 #else /* CONFIG_NUMA */
2948 static void set_zonelist_order(void)
2950 current_zonelist_order = ZONELIST_ORDER_ZONE;
2953 static void build_zonelists(pg_data_t *pgdat)
2955 int node, local_node;
2956 enum zone_type j;
2957 struct zonelist *zonelist;
2959 local_node = pgdat->node_id;
2961 zonelist = &pgdat->node_zonelists[0];
2962 j = build_zonelists_node(pgdat, zonelist, 0, MAX_NR_ZONES - 1);
2965 * Now we build the zonelist so that it contains the zones
2966 * of all the other nodes.
2967 * We don't want to pressure a particular node, so when
2968 * building the zones for node N, we make sure that the
2969 * zones coming right after the local ones are those from
2970 * node N+1 (modulo N)
2972 for (node = local_node + 1; node < MAX_NUMNODES; node++) {
2973 if (!node_online(node))
2974 continue;
2975 j = build_zonelists_node(NODE_DATA(node), zonelist, j,
2976 MAX_NR_ZONES - 1);
2978 for (node = 0; node < local_node; node++) {
2979 if (!node_online(node))
2980 continue;
2981 j = build_zonelists_node(NODE_DATA(node), zonelist, j,
2982 MAX_NR_ZONES - 1);
2985 zonelist->_zonerefs[j].zone = NULL;
2986 zonelist->_zonerefs[j].zone_idx = 0;
2989 /* non-NUMA variant of zonelist performance cache - just NULL zlcache_ptr */
2990 static void build_zonelist_cache(pg_data_t *pgdat)
2992 pgdat->node_zonelists[0].zlcache_ptr = NULL;
2995 #endif /* CONFIG_NUMA */
2998 * Boot pageset table. One per cpu which is going to be used for all
2999 * zones and all nodes. The parameters will be set in such a way
3000 * that an item put on a list will immediately be handed over to
3001 * the buddy list. This is safe since pageset manipulation is done
3002 * with interrupts disabled.
3004 * The boot_pagesets must be kept even after bootup is complete for
3005 * unused processors and/or zones. They do play a role for bootstrapping
3006 * hotplugged processors.
3008 * zoneinfo_show() and maybe other functions do
3009 * not check if the processor is online before following the pageset pointer.
3010 * Other parts of the kernel may not check if the zone is available.
3012 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch);
3013 static DEFINE_PER_CPU(struct per_cpu_pageset, boot_pageset);
3014 static void setup_zone_pageset(struct zone *zone);
3017 * Global mutex to protect against size modification of zonelists
3018 * as well as to serialize pageset setup for the new populated zone.
3020 DEFINE_MUTEX(zonelists_mutex);
3022 /* return values int ....just for stop_machine() */
3023 static __init_refok int __build_all_zonelists(void *data)
3025 int nid;
3026 int cpu;
3028 #ifdef CONFIG_NUMA
3029 memset(node_load, 0, sizeof(node_load));
3030 #endif
3031 for_each_online_node(nid) {
3032 pg_data_t *pgdat = NODE_DATA(nid);
3034 build_zonelists(pgdat);
3035 build_zonelist_cache(pgdat);
3038 #ifdef CONFIG_MEMORY_HOTPLUG
3039 /* Setup real pagesets for the new zone */
3040 if (data) {
3041 struct zone *zone = data;
3042 setup_zone_pageset(zone);
3044 #endif
3047 * Initialize the boot_pagesets that are going to be used
3048 * for bootstrapping processors. The real pagesets for
3049 * each zone will be allocated later when the per cpu
3050 * allocator is available.
3052 * boot_pagesets are used also for bootstrapping offline
3053 * cpus if the system is already booted because the pagesets
3054 * are needed to initialize allocators on a specific cpu too.
3055 * F.e. the percpu allocator needs the page allocator which
3056 * needs the percpu allocator in order to allocate its pagesets
3057 * (a chicken-egg dilemma).
3059 for_each_possible_cpu(cpu) {
3060 setup_pageset(&per_cpu(boot_pageset, cpu), 0);
3062 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
3064 * We now know the "local memory node" for each node--
3065 * i.e., the node of the first zone in the generic zonelist.
3066 * Set up numa_mem percpu variable for on-line cpus. During
3067 * boot, only the boot cpu should be on-line; we'll init the
3068 * secondary cpus' numa_mem as they come on-line. During
3069 * node/memory hotplug, we'll fixup all on-line cpus.
3071 if (cpu_online(cpu))
3072 set_cpu_numa_mem(cpu, local_memory_node(cpu_to_node(cpu)));
3073 #endif
3076 return 0;
3080 * Called with zonelists_mutex held always
3081 * unless system_state == SYSTEM_BOOTING.
3083 void build_all_zonelists(void *data)
3085 set_zonelist_order();
3087 if (system_state == SYSTEM_BOOTING) {
3088 __build_all_zonelists(NULL);
3089 mminit_verify_zonelist();
3090 cpuset_init_current_mems_allowed();
3091 } else {
3092 /* we have to stop all cpus to guarantee there is no user
3093 of zonelist */
3094 stop_machine(__build_all_zonelists, data, NULL);
3095 /* cpuset refresh routine should be here */
3097 vm_total_pages = nr_free_pagecache_pages();
3099 * Disable grouping by mobility if the number of pages in the
3100 * system is too low to allow the mechanism to work. It would be
3101 * more accurate, but expensive to check per-zone. This check is
3102 * made on memory-hotadd so a system can start with mobility
3103 * disabled and enable it later
3105 if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES))
3106 page_group_by_mobility_disabled = 1;
3107 else
3108 page_group_by_mobility_disabled = 0;
3110 printk("Built %i zonelists in %s order, mobility grouping %s. "
3111 "Total pages: %ld\n",
3112 nr_online_nodes,
3113 zonelist_order_name[current_zonelist_order],
3114 page_group_by_mobility_disabled ? "off" : "on",
3115 vm_total_pages);
3116 #ifdef CONFIG_NUMA
3117 printk("Policy zone: %s\n", zone_names[policy_zone]);
3118 #endif
3122 * Helper functions to size the waitqueue hash table.
3123 * Essentially these want to choose hash table sizes sufficiently
3124 * large so that collisions trying to wait on pages are rare.
3125 * But in fact, the number of active page waitqueues on typical
3126 * systems is ridiculously low, less than 200. So this is even
3127 * conservative, even though it seems large.
3129 * The constant PAGES_PER_WAITQUEUE specifies the ratio of pages to
3130 * waitqueues, i.e. the size of the waitq table given the number of pages.
3132 #define PAGES_PER_WAITQUEUE 256
3134 #ifndef CONFIG_MEMORY_HOTPLUG
3135 static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
3137 unsigned long size = 1;
3139 pages /= PAGES_PER_WAITQUEUE;
3141 while (size < pages)
3142 size <<= 1;
3145 * Once we have dozens or even hundreds of threads sleeping
3146 * on IO we've got bigger problems than wait queue collision.
3147 * Limit the size of the wait table to a reasonable size.
3149 size = min(size, 4096UL);
3151 return max(size, 4UL);
3153 #else
3155 * A zone's size might be changed by hot-add, so it is not possible to determine
3156 * a suitable size for its wait_table. So we use the maximum size now.
3158 * The max wait table size = 4096 x sizeof(wait_queue_head_t). ie:
3160 * i386 (preemption config) : 4096 x 16 = 64Kbyte.
3161 * ia64, x86-64 (no preemption): 4096 x 20 = 80Kbyte.
3162 * ia64, x86-64 (preemption) : 4096 x 24 = 96Kbyte.
3164 * The maximum entries are prepared when a zone's memory is (512K + 256) pages
3165 * or more by the traditional way. (See above). It equals:
3167 * i386, x86-64, powerpc(4K page size) : = ( 2G + 1M)byte.
3168 * ia64(16K page size) : = ( 8G + 4M)byte.
3169 * powerpc (64K page size) : = (32G +16M)byte.
3171 static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
3173 return 4096UL;
3175 #endif
3178 * This is an integer logarithm so that shifts can be used later
3179 * to extract the more random high bits from the multiplicative
3180 * hash function before the remainder is taken.
3182 static inline unsigned long wait_table_bits(unsigned long size)
3184 return ffz(~size);
3187 #define LONG_ALIGN(x) (((x)+(sizeof(long))-1)&~((sizeof(long))-1))
3190 * Mark a number of pageblocks as MIGRATE_RESERVE. The number
3191 * of blocks reserved is based on min_wmark_pages(zone). The memory within
3192 * the reserve will tend to store contiguous free pages. Setting min_free_kbytes
3193 * higher will lead to a bigger reserve which will get freed as contiguous
3194 * blocks as reclaim kicks in
3196 static void setup_zone_migrate_reserve(struct zone *zone)
3198 unsigned long start_pfn, pfn, end_pfn;
3199 struct page *page;
3200 unsigned long block_migratetype;
3201 int reserve;
3203 /* Get the start pfn, end pfn and the number of blocks to reserve */
3204 start_pfn = zone->zone_start_pfn;
3205 end_pfn = start_pfn + zone->spanned_pages;
3206 reserve = roundup(min_wmark_pages(zone), pageblock_nr_pages) >>
3207 pageblock_order;
3210 * Reserve blocks are generally in place to help high-order atomic
3211 * allocations that are short-lived. A min_free_kbytes value that
3212 * would result in more than 2 reserve blocks for atomic allocations
3213 * is assumed to be in place to help anti-fragmentation for the
3214 * future allocation of hugepages at runtime.
3216 reserve = min(2, reserve);
3218 for (pfn = start_pfn; pfn < end_pfn; pfn += pageblock_nr_pages) {
3219 if (!pfn_valid(pfn))
3220 continue;
3221 page = pfn_to_page(pfn);
3223 /* Watch out for overlapping nodes */
3224 if (page_to_nid(page) != zone_to_nid(zone))
3225 continue;
3227 /* Blocks with reserved pages will never free, skip them. */
3228 if (PageReserved(page))
3229 continue;
3231 block_migratetype = get_pageblock_migratetype(page);
3233 /* If this block is reserved, account for it */
3234 if (reserve > 0 && block_migratetype == MIGRATE_RESERVE) {
3235 reserve--;
3236 continue;
3239 /* Suitable for reserving if this block is movable */
3240 if (reserve > 0 && block_migratetype == MIGRATE_MOVABLE) {
3241 set_pageblock_migratetype(page, MIGRATE_RESERVE);
3242 move_freepages_block(zone, page, MIGRATE_RESERVE);
3243 reserve--;
3244 continue;
3248 * If the reserve is met and this is a previous reserved block,
3249 * take it back
3251 if (block_migratetype == MIGRATE_RESERVE) {
3252 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
3253 move_freepages_block(zone, page, MIGRATE_MOVABLE);
3259 * Initially all pages are reserved - free ones are freed
3260 * up by free_all_bootmem() once the early boot process is
3261 * done. Non-atomic initialization, single-pass.
3263 void __meminit memmap_init_zone(unsigned long size, int nid, unsigned long zone,
3264 unsigned long start_pfn, enum memmap_context context)
3266 struct page *page;
3267 unsigned long end_pfn = start_pfn + size;
3268 unsigned long pfn;
3269 struct zone *z;
3271 if (highest_memmap_pfn < end_pfn - 1)
3272 highest_memmap_pfn = end_pfn - 1;
3274 z = &NODE_DATA(nid)->node_zones[zone];
3275 for (pfn = start_pfn; pfn < end_pfn; pfn++) {
3277 * There can be holes in boot-time mem_map[]s
3278 * handed to this function. They do not
3279 * exist on hotplugged memory.
3281 if (context == MEMMAP_EARLY) {
3282 if (!early_pfn_valid(pfn))
3283 continue;
3284 if (!early_pfn_in_nid(pfn, nid))
3285 continue;
3287 page = pfn_to_page(pfn);
3288 set_page_links(page, zone, nid, pfn);
3289 mminit_verify_page_links(page, zone, nid, pfn);
3290 init_page_count(page);
3291 reset_page_mapcount(page);
3292 SetPageReserved(page);
3294 * Mark the block movable so that blocks are reserved for
3295 * movable at startup. This will force kernel allocations
3296 * to reserve their blocks rather than leaking throughout
3297 * the address space during boot when many long-lived
3298 * kernel allocations are made. Later some blocks near
3299 * the start are marked MIGRATE_RESERVE by
3300 * setup_zone_migrate_reserve()
3302 * bitmap is created for zone's valid pfn range. but memmap
3303 * can be created for invalid pages (for alignment)
3304 * check here not to call set_pageblock_migratetype() against
3305 * pfn out of zone.
3307 if ((z->zone_start_pfn <= pfn)
3308 && (pfn < z->zone_start_pfn + z->spanned_pages)
3309 && !(pfn & (pageblock_nr_pages - 1)))
3310 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
3312 INIT_LIST_HEAD(&page->lru);
3313 #ifdef WANT_PAGE_VIRTUAL
3314 /* The shift won't overflow because ZONE_NORMAL is below 4G. */
3315 if (!is_highmem_idx(zone))
3316 set_page_address(page, __va(pfn << PAGE_SHIFT));
3317 #endif
3321 static void __meminit zone_init_free_lists(struct zone *zone)
3323 int order, t;
3324 for_each_migratetype_order(order, t) {
3325 INIT_LIST_HEAD(&zone->free_area[order].free_list[t]);
3326 zone->free_area[order].nr_free = 0;
3330 #ifndef __HAVE_ARCH_MEMMAP_INIT
3331 #define memmap_init(size, nid, zone, start_pfn) \
3332 memmap_init_zone((size), (nid), (zone), (start_pfn), MEMMAP_EARLY)
3333 #endif
3335 static int zone_batchsize(struct zone *zone)
3337 #ifdef CONFIG_MMU
3338 int batch;
3341 * The per-cpu-pages pools are set to around 1000th of the
3342 * size of the zone. But no more than 1/2 of a meg.
3344 * OK, so we don't know how big the cache is. So guess.
3346 batch = zone->present_pages / 1024;
3347 if (batch * PAGE_SIZE > 512 * 1024)
3348 batch = (512 * 1024) / PAGE_SIZE;
3349 batch /= 4; /* We effectively *= 4 below */
3350 if (batch < 1)
3351 batch = 1;
3354 * Clamp the batch to a 2^n - 1 value. Having a power
3355 * of 2 value was found to be more likely to have
3356 * suboptimal cache aliasing properties in some cases.
3358 * For example if 2 tasks are alternately allocating
3359 * batches of pages, one task can end up with a lot
3360 * of pages of one half of the possible page colors
3361 * and the other with pages of the other colors.
3363 batch = rounddown_pow_of_two(batch + batch/2) - 1;
3365 return batch;
3367 #else
3368 /* The deferral and batching of frees should be suppressed under NOMMU
3369 * conditions.
3371 * The problem is that NOMMU needs to be able to allocate large chunks
3372 * of contiguous memory as there's no hardware page translation to
3373 * assemble apparent contiguous memory from discontiguous pages.
3375 * Queueing large contiguous runs of pages for batching, however,
3376 * causes the pages to actually be freed in smaller chunks. As there
3377 * can be a significant delay between the individual batches being
3378 * recycled, this leads to the once large chunks of space being
3379 * fragmented and becoming unavailable for high-order allocations.
3381 return 0;
3382 #endif
3385 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch)
3387 struct per_cpu_pages *pcp;
3388 int migratetype;
3390 memset(p, 0, sizeof(*p));
3392 pcp = &p->pcp;
3393 pcp->count = 0;
3394 pcp->high = 6 * batch;
3395 pcp->batch = max(1UL, 1 * batch);
3396 for (migratetype = 0; migratetype < MIGRATE_PCPTYPES; migratetype++)
3397 INIT_LIST_HEAD(&pcp->lists[migratetype]);
3401 * setup_pagelist_highmark() sets the high water mark for hot per_cpu_pagelist
3402 * to the value high for the pageset p.
3405 static void setup_pagelist_highmark(struct per_cpu_pageset *p,
3406 unsigned long high)
3408 struct per_cpu_pages *pcp;
3410 pcp = &p->pcp;
3411 pcp->high = high;
3412 pcp->batch = max(1UL, high/4);
3413 if ((high/4) > (PAGE_SHIFT * 8))
3414 pcp->batch = PAGE_SHIFT * 8;
3417 static __meminit void setup_zone_pageset(struct zone *zone)
3419 int cpu;
3421 zone->pageset = alloc_percpu(struct per_cpu_pageset);
3423 for_each_possible_cpu(cpu) {
3424 struct per_cpu_pageset *pcp = per_cpu_ptr(zone->pageset, cpu);
3426 setup_pageset(pcp, zone_batchsize(zone));
3428 if (percpu_pagelist_fraction)
3429 setup_pagelist_highmark(pcp,
3430 (zone->present_pages /
3431 percpu_pagelist_fraction));
3436 * Allocate per cpu pagesets and initialize them.
3437 * Before this call only boot pagesets were available.
3439 void __init setup_per_cpu_pageset(void)
3441 struct zone *zone;
3443 for_each_populated_zone(zone)
3444 setup_zone_pageset(zone);
3447 static noinline __init_refok
3448 int zone_wait_table_init(struct zone *zone, unsigned long zone_size_pages)
3450 int i;
3451 struct pglist_data *pgdat = zone->zone_pgdat;
3452 size_t alloc_size;
3455 * The per-page waitqueue mechanism uses hashed waitqueues
3456 * per zone.
3458 zone->wait_table_hash_nr_entries =
3459 wait_table_hash_nr_entries(zone_size_pages);
3460 zone->wait_table_bits =
3461 wait_table_bits(zone->wait_table_hash_nr_entries);
3462 alloc_size = zone->wait_table_hash_nr_entries
3463 * sizeof(wait_queue_head_t);
3465 if (!slab_is_available()) {
3466 zone->wait_table = (wait_queue_head_t *)
3467 alloc_bootmem_node(pgdat, alloc_size);
3468 } else {
3470 * This case means that a zone whose size was 0 gets new memory
3471 * via memory hot-add.
3472 * But it may be the case that a new node was hot-added. In
3473 * this case vmalloc() will not be able to use this new node's
3474 * memory - this wait_table must be initialized to use this new
3475 * node itself as well.
3476 * To use this new node's memory, further consideration will be
3477 * necessary.
3479 zone->wait_table = vmalloc(alloc_size);
3481 if (!zone->wait_table)
3482 return -ENOMEM;
3484 for(i = 0; i < zone->wait_table_hash_nr_entries; ++i)
3485 init_waitqueue_head(zone->wait_table + i);
3487 return 0;
3490 static int __zone_pcp_update(void *data)
3492 struct zone *zone = data;
3493 int cpu;
3494 unsigned long batch = zone_batchsize(zone), flags;
3496 for_each_possible_cpu(cpu) {
3497 struct per_cpu_pageset *pset;
3498 struct per_cpu_pages *pcp;
3500 pset = per_cpu_ptr(zone->pageset, cpu);
3501 pcp = &pset->pcp;
3503 local_irq_save(flags);
3504 free_pcppages_bulk(zone, pcp->count, pcp);
3505 setup_pageset(pset, batch);
3506 local_irq_restore(flags);
3508 return 0;
3511 void zone_pcp_update(struct zone *zone)
3513 stop_machine(__zone_pcp_update, zone, NULL);
3516 static __meminit void zone_pcp_init(struct zone *zone)
3519 * per cpu subsystem is not up at this point. The following code
3520 * relies on the ability of the linker to provide the
3521 * offset of a (static) per cpu variable into the per cpu area.
3523 zone->pageset = &boot_pageset;
3525 if (zone->present_pages)
3526 printk(KERN_DEBUG " %s zone: %lu pages, LIFO batch:%u\n",
3527 zone->name, zone->present_pages,
3528 zone_batchsize(zone));
3531 __meminit int init_currently_empty_zone(struct zone *zone,
3532 unsigned long zone_start_pfn,
3533 unsigned long size,
3534 enum memmap_context context)
3536 struct pglist_data *pgdat = zone->zone_pgdat;
3537 int ret;
3538 ret = zone_wait_table_init(zone, size);
3539 if (ret)
3540 return ret;
3541 pgdat->nr_zones = zone_idx(zone) + 1;
3543 zone->zone_start_pfn = zone_start_pfn;
3545 mminit_dprintk(MMINIT_TRACE, "memmap_init",
3546 "Initialising map node %d zone %lu pfns %lu -> %lu\n",
3547 pgdat->node_id,
3548 (unsigned long)zone_idx(zone),
3549 zone_start_pfn, (zone_start_pfn + size));
3551 zone_init_free_lists(zone);
3553 return 0;
3556 #ifdef CONFIG_ARCH_POPULATES_NODE_MAP
3558 * Basic iterator support. Return the first range of PFNs for a node
3559 * Note: nid == MAX_NUMNODES returns first region regardless of node
3561 static int __meminit first_active_region_index_in_nid(int nid)
3563 int i;
3565 for (i = 0; i < nr_nodemap_entries; i++)
3566 if (nid == MAX_NUMNODES || early_node_map[i].nid == nid)
3567 return i;
3569 return -1;
3573 * Basic iterator support. Return the next active range of PFNs for a node
3574 * Note: nid == MAX_NUMNODES returns next region regardless of node
3576 static int __meminit next_active_region_index_in_nid(int index, int nid)
3578 for (index = index + 1; index < nr_nodemap_entries; index++)
3579 if (nid == MAX_NUMNODES || early_node_map[index].nid == nid)
3580 return index;
3582 return -1;
3585 #ifndef CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID
3587 * Required by SPARSEMEM. Given a PFN, return what node the PFN is on.
3588 * Architectures may implement their own version but if add_active_range()
3589 * was used and there are no special requirements, this is a convenient
3590 * alternative
3592 int __meminit __early_pfn_to_nid(unsigned long pfn)
3594 int i;
3596 for (i = 0; i < nr_nodemap_entries; i++) {
3597 unsigned long start_pfn = early_node_map[i].start_pfn;
3598 unsigned long end_pfn = early_node_map[i].end_pfn;
3600 if (start_pfn <= pfn && pfn < end_pfn)
3601 return early_node_map[i].nid;
3603 /* This is a memory hole */
3604 return -1;
3606 #endif /* CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID */
3608 int __meminit early_pfn_to_nid(unsigned long pfn)
3610 int nid;
3612 nid = __early_pfn_to_nid(pfn);
3613 if (nid >= 0)
3614 return nid;
3615 /* just returns 0 */
3616 return 0;
3619 #ifdef CONFIG_NODES_SPAN_OTHER_NODES
3620 bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
3622 int nid;
3624 nid = __early_pfn_to_nid(pfn);
3625 if (nid >= 0 && nid != node)
3626 return false;
3627 return true;
3629 #endif
3631 /* Basic iterator support to walk early_node_map[] */
3632 #define for_each_active_range_index_in_nid(i, nid) \
3633 for (i = first_active_region_index_in_nid(nid); i != -1; \
3634 i = next_active_region_index_in_nid(i, nid))
3637 * free_bootmem_with_active_regions - Call free_bootmem_node for each active range
3638 * @nid: The node to free memory on. If MAX_NUMNODES, all nodes are freed.
3639 * @max_low_pfn: The highest PFN that will be passed to free_bootmem_node
3641 * If an architecture guarantees that all ranges registered with
3642 * add_active_ranges() contain no holes and may be freed, this
3643 * this function may be used instead of calling free_bootmem() manually.
3645 void __init free_bootmem_with_active_regions(int nid,
3646 unsigned long max_low_pfn)
3648 int i;
3650 for_each_active_range_index_in_nid(i, nid) {
3651 unsigned long size_pages = 0;
3652 unsigned long end_pfn = early_node_map[i].end_pfn;
3654 if (early_node_map[i].start_pfn >= max_low_pfn)
3655 continue;
3657 if (end_pfn > max_low_pfn)
3658 end_pfn = max_low_pfn;
3660 size_pages = end_pfn - early_node_map[i].start_pfn;
3661 free_bootmem_node(NODE_DATA(early_node_map[i].nid),
3662 PFN_PHYS(early_node_map[i].start_pfn),
3663 size_pages << PAGE_SHIFT);
3667 int __init add_from_early_node_map(struct range *range, int az,
3668 int nr_range, int nid)
3670 int i;
3671 u64 start, end;
3673 /* need to go over early_node_map to find out good range for node */
3674 for_each_active_range_index_in_nid(i, nid) {
3675 start = early_node_map[i].start_pfn;
3676 end = early_node_map[i].end_pfn;
3677 nr_range = add_range(range, az, nr_range, start, end);
3679 return nr_range;
3682 #ifdef CONFIG_NO_BOOTMEM
3683 void * __init __alloc_memory_core_early(int nid, u64 size, u64 align,
3684 u64 goal, u64 limit)
3686 int i;
3687 void *ptr;
3689 if (limit > get_max_mapped())
3690 limit = get_max_mapped();
3692 /* need to go over early_node_map to find out good range for node */
3693 for_each_active_range_index_in_nid(i, nid) {
3694 u64 addr;
3695 u64 ei_start, ei_last;
3697 ei_last = early_node_map[i].end_pfn;
3698 ei_last <<= PAGE_SHIFT;
3699 ei_start = early_node_map[i].start_pfn;
3700 ei_start <<= PAGE_SHIFT;
3701 addr = find_early_area(ei_start, ei_last,
3702 goal, limit, size, align);
3704 if (addr == -1ULL)
3705 continue;
3708 ptr = phys_to_virt(addr);
3709 memset(ptr, 0, size);
3710 reserve_early_without_check(addr, addr + size, "BOOTMEM");
3712 * The min_count is set to 0 so that bootmem allocated blocks
3713 * are never reported as leaks.
3715 kmemleak_alloc(ptr, size, 0, 0);
3716 return ptr;
3719 return NULL;
3721 #endif
3724 void __init work_with_active_regions(int nid, work_fn_t work_fn, void *data)
3726 int i;
3727 int ret;
3729 for_each_active_range_index_in_nid(i, nid) {
3730 ret = work_fn(early_node_map[i].start_pfn,
3731 early_node_map[i].end_pfn, data);
3732 if (ret)
3733 break;
3737 * sparse_memory_present_with_active_regions - Call memory_present for each active range
3738 * @nid: The node to call memory_present for. If MAX_NUMNODES, all nodes will be used.
3740 * If an architecture guarantees that all ranges registered with
3741 * add_active_ranges() contain no holes and may be freed, this
3742 * function may be used instead of calling memory_present() manually.
3744 void __init sparse_memory_present_with_active_regions(int nid)
3746 int i;
3748 for_each_active_range_index_in_nid(i, nid)
3749 memory_present(early_node_map[i].nid,
3750 early_node_map[i].start_pfn,
3751 early_node_map[i].end_pfn);
3755 * get_pfn_range_for_nid - Return the start and end page frames for a node
3756 * @nid: The nid to return the range for. If MAX_NUMNODES, the min and max PFN are returned.
3757 * @start_pfn: Passed by reference. On return, it will have the node start_pfn.
3758 * @end_pfn: Passed by reference. On return, it will have the node end_pfn.
3760 * It returns the start and end page frame of a node based on information
3761 * provided by an arch calling add_active_range(). If called for a node
3762 * with no available memory, a warning is printed and the start and end
3763 * PFNs will be 0.
3765 void __meminit get_pfn_range_for_nid(unsigned int nid,
3766 unsigned long *start_pfn, unsigned long *end_pfn)
3768 int i;
3769 *start_pfn = -1UL;
3770 *end_pfn = 0;
3772 for_each_active_range_index_in_nid(i, nid) {
3773 *start_pfn = min(*start_pfn, early_node_map[i].start_pfn);
3774 *end_pfn = max(*end_pfn, early_node_map[i].end_pfn);
3777 if (*start_pfn == -1UL)
3778 *start_pfn = 0;
3782 * This finds a zone that can be used for ZONE_MOVABLE pages. The
3783 * assumption is made that zones within a node are ordered in monotonic
3784 * increasing memory addresses so that the "highest" populated zone is used
3786 static void __init find_usable_zone_for_movable(void)
3788 int zone_index;
3789 for (zone_index = MAX_NR_ZONES - 1; zone_index >= 0; zone_index--) {
3790 if (zone_index == ZONE_MOVABLE)
3791 continue;
3793 if (arch_zone_highest_possible_pfn[zone_index] >
3794 arch_zone_lowest_possible_pfn[zone_index])
3795 break;
3798 VM_BUG_ON(zone_index == -1);
3799 movable_zone = zone_index;
3803 * The zone ranges provided by the architecture do not include ZONE_MOVABLE
3804 * because it is sized independant of architecture. Unlike the other zones,
3805 * the starting point for ZONE_MOVABLE is not fixed. It may be different
3806 * in each node depending on the size of each node and how evenly kernelcore
3807 * is distributed. This helper function adjusts the zone ranges
3808 * provided by the architecture for a given node by using the end of the
3809 * highest usable zone for ZONE_MOVABLE. This preserves the assumption that
3810 * zones within a node are in order of monotonic increases memory addresses
3812 static void __meminit adjust_zone_range_for_zone_movable(int nid,
3813 unsigned long zone_type,
3814 unsigned long node_start_pfn,
3815 unsigned long node_end_pfn,
3816 unsigned long *zone_start_pfn,
3817 unsigned long *zone_end_pfn)
3819 /* Only adjust if ZONE_MOVABLE is on this node */
3820 if (zone_movable_pfn[nid]) {
3821 /* Size ZONE_MOVABLE */
3822 if (zone_type == ZONE_MOVABLE) {
3823 *zone_start_pfn = zone_movable_pfn[nid];
3824 *zone_end_pfn = min(node_end_pfn,
3825 arch_zone_highest_possible_pfn[movable_zone]);
3827 /* Adjust for ZONE_MOVABLE starting within this range */
3828 } else if (*zone_start_pfn < zone_movable_pfn[nid] &&
3829 *zone_end_pfn > zone_movable_pfn[nid]) {
3830 *zone_end_pfn = zone_movable_pfn[nid];
3832 /* Check if this whole range is within ZONE_MOVABLE */
3833 } else if (*zone_start_pfn >= zone_movable_pfn[nid])
3834 *zone_start_pfn = *zone_end_pfn;
3839 * Return the number of pages a zone spans in a node, including holes
3840 * present_pages = zone_spanned_pages_in_node() - zone_absent_pages_in_node()
3842 static unsigned long __meminit zone_spanned_pages_in_node(int nid,
3843 unsigned long zone_type,
3844 unsigned long *ignored)
3846 unsigned long node_start_pfn, node_end_pfn;
3847 unsigned long zone_start_pfn, zone_end_pfn;
3849 /* Get the start and end of the node and zone */
3850 get_pfn_range_for_nid(nid, &node_start_pfn, &node_end_pfn);
3851 zone_start_pfn = arch_zone_lowest_possible_pfn[zone_type];
3852 zone_end_pfn = arch_zone_highest_possible_pfn[zone_type];
3853 adjust_zone_range_for_zone_movable(nid, zone_type,
3854 node_start_pfn, node_end_pfn,
3855 &zone_start_pfn, &zone_end_pfn);
3857 /* Check that this node has pages within the zone's required range */
3858 if (zone_end_pfn < node_start_pfn || zone_start_pfn > node_end_pfn)
3859 return 0;
3861 /* Move the zone boundaries inside the node if necessary */
3862 zone_end_pfn = min(zone_end_pfn, node_end_pfn);
3863 zone_start_pfn = max(zone_start_pfn, node_start_pfn);
3865 /* Return the spanned pages */
3866 return zone_end_pfn - zone_start_pfn;
3870 * Return the number of holes in a range on a node. If nid is MAX_NUMNODES,
3871 * then all holes in the requested range will be accounted for.
3873 unsigned long __meminit __absent_pages_in_range(int nid,
3874 unsigned long range_start_pfn,
3875 unsigned long range_end_pfn)
3877 int i = 0;
3878 unsigned long prev_end_pfn = 0, hole_pages = 0;
3879 unsigned long start_pfn;
3881 /* Find the end_pfn of the first active range of pfns in the node */
3882 i = first_active_region_index_in_nid(nid);
3883 if (i == -1)
3884 return 0;
3886 prev_end_pfn = min(early_node_map[i].start_pfn, range_end_pfn);
3888 /* Account for ranges before physical memory on this node */
3889 if (early_node_map[i].start_pfn > range_start_pfn)
3890 hole_pages = prev_end_pfn - range_start_pfn;
3892 /* Find all holes for the zone within the node */
3893 for (; i != -1; i = next_active_region_index_in_nid(i, nid)) {
3895 /* No need to continue if prev_end_pfn is outside the zone */
3896 if (prev_end_pfn >= range_end_pfn)
3897 break;
3899 /* Make sure the end of the zone is not within the hole */
3900 start_pfn = min(early_node_map[i].start_pfn, range_end_pfn);
3901 prev_end_pfn = max(prev_end_pfn, range_start_pfn);
3903 /* Update the hole size cound and move on */
3904 if (start_pfn > range_start_pfn) {
3905 BUG_ON(prev_end_pfn > start_pfn);
3906 hole_pages += start_pfn - prev_end_pfn;
3908 prev_end_pfn = early_node_map[i].end_pfn;
3911 /* Account for ranges past physical memory on this node */
3912 if (range_end_pfn > prev_end_pfn)
3913 hole_pages += range_end_pfn -
3914 max(range_start_pfn, prev_end_pfn);
3916 return hole_pages;
3920 * absent_pages_in_range - Return number of page frames in holes within a range
3921 * @start_pfn: The start PFN to start searching for holes
3922 * @end_pfn: The end PFN to stop searching for holes
3924 * It returns the number of pages frames in memory holes within a range.
3926 unsigned long __init absent_pages_in_range(unsigned long start_pfn,
3927 unsigned long end_pfn)
3929 return __absent_pages_in_range(MAX_NUMNODES, start_pfn, end_pfn);
3932 /* Return the number of page frames in holes in a zone on a node */
3933 static unsigned long __meminit zone_absent_pages_in_node(int nid,
3934 unsigned long zone_type,
3935 unsigned long *ignored)
3937 unsigned long node_start_pfn, node_end_pfn;
3938 unsigned long zone_start_pfn, zone_end_pfn;
3940 get_pfn_range_for_nid(nid, &node_start_pfn, &node_end_pfn);
3941 zone_start_pfn = max(arch_zone_lowest_possible_pfn[zone_type],
3942 node_start_pfn);
3943 zone_end_pfn = min(arch_zone_highest_possible_pfn[zone_type],
3944 node_end_pfn);
3946 adjust_zone_range_for_zone_movable(nid, zone_type,
3947 node_start_pfn, node_end_pfn,
3948 &zone_start_pfn, &zone_end_pfn);
3949 return __absent_pages_in_range(nid, zone_start_pfn, zone_end_pfn);
3952 #else
3953 static inline unsigned long __meminit zone_spanned_pages_in_node(int nid,
3954 unsigned long zone_type,
3955 unsigned long *zones_size)
3957 return zones_size[zone_type];
3960 static inline unsigned long __meminit zone_absent_pages_in_node(int nid,
3961 unsigned long zone_type,
3962 unsigned long *zholes_size)
3964 if (!zholes_size)
3965 return 0;
3967 return zholes_size[zone_type];
3970 #endif
3972 static void __meminit calculate_node_totalpages(struct pglist_data *pgdat,
3973 unsigned long *zones_size, unsigned long *zholes_size)
3975 unsigned long realtotalpages, totalpages = 0;
3976 enum zone_type i;
3978 for (i = 0; i < MAX_NR_ZONES; i++)
3979 totalpages += zone_spanned_pages_in_node(pgdat->node_id, i,
3980 zones_size);
3981 pgdat->node_spanned_pages = totalpages;
3983 realtotalpages = totalpages;
3984 for (i = 0; i < MAX_NR_ZONES; i++)
3985 realtotalpages -=
3986 zone_absent_pages_in_node(pgdat->node_id, i,
3987 zholes_size);
3988 pgdat->node_present_pages = realtotalpages;
3989 printk(KERN_DEBUG "On node %d totalpages: %lu\n", pgdat->node_id,
3990 realtotalpages);
3993 #ifndef CONFIG_SPARSEMEM
3995 * Calculate the size of the zone->blockflags rounded to an unsigned long
3996 * Start by making sure zonesize is a multiple of pageblock_order by rounding
3997 * up. Then use 1 NR_PAGEBLOCK_BITS worth of bits per pageblock, finally
3998 * round what is now in bits to nearest long in bits, then return it in
3999 * bytes.
4001 static unsigned long __init usemap_size(unsigned long zonesize)
4003 unsigned long usemapsize;
4005 usemapsize = roundup(zonesize, pageblock_nr_pages);
4006 usemapsize = usemapsize >> pageblock_order;
4007 usemapsize *= NR_PAGEBLOCK_BITS;
4008 usemapsize = roundup(usemapsize, 8 * sizeof(unsigned long));
4010 return usemapsize / 8;
4013 static void __init setup_usemap(struct pglist_data *pgdat,
4014 struct zone *zone, unsigned long zonesize)
4016 unsigned long usemapsize = usemap_size(zonesize);
4017 zone->pageblock_flags = NULL;
4018 if (usemapsize)
4019 zone->pageblock_flags = alloc_bootmem_node(pgdat, usemapsize);
4021 #else
4022 static void inline setup_usemap(struct pglist_data *pgdat,
4023 struct zone *zone, unsigned long zonesize) {}
4024 #endif /* CONFIG_SPARSEMEM */
4026 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
4028 /* Return a sensible default order for the pageblock size. */
4029 static inline int pageblock_default_order(void)
4031 if (HPAGE_SHIFT > PAGE_SHIFT)
4032 return HUGETLB_PAGE_ORDER;
4034 return MAX_ORDER-1;
4037 /* Initialise the number of pages represented by NR_PAGEBLOCK_BITS */
4038 static inline void __init set_pageblock_order(unsigned int order)
4040 /* Check that pageblock_nr_pages has not already been setup */
4041 if (pageblock_order)
4042 return;
4045 * Assume the largest contiguous order of interest is a huge page.
4046 * This value may be variable depending on boot parameters on IA64
4048 pageblock_order = order;
4050 #else /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
4053 * When CONFIG_HUGETLB_PAGE_SIZE_VARIABLE is not set, set_pageblock_order()
4054 * and pageblock_default_order() are unused as pageblock_order is set
4055 * at compile-time. See include/linux/pageblock-flags.h for the values of
4056 * pageblock_order based on the kernel config
4058 static inline int pageblock_default_order(unsigned int order)
4060 return MAX_ORDER-1;
4062 #define set_pageblock_order(x) do {} while (0)
4064 #endif /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
4067 * Set up the zone data structures:
4068 * - mark all pages reserved
4069 * - mark all memory queues empty
4070 * - clear the memory bitmaps
4072 static void __paginginit free_area_init_core(struct pglist_data *pgdat,
4073 unsigned long *zones_size, unsigned long *zholes_size)
4075 enum zone_type j;
4076 int nid = pgdat->node_id;
4077 unsigned long zone_start_pfn = pgdat->node_start_pfn;
4078 int ret;
4080 pgdat_resize_init(pgdat);
4081 pgdat->nr_zones = 0;
4082 init_waitqueue_head(&pgdat->kswapd_wait);
4083 pgdat->kswapd_max_order = 0;
4084 pgdat_page_cgroup_init(pgdat);
4086 for (j = 0; j < MAX_NR_ZONES; j++) {
4087 struct zone *zone = pgdat->node_zones + j;
4088 unsigned long size, realsize, memmap_pages;
4089 enum lru_list l;
4091 size = zone_spanned_pages_in_node(nid, j, zones_size);
4092 realsize = size - zone_absent_pages_in_node(nid, j,
4093 zholes_size);
4096 * Adjust realsize so that it accounts for how much memory
4097 * is used by this zone for memmap. This affects the watermark
4098 * and per-cpu initialisations
4100 memmap_pages =
4101 PAGE_ALIGN(size * sizeof(struct page)) >> PAGE_SHIFT;
4102 if (realsize >= memmap_pages) {
4103 realsize -= memmap_pages;
4104 if (memmap_pages)
4105 printk(KERN_DEBUG
4106 " %s zone: %lu pages used for memmap\n",
4107 zone_names[j], memmap_pages);
4108 } else
4109 printk(KERN_WARNING
4110 " %s zone: %lu pages exceeds realsize %lu\n",
4111 zone_names[j], memmap_pages, realsize);
4113 /* Account for reserved pages */
4114 if (j == 0 && realsize > dma_reserve) {
4115 realsize -= dma_reserve;
4116 printk(KERN_DEBUG " %s zone: %lu pages reserved\n",
4117 zone_names[0], dma_reserve);
4120 if (!is_highmem_idx(j))
4121 nr_kernel_pages += realsize;
4122 nr_all_pages += realsize;
4124 zone->spanned_pages = size;
4125 zone->present_pages = realsize;
4126 #ifdef CONFIG_NUMA
4127 zone->node = nid;
4128 zone->min_unmapped_pages = (realsize*sysctl_min_unmapped_ratio)
4129 / 100;
4130 zone->min_slab_pages = (realsize * sysctl_min_slab_ratio) / 100;
4131 #endif
4132 zone->name = zone_names[j];
4133 spin_lock_init(&zone->lock);
4134 spin_lock_init(&zone->lru_lock);
4135 zone_seqlock_init(zone);
4136 zone->zone_pgdat = pgdat;
4138 zone_pcp_init(zone);
4139 for_each_lru(l) {
4140 INIT_LIST_HEAD(&zone->lru[l].list);
4141 zone->reclaim_stat.nr_saved_scan[l] = 0;
4143 zone->reclaim_stat.recent_rotated[0] = 0;
4144 zone->reclaim_stat.recent_rotated[1] = 0;
4145 zone->reclaim_stat.recent_scanned[0] = 0;
4146 zone->reclaim_stat.recent_scanned[1] = 0;
4147 zap_zone_vm_stats(zone);
4148 zone->flags = 0;
4149 if (!size)
4150 continue;
4152 set_pageblock_order(pageblock_default_order());
4153 setup_usemap(pgdat, zone, size);
4154 ret = init_currently_empty_zone(zone, zone_start_pfn,
4155 size, MEMMAP_EARLY);
4156 BUG_ON(ret);
4157 memmap_init(size, nid, j, zone_start_pfn);
4158 zone_start_pfn += size;
4162 static void __init_refok alloc_node_mem_map(struct pglist_data *pgdat)
4164 /* Skip empty nodes */
4165 if (!pgdat->node_spanned_pages)
4166 return;
4168 #ifdef CONFIG_FLAT_NODE_MEM_MAP
4169 /* ia64 gets its own node_mem_map, before this, without bootmem */
4170 if (!pgdat->node_mem_map) {
4171 unsigned long size, start, end;
4172 struct page *map;
4175 * The zone's endpoints aren't required to be MAX_ORDER
4176 * aligned but the node_mem_map endpoints must be in order
4177 * for the buddy allocator to function correctly.
4179 start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1);
4180 end = pgdat->node_start_pfn + pgdat->node_spanned_pages;
4181 end = ALIGN(end, MAX_ORDER_NR_PAGES);
4182 size = (end - start) * sizeof(struct page);
4183 map = alloc_remap(pgdat->node_id, size);
4184 if (!map)
4185 map = alloc_bootmem_node(pgdat, size);
4186 pgdat->node_mem_map = map + (pgdat->node_start_pfn - start);
4188 #ifndef CONFIG_NEED_MULTIPLE_NODES
4190 * With no DISCONTIG, the global mem_map is just set as node 0's
4192 if (pgdat == NODE_DATA(0)) {
4193 mem_map = NODE_DATA(0)->node_mem_map;
4194 #ifdef CONFIG_ARCH_POPULATES_NODE_MAP
4195 if (page_to_pfn(mem_map) != pgdat->node_start_pfn)
4196 mem_map -= (pgdat->node_start_pfn - ARCH_PFN_OFFSET);
4197 #endif /* CONFIG_ARCH_POPULATES_NODE_MAP */
4199 #endif
4200 #endif /* CONFIG_FLAT_NODE_MEM_MAP */
4203 void __paginginit free_area_init_node(int nid, unsigned long *zones_size,
4204 unsigned long node_start_pfn, unsigned long *zholes_size)
4206 pg_data_t *pgdat = NODE_DATA(nid);
4208 pgdat->node_id = nid;
4209 pgdat->node_start_pfn = node_start_pfn;
4210 calculate_node_totalpages(pgdat, zones_size, zholes_size);
4212 alloc_node_mem_map(pgdat);
4213 #ifdef CONFIG_FLAT_NODE_MEM_MAP
4214 printk(KERN_DEBUG "free_area_init_node: node %d, pgdat %08lx, node_mem_map %08lx\n",
4215 nid, (unsigned long)pgdat,
4216 (unsigned long)pgdat->node_mem_map);
4217 #endif
4219 free_area_init_core(pgdat, zones_size, zholes_size);
4222 #ifdef CONFIG_ARCH_POPULATES_NODE_MAP
4224 #if MAX_NUMNODES > 1
4226 * Figure out the number of possible node ids.
4228 static void __init setup_nr_node_ids(void)
4230 unsigned int node;
4231 unsigned int highest = 0;
4233 for_each_node_mask(node, node_possible_map)
4234 highest = node;
4235 nr_node_ids = highest + 1;
4237 #else
4238 static inline void setup_nr_node_ids(void)
4241 #endif
4244 * add_active_range - Register a range of PFNs backed by physical memory
4245 * @nid: The node ID the range resides on
4246 * @start_pfn: The start PFN of the available physical memory
4247 * @end_pfn: The end PFN of the available physical memory
4249 * These ranges are stored in an early_node_map[] and later used by
4250 * free_area_init_nodes() to calculate zone sizes and holes. If the
4251 * range spans a memory hole, it is up to the architecture to ensure
4252 * the memory is not freed by the bootmem allocator. If possible
4253 * the range being registered will be merged with existing ranges.
4255 void __init add_active_range(unsigned int nid, unsigned long start_pfn,
4256 unsigned long end_pfn)
4258 int i;
4260 mminit_dprintk(MMINIT_TRACE, "memory_register",
4261 "Entering add_active_range(%d, %#lx, %#lx) "
4262 "%d entries of %d used\n",
4263 nid, start_pfn, end_pfn,
4264 nr_nodemap_entries, MAX_ACTIVE_REGIONS);
4266 mminit_validate_memmodel_limits(&start_pfn, &end_pfn);
4268 /* Merge with existing active regions if possible */
4269 for (i = 0; i < nr_nodemap_entries; i++) {
4270 if (early_node_map[i].nid != nid)
4271 continue;
4273 /* Skip if an existing region covers this new one */
4274 if (start_pfn >= early_node_map[i].start_pfn &&
4275 end_pfn <= early_node_map[i].end_pfn)
4276 return;
4278 /* Merge forward if suitable */
4279 if (start_pfn <= early_node_map[i].end_pfn &&
4280 end_pfn > early_node_map[i].end_pfn) {
4281 early_node_map[i].end_pfn = end_pfn;
4282 return;
4285 /* Merge backward if suitable */
4286 if (start_pfn < early_node_map[i].start_pfn &&
4287 end_pfn >= early_node_map[i].start_pfn) {
4288 early_node_map[i].start_pfn = start_pfn;
4289 return;
4293 /* Check that early_node_map is large enough */
4294 if (i >= MAX_ACTIVE_REGIONS) {
4295 printk(KERN_CRIT "More than %d memory regions, truncating\n",
4296 MAX_ACTIVE_REGIONS);
4297 return;
4300 early_node_map[i].nid = nid;
4301 early_node_map[i].start_pfn = start_pfn;
4302 early_node_map[i].end_pfn = end_pfn;
4303 nr_nodemap_entries = i + 1;
4307 * remove_active_range - Shrink an existing registered range of PFNs
4308 * @nid: The node id the range is on that should be shrunk
4309 * @start_pfn: The new PFN of the range
4310 * @end_pfn: The new PFN of the range
4312 * i386 with NUMA use alloc_remap() to store a node_mem_map on a local node.
4313 * The map is kept near the end physical page range that has already been
4314 * registered. This function allows an arch to shrink an existing registered
4315 * range.
4317 void __init remove_active_range(unsigned int nid, unsigned long start_pfn,
4318 unsigned long end_pfn)
4320 int i, j;
4321 int removed = 0;
4323 printk(KERN_DEBUG "remove_active_range (%d, %lu, %lu)\n",
4324 nid, start_pfn, end_pfn);
4326 /* Find the old active region end and shrink */
4327 for_each_active_range_index_in_nid(i, nid) {
4328 if (early_node_map[i].start_pfn >= start_pfn &&
4329 early_node_map[i].end_pfn <= end_pfn) {
4330 /* clear it */
4331 early_node_map[i].start_pfn = 0;
4332 early_node_map[i].end_pfn = 0;
4333 removed = 1;
4334 continue;
4336 if (early_node_map[i].start_pfn < start_pfn &&
4337 early_node_map[i].end_pfn > start_pfn) {
4338 unsigned long temp_end_pfn = early_node_map[i].end_pfn;
4339 early_node_map[i].end_pfn = start_pfn;
4340 if (temp_end_pfn > end_pfn)
4341 add_active_range(nid, end_pfn, temp_end_pfn);
4342 continue;
4344 if (early_node_map[i].start_pfn >= start_pfn &&
4345 early_node_map[i].end_pfn > end_pfn &&
4346 early_node_map[i].start_pfn < end_pfn) {
4347 early_node_map[i].start_pfn = end_pfn;
4348 continue;
4352 if (!removed)
4353 return;
4355 /* remove the blank ones */
4356 for (i = nr_nodemap_entries - 1; i > 0; i--) {
4357 if (early_node_map[i].nid != nid)
4358 continue;
4359 if (early_node_map[i].end_pfn)
4360 continue;
4361 /* we found it, get rid of it */
4362 for (j = i; j < nr_nodemap_entries - 1; j++)
4363 memcpy(&early_node_map[j], &early_node_map[j+1],
4364 sizeof(early_node_map[j]));
4365 j = nr_nodemap_entries - 1;
4366 memset(&early_node_map[j], 0, sizeof(early_node_map[j]));
4367 nr_nodemap_entries--;
4372 * remove_all_active_ranges - Remove all currently registered regions
4374 * During discovery, it may be found that a table like SRAT is invalid
4375 * and an alternative discovery method must be used. This function removes
4376 * all currently registered regions.
4378 void __init remove_all_active_ranges(void)
4380 memset(early_node_map, 0, sizeof(early_node_map));
4381 nr_nodemap_entries = 0;
4384 /* Compare two active node_active_regions */
4385 static int __init cmp_node_active_region(const void *a, const void *b)
4387 struct node_active_region *arange = (struct node_active_region *)a;
4388 struct node_active_region *brange = (struct node_active_region *)b;
4390 /* Done this way to avoid overflows */
4391 if (arange->start_pfn > brange->start_pfn)
4392 return 1;
4393 if (arange->start_pfn < brange->start_pfn)
4394 return -1;
4396 return 0;
4399 /* sort the node_map by start_pfn */
4400 void __init sort_node_map(void)
4402 sort(early_node_map, (size_t)nr_nodemap_entries,
4403 sizeof(struct node_active_region),
4404 cmp_node_active_region, NULL);
4407 /* Find the lowest pfn for a node */
4408 static unsigned long __init find_min_pfn_for_node(int nid)
4410 int i;
4411 unsigned long min_pfn = ULONG_MAX;
4413 /* Assuming a sorted map, the first range found has the starting pfn */
4414 for_each_active_range_index_in_nid(i, nid)
4415 min_pfn = min(min_pfn, early_node_map[i].start_pfn);
4417 if (min_pfn == ULONG_MAX) {
4418 printk(KERN_WARNING
4419 "Could not find start_pfn for node %d\n", nid);
4420 return 0;
4423 return min_pfn;
4427 * find_min_pfn_with_active_regions - Find the minimum PFN registered
4429 * It returns the minimum PFN based on information provided via
4430 * add_active_range().
4432 unsigned long __init find_min_pfn_with_active_regions(void)
4434 return find_min_pfn_for_node(MAX_NUMNODES);
4438 * early_calculate_totalpages()
4439 * Sum pages in active regions for movable zone.
4440 * Populate N_HIGH_MEMORY for calculating usable_nodes.
4442 static unsigned long __init early_calculate_totalpages(void)
4444 int i;
4445 unsigned long totalpages = 0;
4447 for (i = 0; i < nr_nodemap_entries; i++) {
4448 unsigned long pages = early_node_map[i].end_pfn -
4449 early_node_map[i].start_pfn;
4450 totalpages += pages;
4451 if (pages)
4452 node_set_state(early_node_map[i].nid, N_HIGH_MEMORY);
4454 return totalpages;
4458 * Find the PFN the Movable zone begins in each node. Kernel memory
4459 * is spread evenly between nodes as long as the nodes have enough
4460 * memory. When they don't, some nodes will have more kernelcore than
4461 * others
4463 static void __init find_zone_movable_pfns_for_nodes(unsigned long *movable_pfn)
4465 int i, nid;
4466 unsigned long usable_startpfn;
4467 unsigned long kernelcore_node, kernelcore_remaining;
4468 /* save the state before borrow the nodemask */
4469 nodemask_t saved_node_state = node_states[N_HIGH_MEMORY];
4470 unsigned long totalpages = early_calculate_totalpages();
4471 int usable_nodes = nodes_weight(node_states[N_HIGH_MEMORY]);
4474 * If movablecore was specified, calculate what size of
4475 * kernelcore that corresponds so that memory usable for
4476 * any allocation type is evenly spread. If both kernelcore
4477 * and movablecore are specified, then the value of kernelcore
4478 * will be used for required_kernelcore if it's greater than
4479 * what movablecore would have allowed.
4481 if (required_movablecore) {
4482 unsigned long corepages;
4485 * Round-up so that ZONE_MOVABLE is at least as large as what
4486 * was requested by the user
4488 required_movablecore =
4489 roundup(required_movablecore, MAX_ORDER_NR_PAGES);
4490 corepages = totalpages - required_movablecore;
4492 required_kernelcore = max(required_kernelcore, corepages);
4495 /* If kernelcore was not specified, there is no ZONE_MOVABLE */
4496 if (!required_kernelcore)
4497 goto out;
4499 /* usable_startpfn is the lowest possible pfn ZONE_MOVABLE can be at */
4500 find_usable_zone_for_movable();
4501 usable_startpfn = arch_zone_lowest_possible_pfn[movable_zone];
4503 restart:
4504 /* Spread kernelcore memory as evenly as possible throughout nodes */
4505 kernelcore_node = required_kernelcore / usable_nodes;
4506 for_each_node_state(nid, N_HIGH_MEMORY) {
4508 * Recalculate kernelcore_node if the division per node
4509 * now exceeds what is necessary to satisfy the requested
4510 * amount of memory for the kernel
4512 if (required_kernelcore < kernelcore_node)
4513 kernelcore_node = required_kernelcore / usable_nodes;
4516 * As the map is walked, we track how much memory is usable
4517 * by the kernel using kernelcore_remaining. When it is
4518 * 0, the rest of the node is usable by ZONE_MOVABLE
4520 kernelcore_remaining = kernelcore_node;
4522 /* Go through each range of PFNs within this node */
4523 for_each_active_range_index_in_nid(i, nid) {
4524 unsigned long start_pfn, end_pfn;
4525 unsigned long size_pages;
4527 start_pfn = max(early_node_map[i].start_pfn,
4528 zone_movable_pfn[nid]);
4529 end_pfn = early_node_map[i].end_pfn;
4530 if (start_pfn >= end_pfn)
4531 continue;
4533 /* Account for what is only usable for kernelcore */
4534 if (start_pfn < usable_startpfn) {
4535 unsigned long kernel_pages;
4536 kernel_pages = min(end_pfn, usable_startpfn)
4537 - start_pfn;
4539 kernelcore_remaining -= min(kernel_pages,
4540 kernelcore_remaining);
4541 required_kernelcore -= min(kernel_pages,
4542 required_kernelcore);
4544 /* Continue if range is now fully accounted */
4545 if (end_pfn <= usable_startpfn) {
4548 * Push zone_movable_pfn to the end so
4549 * that if we have to rebalance
4550 * kernelcore across nodes, we will
4551 * not double account here
4553 zone_movable_pfn[nid] = end_pfn;
4554 continue;
4556 start_pfn = usable_startpfn;
4560 * The usable PFN range for ZONE_MOVABLE is from
4561 * start_pfn->end_pfn. Calculate size_pages as the
4562 * number of pages used as kernelcore
4564 size_pages = end_pfn - start_pfn;
4565 if (size_pages > kernelcore_remaining)
4566 size_pages = kernelcore_remaining;
4567 zone_movable_pfn[nid] = start_pfn + size_pages;
4570 * Some kernelcore has been met, update counts and
4571 * break if the kernelcore for this node has been
4572 * satisified
4574 required_kernelcore -= min(required_kernelcore,
4575 size_pages);
4576 kernelcore_remaining -= size_pages;
4577 if (!kernelcore_remaining)
4578 break;
4583 * If there is still required_kernelcore, we do another pass with one
4584 * less node in the count. This will push zone_movable_pfn[nid] further
4585 * along on the nodes that still have memory until kernelcore is
4586 * satisified
4588 usable_nodes--;
4589 if (usable_nodes && required_kernelcore > usable_nodes)
4590 goto restart;
4592 /* Align start of ZONE_MOVABLE on all nids to MAX_ORDER_NR_PAGES */
4593 for (nid = 0; nid < MAX_NUMNODES; nid++)
4594 zone_movable_pfn[nid] =
4595 roundup(zone_movable_pfn[nid], MAX_ORDER_NR_PAGES);
4597 out:
4598 /* restore the node_state */
4599 node_states[N_HIGH_MEMORY] = saved_node_state;
4602 /* Any regular memory on that node ? */
4603 static void check_for_regular_memory(pg_data_t *pgdat)
4605 #ifdef CONFIG_HIGHMEM
4606 enum zone_type zone_type;
4608 for (zone_type = 0; zone_type <= ZONE_NORMAL; zone_type++) {
4609 struct zone *zone = &pgdat->node_zones[zone_type];
4610 if (zone->present_pages)
4611 node_set_state(zone_to_nid(zone), N_NORMAL_MEMORY);
4613 #endif
4617 * free_area_init_nodes - Initialise all pg_data_t and zone data
4618 * @max_zone_pfn: an array of max PFNs for each zone
4620 * This will call free_area_init_node() for each active node in the system.
4621 * Using the page ranges provided by add_active_range(), the size of each
4622 * zone in each node and their holes is calculated. If the maximum PFN
4623 * between two adjacent zones match, it is assumed that the zone is empty.
4624 * For example, if arch_max_dma_pfn == arch_max_dma32_pfn, it is assumed
4625 * that arch_max_dma32_pfn has no pages. It is also assumed that a zone
4626 * starts where the previous one ended. For example, ZONE_DMA32 starts
4627 * at arch_max_dma_pfn.
4629 void __init free_area_init_nodes(unsigned long *max_zone_pfn)
4631 unsigned long nid;
4632 int i;
4634 /* Sort early_node_map as initialisation assumes it is sorted */
4635 sort_node_map();
4637 /* Record where the zone boundaries are */
4638 memset(arch_zone_lowest_possible_pfn, 0,
4639 sizeof(arch_zone_lowest_possible_pfn));
4640 memset(arch_zone_highest_possible_pfn, 0,
4641 sizeof(arch_zone_highest_possible_pfn));
4642 arch_zone_lowest_possible_pfn[0] = find_min_pfn_with_active_regions();
4643 arch_zone_highest_possible_pfn[0] = max_zone_pfn[0];
4644 for (i = 1; i < MAX_NR_ZONES; i++) {
4645 if (i == ZONE_MOVABLE)
4646 continue;
4647 arch_zone_lowest_possible_pfn[i] =
4648 arch_zone_highest_possible_pfn[i-1];
4649 arch_zone_highest_possible_pfn[i] =
4650 max(max_zone_pfn[i], arch_zone_lowest_possible_pfn[i]);
4652 arch_zone_lowest_possible_pfn[ZONE_MOVABLE] = 0;
4653 arch_zone_highest_possible_pfn[ZONE_MOVABLE] = 0;
4655 /* Find the PFNs that ZONE_MOVABLE begins at in each node */
4656 memset(zone_movable_pfn, 0, sizeof(zone_movable_pfn));
4657 find_zone_movable_pfns_for_nodes(zone_movable_pfn);
4659 /* Print out the zone ranges */
4660 printk("Zone PFN ranges:\n");
4661 for (i = 0; i < MAX_NR_ZONES; i++) {
4662 if (i == ZONE_MOVABLE)
4663 continue;
4664 printk(" %-8s ", zone_names[i]);
4665 if (arch_zone_lowest_possible_pfn[i] ==
4666 arch_zone_highest_possible_pfn[i])
4667 printk("empty\n");
4668 else
4669 printk("%0#10lx -> %0#10lx\n",
4670 arch_zone_lowest_possible_pfn[i],
4671 arch_zone_highest_possible_pfn[i]);
4674 /* Print out the PFNs ZONE_MOVABLE begins at in each node */
4675 printk("Movable zone start PFN for each node\n");
4676 for (i = 0; i < MAX_NUMNODES; i++) {
4677 if (zone_movable_pfn[i])
4678 printk(" Node %d: %lu\n", i, zone_movable_pfn[i]);
4681 /* Print out the early_node_map[] */
4682 printk("early_node_map[%d] active PFN ranges\n", nr_nodemap_entries);
4683 for (i = 0; i < nr_nodemap_entries; i++)
4684 printk(" %3d: %0#10lx -> %0#10lx\n", early_node_map[i].nid,
4685 early_node_map[i].start_pfn,
4686 early_node_map[i].end_pfn);
4688 /* Initialise every node */
4689 mminit_verify_pageflags_layout();
4690 setup_nr_node_ids();
4691 for_each_online_node(nid) {
4692 pg_data_t *pgdat = NODE_DATA(nid);
4693 free_area_init_node(nid, NULL,
4694 find_min_pfn_for_node(nid), NULL);
4696 /* Any memory on that node */
4697 if (pgdat->node_present_pages)
4698 node_set_state(nid, N_HIGH_MEMORY);
4699 check_for_regular_memory(pgdat);
4703 static int __init cmdline_parse_core(char *p, unsigned long *core)
4705 unsigned long long coremem;
4706 if (!p)
4707 return -EINVAL;
4709 coremem = memparse(p, &p);
4710 *core = coremem >> PAGE_SHIFT;
4712 /* Paranoid check that UL is enough for the coremem value */
4713 WARN_ON((coremem >> PAGE_SHIFT) > ULONG_MAX);
4715 return 0;
4719 * kernelcore=size sets the amount of memory for use for allocations that
4720 * cannot be reclaimed or migrated.
4722 static int __init cmdline_parse_kernelcore(char *p)
4724 return cmdline_parse_core(p, &required_kernelcore);
4728 * movablecore=size sets the amount of memory for use for allocations that
4729 * can be reclaimed or migrated.
4731 static int __init cmdline_parse_movablecore(char *p)
4733 return cmdline_parse_core(p, &required_movablecore);
4736 early_param("kernelcore", cmdline_parse_kernelcore);
4737 early_param("movablecore", cmdline_parse_movablecore);
4739 #endif /* CONFIG_ARCH_POPULATES_NODE_MAP */
4742 * set_dma_reserve - set the specified number of pages reserved in the first zone
4743 * @new_dma_reserve: The number of pages to mark reserved
4745 * The per-cpu batchsize and zone watermarks are determined by present_pages.
4746 * In the DMA zone, a significant percentage may be consumed by kernel image
4747 * and other unfreeable allocations which can skew the watermarks badly. This
4748 * function may optionally be used to account for unfreeable pages in the
4749 * first zone (e.g., ZONE_DMA). The effect will be lower watermarks and
4750 * smaller per-cpu batchsize.
4752 void __init set_dma_reserve(unsigned long new_dma_reserve)
4754 dma_reserve = new_dma_reserve;
4757 #ifndef CONFIG_NEED_MULTIPLE_NODES
4758 struct pglist_data __refdata contig_page_data = {
4759 #ifndef CONFIG_NO_BOOTMEM
4760 .bdata = &bootmem_node_data[0]
4761 #endif
4763 EXPORT_SYMBOL(contig_page_data);
4764 #endif
4766 void __init free_area_init(unsigned long *zones_size)
4768 free_area_init_node(0, zones_size,
4769 __pa(PAGE_OFFSET) >> PAGE_SHIFT, NULL);
4772 static int page_alloc_cpu_notify(struct notifier_block *self,
4773 unsigned long action, void *hcpu)
4775 int cpu = (unsigned long)hcpu;
4777 if (action == CPU_DEAD || action == CPU_DEAD_FROZEN) {
4778 drain_pages(cpu);
4781 * Spill the event counters of the dead processor
4782 * into the current processors event counters.
4783 * This artificially elevates the count of the current
4784 * processor.
4786 vm_events_fold_cpu(cpu);
4789 * Zero the differential counters of the dead processor
4790 * so that the vm statistics are consistent.
4792 * This is only okay since the processor is dead and cannot
4793 * race with what we are doing.
4795 refresh_cpu_vm_stats(cpu);
4797 return NOTIFY_OK;
4800 void __init page_alloc_init(void)
4802 hotcpu_notifier(page_alloc_cpu_notify, 0);
4806 * calculate_totalreserve_pages - called when sysctl_lower_zone_reserve_ratio
4807 * or min_free_kbytes changes.
4809 static void calculate_totalreserve_pages(void)
4811 struct pglist_data *pgdat;
4812 unsigned long reserve_pages = 0;
4813 enum zone_type i, j;
4815 for_each_online_pgdat(pgdat) {
4816 for (i = 0; i < MAX_NR_ZONES; i++) {
4817 struct zone *zone = pgdat->node_zones + i;
4818 unsigned long max = 0;
4820 /* Find valid and maximum lowmem_reserve in the zone */
4821 for (j = i; j < MAX_NR_ZONES; j++) {
4822 if (zone->lowmem_reserve[j] > max)
4823 max = zone->lowmem_reserve[j];
4826 /* we treat the high watermark as reserved pages. */
4827 max += high_wmark_pages(zone);
4829 if (max > zone->present_pages)
4830 max = zone->present_pages;
4831 reserve_pages += max;
4834 totalreserve_pages = reserve_pages;
4838 * setup_per_zone_lowmem_reserve - called whenever
4839 * sysctl_lower_zone_reserve_ratio changes. Ensures that each zone
4840 * has a correct pages reserved value, so an adequate number of
4841 * pages are left in the zone after a successful __alloc_pages().
4843 static void setup_per_zone_lowmem_reserve(void)
4845 struct pglist_data *pgdat;
4846 enum zone_type j, idx;
4848 for_each_online_pgdat(pgdat) {
4849 for (j = 0; j < MAX_NR_ZONES; j++) {
4850 struct zone *zone = pgdat->node_zones + j;
4851 unsigned long present_pages = zone->present_pages;
4853 zone->lowmem_reserve[j] = 0;
4855 idx = j;
4856 while (idx) {
4857 struct zone *lower_zone;
4859 idx--;
4861 if (sysctl_lowmem_reserve_ratio[idx] < 1)
4862 sysctl_lowmem_reserve_ratio[idx] = 1;
4864 lower_zone = pgdat->node_zones + idx;
4865 lower_zone->lowmem_reserve[j] = present_pages /
4866 sysctl_lowmem_reserve_ratio[idx];
4867 present_pages += lower_zone->present_pages;
4872 /* update totalreserve_pages */
4873 calculate_totalreserve_pages();
4877 * setup_per_zone_wmarks - called when min_free_kbytes changes
4878 * or when memory is hot-{added|removed}
4880 * Ensures that the watermark[min,low,high] values for each zone are set
4881 * correctly with respect to min_free_kbytes.
4883 void setup_per_zone_wmarks(void)
4885 unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
4886 unsigned long lowmem_pages = 0;
4887 struct zone *zone;
4888 unsigned long flags;
4890 /* Calculate total number of !ZONE_HIGHMEM pages */
4891 for_each_zone(zone) {
4892 if (!is_highmem(zone))
4893 lowmem_pages += zone->present_pages;
4896 for_each_zone(zone) {
4897 u64 tmp;
4899 spin_lock_irqsave(&zone->lock, flags);
4900 tmp = (u64)pages_min * zone->present_pages;
4901 do_div(tmp, lowmem_pages);
4902 if (is_highmem(zone)) {
4904 * __GFP_HIGH and PF_MEMALLOC allocations usually don't
4905 * need highmem pages, so cap pages_min to a small
4906 * value here.
4908 * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN)
4909 * deltas controls asynch page reclaim, and so should
4910 * not be capped for highmem.
4912 int min_pages;
4914 min_pages = zone->present_pages / 1024;
4915 if (min_pages < SWAP_CLUSTER_MAX)
4916 min_pages = SWAP_CLUSTER_MAX;
4917 if (min_pages > 128)
4918 min_pages = 128;
4919 zone->watermark[WMARK_MIN] = min_pages;
4920 } else {
4922 * If it's a lowmem zone, reserve a number of pages
4923 * proportionate to the zone's size.
4925 zone->watermark[WMARK_MIN] = tmp;
4928 zone->watermark[WMARK_LOW] = min_wmark_pages(zone) + (tmp >> 2);
4929 zone->watermark[WMARK_HIGH] = min_wmark_pages(zone) + (tmp >> 1);
4930 setup_zone_migrate_reserve(zone);
4931 spin_unlock_irqrestore(&zone->lock, flags);
4934 /* update totalreserve_pages */
4935 calculate_totalreserve_pages();
4939 * The inactive anon list should be small enough that the VM never has to
4940 * do too much work, but large enough that each inactive page has a chance
4941 * to be referenced again before it is swapped out.
4943 * The inactive_anon ratio is the target ratio of ACTIVE_ANON to
4944 * INACTIVE_ANON pages on this zone's LRU, maintained by the
4945 * pageout code. A zone->inactive_ratio of 3 means 3:1 or 25% of
4946 * the anonymous pages are kept on the inactive list.
4948 * total target max
4949 * memory ratio inactive anon
4950 * -------------------------------------
4951 * 10MB 1 5MB
4952 * 100MB 1 50MB
4953 * 1GB 3 250MB
4954 * 10GB 10 0.9GB
4955 * 100GB 31 3GB
4956 * 1TB 101 10GB
4957 * 10TB 320 32GB
4959 void calculate_zone_inactive_ratio(struct zone *zone)
4961 unsigned int gb, ratio;
4963 /* Zone size in gigabytes */
4964 gb = zone->present_pages >> (30 - PAGE_SHIFT);
4965 if (gb)
4966 ratio = int_sqrt(10 * gb);
4967 else
4968 ratio = 1;
4970 zone->inactive_ratio = ratio;
4973 static void __init setup_per_zone_inactive_ratio(void)
4975 struct zone *zone;
4977 for_each_zone(zone)
4978 calculate_zone_inactive_ratio(zone);
4982 * Initialise min_free_kbytes.
4984 * For small machines we want it small (128k min). For large machines
4985 * we want it large (64MB max). But it is not linear, because network
4986 * bandwidth does not increase linearly with machine size. We use
4988 * min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
4989 * min_free_kbytes = sqrt(lowmem_kbytes * 16)
4991 * which yields
4993 * 16MB: 512k
4994 * 32MB: 724k
4995 * 64MB: 1024k
4996 * 128MB: 1448k
4997 * 256MB: 2048k
4998 * 512MB: 2896k
4999 * 1024MB: 4096k
5000 * 2048MB: 5792k
5001 * 4096MB: 8192k
5002 * 8192MB: 11584k
5003 * 16384MB: 16384k
5005 static int __init init_per_zone_wmark_min(void)
5007 unsigned long lowmem_kbytes;
5009 lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
5011 min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
5012 if (min_free_kbytes < 128)
5013 min_free_kbytes = 128;
5014 if (min_free_kbytes > 65536)
5015 min_free_kbytes = 65536;
5016 setup_per_zone_wmarks();
5017 setup_per_zone_lowmem_reserve();
5018 setup_per_zone_inactive_ratio();
5019 return 0;
5021 module_init(init_per_zone_wmark_min)
5024 * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
5025 * that we can call two helper functions whenever min_free_kbytes
5026 * changes.
5028 int min_free_kbytes_sysctl_handler(ctl_table *table, int write,
5029 void __user *buffer, size_t *length, loff_t *ppos)
5031 proc_dointvec(table, write, buffer, length, ppos);
5032 if (write)
5033 setup_per_zone_wmarks();
5034 return 0;
5037 #ifdef CONFIG_NUMA
5038 int sysctl_min_unmapped_ratio_sysctl_handler(ctl_table *table, int write,
5039 void __user *buffer, size_t *length, loff_t *ppos)
5041 struct zone *zone;
5042 int rc;
5044 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
5045 if (rc)
5046 return rc;
5048 for_each_zone(zone)
5049 zone->min_unmapped_pages = (zone->present_pages *
5050 sysctl_min_unmapped_ratio) / 100;
5051 return 0;
5054 int sysctl_min_slab_ratio_sysctl_handler(ctl_table *table, int write,
5055 void __user *buffer, size_t *length, loff_t *ppos)
5057 struct zone *zone;
5058 int rc;
5060 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
5061 if (rc)
5062 return rc;
5064 for_each_zone(zone)
5065 zone->min_slab_pages = (zone->present_pages *
5066 sysctl_min_slab_ratio) / 100;
5067 return 0;
5069 #endif
5072 * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
5073 * proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
5074 * whenever sysctl_lowmem_reserve_ratio changes.
5076 * The reserve ratio obviously has absolutely no relation with the
5077 * minimum watermarks. The lowmem reserve ratio can only make sense
5078 * if in function of the boot time zone sizes.
5080 int lowmem_reserve_ratio_sysctl_handler(ctl_table *table, int write,
5081 void __user *buffer, size_t *length, loff_t *ppos)
5083 proc_dointvec_minmax(table, write, buffer, length, ppos);
5084 setup_per_zone_lowmem_reserve();
5085 return 0;
5089 * percpu_pagelist_fraction - changes the pcp->high for each zone on each
5090 * cpu. It is the fraction of total pages in each zone that a hot per cpu pagelist
5091 * can have before it gets flushed back to buddy allocator.
5094 int percpu_pagelist_fraction_sysctl_handler(ctl_table *table, int write,
5095 void __user *buffer, size_t *length, loff_t *ppos)
5097 struct zone *zone;
5098 unsigned int cpu;
5099 int ret;
5101 ret = proc_dointvec_minmax(table, write, buffer, length, ppos);
5102 if (!write || (ret == -EINVAL))
5103 return ret;
5104 for_each_populated_zone(zone) {
5105 for_each_possible_cpu(cpu) {
5106 unsigned long high;
5107 high = zone->present_pages / percpu_pagelist_fraction;
5108 setup_pagelist_highmark(
5109 per_cpu_ptr(zone->pageset, cpu), high);
5112 return 0;
5115 int hashdist = HASHDIST_DEFAULT;
5117 #ifdef CONFIG_NUMA
5118 static int __init set_hashdist(char *str)
5120 if (!str)
5121 return 0;
5122 hashdist = simple_strtoul(str, &str, 0);
5123 return 1;
5125 __setup("hashdist=", set_hashdist);
5126 #endif
5129 * allocate a large system hash table from bootmem
5130 * - it is assumed that the hash table must contain an exact power-of-2
5131 * quantity of entries
5132 * - limit is the number of hash buckets, not the total allocation size
5134 void *__init alloc_large_system_hash(const char *tablename,
5135 unsigned long bucketsize,
5136 unsigned long numentries,
5137 int scale,
5138 int flags,
5139 unsigned int *_hash_shift,
5140 unsigned int *_hash_mask,
5141 unsigned long limit)
5143 unsigned long long max = limit;
5144 unsigned long log2qty, size;
5145 void *table = NULL;
5147 /* allow the kernel cmdline to have a say */
5148 if (!numentries) {
5149 /* round applicable memory size up to nearest megabyte */
5150 numentries = nr_kernel_pages;
5151 numentries += (1UL << (20 - PAGE_SHIFT)) - 1;
5152 numentries >>= 20 - PAGE_SHIFT;
5153 numentries <<= 20 - PAGE_SHIFT;
5155 /* limit to 1 bucket per 2^scale bytes of low memory */
5156 if (scale > PAGE_SHIFT)
5157 numentries >>= (scale - PAGE_SHIFT);
5158 else
5159 numentries <<= (PAGE_SHIFT - scale);
5161 /* Make sure we've got at least a 0-order allocation.. */
5162 if (unlikely(flags & HASH_SMALL)) {
5163 /* Makes no sense without HASH_EARLY */
5164 WARN_ON(!(flags & HASH_EARLY));
5165 if (!(numentries >> *_hash_shift)) {
5166 numentries = 1UL << *_hash_shift;
5167 BUG_ON(!numentries);
5169 } else if (unlikely((numentries * bucketsize) < PAGE_SIZE))
5170 numentries = PAGE_SIZE / bucketsize;
5172 numentries = roundup_pow_of_two(numentries);
5174 /* limit allocation size to 1/16 total memory by default */
5175 if (max == 0) {
5176 max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
5177 do_div(max, bucketsize);
5180 if (numentries > max)
5181 numentries = max;
5183 log2qty = ilog2(numentries);
5185 do {
5186 size = bucketsize << log2qty;
5187 if (flags & HASH_EARLY)
5188 table = alloc_bootmem_nopanic(size);
5189 else if (hashdist)
5190 table = __vmalloc(size, GFP_ATOMIC, PAGE_KERNEL);
5191 else {
5193 * If bucketsize is not a power-of-two, we may free
5194 * some pages at the end of hash table which
5195 * alloc_pages_exact() automatically does
5197 if (get_order(size) < MAX_ORDER) {
5198 table = alloc_pages_exact(size, GFP_ATOMIC);
5199 kmemleak_alloc(table, size, 1, GFP_ATOMIC);
5202 } while (!table && size > PAGE_SIZE && --log2qty);
5204 if (!table)
5205 panic("Failed to allocate %s hash table\n", tablename);
5207 printk(KERN_INFO "%s hash table entries: %ld (order: %d, %lu bytes)\n",
5208 tablename,
5209 (1UL << log2qty),
5210 ilog2(size) - PAGE_SHIFT,
5211 size);
5213 if (_hash_shift)
5214 *_hash_shift = log2qty;
5215 if (_hash_mask)
5216 *_hash_mask = (1 << log2qty) - 1;
5218 return table;
5221 /* Return a pointer to the bitmap storing bits affecting a block of pages */
5222 static inline unsigned long *get_pageblock_bitmap(struct zone *zone,
5223 unsigned long pfn)
5225 #ifdef CONFIG_SPARSEMEM
5226 return __pfn_to_section(pfn)->pageblock_flags;
5227 #else
5228 return zone->pageblock_flags;
5229 #endif /* CONFIG_SPARSEMEM */
5232 static inline int pfn_to_bitidx(struct zone *zone, unsigned long pfn)
5234 #ifdef CONFIG_SPARSEMEM
5235 pfn &= (PAGES_PER_SECTION-1);
5236 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
5237 #else
5238 pfn = pfn - zone->zone_start_pfn;
5239 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
5240 #endif /* CONFIG_SPARSEMEM */
5244 * get_pageblock_flags_group - Return the requested group of flags for the pageblock_nr_pages block of pages
5245 * @page: The page within the block of interest
5246 * @start_bitidx: The first bit of interest to retrieve
5247 * @end_bitidx: The last bit of interest
5248 * returns pageblock_bits flags
5250 unsigned long get_pageblock_flags_group(struct page *page,
5251 int start_bitidx, int end_bitidx)
5253 struct zone *zone;
5254 unsigned long *bitmap;
5255 unsigned long pfn, bitidx;
5256 unsigned long flags = 0;
5257 unsigned long value = 1;
5259 zone = page_zone(page);
5260 pfn = page_to_pfn(page);
5261 bitmap = get_pageblock_bitmap(zone, pfn);
5262 bitidx = pfn_to_bitidx(zone, pfn);
5264 for (; start_bitidx <= end_bitidx; start_bitidx++, value <<= 1)
5265 if (test_bit(bitidx + start_bitidx, bitmap))
5266 flags |= value;
5268 return flags;
5272 * set_pageblock_flags_group - Set the requested group of flags for a pageblock_nr_pages block of pages
5273 * @page: The page within the block of interest
5274 * @start_bitidx: The first bit of interest
5275 * @end_bitidx: The last bit of interest
5276 * @flags: The flags to set
5278 void set_pageblock_flags_group(struct page *page, unsigned long flags,
5279 int start_bitidx, int end_bitidx)
5281 struct zone *zone;
5282 unsigned long *bitmap;
5283 unsigned long pfn, bitidx;
5284 unsigned long value = 1;
5286 zone = page_zone(page);
5287 pfn = page_to_pfn(page);
5288 bitmap = get_pageblock_bitmap(zone, pfn);
5289 bitidx = pfn_to_bitidx(zone, pfn);
5290 VM_BUG_ON(pfn < zone->zone_start_pfn);
5291 VM_BUG_ON(pfn >= zone->zone_start_pfn + zone->spanned_pages);
5293 for (; start_bitidx <= end_bitidx; start_bitidx++, value <<= 1)
5294 if (flags & value)
5295 __set_bit(bitidx + start_bitidx, bitmap);
5296 else
5297 __clear_bit(bitidx + start_bitidx, bitmap);
5301 * This is designed as sub function...plz see page_isolation.c also.
5302 * set/clear page block's type to be ISOLATE.
5303 * page allocater never alloc memory from ISOLATE block.
5306 int set_migratetype_isolate(struct page *page)
5308 struct zone *zone;
5309 struct page *curr_page;
5310 unsigned long flags, pfn, iter;
5311 unsigned long immobile = 0;
5312 struct memory_isolate_notify arg;
5313 int notifier_ret;
5314 int ret = -EBUSY;
5315 int zone_idx;
5317 zone = page_zone(page);
5318 zone_idx = zone_idx(zone);
5320 spin_lock_irqsave(&zone->lock, flags);
5321 if (get_pageblock_migratetype(page) == MIGRATE_MOVABLE ||
5322 zone_idx == ZONE_MOVABLE) {
5323 ret = 0;
5324 goto out;
5327 pfn = page_to_pfn(page);
5328 arg.start_pfn = pfn;
5329 arg.nr_pages = pageblock_nr_pages;
5330 arg.pages_found = 0;
5333 * It may be possible to isolate a pageblock even if the
5334 * migratetype is not MIGRATE_MOVABLE. The memory isolation
5335 * notifier chain is used by balloon drivers to return the
5336 * number of pages in a range that are held by the balloon
5337 * driver to shrink memory. If all the pages are accounted for
5338 * by balloons, are free, or on the LRU, isolation can continue.
5339 * Later, for example, when memory hotplug notifier runs, these
5340 * pages reported as "can be isolated" should be isolated(freed)
5341 * by the balloon driver through the memory notifier chain.
5343 notifier_ret = memory_isolate_notify(MEM_ISOLATE_COUNT, &arg);
5344 notifier_ret = notifier_to_errno(notifier_ret);
5345 if (notifier_ret || !arg.pages_found)
5346 goto out;
5348 for (iter = pfn; iter < (pfn + pageblock_nr_pages); iter++) {
5349 if (!pfn_valid_within(pfn))
5350 continue;
5352 curr_page = pfn_to_page(iter);
5353 if (!page_count(curr_page) || PageLRU(curr_page))
5354 continue;
5356 immobile++;
5359 if (arg.pages_found == immobile)
5360 ret = 0;
5362 out:
5363 if (!ret) {
5364 set_pageblock_migratetype(page, MIGRATE_ISOLATE);
5365 move_freepages_block(zone, page, MIGRATE_ISOLATE);
5368 spin_unlock_irqrestore(&zone->lock, flags);
5369 if (!ret)
5370 drain_all_pages();
5371 return ret;
5374 void unset_migratetype_isolate(struct page *page)
5376 struct zone *zone;
5377 unsigned long flags;
5378 zone = page_zone(page);
5379 spin_lock_irqsave(&zone->lock, flags);
5380 if (get_pageblock_migratetype(page) != MIGRATE_ISOLATE)
5381 goto out;
5382 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
5383 move_freepages_block(zone, page, MIGRATE_MOVABLE);
5384 out:
5385 spin_unlock_irqrestore(&zone->lock, flags);
5388 #ifdef CONFIG_MEMORY_HOTREMOVE
5390 * All pages in the range must be isolated before calling this.
5392 void
5393 __offline_isolated_pages(unsigned long start_pfn, unsigned long end_pfn)
5395 struct page *page;
5396 struct zone *zone;
5397 int order, i;
5398 unsigned long pfn;
5399 unsigned long flags;
5400 /* find the first valid pfn */
5401 for (pfn = start_pfn; pfn < end_pfn; pfn++)
5402 if (pfn_valid(pfn))
5403 break;
5404 if (pfn == end_pfn)
5405 return;
5406 zone = page_zone(pfn_to_page(pfn));
5407 spin_lock_irqsave(&zone->lock, flags);
5408 pfn = start_pfn;
5409 while (pfn < end_pfn) {
5410 if (!pfn_valid(pfn)) {
5411 pfn++;
5412 continue;
5414 page = pfn_to_page(pfn);
5415 BUG_ON(page_count(page));
5416 BUG_ON(!PageBuddy(page));
5417 order = page_order(page);
5418 #ifdef CONFIG_DEBUG_VM
5419 printk(KERN_INFO "remove from free list %lx %d %lx\n",
5420 pfn, 1 << order, end_pfn);
5421 #endif
5422 list_del(&page->lru);
5423 rmv_page_order(page);
5424 zone->free_area[order].nr_free--;
5425 __mod_zone_page_state(zone, NR_FREE_PAGES,
5426 - (1UL << order));
5427 for (i = 0; i < (1 << order); i++)
5428 SetPageReserved((page+i));
5429 pfn += (1 << order);
5431 spin_unlock_irqrestore(&zone->lock, flags);
5433 #endif
5435 #ifdef CONFIG_MEMORY_FAILURE
5436 bool is_free_buddy_page(struct page *page)
5438 struct zone *zone = page_zone(page);
5439 unsigned long pfn = page_to_pfn(page);
5440 unsigned long flags;
5441 int order;
5443 spin_lock_irqsave(&zone->lock, flags);
5444 for (order = 0; order < MAX_ORDER; order++) {
5445 struct page *page_head = page - (pfn & ((1 << order) - 1));
5447 if (PageBuddy(page_head) && page_order(page_head) >= order)
5448 break;
5450 spin_unlock_irqrestore(&zone->lock, flags);
5452 return order < MAX_ORDER;
5454 #endif
5456 static struct trace_print_flags pageflag_names[] = {
5457 {1UL << PG_locked, "locked" },
5458 {1UL << PG_error, "error" },
5459 {1UL << PG_referenced, "referenced" },
5460 {1UL << PG_uptodate, "uptodate" },
5461 {1UL << PG_dirty, "dirty" },
5462 {1UL << PG_lru, "lru" },
5463 {1UL << PG_active, "active" },
5464 {1UL << PG_slab, "slab" },
5465 {1UL << PG_owner_priv_1, "owner_priv_1" },
5466 {1UL << PG_arch_1, "arch_1" },
5467 {1UL << PG_reserved, "reserved" },
5468 {1UL << PG_private, "private" },
5469 {1UL << PG_private_2, "private_2" },
5470 {1UL << PG_writeback, "writeback" },
5471 #ifdef CONFIG_PAGEFLAGS_EXTENDED
5472 {1UL << PG_head, "head" },
5473 {1UL << PG_tail, "tail" },
5474 #else
5475 {1UL << PG_compound, "compound" },
5476 #endif
5477 {1UL << PG_swapcache, "swapcache" },
5478 {1UL << PG_mappedtodisk, "mappedtodisk" },
5479 {1UL << PG_reclaim, "reclaim" },
5480 {1UL << PG_buddy, "buddy" },
5481 {1UL << PG_swapbacked, "swapbacked" },
5482 {1UL << PG_unevictable, "unevictable" },
5483 #ifdef CONFIG_MMU
5484 {1UL << PG_mlocked, "mlocked" },
5485 #endif
5486 #ifdef CONFIG_ARCH_USES_PG_UNCACHED
5487 {1UL << PG_uncached, "uncached" },
5488 #endif
5489 #ifdef CONFIG_MEMORY_FAILURE
5490 {1UL << PG_hwpoison, "hwpoison" },
5491 #endif
5492 {-1UL, NULL },
5495 static void dump_page_flags(unsigned long flags)
5497 const char *delim = "";
5498 unsigned long mask;
5499 int i;
5501 printk(KERN_ALERT "page flags: %#lx(", flags);
5503 /* remove zone id */
5504 flags &= (1UL << NR_PAGEFLAGS) - 1;
5506 for (i = 0; pageflag_names[i].name && flags; i++) {
5508 mask = pageflag_names[i].mask;
5509 if ((flags & mask) != mask)
5510 continue;
5512 flags &= ~mask;
5513 printk("%s%s", delim, pageflag_names[i].name);
5514 delim = "|";
5517 /* check for left over flags */
5518 if (flags)
5519 printk("%s%#lx", delim, flags);
5521 printk(")\n");
5524 void dump_page(struct page *page)
5526 printk(KERN_ALERT
5527 "page:%p count:%d mapcount:%d mapping:%p index:%#lx\n",
5528 page, page_count(page), page_mapcount(page),
5529 page->mapping, page->index);
5530 dump_page_flags(page->flags);