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 * When calculating the number of globally allowed dirty pages, there
119 * is a certain number of per-zone reserves that should not be
120 * considered dirtyable memory. This is the sum of those reserves
121 * over all existing zones that contribute dirtyable memory.
123 unsigned long dirty_balance_reserve __read_mostly;
125 int percpu_pagelist_fraction;
126 gfp_t gfp_allowed_mask __read_mostly = GFP_BOOT_MASK;
129 * A cached value of the page's pageblock's migratetype, used when the page is
130 * put on a pcplist. Used to avoid the pageblock migratetype lookup when
131 * freeing from pcplists in most cases, at the cost of possibly becoming stale.
132 * Also the migratetype set in the page does not necessarily match the pcplist
133 * index, e.g. page might have MIGRATE_CMA set but be on a pcplist with any
134 * other index - this ensures that it will be put on the correct CMA freelist.
136 static inline int get_pcppage_migratetype(struct page *page)
141 static inline void set_pcppage_migratetype(struct page *page, int migratetype)
143 page->index = migratetype;
146 #ifdef CONFIG_PM_SLEEP
148 * The following functions are used by the suspend/hibernate code to temporarily
149 * change gfp_allowed_mask in order to avoid using I/O during memory allocations
150 * while devices are suspended. To avoid races with the suspend/hibernate code,
151 * they should always be called with pm_mutex held (gfp_allowed_mask also should
152 * only be modified with pm_mutex held, unless the suspend/hibernate code is
153 * guaranteed not to run in parallel with that modification).
156 static gfp_t saved_gfp_mask;
158 void pm_restore_gfp_mask(void)
160 WARN_ON(!mutex_is_locked(&pm_mutex));
161 if (saved_gfp_mask) {
162 gfp_allowed_mask = saved_gfp_mask;
167 void pm_restrict_gfp_mask(void)
169 WARN_ON(!mutex_is_locked(&pm_mutex));
170 WARN_ON(saved_gfp_mask);
171 saved_gfp_mask = gfp_allowed_mask;
172 gfp_allowed_mask &= ~(__GFP_IO | __GFP_FS);
175 bool pm_suspended_storage(void)
177 if ((gfp_allowed_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
181 #endif /* CONFIG_PM_SLEEP */
183 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
184 unsigned int pageblock_order __read_mostly;
187 static void __free_pages_ok(struct page *page, unsigned int order);
190 * results with 256, 32 in the lowmem_reserve sysctl:
191 * 1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
192 * 1G machine -> (16M dma, 784M normal, 224M high)
193 * NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
194 * HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
195 * HIGHMEM allocation will leave (224M+784M)/256 of ram reserved in ZONE_DMA
197 * TBD: should special case ZONE_DMA32 machines here - in those we normally
198 * don't need any ZONE_NORMAL reservation
200 int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES-1] = {
201 #ifdef CONFIG_ZONE_DMA
204 #ifdef CONFIG_ZONE_DMA32
207 #ifdef CONFIG_HIGHMEM
213 EXPORT_SYMBOL(totalram_pages);
215 static char * const zone_names[MAX_NR_ZONES] = {
216 #ifdef CONFIG_ZONE_DMA
219 #ifdef CONFIG_ZONE_DMA32
223 #ifdef CONFIG_HIGHMEM
227 #ifdef CONFIG_ZONE_DEVICE
232 static void free_compound_page(struct page *page);
233 compound_page_dtor * const compound_page_dtors[] = {
236 #ifdef CONFIG_HUGETLB_PAGE
241 int min_free_kbytes = 1024;
242 int user_min_free_kbytes = -1;
244 static unsigned long __meminitdata nr_kernel_pages;
245 static unsigned long __meminitdata nr_all_pages;
246 static unsigned long __meminitdata dma_reserve;
248 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
249 static unsigned long __meminitdata arch_zone_lowest_possible_pfn[MAX_NR_ZONES];
250 static unsigned long __meminitdata arch_zone_highest_possible_pfn[MAX_NR_ZONES];
251 static unsigned long __initdata required_kernelcore;
252 static unsigned long __initdata required_movablecore;
253 static unsigned long __meminitdata zone_movable_pfn[MAX_NUMNODES];
255 /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
257 EXPORT_SYMBOL(movable_zone);
258 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
261 int nr_node_ids __read_mostly = MAX_NUMNODES;
262 int nr_online_nodes __read_mostly = 1;
263 EXPORT_SYMBOL(nr_node_ids);
264 EXPORT_SYMBOL(nr_online_nodes);
267 int page_group_by_mobility_disabled __read_mostly;
269 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
270 static inline void reset_deferred_meminit(pg_data_t *pgdat)
272 unsigned long max_initialise;
273 unsigned long reserved_lowmem;
276 * Initialise at least 2G of a node but also take into account that
277 * two large system hashes that can take up 1GB for 0.25TB/node.
279 max_initialise = max(2UL << (30 - PAGE_SHIFT),
280 (pgdat->node_spanned_pages >> 8));
283 * Compensate the all the memblock reservations (e.g. crash kernel)
284 * from the initial estimation to make sure we will initialize enough
287 reserved_lowmem = memblock_reserved_memory_within(pgdat->node_start_pfn,
288 pgdat->node_start_pfn + max_initialise);
289 max_initialise += reserved_lowmem;
291 pgdat->static_init_size = min(max_initialise, pgdat->node_spanned_pages);
292 pgdat->first_deferred_pfn = ULONG_MAX;
295 /* Returns true if the struct page for the pfn is uninitialised */
296 static inline bool __meminit early_page_uninitialised(unsigned long pfn)
298 int nid = early_pfn_to_nid(pfn);
300 if (node_online(nid) && pfn >= NODE_DATA(nid)->first_deferred_pfn)
306 static inline bool early_page_nid_uninitialised(unsigned long pfn, int nid)
308 if (pfn >= NODE_DATA(nid)->first_deferred_pfn)
315 * Returns false when the remaining initialisation should be deferred until
316 * later in the boot cycle when it can be parallelised.
318 static inline bool update_defer_init(pg_data_t *pgdat,
319 unsigned long pfn, unsigned long zone_end,
320 unsigned long *nr_initialised)
322 /* Always populate low zones for address-contrained allocations */
323 if (zone_end < pgdat_end_pfn(pgdat))
325 /* Initialise at least 2G of the highest zone */
327 if ((*nr_initialised > pgdat->static_init_size) &&
328 (pfn & (PAGES_PER_SECTION - 1)) == 0) {
329 pgdat->first_deferred_pfn = pfn;
336 static inline void reset_deferred_meminit(pg_data_t *pgdat)
340 static inline bool early_page_uninitialised(unsigned long pfn)
345 static inline bool early_page_nid_uninitialised(unsigned long pfn, int nid)
350 static inline bool update_defer_init(pg_data_t *pgdat,
351 unsigned long pfn, unsigned long zone_end,
352 unsigned long *nr_initialised)
359 void set_pageblock_migratetype(struct page *page, int migratetype)
361 if (unlikely(page_group_by_mobility_disabled &&
362 migratetype < MIGRATE_PCPTYPES))
363 migratetype = MIGRATE_UNMOVABLE;
365 set_pageblock_flags_group(page, (unsigned long)migratetype,
366 PB_migrate, PB_migrate_end);
369 #ifdef CONFIG_DEBUG_VM
370 static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
374 unsigned long pfn = page_to_pfn(page);
375 unsigned long sp, start_pfn;
378 seq = zone_span_seqbegin(zone);
379 start_pfn = zone->zone_start_pfn;
380 sp = zone->spanned_pages;
381 if (!zone_spans_pfn(zone, pfn))
383 } while (zone_span_seqretry(zone, seq));
386 pr_err("page 0x%lx outside node %d zone %s [ 0x%lx - 0x%lx ]\n",
387 pfn, zone_to_nid(zone), zone->name,
388 start_pfn, start_pfn + sp);
393 static int page_is_consistent(struct zone *zone, struct page *page)
395 if (!pfn_valid_within(page_to_pfn(page)))
397 if (zone != page_zone(page))
403 * Temporary debugging check for pages not lying within a given zone.
405 static int bad_range(struct zone *zone, struct page *page)
407 if (page_outside_zone_boundaries(zone, page))
409 if (!page_is_consistent(zone, page))
415 static inline int bad_range(struct zone *zone, struct page *page)
421 static void bad_page(struct page *page, const char *reason,
422 unsigned long bad_flags)
424 static unsigned long resume;
425 static unsigned long nr_shown;
426 static unsigned long nr_unshown;
428 /* Don't complain about poisoned pages */
429 if (PageHWPoison(page)) {
430 page_mapcount_reset(page); /* remove PageBuddy */
435 * Allow a burst of 60 reports, then keep quiet for that minute;
436 * or allow a steady drip of one report per second.
438 if (nr_shown == 60) {
439 if (time_before(jiffies, resume)) {
445 "BUG: Bad page state: %lu messages suppressed\n",
452 resume = jiffies + 60 * HZ;
454 printk(KERN_ALERT "BUG: Bad page state in process %s pfn:%05lx\n",
455 current->comm, page_to_pfn(page));
456 dump_page_badflags(page, reason, bad_flags);
461 /* Leave bad fields for debug, except PageBuddy could make trouble */
462 page_mapcount_reset(page); /* remove PageBuddy */
463 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
467 * Higher-order pages are called "compound pages". They are structured thusly:
469 * The first PAGE_SIZE page is called the "head page" and have PG_head set.
471 * The remaining PAGE_SIZE pages are called "tail pages". PageTail() is encoded
472 * in bit 0 of page->compound_head. The rest of bits is pointer to head page.
474 * The first tail page's ->compound_dtor holds the offset in array of compound
475 * page destructors. See compound_page_dtors.
477 * The first tail page's ->compound_order holds the order of allocation.
478 * This usage means that zero-order pages may not be compound.
481 static void free_compound_page(struct page *page)
483 __free_pages_ok(page, compound_order(page));
486 void prep_compound_page(struct page *page, unsigned int order)
489 int nr_pages = 1 << order;
491 set_compound_page_dtor(page, COMPOUND_PAGE_DTOR);
492 set_compound_order(page, order);
494 for (i = 1; i < nr_pages; i++) {
495 struct page *p = page + i;
496 set_page_count(p, 0);
497 set_compound_head(p, page);
501 #ifdef CONFIG_DEBUG_PAGEALLOC
502 unsigned int _debug_guardpage_minorder;
503 bool _debug_pagealloc_enabled __read_mostly;
504 bool _debug_guardpage_enabled __read_mostly;
506 static int __init early_debug_pagealloc(char *buf)
511 if (strcmp(buf, "on") == 0)
512 _debug_pagealloc_enabled = true;
516 early_param("debug_pagealloc", early_debug_pagealloc);
518 static bool need_debug_guardpage(void)
520 /* If we don't use debug_pagealloc, we don't need guard page */
521 if (!debug_pagealloc_enabled())
527 static void init_debug_guardpage(void)
529 if (!debug_pagealloc_enabled())
532 _debug_guardpage_enabled = true;
535 struct page_ext_operations debug_guardpage_ops = {
536 .need = need_debug_guardpage,
537 .init = init_debug_guardpage,
540 static int __init debug_guardpage_minorder_setup(char *buf)
544 if (kstrtoul(buf, 10, &res) < 0 || res > MAX_ORDER / 2) {
545 printk(KERN_ERR "Bad debug_guardpage_minorder value\n");
548 _debug_guardpage_minorder = res;
549 printk(KERN_INFO "Setting debug_guardpage_minorder to %lu\n", res);
552 __setup("debug_guardpage_minorder=", debug_guardpage_minorder_setup);
554 static inline void set_page_guard(struct zone *zone, struct page *page,
555 unsigned int order, int migratetype)
557 struct page_ext *page_ext;
559 if (!debug_guardpage_enabled())
562 page_ext = lookup_page_ext(page);
563 __set_bit(PAGE_EXT_DEBUG_GUARD, &page_ext->flags);
565 INIT_LIST_HEAD(&page->lru);
566 set_page_private(page, order);
567 /* Guard pages are not available for any usage */
568 __mod_zone_freepage_state(zone, -(1 << order), migratetype);
571 static inline void clear_page_guard(struct zone *zone, struct page *page,
572 unsigned int order, int migratetype)
574 struct page_ext *page_ext;
576 if (!debug_guardpage_enabled())
579 page_ext = lookup_page_ext(page);
580 __clear_bit(PAGE_EXT_DEBUG_GUARD, &page_ext->flags);
582 set_page_private(page, 0);
583 if (!is_migrate_isolate(migratetype))
584 __mod_zone_freepage_state(zone, (1 << order), migratetype);
587 struct page_ext_operations debug_guardpage_ops = { NULL, };
588 static inline void set_page_guard(struct zone *zone, struct page *page,
589 unsigned int order, int migratetype) {}
590 static inline void clear_page_guard(struct zone *zone, struct page *page,
591 unsigned int order, int migratetype) {}
594 static inline void set_page_order(struct page *page, unsigned int order)
596 set_page_private(page, order);
597 __SetPageBuddy(page);
600 static inline void rmv_page_order(struct page *page)
602 __ClearPageBuddy(page);
603 set_page_private(page, 0);
607 * This function checks whether a page is free && is the buddy
608 * we can do coalesce a page and its buddy if
609 * (a) the buddy is not in a hole &&
610 * (b) the buddy is in the buddy system &&
611 * (c) a page and its buddy have the same order &&
612 * (d) a page and its buddy are in the same zone.
614 * For recording whether a page is in the buddy system, we set ->_mapcount
615 * PAGE_BUDDY_MAPCOUNT_VALUE.
616 * Setting, clearing, and testing _mapcount PAGE_BUDDY_MAPCOUNT_VALUE is
617 * serialized by zone->lock.
619 * For recording page's order, we use page_private(page).
621 static inline int page_is_buddy(struct page *page, struct page *buddy,
624 if (!pfn_valid_within(page_to_pfn(buddy)))
627 if (page_is_guard(buddy) && page_order(buddy) == order) {
628 if (page_zone_id(page) != page_zone_id(buddy))
631 VM_BUG_ON_PAGE(page_count(buddy) != 0, buddy);
636 if (PageBuddy(buddy) && page_order(buddy) == order) {
638 * zone check is done late to avoid uselessly
639 * calculating zone/node ids for pages that could
642 if (page_zone_id(page) != page_zone_id(buddy))
645 VM_BUG_ON_PAGE(page_count(buddy) != 0, buddy);
653 * Freeing function for a buddy system allocator.
655 * The concept of a buddy system is to maintain direct-mapped table
656 * (containing bit values) for memory blocks of various "orders".
657 * The bottom level table contains the map for the smallest allocatable
658 * units of memory (here, pages), and each level above it describes
659 * pairs of units from the levels below, hence, "buddies".
660 * At a high level, all that happens here is marking the table entry
661 * at the bottom level available, and propagating the changes upward
662 * as necessary, plus some accounting needed to play nicely with other
663 * parts of the VM system.
664 * At each level, we keep a list of pages, which are heads of continuous
665 * free pages of length of (1 << order) and marked with _mapcount
666 * PAGE_BUDDY_MAPCOUNT_VALUE. Page's order is recorded in page_private(page)
668 * So when we are allocating or freeing one, we can derive the state of the
669 * other. That is, if we allocate a small block, and both were
670 * free, the remainder of the region must be split into blocks.
671 * If a block is freed, and its buddy is also free, then this
672 * triggers coalescing into a block of larger size.
677 static inline void __free_one_page(struct page *page,
679 struct zone *zone, unsigned int order,
682 unsigned long page_idx;
683 unsigned long combined_idx;
684 unsigned long uninitialized_var(buddy_idx);
686 unsigned int max_order;
688 max_order = min_t(unsigned int, MAX_ORDER, pageblock_order + 1);
690 VM_BUG_ON(!zone_is_initialized(zone));
691 VM_BUG_ON_PAGE(page->flags & PAGE_FLAGS_CHECK_AT_PREP, page);
693 VM_BUG_ON(migratetype == -1);
694 if (likely(!is_migrate_isolate(migratetype)))
695 __mod_zone_freepage_state(zone, 1 << order, migratetype);
697 page_idx = pfn & ((1 << MAX_ORDER) - 1);
699 VM_BUG_ON_PAGE(page_idx & ((1 << order) - 1), page);
700 VM_BUG_ON_PAGE(bad_range(zone, page), page);
703 while (order < max_order - 1) {
704 buddy_idx = __find_buddy_index(page_idx, order);
705 buddy = page + (buddy_idx - page_idx);
706 if (!page_is_buddy(page, buddy, order))
709 * Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page,
710 * merge with it and move up one order.
712 if (page_is_guard(buddy)) {
713 clear_page_guard(zone, buddy, order, migratetype);
715 list_del(&buddy->lru);
716 zone->free_area[order].nr_free--;
717 rmv_page_order(buddy);
719 combined_idx = buddy_idx & page_idx;
720 page = page + (combined_idx - page_idx);
721 page_idx = combined_idx;
724 if (max_order < MAX_ORDER) {
725 /* If we are here, it means order is >= pageblock_order.
726 * We want to prevent merge between freepages on isolate
727 * pageblock and normal pageblock. Without this, pageblock
728 * isolation could cause incorrect freepage or CMA accounting.
730 * We don't want to hit this code for the more frequent
733 if (unlikely(has_isolate_pageblock(zone))) {
736 buddy_idx = __find_buddy_index(page_idx, order);
737 buddy = page + (buddy_idx - page_idx);
738 buddy_mt = get_pageblock_migratetype(buddy);
740 if (migratetype != buddy_mt
741 && (is_migrate_isolate(migratetype) ||
742 is_migrate_isolate(buddy_mt)))
746 goto continue_merging;
750 set_page_order(page, order);
753 * If this is not the largest possible page, check if the buddy
754 * of the next-highest order is free. If it is, it's possible
755 * that pages are being freed that will coalesce soon. In case,
756 * that is happening, add the free page to the tail of the list
757 * so it's less likely to be used soon and more likely to be merged
758 * as a higher order page
760 if ((order < MAX_ORDER-2) && pfn_valid_within(page_to_pfn(buddy))) {
761 struct page *higher_page, *higher_buddy;
762 combined_idx = buddy_idx & page_idx;
763 higher_page = page + (combined_idx - page_idx);
764 buddy_idx = __find_buddy_index(combined_idx, order + 1);
765 higher_buddy = higher_page + (buddy_idx - combined_idx);
766 if (page_is_buddy(higher_page, higher_buddy, order + 1)) {
767 list_add_tail(&page->lru,
768 &zone->free_area[order].free_list[migratetype]);
773 list_add(&page->lru, &zone->free_area[order].free_list[migratetype]);
775 zone->free_area[order].nr_free++;
778 static inline int free_pages_check(struct page *page)
780 const char *bad_reason = NULL;
781 unsigned long bad_flags = 0;
783 if (unlikely(page_mapcount(page)))
784 bad_reason = "nonzero mapcount";
785 if (unlikely(page->mapping != NULL))
786 bad_reason = "non-NULL mapping";
787 if (unlikely(atomic_read(&page->_count) != 0))
788 bad_reason = "nonzero _count";
789 if (unlikely(page->flags & PAGE_FLAGS_CHECK_AT_FREE)) {
790 bad_reason = "PAGE_FLAGS_CHECK_AT_FREE flag(s) set";
791 bad_flags = PAGE_FLAGS_CHECK_AT_FREE;
794 if (unlikely(page->mem_cgroup))
795 bad_reason = "page still charged to cgroup";
797 if (unlikely(bad_reason)) {
798 bad_page(page, bad_reason, bad_flags);
801 page_cpupid_reset_last(page);
802 if (page->flags & PAGE_FLAGS_CHECK_AT_PREP)
803 page->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
808 * Frees a number of pages from the PCP lists
809 * Assumes all pages on list are in same zone, and of same order.
810 * count is the number of pages to free.
812 * If the zone was previously in an "all pages pinned" state then look to
813 * see if this freeing clears that state.
815 * And clear the zone's pages_scanned counter, to hold off the "all pages are
816 * pinned" detection logic.
818 static void free_pcppages_bulk(struct zone *zone, int count,
819 struct per_cpu_pages *pcp)
824 unsigned long nr_scanned;
826 spin_lock(&zone->lock);
827 nr_scanned = zone_page_state(zone, NR_PAGES_SCANNED);
829 __mod_zone_page_state(zone, NR_PAGES_SCANNED, -nr_scanned);
833 struct list_head *list;
836 * Remove pages from lists in a round-robin fashion. A
837 * batch_free count is maintained that is incremented when an
838 * empty list is encountered. This is so more pages are freed
839 * off fuller lists instead of spinning excessively around empty
844 if (++migratetype == MIGRATE_PCPTYPES)
846 list = &pcp->lists[migratetype];
847 } while (list_empty(list));
849 /* This is the only non-empty list. Free them all. */
850 if (batch_free == MIGRATE_PCPTYPES)
851 batch_free = to_free;
854 int mt; /* migratetype of the to-be-freed page */
856 page = list_entry(list->prev, struct page, lru);
857 /* must delete as __free_one_page list manipulates */
858 list_del(&page->lru);
860 mt = get_pcppage_migratetype(page);
861 /* MIGRATE_ISOLATE page should not go to pcplists */
862 VM_BUG_ON_PAGE(is_migrate_isolate(mt), page);
863 /* Pageblock could have been isolated meanwhile */
864 if (unlikely(has_isolate_pageblock(zone)))
865 mt = get_pageblock_migratetype(page);
867 __free_one_page(page, page_to_pfn(page), zone, 0, mt);
868 trace_mm_page_pcpu_drain(page, 0, mt);
869 } while (--to_free && --batch_free && !list_empty(list));
871 spin_unlock(&zone->lock);
874 static void free_one_page(struct zone *zone,
875 struct page *page, unsigned long pfn,
879 unsigned long nr_scanned;
880 spin_lock(&zone->lock);
881 nr_scanned = zone_page_state(zone, NR_PAGES_SCANNED);
883 __mod_zone_page_state(zone, NR_PAGES_SCANNED, -nr_scanned);
885 if (unlikely(has_isolate_pageblock(zone) ||
886 is_migrate_isolate(migratetype))) {
887 migratetype = get_pfnblock_migratetype(page, pfn);
889 __free_one_page(page, pfn, zone, order, migratetype);
890 spin_unlock(&zone->lock);
893 static int free_tail_pages_check(struct page *head_page, struct page *page)
898 * We rely page->lru.next never has bit 0 set, unless the page
899 * is PageTail(). Let's make sure that's true even for poisoned ->lru.
901 BUILD_BUG_ON((unsigned long)LIST_POISON1 & 1);
903 if (!IS_ENABLED(CONFIG_DEBUG_VM)) {
907 if (unlikely(!PageTail(page))) {
908 bad_page(page, "PageTail not set", 0);
911 if (unlikely(compound_head(page) != head_page)) {
912 bad_page(page, "compound_head not consistent", 0);
917 clear_compound_head(page);
921 static void __meminit __init_single_page(struct page *page, unsigned long pfn,
922 unsigned long zone, int nid)
924 set_page_links(page, zone, nid, pfn);
925 init_page_count(page);
926 page_mapcount_reset(page);
927 page_cpupid_reset_last(page);
929 INIT_LIST_HEAD(&page->lru);
930 #ifdef WANT_PAGE_VIRTUAL
931 /* The shift won't overflow because ZONE_NORMAL is below 4G. */
932 if (!is_highmem_idx(zone))
933 set_page_address(page, __va(pfn << PAGE_SHIFT));
937 static void __meminit __init_single_pfn(unsigned long pfn, unsigned long zone,
940 return __init_single_page(pfn_to_page(pfn), pfn, zone, nid);
943 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
944 static void init_reserved_page(unsigned long pfn)
949 if (!early_page_uninitialised(pfn))
952 nid = early_pfn_to_nid(pfn);
953 pgdat = NODE_DATA(nid);
955 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
956 struct zone *zone = &pgdat->node_zones[zid];
958 if (pfn >= zone->zone_start_pfn && pfn < zone_end_pfn(zone))
961 __init_single_pfn(pfn, zid, nid);
964 static inline void init_reserved_page(unsigned long pfn)
967 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
970 * Initialised pages do not have PageReserved set. This function is
971 * called for each range allocated by the bootmem allocator and
972 * marks the pages PageReserved. The remaining valid pages are later
973 * sent to the buddy page allocator.
975 void __meminit reserve_bootmem_region(phys_addr_t start, phys_addr_t end)
977 unsigned long start_pfn = PFN_DOWN(start);
978 unsigned long end_pfn = PFN_UP(end);
980 for (; start_pfn < end_pfn; start_pfn++) {
981 if (pfn_valid(start_pfn)) {
982 struct page *page = pfn_to_page(start_pfn);
984 init_reserved_page(start_pfn);
986 /* Avoid false-positive PageTail() */
987 INIT_LIST_HEAD(&page->lru);
989 SetPageReserved(page);
994 static bool free_pages_prepare(struct page *page, unsigned int order)
996 bool compound = PageCompound(page);
999 VM_BUG_ON_PAGE(PageTail(page), page);
1000 VM_BUG_ON_PAGE(compound && compound_order(page) != order, page);
1002 trace_mm_page_free(page, order);
1003 kmemcheck_free_shadow(page, order);
1004 kasan_free_pages(page, order);
1007 page->mapping = NULL;
1008 bad += free_pages_check(page);
1009 for (i = 1; i < (1 << order); i++) {
1011 bad += free_tail_pages_check(page, page + i);
1012 bad += free_pages_check(page + i);
1017 reset_page_owner(page, order);
1019 if (!PageHighMem(page)) {
1020 debug_check_no_locks_freed(page_address(page),
1021 PAGE_SIZE << order);
1022 debug_check_no_obj_freed(page_address(page),
1023 PAGE_SIZE << order);
1025 arch_free_page(page, order);
1026 kernel_map_pages(page, 1 << order, 0);
1031 static void __free_pages_ok(struct page *page, unsigned int order)
1033 unsigned long flags;
1035 unsigned long pfn = page_to_pfn(page);
1037 if (!free_pages_prepare(page, order))
1040 migratetype = get_pfnblock_migratetype(page, pfn);
1041 local_irq_save(flags);
1042 __count_vm_events(PGFREE, 1 << order);
1043 free_one_page(page_zone(page), page, pfn, order, migratetype);
1044 local_irq_restore(flags);
1047 static void __init __free_pages_boot_core(struct page *page,
1048 unsigned long pfn, unsigned int order)
1050 unsigned int nr_pages = 1 << order;
1051 struct page *p = page;
1055 for (loop = 0; loop < (nr_pages - 1); loop++, p++) {
1057 __ClearPageReserved(p);
1058 set_page_count(p, 0);
1060 __ClearPageReserved(p);
1061 set_page_count(p, 0);
1063 page_zone(page)->managed_pages += nr_pages;
1064 set_page_refcounted(page);
1065 __free_pages(page, order);
1068 #if defined(CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID) || \
1069 defined(CONFIG_HAVE_MEMBLOCK_NODE_MAP)
1071 static struct mminit_pfnnid_cache early_pfnnid_cache __meminitdata;
1073 int __meminit early_pfn_to_nid(unsigned long pfn)
1075 static DEFINE_SPINLOCK(early_pfn_lock);
1078 spin_lock(&early_pfn_lock);
1079 nid = __early_pfn_to_nid(pfn, &early_pfnnid_cache);
1081 nid = first_online_node;
1082 spin_unlock(&early_pfn_lock);
1088 #ifdef CONFIG_NODES_SPAN_OTHER_NODES
1089 static inline bool __meminit meminit_pfn_in_nid(unsigned long pfn, int node,
1090 struct mminit_pfnnid_cache *state)
1094 nid = __early_pfn_to_nid(pfn, state);
1095 if (nid >= 0 && nid != node)
1100 /* Only safe to use early in boot when initialisation is single-threaded */
1101 static inline bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
1103 return meminit_pfn_in_nid(pfn, node, &early_pfnnid_cache);
1108 static inline bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
1112 static inline bool __meminit meminit_pfn_in_nid(unsigned long pfn, int node,
1113 struct mminit_pfnnid_cache *state)
1120 void __init __free_pages_bootmem(struct page *page, unsigned long pfn,
1123 if (early_page_uninitialised(pfn))
1125 return __free_pages_boot_core(page, pfn, order);
1128 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1129 static void __init deferred_free_range(struct page *page,
1130 unsigned long pfn, int nr_pages)
1137 /* Free a large naturally-aligned chunk if possible */
1138 if (nr_pages == MAX_ORDER_NR_PAGES &&
1139 (pfn & (MAX_ORDER_NR_PAGES-1)) == 0) {
1140 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
1141 __free_pages_boot_core(page, pfn, MAX_ORDER-1);
1145 for (i = 0; i < nr_pages; i++, page++, pfn++)
1146 __free_pages_boot_core(page, pfn, 0);
1149 /* Completion tracking for deferred_init_memmap() threads */
1150 static atomic_t pgdat_init_n_undone __initdata;
1151 static __initdata DECLARE_COMPLETION(pgdat_init_all_done_comp);
1153 static inline void __init pgdat_init_report_one_done(void)
1155 if (atomic_dec_and_test(&pgdat_init_n_undone))
1156 complete(&pgdat_init_all_done_comp);
1159 /* Initialise remaining memory on a node */
1160 static int __init deferred_init_memmap(void *data)
1162 pg_data_t *pgdat = data;
1163 int nid = pgdat->node_id;
1164 struct mminit_pfnnid_cache nid_init_state = { };
1165 unsigned long start = jiffies;
1166 unsigned long nr_pages = 0;
1167 unsigned long walk_start, walk_end;
1170 unsigned long first_init_pfn = pgdat->first_deferred_pfn;
1171 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
1173 if (first_init_pfn == ULONG_MAX) {
1174 pgdat_init_report_one_done();
1178 /* Bind memory initialisation thread to a local node if possible */
1179 if (!cpumask_empty(cpumask))
1180 set_cpus_allowed_ptr(current, cpumask);
1182 /* Sanity check boundaries */
1183 BUG_ON(pgdat->first_deferred_pfn < pgdat->node_start_pfn);
1184 BUG_ON(pgdat->first_deferred_pfn > pgdat_end_pfn(pgdat));
1185 pgdat->first_deferred_pfn = ULONG_MAX;
1187 /* Only the highest zone is deferred so find it */
1188 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1189 zone = pgdat->node_zones + zid;
1190 if (first_init_pfn < zone_end_pfn(zone))
1194 for_each_mem_pfn_range(i, nid, &walk_start, &walk_end, NULL) {
1195 unsigned long pfn, end_pfn;
1196 struct page *page = NULL;
1197 struct page *free_base_page = NULL;
1198 unsigned long free_base_pfn = 0;
1201 end_pfn = min(walk_end, zone_end_pfn(zone));
1202 pfn = first_init_pfn;
1203 if (pfn < walk_start)
1205 if (pfn < zone->zone_start_pfn)
1206 pfn = zone->zone_start_pfn;
1208 for (; pfn < end_pfn; pfn++) {
1209 if (!pfn_valid_within(pfn))
1213 * Ensure pfn_valid is checked every
1214 * MAX_ORDER_NR_PAGES for memory holes
1216 if ((pfn & (MAX_ORDER_NR_PAGES - 1)) == 0) {
1217 if (!pfn_valid(pfn)) {
1223 if (!meminit_pfn_in_nid(pfn, nid, &nid_init_state)) {
1228 /* Minimise pfn page lookups and scheduler checks */
1229 if (page && (pfn & (MAX_ORDER_NR_PAGES - 1)) != 0) {
1232 nr_pages += nr_to_free;
1233 deferred_free_range(free_base_page,
1234 free_base_pfn, nr_to_free);
1235 free_base_page = NULL;
1236 free_base_pfn = nr_to_free = 0;
1238 page = pfn_to_page(pfn);
1243 VM_BUG_ON(page_zone(page) != zone);
1247 __init_single_page(page, pfn, zid, nid);
1248 if (!free_base_page) {
1249 free_base_page = page;
1250 free_base_pfn = pfn;
1255 /* Where possible, batch up pages for a single free */
1258 /* Free the current block of pages to allocator */
1259 nr_pages += nr_to_free;
1260 deferred_free_range(free_base_page, free_base_pfn,
1262 free_base_page = NULL;
1263 free_base_pfn = nr_to_free = 0;
1266 first_init_pfn = max(end_pfn, first_init_pfn);
1269 /* Sanity check that the next zone really is unpopulated */
1270 WARN_ON(++zid < MAX_NR_ZONES && populated_zone(++zone));
1272 pr_info("node %d initialised, %lu pages in %ums\n", nid, nr_pages,
1273 jiffies_to_msecs(jiffies - start));
1275 pgdat_init_report_one_done();
1279 void __init page_alloc_init_late(void)
1283 /* There will be num_node_state(N_MEMORY) threads */
1284 atomic_set(&pgdat_init_n_undone, num_node_state(N_MEMORY));
1285 for_each_node_state(nid, N_MEMORY) {
1286 kthread_run(deferred_init_memmap, NODE_DATA(nid), "pgdatinit%d", nid);
1289 /* Block until all are initialised */
1290 wait_for_completion(&pgdat_init_all_done_comp);
1292 /* Reinit limits that are based on free pages after the kernel is up */
1293 files_maxfiles_init();
1295 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
1298 /* Free whole pageblock and set its migration type to MIGRATE_CMA. */
1299 void __init init_cma_reserved_pageblock(struct page *page)
1301 unsigned i = pageblock_nr_pages;
1302 struct page *p = page;
1305 __ClearPageReserved(p);
1306 set_page_count(p, 0);
1309 set_pageblock_migratetype(page, MIGRATE_CMA);
1311 if (pageblock_order >= MAX_ORDER) {
1312 i = pageblock_nr_pages;
1315 set_page_refcounted(p);
1316 __free_pages(p, MAX_ORDER - 1);
1317 p += MAX_ORDER_NR_PAGES;
1318 } while (i -= MAX_ORDER_NR_PAGES);
1320 set_page_refcounted(page);
1321 __free_pages(page, pageblock_order);
1324 adjust_managed_page_count(page, pageblock_nr_pages);
1329 * The order of subdivision here is critical for the IO subsystem.
1330 * Please do not alter this order without good reasons and regression
1331 * testing. Specifically, as large blocks of memory are subdivided,
1332 * the order in which smaller blocks are delivered depends on the order
1333 * they're subdivided in this function. This is the primary factor
1334 * influencing the order in which pages are delivered to the IO
1335 * subsystem according to empirical testing, and this is also justified
1336 * by considering the behavior of a buddy system containing a single
1337 * large block of memory acted on by a series of small allocations.
1338 * This behavior is a critical factor in sglist merging's success.
1342 static inline void expand(struct zone *zone, struct page *page,
1343 int low, int high, struct free_area *area,
1346 unsigned long size = 1 << high;
1348 while (high > low) {
1352 VM_BUG_ON_PAGE(bad_range(zone, &page[size]), &page[size]);
1354 if (IS_ENABLED(CONFIG_DEBUG_PAGEALLOC) &&
1355 debug_guardpage_enabled() &&
1356 high < debug_guardpage_minorder()) {
1358 * Mark as guard pages (or page), that will allow to
1359 * merge back to allocator when buddy will be freed.
1360 * Corresponding page table entries will not be touched,
1361 * pages will stay not present in virtual address space
1363 set_page_guard(zone, &page[size], high, migratetype);
1366 list_add(&page[size].lru, &area->free_list[migratetype]);
1368 set_page_order(&page[size], high);
1373 * This page is about to be returned from the page allocator
1375 static inline int check_new_page(struct page *page)
1377 const char *bad_reason = NULL;
1378 unsigned long bad_flags = 0;
1380 if (unlikely(page_mapcount(page)))
1381 bad_reason = "nonzero mapcount";
1382 if (unlikely(page->mapping != NULL))
1383 bad_reason = "non-NULL mapping";
1384 if (unlikely(atomic_read(&page->_count) != 0))
1385 bad_reason = "nonzero _count";
1386 if (unlikely(page->flags & __PG_HWPOISON)) {
1387 bad_reason = "HWPoisoned (hardware-corrupted)";
1388 bad_flags = __PG_HWPOISON;
1390 if (unlikely(page->flags & PAGE_FLAGS_CHECK_AT_PREP)) {
1391 bad_reason = "PAGE_FLAGS_CHECK_AT_PREP flag set";
1392 bad_flags = PAGE_FLAGS_CHECK_AT_PREP;
1395 if (unlikely(page->mem_cgroup))
1396 bad_reason = "page still charged to cgroup";
1398 if (unlikely(bad_reason)) {
1399 bad_page(page, bad_reason, bad_flags);
1405 static int prep_new_page(struct page *page, unsigned int order, gfp_t gfp_flags,
1410 for (i = 0; i < (1 << order); i++) {
1411 struct page *p = page + i;
1412 if (unlikely(check_new_page(p)))
1416 set_page_private(page, 0);
1417 set_page_refcounted(page);
1419 arch_alloc_page(page, order);
1420 kernel_map_pages(page, 1 << order, 1);
1421 kasan_alloc_pages(page, order);
1423 if (gfp_flags & __GFP_ZERO)
1424 for (i = 0; i < (1 << order); i++)
1425 clear_highpage(page + i);
1427 if (order && (gfp_flags & __GFP_COMP))
1428 prep_compound_page(page, order);
1430 set_page_owner(page, order, gfp_flags);
1433 * page is set pfmemalloc when ALLOC_NO_WATERMARKS was necessary to
1434 * allocate the page. The expectation is that the caller is taking
1435 * steps that will free more memory. The caller should avoid the page
1436 * being used for !PFMEMALLOC purposes.
1438 if (alloc_flags & ALLOC_NO_WATERMARKS)
1439 set_page_pfmemalloc(page);
1441 clear_page_pfmemalloc(page);
1447 * Go through the free lists for the given migratetype and remove
1448 * the smallest available page from the freelists
1451 struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
1454 unsigned int current_order;
1455 struct free_area *area;
1458 /* Find a page of the appropriate size in the preferred list */
1459 for (current_order = order; current_order < MAX_ORDER; ++current_order) {
1460 area = &(zone->free_area[current_order]);
1461 if (list_empty(&area->free_list[migratetype]))
1464 page = list_entry(area->free_list[migratetype].next,
1466 list_del(&page->lru);
1467 rmv_page_order(page);
1469 expand(zone, page, order, current_order, area, migratetype);
1470 set_pcppage_migratetype(page, migratetype);
1479 * This array describes the order lists are fallen back to when
1480 * the free lists for the desirable migrate type are depleted
1482 static int fallbacks[MIGRATE_TYPES][4] = {
1483 [MIGRATE_UNMOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE, MIGRATE_TYPES },
1484 [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE, MIGRATE_MOVABLE, MIGRATE_TYPES },
1485 [MIGRATE_MOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_TYPES },
1487 [MIGRATE_CMA] = { MIGRATE_TYPES }, /* Never used */
1489 #ifdef CONFIG_MEMORY_ISOLATION
1490 [MIGRATE_ISOLATE] = { MIGRATE_TYPES }, /* Never used */
1495 static struct page *__rmqueue_cma_fallback(struct zone *zone,
1498 return __rmqueue_smallest(zone, order, MIGRATE_CMA);
1501 static inline struct page *__rmqueue_cma_fallback(struct zone *zone,
1502 unsigned int order) { return NULL; }
1506 * Move the free pages in a range to the free lists of the requested type.
1507 * Note that start_page and end_pages are not aligned on a pageblock
1508 * boundary. If alignment is required, use move_freepages_block()
1510 int move_freepages(struct zone *zone,
1511 struct page *start_page, struct page *end_page,
1516 int pages_moved = 0;
1518 #ifndef CONFIG_HOLES_IN_ZONE
1520 * page_zone is not safe to call in this context when
1521 * CONFIG_HOLES_IN_ZONE is set. This bug check is probably redundant
1522 * anyway as we check zone boundaries in move_freepages_block().
1523 * Remove at a later date when no bug reports exist related to
1524 * grouping pages by mobility
1526 VM_BUG_ON(page_zone(start_page) != page_zone(end_page));
1529 for (page = start_page; page <= end_page;) {
1530 if (!pfn_valid_within(page_to_pfn(page))) {
1535 /* Make sure we are not inadvertently changing nodes */
1536 VM_BUG_ON_PAGE(page_to_nid(page) != zone_to_nid(zone), page);
1538 if (!PageBuddy(page)) {
1543 order = page_order(page);
1544 list_move(&page->lru,
1545 &zone->free_area[order].free_list[migratetype]);
1547 pages_moved += 1 << order;
1553 int move_freepages_block(struct zone *zone, struct page *page,
1556 unsigned long start_pfn, end_pfn;
1557 struct page *start_page, *end_page;
1559 start_pfn = page_to_pfn(page);
1560 start_pfn = start_pfn & ~(pageblock_nr_pages-1);
1561 start_page = pfn_to_page(start_pfn);
1562 end_page = start_page + pageblock_nr_pages - 1;
1563 end_pfn = start_pfn + pageblock_nr_pages - 1;
1565 /* Do not cross zone boundaries */
1566 if (!zone_spans_pfn(zone, start_pfn))
1568 if (!zone_spans_pfn(zone, end_pfn))
1571 return move_freepages(zone, start_page, end_page, migratetype);
1574 static void change_pageblock_range(struct page *pageblock_page,
1575 int start_order, int migratetype)
1577 int nr_pageblocks = 1 << (start_order - pageblock_order);
1579 while (nr_pageblocks--) {
1580 set_pageblock_migratetype(pageblock_page, migratetype);
1581 pageblock_page += pageblock_nr_pages;
1586 * When we are falling back to another migratetype during allocation, try to
1587 * steal extra free pages from the same pageblocks to satisfy further
1588 * allocations, instead of polluting multiple pageblocks.
1590 * If we are stealing a relatively large buddy page, it is likely there will
1591 * be more free pages in the pageblock, so try to steal them all. For
1592 * reclaimable and unmovable allocations, we steal regardless of page size,
1593 * as fragmentation caused by those allocations polluting movable pageblocks
1594 * is worse than movable allocations stealing from unmovable and reclaimable
1597 static bool can_steal_fallback(unsigned int order, int start_mt)
1600 * Leaving this order check is intended, although there is
1601 * relaxed order check in next check. The reason is that
1602 * we can actually steal whole pageblock if this condition met,
1603 * but, below check doesn't guarantee it and that is just heuristic
1604 * so could be changed anytime.
1606 if (order >= pageblock_order)
1609 if (order >= pageblock_order / 2 ||
1610 start_mt == MIGRATE_RECLAIMABLE ||
1611 start_mt == MIGRATE_UNMOVABLE ||
1612 page_group_by_mobility_disabled)
1619 * This function implements actual steal behaviour. If order is large enough,
1620 * we can steal whole pageblock. If not, we first move freepages in this
1621 * pageblock and check whether half of pages are moved or not. If half of
1622 * pages are moved, we can change migratetype of pageblock and permanently
1623 * use it's pages as requested migratetype in the future.
1625 static void steal_suitable_fallback(struct zone *zone, struct page *page,
1628 unsigned int current_order = page_order(page);
1631 /* Take ownership for orders >= pageblock_order */
1632 if (current_order >= pageblock_order) {
1633 change_pageblock_range(page, current_order, start_type);
1637 pages = move_freepages_block(zone, page, start_type);
1639 /* Claim the whole block if over half of it is free */
1640 if (pages >= (1 << (pageblock_order-1)) ||
1641 page_group_by_mobility_disabled)
1642 set_pageblock_migratetype(page, start_type);
1646 * Check whether there is a suitable fallback freepage with requested order.
1647 * If only_stealable is true, this function returns fallback_mt only if
1648 * we can steal other freepages all together. This would help to reduce
1649 * fragmentation due to mixed migratetype pages in one pageblock.
1651 int find_suitable_fallback(struct free_area *area, unsigned int order,
1652 int migratetype, bool only_stealable, bool *can_steal)
1657 if (area->nr_free == 0)
1662 fallback_mt = fallbacks[migratetype][i];
1663 if (fallback_mt == MIGRATE_TYPES)
1666 if (list_empty(&area->free_list[fallback_mt]))
1669 if (can_steal_fallback(order, migratetype))
1672 if (!only_stealable)
1683 * Reserve a pageblock for exclusive use of high-order atomic allocations if
1684 * there are no empty page blocks that contain a page with a suitable order
1686 static void reserve_highatomic_pageblock(struct page *page, struct zone *zone,
1687 unsigned int alloc_order)
1690 unsigned long max_managed, flags;
1693 * Limit the number reserved to 1 pageblock or roughly 1% of a zone.
1694 * Check is race-prone but harmless.
1696 max_managed = (zone->managed_pages / 100) + pageblock_nr_pages;
1697 if (zone->nr_reserved_highatomic >= max_managed)
1700 spin_lock_irqsave(&zone->lock, flags);
1702 /* Recheck the nr_reserved_highatomic limit under the lock */
1703 if (zone->nr_reserved_highatomic >= max_managed)
1707 mt = get_pageblock_migratetype(page);
1708 if (mt != MIGRATE_HIGHATOMIC &&
1709 !is_migrate_isolate(mt) && !is_migrate_cma(mt)) {
1710 zone->nr_reserved_highatomic += pageblock_nr_pages;
1711 set_pageblock_migratetype(page, MIGRATE_HIGHATOMIC);
1712 move_freepages_block(zone, page, MIGRATE_HIGHATOMIC);
1716 spin_unlock_irqrestore(&zone->lock, flags);
1720 * Used when an allocation is about to fail under memory pressure. This
1721 * potentially hurts the reliability of high-order allocations when under
1722 * intense memory pressure but failed atomic allocations should be easier
1723 * to recover from than an OOM.
1725 static void unreserve_highatomic_pageblock(const struct alloc_context *ac)
1727 struct zonelist *zonelist = ac->zonelist;
1728 unsigned long flags;
1734 for_each_zone_zonelist_nodemask(zone, z, zonelist, ac->high_zoneidx,
1736 /* Preserve at least one pageblock */
1737 if (zone->nr_reserved_highatomic <= pageblock_nr_pages)
1740 spin_lock_irqsave(&zone->lock, flags);
1741 for (order = 0; order < MAX_ORDER; order++) {
1742 struct free_area *area = &(zone->free_area[order]);
1744 if (list_empty(&area->free_list[MIGRATE_HIGHATOMIC]))
1747 page = list_entry(area->free_list[MIGRATE_HIGHATOMIC].next,
1751 * It should never happen but changes to locking could
1752 * inadvertently allow a per-cpu drain to add pages
1753 * to MIGRATE_HIGHATOMIC while unreserving so be safe
1754 * and watch for underflows.
1756 zone->nr_reserved_highatomic -= min(pageblock_nr_pages,
1757 zone->nr_reserved_highatomic);
1760 * Convert to ac->migratetype and avoid the normal
1761 * pageblock stealing heuristics. Minimally, the caller
1762 * is doing the work and needs the pages. More
1763 * importantly, if the block was always converted to
1764 * MIGRATE_UNMOVABLE or another type then the number
1765 * of pageblocks that cannot be completely freed
1768 set_pageblock_migratetype(page, ac->migratetype);
1769 move_freepages_block(zone, page, ac->migratetype);
1770 spin_unlock_irqrestore(&zone->lock, flags);
1773 spin_unlock_irqrestore(&zone->lock, flags);
1777 /* Remove an element from the buddy allocator from the fallback list */
1778 static inline struct page *
1779 __rmqueue_fallback(struct zone *zone, unsigned int order, int start_migratetype)
1781 struct free_area *area;
1782 unsigned int current_order;
1787 /* Find the largest possible block of pages in the other list */
1788 for (current_order = MAX_ORDER-1;
1789 current_order >= order && current_order <= MAX_ORDER-1;
1791 area = &(zone->free_area[current_order]);
1792 fallback_mt = find_suitable_fallback(area, current_order,
1793 start_migratetype, false, &can_steal);
1794 if (fallback_mt == -1)
1797 page = list_entry(area->free_list[fallback_mt].next,
1800 steal_suitable_fallback(zone, page, start_migratetype);
1802 /* Remove the page from the freelists */
1804 list_del(&page->lru);
1805 rmv_page_order(page);
1807 expand(zone, page, order, current_order, area,
1810 * The pcppage_migratetype may differ from pageblock's
1811 * migratetype depending on the decisions in
1812 * find_suitable_fallback(). This is OK as long as it does not
1813 * differ for MIGRATE_CMA pageblocks. Those can be used as
1814 * fallback only via special __rmqueue_cma_fallback() function
1816 set_pcppage_migratetype(page, start_migratetype);
1818 trace_mm_page_alloc_extfrag(page, order, current_order,
1819 start_migratetype, fallback_mt);
1828 * Do the hard work of removing an element from the buddy allocator.
1829 * Call me with the zone->lock already held.
1831 static struct page *__rmqueue(struct zone *zone, unsigned int order,
1832 int migratetype, gfp_t gfp_flags)
1836 page = __rmqueue_smallest(zone, order, migratetype);
1837 if (unlikely(!page)) {
1838 if (migratetype == MIGRATE_MOVABLE)
1839 page = __rmqueue_cma_fallback(zone, order);
1842 page = __rmqueue_fallback(zone, order, migratetype);
1845 trace_mm_page_alloc_zone_locked(page, order, migratetype);
1850 * Obtain a specified number of elements from the buddy allocator, all under
1851 * a single hold of the lock, for efficiency. Add them to the supplied list.
1852 * Returns the number of new pages which were placed at *list.
1854 static int rmqueue_bulk(struct zone *zone, unsigned int order,
1855 unsigned long count, struct list_head *list,
1856 int migratetype, bool cold)
1860 spin_lock(&zone->lock);
1861 for (i = 0; i < count; ++i) {
1862 struct page *page = __rmqueue(zone, order, migratetype, 0);
1863 if (unlikely(page == NULL))
1867 * Split buddy pages returned by expand() are received here
1868 * in physical page order. The page is added to the callers and
1869 * list and the list head then moves forward. From the callers
1870 * perspective, the linked list is ordered by page number in
1871 * some conditions. This is useful for IO devices that can
1872 * merge IO requests if the physical pages are ordered
1876 list_add(&page->lru, list);
1878 list_add_tail(&page->lru, list);
1880 if (is_migrate_cma(get_pcppage_migratetype(page)))
1881 __mod_zone_page_state(zone, NR_FREE_CMA_PAGES,
1884 __mod_zone_page_state(zone, NR_FREE_PAGES, -(i << order));
1885 spin_unlock(&zone->lock);
1891 * Called from the vmstat counter updater to drain pagesets of this
1892 * currently executing processor on remote nodes after they have
1895 * Note that this function must be called with the thread pinned to
1896 * a single processor.
1898 void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp)
1900 unsigned long flags;
1901 int to_drain, batch;
1903 local_irq_save(flags);
1904 batch = READ_ONCE(pcp->batch);
1905 to_drain = min(pcp->count, batch);
1907 free_pcppages_bulk(zone, to_drain, pcp);
1908 pcp->count -= to_drain;
1910 local_irq_restore(flags);
1915 * Drain pcplists of the indicated processor and zone.
1917 * The processor must either be the current processor and the
1918 * thread pinned to the current processor or a processor that
1921 static void drain_pages_zone(unsigned int cpu, struct zone *zone)
1923 unsigned long flags;
1924 struct per_cpu_pageset *pset;
1925 struct per_cpu_pages *pcp;
1927 local_irq_save(flags);
1928 pset = per_cpu_ptr(zone->pageset, cpu);
1932 free_pcppages_bulk(zone, pcp->count, pcp);
1935 local_irq_restore(flags);
1939 * Drain pcplists of all zones on the indicated processor.
1941 * The processor must either be the current processor and the
1942 * thread pinned to the current processor or a processor that
1945 static void drain_pages(unsigned int cpu)
1949 for_each_populated_zone(zone) {
1950 drain_pages_zone(cpu, zone);
1955 * Spill all of this CPU's per-cpu pages back into the buddy allocator.
1957 * The CPU has to be pinned. When zone parameter is non-NULL, spill just
1958 * the single zone's pages.
1960 void drain_local_pages(struct zone *zone)
1962 int cpu = smp_processor_id();
1965 drain_pages_zone(cpu, zone);
1971 * Spill all the per-cpu pages from all CPUs back into the buddy allocator.
1973 * When zone parameter is non-NULL, spill just the single zone's pages.
1975 * Note that this code is protected against sending an IPI to an offline
1976 * CPU but does not guarantee sending an IPI to newly hotplugged CPUs:
1977 * on_each_cpu_mask() blocks hotplug and won't talk to offlined CPUs but
1978 * nothing keeps CPUs from showing up after we populated the cpumask and
1979 * before the call to on_each_cpu_mask().
1981 void drain_all_pages(struct zone *zone)
1986 * Allocate in the BSS so we wont require allocation in
1987 * direct reclaim path for CONFIG_CPUMASK_OFFSTACK=y
1989 static cpumask_t cpus_with_pcps;
1992 * We don't care about racing with CPU hotplug event
1993 * as offline notification will cause the notified
1994 * cpu to drain that CPU pcps and on_each_cpu_mask
1995 * disables preemption as part of its processing
1997 for_each_online_cpu(cpu) {
1998 struct per_cpu_pageset *pcp;
2000 bool has_pcps = false;
2003 pcp = per_cpu_ptr(zone->pageset, cpu);
2007 for_each_populated_zone(z) {
2008 pcp = per_cpu_ptr(z->pageset, cpu);
2009 if (pcp->pcp.count) {
2017 cpumask_set_cpu(cpu, &cpus_with_pcps);
2019 cpumask_clear_cpu(cpu, &cpus_with_pcps);
2021 on_each_cpu_mask(&cpus_with_pcps, (smp_call_func_t) drain_local_pages,
2025 #ifdef CONFIG_HIBERNATION
2027 void mark_free_pages(struct zone *zone)
2029 unsigned long pfn, max_zone_pfn;
2030 unsigned long flags;
2031 unsigned int order, t;
2032 struct list_head *curr;
2034 if (zone_is_empty(zone))
2037 spin_lock_irqsave(&zone->lock, flags);
2039 max_zone_pfn = zone_end_pfn(zone);
2040 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
2041 if (pfn_valid(pfn)) {
2042 struct page *page = pfn_to_page(pfn);
2044 if (!swsusp_page_is_forbidden(page))
2045 swsusp_unset_page_free(page);
2048 for_each_migratetype_order(order, t) {
2049 list_for_each(curr, &zone->free_area[order].free_list[t]) {
2052 pfn = page_to_pfn(list_entry(curr, struct page, lru));
2053 for (i = 0; i < (1UL << order); i++)
2054 swsusp_set_page_free(pfn_to_page(pfn + i));
2057 spin_unlock_irqrestore(&zone->lock, flags);
2059 #endif /* CONFIG_PM */
2062 * Free a 0-order page
2063 * cold == true ? free a cold page : free a hot page
2065 void free_hot_cold_page(struct page *page, bool cold)
2067 struct zone *zone = page_zone(page);
2068 struct per_cpu_pages *pcp;
2069 unsigned long flags;
2070 unsigned long pfn = page_to_pfn(page);
2073 if (!free_pages_prepare(page, 0))
2076 migratetype = get_pfnblock_migratetype(page, pfn);
2077 set_pcppage_migratetype(page, migratetype);
2078 local_irq_save(flags);
2079 __count_vm_event(PGFREE);
2082 * We only track unmovable, reclaimable and movable on pcp lists.
2083 * Free ISOLATE pages back to the allocator because they are being
2084 * offlined but treat RESERVE as movable pages so we can get those
2085 * areas back if necessary. Otherwise, we may have to free
2086 * excessively into the page allocator
2088 if (migratetype >= MIGRATE_PCPTYPES) {
2089 if (unlikely(is_migrate_isolate(migratetype))) {
2090 free_one_page(zone, page, pfn, 0, migratetype);
2093 migratetype = MIGRATE_MOVABLE;
2096 pcp = &this_cpu_ptr(zone->pageset)->pcp;
2098 list_add(&page->lru, &pcp->lists[migratetype]);
2100 list_add_tail(&page->lru, &pcp->lists[migratetype]);
2102 if (pcp->count >= pcp->high) {
2103 unsigned long batch = READ_ONCE(pcp->batch);
2104 free_pcppages_bulk(zone, batch, pcp);
2105 pcp->count -= batch;
2109 local_irq_restore(flags);
2113 * Free a list of 0-order pages
2115 void free_hot_cold_page_list(struct list_head *list, bool cold)
2117 struct page *page, *next;
2119 list_for_each_entry_safe(page, next, list, lru) {
2120 trace_mm_page_free_batched(page, cold);
2121 free_hot_cold_page(page, cold);
2126 * split_page takes a non-compound higher-order page, and splits it into
2127 * n (1<<order) sub-pages: page[0..n]
2128 * Each sub-page must be freed individually.
2130 * Note: this is probably too low level an operation for use in drivers.
2131 * Please consult with lkml before using this in your driver.
2133 void split_page(struct page *page, unsigned int order)
2138 VM_BUG_ON_PAGE(PageCompound(page), page);
2139 VM_BUG_ON_PAGE(!page_count(page), page);
2141 #ifdef CONFIG_KMEMCHECK
2143 * Split shadow pages too, because free(page[0]) would
2144 * otherwise free the whole shadow.
2146 if (kmemcheck_page_is_tracked(page))
2147 split_page(virt_to_page(page[0].shadow), order);
2150 gfp_mask = get_page_owner_gfp(page);
2151 set_page_owner(page, 0, gfp_mask);
2152 for (i = 1; i < (1 << order); i++) {
2153 set_page_refcounted(page + i);
2154 set_page_owner(page + i, 0, gfp_mask);
2157 EXPORT_SYMBOL_GPL(split_page);
2159 int __isolate_free_page(struct page *page, unsigned int order)
2161 unsigned long watermark;
2165 BUG_ON(!PageBuddy(page));
2167 zone = page_zone(page);
2168 mt = get_pageblock_migratetype(page);
2170 if (!is_migrate_isolate(mt)) {
2171 /* Obey watermarks as if the page was being allocated */
2172 watermark = low_wmark_pages(zone) + (1 << order);
2173 if (!zone_watermark_ok(zone, 0, watermark, 0, 0))
2176 __mod_zone_freepage_state(zone, -(1UL << order), mt);
2179 /* Remove page from free list */
2180 list_del(&page->lru);
2181 zone->free_area[order].nr_free--;
2182 rmv_page_order(page);
2184 set_page_owner(page, order, __GFP_MOVABLE);
2186 /* Set the pageblock if the isolated page is at least a pageblock */
2187 if (order >= pageblock_order - 1) {
2188 struct page *endpage = page + (1 << order) - 1;
2189 for (; page < endpage; page += pageblock_nr_pages) {
2190 int mt = get_pageblock_migratetype(page);
2191 if (!is_migrate_isolate(mt) && !is_migrate_cma(mt))
2192 set_pageblock_migratetype(page,
2198 return 1UL << order;
2202 * Similar to split_page except the page is already free. As this is only
2203 * being used for migration, the migratetype of the block also changes.
2204 * As this is called with interrupts disabled, the caller is responsible
2205 * for calling arch_alloc_page() and kernel_map_page() after interrupts
2208 * Note: this is probably too low level an operation for use in drivers.
2209 * Please consult with lkml before using this in your driver.
2211 int split_free_page(struct page *page)
2216 order = page_order(page);
2218 nr_pages = __isolate_free_page(page, order);
2222 /* Split into individual pages */
2223 set_page_refcounted(page);
2224 split_page(page, order);
2229 * Allocate a page from the given zone. Use pcplists for order-0 allocations.
2232 struct page *buffered_rmqueue(struct zone *preferred_zone,
2233 struct zone *zone, unsigned int order,
2234 gfp_t gfp_flags, int alloc_flags, int migratetype)
2236 unsigned long flags;
2238 bool cold = ((gfp_flags & __GFP_COLD) != 0);
2240 if (likely(order == 0)) {
2241 struct per_cpu_pages *pcp;
2242 struct list_head *list;
2244 local_irq_save(flags);
2245 pcp = &this_cpu_ptr(zone->pageset)->pcp;
2246 list = &pcp->lists[migratetype];
2247 if (list_empty(list)) {
2248 pcp->count += rmqueue_bulk(zone, 0,
2251 if (unlikely(list_empty(list)))
2256 page = list_entry(list->prev, struct page, lru);
2258 page = list_entry(list->next, struct page, lru);
2260 list_del(&page->lru);
2263 if (unlikely(gfp_flags & __GFP_NOFAIL)) {
2265 * __GFP_NOFAIL is not to be used in new code.
2267 * All __GFP_NOFAIL callers should be fixed so that they
2268 * properly detect and handle allocation failures.
2270 * We most definitely don't want callers attempting to
2271 * allocate greater than order-1 page units with
2274 WARN_ON_ONCE(order > 1);
2276 spin_lock_irqsave(&zone->lock, flags);
2279 if (alloc_flags & ALLOC_HARDER) {
2280 page = __rmqueue_smallest(zone, order, MIGRATE_HIGHATOMIC);
2282 trace_mm_page_alloc_zone_locked(page, order, migratetype);
2285 page = __rmqueue(zone, order, migratetype, gfp_flags);
2286 spin_unlock(&zone->lock);
2289 __mod_zone_freepage_state(zone, -(1 << order),
2290 get_pcppage_migratetype(page));
2293 __mod_zone_page_state(zone, NR_ALLOC_BATCH, -(1 << order));
2294 if (atomic_long_read(&zone->vm_stat[NR_ALLOC_BATCH]) <= 0 &&
2295 !test_bit(ZONE_FAIR_DEPLETED, &zone->flags))
2296 set_bit(ZONE_FAIR_DEPLETED, &zone->flags);
2298 __count_zone_vm_events(PGALLOC, zone, 1 << order);
2299 zone_statistics(preferred_zone, zone, gfp_flags);
2300 local_irq_restore(flags);
2302 VM_BUG_ON_PAGE(bad_range(zone, page), page);
2306 local_irq_restore(flags);
2310 #ifdef CONFIG_FAIL_PAGE_ALLOC
2313 struct fault_attr attr;
2315 bool ignore_gfp_highmem;
2316 bool ignore_gfp_reclaim;
2318 } fail_page_alloc = {
2319 .attr = FAULT_ATTR_INITIALIZER,
2320 .ignore_gfp_reclaim = true,
2321 .ignore_gfp_highmem = true,
2325 static int __init setup_fail_page_alloc(char *str)
2327 return setup_fault_attr(&fail_page_alloc.attr, str);
2329 __setup("fail_page_alloc=", setup_fail_page_alloc);
2331 static bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
2333 if (order < fail_page_alloc.min_order)
2335 if (gfp_mask & __GFP_NOFAIL)
2337 if (fail_page_alloc.ignore_gfp_highmem && (gfp_mask & __GFP_HIGHMEM))
2339 if (fail_page_alloc.ignore_gfp_reclaim &&
2340 (gfp_mask & __GFP_DIRECT_RECLAIM))
2343 return should_fail(&fail_page_alloc.attr, 1 << order);
2346 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
2348 static int __init fail_page_alloc_debugfs(void)
2350 umode_t mode = S_IFREG | S_IRUSR | S_IWUSR;
2353 dir = fault_create_debugfs_attr("fail_page_alloc", NULL,
2354 &fail_page_alloc.attr);
2356 return PTR_ERR(dir);
2358 if (!debugfs_create_bool("ignore-gfp-wait", mode, dir,
2359 &fail_page_alloc.ignore_gfp_reclaim))
2361 if (!debugfs_create_bool("ignore-gfp-highmem", mode, dir,
2362 &fail_page_alloc.ignore_gfp_highmem))
2364 if (!debugfs_create_u32("min-order", mode, dir,
2365 &fail_page_alloc.min_order))
2370 debugfs_remove_recursive(dir);
2375 late_initcall(fail_page_alloc_debugfs);
2377 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
2379 #else /* CONFIG_FAIL_PAGE_ALLOC */
2381 static inline bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
2386 #endif /* CONFIG_FAIL_PAGE_ALLOC */
2389 * Return true if free base pages are above 'mark'. For high-order checks it
2390 * will return true of the order-0 watermark is reached and there is at least
2391 * one free page of a suitable size. Checking now avoids taking the zone lock
2392 * to check in the allocation paths if no pages are free.
2394 static bool __zone_watermark_ok(struct zone *z, unsigned int order,
2395 unsigned long mark, int classzone_idx, int alloc_flags,
2400 const int alloc_harder = (alloc_flags & ALLOC_HARDER);
2402 /* free_pages may go negative - that's OK */
2403 free_pages -= (1 << order) - 1;
2405 if (alloc_flags & ALLOC_HIGH)
2409 * If the caller does not have rights to ALLOC_HARDER then subtract
2410 * the high-atomic reserves. This will over-estimate the size of the
2411 * atomic reserve but it avoids a search.
2413 if (likely(!alloc_harder))
2414 free_pages -= z->nr_reserved_highatomic;
2419 /* If allocation can't use CMA areas don't use free CMA pages */
2420 if (!(alloc_flags & ALLOC_CMA))
2421 free_pages -= zone_page_state(z, NR_FREE_CMA_PAGES);
2425 * Check watermarks for an order-0 allocation request. If these
2426 * are not met, then a high-order request also cannot go ahead
2427 * even if a suitable page happened to be free.
2429 if (free_pages <= min + z->lowmem_reserve[classzone_idx])
2432 /* If this is an order-0 request then the watermark is fine */
2436 /* For a high-order request, check at least one suitable page is free */
2437 for (o = order; o < MAX_ORDER; o++) {
2438 struct free_area *area = &z->free_area[o];
2447 for (mt = 0; mt < MIGRATE_PCPTYPES; mt++) {
2448 if (!list_empty(&area->free_list[mt]))
2453 if ((alloc_flags & ALLOC_CMA) &&
2454 !list_empty(&area->free_list[MIGRATE_CMA])) {
2462 bool zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
2463 int classzone_idx, int alloc_flags)
2465 return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
2466 zone_page_state(z, NR_FREE_PAGES));
2469 bool zone_watermark_ok_safe(struct zone *z, unsigned int order,
2470 unsigned long mark, int classzone_idx)
2472 long free_pages = zone_page_state(z, NR_FREE_PAGES);
2474 if (z->percpu_drift_mark && free_pages < z->percpu_drift_mark)
2475 free_pages = zone_page_state_snapshot(z, NR_FREE_PAGES);
2477 return __zone_watermark_ok(z, order, mark, classzone_idx, 0,
2482 static bool zone_local(struct zone *local_zone, struct zone *zone)
2484 return local_zone->node == zone->node;
2487 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
2489 return node_distance(zone_to_nid(local_zone), zone_to_nid(zone)) <=
2492 #else /* CONFIG_NUMA */
2493 static bool zone_local(struct zone *local_zone, struct zone *zone)
2498 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
2502 #endif /* CONFIG_NUMA */
2504 static void reset_alloc_batches(struct zone *preferred_zone)
2506 struct zone *zone = preferred_zone->zone_pgdat->node_zones;
2509 mod_zone_page_state(zone, NR_ALLOC_BATCH,
2510 high_wmark_pages(zone) - low_wmark_pages(zone) -
2511 atomic_long_read(&zone->vm_stat[NR_ALLOC_BATCH]));
2512 clear_bit(ZONE_FAIR_DEPLETED, &zone->flags);
2513 } while (zone++ != preferred_zone);
2517 * get_page_from_freelist goes through the zonelist trying to allocate
2520 static struct page *
2521 get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags,
2522 const struct alloc_context *ac)
2524 struct zonelist *zonelist = ac->zonelist;
2526 struct page *page = NULL;
2528 int nr_fair_skipped = 0;
2529 bool zonelist_rescan;
2532 zonelist_rescan = false;
2535 * Scan zonelist, looking for a zone with enough free.
2536 * See also __cpuset_node_allowed() comment in kernel/cpuset.c.
2538 for_each_zone_zonelist_nodemask(zone, z, zonelist, ac->high_zoneidx,
2542 if (cpusets_enabled() &&
2543 (alloc_flags & ALLOC_CPUSET) &&
2544 !cpuset_zone_allowed(zone, gfp_mask))
2547 * Distribute pages in proportion to the individual
2548 * zone size to ensure fair page aging. The zone a
2549 * page was allocated in should have no effect on the
2550 * time the page has in memory before being reclaimed.
2552 if (alloc_flags & ALLOC_FAIR) {
2553 if (!zone_local(ac->preferred_zone, zone))
2555 if (test_bit(ZONE_FAIR_DEPLETED, &zone->flags)) {
2561 * When allocating a page cache page for writing, we
2562 * want to get it from a zone that is within its dirty
2563 * limit, such that no single zone holds more than its
2564 * proportional share of globally allowed dirty pages.
2565 * The dirty limits take into account the zone's
2566 * lowmem reserves and high watermark so that kswapd
2567 * should be able to balance it without having to
2568 * write pages from its LRU list.
2570 * This may look like it could increase pressure on
2571 * lower zones by failing allocations in higher zones
2572 * before they are full. But the pages that do spill
2573 * over are limited as the lower zones are protected
2574 * by this very same mechanism. It should not become
2575 * a practical burden to them.
2577 * XXX: For now, allow allocations to potentially
2578 * exceed the per-zone dirty limit in the slowpath
2579 * (spread_dirty_pages unset) before going into reclaim,
2580 * which is important when on a NUMA setup the allowed
2581 * zones are together not big enough to reach the
2582 * global limit. The proper fix for these situations
2583 * will require awareness of zones in the
2584 * dirty-throttling and the flusher threads.
2586 if (ac->spread_dirty_pages && !zone_dirty_ok(zone))
2589 mark = zone->watermark[alloc_flags & ALLOC_WMARK_MASK];
2590 if (!zone_watermark_ok(zone, order, mark,
2591 ac->classzone_idx, alloc_flags)) {
2594 /* Checked here to keep the fast path fast */
2595 BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK);
2596 if (alloc_flags & ALLOC_NO_WATERMARKS)
2599 if (zone_reclaim_mode == 0 ||
2600 !zone_allows_reclaim(ac->preferred_zone, zone))
2603 ret = zone_reclaim(zone, gfp_mask, order);
2605 case ZONE_RECLAIM_NOSCAN:
2608 case ZONE_RECLAIM_FULL:
2609 /* scanned but unreclaimable */
2612 /* did we reclaim enough */
2613 if (zone_watermark_ok(zone, order, mark,
2614 ac->classzone_idx, alloc_flags))
2622 page = buffered_rmqueue(ac->preferred_zone, zone, order,
2623 gfp_mask, alloc_flags, ac->migratetype);
2625 if (prep_new_page(page, order, gfp_mask, alloc_flags))
2629 * If this is a high-order atomic allocation then check
2630 * if the pageblock should be reserved for the future
2632 if (unlikely(order && (alloc_flags & ALLOC_HARDER)))
2633 reserve_highatomic_pageblock(page, zone, order);
2640 * The first pass makes sure allocations are spread fairly within the
2641 * local node. However, the local node might have free pages left
2642 * after the fairness batches are exhausted, and remote zones haven't
2643 * even been considered yet. Try once more without fairness, and
2644 * include remote zones now, before entering the slowpath and waking
2645 * kswapd: prefer spilling to a remote zone over swapping locally.
2647 if (alloc_flags & ALLOC_FAIR) {
2648 alloc_flags &= ~ALLOC_FAIR;
2649 if (nr_fair_skipped) {
2650 zonelist_rescan = true;
2651 reset_alloc_batches(ac->preferred_zone);
2653 if (nr_online_nodes > 1)
2654 zonelist_rescan = true;
2657 if (zonelist_rescan)
2664 * Large machines with many possible nodes should not always dump per-node
2665 * meminfo in irq context.
2667 static inline bool should_suppress_show_mem(void)
2672 ret = in_interrupt();
2677 static DEFINE_RATELIMIT_STATE(nopage_rs,
2678 DEFAULT_RATELIMIT_INTERVAL,
2679 DEFAULT_RATELIMIT_BURST);
2681 void warn_alloc_failed(gfp_t gfp_mask, unsigned int order, const char *fmt, ...)
2683 unsigned int filter = SHOW_MEM_FILTER_NODES;
2685 if ((gfp_mask & __GFP_NOWARN) || !__ratelimit(&nopage_rs) ||
2686 debug_guardpage_minorder() > 0)
2690 * This documents exceptions given to allocations in certain
2691 * contexts that are allowed to allocate outside current's set
2694 if (!(gfp_mask & __GFP_NOMEMALLOC))
2695 if (test_thread_flag(TIF_MEMDIE) ||
2696 (current->flags & (PF_MEMALLOC | PF_EXITING)))
2697 filter &= ~SHOW_MEM_FILTER_NODES;
2698 if (in_interrupt() || !(gfp_mask & __GFP_DIRECT_RECLAIM))
2699 filter &= ~SHOW_MEM_FILTER_NODES;
2702 struct va_format vaf;
2705 va_start(args, fmt);
2710 pr_warn("%pV", &vaf);
2715 pr_warn("%s: page allocation failure: order:%u, mode:0x%x\n",
2716 current->comm, order, gfp_mask);
2719 if (!should_suppress_show_mem())
2723 static inline struct page *
2724 __alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order,
2725 const struct alloc_context *ac, unsigned long *did_some_progress)
2727 struct oom_control oc = {
2728 .zonelist = ac->zonelist,
2729 .nodemask = ac->nodemask,
2730 .gfp_mask = gfp_mask,
2735 *did_some_progress = 0;
2738 * Acquire the oom lock. If that fails, somebody else is
2739 * making progress for us.
2741 if (!mutex_trylock(&oom_lock)) {
2742 *did_some_progress = 1;
2743 schedule_timeout_uninterruptible(1);
2748 * Go through the zonelist yet one more time, keep very high watermark
2749 * here, this is only to catch a parallel oom killing, we must fail if
2750 * we're still under heavy pressure.
2752 page = get_page_from_freelist(gfp_mask | __GFP_HARDWALL, order,
2753 ALLOC_WMARK_HIGH|ALLOC_CPUSET, ac);
2757 if (!(gfp_mask & __GFP_NOFAIL)) {
2758 /* Coredumps can quickly deplete all memory reserves */
2759 if (current->flags & PF_DUMPCORE)
2761 /* The OOM killer will not help higher order allocs */
2762 if (order > PAGE_ALLOC_COSTLY_ORDER)
2764 /* The OOM killer does not needlessly kill tasks for lowmem */
2765 if (ac->high_zoneidx < ZONE_NORMAL)
2767 /* The OOM killer does not compensate for IO-less reclaim */
2768 if (!(gfp_mask & __GFP_FS)) {
2770 * XXX: Page reclaim didn't yield anything,
2771 * and the OOM killer can't be invoked, but
2772 * keep looping as per tradition.
2774 *did_some_progress = 1;
2777 if (pm_suspended_storage())
2779 /* The OOM killer may not free memory on a specific node */
2780 if (gfp_mask & __GFP_THISNODE)
2783 /* Exhausted what can be done so it's blamo time */
2784 if (out_of_memory(&oc) || WARN_ON_ONCE(gfp_mask & __GFP_NOFAIL))
2785 *did_some_progress = 1;
2787 mutex_unlock(&oom_lock);
2791 #ifdef CONFIG_COMPACTION
2792 /* Try memory compaction for high-order allocations before reclaim */
2793 static struct page *
2794 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
2795 int alloc_flags, const struct alloc_context *ac,
2796 enum migrate_mode mode, int *contended_compaction,
2797 bool *deferred_compaction)
2799 unsigned long compact_result;
2805 current->flags |= PF_MEMALLOC;
2806 compact_result = try_to_compact_pages(gfp_mask, order, alloc_flags, ac,
2807 mode, contended_compaction);
2808 current->flags &= ~PF_MEMALLOC;
2810 switch (compact_result) {
2811 case COMPACT_DEFERRED:
2812 *deferred_compaction = true;
2814 case COMPACT_SKIPPED:
2821 * At least in one zone compaction wasn't deferred or skipped, so let's
2822 * count a compaction stall
2824 count_vm_event(COMPACTSTALL);
2826 page = get_page_from_freelist(gfp_mask, order,
2827 alloc_flags & ~ALLOC_NO_WATERMARKS, ac);
2830 struct zone *zone = page_zone(page);
2832 zone->compact_blockskip_flush = false;
2833 compaction_defer_reset(zone, order, true);
2834 count_vm_event(COMPACTSUCCESS);
2839 * It's bad if compaction run occurs and fails. The most likely reason
2840 * is that pages exist, but not enough to satisfy watermarks.
2842 count_vm_event(COMPACTFAIL);
2849 static inline struct page *
2850 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
2851 int alloc_flags, const struct alloc_context *ac,
2852 enum migrate_mode mode, int *contended_compaction,
2853 bool *deferred_compaction)
2857 #endif /* CONFIG_COMPACTION */
2859 /* Perform direct synchronous page reclaim */
2861 __perform_reclaim(gfp_t gfp_mask, unsigned int order,
2862 const struct alloc_context *ac)
2864 struct reclaim_state reclaim_state;
2869 /* We now go into synchronous reclaim */
2870 cpuset_memory_pressure_bump();
2871 current->flags |= PF_MEMALLOC;
2872 lockdep_set_current_reclaim_state(gfp_mask);
2873 reclaim_state.reclaimed_slab = 0;
2874 current->reclaim_state = &reclaim_state;
2876 progress = try_to_free_pages(ac->zonelist, order, gfp_mask,
2879 current->reclaim_state = NULL;
2880 lockdep_clear_current_reclaim_state();
2881 current->flags &= ~PF_MEMALLOC;
2888 /* The really slow allocator path where we enter direct reclaim */
2889 static inline struct page *
2890 __alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order,
2891 int alloc_flags, const struct alloc_context *ac,
2892 unsigned long *did_some_progress)
2894 struct page *page = NULL;
2895 bool drained = false;
2897 *did_some_progress = __perform_reclaim(gfp_mask, order, ac);
2898 if (unlikely(!(*did_some_progress)))
2902 page = get_page_from_freelist(gfp_mask, order,
2903 alloc_flags & ~ALLOC_NO_WATERMARKS, ac);
2906 * If an allocation failed after direct reclaim, it could be because
2907 * pages are pinned on the per-cpu lists or in high alloc reserves.
2908 * Shrink them them and try again
2910 if (!page && !drained) {
2911 unreserve_highatomic_pageblock(ac);
2912 drain_all_pages(NULL);
2921 * This is called in the allocator slow-path if the allocation request is of
2922 * sufficient urgency to ignore watermarks and take other desperate measures
2924 static inline struct page *
2925 __alloc_pages_high_priority(gfp_t gfp_mask, unsigned int order,
2926 const struct alloc_context *ac)
2931 page = get_page_from_freelist(gfp_mask, order,
2932 ALLOC_NO_WATERMARKS, ac);
2934 if (!page && gfp_mask & __GFP_NOFAIL)
2935 wait_iff_congested(ac->preferred_zone, BLK_RW_ASYNC,
2937 } while (!page && (gfp_mask & __GFP_NOFAIL));
2942 static void wake_all_kswapds(unsigned int order, const struct alloc_context *ac)
2947 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
2948 ac->high_zoneidx, ac->nodemask)
2949 wakeup_kswapd(zone, order, zone_idx(ac->preferred_zone));
2953 gfp_to_alloc_flags(gfp_t gfp_mask)
2955 int alloc_flags = ALLOC_WMARK_MIN | ALLOC_CPUSET;
2957 /* __GFP_HIGH is assumed to be the same as ALLOC_HIGH to save a branch. */
2958 BUILD_BUG_ON(__GFP_HIGH != (__force gfp_t) ALLOC_HIGH);
2961 * The caller may dip into page reserves a bit more if the caller
2962 * cannot run direct reclaim, or if the caller has realtime scheduling
2963 * policy or is asking for __GFP_HIGH memory. GFP_ATOMIC requests will
2964 * set both ALLOC_HARDER (__GFP_ATOMIC) and ALLOC_HIGH (__GFP_HIGH).
2966 alloc_flags |= (__force int) (gfp_mask & __GFP_HIGH);
2968 if (gfp_mask & __GFP_ATOMIC) {
2970 * Not worth trying to allocate harder for __GFP_NOMEMALLOC even
2971 * if it can't schedule.
2973 if (!(gfp_mask & __GFP_NOMEMALLOC))
2974 alloc_flags |= ALLOC_HARDER;
2976 * Ignore cpuset mems for GFP_ATOMIC rather than fail, see the
2977 * comment for __cpuset_node_allowed().
2979 alloc_flags &= ~ALLOC_CPUSET;
2980 } else if (unlikely(rt_task(current)) && !in_interrupt())
2981 alloc_flags |= ALLOC_HARDER;
2983 if (likely(!(gfp_mask & __GFP_NOMEMALLOC))) {
2984 if (gfp_mask & __GFP_MEMALLOC)
2985 alloc_flags |= ALLOC_NO_WATERMARKS;
2986 else if (in_serving_softirq() && (current->flags & PF_MEMALLOC))
2987 alloc_flags |= ALLOC_NO_WATERMARKS;
2988 else if (!in_interrupt() &&
2989 ((current->flags & PF_MEMALLOC) ||
2990 unlikely(test_thread_flag(TIF_MEMDIE))))
2991 alloc_flags |= ALLOC_NO_WATERMARKS;
2994 if (gfpflags_to_migratetype(gfp_mask) == MIGRATE_MOVABLE)
2995 alloc_flags |= ALLOC_CMA;
3000 bool gfp_pfmemalloc_allowed(gfp_t gfp_mask)
3002 return !!(gfp_to_alloc_flags(gfp_mask) & ALLOC_NO_WATERMARKS);
3005 static inline bool is_thp_gfp_mask(gfp_t gfp_mask)
3007 return (gfp_mask & (GFP_TRANSHUGE | __GFP_KSWAPD_RECLAIM)) == GFP_TRANSHUGE;
3010 static inline struct page *
3011 __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order,
3012 struct alloc_context *ac)
3014 bool can_direct_reclaim = gfp_mask & __GFP_DIRECT_RECLAIM;
3015 struct page *page = NULL;
3017 unsigned long pages_reclaimed = 0;
3018 unsigned long did_some_progress;
3019 enum migrate_mode migration_mode = MIGRATE_ASYNC;
3020 bool deferred_compaction = false;
3021 int contended_compaction = COMPACT_CONTENDED_NONE;
3024 * In the slowpath, we sanity check order to avoid ever trying to
3025 * reclaim >= MAX_ORDER areas which will never succeed. Callers may
3026 * be using allocators in order of preference for an area that is
3029 if (order >= MAX_ORDER) {
3030 WARN_ON_ONCE(!(gfp_mask & __GFP_NOWARN));
3035 * We also sanity check to catch abuse of atomic reserves being used by
3036 * callers that are not in atomic context.
3038 if (WARN_ON_ONCE((gfp_mask & (__GFP_ATOMIC|__GFP_DIRECT_RECLAIM)) ==
3039 (__GFP_ATOMIC|__GFP_DIRECT_RECLAIM)))
3040 gfp_mask &= ~__GFP_ATOMIC;
3043 * If this allocation cannot block and it is for a specific node, then
3044 * fail early. There's no need to wakeup kswapd or retry for a
3045 * speculative node-specific allocation.
3047 if (IS_ENABLED(CONFIG_NUMA) && (gfp_mask & __GFP_THISNODE) && !can_direct_reclaim)
3051 if (gfp_mask & __GFP_KSWAPD_RECLAIM)
3052 wake_all_kswapds(order, ac);
3055 * OK, we're below the kswapd watermark and have kicked background
3056 * reclaim. Now things get more complex, so set up alloc_flags according
3057 * to how we want to proceed.
3059 alloc_flags = gfp_to_alloc_flags(gfp_mask);
3062 * Find the true preferred zone if the allocation is unconstrained by
3065 if (!(alloc_flags & ALLOC_CPUSET) && !ac->nodemask) {
3066 struct zoneref *preferred_zoneref;
3067 preferred_zoneref = first_zones_zonelist(ac->zonelist,
3068 ac->high_zoneidx, NULL, &ac->preferred_zone);
3069 ac->classzone_idx = zonelist_zone_idx(preferred_zoneref);
3072 /* This is the last chance, in general, before the goto nopage. */
3073 page = get_page_from_freelist(gfp_mask, order,
3074 alloc_flags & ~ALLOC_NO_WATERMARKS, ac);
3078 /* Allocate without watermarks if the context allows */
3079 if (alloc_flags & ALLOC_NO_WATERMARKS) {
3081 * Ignore mempolicies if ALLOC_NO_WATERMARKS on the grounds
3082 * the allocation is high priority and these type of
3083 * allocations are system rather than user orientated
3085 ac->zonelist = node_zonelist(numa_node_id(), gfp_mask);
3087 page = __alloc_pages_high_priority(gfp_mask, order, ac);
3094 /* Caller is not willing to reclaim, we can't balance anything */
3095 if (!can_direct_reclaim) {
3097 * All existing users of the deprecated __GFP_NOFAIL are
3098 * blockable, so warn of any new users that actually allow this
3099 * type of allocation to fail.
3101 WARN_ON_ONCE(gfp_mask & __GFP_NOFAIL);
3105 /* Avoid recursion of direct reclaim */
3106 if (current->flags & PF_MEMALLOC)
3109 /* Avoid allocations with no watermarks from looping endlessly */
3110 if (test_thread_flag(TIF_MEMDIE) && !(gfp_mask & __GFP_NOFAIL))
3114 * Try direct compaction. The first pass is asynchronous. Subsequent
3115 * attempts after direct reclaim are synchronous
3117 page = __alloc_pages_direct_compact(gfp_mask, order, alloc_flags, ac,
3119 &contended_compaction,
3120 &deferred_compaction);
3124 /* Checks for THP-specific high-order allocations */
3125 if (is_thp_gfp_mask(gfp_mask)) {
3127 * If compaction is deferred for high-order allocations, it is
3128 * because sync compaction recently failed. If this is the case
3129 * and the caller requested a THP allocation, we do not want
3130 * to heavily disrupt the system, so we fail the allocation
3131 * instead of entering direct reclaim.
3133 if (deferred_compaction)
3137 * In all zones where compaction was attempted (and not
3138 * deferred or skipped), lock contention has been detected.
3139 * For THP allocation we do not want to disrupt the others
3140 * so we fallback to base pages instead.
3142 if (contended_compaction == COMPACT_CONTENDED_LOCK)
3146 * If compaction was aborted due to need_resched(), we do not
3147 * want to further increase allocation latency, unless it is
3148 * khugepaged trying to collapse.
3150 if (contended_compaction == COMPACT_CONTENDED_SCHED
3151 && !(current->flags & PF_KTHREAD))
3156 * It can become very expensive to allocate transparent hugepages at
3157 * fault, so use asynchronous memory compaction for THP unless it is
3158 * khugepaged trying to collapse.
3160 if (!is_thp_gfp_mask(gfp_mask) || (current->flags & PF_KTHREAD))
3161 migration_mode = MIGRATE_SYNC_LIGHT;
3163 /* Try direct reclaim and then allocating */
3164 page = __alloc_pages_direct_reclaim(gfp_mask, order, alloc_flags, ac,
3165 &did_some_progress);
3169 /* Do not loop if specifically requested */
3170 if (gfp_mask & __GFP_NORETRY)
3173 /* Keep reclaiming pages as long as there is reasonable progress */
3174 pages_reclaimed += did_some_progress;
3175 if ((did_some_progress && order <= PAGE_ALLOC_COSTLY_ORDER) ||
3176 ((gfp_mask & __GFP_REPEAT) && pages_reclaimed < (1 << order))) {
3177 /* Wait for some write requests to complete then retry */
3178 wait_iff_congested(ac->preferred_zone, BLK_RW_ASYNC, HZ/50);
3182 /* Reclaim has failed us, start killing things */
3183 page = __alloc_pages_may_oom(gfp_mask, order, ac, &did_some_progress);
3187 /* Retry as long as the OOM killer is making progress */
3188 if (did_some_progress)
3193 * High-order allocations do not necessarily loop after
3194 * direct reclaim and reclaim/compaction depends on compaction
3195 * being called after reclaim so call directly if necessary
3197 page = __alloc_pages_direct_compact(gfp_mask, order, alloc_flags,
3199 &contended_compaction,
3200 &deferred_compaction);
3204 warn_alloc_failed(gfp_mask, order, NULL);
3210 * This is the 'heart' of the zoned buddy allocator.
3213 __alloc_pages_nodemask(gfp_t gfp_mask, unsigned int order,
3214 struct zonelist *zonelist, nodemask_t *nodemask)
3216 struct zoneref *preferred_zoneref;
3217 struct page *page = NULL;
3218 unsigned int cpuset_mems_cookie;
3219 int alloc_flags = ALLOC_WMARK_LOW|ALLOC_CPUSET|ALLOC_FAIR;
3220 gfp_t alloc_mask; /* The gfp_t that was actually used for allocation */
3221 struct alloc_context ac = {
3222 .high_zoneidx = gfp_zone(gfp_mask),
3223 .nodemask = nodemask,
3224 .migratetype = gfpflags_to_migratetype(gfp_mask),
3227 gfp_mask &= gfp_allowed_mask;
3229 lockdep_trace_alloc(gfp_mask);
3231 might_sleep_if(gfp_mask & __GFP_DIRECT_RECLAIM);
3233 if (should_fail_alloc_page(gfp_mask, order))
3237 * Check the zones suitable for the gfp_mask contain at least one
3238 * valid zone. It's possible to have an empty zonelist as a result
3239 * of __GFP_THISNODE and a memoryless node
3241 if (unlikely(!zonelist->_zonerefs->zone))
3244 if (IS_ENABLED(CONFIG_CMA) && ac.migratetype == MIGRATE_MOVABLE)
3245 alloc_flags |= ALLOC_CMA;
3248 cpuset_mems_cookie = read_mems_allowed_begin();
3250 /* We set it here, as __alloc_pages_slowpath might have changed it */
3251 ac.zonelist = zonelist;
3253 /* Dirty zone balancing only done in the fast path */
3254 ac.spread_dirty_pages = (gfp_mask & __GFP_WRITE);
3256 /* The preferred zone is used for statistics later */
3257 preferred_zoneref = first_zones_zonelist(ac.zonelist, ac.high_zoneidx,
3258 ac.nodemask ? : &cpuset_current_mems_allowed,
3259 &ac.preferred_zone);
3260 if (!ac.preferred_zone)
3262 ac.classzone_idx = zonelist_zone_idx(preferred_zoneref);
3264 /* First allocation attempt */
3265 alloc_mask = gfp_mask|__GFP_HARDWALL;
3266 page = get_page_from_freelist(alloc_mask, order, alloc_flags, &ac);
3267 if (unlikely(!page)) {
3269 * Runtime PM, block IO and its error handling path
3270 * can deadlock because I/O on the device might not
3273 alloc_mask = memalloc_noio_flags(gfp_mask);
3274 ac.spread_dirty_pages = false;
3276 page = __alloc_pages_slowpath(alloc_mask, order, &ac);
3279 if (kmemcheck_enabled && page)
3280 kmemcheck_pagealloc_alloc(page, order, gfp_mask);
3282 trace_mm_page_alloc(page, order, alloc_mask, ac.migratetype);
3286 * When updating a task's mems_allowed, it is possible to race with
3287 * parallel threads in such a way that an allocation can fail while
3288 * the mask is being updated. If a page allocation is about to fail,
3289 * check if the cpuset changed during allocation and if so, retry.
3291 if (unlikely(!page && read_mems_allowed_retry(cpuset_mems_cookie)))
3296 EXPORT_SYMBOL(__alloc_pages_nodemask);
3299 * Common helper functions.
3301 unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order)
3306 * __get_free_pages() returns a 32-bit address, which cannot represent
3309 VM_BUG_ON((gfp_mask & __GFP_HIGHMEM) != 0);
3311 page = alloc_pages(gfp_mask, order);
3314 return (unsigned long) page_address(page);
3316 EXPORT_SYMBOL(__get_free_pages);
3318 unsigned long get_zeroed_page(gfp_t gfp_mask)
3320 return __get_free_pages(gfp_mask | __GFP_ZERO, 0);
3322 EXPORT_SYMBOL(get_zeroed_page);
3324 void __free_pages(struct page *page, unsigned int order)
3326 if (put_page_testzero(page)) {
3328 free_hot_cold_page(page, false);
3330 __free_pages_ok(page, order);
3334 EXPORT_SYMBOL(__free_pages);
3336 void free_pages(unsigned long addr, unsigned int order)
3339 VM_BUG_ON(!virt_addr_valid((void *)addr));
3340 __free_pages(virt_to_page((void *)addr), order);
3344 EXPORT_SYMBOL(free_pages);
3348 * An arbitrary-length arbitrary-offset area of memory which resides
3349 * within a 0 or higher order page. Multiple fragments within that page
3350 * are individually refcounted, in the page's reference counter.
3352 * The page_frag functions below provide a simple allocation framework for
3353 * page fragments. This is used by the network stack and network device
3354 * drivers to provide a backing region of memory for use as either an
3355 * sk_buff->head, or to be used in the "frags" portion of skb_shared_info.
3357 static struct page *__page_frag_refill(struct page_frag_cache *nc,
3360 struct page *page = NULL;
3361 gfp_t gfp = gfp_mask;
3363 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
3364 gfp_mask |= __GFP_COMP | __GFP_NOWARN | __GFP_NORETRY |
3366 page = alloc_pages_node(NUMA_NO_NODE, gfp_mask,
3367 PAGE_FRAG_CACHE_MAX_ORDER);
3368 nc->size = page ? PAGE_FRAG_CACHE_MAX_SIZE : PAGE_SIZE;
3370 if (unlikely(!page))
3371 page = alloc_pages_node(NUMA_NO_NODE, gfp, 0);
3373 nc->va = page ? page_address(page) : NULL;
3378 void *__alloc_page_frag(struct page_frag_cache *nc,
3379 unsigned int fragsz, gfp_t gfp_mask)
3381 unsigned int size = PAGE_SIZE;
3385 if (unlikely(!nc->va)) {
3387 page = __page_frag_refill(nc, gfp_mask);
3391 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
3392 /* if size can vary use size else just use PAGE_SIZE */
3395 /* Even if we own the page, we do not use atomic_set().
3396 * This would break get_page_unless_zero() users.
3398 atomic_add(size - 1, &page->_count);
3400 /* reset page count bias and offset to start of new frag */
3401 nc->pfmemalloc = page_is_pfmemalloc(page);
3402 nc->pagecnt_bias = size;
3406 offset = nc->offset - fragsz;
3407 if (unlikely(offset < 0)) {
3408 page = virt_to_page(nc->va);
3410 if (!atomic_sub_and_test(nc->pagecnt_bias, &page->_count))
3413 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
3414 /* if size can vary use size else just use PAGE_SIZE */
3417 /* OK, page count is 0, we can safely set it */
3418 atomic_set(&page->_count, size);
3420 /* reset page count bias and offset to start of new frag */
3421 nc->pagecnt_bias = size;
3422 offset = size - fragsz;
3426 nc->offset = offset;
3428 return nc->va + offset;
3430 EXPORT_SYMBOL(__alloc_page_frag);
3433 * Frees a page fragment allocated out of either a compound or order 0 page.
3435 void __free_page_frag(void *addr)
3437 struct page *page = virt_to_head_page(addr);
3439 if (unlikely(put_page_testzero(page)))
3440 __free_pages_ok(page, compound_order(page));
3442 EXPORT_SYMBOL(__free_page_frag);
3445 * alloc_kmem_pages charges newly allocated pages to the kmem resource counter
3446 * of the current memory cgroup.
3448 * It should be used when the caller would like to use kmalloc, but since the
3449 * allocation is large, it has to fall back to the page allocator.
3451 struct page *alloc_kmem_pages(gfp_t gfp_mask, unsigned int order)
3455 page = alloc_pages(gfp_mask, order);
3456 if (page && memcg_kmem_charge(page, gfp_mask, order) != 0) {
3457 __free_pages(page, order);
3463 struct page *alloc_kmem_pages_node(int nid, gfp_t gfp_mask, unsigned int order)
3467 page = alloc_pages_node(nid, gfp_mask, order);
3468 if (page && memcg_kmem_charge(page, gfp_mask, order) != 0) {
3469 __free_pages(page, order);
3476 * __free_kmem_pages and free_kmem_pages will free pages allocated with
3479 void __free_kmem_pages(struct page *page, unsigned int order)
3481 memcg_kmem_uncharge(page, order);
3482 __free_pages(page, order);
3485 void free_kmem_pages(unsigned long addr, unsigned int order)
3488 VM_BUG_ON(!virt_addr_valid((void *)addr));
3489 __free_kmem_pages(virt_to_page((void *)addr), order);
3493 static void *make_alloc_exact(unsigned long addr, unsigned int order,
3497 unsigned long alloc_end = addr + (PAGE_SIZE << order);
3498 unsigned long used = addr + PAGE_ALIGN(size);
3500 split_page(virt_to_page((void *)addr), order);
3501 while (used < alloc_end) {
3506 return (void *)addr;
3510 * alloc_pages_exact - allocate an exact number physically-contiguous pages.
3511 * @size: the number of bytes to allocate
3512 * @gfp_mask: GFP flags for the allocation
3514 * This function is similar to alloc_pages(), except that it allocates the
3515 * minimum number of pages to satisfy the request. alloc_pages() can only
3516 * allocate memory in power-of-two pages.
3518 * This function is also limited by MAX_ORDER.
3520 * Memory allocated by this function must be released by free_pages_exact().
3522 void *alloc_pages_exact(size_t size, gfp_t gfp_mask)
3524 unsigned int order = get_order(size);
3527 addr = __get_free_pages(gfp_mask, order);
3528 return make_alloc_exact(addr, order, size);
3530 EXPORT_SYMBOL(alloc_pages_exact);
3533 * alloc_pages_exact_nid - allocate an exact number of physically-contiguous
3535 * @nid: the preferred node ID where memory should be allocated
3536 * @size: the number of bytes to allocate
3537 * @gfp_mask: GFP flags for the allocation
3539 * Like alloc_pages_exact(), but try to allocate on node nid first before falling
3542 void * __meminit alloc_pages_exact_nid(int nid, size_t size, gfp_t gfp_mask)
3544 unsigned int order = get_order(size);
3545 struct page *p = alloc_pages_node(nid, gfp_mask, order);
3548 return make_alloc_exact((unsigned long)page_address(p), order, size);
3552 * free_pages_exact - release memory allocated via alloc_pages_exact()
3553 * @virt: the value returned by alloc_pages_exact.
3554 * @size: size of allocation, same value as passed to alloc_pages_exact().
3556 * Release the memory allocated by a previous call to alloc_pages_exact.
3558 void free_pages_exact(void *virt, size_t size)
3560 unsigned long addr = (unsigned long)virt;
3561 unsigned long end = addr + PAGE_ALIGN(size);
3563 while (addr < end) {
3568 EXPORT_SYMBOL(free_pages_exact);
3571 * nr_free_zone_pages - count number of pages beyond high watermark
3572 * @offset: The zone index of the highest zone
3574 * nr_free_zone_pages() counts the number of counts pages which are beyond the
3575 * high watermark within all zones at or below a given zone index. For each
3576 * zone, the number of pages is calculated as:
3577 * managed_pages - high_pages
3579 static unsigned long nr_free_zone_pages(int offset)
3584 /* Just pick one node, since fallback list is circular */
3585 unsigned long sum = 0;
3587 struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL);
3589 for_each_zone_zonelist(zone, z, zonelist, offset) {
3590 unsigned long size = zone->managed_pages;
3591 unsigned long high = high_wmark_pages(zone);
3600 * nr_free_buffer_pages - count number of pages beyond high watermark
3602 * nr_free_buffer_pages() counts the number of pages which are beyond the high
3603 * watermark within ZONE_DMA and ZONE_NORMAL.
3605 unsigned long nr_free_buffer_pages(void)
3607 return nr_free_zone_pages(gfp_zone(GFP_USER));
3609 EXPORT_SYMBOL_GPL(nr_free_buffer_pages);
3612 * nr_free_pagecache_pages - count number of pages beyond high watermark
3614 * nr_free_pagecache_pages() counts the number of pages which are beyond the
3615 * high watermark within all zones.
3617 unsigned long nr_free_pagecache_pages(void)
3619 return nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE));
3622 static inline void show_node(struct zone *zone)
3624 if (IS_ENABLED(CONFIG_NUMA))
3625 printk("Node %d ", zone_to_nid(zone));
3628 void si_meminfo(struct sysinfo *val)
3630 val->totalram = totalram_pages;
3631 val->sharedram = global_page_state(NR_SHMEM);
3632 val->freeram = global_page_state(NR_FREE_PAGES);
3633 val->bufferram = nr_blockdev_pages();
3634 val->totalhigh = totalhigh_pages;
3635 val->freehigh = nr_free_highpages();
3636 val->mem_unit = PAGE_SIZE;
3639 EXPORT_SYMBOL(si_meminfo);
3642 void si_meminfo_node(struct sysinfo *val, int nid)
3644 int zone_type; /* needs to be signed */
3645 unsigned long managed_pages = 0;
3646 pg_data_t *pgdat = NODE_DATA(nid);
3648 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++)
3649 managed_pages += pgdat->node_zones[zone_type].managed_pages;
3650 val->totalram = managed_pages;
3651 val->sharedram = node_page_state(nid, NR_SHMEM);
3652 val->freeram = node_page_state(nid, NR_FREE_PAGES);
3653 #ifdef CONFIG_HIGHMEM
3654 val->totalhigh = pgdat->node_zones[ZONE_HIGHMEM].managed_pages;
3655 val->freehigh = zone_page_state(&pgdat->node_zones[ZONE_HIGHMEM],
3661 val->mem_unit = PAGE_SIZE;
3666 * Determine whether the node should be displayed or not, depending on whether
3667 * SHOW_MEM_FILTER_NODES was passed to show_free_areas().
3669 bool skip_free_areas_node(unsigned int flags, int nid)
3672 unsigned int cpuset_mems_cookie;
3674 if (!(flags & SHOW_MEM_FILTER_NODES))
3678 cpuset_mems_cookie = read_mems_allowed_begin();
3679 ret = !node_isset(nid, cpuset_current_mems_allowed);
3680 } while (read_mems_allowed_retry(cpuset_mems_cookie));
3685 #define K(x) ((x) << (PAGE_SHIFT-10))
3687 static void show_migration_types(unsigned char type)
3689 static const char types[MIGRATE_TYPES] = {
3690 [MIGRATE_UNMOVABLE] = 'U',
3691 [MIGRATE_MOVABLE] = 'M',
3692 [MIGRATE_RECLAIMABLE] = 'E',
3693 [MIGRATE_HIGHATOMIC] = 'H',
3695 [MIGRATE_CMA] = 'C',
3697 #ifdef CONFIG_MEMORY_ISOLATION
3698 [MIGRATE_ISOLATE] = 'I',
3701 char tmp[MIGRATE_TYPES + 1];
3705 for (i = 0; i < MIGRATE_TYPES; i++) {
3706 if (type & (1 << i))
3711 printk("(%s) ", tmp);
3715 * Show free area list (used inside shift_scroll-lock stuff)
3716 * We also calculate the percentage fragmentation. We do this by counting the
3717 * memory on each free list with the exception of the first item on the list.
3720 * SHOW_MEM_FILTER_NODES: suppress nodes that are not allowed by current's
3723 void show_free_areas(unsigned int filter)
3725 unsigned long free_pcp = 0;
3729 for_each_populated_zone(zone) {
3730 if (skip_free_areas_node(filter, zone_to_nid(zone)))
3733 for_each_online_cpu(cpu)
3734 free_pcp += per_cpu_ptr(zone->pageset, cpu)->pcp.count;
3737 printk("active_anon:%lu inactive_anon:%lu isolated_anon:%lu\n"
3738 " active_file:%lu inactive_file:%lu isolated_file:%lu\n"
3739 " unevictable:%lu dirty:%lu writeback:%lu unstable:%lu\n"
3740 " slab_reclaimable:%lu slab_unreclaimable:%lu\n"
3741 " mapped:%lu shmem:%lu pagetables:%lu bounce:%lu\n"
3742 " free:%lu free_pcp:%lu free_cma:%lu\n",
3743 global_page_state(NR_ACTIVE_ANON),
3744 global_page_state(NR_INACTIVE_ANON),
3745 global_page_state(NR_ISOLATED_ANON),
3746 global_page_state(NR_ACTIVE_FILE),
3747 global_page_state(NR_INACTIVE_FILE),
3748 global_page_state(NR_ISOLATED_FILE),
3749 global_page_state(NR_UNEVICTABLE),
3750 global_page_state(NR_FILE_DIRTY),
3751 global_page_state(NR_WRITEBACK),
3752 global_page_state(NR_UNSTABLE_NFS),
3753 global_page_state(NR_SLAB_RECLAIMABLE),
3754 global_page_state(NR_SLAB_UNRECLAIMABLE),
3755 global_page_state(NR_FILE_MAPPED),
3756 global_page_state(NR_SHMEM),
3757 global_page_state(NR_PAGETABLE),
3758 global_page_state(NR_BOUNCE),
3759 global_page_state(NR_FREE_PAGES),
3761 global_page_state(NR_FREE_CMA_PAGES));
3763 for_each_populated_zone(zone) {
3766 if (skip_free_areas_node(filter, zone_to_nid(zone)))
3770 for_each_online_cpu(cpu)
3771 free_pcp += per_cpu_ptr(zone->pageset, cpu)->pcp.count;
3779 " active_anon:%lukB"
3780 " inactive_anon:%lukB"
3781 " active_file:%lukB"
3782 " inactive_file:%lukB"
3783 " unevictable:%lukB"
3784 " isolated(anon):%lukB"
3785 " isolated(file):%lukB"
3793 " slab_reclaimable:%lukB"
3794 " slab_unreclaimable:%lukB"
3795 " kernel_stack:%lukB"
3802 " writeback_tmp:%lukB"
3803 " pages_scanned:%lu"
3804 " all_unreclaimable? %s"
3807 K(zone_page_state(zone, NR_FREE_PAGES)),
3808 K(min_wmark_pages(zone)),
3809 K(low_wmark_pages(zone)),
3810 K(high_wmark_pages(zone)),
3811 K(zone_page_state(zone, NR_ACTIVE_ANON)),
3812 K(zone_page_state(zone, NR_INACTIVE_ANON)),
3813 K(zone_page_state(zone, NR_ACTIVE_FILE)),
3814 K(zone_page_state(zone, NR_INACTIVE_FILE)),
3815 K(zone_page_state(zone, NR_UNEVICTABLE)),
3816 K(zone_page_state(zone, NR_ISOLATED_ANON)),
3817 K(zone_page_state(zone, NR_ISOLATED_FILE)),
3818 K(zone->present_pages),
3819 K(zone->managed_pages),
3820 K(zone_page_state(zone, NR_MLOCK)),
3821 K(zone_page_state(zone, NR_FILE_DIRTY)),
3822 K(zone_page_state(zone, NR_WRITEBACK)),
3823 K(zone_page_state(zone, NR_FILE_MAPPED)),
3824 K(zone_page_state(zone, NR_SHMEM)),
3825 K(zone_page_state(zone, NR_SLAB_RECLAIMABLE)),
3826 K(zone_page_state(zone, NR_SLAB_UNRECLAIMABLE)),
3827 zone_page_state(zone, NR_KERNEL_STACK) *
3829 K(zone_page_state(zone, NR_PAGETABLE)),
3830 K(zone_page_state(zone, NR_UNSTABLE_NFS)),
3831 K(zone_page_state(zone, NR_BOUNCE)),
3833 K(this_cpu_read(zone->pageset->pcp.count)),
3834 K(zone_page_state(zone, NR_FREE_CMA_PAGES)),
3835 K(zone_page_state(zone, NR_WRITEBACK_TEMP)),
3836 K(zone_page_state(zone, NR_PAGES_SCANNED)),
3837 (!zone_reclaimable(zone) ? "yes" : "no")
3839 printk("lowmem_reserve[]:");
3840 for (i = 0; i < MAX_NR_ZONES; i++)
3841 printk(" %ld", zone->lowmem_reserve[i]);
3845 for_each_populated_zone(zone) {
3847 unsigned long nr[MAX_ORDER], flags, total = 0;
3848 unsigned char types[MAX_ORDER];
3850 if (skip_free_areas_node(filter, zone_to_nid(zone)))
3853 printk("%s: ", zone->name);
3855 spin_lock_irqsave(&zone->lock, flags);
3856 for (order = 0; order < MAX_ORDER; order++) {
3857 struct free_area *area = &zone->free_area[order];
3860 nr[order] = area->nr_free;
3861 total += nr[order] << order;
3864 for (type = 0; type < MIGRATE_TYPES; type++) {
3865 if (!list_empty(&area->free_list[type]))
3866 types[order] |= 1 << type;
3869 spin_unlock_irqrestore(&zone->lock, flags);
3870 for (order = 0; order < MAX_ORDER; order++) {
3871 printk("%lu*%lukB ", nr[order], K(1UL) << order);
3873 show_migration_types(types[order]);
3875 printk("= %lukB\n", K(total));
3878 hugetlb_show_meminfo();
3880 printk("%ld total pagecache pages\n", global_page_state(NR_FILE_PAGES));
3882 show_swap_cache_info();
3885 static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref)
3887 zoneref->zone = zone;
3888 zoneref->zone_idx = zone_idx(zone);
3892 * Builds allocation fallback zone lists.
3894 * Add all populated zones of a node to the zonelist.
3896 static int build_zonelists_node(pg_data_t *pgdat, struct zonelist *zonelist,
3900 enum zone_type zone_type = MAX_NR_ZONES;
3904 zone = pgdat->node_zones + zone_type;
3905 if (populated_zone(zone)) {
3906 zoneref_set_zone(zone,
3907 &zonelist->_zonerefs[nr_zones++]);
3908 check_highest_zone(zone_type);
3910 } while (zone_type);
3918 * 0 = automatic detection of better ordering.
3919 * 1 = order by ([node] distance, -zonetype)
3920 * 2 = order by (-zonetype, [node] distance)
3922 * If not NUMA, ZONELIST_ORDER_ZONE and ZONELIST_ORDER_NODE will create
3923 * the same zonelist. So only NUMA can configure this param.
3925 #define ZONELIST_ORDER_DEFAULT 0
3926 #define ZONELIST_ORDER_NODE 1
3927 #define ZONELIST_ORDER_ZONE 2
3929 /* zonelist order in the kernel.
3930 * set_zonelist_order() will set this to NODE or ZONE.
3932 static int current_zonelist_order = ZONELIST_ORDER_DEFAULT;
3933 static char zonelist_order_name[3][8] = {"Default", "Node", "Zone"};
3937 /* The value user specified ....changed by config */
3938 static int user_zonelist_order = ZONELIST_ORDER_DEFAULT;
3939 /* string for sysctl */
3940 #define NUMA_ZONELIST_ORDER_LEN 16
3941 char numa_zonelist_order[16] = "default";
3944 * interface for configure zonelist ordering.
3945 * command line option "numa_zonelist_order"
3946 * = "[dD]efault - default, automatic configuration.
3947 * = "[nN]ode - order by node locality, then by zone within node
3948 * = "[zZ]one - order by zone, then by locality within zone
3951 static int __parse_numa_zonelist_order(char *s)
3953 if (*s == 'd' || *s == 'D') {
3954 user_zonelist_order = ZONELIST_ORDER_DEFAULT;
3955 } else if (*s == 'n' || *s == 'N') {
3956 user_zonelist_order = ZONELIST_ORDER_NODE;
3957 } else if (*s == 'z' || *s == 'Z') {
3958 user_zonelist_order = ZONELIST_ORDER_ZONE;
3961 "Ignoring invalid numa_zonelist_order value: "
3968 static __init int setup_numa_zonelist_order(char *s)
3975 ret = __parse_numa_zonelist_order(s);
3977 strlcpy(numa_zonelist_order, s, NUMA_ZONELIST_ORDER_LEN);
3981 early_param("numa_zonelist_order", setup_numa_zonelist_order);
3984 * sysctl handler for numa_zonelist_order
3986 int numa_zonelist_order_handler(struct ctl_table *table, int write,
3987 void __user *buffer, size_t *length,
3990 char saved_string[NUMA_ZONELIST_ORDER_LEN];
3992 static DEFINE_MUTEX(zl_order_mutex);
3994 mutex_lock(&zl_order_mutex);
3996 if (strlen((char *)table->data) >= NUMA_ZONELIST_ORDER_LEN) {
4000 strcpy(saved_string, (char *)table->data);
4002 ret = proc_dostring(table, write, buffer, length, ppos);
4006 int oldval = user_zonelist_order;
4008 ret = __parse_numa_zonelist_order((char *)table->data);
4011 * bogus value. restore saved string
4013 strncpy((char *)table->data, saved_string,
4014 NUMA_ZONELIST_ORDER_LEN);
4015 user_zonelist_order = oldval;
4016 } else if (oldval != user_zonelist_order) {
4017 mutex_lock(&zonelists_mutex);
4018 build_all_zonelists(NULL, NULL);
4019 mutex_unlock(&zonelists_mutex);
4023 mutex_unlock(&zl_order_mutex);
4028 #define MAX_NODE_LOAD (nr_online_nodes)
4029 static int node_load[MAX_NUMNODES];
4032 * find_next_best_node - find the next node that should appear in a given node's fallback list
4033 * @node: node whose fallback list we're appending
4034 * @used_node_mask: nodemask_t of already used nodes
4036 * We use a number of factors to determine which is the next node that should
4037 * appear on a given node's fallback list. The node should not have appeared
4038 * already in @node's fallback list, and it should be the next closest node
4039 * according to the distance array (which contains arbitrary distance values
4040 * from each node to each node in the system), and should also prefer nodes
4041 * with no CPUs, since presumably they'll have very little allocation pressure
4042 * on them otherwise.
4043 * It returns -1 if no node is found.
4045 static int find_next_best_node(int node, nodemask_t *used_node_mask)
4048 int min_val = INT_MAX;
4049 int best_node = NUMA_NO_NODE;
4050 const struct cpumask *tmp = cpumask_of_node(0);
4052 /* Use the local node if we haven't already */
4053 if (!node_isset(node, *used_node_mask)) {
4054 node_set(node, *used_node_mask);
4058 for_each_node_state(n, N_MEMORY) {
4060 /* Don't want a node to appear more than once */
4061 if (node_isset(n, *used_node_mask))
4064 /* Use the distance array to find the distance */
4065 val = node_distance(node, n);
4067 /* Penalize nodes under us ("prefer the next node") */
4070 /* Give preference to headless and unused nodes */
4071 tmp = cpumask_of_node(n);
4072 if (!cpumask_empty(tmp))
4073 val += PENALTY_FOR_NODE_WITH_CPUS;
4075 /* Slight preference for less loaded node */
4076 val *= (MAX_NODE_LOAD*MAX_NUMNODES);
4077 val += node_load[n];
4079 if (val < min_val) {
4086 node_set(best_node, *used_node_mask);
4093 * Build zonelists ordered by node and zones within node.
4094 * This results in maximum locality--normal zone overflows into local
4095 * DMA zone, if any--but risks exhausting DMA zone.
4097 static void build_zonelists_in_node_order(pg_data_t *pgdat, int node)
4100 struct zonelist *zonelist;
4102 zonelist = &pgdat->node_zonelists[0];
4103 for (j = 0; zonelist->_zonerefs[j].zone != NULL; j++)
4105 j = build_zonelists_node(NODE_DATA(node), zonelist, j);
4106 zonelist->_zonerefs[j].zone = NULL;
4107 zonelist->_zonerefs[j].zone_idx = 0;
4111 * Build gfp_thisnode zonelists
4113 static void build_thisnode_zonelists(pg_data_t *pgdat)
4116 struct zonelist *zonelist;
4118 zonelist = &pgdat->node_zonelists[1];
4119 j = build_zonelists_node(pgdat, zonelist, 0);
4120 zonelist->_zonerefs[j].zone = NULL;
4121 zonelist->_zonerefs[j].zone_idx = 0;
4125 * Build zonelists ordered by zone and nodes within zones.
4126 * This results in conserving DMA zone[s] until all Normal memory is
4127 * exhausted, but results in overflowing to remote node while memory
4128 * may still exist in local DMA zone.
4130 static int node_order[MAX_NUMNODES];
4132 static void build_zonelists_in_zone_order(pg_data_t *pgdat, int nr_nodes)
4135 int zone_type; /* needs to be signed */
4137 struct zonelist *zonelist;
4139 zonelist = &pgdat->node_zonelists[0];
4141 for (zone_type = MAX_NR_ZONES - 1; zone_type >= 0; zone_type--) {
4142 for (j = 0; j < nr_nodes; j++) {
4143 node = node_order[j];
4144 z = &NODE_DATA(node)->node_zones[zone_type];
4145 if (populated_zone(z)) {
4147 &zonelist->_zonerefs[pos++]);
4148 check_highest_zone(zone_type);
4152 zonelist->_zonerefs[pos].zone = NULL;
4153 zonelist->_zonerefs[pos].zone_idx = 0;
4156 #if defined(CONFIG_64BIT)
4158 * Devices that require DMA32/DMA are relatively rare and do not justify a
4159 * penalty to every machine in case the specialised case applies. Default
4160 * to Node-ordering on 64-bit NUMA machines
4162 static int default_zonelist_order(void)
4164 return ZONELIST_ORDER_NODE;
4168 * On 32-bit, the Normal zone needs to be preserved for allocations accessible
4169 * by the kernel. If processes running on node 0 deplete the low memory zone
4170 * then reclaim will occur more frequency increasing stalls and potentially
4171 * be easier to OOM if a large percentage of the zone is under writeback or
4172 * dirty. The problem is significantly worse if CONFIG_HIGHPTE is not set.
4173 * Hence, default to zone ordering on 32-bit.
4175 static int default_zonelist_order(void)
4177 return ZONELIST_ORDER_ZONE;
4179 #endif /* CONFIG_64BIT */
4181 static void set_zonelist_order(void)
4183 if (user_zonelist_order == ZONELIST_ORDER_DEFAULT)
4184 current_zonelist_order = default_zonelist_order();
4186 current_zonelist_order = user_zonelist_order;
4189 static void build_zonelists(pg_data_t *pgdat)
4193 nodemask_t used_mask;
4194 int local_node, prev_node;
4195 struct zonelist *zonelist;
4196 unsigned int order = current_zonelist_order;
4198 /* initialize zonelists */
4199 for (i = 0; i < MAX_ZONELISTS; i++) {
4200 zonelist = pgdat->node_zonelists + i;
4201 zonelist->_zonerefs[0].zone = NULL;
4202 zonelist->_zonerefs[0].zone_idx = 0;
4205 /* NUMA-aware ordering of nodes */
4206 local_node = pgdat->node_id;
4207 load = nr_online_nodes;
4208 prev_node = local_node;
4209 nodes_clear(used_mask);
4211 memset(node_order, 0, sizeof(node_order));
4214 while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
4216 * We don't want to pressure a particular node.
4217 * So adding penalty to the first node in same
4218 * distance group to make it round-robin.
4220 if (node_distance(local_node, node) !=
4221 node_distance(local_node, prev_node))
4222 node_load[node] = load;
4226 if (order == ZONELIST_ORDER_NODE)
4227 build_zonelists_in_node_order(pgdat, node);
4229 node_order[j++] = node; /* remember order */
4232 if (order == ZONELIST_ORDER_ZONE) {
4233 /* calculate node order -- i.e., DMA last! */
4234 build_zonelists_in_zone_order(pgdat, j);
4237 build_thisnode_zonelists(pgdat);
4240 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
4242 * Return node id of node used for "local" allocations.
4243 * I.e., first node id of first zone in arg node's generic zonelist.
4244 * Used for initializing percpu 'numa_mem', which is used primarily
4245 * for kernel allocations, so use GFP_KERNEL flags to locate zonelist.
4247 int local_memory_node(int node)
4251 (void)first_zones_zonelist(node_zonelist(node, GFP_KERNEL),
4252 gfp_zone(GFP_KERNEL),
4259 #else /* CONFIG_NUMA */
4261 static void set_zonelist_order(void)
4263 current_zonelist_order = ZONELIST_ORDER_ZONE;
4266 static void build_zonelists(pg_data_t *pgdat)
4268 int node, local_node;
4270 struct zonelist *zonelist;
4272 local_node = pgdat->node_id;
4274 zonelist = &pgdat->node_zonelists[0];
4275 j = build_zonelists_node(pgdat, zonelist, 0);
4278 * Now we build the zonelist so that it contains the zones
4279 * of all the other nodes.
4280 * We don't want to pressure a particular node, so when
4281 * building the zones for node N, we make sure that the
4282 * zones coming right after the local ones are those from
4283 * node N+1 (modulo N)
4285 for (node = local_node + 1; node < MAX_NUMNODES; node++) {
4286 if (!node_online(node))
4288 j = build_zonelists_node(NODE_DATA(node), zonelist, j);
4290 for (node = 0; node < local_node; node++) {
4291 if (!node_online(node))
4293 j = build_zonelists_node(NODE_DATA(node), zonelist, j);
4296 zonelist->_zonerefs[j].zone = NULL;
4297 zonelist->_zonerefs[j].zone_idx = 0;
4300 #endif /* CONFIG_NUMA */
4303 * Boot pageset table. One per cpu which is going to be used for all
4304 * zones and all nodes. The parameters will be set in such a way
4305 * that an item put on a list will immediately be handed over to
4306 * the buddy list. This is safe since pageset manipulation is done
4307 * with interrupts disabled.
4309 * The boot_pagesets must be kept even after bootup is complete for
4310 * unused processors and/or zones. They do play a role for bootstrapping
4311 * hotplugged processors.
4313 * zoneinfo_show() and maybe other functions do
4314 * not check if the processor is online before following the pageset pointer.
4315 * Other parts of the kernel may not check if the zone is available.
4317 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch);
4318 static DEFINE_PER_CPU(struct per_cpu_pageset, boot_pageset);
4319 static void setup_zone_pageset(struct zone *zone);
4322 * Global mutex to protect against size modification of zonelists
4323 * as well as to serialize pageset setup for the new populated zone.
4325 DEFINE_MUTEX(zonelists_mutex);
4327 /* return values int ....just for stop_machine() */
4328 static int __build_all_zonelists(void *data)
4332 pg_data_t *self = data;
4335 memset(node_load, 0, sizeof(node_load));
4338 if (self && !node_online(self->node_id)) {
4339 build_zonelists(self);
4342 for_each_online_node(nid) {
4343 pg_data_t *pgdat = NODE_DATA(nid);
4345 build_zonelists(pgdat);
4349 * Initialize the boot_pagesets that are going to be used
4350 * for bootstrapping processors. The real pagesets for
4351 * each zone will be allocated later when the per cpu
4352 * allocator is available.
4354 * boot_pagesets are used also for bootstrapping offline
4355 * cpus if the system is already booted because the pagesets
4356 * are needed to initialize allocators on a specific cpu too.
4357 * F.e. the percpu allocator needs the page allocator which
4358 * needs the percpu allocator in order to allocate its pagesets
4359 * (a chicken-egg dilemma).
4361 for_each_possible_cpu(cpu) {
4362 setup_pageset(&per_cpu(boot_pageset, cpu), 0);
4364 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
4366 * We now know the "local memory node" for each node--
4367 * i.e., the node of the first zone in the generic zonelist.
4368 * Set up numa_mem percpu variable for on-line cpus. During
4369 * boot, only the boot cpu should be on-line; we'll init the
4370 * secondary cpus' numa_mem as they come on-line. During
4371 * node/memory hotplug, we'll fixup all on-line cpus.
4373 if (cpu_online(cpu))
4374 set_cpu_numa_mem(cpu, local_memory_node(cpu_to_node(cpu)));
4381 static noinline void __init
4382 build_all_zonelists_init(void)
4384 __build_all_zonelists(NULL);
4385 mminit_verify_zonelist();
4386 cpuset_init_current_mems_allowed();
4390 * Called with zonelists_mutex held always
4391 * unless system_state == SYSTEM_BOOTING.
4393 * __ref due to (1) call of __meminit annotated setup_zone_pageset
4394 * [we're only called with non-NULL zone through __meminit paths] and
4395 * (2) call of __init annotated helper build_all_zonelists_init
4396 * [protected by SYSTEM_BOOTING].
4398 void __ref build_all_zonelists(pg_data_t *pgdat, struct zone *zone)
4400 set_zonelist_order();
4402 if (system_state == SYSTEM_BOOTING) {
4403 build_all_zonelists_init();
4405 #ifdef CONFIG_MEMORY_HOTPLUG
4407 setup_zone_pageset(zone);
4409 /* we have to stop all cpus to guarantee there is no user
4411 stop_machine(__build_all_zonelists, pgdat, NULL);
4412 /* cpuset refresh routine should be here */
4414 vm_total_pages = nr_free_pagecache_pages();
4416 * Disable grouping by mobility if the number of pages in the
4417 * system is too low to allow the mechanism to work. It would be
4418 * more accurate, but expensive to check per-zone. This check is
4419 * made on memory-hotadd so a system can start with mobility
4420 * disabled and enable it later
4422 if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES))
4423 page_group_by_mobility_disabled = 1;
4425 page_group_by_mobility_disabled = 0;
4427 pr_info("Built %i zonelists in %s order, mobility grouping %s. "
4428 "Total pages: %ld\n",
4430 zonelist_order_name[current_zonelist_order],
4431 page_group_by_mobility_disabled ? "off" : "on",
4434 pr_info("Policy zone: %s\n", zone_names[policy_zone]);
4439 * Helper functions to size the waitqueue hash table.
4440 * Essentially these want to choose hash table sizes sufficiently
4441 * large so that collisions trying to wait on pages are rare.
4442 * But in fact, the number of active page waitqueues on typical
4443 * systems is ridiculously low, less than 200. So this is even
4444 * conservative, even though it seems large.
4446 * The constant PAGES_PER_WAITQUEUE specifies the ratio of pages to
4447 * waitqueues, i.e. the size of the waitq table given the number of pages.
4449 #define PAGES_PER_WAITQUEUE 256
4451 #ifndef CONFIG_MEMORY_HOTPLUG
4452 static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
4454 unsigned long size = 1;
4456 pages /= PAGES_PER_WAITQUEUE;
4458 while (size < pages)
4462 * Once we have dozens or even hundreds of threads sleeping
4463 * on IO we've got bigger problems than wait queue collision.
4464 * Limit the size of the wait table to a reasonable size.
4466 size = min(size, 4096UL);
4468 return max(size, 4UL);
4472 * A zone's size might be changed by hot-add, so it is not possible to determine
4473 * a suitable size for its wait_table. So we use the maximum size now.
4475 * The max wait table size = 4096 x sizeof(wait_queue_head_t). ie:
4477 * i386 (preemption config) : 4096 x 16 = 64Kbyte.
4478 * ia64, x86-64 (no preemption): 4096 x 20 = 80Kbyte.
4479 * ia64, x86-64 (preemption) : 4096 x 24 = 96Kbyte.
4481 * The maximum entries are prepared when a zone's memory is (512K + 256) pages
4482 * or more by the traditional way. (See above). It equals:
4484 * i386, x86-64, powerpc(4K page size) : = ( 2G + 1M)byte.
4485 * ia64(16K page size) : = ( 8G + 4M)byte.
4486 * powerpc (64K page size) : = (32G +16M)byte.
4488 static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
4495 * This is an integer logarithm so that shifts can be used later
4496 * to extract the more random high bits from the multiplicative
4497 * hash function before the remainder is taken.
4499 static inline unsigned long wait_table_bits(unsigned long size)
4505 * Initially all pages are reserved - free ones are freed
4506 * up by free_all_bootmem() once the early boot process is
4507 * done. Non-atomic initialization, single-pass.
4509 void __meminit memmap_init_zone(unsigned long size, int nid, unsigned long zone,
4510 unsigned long start_pfn, enum memmap_context context)
4512 pg_data_t *pgdat = NODE_DATA(nid);
4513 unsigned long end_pfn = start_pfn + size;
4516 unsigned long nr_initialised = 0;
4518 if (highest_memmap_pfn < end_pfn - 1)
4519 highest_memmap_pfn = end_pfn - 1;
4521 z = &pgdat->node_zones[zone];
4522 for (pfn = start_pfn; pfn < end_pfn; pfn++) {
4524 * There can be holes in boot-time mem_map[]s
4525 * handed to this function. They do not
4526 * exist on hotplugged memory.
4528 if (context == MEMMAP_EARLY) {
4529 if (!early_pfn_valid(pfn))
4531 if (!early_pfn_in_nid(pfn, nid))
4533 if (!update_defer_init(pgdat, pfn, end_pfn,
4539 * Mark the block movable so that blocks are reserved for
4540 * movable at startup. This will force kernel allocations
4541 * to reserve their blocks rather than leaking throughout
4542 * the address space during boot when many long-lived
4543 * kernel allocations are made.
4545 * bitmap is created for zone's valid pfn range. but memmap
4546 * can be created for invalid pages (for alignment)
4547 * check here not to call set_pageblock_migratetype() against
4550 if (!(pfn & (pageblock_nr_pages - 1))) {
4551 struct page *page = pfn_to_page(pfn);
4553 __init_single_page(page, pfn, zone, nid);
4554 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
4556 __init_single_pfn(pfn, zone, nid);
4561 static void __meminit zone_init_free_lists(struct zone *zone)
4563 unsigned int order, t;
4564 for_each_migratetype_order(order, t) {
4565 INIT_LIST_HEAD(&zone->free_area[order].free_list[t]);
4566 zone->free_area[order].nr_free = 0;
4570 #ifndef __HAVE_ARCH_MEMMAP_INIT
4571 #define memmap_init(size, nid, zone, start_pfn) \
4572 memmap_init_zone((size), (nid), (zone), (start_pfn), MEMMAP_EARLY)
4575 static int zone_batchsize(struct zone *zone)
4581 * The per-cpu-pages pools are set to around 1000th of the
4582 * size of the zone. But no more than 1/2 of a meg.
4584 * OK, so we don't know how big the cache is. So guess.
4586 batch = zone->managed_pages / 1024;
4587 if (batch * PAGE_SIZE > 512 * 1024)
4588 batch = (512 * 1024) / PAGE_SIZE;
4589 batch /= 4; /* We effectively *= 4 below */
4594 * Clamp the batch to a 2^n - 1 value. Having a power
4595 * of 2 value was found to be more likely to have
4596 * suboptimal cache aliasing properties in some cases.
4598 * For example if 2 tasks are alternately allocating
4599 * batches of pages, one task can end up with a lot
4600 * of pages of one half of the possible page colors
4601 * and the other with pages of the other colors.
4603 batch = rounddown_pow_of_two(batch + batch/2) - 1;
4608 /* The deferral and batching of frees should be suppressed under NOMMU
4611 * The problem is that NOMMU needs to be able to allocate large chunks
4612 * of contiguous memory as there's no hardware page translation to
4613 * assemble apparent contiguous memory from discontiguous pages.
4615 * Queueing large contiguous runs of pages for batching, however,
4616 * causes the pages to actually be freed in smaller chunks. As there
4617 * can be a significant delay between the individual batches being
4618 * recycled, this leads to the once large chunks of space being
4619 * fragmented and becoming unavailable for high-order allocations.
4626 * pcp->high and pcp->batch values are related and dependent on one another:
4627 * ->batch must never be higher then ->high.
4628 * The following function updates them in a safe manner without read side
4631 * Any new users of pcp->batch and pcp->high should ensure they can cope with
4632 * those fields changing asynchronously (acording the the above rule).
4634 * mutex_is_locked(&pcp_batch_high_lock) required when calling this function
4635 * outside of boot time (or some other assurance that no concurrent updaters
4638 static void pageset_update(struct per_cpu_pages *pcp, unsigned long high,
4639 unsigned long batch)
4641 /* start with a fail safe value for batch */
4645 /* Update high, then batch, in order */
4652 /* a companion to pageset_set_high() */
4653 static void pageset_set_batch(struct per_cpu_pageset *p, unsigned long batch)
4655 pageset_update(&p->pcp, 6 * batch, max(1UL, 1 * batch));
4658 static void pageset_init(struct per_cpu_pageset *p)
4660 struct per_cpu_pages *pcp;
4663 memset(p, 0, sizeof(*p));
4667 for (migratetype = 0; migratetype < MIGRATE_PCPTYPES; migratetype++)
4668 INIT_LIST_HEAD(&pcp->lists[migratetype]);
4671 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch)
4674 pageset_set_batch(p, batch);
4678 * pageset_set_high() sets the high water mark for hot per_cpu_pagelist
4679 * to the value high for the pageset p.
4681 static void pageset_set_high(struct per_cpu_pageset *p,
4684 unsigned long batch = max(1UL, high / 4);
4685 if ((high / 4) > (PAGE_SHIFT * 8))
4686 batch = PAGE_SHIFT * 8;
4688 pageset_update(&p->pcp, high, batch);
4691 static void pageset_set_high_and_batch(struct zone *zone,
4692 struct per_cpu_pageset *pcp)
4694 if (percpu_pagelist_fraction)
4695 pageset_set_high(pcp,
4696 (zone->managed_pages /
4697 percpu_pagelist_fraction));
4699 pageset_set_batch(pcp, zone_batchsize(zone));
4702 static void __meminit zone_pageset_init(struct zone *zone, int cpu)
4704 struct per_cpu_pageset *pcp = per_cpu_ptr(zone->pageset, cpu);
4707 pageset_set_high_and_batch(zone, pcp);
4710 static void __meminit setup_zone_pageset(struct zone *zone)
4713 zone->pageset = alloc_percpu(struct per_cpu_pageset);
4714 for_each_possible_cpu(cpu)
4715 zone_pageset_init(zone, cpu);
4719 * Allocate per cpu pagesets and initialize them.
4720 * Before this call only boot pagesets were available.
4722 void __init setup_per_cpu_pageset(void)
4726 for_each_populated_zone(zone)
4727 setup_zone_pageset(zone);
4730 static noinline __init_refok
4731 int zone_wait_table_init(struct zone *zone, unsigned long zone_size_pages)
4737 * The per-page waitqueue mechanism uses hashed waitqueues
4740 zone->wait_table_hash_nr_entries =
4741 wait_table_hash_nr_entries(zone_size_pages);
4742 zone->wait_table_bits =
4743 wait_table_bits(zone->wait_table_hash_nr_entries);
4744 alloc_size = zone->wait_table_hash_nr_entries
4745 * sizeof(wait_queue_head_t);
4747 if (!slab_is_available()) {
4748 zone->wait_table = (wait_queue_head_t *)
4749 memblock_virt_alloc_node_nopanic(
4750 alloc_size, zone->zone_pgdat->node_id);
4753 * This case means that a zone whose size was 0 gets new memory
4754 * via memory hot-add.
4755 * But it may be the case that a new node was hot-added. In
4756 * this case vmalloc() will not be able to use this new node's
4757 * memory - this wait_table must be initialized to use this new
4758 * node itself as well.
4759 * To use this new node's memory, further consideration will be
4762 zone->wait_table = vmalloc(alloc_size);
4764 if (!zone->wait_table)
4767 for (i = 0; i < zone->wait_table_hash_nr_entries; ++i)
4768 init_waitqueue_head(zone->wait_table + i);
4773 static __meminit void zone_pcp_init(struct zone *zone)
4776 * per cpu subsystem is not up at this point. The following code
4777 * relies on the ability of the linker to provide the
4778 * offset of a (static) per cpu variable into the per cpu area.
4780 zone->pageset = &boot_pageset;
4782 if (populated_zone(zone))
4783 printk(KERN_DEBUG " %s zone: %lu pages, LIFO batch:%u\n",
4784 zone->name, zone->present_pages,
4785 zone_batchsize(zone));
4788 int __meminit init_currently_empty_zone(struct zone *zone,
4789 unsigned long zone_start_pfn,
4792 struct pglist_data *pgdat = zone->zone_pgdat;
4794 ret = zone_wait_table_init(zone, size);
4797 pgdat->nr_zones = zone_idx(zone) + 1;
4799 zone->zone_start_pfn = zone_start_pfn;
4801 mminit_dprintk(MMINIT_TRACE, "memmap_init",
4802 "Initialising map node %d zone %lu pfns %lu -> %lu\n",
4804 (unsigned long)zone_idx(zone),
4805 zone_start_pfn, (zone_start_pfn + size));
4807 zone_init_free_lists(zone);
4812 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
4813 #ifndef CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID
4816 * Required by SPARSEMEM. Given a PFN, return what node the PFN is on.
4818 int __meminit __early_pfn_to_nid(unsigned long pfn,
4819 struct mminit_pfnnid_cache *state)
4821 unsigned long start_pfn, end_pfn;
4824 if (state->last_start <= pfn && pfn < state->last_end)
4825 return state->last_nid;
4827 nid = memblock_search_pfn_nid(pfn, &start_pfn, &end_pfn);
4829 state->last_start = start_pfn;
4830 state->last_end = end_pfn;
4831 state->last_nid = nid;
4836 #endif /* CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID */
4839 * free_bootmem_with_active_regions - Call memblock_free_early_nid for each active range
4840 * @nid: The node to free memory on. If MAX_NUMNODES, all nodes are freed.
4841 * @max_low_pfn: The highest PFN that will be passed to memblock_free_early_nid
4843 * If an architecture guarantees that all ranges registered contain no holes
4844 * and may be freed, this this function may be used instead of calling
4845 * memblock_free_early_nid() manually.
4847 void __init free_bootmem_with_active_regions(int nid, unsigned long max_low_pfn)
4849 unsigned long start_pfn, end_pfn;
4852 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, &this_nid) {
4853 start_pfn = min(start_pfn, max_low_pfn);
4854 end_pfn = min(end_pfn, max_low_pfn);
4856 if (start_pfn < end_pfn)
4857 memblock_free_early_nid(PFN_PHYS(start_pfn),
4858 (end_pfn - start_pfn) << PAGE_SHIFT,
4864 * sparse_memory_present_with_active_regions - Call memory_present for each active range
4865 * @nid: The node to call memory_present for. If MAX_NUMNODES, all nodes will be used.
4867 * If an architecture guarantees that all ranges registered contain no holes and may
4868 * be freed, this function may be used instead of calling memory_present() manually.
4870 void __init sparse_memory_present_with_active_regions(int nid)
4872 unsigned long start_pfn, end_pfn;
4875 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, &this_nid)
4876 memory_present(this_nid, start_pfn, end_pfn);
4880 * get_pfn_range_for_nid - Return the start and end page frames for a node
4881 * @nid: The nid to return the range for. If MAX_NUMNODES, the min and max PFN are returned.
4882 * @start_pfn: Passed by reference. On return, it will have the node start_pfn.
4883 * @end_pfn: Passed by reference. On return, it will have the node end_pfn.
4885 * It returns the start and end page frame of a node based on information
4886 * provided by memblock_set_node(). If called for a node
4887 * with no available memory, a warning is printed and the start and end
4890 void __meminit get_pfn_range_for_nid(unsigned int nid,
4891 unsigned long *start_pfn, unsigned long *end_pfn)
4893 unsigned long this_start_pfn, this_end_pfn;
4899 for_each_mem_pfn_range(i, nid, &this_start_pfn, &this_end_pfn, NULL) {
4900 *start_pfn = min(*start_pfn, this_start_pfn);
4901 *end_pfn = max(*end_pfn, this_end_pfn);
4904 if (*start_pfn == -1UL)
4909 * This finds a zone that can be used for ZONE_MOVABLE pages. The
4910 * assumption is made that zones within a node are ordered in monotonic
4911 * increasing memory addresses so that the "highest" populated zone is used
4913 static void __init find_usable_zone_for_movable(void)
4916 for (zone_index = MAX_NR_ZONES - 1; zone_index >= 0; zone_index--) {
4917 if (zone_index == ZONE_MOVABLE)
4920 if (arch_zone_highest_possible_pfn[zone_index] >
4921 arch_zone_lowest_possible_pfn[zone_index])
4925 VM_BUG_ON(zone_index == -1);
4926 movable_zone = zone_index;
4930 * The zone ranges provided by the architecture do not include ZONE_MOVABLE
4931 * because it is sized independent of architecture. Unlike the other zones,
4932 * the starting point for ZONE_MOVABLE is not fixed. It may be different
4933 * in each node depending on the size of each node and how evenly kernelcore
4934 * is distributed. This helper function adjusts the zone ranges
4935 * provided by the architecture for a given node by using the end of the
4936 * highest usable zone for ZONE_MOVABLE. This preserves the assumption that
4937 * zones within a node are in order of monotonic increases memory addresses
4939 static void __meminit adjust_zone_range_for_zone_movable(int nid,
4940 unsigned long zone_type,
4941 unsigned long node_start_pfn,
4942 unsigned long node_end_pfn,
4943 unsigned long *zone_start_pfn,
4944 unsigned long *zone_end_pfn)
4946 /* Only adjust if ZONE_MOVABLE is on this node */
4947 if (zone_movable_pfn[nid]) {
4948 /* Size ZONE_MOVABLE */
4949 if (zone_type == ZONE_MOVABLE) {
4950 *zone_start_pfn = zone_movable_pfn[nid];
4951 *zone_end_pfn = min(node_end_pfn,
4952 arch_zone_highest_possible_pfn[movable_zone]);
4954 /* Adjust for ZONE_MOVABLE starting within this range */
4955 } else if (*zone_start_pfn < zone_movable_pfn[nid] &&
4956 *zone_end_pfn > zone_movable_pfn[nid]) {
4957 *zone_end_pfn = zone_movable_pfn[nid];
4959 /* Check if this whole range is within ZONE_MOVABLE */
4960 } else if (*zone_start_pfn >= zone_movable_pfn[nid])
4961 *zone_start_pfn = *zone_end_pfn;
4966 * Return the number of pages a zone spans in a node, including holes
4967 * present_pages = zone_spanned_pages_in_node() - zone_absent_pages_in_node()
4969 static unsigned long __meminit zone_spanned_pages_in_node(int nid,
4970 unsigned long zone_type,
4971 unsigned long node_start_pfn,
4972 unsigned long node_end_pfn,
4973 unsigned long *ignored)
4975 unsigned long zone_start_pfn, zone_end_pfn;
4977 /* When hotadd a new node from cpu_up(), the node should be empty */
4978 if (!node_start_pfn && !node_end_pfn)
4981 /* Get the start and end of the zone */
4982 zone_start_pfn = arch_zone_lowest_possible_pfn[zone_type];
4983 zone_end_pfn = arch_zone_highest_possible_pfn[zone_type];
4984 adjust_zone_range_for_zone_movable(nid, zone_type,
4985 node_start_pfn, node_end_pfn,
4986 &zone_start_pfn, &zone_end_pfn);
4988 /* Check that this node has pages within the zone's required range */
4989 if (zone_end_pfn < node_start_pfn || zone_start_pfn > node_end_pfn)
4992 /* Move the zone boundaries inside the node if necessary */
4993 zone_end_pfn = min(zone_end_pfn, node_end_pfn);
4994 zone_start_pfn = max(zone_start_pfn, node_start_pfn);
4996 /* Return the spanned pages */
4997 return zone_end_pfn - zone_start_pfn;
5001 * Return the number of holes in a range on a node. If nid is MAX_NUMNODES,
5002 * then all holes in the requested range will be accounted for.
5004 unsigned long __meminit __absent_pages_in_range(int nid,
5005 unsigned long range_start_pfn,
5006 unsigned long range_end_pfn)
5008 unsigned long nr_absent = range_end_pfn - range_start_pfn;
5009 unsigned long start_pfn, end_pfn;
5012 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
5013 start_pfn = clamp(start_pfn, range_start_pfn, range_end_pfn);
5014 end_pfn = clamp(end_pfn, range_start_pfn, range_end_pfn);
5015 nr_absent -= end_pfn - start_pfn;
5021 * absent_pages_in_range - Return number of page frames in holes within a range
5022 * @start_pfn: The start PFN to start searching for holes
5023 * @end_pfn: The end PFN to stop searching for holes
5025 * It returns the number of pages frames in memory holes within a range.
5027 unsigned long __init absent_pages_in_range(unsigned long start_pfn,
5028 unsigned long end_pfn)
5030 return __absent_pages_in_range(MAX_NUMNODES, start_pfn, end_pfn);
5033 /* Return the number of page frames in holes in a zone on a node */
5034 static unsigned long __meminit zone_absent_pages_in_node(int nid,
5035 unsigned long zone_type,
5036 unsigned long node_start_pfn,
5037 unsigned long node_end_pfn,
5038 unsigned long *ignored)
5040 unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type];
5041 unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type];
5042 unsigned long zone_start_pfn, zone_end_pfn;
5044 /* When hotadd a new node from cpu_up(), the node should be empty */
5045 if (!node_start_pfn && !node_end_pfn)
5048 zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high);
5049 zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high);
5051 adjust_zone_range_for_zone_movable(nid, zone_type,
5052 node_start_pfn, node_end_pfn,
5053 &zone_start_pfn, &zone_end_pfn);
5054 return __absent_pages_in_range(nid, zone_start_pfn, zone_end_pfn);
5057 #else /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
5058 static inline unsigned long __meminit zone_spanned_pages_in_node(int nid,
5059 unsigned long zone_type,
5060 unsigned long node_start_pfn,
5061 unsigned long node_end_pfn,
5062 unsigned long *zones_size)
5064 return zones_size[zone_type];
5067 static inline unsigned long __meminit zone_absent_pages_in_node(int nid,
5068 unsigned long zone_type,
5069 unsigned long node_start_pfn,
5070 unsigned long node_end_pfn,
5071 unsigned long *zholes_size)
5076 return zholes_size[zone_type];
5079 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
5081 static void __meminit calculate_node_totalpages(struct pglist_data *pgdat,
5082 unsigned long node_start_pfn,
5083 unsigned long node_end_pfn,
5084 unsigned long *zones_size,
5085 unsigned long *zholes_size)
5087 unsigned long realtotalpages = 0, totalpages = 0;
5090 for (i = 0; i < MAX_NR_ZONES; i++) {
5091 struct zone *zone = pgdat->node_zones + i;
5092 unsigned long size, real_size;
5094 size = zone_spanned_pages_in_node(pgdat->node_id, i,
5098 real_size = size - zone_absent_pages_in_node(pgdat->node_id, i,
5099 node_start_pfn, node_end_pfn,
5101 zone->spanned_pages = size;
5102 zone->present_pages = real_size;
5105 realtotalpages += real_size;
5108 pgdat->node_spanned_pages = totalpages;
5109 pgdat->node_present_pages = realtotalpages;
5110 printk(KERN_DEBUG "On node %d totalpages: %lu\n", pgdat->node_id,
5114 #ifndef CONFIG_SPARSEMEM
5116 * Calculate the size of the zone->blockflags rounded to an unsigned long
5117 * Start by making sure zonesize is a multiple of pageblock_order by rounding
5118 * up. Then use 1 NR_PAGEBLOCK_BITS worth of bits per pageblock, finally
5119 * round what is now in bits to nearest long in bits, then return it in
5122 static unsigned long __init usemap_size(unsigned long zone_start_pfn, unsigned long zonesize)
5124 unsigned long usemapsize;
5126 zonesize += zone_start_pfn & (pageblock_nr_pages-1);
5127 usemapsize = roundup(zonesize, pageblock_nr_pages);
5128 usemapsize = usemapsize >> pageblock_order;
5129 usemapsize *= NR_PAGEBLOCK_BITS;
5130 usemapsize = roundup(usemapsize, 8 * sizeof(unsigned long));
5132 return usemapsize / 8;
5135 static void __init setup_usemap(struct pglist_data *pgdat,
5137 unsigned long zone_start_pfn,
5138 unsigned long zonesize)
5140 unsigned long usemapsize = usemap_size(zone_start_pfn, zonesize);
5141 zone->pageblock_flags = NULL;
5143 zone->pageblock_flags =
5144 memblock_virt_alloc_node_nopanic(usemapsize,
5148 static inline void setup_usemap(struct pglist_data *pgdat, struct zone *zone,
5149 unsigned long zone_start_pfn, unsigned long zonesize) {}
5150 #endif /* CONFIG_SPARSEMEM */
5152 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
5154 /* Initialise the number of pages represented by NR_PAGEBLOCK_BITS */
5155 void __paginginit set_pageblock_order(void)
5159 /* Check that pageblock_nr_pages has not already been setup */
5160 if (pageblock_order)
5163 if (HPAGE_SHIFT > PAGE_SHIFT)
5164 order = HUGETLB_PAGE_ORDER;
5166 order = MAX_ORDER - 1;
5169 * Assume the largest contiguous order of interest is a huge page.
5170 * This value may be variable depending on boot parameters on IA64 and
5173 pageblock_order = order;
5175 #else /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
5178 * When CONFIG_HUGETLB_PAGE_SIZE_VARIABLE is not set, set_pageblock_order()
5179 * is unused as pageblock_order is set at compile-time. See
5180 * include/linux/pageblock-flags.h for the values of pageblock_order based on
5183 void __paginginit set_pageblock_order(void)
5187 #endif /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
5189 static unsigned long __paginginit calc_memmap_size(unsigned long spanned_pages,
5190 unsigned long present_pages)
5192 unsigned long pages = spanned_pages;
5195 * Provide a more accurate estimation if there are holes within
5196 * the zone and SPARSEMEM is in use. If there are holes within the
5197 * zone, each populated memory region may cost us one or two extra
5198 * memmap pages due to alignment because memmap pages for each
5199 * populated regions may not naturally algined on page boundary.
5200 * So the (present_pages >> 4) heuristic is a tradeoff for that.
5202 if (spanned_pages > present_pages + (present_pages >> 4) &&
5203 IS_ENABLED(CONFIG_SPARSEMEM))
5204 pages = present_pages;
5206 return PAGE_ALIGN(pages * sizeof(struct page)) >> PAGE_SHIFT;
5210 * Set up the zone data structures:
5211 * - mark all pages reserved
5212 * - mark all memory queues empty
5213 * - clear the memory bitmaps
5215 * NOTE: pgdat should get zeroed by caller.
5217 static void __paginginit free_area_init_core(struct pglist_data *pgdat)
5220 int nid = pgdat->node_id;
5221 unsigned long zone_start_pfn = pgdat->node_start_pfn;
5224 pgdat_resize_init(pgdat);
5225 #ifdef CONFIG_NUMA_BALANCING
5226 spin_lock_init(&pgdat->numabalancing_migrate_lock);
5227 pgdat->numabalancing_migrate_nr_pages = 0;
5228 pgdat->numabalancing_migrate_next_window = jiffies;
5230 init_waitqueue_head(&pgdat->kswapd_wait);
5231 init_waitqueue_head(&pgdat->pfmemalloc_wait);
5232 pgdat_page_ext_init(pgdat);
5234 for (j = 0; j < MAX_NR_ZONES; j++) {
5235 struct zone *zone = pgdat->node_zones + j;
5236 unsigned long size, realsize, freesize, memmap_pages;
5238 size = zone->spanned_pages;
5239 realsize = freesize = zone->present_pages;
5242 * Adjust freesize so that it accounts for how much memory
5243 * is used by this zone for memmap. This affects the watermark
5244 * and per-cpu initialisations
5246 memmap_pages = calc_memmap_size(size, realsize);
5247 if (!is_highmem_idx(j)) {
5248 if (freesize >= memmap_pages) {
5249 freesize -= memmap_pages;
5252 " %s zone: %lu pages used for memmap\n",
5253 zone_names[j], memmap_pages);
5256 " %s zone: %lu pages exceeds freesize %lu\n",
5257 zone_names[j], memmap_pages, freesize);
5260 /* Account for reserved pages */
5261 if (j == 0 && freesize > dma_reserve) {
5262 freesize -= dma_reserve;
5263 printk(KERN_DEBUG " %s zone: %lu pages reserved\n",
5264 zone_names[0], dma_reserve);
5267 if (!is_highmem_idx(j))
5268 nr_kernel_pages += freesize;
5269 /* Charge for highmem memmap if there are enough kernel pages */
5270 else if (nr_kernel_pages > memmap_pages * 2)
5271 nr_kernel_pages -= memmap_pages;
5272 nr_all_pages += freesize;
5275 * Set an approximate value for lowmem here, it will be adjusted
5276 * when the bootmem allocator frees pages into the buddy system.
5277 * And all highmem pages will be managed by the buddy system.
5279 zone->managed_pages = is_highmem_idx(j) ? realsize : freesize;
5282 zone->min_unmapped_pages = (freesize*sysctl_min_unmapped_ratio)
5284 zone->min_slab_pages = (freesize * sysctl_min_slab_ratio) / 100;
5286 zone->name = zone_names[j];
5287 spin_lock_init(&zone->lock);
5288 spin_lock_init(&zone->lru_lock);
5289 zone_seqlock_init(zone);
5290 zone->zone_pgdat = pgdat;
5291 zone_pcp_init(zone);
5293 /* For bootup, initialized properly in watermark setup */
5294 mod_zone_page_state(zone, NR_ALLOC_BATCH, zone->managed_pages);
5296 lruvec_init(&zone->lruvec);
5300 set_pageblock_order();
5301 setup_usemap(pgdat, zone, zone_start_pfn, size);
5302 ret = init_currently_empty_zone(zone, zone_start_pfn, size);
5304 memmap_init(size, nid, j, zone_start_pfn);
5305 zone_start_pfn += size;
5309 static void __init_refok alloc_node_mem_map(struct pglist_data *pgdat)
5311 unsigned long __maybe_unused start = 0;
5312 unsigned long __maybe_unused offset = 0;
5314 /* Skip empty nodes */
5315 if (!pgdat->node_spanned_pages)
5318 #ifdef CONFIG_FLAT_NODE_MEM_MAP
5319 start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1);
5320 offset = pgdat->node_start_pfn - start;
5321 /* ia64 gets its own node_mem_map, before this, without bootmem */
5322 if (!pgdat->node_mem_map) {
5323 unsigned long size, end;
5327 * The zone's endpoints aren't required to be MAX_ORDER
5328 * aligned but the node_mem_map endpoints must be in order
5329 * for the buddy allocator to function correctly.
5331 end = pgdat_end_pfn(pgdat);
5332 end = ALIGN(end, MAX_ORDER_NR_PAGES);
5333 size = (end - start) * sizeof(struct page);
5334 map = alloc_remap(pgdat->node_id, size);
5336 map = memblock_virt_alloc_node_nopanic(size,
5338 pgdat->node_mem_map = map + offset;
5340 #ifndef CONFIG_NEED_MULTIPLE_NODES
5342 * With no DISCONTIG, the global mem_map is just set as node 0's
5344 if (pgdat == NODE_DATA(0)) {
5345 mem_map = NODE_DATA(0)->node_mem_map;
5346 #if defined(CONFIG_HAVE_MEMBLOCK_NODE_MAP) || defined(CONFIG_FLATMEM)
5347 if (page_to_pfn(mem_map) != pgdat->node_start_pfn)
5349 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
5352 #endif /* CONFIG_FLAT_NODE_MEM_MAP */
5355 void __paginginit free_area_init_node(int nid, unsigned long *zones_size,
5356 unsigned long node_start_pfn, unsigned long *zholes_size)
5358 pg_data_t *pgdat = NODE_DATA(nid);
5359 unsigned long start_pfn = 0;
5360 unsigned long end_pfn = 0;
5362 /* pg_data_t should be reset to zero when it's allocated */
5363 WARN_ON(pgdat->nr_zones || pgdat->classzone_idx);
5365 pgdat->node_id = nid;
5366 pgdat->node_start_pfn = node_start_pfn;
5367 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
5368 get_pfn_range_for_nid(nid, &start_pfn, &end_pfn);
5369 pr_info("Initmem setup node %d [mem %#018Lx-%#018Lx]\n", nid,
5370 (u64)start_pfn << PAGE_SHIFT,
5371 end_pfn ? ((u64)end_pfn << PAGE_SHIFT) - 1 : 0);
5373 calculate_node_totalpages(pgdat, start_pfn, end_pfn,
5374 zones_size, zholes_size);
5376 alloc_node_mem_map(pgdat);
5377 #ifdef CONFIG_FLAT_NODE_MEM_MAP
5378 printk(KERN_DEBUG "free_area_init_node: node %d, pgdat %08lx, node_mem_map %08lx\n",
5379 nid, (unsigned long)pgdat,
5380 (unsigned long)pgdat->node_mem_map);
5383 reset_deferred_meminit(pgdat);
5384 free_area_init_core(pgdat);
5387 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
5389 #if MAX_NUMNODES > 1
5391 * Figure out the number of possible node ids.
5393 void __init setup_nr_node_ids(void)
5395 unsigned int highest;
5397 highest = find_last_bit(node_possible_map.bits, MAX_NUMNODES);
5398 nr_node_ids = highest + 1;
5403 * node_map_pfn_alignment - determine the maximum internode alignment
5405 * This function should be called after node map is populated and sorted.
5406 * It calculates the maximum power of two alignment which can distinguish
5409 * For example, if all nodes are 1GiB and aligned to 1GiB, the return value
5410 * would indicate 1GiB alignment with (1 << (30 - PAGE_SHIFT)). If the
5411 * nodes are shifted by 256MiB, 256MiB. Note that if only the last node is
5412 * shifted, 1GiB is enough and this function will indicate so.
5414 * This is used to test whether pfn -> nid mapping of the chosen memory
5415 * model has fine enough granularity to avoid incorrect mapping for the
5416 * populated node map.
5418 * Returns the determined alignment in pfn's. 0 if there is no alignment
5419 * requirement (single node).
5421 unsigned long __init node_map_pfn_alignment(void)
5423 unsigned long accl_mask = 0, last_end = 0;
5424 unsigned long start, end, mask;
5428 for_each_mem_pfn_range(i, MAX_NUMNODES, &start, &end, &nid) {
5429 if (!start || last_nid < 0 || last_nid == nid) {
5436 * Start with a mask granular enough to pin-point to the
5437 * start pfn and tick off bits one-by-one until it becomes
5438 * too coarse to separate the current node from the last.
5440 mask = ~((1 << __ffs(start)) - 1);
5441 while (mask && last_end <= (start & (mask << 1)))
5444 /* accumulate all internode masks */
5448 /* convert mask to number of pages */
5449 return ~accl_mask + 1;
5452 /* Find the lowest pfn for a node */
5453 static unsigned long __init find_min_pfn_for_node(int nid)
5455 unsigned long min_pfn = ULONG_MAX;
5456 unsigned long start_pfn;
5459 for_each_mem_pfn_range(i, nid, &start_pfn, NULL, NULL)
5460 min_pfn = min(min_pfn, start_pfn);
5462 if (min_pfn == ULONG_MAX) {
5464 "Could not find start_pfn for node %d\n", nid);
5472 * find_min_pfn_with_active_regions - Find the minimum PFN registered
5474 * It returns the minimum PFN based on information provided via
5475 * memblock_set_node().
5477 unsigned long __init find_min_pfn_with_active_regions(void)
5479 return find_min_pfn_for_node(MAX_NUMNODES);
5483 * early_calculate_totalpages()
5484 * Sum pages in active regions for movable zone.
5485 * Populate N_MEMORY for calculating usable_nodes.
5487 static unsigned long __init early_calculate_totalpages(void)
5489 unsigned long totalpages = 0;
5490 unsigned long start_pfn, end_pfn;
5493 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
5494 unsigned long pages = end_pfn - start_pfn;
5496 totalpages += pages;
5498 node_set_state(nid, N_MEMORY);
5504 * Find the PFN the Movable zone begins in each node. Kernel memory
5505 * is spread evenly between nodes as long as the nodes have enough
5506 * memory. When they don't, some nodes will have more kernelcore than
5509 static void __init find_zone_movable_pfns_for_nodes(void)
5512 unsigned long usable_startpfn;
5513 unsigned long kernelcore_node, kernelcore_remaining;
5514 /* save the state before borrow the nodemask */
5515 nodemask_t saved_node_state = node_states[N_MEMORY];
5516 unsigned long totalpages = early_calculate_totalpages();
5517 int usable_nodes = nodes_weight(node_states[N_MEMORY]);
5518 struct memblock_region *r;
5520 /* Need to find movable_zone earlier when movable_node is specified. */
5521 find_usable_zone_for_movable();
5524 * If movable_node is specified, ignore kernelcore and movablecore
5527 if (movable_node_is_enabled()) {
5528 for_each_memblock(memory, r) {
5529 if (!memblock_is_hotpluggable(r))
5534 usable_startpfn = PFN_DOWN(r->base);
5535 zone_movable_pfn[nid] = zone_movable_pfn[nid] ?
5536 min(usable_startpfn, zone_movable_pfn[nid]) :
5544 * If movablecore=nn[KMG] was specified, calculate what size of
5545 * kernelcore that corresponds so that memory usable for
5546 * any allocation type is evenly spread. If both kernelcore
5547 * and movablecore are specified, then the value of kernelcore
5548 * will be used for required_kernelcore if it's greater than
5549 * what movablecore would have allowed.
5551 if (required_movablecore) {
5552 unsigned long corepages;
5555 * Round-up so that ZONE_MOVABLE is at least as large as what
5556 * was requested by the user
5558 required_movablecore =
5559 roundup(required_movablecore, MAX_ORDER_NR_PAGES);
5560 required_movablecore = min(totalpages, required_movablecore);
5561 corepages = totalpages - required_movablecore;
5563 required_kernelcore = max(required_kernelcore, corepages);
5567 * If kernelcore was not specified or kernelcore size is larger
5568 * than totalpages, there is no ZONE_MOVABLE.
5570 if (!required_kernelcore || required_kernelcore >= totalpages)
5573 /* usable_startpfn is the lowest possible pfn ZONE_MOVABLE can be at */
5574 usable_startpfn = arch_zone_lowest_possible_pfn[movable_zone];
5577 /* Spread kernelcore memory as evenly as possible throughout nodes */
5578 kernelcore_node = required_kernelcore / usable_nodes;
5579 for_each_node_state(nid, N_MEMORY) {
5580 unsigned long start_pfn, end_pfn;
5583 * Recalculate kernelcore_node if the division per node
5584 * now exceeds what is necessary to satisfy the requested
5585 * amount of memory for the kernel
5587 if (required_kernelcore < kernelcore_node)
5588 kernelcore_node = required_kernelcore / usable_nodes;
5591 * As the map is walked, we track how much memory is usable
5592 * by the kernel using kernelcore_remaining. When it is
5593 * 0, the rest of the node is usable by ZONE_MOVABLE
5595 kernelcore_remaining = kernelcore_node;
5597 /* Go through each range of PFNs within this node */
5598 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
5599 unsigned long size_pages;
5601 start_pfn = max(start_pfn, zone_movable_pfn[nid]);
5602 if (start_pfn >= end_pfn)
5605 /* Account for what is only usable for kernelcore */
5606 if (start_pfn < usable_startpfn) {
5607 unsigned long kernel_pages;
5608 kernel_pages = min(end_pfn, usable_startpfn)
5611 kernelcore_remaining -= min(kernel_pages,
5612 kernelcore_remaining);
5613 required_kernelcore -= min(kernel_pages,
5614 required_kernelcore);
5616 /* Continue if range is now fully accounted */
5617 if (end_pfn <= usable_startpfn) {
5620 * Push zone_movable_pfn to the end so
5621 * that if we have to rebalance
5622 * kernelcore across nodes, we will
5623 * not double account here
5625 zone_movable_pfn[nid] = end_pfn;
5628 start_pfn = usable_startpfn;
5632 * The usable PFN range for ZONE_MOVABLE is from
5633 * start_pfn->end_pfn. Calculate size_pages as the
5634 * number of pages used as kernelcore
5636 size_pages = end_pfn - start_pfn;
5637 if (size_pages > kernelcore_remaining)
5638 size_pages = kernelcore_remaining;
5639 zone_movable_pfn[nid] = start_pfn + size_pages;
5642 * Some kernelcore has been met, update counts and
5643 * break if the kernelcore for this node has been
5646 required_kernelcore -= min(required_kernelcore,
5648 kernelcore_remaining -= size_pages;
5649 if (!kernelcore_remaining)
5655 * If there is still required_kernelcore, we do another pass with one
5656 * less node in the count. This will push zone_movable_pfn[nid] further
5657 * along on the nodes that still have memory until kernelcore is
5661 if (usable_nodes && required_kernelcore > usable_nodes)
5665 /* Align start of ZONE_MOVABLE on all nids to MAX_ORDER_NR_PAGES */
5666 for (nid = 0; nid < MAX_NUMNODES; nid++)
5667 zone_movable_pfn[nid] =
5668 roundup(zone_movable_pfn[nid], MAX_ORDER_NR_PAGES);
5671 /* restore the node_state */
5672 node_states[N_MEMORY] = saved_node_state;
5675 /* Any regular or high memory on that node ? */
5676 static void check_for_memory(pg_data_t *pgdat, int nid)
5678 enum zone_type zone_type;
5680 if (N_MEMORY == N_NORMAL_MEMORY)
5683 for (zone_type = 0; zone_type <= ZONE_MOVABLE - 1; zone_type++) {
5684 struct zone *zone = &pgdat->node_zones[zone_type];
5685 if (populated_zone(zone)) {
5686 node_set_state(nid, N_HIGH_MEMORY);
5687 if (N_NORMAL_MEMORY != N_HIGH_MEMORY &&
5688 zone_type <= ZONE_NORMAL)
5689 node_set_state(nid, N_NORMAL_MEMORY);
5696 * free_area_init_nodes - Initialise all pg_data_t and zone data
5697 * @max_zone_pfn: an array of max PFNs for each zone
5699 * This will call free_area_init_node() for each active node in the system.
5700 * Using the page ranges provided by memblock_set_node(), the size of each
5701 * zone in each node and their holes is calculated. If the maximum PFN
5702 * between two adjacent zones match, it is assumed that the zone is empty.
5703 * For example, if arch_max_dma_pfn == arch_max_dma32_pfn, it is assumed
5704 * that arch_max_dma32_pfn has no pages. It is also assumed that a zone
5705 * starts where the previous one ended. For example, ZONE_DMA32 starts
5706 * at arch_max_dma_pfn.
5708 void __init free_area_init_nodes(unsigned long *max_zone_pfn)
5710 unsigned long start_pfn, end_pfn;
5713 /* Record where the zone boundaries are */
5714 memset(arch_zone_lowest_possible_pfn, 0,
5715 sizeof(arch_zone_lowest_possible_pfn));
5716 memset(arch_zone_highest_possible_pfn, 0,
5717 sizeof(arch_zone_highest_possible_pfn));
5719 start_pfn = find_min_pfn_with_active_regions();
5721 for (i = 0; i < MAX_NR_ZONES; i++) {
5722 if (i == ZONE_MOVABLE)
5725 end_pfn = max(max_zone_pfn[i], start_pfn);
5726 arch_zone_lowest_possible_pfn[i] = start_pfn;
5727 arch_zone_highest_possible_pfn[i] = end_pfn;
5729 start_pfn = end_pfn;
5731 arch_zone_lowest_possible_pfn[ZONE_MOVABLE] = 0;
5732 arch_zone_highest_possible_pfn[ZONE_MOVABLE] = 0;
5734 /* Find the PFNs that ZONE_MOVABLE begins at in each node */
5735 memset(zone_movable_pfn, 0, sizeof(zone_movable_pfn));
5736 find_zone_movable_pfns_for_nodes();
5738 /* Print out the zone ranges */
5739 pr_info("Zone ranges:\n");
5740 for (i = 0; i < MAX_NR_ZONES; i++) {
5741 if (i == ZONE_MOVABLE)
5743 pr_info(" %-8s ", zone_names[i]);
5744 if (arch_zone_lowest_possible_pfn[i] ==
5745 arch_zone_highest_possible_pfn[i])
5748 pr_cont("[mem %#018Lx-%#018Lx]\n",
5749 (u64)arch_zone_lowest_possible_pfn[i]
5751 ((u64)arch_zone_highest_possible_pfn[i]
5752 << PAGE_SHIFT) - 1);
5755 /* Print out the PFNs ZONE_MOVABLE begins at in each node */
5756 pr_info("Movable zone start for each node\n");
5757 for (i = 0; i < MAX_NUMNODES; i++) {
5758 if (zone_movable_pfn[i])
5759 pr_info(" Node %d: %#018Lx\n", i,
5760 (u64)zone_movable_pfn[i] << PAGE_SHIFT);
5763 /* Print out the early node map */
5764 pr_info("Early memory node ranges\n");
5765 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid)
5766 pr_info(" node %3d: [mem %#018Lx-%#018Lx]\n", nid,
5767 (u64)start_pfn << PAGE_SHIFT,
5768 ((u64)end_pfn << PAGE_SHIFT) - 1);
5770 /* Initialise every node */
5771 mminit_verify_pageflags_layout();
5772 setup_nr_node_ids();
5773 for_each_online_node(nid) {
5774 pg_data_t *pgdat = NODE_DATA(nid);
5775 free_area_init_node(nid, NULL,
5776 find_min_pfn_for_node(nid), NULL);
5778 /* Any memory on that node */
5779 if (pgdat->node_present_pages)
5780 node_set_state(nid, N_MEMORY);
5781 check_for_memory(pgdat, nid);
5785 static int __init cmdline_parse_core(char *p, unsigned long *core)
5787 unsigned long long coremem;
5791 coremem = memparse(p, &p);
5792 *core = coremem >> PAGE_SHIFT;
5794 /* Paranoid check that UL is enough for the coremem value */
5795 WARN_ON((coremem >> PAGE_SHIFT) > ULONG_MAX);
5801 * kernelcore=size sets the amount of memory for use for allocations that
5802 * cannot be reclaimed or migrated.
5804 static int __init cmdline_parse_kernelcore(char *p)
5806 return cmdline_parse_core(p, &required_kernelcore);
5810 * movablecore=size sets the amount of memory for use for allocations that
5811 * can be reclaimed or migrated.
5813 static int __init cmdline_parse_movablecore(char *p)
5815 return cmdline_parse_core(p, &required_movablecore);
5818 early_param("kernelcore", cmdline_parse_kernelcore);
5819 early_param("movablecore", cmdline_parse_movablecore);
5821 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
5823 void adjust_managed_page_count(struct page *page, long count)
5825 spin_lock(&managed_page_count_lock);
5826 page_zone(page)->managed_pages += count;
5827 totalram_pages += count;
5828 #ifdef CONFIG_HIGHMEM
5829 if (PageHighMem(page))
5830 totalhigh_pages += count;
5832 spin_unlock(&managed_page_count_lock);
5834 EXPORT_SYMBOL(adjust_managed_page_count);
5836 unsigned long free_reserved_area(void *start, void *end, int poison, char *s)
5839 unsigned long pages = 0;
5841 start = (void *)PAGE_ALIGN((unsigned long)start);
5842 end = (void *)((unsigned long)end & PAGE_MASK);
5843 for (pos = start; pos < end; pos += PAGE_SIZE, pages++) {
5844 if ((unsigned int)poison <= 0xFF)
5845 memset(pos, poison, PAGE_SIZE);
5846 free_reserved_page(virt_to_page(pos));
5850 pr_info("Freeing %s memory: %ldK\n",
5851 s, pages << (PAGE_SHIFT - 10));
5855 EXPORT_SYMBOL(free_reserved_area);
5857 #ifdef CONFIG_HIGHMEM
5858 void free_highmem_page(struct page *page)
5860 __free_reserved_page(page);
5862 page_zone(page)->managed_pages++;
5868 void __init mem_init_print_info(const char *str)
5870 unsigned long physpages, codesize, datasize, rosize, bss_size;
5871 unsigned long init_code_size, init_data_size;
5873 physpages = get_num_physpages();
5874 codesize = _etext - _stext;
5875 datasize = _edata - _sdata;
5876 rosize = __end_rodata - __start_rodata;
5877 bss_size = __bss_stop - __bss_start;
5878 init_data_size = __init_end - __init_begin;
5879 init_code_size = _einittext - _sinittext;
5882 * Detect special cases and adjust section sizes accordingly:
5883 * 1) .init.* may be embedded into .data sections
5884 * 2) .init.text.* may be out of [__init_begin, __init_end],
5885 * please refer to arch/tile/kernel/vmlinux.lds.S.
5886 * 3) .rodata.* may be embedded into .text or .data sections.
5888 #define adj_init_size(start, end, size, pos, adj) \
5890 if (start <= pos && pos < end && size > adj) \
5894 adj_init_size(__init_begin, __init_end, init_data_size,
5895 _sinittext, init_code_size);
5896 adj_init_size(_stext, _etext, codesize, _sinittext, init_code_size);
5897 adj_init_size(_sdata, _edata, datasize, __init_begin, init_data_size);
5898 adj_init_size(_stext, _etext, codesize, __start_rodata, rosize);
5899 adj_init_size(_sdata, _edata, datasize, __start_rodata, rosize);
5901 #undef adj_init_size
5903 pr_info("Memory: %luK/%luK available "
5904 "(%luK kernel code, %luK rwdata, %luK rodata, "
5905 "%luK init, %luK bss, %luK reserved, %luK cma-reserved"
5906 #ifdef CONFIG_HIGHMEM
5910 nr_free_pages() << (PAGE_SHIFT-10), physpages << (PAGE_SHIFT-10),
5911 codesize >> 10, datasize >> 10, rosize >> 10,
5912 (init_data_size + init_code_size) >> 10, bss_size >> 10,
5913 (physpages - totalram_pages - totalcma_pages) << (PAGE_SHIFT-10),
5914 totalcma_pages << (PAGE_SHIFT-10),
5915 #ifdef CONFIG_HIGHMEM
5916 totalhigh_pages << (PAGE_SHIFT-10),
5918 str ? ", " : "", str ? str : "");
5922 * set_dma_reserve - set the specified number of pages reserved in the first zone
5923 * @new_dma_reserve: The number of pages to mark reserved
5925 * The per-cpu batchsize and zone watermarks are determined by managed_pages.
5926 * In the DMA zone, a significant percentage may be consumed by kernel image
5927 * and other unfreeable allocations which can skew the watermarks badly. This
5928 * function may optionally be used to account for unfreeable pages in the
5929 * first zone (e.g., ZONE_DMA). The effect will be lower watermarks and
5930 * smaller per-cpu batchsize.
5932 void __init set_dma_reserve(unsigned long new_dma_reserve)
5934 dma_reserve = new_dma_reserve;
5937 void __init free_area_init(unsigned long *zones_size)
5939 free_area_init_node(0, zones_size,
5940 __pa(PAGE_OFFSET) >> PAGE_SHIFT, NULL);
5943 static int page_alloc_cpu_notify(struct notifier_block *self,
5944 unsigned long action, void *hcpu)
5946 int cpu = (unsigned long)hcpu;
5948 if (action == CPU_DEAD || action == CPU_DEAD_FROZEN) {
5949 lru_add_drain_cpu(cpu);
5953 * Spill the event counters of the dead processor
5954 * into the current processors event counters.
5955 * This artificially elevates the count of the current
5958 vm_events_fold_cpu(cpu);
5961 * Zero the differential counters of the dead processor
5962 * so that the vm statistics are consistent.
5964 * This is only okay since the processor is dead and cannot
5965 * race with what we are doing.
5967 cpu_vm_stats_fold(cpu);
5972 void __init page_alloc_init(void)
5974 hotcpu_notifier(page_alloc_cpu_notify, 0);
5978 * calculate_totalreserve_pages - called when sysctl_lowmem_reserve_ratio
5979 * or min_free_kbytes changes.
5981 static void calculate_totalreserve_pages(void)
5983 struct pglist_data *pgdat;
5984 unsigned long reserve_pages = 0;
5985 enum zone_type i, j;
5987 for_each_online_pgdat(pgdat) {
5988 for (i = 0; i < MAX_NR_ZONES; i++) {
5989 struct zone *zone = pgdat->node_zones + i;
5992 /* Find valid and maximum lowmem_reserve in the zone */
5993 for (j = i; j < MAX_NR_ZONES; j++) {
5994 if (zone->lowmem_reserve[j] > max)
5995 max = zone->lowmem_reserve[j];
5998 /* we treat the high watermark as reserved pages. */
5999 max += high_wmark_pages(zone);
6001 if (max > zone->managed_pages)
6002 max = zone->managed_pages;
6003 reserve_pages += max;
6005 * Lowmem reserves are not available to
6006 * GFP_HIGHUSER page cache allocations and
6007 * kswapd tries to balance zones to their high
6008 * watermark. As a result, neither should be
6009 * regarded as dirtyable memory, to prevent a
6010 * situation where reclaim has to clean pages
6011 * in order to balance the zones.
6013 zone->dirty_balance_reserve = max;
6016 dirty_balance_reserve = reserve_pages;
6017 totalreserve_pages = reserve_pages;
6021 * setup_per_zone_lowmem_reserve - called whenever
6022 * sysctl_lowmem_reserve_ratio changes. Ensures that each zone
6023 * has a correct pages reserved value, so an adequate number of
6024 * pages are left in the zone after a successful __alloc_pages().
6026 static void setup_per_zone_lowmem_reserve(void)
6028 struct pglist_data *pgdat;
6029 enum zone_type j, idx;
6031 for_each_online_pgdat(pgdat) {
6032 for (j = 0; j < MAX_NR_ZONES; j++) {
6033 struct zone *zone = pgdat->node_zones + j;
6034 unsigned long managed_pages = zone->managed_pages;
6036 zone->lowmem_reserve[j] = 0;
6040 struct zone *lower_zone;
6044 if (sysctl_lowmem_reserve_ratio[idx] < 1)
6045 sysctl_lowmem_reserve_ratio[idx] = 1;
6047 lower_zone = pgdat->node_zones + idx;
6048 lower_zone->lowmem_reserve[j] = managed_pages /
6049 sysctl_lowmem_reserve_ratio[idx];
6050 managed_pages += lower_zone->managed_pages;
6055 /* update totalreserve_pages */
6056 calculate_totalreserve_pages();
6059 static void __setup_per_zone_wmarks(void)
6061 unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
6062 unsigned long lowmem_pages = 0;
6064 unsigned long flags;
6066 /* Calculate total number of !ZONE_HIGHMEM pages */
6067 for_each_zone(zone) {
6068 if (!is_highmem(zone))
6069 lowmem_pages += zone->managed_pages;
6072 for_each_zone(zone) {
6075 spin_lock_irqsave(&zone->lock, flags);
6076 tmp = (u64)pages_min * zone->managed_pages;
6077 do_div(tmp, lowmem_pages);
6078 if (is_highmem(zone)) {
6080 * __GFP_HIGH and PF_MEMALLOC allocations usually don't
6081 * need highmem pages, so cap pages_min to a small
6084 * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN)
6085 * deltas control asynch page reclaim, and so should
6086 * not be capped for highmem.
6088 unsigned long min_pages;
6090 min_pages = zone->managed_pages / 1024;
6091 min_pages = clamp(min_pages, SWAP_CLUSTER_MAX, 128UL);
6092 zone->watermark[WMARK_MIN] = min_pages;
6095 * If it's a lowmem zone, reserve a number of pages
6096 * proportionate to the zone's size.
6098 zone->watermark[WMARK_MIN] = tmp;
6101 zone->watermark[WMARK_LOW] = min_wmark_pages(zone) + (tmp >> 2);
6102 zone->watermark[WMARK_HIGH] = min_wmark_pages(zone) + (tmp >> 1);
6104 __mod_zone_page_state(zone, NR_ALLOC_BATCH,
6105 high_wmark_pages(zone) - low_wmark_pages(zone) -
6106 atomic_long_read(&zone->vm_stat[NR_ALLOC_BATCH]));
6108 spin_unlock_irqrestore(&zone->lock, flags);
6111 /* update totalreserve_pages */
6112 calculate_totalreserve_pages();
6116 * setup_per_zone_wmarks - called when min_free_kbytes changes
6117 * or when memory is hot-{added|removed}
6119 * Ensures that the watermark[min,low,high] values for each zone are set
6120 * correctly with respect to min_free_kbytes.
6122 void setup_per_zone_wmarks(void)
6124 mutex_lock(&zonelists_mutex);
6125 __setup_per_zone_wmarks();
6126 mutex_unlock(&zonelists_mutex);
6130 * The inactive anon list should be small enough that the VM never has to
6131 * do too much work, but large enough that each inactive page has a chance
6132 * to be referenced again before it is swapped out.
6134 * The inactive_anon ratio is the target ratio of ACTIVE_ANON to
6135 * INACTIVE_ANON pages on this zone's LRU, maintained by the
6136 * pageout code. A zone->inactive_ratio of 3 means 3:1 or 25% of
6137 * the anonymous pages are kept on the inactive list.
6140 * memory ratio inactive anon
6141 * -------------------------------------
6150 static void __meminit calculate_zone_inactive_ratio(struct zone *zone)
6152 unsigned int gb, ratio;
6154 /* Zone size in gigabytes */
6155 gb = zone->managed_pages >> (30 - PAGE_SHIFT);
6157 ratio = int_sqrt(10 * gb);
6161 zone->inactive_ratio = ratio;
6164 static void __meminit setup_per_zone_inactive_ratio(void)
6169 calculate_zone_inactive_ratio(zone);
6173 * Initialise min_free_kbytes.
6175 * For small machines we want it small (128k min). For large machines
6176 * we want it large (64MB max). But it is not linear, because network
6177 * bandwidth does not increase linearly with machine size. We use
6179 * min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
6180 * min_free_kbytes = sqrt(lowmem_kbytes * 16)
6196 int __meminit init_per_zone_wmark_min(void)
6198 unsigned long lowmem_kbytes;
6199 int new_min_free_kbytes;
6201 lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
6202 new_min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
6204 if (new_min_free_kbytes > user_min_free_kbytes) {
6205 min_free_kbytes = new_min_free_kbytes;
6206 if (min_free_kbytes < 128)
6207 min_free_kbytes = 128;
6208 if (min_free_kbytes > 65536)
6209 min_free_kbytes = 65536;
6211 pr_warn("min_free_kbytes is not updated to %d because user defined value %d is preferred\n",
6212 new_min_free_kbytes, user_min_free_kbytes);
6214 setup_per_zone_wmarks();
6215 refresh_zone_stat_thresholds();
6216 setup_per_zone_lowmem_reserve();
6217 setup_per_zone_inactive_ratio();
6220 core_initcall(init_per_zone_wmark_min)
6223 * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
6224 * that we can call two helper functions whenever min_free_kbytes
6227 int min_free_kbytes_sysctl_handler(struct ctl_table *table, int write,
6228 void __user *buffer, size_t *length, loff_t *ppos)
6232 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
6237 user_min_free_kbytes = min_free_kbytes;
6238 setup_per_zone_wmarks();
6244 int sysctl_min_unmapped_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_unmapped_pages = (zone->managed_pages *
6256 sysctl_min_unmapped_ratio) / 100;
6260 int sysctl_min_slab_ratio_sysctl_handler(struct ctl_table *table, int write,
6261 void __user *buffer, size_t *length, loff_t *ppos)
6266 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
6271 zone->min_slab_pages = (zone->managed_pages *
6272 sysctl_min_slab_ratio) / 100;
6278 * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
6279 * proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
6280 * whenever sysctl_lowmem_reserve_ratio changes.
6282 * The reserve ratio obviously has absolutely no relation with the
6283 * minimum watermarks. The lowmem reserve ratio can only make sense
6284 * if in function of the boot time zone sizes.
6286 int lowmem_reserve_ratio_sysctl_handler(struct ctl_table *table, int write,
6287 void __user *buffer, size_t *length, loff_t *ppos)
6289 proc_dointvec_minmax(table, write, buffer, length, ppos);
6290 setup_per_zone_lowmem_reserve();
6295 * percpu_pagelist_fraction - changes the pcp->high for each zone on each
6296 * cpu. It is the fraction of total pages in each zone that a hot per cpu
6297 * pagelist can have before it gets flushed back to buddy allocator.
6299 int percpu_pagelist_fraction_sysctl_handler(struct ctl_table *table, int write,
6300 void __user *buffer, size_t *length, loff_t *ppos)
6303 int old_percpu_pagelist_fraction;
6306 mutex_lock(&pcp_batch_high_lock);
6307 old_percpu_pagelist_fraction = percpu_pagelist_fraction;
6309 ret = proc_dointvec_minmax(table, write, buffer, length, ppos);
6310 if (!write || ret < 0)
6313 /* Sanity checking to avoid pcp imbalance */
6314 if (percpu_pagelist_fraction &&
6315 percpu_pagelist_fraction < MIN_PERCPU_PAGELIST_FRACTION) {
6316 percpu_pagelist_fraction = old_percpu_pagelist_fraction;
6322 if (percpu_pagelist_fraction == old_percpu_pagelist_fraction)
6325 for_each_populated_zone(zone) {
6328 for_each_possible_cpu(cpu)
6329 pageset_set_high_and_batch(zone,
6330 per_cpu_ptr(zone->pageset, cpu));
6333 mutex_unlock(&pcp_batch_high_lock);
6338 int hashdist = HASHDIST_DEFAULT;
6340 static int __init set_hashdist(char *str)
6344 hashdist = simple_strtoul(str, &str, 0);
6347 __setup("hashdist=", set_hashdist);
6351 * allocate a large system hash table from bootmem
6352 * - it is assumed that the hash table must contain an exact power-of-2
6353 * quantity of entries
6354 * - limit is the number of hash buckets, not the total allocation size
6356 void *__init alloc_large_system_hash(const char *tablename,
6357 unsigned long bucketsize,
6358 unsigned long numentries,
6361 unsigned int *_hash_shift,
6362 unsigned int *_hash_mask,
6363 unsigned long low_limit,
6364 unsigned long high_limit)
6366 unsigned long long max = high_limit;
6367 unsigned long log2qty, size;
6370 /* allow the kernel cmdline to have a say */
6372 /* round applicable memory size up to nearest megabyte */
6373 numentries = nr_kernel_pages;
6375 /* It isn't necessary when PAGE_SIZE >= 1MB */
6376 if (PAGE_SHIFT < 20)
6377 numentries = round_up(numentries, (1<<20)/PAGE_SIZE);
6379 /* limit to 1 bucket per 2^scale bytes of low memory */
6380 if (scale > PAGE_SHIFT)
6381 numentries >>= (scale - PAGE_SHIFT);
6383 numentries <<= (PAGE_SHIFT - scale);
6385 /* Make sure we've got at least a 0-order allocation.. */
6386 if (unlikely(flags & HASH_SMALL)) {
6387 /* Makes no sense without HASH_EARLY */
6388 WARN_ON(!(flags & HASH_EARLY));
6389 if (!(numentries >> *_hash_shift)) {
6390 numentries = 1UL << *_hash_shift;
6391 BUG_ON(!numentries);
6393 } else if (unlikely((numentries * bucketsize) < PAGE_SIZE))
6394 numentries = PAGE_SIZE / bucketsize;
6396 numentries = roundup_pow_of_two(numentries);
6398 /* limit allocation size to 1/16 total memory by default */
6400 max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
6401 do_div(max, bucketsize);
6403 max = min(max, 0x80000000ULL);
6405 if (numentries < low_limit)
6406 numentries = low_limit;
6407 if (numentries > max)
6410 log2qty = ilog2(numentries);
6413 size = bucketsize << log2qty;
6414 if (flags & HASH_EARLY)
6415 table = memblock_virt_alloc_nopanic(size, 0);
6417 table = __vmalloc(size, GFP_ATOMIC, PAGE_KERNEL);
6420 * If bucketsize is not a power-of-two, we may free
6421 * some pages at the end of hash table which
6422 * alloc_pages_exact() automatically does
6424 if (get_order(size) < MAX_ORDER) {
6425 table = alloc_pages_exact(size, GFP_ATOMIC);
6426 kmemleak_alloc(table, size, 1, GFP_ATOMIC);
6429 } while (!table && size > PAGE_SIZE && --log2qty);
6432 panic("Failed to allocate %s hash table\n", tablename);
6434 printk(KERN_INFO "%s hash table entries: %ld (order: %d, %lu bytes)\n",
6437 ilog2(size) - PAGE_SHIFT,
6441 *_hash_shift = log2qty;
6443 *_hash_mask = (1 << log2qty) - 1;
6448 /* Return a pointer to the bitmap storing bits affecting a block of pages */
6449 static inline unsigned long *get_pageblock_bitmap(struct zone *zone,
6452 #ifdef CONFIG_SPARSEMEM
6453 return __pfn_to_section(pfn)->pageblock_flags;
6455 return zone->pageblock_flags;
6456 #endif /* CONFIG_SPARSEMEM */
6459 static inline int pfn_to_bitidx(struct zone *zone, unsigned long pfn)
6461 #ifdef CONFIG_SPARSEMEM
6462 pfn &= (PAGES_PER_SECTION-1);
6463 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
6465 pfn = pfn - round_down(zone->zone_start_pfn, pageblock_nr_pages);
6466 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
6467 #endif /* CONFIG_SPARSEMEM */
6471 * get_pfnblock_flags_mask - Return the requested group of flags for the pageblock_nr_pages block of pages
6472 * @page: The page within the block of interest
6473 * @pfn: The target page frame number
6474 * @end_bitidx: The last bit of interest to retrieve
6475 * @mask: mask of bits that the caller is interested in
6477 * Return: pageblock_bits flags
6479 unsigned long get_pfnblock_flags_mask(struct page *page, unsigned long pfn,
6480 unsigned long end_bitidx,
6484 unsigned long *bitmap;
6485 unsigned long bitidx, word_bitidx;
6488 zone = page_zone(page);
6489 bitmap = get_pageblock_bitmap(zone, pfn);
6490 bitidx = pfn_to_bitidx(zone, pfn);
6491 word_bitidx = bitidx / BITS_PER_LONG;
6492 bitidx &= (BITS_PER_LONG-1);
6494 word = bitmap[word_bitidx];
6495 bitidx += end_bitidx;
6496 return (word >> (BITS_PER_LONG - bitidx - 1)) & mask;
6500 * set_pfnblock_flags_mask - Set the requested group of flags for a pageblock_nr_pages block of pages
6501 * @page: The page within the block of interest
6502 * @flags: The flags to set
6503 * @pfn: The target page frame number
6504 * @end_bitidx: The last bit of interest
6505 * @mask: mask of bits that the caller is interested in
6507 void set_pfnblock_flags_mask(struct page *page, unsigned long flags,
6509 unsigned long end_bitidx,
6513 unsigned long *bitmap;
6514 unsigned long bitidx, word_bitidx;
6515 unsigned long old_word, word;
6517 BUILD_BUG_ON(NR_PAGEBLOCK_BITS != 4);
6519 zone = page_zone(page);
6520 bitmap = get_pageblock_bitmap(zone, pfn);
6521 bitidx = pfn_to_bitidx(zone, pfn);
6522 word_bitidx = bitidx / BITS_PER_LONG;
6523 bitidx &= (BITS_PER_LONG-1);
6525 VM_BUG_ON_PAGE(!zone_spans_pfn(zone, pfn), page);
6527 bitidx += end_bitidx;
6528 mask <<= (BITS_PER_LONG - bitidx - 1);
6529 flags <<= (BITS_PER_LONG - bitidx - 1);
6531 word = READ_ONCE(bitmap[word_bitidx]);
6533 old_word = cmpxchg(&bitmap[word_bitidx], word, (word & ~mask) | flags);
6534 if (word == old_word)
6541 * This function checks whether pageblock includes unmovable pages or not.
6542 * If @count is not zero, it is okay to include less @count unmovable pages
6544 * PageLRU check without isolation or lru_lock could race so that
6545 * MIGRATE_MOVABLE block might include unmovable pages. It means you can't
6546 * expect this function should be exact.
6548 bool has_unmovable_pages(struct zone *zone, struct page *page, int count,
6549 bool skip_hwpoisoned_pages)
6551 unsigned long pfn, iter, found;
6555 * For avoiding noise data, lru_add_drain_all() should be called
6556 * If ZONE_MOVABLE, the zone never contains unmovable pages
6558 if (zone_idx(zone) == ZONE_MOVABLE)
6560 mt = get_pageblock_migratetype(page);
6561 if (mt == MIGRATE_MOVABLE || is_migrate_cma(mt))
6564 pfn = page_to_pfn(page);
6565 for (found = 0, iter = 0; iter < pageblock_nr_pages; iter++) {
6566 unsigned long check = pfn + iter;
6568 if (!pfn_valid_within(check))
6571 page = pfn_to_page(check);
6574 * Hugepages are not in LRU lists, but they're movable.
6575 * We need not scan over tail pages bacause we don't
6576 * handle each tail page individually in migration.
6578 if (PageHuge(page)) {
6579 iter = round_up(iter + 1, 1<<compound_order(page)) - 1;
6584 * We can't use page_count without pin a page
6585 * because another CPU can free compound page.
6586 * This check already skips compound tails of THP
6587 * because their page->_count is zero at all time.
6589 if (!atomic_read(&page->_count)) {
6590 if (PageBuddy(page))
6591 iter += (1 << page_order(page)) - 1;
6596 * The HWPoisoned page may be not in buddy system, and
6597 * page_count() is not 0.
6599 if (skip_hwpoisoned_pages && PageHWPoison(page))
6605 * If there are RECLAIMABLE pages, we need to check
6606 * it. But now, memory offline itself doesn't call
6607 * shrink_node_slabs() and it still to be fixed.
6610 * If the page is not RAM, page_count()should be 0.
6611 * we don't need more check. This is an _used_ not-movable page.
6613 * The problematic thing here is PG_reserved pages. PG_reserved
6614 * is set to both of a memory hole page and a _used_ kernel
6623 bool is_pageblock_removable_nolock(struct page *page)
6629 * We have to be careful here because we are iterating over memory
6630 * sections which are not zone aware so we might end up outside of
6631 * the zone but still within the section.
6632 * We have to take care about the node as well. If the node is offline
6633 * its NODE_DATA will be NULL - see page_zone.
6635 if (!node_online(page_to_nid(page)))
6638 zone = page_zone(page);
6639 pfn = page_to_pfn(page);
6640 if (!zone_spans_pfn(zone, pfn))
6643 return !has_unmovable_pages(zone, page, 0, true);
6648 static unsigned long pfn_max_align_down(unsigned long pfn)
6650 return pfn & ~(max_t(unsigned long, MAX_ORDER_NR_PAGES,
6651 pageblock_nr_pages) - 1);
6654 static unsigned long pfn_max_align_up(unsigned long pfn)
6656 return ALIGN(pfn, max_t(unsigned long, MAX_ORDER_NR_PAGES,
6657 pageblock_nr_pages));
6660 /* [start, end) must belong to a single zone. */
6661 static int __alloc_contig_migrate_range(struct compact_control *cc,
6662 unsigned long start, unsigned long end)
6664 /* This function is based on compact_zone() from compaction.c. */
6665 unsigned long nr_reclaimed;
6666 unsigned long pfn = start;
6667 unsigned int tries = 0;
6672 while (pfn < end || !list_empty(&cc->migratepages)) {
6673 if (fatal_signal_pending(current)) {
6678 if (list_empty(&cc->migratepages)) {
6679 cc->nr_migratepages = 0;
6680 pfn = isolate_migratepages_range(cc, pfn, end);
6686 } else if (++tries == 5) {
6687 ret = ret < 0 ? ret : -EBUSY;
6691 nr_reclaimed = reclaim_clean_pages_from_list(cc->zone,
6693 cc->nr_migratepages -= nr_reclaimed;
6695 ret = migrate_pages(&cc->migratepages, alloc_migrate_target,
6696 NULL, 0, cc->mode, MR_CMA);
6699 putback_movable_pages(&cc->migratepages);
6706 * alloc_contig_range() -- tries to allocate given range of pages
6707 * @start: start PFN to allocate
6708 * @end: one-past-the-last PFN to allocate
6709 * @migratetype: migratetype of the underlaying pageblocks (either
6710 * #MIGRATE_MOVABLE or #MIGRATE_CMA). All pageblocks
6711 * in range must have the same migratetype and it must
6712 * be either of the two.
6714 * The PFN range does not have to be pageblock or MAX_ORDER_NR_PAGES
6715 * aligned, however it's the caller's responsibility to guarantee that
6716 * we are the only thread that changes migrate type of pageblocks the
6719 * The PFN range must belong to a single zone.
6721 * Returns zero on success or negative error code. On success all
6722 * pages which PFN is in [start, end) are allocated for the caller and
6723 * need to be freed with free_contig_range().
6725 int alloc_contig_range(unsigned long start, unsigned long end,
6726 unsigned migratetype)
6728 unsigned long outer_start, outer_end;
6732 struct compact_control cc = {
6733 .nr_migratepages = 0,
6735 .zone = page_zone(pfn_to_page(start)),
6736 .mode = MIGRATE_SYNC,
6737 .ignore_skip_hint = true,
6739 INIT_LIST_HEAD(&cc.migratepages);
6742 * What we do here is we mark all pageblocks in range as
6743 * MIGRATE_ISOLATE. Because pageblock and max order pages may
6744 * have different sizes, and due to the way page allocator
6745 * work, we align the range to biggest of the two pages so
6746 * that page allocator won't try to merge buddies from
6747 * different pageblocks and change MIGRATE_ISOLATE to some
6748 * other migration type.
6750 * Once the pageblocks are marked as MIGRATE_ISOLATE, we
6751 * migrate the pages from an unaligned range (ie. pages that
6752 * we are interested in). This will put all the pages in
6753 * range back to page allocator as MIGRATE_ISOLATE.
6755 * When this is done, we take the pages in range from page
6756 * allocator removing them from the buddy system. This way
6757 * page allocator will never consider using them.
6759 * This lets us mark the pageblocks back as
6760 * MIGRATE_CMA/MIGRATE_MOVABLE so that free pages in the
6761 * aligned range but not in the unaligned, original range are
6762 * put back to page allocator so that buddy can use them.
6765 ret = start_isolate_page_range(pfn_max_align_down(start),
6766 pfn_max_align_up(end), migratetype,
6771 ret = __alloc_contig_migrate_range(&cc, start, end);
6776 * Pages from [start, end) are within a MAX_ORDER_NR_PAGES
6777 * aligned blocks that are marked as MIGRATE_ISOLATE. What's
6778 * more, all pages in [start, end) are free in page allocator.
6779 * What we are going to do is to allocate all pages from
6780 * [start, end) (that is remove them from page allocator).
6782 * The only problem is that pages at the beginning and at the
6783 * end of interesting range may be not aligned with pages that
6784 * page allocator holds, ie. they can be part of higher order
6785 * pages. Because of this, we reserve the bigger range and
6786 * once this is done free the pages we are not interested in.
6788 * We don't have to hold zone->lock here because the pages are
6789 * isolated thus they won't get removed from buddy.
6792 lru_add_drain_all();
6793 drain_all_pages(cc.zone);
6796 outer_start = start;
6797 while (!PageBuddy(pfn_to_page(outer_start))) {
6798 if (++order >= MAX_ORDER) {
6802 outer_start &= ~0UL << order;
6805 /* Make sure the range is really isolated. */
6806 if (test_pages_isolated(outer_start, end, false)) {
6807 pr_info("%s: [%lx, %lx) PFNs busy\n",
6808 __func__, outer_start, end);
6813 /* Grab isolated pages from freelists. */
6814 outer_end = isolate_freepages_range(&cc, outer_start, end);
6820 /* Free head and tail (if any) */
6821 if (start != outer_start)
6822 free_contig_range(outer_start, start - outer_start);
6823 if (end != outer_end)
6824 free_contig_range(end, outer_end - end);
6827 undo_isolate_page_range(pfn_max_align_down(start),
6828 pfn_max_align_up(end), migratetype);
6832 void free_contig_range(unsigned long pfn, unsigned nr_pages)
6834 unsigned int count = 0;
6836 for (; nr_pages--; pfn++) {
6837 struct page *page = pfn_to_page(pfn);
6839 count += page_count(page) != 1;
6842 WARN(count != 0, "%d pages are still in use!\n", count);
6846 #ifdef CONFIG_MEMORY_HOTPLUG
6848 * The zone indicated has a new number of managed_pages; batch sizes and percpu
6849 * page high values need to be recalulated.
6851 void __meminit zone_pcp_update(struct zone *zone)
6854 mutex_lock(&pcp_batch_high_lock);
6855 for_each_possible_cpu(cpu)
6856 pageset_set_high_and_batch(zone,
6857 per_cpu_ptr(zone->pageset, cpu));
6858 mutex_unlock(&pcp_batch_high_lock);
6862 void zone_pcp_reset(struct zone *zone)
6864 unsigned long flags;
6866 struct per_cpu_pageset *pset;
6868 /* avoid races with drain_pages() */
6869 local_irq_save(flags);
6870 if (zone->pageset != &boot_pageset) {
6871 for_each_online_cpu(cpu) {
6872 pset = per_cpu_ptr(zone->pageset, cpu);
6873 drain_zonestat(zone, pset);
6875 free_percpu(zone->pageset);
6876 zone->pageset = &boot_pageset;
6878 local_irq_restore(flags);
6881 #ifdef CONFIG_MEMORY_HOTREMOVE
6883 * All pages in the range must be isolated before calling this.
6886 __offline_isolated_pages(unsigned long start_pfn, unsigned long end_pfn)
6890 unsigned int order, i;
6892 unsigned long flags;
6893 /* find the first valid pfn */
6894 for (pfn = start_pfn; pfn < end_pfn; pfn++)
6899 zone = page_zone(pfn_to_page(pfn));
6900 spin_lock_irqsave(&zone->lock, flags);
6902 while (pfn < end_pfn) {
6903 if (!pfn_valid(pfn)) {
6907 page = pfn_to_page(pfn);
6909 * The HWPoisoned page may be not in buddy system, and
6910 * page_count() is not 0.
6912 if (unlikely(!PageBuddy(page) && PageHWPoison(page))) {
6914 SetPageReserved(page);
6918 BUG_ON(page_count(page));
6919 BUG_ON(!PageBuddy(page));
6920 order = page_order(page);
6921 #ifdef CONFIG_DEBUG_VM
6922 printk(KERN_INFO "remove from free list %lx %d %lx\n",
6923 pfn, 1 << order, end_pfn);
6925 list_del(&page->lru);
6926 rmv_page_order(page);
6927 zone->free_area[order].nr_free--;
6928 for (i = 0; i < (1 << order); i++)
6929 SetPageReserved((page+i));
6930 pfn += (1 << order);
6932 spin_unlock_irqrestore(&zone->lock, flags);
6936 #ifdef CONFIG_MEMORY_FAILURE
6937 bool is_free_buddy_page(struct page *page)
6939 struct zone *zone = page_zone(page);
6940 unsigned long pfn = page_to_pfn(page);
6941 unsigned long flags;
6944 spin_lock_irqsave(&zone->lock, flags);
6945 for (order = 0; order < MAX_ORDER; order++) {
6946 struct page *page_head = page - (pfn & ((1 << order) - 1));
6948 if (PageBuddy(page_head) && page_order(page_head) >= order)
6951 spin_unlock_irqrestore(&zone->lock, flags);
6953 return order < MAX_ORDER;