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/kasan.h>
29 #include <linux/module.h>
30 #include <linux/suspend.h>
31 #include <linux/pagevec.h>
32 #include <linux/blkdev.h>
33 #include <linux/slab.h>
34 #include <linux/ratelimit.h>
35 #include <linux/oom.h>
36 #include <linux/notifier.h>
37 #include <linux/topology.h>
38 #include <linux/sysctl.h>
39 #include <linux/cpu.h>
40 #include <linux/cpuset.h>
41 #include <linux/memory_hotplug.h>
42 #include <linux/nodemask.h>
43 #include <linux/vmalloc.h>
44 #include <linux/vmstat.h>
45 #include <linux/mempolicy.h>
46 #include <linux/stop_machine.h>
47 #include <linux/sort.h>
48 #include <linux/pfn.h>
49 #include <linux/backing-dev.h>
50 #include <linux/fault-inject.h>
51 #include <linux/page-isolation.h>
52 #include <linux/page_ext.h>
53 #include <linux/debugobjects.h>
54 #include <linux/kmemleak.h>
55 #include <linux/compaction.h>
56 #include <trace/events/kmem.h>
57 #include <linux/prefetch.h>
58 #include <linux/mm_inline.h>
59 #include <linux/migrate.h>
60 #include <linux/page_ext.h>
61 #include <linux/hugetlb.h>
62 #include <linux/sched/rt.h>
63 #include <linux/page_owner.h>
64 #include <linux/kthread.h>
66 #include <asm/sections.h>
67 #include <asm/tlbflush.h>
68 #include <asm/div64.h>
71 /* prevent >1 _updater_ of zone percpu pageset ->high and ->batch fields */
72 static DEFINE_MUTEX(pcp_batch_high_lock);
73 #define MIN_PERCPU_PAGELIST_FRACTION (8)
75 #ifdef CONFIG_USE_PERCPU_NUMA_NODE_ID
76 DEFINE_PER_CPU(int, numa_node);
77 EXPORT_PER_CPU_SYMBOL(numa_node);
80 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
82 * N.B., Do NOT reference the '_numa_mem_' per cpu variable directly.
83 * It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined.
84 * Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem()
85 * defined in <linux/topology.h>.
87 DEFINE_PER_CPU(int, _numa_mem_); /* Kernel "local memory" node */
88 EXPORT_PER_CPU_SYMBOL(_numa_mem_);
89 int _node_numa_mem_[MAX_NUMNODES];
93 * Array of node states.
95 nodemask_t node_states[NR_NODE_STATES] __read_mostly = {
96 [N_POSSIBLE] = NODE_MASK_ALL,
97 [N_ONLINE] = { { [0] = 1UL } },
99 [N_NORMAL_MEMORY] = { { [0] = 1UL } },
100 #ifdef CONFIG_HIGHMEM
101 [N_HIGH_MEMORY] = { { [0] = 1UL } },
103 #ifdef CONFIG_MOVABLE_NODE
104 [N_MEMORY] = { { [0] = 1UL } },
106 [N_CPU] = { { [0] = 1UL } },
109 EXPORT_SYMBOL(node_states);
111 /* Protect totalram_pages and zone->managed_pages */
112 static DEFINE_SPINLOCK(managed_page_count_lock);
114 unsigned long totalram_pages __read_mostly;
115 unsigned long totalreserve_pages __read_mostly;
116 unsigned long totalcma_pages __read_mostly;
118 int percpu_pagelist_fraction;
119 gfp_t gfp_allowed_mask __read_mostly = GFP_BOOT_MASK;
122 * A cached value of the page's pageblock's migratetype, used when the page is
123 * put on a pcplist. Used to avoid the pageblock migratetype lookup when
124 * freeing from pcplists in most cases, at the cost of possibly becoming stale.
125 * Also the migratetype set in the page does not necessarily match the pcplist
126 * index, e.g. page might have MIGRATE_CMA set but be on a pcplist with any
127 * other index - this ensures that it will be put on the correct CMA freelist.
129 static inline int get_pcppage_migratetype(struct page *page)
134 static inline void set_pcppage_migratetype(struct page *page, int migratetype)
136 page->index = migratetype;
139 #ifdef CONFIG_PM_SLEEP
141 * The following functions are used by the suspend/hibernate code to temporarily
142 * change gfp_allowed_mask in order to avoid using I/O during memory allocations
143 * while devices are suspended. To avoid races with the suspend/hibernate code,
144 * they should always be called with pm_mutex held (gfp_allowed_mask also should
145 * only be modified with pm_mutex held, unless the suspend/hibernate code is
146 * guaranteed not to run in parallel with that modification).
149 static gfp_t saved_gfp_mask;
151 void pm_restore_gfp_mask(void)
153 WARN_ON(!mutex_is_locked(&pm_mutex));
154 if (saved_gfp_mask) {
155 gfp_allowed_mask = saved_gfp_mask;
160 void pm_restrict_gfp_mask(void)
162 WARN_ON(!mutex_is_locked(&pm_mutex));
163 WARN_ON(saved_gfp_mask);
164 saved_gfp_mask = gfp_allowed_mask;
165 gfp_allowed_mask &= ~(__GFP_IO | __GFP_FS);
168 bool pm_suspended_storage(void)
170 if ((gfp_allowed_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
174 #endif /* CONFIG_PM_SLEEP */
176 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
177 unsigned int pageblock_order __read_mostly;
180 static void __free_pages_ok(struct page *page, unsigned int order);
183 * results with 256, 32 in the lowmem_reserve sysctl:
184 * 1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
185 * 1G machine -> (16M dma, 784M normal, 224M high)
186 * NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
187 * HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
188 * HIGHMEM allocation will leave (224M+784M)/256 of ram reserved in ZONE_DMA
190 * TBD: should special case ZONE_DMA32 machines here - in those we normally
191 * don't need any ZONE_NORMAL reservation
193 int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES-1] = {
194 #ifdef CONFIG_ZONE_DMA
197 #ifdef CONFIG_ZONE_DMA32
200 #ifdef CONFIG_HIGHMEM
206 EXPORT_SYMBOL(totalram_pages);
208 static char * const zone_names[MAX_NR_ZONES] = {
209 #ifdef CONFIG_ZONE_DMA
212 #ifdef CONFIG_ZONE_DMA32
216 #ifdef CONFIG_HIGHMEM
220 #ifdef CONFIG_ZONE_DEVICE
225 static void free_compound_page(struct page *page);
226 compound_page_dtor * const compound_page_dtors[] = {
229 #ifdef CONFIG_HUGETLB_PAGE
235 * Try to keep at least this much lowmem free. Do not allow normal
236 * allocations below this point, only high priority ones. Automatically
237 * tuned according to the amount of memory in the system.
239 int min_free_kbytes = 1024;
240 int user_min_free_kbytes = -1;
243 * Extra memory for the system to try freeing. Used to temporarily
244 * free memory, to make space for new workloads. Anyone can allocate
245 * down to the min watermarks controlled by min_free_kbytes above.
247 int extra_free_kbytes = 0;
249 static unsigned long __meminitdata nr_kernel_pages;
250 static unsigned long __meminitdata nr_all_pages;
251 static unsigned long __meminitdata dma_reserve;
253 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
254 static unsigned long __meminitdata arch_zone_lowest_possible_pfn[MAX_NR_ZONES];
255 static unsigned long __meminitdata arch_zone_highest_possible_pfn[MAX_NR_ZONES];
256 static unsigned long __initdata required_kernelcore;
257 static unsigned long __initdata required_movablecore;
258 static unsigned long __meminitdata zone_movable_pfn[MAX_NUMNODES];
260 /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
262 EXPORT_SYMBOL(movable_zone);
263 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
266 int nr_node_ids __read_mostly = MAX_NUMNODES;
267 int nr_online_nodes __read_mostly = 1;
268 EXPORT_SYMBOL(nr_node_ids);
269 EXPORT_SYMBOL(nr_online_nodes);
272 int page_group_by_mobility_disabled __read_mostly;
274 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
275 static inline void reset_deferred_meminit(pg_data_t *pgdat)
277 pgdat->first_deferred_pfn = ULONG_MAX;
280 /* Returns true if the struct page for the pfn is uninitialised */
281 static inline bool __meminit early_page_uninitialised(unsigned long pfn)
283 int nid = early_pfn_to_nid(pfn);
285 if (node_online(nid) && pfn >= NODE_DATA(nid)->first_deferred_pfn)
291 static inline bool early_page_nid_uninitialised(unsigned long pfn, int nid)
293 if (pfn >= NODE_DATA(nid)->first_deferred_pfn)
300 * Returns false when the remaining initialisation should be deferred until
301 * later in the boot cycle when it can be parallelised.
303 static inline bool update_defer_init(pg_data_t *pgdat,
304 unsigned long pfn, unsigned long zone_end,
305 unsigned long *nr_initialised)
307 /* Always populate low zones for address-contrained allocations */
308 if (zone_end < pgdat_end_pfn(pgdat))
311 /* Initialise at least 2G of the highest zone */
313 if (*nr_initialised > (2UL << (30 - PAGE_SHIFT)) &&
314 (pfn & (PAGES_PER_SECTION - 1)) == 0) {
315 pgdat->first_deferred_pfn = pfn;
322 static inline void reset_deferred_meminit(pg_data_t *pgdat)
326 static inline bool early_page_uninitialised(unsigned long pfn)
331 static inline bool early_page_nid_uninitialised(unsigned long pfn, int nid)
336 static inline bool update_defer_init(pg_data_t *pgdat,
337 unsigned long pfn, unsigned long zone_end,
338 unsigned long *nr_initialised)
345 void set_pageblock_migratetype(struct page *page, int migratetype)
347 if (unlikely(page_group_by_mobility_disabled &&
348 migratetype < MIGRATE_PCPTYPES))
349 migratetype = MIGRATE_UNMOVABLE;
351 set_pageblock_flags_group(page, (unsigned long)migratetype,
352 PB_migrate, PB_migrate_end);
355 #ifdef CONFIG_DEBUG_VM
356 static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
360 unsigned long pfn = page_to_pfn(page);
361 unsigned long sp, start_pfn;
364 seq = zone_span_seqbegin(zone);
365 start_pfn = zone->zone_start_pfn;
366 sp = zone->spanned_pages;
367 if (!zone_spans_pfn(zone, pfn))
369 } while (zone_span_seqretry(zone, seq));
372 pr_err("page 0x%lx outside node %d zone %s [ 0x%lx - 0x%lx ]\n",
373 pfn, zone_to_nid(zone), zone->name,
374 start_pfn, start_pfn + sp);
379 static int page_is_consistent(struct zone *zone, struct page *page)
381 if (!pfn_valid_within(page_to_pfn(page)))
383 if (zone != page_zone(page))
389 * Temporary debugging check for pages not lying within a given zone.
391 static int bad_range(struct zone *zone, struct page *page)
393 if (page_outside_zone_boundaries(zone, page))
395 if (!page_is_consistent(zone, page))
401 static inline int bad_range(struct zone *zone, struct page *page)
407 static void bad_page(struct page *page, const char *reason,
408 unsigned long bad_flags)
410 static unsigned long resume;
411 static unsigned long nr_shown;
412 static unsigned long nr_unshown;
414 /* Don't complain about poisoned pages */
415 if (PageHWPoison(page)) {
416 page_mapcount_reset(page); /* remove PageBuddy */
421 * Allow a burst of 60 reports, then keep quiet for that minute;
422 * or allow a steady drip of one report per second.
424 if (nr_shown == 60) {
425 if (time_before(jiffies, resume)) {
431 "BUG: Bad page state: %lu messages suppressed\n",
438 resume = jiffies + 60 * HZ;
440 printk(KERN_ALERT "BUG: Bad page state in process %s pfn:%05lx\n",
441 current->comm, page_to_pfn(page));
442 dump_page_badflags(page, reason, bad_flags);
447 /* Leave bad fields for debug, except PageBuddy could make trouble */
448 page_mapcount_reset(page); /* remove PageBuddy */
449 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
453 * Higher-order pages are called "compound pages". They are structured thusly:
455 * The first PAGE_SIZE page is called the "head page" and have PG_head set.
457 * The remaining PAGE_SIZE pages are called "tail pages". PageTail() is encoded
458 * in bit 0 of page->compound_head. The rest of bits is pointer to head page.
460 * The first tail page's ->compound_dtor holds the offset in array of compound
461 * page destructors. See compound_page_dtors.
463 * The first tail page's ->compound_order holds the order of allocation.
464 * This usage means that zero-order pages may not be compound.
467 static void free_compound_page(struct page *page)
469 __free_pages_ok(page, compound_order(page));
472 void prep_compound_page(struct page *page, unsigned int order)
475 int nr_pages = 1 << order;
477 set_compound_page_dtor(page, COMPOUND_PAGE_DTOR);
478 set_compound_order(page, order);
480 for (i = 1; i < nr_pages; i++) {
481 struct page *p = page + i;
482 set_page_count(p, 0);
483 set_compound_head(p, page);
487 #ifdef CONFIG_DEBUG_PAGEALLOC
488 unsigned int _debug_guardpage_minorder;
489 bool _debug_pagealloc_enabled __read_mostly;
490 bool _debug_guardpage_enabled __read_mostly;
492 static int __init early_debug_pagealloc(char *buf)
497 if (strcmp(buf, "on") == 0)
498 _debug_pagealloc_enabled = true;
502 early_param("debug_pagealloc", early_debug_pagealloc);
504 static bool need_debug_guardpage(void)
506 /* If we don't use debug_pagealloc, we don't need guard page */
507 if (!debug_pagealloc_enabled())
513 static void init_debug_guardpage(void)
515 if (!debug_pagealloc_enabled())
518 _debug_guardpage_enabled = true;
521 struct page_ext_operations debug_guardpage_ops = {
522 .need = need_debug_guardpage,
523 .init = init_debug_guardpage,
526 static int __init debug_guardpage_minorder_setup(char *buf)
530 if (kstrtoul(buf, 10, &res) < 0 || res > MAX_ORDER / 2) {
531 printk(KERN_ERR "Bad debug_guardpage_minorder value\n");
534 _debug_guardpage_minorder = res;
535 printk(KERN_INFO "Setting debug_guardpage_minorder to %lu\n", res);
538 __setup("debug_guardpage_minorder=", debug_guardpage_minorder_setup);
540 static inline void set_page_guard(struct zone *zone, struct page *page,
541 unsigned int order, int migratetype)
543 struct page_ext *page_ext;
545 if (!debug_guardpage_enabled())
548 page_ext = lookup_page_ext(page);
549 __set_bit(PAGE_EXT_DEBUG_GUARD, &page_ext->flags);
551 INIT_LIST_HEAD(&page->lru);
552 set_page_private(page, order);
553 /* Guard pages are not available for any usage */
554 __mod_zone_freepage_state(zone, -(1 << order), migratetype);
557 static inline void clear_page_guard(struct zone *zone, struct page *page,
558 unsigned int order, int migratetype)
560 struct page_ext *page_ext;
562 if (!debug_guardpage_enabled())
565 page_ext = lookup_page_ext(page);
566 __clear_bit(PAGE_EXT_DEBUG_GUARD, &page_ext->flags);
568 set_page_private(page, 0);
569 if (!is_migrate_isolate(migratetype))
570 __mod_zone_freepage_state(zone, (1 << order), migratetype);
573 struct page_ext_operations debug_guardpage_ops = { NULL, };
574 static inline void set_page_guard(struct zone *zone, struct page *page,
575 unsigned int order, int migratetype) {}
576 static inline void clear_page_guard(struct zone *zone, struct page *page,
577 unsigned int order, int migratetype) {}
580 static inline void set_page_order(struct page *page, unsigned int order)
582 set_page_private(page, order);
583 __SetPageBuddy(page);
586 static inline void rmv_page_order(struct page *page)
588 __ClearPageBuddy(page);
589 set_page_private(page, 0);
593 * This function checks whether a page is free && is the buddy
594 * we can do coalesce a page and its buddy if
595 * (a) the buddy is not in a hole &&
596 * (b) the buddy is in the buddy system &&
597 * (c) a page and its buddy have the same order &&
598 * (d) a page and its buddy are in the same zone.
600 * For recording whether a page is in the buddy system, we set ->_mapcount
601 * PAGE_BUDDY_MAPCOUNT_VALUE.
602 * Setting, clearing, and testing _mapcount PAGE_BUDDY_MAPCOUNT_VALUE is
603 * serialized by zone->lock.
605 * For recording page's order, we use page_private(page).
607 static inline int page_is_buddy(struct page *page, struct page *buddy,
610 if (!pfn_valid_within(page_to_pfn(buddy)))
613 if (page_is_guard(buddy) && page_order(buddy) == order) {
614 if (page_zone_id(page) != page_zone_id(buddy))
617 VM_BUG_ON_PAGE(page_count(buddy) != 0, buddy);
622 if (PageBuddy(buddy) && page_order(buddy) == order) {
624 * zone check is done late to avoid uselessly
625 * calculating zone/node ids for pages that could
628 if (page_zone_id(page) != page_zone_id(buddy))
631 VM_BUG_ON_PAGE(page_count(buddy) != 0, buddy);
639 * Freeing function for a buddy system allocator.
641 * The concept of a buddy system is to maintain direct-mapped table
642 * (containing bit values) for memory blocks of various "orders".
643 * The bottom level table contains the map for the smallest allocatable
644 * units of memory (here, pages), and each level above it describes
645 * pairs of units from the levels below, hence, "buddies".
646 * At a high level, all that happens here is marking the table entry
647 * at the bottom level available, and propagating the changes upward
648 * as necessary, plus some accounting needed to play nicely with other
649 * parts of the VM system.
650 * At each level, we keep a list of pages, which are heads of continuous
651 * free pages of length of (1 << order) and marked with _mapcount
652 * PAGE_BUDDY_MAPCOUNT_VALUE. Page's order is recorded in page_private(page)
654 * So when we are allocating or freeing one, we can derive the state of the
655 * other. That is, if we allocate a small block, and both were
656 * free, the remainder of the region must be split into blocks.
657 * If a block is freed, and its buddy is also free, then this
658 * triggers coalescing into a block of larger size.
663 static inline void __free_one_page(struct page *page,
665 struct zone *zone, unsigned int order,
668 unsigned long page_idx;
669 unsigned long combined_idx;
670 unsigned long uninitialized_var(buddy_idx);
672 unsigned int max_order;
674 max_order = min_t(unsigned int, MAX_ORDER, pageblock_order + 1);
676 VM_BUG_ON(!zone_is_initialized(zone));
677 VM_BUG_ON_PAGE(page->flags & PAGE_FLAGS_CHECK_AT_PREP, page);
679 VM_BUG_ON(migratetype == -1);
680 if (likely(!is_migrate_isolate(migratetype)))
681 __mod_zone_freepage_state(zone, 1 << order, migratetype);
683 page_idx = pfn & ((1 << MAX_ORDER) - 1);
685 VM_BUG_ON_PAGE(page_idx & ((1 << order) - 1), page);
686 VM_BUG_ON_PAGE(bad_range(zone, page), page);
689 while (order < max_order - 1) {
690 buddy_idx = __find_buddy_index(page_idx, order);
691 buddy = page + (buddy_idx - page_idx);
692 if (!page_is_buddy(page, buddy, order))
695 * Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page,
696 * merge with it and move up one order.
698 if (page_is_guard(buddy)) {
699 clear_page_guard(zone, buddy, order, migratetype);
701 list_del(&buddy->lru);
702 zone->free_area[order].nr_free--;
703 rmv_page_order(buddy);
705 combined_idx = buddy_idx & page_idx;
706 page = page + (combined_idx - page_idx);
707 page_idx = combined_idx;
710 if (max_order < MAX_ORDER) {
711 /* If we are here, it means order is >= pageblock_order.
712 * We want to prevent merge between freepages on isolate
713 * pageblock and normal pageblock. Without this, pageblock
714 * isolation could cause incorrect freepage or CMA accounting.
716 * We don't want to hit this code for the more frequent
719 if (unlikely(has_isolate_pageblock(zone))) {
722 buddy_idx = __find_buddy_index(page_idx, order);
723 buddy = page + (buddy_idx - page_idx);
724 buddy_mt = get_pageblock_migratetype(buddy);
726 if (migratetype != buddy_mt
727 && (is_migrate_isolate(migratetype) ||
728 is_migrate_isolate(buddy_mt)))
732 goto continue_merging;
736 set_page_order(page, order);
739 * If this is not the largest possible page, check if the buddy
740 * of the next-highest order is free. If it is, it's possible
741 * that pages are being freed that will coalesce soon. In case,
742 * that is happening, add the free page to the tail of the list
743 * so it's less likely to be used soon and more likely to be merged
744 * as a higher order page
746 if ((order < MAX_ORDER-2) && pfn_valid_within(page_to_pfn(buddy))) {
747 struct page *higher_page, *higher_buddy;
748 combined_idx = buddy_idx & page_idx;
749 higher_page = page + (combined_idx - page_idx);
750 buddy_idx = __find_buddy_index(combined_idx, order + 1);
751 higher_buddy = higher_page + (buddy_idx - combined_idx);
752 if (page_is_buddy(higher_page, higher_buddy, order + 1)) {
753 list_add_tail(&page->lru,
754 &zone->free_area[order].free_list[migratetype]);
759 list_add(&page->lru, &zone->free_area[order].free_list[migratetype]);
761 zone->free_area[order].nr_free++;
764 static inline int free_pages_check(struct page *page)
766 const char *bad_reason = NULL;
767 unsigned long bad_flags = 0;
769 if (unlikely(page_mapcount(page)))
770 bad_reason = "nonzero mapcount";
771 if (unlikely(page->mapping != NULL))
772 bad_reason = "non-NULL mapping";
773 if (unlikely(atomic_read(&page->_count) != 0))
774 bad_reason = "nonzero _count";
775 if (unlikely(page->flags & PAGE_FLAGS_CHECK_AT_FREE)) {
776 bad_reason = "PAGE_FLAGS_CHECK_AT_FREE flag(s) set";
777 bad_flags = PAGE_FLAGS_CHECK_AT_FREE;
780 if (unlikely(page->mem_cgroup))
781 bad_reason = "page still charged to cgroup";
783 if (unlikely(bad_reason)) {
784 bad_page(page, bad_reason, bad_flags);
787 page_cpupid_reset_last(page);
788 if (page->flags & PAGE_FLAGS_CHECK_AT_PREP)
789 page->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
794 * Frees a number of pages from the PCP lists
795 * Assumes all pages on list are in same zone, and of same order.
796 * count is the number of pages to free.
798 * If the zone was previously in an "all pages pinned" state then look to
799 * see if this freeing clears that state.
801 * And clear the zone's pages_scanned counter, to hold off the "all pages are
802 * pinned" detection logic.
804 static void free_pcppages_bulk(struct zone *zone, int count,
805 struct per_cpu_pages *pcp)
810 unsigned long nr_scanned;
812 spin_lock(&zone->lock);
813 nr_scanned = zone_page_state(zone, NR_PAGES_SCANNED);
815 __mod_zone_page_state(zone, NR_PAGES_SCANNED, -nr_scanned);
819 struct list_head *list;
822 * Remove pages from lists in a round-robin fashion. A
823 * batch_free count is maintained that is incremented when an
824 * empty list is encountered. This is so more pages are freed
825 * off fuller lists instead of spinning excessively around empty
830 if (++migratetype == MIGRATE_PCPTYPES)
832 list = &pcp->lists[migratetype];
833 } while (list_empty(list));
835 /* This is the only non-empty list. Free them all. */
836 if (batch_free == MIGRATE_PCPTYPES)
837 batch_free = to_free;
840 int mt; /* migratetype of the to-be-freed page */
842 page = list_entry(list->prev, struct page, lru);
843 /* must delete as __free_one_page list manipulates */
844 list_del(&page->lru);
846 mt = get_pcppage_migratetype(page);
847 /* MIGRATE_ISOLATE page should not go to pcplists */
848 VM_BUG_ON_PAGE(is_migrate_isolate(mt), page);
849 /* Pageblock could have been isolated meanwhile */
850 if (unlikely(has_isolate_pageblock(zone)))
851 mt = get_pageblock_migratetype(page);
853 __free_one_page(page, page_to_pfn(page), zone, 0, mt);
854 trace_mm_page_pcpu_drain(page, 0, mt);
855 } while (--to_free && --batch_free && !list_empty(list));
857 spin_unlock(&zone->lock);
860 static void free_one_page(struct zone *zone,
861 struct page *page, unsigned long pfn,
865 unsigned long nr_scanned;
866 spin_lock(&zone->lock);
867 nr_scanned = zone_page_state(zone, NR_PAGES_SCANNED);
869 __mod_zone_page_state(zone, NR_PAGES_SCANNED, -nr_scanned);
871 if (unlikely(has_isolate_pageblock(zone) ||
872 is_migrate_isolate(migratetype))) {
873 migratetype = get_pfnblock_migratetype(page, pfn);
875 __free_one_page(page, pfn, zone, order, migratetype);
876 spin_unlock(&zone->lock);
879 static int free_tail_pages_check(struct page *head_page, struct page *page)
884 * We rely page->lru.next never has bit 0 set, unless the page
885 * is PageTail(). Let's make sure that's true even for poisoned ->lru.
887 BUILD_BUG_ON((unsigned long)LIST_POISON1 & 1);
889 if (!IS_ENABLED(CONFIG_DEBUG_VM)) {
893 if (unlikely(!PageTail(page))) {
894 bad_page(page, "PageTail not set", 0);
897 if (unlikely(compound_head(page) != head_page)) {
898 bad_page(page, "compound_head not consistent", 0);
903 clear_compound_head(page);
907 static void __meminit __init_single_page(struct page *page, unsigned long pfn,
908 unsigned long zone, int nid)
910 set_page_links(page, zone, nid, pfn);
911 init_page_count(page);
912 page_mapcount_reset(page);
913 page_cpupid_reset_last(page);
915 INIT_LIST_HEAD(&page->lru);
916 #ifdef WANT_PAGE_VIRTUAL
917 /* The shift won't overflow because ZONE_NORMAL is below 4G. */
918 if (!is_highmem_idx(zone))
919 set_page_address(page, __va(pfn << PAGE_SHIFT));
923 static void __meminit __init_single_pfn(unsigned long pfn, unsigned long zone,
926 return __init_single_page(pfn_to_page(pfn), pfn, zone, nid);
929 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
930 static void init_reserved_page(unsigned long pfn)
935 if (!early_page_uninitialised(pfn))
938 nid = early_pfn_to_nid(pfn);
939 pgdat = NODE_DATA(nid);
941 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
942 struct zone *zone = &pgdat->node_zones[zid];
944 if (pfn >= zone->zone_start_pfn && pfn < zone_end_pfn(zone))
947 __init_single_pfn(pfn, zid, nid);
950 static inline void init_reserved_page(unsigned long pfn)
953 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
956 * Initialised pages do not have PageReserved set. This function is
957 * called for each range allocated by the bootmem allocator and
958 * marks the pages PageReserved. The remaining valid pages are later
959 * sent to the buddy page allocator.
961 void __meminit reserve_bootmem_region(phys_addr_t start, phys_addr_t end)
963 unsigned long start_pfn = PFN_DOWN(start);
964 unsigned long end_pfn = PFN_UP(end);
966 for (; start_pfn < end_pfn; start_pfn++) {
967 if (pfn_valid(start_pfn)) {
968 struct page *page = pfn_to_page(start_pfn);
970 init_reserved_page(start_pfn);
972 /* Avoid false-positive PageTail() */
973 INIT_LIST_HEAD(&page->lru);
975 SetPageReserved(page);
980 static bool free_pages_prepare(struct page *page, unsigned int order)
982 bool compound = PageCompound(page);
985 VM_BUG_ON_PAGE(PageTail(page), page);
986 VM_BUG_ON_PAGE(compound && compound_order(page) != order, page);
988 trace_mm_page_free(page, order);
989 kmemcheck_free_shadow(page, order);
990 kasan_free_pages(page, order);
993 page->mapping = NULL;
994 bad += free_pages_check(page);
995 for (i = 1; i < (1 << order); i++) {
997 bad += free_tail_pages_check(page, page + i);
998 bad += free_pages_check(page + i);
1003 reset_page_owner(page, order);
1005 if (!PageHighMem(page)) {
1006 debug_check_no_locks_freed(page_address(page),
1007 PAGE_SIZE << order);
1008 debug_check_no_obj_freed(page_address(page),
1009 PAGE_SIZE << order);
1011 arch_free_page(page, order);
1012 kernel_map_pages(page, 1 << order, 0);
1017 static void __free_pages_ok(struct page *page, unsigned int order)
1019 unsigned long flags;
1021 unsigned long pfn = page_to_pfn(page);
1023 if (!free_pages_prepare(page, order))
1026 migratetype = get_pfnblock_migratetype(page, pfn);
1027 local_irq_save(flags);
1028 __count_vm_events(PGFREE, 1 << order);
1029 free_one_page(page_zone(page), page, pfn, order, migratetype);
1030 local_irq_restore(flags);
1033 static void __init __free_pages_boot_core(struct page *page,
1034 unsigned long pfn, unsigned int order)
1036 unsigned int nr_pages = 1 << order;
1037 struct page *p = page;
1041 for (loop = 0; loop < (nr_pages - 1); loop++, p++) {
1043 __ClearPageReserved(p);
1044 set_page_count(p, 0);
1046 __ClearPageReserved(p);
1047 set_page_count(p, 0);
1049 page_zone(page)->managed_pages += nr_pages;
1050 set_page_refcounted(page);
1051 __free_pages(page, order);
1054 #if defined(CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID) || \
1055 defined(CONFIG_HAVE_MEMBLOCK_NODE_MAP)
1057 static struct mminit_pfnnid_cache early_pfnnid_cache __meminitdata;
1059 int __meminit early_pfn_to_nid(unsigned long pfn)
1061 static DEFINE_SPINLOCK(early_pfn_lock);
1064 spin_lock(&early_pfn_lock);
1065 nid = __early_pfn_to_nid(pfn, &early_pfnnid_cache);
1067 nid = first_online_node;
1068 spin_unlock(&early_pfn_lock);
1074 #ifdef CONFIG_NODES_SPAN_OTHER_NODES
1075 static inline bool __meminit meminit_pfn_in_nid(unsigned long pfn, int node,
1076 struct mminit_pfnnid_cache *state)
1080 nid = __early_pfn_to_nid(pfn, state);
1081 if (nid >= 0 && nid != node)
1086 /* Only safe to use early in boot when initialisation is single-threaded */
1087 static inline bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
1089 return meminit_pfn_in_nid(pfn, node, &early_pfnnid_cache);
1094 static inline bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
1098 static inline bool __meminit meminit_pfn_in_nid(unsigned long pfn, int node,
1099 struct mminit_pfnnid_cache *state)
1106 void __init __free_pages_bootmem(struct page *page, unsigned long pfn,
1109 if (early_page_uninitialised(pfn))
1111 return __free_pages_boot_core(page, pfn, order);
1114 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1115 static void __init deferred_free_range(struct page *page,
1116 unsigned long pfn, int nr_pages)
1123 /* Free a large naturally-aligned chunk if possible */
1124 if (nr_pages == MAX_ORDER_NR_PAGES &&
1125 (pfn & (MAX_ORDER_NR_PAGES-1)) == 0) {
1126 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
1127 __free_pages_boot_core(page, pfn, MAX_ORDER-1);
1131 for (i = 0; i < nr_pages; i++, page++, pfn++)
1132 __free_pages_boot_core(page, pfn, 0);
1135 /* Completion tracking for deferred_init_memmap() threads */
1136 static atomic_t pgdat_init_n_undone __initdata;
1137 static __initdata DECLARE_COMPLETION(pgdat_init_all_done_comp);
1139 static inline void __init pgdat_init_report_one_done(void)
1141 if (atomic_dec_and_test(&pgdat_init_n_undone))
1142 complete(&pgdat_init_all_done_comp);
1145 /* Initialise remaining memory on a node */
1146 static int __init deferred_init_memmap(void *data)
1148 pg_data_t *pgdat = data;
1149 int nid = pgdat->node_id;
1150 struct mminit_pfnnid_cache nid_init_state = { };
1151 unsigned long start = jiffies;
1152 unsigned long nr_pages = 0;
1153 unsigned long walk_start, walk_end;
1156 unsigned long first_init_pfn = pgdat->first_deferred_pfn;
1157 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
1159 if (first_init_pfn == ULONG_MAX) {
1160 pgdat_init_report_one_done();
1164 /* Bind memory initialisation thread to a local node if possible */
1165 if (!cpumask_empty(cpumask))
1166 set_cpus_allowed_ptr(current, cpumask);
1168 /* Sanity check boundaries */
1169 BUG_ON(pgdat->first_deferred_pfn < pgdat->node_start_pfn);
1170 BUG_ON(pgdat->first_deferred_pfn > pgdat_end_pfn(pgdat));
1171 pgdat->first_deferred_pfn = ULONG_MAX;
1173 /* Only the highest zone is deferred so find it */
1174 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1175 zone = pgdat->node_zones + zid;
1176 if (first_init_pfn < zone_end_pfn(zone))
1180 for_each_mem_pfn_range(i, nid, &walk_start, &walk_end, NULL) {
1181 unsigned long pfn, end_pfn;
1182 struct page *page = NULL;
1183 struct page *free_base_page = NULL;
1184 unsigned long free_base_pfn = 0;
1187 end_pfn = min(walk_end, zone_end_pfn(zone));
1188 pfn = first_init_pfn;
1189 if (pfn < walk_start)
1191 if (pfn < zone->zone_start_pfn)
1192 pfn = zone->zone_start_pfn;
1194 for (; pfn < end_pfn; pfn++) {
1195 if (!pfn_valid_within(pfn))
1199 * Ensure pfn_valid is checked every
1200 * MAX_ORDER_NR_PAGES for memory holes
1202 if ((pfn & (MAX_ORDER_NR_PAGES - 1)) == 0) {
1203 if (!pfn_valid(pfn)) {
1209 if (!meminit_pfn_in_nid(pfn, nid, &nid_init_state)) {
1214 /* Minimise pfn page lookups and scheduler checks */
1215 if (page && (pfn & (MAX_ORDER_NR_PAGES - 1)) != 0) {
1218 nr_pages += nr_to_free;
1219 deferred_free_range(free_base_page,
1220 free_base_pfn, nr_to_free);
1221 free_base_page = NULL;
1222 free_base_pfn = nr_to_free = 0;
1224 page = pfn_to_page(pfn);
1229 VM_BUG_ON(page_zone(page) != zone);
1233 __init_single_page(page, pfn, zid, nid);
1234 if (!free_base_page) {
1235 free_base_page = page;
1236 free_base_pfn = pfn;
1241 /* Where possible, batch up pages for a single free */
1244 /* Free the current block of pages to allocator */
1245 nr_pages += nr_to_free;
1246 deferred_free_range(free_base_page, free_base_pfn,
1248 free_base_page = NULL;
1249 free_base_pfn = nr_to_free = 0;
1252 first_init_pfn = max(end_pfn, first_init_pfn);
1255 /* Sanity check that the next zone really is unpopulated */
1256 WARN_ON(++zid < MAX_NR_ZONES && populated_zone(++zone));
1258 pr_info("node %d initialised, %lu pages in %ums\n", nid, nr_pages,
1259 jiffies_to_msecs(jiffies - start));
1261 pgdat_init_report_one_done();
1265 void __init page_alloc_init_late(void)
1269 /* There will be num_node_state(N_MEMORY) threads */
1270 atomic_set(&pgdat_init_n_undone, num_node_state(N_MEMORY));
1271 for_each_node_state(nid, N_MEMORY) {
1272 kthread_run(deferred_init_memmap, NODE_DATA(nid), "pgdatinit%d", nid);
1275 /* Block until all are initialised */
1276 wait_for_completion(&pgdat_init_all_done_comp);
1278 /* Reinit limits that are based on free pages after the kernel is up */
1279 files_maxfiles_init();
1281 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
1284 /* Free whole pageblock and set its migration type to MIGRATE_CMA. */
1285 void __init init_cma_reserved_pageblock(struct page *page)
1287 unsigned i = pageblock_nr_pages;
1288 struct page *p = page;
1291 __ClearPageReserved(p);
1292 set_page_count(p, 0);
1295 set_pageblock_migratetype(page, MIGRATE_CMA);
1297 if (pageblock_order >= MAX_ORDER) {
1298 i = pageblock_nr_pages;
1301 set_page_refcounted(p);
1302 __free_pages(p, MAX_ORDER - 1);
1303 p += MAX_ORDER_NR_PAGES;
1304 } while (i -= MAX_ORDER_NR_PAGES);
1306 set_page_refcounted(page);
1307 __free_pages(page, pageblock_order);
1310 adjust_managed_page_count(page, pageblock_nr_pages);
1315 * The order of subdivision here is critical for the IO subsystem.
1316 * Please do not alter this order without good reasons and regression
1317 * testing. Specifically, as large blocks of memory are subdivided,
1318 * the order in which smaller blocks are delivered depends on the order
1319 * they're subdivided in this function. This is the primary factor
1320 * influencing the order in which pages are delivered to the IO
1321 * subsystem according to empirical testing, and this is also justified
1322 * by considering the behavior of a buddy system containing a single
1323 * large block of memory acted on by a series of small allocations.
1324 * This behavior is a critical factor in sglist merging's success.
1328 static inline void expand(struct zone *zone, struct page *page,
1329 int low, int high, struct free_area *area,
1332 unsigned long size = 1 << high;
1334 while (high > low) {
1338 VM_BUG_ON_PAGE(bad_range(zone, &page[size]), &page[size]);
1340 if (IS_ENABLED(CONFIG_DEBUG_PAGEALLOC) &&
1341 debug_guardpage_enabled() &&
1342 high < debug_guardpage_minorder()) {
1344 * Mark as guard pages (or page), that will allow to
1345 * merge back to allocator when buddy will be freed.
1346 * Corresponding page table entries will not be touched,
1347 * pages will stay not present in virtual address space
1349 set_page_guard(zone, &page[size], high, migratetype);
1352 list_add(&page[size].lru, &area->free_list[migratetype]);
1354 set_page_order(&page[size], high);
1359 * This page is about to be returned from the page allocator
1361 static inline int check_new_page(struct page *page)
1363 const char *bad_reason = NULL;
1364 unsigned long bad_flags = 0;
1366 if (unlikely(page_mapcount(page)))
1367 bad_reason = "nonzero mapcount";
1368 if (unlikely(page->mapping != NULL))
1369 bad_reason = "non-NULL mapping";
1370 if (unlikely(atomic_read(&page->_count) != 0))
1371 bad_reason = "nonzero _count";
1372 if (unlikely(page->flags & __PG_HWPOISON)) {
1373 bad_reason = "HWPoisoned (hardware-corrupted)";
1374 bad_flags = __PG_HWPOISON;
1376 if (unlikely(page->flags & PAGE_FLAGS_CHECK_AT_PREP)) {
1377 bad_reason = "PAGE_FLAGS_CHECK_AT_PREP flag set";
1378 bad_flags = PAGE_FLAGS_CHECK_AT_PREP;
1381 if (unlikely(page->mem_cgroup))
1382 bad_reason = "page still charged to cgroup";
1384 if (unlikely(bad_reason)) {
1385 bad_page(page, bad_reason, bad_flags);
1391 static int prep_new_page(struct page *page, unsigned int order, gfp_t gfp_flags,
1396 for (i = 0; i < (1 << order); i++) {
1397 struct page *p = page + i;
1398 if (unlikely(check_new_page(p)))
1402 set_page_private(page, 0);
1403 set_page_refcounted(page);
1405 arch_alloc_page(page, order);
1406 kernel_map_pages(page, 1 << order, 1);
1407 kasan_alloc_pages(page, order);
1409 if (gfp_flags & __GFP_ZERO)
1410 for (i = 0; i < (1 << order); i++)
1411 clear_highpage(page + i);
1413 if (order && (gfp_flags & __GFP_COMP))
1414 prep_compound_page(page, order);
1416 set_page_owner(page, order, gfp_flags);
1419 * page is set pfmemalloc when ALLOC_NO_WATERMARKS was necessary to
1420 * allocate the page. The expectation is that the caller is taking
1421 * steps that will free more memory. The caller should avoid the page
1422 * being used for !PFMEMALLOC purposes.
1424 if (alloc_flags & ALLOC_NO_WATERMARKS)
1425 set_page_pfmemalloc(page);
1427 clear_page_pfmemalloc(page);
1433 * Go through the free lists for the given migratetype and remove
1434 * the smallest available page from the freelists
1437 struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
1440 unsigned int current_order;
1441 struct free_area *area;
1444 /* Find a page of the appropriate size in the preferred list */
1445 for (current_order = order; current_order < MAX_ORDER; ++current_order) {
1446 area = &(zone->free_area[current_order]);
1447 if (list_empty(&area->free_list[migratetype]))
1450 page = list_entry(area->free_list[migratetype].next,
1452 list_del(&page->lru);
1453 rmv_page_order(page);
1455 expand(zone, page, order, current_order, area, migratetype);
1456 set_pcppage_migratetype(page, migratetype);
1465 * This array describes the order lists are fallen back to when
1466 * the free lists for the desirable migrate type are depleted
1468 static int fallbacks[MIGRATE_TYPES][4] = {
1469 [MIGRATE_UNMOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE, MIGRATE_TYPES },
1470 [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE, MIGRATE_MOVABLE, MIGRATE_TYPES },
1471 [MIGRATE_MOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_TYPES },
1473 [MIGRATE_CMA] = { MIGRATE_TYPES }, /* Never used */
1475 #ifdef CONFIG_MEMORY_ISOLATION
1476 [MIGRATE_ISOLATE] = { MIGRATE_TYPES }, /* Never used */
1481 static struct page *__rmqueue_cma_fallback(struct zone *zone,
1484 return __rmqueue_smallest(zone, order, MIGRATE_CMA);
1487 static inline struct page *__rmqueue_cma_fallback(struct zone *zone,
1488 unsigned int order) { return NULL; }
1492 * Move the free pages in a range to the free lists of the requested type.
1493 * Note that start_page and end_pages are not aligned on a pageblock
1494 * boundary. If alignment is required, use move_freepages_block()
1496 int move_freepages(struct zone *zone,
1497 struct page *start_page, struct page *end_page,
1502 int pages_moved = 0;
1504 #ifndef CONFIG_HOLES_IN_ZONE
1506 * page_zone is not safe to call in this context when
1507 * CONFIG_HOLES_IN_ZONE is set. This bug check is probably redundant
1508 * anyway as we check zone boundaries in move_freepages_block().
1509 * Remove at a later date when no bug reports exist related to
1510 * grouping pages by mobility
1512 VM_BUG_ON(page_zone(start_page) != page_zone(end_page));
1515 for (page = start_page; page <= end_page;) {
1516 /* Make sure we are not inadvertently changing nodes */
1517 VM_BUG_ON_PAGE(page_to_nid(page) != zone_to_nid(zone), page);
1519 if (!pfn_valid_within(page_to_pfn(page))) {
1524 if (!PageBuddy(page)) {
1529 order = page_order(page);
1530 list_move(&page->lru,
1531 &zone->free_area[order].free_list[migratetype]);
1533 pages_moved += 1 << order;
1539 int move_freepages_block(struct zone *zone, struct page *page,
1542 unsigned long start_pfn, end_pfn;
1543 struct page *start_page, *end_page;
1545 start_pfn = page_to_pfn(page);
1546 start_pfn = start_pfn & ~(pageblock_nr_pages-1);
1547 start_page = pfn_to_page(start_pfn);
1548 end_page = start_page + pageblock_nr_pages - 1;
1549 end_pfn = start_pfn + pageblock_nr_pages - 1;
1551 /* Do not cross zone boundaries */
1552 if (!zone_spans_pfn(zone, start_pfn))
1554 if (!zone_spans_pfn(zone, end_pfn))
1557 return move_freepages(zone, start_page, end_page, migratetype);
1560 static void change_pageblock_range(struct page *pageblock_page,
1561 int start_order, int migratetype)
1563 int nr_pageblocks = 1 << (start_order - pageblock_order);
1565 while (nr_pageblocks--) {
1566 set_pageblock_migratetype(pageblock_page, migratetype);
1567 pageblock_page += pageblock_nr_pages;
1572 * When we are falling back to another migratetype during allocation, try to
1573 * steal extra free pages from the same pageblocks to satisfy further
1574 * allocations, instead of polluting multiple pageblocks.
1576 * If we are stealing a relatively large buddy page, it is likely there will
1577 * be more free pages in the pageblock, so try to steal them all. For
1578 * reclaimable and unmovable allocations, we steal regardless of page size,
1579 * as fragmentation caused by those allocations polluting movable pageblocks
1580 * is worse than movable allocations stealing from unmovable and reclaimable
1583 static bool can_steal_fallback(unsigned int order, int start_mt)
1586 * Leaving this order check is intended, although there is
1587 * relaxed order check in next check. The reason is that
1588 * we can actually steal whole pageblock if this condition met,
1589 * but, below check doesn't guarantee it and that is just heuristic
1590 * so could be changed anytime.
1592 if (order >= pageblock_order)
1595 if (order >= pageblock_order / 2 ||
1596 start_mt == MIGRATE_RECLAIMABLE ||
1597 start_mt == MIGRATE_UNMOVABLE ||
1598 page_group_by_mobility_disabled)
1605 * This function implements actual steal behaviour. If order is large enough,
1606 * we can steal whole pageblock. If not, we first move freepages in this
1607 * pageblock and check whether half of pages are moved or not. If half of
1608 * pages are moved, we can change migratetype of pageblock and permanently
1609 * use it's pages as requested migratetype in the future.
1611 static void steal_suitable_fallback(struct zone *zone, struct page *page,
1614 unsigned int current_order = page_order(page);
1617 /* Take ownership for orders >= pageblock_order */
1618 if (current_order >= pageblock_order) {
1619 change_pageblock_range(page, current_order, start_type);
1623 pages = move_freepages_block(zone, page, start_type);
1625 /* Claim the whole block if over half of it is free */
1626 if (pages >= (1 << (pageblock_order-1)) ||
1627 page_group_by_mobility_disabled)
1628 set_pageblock_migratetype(page, start_type);
1632 * Check whether there is a suitable fallback freepage with requested order.
1633 * If only_stealable is true, this function returns fallback_mt only if
1634 * we can steal other freepages all together. This would help to reduce
1635 * fragmentation due to mixed migratetype pages in one pageblock.
1637 int find_suitable_fallback(struct free_area *area, unsigned int order,
1638 int migratetype, bool only_stealable, bool *can_steal)
1643 if (area->nr_free == 0)
1648 fallback_mt = fallbacks[migratetype][i];
1649 if (fallback_mt == MIGRATE_TYPES)
1652 if (list_empty(&area->free_list[fallback_mt]))
1655 if (can_steal_fallback(order, migratetype))
1658 if (!only_stealable)
1669 * Reserve a pageblock for exclusive use of high-order atomic allocations if
1670 * there are no empty page blocks that contain a page with a suitable order
1672 static void reserve_highatomic_pageblock(struct page *page, struct zone *zone,
1673 unsigned int alloc_order)
1676 unsigned long max_managed, flags;
1679 * Limit the number reserved to 1 pageblock or roughly 1% of a zone.
1680 * Check is race-prone but harmless.
1682 max_managed = (zone->managed_pages / 100) + pageblock_nr_pages;
1683 if (zone->nr_reserved_highatomic >= max_managed)
1686 spin_lock_irqsave(&zone->lock, flags);
1688 /* Recheck the nr_reserved_highatomic limit under the lock */
1689 if (zone->nr_reserved_highatomic >= max_managed)
1693 mt = get_pageblock_migratetype(page);
1694 if (mt != MIGRATE_HIGHATOMIC &&
1695 !is_migrate_isolate(mt) && !is_migrate_cma(mt)) {
1696 zone->nr_reserved_highatomic += pageblock_nr_pages;
1697 set_pageblock_migratetype(page, MIGRATE_HIGHATOMIC);
1698 move_freepages_block(zone, page, MIGRATE_HIGHATOMIC);
1702 spin_unlock_irqrestore(&zone->lock, flags);
1706 * Used when an allocation is about to fail under memory pressure. This
1707 * potentially hurts the reliability of high-order allocations when under
1708 * intense memory pressure but failed atomic allocations should be easier
1709 * to recover from than an OOM.
1711 static void unreserve_highatomic_pageblock(const struct alloc_context *ac)
1713 struct zonelist *zonelist = ac->zonelist;
1714 unsigned long flags;
1720 for_each_zone_zonelist_nodemask(zone, z, zonelist, ac->high_zoneidx,
1722 /* Preserve at least one pageblock */
1723 if (zone->nr_reserved_highatomic <= pageblock_nr_pages)
1726 spin_lock_irqsave(&zone->lock, flags);
1727 for (order = 0; order < MAX_ORDER; order++) {
1728 struct free_area *area = &(zone->free_area[order]);
1730 if (list_empty(&area->free_list[MIGRATE_HIGHATOMIC]))
1733 page = list_entry(area->free_list[MIGRATE_HIGHATOMIC].next,
1737 * It should never happen but changes to locking could
1738 * inadvertently allow a per-cpu drain to add pages
1739 * to MIGRATE_HIGHATOMIC while unreserving so be safe
1740 * and watch for underflows.
1742 zone->nr_reserved_highatomic -= min(pageblock_nr_pages,
1743 zone->nr_reserved_highatomic);
1746 * Convert to ac->migratetype and avoid the normal
1747 * pageblock stealing heuristics. Minimally, the caller
1748 * is doing the work and needs the pages. More
1749 * importantly, if the block was always converted to
1750 * MIGRATE_UNMOVABLE or another type then the number
1751 * of pageblocks that cannot be completely freed
1754 set_pageblock_migratetype(page, ac->migratetype);
1755 move_freepages_block(zone, page, ac->migratetype);
1756 spin_unlock_irqrestore(&zone->lock, flags);
1759 spin_unlock_irqrestore(&zone->lock, flags);
1763 /* Remove an element from the buddy allocator from the fallback list */
1764 static inline struct page *
1765 __rmqueue_fallback(struct zone *zone, unsigned int order, int start_migratetype)
1767 struct free_area *area;
1768 unsigned int current_order;
1773 /* Find the largest possible block of pages in the other list */
1774 for (current_order = MAX_ORDER-1;
1775 current_order >= order && current_order <= MAX_ORDER-1;
1777 area = &(zone->free_area[current_order]);
1778 fallback_mt = find_suitable_fallback(area, current_order,
1779 start_migratetype, false, &can_steal);
1780 if (fallback_mt == -1)
1783 page = list_entry(area->free_list[fallback_mt].next,
1786 steal_suitable_fallback(zone, page, start_migratetype);
1788 /* Remove the page from the freelists */
1790 list_del(&page->lru);
1791 rmv_page_order(page);
1793 expand(zone, page, order, current_order, area,
1796 * The pcppage_migratetype may differ from pageblock's
1797 * migratetype depending on the decisions in
1798 * find_suitable_fallback(). This is OK as long as it does not
1799 * differ for MIGRATE_CMA pageblocks. Those can be used as
1800 * fallback only via special __rmqueue_cma_fallback() function
1802 set_pcppage_migratetype(page, start_migratetype);
1804 trace_mm_page_alloc_extfrag(page, order, current_order,
1805 start_migratetype, fallback_mt);
1814 * Do the hard work of removing an element from the buddy allocator.
1815 * Call me with the zone->lock already held.
1817 static struct page *__rmqueue(struct zone *zone, unsigned int order,
1818 int migratetype, gfp_t gfp_flags)
1822 page = __rmqueue_smallest(zone, order, migratetype);
1823 if (unlikely(!page)) {
1824 if (migratetype == MIGRATE_MOVABLE)
1825 page = __rmqueue_cma_fallback(zone, order);
1828 page = __rmqueue_fallback(zone, order, migratetype);
1831 trace_mm_page_alloc_zone_locked(page, order, migratetype);
1836 * Obtain a specified number of elements from the buddy allocator, all under
1837 * a single hold of the lock, for efficiency. Add them to the supplied list.
1838 * Returns the number of new pages which were placed at *list.
1840 static int rmqueue_bulk(struct zone *zone, unsigned int order,
1841 unsigned long count, struct list_head *list,
1842 int migratetype, bool cold)
1846 spin_lock(&zone->lock);
1847 for (i = 0; i < count; ++i) {
1848 struct page *page = __rmqueue(zone, order, migratetype, 0);
1849 if (unlikely(page == NULL))
1853 * Split buddy pages returned by expand() are received here
1854 * in physical page order. The page is added to the callers and
1855 * list and the list head then moves forward. From the callers
1856 * perspective, the linked list is ordered by page number in
1857 * some conditions. This is useful for IO devices that can
1858 * merge IO requests if the physical pages are ordered
1862 list_add(&page->lru, list);
1864 list_add_tail(&page->lru, list);
1866 if (is_migrate_cma(get_pcppage_migratetype(page)))
1867 __mod_zone_page_state(zone, NR_FREE_CMA_PAGES,
1870 __mod_zone_page_state(zone, NR_FREE_PAGES, -(i << order));
1871 spin_unlock(&zone->lock);
1877 * Called from the vmstat counter updater to drain pagesets of this
1878 * currently executing processor on remote nodes after they have
1881 * Note that this function must be called with the thread pinned to
1882 * a single processor.
1884 void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp)
1886 unsigned long flags;
1887 int to_drain, batch;
1889 local_irq_save(flags);
1890 batch = READ_ONCE(pcp->batch);
1891 to_drain = min(pcp->count, batch);
1893 free_pcppages_bulk(zone, to_drain, pcp);
1894 pcp->count -= to_drain;
1896 local_irq_restore(flags);
1901 * Drain pcplists of the indicated processor and zone.
1903 * The processor must either be the current processor and the
1904 * thread pinned to the current processor or a processor that
1907 static void drain_pages_zone(unsigned int cpu, struct zone *zone)
1909 unsigned long flags;
1910 struct per_cpu_pageset *pset;
1911 struct per_cpu_pages *pcp;
1913 local_irq_save(flags);
1914 pset = per_cpu_ptr(zone->pageset, cpu);
1918 free_pcppages_bulk(zone, pcp->count, pcp);
1921 local_irq_restore(flags);
1925 * Drain pcplists of all zones on the indicated processor.
1927 * The processor must either be the current processor and the
1928 * thread pinned to the current processor or a processor that
1931 static void drain_pages(unsigned int cpu)
1935 for_each_populated_zone(zone) {
1936 drain_pages_zone(cpu, zone);
1941 * Spill all of this CPU's per-cpu pages back into the buddy allocator.
1943 * The CPU has to be pinned. When zone parameter is non-NULL, spill just
1944 * the single zone's pages.
1946 void drain_local_pages(struct zone *zone)
1948 int cpu = smp_processor_id();
1951 drain_pages_zone(cpu, zone);
1957 * Spill all the per-cpu pages from all CPUs back into the buddy allocator.
1959 * When zone parameter is non-NULL, spill just the single zone's pages.
1961 * Note that this code is protected against sending an IPI to an offline
1962 * CPU but does not guarantee sending an IPI to newly hotplugged CPUs:
1963 * on_each_cpu_mask() blocks hotplug and won't talk to offlined CPUs but
1964 * nothing keeps CPUs from showing up after we populated the cpumask and
1965 * before the call to on_each_cpu_mask().
1967 void drain_all_pages(struct zone *zone)
1972 * Allocate in the BSS so we wont require allocation in
1973 * direct reclaim path for CONFIG_CPUMASK_OFFSTACK=y
1975 static cpumask_t cpus_with_pcps;
1978 * We don't care about racing with CPU hotplug event
1979 * as offline notification will cause the notified
1980 * cpu to drain that CPU pcps and on_each_cpu_mask
1981 * disables preemption as part of its processing
1983 for_each_online_cpu(cpu) {
1984 struct per_cpu_pageset *pcp;
1986 bool has_pcps = false;
1989 pcp = per_cpu_ptr(zone->pageset, cpu);
1993 for_each_populated_zone(z) {
1994 pcp = per_cpu_ptr(z->pageset, cpu);
1995 if (pcp->pcp.count) {
2003 cpumask_set_cpu(cpu, &cpus_with_pcps);
2005 cpumask_clear_cpu(cpu, &cpus_with_pcps);
2007 on_each_cpu_mask(&cpus_with_pcps, (smp_call_func_t) drain_local_pages,
2011 #ifdef CONFIG_HIBERNATION
2013 void mark_free_pages(struct zone *zone)
2015 unsigned long pfn, max_zone_pfn;
2016 unsigned long flags;
2017 unsigned int order, t;
2018 struct list_head *curr;
2020 if (zone_is_empty(zone))
2023 spin_lock_irqsave(&zone->lock, flags);
2025 max_zone_pfn = zone_end_pfn(zone);
2026 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
2027 if (pfn_valid(pfn)) {
2028 struct page *page = pfn_to_page(pfn);
2030 if (!swsusp_page_is_forbidden(page))
2031 swsusp_unset_page_free(page);
2034 for_each_migratetype_order(order, t) {
2035 list_for_each(curr, &zone->free_area[order].free_list[t]) {
2038 pfn = page_to_pfn(list_entry(curr, struct page, lru));
2039 for (i = 0; i < (1UL << order); i++)
2040 swsusp_set_page_free(pfn_to_page(pfn + i));
2043 spin_unlock_irqrestore(&zone->lock, flags);
2045 #endif /* CONFIG_PM */
2048 * Free a 0-order page
2049 * cold == true ? free a cold page : free a hot page
2051 void free_hot_cold_page(struct page *page, bool cold)
2053 struct zone *zone = page_zone(page);
2054 struct per_cpu_pages *pcp;
2055 unsigned long flags;
2056 unsigned long pfn = page_to_pfn(page);
2059 if (!free_pages_prepare(page, 0))
2062 migratetype = get_pfnblock_migratetype(page, pfn);
2063 set_pcppage_migratetype(page, migratetype);
2064 local_irq_save(flags);
2065 __count_vm_event(PGFREE);
2068 * We only track unmovable, reclaimable and movable on pcp lists.
2069 * Free ISOLATE pages back to the allocator because they are being
2070 * offlined but treat RESERVE as movable pages so we can get those
2071 * areas back if necessary. Otherwise, we may have to free
2072 * excessively into the page allocator
2074 if (migratetype >= MIGRATE_PCPTYPES) {
2075 if (unlikely(is_migrate_isolate(migratetype))) {
2076 free_one_page(zone, page, pfn, 0, migratetype);
2079 migratetype = MIGRATE_MOVABLE;
2082 pcp = &this_cpu_ptr(zone->pageset)->pcp;
2084 list_add(&page->lru, &pcp->lists[migratetype]);
2086 list_add_tail(&page->lru, &pcp->lists[migratetype]);
2088 if (pcp->count >= pcp->high) {
2089 unsigned long batch = READ_ONCE(pcp->batch);
2090 free_pcppages_bulk(zone, batch, pcp);
2091 pcp->count -= batch;
2095 local_irq_restore(flags);
2099 * Free a list of 0-order pages
2101 void free_hot_cold_page_list(struct list_head *list, bool cold)
2103 struct page *page, *next;
2105 list_for_each_entry_safe(page, next, list, lru) {
2106 trace_mm_page_free_batched(page, cold);
2107 free_hot_cold_page(page, cold);
2112 * split_page takes a non-compound higher-order page, and splits it into
2113 * n (1<<order) sub-pages: page[0..n]
2114 * Each sub-page must be freed individually.
2116 * Note: this is probably too low level an operation for use in drivers.
2117 * Please consult with lkml before using this in your driver.
2119 void split_page(struct page *page, unsigned int order)
2124 VM_BUG_ON_PAGE(PageCompound(page), page);
2125 VM_BUG_ON_PAGE(!page_count(page), page);
2127 #ifdef CONFIG_KMEMCHECK
2129 * Split shadow pages too, because free(page[0]) would
2130 * otherwise free the whole shadow.
2132 if (kmemcheck_page_is_tracked(page))
2133 split_page(virt_to_page(page[0].shadow), order);
2136 gfp_mask = get_page_owner_gfp(page);
2137 set_page_owner(page, 0, gfp_mask);
2138 for (i = 1; i < (1 << order); i++) {
2139 set_page_refcounted(page + i);
2140 set_page_owner(page + i, 0, gfp_mask);
2143 EXPORT_SYMBOL_GPL(split_page);
2145 int __isolate_free_page(struct page *page, unsigned int order)
2147 unsigned long watermark;
2151 BUG_ON(!PageBuddy(page));
2153 zone = page_zone(page);
2154 mt = get_pageblock_migratetype(page);
2156 if (!is_migrate_isolate(mt)) {
2157 /* Obey watermarks as if the page was being allocated */
2158 watermark = low_wmark_pages(zone) + (1 << order);
2159 if (!zone_watermark_ok(zone, 0, watermark, 0, 0))
2162 __mod_zone_freepage_state(zone, -(1UL << order), mt);
2165 /* Remove page from free list */
2166 list_del(&page->lru);
2167 zone->free_area[order].nr_free--;
2168 rmv_page_order(page);
2170 set_page_owner(page, order, __GFP_MOVABLE);
2172 /* Set the pageblock if the isolated page is at least a pageblock */
2173 if (order >= pageblock_order - 1) {
2174 struct page *endpage = page + (1 << order) - 1;
2175 for (; page < endpage; page += pageblock_nr_pages) {
2176 int mt = get_pageblock_migratetype(page);
2177 if (!is_migrate_isolate(mt) && !is_migrate_cma(mt))
2178 set_pageblock_migratetype(page,
2184 return 1UL << order;
2188 * Similar to split_page except the page is already free. As this is only
2189 * being used for migration, the migratetype of the block also changes.
2190 * As this is called with interrupts disabled, the caller is responsible
2191 * for calling arch_alloc_page() and kernel_map_page() after interrupts
2194 * Note: this is probably too low level an operation for use in drivers.
2195 * Please consult with lkml before using this in your driver.
2197 int split_free_page(struct page *page)
2202 order = page_order(page);
2204 nr_pages = __isolate_free_page(page, order);
2208 /* Split into individual pages */
2209 set_page_refcounted(page);
2210 split_page(page, order);
2215 * Allocate a page from the given zone. Use pcplists for order-0 allocations.
2218 struct page *buffered_rmqueue(struct zone *preferred_zone,
2219 struct zone *zone, unsigned int order,
2220 gfp_t gfp_flags, int alloc_flags, int migratetype)
2222 unsigned long flags;
2224 bool cold = ((gfp_flags & __GFP_COLD) != 0);
2226 if (likely(order == 0)) {
2227 struct per_cpu_pages *pcp;
2228 struct list_head *list;
2230 local_irq_save(flags);
2231 pcp = &this_cpu_ptr(zone->pageset)->pcp;
2232 list = &pcp->lists[migratetype];
2233 if (list_empty(list)) {
2234 pcp->count += rmqueue_bulk(zone, 0,
2237 if (unlikely(list_empty(list)))
2242 page = list_entry(list->prev, struct page, lru);
2244 page = list_entry(list->next, struct page, lru);
2246 list_del(&page->lru);
2249 if (unlikely(gfp_flags & __GFP_NOFAIL)) {
2251 * __GFP_NOFAIL is not to be used in new code.
2253 * All __GFP_NOFAIL callers should be fixed so that they
2254 * properly detect and handle allocation failures.
2256 * We most definitely don't want callers attempting to
2257 * allocate greater than order-1 page units with
2260 WARN_ON_ONCE(order > 1);
2262 spin_lock_irqsave(&zone->lock, flags);
2265 if (alloc_flags & ALLOC_HARDER) {
2266 page = __rmqueue_smallest(zone, order, MIGRATE_HIGHATOMIC);
2268 trace_mm_page_alloc_zone_locked(page, order, migratetype);
2271 page = __rmqueue(zone, order, migratetype, gfp_flags);
2272 spin_unlock(&zone->lock);
2275 __mod_zone_freepage_state(zone, -(1 << order),
2276 get_pcppage_migratetype(page));
2279 __mod_zone_page_state(zone, NR_ALLOC_BATCH, -(1 << order));
2280 if (atomic_long_read(&zone->vm_stat[NR_ALLOC_BATCH]) <= 0 &&
2281 !test_bit(ZONE_FAIR_DEPLETED, &zone->flags))
2282 set_bit(ZONE_FAIR_DEPLETED, &zone->flags);
2284 __count_zone_vm_events(PGALLOC, zone, 1 << order);
2285 zone_statistics(preferred_zone, zone, gfp_flags);
2286 local_irq_restore(flags);
2288 VM_BUG_ON_PAGE(bad_range(zone, page), page);
2292 local_irq_restore(flags);
2296 #ifdef CONFIG_FAIL_PAGE_ALLOC
2299 struct fault_attr attr;
2301 bool ignore_gfp_highmem;
2302 bool ignore_gfp_reclaim;
2304 } fail_page_alloc = {
2305 .attr = FAULT_ATTR_INITIALIZER,
2306 .ignore_gfp_reclaim = true,
2307 .ignore_gfp_highmem = true,
2311 static int __init setup_fail_page_alloc(char *str)
2313 return setup_fault_attr(&fail_page_alloc.attr, str);
2315 __setup("fail_page_alloc=", setup_fail_page_alloc);
2317 static bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
2319 if (order < fail_page_alloc.min_order)
2321 if (gfp_mask & __GFP_NOFAIL)
2323 if (fail_page_alloc.ignore_gfp_highmem && (gfp_mask & __GFP_HIGHMEM))
2325 if (fail_page_alloc.ignore_gfp_reclaim &&
2326 (gfp_mask & __GFP_DIRECT_RECLAIM))
2329 return should_fail(&fail_page_alloc.attr, 1 << order);
2332 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
2334 static int __init fail_page_alloc_debugfs(void)
2336 umode_t mode = S_IFREG | S_IRUSR | S_IWUSR;
2339 dir = fault_create_debugfs_attr("fail_page_alloc", NULL,
2340 &fail_page_alloc.attr);
2342 return PTR_ERR(dir);
2344 if (!debugfs_create_bool("ignore-gfp-wait", mode, dir,
2345 &fail_page_alloc.ignore_gfp_reclaim))
2347 if (!debugfs_create_bool("ignore-gfp-highmem", mode, dir,
2348 &fail_page_alloc.ignore_gfp_highmem))
2350 if (!debugfs_create_u32("min-order", mode, dir,
2351 &fail_page_alloc.min_order))
2356 debugfs_remove_recursive(dir);
2361 late_initcall(fail_page_alloc_debugfs);
2363 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
2365 #else /* CONFIG_FAIL_PAGE_ALLOC */
2367 static inline bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
2372 #endif /* CONFIG_FAIL_PAGE_ALLOC */
2375 * Return true if free base pages are above 'mark'. For high-order checks it
2376 * will return true of the order-0 watermark is reached and there is at least
2377 * one free page of a suitable size. Checking now avoids taking the zone lock
2378 * to check in the allocation paths if no pages are free.
2380 static bool __zone_watermark_ok(struct zone *z, unsigned int order,
2381 unsigned long mark, int classzone_idx, int alloc_flags,
2386 const int alloc_harder = (alloc_flags & ALLOC_HARDER);
2388 /* free_pages may go negative - that's OK */
2389 free_pages -= (1 << order) - 1;
2391 if (alloc_flags & ALLOC_HIGH)
2395 * If the caller does not have rights to ALLOC_HARDER then subtract
2396 * the high-atomic reserves. This will over-estimate the size of the
2397 * atomic reserve but it avoids a search.
2399 if (likely(!alloc_harder))
2400 free_pages -= z->nr_reserved_highatomic;
2405 /* If allocation can't use CMA areas don't use free CMA pages */
2406 if (!(alloc_flags & ALLOC_CMA))
2407 free_pages -= zone_page_state(z, NR_FREE_CMA_PAGES);
2411 * Check watermarks for an order-0 allocation request. If these
2412 * are not met, then a high-order request also cannot go ahead
2413 * even if a suitable page happened to be free.
2415 if (free_pages <= min + z->lowmem_reserve[classzone_idx])
2418 /* If this is an order-0 request then the watermark is fine */
2422 /* For a high-order request, check at least one suitable page is free */
2423 for (o = order; o < MAX_ORDER; o++) {
2424 struct free_area *area = &z->free_area[o];
2433 for (mt = 0; mt < MIGRATE_PCPTYPES; mt++) {
2434 if (!list_empty(&area->free_list[mt]))
2439 if ((alloc_flags & ALLOC_CMA) &&
2440 !list_empty(&area->free_list[MIGRATE_CMA])) {
2448 bool zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
2449 int classzone_idx, int alloc_flags)
2451 return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
2452 zone_page_state(z, NR_FREE_PAGES));
2455 bool zone_watermark_ok_safe(struct zone *z, unsigned int order,
2456 unsigned long mark, int classzone_idx)
2458 long free_pages = zone_page_state(z, NR_FREE_PAGES);
2460 if (z->percpu_drift_mark && free_pages < z->percpu_drift_mark)
2461 free_pages = zone_page_state_snapshot(z, NR_FREE_PAGES);
2463 return __zone_watermark_ok(z, order, mark, classzone_idx, 0,
2468 static bool zone_local(struct zone *local_zone, struct zone *zone)
2470 return local_zone->node == zone->node;
2473 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
2475 return node_distance(zone_to_nid(local_zone), zone_to_nid(zone)) <=
2478 #else /* CONFIG_NUMA */
2479 static bool zone_local(struct zone *local_zone, struct zone *zone)
2484 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
2488 #endif /* CONFIG_NUMA */
2490 static void reset_alloc_batches(struct zone *preferred_zone)
2492 struct zone *zone = preferred_zone->zone_pgdat->node_zones;
2495 mod_zone_page_state(zone, NR_ALLOC_BATCH,
2496 high_wmark_pages(zone) - low_wmark_pages(zone) -
2497 atomic_long_read(&zone->vm_stat[NR_ALLOC_BATCH]));
2498 clear_bit(ZONE_FAIR_DEPLETED, &zone->flags);
2499 } while (zone++ != preferred_zone);
2503 * get_page_from_freelist goes through the zonelist trying to allocate
2506 static struct page *
2507 get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags,
2508 const struct alloc_context *ac)
2510 struct zonelist *zonelist = ac->zonelist;
2512 struct page *page = NULL;
2514 int nr_fair_skipped = 0;
2515 bool zonelist_rescan;
2518 zonelist_rescan = false;
2521 * Scan zonelist, looking for a zone with enough free.
2522 * See also __cpuset_node_allowed() comment in kernel/cpuset.c.
2524 for_each_zone_zonelist_nodemask(zone, z, zonelist, ac->high_zoneidx,
2528 if (cpusets_enabled() &&
2529 (alloc_flags & ALLOC_CPUSET) &&
2530 !cpuset_zone_allowed(zone, gfp_mask))
2533 * Distribute pages in proportion to the individual
2534 * zone size to ensure fair page aging. The zone a
2535 * page was allocated in should have no effect on the
2536 * time the page has in memory before being reclaimed.
2538 if (alloc_flags & ALLOC_FAIR) {
2539 if (!zone_local(ac->preferred_zone, zone))
2541 if (test_bit(ZONE_FAIR_DEPLETED, &zone->flags)) {
2547 * When allocating a page cache page for writing, we
2548 * want to get it from a zone that is within its dirty
2549 * limit, such that no single zone holds more than its
2550 * proportional share of globally allowed dirty pages.
2551 * The dirty limits take into account the zone's
2552 * lowmem reserves and high watermark so that kswapd
2553 * should be able to balance it without having to
2554 * write pages from its LRU list.
2556 * This may look like it could increase pressure on
2557 * lower zones by failing allocations in higher zones
2558 * before they are full. But the pages that do spill
2559 * over are limited as the lower zones are protected
2560 * by this very same mechanism. It should not become
2561 * a practical burden to them.
2563 * XXX: For now, allow allocations to potentially
2564 * exceed the per-zone dirty limit in the slowpath
2565 * (spread_dirty_pages unset) before going into reclaim,
2566 * which is important when on a NUMA setup the allowed
2567 * zones are together not big enough to reach the
2568 * global limit. The proper fix for these situations
2569 * will require awareness of zones in the
2570 * dirty-throttling and the flusher threads.
2572 if (ac->spread_dirty_pages && !zone_dirty_ok(zone))
2575 mark = zone->watermark[alloc_flags & ALLOC_WMARK_MASK];
2576 if (!zone_watermark_ok(zone, order, mark,
2577 ac->classzone_idx, alloc_flags)) {
2580 /* Checked here to keep the fast path fast */
2581 BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK);
2582 if (alloc_flags & ALLOC_NO_WATERMARKS)
2585 if (zone_reclaim_mode == 0 ||
2586 !zone_allows_reclaim(ac->preferred_zone, zone))
2589 ret = zone_reclaim(zone, gfp_mask, order);
2591 case ZONE_RECLAIM_NOSCAN:
2594 case ZONE_RECLAIM_FULL:
2595 /* scanned but unreclaimable */
2598 /* did we reclaim enough */
2599 if (zone_watermark_ok(zone, order, mark,
2600 ac->classzone_idx, alloc_flags))
2608 page = buffered_rmqueue(ac->preferred_zone, zone, order,
2609 gfp_mask, alloc_flags, ac->migratetype);
2611 if (prep_new_page(page, order, gfp_mask, alloc_flags))
2615 * If this is a high-order atomic allocation then check
2616 * if the pageblock should be reserved for the future
2618 if (unlikely(order && (alloc_flags & ALLOC_HARDER)))
2619 reserve_highatomic_pageblock(page, zone, order);
2626 * The first pass makes sure allocations are spread fairly within the
2627 * local node. However, the local node might have free pages left
2628 * after the fairness batches are exhausted, and remote zones haven't
2629 * even been considered yet. Try once more without fairness, and
2630 * include remote zones now, before entering the slowpath and waking
2631 * kswapd: prefer spilling to a remote zone over swapping locally.
2633 if (alloc_flags & ALLOC_FAIR) {
2634 alloc_flags &= ~ALLOC_FAIR;
2635 if (nr_fair_skipped) {
2636 zonelist_rescan = true;
2637 reset_alloc_batches(ac->preferred_zone);
2639 if (nr_online_nodes > 1)
2640 zonelist_rescan = true;
2643 if (zonelist_rescan)
2650 * Large machines with many possible nodes should not always dump per-node
2651 * meminfo in irq context.
2653 static inline bool should_suppress_show_mem(void)
2658 ret = in_interrupt();
2663 static DEFINE_RATELIMIT_STATE(nopage_rs,
2664 DEFAULT_RATELIMIT_INTERVAL,
2665 DEFAULT_RATELIMIT_BURST);
2667 void warn_alloc_failed(gfp_t gfp_mask, unsigned int order, const char *fmt, ...)
2669 unsigned int filter = SHOW_MEM_FILTER_NODES;
2671 if ((gfp_mask & __GFP_NOWARN) || !__ratelimit(&nopage_rs) ||
2672 debug_guardpage_minorder() > 0)
2676 * This documents exceptions given to allocations in certain
2677 * contexts that are allowed to allocate outside current's set
2680 if (!(gfp_mask & __GFP_NOMEMALLOC))
2681 if (test_thread_flag(TIF_MEMDIE) ||
2682 (current->flags & (PF_MEMALLOC | PF_EXITING)))
2683 filter &= ~SHOW_MEM_FILTER_NODES;
2684 if (in_interrupt() || !(gfp_mask & __GFP_DIRECT_RECLAIM))
2685 filter &= ~SHOW_MEM_FILTER_NODES;
2688 struct va_format vaf;
2691 va_start(args, fmt);
2696 pr_warn("%pV", &vaf);
2701 pr_warn("%s: page allocation failure: order:%u, mode:0x%x\n",
2702 current->comm, order, gfp_mask);
2705 if (!should_suppress_show_mem())
2709 static inline struct page *
2710 __alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order,
2711 const struct alloc_context *ac, unsigned long *did_some_progress)
2713 struct oom_control oc = {
2714 .zonelist = ac->zonelist,
2715 .nodemask = ac->nodemask,
2716 .gfp_mask = gfp_mask,
2721 *did_some_progress = 0;
2724 * Acquire the oom lock. If that fails, somebody else is
2725 * making progress for us.
2727 if (!mutex_trylock(&oom_lock)) {
2728 *did_some_progress = 1;
2729 schedule_timeout_uninterruptible(1);
2734 * Go through the zonelist yet one more time, keep very high watermark
2735 * here, this is only to catch a parallel oom killing, we must fail if
2736 * we're still under heavy pressure.
2738 page = get_page_from_freelist(gfp_mask | __GFP_HARDWALL, order,
2739 ALLOC_WMARK_HIGH|ALLOC_CPUSET, ac);
2743 if (!(gfp_mask & __GFP_NOFAIL)) {
2744 /* Coredumps can quickly deplete all memory reserves */
2745 if (current->flags & PF_DUMPCORE)
2747 /* The OOM killer will not help higher order allocs */
2748 if (order > PAGE_ALLOC_COSTLY_ORDER)
2750 /* The OOM killer does not needlessly kill tasks for lowmem */
2751 if (ac->high_zoneidx < ZONE_NORMAL)
2753 /* The OOM killer does not compensate for IO-less reclaim */
2754 if (!(gfp_mask & __GFP_FS)) {
2756 * XXX: Page reclaim didn't yield anything,
2757 * and the OOM killer can't be invoked, but
2758 * keep looping as per tradition.
2760 *did_some_progress = 1;
2763 if (pm_suspended_storage())
2765 /* The OOM killer may not free memory on a specific node */
2766 if (gfp_mask & __GFP_THISNODE)
2769 /* Exhausted what can be done so it's blamo time */
2770 if (out_of_memory(&oc) || WARN_ON_ONCE(gfp_mask & __GFP_NOFAIL))
2771 *did_some_progress = 1;
2773 mutex_unlock(&oom_lock);
2777 #ifdef CONFIG_COMPACTION
2778 /* Try memory compaction for high-order allocations before reclaim */
2779 static struct page *
2780 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
2781 int alloc_flags, const struct alloc_context *ac,
2782 enum migrate_mode mode, int *contended_compaction,
2783 bool *deferred_compaction)
2785 unsigned long compact_result;
2791 current->flags |= PF_MEMALLOC;
2792 compact_result = try_to_compact_pages(gfp_mask, order, alloc_flags, ac,
2793 mode, contended_compaction);
2794 current->flags &= ~PF_MEMALLOC;
2796 switch (compact_result) {
2797 case COMPACT_DEFERRED:
2798 *deferred_compaction = true;
2800 case COMPACT_SKIPPED:
2807 * At least in one zone compaction wasn't deferred or skipped, so let's
2808 * count a compaction stall
2810 count_vm_event(COMPACTSTALL);
2812 page = get_page_from_freelist(gfp_mask, order,
2813 alloc_flags & ~ALLOC_NO_WATERMARKS, ac);
2816 struct zone *zone = page_zone(page);
2818 zone->compact_blockskip_flush = false;
2819 compaction_defer_reset(zone, order, true);
2820 count_vm_event(COMPACTSUCCESS);
2825 * It's bad if compaction run occurs and fails. The most likely reason
2826 * is that pages exist, but not enough to satisfy watermarks.
2828 count_vm_event(COMPACTFAIL);
2835 static inline struct page *
2836 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
2837 int alloc_flags, const struct alloc_context *ac,
2838 enum migrate_mode mode, int *contended_compaction,
2839 bool *deferred_compaction)
2843 #endif /* CONFIG_COMPACTION */
2845 /* Perform direct synchronous page reclaim */
2847 __perform_reclaim(gfp_t gfp_mask, unsigned int order,
2848 const struct alloc_context *ac)
2850 struct reclaim_state reclaim_state;
2855 /* We now go into synchronous reclaim */
2856 cpuset_memory_pressure_bump();
2857 current->flags |= PF_MEMALLOC;
2858 lockdep_set_current_reclaim_state(gfp_mask);
2859 reclaim_state.reclaimed_slab = 0;
2860 current->reclaim_state = &reclaim_state;
2862 progress = try_to_free_pages(ac->zonelist, order, gfp_mask,
2865 current->reclaim_state = NULL;
2866 lockdep_clear_current_reclaim_state();
2867 current->flags &= ~PF_MEMALLOC;
2874 /* The really slow allocator path where we enter direct reclaim */
2875 static inline struct page *
2876 __alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order,
2877 int alloc_flags, const struct alloc_context *ac,
2878 unsigned long *did_some_progress)
2880 struct page *page = NULL;
2881 bool drained = false;
2883 *did_some_progress = __perform_reclaim(gfp_mask, order, ac);
2884 if (unlikely(!(*did_some_progress)))
2888 page = get_page_from_freelist(gfp_mask, order,
2889 alloc_flags & ~ALLOC_NO_WATERMARKS, ac);
2892 * If an allocation failed after direct reclaim, it could be because
2893 * pages are pinned on the per-cpu lists or in high alloc reserves.
2894 * Shrink them them and try again
2896 if (!page && !drained) {
2897 unreserve_highatomic_pageblock(ac);
2898 drain_all_pages(NULL);
2907 * This is called in the allocator slow-path if the allocation request is of
2908 * sufficient urgency to ignore watermarks and take other desperate measures
2910 static inline struct page *
2911 __alloc_pages_high_priority(gfp_t gfp_mask, unsigned int order,
2912 const struct alloc_context *ac)
2917 page = get_page_from_freelist(gfp_mask, order,
2918 ALLOC_NO_WATERMARKS, ac);
2920 if (!page && gfp_mask & __GFP_NOFAIL)
2921 wait_iff_congested(ac->preferred_zone, BLK_RW_ASYNC,
2923 } while (!page && (gfp_mask & __GFP_NOFAIL));
2928 static void wake_all_kswapds(unsigned int order, const struct alloc_context *ac)
2933 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
2934 ac->high_zoneidx, ac->nodemask)
2935 wakeup_kswapd(zone, order, zone_idx(ac->preferred_zone));
2939 gfp_to_alloc_flags(gfp_t gfp_mask)
2941 int alloc_flags = ALLOC_WMARK_MIN | ALLOC_CPUSET;
2943 /* __GFP_HIGH is assumed to be the same as ALLOC_HIGH to save a branch. */
2944 BUILD_BUG_ON(__GFP_HIGH != (__force gfp_t) ALLOC_HIGH);
2947 * The caller may dip into page reserves a bit more if the caller
2948 * cannot run direct reclaim, or if the caller has realtime scheduling
2949 * policy or is asking for __GFP_HIGH memory. GFP_ATOMIC requests will
2950 * set both ALLOC_HARDER (__GFP_ATOMIC) and ALLOC_HIGH (__GFP_HIGH).
2952 alloc_flags |= (__force int) (gfp_mask & __GFP_HIGH);
2954 if (gfp_mask & __GFP_ATOMIC) {
2956 * Not worth trying to allocate harder for __GFP_NOMEMALLOC even
2957 * if it can't schedule.
2959 if (!(gfp_mask & __GFP_NOMEMALLOC))
2960 alloc_flags |= ALLOC_HARDER;
2962 * Ignore cpuset mems for GFP_ATOMIC rather than fail, see the
2963 * comment for __cpuset_node_allowed().
2965 alloc_flags &= ~ALLOC_CPUSET;
2966 } else if (unlikely(rt_task(current)) && !in_interrupt())
2967 alloc_flags |= ALLOC_HARDER;
2969 if (likely(!(gfp_mask & __GFP_NOMEMALLOC))) {
2970 if (gfp_mask & __GFP_MEMALLOC)
2971 alloc_flags |= ALLOC_NO_WATERMARKS;
2972 else if (in_serving_softirq() && (current->flags & PF_MEMALLOC))
2973 alloc_flags |= ALLOC_NO_WATERMARKS;
2974 else if (!in_interrupt() &&
2975 ((current->flags & PF_MEMALLOC) ||
2976 unlikely(test_thread_flag(TIF_MEMDIE))))
2977 alloc_flags |= ALLOC_NO_WATERMARKS;
2980 if (gfpflags_to_migratetype(gfp_mask) == MIGRATE_MOVABLE)
2981 alloc_flags |= ALLOC_CMA;
2986 bool gfp_pfmemalloc_allowed(gfp_t gfp_mask)
2988 return !!(gfp_to_alloc_flags(gfp_mask) & ALLOC_NO_WATERMARKS);
2991 static inline bool is_thp_gfp_mask(gfp_t gfp_mask)
2993 return (gfp_mask & (GFP_TRANSHUGE | __GFP_KSWAPD_RECLAIM)) == GFP_TRANSHUGE;
2996 static inline struct page *
2997 __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order,
2998 struct alloc_context *ac)
3000 bool can_direct_reclaim = gfp_mask & __GFP_DIRECT_RECLAIM;
3001 struct page *page = NULL;
3003 unsigned long pages_reclaimed = 0;
3004 unsigned long did_some_progress;
3005 enum migrate_mode migration_mode = MIGRATE_ASYNC;
3006 bool deferred_compaction = false;
3007 int contended_compaction = COMPACT_CONTENDED_NONE;
3010 * In the slowpath, we sanity check order to avoid ever trying to
3011 * reclaim >= MAX_ORDER areas which will never succeed. Callers may
3012 * be using allocators in order of preference for an area that is
3015 if (order >= MAX_ORDER) {
3016 WARN_ON_ONCE(!(gfp_mask & __GFP_NOWARN));
3021 * We also sanity check to catch abuse of atomic reserves being used by
3022 * callers that are not in atomic context.
3024 if (WARN_ON_ONCE((gfp_mask & (__GFP_ATOMIC|__GFP_DIRECT_RECLAIM)) ==
3025 (__GFP_ATOMIC|__GFP_DIRECT_RECLAIM)))
3026 gfp_mask &= ~__GFP_ATOMIC;
3029 * If this allocation cannot block and it is for a specific node, then
3030 * fail early. There's no need to wakeup kswapd or retry for a
3031 * speculative node-specific allocation.
3033 if (IS_ENABLED(CONFIG_NUMA) && (gfp_mask & __GFP_THISNODE) && !can_direct_reclaim)
3037 if (gfp_mask & __GFP_KSWAPD_RECLAIM)
3038 wake_all_kswapds(order, ac);
3041 * OK, we're below the kswapd watermark and have kicked background
3042 * reclaim. Now things get more complex, so set up alloc_flags according
3043 * to how we want to proceed.
3045 alloc_flags = gfp_to_alloc_flags(gfp_mask);
3048 * Find the true preferred zone if the allocation is unconstrained by
3051 if (!(alloc_flags & ALLOC_CPUSET) && !ac->nodemask) {
3052 struct zoneref *preferred_zoneref;
3053 preferred_zoneref = first_zones_zonelist(ac->zonelist,
3054 ac->high_zoneidx, NULL, &ac->preferred_zone);
3055 ac->classzone_idx = zonelist_zone_idx(preferred_zoneref);
3058 /* This is the last chance, in general, before the goto nopage. */
3059 page = get_page_from_freelist(gfp_mask, order,
3060 alloc_flags & ~ALLOC_NO_WATERMARKS, ac);
3064 /* Allocate without watermarks if the context allows */
3065 if (alloc_flags & ALLOC_NO_WATERMARKS) {
3067 * Ignore mempolicies if ALLOC_NO_WATERMARKS on the grounds
3068 * the allocation is high priority and these type of
3069 * allocations are system rather than user orientated
3071 ac->zonelist = node_zonelist(numa_node_id(), gfp_mask);
3073 page = __alloc_pages_high_priority(gfp_mask, order, ac);
3080 /* Caller is not willing to reclaim, we can't balance anything */
3081 if (!can_direct_reclaim) {
3083 * All existing users of the deprecated __GFP_NOFAIL are
3084 * blockable, so warn of any new users that actually allow this
3085 * type of allocation to fail.
3087 WARN_ON_ONCE(gfp_mask & __GFP_NOFAIL);
3091 /* Avoid recursion of direct reclaim */
3092 if (current->flags & PF_MEMALLOC)
3095 /* Avoid allocations with no watermarks from looping endlessly */
3096 if (test_thread_flag(TIF_MEMDIE) && !(gfp_mask & __GFP_NOFAIL))
3100 * Try direct compaction. The first pass is asynchronous. Subsequent
3101 * attempts after direct reclaim are synchronous
3103 page = __alloc_pages_direct_compact(gfp_mask, order, alloc_flags, ac,
3105 &contended_compaction,
3106 &deferred_compaction);
3110 /* Checks for THP-specific high-order allocations */
3111 if (is_thp_gfp_mask(gfp_mask)) {
3113 * If compaction is deferred for high-order allocations, it is
3114 * because sync compaction recently failed. If this is the case
3115 * and the caller requested a THP allocation, we do not want
3116 * to heavily disrupt the system, so we fail the allocation
3117 * instead of entering direct reclaim.
3119 if (deferred_compaction)
3123 * In all zones where compaction was attempted (and not
3124 * deferred or skipped), lock contention has been detected.
3125 * For THP allocation we do not want to disrupt the others
3126 * so we fallback to base pages instead.
3128 if (contended_compaction == COMPACT_CONTENDED_LOCK)
3132 * If compaction was aborted due to need_resched(), we do not
3133 * want to further increase allocation latency, unless it is
3134 * khugepaged trying to collapse.
3136 if (contended_compaction == COMPACT_CONTENDED_SCHED
3137 && !(current->flags & PF_KTHREAD))
3142 * It can become very expensive to allocate transparent hugepages at
3143 * fault, so use asynchronous memory compaction for THP unless it is
3144 * khugepaged trying to collapse.
3146 if (!is_thp_gfp_mask(gfp_mask) || (current->flags & PF_KTHREAD))
3147 migration_mode = MIGRATE_SYNC_LIGHT;
3149 /* Try direct reclaim and then allocating */
3150 page = __alloc_pages_direct_reclaim(gfp_mask, order, alloc_flags, ac,
3151 &did_some_progress);
3155 /* Do not loop if specifically requested */
3156 if (gfp_mask & __GFP_NORETRY)
3159 /* Keep reclaiming pages as long as there is reasonable progress */
3160 pages_reclaimed += did_some_progress;
3161 if ((did_some_progress && order <= PAGE_ALLOC_COSTLY_ORDER) ||
3162 ((gfp_mask & __GFP_REPEAT) && pages_reclaimed < (1 << order))) {
3163 /* Wait for some write requests to complete then retry */
3164 wait_iff_congested(ac->preferred_zone, BLK_RW_ASYNC, HZ/50);
3168 /* Reclaim has failed us, start killing things */
3169 page = __alloc_pages_may_oom(gfp_mask, order, ac, &did_some_progress);
3173 /* Retry as long as the OOM killer is making progress */
3174 if (did_some_progress)
3179 * High-order allocations do not necessarily loop after
3180 * direct reclaim and reclaim/compaction depends on compaction
3181 * being called after reclaim so call directly if necessary
3183 page = __alloc_pages_direct_compact(gfp_mask, order, alloc_flags,
3185 &contended_compaction,
3186 &deferred_compaction);
3190 warn_alloc_failed(gfp_mask, order, NULL);
3196 * This is the 'heart' of the zoned buddy allocator.
3199 __alloc_pages_nodemask(gfp_t gfp_mask, unsigned int order,
3200 struct zonelist *zonelist, nodemask_t *nodemask)
3202 struct zoneref *preferred_zoneref;
3203 struct page *page = NULL;
3204 unsigned int cpuset_mems_cookie;
3205 int alloc_flags = ALLOC_WMARK_LOW|ALLOC_CPUSET|ALLOC_FAIR;
3206 gfp_t alloc_mask; /* The gfp_t that was actually used for allocation */
3207 struct alloc_context ac = {
3208 .high_zoneidx = gfp_zone(gfp_mask),
3209 .nodemask = nodemask,
3210 .migratetype = gfpflags_to_migratetype(gfp_mask),
3213 gfp_mask &= gfp_allowed_mask;
3215 lockdep_trace_alloc(gfp_mask);
3217 might_sleep_if(gfp_mask & __GFP_DIRECT_RECLAIM);
3219 if (should_fail_alloc_page(gfp_mask, order))
3223 * Check the zones suitable for the gfp_mask contain at least one
3224 * valid zone. It's possible to have an empty zonelist as a result
3225 * of __GFP_THISNODE and a memoryless node
3227 if (unlikely(!zonelist->_zonerefs->zone))
3230 if (IS_ENABLED(CONFIG_CMA) && ac.migratetype == MIGRATE_MOVABLE)
3231 alloc_flags |= ALLOC_CMA;
3234 cpuset_mems_cookie = read_mems_allowed_begin();
3236 /* We set it here, as __alloc_pages_slowpath might have changed it */
3237 ac.zonelist = zonelist;
3239 /* Dirty zone balancing only done in the fast path */
3240 ac.spread_dirty_pages = (gfp_mask & __GFP_WRITE);
3242 /* The preferred zone is used for statistics later */
3243 preferred_zoneref = first_zones_zonelist(ac.zonelist, ac.high_zoneidx,
3244 ac.nodemask ? : &cpuset_current_mems_allowed,
3245 &ac.preferred_zone);
3246 if (!ac.preferred_zone)
3248 ac.classzone_idx = zonelist_zone_idx(preferred_zoneref);
3250 /* First allocation attempt */
3251 alloc_mask = gfp_mask|__GFP_HARDWALL;
3252 page = get_page_from_freelist(alloc_mask, order, alloc_flags, &ac);
3253 if (unlikely(!page)) {
3255 * Runtime PM, block IO and its error handling path
3256 * can deadlock because I/O on the device might not
3259 alloc_mask = memalloc_noio_flags(gfp_mask);
3260 ac.spread_dirty_pages = false;
3262 page = __alloc_pages_slowpath(alloc_mask, order, &ac);
3265 if (kmemcheck_enabled && page)
3266 kmemcheck_pagealloc_alloc(page, order, gfp_mask);
3268 trace_mm_page_alloc(page, order, alloc_mask, ac.migratetype);
3272 * When updating a task's mems_allowed, it is possible to race with
3273 * parallel threads in such a way that an allocation can fail while
3274 * the mask is being updated. If a page allocation is about to fail,
3275 * check if the cpuset changed during allocation and if so, retry.
3277 if (unlikely(!page && read_mems_allowed_retry(cpuset_mems_cookie)))
3282 EXPORT_SYMBOL(__alloc_pages_nodemask);
3285 * Common helper functions.
3287 unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order)
3292 * __get_free_pages() returns a 32-bit address, which cannot represent
3295 VM_BUG_ON((gfp_mask & __GFP_HIGHMEM) != 0);
3297 page = alloc_pages(gfp_mask, order);
3300 return (unsigned long) page_address(page);
3302 EXPORT_SYMBOL(__get_free_pages);
3304 unsigned long get_zeroed_page(gfp_t gfp_mask)
3306 return __get_free_pages(gfp_mask | __GFP_ZERO, 0);
3308 EXPORT_SYMBOL(get_zeroed_page);
3310 void __free_pages(struct page *page, unsigned int order)
3312 if (put_page_testzero(page)) {
3314 free_hot_cold_page(page, false);
3316 __free_pages_ok(page, order);
3320 EXPORT_SYMBOL(__free_pages);
3322 void free_pages(unsigned long addr, unsigned int order)
3325 VM_BUG_ON(!virt_addr_valid((void *)addr));
3326 __free_pages(virt_to_page((void *)addr), order);
3330 EXPORT_SYMBOL(free_pages);
3334 * An arbitrary-length arbitrary-offset area of memory which resides
3335 * within a 0 or higher order page. Multiple fragments within that page
3336 * are individually refcounted, in the page's reference counter.
3338 * The page_frag functions below provide a simple allocation framework for
3339 * page fragments. This is used by the network stack and network device
3340 * drivers to provide a backing region of memory for use as either an
3341 * sk_buff->head, or to be used in the "frags" portion of skb_shared_info.
3343 static struct page *__page_frag_refill(struct page_frag_cache *nc,
3346 struct page *page = NULL;
3347 gfp_t gfp = gfp_mask;
3349 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
3350 gfp_mask |= __GFP_COMP | __GFP_NOWARN | __GFP_NORETRY |
3352 page = alloc_pages_node(NUMA_NO_NODE, gfp_mask,
3353 PAGE_FRAG_CACHE_MAX_ORDER);
3354 nc->size = page ? PAGE_FRAG_CACHE_MAX_SIZE : PAGE_SIZE;
3356 if (unlikely(!page))
3357 page = alloc_pages_node(NUMA_NO_NODE, gfp, 0);
3359 nc->va = page ? page_address(page) : NULL;
3364 void *__alloc_page_frag(struct page_frag_cache *nc,
3365 unsigned int fragsz, gfp_t gfp_mask)
3367 unsigned int size = PAGE_SIZE;
3371 if (unlikely(!nc->va)) {
3373 page = __page_frag_refill(nc, gfp_mask);
3377 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
3378 /* if size can vary use size else just use PAGE_SIZE */
3381 /* Even if we own the page, we do not use atomic_set().
3382 * This would break get_page_unless_zero() users.
3384 atomic_add(size - 1, &page->_count);
3386 /* reset page count bias and offset to start of new frag */
3387 nc->pfmemalloc = page_is_pfmemalloc(page);
3388 nc->pagecnt_bias = size;
3392 offset = nc->offset - fragsz;
3393 if (unlikely(offset < 0)) {
3394 page = virt_to_page(nc->va);
3396 if (!atomic_sub_and_test(nc->pagecnt_bias, &page->_count))
3399 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
3400 /* if size can vary use size else just use PAGE_SIZE */
3403 /* OK, page count is 0, we can safely set it */
3404 atomic_set(&page->_count, size);
3406 /* reset page count bias and offset to start of new frag */
3407 nc->pagecnt_bias = size;
3408 offset = size - fragsz;
3412 nc->offset = offset;
3414 return nc->va + offset;
3416 EXPORT_SYMBOL(__alloc_page_frag);
3419 * Frees a page fragment allocated out of either a compound or order 0 page.
3421 void __free_page_frag(void *addr)
3423 struct page *page = virt_to_head_page(addr);
3425 if (unlikely(put_page_testzero(page)))
3426 __free_pages_ok(page, compound_order(page));
3428 EXPORT_SYMBOL(__free_page_frag);
3431 * alloc_kmem_pages charges newly allocated pages to the kmem resource counter
3432 * of the current memory cgroup.
3434 * It should be used when the caller would like to use kmalloc, but since the
3435 * allocation is large, it has to fall back to the page allocator.
3437 struct page *alloc_kmem_pages(gfp_t gfp_mask, unsigned int order)
3441 page = alloc_pages(gfp_mask, order);
3442 if (page && memcg_kmem_charge(page, gfp_mask, order) != 0) {
3443 __free_pages(page, order);
3449 struct page *alloc_kmem_pages_node(int nid, gfp_t gfp_mask, unsigned int order)
3453 page = alloc_pages_node(nid, gfp_mask, order);
3454 if (page && memcg_kmem_charge(page, gfp_mask, order) != 0) {
3455 __free_pages(page, order);
3462 * __free_kmem_pages and free_kmem_pages will free pages allocated with
3465 void __free_kmem_pages(struct page *page, unsigned int order)
3467 memcg_kmem_uncharge(page, order);
3468 __free_pages(page, order);
3471 void free_kmem_pages(unsigned long addr, unsigned int order)
3474 VM_BUG_ON(!virt_addr_valid((void *)addr));
3475 __free_kmem_pages(virt_to_page((void *)addr), order);
3479 static void *make_alloc_exact(unsigned long addr, unsigned int order,
3483 unsigned long alloc_end = addr + (PAGE_SIZE << order);
3484 unsigned long used = addr + PAGE_ALIGN(size);
3486 split_page(virt_to_page((void *)addr), order);
3487 while (used < alloc_end) {
3492 return (void *)addr;
3496 * alloc_pages_exact - allocate an exact number physically-contiguous pages.
3497 * @size: the number of bytes to allocate
3498 * @gfp_mask: GFP flags for the allocation
3500 * This function is similar to alloc_pages(), except that it allocates the
3501 * minimum number of pages to satisfy the request. alloc_pages() can only
3502 * allocate memory in power-of-two pages.
3504 * This function is also limited by MAX_ORDER.
3506 * Memory allocated by this function must be released by free_pages_exact().
3508 void *alloc_pages_exact(size_t size, gfp_t gfp_mask)
3510 unsigned int order = get_order(size);
3513 addr = __get_free_pages(gfp_mask, order);
3514 return make_alloc_exact(addr, order, size);
3516 EXPORT_SYMBOL(alloc_pages_exact);
3519 * alloc_pages_exact_nid - allocate an exact number of physically-contiguous
3521 * @nid: the preferred node ID where memory should be allocated
3522 * @size: the number of bytes to allocate
3523 * @gfp_mask: GFP flags for the allocation
3525 * Like alloc_pages_exact(), but try to allocate on node nid first before falling
3528 void * __meminit alloc_pages_exact_nid(int nid, size_t size, gfp_t gfp_mask)
3530 unsigned int order = get_order(size);
3531 struct page *p = alloc_pages_node(nid, gfp_mask, order);
3534 return make_alloc_exact((unsigned long)page_address(p), order, size);
3538 * free_pages_exact - release memory allocated via alloc_pages_exact()
3539 * @virt: the value returned by alloc_pages_exact.
3540 * @size: size of allocation, same value as passed to alloc_pages_exact().
3542 * Release the memory allocated by a previous call to alloc_pages_exact.
3544 void free_pages_exact(void *virt, size_t size)
3546 unsigned long addr = (unsigned long)virt;
3547 unsigned long end = addr + PAGE_ALIGN(size);
3549 while (addr < end) {
3554 EXPORT_SYMBOL(free_pages_exact);
3557 * nr_free_zone_pages - count number of pages beyond high watermark
3558 * @offset: The zone index of the highest zone
3560 * nr_free_zone_pages() counts the number of counts pages which are beyond the
3561 * high watermark within all zones at or below a given zone index. For each
3562 * zone, the number of pages is calculated as:
3563 * managed_pages - high_pages
3565 static unsigned long nr_free_zone_pages(int offset)
3570 /* Just pick one node, since fallback list is circular */
3571 unsigned long sum = 0;
3573 struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL);
3575 for_each_zone_zonelist(zone, z, zonelist, offset) {
3576 unsigned long size = zone->managed_pages;
3577 unsigned long high = high_wmark_pages(zone);
3586 * nr_free_buffer_pages - count number of pages beyond high watermark
3588 * nr_free_buffer_pages() counts the number of pages which are beyond the high
3589 * watermark within ZONE_DMA and ZONE_NORMAL.
3591 unsigned long nr_free_buffer_pages(void)
3593 return nr_free_zone_pages(gfp_zone(GFP_USER));
3595 EXPORT_SYMBOL_GPL(nr_free_buffer_pages);
3598 * nr_free_pagecache_pages - count number of pages beyond high watermark
3600 * nr_free_pagecache_pages() counts the number of pages which are beyond the
3601 * high watermark within all zones.
3603 unsigned long nr_free_pagecache_pages(void)
3605 return nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE));
3608 static inline void show_node(struct zone *zone)
3610 if (IS_ENABLED(CONFIG_NUMA))
3611 printk("Node %d ", zone_to_nid(zone));
3614 void si_meminfo(struct sysinfo *val)
3616 val->totalram = totalram_pages;
3617 val->sharedram = global_page_state(NR_SHMEM);
3618 val->freeram = global_page_state(NR_FREE_PAGES);
3619 val->bufferram = nr_blockdev_pages();
3620 val->totalhigh = totalhigh_pages;
3621 val->freehigh = nr_free_highpages();
3622 val->mem_unit = PAGE_SIZE;
3625 EXPORT_SYMBOL(si_meminfo);
3628 void si_meminfo_node(struct sysinfo *val, int nid)
3630 int zone_type; /* needs to be signed */
3631 unsigned long managed_pages = 0;
3632 pg_data_t *pgdat = NODE_DATA(nid);
3634 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++)
3635 managed_pages += pgdat->node_zones[zone_type].managed_pages;
3636 val->totalram = managed_pages;
3637 val->sharedram = node_page_state(nid, NR_SHMEM);
3638 val->freeram = node_page_state(nid, NR_FREE_PAGES);
3639 #ifdef CONFIG_HIGHMEM
3640 val->totalhigh = pgdat->node_zones[ZONE_HIGHMEM].managed_pages;
3641 val->freehigh = zone_page_state(&pgdat->node_zones[ZONE_HIGHMEM],
3647 val->mem_unit = PAGE_SIZE;
3652 * Determine whether the node should be displayed or not, depending on whether
3653 * SHOW_MEM_FILTER_NODES was passed to show_free_areas().
3655 bool skip_free_areas_node(unsigned int flags, int nid)
3658 unsigned int cpuset_mems_cookie;
3660 if (!(flags & SHOW_MEM_FILTER_NODES))
3664 cpuset_mems_cookie = read_mems_allowed_begin();
3665 ret = !node_isset(nid, cpuset_current_mems_allowed);
3666 } while (read_mems_allowed_retry(cpuset_mems_cookie));
3671 #define K(x) ((x) << (PAGE_SHIFT-10))
3673 static void show_migration_types(unsigned char type)
3675 static const char types[MIGRATE_TYPES] = {
3676 [MIGRATE_UNMOVABLE] = 'U',
3677 [MIGRATE_MOVABLE] = 'M',
3678 [MIGRATE_RECLAIMABLE] = 'E',
3679 [MIGRATE_HIGHATOMIC] = 'H',
3681 [MIGRATE_CMA] = 'C',
3683 #ifdef CONFIG_MEMORY_ISOLATION
3684 [MIGRATE_ISOLATE] = 'I',
3687 char tmp[MIGRATE_TYPES + 1];
3691 for (i = 0; i < MIGRATE_TYPES; i++) {
3692 if (type & (1 << i))
3697 printk("(%s) ", tmp);
3701 * Show free area list (used inside shift_scroll-lock stuff)
3702 * We also calculate the percentage fragmentation. We do this by counting the
3703 * memory on each free list with the exception of the first item on the list.
3706 * SHOW_MEM_FILTER_NODES: suppress nodes that are not allowed by current's
3709 void show_free_areas(unsigned int filter)
3711 unsigned long free_pcp = 0;
3715 for_each_populated_zone(zone) {
3716 if (skip_free_areas_node(filter, zone_to_nid(zone)))
3719 for_each_online_cpu(cpu)
3720 free_pcp += per_cpu_ptr(zone->pageset, cpu)->pcp.count;
3723 printk("active_anon:%lu inactive_anon:%lu isolated_anon:%lu\n"
3724 " active_file:%lu inactive_file:%lu isolated_file:%lu\n"
3725 " unevictable:%lu dirty:%lu writeback:%lu unstable:%lu\n"
3726 " slab_reclaimable:%lu slab_unreclaimable:%lu\n"
3727 " mapped:%lu shmem:%lu pagetables:%lu bounce:%lu\n"
3728 " free:%lu free_pcp:%lu free_cma:%lu\n",
3729 global_page_state(NR_ACTIVE_ANON),
3730 global_page_state(NR_INACTIVE_ANON),
3731 global_page_state(NR_ISOLATED_ANON),
3732 global_page_state(NR_ACTIVE_FILE),
3733 global_page_state(NR_INACTIVE_FILE),
3734 global_page_state(NR_ISOLATED_FILE),
3735 global_page_state(NR_UNEVICTABLE),
3736 global_page_state(NR_FILE_DIRTY),
3737 global_page_state(NR_WRITEBACK),
3738 global_page_state(NR_UNSTABLE_NFS),
3739 global_page_state(NR_SLAB_RECLAIMABLE),
3740 global_page_state(NR_SLAB_UNRECLAIMABLE),
3741 global_page_state(NR_FILE_MAPPED),
3742 global_page_state(NR_SHMEM),
3743 global_page_state(NR_PAGETABLE),
3744 global_page_state(NR_BOUNCE),
3745 global_page_state(NR_FREE_PAGES),
3747 global_page_state(NR_FREE_CMA_PAGES));
3749 for_each_populated_zone(zone) {
3752 if (skip_free_areas_node(filter, zone_to_nid(zone)))
3756 for_each_online_cpu(cpu)
3757 free_pcp += per_cpu_ptr(zone->pageset, cpu)->pcp.count;
3765 " active_anon:%lukB"
3766 " inactive_anon:%lukB"
3767 " active_file:%lukB"
3768 " inactive_file:%lukB"
3769 " unevictable:%lukB"
3770 " isolated(anon):%lukB"
3771 " isolated(file):%lukB"
3779 " slab_reclaimable:%lukB"
3780 " slab_unreclaimable:%lukB"
3781 " kernel_stack:%lukB"
3788 " writeback_tmp:%lukB"
3789 " pages_scanned:%lu"
3790 " all_unreclaimable? %s"
3793 K(zone_page_state(zone, NR_FREE_PAGES)),
3794 K(min_wmark_pages(zone)),
3795 K(low_wmark_pages(zone)),
3796 K(high_wmark_pages(zone)),
3797 K(zone_page_state(zone, NR_ACTIVE_ANON)),
3798 K(zone_page_state(zone, NR_INACTIVE_ANON)),
3799 K(zone_page_state(zone, NR_ACTIVE_FILE)),
3800 K(zone_page_state(zone, NR_INACTIVE_FILE)),
3801 K(zone_page_state(zone, NR_UNEVICTABLE)),
3802 K(zone_page_state(zone, NR_ISOLATED_ANON)),
3803 K(zone_page_state(zone, NR_ISOLATED_FILE)),
3804 K(zone->present_pages),
3805 K(zone->managed_pages),
3806 K(zone_page_state(zone, NR_MLOCK)),
3807 K(zone_page_state(zone, NR_FILE_DIRTY)),
3808 K(zone_page_state(zone, NR_WRITEBACK)),
3809 K(zone_page_state(zone, NR_FILE_MAPPED)),
3810 K(zone_page_state(zone, NR_SHMEM)),
3811 K(zone_page_state(zone, NR_SLAB_RECLAIMABLE)),
3812 K(zone_page_state(zone, NR_SLAB_UNRECLAIMABLE)),
3813 zone_page_state(zone, NR_KERNEL_STACK) *
3815 K(zone_page_state(zone, NR_PAGETABLE)),
3816 K(zone_page_state(zone, NR_UNSTABLE_NFS)),
3817 K(zone_page_state(zone, NR_BOUNCE)),
3819 K(this_cpu_read(zone->pageset->pcp.count)),
3820 K(zone_page_state(zone, NR_FREE_CMA_PAGES)),
3821 K(zone_page_state(zone, NR_WRITEBACK_TEMP)),
3822 K(zone_page_state(zone, NR_PAGES_SCANNED)),
3823 (!zone_reclaimable(zone) ? "yes" : "no")
3825 printk("lowmem_reserve[]:");
3826 for (i = 0; i < MAX_NR_ZONES; i++)
3827 printk(" %ld", zone->lowmem_reserve[i]);
3831 for_each_populated_zone(zone) {
3833 unsigned long nr[MAX_ORDER], flags, total = 0;
3834 unsigned char types[MAX_ORDER];
3836 if (skip_free_areas_node(filter, zone_to_nid(zone)))
3839 printk("%s: ", zone->name);
3841 spin_lock_irqsave(&zone->lock, flags);
3842 for (order = 0; order < MAX_ORDER; order++) {
3843 struct free_area *area = &zone->free_area[order];
3846 nr[order] = area->nr_free;
3847 total += nr[order] << order;
3850 for (type = 0; type < MIGRATE_TYPES; type++) {
3851 if (!list_empty(&area->free_list[type]))
3852 types[order] |= 1 << type;
3855 spin_unlock_irqrestore(&zone->lock, flags);
3856 for (order = 0; order < MAX_ORDER; order++) {
3857 printk("%lu*%lukB ", nr[order], K(1UL) << order);
3859 show_migration_types(types[order]);
3861 printk("= %lukB\n", K(total));
3864 hugetlb_show_meminfo();
3866 printk("%ld total pagecache pages\n", global_page_state(NR_FILE_PAGES));
3868 show_swap_cache_info();
3871 static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref)
3873 zoneref->zone = zone;
3874 zoneref->zone_idx = zone_idx(zone);
3878 * Builds allocation fallback zone lists.
3880 * Add all populated zones of a node to the zonelist.
3882 static int build_zonelists_node(pg_data_t *pgdat, struct zonelist *zonelist,
3886 enum zone_type zone_type = MAX_NR_ZONES;
3890 zone = pgdat->node_zones + zone_type;
3891 if (populated_zone(zone)) {
3892 zoneref_set_zone(zone,
3893 &zonelist->_zonerefs[nr_zones++]);
3894 check_highest_zone(zone_type);
3896 } while (zone_type);
3904 * 0 = automatic detection of better ordering.
3905 * 1 = order by ([node] distance, -zonetype)
3906 * 2 = order by (-zonetype, [node] distance)
3908 * If not NUMA, ZONELIST_ORDER_ZONE and ZONELIST_ORDER_NODE will create
3909 * the same zonelist. So only NUMA can configure this param.
3911 #define ZONELIST_ORDER_DEFAULT 0
3912 #define ZONELIST_ORDER_NODE 1
3913 #define ZONELIST_ORDER_ZONE 2
3915 /* zonelist order in the kernel.
3916 * set_zonelist_order() will set this to NODE or ZONE.
3918 static int current_zonelist_order = ZONELIST_ORDER_DEFAULT;
3919 static char zonelist_order_name[3][8] = {"Default", "Node", "Zone"};
3923 /* The value user specified ....changed by config */
3924 static int user_zonelist_order = ZONELIST_ORDER_DEFAULT;
3925 /* string for sysctl */
3926 #define NUMA_ZONELIST_ORDER_LEN 16
3927 char numa_zonelist_order[16] = "default";
3930 * interface for configure zonelist ordering.
3931 * command line option "numa_zonelist_order"
3932 * = "[dD]efault - default, automatic configuration.
3933 * = "[nN]ode - order by node locality, then by zone within node
3934 * = "[zZ]one - order by zone, then by locality within zone
3937 static int __parse_numa_zonelist_order(char *s)
3939 if (*s == 'd' || *s == 'D') {
3940 user_zonelist_order = ZONELIST_ORDER_DEFAULT;
3941 } else if (*s == 'n' || *s == 'N') {
3942 user_zonelist_order = ZONELIST_ORDER_NODE;
3943 } else if (*s == 'z' || *s == 'Z') {
3944 user_zonelist_order = ZONELIST_ORDER_ZONE;
3947 "Ignoring invalid numa_zonelist_order value: "
3954 static __init int setup_numa_zonelist_order(char *s)
3961 ret = __parse_numa_zonelist_order(s);
3963 strlcpy(numa_zonelist_order, s, NUMA_ZONELIST_ORDER_LEN);
3967 early_param("numa_zonelist_order", setup_numa_zonelist_order);
3970 * sysctl handler for numa_zonelist_order
3972 int numa_zonelist_order_handler(struct ctl_table *table, int write,
3973 void __user *buffer, size_t *length,
3976 char saved_string[NUMA_ZONELIST_ORDER_LEN];
3978 static DEFINE_MUTEX(zl_order_mutex);
3980 mutex_lock(&zl_order_mutex);
3982 if (strlen((char *)table->data) >= NUMA_ZONELIST_ORDER_LEN) {
3986 strcpy(saved_string, (char *)table->data);
3988 ret = proc_dostring(table, write, buffer, length, ppos);
3992 int oldval = user_zonelist_order;
3994 ret = __parse_numa_zonelist_order((char *)table->data);
3997 * bogus value. restore saved string
3999 strncpy((char *)table->data, saved_string,
4000 NUMA_ZONELIST_ORDER_LEN);
4001 user_zonelist_order = oldval;
4002 } else if (oldval != user_zonelist_order) {
4003 mutex_lock(&zonelists_mutex);
4004 build_all_zonelists(NULL, NULL);
4005 mutex_unlock(&zonelists_mutex);
4009 mutex_unlock(&zl_order_mutex);
4014 #define MAX_NODE_LOAD (nr_online_nodes)
4015 static int node_load[MAX_NUMNODES];
4018 * find_next_best_node - find the next node that should appear in a given node's fallback list
4019 * @node: node whose fallback list we're appending
4020 * @used_node_mask: nodemask_t of already used nodes
4022 * We use a number of factors to determine which is the next node that should
4023 * appear on a given node's fallback list. The node should not have appeared
4024 * already in @node's fallback list, and it should be the next closest node
4025 * according to the distance array (which contains arbitrary distance values
4026 * from each node to each node in the system), and should also prefer nodes
4027 * with no CPUs, since presumably they'll have very little allocation pressure
4028 * on them otherwise.
4029 * It returns -1 if no node is found.
4031 static int find_next_best_node(int node, nodemask_t *used_node_mask)
4034 int min_val = INT_MAX;
4035 int best_node = NUMA_NO_NODE;
4036 const struct cpumask *tmp = cpumask_of_node(0);
4038 /* Use the local node if we haven't already */
4039 if (!node_isset(node, *used_node_mask)) {
4040 node_set(node, *used_node_mask);
4044 for_each_node_state(n, N_MEMORY) {
4046 /* Don't want a node to appear more than once */
4047 if (node_isset(n, *used_node_mask))
4050 /* Use the distance array to find the distance */
4051 val = node_distance(node, n);
4053 /* Penalize nodes under us ("prefer the next node") */
4056 /* Give preference to headless and unused nodes */
4057 tmp = cpumask_of_node(n);
4058 if (!cpumask_empty(tmp))
4059 val += PENALTY_FOR_NODE_WITH_CPUS;
4061 /* Slight preference for less loaded node */
4062 val *= (MAX_NODE_LOAD*MAX_NUMNODES);
4063 val += node_load[n];
4065 if (val < min_val) {
4072 node_set(best_node, *used_node_mask);
4079 * Build zonelists ordered by node and zones within node.
4080 * This results in maximum locality--normal zone overflows into local
4081 * DMA zone, if any--but risks exhausting DMA zone.
4083 static void build_zonelists_in_node_order(pg_data_t *pgdat, int node)
4086 struct zonelist *zonelist;
4088 zonelist = &pgdat->node_zonelists[0];
4089 for (j = 0; zonelist->_zonerefs[j].zone != NULL; j++)
4091 j = build_zonelists_node(NODE_DATA(node), zonelist, j);
4092 zonelist->_zonerefs[j].zone = NULL;
4093 zonelist->_zonerefs[j].zone_idx = 0;
4097 * Build gfp_thisnode zonelists
4099 static void build_thisnode_zonelists(pg_data_t *pgdat)
4102 struct zonelist *zonelist;
4104 zonelist = &pgdat->node_zonelists[1];
4105 j = build_zonelists_node(pgdat, zonelist, 0);
4106 zonelist->_zonerefs[j].zone = NULL;
4107 zonelist->_zonerefs[j].zone_idx = 0;
4111 * Build zonelists ordered by zone and nodes within zones.
4112 * This results in conserving DMA zone[s] until all Normal memory is
4113 * exhausted, but results in overflowing to remote node while memory
4114 * may still exist in local DMA zone.
4116 static int node_order[MAX_NUMNODES];
4118 static void build_zonelists_in_zone_order(pg_data_t *pgdat, int nr_nodes)
4121 int zone_type; /* needs to be signed */
4123 struct zonelist *zonelist;
4125 zonelist = &pgdat->node_zonelists[0];
4127 for (zone_type = MAX_NR_ZONES - 1; zone_type >= 0; zone_type--) {
4128 for (j = 0; j < nr_nodes; j++) {
4129 node = node_order[j];
4130 z = &NODE_DATA(node)->node_zones[zone_type];
4131 if (populated_zone(z)) {
4133 &zonelist->_zonerefs[pos++]);
4134 check_highest_zone(zone_type);
4138 zonelist->_zonerefs[pos].zone = NULL;
4139 zonelist->_zonerefs[pos].zone_idx = 0;
4142 #if defined(CONFIG_64BIT)
4144 * Devices that require DMA32/DMA are relatively rare and do not justify a
4145 * penalty to every machine in case the specialised case applies. Default
4146 * to Node-ordering on 64-bit NUMA machines
4148 static int default_zonelist_order(void)
4150 return ZONELIST_ORDER_NODE;
4154 * On 32-bit, the Normal zone needs to be preserved for allocations accessible
4155 * by the kernel. If processes running on node 0 deplete the low memory zone
4156 * then reclaim will occur more frequency increasing stalls and potentially
4157 * be easier to OOM if a large percentage of the zone is under writeback or
4158 * dirty. The problem is significantly worse if CONFIG_HIGHPTE is not set.
4159 * Hence, default to zone ordering on 32-bit.
4161 static int default_zonelist_order(void)
4163 return ZONELIST_ORDER_ZONE;
4165 #endif /* CONFIG_64BIT */
4167 static void set_zonelist_order(void)
4169 if (user_zonelist_order == ZONELIST_ORDER_DEFAULT)
4170 current_zonelist_order = default_zonelist_order();
4172 current_zonelist_order = user_zonelist_order;
4175 static void build_zonelists(pg_data_t *pgdat)
4179 nodemask_t used_mask;
4180 int local_node, prev_node;
4181 struct zonelist *zonelist;
4182 unsigned int order = current_zonelist_order;
4184 /* initialize zonelists */
4185 for (i = 0; i < MAX_ZONELISTS; i++) {
4186 zonelist = pgdat->node_zonelists + i;
4187 zonelist->_zonerefs[0].zone = NULL;
4188 zonelist->_zonerefs[0].zone_idx = 0;
4191 /* NUMA-aware ordering of nodes */
4192 local_node = pgdat->node_id;
4193 load = nr_online_nodes;
4194 prev_node = local_node;
4195 nodes_clear(used_mask);
4197 memset(node_order, 0, sizeof(node_order));
4200 while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
4202 * We don't want to pressure a particular node.
4203 * So adding penalty to the first node in same
4204 * distance group to make it round-robin.
4206 if (node_distance(local_node, node) !=
4207 node_distance(local_node, prev_node))
4208 node_load[node] = load;
4212 if (order == ZONELIST_ORDER_NODE)
4213 build_zonelists_in_node_order(pgdat, node);
4215 node_order[j++] = node; /* remember order */
4218 if (order == ZONELIST_ORDER_ZONE) {
4219 /* calculate node order -- i.e., DMA last! */
4220 build_zonelists_in_zone_order(pgdat, j);
4223 build_thisnode_zonelists(pgdat);
4226 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
4228 * Return node id of node used for "local" allocations.
4229 * I.e., first node id of first zone in arg node's generic zonelist.
4230 * Used for initializing percpu 'numa_mem', which is used primarily
4231 * for kernel allocations, so use GFP_KERNEL flags to locate zonelist.
4233 int local_memory_node(int node)
4237 (void)first_zones_zonelist(node_zonelist(node, GFP_KERNEL),
4238 gfp_zone(GFP_KERNEL),
4245 #else /* CONFIG_NUMA */
4247 static void set_zonelist_order(void)
4249 current_zonelist_order = ZONELIST_ORDER_ZONE;
4252 static void build_zonelists(pg_data_t *pgdat)
4254 int node, local_node;
4256 struct zonelist *zonelist;
4258 local_node = pgdat->node_id;
4260 zonelist = &pgdat->node_zonelists[0];
4261 j = build_zonelists_node(pgdat, zonelist, 0);
4264 * Now we build the zonelist so that it contains the zones
4265 * of all the other nodes.
4266 * We don't want to pressure a particular node, so when
4267 * building the zones for node N, we make sure that the
4268 * zones coming right after the local ones are those from
4269 * node N+1 (modulo N)
4271 for (node = local_node + 1; node < MAX_NUMNODES; node++) {
4272 if (!node_online(node))
4274 j = build_zonelists_node(NODE_DATA(node), zonelist, j);
4276 for (node = 0; node < local_node; node++) {
4277 if (!node_online(node))
4279 j = build_zonelists_node(NODE_DATA(node), zonelist, j);
4282 zonelist->_zonerefs[j].zone = NULL;
4283 zonelist->_zonerefs[j].zone_idx = 0;
4286 #endif /* CONFIG_NUMA */
4289 * Boot pageset table. One per cpu which is going to be used for all
4290 * zones and all nodes. The parameters will be set in such a way
4291 * that an item put on a list will immediately be handed over to
4292 * the buddy list. This is safe since pageset manipulation is done
4293 * with interrupts disabled.
4295 * The boot_pagesets must be kept even after bootup is complete for
4296 * unused processors and/or zones. They do play a role for bootstrapping
4297 * hotplugged processors.
4299 * zoneinfo_show() and maybe other functions do
4300 * not check if the processor is online before following the pageset pointer.
4301 * Other parts of the kernel may not check if the zone is available.
4303 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch);
4304 static DEFINE_PER_CPU(struct per_cpu_pageset, boot_pageset);
4305 static void setup_zone_pageset(struct zone *zone);
4308 * Global mutex to protect against size modification of zonelists
4309 * as well as to serialize pageset setup for the new populated zone.
4311 DEFINE_MUTEX(zonelists_mutex);
4313 /* return values int ....just for stop_machine() */
4314 static int __build_all_zonelists(void *data)
4318 pg_data_t *self = data;
4321 memset(node_load, 0, sizeof(node_load));
4324 if (self && !node_online(self->node_id)) {
4325 build_zonelists(self);
4328 for_each_online_node(nid) {
4329 pg_data_t *pgdat = NODE_DATA(nid);
4331 build_zonelists(pgdat);
4335 * Initialize the boot_pagesets that are going to be used
4336 * for bootstrapping processors. The real pagesets for
4337 * each zone will be allocated later when the per cpu
4338 * allocator is available.
4340 * boot_pagesets are used also for bootstrapping offline
4341 * cpus if the system is already booted because the pagesets
4342 * are needed to initialize allocators on a specific cpu too.
4343 * F.e. the percpu allocator needs the page allocator which
4344 * needs the percpu allocator in order to allocate its pagesets
4345 * (a chicken-egg dilemma).
4347 for_each_possible_cpu(cpu) {
4348 setup_pageset(&per_cpu(boot_pageset, cpu), 0);
4350 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
4352 * We now know the "local memory node" for each node--
4353 * i.e., the node of the first zone in the generic zonelist.
4354 * Set up numa_mem percpu variable for on-line cpus. During
4355 * boot, only the boot cpu should be on-line; we'll init the
4356 * secondary cpus' numa_mem as they come on-line. During
4357 * node/memory hotplug, we'll fixup all on-line cpus.
4359 if (cpu_online(cpu))
4360 set_cpu_numa_mem(cpu, local_memory_node(cpu_to_node(cpu)));
4367 static noinline void __init
4368 build_all_zonelists_init(void)
4370 __build_all_zonelists(NULL);
4371 mminit_verify_zonelist();
4372 cpuset_init_current_mems_allowed();
4376 * Called with zonelists_mutex held always
4377 * unless system_state == SYSTEM_BOOTING.
4379 * __ref due to (1) call of __meminit annotated setup_zone_pageset
4380 * [we're only called with non-NULL zone through __meminit paths] and
4381 * (2) call of __init annotated helper build_all_zonelists_init
4382 * [protected by SYSTEM_BOOTING].
4384 void __ref build_all_zonelists(pg_data_t *pgdat, struct zone *zone)
4386 set_zonelist_order();
4388 if (system_state == SYSTEM_BOOTING) {
4389 build_all_zonelists_init();
4391 #ifdef CONFIG_MEMORY_HOTPLUG
4393 setup_zone_pageset(zone);
4395 /* we have to stop all cpus to guarantee there is no user
4397 stop_machine(__build_all_zonelists, pgdat, NULL);
4398 /* cpuset refresh routine should be here */
4400 vm_total_pages = nr_free_pagecache_pages();
4402 * Disable grouping by mobility if the number of pages in the
4403 * system is too low to allow the mechanism to work. It would be
4404 * more accurate, but expensive to check per-zone. This check is
4405 * made on memory-hotadd so a system can start with mobility
4406 * disabled and enable it later
4408 if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES))
4409 page_group_by_mobility_disabled = 1;
4411 page_group_by_mobility_disabled = 0;
4413 pr_info("Built %i zonelists in %s order, mobility grouping %s. "
4414 "Total pages: %ld\n",
4416 zonelist_order_name[current_zonelist_order],
4417 page_group_by_mobility_disabled ? "off" : "on",
4420 pr_info("Policy zone: %s\n", zone_names[policy_zone]);
4425 * Helper functions to size the waitqueue hash table.
4426 * Essentially these want to choose hash table sizes sufficiently
4427 * large so that collisions trying to wait on pages are rare.
4428 * But in fact, the number of active page waitqueues on typical
4429 * systems is ridiculously low, less than 200. So this is even
4430 * conservative, even though it seems large.
4432 * The constant PAGES_PER_WAITQUEUE specifies the ratio of pages to
4433 * waitqueues, i.e. the size of the waitq table given the number of pages.
4435 #define PAGES_PER_WAITQUEUE 256
4437 #ifndef CONFIG_MEMORY_HOTPLUG
4438 static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
4440 unsigned long size = 1;
4442 pages /= PAGES_PER_WAITQUEUE;
4444 while (size < pages)
4448 * Once we have dozens or even hundreds of threads sleeping
4449 * on IO we've got bigger problems than wait queue collision.
4450 * Limit the size of the wait table to a reasonable size.
4452 size = min(size, 4096UL);
4454 return max(size, 4UL);
4458 * A zone's size might be changed by hot-add, so it is not possible to determine
4459 * a suitable size for its wait_table. So we use the maximum size now.
4461 * The max wait table size = 4096 x sizeof(wait_queue_head_t). ie:
4463 * i386 (preemption config) : 4096 x 16 = 64Kbyte.
4464 * ia64, x86-64 (no preemption): 4096 x 20 = 80Kbyte.
4465 * ia64, x86-64 (preemption) : 4096 x 24 = 96Kbyte.
4467 * The maximum entries are prepared when a zone's memory is (512K + 256) pages
4468 * or more by the traditional way. (See above). It equals:
4470 * i386, x86-64, powerpc(4K page size) : = ( 2G + 1M)byte.
4471 * ia64(16K page size) : = ( 8G + 4M)byte.
4472 * powerpc (64K page size) : = (32G +16M)byte.
4474 static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
4481 * This is an integer logarithm so that shifts can be used later
4482 * to extract the more random high bits from the multiplicative
4483 * hash function before the remainder is taken.
4485 static inline unsigned long wait_table_bits(unsigned long size)
4491 * Initially all pages are reserved - free ones are freed
4492 * up by free_all_bootmem() once the early boot process is
4493 * done. Non-atomic initialization, single-pass.
4495 void __meminit memmap_init_zone(unsigned long size, int nid, unsigned long zone,
4496 unsigned long start_pfn, enum memmap_context context)
4498 pg_data_t *pgdat = NODE_DATA(nid);
4499 unsigned long end_pfn = start_pfn + size;
4502 unsigned long nr_initialised = 0;
4504 if (highest_memmap_pfn < end_pfn - 1)
4505 highest_memmap_pfn = end_pfn - 1;
4507 z = &pgdat->node_zones[zone];
4508 for (pfn = start_pfn; pfn < end_pfn; pfn++) {
4510 * There can be holes in boot-time mem_map[]s
4511 * handed to this function. They do not
4512 * exist on hotplugged memory.
4514 if (context == MEMMAP_EARLY) {
4515 if (!early_pfn_valid(pfn))
4517 if (!early_pfn_in_nid(pfn, nid))
4519 if (!update_defer_init(pgdat, pfn, end_pfn,
4525 * Mark the block movable so that blocks are reserved for
4526 * movable at startup. This will force kernel allocations
4527 * to reserve their blocks rather than leaking throughout
4528 * the address space during boot when many long-lived
4529 * kernel allocations are made.
4531 * bitmap is created for zone's valid pfn range. but memmap
4532 * can be created for invalid pages (for alignment)
4533 * check here not to call set_pageblock_migratetype() against
4536 if (!(pfn & (pageblock_nr_pages - 1))) {
4537 struct page *page = pfn_to_page(pfn);
4539 __init_single_page(page, pfn, zone, nid);
4540 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
4542 __init_single_pfn(pfn, zone, nid);
4547 static void __meminit zone_init_free_lists(struct zone *zone)
4549 unsigned int order, t;
4550 for_each_migratetype_order(order, t) {
4551 INIT_LIST_HEAD(&zone->free_area[order].free_list[t]);
4552 zone->free_area[order].nr_free = 0;
4556 #ifndef __HAVE_ARCH_MEMMAP_INIT
4557 #define memmap_init(size, nid, zone, start_pfn) \
4558 memmap_init_zone((size), (nid), (zone), (start_pfn), MEMMAP_EARLY)
4561 static int zone_batchsize(struct zone *zone)
4567 * The per-cpu-pages pools are set to around 1000th of the
4568 * size of the zone. But no more than 1/2 of a meg.
4570 * OK, so we don't know how big the cache is. So guess.
4572 batch = zone->managed_pages / 1024;
4573 if (batch * PAGE_SIZE > 512 * 1024)
4574 batch = (512 * 1024) / PAGE_SIZE;
4575 batch /= 4; /* We effectively *= 4 below */
4580 * Clamp the batch to a 2^n - 1 value. Having a power
4581 * of 2 value was found to be more likely to have
4582 * suboptimal cache aliasing properties in some cases.
4584 * For example if 2 tasks are alternately allocating
4585 * batches of pages, one task can end up with a lot
4586 * of pages of one half of the possible page colors
4587 * and the other with pages of the other colors.
4589 batch = rounddown_pow_of_two(batch + batch/2) - 1;
4594 /* The deferral and batching of frees should be suppressed under NOMMU
4597 * The problem is that NOMMU needs to be able to allocate large chunks
4598 * of contiguous memory as there's no hardware page translation to
4599 * assemble apparent contiguous memory from discontiguous pages.
4601 * Queueing large contiguous runs of pages for batching, however,
4602 * causes the pages to actually be freed in smaller chunks. As there
4603 * can be a significant delay between the individual batches being
4604 * recycled, this leads to the once large chunks of space being
4605 * fragmented and becoming unavailable for high-order allocations.
4612 * pcp->high and pcp->batch values are related and dependent on one another:
4613 * ->batch must never be higher then ->high.
4614 * The following function updates them in a safe manner without read side
4617 * Any new users of pcp->batch and pcp->high should ensure they can cope with
4618 * those fields changing asynchronously (acording the the above rule).
4620 * mutex_is_locked(&pcp_batch_high_lock) required when calling this function
4621 * outside of boot time (or some other assurance that no concurrent updaters
4624 static void pageset_update(struct per_cpu_pages *pcp, unsigned long high,
4625 unsigned long batch)
4627 /* start with a fail safe value for batch */
4631 /* Update high, then batch, in order */
4638 /* a companion to pageset_set_high() */
4639 static void pageset_set_batch(struct per_cpu_pageset *p, unsigned long batch)
4641 pageset_update(&p->pcp, 6 * batch, max(1UL, 1 * batch));
4644 static void pageset_init(struct per_cpu_pageset *p)
4646 struct per_cpu_pages *pcp;
4649 memset(p, 0, sizeof(*p));
4653 for (migratetype = 0; migratetype < MIGRATE_PCPTYPES; migratetype++)
4654 INIT_LIST_HEAD(&pcp->lists[migratetype]);
4657 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch)
4660 pageset_set_batch(p, batch);
4664 * pageset_set_high() sets the high water mark for hot per_cpu_pagelist
4665 * to the value high for the pageset p.
4667 static void pageset_set_high(struct per_cpu_pageset *p,
4670 unsigned long batch = max(1UL, high / 4);
4671 if ((high / 4) > (PAGE_SHIFT * 8))
4672 batch = PAGE_SHIFT * 8;
4674 pageset_update(&p->pcp, high, batch);
4677 static void pageset_set_high_and_batch(struct zone *zone,
4678 struct per_cpu_pageset *pcp)
4680 if (percpu_pagelist_fraction)
4681 pageset_set_high(pcp,
4682 (zone->managed_pages /
4683 percpu_pagelist_fraction));
4685 pageset_set_batch(pcp, zone_batchsize(zone));
4688 static void __meminit zone_pageset_init(struct zone *zone, int cpu)
4690 struct per_cpu_pageset *pcp = per_cpu_ptr(zone->pageset, cpu);
4693 pageset_set_high_and_batch(zone, pcp);
4696 static void __meminit setup_zone_pageset(struct zone *zone)
4699 zone->pageset = alloc_percpu(struct per_cpu_pageset);
4700 for_each_possible_cpu(cpu)
4701 zone_pageset_init(zone, cpu);
4705 * Allocate per cpu pagesets and initialize them.
4706 * Before this call only boot pagesets were available.
4708 void __init setup_per_cpu_pageset(void)
4712 for_each_populated_zone(zone)
4713 setup_zone_pageset(zone);
4716 static noinline __init_refok
4717 int zone_wait_table_init(struct zone *zone, unsigned long zone_size_pages)
4723 * The per-page waitqueue mechanism uses hashed waitqueues
4726 zone->wait_table_hash_nr_entries =
4727 wait_table_hash_nr_entries(zone_size_pages);
4728 zone->wait_table_bits =
4729 wait_table_bits(zone->wait_table_hash_nr_entries);
4730 alloc_size = zone->wait_table_hash_nr_entries
4731 * sizeof(wait_queue_head_t);
4733 if (!slab_is_available()) {
4734 zone->wait_table = (wait_queue_head_t *)
4735 memblock_virt_alloc_node_nopanic(
4736 alloc_size, zone->zone_pgdat->node_id);
4739 * This case means that a zone whose size was 0 gets new memory
4740 * via memory hot-add.
4741 * But it may be the case that a new node was hot-added. In
4742 * this case vmalloc() will not be able to use this new node's
4743 * memory - this wait_table must be initialized to use this new
4744 * node itself as well.
4745 * To use this new node's memory, further consideration will be
4748 zone->wait_table = vmalloc(alloc_size);
4750 if (!zone->wait_table)
4753 for (i = 0; i < zone->wait_table_hash_nr_entries; ++i)
4754 init_waitqueue_head(zone->wait_table + i);
4759 static __meminit void zone_pcp_init(struct zone *zone)
4762 * per cpu subsystem is not up at this point. The following code
4763 * relies on the ability of the linker to provide the
4764 * offset of a (static) per cpu variable into the per cpu area.
4766 zone->pageset = &boot_pageset;
4768 if (populated_zone(zone))
4769 printk(KERN_DEBUG " %s zone: %lu pages, LIFO batch:%u\n",
4770 zone->name, zone->present_pages,
4771 zone_batchsize(zone));
4774 int __meminit init_currently_empty_zone(struct zone *zone,
4775 unsigned long zone_start_pfn,
4778 struct pglist_data *pgdat = zone->zone_pgdat;
4780 ret = zone_wait_table_init(zone, size);
4783 pgdat->nr_zones = zone_idx(zone) + 1;
4785 zone->zone_start_pfn = zone_start_pfn;
4787 mminit_dprintk(MMINIT_TRACE, "memmap_init",
4788 "Initialising map node %d zone %lu pfns %lu -> %lu\n",
4790 (unsigned long)zone_idx(zone),
4791 zone_start_pfn, (zone_start_pfn + size));
4793 zone_init_free_lists(zone);
4798 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
4799 #ifndef CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID
4802 * Required by SPARSEMEM. Given a PFN, return what node the PFN is on.
4804 int __meminit __early_pfn_to_nid(unsigned long pfn,
4805 struct mminit_pfnnid_cache *state)
4807 unsigned long start_pfn, end_pfn;
4810 if (state->last_start <= pfn && pfn < state->last_end)
4811 return state->last_nid;
4813 nid = memblock_search_pfn_nid(pfn, &start_pfn, &end_pfn);
4815 state->last_start = start_pfn;
4816 state->last_end = end_pfn;
4817 state->last_nid = nid;
4822 #endif /* CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID */
4825 * free_bootmem_with_active_regions - Call memblock_free_early_nid for each active range
4826 * @nid: The node to free memory on. If MAX_NUMNODES, all nodes are freed.
4827 * @max_low_pfn: The highest PFN that will be passed to memblock_free_early_nid
4829 * If an architecture guarantees that all ranges registered contain no holes
4830 * and may be freed, this this function may be used instead of calling
4831 * memblock_free_early_nid() manually.
4833 void __init free_bootmem_with_active_regions(int nid, unsigned long max_low_pfn)
4835 unsigned long start_pfn, end_pfn;
4838 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, &this_nid) {
4839 start_pfn = min(start_pfn, max_low_pfn);
4840 end_pfn = min(end_pfn, max_low_pfn);
4842 if (start_pfn < end_pfn)
4843 memblock_free_early_nid(PFN_PHYS(start_pfn),
4844 (end_pfn - start_pfn) << PAGE_SHIFT,
4850 * sparse_memory_present_with_active_regions - Call memory_present for each active range
4851 * @nid: The node to call memory_present for. If MAX_NUMNODES, all nodes will be used.
4853 * If an architecture guarantees that all ranges registered contain no holes and may
4854 * be freed, this function may be used instead of calling memory_present() manually.
4856 void __init sparse_memory_present_with_active_regions(int nid)
4858 unsigned long start_pfn, end_pfn;
4861 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, &this_nid)
4862 memory_present(this_nid, start_pfn, end_pfn);
4866 * get_pfn_range_for_nid - Return the start and end page frames for a node
4867 * @nid: The nid to return the range for. If MAX_NUMNODES, the min and max PFN are returned.
4868 * @start_pfn: Passed by reference. On return, it will have the node start_pfn.
4869 * @end_pfn: Passed by reference. On return, it will have the node end_pfn.
4871 * It returns the start and end page frame of a node based on information
4872 * provided by memblock_set_node(). If called for a node
4873 * with no available memory, a warning is printed and the start and end
4876 void __meminit get_pfn_range_for_nid(unsigned int nid,
4877 unsigned long *start_pfn, unsigned long *end_pfn)
4879 unsigned long this_start_pfn, this_end_pfn;
4885 for_each_mem_pfn_range(i, nid, &this_start_pfn, &this_end_pfn, NULL) {
4886 *start_pfn = min(*start_pfn, this_start_pfn);
4887 *end_pfn = max(*end_pfn, this_end_pfn);
4890 if (*start_pfn == -1UL)
4895 * This finds a zone that can be used for ZONE_MOVABLE pages. The
4896 * assumption is made that zones within a node are ordered in monotonic
4897 * increasing memory addresses so that the "highest" populated zone is used
4899 static void __init find_usable_zone_for_movable(void)
4902 for (zone_index = MAX_NR_ZONES - 1; zone_index >= 0; zone_index--) {
4903 if (zone_index == ZONE_MOVABLE)
4906 if (arch_zone_highest_possible_pfn[zone_index] >
4907 arch_zone_lowest_possible_pfn[zone_index])
4911 VM_BUG_ON(zone_index == -1);
4912 movable_zone = zone_index;
4916 * The zone ranges provided by the architecture do not include ZONE_MOVABLE
4917 * because it is sized independent of architecture. Unlike the other zones,
4918 * the starting point for ZONE_MOVABLE is not fixed. It may be different
4919 * in each node depending on the size of each node and how evenly kernelcore
4920 * is distributed. This helper function adjusts the zone ranges
4921 * provided by the architecture for a given node by using the end of the
4922 * highest usable zone for ZONE_MOVABLE. This preserves the assumption that
4923 * zones within a node are in order of monotonic increases memory addresses
4925 static void __meminit adjust_zone_range_for_zone_movable(int nid,
4926 unsigned long zone_type,
4927 unsigned long node_start_pfn,
4928 unsigned long node_end_pfn,
4929 unsigned long *zone_start_pfn,
4930 unsigned long *zone_end_pfn)
4932 /* Only adjust if ZONE_MOVABLE is on this node */
4933 if (zone_movable_pfn[nid]) {
4934 /* Size ZONE_MOVABLE */
4935 if (zone_type == ZONE_MOVABLE) {
4936 *zone_start_pfn = zone_movable_pfn[nid];
4937 *zone_end_pfn = min(node_end_pfn,
4938 arch_zone_highest_possible_pfn[movable_zone]);
4940 /* Adjust for ZONE_MOVABLE starting within this range */
4941 } else if (*zone_start_pfn < zone_movable_pfn[nid] &&
4942 *zone_end_pfn > zone_movable_pfn[nid]) {
4943 *zone_end_pfn = zone_movable_pfn[nid];
4945 /* Check if this whole range is within ZONE_MOVABLE */
4946 } else if (*zone_start_pfn >= zone_movable_pfn[nid])
4947 *zone_start_pfn = *zone_end_pfn;
4952 * Return the number of pages a zone spans in a node, including holes
4953 * present_pages = zone_spanned_pages_in_node() - zone_absent_pages_in_node()
4955 static unsigned long __meminit zone_spanned_pages_in_node(int nid,
4956 unsigned long zone_type,
4957 unsigned long node_start_pfn,
4958 unsigned long node_end_pfn,
4959 unsigned long *ignored)
4961 unsigned long zone_start_pfn, zone_end_pfn;
4963 /* When hotadd a new node from cpu_up(), the node should be empty */
4964 if (!node_start_pfn && !node_end_pfn)
4967 /* Get the start and end of the zone */
4968 zone_start_pfn = arch_zone_lowest_possible_pfn[zone_type];
4969 zone_end_pfn = arch_zone_highest_possible_pfn[zone_type];
4970 adjust_zone_range_for_zone_movable(nid, zone_type,
4971 node_start_pfn, node_end_pfn,
4972 &zone_start_pfn, &zone_end_pfn);
4974 /* Check that this node has pages within the zone's required range */
4975 if (zone_end_pfn < node_start_pfn || zone_start_pfn > node_end_pfn)
4978 /* Move the zone boundaries inside the node if necessary */
4979 zone_end_pfn = min(zone_end_pfn, node_end_pfn);
4980 zone_start_pfn = max(zone_start_pfn, node_start_pfn);
4982 /* Return the spanned pages */
4983 return zone_end_pfn - zone_start_pfn;
4987 * Return the number of holes in a range on a node. If nid is MAX_NUMNODES,
4988 * then all holes in the requested range will be accounted for.
4990 unsigned long __meminit __absent_pages_in_range(int nid,
4991 unsigned long range_start_pfn,
4992 unsigned long range_end_pfn)
4994 unsigned long nr_absent = range_end_pfn - range_start_pfn;
4995 unsigned long start_pfn, end_pfn;
4998 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
4999 start_pfn = clamp(start_pfn, range_start_pfn, range_end_pfn);
5000 end_pfn = clamp(end_pfn, range_start_pfn, range_end_pfn);
5001 nr_absent -= end_pfn - start_pfn;
5007 * absent_pages_in_range - Return number of page frames in holes within a range
5008 * @start_pfn: The start PFN to start searching for holes
5009 * @end_pfn: The end PFN to stop searching for holes
5011 * It returns the number of pages frames in memory holes within a range.
5013 unsigned long __init absent_pages_in_range(unsigned long start_pfn,
5014 unsigned long end_pfn)
5016 return __absent_pages_in_range(MAX_NUMNODES, start_pfn, end_pfn);
5019 /* Return the number of page frames in holes in a zone on a node */
5020 static unsigned long __meminit zone_absent_pages_in_node(int nid,
5021 unsigned long zone_type,
5022 unsigned long node_start_pfn,
5023 unsigned long node_end_pfn,
5024 unsigned long *ignored)
5026 unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type];
5027 unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type];
5028 unsigned long zone_start_pfn, zone_end_pfn;
5030 /* When hotadd a new node from cpu_up(), the node should be empty */
5031 if (!node_start_pfn && !node_end_pfn)
5034 zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high);
5035 zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high);
5037 adjust_zone_range_for_zone_movable(nid, zone_type,
5038 node_start_pfn, node_end_pfn,
5039 &zone_start_pfn, &zone_end_pfn);
5040 return __absent_pages_in_range(nid, zone_start_pfn, zone_end_pfn);
5043 #else /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
5044 static inline unsigned long __meminit zone_spanned_pages_in_node(int nid,
5045 unsigned long zone_type,
5046 unsigned long node_start_pfn,
5047 unsigned long node_end_pfn,
5048 unsigned long *zones_size)
5050 return zones_size[zone_type];
5053 static inline unsigned long __meminit zone_absent_pages_in_node(int nid,
5054 unsigned long zone_type,
5055 unsigned long node_start_pfn,
5056 unsigned long node_end_pfn,
5057 unsigned long *zholes_size)
5062 return zholes_size[zone_type];
5065 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
5067 static void __meminit calculate_node_totalpages(struct pglist_data *pgdat,
5068 unsigned long node_start_pfn,
5069 unsigned long node_end_pfn,
5070 unsigned long *zones_size,
5071 unsigned long *zholes_size)
5073 unsigned long realtotalpages = 0, totalpages = 0;
5076 for (i = 0; i < MAX_NR_ZONES; i++) {
5077 struct zone *zone = pgdat->node_zones + i;
5078 unsigned long size, real_size;
5080 size = zone_spanned_pages_in_node(pgdat->node_id, i,
5084 real_size = size - zone_absent_pages_in_node(pgdat->node_id, i,
5085 node_start_pfn, node_end_pfn,
5087 zone->spanned_pages = size;
5088 zone->present_pages = real_size;
5091 realtotalpages += real_size;
5094 pgdat->node_spanned_pages = totalpages;
5095 pgdat->node_present_pages = realtotalpages;
5096 printk(KERN_DEBUG "On node %d totalpages: %lu\n", pgdat->node_id,
5100 #ifndef CONFIG_SPARSEMEM
5102 * Calculate the size of the zone->blockflags rounded to an unsigned long
5103 * Start by making sure zonesize is a multiple of pageblock_order by rounding
5104 * up. Then use 1 NR_PAGEBLOCK_BITS worth of bits per pageblock, finally
5105 * round what is now in bits to nearest long in bits, then return it in
5108 static unsigned long __init usemap_size(unsigned long zone_start_pfn, unsigned long zonesize)
5110 unsigned long usemapsize;
5112 zonesize += zone_start_pfn & (pageblock_nr_pages-1);
5113 usemapsize = roundup(zonesize, pageblock_nr_pages);
5114 usemapsize = usemapsize >> pageblock_order;
5115 usemapsize *= NR_PAGEBLOCK_BITS;
5116 usemapsize = roundup(usemapsize, 8 * sizeof(unsigned long));
5118 return usemapsize / 8;
5121 static void __init setup_usemap(struct pglist_data *pgdat,
5123 unsigned long zone_start_pfn,
5124 unsigned long zonesize)
5126 unsigned long usemapsize = usemap_size(zone_start_pfn, zonesize);
5127 zone->pageblock_flags = NULL;
5129 zone->pageblock_flags =
5130 memblock_virt_alloc_node_nopanic(usemapsize,
5134 static inline void setup_usemap(struct pglist_data *pgdat, struct zone *zone,
5135 unsigned long zone_start_pfn, unsigned long zonesize) {}
5136 #endif /* CONFIG_SPARSEMEM */
5138 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
5140 /* Initialise the number of pages represented by NR_PAGEBLOCK_BITS */
5141 void __paginginit set_pageblock_order(void)
5145 /* Check that pageblock_nr_pages has not already been setup */
5146 if (pageblock_order)
5149 if (HPAGE_SHIFT > PAGE_SHIFT)
5150 order = HUGETLB_PAGE_ORDER;
5152 order = MAX_ORDER - 1;
5155 * Assume the largest contiguous order of interest is a huge page.
5156 * This value may be variable depending on boot parameters on IA64 and
5159 pageblock_order = order;
5161 #else /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
5164 * When CONFIG_HUGETLB_PAGE_SIZE_VARIABLE is not set, set_pageblock_order()
5165 * is unused as pageblock_order is set at compile-time. See
5166 * include/linux/pageblock-flags.h for the values of pageblock_order based on
5169 void __paginginit set_pageblock_order(void)
5173 #endif /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
5175 static unsigned long __paginginit calc_memmap_size(unsigned long spanned_pages,
5176 unsigned long present_pages)
5178 unsigned long pages = spanned_pages;
5181 * Provide a more accurate estimation if there are holes within
5182 * the zone and SPARSEMEM is in use. If there are holes within the
5183 * zone, each populated memory region may cost us one or two extra
5184 * memmap pages due to alignment because memmap pages for each
5185 * populated regions may not naturally algined on page boundary.
5186 * So the (present_pages >> 4) heuristic is a tradeoff for that.
5188 if (spanned_pages > present_pages + (present_pages >> 4) &&
5189 IS_ENABLED(CONFIG_SPARSEMEM))
5190 pages = present_pages;
5192 return PAGE_ALIGN(pages * sizeof(struct page)) >> PAGE_SHIFT;
5196 * Set up the zone data structures:
5197 * - mark all pages reserved
5198 * - mark all memory queues empty
5199 * - clear the memory bitmaps
5201 * NOTE: pgdat should get zeroed by caller.
5203 static void __paginginit free_area_init_core(struct pglist_data *pgdat)
5206 int nid = pgdat->node_id;
5207 unsigned long zone_start_pfn = pgdat->node_start_pfn;
5210 pgdat_resize_init(pgdat);
5211 #ifdef CONFIG_NUMA_BALANCING
5212 spin_lock_init(&pgdat->numabalancing_migrate_lock);
5213 pgdat->numabalancing_migrate_nr_pages = 0;
5214 pgdat->numabalancing_migrate_next_window = jiffies;
5216 init_waitqueue_head(&pgdat->kswapd_wait);
5217 init_waitqueue_head(&pgdat->pfmemalloc_wait);
5218 pgdat_page_ext_init(pgdat);
5220 for (j = 0; j < MAX_NR_ZONES; j++) {
5221 struct zone *zone = pgdat->node_zones + j;
5222 unsigned long size, realsize, freesize, memmap_pages;
5224 size = zone->spanned_pages;
5225 realsize = freesize = zone->present_pages;
5228 * Adjust freesize so that it accounts for how much memory
5229 * is used by this zone for memmap. This affects the watermark
5230 * and per-cpu initialisations
5232 memmap_pages = calc_memmap_size(size, realsize);
5233 if (!is_highmem_idx(j)) {
5234 if (freesize >= memmap_pages) {
5235 freesize -= memmap_pages;
5238 " %s zone: %lu pages used for memmap\n",
5239 zone_names[j], memmap_pages);
5242 " %s zone: %lu pages exceeds freesize %lu\n",
5243 zone_names[j], memmap_pages, freesize);
5246 /* Account for reserved pages */
5247 if (j == 0 && freesize > dma_reserve) {
5248 freesize -= dma_reserve;
5249 printk(KERN_DEBUG " %s zone: %lu pages reserved\n",
5250 zone_names[0], dma_reserve);
5253 if (!is_highmem_idx(j))
5254 nr_kernel_pages += freesize;
5255 /* Charge for highmem memmap if there are enough kernel pages */
5256 else if (nr_kernel_pages > memmap_pages * 2)
5257 nr_kernel_pages -= memmap_pages;
5258 nr_all_pages += freesize;
5261 * Set an approximate value for lowmem here, it will be adjusted
5262 * when the bootmem allocator frees pages into the buddy system.
5263 * And all highmem pages will be managed by the buddy system.
5265 zone->managed_pages = is_highmem_idx(j) ? realsize : freesize;
5268 zone->min_unmapped_pages = (freesize*sysctl_min_unmapped_ratio)
5270 zone->min_slab_pages = (freesize * sysctl_min_slab_ratio) / 100;
5272 zone->name = zone_names[j];
5273 spin_lock_init(&zone->lock);
5274 spin_lock_init(&zone->lru_lock);
5275 zone_seqlock_init(zone);
5276 zone->zone_pgdat = pgdat;
5277 zone_pcp_init(zone);
5279 /* For bootup, initialized properly in watermark setup */
5280 mod_zone_page_state(zone, NR_ALLOC_BATCH, zone->managed_pages);
5282 lruvec_init(&zone->lruvec);
5286 set_pageblock_order();
5287 setup_usemap(pgdat, zone, zone_start_pfn, size);
5288 ret = init_currently_empty_zone(zone, zone_start_pfn, size);
5290 memmap_init(size, nid, j, zone_start_pfn);
5291 zone_start_pfn += size;
5295 static void __init_refok alloc_node_mem_map(struct pglist_data *pgdat)
5297 unsigned long __maybe_unused start = 0;
5298 unsigned long __maybe_unused offset = 0;
5300 /* Skip empty nodes */
5301 if (!pgdat->node_spanned_pages)
5304 #ifdef CONFIG_FLAT_NODE_MEM_MAP
5305 start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1);
5306 offset = pgdat->node_start_pfn - start;
5307 /* ia64 gets its own node_mem_map, before this, without bootmem */
5308 if (!pgdat->node_mem_map) {
5309 unsigned long size, end;
5313 * The zone's endpoints aren't required to be MAX_ORDER
5314 * aligned but the node_mem_map endpoints must be in order
5315 * for the buddy allocator to function correctly.
5317 end = pgdat_end_pfn(pgdat);
5318 end = ALIGN(end, MAX_ORDER_NR_PAGES);
5319 size = (end - start) * sizeof(struct page);
5320 map = alloc_remap(pgdat->node_id, size);
5322 map = memblock_virt_alloc_node_nopanic(size,
5324 pgdat->node_mem_map = map + offset;
5326 #ifndef CONFIG_NEED_MULTIPLE_NODES
5328 * With no DISCONTIG, the global mem_map is just set as node 0's
5330 if (pgdat == NODE_DATA(0)) {
5331 mem_map = NODE_DATA(0)->node_mem_map;
5332 #if defined(CONFIG_HAVE_MEMBLOCK_NODE_MAP) || defined(CONFIG_FLATMEM)
5333 if (page_to_pfn(mem_map) != pgdat->node_start_pfn)
5335 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
5338 #endif /* CONFIG_FLAT_NODE_MEM_MAP */
5341 void __paginginit free_area_init_node(int nid, unsigned long *zones_size,
5342 unsigned long node_start_pfn, unsigned long *zholes_size)
5344 pg_data_t *pgdat = NODE_DATA(nid);
5345 unsigned long start_pfn = 0;
5346 unsigned long end_pfn = 0;
5348 /* pg_data_t should be reset to zero when it's allocated */
5349 WARN_ON(pgdat->nr_zones || pgdat->classzone_idx);
5351 reset_deferred_meminit(pgdat);
5352 pgdat->node_id = nid;
5353 pgdat->node_start_pfn = node_start_pfn;
5354 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
5355 get_pfn_range_for_nid(nid, &start_pfn, &end_pfn);
5356 pr_info("Initmem setup node %d [mem %#018Lx-%#018Lx]\n", nid,
5357 (u64)start_pfn << PAGE_SHIFT,
5358 end_pfn ? ((u64)end_pfn << PAGE_SHIFT) - 1 : 0);
5360 calculate_node_totalpages(pgdat, start_pfn, end_pfn,
5361 zones_size, zholes_size);
5363 alloc_node_mem_map(pgdat);
5364 #ifdef CONFIG_FLAT_NODE_MEM_MAP
5365 printk(KERN_DEBUG "free_area_init_node: node %d, pgdat %08lx, node_mem_map %08lx\n",
5366 nid, (unsigned long)pgdat,
5367 (unsigned long)pgdat->node_mem_map);
5370 free_area_init_core(pgdat);
5373 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
5375 #if MAX_NUMNODES > 1
5377 * Figure out the number of possible node ids.
5379 void __init setup_nr_node_ids(void)
5381 unsigned int highest;
5383 highest = find_last_bit(node_possible_map.bits, MAX_NUMNODES);
5384 nr_node_ids = highest + 1;
5389 * node_map_pfn_alignment - determine the maximum internode alignment
5391 * This function should be called after node map is populated and sorted.
5392 * It calculates the maximum power of two alignment which can distinguish
5395 * For example, if all nodes are 1GiB and aligned to 1GiB, the return value
5396 * would indicate 1GiB alignment with (1 << (30 - PAGE_SHIFT)). If the
5397 * nodes are shifted by 256MiB, 256MiB. Note that if only the last node is
5398 * shifted, 1GiB is enough and this function will indicate so.
5400 * This is used to test whether pfn -> nid mapping of the chosen memory
5401 * model has fine enough granularity to avoid incorrect mapping for the
5402 * populated node map.
5404 * Returns the determined alignment in pfn's. 0 if there is no alignment
5405 * requirement (single node).
5407 unsigned long __init node_map_pfn_alignment(void)
5409 unsigned long accl_mask = 0, last_end = 0;
5410 unsigned long start, end, mask;
5414 for_each_mem_pfn_range(i, MAX_NUMNODES, &start, &end, &nid) {
5415 if (!start || last_nid < 0 || last_nid == nid) {
5422 * Start with a mask granular enough to pin-point to the
5423 * start pfn and tick off bits one-by-one until it becomes
5424 * too coarse to separate the current node from the last.
5426 mask = ~((1 << __ffs(start)) - 1);
5427 while (mask && last_end <= (start & (mask << 1)))
5430 /* accumulate all internode masks */
5434 /* convert mask to number of pages */
5435 return ~accl_mask + 1;
5438 /* Find the lowest pfn for a node */
5439 static unsigned long __init find_min_pfn_for_node(int nid)
5441 unsigned long min_pfn = ULONG_MAX;
5442 unsigned long start_pfn;
5445 for_each_mem_pfn_range(i, nid, &start_pfn, NULL, NULL)
5446 min_pfn = min(min_pfn, start_pfn);
5448 if (min_pfn == ULONG_MAX) {
5450 "Could not find start_pfn for node %d\n", nid);
5458 * find_min_pfn_with_active_regions - Find the minimum PFN registered
5460 * It returns the minimum PFN based on information provided via
5461 * memblock_set_node().
5463 unsigned long __init find_min_pfn_with_active_regions(void)
5465 return find_min_pfn_for_node(MAX_NUMNODES);
5469 * early_calculate_totalpages()
5470 * Sum pages in active regions for movable zone.
5471 * Populate N_MEMORY for calculating usable_nodes.
5473 static unsigned long __init early_calculate_totalpages(void)
5475 unsigned long totalpages = 0;
5476 unsigned long start_pfn, end_pfn;
5479 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
5480 unsigned long pages = end_pfn - start_pfn;
5482 totalpages += pages;
5484 node_set_state(nid, N_MEMORY);
5490 * Find the PFN the Movable zone begins in each node. Kernel memory
5491 * is spread evenly between nodes as long as the nodes have enough
5492 * memory. When they don't, some nodes will have more kernelcore than
5495 static void __init find_zone_movable_pfns_for_nodes(void)
5498 unsigned long usable_startpfn;
5499 unsigned long kernelcore_node, kernelcore_remaining;
5500 /* save the state before borrow the nodemask */
5501 nodemask_t saved_node_state = node_states[N_MEMORY];
5502 unsigned long totalpages = early_calculate_totalpages();
5503 int usable_nodes = nodes_weight(node_states[N_MEMORY]);
5504 struct memblock_region *r;
5506 /* Need to find movable_zone earlier when movable_node is specified. */
5507 find_usable_zone_for_movable();
5510 * If movable_node is specified, ignore kernelcore and movablecore
5513 if (movable_node_is_enabled()) {
5514 for_each_memblock(memory, r) {
5515 if (!memblock_is_hotpluggable(r))
5520 usable_startpfn = PFN_DOWN(r->base);
5521 zone_movable_pfn[nid] = zone_movable_pfn[nid] ?
5522 min(usable_startpfn, zone_movable_pfn[nid]) :
5530 * If movablecore=nn[KMG] was specified, calculate what size of
5531 * kernelcore that corresponds so that memory usable for
5532 * any allocation type is evenly spread. If both kernelcore
5533 * and movablecore are specified, then the value of kernelcore
5534 * will be used for required_kernelcore if it's greater than
5535 * what movablecore would have allowed.
5537 if (required_movablecore) {
5538 unsigned long corepages;
5541 * Round-up so that ZONE_MOVABLE is at least as large as what
5542 * was requested by the user
5544 required_movablecore =
5545 roundup(required_movablecore, MAX_ORDER_NR_PAGES);
5546 required_movablecore = min(totalpages, required_movablecore);
5547 corepages = totalpages - required_movablecore;
5549 required_kernelcore = max(required_kernelcore, corepages);
5553 * If kernelcore was not specified or kernelcore size is larger
5554 * than totalpages, there is no ZONE_MOVABLE.
5556 if (!required_kernelcore || required_kernelcore >= totalpages)
5559 /* usable_startpfn is the lowest possible pfn ZONE_MOVABLE can be at */
5560 usable_startpfn = arch_zone_lowest_possible_pfn[movable_zone];
5563 /* Spread kernelcore memory as evenly as possible throughout nodes */
5564 kernelcore_node = required_kernelcore / usable_nodes;
5565 for_each_node_state(nid, N_MEMORY) {
5566 unsigned long start_pfn, end_pfn;
5569 * Recalculate kernelcore_node if the division per node
5570 * now exceeds what is necessary to satisfy the requested
5571 * amount of memory for the kernel
5573 if (required_kernelcore < kernelcore_node)
5574 kernelcore_node = required_kernelcore / usable_nodes;
5577 * As the map is walked, we track how much memory is usable
5578 * by the kernel using kernelcore_remaining. When it is
5579 * 0, the rest of the node is usable by ZONE_MOVABLE
5581 kernelcore_remaining = kernelcore_node;
5583 /* Go through each range of PFNs within this node */
5584 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
5585 unsigned long size_pages;
5587 start_pfn = max(start_pfn, zone_movable_pfn[nid]);
5588 if (start_pfn >= end_pfn)
5591 /* Account for what is only usable for kernelcore */
5592 if (start_pfn < usable_startpfn) {
5593 unsigned long kernel_pages;
5594 kernel_pages = min(end_pfn, usable_startpfn)
5597 kernelcore_remaining -= min(kernel_pages,
5598 kernelcore_remaining);
5599 required_kernelcore -= min(kernel_pages,
5600 required_kernelcore);
5602 /* Continue if range is now fully accounted */
5603 if (end_pfn <= usable_startpfn) {
5606 * Push zone_movable_pfn to the end so
5607 * that if we have to rebalance
5608 * kernelcore across nodes, we will
5609 * not double account here
5611 zone_movable_pfn[nid] = end_pfn;
5614 start_pfn = usable_startpfn;
5618 * The usable PFN range for ZONE_MOVABLE is from
5619 * start_pfn->end_pfn. Calculate size_pages as the
5620 * number of pages used as kernelcore
5622 size_pages = end_pfn - start_pfn;
5623 if (size_pages > kernelcore_remaining)
5624 size_pages = kernelcore_remaining;
5625 zone_movable_pfn[nid] = start_pfn + size_pages;
5628 * Some kernelcore has been met, update counts and
5629 * break if the kernelcore for this node has been
5632 required_kernelcore -= min(required_kernelcore,
5634 kernelcore_remaining -= size_pages;
5635 if (!kernelcore_remaining)
5641 * If there is still required_kernelcore, we do another pass with one
5642 * less node in the count. This will push zone_movable_pfn[nid] further
5643 * along on the nodes that still have memory until kernelcore is
5647 if (usable_nodes && required_kernelcore > usable_nodes)
5651 /* Align start of ZONE_MOVABLE on all nids to MAX_ORDER_NR_PAGES */
5652 for (nid = 0; nid < MAX_NUMNODES; nid++)
5653 zone_movable_pfn[nid] =
5654 roundup(zone_movable_pfn[nid], MAX_ORDER_NR_PAGES);
5657 /* restore the node_state */
5658 node_states[N_MEMORY] = saved_node_state;
5661 /* Any regular or high memory on that node ? */
5662 static void check_for_memory(pg_data_t *pgdat, int nid)
5664 enum zone_type zone_type;
5666 if (N_MEMORY == N_NORMAL_MEMORY)
5669 for (zone_type = 0; zone_type <= ZONE_MOVABLE - 1; zone_type++) {
5670 struct zone *zone = &pgdat->node_zones[zone_type];
5671 if (populated_zone(zone)) {
5672 node_set_state(nid, N_HIGH_MEMORY);
5673 if (N_NORMAL_MEMORY != N_HIGH_MEMORY &&
5674 zone_type <= ZONE_NORMAL)
5675 node_set_state(nid, N_NORMAL_MEMORY);
5682 * free_area_init_nodes - Initialise all pg_data_t and zone data
5683 * @max_zone_pfn: an array of max PFNs for each zone
5685 * This will call free_area_init_node() for each active node in the system.
5686 * Using the page ranges provided by memblock_set_node(), the size of each
5687 * zone in each node and their holes is calculated. If the maximum PFN
5688 * between two adjacent zones match, it is assumed that the zone is empty.
5689 * For example, if arch_max_dma_pfn == arch_max_dma32_pfn, it is assumed
5690 * that arch_max_dma32_pfn has no pages. It is also assumed that a zone
5691 * starts where the previous one ended. For example, ZONE_DMA32 starts
5692 * at arch_max_dma_pfn.
5694 void __init free_area_init_nodes(unsigned long *max_zone_pfn)
5696 unsigned long start_pfn, end_pfn;
5699 /* Record where the zone boundaries are */
5700 memset(arch_zone_lowest_possible_pfn, 0,
5701 sizeof(arch_zone_lowest_possible_pfn));
5702 memset(arch_zone_highest_possible_pfn, 0,
5703 sizeof(arch_zone_highest_possible_pfn));
5705 start_pfn = find_min_pfn_with_active_regions();
5707 for (i = 0; i < MAX_NR_ZONES; i++) {
5708 if (i == ZONE_MOVABLE)
5711 end_pfn = max(max_zone_pfn[i], start_pfn);
5712 arch_zone_lowest_possible_pfn[i] = start_pfn;
5713 arch_zone_highest_possible_pfn[i] = end_pfn;
5715 start_pfn = end_pfn;
5717 arch_zone_lowest_possible_pfn[ZONE_MOVABLE] = 0;
5718 arch_zone_highest_possible_pfn[ZONE_MOVABLE] = 0;
5720 /* Find the PFNs that ZONE_MOVABLE begins at in each node */
5721 memset(zone_movable_pfn, 0, sizeof(zone_movable_pfn));
5722 find_zone_movable_pfns_for_nodes();
5724 /* Print out the zone ranges */
5725 pr_info("Zone ranges:\n");
5726 for (i = 0; i < MAX_NR_ZONES; i++) {
5727 if (i == ZONE_MOVABLE)
5729 pr_info(" %-8s ", zone_names[i]);
5730 if (arch_zone_lowest_possible_pfn[i] ==
5731 arch_zone_highest_possible_pfn[i])
5734 pr_cont("[mem %#018Lx-%#018Lx]\n",
5735 (u64)arch_zone_lowest_possible_pfn[i]
5737 ((u64)arch_zone_highest_possible_pfn[i]
5738 << PAGE_SHIFT) - 1);
5741 /* Print out the PFNs ZONE_MOVABLE begins at in each node */
5742 pr_info("Movable zone start for each node\n");
5743 for (i = 0; i < MAX_NUMNODES; i++) {
5744 if (zone_movable_pfn[i])
5745 pr_info(" Node %d: %#018Lx\n", i,
5746 (u64)zone_movable_pfn[i] << PAGE_SHIFT);
5749 /* Print out the early node map */
5750 pr_info("Early memory node ranges\n");
5751 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid)
5752 pr_info(" node %3d: [mem %#018Lx-%#018Lx]\n", nid,
5753 (u64)start_pfn << PAGE_SHIFT,
5754 ((u64)end_pfn << PAGE_SHIFT) - 1);
5756 /* Initialise every node */
5757 mminit_verify_pageflags_layout();
5758 setup_nr_node_ids();
5759 for_each_online_node(nid) {
5760 pg_data_t *pgdat = NODE_DATA(nid);
5761 free_area_init_node(nid, NULL,
5762 find_min_pfn_for_node(nid), NULL);
5764 /* Any memory on that node */
5765 if (pgdat->node_present_pages)
5766 node_set_state(nid, N_MEMORY);
5767 check_for_memory(pgdat, nid);
5771 static int __init cmdline_parse_core(char *p, unsigned long *core)
5773 unsigned long long coremem;
5777 coremem = memparse(p, &p);
5778 *core = coremem >> PAGE_SHIFT;
5780 /* Paranoid check that UL is enough for the coremem value */
5781 WARN_ON((coremem >> PAGE_SHIFT) > ULONG_MAX);
5787 * kernelcore=size sets the amount of memory for use for allocations that
5788 * cannot be reclaimed or migrated.
5790 static int __init cmdline_parse_kernelcore(char *p)
5792 return cmdline_parse_core(p, &required_kernelcore);
5796 * movablecore=size sets the amount of memory for use for allocations that
5797 * can be reclaimed or migrated.
5799 static int __init cmdline_parse_movablecore(char *p)
5801 return cmdline_parse_core(p, &required_movablecore);
5804 early_param("kernelcore", cmdline_parse_kernelcore);
5805 early_param("movablecore", cmdline_parse_movablecore);
5807 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
5809 void adjust_managed_page_count(struct page *page, long count)
5811 spin_lock(&managed_page_count_lock);
5812 page_zone(page)->managed_pages += count;
5813 totalram_pages += count;
5814 #ifdef CONFIG_HIGHMEM
5815 if (PageHighMem(page))
5816 totalhigh_pages += count;
5818 spin_unlock(&managed_page_count_lock);
5820 EXPORT_SYMBOL(adjust_managed_page_count);
5822 unsigned long free_reserved_area(void *start, void *end, int poison, char *s)
5825 unsigned long pages = 0;
5827 start = (void *)PAGE_ALIGN((unsigned long)start);
5828 end = (void *)((unsigned long)end & PAGE_MASK);
5829 for (pos = start; pos < end; pos += PAGE_SIZE, pages++) {
5830 if ((unsigned int)poison <= 0xFF)
5831 memset(pos, poison, PAGE_SIZE);
5832 free_reserved_page(virt_to_page(pos));
5836 pr_info("Freeing %s memory: %ldK (%p - %p)\n",
5837 s, pages << (PAGE_SHIFT - 10), start, end);
5841 EXPORT_SYMBOL(free_reserved_area);
5843 #ifdef CONFIG_HIGHMEM
5844 void free_highmem_page(struct page *page)
5846 __free_reserved_page(page);
5848 page_zone(page)->managed_pages++;
5854 void __init mem_init_print_info(const char *str)
5856 unsigned long physpages, codesize, datasize, rosize, bss_size;
5857 unsigned long init_code_size, init_data_size;
5859 physpages = get_num_physpages();
5860 codesize = _etext - _stext;
5861 datasize = _edata - _sdata;
5862 rosize = __end_rodata - __start_rodata;
5863 bss_size = __bss_stop - __bss_start;
5864 init_data_size = __init_end - __init_begin;
5865 init_code_size = _einittext - _sinittext;
5868 * Detect special cases and adjust section sizes accordingly:
5869 * 1) .init.* may be embedded into .data sections
5870 * 2) .init.text.* may be out of [__init_begin, __init_end],
5871 * please refer to arch/tile/kernel/vmlinux.lds.S.
5872 * 3) .rodata.* may be embedded into .text or .data sections.
5874 #define adj_init_size(start, end, size, pos, adj) \
5876 if (start <= pos && pos < end && size > adj) \
5880 adj_init_size(__init_begin, __init_end, init_data_size,
5881 _sinittext, init_code_size);
5882 adj_init_size(_stext, _etext, codesize, _sinittext, init_code_size);
5883 adj_init_size(_sdata, _edata, datasize, __init_begin, init_data_size);
5884 adj_init_size(_stext, _etext, codesize, __start_rodata, rosize);
5885 adj_init_size(_sdata, _edata, datasize, __start_rodata, rosize);
5887 #undef adj_init_size
5889 pr_info("Memory: %luK/%luK available "
5890 "(%luK kernel code, %luK rwdata, %luK rodata, "
5891 "%luK init, %luK bss, %luK reserved, %luK cma-reserved"
5892 #ifdef CONFIG_HIGHMEM
5896 nr_free_pages() << (PAGE_SHIFT-10), physpages << (PAGE_SHIFT-10),
5897 codesize >> 10, datasize >> 10, rosize >> 10,
5898 (init_data_size + init_code_size) >> 10, bss_size >> 10,
5899 (physpages - totalram_pages - totalcma_pages) << (PAGE_SHIFT-10),
5900 totalcma_pages << (PAGE_SHIFT-10),
5901 #ifdef CONFIG_HIGHMEM
5902 totalhigh_pages << (PAGE_SHIFT-10),
5904 str ? ", " : "", str ? str : "");
5908 * set_dma_reserve - set the specified number of pages reserved in the first zone
5909 * @new_dma_reserve: The number of pages to mark reserved
5911 * The per-cpu batchsize and zone watermarks are determined by managed_pages.
5912 * In the DMA zone, a significant percentage may be consumed by kernel image
5913 * and other unfreeable allocations which can skew the watermarks badly. This
5914 * function may optionally be used to account for unfreeable pages in the
5915 * first zone (e.g., ZONE_DMA). The effect will be lower watermarks and
5916 * smaller per-cpu batchsize.
5918 void __init set_dma_reserve(unsigned long new_dma_reserve)
5920 dma_reserve = new_dma_reserve;
5923 void __init free_area_init(unsigned long *zones_size)
5925 free_area_init_node(0, zones_size,
5926 __pa(PAGE_OFFSET) >> PAGE_SHIFT, NULL);
5929 static int page_alloc_cpu_notify(struct notifier_block *self,
5930 unsigned long action, void *hcpu)
5932 int cpu = (unsigned long)hcpu;
5934 if (action == CPU_DEAD || action == CPU_DEAD_FROZEN) {
5935 lru_add_drain_cpu(cpu);
5939 * Spill the event counters of the dead processor
5940 * into the current processors event counters.
5941 * This artificially elevates the count of the current
5944 vm_events_fold_cpu(cpu);
5947 * Zero the differential counters of the dead processor
5948 * so that the vm statistics are consistent.
5950 * This is only okay since the processor is dead and cannot
5951 * race with what we are doing.
5953 cpu_vm_stats_fold(cpu);
5958 void __init page_alloc_init(void)
5960 hotcpu_notifier(page_alloc_cpu_notify, 0);
5964 * calculate_totalreserve_pages - called when sysctl_lowmem_reserve_ratio
5965 * or min_free_kbytes changes.
5967 static void calculate_totalreserve_pages(void)
5969 struct pglist_data *pgdat;
5970 unsigned long reserve_pages = 0;
5971 enum zone_type i, j;
5973 for_each_online_pgdat(pgdat) {
5974 for (i = 0; i < MAX_NR_ZONES; i++) {
5975 struct zone *zone = pgdat->node_zones + i;
5978 /* Find valid and maximum lowmem_reserve in the zone */
5979 for (j = i; j < MAX_NR_ZONES; j++) {
5980 if (zone->lowmem_reserve[j] > max)
5981 max = zone->lowmem_reserve[j];
5984 /* we treat the high watermark as reserved pages. */
5985 max += high_wmark_pages(zone);
5987 if (max > zone->managed_pages)
5988 max = zone->managed_pages;
5990 zone->totalreserve_pages = max;
5992 reserve_pages += max;
5995 totalreserve_pages = reserve_pages;
5999 * setup_per_zone_lowmem_reserve - called whenever
6000 * sysctl_lowmem_reserve_ratio changes. Ensures that each zone
6001 * has a correct pages reserved value, so an adequate number of
6002 * pages are left in the zone after a successful __alloc_pages().
6004 static void setup_per_zone_lowmem_reserve(void)
6006 struct pglist_data *pgdat;
6007 enum zone_type j, idx;
6009 for_each_online_pgdat(pgdat) {
6010 for (j = 0; j < MAX_NR_ZONES; j++) {
6011 struct zone *zone = pgdat->node_zones + j;
6012 unsigned long managed_pages = zone->managed_pages;
6014 zone->lowmem_reserve[j] = 0;
6018 struct zone *lower_zone;
6022 if (sysctl_lowmem_reserve_ratio[idx] < 1)
6023 sysctl_lowmem_reserve_ratio[idx] = 1;
6025 lower_zone = pgdat->node_zones + idx;
6026 lower_zone->lowmem_reserve[j] = managed_pages /
6027 sysctl_lowmem_reserve_ratio[idx];
6028 managed_pages += lower_zone->managed_pages;
6033 /* update totalreserve_pages */
6034 calculate_totalreserve_pages();
6037 static void __setup_per_zone_wmarks(void)
6039 unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
6040 unsigned long pages_low = extra_free_kbytes >> (PAGE_SHIFT - 10);
6041 unsigned long lowmem_pages = 0;
6043 unsigned long flags;
6045 /* Calculate total number of !ZONE_HIGHMEM pages */
6046 for_each_zone(zone) {
6047 if (!is_highmem(zone))
6048 lowmem_pages += zone->managed_pages;
6051 for_each_zone(zone) {
6054 spin_lock_irqsave(&zone->lock, flags);
6055 min = (u64)pages_min * zone->managed_pages;
6056 do_div(min, lowmem_pages);
6057 low = (u64)pages_low * zone->managed_pages;
6058 do_div(low, vm_total_pages);
6060 if (is_highmem(zone)) {
6062 * __GFP_HIGH and PF_MEMALLOC allocations usually don't
6063 * need highmem pages, so cap pages_min to a small
6066 * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN)
6067 * deltas control asynch page reclaim, and so should
6068 * not be capped for highmem.
6070 unsigned long min_pages;
6072 min_pages = zone->managed_pages / 1024;
6073 min_pages = clamp(min_pages, SWAP_CLUSTER_MAX, 128UL);
6074 zone->watermark[WMARK_MIN] = min_pages;
6077 * If it's a lowmem zone, reserve a number of pages
6078 * proportionate to the zone's size.
6080 zone->watermark[WMARK_MIN] = min;
6083 zone->watermark[WMARK_LOW] = min_wmark_pages(zone) +
6085 zone->watermark[WMARK_HIGH] = min_wmark_pages(zone) +
6088 __mod_zone_page_state(zone, NR_ALLOC_BATCH,
6089 high_wmark_pages(zone) - low_wmark_pages(zone) -
6090 atomic_long_read(&zone->vm_stat[NR_ALLOC_BATCH]));
6092 spin_unlock_irqrestore(&zone->lock, flags);
6095 /* update totalreserve_pages */
6096 calculate_totalreserve_pages();
6100 * setup_per_zone_wmarks - called when min_free_kbytes changes
6101 * or when memory is hot-{added|removed}
6103 * Ensures that the watermark[min,low,high] values for each zone are set
6104 * correctly with respect to min_free_kbytes.
6106 void setup_per_zone_wmarks(void)
6108 mutex_lock(&zonelists_mutex);
6109 __setup_per_zone_wmarks();
6110 mutex_unlock(&zonelists_mutex);
6114 * The inactive anon list should be small enough that the VM never has to
6115 * do too much work, but large enough that each inactive page has a chance
6116 * to be referenced again before it is swapped out.
6118 * The inactive_anon ratio is the target ratio of ACTIVE_ANON to
6119 * INACTIVE_ANON pages on this zone's LRU, maintained by the
6120 * pageout code. A zone->inactive_ratio of 3 means 3:1 or 25% of
6121 * the anonymous pages are kept on the inactive list.
6124 * memory ratio inactive anon
6125 * -------------------------------------
6134 static void __meminit calculate_zone_inactive_ratio(struct zone *zone)
6136 unsigned int gb, ratio;
6138 /* Zone size in gigabytes */
6139 gb = zone->managed_pages >> (30 - PAGE_SHIFT);
6141 ratio = int_sqrt(10 * gb);
6145 zone->inactive_ratio = ratio;
6148 static void __meminit setup_per_zone_inactive_ratio(void)
6153 calculate_zone_inactive_ratio(zone);
6157 * Initialise min_free_kbytes.
6159 * For small machines we want it small (128k min). For large machines
6160 * we want it large (64MB max). But it is not linear, because network
6161 * bandwidth does not increase linearly with machine size. We use
6163 * min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
6164 * min_free_kbytes = sqrt(lowmem_kbytes * 16)
6180 int __meminit init_per_zone_wmark_min(void)
6182 unsigned long lowmem_kbytes;
6183 int new_min_free_kbytes;
6185 lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
6186 new_min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
6188 if (new_min_free_kbytes > user_min_free_kbytes) {
6189 min_free_kbytes = new_min_free_kbytes;
6190 if (min_free_kbytes < 128)
6191 min_free_kbytes = 128;
6192 if (min_free_kbytes > 65536)
6193 min_free_kbytes = 65536;
6195 pr_warn("min_free_kbytes is not updated to %d because user defined value %d is preferred\n",
6196 new_min_free_kbytes, user_min_free_kbytes);
6198 setup_per_zone_wmarks();
6199 refresh_zone_stat_thresholds();
6200 setup_per_zone_lowmem_reserve();
6201 setup_per_zone_inactive_ratio();
6204 core_initcall(init_per_zone_wmark_min)
6207 * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
6208 * that we can call two helper functions whenever min_free_kbytes
6209 * or extra_free_kbytes changes.
6211 int min_free_kbytes_sysctl_handler(struct ctl_table *table, int write,
6212 void __user *buffer, size_t *length, loff_t *ppos)
6216 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
6221 user_min_free_kbytes = min_free_kbytes;
6222 setup_per_zone_wmarks();
6228 int sysctl_min_unmapped_ratio_sysctl_handler(struct ctl_table *table, int write,
6229 void __user *buffer, size_t *length, loff_t *ppos)
6234 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
6239 zone->min_unmapped_pages = (zone->managed_pages *
6240 sysctl_min_unmapped_ratio) / 100;
6244 int sysctl_min_slab_ratio_sysctl_handler(struct ctl_table *table, int write,
6245 void __user *buffer, size_t *length, loff_t *ppos)
6250 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
6255 zone->min_slab_pages = (zone->managed_pages *
6256 sysctl_min_slab_ratio) / 100;
6262 * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
6263 * proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
6264 * whenever sysctl_lowmem_reserve_ratio changes.
6266 * The reserve ratio obviously has absolutely no relation with the
6267 * minimum watermarks. The lowmem reserve ratio can only make sense
6268 * if in function of the boot time zone sizes.
6270 int lowmem_reserve_ratio_sysctl_handler(struct ctl_table *table, int write,
6271 void __user *buffer, size_t *length, loff_t *ppos)
6273 proc_dointvec_minmax(table, write, buffer, length, ppos);
6274 setup_per_zone_lowmem_reserve();
6279 * percpu_pagelist_fraction - changes the pcp->high for each zone on each
6280 * cpu. It is the fraction of total pages in each zone that a hot per cpu
6281 * pagelist can have before it gets flushed back to buddy allocator.
6283 int percpu_pagelist_fraction_sysctl_handler(struct ctl_table *table, int write,
6284 void __user *buffer, size_t *length, loff_t *ppos)
6287 int old_percpu_pagelist_fraction;
6290 mutex_lock(&pcp_batch_high_lock);
6291 old_percpu_pagelist_fraction = percpu_pagelist_fraction;
6293 ret = proc_dointvec_minmax(table, write, buffer, length, ppos);
6294 if (!write || ret < 0)
6297 /* Sanity checking to avoid pcp imbalance */
6298 if (percpu_pagelist_fraction &&
6299 percpu_pagelist_fraction < MIN_PERCPU_PAGELIST_FRACTION) {
6300 percpu_pagelist_fraction = old_percpu_pagelist_fraction;
6306 if (percpu_pagelist_fraction == old_percpu_pagelist_fraction)
6309 for_each_populated_zone(zone) {
6312 for_each_possible_cpu(cpu)
6313 pageset_set_high_and_batch(zone,
6314 per_cpu_ptr(zone->pageset, cpu));
6317 mutex_unlock(&pcp_batch_high_lock);
6322 int hashdist = HASHDIST_DEFAULT;
6324 static int __init set_hashdist(char *str)
6328 hashdist = simple_strtoul(str, &str, 0);
6331 __setup("hashdist=", set_hashdist);
6335 * allocate a large system hash table from bootmem
6336 * - it is assumed that the hash table must contain an exact power-of-2
6337 * quantity of entries
6338 * - limit is the number of hash buckets, not the total allocation size
6340 void *__init alloc_large_system_hash(const char *tablename,
6341 unsigned long bucketsize,
6342 unsigned long numentries,
6345 unsigned int *_hash_shift,
6346 unsigned int *_hash_mask,
6347 unsigned long low_limit,
6348 unsigned long high_limit)
6350 unsigned long long max = high_limit;
6351 unsigned long log2qty, size;
6354 /* allow the kernel cmdline to have a say */
6356 /* round applicable memory size up to nearest megabyte */
6357 numentries = nr_kernel_pages;
6359 /* It isn't necessary when PAGE_SIZE >= 1MB */
6360 if (PAGE_SHIFT < 20)
6361 numentries = round_up(numentries, (1<<20)/PAGE_SIZE);
6363 /* limit to 1 bucket per 2^scale bytes of low memory */
6364 if (scale > PAGE_SHIFT)
6365 numentries >>= (scale - PAGE_SHIFT);
6367 numentries <<= (PAGE_SHIFT - scale);
6369 /* Make sure we've got at least a 0-order allocation.. */
6370 if (unlikely(flags & HASH_SMALL)) {
6371 /* Makes no sense without HASH_EARLY */
6372 WARN_ON(!(flags & HASH_EARLY));
6373 if (!(numentries >> *_hash_shift)) {
6374 numentries = 1UL << *_hash_shift;
6375 BUG_ON(!numentries);
6377 } else if (unlikely((numentries * bucketsize) < PAGE_SIZE))
6378 numentries = PAGE_SIZE / bucketsize;
6380 numentries = roundup_pow_of_two(numentries);
6382 /* limit allocation size to 1/16 total memory by default */
6384 max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
6385 do_div(max, bucketsize);
6387 max = min(max, 0x80000000ULL);
6389 if (numentries < low_limit)
6390 numentries = low_limit;
6391 if (numentries > max)
6394 log2qty = ilog2(numentries);
6397 size = bucketsize << log2qty;
6398 if (flags & HASH_EARLY)
6399 table = memblock_virt_alloc_nopanic(size, 0);
6401 table = __vmalloc(size, GFP_ATOMIC, PAGE_KERNEL);
6404 * If bucketsize is not a power-of-two, we may free
6405 * some pages at the end of hash table which
6406 * alloc_pages_exact() automatically does
6408 if (get_order(size) < MAX_ORDER) {
6409 table = alloc_pages_exact(size, GFP_ATOMIC);
6410 kmemleak_alloc(table, size, 1, GFP_ATOMIC);
6413 } while (!table && size > PAGE_SIZE && --log2qty);
6416 panic("Failed to allocate %s hash table\n", tablename);
6418 printk(KERN_INFO "%s hash table entries: %ld (order: %d, %lu bytes)\n",
6421 ilog2(size) - PAGE_SHIFT,
6425 *_hash_shift = log2qty;
6427 *_hash_mask = (1 << log2qty) - 1;
6432 /* Return a pointer to the bitmap storing bits affecting a block of pages */
6433 static inline unsigned long *get_pageblock_bitmap(struct zone *zone,
6436 #ifdef CONFIG_SPARSEMEM
6437 return __pfn_to_section(pfn)->pageblock_flags;
6439 return zone->pageblock_flags;
6440 #endif /* CONFIG_SPARSEMEM */
6443 static inline int pfn_to_bitidx(struct zone *zone, unsigned long pfn)
6445 #ifdef CONFIG_SPARSEMEM
6446 pfn &= (PAGES_PER_SECTION-1);
6447 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
6449 pfn = pfn - round_down(zone->zone_start_pfn, pageblock_nr_pages);
6450 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
6451 #endif /* CONFIG_SPARSEMEM */
6455 * get_pfnblock_flags_mask - Return the requested group of flags for the pageblock_nr_pages block of pages
6456 * @page: The page within the block of interest
6457 * @pfn: The target page frame number
6458 * @end_bitidx: The last bit of interest to retrieve
6459 * @mask: mask of bits that the caller is interested in
6461 * Return: pageblock_bits flags
6463 unsigned long get_pfnblock_flags_mask(struct page *page, unsigned long pfn,
6464 unsigned long end_bitidx,
6468 unsigned long *bitmap;
6469 unsigned long bitidx, word_bitidx;
6472 zone = page_zone(page);
6473 bitmap = get_pageblock_bitmap(zone, pfn);
6474 bitidx = pfn_to_bitidx(zone, pfn);
6475 word_bitidx = bitidx / BITS_PER_LONG;
6476 bitidx &= (BITS_PER_LONG-1);
6478 word = bitmap[word_bitidx];
6479 bitidx += end_bitidx;
6480 return (word >> (BITS_PER_LONG - bitidx - 1)) & mask;
6484 * set_pfnblock_flags_mask - Set the requested group of flags for a pageblock_nr_pages block of pages
6485 * @page: The page within the block of interest
6486 * @flags: The flags to set
6487 * @pfn: The target page frame number
6488 * @end_bitidx: The last bit of interest
6489 * @mask: mask of bits that the caller is interested in
6491 void set_pfnblock_flags_mask(struct page *page, unsigned long flags,
6493 unsigned long end_bitidx,
6497 unsigned long *bitmap;
6498 unsigned long bitidx, word_bitidx;
6499 unsigned long old_word, word;
6501 BUILD_BUG_ON(NR_PAGEBLOCK_BITS != 4);
6503 zone = page_zone(page);
6504 bitmap = get_pageblock_bitmap(zone, pfn);
6505 bitidx = pfn_to_bitidx(zone, pfn);
6506 word_bitidx = bitidx / BITS_PER_LONG;
6507 bitidx &= (BITS_PER_LONG-1);
6509 VM_BUG_ON_PAGE(!zone_spans_pfn(zone, pfn), page);
6511 bitidx += end_bitidx;
6512 mask <<= (BITS_PER_LONG - bitidx - 1);
6513 flags <<= (BITS_PER_LONG - bitidx - 1);
6515 word = READ_ONCE(bitmap[word_bitidx]);
6517 old_word = cmpxchg(&bitmap[word_bitidx], word, (word & ~mask) | flags);
6518 if (word == old_word)
6525 * This function checks whether pageblock includes unmovable pages or not.
6526 * If @count is not zero, it is okay to include less @count unmovable pages
6528 * PageLRU check without isolation or lru_lock could race so that
6529 * MIGRATE_MOVABLE block might include unmovable pages. It means you can't
6530 * expect this function should be exact.
6532 bool has_unmovable_pages(struct zone *zone, struct page *page, int count,
6533 bool skip_hwpoisoned_pages)
6535 unsigned long pfn, iter, found;
6539 * For avoiding noise data, lru_add_drain_all() should be called
6540 * If ZONE_MOVABLE, the zone never contains unmovable pages
6542 if (zone_idx(zone) == ZONE_MOVABLE)
6544 mt = get_pageblock_migratetype(page);
6545 if (mt == MIGRATE_MOVABLE || is_migrate_cma(mt))
6548 pfn = page_to_pfn(page);
6549 for (found = 0, iter = 0; iter < pageblock_nr_pages; iter++) {
6550 unsigned long check = pfn + iter;
6552 if (!pfn_valid_within(check))
6555 page = pfn_to_page(check);
6558 * Hugepages are not in LRU lists, but they're movable.
6559 * We need not scan over tail pages bacause we don't
6560 * handle each tail page individually in migration.
6562 if (PageHuge(page)) {
6563 iter = round_up(iter + 1, 1<<compound_order(page)) - 1;
6568 * We can't use page_count without pin a page
6569 * because another CPU can free compound page.
6570 * This check already skips compound tails of THP
6571 * because their page->_count is zero at all time.
6573 if (!atomic_read(&page->_count)) {
6574 if (PageBuddy(page))
6575 iter += (1 << page_order(page)) - 1;
6580 * The HWPoisoned page may be not in buddy system, and
6581 * page_count() is not 0.
6583 if (skip_hwpoisoned_pages && PageHWPoison(page))
6589 * If there are RECLAIMABLE pages, we need to check
6590 * it. But now, memory offline itself doesn't call
6591 * shrink_node_slabs() and it still to be fixed.
6594 * If the page is not RAM, page_count()should be 0.
6595 * we don't need more check. This is an _used_ not-movable page.
6597 * The problematic thing here is PG_reserved pages. PG_reserved
6598 * is set to both of a memory hole page and a _used_ kernel
6607 bool is_pageblock_removable_nolock(struct page *page)
6613 * We have to be careful here because we are iterating over memory
6614 * sections which are not zone aware so we might end up outside of
6615 * the zone but still within the section.
6616 * We have to take care about the node as well. If the node is offline
6617 * its NODE_DATA will be NULL - see page_zone.
6619 if (!node_online(page_to_nid(page)))
6622 zone = page_zone(page);
6623 pfn = page_to_pfn(page);
6624 if (!zone_spans_pfn(zone, pfn))
6627 return !has_unmovable_pages(zone, page, 0, true);
6632 static unsigned long pfn_max_align_down(unsigned long pfn)
6634 return pfn & ~(max_t(unsigned long, MAX_ORDER_NR_PAGES,
6635 pageblock_nr_pages) - 1);
6638 static unsigned long pfn_max_align_up(unsigned long pfn)
6640 return ALIGN(pfn, max_t(unsigned long, MAX_ORDER_NR_PAGES,
6641 pageblock_nr_pages));
6644 /* [start, end) must belong to a single zone. */
6645 static int __alloc_contig_migrate_range(struct compact_control *cc,
6646 unsigned long start, unsigned long end)
6648 /* This function is based on compact_zone() from compaction.c. */
6649 unsigned long nr_reclaimed;
6650 unsigned long pfn = start;
6651 unsigned int tries = 0;
6656 while (pfn < end || !list_empty(&cc->migratepages)) {
6657 if (fatal_signal_pending(current)) {
6662 if (list_empty(&cc->migratepages)) {
6663 cc->nr_migratepages = 0;
6664 pfn = isolate_migratepages_range(cc, pfn, end);
6670 } else if (++tries == 5) {
6671 ret = ret < 0 ? ret : -EBUSY;
6675 nr_reclaimed = reclaim_clean_pages_from_list(cc->zone,
6677 cc->nr_migratepages -= nr_reclaimed;
6679 ret = migrate_pages(&cc->migratepages, alloc_migrate_target,
6680 NULL, 0, cc->mode, MR_CMA);
6683 putback_movable_pages(&cc->migratepages);
6690 * alloc_contig_range() -- tries to allocate given range of pages
6691 * @start: start PFN to allocate
6692 * @end: one-past-the-last PFN to allocate
6693 * @migratetype: migratetype of the underlaying pageblocks (either
6694 * #MIGRATE_MOVABLE or #MIGRATE_CMA). All pageblocks
6695 * in range must have the same migratetype and it must
6696 * be either of the two.
6698 * The PFN range does not have to be pageblock or MAX_ORDER_NR_PAGES
6699 * aligned, however it's the caller's responsibility to guarantee that
6700 * we are the only thread that changes migrate type of pageblocks the
6703 * The PFN range must belong to a single zone.
6705 * Returns zero on success or negative error code. On success all
6706 * pages which PFN is in [start, end) are allocated for the caller and
6707 * need to be freed with free_contig_range().
6709 int alloc_contig_range(unsigned long start, unsigned long end,
6710 unsigned migratetype)
6712 unsigned long outer_start, outer_end;
6716 struct compact_control cc = {
6717 .nr_migratepages = 0,
6719 .zone = page_zone(pfn_to_page(start)),
6720 .mode = MIGRATE_SYNC,
6721 .ignore_skip_hint = true,
6723 INIT_LIST_HEAD(&cc.migratepages);
6726 * What we do here is we mark all pageblocks in range as
6727 * MIGRATE_ISOLATE. Because pageblock and max order pages may
6728 * have different sizes, and due to the way page allocator
6729 * work, we align the range to biggest of the two pages so
6730 * that page allocator won't try to merge buddies from
6731 * different pageblocks and change MIGRATE_ISOLATE to some
6732 * other migration type.
6734 * Once the pageblocks are marked as MIGRATE_ISOLATE, we
6735 * migrate the pages from an unaligned range (ie. pages that
6736 * we are interested in). This will put all the pages in
6737 * range back to page allocator as MIGRATE_ISOLATE.
6739 * When this is done, we take the pages in range from page
6740 * allocator removing them from the buddy system. This way
6741 * page allocator will never consider using them.
6743 * This lets us mark the pageblocks back as
6744 * MIGRATE_CMA/MIGRATE_MOVABLE so that free pages in the
6745 * aligned range but not in the unaligned, original range are
6746 * put back to page allocator so that buddy can use them.
6749 ret = start_isolate_page_range(pfn_max_align_down(start),
6750 pfn_max_align_up(end), migratetype,
6755 ret = __alloc_contig_migrate_range(&cc, start, end);
6760 * Pages from [start, end) are within a MAX_ORDER_NR_PAGES
6761 * aligned blocks that are marked as MIGRATE_ISOLATE. What's
6762 * more, all pages in [start, end) are free in page allocator.
6763 * What we are going to do is to allocate all pages from
6764 * [start, end) (that is remove them from page allocator).
6766 * The only problem is that pages at the beginning and at the
6767 * end of interesting range may be not aligned with pages that
6768 * page allocator holds, ie. they can be part of higher order
6769 * pages. Because of this, we reserve the bigger range and
6770 * once this is done free the pages we are not interested in.
6772 * We don't have to hold zone->lock here because the pages are
6773 * isolated thus they won't get removed from buddy.
6776 lru_add_drain_all();
6777 drain_all_pages(cc.zone);
6780 outer_start = start;
6781 while (!PageBuddy(pfn_to_page(outer_start))) {
6782 if (++order >= MAX_ORDER) {
6786 outer_start &= ~0UL << order;
6789 /* Make sure the range is really isolated. */
6790 if (test_pages_isolated(outer_start, end, false)) {
6791 pr_info("%s: [%lx, %lx) PFNs busy\n",
6792 __func__, outer_start, end);
6797 /* Grab isolated pages from freelists. */
6798 outer_end = isolate_freepages_range(&cc, outer_start, end);
6804 /* Free head and tail (if any) */
6805 if (start != outer_start)
6806 free_contig_range(outer_start, start - outer_start);
6807 if (end != outer_end)
6808 free_contig_range(end, outer_end - end);
6811 undo_isolate_page_range(pfn_max_align_down(start),
6812 pfn_max_align_up(end), migratetype);
6816 void free_contig_range(unsigned long pfn, unsigned nr_pages)
6818 unsigned int count = 0;
6820 for (; nr_pages--; pfn++) {
6821 struct page *page = pfn_to_page(pfn);
6823 count += page_count(page) != 1;
6826 WARN(count != 0, "%d pages are still in use!\n", count);
6830 #ifdef CONFIG_MEMORY_HOTPLUG
6832 * The zone indicated has a new number of managed_pages; batch sizes and percpu
6833 * page high values need to be recalulated.
6835 void __meminit zone_pcp_update(struct zone *zone)
6838 mutex_lock(&pcp_batch_high_lock);
6839 for_each_possible_cpu(cpu)
6840 pageset_set_high_and_batch(zone,
6841 per_cpu_ptr(zone->pageset, cpu));
6842 mutex_unlock(&pcp_batch_high_lock);
6846 void zone_pcp_reset(struct zone *zone)
6848 unsigned long flags;
6850 struct per_cpu_pageset *pset;
6852 /* avoid races with drain_pages() */
6853 local_irq_save(flags);
6854 if (zone->pageset != &boot_pageset) {
6855 for_each_online_cpu(cpu) {
6856 pset = per_cpu_ptr(zone->pageset, cpu);
6857 drain_zonestat(zone, pset);
6859 free_percpu(zone->pageset);
6860 zone->pageset = &boot_pageset;
6862 local_irq_restore(flags);
6865 #ifdef CONFIG_MEMORY_HOTREMOVE
6867 * All pages in the range must be isolated before calling this.
6870 __offline_isolated_pages(unsigned long start_pfn, unsigned long end_pfn)
6874 unsigned int order, i;
6876 unsigned long flags;
6877 /* find the first valid pfn */
6878 for (pfn = start_pfn; pfn < end_pfn; pfn++)
6883 zone = page_zone(pfn_to_page(pfn));
6884 spin_lock_irqsave(&zone->lock, flags);
6886 while (pfn < end_pfn) {
6887 if (!pfn_valid(pfn)) {
6891 page = pfn_to_page(pfn);
6893 * The HWPoisoned page may be not in buddy system, and
6894 * page_count() is not 0.
6896 if (unlikely(!PageBuddy(page) && PageHWPoison(page))) {
6898 SetPageReserved(page);
6902 BUG_ON(page_count(page));
6903 BUG_ON(!PageBuddy(page));
6904 order = page_order(page);
6905 #ifdef CONFIG_DEBUG_VM
6906 printk(KERN_INFO "remove from free list %lx %d %lx\n",
6907 pfn, 1 << order, end_pfn);
6909 list_del(&page->lru);
6910 rmv_page_order(page);
6911 zone->free_area[order].nr_free--;
6912 for (i = 0; i < (1 << order); i++)
6913 SetPageReserved((page+i));
6914 pfn += (1 << order);
6916 spin_unlock_irqrestore(&zone->lock, flags);
6920 #ifdef CONFIG_MEMORY_FAILURE
6921 bool is_free_buddy_page(struct page *page)
6923 struct zone *zone = page_zone(page);
6924 unsigned long pfn = page_to_pfn(page);
6925 unsigned long flags;
6928 spin_lock_irqsave(&zone->lock, flags);
6929 for (order = 0; order < MAX_ORDER; order++) {
6930 struct page *page_head = page - (pfn & ((1 << order) - 1));
6932 if (PageBuddy(page_head) && page_order(page_head) >= order)
6935 spin_unlock_irqrestore(&zone->lock, flags);
6937 return order < MAX_ORDER;