2 * linux/mm/page_alloc.c
4 * Manages the free list, the system allocates free pages here.
5 * Note that kmalloc() lives in slab.c
7 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
8 * Swap reorganised 29.12.95, Stephen Tweedie
9 * Support of BIGMEM added by Gerhard Wichert, Siemens AG, July 1999
10 * Reshaped it to be a zoned allocator, Ingo Molnar, Red Hat, 1999
11 * Discontiguous memory support, Kanoj Sarcar, SGI, Nov 1999
12 * Zone balancing, Kanoj Sarcar, SGI, Jan 2000
13 * Per cpu hot/cold page lists, bulk allocation, Martin J. Bligh, Sept 2002
14 * (lots of bits borrowed from Ingo Molnar & Andrew Morton)
17 #include <linux/stddef.h>
19 #include <linux/swap.h>
20 #include <linux/interrupt.h>
21 #include <linux/pagemap.h>
22 #include <linux/jiffies.h>
23 #include <linux/bootmem.h>
24 #include <linux/memblock.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/ratelimit.h>
34 #include <linux/oom.h>
35 #include <linux/notifier.h>
36 #include <linux/topology.h>
37 #include <linux/sysctl.h>
38 #include <linux/cpu.h>
39 #include <linux/cpuset.h>
40 #include <linux/memory_hotplug.h>
41 #include <linux/nodemask.h>
42 #include <linux/vmalloc.h>
43 #include <linux/vmstat.h>
44 #include <linux/mempolicy.h>
45 #include <linux/stop_machine.h>
46 #include <linux/sort.h>
47 #include <linux/pfn.h>
48 #include <linux/backing-dev.h>
49 #include <linux/fault-inject.h>
50 #include <linux/page-isolation.h>
51 #include <linux/page_cgroup.h>
52 #include <linux/debugobjects.h>
53 #include <linux/kmemleak.h>
54 #include <linux/memory.h>
55 #include <linux/compaction.h>
56 #include <trace/events/kmem.h>
57 #include <linux/ftrace_event.h>
58 #include <linux/memcontrol.h>
59 #include <linux/prefetch.h>
60 #include <linux/migrate.h>
61 #include <linux/page-debug-flags.h>
62 #include <linux/nmi.h>
64 #include <asm/tlbflush.h>
65 #include <asm/div64.h>
68 #ifdef CONFIG_USE_PERCPU_NUMA_NODE_ID
69 DEFINE_PER_CPU(int, numa_node);
70 EXPORT_PER_CPU_SYMBOL(numa_node);
73 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
75 * N.B., Do NOT reference the '_numa_mem_' per cpu variable directly.
76 * It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined.
77 * Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem()
78 * defined in <linux/topology.h>.
80 DEFINE_PER_CPU(int, _numa_mem_); /* Kernel "local memory" node */
81 EXPORT_PER_CPU_SYMBOL(_numa_mem_);
85 * Array of node states.
87 nodemask_t node_states[NR_NODE_STATES] __read_mostly = {
88 [N_POSSIBLE] = NODE_MASK_ALL,
89 [N_ONLINE] = { { [0] = 1UL } },
91 [N_NORMAL_MEMORY] = { { [0] = 1UL } },
93 [N_HIGH_MEMORY] = { { [0] = 1UL } },
95 [N_CPU] = { { [0] = 1UL } },
98 EXPORT_SYMBOL(node_states);
100 unsigned long totalram_pages __read_mostly;
101 unsigned long totalreserve_pages __read_mostly;
103 * When calculating the number of globally allowed dirty pages, there
104 * is a certain number of per-zone reserves that should not be
105 * considered dirtyable memory. This is the sum of those reserves
106 * over all existing zones that contribute dirtyable memory.
108 unsigned long dirty_balance_reserve __read_mostly;
110 int percpu_pagelist_fraction;
111 gfp_t gfp_allowed_mask __read_mostly = GFP_BOOT_MASK;
113 #ifdef CONFIG_PM_SLEEP
115 * The following functions are used by the suspend/hibernate code to temporarily
116 * change gfp_allowed_mask in order to avoid using I/O during memory allocations
117 * while devices are suspended. To avoid races with the suspend/hibernate code,
118 * they should always be called with pm_mutex held (gfp_allowed_mask also should
119 * only be modified with pm_mutex held, unless the suspend/hibernate code is
120 * guaranteed not to run in parallel with that modification).
123 static gfp_t saved_gfp_mask;
125 void pm_restore_gfp_mask(void)
127 WARN_ON(!mutex_is_locked(&pm_mutex));
128 if (saved_gfp_mask) {
129 gfp_allowed_mask = saved_gfp_mask;
134 void pm_restrict_gfp_mask(void)
136 WARN_ON(!mutex_is_locked(&pm_mutex));
137 WARN_ON(saved_gfp_mask);
138 saved_gfp_mask = gfp_allowed_mask;
139 gfp_allowed_mask &= ~GFP_IOFS;
142 bool pm_suspended_storage(void)
144 if ((gfp_allowed_mask & GFP_IOFS) == GFP_IOFS)
148 #endif /* CONFIG_PM_SLEEP */
150 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
151 int pageblock_order __read_mostly;
154 static void __free_pages_ok(struct page *page, unsigned int order);
157 * results with 256, 32 in the lowmem_reserve sysctl:
158 * 1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
159 * 1G machine -> (16M dma, 784M normal, 224M high)
160 * NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
161 * HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
162 * HIGHMEM allocation will (224M+784M)/256 of ram reserved in ZONE_DMA
164 * TBD: should special case ZONE_DMA32 machines here - in those we normally
165 * don't need any ZONE_NORMAL reservation
167 int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES-1] = {
168 #ifdef CONFIG_ZONE_DMA
171 #ifdef CONFIG_ZONE_DMA32
174 #ifdef CONFIG_HIGHMEM
180 EXPORT_SYMBOL(totalram_pages);
182 static char * const zone_names[MAX_NR_ZONES] = {
183 #ifdef CONFIG_ZONE_DMA
186 #ifdef CONFIG_ZONE_DMA32
190 #ifdef CONFIG_HIGHMEM
196 int min_free_kbytes = 1024;
198 static unsigned long __meminitdata nr_kernel_pages;
199 static unsigned long __meminitdata nr_all_pages;
200 static unsigned long __meminitdata dma_reserve;
202 #ifdef CONFIG_ARCH_POPULATES_NODE_MAP
204 * MAX_ACTIVE_REGIONS determines the maximum number of distinct
205 * ranges of memory (RAM) that may be registered with add_active_range().
206 * Ranges passed to add_active_range() will be merged if possible
207 * so the number of times add_active_range() can be called is
208 * related to the number of nodes and the number of holes
210 #ifdef CONFIG_MAX_ACTIVE_REGIONS
211 /* Allow an architecture to set MAX_ACTIVE_REGIONS to save memory */
212 #define MAX_ACTIVE_REGIONS CONFIG_MAX_ACTIVE_REGIONS
214 #if MAX_NUMNODES >= 32
215 /* If there can be many nodes, allow up to 50 holes per node */
216 #define MAX_ACTIVE_REGIONS (MAX_NUMNODES*50)
218 /* By default, allow up to 256 distinct regions */
219 #define MAX_ACTIVE_REGIONS 256
223 static struct node_active_region __meminitdata early_node_map[MAX_ACTIVE_REGIONS];
224 static int __meminitdata nr_nodemap_entries;
225 static unsigned long __meminitdata arch_zone_lowest_possible_pfn[MAX_NR_ZONES];
226 static unsigned long __meminitdata arch_zone_highest_possible_pfn[MAX_NR_ZONES];
227 static unsigned long __initdata required_kernelcore;
228 static unsigned long __initdata required_movablecore;
229 static unsigned long __meminitdata zone_movable_pfn[MAX_NUMNODES];
231 /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
233 EXPORT_SYMBOL(movable_zone);
234 #endif /* CONFIG_ARCH_POPULATES_NODE_MAP */
237 int nr_node_ids __read_mostly = MAX_NUMNODES;
238 int nr_online_nodes __read_mostly = 1;
239 EXPORT_SYMBOL(nr_node_ids);
240 EXPORT_SYMBOL(nr_online_nodes);
243 int page_group_by_mobility_disabled __read_mostly;
245 static void set_pageblock_migratetype(struct page *page, int migratetype)
248 if (unlikely(page_group_by_mobility_disabled))
249 migratetype = MIGRATE_UNMOVABLE;
251 set_pageblock_flags_group(page, (unsigned long)migratetype,
252 PB_migrate, PB_migrate_end);
255 bool oom_killer_disabled __read_mostly;
257 #ifdef CONFIG_DEBUG_VM
258 static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
262 unsigned long pfn = page_to_pfn(page);
265 seq = zone_span_seqbegin(zone);
266 if (pfn >= zone->zone_start_pfn + zone->spanned_pages)
268 else if (pfn < zone->zone_start_pfn)
270 } while (zone_span_seqretry(zone, seq));
275 static int page_is_consistent(struct zone *zone, struct page *page)
277 if (!pfn_valid_within(page_to_pfn(page)))
279 if (zone != page_zone(page))
285 * Temporary debugging check for pages not lying within a given zone.
287 static int bad_range(struct zone *zone, struct page *page)
289 if (page_outside_zone_boundaries(zone, page))
291 if (!page_is_consistent(zone, page))
297 static inline int bad_range(struct zone *zone, struct page *page)
303 static void bad_page(struct page *page)
305 static unsigned long resume;
306 static unsigned long nr_shown;
307 static unsigned long nr_unshown;
309 /* Don't complain about poisoned pages */
310 if (PageHWPoison(page)) {
311 reset_page_mapcount(page); /* remove PageBuddy */
316 * Allow a burst of 60 reports, then keep quiet for that minute;
317 * or allow a steady drip of one report per second.
319 if (nr_shown == 60) {
320 if (time_before(jiffies, resume)) {
326 "BUG: Bad page state: %lu messages suppressed\n",
333 resume = jiffies + 60 * HZ;
335 printk(KERN_ALERT "BUG: Bad page state in process %s pfn:%05lx\n",
336 current->comm, page_to_pfn(page));
342 /* Leave bad fields for debug, except PageBuddy could make trouble */
343 reset_page_mapcount(page); /* remove PageBuddy */
344 add_taint(TAINT_BAD_PAGE);
348 * Higher-order pages are called "compound pages". They are structured thusly:
350 * The first PAGE_SIZE page is called the "head page".
352 * The remaining PAGE_SIZE pages are called "tail pages".
354 * All pages have PG_compound set. All pages have their ->private pointing at
355 * the head page (even the head page has this).
357 * The first tail page's ->lru.next holds the address of the compound page's
358 * put_page() function. Its ->lru.prev holds the order of allocation.
359 * This usage means that zero-order pages may not be compound.
362 static void free_compound_page(struct page *page)
364 __free_pages_ok(page, compound_order(page));
367 void prep_compound_page(struct page *page, unsigned long order)
370 int nr_pages = 1 << order;
372 set_compound_page_dtor(page, free_compound_page);
373 set_compound_order(page, order);
375 for (i = 1; i < nr_pages; i++) {
376 struct page *p = page + i;
378 set_page_count(p, 0);
379 p->first_page = page;
383 /* update __split_huge_page_refcount if you change this function */
384 static int destroy_compound_page(struct page *page, unsigned long order)
387 int nr_pages = 1 << order;
390 if (unlikely(compound_order(page) != order) ||
391 unlikely(!PageHead(page))) {
396 __ClearPageHead(page);
398 for (i = 1; i < nr_pages; i++) {
399 struct page *p = page + i;
401 if (unlikely(!PageTail(p) || (p->first_page != page))) {
411 static inline void prep_zero_page(struct page *page, int order, gfp_t gfp_flags)
416 * clear_highpage() will use KM_USER0, so it's a bug to use __GFP_ZERO
417 * and __GFP_HIGHMEM from hard or soft interrupt context.
419 VM_BUG_ON((gfp_flags & __GFP_HIGHMEM) && in_interrupt());
420 for (i = 0; i < (1 << order); i++)
421 clear_highpage(page + i);
424 #ifdef CONFIG_DEBUG_PAGEALLOC
425 unsigned int _debug_guardpage_minorder;
427 static int __init debug_guardpage_minorder_setup(char *buf)
431 if (kstrtoul(buf, 10, &res) < 0 || res > MAX_ORDER / 2) {
432 printk(KERN_ERR "Bad debug_guardpage_minorder value\n");
435 _debug_guardpage_minorder = res;
436 printk(KERN_INFO "Setting debug_guardpage_minorder to %lu\n", res);
439 __setup("debug_guardpage_minorder=", debug_guardpage_minorder_setup);
441 static inline void set_page_guard_flag(struct page *page)
443 __set_bit(PAGE_DEBUG_FLAG_GUARD, &page->debug_flags);
446 static inline void clear_page_guard_flag(struct page *page)
448 __clear_bit(PAGE_DEBUG_FLAG_GUARD, &page->debug_flags);
451 static inline void set_page_guard_flag(struct page *page) { }
452 static inline void clear_page_guard_flag(struct page *page) { }
455 static inline void set_page_order(struct page *page, int order)
457 set_page_private(page, order);
458 __SetPageBuddy(page);
461 static inline void rmv_page_order(struct page *page)
463 __ClearPageBuddy(page);
464 set_page_private(page, 0);
468 * Locate the struct page for both the matching buddy in our
469 * pair (buddy1) and the combined O(n+1) page they form (page).
471 * 1) Any buddy B1 will have an order O twin B2 which satisfies
472 * the following equation:
474 * For example, if the starting buddy (buddy2) is #8 its order
476 * B2 = 8 ^ (1 << 1) = 8 ^ 2 = 10
478 * 2) Any buddy B will have an order O+1 parent P which
479 * satisfies the following equation:
482 * Assumption: *_mem_map is contiguous at least up to MAX_ORDER
484 static inline unsigned long
485 __find_buddy_index(unsigned long page_idx, unsigned int order)
487 return page_idx ^ (1 << order);
491 * This function checks whether a page is free && is the buddy
492 * we can do coalesce a page and its buddy if
493 * (a) the buddy is not in a hole &&
494 * (b) the buddy is in the buddy system &&
495 * (c) a page and its buddy have the same order &&
496 * (d) a page and its buddy are in the same zone.
498 * For recording whether a page is in the buddy system, we set ->_mapcount -2.
499 * Setting, clearing, and testing _mapcount -2 is serialized by zone->lock.
501 * For recording page's order, we use page_private(page).
503 static inline int page_is_buddy(struct page *page, struct page *buddy,
506 if (!pfn_valid_within(page_to_pfn(buddy)))
509 if (page_zone_id(page) != page_zone_id(buddy))
512 if (page_is_guard(buddy) && page_order(buddy) == order) {
513 VM_BUG_ON(page_count(buddy) != 0);
517 if (PageBuddy(buddy) && page_order(buddy) == order) {
518 VM_BUG_ON(page_count(buddy) != 0);
525 * Freeing function for a buddy system allocator.
527 * The concept of a buddy system is to maintain direct-mapped table
528 * (containing bit values) for memory blocks of various "orders".
529 * The bottom level table contains the map for the smallest allocatable
530 * units of memory (here, pages), and each level above it describes
531 * pairs of units from the levels below, hence, "buddies".
532 * At a high level, all that happens here is marking the table entry
533 * at the bottom level available, and propagating the changes upward
534 * as necessary, plus some accounting needed to play nicely with other
535 * parts of the VM system.
536 * At each level, we keep a list of pages, which are heads of continuous
537 * free pages of length of (1 << order) and marked with _mapcount -2. Page's
538 * order is recorded in page_private(page) field.
539 * So when we are allocating or freeing one, we can derive the state of the
540 * other. That is, if we allocate a small block, and both were
541 * free, the remainder of the region must be split into blocks.
542 * If a block is freed, and its buddy is also free, then this
543 * triggers coalescing into a block of larger size.
548 static inline void __free_one_page(struct page *page,
549 struct zone *zone, unsigned int order,
552 unsigned long page_idx;
553 unsigned long combined_idx;
554 unsigned long uninitialized_var(buddy_idx);
557 if (unlikely(PageCompound(page)))
558 if (unlikely(destroy_compound_page(page, order)))
561 VM_BUG_ON(migratetype == -1);
563 page_idx = page_to_pfn(page) & ((1 << MAX_ORDER) - 1);
565 VM_BUG_ON(page_idx & ((1 << order) - 1));
566 VM_BUG_ON(bad_range(zone, page));
568 while (order < MAX_ORDER-1) {
569 buddy_idx = __find_buddy_index(page_idx, order);
570 buddy = page + (buddy_idx - page_idx);
571 if (!page_is_buddy(page, buddy, order))
574 * Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page,
575 * merge with it and move up one order.
577 if (page_is_guard(buddy)) {
578 clear_page_guard_flag(buddy);
579 set_page_private(page, 0);
580 __mod_zone_page_state(zone, NR_FREE_PAGES, 1 << order);
582 list_del(&buddy->lru);
583 zone->free_area[order].nr_free--;
584 rmv_page_order(buddy);
586 combined_idx = buddy_idx & page_idx;
587 page = page + (combined_idx - page_idx);
588 page_idx = combined_idx;
591 set_page_order(page, order);
594 * If this is not the largest possible page, check if the buddy
595 * of the next-highest order is free. If it is, it's possible
596 * that pages are being freed that will coalesce soon. In case,
597 * that is happening, add the free page to the tail of the list
598 * so it's less likely to be used soon and more likely to be merged
599 * as a higher order page
601 if ((order < MAX_ORDER-2) && pfn_valid_within(page_to_pfn(buddy))) {
602 struct page *higher_page, *higher_buddy;
603 combined_idx = buddy_idx & page_idx;
604 higher_page = page + (combined_idx - page_idx);
605 buddy_idx = __find_buddy_index(combined_idx, order + 1);
606 higher_buddy = higher_page + (buddy_idx - combined_idx);
607 if (page_is_buddy(higher_page, higher_buddy, order + 1)) {
608 list_add_tail(&page->lru,
609 &zone->free_area[order].free_list[migratetype]);
614 list_add(&page->lru, &zone->free_area[order].free_list[migratetype]);
616 zone->free_area[order].nr_free++;
620 * free_page_mlock() -- clean up attempts to free and mlocked() page.
621 * Page should not be on lru, so no need to fix that up.
622 * free_pages_check() will verify...
624 static inline void free_page_mlock(struct page *page)
626 __dec_zone_page_state(page, NR_MLOCK);
627 __count_vm_event(UNEVICTABLE_MLOCKFREED);
630 static inline int free_pages_check(struct page *page)
632 if (unlikely(page_mapcount(page) |
633 (page->mapping != NULL) |
634 (atomic_read(&page->_count) != 0) |
635 (page->flags & PAGE_FLAGS_CHECK_AT_FREE) |
636 (mem_cgroup_bad_page_check(page)))) {
640 if (page->flags & PAGE_FLAGS_CHECK_AT_PREP)
641 page->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
646 * Frees a number of pages from the PCP lists
647 * Assumes all pages on list are in same zone, and of same order.
648 * count is the number of pages to free.
650 * If the zone was previously in an "all pages pinned" state then look to
651 * see if this freeing clears that state.
653 * And clear the zone's pages_scanned counter, to hold off the "all pages are
654 * pinned" detection logic.
656 static void free_pcppages_bulk(struct zone *zone, int count,
657 struct per_cpu_pages *pcp)
663 spin_lock(&zone->lock);
664 zone->all_unreclaimable = 0;
665 zone->pages_scanned = 0;
669 struct list_head *list;
672 * Remove pages from lists in a round-robin fashion. A
673 * batch_free count is maintained that is incremented when an
674 * empty list is encountered. This is so more pages are freed
675 * off fuller lists instead of spinning excessively around empty
680 if (++migratetype == MIGRATE_PCPTYPES)
682 list = &pcp->lists[migratetype];
683 } while (list_empty(list));
685 /* This is the only non-empty list. Free them all. */
686 if (batch_free == MIGRATE_PCPTYPES)
687 batch_free = to_free;
690 page = list_entry(list->prev, struct page, lru);
691 /* must delete as __free_one_page list manipulates */
692 list_del(&page->lru);
693 /* MIGRATE_MOVABLE list may include MIGRATE_RESERVEs */
694 __free_one_page(page, zone, 0, page_private(page));
695 trace_mm_page_pcpu_drain(page, 0, page_private(page));
696 } while (--to_free && --batch_free && !list_empty(list));
698 __mod_zone_page_state(zone, NR_FREE_PAGES, count);
699 spin_unlock(&zone->lock);
702 static void free_one_page(struct zone *zone, struct page *page, int order,
705 spin_lock(&zone->lock);
706 zone->all_unreclaimable = 0;
707 zone->pages_scanned = 0;
709 __free_one_page(page, zone, order, migratetype);
710 __mod_zone_page_state(zone, NR_FREE_PAGES, 1 << order);
711 spin_unlock(&zone->lock);
714 static bool free_pages_prepare(struct page *page, unsigned int order)
719 trace_mm_page_free(page, order);
720 kmemcheck_free_shadow(page, order);
723 page->mapping = NULL;
724 for (i = 0; i < (1 << order); i++)
725 bad += free_pages_check(page + i);
729 if (!PageHighMem(page)) {
730 debug_check_no_locks_freed(page_address(page),PAGE_SIZE<<order);
731 debug_check_no_obj_freed(page_address(page),
734 arch_free_page(page, order);
735 kernel_map_pages(page, 1 << order, 0);
740 static void __free_pages_ok(struct page *page, unsigned int order)
743 int wasMlocked = __TestClearPageMlocked(page);
745 if (!free_pages_prepare(page, order))
748 local_irq_save(flags);
749 if (unlikely(wasMlocked))
750 free_page_mlock(page);
751 __count_vm_events(PGFREE, 1 << order);
752 free_one_page(page_zone(page), page, order,
753 get_pageblock_migratetype(page));
754 local_irq_restore(flags);
758 * permit the bootmem allocator to evade page validation on high-order frees
760 void __meminit __free_pages_bootmem(struct page *page, unsigned int order)
763 __ClearPageReserved(page);
764 set_page_count(page, 0);
765 set_page_refcounted(page);
771 for (loop = 0; loop < BITS_PER_LONG; loop++) {
772 struct page *p = &page[loop];
774 if (loop + 1 < BITS_PER_LONG)
776 __ClearPageReserved(p);
777 set_page_count(p, 0);
780 set_page_refcounted(page);
781 __free_pages(page, order);
786 /* Free whole pageblock and set it's migration type to MIGRATE_CMA. */
787 void __init init_cma_reserved_pageblock(struct page *page)
789 unsigned i = pageblock_nr_pages;
790 struct page *p = page;
793 __ClearPageReserved(p);
794 set_page_count(p, 0);
797 set_page_refcounted(page);
798 set_pageblock_migratetype(page, MIGRATE_CMA);
799 __free_pages(page, pageblock_order);
800 totalram_pages += pageblock_nr_pages;
805 * The order of subdivision here is critical for the IO subsystem.
806 * Please do not alter this order without good reasons and regression
807 * testing. Specifically, as large blocks of memory are subdivided,
808 * the order in which smaller blocks are delivered depends on the order
809 * they're subdivided in this function. This is the primary factor
810 * influencing the order in which pages are delivered to the IO
811 * subsystem according to empirical testing, and this is also justified
812 * by considering the behavior of a buddy system containing a single
813 * large block of memory acted on by a series of small allocations.
814 * This behavior is a critical factor in sglist merging's success.
818 static inline void expand(struct zone *zone, struct page *page,
819 int low, int high, struct free_area *area,
822 unsigned long size = 1 << high;
828 VM_BUG_ON(bad_range(zone, &page[size]));
830 #ifdef CONFIG_DEBUG_PAGEALLOC
831 if (high < debug_guardpage_minorder()) {
833 * Mark as guard pages (or page), that will allow to
834 * merge back to allocator when buddy will be freed.
835 * Corresponding page table entries will not be touched,
836 * pages will stay not present in virtual address space
838 INIT_LIST_HEAD(&page[size].lru);
839 set_page_guard_flag(&page[size]);
840 set_page_private(&page[size], high);
841 /* Guard pages are not available for any usage */
842 __mod_zone_page_state(zone, NR_FREE_PAGES, -(1 << high));
846 list_add(&page[size].lru, &area->free_list[migratetype]);
848 set_page_order(&page[size], high);
853 * This page is about to be returned from the page allocator
855 static inline int check_new_page(struct page *page)
857 if (unlikely(page_mapcount(page) |
858 (page->mapping != NULL) |
859 (atomic_read(&page->_count) != 0) |
860 (page->flags & PAGE_FLAGS_CHECK_AT_PREP) |
861 (mem_cgroup_bad_page_check(page)))) {
868 static int prep_new_page(struct page *page, int order, gfp_t gfp_flags)
872 for (i = 0; i < (1 << order); i++) {
873 struct page *p = page + i;
874 if (unlikely(check_new_page(p)))
878 set_page_private(page, 0);
879 set_page_refcounted(page);
881 arch_alloc_page(page, order);
882 kernel_map_pages(page, 1 << order, 1);
884 if (gfp_flags & __GFP_ZERO)
885 prep_zero_page(page, order, gfp_flags);
887 if (order && (gfp_flags & __GFP_COMP))
888 prep_compound_page(page, order);
894 * Go through the free lists for the given migratetype and remove
895 * the smallest available page from the freelists
898 struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
901 unsigned int current_order;
902 struct free_area * area;
905 /* Find a page of the appropriate size in the preferred list */
906 for (current_order = order; current_order < MAX_ORDER; ++current_order) {
907 area = &(zone->free_area[current_order]);
908 if (list_empty(&area->free_list[migratetype]))
911 page = list_entry(area->free_list[migratetype].next,
913 list_del(&page->lru);
914 rmv_page_order(page);
916 expand(zone, page, order, current_order, area, migratetype);
925 * This array describes the order lists are fallen back to when
926 * the free lists for the desirable migrate type are depleted
928 static int fallbacks[MIGRATE_TYPES][4] = {
929 [MIGRATE_UNMOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE, MIGRATE_RESERVE },
930 [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE, MIGRATE_MOVABLE, MIGRATE_RESERVE },
932 [MIGRATE_MOVABLE] = { MIGRATE_CMA, MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_RESERVE },
933 [MIGRATE_CMA] = { MIGRATE_RESERVE }, /* Never used */
935 [MIGRATE_MOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_RESERVE },
937 [MIGRATE_RESERVE] = { MIGRATE_RESERVE }, /* Never used */
938 [MIGRATE_ISOLATE] = { MIGRATE_RESERVE }, /* Never used */
942 * Move the free pages in a range to the free lists of the requested type.
943 * Note that start_page and end_pages are not aligned on a pageblock
944 * boundary. If alignment is required, use move_freepages_block()
946 static int move_freepages(struct zone *zone,
947 struct page *start_page, struct page *end_page,
954 #ifndef CONFIG_HOLES_IN_ZONE
956 * page_zone is not safe to call in this context when
957 * CONFIG_HOLES_IN_ZONE is set. This bug check is probably redundant
958 * anyway as we check zone boundaries in move_freepages_block().
959 * Remove at a later date when no bug reports exist related to
960 * grouping pages by mobility
962 BUG_ON(page_zone(start_page) != page_zone(end_page));
965 for (page = start_page; page <= end_page;) {
966 /* Make sure we are not inadvertently changing nodes */
967 VM_BUG_ON(page_to_nid(page) != zone_to_nid(zone));
969 if (!pfn_valid_within(page_to_pfn(page))) {
974 if (!PageBuddy(page)) {
979 order = page_order(page);
980 list_move(&page->lru,
981 &zone->free_area[order].free_list[migratetype]);
983 pages_moved += 1 << order;
989 static int move_freepages_block(struct zone *zone, struct page *page,
992 unsigned long start_pfn, end_pfn;
993 struct page *start_page, *end_page;
995 start_pfn = page_to_pfn(page);
996 start_pfn = start_pfn & ~(pageblock_nr_pages-1);
997 start_page = pfn_to_page(start_pfn);
998 end_page = start_page + pageblock_nr_pages - 1;
999 end_pfn = start_pfn + pageblock_nr_pages - 1;
1001 /* Do not cross zone boundaries */
1002 if (start_pfn < zone->zone_start_pfn)
1004 if (end_pfn >= zone->zone_start_pfn + zone->spanned_pages)
1007 return move_freepages(zone, start_page, end_page, migratetype);
1010 static void change_pageblock_range(struct page *pageblock_page,
1011 int start_order, int migratetype)
1013 int nr_pageblocks = 1 << (start_order - pageblock_order);
1015 while (nr_pageblocks--) {
1016 set_pageblock_migratetype(pageblock_page, migratetype);
1017 pageblock_page += pageblock_nr_pages;
1021 /* Remove an element from the buddy allocator from the fallback list */
1022 static inline struct page *
1023 __rmqueue_fallback(struct zone *zone, int order, int start_migratetype)
1025 struct free_area * area;
1030 /* Find the largest possible block of pages in the other list */
1031 for (current_order = MAX_ORDER-1; current_order >= order;
1034 migratetype = fallbacks[start_migratetype][i];
1036 /* MIGRATE_RESERVE handled later if necessary */
1037 if (migratetype == MIGRATE_RESERVE)
1040 area = &(zone->free_area[current_order]);
1041 if (list_empty(&area->free_list[migratetype]))
1044 page = list_entry(area->free_list[migratetype].next,
1049 * If breaking a large block of pages, move all free
1050 * pages to the preferred allocation list. If falling
1051 * back for a reclaimable kernel allocation, be more
1052 * aggressive about taking ownership of free pages
1054 * On the other hand, never change migration
1055 * type of MIGRATE_CMA pageblocks nor move CMA
1056 * pages on different free lists. We don't
1057 * want unmovable pages to be allocated from
1058 * MIGRATE_CMA areas.
1060 if (!is_migrate_cma(migratetype) &&
1061 (unlikely(current_order >= pageblock_order / 2) ||
1062 start_migratetype == MIGRATE_RECLAIMABLE ||
1063 page_group_by_mobility_disabled)) {
1065 pages = move_freepages_block(zone, page,
1068 /* Claim the whole block if over half of it is free */
1069 if (pages >= (1 << (pageblock_order-1)) ||
1070 page_group_by_mobility_disabled)
1071 set_pageblock_migratetype(page,
1074 migratetype = start_migratetype;
1077 /* Remove the page from the freelists */
1078 list_del(&page->lru);
1079 rmv_page_order(page);
1081 /* Take ownership for orders >= pageblock_order */
1082 if (current_order >= pageblock_order &&
1083 !is_migrate_cma(migratetype))
1084 change_pageblock_range(page, current_order,
1087 expand(zone, page, order, current_order, area,
1088 is_migrate_cma(migratetype)
1089 ? migratetype : start_migratetype);
1091 trace_mm_page_alloc_extfrag(page, order, current_order,
1092 start_migratetype, migratetype);
1102 * Do the hard work of removing an element from the buddy allocator.
1103 * Call me with the zone->lock already held.
1105 static struct page *__rmqueue(struct zone *zone, unsigned int order,
1111 page = __rmqueue_smallest(zone, order, migratetype);
1113 if (unlikely(!page) && migratetype != MIGRATE_RESERVE) {
1114 page = __rmqueue_fallback(zone, order, migratetype);
1117 * Use MIGRATE_RESERVE rather than fail an allocation. goto
1118 * is used because __rmqueue_smallest is an inline function
1119 * and we want just one call site
1122 migratetype = MIGRATE_RESERVE;
1127 trace_mm_page_alloc_zone_locked(page, order, migratetype);
1132 * Obtain a specified number of elements from the buddy allocator, all under
1133 * a single hold of the lock, for efficiency. Add them to the supplied list.
1134 * Returns the number of new pages which were placed at *list.
1136 static int rmqueue_bulk(struct zone *zone, unsigned int order,
1137 unsigned long count, struct list_head *list,
1138 int migratetype, int cold)
1140 int mt = migratetype, i;
1142 spin_lock(&zone->lock);
1143 for (i = 0; i < count; ++i) {
1144 struct page *page = __rmqueue(zone, order, migratetype);
1145 if (unlikely(page == NULL))
1149 * Split buddy pages returned by expand() are received here
1150 * in physical page order. The page is added to the callers and
1151 * list and the list head then moves forward. From the callers
1152 * perspective, the linked list is ordered by page number in
1153 * some conditions. This is useful for IO devices that can
1154 * merge IO requests if the physical pages are ordered
1157 if (likely(cold == 0))
1158 list_add(&page->lru, list);
1160 list_add_tail(&page->lru, list);
1161 if (IS_ENABLED(CONFIG_CMA)) {
1162 mt = get_pageblock_migratetype(page);
1163 if (!is_migrate_cma(mt) && mt != MIGRATE_ISOLATE)
1166 set_page_private(page, mt);
1169 __mod_zone_page_state(zone, NR_FREE_PAGES, -(i << order));
1170 spin_unlock(&zone->lock);
1176 * Called from the vmstat counter updater to drain pagesets of this
1177 * currently executing processor on remote nodes after they have
1180 * Note that this function must be called with the thread pinned to
1181 * a single processor.
1183 void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp)
1185 unsigned long flags;
1188 local_irq_save(flags);
1189 if (pcp->count >= pcp->batch)
1190 to_drain = pcp->batch;
1192 to_drain = pcp->count;
1193 free_pcppages_bulk(zone, to_drain, pcp);
1194 pcp->count -= to_drain;
1195 local_irq_restore(flags);
1200 * Drain pages of the indicated processor.
1202 * The processor must either be the current processor and the
1203 * thread pinned to the current processor or a processor that
1206 static void drain_pages(unsigned int cpu)
1208 unsigned long flags;
1211 for_each_populated_zone(zone) {
1212 struct per_cpu_pageset *pset;
1213 struct per_cpu_pages *pcp;
1215 local_irq_save(flags);
1216 pset = per_cpu_ptr(zone->pageset, cpu);
1220 free_pcppages_bulk(zone, pcp->count, pcp);
1223 local_irq_restore(flags);
1228 * Spill all of this CPU's per-cpu pages back into the buddy allocator.
1230 void drain_local_pages(void *arg)
1232 drain_pages(smp_processor_id());
1236 * Spill all the per-cpu pages from all CPUs back into the buddy allocator
1238 void drain_all_pages(void)
1240 on_each_cpu(drain_local_pages, NULL, 1);
1243 #ifdef CONFIG_HIBERNATION
1246 * Touch the watchdog for every WD_PAGE_COUNT pages.
1248 #define WD_PAGE_COUNT (128*1024)
1250 void mark_free_pages(struct zone *zone)
1252 unsigned long pfn, max_zone_pfn, page_count = WD_PAGE_COUNT;
1253 unsigned long flags;
1255 struct list_head *curr;
1257 if (!zone->spanned_pages)
1260 spin_lock_irqsave(&zone->lock, flags);
1262 max_zone_pfn = zone->zone_start_pfn + zone->spanned_pages;
1263 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
1264 if (pfn_valid(pfn)) {
1265 struct page *page = pfn_to_page(pfn);
1267 if (!--page_count) {
1268 touch_nmi_watchdog();
1269 page_count = WD_PAGE_COUNT;
1272 if (!swsusp_page_is_forbidden(page))
1273 swsusp_unset_page_free(page);
1276 for_each_migratetype_order(order, t) {
1277 list_for_each(curr, &zone->free_area[order].free_list[t]) {
1280 pfn = page_to_pfn(list_entry(curr, struct page, lru));
1281 for (i = 0; i < (1UL << order); i++) {
1282 if (!--page_count) {
1283 touch_nmi_watchdog();
1284 page_count = WD_PAGE_COUNT;
1286 swsusp_set_page_free(pfn_to_page(pfn + i));
1290 spin_unlock_irqrestore(&zone->lock, flags);
1292 #endif /* CONFIG_PM */
1295 * Free a 0-order page
1296 * cold == 1 ? free a cold page : free a hot page
1298 void free_hot_cold_page(struct page *page, int cold)
1300 struct zone *zone = page_zone(page);
1301 struct per_cpu_pages *pcp;
1302 unsigned long flags;
1304 int wasMlocked = __TestClearPageMlocked(page);
1306 if (!free_pages_prepare(page, 0))
1309 migratetype = get_pageblock_migratetype(page);
1310 set_page_private(page, migratetype);
1311 local_irq_save(flags);
1312 if (unlikely(wasMlocked))
1313 free_page_mlock(page);
1314 __count_vm_event(PGFREE);
1317 * We only track unmovable, reclaimable and movable on pcp lists.
1318 * Free ISOLATE pages back to the allocator because they are being
1319 * offlined but treat RESERVE as movable pages so we can get those
1320 * areas back if necessary. Otherwise, we may have to free
1321 * excessively into the page allocator
1323 if (migratetype >= MIGRATE_PCPTYPES) {
1324 if (unlikely(migratetype == MIGRATE_ISOLATE)) {
1325 free_one_page(zone, page, 0, migratetype);
1328 migratetype = MIGRATE_MOVABLE;
1331 pcp = &this_cpu_ptr(zone->pageset)->pcp;
1333 list_add_tail(&page->lru, &pcp->lists[migratetype]);
1335 list_add(&page->lru, &pcp->lists[migratetype]);
1337 if (pcp->count >= pcp->high) {
1338 free_pcppages_bulk(zone, pcp->batch, pcp);
1339 pcp->count -= pcp->batch;
1343 local_irq_restore(flags);
1347 * Free a list of 0-order pages
1349 void free_hot_cold_page_list(struct list_head *list, int cold)
1351 struct page *page, *next;
1353 list_for_each_entry_safe(page, next, list, lru) {
1354 trace_mm_page_free_batched(page, cold);
1355 free_hot_cold_page(page, cold);
1360 * split_page takes a non-compound higher-order page, and splits it into
1361 * n (1<<order) sub-pages: page[0..n]
1362 * Each sub-page must be freed individually.
1364 * Note: this is probably too low level an operation for use in drivers.
1365 * Please consult with lkml before using this in your driver.
1367 void split_page(struct page *page, unsigned int order)
1371 VM_BUG_ON(PageCompound(page));
1372 VM_BUG_ON(!page_count(page));
1374 #ifdef CONFIG_KMEMCHECK
1376 * Split shadow pages too, because free(page[0]) would
1377 * otherwise free the whole shadow.
1379 if (kmemcheck_page_is_tracked(page))
1380 split_page(virt_to_page(page[0].shadow), order);
1383 for (i = 1; i < (1 << order); i++)
1384 set_page_refcounted(page + i);
1388 * Similar to split_page except the page is already free. As this is only
1389 * being used for migration, the migratetype of the block also changes.
1390 * As this is called with interrupts disabled, the caller is responsible
1391 * for calling arch_alloc_page() and kernel_map_page() after interrupts
1394 * Note: this is probably too low level an operation for use in drivers.
1395 * Please consult with lkml before using this in your driver.
1397 int split_free_page(struct page *page)
1400 unsigned long watermark;
1403 BUG_ON(!PageBuddy(page));
1405 zone = page_zone(page);
1406 order = page_order(page);
1408 /* Obey watermarks as if the page was being allocated */
1409 watermark = low_wmark_pages(zone) + (1 << order);
1410 if (!zone_watermark_ok(zone, 0, watermark, 0, 0))
1413 /* Remove page from free list */
1414 list_del(&page->lru);
1415 zone->free_area[order].nr_free--;
1416 rmv_page_order(page);
1417 __mod_zone_page_state(zone, NR_FREE_PAGES, -(1UL << order));
1419 /* Split into individual pages */
1420 set_page_refcounted(page);
1421 split_page(page, order);
1423 if (order >= pageblock_order - 1) {
1424 struct page *endpage = page + (1 << order) - 1;
1425 for (; page < endpage; page += pageblock_nr_pages) {
1426 int mt = get_pageblock_migratetype(page);
1427 if (mt != MIGRATE_ISOLATE && !is_migrate_cma(mt))
1428 set_pageblock_migratetype(page,
1437 * Really, prep_compound_page() should be called from __rmqueue_bulk(). But
1438 * we cheat by calling it from here, in the order > 0 path. Saves a branch
1442 struct page *buffered_rmqueue(struct zone *preferred_zone,
1443 struct zone *zone, int order, gfp_t gfp_flags,
1446 unsigned long flags;
1448 int cold = !!(gfp_flags & __GFP_COLD);
1451 if (likely(order == 0)) {
1452 struct per_cpu_pages *pcp;
1453 struct list_head *list;
1455 local_irq_save(flags);
1456 pcp = &this_cpu_ptr(zone->pageset)->pcp;
1457 list = &pcp->lists[migratetype];
1458 if (list_empty(list)) {
1459 pcp->count += rmqueue_bulk(zone, 0,
1462 if (unlikely(list_empty(list)))
1467 page = list_entry(list->prev, struct page, lru);
1469 page = list_entry(list->next, struct page, lru);
1471 list_del(&page->lru);
1474 if (unlikely(gfp_flags & __GFP_NOFAIL)) {
1476 * __GFP_NOFAIL is not to be used in new code.
1478 * All __GFP_NOFAIL callers should be fixed so that they
1479 * properly detect and handle allocation failures.
1481 * We most definitely don't want callers attempting to
1482 * allocate greater than order-1 page units with
1485 WARN_ON_ONCE(order > 1);
1487 spin_lock_irqsave(&zone->lock, flags);
1488 page = __rmqueue(zone, order, migratetype);
1489 spin_unlock(&zone->lock);
1492 __mod_zone_page_state(zone, NR_FREE_PAGES, -(1 << order));
1495 __count_zone_vm_events(PGALLOC, zone, 1 << order);
1496 zone_statistics(preferred_zone, zone, gfp_flags);
1497 local_irq_restore(flags);
1499 VM_BUG_ON(bad_range(zone, page));
1500 if (prep_new_page(page, order, gfp_flags))
1505 local_irq_restore(flags);
1509 /* The ALLOC_WMARK bits are used as an index to zone->watermark */
1510 #define ALLOC_WMARK_MIN WMARK_MIN
1511 #define ALLOC_WMARK_LOW WMARK_LOW
1512 #define ALLOC_WMARK_HIGH WMARK_HIGH
1513 #define ALLOC_NO_WATERMARKS 0x04 /* don't check watermarks at all */
1515 /* Mask to get the watermark bits */
1516 #define ALLOC_WMARK_MASK (ALLOC_NO_WATERMARKS-1)
1518 #define ALLOC_HARDER 0x10 /* try to alloc harder */
1519 #define ALLOC_HIGH 0x20 /* __GFP_HIGH set */
1520 #define ALLOC_CPUSET 0x40 /* check for correct cpuset */
1522 #ifdef CONFIG_FAIL_PAGE_ALLOC
1525 struct fault_attr attr;
1527 u32 ignore_gfp_highmem;
1528 u32 ignore_gfp_wait;
1530 } fail_page_alloc = {
1531 .attr = FAULT_ATTR_INITIALIZER,
1532 .ignore_gfp_wait = 1,
1533 .ignore_gfp_highmem = 1,
1537 static int __init setup_fail_page_alloc(char *str)
1539 return setup_fault_attr(&fail_page_alloc.attr, str);
1541 __setup("fail_page_alloc=", setup_fail_page_alloc);
1543 static int should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
1545 if (order < fail_page_alloc.min_order)
1547 if (gfp_mask & __GFP_NOFAIL)
1549 if (fail_page_alloc.ignore_gfp_highmem && (gfp_mask & __GFP_HIGHMEM))
1551 if (fail_page_alloc.ignore_gfp_wait && (gfp_mask & __GFP_WAIT))
1554 return should_fail(&fail_page_alloc.attr, 1 << order);
1557 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
1559 static int __init fail_page_alloc_debugfs(void)
1561 umode_t mode = S_IFREG | S_IRUSR | S_IWUSR;
1564 dir = fault_create_debugfs_attr("fail_page_alloc", NULL,
1565 &fail_page_alloc.attr);
1567 return PTR_ERR(dir);
1569 if (!debugfs_create_bool("ignore-gfp-wait", mode, dir,
1570 &fail_page_alloc.ignore_gfp_wait))
1572 if (!debugfs_create_bool("ignore-gfp-highmem", mode, dir,
1573 &fail_page_alloc.ignore_gfp_highmem))
1575 if (!debugfs_create_u32("min-order", mode, dir,
1576 &fail_page_alloc.min_order))
1581 debugfs_remove_recursive(dir);
1586 late_initcall(fail_page_alloc_debugfs);
1588 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
1590 #else /* CONFIG_FAIL_PAGE_ALLOC */
1592 static inline int should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
1597 #endif /* CONFIG_FAIL_PAGE_ALLOC */
1600 * Return true if free pages are above 'mark'. This takes into account the order
1601 * of the allocation.
1603 static bool __zone_watermark_ok(struct zone *z, int order, unsigned long mark,
1604 int classzone_idx, int alloc_flags, long free_pages)
1606 /* free_pages my go negative - that's OK */
1610 free_pages -= (1 << order) - 1;
1611 if (alloc_flags & ALLOC_HIGH)
1613 if (alloc_flags & ALLOC_HARDER)
1616 if (free_pages <= min + z->lowmem_reserve[classzone_idx])
1618 for (o = 0; o < order; o++) {
1619 /* At the next order, this order's pages become unavailable */
1620 free_pages -= z->free_area[o].nr_free << o;
1622 /* Require fewer higher order pages to be free */
1625 if (free_pages <= min)
1631 bool zone_watermark_ok(struct zone *z, int order, unsigned long mark,
1632 int classzone_idx, int alloc_flags)
1634 return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
1635 zone_page_state(z, NR_FREE_PAGES));
1638 bool zone_watermark_ok_safe(struct zone *z, int order, unsigned long mark,
1639 int classzone_idx, int alloc_flags)
1641 long free_pages = zone_page_state(z, NR_FREE_PAGES);
1643 if (z->percpu_drift_mark && free_pages < z->percpu_drift_mark)
1644 free_pages = zone_page_state_snapshot(z, NR_FREE_PAGES);
1646 return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
1652 * zlc_setup - Setup for "zonelist cache". Uses cached zone data to
1653 * skip over zones that are not allowed by the cpuset, or that have
1654 * been recently (in last second) found to be nearly full. See further
1655 * comments in mmzone.h. Reduces cache footprint of zonelist scans
1656 * that have to skip over a lot of full or unallowed zones.
1658 * If the zonelist cache is present in the passed in zonelist, then
1659 * returns a pointer to the allowed node mask (either the current
1660 * tasks mems_allowed, or node_states[N_HIGH_MEMORY].)
1662 * If the zonelist cache is not available for this zonelist, does
1663 * nothing and returns NULL.
1665 * If the fullzones BITMAP in the zonelist cache is stale (more than
1666 * a second since last zap'd) then we zap it out (clear its bits.)
1668 * We hold off even calling zlc_setup, until after we've checked the
1669 * first zone in the zonelist, on the theory that most allocations will
1670 * be satisfied from that first zone, so best to examine that zone as
1671 * quickly as we can.
1673 static nodemask_t *zlc_setup(struct zonelist *zonelist, int alloc_flags)
1675 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1676 nodemask_t *allowednodes; /* zonelist_cache approximation */
1678 zlc = zonelist->zlcache_ptr;
1682 if (time_after(jiffies, zlc->last_full_zap + HZ)) {
1683 bitmap_zero(zlc->fullzones, MAX_ZONES_PER_ZONELIST);
1684 zlc->last_full_zap = jiffies;
1687 allowednodes = !in_interrupt() && (alloc_flags & ALLOC_CPUSET) ?
1688 &cpuset_current_mems_allowed :
1689 &node_states[N_HIGH_MEMORY];
1690 return allowednodes;
1694 * Given 'z' scanning a zonelist, run a couple of quick checks to see
1695 * if it is worth looking at further for free memory:
1696 * 1) Check that the zone isn't thought to be full (doesn't have its
1697 * bit set in the zonelist_cache fullzones BITMAP).
1698 * 2) Check that the zones node (obtained from the zonelist_cache
1699 * z_to_n[] mapping) is allowed in the passed in allowednodes mask.
1700 * Return true (non-zero) if zone is worth looking at further, or
1701 * else return false (zero) if it is not.
1703 * This check -ignores- the distinction between various watermarks,
1704 * such as GFP_HIGH, GFP_ATOMIC, PF_MEMALLOC, ... If a zone is
1705 * found to be full for any variation of these watermarks, it will
1706 * be considered full for up to one second by all requests, unless
1707 * we are so low on memory on all allowed nodes that we are forced
1708 * into the second scan of the zonelist.
1710 * In the second scan we ignore this zonelist cache and exactly
1711 * apply the watermarks to all zones, even it is slower to do so.
1712 * We are low on memory in the second scan, and should leave no stone
1713 * unturned looking for a free page.
1715 static int zlc_zone_worth_trying(struct zonelist *zonelist, struct zoneref *z,
1716 nodemask_t *allowednodes)
1718 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1719 int i; /* index of *z in zonelist zones */
1720 int n; /* node that zone *z is on */
1722 zlc = zonelist->zlcache_ptr;
1726 i = z - zonelist->_zonerefs;
1729 /* This zone is worth trying if it is allowed but not full */
1730 return node_isset(n, *allowednodes) && !test_bit(i, zlc->fullzones);
1734 * Given 'z' scanning a zonelist, set the corresponding bit in
1735 * zlc->fullzones, so that subsequent attempts to allocate a page
1736 * from that zone don't waste time re-examining it.
1738 static void zlc_mark_zone_full(struct zonelist *zonelist, struct zoneref *z)
1740 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1741 int i; /* index of *z in zonelist zones */
1743 zlc = zonelist->zlcache_ptr;
1747 i = z - zonelist->_zonerefs;
1749 set_bit(i, zlc->fullzones);
1753 * clear all zones full, called after direct reclaim makes progress so that
1754 * a zone that was recently full is not skipped over for up to a second
1756 static void zlc_clear_zones_full(struct zonelist *zonelist)
1758 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1760 zlc = zonelist->zlcache_ptr;
1764 bitmap_zero(zlc->fullzones, MAX_ZONES_PER_ZONELIST);
1767 #else /* CONFIG_NUMA */
1769 static nodemask_t *zlc_setup(struct zonelist *zonelist, int alloc_flags)
1774 static int zlc_zone_worth_trying(struct zonelist *zonelist, struct zoneref *z,
1775 nodemask_t *allowednodes)
1780 static void zlc_mark_zone_full(struct zonelist *zonelist, struct zoneref *z)
1784 static void zlc_clear_zones_full(struct zonelist *zonelist)
1787 #endif /* CONFIG_NUMA */
1790 * get_page_from_freelist goes through the zonelist trying to allocate
1793 static struct page *
1794 get_page_from_freelist(gfp_t gfp_mask, nodemask_t *nodemask, unsigned int order,
1795 struct zonelist *zonelist, int high_zoneidx, int alloc_flags,
1796 struct zone *preferred_zone, int migratetype)
1799 struct page *page = NULL;
1802 nodemask_t *allowednodes = NULL;/* zonelist_cache approximation */
1803 int zlc_active = 0; /* set if using zonelist_cache */
1804 int did_zlc_setup = 0; /* just call zlc_setup() one time */
1806 classzone_idx = zone_idx(preferred_zone);
1809 * Scan zonelist, looking for a zone with enough free.
1810 * See also cpuset_zone_allowed() comment in kernel/cpuset.c.
1812 for_each_zone_zonelist_nodemask(zone, z, zonelist,
1813 high_zoneidx, nodemask) {
1814 if (NUMA_BUILD && zlc_active &&
1815 !zlc_zone_worth_trying(zonelist, z, allowednodes))
1817 if ((alloc_flags & ALLOC_CPUSET) &&
1818 !cpuset_zone_allowed_softwall(zone, gfp_mask))
1821 BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK);
1822 if (!(alloc_flags & ALLOC_NO_WATERMARKS)) {
1826 mark = zone->watermark[alloc_flags & ALLOC_WMARK_MASK];
1827 if (zone_watermark_ok(zone, order, mark,
1828 classzone_idx, alloc_flags))
1831 if (NUMA_BUILD && !did_zlc_setup && nr_online_nodes > 1) {
1833 * we do zlc_setup if there are multiple nodes
1834 * and before considering the first zone allowed
1837 allowednodes = zlc_setup(zonelist, alloc_flags);
1842 if (zone_reclaim_mode == 0)
1843 goto this_zone_full;
1846 * As we may have just activated ZLC, check if the first
1847 * eligible zone has failed zone_reclaim recently.
1849 if (NUMA_BUILD && zlc_active &&
1850 !zlc_zone_worth_trying(zonelist, z, allowednodes))
1853 ret = zone_reclaim(zone, gfp_mask, order);
1855 case ZONE_RECLAIM_NOSCAN:
1858 case ZONE_RECLAIM_FULL:
1859 /* scanned but unreclaimable */
1862 /* did we reclaim enough */
1863 if (!zone_watermark_ok(zone, order, mark,
1864 classzone_idx, alloc_flags))
1865 goto this_zone_full;
1870 page = buffered_rmqueue(preferred_zone, zone, order,
1871 gfp_mask, migratetype);
1876 zlc_mark_zone_full(zonelist, z);
1879 if (unlikely(NUMA_BUILD && page == NULL && zlc_active)) {
1880 /* Disable zlc cache for second zonelist scan */
1888 * Large machines with many possible nodes should not always dump per-node
1889 * meminfo in irq context.
1891 static inline bool should_suppress_show_mem(void)
1896 ret = in_interrupt();
1901 static DEFINE_RATELIMIT_STATE(nopage_rs,
1902 DEFAULT_RATELIMIT_INTERVAL,
1903 DEFAULT_RATELIMIT_BURST);
1905 void warn_alloc_failed(gfp_t gfp_mask, int order, const char *fmt, ...)
1907 unsigned int filter = SHOW_MEM_FILTER_NODES;
1909 if ((gfp_mask & __GFP_NOWARN) || !__ratelimit(&nopage_rs) ||
1910 debug_guardpage_minorder() > 0)
1914 * Walking all memory to count page types is very expensive and should
1915 * be inhibited in non-blockable contexts.
1917 if (!(gfp_mask & __GFP_WAIT))
1918 filter |= SHOW_MEM_FILTER_PAGE_COUNT;
1921 * This documents exceptions given to allocations in certain
1922 * contexts that are allowed to allocate outside current's set
1925 if (!(gfp_mask & __GFP_NOMEMALLOC))
1926 if (test_thread_flag(TIF_MEMDIE) ||
1927 (current->flags & (PF_MEMALLOC | PF_EXITING)))
1928 filter &= ~SHOW_MEM_FILTER_NODES;
1929 if (in_interrupt() || !(gfp_mask & __GFP_WAIT))
1930 filter &= ~SHOW_MEM_FILTER_NODES;
1933 struct va_format vaf;
1936 va_start(args, fmt);
1941 pr_warn("%pV", &vaf);
1946 pr_warn("%s: page allocation failure: order:%d, mode:0x%x\n",
1947 current->comm, order, gfp_mask);
1950 if (!should_suppress_show_mem())
1955 should_alloc_retry(gfp_t gfp_mask, unsigned int order,
1956 unsigned long did_some_progress,
1957 unsigned long pages_reclaimed)
1959 /* Do not loop if specifically requested */
1960 if (gfp_mask & __GFP_NORETRY)
1963 /* Always retry if specifically requested */
1964 if (gfp_mask & __GFP_NOFAIL)
1968 * Suspend converts GFP_KERNEL to __GFP_WAIT which can prevent reclaim
1969 * making forward progress without invoking OOM. Suspend also disables
1970 * storage devices so kswapd will not help. Bail if we are suspending.
1972 if (!did_some_progress && pm_suspended_storage())
1976 * In this implementation, order <= PAGE_ALLOC_COSTLY_ORDER
1977 * means __GFP_NOFAIL, but that may not be true in other
1980 if (order <= PAGE_ALLOC_COSTLY_ORDER)
1984 * For order > PAGE_ALLOC_COSTLY_ORDER, if __GFP_REPEAT is
1985 * specified, then we retry until we no longer reclaim any pages
1986 * (above), or we've reclaimed an order of pages at least as
1987 * large as the allocation's order. In both cases, if the
1988 * allocation still fails, we stop retrying.
1990 if (gfp_mask & __GFP_REPEAT && pages_reclaimed < (1 << order))
1996 static inline struct page *
1997 __alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order,
1998 struct zonelist *zonelist, enum zone_type high_zoneidx,
1999 nodemask_t *nodemask, struct zone *preferred_zone,
2004 /* Acquire the OOM killer lock for the zones in zonelist */
2005 if (!try_set_zonelist_oom(zonelist, gfp_mask)) {
2006 schedule_timeout_uninterruptible(1);
2011 * Go through the zonelist yet one more time, keep very high watermark
2012 * here, this is only to catch a parallel oom killing, we must fail if
2013 * we're still under heavy pressure.
2015 page = get_page_from_freelist(gfp_mask|__GFP_HARDWALL, nodemask,
2016 order, zonelist, high_zoneidx,
2017 ALLOC_WMARK_HIGH|ALLOC_CPUSET,
2018 preferred_zone, migratetype);
2022 if (!(gfp_mask & __GFP_NOFAIL)) {
2023 /* The OOM killer will not help higher order allocs */
2024 if (order > PAGE_ALLOC_COSTLY_ORDER)
2026 /* The OOM killer does not needlessly kill tasks for lowmem */
2027 if (high_zoneidx < ZONE_NORMAL)
2030 * GFP_THISNODE contains __GFP_NORETRY and we never hit this.
2031 * Sanity check for bare calls of __GFP_THISNODE, not real OOM.
2032 * The caller should handle page allocation failure by itself if
2033 * it specifies __GFP_THISNODE.
2034 * Note: Hugepage uses it but will hit PAGE_ALLOC_COSTLY_ORDER.
2036 if (gfp_mask & __GFP_THISNODE)
2039 /* Exhausted what can be done so it's blamo time */
2040 out_of_memory(zonelist, gfp_mask, order, nodemask);
2043 clear_zonelist_oom(zonelist, gfp_mask);
2047 #ifdef CONFIG_COMPACTION
2048 /* Try memory compaction for high-order allocations before reclaim */
2049 static struct page *
2050 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
2051 struct zonelist *zonelist, enum zone_type high_zoneidx,
2052 nodemask_t *nodemask, int alloc_flags, struct zone *preferred_zone,
2053 int migratetype, bool sync_migration,
2054 bool *deferred_compaction,
2055 unsigned long *did_some_progress)
2062 if (compaction_deferred(preferred_zone)) {
2063 *deferred_compaction = true;
2067 current->flags |= PF_MEMALLOC;
2068 *did_some_progress = try_to_compact_pages(zonelist, order, gfp_mask,
2069 nodemask, sync_migration);
2070 current->flags &= ~PF_MEMALLOC;
2071 if (*did_some_progress != COMPACT_SKIPPED) {
2073 /* Page migration frees to the PCP lists but we want merging */
2074 drain_pages(get_cpu());
2077 page = get_page_from_freelist(gfp_mask, nodemask,
2078 order, zonelist, high_zoneidx,
2079 alloc_flags, preferred_zone,
2082 preferred_zone->compact_considered = 0;
2083 preferred_zone->compact_defer_shift = 0;
2084 count_vm_event(COMPACTSUCCESS);
2089 * It's bad if compaction run occurs and fails.
2090 * The most likely reason is that pages exist,
2091 * but not enough to satisfy watermarks.
2093 count_vm_event(COMPACTFAIL);
2096 * As async compaction considers a subset of pageblocks, only
2097 * defer if the failure was a sync compaction failure.
2100 defer_compaction(preferred_zone);
2108 static inline struct page *
2109 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
2110 struct zonelist *zonelist, enum zone_type high_zoneidx,
2111 nodemask_t *nodemask, int alloc_flags, struct zone *preferred_zone,
2112 int migratetype, bool sync_migration,
2113 bool *deferred_compaction,
2114 unsigned long *did_some_progress)
2118 #endif /* CONFIG_COMPACTION */
2120 /* Perform direct synchronous page reclaim */
2122 __perform_reclaim(gfp_t gfp_mask, unsigned int order, struct zonelist *zonelist,
2123 nodemask_t *nodemask)
2125 struct reclaim_state reclaim_state;
2130 /* We now go into synchronous reclaim */
2131 cpuset_memory_pressure_bump();
2132 current->flags |= PF_MEMALLOC;
2133 lockdep_set_current_reclaim_state(gfp_mask);
2134 reclaim_state.reclaimed_slab = 0;
2135 current->reclaim_state = &reclaim_state;
2137 progress = try_to_free_pages(zonelist, order, gfp_mask, nodemask);
2139 current->reclaim_state = NULL;
2140 lockdep_clear_current_reclaim_state();
2141 current->flags &= ~PF_MEMALLOC;
2148 /* The really slow allocator path where we enter direct reclaim */
2149 static inline struct page *
2150 __alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order,
2151 struct zonelist *zonelist, enum zone_type high_zoneidx,
2152 nodemask_t *nodemask, int alloc_flags, struct zone *preferred_zone,
2153 int migratetype, unsigned long *did_some_progress)
2155 struct page *page = NULL;
2156 bool drained = false;
2158 *did_some_progress = __perform_reclaim(gfp_mask, order, zonelist,
2160 if (unlikely(!(*did_some_progress)))
2163 /* After successful reclaim, reconsider all zones for allocation */
2165 zlc_clear_zones_full(zonelist);
2168 page = get_page_from_freelist(gfp_mask, nodemask, order,
2169 zonelist, high_zoneidx,
2170 alloc_flags, preferred_zone,
2174 * If an allocation failed after direct reclaim, it could be because
2175 * pages are pinned on the per-cpu lists. Drain them and try again
2177 if (!page && !drained) {
2187 * This is called in the allocator slow-path if the allocation request is of
2188 * sufficient urgency to ignore watermarks and take other desperate measures
2190 static inline struct page *
2191 __alloc_pages_high_priority(gfp_t gfp_mask, unsigned int order,
2192 struct zonelist *zonelist, enum zone_type high_zoneidx,
2193 nodemask_t *nodemask, struct zone *preferred_zone,
2199 page = get_page_from_freelist(gfp_mask, nodemask, order,
2200 zonelist, high_zoneidx, ALLOC_NO_WATERMARKS,
2201 preferred_zone, migratetype);
2203 if (!page && gfp_mask & __GFP_NOFAIL)
2204 wait_iff_congested(preferred_zone, BLK_RW_ASYNC, HZ/50);
2205 } while (!page && (gfp_mask & __GFP_NOFAIL));
2211 void wake_all_kswapd(unsigned int order, struct zonelist *zonelist,
2212 enum zone_type high_zoneidx,
2213 enum zone_type classzone_idx)
2218 for_each_zone_zonelist(zone, z, zonelist, high_zoneidx)
2219 wakeup_kswapd(zone, order, classzone_idx);
2223 gfp_to_alloc_flags(gfp_t gfp_mask)
2225 int alloc_flags = ALLOC_WMARK_MIN | ALLOC_CPUSET;
2226 const bool atomic = !(gfp_mask & (__GFP_WAIT | __GFP_NO_KSWAPD));
2228 /* __GFP_HIGH is assumed to be the same as ALLOC_HIGH to save a branch. */
2229 BUILD_BUG_ON(__GFP_HIGH != (__force gfp_t) ALLOC_HIGH);
2232 * The caller may dip into page reserves a bit more if the caller
2233 * cannot run direct reclaim, or if the caller has realtime scheduling
2234 * policy or is asking for __GFP_HIGH memory. GFP_ATOMIC requests will
2235 * set both ALLOC_HARDER (atomic == true) and ALLOC_HIGH (__GFP_HIGH).
2237 alloc_flags |= (__force int) (gfp_mask & __GFP_HIGH);
2241 * Not worth trying to allocate harder for __GFP_NOMEMALLOC even
2242 * if it can't schedule.
2244 if (!(gfp_mask & __GFP_NOMEMALLOC))
2245 alloc_flags |= ALLOC_HARDER;
2247 * Ignore cpuset mems for GFP_ATOMIC rather than fail, see the
2248 * comment for __cpuset_node_allowed_softwall().
2250 alloc_flags &= ~ALLOC_CPUSET;
2251 } else if (unlikely(rt_task(current)) && !in_interrupt())
2252 alloc_flags |= ALLOC_HARDER;
2254 if (likely(!(gfp_mask & __GFP_NOMEMALLOC))) {
2255 if (!in_interrupt() &&
2256 ((current->flags & PF_MEMALLOC) ||
2257 unlikely(test_thread_flag(TIF_MEMDIE))))
2258 alloc_flags |= ALLOC_NO_WATERMARKS;
2264 static inline struct page *
2265 __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order,
2266 struct zonelist *zonelist, enum zone_type high_zoneidx,
2267 nodemask_t *nodemask, struct zone *preferred_zone,
2270 const gfp_t wait = gfp_mask & __GFP_WAIT;
2271 struct page *page = NULL;
2273 unsigned long pages_reclaimed = 0;
2274 unsigned long did_some_progress;
2275 bool sync_migration = false;
2276 bool deferred_compaction = false;
2279 * In the slowpath, we sanity check order to avoid ever trying to
2280 * reclaim >= MAX_ORDER areas which will never succeed. Callers may
2281 * be using allocators in order of preference for an area that is
2284 if (order >= MAX_ORDER) {
2285 WARN_ON_ONCE(!(gfp_mask & __GFP_NOWARN));
2290 * GFP_THISNODE (meaning __GFP_THISNODE, __GFP_NORETRY and
2291 * __GFP_NOWARN set) should not cause reclaim since the subsystem
2292 * (f.e. slab) using GFP_THISNODE may choose to trigger reclaim
2293 * using a larger set of nodes after it has established that the
2294 * allowed per node queues are empty and that nodes are
2297 if (NUMA_BUILD && (gfp_mask & GFP_THISNODE) == GFP_THISNODE)
2301 if (!(gfp_mask & __GFP_NO_KSWAPD))
2302 wake_all_kswapd(order, zonelist, high_zoneidx,
2303 zone_idx(preferred_zone));
2306 * OK, we're below the kswapd watermark and have kicked background
2307 * reclaim. Now things get more complex, so set up alloc_flags according
2308 * to how we want to proceed.
2310 alloc_flags = gfp_to_alloc_flags(gfp_mask);
2313 * Find the true preferred zone if the allocation is unconstrained by
2316 if (!(alloc_flags & ALLOC_CPUSET) && !nodemask)
2317 first_zones_zonelist(zonelist, high_zoneidx, NULL,
2321 /* This is the last chance, in general, before the goto nopage. */
2322 page = get_page_from_freelist(gfp_mask, nodemask, order, zonelist,
2323 high_zoneidx, alloc_flags & ~ALLOC_NO_WATERMARKS,
2324 preferred_zone, migratetype);
2328 /* Allocate without watermarks if the context allows */
2329 if (alloc_flags & ALLOC_NO_WATERMARKS) {
2330 page = __alloc_pages_high_priority(gfp_mask, order,
2331 zonelist, high_zoneidx, nodemask,
2332 preferred_zone, migratetype);
2337 /* Atomic allocations - we can't balance anything */
2341 /* Avoid recursion of direct reclaim */
2342 if (current->flags & PF_MEMALLOC)
2345 /* Avoid allocations with no watermarks from looping endlessly */
2346 if (test_thread_flag(TIF_MEMDIE) && !(gfp_mask & __GFP_NOFAIL))
2350 * Try direct compaction. The first pass is asynchronous. Subsequent
2351 * attempts after direct reclaim are synchronous
2353 page = __alloc_pages_direct_compact(gfp_mask, order,
2354 zonelist, high_zoneidx,
2356 alloc_flags, preferred_zone,
2357 migratetype, sync_migration,
2358 &deferred_compaction,
2359 &did_some_progress);
2362 sync_migration = true;
2365 * If compaction is deferred for high-order allocations, it is because
2366 * sync compaction recently failed. In this is the case and the caller
2367 * has requested the system not be heavily disrupted, fail the
2368 * allocation now instead of entering direct reclaim
2370 if (deferred_compaction && (gfp_mask & __GFP_NO_KSWAPD))
2373 /* Try direct reclaim and then allocating */
2374 page = __alloc_pages_direct_reclaim(gfp_mask, order,
2375 zonelist, high_zoneidx,
2377 alloc_flags, preferred_zone,
2378 migratetype, &did_some_progress);
2383 * If we failed to make any progress reclaiming, then we are
2384 * running out of options and have to consider going OOM
2386 if (!did_some_progress) {
2387 if ((gfp_mask & __GFP_FS) && !(gfp_mask & __GFP_NORETRY)) {
2388 if (oom_killer_disabled)
2390 page = __alloc_pages_may_oom(gfp_mask, order,
2391 zonelist, high_zoneidx,
2392 nodemask, preferred_zone,
2397 if (!(gfp_mask & __GFP_NOFAIL)) {
2399 * The oom killer is not called for high-order
2400 * allocations that may fail, so if no progress
2401 * is being made, there are no other options and
2402 * retrying is unlikely to help.
2404 if (order > PAGE_ALLOC_COSTLY_ORDER)
2407 * The oom killer is not called for lowmem
2408 * allocations to prevent needlessly killing
2411 if (high_zoneidx < ZONE_NORMAL)
2419 /* Check if we should retry the allocation */
2420 pages_reclaimed += did_some_progress;
2421 if (should_alloc_retry(gfp_mask, order, did_some_progress,
2423 /* Wait for some write requests to complete then retry */
2424 wait_iff_congested(preferred_zone, BLK_RW_ASYNC, HZ/50);
2428 * High-order allocations do not necessarily loop after
2429 * direct reclaim and reclaim/compaction depends on compaction
2430 * being called after reclaim so call directly if necessary
2432 page = __alloc_pages_direct_compact(gfp_mask, order,
2433 zonelist, high_zoneidx,
2435 alloc_flags, preferred_zone,
2436 migratetype, sync_migration,
2437 &deferred_compaction,
2438 &did_some_progress);
2444 warn_alloc_failed(gfp_mask, order, NULL);
2447 if (kmemcheck_enabled)
2448 kmemcheck_pagealloc_alloc(page, order, gfp_mask);
2454 * This is the 'heart' of the zoned buddy allocator.
2457 __alloc_pages_nodemask(gfp_t gfp_mask, unsigned int order,
2458 struct zonelist *zonelist, nodemask_t *nodemask)
2460 enum zone_type high_zoneidx = gfp_zone(gfp_mask);
2461 struct zone *preferred_zone;
2462 struct page *page = NULL;
2463 int migratetype = allocflags_to_migratetype(gfp_mask);
2464 unsigned int cpuset_mems_cookie;
2466 gfp_mask &= gfp_allowed_mask;
2468 lockdep_trace_alloc(gfp_mask);
2470 might_sleep_if(gfp_mask & __GFP_WAIT);
2472 if (should_fail_alloc_page(gfp_mask, order))
2476 * Check the zones suitable for the gfp_mask contain at least one
2477 * valid zone. It's possible to have an empty zonelist as a result
2478 * of GFP_THISNODE and a memoryless node
2480 if (unlikely(!zonelist->_zonerefs->zone))
2484 cpuset_mems_cookie = get_mems_allowed();
2486 /* The preferred zone is used for statistics later */
2487 first_zones_zonelist(zonelist, high_zoneidx,
2488 nodemask ? : &cpuset_current_mems_allowed,
2490 if (!preferred_zone)
2493 /* First allocation attempt */
2494 page = get_page_from_freelist(gfp_mask|__GFP_HARDWALL, nodemask, order,
2495 zonelist, high_zoneidx, ALLOC_WMARK_LOW|ALLOC_CPUSET,
2496 preferred_zone, migratetype);
2497 if (unlikely(!page))
2498 page = __alloc_pages_slowpath(gfp_mask, order,
2499 zonelist, high_zoneidx, nodemask,
2500 preferred_zone, migratetype);
2502 trace_mm_page_alloc(page, order, gfp_mask, migratetype);
2506 * When updating a task's mems_allowed, it is possible to race with
2507 * parallel threads in such a way that an allocation can fail while
2508 * the mask is being updated. If a page allocation is about to fail,
2509 * check if the cpuset changed during allocation and if so, retry.
2511 if (unlikely(!put_mems_allowed(cpuset_mems_cookie) && !page))
2516 EXPORT_SYMBOL(__alloc_pages_nodemask);
2519 * Common helper functions.
2521 unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order)
2526 * __get_free_pages() returns a 32-bit address, which cannot represent
2529 VM_BUG_ON((gfp_mask & __GFP_HIGHMEM) != 0);
2531 page = alloc_pages(gfp_mask, order);
2534 return (unsigned long) page_address(page);
2536 EXPORT_SYMBOL(__get_free_pages);
2538 unsigned long get_zeroed_page(gfp_t gfp_mask)
2540 return __get_free_pages(gfp_mask | __GFP_ZERO, 0);
2542 EXPORT_SYMBOL(get_zeroed_page);
2544 void __free_pages(struct page *page, unsigned int order)
2546 if (put_page_testzero(page)) {
2548 free_hot_cold_page(page, 0);
2550 __free_pages_ok(page, order);
2554 EXPORT_SYMBOL(__free_pages);
2556 void free_pages(unsigned long addr, unsigned int order)
2559 VM_BUG_ON(!virt_addr_valid((void *)addr));
2560 __free_pages(virt_to_page((void *)addr), order);
2564 EXPORT_SYMBOL(free_pages);
2566 static void *make_alloc_exact(unsigned long addr, unsigned order, size_t size)
2569 unsigned long alloc_end = addr + (PAGE_SIZE << order);
2570 unsigned long used = addr + PAGE_ALIGN(size);
2572 split_page(virt_to_page((void *)addr), order);
2573 while (used < alloc_end) {
2578 return (void *)addr;
2582 * alloc_pages_exact - allocate an exact number physically-contiguous pages.
2583 * @size: the number of bytes to allocate
2584 * @gfp_mask: GFP flags for the allocation
2586 * This function is similar to alloc_pages(), except that it allocates the
2587 * minimum number of pages to satisfy the request. alloc_pages() can only
2588 * allocate memory in power-of-two pages.
2590 * This function is also limited by MAX_ORDER.
2592 * Memory allocated by this function must be released by free_pages_exact().
2594 void *alloc_pages_exact(size_t size, gfp_t gfp_mask)
2596 unsigned int order = get_order(size);
2599 addr = __get_free_pages(gfp_mask, order);
2600 return make_alloc_exact(addr, order, size);
2602 EXPORT_SYMBOL(alloc_pages_exact);
2605 * alloc_pages_exact_nid - allocate an exact number of physically-contiguous
2607 * @nid: the preferred node ID where memory should be allocated
2608 * @size: the number of bytes to allocate
2609 * @gfp_mask: GFP flags for the allocation
2611 * Like alloc_pages_exact(), but try to allocate on node nid first before falling
2613 * Note this is not alloc_pages_exact_node() which allocates on a specific node,
2616 void *alloc_pages_exact_nid(int nid, size_t size, gfp_t gfp_mask)
2618 unsigned order = get_order(size);
2619 struct page *p = alloc_pages_node(nid, gfp_mask, order);
2622 return make_alloc_exact((unsigned long)page_address(p), order, size);
2624 EXPORT_SYMBOL(alloc_pages_exact_nid);
2627 * free_pages_exact - release memory allocated via alloc_pages_exact()
2628 * @virt: the value returned by alloc_pages_exact.
2629 * @size: size of allocation, same value as passed to alloc_pages_exact().
2631 * Release the memory allocated by a previous call to alloc_pages_exact.
2633 void free_pages_exact(void *virt, size_t size)
2635 unsigned long addr = (unsigned long)virt;
2636 unsigned long end = addr + PAGE_ALIGN(size);
2638 while (addr < end) {
2643 EXPORT_SYMBOL(free_pages_exact);
2645 static unsigned int nr_free_zone_pages(int offset)
2650 /* Just pick one node, since fallback list is circular */
2651 unsigned int sum = 0;
2653 struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL);
2655 for_each_zone_zonelist(zone, z, zonelist, offset) {
2656 unsigned long size = zone->present_pages;
2657 unsigned long high = high_wmark_pages(zone);
2666 * Amount of free RAM allocatable within ZONE_DMA and ZONE_NORMAL
2668 unsigned int nr_free_buffer_pages(void)
2670 return nr_free_zone_pages(gfp_zone(GFP_USER));
2672 EXPORT_SYMBOL_GPL(nr_free_buffer_pages);
2675 * Amount of free RAM allocatable within all zones
2677 unsigned int nr_free_pagecache_pages(void)
2679 return nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE));
2682 static inline void show_node(struct zone *zone)
2685 printk("Node %d ", zone_to_nid(zone));
2688 void si_meminfo(struct sysinfo *val)
2690 val->totalram = totalram_pages;
2692 val->freeram = global_page_state(NR_FREE_PAGES);
2693 val->bufferram = nr_blockdev_pages();
2694 val->totalhigh = totalhigh_pages;
2695 val->freehigh = nr_free_highpages();
2696 val->mem_unit = PAGE_SIZE;
2699 EXPORT_SYMBOL(si_meminfo);
2702 void si_meminfo_node(struct sysinfo *val, int nid)
2704 pg_data_t *pgdat = NODE_DATA(nid);
2706 val->totalram = pgdat->node_present_pages;
2707 val->freeram = node_page_state(nid, NR_FREE_PAGES);
2708 #ifdef CONFIG_HIGHMEM
2709 val->totalhigh = pgdat->node_zones[ZONE_HIGHMEM].present_pages;
2710 val->freehigh = zone_page_state(&pgdat->node_zones[ZONE_HIGHMEM],
2716 val->mem_unit = PAGE_SIZE;
2721 * Determine whether the node should be displayed or not, depending on whether
2722 * SHOW_MEM_FILTER_NODES was passed to show_free_areas().
2724 bool skip_free_areas_node(unsigned int flags, int nid)
2727 unsigned int cpuset_mems_cookie;
2729 if (!(flags & SHOW_MEM_FILTER_NODES))
2733 cpuset_mems_cookie = get_mems_allowed();
2734 ret = !node_isset(nid, cpuset_current_mems_allowed);
2735 } while (!put_mems_allowed(cpuset_mems_cookie));
2740 #define K(x) ((x) << (PAGE_SHIFT-10))
2743 * Show free area list (used inside shift_scroll-lock stuff)
2744 * We also calculate the percentage fragmentation. We do this by counting the
2745 * memory on each free list with the exception of the first item on the list.
2746 * Suppresses nodes that are not allowed by current's cpuset if
2747 * SHOW_MEM_FILTER_NODES is passed.
2749 void show_free_areas(unsigned int filter)
2754 for_each_populated_zone(zone) {
2755 if (skip_free_areas_node(filter, zone_to_nid(zone)))
2758 printk("%s per-cpu:\n", zone->name);
2760 for_each_online_cpu(cpu) {
2761 struct per_cpu_pageset *pageset;
2763 pageset = per_cpu_ptr(zone->pageset, cpu);
2765 printk("CPU %4d: hi:%5d, btch:%4d usd:%4d\n",
2766 cpu, pageset->pcp.high,
2767 pageset->pcp.batch, pageset->pcp.count);
2771 printk("active_anon:%lu inactive_anon:%lu isolated_anon:%lu\n"
2772 " active_file:%lu inactive_file:%lu isolated_file:%lu\n"
2774 " dirty:%lu writeback:%lu unstable:%lu\n"
2775 " free:%lu slab_reclaimable:%lu slab_unreclaimable:%lu\n"
2776 " mapped:%lu shmem:%lu pagetables:%lu bounce:%lu\n",
2777 global_page_state(NR_ACTIVE_ANON),
2778 global_page_state(NR_INACTIVE_ANON),
2779 global_page_state(NR_ISOLATED_ANON),
2780 global_page_state(NR_ACTIVE_FILE),
2781 global_page_state(NR_INACTIVE_FILE),
2782 global_page_state(NR_ISOLATED_FILE),
2783 global_page_state(NR_UNEVICTABLE),
2784 global_page_state(NR_FILE_DIRTY),
2785 global_page_state(NR_WRITEBACK),
2786 global_page_state(NR_UNSTABLE_NFS),
2787 global_page_state(NR_FREE_PAGES),
2788 global_page_state(NR_SLAB_RECLAIMABLE),
2789 global_page_state(NR_SLAB_UNRECLAIMABLE),
2790 global_page_state(NR_FILE_MAPPED),
2791 global_page_state(NR_SHMEM),
2792 global_page_state(NR_PAGETABLE),
2793 global_page_state(NR_BOUNCE));
2795 for_each_populated_zone(zone) {
2798 if (skip_free_areas_node(filter, zone_to_nid(zone)))
2806 " active_anon:%lukB"
2807 " inactive_anon:%lukB"
2808 " active_file:%lukB"
2809 " inactive_file:%lukB"
2810 " unevictable:%lukB"
2811 " isolated(anon):%lukB"
2812 " isolated(file):%lukB"
2819 " slab_reclaimable:%lukB"
2820 " slab_unreclaimable:%lukB"
2821 " kernel_stack:%lukB"
2825 " writeback_tmp:%lukB"
2826 " pages_scanned:%lu"
2827 " all_unreclaimable? %s"
2830 K(zone_page_state(zone, NR_FREE_PAGES)),
2831 K(min_wmark_pages(zone)),
2832 K(low_wmark_pages(zone)),
2833 K(high_wmark_pages(zone)),
2834 K(zone_page_state(zone, NR_ACTIVE_ANON)),
2835 K(zone_page_state(zone, NR_INACTIVE_ANON)),
2836 K(zone_page_state(zone, NR_ACTIVE_FILE)),
2837 K(zone_page_state(zone, NR_INACTIVE_FILE)),
2838 K(zone_page_state(zone, NR_UNEVICTABLE)),
2839 K(zone_page_state(zone, NR_ISOLATED_ANON)),
2840 K(zone_page_state(zone, NR_ISOLATED_FILE)),
2841 K(zone->present_pages),
2842 K(zone_page_state(zone, NR_MLOCK)),
2843 K(zone_page_state(zone, NR_FILE_DIRTY)),
2844 K(zone_page_state(zone, NR_WRITEBACK)),
2845 K(zone_page_state(zone, NR_FILE_MAPPED)),
2846 K(zone_page_state(zone, NR_SHMEM)),
2847 K(zone_page_state(zone, NR_SLAB_RECLAIMABLE)),
2848 K(zone_page_state(zone, NR_SLAB_UNRECLAIMABLE)),
2849 zone_page_state(zone, NR_KERNEL_STACK) *
2851 K(zone_page_state(zone, NR_PAGETABLE)),
2852 K(zone_page_state(zone, NR_UNSTABLE_NFS)),
2853 K(zone_page_state(zone, NR_BOUNCE)),
2854 K(zone_page_state(zone, NR_WRITEBACK_TEMP)),
2855 zone->pages_scanned,
2856 (zone->all_unreclaimable ? "yes" : "no")
2858 printk("lowmem_reserve[]:");
2859 for (i = 0; i < MAX_NR_ZONES; i++)
2860 printk(" %lu", zone->lowmem_reserve[i]);
2864 for_each_populated_zone(zone) {
2865 unsigned long nr[MAX_ORDER], flags, order, total = 0;
2867 if (skip_free_areas_node(filter, zone_to_nid(zone)))
2870 printk("%s: ", zone->name);
2872 spin_lock_irqsave(&zone->lock, flags);
2873 for (order = 0; order < MAX_ORDER; order++) {
2874 nr[order] = zone->free_area[order].nr_free;
2875 total += nr[order] << order;
2877 spin_unlock_irqrestore(&zone->lock, flags);
2878 for (order = 0; order < MAX_ORDER; order++)
2879 printk("%lu*%lukB ", nr[order], K(1UL) << order);
2880 printk("= %lukB\n", K(total));
2883 printk("%ld total pagecache pages\n", global_page_state(NR_FILE_PAGES));
2885 show_swap_cache_info();
2888 static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref)
2890 zoneref->zone = zone;
2891 zoneref->zone_idx = zone_idx(zone);
2895 * Builds allocation fallback zone lists.
2897 * Add all populated zones of a node to the zonelist.
2899 static int build_zonelists_node(pg_data_t *pgdat, struct zonelist *zonelist,
2900 int nr_zones, enum zone_type zone_type)
2904 BUG_ON(zone_type >= MAX_NR_ZONES);
2909 zone = pgdat->node_zones + zone_type;
2910 if (populated_zone(zone)) {
2911 zoneref_set_zone(zone,
2912 &zonelist->_zonerefs[nr_zones++]);
2913 check_highest_zone(zone_type);
2916 } while (zone_type);
2923 * 0 = automatic detection of better ordering.
2924 * 1 = order by ([node] distance, -zonetype)
2925 * 2 = order by (-zonetype, [node] distance)
2927 * If not NUMA, ZONELIST_ORDER_ZONE and ZONELIST_ORDER_NODE will create
2928 * the same zonelist. So only NUMA can configure this param.
2930 #define ZONELIST_ORDER_DEFAULT 0
2931 #define ZONELIST_ORDER_NODE 1
2932 #define ZONELIST_ORDER_ZONE 2
2934 /* zonelist order in the kernel.
2935 * set_zonelist_order() will set this to NODE or ZONE.
2937 static int current_zonelist_order = ZONELIST_ORDER_DEFAULT;
2938 static char zonelist_order_name[3][8] = {"Default", "Node", "Zone"};
2942 /* The value user specified ....changed by config */
2943 static int user_zonelist_order = ZONELIST_ORDER_DEFAULT;
2944 /* string for sysctl */
2945 #define NUMA_ZONELIST_ORDER_LEN 16
2946 char numa_zonelist_order[16] = "default";
2949 * interface for configure zonelist ordering.
2950 * command line option "numa_zonelist_order"
2951 * = "[dD]efault - default, automatic configuration.
2952 * = "[nN]ode - order by node locality, then by zone within node
2953 * = "[zZ]one - order by zone, then by locality within zone
2956 static int __parse_numa_zonelist_order(char *s)
2958 if (*s == 'd' || *s == 'D') {
2959 user_zonelist_order = ZONELIST_ORDER_DEFAULT;
2960 } else if (*s == 'n' || *s == 'N') {
2961 user_zonelist_order = ZONELIST_ORDER_NODE;
2962 } else if (*s == 'z' || *s == 'Z') {
2963 user_zonelist_order = ZONELIST_ORDER_ZONE;
2966 "Ignoring invalid numa_zonelist_order value: "
2973 static __init int setup_numa_zonelist_order(char *s)
2980 ret = __parse_numa_zonelist_order(s);
2982 strlcpy(numa_zonelist_order, s, NUMA_ZONELIST_ORDER_LEN);
2986 early_param("numa_zonelist_order", setup_numa_zonelist_order);
2989 * sysctl handler for numa_zonelist_order
2991 int numa_zonelist_order_handler(ctl_table *table, int write,
2992 void __user *buffer, size_t *length,
2995 char saved_string[NUMA_ZONELIST_ORDER_LEN];
2997 static DEFINE_MUTEX(zl_order_mutex);
2999 mutex_lock(&zl_order_mutex);
3001 strcpy(saved_string, (char*)table->data);
3002 ret = proc_dostring(table, write, buffer, length, ppos);
3006 int oldval = user_zonelist_order;
3007 if (__parse_numa_zonelist_order((char*)table->data)) {
3009 * bogus value. restore saved string
3011 strncpy((char*)table->data, saved_string,
3012 NUMA_ZONELIST_ORDER_LEN);
3013 user_zonelist_order = oldval;
3014 } else if (oldval != user_zonelist_order) {
3015 mutex_lock(&zonelists_mutex);
3016 build_all_zonelists(NULL);
3017 mutex_unlock(&zonelists_mutex);
3021 mutex_unlock(&zl_order_mutex);
3026 #define MAX_NODE_LOAD (nr_online_nodes)
3027 static int node_load[MAX_NUMNODES];
3030 * find_next_best_node - find the next node that should appear in a given node's fallback list
3031 * @node: node whose fallback list we're appending
3032 * @used_node_mask: nodemask_t of already used nodes
3034 * We use a number of factors to determine which is the next node that should
3035 * appear on a given node's fallback list. The node should not have appeared
3036 * already in @node's fallback list, and it should be the next closest node
3037 * according to the distance array (which contains arbitrary distance values
3038 * from each node to each node in the system), and should also prefer nodes
3039 * with no CPUs, since presumably they'll have very little allocation pressure
3040 * on them otherwise.
3041 * It returns -1 if no node is found.
3043 static int find_next_best_node(int node, nodemask_t *used_node_mask)
3046 int min_val = INT_MAX;
3048 const struct cpumask *tmp = cpumask_of_node(0);
3050 /* Use the local node if we haven't already */
3051 if (!node_isset(node, *used_node_mask)) {
3052 node_set(node, *used_node_mask);
3056 for_each_node_state(n, N_HIGH_MEMORY) {
3058 /* Don't want a node to appear more than once */
3059 if (node_isset(n, *used_node_mask))
3062 /* Use the distance array to find the distance */
3063 val = node_distance(node, n);
3065 /* Penalize nodes under us ("prefer the next node") */
3068 /* Give preference to headless and unused nodes */
3069 tmp = cpumask_of_node(n);
3070 if (!cpumask_empty(tmp))
3071 val += PENALTY_FOR_NODE_WITH_CPUS;
3073 /* Slight preference for less loaded node */
3074 val *= (MAX_NODE_LOAD*MAX_NUMNODES);
3075 val += node_load[n];
3077 if (val < min_val) {
3084 node_set(best_node, *used_node_mask);
3091 * Build zonelists ordered by node and zones within node.
3092 * This results in maximum locality--normal zone overflows into local
3093 * DMA zone, if any--but risks exhausting DMA zone.
3095 static void build_zonelists_in_node_order(pg_data_t *pgdat, int node)
3098 struct zonelist *zonelist;
3100 zonelist = &pgdat->node_zonelists[0];
3101 for (j = 0; zonelist->_zonerefs[j].zone != NULL; j++)
3103 j = build_zonelists_node(NODE_DATA(node), zonelist, j,
3105 zonelist->_zonerefs[j].zone = NULL;
3106 zonelist->_zonerefs[j].zone_idx = 0;
3110 * Build gfp_thisnode zonelists
3112 static void build_thisnode_zonelists(pg_data_t *pgdat)
3115 struct zonelist *zonelist;
3117 zonelist = &pgdat->node_zonelists[1];
3118 j = build_zonelists_node(pgdat, zonelist, 0, MAX_NR_ZONES - 1);
3119 zonelist->_zonerefs[j].zone = NULL;
3120 zonelist->_zonerefs[j].zone_idx = 0;
3124 * Build zonelists ordered by zone and nodes within zones.
3125 * This results in conserving DMA zone[s] until all Normal memory is
3126 * exhausted, but results in overflowing to remote node while memory
3127 * may still exist in local DMA zone.
3129 static int node_order[MAX_NUMNODES];
3131 static void build_zonelists_in_zone_order(pg_data_t *pgdat, int nr_nodes)
3134 int zone_type; /* needs to be signed */
3136 struct zonelist *zonelist;
3138 zonelist = &pgdat->node_zonelists[0];
3140 for (zone_type = MAX_NR_ZONES - 1; zone_type >= 0; zone_type--) {
3141 for (j = 0; j < nr_nodes; j++) {
3142 node = node_order[j];
3143 z = &NODE_DATA(node)->node_zones[zone_type];
3144 if (populated_zone(z)) {
3146 &zonelist->_zonerefs[pos++]);
3147 check_highest_zone(zone_type);
3151 zonelist->_zonerefs[pos].zone = NULL;
3152 zonelist->_zonerefs[pos].zone_idx = 0;
3155 static int default_zonelist_order(void)
3158 unsigned long low_kmem_size,total_size;
3162 * ZONE_DMA and ZONE_DMA32 can be very small area in the system.
3163 * If they are really small and used heavily, the system can fall
3164 * into OOM very easily.
3165 * This function detect ZONE_DMA/DMA32 size and configures zone order.
3167 /* Is there ZONE_NORMAL ? (ex. ppc has only DMA zone..) */
3170 for_each_online_node(nid) {
3171 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
3172 z = &NODE_DATA(nid)->node_zones[zone_type];
3173 if (populated_zone(z)) {
3174 if (zone_type < ZONE_NORMAL)
3175 low_kmem_size += z->present_pages;
3176 total_size += z->present_pages;
3177 } else if (zone_type == ZONE_NORMAL) {
3179 * If any node has only lowmem, then node order
3180 * is preferred to allow kernel allocations
3181 * locally; otherwise, they can easily infringe
3182 * on other nodes when there is an abundance of
3183 * lowmem available to allocate from.
3185 return ZONELIST_ORDER_NODE;
3189 if (!low_kmem_size || /* there are no DMA area. */
3190 low_kmem_size > total_size/2) /* DMA/DMA32 is big. */
3191 return ZONELIST_ORDER_NODE;
3193 * look into each node's config.
3194 * If there is a node whose DMA/DMA32 memory is very big area on
3195 * local memory, NODE_ORDER may be suitable.
3197 average_size = total_size /
3198 (nodes_weight(node_states[N_HIGH_MEMORY]) + 1);
3199 for_each_online_node(nid) {
3202 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
3203 z = &NODE_DATA(nid)->node_zones[zone_type];
3204 if (populated_zone(z)) {
3205 if (zone_type < ZONE_NORMAL)
3206 low_kmem_size += z->present_pages;
3207 total_size += z->present_pages;
3210 if (low_kmem_size &&
3211 total_size > average_size && /* ignore small node */
3212 low_kmem_size > total_size * 70/100)
3213 return ZONELIST_ORDER_NODE;
3215 return ZONELIST_ORDER_ZONE;
3218 static void set_zonelist_order(void)
3220 if (user_zonelist_order == ZONELIST_ORDER_DEFAULT)
3221 current_zonelist_order = default_zonelist_order();
3223 current_zonelist_order = user_zonelist_order;
3226 static void build_zonelists(pg_data_t *pgdat)
3230 nodemask_t used_mask;
3231 int local_node, prev_node;
3232 struct zonelist *zonelist;
3233 int order = current_zonelist_order;
3235 /* initialize zonelists */
3236 for (i = 0; i < MAX_ZONELISTS; i++) {
3237 zonelist = pgdat->node_zonelists + i;
3238 zonelist->_zonerefs[0].zone = NULL;
3239 zonelist->_zonerefs[0].zone_idx = 0;
3242 /* NUMA-aware ordering of nodes */
3243 local_node = pgdat->node_id;
3244 load = nr_online_nodes;
3245 prev_node = local_node;
3246 nodes_clear(used_mask);
3248 memset(node_order, 0, sizeof(node_order));
3251 while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
3252 int distance = node_distance(local_node, node);
3255 * If another node is sufficiently far away then it is better
3256 * to reclaim pages in a zone before going off node.
3258 if (distance > RECLAIM_DISTANCE)
3259 zone_reclaim_mode = 1;
3262 * We don't want to pressure a particular node.
3263 * So adding penalty to the first node in same
3264 * distance group to make it round-robin.
3266 if (distance != node_distance(local_node, prev_node))
3267 node_load[node] = load;
3271 if (order == ZONELIST_ORDER_NODE)
3272 build_zonelists_in_node_order(pgdat, node);
3274 node_order[j++] = node; /* remember order */
3277 if (order == ZONELIST_ORDER_ZONE) {
3278 /* calculate node order -- i.e., DMA last! */
3279 build_zonelists_in_zone_order(pgdat, j);
3282 build_thisnode_zonelists(pgdat);
3285 /* Construct the zonelist performance cache - see further mmzone.h */
3286 static void build_zonelist_cache(pg_data_t *pgdat)
3288 struct zonelist *zonelist;
3289 struct zonelist_cache *zlc;
3292 zonelist = &pgdat->node_zonelists[0];
3293 zonelist->zlcache_ptr = zlc = &zonelist->zlcache;
3294 bitmap_zero(zlc->fullzones, MAX_ZONES_PER_ZONELIST);
3295 for (z = zonelist->_zonerefs; z->zone; z++)
3296 zlc->z_to_n[z - zonelist->_zonerefs] = zonelist_node_idx(z);
3299 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
3301 * Return node id of node used for "local" allocations.
3302 * I.e., first node id of first zone in arg node's generic zonelist.
3303 * Used for initializing percpu 'numa_mem', which is used primarily
3304 * for kernel allocations, so use GFP_KERNEL flags to locate zonelist.
3306 int local_memory_node(int node)
3310 (void)first_zones_zonelist(node_zonelist(node, GFP_KERNEL),
3311 gfp_zone(GFP_KERNEL),
3318 #else /* CONFIG_NUMA */
3320 static void set_zonelist_order(void)
3322 current_zonelist_order = ZONELIST_ORDER_ZONE;
3325 static void build_zonelists(pg_data_t *pgdat)
3327 int node, local_node;
3329 struct zonelist *zonelist;
3331 local_node = pgdat->node_id;
3333 zonelist = &pgdat->node_zonelists[0];
3334 j = build_zonelists_node(pgdat, zonelist, 0, MAX_NR_ZONES - 1);
3337 * Now we build the zonelist so that it contains the zones
3338 * of all the other nodes.
3339 * We don't want to pressure a particular node, so when
3340 * building the zones for node N, we make sure that the
3341 * zones coming right after the local ones are those from
3342 * node N+1 (modulo N)
3344 for (node = local_node + 1; node < MAX_NUMNODES; node++) {
3345 if (!node_online(node))
3347 j = build_zonelists_node(NODE_DATA(node), zonelist, j,
3350 for (node = 0; node < local_node; node++) {
3351 if (!node_online(node))
3353 j = build_zonelists_node(NODE_DATA(node), zonelist, j,
3357 zonelist->_zonerefs[j].zone = NULL;
3358 zonelist->_zonerefs[j].zone_idx = 0;
3361 /* non-NUMA variant of zonelist performance cache - just NULL zlcache_ptr */
3362 static void build_zonelist_cache(pg_data_t *pgdat)
3364 pgdat->node_zonelists[0].zlcache_ptr = NULL;
3367 #endif /* CONFIG_NUMA */
3370 * Boot pageset table. One per cpu which is going to be used for all
3371 * zones and all nodes. The parameters will be set in such a way
3372 * that an item put on a list will immediately be handed over to
3373 * the buddy list. This is safe since pageset manipulation is done
3374 * with interrupts disabled.
3376 * The boot_pagesets must be kept even after bootup is complete for
3377 * unused processors and/or zones. They do play a role for bootstrapping
3378 * hotplugged processors.
3380 * zoneinfo_show() and maybe other functions do
3381 * not check if the processor is online before following the pageset pointer.
3382 * Other parts of the kernel may not check if the zone is available.
3384 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch);
3385 static DEFINE_PER_CPU(struct per_cpu_pageset, boot_pageset);
3386 static void setup_zone_pageset(struct zone *zone);
3389 * Global mutex to protect against size modification of zonelists
3390 * as well as to serialize pageset setup for the new populated zone.
3392 DEFINE_MUTEX(zonelists_mutex);
3394 /* return values int ....just for stop_machine() */
3395 static __init_refok int __build_all_zonelists(void *data)
3401 memset(node_load, 0, sizeof(node_load));
3403 for_each_online_node(nid) {
3404 pg_data_t *pgdat = NODE_DATA(nid);
3406 build_zonelists(pgdat);
3407 build_zonelist_cache(pgdat);
3411 * Initialize the boot_pagesets that are going to be used
3412 * for bootstrapping processors. The real pagesets for
3413 * each zone will be allocated later when the per cpu
3414 * allocator is available.
3416 * boot_pagesets are used also for bootstrapping offline
3417 * cpus if the system is already booted because the pagesets
3418 * are needed to initialize allocators on a specific cpu too.
3419 * F.e. the percpu allocator needs the page allocator which
3420 * needs the percpu allocator in order to allocate its pagesets
3421 * (a chicken-egg dilemma).
3423 for_each_possible_cpu(cpu) {
3424 setup_pageset(&per_cpu(boot_pageset, cpu), 0);
3426 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
3428 * We now know the "local memory node" for each node--
3429 * i.e., the node of the first zone in the generic zonelist.
3430 * Set up numa_mem percpu variable for on-line cpus. During
3431 * boot, only the boot cpu should be on-line; we'll init the
3432 * secondary cpus' numa_mem as they come on-line. During
3433 * node/memory hotplug, we'll fixup all on-line cpus.
3435 if (cpu_online(cpu))
3436 set_cpu_numa_mem(cpu, local_memory_node(cpu_to_node(cpu)));
3444 * Called with zonelists_mutex held always
3445 * unless system_state == SYSTEM_BOOTING.
3447 void __ref build_all_zonelists(void *data)
3449 set_zonelist_order();
3451 if (system_state == SYSTEM_BOOTING) {
3452 __build_all_zonelists(NULL);
3453 mminit_verify_zonelist();
3454 cpuset_init_current_mems_allowed();
3456 /* we have to stop all cpus to guarantee there is no user
3458 #ifdef CONFIG_MEMORY_HOTPLUG
3460 setup_zone_pageset((struct zone *)data);
3462 stop_machine(__build_all_zonelists, NULL, NULL);
3463 /* cpuset refresh routine should be here */
3465 vm_total_pages = nr_free_pagecache_pages();
3467 * Disable grouping by mobility if the number of pages in the
3468 * system is too low to allow the mechanism to work. It would be
3469 * more accurate, but expensive to check per-zone. This check is
3470 * made on memory-hotadd so a system can start with mobility
3471 * disabled and enable it later
3473 if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES))
3474 page_group_by_mobility_disabled = 1;
3476 page_group_by_mobility_disabled = 0;
3478 printk("Built %i zonelists in %s order, mobility grouping %s. "
3479 "Total pages: %ld\n",
3481 zonelist_order_name[current_zonelist_order],
3482 page_group_by_mobility_disabled ? "off" : "on",
3485 printk("Policy zone: %s\n", zone_names[policy_zone]);
3490 * Helper functions to size the waitqueue hash table.
3491 * Essentially these want to choose hash table sizes sufficiently
3492 * large so that collisions trying to wait on pages are rare.
3493 * But in fact, the number of active page waitqueues on typical
3494 * systems is ridiculously low, less than 200. So this is even
3495 * conservative, even though it seems large.
3497 * The constant PAGES_PER_WAITQUEUE specifies the ratio of pages to
3498 * waitqueues, i.e. the size of the waitq table given the number of pages.
3500 #define PAGES_PER_WAITQUEUE 256
3502 #ifndef CONFIG_MEMORY_HOTPLUG
3503 static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
3505 unsigned long size = 1;
3507 pages /= PAGES_PER_WAITQUEUE;
3509 while (size < pages)
3513 * Once we have dozens or even hundreds of threads sleeping
3514 * on IO we've got bigger problems than wait queue collision.
3515 * Limit the size of the wait table to a reasonable size.
3517 size = min(size, 4096UL);
3519 return max(size, 4UL);
3523 * A zone's size might be changed by hot-add, so it is not possible to determine
3524 * a suitable size for its wait_table. So we use the maximum size now.
3526 * The max wait table size = 4096 x sizeof(wait_queue_head_t). ie:
3528 * i386 (preemption config) : 4096 x 16 = 64Kbyte.
3529 * ia64, x86-64 (no preemption): 4096 x 20 = 80Kbyte.
3530 * ia64, x86-64 (preemption) : 4096 x 24 = 96Kbyte.
3532 * The maximum entries are prepared when a zone's memory is (512K + 256) pages
3533 * or more by the traditional way. (See above). It equals:
3535 * i386, x86-64, powerpc(4K page size) : = ( 2G + 1M)byte.
3536 * ia64(16K page size) : = ( 8G + 4M)byte.
3537 * powerpc (64K page size) : = (32G +16M)byte.
3539 static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
3546 * This is an integer logarithm so that shifts can be used later
3547 * to extract the more random high bits from the multiplicative
3548 * hash function before the remainder is taken.
3550 static inline unsigned long wait_table_bits(unsigned long size)
3555 #define LONG_ALIGN(x) (((x)+(sizeof(long))-1)&~((sizeof(long))-1))
3558 * Check if a pageblock contains reserved pages
3560 static int pageblock_is_reserved(unsigned long start_pfn, unsigned long end_pfn)
3564 for (pfn = start_pfn; pfn < end_pfn; pfn++) {
3565 if (!pfn_valid_within(pfn) || PageReserved(pfn_to_page(pfn)))
3572 * Mark a number of pageblocks as MIGRATE_RESERVE. The number
3573 * of blocks reserved is based on min_wmark_pages(zone). The memory within
3574 * the reserve will tend to store contiguous free pages. Setting min_free_kbytes
3575 * higher will lead to a bigger reserve which will get freed as contiguous
3576 * blocks as reclaim kicks in
3578 static void setup_zone_migrate_reserve(struct zone *zone)
3580 unsigned long start_pfn, pfn, end_pfn, block_end_pfn;
3582 unsigned long block_migratetype;
3586 * Get the start pfn, end pfn and the number of blocks to reserve
3587 * We have to be careful to be aligned to pageblock_nr_pages to
3588 * make sure that we always check pfn_valid for the first page in
3591 start_pfn = zone->zone_start_pfn;
3592 end_pfn = start_pfn + zone->spanned_pages;
3593 start_pfn = roundup(start_pfn, pageblock_nr_pages);
3594 reserve = roundup(min_wmark_pages(zone), pageblock_nr_pages) >>
3598 * Reserve blocks are generally in place to help high-order atomic
3599 * allocations that are short-lived. A min_free_kbytes value that
3600 * would result in more than 2 reserve blocks for atomic allocations
3601 * is assumed to be in place to help anti-fragmentation for the
3602 * future allocation of hugepages at runtime.
3604 reserve = min(2, reserve);
3606 for (pfn = start_pfn; pfn < end_pfn; pfn += pageblock_nr_pages) {
3607 if (!pfn_valid(pfn))
3609 page = pfn_to_page(pfn);
3611 /* Watch out for overlapping nodes */
3612 if (page_to_nid(page) != zone_to_nid(zone))
3615 block_migratetype = get_pageblock_migratetype(page);
3617 /* Only test what is necessary when the reserves are not met */
3620 * Blocks with reserved pages will never free, skip
3623 block_end_pfn = min(pfn + pageblock_nr_pages, end_pfn);
3624 if (pageblock_is_reserved(pfn, block_end_pfn))
3627 /* If this block is reserved, account for it */
3628 if (block_migratetype == MIGRATE_RESERVE) {
3633 /* Suitable for reserving if this block is movable */
3634 if (block_migratetype == MIGRATE_MOVABLE) {
3635 set_pageblock_migratetype(page,
3637 move_freepages_block(zone, page,
3645 * If the reserve is met and this is a previous reserved block,
3648 if (block_migratetype == MIGRATE_RESERVE) {
3649 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
3650 move_freepages_block(zone, page, MIGRATE_MOVABLE);
3656 * Initially all pages are reserved - free ones are freed
3657 * up by free_all_bootmem() once the early boot process is
3658 * done. Non-atomic initialization, single-pass.
3660 void __meminit memmap_init_zone(unsigned long size, int nid, unsigned long zone,
3661 unsigned long start_pfn, enum memmap_context context)
3664 unsigned long end_pfn = start_pfn + size;
3668 if (highest_memmap_pfn < end_pfn - 1)
3669 highest_memmap_pfn = end_pfn - 1;
3671 z = &NODE_DATA(nid)->node_zones[zone];
3672 for (pfn = start_pfn; pfn < end_pfn; pfn++) {
3674 * There can be holes in boot-time mem_map[]s
3675 * handed to this function. They do not
3676 * exist on hotplugged memory.
3678 if (context == MEMMAP_EARLY) {
3679 if (!early_pfn_valid(pfn))
3681 if (!early_pfn_in_nid(pfn, nid))
3684 page = pfn_to_page(pfn);
3685 set_page_links(page, zone, nid, pfn);
3686 mminit_verify_page_links(page, zone, nid, pfn);
3687 init_page_count(page);
3688 reset_page_mapcount(page);
3689 SetPageReserved(page);
3691 * Mark the block movable so that blocks are reserved for
3692 * movable at startup. This will force kernel allocations
3693 * to reserve their blocks rather than leaking throughout
3694 * the address space during boot when many long-lived
3695 * kernel allocations are made. Later some blocks near
3696 * the start are marked MIGRATE_RESERVE by
3697 * setup_zone_migrate_reserve()
3699 * bitmap is created for zone's valid pfn range. but memmap
3700 * can be created for invalid pages (for alignment)
3701 * check here not to call set_pageblock_migratetype() against
3704 if ((z->zone_start_pfn <= pfn)
3705 && (pfn < z->zone_start_pfn + z->spanned_pages)
3706 && !(pfn & (pageblock_nr_pages - 1)))
3707 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
3709 INIT_LIST_HEAD(&page->lru);
3710 #ifdef WANT_PAGE_VIRTUAL
3711 /* The shift won't overflow because ZONE_NORMAL is below 4G. */
3712 if (!is_highmem_idx(zone))
3713 set_page_address(page, __va(pfn << PAGE_SHIFT));
3718 static void __meminit zone_init_free_lists(struct zone *zone)
3721 for_each_migratetype_order(order, t) {
3722 INIT_LIST_HEAD(&zone->free_area[order].free_list[t]);
3723 zone->free_area[order].nr_free = 0;
3727 #ifndef __HAVE_ARCH_MEMMAP_INIT
3728 #define memmap_init(size, nid, zone, start_pfn) \
3729 memmap_init_zone((size), (nid), (zone), (start_pfn), MEMMAP_EARLY)
3732 static int zone_batchsize(struct zone *zone)
3738 * The per-cpu-pages pools are set to around 1000th of the
3739 * size of the zone. But no more than 1/2 of a meg.
3741 * OK, so we don't know how big the cache is. So guess.
3743 batch = zone->present_pages / 1024;
3744 if (batch * PAGE_SIZE > 512 * 1024)
3745 batch = (512 * 1024) / PAGE_SIZE;
3746 batch /= 4; /* We effectively *= 4 below */
3751 * Clamp the batch to a 2^n - 1 value. Having a power
3752 * of 2 value was found to be more likely to have
3753 * suboptimal cache aliasing properties in some cases.
3755 * For example if 2 tasks are alternately allocating
3756 * batches of pages, one task can end up with a lot
3757 * of pages of one half of the possible page colors
3758 * and the other with pages of the other colors.
3760 batch = rounddown_pow_of_two(batch + batch/2) - 1;
3765 /* The deferral and batching of frees should be suppressed under NOMMU
3768 * The problem is that NOMMU needs to be able to allocate large chunks
3769 * of contiguous memory as there's no hardware page translation to
3770 * assemble apparent contiguous memory from discontiguous pages.
3772 * Queueing large contiguous runs of pages for batching, however,
3773 * causes the pages to actually be freed in smaller chunks. As there
3774 * can be a significant delay between the individual batches being
3775 * recycled, this leads to the once large chunks of space being
3776 * fragmented and becoming unavailable for high-order allocations.
3782 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch)
3784 struct per_cpu_pages *pcp;
3787 memset(p, 0, sizeof(*p));
3791 pcp->high = 6 * batch;
3792 pcp->batch = max(1UL, 1 * batch);
3793 for (migratetype = 0; migratetype < MIGRATE_PCPTYPES; migratetype++)
3794 INIT_LIST_HEAD(&pcp->lists[migratetype]);
3798 * setup_pagelist_highmark() sets the high water mark for hot per_cpu_pagelist
3799 * to the value high for the pageset p.
3802 static void setup_pagelist_highmark(struct per_cpu_pageset *p,
3805 struct per_cpu_pages *pcp;
3809 pcp->batch = max(1UL, high/4);
3810 if ((high/4) > (PAGE_SHIFT * 8))
3811 pcp->batch = PAGE_SHIFT * 8;
3814 static void setup_zone_pageset(struct zone *zone)
3818 zone->pageset = alloc_percpu(struct per_cpu_pageset);
3820 for_each_possible_cpu(cpu) {
3821 struct per_cpu_pageset *pcp = per_cpu_ptr(zone->pageset, cpu);
3823 setup_pageset(pcp, zone_batchsize(zone));
3825 if (percpu_pagelist_fraction)
3826 setup_pagelist_highmark(pcp,
3827 (zone->present_pages /
3828 percpu_pagelist_fraction));
3833 * Allocate per cpu pagesets and initialize them.
3834 * Before this call only boot pagesets were available.
3836 void __init setup_per_cpu_pageset(void)
3840 for_each_populated_zone(zone)
3841 setup_zone_pageset(zone);
3844 static noinline __init_refok
3845 int zone_wait_table_init(struct zone *zone, unsigned long zone_size_pages)
3848 struct pglist_data *pgdat = zone->zone_pgdat;
3852 * The per-page waitqueue mechanism uses hashed waitqueues
3855 zone->wait_table_hash_nr_entries =
3856 wait_table_hash_nr_entries(zone_size_pages);
3857 zone->wait_table_bits =
3858 wait_table_bits(zone->wait_table_hash_nr_entries);
3859 alloc_size = zone->wait_table_hash_nr_entries
3860 * sizeof(wait_queue_head_t);
3862 if (!slab_is_available()) {
3863 zone->wait_table = (wait_queue_head_t *)
3864 alloc_bootmem_node_nopanic(pgdat, alloc_size);
3867 * This case means that a zone whose size was 0 gets new memory
3868 * via memory hot-add.
3869 * But it may be the case that a new node was hot-added. In
3870 * this case vmalloc() will not be able to use this new node's
3871 * memory - this wait_table must be initialized to use this new
3872 * node itself as well.
3873 * To use this new node's memory, further consideration will be
3876 zone->wait_table = vmalloc(alloc_size);
3878 if (!zone->wait_table)
3881 for(i = 0; i < zone->wait_table_hash_nr_entries; ++i)
3882 init_waitqueue_head(zone->wait_table + i);
3887 static int __zone_pcp_update(void *data)
3889 struct zone *zone = data;
3891 unsigned long batch = zone_batchsize(zone), flags;
3893 for_each_possible_cpu(cpu) {
3894 struct per_cpu_pageset *pset;
3895 struct per_cpu_pages *pcp;
3897 pset = per_cpu_ptr(zone->pageset, cpu);
3900 local_irq_save(flags);
3901 free_pcppages_bulk(zone, pcp->count, pcp);
3902 setup_pageset(pset, batch);
3903 local_irq_restore(flags);
3908 void zone_pcp_update(struct zone *zone)
3910 stop_machine(__zone_pcp_update, zone, NULL);
3913 static __meminit void zone_pcp_init(struct zone *zone)
3916 * per cpu subsystem is not up at this point. The following code
3917 * relies on the ability of the linker to provide the
3918 * offset of a (static) per cpu variable into the per cpu area.
3920 zone->pageset = &boot_pageset;
3922 if (zone->present_pages)
3923 printk(KERN_DEBUG " %s zone: %lu pages, LIFO batch:%u\n",
3924 zone->name, zone->present_pages,
3925 zone_batchsize(zone));
3928 __meminit int init_currently_empty_zone(struct zone *zone,
3929 unsigned long zone_start_pfn,
3931 enum memmap_context context)
3933 struct pglist_data *pgdat = zone->zone_pgdat;
3935 ret = zone_wait_table_init(zone, size);
3938 pgdat->nr_zones = zone_idx(zone) + 1;
3940 zone->zone_start_pfn = zone_start_pfn;
3942 mminit_dprintk(MMINIT_TRACE, "memmap_init",
3943 "Initialising map node %d zone %lu pfns %lu -> %lu\n",
3945 (unsigned long)zone_idx(zone),
3946 zone_start_pfn, (zone_start_pfn + size));
3948 zone_init_free_lists(zone);
3953 #ifdef CONFIG_ARCH_POPULATES_NODE_MAP
3955 * Basic iterator support. Return the first range of PFNs for a node
3956 * Note: nid == MAX_NUMNODES returns first region regardless of node
3958 static int __meminit first_active_region_index_in_nid(int nid)
3962 for (i = 0; i < nr_nodemap_entries; i++)
3963 if (nid == MAX_NUMNODES || early_node_map[i].nid == nid)
3970 * Basic iterator support. Return the next active range of PFNs for a node
3971 * Note: nid == MAX_NUMNODES returns next region regardless of node
3973 static int __meminit next_active_region_index_in_nid(int index, int nid)
3975 for (index = index + 1; index < nr_nodemap_entries; index++)
3976 if (nid == MAX_NUMNODES || early_node_map[index].nid == nid)
3982 #ifndef CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID
3984 * Required by SPARSEMEM. Given a PFN, return what node the PFN is on.
3985 * Architectures may implement their own version but if add_active_range()
3986 * was used and there are no special requirements, this is a convenient
3989 int __meminit __early_pfn_to_nid(unsigned long pfn)
3993 for (i = 0; i < nr_nodemap_entries; i++) {
3994 unsigned long start_pfn = early_node_map[i].start_pfn;
3995 unsigned long end_pfn = early_node_map[i].end_pfn;
3997 if (start_pfn <= pfn && pfn < end_pfn)
3998 return early_node_map[i].nid;
4000 /* This is a memory hole */
4003 #endif /* CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID */
4005 int __meminit early_pfn_to_nid(unsigned long pfn)
4009 nid = __early_pfn_to_nid(pfn);
4012 /* just returns 0 */
4016 #ifdef CONFIG_NODES_SPAN_OTHER_NODES
4017 bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
4021 nid = __early_pfn_to_nid(pfn);
4022 if (nid >= 0 && nid != node)
4028 /* Basic iterator support to walk early_node_map[] */
4029 #define for_each_active_range_index_in_nid(i, nid) \
4030 for (i = first_active_region_index_in_nid(nid); i != -1; \
4031 i = next_active_region_index_in_nid(i, nid))
4034 * free_bootmem_with_active_regions - Call free_bootmem_node for each active range
4035 * @nid: The node to free memory on. If MAX_NUMNODES, all nodes are freed.
4036 * @max_low_pfn: The highest PFN that will be passed to free_bootmem_node
4038 * If an architecture guarantees that all ranges registered with
4039 * add_active_ranges() contain no holes and may be freed, this
4040 * this function may be used instead of calling free_bootmem() manually.
4042 void __init free_bootmem_with_active_regions(int nid,
4043 unsigned long max_low_pfn)
4047 for_each_active_range_index_in_nid(i, nid) {
4048 unsigned long size_pages = 0;
4049 unsigned long end_pfn = early_node_map[i].end_pfn;
4051 if (early_node_map[i].start_pfn >= max_low_pfn)
4054 if (end_pfn > max_low_pfn)
4055 end_pfn = max_low_pfn;
4057 size_pages = end_pfn - early_node_map[i].start_pfn;
4058 free_bootmem_node(NODE_DATA(early_node_map[i].nid),
4059 PFN_PHYS(early_node_map[i].start_pfn),
4060 size_pages << PAGE_SHIFT);
4064 #ifdef CONFIG_HAVE_MEMBLOCK
4066 * Basic iterator support. Return the last range of PFNs for a node
4067 * Note: nid == MAX_NUMNODES returns last region regardless of node
4069 static int __meminit last_active_region_index_in_nid(int nid)
4073 for (i = nr_nodemap_entries - 1; i >= 0; i--)
4074 if (nid == MAX_NUMNODES || early_node_map[i].nid == nid)
4081 * Basic iterator support. Return the previous active range of PFNs for a node
4082 * Note: nid == MAX_NUMNODES returns next region regardless of node
4084 static int __meminit previous_active_region_index_in_nid(int index, int nid)
4086 for (index = index - 1; index >= 0; index--)
4087 if (nid == MAX_NUMNODES || early_node_map[index].nid == nid)
4093 #define for_each_active_range_index_in_nid_reverse(i, nid) \
4094 for (i = last_active_region_index_in_nid(nid); i != -1; \
4095 i = previous_active_region_index_in_nid(i, nid))
4097 u64 __init find_memory_core_early(int nid, u64 size, u64 align,
4098 u64 goal, u64 limit)
4102 /* Need to go over early_node_map to find out good range for node */
4103 for_each_active_range_index_in_nid_reverse(i, nid) {
4105 u64 ei_start, ei_last;
4106 u64 final_start, final_end;
4108 ei_last = early_node_map[i].end_pfn;
4109 ei_last <<= PAGE_SHIFT;
4110 ei_start = early_node_map[i].start_pfn;
4111 ei_start <<= PAGE_SHIFT;
4113 final_start = max(ei_start, goal);
4114 final_end = min(ei_last, limit);
4116 if (final_start >= final_end)
4119 addr = memblock_find_in_range(final_start, final_end, size, align);
4121 if (addr == MEMBLOCK_ERROR)
4127 return MEMBLOCK_ERROR;
4131 int __init add_from_early_node_map(struct range *range, int az,
4132 int nr_range, int nid)
4137 /* need to go over early_node_map to find out good range for node */
4138 for_each_active_range_index_in_nid(i, nid) {
4139 start = early_node_map[i].start_pfn;
4140 end = early_node_map[i].end_pfn;
4141 nr_range = add_range(range, az, nr_range, start, end);
4146 void __init work_with_active_regions(int nid, work_fn_t work_fn, void *data)
4151 for_each_active_range_index_in_nid(i, nid) {
4152 ret = work_fn(early_node_map[i].start_pfn,
4153 early_node_map[i].end_pfn, data);
4159 * sparse_memory_present_with_active_regions - Call memory_present for each active range
4160 * @nid: The node to call memory_present for. If MAX_NUMNODES, all nodes will be used.
4162 * If an architecture guarantees that all ranges registered with
4163 * add_active_ranges() contain no holes and may be freed, this
4164 * function may be used instead of calling memory_present() manually.
4166 void __init sparse_memory_present_with_active_regions(int nid)
4170 for_each_active_range_index_in_nid(i, nid)
4171 memory_present(early_node_map[i].nid,
4172 early_node_map[i].start_pfn,
4173 early_node_map[i].end_pfn);
4177 * get_pfn_range_for_nid - Return the start and end page frames for a node
4178 * @nid: The nid to return the range for. If MAX_NUMNODES, the min and max PFN are returned.
4179 * @start_pfn: Passed by reference. On return, it will have the node start_pfn.
4180 * @end_pfn: Passed by reference. On return, it will have the node end_pfn.
4182 * It returns the start and end page frame of a node based on information
4183 * provided by an arch calling add_active_range(). If called for a node
4184 * with no available memory, a warning is printed and the start and end
4187 void __meminit get_pfn_range_for_nid(unsigned int nid,
4188 unsigned long *start_pfn, unsigned long *end_pfn)
4194 for_each_active_range_index_in_nid(i, nid) {
4195 *start_pfn = min(*start_pfn, early_node_map[i].start_pfn);
4196 *end_pfn = max(*end_pfn, early_node_map[i].end_pfn);
4199 if (*start_pfn == -1UL)
4204 * This finds a zone that can be used for ZONE_MOVABLE pages. The
4205 * assumption is made that zones within a node are ordered in monotonic
4206 * increasing memory addresses so that the "highest" populated zone is used
4208 static void __init find_usable_zone_for_movable(void)
4211 for (zone_index = MAX_NR_ZONES - 1; zone_index >= 0; zone_index--) {
4212 if (zone_index == ZONE_MOVABLE)
4215 if (arch_zone_highest_possible_pfn[zone_index] >
4216 arch_zone_lowest_possible_pfn[zone_index])
4220 VM_BUG_ON(zone_index == -1);
4221 movable_zone = zone_index;
4225 * The zone ranges provided by the architecture do not include ZONE_MOVABLE
4226 * because it is sized independent of architecture. Unlike the other zones,
4227 * the starting point for ZONE_MOVABLE is not fixed. It may be different
4228 * in each node depending on the size of each node and how evenly kernelcore
4229 * is distributed. This helper function adjusts the zone ranges
4230 * provided by the architecture for a given node by using the end of the
4231 * highest usable zone for ZONE_MOVABLE. This preserves the assumption that
4232 * zones within a node are in order of monotonic increases memory addresses
4234 static void __meminit adjust_zone_range_for_zone_movable(int nid,
4235 unsigned long zone_type,
4236 unsigned long node_start_pfn,
4237 unsigned long node_end_pfn,
4238 unsigned long *zone_start_pfn,
4239 unsigned long *zone_end_pfn)
4241 /* Only adjust if ZONE_MOVABLE is on this node */
4242 if (zone_movable_pfn[nid]) {
4243 /* Size ZONE_MOVABLE */
4244 if (zone_type == ZONE_MOVABLE) {
4245 *zone_start_pfn = zone_movable_pfn[nid];
4246 *zone_end_pfn = min(node_end_pfn,
4247 arch_zone_highest_possible_pfn[movable_zone]);
4249 /* Adjust for ZONE_MOVABLE starting within this range */
4250 } else if (*zone_start_pfn < zone_movable_pfn[nid] &&
4251 *zone_end_pfn > zone_movable_pfn[nid]) {
4252 *zone_end_pfn = zone_movable_pfn[nid];
4254 /* Check if this whole range is within ZONE_MOVABLE */
4255 } else if (*zone_start_pfn >= zone_movable_pfn[nid])
4256 *zone_start_pfn = *zone_end_pfn;
4261 * Return the number of pages a zone spans in a node, including holes
4262 * present_pages = zone_spanned_pages_in_node() - zone_absent_pages_in_node()
4264 static unsigned long __meminit zone_spanned_pages_in_node(int nid,
4265 unsigned long zone_type,
4266 unsigned long *ignored)
4268 unsigned long node_start_pfn, node_end_pfn;
4269 unsigned long zone_start_pfn, zone_end_pfn;
4271 /* Get the start and end of the node and zone */
4272 get_pfn_range_for_nid(nid, &node_start_pfn, &node_end_pfn);
4273 zone_start_pfn = arch_zone_lowest_possible_pfn[zone_type];
4274 zone_end_pfn = arch_zone_highest_possible_pfn[zone_type];
4275 adjust_zone_range_for_zone_movable(nid, zone_type,
4276 node_start_pfn, node_end_pfn,
4277 &zone_start_pfn, &zone_end_pfn);
4279 /* Check that this node has pages within the zone's required range */
4280 if (zone_end_pfn < node_start_pfn || zone_start_pfn > node_end_pfn)
4283 /* Move the zone boundaries inside the node if necessary */
4284 zone_end_pfn = min(zone_end_pfn, node_end_pfn);
4285 zone_start_pfn = max(zone_start_pfn, node_start_pfn);
4287 /* Return the spanned pages */
4288 return zone_end_pfn - zone_start_pfn;
4292 * Return the number of holes in a range on a node. If nid is MAX_NUMNODES,
4293 * then all holes in the requested range will be accounted for.
4295 unsigned long __meminit __absent_pages_in_range(int nid,
4296 unsigned long range_start_pfn,
4297 unsigned long range_end_pfn)
4300 unsigned long prev_end_pfn = 0, hole_pages = 0;
4301 unsigned long start_pfn;
4303 /* Find the end_pfn of the first active range of pfns in the node */
4304 i = first_active_region_index_in_nid(nid);
4308 prev_end_pfn = min(early_node_map[i].start_pfn, range_end_pfn);
4310 /* Account for ranges before physical memory on this node */
4311 if (early_node_map[i].start_pfn > range_start_pfn)
4312 hole_pages = prev_end_pfn - range_start_pfn;
4314 /* Find all holes for the zone within the node */
4315 for (; i != -1; i = next_active_region_index_in_nid(i, nid)) {
4317 /* No need to continue if prev_end_pfn is outside the zone */
4318 if (prev_end_pfn >= range_end_pfn)
4321 /* Make sure the end of the zone is not within the hole */
4322 start_pfn = min(early_node_map[i].start_pfn, range_end_pfn);
4323 prev_end_pfn = max(prev_end_pfn, range_start_pfn);
4325 /* Update the hole size cound and move on */
4326 if (start_pfn > range_start_pfn) {
4327 BUG_ON(prev_end_pfn > start_pfn);
4328 hole_pages += start_pfn - prev_end_pfn;
4330 prev_end_pfn = early_node_map[i].end_pfn;
4333 /* Account for ranges past physical memory on this node */
4334 if (range_end_pfn > prev_end_pfn)
4335 hole_pages += range_end_pfn -
4336 max(range_start_pfn, prev_end_pfn);
4342 * absent_pages_in_range - Return number of page frames in holes within a range
4343 * @start_pfn: The start PFN to start searching for holes
4344 * @end_pfn: The end PFN to stop searching for holes
4346 * It returns the number of pages frames in memory holes within a range.
4348 unsigned long __init absent_pages_in_range(unsigned long start_pfn,
4349 unsigned long end_pfn)
4351 return __absent_pages_in_range(MAX_NUMNODES, start_pfn, end_pfn);
4354 /* Return the number of page frames in holes in a zone on a node */
4355 static unsigned long __meminit zone_absent_pages_in_node(int nid,
4356 unsigned long zone_type,
4357 unsigned long *ignored)
4359 unsigned long node_start_pfn, node_end_pfn;
4360 unsigned long zone_start_pfn, zone_end_pfn;
4362 get_pfn_range_for_nid(nid, &node_start_pfn, &node_end_pfn);
4363 zone_start_pfn = max(arch_zone_lowest_possible_pfn[zone_type],
4365 zone_end_pfn = min(arch_zone_highest_possible_pfn[zone_type],
4368 adjust_zone_range_for_zone_movable(nid, zone_type,
4369 node_start_pfn, node_end_pfn,
4370 &zone_start_pfn, &zone_end_pfn);
4371 return __absent_pages_in_range(nid, zone_start_pfn, zone_end_pfn);
4375 static inline unsigned long __meminit zone_spanned_pages_in_node(int nid,
4376 unsigned long zone_type,
4377 unsigned long *zones_size)
4379 return zones_size[zone_type];
4382 static inline unsigned long __meminit zone_absent_pages_in_node(int nid,
4383 unsigned long zone_type,
4384 unsigned long *zholes_size)
4389 return zholes_size[zone_type];
4394 static void __meminit calculate_node_totalpages(struct pglist_data *pgdat,
4395 unsigned long *zones_size, unsigned long *zholes_size)
4397 unsigned long realtotalpages, totalpages = 0;
4400 for (i = 0; i < MAX_NR_ZONES; i++)
4401 totalpages += zone_spanned_pages_in_node(pgdat->node_id, i,
4403 pgdat->node_spanned_pages = totalpages;
4405 realtotalpages = totalpages;
4406 for (i = 0; i < MAX_NR_ZONES; i++)
4408 zone_absent_pages_in_node(pgdat->node_id, i,
4410 pgdat->node_present_pages = realtotalpages;
4411 printk(KERN_DEBUG "On node %d totalpages: %lu\n", pgdat->node_id,
4415 #ifndef CONFIG_SPARSEMEM
4417 * Calculate the size of the zone->blockflags rounded to an unsigned long
4418 * Start by making sure zonesize is a multiple of pageblock_order by rounding
4419 * up. Then use 1 NR_PAGEBLOCK_BITS worth of bits per pageblock, finally
4420 * round what is now in bits to nearest long in bits, then return it in
4423 static unsigned long __init usemap_size(unsigned long zone_start_pfn, unsigned long zonesize)
4425 unsigned long usemapsize;
4427 zonesize += zone_start_pfn & (pageblock_nr_pages-1);
4428 usemapsize = roundup(zonesize, pageblock_nr_pages);
4429 usemapsize = usemapsize >> pageblock_order;
4430 usemapsize *= NR_PAGEBLOCK_BITS;
4431 usemapsize = roundup(usemapsize, 8 * sizeof(unsigned long));
4433 return usemapsize / 8;
4436 static void __init setup_usemap(struct pglist_data *pgdat,
4438 unsigned long zone_start_pfn,
4439 unsigned long zonesize)
4441 unsigned long usemapsize = usemap_size(zone_start_pfn, zonesize);
4442 zone->pageblock_flags = NULL;
4444 zone->pageblock_flags = alloc_bootmem_node_nopanic(pgdat,
4448 static inline void setup_usemap(struct pglist_data *pgdat, struct zone *zone,
4449 unsigned long zone_start_pfn, unsigned long zonesize) {}
4450 #endif /* CONFIG_SPARSEMEM */
4452 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
4454 /* Initialise the number of pages represented by NR_PAGEBLOCK_BITS */
4455 void __init set_pageblock_order(void)
4459 /* Check that pageblock_nr_pages has not already been setup */
4460 if (pageblock_order)
4463 if (HPAGE_SHIFT > PAGE_SHIFT)
4464 order = HUGETLB_PAGE_ORDER;
4466 order = MAX_ORDER - 1;
4469 * Assume the largest contiguous order of interest is a huge page.
4470 * This value may be variable depending on boot parameters on IA64 and
4473 pageblock_order = order;
4475 #else /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
4478 * When CONFIG_HUGETLB_PAGE_SIZE_VARIABLE is not set, set_pageblock_order()
4479 * is unused as pageblock_order is set at compile-time. See
4480 * include/linux/pageblock-flags.h for the values of pageblock_order based on
4483 void __init set_pageblock_order(void)
4487 #endif /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
4490 * Set up the zone data structures:
4491 * - mark all pages reserved
4492 * - mark all memory queues empty
4493 * - clear the memory bitmaps
4495 static void __paginginit free_area_init_core(struct pglist_data *pgdat,
4496 unsigned long *zones_size, unsigned long *zholes_size)
4499 int nid = pgdat->node_id;
4500 unsigned long zone_start_pfn = pgdat->node_start_pfn;
4503 pgdat_resize_init(pgdat);
4504 pgdat->nr_zones = 0;
4505 init_waitqueue_head(&pgdat->kswapd_wait);
4506 pgdat->kswapd_max_order = 0;
4507 pgdat_page_cgroup_init(pgdat);
4509 for (j = 0; j < MAX_NR_ZONES; j++) {
4510 struct zone *zone = pgdat->node_zones + j;
4511 unsigned long size, realsize, memmap_pages;
4514 size = zone_spanned_pages_in_node(nid, j, zones_size);
4515 realsize = size - zone_absent_pages_in_node(nid, j,
4519 * Adjust realsize so that it accounts for how much memory
4520 * is used by this zone for memmap. This affects the watermark
4521 * and per-cpu initialisations
4524 PAGE_ALIGN(size * sizeof(struct page)) >> PAGE_SHIFT;
4525 if (realsize >= memmap_pages) {
4526 realsize -= memmap_pages;
4529 " %s zone: %lu pages used for memmap\n",
4530 zone_names[j], memmap_pages);
4533 " %s zone: %lu pages exceeds realsize %lu\n",
4534 zone_names[j], memmap_pages, realsize);
4536 /* Account for reserved pages */
4537 if (j == 0 && realsize > dma_reserve) {
4538 realsize -= dma_reserve;
4539 printk(KERN_DEBUG " %s zone: %lu pages reserved\n",
4540 zone_names[0], dma_reserve);
4543 if (!is_highmem_idx(j))
4544 nr_kernel_pages += realsize;
4545 nr_all_pages += realsize;
4547 zone->spanned_pages = size;
4548 zone->present_pages = realsize;
4551 zone->min_unmapped_pages = (realsize*sysctl_min_unmapped_ratio)
4553 zone->min_slab_pages = (realsize * sysctl_min_slab_ratio) / 100;
4555 zone->name = zone_names[j];
4556 spin_lock_init(&zone->lock);
4557 spin_lock_init(&zone->lru_lock);
4558 zone_seqlock_init(zone);
4559 zone->zone_pgdat = pgdat;
4561 zone_pcp_init(zone);
4563 INIT_LIST_HEAD(&zone->lru[l].list);
4564 zone->reclaim_stat.recent_rotated[0] = 0;
4565 zone->reclaim_stat.recent_rotated[1] = 0;
4566 zone->reclaim_stat.recent_scanned[0] = 0;
4567 zone->reclaim_stat.recent_scanned[1] = 0;
4568 zap_zone_vm_stats(zone);
4573 set_pageblock_order();
4574 setup_usemap(pgdat, zone, zone_start_pfn, size);
4575 ret = init_currently_empty_zone(zone, zone_start_pfn,
4576 size, MEMMAP_EARLY);
4578 memmap_init(size, nid, j, zone_start_pfn);
4579 zone_start_pfn += size;
4583 static void __init_refok alloc_node_mem_map(struct pglist_data *pgdat)
4585 /* Skip empty nodes */
4586 if (!pgdat->node_spanned_pages)
4589 #ifdef CONFIG_FLAT_NODE_MEM_MAP
4590 /* ia64 gets its own node_mem_map, before this, without bootmem */
4591 if (!pgdat->node_mem_map) {
4592 unsigned long size, start, end;
4596 * The zone's endpoints aren't required to be MAX_ORDER
4597 * aligned but the node_mem_map endpoints must be in order
4598 * for the buddy allocator to function correctly.
4600 start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1);
4601 end = pgdat->node_start_pfn + pgdat->node_spanned_pages;
4602 end = ALIGN(end, MAX_ORDER_NR_PAGES);
4603 size = (end - start) * sizeof(struct page);
4604 map = alloc_remap(pgdat->node_id, size);
4606 map = alloc_bootmem_node_nopanic(pgdat, size);
4607 pgdat->node_mem_map = map + (pgdat->node_start_pfn - start);
4609 #ifndef CONFIG_NEED_MULTIPLE_NODES
4611 * With no DISCONTIG, the global mem_map is just set as node 0's
4613 if (pgdat == NODE_DATA(0)) {
4614 mem_map = NODE_DATA(0)->node_mem_map;
4615 #ifdef CONFIG_ARCH_POPULATES_NODE_MAP
4616 if (page_to_pfn(mem_map) != pgdat->node_start_pfn)
4617 mem_map -= (pgdat->node_start_pfn - ARCH_PFN_OFFSET);
4618 #endif /* CONFIG_ARCH_POPULATES_NODE_MAP */
4621 #endif /* CONFIG_FLAT_NODE_MEM_MAP */
4624 void __paginginit free_area_init_node(int nid, unsigned long *zones_size,
4625 unsigned long node_start_pfn, unsigned long *zholes_size)
4627 pg_data_t *pgdat = NODE_DATA(nid);
4629 pgdat->node_id = nid;
4630 pgdat->node_start_pfn = node_start_pfn;
4631 calculate_node_totalpages(pgdat, zones_size, zholes_size);
4633 alloc_node_mem_map(pgdat);
4634 #ifdef CONFIG_FLAT_NODE_MEM_MAP
4635 printk(KERN_DEBUG "free_area_init_node: node %d, pgdat %08lx, node_mem_map %08lx\n",
4636 nid, (unsigned long)pgdat,
4637 (unsigned long)pgdat->node_mem_map);
4640 free_area_init_core(pgdat, zones_size, zholes_size);
4643 #ifdef CONFIG_ARCH_POPULATES_NODE_MAP
4645 #if MAX_NUMNODES > 1
4647 * Figure out the number of possible node ids.
4649 static void __init setup_nr_node_ids(void)
4652 unsigned int highest = 0;
4654 for_each_node_mask(node, node_possible_map)
4656 nr_node_ids = highest + 1;
4659 static inline void setup_nr_node_ids(void)
4665 * add_active_range - Register a range of PFNs backed by physical memory
4666 * @nid: The node ID the range resides on
4667 * @start_pfn: The start PFN of the available physical memory
4668 * @end_pfn: The end PFN of the available physical memory
4670 * These ranges are stored in an early_node_map[] and later used by
4671 * free_area_init_nodes() to calculate zone sizes and holes. If the
4672 * range spans a memory hole, it is up to the architecture to ensure
4673 * the memory is not freed by the bootmem allocator. If possible
4674 * the range being registered will be merged with existing ranges.
4676 void __init add_active_range(unsigned int nid, unsigned long start_pfn,
4677 unsigned long end_pfn)
4681 mminit_dprintk(MMINIT_TRACE, "memory_register",
4682 "Entering add_active_range(%d, %#lx, %#lx) "
4683 "%d entries of %d used\n",
4684 nid, start_pfn, end_pfn,
4685 nr_nodemap_entries, MAX_ACTIVE_REGIONS);
4687 mminit_validate_memmodel_limits(&start_pfn, &end_pfn);
4689 /* Merge with existing active regions if possible */
4690 for (i = 0; i < nr_nodemap_entries; i++) {
4691 if (early_node_map[i].nid != nid)
4694 /* Skip if an existing region covers this new one */
4695 if (start_pfn >= early_node_map[i].start_pfn &&
4696 end_pfn <= early_node_map[i].end_pfn)
4699 /* Merge forward if suitable */
4700 if (start_pfn <= early_node_map[i].end_pfn &&
4701 end_pfn > early_node_map[i].end_pfn) {
4702 early_node_map[i].end_pfn = end_pfn;
4706 /* Merge backward if suitable */
4707 if (start_pfn < early_node_map[i].start_pfn &&
4708 end_pfn >= early_node_map[i].start_pfn) {
4709 early_node_map[i].start_pfn = start_pfn;
4714 /* Check that early_node_map is large enough */
4715 if (i >= MAX_ACTIVE_REGIONS) {
4716 printk(KERN_CRIT "More than %d memory regions, truncating\n",
4717 MAX_ACTIVE_REGIONS);
4721 early_node_map[i].nid = nid;
4722 early_node_map[i].start_pfn = start_pfn;
4723 early_node_map[i].end_pfn = end_pfn;
4724 nr_nodemap_entries = i + 1;
4728 * remove_active_range - Shrink an existing registered range of PFNs
4729 * @nid: The node id the range is on that should be shrunk
4730 * @start_pfn: The new PFN of the range
4731 * @end_pfn: The new PFN of the range
4733 * i386 with NUMA use alloc_remap() to store a node_mem_map on a local node.
4734 * The map is kept near the end physical page range that has already been
4735 * registered. This function allows an arch to shrink an existing registered
4738 void __init remove_active_range(unsigned int nid, unsigned long start_pfn,
4739 unsigned long end_pfn)
4744 printk(KERN_DEBUG "remove_active_range (%d, %lu, %lu)\n",
4745 nid, start_pfn, end_pfn);
4747 /* Find the old active region end and shrink */
4748 for_each_active_range_index_in_nid(i, nid) {
4749 if (early_node_map[i].start_pfn >= start_pfn &&
4750 early_node_map[i].end_pfn <= end_pfn) {
4752 early_node_map[i].start_pfn = 0;
4753 early_node_map[i].end_pfn = 0;
4757 if (early_node_map[i].start_pfn < start_pfn &&
4758 early_node_map[i].end_pfn > start_pfn) {
4759 unsigned long temp_end_pfn = early_node_map[i].end_pfn;
4760 early_node_map[i].end_pfn = start_pfn;
4761 if (temp_end_pfn > end_pfn)
4762 add_active_range(nid, end_pfn, temp_end_pfn);
4765 if (early_node_map[i].start_pfn >= start_pfn &&
4766 early_node_map[i].end_pfn > end_pfn &&
4767 early_node_map[i].start_pfn < end_pfn) {
4768 early_node_map[i].start_pfn = end_pfn;
4776 /* remove the blank ones */
4777 for (i = nr_nodemap_entries - 1; i > 0; i--) {
4778 if (early_node_map[i].nid != nid)
4780 if (early_node_map[i].end_pfn)
4782 /* we found it, get rid of it */
4783 for (j = i; j < nr_nodemap_entries - 1; j++)
4784 memcpy(&early_node_map[j], &early_node_map[j+1],
4785 sizeof(early_node_map[j]));
4786 j = nr_nodemap_entries - 1;
4787 memset(&early_node_map[j], 0, sizeof(early_node_map[j]));
4788 nr_nodemap_entries--;
4793 * remove_all_active_ranges - Remove all currently registered regions
4795 * During discovery, it may be found that a table like SRAT is invalid
4796 * and an alternative discovery method must be used. This function removes
4797 * all currently registered regions.
4799 void __init remove_all_active_ranges(void)
4801 memset(early_node_map, 0, sizeof(early_node_map));
4802 nr_nodemap_entries = 0;
4805 /* Compare two active node_active_regions */
4806 static int __init cmp_node_active_region(const void *a, const void *b)
4808 struct node_active_region *arange = (struct node_active_region *)a;
4809 struct node_active_region *brange = (struct node_active_region *)b;
4811 /* Done this way to avoid overflows */
4812 if (arange->start_pfn > brange->start_pfn)
4814 if (arange->start_pfn < brange->start_pfn)
4820 /* sort the node_map by start_pfn */
4821 void __init sort_node_map(void)
4823 sort(early_node_map, (size_t)nr_nodemap_entries,
4824 sizeof(struct node_active_region),
4825 cmp_node_active_region, NULL);
4829 * node_map_pfn_alignment - determine the maximum internode alignment
4831 * This function should be called after node map is populated and sorted.
4832 * It calculates the maximum power of two alignment which can distinguish
4835 * For example, if all nodes are 1GiB and aligned to 1GiB, the return value
4836 * would indicate 1GiB alignment with (1 << (30 - PAGE_SHIFT)). If the
4837 * nodes are shifted by 256MiB, 256MiB. Note that if only the last node is
4838 * shifted, 1GiB is enough and this function will indicate so.
4840 * This is used to test whether pfn -> nid mapping of the chosen memory
4841 * model has fine enough granularity to avoid incorrect mapping for the
4842 * populated node map.
4844 * Returns the determined alignment in pfn's. 0 if there is no alignment
4845 * requirement (single node).
4847 unsigned long __init node_map_pfn_alignment(void)
4849 unsigned long accl_mask = 0, last_end = 0;
4853 for_each_active_range_index_in_nid(i, MAX_NUMNODES) {
4854 int nid = early_node_map[i].nid;
4855 unsigned long start = early_node_map[i].start_pfn;
4856 unsigned long end = early_node_map[i].end_pfn;
4859 if (!start || last_nid < 0 || last_nid == nid) {
4866 * Start with a mask granular enough to pin-point to the
4867 * start pfn and tick off bits one-by-one until it becomes
4868 * too coarse to separate the current node from the last.
4870 mask = ~((1 << __ffs(start)) - 1);
4871 while (mask && last_end <= (start & (mask << 1)))
4874 /* accumulate all internode masks */
4878 /* convert mask to number of pages */
4879 return ~accl_mask + 1;
4882 /* Find the lowest pfn for a node */
4883 static unsigned long __init find_min_pfn_for_node(int nid)
4886 unsigned long min_pfn = ULONG_MAX;
4888 /* Assuming a sorted map, the first range found has the starting pfn */
4889 for_each_active_range_index_in_nid(i, nid)
4890 min_pfn = min(min_pfn, early_node_map[i].start_pfn);
4892 if (min_pfn == ULONG_MAX) {
4894 "Could not find start_pfn for node %d\n", nid);
4902 * find_min_pfn_with_active_regions - Find the minimum PFN registered
4904 * It returns the minimum PFN based on information provided via
4905 * add_active_range().
4907 unsigned long __init find_min_pfn_with_active_regions(void)
4909 return find_min_pfn_for_node(MAX_NUMNODES);
4913 * early_calculate_totalpages()
4914 * Sum pages in active regions for movable zone.
4915 * Populate N_HIGH_MEMORY for calculating usable_nodes.
4917 static unsigned long __init early_calculate_totalpages(void)
4920 unsigned long totalpages = 0;
4922 for (i = 0; i < nr_nodemap_entries; i++) {
4923 unsigned long pages = early_node_map[i].end_pfn -
4924 early_node_map[i].start_pfn;
4925 totalpages += pages;
4927 node_set_state(early_node_map[i].nid, N_HIGH_MEMORY);
4933 * Find the PFN the Movable zone begins in each node. Kernel memory
4934 * is spread evenly between nodes as long as the nodes have enough
4935 * memory. When they don't, some nodes will have more kernelcore than
4938 static void __init find_zone_movable_pfns_for_nodes(unsigned long *movable_pfn)
4941 unsigned long usable_startpfn;
4942 unsigned long kernelcore_node, kernelcore_remaining;
4943 /* save the state before borrow the nodemask */
4944 nodemask_t saved_node_state = node_states[N_HIGH_MEMORY];
4945 unsigned long totalpages = early_calculate_totalpages();
4946 int usable_nodes = nodes_weight(node_states[N_HIGH_MEMORY]);
4949 * If movablecore was specified, calculate what size of
4950 * kernelcore that corresponds so that memory usable for
4951 * any allocation type is evenly spread. If both kernelcore
4952 * and movablecore are specified, then the value of kernelcore
4953 * will be used for required_kernelcore if it's greater than
4954 * what movablecore would have allowed.
4956 if (required_movablecore) {
4957 unsigned long corepages;
4960 * Round-up so that ZONE_MOVABLE is at least as large as what
4961 * was requested by the user
4963 required_movablecore =
4964 roundup(required_movablecore, MAX_ORDER_NR_PAGES);
4965 corepages = totalpages - required_movablecore;
4967 required_kernelcore = max(required_kernelcore, corepages);
4970 /* If kernelcore was not specified, there is no ZONE_MOVABLE */
4971 if (!required_kernelcore)
4974 /* usable_startpfn is the lowest possible pfn ZONE_MOVABLE can be at */
4975 find_usable_zone_for_movable();
4976 usable_startpfn = arch_zone_lowest_possible_pfn[movable_zone];
4979 /* Spread kernelcore memory as evenly as possible throughout nodes */
4980 kernelcore_node = required_kernelcore / usable_nodes;
4981 for_each_node_state(nid, N_HIGH_MEMORY) {
4983 * Recalculate kernelcore_node if the division per node
4984 * now exceeds what is necessary to satisfy the requested
4985 * amount of memory for the kernel
4987 if (required_kernelcore < kernelcore_node)
4988 kernelcore_node = required_kernelcore / usable_nodes;
4991 * As the map is walked, we track how much memory is usable
4992 * by the kernel using kernelcore_remaining. When it is
4993 * 0, the rest of the node is usable by ZONE_MOVABLE
4995 kernelcore_remaining = kernelcore_node;
4997 /* Go through each range of PFNs within this node */
4998 for_each_active_range_index_in_nid(i, nid) {
4999 unsigned long start_pfn, end_pfn;
5000 unsigned long size_pages;
5002 start_pfn = max(early_node_map[i].start_pfn,
5003 zone_movable_pfn[nid]);
5004 end_pfn = early_node_map[i].end_pfn;
5005 if (start_pfn >= end_pfn)
5008 /* Account for what is only usable for kernelcore */
5009 if (start_pfn < usable_startpfn) {
5010 unsigned long kernel_pages;
5011 kernel_pages = min(end_pfn, usable_startpfn)
5014 kernelcore_remaining -= min(kernel_pages,
5015 kernelcore_remaining);
5016 required_kernelcore -= min(kernel_pages,
5017 required_kernelcore);
5019 /* Continue if range is now fully accounted */
5020 if (end_pfn <= usable_startpfn) {
5023 * Push zone_movable_pfn to the end so
5024 * that if we have to rebalance
5025 * kernelcore across nodes, we will
5026 * not double account here
5028 zone_movable_pfn[nid] = end_pfn;
5031 start_pfn = usable_startpfn;
5035 * The usable PFN range for ZONE_MOVABLE is from
5036 * start_pfn->end_pfn. Calculate size_pages as the
5037 * number of pages used as kernelcore
5039 size_pages = end_pfn - start_pfn;
5040 if (size_pages > kernelcore_remaining)
5041 size_pages = kernelcore_remaining;
5042 zone_movable_pfn[nid] = start_pfn + size_pages;
5045 * Some kernelcore has been met, update counts and
5046 * break if the kernelcore for this node has been
5049 required_kernelcore -= min(required_kernelcore,
5051 kernelcore_remaining -= size_pages;
5052 if (!kernelcore_remaining)
5058 * If there is still required_kernelcore, we do another pass with one
5059 * less node in the count. This will push zone_movable_pfn[nid] further
5060 * along on the nodes that still have memory until kernelcore is
5064 if (usable_nodes && required_kernelcore > usable_nodes)
5067 /* Align start of ZONE_MOVABLE on all nids to MAX_ORDER_NR_PAGES */
5068 for (nid = 0; nid < MAX_NUMNODES; nid++)
5069 zone_movable_pfn[nid] =
5070 roundup(zone_movable_pfn[nid], MAX_ORDER_NR_PAGES);
5073 /* restore the node_state */
5074 node_states[N_HIGH_MEMORY] = saved_node_state;
5077 /* Any regular memory on that node ? */
5078 static void check_for_regular_memory(pg_data_t *pgdat)
5080 #ifdef CONFIG_HIGHMEM
5081 enum zone_type zone_type;
5083 for (zone_type = 0; zone_type <= ZONE_NORMAL; zone_type++) {
5084 struct zone *zone = &pgdat->node_zones[zone_type];
5085 if (zone->present_pages)
5086 node_set_state(zone_to_nid(zone), N_NORMAL_MEMORY);
5092 * free_area_init_nodes - Initialise all pg_data_t and zone data
5093 * @max_zone_pfn: an array of max PFNs for each zone
5095 * This will call free_area_init_node() for each active node in the system.
5096 * Using the page ranges provided by add_active_range(), the size of each
5097 * zone in each node and their holes is calculated. If the maximum PFN
5098 * between two adjacent zones match, it is assumed that the zone is empty.
5099 * For example, if arch_max_dma_pfn == arch_max_dma32_pfn, it is assumed
5100 * that arch_max_dma32_pfn has no pages. It is also assumed that a zone
5101 * starts where the previous one ended. For example, ZONE_DMA32 starts
5102 * at arch_max_dma_pfn.
5104 void __init free_area_init_nodes(unsigned long *max_zone_pfn)
5109 /* Sort early_node_map as initialisation assumes it is sorted */
5112 /* Record where the zone boundaries are */
5113 memset(arch_zone_lowest_possible_pfn, 0,
5114 sizeof(arch_zone_lowest_possible_pfn));
5115 memset(arch_zone_highest_possible_pfn, 0,
5116 sizeof(arch_zone_highest_possible_pfn));
5117 arch_zone_lowest_possible_pfn[0] = find_min_pfn_with_active_regions();
5118 arch_zone_highest_possible_pfn[0] = max_zone_pfn[0];
5119 for (i = 1; i < MAX_NR_ZONES; i++) {
5120 if (i == ZONE_MOVABLE)
5122 arch_zone_lowest_possible_pfn[i] =
5123 arch_zone_highest_possible_pfn[i-1];
5124 arch_zone_highest_possible_pfn[i] =
5125 max(max_zone_pfn[i], arch_zone_lowest_possible_pfn[i]);
5127 arch_zone_lowest_possible_pfn[ZONE_MOVABLE] = 0;
5128 arch_zone_highest_possible_pfn[ZONE_MOVABLE] = 0;
5130 /* Find the PFNs that ZONE_MOVABLE begins at in each node */
5131 memset(zone_movable_pfn, 0, sizeof(zone_movable_pfn));
5132 find_zone_movable_pfns_for_nodes(zone_movable_pfn);
5134 /* Print out the zone ranges */
5135 printk("Zone PFN ranges:\n");
5136 for (i = 0; i < MAX_NR_ZONES; i++) {
5137 if (i == ZONE_MOVABLE)
5139 printk(" %-8s ", zone_names[i]);
5140 if (arch_zone_lowest_possible_pfn[i] ==
5141 arch_zone_highest_possible_pfn[i])
5144 printk("%0#10lx -> %0#10lx\n",
5145 arch_zone_lowest_possible_pfn[i],
5146 arch_zone_highest_possible_pfn[i]);
5149 /* Print out the PFNs ZONE_MOVABLE begins at in each node */
5150 printk("Movable zone start PFN for each node\n");
5151 for (i = 0; i < MAX_NUMNODES; i++) {
5152 if (zone_movable_pfn[i])
5153 printk(" Node %d: %lu\n", i, zone_movable_pfn[i]);
5156 /* Print out the early_node_map[] */
5157 printk("early_node_map[%d] active PFN ranges\n", nr_nodemap_entries);
5158 for (i = 0; i < nr_nodemap_entries; i++)
5159 printk(" %3d: %0#10lx -> %0#10lx\n", early_node_map[i].nid,
5160 early_node_map[i].start_pfn,
5161 early_node_map[i].end_pfn);
5163 /* Initialise every node */
5164 mminit_verify_pageflags_layout();
5165 setup_nr_node_ids();
5166 for_each_online_node(nid) {
5167 pg_data_t *pgdat = NODE_DATA(nid);
5168 free_area_init_node(nid, NULL,
5169 find_min_pfn_for_node(nid), NULL);
5171 /* Any memory on that node */
5172 if (pgdat->node_present_pages)
5173 node_set_state(nid, N_HIGH_MEMORY);
5174 check_for_regular_memory(pgdat);
5178 static int __init cmdline_parse_core(char *p, unsigned long *core)
5180 unsigned long long coremem;
5184 coremem = memparse(p, &p);
5185 *core = coremem >> PAGE_SHIFT;
5187 /* Paranoid check that UL is enough for the coremem value */
5188 WARN_ON((coremem >> PAGE_SHIFT) > ULONG_MAX);
5194 * kernelcore=size sets the amount of memory for use for allocations that
5195 * cannot be reclaimed or migrated.
5197 static int __init cmdline_parse_kernelcore(char *p)
5199 return cmdline_parse_core(p, &required_kernelcore);
5203 * movablecore=size sets the amount of memory for use for allocations that
5204 * can be reclaimed or migrated.
5206 static int __init cmdline_parse_movablecore(char *p)
5208 return cmdline_parse_core(p, &required_movablecore);
5211 early_param("kernelcore", cmdline_parse_kernelcore);
5212 early_param("movablecore", cmdline_parse_movablecore);
5214 #endif /* CONFIG_ARCH_POPULATES_NODE_MAP */
5217 * set_dma_reserve - set the specified number of pages reserved in the first zone
5218 * @new_dma_reserve: The number of pages to mark reserved
5220 * The per-cpu batchsize and zone watermarks are determined by present_pages.
5221 * In the DMA zone, a significant percentage may be consumed by kernel image
5222 * and other unfreeable allocations which can skew the watermarks badly. This
5223 * function may optionally be used to account for unfreeable pages in the
5224 * first zone (e.g., ZONE_DMA). The effect will be lower watermarks and
5225 * smaller per-cpu batchsize.
5227 void __init set_dma_reserve(unsigned long new_dma_reserve)
5229 dma_reserve = new_dma_reserve;
5232 void __init free_area_init(unsigned long *zones_size)
5234 free_area_init_node(0, zones_size,
5235 __pa(PAGE_OFFSET) >> PAGE_SHIFT, NULL);
5238 static int page_alloc_cpu_notify(struct notifier_block *self,
5239 unsigned long action, void *hcpu)
5241 int cpu = (unsigned long)hcpu;
5243 if (action == CPU_DEAD || action == CPU_DEAD_FROZEN) {
5247 * Spill the event counters of the dead processor
5248 * into the current processors event counters.
5249 * This artificially elevates the count of the current
5252 vm_events_fold_cpu(cpu);
5255 * Zero the differential counters of the dead processor
5256 * so that the vm statistics are consistent.
5258 * This is only okay since the processor is dead and cannot
5259 * race with what we are doing.
5261 refresh_cpu_vm_stats(cpu);
5266 void __init page_alloc_init(void)
5268 hotcpu_notifier(page_alloc_cpu_notify, 0);
5272 * calculate_totalreserve_pages - called when sysctl_lower_zone_reserve_ratio
5273 * or min_free_kbytes changes.
5275 static void calculate_totalreserve_pages(void)
5277 struct pglist_data *pgdat;
5278 unsigned long reserve_pages = 0;
5279 enum zone_type i, j;
5281 for_each_online_pgdat(pgdat) {
5282 for (i = 0; i < MAX_NR_ZONES; i++) {
5283 struct zone *zone = pgdat->node_zones + i;
5284 unsigned long max = 0;
5286 /* Find valid and maximum lowmem_reserve in the zone */
5287 for (j = i; j < MAX_NR_ZONES; j++) {
5288 if (zone->lowmem_reserve[j] > max)
5289 max = zone->lowmem_reserve[j];
5292 /* we treat the high watermark as reserved pages. */
5293 max += high_wmark_pages(zone);
5295 if (max > zone->present_pages)
5296 max = zone->present_pages;
5297 reserve_pages += max;
5299 * Lowmem reserves are not available to
5300 * GFP_HIGHUSER page cache allocations and
5301 * kswapd tries to balance zones to their high
5302 * watermark. As a result, neither should be
5303 * regarded as dirtyable memory, to prevent a
5304 * situation where reclaim has to clean pages
5305 * in order to balance the zones.
5307 zone->dirty_balance_reserve = max;
5310 dirty_balance_reserve = reserve_pages;
5311 totalreserve_pages = reserve_pages;
5315 * setup_per_zone_lowmem_reserve - called whenever
5316 * sysctl_lower_zone_reserve_ratio changes. Ensures that each zone
5317 * has a correct pages reserved value, so an adequate number of
5318 * pages are left in the zone after a successful __alloc_pages().
5320 static void setup_per_zone_lowmem_reserve(void)
5322 struct pglist_data *pgdat;
5323 enum zone_type j, idx;
5325 for_each_online_pgdat(pgdat) {
5326 for (j = 0; j < MAX_NR_ZONES; j++) {
5327 struct zone *zone = pgdat->node_zones + j;
5328 unsigned long present_pages = zone->present_pages;
5330 zone->lowmem_reserve[j] = 0;
5334 struct zone *lower_zone;
5338 if (sysctl_lowmem_reserve_ratio[idx] < 1)
5339 sysctl_lowmem_reserve_ratio[idx] = 1;
5341 lower_zone = pgdat->node_zones + idx;
5342 lower_zone->lowmem_reserve[j] = present_pages /
5343 sysctl_lowmem_reserve_ratio[idx];
5344 present_pages += lower_zone->present_pages;
5349 /* update totalreserve_pages */
5350 calculate_totalreserve_pages();
5353 static void __setup_per_zone_wmarks(void)
5355 unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
5356 unsigned long lowmem_pages = 0;
5358 unsigned long flags;
5360 /* Calculate total number of !ZONE_HIGHMEM pages */
5361 for_each_zone(zone) {
5362 if (!is_highmem(zone))
5363 lowmem_pages += zone->present_pages;
5366 for_each_zone(zone) {
5369 spin_lock_irqsave(&zone->lock, flags);
5370 tmp = (u64)pages_min * zone->present_pages;
5371 do_div(tmp, lowmem_pages);
5372 if (is_highmem(zone)) {
5374 * __GFP_HIGH and PF_MEMALLOC allocations usually don't
5375 * need highmem pages, so cap pages_min to a small
5378 * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN)
5379 * deltas controls asynch page reclaim, and so should
5380 * not be capped for highmem.
5384 min_pages = zone->present_pages / 1024;
5385 if (min_pages < SWAP_CLUSTER_MAX)
5386 min_pages = SWAP_CLUSTER_MAX;
5387 if (min_pages > 128)
5389 zone->watermark[WMARK_MIN] = min_pages;
5392 * If it's a lowmem zone, reserve a number of pages
5393 * proportionate to the zone's size.
5395 zone->watermark[WMARK_MIN] = tmp;
5398 zone->watermark[WMARK_LOW] = min_wmark_pages(zone) + (tmp >> 2);
5399 zone->watermark[WMARK_HIGH] = min_wmark_pages(zone) + (tmp >> 1);
5401 zone->watermark[WMARK_MIN] += cma_wmark_pages(zone);
5402 zone->watermark[WMARK_LOW] += cma_wmark_pages(zone);
5403 zone->watermark[WMARK_HIGH] += cma_wmark_pages(zone);
5405 setup_zone_migrate_reserve(zone);
5406 spin_unlock_irqrestore(&zone->lock, flags);
5409 /* update totalreserve_pages */
5410 calculate_totalreserve_pages();
5414 * setup_per_zone_wmarks - called when min_free_kbytes changes
5415 * or when memory is hot-{added|removed}
5417 * Ensures that the watermark[min,low,high] values for each zone are set
5418 * correctly with respect to min_free_kbytes.
5420 void setup_per_zone_wmarks(void)
5422 mutex_lock(&zonelists_mutex);
5423 __setup_per_zone_wmarks();
5424 mutex_unlock(&zonelists_mutex);
5428 * The inactive anon list should be small enough that the VM never has to
5429 * do too much work, but large enough that each inactive page has a chance
5430 * to be referenced again before it is swapped out.
5432 * The inactive_anon ratio is the target ratio of ACTIVE_ANON to
5433 * INACTIVE_ANON pages on this zone's LRU, maintained by the
5434 * pageout code. A zone->inactive_ratio of 3 means 3:1 or 25% of
5435 * the anonymous pages are kept on the inactive list.
5438 * memory ratio inactive anon
5439 * -------------------------------------
5448 static void __meminit calculate_zone_inactive_ratio(struct zone *zone)
5450 unsigned int gb, ratio;
5452 /* Zone size in gigabytes */
5453 gb = zone->present_pages >> (30 - PAGE_SHIFT);
5455 ratio = int_sqrt(10 * gb);
5459 zone->inactive_ratio = ratio;
5462 static void __meminit setup_per_zone_inactive_ratio(void)
5467 calculate_zone_inactive_ratio(zone);
5471 * Initialise min_free_kbytes.
5473 * For small machines we want it small (128k min). For large machines
5474 * we want it large (64MB max). But it is not linear, because network
5475 * bandwidth does not increase linearly with machine size. We use
5477 * min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
5478 * min_free_kbytes = sqrt(lowmem_kbytes * 16)
5494 int __meminit init_per_zone_wmark_min(void)
5496 unsigned long lowmem_kbytes;
5498 lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
5500 min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
5501 if (min_free_kbytes < 128)
5502 min_free_kbytes = 128;
5503 if (min_free_kbytes > 65536)
5504 min_free_kbytes = 65536;
5505 setup_per_zone_wmarks();
5506 refresh_zone_stat_thresholds();
5507 setup_per_zone_lowmem_reserve();
5508 setup_per_zone_inactive_ratio();
5511 module_init(init_per_zone_wmark_min)
5514 * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
5515 * that we can call two helper functions whenever min_free_kbytes
5518 int min_free_kbytes_sysctl_handler(ctl_table *table, int write,
5519 void __user *buffer, size_t *length, loff_t *ppos)
5521 proc_dointvec(table, write, buffer, length, ppos);
5523 setup_per_zone_wmarks();
5528 int sysctl_min_unmapped_ratio_sysctl_handler(ctl_table *table, int write,
5529 void __user *buffer, size_t *length, loff_t *ppos)
5534 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
5539 zone->min_unmapped_pages = (zone->present_pages *
5540 sysctl_min_unmapped_ratio) / 100;
5544 int sysctl_min_slab_ratio_sysctl_handler(ctl_table *table, int write,
5545 void __user *buffer, size_t *length, loff_t *ppos)
5550 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
5555 zone->min_slab_pages = (zone->present_pages *
5556 sysctl_min_slab_ratio) / 100;
5562 * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
5563 * proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
5564 * whenever sysctl_lowmem_reserve_ratio changes.
5566 * The reserve ratio obviously has absolutely no relation with the
5567 * minimum watermarks. The lowmem reserve ratio can only make sense
5568 * if in function of the boot time zone sizes.
5570 int lowmem_reserve_ratio_sysctl_handler(ctl_table *table, int write,
5571 void __user *buffer, size_t *length, loff_t *ppos)
5573 proc_dointvec_minmax(table, write, buffer, length, ppos);
5574 setup_per_zone_lowmem_reserve();
5579 * percpu_pagelist_fraction - changes the pcp->high for each zone on each
5580 * cpu. It is the fraction of total pages in each zone that a hot per cpu pagelist
5581 * can have before it gets flushed back to buddy allocator.
5584 int percpu_pagelist_fraction_sysctl_handler(ctl_table *table, int write,
5585 void __user *buffer, size_t *length, loff_t *ppos)
5591 ret = proc_dointvec_minmax(table, write, buffer, length, ppos);
5592 if (!write || (ret == -EINVAL))
5594 for_each_populated_zone(zone) {
5595 for_each_possible_cpu(cpu) {
5597 high = zone->present_pages / percpu_pagelist_fraction;
5598 setup_pagelist_highmark(
5599 per_cpu_ptr(zone->pageset, cpu), high);
5605 int hashdist = HASHDIST_DEFAULT;
5608 static int __init set_hashdist(char *str)
5612 hashdist = simple_strtoul(str, &str, 0);
5615 __setup("hashdist=", set_hashdist);
5619 * allocate a large system hash table from bootmem
5620 * - it is assumed that the hash table must contain an exact power-of-2
5621 * quantity of entries
5622 * - limit is the number of hash buckets, not the total allocation size
5624 void *__init alloc_large_system_hash(const char *tablename,
5625 unsigned long bucketsize,
5626 unsigned long numentries,
5629 unsigned int *_hash_shift,
5630 unsigned int *_hash_mask,
5631 unsigned long limit)
5633 unsigned long long max = limit;
5634 unsigned long log2qty, size;
5637 /* allow the kernel cmdline to have a say */
5639 /* round applicable memory size up to nearest megabyte */
5640 numentries = nr_kernel_pages;
5641 numentries += (1UL << (20 - PAGE_SHIFT)) - 1;
5642 numentries >>= 20 - PAGE_SHIFT;
5643 numentries <<= 20 - PAGE_SHIFT;
5645 /* limit to 1 bucket per 2^scale bytes of low memory */
5646 if (scale > PAGE_SHIFT)
5647 numentries >>= (scale - PAGE_SHIFT);
5649 numentries <<= (PAGE_SHIFT - scale);
5651 /* Make sure we've got at least a 0-order allocation.. */
5652 if (unlikely(flags & HASH_SMALL)) {
5653 /* Makes no sense without HASH_EARLY */
5654 WARN_ON(!(flags & HASH_EARLY));
5655 if (!(numentries >> *_hash_shift)) {
5656 numentries = 1UL << *_hash_shift;
5657 BUG_ON(!numentries);
5659 } else if (unlikely((numentries * bucketsize) < PAGE_SIZE))
5660 numentries = PAGE_SIZE / bucketsize;
5662 numentries = roundup_pow_of_two(numentries);
5664 /* limit allocation size to 1/16 total memory by default */
5666 max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
5667 do_div(max, bucketsize);
5670 if (numentries > max)
5673 log2qty = ilog2(numentries);
5676 size = bucketsize << log2qty;
5677 if (flags & HASH_EARLY)
5678 table = alloc_bootmem_nopanic(size);
5680 table = __vmalloc(size, GFP_ATOMIC, PAGE_KERNEL);
5683 * If bucketsize is not a power-of-two, we may free
5684 * some pages at the end of hash table which
5685 * alloc_pages_exact() automatically does
5687 if (get_order(size) < MAX_ORDER) {
5688 table = alloc_pages_exact(size, GFP_ATOMIC);
5689 kmemleak_alloc(table, size, 1, GFP_ATOMIC);
5692 } while (!table && size > PAGE_SIZE && --log2qty);
5695 panic("Failed to allocate %s hash table\n", tablename);
5697 printk(KERN_INFO "%s hash table entries: %ld (order: %d, %lu bytes)\n",
5700 ilog2(size) - PAGE_SHIFT,
5704 *_hash_shift = log2qty;
5706 *_hash_mask = (1 << log2qty) - 1;
5711 /* Return a pointer to the bitmap storing bits affecting a block of pages */
5712 static inline unsigned long *get_pageblock_bitmap(struct zone *zone,
5715 #ifdef CONFIG_SPARSEMEM
5716 return __pfn_to_section(pfn)->pageblock_flags;
5718 return zone->pageblock_flags;
5719 #endif /* CONFIG_SPARSEMEM */
5722 static inline int pfn_to_bitidx(struct zone *zone, unsigned long pfn)
5724 #ifdef CONFIG_SPARSEMEM
5725 pfn &= (PAGES_PER_SECTION-1);
5726 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
5728 pfn = pfn - round_down(zone->zone_start_pfn, pageblock_nr_pages);
5729 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
5730 #endif /* CONFIG_SPARSEMEM */
5734 * get_pageblock_flags_group - Return the requested group of flags for the pageblock_nr_pages block of pages
5735 * @page: The page within the block of interest
5736 * @start_bitidx: The first bit of interest to retrieve
5737 * @end_bitidx: The last bit of interest
5738 * returns pageblock_bits flags
5740 unsigned long get_pageblock_flags_group(struct page *page,
5741 int start_bitidx, int end_bitidx)
5744 unsigned long *bitmap;
5745 unsigned long pfn, bitidx;
5746 unsigned long flags = 0;
5747 unsigned long value = 1;
5749 zone = page_zone(page);
5750 pfn = page_to_pfn(page);
5751 bitmap = get_pageblock_bitmap(zone, pfn);
5752 bitidx = pfn_to_bitidx(zone, pfn);
5754 for (; start_bitidx <= end_bitidx; start_bitidx++, value <<= 1)
5755 if (test_bit(bitidx + start_bitidx, bitmap))
5762 * set_pageblock_flags_group - Set the requested group of flags for a pageblock_nr_pages block of pages
5763 * @page: The page within the block of interest
5764 * @start_bitidx: The first bit of interest
5765 * @end_bitidx: The last bit of interest
5766 * @flags: The flags to set
5768 void set_pageblock_flags_group(struct page *page, unsigned long flags,
5769 int start_bitidx, int end_bitidx)
5772 unsigned long *bitmap;
5773 unsigned long pfn, bitidx;
5774 unsigned long value = 1;
5776 zone = page_zone(page);
5777 pfn = page_to_pfn(page);
5778 bitmap = get_pageblock_bitmap(zone, pfn);
5779 bitidx = pfn_to_bitidx(zone, pfn);
5780 VM_BUG_ON(pfn < zone->zone_start_pfn);
5781 VM_BUG_ON(pfn >= zone->zone_start_pfn + zone->spanned_pages);
5783 for (; start_bitidx <= end_bitidx; start_bitidx++, value <<= 1)
5785 __set_bit(bitidx + start_bitidx, bitmap);
5787 __clear_bit(bitidx + start_bitidx, bitmap);
5791 * This is designed as sub function...plz see page_isolation.c also.
5792 * set/clear page block's type to be ISOLATE.
5793 * page allocater never alloc memory from ISOLATE block.
5797 __count_immobile_pages(struct zone *zone, struct page *page, int count)
5799 unsigned long pfn, iter, found;
5803 * For avoiding noise data, lru_add_drain_all() should be called
5804 * If ZONE_MOVABLE, the zone never contains immobile pages
5806 if (zone_idx(zone) == ZONE_MOVABLE)
5808 mt = get_pageblock_migratetype(page);
5809 if (mt == MIGRATE_MOVABLE || is_migrate_cma(mt))
5812 pfn = page_to_pfn(page);
5813 for (found = 0, iter = 0; iter < pageblock_nr_pages; iter++) {
5814 unsigned long check = pfn + iter;
5816 if (!pfn_valid_within(check))
5819 page = pfn_to_page(check);
5820 if (!page_count(page)) {
5821 if (PageBuddy(page))
5822 iter += (1 << page_order(page)) - 1;
5828 * If there are RECLAIMABLE pages, we need to check it.
5829 * But now, memory offline itself doesn't call shrink_slab()
5830 * and it still to be fixed.
5833 * If the page is not RAM, page_count()should be 0.
5834 * we don't need more check. This is an _used_ not-movable page.
5836 * The problematic thing here is PG_reserved pages. PG_reserved
5837 * is set to both of a memory hole page and a _used_ kernel
5846 bool is_pageblock_removable_nolock(struct page *page)
5848 struct zone *zone = page_zone(page);
5849 unsigned long pfn = page_to_pfn(page);
5852 * We have to be careful here because we are iterating over memory
5853 * sections which are not zone aware so we might end up outside of
5854 * the zone but still within the section.
5856 if (!zone || zone->zone_start_pfn > pfn ||
5857 zone->zone_start_pfn + zone->spanned_pages <= pfn)
5860 return __count_immobile_pages(zone, page, 0);
5863 int set_migratetype_isolate(struct page *page)
5866 unsigned long flags, pfn;
5867 struct memory_isolate_notify arg;
5871 zone = page_zone(page);
5873 spin_lock_irqsave(&zone->lock, flags);
5875 pfn = page_to_pfn(page);
5876 arg.start_pfn = pfn;
5877 arg.nr_pages = pageblock_nr_pages;
5878 arg.pages_found = 0;
5881 * It may be possible to isolate a pageblock even if the
5882 * migratetype is not MIGRATE_MOVABLE. The memory isolation
5883 * notifier chain is used by balloon drivers to return the
5884 * number of pages in a range that are held by the balloon
5885 * driver to shrink memory. If all the pages are accounted for
5886 * by balloons, are free, or on the LRU, isolation can continue.
5887 * Later, for example, when memory hotplug notifier runs, these
5888 * pages reported as "can be isolated" should be isolated(freed)
5889 * by the balloon driver through the memory notifier chain.
5891 notifier_ret = memory_isolate_notify(MEM_ISOLATE_COUNT, &arg);
5892 notifier_ret = notifier_to_errno(notifier_ret);
5896 * FIXME: Now, memory hotplug doesn't call shrink_slab() by itself.
5897 * We just check MOVABLE pages.
5899 if (__count_immobile_pages(zone, page, arg.pages_found))
5903 * immobile means "not-on-lru" paes. If immobile is larger than
5904 * removable-by-driver pages reported by notifier, we'll fail.
5909 set_pageblock_migratetype(page, MIGRATE_ISOLATE);
5910 move_freepages_block(zone, page, MIGRATE_ISOLATE);
5913 spin_unlock_irqrestore(&zone->lock, flags);
5919 void unset_migratetype_isolate(struct page *page, unsigned migratetype)
5922 unsigned long flags;
5923 zone = page_zone(page);
5924 spin_lock_irqsave(&zone->lock, flags);
5925 if (get_pageblock_migratetype(page) != MIGRATE_ISOLATE)
5927 set_pageblock_migratetype(page, migratetype);
5928 move_freepages_block(zone, page, migratetype);
5930 spin_unlock_irqrestore(&zone->lock, flags);
5935 static unsigned long pfn_max_align_down(unsigned long pfn)
5937 return pfn & ~(max_t(unsigned long, MAX_ORDER_NR_PAGES,
5938 pageblock_nr_pages) - 1);
5941 static unsigned long pfn_max_align_up(unsigned long pfn)
5943 return ALIGN(pfn, max_t(unsigned long, MAX_ORDER_NR_PAGES,
5944 pageblock_nr_pages));
5947 static struct page *
5948 __alloc_contig_migrate_alloc(struct page *page, unsigned long private,
5951 gfp_t gfp_mask = GFP_USER | __GFP_MOVABLE;
5953 if (PageHighMem(page))
5954 gfp_mask |= __GFP_HIGHMEM;
5956 return alloc_page(gfp_mask);
5959 /* [start, end) must belong to a single zone. */
5960 static int __alloc_contig_migrate_range(unsigned long start, unsigned long end)
5962 /* This function is based on compact_zone() from compaction.c. */
5964 unsigned long pfn = start;
5965 unsigned int tries = 0;
5968 struct compact_control cc = {
5969 .nr_migratepages = 0,
5971 .zone = page_zone(pfn_to_page(start)),
5974 INIT_LIST_HEAD(&cc.migratepages);
5976 migrate_prep_local();
5978 while (pfn < end || !list_empty(&cc.migratepages)) {
5979 if (fatal_signal_pending(current)) {
5984 if (list_empty(&cc.migratepages)) {
5985 cc.nr_migratepages = 0;
5986 pfn = isolate_migratepages_range(cc.zone, &cc,
5993 } else if (++tries == 5) {
5994 ret = ret < 0 ? ret : -EBUSY;
5998 ret = migrate_pages(&cc.migratepages,
5999 __alloc_contig_migrate_alloc,
6000 0, false, MIGRATE_SYNC);
6003 putback_lru_pages(&cc.migratepages);
6004 return ret > 0 ? 0 : ret;
6008 * Update zone's cma pages counter used for watermark level calculation.
6010 static inline void __update_cma_watermarks(struct zone *zone, int count)
6012 unsigned long flags;
6013 spin_lock_irqsave(&zone->lock, flags);
6014 zone->min_cma_pages += count;
6015 spin_unlock_irqrestore(&zone->lock, flags);
6016 setup_per_zone_wmarks();
6020 * Trigger memory pressure bump to reclaim some pages in order to be able to
6021 * allocate 'count' pages in single page units. Does similar work as
6022 *__alloc_pages_slowpath() function.
6024 static int __reclaim_pages(struct zone *zone, gfp_t gfp_mask, int count)
6026 enum zone_type high_zoneidx = gfp_zone(gfp_mask);
6027 struct zonelist *zonelist = node_zonelist(0, gfp_mask);
6028 int did_some_progress = 0;
6032 * Increase level of watermarks to force kswapd do his job
6033 * to stabilise at new watermark level.
6035 __update_cma_watermarks(zone, count);
6037 /* Obey watermarks as if the page was being allocated */
6038 while (!zone_watermark_ok(zone, 0, low_wmark_pages(zone), 0, 0)) {
6039 wake_all_kswapd(order, zonelist, high_zoneidx, zone_idx(zone));
6041 did_some_progress = __perform_reclaim(gfp_mask, order, zonelist,
6043 if (!did_some_progress) {
6044 /* Exhausted what can be done so it's blamo time */
6045 out_of_memory(zonelist, gfp_mask, order, NULL);
6049 /* Restore original watermark levels. */
6050 __update_cma_watermarks(zone, -count);
6056 * alloc_contig_range() -- tries to allocate given range of pages
6057 * @start: start PFN to allocate
6058 * @end: one-past-the-last PFN to allocate
6059 * @migratetype: migratetype of the underlaying pageblocks (either
6060 * #MIGRATE_MOVABLE or #MIGRATE_CMA). All pageblocks
6061 * in range must have the same migratetype and it must
6062 * be either of the two.
6064 * The PFN range does not have to be pageblock or MAX_ORDER_NR_PAGES
6065 * aligned, however it's the caller's responsibility to guarantee that
6066 * we are the only thread that changes migrate type of pageblocks the
6069 * The PFN range must belong to a single zone.
6071 * Returns zero on success or negative error code. On success all
6072 * pages which PFN is in [start, end) are allocated for the caller and
6073 * need to be freed with free_contig_range().
6075 int alloc_contig_range(unsigned long start, unsigned long end,
6076 unsigned migratetype)
6078 struct zone *zone = page_zone(pfn_to_page(start));
6079 unsigned long outer_start, outer_end;
6083 * What we do here is we mark all pageblocks in range as
6084 * MIGRATE_ISOLATE. Because pageblock and max order pages may
6085 * have different sizes, and due to the way page allocator
6086 * work, we align the range to biggest of the two pages so
6087 * that page allocator won't try to merge buddies from
6088 * different pageblocks and change MIGRATE_ISOLATE to some
6089 * other migration type.
6091 * Once the pageblocks are marked as MIGRATE_ISOLATE, we
6092 * migrate the pages from an unaligned range (ie. pages that
6093 * we are interested in). This will put all the pages in
6094 * range back to page allocator as MIGRATE_ISOLATE.
6096 * When this is done, we take the pages in range from page
6097 * allocator removing them from the buddy system. This way
6098 * page allocator will never consider using them.
6100 * This lets us mark the pageblocks back as
6101 * MIGRATE_CMA/MIGRATE_MOVABLE so that free pages in the
6102 * aligned range but not in the unaligned, original range are
6103 * put back to page allocator so that buddy can use them.
6106 ret = start_isolate_page_range(pfn_max_align_down(start),
6107 pfn_max_align_up(end), migratetype);
6111 ret = __alloc_contig_migrate_range(start, end);
6116 * Pages from [start, end) are within a MAX_ORDER_NR_PAGES
6117 * aligned blocks that are marked as MIGRATE_ISOLATE. What's
6118 * more, all pages in [start, end) are free in page allocator.
6119 * What we are going to do is to allocate all pages from
6120 * [start, end) (that is remove them from page allocator).
6122 * The only problem is that pages at the beginning and at the
6123 * end of interesting range may be not aligned with pages that
6124 * page allocator holds, ie. they can be part of higher order
6125 * pages. Because of this, we reserve the bigger range and
6126 * once this is done free the pages we are not interested in.
6128 * We don't have to hold zone->lock here because the pages are
6129 * isolated thus they won't get removed from buddy.
6132 lru_add_drain_all();
6136 outer_start = start;
6137 while (!PageBuddy(pfn_to_page(outer_start))) {
6138 if (++order >= MAX_ORDER) {
6142 outer_start &= ~0UL << order;
6145 /* Make sure the range is really isolated. */
6146 if (test_pages_isolated(outer_start, end)) {
6147 pr_warn("alloc_contig_range test_pages_isolated(%lx, %lx) failed\n",
6154 * Reclaim enough pages to make sure that contiguous allocation
6155 * will not starve the system.
6157 __reclaim_pages(zone, GFP_HIGHUSER_MOVABLE, end-start);
6159 /* Grab isolated pages from freelists. */
6160 outer_end = isolate_freepages_range(outer_start, end);
6166 /* Free head and tail (if any) */
6167 if (start != outer_start)
6168 free_contig_range(outer_start, start - outer_start);
6169 if (end != outer_end)
6170 free_contig_range(end, outer_end - end);
6173 undo_isolate_page_range(pfn_max_align_down(start),
6174 pfn_max_align_up(end), migratetype);
6178 void free_contig_range(unsigned long pfn, unsigned nr_pages)
6180 for (; nr_pages--; ++pfn)
6181 __free_page(pfn_to_page(pfn));
6185 #ifdef CONFIG_MEMORY_HOTREMOVE
6187 * All pages in the range must be isolated before calling this.
6190 __offline_isolated_pages(unsigned long start_pfn, unsigned long end_pfn)
6196 unsigned long flags;
6197 /* find the first valid pfn */
6198 for (pfn = start_pfn; pfn < end_pfn; pfn++)
6203 zone = page_zone(pfn_to_page(pfn));
6204 spin_lock_irqsave(&zone->lock, flags);
6206 while (pfn < end_pfn) {
6207 if (!pfn_valid(pfn)) {
6211 page = pfn_to_page(pfn);
6212 BUG_ON(page_count(page));
6213 BUG_ON(!PageBuddy(page));
6214 order = page_order(page);
6215 #ifdef CONFIG_DEBUG_VM
6216 printk(KERN_INFO "remove from free list %lx %d %lx\n",
6217 pfn, 1 << order, end_pfn);
6219 list_del(&page->lru);
6220 rmv_page_order(page);
6221 zone->free_area[order].nr_free--;
6222 __mod_zone_page_state(zone, NR_FREE_PAGES,
6224 #ifdef CONFIG_HIGHMEM
6225 if (PageHighMem(page))
6226 totalhigh_pages -= 1 << order;
6228 for (i = 0; i < (1 << order); i++)
6229 SetPageReserved((page+i));
6230 pfn += (1 << order);
6232 spin_unlock_irqrestore(&zone->lock, flags);
6236 #ifdef CONFIG_MEMORY_FAILURE
6237 bool is_free_buddy_page(struct page *page)
6239 struct zone *zone = page_zone(page);
6240 unsigned long pfn = page_to_pfn(page);
6241 unsigned long flags;
6244 spin_lock_irqsave(&zone->lock, flags);
6245 for (order = 0; order < MAX_ORDER; order++) {
6246 struct page *page_head = page - (pfn & ((1 << order) - 1));
6248 if (PageBuddy(page_head) && page_order(page_head) >= order)
6251 spin_unlock_irqrestore(&zone->lock, flags);
6253 return order < MAX_ORDER;
6257 static struct trace_print_flags pageflag_names[] = {
6258 {1UL << PG_locked, "locked" },
6259 {1UL << PG_error, "error" },
6260 {1UL << PG_referenced, "referenced" },
6261 {1UL << PG_uptodate, "uptodate" },
6262 {1UL << PG_dirty, "dirty" },
6263 {1UL << PG_lru, "lru" },
6264 {1UL << PG_active, "active" },
6265 {1UL << PG_slab, "slab" },
6266 {1UL << PG_owner_priv_1, "owner_priv_1" },
6267 {1UL << PG_arch_1, "arch_1" },
6268 {1UL << PG_reserved, "reserved" },
6269 {1UL << PG_private, "private" },
6270 {1UL << PG_private_2, "private_2" },
6271 {1UL << PG_writeback, "writeback" },
6272 #ifdef CONFIG_PAGEFLAGS_EXTENDED
6273 {1UL << PG_head, "head" },
6274 {1UL << PG_tail, "tail" },
6276 {1UL << PG_compound, "compound" },
6278 {1UL << PG_swapcache, "swapcache" },
6279 {1UL << PG_mappedtodisk, "mappedtodisk" },
6280 {1UL << PG_reclaim, "reclaim" },
6281 {1UL << PG_swapbacked, "swapbacked" },
6282 {1UL << PG_unevictable, "unevictable" },
6284 {1UL << PG_mlocked, "mlocked" },
6286 #ifdef CONFIG_ARCH_USES_PG_UNCACHED
6287 {1UL << PG_uncached, "uncached" },
6289 #ifdef CONFIG_MEMORY_FAILURE
6290 {1UL << PG_hwpoison, "hwpoison" },
6295 static void dump_page_flags(unsigned long flags)
6297 const char *delim = "";
6301 printk(KERN_ALERT "page flags: %#lx(", flags);
6303 /* remove zone id */
6304 flags &= (1UL << NR_PAGEFLAGS) - 1;
6306 for (i = 0; pageflag_names[i].name && flags; i++) {
6308 mask = pageflag_names[i].mask;
6309 if ((flags & mask) != mask)
6313 printk("%s%s", delim, pageflag_names[i].name);
6317 /* check for left over flags */
6319 printk("%s%#lx", delim, flags);
6324 void dump_page(struct page *page)
6327 "page:%p count:%d mapcount:%d mapping:%p index:%#lx\n",
6328 page, atomic_read(&page->_count), page_mapcount(page),
6329 page->mapping, page->index);
6330 dump_page_flags(page->flags);
6331 mem_cgroup_print_bad_page(page);