mm/page_alloc: remove nr_free_pagecache_pages()
[linux-2.6-microblaze.git] / mm / page_alloc.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  linux/mm/page_alloc.c
4  *
5  *  Manages the free list, the system allocates free pages here.
6  *  Note that kmalloc() lives in slab.c
7  *
8  *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
9  *  Swap reorganised 29.12.95, Stephen Tweedie
10  *  Support of BIGMEM added by Gerhard Wichert, Siemens AG, July 1999
11  *  Reshaped it to be a zoned allocator, Ingo Molnar, Red Hat, 1999
12  *  Discontiguous memory support, Kanoj Sarcar, SGI, Nov 1999
13  *  Zone balancing, Kanoj Sarcar, SGI, Jan 2000
14  *  Per cpu hot/cold page lists, bulk allocation, Martin J. Bligh, Sept 2002
15  *          (lots of bits borrowed from Ingo Molnar & Andrew Morton)
16  */
17
18 #include <linux/stddef.h>
19 #include <linux/mm.h>
20 #include <linux/highmem.h>
21 #include <linux/swap.h>
22 #include <linux/interrupt.h>
23 #include <linux/pagemap.h>
24 #include <linux/jiffies.h>
25 #include <linux/memblock.h>
26 #include <linux/compiler.h>
27 #include <linux/kernel.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/topology.h>
37 #include <linux/sysctl.h>
38 #include <linux/cpu.h>
39 #include <linux/cpuset.h>
40 #include <linux/memory_hotplug.h>
41 #include <linux/nodemask.h>
42 #include <linux/vmalloc.h>
43 #include <linux/vmstat.h>
44 #include <linux/mempolicy.h>
45 #include <linux/memremap.h>
46 #include <linux/stop_machine.h>
47 #include <linux/random.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/debugobjects.h>
54 #include <linux/kmemleak.h>
55 #include <linux/compaction.h>
56 #include <trace/events/kmem.h>
57 #include <trace/events/oom.h>
58 #include <linux/prefetch.h>
59 #include <linux/mm_inline.h>
60 #include <linux/migrate.h>
61 #include <linux/hugetlb.h>
62 #include <linux/sched/rt.h>
63 #include <linux/sched/mm.h>
64 #include <linux/page_owner.h>
65 #include <linux/kthread.h>
66 #include <linux/memcontrol.h>
67 #include <linux/ftrace.h>
68 #include <linux/lockdep.h>
69 #include <linux/nmi.h>
70 #include <linux/psi.h>
71 #include <linux/padata.h>
72
73 #include <asm/sections.h>
74 #include <asm/tlbflush.h>
75 #include <asm/div64.h>
76 #include "internal.h"
77 #include "shuffle.h"
78 #include "page_reporting.h"
79
80 /* prevent >1 _updater_ of zone percpu pageset ->high and ->batch fields */
81 static DEFINE_MUTEX(pcp_batch_high_lock);
82 #define MIN_PERCPU_PAGELIST_FRACTION    (8)
83
84 #ifdef CONFIG_USE_PERCPU_NUMA_NODE_ID
85 DEFINE_PER_CPU(int, numa_node);
86 EXPORT_PER_CPU_SYMBOL(numa_node);
87 #endif
88
89 DEFINE_STATIC_KEY_TRUE(vm_numa_stat_key);
90
91 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
92 /*
93  * N.B., Do NOT reference the '_numa_mem_' per cpu variable directly.
94  * It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined.
95  * Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem()
96  * defined in <linux/topology.h>.
97  */
98 DEFINE_PER_CPU(int, _numa_mem_);                /* Kernel "local memory" node */
99 EXPORT_PER_CPU_SYMBOL(_numa_mem_);
100 #endif
101
102 /* work_structs for global per-cpu drains */
103 struct pcpu_drain {
104         struct zone *zone;
105         struct work_struct work;
106 };
107 static DEFINE_MUTEX(pcpu_drain_mutex);
108 static DEFINE_PER_CPU(struct pcpu_drain, pcpu_drain);
109
110 #ifdef CONFIG_GCC_PLUGIN_LATENT_ENTROPY
111 volatile unsigned long latent_entropy __latent_entropy;
112 EXPORT_SYMBOL(latent_entropy);
113 #endif
114
115 /*
116  * Array of node states.
117  */
118 nodemask_t node_states[NR_NODE_STATES] __read_mostly = {
119         [N_POSSIBLE] = NODE_MASK_ALL,
120         [N_ONLINE] = { { [0] = 1UL } },
121 #ifndef CONFIG_NUMA
122         [N_NORMAL_MEMORY] = { { [0] = 1UL } },
123 #ifdef CONFIG_HIGHMEM
124         [N_HIGH_MEMORY] = { { [0] = 1UL } },
125 #endif
126         [N_MEMORY] = { { [0] = 1UL } },
127         [N_CPU] = { { [0] = 1UL } },
128 #endif  /* NUMA */
129 };
130 EXPORT_SYMBOL(node_states);
131
132 atomic_long_t _totalram_pages __read_mostly;
133 EXPORT_SYMBOL(_totalram_pages);
134 unsigned long totalreserve_pages __read_mostly;
135 unsigned long totalcma_pages __read_mostly;
136
137 int percpu_pagelist_fraction;
138 gfp_t gfp_allowed_mask __read_mostly = GFP_BOOT_MASK;
139 #ifdef CONFIG_INIT_ON_ALLOC_DEFAULT_ON
140 DEFINE_STATIC_KEY_TRUE(init_on_alloc);
141 #else
142 DEFINE_STATIC_KEY_FALSE(init_on_alloc);
143 #endif
144 EXPORT_SYMBOL(init_on_alloc);
145
146 #ifdef CONFIG_INIT_ON_FREE_DEFAULT_ON
147 DEFINE_STATIC_KEY_TRUE(init_on_free);
148 #else
149 DEFINE_STATIC_KEY_FALSE(init_on_free);
150 #endif
151 EXPORT_SYMBOL(init_on_free);
152
153 static int __init early_init_on_alloc(char *buf)
154 {
155         int ret;
156         bool bool_result;
157
158         if (!buf)
159                 return -EINVAL;
160         ret = kstrtobool(buf, &bool_result);
161         if (bool_result && page_poisoning_enabled())
162                 pr_info("mem auto-init: CONFIG_PAGE_POISONING is on, will take precedence over init_on_alloc\n");
163         if (bool_result)
164                 static_branch_enable(&init_on_alloc);
165         else
166                 static_branch_disable(&init_on_alloc);
167         return ret;
168 }
169 early_param("init_on_alloc", early_init_on_alloc);
170
171 static int __init early_init_on_free(char *buf)
172 {
173         int ret;
174         bool bool_result;
175
176         if (!buf)
177                 return -EINVAL;
178         ret = kstrtobool(buf, &bool_result);
179         if (bool_result && page_poisoning_enabled())
180                 pr_info("mem auto-init: CONFIG_PAGE_POISONING is on, will take precedence over init_on_free\n");
181         if (bool_result)
182                 static_branch_enable(&init_on_free);
183         else
184                 static_branch_disable(&init_on_free);
185         return ret;
186 }
187 early_param("init_on_free", early_init_on_free);
188
189 /*
190  * A cached value of the page's pageblock's migratetype, used when the page is
191  * put on a pcplist. Used to avoid the pageblock migratetype lookup when
192  * freeing from pcplists in most cases, at the cost of possibly becoming stale.
193  * Also the migratetype set in the page does not necessarily match the pcplist
194  * index, e.g. page might have MIGRATE_CMA set but be on a pcplist with any
195  * other index - this ensures that it will be put on the correct CMA freelist.
196  */
197 static inline int get_pcppage_migratetype(struct page *page)
198 {
199         return page->index;
200 }
201
202 static inline void set_pcppage_migratetype(struct page *page, int migratetype)
203 {
204         page->index = migratetype;
205 }
206
207 #ifdef CONFIG_PM_SLEEP
208 /*
209  * The following functions are used by the suspend/hibernate code to temporarily
210  * change gfp_allowed_mask in order to avoid using I/O during memory allocations
211  * while devices are suspended.  To avoid races with the suspend/hibernate code,
212  * they should always be called with system_transition_mutex held
213  * (gfp_allowed_mask also should only be modified with system_transition_mutex
214  * held, unless the suspend/hibernate code is guaranteed not to run in parallel
215  * with that modification).
216  */
217
218 static gfp_t saved_gfp_mask;
219
220 void pm_restore_gfp_mask(void)
221 {
222         WARN_ON(!mutex_is_locked(&system_transition_mutex));
223         if (saved_gfp_mask) {
224                 gfp_allowed_mask = saved_gfp_mask;
225                 saved_gfp_mask = 0;
226         }
227 }
228
229 void pm_restrict_gfp_mask(void)
230 {
231         WARN_ON(!mutex_is_locked(&system_transition_mutex));
232         WARN_ON(saved_gfp_mask);
233         saved_gfp_mask = gfp_allowed_mask;
234         gfp_allowed_mask &= ~(__GFP_IO | __GFP_FS);
235 }
236
237 bool pm_suspended_storage(void)
238 {
239         if ((gfp_allowed_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
240                 return false;
241         return true;
242 }
243 #endif /* CONFIG_PM_SLEEP */
244
245 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
246 unsigned int pageblock_order __read_mostly;
247 #endif
248
249 static void __free_pages_ok(struct page *page, unsigned int order);
250
251 /*
252  * results with 256, 32 in the lowmem_reserve sysctl:
253  *      1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
254  *      1G machine -> (16M dma, 784M normal, 224M high)
255  *      NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
256  *      HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
257  *      HIGHMEM allocation will leave (224M+784M)/256 of ram reserved in ZONE_DMA
258  *
259  * TBD: should special case ZONE_DMA32 machines here - in those we normally
260  * don't need any ZONE_NORMAL reservation
261  */
262 int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES] = {
263 #ifdef CONFIG_ZONE_DMA
264         [ZONE_DMA] = 256,
265 #endif
266 #ifdef CONFIG_ZONE_DMA32
267         [ZONE_DMA32] = 256,
268 #endif
269         [ZONE_NORMAL] = 32,
270 #ifdef CONFIG_HIGHMEM
271         [ZONE_HIGHMEM] = 0,
272 #endif
273         [ZONE_MOVABLE] = 0,
274 };
275
276 static char * const zone_names[MAX_NR_ZONES] = {
277 #ifdef CONFIG_ZONE_DMA
278          "DMA",
279 #endif
280 #ifdef CONFIG_ZONE_DMA32
281          "DMA32",
282 #endif
283          "Normal",
284 #ifdef CONFIG_HIGHMEM
285          "HighMem",
286 #endif
287          "Movable",
288 #ifdef CONFIG_ZONE_DEVICE
289          "Device",
290 #endif
291 };
292
293 const char * const migratetype_names[MIGRATE_TYPES] = {
294         "Unmovable",
295         "Movable",
296         "Reclaimable",
297         "HighAtomic",
298 #ifdef CONFIG_CMA
299         "CMA",
300 #endif
301 #ifdef CONFIG_MEMORY_ISOLATION
302         "Isolate",
303 #endif
304 };
305
306 compound_page_dtor * const compound_page_dtors[NR_COMPOUND_DTORS] = {
307         [NULL_COMPOUND_DTOR] = NULL,
308         [COMPOUND_PAGE_DTOR] = free_compound_page,
309 #ifdef CONFIG_HUGETLB_PAGE
310         [HUGETLB_PAGE_DTOR] = free_huge_page,
311 #endif
312 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
313         [TRANSHUGE_PAGE_DTOR] = free_transhuge_page,
314 #endif
315 };
316
317 int min_free_kbytes = 1024;
318 int user_min_free_kbytes = -1;
319 #ifdef CONFIG_DISCONTIGMEM
320 /*
321  * DiscontigMem defines memory ranges as separate pg_data_t even if the ranges
322  * are not on separate NUMA nodes. Functionally this works but with
323  * watermark_boost_factor, it can reclaim prematurely as the ranges can be
324  * quite small. By default, do not boost watermarks on discontigmem as in
325  * many cases very high-order allocations like THP are likely to be
326  * unsupported and the premature reclaim offsets the advantage of long-term
327  * fragmentation avoidance.
328  */
329 int watermark_boost_factor __read_mostly;
330 #else
331 int watermark_boost_factor __read_mostly = 15000;
332 #endif
333 int watermark_scale_factor = 10;
334
335 static unsigned long nr_kernel_pages __initdata;
336 static unsigned long nr_all_pages __initdata;
337 static unsigned long dma_reserve __initdata;
338
339 static unsigned long arch_zone_lowest_possible_pfn[MAX_NR_ZONES] __initdata;
340 static unsigned long arch_zone_highest_possible_pfn[MAX_NR_ZONES] __initdata;
341 static unsigned long required_kernelcore __initdata;
342 static unsigned long required_kernelcore_percent __initdata;
343 static unsigned long required_movablecore __initdata;
344 static unsigned long required_movablecore_percent __initdata;
345 static unsigned long zone_movable_pfn[MAX_NUMNODES] __initdata;
346 static bool mirrored_kernelcore __meminitdata;
347
348 /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
349 int movable_zone;
350 EXPORT_SYMBOL(movable_zone);
351
352 #if MAX_NUMNODES > 1
353 unsigned int nr_node_ids __read_mostly = MAX_NUMNODES;
354 unsigned int nr_online_nodes __read_mostly = 1;
355 EXPORT_SYMBOL(nr_node_ids);
356 EXPORT_SYMBOL(nr_online_nodes);
357 #endif
358
359 int page_group_by_mobility_disabled __read_mostly;
360
361 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
362 /*
363  * During boot we initialize deferred pages on-demand, as needed, but once
364  * page_alloc_init_late() has finished, the deferred pages are all initialized,
365  * and we can permanently disable that path.
366  */
367 static DEFINE_STATIC_KEY_TRUE(deferred_pages);
368
369 /*
370  * Calling kasan_free_pages() only after deferred memory initialization
371  * has completed. Poisoning pages during deferred memory init will greatly
372  * lengthen the process and cause problem in large memory systems as the
373  * deferred pages initialization is done with interrupt disabled.
374  *
375  * Assuming that there will be no reference to those newly initialized
376  * pages before they are ever allocated, this should have no effect on
377  * KASAN memory tracking as the poison will be properly inserted at page
378  * allocation time. The only corner case is when pages are allocated by
379  * on-demand allocation and then freed again before the deferred pages
380  * initialization is done, but this is not likely to happen.
381  */
382 static inline void kasan_free_nondeferred_pages(struct page *page, int order)
383 {
384         if (!static_branch_unlikely(&deferred_pages))
385                 kasan_free_pages(page, order);
386 }
387
388 /* Returns true if the struct page for the pfn is uninitialised */
389 static inline bool __meminit early_page_uninitialised(unsigned long pfn)
390 {
391         int nid = early_pfn_to_nid(pfn);
392
393         if (node_online(nid) && pfn >= NODE_DATA(nid)->first_deferred_pfn)
394                 return true;
395
396         return false;
397 }
398
399 /*
400  * Returns true when the remaining initialisation should be deferred until
401  * later in the boot cycle when it can be parallelised.
402  */
403 static bool __meminit
404 defer_init(int nid, unsigned long pfn, unsigned long end_pfn)
405 {
406         static unsigned long prev_end_pfn, nr_initialised;
407
408         /*
409          * prev_end_pfn static that contains the end of previous zone
410          * No need to protect because called very early in boot before smp_init.
411          */
412         if (prev_end_pfn != end_pfn) {
413                 prev_end_pfn = end_pfn;
414                 nr_initialised = 0;
415         }
416
417         /* Always populate low zones for address-constrained allocations */
418         if (end_pfn < pgdat_end_pfn(NODE_DATA(nid)))
419                 return false;
420
421         /*
422          * We start only with one section of pages, more pages are added as
423          * needed until the rest of deferred pages are initialized.
424          */
425         nr_initialised++;
426         if ((nr_initialised > PAGES_PER_SECTION) &&
427             (pfn & (PAGES_PER_SECTION - 1)) == 0) {
428                 NODE_DATA(nid)->first_deferred_pfn = pfn;
429                 return true;
430         }
431         return false;
432 }
433 #else
434 #define kasan_free_nondeferred_pages(p, o)      kasan_free_pages(p, o)
435
436 static inline bool early_page_uninitialised(unsigned long pfn)
437 {
438         return false;
439 }
440
441 static inline bool defer_init(int nid, unsigned long pfn, unsigned long end_pfn)
442 {
443         return false;
444 }
445 #endif
446
447 /* Return a pointer to the bitmap storing bits affecting a block of pages */
448 static inline unsigned long *get_pageblock_bitmap(struct page *page,
449                                                         unsigned long pfn)
450 {
451 #ifdef CONFIG_SPARSEMEM
452         return section_to_usemap(__pfn_to_section(pfn));
453 #else
454         return page_zone(page)->pageblock_flags;
455 #endif /* CONFIG_SPARSEMEM */
456 }
457
458 static inline int pfn_to_bitidx(struct page *page, unsigned long pfn)
459 {
460 #ifdef CONFIG_SPARSEMEM
461         pfn &= (PAGES_PER_SECTION-1);
462         return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
463 #else
464         pfn = pfn - round_down(page_zone(page)->zone_start_pfn, pageblock_nr_pages);
465         return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
466 #endif /* CONFIG_SPARSEMEM */
467 }
468
469 /**
470  * get_pfnblock_flags_mask - Return the requested group of flags for the pageblock_nr_pages block of pages
471  * @page: The page within the block of interest
472  * @pfn: The target page frame number
473  * @end_bitidx: The last bit of interest to retrieve
474  * @mask: mask of bits that the caller is interested in
475  *
476  * Return: pageblock_bits flags
477  */
478 static __always_inline unsigned long __get_pfnblock_flags_mask(struct page *page,
479                                         unsigned long pfn,
480                                         unsigned long end_bitidx,
481                                         unsigned long mask)
482 {
483         unsigned long *bitmap;
484         unsigned long bitidx, word_bitidx;
485         unsigned long word;
486
487         bitmap = get_pageblock_bitmap(page, pfn);
488         bitidx = pfn_to_bitidx(page, pfn);
489         word_bitidx = bitidx / BITS_PER_LONG;
490         bitidx &= (BITS_PER_LONG-1);
491
492         word = bitmap[word_bitidx];
493         bitidx += end_bitidx;
494         return (word >> (BITS_PER_LONG - bitidx - 1)) & mask;
495 }
496
497 unsigned long get_pfnblock_flags_mask(struct page *page, unsigned long pfn,
498                                         unsigned long end_bitidx,
499                                         unsigned long mask)
500 {
501         return __get_pfnblock_flags_mask(page, pfn, end_bitidx, mask);
502 }
503
504 static __always_inline int get_pfnblock_migratetype(struct page *page, unsigned long pfn)
505 {
506         return __get_pfnblock_flags_mask(page, pfn, PB_migrate_end, MIGRATETYPE_MASK);
507 }
508
509 /**
510  * set_pfnblock_flags_mask - Set the requested group of flags for a pageblock_nr_pages block of pages
511  * @page: The page within the block of interest
512  * @flags: The flags to set
513  * @pfn: The target page frame number
514  * @end_bitidx: The last bit of interest
515  * @mask: mask of bits that the caller is interested in
516  */
517 void set_pfnblock_flags_mask(struct page *page, unsigned long flags,
518                                         unsigned long pfn,
519                                         unsigned long end_bitidx,
520                                         unsigned long mask)
521 {
522         unsigned long *bitmap;
523         unsigned long bitidx, word_bitidx;
524         unsigned long old_word, word;
525
526         BUILD_BUG_ON(NR_PAGEBLOCK_BITS != 4);
527         BUILD_BUG_ON(MIGRATE_TYPES > (1 << PB_migratetype_bits));
528
529         bitmap = get_pageblock_bitmap(page, pfn);
530         bitidx = pfn_to_bitidx(page, pfn);
531         word_bitidx = bitidx / BITS_PER_LONG;
532         bitidx &= (BITS_PER_LONG-1);
533
534         VM_BUG_ON_PAGE(!zone_spans_pfn(page_zone(page), pfn), page);
535
536         bitidx += end_bitidx;
537         mask <<= (BITS_PER_LONG - bitidx - 1);
538         flags <<= (BITS_PER_LONG - bitidx - 1);
539
540         word = READ_ONCE(bitmap[word_bitidx]);
541         for (;;) {
542                 old_word = cmpxchg(&bitmap[word_bitidx], word, (word & ~mask) | flags);
543                 if (word == old_word)
544                         break;
545                 word = old_word;
546         }
547 }
548
549 void set_pageblock_migratetype(struct page *page, int migratetype)
550 {
551         if (unlikely(page_group_by_mobility_disabled &&
552                      migratetype < MIGRATE_PCPTYPES))
553                 migratetype = MIGRATE_UNMOVABLE;
554
555         set_pageblock_flags_group(page, (unsigned long)migratetype,
556                                         PB_migrate, PB_migrate_end);
557 }
558
559 #ifdef CONFIG_DEBUG_VM
560 static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
561 {
562         int ret = 0;
563         unsigned seq;
564         unsigned long pfn = page_to_pfn(page);
565         unsigned long sp, start_pfn;
566
567         do {
568                 seq = zone_span_seqbegin(zone);
569                 start_pfn = zone->zone_start_pfn;
570                 sp = zone->spanned_pages;
571                 if (!zone_spans_pfn(zone, pfn))
572                         ret = 1;
573         } while (zone_span_seqretry(zone, seq));
574
575         if (ret)
576                 pr_err("page 0x%lx outside node %d zone %s [ 0x%lx - 0x%lx ]\n",
577                         pfn, zone_to_nid(zone), zone->name,
578                         start_pfn, start_pfn + sp);
579
580         return ret;
581 }
582
583 static int page_is_consistent(struct zone *zone, struct page *page)
584 {
585         if (!pfn_valid_within(page_to_pfn(page)))
586                 return 0;
587         if (zone != page_zone(page))
588                 return 0;
589
590         return 1;
591 }
592 /*
593  * Temporary debugging check for pages not lying within a given zone.
594  */
595 static int __maybe_unused bad_range(struct zone *zone, struct page *page)
596 {
597         if (page_outside_zone_boundaries(zone, page))
598                 return 1;
599         if (!page_is_consistent(zone, page))
600                 return 1;
601
602         return 0;
603 }
604 #else
605 static inline int __maybe_unused bad_range(struct zone *zone, struct page *page)
606 {
607         return 0;
608 }
609 #endif
610
611 static void bad_page(struct page *page, const char *reason)
612 {
613         static unsigned long resume;
614         static unsigned long nr_shown;
615         static unsigned long nr_unshown;
616
617         /*
618          * Allow a burst of 60 reports, then keep quiet for that minute;
619          * or allow a steady drip of one report per second.
620          */
621         if (nr_shown == 60) {
622                 if (time_before(jiffies, resume)) {
623                         nr_unshown++;
624                         goto out;
625                 }
626                 if (nr_unshown) {
627                         pr_alert(
628                               "BUG: Bad page state: %lu messages suppressed\n",
629                                 nr_unshown);
630                         nr_unshown = 0;
631                 }
632                 nr_shown = 0;
633         }
634         if (nr_shown++ == 0)
635                 resume = jiffies + 60 * HZ;
636
637         pr_alert("BUG: Bad page state in process %s  pfn:%05lx\n",
638                 current->comm, page_to_pfn(page));
639         __dump_page(page, reason);
640         dump_page_owner(page);
641
642         print_modules();
643         dump_stack();
644 out:
645         /* Leave bad fields for debug, except PageBuddy could make trouble */
646         page_mapcount_reset(page); /* remove PageBuddy */
647         add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
648 }
649
650 /*
651  * Higher-order pages are called "compound pages".  They are structured thusly:
652  *
653  * The first PAGE_SIZE page is called the "head page" and have PG_head set.
654  *
655  * The remaining PAGE_SIZE pages are called "tail pages". PageTail() is encoded
656  * in bit 0 of page->compound_head. The rest of bits is pointer to head page.
657  *
658  * The first tail page's ->compound_dtor holds the offset in array of compound
659  * page destructors. See compound_page_dtors.
660  *
661  * The first tail page's ->compound_order holds the order of allocation.
662  * This usage means that zero-order pages may not be compound.
663  */
664
665 void free_compound_page(struct page *page)
666 {
667         mem_cgroup_uncharge(page);
668         __free_pages_ok(page, compound_order(page));
669 }
670
671 void prep_compound_page(struct page *page, unsigned int order)
672 {
673         int i;
674         int nr_pages = 1 << order;
675
676         set_compound_page_dtor(page, COMPOUND_PAGE_DTOR);
677         set_compound_order(page, order);
678         __SetPageHead(page);
679         for (i = 1; i < nr_pages; i++) {
680                 struct page *p = page + i;
681                 set_page_count(p, 0);
682                 p->mapping = TAIL_MAPPING;
683                 set_compound_head(p, page);
684         }
685         atomic_set(compound_mapcount_ptr(page), -1);
686         if (hpage_pincount_available(page))
687                 atomic_set(compound_pincount_ptr(page), 0);
688 }
689
690 #ifdef CONFIG_DEBUG_PAGEALLOC
691 unsigned int _debug_guardpage_minorder;
692
693 bool _debug_pagealloc_enabled_early __read_mostly
694                         = IS_ENABLED(CONFIG_DEBUG_PAGEALLOC_ENABLE_DEFAULT);
695 EXPORT_SYMBOL(_debug_pagealloc_enabled_early);
696 DEFINE_STATIC_KEY_FALSE(_debug_pagealloc_enabled);
697 EXPORT_SYMBOL(_debug_pagealloc_enabled);
698
699 DEFINE_STATIC_KEY_FALSE(_debug_guardpage_enabled);
700
701 static int __init early_debug_pagealloc(char *buf)
702 {
703         return kstrtobool(buf, &_debug_pagealloc_enabled_early);
704 }
705 early_param("debug_pagealloc", early_debug_pagealloc);
706
707 void init_debug_pagealloc(void)
708 {
709         if (!debug_pagealloc_enabled())
710                 return;
711
712         static_branch_enable(&_debug_pagealloc_enabled);
713
714         if (!debug_guardpage_minorder())
715                 return;
716
717         static_branch_enable(&_debug_guardpage_enabled);
718 }
719
720 static int __init debug_guardpage_minorder_setup(char *buf)
721 {
722         unsigned long res;
723
724         if (kstrtoul(buf, 10, &res) < 0 ||  res > MAX_ORDER / 2) {
725                 pr_err("Bad debug_guardpage_minorder value\n");
726                 return 0;
727         }
728         _debug_guardpage_minorder = res;
729         pr_info("Setting debug_guardpage_minorder to %lu\n", res);
730         return 0;
731 }
732 early_param("debug_guardpage_minorder", debug_guardpage_minorder_setup);
733
734 static inline bool set_page_guard(struct zone *zone, struct page *page,
735                                 unsigned int order, int migratetype)
736 {
737         if (!debug_guardpage_enabled())
738                 return false;
739
740         if (order >= debug_guardpage_minorder())
741                 return false;
742
743         __SetPageGuard(page);
744         INIT_LIST_HEAD(&page->lru);
745         set_page_private(page, order);
746         /* Guard pages are not available for any usage */
747         __mod_zone_freepage_state(zone, -(1 << order), migratetype);
748
749         return true;
750 }
751
752 static inline void clear_page_guard(struct zone *zone, struct page *page,
753                                 unsigned int order, int migratetype)
754 {
755         if (!debug_guardpage_enabled())
756                 return;
757
758         __ClearPageGuard(page);
759
760         set_page_private(page, 0);
761         if (!is_migrate_isolate(migratetype))
762                 __mod_zone_freepage_state(zone, (1 << order), migratetype);
763 }
764 #else
765 static inline bool set_page_guard(struct zone *zone, struct page *page,
766                         unsigned int order, int migratetype) { return false; }
767 static inline void clear_page_guard(struct zone *zone, struct page *page,
768                                 unsigned int order, int migratetype) {}
769 #endif
770
771 static inline void set_page_order(struct page *page, unsigned int order)
772 {
773         set_page_private(page, order);
774         __SetPageBuddy(page);
775 }
776
777 /*
778  * This function checks whether a page is free && is the buddy
779  * we can coalesce a page and its buddy if
780  * (a) the buddy is not in a hole (check before calling!) &&
781  * (b) the buddy is in the buddy system &&
782  * (c) a page and its buddy have the same order &&
783  * (d) a page and its buddy are in the same zone.
784  *
785  * For recording whether a page is in the buddy system, we set PageBuddy.
786  * Setting, clearing, and testing PageBuddy is serialized by zone->lock.
787  *
788  * For recording page's order, we use page_private(page).
789  */
790 static inline bool page_is_buddy(struct page *page, struct page *buddy,
791                                                         unsigned int order)
792 {
793         if (!page_is_guard(buddy) && !PageBuddy(buddy))
794                 return false;
795
796         if (page_order(buddy) != order)
797                 return false;
798
799         /*
800          * zone check is done late to avoid uselessly calculating
801          * zone/node ids for pages that could never merge.
802          */
803         if (page_zone_id(page) != page_zone_id(buddy))
804                 return false;
805
806         VM_BUG_ON_PAGE(page_count(buddy) != 0, buddy);
807
808         return true;
809 }
810
811 #ifdef CONFIG_COMPACTION
812 static inline struct capture_control *task_capc(struct zone *zone)
813 {
814         struct capture_control *capc = current->capture_control;
815
816         return unlikely(capc) &&
817                 !(current->flags & PF_KTHREAD) &&
818                 !capc->page &&
819                 capc->cc->zone == zone ? capc : NULL;
820 }
821
822 static inline bool
823 compaction_capture(struct capture_control *capc, struct page *page,
824                    int order, int migratetype)
825 {
826         if (!capc || order != capc->cc->order)
827                 return false;
828
829         /* Do not accidentally pollute CMA or isolated regions*/
830         if (is_migrate_cma(migratetype) ||
831             is_migrate_isolate(migratetype))
832                 return false;
833
834         /*
835          * Do not let lower order allocations polluate a movable pageblock.
836          * This might let an unmovable request use a reclaimable pageblock
837          * and vice-versa but no more than normal fallback logic which can
838          * have trouble finding a high-order free page.
839          */
840         if (order < pageblock_order && migratetype == MIGRATE_MOVABLE)
841                 return false;
842
843         capc->page = page;
844         return true;
845 }
846
847 #else
848 static inline struct capture_control *task_capc(struct zone *zone)
849 {
850         return NULL;
851 }
852
853 static inline bool
854 compaction_capture(struct capture_control *capc, struct page *page,
855                    int order, int migratetype)
856 {
857         return false;
858 }
859 #endif /* CONFIG_COMPACTION */
860
861 /* Used for pages not on another list */
862 static inline void add_to_free_list(struct page *page, struct zone *zone,
863                                     unsigned int order, int migratetype)
864 {
865         struct free_area *area = &zone->free_area[order];
866
867         list_add(&page->lru, &area->free_list[migratetype]);
868         area->nr_free++;
869 }
870
871 /* Used for pages not on another list */
872 static inline void add_to_free_list_tail(struct page *page, struct zone *zone,
873                                          unsigned int order, int migratetype)
874 {
875         struct free_area *area = &zone->free_area[order];
876
877         list_add_tail(&page->lru, &area->free_list[migratetype]);
878         area->nr_free++;
879 }
880
881 /* Used for pages which are on another list */
882 static inline void move_to_free_list(struct page *page, struct zone *zone,
883                                      unsigned int order, int migratetype)
884 {
885         struct free_area *area = &zone->free_area[order];
886
887         list_move(&page->lru, &area->free_list[migratetype]);
888 }
889
890 static inline void del_page_from_free_list(struct page *page, struct zone *zone,
891                                            unsigned int order)
892 {
893         /* clear reported state and update reported page count */
894         if (page_reported(page))
895                 __ClearPageReported(page);
896
897         list_del(&page->lru);
898         __ClearPageBuddy(page);
899         set_page_private(page, 0);
900         zone->free_area[order].nr_free--;
901 }
902
903 /*
904  * If this is not the largest possible page, check if the buddy
905  * of the next-highest order is free. If it is, it's possible
906  * that pages are being freed that will coalesce soon. In case,
907  * that is happening, add the free page to the tail of the list
908  * so it's less likely to be used soon and more likely to be merged
909  * as a higher order page
910  */
911 static inline bool
912 buddy_merge_likely(unsigned long pfn, unsigned long buddy_pfn,
913                    struct page *page, unsigned int order)
914 {
915         struct page *higher_page, *higher_buddy;
916         unsigned long combined_pfn;
917
918         if (order >= MAX_ORDER - 2)
919                 return false;
920
921         if (!pfn_valid_within(buddy_pfn))
922                 return false;
923
924         combined_pfn = buddy_pfn & pfn;
925         higher_page = page + (combined_pfn - pfn);
926         buddy_pfn = __find_buddy_pfn(combined_pfn, order + 1);
927         higher_buddy = higher_page + (buddy_pfn - combined_pfn);
928
929         return pfn_valid_within(buddy_pfn) &&
930                page_is_buddy(higher_page, higher_buddy, order + 1);
931 }
932
933 /*
934  * Freeing function for a buddy system allocator.
935  *
936  * The concept of a buddy system is to maintain direct-mapped table
937  * (containing bit values) for memory blocks of various "orders".
938  * The bottom level table contains the map for the smallest allocatable
939  * units of memory (here, pages), and each level above it describes
940  * pairs of units from the levels below, hence, "buddies".
941  * At a high level, all that happens here is marking the table entry
942  * at the bottom level available, and propagating the changes upward
943  * as necessary, plus some accounting needed to play nicely with other
944  * parts of the VM system.
945  * At each level, we keep a list of pages, which are heads of continuous
946  * free pages of length of (1 << order) and marked with PageBuddy.
947  * Page's order is recorded in page_private(page) field.
948  * So when we are allocating or freeing one, we can derive the state of the
949  * other.  That is, if we allocate a small block, and both were
950  * free, the remainder of the region must be split into blocks.
951  * If a block is freed, and its buddy is also free, then this
952  * triggers coalescing into a block of larger size.
953  *
954  * -- nyc
955  */
956
957 static inline void __free_one_page(struct page *page,
958                 unsigned long pfn,
959                 struct zone *zone, unsigned int order,
960                 int migratetype, bool report)
961 {
962         struct capture_control *capc = task_capc(zone);
963         unsigned long buddy_pfn;
964         unsigned long combined_pfn;
965         unsigned int max_order;
966         struct page *buddy;
967         bool to_tail;
968
969         max_order = min_t(unsigned int, MAX_ORDER, pageblock_order + 1);
970
971         VM_BUG_ON(!zone_is_initialized(zone));
972         VM_BUG_ON_PAGE(page->flags & PAGE_FLAGS_CHECK_AT_PREP, page);
973
974         VM_BUG_ON(migratetype == -1);
975         if (likely(!is_migrate_isolate(migratetype)))
976                 __mod_zone_freepage_state(zone, 1 << order, migratetype);
977
978         VM_BUG_ON_PAGE(pfn & ((1 << order) - 1), page);
979         VM_BUG_ON_PAGE(bad_range(zone, page), page);
980
981 continue_merging:
982         while (order < max_order - 1) {
983                 if (compaction_capture(capc, page, order, migratetype)) {
984                         __mod_zone_freepage_state(zone, -(1 << order),
985                                                                 migratetype);
986                         return;
987                 }
988                 buddy_pfn = __find_buddy_pfn(pfn, order);
989                 buddy = page + (buddy_pfn - pfn);
990
991                 if (!pfn_valid_within(buddy_pfn))
992                         goto done_merging;
993                 if (!page_is_buddy(page, buddy, order))
994                         goto done_merging;
995                 /*
996                  * Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page,
997                  * merge with it and move up one order.
998                  */
999                 if (page_is_guard(buddy))
1000                         clear_page_guard(zone, buddy, order, migratetype);
1001                 else
1002                         del_page_from_free_list(buddy, zone, order);
1003                 combined_pfn = buddy_pfn & pfn;
1004                 page = page + (combined_pfn - pfn);
1005                 pfn = combined_pfn;
1006                 order++;
1007         }
1008         if (max_order < MAX_ORDER) {
1009                 /* If we are here, it means order is >= pageblock_order.
1010                  * We want to prevent merge between freepages on isolate
1011                  * pageblock and normal pageblock. Without this, pageblock
1012                  * isolation could cause incorrect freepage or CMA accounting.
1013                  *
1014                  * We don't want to hit this code for the more frequent
1015                  * low-order merging.
1016                  */
1017                 if (unlikely(has_isolate_pageblock(zone))) {
1018                         int buddy_mt;
1019
1020                         buddy_pfn = __find_buddy_pfn(pfn, order);
1021                         buddy = page + (buddy_pfn - pfn);
1022                         buddy_mt = get_pageblock_migratetype(buddy);
1023
1024                         if (migratetype != buddy_mt
1025                                         && (is_migrate_isolate(migratetype) ||
1026                                                 is_migrate_isolate(buddy_mt)))
1027                                 goto done_merging;
1028                 }
1029                 max_order++;
1030                 goto continue_merging;
1031         }
1032
1033 done_merging:
1034         set_page_order(page, order);
1035
1036         if (is_shuffle_order(order))
1037                 to_tail = shuffle_pick_tail();
1038         else
1039                 to_tail = buddy_merge_likely(pfn, buddy_pfn, page, order);
1040
1041         if (to_tail)
1042                 add_to_free_list_tail(page, zone, order, migratetype);
1043         else
1044                 add_to_free_list(page, zone, order, migratetype);
1045
1046         /* Notify page reporting subsystem of freed page */
1047         if (report)
1048                 page_reporting_notify_free(order);
1049 }
1050
1051 /*
1052  * A bad page could be due to a number of fields. Instead of multiple branches,
1053  * try and check multiple fields with one check. The caller must do a detailed
1054  * check if necessary.
1055  */
1056 static inline bool page_expected_state(struct page *page,
1057                                         unsigned long check_flags)
1058 {
1059         if (unlikely(atomic_read(&page->_mapcount) != -1))
1060                 return false;
1061
1062         if (unlikely((unsigned long)page->mapping |
1063                         page_ref_count(page) |
1064 #ifdef CONFIG_MEMCG
1065                         (unsigned long)page->mem_cgroup |
1066 #endif
1067                         (page->flags & check_flags)))
1068                 return false;
1069
1070         return true;
1071 }
1072
1073 static const char *page_bad_reason(struct page *page, unsigned long flags)
1074 {
1075         const char *bad_reason = NULL;
1076
1077         if (unlikely(atomic_read(&page->_mapcount) != -1))
1078                 bad_reason = "nonzero mapcount";
1079         if (unlikely(page->mapping != NULL))
1080                 bad_reason = "non-NULL mapping";
1081         if (unlikely(page_ref_count(page) != 0))
1082                 bad_reason = "nonzero _refcount";
1083         if (unlikely(page->flags & flags)) {
1084                 if (flags == PAGE_FLAGS_CHECK_AT_PREP)
1085                         bad_reason = "PAGE_FLAGS_CHECK_AT_PREP flag(s) set";
1086                 else
1087                         bad_reason = "PAGE_FLAGS_CHECK_AT_FREE flag(s) set";
1088         }
1089 #ifdef CONFIG_MEMCG
1090         if (unlikely(page->mem_cgroup))
1091                 bad_reason = "page still charged to cgroup";
1092 #endif
1093         return bad_reason;
1094 }
1095
1096 static void check_free_page_bad(struct page *page)
1097 {
1098         bad_page(page,
1099                  page_bad_reason(page, PAGE_FLAGS_CHECK_AT_FREE));
1100 }
1101
1102 static inline int check_free_page(struct page *page)
1103 {
1104         if (likely(page_expected_state(page, PAGE_FLAGS_CHECK_AT_FREE)))
1105                 return 0;
1106
1107         /* Something has gone sideways, find it */
1108         check_free_page_bad(page);
1109         return 1;
1110 }
1111
1112 static int free_tail_pages_check(struct page *head_page, struct page *page)
1113 {
1114         int ret = 1;
1115
1116         /*
1117          * We rely page->lru.next never has bit 0 set, unless the page
1118          * is PageTail(). Let's make sure that's true even for poisoned ->lru.
1119          */
1120         BUILD_BUG_ON((unsigned long)LIST_POISON1 & 1);
1121
1122         if (!IS_ENABLED(CONFIG_DEBUG_VM)) {
1123                 ret = 0;
1124                 goto out;
1125         }
1126         switch (page - head_page) {
1127         case 1:
1128                 /* the first tail page: ->mapping may be compound_mapcount() */
1129                 if (unlikely(compound_mapcount(page))) {
1130                         bad_page(page, "nonzero compound_mapcount");
1131                         goto out;
1132                 }
1133                 break;
1134         case 2:
1135                 /*
1136                  * the second tail page: ->mapping is
1137                  * deferred_list.next -- ignore value.
1138                  */
1139                 break;
1140         default:
1141                 if (page->mapping != TAIL_MAPPING) {
1142                         bad_page(page, "corrupted mapping in tail page");
1143                         goto out;
1144                 }
1145                 break;
1146         }
1147         if (unlikely(!PageTail(page))) {
1148                 bad_page(page, "PageTail not set");
1149                 goto out;
1150         }
1151         if (unlikely(compound_head(page) != head_page)) {
1152                 bad_page(page, "compound_head not consistent");
1153                 goto out;
1154         }
1155         ret = 0;
1156 out:
1157         page->mapping = NULL;
1158         clear_compound_head(page);
1159         return ret;
1160 }
1161
1162 static void kernel_init_free_pages(struct page *page, int numpages)
1163 {
1164         int i;
1165
1166         for (i = 0; i < numpages; i++)
1167                 clear_highpage(page + i);
1168 }
1169
1170 static __always_inline bool free_pages_prepare(struct page *page,
1171                                         unsigned int order, bool check_free)
1172 {
1173         int bad = 0;
1174
1175         VM_BUG_ON_PAGE(PageTail(page), page);
1176
1177         trace_mm_page_free(page, order);
1178
1179         /*
1180          * Check tail pages before head page information is cleared to
1181          * avoid checking PageCompound for order-0 pages.
1182          */
1183         if (unlikely(order)) {
1184                 bool compound = PageCompound(page);
1185                 int i;
1186
1187                 VM_BUG_ON_PAGE(compound && compound_order(page) != order, page);
1188
1189                 if (compound)
1190                         ClearPageDoubleMap(page);
1191                 for (i = 1; i < (1 << order); i++) {
1192                         if (compound)
1193                                 bad += free_tail_pages_check(page, page + i);
1194                         if (unlikely(check_free_page(page + i))) {
1195                                 bad++;
1196                                 continue;
1197                         }
1198                         (page + i)->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
1199                 }
1200         }
1201         if (PageMappingFlags(page))
1202                 page->mapping = NULL;
1203         if (memcg_kmem_enabled() && PageKmemcg(page))
1204                 __memcg_kmem_uncharge_page(page, order);
1205         if (check_free)
1206                 bad += check_free_page(page);
1207         if (bad)
1208                 return false;
1209
1210         page_cpupid_reset_last(page);
1211         page->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
1212         reset_page_owner(page, order);
1213
1214         if (!PageHighMem(page)) {
1215                 debug_check_no_locks_freed(page_address(page),
1216                                            PAGE_SIZE << order);
1217                 debug_check_no_obj_freed(page_address(page),
1218                                            PAGE_SIZE << order);
1219         }
1220         if (want_init_on_free())
1221                 kernel_init_free_pages(page, 1 << order);
1222
1223         kernel_poison_pages(page, 1 << order, 0);
1224         /*
1225          * arch_free_page() can make the page's contents inaccessible.  s390
1226          * does this.  So nothing which can access the page's contents should
1227          * happen after this.
1228          */
1229         arch_free_page(page, order);
1230
1231         if (debug_pagealloc_enabled_static())
1232                 kernel_map_pages(page, 1 << order, 0);
1233
1234         kasan_free_nondeferred_pages(page, order);
1235
1236         return true;
1237 }
1238
1239 #ifdef CONFIG_DEBUG_VM
1240 /*
1241  * With DEBUG_VM enabled, order-0 pages are checked immediately when being freed
1242  * to pcp lists. With debug_pagealloc also enabled, they are also rechecked when
1243  * moved from pcp lists to free lists.
1244  */
1245 static bool free_pcp_prepare(struct page *page)
1246 {
1247         return free_pages_prepare(page, 0, true);
1248 }
1249
1250 static bool bulkfree_pcp_prepare(struct page *page)
1251 {
1252         if (debug_pagealloc_enabled_static())
1253                 return check_free_page(page);
1254         else
1255                 return false;
1256 }
1257 #else
1258 /*
1259  * With DEBUG_VM disabled, order-0 pages being freed are checked only when
1260  * moving from pcp lists to free list in order to reduce overhead. With
1261  * debug_pagealloc enabled, they are checked also immediately when being freed
1262  * to the pcp lists.
1263  */
1264 static bool free_pcp_prepare(struct page *page)
1265 {
1266         if (debug_pagealloc_enabled_static())
1267                 return free_pages_prepare(page, 0, true);
1268         else
1269                 return free_pages_prepare(page, 0, false);
1270 }
1271
1272 static bool bulkfree_pcp_prepare(struct page *page)
1273 {
1274         return check_free_page(page);
1275 }
1276 #endif /* CONFIG_DEBUG_VM */
1277
1278 static inline void prefetch_buddy(struct page *page)
1279 {
1280         unsigned long pfn = page_to_pfn(page);
1281         unsigned long buddy_pfn = __find_buddy_pfn(pfn, 0);
1282         struct page *buddy = page + (buddy_pfn - pfn);
1283
1284         prefetch(buddy);
1285 }
1286
1287 /*
1288  * Frees a number of pages from the PCP lists
1289  * Assumes all pages on list are in same zone, and of same order.
1290  * count is the number of pages to free.
1291  *
1292  * If the zone was previously in an "all pages pinned" state then look to
1293  * see if this freeing clears that state.
1294  *
1295  * And clear the zone's pages_scanned counter, to hold off the "all pages are
1296  * pinned" detection logic.
1297  */
1298 static void free_pcppages_bulk(struct zone *zone, int count,
1299                                         struct per_cpu_pages *pcp)
1300 {
1301         int migratetype = 0;
1302         int batch_free = 0;
1303         int prefetch_nr = 0;
1304         bool isolated_pageblocks;
1305         struct page *page, *tmp;
1306         LIST_HEAD(head);
1307
1308         while (count) {
1309                 struct list_head *list;
1310
1311                 /*
1312                  * Remove pages from lists in a round-robin fashion. A
1313                  * batch_free count is maintained that is incremented when an
1314                  * empty list is encountered.  This is so more pages are freed
1315                  * off fuller lists instead of spinning excessively around empty
1316                  * lists
1317                  */
1318                 do {
1319                         batch_free++;
1320                         if (++migratetype == MIGRATE_PCPTYPES)
1321                                 migratetype = 0;
1322                         list = &pcp->lists[migratetype];
1323                 } while (list_empty(list));
1324
1325                 /* This is the only non-empty list. Free them all. */
1326                 if (batch_free == MIGRATE_PCPTYPES)
1327                         batch_free = count;
1328
1329                 do {
1330                         page = list_last_entry(list, struct page, lru);
1331                         /* must delete to avoid corrupting pcp list */
1332                         list_del(&page->lru);
1333                         pcp->count--;
1334
1335                         if (bulkfree_pcp_prepare(page))
1336                                 continue;
1337
1338                         list_add_tail(&page->lru, &head);
1339
1340                         /*
1341                          * We are going to put the page back to the global
1342                          * pool, prefetch its buddy to speed up later access
1343                          * under zone->lock. It is believed the overhead of
1344                          * an additional test and calculating buddy_pfn here
1345                          * can be offset by reduced memory latency later. To
1346                          * avoid excessive prefetching due to large count, only
1347                          * prefetch buddy for the first pcp->batch nr of pages.
1348                          */
1349                         if (prefetch_nr++ < pcp->batch)
1350                                 prefetch_buddy(page);
1351                 } while (--count && --batch_free && !list_empty(list));
1352         }
1353
1354         spin_lock(&zone->lock);
1355         isolated_pageblocks = has_isolate_pageblock(zone);
1356
1357         /*
1358          * Use safe version since after __free_one_page(),
1359          * page->lru.next will not point to original list.
1360          */
1361         list_for_each_entry_safe(page, tmp, &head, lru) {
1362                 int mt = get_pcppage_migratetype(page);
1363                 /* MIGRATE_ISOLATE page should not go to pcplists */
1364                 VM_BUG_ON_PAGE(is_migrate_isolate(mt), page);
1365                 /* Pageblock could have been isolated meanwhile */
1366                 if (unlikely(isolated_pageblocks))
1367                         mt = get_pageblock_migratetype(page);
1368
1369                 __free_one_page(page, page_to_pfn(page), zone, 0, mt, true);
1370                 trace_mm_page_pcpu_drain(page, 0, mt);
1371         }
1372         spin_unlock(&zone->lock);
1373 }
1374
1375 static void free_one_page(struct zone *zone,
1376                                 struct page *page, unsigned long pfn,
1377                                 unsigned int order,
1378                                 int migratetype)
1379 {
1380         spin_lock(&zone->lock);
1381         if (unlikely(has_isolate_pageblock(zone) ||
1382                 is_migrate_isolate(migratetype))) {
1383                 migratetype = get_pfnblock_migratetype(page, pfn);
1384         }
1385         __free_one_page(page, pfn, zone, order, migratetype, true);
1386         spin_unlock(&zone->lock);
1387 }
1388
1389 static void __meminit __init_single_page(struct page *page, unsigned long pfn,
1390                                 unsigned long zone, int nid)
1391 {
1392         mm_zero_struct_page(page);
1393         set_page_links(page, zone, nid, pfn);
1394         init_page_count(page);
1395         page_mapcount_reset(page);
1396         page_cpupid_reset_last(page);
1397         page_kasan_tag_reset(page);
1398
1399         INIT_LIST_HEAD(&page->lru);
1400 #ifdef WANT_PAGE_VIRTUAL
1401         /* The shift won't overflow because ZONE_NORMAL is below 4G. */
1402         if (!is_highmem_idx(zone))
1403                 set_page_address(page, __va(pfn << PAGE_SHIFT));
1404 #endif
1405 }
1406
1407 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1408 static void __meminit init_reserved_page(unsigned long pfn)
1409 {
1410         pg_data_t *pgdat;
1411         int nid, zid;
1412
1413         if (!early_page_uninitialised(pfn))
1414                 return;
1415
1416         nid = early_pfn_to_nid(pfn);
1417         pgdat = NODE_DATA(nid);
1418
1419         for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1420                 struct zone *zone = &pgdat->node_zones[zid];
1421
1422                 if (pfn >= zone->zone_start_pfn && pfn < zone_end_pfn(zone))
1423                         break;
1424         }
1425         __init_single_page(pfn_to_page(pfn), pfn, zid, nid);
1426 }
1427 #else
1428 static inline void init_reserved_page(unsigned long pfn)
1429 {
1430 }
1431 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
1432
1433 /*
1434  * Initialised pages do not have PageReserved set. This function is
1435  * called for each range allocated by the bootmem allocator and
1436  * marks the pages PageReserved. The remaining valid pages are later
1437  * sent to the buddy page allocator.
1438  */
1439 void __meminit reserve_bootmem_region(phys_addr_t start, phys_addr_t end)
1440 {
1441         unsigned long start_pfn = PFN_DOWN(start);
1442         unsigned long end_pfn = PFN_UP(end);
1443
1444         for (; start_pfn < end_pfn; start_pfn++) {
1445                 if (pfn_valid(start_pfn)) {
1446                         struct page *page = pfn_to_page(start_pfn);
1447
1448                         init_reserved_page(start_pfn);
1449
1450                         /* Avoid false-positive PageTail() */
1451                         INIT_LIST_HEAD(&page->lru);
1452
1453                         /*
1454                          * no need for atomic set_bit because the struct
1455                          * page is not visible yet so nobody should
1456                          * access it yet.
1457                          */
1458                         __SetPageReserved(page);
1459                 }
1460         }
1461 }
1462
1463 static void __free_pages_ok(struct page *page, unsigned int order)
1464 {
1465         unsigned long flags;
1466         int migratetype;
1467         unsigned long pfn = page_to_pfn(page);
1468
1469         if (!free_pages_prepare(page, order, true))
1470                 return;
1471
1472         migratetype = get_pfnblock_migratetype(page, pfn);
1473         local_irq_save(flags);
1474         __count_vm_events(PGFREE, 1 << order);
1475         free_one_page(page_zone(page), page, pfn, order, migratetype);
1476         local_irq_restore(flags);
1477 }
1478
1479 void __free_pages_core(struct page *page, unsigned int order)
1480 {
1481         unsigned int nr_pages = 1 << order;
1482         struct page *p = page;
1483         unsigned int loop;
1484
1485         prefetchw(p);
1486         for (loop = 0; loop < (nr_pages - 1); loop++, p++) {
1487                 prefetchw(p + 1);
1488                 __ClearPageReserved(p);
1489                 set_page_count(p, 0);
1490         }
1491         __ClearPageReserved(p);
1492         set_page_count(p, 0);
1493
1494         atomic_long_add(nr_pages, &page_zone(page)->managed_pages);
1495         set_page_refcounted(page);
1496         __free_pages(page, order);
1497 }
1498
1499 #ifdef CONFIG_NEED_MULTIPLE_NODES
1500
1501 static struct mminit_pfnnid_cache early_pfnnid_cache __meminitdata;
1502
1503 #ifndef CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID
1504
1505 /*
1506  * Required by SPARSEMEM. Given a PFN, return what node the PFN is on.
1507  */
1508 int __meminit __early_pfn_to_nid(unsigned long pfn,
1509                                         struct mminit_pfnnid_cache *state)
1510 {
1511         unsigned long start_pfn, end_pfn;
1512         int nid;
1513
1514         if (state->last_start <= pfn && pfn < state->last_end)
1515                 return state->last_nid;
1516
1517         nid = memblock_search_pfn_nid(pfn, &start_pfn, &end_pfn);
1518         if (nid != NUMA_NO_NODE) {
1519                 state->last_start = start_pfn;
1520                 state->last_end = end_pfn;
1521                 state->last_nid = nid;
1522         }
1523
1524         return nid;
1525 }
1526 #endif /* CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID */
1527
1528 int __meminit early_pfn_to_nid(unsigned long pfn)
1529 {
1530         static DEFINE_SPINLOCK(early_pfn_lock);
1531         int nid;
1532
1533         spin_lock(&early_pfn_lock);
1534         nid = __early_pfn_to_nid(pfn, &early_pfnnid_cache);
1535         if (nid < 0)
1536                 nid = first_online_node;
1537         spin_unlock(&early_pfn_lock);
1538
1539         return nid;
1540 }
1541 #endif /* CONFIG_NEED_MULTIPLE_NODES */
1542
1543 void __init memblock_free_pages(struct page *page, unsigned long pfn,
1544                                                         unsigned int order)
1545 {
1546         if (early_page_uninitialised(pfn))
1547                 return;
1548         __free_pages_core(page, order);
1549 }
1550
1551 /*
1552  * Check that the whole (or subset of) a pageblock given by the interval of
1553  * [start_pfn, end_pfn) is valid and within the same zone, before scanning it
1554  * with the migration of free compaction scanner. The scanners then need to
1555  * use only pfn_valid_within() check for arches that allow holes within
1556  * pageblocks.
1557  *
1558  * Return struct page pointer of start_pfn, or NULL if checks were not passed.
1559  *
1560  * It's possible on some configurations to have a setup like node0 node1 node0
1561  * i.e. it's possible that all pages within a zones range of pages do not
1562  * belong to a single zone. We assume that a border between node0 and node1
1563  * can occur within a single pageblock, but not a node0 node1 node0
1564  * interleaving within a single pageblock. It is therefore sufficient to check
1565  * the first and last page of a pageblock and avoid checking each individual
1566  * page in a pageblock.
1567  */
1568 struct page *__pageblock_pfn_to_page(unsigned long start_pfn,
1569                                      unsigned long end_pfn, struct zone *zone)
1570 {
1571         struct page *start_page;
1572         struct page *end_page;
1573
1574         /* end_pfn is one past the range we are checking */
1575         end_pfn--;
1576
1577         if (!pfn_valid(start_pfn) || !pfn_valid(end_pfn))
1578                 return NULL;
1579
1580         start_page = pfn_to_online_page(start_pfn);
1581         if (!start_page)
1582                 return NULL;
1583
1584         if (page_zone(start_page) != zone)
1585                 return NULL;
1586
1587         end_page = pfn_to_page(end_pfn);
1588
1589         /* This gives a shorter code than deriving page_zone(end_page) */
1590         if (page_zone_id(start_page) != page_zone_id(end_page))
1591                 return NULL;
1592
1593         return start_page;
1594 }
1595
1596 void set_zone_contiguous(struct zone *zone)
1597 {
1598         unsigned long block_start_pfn = zone->zone_start_pfn;
1599         unsigned long block_end_pfn;
1600
1601         block_end_pfn = ALIGN(block_start_pfn + 1, pageblock_nr_pages);
1602         for (; block_start_pfn < zone_end_pfn(zone);
1603                         block_start_pfn = block_end_pfn,
1604                          block_end_pfn += pageblock_nr_pages) {
1605
1606                 block_end_pfn = min(block_end_pfn, zone_end_pfn(zone));
1607
1608                 if (!__pageblock_pfn_to_page(block_start_pfn,
1609                                              block_end_pfn, zone))
1610                         return;
1611                 cond_resched();
1612         }
1613
1614         /* We confirm that there is no hole */
1615         zone->contiguous = true;
1616 }
1617
1618 void clear_zone_contiguous(struct zone *zone)
1619 {
1620         zone->contiguous = false;
1621 }
1622
1623 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1624 static void __init deferred_free_range(unsigned long pfn,
1625                                        unsigned long nr_pages)
1626 {
1627         struct page *page;
1628         unsigned long i;
1629
1630         if (!nr_pages)
1631                 return;
1632
1633         page = pfn_to_page(pfn);
1634
1635         /* Free a large naturally-aligned chunk if possible */
1636         if (nr_pages == pageblock_nr_pages &&
1637             (pfn & (pageblock_nr_pages - 1)) == 0) {
1638                 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
1639                 __free_pages_core(page, pageblock_order);
1640                 return;
1641         }
1642
1643         for (i = 0; i < nr_pages; i++, page++, pfn++) {
1644                 if ((pfn & (pageblock_nr_pages - 1)) == 0)
1645                         set_pageblock_migratetype(page, MIGRATE_MOVABLE);
1646                 __free_pages_core(page, 0);
1647         }
1648 }
1649
1650 /* Completion tracking for deferred_init_memmap() threads */
1651 static atomic_t pgdat_init_n_undone __initdata;
1652 static __initdata DECLARE_COMPLETION(pgdat_init_all_done_comp);
1653
1654 static inline void __init pgdat_init_report_one_done(void)
1655 {
1656         if (atomic_dec_and_test(&pgdat_init_n_undone))
1657                 complete(&pgdat_init_all_done_comp);
1658 }
1659
1660 /*
1661  * Returns true if page needs to be initialized or freed to buddy allocator.
1662  *
1663  * First we check if pfn is valid on architectures where it is possible to have
1664  * holes within pageblock_nr_pages. On systems where it is not possible, this
1665  * function is optimized out.
1666  *
1667  * Then, we check if a current large page is valid by only checking the validity
1668  * of the head pfn.
1669  */
1670 static inline bool __init deferred_pfn_valid(unsigned long pfn)
1671 {
1672         if (!pfn_valid_within(pfn))
1673                 return false;
1674         if (!(pfn & (pageblock_nr_pages - 1)) && !pfn_valid(pfn))
1675                 return false;
1676         return true;
1677 }
1678
1679 /*
1680  * Free pages to buddy allocator. Try to free aligned pages in
1681  * pageblock_nr_pages sizes.
1682  */
1683 static void __init deferred_free_pages(unsigned long pfn,
1684                                        unsigned long end_pfn)
1685 {
1686         unsigned long nr_pgmask = pageblock_nr_pages - 1;
1687         unsigned long nr_free = 0;
1688
1689         for (; pfn < end_pfn; pfn++) {
1690                 if (!deferred_pfn_valid(pfn)) {
1691                         deferred_free_range(pfn - nr_free, nr_free);
1692                         nr_free = 0;
1693                 } else if (!(pfn & nr_pgmask)) {
1694                         deferred_free_range(pfn - nr_free, nr_free);
1695                         nr_free = 1;
1696                 } else {
1697                         nr_free++;
1698                 }
1699         }
1700         /* Free the last block of pages to allocator */
1701         deferred_free_range(pfn - nr_free, nr_free);
1702 }
1703
1704 /*
1705  * Initialize struct pages.  We minimize pfn page lookups and scheduler checks
1706  * by performing it only once every pageblock_nr_pages.
1707  * Return number of pages initialized.
1708  */
1709 static unsigned long  __init deferred_init_pages(struct zone *zone,
1710                                                  unsigned long pfn,
1711                                                  unsigned long end_pfn)
1712 {
1713         unsigned long nr_pgmask = pageblock_nr_pages - 1;
1714         int nid = zone_to_nid(zone);
1715         unsigned long nr_pages = 0;
1716         int zid = zone_idx(zone);
1717         struct page *page = NULL;
1718
1719         for (; pfn < end_pfn; pfn++) {
1720                 if (!deferred_pfn_valid(pfn)) {
1721                         page = NULL;
1722                         continue;
1723                 } else if (!page || !(pfn & nr_pgmask)) {
1724                         page = pfn_to_page(pfn);
1725                 } else {
1726                         page++;
1727                 }
1728                 __init_single_page(page, pfn, zid, nid);
1729                 nr_pages++;
1730         }
1731         return (nr_pages);
1732 }
1733
1734 /*
1735  * This function is meant to pre-load the iterator for the zone init.
1736  * Specifically it walks through the ranges until we are caught up to the
1737  * first_init_pfn value and exits there. If we never encounter the value we
1738  * return false indicating there are no valid ranges left.
1739  */
1740 static bool __init
1741 deferred_init_mem_pfn_range_in_zone(u64 *i, struct zone *zone,
1742                                     unsigned long *spfn, unsigned long *epfn,
1743                                     unsigned long first_init_pfn)
1744 {
1745         u64 j;
1746
1747         /*
1748          * Start out by walking through the ranges in this zone that have
1749          * already been initialized. We don't need to do anything with them
1750          * so we just need to flush them out of the system.
1751          */
1752         for_each_free_mem_pfn_range_in_zone(j, zone, spfn, epfn) {
1753                 if (*epfn <= first_init_pfn)
1754                         continue;
1755                 if (*spfn < first_init_pfn)
1756                         *spfn = first_init_pfn;
1757                 *i = j;
1758                 return true;
1759         }
1760
1761         return false;
1762 }
1763
1764 /*
1765  * Initialize and free pages. We do it in two loops: first we initialize
1766  * struct page, then free to buddy allocator, because while we are
1767  * freeing pages we can access pages that are ahead (computing buddy
1768  * page in __free_one_page()).
1769  *
1770  * In order to try and keep some memory in the cache we have the loop
1771  * broken along max page order boundaries. This way we will not cause
1772  * any issues with the buddy page computation.
1773  */
1774 static unsigned long __init
1775 deferred_init_maxorder(u64 *i, struct zone *zone, unsigned long *start_pfn,
1776                        unsigned long *end_pfn)
1777 {
1778         unsigned long mo_pfn = ALIGN(*start_pfn + 1, MAX_ORDER_NR_PAGES);
1779         unsigned long spfn = *start_pfn, epfn = *end_pfn;
1780         unsigned long nr_pages = 0;
1781         u64 j = *i;
1782
1783         /* First we loop through and initialize the page values */
1784         for_each_free_mem_pfn_range_in_zone_from(j, zone, start_pfn, end_pfn) {
1785                 unsigned long t;
1786
1787                 if (mo_pfn <= *start_pfn)
1788                         break;
1789
1790                 t = min(mo_pfn, *end_pfn);
1791                 nr_pages += deferred_init_pages(zone, *start_pfn, t);
1792
1793                 if (mo_pfn < *end_pfn) {
1794                         *start_pfn = mo_pfn;
1795                         break;
1796                 }
1797         }
1798
1799         /* Reset values and now loop through freeing pages as needed */
1800         swap(j, *i);
1801
1802         for_each_free_mem_pfn_range_in_zone_from(j, zone, &spfn, &epfn) {
1803                 unsigned long t;
1804
1805                 if (mo_pfn <= spfn)
1806                         break;
1807
1808                 t = min(mo_pfn, epfn);
1809                 deferred_free_pages(spfn, t);
1810
1811                 if (mo_pfn <= epfn)
1812                         break;
1813         }
1814
1815         return nr_pages;
1816 }
1817
1818 static void __init
1819 deferred_init_memmap_chunk(unsigned long start_pfn, unsigned long end_pfn,
1820                            void *arg)
1821 {
1822         unsigned long spfn, epfn;
1823         struct zone *zone = arg;
1824         u64 i;
1825
1826         deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn, start_pfn);
1827
1828         /*
1829          * Initialize and free pages in MAX_ORDER sized increments so that we
1830          * can avoid introducing any issues with the buddy allocator.
1831          */
1832         while (spfn < end_pfn) {
1833                 deferred_init_maxorder(&i, zone, &spfn, &epfn);
1834                 cond_resched();
1835         }
1836 }
1837
1838 /* An arch may override for more concurrency. */
1839 __weak int __init
1840 deferred_page_init_max_threads(const struct cpumask *node_cpumask)
1841 {
1842         return 1;
1843 }
1844
1845 /* Initialise remaining memory on a node */
1846 static int __init deferred_init_memmap(void *data)
1847 {
1848         pg_data_t *pgdat = data;
1849         const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
1850         unsigned long spfn = 0, epfn = 0;
1851         unsigned long first_init_pfn, flags;
1852         unsigned long start = jiffies;
1853         struct zone *zone;
1854         int zid, max_threads;
1855         u64 i;
1856
1857         /* Bind memory initialisation thread to a local node if possible */
1858         if (!cpumask_empty(cpumask))
1859                 set_cpus_allowed_ptr(current, cpumask);
1860
1861         pgdat_resize_lock(pgdat, &flags);
1862         first_init_pfn = pgdat->first_deferred_pfn;
1863         if (first_init_pfn == ULONG_MAX) {
1864                 pgdat_resize_unlock(pgdat, &flags);
1865                 pgdat_init_report_one_done();
1866                 return 0;
1867         }
1868
1869         /* Sanity check boundaries */
1870         BUG_ON(pgdat->first_deferred_pfn < pgdat->node_start_pfn);
1871         BUG_ON(pgdat->first_deferred_pfn > pgdat_end_pfn(pgdat));
1872         pgdat->first_deferred_pfn = ULONG_MAX;
1873
1874         /*
1875          * Once we unlock here, the zone cannot be grown anymore, thus if an
1876          * interrupt thread must allocate this early in boot, zone must be
1877          * pre-grown prior to start of deferred page initialization.
1878          */
1879         pgdat_resize_unlock(pgdat, &flags);
1880
1881         /* Only the highest zone is deferred so find it */
1882         for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1883                 zone = pgdat->node_zones + zid;
1884                 if (first_init_pfn < zone_end_pfn(zone))
1885                         break;
1886         }
1887
1888         /* If the zone is empty somebody else may have cleared out the zone */
1889         if (!deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn,
1890                                                  first_init_pfn))
1891                 goto zone_empty;
1892
1893         max_threads = deferred_page_init_max_threads(cpumask);
1894
1895         while (spfn < epfn) {
1896                 unsigned long epfn_align = ALIGN(epfn, PAGES_PER_SECTION);
1897                 struct padata_mt_job job = {
1898                         .thread_fn   = deferred_init_memmap_chunk,
1899                         .fn_arg      = zone,
1900                         .start       = spfn,
1901                         .size        = epfn_align - spfn,
1902                         .align       = PAGES_PER_SECTION,
1903                         .min_chunk   = PAGES_PER_SECTION,
1904                         .max_threads = max_threads,
1905                 };
1906
1907                 padata_do_multithreaded(&job);
1908                 deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn,
1909                                                     epfn_align);
1910         }
1911 zone_empty:
1912         /* Sanity check that the next zone really is unpopulated */
1913         WARN_ON(++zid < MAX_NR_ZONES && populated_zone(++zone));
1914
1915         pr_info("node %d deferred pages initialised in %ums\n",
1916                 pgdat->node_id, jiffies_to_msecs(jiffies - start));
1917
1918         pgdat_init_report_one_done();
1919         return 0;
1920 }
1921
1922 /*
1923  * If this zone has deferred pages, try to grow it by initializing enough
1924  * deferred pages to satisfy the allocation specified by order, rounded up to
1925  * the nearest PAGES_PER_SECTION boundary.  So we're adding memory in increments
1926  * of SECTION_SIZE bytes by initializing struct pages in increments of
1927  * PAGES_PER_SECTION * sizeof(struct page) bytes.
1928  *
1929  * Return true when zone was grown, otherwise return false. We return true even
1930  * when we grow less than requested, to let the caller decide if there are
1931  * enough pages to satisfy the allocation.
1932  *
1933  * Note: We use noinline because this function is needed only during boot, and
1934  * it is called from a __ref function _deferred_grow_zone. This way we are
1935  * making sure that it is not inlined into permanent text section.
1936  */
1937 static noinline bool __init
1938 deferred_grow_zone(struct zone *zone, unsigned int order)
1939 {
1940         unsigned long nr_pages_needed = ALIGN(1 << order, PAGES_PER_SECTION);
1941         pg_data_t *pgdat = zone->zone_pgdat;
1942         unsigned long first_deferred_pfn = pgdat->first_deferred_pfn;
1943         unsigned long spfn, epfn, flags;
1944         unsigned long nr_pages = 0;
1945         u64 i;
1946
1947         /* Only the last zone may have deferred pages */
1948         if (zone_end_pfn(zone) != pgdat_end_pfn(pgdat))
1949                 return false;
1950
1951         pgdat_resize_lock(pgdat, &flags);
1952
1953         /*
1954          * If someone grew this zone while we were waiting for spinlock, return
1955          * true, as there might be enough pages already.
1956          */
1957         if (first_deferred_pfn != pgdat->first_deferred_pfn) {
1958                 pgdat_resize_unlock(pgdat, &flags);
1959                 return true;
1960         }
1961
1962         /* If the zone is empty somebody else may have cleared out the zone */
1963         if (!deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn,
1964                                                  first_deferred_pfn)) {
1965                 pgdat->first_deferred_pfn = ULONG_MAX;
1966                 pgdat_resize_unlock(pgdat, &flags);
1967                 /* Retry only once. */
1968                 return first_deferred_pfn != ULONG_MAX;
1969         }
1970
1971         /*
1972          * Initialize and free pages in MAX_ORDER sized increments so
1973          * that we can avoid introducing any issues with the buddy
1974          * allocator.
1975          */
1976         while (spfn < epfn) {
1977                 /* update our first deferred PFN for this section */
1978                 first_deferred_pfn = spfn;
1979
1980                 nr_pages += deferred_init_maxorder(&i, zone, &spfn, &epfn);
1981                 touch_nmi_watchdog();
1982
1983                 /* We should only stop along section boundaries */
1984                 if ((first_deferred_pfn ^ spfn) < PAGES_PER_SECTION)
1985                         continue;
1986
1987                 /* If our quota has been met we can stop here */
1988                 if (nr_pages >= nr_pages_needed)
1989                         break;
1990         }
1991
1992         pgdat->first_deferred_pfn = spfn;
1993         pgdat_resize_unlock(pgdat, &flags);
1994
1995         return nr_pages > 0;
1996 }
1997
1998 /*
1999  * deferred_grow_zone() is __init, but it is called from
2000  * get_page_from_freelist() during early boot until deferred_pages permanently
2001  * disables this call. This is why we have refdata wrapper to avoid warning,
2002  * and to ensure that the function body gets unloaded.
2003  */
2004 static bool __ref
2005 _deferred_grow_zone(struct zone *zone, unsigned int order)
2006 {
2007         return deferred_grow_zone(zone, order);
2008 }
2009
2010 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
2011
2012 void __init page_alloc_init_late(void)
2013 {
2014         struct zone *zone;
2015         int nid;
2016
2017 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
2018
2019         /* There will be num_node_state(N_MEMORY) threads */
2020         atomic_set(&pgdat_init_n_undone, num_node_state(N_MEMORY));
2021         for_each_node_state(nid, N_MEMORY) {
2022                 kthread_run(deferred_init_memmap, NODE_DATA(nid), "pgdatinit%d", nid);
2023         }
2024
2025         /* Block until all are initialised */
2026         wait_for_completion(&pgdat_init_all_done_comp);
2027
2028         /*
2029          * The number of managed pages has changed due to the initialisation
2030          * so the pcpu batch and high limits needs to be updated or the limits
2031          * will be artificially small.
2032          */
2033         for_each_populated_zone(zone)
2034                 zone_pcp_update(zone);
2035
2036         /*
2037          * We initialized the rest of the deferred pages.  Permanently disable
2038          * on-demand struct page initialization.
2039          */
2040         static_branch_disable(&deferred_pages);
2041
2042         /* Reinit limits that are based on free pages after the kernel is up */
2043         files_maxfiles_init();
2044 #endif
2045
2046         /* Discard memblock private memory */
2047         memblock_discard();
2048
2049         for_each_node_state(nid, N_MEMORY)
2050                 shuffle_free_memory(NODE_DATA(nid));
2051
2052         for_each_populated_zone(zone)
2053                 set_zone_contiguous(zone);
2054 }
2055
2056 #ifdef CONFIG_CMA
2057 /* Free whole pageblock and set its migration type to MIGRATE_CMA. */
2058 void __init init_cma_reserved_pageblock(struct page *page)
2059 {
2060         unsigned i = pageblock_nr_pages;
2061         struct page *p = page;
2062
2063         do {
2064                 __ClearPageReserved(p);
2065                 set_page_count(p, 0);
2066         } while (++p, --i);
2067
2068         set_pageblock_migratetype(page, MIGRATE_CMA);
2069
2070         if (pageblock_order >= MAX_ORDER) {
2071                 i = pageblock_nr_pages;
2072                 p = page;
2073                 do {
2074                         set_page_refcounted(p);
2075                         __free_pages(p, MAX_ORDER - 1);
2076                         p += MAX_ORDER_NR_PAGES;
2077                 } while (i -= MAX_ORDER_NR_PAGES);
2078         } else {
2079                 set_page_refcounted(page);
2080                 __free_pages(page, pageblock_order);
2081         }
2082
2083         adjust_managed_page_count(page, pageblock_nr_pages);
2084 }
2085 #endif
2086
2087 /*
2088  * The order of subdivision here is critical for the IO subsystem.
2089  * Please do not alter this order without good reasons and regression
2090  * testing. Specifically, as large blocks of memory are subdivided,
2091  * the order in which smaller blocks are delivered depends on the order
2092  * they're subdivided in this function. This is the primary factor
2093  * influencing the order in which pages are delivered to the IO
2094  * subsystem according to empirical testing, and this is also justified
2095  * by considering the behavior of a buddy system containing a single
2096  * large block of memory acted on by a series of small allocations.
2097  * This behavior is a critical factor in sglist merging's success.
2098  *
2099  * -- nyc
2100  */
2101 static inline void expand(struct zone *zone, struct page *page,
2102         int low, int high, int migratetype)
2103 {
2104         unsigned long size = 1 << high;
2105
2106         while (high > low) {
2107                 high--;
2108                 size >>= 1;
2109                 VM_BUG_ON_PAGE(bad_range(zone, &page[size]), &page[size]);
2110
2111                 /*
2112                  * Mark as guard pages (or page), that will allow to
2113                  * merge back to allocator when buddy will be freed.
2114                  * Corresponding page table entries will not be touched,
2115                  * pages will stay not present in virtual address space
2116                  */
2117                 if (set_page_guard(zone, &page[size], high, migratetype))
2118                         continue;
2119
2120                 add_to_free_list(&page[size], zone, high, migratetype);
2121                 set_page_order(&page[size], high);
2122         }
2123 }
2124
2125 static void check_new_page_bad(struct page *page)
2126 {
2127         if (unlikely(page->flags & __PG_HWPOISON)) {
2128                 /* Don't complain about hwpoisoned pages */
2129                 page_mapcount_reset(page); /* remove PageBuddy */
2130                 return;
2131         }
2132
2133         bad_page(page,
2134                  page_bad_reason(page, PAGE_FLAGS_CHECK_AT_PREP));
2135 }
2136
2137 /*
2138  * This page is about to be returned from the page allocator
2139  */
2140 static inline int check_new_page(struct page *page)
2141 {
2142         if (likely(page_expected_state(page,
2143                                 PAGE_FLAGS_CHECK_AT_PREP|__PG_HWPOISON)))
2144                 return 0;
2145
2146         check_new_page_bad(page);
2147         return 1;
2148 }
2149
2150 static inline bool free_pages_prezeroed(void)
2151 {
2152         return (IS_ENABLED(CONFIG_PAGE_POISONING_ZERO) &&
2153                 page_poisoning_enabled()) || want_init_on_free();
2154 }
2155
2156 #ifdef CONFIG_DEBUG_VM
2157 /*
2158  * With DEBUG_VM enabled, order-0 pages are checked for expected state when
2159  * being allocated from pcp lists. With debug_pagealloc also enabled, they are
2160  * also checked when pcp lists are refilled from the free lists.
2161  */
2162 static inline bool check_pcp_refill(struct page *page)
2163 {
2164         if (debug_pagealloc_enabled_static())
2165                 return check_new_page(page);
2166         else
2167                 return false;
2168 }
2169
2170 static inline bool check_new_pcp(struct page *page)
2171 {
2172         return check_new_page(page);
2173 }
2174 #else
2175 /*
2176  * With DEBUG_VM disabled, free order-0 pages are checked for expected state
2177  * when pcp lists are being refilled from the free lists. With debug_pagealloc
2178  * enabled, they are also checked when being allocated from the pcp lists.
2179  */
2180 static inline bool check_pcp_refill(struct page *page)
2181 {
2182         return check_new_page(page);
2183 }
2184 static inline bool check_new_pcp(struct page *page)
2185 {
2186         if (debug_pagealloc_enabled_static())
2187                 return check_new_page(page);
2188         else
2189                 return false;
2190 }
2191 #endif /* CONFIG_DEBUG_VM */
2192
2193 static bool check_new_pages(struct page *page, unsigned int order)
2194 {
2195         int i;
2196         for (i = 0; i < (1 << order); i++) {
2197                 struct page *p = page + i;
2198
2199                 if (unlikely(check_new_page(p)))
2200                         return true;
2201         }
2202
2203         return false;
2204 }
2205
2206 inline void post_alloc_hook(struct page *page, unsigned int order,
2207                                 gfp_t gfp_flags)
2208 {
2209         set_page_private(page, 0);
2210         set_page_refcounted(page);
2211
2212         arch_alloc_page(page, order);
2213         if (debug_pagealloc_enabled_static())
2214                 kernel_map_pages(page, 1 << order, 1);
2215         kasan_alloc_pages(page, order);
2216         kernel_poison_pages(page, 1 << order, 1);
2217         set_page_owner(page, order, gfp_flags);
2218 }
2219
2220 static void prep_new_page(struct page *page, unsigned int order, gfp_t gfp_flags,
2221                                                         unsigned int alloc_flags)
2222 {
2223         post_alloc_hook(page, order, gfp_flags);
2224
2225         if (!free_pages_prezeroed() && want_init_on_alloc(gfp_flags))
2226                 kernel_init_free_pages(page, 1 << order);
2227
2228         if (order && (gfp_flags & __GFP_COMP))
2229                 prep_compound_page(page, order);
2230
2231         /*
2232          * page is set pfmemalloc when ALLOC_NO_WATERMARKS was necessary to
2233          * allocate the page. The expectation is that the caller is taking
2234          * steps that will free more memory. The caller should avoid the page
2235          * being used for !PFMEMALLOC purposes.
2236          */
2237         if (alloc_flags & ALLOC_NO_WATERMARKS)
2238                 set_page_pfmemalloc(page);
2239         else
2240                 clear_page_pfmemalloc(page);
2241 }
2242
2243 /*
2244  * Go through the free lists for the given migratetype and remove
2245  * the smallest available page from the freelists
2246  */
2247 static __always_inline
2248 struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
2249                                                 int migratetype)
2250 {
2251         unsigned int current_order;
2252         struct free_area *area;
2253         struct page *page;
2254
2255         /* Find a page of the appropriate size in the preferred list */
2256         for (current_order = order; current_order < MAX_ORDER; ++current_order) {
2257                 area = &(zone->free_area[current_order]);
2258                 page = get_page_from_free_area(area, migratetype);
2259                 if (!page)
2260                         continue;
2261                 del_page_from_free_list(page, zone, current_order);
2262                 expand(zone, page, order, current_order, migratetype);
2263                 set_pcppage_migratetype(page, migratetype);
2264                 return page;
2265         }
2266
2267         return NULL;
2268 }
2269
2270
2271 /*
2272  * This array describes the order lists are fallen back to when
2273  * the free lists for the desirable migrate type are depleted
2274  */
2275 static int fallbacks[MIGRATE_TYPES][4] = {
2276         [MIGRATE_UNMOVABLE]   = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE,   MIGRATE_TYPES },
2277         [MIGRATE_MOVABLE]     = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_TYPES },
2278         [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE,   MIGRATE_MOVABLE,   MIGRATE_TYPES },
2279 #ifdef CONFIG_CMA
2280         [MIGRATE_CMA]         = { MIGRATE_TYPES }, /* Never used */
2281 #endif
2282 #ifdef CONFIG_MEMORY_ISOLATION
2283         [MIGRATE_ISOLATE]     = { MIGRATE_TYPES }, /* Never used */
2284 #endif
2285 };
2286
2287 #ifdef CONFIG_CMA
2288 static __always_inline struct page *__rmqueue_cma_fallback(struct zone *zone,
2289                                         unsigned int order)
2290 {
2291         return __rmqueue_smallest(zone, order, MIGRATE_CMA);
2292 }
2293 #else
2294 static inline struct page *__rmqueue_cma_fallback(struct zone *zone,
2295                                         unsigned int order) { return NULL; }
2296 #endif
2297
2298 /*
2299  * Move the free pages in a range to the free lists of the requested type.
2300  * Note that start_page and end_pages are not aligned on a pageblock
2301  * boundary. If alignment is required, use move_freepages_block()
2302  */
2303 static int move_freepages(struct zone *zone,
2304                           struct page *start_page, struct page *end_page,
2305                           int migratetype, int *num_movable)
2306 {
2307         struct page *page;
2308         unsigned int order;
2309         int pages_moved = 0;
2310
2311         for (page = start_page; page <= end_page;) {
2312                 if (!pfn_valid_within(page_to_pfn(page))) {
2313                         page++;
2314                         continue;
2315                 }
2316
2317                 if (!PageBuddy(page)) {
2318                         /*
2319                          * We assume that pages that could be isolated for
2320                          * migration are movable. But we don't actually try
2321                          * isolating, as that would be expensive.
2322                          */
2323                         if (num_movable &&
2324                                         (PageLRU(page) || __PageMovable(page)))
2325                                 (*num_movable)++;
2326
2327                         page++;
2328                         continue;
2329                 }
2330
2331                 /* Make sure we are not inadvertently changing nodes */
2332                 VM_BUG_ON_PAGE(page_to_nid(page) != zone_to_nid(zone), page);
2333                 VM_BUG_ON_PAGE(page_zone(page) != zone, page);
2334
2335                 order = page_order(page);
2336                 move_to_free_list(page, zone, order, migratetype);
2337                 page += 1 << order;
2338                 pages_moved += 1 << order;
2339         }
2340
2341         return pages_moved;
2342 }
2343
2344 int move_freepages_block(struct zone *zone, struct page *page,
2345                                 int migratetype, int *num_movable)
2346 {
2347         unsigned long start_pfn, end_pfn;
2348         struct page *start_page, *end_page;
2349
2350         if (num_movable)
2351                 *num_movable = 0;
2352
2353         start_pfn = page_to_pfn(page);
2354         start_pfn = start_pfn & ~(pageblock_nr_pages-1);
2355         start_page = pfn_to_page(start_pfn);
2356         end_page = start_page + pageblock_nr_pages - 1;
2357         end_pfn = start_pfn + pageblock_nr_pages - 1;
2358
2359         /* Do not cross zone boundaries */
2360         if (!zone_spans_pfn(zone, start_pfn))
2361                 start_page = page;
2362         if (!zone_spans_pfn(zone, end_pfn))
2363                 return 0;
2364
2365         return move_freepages(zone, start_page, end_page, migratetype,
2366                                                                 num_movable);
2367 }
2368
2369 static void change_pageblock_range(struct page *pageblock_page,
2370                                         int start_order, int migratetype)
2371 {
2372         int nr_pageblocks = 1 << (start_order - pageblock_order);
2373
2374         while (nr_pageblocks--) {
2375                 set_pageblock_migratetype(pageblock_page, migratetype);
2376                 pageblock_page += pageblock_nr_pages;
2377         }
2378 }
2379
2380 /*
2381  * When we are falling back to another migratetype during allocation, try to
2382  * steal extra free pages from the same pageblocks to satisfy further
2383  * allocations, instead of polluting multiple pageblocks.
2384  *
2385  * If we are stealing a relatively large buddy page, it is likely there will
2386  * be more free pages in the pageblock, so try to steal them all. For
2387  * reclaimable and unmovable allocations, we steal regardless of page size,
2388  * as fragmentation caused by those allocations polluting movable pageblocks
2389  * is worse than movable allocations stealing from unmovable and reclaimable
2390  * pageblocks.
2391  */
2392 static bool can_steal_fallback(unsigned int order, int start_mt)
2393 {
2394         /*
2395          * Leaving this order check is intended, although there is
2396          * relaxed order check in next check. The reason is that
2397          * we can actually steal whole pageblock if this condition met,
2398          * but, below check doesn't guarantee it and that is just heuristic
2399          * so could be changed anytime.
2400          */
2401         if (order >= pageblock_order)
2402                 return true;
2403
2404         if (order >= pageblock_order / 2 ||
2405                 start_mt == MIGRATE_RECLAIMABLE ||
2406                 start_mt == MIGRATE_UNMOVABLE ||
2407                 page_group_by_mobility_disabled)
2408                 return true;
2409
2410         return false;
2411 }
2412
2413 static inline void boost_watermark(struct zone *zone)
2414 {
2415         unsigned long max_boost;
2416
2417         if (!watermark_boost_factor)
2418                 return;
2419         /*
2420          * Don't bother in zones that are unlikely to produce results.
2421          * On small machines, including kdump capture kernels running
2422          * in a small area, boosting the watermark can cause an out of
2423          * memory situation immediately.
2424          */
2425         if ((pageblock_nr_pages * 4) > zone_managed_pages(zone))
2426                 return;
2427
2428         max_boost = mult_frac(zone->_watermark[WMARK_HIGH],
2429                         watermark_boost_factor, 10000);
2430
2431         /*
2432          * high watermark may be uninitialised if fragmentation occurs
2433          * very early in boot so do not boost. We do not fall
2434          * through and boost by pageblock_nr_pages as failing
2435          * allocations that early means that reclaim is not going
2436          * to help and it may even be impossible to reclaim the
2437          * boosted watermark resulting in a hang.
2438          */
2439         if (!max_boost)
2440                 return;
2441
2442         max_boost = max(pageblock_nr_pages, max_boost);
2443
2444         zone->watermark_boost = min(zone->watermark_boost + pageblock_nr_pages,
2445                 max_boost);
2446 }
2447
2448 /*
2449  * This function implements actual steal behaviour. If order is large enough,
2450  * we can steal whole pageblock. If not, we first move freepages in this
2451  * pageblock to our migratetype and determine how many already-allocated pages
2452  * are there in the pageblock with a compatible migratetype. If at least half
2453  * of pages are free or compatible, we can change migratetype of the pageblock
2454  * itself, so pages freed in the future will be put on the correct free list.
2455  */
2456 static void steal_suitable_fallback(struct zone *zone, struct page *page,
2457                 unsigned int alloc_flags, int start_type, bool whole_block)
2458 {
2459         unsigned int current_order = page_order(page);
2460         int free_pages, movable_pages, alike_pages;
2461         int old_block_type;
2462
2463         old_block_type = get_pageblock_migratetype(page);
2464
2465         /*
2466          * This can happen due to races and we want to prevent broken
2467          * highatomic accounting.
2468          */
2469         if (is_migrate_highatomic(old_block_type))
2470                 goto single_page;
2471
2472         /* Take ownership for orders >= pageblock_order */
2473         if (current_order >= pageblock_order) {
2474                 change_pageblock_range(page, current_order, start_type);
2475                 goto single_page;
2476         }
2477
2478         /*
2479          * Boost watermarks to increase reclaim pressure to reduce the
2480          * likelihood of future fallbacks. Wake kswapd now as the node
2481          * may be balanced overall and kswapd will not wake naturally.
2482          */
2483         boost_watermark(zone);
2484         if (alloc_flags & ALLOC_KSWAPD)
2485                 set_bit(ZONE_BOOSTED_WATERMARK, &zone->flags);
2486
2487         /* We are not allowed to try stealing from the whole block */
2488         if (!whole_block)
2489                 goto single_page;
2490
2491         free_pages = move_freepages_block(zone, page, start_type,
2492                                                 &movable_pages);
2493         /*
2494          * Determine how many pages are compatible with our allocation.
2495          * For movable allocation, it's the number of movable pages which
2496          * we just obtained. For other types it's a bit more tricky.
2497          */
2498         if (start_type == MIGRATE_MOVABLE) {
2499                 alike_pages = movable_pages;
2500         } else {
2501                 /*
2502                  * If we are falling back a RECLAIMABLE or UNMOVABLE allocation
2503                  * to MOVABLE pageblock, consider all non-movable pages as
2504                  * compatible. If it's UNMOVABLE falling back to RECLAIMABLE or
2505                  * vice versa, be conservative since we can't distinguish the
2506                  * exact migratetype of non-movable pages.
2507                  */
2508                 if (old_block_type == MIGRATE_MOVABLE)
2509                         alike_pages = pageblock_nr_pages
2510                                                 - (free_pages + movable_pages);
2511                 else
2512                         alike_pages = 0;
2513         }
2514
2515         /* moving whole block can fail due to zone boundary conditions */
2516         if (!free_pages)
2517                 goto single_page;
2518
2519         /*
2520          * If a sufficient number of pages in the block are either free or of
2521          * comparable migratability as our allocation, claim the whole block.
2522          */
2523         if (free_pages + alike_pages >= (1 << (pageblock_order-1)) ||
2524                         page_group_by_mobility_disabled)
2525                 set_pageblock_migratetype(page, start_type);
2526
2527         return;
2528
2529 single_page:
2530         move_to_free_list(page, zone, current_order, start_type);
2531 }
2532
2533 /*
2534  * Check whether there is a suitable fallback freepage with requested order.
2535  * If only_stealable is true, this function returns fallback_mt only if
2536  * we can steal other freepages all together. This would help to reduce
2537  * fragmentation due to mixed migratetype pages in one pageblock.
2538  */
2539 int find_suitable_fallback(struct free_area *area, unsigned int order,
2540                         int migratetype, bool only_stealable, bool *can_steal)
2541 {
2542         int i;
2543         int fallback_mt;
2544
2545         if (area->nr_free == 0)
2546                 return -1;
2547
2548         *can_steal = false;
2549         for (i = 0;; i++) {
2550                 fallback_mt = fallbacks[migratetype][i];
2551                 if (fallback_mt == MIGRATE_TYPES)
2552                         break;
2553
2554                 if (free_area_empty(area, fallback_mt))
2555                         continue;
2556
2557                 if (can_steal_fallback(order, migratetype))
2558                         *can_steal = true;
2559
2560                 if (!only_stealable)
2561                         return fallback_mt;
2562
2563                 if (*can_steal)
2564                         return fallback_mt;
2565         }
2566
2567         return -1;
2568 }
2569
2570 /*
2571  * Reserve a pageblock for exclusive use of high-order atomic allocations if
2572  * there are no empty page blocks that contain a page with a suitable order
2573  */
2574 static void reserve_highatomic_pageblock(struct page *page, struct zone *zone,
2575                                 unsigned int alloc_order)
2576 {
2577         int mt;
2578         unsigned long max_managed, flags;
2579
2580         /*
2581          * Limit the number reserved to 1 pageblock or roughly 1% of a zone.
2582          * Check is race-prone but harmless.
2583          */
2584         max_managed = (zone_managed_pages(zone) / 100) + pageblock_nr_pages;
2585         if (zone->nr_reserved_highatomic >= max_managed)
2586                 return;
2587
2588         spin_lock_irqsave(&zone->lock, flags);
2589
2590         /* Recheck the nr_reserved_highatomic limit under the lock */
2591         if (zone->nr_reserved_highatomic >= max_managed)
2592                 goto out_unlock;
2593
2594         /* Yoink! */
2595         mt = get_pageblock_migratetype(page);
2596         if (!is_migrate_highatomic(mt) && !is_migrate_isolate(mt)
2597             && !is_migrate_cma(mt)) {
2598                 zone->nr_reserved_highatomic += pageblock_nr_pages;
2599                 set_pageblock_migratetype(page, MIGRATE_HIGHATOMIC);
2600                 move_freepages_block(zone, page, MIGRATE_HIGHATOMIC, NULL);
2601         }
2602
2603 out_unlock:
2604         spin_unlock_irqrestore(&zone->lock, flags);
2605 }
2606
2607 /*
2608  * Used when an allocation is about to fail under memory pressure. This
2609  * potentially hurts the reliability of high-order allocations when under
2610  * intense memory pressure but failed atomic allocations should be easier
2611  * to recover from than an OOM.
2612  *
2613  * If @force is true, try to unreserve a pageblock even though highatomic
2614  * pageblock is exhausted.
2615  */
2616 static bool unreserve_highatomic_pageblock(const struct alloc_context *ac,
2617                                                 bool force)
2618 {
2619         struct zonelist *zonelist = ac->zonelist;
2620         unsigned long flags;
2621         struct zoneref *z;
2622         struct zone *zone;
2623         struct page *page;
2624         int order;
2625         bool ret;
2626
2627         for_each_zone_zonelist_nodemask(zone, z, zonelist, ac->highest_zoneidx,
2628                                                                 ac->nodemask) {
2629                 /*
2630                  * Preserve at least one pageblock unless memory pressure
2631                  * is really high.
2632                  */
2633                 if (!force && zone->nr_reserved_highatomic <=
2634                                         pageblock_nr_pages)
2635                         continue;
2636
2637                 spin_lock_irqsave(&zone->lock, flags);
2638                 for (order = 0; order < MAX_ORDER; order++) {
2639                         struct free_area *area = &(zone->free_area[order]);
2640
2641                         page = get_page_from_free_area(area, MIGRATE_HIGHATOMIC);
2642                         if (!page)
2643                                 continue;
2644
2645                         /*
2646                          * In page freeing path, migratetype change is racy so
2647                          * we can counter several free pages in a pageblock
2648                          * in this loop althoug we changed the pageblock type
2649                          * from highatomic to ac->migratetype. So we should
2650                          * adjust the count once.
2651                          */
2652                         if (is_migrate_highatomic_page(page)) {
2653                                 /*
2654                                  * It should never happen but changes to
2655                                  * locking could inadvertently allow a per-cpu
2656                                  * drain to add pages to MIGRATE_HIGHATOMIC
2657                                  * while unreserving so be safe and watch for
2658                                  * underflows.
2659                                  */
2660                                 zone->nr_reserved_highatomic -= min(
2661                                                 pageblock_nr_pages,
2662                                                 zone->nr_reserved_highatomic);
2663                         }
2664
2665                         /*
2666                          * Convert to ac->migratetype and avoid the normal
2667                          * pageblock stealing heuristics. Minimally, the caller
2668                          * is doing the work and needs the pages. More
2669                          * importantly, if the block was always converted to
2670                          * MIGRATE_UNMOVABLE or another type then the number
2671                          * of pageblocks that cannot be completely freed
2672                          * may increase.
2673                          */
2674                         set_pageblock_migratetype(page, ac->migratetype);
2675                         ret = move_freepages_block(zone, page, ac->migratetype,
2676                                                                         NULL);
2677                         if (ret) {
2678                                 spin_unlock_irqrestore(&zone->lock, flags);
2679                                 return ret;
2680                         }
2681                 }
2682                 spin_unlock_irqrestore(&zone->lock, flags);
2683         }
2684
2685         return false;
2686 }
2687
2688 /*
2689  * Try finding a free buddy page on the fallback list and put it on the free
2690  * list of requested migratetype, possibly along with other pages from the same
2691  * block, depending on fragmentation avoidance heuristics. Returns true if
2692  * fallback was found so that __rmqueue_smallest() can grab it.
2693  *
2694  * The use of signed ints for order and current_order is a deliberate
2695  * deviation from the rest of this file, to make the for loop
2696  * condition simpler.
2697  */
2698 static __always_inline bool
2699 __rmqueue_fallback(struct zone *zone, int order, int start_migratetype,
2700                                                 unsigned int alloc_flags)
2701 {
2702         struct free_area *area;
2703         int current_order;
2704         int min_order = order;
2705         struct page *page;
2706         int fallback_mt;
2707         bool can_steal;
2708
2709         /*
2710          * Do not steal pages from freelists belonging to other pageblocks
2711          * i.e. orders < pageblock_order. If there are no local zones free,
2712          * the zonelists will be reiterated without ALLOC_NOFRAGMENT.
2713          */
2714         if (alloc_flags & ALLOC_NOFRAGMENT)
2715                 min_order = pageblock_order;
2716
2717         /*
2718          * Find the largest available free page in the other list. This roughly
2719          * approximates finding the pageblock with the most free pages, which
2720          * would be too costly to do exactly.
2721          */
2722         for (current_order = MAX_ORDER - 1; current_order >= min_order;
2723                                 --current_order) {
2724                 area = &(zone->free_area[current_order]);
2725                 fallback_mt = find_suitable_fallback(area, current_order,
2726                                 start_migratetype, false, &can_steal);
2727                 if (fallback_mt == -1)
2728                         continue;
2729
2730                 /*
2731                  * We cannot steal all free pages from the pageblock and the
2732                  * requested migratetype is movable. In that case it's better to
2733                  * steal and split the smallest available page instead of the
2734                  * largest available page, because even if the next movable
2735                  * allocation falls back into a different pageblock than this
2736                  * one, it won't cause permanent fragmentation.
2737                  */
2738                 if (!can_steal && start_migratetype == MIGRATE_MOVABLE
2739                                         && current_order > order)
2740                         goto find_smallest;
2741
2742                 goto do_steal;
2743         }
2744
2745         return false;
2746
2747 find_smallest:
2748         for (current_order = order; current_order < MAX_ORDER;
2749                                                         current_order++) {
2750                 area = &(zone->free_area[current_order]);
2751                 fallback_mt = find_suitable_fallback(area, current_order,
2752                                 start_migratetype, false, &can_steal);
2753                 if (fallback_mt != -1)
2754                         break;
2755         }
2756
2757         /*
2758          * This should not happen - we already found a suitable fallback
2759          * when looking for the largest page.
2760          */
2761         VM_BUG_ON(current_order == MAX_ORDER);
2762
2763 do_steal:
2764         page = get_page_from_free_area(area, fallback_mt);
2765
2766         steal_suitable_fallback(zone, page, alloc_flags, start_migratetype,
2767                                                                 can_steal);
2768
2769         trace_mm_page_alloc_extfrag(page, order, current_order,
2770                 start_migratetype, fallback_mt);
2771
2772         return true;
2773
2774 }
2775
2776 /*
2777  * Do the hard work of removing an element from the buddy allocator.
2778  * Call me with the zone->lock already held.
2779  */
2780 static __always_inline struct page *
2781 __rmqueue(struct zone *zone, unsigned int order, int migratetype,
2782                                                 unsigned int alloc_flags)
2783 {
2784         struct page *page;
2785
2786 #ifdef CONFIG_CMA
2787         /*
2788          * Balance movable allocations between regular and CMA areas by
2789          * allocating from CMA when over half of the zone's free memory
2790          * is in the CMA area.
2791          */
2792         if (migratetype == MIGRATE_MOVABLE &&
2793             zone_page_state(zone, NR_FREE_CMA_PAGES) >
2794             zone_page_state(zone, NR_FREE_PAGES) / 2) {
2795                 page = __rmqueue_cma_fallback(zone, order);
2796                 if (page)
2797                         return page;
2798         }
2799 #endif
2800 retry:
2801         page = __rmqueue_smallest(zone, order, migratetype);
2802         if (unlikely(!page)) {
2803                 if (migratetype == MIGRATE_MOVABLE)
2804                         page = __rmqueue_cma_fallback(zone, order);
2805
2806                 if (!page && __rmqueue_fallback(zone, order, migratetype,
2807                                                                 alloc_flags))
2808                         goto retry;
2809         }
2810
2811         trace_mm_page_alloc_zone_locked(page, order, migratetype);
2812         return page;
2813 }
2814
2815 /*
2816  * Obtain a specified number of elements from the buddy allocator, all under
2817  * a single hold of the lock, for efficiency.  Add them to the supplied list.
2818  * Returns the number of new pages which were placed at *list.
2819  */
2820 static int rmqueue_bulk(struct zone *zone, unsigned int order,
2821                         unsigned long count, struct list_head *list,
2822                         int migratetype, unsigned int alloc_flags)
2823 {
2824         int i, alloced = 0;
2825
2826         spin_lock(&zone->lock);
2827         for (i = 0; i < count; ++i) {
2828                 struct page *page = __rmqueue(zone, order, migratetype,
2829                                                                 alloc_flags);
2830                 if (unlikely(page == NULL))
2831                         break;
2832
2833                 if (unlikely(check_pcp_refill(page)))
2834                         continue;
2835
2836                 /*
2837                  * Split buddy pages returned by expand() are received here in
2838                  * physical page order. The page is added to the tail of
2839                  * caller's list. From the callers perspective, the linked list
2840                  * is ordered by page number under some conditions. This is
2841                  * useful for IO devices that can forward direction from the
2842                  * head, thus also in the physical page order. This is useful
2843                  * for IO devices that can merge IO requests if the physical
2844                  * pages are ordered properly.
2845                  */
2846                 list_add_tail(&page->lru, list);
2847                 alloced++;
2848                 if (is_migrate_cma(get_pcppage_migratetype(page)))
2849                         __mod_zone_page_state(zone, NR_FREE_CMA_PAGES,
2850                                               -(1 << order));
2851         }
2852
2853         /*
2854          * i pages were removed from the buddy list even if some leak due
2855          * to check_pcp_refill failing so adjust NR_FREE_PAGES based
2856          * on i. Do not confuse with 'alloced' which is the number of
2857          * pages added to the pcp list.
2858          */
2859         __mod_zone_page_state(zone, NR_FREE_PAGES, -(i << order));
2860         spin_unlock(&zone->lock);
2861         return alloced;
2862 }
2863
2864 #ifdef CONFIG_NUMA
2865 /*
2866  * Called from the vmstat counter updater to drain pagesets of this
2867  * currently executing processor on remote nodes after they have
2868  * expired.
2869  *
2870  * Note that this function must be called with the thread pinned to
2871  * a single processor.
2872  */
2873 void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp)
2874 {
2875         unsigned long flags;
2876         int to_drain, batch;
2877
2878         local_irq_save(flags);
2879         batch = READ_ONCE(pcp->batch);
2880         to_drain = min(pcp->count, batch);
2881         if (to_drain > 0)
2882                 free_pcppages_bulk(zone, to_drain, pcp);
2883         local_irq_restore(flags);
2884 }
2885 #endif
2886
2887 /*
2888  * Drain pcplists of the indicated processor and zone.
2889  *
2890  * The processor must either be the current processor and the
2891  * thread pinned to the current processor or a processor that
2892  * is not online.
2893  */
2894 static void drain_pages_zone(unsigned int cpu, struct zone *zone)
2895 {
2896         unsigned long flags;
2897         struct per_cpu_pageset *pset;
2898         struct per_cpu_pages *pcp;
2899
2900         local_irq_save(flags);
2901         pset = per_cpu_ptr(zone->pageset, cpu);
2902
2903         pcp = &pset->pcp;
2904         if (pcp->count)
2905                 free_pcppages_bulk(zone, pcp->count, pcp);
2906         local_irq_restore(flags);
2907 }
2908
2909 /*
2910  * Drain pcplists of all zones on the indicated processor.
2911  *
2912  * The processor must either be the current processor and the
2913  * thread pinned to the current processor or a processor that
2914  * is not online.
2915  */
2916 static void drain_pages(unsigned int cpu)
2917 {
2918         struct zone *zone;
2919
2920         for_each_populated_zone(zone) {
2921                 drain_pages_zone(cpu, zone);
2922         }
2923 }
2924
2925 /*
2926  * Spill all of this CPU's per-cpu pages back into the buddy allocator.
2927  *
2928  * The CPU has to be pinned. When zone parameter is non-NULL, spill just
2929  * the single zone's pages.
2930  */
2931 void drain_local_pages(struct zone *zone)
2932 {
2933         int cpu = smp_processor_id();
2934
2935         if (zone)
2936                 drain_pages_zone(cpu, zone);
2937         else
2938                 drain_pages(cpu);
2939 }
2940
2941 static void drain_local_pages_wq(struct work_struct *work)
2942 {
2943         struct pcpu_drain *drain;
2944
2945         drain = container_of(work, struct pcpu_drain, work);
2946
2947         /*
2948          * drain_all_pages doesn't use proper cpu hotplug protection so
2949          * we can race with cpu offline when the WQ can move this from
2950          * a cpu pinned worker to an unbound one. We can operate on a different
2951          * cpu which is allright but we also have to make sure to not move to
2952          * a different one.
2953          */
2954         preempt_disable();
2955         drain_local_pages(drain->zone);
2956         preempt_enable();
2957 }
2958
2959 /*
2960  * Spill all the per-cpu pages from all CPUs back into the buddy allocator.
2961  *
2962  * When zone parameter is non-NULL, spill just the single zone's pages.
2963  *
2964  * Note that this can be extremely slow as the draining happens in a workqueue.
2965  */
2966 void drain_all_pages(struct zone *zone)
2967 {
2968         int cpu;
2969
2970         /*
2971          * Allocate in the BSS so we wont require allocation in
2972          * direct reclaim path for CONFIG_CPUMASK_OFFSTACK=y
2973          */
2974         static cpumask_t cpus_with_pcps;
2975
2976         /*
2977          * Make sure nobody triggers this path before mm_percpu_wq is fully
2978          * initialized.
2979          */
2980         if (WARN_ON_ONCE(!mm_percpu_wq))
2981                 return;
2982
2983         /*
2984          * Do not drain if one is already in progress unless it's specific to
2985          * a zone. Such callers are primarily CMA and memory hotplug and need
2986          * the drain to be complete when the call returns.
2987          */
2988         if (unlikely(!mutex_trylock(&pcpu_drain_mutex))) {
2989                 if (!zone)
2990                         return;
2991                 mutex_lock(&pcpu_drain_mutex);
2992         }
2993
2994         /*
2995          * We don't care about racing with CPU hotplug event
2996          * as offline notification will cause the notified
2997          * cpu to drain that CPU pcps and on_each_cpu_mask
2998          * disables preemption as part of its processing
2999          */
3000         for_each_online_cpu(cpu) {
3001                 struct per_cpu_pageset *pcp;
3002                 struct zone *z;
3003                 bool has_pcps = false;
3004
3005                 if (zone) {
3006                         pcp = per_cpu_ptr(zone->pageset, cpu);
3007                         if (pcp->pcp.count)
3008                                 has_pcps = true;
3009                 } else {
3010                         for_each_populated_zone(z) {
3011                                 pcp = per_cpu_ptr(z->pageset, cpu);
3012                                 if (pcp->pcp.count) {
3013                                         has_pcps = true;
3014                                         break;
3015                                 }
3016                         }
3017                 }
3018
3019                 if (has_pcps)
3020                         cpumask_set_cpu(cpu, &cpus_with_pcps);
3021                 else
3022                         cpumask_clear_cpu(cpu, &cpus_with_pcps);
3023         }
3024
3025         for_each_cpu(cpu, &cpus_with_pcps) {
3026                 struct pcpu_drain *drain = per_cpu_ptr(&pcpu_drain, cpu);
3027
3028                 drain->zone = zone;
3029                 INIT_WORK(&drain->work, drain_local_pages_wq);
3030                 queue_work_on(cpu, mm_percpu_wq, &drain->work);
3031         }
3032         for_each_cpu(cpu, &cpus_with_pcps)
3033                 flush_work(&per_cpu_ptr(&pcpu_drain, cpu)->work);
3034
3035         mutex_unlock(&pcpu_drain_mutex);
3036 }
3037
3038 #ifdef CONFIG_HIBERNATION
3039
3040 /*
3041  * Touch the watchdog for every WD_PAGE_COUNT pages.
3042  */
3043 #define WD_PAGE_COUNT   (128*1024)
3044
3045 void mark_free_pages(struct zone *zone)
3046 {
3047         unsigned long pfn, max_zone_pfn, page_count = WD_PAGE_COUNT;
3048         unsigned long flags;
3049         unsigned int order, t;
3050         struct page *page;
3051
3052         if (zone_is_empty(zone))
3053                 return;
3054
3055         spin_lock_irqsave(&zone->lock, flags);
3056
3057         max_zone_pfn = zone_end_pfn(zone);
3058         for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
3059                 if (pfn_valid(pfn)) {
3060                         page = pfn_to_page(pfn);
3061
3062                         if (!--page_count) {
3063                                 touch_nmi_watchdog();
3064                                 page_count = WD_PAGE_COUNT;
3065                         }
3066
3067                         if (page_zone(page) != zone)
3068                                 continue;
3069
3070                         if (!swsusp_page_is_forbidden(page))
3071                                 swsusp_unset_page_free(page);
3072                 }
3073
3074         for_each_migratetype_order(order, t) {
3075                 list_for_each_entry(page,
3076                                 &zone->free_area[order].free_list[t], lru) {
3077                         unsigned long i;
3078
3079                         pfn = page_to_pfn(page);
3080                         for (i = 0; i < (1UL << order); i++) {
3081                                 if (!--page_count) {
3082                                         touch_nmi_watchdog();
3083                                         page_count = WD_PAGE_COUNT;
3084                                 }
3085                                 swsusp_set_page_free(pfn_to_page(pfn + i));
3086                         }
3087                 }
3088         }
3089         spin_unlock_irqrestore(&zone->lock, flags);
3090 }
3091 #endif /* CONFIG_PM */
3092
3093 static bool free_unref_page_prepare(struct page *page, unsigned long pfn)
3094 {
3095         int migratetype;
3096
3097         if (!free_pcp_prepare(page))
3098                 return false;
3099
3100         migratetype = get_pfnblock_migratetype(page, pfn);
3101         set_pcppage_migratetype(page, migratetype);
3102         return true;
3103 }
3104
3105 static void free_unref_page_commit(struct page *page, unsigned long pfn)
3106 {
3107         struct zone *zone = page_zone(page);
3108         struct per_cpu_pages *pcp;
3109         int migratetype;
3110
3111         migratetype = get_pcppage_migratetype(page);
3112         __count_vm_event(PGFREE);
3113
3114         /*
3115          * We only track unmovable, reclaimable and movable on pcp lists.
3116          * Free ISOLATE pages back to the allocator because they are being
3117          * offlined but treat HIGHATOMIC as movable pages so we can get those
3118          * areas back if necessary. Otherwise, we may have to free
3119          * excessively into the page allocator
3120          */
3121         if (migratetype >= MIGRATE_PCPTYPES) {
3122                 if (unlikely(is_migrate_isolate(migratetype))) {
3123                         free_one_page(zone, page, pfn, 0, migratetype);
3124                         return;
3125                 }
3126                 migratetype = MIGRATE_MOVABLE;
3127         }
3128
3129         pcp = &this_cpu_ptr(zone->pageset)->pcp;
3130         list_add(&page->lru, &pcp->lists[migratetype]);
3131         pcp->count++;
3132         if (pcp->count >= pcp->high) {
3133                 unsigned long batch = READ_ONCE(pcp->batch);
3134                 free_pcppages_bulk(zone, batch, pcp);
3135         }
3136 }
3137
3138 /*
3139  * Free a 0-order page
3140  */
3141 void free_unref_page(struct page *page)
3142 {
3143         unsigned long flags;
3144         unsigned long pfn = page_to_pfn(page);
3145
3146         if (!free_unref_page_prepare(page, pfn))
3147                 return;
3148
3149         local_irq_save(flags);
3150         free_unref_page_commit(page, pfn);
3151         local_irq_restore(flags);
3152 }
3153
3154 /*
3155  * Free a list of 0-order pages
3156  */
3157 void free_unref_page_list(struct list_head *list)
3158 {
3159         struct page *page, *next;
3160         unsigned long flags, pfn;
3161         int batch_count = 0;
3162
3163         /* Prepare pages for freeing */
3164         list_for_each_entry_safe(page, next, list, lru) {
3165                 pfn = page_to_pfn(page);
3166                 if (!free_unref_page_prepare(page, pfn))
3167                         list_del(&page->lru);
3168                 set_page_private(page, pfn);
3169         }
3170
3171         local_irq_save(flags);
3172         list_for_each_entry_safe(page, next, list, lru) {
3173                 unsigned long pfn = page_private(page);
3174
3175                 set_page_private(page, 0);
3176                 trace_mm_page_free_batched(page);
3177                 free_unref_page_commit(page, pfn);
3178
3179                 /*
3180                  * Guard against excessive IRQ disabled times when we get
3181                  * a large list of pages to free.
3182                  */
3183                 if (++batch_count == SWAP_CLUSTER_MAX) {
3184                         local_irq_restore(flags);
3185                         batch_count = 0;
3186                         local_irq_save(flags);
3187                 }
3188         }
3189         local_irq_restore(flags);
3190 }
3191
3192 /*
3193  * split_page takes a non-compound higher-order page, and splits it into
3194  * n (1<<order) sub-pages: page[0..n]
3195  * Each sub-page must be freed individually.
3196  *
3197  * Note: this is probably too low level an operation for use in drivers.
3198  * Please consult with lkml before using this in your driver.
3199  */
3200 void split_page(struct page *page, unsigned int order)
3201 {
3202         int i;
3203
3204         VM_BUG_ON_PAGE(PageCompound(page), page);
3205         VM_BUG_ON_PAGE(!page_count(page), page);
3206
3207         for (i = 1; i < (1 << order); i++)
3208                 set_page_refcounted(page + i);
3209         split_page_owner(page, order);
3210 }
3211 EXPORT_SYMBOL_GPL(split_page);
3212
3213 int __isolate_free_page(struct page *page, unsigned int order)
3214 {
3215         unsigned long watermark;
3216         struct zone *zone;
3217         int mt;
3218
3219         BUG_ON(!PageBuddy(page));
3220
3221         zone = page_zone(page);
3222         mt = get_pageblock_migratetype(page);
3223
3224         if (!is_migrate_isolate(mt)) {
3225                 /*
3226                  * Obey watermarks as if the page was being allocated. We can
3227                  * emulate a high-order watermark check with a raised order-0
3228                  * watermark, because we already know our high-order page
3229                  * exists.
3230                  */
3231                 watermark = zone->_watermark[WMARK_MIN] + (1UL << order);
3232                 if (!zone_watermark_ok(zone, 0, watermark, 0, ALLOC_CMA))
3233                         return 0;
3234
3235                 __mod_zone_freepage_state(zone, -(1UL << order), mt);
3236         }
3237
3238         /* Remove page from free list */
3239
3240         del_page_from_free_list(page, zone, order);
3241
3242         /*
3243          * Set the pageblock if the isolated page is at least half of a
3244          * pageblock
3245          */
3246         if (order >= pageblock_order - 1) {
3247                 struct page *endpage = page + (1 << order) - 1;
3248                 for (; page < endpage; page += pageblock_nr_pages) {
3249                         int mt = get_pageblock_migratetype(page);
3250                         if (!is_migrate_isolate(mt) && !is_migrate_cma(mt)
3251                             && !is_migrate_highatomic(mt))
3252                                 set_pageblock_migratetype(page,
3253                                                           MIGRATE_MOVABLE);
3254                 }
3255         }
3256
3257
3258         return 1UL << order;
3259 }
3260
3261 /**
3262  * __putback_isolated_page - Return a now-isolated page back where we got it
3263  * @page: Page that was isolated
3264  * @order: Order of the isolated page
3265  * @mt: The page's pageblock's migratetype
3266  *
3267  * This function is meant to return a page pulled from the free lists via
3268  * __isolate_free_page back to the free lists they were pulled from.
3269  */
3270 void __putback_isolated_page(struct page *page, unsigned int order, int mt)
3271 {
3272         struct zone *zone = page_zone(page);
3273
3274         /* zone lock should be held when this function is called */
3275         lockdep_assert_held(&zone->lock);
3276
3277         /* Return isolated page to tail of freelist. */
3278         __free_one_page(page, page_to_pfn(page), zone, order, mt, false);
3279 }
3280
3281 /*
3282  * Update NUMA hit/miss statistics
3283  *
3284  * Must be called with interrupts disabled.
3285  */
3286 static inline void zone_statistics(struct zone *preferred_zone, struct zone *z)
3287 {
3288 #ifdef CONFIG_NUMA
3289         enum numa_stat_item local_stat = NUMA_LOCAL;
3290
3291         /* skip numa counters update if numa stats is disabled */
3292         if (!static_branch_likely(&vm_numa_stat_key))
3293                 return;
3294
3295         if (zone_to_nid(z) != numa_node_id())
3296                 local_stat = NUMA_OTHER;
3297
3298         if (zone_to_nid(z) == zone_to_nid(preferred_zone))
3299                 __inc_numa_state(z, NUMA_HIT);
3300         else {
3301                 __inc_numa_state(z, NUMA_MISS);
3302                 __inc_numa_state(preferred_zone, NUMA_FOREIGN);
3303         }
3304         __inc_numa_state(z, local_stat);
3305 #endif
3306 }
3307
3308 /* Remove page from the per-cpu list, caller must protect the list */
3309 static struct page *__rmqueue_pcplist(struct zone *zone, int migratetype,
3310                         unsigned int alloc_flags,
3311                         struct per_cpu_pages *pcp,
3312                         struct list_head *list)
3313 {
3314         struct page *page;
3315
3316         do {
3317                 if (list_empty(list)) {
3318                         pcp->count += rmqueue_bulk(zone, 0,
3319                                         pcp->batch, list,
3320                                         migratetype, alloc_flags);
3321                         if (unlikely(list_empty(list)))
3322                                 return NULL;
3323                 }
3324
3325                 page = list_first_entry(list, struct page, lru);
3326                 list_del(&page->lru);
3327                 pcp->count--;
3328         } while (check_new_pcp(page));
3329
3330         return page;
3331 }
3332
3333 /* Lock and remove page from the per-cpu list */
3334 static struct page *rmqueue_pcplist(struct zone *preferred_zone,
3335                         struct zone *zone, gfp_t gfp_flags,
3336                         int migratetype, unsigned int alloc_flags)
3337 {
3338         struct per_cpu_pages *pcp;
3339         struct list_head *list;
3340         struct page *page;
3341         unsigned long flags;
3342
3343         local_irq_save(flags);
3344         pcp = &this_cpu_ptr(zone->pageset)->pcp;
3345         list = &pcp->lists[migratetype];
3346         page = __rmqueue_pcplist(zone,  migratetype, alloc_flags, pcp, list);
3347         if (page) {
3348                 __count_zid_vm_events(PGALLOC, page_zonenum(page), 1);
3349                 zone_statistics(preferred_zone, zone);
3350         }
3351         local_irq_restore(flags);
3352         return page;
3353 }
3354
3355 /*
3356  * Allocate a page from the given zone. Use pcplists for order-0 allocations.
3357  */
3358 static inline
3359 struct page *rmqueue(struct zone *preferred_zone,
3360                         struct zone *zone, unsigned int order,
3361                         gfp_t gfp_flags, unsigned int alloc_flags,
3362                         int migratetype)
3363 {
3364         unsigned long flags;
3365         struct page *page;
3366
3367         if (likely(order == 0)) {
3368                 page = rmqueue_pcplist(preferred_zone, zone, gfp_flags,
3369                                         migratetype, alloc_flags);
3370                 goto out;
3371         }
3372
3373         /*
3374          * We most definitely don't want callers attempting to
3375          * allocate greater than order-1 page units with __GFP_NOFAIL.
3376          */
3377         WARN_ON_ONCE((gfp_flags & __GFP_NOFAIL) && (order > 1));
3378         spin_lock_irqsave(&zone->lock, flags);
3379
3380         do {
3381                 page = NULL;
3382                 if (alloc_flags & ALLOC_HARDER) {
3383                         page = __rmqueue_smallest(zone, order, MIGRATE_HIGHATOMIC);
3384                         if (page)
3385                                 trace_mm_page_alloc_zone_locked(page, order, migratetype);
3386                 }
3387                 if (!page)
3388                         page = __rmqueue(zone, order, migratetype, alloc_flags);
3389         } while (page && check_new_pages(page, order));
3390         spin_unlock(&zone->lock);
3391         if (!page)
3392                 goto failed;
3393         __mod_zone_freepage_state(zone, -(1 << order),
3394                                   get_pcppage_migratetype(page));
3395
3396         __count_zid_vm_events(PGALLOC, page_zonenum(page), 1 << order);
3397         zone_statistics(preferred_zone, zone);
3398         local_irq_restore(flags);
3399
3400 out:
3401         /* Separate test+clear to avoid unnecessary atomics */
3402         if (test_bit(ZONE_BOOSTED_WATERMARK, &zone->flags)) {
3403                 clear_bit(ZONE_BOOSTED_WATERMARK, &zone->flags);
3404                 wakeup_kswapd(zone, 0, 0, zone_idx(zone));
3405         }
3406
3407         VM_BUG_ON_PAGE(page && bad_range(zone, page), page);
3408         return page;
3409
3410 failed:
3411         local_irq_restore(flags);
3412         return NULL;
3413 }
3414
3415 #ifdef CONFIG_FAIL_PAGE_ALLOC
3416
3417 static struct {
3418         struct fault_attr attr;
3419
3420         bool ignore_gfp_highmem;
3421         bool ignore_gfp_reclaim;
3422         u32 min_order;
3423 } fail_page_alloc = {
3424         .attr = FAULT_ATTR_INITIALIZER,
3425         .ignore_gfp_reclaim = true,
3426         .ignore_gfp_highmem = true,
3427         .min_order = 1,
3428 };
3429
3430 static int __init setup_fail_page_alloc(char *str)
3431 {
3432         return setup_fault_attr(&fail_page_alloc.attr, str);
3433 }
3434 __setup("fail_page_alloc=", setup_fail_page_alloc);
3435
3436 static bool __should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
3437 {
3438         if (order < fail_page_alloc.min_order)
3439                 return false;
3440         if (gfp_mask & __GFP_NOFAIL)
3441                 return false;
3442         if (fail_page_alloc.ignore_gfp_highmem && (gfp_mask & __GFP_HIGHMEM))
3443                 return false;
3444         if (fail_page_alloc.ignore_gfp_reclaim &&
3445                         (gfp_mask & __GFP_DIRECT_RECLAIM))
3446                 return false;
3447
3448         return should_fail(&fail_page_alloc.attr, 1 << order);
3449 }
3450
3451 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
3452
3453 static int __init fail_page_alloc_debugfs(void)
3454 {
3455         umode_t mode = S_IFREG | 0600;
3456         struct dentry *dir;
3457
3458         dir = fault_create_debugfs_attr("fail_page_alloc", NULL,
3459                                         &fail_page_alloc.attr);
3460
3461         debugfs_create_bool("ignore-gfp-wait", mode, dir,
3462                             &fail_page_alloc.ignore_gfp_reclaim);
3463         debugfs_create_bool("ignore-gfp-highmem", mode, dir,
3464                             &fail_page_alloc.ignore_gfp_highmem);
3465         debugfs_create_u32("min-order", mode, dir, &fail_page_alloc.min_order);
3466
3467         return 0;
3468 }
3469
3470 late_initcall(fail_page_alloc_debugfs);
3471
3472 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
3473
3474 #else /* CONFIG_FAIL_PAGE_ALLOC */
3475
3476 static inline bool __should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
3477 {
3478         return false;
3479 }
3480
3481 #endif /* CONFIG_FAIL_PAGE_ALLOC */
3482
3483 static noinline bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
3484 {
3485         return __should_fail_alloc_page(gfp_mask, order);
3486 }
3487 ALLOW_ERROR_INJECTION(should_fail_alloc_page, TRUE);
3488
3489 static inline long __zone_watermark_unusable_free(struct zone *z,
3490                                 unsigned int order, unsigned int alloc_flags)
3491 {
3492         const bool alloc_harder = (alloc_flags & (ALLOC_HARDER|ALLOC_OOM));
3493         long unusable_free = (1 << order) - 1;
3494
3495         /*
3496          * If the caller does not have rights to ALLOC_HARDER then subtract
3497          * the high-atomic reserves. This will over-estimate the size of the
3498          * atomic reserve but it avoids a search.
3499          */
3500         if (likely(!alloc_harder))
3501                 unusable_free += z->nr_reserved_highatomic;
3502
3503 #ifdef CONFIG_CMA
3504         /* If allocation can't use CMA areas don't use free CMA pages */
3505         if (!(alloc_flags & ALLOC_CMA))
3506                 unusable_free += zone_page_state(z, NR_FREE_CMA_PAGES);
3507 #endif
3508
3509         return unusable_free;
3510 }
3511
3512 /*
3513  * Return true if free base pages are above 'mark'. For high-order checks it
3514  * will return true of the order-0 watermark is reached and there is at least
3515  * one free page of a suitable size. Checking now avoids taking the zone lock
3516  * to check in the allocation paths if no pages are free.
3517  */
3518 bool __zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
3519                          int highest_zoneidx, unsigned int alloc_flags,
3520                          long free_pages)
3521 {
3522         long min = mark;
3523         int o;
3524         const bool alloc_harder = (alloc_flags & (ALLOC_HARDER|ALLOC_OOM));
3525
3526         /* free_pages may go negative - that's OK */
3527         free_pages -= __zone_watermark_unusable_free(z, order, alloc_flags);
3528
3529         if (alloc_flags & ALLOC_HIGH)
3530                 min -= min / 2;
3531
3532         if (unlikely(alloc_harder)) {
3533                 /*
3534                  * OOM victims can try even harder than normal ALLOC_HARDER
3535                  * users on the grounds that it's definitely going to be in
3536                  * the exit path shortly and free memory. Any allocation it
3537                  * makes during the free path will be small and short-lived.
3538                  */
3539                 if (alloc_flags & ALLOC_OOM)
3540                         min -= min / 2;
3541                 else
3542                         min -= min / 4;
3543         }
3544
3545         /*
3546          * Check watermarks for an order-0 allocation request. If these
3547          * are not met, then a high-order request also cannot go ahead
3548          * even if a suitable page happened to be free.
3549          */
3550         if (free_pages <= min + z->lowmem_reserve[highest_zoneidx])
3551                 return false;
3552
3553         /* If this is an order-0 request then the watermark is fine */
3554         if (!order)
3555                 return true;
3556
3557         /* For a high-order request, check at least one suitable page is free */
3558         for (o = order; o < MAX_ORDER; o++) {
3559                 struct free_area *area = &z->free_area[o];
3560                 int mt;
3561
3562                 if (!area->nr_free)
3563                         continue;
3564
3565                 for (mt = 0; mt < MIGRATE_PCPTYPES; mt++) {
3566                         if (!free_area_empty(area, mt))
3567                                 return true;
3568                 }
3569
3570 #ifdef CONFIG_CMA
3571                 if ((alloc_flags & ALLOC_CMA) &&
3572                     !free_area_empty(area, MIGRATE_CMA)) {
3573                         return true;
3574                 }
3575 #endif
3576                 if (alloc_harder && !free_area_empty(area, MIGRATE_HIGHATOMIC))
3577                         return true;
3578         }
3579         return false;
3580 }
3581
3582 bool zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
3583                       int highest_zoneidx, unsigned int alloc_flags)
3584 {
3585         return __zone_watermark_ok(z, order, mark, highest_zoneidx, alloc_flags,
3586                                         zone_page_state(z, NR_FREE_PAGES));
3587 }
3588
3589 static inline bool zone_watermark_fast(struct zone *z, unsigned int order,
3590                                 unsigned long mark, int highest_zoneidx,
3591                                 unsigned int alloc_flags, gfp_t gfp_mask)
3592 {
3593         long free_pages;
3594
3595         free_pages = zone_page_state(z, NR_FREE_PAGES);
3596
3597         /*
3598          * Fast check for order-0 only. If this fails then the reserves
3599          * need to be calculated.
3600          */
3601         if (!order) {
3602                 long fast_free;
3603
3604                 fast_free = free_pages;
3605                 fast_free -= __zone_watermark_unusable_free(z, 0, alloc_flags);
3606                 if (fast_free > mark + z->lowmem_reserve[highest_zoneidx])
3607                         return true;
3608         }
3609
3610         if (__zone_watermark_ok(z, order, mark, highest_zoneidx, alloc_flags,
3611                                         free_pages))
3612                 return true;
3613         /*
3614          * Ignore watermark boosting for GFP_ATOMIC order-0 allocations
3615          * when checking the min watermark. The min watermark is the
3616          * point where boosting is ignored so that kswapd is woken up
3617          * when below the low watermark.
3618          */
3619         if (unlikely(!order && (gfp_mask & __GFP_ATOMIC) && z->watermark_boost
3620                 && ((alloc_flags & ALLOC_WMARK_MASK) == WMARK_MIN))) {
3621                 mark = z->_watermark[WMARK_MIN];
3622                 return __zone_watermark_ok(z, order, mark, highest_zoneidx,
3623                                         alloc_flags, free_pages);
3624         }
3625
3626         return false;
3627 }
3628
3629 bool zone_watermark_ok_safe(struct zone *z, unsigned int order,
3630                         unsigned long mark, int highest_zoneidx)
3631 {
3632         long free_pages = zone_page_state(z, NR_FREE_PAGES);
3633
3634         if (z->percpu_drift_mark && free_pages < z->percpu_drift_mark)
3635                 free_pages = zone_page_state_snapshot(z, NR_FREE_PAGES);
3636
3637         return __zone_watermark_ok(z, order, mark, highest_zoneidx, 0,
3638                                                                 free_pages);
3639 }
3640
3641 #ifdef CONFIG_NUMA
3642 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
3643 {
3644         return node_distance(zone_to_nid(local_zone), zone_to_nid(zone)) <=
3645                                 node_reclaim_distance;
3646 }
3647 #else   /* CONFIG_NUMA */
3648 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
3649 {
3650         return true;
3651 }
3652 #endif  /* CONFIG_NUMA */
3653
3654 /*
3655  * The restriction on ZONE_DMA32 as being a suitable zone to use to avoid
3656  * fragmentation is subtle. If the preferred zone was HIGHMEM then
3657  * premature use of a lower zone may cause lowmem pressure problems that
3658  * are worse than fragmentation. If the next zone is ZONE_DMA then it is
3659  * probably too small. It only makes sense to spread allocations to avoid
3660  * fragmentation between the Normal and DMA32 zones.
3661  */
3662 static inline unsigned int
3663 alloc_flags_nofragment(struct zone *zone, gfp_t gfp_mask)
3664 {
3665         unsigned int alloc_flags;
3666
3667         /*
3668          * __GFP_KSWAPD_RECLAIM is assumed to be the same as ALLOC_KSWAPD
3669          * to save a branch.
3670          */
3671         alloc_flags = (__force int) (gfp_mask & __GFP_KSWAPD_RECLAIM);
3672
3673 #ifdef CONFIG_ZONE_DMA32
3674         if (!zone)
3675                 return alloc_flags;
3676
3677         if (zone_idx(zone) != ZONE_NORMAL)
3678                 return alloc_flags;
3679
3680         /*
3681          * If ZONE_DMA32 exists, assume it is the one after ZONE_NORMAL and
3682          * the pointer is within zone->zone_pgdat->node_zones[]. Also assume
3683          * on UMA that if Normal is populated then so is DMA32.
3684          */
3685         BUILD_BUG_ON(ZONE_NORMAL - ZONE_DMA32 != 1);
3686         if (nr_online_nodes > 1 && !populated_zone(--zone))
3687                 return alloc_flags;
3688
3689         alloc_flags |= ALLOC_NOFRAGMENT;
3690 #endif /* CONFIG_ZONE_DMA32 */
3691         return alloc_flags;
3692 }
3693
3694 /*
3695  * get_page_from_freelist goes through the zonelist trying to allocate
3696  * a page.
3697  */
3698 static struct page *
3699 get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags,
3700                                                 const struct alloc_context *ac)
3701 {
3702         struct zoneref *z;
3703         struct zone *zone;
3704         struct pglist_data *last_pgdat_dirty_limit = NULL;
3705         bool no_fallback;
3706
3707 retry:
3708         /*
3709          * Scan zonelist, looking for a zone with enough free.
3710          * See also __cpuset_node_allowed() comment in kernel/cpuset.c.
3711          */
3712         no_fallback = alloc_flags & ALLOC_NOFRAGMENT;
3713         z = ac->preferred_zoneref;
3714         for_next_zone_zonelist_nodemask(zone, z, ac->zonelist,
3715                                         ac->highest_zoneidx, ac->nodemask) {
3716                 struct page *page;
3717                 unsigned long mark;
3718
3719                 if (cpusets_enabled() &&
3720                         (alloc_flags & ALLOC_CPUSET) &&
3721                         !__cpuset_zone_allowed(zone, gfp_mask))
3722                                 continue;
3723                 /*
3724                  * When allocating a page cache page for writing, we
3725                  * want to get it from a node that is within its dirty
3726                  * limit, such that no single node holds more than its
3727                  * proportional share of globally allowed dirty pages.
3728                  * The dirty limits take into account the node's
3729                  * lowmem reserves and high watermark so that kswapd
3730                  * should be able to balance it without having to
3731                  * write pages from its LRU list.
3732                  *
3733                  * XXX: For now, allow allocations to potentially
3734                  * exceed the per-node dirty limit in the slowpath
3735                  * (spread_dirty_pages unset) before going into reclaim,
3736                  * which is important when on a NUMA setup the allowed
3737                  * nodes are together not big enough to reach the
3738                  * global limit.  The proper fix for these situations
3739                  * will require awareness of nodes in the
3740                  * dirty-throttling and the flusher threads.
3741                  */
3742                 if (ac->spread_dirty_pages) {
3743                         if (last_pgdat_dirty_limit == zone->zone_pgdat)
3744                                 continue;
3745
3746                         if (!node_dirty_ok(zone->zone_pgdat)) {
3747                                 last_pgdat_dirty_limit = zone->zone_pgdat;
3748                                 continue;
3749                         }
3750                 }
3751
3752                 if (no_fallback && nr_online_nodes > 1 &&
3753                     zone != ac->preferred_zoneref->zone) {
3754                         int local_nid;
3755
3756                         /*
3757                          * If moving to a remote node, retry but allow
3758                          * fragmenting fallbacks. Locality is more important
3759                          * than fragmentation avoidance.
3760                          */
3761                         local_nid = zone_to_nid(ac->preferred_zoneref->zone);
3762                         if (zone_to_nid(zone) != local_nid) {
3763                                 alloc_flags &= ~ALLOC_NOFRAGMENT;
3764                                 goto retry;
3765                         }
3766                 }
3767
3768                 mark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK);
3769                 if (!zone_watermark_fast(zone, order, mark,
3770                                        ac->highest_zoneidx, alloc_flags,
3771                                        gfp_mask)) {
3772                         int ret;
3773
3774 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
3775                         /*
3776                          * Watermark failed for this zone, but see if we can
3777                          * grow this zone if it contains deferred pages.
3778                          */
3779                         if (static_branch_unlikely(&deferred_pages)) {
3780                                 if (_deferred_grow_zone(zone, order))
3781                                         goto try_this_zone;
3782                         }
3783 #endif
3784                         /* Checked here to keep the fast path fast */
3785                         BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK);
3786                         if (alloc_flags & ALLOC_NO_WATERMARKS)
3787                                 goto try_this_zone;
3788
3789                         if (node_reclaim_mode == 0 ||
3790                             !zone_allows_reclaim(ac->preferred_zoneref->zone, zone))
3791                                 continue;
3792
3793                         ret = node_reclaim(zone->zone_pgdat, gfp_mask, order);
3794                         switch (ret) {
3795                         case NODE_RECLAIM_NOSCAN:
3796                                 /* did not scan */
3797                                 continue;
3798                         case NODE_RECLAIM_FULL:
3799                                 /* scanned but unreclaimable */
3800                                 continue;
3801                         default:
3802                                 /* did we reclaim enough */
3803                                 if (zone_watermark_ok(zone, order, mark,
3804                                         ac->highest_zoneidx, alloc_flags))
3805                                         goto try_this_zone;
3806
3807                                 continue;
3808                         }
3809                 }
3810
3811 try_this_zone:
3812                 page = rmqueue(ac->preferred_zoneref->zone, zone, order,
3813                                 gfp_mask, alloc_flags, ac->migratetype);
3814                 if (page) {
3815                         prep_new_page(page, order, gfp_mask, alloc_flags);
3816
3817                         /*
3818                          * If this is a high-order atomic allocation then check
3819                          * if the pageblock should be reserved for the future
3820                          */
3821                         if (unlikely(order && (alloc_flags & ALLOC_HARDER)))
3822                                 reserve_highatomic_pageblock(page, zone, order);
3823
3824                         return page;
3825                 } else {
3826 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
3827                         /* Try again if zone has deferred pages */
3828                         if (static_branch_unlikely(&deferred_pages)) {
3829                                 if (_deferred_grow_zone(zone, order))
3830                                         goto try_this_zone;
3831                         }
3832 #endif
3833                 }
3834         }
3835
3836         /*
3837          * It's possible on a UMA machine to get through all zones that are
3838          * fragmented. If avoiding fragmentation, reset and try again.
3839          */
3840         if (no_fallback) {
3841                 alloc_flags &= ~ALLOC_NOFRAGMENT;
3842                 goto retry;
3843         }
3844
3845         return NULL;
3846 }
3847
3848 static void warn_alloc_show_mem(gfp_t gfp_mask, nodemask_t *nodemask)
3849 {
3850         unsigned int filter = SHOW_MEM_FILTER_NODES;
3851
3852         /*
3853          * This documents exceptions given to allocations in certain
3854          * contexts that are allowed to allocate outside current's set
3855          * of allowed nodes.
3856          */
3857         if (!(gfp_mask & __GFP_NOMEMALLOC))
3858                 if (tsk_is_oom_victim(current) ||
3859                     (current->flags & (PF_MEMALLOC | PF_EXITING)))
3860                         filter &= ~SHOW_MEM_FILTER_NODES;
3861         if (in_interrupt() || !(gfp_mask & __GFP_DIRECT_RECLAIM))
3862                 filter &= ~SHOW_MEM_FILTER_NODES;
3863
3864         show_mem(filter, nodemask);
3865 }
3866
3867 void warn_alloc(gfp_t gfp_mask, nodemask_t *nodemask, const char *fmt, ...)
3868 {
3869         struct va_format vaf;
3870         va_list args;
3871         static DEFINE_RATELIMIT_STATE(nopage_rs, 10*HZ, 1);
3872
3873         if ((gfp_mask & __GFP_NOWARN) || !__ratelimit(&nopage_rs))
3874                 return;
3875
3876         va_start(args, fmt);
3877         vaf.fmt = fmt;
3878         vaf.va = &args;
3879         pr_warn("%s: %pV, mode:%#x(%pGg), nodemask=%*pbl",
3880                         current->comm, &vaf, gfp_mask, &gfp_mask,
3881                         nodemask_pr_args(nodemask));
3882         va_end(args);
3883
3884         cpuset_print_current_mems_allowed();
3885         pr_cont("\n");
3886         dump_stack();
3887         warn_alloc_show_mem(gfp_mask, nodemask);
3888 }
3889
3890 static inline struct page *
3891 __alloc_pages_cpuset_fallback(gfp_t gfp_mask, unsigned int order,
3892                               unsigned int alloc_flags,
3893                               const struct alloc_context *ac)
3894 {
3895         struct page *page;
3896
3897         page = get_page_from_freelist(gfp_mask, order,
3898                         alloc_flags|ALLOC_CPUSET, ac);
3899         /*
3900          * fallback to ignore cpuset restriction if our nodes
3901          * are depleted
3902          */
3903         if (!page)
3904                 page = get_page_from_freelist(gfp_mask, order,
3905                                 alloc_flags, ac);
3906
3907         return page;
3908 }
3909
3910 static inline struct page *
3911 __alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order,
3912         const struct alloc_context *ac, unsigned long *did_some_progress)
3913 {
3914         struct oom_control oc = {
3915                 .zonelist = ac->zonelist,
3916                 .nodemask = ac->nodemask,
3917                 .memcg = NULL,
3918                 .gfp_mask = gfp_mask,
3919                 .order = order,
3920         };
3921         struct page *page;
3922
3923         *did_some_progress = 0;
3924
3925         /*
3926          * Acquire the oom lock.  If that fails, somebody else is
3927          * making progress for us.
3928          */
3929         if (!mutex_trylock(&oom_lock)) {
3930                 *did_some_progress = 1;
3931                 schedule_timeout_uninterruptible(1);
3932                 return NULL;
3933         }
3934
3935         /*
3936          * Go through the zonelist yet one more time, keep very high watermark
3937          * here, this is only to catch a parallel oom killing, we must fail if
3938          * we're still under heavy pressure. But make sure that this reclaim
3939          * attempt shall not depend on __GFP_DIRECT_RECLAIM && !__GFP_NORETRY
3940          * allocation which will never fail due to oom_lock already held.
3941          */
3942         page = get_page_from_freelist((gfp_mask | __GFP_HARDWALL) &
3943                                       ~__GFP_DIRECT_RECLAIM, order,
3944                                       ALLOC_WMARK_HIGH|ALLOC_CPUSET, ac);
3945         if (page)
3946                 goto out;
3947
3948         /* Coredumps can quickly deplete all memory reserves */
3949         if (current->flags & PF_DUMPCORE)
3950                 goto out;
3951         /* The OOM killer will not help higher order allocs */
3952         if (order > PAGE_ALLOC_COSTLY_ORDER)
3953                 goto out;
3954         /*
3955          * We have already exhausted all our reclaim opportunities without any
3956          * success so it is time to admit defeat. We will skip the OOM killer
3957          * because it is very likely that the caller has a more reasonable
3958          * fallback than shooting a random task.
3959          */
3960         if (gfp_mask & __GFP_RETRY_MAYFAIL)
3961                 goto out;
3962         /* The OOM killer does not needlessly kill tasks for lowmem */
3963         if (ac->highest_zoneidx < ZONE_NORMAL)
3964                 goto out;
3965         if (pm_suspended_storage())
3966                 goto out;
3967         /*
3968          * XXX: GFP_NOFS allocations should rather fail than rely on
3969          * other request to make a forward progress.
3970          * We are in an unfortunate situation where out_of_memory cannot
3971          * do much for this context but let's try it to at least get
3972          * access to memory reserved if the current task is killed (see
3973          * out_of_memory). Once filesystems are ready to handle allocation
3974          * failures more gracefully we should just bail out here.
3975          */
3976
3977         /* The OOM killer may not free memory on a specific node */
3978         if (gfp_mask & __GFP_THISNODE)
3979                 goto out;
3980
3981         /* Exhausted what can be done so it's blame time */
3982         if (out_of_memory(&oc) || WARN_ON_ONCE(gfp_mask & __GFP_NOFAIL)) {
3983                 *did_some_progress = 1;
3984
3985                 /*
3986                  * Help non-failing allocations by giving them access to memory
3987                  * reserves
3988                  */
3989                 if (gfp_mask & __GFP_NOFAIL)
3990                         page = __alloc_pages_cpuset_fallback(gfp_mask, order,
3991                                         ALLOC_NO_WATERMARKS, ac);
3992         }
3993 out:
3994         mutex_unlock(&oom_lock);
3995         return page;
3996 }
3997
3998 /*
3999  * Maximum number of compaction retries wit a progress before OOM
4000  * killer is consider as the only way to move forward.
4001  */
4002 #define MAX_COMPACT_RETRIES 16
4003
4004 #ifdef CONFIG_COMPACTION
4005 /* Try memory compaction for high-order allocations before reclaim */
4006 static struct page *
4007 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
4008                 unsigned int alloc_flags, const struct alloc_context *ac,
4009                 enum compact_priority prio, enum compact_result *compact_result)
4010 {
4011         struct page *page = NULL;
4012         unsigned long pflags;
4013         unsigned int noreclaim_flag;
4014
4015         if (!order)
4016                 return NULL;
4017
4018         psi_memstall_enter(&pflags);
4019         noreclaim_flag = memalloc_noreclaim_save();
4020
4021         *compact_result = try_to_compact_pages(gfp_mask, order, alloc_flags, ac,
4022                                                                 prio, &page);
4023
4024         memalloc_noreclaim_restore(noreclaim_flag);
4025         psi_memstall_leave(&pflags);
4026
4027         /*
4028          * At least in one zone compaction wasn't deferred or skipped, so let's
4029          * count a compaction stall
4030          */
4031         count_vm_event(COMPACTSTALL);
4032
4033         /* Prep a captured page if available */
4034         if (page)
4035                 prep_new_page(page, order, gfp_mask, alloc_flags);
4036
4037         /* Try get a page from the freelist if available */
4038         if (!page)
4039                 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4040
4041         if (page) {
4042                 struct zone *zone = page_zone(page);
4043
4044                 zone->compact_blockskip_flush = false;
4045                 compaction_defer_reset(zone, order, true);
4046                 count_vm_event(COMPACTSUCCESS);
4047                 return page;
4048         }
4049
4050         /*
4051          * It's bad if compaction run occurs and fails. The most likely reason
4052          * is that pages exist, but not enough to satisfy watermarks.
4053          */
4054         count_vm_event(COMPACTFAIL);
4055
4056         cond_resched();
4057
4058         return NULL;
4059 }
4060
4061 static inline bool
4062 should_compact_retry(struct alloc_context *ac, int order, int alloc_flags,
4063                      enum compact_result compact_result,
4064                      enum compact_priority *compact_priority,
4065                      int *compaction_retries)
4066 {
4067         int max_retries = MAX_COMPACT_RETRIES;
4068         int min_priority;
4069         bool ret = false;
4070         int retries = *compaction_retries;
4071         enum compact_priority priority = *compact_priority;
4072
4073         if (!order)
4074                 return false;
4075
4076         if (compaction_made_progress(compact_result))
4077                 (*compaction_retries)++;
4078
4079         /*
4080          * compaction considers all the zone as desperately out of memory
4081          * so it doesn't really make much sense to retry except when the
4082          * failure could be caused by insufficient priority
4083          */
4084         if (compaction_failed(compact_result))
4085                 goto check_priority;
4086
4087         /*
4088          * compaction was skipped because there are not enough order-0 pages
4089          * to work with, so we retry only if it looks like reclaim can help.
4090          */
4091         if (compaction_needs_reclaim(compact_result)) {
4092                 ret = compaction_zonelist_suitable(ac, order, alloc_flags);
4093                 goto out;
4094         }
4095
4096         /*
4097          * make sure the compaction wasn't deferred or didn't bail out early
4098          * due to locks contention before we declare that we should give up.
4099          * But the next retry should use a higher priority if allowed, so
4100          * we don't just keep bailing out endlessly.
4101          */
4102         if (compaction_withdrawn(compact_result)) {
4103                 goto check_priority;
4104         }
4105
4106         /*
4107          * !costly requests are much more important than __GFP_RETRY_MAYFAIL
4108          * costly ones because they are de facto nofail and invoke OOM
4109          * killer to move on while costly can fail and users are ready
4110          * to cope with that. 1/4 retries is rather arbitrary but we
4111          * would need much more detailed feedback from compaction to
4112          * make a better decision.
4113          */
4114         if (order > PAGE_ALLOC_COSTLY_ORDER)
4115                 max_retries /= 4;
4116         if (*compaction_retries <= max_retries) {
4117                 ret = true;
4118                 goto out;
4119         }
4120
4121         /*
4122          * Make sure there are attempts at the highest priority if we exhausted
4123          * all retries or failed at the lower priorities.
4124          */
4125 check_priority:
4126         min_priority = (order > PAGE_ALLOC_COSTLY_ORDER) ?
4127                         MIN_COMPACT_COSTLY_PRIORITY : MIN_COMPACT_PRIORITY;
4128
4129         if (*compact_priority > min_priority) {
4130                 (*compact_priority)--;
4131                 *compaction_retries = 0;
4132                 ret = true;
4133         }
4134 out:
4135         trace_compact_retry(order, priority, compact_result, retries, max_retries, ret);
4136         return ret;
4137 }
4138 #else
4139 static inline struct page *
4140 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
4141                 unsigned int alloc_flags, const struct alloc_context *ac,
4142                 enum compact_priority prio, enum compact_result *compact_result)
4143 {
4144         *compact_result = COMPACT_SKIPPED;
4145         return NULL;
4146 }
4147
4148 static inline bool
4149 should_compact_retry(struct alloc_context *ac, unsigned int order, int alloc_flags,
4150                      enum compact_result compact_result,
4151                      enum compact_priority *compact_priority,
4152                      int *compaction_retries)
4153 {
4154         struct zone *zone;
4155         struct zoneref *z;
4156
4157         if (!order || order > PAGE_ALLOC_COSTLY_ORDER)
4158                 return false;
4159
4160         /*
4161          * There are setups with compaction disabled which would prefer to loop
4162          * inside the allocator rather than hit the oom killer prematurely.
4163          * Let's give them a good hope and keep retrying while the order-0
4164          * watermarks are OK.
4165          */
4166         for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
4167                                 ac->highest_zoneidx, ac->nodemask) {
4168                 if (zone_watermark_ok(zone, 0, min_wmark_pages(zone),
4169                                         ac->highest_zoneidx, alloc_flags))
4170                         return true;
4171         }
4172         return false;
4173 }
4174 #endif /* CONFIG_COMPACTION */
4175
4176 #ifdef CONFIG_LOCKDEP
4177 static struct lockdep_map __fs_reclaim_map =
4178         STATIC_LOCKDEP_MAP_INIT("fs_reclaim", &__fs_reclaim_map);
4179
4180 static bool __need_fs_reclaim(gfp_t gfp_mask)
4181 {
4182         gfp_mask = current_gfp_context(gfp_mask);
4183
4184         /* no reclaim without waiting on it */
4185         if (!(gfp_mask & __GFP_DIRECT_RECLAIM))
4186                 return false;
4187
4188         /* this guy won't enter reclaim */
4189         if (current->flags & PF_MEMALLOC)
4190                 return false;
4191
4192         /* We're only interested __GFP_FS allocations for now */
4193         if (!(gfp_mask & __GFP_FS))
4194                 return false;
4195
4196         if (gfp_mask & __GFP_NOLOCKDEP)
4197                 return false;
4198
4199         return true;
4200 }
4201
4202 void __fs_reclaim_acquire(void)
4203 {
4204         lock_map_acquire(&__fs_reclaim_map);
4205 }
4206
4207 void __fs_reclaim_release(void)
4208 {
4209         lock_map_release(&__fs_reclaim_map);
4210 }
4211
4212 void fs_reclaim_acquire(gfp_t gfp_mask)
4213 {
4214         if (__need_fs_reclaim(gfp_mask))
4215                 __fs_reclaim_acquire();
4216 }
4217 EXPORT_SYMBOL_GPL(fs_reclaim_acquire);
4218
4219 void fs_reclaim_release(gfp_t gfp_mask)
4220 {
4221         if (__need_fs_reclaim(gfp_mask))
4222                 __fs_reclaim_release();
4223 }
4224 EXPORT_SYMBOL_GPL(fs_reclaim_release);
4225 #endif
4226
4227 /* Perform direct synchronous page reclaim */
4228 static int
4229 __perform_reclaim(gfp_t gfp_mask, unsigned int order,
4230                                         const struct alloc_context *ac)
4231 {
4232         int progress;
4233         unsigned int noreclaim_flag;
4234         unsigned long pflags;
4235
4236         cond_resched();
4237
4238         /* We now go into synchronous reclaim */
4239         cpuset_memory_pressure_bump();
4240         psi_memstall_enter(&pflags);
4241         fs_reclaim_acquire(gfp_mask);
4242         noreclaim_flag = memalloc_noreclaim_save();
4243
4244         progress = try_to_free_pages(ac->zonelist, order, gfp_mask,
4245                                                                 ac->nodemask);
4246
4247         memalloc_noreclaim_restore(noreclaim_flag);
4248         fs_reclaim_release(gfp_mask);
4249         psi_memstall_leave(&pflags);
4250
4251         cond_resched();
4252
4253         return progress;
4254 }
4255
4256 /* The really slow allocator path where we enter direct reclaim */
4257 static inline struct page *
4258 __alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order,
4259                 unsigned int alloc_flags, const struct alloc_context *ac,
4260                 unsigned long *did_some_progress)
4261 {
4262         struct page *page = NULL;
4263         bool drained = false;
4264
4265         *did_some_progress = __perform_reclaim(gfp_mask, order, ac);
4266         if (unlikely(!(*did_some_progress)))
4267                 return NULL;
4268
4269 retry:
4270         page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4271
4272         /*
4273          * If an allocation failed after direct reclaim, it could be because
4274          * pages are pinned on the per-cpu lists or in high alloc reserves.
4275          * Shrink them them and try again
4276          */
4277         if (!page && !drained) {
4278                 unreserve_highatomic_pageblock(ac, false);
4279                 drain_all_pages(NULL);
4280                 drained = true;
4281                 goto retry;
4282         }
4283
4284         return page;
4285 }
4286
4287 static void wake_all_kswapds(unsigned int order, gfp_t gfp_mask,
4288                              const struct alloc_context *ac)
4289 {
4290         struct zoneref *z;
4291         struct zone *zone;
4292         pg_data_t *last_pgdat = NULL;
4293         enum zone_type highest_zoneidx = ac->highest_zoneidx;
4294
4295         for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, highest_zoneidx,
4296                                         ac->nodemask) {
4297                 if (last_pgdat != zone->zone_pgdat)
4298                         wakeup_kswapd(zone, gfp_mask, order, highest_zoneidx);
4299                 last_pgdat = zone->zone_pgdat;
4300         }
4301 }
4302
4303 static inline unsigned int
4304 gfp_to_alloc_flags(gfp_t gfp_mask)
4305 {
4306         unsigned int alloc_flags = ALLOC_WMARK_MIN | ALLOC_CPUSET;
4307
4308         /*
4309          * __GFP_HIGH is assumed to be the same as ALLOC_HIGH
4310          * and __GFP_KSWAPD_RECLAIM is assumed to be the same as ALLOC_KSWAPD
4311          * to save two branches.
4312          */
4313         BUILD_BUG_ON(__GFP_HIGH != (__force gfp_t) ALLOC_HIGH);
4314         BUILD_BUG_ON(__GFP_KSWAPD_RECLAIM != (__force gfp_t) ALLOC_KSWAPD);
4315
4316         /*
4317          * The caller may dip into page reserves a bit more if the caller
4318          * cannot run direct reclaim, or if the caller has realtime scheduling
4319          * policy or is asking for __GFP_HIGH memory.  GFP_ATOMIC requests will
4320          * set both ALLOC_HARDER (__GFP_ATOMIC) and ALLOC_HIGH (__GFP_HIGH).
4321          */
4322         alloc_flags |= (__force int)
4323                 (gfp_mask & (__GFP_HIGH | __GFP_KSWAPD_RECLAIM));
4324
4325         if (gfp_mask & __GFP_ATOMIC) {
4326                 /*
4327                  * Not worth trying to allocate harder for __GFP_NOMEMALLOC even
4328                  * if it can't schedule.
4329                  */
4330                 if (!(gfp_mask & __GFP_NOMEMALLOC))
4331                         alloc_flags |= ALLOC_HARDER;
4332                 /*
4333                  * Ignore cpuset mems for GFP_ATOMIC rather than fail, see the
4334                  * comment for __cpuset_node_allowed().
4335                  */
4336                 alloc_flags &= ~ALLOC_CPUSET;
4337         } else if (unlikely(rt_task(current)) && !in_interrupt())
4338                 alloc_flags |= ALLOC_HARDER;
4339
4340 #ifdef CONFIG_CMA
4341         if (gfp_migratetype(gfp_mask) == MIGRATE_MOVABLE)
4342                 alloc_flags |= ALLOC_CMA;
4343 #endif
4344         return alloc_flags;
4345 }
4346
4347 static bool oom_reserves_allowed(struct task_struct *tsk)
4348 {
4349         if (!tsk_is_oom_victim(tsk))
4350                 return false;
4351
4352         /*
4353          * !MMU doesn't have oom reaper so give access to memory reserves
4354          * only to the thread with TIF_MEMDIE set
4355          */
4356         if (!IS_ENABLED(CONFIG_MMU) && !test_thread_flag(TIF_MEMDIE))
4357                 return false;
4358
4359         return true;
4360 }
4361
4362 /*
4363  * Distinguish requests which really need access to full memory
4364  * reserves from oom victims which can live with a portion of it
4365  */
4366 static inline int __gfp_pfmemalloc_flags(gfp_t gfp_mask)
4367 {
4368         if (unlikely(gfp_mask & __GFP_NOMEMALLOC))
4369                 return 0;
4370         if (gfp_mask & __GFP_MEMALLOC)
4371                 return ALLOC_NO_WATERMARKS;
4372         if (in_serving_softirq() && (current->flags & PF_MEMALLOC))
4373                 return ALLOC_NO_WATERMARKS;
4374         if (!in_interrupt()) {
4375                 if (current->flags & PF_MEMALLOC)
4376                         return ALLOC_NO_WATERMARKS;
4377                 else if (oom_reserves_allowed(current))
4378                         return ALLOC_OOM;
4379         }
4380
4381         return 0;
4382 }
4383
4384 bool gfp_pfmemalloc_allowed(gfp_t gfp_mask)
4385 {
4386         return !!__gfp_pfmemalloc_flags(gfp_mask);
4387 }
4388
4389 /*
4390  * Checks whether it makes sense to retry the reclaim to make a forward progress
4391  * for the given allocation request.
4392  *
4393  * We give up when we either have tried MAX_RECLAIM_RETRIES in a row
4394  * without success, or when we couldn't even meet the watermark if we
4395  * reclaimed all remaining pages on the LRU lists.
4396  *
4397  * Returns true if a retry is viable or false to enter the oom path.
4398  */
4399 static inline bool
4400 should_reclaim_retry(gfp_t gfp_mask, unsigned order,
4401                      struct alloc_context *ac, int alloc_flags,
4402                      bool did_some_progress, int *no_progress_loops)
4403 {
4404         struct zone *zone;
4405         struct zoneref *z;
4406         bool ret = false;
4407
4408         /*
4409          * Costly allocations might have made a progress but this doesn't mean
4410          * their order will become available due to high fragmentation so
4411          * always increment the no progress counter for them
4412          */
4413         if (did_some_progress && order <= PAGE_ALLOC_COSTLY_ORDER)
4414                 *no_progress_loops = 0;
4415         else
4416                 (*no_progress_loops)++;
4417
4418         /*
4419          * Make sure we converge to OOM if we cannot make any progress
4420          * several times in the row.
4421          */
4422         if (*no_progress_loops > MAX_RECLAIM_RETRIES) {
4423                 /* Before OOM, exhaust highatomic_reserve */
4424                 return unreserve_highatomic_pageblock(ac, true);
4425         }
4426
4427         /*
4428          * Keep reclaiming pages while there is a chance this will lead
4429          * somewhere.  If none of the target zones can satisfy our allocation
4430          * request even if all reclaimable pages are considered then we are
4431          * screwed and have to go OOM.
4432          */
4433         for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
4434                                 ac->highest_zoneidx, ac->nodemask) {
4435                 unsigned long available;
4436                 unsigned long reclaimable;
4437                 unsigned long min_wmark = min_wmark_pages(zone);
4438                 bool wmark;
4439
4440                 available = reclaimable = zone_reclaimable_pages(zone);
4441                 available += zone_page_state_snapshot(zone, NR_FREE_PAGES);
4442
4443                 /*
4444                  * Would the allocation succeed if we reclaimed all
4445                  * reclaimable pages?
4446                  */
4447                 wmark = __zone_watermark_ok(zone, order, min_wmark,
4448                                 ac->highest_zoneidx, alloc_flags, available);
4449                 trace_reclaim_retry_zone(z, order, reclaimable,
4450                                 available, min_wmark, *no_progress_loops, wmark);
4451                 if (wmark) {
4452                         /*
4453                          * If we didn't make any progress and have a lot of
4454                          * dirty + writeback pages then we should wait for
4455                          * an IO to complete to slow down the reclaim and
4456                          * prevent from pre mature OOM
4457                          */
4458                         if (!did_some_progress) {
4459                                 unsigned long write_pending;
4460
4461                                 write_pending = zone_page_state_snapshot(zone,
4462                                                         NR_ZONE_WRITE_PENDING);
4463
4464                                 if (2 * write_pending > reclaimable) {
4465                                         congestion_wait(BLK_RW_ASYNC, HZ/10);
4466                                         return true;
4467                                 }
4468                         }
4469
4470                         ret = true;
4471                         goto out;
4472                 }
4473         }
4474
4475 out:
4476         /*
4477          * Memory allocation/reclaim might be called from a WQ context and the
4478          * current implementation of the WQ concurrency control doesn't
4479          * recognize that a particular WQ is congested if the worker thread is
4480          * looping without ever sleeping. Therefore we have to do a short sleep
4481          * here rather than calling cond_resched().
4482          */
4483         if (current->flags & PF_WQ_WORKER)
4484                 schedule_timeout_uninterruptible(1);
4485         else
4486                 cond_resched();
4487         return ret;
4488 }
4489
4490 static inline bool
4491 check_retry_cpuset(int cpuset_mems_cookie, struct alloc_context *ac)
4492 {
4493         /*
4494          * It's possible that cpuset's mems_allowed and the nodemask from
4495          * mempolicy don't intersect. This should be normally dealt with by
4496          * policy_nodemask(), but it's possible to race with cpuset update in
4497          * such a way the check therein was true, and then it became false
4498          * before we got our cpuset_mems_cookie here.
4499          * This assumes that for all allocations, ac->nodemask can come only
4500          * from MPOL_BIND mempolicy (whose documented semantics is to be ignored
4501          * when it does not intersect with the cpuset restrictions) or the
4502          * caller can deal with a violated nodemask.
4503          */
4504         if (cpusets_enabled() && ac->nodemask &&
4505                         !cpuset_nodemask_valid_mems_allowed(ac->nodemask)) {
4506                 ac->nodemask = NULL;
4507                 return true;
4508         }
4509
4510         /*
4511          * When updating a task's mems_allowed or mempolicy nodemask, it is
4512          * possible to race with parallel threads in such a way that our
4513          * allocation can fail while the mask is being updated. If we are about
4514          * to fail, check if the cpuset changed during allocation and if so,
4515          * retry.
4516          */
4517         if (read_mems_allowed_retry(cpuset_mems_cookie))
4518                 return true;
4519
4520         return false;
4521 }
4522
4523 static inline struct page *
4524 __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order,
4525                                                 struct alloc_context *ac)
4526 {
4527         bool can_direct_reclaim = gfp_mask & __GFP_DIRECT_RECLAIM;
4528         const bool costly_order = order > PAGE_ALLOC_COSTLY_ORDER;
4529         struct page *page = NULL;
4530         unsigned int alloc_flags;
4531         unsigned long did_some_progress;
4532         enum compact_priority compact_priority;
4533         enum compact_result compact_result;
4534         int compaction_retries;
4535         int no_progress_loops;
4536         unsigned int cpuset_mems_cookie;
4537         int reserve_flags;
4538
4539         /*
4540          * We also sanity check to catch abuse of atomic reserves being used by
4541          * callers that are not in atomic context.
4542          */
4543         if (WARN_ON_ONCE((gfp_mask & (__GFP_ATOMIC|__GFP_DIRECT_RECLAIM)) ==
4544                                 (__GFP_ATOMIC|__GFP_DIRECT_RECLAIM)))
4545                 gfp_mask &= ~__GFP_ATOMIC;
4546
4547 retry_cpuset:
4548         compaction_retries = 0;
4549         no_progress_loops = 0;
4550         compact_priority = DEF_COMPACT_PRIORITY;
4551         cpuset_mems_cookie = read_mems_allowed_begin();
4552
4553         /*
4554          * The fast path uses conservative alloc_flags to succeed only until
4555          * kswapd needs to be woken up, and to avoid the cost of setting up
4556          * alloc_flags precisely. So we do that now.
4557          */
4558         alloc_flags = gfp_to_alloc_flags(gfp_mask);
4559
4560         /*
4561          * We need to recalculate the starting point for the zonelist iterator
4562          * because we might have used different nodemask in the fast path, or
4563          * there was a cpuset modification and we are retrying - otherwise we
4564          * could end up iterating over non-eligible zones endlessly.
4565          */
4566         ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
4567                                         ac->highest_zoneidx, ac->nodemask);
4568         if (!ac->preferred_zoneref->zone)
4569                 goto nopage;
4570
4571         if (alloc_flags & ALLOC_KSWAPD)
4572                 wake_all_kswapds(order, gfp_mask, ac);
4573
4574         /*
4575          * The adjusted alloc_flags might result in immediate success, so try
4576          * that first
4577          */
4578         page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4579         if (page)
4580                 goto got_pg;
4581
4582         /*
4583          * For costly allocations, try direct compaction first, as it's likely
4584          * that we have enough base pages and don't need to reclaim. For non-
4585          * movable high-order allocations, do that as well, as compaction will
4586          * try prevent permanent fragmentation by migrating from blocks of the
4587          * same migratetype.
4588          * Don't try this for allocations that are allowed to ignore
4589          * watermarks, as the ALLOC_NO_WATERMARKS attempt didn't yet happen.
4590          */
4591         if (can_direct_reclaim &&
4592                         (costly_order ||
4593                            (order > 0 && ac->migratetype != MIGRATE_MOVABLE))
4594                         && !gfp_pfmemalloc_allowed(gfp_mask)) {
4595                 page = __alloc_pages_direct_compact(gfp_mask, order,
4596                                                 alloc_flags, ac,
4597                                                 INIT_COMPACT_PRIORITY,
4598                                                 &compact_result);
4599                 if (page)
4600                         goto got_pg;
4601
4602                 /*
4603                  * Checks for costly allocations with __GFP_NORETRY, which
4604                  * includes some THP page fault allocations
4605                  */
4606                 if (costly_order && (gfp_mask & __GFP_NORETRY)) {
4607                         /*
4608                          * If allocating entire pageblock(s) and compaction
4609                          * failed because all zones are below low watermarks
4610                          * or is prohibited because it recently failed at this
4611                          * order, fail immediately unless the allocator has
4612                          * requested compaction and reclaim retry.
4613                          *
4614                          * Reclaim is
4615                          *  - potentially very expensive because zones are far
4616                          *    below their low watermarks or this is part of very
4617                          *    bursty high order allocations,
4618                          *  - not guaranteed to help because isolate_freepages()
4619                          *    may not iterate over freed pages as part of its
4620                          *    linear scan, and
4621                          *  - unlikely to make entire pageblocks free on its
4622                          *    own.
4623                          */
4624                         if (compact_result == COMPACT_SKIPPED ||
4625                             compact_result == COMPACT_DEFERRED)
4626                                 goto nopage;
4627
4628                         /*
4629                          * Looks like reclaim/compaction is worth trying, but
4630                          * sync compaction could be very expensive, so keep
4631                          * using async compaction.
4632                          */
4633                         compact_priority = INIT_COMPACT_PRIORITY;
4634                 }
4635         }
4636
4637 retry:
4638         /* Ensure kswapd doesn't accidentally go to sleep as long as we loop */
4639         if (alloc_flags & ALLOC_KSWAPD)
4640                 wake_all_kswapds(order, gfp_mask, ac);
4641
4642         reserve_flags = __gfp_pfmemalloc_flags(gfp_mask);
4643         if (reserve_flags)
4644                 alloc_flags = reserve_flags;
4645
4646         /*
4647          * Reset the nodemask and zonelist iterators if memory policies can be
4648          * ignored. These allocations are high priority and system rather than
4649          * user oriented.
4650          */
4651         if (!(alloc_flags & ALLOC_CPUSET) || reserve_flags) {
4652                 ac->nodemask = NULL;
4653                 ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
4654                                         ac->highest_zoneidx, ac->nodemask);
4655         }
4656
4657         /* Attempt with potentially adjusted zonelist and alloc_flags */
4658         page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4659         if (page)
4660                 goto got_pg;
4661
4662         /* Caller is not willing to reclaim, we can't balance anything */
4663         if (!can_direct_reclaim)
4664                 goto nopage;
4665
4666         /* Avoid recursion of direct reclaim */
4667         if (current->flags & PF_MEMALLOC)
4668                 goto nopage;
4669
4670         /* Try direct reclaim and then allocating */
4671         page = __alloc_pages_direct_reclaim(gfp_mask, order, alloc_flags, ac,
4672                                                         &did_some_progress);
4673         if (page)
4674                 goto got_pg;
4675
4676         /* Try direct compaction and then allocating */
4677         page = __alloc_pages_direct_compact(gfp_mask, order, alloc_flags, ac,
4678                                         compact_priority, &compact_result);
4679         if (page)
4680                 goto got_pg;
4681
4682         /* Do not loop if specifically requested */
4683         if (gfp_mask & __GFP_NORETRY)
4684                 goto nopage;
4685
4686         /*
4687          * Do not retry costly high order allocations unless they are
4688          * __GFP_RETRY_MAYFAIL
4689          */
4690         if (costly_order && !(gfp_mask & __GFP_RETRY_MAYFAIL))
4691                 goto nopage;
4692
4693         if (should_reclaim_retry(gfp_mask, order, ac, alloc_flags,
4694                                  did_some_progress > 0, &no_progress_loops))
4695                 goto retry;
4696
4697         /*
4698          * It doesn't make any sense to retry for the compaction if the order-0
4699          * reclaim is not able to make any progress because the current
4700          * implementation of the compaction depends on the sufficient amount
4701          * of free memory (see __compaction_suitable)
4702          */
4703         if (did_some_progress > 0 &&
4704                         should_compact_retry(ac, order, alloc_flags,
4705                                 compact_result, &compact_priority,
4706                                 &compaction_retries))
4707                 goto retry;
4708
4709
4710         /* Deal with possible cpuset update races before we start OOM killing */
4711         if (check_retry_cpuset(cpuset_mems_cookie, ac))
4712                 goto retry_cpuset;
4713
4714         /* Reclaim has failed us, start killing things */
4715         page = __alloc_pages_may_oom(gfp_mask, order, ac, &did_some_progress);
4716         if (page)
4717                 goto got_pg;
4718
4719         /* Avoid allocations with no watermarks from looping endlessly */
4720         if (tsk_is_oom_victim(current) &&
4721             (alloc_flags == ALLOC_OOM ||
4722              (gfp_mask & __GFP_NOMEMALLOC)))
4723                 goto nopage;
4724
4725         /* Retry as long as the OOM killer is making progress */
4726         if (did_some_progress) {
4727                 no_progress_loops = 0;
4728                 goto retry;
4729         }
4730
4731 nopage:
4732         /* Deal with possible cpuset update races before we fail */
4733         if (check_retry_cpuset(cpuset_mems_cookie, ac))
4734                 goto retry_cpuset;
4735
4736         /*
4737          * Make sure that __GFP_NOFAIL request doesn't leak out and make sure
4738          * we always retry
4739          */
4740         if (gfp_mask & __GFP_NOFAIL) {
4741                 /*
4742                  * All existing users of the __GFP_NOFAIL are blockable, so warn
4743                  * of any new users that actually require GFP_NOWAIT
4744                  */
4745                 if (WARN_ON_ONCE(!can_direct_reclaim))
4746                         goto fail;
4747
4748                 /*
4749                  * PF_MEMALLOC request from this context is rather bizarre
4750                  * because we cannot reclaim anything and only can loop waiting
4751                  * for somebody to do a work for us
4752                  */
4753                 WARN_ON_ONCE(current->flags & PF_MEMALLOC);
4754
4755                 /*
4756                  * non failing costly orders are a hard requirement which we
4757                  * are not prepared for much so let's warn about these users
4758                  * so that we can identify them and convert them to something
4759                  * else.
4760                  */
4761                 WARN_ON_ONCE(order > PAGE_ALLOC_COSTLY_ORDER);
4762
4763                 /*
4764                  * Help non-failing allocations by giving them access to memory
4765                  * reserves but do not use ALLOC_NO_WATERMARKS because this
4766                  * could deplete whole memory reserves which would just make
4767                  * the situation worse
4768                  */
4769                 page = __alloc_pages_cpuset_fallback(gfp_mask, order, ALLOC_HARDER, ac);
4770                 if (page)
4771                         goto got_pg;
4772
4773                 cond_resched();
4774                 goto retry;
4775         }
4776 fail:
4777         warn_alloc(gfp_mask, ac->nodemask,
4778                         "page allocation failure: order:%u", order);
4779 got_pg:
4780         return page;
4781 }
4782
4783 static inline bool prepare_alloc_pages(gfp_t gfp_mask, unsigned int order,
4784                 int preferred_nid, nodemask_t *nodemask,
4785                 struct alloc_context *ac, gfp_t *alloc_mask,
4786                 unsigned int *alloc_flags)
4787 {
4788         ac->highest_zoneidx = gfp_zone(gfp_mask);
4789         ac->zonelist = node_zonelist(preferred_nid, gfp_mask);
4790         ac->nodemask = nodemask;
4791         ac->migratetype = gfp_migratetype(gfp_mask);
4792
4793         if (cpusets_enabled()) {
4794                 *alloc_mask |= __GFP_HARDWALL;
4795                 if (!ac->nodemask)
4796                         ac->nodemask = &cpuset_current_mems_allowed;
4797                 else
4798                         *alloc_flags |= ALLOC_CPUSET;
4799         }
4800
4801         fs_reclaim_acquire(gfp_mask);
4802         fs_reclaim_release(gfp_mask);
4803
4804         might_sleep_if(gfp_mask & __GFP_DIRECT_RECLAIM);
4805
4806         if (should_fail_alloc_page(gfp_mask, order))
4807                 return false;
4808
4809         if (IS_ENABLED(CONFIG_CMA) && ac->migratetype == MIGRATE_MOVABLE)
4810                 *alloc_flags |= ALLOC_CMA;
4811
4812         return true;
4813 }
4814
4815 /* Determine whether to spread dirty pages and what the first usable zone */
4816 static inline void finalise_ac(gfp_t gfp_mask, struct alloc_context *ac)
4817 {
4818         /* Dirty zone balancing only done in the fast path */
4819         ac->spread_dirty_pages = (gfp_mask & __GFP_WRITE);
4820
4821         /*
4822          * The preferred zone is used for statistics but crucially it is
4823          * also used as the starting point for the zonelist iterator. It
4824          * may get reset for allocations that ignore memory policies.
4825          */
4826         ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
4827                                         ac->highest_zoneidx, ac->nodemask);
4828 }
4829
4830 /*
4831  * This is the 'heart' of the zoned buddy allocator.
4832  */
4833 struct page *
4834 __alloc_pages_nodemask(gfp_t gfp_mask, unsigned int order, int preferred_nid,
4835                                                         nodemask_t *nodemask)
4836 {
4837         struct page *page;
4838         unsigned int alloc_flags = ALLOC_WMARK_LOW;
4839         gfp_t alloc_mask; /* The gfp_t that was actually used for allocation */
4840         struct alloc_context ac = { };
4841
4842         /*
4843          * There are several places where we assume that the order value is sane
4844          * so bail out early if the request is out of bound.
4845          */
4846         if (unlikely(order >= MAX_ORDER)) {
4847                 WARN_ON_ONCE(!(gfp_mask & __GFP_NOWARN));
4848                 return NULL;
4849         }
4850
4851         gfp_mask &= gfp_allowed_mask;
4852         alloc_mask = gfp_mask;
4853         if (!prepare_alloc_pages(gfp_mask, order, preferred_nid, nodemask, &ac, &alloc_mask, &alloc_flags))
4854                 return NULL;
4855
4856         finalise_ac(gfp_mask, &ac);
4857
4858         /*
4859          * Forbid the first pass from falling back to types that fragment
4860          * memory until all local zones are considered.
4861          */
4862         alloc_flags |= alloc_flags_nofragment(ac.preferred_zoneref->zone, gfp_mask);
4863
4864         /* First allocation attempt */
4865         page = get_page_from_freelist(alloc_mask, order, alloc_flags, &ac);
4866         if (likely(page))
4867                 goto out;
4868
4869         /*
4870          * Apply scoped allocation constraints. This is mainly about GFP_NOFS
4871          * resp. GFP_NOIO which has to be inherited for all allocation requests
4872          * from a particular context which has been marked by
4873          * memalloc_no{fs,io}_{save,restore}.
4874          */
4875         alloc_mask = current_gfp_context(gfp_mask);
4876         ac.spread_dirty_pages = false;
4877
4878         /*
4879          * Restore the original nodemask if it was potentially replaced with
4880          * &cpuset_current_mems_allowed to optimize the fast-path attempt.
4881          */
4882         ac.nodemask = nodemask;
4883
4884         page = __alloc_pages_slowpath(alloc_mask, order, &ac);
4885
4886 out:
4887         if (memcg_kmem_enabled() && (gfp_mask & __GFP_ACCOUNT) && page &&
4888             unlikely(__memcg_kmem_charge_page(page, gfp_mask, order) != 0)) {
4889                 __free_pages(page, order);
4890                 page = NULL;
4891         }
4892
4893         trace_mm_page_alloc(page, order, alloc_mask, ac.migratetype);
4894
4895         return page;
4896 }
4897 EXPORT_SYMBOL(__alloc_pages_nodemask);
4898
4899 /*
4900  * Common helper functions. Never use with __GFP_HIGHMEM because the returned
4901  * address cannot represent highmem pages. Use alloc_pages and then kmap if
4902  * you need to access high mem.
4903  */
4904 unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order)
4905 {
4906         struct page *page;
4907
4908         page = alloc_pages(gfp_mask & ~__GFP_HIGHMEM, order);
4909         if (!page)
4910                 return 0;
4911         return (unsigned long) page_address(page);
4912 }
4913 EXPORT_SYMBOL(__get_free_pages);
4914
4915 unsigned long get_zeroed_page(gfp_t gfp_mask)
4916 {
4917         return __get_free_pages(gfp_mask | __GFP_ZERO, 0);
4918 }
4919 EXPORT_SYMBOL(get_zeroed_page);
4920
4921 static inline void free_the_page(struct page *page, unsigned int order)
4922 {
4923         if (order == 0)         /* Via pcp? */
4924                 free_unref_page(page);
4925         else
4926                 __free_pages_ok(page, order);
4927 }
4928
4929 void __free_pages(struct page *page, unsigned int order)
4930 {
4931         if (put_page_testzero(page))
4932                 free_the_page(page, order);
4933 }
4934 EXPORT_SYMBOL(__free_pages);
4935
4936 void free_pages(unsigned long addr, unsigned int order)
4937 {
4938         if (addr != 0) {
4939                 VM_BUG_ON(!virt_addr_valid((void *)addr));
4940                 __free_pages(virt_to_page((void *)addr), order);
4941         }
4942 }
4943
4944 EXPORT_SYMBOL(free_pages);
4945
4946 /*
4947  * Page Fragment:
4948  *  An arbitrary-length arbitrary-offset area of memory which resides
4949  *  within a 0 or higher order page.  Multiple fragments within that page
4950  *  are individually refcounted, in the page's reference counter.
4951  *
4952  * The page_frag functions below provide a simple allocation framework for
4953  * page fragments.  This is used by the network stack and network device
4954  * drivers to provide a backing region of memory for use as either an
4955  * sk_buff->head, or to be used in the "frags" portion of skb_shared_info.
4956  */
4957 static struct page *__page_frag_cache_refill(struct page_frag_cache *nc,
4958                                              gfp_t gfp_mask)
4959 {
4960         struct page *page = NULL;
4961         gfp_t gfp = gfp_mask;
4962
4963 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
4964         gfp_mask |= __GFP_COMP | __GFP_NOWARN | __GFP_NORETRY |
4965                     __GFP_NOMEMALLOC;
4966         page = alloc_pages_node(NUMA_NO_NODE, gfp_mask,
4967                                 PAGE_FRAG_CACHE_MAX_ORDER);
4968         nc->size = page ? PAGE_FRAG_CACHE_MAX_SIZE : PAGE_SIZE;
4969 #endif
4970         if (unlikely(!page))
4971                 page = alloc_pages_node(NUMA_NO_NODE, gfp, 0);
4972
4973         nc->va = page ? page_address(page) : NULL;
4974
4975         return page;
4976 }
4977
4978 void __page_frag_cache_drain(struct page *page, unsigned int count)
4979 {
4980         VM_BUG_ON_PAGE(page_ref_count(page) == 0, page);
4981
4982         if (page_ref_sub_and_test(page, count))
4983                 free_the_page(page, compound_order(page));
4984 }
4985 EXPORT_SYMBOL(__page_frag_cache_drain);
4986
4987 void *page_frag_alloc(struct page_frag_cache *nc,
4988                       unsigned int fragsz, gfp_t gfp_mask)
4989 {
4990         unsigned int size = PAGE_SIZE;
4991         struct page *page;
4992         int offset;
4993
4994         if (unlikely(!nc->va)) {
4995 refill:
4996                 page = __page_frag_cache_refill(nc, gfp_mask);
4997                 if (!page)
4998                         return NULL;
4999
5000 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
5001                 /* if size can vary use size else just use PAGE_SIZE */
5002                 size = nc->size;
5003 #endif
5004                 /* Even if we own the page, we do not use atomic_set().
5005                  * This would break get_page_unless_zero() users.
5006                  */
5007                 page_ref_add(page, PAGE_FRAG_CACHE_MAX_SIZE);
5008
5009                 /* reset page count bias and offset to start of new frag */
5010                 nc->pfmemalloc = page_is_pfmemalloc(page);
5011                 nc->pagecnt_bias = PAGE_FRAG_CACHE_MAX_SIZE + 1;
5012                 nc->offset = size;
5013         }
5014
5015         offset = nc->offset - fragsz;
5016         if (unlikely(offset < 0)) {
5017                 page = virt_to_page(nc->va);
5018
5019                 if (!page_ref_sub_and_test(page, nc->pagecnt_bias))
5020                         goto refill;
5021
5022 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
5023                 /* if size can vary use size else just use PAGE_SIZE */
5024                 size = nc->size;
5025 #endif
5026                 /* OK, page count is 0, we can safely set it */
5027                 set_page_count(page, PAGE_FRAG_CACHE_MAX_SIZE + 1);
5028
5029                 /* reset page count bias and offset to start of new frag */
5030                 nc->pagecnt_bias = PAGE_FRAG_CACHE_MAX_SIZE + 1;
5031                 offset = size - fragsz;
5032         }
5033
5034         nc->pagecnt_bias--;
5035         nc->offset = offset;
5036
5037         return nc->va + offset;
5038 }
5039 EXPORT_SYMBOL(page_frag_alloc);
5040
5041 /*
5042  * Frees a page fragment allocated out of either a compound or order 0 page.
5043  */
5044 void page_frag_free(void *addr)
5045 {
5046         struct page *page = virt_to_head_page(addr);
5047
5048         if (unlikely(put_page_testzero(page)))
5049                 free_the_page(page, compound_order(page));
5050 }
5051 EXPORT_SYMBOL(page_frag_free);
5052
5053 static void *make_alloc_exact(unsigned long addr, unsigned int order,
5054                 size_t size)
5055 {
5056         if (addr) {
5057                 unsigned long alloc_end = addr + (PAGE_SIZE << order);
5058                 unsigned long used = addr + PAGE_ALIGN(size);
5059
5060                 split_page(virt_to_page((void *)addr), order);
5061                 while (used < alloc_end) {
5062                         free_page(used);
5063                         used += PAGE_SIZE;
5064                 }
5065         }
5066         return (void *)addr;
5067 }
5068
5069 /**
5070  * alloc_pages_exact - allocate an exact number physically-contiguous pages.
5071  * @size: the number of bytes to allocate
5072  * @gfp_mask: GFP flags for the allocation, must not contain __GFP_COMP
5073  *
5074  * This function is similar to alloc_pages(), except that it allocates the
5075  * minimum number of pages to satisfy the request.  alloc_pages() can only
5076  * allocate memory in power-of-two pages.
5077  *
5078  * This function is also limited by MAX_ORDER.
5079  *
5080  * Memory allocated by this function must be released by free_pages_exact().
5081  *
5082  * Return: pointer to the allocated area or %NULL in case of error.
5083  */
5084 void *alloc_pages_exact(size_t size, gfp_t gfp_mask)
5085 {
5086         unsigned int order = get_order(size);
5087         unsigned long addr;
5088
5089         if (WARN_ON_ONCE(gfp_mask & __GFP_COMP))
5090                 gfp_mask &= ~__GFP_COMP;
5091
5092         addr = __get_free_pages(gfp_mask, order);
5093         return make_alloc_exact(addr, order, size);
5094 }
5095 EXPORT_SYMBOL(alloc_pages_exact);
5096
5097 /**
5098  * alloc_pages_exact_nid - allocate an exact number of physically-contiguous
5099  *                         pages on a node.
5100  * @nid: the preferred node ID where memory should be allocated
5101  * @size: the number of bytes to allocate
5102  * @gfp_mask: GFP flags for the allocation, must not contain __GFP_COMP
5103  *
5104  * Like alloc_pages_exact(), but try to allocate on node nid first before falling
5105  * back.
5106  *
5107  * Return: pointer to the allocated area or %NULL in case of error.
5108  */
5109 void * __meminit alloc_pages_exact_nid(int nid, size_t size, gfp_t gfp_mask)
5110 {
5111         unsigned int order = get_order(size);
5112         struct page *p;
5113
5114         if (WARN_ON_ONCE(gfp_mask & __GFP_COMP))
5115                 gfp_mask &= ~__GFP_COMP;
5116
5117         p = alloc_pages_node(nid, gfp_mask, order);
5118         if (!p)
5119                 return NULL;
5120         return make_alloc_exact((unsigned long)page_address(p), order, size);
5121 }
5122
5123 /**
5124  * free_pages_exact - release memory allocated via alloc_pages_exact()
5125  * @virt: the value returned by alloc_pages_exact.
5126  * @size: size of allocation, same value as passed to alloc_pages_exact().
5127  *
5128  * Release the memory allocated by a previous call to alloc_pages_exact.
5129  */
5130 void free_pages_exact(void *virt, size_t size)
5131 {
5132         unsigned long addr = (unsigned long)virt;
5133         unsigned long end = addr + PAGE_ALIGN(size);
5134
5135         while (addr < end) {
5136                 free_page(addr);
5137                 addr += PAGE_SIZE;
5138         }
5139 }
5140 EXPORT_SYMBOL(free_pages_exact);
5141
5142 /**
5143  * nr_free_zone_pages - count number of pages beyond high watermark
5144  * @offset: The zone index of the highest zone
5145  *
5146  * nr_free_zone_pages() counts the number of pages which are beyond the
5147  * high watermark within all zones at or below a given zone index.  For each
5148  * zone, the number of pages is calculated as:
5149  *
5150  *     nr_free_zone_pages = managed_pages - high_pages
5151  *
5152  * Return: number of pages beyond high watermark.
5153  */
5154 static unsigned long nr_free_zone_pages(int offset)
5155 {
5156         struct zoneref *z;
5157         struct zone *zone;
5158
5159         /* Just pick one node, since fallback list is circular */
5160         unsigned long sum = 0;
5161
5162         struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL);
5163
5164         for_each_zone_zonelist(zone, z, zonelist, offset) {
5165                 unsigned long size = zone_managed_pages(zone);
5166                 unsigned long high = high_wmark_pages(zone);
5167                 if (size > high)
5168                         sum += size - high;
5169         }
5170
5171         return sum;
5172 }
5173
5174 /**
5175  * nr_free_buffer_pages - count number of pages beyond high watermark
5176  *
5177  * nr_free_buffer_pages() counts the number of pages which are beyond the high
5178  * watermark within ZONE_DMA and ZONE_NORMAL.
5179  *
5180  * Return: number of pages beyond high watermark within ZONE_DMA and
5181  * ZONE_NORMAL.
5182  */
5183 unsigned long nr_free_buffer_pages(void)
5184 {
5185         return nr_free_zone_pages(gfp_zone(GFP_USER));
5186 }
5187 EXPORT_SYMBOL_GPL(nr_free_buffer_pages);
5188
5189 static inline void show_node(struct zone *zone)
5190 {
5191         if (IS_ENABLED(CONFIG_NUMA))
5192                 printk("Node %d ", zone_to_nid(zone));
5193 }
5194
5195 long si_mem_available(void)
5196 {
5197         long available;
5198         unsigned long pagecache;
5199         unsigned long wmark_low = 0;
5200         unsigned long pages[NR_LRU_LISTS];
5201         unsigned long reclaimable;
5202         struct zone *zone;
5203         int lru;
5204
5205         for (lru = LRU_BASE; lru < NR_LRU_LISTS; lru++)
5206                 pages[lru] = global_node_page_state(NR_LRU_BASE + lru);
5207
5208         for_each_zone(zone)
5209                 wmark_low += low_wmark_pages(zone);
5210
5211         /*
5212          * Estimate the amount of memory available for userspace allocations,
5213          * without causing swapping.
5214          */
5215         available = global_zone_page_state(NR_FREE_PAGES) - totalreserve_pages;
5216
5217         /*
5218          * Not all the page cache can be freed, otherwise the system will
5219          * start swapping. Assume at least half of the page cache, or the
5220          * low watermark worth of cache, needs to stay.
5221          */
5222         pagecache = pages[LRU_ACTIVE_FILE] + pages[LRU_INACTIVE_FILE];
5223         pagecache -= min(pagecache / 2, wmark_low);
5224         available += pagecache;
5225
5226         /*
5227          * Part of the reclaimable slab and other kernel memory consists of
5228          * items that are in use, and cannot be freed. Cap this estimate at the
5229          * low watermark.
5230          */
5231         reclaimable = global_node_page_state_pages(NR_SLAB_RECLAIMABLE_B) +
5232                 global_node_page_state(NR_KERNEL_MISC_RECLAIMABLE);
5233         available += reclaimable - min(reclaimable / 2, wmark_low);
5234
5235         if (available < 0)
5236                 available = 0;
5237         return available;
5238 }
5239 EXPORT_SYMBOL_GPL(si_mem_available);
5240
5241 void si_meminfo(struct sysinfo *val)
5242 {
5243         val->totalram = totalram_pages();
5244         val->sharedram = global_node_page_state(NR_SHMEM);
5245         val->freeram = global_zone_page_state(NR_FREE_PAGES);
5246         val->bufferram = nr_blockdev_pages();
5247         val->totalhigh = totalhigh_pages();
5248         val->freehigh = nr_free_highpages();
5249         val->mem_unit = PAGE_SIZE;
5250 }
5251
5252 EXPORT_SYMBOL(si_meminfo);
5253
5254 #ifdef CONFIG_NUMA
5255 void si_meminfo_node(struct sysinfo *val, int nid)
5256 {
5257         int zone_type;          /* needs to be signed */
5258         unsigned long managed_pages = 0;
5259         unsigned long managed_highpages = 0;
5260         unsigned long free_highpages = 0;
5261         pg_data_t *pgdat = NODE_DATA(nid);
5262
5263         for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++)
5264                 managed_pages += zone_managed_pages(&pgdat->node_zones[zone_type]);
5265         val->totalram = managed_pages;
5266         val->sharedram = node_page_state(pgdat, NR_SHMEM);
5267         val->freeram = sum_zone_node_page_state(nid, NR_FREE_PAGES);
5268 #ifdef CONFIG_HIGHMEM
5269         for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
5270                 struct zone *zone = &pgdat->node_zones[zone_type];
5271
5272                 if (is_highmem(zone)) {
5273                         managed_highpages += zone_managed_pages(zone);
5274                         free_highpages += zone_page_state(zone, NR_FREE_PAGES);
5275                 }
5276         }
5277         val->totalhigh = managed_highpages;
5278         val->freehigh = free_highpages;
5279 #else
5280         val->totalhigh = managed_highpages;
5281         val->freehigh = free_highpages;
5282 #endif
5283         val->mem_unit = PAGE_SIZE;
5284 }
5285 #endif
5286
5287 /*
5288  * Determine whether the node should be displayed or not, depending on whether
5289  * SHOW_MEM_FILTER_NODES was passed to show_free_areas().
5290  */
5291 static bool show_mem_node_skip(unsigned int flags, int nid, nodemask_t *nodemask)
5292 {
5293         if (!(flags & SHOW_MEM_FILTER_NODES))
5294                 return false;
5295
5296         /*
5297          * no node mask - aka implicit memory numa policy. Do not bother with
5298          * the synchronization - read_mems_allowed_begin - because we do not
5299          * have to be precise here.
5300          */
5301         if (!nodemask)
5302                 nodemask = &cpuset_current_mems_allowed;
5303
5304         return !node_isset(nid, *nodemask);
5305 }
5306
5307 #define K(x) ((x) << (PAGE_SHIFT-10))
5308
5309 static void show_migration_types(unsigned char type)
5310 {
5311         static const char types[MIGRATE_TYPES] = {
5312                 [MIGRATE_UNMOVABLE]     = 'U',
5313                 [MIGRATE_MOVABLE]       = 'M',
5314                 [MIGRATE_RECLAIMABLE]   = 'E',
5315                 [MIGRATE_HIGHATOMIC]    = 'H',
5316 #ifdef CONFIG_CMA
5317                 [MIGRATE_CMA]           = 'C',
5318 #endif
5319 #ifdef CONFIG_MEMORY_ISOLATION
5320                 [MIGRATE_ISOLATE]       = 'I',
5321 #endif
5322         };
5323         char tmp[MIGRATE_TYPES + 1];
5324         char *p = tmp;
5325         int i;
5326
5327         for (i = 0; i < MIGRATE_TYPES; i++) {
5328                 if (type & (1 << i))
5329                         *p++ = types[i];
5330         }
5331
5332         *p = '\0';
5333         printk(KERN_CONT "(%s) ", tmp);
5334 }
5335
5336 /*
5337  * Show free area list (used inside shift_scroll-lock stuff)
5338  * We also calculate the percentage fragmentation. We do this by counting the
5339  * memory on each free list with the exception of the first item on the list.
5340  *
5341  * Bits in @filter:
5342  * SHOW_MEM_FILTER_NODES: suppress nodes that are not allowed by current's
5343  *   cpuset.
5344  */
5345 void show_free_areas(unsigned int filter, nodemask_t *nodemask)
5346 {
5347         unsigned long free_pcp = 0;
5348         int cpu;
5349         struct zone *zone;
5350         pg_data_t *pgdat;
5351
5352         for_each_populated_zone(zone) {
5353                 if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask))
5354                         continue;
5355
5356                 for_each_online_cpu(cpu)
5357                         free_pcp += per_cpu_ptr(zone->pageset, cpu)->pcp.count;
5358         }
5359
5360         printk("active_anon:%lu inactive_anon:%lu isolated_anon:%lu\n"
5361                 " active_file:%lu inactive_file:%lu isolated_file:%lu\n"
5362                 " unevictable:%lu dirty:%lu writeback:%lu\n"
5363                 " slab_reclaimable:%lu slab_unreclaimable:%lu\n"
5364                 " mapped:%lu shmem:%lu pagetables:%lu bounce:%lu\n"
5365                 " free:%lu free_pcp:%lu free_cma:%lu\n",
5366                 global_node_page_state(NR_ACTIVE_ANON),
5367                 global_node_page_state(NR_INACTIVE_ANON),
5368                 global_node_page_state(NR_ISOLATED_ANON),
5369                 global_node_page_state(NR_ACTIVE_FILE),
5370                 global_node_page_state(NR_INACTIVE_FILE),
5371                 global_node_page_state(NR_ISOLATED_FILE),
5372                 global_node_page_state(NR_UNEVICTABLE),
5373                 global_node_page_state(NR_FILE_DIRTY),
5374                 global_node_page_state(NR_WRITEBACK),
5375                 global_node_page_state_pages(NR_SLAB_RECLAIMABLE_B),
5376                 global_node_page_state_pages(NR_SLAB_UNRECLAIMABLE_B),
5377                 global_node_page_state(NR_FILE_MAPPED),
5378                 global_node_page_state(NR_SHMEM),
5379                 global_zone_page_state(NR_PAGETABLE),
5380                 global_zone_page_state(NR_BOUNCE),
5381                 global_zone_page_state(NR_FREE_PAGES),
5382                 free_pcp,
5383                 global_zone_page_state(NR_FREE_CMA_PAGES));
5384
5385         for_each_online_pgdat(pgdat) {
5386                 if (show_mem_node_skip(filter, pgdat->node_id, nodemask))
5387                         continue;
5388
5389                 printk("Node %d"
5390                         " active_anon:%lukB"
5391                         " inactive_anon:%lukB"
5392                         " active_file:%lukB"
5393                         " inactive_file:%lukB"
5394                         " unevictable:%lukB"
5395                         " isolated(anon):%lukB"
5396                         " isolated(file):%lukB"
5397                         " mapped:%lukB"
5398                         " dirty:%lukB"
5399                         " writeback:%lukB"
5400                         " shmem:%lukB"
5401 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5402                         " shmem_thp: %lukB"
5403                         " shmem_pmdmapped: %lukB"
5404                         " anon_thp: %lukB"
5405 #endif
5406                         " writeback_tmp:%lukB"
5407                         " kernel_stack:%lukB"
5408 #ifdef CONFIG_SHADOW_CALL_STACK
5409                         " shadow_call_stack:%lukB"
5410 #endif
5411                         " all_unreclaimable? %s"
5412                         "\n",
5413                         pgdat->node_id,
5414                         K(node_page_state(pgdat, NR_ACTIVE_ANON)),
5415                         K(node_page_state(pgdat, NR_INACTIVE_ANON)),
5416                         K(node_page_state(pgdat, NR_ACTIVE_FILE)),
5417                         K(node_page_state(pgdat, NR_INACTIVE_FILE)),
5418                         K(node_page_state(pgdat, NR_UNEVICTABLE)),
5419                         K(node_page_state(pgdat, NR_ISOLATED_ANON)),
5420                         K(node_page_state(pgdat, NR_ISOLATED_FILE)),
5421                         K(node_page_state(pgdat, NR_FILE_MAPPED)),
5422                         K(node_page_state(pgdat, NR_FILE_DIRTY)),
5423                         K(node_page_state(pgdat, NR_WRITEBACK)),
5424                         K(node_page_state(pgdat, NR_SHMEM)),
5425 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5426                         K(node_page_state(pgdat, NR_SHMEM_THPS) * HPAGE_PMD_NR),
5427                         K(node_page_state(pgdat, NR_SHMEM_PMDMAPPED)
5428                                         * HPAGE_PMD_NR),
5429                         K(node_page_state(pgdat, NR_ANON_THPS) * HPAGE_PMD_NR),
5430 #endif
5431                         K(node_page_state(pgdat, NR_WRITEBACK_TEMP)),
5432                         node_page_state(pgdat, NR_KERNEL_STACK_KB),
5433 #ifdef CONFIG_SHADOW_CALL_STACK
5434                         node_page_state(pgdat, NR_KERNEL_SCS_KB),
5435 #endif
5436                         pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ?
5437                                 "yes" : "no");
5438         }
5439
5440         for_each_populated_zone(zone) {
5441                 int i;
5442
5443                 if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask))
5444                         continue;
5445
5446                 free_pcp = 0;
5447                 for_each_online_cpu(cpu)
5448                         free_pcp += per_cpu_ptr(zone->pageset, cpu)->pcp.count;
5449
5450                 show_node(zone);
5451                 printk(KERN_CONT
5452                         "%s"
5453                         " free:%lukB"
5454                         " min:%lukB"
5455                         " low:%lukB"
5456                         " high:%lukB"
5457                         " reserved_highatomic:%luKB"
5458                         " active_anon:%lukB"
5459                         " inactive_anon:%lukB"
5460                         " active_file:%lukB"
5461                         " inactive_file:%lukB"
5462                         " unevictable:%lukB"
5463                         " writepending:%lukB"
5464                         " present:%lukB"
5465                         " managed:%lukB"
5466                         " mlocked:%lukB"
5467                         " pagetables:%lukB"
5468                         " bounce:%lukB"
5469                         " free_pcp:%lukB"
5470                         " local_pcp:%ukB"
5471                         " free_cma:%lukB"
5472                         "\n",
5473                         zone->name,
5474                         K(zone_page_state(zone, NR_FREE_PAGES)),
5475                         K(min_wmark_pages(zone)),
5476                         K(low_wmark_pages(zone)),
5477                         K(high_wmark_pages(zone)),
5478                         K(zone->nr_reserved_highatomic),
5479                         K(zone_page_state(zone, NR_ZONE_ACTIVE_ANON)),
5480                         K(zone_page_state(zone, NR_ZONE_INACTIVE_ANON)),
5481                         K(zone_page_state(zone, NR_ZONE_ACTIVE_FILE)),
5482                         K(zone_page_state(zone, NR_ZONE_INACTIVE_FILE)),
5483                         K(zone_page_state(zone, NR_ZONE_UNEVICTABLE)),
5484                         K(zone_page_state(zone, NR_ZONE_WRITE_PENDING)),
5485                         K(zone->present_pages),
5486                         K(zone_managed_pages(zone)),
5487                         K(zone_page_state(zone, NR_MLOCK)),
5488                         K(zone_page_state(zone, NR_PAGETABLE)),
5489                         K(zone_page_state(zone, NR_BOUNCE)),
5490                         K(free_pcp),
5491                         K(this_cpu_read(zone->pageset->pcp.count)),
5492                         K(zone_page_state(zone, NR_FREE_CMA_PAGES)));
5493                 printk("lowmem_reserve[]:");
5494                 for (i = 0; i < MAX_NR_ZONES; i++)
5495                         printk(KERN_CONT " %ld", zone->lowmem_reserve[i]);
5496                 printk(KERN_CONT "\n");
5497         }
5498
5499         for_each_populated_zone(zone) {
5500                 unsigned int order;
5501                 unsigned long nr[MAX_ORDER], flags, total = 0;
5502                 unsigned char types[MAX_ORDER];
5503
5504                 if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask))
5505                         continue;
5506                 show_node(zone);
5507                 printk(KERN_CONT "%s: ", zone->name);
5508
5509                 spin_lock_irqsave(&zone->lock, flags);
5510                 for (order = 0; order < MAX_ORDER; order++) {
5511                         struct free_area *area = &zone->free_area[order];
5512                         int type;
5513
5514                         nr[order] = area->nr_free;
5515                         total += nr[order] << order;
5516
5517                         types[order] = 0;
5518                         for (type = 0; type < MIGRATE_TYPES; type++) {
5519                                 if (!free_area_empty(area, type))
5520                                         types[order] |= 1 << type;
5521                         }
5522                 }
5523                 spin_unlock_irqrestore(&zone->lock, flags);
5524                 for (order = 0; order < MAX_ORDER; order++) {
5525                         printk(KERN_CONT "%lu*%lukB ",
5526                                nr[order], K(1UL) << order);
5527                         if (nr[order])
5528                                 show_migration_types(types[order]);
5529                 }
5530                 printk(KERN_CONT "= %lukB\n", K(total));
5531         }
5532
5533         hugetlb_show_meminfo();
5534
5535         printk("%ld total pagecache pages\n", global_node_page_state(NR_FILE_PAGES));
5536
5537         show_swap_cache_info();
5538 }
5539
5540 static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref)
5541 {
5542         zoneref->zone = zone;
5543         zoneref->zone_idx = zone_idx(zone);
5544 }
5545
5546 /*
5547  * Builds allocation fallback zone lists.
5548  *
5549  * Add all populated zones of a node to the zonelist.
5550  */
5551 static int build_zonerefs_node(pg_data_t *pgdat, struct zoneref *zonerefs)
5552 {
5553         struct zone *zone;
5554         enum zone_type zone_type = MAX_NR_ZONES;
5555         int nr_zones = 0;
5556
5557         do {
5558                 zone_type--;
5559                 zone = pgdat->node_zones + zone_type;
5560                 if (managed_zone(zone)) {
5561                         zoneref_set_zone(zone, &zonerefs[nr_zones++]);
5562                         check_highest_zone(zone_type);
5563                 }
5564         } while (zone_type);
5565
5566         return nr_zones;
5567 }
5568
5569 #ifdef CONFIG_NUMA
5570
5571 static int __parse_numa_zonelist_order(char *s)
5572 {
5573         /*
5574          * We used to support different zonlists modes but they turned
5575          * out to be just not useful. Let's keep the warning in place
5576          * if somebody still use the cmd line parameter so that we do
5577          * not fail it silently
5578          */
5579         if (!(*s == 'd' || *s == 'D' || *s == 'n' || *s == 'N')) {
5580                 pr_warn("Ignoring unsupported numa_zonelist_order value:  %s\n", s);
5581                 return -EINVAL;
5582         }
5583         return 0;
5584 }
5585
5586 char numa_zonelist_order[] = "Node";
5587
5588 /*
5589  * sysctl handler for numa_zonelist_order
5590  */
5591 int numa_zonelist_order_handler(struct ctl_table *table, int write,
5592                 void *buffer, size_t *length, loff_t *ppos)
5593 {
5594         if (write)
5595                 return __parse_numa_zonelist_order(buffer);
5596         return proc_dostring(table, write, buffer, length, ppos);
5597 }
5598
5599
5600 #define MAX_NODE_LOAD (nr_online_nodes)
5601 static int node_load[MAX_NUMNODES];
5602
5603 /**
5604  * find_next_best_node - find the next node that should appear in a given node's fallback list
5605  * @node: node whose fallback list we're appending
5606  * @used_node_mask: nodemask_t of already used nodes
5607  *
5608  * We use a number of factors to determine which is the next node that should
5609  * appear on a given node's fallback list.  The node should not have appeared
5610  * already in @node's fallback list, and it should be the next closest node
5611  * according to the distance array (which contains arbitrary distance values
5612  * from each node to each node in the system), and should also prefer nodes
5613  * with no CPUs, since presumably they'll have very little allocation pressure
5614  * on them otherwise.
5615  *
5616  * Return: node id of the found node or %NUMA_NO_NODE if no node is found.
5617  */
5618 static int find_next_best_node(int node, nodemask_t *used_node_mask)
5619 {
5620         int n, val;
5621         int min_val = INT_MAX;
5622         int best_node = NUMA_NO_NODE;
5623         const struct cpumask *tmp = cpumask_of_node(0);
5624
5625         /* Use the local node if we haven't already */
5626         if (!node_isset(node, *used_node_mask)) {
5627                 node_set(node, *used_node_mask);
5628                 return node;
5629         }
5630
5631         for_each_node_state(n, N_MEMORY) {
5632
5633                 /* Don't want a node to appear more than once */
5634                 if (node_isset(n, *used_node_mask))
5635                         continue;
5636
5637                 /* Use the distance array to find the distance */
5638                 val = node_distance(node, n);
5639
5640                 /* Penalize nodes under us ("prefer the next node") */
5641                 val += (n < node);
5642
5643                 /* Give preference to headless and unused nodes */
5644                 tmp = cpumask_of_node(n);
5645                 if (!cpumask_empty(tmp))
5646                         val += PENALTY_FOR_NODE_WITH_CPUS;
5647
5648                 /* Slight preference for less loaded node */
5649                 val *= (MAX_NODE_LOAD*MAX_NUMNODES);
5650                 val += node_load[n];
5651
5652                 if (val < min_val) {
5653                         min_val = val;
5654                         best_node = n;
5655                 }
5656         }
5657
5658         if (best_node >= 0)
5659                 node_set(best_node, *used_node_mask);
5660
5661         return best_node;
5662 }
5663
5664
5665 /*
5666  * Build zonelists ordered by node and zones within node.
5667  * This results in maximum locality--normal zone overflows into local
5668  * DMA zone, if any--but risks exhausting DMA zone.
5669  */
5670 static void build_zonelists_in_node_order(pg_data_t *pgdat, int *node_order,
5671                 unsigned nr_nodes)
5672 {
5673         struct zoneref *zonerefs;
5674         int i;
5675
5676         zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs;
5677
5678         for (i = 0; i < nr_nodes; i++) {
5679                 int nr_zones;
5680
5681                 pg_data_t *node = NODE_DATA(node_order[i]);
5682
5683                 nr_zones = build_zonerefs_node(node, zonerefs);
5684                 zonerefs += nr_zones;
5685         }
5686         zonerefs->zone = NULL;
5687         zonerefs->zone_idx = 0;
5688 }
5689
5690 /*
5691  * Build gfp_thisnode zonelists
5692  */
5693 static void build_thisnode_zonelists(pg_data_t *pgdat)
5694 {
5695         struct zoneref *zonerefs;
5696         int nr_zones;
5697
5698         zonerefs = pgdat->node_zonelists[ZONELIST_NOFALLBACK]._zonerefs;
5699         nr_zones = build_zonerefs_node(pgdat, zonerefs);
5700         zonerefs += nr_zones;
5701         zonerefs->zone = NULL;
5702         zonerefs->zone_idx = 0;
5703 }
5704
5705 /*
5706  * Build zonelists ordered by zone and nodes within zones.
5707  * This results in conserving DMA zone[s] until all Normal memory is
5708  * exhausted, but results in overflowing to remote node while memory
5709  * may still exist in local DMA zone.
5710  */
5711
5712 static void build_zonelists(pg_data_t *pgdat)
5713 {
5714         static int node_order[MAX_NUMNODES];
5715         int node, load, nr_nodes = 0;
5716         nodemask_t used_mask = NODE_MASK_NONE;
5717         int local_node, prev_node;
5718
5719         /* NUMA-aware ordering of nodes */
5720         local_node = pgdat->node_id;
5721         load = nr_online_nodes;
5722         prev_node = local_node;
5723
5724         memset(node_order, 0, sizeof(node_order));
5725         while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
5726                 /*
5727                  * We don't want to pressure a particular node.
5728                  * So adding penalty to the first node in same
5729                  * distance group to make it round-robin.
5730                  */
5731                 if (node_distance(local_node, node) !=
5732                     node_distance(local_node, prev_node))
5733                         node_load[node] = load;
5734
5735                 node_order[nr_nodes++] = node;
5736                 prev_node = node;
5737                 load--;
5738         }
5739
5740         build_zonelists_in_node_order(pgdat, node_order, nr_nodes);
5741         build_thisnode_zonelists(pgdat);
5742 }
5743
5744 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
5745 /*
5746  * Return node id of node used for "local" allocations.
5747  * I.e., first node id of first zone in arg node's generic zonelist.
5748  * Used for initializing percpu 'numa_mem', which is used primarily
5749  * for kernel allocations, so use GFP_KERNEL flags to locate zonelist.
5750  */
5751 int local_memory_node(int node)
5752 {
5753         struct zoneref *z;
5754
5755         z = first_zones_zonelist(node_zonelist(node, GFP_KERNEL),
5756                                    gfp_zone(GFP_KERNEL),
5757                                    NULL);
5758         return zone_to_nid(z->zone);
5759 }
5760 #endif
5761
5762 static void setup_min_unmapped_ratio(void);
5763 static void setup_min_slab_ratio(void);
5764 #else   /* CONFIG_NUMA */
5765
5766 static void build_zonelists(pg_data_t *pgdat)
5767 {
5768         int node, local_node;
5769         struct zoneref *zonerefs;
5770         int nr_zones;
5771
5772         local_node = pgdat->node_id;
5773
5774         zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs;
5775         nr_zones = build_zonerefs_node(pgdat, zonerefs);
5776         zonerefs += nr_zones;
5777
5778         /*
5779          * Now we build the zonelist so that it contains the zones
5780          * of all the other nodes.
5781          * We don't want to pressure a particular node, so when
5782          * building the zones for node N, we make sure that the
5783          * zones coming right after the local ones are those from
5784          * node N+1 (modulo N)
5785          */
5786         for (node = local_node + 1; node < MAX_NUMNODES; node++) {
5787                 if (!node_online(node))
5788                         continue;
5789                 nr_zones = build_zonerefs_node(NODE_DATA(node), zonerefs);
5790                 zonerefs += nr_zones;
5791         }
5792         for (node = 0; node < local_node; node++) {
5793                 if (!node_online(node))
5794                         continue;
5795                 nr_zones = build_zonerefs_node(NODE_DATA(node), zonerefs);
5796                 zonerefs += nr_zones;
5797         }
5798
5799         zonerefs->zone = NULL;
5800         zonerefs->zone_idx = 0;
5801 }
5802
5803 #endif  /* CONFIG_NUMA */
5804
5805 /*
5806  * Boot pageset table. One per cpu which is going to be used for all
5807  * zones and all nodes. The parameters will be set in such a way
5808  * that an item put on a list will immediately be handed over to
5809  * the buddy list. This is safe since pageset manipulation is done
5810  * with interrupts disabled.
5811  *
5812  * The boot_pagesets must be kept even after bootup is complete for
5813  * unused processors and/or zones. They do play a role for bootstrapping
5814  * hotplugged processors.
5815  *
5816  * zoneinfo_show() and maybe other functions do
5817  * not check if the processor is online before following the pageset pointer.
5818  * Other parts of the kernel may not check if the zone is available.
5819  */
5820 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch);
5821 static DEFINE_PER_CPU(struct per_cpu_pageset, boot_pageset);
5822 static DEFINE_PER_CPU(struct per_cpu_nodestat, boot_nodestats);
5823
5824 static void __build_all_zonelists(void *data)
5825 {
5826         int nid;
5827         int __maybe_unused cpu;
5828         pg_data_t *self = data;
5829         static DEFINE_SPINLOCK(lock);
5830
5831         spin_lock(&lock);
5832
5833 #ifdef CONFIG_NUMA
5834         memset(node_load, 0, sizeof(node_load));
5835 #endif
5836
5837         /*
5838          * This node is hotadded and no memory is yet present.   So just
5839          * building zonelists is fine - no need to touch other nodes.
5840          */
5841         if (self && !node_online(self->node_id)) {
5842                 build_zonelists(self);
5843         } else {
5844                 for_each_online_node(nid) {
5845                         pg_data_t *pgdat = NODE_DATA(nid);
5846
5847                         build_zonelists(pgdat);
5848                 }
5849
5850 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
5851                 /*
5852                  * We now know the "local memory node" for each node--
5853                  * i.e., the node of the first zone in the generic zonelist.
5854                  * Set up numa_mem percpu variable for on-line cpus.  During
5855                  * boot, only the boot cpu should be on-line;  we'll init the
5856                  * secondary cpus' numa_mem as they come on-line.  During
5857                  * node/memory hotplug, we'll fixup all on-line cpus.
5858                  */
5859                 for_each_online_cpu(cpu)
5860                         set_cpu_numa_mem(cpu, local_memory_node(cpu_to_node(cpu)));
5861 #endif
5862         }
5863
5864         spin_unlock(&lock);
5865 }
5866
5867 static noinline void __init
5868 build_all_zonelists_init(void)
5869 {
5870         int cpu;
5871
5872         __build_all_zonelists(NULL);
5873
5874         /*
5875          * Initialize the boot_pagesets that are going to be used
5876          * for bootstrapping processors. The real pagesets for
5877          * each zone will be allocated later when the per cpu
5878          * allocator is available.
5879          *
5880          * boot_pagesets are used also for bootstrapping offline
5881          * cpus if the system is already booted because the pagesets
5882          * are needed to initialize allocators on a specific cpu too.
5883          * F.e. the percpu allocator needs the page allocator which
5884          * needs the percpu allocator in order to allocate its pagesets
5885          * (a chicken-egg dilemma).
5886          */
5887         for_each_possible_cpu(cpu)
5888                 setup_pageset(&per_cpu(boot_pageset, cpu), 0);
5889
5890         mminit_verify_zonelist();
5891         cpuset_init_current_mems_allowed();
5892 }
5893
5894 /*
5895  * unless system_state == SYSTEM_BOOTING.
5896  *
5897  * __ref due to call of __init annotated helper build_all_zonelists_init
5898  * [protected by SYSTEM_BOOTING].
5899  */
5900 void __ref build_all_zonelists(pg_data_t *pgdat)
5901 {
5902         unsigned long vm_total_pages;
5903
5904         if (system_state == SYSTEM_BOOTING) {
5905                 build_all_zonelists_init();
5906         } else {
5907                 __build_all_zonelists(pgdat);
5908                 /* cpuset refresh routine should be here */
5909         }
5910         /* Get the number of free pages beyond high watermark in all zones. */
5911         vm_total_pages = nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE));
5912         /*
5913          * Disable grouping by mobility if the number of pages in the
5914          * system is too low to allow the mechanism to work. It would be
5915          * more accurate, but expensive to check per-zone. This check is
5916          * made on memory-hotadd so a system can start with mobility
5917          * disabled and enable it later
5918          */
5919         if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES))
5920                 page_group_by_mobility_disabled = 1;
5921         else
5922                 page_group_by_mobility_disabled = 0;
5923
5924         pr_info("Built %u zonelists, mobility grouping %s.  Total pages: %ld\n",
5925                 nr_online_nodes,
5926                 page_group_by_mobility_disabled ? "off" : "on",
5927                 vm_total_pages);
5928 #ifdef CONFIG_NUMA
5929         pr_info("Policy zone: %s\n", zone_names[policy_zone]);
5930 #endif
5931 }
5932
5933 /* If zone is ZONE_MOVABLE but memory is mirrored, it is an overlapped init */
5934 static bool __meminit
5935 overlap_memmap_init(unsigned long zone, unsigned long *pfn)
5936 {
5937         static struct memblock_region *r;
5938
5939         if (mirrored_kernelcore && zone == ZONE_MOVABLE) {
5940                 if (!r || *pfn >= memblock_region_memory_end_pfn(r)) {
5941                         for_each_memblock(memory, r) {
5942                                 if (*pfn < memblock_region_memory_end_pfn(r))
5943                                         break;
5944                         }
5945                 }
5946                 if (*pfn >= memblock_region_memory_base_pfn(r) &&
5947                     memblock_is_mirror(r)) {
5948                         *pfn = memblock_region_memory_end_pfn(r);
5949                         return true;
5950                 }
5951         }
5952         return false;
5953 }
5954
5955 /*
5956  * Initially all pages are reserved - free ones are freed
5957  * up by memblock_free_all() once the early boot process is
5958  * done. Non-atomic initialization, single-pass.
5959  */
5960 void __meminit memmap_init_zone(unsigned long size, int nid, unsigned long zone,
5961                 unsigned long start_pfn, enum memmap_context context,
5962                 struct vmem_altmap *altmap)
5963 {
5964         unsigned long pfn, end_pfn = start_pfn + size;
5965         struct page *page;
5966
5967         if (highest_memmap_pfn < end_pfn - 1)
5968                 highest_memmap_pfn = end_pfn - 1;
5969
5970 #ifdef CONFIG_ZONE_DEVICE
5971         /*
5972          * Honor reservation requested by the driver for this ZONE_DEVICE
5973          * memory. We limit the total number of pages to initialize to just
5974          * those that might contain the memory mapping. We will defer the
5975          * ZONE_DEVICE page initialization until after we have released
5976          * the hotplug lock.
5977          */
5978         if (zone == ZONE_DEVICE) {
5979                 if (!altmap)
5980                         return;
5981
5982                 if (start_pfn == altmap->base_pfn)
5983                         start_pfn += altmap->reserve;
5984                 end_pfn = altmap->base_pfn + vmem_altmap_offset(altmap);
5985         }
5986 #endif
5987
5988         for (pfn = start_pfn; pfn < end_pfn; ) {
5989                 /*
5990                  * There can be holes in boot-time mem_map[]s handed to this
5991                  * function.  They do not exist on hotplugged memory.
5992                  */
5993                 if (context == MEMMAP_EARLY) {
5994                         if (overlap_memmap_init(zone, &pfn))
5995                                 continue;
5996                         if (defer_init(nid, pfn, end_pfn))
5997                                 break;
5998                 }
5999
6000                 page = pfn_to_page(pfn);
6001                 __init_single_page(page, pfn, zone, nid);
6002                 if (context == MEMMAP_HOTPLUG)
6003                         __SetPageReserved(page);
6004
6005                 /*
6006                  * Mark the block movable so that blocks are reserved for
6007                  * movable at startup. This will force kernel allocations
6008                  * to reserve their blocks rather than leaking throughout
6009                  * the address space during boot when many long-lived
6010                  * kernel allocations are made.
6011                  *
6012                  * bitmap is created for zone's valid pfn range. but memmap
6013                  * can be created for invalid pages (for alignment)
6014                  * check here not to call set_pageblock_migratetype() against
6015                  * pfn out of zone.
6016                  */
6017                 if (!(pfn & (pageblock_nr_pages - 1))) {
6018                         set_pageblock_migratetype(page, MIGRATE_MOVABLE);
6019                         cond_resched();
6020                 }
6021                 pfn++;
6022         }
6023 }
6024
6025 #ifdef CONFIG_ZONE_DEVICE
6026 void __ref memmap_init_zone_device(struct zone *zone,
6027                                    unsigned long start_pfn,
6028                                    unsigned long nr_pages,
6029                                    struct dev_pagemap *pgmap)
6030 {
6031         unsigned long pfn, end_pfn = start_pfn + nr_pages;
6032         struct pglist_data *pgdat = zone->zone_pgdat;
6033         struct vmem_altmap *altmap = pgmap_altmap(pgmap);
6034         unsigned long zone_idx = zone_idx(zone);
6035         unsigned long start = jiffies;
6036         int nid = pgdat->node_id;
6037
6038         if (WARN_ON_ONCE(!pgmap || zone_idx(zone) != ZONE_DEVICE))
6039                 return;
6040
6041         /*
6042          * The call to memmap_init_zone should have already taken care
6043          * of the pages reserved for the memmap, so we can just jump to
6044          * the end of that region and start processing the device pages.
6045          */
6046         if (altmap) {
6047                 start_pfn = altmap->base_pfn + vmem_altmap_offset(altmap);
6048                 nr_pages = end_pfn - start_pfn;
6049         }
6050
6051         for (pfn = start_pfn; pfn < end_pfn; pfn++) {
6052                 struct page *page = pfn_to_page(pfn);
6053
6054                 __init_single_page(page, pfn, zone_idx, nid);
6055
6056                 /*
6057                  * Mark page reserved as it will need to wait for onlining
6058                  * phase for it to be fully associated with a zone.
6059                  *
6060                  * We can use the non-atomic __set_bit operation for setting
6061                  * the flag as we are still initializing the pages.
6062                  */
6063                 __SetPageReserved(page);
6064
6065                 /*
6066                  * ZONE_DEVICE pages union ->lru with a ->pgmap back pointer
6067                  * and zone_device_data.  It is a bug if a ZONE_DEVICE page is
6068                  * ever freed or placed on a driver-private list.
6069                  */
6070                 page->pgmap = pgmap;
6071                 page->zone_device_data = NULL;
6072
6073                 /*
6074                  * Mark the block movable so that blocks are reserved for
6075                  * movable at startup. This will force kernel allocations
6076                  * to reserve their blocks rather than leaking throughout
6077                  * the address space during boot when many long-lived
6078                  * kernel allocations are made.
6079                  *
6080                  * bitmap is created for zone's valid pfn range. but memmap
6081                  * can be created for invalid pages (for alignment)
6082                  * check here not to call set_pageblock_migratetype() against
6083                  * pfn out of zone.
6084                  *
6085                  * Please note that MEMMAP_HOTPLUG path doesn't clear memmap
6086                  * because this is done early in section_activate()
6087                  */
6088                 if (!(pfn & (pageblock_nr_pages - 1))) {
6089                         set_pageblock_migratetype(page, MIGRATE_MOVABLE);
6090                         cond_resched();
6091                 }
6092         }
6093
6094         pr_info("%s initialised %lu pages in %ums\n", __func__,
6095                 nr_pages, jiffies_to_msecs(jiffies - start));
6096 }
6097
6098 #endif
6099 static void __meminit zone_init_free_lists(struct zone *zone)
6100 {
6101         unsigned int order, t;
6102         for_each_migratetype_order(order, t) {
6103                 INIT_LIST_HEAD(&zone->free_area[order].free_list[t]);
6104                 zone->free_area[order].nr_free = 0;
6105         }
6106 }
6107
6108 void __meminit __weak memmap_init(unsigned long size, int nid,
6109                                   unsigned long zone,
6110                                   unsigned long range_start_pfn)
6111 {
6112         unsigned long start_pfn, end_pfn;
6113         unsigned long range_end_pfn = range_start_pfn + size;
6114         int i;
6115
6116         for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
6117                 start_pfn = clamp(start_pfn, range_start_pfn, range_end_pfn);
6118                 end_pfn = clamp(end_pfn, range_start_pfn, range_end_pfn);
6119
6120                 if (end_pfn > start_pfn) {
6121                         size = end_pfn - start_pfn;
6122                         memmap_init_zone(size, nid, zone, start_pfn,
6123                                          MEMMAP_EARLY, NULL);
6124                 }
6125         }
6126 }
6127
6128 static int zone_batchsize(struct zone *zone)
6129 {
6130 #ifdef CONFIG_MMU
6131         int batch;
6132
6133         /*
6134          * The per-cpu-pages pools are set to around 1000th of the
6135          * size of the zone.
6136          */
6137         batch = zone_managed_pages(zone) / 1024;
6138         /* But no more than a meg. */
6139         if (batch * PAGE_SIZE > 1024 * 1024)
6140                 batch = (1024 * 1024) / PAGE_SIZE;
6141         batch /= 4;             /* We effectively *= 4 below */
6142         if (batch < 1)
6143                 batch = 1;
6144
6145         /*
6146          * Clamp the batch to a 2^n - 1 value. Having a power
6147          * of 2 value was found to be more likely to have
6148          * suboptimal cache aliasing properties in some cases.
6149          *
6150          * For example if 2 tasks are alternately allocating
6151          * batches of pages, one task can end up with a lot
6152          * of pages of one half of the possible page colors
6153          * and the other with pages of the other colors.
6154          */
6155         batch = rounddown_pow_of_two(batch + batch/2) - 1;
6156
6157         return batch;
6158
6159 #else
6160         /* The deferral and batching of frees should be suppressed under NOMMU
6161          * conditions.
6162          *
6163          * The problem is that NOMMU needs to be able to allocate large chunks
6164          * of contiguous memory as there's no hardware page translation to
6165          * assemble apparent contiguous memory from discontiguous pages.
6166          *
6167          * Queueing large contiguous runs of pages for batching, however,
6168          * causes the pages to actually be freed in smaller chunks.  As there
6169          * can be a significant delay between the individual batches being
6170          * recycled, this leads to the once large chunks of space being
6171          * fragmented and becoming unavailable for high-order allocations.
6172          */
6173         return 0;
6174 #endif
6175 }
6176
6177 /*
6178  * pcp->high and pcp->batch values are related and dependent on one another:
6179  * ->batch must never be higher then ->high.
6180  * The following function updates them in a safe manner without read side
6181  * locking.
6182  *
6183  * Any new users of pcp->batch and pcp->high should ensure they can cope with
6184  * those fields changing asynchronously (acording the the above rule).
6185  *
6186  * mutex_is_locked(&pcp_batch_high_lock) required when calling this function
6187  * outside of boot time (or some other assurance that no concurrent updaters
6188  * exist).
6189  */
6190 static void pageset_update(struct per_cpu_pages *pcp, unsigned long high,
6191                 unsigned long batch)
6192 {
6193        /* start with a fail safe value for batch */
6194         pcp->batch = 1;
6195         smp_wmb();
6196
6197        /* Update high, then batch, in order */
6198         pcp->high = high;
6199         smp_wmb();
6200
6201         pcp->batch = batch;
6202 }
6203
6204 /* a companion to pageset_set_high() */
6205 static void pageset_set_batch(struct per_cpu_pageset *p, unsigned long batch)
6206 {
6207         pageset_update(&p->pcp, 6 * batch, max(1UL, 1 * batch));
6208 }
6209
6210 static void pageset_init(struct per_cpu_pageset *p)
6211 {
6212         struct per_cpu_pages *pcp;
6213         int migratetype;
6214
6215         memset(p, 0, sizeof(*p));
6216
6217         pcp = &p->pcp;
6218         for (migratetype = 0; migratetype < MIGRATE_PCPTYPES; migratetype++)
6219                 INIT_LIST_HEAD(&pcp->lists[migratetype]);
6220 }
6221
6222 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch)
6223 {
6224         pageset_init(p);
6225         pageset_set_batch(p, batch);
6226 }
6227
6228 /*
6229  * pageset_set_high() sets the high water mark for hot per_cpu_pagelist
6230  * to the value high for the pageset p.
6231  */
6232 static void pageset_set_high(struct per_cpu_pageset *p,
6233                                 unsigned long high)
6234 {
6235         unsigned long batch = max(1UL, high / 4);
6236         if ((high / 4) > (PAGE_SHIFT * 8))
6237                 batch = PAGE_SHIFT * 8;
6238
6239         pageset_update(&p->pcp, high, batch);
6240 }
6241
6242 static void pageset_set_high_and_batch(struct zone *zone,
6243                                        struct per_cpu_pageset *pcp)
6244 {
6245         if (percpu_pagelist_fraction)
6246                 pageset_set_high(pcp,
6247                         (zone_managed_pages(zone) /
6248                                 percpu_pagelist_fraction));
6249         else
6250                 pageset_set_batch(pcp, zone_batchsize(zone));
6251 }
6252
6253 static void __meminit zone_pageset_init(struct zone *zone, int cpu)
6254 {
6255         struct per_cpu_pageset *pcp = per_cpu_ptr(zone->pageset, cpu);
6256
6257         pageset_init(pcp);
6258         pageset_set_high_and_batch(zone, pcp);
6259 }
6260
6261 void __meminit setup_zone_pageset(struct zone *zone)
6262 {
6263         int cpu;
6264         zone->pageset = alloc_percpu(struct per_cpu_pageset);
6265         for_each_possible_cpu(cpu)
6266                 zone_pageset_init(zone, cpu);
6267 }
6268
6269 /*
6270  * Allocate per cpu pagesets and initialize them.
6271  * Before this call only boot pagesets were available.
6272  */
6273 void __init setup_per_cpu_pageset(void)
6274 {
6275         struct pglist_data *pgdat;
6276         struct zone *zone;
6277         int __maybe_unused cpu;
6278
6279         for_each_populated_zone(zone)
6280                 setup_zone_pageset(zone);
6281
6282 #ifdef CONFIG_NUMA
6283         /*
6284          * Unpopulated zones continue using the boot pagesets.
6285          * The numa stats for these pagesets need to be reset.
6286          * Otherwise, they will end up skewing the stats of
6287          * the nodes these zones are associated with.
6288          */
6289         for_each_possible_cpu(cpu) {
6290                 struct per_cpu_pageset *pcp = &per_cpu(boot_pageset, cpu);
6291                 memset(pcp->vm_numa_stat_diff, 0,
6292                        sizeof(pcp->vm_numa_stat_diff));
6293         }
6294 #endif
6295
6296         for_each_online_pgdat(pgdat)
6297                 pgdat->per_cpu_nodestats =
6298                         alloc_percpu(struct per_cpu_nodestat);
6299 }
6300
6301 static __meminit void zone_pcp_init(struct zone *zone)
6302 {
6303         /*
6304          * per cpu subsystem is not up at this point. The following code
6305          * relies on the ability of the linker to provide the
6306          * offset of a (static) per cpu variable into the per cpu area.
6307          */
6308         zone->pageset = &boot_pageset;
6309
6310         if (populated_zone(zone))
6311                 printk(KERN_DEBUG "  %s zone: %lu pages, LIFO batch:%u\n",
6312                         zone->name, zone->present_pages,
6313                                          zone_batchsize(zone));
6314 }
6315
6316 void __meminit init_currently_empty_zone(struct zone *zone,
6317                                         unsigned long zone_start_pfn,
6318                                         unsigned long size)
6319 {
6320         struct pglist_data *pgdat = zone->zone_pgdat;
6321         int zone_idx = zone_idx(zone) + 1;
6322
6323         if (zone_idx > pgdat->nr_zones)
6324                 pgdat->nr_zones = zone_idx;
6325
6326         zone->zone_start_pfn = zone_start_pfn;
6327
6328         mminit_dprintk(MMINIT_TRACE, "memmap_init",
6329                         "Initialising map node %d zone %lu pfns %lu -> %lu\n",
6330                         pgdat->node_id,
6331                         (unsigned long)zone_idx(zone),
6332                         zone_start_pfn, (zone_start_pfn + size));
6333
6334         zone_init_free_lists(zone);
6335         zone->initialized = 1;
6336 }
6337
6338 /**
6339  * get_pfn_range_for_nid - Return the start and end page frames for a node
6340  * @nid: The nid to return the range for. If MAX_NUMNODES, the min and max PFN are returned.
6341  * @start_pfn: Passed by reference. On return, it will have the node start_pfn.
6342  * @end_pfn: Passed by reference. On return, it will have the node end_pfn.
6343  *
6344  * It returns the start and end page frame of a node based on information
6345  * provided by memblock_set_node(). If called for a node
6346  * with no available memory, a warning is printed and the start and end
6347  * PFNs will be 0.
6348  */
6349 void __init get_pfn_range_for_nid(unsigned int nid,
6350                         unsigned long *start_pfn, unsigned long *end_pfn)
6351 {
6352         unsigned long this_start_pfn, this_end_pfn;
6353         int i;
6354
6355         *start_pfn = -1UL;
6356         *end_pfn = 0;
6357
6358         for_each_mem_pfn_range(i, nid, &this_start_pfn, &this_end_pfn, NULL) {
6359                 *start_pfn = min(*start_pfn, this_start_pfn);
6360                 *end_pfn = max(*end_pfn, this_end_pfn);
6361         }
6362
6363         if (*start_pfn == -1UL)
6364                 *start_pfn = 0;
6365 }
6366
6367 /*
6368  * This finds a zone that can be used for ZONE_MOVABLE pages. The
6369  * assumption is made that zones within a node are ordered in monotonic
6370  * increasing memory addresses so that the "highest" populated zone is used
6371  */
6372 static void __init find_usable_zone_for_movable(void)
6373 {
6374         int zone_index;
6375         for (zone_index = MAX_NR_ZONES - 1; zone_index >= 0; zone_index--) {
6376                 if (zone_index == ZONE_MOVABLE)
6377                         continue;
6378
6379                 if (arch_zone_highest_possible_pfn[zone_index] >
6380                                 arch_zone_lowest_possible_pfn[zone_index])
6381                         break;
6382         }
6383
6384         VM_BUG_ON(zone_index == -1);
6385         movable_zone = zone_index;
6386 }
6387
6388 /*
6389  * The zone ranges provided by the architecture do not include ZONE_MOVABLE
6390  * because it is sized independent of architecture. Unlike the other zones,
6391  * the starting point for ZONE_MOVABLE is not fixed. It may be different
6392  * in each node depending on the size of each node and how evenly kernelcore
6393  * is distributed. This helper function adjusts the zone ranges
6394  * provided by the architecture for a given node by using the end of the
6395  * highest usable zone for ZONE_MOVABLE. This preserves the assumption that
6396  * zones within a node are in order of monotonic increases memory addresses
6397  */
6398 static void __init adjust_zone_range_for_zone_movable(int nid,
6399                                         unsigned long zone_type,
6400                                         unsigned long node_start_pfn,
6401                                         unsigned long node_end_pfn,
6402                                         unsigned long *zone_start_pfn,
6403                                         unsigned long *zone_end_pfn)
6404 {
6405         /* Only adjust if ZONE_MOVABLE is on this node */
6406         if (zone_movable_pfn[nid]) {
6407                 /* Size ZONE_MOVABLE */
6408                 if (zone_type == ZONE_MOVABLE) {
6409                         *zone_start_pfn = zone_movable_pfn[nid];
6410                         *zone_end_pfn = min(node_end_pfn,
6411                                 arch_zone_highest_possible_pfn[movable_zone]);
6412
6413                 /* Adjust for ZONE_MOVABLE starting within this range */
6414                 } else if (!mirrored_kernelcore &&
6415                         *zone_start_pfn < zone_movable_pfn[nid] &&
6416                         *zone_end_pfn > zone_movable_pfn[nid]) {
6417                         *zone_end_pfn = zone_movable_pfn[nid];
6418
6419                 /* Check if this whole range is within ZONE_MOVABLE */
6420                 } else if (*zone_start_pfn >= zone_movable_pfn[nid])
6421                         *zone_start_pfn = *zone_end_pfn;
6422         }
6423 }
6424
6425 /*
6426  * Return the number of pages a zone spans in a node, including holes
6427  * present_pages = zone_spanned_pages_in_node() - zone_absent_pages_in_node()
6428  */
6429 static unsigned long __init zone_spanned_pages_in_node(int nid,
6430                                         unsigned long zone_type,
6431                                         unsigned long node_start_pfn,
6432                                         unsigned long node_end_pfn,
6433                                         unsigned long *zone_start_pfn,
6434                                         unsigned long *zone_end_pfn)
6435 {
6436         unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type];
6437         unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type];
6438         /* When hotadd a new node from cpu_up(), the node should be empty */
6439         if (!node_start_pfn && !node_end_pfn)
6440                 return 0;
6441
6442         /* Get the start and end of the zone */
6443         *zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high);
6444         *zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high);
6445         adjust_zone_range_for_zone_movable(nid, zone_type,
6446                                 node_start_pfn, node_end_pfn,
6447                                 zone_start_pfn, zone_end_pfn);
6448
6449         /* Check that this node has pages within the zone's required range */
6450         if (*zone_end_pfn < node_start_pfn || *zone_start_pfn > node_end_pfn)
6451                 return 0;
6452
6453         /* Move the zone boundaries inside the node if necessary */
6454         *zone_end_pfn = min(*zone_end_pfn, node_end_pfn);
6455         *zone_start_pfn = max(*zone_start_pfn, node_start_pfn);
6456
6457         /* Return the spanned pages */
6458         return *zone_end_pfn - *zone_start_pfn;
6459 }
6460
6461 /*
6462  * Return the number of holes in a range on a node. If nid is MAX_NUMNODES,
6463  * then all holes in the requested range will be accounted for.
6464  */
6465 unsigned long __init __absent_pages_in_range(int nid,
6466                                 unsigned long range_start_pfn,
6467                                 unsigned long range_end_pfn)
6468 {
6469         unsigned long nr_absent = range_end_pfn - range_start_pfn;
6470         unsigned long start_pfn, end_pfn;
6471         int i;
6472
6473         for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
6474                 start_pfn = clamp(start_pfn, range_start_pfn, range_end_pfn);
6475                 end_pfn = clamp(end_pfn, range_start_pfn, range_end_pfn);
6476                 nr_absent -= end_pfn - start_pfn;
6477         }
6478         return nr_absent;
6479 }
6480
6481 /**
6482  * absent_pages_in_range - Return number of page frames in holes within a range
6483  * @start_pfn: The start PFN to start searching for holes
6484  * @end_pfn: The end PFN to stop searching for holes
6485  *
6486  * Return: the number of pages frames in memory holes within a range.
6487  */
6488 unsigned long __init absent_pages_in_range(unsigned long start_pfn,
6489                                                         unsigned long end_pfn)
6490 {
6491         return __absent_pages_in_range(MAX_NUMNODES, start_pfn, end_pfn);
6492 }
6493
6494 /* Return the number of page frames in holes in a zone on a node */
6495 static unsigned long __init zone_absent_pages_in_node(int nid,
6496                                         unsigned long zone_type,
6497                                         unsigned long node_start_pfn,
6498                                         unsigned long node_end_pfn)
6499 {
6500         unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type];
6501         unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type];
6502         unsigned long zone_start_pfn, zone_end_pfn;
6503         unsigned long nr_absent;
6504
6505         /* When hotadd a new node from cpu_up(), the node should be empty */
6506         if (!node_start_pfn && !node_end_pfn)
6507                 return 0;
6508
6509         zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high);
6510         zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high);
6511
6512         adjust_zone_range_for_zone_movable(nid, zone_type,
6513                         node_start_pfn, node_end_pfn,
6514                         &zone_start_pfn, &zone_end_pfn);
6515         nr_absent = __absent_pages_in_range(nid, zone_start_pfn, zone_end_pfn);
6516
6517         /*
6518          * ZONE_MOVABLE handling.
6519          * Treat pages to be ZONE_MOVABLE in ZONE_NORMAL as absent pages
6520          * and vice versa.
6521          */
6522         if (mirrored_kernelcore && zone_movable_pfn[nid]) {
6523                 unsigned long start_pfn, end_pfn;
6524                 struct memblock_region *r;
6525
6526                 for_each_memblock(memory, r) {
6527                         start_pfn = clamp(memblock_region_memory_base_pfn(r),
6528                                           zone_start_pfn, zone_end_pfn);
6529                         end_pfn = clamp(memblock_region_memory_end_pfn(r),
6530                                         zone_start_pfn, zone_end_pfn);
6531
6532                         if (zone_type == ZONE_MOVABLE &&
6533                             memblock_is_mirror(r))
6534                                 nr_absent += end_pfn - start_pfn;
6535
6536                         if (zone_type == ZONE_NORMAL &&
6537                             !memblock_is_mirror(r))
6538                                 nr_absent += end_pfn - start_pfn;
6539                 }
6540         }
6541
6542         return nr_absent;
6543 }
6544
6545 static void __init calculate_node_totalpages(struct pglist_data *pgdat,
6546                                                 unsigned long node_start_pfn,
6547                                                 unsigned long node_end_pfn)
6548 {
6549         unsigned long realtotalpages = 0, totalpages = 0;
6550         enum zone_type i;
6551
6552         for (i = 0; i < MAX_NR_ZONES; i++) {
6553                 struct zone *zone = pgdat->node_zones + i;
6554                 unsigned long zone_start_pfn, zone_end_pfn;
6555                 unsigned long spanned, absent;
6556                 unsigned long size, real_size;
6557
6558                 spanned = zone_spanned_pages_in_node(pgdat->node_id, i,
6559                                                      node_start_pfn,
6560                                                      node_end_pfn,
6561                                                      &zone_start_pfn,
6562                                                      &zone_end_pfn);
6563                 absent = zone_absent_pages_in_node(pgdat->node_id, i,
6564                                                    node_start_pfn,
6565                                                    node_end_pfn);
6566
6567                 size = spanned;
6568                 real_size = size - absent;
6569
6570                 if (size)
6571                         zone->zone_start_pfn = zone_start_pfn;
6572                 else
6573                         zone->zone_start_pfn = 0;
6574                 zone->spanned_pages = size;
6575                 zone->present_pages = real_size;
6576
6577                 totalpages += size;
6578                 realtotalpages += real_size;
6579         }
6580
6581         pgdat->node_spanned_pages = totalpages;
6582         pgdat->node_present_pages = realtotalpages;
6583         printk(KERN_DEBUG "On node %d totalpages: %lu\n", pgdat->node_id,
6584                                                         realtotalpages);
6585 }
6586
6587 #ifndef CONFIG_SPARSEMEM
6588 /*
6589  * Calculate the size of the zone->blockflags rounded to an unsigned long
6590  * Start by making sure zonesize is a multiple of pageblock_order by rounding
6591  * up. Then use 1 NR_PAGEBLOCK_BITS worth of bits per pageblock, finally
6592  * round what is now in bits to nearest long in bits, then return it in
6593  * bytes.
6594  */
6595 static unsigned long __init usemap_size(unsigned long zone_start_pfn, unsigned long zonesize)
6596 {
6597         unsigned long usemapsize;
6598
6599         zonesize += zone_start_pfn & (pageblock_nr_pages-1);
6600         usemapsize = roundup(zonesize, pageblock_nr_pages);
6601         usemapsize = usemapsize >> pageblock_order;
6602         usemapsize *= NR_PAGEBLOCK_BITS;
6603         usemapsize = roundup(usemapsize, 8 * sizeof(unsigned long));
6604
6605         return usemapsize / 8;
6606 }
6607
6608 static void __ref setup_usemap(struct pglist_data *pgdat,
6609                                 struct zone *zone,
6610                                 unsigned long zone_start_pfn,
6611                                 unsigned long zonesize)
6612 {
6613         unsigned long usemapsize = usemap_size(zone_start_pfn, zonesize);
6614         zone->pageblock_flags = NULL;
6615         if (usemapsize) {
6616                 zone->pageblock_flags =
6617                         memblock_alloc_node(usemapsize, SMP_CACHE_BYTES,
6618                                             pgdat->node_id);
6619                 if (!zone->pageblock_flags)
6620                         panic("Failed to allocate %ld bytes for zone %s pageblock flags on node %d\n",
6621                               usemapsize, zone->name, pgdat->node_id);
6622         }
6623 }
6624 #else
6625 static inline void setup_usemap(struct pglist_data *pgdat, struct zone *zone,
6626                                 unsigned long zone_start_pfn, unsigned long zonesize) {}
6627 #endif /* CONFIG_SPARSEMEM */
6628
6629 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
6630
6631 /* Initialise the number of pages represented by NR_PAGEBLOCK_BITS */
6632 void __init set_pageblock_order(void)
6633 {
6634         unsigned int order;
6635
6636         /* Check that pageblock_nr_pages has not already been setup */
6637         if (pageblock_order)
6638                 return;
6639
6640         if (HPAGE_SHIFT > PAGE_SHIFT)
6641                 order = HUGETLB_PAGE_ORDER;
6642         else
6643                 order = MAX_ORDER - 1;
6644
6645         /*
6646          * Assume the largest contiguous order of interest is a huge page.
6647          * This value may be variable depending on boot parameters on IA64 and
6648          * powerpc.
6649          */
6650         pageblock_order = order;
6651 }
6652 #else /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
6653
6654 /*
6655  * When CONFIG_HUGETLB_PAGE_SIZE_VARIABLE is not set, set_pageblock_order()
6656  * is unused as pageblock_order is set at compile-time. See
6657  * include/linux/pageblock-flags.h for the values of pageblock_order based on
6658  * the kernel config
6659  */
6660 void __init set_pageblock_order(void)
6661 {
6662 }
6663
6664 #endif /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
6665
6666 static unsigned long __init calc_memmap_size(unsigned long spanned_pages,
6667                                                 unsigned long present_pages)
6668 {
6669         unsigned long pages = spanned_pages;
6670
6671         /*
6672          * Provide a more accurate estimation if there are holes within
6673          * the zone and SPARSEMEM is in use. If there are holes within the
6674          * zone, each populated memory region may cost us one or two extra
6675          * memmap pages due to alignment because memmap pages for each
6676          * populated regions may not be naturally aligned on page boundary.
6677          * So the (present_pages >> 4) heuristic is a tradeoff for that.
6678          */
6679         if (spanned_pages > present_pages + (present_pages >> 4) &&
6680             IS_ENABLED(CONFIG_SPARSEMEM))
6681                 pages = present_pages;
6682
6683         return PAGE_ALIGN(pages * sizeof(struct page)) >> PAGE_SHIFT;
6684 }
6685
6686 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
6687 static void pgdat_init_split_queue(struct pglist_data *pgdat)
6688 {
6689         struct deferred_split *ds_queue = &pgdat->deferred_split_queue;
6690
6691         spin_lock_init(&ds_queue->split_queue_lock);
6692         INIT_LIST_HEAD(&ds_queue->split_queue);
6693         ds_queue->split_queue_len = 0;
6694 }
6695 #else
6696 static void pgdat_init_split_queue(struct pglist_data *pgdat) {}
6697 #endif
6698
6699 #ifdef CONFIG_COMPACTION
6700 static void pgdat_init_kcompactd(struct pglist_data *pgdat)
6701 {
6702         init_waitqueue_head(&pgdat->kcompactd_wait);
6703 }
6704 #else
6705 static void pgdat_init_kcompactd(struct pglist_data *pgdat) {}
6706 #endif
6707
6708 static void __meminit pgdat_init_internals(struct pglist_data *pgdat)
6709 {
6710         pgdat_resize_init(pgdat);
6711
6712         pgdat_init_split_queue(pgdat);
6713         pgdat_init_kcompactd(pgdat);
6714
6715         init_waitqueue_head(&pgdat->kswapd_wait);
6716         init_waitqueue_head(&pgdat->pfmemalloc_wait);
6717
6718         pgdat_page_ext_init(pgdat);
6719         spin_lock_init(&pgdat->lru_lock);
6720         lruvec_init(&pgdat->__lruvec);
6721 }
6722
6723 static void __meminit zone_init_internals(struct zone *zone, enum zone_type idx, int nid,
6724                                                         unsigned long remaining_pages)
6725 {
6726         atomic_long_set(&zone->managed_pages, remaining_pages);
6727         zone_set_nid(zone, nid);
6728         zone->name = zone_names[idx];
6729         zone->zone_pgdat = NODE_DATA(nid);
6730         spin_lock_init(&zone->lock);
6731         zone_seqlock_init(zone);
6732         zone_pcp_init(zone);
6733 }
6734
6735 /*
6736  * Set up the zone data structures
6737  * - init pgdat internals
6738  * - init all zones belonging to this node
6739  *
6740  * NOTE: this function is only called during memory hotplug
6741  */
6742 #ifdef CONFIG_MEMORY_HOTPLUG
6743 void __ref free_area_init_core_hotplug(int nid)
6744 {
6745         enum zone_type z;
6746         pg_data_t *pgdat = NODE_DATA(nid);
6747
6748         pgdat_init_internals(pgdat);
6749         for (z = 0; z < MAX_NR_ZONES; z++)
6750                 zone_init_internals(&pgdat->node_zones[z], z, nid, 0);
6751 }
6752 #endif
6753
6754 /*
6755  * Set up the zone data structures:
6756  *   - mark all pages reserved
6757  *   - mark all memory queues empty
6758  *   - clear the memory bitmaps
6759  *
6760  * NOTE: pgdat should get zeroed by caller.
6761  * NOTE: this function is only called during early init.
6762  */
6763 static void __init free_area_init_core(struct pglist_data *pgdat)
6764 {
6765         enum zone_type j;
6766         int nid = pgdat->node_id;
6767
6768         pgdat_init_internals(pgdat);
6769         pgdat->per_cpu_nodestats = &boot_nodestats;
6770
6771         for (j = 0; j < MAX_NR_ZONES; j++) {
6772                 struct zone *zone = pgdat->node_zones + j;
6773                 unsigned long size, freesize, memmap_pages;
6774                 unsigned long zone_start_pfn = zone->zone_start_pfn;
6775
6776                 size = zone->spanned_pages;
6777                 freesize = zone->present_pages;
6778
6779                 /*
6780                  * Adjust freesize so that it accounts for how much memory
6781                  * is used by this zone for memmap. This affects the watermark
6782                  * and per-cpu initialisations
6783                  */
6784                 memmap_pages = calc_memmap_size(size, freesize);
6785                 if (!is_highmem_idx(j)) {
6786                         if (freesize >= memmap_pages) {
6787                                 freesize -= memmap_pages;
6788                                 if (memmap_pages)
6789                                         printk(KERN_DEBUG
6790                                                "  %s zone: %lu pages used for memmap\n",
6791                                                zone_names[j], memmap_pages);
6792                         } else
6793                                 pr_warn("  %s zone: %lu pages exceeds freesize %lu\n",
6794                                         zone_names[j], memmap_pages, freesize);
6795                 }
6796
6797                 /* Account for reserved pages */
6798                 if (j == 0 && freesize > dma_reserve) {
6799                         freesize -= dma_reserve;
6800                         printk(KERN_DEBUG "  %s zone: %lu pages reserved\n",
6801                                         zone_names[0], dma_reserve);
6802                 }
6803
6804                 if (!is_highmem_idx(j))
6805                         nr_kernel_pages += freesize;
6806                 /* Charge for highmem memmap if there are enough kernel pages */
6807                 else if (nr_kernel_pages > memmap_pages * 2)
6808                         nr_kernel_pages -= memmap_pages;
6809                 nr_all_pages += freesize;
6810
6811                 /*
6812                  * Set an approximate value for lowmem here, it will be adjusted
6813                  * when the bootmem allocator frees pages into the buddy system.
6814                  * And all highmem pages will be managed by the buddy system.
6815                  */
6816                 zone_init_internals(zone, j, nid, freesize);
6817
6818                 if (!size)
6819                         continue;
6820
6821                 set_pageblock_order();
6822                 setup_usemap(pgdat, zone, zone_start_pfn, size);
6823                 init_currently_empty_zone(zone, zone_start_pfn, size);
6824                 memmap_init(size, nid, j, zone_start_pfn);
6825         }
6826 }
6827
6828 #ifdef CONFIG_FLAT_NODE_MEM_MAP
6829 static void __ref alloc_node_mem_map(struct pglist_data *pgdat)
6830 {
6831         unsigned long __maybe_unused start = 0;
6832         unsigned long __maybe_unused offset = 0;
6833
6834         /* Skip empty nodes */
6835         if (!pgdat->node_spanned_pages)
6836                 return;
6837
6838         start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1);
6839         offset = pgdat->node_start_pfn - start;
6840         /* ia64 gets its own node_mem_map, before this, without bootmem */
6841         if (!pgdat->node_mem_map) {
6842                 unsigned long size, end;
6843                 struct page *map;
6844
6845                 /*
6846                  * The zone's endpoints aren't required to be MAX_ORDER
6847                  * aligned but the node_mem_map endpoints must be in order
6848                  * for the buddy allocator to function correctly.
6849                  */
6850                 end = pgdat_end_pfn(pgdat);
6851                 end = ALIGN(end, MAX_ORDER_NR_PAGES);
6852                 size =  (end - start) * sizeof(struct page);
6853                 map = memblock_alloc_node(size, SMP_CACHE_BYTES,
6854                                           pgdat->node_id);
6855                 if (!map)
6856                         panic("Failed to allocate %ld bytes for node %d memory map\n",
6857                               size, pgdat->node_id);
6858                 pgdat->node_mem_map = map + offset;
6859         }
6860         pr_debug("%s: node %d, pgdat %08lx, node_mem_map %08lx\n",
6861                                 __func__, pgdat->node_id, (unsigned long)pgdat,
6862                                 (unsigned long)pgdat->node_mem_map);
6863 #ifndef CONFIG_NEED_MULTIPLE_NODES
6864         /*
6865          * With no DISCONTIG, the global mem_map is just set as node 0's
6866          */
6867         if (pgdat == NODE_DATA(0)) {
6868                 mem_map = NODE_DATA(0)->node_mem_map;
6869                 if (page_to_pfn(mem_map) != pgdat->node_start_pfn)
6870                         mem_map -= offset;
6871         }
6872 #endif
6873 }
6874 #else
6875 static void __ref alloc_node_mem_map(struct pglist_data *pgdat) { }
6876 #endif /* CONFIG_FLAT_NODE_MEM_MAP */
6877
6878 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
6879 static inline void pgdat_set_deferred_range(pg_data_t *pgdat)
6880 {
6881         pgdat->first_deferred_pfn = ULONG_MAX;
6882 }
6883 #else
6884 static inline void pgdat_set_deferred_range(pg_data_t *pgdat) {}
6885 #endif
6886
6887 static void __init free_area_init_node(int nid)
6888 {
6889         pg_data_t *pgdat = NODE_DATA(nid);
6890         unsigned long start_pfn = 0;
6891         unsigned long end_pfn = 0;
6892
6893         /* pg_data_t should be reset to zero when it's allocated */
6894         WARN_ON(pgdat->nr_zones || pgdat->kswapd_highest_zoneidx);
6895
6896         get_pfn_range_for_nid(nid, &start_pfn, &end_pfn);
6897
6898         pgdat->node_id = nid;
6899         pgdat->node_start_pfn = start_pfn;
6900         pgdat->per_cpu_nodestats = NULL;
6901
6902         pr_info("Initmem setup node %d [mem %#018Lx-%#018Lx]\n", nid,
6903                 (u64)start_pfn << PAGE_SHIFT,
6904                 end_pfn ? ((u64)end_pfn << PAGE_SHIFT) - 1 : 0);
6905         calculate_node_totalpages(pgdat, start_pfn, end_pfn);
6906
6907         alloc_node_mem_map(pgdat);
6908         pgdat_set_deferred_range(pgdat);
6909
6910         free_area_init_core(pgdat);
6911 }
6912
6913 void __init free_area_init_memoryless_node(int nid)
6914 {
6915         free_area_init_node(nid);
6916 }
6917
6918 #if !defined(CONFIG_FLAT_NODE_MEM_MAP)
6919 /*
6920  * Initialize all valid struct pages in the range [spfn, epfn) and mark them
6921  * PageReserved(). Return the number of struct pages that were initialized.
6922  */
6923 static u64 __init init_unavailable_range(unsigned long spfn, unsigned long epfn)
6924 {
6925         unsigned long pfn;
6926         u64 pgcnt = 0;
6927
6928         for (pfn = spfn; pfn < epfn; pfn++) {
6929                 if (!pfn_valid(ALIGN_DOWN(pfn, pageblock_nr_pages))) {
6930                         pfn = ALIGN_DOWN(pfn, pageblock_nr_pages)
6931                                 + pageblock_nr_pages - 1;
6932                         continue;
6933                 }
6934                 /*
6935                  * Use a fake node/zone (0) for now. Some of these pages
6936                  * (in memblock.reserved but not in memblock.memory) will
6937                  * get re-initialized via reserve_bootmem_region() later.
6938                  */
6939                 __init_single_page(pfn_to_page(pfn), pfn, 0, 0);
6940                 __SetPageReserved(pfn_to_page(pfn));
6941                 pgcnt++;
6942         }
6943
6944         return pgcnt;
6945 }
6946
6947 /*
6948  * Only struct pages that are backed by physical memory are zeroed and
6949  * initialized by going through __init_single_page(). But, there are some
6950  * struct pages which are reserved in memblock allocator and their fields
6951  * may be accessed (for example page_to_pfn() on some configuration accesses
6952  * flags). We must explicitly initialize those struct pages.
6953  *
6954  * This function also addresses a similar issue where struct pages are left
6955  * uninitialized because the physical address range is not covered by
6956  * memblock.memory or memblock.reserved. That could happen when memblock
6957  * layout is manually configured via memmap=, or when the highest physical
6958  * address (max_pfn) does not end on a section boundary.
6959  */
6960 static void __init init_unavailable_mem(void)
6961 {
6962         phys_addr_t start, end;
6963         u64 i, pgcnt;
6964         phys_addr_t next = 0;
6965
6966         /*
6967          * Loop through unavailable ranges not covered by memblock.memory.
6968          */
6969         pgcnt = 0;
6970         for_each_mem_range(i, &memblock.memory, NULL,
6971                         NUMA_NO_NODE, MEMBLOCK_NONE, &start, &end, NULL) {
6972                 if (next < start)
6973                         pgcnt += init_unavailable_range(PFN_DOWN(next),
6974                                                         PFN_UP(start));
6975                 next = end;
6976         }
6977
6978         /*
6979          * Early sections always have a fully populated memmap for the whole
6980          * section - see pfn_valid(). If the last section has holes at the
6981          * end and that section is marked "online", the memmap will be
6982          * considered initialized. Make sure that memmap has a well defined
6983          * state.
6984          */
6985         pgcnt += init_unavailable_range(PFN_DOWN(next),
6986                                         round_up(max_pfn, PAGES_PER_SECTION));
6987
6988         /*
6989          * Struct pages that do not have backing memory. This could be because
6990          * firmware is using some of this memory, or for some other reasons.
6991          */
6992         if (pgcnt)
6993                 pr_info("Zeroed struct page in unavailable ranges: %lld pages", pgcnt);
6994 }
6995 #else
6996 static inline void __init init_unavailable_mem(void)
6997 {
6998 }
6999 #endif /* !CONFIG_FLAT_NODE_MEM_MAP */
7000
7001 #if MAX_NUMNODES > 1
7002 /*
7003  * Figure out the number of possible node ids.
7004  */
7005 void __init setup_nr_node_ids(void)
7006 {
7007         unsigned int highest;
7008
7009         highest = find_last_bit(node_possible_map.bits, MAX_NUMNODES);
7010         nr_node_ids = highest + 1;
7011 }
7012 #endif
7013
7014 /**
7015  * node_map_pfn_alignment - determine the maximum internode alignment
7016  *
7017  * This function should be called after node map is populated and sorted.
7018  * It calculates the maximum power of two alignment which can distinguish
7019  * all the nodes.
7020  *
7021  * For example, if all nodes are 1GiB and aligned to 1GiB, the return value
7022  * would indicate 1GiB alignment with (1 << (30 - PAGE_SHIFT)).  If the
7023  * nodes are shifted by 256MiB, 256MiB.  Note that if only the last node is
7024  * shifted, 1GiB is enough and this function will indicate so.
7025  *
7026  * This is used to test whether pfn -> nid mapping of the chosen memory
7027  * model has fine enough granularity to avoid incorrect mapping for the
7028  * populated node map.
7029  *
7030  * Return: the determined alignment in pfn's.  0 if there is no alignment
7031  * requirement (single node).
7032  */
7033 unsigned long __init node_map_pfn_alignment(void)
7034 {
7035         unsigned long accl_mask = 0, last_end = 0;
7036         unsigned long start, end, mask;
7037         int last_nid = NUMA_NO_NODE;
7038         int i, nid;
7039
7040         for_each_mem_pfn_range(i, MAX_NUMNODES, &start, &end, &nid) {
7041                 if (!start || last_nid < 0 || last_nid == nid) {
7042                         last_nid = nid;
7043                         last_end = end;
7044                         continue;
7045                 }
7046
7047                 /*
7048                  * Start with a mask granular enough to pin-point to the
7049                  * start pfn and tick off bits one-by-one until it becomes
7050                  * too coarse to separate the current node from the last.
7051                  */
7052                 mask = ~((1 << __ffs(start)) - 1);
7053                 while (mask && last_end <= (start & (mask << 1)))
7054                         mask <<= 1;
7055
7056                 /* accumulate all internode masks */
7057                 accl_mask |= mask;
7058         }
7059
7060         /* convert mask to number of pages */
7061         return ~accl_mask + 1;
7062 }
7063
7064 /**
7065  * find_min_pfn_with_active_regions - Find the minimum PFN registered
7066  *
7067  * Return: the minimum PFN based on information provided via
7068  * memblock_set_node().
7069  */
7070 unsigned long __init find_min_pfn_with_active_regions(void)
7071 {
7072         return PHYS_PFN(memblock_start_of_DRAM());
7073 }
7074
7075 /*
7076  * early_calculate_totalpages()
7077  * Sum pages in active regions for movable zone.
7078  * Populate N_MEMORY for calculating usable_nodes.
7079  */
7080 static unsigned long __init early_calculate_totalpages(void)
7081 {
7082         unsigned long totalpages = 0;
7083         unsigned long start_pfn, end_pfn;
7084         int i, nid;
7085
7086         for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
7087                 unsigned long pages = end_pfn - start_pfn;
7088
7089                 totalpages += pages;
7090                 if (pages)
7091                         node_set_state(nid, N_MEMORY);
7092         }
7093         return totalpages;
7094 }
7095
7096 /*
7097  * Find the PFN the Movable zone begins in each node. Kernel memory
7098  * is spread evenly between nodes as long as the nodes have enough
7099  * memory. When they don't, some nodes will have more kernelcore than
7100  * others
7101  */
7102 static void __init find_zone_movable_pfns_for_nodes(void)
7103 {
7104         int i, nid;
7105         unsigned long usable_startpfn;
7106         unsigned long kernelcore_node, kernelcore_remaining;
7107         /* save the state before borrow the nodemask */
7108         nodemask_t saved_node_state = node_states[N_MEMORY];
7109         unsigned long totalpages = early_calculate_totalpages();
7110         int usable_nodes = nodes_weight(node_states[N_MEMORY]);
7111         struct memblock_region *r;
7112
7113         /* Need to find movable_zone earlier when movable_node is specified. */
7114         find_usable_zone_for_movable();
7115
7116         /*
7117          * If movable_node is specified, ignore kernelcore and movablecore
7118          * options.
7119          */
7120         if (movable_node_is_enabled()) {
7121                 for_each_memblock(memory, r) {
7122                         if (!memblock_is_hotpluggable(r))
7123                                 continue;
7124
7125                         nid = memblock_get_region_node(r);
7126
7127                         usable_startpfn = PFN_DOWN(r->base);
7128                         zone_movable_pfn[nid] = zone_movable_pfn[nid] ?
7129                                 min(usable_startpfn, zone_movable_pfn[nid]) :
7130                                 usable_startpfn;
7131                 }
7132
7133                 goto out2;
7134         }
7135
7136         /*
7137          * If kernelcore=mirror is specified, ignore movablecore option
7138          */
7139         if (mirrored_kernelcore) {
7140                 bool mem_below_4gb_not_mirrored = false;
7141
7142                 for_each_memblock(memory, r) {
7143                         if (memblock_is_mirror(r))
7144                                 continue;
7145
7146                         nid = memblock_get_region_node(r);
7147
7148                         usable_startpfn = memblock_region_memory_base_pfn(r);
7149
7150                         if (usable_startpfn < 0x100000) {
7151                                 mem_below_4gb_not_mirrored = true;
7152                                 continue;
7153                         }
7154
7155                         zone_movable_pfn[nid] = zone_movable_pfn[nid] ?
7156                                 min(usable_startpfn, zone_movable_pfn[nid]) :
7157                                 usable_startpfn;
7158                 }
7159
7160                 if (mem_below_4gb_not_mirrored)
7161                         pr_warn("This configuration results in unmirrored kernel memory.\n");
7162
7163                 goto out2;
7164         }
7165
7166         /*
7167          * If kernelcore=nn% or movablecore=nn% was specified, calculate the
7168          * amount of necessary memory.
7169          */
7170         if (required_kernelcore_percent)
7171                 required_kernelcore = (totalpages * 100 * required_kernelcore_percent) /
7172                                        10000UL;
7173         if (required_movablecore_percent)
7174                 required_movablecore = (totalpages * 100 * required_movablecore_percent) /
7175                                         10000UL;
7176
7177         /*
7178          * If movablecore= was specified, calculate what size of
7179          * kernelcore that corresponds so that memory usable for
7180          * any allocation type is evenly spread. If both kernelcore
7181          * and movablecore are specified, then the value of kernelcore
7182          * will be used for required_kernelcore if it's greater than
7183          * what movablecore would have allowed.
7184          */
7185         if (required_movablecore) {
7186                 unsigned long corepages;
7187
7188                 /*
7189                  * Round-up so that ZONE_MOVABLE is at least as large as what
7190                  * was requested by the user
7191                  */
7192                 required_movablecore =
7193                         roundup(required_movablecore, MAX_ORDER_NR_PAGES);
7194                 required_movablecore = min(totalpages, required_movablecore);
7195                 corepages = totalpages - required_movablecore;
7196
7197                 required_kernelcore = max(required_kernelcore, corepages);
7198         }
7199
7200         /*
7201          * If kernelcore was not specified or kernelcore size is larger
7202          * than totalpages, there is no ZONE_MOVABLE.
7203          */
7204         if (!required_kernelcore || required_kernelcore >= totalpages)
7205                 goto out;
7206
7207         /* usable_startpfn is the lowest possible pfn ZONE_MOVABLE can be at */
7208         usable_startpfn = arch_zone_lowest_possible_pfn[movable_zone];
7209
7210 restart:
7211         /* Spread kernelcore memory as evenly as possible throughout nodes */
7212         kernelcore_node = required_kernelcore / usable_nodes;
7213         for_each_node_state(nid, N_MEMORY) {
7214                 unsigned long start_pfn, end_pfn;
7215
7216                 /*
7217                  * Recalculate kernelcore_node if the division per node
7218                  * now exceeds what is necessary to satisfy the requested
7219                  * amount of memory for the kernel
7220                  */
7221                 if (required_kernelcore < kernelcore_node)
7222                         kernelcore_node = required_kernelcore / usable_nodes;
7223
7224                 /*
7225                  * As the map is walked, we track how much memory is usable
7226                  * by the kernel using kernelcore_remaining. When it is
7227                  * 0, the rest of the node is usable by ZONE_MOVABLE
7228                  */
7229                 kernelcore_remaining = kernelcore_node;
7230
7231                 /* Go through each range of PFNs within this node */
7232                 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
7233                         unsigned long size_pages;
7234
7235                         start_pfn = max(start_pfn, zone_movable_pfn[nid]);
7236                         if (start_pfn >= end_pfn)
7237                                 continue;
7238
7239                         /* Account for what is only usable for kernelcore */
7240                         if (start_pfn < usable_startpfn) {
7241                                 unsigned long kernel_pages;
7242                                 kernel_pages = min(end_pfn, usable_startpfn)
7243                                                                 - start_pfn;
7244
7245                                 kernelcore_remaining -= min(kernel_pages,
7246                                                         kernelcore_remaining);
7247                                 required_kernelcore -= min(kernel_pages,
7248                                                         required_kernelcore);
7249
7250                                 /* Continue if range is now fully accounted */
7251                                 if (end_pfn <= usable_startpfn) {
7252
7253                                         /*
7254                                          * Push zone_movable_pfn to the end so
7255                                          * that if we have to rebalance
7256                                          * kernelcore across nodes, we will
7257                                          * not double account here
7258                                          */
7259                                         zone_movable_pfn[nid] = end_pfn;
7260                                         continue;
7261                                 }
7262                                 start_pfn = usable_startpfn;
7263                         }
7264
7265                         /*
7266                          * The usable PFN range for ZONE_MOVABLE is from
7267                          * start_pfn->end_pfn. Calculate size_pages as the
7268                          * number of pages used as kernelcore
7269                          */
7270                         size_pages = end_pfn - start_pfn;
7271                         if (size_pages > kernelcore_remaining)
7272                                 size_pages = kernelcore_remaining;
7273                         zone_movable_pfn[nid] = start_pfn + size_pages;
7274
7275                         /*
7276                          * Some kernelcore has been met, update counts and
7277                          * break if the kernelcore for this node has been
7278                          * satisfied
7279                          */
7280                         required_kernelcore -= min(required_kernelcore,
7281                                                                 size_pages);
7282                         kernelcore_remaining -= size_pages;
7283                         if (!kernelcore_remaining)
7284                                 break;
7285                 }
7286         }
7287
7288         /*
7289          * If there is still required_kernelcore, we do another pass with one
7290          * less node in the count. This will push zone_movable_pfn[nid] further
7291          * along on the nodes that still have memory until kernelcore is
7292          * satisfied
7293          */
7294         usable_nodes--;
7295         if (usable_nodes && required_kernelcore > usable_nodes)
7296                 goto restart;
7297
7298 out2:
7299         /* Align start of ZONE_MOVABLE on all nids to MAX_ORDER_NR_PAGES */
7300         for (nid = 0; nid < MAX_NUMNODES; nid++)
7301                 zone_movable_pfn[nid] =
7302                         roundup(zone_movable_pfn[nid], MAX_ORDER_NR_PAGES);
7303
7304 out:
7305         /* restore the node_state */
7306         node_states[N_MEMORY] = saved_node_state;
7307 }
7308
7309 /* Any regular or high memory on that node ? */
7310 static void check_for_memory(pg_data_t *pgdat, int nid)
7311 {
7312         enum zone_type zone_type;
7313
7314         for (zone_type = 0; zone_type <= ZONE_MOVABLE - 1; zone_type++) {
7315                 struct zone *zone = &pgdat->node_zones[zone_type];
7316                 if (populated_zone(zone)) {
7317                         if (IS_ENABLED(CONFIG_HIGHMEM))
7318                                 node_set_state(nid, N_HIGH_MEMORY);
7319                         if (zone_type <= ZONE_NORMAL)
7320                                 node_set_state(nid, N_NORMAL_MEMORY);
7321                         break;
7322                 }
7323         }
7324 }
7325
7326 /*
7327  * Some architecturs, e.g. ARC may have ZONE_HIGHMEM below ZONE_NORMAL. For
7328  * such cases we allow max_zone_pfn sorted in the descending order
7329  */
7330 bool __weak arch_has_descending_max_zone_pfns(void)
7331 {
7332         return false;
7333 }
7334
7335 /**
7336  * free_area_init - Initialise all pg_data_t and zone data
7337  * @max_zone_pfn: an array of max PFNs for each zone
7338  *
7339  * This will call free_area_init_node() for each active node in the system.
7340  * Using the page ranges provided by memblock_set_node(), the size of each
7341  * zone in each node and their holes is calculated. If the maximum PFN
7342  * between two adjacent zones match, it is assumed that the zone is empty.
7343  * For example, if arch_max_dma_pfn == arch_max_dma32_pfn, it is assumed
7344  * that arch_max_dma32_pfn has no pages. It is also assumed that a zone
7345  * starts where the previous one ended. For example, ZONE_DMA32 starts
7346  * at arch_max_dma_pfn.
7347  */
7348 void __init free_area_init(unsigned long *max_zone_pfn)
7349 {
7350         unsigned long start_pfn, end_pfn;
7351         int i, nid, zone;
7352         bool descending;
7353
7354         /* Record where the zone boundaries are */
7355         memset(arch_zone_lowest_possible_pfn, 0,
7356                                 sizeof(arch_zone_lowest_possible_pfn));
7357         memset(arch_zone_highest_possible_pfn, 0,
7358                                 sizeof(arch_zone_highest_possible_pfn));
7359
7360         start_pfn = find_min_pfn_with_active_regions();
7361         descending = arch_has_descending_max_zone_pfns();
7362
7363         for (i = 0; i < MAX_NR_ZONES; i++) {
7364                 if (descending)
7365                         zone = MAX_NR_ZONES - i - 1;
7366                 else
7367                         zone = i;
7368
7369                 if (zone == ZONE_MOVABLE)
7370                         continue;
7371
7372                 end_pfn = max(max_zone_pfn[zone], start_pfn);
7373                 arch_zone_lowest_possible_pfn[zone] = start_pfn;
7374                 arch_zone_highest_possible_pfn[zone] = end_pfn;
7375
7376                 start_pfn = end_pfn;
7377         }
7378
7379         /* Find the PFNs that ZONE_MOVABLE begins at in each node */
7380         memset(zone_movable_pfn, 0, sizeof(zone_movable_pfn));
7381         find_zone_movable_pfns_for_nodes();
7382
7383         /* Print out the zone ranges */
7384         pr_info("Zone ranges:\n");
7385         for (i = 0; i < MAX_NR_ZONES; i++) {
7386                 if (i == ZONE_MOVABLE)
7387                         continue;
7388                 pr_info("  %-8s ", zone_names[i]);
7389                 if (arch_zone_lowest_possible_pfn[i] ==
7390                                 arch_zone_highest_possible_pfn[i])
7391                         pr_cont("empty\n");
7392                 else
7393                         pr_cont("[mem %#018Lx-%#018Lx]\n",
7394                                 (u64)arch_zone_lowest_possible_pfn[i]
7395                                         << PAGE_SHIFT,
7396                                 ((u64)arch_zone_highest_possible_pfn[i]
7397                                         << PAGE_SHIFT) - 1);
7398         }
7399
7400         /* Print out the PFNs ZONE_MOVABLE begins at in each node */
7401         pr_info("Movable zone start for each node\n");
7402         for (i = 0; i < MAX_NUMNODES; i++) {
7403                 if (zone_movable_pfn[i])
7404                         pr_info("  Node %d: %#018Lx\n", i,
7405                                (u64)zone_movable_pfn[i] << PAGE_SHIFT);
7406         }
7407
7408         /*
7409          * Print out the early node map, and initialize the
7410          * subsection-map relative to active online memory ranges to
7411          * enable future "sub-section" extensions of the memory map.
7412          */
7413         pr_info("Early memory node ranges\n");
7414         for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
7415                 pr_info("  node %3d: [mem %#018Lx-%#018Lx]\n", nid,
7416                         (u64)start_pfn << PAGE_SHIFT,
7417                         ((u64)end_pfn << PAGE_SHIFT) - 1);
7418                 subsection_map_init(start_pfn, end_pfn - start_pfn);
7419         }
7420
7421         /* Initialise every node */
7422         mminit_verify_pageflags_layout();
7423         setup_nr_node_ids();
7424         init_unavailable_mem();
7425         for_each_online_node(nid) {
7426                 pg_data_t *pgdat = NODE_DATA(nid);
7427                 free_area_init_node(nid);
7428
7429                 /* Any memory on that node */
7430                 if (pgdat->node_present_pages)
7431                         node_set_state(nid, N_MEMORY);
7432                 check_for_memory(pgdat, nid);
7433         }
7434 }
7435
7436 static int __init cmdline_parse_core(char *p, unsigned long *core,
7437                                      unsigned long *percent)
7438 {
7439         unsigned long long coremem;
7440         char *endptr;
7441
7442         if (!p)
7443                 return -EINVAL;
7444
7445         /* Value may be a percentage of total memory, otherwise bytes */
7446         coremem = simple_strtoull(p, &endptr, 0);
7447         if (*endptr == '%') {
7448                 /* Paranoid check for percent values greater than 100 */
7449                 WARN_ON(coremem > 100);
7450
7451                 *percent = coremem;
7452         } else {
7453                 coremem = memparse(p, &p);
7454                 /* Paranoid check that UL is enough for the coremem value */
7455                 WARN_ON((coremem >> PAGE_SHIFT) > ULONG_MAX);
7456
7457                 *core = coremem >> PAGE_SHIFT;
7458                 *percent = 0UL;
7459         }
7460         return 0;
7461 }
7462
7463 /*
7464  * kernelcore=size sets the amount of memory for use for allocations that
7465  * cannot be reclaimed or migrated.
7466  */
7467 static int __init cmdline_parse_kernelcore(char *p)
7468 {
7469         /* parse kernelcore=mirror */
7470         if (parse_option_str(p, "mirror")) {
7471                 mirrored_kernelcore = true;
7472                 return 0;
7473         }
7474
7475         return cmdline_parse_core(p, &required_kernelcore,
7476                                   &required_kernelcore_percent);
7477 }
7478
7479 /*
7480  * movablecore=size sets the amount of memory for use for allocations that
7481  * can be reclaimed or migrated.
7482  */
7483 static int __init cmdline_parse_movablecore(char *p)
7484 {
7485         return cmdline_parse_core(p, &required_movablecore,
7486                                   &required_movablecore_percent);
7487 }
7488
7489 early_param("kernelcore", cmdline_parse_kernelcore);
7490 early_param("movablecore", cmdline_parse_movablecore);
7491
7492 void adjust_managed_page_count(struct page *page, long count)
7493 {
7494         atomic_long_add(count, &page_zone(page)->managed_pages);
7495         totalram_pages_add(count);
7496 #ifdef CONFIG_HIGHMEM
7497         if (PageHighMem(page))
7498                 totalhigh_pages_add(count);
7499 #endif
7500 }
7501 EXPORT_SYMBOL(adjust_managed_page_count);
7502
7503 unsigned long free_reserved_area(void *start, void *end, int poison, const char *s)
7504 {
7505         void *pos;
7506         unsigned long pages = 0;
7507
7508         start = (void *)PAGE_ALIGN((unsigned long)start);
7509         end = (void *)((unsigned long)end & PAGE_MASK);
7510         for (pos = start; pos < end; pos += PAGE_SIZE, pages++) {
7511                 struct page *page = virt_to_page(pos);
7512                 void *direct_map_addr;
7513
7514                 /*
7515                  * 'direct_map_addr' might be different from 'pos'
7516                  * because some architectures' virt_to_page()
7517                  * work with aliases.  Getting the direct map
7518                  * address ensures that we get a _writeable_
7519                  * alias for the memset().
7520                  */
7521                 direct_map_addr = page_address(page);
7522                 if ((unsigned int)poison <= 0xFF)
7523                         memset(direct_map_addr, poison, PAGE_SIZE);
7524
7525                 free_reserved_page(page);
7526         }
7527
7528         if (pages && s)
7529                 pr_info("Freeing %s memory: %ldK\n",
7530                         s, pages << (PAGE_SHIFT - 10));
7531
7532         return pages;
7533 }
7534
7535 #ifdef  CONFIG_HIGHMEM
7536 void free_highmem_page(struct page *page)
7537 {
7538         __free_reserved_page(page);
7539         totalram_pages_inc();
7540         atomic_long_inc(&page_zone(page)->managed_pages);
7541         totalhigh_pages_inc();
7542 }
7543 #endif
7544
7545
7546 void __init mem_init_print_info(const char *str)
7547 {
7548         unsigned long physpages, codesize, datasize, rosize, bss_size;
7549         unsigned long init_code_size, init_data_size;
7550
7551         physpages = get_num_physpages();
7552         codesize = _etext - _stext;
7553         datasize = _edata - _sdata;
7554         rosize = __end_rodata - __start_rodata;
7555         bss_size = __bss_stop - __bss_start;
7556         init_data_size = __init_end - __init_begin;
7557         init_code_size = _einittext - _sinittext;
7558
7559         /*
7560          * Detect special cases and adjust section sizes accordingly:
7561          * 1) .init.* may be embedded into .data sections
7562          * 2) .init.text.* may be out of [__init_begin, __init_end],
7563          *    please refer to arch/tile/kernel/vmlinux.lds.S.
7564          * 3) .rodata.* may be embedded into .text or .data sections.
7565          */
7566 #define adj_init_size(start, end, size, pos, adj) \
7567         do { \
7568                 if (start <= pos && pos < end && size > adj) \
7569                         size -= adj; \
7570         } while (0)
7571
7572         adj_init_size(__init_begin, __init_end, init_data_size,
7573                      _sinittext, init_code_size);
7574         adj_init_size(_stext, _etext, codesize, _sinittext, init_code_size);
7575         adj_init_size(_sdata, _edata, datasize, __init_begin, init_data_size);
7576         adj_init_size(_stext, _etext, codesize, __start_rodata, rosize);
7577         adj_init_size(_sdata, _edata, datasize, __start_rodata, rosize);
7578
7579 #undef  adj_init_size
7580
7581         pr_info("Memory: %luK/%luK available (%luK kernel code, %luK rwdata, %luK rodata, %luK init, %luK bss, %luK reserved, %luK cma-reserved"
7582 #ifdef  CONFIG_HIGHMEM
7583                 ", %luK highmem"
7584 #endif
7585                 "%s%s)\n",
7586                 nr_free_pages() << (PAGE_SHIFT - 10),
7587                 physpages << (PAGE_SHIFT - 10),
7588                 codesize >> 10, datasize >> 10, rosize >> 10,
7589                 (init_data_size + init_code_size) >> 10, bss_size >> 10,
7590                 (physpages - totalram_pages() - totalcma_pages) << (PAGE_SHIFT - 10),
7591                 totalcma_pages << (PAGE_SHIFT - 10),
7592 #ifdef  CONFIG_HIGHMEM
7593                 totalhigh_pages() << (PAGE_SHIFT - 10),
7594 #endif
7595                 str ? ", " : "", str ? str : "");
7596 }
7597
7598 /**
7599  * set_dma_reserve - set the specified number of pages reserved in the first zone
7600  * @new_dma_reserve: The number of pages to mark reserved
7601  *
7602  * The per-cpu batchsize and zone watermarks are determined by managed_pages.
7603  * In the DMA zone, a significant percentage may be consumed by kernel image
7604  * and other unfreeable allocations which can skew the watermarks badly. This
7605  * function may optionally be used to account for unfreeable pages in the
7606  * first zone (e.g., ZONE_DMA). The effect will be lower watermarks and
7607  * smaller per-cpu batchsize.
7608  */
7609 void __init set_dma_reserve(unsigned long new_dma_reserve)
7610 {
7611         dma_reserve = new_dma_reserve;
7612 }
7613
7614 static int page_alloc_cpu_dead(unsigned int cpu)
7615 {
7616
7617         lru_add_drain_cpu(cpu);
7618         drain_pages(cpu);
7619
7620         /*
7621          * Spill the event counters of the dead processor
7622          * into the current processors event counters.
7623          * This artificially elevates the count of the current
7624          * processor.
7625          */
7626         vm_events_fold_cpu(cpu);
7627
7628         /*
7629          * Zero the differential counters of the dead processor
7630          * so that the vm statistics are consistent.
7631          *
7632          * This is only okay since the processor is dead and cannot
7633          * race with what we are doing.
7634          */
7635         cpu_vm_stats_fold(cpu);
7636         return 0;
7637 }
7638
7639 #ifdef CONFIG_NUMA
7640 int hashdist = HASHDIST_DEFAULT;
7641
7642 static int __init set_hashdist(char *str)
7643 {
7644         if (!str)
7645                 return 0;
7646         hashdist = simple_strtoul(str, &str, 0);
7647         return 1;
7648 }
7649 __setup("hashdist=", set_hashdist);
7650 #endif
7651
7652 void __init page_alloc_init(void)
7653 {
7654         int ret;
7655
7656 #ifdef CONFIG_NUMA
7657         if (num_node_state(N_MEMORY) == 1)
7658                 hashdist = 0;
7659 #endif
7660
7661         ret = cpuhp_setup_state_nocalls(CPUHP_PAGE_ALLOC_DEAD,
7662                                         "mm/page_alloc:dead", NULL,
7663                                         page_alloc_cpu_dead);
7664         WARN_ON(ret < 0);
7665 }
7666
7667 /*
7668  * calculate_totalreserve_pages - called when sysctl_lowmem_reserve_ratio
7669  *      or min_free_kbytes changes.
7670  */
7671 static void calculate_totalreserve_pages(void)
7672 {
7673         struct pglist_data *pgdat;
7674         unsigned long reserve_pages = 0;
7675         enum zone_type i, j;
7676
7677         for_each_online_pgdat(pgdat) {
7678
7679                 pgdat->totalreserve_pages = 0;
7680
7681                 for (i = 0; i < MAX_NR_ZONES; i++) {
7682                         struct zone *zone = pgdat->node_zones + i;
7683                         long max = 0;
7684                         unsigned long managed_pages = zone_managed_pages(zone);
7685
7686                         /* Find valid and maximum lowmem_reserve in the zone */
7687                         for (j = i; j < MAX_NR_ZONES; j++) {
7688                                 if (zone->lowmem_reserve[j] > max)
7689                                         max = zone->lowmem_reserve[j];
7690                         }
7691
7692                         /* we treat the high watermark as reserved pages. */
7693                         max += high_wmark_pages(zone);
7694
7695                         if (max > managed_pages)
7696                                 max = managed_pages;
7697
7698                         pgdat->totalreserve_pages += max;
7699
7700                         reserve_pages += max;
7701                 }
7702         }
7703         totalreserve_pages = reserve_pages;
7704 }
7705
7706 /*
7707  * setup_per_zone_lowmem_reserve - called whenever
7708  *      sysctl_lowmem_reserve_ratio changes.  Ensures that each zone
7709  *      has a correct pages reserved value, so an adequate number of
7710  *      pages are left in the zone after a successful __alloc_pages().
7711  */
7712 static void setup_per_zone_lowmem_reserve(void)
7713 {
7714         struct pglist_data *pgdat;
7715         enum zone_type j, idx;
7716
7717         for_each_online_pgdat(pgdat) {
7718                 for (j = 0; j < MAX_NR_ZONES; j++) {
7719                         struct zone *zone = pgdat->node_zones + j;
7720                         unsigned long managed_pages = zone_managed_pages(zone);
7721
7722                         zone->lowmem_reserve[j] = 0;
7723
7724                         idx = j;
7725                         while (idx) {
7726                                 struct zone *lower_zone;
7727
7728                                 idx--;
7729                                 lower_zone = pgdat->node_zones + idx;
7730
7731                                 if (!sysctl_lowmem_reserve_ratio[idx] ||
7732                                     !zone_managed_pages(lower_zone)) {
7733                                         lower_zone->lowmem_reserve[j] = 0;
7734                                         continue;
7735                                 } else {
7736                                         lower_zone->lowmem_reserve[j] =
7737                                                 managed_pages / sysctl_lowmem_reserve_ratio[idx];
7738                                 }
7739                                 managed_pages += zone_managed_pages(lower_zone);
7740                         }
7741                 }
7742         }
7743
7744         /* update totalreserve_pages */
7745         calculate_totalreserve_pages();
7746 }
7747
7748 static void __setup_per_zone_wmarks(void)
7749 {
7750         unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
7751         unsigned long lowmem_pages = 0;
7752         struct zone *zone;
7753         unsigned long flags;
7754
7755         /* Calculate total number of !ZONE_HIGHMEM pages */
7756         for_each_zone(zone) {
7757                 if (!is_highmem(zone))
7758                         lowmem_pages += zone_managed_pages(zone);
7759         }
7760
7761         for_each_zone(zone) {
7762                 u64 tmp;
7763
7764                 spin_lock_irqsave(&zone->lock, flags);
7765                 tmp = (u64)pages_min * zone_managed_pages(zone);
7766                 do_div(tmp, lowmem_pages);
7767                 if (is_highmem(zone)) {
7768                         /*
7769                          * __GFP_HIGH and PF_MEMALLOC allocations usually don't
7770                          * need highmem pages, so cap pages_min to a small
7771                          * value here.
7772                          *
7773                          * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN)
7774                          * deltas control async page reclaim, and so should
7775                          * not be capped for highmem.
7776                          */
7777                         unsigned long min_pages;
7778
7779                         min_pages = zone_managed_pages(zone) / 1024;
7780                         min_pages = clamp(min_pages, SWAP_CLUSTER_MAX, 128UL);
7781                         zone->_watermark[WMARK_MIN] = min_pages;
7782                 } else {
7783                         /*
7784                          * If it's a lowmem zone, reserve a number of pages
7785                          * proportionate to the zone's size.
7786                          */
7787                         zone->_watermark[WMARK_MIN] = tmp;
7788                 }
7789
7790                 /*
7791                  * Set the kswapd watermarks distance according to the
7792                  * scale factor in proportion to available memory, but
7793                  * ensure a minimum size on small systems.
7794                  */
7795                 tmp = max_t(u64, tmp >> 2,
7796                             mult_frac(zone_managed_pages(zone),
7797                                       watermark_scale_factor, 10000));
7798
7799                 zone->watermark_boost = 0;
7800                 zone->_watermark[WMARK_LOW]  = min_wmark_pages(zone) + tmp;
7801                 zone->_watermark[WMARK_HIGH] = min_wmark_pages(zone) + tmp * 2;
7802
7803                 spin_unlock_irqrestore(&zone->lock, flags);
7804         }
7805
7806         /* update totalreserve_pages */
7807         calculate_totalreserve_pages();
7808 }
7809
7810 /**
7811  * setup_per_zone_wmarks - called when min_free_kbytes changes
7812  * or when memory is hot-{added|removed}
7813  *
7814  * Ensures that the watermark[min,low,high] values for each zone are set
7815  * correctly with respect to min_free_kbytes.
7816  */
7817 void setup_per_zone_wmarks(void)
7818 {
7819         static DEFINE_SPINLOCK(lock);
7820
7821         spin_lock(&lock);
7822         __setup_per_zone_wmarks();
7823         spin_unlock(&lock);
7824 }
7825
7826 /*
7827  * Initialise min_free_kbytes.
7828  *
7829  * For small machines we want it small (128k min).  For large machines
7830  * we want it large (256MB max).  But it is not linear, because network
7831  * bandwidth does not increase linearly with machine size.  We use
7832  *
7833  *      min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
7834  *      min_free_kbytes = sqrt(lowmem_kbytes * 16)
7835  *
7836  * which yields
7837  *
7838  * 16MB:        512k
7839  * 32MB:        724k
7840  * 64MB:        1024k
7841  * 128MB:       1448k
7842  * 256MB:       2048k
7843  * 512MB:       2896k
7844  * 1024MB:      4096k
7845  * 2048MB:      5792k
7846  * 4096MB:      8192k
7847  * 8192MB:      11584k
7848  * 16384MB:     16384k
7849  */
7850 int __meminit init_per_zone_wmark_min(void)
7851 {
7852         unsigned long lowmem_kbytes;
7853         int new_min_free_kbytes;
7854
7855         lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
7856         new_min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
7857
7858         if (new_min_free_kbytes > user_min_free_kbytes) {
7859                 min_free_kbytes = new_min_free_kbytes;
7860                 if (min_free_kbytes < 128)
7861                         min_free_kbytes = 128;
7862                 if (min_free_kbytes > 262144)
7863                         min_free_kbytes = 262144;
7864         } else {
7865                 pr_warn("min_free_kbytes is not updated to %d because user defined value %d is preferred\n",
7866                                 new_min_free_kbytes, user_min_free_kbytes);
7867         }
7868         setup_per_zone_wmarks();
7869         refresh_zone_stat_thresholds();
7870         setup_per_zone_lowmem_reserve();
7871
7872 #ifdef CONFIG_NUMA
7873         setup_min_unmapped_ratio();
7874         setup_min_slab_ratio();
7875 #endif
7876
7877         return 0;
7878 }
7879 core_initcall(init_per_zone_wmark_min)
7880
7881 /*
7882  * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
7883  *      that we can call two helper functions whenever min_free_kbytes
7884  *      changes.
7885  */
7886 int min_free_kbytes_sysctl_handler(struct ctl_table *table, int write,
7887                 void *buffer, size_t *length, loff_t *ppos)
7888 {
7889         int rc;
7890
7891         rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
7892         if (rc)
7893                 return rc;
7894
7895         if (write) {
7896                 user_min_free_kbytes = min_free_kbytes;
7897                 setup_per_zone_wmarks();
7898         }
7899         return 0;
7900 }
7901
7902 int watermark_scale_factor_sysctl_handler(struct ctl_table *table, int write,
7903                 void *buffer, size_t *length, loff_t *ppos)
7904 {
7905         int rc;
7906
7907         rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
7908         if (rc)
7909                 return rc;
7910
7911         if (write)
7912                 setup_per_zone_wmarks();
7913
7914         return 0;
7915 }
7916
7917 #ifdef CONFIG_NUMA
7918 static void setup_min_unmapped_ratio(void)
7919 {
7920         pg_data_t *pgdat;
7921         struct zone *zone;
7922
7923         for_each_online_pgdat(pgdat)
7924                 pgdat->min_unmapped_pages = 0;
7925
7926         for_each_zone(zone)
7927                 zone->zone_pgdat->min_unmapped_pages += (zone_managed_pages(zone) *
7928                                                          sysctl_min_unmapped_ratio) / 100;
7929 }
7930
7931
7932 int sysctl_min_unmapped_ratio_sysctl_handler(struct ctl_table *table, int write,
7933                 void *buffer, size_t *length, loff_t *ppos)
7934 {
7935         int rc;
7936
7937         rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
7938         if (rc)
7939                 return rc;
7940
7941         setup_min_unmapped_ratio();
7942
7943         return 0;
7944 }
7945
7946 static void setup_min_slab_ratio(void)
7947 {
7948         pg_data_t *pgdat;
7949         struct zone *zone;
7950
7951         for_each_online_pgdat(pgdat)
7952                 pgdat->min_slab_pages = 0;
7953
7954         for_each_zone(zone)
7955                 zone->zone_pgdat->min_slab_pages += (zone_managed_pages(zone) *
7956                                                      sysctl_min_slab_ratio) / 100;
7957 }
7958
7959 int sysctl_min_slab_ratio_sysctl_handler(struct ctl_table *table, int write,
7960                 void *buffer, size_t *length, loff_t *ppos)
7961 {
7962         int rc;
7963
7964         rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
7965         if (rc)
7966                 return rc;
7967
7968         setup_min_slab_ratio();
7969
7970         return 0;
7971 }
7972 #endif
7973
7974 /*
7975  * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
7976  *      proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
7977  *      whenever sysctl_lowmem_reserve_ratio changes.
7978  *
7979  * The reserve ratio obviously has absolutely no relation with the
7980  * minimum watermarks. The lowmem reserve ratio can only make sense
7981  * if in function of the boot time zone sizes.
7982  */
7983 int lowmem_reserve_ratio_sysctl_handler(struct ctl_table *table, int write,
7984                 void *buffer, size_t *length, loff_t *ppos)
7985 {
7986         int i;
7987
7988         proc_dointvec_minmax(table, write, buffer, length, ppos);
7989
7990         for (i = 0; i < MAX_NR_ZONES; i++) {
7991                 if (sysctl_lowmem_reserve_ratio[i] < 1)
7992                         sysctl_lowmem_reserve_ratio[i] = 0;
7993         }
7994
7995         setup_per_zone_lowmem_reserve();
7996         return 0;
7997 }
7998
7999 static void __zone_pcp_update(struct zone *zone)
8000 {
8001         unsigned int cpu;
8002
8003         for_each_possible_cpu(cpu)
8004                 pageset_set_high_and_batch(zone,
8005                                 per_cpu_ptr(zone->pageset, cpu));
8006 }
8007
8008 /*
8009  * percpu_pagelist_fraction - changes the pcp->high for each zone on each
8010  * cpu.  It is the fraction of total pages in each zone that a hot per cpu
8011  * pagelist can have before it gets flushed back to buddy allocator.
8012  */
8013 int percpu_pagelist_fraction_sysctl_handler(struct ctl_table *table, int write,
8014                 void *buffer, size_t *length, loff_t *ppos)
8015 {
8016         struct zone *zone;
8017         int old_percpu_pagelist_fraction;
8018         int ret;
8019
8020         mutex_lock(&pcp_batch_high_lock);
8021         old_percpu_pagelist_fraction = percpu_pagelist_fraction;
8022
8023         ret = proc_dointvec_minmax(table, write, buffer, length, ppos);
8024         if (!write || ret < 0)
8025                 goto out;
8026
8027         /* Sanity checking to avoid pcp imbalance */
8028         if (percpu_pagelist_fraction &&
8029             percpu_pagelist_fraction < MIN_PERCPU_PAGELIST_FRACTION) {
8030                 percpu_pagelist_fraction = old_percpu_pagelist_fraction;
8031                 ret = -EINVAL;
8032                 goto out;
8033         }
8034
8035         /* No change? */
8036         if (percpu_pagelist_fraction == old_percpu_pagelist_fraction)
8037                 goto out;
8038
8039         for_each_populated_zone(zone)
8040                 __zone_pcp_update(zone);
8041 out:
8042         mutex_unlock(&pcp_batch_high_lock);
8043         return ret;
8044 }
8045
8046 #ifndef __HAVE_ARCH_RESERVED_KERNEL_PAGES
8047 /*
8048  * Returns the number of pages that arch has reserved but
8049  * is not known to alloc_large_system_hash().
8050  */
8051 static unsigned long __init arch_reserved_kernel_pages(void)
8052 {
8053         return 0;
8054 }
8055 #endif
8056
8057 /*
8058  * Adaptive scale is meant to reduce sizes of hash tables on large memory
8059  * machines. As memory size is increased the scale is also increased but at
8060  * slower pace.  Starting from ADAPT_SCALE_BASE (64G), every time memory
8061  * quadruples the scale is increased by one, which means the size of hash table
8062  * only doubles, instead of quadrupling as well.
8063  * Because 32-bit systems cannot have large physical memory, where this scaling
8064  * makes sense, it is disabled on such platforms.
8065  */
8066 #if __BITS_PER_LONG > 32
8067 #define ADAPT_SCALE_BASE        (64ul << 30)
8068 #define ADAPT_SCALE_SHIFT       2
8069 #define ADAPT_SCALE_NPAGES      (ADAPT_SCALE_BASE >> PAGE_SHIFT)
8070 #endif
8071
8072 /*
8073  * allocate a large system hash table from bootmem
8074  * - it is assumed that the hash table must contain an exact power-of-2
8075  *   quantity of entries
8076  * - limit is the number of hash buckets, not the total allocation size
8077  */
8078 void *__init alloc_large_system_hash(const char *tablename,
8079                                      unsigned long bucketsize,
8080                                      unsigned long numentries,
8081                                      int scale,
8082                                      int flags,
8083                                      unsigned int *_hash_shift,
8084                                      unsigned int *_hash_mask,
8085                                      unsigned long low_limit,
8086                                      unsigned long high_limit)
8087 {
8088         unsigned long long max = high_limit;
8089         unsigned long log2qty, size;
8090         void *table = NULL;
8091         gfp_t gfp_flags;
8092         bool virt;
8093
8094         /* allow the kernel cmdline to have a say */
8095         if (!numentries) {
8096                 /* round applicable memory size up to nearest megabyte */
8097                 numentries = nr_kernel_pages;
8098                 numentries -= arch_reserved_kernel_pages();
8099
8100                 /* It isn't necessary when PAGE_SIZE >= 1MB */
8101                 if (PAGE_SHIFT < 20)
8102                         numentries = round_up(numentries, (1<<20)/PAGE_SIZE);
8103
8104 #if __BITS_PER_LONG > 32
8105                 if (!high_limit) {
8106                         unsigned long adapt;
8107
8108                         for (adapt = ADAPT_SCALE_NPAGES; adapt < numentries;
8109                              adapt <<= ADAPT_SCALE_SHIFT)
8110                                 scale++;
8111                 }
8112 #endif
8113
8114                 /* limit to 1 bucket per 2^scale bytes of low memory */
8115                 if (scale > PAGE_SHIFT)
8116                         numentries >>= (scale - PAGE_SHIFT);
8117                 else
8118                         numentries <<= (PAGE_SHIFT - scale);
8119
8120                 /* Make sure we've got at least a 0-order allocation.. */
8121                 if (unlikely(flags & HASH_SMALL)) {
8122                         /* Makes no sense without HASH_EARLY */
8123                         WARN_ON(!(flags & HASH_EARLY));
8124                         if (!(numentries >> *_hash_shift)) {
8125                                 numentries = 1UL << *_hash_shift;
8126                                 BUG_ON(!numentries);
8127                         }
8128                 } else if (unlikely((numentries * bucketsize) < PAGE_SIZE))
8129                         numentries = PAGE_SIZE / bucketsize;
8130         }
8131         numentries = roundup_pow_of_two(numentries);
8132
8133         /* limit allocation size to 1/16 total memory by default */
8134         if (max == 0) {
8135                 max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
8136                 do_div(max, bucketsize);
8137         }
8138         max = min(max, 0x80000000ULL);
8139
8140         if (numentries < low_limit)
8141                 numentries = low_limit;
8142         if (numentries > max)
8143                 numentries = max;
8144
8145         log2qty = ilog2(numentries);
8146
8147         gfp_flags = (flags & HASH_ZERO) ? GFP_ATOMIC | __GFP_ZERO : GFP_ATOMIC;
8148         do {
8149                 virt = false;
8150                 size = bucketsize << log2qty;
8151                 if (flags & HASH_EARLY) {
8152                         if (flags & HASH_ZERO)
8153                                 table = memblock_alloc(size, SMP_CACHE_BYTES);
8154                         else
8155                                 table = memblock_alloc_raw(size,
8156                                                            SMP_CACHE_BYTES);
8157                 } else if (get_order(size) >= MAX_ORDER || hashdist) {
8158                         table = __vmalloc(size, gfp_flags);
8159                         virt = true;
8160                 } else {
8161                         /*
8162                          * If bucketsize is not a power-of-two, we may free
8163                          * some pages at the end of hash table which
8164                          * alloc_pages_exact() automatically does
8165                          */
8166                         table = alloc_pages_exact(size, gfp_flags);
8167                         kmemleak_alloc(table, size, 1, gfp_flags);
8168                 }
8169         } while (!table && size > PAGE_SIZE && --log2qty);
8170
8171         if (!table)
8172                 panic("Failed to allocate %s hash table\n", tablename);
8173
8174         pr_info("%s hash table entries: %ld (order: %d, %lu bytes, %s)\n",
8175                 tablename, 1UL << log2qty, ilog2(size) - PAGE_SHIFT, size,
8176                 virt ? "vmalloc" : "linear");
8177
8178         if (_hash_shift)
8179                 *_hash_shift = log2qty;
8180         if (_hash_mask)
8181                 *_hash_mask = (1 << log2qty) - 1;
8182
8183         return table;
8184 }
8185
8186 /*
8187  * This function checks whether pageblock includes unmovable pages or not.
8188  *
8189  * PageLRU check without isolation or lru_lock could race so that
8190  * MIGRATE_MOVABLE block might include unmovable pages. And __PageMovable
8191  * check without lock_page also may miss some movable non-lru pages at
8192  * race condition. So you can't expect this function should be exact.
8193  *
8194  * Returns a page without holding a reference. If the caller wants to
8195  * dereference that page (e.g., dumping), it has to make sure that that it
8196  * cannot get removed (e.g., via memory unplug) concurrently.
8197  *
8198  */
8199 struct page *has_unmovable_pages(struct zone *zone, struct page *page,
8200                                  int migratetype, int flags)
8201 {
8202         unsigned long iter = 0;
8203         unsigned long pfn = page_to_pfn(page);
8204
8205         /*
8206          * TODO we could make this much more efficient by not checking every
8207          * page in the range if we know all of them are in MOVABLE_ZONE and
8208          * that the movable zone guarantees that pages are migratable but
8209          * the later is not the case right now unfortunatelly. E.g. movablecore
8210          * can still lead to having bootmem allocations in zone_movable.
8211          */
8212
8213         if (is_migrate_cma_page(page)) {
8214                 /*
8215                  * CMA allocations (alloc_contig_range) really need to mark
8216                  * isolate CMA pageblocks even when they are not movable in fact
8217                  * so consider them movable here.
8218                  */
8219                 if (is_migrate_cma(migratetype))
8220                         return NULL;
8221
8222                 return page;
8223         }
8224
8225         for (; iter < pageblock_nr_pages; iter++) {
8226                 if (!pfn_valid_within(pfn + iter))
8227                         continue;
8228
8229                 page = pfn_to_page(pfn + iter);
8230
8231                 if (PageReserved(page))
8232                         return page;
8233
8234                 /*
8235                  * If the zone is movable and we have ruled out all reserved
8236                  * pages then it should be reasonably safe to assume the rest
8237                  * is movable.
8238                  */
8239                 if (zone_idx(zone) == ZONE_MOVABLE)
8240                         continue;
8241
8242                 /*
8243                  * Hugepages are not in LRU lists, but they're movable.
8244                  * THPs are on the LRU, but need to be counted as #small pages.
8245                  * We need not scan over tail pages because we don't
8246                  * handle each tail page individually in migration.
8247                  */
8248                 if (PageHuge(page) || PageTransCompound(page)) {
8249                         struct page *head = compound_head(page);
8250                         unsigned int skip_pages;
8251
8252                         if (PageHuge(page)) {
8253                                 if (!hugepage_migration_supported(page_hstate(head)))
8254                                         return page;
8255                         } else if (!PageLRU(head) && !__PageMovable(head)) {
8256                                 return page;
8257                         }
8258
8259                         skip_pages = compound_nr(head) - (page - head);
8260                         iter += skip_pages - 1;
8261                         continue;
8262                 }
8263
8264                 /*
8265                  * We can't use page_count without pin a page
8266                  * because another CPU can free compound page.
8267                  * This check already skips compound tails of THP
8268                  * because their page->_refcount is zero at all time.
8269                  */
8270                 if (!page_ref_count(page)) {
8271                         if (PageBuddy(page))
8272                                 iter += (1 << page_order(page)) - 1;
8273                         continue;
8274                 }
8275
8276                 /*
8277                  * The HWPoisoned page may be not in buddy system, and
8278                  * page_count() is not 0.
8279                  */
8280                 if ((flags & MEMORY_OFFLINE) && PageHWPoison(page))
8281                         continue;
8282
8283                 /*
8284                  * We treat all PageOffline() pages as movable when offlining
8285                  * to give drivers a chance to decrement their reference count
8286                  * in MEM_GOING_OFFLINE in order to indicate that these pages
8287                  * can be offlined as there are no direct references anymore.
8288                  * For actually unmovable PageOffline() where the driver does
8289                  * not support this, we will fail later when trying to actually
8290                  * move these pages that still have a reference count > 0.
8291                  * (false negatives in this function only)
8292                  */
8293                 if ((flags & MEMORY_OFFLINE) && PageOffline(page))
8294                         continue;
8295
8296                 if (__PageMovable(page) || PageLRU(page))
8297                         continue;
8298
8299                 /*
8300                  * If there are RECLAIMABLE pages, we need to check
8301                  * it.  But now, memory offline itself doesn't call
8302                  * shrink_node_slabs() and it still to be fixed.
8303                  */
8304                 /*
8305                  * If the page is not RAM, page_count()should be 0.
8306                  * we don't need more check. This is an _used_ not-movable page.
8307                  *
8308                  * The problematic thing here is PG_reserved pages. PG_reserved
8309                  * is set to both of a memory hole page and a _used_ kernel
8310                  * page at boot.
8311                  */
8312                 return page;
8313         }
8314         return NULL;
8315 }
8316
8317 #ifdef CONFIG_CONTIG_ALLOC
8318 static unsigned long pfn_max_align_down(unsigned long pfn)
8319 {
8320         return pfn & ~(max_t(unsigned long, MAX_ORDER_NR_PAGES,
8321                              pageblock_nr_pages) - 1);
8322 }
8323
8324 static unsigned long pfn_max_align_up(unsigned long pfn)
8325 {
8326         return ALIGN(pfn, max_t(unsigned long, MAX_ORDER_NR_PAGES,
8327                                 pageblock_nr_pages));
8328 }
8329
8330 /* [start, end) must belong to a single zone. */
8331 static int __alloc_contig_migrate_range(struct compact_control *cc,
8332                                         unsigned long start, unsigned long end)
8333 {
8334         /* This function is based on compact_zone() from compaction.c. */
8335         unsigned int nr_reclaimed;
8336         unsigned long pfn = start;
8337         unsigned int tries = 0;
8338         int ret = 0;
8339
8340         migrate_prep();
8341
8342         while (pfn < end || !list_empty(&cc->migratepages)) {
8343                 if (fatal_signal_pending(current)) {
8344                         ret = -EINTR;
8345                         break;
8346                 }
8347
8348                 if (list_empty(&cc->migratepages)) {
8349                         cc->nr_migratepages = 0;
8350                         pfn = isolate_migratepages_range(cc, pfn, end);
8351                         if (!pfn) {
8352                                 ret = -EINTR;
8353                                 break;
8354                         }
8355                         tries = 0;
8356                 } else if (++tries == 5) {
8357                         ret = ret < 0 ? ret : -EBUSY;
8358                         break;
8359                 }
8360
8361                 nr_reclaimed = reclaim_clean_pages_from_list(cc->zone,
8362                                                         &cc->migratepages);
8363                 cc->nr_migratepages -= nr_reclaimed;
8364
8365                 ret = migrate_pages(&cc->migratepages, alloc_migrate_target,
8366                                     NULL, 0, cc->mode, MR_CONTIG_RANGE);
8367         }
8368         if (ret < 0) {
8369                 putback_movable_pages(&cc->migratepages);
8370                 return ret;
8371         }
8372         return 0;
8373 }
8374
8375 /**
8376  * alloc_contig_range() -- tries to allocate given range of pages
8377  * @start:      start PFN to allocate
8378  * @end:        one-past-the-last PFN to allocate
8379  * @migratetype:        migratetype of the underlaying pageblocks (either
8380  *                      #MIGRATE_MOVABLE or #MIGRATE_CMA).  All pageblocks
8381  *                      in range must have the same migratetype and it must
8382  *                      be either of the two.
8383  * @gfp_mask:   GFP mask to use during compaction
8384  *
8385  * The PFN range does not have to be pageblock or MAX_ORDER_NR_PAGES
8386  * aligned.  The PFN range must belong to a single zone.
8387  *
8388  * The first thing this routine does is attempt to MIGRATE_ISOLATE all
8389  * pageblocks in the range.  Once isolated, the pageblocks should not
8390  * be modified by others.
8391  *
8392  * Return: zero on success or negative error code.  On success all
8393  * pages which PFN is in [start, end) are allocated for the caller and
8394  * need to be freed with free_contig_range().
8395  */
8396 int alloc_contig_range(unsigned long start, unsigned long end,
8397                        unsigned migratetype, gfp_t gfp_mask)
8398 {
8399         unsigned long outer_start, outer_end;
8400         unsigned int order;
8401         int ret = 0;
8402
8403         struct compact_control cc = {
8404                 .nr_migratepages = 0,
8405                 .order = -1,
8406                 .zone = page_zone(pfn_to_page(start)),
8407                 .mode = MIGRATE_SYNC,
8408                 .ignore_skip_hint = true,
8409                 .no_set_skip_hint = true,
8410                 .gfp_mask = current_gfp_context(gfp_mask),
8411                 .alloc_contig = true,
8412         };
8413         INIT_LIST_HEAD(&cc.migratepages);
8414
8415         /*
8416          * What we do here is we mark all pageblocks in range as
8417          * MIGRATE_ISOLATE.  Because pageblock and max order pages may
8418          * have different sizes, and due to the way page allocator
8419          * work, we align the range to biggest of the two pages so
8420          * that page allocator won't try to merge buddies from
8421          * different pageblocks and change MIGRATE_ISOLATE to some
8422          * other migration type.
8423          *
8424          * Once the pageblocks are marked as MIGRATE_ISOLATE, we
8425          * migrate the pages from an unaligned range (ie. pages that
8426          * we are interested in).  This will put all the pages in
8427          * range back to page allocator as MIGRATE_ISOLATE.
8428          *
8429          * When this is done, we take the pages in range from page
8430          * allocator removing them from the buddy system.  This way
8431          * page allocator will never consider using them.
8432          *
8433          * This lets us mark the pageblocks back as
8434          * MIGRATE_CMA/MIGRATE_MOVABLE so that free pages in the
8435          * aligned range but not in the unaligned, original range are
8436          * put back to page allocator so that buddy can use them.
8437          */
8438
8439         ret = start_isolate_page_range(pfn_max_align_down(start),
8440                                        pfn_max_align_up(end), migratetype, 0);
8441         if (ret < 0)
8442                 return ret;
8443
8444         /*
8445          * In case of -EBUSY, we'd like to know which page causes problem.
8446          * So, just fall through. test_pages_isolated() has a tracepoint
8447          * which will report the busy page.
8448          *
8449          * It is possible that busy pages could become available before
8450          * the call to test_pages_isolated, and the range will actually be
8451          * allocated.  So, if we fall through be sure to clear ret so that
8452          * -EBUSY is not accidentally used or returned to caller.
8453          */
8454         ret = __alloc_contig_migrate_range(&cc, start, end);
8455         if (ret && ret != -EBUSY)
8456                 goto done;
8457         ret =0;
8458
8459         /*
8460          * Pages from [start, end) are within a MAX_ORDER_NR_PAGES
8461          * aligned blocks that are marked as MIGRATE_ISOLATE.  What's
8462          * more, all pages in [start, end) are free in page allocator.
8463          * What we are going to do is to allocate all pages from
8464          * [start, end) (that is remove them from page allocator).
8465          *
8466          * The only problem is that pages at the beginning and at the
8467          * end of interesting range may be not aligned with pages that
8468          * page allocator holds, ie. they can be part of higher order
8469          * pages.  Because of this, we reserve the bigger range and
8470          * once this is done free the pages we are not interested in.
8471          *
8472          * We don't have to hold zone->lock here because the pages are
8473          * isolated thus they won't get removed from buddy.
8474          */
8475
8476         lru_add_drain_all();
8477
8478         order = 0;
8479         outer_start = start;
8480         while (!PageBuddy(pfn_to_page(outer_start))) {
8481                 if (++order >= MAX_ORDER) {
8482                         outer_start = start;
8483                         break;
8484                 }
8485                 outer_start &= ~0UL << order;
8486         }
8487
8488         if (outer_start != start) {
8489                 order = page_order(pfn_to_page(outer_start));
8490
8491                 /*
8492                  * outer_start page could be small order buddy page and
8493                  * it doesn't include start page. Adjust outer_start
8494                  * in this case to report failed page properly
8495                  * on tracepoint in test_pages_isolated()
8496                  */
8497                 if (outer_start + (1UL << order) <= start)
8498                         outer_start = start;
8499         }
8500
8501         /* Make sure the range is really isolated. */
8502         if (test_pages_isolated(outer_start, end, 0)) {
8503                 pr_info_ratelimited("%s: [%lx, %lx) PFNs busy\n",
8504                         __func__, outer_start, end);
8505                 ret = -EBUSY;
8506                 goto done;
8507         }
8508
8509         /* Grab isolated pages from freelists. */
8510         outer_end = isolate_freepages_range(&cc, outer_start, end);
8511         if (!outer_end) {
8512                 ret = -EBUSY;
8513                 goto done;
8514         }
8515
8516         /* Free head and tail (if any) */
8517         if (start != outer_start)
8518                 free_contig_range(outer_start, start - outer_start);
8519         if (end != outer_end)
8520                 free_contig_range(end, outer_end - end);
8521
8522 done:
8523         undo_isolate_page_range(pfn_max_align_down(start),
8524                                 pfn_max_align_up(end), migratetype);
8525         return ret;
8526 }
8527 EXPORT_SYMBOL(alloc_contig_range);
8528
8529 static int __alloc_contig_pages(unsigned long start_pfn,
8530                                 unsigned long nr_pages, gfp_t gfp_mask)
8531 {
8532         unsigned long end_pfn = start_pfn + nr_pages;
8533
8534         return alloc_contig_range(start_pfn, end_pfn, MIGRATE_MOVABLE,
8535                                   gfp_mask);
8536 }
8537
8538 static bool pfn_range_valid_contig(struct zone *z, unsigned long start_pfn,
8539                                    unsigned long nr_pages)
8540 {
8541         unsigned long i, end_pfn = start_pfn + nr_pages;
8542         struct page *page;
8543
8544         for (i = start_pfn; i < end_pfn; i++) {
8545                 page = pfn_to_online_page(i);
8546                 if (!page)
8547                         return false;
8548
8549                 if (page_zone(page) != z)
8550                         return false;
8551
8552                 if (PageReserved(page))
8553                         return false;
8554
8555                 if (page_count(page) > 0)
8556                         return false;
8557
8558                 if (PageHuge(page))
8559                         return false;
8560         }
8561         return true;
8562 }
8563
8564 static bool zone_spans_last_pfn(const struct zone *zone,
8565                                 unsigned long start_pfn, unsigned long nr_pages)
8566 {
8567         unsigned long last_pfn = start_pfn + nr_pages - 1;
8568
8569         return zone_spans_pfn(zone, last_pfn);
8570 }
8571
8572 /**
8573  * alloc_contig_pages() -- tries to find and allocate contiguous range of pages
8574  * @nr_pages:   Number of contiguous pages to allocate
8575  * @gfp_mask:   GFP mask to limit search and used during compaction
8576  * @nid:        Target node
8577  * @nodemask:   Mask for other possible nodes
8578  *
8579  * This routine is a wrapper around alloc_contig_range(). It scans over zones
8580  * on an applicable zonelist to find a contiguous pfn range which can then be
8581  * tried for allocation with alloc_contig_range(). This routine is intended
8582  * for allocation requests which can not be fulfilled with the buddy allocator.
8583  *
8584  * The allocated memory is always aligned to a page boundary. If nr_pages is a
8585  * power of two then the alignment is guaranteed to be to the given nr_pages
8586  * (e.g. 1GB request would be aligned to 1GB).
8587  *
8588  * Allocated pages can be freed with free_contig_range() or by manually calling
8589  * __free_page() on each allocated page.
8590  *
8591  * Return: pointer to contiguous pages on success, or NULL if not successful.
8592  */
8593 struct page *alloc_contig_pages(unsigned long nr_pages, gfp_t gfp_mask,
8594                                 int nid, nodemask_t *nodemask)
8595 {
8596         unsigned long ret, pfn, flags;
8597         struct zonelist *zonelist;
8598         struct zone *zone;
8599         struct zoneref *z;
8600
8601         zonelist = node_zonelist(nid, gfp_mask);
8602         for_each_zone_zonelist_nodemask(zone, z, zonelist,
8603                                         gfp_zone(gfp_mask), nodemask) {
8604                 spin_lock_irqsave(&zone->lock, flags);
8605
8606                 pfn = ALIGN(zone->zone_start_pfn, nr_pages);
8607                 while (zone_spans_last_pfn(zone, pfn, nr_pages)) {
8608                         if (pfn_range_valid_contig(zone, pfn, nr_pages)) {
8609                                 /*
8610                                  * We release the zone lock here because
8611                                  * alloc_contig_range() will also lock the zone
8612                                  * at some point. If there's an allocation
8613                                  * spinning on this lock, it may win the race
8614                                  * and cause alloc_contig_range() to fail...
8615                                  */
8616                                 spin_unlock_irqrestore(&zone->lock, flags);
8617                                 ret = __alloc_contig_pages(pfn, nr_pages,
8618                                                         gfp_mask);
8619                                 if (!ret)
8620                                         return pfn_to_page(pfn);
8621                                 spin_lock_irqsave(&zone->lock, flags);
8622                         }
8623                         pfn += nr_pages;
8624                 }
8625                 spin_unlock_irqrestore(&zone->lock, flags);
8626         }
8627         return NULL;
8628 }
8629 #endif /* CONFIG_CONTIG_ALLOC */
8630
8631 void free_contig_range(unsigned long pfn, unsigned int nr_pages)
8632 {
8633         unsigned int count = 0;
8634
8635         for (; nr_pages--; pfn++) {
8636                 struct page *page = pfn_to_page(pfn);
8637
8638                 count += page_count(page) != 1;
8639                 __free_page(page);
8640         }
8641         WARN(count != 0, "%d pages are still in use!\n", count);
8642 }
8643 EXPORT_SYMBOL(free_contig_range);
8644
8645 /*
8646  * The zone indicated has a new number of managed_pages; batch sizes and percpu
8647  * page high values need to be recalulated.
8648  */
8649 void __meminit zone_pcp_update(struct zone *zone)
8650 {
8651         mutex_lock(&pcp_batch_high_lock);
8652         __zone_pcp_update(zone);
8653         mutex_unlock(&pcp_batch_high_lock);
8654 }
8655
8656 void zone_pcp_reset(struct zone *zone)
8657 {
8658         unsigned long flags;
8659         int cpu;
8660         struct per_cpu_pageset *pset;
8661
8662         /* avoid races with drain_pages()  */
8663         local_irq_save(flags);
8664         if (zone->pageset != &boot_pageset) {
8665                 for_each_online_cpu(cpu) {
8666                         pset = per_cpu_ptr(zone->pageset, cpu);
8667                         drain_zonestat(zone, pset);
8668                 }
8669                 free_percpu(zone->pageset);
8670                 zone->pageset = &boot_pageset;
8671         }
8672         local_irq_restore(flags);
8673 }
8674
8675 #ifdef CONFIG_MEMORY_HOTREMOVE
8676 /*
8677  * All pages in the range must be in a single zone and isolated
8678  * before calling this.
8679  */
8680 unsigned long
8681 __offline_isolated_pages(unsigned long start_pfn, unsigned long end_pfn)
8682 {
8683         struct page *page;
8684         struct zone *zone;
8685         unsigned int order;
8686         unsigned long pfn;
8687         unsigned long flags;
8688         unsigned long offlined_pages = 0;
8689
8690         /* find the first valid pfn */
8691         for (pfn = start_pfn; pfn < end_pfn; pfn++)
8692                 if (pfn_valid(pfn))
8693                         break;
8694         if (pfn == end_pfn)
8695                 return offlined_pages;
8696
8697         offline_mem_sections(pfn, end_pfn);
8698         zone = page_zone(pfn_to_page(pfn));
8699         spin_lock_irqsave(&zone->lock, flags);
8700         pfn = start_pfn;
8701         while (pfn < end_pfn) {
8702                 if (!pfn_valid(pfn)) {
8703                         pfn++;
8704                         continue;
8705                 }
8706                 page = pfn_to_page(pfn);
8707                 /*
8708                  * The HWPoisoned page may be not in buddy system, and
8709                  * page_count() is not 0.
8710                  */
8711                 if (unlikely(!PageBuddy(page) && PageHWPoison(page))) {
8712                         pfn++;
8713                         offlined_pages++;
8714                         continue;
8715                 }
8716                 /*
8717                  * At this point all remaining PageOffline() pages have a
8718                  * reference count of 0 and can simply be skipped.
8719                  */
8720                 if (PageOffline(page)) {
8721                         BUG_ON(page_count(page));
8722                         BUG_ON(PageBuddy(page));
8723                         pfn++;
8724                         offlined_pages++;
8725                         continue;
8726                 }
8727
8728                 BUG_ON(page_count(page));
8729                 BUG_ON(!PageBuddy(page));
8730                 order = page_order(page);
8731                 offlined_pages += 1 << order;
8732                 del_page_from_free_list(page, zone, order);
8733                 pfn += (1 << order);
8734         }
8735         spin_unlock_irqrestore(&zone->lock, flags);
8736
8737         return offlined_pages;
8738 }
8739 #endif
8740
8741 bool is_free_buddy_page(struct page *page)
8742 {
8743         struct zone *zone = page_zone(page);
8744         unsigned long pfn = page_to_pfn(page);
8745         unsigned long flags;
8746         unsigned int order;
8747
8748         spin_lock_irqsave(&zone->lock, flags);
8749         for (order = 0; order < MAX_ORDER; order++) {
8750                 struct page *page_head = page - (pfn & ((1 << order) - 1));
8751
8752                 if (PageBuddy(page_head) && page_order(page_head) >= order)
8753                         break;
8754         }
8755         spin_unlock_irqrestore(&zone->lock, flags);
8756
8757         return order < MAX_ORDER;
8758 }
8759
8760 #ifdef CONFIG_MEMORY_FAILURE
8761 /*
8762  * Set PG_hwpoison flag if a given page is confirmed to be a free page.  This
8763  * test is performed under the zone lock to prevent a race against page
8764  * allocation.
8765  */
8766 bool set_hwpoison_free_buddy_page(struct page *page)
8767 {
8768         struct zone *zone = page_zone(page);
8769         unsigned long pfn = page_to_pfn(page);
8770         unsigned long flags;
8771         unsigned int order;
8772         bool hwpoisoned = false;
8773
8774         spin_lock_irqsave(&zone->lock, flags);
8775         for (order = 0; order < MAX_ORDER; order++) {
8776                 struct page *page_head = page - (pfn & ((1 << order) - 1));
8777
8778                 if (PageBuddy(page_head) && page_order(page_head) >= order) {
8779                         if (!TestSetPageHWPoison(page))
8780                                 hwpoisoned = true;
8781                         break;
8782                 }
8783         }
8784         spin_unlock_irqrestore(&zone->lock, flags);
8785
8786         return hwpoisoned;
8787 }
8788 #endif