~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/mm/page_alloc.c

Version: ~ [ linux-5.5-rc7 ] ~ [ linux-5.4.13 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.97 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.166 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.210 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.210 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.19.8 ] ~ [ linux-3.18.140 ] ~ [ linux-3.17.8 ] ~ [ linux-3.16.81 ] ~ [ linux-3.15.10 ] ~ [ linux-3.14.79 ] ~ [ linux-3.13.11 ] ~ [ linux-3.12.74 ] ~ [ linux-3.11.10 ] ~ [ linux-3.10.108 ] ~ [ linux-3.9.11 ] ~ [ linux-3.8.13 ] ~ [ linux-3.7.10 ] ~ [ linux-3.6.11 ] ~ [ linux-3.5.7 ] ~ [ linux-3.4.113 ] ~ [ linux-3.3.8 ] ~ [ linux-3.2.102 ] ~ [ linux-3.1.10 ] ~ [ linux-3.0.101 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

  1 /*
  2  *  linux/mm/page_alloc.c
  3  *
  4  *  Manages the free list, the system allocates free pages here.
  5  *  Note that kmalloc() lives in slab.c
  6  *
  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)
 15  */
 16 
 17 #include <linux/stddef.h>
 18 #include <linux/mm.h>
 19 #include <linux/swap.h>
 20 #include <linux/interrupt.h>
 21 #include <linux/pagemap.h>
 22 #include <linux/jiffies.h>
 23 #include <linux/bootmem.h>
 24 #include <linux/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/memremap.h>
 47 #include <linux/stop_machine.h>
 48 #include <linux/sort.h>
 49 #include <linux/pfn.h>
 50 #include <linux/backing-dev.h>
 51 #include <linux/fault-inject.h>
 52 #include <linux/page-isolation.h>
 53 #include <linux/page_ext.h>
 54 #include <linux/debugobjects.h>
 55 #include <linux/kmemleak.h>
 56 #include <linux/compaction.h>
 57 #include <trace/events/kmem.h>
 58 #include <linux/prefetch.h>
 59 #include <linux/mm_inline.h>
 60 #include <linux/migrate.h>
 61 #include <linux/page_ext.h>
 62 #include <linux/hugetlb.h>
 63 #include <linux/sched/rt.h>
 64 #include <linux/page_owner.h>
 65 #include <linux/kthread.h>
 66 
 67 #include <asm/sections.h>
 68 #include <asm/tlbflush.h>
 69 #include <asm/div64.h>
 70 #include "internal.h"
 71 
 72 /* prevent >1 _updater_ of zone percpu pageset ->high and ->batch fields */
 73 static DEFINE_MUTEX(pcp_batch_high_lock);
 74 #define MIN_PERCPU_PAGELIST_FRACTION    (8)
 75 
 76 #ifdef CONFIG_USE_PERCPU_NUMA_NODE_ID
 77 DEFINE_PER_CPU(int, numa_node);
 78 EXPORT_PER_CPU_SYMBOL(numa_node);
 79 #endif
 80 
 81 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
 82 /*
 83  * N.B., Do NOT reference the '_numa_mem_' per cpu variable directly.
 84  * It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined.
 85  * Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem()
 86  * defined in <linux/topology.h>.
 87  */
 88 DEFINE_PER_CPU(int, _numa_mem_);                /* Kernel "local memory" node */
 89 EXPORT_PER_CPU_SYMBOL(_numa_mem_);
 90 int _node_numa_mem_[MAX_NUMNODES];
 91 #endif
 92 
 93 /*
 94  * Array of node states.
 95  */
 96 nodemask_t node_states[NR_NODE_STATES] __read_mostly = {
 97         [N_POSSIBLE] = NODE_MASK_ALL,
 98         [N_ONLINE] = { { [0] = 1UL } },
 99 #ifndef CONFIG_NUMA
100         [N_NORMAL_MEMORY] = { { [0] = 1UL } },
101 #ifdef CONFIG_HIGHMEM
102         [N_HIGH_MEMORY] = { { [0] = 1UL } },
103 #endif
104 #ifdef CONFIG_MOVABLE_NODE
105         [N_MEMORY] = { { [0] = 1UL } },
106 #endif
107         [N_CPU] = { { [0] = 1UL } },
108 #endif  /* NUMA */
109 };
110 EXPORT_SYMBOL(node_states);
111 
112 /* Protect totalram_pages and zone->managed_pages */
113 static DEFINE_SPINLOCK(managed_page_count_lock);
114 
115 unsigned long totalram_pages __read_mostly;
116 unsigned long totalreserve_pages __read_mostly;
117 unsigned long totalcma_pages __read_mostly;
118 
119 int percpu_pagelist_fraction;
120 gfp_t gfp_allowed_mask __read_mostly = GFP_BOOT_MASK;
121 
122 /*
123  * A cached value of the page's pageblock's migratetype, used when the page is
124  * put on a pcplist. Used to avoid the pageblock migratetype lookup when
125  * freeing from pcplists in most cases, at the cost of possibly becoming stale.
126  * Also the migratetype set in the page does not necessarily match the pcplist
127  * index, e.g. page might have MIGRATE_CMA set but be on a pcplist with any
128  * other index - this ensures that it will be put on the correct CMA freelist.
129  */
130 static inline int get_pcppage_migratetype(struct page *page)
131 {
132         return page->index;
133 }
134 
135 static inline void set_pcppage_migratetype(struct page *page, int migratetype)
136 {
137         page->index = migratetype;
138 }
139 
140 #ifdef CONFIG_PM_SLEEP
141 /*
142  * The following functions are used by the suspend/hibernate code to temporarily
143  * change gfp_allowed_mask in order to avoid using I/O during memory allocations
144  * while devices are suspended.  To avoid races with the suspend/hibernate code,
145  * they should always be called with pm_mutex held (gfp_allowed_mask also should
146  * only be modified with pm_mutex held, unless the suspend/hibernate code is
147  * guaranteed not to run in parallel with that modification).
148  */
149 
150 static gfp_t saved_gfp_mask;
151 
152 void pm_restore_gfp_mask(void)
153 {
154         WARN_ON(!mutex_is_locked(&pm_mutex));
155         if (saved_gfp_mask) {
156                 gfp_allowed_mask = saved_gfp_mask;
157                 saved_gfp_mask = 0;
158         }
159 }
160 
161 void pm_restrict_gfp_mask(void)
162 {
163         WARN_ON(!mutex_is_locked(&pm_mutex));
164         WARN_ON(saved_gfp_mask);
165         saved_gfp_mask = gfp_allowed_mask;
166         gfp_allowed_mask &= ~(__GFP_IO | __GFP_FS);
167 }
168 
169 bool pm_suspended_storage(void)
170 {
171         if ((gfp_allowed_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
172                 return false;
173         return true;
174 }
175 #endif /* CONFIG_PM_SLEEP */
176 
177 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
178 unsigned int pageblock_order __read_mostly;
179 #endif
180 
181 static void __free_pages_ok(struct page *page, unsigned int order);
182 
183 /*
184  * results with 256, 32 in the lowmem_reserve sysctl:
185  *      1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
186  *      1G machine -> (16M dma, 784M normal, 224M high)
187  *      NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
188  *      HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
189  *      HIGHMEM allocation will leave (224M+784M)/256 of ram reserved in ZONE_DMA
190  *
191  * TBD: should special case ZONE_DMA32 machines here - in those we normally
192  * don't need any ZONE_NORMAL reservation
193  */
194 int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES-1] = {
195 #ifdef CONFIG_ZONE_DMA
196          256,
197 #endif
198 #ifdef CONFIG_ZONE_DMA32
199          256,
200 #endif
201 #ifdef CONFIG_HIGHMEM
202          32,
203 #endif
204          32,
205 };
206 
207 EXPORT_SYMBOL(totalram_pages);
208 
209 static char * const zone_names[MAX_NR_ZONES] = {
210 #ifdef CONFIG_ZONE_DMA
211          "DMA",
212 #endif
213 #ifdef CONFIG_ZONE_DMA32
214          "DMA32",
215 #endif
216          "Normal",
217 #ifdef CONFIG_HIGHMEM
218          "HighMem",
219 #endif
220          "Movable",
221 #ifdef CONFIG_ZONE_DEVICE
222          "Device",
223 #endif
224 };
225 
226 char * const migratetype_names[MIGRATE_TYPES] = {
227         "Unmovable",
228         "Movable",
229         "Reclaimable",
230         "HighAtomic",
231 #ifdef CONFIG_CMA
232         "CMA",
233 #endif
234 #ifdef CONFIG_MEMORY_ISOLATION
235         "Isolate",
236 #endif
237 };
238 
239 compound_page_dtor * const compound_page_dtors[] = {
240         NULL,
241         free_compound_page,
242 #ifdef CONFIG_HUGETLB_PAGE
243         free_huge_page,
244 #endif
245 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
246         free_transhuge_page,
247 #endif
248 };
249 
250 int min_free_kbytes = 1024;
251 int user_min_free_kbytes = -1;
252 int watermark_scale_factor = 10;
253 
254 static unsigned long __meminitdata nr_kernel_pages;
255 static unsigned long __meminitdata nr_all_pages;
256 static unsigned long __meminitdata dma_reserve;
257 
258 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
259 static unsigned long __meminitdata arch_zone_lowest_possible_pfn[MAX_NR_ZONES];
260 static unsigned long __meminitdata arch_zone_highest_possible_pfn[MAX_NR_ZONES];
261 static unsigned long __initdata required_kernelcore;
262 static unsigned long __initdata required_movablecore;
263 static unsigned long __meminitdata zone_movable_pfn[MAX_NUMNODES];
264 static bool mirrored_kernelcore;
265 
266 /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
267 int movable_zone;
268 EXPORT_SYMBOL(movable_zone);
269 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
270 
271 #if MAX_NUMNODES > 1
272 int nr_node_ids __read_mostly = MAX_NUMNODES;
273 int nr_online_nodes __read_mostly = 1;
274 EXPORT_SYMBOL(nr_node_ids);
275 EXPORT_SYMBOL(nr_online_nodes);
276 #endif
277 
278 int page_group_by_mobility_disabled __read_mostly;
279 
280 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
281 static inline void reset_deferred_meminit(pg_data_t *pgdat)
282 {
283         pgdat->first_deferred_pfn = ULONG_MAX;
284 }
285 
286 /* Returns true if the struct page for the pfn is uninitialised */
287 static inline bool __meminit early_page_uninitialised(unsigned long pfn)
288 {
289         int nid = early_pfn_to_nid(pfn);
290 
291         if (node_online(nid) && pfn >= NODE_DATA(nid)->first_deferred_pfn)
292                 return true;
293 
294         return false;
295 }
296 
297 static inline bool early_page_nid_uninitialised(unsigned long pfn, int nid)
298 {
299         if (pfn >= NODE_DATA(nid)->first_deferred_pfn)
300                 return true;
301 
302         return false;
303 }
304 
305 /*
306  * Returns false when the remaining initialisation should be deferred until
307  * later in the boot cycle when it can be parallelised.
308  */
309 static inline bool update_defer_init(pg_data_t *pgdat,
310                                 unsigned long pfn, unsigned long zone_end,
311                                 unsigned long *nr_initialised)
312 {
313         unsigned long max_initialise;
314 
315         /* Always populate low zones for address-contrained allocations */
316         if (zone_end < pgdat_end_pfn(pgdat))
317                 return true;
318         /*
319          * Initialise at least 2G of a node but also take into account that
320          * two large system hashes that can take up 1GB for 0.25TB/node.
321          */
322         max_initialise = max(2UL << (30 - PAGE_SHIFT),
323                 (pgdat->node_spanned_pages >> 8));
324 
325         (*nr_initialised)++;
326         if ((*nr_initialised > max_initialise) &&
327             (pfn & (PAGES_PER_SECTION - 1)) == 0) {
328                 pgdat->first_deferred_pfn = pfn;
329                 return false;
330         }
331 
332         return true;
333 }
334 #else
335 static inline void reset_deferred_meminit(pg_data_t *pgdat)
336 {
337 }
338 
339 static inline bool early_page_uninitialised(unsigned long pfn)
340 {
341         return false;
342 }
343 
344 static inline bool early_page_nid_uninitialised(unsigned long pfn, int nid)
345 {
346         return false;
347 }
348 
349 static inline bool update_defer_init(pg_data_t *pgdat,
350                                 unsigned long pfn, unsigned long zone_end,
351                                 unsigned long *nr_initialised)
352 {
353         return true;
354 }
355 #endif
356 
357 
358 void set_pageblock_migratetype(struct page *page, int migratetype)
359 {
360         if (unlikely(page_group_by_mobility_disabled &&
361                      migratetype < MIGRATE_PCPTYPES))
362                 migratetype = MIGRATE_UNMOVABLE;
363 
364         set_pageblock_flags_group(page, (unsigned long)migratetype,
365                                         PB_migrate, PB_migrate_end);
366 }
367 
368 #ifdef CONFIG_DEBUG_VM
369 static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
370 {
371         int ret = 0;
372         unsigned seq;
373         unsigned long pfn = page_to_pfn(page);
374         unsigned long sp, start_pfn;
375 
376         do {
377                 seq = zone_span_seqbegin(zone);
378                 start_pfn = zone->zone_start_pfn;
379                 sp = zone->spanned_pages;
380                 if (!zone_spans_pfn(zone, pfn))
381                         ret = 1;
382         } while (zone_span_seqretry(zone, seq));
383 
384         if (ret)
385                 pr_err("page 0x%lx outside node %d zone %s [ 0x%lx - 0x%lx ]\n",
386                         pfn, zone_to_nid(zone), zone->name,
387                         start_pfn, start_pfn + sp);
388 
389         return ret;
390 }
391 
392 static int page_is_consistent(struct zone *zone, struct page *page)
393 {
394         if (!pfn_valid_within(page_to_pfn(page)))
395                 return 0;
396         if (zone != page_zone(page))
397                 return 0;
398 
399         return 1;
400 }
401 /*
402  * Temporary debugging check for pages not lying within a given zone.
403  */
404 static int bad_range(struct zone *zone, struct page *page)
405 {
406         if (page_outside_zone_boundaries(zone, page))
407                 return 1;
408         if (!page_is_consistent(zone, page))
409                 return 1;
410 
411         return 0;
412 }
413 #else
414 static inline int bad_range(struct zone *zone, struct page *page)
415 {
416         return 0;
417 }
418 #endif
419 
420 static void bad_page(struct page *page, const char *reason,
421                 unsigned long bad_flags)
422 {
423         static unsigned long resume;
424         static unsigned long nr_shown;
425         static unsigned long nr_unshown;
426 
427         /* Don't complain about poisoned pages */
428         if (PageHWPoison(page)) {
429                 page_mapcount_reset(page); /* remove PageBuddy */
430                 return;
431         }
432 
433         /*
434          * Allow a burst of 60 reports, then keep quiet for that minute;
435          * or allow a steady drip of one report per second.
436          */
437         if (nr_shown == 60) {
438                 if (time_before(jiffies, resume)) {
439                         nr_unshown++;
440                         goto out;
441                 }
442                 if (nr_unshown) {
443                         pr_alert(
444                               "BUG: Bad page state: %lu messages suppressed\n",
445                                 nr_unshown);
446                         nr_unshown = 0;
447                 }
448                 nr_shown = 0;
449         }
450         if (nr_shown++ == 0)
451                 resume = jiffies + 60 * HZ;
452 
453         pr_alert("BUG: Bad page state in process %s  pfn:%05lx\n",
454                 current->comm, page_to_pfn(page));
455         __dump_page(page, reason);
456         bad_flags &= page->flags;
457         if (bad_flags)
458                 pr_alert("bad because of flags: %#lx(%pGp)\n",
459                                                 bad_flags, &bad_flags);
460         dump_page_owner(page);
461 
462         print_modules();
463         dump_stack();
464 out:
465         /* Leave bad fields for debug, except PageBuddy could make trouble */
466         page_mapcount_reset(page); /* remove PageBuddy */
467         add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
468 }
469 
470 /*
471  * Higher-order pages are called "compound pages".  They are structured thusly:
472  *
473  * The first PAGE_SIZE page is called the "head page" and have PG_head set.
474  *
475  * The remaining PAGE_SIZE pages are called "tail pages". PageTail() is encoded
476  * in bit 0 of page->compound_head. The rest of bits is pointer to head page.
477  *
478  * The first tail page's ->compound_dtor holds the offset in array of compound
479  * page destructors. See compound_page_dtors.
480  *
481  * The first tail page's ->compound_order holds the order of allocation.
482  * This usage means that zero-order pages may not be compound.
483  */
484 
485 void free_compound_page(struct page *page)
486 {
487         __free_pages_ok(page, compound_order(page));
488 }
489 
490 void prep_compound_page(struct page *page, unsigned int order)
491 {
492         int i;
493         int nr_pages = 1 << order;
494 
495         set_compound_page_dtor(page, COMPOUND_PAGE_DTOR);
496         set_compound_order(page, order);
497         __SetPageHead(page);
498         for (i = 1; i < nr_pages; i++) {
499                 struct page *p = page + i;
500                 set_page_count(p, 0);
501                 p->mapping = TAIL_MAPPING;
502                 set_compound_head(p, page);
503         }
504         atomic_set(compound_mapcount_ptr(page), -1);
505 }
506 
507 #ifdef CONFIG_DEBUG_PAGEALLOC
508 unsigned int _debug_guardpage_minorder;
509 bool _debug_pagealloc_enabled __read_mostly
510                         = IS_ENABLED(CONFIG_DEBUG_PAGEALLOC_ENABLE_DEFAULT);
511 EXPORT_SYMBOL(_debug_pagealloc_enabled);
512 bool _debug_guardpage_enabled __read_mostly;
513 
514 static int __init early_debug_pagealloc(char *buf)
515 {
516         if (!buf)
517                 return -EINVAL;
518 
519         if (strcmp(buf, "on") == 0)
520                 _debug_pagealloc_enabled = true;
521 
522         if (strcmp(buf, "off") == 0)
523                 _debug_pagealloc_enabled = false;
524 
525         return 0;
526 }
527 early_param("debug_pagealloc", early_debug_pagealloc);
528 
529 static bool need_debug_guardpage(void)
530 {
531         /* If we don't use debug_pagealloc, we don't need guard page */
532         if (!debug_pagealloc_enabled())
533                 return false;
534 
535         return true;
536 }
537 
538 static void init_debug_guardpage(void)
539 {
540         if (!debug_pagealloc_enabled())
541                 return;
542 
543         _debug_guardpage_enabled = true;
544 }
545 
546 struct page_ext_operations debug_guardpage_ops = {
547         .need = need_debug_guardpage,
548         .init = init_debug_guardpage,
549 };
550 
551 static int __init debug_guardpage_minorder_setup(char *buf)
552 {
553         unsigned long res;
554 
555         if (kstrtoul(buf, 10, &res) < 0 ||  res > MAX_ORDER / 2) {
556                 pr_err("Bad debug_guardpage_minorder value\n");
557                 return 0;
558         }
559         _debug_guardpage_minorder = res;
560         pr_info("Setting debug_guardpage_minorder to %lu\n", res);
561         return 0;
562 }
563 __setup("debug_guardpage_minorder=", debug_guardpage_minorder_setup);
564 
565 static inline void set_page_guard(struct zone *zone, struct page *page,
566                                 unsigned int order, int migratetype)
567 {
568         struct page_ext *page_ext;
569 
570         if (!debug_guardpage_enabled())
571                 return;
572 
573         page_ext = lookup_page_ext(page);
574         __set_bit(PAGE_EXT_DEBUG_GUARD, &page_ext->flags);
575 
576         INIT_LIST_HEAD(&page->lru);
577         set_page_private(page, order);
578         /* Guard pages are not available for any usage */
579         __mod_zone_freepage_state(zone, -(1 << order), migratetype);
580 }
581 
582 static inline void clear_page_guard(struct zone *zone, struct page *page,
583                                 unsigned int order, int migratetype)
584 {
585         struct page_ext *page_ext;
586 
587         if (!debug_guardpage_enabled())
588                 return;
589 
590         page_ext = lookup_page_ext(page);
591         __clear_bit(PAGE_EXT_DEBUG_GUARD, &page_ext->flags);
592 
593         set_page_private(page, 0);
594         if (!is_migrate_isolate(migratetype))
595                 __mod_zone_freepage_state(zone, (1 << order), migratetype);
596 }
597 #else
598 struct page_ext_operations debug_guardpage_ops = { NULL, };
599 static inline void set_page_guard(struct zone *zone, struct page *page,
600                                 unsigned int order, int migratetype) {}
601 static inline void clear_page_guard(struct zone *zone, struct page *page,
602                                 unsigned int order, int migratetype) {}
603 #endif
604 
605 static inline void set_page_order(struct page *page, unsigned int order)
606 {
607         set_page_private(page, order);
608         __SetPageBuddy(page);
609 }
610 
611 static inline void rmv_page_order(struct page *page)
612 {
613         __ClearPageBuddy(page);
614         set_page_private(page, 0);
615 }
616 
617 /*
618  * This function checks whether a page is free && is the buddy
619  * we can do coalesce a page and its buddy if
620  * (a) the buddy is not in a hole &&
621  * (b) the buddy is in the buddy system &&
622  * (c) a page and its buddy have the same order &&
623  * (d) a page and its buddy are in the same zone.
624  *
625  * For recording whether a page is in the buddy system, we set ->_mapcount
626  * PAGE_BUDDY_MAPCOUNT_VALUE.
627  * Setting, clearing, and testing _mapcount PAGE_BUDDY_MAPCOUNT_VALUE is
628  * serialized by zone->lock.
629  *
630  * For recording page's order, we use page_private(page).
631  */
632 static inline int page_is_buddy(struct page *page, struct page *buddy,
633                                                         unsigned int order)
634 {
635         if (!pfn_valid_within(page_to_pfn(buddy)))
636                 return 0;
637 
638         if (page_is_guard(buddy) && page_order(buddy) == order) {
639                 if (page_zone_id(page) != page_zone_id(buddy))
640                         return 0;
641 
642                 VM_BUG_ON_PAGE(page_count(buddy) != 0, buddy);
643 
644                 return 1;
645         }
646 
647         if (PageBuddy(buddy) && page_order(buddy) == order) {
648                 /*
649                  * zone check is done late to avoid uselessly
650                  * calculating zone/node ids for pages that could
651                  * never merge.
652                  */
653                 if (page_zone_id(page) != page_zone_id(buddy))
654                         return 0;
655 
656                 VM_BUG_ON_PAGE(page_count(buddy) != 0, buddy);
657 
658                 return 1;
659         }
660         return 0;
661 }
662 
663 /*
664  * Freeing function for a buddy system allocator.
665  *
666  * The concept of a buddy system is to maintain direct-mapped table
667  * (containing bit values) for memory blocks of various "orders".
668  * The bottom level table contains the map for the smallest allocatable
669  * units of memory (here, pages), and each level above it describes
670  * pairs of units from the levels below, hence, "buddies".
671  * At a high level, all that happens here is marking the table entry
672  * at the bottom level available, and propagating the changes upward
673  * as necessary, plus some accounting needed to play nicely with other
674  * parts of the VM system.
675  * At each level, we keep a list of pages, which are heads of continuous
676  * free pages of length of (1 << order) and marked with _mapcount
677  * PAGE_BUDDY_MAPCOUNT_VALUE. Page's order is recorded in page_private(page)
678  * field.
679  * So when we are allocating or freeing one, we can derive the state of the
680  * other.  That is, if we allocate a small block, and both were
681  * free, the remainder of the region must be split into blocks.
682  * If a block is freed, and its buddy is also free, then this
683  * triggers coalescing into a block of larger size.
684  *
685  * -- nyc
686  */
687 
688 static inline void __free_one_page(struct page *page,
689                 unsigned long pfn,
690                 struct zone *zone, unsigned int order,
691                 int migratetype)
692 {
693         unsigned long page_idx;
694         unsigned long combined_idx;
695         unsigned long uninitialized_var(buddy_idx);
696         struct page *buddy;
697         unsigned int max_order;
698 
699         max_order = min_t(unsigned int, MAX_ORDER, pageblock_order + 1);
700 
701         VM_BUG_ON(!zone_is_initialized(zone));
702         VM_BUG_ON_PAGE(page->flags & PAGE_FLAGS_CHECK_AT_PREP, page);
703 
704         VM_BUG_ON(migratetype == -1);
705         if (likely(!is_migrate_isolate(migratetype)))
706                 __mod_zone_freepage_state(zone, 1 << order, migratetype);
707 
708         page_idx = pfn & ((1 << MAX_ORDER) - 1);
709 
710         VM_BUG_ON_PAGE(page_idx & ((1 << order) - 1), page);
711         VM_BUG_ON_PAGE(bad_range(zone, page), page);
712 
713 continue_merging:
714         while (order < max_order - 1) {
715                 buddy_idx = __find_buddy_index(page_idx, order);
716                 buddy = page + (buddy_idx - page_idx);
717                 if (!page_is_buddy(page, buddy, order))
718                         goto done_merging;
719                 /*
720                  * Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page,
721                  * merge with it and move up one order.
722                  */
723                 if (page_is_guard(buddy)) {
724                         clear_page_guard(zone, buddy, order, migratetype);
725                 } else {
726                         list_del(&buddy->lru);
727                         zone->free_area[order].nr_free--;
728                         rmv_page_order(buddy);
729                 }
730                 combined_idx = buddy_idx & page_idx;
731                 page = page + (combined_idx - page_idx);
732                 page_idx = combined_idx;
733                 order++;
734         }
735         if (max_order < MAX_ORDER) {
736                 /* If we are here, it means order is >= pageblock_order.
737                  * We want to prevent merge between freepages on isolate
738                  * pageblock and normal pageblock. Without this, pageblock
739                  * isolation could cause incorrect freepage or CMA accounting.
740                  *
741                  * We don't want to hit this code for the more frequent
742                  * low-order merging.
743                  */
744                 if (unlikely(has_isolate_pageblock(zone))) {
745                         int buddy_mt;
746 
747                         buddy_idx = __find_buddy_index(page_idx, order);
748                         buddy = page + (buddy_idx - page_idx);
749                         buddy_mt = get_pageblock_migratetype(buddy);
750 
751                         if (migratetype != buddy_mt
752                                         && (is_migrate_isolate(migratetype) ||
753                                                 is_migrate_isolate(buddy_mt)))
754                                 goto done_merging;
755                 }
756                 max_order++;
757                 goto continue_merging;
758         }
759 
760 done_merging:
761         set_page_order(page, order);
762 
763         /*
764          * If this is not the largest possible page, check if the buddy
765          * of the next-highest order is free. If it is, it's possible
766          * that pages are being freed that will coalesce soon. In case,
767          * that is happening, add the free page to the tail of the list
768          * so it's less likely to be used soon and more likely to be merged
769          * as a higher order page
770          */
771         if ((order < MAX_ORDER-2) && pfn_valid_within(page_to_pfn(buddy))) {
772                 struct page *higher_page, *higher_buddy;
773                 combined_idx = buddy_idx & page_idx;
774                 higher_page = page + (combined_idx - page_idx);
775                 buddy_idx = __find_buddy_index(combined_idx, order + 1);
776                 higher_buddy = higher_page + (buddy_idx - combined_idx);
777                 if (page_is_buddy(higher_page, higher_buddy, order + 1)) {
778                         list_add_tail(&page->lru,
779                                 &zone->free_area[order].free_list[migratetype]);
780                         goto out;
781                 }
782         }
783 
784         list_add(&page->lru, &zone->free_area[order].free_list[migratetype]);
785 out:
786         zone->free_area[order].nr_free++;
787 }
788 
789 static inline int free_pages_check(struct page *page)
790 {
791         const char *bad_reason = NULL;
792         unsigned long bad_flags = 0;
793 
794         if (unlikely(atomic_read(&page->_mapcount) != -1))
795                 bad_reason = "nonzero mapcount";
796         if (unlikely(page->mapping != NULL))
797                 bad_reason = "non-NULL mapping";
798         if (unlikely(page_ref_count(page) != 0))
799                 bad_reason = "nonzero _count";
800         if (unlikely(page->flags & PAGE_FLAGS_CHECK_AT_FREE)) {
801                 bad_reason = "PAGE_FLAGS_CHECK_AT_FREE flag(s) set";
802                 bad_flags = PAGE_FLAGS_CHECK_AT_FREE;
803         }
804 #ifdef CONFIG_MEMCG
805         if (unlikely(page->mem_cgroup))
806                 bad_reason = "page still charged to cgroup";
807 #endif
808         if (unlikely(bad_reason)) {
809                 bad_page(page, bad_reason, bad_flags);
810                 return 1;
811         }
812         page_cpupid_reset_last(page);
813         if (page->flags & PAGE_FLAGS_CHECK_AT_PREP)
814                 page->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
815         return 0;
816 }
817 
818 /*
819  * Frees a number of pages from the PCP lists
820  * Assumes all pages on list are in same zone, and of same order.
821  * count is the number of pages to free.
822  *
823  * If the zone was previously in an "all pages pinned" state then look to
824  * see if this freeing clears that state.
825  *
826  * And clear the zone's pages_scanned counter, to hold off the "all pages are
827  * pinned" detection logic.
828  */
829 static void free_pcppages_bulk(struct zone *zone, int count,
830                                         struct per_cpu_pages *pcp)
831 {
832         int migratetype = 0;
833         int batch_free = 0;
834         int to_free = count;
835         unsigned long nr_scanned;
836 
837         spin_lock(&zone->lock);
838         nr_scanned = zone_page_state(zone, NR_PAGES_SCANNED);
839         if (nr_scanned)
840                 __mod_zone_page_state(zone, NR_PAGES_SCANNED, -nr_scanned);
841 
842         while (to_free) {
843                 struct page *page;
844                 struct list_head *list;
845 
846                 /*
847                  * Remove pages from lists in a round-robin fashion. A
848                  * batch_free count is maintained that is incremented when an
849                  * empty list is encountered.  This is so more pages are freed
850                  * off fuller lists instead of spinning excessively around empty
851                  * lists
852                  */
853                 do {
854                         batch_free++;
855                         if (++migratetype == MIGRATE_PCPTYPES)
856                                 migratetype = 0;
857                         list = &pcp->lists[migratetype];
858                 } while (list_empty(list));
859 
860                 /* This is the only non-empty list. Free them all. */
861                 if (batch_free == MIGRATE_PCPTYPES)
862                         batch_free = to_free;
863 
864                 do {
865                         int mt; /* migratetype of the to-be-freed page */
866 
867                         page = list_last_entry(list, struct page, lru);
868                         /* must delete as __free_one_page list manipulates */
869                         list_del(&page->lru);
870 
871                         mt = get_pcppage_migratetype(page);
872                         /* MIGRATE_ISOLATE page should not go to pcplists */
873                         VM_BUG_ON_PAGE(is_migrate_isolate(mt), page);
874                         /* Pageblock could have been isolated meanwhile */
875                         if (unlikely(has_isolate_pageblock(zone)))
876                                 mt = get_pageblock_migratetype(page);
877 
878                         __free_one_page(page, page_to_pfn(page), zone, 0, mt);
879                         trace_mm_page_pcpu_drain(page, 0, mt);
880                 } while (--to_free && --batch_free && !list_empty(list));
881         }
882         spin_unlock(&zone->lock);
883 }
884 
885 static void free_one_page(struct zone *zone,
886                                 struct page *page, unsigned long pfn,
887                                 unsigned int order,
888                                 int migratetype)
889 {
890         unsigned long nr_scanned;
891         spin_lock(&zone->lock);
892         nr_scanned = zone_page_state(zone, NR_PAGES_SCANNED);
893         if (nr_scanned)
894                 __mod_zone_page_state(zone, NR_PAGES_SCANNED, -nr_scanned);
895 
896         if (unlikely(has_isolate_pageblock(zone) ||
897                 is_migrate_isolate(migratetype))) {
898                 migratetype = get_pfnblock_migratetype(page, pfn);
899         }
900         __free_one_page(page, pfn, zone, order, migratetype);
901         spin_unlock(&zone->lock);
902 }
903 
904 static int free_tail_pages_check(struct page *head_page, struct page *page)
905 {
906         int ret = 1;
907 
908         /*
909          * We rely page->lru.next never has bit 0 set, unless the page
910          * is PageTail(). Let's make sure that's true even for poisoned ->lru.
911          */
912         BUILD_BUG_ON((unsigned long)LIST_POISON1 & 1);
913 
914         if (!IS_ENABLED(CONFIG_DEBUG_VM)) {
915                 ret = 0;
916                 goto out;
917         }
918         switch (page - head_page) {
919         case 1:
920                 /* the first tail page: ->mapping is compound_mapcount() */
921                 if (unlikely(compound_mapcount(page))) {
922                         bad_page(page, "nonzero compound_mapcount", 0);
923                         goto out;
924                 }
925                 break;
926         case 2:
927                 /*
928                  * the second tail page: ->mapping is
929                  * page_deferred_list().next -- ignore value.
930                  */
931                 break;
932         default:
933                 if (page->mapping != TAIL_MAPPING) {
934                         bad_page(page, "corrupted mapping in tail page", 0);
935                         goto out;
936                 }
937                 break;
938         }
939         if (unlikely(!PageTail(page))) {
940                 bad_page(page, "PageTail not set", 0);
941                 goto out;
942         }
943         if (unlikely(compound_head(page) != head_page)) {
944                 bad_page(page, "compound_head not consistent", 0);
945                 goto out;
946         }
947         ret = 0;
948 out:
949         page->mapping = NULL;
950         clear_compound_head(page);
951         return ret;
952 }
953 
954 static void __meminit __init_single_page(struct page *page, unsigned long pfn,
955                                 unsigned long zone, int nid)
956 {
957         set_page_links(page, zone, nid, pfn);
958         init_page_count(page);
959         page_mapcount_reset(page);
960         page_cpupid_reset_last(page);
961 
962         INIT_LIST_HEAD(&page->lru);
963 #ifdef WANT_PAGE_VIRTUAL
964         /* The shift won't overflow because ZONE_NORMAL is below 4G. */
965         if (!is_highmem_idx(zone))
966                 set_page_address(page, __va(pfn << PAGE_SHIFT));
967 #endif
968 }
969 
970 static void __meminit __init_single_pfn(unsigned long pfn, unsigned long zone,
971                                         int nid)
972 {
973         return __init_single_page(pfn_to_page(pfn), pfn, zone, nid);
974 }
975 
976 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
977 static void init_reserved_page(unsigned long pfn)
978 {
979         pg_data_t *pgdat;
980         int nid, zid;
981 
982         if (!early_page_uninitialised(pfn))
983                 return;
984 
985         nid = early_pfn_to_nid(pfn);
986         pgdat = NODE_DATA(nid);
987 
988         for (zid = 0; zid < MAX_NR_ZONES; zid++) {
989                 struct zone *zone = &pgdat->node_zones[zid];
990 
991                 if (pfn >= zone->zone_start_pfn && pfn < zone_end_pfn(zone))
992                         break;
993         }
994         __init_single_pfn(pfn, zid, nid);
995 }
996 #else
997 static inline void init_reserved_page(unsigned long pfn)
998 {
999 }
1000 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
1001 
1002 /*
1003  * Initialised pages do not have PageReserved set. This function is
1004  * called for each range allocated by the bootmem allocator and
1005  * marks the pages PageReserved. The remaining valid pages are later
1006  * sent to the buddy page allocator.
1007  */
1008 void __meminit reserve_bootmem_region(phys_addr_t start, phys_addr_t end)
1009 {
1010         unsigned long start_pfn = PFN_DOWN(start);
1011         unsigned long end_pfn = PFN_UP(end);
1012 
1013         for (; start_pfn < end_pfn; start_pfn++) {
1014                 if (pfn_valid(start_pfn)) {
1015                         struct page *page = pfn_to_page(start_pfn);
1016 
1017                         init_reserved_page(start_pfn);
1018 
1019                         /* Avoid false-positive PageTail() */
1020                         INIT_LIST_HEAD(&page->lru);
1021 
1022                         SetPageReserved(page);
1023                 }
1024         }
1025 }
1026 
1027 static bool free_pages_prepare(struct page *page, unsigned int order)
1028 {
1029         bool compound = PageCompound(page);
1030         int i, bad = 0;
1031 
1032         VM_BUG_ON_PAGE(PageTail(page), page);
1033         VM_BUG_ON_PAGE(compound && compound_order(page) != order, page);
1034 
1035         trace_mm_page_free(page, order);
1036         kmemcheck_free_shadow(page, order);
1037         kasan_free_pages(page, order);
1038 
1039         if (PageAnon(page))
1040                 page->mapping = NULL;
1041         bad += free_pages_check(page);
1042         for (i = 1; i < (1 << order); i++) {
1043                 if (compound)
1044                         bad += free_tail_pages_check(page, page + i);
1045                 bad += free_pages_check(page + i);
1046         }
1047         if (bad)
1048                 return false;
1049 
1050         reset_page_owner(page, order);
1051 
1052         if (!PageHighMem(page)) {
1053                 debug_check_no_locks_freed(page_address(page),
1054                                            PAGE_SIZE << order);
1055                 debug_check_no_obj_freed(page_address(page),
1056                                            PAGE_SIZE << order);
1057         }
1058         arch_free_page(page, order);
1059         kernel_poison_pages(page, 1 << order, 0);
1060         kernel_map_pages(page, 1 << order, 0);
1061 
1062         return true;
1063 }
1064 
1065 static void __free_pages_ok(struct page *page, unsigned int order)
1066 {
1067         unsigned long flags;
1068         int migratetype;
1069         unsigned long pfn = page_to_pfn(page);
1070 
1071         if (!free_pages_prepare(page, order))
1072                 return;
1073 
1074         migratetype = get_pfnblock_migratetype(page, pfn);
1075         local_irq_save(flags);
1076         __count_vm_events(PGFREE, 1 << order);
1077         free_one_page(page_zone(page), page, pfn, order, migratetype);
1078         local_irq_restore(flags);
1079 }
1080 
1081 static void __init __free_pages_boot_core(struct page *page,
1082                                         unsigned long pfn, unsigned int order)
1083 {
1084         unsigned int nr_pages = 1 << order;
1085         struct page *p = page;
1086         unsigned int loop;
1087 
1088         prefetchw(p);
1089         for (loop = 0; loop < (nr_pages - 1); loop++, p++) {
1090                 prefetchw(p + 1);
1091                 __ClearPageReserved(p);
1092                 set_page_count(p, 0);
1093         }
1094         __ClearPageReserved(p);
1095         set_page_count(p, 0);
1096 
1097         page_zone(page)->managed_pages += nr_pages;
1098         set_page_refcounted(page);
1099         __free_pages(page, order);
1100 }
1101 
1102 #if defined(CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID) || \
1103         defined(CONFIG_HAVE_MEMBLOCK_NODE_MAP)
1104 
1105 static struct mminit_pfnnid_cache early_pfnnid_cache __meminitdata;
1106 
1107 int __meminit early_pfn_to_nid(unsigned long pfn)
1108 {
1109         static DEFINE_SPINLOCK(early_pfn_lock);
1110         int nid;
1111 
1112         spin_lock(&early_pfn_lock);
1113         nid = __early_pfn_to_nid(pfn, &early_pfnnid_cache);
1114         if (nid < 0)
1115                 nid = first_online_node;
1116         spin_unlock(&early_pfn_lock);
1117 
1118         return nid;
1119 }
1120 #endif
1121 
1122 #ifdef CONFIG_NODES_SPAN_OTHER_NODES
1123 static inline bool __meminit meminit_pfn_in_nid(unsigned long pfn, int node,
1124                                         struct mminit_pfnnid_cache *state)
1125 {
1126         int nid;
1127 
1128         nid = __early_pfn_to_nid(pfn, state);
1129         if (nid >= 0 && nid != node)
1130                 return false;
1131         return true;
1132 }
1133 
1134 /* Only safe to use early in boot when initialisation is single-threaded */
1135 static inline bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
1136 {
1137         return meminit_pfn_in_nid(pfn, node, &early_pfnnid_cache);
1138 }
1139 
1140 #else
1141 
1142 static inline bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
1143 {
1144         return true;
1145 }
1146 static inline bool __meminit meminit_pfn_in_nid(unsigned long pfn, int node,
1147                                         struct mminit_pfnnid_cache *state)
1148 {
1149         return true;
1150 }
1151 #endif
1152 
1153 
1154 void __init __free_pages_bootmem(struct page *page, unsigned long pfn,
1155                                                         unsigned int order)
1156 {
1157         if (early_page_uninitialised(pfn))
1158                 return;
1159         return __free_pages_boot_core(page, pfn, order);
1160 }
1161 
1162 /*
1163  * Check that the whole (or subset of) a pageblock given by the interval of
1164  * [start_pfn, end_pfn) is valid and within the same zone, before scanning it
1165  * with the migration of free compaction scanner. The scanners then need to
1166  * use only pfn_valid_within() check for arches that allow holes within
1167  * pageblocks.
1168  *
1169  * Return struct page pointer of start_pfn, or NULL if checks were not passed.
1170  *
1171  * It's possible on some configurations to have a setup like node0 node1 node0
1172  * i.e. it's possible that all pages within a zones range of pages do not
1173  * belong to a single zone. We assume that a border between node0 and node1
1174  * can occur within a single pageblock, but not a node0 node1 node0
1175  * interleaving within a single pageblock. It is therefore sufficient to check
1176  * the first and last page of a pageblock and avoid checking each individual
1177  * page in a pageblock.
1178  */
1179 struct page *__pageblock_pfn_to_page(unsigned long start_pfn,
1180                                      unsigned long end_pfn, struct zone *zone)
1181 {
1182         struct page *start_page;
1183         struct page *end_page;
1184 
1185         /* end_pfn is one past the range we are checking */
1186         end_pfn--;
1187 
1188         if (!pfn_valid(start_pfn) || !pfn_valid(end_pfn))
1189                 return NULL;
1190 
1191         start_page = pfn_to_page(start_pfn);
1192 
1193         if (page_zone(start_page) != zone)
1194                 return NULL;
1195 
1196         end_page = pfn_to_page(end_pfn);
1197 
1198         /* This gives a shorter code than deriving page_zone(end_page) */
1199         if (page_zone_id(start_page) != page_zone_id(end_page))
1200                 return NULL;
1201 
1202         return start_page;
1203 }
1204 
1205 void set_zone_contiguous(struct zone *zone)
1206 {
1207         unsigned long block_start_pfn = zone->zone_start_pfn;
1208         unsigned long block_end_pfn;
1209 
1210         block_end_pfn = ALIGN(block_start_pfn + 1, pageblock_nr_pages);
1211         for (; block_start_pfn < zone_end_pfn(zone);
1212                         block_start_pfn = block_end_pfn,
1213                          block_end_pfn += pageblock_nr_pages) {
1214 
1215                 block_end_pfn = min(block_end_pfn, zone_end_pfn(zone));
1216 
1217                 if (!__pageblock_pfn_to_page(block_start_pfn,
1218                                              block_end_pfn, zone))
1219                         return;
1220         }
1221 
1222         /* We confirm that there is no hole */
1223         zone->contiguous = true;
1224 }
1225 
1226 void clear_zone_contiguous(struct zone *zone)
1227 {
1228         zone->contiguous = false;
1229 }
1230 
1231 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1232 static void __init deferred_free_range(struct page *page,
1233                                         unsigned long pfn, int nr_pages)
1234 {
1235         int i;
1236 
1237         if (!page)
1238                 return;
1239 
1240         /* Free a large naturally-aligned chunk if possible */
1241         if (nr_pages == MAX_ORDER_NR_PAGES &&
1242             (pfn & (MAX_ORDER_NR_PAGES-1)) == 0) {
1243                 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
1244                 __free_pages_boot_core(page, pfn, MAX_ORDER-1);
1245                 return;
1246         }
1247 
1248         for (i = 0; i < nr_pages; i++, page++, pfn++)
1249                 __free_pages_boot_core(page, pfn, 0);
1250 }
1251 
1252 /* Completion tracking for deferred_init_memmap() threads */
1253 static atomic_t pgdat_init_n_undone __initdata;
1254 static __initdata DECLARE_COMPLETION(pgdat_init_all_done_comp);
1255 
1256 static inline void __init pgdat_init_report_one_done(void)
1257 {
1258         if (atomic_dec_and_test(&pgdat_init_n_undone))
1259                 complete(&pgdat_init_all_done_comp);
1260 }
1261 
1262 /* Initialise remaining memory on a node */
1263 static int __init deferred_init_memmap(void *data)
1264 {
1265         pg_data_t *pgdat = data;
1266         int nid = pgdat->node_id;
1267         struct mminit_pfnnid_cache nid_init_state = { };
1268         unsigned long start = jiffies;
1269         unsigned long nr_pages = 0;
1270         unsigned long walk_start, walk_end;
1271         int i, zid;
1272         struct zone *zone;
1273         unsigned long first_init_pfn = pgdat->first_deferred_pfn;
1274         const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
1275 
1276         if (first_init_pfn == ULONG_MAX) {
1277                 pgdat_init_report_one_done();
1278                 return 0;
1279         }
1280 
1281         /* Bind memory initialisation thread to a local node if possible */
1282         if (!cpumask_empty(cpumask))
1283                 set_cpus_allowed_ptr(current, cpumask);
1284 
1285         /* Sanity check boundaries */
1286         BUG_ON(pgdat->first_deferred_pfn < pgdat->node_start_pfn);
1287         BUG_ON(pgdat->first_deferred_pfn > pgdat_end_pfn(pgdat));
1288         pgdat->first_deferred_pfn = ULONG_MAX;
1289 
1290         /* Only the highest zone is deferred so find it */
1291         for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1292                 zone = pgdat->node_zones + zid;
1293                 if (first_init_pfn < zone_end_pfn(zone))
1294                         break;
1295         }
1296 
1297         for_each_mem_pfn_range(i, nid, &walk_start, &walk_end, NULL) {
1298                 unsigned long pfn, end_pfn;
1299                 struct page *page = NULL;
1300                 struct page *free_base_page = NULL;
1301                 unsigned long free_base_pfn = 0;
1302                 int nr_to_free = 0;
1303 
1304                 end_pfn = min(walk_end, zone_end_pfn(zone));
1305                 pfn = first_init_pfn;
1306                 if (pfn < walk_start)
1307                         pfn = walk_start;
1308                 if (pfn < zone->zone_start_pfn)
1309                         pfn = zone->zone_start_pfn;
1310 
1311                 for (; pfn < end_pfn; pfn++) {
1312                         if (!pfn_valid_within(pfn))
1313                                 goto free_range;
1314 
1315                         /*
1316                          * Ensure pfn_valid is checked every
1317                          * MAX_ORDER_NR_PAGES for memory holes
1318                          */
1319                         if ((pfn & (MAX_ORDER_NR_PAGES - 1)) == 0) {
1320                                 if (!pfn_valid(pfn)) {
1321                                         page = NULL;
1322                                         goto free_range;
1323                                 }
1324                         }
1325 
1326                         if (!meminit_pfn_in_nid(pfn, nid, &nid_init_state)) {
1327                                 page = NULL;
1328                                 goto free_range;
1329                         }
1330 
1331                         /* Minimise pfn page lookups and scheduler checks */
1332                         if (page && (pfn & (MAX_ORDER_NR_PAGES - 1)) != 0) {
1333                                 page++;
1334                         } else {
1335                                 nr_pages += nr_to_free;
1336                                 deferred_free_range(free_base_page,
1337                                                 free_base_pfn, nr_to_free);
1338                                 free_base_page = NULL;
1339                                 free_base_pfn = nr_to_free = 0;
1340 
1341                                 page = pfn_to_page(pfn);
1342                                 cond_resched();
1343                         }
1344 
1345                         if (page->flags) {
1346                                 VM_BUG_ON(page_zone(page) != zone);
1347                                 goto free_range;
1348                         }
1349 
1350                         __init_single_page(page, pfn, zid, nid);
1351                         if (!free_base_page) {
1352                                 free_base_page = page;
1353                                 free_base_pfn = pfn;
1354                                 nr_to_free = 0;
1355                         }
1356                         nr_to_free++;
1357 
1358                         /* Where possible, batch up pages for a single free */
1359                         continue;
1360 free_range:
1361                         /* Free the current block of pages to allocator */
1362                         nr_pages += nr_to_free;
1363                         deferred_free_range(free_base_page, free_base_pfn,
1364                                                                 nr_to_free);
1365                         free_base_page = NULL;
1366                         free_base_pfn = nr_to_free = 0;
1367                 }
1368 
1369                 first_init_pfn = max(end_pfn, first_init_pfn);
1370         }
1371 
1372         /* Sanity check that the next zone really is unpopulated */
1373         WARN_ON(++zid < MAX_NR_ZONES && populated_zone(++zone));
1374 
1375         pr_info("node %d initialised, %lu pages in %ums\n", nid, nr_pages,
1376                                         jiffies_to_msecs(jiffies - start));
1377 
1378         pgdat_init_report_one_done();
1379         return 0;
1380 }
1381 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
1382 
1383 void __init page_alloc_init_late(void)
1384 {
1385         struct zone *zone;
1386 
1387 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1388         int nid;
1389 
1390         /* There will be num_node_state(N_MEMORY) threads */
1391         atomic_set(&pgdat_init_n_undone, num_node_state(N_MEMORY));
1392         for_each_node_state(nid, N_MEMORY) {
1393                 kthread_run(deferred_init_memmap, NODE_DATA(nid), "pgdatinit%d", nid);
1394         }
1395 
1396         /* Block until all are initialised */
1397         wait_for_completion(&pgdat_init_all_done_comp);
1398 
1399         /* Reinit limits that are based on free pages after the kernel is up */
1400         files_maxfiles_init();
1401 #endif
1402 
1403         for_each_populated_zone(zone)
1404                 set_zone_contiguous(zone);
1405 }
1406 
1407 #ifdef CONFIG_CMA
1408 /* Free whole pageblock and set its migration type to MIGRATE_CMA. */
1409 void __init init_cma_reserved_pageblock(struct page *page)
1410 {
1411         unsigned i = pageblock_nr_pages;
1412         struct page *p = page;
1413 
1414         do {
1415                 __ClearPageReserved(p);
1416                 set_page_count(p, 0);
1417         } while (++p, --i);
1418 
1419         set_pageblock_migratetype(page, MIGRATE_CMA);
1420 
1421         if (pageblock_order >= MAX_ORDER) {
1422                 i = pageblock_nr_pages;
1423                 p = page;
1424                 do {
1425                         set_page_refcounted(p);
1426                         __free_pages(p, MAX_ORDER - 1);
1427                         p += MAX_ORDER_NR_PAGES;
1428                 } while (i -= MAX_ORDER_NR_PAGES);
1429         } else {
1430                 set_page_refcounted(page);
1431                 __free_pages(page, pageblock_order);
1432         }
1433 
1434         adjust_managed_page_count(page, pageblock_nr_pages);
1435 }
1436 #endif
1437 
1438 /*
1439  * The order of subdivision here is critical for the IO subsystem.
1440  * Please do not alter this order without good reasons and regression
1441  * testing. Specifically, as large blocks of memory are subdivided,
1442  * the order in which smaller blocks are delivered depends on the order
1443  * they're subdivided in this function. This is the primary factor
1444  * influencing the order in which pages are delivered to the IO
1445  * subsystem according to empirical testing, and this is also justified
1446  * by considering the behavior of a buddy system containing a single
1447  * large block of memory acted on by a series of small allocations.
1448  * This behavior is a critical factor in sglist merging's success.
1449  *
1450  * -- nyc
1451  */
1452 static inline void expand(struct zone *zone, struct page *page,
1453         int low, int high, struct free_area *area,
1454         int migratetype)
1455 {
1456         unsigned long size = 1 << high;
1457 
1458         while (high > low) {
1459                 area--;
1460                 high--;
1461                 size >>= 1;
1462                 VM_BUG_ON_PAGE(bad_range(zone, &page[size]), &page[size]);
1463 
1464                 if (IS_ENABLED(CONFIG_DEBUG_PAGEALLOC) &&
1465                         debug_guardpage_enabled() &&
1466                         high < debug_guardpage_minorder()) {
1467                         /*
1468                          * Mark as guard pages (or page), that will allow to
1469                          * merge back to allocator when buddy will be freed.
1470                          * Corresponding page table entries will not be touched,
1471                          * pages will stay not present in virtual address space
1472                          */
1473                         set_page_guard(zone, &page[size], high, migratetype);
1474                         continue;
1475                 }
1476                 list_add(&page[size].lru, &area->free_list[migratetype]);
1477                 area->nr_free++;
1478                 set_page_order(&page[size], high);
1479         }
1480 }
1481 
1482 /*
1483  * This page is about to be returned from the page allocator
1484  */
1485 static inline int check_new_page(struct page *page)
1486 {
1487         const char *bad_reason = NULL;
1488         unsigned long bad_flags = 0;
1489 
1490         if (unlikely(atomic_read(&page->_mapcount) != -1))
1491                 bad_reason = "nonzero mapcount";
1492         if (unlikely(page->mapping != NULL))
1493                 bad_reason = "non-NULL mapping";
1494         if (unlikely(page_ref_count(page) != 0))
1495                 bad_reason = "nonzero _count";
1496         if (unlikely(page->flags & __PG_HWPOISON)) {
1497                 bad_reason = "HWPoisoned (hardware-corrupted)";
1498                 bad_flags = __PG_HWPOISON;
1499         }
1500         if (unlikely(page->flags & PAGE_FLAGS_CHECK_AT_PREP)) {
1501                 bad_reason = "PAGE_FLAGS_CHECK_AT_PREP flag set";
1502                 bad_flags = PAGE_FLAGS_CHECK_AT_PREP;
1503         }
1504 #ifdef CONFIG_MEMCG
1505         if (unlikely(page->mem_cgroup))
1506                 bad_reason = "page still charged to cgroup";
1507 #endif
1508         if (unlikely(bad_reason)) {
1509                 bad_page(page, bad_reason, bad_flags);
1510                 return 1;
1511         }
1512         return 0;
1513 }
1514 
1515 static inline bool free_pages_prezeroed(bool poisoned)
1516 {
1517         return IS_ENABLED(CONFIG_PAGE_POISONING_ZERO) &&
1518                 page_poisoning_enabled() && poisoned;
1519 }
1520 
1521 static int prep_new_page(struct page *page, unsigned int order, gfp_t gfp_flags,
1522                                                                 int alloc_flags)
1523 {
1524         int i;
1525         bool poisoned = true;
1526 
1527         for (i = 0; i < (1 << order); i++) {
1528                 struct page *p = page + i;
1529                 if (unlikely(check_new_page(p)))
1530                         return 1;
1531                 if (poisoned)
1532                         poisoned &= page_is_poisoned(p);
1533         }
1534 
1535         set_page_private(page, 0);
1536         set_page_refcounted(page);
1537 
1538         arch_alloc_page(page, order);
1539         kernel_map_pages(page, 1 << order, 1);
1540         kernel_poison_pages(page, 1 << order, 1);
1541         kasan_alloc_pages(page, order);
1542 
1543         if (!free_pages_prezeroed(poisoned) && (gfp_flags & __GFP_ZERO))
1544                 for (i = 0; i < (1 << order); i++)
1545                         clear_highpage(page + i);
1546 
1547         if (order && (gfp_flags & __GFP_COMP))
1548                 prep_compound_page(page, order);
1549 
1550         set_page_owner(page, order, gfp_flags);
1551 
1552         /*
1553          * page is set pfmemalloc when ALLOC_NO_WATERMARKS was necessary to
1554          * allocate the page. The expectation is that the caller is taking
1555          * steps that will free more memory. The caller should avoid the page
1556          * being used for !PFMEMALLOC purposes.
1557          */
1558         if (alloc_flags & ALLOC_NO_WATERMARKS)
1559                 set_page_pfmemalloc(page);
1560         else
1561                 clear_page_pfmemalloc(page);
1562 
1563         return 0;
1564 }
1565 
1566 /*
1567  * Go through the free lists for the given migratetype and remove
1568  * the smallest available page from the freelists
1569  */
1570 static inline
1571 struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
1572                                                 int migratetype)
1573 {
1574         unsigned int current_order;
1575         struct free_area *area;
1576         struct page *page;
1577 
1578         /* Find a page of the appropriate size in the preferred list */
1579         for (current_order = order; current_order < MAX_ORDER; ++current_order) {
1580                 area = &(zone->free_area[current_order]);
1581                 page = list_first_entry_or_null(&area->free_list[migratetype],
1582                                                         struct page, lru);
1583                 if (!page)
1584                         continue;
1585                 list_del(&page->lru);
1586                 rmv_page_order(page);
1587                 area->nr_free--;
1588                 expand(zone, page, order, current_order, area, migratetype);
1589                 set_pcppage_migratetype(page, migratetype);
1590                 return page;
1591         }
1592 
1593         return NULL;
1594 }
1595 
1596 
1597 /*
1598  * This array describes the order lists are fallen back to when
1599  * the free lists for the desirable migrate type are depleted
1600  */
1601 static int fallbacks[MIGRATE_TYPES][4] = {
1602         [MIGRATE_UNMOVABLE]   = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE,   MIGRATE_TYPES },
1603         [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE,   MIGRATE_MOVABLE,   MIGRATE_TYPES },
1604         [MIGRATE_MOVABLE]     = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_TYPES },
1605 #ifdef CONFIG_CMA
1606         [MIGRATE_CMA]         = { MIGRATE_TYPES }, /* Never used */
1607 #endif
1608 #ifdef CONFIG_MEMORY_ISOLATION
1609         [MIGRATE_ISOLATE]     = { MIGRATE_TYPES }, /* Never used */
1610 #endif
1611 };
1612 
1613 #ifdef CONFIG_CMA
1614 static struct page *__rmqueue_cma_fallback(struct zone *zone,
1615                                         unsigned int order)
1616 {
1617         return __rmqueue_smallest(zone, order, MIGRATE_CMA);
1618 }
1619 #else
1620 static inline struct page *__rmqueue_cma_fallback(struct zone *zone,
1621                                         unsigned int order) { return NULL; }
1622 #endif
1623 
1624 /*
1625  * Move the free pages in a range to the free lists of the requested type.
1626  * Note that start_page and end_pages are not aligned on a pageblock
1627  * boundary. If alignment is required, use move_freepages_block()
1628  */
1629 int move_freepages(struct zone *zone,
1630                           struct page *start_page, struct page *end_page,
1631                           int migratetype)
1632 {
1633         struct page *page;
1634         unsigned int order;
1635         int pages_moved = 0;
1636 
1637 #ifndef CONFIG_HOLES_IN_ZONE
1638         /*
1639          * page_zone is not safe to call in this context when
1640          * CONFIG_HOLES_IN_ZONE is set. This bug check is probably redundant
1641          * anyway as we check zone boundaries in move_freepages_block().
1642          * Remove at a later date when no bug reports exist related to
1643          * grouping pages by mobility
1644          */
1645         VM_BUG_ON(page_zone(start_page) != page_zone(end_page));
1646 #endif
1647 
1648         for (page = start_page; page <= end_page;) {
1649                 /* Make sure we are not inadvertently changing nodes */
1650                 VM_BUG_ON_PAGE(page_to_nid(page) != zone_to_nid(zone), page);
1651 
1652                 if (!pfn_valid_within(page_to_pfn(page))) {
1653                         page++;
1654                         continue;
1655                 }
1656 
1657                 if (!PageBuddy(page)) {
1658                         page++;
1659                         continue;
1660                 }
1661 
1662                 order = page_order(page);
1663                 list_move(&page->lru,
1664                           &zone->free_area[order].free_list[migratetype]);
1665                 page += 1 << order;
1666                 pages_moved += 1 << order;
1667         }
1668 
1669         return pages_moved;
1670 }
1671 
1672 int move_freepages_block(struct zone *zone, struct page *page,
1673                                 int migratetype)
1674 {
1675         unsigned long start_pfn, end_pfn;
1676         struct page *start_page, *end_page;
1677 
1678         start_pfn = page_to_pfn(page);
1679         start_pfn = start_pfn & ~(pageblock_nr_pages-1);
1680         start_page = pfn_to_page(start_pfn);
1681         end_page = start_page + pageblock_nr_pages - 1;
1682         end_pfn = start_pfn + pageblock_nr_pages - 1;
1683 
1684         /* Do not cross zone boundaries */
1685         if (!zone_spans_pfn(zone, start_pfn))
1686                 start_page = page;
1687         if (!zone_spans_pfn(zone, end_pfn))
1688                 return 0;
1689 
1690         return move_freepages(zone, start_page, end_page, migratetype);
1691 }
1692 
1693 static void change_pageblock_range(struct page *pageblock_page,
1694                                         int start_order, int migratetype)
1695 {
1696         int nr_pageblocks = 1 << (start_order - pageblock_order);
1697 
1698         while (nr_pageblocks--) {
1699                 set_pageblock_migratetype(pageblock_page, migratetype);
1700                 pageblock_page += pageblock_nr_pages;
1701         }
1702 }
1703 
1704 /*
1705  * When we are falling back to another migratetype during allocation, try to
1706  * steal extra free pages from the same pageblocks to satisfy further
1707  * allocations, instead of polluting multiple pageblocks.
1708  *
1709  * If we are stealing a relatively large buddy page, it is likely there will
1710  * be more free pages in the pageblock, so try to steal them all. For
1711  * reclaimable and unmovable allocations, we steal regardless of page size,
1712  * as fragmentation caused by those allocations polluting movable pageblocks
1713  * is worse than movable allocations stealing from unmovable and reclaimable
1714  * pageblocks.
1715  */
1716 static bool can_steal_fallback(unsigned int order, int start_mt)
1717 {
1718         /*
1719          * Leaving this order check is intended, although there is
1720          * relaxed order check in next check. The reason is that
1721          * we can actually steal whole pageblock if this condition met,
1722          * but, below check doesn't guarantee it and that is just heuristic
1723          * so could be changed anytime.
1724          */
1725         if (order >= pageblock_order)
1726                 return true;
1727 
1728         if (order >= pageblock_order / 2 ||
1729                 start_mt == MIGRATE_RECLAIMABLE ||
1730                 start_mt == MIGRATE_UNMOVABLE ||
1731                 page_group_by_mobility_disabled)
1732                 return true;
1733 
1734         return false;
1735 }
1736 
1737 /*
1738  * This function implements actual steal behaviour. If order is large enough,
1739  * we can steal whole pageblock. If not, we first move freepages in this
1740  * pageblock and check whether half of pages are moved or not. If half of
1741  * pages are moved, we can change migratetype of pageblock and permanently
1742  * use it's pages as requested migratetype in the future.
1743  */
1744 static void steal_suitable_fallback(struct zone *zone, struct page *page,
1745                                                           int start_type)
1746 {
1747         unsigned int current_order = page_order(page);
1748         int pages;
1749 
1750         /* Take ownership for orders >= pageblock_order */
1751         if (current_order >= pageblock_order) {
1752                 change_pageblock_range(page, current_order, start_type);
1753                 return;
1754         }
1755 
1756         pages = move_freepages_block(zone, page, start_type);
1757 
1758         /* Claim the whole block if over half of it is free */
1759         if (pages >= (1 << (pageblock_order-1)) ||
1760                         page_group_by_mobility_disabled)
1761                 set_pageblock_migratetype(page, start_type);
1762 }
1763 
1764 /*
1765  * Check whether there is a suitable fallback freepage with requested order.
1766  * If only_stealable is true, this function returns fallback_mt only if
1767  * we can steal other freepages all together. This would help to reduce
1768  * fragmentation due to mixed migratetype pages in one pageblock.
1769  */
1770 int find_suitable_fallback(struct free_area *area, unsigned int order,
1771                         int migratetype, bool only_stealable, bool *can_steal)
1772 {
1773         int i;
1774         int fallback_mt;
1775 
1776         if (area->nr_free == 0)
1777                 return -1;
1778 
1779         *can_steal = false;
1780         for (i = 0;; i++) {
1781                 fallback_mt = fallbacks[migratetype][i];
1782                 if (fallback_mt == MIGRATE_TYPES)
1783                         break;
1784 
1785                 if (list_empty(&area->free_list[fallback_mt]))
1786                         continue;
1787 
1788                 if (can_steal_fallback(order, migratetype))
1789                         *can_steal = true;
1790 
1791                 if (!only_stealable)
1792                         return fallback_mt;
1793 
1794                 if (*can_steal)
1795                         return fallback_mt;
1796         }
1797 
1798         return -1;
1799 }
1800 
1801 /*
1802  * Reserve a pageblock for exclusive use of high-order atomic allocations if
1803  * there are no empty page blocks that contain a page with a suitable order
1804  */
1805 static void reserve_highatomic_pageblock(struct page *page, struct zone *zone,
1806                                 unsigned int alloc_order)
1807 {
1808         int mt;
1809         unsigned long max_managed, flags;
1810 
1811         /*
1812          * Limit the number reserved to 1 pageblock or roughly 1% of a zone.
1813          * Check is race-prone but harmless.
1814          */
1815         max_managed = (zone->managed_pages / 100) + pageblock_nr_pages;
1816         if (zone->nr_reserved_highatomic >= max_managed)
1817                 return;
1818 
1819         spin_lock_irqsave(&zone->lock, flags);
1820 
1821         /* Recheck the nr_reserved_highatomic limit under the lock */
1822         if (zone->nr_reserved_highatomic >= max_managed)
1823                 goto out_unlock;
1824 
1825         /* Yoink! */
1826         mt = get_pageblock_migratetype(page);
1827         if (mt != MIGRATE_HIGHATOMIC &&
1828                         !is_migrate_isolate(mt) && !is_migrate_cma(mt)) {
1829                 zone->nr_reserved_highatomic += pageblock_nr_pages;
1830                 set_pageblock_migratetype(page, MIGRATE_HIGHATOMIC);
1831                 move_freepages_block(zone, page, MIGRATE_HIGHATOMIC);
1832         }
1833 
1834 out_unlock:
1835         spin_unlock_irqrestore(&zone->lock, flags);
1836 }
1837 
1838 /*
1839  * Used when an allocation is about to fail under memory pressure. This
1840  * potentially hurts the reliability of high-order allocations when under
1841  * intense memory pressure but failed atomic allocations should be easier
1842  * to recover from than an OOM.
1843  */
1844 static void unreserve_highatomic_pageblock(const struct alloc_context *ac)
1845 {
1846         struct zonelist *zonelist = ac->zonelist;
1847         unsigned long flags;
1848         struct zoneref *z;
1849         struct zone *zone;
1850         struct page *page;
1851         int order;
1852 
1853         for_each_zone_zonelist_nodemask(zone, z, zonelist, ac->high_zoneidx,
1854                                                                 ac->nodemask) {
1855                 /* Preserve at least one pageblock */
1856                 if (zone->nr_reserved_highatomic <= pageblock_nr_pages)
1857                         continue;
1858 
1859                 spin_lock_irqsave(&zone->lock, flags);
1860                 for (order = 0; order < MAX_ORDER; order++) {
1861                         struct free_area *area = &(zone->free_area[order]);
1862 
1863                         page = list_first_entry_or_null(
1864                                         &area->free_list[MIGRATE_HIGHATOMIC],
1865                                         struct page, lru);
1866                         if (!page)
1867                                 continue;
1868 
1869                         /*
1870                          * It should never happen but changes to locking could
1871                          * inadvertently allow a per-cpu drain to add pages
1872                          * to MIGRATE_HIGHATOMIC while unreserving so be safe
1873                          * and watch for underflows.
1874                          */
1875                         zone->nr_reserved_highatomic -= min(pageblock_nr_pages,
1876                                 zone->nr_reserved_highatomic);
1877 
1878                         /*
1879                          * Convert to ac->migratetype and avoid the normal
1880                          * pageblock stealing heuristics. Minimally, the caller
1881                          * is doing the work and needs the pages. More
1882                          * importantly, if the block was always converted to
1883                          * MIGRATE_UNMOVABLE or another type then the number
1884                          * of pageblocks that cannot be completely freed
1885                          * may increase.
1886                          */
1887                         set_pageblock_migratetype(page, ac->migratetype);
1888                         move_freepages_block(zone, page, ac->migratetype);
1889                         spin_unlock_irqrestore(&zone->lock, flags);
1890                         return;
1891                 }
1892                 spin_unlock_irqrestore(&zone->lock, flags);
1893         }
1894 }
1895 
1896 /* Remove an element from the buddy allocator from the fallback list */
1897 static inline struct page *
1898 __rmqueue_fallback(struct zone *zone, unsigned int order, int start_migratetype)
1899 {
1900         struct free_area *area;
1901         unsigned int current_order;
1902         struct page *page;
1903         int fallback_mt;
1904         bool can_steal;
1905 
1906         /* Find the largest possible block of pages in the other list */
1907         for (current_order = MAX_ORDER-1;
1908                                 current_order >= order && current_order <= MAX_ORDER-1;
1909                                 --current_order) {
1910                 area = &(zone->free_area[current_order]);
1911                 fallback_mt = find_suitable_fallback(area, current_order,
1912                                 start_migratetype, false, &can_steal);
1913                 if (fallback_mt == -1)
1914                         continue;
1915 
1916                 page = list_first_entry(&area->free_list[fallback_mt],
1917                                                 struct page, lru);
1918                 if (can_steal)
1919                         steal_suitable_fallback(zone, page, start_migratetype);
1920 
1921                 /* Remove the page from the freelists */
1922                 area->nr_free--;
1923                 list_del(&page->lru);
1924                 rmv_page_order(page);
1925 
1926                 expand(zone, page, order, current_order, area,
1927                                         start_migratetype);
1928                 /*
1929                  * The pcppage_migratetype may differ from pageblock's
1930                  * migratetype depending on the decisions in
1931                  * find_suitable_fallback(). This is OK as long as it does not
1932                  * differ for MIGRATE_CMA pageblocks. Those can be used as
1933                  * fallback only via special __rmqueue_cma_fallback() function
1934                  */
1935                 set_pcppage_migratetype(page, start_migratetype);
1936 
1937                 trace_mm_page_alloc_extfrag(page, order, current_order,
1938                         start_migratetype, fallback_mt);
1939 
1940                 return page;
1941         }
1942 
1943         return NULL;
1944 }
1945 
1946 /*
1947  * Do the hard work of removing an element from the buddy allocator.
1948  * Call me with the zone->lock already held.
1949  */
1950 static struct page *__rmqueue(struct zone *zone, unsigned int order,
1951                                 int migratetype)
1952 {
1953         struct page *page;
1954 
1955         page = __rmqueue_smallest(zone, order, migratetype);
1956         if (unlikely(!page)) {
1957                 if (migratetype == MIGRATE_MOVABLE)
1958                         page = __rmqueue_cma_fallback(zone, order);
1959 
1960                 if (!page)
1961                         page = __rmqueue_fallback(zone, order, migratetype);
1962         }
1963 
1964         trace_mm_page_alloc_zone_locked(page, order, migratetype);
1965         return page;
1966 }
1967 
1968 /*
1969  * Obtain a specified number of elements from the buddy allocator, all under
1970  * a single hold of the lock, for efficiency.  Add them to the supplied list.
1971  * Returns the number of new pages which were placed at *list.
1972  */
1973 static int rmqueue_bulk(struct zone *zone, unsigned int order,
1974                         unsigned long count, struct list_head *list,
1975                         int migratetype, bool cold)
1976 {
1977         int i;
1978 
1979         spin_lock(&zone->lock);
1980         for (i = 0; i < count; ++i) {
1981                 struct page *page = __rmqueue(zone, order, migratetype);
1982                 if (unlikely(page == NULL))
1983                         break;
1984 
1985                 /*
1986                  * Split buddy pages returned by expand() are received here
1987                  * in physical page order. The page is added to the callers and
1988                  * list and the list head then moves forward. From the callers
1989                  * perspective, the linked list is ordered by page number in
1990                  * some conditions. This is useful for IO devices that can
1991                  * merge IO requests if the physical pages are ordered
1992                  * properly.
1993                  */
1994                 if (likely(!cold))
1995                         list_add(&page->lru, list);
1996                 else
1997                         list_add_tail(&page->lru, list);
1998                 list = &page->lru;
1999                 if (is_migrate_cma(get_pcppage_migratetype(page)))
2000                         __mod_zone_page_state(zone, NR_FREE_CMA_PAGES,
2001                                               -(1 << order));
2002         }
2003         __mod_zone_page_state(zone, NR_FREE_PAGES, -(i << order));
2004         spin_unlock(&zone->lock);
2005         return i;
2006 }
2007 
2008 #ifdef CONFIG_NUMA
2009 /*
2010  * Called from the vmstat counter updater to drain pagesets of this
2011  * currently executing processor on remote nodes after they have
2012  * expired.
2013  *
2014  * Note that this function must be called with the thread pinned to
2015  * a single processor.
2016  */
2017 void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp)
2018 {
2019         unsigned long flags;
2020         int to_drain, batch;
2021 
2022         local_irq_save(flags);
2023         batch = READ_ONCE(pcp->batch);
2024         to_drain = min(pcp->count, batch);
2025         if (to_drain > 0) {
2026                 free_pcppages_bulk(zone, to_drain, pcp);
2027                 pcp->count -= to_drain;
2028         }
2029         local_irq_restore(flags);
2030 }
2031 #endif
2032 
2033 /*
2034  * Drain pcplists of the indicated processor and zone.
2035  *
2036  * The processor must either be the current processor and the
2037  * thread pinned to the current processor or a processor that
2038  * is not online.
2039  */
2040 static void drain_pages_zone(unsigned int cpu, struct zone *zone)
2041 {
2042         unsigned long flags;
2043         struct per_cpu_pageset *pset;
2044         struct per_cpu_pages *pcp;
2045 
2046         local_irq_save(flags);
2047         pset = per_cpu_ptr(zone->pageset, cpu);
2048 
2049         pcp = &pset->pcp;
2050         if (pcp->count) {
2051                 free_pcppages_bulk(zone, pcp->count, pcp);
2052                 pcp->count = 0;
2053         }
2054         local_irq_restore(flags);
2055 }
2056 
2057 /*
2058  * Drain pcplists of all zones on the indicated processor.
2059  *
2060  * The processor must either be the current processor and the
2061  * thread pinned to the current processor or a processor that
2062  * is not online.
2063  */
2064 static void drain_pages(unsigned int cpu)
2065 {
2066         struct zone *zone;
2067 
2068         for_each_populated_zone(zone) {
2069                 drain_pages_zone(cpu, zone);
2070         }
2071 }
2072 
2073 /*
2074  * Spill all of this CPU's per-cpu pages back into the buddy allocator.
2075  *
2076  * The CPU has to be pinned. When zone parameter is non-NULL, spill just
2077  * the single zone's pages.
2078  */
2079 void drain_local_pages(struct zone *zone)
2080 {
2081         int cpu = smp_processor_id();
2082 
2083         if (zone)
2084                 drain_pages_zone(cpu, zone);
2085         else
2086                 drain_pages(cpu);
2087 }
2088 
2089 /*
2090  * Spill all the per-cpu pages from all CPUs back into the buddy allocator.
2091  *
2092  * When zone parameter is non-NULL, spill just the single zone's pages.
2093  *
2094  * Note that this code is protected against sending an IPI to an offline
2095  * CPU but does not guarantee sending an IPI to newly hotplugged CPUs:
2096  * on_each_cpu_mask() blocks hotplug and won't talk to offlined CPUs but
2097  * nothing keeps CPUs from showing up after we populated the cpumask and
2098  * before the call to on_each_cpu_mask().
2099  */
2100 void drain_all_pages(struct zone *zone)
2101 {
2102         int cpu;
2103 
2104         /*
2105          * Allocate in the BSS so we wont require allocation in
2106          * direct reclaim path for CONFIG_CPUMASK_OFFSTACK=y
2107          */
2108         static cpumask_t cpus_with_pcps;
2109 
2110         /*
2111          * We don't care about racing with CPU hotplug event
2112          * as offline notification will cause the notified
2113          * cpu to drain that CPU pcps and on_each_cpu_mask
2114          * disables preemption as part of its processing
2115          */
2116         for_each_online_cpu(cpu) {
2117                 struct per_cpu_pageset *pcp;
2118                 struct zone *z;
2119                 bool has_pcps = false;
2120 
2121                 if (zone) {
2122                         pcp = per_cpu_ptr(zone->pageset, cpu);
2123                         if (pcp->pcp.count)
2124                                 has_pcps = true;
2125                 } else {
2126                         for_each_populated_zone(z) {
2127                                 pcp = per_cpu_ptr(z->pageset, cpu);
2128                                 if (pcp->pcp.count) {
2129                                         has_pcps = true;
2130                                         break;
2131                                 }
2132                         }
2133                 }
2134 
2135                 if (has_pcps)
2136                         cpumask_set_cpu(cpu, &cpus_with_pcps);
2137                 else
2138                         cpumask_clear_cpu(cpu, &cpus_with_pcps);
2139         }
2140         on_each_cpu_mask(&cpus_with_pcps, (smp_call_func_t) drain_local_pages,
2141                                                                 zone, 1);
2142 }
2143 
2144 #ifdef CONFIG_HIBERNATION
2145 
2146 void mark_free_pages(struct zone *zone)
2147 {
2148         unsigned long pfn, max_zone_pfn;
2149         unsigned long flags;
2150         unsigned int order, t;
2151         struct page *page;
2152 
2153         if (zone_is_empty(zone))
2154                 return;
2155 
2156         spin_lock_irqsave(&zone->lock, flags);
2157 
2158         max_zone_pfn = zone_end_pfn(zone);
2159         for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
2160                 if (pfn_valid(pfn)) {
2161                         page = pfn_to_page(pfn);
2162                         if (!swsusp_page_is_forbidden(page))
2163                                 swsusp_unset_page_free(page);
2164                 }
2165 
2166         for_each_migratetype_order(order, t) {
2167                 list_for_each_entry(page,
2168                                 &zone->free_area[order].free_list[t], lru) {
2169                         unsigned long i;
2170 
2171                         pfn = page_to_pfn(page);
2172                         for (i = 0; i < (1UL << order); i++)
2173                                 swsusp_set_page_free(pfn_to_page(pfn + i));
2174                 }
2175         }
2176         spin_unlock_irqrestore(&zone->lock, flags);
2177 }
2178 #endif /* CONFIG_PM */
2179 
2180 /*
2181  * Free a 0-order page
2182  * cold == true ? free a cold page : free a hot page
2183  */
2184 void free_hot_cold_page(struct page *page, bool cold)
2185 {
2186         struct zone *zone = page_zone(page);
2187         struct per_cpu_pages *pcp;
2188         unsigned long flags;
2189         unsigned long pfn = page_to_pfn(page);
2190         int migratetype;
2191 
2192         if (!free_pages_prepare(page, 0))
2193                 return;
2194 
2195         migratetype = get_pfnblock_migratetype(page, pfn);
2196         set_pcppage_migratetype(page, migratetype);
2197         local_irq_save(flags);
2198         __count_vm_event(PGFREE);
2199 
2200         /*
2201          * We only track unmovable, reclaimable and movable on pcp lists.
2202          * Free ISOLATE pages back to the allocator because they are being
2203          * offlined but treat RESERVE as movable pages so we can get those
2204          * areas back if necessary. Otherwise, we may have to free
2205          * excessively into the page allocator
2206          */
2207         if (migratetype >= MIGRATE_PCPTYPES) {
2208                 if (unlikely(is_migrate_isolate(migratetype))) {
2209                         free_one_page(zone, page, pfn, 0, migratetype);
2210                         goto out;
2211                 }
2212                 migratetype = MIGRATE_MOVABLE;
2213         }
2214 
2215         pcp = &this_cpu_ptr(zone->pageset)->pcp;
2216         if (!cold)
2217                 list_add(&page->lru, &pcp->lists[migratetype]);
2218         else
2219                 list_add_tail(&page->lru, &pcp->lists[migratetype]);
2220         pcp->count++;
2221         if (pcp->count >= pcp->high) {
2222                 unsigned long batch = READ_ONCE(pcp->batch);
2223                 free_pcppages_bulk(zone, batch, pcp);
2224                 pcp->count -= batch;
2225         }
2226 
2227 out:
2228         local_irq_restore(flags);
2229 }
2230 
2231 /*
2232  * Free a list of 0-order pages
2233  */
2234 void free_hot_cold_page_list(struct list_head *list, bool cold)
2235 {
2236         struct page *page, *next;
2237 
2238         list_for_each_entry_safe(page, next, list, lru) {
2239                 trace_mm_page_free_batched(page, cold);
2240                 free_hot_cold_page(page, cold);
2241         }
2242 }
2243 
2244 /*
2245  * split_page takes a non-compound higher-order page, and splits it into
2246  * n (1<<order) sub-pages: page[0..n]
2247  * Each sub-page must be freed individually.
2248  *
2249  * Note: this is probably too low level an operation for use in drivers.
2250  * Please consult with lkml before using this in your driver.
2251  */
2252 void split_page(struct page *page, unsigned int order)
2253 {
2254         int i;
2255         gfp_t gfp_mask;
2256 
2257         VM_BUG_ON_PAGE(PageCompound(page), page);
2258         VM_BUG_ON_PAGE(!page_count(page), page);
2259 
2260 #ifdef CONFIG_KMEMCHECK
2261         /*
2262          * Split shadow pages too, because free(page[0]) would
2263          * otherwise free the whole shadow.
2264          */
2265         if (kmemcheck_page_is_tracked(page))
2266                 split_page(virt_to_page(page[0].shadow), order);
2267 #endif
2268 
2269         gfp_mask = get_page_owner_gfp(page);
2270         set_page_owner(page, 0, gfp_mask);
2271         for (i = 1; i < (1 << order); i++) {
2272                 set_page_refcounted(page + i);
2273                 set_page_owner(page + i, 0, gfp_mask);
2274         }
2275 }
2276 EXPORT_SYMBOL_GPL(split_page);
2277 
2278 int __isolate_free_page(struct page *page, unsigned int order)
2279 {
2280         unsigned long watermark;
2281         struct zone *zone;
2282         int mt;
2283 
2284         BUG_ON(!PageBuddy(page));
2285 
2286         zone = page_zone(page);
2287         mt = get_pageblock_migratetype(page);
2288 
2289         if (!is_migrate_isolate(mt)) {
2290                 /* Obey watermarks as if the page was being allocated */
2291                 watermark = low_wmark_pages(zone) + (1 << order);
2292                 if (!zone_watermark_ok(zone, 0, watermark, 0, 0))
2293                         return 0;
2294 
2295                 __mod_zone_freepage_state(zone, -(1UL << order), mt);
2296         }
2297 
2298         /* Remove page from free list */
2299         list_del(&page->lru);
2300         zone->free_area[order].nr_free--;
2301         rmv_page_order(page);
2302 
2303         set_page_owner(page, order, __GFP_MOVABLE);
2304 
2305         /* Set the pageblock if the isolated page is at least a pageblock */
2306         if (order >= pageblock_order - 1) {
2307                 struct page *endpage = page + (1 << order) - 1;
2308                 for (; page < endpage; page += pageblock_nr_pages) {
2309                         int mt = get_pageblock_migratetype(page);
2310                         if (!is_migrate_isolate(mt) && !is_migrate_cma(mt))
2311                                 set_pageblock_migratetype(page,
2312                                                           MIGRATE_MOVABLE);
2313                 }
2314         }
2315 
2316 
2317         return 1UL << order;
2318 }
2319 
2320 /*
2321  * Similar to split_page except the page is already free. As this is only
2322  * being used for migration, the migratetype of the block also changes.
2323  * As this is called with interrupts disabled, the caller is responsible
2324  * for calling arch_alloc_page() and kernel_map_page() after interrupts
2325  * are enabled.
2326  *
2327  * Note: this is probably too low level an operation for use in drivers.
2328  * Please consult with lkml before using this in your driver.
2329  */
2330 int split_free_page(struct page *page)
2331 {
2332         unsigned int order;
2333         int nr_pages;
2334 
2335         order = page_order(page);
2336 
2337         nr_pages = __isolate_free_page(page, order);
2338         if (!nr_pages)
2339                 return 0;
2340 
2341         /* Split into individual pages */
2342         set_page_refcounted(page);
2343         split_page(page, order);
2344         return nr_pages;
2345 }
2346 
2347 /*
2348  * Allocate a page from the given zone. Use pcplists for order-0 allocations.
2349  */
2350 static inline
2351 struct page *buffered_rmqueue(struct zone *preferred_zone,
2352                         struct zone *zone, unsigned int order,
2353                         gfp_t gfp_flags, int alloc_flags, int migratetype)
2354 {
2355         unsigned long flags;
2356         struct page *page;
2357         bool cold = ((gfp_flags & __GFP_COLD) != 0);
2358 
2359         if (likely(order == 0)) {
2360                 struct per_cpu_pages *pcp;
2361                 struct list_head *list;
2362 
2363                 local_irq_save(flags);
2364                 pcp = &this_cpu_ptr(zone->pageset)->pcp;
2365                 list = &pcp->lists[migratetype];
2366                 if (list_empty(list)) {
2367                         pcp->count += rmqueue_bulk(zone, 0,
2368                                         pcp->batch, list,
2369                                         migratetype, cold);
2370                         if (unlikely(list_empty(list)))
2371                                 goto failed;
2372                 }
2373 
2374                 if (cold)
2375                         page = list_last_entry(list, struct page, lru);
2376                 else
2377                         page = list_first_entry(list, struct page, lru);
2378 
2379                 list_del(&page->lru);
2380                 pcp->count--;
2381         } else {
2382                 /*
2383                  * We most definitely don't want callers attempting to
2384                  * allocate greater than order-1 page units with __GFP_NOFAIL.
2385                  */
2386                 WARN_ON_ONCE((gfp_flags & __GFP_NOFAIL) && (order > 1));
2387                 spin_lock_irqsave(&zone->lock, flags);
2388 
2389                 page = NULL;
2390                 if (alloc_flags & ALLOC_HARDER) {
2391                         page = __rmqueue_smallest(zone, order, MIGRATE_HIGHATOMIC);
2392                         if (page)
2393                                 trace_mm_page_alloc_zone_locked(page, order, migratetype);
2394                 }
2395                 if (!page)
2396                         page = __rmqueue(zone, order, migratetype);
2397                 spin_unlock(&zone->lock);
2398                 if (!page)
2399                         goto failed;
2400                 __mod_zone_freepage_state(zone, -(1 << order),
2401                                           get_pcppage_migratetype(page));
2402         }
2403 
2404         __mod_zone_page_state(zone, NR_ALLOC_BATCH, -(1 << order));
2405         if (atomic_long_read(&zone->vm_stat[NR_ALLOC_BATCH]) <= 0 &&
2406             !test_bit(ZONE_FAIR_DEPLETED, &zone->flags))
2407                 set_bit(ZONE_FAIR_DEPLETED, &zone->flags);
2408 
2409         __count_zone_vm_events(PGALLOC, zone, 1 << order);
2410         zone_statistics(preferred_zone, zone, gfp_flags);
2411         local_irq_restore(flags);
2412 
2413         VM_BUG_ON_PAGE(bad_range(zone, page), page);
2414         return page;
2415 
2416 failed:
2417         local_irq_restore(flags);
2418         return NULL;
2419 }
2420 
2421 #ifdef CONFIG_FAIL_PAGE_ALLOC
2422 
2423 static struct {
2424         struct fault_attr attr;
2425 
2426         bool ignore_gfp_highmem;
2427         bool ignore_gfp_reclaim;
2428         u32 min_order;
2429 } fail_page_alloc = {
2430         .attr = FAULT_ATTR_INITIALIZER,
2431         .ignore_gfp_reclaim = true,
2432         .ignore_gfp_highmem = true,
2433         .min_order = 1,
2434 };
2435 
2436 static int __init setup_fail_page_alloc(char *str)
2437 {
2438         return setup_fault_attr(&fail_page_alloc.attr, str);
2439 }
2440 __setup("fail_page_alloc=", setup_fail_page_alloc);
2441 
2442 static bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
2443 {
2444         if (order < fail_page_alloc.min_order)
2445                 return false;
2446         if (gfp_mask & __GFP_NOFAIL)
2447                 return false;
2448         if (fail_page_alloc.ignore_gfp_highmem && (gfp_mask & __GFP_HIGHMEM))
2449                 return false;
2450         if (fail_page_alloc.ignore_gfp_reclaim &&
2451                         (gfp_mask & __GFP_DIRECT_RECLAIM))
2452                 return false;
2453 
2454         return should_fail(&fail_page_alloc.attr, 1 << order);
2455 }
2456 
2457 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
2458 
2459 static int __init fail_page_alloc_debugfs(void)
2460 {
2461         umode_t mode = S_IFREG | S_IRUSR | S_IWUSR;
2462         struct dentry *dir;
2463 
2464         dir = fault_create_debugfs_attr("fail_page_alloc", NULL,
2465                                         &fail_page_alloc.attr);
2466         if (IS_ERR(dir))
2467                 return PTR_ERR(dir);
2468 
2469         if (!debugfs_create_bool("ignore-gfp-wait", mode, dir,
2470                                 &fail_page_alloc.ignore_gfp_reclaim))
2471                 goto fail;
2472         if (!debugfs_create_bool("ignore-gfp-highmem", mode, dir,
2473                                 &fail_page_alloc.ignore_gfp_highmem))
2474                 goto fail;
2475         if (!debugfs_create_u32("min-order", mode, dir,
2476                                 &fail_page_alloc.min_order))
2477                 goto fail;
2478 
2479         return 0;
2480 fail:
2481         debugfs_remove_recursive(dir);
2482 
2483         return -ENOMEM;
2484 }
2485 
2486 late_initcall(fail_page_alloc_debugfs);
2487 
2488 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
2489 
2490 #else /* CONFIG_FAIL_PAGE_ALLOC */
2491 
2492 static inline bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
2493 {
2494         return false;
2495 }
2496 
2497 #endif /* CONFIG_FAIL_PAGE_ALLOC */
2498 
2499 /*
2500  * Return true if free base pages are above 'mark'. For high-order checks it
2501  * will return true of the order-0 watermark is reached and there is at least
2502  * one free page of a suitable size. Checking now avoids taking the zone lock
2503  * to check in the allocation paths if no pages are free.
2504  */
2505 static bool __zone_watermark_ok(struct zone *z, unsigned int order,
2506                         unsigned long mark, int classzone_idx, int alloc_flags,
2507                         long free_pages)
2508 {
2509         long min = mark;
2510         int o;
2511         const int alloc_harder = (alloc_flags & ALLOC_HARDER);
2512 
2513         /* free_pages may go negative - that's OK */
2514         free_pages -= (1 << order) - 1;
2515 
2516         if (alloc_flags & ALLOC_HIGH)
2517                 min -= min / 2;
2518 
2519         /*
2520          * If the caller does not have rights to ALLOC_HARDER then subtract
2521          * the high-atomic reserves. This will over-estimate the size of the
2522          * atomic reserve but it avoids a search.
2523          */
2524         if (likely(!alloc_harder))
2525                 free_pages -= z->nr_reserved_highatomic;
2526         else
2527                 min -= min / 4;
2528 
2529 #ifdef CONFIG_CMA
2530         /* If allocation can't use CMA areas don't use free CMA pages */
2531         if (!(alloc_flags & ALLOC_CMA))
2532                 free_pages -= zone_page_state(z, NR_FREE_CMA_PAGES);
2533 #endif
2534 
2535         /*
2536          * Check watermarks for an order-0 allocation request. If these
2537          * are not met, then a high-order request also cannot go ahead
2538          * even if a suitable page happened to be free.
2539          */
2540         if (free_pages <= min + z->lowmem_reserve[classzone_idx])
2541                 return false;
2542 
2543         /* If this is an order-0 request then the watermark is fine */
2544         if (!order)
2545                 return true;
2546 
2547         /* For a high-order request, check at least one suitable page is free */
2548         for (o = order; o < MAX_ORDER; o++) {
2549                 struct free_area *area = &z->free_area[o];
2550                 int mt;
2551 
2552                 if (!area->nr_free)
2553                         continue;
2554 
2555                 if (alloc_harder)
2556                         return true;
2557 
2558                 for (mt = 0; mt < MIGRATE_PCPTYPES; mt++) {
2559                         if (!list_empty(&area->free_list[mt]))
2560                                 return true;
2561                 }
2562 
2563 #ifdef CONFIG_CMA
2564                 if ((alloc_flags & ALLOC_CMA) &&
2565                     !list_empty(&area->free_list[MIGRATE_CMA])) {
2566                         return true;
2567                 }
2568 #endif
2569         }
2570         return false;
2571 }
2572 
2573 bool zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
2574                       int classzone_idx, int alloc_flags)
2575 {
2576         return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
2577                                         zone_page_state(z, NR_FREE_PAGES));
2578 }
2579 
2580 bool zone_watermark_ok_safe(struct zone *z, unsigned int order,
2581                         unsigned long mark, int classzone_idx)
2582 {
2583         long free_pages = zone_page_state(z, NR_FREE_PAGES);
2584 
2585         if (z->percpu_drift_mark && free_pages < z->percpu_drift_mark)
2586                 free_pages = zone_page_state_snapshot(z, NR_FREE_PAGES);
2587 
2588         return __zone_watermark_ok(z, order, mark, classzone_idx, 0,
2589                                                                 free_pages);
2590 }
2591 
2592 #ifdef CONFIG_NUMA
2593 static bool zone_local(struct zone *local_zone, struct zone *zone)
2594 {
2595         return local_zone->node == zone->node;
2596 }
2597 
2598 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
2599 {
2600         return node_distance(zone_to_nid(local_zone), zone_to_nid(zone)) <
2601                                 RECLAIM_DISTANCE;
2602 }
2603 #else   /* CONFIG_NUMA */
2604 static bool zone_local(struct zone *local_zone, struct zone *zone)
2605 {
2606         return true;
2607 }
2608 
2609 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
2610 {
2611         return true;
2612 }
2613 #endif  /* CONFIG_NUMA */
2614 
2615 static void reset_alloc_batches(struct zone *preferred_zone)
2616 {
2617         struct zone *zone = preferred_zone->zone_pgdat->node_zones;
2618 
2619         do {
2620                 mod_zone_page_state(zone, NR_ALLOC_BATCH,
2621                         high_wmark_pages(zone) - low_wmark_pages(zone) -
2622                         atomic_long_read(&zone->vm_stat[NR_ALLOC_BATCH]));
2623                 clear_bit(ZONE_FAIR_DEPLETED, &zone->flags);
2624         } while (zone++ != preferred_zone);
2625 }
2626 
2627 /*
2628  * get_page_from_freelist goes through the zonelist trying to allocate
2629  * a page.
2630  */
2631 static struct page *
2632 get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags,
2633                                                 const struct alloc_context *ac)
2634 {
2635         struct zonelist *zonelist = ac->zonelist;
2636         struct zoneref *z;
2637         struct page *page = NULL;
2638         struct zone *zone;
2639         int nr_fair_skipped = 0;
2640         bool zonelist_rescan;
2641 
2642 zonelist_scan:
2643         zonelist_rescan = false;
2644 
2645         /*
2646          * Scan zonelist, looking for a zone with enough free.
2647          * See also __cpuset_node_allowed() comment in kernel/cpuset.c.
2648          */
2649         for_each_zone_zonelist_nodemask(zone, z, zonelist, ac->high_zoneidx,
2650                                                                 ac->nodemask) {
2651                 unsigned long mark;
2652 
2653                 if (cpusets_enabled() &&
2654                         (alloc_flags & ALLOC_CPUSET) &&
2655                         !cpuset_zone_allowed(zone, gfp_mask))
2656                                 continue;
2657                 /*
2658                  * Distribute pages in proportion to the individual
2659                  * zone size to ensure fair page aging.  The zone a
2660                  * page was allocated in should have no effect on the
2661                  * time the page has in memory before being reclaimed.
2662                  */
2663                 if (alloc_flags & ALLOC_FAIR) {
2664                         if (!zone_local(ac->preferred_zone, zone))
2665                                 break;
2666                         if (test_bit(ZONE_FAIR_DEPLETED, &zone->flags)) {
2667                                 nr_fair_skipped++;
2668                                 continue;
2669                         }
2670                 }
2671                 /*
2672                  * When allocating a page cache page for writing, we
2673                  * want to get it from a zone that is within its dirty
2674                  * limit, such that no single zone holds more than its
2675                  * proportional share of globally allowed dirty pages.
2676                  * The dirty limits take into account the zone's
2677                  * lowmem reserves and high watermark so that kswapd
2678                  * should be able to balance it without having to
2679                  * write pages from its LRU list.
2680                  *
2681                  * This may look like it could increase pressure on
2682                  * lower zones by failing allocations in higher zones
2683                  * before they are full.  But the pages that do spill
2684                  * over are limited as the lower zones are protected
2685                  * by this very same mechanism.  It should not become
2686                  * a practical burden to them.
2687                  *
2688                  * XXX: For now, allow allocations to potentially
2689                  * exceed the per-zone dirty limit in the slowpath
2690                  * (spread_dirty_pages unset) before going into reclaim,
2691                  * which is important when on a NUMA setup the allowed
2692                  * zones are together not big enough to reach the
2693                  * global limit.  The proper fix for these situations
2694                  * will require awareness of zones in the
2695                  * dirty-throttling and the flusher threads.
2696                  */
2697                 if (ac->spread_dirty_pages && !zone_dirty_ok(zone))
2698                         continue;
2699 
2700                 mark = zone->watermark[alloc_flags & ALLOC_WMARK_MASK];
2701                 if (!zone_watermark_ok(zone, order, mark,
2702                                        ac->classzone_idx, alloc_flags)) {
2703                         int ret;
2704 
2705                         /* Checked here to keep the fast path fast */
2706                         BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK);
2707                         if (alloc_flags & ALLOC_NO_WATERMARKS)
2708                                 goto try_this_zone;
2709 
2710                         if (zone_reclaim_mode == 0 ||
2711                             !zone_allows_reclaim(ac->preferred_zone, zone))
2712                                 continue;
2713 
2714                         ret = zone_reclaim(zone, gfp_mask, order);
2715                         switch (ret) {
2716                         case ZONE_RECLAIM_NOSCAN:
2717                                 /* did not scan */
2718                                 continue;
2719                         case ZONE_RECLAIM_FULL:
2720                                 /* scanned but unreclaimable */
2721                                 continue;
2722                         default:
2723                                 /* did we reclaim enough */
2724                                 if (zone_watermark_ok(zone, order, mark,
2725                                                 ac->classzone_idx, alloc_flags))
2726                                         goto try_this_zone;
2727 
2728                                 continue;
2729                         }
2730                 }
2731 
2732 try_this_zone:
2733                 page = buffered_rmqueue(ac->preferred_zone, zone, order,
2734                                 gfp_mask, alloc_flags, ac->migratetype);
2735                 if (page) {
2736                         if (prep_new_page(page, order, gfp_mask, alloc_flags))
2737                                 goto try_this_zone;
2738 
2739                         /*
2740                          * If this is a high-order atomic allocation then check
2741                          * if the pageblock should be reserved for the future
2742                          */
2743                         if (unlikely(order && (alloc_flags & ALLOC_HARDER)))
2744                                 reserve_highatomic_pageblock(page, zone, order);
2745 
2746                         return page;
2747                 }
2748         }
2749 
2750         /*
2751          * The first pass makes sure allocations are spread fairly within the
2752          * local node.  However, the local node might have free pages left
2753          * after the fairness batches are exhausted, and remote zones haven't
2754          * even been considered yet.  Try once more without fairness, and
2755          * include remote zones now, before entering the slowpath and waking
2756          * kswapd: prefer spilling to a remote zone over swapping locally.
2757          */
2758         if (alloc_flags & ALLOC_FAIR) {
2759                 alloc_flags &= ~ALLOC_FAIR;
2760                 if (nr_fair_skipped) {
2761                         zonelist_rescan = true;
2762                         reset_alloc_batches(ac->preferred_zone);
2763                 }
2764                 if (nr_online_nodes > 1)
2765                         zonelist_rescan = true;
2766         }
2767 
2768         if (zonelist_rescan)
2769                 goto zonelist_scan;
2770 
2771         return NULL;
2772 }
2773 
2774 /*
2775  * Large machines with many possible nodes should not always dump per-node
2776  * meminfo in irq context.
2777  */
2778 static inline bool should_suppress_show_mem(void)
2779 {
2780         bool ret = false;
2781 
2782 #if NODES_SHIFT > 8
2783         ret = in_interrupt();
2784 #endif
2785         return ret;
2786 }
2787 
2788 static DEFINE_RATELIMIT_STATE(nopage_rs,
2789                 DEFAULT_RATELIMIT_INTERVAL,
2790                 DEFAULT_RATELIMIT_BURST);
2791 
2792 void warn_alloc_failed(gfp_t gfp_mask, unsigned int order, const char *fmt, ...)
2793 {
2794         unsigned int filter = SHOW_MEM_FILTER_NODES;
2795 
2796         if ((gfp_mask & __GFP_NOWARN) || !__ratelimit(&nopage_rs) ||
2797             debug_guardpage_minorder() > 0)
2798                 return;
2799 
2800         /*
2801          * This documents exceptions given to allocations in certain
2802          * contexts that are allowed to allocate outside current's set
2803          * of allowed nodes.
2804          */
2805         if (!(gfp_mask & __GFP_NOMEMALLOC))
2806                 if (test_thread_flag(TIF_MEMDIE) ||
2807                     (current->flags & (PF_MEMALLOC | PF_EXITING)))
2808                         filter &= ~SHOW_MEM_FILTER_NODES;
2809         if (in_interrupt() || !(gfp_mask & __GFP_DIRECT_RECLAIM))
2810                 filter &= ~SHOW_MEM_FILTER_NODES;
2811 
2812         if (fmt) {
2813                 struct va_format vaf;
2814                 va_list args;
2815 
2816                 va_start(args, fmt);
2817 
2818                 vaf.fmt = fmt;
2819                 vaf.va = &args;
2820 
2821                 pr_warn("%pV", &vaf);
2822 
2823                 va_end(args);
2824         }
2825 
2826         pr_warn("%s: page allocation failure: order:%u, mode:%#x(%pGg)\n",
2827                 current->comm, order, gfp_mask, &gfp_mask);
2828         dump_stack();
2829         if (!should_suppress_show_mem())
2830                 show_mem(filter);
2831 }
2832 
2833 static inline struct page *
2834 __alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order,
2835         const struct alloc_context *ac, unsigned long *did_some_progress)
2836 {
2837         struct oom_control oc = {
2838                 .zonelist = ac->zonelist,
2839                 .nodemask = ac->nodemask,
2840                 .gfp_mask = gfp_mask,
2841                 .order = order,
2842         };
2843         struct page *page;
2844 
2845         *did_some_progress = 0;
2846 
2847         /*
2848          * Acquire the oom lock.  If that fails, somebody else is
2849          * making progress for us.
2850          */
2851         if (!mutex_trylock(&oom_lock)) {
2852                 *did_some_progress = 1;
2853                 schedule_timeout_uninterruptible(1);
2854                 return NULL;
2855         }
2856 
2857         /*
2858          * Go through the zonelist yet one more time, keep very high watermark
2859          * here, this is only to catch a parallel oom killing, we must fail if
2860          * we're still under heavy pressure.
2861          */
2862         page = get_page_from_freelist(gfp_mask | __GFP_HARDWALL, order,
2863                                         ALLOC_WMARK_HIGH|ALLOC_CPUSET, ac);
2864         if (page)
2865                 goto out;
2866 
2867         if (!(gfp_mask & __GFP_NOFAIL)) {
2868                 /* Coredumps can quickly deplete all memory reserves */
2869                 if (current->flags & PF_DUMPCORE)
2870                         goto out;
2871                 /* The OOM killer will not help higher order allocs */
2872                 if (order > PAGE_ALLOC_COSTLY_ORDER)
2873                         goto out;
2874                 /* The OOM killer does not needlessly kill tasks for lowmem */
2875                 if (ac->high_zoneidx < ZONE_NORMAL)
2876                         goto out;
2877                 /* The OOM killer does not compensate for IO-less reclaim */
2878                 if (!(gfp_mask & __GFP_FS)) {
2879                         /*
2880                          * XXX: Page reclaim didn't yield anything,
2881                          * and the OOM killer can't be invoked, but
2882                          * keep looping as per tradition.
2883                          *
2884                          * But do not keep looping if oom_killer_disable()
2885                          * was already called, for the system is trying to
2886                          * enter a quiescent state during suspend.
2887                          */
2888                         *did_some_progress = !oom_killer_disabled;
2889                         goto out;
2890                 }
2891                 if (pm_suspended_storage())
2892                         goto out;
2893                 /* The OOM killer may not free memory on a specific node */
2894                 if (gfp_mask & __GFP_THISNODE)
2895                         goto out;
2896         }
2897         /* Exhausted what can be done so it's blamo time */
2898         if (out_of_memory(&oc) || WARN_ON_ONCE(gfp_mask & __GFP_NOFAIL)) {
2899                 *did_some_progress = 1;
2900 
2901                 if (gfp_mask & __GFP_NOFAIL) {
2902                         page = get_page_from_freelist(gfp_mask, order,
2903                                         ALLOC_NO_WATERMARKS|ALLOC_CPUSET, ac);
2904                         /*
2905                          * fallback to ignore cpuset restriction if our nodes
2906                          * are depleted
2907                          */
2908                         if (!page)
2909                                 page = get_page_from_freelist(gfp_mask, order,
2910                                         ALLOC_NO_WATERMARKS, ac);
2911                 }
2912         }
2913 out:
2914         mutex_unlock(&oom_lock);
2915         return page;
2916 }
2917 
2918 #ifdef CONFIG_COMPACTION
2919 /* Try memory compaction for high-order allocations before reclaim */
2920 static struct page *
2921 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
2922                 int alloc_flags, const struct alloc_context *ac,
2923                 enum migrate_mode mode, int *contended_compaction,
2924                 bool *deferred_compaction)
2925 {
2926         unsigned long compact_result;
2927         struct page *page;
2928 
2929         if (!order)
2930                 return NULL;
2931 
2932         current->flags |= PF_MEMALLOC;
2933         compact_result = try_to_compact_pages(gfp_mask, order, alloc_flags, ac,
2934                                                 mode, contended_compaction);
2935         current->flags &= ~PF_MEMALLOC;
2936 
2937         switch (compact_result) {
2938         case COMPACT_DEFERRED:
2939                 *deferred_compaction = true;
2940                 /* fall-through */
2941         case COMPACT_SKIPPED:
2942                 return NULL;
2943         default:
2944                 break;
2945         }
2946 
2947         /*
2948          * At least in one zone compaction wasn't deferred or skipped, so let's
2949          * count a compaction stall
2950          */
2951         count_vm_event(COMPACTSTALL);
2952 
2953         page = get_page_from_freelist(gfp_mask, order,
2954                                         alloc_flags & ~ALLOC_NO_WATERMARKS, ac);
2955 
2956         if (page) {
2957                 struct zone *zone = page_zone(page);
2958 
2959                 zone->compact_blockskip_flush = false;
2960                 compaction_defer_reset(zone, order, true);
2961                 count_vm_event(COMPACTSUCCESS);
2962                 return page;
2963         }
2964 
2965         /*
2966          * It's bad if compaction run occurs and fails. The most likely reason
2967          * is that pages exist, but not enough to satisfy watermarks.
2968          */
2969         count_vm_event(COMPACTFAIL);
2970 
2971         cond_resched();
2972 
2973         return NULL;
2974 }
2975 #else
2976 static inline struct page *
2977 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
2978                 int alloc_flags, const struct alloc_context *ac,
2979                 enum migrate_mode mode, int *contended_compaction,
2980                 bool *deferred_compaction)
2981 {
2982         return NULL;
2983 }
2984 #endif /* CONFIG_COMPACTION */
2985 
2986 /* Perform direct synchronous page reclaim */
2987 static int
2988 __perform_reclaim(gfp_t gfp_mask, unsigned int order,
2989                                         const struct alloc_context *ac)
2990 {
2991         struct reclaim_state reclaim_state;
2992         int progress;
2993 
2994         cond_resched();
2995 
2996         /* We now go into synchronous reclaim */
2997         cpuset_memory_pressure_bump();
2998         current->flags |= PF_MEMALLOC;
2999         lockdep_set_current_reclaim_state(gfp_mask);
3000         reclaim_state.reclaimed_slab = 0;
3001         current->reclaim_state = &reclaim_state;
3002 
3003         progress = try_to_free_pages(ac->zonelist, order, gfp_mask,
3004                                                                 ac->nodemask);
3005 
3006         current->reclaim_state = NULL;
3007         lockdep_clear_current_reclaim_state();
3008         current->flags &= ~PF_MEMALLOC;
3009 
3010         cond_resched();
3011 
3012         return progress;
3013 }
3014 
3015 /* The really slow allocator path where we enter direct reclaim */
3016 static inline struct page *
3017 __alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order,
3018                 int alloc_flags, const struct alloc_context *ac,
3019                 unsigned long *did_some_progress)
3020 {
3021         struct page *page = NULL;
3022         bool drained = false;
3023 
3024         *did_some_progress = __perform_reclaim(gfp_mask, order, ac);
3025         if (unlikely(!(*did_some_progress)))
3026                 return NULL;
3027 
3028 retry:
3029         page = get_page_from_freelist(gfp_mask, order,
3030                                         alloc_flags & ~ALLOC_NO_WATERMARKS, ac);
3031 
3032         /*
3033          * If an allocation failed after direct reclaim, it could be because
3034          * pages are pinned on the per-cpu lists or in high alloc reserves.
3035          * Shrink them them and try again
3036          */
3037         if (!page && !drained) {
3038                 unreserve_highatomic_pageblock(ac);
3039                 drain_all_pages(NULL);
3040                 drained = true;
3041                 goto retry;
3042         }
3043 
3044         return page;
3045 }
3046 
3047 static void wake_all_kswapds(unsigned int order, const struct alloc_context *ac)
3048 {
3049         struct zoneref *z;
3050         struct zone *zone;
3051 
3052         for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
3053                                                 ac->high_zoneidx, ac->nodemask)
3054                 wakeup_kswapd(zone, order, zone_idx(ac->preferred_zone));
3055 }
3056 
3057 static inline int
3058 gfp_to_alloc_flags(gfp_t gfp_mask)
3059 {
3060         int alloc_flags = ALLOC_WMARK_MIN | ALLOC_CPUSET;
3061 
3062         /* __GFP_HIGH is assumed to be the same as ALLOC_HIGH to save a branch. */
3063         BUILD_BUG_ON(__GFP_HIGH != (__force gfp_t) ALLOC_HIGH);
3064 
3065         /*
3066          * The caller may dip into page reserves a bit more if the caller
3067          * cannot run direct reclaim, or if the caller has realtime scheduling
3068          * policy or is asking for __GFP_HIGH memory.  GFP_ATOMIC requests will
3069          * set both ALLOC_HARDER (__GFP_ATOMIC) and ALLOC_HIGH (__GFP_HIGH).
3070          */
3071         alloc_flags |= (__force int) (gfp_mask & __GFP_HIGH);
3072 
3073         if (gfp_mask & __GFP_ATOMIC) {
3074                 /*
3075                  * Not worth trying to allocate harder for __GFP_NOMEMALLOC even
3076                  * if it can't schedule.
3077                  */
3078                 if (!(gfp_mask & __GFP_NOMEMALLOC))
3079                         alloc_flags |= ALLOC_HARDER;
3080                 /*
3081                  * Ignore cpuset mems for GFP_ATOMIC rather than fail, see the
3082                  * comment for __cpuset_node_allowed().
3083                  */
3084                 alloc_flags &= ~ALLOC_CPUSET;
3085         } else if (unlikely(rt_task(current)) && !in_interrupt())
3086                 alloc_flags |= ALLOC_HARDER;
3087 
3088         if (likely(!(gfp_mask & __GFP_NOMEMALLOC))) {
3089                 if (gfp_mask & __GFP_MEMALLOC)
3090                         alloc_flags |= ALLOC_NO_WATERMARKS;
3091                 else if (in_serving_softirq() && (current->flags & PF_MEMALLOC))
3092                         alloc_flags |= ALLOC_NO_WATERMARKS;
3093                 else if (!in_interrupt() &&
3094                                 ((current->flags & PF_MEMALLOC) ||
3095                                  unlikely(test_thread_flag(TIF_MEMDIE))))
3096                         alloc_flags |= ALLOC_NO_WATERMARKS;
3097         }
3098 #ifdef CONFIG_CMA
3099         if (gfpflags_to_migratetype(gfp_mask) == MIGRATE_MOVABLE)
3100                 alloc_flags |= ALLOC_CMA;
3101 #endif
3102         return alloc_flags;
3103 }
3104 
3105 bool gfp_pfmemalloc_allowed(gfp_t gfp_mask)
3106 {
3107         return !!(gfp_to_alloc_flags(gfp_mask) & ALLOC_NO_WATERMARKS);
3108 }
3109 
3110 static inline bool is_thp_gfp_mask(gfp_t gfp_mask)
3111 {
3112         return (gfp_mask & (GFP_TRANSHUGE | __GFP_KSWAPD_RECLAIM)) == GFP_TRANSHUGE;
3113 }
3114 
3115 static inline struct page *
3116 __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order,
3117                                                 struct alloc_context *ac)
3118 {
3119         bool can_direct_reclaim = gfp_mask & __GFP_DIRECT_RECLAIM;
3120         struct page *page = NULL;
3121         int alloc_flags;
3122         unsigned long pages_reclaimed = 0;
3123         unsigned long did_some_progress;
3124         enum migrate_mode migration_mode = MIGRATE_ASYNC;
3125         bool deferred_compaction = false;
3126         int contended_compaction = COMPACT_CONTENDED_NONE;
3127 
3128         /*
3129          * In the slowpath, we sanity check order to avoid ever trying to
3130          * reclaim >= MAX_ORDER areas which will never succeed. Callers may
3131          * be using allocators in order of preference for an area that is
3132          * too large.
3133          */
3134         if (order >= MAX_ORDER) {
3135                 WARN_ON_ONCE(!(gfp_mask & __GFP_NOWARN));
3136                 return NULL;
3137         }
3138 
3139         /*
3140          * We also sanity check to catch abuse of atomic reserves being used by
3141          * callers that are not in atomic context.
3142          */
3143         if (WARN_ON_ONCE((gfp_mask & (__GFP_ATOMIC|__GFP_DIRECT_RECLAIM)) ==
3144                                 (__GFP_ATOMIC|__GFP_DIRECT_RECLAIM)))
3145                 gfp_mask &= ~__GFP_ATOMIC;
3146 
3147 retry:
3148         if (gfp_mask & __GFP_KSWAPD_RECLAIM)
3149                 wake_all_kswapds(order, ac);
3150 
3151         /*
3152          * OK, we're below the kswapd watermark and have kicked background
3153          * reclaim. Now things get more complex, so set up alloc_flags according
3154          * to how we want to proceed.
3155          */
3156         alloc_flags = gfp_to_alloc_flags(gfp_mask);
3157 
3158         /*
3159          * Find the true preferred zone if the allocation is unconstrained by
3160          * cpusets.
3161          */
3162         if (!(alloc_flags & ALLOC_CPUSET) && !ac->nodemask) {
3163                 struct zoneref *preferred_zoneref;
3164                 preferred_zoneref = first_zones_zonelist(ac->zonelist,
3165                                 ac->high_zoneidx, NULL, &ac->preferred_zone);
3166                 ac->classzone_idx = zonelist_zone_idx(preferred_zoneref);
3167         }
3168 
3169         /* This is the last chance, in general, before the goto nopage. */
3170         page = get_page_from_freelist(gfp_mask, order,
3171                                 alloc_flags & ~ALLOC_NO_WATERMARKS, ac);
3172         if (page)
3173                 goto got_pg;
3174 
3175         /* Allocate without watermarks if the context allows */
3176         if (alloc_flags & ALLOC_NO_WATERMARKS) {
3177                 /*
3178                  * Ignore mempolicies if ALLOC_NO_WATERMARKS on the grounds
3179                  * the allocation is high priority and these type of
3180                  * allocations are system rather than user orientated
3181                  */
3182                 ac->zonelist = node_zonelist(numa_node_id(), gfp_mask);
3183                 page = get_page_from_freelist(gfp_mask, order,
3184                                                 ALLOC_NO_WATERMARKS, ac);
3185                 if (page)
3186                         goto got_pg;
3187         }
3188 
3189         /* Caller is not willing to reclaim, we can't balance anything */
3190         if (!can_direct_reclaim) {
3191                 /*
3192                  * All existing users of the __GFP_NOFAIL are blockable, so warn
3193                  * of any new users that actually allow this type of allocation
3194                  * to fail.
3195                  */
3196                 WARN_ON_ONCE(gfp_mask & __GFP_NOFAIL);
3197                 goto nopage;
3198         }
3199 
3200         /* Avoid recursion of direct reclaim */
3201         if (current->flags & PF_MEMALLOC) {
3202                 /*
3203                  * __GFP_NOFAIL request from this context is rather bizarre
3204                  * because we cannot reclaim anything and only can loop waiting
3205                  * for somebody to do a work for us.
3206                  */
3207                 if (WARN_ON_ONCE(gfp_mask & __GFP_NOFAIL)) {
3208                         cond_resched();
3209                         goto retry;
3210                 }
3211                 goto nopage;
3212         }
3213 
3214         /* Avoid allocations with no watermarks from looping endlessly */
3215         if (test_thread_flag(TIF_MEMDIE) && !(gfp_mask & __GFP_NOFAIL))
3216                 goto nopage;
3217 
3218         /*
3219          * Try direct compaction. The first pass is asynchronous. Subsequent
3220          * attempts after direct reclaim are synchronous
3221          */
3222         page = __alloc_pages_direct_compact(gfp_mask, order, alloc_flags, ac,
3223                                         migration_mode,
3224                                         &contended_compaction,
3225                                         &deferred_compaction);
3226         if (page)
3227                 goto got_pg;
3228 
3229         /* Checks for THP-specific high-order allocations */
3230         if (is_thp_gfp_mask(gfp_mask)) {
3231                 /*
3232                  * If compaction is deferred for high-order allocations, it is
3233                  * because sync compaction recently failed. If this is the case
3234                  * and the caller requested a THP allocation, we do not want
3235                  * to heavily disrupt the system, so we fail the allocation
3236                  * instead of entering direct reclaim.
3237                  */
3238                 if (deferred_compaction)
3239                         goto nopage;
3240 
3241                 /*
3242                  * In all zones where compaction was attempted (and not
3243                  * deferred or skipped), lock contention has been detected.
3244                  * For THP allocation we do not want to disrupt the others
3245                  * so we fallback to base pages instead.
3246                  */
3247                 if (contended_compaction == COMPACT_CONTENDED_LOCK)
3248                         goto nopage;
3249 
3250                 /*
3251                  * If compaction was aborted due to need_resched(), we do not
3252                  * want to further increase allocation latency, unless it is
3253                  * khugepaged trying to collapse.
3254                  */
3255                 if (contended_compaction == COMPACT_CONTENDED_SCHED
3256                         && !(current->flags & PF_KTHREAD))
3257                         goto nopage;
3258         }
3259 
3260         /*
3261          * It can become very expensive to allocate transparent hugepages at
3262          * fault, so use asynchronous memory compaction for THP unless it is
3263          * khugepaged trying to collapse.
3264          */
3265         if (!is_thp_gfp_mask(gfp_mask) || (current->flags & PF_KTHREAD))
3266                 migration_mode = MIGRATE_SYNC_LIGHT;
3267 
3268         /* Try direct reclaim and then allocating */
3269         page = __alloc_pages_direct_reclaim(gfp_mask, order, alloc_flags, ac,
3270                                                         &did_some_progress);
3271         if (page)
3272                 goto got_pg;
3273 
3274         /* Do not loop if specifically requested */
3275         if (gfp_mask & __GFP_NORETRY)
3276                 goto noretry;
3277 
3278         /* Keep reclaiming pages as long as there is reasonable progress */
3279         pages_reclaimed += did_some_progress;
3280         if ((did_some_progress && order <= PAGE_ALLOC_COSTLY_ORDER) ||
3281             ((gfp_mask & __GFP_REPEAT) && pages_reclaimed < (1 << order))) {
3282                 /* Wait for some write requests to complete then retry */
3283                 wait_iff_congested(ac->preferred_zone, BLK_RW_ASYNC, HZ/50);
3284                 goto retry;
3285         }
3286 
3287         /* Reclaim has failed us, start killing things */
3288         page = __alloc_pages_may_oom(gfp_mask, order, ac, &did_some_progress);
3289         if (page)
3290                 goto got_pg;
3291 
3292         /* Retry as long as the OOM killer is making progress */
3293         if (did_some_progress)
3294                 goto retry;
3295 
3296 noretry:
3297         /*
3298          * High-order allocations do not necessarily loop after
3299          * direct reclaim and reclaim/compaction depends on compaction
3300          * being called after reclaim so call directly if necessary
3301          */
3302         page = __alloc_pages_direct_compact(gfp_mask, order, alloc_flags,
3303                                             ac, migration_mode,
3304                                             &contended_compaction,
3305                                             &deferred_compaction);
3306         if (page)
3307                 goto got_pg;
3308 nopage:
3309         warn_alloc_failed(gfp_mask, order, NULL);
3310 got_pg:
3311         return page;
3312 }
3313 
3314 /*
3315  * This is the 'heart' of the zoned buddy allocator.
3316  */
3317 struct page *
3318 __alloc_pages_nodemask(gfp_t gfp_mask, unsigned int order,
3319                         struct zonelist *zonelist, nodemask_t *nodemask)
3320 {
3321         struct zoneref *preferred_zoneref;
3322         struct page *page = NULL;
3323         unsigned int cpuset_mems_cookie;
3324         int alloc_flags = ALLOC_WMARK_LOW|ALLOC_CPUSET|ALLOC_FAIR;
3325         gfp_t alloc_mask; /* The gfp_t that was actually used for allocation */
3326         struct alloc_context ac = {
3327                 .high_zoneidx = gfp_zone(gfp_mask),
3328                 .nodemask = nodemask,
3329                 .migratetype = gfpflags_to_migratetype(gfp_mask),
3330         };
3331 
3332         gfp_mask &= gfp_allowed_mask;
3333 
3334         lockdep_trace_alloc(gfp_mask);
3335 
3336         might_sleep_if(gfp_mask & __GFP_DIRECT_RECLAIM);
3337 
3338         if (should_fail_alloc_page(gfp_mask, order))
3339                 return NULL;
3340 
3341         /*
3342          * Check the zones suitable for the gfp_mask contain at least one
3343          * valid zone. It's possible to have an empty zonelist as a result
3344          * of __GFP_THISNODE and a memoryless node
3345          */
3346         if (unlikely(!zonelist->_zonerefs->zone))
3347                 return NULL;
3348 
3349         if (IS_ENABLED(CONFIG_CMA) && ac.migratetype == MIGRATE_MOVABLE)
3350                 alloc_flags |= ALLOC_CMA;
3351 
3352 retry_cpuset:
3353         cpuset_mems_cookie = read_mems_allowed_begin();
3354 
3355         /* We set it here, as __alloc_pages_slowpath might have changed it */
3356         ac.zonelist = zonelist;
3357 
3358         /* Dirty zone balancing only done in the fast path */
3359         ac.spread_dirty_pages = (gfp_mask & __GFP_WRITE);
3360 
3361         /* The preferred zone is used for statistics later */
3362         preferred_zoneref = first_zones_zonelist(ac.zonelist, ac.high_zoneidx,
3363                                 ac.nodemask ? : &cpuset_current_mems_allowed,
3364                                 &ac.preferred_zone);
3365         if (!ac.preferred_zone)
3366                 goto out;
3367         ac.classzone_idx = zonelist_zone_idx(preferred_zoneref);
3368 
3369         /* First allocation attempt */
3370         alloc_mask = gfp_mask|__GFP_HARDWALL;
3371         page = get_page_from_freelist(alloc_mask, order, alloc_flags, &ac);
3372         if (unlikely(!page)) {
3373                 /*
3374                  * Runtime PM, block IO and its error handling path
3375                  * can deadlock because I/O on the device might not
3376                  * complete.
3377                  */
3378                 alloc_mask = memalloc_noio_flags(gfp_mask);
3379                 ac.spread_dirty_pages = false;
3380 
3381                 page = __alloc_pages_slowpath(alloc_mask, order, &ac);
3382         }
3383 
3384         if (kmemcheck_enabled && page)
3385                 kmemcheck_pagealloc_alloc(page, order, gfp_mask);
3386 
3387         trace_mm_page_alloc(page, order, alloc_mask, ac.migratetype);
3388 
3389 out:
3390         /*
3391          * When updating a task's mems_allowed, it is possible to race with
3392          * parallel threads in such a way that an allocation can fail while
3393          * the mask is being updated. If a page allocation is about to fail,
3394          * check if the cpuset changed during allocation and if so, retry.
3395          */
3396         if (unlikely(!page && read_mems_allowed_retry(cpuset_mems_cookie)))
3397                 goto retry_cpuset;
3398 
3399         return page;
3400 }
3401 EXPORT_SYMBOL(__alloc_pages_nodemask);
3402 
3403 /*
3404  * Common helper functions.
3405  */
3406 unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order)
3407 {
3408         struct page *page;
3409 
3410         /*
3411          * __get_free_pages() returns a 32-bit address, which cannot represent
3412          * a highmem page
3413          */
3414         VM_BUG_ON((gfp_mask & __GFP_HIGHMEM) != 0);
3415 
3416         page = alloc_pages(gfp_mask, order);
3417         if (!page)
3418                 return 0;
3419         return (unsigned long) page_address(page);
3420 }
3421 EXPORT_SYMBOL(__get_free_pages);
3422 
3423 unsigned long get_zeroed_page(gfp_t gfp_mask)
3424 {
3425         return __get_free_pages(gfp_mask | __GFP_ZERO, 0);
3426 }
3427 EXPORT_SYMBOL(get_zeroed_page);
3428 
3429 void __free_pages(struct page *page, unsigned int order)
3430 {
3431         if (put_page_testzero(page)) {
3432                 if (order == 0)
3433                         free_hot_cold_page(page, false);
3434                 else
3435                         __free_pages_ok(page, order);
3436         }
3437 }
3438 
3439 EXPORT_SYMBOL(__free_pages);
3440 
3441 void free_pages(unsigned long addr, unsigned int order)
3442 {
3443         if (addr != 0) {
3444                 VM_BUG_ON(!virt_addr_valid((void *)addr));
3445                 __free_pages(virt_to_page((void *)addr), order);
3446         }
3447 }
3448 
3449 EXPORT_SYMBOL(free_pages);
3450 
3451 /*
3452  * Page Fragment:
3453  *  An arbitrary-length arbitrary-offset area of memory which resides
3454  *  within a 0 or higher order page.  Multiple fragments within that page
3455  *  are individually refcounted, in the page's reference counter.
3456  *
3457  * The page_frag functions below provide a simple allocation framework for
3458  * page fragments.  This is used by the network stack and network device
3459  * drivers to provide a backing region of memory for use as either an
3460  * sk_buff->head, or to be used in the "frags" portion of skb_shared_info.
3461  */
3462 static struct page *__page_frag_refill(struct page_frag_cache *nc,
3463                                        gfp_t gfp_mask)
3464 {
3465         struct page *page = NULL;
3466         gfp_t gfp = gfp_mask;
3467 
3468 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
3469         gfp_mask |= __GFP_COMP | __GFP_NOWARN | __GFP_NORETRY |
3470                     __GFP_NOMEMALLOC;
3471         page = alloc_pages_node(NUMA_NO_NODE, gfp_mask,
3472                                 PAGE_FRAG_CACHE_MAX_ORDER);
3473         nc->size = page ? PAGE_FRAG_CACHE_MAX_SIZE : PAGE_SIZE;
3474 #endif
3475         if (unlikely(!page))
3476                 page = alloc_pages_node(NUMA_NO_NODE, gfp, 0);
3477 
3478         nc->va = page ? page_address(page) : NULL;
3479 
3480         return page;
3481 }
3482 
3483 void *__alloc_page_frag(struct page_frag_cache *nc,
3484                         unsigned int fragsz, gfp_t gfp_mask)
3485 {
3486         unsigned int size = PAGE_SIZE;
3487         struct page *page;
3488         int offset;
3489 
3490         if (unlikely(!nc->va)) {
3491 refill:
3492                 page = __page_frag_refill(nc, gfp_mask);
3493                 if (!page)
3494                         return NULL;
3495 
3496 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
3497                 /* if size can vary use size else just use PAGE_SIZE */
3498                 size = nc->size;
3499 #endif
3500                 /* Even if we own the page, we do not use atomic_set().
3501                  * This would break get_page_unless_zero() users.
3502                  */
3503                 page_ref_add(page, size - 1);
3504 
3505                 /* reset page count bias and offset to start of new frag */
3506                 nc->pfmemalloc = page_is_pfmemalloc(page);
3507                 nc->pagecnt_bias = size;
3508                 nc->offset = size;
3509         }
3510 
3511         offset = nc->offset - fragsz;
3512         if (unlikely(offset < 0)) {
3513                 page = virt_to_page(nc->va);
3514 
3515                 if (!page_ref_sub_and_test(page, nc->pagecnt_bias))
3516                         goto refill;
3517 
3518 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
3519                 /* if size can vary use size else just use PAGE_SIZE */
3520                 size = nc->size;
3521 #endif
3522                 /* OK, page count is 0, we can safely set it */
3523                 set_page_count(page, size);
3524 
3525                 /* reset page count bias and offset to start of new frag */
3526                 nc->pagecnt_bias = size;
3527                 offset = size - fragsz;
3528         }
3529 
3530         nc->pagecnt_bias--;
3531         nc->offset = offset;
3532 
3533         return nc->va + offset;
3534 }
3535 EXPORT_SYMBOL(__alloc_page_frag);
3536 
3537 /*
3538  * Frees a page fragment allocated out of either a compound or order 0 page.
3539  */
3540 void __free_page_frag(void *addr)
3541 {
3542         struct page *page = virt_to_head_page(addr);
3543 
3544         if (unlikely(put_page_testzero(page)))
3545                 __free_pages_ok(page, compound_order(page));
3546 }
3547 EXPORT_SYMBOL(__free_page_frag);
3548 
3549 /*
3550  * alloc_kmem_pages charges newly allocated pages to the kmem resource counter
3551  * of the current memory cgroup if __GFP_ACCOUNT is set, other than that it is
3552  * equivalent to alloc_pages.
3553  *
3554  * It should be used when the caller would like to use kmalloc, but since the
3555  * allocation is large, it has to fall back to the page allocator.
3556  */
3557 struct page *alloc_kmem_pages(gfp_t gfp_mask, unsigned int order)
3558 {
3559         struct page *page;
3560 
3561         page = alloc_pages(gfp_mask, order);
3562         if (page && memcg_kmem_charge(page, gfp_mask, order) != 0) {
3563                 __free_pages(page, order);
3564                 page = NULL;
3565         }
3566         return page;
3567 }
3568 
3569 struct page *alloc_kmem_pages_node(int nid, gfp_t gfp_mask, unsigned int order)
3570 {
3571         struct page *page;
3572 
3573         page = alloc_pages_node(nid, gfp_mask, order);
3574         if (page && memcg_kmem_charge(page, gfp_mask, order) != 0) {
3575                 __free_pages(page, order);
3576                 page = NULL;
3577         }
3578         return page;
3579 }
3580 
3581 /*
3582  * __free_kmem_pages and free_kmem_pages will free pages allocated with
3583  * alloc_kmem_pages.
3584  */
3585 void __free_kmem_pages(struct page *page, unsigned int order)
3586 {
3587         memcg_kmem_uncharge(page, order);
3588         __free_pages(page, order);
3589 }
3590 
3591 void free_kmem_pages(unsigned long addr, unsigned int order)
3592 {
3593         if (addr != 0) {
3594                 VM_BUG_ON(!virt_addr_valid((void *)addr));
3595                 __free_kmem_pages(virt_to_page((void *)addr), order);
3596         }
3597 }
3598 
3599 static void *make_alloc_exact(unsigned long addr, unsigned int order,
3600                 size_t size)
3601 {
3602         if (addr) {
3603                 unsigned long alloc_end = addr + (PAGE_SIZE << order);
3604                 unsigned long used = addr + PAGE_ALIGN(size);
3605 
3606                 split_page(virt_to_page((void *)addr), order);
3607                 while (used < alloc_end) {
3608                         free_page(used);
3609                         used += PAGE_SIZE;
3610                 }
3611         }
3612         return (void *)addr;
3613 }
3614 
3615 /**
3616  * alloc_pages_exact - allocate an exact number physically-contiguous pages.
3617  * @size: the number of bytes to allocate
3618  * @gfp_mask: GFP flags for the allocation
3619  *
3620  * This function is similar to alloc_pages(), except that it allocates the
3621  * minimum number of pages to satisfy the request.  alloc_pages() can only
3622  * allocate memory in power-of-two pages.
3623  *
3624  * This function is also limited by MAX_ORDER.
3625  *
3626  * Memory allocated by this function must be released by free_pages_exact().
3627  */
3628 void *alloc_pages_exact(size_t size, gfp_t gfp_mask)
3629 {
3630         unsigned int order = get_order(size);
3631         unsigned long addr;
3632 
3633         addr = __get_free_pages(gfp_mask, order);
3634         return make_alloc_exact(addr, order, size);
3635 }
3636 EXPORT_SYMBOL(alloc_pages_exact);
3637 
3638 /**
3639  * alloc_pages_exact_nid - allocate an exact number of physically-contiguous
3640  *                         pages on a node.
3641  * @nid: the preferred node ID where memory should be allocated
3642  * @size: the number of bytes to allocate
3643  * @gfp_mask: GFP flags for the allocation
3644  *
3645  * Like alloc_pages_exact(), but try to allocate on node nid first before falling
3646  * back.
3647  */
3648 void * __meminit alloc_pages_exact_nid(int nid, size_t size, gfp_t gfp_mask)
3649 {
3650         unsigned int order = get_order(size);
3651         struct page *p = alloc_pages_node(nid, gfp_mask, order);
3652         if (!p)
3653                 return NULL;
3654         return make_alloc_exact((unsigned long)page_address(p), order, size);
3655 }
3656 
3657 /**
3658  * free_pages_exact - release memory allocated via alloc_pages_exact()
3659  * @virt: the value returned by alloc_pages_exact.
3660  * @size: size of allocation, same value as passed to alloc_pages_exact().
3661  *
3662  * Release the memory allocated by a previous call to alloc_pages_exact.
3663  */
3664 void free_pages_exact(void *virt, size_t size)
3665 {
3666         unsigned long addr = (unsigned long)virt;
3667         unsigned long end = addr + PAGE_ALIGN(size);
3668 
3669         while (addr < end) {
3670                 free_page(addr);
3671                 addr += PAGE_SIZE;
3672         }
3673 }
3674 EXPORT_SYMBOL(free_pages_exact);
3675 
3676 /**
3677  * nr_free_zone_pages - count number of pages beyond high watermark
3678  * @offset: The zone index of the highest zone
3679  *
3680  * nr_free_zone_pages() counts the number of counts pages which are beyond the
3681  * high watermark within all zones at or below a given zone index.  For each
3682  * zone, the number of pages is calculated as:
3683  *     managed_pages - high_pages
3684  */
3685 static unsigned long nr_free_zone_pages(int offset)
3686 {
3687         struct zoneref *z;
3688         struct zone *zone;
3689 
3690         /* Just pick one node, since fallback list is circular */
3691         unsigned long sum = 0;
3692 
3693         struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL);
3694 
3695         for_each_zone_zonelist(zone, z, zonelist, offset) {
3696                 unsigned long size = zone->managed_pages;
3697                 unsigned long high = high_wmark_pages(zone);
3698                 if (size > high)
3699                         sum += size - high;
3700         }
3701 
3702         return sum;
3703 }
3704 
3705 /**
3706  * nr_free_buffer_pages - count number of pages beyond high watermark
3707  *
3708  * nr_free_buffer_pages() counts the number of pages which are beyond the high
3709  * watermark within ZONE_DMA and ZONE_NORMAL.
3710  */
3711 unsigned long nr_free_buffer_pages(void)
3712 {
3713         return nr_free_zone_pages(gfp_zone(GFP_USER));
3714 }
3715 EXPORT_SYMBOL_GPL(nr_free_buffer_pages);
3716 
3717 /**
3718  * nr_free_pagecache_pages - count number of pages beyond high watermark
3719  *
3720  * nr_free_pagecache_pages() counts the number of pages which are beyond the
3721  * high watermark within all zones.
3722  */
3723 unsigned long nr_free_pagecache_pages(void)
3724 {
3725         return nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE));
3726 }
3727 
3728 static inline void show_node(struct zone *zone)
3729 {
3730         if (IS_ENABLED(CONFIG_NUMA))
3731                 printk("Node %d ", zone_to_nid(zone));
3732 }
3733 
3734 long si_mem_available(void)
3735 {
3736         long available;
3737         unsigned long pagecache;
3738         unsigned long wmark_low = 0;
3739         unsigned long pages[NR_LRU_LISTS];
3740         struct zone *zone;
3741         int lru;
3742 
3743         for (lru = LRU_BASE; lru < NR_LRU_LISTS; lru++)
3744                 pages[lru] = global_page_state(NR_LRU_BASE + lru);
3745 
3746         for_each_zone(zone)
3747                 wmark_low += zone->watermark[WMARK_LOW];
3748 
3749         /*
3750          * Estimate the amount of memory available for userspace allocations,
3751          * without causing swapping.
3752          */
3753         available = global_page_state(NR_FREE_PAGES) - totalreserve_pages;
3754 
3755         /*
3756          * Not all the page cache can be freed, otherwise the system will
3757          * start swapping. Assume at least half of the page cache, or the
3758          * low watermark worth of cache, needs to stay.
3759          */
3760         pagecache = pages[LRU_ACTIVE_FILE] + pages[LRU_INACTIVE_FILE];
3761         pagecache -= min(pagecache / 2, wmark_low);
3762         available += pagecache;
3763 
3764         /*
3765          * Part of the reclaimable slab consists of items that are in use,
3766          * and cannot be freed. Cap this estimate at the low watermark.
3767          */
3768         available += global_page_state(NR_SLAB_RECLAIMABLE) -
3769                      min(global_page_state(NR_SLAB_RECLAIMABLE) / 2, wmark_low);
3770 
3771         if (available < 0)
3772                 available = 0;
3773         return available;
3774 }
3775 EXPORT_SYMBOL_GPL(si_mem_available);
3776 
3777 void si_meminfo(struct sysinfo *val)
3778 {
3779         val->totalram = totalram_pages;
3780         val->sharedram = global_page_state(NR_SHMEM);
3781         val->freeram = global_page_state(NR_FREE_PAGES);
3782         val->bufferram = nr_blockdev_pages();
3783         val->totalhigh = totalhigh_pages;
3784         val->freehigh = nr_free_highpages();
3785         val->mem_unit = PAGE_SIZE;
3786 }
3787 
3788 EXPORT_SYMBOL(si_meminfo);
3789 
3790 #ifdef CONFIG_NUMA
3791 void si_meminfo_node(struct sysinfo *val, int nid)
3792 {
3793         int zone_type;          /* needs to be signed */
3794         unsigned long managed_pages = 0;
3795         pg_data_t *pgdat = NODE_DATA(nid);
3796 
3797         for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++)
3798                 managed_pages += pgdat->node_zones[zone_type].managed_pages;
3799         val->totalram = managed_pages;
3800         val->sharedram = node_page_state(nid, NR_SHMEM);
3801         val->freeram = node_page_state(nid, NR_FREE_PAGES);
3802 #ifdef CONFIG_HIGHMEM
3803         val->totalhigh = pgdat->node_zones[ZONE_HIGHMEM].managed_pages;
3804         val->freehigh = zone_page_state(&pgdat->node_zones[ZONE_HIGHMEM],
3805                         NR_FREE_PAGES);
3806 #else
3807         val->totalhigh = 0;
3808         val->freehigh = 0;
3809 #endif
3810         val->mem_unit = PAGE_SIZE;
3811 }
3812 #endif
3813 
3814 /*
3815  * Determine whether the node should be displayed or not, depending on whether
3816  * SHOW_MEM_FILTER_NODES was passed to show_free_areas().
3817  */
3818 bool skip_free_areas_node(unsigned int flags, int nid)
3819 {
3820         bool ret = false;
3821         unsigned int cpuset_mems_cookie;
3822 
3823         if (!(flags & SHOW_MEM_FILTER_NODES))
3824                 goto out;
3825 
3826         do {
3827                 cpuset_mems_cookie = read_mems_allowed_begin();
3828                 ret = !node_isset(nid, cpuset_current_mems_allowed);
3829         } while (read_mems_allowed_retry(cpuset_mems_cookie));
3830 out:
3831         return ret;
3832 }
3833 
3834 #define K(x) ((x) << (PAGE_SHIFT-10))
3835 
3836 static void show_migration_types(unsigned char type)
3837 {
3838         static const char types[MIGRATE_TYPES] = {
3839                 [MIGRATE_UNMOVABLE]     = 'U',
3840                 [MIGRATE_MOVABLE]       = 'M',
3841                 [MIGRATE_RECLAIMABLE]   = 'E',
3842                 [MIGRATE_HIGHATOMIC]    = 'H',
3843 #ifdef CONFIG_CMA
3844                 [MIGRATE_CMA]           = 'C',
3845 #endif
3846 #ifdef CONFIG_MEMORY_ISOLATION
3847                 [MIGRATE_ISOLATE]       = 'I',
3848 #endif
3849         };
3850         char tmp[MIGRATE_TYPES + 1];
3851         char *p = tmp;
3852         int i;
3853 
3854         for (i = 0; i < MIGRATE_TYPES; i++) {
3855                 if (type & (1 << i))
3856                         *p++ = types[i];
3857         }
3858 
3859         *p = '\0';
3860         printk("(%s) ", tmp);
3861 }
3862 
3863 /*
3864  * Show free area list (used inside shift_scroll-lock stuff)
3865  * We also calculate the percentage fragmentation. We do this by counting the
3866  * memory on each free list with the exception of the first item on the list.
3867  *
3868  * Bits in @filter:
3869  * SHOW_MEM_FILTER_NODES: suppress nodes that are not allowed by current's
3870  *   cpuset.
3871  */
3872 void show_free_areas(unsigned int filter)
3873 {
3874         unsigned long free_pcp = 0;
3875         int cpu;
3876         struct zone *zone;
3877 
3878         for_each_populated_zone(zone) {
3879                 if (skip_free_areas_node(filter, zone_to_nid(zone)))
3880                         continue;
3881 
3882                 for_each_online_cpu(cpu)
3883                         free_pcp += per_cpu_ptr(zone->pageset, cpu)->pcp.count;
3884         }
3885 
3886         printk("active_anon:%lu inactive_anon:%lu isolated_anon:%lu\n"
3887                 " active_file:%lu inactive_file:%lu isolated_file:%lu\n"
3888                 " unevictable:%lu dirty:%lu writeback:%lu unstable:%lu\n"
3889                 " slab_reclaimable:%lu slab_unreclaimable:%lu\n"
3890                 " mapped:%lu shmem:%lu pagetables:%lu bounce:%lu\n"
3891                 " free:%lu free_pcp:%lu free_cma:%lu\n",
3892                 global_page_state(NR_ACTIVE_ANON),
3893                 global_page_state(NR_INACTIVE_ANON),
3894                 global_page_state(NR_ISOLATED_ANON),
3895                 global_page_state(NR_ACTIVE_FILE),
3896                 global_page_state(NR_INACTIVE_FILE),
3897                 global_page_state(NR_ISOLATED_FILE),
3898                 global_page_state(NR_UNEVICTABLE),
3899                 global_page_state(NR_FILE_DIRTY),
3900                 global_page_state(NR_WRITEBACK),
3901                 global_page_state(NR_UNSTABLE_NFS),
3902                 global_page_state(NR_SLAB_RECLAIMABLE),
3903                 global_page_state(NR_SLAB_UNRECLAIMABLE),
3904                 global_page_state(NR_FILE_MAPPED),
3905                 global_page_state(NR_SHMEM),
3906                 global_page_state(NR_PAGETABLE),
3907                 global_page_state(NR_BOUNCE),
3908                 global_page_state(NR_FREE_PAGES),
3909                 free_pcp,
3910                 global_page_state(NR_FREE_CMA_PAGES));
3911 
3912         for_each_populated_zone(zone) {
3913                 int i;
3914 
3915                 if (skip_free_areas_node(filter, zone_to_nid(zone)))
3916                         continue;
3917 
3918                 free_pcp = 0;
3919                 for_each_online_cpu(cpu)
3920                         free_pcp += per_cpu_ptr(zone->pageset, cpu)->pcp.count;
3921 
3922                 show_node(zone);
3923                 printk("%s"
3924                         " free:%lukB"
3925                         " min:%lukB"
3926                         " low:%lukB"
3927                         " high:%lukB"
3928                         " active_anon:%lukB"
3929                         " inactive_anon:%lukB"
3930                         " active_file:%lukB"
3931                         " inactive_file:%lukB"
3932                         " unevictable:%lukB"
3933                         " isolated(anon):%lukB"
3934                         " isolated(file):%lukB"
3935                         " present:%lukB"
3936                         " managed:%lukB"
3937                         " mlocked:%lukB"
3938                         " dirty:%lukB"
3939                         " writeback:%lukB"
3940                         " mapped:%lukB"
3941                         " shmem:%lukB"
3942                         " slab_reclaimable:%lukB"
3943                         " slab_unreclaimable:%lukB"
3944                         " kernel_stack:%lukB"
3945                         " pagetables:%lukB"
3946                         " unstable:%lukB"
3947                         " bounce:%lukB"
3948                         " free_pcp:%lukB"
3949                         " local_pcp:%ukB"
3950                         " free_cma:%lukB"
3951                         " writeback_tmp:%lukB"
3952                         " pages_scanned:%lu"
3953                         " all_unreclaimable? %s"
3954                         "\n",
3955                         zone->name,
3956                         K(zone_page_state(zone, NR_FREE_PAGES)),
3957                         K(min_wmark_pages(zone)),
3958                         K(low_wmark_pages(zone)),
3959                         K(high_wmark_pages(zone)),
3960                         K(zone_page_state(zone, NR_ACTIVE_ANON)),
3961                         K(zone_page_state(zone, NR_INACTIVE_ANON)),
3962                         K(zone_page_state(zone, NR_ACTIVE_FILE)),
3963                         K(zone_page_state(zone, NR_INACTIVE_FILE)),
3964                         K(zone_page_state(zone, NR_UNEVICTABLE)),
3965                         K(zone_page_state(zone, NR_ISOLATED_ANON)),
3966                         K(zone_page_state(zone, NR_ISOLATED_FILE)),
3967                         K(zone->present_pages),
3968                         K(zone->managed_pages),
3969                         K(zone_page_state(zone, NR_MLOCK)),
3970                         K(zone_page_state(zone, NR_FILE_DIRTY)),
3971                         K(zone_page_state(zone, NR_WRITEBACK)),
3972                         K(zone_page_state(zone, NR_FILE_MAPPED)),
3973                         K(zone_page_state(zone, NR_SHMEM)),
3974                         K(zone_page_state(zone, NR_SLAB_RECLAIMABLE)),
3975                         K(zone_page_state(zone, NR_SLAB_UNRECLAIMABLE)),
3976                         zone_page_state(zone, NR_KERNEL_STACK) *
3977                                 THREAD_SIZE / 1024,
3978                         K(zone_page_state(zone, NR_PAGETABLE)),
3979                         K(zone_page_state(zone, NR_UNSTABLE_NFS)),
3980                         K(zone_page_state(zone, NR_BOUNCE)),
3981                         K(free_pcp),
3982                         K(this_cpu_read(zone->pageset->pcp.count)),
3983                         K(zone_page_state(zone, NR_FREE_CMA_PAGES)),
3984                         K(zone_page_state(zone, NR_WRITEBACK_TEMP)),
3985                         K(zone_page_state(zone, NR_PAGES_SCANNED)),
3986                         (!zone_reclaimable(zone) ? "yes" : "no")
3987                         );
3988                 printk("lowmem_reserve[]:");
3989                 for (i = 0; i < MAX_NR_ZONES; i++)
3990                         printk(" %ld", zone->lowmem_reserve[i]);
3991                 printk("\n");
3992         }
3993 
3994         for_each_populated_zone(zone) {
3995                 unsigned int order;
3996                 unsigned long nr[MAX_ORDER], flags, total = 0;
3997                 unsigned char types[MAX_ORDER];
3998 
3999                 if (skip_free_areas_node(filter, zone_to_nid(zone)))
4000                         continue;
4001                 show_node(zone);
4002                 printk("%s: ", zone->name);
4003 
4004                 spin_lock_irqsave(&zone->lock, flags);
4005                 for (order = 0; order < MAX_ORDER; order++) {
4006                         struct free_area *area = &zone->free_area[order];
4007                         int type;
4008 
4009                         nr[order] = area->nr_free;
4010                         total += nr[order] << order;
4011 
4012                         types[order] = 0;
4013                         for (type = 0; type < MIGRATE_TYPES; type++) {
4014                                 if (!list_empty(&area->free_list[type]))
4015                                         types[order] |= 1 << type;
4016                         }
4017                 }
4018                 spin_unlock_irqrestore(&zone->lock, flags);
4019                 for (order = 0; order < MAX_ORDER; order++) {
4020                         printk("%lu*%lukB ", nr[order], K(1UL) << order);
4021                         if (nr[order])
4022                                 show_migration_types(types[order]);
4023                 }
4024                 printk("= %lukB\n", K(total));
4025         }
4026 
4027         hugetlb_show_meminfo();
4028 
4029         printk("%ld total pagecache pages\n", global_page_state(NR_FILE_PAGES));
4030 
4031         show_swap_cache_info();
4032 }
4033 
4034 static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref)
4035 {
4036         zoneref->zone = zone;
4037         zoneref->zone_idx = zone_idx(zone);
4038 }
4039 
4040 /*
4041  * Builds allocation fallback zone lists.
4042  *
4043  * Add all populated zones of a node to the zonelist.
4044  */
4045 static int build_zonelists_node(pg_data_t *pgdat, struct zonelist *zonelist,
4046                                 int nr_zones)
4047 {
4048         struct zone *zone;
4049         enum zone_type zone_type = MAX_NR_ZONES;
4050 
4051         do {
4052                 zone_type--;
4053                 zone = pgdat->node_zones + zone_type;
4054                 if (populated_zone(zone)) {
4055                         zoneref_set_zone(zone,
4056                                 &zonelist->_zonerefs[nr_zones++]);
4057                         check_highest_zone(zone_type);
4058                 }
4059         } while (zone_type);
4060 
4061         return nr_zones;
4062 }
4063 
4064 
4065 /*
4066  *  zonelist_order:
4067  *  0 = automatic detection of better ordering.
4068  *  1 = order by ([node] distance, -zonetype)
4069  *  2 = order by (-zonetype, [node] distance)
4070  *
4071  *  If not NUMA, ZONELIST_ORDER_ZONE and ZONELIST_ORDER_NODE will create
4072  *  the same zonelist. So only NUMA can configure this param.
4073  */
4074 #define ZONELIST_ORDER_DEFAULT  0
4075 #define ZONELIST_ORDER_NODE     1
4076 #define ZONELIST_ORDER_ZONE     2
4077 
4078 /* zonelist order in the kernel.
4079  * set_zonelist_order() will set this to NODE or ZONE.
4080  */
4081 static int current_zonelist_order = ZONELIST_ORDER_DEFAULT;
4082 static char zonelist_order_name[3][8] = {"Default", "Node", "Zone"};
4083 
4084 
4085 #ifdef CONFIG_NUMA
4086 /* The value user specified ....changed by config */
4087 static int user_zonelist_order = ZONELIST_ORDER_DEFAULT;
4088 /* string for sysctl */
4089 #define NUMA_ZONELIST_ORDER_LEN 16
4090 char numa_zonelist_order[16] = "default";
4091 
4092 /*
4093  * interface for configure zonelist ordering.
4094  * command line option "numa_zonelist_order"
4095  *      = "[dD]efault   - default, automatic configuration.
4096  *      = "[nN]ode      - order by node locality, then by zone within node
4097  *      = "[zZ]one      - order by zone, then by locality within zone
4098  */
4099 
4100 static int __parse_numa_zonelist_order(char *s)
4101 {
4102         if (*s == 'd' || *s == 'D') {
4103                 user_zonelist_order = ZONELIST_ORDER_DEFAULT;
4104         } else if (*s == 'n' || *s == 'N') {
4105                 user_zonelist_order = ZONELIST_ORDER_NODE;
4106         } else if (*s == 'z' || *s == 'Z') {
4107                 user_zonelist_order = ZONELIST_ORDER_ZONE;
4108         } else {
4109                 pr_warn("Ignoring invalid numa_zonelist_order value:  %s\n", s);
4110                 return -EINVAL;
4111         }
4112         return 0;
4113 }
4114 
4115 static __init int setup_numa_zonelist_order(char *s)
4116 {
4117         int ret;
4118 
4119         if (!s)
4120                 return 0;
4121 
4122         ret = __parse_numa_zonelist_order(s);
4123         if (ret == 0)
4124                 strlcpy(numa_zonelist_order, s, NUMA_ZONELIST_ORDER_LEN);
4125 
4126         return ret;
4127 }
4128 early_param("numa_zonelist_order", setup_numa_zonelist_order);
4129 
4130 /*
4131  * sysctl handler for numa_zonelist_order
4132  */
4133 int numa_zonelist_order_handler(struct ctl_table *table, int write,
4134                 void __user *buffer, size_t *length,
4135                 loff_t *ppos)
4136 {
4137         char saved_string[NUMA_ZONELIST_ORDER_LEN];
4138         int ret;
4139         static DEFINE_MUTEX(zl_order_mutex);
4140 
4141         mutex_lock(&zl_order_mutex);
4142         if (write) {
4143                 if (strlen((char *)table->data) >= NUMA_ZONELIST_ORDER_LEN) {
4144                         ret = -EINVAL;
4145                         goto out;
4146                 }
4147                 strcpy(saved_string, (char *)table->data);
4148         }
4149         ret = proc_dostring(table, write, buffer, length, ppos);
4150         if (ret)
4151                 goto out;
4152         if (write) {
4153                 int oldval = user_zonelist_order;
4154 
4155                 ret = __parse_numa_zonelist_order((char *)table->data);
4156                 if (ret) {
4157                         /*
4158                          * bogus value.  restore saved string
4159                          */
4160                         strncpy((char *)table->data, saved_string,
4161                                 NUMA_ZONELIST_ORDER_LEN);
4162                         user_zonelist_order = oldval;
4163                 } else if (oldval != user_zonelist_order) {
4164                         mutex_lock(&zonelists_mutex);
4165                         build_all_zonelists(NULL, NULL);
4166                         mutex_unlock(&zonelists_mutex);
4167                 }
4168         }
4169 out:
4170         mutex_unlock(&zl_order_mutex);
4171         return ret;
4172 }
4173 
4174 
4175 #define MAX_NODE_LOAD (nr_online_nodes)
4176 static int node_load[MAX_NUMNODES];
4177 
4178 /**
4179  * find_next_best_node - find the next node that should appear in a given node's fallback list
4180  * @node: node whose fallback list we're appending
4181  * @used_node_mask: nodemask_t of already used nodes
4182  *
4183  * We use a number of factors to determine which is the next node that should
4184  * appear on a given node's fallback list.  The node should not have appeared
4185  * already in @node's fallback list, and it should be the next closest node
4186  * according to the distance array (which contains arbitrary distance values
4187  * from each node to each node in the system), and should also prefer nodes
4188  * with no CPUs, since presumably they'll have very little allocation pressure
4189  * on them otherwise.
4190  * It returns -1 if no node is found.
4191  */
4192 static int find_next_best_node(int node, nodemask_t *used_node_mask)
4193 {
4194         int n, val;
4195         int min_val = INT_MAX;
4196         int best_node = NUMA_NO_NODE;
4197         const struct cpumask *tmp = cpumask_of_node(0);
4198 
4199         /* Use the local node if we haven't already */
4200         if (!node_isset(node, *used_node_mask)) {
4201                 node_set(node, *used_node_mask);
4202                 return node;
4203         }
4204 
4205         for_each_node_state(n, N_MEMORY) {
4206 
4207                 /* Don't want a node to appear more than once */
4208                 if (node_isset(n, *used_node_mask))
4209                         continue;
4210 
4211                 /* Use the distance array to find the distance */
4212                 val = node_distance(node, n);
4213 
4214                 /* Penalize nodes under us ("prefer the next node") */
4215                 val += (n < node);
4216 
4217                 /* Give preference to headless and unused nodes */
4218                 tmp = cpumask_of_node(n);
4219                 if (!cpumask_empty(tmp))
4220                         val += PENALTY_FOR_NODE_WITH_CPUS;
4221 
4222                 /* Slight preference for less loaded node */
4223                 val *= (MAX_NODE_LOAD*MAX_NUMNODES);
4224                 val += node_load[n];
4225 
4226                 if (val < min_val) {
4227                         min_val = val;
4228                         best_node = n;
4229                 }
4230         }
4231 
4232         if (best_node >= 0)
4233                 node_set(best_node, *used_node_mask);
4234 
4235         return best_node;
4236 }
4237 
4238 
4239 /*
4240  * Build zonelists ordered by node and zones within node.
4241  * This results in maximum locality--normal zone overflows into local
4242  * DMA zone, if any--but risks exhausting DMA zone.
4243  */
4244 static void build_zonelists_in_node_order(pg_data_t *pgdat, int node)
4245 {
4246         int j;
4247         struct zonelist *zonelist;
4248 
4249         zonelist = &pgdat->node_zonelists[0];
4250         for (j = 0; zonelist->_zonerefs[j].zone != NULL; j++)
4251                 ;
4252         j = build_zonelists_node(NODE_DATA(node), zonelist, j);
4253         zonelist->_zonerefs[j].zone = NULL;
4254         zonelist->_zonerefs[j].zone_idx = 0;
4255 }
4256 
4257 /*
4258  * Build gfp_thisnode zonelists
4259  */
4260 static void build_thisnode_zonelists(pg_data_t *pgdat)
4261 {
4262         int j;
4263         struct zonelist *zonelist;
4264 
4265         zonelist = &pgdat->node_zonelists[1];
4266         j = build_zonelists_node(pgdat, zonelist, 0);
4267         zonelist->_zonerefs[j].zone = NULL;
4268         zonelist->_zonerefs[j].zone_idx = 0;
4269 }
4270 
4271 /*
4272  * Build zonelists ordered by zone and nodes within zones.
4273  * This results in conserving DMA zone[s] until all Normal memory is
4274  * exhausted, but results in overflowing to remote node while memory
4275  * may still exist in local DMA zone.
4276  */
4277 static int node_order[MAX_NUMNODES];
4278 
4279 static void build_zonelists_in_zone_order(pg_data_t *pgdat, int nr_nodes)
4280 {
4281         int pos, j, node;
4282         int zone_type;          /* needs to be signed */
4283         struct zone *z;
4284         struct zonelist *zonelist;
4285 
4286         zonelist = &pgdat->node_zonelists[0];
4287         pos = 0;
4288         for (zone_type = MAX_NR_ZONES - 1; zone_type >= 0; zone_type--) {
4289                 for (j = 0; j < nr_nodes; j++) {
4290                         node = node_order[j];
4291                         z = &NODE_DATA(node)->node_zones[zone_type];
4292                         if (populated_zone(z)) {
4293                                 zoneref_set_zone(z,
4294                                         &zonelist->_zonerefs[pos++]);
4295                                 check_highest_zone(zone_type);
4296                         }
4297                 }
4298         }
4299         zonelist->_zonerefs[pos].zone = NULL;
4300         zonelist->_zonerefs[pos].zone_idx = 0;
4301 }
4302 
4303 #if defined(CONFIG_64BIT)
4304 /*
4305  * Devices that require DMA32/DMA are relatively rare and do not justify a
4306  * penalty to every machine in case the specialised case applies. Default
4307  * to Node-ordering on 64-bit NUMA machines
4308  */
4309 static int default_zonelist_order(void)
4310 {
4311         return ZONELIST_ORDER_NODE;
4312 }
4313 #else
4314 /*
4315  * On 32-bit, the Normal zone needs to be preserved for allocations accessible
4316  * by the kernel. If processes running on node 0 deplete the low memory zone
4317  * then reclaim will occur more frequency increasing stalls and potentially
4318  * be easier to OOM if a large percentage of the zone is under writeback or
4319  * dirty. The problem is significantly worse if CONFIG_HIGHPTE is not set.
4320  * Hence, default to zone ordering on 32-bit.
4321  */
4322 static int default_zonelist_order(void)
4323 {
4324         return ZONELIST_ORDER_ZONE;
4325 }
4326 #endif /* CONFIG_64BIT */
4327 
4328 static void set_zonelist_order(void)
4329 {
4330         if (user_zonelist_order == ZONELIST_ORDER_DEFAULT)
4331                 current_zonelist_order = default_zonelist_order();
4332         else
4333                 current_zonelist_order = user_zonelist_order;
4334 }
4335 
4336 static void build_zonelists(pg_data_t *pgdat)
4337 {
4338         int i, node, load;
4339         nodemask_t used_mask;
4340         int local_node, prev_node;
4341         struct zonelist *zonelist;
4342         unsigned int order = current_zonelist_order;
4343 
4344         /* initialize zonelists */
4345         for (i = 0; i < MAX_ZONELISTS; i++) {
4346                 zonelist = pgdat->node_zonelists + i;
4347                 zonelist->_zonerefs[0].zone = NULL;
4348                 zonelist->_zonerefs[0].zone_idx = 0;
4349         }
4350 
4351         /* NUMA-aware ordering of nodes */
4352         local_node = pgdat->node_id;
4353         load = nr_online_nodes;
4354         prev_node = local_node;
4355         nodes_clear(used_mask);
4356 
4357         memset(node_order, 0, sizeof(node_order));
4358         i = 0;
4359 
4360         while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
4361                 /*
4362                  * We don't want to pressure a particular node.
4363                  * So adding penalty to the first node in same
4364                  * distance group to make it round-robin.
4365                  */
4366                 if (node_distance(local_node, node) !=
4367                     node_distance(local_node, prev_node))
4368                         node_load[node] = load;
4369 
4370                 prev_node = node;
4371                 load--;
4372                 if (order == ZONELIST_ORDER_NODE)
4373                         build_zonelists_in_node_order(pgdat, node);
4374                 else
4375                         node_order[i++] = node; /* remember order */
4376         }
4377 
4378         if (order == ZONELIST_ORDER_ZONE) {
4379                 /* calculate node order -- i.e., DMA last! */
4380                 build_zonelists_in_zone_order(pgdat, i);
4381         }
4382 
4383         build_thisnode_zonelists(pgdat);
4384 }
4385 
4386 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
4387 /*
4388  * Return node id of node used for "local" allocations.
4389  * I.e., first node id of first zone in arg node's generic zonelist.
4390  * Used for initializing percpu 'numa_mem', which is used primarily
4391  * for kernel allocations, so use GFP_KERNEL flags to locate zonelist.
4392  */
4393 int local_memory_node(int node)
4394 {
4395         struct zone *zone;
4396 
4397         (void)first_zones_zonelist(node_zonelist(node, GFP_KERNEL),
4398                                    gfp_zone(GFP_KERNEL),
4399                                    NULL,
4400                                    &zone);
4401         return zone->node;
4402 }
4403 #endif
4404 
4405 #else   /* CONFIG_NUMA */
4406 
4407 static void set_zonelist_order(void)
4408 {
4409         current_zonelist_order = ZONELIST_ORDER_ZONE;
4410 }
4411 
4412 static void build_zonelists(pg_data_t *pgdat)
4413 {
4414         int node, local_node;
4415         enum zone_type j;
4416         struct zonelist *zonelist;
4417 
4418         local_node = pgdat->node_id;
4419 
4420         zonelist = &pgdat->node_zonelists[0];
4421         j = build_zonelists_node(pgdat, zonelist, 0);
4422 
4423         /*
4424          * Now we build the zonelist so that it contains the zones
4425          * of all the other nodes.
4426          * We don't want to pressure a particular node, so when
4427          * building the zones for node N, we make sure that the
4428          * zones coming right after the local ones are those from
4429          * node N+1 (modulo N)
4430          */
4431         for (node = local_node + 1; node < MAX_NUMNODES; node++) {
4432                 if (!node_online(node))
4433                         continue;
4434                 j = build_zonelists_node(NODE_DATA(node), zonelist, j);
4435         }
4436         for (node = 0; node < local_node; node++) {
4437                 if (!node_online(node))
4438                         continue;
4439                 j = build_zonelists_node(NODE_DATA(node), zonelist, j);
4440         }
4441 
4442         zonelist->_zonerefs[j].zone = NULL;
4443         zonelist->_zonerefs[j].zone_idx = 0;
4444 }
4445 
4446 #endif  /* CONFIG_NUMA */
4447 
4448 /*
4449  * Boot pageset table. One per cpu which is going to be used for all
4450  * zones and all nodes. The parameters will be set in such a way
4451  * that an item put on a list will immediately be handed over to
4452  * the buddy list. This is safe since pageset manipulation is done
4453  * with interrupts disabled.
4454  *
4455  * The boot_pagesets must be kept even after bootup is complete for
4456  * unused processors and/or zones. They do play a role for bootstrapping
4457  * hotplugged processors.
4458  *
4459  * zoneinfo_show() and maybe other functions do
4460  * not check if the processor is online before following the pageset pointer.
4461  * Other parts of the kernel may not check if the zone is available.
4462  */
4463 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch);
4464 static DEFINE_PER_CPU(struct per_cpu_pageset, boot_pageset);
4465 static void setup_zone_pageset(struct zone *zone);
4466 
4467 /*
4468  * Global mutex to protect against size modification of zonelists
4469  * as well as to serialize pageset setup for the new populated zone.
4470  */
4471 DEFINE_MUTEX(zonelists_mutex);
4472 
4473 /* return values int ....just for stop_machine() */
4474 static int __build_all_zonelists(void *data)
4475 {
4476         int nid;
4477         int cpu;
4478         pg_data_t *self = data;
4479 
4480 #ifdef CONFIG_NUMA
4481         memset(node_load, 0, sizeof(node_load));
4482 #endif
4483 
4484         if (self && !node_online(self->node_id)) {
4485                 build_zonelists(self);
4486         }
4487 
4488         for_each_online_node(nid) {
4489                 pg_data_t *pgdat = NODE_DATA(nid);
4490 
4491                 build_zonelists(pgdat);
4492         }
4493 
4494         /*
4495          * Initialize the boot_pagesets that are going to be used
4496          * for bootstrapping processors. The real pagesets for
4497          * each zone will be allocated later when the per cpu
4498          * allocator is available.
4499          *
4500          * boot_pagesets are used also for bootstrapping offline
4501          * cpus if the system is already booted because the pagesets
4502          * are needed to initialize allocators on a specific cpu too.
4503          * F.e. the percpu allocator needs the page allocator which
4504          * needs the percpu allocator in order to allocate its pagesets
4505          * (a chicken-egg dilemma).
4506          */
4507         for_each_possible_cpu(cpu) {
4508                 setup_pageset(&per_cpu(boot_pageset, cpu), 0);
4509 
4510 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
4511                 /*
4512                  * We now know the "local memory node" for each node--
4513                  * i.e., the node of the first zone in the generic zonelist.
4514                  * Set up numa_mem percpu variable for on-line cpus.  During
4515                  * boot, only the boot cpu should be on-line;  we'll init the
4516                  * secondary cpus' numa_mem as they come on-line.  During
4517                  * node/memory hotplug, we'll fixup all on-line cpus.
4518                  */
4519                 if (cpu_online(cpu))
4520                         set_cpu_numa_mem(cpu, local_memory_node(cpu_to_node(cpu)));
4521 #endif
4522         }
4523 
4524         return 0;
4525 }
4526 
4527 static noinline void __init
4528 build_all_zonelists_init(void)
4529 {
4530         __build_all_zonelists(NULL);
4531         mminit_verify_zonelist();
4532         cpuset_init_current_mems_allowed();
4533 }
4534 
4535 /*
4536  * Called with zonelists_mutex held always
4537  * unless system_state == SYSTEM_BOOTING.
4538  *
4539  * __ref due to (1) call of __meminit annotated setup_zone_pageset
4540  * [we're only called with non-NULL zone through __meminit paths] and
4541  * (2) call of __init annotated helper build_all_zonelists_init
4542  * [protected by SYSTEM_BOOTING].
4543  */
4544 void __ref build_all_zonelists(pg_data_t *pgdat, struct zone *zone)
4545 {
4546         set_zonelist_order();
4547 
4548         if (system_state == SYSTEM_BOOTING) {
4549                 build_all_zonelists_init();
4550         } else {
4551 #ifdef CONFIG_MEMORY_HOTPLUG
4552                 if (zone)
4553                         setup_zone_pageset(zone);
4554 #endif
4555                 /* we have to stop all cpus to guarantee there is no user
4556                    of zonelist */
4557                 stop_machine(__build_all_zonelists, pgdat, NULL);
4558                 /* cpuset refresh routine should be here */
4559         }
4560         vm_total_pages = nr_free_pagecache_pages();
4561         /*
4562          * Disable grouping by mobility if the number of pages in the
4563          * system is too low to allow the mechanism to work. It would be
4564          * more accurate, but expensive to check per-zone. This check is
4565          * made on memory-hotadd so a system can start with mobility
4566          * disabled and enable it later
4567          */
4568         if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES))
4569                 page_group_by_mobility_disabled = 1;
4570         else
4571                 page_group_by_mobility_disabled = 0;
4572 
4573         pr_info("Built %i zonelists in %s order, mobility grouping %s.  Total pages: %ld\n",
4574                 nr_online_nodes,
4575                 zonelist_order_name[current_zonelist_order],
4576                 page_group_by_mobility_disabled ? "off" : "on",
4577                 vm_total_pages);
4578 #ifdef CONFIG_NUMA
4579         pr_info("Policy zone: %s\n", zone_names[policy_zone]);
4580 #endif
4581 }
4582 
4583 /*
4584  * Helper functions to size the waitqueue hash table.
4585  * Essentially these want to choose hash table sizes sufficiently
4586  * large so that collisions trying to wait on pages are rare.
4587  * But in fact, the number of active page waitqueues on typical
4588  * systems is ridiculously low, less than 200. So this is even
4589  * conservative, even though it seems large.
4590  *
4591  * The constant PAGES_PER_WAITQUEUE specifies the ratio of pages to
4592  * waitqueues, i.e. the size of the waitq table given the number of pages.
4593  */
4594 #define PAGES_PER_WAITQUEUE     256
4595 
4596 #ifndef CONFIG_MEMORY_HOTPLUG
4597 static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
4598 {
4599         unsigned long size = 1;
4600 
4601         pages /= PAGES_PER_WAITQUEUE;
4602 
4603         while (size < pages)
4604                 size <<= 1;
4605 
4606         /*
4607          * Once we have dozens or even hundreds of threads sleeping
4608          * on IO we've got bigger problems than wait queue collision.
4609          * Limit the size of the wait table to a reasonable size.
4610          */
4611         size = min(size, 4096UL);
4612 
4613         return max(size, 4UL);
4614 }
4615 #else
4616 /*
4617  * A zone's size might be changed by hot-add, so it is not possible to determine
4618  * a suitable size for its wait_table.  So we use the maximum size now.
4619  *
4620  * The max wait table size = 4096 x sizeof(wait_queue_head_t).   ie:
4621  *
4622  *    i386 (preemption config)    : 4096 x 16 = 64Kbyte.
4623  *    ia64, x86-64 (no preemption): 4096 x 20 = 80Kbyte.
4624  *    ia64, x86-64 (preemption)   : 4096 x 24 = 96Kbyte.
4625  *
4626  * The maximum entries are prepared when a zone's memory is (512K + 256) pages
4627  * or more by the traditional way. (See above).  It equals:
4628  *
4629  *    i386, x86-64, powerpc(4K page size) : =  ( 2G + 1M)byte.
4630  *    ia64(16K page size)                 : =  ( 8G + 4M)byte.
4631  *    powerpc (64K page size)             : =  (32G +16M)byte.
4632  */
4633 static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
4634 {
4635         return 4096UL;
4636 }
4637 #endif
4638 
4639 /*
4640  * This is an integer logarithm so that shifts can be used later
4641  * to extract the more random high bits from the multiplicative
4642  * hash function before the remainder is taken.
4643  */
4644 static inline unsigned long wait_table_bits(unsigned long size)
4645 {
4646         return ffz(~size);
4647 }
4648 
4649 /*
4650  * Initially all pages are reserved - free ones are freed
4651  * up by free_all_bootmem() once the early boot process is
4652  * done. Non-atomic initialization, single-pass.
4653  */
4654 void __meminit memmap_init_zone(unsigned long size, int nid, unsigned long zone,
4655                 unsigned long start_pfn, enum memmap_context context)
4656 {
4657         struct vmem_altmap *altmap = to_vmem_altmap(__pfn_to_phys(start_pfn));
4658         unsigned long end_pfn = start_pfn + size;
4659         pg_data_t *pgdat = NODE_DATA(nid);
4660         unsigned long pfn;
4661         unsigned long nr_initialised = 0;
4662 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
4663         struct memblock_region *r = NULL, *tmp;
4664 #endif
4665 
4666         if (highest_memmap_pfn < end_pfn - 1)
4667                 highest_memmap_pfn = end_pfn - 1;
4668 
4669         /*
4670          * Honor reservation requested by the driver for this ZONE_DEVICE
4671          * memory
4672          */
4673         if (altmap && start_pfn == altmap->base_pfn)
4674                 start_pfn += altmap->reserve;
4675 
4676         for (pfn = start_pfn; pfn < end_pfn; pfn++) {
4677                 /*
4678                  * There can be holes in boot-time mem_map[]s handed to this
4679                  * function.  They do not exist on hotplugged memory.
4680                  */
4681                 if (context != MEMMAP_EARLY)
4682                         goto not_early;
4683 
4684                 if (!early_pfn_valid(pfn))
4685                         continue;
4686                 if (!early_pfn_in_nid(pfn, nid))
4687                         continue;
4688                 if (!update_defer_init(pgdat, pfn, end_pfn, &nr_initialised))
4689                         break;
4690 
4691 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
4692                 /*
4693                  * If not mirrored_kernelcore and ZONE_MOVABLE exists, range
4694                  * from zone_movable_pfn[nid] to end of each node should be
4695                  * ZONE_MOVABLE not ZONE_NORMAL. skip it.
4696                  */
4697                 if (!mirrored_kernelcore && zone_movable_pfn[nid])
4698                         if (zone == ZONE_NORMAL && pfn >= zone_movable_pfn[nid])
4699                                 continue;
4700 
4701                 /*
4702                  * Check given memblock attribute by firmware which can affect
4703                  * kernel memory layout.  If zone==ZONE_MOVABLE but memory is
4704                  * mirrored, it's an overlapped memmap init. skip it.
4705                  */
4706                 if (mirrored_kernelcore && zone == ZONE_MOVABLE) {
4707                         if (!r || pfn >= memblock_region_memory_end_pfn(r)) {
4708                                 for_each_memblock(memory, tmp)
4709                                         if (pfn < memblock_region_memory_end_pfn(tmp))
4710                                                 break;
4711                                 r = tmp;
4712                         }
4713                         if (pfn >= memblock_region_memory_base_pfn(r) &&
4714                             memblock_is_mirror(r)) {
4715                                 /* already initialized as NORMAL */
4716                                 pfn = memblock_region_memory_end_pfn(r);
4717                                 continue;
4718                         }
4719                 }
4720 #endif
4721 
4722 not_early:
4723                 /*
4724                  * Mark the block movable so that blocks are reserved for
4725                  * movable at startup. This will force kernel allocations
4726                  * to reserve their blocks rather than leaking throughout
4727                  * the address space during boot when many long-lived
4728                  * kernel allocations are made.
4729                  *
4730                  * bitmap is created for zone's valid pfn range. but memmap
4731                  * can be created for invalid pages (for alignment)
4732                  * check here not to call set_pageblock_migratetype() against
4733                  * pfn out of zone.
4734                  */
4735                 if (!(pfn & (pageblock_nr_pages - 1))) {
4736                         struct page *page = pfn_to_page(pfn);
4737 
4738                         __init_single_page(page, pfn, zone, nid);
4739                         set_pageblock_migratetype(page, MIGRATE_MOVABLE);
4740                 } else {
4741                         __init_single_pfn(pfn, zone, nid);
4742                 }
4743         }
4744 }
4745 
4746 static void __meminit zone_init_free_lists(struct zone *zone)
4747 {
4748         unsigned int order, t;
4749         for_each_migratetype_order(order, t) {
4750                 INIT_LIST_HEAD(&zone->free_area[order].free_list[t]);
4751                 zone->free_area[order].nr_free = 0;
4752         }
4753 }
4754 
4755 #ifndef __HAVE_ARCH_MEMMAP_INIT
4756 #define memmap_init(size, nid, zone, start_pfn) \
4757         memmap_init_zone((size), (nid), (zone), (start_pfn), MEMMAP_EARLY)
4758 #endif
4759 
4760 static int zone_batchsize(struct zone *zone)
4761 {
4762 #ifdef CONFIG_MMU
4763         int batch;
4764 
4765         /*
4766          * The per-cpu-pages pools are set to around 1000th of the
4767          * size of the zone.  But no more than 1/2 of a meg.
4768          *
4769          * OK, so we don't know how big the cache is.  So guess.
4770          */
4771         batch = zone->managed_pages / 1024;
4772         if (batch * PAGE_SIZE > 512 * 1024)
4773                 batch = (512 * 1024) / PAGE_SIZE;
4774         batch /= 4;             /* We effectively *= 4 below */
4775         if (batch < 1)
4776                 batch = 1;
4777 
4778         /*
4779          * Clamp the batch to a 2^n - 1 value. Having a power
4780          * of 2 value was found to be more likely to have
4781          * suboptimal cache aliasing properties in some cases.
4782          *
4783          * For example if 2 tasks are alternately allocating
4784          * batches of pages, one task can end up with a lot
4785          * of pages of one half of the possible page colors
4786          * and the other with pages of the other colors.
4787          */
4788         batch = rounddown_pow_of_two(batch + batch/2) - 1;
4789 
4790         return batch;
4791 
4792 #else
4793         /* The deferral and batching of frees should be suppressed under NOMMU
4794          * conditions.
4795          *
4796          * The problem is that NOMMU needs to be able to allocate large chunks
4797          * of contiguous memory as there's no hardware page translation to
4798          * assemble apparent contiguous memory from discontiguous pages.
4799          *
4800          * Queueing large contiguous runs of pages for batching, however,
4801          * causes the pages to actually be freed in smaller chunks.  As there
4802          * can be a significant delay between the individual batches being
4803          * recycled, this leads to the once large chunks of space being
4804          * fragmented and becoming unavailable for high-order allocations.
4805          */
4806         return 0;
4807 #endif
4808 }
4809 
4810 /*
4811  * pcp->high and pcp->batch values are related and dependent on one another:
4812  * ->batch must never be higher then ->high.
4813  * The following function updates them in a safe manner without read side
4814  * locking.
4815  *
4816  * Any new users of pcp->batch and pcp->high should ensure they can cope with
4817  * those fields changing asynchronously (acording the the above rule).
4818  *
4819  * mutex_is_locked(&pcp_batch_high_lock) required when calling this function
4820  * outside of boot time (or some other assurance that no concurrent updaters
4821  * exist).
4822  */
4823 static void pageset_update(struct per_cpu_pages *pcp, unsigned long high,
4824                 unsigned long batch)
4825 {
4826        /* start with a fail safe value for batch */
4827         pcp->batch = 1;
4828         smp_wmb();
4829 
4830        /* Update high, then batch, in order */
4831         pcp->high = high;
4832         smp_wmb();
4833 
4834         pcp->batch = batch;
4835 }
4836 
4837 /* a companion to pageset_set_high() */
4838 static void pageset_set_batch(struct per_cpu_pageset *p, unsigned long batch)
4839 {
4840         pageset_update(&p->pcp, 6 * batch, max(1UL, 1 * batch));
4841 }
4842 
4843 static void pageset_init(struct per_cpu_pageset *p)
4844 {
4845         struct per_cpu_pages *pcp;
4846         int migratetype;
4847 
4848         memset(p, 0, sizeof(*p));
4849 
4850         pcp = &p->pcp;
4851         pcp->count = 0;
4852         for (migratetype = 0; migratetype < MIGRATE_PCPTYPES; migratetype++)
4853                 INIT_LIST_HEAD(&pcp->lists[migratetype]);
4854 }
4855 
4856 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch)
4857 {
4858         pageset_init(p);
4859         pageset_set_batch(p, batch);
4860 }
4861 
4862 /*
4863  * pageset_set_high() sets the high water mark for hot per_cpu_pagelist
4864  * to the value high for the pageset p.
4865  */
4866 static void pageset_set_high(struct per_cpu_pageset *p,
4867                                 unsigned long high)
4868 {
4869         unsigned long batch = max(1UL, high / 4);
4870         if ((high / 4) > (PAGE_SHIFT * 8))
4871                 batch = PAGE_SHIFT * 8;
4872 
4873         pageset_update(&p->pcp, high, batch);
4874 }
4875 
4876 static void pageset_set_high_and_batch(struct zone *zone,
4877                                        struct per_cpu_pageset *pcp)
4878 {
4879         if (percpu_pagelist_fraction)
4880                 pageset_set_high(pcp,
4881                         (zone->managed_pages /
4882                                 percpu_pagelist_fraction));
4883         else
4884                 pageset_set_batch(pcp, zone_batchsize(zone));
4885 }
4886 
4887 static void __meminit zone_pageset_init(struct zone *zone, int cpu)
4888 {
4889         struct per_cpu_pageset *pcp = per_cpu_ptr(zone->pageset, cpu);
4890 
4891         pageset_init(pcp);
4892         pageset_set_high_and_batch(zone, pcp);
4893 }
4894 
4895 static void __meminit setup_zone_pageset(struct zone *zone)
4896 {
4897         int cpu;
4898         zone->pageset = alloc_percpu(struct per_cpu_pageset);
4899         for_each_possible_cpu(cpu)
4900                 zone_pageset_init(zone, cpu);
4901 }
4902 
4903 /*
4904  * Allocate per cpu pagesets and initialize them.
4905  * Before this call only boot pagesets were available.
4906  */
4907 void __init setup_per_cpu_pageset(void)
4908 {
4909         struct zone *zone;
4910 
4911         for_each_populated_zone(zone)
4912                 setup_zone_pageset(zone);
4913 }
4914 
4915 static noinline __init_refok
4916 int zone_wait_table_init(struct zone *zone, unsigned long zone_size_pages)
4917 {
4918         int i;
4919         size_t alloc_size;
4920 
4921         /*
4922          * The per-page waitqueue mechanism uses hashed waitqueues
4923          * per zone.
4924          */
4925         zone->wait_table_hash_nr_entries =
4926                  wait_table_hash_nr_entries(zone_size_pages);
4927         zone->wait_table_bits =
4928                 wait_table_bits(zone->wait_table_hash_nr_entries);
4929         alloc_size = zone->wait_table_hash_nr_entries
4930                                         * sizeof(wait_queue_head_t);
4931 
4932         if (!slab_is_available()) {
4933                 zone->wait_table = (wait_queue_head_t *)
4934                         memblock_virt_alloc_node_nopanic(
4935                                 alloc_size, zone->zone_pgdat->node_id);
4936         } else {
4937                 /*
4938                  * This case means that a zone whose size was 0 gets new memory
4939                  * via memory hot-add.
4940                  * But it may be the case that a new node was hot-added.  In
4941                  * this case vmalloc() will not be able to use this new node's
4942                  * memory - this wait_table must be initialized to use this new
4943                  * node itself as well.
4944                  * To use this new node's memory, further consideration will be
4945                  * necessary.
4946                  */
4947                 zone->wait_table = vmalloc(alloc_size);
4948         }
4949         if (!zone->wait_table)
4950                 return -ENOMEM;
4951 
4952         for (i = 0; i < zone->wait_table_hash_nr_entries; ++i)
4953                 init_waitqueue_head(zone->wait_table + i);
4954 
4955         return 0;
4956 }
4957 
4958 static __meminit void zone_pcp_init(struct zone *zone)
4959 {
4960         /*
4961          * per cpu subsystem is not up at this point. The following code
4962          * relies on the ability of the linker to provide the
4963          * offset of a (static) per cpu variable into the per cpu area.
4964          */
4965         zone->pageset = &boot_pageset;
4966 
4967         if (populated_zone(zone))
4968                 printk(KERN_DEBUG "  %s zone: %lu pages, LIFO batch:%u\n",
4969                         zone->name, zone->present_pages,
4970                                          zone_batchsize(zone));
4971 }
4972 
4973 int __meminit init_currently_empty_zone(struct zone *zone,
4974                                         unsigned long zone_start_pfn,
4975                                         unsigned long size)
4976 {
4977         struct pglist_data *pgdat = zone->zone_pgdat;
4978         int ret;
4979         ret = zone_wait_table_init(zone, size);
4980         if (ret)
4981                 return ret;
4982         pgdat->nr_zones = zone_idx(zone) + 1;
4983 
4984         zone->zone_start_pfn = zone_start_pfn;
4985 
4986         mminit_dprintk(MMINIT_TRACE, "memmap_init",
4987                         "Initialising map node %d zone %lu pfns %lu -> %lu\n",
4988                         pgdat->node_id,
4989                         (unsigned long)zone_idx(zone),
4990                         zone_start_pfn, (zone_start_pfn + size));
4991 
4992         zone_init_free_lists(zone);
4993 
4994         return 0;
4995 }
4996 
4997 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
4998 #ifndef CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID
4999 
5000 /*
5001  * Required by SPARSEMEM. Given a PFN, return what node the PFN is on.
5002  */
5003 int __meminit __early_pfn_to_nid(unsigned long pfn,
5004                                         struct mminit_pfnnid_cache *state)
5005 {
5006         unsigned long start_pfn, end_pfn;
5007         int nid;
5008 
5009         if (state->last_start <= pfn && pfn < state->last_end)
5010                 return state->last_nid;
5011 
5012         nid = memblock_search_pfn_nid(pfn, &start_pfn, &end_pfn);
5013         if (nid != -1) {
5014                 state->last_start = start_pfn;
5015                 state->last_end = end_pfn;
5016                 state->last_nid = nid;
5017         }
5018 
5019         return nid;
5020 }
5021 #endif /* CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID */
5022 
5023 /**
5024  * free_bootmem_with_active_regions - Call memblock_free_early_nid for each active range
5025  * @nid: The node to free memory on. If MAX_NUMNODES, all nodes are freed.
5026  * @max_low_pfn: The highest PFN that will be passed to memblock_free_early_nid
5027  *
5028  * If an architecture guarantees that all ranges registered contain no holes
5029  * and may be freed, this this function may be used instead of calling
5030  * memblock_free_early_nid() manually.
5031  */
5032 void __init free_bootmem_with_active_regions(int nid, unsigned long max_low_pfn)
5033 {
5034         unsigned long start_pfn, end_pfn;
5035         int i, this_nid;
5036 
5037         for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, &this_nid) {
5038                 start_pfn = min(start_pfn, max_low_pfn);
5039                 end_pfn = min(end_pfn, max_low_pfn);
5040 
5041                 if (start_pfn < end_pfn)
5042                         memblock_free_early_nid(PFN_PHYS(start_pfn),
5043                                         (end_pfn - start_pfn) << PAGE_SHIFT,
5044                                         this_nid);
5045         }
5046 }
5047 
5048 /**
5049  * sparse_memory_present_with_active_regions - Call memory_present for each active range
5050  * @nid: The node to call memory_present for. If MAX_NUMNODES, all nodes will be used.
5051  *
5052  * If an architecture guarantees that all ranges registered contain no holes and may
5053  * be freed, this function may be used instead of calling memory_present() manually.
5054  */
5055 void __init sparse_memory_present_with_active_regions(int nid)
5056 {
5057         unsigned long start_pfn, end_pfn;
5058         int i, this_nid;
5059 
5060         for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, &this_nid)
5061                 memory_present(this_nid, start_pfn, end_pfn);
5062 }
5063 
5064 /**
5065  * get_pfn_range_for_nid - Return the start and end page frames for a node
5066  * @nid: The nid to return the range for. If MAX_NUMNODES, the min and max PFN are returned.
5067  * @start_pfn: Passed by reference. On return, it will have the node start_pfn.
5068  * @end_pfn: Passed by reference. On return, it will have the node end_pfn.
5069  *
5070  * It returns the start and end page frame of a node based on information
5071  * provided by memblock_set_node(). If called for a node
5072  * with no available memory, a warning is printed and the start and end
5073  * PFNs will be 0.
5074  */
5075 void __meminit get_pfn_range_for_nid(unsigned int nid,
5076                         unsigned long *start_pfn, unsigned long *end_pfn)
5077 {
5078         unsigned long this_start_pfn, this_end_pfn;
5079         int i;
5080 
5081         *start_pfn = -1UL;
5082         *end_pfn = 0;
5083 
5084         for_each_mem_pfn_range(i, nid, &this_start_pfn, &this_end_pfn, NULL) {
5085                 *start_pfn = min(*start_pfn, this_start_pfn);
5086                 *end_pfn = max(*end_pfn, this_end_pfn);
5087         }
5088 
5089         if (*start_pfn == -1UL)
5090                 *start_pfn = 0;
5091 }
5092 
5093 /*
5094  * This finds a zone that can be used for ZONE_MOVABLE pages. The
5095  * assumption is made that zones within a node are ordered in monotonic
5096  * increasing memory addresses so that the "highest" populated zone is used
5097  */
5098 static void __init find_usable_zone_for_movable(void)
5099 {
5100         int zone_index;
5101         for (zone_index = MAX_NR_ZONES - 1; zone_index >= 0; zone_index--) {
5102                 if (zone_index == ZONE_MOVABLE)
5103                         continue;
5104 
5105                 if (arch_zone_highest_possible_pfn[zone_index] >
5106                                 arch_zone_lowest_possible_pfn[zone_index])
5107                         break;
5108         }
5109 
5110         VM_BUG_ON(zone_index == -1);
5111         movable_zone = zone_index;
5112 }
5113 
5114 /*
5115  * The zone ranges provided by the architecture do not include ZONE_MOVABLE
5116  * because it is sized independent of architecture. Unlike the other zones,
5117  * the starting point for ZONE_MOVABLE is not fixed. It may be different
5118  * in each node depending on the size of each node and how evenly kernelcore
5119  * is distributed. This helper function adjusts the zone ranges
5120  * provided by the architecture for a given node by using the end of the
5121  * highest usable zone for ZONE_MOVABLE. This preserves the assumption that
5122  * zones within a node are in order of monotonic increases memory addresses
5123  */
5124 static void __meminit adjust_zone_range_for_zone_movable(int nid,
5125                                         unsigned long zone_type,
5126                                         unsigned long node_start_pfn,
5127                                         unsigned long node_end_pfn,
5128                                         unsigned long *zone_start_pfn,
5129                                         unsigned long *zone_end_pfn)
5130 {
5131         /* Only adjust if ZONE_MOVABLE is on this node */
5132         if (zone_movable_pfn[nid]) {
5133                 /* Size ZONE_MOVABLE */
5134                 if (zone_type == ZONE_MOVABLE) {
5135                         *zone_start_pfn = zone_movable_pfn[nid];
5136                         *zone_end_pfn = min(node_end_pfn,
5137                                 arch_zone_highest_possible_pfn[movable_zone]);
5138 
5139                 /* Check if this whole range is within ZONE_MOVABLE */
5140                 } else if (*zone_start_pfn >= zone_movable_pfn[nid])
5141                         *zone_start_pfn = *zone_end_pfn;
5142         }
5143 }
5144 
5145 /*
5146  * Return the number of pages a zone spans in a node, including holes
5147  * present_pages = zone_spanned_pages_in_node() - zone_absent_pages_in_node()
5148  */
5149 static unsigned long __meminit zone_spanned_pages_in_node(int nid,
5150                                         unsigned long zone_type,
5151                                         unsigned long node_start_pfn,
5152                                         unsigned long node_end_pfn,
5153                                         unsigned long *zone_start_pfn,
5154                                         unsigned long *zone_end_pfn,
5155                                         unsigned long *ignored)
5156 {
5157         /* When hotadd a new node from cpu_up(), the node should be empty */
5158         if (!node_start_pfn && !node_end_pfn)
5159                 return 0;
5160 
5161         /* Get the start and end of the zone */
5162         *zone_start_pfn = arch_zone_lowest_possible_pfn[zone_type];
5163         *zone_end_pfn = arch_zone_highest_possible_pfn[zone_type];
5164         adjust_zone_range_for_zone_movable(nid, zone_type,
5165                                 node_start_pfn, node_end_pfn,
5166                                 zone_start_pfn, zone_end_pfn);
5167 
5168         /* Check that this node has pages within the zone's required range */
5169         if (*zone_end_pfn < node_start_pfn || *zone_start_pfn > node_end_pfn)
5170                 return 0;
5171 
5172         /* Move the zone boundaries inside the node if necessary */
5173         *zone_end_pfn = min(*zone_end_pfn, node_end_pfn);
5174         *zone_start_pfn = max(*zone_start_pfn, node_start_pfn);
5175 
5176         /* Return the spanned pages */
5177         return *zone_end_pfn - *zone_start_pfn;
5178 }
5179 
5180 /*
5181  * Return the number of holes in a range on a node. If nid is MAX_NUMNODES,
5182  * then all holes in the requested range will be accounted for.
5183  */
5184 unsigned long __meminit __absent_pages_in_range(int nid,
5185                                 unsigned long range_start_pfn,
5186                                 unsigned long range_end_pfn)
5187 {
5188         unsigned long nr_absent = range_end_pfn - range_start_pfn;
5189         unsigned long start_pfn, end_pfn;
5190         int i;
5191 
5192         for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
5193                 start_pfn = clamp(start_pfn, range_start_pfn, range_end_pfn);
5194                 end_pfn = clamp(end_pfn, range_start_pfn, range_end_pfn);
5195                 nr_absent -= end_pfn - start_pfn;
5196         }
5197         return nr_absent;
5198 }
5199 
5200 /**
5201  * absent_pages_in_range - Return number of page frames in holes within a range
5202  * @start_pfn: The start PFN to start searching for holes
5203  * @end_pfn: The end PFN to stop searching for holes
5204  *
5205  * It returns the number of pages frames in memory holes within a range.
5206  */
5207 unsigned long __init absent_pages_in_range(unsigned long start_pfn,
5208                                                         unsigned long end_pfn)
5209 {
5210         return __absent_pages_in_range(MAX_NUMNODES, start_pfn, end_pfn);
5211 }
5212 
5213 /* Return the number of page frames in holes in a zone on a node */
5214 static unsigned long __meminit zone_absent_pages_in_node(int nid,
5215                                         unsigned long zone_type,
5216                                         unsigned long node_start_pfn,
5217                                         unsigned long node_end_pfn,
5218                                         unsigned long *ignored)
5219 {
5220         unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type];
5221         unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type];
5222         unsigned long zone_start_pfn, zone_end_pfn;
5223         unsigned long nr_absent;
5224 
5225         /* When hotadd a new node from cpu_up(), the node should be empty */
5226         if (!node_start_pfn && !node_end_pfn)
5227                 return 0;
5228 
5229         zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high);
5230         zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high);
5231 
5232         adjust_zone_range_for_zone_movable(nid, zone_type,
5233                         node_start_pfn, node_end_pfn,
5234                         &zone_start_pfn, &zone_end_pfn);
5235         nr_absent = __absent_pages_in_range(nid, zone_start_pfn, zone_end_pfn);
5236 
5237         /*
5238          * ZONE_MOVABLE handling.
5239          * Treat pages to be ZONE_MOVABLE in ZONE_NORMAL as absent pages
5240          * and vice versa.
5241          */
5242         if (zone_movable_pfn[nid]) {
5243                 if (mirrored_kernelcore) {
5244                         unsigned long start_pfn, end_pfn;
5245                         struct memblock_region *r;
5246 
5247                         for_each_memblock(memory, r) {
5248                                 start_pfn = clamp(memblock_region_memory_base_pfn(r),
5249                                                   zone_start_pfn, zone_end_pfn);
5250                                 end_pfn = clamp(memblock_region_memory_end_pfn(r),
5251                                                 zone_start_pfn, zone_end_pfn);
5252 
5253                                 if (zone_type == ZONE_MOVABLE &&
5254                                     memblock_is_mirror(r))
5255                                         nr_absent += end_pfn - start_pfn;
5256 
5257                                 if (zone_type == ZONE_NORMAL &&
5258                                     !memblock_is_mirror(r))
5259                                         nr_absent += end_pfn - start_pfn;
5260                         }
5261                 } else {
5262                         if (zone_type == ZONE_NORMAL)
5263                                 nr_absent += node_end_pfn - zone_movable_pfn[nid];
5264                 }
5265         }
5266 
5267         return nr_absent;
5268 }
5269 
5270 #else /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
5271 static inline unsigned long __meminit zone_spanned_pages_in_node(int nid,
5272                                         unsigned long zone_type,
5273                                         unsigned long node_start_pfn,
5274                                         unsigned long node_end_pfn,
5275                                         unsigned long *zone_start_pfn,
5276                                         unsigned long *zone_end_pfn,
5277                                         unsigned long *zones_size)
5278 {
5279         unsigned int zone;
5280 
5281         *zone_start_pfn = node_start_pfn;
5282         for (zone = 0; zone < zone_type; zone++)
5283                 *zone_start_pfn += zones_size[zone];
5284 
5285         *zone_end_pfn = *zone_start_pfn + zones_size[zone_type];
5286 
5287         return zones_size[zone_type];
5288 }
5289 
5290 static inline unsigned long __meminit zone_absent_pages_in_node(int nid,
5291                                                 unsigned long zone_type,
5292                                                 unsigned long node_start_pfn,
5293                                                 unsigned long node_end_pfn,
5294                                                 unsigned long *zholes_size)
5295 {
5296         if (!zholes_size)
5297                 return 0;
5298 
5299         return zholes_size[zone_type];
5300 }
5301 
5302 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
5303 
5304 static void __meminit calculate_node_totalpages(struct pglist_data *pgdat,
5305                                                 unsigned long node_start_pfn,
5306                                                 unsigned long node_end_pfn,
5307                                                 unsigned long *zones_size,
5308                                                 unsigned long *zholes_size)
5309 {
5310         unsigned long realtotalpages = 0, totalpages = 0;
5311         enum zone_type i;
5312 
5313         for (i = 0; i < MAX_NR_ZONES; i++) {
5314                 struct zone *zone = pgdat->node_zones + i;
5315                 unsigned long zone_start_pfn, zone_end_pfn;
5316                 unsigned long size, real_size;
5317 
5318                 size = zone_spanned_pages_in_node(pgdat->node_id, i,
5319                                                   node_start_pfn,
5320                                                   node_end_pfn,
5321                                                   &zone_start_pfn,
5322                                                   &zone_end_pfn,
5323                                                   zones_size);
5324                 real_size = size - zone_absent_pages_in_node(pgdat->node_id, i,
5325                                                   node_start_pfn, node_end_pfn,
5326                                                   zholes_size);
5327                 if (size)
5328                         zone->zone_start_pfn = zone_start_pfn;
5329                 else
5330                         zone->zone_start_pfn = 0;
5331                 zone->spanned_pages = size;
5332                 zone->present_pages = real_size;
5333 
5334                 totalpages += size;
5335                 realtotalpages += real_size;
5336         }
5337 
5338         pgdat->node_spanned_pages = totalpages;
5339         pgdat->node_present_pages = realtotalpages;
5340         printk(KERN_DEBUG "On node %d totalpages: %lu\n", pgdat->node_id,
5341                                                         realtotalpages);
5342 }
5343 
5344 #ifndef CONFIG_SPARSEMEM
5345 /*
5346  * Calculate the size of the zone->blockflags rounded to an unsigned long
5347  * Start by making sure zonesize is a multiple of pageblock_order by rounding
5348  * up. Then use 1 NR_PAGEBLOCK_BITS worth of bits per pageblock, finally
5349  * round what is now in bits to nearest long in bits, then return it in
5350  * bytes.
5351  */
5352 static unsigned long __init usemap_size(unsigned long zone_start_pfn, unsigned long zonesize)
5353 {
5354         unsigned long usemapsize;
5355 
5356         zonesize += zone_start_pfn & (pageblock_nr_pages-1);
5357         usemapsize = roundup(zonesize, pageblock_nr_pages);
5358         usemapsize = usemapsize >> pageblock_order;
5359         usemapsize *= NR_PAGEBLOCK_BITS;
5360         usemapsize = roundup(usemapsize, 8 * sizeof(unsigned long));
5361 
5362         return usemapsize / 8;
5363 }
5364 
5365 static void __init setup_usemap(struct pglist_data *pgdat,
5366                                 struct zone *zone,
5367                                 unsigned long zone_start_pfn,
5368                                 unsigned long zonesize)
5369 {
5370         unsigned long usemapsize = usemap_size(zone_start_pfn, zonesize);
5371         zone->pageblock_flags = NULL;
5372         if (usemapsize)
5373                 zone->pageblock_flags =
5374                         memblock_virt_alloc_node_nopanic(usemapsize,
5375                                                          pgdat->node_id);
5376 }
5377 #else
5378 static inline void setup_usemap(struct pglist_data *pgdat, struct zone *zone,
5379                                 unsigned long zone_start_pfn, unsigned long zonesize) {}
5380 #endif /* CONFIG_SPARSEMEM */
5381 
5382 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
5383 
5384 /* Initialise the number of pages represented by NR_PAGEBLOCK_BITS */
5385 void __paginginit set_pageblock_order(void)
5386 {
5387         unsigned int order;
5388 
5389         /* Check that pageblock_nr_pages has not already been setup */
5390         if (pageblock_order)
5391                 return;
5392 
5393         if (HPAGE_SHIFT > PAGE_SHIFT)
5394                 order = HUGETLB_PAGE_ORDER;
5395         else
5396                 order = MAX_ORDER - 1;
5397 
5398         /*
5399          * Assume the largest contiguous order of interest is a huge page.
5400          * This value may be variable depending on boot parameters on IA64 and
5401          * powerpc.
5402          */
5403         pageblock_order = order;
5404 }
5405 #else /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
5406 
5407 /*
5408  * When CONFIG_HUGETLB_PAGE_SIZE_VARIABLE is not set, set_pageblock_order()
5409  * is unused as pageblock_order is set at compile-time. See
5410  * include/linux/pageblock-flags.h for the values of pageblock_order based on
5411  * the kernel config
5412  */
5413 void __paginginit set_pageblock_order(void)
5414 {
5415 }
5416 
5417 #endif /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
5418 
5419 static unsigned long __paginginit calc_memmap_size(unsigned long spanned_pages,
5420                                                    unsigned long present_pages)
5421 {
5422         unsigned long pages = spanned_pages;
5423 
5424         /*
5425          * Provide a more accurate estimation if there are holes within
5426          * the zone and SPARSEMEM is in use. If there are holes within the
5427          * zone, each populated memory region may cost us one or two extra
5428          * memmap pages due to alignment because memmap pages for each
5429          * populated regions may not naturally algined on page boundary.
5430          * So the (present_pages >> 4) heuristic is a tradeoff for that.
5431          */
5432         if (spanned_pages > present_pages + (present_pages >> 4) &&
5433             IS_ENABLED(CONFIG_SPARSEMEM))
5434                 pages = present_pages;
5435 
5436         return PAGE_ALIGN(pages * sizeof(struct page)) >> PAGE_SHIFT;
5437 }
5438 
5439 /*
5440  * Set up the zone data structures:
5441  *   - mark all pages reserved
5442  *   - mark all memory queues empty
5443  *   - clear the memory bitmaps
5444  *
5445  * NOTE: pgdat should get zeroed by caller.
5446  */
5447 static void __paginginit free_area_init_core(struct pglist_data *pgdat)
5448 {
5449         enum zone_type j;
5450         int nid = pgdat->node_id;
5451         int ret;
5452 
5453         pgdat_resize_init(pgdat);
5454 #ifdef CONFIG_NUMA_BALANCING
5455         spin_lock_init(&pgdat->numabalancing_migrate_lock);
5456         pgdat->numabalancing_migrate_nr_pages = 0;
5457         pgdat->numabalancing_migrate_next_window = jiffies;
5458 #endif
5459 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5460         spin_lock_init(&pgdat->split_queue_lock);
5461         INIT_LIST_HEAD(&pgdat->split_queue);
5462         pgdat->split_queue_len = 0;
5463 #endif
5464         init_waitqueue_head(&pgdat->kswapd_wait);
5465         init_waitqueue_head(&pgdat->pfmemalloc_wait);
5466 #ifdef CONFIG_COMPACTION
5467         init_waitqueue_head(&pgdat->kcompactd_wait);
5468 #endif
5469         pgdat_page_ext_init(pgdat);
5470 
5471         for (j = 0; j < MAX_NR_ZONES; j++) {
5472                 struct zone *zone = pgdat->node_zones + j;
5473                 unsigned long size, realsize, freesize, memmap_pages;
5474                 unsigned long zone_start_pfn = zone->zone_start_pfn;
5475 
5476                 size = zone->spanned_pages;
5477                 realsize = freesize = zone->present_pages;
5478 
5479                 /*
5480                  * Adjust freesize so that it accounts for how much memory
5481                  * is used by this zone for memmap. This affects the watermark
5482                  * and per-cpu initialisations
5483                  */
5484                 memmap_pages = calc_memmap_size(size, realsize);
5485                 if (!is_highmem_idx(j)) {
5486                         if (freesize >= memmap_pages) {
5487                                 freesize -= memmap_pages;
5488                                 if (memmap_pages)
5489                                         printk(KERN_DEBUG
5490                                                "  %s zone: %lu pages used for memmap\n",
5491                                                zone_names[j], memmap_pages);
5492                         } else
5493                                 pr_warn("  %s zone: %lu pages exceeds freesize %lu\n",
5494                                         zone_names[j], memmap_pages, freesize);
5495                 }
5496 
5497                 /* Account for reserved pages */
5498                 if (j == 0 && freesize > dma_reserve) {
5499                         freesize -= dma_reserve;
5500                         printk(KERN_DEBUG "  %s zone: %lu pages reserved\n",
5501                                         zone_names[0], dma_reserve);
5502                 }
5503 
5504                 if (!is_highmem_idx(j))
5505                         nr_kernel_pages += freesize;
5506                 /* Charge for highmem memmap if there are enough kernel pages */
5507                 else if (nr_kernel_pages > memmap_pages * 2)
5508                         nr_kernel_pages -= memmap_pages;
5509                 nr_all_pages += freesize;
5510 
5511                 /*
5512                  * Set an approximate value for lowmem here, it will be adjusted
5513                  * when the bootmem allocator frees pages into the buddy system.
5514                  * And all highmem pages will be managed by the buddy system.
5515                  */
5516                 zone->managed_pages = is_highmem_idx(j) ? realsize : freesize;
5517 #ifdef CONFIG_NUMA
5518                 zone->node = nid;
5519                 zone->min_unmapped_pages = (freesize*sysctl_min_unmapped_ratio)
5520                                                 / 100;
5521                 zone->min_slab_pages = (freesize * sysctl_min_slab_ratio) / 100;
5522 #endif
5523                 zone->name = zone_names[j];
5524                 spin_lock_init(&zone->lock);
5525                 spin_lock_init(&zone->lru_lock);
5526                 zone_seqlock_init(zone);
5527                 zone->zone_pgdat = pgdat;
5528                 zone_pcp_init(zone);
5529 
5530                 /* For bootup, initialized properly in watermark setup */
5531                 mod_zone_page_state(zone, NR_ALLOC_BATCH, zone->managed_pages);
5532 
5533                 lruvec_init(&zone->lruvec);
5534                 if (!size)
5535                         continue;
5536 
5537                 set_pageblock_order();
5538                 setup_usemap(pgdat, zone, zone_start_pfn, size);
5539                 ret = init_currently_empty_zone(zone, zone_start_pfn, size);
5540                 BUG_ON(ret);
5541                 memmap_init(size, nid, j, zone_start_pfn);
5542         }
5543 }
5544 
5545 static void __init_refok alloc_node_mem_map(struct pglist_data *pgdat)
5546 {
5547         unsigned long __maybe_unused start = 0;
5548         unsigned long __maybe_unused offset = 0;
5549 
5550         /* Skip empty nodes */
5551         if (!pgdat->node_spanned_pages)
5552                 return;
5553 
5554 #ifdef CONFIG_FLAT_NODE_MEM_MAP
5555         start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1);
5556         offset = pgdat->node_start_pfn - start;
5557         /* ia64 gets its own node_mem_map, before this, without bootmem */
5558         if (!pgdat->node_mem_map) {
5559                 unsigned long size, end;
5560                 struct page *map;
5561 
5562                 /*
5563                  * The zone's endpoints aren't required to be MAX_ORDER
5564                  * aligned but the node_mem_map endpoints must be in order
5565                  * for the buddy allocator to function correctly.
5566                  */
5567                 end = pgdat_end_pfn(pgdat);
5568                 end = ALIGN(end, MAX_ORDER_NR_PAGES);
5569                 size =  (end - start) * sizeof(struct page);
5570                 map = alloc_remap(pgdat->node_id, size);
5571                 if (!map)
5572                         map = memblock_virt_alloc_node_nopanic(size,
5573                                                                pgdat->node_id);
5574                 pgdat->node_mem_map = map + offset;
5575         }
5576 #ifndef CONFIG_NEED_MULTIPLE_NODES
5577         /*
5578          * With no DISCONTIG, the global mem_map is just set as node 0's
5579          */
5580         if (pgdat == NODE_DATA(0)) {
5581                 mem_map = NODE_DATA(0)->node_mem_map;
5582 #if defined(CONFIG_HAVE_MEMBLOCK_NODE_MAP) || defined(CONFIG_FLATMEM)
5583                 if (page_to_pfn(mem_map) != pgdat->node_start_pfn)
5584                         mem_map -= offset;
5585 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
5586         }
5587 #endif
5588 #endif /* CONFIG_FLAT_NODE_MEM_MAP */
5589 }
5590 
5591 void __paginginit free_area_init_node(int nid, unsigned long *zones_size,
5592                 unsigned long node_start_pfn, unsigned long *zholes_size)
5593 {
5594         pg_data_t *pgdat = NODE_DATA(nid);
5595         unsigned long start_pfn = 0;
5596         unsigned long end_pfn = 0;
5597 
5598         /* pg_data_t should be reset to zero when it's allocated */
5599         WARN_ON(pgdat->nr_zones || pgdat->classzone_idx);
5600 
5601         reset_deferred_meminit(pgdat);
5602         pgdat->node_id = nid;
5603         pgdat->node_start_pfn = node_start_pfn;
5604 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
5605         get_pfn_range_for_nid(nid, &start_pfn, &end_pfn);
5606         pr_info("Initmem setup node %d [mem %#018Lx-%#018Lx]\n", nid,
5607                 (u64)start_pfn << PAGE_SHIFT,
5608                 end_pfn ? ((u64)end_pfn << PAGE_SHIFT) - 1 : 0);
5609 #else
5610         start_pfn = node_start_pfn;
5611 #endif
5612         calculate_node_totalpages(pgdat, start_pfn, end_pfn,
5613                                   zones_size, zholes_size);
5614 
5615         alloc_node_mem_map(pgdat);
5616 #ifdef CONFIG_FLAT_NODE_MEM_MAP
5617         printk(KERN_DEBUG "free_area_init_node: node %d, pgdat %08lx, node_mem_map %08lx\n",
5618                 nid, (unsigned long)pgdat,
5619                 (unsigned long)pgdat->node_mem_map);
5620 #endif
5621 
5622         free_area_init_core(pgdat);
5623 }
5624 
5625 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
5626 
5627 #if MAX_NUMNODES > 1
5628 /*
5629  * Figure out the number of possible node ids.
5630  */
5631 void __init setup_nr_node_ids(void)
5632 {
5633         unsigned int highest;
5634 
5635         highest = find_last_bit(node_possible_map.bits, MAX_NUMNODES);
5636         nr_node_ids = highest + 1;
5637 }
5638 #endif
5639 
5640 /**
5641  * node_map_pfn_alignment - determine the maximum internode alignment
5642  *
5643  * This function should be called after node map is populated and sorted.
5644  * It calculates the maximum power of two alignment which can distinguish
5645  * all the nodes.
5646  *
5647  * For example, if all nodes are 1GiB and aligned to 1GiB, the return value
5648  * would indicate 1GiB alignment with (1 << (30 - PAGE_SHIFT)).  If the
5649  * nodes are shifted by 256MiB, 256MiB.  Note that if only the last node is
5650  * shifted, 1GiB is enough and this function will indicate so.
5651  *
5652  * This is used to test whether pfn -> nid mapping of the chosen memory
5653  * model has fine enough granularity to avoid incorrect mapping for the
5654  * populated node map.
5655  *
5656  * Returns the determined alignment in pfn's.  0 if there is no alignment
5657  * requirement (single node).
5658  */
5659 unsigned long __init node_map_pfn_alignment(void)
5660 {
5661         unsigned long accl_mask = 0, last_end = 0;
5662         unsigned long start, end, mask;
5663         int last_nid = -1;
5664         int i, nid;
5665 
5666         for_each_mem_pfn_range(i, MAX_NUMNODES, &start, &end, &nid) {
5667                 if (!start || last_nid < 0 || last_nid == nid) {
5668                         last_nid = nid;
5669                         last_end = end;
5670                         continue;
5671                 }
5672 
5673                 /*
5674                  * Start with a mask granular enough to pin-point to the
5675                  * start pfn and tick off bits one-by-one until it becomes
5676                  * too coarse to separate the current node from the last.
5677                  */
5678                 mask = ~((1 << __ffs(start)) - 1);
5679                 while (mask && last_end <= (start & (mask << 1)))
5680                         mask <<= 1;
5681 
5682                 /* accumulate all internode masks */
5683                 accl_mask |= mask;
5684         }
5685 
5686         /* convert mask to number of pages */
5687         return ~accl_mask + 1;
5688 }
5689 
5690 /* Find the lowest pfn for a node */
5691 static unsigned long __init find_min_pfn_for_node(int nid)
5692 {
5693         unsigned long min_pfn = ULONG_MAX;
5694         unsigned long start_pfn;
5695         int i;
5696 
5697         for_each_mem_pfn_range(i, nid, &start_pfn, NULL, NULL)
5698                 min_pfn = min(min_pfn, start_pfn);
5699 
5700         if (min_pfn == ULONG_MAX) {
5701                 pr_warn("Could not find start_pfn for node %d\n", nid);
5702                 return 0;
5703         }
5704 
5705         return min_pfn;
5706 }
5707 
5708 /**
5709  * find_min_pfn_with_active_regions - Find the minimum PFN registered
5710  *
5711  * It returns the minimum PFN based on information provided via
5712  * memblock_set_node().
5713  */
5714 unsigned long __init find_min_pfn_with_active_regions(void)
5715 {
5716         return find_min_pfn_for_node(MAX_NUMNODES);
5717 }
5718 
5719 /*
5720  * early_calculate_totalpages()
5721  * Sum pages in active regions for movable zone.
5722  * Populate N_MEMORY for calculating usable_nodes.
5723  */
5724 static unsigned long __init early_calculate_totalpages(void)
5725 {
5726         unsigned long totalpages = 0;
5727         unsigned long start_pfn, end_pfn;
5728         int i, nid;
5729 
5730         for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
5731                 unsigned long pages = end_pfn - start_pfn;
5732 
5733                 totalpages += pages;
5734                 if (pages)
5735                         node_set_state(nid, N_MEMORY);
5736         }
5737         return totalpages;
5738 }
5739 
5740 /*
5741  * Find the PFN the Movable zone begins in each node. Kernel memory
5742  * is spread evenly between nodes as long as the nodes have enough
5743  * memory. When they don't, some nodes will have more kernelcore than
5744  * others
5745  */
5746 static void __init find_zone_movable_pfns_for_nodes(void)
5747 {
5748         int i, nid;
5749         unsigned long usable_startpfn;
5750         unsigned long kernelcore_node, kernelcore_remaining;
5751         /* save the state before borrow the nodemask */
5752         nodemask_t saved_node_state = node_states[N_MEMORY];
5753         unsigned long totalpages = early_calculate_totalpages();
5754         int usable_nodes = nodes_weight(node_states[N_MEMORY]);
5755         struct memblock_region *r;
5756 
5757         /* Need to find movable_zone earlier when movable_node is specified. */
5758         find_usable_zone_for_movable();
5759 
5760         /*
5761          * If movable_node is specified, ignore kernelcore and movablecore
5762          * options.
5763          */
5764         if (movable_node_is_enabled()) {
5765                 for_each_memblock(memory, r) {
5766                         if (!memblock_is_hotpluggable(r))
5767                                 continue;
5768 
5769                         nid = r->nid;
5770 
5771                         usable_startpfn = PFN_DOWN(r->base);
5772                         zone_movable_pfn[nid] = zone_movable_pfn[nid] ?
5773                                 min(usable_startpfn, zone_movable_pfn[nid]) :
5774                                 usable_startpfn;
5775                 }
5776 
5777                 goto out2;
5778         }
5779 
5780         /*
5781          * If kernelcore=mirror is specified, ignore movablecore option
5782          */
5783         if (mirrored_kernelcore) {
5784                 bool mem_below_4gb_not_mirrored = false;
5785 
5786                 for_each_memblock(memory, r) {
5787                         if (memblock_is_mirror(r))
5788                                 continue;
5789 
5790                         nid = r->nid;
5791 
5792                         usable_startpfn = memblock_region_memory_base_pfn(r);
5793 
5794                         if (usable_startpfn < 0x100000) {
5795                                 mem_below_4gb_not_mirrored = true;
5796                                 continue;
5797                         }
5798 
5799                         zone_movable_pfn[nid] = zone_movable_pfn[nid] ?
5800                                 min(usable_startpfn, zone_movable_pfn[nid]) :
5801                                 usable_startpfn;
5802                 }
5803 
5804                 if (mem_below_4gb_not_mirrored)
5805                         pr_warn("This configuration results in unmirrored kernel memory.");
5806 
5807                 goto out2;
5808         }
5809 
5810         /*
5811          * If movablecore=nn[KMG] was specified, calculate what size of
5812          * kernelcore that corresponds so that memory usable for
5813          * any allocation type is evenly spread. If both kernelcore
5814          * and movablecore are specified, then the value of kernelcore
5815          * will be used for required_kernelcore if it's greater than
5816          * what movablecore would have allowed.
5817          */
5818         if (required_movablecore) {
5819                 unsigned long corepages;
5820 
5821                 /*
5822                  * Round-up so that ZONE_MOVABLE is at least as large as what
5823                  * was requested by the user
5824                  */
5825                 required_movablecore =
5826                         roundup(required_movablecore, MAX_ORDER_NR_PAGES);
5827                 required_movablecore = min(totalpages, required_movablecore);
5828                 corepages = totalpages - required_movablecore;
5829 
5830                 required_kernelcore = max(required_kernelcore, corepages);
5831         }
5832 
5833         /*
5834          * If kernelcore was not specified or kernelcore size is larger
5835          * than totalpages, there is no ZONE_MOVABLE.
5836          */
5837         if (!required_kernelcore || required_kernelcore >= totalpages)
5838                 goto out;
5839 
5840         /* usable_startpfn is the lowest possible pfn ZONE_MOVABLE can be at */
5841         usable_startpfn = arch_zone_lowest_possible_pfn[movable_zone];
5842 
5843 restart:
5844         /* Spread kernelcore memory as evenly as possible throughout nodes */
5845         kernelcore_node = required_kernelcore / usable_nodes;
5846         for_each_node_state(nid, N_MEMORY) {
5847                 unsigned long start_pfn, end_pfn;
5848 
5849                 /*
5850                  * Recalculate kernelcore_node if the division per node
5851                  * now exceeds what is necessary to satisfy the requested
5852                  * amount of memory for the kernel
5853                  */
5854                 if (required_kernelcore < kernelcore_node)
5855                         kernelcore_node = required_kernelcore / usable_nodes;
5856 
5857                 /*
5858                  * As the map is walked, we track how much memory is usable
5859                  * by the kernel using kernelcore_remaining. When it is
5860                  * 0, the rest of the node is usable by ZONE_MOVABLE
5861                  */
5862                 kernelcore_remaining = kernelcore_node;
5863 
5864                 /* Go through each range of PFNs within this node */
5865                 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
5866                         unsigned long size_pages;
5867 
5868                         start_pfn = max(start_pfn, zone_movable_pfn[nid]);
5869                         if (start_pfn >= end_pfn)
5870                                 continue;
5871 
5872                         /* Account for what is only usable for kernelcore */
5873                         if (start_pfn < usable_startpfn) {
5874                                 unsigned long kernel_pages;
5875                                 kernel_pages = min(end_pfn, usable_startpfn)
5876                                                                 - start_pfn;
5877 
5878                                 kernelcore_remaining -= min(kernel_pages,
5879                                                         kernelcore_remaining);
5880                                 required_kernelcore -= min(kernel_pages,
5881                                                         required_kernelcore);
5882 
5883                                 /* Continue if range is now fully accounted */
5884                                 if (end_pfn <= usable_startpfn) {
5885 
5886                                         /*
5887                                          * Push zone_movable_pfn to the end so
5888                                          * that if we have to rebalance
5889                                          * kernelcore across nodes, we will
5890                                          * not double account here
5891                                          */
5892                                         zone_movable_pfn[nid] = end_pfn;
5893                                         continue;
5894                                 }
5895                                 start_pfn = usable_startpfn;
5896                         }
5897 
5898                         /*
5899                          * The usable PFN range for ZONE_MOVABLE is from
5900                          * start_pfn->end_pfn. Calculate size_pages as the
5901                          * number of pages used as kernelcore
5902                          */
5903                         size_pages = end_pfn - start_pfn;
5904                         if (size_pages > kernelcore_remaining)
5905                                 size_pages = kernelcore_remaining;
5906                         zone_movable_pfn[nid] = start_pfn + size_pages;
5907 
5908                         /*
5909                          * Some kernelcore has been met, update counts and
5910                          * break if the kernelcore for this node has been
5911                          * satisfied
5912                          */
5913                         required_kernelcore -= min(required_kernelcore,
5914                                                                 size_pages);
5915                         kernelcore_remaining -= size_pages;
5916                         if (!kernelcore_remaining)
5917                                 break;
5918                 }
5919         }
5920 
5921         /*
5922          * If there is still required_kernelcore, we do another pass with one
5923          * less node in the count. This will push zone_movable_pfn[nid] further
5924          * along on the nodes that still have memory until kernelcore is
5925          * satisfied
5926          */
5927         usable_nodes--;
5928         if (usable_nodes && required_kernelcore > usable_nodes)
5929                 goto restart;
5930 
5931 out2:
5932         /* Align start of ZONE_MOVABLE on all nids to MAX_ORDER_NR_PAGES */
5933         for (nid = 0; nid < MAX_NUMNODES; nid++)
5934                 zone_movable_pfn[nid] =
5935                         roundup(zone_movable_pfn[nid], MAX_ORDER_NR_PAGES);
5936 
5937 out:
5938         /* restore the node_state */
5939         node_states[N_MEMORY] = saved_node_state;
5940 }
5941 
5942 /* Any regular or high memory on that node ? */
5943 static void check_for_memory(pg_data_t *pgdat, int nid)
5944 {
5945         enum zone_type zone_type;
5946 
5947         if (N_MEMORY == N_NORMAL_MEMORY)
5948                 return;
5949 
5950         for (zone_type = 0; zone_type <= ZONE_MOVABLE - 1; zone_type++) {
5951                 struct zone *zone = &pgdat->node_zones[zone_type];
5952                 if (populated_zone(zone)) {
5953                         node_set_state(nid, N_HIGH_MEMORY);
5954                         if (N_NORMAL_MEMORY != N_HIGH_MEMORY &&
5955                             zone_type <= ZONE_NORMAL)
5956                                 node_set_state(nid, N_NORMAL_MEMORY);
5957                         break;
5958                 }
5959         }
5960 }
5961 
5962 /**
5963  * free_area_init_nodes - Initialise all pg_data_t and zone data
5964  * @max_zone_pfn: an array of max PFNs for each zone
5965  *
5966  * This will call free_area_init_node() for each active node in the system.
5967  * Using the page ranges provided by memblock_set_node(), the size of each
5968  * zone in each node and their holes is calculated. If the maximum PFN
5969  * between two adjacent zones match, it is assumed that the zone is empty.
5970  * For example, if arch_max_dma_pfn == arch_max_dma32_pfn, it is assumed
5971  * that arch_max_dma32_pfn has no pages. It is also assumed that a zone
5972  * starts where the previous one ended. For example, ZONE_DMA32 starts
5973  * at arch_max_dma_pfn.
5974  */
5975 void __init free_area_init_nodes(unsigned long *max_zone_pfn)
5976 {
5977         unsigned long start_pfn, end_pfn;
5978         int i, nid;
5979 
5980         /* Record where the zone boundaries are */
5981         memset(arch_zone_lowest_possible_pfn, 0,
5982                                 sizeof(arch_zone_lowest_possible_pfn));
5983         memset(arch_zone_highest_possible_pfn, 0,
5984                                 sizeof(arch_zone_highest_possible_pfn));
5985         arch_zone_lowest_possible_pfn[0] = find_min_pfn_with_active_regions();
5986         arch_zone_highest_possible_pfn[0] = max_zone_pfn[0];
5987         for (i = 1; i < MAX_NR_ZONES; i++) {
5988                 if (i == ZONE_MOVABLE)
5989                         continue;
5990                 arch_zone_lowest_possible_pfn[i] =
5991                         arch_zone_highest_possible_pfn[i-1];
5992                 arch_zone_highest_possible_pfn[i] =
5993                         max(max_zone_pfn[i], arch_zone_lowest_possible_pfn[i]);
5994         }
5995         arch_zone_lowest_possible_pfn[ZONE_MOVABLE] = 0;
5996         arch_zone_highest_possible_pfn[ZONE_MOVABLE] = 0;
5997 
5998         /* Find the PFNs that ZONE_MOVABLE begins at in each node */
5999         memset(zone_movable_pfn, 0, sizeof(zone_movable_pfn));
6000         find_zone_movable_pfns_for_nodes();
6001 
6002         /* Print out the zone ranges */
6003         pr_info("Zone ranges:\n");
6004         for (i = 0; i < MAX_NR_ZONES; i++) {
6005                 if (i == ZONE_MOVABLE)
6006                         continue;
6007                 pr_info("  %-8s ", zone_names[i]);
6008                 if (arch_zone_lowest_possible_pfn[i] ==
6009                                 arch_zone_highest_possible_pfn[i])
6010                         pr_cont("empty\n");
6011                 else
6012                         pr_cont("[mem %#018Lx-%#018Lx]\n",
6013                                 (u64)arch_zone_lowest_possible_pfn[i]
6014                                         << PAGE_SHIFT,
6015                                 ((u64)arch_zone_highest_possible_pfn[i]
6016                                         << PAGE_SHIFT) - 1);
6017         }
6018 
6019         /* Print out the PFNs ZONE_MOVABLE begins at in each node */
6020         pr_info("Movable zone start for each node\n");
6021         for (i = 0; i < MAX_NUMNODES; i++) {
6022                 if (zone_movable_pfn[i])
6023                         pr_info("  Node %d: %#018Lx\n", i,
6024                                (u64)zone_movable_pfn[i] << PAGE_SHIFT);
6025         }
6026 
6027         /* Print out the early node map */
6028         pr_info("Early memory node ranges\n");
6029         for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid)
6030                 pr_info("  node %3d: [mem %#018Lx-%#018Lx]\n", nid,
6031                         (u64)start_pfn << PAGE_SHIFT,
6032                         ((u64)end_pfn << PAGE_SHIFT) - 1);
6033 
6034         /* Initialise every node */
6035         mminit_verify_pageflags_layout();
6036         setup_nr_node_ids();
6037         for_each_online_node(nid) {
6038                 pg_data_t *pgdat = NODE_DATA(nid);
6039                 free_area_init_node(nid, NULL,
6040                                 find_min_pfn_for_node(nid), NULL);
6041 
6042                 /* Any memory on that node */
6043                 if (pgdat->node_present_pages)
6044                         node_set_state(nid, N_MEMORY);
6045                 check_for_memory(pgdat, nid);
6046         }
6047 }
6048 
6049 static int __init cmdline_parse_core(char *p, unsigned long *core)
6050 {
6051         unsigned long long coremem;
6052         if (!p)
6053                 return -EINVAL;
6054 
6055         coremem = memparse(p, &p);
6056         *core = coremem >> PAGE_SHIFT;
6057 
6058         /* Paranoid check that UL is enough for the coremem value */
6059         WARN_ON((coremem >> PAGE_SHIFT) > ULONG_MAX);
6060 
6061         return 0;
6062 }
6063 
6064 /*
6065  * kernelcore=size sets the amount of memory for use for allocations that
6066  * cannot be reclaimed or migrated.
6067  */
6068 static int __init cmdline_parse_kernelcore(char *p)
6069 {
6070         /* parse kernelcore=mirror */
6071         if (parse_option_str(p, "mirror")) {
6072                 mirrored_kernelcore = true;
6073                 return 0;
6074         }
6075 
6076         return cmdline_parse_core(p, &required_kernelcore);
6077 }
6078 
6079 /*
6080  * movablecore=size sets the amount of memory for use for allocations that
6081  * can be reclaimed or migrated.
6082  */
6083 static int __init cmdline_parse_movablecore(char *p)
6084 {
6085         return cmdline_parse_core(p, &required_movablecore);
6086 }
6087 
6088 early_param("kernelcore", cmdline_parse_kernelcore);
6089 early_param("movablecore", cmdline_parse_movablecore);
6090 
6091 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
6092 
6093 void adjust_managed_page_count(struct page *page, long count)
6094 {
6095         spin_lock(&managed_page_count_lock);
6096         page_zone(page)->managed_pages += count;
6097         totalram_pages += count;
6098 #ifdef CONFIG_HIGHMEM
6099         if (PageHighMem(page))
6100                 totalhigh_pages += count;
6101 #endif
6102         spin_unlock(&managed_page_count_lock);
6103 }
6104 EXPORT_SYMBOL(adjust_managed_page_count);
6105 
6106 unsigned long free_reserved_area(void *start, void *end, int poison, char *s)
6107 {
6108         void *pos;
6109         unsigned long pages = 0;
6110 
6111         start = (void *)PAGE_ALIGN((unsigned long)start);
6112         end = (void *)((unsigned long)end & PAGE_MASK);
6113         for (pos = start; pos < end; pos += PAGE_SIZE, pages++) {
6114                 if ((unsigned int)poison <= 0xFF)
6115                         memset(pos, poison, PAGE_SIZE);
6116                 free_reserved_page(virt_to_page(pos));
6117         }
6118 
6119         if (pages && s)
6120                 pr_info("Freeing %s memory: %ldK (%p - %p)\n",
6121                         s, pages << (PAGE_SHIFT - 10), start, end);
6122 
6123         return pages;
6124 }
6125 EXPORT_SYMBOL(free_reserved_area);
6126 
6127 #ifdef  CONFIG_HIGHMEM
6128 void free_highmem_page(struct page *page)
6129 {
6130         __free_reserved_page(page);
6131         totalram_pages++;
6132         page_zone(page)->managed_pages++;
6133         totalhigh_pages++;
6134 }
6135 #endif
6136 
6137 
6138 void __init mem_init_print_info(const char *str)
6139 {
6140         unsigned long physpages, codesize, datasize, rosize, bss_size;
6141         unsigned long init_code_size, init_data_size;
6142 
6143         physpages = get_num_physpages();
6144         codesize = _etext - _stext;
6145         datasize = _edata - _sdata;
6146         rosize = __end_rodata - __start_rodata;
6147         bss_size = __bss_stop - __bss_start;
6148         init_data_size = __init_end - __init_begin;
6149         init_code_size = _einittext - _sinittext;
6150 
6151         /*
6152          * Detect special cases and adjust section sizes accordingly:
6153          * 1) .init.* may be embedded into .data sections
6154          * 2) .init.text.* may be out of [__init_begin, __init_end],
6155          *    please refer to arch/tile/kernel/vmlinux.lds.S.
6156          * 3) .rodata.* may be embedded into .text or .data sections.
6157          */
6158 #define adj_init_size(start, end, size, pos, adj) \
6159         do { \
6160                 if (start <= pos && pos < end && size > adj) \
6161                         size -= adj; \
6162         } while (0)
6163 
6164         adj_init_size(__init_begin, __init_end, init_data_size,
6165                      _sinittext, init_code_size);
6166         adj_init_size(_stext, _etext, codesize, _sinittext, init_code_size);
6167         adj_init_size(_sdata, _edata, datasize, __init_begin, init_data_size);
6168         adj_init_size(_stext, _etext, codesize, __start_rodata, rosize);
6169         adj_init_size(_sdata, _edata, datasize, __start_rodata, rosize);
6170 
6171 #undef  adj_init_size
6172 
6173         pr_info("Memory: %luK/%luK available (%luK kernel code, %luK rwdata, %luK rodata, %luK init, %luK bss, %luK reserved, %luK cma-reserved"
6174 #ifdef  CONFIG_HIGHMEM
6175                 ", %luK highmem"
6176 #endif
6177                 "%s%s)\n",
6178                 nr_free_pages() << (PAGE_SHIFT - 10),
6179                 physpages << (PAGE_SHIFT - 10),
6180                 codesize >> 10, datasize >> 10, rosize >> 10,
6181                 (init_data_size + init_code_size) >> 10, bss_size >> 10,
6182                 (physpages - totalram_pages - totalcma_pages) << (PAGE_SHIFT - 10),
6183                 totalcma_pages << (PAGE_SHIFT - 10),
6184 #ifdef  CONFIG_HIGHMEM
6185                 totalhigh_pages << (PAGE_SHIFT - 10),
6186 #endif
6187                 str ? ", " : "", str ? str : "");
6188 }
6189 
6190 /**
6191  * set_dma_reserve - set the specified number of pages reserved in the first zone
6192  * @new_dma_reserve: The number of pages to mark reserved
6193  *
6194  * The per-cpu batchsize and zone watermarks are determined by managed_pages.
6195  * In the DMA zone, a significant percentage may be consumed by kernel image
6196  * and other unfreeable allocations which can skew the watermarks badly. This
6197  * function may optionally be used to account for unfreeable pages in the
6198  * first zone (e.g., ZONE_DMA). The effect will be lower watermarks and
6199  * smaller per-cpu batchsize.
6200  */
6201 void __init set_dma_reserve(unsigned long new_dma_reserve)
6202 {
6203         dma_reserve = new_dma_reserve;
6204 }
6205 
6206 void __init free_area_init(unsigned long *zones_size)
6207 {
6208         free_area_init_node(0, zones_size,
6209                         __pa(PAGE_OFFSET) >> PAGE_SHIFT, NULL);
6210 }
6211 
6212 static int page_alloc_cpu_notify(struct notifier_block *self,
6213                                  unsigned long action, void *hcpu)
6214 {
6215         int cpu = (unsigned long)hcpu;
6216 
6217         if (action == CPU_DEAD || action == CPU_DEAD_FROZEN) {
6218                 lru_add_drain_cpu(cpu);
6219                 drain_pages(cpu);
6220 
6221                 /*
6222                  * Spill the event counters of the dead processor
6223                  * into the current processors event counters.
6224                  * This artificially elevates the count of the current
6225                  * processor.
6226                  */
6227                 vm_events_fold_cpu(cpu);
6228 
6229                 /*
6230                  * Zero the differential counters of the dead processor
6231                  * so that the vm statistics are consistent.
6232                  *
6233                  * This is only okay since the processor is dead and cannot
6234                  * race with what we are doing.
6235                  */
6236                 cpu_vm_stats_fold(cpu);
6237         }
6238         return NOTIFY_OK;
6239 }
6240 
6241 void __init page_alloc_init(void)
6242 {
6243         hotcpu_notifier(page_alloc_cpu_notify, 0);
6244 }
6245 
6246 /*
6247  * calculate_totalreserve_pages - called when sysctl_lowmem_reserve_ratio
6248  *      or min_free_kbytes changes.
6249  */
6250 static void calculate_totalreserve_pages(void)
6251 {
6252         struct pglist_data *pgdat;
6253         unsigned long reserve_pages = 0;
6254         enum zone_type i, j;
6255 
6256         for_each_online_pgdat(pgdat) {
6257                 for (i = 0; i < MAX_NR_ZONES; i++) {
6258                         struct zone *zone = pgdat->node_zones + i;
6259                         long max = 0;
6260 
6261                         /* Find valid and maximum lowmem_reserve in the zone */
6262                         for (j = i; j < MAX_NR_ZONES; j++) {
6263                                 if (zone->lowmem_reserve[j] > max)
6264                                         max = zone->lowmem_reserve[j];
6265                         }
6266 
6267                         /* we treat the high watermark as reserved pages. */
6268                         max += high_wmark_pages(zone);
6269 
6270                         if (max > zone->managed_pages)
6271                                 max = zone->managed_pages;
6272 
6273                         zone->totalreserve_pages = max;
6274 
6275                         reserve_pages += max;
6276                 }
6277         }
6278         totalreserve_pages = reserve_pages;
6279 }
6280 
6281 /*
6282  * setup_per_zone_lowmem_reserve - called whenever
6283  *      sysctl_lowmem_reserve_ratio changes.  Ensures that each zone
6284  *      has a correct pages reserved value, so an adequate number of
6285  *      pages are left in the zone after a successful __alloc_pages().
6286  */
6287 static void setup_per_zone_lowmem_reserve(void)
6288 {
6289         struct pglist_data *pgdat;
6290         enum zone_type j, idx;
6291 
6292         for_each_online_pgdat(pgdat) {
6293                 for (j = 0; j < MAX_NR_ZONES; j++) {
6294                         struct zone *zone = pgdat->node_zones + j;
6295                         unsigned long managed_pages = zone->managed_pages;
6296 
6297                         zone->lowmem_reserve[j] = 0;
6298 
6299                         idx = j;
6300                         while (idx) {
6301                                 struct zone *lower_zone;
6302 
6303                                 idx--;
6304 
6305                                 if (sysctl_lowmem_reserve_ratio[idx] < 1)
6306                                         sysctl_lowmem_reserve_ratio[idx] = 1;
6307 
6308                                 lower_zone = pgdat->node_zones + idx;
6309                                 lower_zone->lowmem_reserve[j] = managed_pages /
6310                                         sysctl_lowmem_reserve_ratio[idx];
6311                                 managed_pages += lower_zone->managed_pages;
6312                         }
6313                 }
6314         }
6315 
6316         /* update totalreserve_pages */
6317         calculate_totalreserve_pages();
6318 }
6319 
6320 static void __setup_per_zone_wmarks(void)
6321 {
6322         unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
6323         unsigned long lowmem_pages = 0;
6324         struct zone *zone;
6325         unsigned long flags;
6326 
6327         /* Calculate total number of !ZONE_HIGHMEM pages */
6328         for_each_zone(zone) {
6329                 if (!is_highmem(zone))
6330                         lowmem_pages += zone->managed_pages;
6331         }
6332 
6333         for_each_zone(zone) {
6334                 u64 tmp;
6335 
6336                 spin_lock_irqsave(&zone->lock, flags);
6337                 tmp = (u64)pages_min * zone->managed_pages;
6338                 do_div(tmp, lowmem_pages);
6339                 if (is_highmem(zone)) {
6340                         /*
6341                          * __GFP_HIGH and PF_MEMALLOC allocations usually don't
6342                          * need highmem pages, so cap pages_min to a small
6343                          * value here.
6344                          *
6345                          * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN)
6346                          * deltas control asynch page reclaim, and so should
6347                          * not be capped for highmem.
6348                          */
6349                         unsigned long min_pages;
6350 
6351                         min_pages = zone->managed_pages / 1024;
6352                         min_pages = clamp(min_pages, SWAP_CLUSTER_MAX, 128UL);
6353                         zone->watermark[WMARK_MIN] = min_pages;
6354                 } else {
6355                         /*
6356                          * If it's a lowmem zone, reserve a number of pages
6357                          * proportionate to the zone's size.
6358                          */
6359                         zone->watermark[WMARK_MIN] = tmp;
6360                 }
6361 
6362                 /*
6363                  * Set the kswapd watermarks distance according to the
6364                  * scale factor in proportion to available memory, but
6365                  * ensure a minimum size on small systems.
6366                  */
6367                 tmp = max_t(u64, tmp >> 2,
6368                             mult_frac(zone->managed_pages,
6369                                       watermark_scale_factor, 10000));
6370 
6371                 zone->watermark[WMARK_LOW]  = min_wmark_pages(zone) + tmp;
6372                 zone->watermark[WMARK_HIGH] = min_wmark_pages(zone) + tmp * 2;
6373 
6374                 __mod_zone_page_state(zone, NR_ALLOC_BATCH,
6375                         high_wmark_pages(zone) - low_wmark_pages(zone) -
6376                         atomic_long_read(&zone->vm_stat[NR_ALLOC_BATCH]));
6377 
6378                 spin_unlock_irqrestore(&zone->lock, flags);
6379         }
6380 
6381         /* update totalreserve_pages */
6382         calculate_totalreserve_pages();
6383 }
6384 
6385 /**
6386  * setup_per_zone_wmarks - called when min_free_kbytes changes
6387  * or when memory is hot-{added|removed}
6388  *
6389  * Ensures that the watermark[min,low,high] values for each zone are set
6390  * correctly with respect to min_free_kbytes.
6391  */
6392 void setup_per_zone_wmarks(void)
6393 {
6394         mutex_lock(&zonelists_mutex);
6395         __setup_per_zone_wmarks();
6396         mutex_unlock(&zonelists_mutex);
6397 }
6398 
6399 /*
6400  * The inactive anon list should be small enough that the VM never has to
6401  * do too much work, but large enough that each inactive page has a chance
6402  * to be referenced again before it is swapped out.
6403  *
6404  * The inactive_anon ratio is the target ratio of ACTIVE_ANON to
6405  * INACTIVE_ANON pages on this zone's LRU, maintained by the
6406  * pageout code. A zone->inactive_ratio of 3 means 3:1 or 25% of
6407  * the anonymous pages are kept on the inactive list.
6408  *
6409  * total     target    max
6410  * memory    ratio     inactive anon
6411  * -------------------------------------
6412  *   10MB       1         5MB
6413  *  100MB       1        50MB
6414  *    1GB       3       250MB
6415  *   10GB      10       0.9GB
6416  *  100GB      31         3GB
6417  *    1TB     101        10GB
6418  *   10TB     320        32GB
6419  */
6420 static void __meminit calculate_zone_inactive_ratio(struct zone *zone)
6421 {
6422         unsigned int gb, ratio;
6423 
6424         /* Zone size in gigabytes */
6425         gb = zone->managed_pages >> (30 - PAGE_SHIFT);
6426         if (gb)
6427                 ratio = int_sqrt(10 * gb);
6428         else
6429                 ratio = 1;
6430 
6431         zone->inactive_ratio = ratio;
6432 }
6433 
6434 static void __meminit setup_per_zone_inactive_ratio(void)
6435 {
6436         struct zone *zone;
6437 
6438         for_each_zone(zone)
6439                 calculate_zone_inactive_ratio(zone);
6440 }
6441 
6442 /*
6443  * Initialise min_free_kbytes.
6444  *
6445  * For small machines we want it small (128k min).  For large machines
6446  * we want it large (64MB max).  But it is not linear, because network
6447  * bandwidth does not increase linearly with machine size.  We use
6448  *
6449  *      min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
6450  *      min_free_kbytes = sqrt(lowmem_kbytes * 16)
6451  *
6452  * which yields
6453  *
6454  * 16MB:        512k
6455  * 32MB:        724k
6456  * 64MB:        1024k
6457  * 128MB:       1448k
6458  * 256MB:       2048k
6459  * 512MB:       2896k
6460  * 1024MB:      4096k
6461  * 2048MB:      5792k
6462  * 4096MB:      8192k
6463  * 8192MB:      11584k
6464  * 16384MB:     16384k
6465  */
6466 int __meminit init_per_zone_wmark_min(void)
6467 {
6468         unsigned long lowmem_kbytes;
6469         int new_min_free_kbytes;
6470 
6471         lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
6472         new_min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
6473 
6474         if (new_min_free_kbytes > user_min_free_kbytes) {
6475                 min_free_kbytes = new_min_free_kbytes;
6476                 if (min_free_kbytes < 128)
6477                         min_free_kbytes = 128;
6478                 if (min_free_kbytes > 65536)
6479                         min_free_kbytes = 65536;
6480         } else {
6481                 pr_warn("min_free_kbytes is not updated to %d because user defined value %d is preferred\n",
6482                                 new_min_free_kbytes, user_min_free_kbytes);
6483         }
6484         setup_per_zone_wmarks();
6485         refresh_zone_stat_thresholds();
6486         setup_per_zone_lowmem_reserve();
6487         setup_per_zone_inactive_ratio();
6488         return 0;
6489 }
6490 core_initcall(init_per_zone_wmark_min)
6491 
6492 /*
6493  * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
6494  *      that we can call two helper functions whenever min_free_kbytes
6495  *      changes.
6496  */
6497 int min_free_kbytes_sysctl_handler(struct ctl_table *table, int write,
6498         void __user *buffer, size_t *length, loff_t *ppos)
6499 {
6500         int rc;
6501 
6502         rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
6503         if (rc)
6504                 return rc;
6505 
6506         if (write) {
6507                 user_min_free_kbytes = min_free_kbytes;
6508                 setup_per_zone_wmarks();
6509         }
6510         return 0;
6511 }
6512 
6513 int watermark_scale_factor_sysctl_handler(struct ctl_table *table, int write,
6514         void __user *buffer, size_t *length, loff_t *ppos)
6515 {
6516         int rc;
6517 
6518         rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
6519         if (rc)
6520                 return rc;
6521 
6522         if (write)
6523                 setup_per_zone_wmarks();
6524 
6525         return 0;
6526 }
6527 
6528 #ifdef CONFIG_NUMA
6529 int sysctl_min_unmapped_ratio_sysctl_handler(struct ctl_table *table, int write,
6530         void __user *buffer, size_t *length, loff_t *ppos)
6531 {
6532         struct zone *zone;
6533         int rc;
6534 
6535         rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
6536         if (rc)
6537                 return rc;
6538 
6539         for_each_zone(zone)
6540                 zone->min_unmapped_pages = (zone->managed_pages *
6541                                 sysctl_min_unmapped_ratio) / 100;
6542         return 0;
6543 }
6544 
6545 int sysctl_min_slab_ratio_sysctl_handler(struct ctl_table *table, int write,
6546         void __user *buffer, size_t *length, loff_t *ppos)
6547 {
6548         struct zone *zone;
6549         int rc;
6550 
6551         rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
6552         if (rc)
6553                 return rc;
6554 
6555         for_each_zone(zone)
6556                 zone->min_slab_pages = (zone->managed_pages *
6557                                 sysctl_min_slab_ratio) / 100;
6558         return 0;
6559 }
6560 #endif
6561 
6562 /*
6563  * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
6564  *      proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
6565  *      whenever sysctl_lowmem_reserve_ratio changes.
6566  *
6567  * The reserve ratio obviously has absolutely no relation with the
6568  * minimum watermarks. The lowmem reserve ratio can only make sense
6569  * if in function of the boot time zone sizes.
6570  */
6571 int lowmem_reserve_ratio_sysctl_handler(struct ctl_table *table, int write,
6572         void __user *buffer, size_t *length, loff_t *ppos)
6573 {
6574         proc_dointvec_minmax(table, write, buffer, length, ppos);
6575         setup_per_zone_lowmem_reserve();
6576         return 0;
6577 }
6578 
6579 /*
6580  * percpu_pagelist_fraction - changes the pcp->high for each zone on each
6581  * cpu.  It is the fraction of total pages in each zone that a hot per cpu
6582  * pagelist can have before it gets flushed back to buddy allocator.
6583  */
6584 int percpu_pagelist_fraction_sysctl_handler(struct ctl_table *table, int write,
6585         void __user *buffer, size_t *length, loff_t *ppos)
6586 {
6587         struct zone *zone;
6588         int old_percpu_pagelist_fraction;
6589         int ret;
6590 
6591         mutex_lock(&pcp_batch_high_lock);
6592         old_percpu_pagelist_fraction = percpu_pagelist_fraction;
6593 
6594         ret = proc_dointvec_minmax(table, write, buffer, length, ppos);
6595         if (!write || ret < 0)
6596                 goto out;
6597 
6598         /* Sanity checking to avoid pcp imbalance */
6599         if (percpu_pagelist_fraction &&
6600             percpu_pagelist_fraction < MIN_PERCPU_PAGELIST_FRACTION) {
6601                 percpu_pagelist_fraction = old_percpu_pagelist_fraction;
6602                 ret = -EINVAL;
6603                 goto out;
6604         }
6605 
6606         /* No change? */
6607         if (percpu_pagelist_fraction == old_percpu_pagelist_fraction)
6608                 goto out;
6609 
6610         for_each_populated_zone(zone) {
6611                 unsigned int cpu;
6612 
6613                 for_each_possible_cpu(cpu)
6614                         pageset_set_high_and_batch(zone,
6615                                         per_cpu_ptr(zone->pageset, cpu));
6616         }
6617 out:
6618         mutex_unlock(&pcp_batch_high_lock);
6619         return ret;
6620 }
6621 
6622 #ifdef CONFIG_NUMA
6623 int hashdist = HASHDIST_DEFAULT;
6624 
6625 static int __init set_hashdist(char *str)
6626 {
6627         if (!str)
6628                 return 0;
6629         hashdist = simple_strtoul(str, &str, 0);
6630         return 1;
6631 }
6632 __setup("hashdist=", set_hashdist);
6633 #endif
6634 
6635 /*
6636  * allocate a large system hash table from bootmem
6637  * - it is assumed that the hash table must contain an exact power-of-2
6638  *   quantity of entries
6639  * - limit is the number of hash buckets, not the total allocation size
6640  */
6641 void *__init alloc_large_system_hash(const char *tablename,
6642                                      unsigned long bucketsize,
6643                                      unsigned long numentries,
6644                                      int scale,
6645                                      int flags,
6646                                      unsigned int *_hash_shift,
6647                                      unsigned int *_hash_mask,
6648                                      unsigned long low_limit,
6649                                      unsigned long high_limit)
6650 {
6651         unsigned long long max = high_limit;
6652         unsigned long log2qty, size;
6653         void *table = NULL;
6654 
6655         /* allow the kernel cmdline to have a say */
6656         if (!numentries) {
6657                 /* round applicable memory size up to nearest megabyte */
6658                 numentries = nr_kernel_pages;
6659 
6660                 /* It isn't necessary when PAGE_SIZE >= 1MB */
6661                 if (PAGE_SHIFT < 20)
6662                         numentries = round_up(numentries, (1<<20)/PAGE_SIZE);
6663 
6664                 /* limit to 1 bucket per 2^scale bytes of low memory */
6665                 if (scale > PAGE_SHIFT)
6666                         numentries >>= (scale - PAGE_SHIFT);
6667                 else
6668                         numentries <<= (PAGE_SHIFT - scale);
6669 
6670                 /* Make sure we've got at least a 0-order allocation.. */
6671                 if (unlikely(flags & HASH_SMALL)) {
6672                         /* Makes no sense without HASH_EARLY */
6673                         WARN_ON(!(flags & HASH_EARLY));
6674                         if (!(numentries >> *_hash_shift)) {
6675                                 numentries = 1UL << *_hash_shift;
6676                                 BUG_ON(!numentries);
6677                         }
6678                 } else if (unlikely((numentries * bucketsize) < PAGE_SIZE))
6679                         numentries = PAGE_SIZE / bucketsize;
6680         }
6681         numentries = roundup_pow_of_two(numentries);
6682 
6683         /* limit allocation size to 1/16 total memory by default */
6684         if (max == 0) {
6685                 max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
6686                 do_div(max, bucketsize);
6687         }
6688         max = min(max, 0x80000000ULL);
6689 
6690         if (numentries < low_limit)
6691                 numentries = low_limit;
6692         if (numentries > max)
6693                 numentries = max;
6694 
6695         log2qty = ilog2(numentries);
6696 
6697         do {
6698                 size = bucketsize << log2qty;
6699                 if (flags & HASH_EARLY)
6700                         table = memblock_virt_alloc_nopanic(size, 0);
6701                 else if (hashdist)
6702                         table = __vmalloc(size, GFP_ATOMIC, PAGE_KERNEL);
6703                 else {
6704                         /*
6705                          * If bucketsize is not a power-of-two, we may free
6706                          * some pages at the end of hash table which
6707                          * alloc_pages_exact() automatically does
6708                          */
6709                         if (get_order(size) < MAX_ORDER) {
6710                                 table = alloc_pages_exact(size, GFP_ATOMIC);
6711                                 kmemleak_alloc(table, size, 1, GFP_ATOMIC);
6712                         }
6713                 }
6714         } while (!table && size > PAGE_SIZE && --log2qty);
6715 
6716         if (!table)
6717                 panic("Failed to allocate %s hash table\n", tablename);
6718 
6719         pr_info("%s hash table entries: %ld (order: %d, %lu bytes)\n",
6720                 tablename, 1UL << log2qty, ilog2(size) - PAGE_SHIFT, size);
6721 
6722         if (_hash_shift)
6723                 *_hash_shift = log2qty;
6724         if (_hash_mask)
6725                 *_hash_mask = (1 << log2qty) - 1;
6726 
6727         return table;
6728 }
6729 
6730 /* Return a pointer to the bitmap storing bits affecting a block of pages */
6731 static inline unsigned long *get_pageblock_bitmap(struct zone *zone,
6732                                                         unsigned long pfn)
6733 {
6734 #ifdef CONFIG_SPARSEMEM
6735         return __pfn_to_section(pfn)->pageblock_flags;
6736 #else
6737         return zone->pageblock_flags;
6738 #endif /* CONFIG_SPARSEMEM */
6739 }
6740 
6741 static inline int pfn_to_bitidx(struct zone *zone, unsigned long pfn)
6742 {
6743 #ifdef CONFIG_SPARSEMEM
6744         pfn &= (PAGES_PER_SECTION-1);
6745         return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
6746 #else
6747         pfn = pfn - round_down(zone->zone_start_pfn, pageblock_nr_pages);
6748         return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
6749 #endif /* CONFIG_SPARSEMEM */
6750 }
6751 
6752 /**
6753  * get_pfnblock_flags_mask - Return the requested group of flags for the pageblock_nr_pages block of pages
6754  * @page: The page within the block of interest
6755  * @pfn: The target page frame number
6756  * @end_bitidx: The last bit of interest to retrieve
6757  * @mask: mask of bits that the caller is interested in
6758  *
6759  * Return: pageblock_bits flags
6760  */
6761 unsigned long get_pfnblock_flags_mask(struct page *page, unsigned long pfn,
6762                                         unsigned long end_bitidx,
6763                                         unsigned long mask)
6764 {
6765         struct zone *zone;
6766         unsigned long *bitmap;
6767         unsigned long bitidx, word_bitidx;
6768         unsigned long word;
6769 
6770         zone = page_zone(page);
6771         bitmap = get_pageblock_bitmap(zone, pfn);
6772         bitidx = pfn_to_bitidx(zone, pfn);
6773         word_bitidx = bitidx / BITS_PER_LONG;
6774         bitidx &= (BITS_PER_LONG-1);
6775 
6776         word = bitmap[word_bitidx];
6777         bitidx += end_bitidx;
6778         return (word >> (BITS_PER_LONG - bitidx - 1)) & mask;
6779 }
6780 
6781 /**
6782  * set_pfnblock_flags_mask - Set the requested group of flags for a pageblock_nr_pages block of pages
6783  * @page: The page within the block of interest
6784  * @flags: The flags to set
6785  * @pfn: The target page frame number
6786  * @end_bitidx: The last bit of interest
6787  * @mask: mask of bits that the caller is interested in
6788  */
6789 void set_pfnblock_flags_mask(struct page *page, unsigned long flags,
6790                                         unsigned long pfn,
6791                                         unsigned long end_bitidx,
6792                                         unsigned long mask)
6793 {
6794         struct zone *zone;
6795         unsigned long *bitmap;
6796         unsigned long bitidx, word_bitidx;
6797         unsigned long old_word, word;
6798 
6799         BUILD_BUG_ON(NR_PAGEBLOCK_BITS != 4);
6800 
6801         zone = page_zone(page);
6802         bitmap = get_pageblock_bitmap(zone, pfn);
6803         bitidx = pfn_to_bitidx(zone, pfn);
6804         word_bitidx = bitidx / BITS_PER_LONG;
6805         bitidx &= (BITS_PER_LONG-1);
6806 
6807         VM_BUG_ON_PAGE(!zone_spans_pfn(zone, pfn), page);
6808 
6809         bitidx += end_bitidx;
6810         mask <<= (BITS_PER_LONG - bitidx - 1);
6811         flags <<= (BITS_PER_LONG - bitidx - 1);
6812 
6813         word = READ_ONCE(bitmap[word_bitidx]);
6814         for (;;) {
6815                 old_word = cmpxchg(&bitmap[word_bitidx], word, (word & ~mask) | flags);
6816                 if (word == old_word)
6817                         break;
6818                 word = old_word;
6819         }
6820 }
6821 
6822 /*
6823  * This function checks whether pageblock includes unmovable pages or not.
6824  * If @count is not zero, it is okay to include less @count unmovable pages
6825  *
6826  * PageLRU check without isolation or lru_lock could race so that
6827  * MIGRATE_MOVABLE block might include unmovable pages. It means you can't
6828  * expect this function should be exact.
6829  */
6830 bool has_unmovable_pages(struct zone *zone, struct page *page, int count,
6831                          bool skip_hwpoisoned_pages)
6832 {
6833         unsigned long pfn, iter, found;
6834         int mt;
6835 
6836         /*
6837          * For avoiding noise data, lru_add_drain_all() should be called
6838          * If ZONE_MOVABLE, the zone never contains unmovable pages
6839          */
6840         if (zone_idx(zone) == ZONE_MOVABLE)
6841                 return false;
6842         mt = get_pageblock_migratetype(page);
6843         if (mt == MIGRATE_MOVABLE || is_migrate_cma(mt))
6844                 return false;
6845 
6846         pfn = page_to_pfn(page);
6847         for (found = 0, iter = 0; iter < pageblock_nr_pages; iter++) {
6848                 unsigned long check = pfn + iter;
6849 
6850                 if (!pfn_valid_within(check))
6851                         continue;
6852 
6853                 page = pfn_to_page(check);
6854 
6855                 /*
6856                  * Hugepages are not in LRU lists, but they're movable.
6857                  * We need not scan over tail pages bacause we don't
6858                  * handle each tail page individually in migration.
6859                  */
6860                 if (PageHuge(page)) {
6861                         iter = round_up(iter + 1, 1<<compound_order(page)) - 1;
6862                         continue;
6863                 }
6864 
6865                 /*
6866                  * We can't use page_count without pin a page
6867                  * because another CPU can free compound page.
6868                  * This check already skips compound tails of THP
6869                  * because their page->_count is zero at all time.
6870                  */
6871                 if (!page_ref_count(page)) {
6872                         if (PageBuddy(page))
6873                                 iter += (1 << page_order(page)) - 1;
6874                         continue;
6875                 }
6876 
6877                 /*
6878                  * The HWPoisoned page may be not in buddy system, and
6879                  * page_count() is not 0.
6880                  */
6881                 if (skip_hwpoisoned_pages && PageHWPoison(page))
6882                         continue;
6883 
6884                 if (!PageLRU(page))
6885                         found++;
6886                 /*
6887                  * If there are RECLAIMABLE pages, we need to check
6888                  * it.  But now, memory offline itself doesn't call
6889                  * shrink_node_slabs() and it still to be fixed.
6890                  */
6891                 /*
6892                  * If the page is not RAM, page_count()should be 0.
6893                  * we don't need more check. This is an _used_ not-movable page.
6894                  *
6895                  * The problematic thing here is PG_reserved pages. PG_reserved
6896                  * is set to both of a memory hole page and a _used_ kernel
6897                  * page at boot.
6898                  */
6899                 if (found > count)
6900                         return true;
6901         }
6902         return false;
6903 }
6904 
6905 bool is_pageblock_removable_nolock(struct page *page)
6906 {
6907         struct zone *zone;
6908         unsigned long pfn;
6909 
6910         /*
6911          * We have to be careful here because we are iterating over memory
6912          * sections which are not zone aware so we might end up outside of
6913          * the zone but still within the section.
6914          * We have to take care about the node as well. If the node is offline
6915          * its NODE_DATA will be NULL - see page_zone.
6916          */
6917         if (!node_online(page_to_nid(page)))
6918                 return false;
6919 
6920         zone = page_zone(page);
6921         pfn = page_to_pfn(page);
6922         if (!zone_spans_pfn(zone, pfn))
6923                 return false;
6924 
6925         return !has_unmovable_pages(zone, page, 0, true);
6926 }
6927 
6928 #if (defined(CONFIG_MEMORY_ISOLATION) && defined(CONFIG_COMPACTION)) || defined(CONFIG_CMA)
6929 
6930 static unsigned long pfn_max_align_down(unsigned long pfn)
6931 {
6932         return pfn & ~(max_t(unsigned long, MAX_ORDER_NR_PAGES,
6933                              pageblock_nr_pages) - 1);
6934 }
6935 
6936 static unsigned long pfn_max_align_up(unsigned long pfn)
6937 {
6938         return ALIGN(pfn, max_t(unsigned long, MAX_ORDER_NR_PAGES,
6939                                 pageblock_nr_pages));
6940 }
6941 
6942 /* [start, end) must belong to a single zone. */
6943 static int __alloc_contig_migrate_range(struct compact_control *cc,
6944                                         unsigned long start, unsigned long end)
6945 {
6946         /* This function is based on compact_zone() from compaction.c. */
6947         unsigned long nr_reclaimed;
6948         unsigned long pfn = start;
6949         unsigned int tries = 0;
6950         int ret = 0;
6951 
6952         migrate_prep();
6953 
6954         while (pfn < end || !list_empty(&cc->migratepages)) {
6955                 if (fatal_signal_pending(current)) {
6956                         ret = -EINTR;
6957                         break;
6958                 }
6959 
6960                 if (list_empty(&cc->migratepages)) {
6961                         cc->nr_migratepages = 0;
6962                         pfn = isolate_migratepages_range(cc, pfn, end);
6963                         if (!pfn) {
6964                                 ret = -EINTR;
6965                                 break;
6966                         }
6967                         tries = 0;
6968                 } else if (++tries == 5) {
6969                         ret = ret < 0 ? ret : -EBUSY;
6970                         break;
6971                 }
6972 
6973                 nr_reclaimed = reclaim_clean_pages_from_list(cc->zone,
6974                                                         &cc->migratepages);
6975                 cc->nr_migratepages -= nr_reclaimed;
6976 
6977                 ret = migrate_pages(&cc->migratepages, alloc_migrate_target,
6978                                     NULL, 0, cc->mode, MR_CMA);
6979         }
6980         if (ret < 0) {
6981                 putback_movable_pages(&cc->migratepages);
6982                 return ret;
6983         }
6984         return 0;
6985 }
6986 
6987 /**
6988  * alloc_contig_range() -- tries to allocate given range of pages
6989  * @start:      start PFN to allocate
6990  * @end:        one-past-the-last PFN to allocate
6991  * @migratetype:        migratetype of the underlaying pageblocks (either
6992  *                      #MIGRATE_MOVABLE or #MIGRATE_CMA).  All pageblocks
6993  *                      in range must have the same migratetype and it must
6994  *                      be either of the two.
6995  *
6996  * The PFN range does not have to be pageblock or MAX_ORDER_NR_PAGES
6997  * aligned, however it's the caller's responsibility to guarantee that
6998  * we are the only thread that changes migrate type of pageblocks the
6999  * pages fall in.
7000  *
7001  * The PFN range must belong to a single zone.
7002  *
7003  * Returns zero on success or negative error code.  On success all
7004  * pages which PFN is in [start, end) are allocated for the caller and
7005  * need to be freed with free_contig_range().
7006  */
7007 int alloc_contig_range(unsigned long start, unsigned long end,
7008                        unsigned migratetype)
7009 {
7010         unsigned long outer_start, outer_end;
7011         unsigned int order;
7012         int ret = 0;
7013 
7014         struct compact_control cc = {
7015                 .nr_migratepages = 0,
7016                 .order = -1,
7017                 .zone = page_zone(pfn_to_page(start)),
7018                 .mode = MIGRATE_SYNC,
7019                 .ignore_skip_hint = true,
7020         };
7021         INIT_LIST_HEAD(&cc.migratepages);
7022 
7023         /*
7024          * What we do here is we mark all pageblocks in range as
7025          * MIGRATE_ISOLATE.  Because pageblock and max order pages may
7026          * have different sizes, and due to the way page allocator
7027          * work, we align the range to biggest of the two pages so
7028          * that page allocator won't try to merge buddies from
7029          * different pageblocks and change MIGRATE_ISOLATE to some
7030          * other migration type.
7031          *
7032          * Once the pageblocks are marked as MIGRATE_ISOLATE, we
7033          * migrate the pages from an unaligned range (ie. pages that
7034          * we are interested in).  This will put all the pages in
7035          * range back to page allocator as MIGRATE_ISOLATE.
7036          *
7037          * When this is done, we take the pages in range from page
7038          * allocator removing them from the buddy system.  This way
7039          * page allocator will never consider using them.
7040          *
7041          * This lets us mark the pageblocks back as
7042          * MIGRATE_CMA/MIGRATE_MOVABLE so that free pages in the
7043          * aligned range but not in the unaligned, original range are
7044          * put back to page allocator so that buddy can use them.
7045          */
7046 
7047         ret = start_isolate_page_range(pfn_max_align_down(start),
7048                                        pfn_max_align_up(end), migratetype,
7049                                        false);
7050         if (ret)
7051                 return ret;
7052 
7053         /*
7054          * In case of -EBUSY, we'd like to know which page causes problem.
7055          * So, just fall through. We will check it in test_pages_isolated().
7056          */
7057         ret = __alloc_contig_migrate_range(&cc, start, end);
7058         if (ret && ret != -EBUSY)
7059                 goto done;
7060 
7061         /*
7062          * Pages from [start, end) are within a MAX_ORDER_NR_PAGES
7063          * aligned blocks that are marked as MIGRATE_ISOLATE.  What's
7064          * more, all pages in [start, end) are free in page allocator.
7065          * What we are going to do is to allocate all pages from
7066          * [start, end) (that is remove them from page allocator).