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