mm/page_alloc: scale the number of pages that are batch freed
[linux-2.6-microblaze.git] / mm / page_alloc.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  linux/mm/page_alloc.c
4  *
5  *  Manages the free list, the system allocates free pages here.
6  *  Note that kmalloc() lives in slab.c
7  *
8  *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
9  *  Swap reorganised 29.12.95, Stephen Tweedie
10  *  Support of BIGMEM added by Gerhard Wichert, Siemens AG, July 1999
11  *  Reshaped it to be a zoned allocator, Ingo Molnar, Red Hat, 1999
12  *  Discontiguous memory support, Kanoj Sarcar, SGI, Nov 1999
13  *  Zone balancing, Kanoj Sarcar, SGI, Jan 2000
14  *  Per cpu hot/cold page lists, bulk allocation, Martin J. Bligh, Sept 2002
15  *          (lots of bits borrowed from Ingo Molnar & Andrew Morton)
16  */
17
18 #include <linux/stddef.h>
19 #include <linux/mm.h>
20 #include <linux/highmem.h>
21 #include <linux/swap.h>
22 #include <linux/interrupt.h>
23 #include <linux/pagemap.h>
24 #include <linux/jiffies.h>
25 #include <linux/memblock.h>
26 #include <linux/compiler.h>
27 #include <linux/kernel.h>
28 #include <linux/kasan.h>
29 #include <linux/module.h>
30 #include <linux/suspend.h>
31 #include <linux/pagevec.h>
32 #include <linux/blkdev.h>
33 #include <linux/slab.h>
34 #include <linux/ratelimit.h>
35 #include <linux/oom.h>
36 #include <linux/topology.h>
37 #include <linux/sysctl.h>
38 #include <linux/cpu.h>
39 #include <linux/cpuset.h>
40 #include <linux/memory_hotplug.h>
41 #include <linux/nodemask.h>
42 #include <linux/vmalloc.h>
43 #include <linux/vmstat.h>
44 #include <linux/mempolicy.h>
45 #include <linux/memremap.h>
46 #include <linux/stop_machine.h>
47 #include <linux/random.h>
48 #include <linux/sort.h>
49 #include <linux/pfn.h>
50 #include <linux/backing-dev.h>
51 #include <linux/fault-inject.h>
52 #include <linux/page-isolation.h>
53 #include <linux/debugobjects.h>
54 #include <linux/kmemleak.h>
55 #include <linux/compaction.h>
56 #include <trace/events/kmem.h>
57 #include <trace/events/oom.h>
58 #include <linux/prefetch.h>
59 #include <linux/mm_inline.h>
60 #include <linux/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 int nr_pcp_free(struct per_cpu_pages *pcp, int high, int batch)
3282 {
3283         int min_nr_free, max_nr_free;
3284
3285         /* Check for PCP disabled or boot pageset */
3286         if (unlikely(high < batch))
3287                 return 1;
3288
3289         /* Leave at least pcp->batch pages on the list */
3290         min_nr_free = batch;
3291         max_nr_free = high - batch;
3292
3293         /*
3294          * Double the number of pages freed each time there is subsequent
3295          * freeing of pages without any allocation.
3296          */
3297         batch <<= pcp->free_factor;
3298         if (batch < max_nr_free)
3299                 pcp->free_factor++;
3300         batch = clamp(batch, min_nr_free, max_nr_free);
3301
3302         return batch;
3303 }
3304
3305 static void free_unref_page_commit(struct page *page, unsigned long pfn,
3306                                    int migratetype)
3307 {
3308         struct zone *zone = page_zone(page);
3309         struct per_cpu_pages *pcp;
3310         int high;
3311
3312         __count_vm_event(PGFREE);
3313         pcp = this_cpu_ptr(zone->per_cpu_pageset);
3314         list_add(&page->lru, &pcp->lists[migratetype]);
3315         pcp->count++;
3316         high = READ_ONCE(pcp->high);
3317         if (pcp->count >= high) {
3318                 int batch = READ_ONCE(pcp->batch);
3319
3320                 free_pcppages_bulk(zone, nr_pcp_free(pcp, high, batch), pcp);
3321         }
3322 }
3323
3324 /*
3325  * Free a 0-order page
3326  */
3327 void free_unref_page(struct page *page)
3328 {
3329         unsigned long flags;
3330         unsigned long pfn = page_to_pfn(page);
3331         int migratetype;
3332
3333         if (!free_unref_page_prepare(page, pfn))
3334                 return;
3335
3336         /*
3337          * We only track unmovable, reclaimable and movable on pcp lists.
3338          * Place ISOLATE pages on the isolated list because they are being
3339          * offlined but treat HIGHATOMIC as movable pages so we can get those
3340          * areas back if necessary. Otherwise, we may have to free
3341          * excessively into the page allocator
3342          */
3343         migratetype = get_pcppage_migratetype(page);
3344         if (unlikely(migratetype >= MIGRATE_PCPTYPES)) {
3345                 if (unlikely(is_migrate_isolate(migratetype))) {
3346                         free_one_page(page_zone(page), page, pfn, 0, migratetype, FPI_NONE);
3347                         return;
3348                 }
3349                 migratetype = MIGRATE_MOVABLE;
3350         }
3351
3352         local_lock_irqsave(&pagesets.lock, flags);
3353         free_unref_page_commit(page, pfn, migratetype);
3354         local_unlock_irqrestore(&pagesets.lock, flags);
3355 }
3356
3357 /*
3358  * Free a list of 0-order pages
3359  */
3360 void free_unref_page_list(struct list_head *list)
3361 {
3362         struct page *page, *next;
3363         unsigned long flags, pfn;
3364         int batch_count = 0;
3365         int migratetype;
3366
3367         /* Prepare pages for freeing */
3368         list_for_each_entry_safe(page, next, list, lru) {
3369                 pfn = page_to_pfn(page);
3370                 if (!free_unref_page_prepare(page, pfn))
3371                         list_del(&page->lru);
3372
3373                 /*
3374                  * Free isolated pages directly to the allocator, see
3375                  * comment in free_unref_page.
3376                  */
3377                 migratetype = get_pcppage_migratetype(page);
3378                 if (unlikely(migratetype >= MIGRATE_PCPTYPES)) {
3379                         if (unlikely(is_migrate_isolate(migratetype))) {
3380                                 list_del(&page->lru);
3381                                 free_one_page(page_zone(page), page, pfn, 0,
3382                                                         migratetype, FPI_NONE);
3383                                 continue;
3384                         }
3385
3386                         /*
3387                          * Non-isolated types over MIGRATE_PCPTYPES get added
3388                          * to the MIGRATE_MOVABLE pcp list.
3389                          */
3390                         set_pcppage_migratetype(page, MIGRATE_MOVABLE);
3391                 }
3392
3393                 set_page_private(page, pfn);
3394         }
3395
3396         local_lock_irqsave(&pagesets.lock, flags);
3397         list_for_each_entry_safe(page, next, list, lru) {
3398                 pfn = page_private(page);
3399                 set_page_private(page, 0);
3400                 migratetype = get_pcppage_migratetype(page);
3401                 trace_mm_page_free_batched(page);
3402                 free_unref_page_commit(page, pfn, migratetype);
3403
3404                 /*
3405                  * Guard against excessive IRQ disabled times when we get
3406                  * a large list of pages to free.
3407                  */
3408                 if (++batch_count == SWAP_CLUSTER_MAX) {
3409                         local_unlock_irqrestore(&pagesets.lock, flags);
3410                         batch_count = 0;
3411                         local_lock_irqsave(&pagesets.lock, flags);
3412                 }
3413         }
3414         local_unlock_irqrestore(&pagesets.lock, flags);
3415 }
3416
3417 /*
3418  * split_page takes a non-compound higher-order page, and splits it into
3419  * n (1<<order) sub-pages: page[0..n]
3420  * Each sub-page must be freed individually.
3421  *
3422  * Note: this is probably too low level an operation for use in drivers.
3423  * Please consult with lkml before using this in your driver.
3424  */
3425 void split_page(struct page *page, unsigned int order)
3426 {
3427         int i;
3428
3429         VM_BUG_ON_PAGE(PageCompound(page), page);
3430         VM_BUG_ON_PAGE(!page_count(page), page);
3431
3432         for (i = 1; i < (1 << order); i++)
3433                 set_page_refcounted(page + i);
3434         split_page_owner(page, 1 << order);
3435         split_page_memcg(page, 1 << order);
3436 }
3437 EXPORT_SYMBOL_GPL(split_page);
3438
3439 int __isolate_free_page(struct page *page, unsigned int order)
3440 {
3441         unsigned long watermark;
3442         struct zone *zone;
3443         int mt;
3444
3445         BUG_ON(!PageBuddy(page));
3446
3447         zone = page_zone(page);
3448         mt = get_pageblock_migratetype(page);
3449
3450         if (!is_migrate_isolate(mt)) {
3451                 /*
3452                  * Obey watermarks as if the page was being allocated. We can
3453                  * emulate a high-order watermark check with a raised order-0
3454                  * watermark, because we already know our high-order page
3455                  * exists.
3456                  */
3457                 watermark = zone->_watermark[WMARK_MIN] + (1UL << order);
3458                 if (!zone_watermark_ok(zone, 0, watermark, 0, ALLOC_CMA))
3459                         return 0;
3460
3461                 __mod_zone_freepage_state(zone, -(1UL << order), mt);
3462         }
3463
3464         /* Remove page from free list */
3465
3466         del_page_from_free_list(page, zone, order);
3467
3468         /*
3469          * Set the pageblock if the isolated page is at least half of a
3470          * pageblock
3471          */
3472         if (order >= pageblock_order - 1) {
3473                 struct page *endpage = page + (1 << order) - 1;
3474                 for (; page < endpage; page += pageblock_nr_pages) {
3475                         int mt = get_pageblock_migratetype(page);
3476                         if (!is_migrate_isolate(mt) && !is_migrate_cma(mt)
3477                             && !is_migrate_highatomic(mt))
3478                                 set_pageblock_migratetype(page,
3479                                                           MIGRATE_MOVABLE);
3480                 }
3481         }
3482
3483
3484         return 1UL << order;
3485 }
3486
3487 /**
3488  * __putback_isolated_page - Return a now-isolated page back where we got it
3489  * @page: Page that was isolated
3490  * @order: Order of the isolated page
3491  * @mt: The page's pageblock's migratetype
3492  *
3493  * This function is meant to return a page pulled from the free lists via
3494  * __isolate_free_page back to the free lists they were pulled from.
3495  */
3496 void __putback_isolated_page(struct page *page, unsigned int order, int mt)
3497 {
3498         struct zone *zone = page_zone(page);
3499
3500         /* zone lock should be held when this function is called */
3501         lockdep_assert_held(&zone->lock);
3502
3503         /* Return isolated page to tail of freelist. */
3504         __free_one_page(page, page_to_pfn(page), zone, order, mt,
3505                         FPI_SKIP_REPORT_NOTIFY | FPI_TO_TAIL);
3506 }
3507
3508 /*
3509  * Update NUMA hit/miss statistics
3510  *
3511  * Must be called with interrupts disabled.
3512  */
3513 static inline void zone_statistics(struct zone *preferred_zone, struct zone *z,
3514                                    long nr_account)
3515 {
3516 #ifdef CONFIG_NUMA
3517         enum numa_stat_item local_stat = NUMA_LOCAL;
3518
3519         /* skip numa counters update if numa stats is disabled */
3520         if (!static_branch_likely(&vm_numa_stat_key))
3521                 return;
3522
3523         if (zone_to_nid(z) != numa_node_id())
3524                 local_stat = NUMA_OTHER;
3525
3526         if (zone_to_nid(z) == zone_to_nid(preferred_zone))
3527                 __count_numa_events(z, NUMA_HIT, nr_account);
3528         else {
3529                 __count_numa_events(z, NUMA_MISS, nr_account);
3530                 __count_numa_events(preferred_zone, NUMA_FOREIGN, nr_account);
3531         }
3532         __count_numa_events(z, local_stat, nr_account);
3533 #endif
3534 }
3535
3536 /* Remove page from the per-cpu list, caller must protect the list */
3537 static inline
3538 struct page *__rmqueue_pcplist(struct zone *zone, int migratetype,
3539                         unsigned int alloc_flags,
3540                         struct per_cpu_pages *pcp,
3541                         struct list_head *list)
3542 {
3543         struct page *page;
3544
3545         do {
3546                 if (list_empty(list)) {
3547                         pcp->count += rmqueue_bulk(zone, 0,
3548                                         READ_ONCE(pcp->batch), list,
3549                                         migratetype, alloc_flags);
3550                         if (unlikely(list_empty(list)))
3551                                 return NULL;
3552                 }
3553
3554                 page = list_first_entry(list, struct page, lru);
3555                 list_del(&page->lru);
3556                 pcp->count--;
3557         } while (check_new_pcp(page));
3558
3559         return page;
3560 }
3561
3562 /* Lock and remove page from the per-cpu list */
3563 static struct page *rmqueue_pcplist(struct zone *preferred_zone,
3564                         struct zone *zone, gfp_t gfp_flags,
3565                         int migratetype, unsigned int alloc_flags)
3566 {
3567         struct per_cpu_pages *pcp;
3568         struct list_head *list;
3569         struct page *page;
3570         unsigned long flags;
3571
3572         local_lock_irqsave(&pagesets.lock, flags);
3573
3574         /*
3575          * On allocation, reduce the number of pages that are batch freed.
3576          * See nr_pcp_free() where free_factor is increased for subsequent
3577          * frees.
3578          */
3579         pcp = this_cpu_ptr(zone->per_cpu_pageset);
3580         pcp->free_factor >>= 1;
3581         list = &pcp->lists[migratetype];
3582         page = __rmqueue_pcplist(zone,  migratetype, alloc_flags, pcp, list);
3583         local_unlock_irqrestore(&pagesets.lock, flags);
3584         if (page) {
3585                 __count_zid_vm_events(PGALLOC, page_zonenum(page), 1);
3586                 zone_statistics(preferred_zone, zone, 1);
3587         }
3588         return page;
3589 }
3590
3591 /*
3592  * Allocate a page from the given zone. Use pcplists for order-0 allocations.
3593  */
3594 static inline
3595 struct page *rmqueue(struct zone *preferred_zone,
3596                         struct zone *zone, unsigned int order,
3597                         gfp_t gfp_flags, unsigned int alloc_flags,
3598                         int migratetype)
3599 {
3600         unsigned long flags;
3601         struct page *page;
3602
3603         if (likely(order == 0)) {
3604                 /*
3605                  * MIGRATE_MOVABLE pcplist could have the pages on CMA area and
3606                  * we need to skip it when CMA area isn't allowed.
3607                  */
3608                 if (!IS_ENABLED(CONFIG_CMA) || alloc_flags & ALLOC_CMA ||
3609                                 migratetype != MIGRATE_MOVABLE) {
3610                         page = rmqueue_pcplist(preferred_zone, zone, gfp_flags,
3611                                         migratetype, alloc_flags);
3612                         goto out;
3613                 }
3614         }
3615
3616         /*
3617          * We most definitely don't want callers attempting to
3618          * allocate greater than order-1 page units with __GFP_NOFAIL.
3619          */
3620         WARN_ON_ONCE((gfp_flags & __GFP_NOFAIL) && (order > 1));
3621         spin_lock_irqsave(&zone->lock, flags);
3622
3623         do {
3624                 page = NULL;
3625                 /*
3626                  * order-0 request can reach here when the pcplist is skipped
3627                  * due to non-CMA allocation context. HIGHATOMIC area is
3628                  * reserved for high-order atomic allocation, so order-0
3629                  * request should skip it.
3630                  */
3631                 if (order > 0 && alloc_flags & ALLOC_HARDER) {
3632                         page = __rmqueue_smallest(zone, order, MIGRATE_HIGHATOMIC);
3633                         if (page)
3634                                 trace_mm_page_alloc_zone_locked(page, order, migratetype);
3635                 }
3636                 if (!page)
3637                         page = __rmqueue(zone, order, migratetype, alloc_flags);
3638         } while (page && check_new_pages(page, order));
3639         if (!page)
3640                 goto failed;
3641
3642         __mod_zone_freepage_state(zone, -(1 << order),
3643                                   get_pcppage_migratetype(page));
3644         spin_unlock_irqrestore(&zone->lock, flags);
3645
3646         __count_zid_vm_events(PGALLOC, page_zonenum(page), 1 << order);
3647         zone_statistics(preferred_zone, zone, 1);
3648
3649 out:
3650         /* Separate test+clear to avoid unnecessary atomics */
3651         if (test_bit(ZONE_BOOSTED_WATERMARK, &zone->flags)) {
3652                 clear_bit(ZONE_BOOSTED_WATERMARK, &zone->flags);
3653                 wakeup_kswapd(zone, 0, 0, zone_idx(zone));
3654         }
3655
3656         VM_BUG_ON_PAGE(page && bad_range(zone, page), page);
3657         return page;
3658
3659 failed:
3660         spin_unlock_irqrestore(&zone->lock, flags);
3661         return NULL;
3662 }
3663
3664 #ifdef CONFIG_FAIL_PAGE_ALLOC
3665
3666 static struct {
3667         struct fault_attr attr;
3668
3669         bool ignore_gfp_highmem;
3670         bool ignore_gfp_reclaim;
3671         u32 min_order;
3672 } fail_page_alloc = {
3673         .attr = FAULT_ATTR_INITIALIZER,
3674         .ignore_gfp_reclaim = true,
3675         .ignore_gfp_highmem = true,
3676         .min_order = 1,
3677 };
3678
3679 static int __init setup_fail_page_alloc(char *str)
3680 {
3681         return setup_fault_attr(&fail_page_alloc.attr, str);
3682 }
3683 __setup("fail_page_alloc=", setup_fail_page_alloc);
3684
3685 static bool __should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
3686 {
3687         if (order < fail_page_alloc.min_order)
3688                 return false;
3689         if (gfp_mask & __GFP_NOFAIL)
3690                 return false;
3691         if (fail_page_alloc.ignore_gfp_highmem && (gfp_mask & __GFP_HIGHMEM))
3692                 return false;
3693         if (fail_page_alloc.ignore_gfp_reclaim &&
3694                         (gfp_mask & __GFP_DIRECT_RECLAIM))
3695                 return false;
3696
3697         return should_fail(&fail_page_alloc.attr, 1 << order);
3698 }
3699
3700 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
3701
3702 static int __init fail_page_alloc_debugfs(void)
3703 {
3704         umode_t mode = S_IFREG | 0600;
3705         struct dentry *dir;
3706
3707         dir = fault_create_debugfs_attr("fail_page_alloc", NULL,
3708                                         &fail_page_alloc.attr);
3709
3710         debugfs_create_bool("ignore-gfp-wait", mode, dir,
3711                             &fail_page_alloc.ignore_gfp_reclaim);
3712         debugfs_create_bool("ignore-gfp-highmem", mode, dir,
3713                             &fail_page_alloc.ignore_gfp_highmem);
3714         debugfs_create_u32("min-order", mode, dir, &fail_page_alloc.min_order);
3715
3716         return 0;
3717 }
3718
3719 late_initcall(fail_page_alloc_debugfs);
3720
3721 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
3722
3723 #else /* CONFIG_FAIL_PAGE_ALLOC */
3724
3725 static inline bool __should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
3726 {
3727         return false;
3728 }
3729
3730 #endif /* CONFIG_FAIL_PAGE_ALLOC */
3731
3732 noinline bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
3733 {
3734         return __should_fail_alloc_page(gfp_mask, order);
3735 }
3736 ALLOW_ERROR_INJECTION(should_fail_alloc_page, TRUE);
3737
3738 static inline long __zone_watermark_unusable_free(struct zone *z,
3739                                 unsigned int order, unsigned int alloc_flags)
3740 {
3741         const bool alloc_harder = (alloc_flags & (ALLOC_HARDER|ALLOC_OOM));
3742         long unusable_free = (1 << order) - 1;
3743
3744         /*
3745          * If the caller does not have rights to ALLOC_HARDER then subtract
3746          * the high-atomic reserves. This will over-estimate the size of the
3747          * atomic reserve but it avoids a search.
3748          */
3749         if (likely(!alloc_harder))
3750                 unusable_free += z->nr_reserved_highatomic;
3751
3752 #ifdef CONFIG_CMA
3753         /* If allocation can't use CMA areas don't use free CMA pages */
3754         if (!(alloc_flags & ALLOC_CMA))
3755                 unusable_free += zone_page_state(z, NR_FREE_CMA_PAGES);
3756 #endif
3757
3758         return unusable_free;
3759 }
3760
3761 /*
3762  * Return true if free base pages are above 'mark'. For high-order checks it
3763  * will return true of the order-0 watermark is reached and there is at least
3764  * one free page of a suitable size. Checking now avoids taking the zone lock
3765  * to check in the allocation paths if no pages are free.
3766  */
3767 bool __zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
3768                          int highest_zoneidx, unsigned int alloc_flags,
3769                          long free_pages)
3770 {
3771         long min = mark;
3772         int o;
3773         const bool alloc_harder = (alloc_flags & (ALLOC_HARDER|ALLOC_OOM));
3774
3775         /* free_pages may go negative - that's OK */
3776         free_pages -= __zone_watermark_unusable_free(z, order, alloc_flags);
3777
3778         if (alloc_flags & ALLOC_HIGH)
3779                 min -= min / 2;
3780
3781         if (unlikely(alloc_harder)) {
3782                 /*
3783                  * OOM victims can try even harder than normal ALLOC_HARDER
3784                  * users on the grounds that it's definitely going to be in
3785                  * the exit path shortly and free memory. Any allocation it
3786                  * makes during the free path will be small and short-lived.
3787                  */
3788                 if (alloc_flags & ALLOC_OOM)
3789                         min -= min / 2;
3790                 else
3791                         min -= min / 4;
3792         }
3793
3794         /*
3795          * Check watermarks for an order-0 allocation request. If these
3796          * are not met, then a high-order request also cannot go ahead
3797          * even if a suitable page happened to be free.
3798          */
3799         if (free_pages <= min + z->lowmem_reserve[highest_zoneidx])
3800                 return false;
3801
3802         /* If this is an order-0 request then the watermark is fine */
3803         if (!order)
3804                 return true;
3805
3806         /* For a high-order request, check at least one suitable page is free */
3807         for (o = order; o < MAX_ORDER; o++) {
3808                 struct free_area *area = &z->free_area[o];
3809                 int mt;
3810
3811                 if (!area->nr_free)
3812                         continue;
3813
3814                 for (mt = 0; mt < MIGRATE_PCPTYPES; mt++) {
3815                         if (!free_area_empty(area, mt))
3816                                 return true;
3817                 }
3818
3819 #ifdef CONFIG_CMA
3820                 if ((alloc_flags & ALLOC_CMA) &&
3821                     !free_area_empty(area, MIGRATE_CMA)) {
3822                         return true;
3823                 }
3824 #endif
3825                 if (alloc_harder && !free_area_empty(area, MIGRATE_HIGHATOMIC))
3826                         return true;
3827         }
3828         return false;
3829 }
3830
3831 bool zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
3832                       int highest_zoneidx, unsigned int alloc_flags)
3833 {
3834         return __zone_watermark_ok(z, order, mark, highest_zoneidx, alloc_flags,
3835                                         zone_page_state(z, NR_FREE_PAGES));
3836 }
3837
3838 static inline bool zone_watermark_fast(struct zone *z, unsigned int order,
3839                                 unsigned long mark, int highest_zoneidx,
3840                                 unsigned int alloc_flags, gfp_t gfp_mask)
3841 {
3842         long free_pages;
3843
3844         free_pages = zone_page_state(z, NR_FREE_PAGES);
3845
3846         /*
3847          * Fast check for order-0 only. If this fails then the reserves
3848          * need to be calculated.
3849          */
3850         if (!order) {
3851                 long fast_free;
3852
3853                 fast_free = free_pages;
3854                 fast_free -= __zone_watermark_unusable_free(z, 0, alloc_flags);
3855                 if (fast_free > mark + z->lowmem_reserve[highest_zoneidx])
3856                         return true;
3857         }
3858
3859         if (__zone_watermark_ok(z, order, mark, highest_zoneidx, alloc_flags,
3860                                         free_pages))
3861                 return true;
3862         /*
3863          * Ignore watermark boosting for GFP_ATOMIC order-0 allocations
3864          * when checking the min watermark. The min watermark is the
3865          * point where boosting is ignored so that kswapd is woken up
3866          * when below the low watermark.
3867          */
3868         if (unlikely(!order && (gfp_mask & __GFP_ATOMIC) && z->watermark_boost
3869                 && ((alloc_flags & ALLOC_WMARK_MASK) == WMARK_MIN))) {
3870                 mark = z->_watermark[WMARK_MIN];
3871                 return __zone_watermark_ok(z, order, mark, highest_zoneidx,
3872                                         alloc_flags, free_pages);
3873         }
3874
3875         return false;
3876 }
3877
3878 bool zone_watermark_ok_safe(struct zone *z, unsigned int order,
3879                         unsigned long mark, int highest_zoneidx)
3880 {
3881         long free_pages = zone_page_state(z, NR_FREE_PAGES);
3882
3883         if (z->percpu_drift_mark && free_pages < z->percpu_drift_mark)
3884                 free_pages = zone_page_state_snapshot(z, NR_FREE_PAGES);
3885
3886         return __zone_watermark_ok(z, order, mark, highest_zoneidx, 0,
3887                                                                 free_pages);
3888 }
3889
3890 #ifdef CONFIG_NUMA
3891 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
3892 {
3893         return node_distance(zone_to_nid(local_zone), zone_to_nid(zone)) <=
3894                                 node_reclaim_distance;
3895 }
3896 #else   /* CONFIG_NUMA */
3897 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
3898 {
3899         return true;
3900 }
3901 #endif  /* CONFIG_NUMA */
3902
3903 /*
3904  * The restriction on ZONE_DMA32 as being a suitable zone to use to avoid
3905  * fragmentation is subtle. If the preferred zone was HIGHMEM then
3906  * premature use of a lower zone may cause lowmem pressure problems that
3907  * are worse than fragmentation. If the next zone is ZONE_DMA then it is
3908  * probably too small. It only makes sense to spread allocations to avoid
3909  * fragmentation between the Normal and DMA32 zones.
3910  */
3911 static inline unsigned int
3912 alloc_flags_nofragment(struct zone *zone, gfp_t gfp_mask)
3913 {
3914         unsigned int alloc_flags;
3915
3916         /*
3917          * __GFP_KSWAPD_RECLAIM is assumed to be the same as ALLOC_KSWAPD
3918          * to save a branch.
3919          */
3920         alloc_flags = (__force int) (gfp_mask & __GFP_KSWAPD_RECLAIM);
3921
3922 #ifdef CONFIG_ZONE_DMA32
3923         if (!zone)
3924                 return alloc_flags;
3925
3926         if (zone_idx(zone) != ZONE_NORMAL)
3927                 return alloc_flags;
3928
3929         /*
3930          * If ZONE_DMA32 exists, assume it is the one after ZONE_NORMAL and
3931          * the pointer is within zone->zone_pgdat->node_zones[]. Also assume
3932          * on UMA that if Normal is populated then so is DMA32.
3933          */
3934         BUILD_BUG_ON(ZONE_NORMAL - ZONE_DMA32 != 1);
3935         if (nr_online_nodes > 1 && !populated_zone(--zone))
3936                 return alloc_flags;
3937
3938         alloc_flags |= ALLOC_NOFRAGMENT;
3939 #endif /* CONFIG_ZONE_DMA32 */
3940         return alloc_flags;
3941 }
3942
3943 /* Must be called after current_gfp_context() which can change gfp_mask */
3944 static inline unsigned int gfp_to_alloc_flags_cma(gfp_t gfp_mask,
3945                                                   unsigned int alloc_flags)
3946 {
3947 #ifdef CONFIG_CMA
3948         if (gfp_migratetype(gfp_mask) == MIGRATE_MOVABLE)
3949                 alloc_flags |= ALLOC_CMA;
3950 #endif
3951         return alloc_flags;
3952 }
3953
3954 /*
3955  * get_page_from_freelist goes through the zonelist trying to allocate
3956  * a page.
3957  */
3958 static struct page *
3959 get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags,
3960                                                 const struct alloc_context *ac)
3961 {
3962         struct zoneref *z;
3963         struct zone *zone;
3964         struct pglist_data *last_pgdat_dirty_limit = NULL;
3965         bool no_fallback;
3966
3967 retry:
3968         /*
3969          * Scan zonelist, looking for a zone with enough free.
3970          * See also __cpuset_node_allowed() comment in kernel/cpuset.c.
3971          */
3972         no_fallback = alloc_flags & ALLOC_NOFRAGMENT;
3973         z = ac->preferred_zoneref;
3974         for_next_zone_zonelist_nodemask(zone, z, ac->highest_zoneidx,
3975                                         ac->nodemask) {
3976                 struct page *page;
3977                 unsigned long mark;
3978
3979                 if (cpusets_enabled() &&
3980                         (alloc_flags & ALLOC_CPUSET) &&
3981                         !__cpuset_zone_allowed(zone, gfp_mask))
3982                                 continue;
3983                 /*
3984                  * When allocating a page cache page for writing, we
3985                  * want to get it from a node that is within its dirty
3986                  * limit, such that no single node holds more than its
3987                  * proportional share of globally allowed dirty pages.
3988                  * The dirty limits take into account the node's
3989                  * lowmem reserves and high watermark so that kswapd
3990                  * should be able to balance it without having to
3991                  * write pages from its LRU list.
3992                  *
3993                  * XXX: For now, allow allocations to potentially
3994                  * exceed the per-node dirty limit in the slowpath
3995                  * (spread_dirty_pages unset) before going into reclaim,
3996                  * which is important when on a NUMA setup the allowed
3997                  * nodes are together not big enough to reach the
3998                  * global limit.  The proper fix for these situations
3999                  * will require awareness of nodes in the
4000                  * dirty-throttling and the flusher threads.
4001                  */
4002                 if (ac->spread_dirty_pages) {
4003                         if (last_pgdat_dirty_limit == zone->zone_pgdat)
4004                                 continue;
4005
4006                         if (!node_dirty_ok(zone->zone_pgdat)) {
4007                                 last_pgdat_dirty_limit = zone->zone_pgdat;
4008                                 continue;
4009                         }
4010                 }
4011
4012                 if (no_fallback && nr_online_nodes > 1 &&
4013                     zone != ac->preferred_zoneref->zone) {
4014                         int local_nid;
4015
4016                         /*
4017                          * If moving to a remote node, retry but allow
4018                          * fragmenting fallbacks. Locality is more important
4019                          * than fragmentation avoidance.
4020                          */
4021                         local_nid = zone_to_nid(ac->preferred_zoneref->zone);
4022                         if (zone_to_nid(zone) != local_nid) {
4023                                 alloc_flags &= ~ALLOC_NOFRAGMENT;
4024                                 goto retry;
4025                         }
4026                 }
4027
4028                 mark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK);
4029                 if (!zone_watermark_fast(zone, order, mark,
4030                                        ac->highest_zoneidx, alloc_flags,
4031                                        gfp_mask)) {
4032                         int ret;
4033
4034 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
4035                         /*
4036                          * Watermark failed for this zone, but see if we can
4037                          * grow this zone if it contains deferred pages.
4038                          */
4039                         if (static_branch_unlikely(&deferred_pages)) {
4040                                 if (_deferred_grow_zone(zone, order))
4041                                         goto try_this_zone;
4042                         }
4043 #endif
4044                         /* Checked here to keep the fast path fast */
4045                         BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK);
4046                         if (alloc_flags & ALLOC_NO_WATERMARKS)
4047                                 goto try_this_zone;
4048
4049                         if (!node_reclaim_enabled() ||
4050                             !zone_allows_reclaim(ac->preferred_zoneref->zone, zone))
4051                                 continue;
4052
4053                         ret = node_reclaim(zone->zone_pgdat, gfp_mask, order);
4054                         switch (ret) {
4055                         case NODE_RECLAIM_NOSCAN:
4056                                 /* did not scan */
4057                                 continue;
4058                         case NODE_RECLAIM_FULL:
4059                                 /* scanned but unreclaimable */
4060                                 continue;
4061                         default:
4062                                 /* did we reclaim enough */
4063                                 if (zone_watermark_ok(zone, order, mark,
4064                                         ac->highest_zoneidx, alloc_flags))
4065                                         goto try_this_zone;
4066
4067                                 continue;
4068                         }
4069                 }
4070
4071 try_this_zone:
4072                 page = rmqueue(ac->preferred_zoneref->zone, zone, order,
4073                                 gfp_mask, alloc_flags, ac->migratetype);
4074                 if (page) {
4075                         prep_new_page(page, order, gfp_mask, alloc_flags);
4076
4077                         /*
4078                          * If this is a high-order atomic allocation then check
4079                          * if the pageblock should be reserved for the future
4080                          */
4081                         if (unlikely(order && (alloc_flags & ALLOC_HARDER)))
4082                                 reserve_highatomic_pageblock(page, zone, order);
4083
4084                         return page;
4085                 } else {
4086 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
4087                         /* Try again if zone has deferred pages */
4088                         if (static_branch_unlikely(&deferred_pages)) {
4089                                 if (_deferred_grow_zone(zone, order))
4090                                         goto try_this_zone;
4091                         }
4092 #endif
4093                 }
4094         }
4095
4096         /*
4097          * It's possible on a UMA machine to get through all zones that are
4098          * fragmented. If avoiding fragmentation, reset and try again.
4099          */
4100         if (no_fallback) {
4101                 alloc_flags &= ~ALLOC_NOFRAGMENT;
4102                 goto retry;
4103         }
4104
4105         return NULL;
4106 }
4107
4108 static void warn_alloc_show_mem(gfp_t gfp_mask, nodemask_t *nodemask)
4109 {
4110         unsigned int filter = SHOW_MEM_FILTER_NODES;
4111
4112         /*
4113          * This documents exceptions given to allocations in certain
4114          * contexts that are allowed to allocate outside current's set
4115          * of allowed nodes.
4116          */
4117         if (!(gfp_mask & __GFP_NOMEMALLOC))
4118                 if (tsk_is_oom_victim(current) ||
4119                     (current->flags & (PF_MEMALLOC | PF_EXITING)))
4120                         filter &= ~SHOW_MEM_FILTER_NODES;
4121         if (in_interrupt() || !(gfp_mask & __GFP_DIRECT_RECLAIM))
4122                 filter &= ~SHOW_MEM_FILTER_NODES;
4123
4124         show_mem(filter, nodemask);
4125 }
4126
4127 void warn_alloc(gfp_t gfp_mask, nodemask_t *nodemask, const char *fmt, ...)
4128 {
4129         struct va_format vaf;
4130         va_list args;
4131         static DEFINE_RATELIMIT_STATE(nopage_rs, 10*HZ, 1);
4132
4133         if ((gfp_mask & __GFP_NOWARN) || !__ratelimit(&nopage_rs))
4134                 return;
4135
4136         va_start(args, fmt);
4137         vaf.fmt = fmt;
4138         vaf.va = &args;
4139         pr_warn("%s: %pV, mode:%#x(%pGg), nodemask=%*pbl",
4140                         current->comm, &vaf, gfp_mask, &gfp_mask,
4141                         nodemask_pr_args(nodemask));
4142         va_end(args);
4143
4144         cpuset_print_current_mems_allowed();
4145         pr_cont("\n");
4146         dump_stack();
4147         warn_alloc_show_mem(gfp_mask, nodemask);
4148 }
4149
4150 static inline struct page *
4151 __alloc_pages_cpuset_fallback(gfp_t gfp_mask, unsigned int order,
4152                               unsigned int alloc_flags,
4153                               const struct alloc_context *ac)
4154 {
4155         struct page *page;
4156
4157         page = get_page_from_freelist(gfp_mask, order,
4158                         alloc_flags|ALLOC_CPUSET, ac);
4159         /*
4160          * fallback to ignore cpuset restriction if our nodes
4161          * are depleted
4162          */
4163         if (!page)
4164                 page = get_page_from_freelist(gfp_mask, order,
4165                                 alloc_flags, ac);
4166
4167         return page;
4168 }
4169
4170 static inline struct page *
4171 __alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order,
4172         const struct alloc_context *ac, unsigned long *did_some_progress)
4173 {
4174         struct oom_control oc = {
4175                 .zonelist = ac->zonelist,
4176                 .nodemask = ac->nodemask,
4177                 .memcg = NULL,
4178                 .gfp_mask = gfp_mask,
4179                 .order = order,
4180         };
4181         struct page *page;
4182
4183         *did_some_progress = 0;
4184
4185         /*
4186          * Acquire the oom lock.  If that fails, somebody else is
4187          * making progress for us.
4188          */
4189         if (!mutex_trylock(&oom_lock)) {
4190                 *did_some_progress = 1;
4191                 schedule_timeout_uninterruptible(1);
4192                 return NULL;
4193         }
4194
4195         /*
4196          * Go through the zonelist yet one more time, keep very high watermark
4197          * here, this is only to catch a parallel oom killing, we must fail if
4198          * we're still under heavy pressure. But make sure that this reclaim
4199          * attempt shall not depend on __GFP_DIRECT_RECLAIM && !__GFP_NORETRY
4200          * allocation which will never fail due to oom_lock already held.
4201          */
4202         page = get_page_from_freelist((gfp_mask | __GFP_HARDWALL) &
4203                                       ~__GFP_DIRECT_RECLAIM, order,
4204                                       ALLOC_WMARK_HIGH|ALLOC_CPUSET, ac);
4205         if (page)
4206                 goto out;
4207
4208         /* Coredumps can quickly deplete all memory reserves */
4209         if (current->flags & PF_DUMPCORE)
4210                 goto out;
4211         /* The OOM killer will not help higher order allocs */
4212         if (order > PAGE_ALLOC_COSTLY_ORDER)
4213                 goto out;
4214         /*
4215          * We have already exhausted all our reclaim opportunities without any
4216          * success so it is time to admit defeat. We will skip the OOM killer
4217          * because it is very likely that the caller has a more reasonable
4218          * fallback than shooting a random task.
4219          *
4220          * The OOM killer may not free memory on a specific node.
4221          */
4222         if (gfp_mask & (__GFP_RETRY_MAYFAIL | __GFP_THISNODE))
4223                 goto out;
4224         /* The OOM killer does not needlessly kill tasks for lowmem */
4225         if (ac->highest_zoneidx < ZONE_NORMAL)
4226                 goto out;
4227         if (pm_suspended_storage())
4228                 goto out;
4229         /*
4230          * XXX: GFP_NOFS allocations should rather fail than rely on
4231          * other request to make a forward progress.
4232          * We are in an unfortunate situation where out_of_memory cannot
4233          * do much for this context but let's try it to at least get
4234          * access to memory reserved if the current task is killed (see
4235          * out_of_memory). Once filesystems are ready to handle allocation
4236          * failures more gracefully we should just bail out here.
4237          */
4238
4239         /* Exhausted what can be done so it's blame time */
4240         if (out_of_memory(&oc) || WARN_ON_ONCE(gfp_mask & __GFP_NOFAIL)) {
4241                 *did_some_progress = 1;
4242
4243                 /*
4244                  * Help non-failing allocations by giving them access to memory
4245                  * reserves
4246                  */
4247                 if (gfp_mask & __GFP_NOFAIL)
4248                         page = __alloc_pages_cpuset_fallback(gfp_mask, order,
4249                                         ALLOC_NO_WATERMARKS, ac);
4250         }
4251 out:
4252         mutex_unlock(&oom_lock);
4253         return page;
4254 }
4255
4256 /*
4257  * Maximum number of compaction retries with a progress before OOM
4258  * killer is consider as the only way to move forward.
4259  */
4260 #define MAX_COMPACT_RETRIES 16
4261
4262 #ifdef CONFIG_COMPACTION
4263 /* Try memory compaction for high-order allocations before reclaim */
4264 static struct page *
4265 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
4266                 unsigned int alloc_flags, const struct alloc_context *ac,
4267                 enum compact_priority prio, enum compact_result *compact_result)
4268 {
4269         struct page *page = NULL;
4270         unsigned long pflags;
4271         unsigned int noreclaim_flag;
4272
4273         if (!order)
4274                 return NULL;
4275
4276         psi_memstall_enter(&pflags);
4277         noreclaim_flag = memalloc_noreclaim_save();
4278
4279         *compact_result = try_to_compact_pages(gfp_mask, order, alloc_flags, ac,
4280                                                                 prio, &page);
4281
4282         memalloc_noreclaim_restore(noreclaim_flag);
4283         psi_memstall_leave(&pflags);
4284
4285         if (*compact_result == COMPACT_SKIPPED)
4286                 return NULL;
4287         /*
4288          * At least in one zone compaction wasn't deferred or skipped, so let's
4289          * count a compaction stall
4290          */
4291         count_vm_event(COMPACTSTALL);
4292
4293         /* Prep a captured page if available */
4294         if (page)
4295                 prep_new_page(page, order, gfp_mask, alloc_flags);
4296
4297         /* Try get a page from the freelist if available */
4298         if (!page)
4299                 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4300
4301         if (page) {
4302                 struct zone *zone = page_zone(page);
4303
4304                 zone->compact_blockskip_flush = false;
4305                 compaction_defer_reset(zone, order, true);
4306                 count_vm_event(COMPACTSUCCESS);
4307                 return page;
4308         }
4309
4310         /*
4311          * It's bad if compaction run occurs and fails. The most likely reason
4312          * is that pages exist, but not enough to satisfy watermarks.
4313          */
4314         count_vm_event(COMPACTFAIL);
4315
4316         cond_resched();
4317
4318         return NULL;
4319 }
4320
4321 static inline bool
4322 should_compact_retry(struct alloc_context *ac, int order, int alloc_flags,
4323                      enum compact_result compact_result,
4324                      enum compact_priority *compact_priority,
4325                      int *compaction_retries)
4326 {
4327         int max_retries = MAX_COMPACT_RETRIES;
4328         int min_priority;
4329         bool ret = false;
4330         int retries = *compaction_retries;
4331         enum compact_priority priority = *compact_priority;
4332
4333         if (!order)
4334                 return false;
4335
4336         if (fatal_signal_pending(current))
4337                 return false;
4338
4339         if (compaction_made_progress(compact_result))
4340                 (*compaction_retries)++;
4341
4342         /*
4343          * compaction considers all the zone as desperately out of memory
4344          * so it doesn't really make much sense to retry except when the
4345          * failure could be caused by insufficient priority
4346          */
4347         if (compaction_failed(compact_result))
4348                 goto check_priority;
4349
4350         /*
4351          * compaction was skipped because there are not enough order-0 pages
4352          * to work with, so we retry only if it looks like reclaim can help.
4353          */
4354         if (compaction_needs_reclaim(compact_result)) {
4355                 ret = compaction_zonelist_suitable(ac, order, alloc_flags);
4356                 goto out;
4357         }
4358
4359         /*
4360          * make sure the compaction wasn't deferred or didn't bail out early
4361          * due to locks contention before we declare that we should give up.
4362          * But the next retry should use a higher priority if allowed, so
4363          * we don't just keep bailing out endlessly.
4364          */
4365         if (compaction_withdrawn(compact_result)) {
4366                 goto check_priority;
4367         }
4368
4369         /*
4370          * !costly requests are much more important than __GFP_RETRY_MAYFAIL
4371          * costly ones because they are de facto nofail and invoke OOM
4372          * killer to move on while costly can fail and users are ready
4373          * to cope with that. 1/4 retries is rather arbitrary but we
4374          * would need much more detailed feedback from compaction to
4375          * make a better decision.
4376          */
4377         if (order > PAGE_ALLOC_COSTLY_ORDER)
4378                 max_retries /= 4;
4379         if (*compaction_retries <= max_retries) {
4380                 ret = true;
4381                 goto out;
4382         }
4383
4384         /*
4385          * Make sure there are attempts at the highest priority if we exhausted
4386          * all retries or failed at the lower priorities.
4387          */
4388 check_priority:
4389         min_priority = (order > PAGE_ALLOC_COSTLY_ORDER) ?
4390                         MIN_COMPACT_COSTLY_PRIORITY : MIN_COMPACT_PRIORITY;
4391
4392         if (*compact_priority > min_priority) {
4393                 (*compact_priority)--;
4394                 *compaction_retries = 0;
4395                 ret = true;
4396         }
4397 out:
4398         trace_compact_retry(order, priority, compact_result, retries, max_retries, ret);
4399         return ret;
4400 }
4401 #else
4402 static inline struct page *
4403 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
4404                 unsigned int alloc_flags, const struct alloc_context *ac,
4405                 enum compact_priority prio, enum compact_result *compact_result)
4406 {
4407         *compact_result = COMPACT_SKIPPED;
4408         return NULL;
4409 }
4410
4411 static inline bool
4412 should_compact_retry(struct alloc_context *ac, unsigned int order, int alloc_flags,
4413                      enum compact_result compact_result,
4414                      enum compact_priority *compact_priority,
4415                      int *compaction_retries)
4416 {
4417         struct zone *zone;
4418         struct zoneref *z;
4419
4420         if (!order || order > PAGE_ALLOC_COSTLY_ORDER)
4421                 return false;
4422
4423         /*
4424          * There are setups with compaction disabled which would prefer to loop
4425          * inside the allocator rather than hit the oom killer prematurely.
4426          * Let's give them a good hope and keep retrying while the order-0
4427          * watermarks are OK.
4428          */
4429         for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
4430                                 ac->highest_zoneidx, ac->nodemask) {
4431                 if (zone_watermark_ok(zone, 0, min_wmark_pages(zone),
4432                                         ac->highest_zoneidx, alloc_flags))
4433                         return true;
4434         }
4435         return false;
4436 }
4437 #endif /* CONFIG_COMPACTION */
4438
4439 #ifdef CONFIG_LOCKDEP
4440 static struct lockdep_map __fs_reclaim_map =
4441         STATIC_LOCKDEP_MAP_INIT("fs_reclaim", &__fs_reclaim_map);
4442
4443 static bool __need_reclaim(gfp_t gfp_mask)
4444 {
4445         /* no reclaim without waiting on it */
4446         if (!(gfp_mask & __GFP_DIRECT_RECLAIM))
4447                 return false;
4448
4449         /* this guy won't enter reclaim */
4450         if (current->flags & PF_MEMALLOC)
4451                 return false;
4452
4453         if (gfp_mask & __GFP_NOLOCKDEP)
4454                 return false;
4455
4456         return true;
4457 }
4458
4459 void __fs_reclaim_acquire(void)
4460 {
4461         lock_map_acquire(&__fs_reclaim_map);
4462 }
4463
4464 void __fs_reclaim_release(void)
4465 {
4466         lock_map_release(&__fs_reclaim_map);
4467 }
4468
4469 void fs_reclaim_acquire(gfp_t gfp_mask)
4470 {
4471         gfp_mask = current_gfp_context(gfp_mask);
4472
4473         if (__need_reclaim(gfp_mask)) {
4474                 if (gfp_mask & __GFP_FS)
4475                         __fs_reclaim_acquire();
4476
4477 #ifdef CONFIG_MMU_NOTIFIER
4478                 lock_map_acquire(&__mmu_notifier_invalidate_range_start_map);
4479                 lock_map_release(&__mmu_notifier_invalidate_range_start_map);
4480 #endif
4481
4482         }
4483 }
4484 EXPORT_SYMBOL_GPL(fs_reclaim_acquire);
4485
4486 void fs_reclaim_release(gfp_t gfp_mask)
4487 {
4488         gfp_mask = current_gfp_context(gfp_mask);
4489
4490         if (__need_reclaim(gfp_mask)) {
4491                 if (gfp_mask & __GFP_FS)
4492                         __fs_reclaim_release();
4493         }
4494 }
4495 EXPORT_SYMBOL_GPL(fs_reclaim_release);
4496 #endif
4497
4498 /* Perform direct synchronous page reclaim */
4499 static unsigned long
4500 __perform_reclaim(gfp_t gfp_mask, unsigned int order,
4501                                         const struct alloc_context *ac)
4502 {
4503         unsigned int noreclaim_flag;
4504         unsigned long pflags, progress;
4505
4506         cond_resched();
4507
4508         /* We now go into synchronous reclaim */
4509         cpuset_memory_pressure_bump();
4510         psi_memstall_enter(&pflags);
4511         fs_reclaim_acquire(gfp_mask);
4512         noreclaim_flag = memalloc_noreclaim_save();
4513
4514         progress = try_to_free_pages(ac->zonelist, order, gfp_mask,
4515                                                                 ac->nodemask);
4516
4517         memalloc_noreclaim_restore(noreclaim_flag);
4518         fs_reclaim_release(gfp_mask);
4519         psi_memstall_leave(&pflags);
4520
4521         cond_resched();
4522
4523         return progress;
4524 }
4525
4526 /* The really slow allocator path where we enter direct reclaim */
4527 static inline struct page *
4528 __alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order,
4529                 unsigned int alloc_flags, const struct alloc_context *ac,
4530                 unsigned long *did_some_progress)
4531 {
4532         struct page *page = NULL;
4533         bool drained = false;
4534
4535         *did_some_progress = __perform_reclaim(gfp_mask, order, ac);
4536         if (unlikely(!(*did_some_progress)))
4537                 return NULL;
4538
4539 retry:
4540         page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4541
4542         /*
4543          * If an allocation failed after direct reclaim, it could be because
4544          * pages are pinned on the per-cpu lists or in high alloc reserves.
4545          * Shrink them and try again
4546          */
4547         if (!page && !drained) {
4548                 unreserve_highatomic_pageblock(ac, false);
4549                 drain_all_pages(NULL);
4550                 drained = true;
4551                 goto retry;
4552         }
4553
4554         return page;
4555 }
4556
4557 static void wake_all_kswapds(unsigned int order, gfp_t gfp_mask,
4558                              const struct alloc_context *ac)
4559 {
4560         struct zoneref *z;
4561         struct zone *zone;
4562         pg_data_t *last_pgdat = NULL;
4563         enum zone_type highest_zoneidx = ac->highest_zoneidx;
4564
4565         for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, highest_zoneidx,
4566                                         ac->nodemask) {
4567                 if (last_pgdat != zone->zone_pgdat)
4568                         wakeup_kswapd(zone, gfp_mask, order, highest_zoneidx);
4569                 last_pgdat = zone->zone_pgdat;
4570         }
4571 }
4572
4573 static inline unsigned int
4574 gfp_to_alloc_flags(gfp_t gfp_mask)
4575 {
4576         unsigned int alloc_flags = ALLOC_WMARK_MIN | ALLOC_CPUSET;
4577
4578         /*
4579          * __GFP_HIGH is assumed to be the same as ALLOC_HIGH
4580          * and __GFP_KSWAPD_RECLAIM is assumed to be the same as ALLOC_KSWAPD
4581          * to save two branches.
4582          */
4583         BUILD_BUG_ON(__GFP_HIGH != (__force gfp_t) ALLOC_HIGH);
4584         BUILD_BUG_ON(__GFP_KSWAPD_RECLAIM != (__force gfp_t) ALLOC_KSWAPD);
4585
4586         /*
4587          * The caller may dip into page reserves a bit more if the caller
4588          * cannot run direct reclaim, or if the caller has realtime scheduling
4589          * policy or is asking for __GFP_HIGH memory.  GFP_ATOMIC requests will
4590          * set both ALLOC_HARDER (__GFP_ATOMIC) and ALLOC_HIGH (__GFP_HIGH).
4591          */
4592         alloc_flags |= (__force int)
4593                 (gfp_mask & (__GFP_HIGH | __GFP_KSWAPD_RECLAIM));
4594
4595         if (gfp_mask & __GFP_ATOMIC) {
4596                 /*
4597                  * Not worth trying to allocate harder for __GFP_NOMEMALLOC even
4598                  * if it can't schedule.
4599                  */
4600                 if (!(gfp_mask & __GFP_NOMEMALLOC))
4601                         alloc_flags |= ALLOC_HARDER;
4602                 /*
4603                  * Ignore cpuset mems for GFP_ATOMIC rather than fail, see the
4604                  * comment for __cpuset_node_allowed().
4605                  */
4606                 alloc_flags &= ~ALLOC_CPUSET;
4607         } else if (unlikely(rt_task(current)) && !in_interrupt())
4608                 alloc_flags |= ALLOC_HARDER;
4609
4610         alloc_flags = gfp_to_alloc_flags_cma(gfp_mask, alloc_flags);
4611
4612         return alloc_flags;
4613 }
4614
4615 static bool oom_reserves_allowed(struct task_struct *tsk)
4616 {
4617         if (!tsk_is_oom_victim(tsk))
4618                 return false;
4619
4620         /*
4621          * !MMU doesn't have oom reaper so give access to memory reserves
4622          * only to the thread with TIF_MEMDIE set
4623          */
4624         if (!IS_ENABLED(CONFIG_MMU) && !test_thread_flag(TIF_MEMDIE))
4625                 return false;
4626
4627         return true;
4628 }
4629
4630 /*
4631  * Distinguish requests which really need access to full memory
4632  * reserves from oom victims which can live with a portion of it
4633  */
4634 static inline int __gfp_pfmemalloc_flags(gfp_t gfp_mask)
4635 {
4636         if (unlikely(gfp_mask & __GFP_NOMEMALLOC))
4637                 return 0;
4638         if (gfp_mask & __GFP_MEMALLOC)
4639                 return ALLOC_NO_WATERMARKS;
4640         if (in_serving_softirq() && (current->flags & PF_MEMALLOC))
4641                 return ALLOC_NO_WATERMARKS;
4642         if (!in_interrupt()) {
4643                 if (current->flags & PF_MEMALLOC)
4644                         return ALLOC_NO_WATERMARKS;
4645                 else if (oom_reserves_allowed(current))
4646                         return ALLOC_OOM;
4647         }
4648
4649         return 0;
4650 }
4651
4652 bool gfp_pfmemalloc_allowed(gfp_t gfp_mask)
4653 {
4654         return !!__gfp_pfmemalloc_flags(gfp_mask);
4655 }
4656
4657 /*
4658  * Checks whether it makes sense to retry the reclaim to make a forward progress
4659  * for the given allocation request.
4660  *
4661  * We give up when we either have tried MAX_RECLAIM_RETRIES in a row
4662  * without success, or when we couldn't even meet the watermark if we
4663  * reclaimed all remaining pages on the LRU lists.
4664  *
4665  * Returns true if a retry is viable or false to enter the oom path.
4666  */
4667 static inline bool
4668 should_reclaim_retry(gfp_t gfp_mask, unsigned order,
4669                      struct alloc_context *ac, int alloc_flags,
4670                      bool did_some_progress, int *no_progress_loops)
4671 {
4672         struct zone *zone;
4673         struct zoneref *z;
4674         bool ret = false;
4675
4676         /*
4677          * Costly allocations might have made a progress but this doesn't mean
4678          * their order will become available due to high fragmentation so
4679          * always increment the no progress counter for them
4680          */
4681         if (did_some_progress && order <= PAGE_ALLOC_COSTLY_ORDER)
4682                 *no_progress_loops = 0;
4683         else
4684                 (*no_progress_loops)++;
4685
4686         /*
4687          * Make sure we converge to OOM if we cannot make any progress
4688          * several times in the row.
4689          */
4690         if (*no_progress_loops > MAX_RECLAIM_RETRIES) {
4691                 /* Before OOM, exhaust highatomic_reserve */
4692                 return unreserve_highatomic_pageblock(ac, true);
4693         }
4694
4695         /*
4696          * Keep reclaiming pages while there is a chance this will lead
4697          * somewhere.  If none of the target zones can satisfy our allocation
4698          * request even if all reclaimable pages are considered then we are
4699          * screwed and have to go OOM.
4700          */
4701         for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
4702                                 ac->highest_zoneidx, ac->nodemask) {
4703                 unsigned long available;
4704                 unsigned long reclaimable;
4705                 unsigned long min_wmark = min_wmark_pages(zone);
4706                 bool wmark;
4707
4708                 available = reclaimable = zone_reclaimable_pages(zone);
4709                 available += zone_page_state_snapshot(zone, NR_FREE_PAGES);
4710
4711                 /*
4712                  * Would the allocation succeed if we reclaimed all
4713                  * reclaimable pages?
4714                  */
4715                 wmark = __zone_watermark_ok(zone, order, min_wmark,
4716                                 ac->highest_zoneidx, alloc_flags, available);
4717                 trace_reclaim_retry_zone(z, order, reclaimable,
4718                                 available, min_wmark, *no_progress_loops, wmark);
4719                 if (wmark) {
4720                         /*
4721                          * If we didn't make any progress and have a lot of
4722                          * dirty + writeback pages then we should wait for
4723                          * an IO to complete to slow down the reclaim and
4724                          * prevent from pre mature OOM
4725                          */
4726                         if (!did_some_progress) {
4727                                 unsigned long write_pending;
4728
4729                                 write_pending = zone_page_state_snapshot(zone,
4730                                                         NR_ZONE_WRITE_PENDING);
4731
4732                                 if (2 * write_pending > reclaimable) {
4733                                         congestion_wait(BLK_RW_ASYNC, HZ/10);
4734                                         return true;
4735                                 }
4736                         }
4737
4738                         ret = true;
4739                         goto out;
4740                 }
4741         }
4742
4743 out:
4744         /*
4745          * Memory allocation/reclaim might be called from a WQ context and the
4746          * current implementation of the WQ concurrency control doesn't
4747          * recognize that a particular WQ is congested if the worker thread is
4748          * looping without ever sleeping. Therefore we have to do a short sleep
4749          * here rather than calling cond_resched().
4750          */
4751         if (current->flags & PF_WQ_WORKER)
4752                 schedule_timeout_uninterruptible(1);
4753         else
4754                 cond_resched();
4755         return ret;
4756 }
4757
4758 static inline bool
4759 check_retry_cpuset(int cpuset_mems_cookie, struct alloc_context *ac)
4760 {
4761         /*
4762          * It's possible that cpuset's mems_allowed and the nodemask from
4763          * mempolicy don't intersect. This should be normally dealt with by
4764          * policy_nodemask(), but it's possible to race with cpuset update in
4765          * such a way the check therein was true, and then it became false
4766          * before we got our cpuset_mems_cookie here.
4767          * This assumes that for all allocations, ac->nodemask can come only
4768          * from MPOL_BIND mempolicy (whose documented semantics is to be ignored
4769          * when it does not intersect with the cpuset restrictions) or the
4770          * caller can deal with a violated nodemask.
4771          */
4772         if (cpusets_enabled() && ac->nodemask &&
4773                         !cpuset_nodemask_valid_mems_allowed(ac->nodemask)) {
4774                 ac->nodemask = NULL;
4775                 return true;
4776         }
4777
4778         /*
4779          * When updating a task's mems_allowed or mempolicy nodemask, it is
4780          * possible to race with parallel threads in such a way that our
4781          * allocation can fail while the mask is being updated. If we are about
4782          * to fail, check if the cpuset changed during allocation and if so,
4783          * retry.
4784          */
4785         if (read_mems_allowed_retry(cpuset_mems_cookie))
4786                 return true;
4787
4788         return false;
4789 }
4790
4791 static inline struct page *
4792 __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order,
4793                                                 struct alloc_context *ac)
4794 {
4795         bool can_direct_reclaim = gfp_mask & __GFP_DIRECT_RECLAIM;
4796         const bool costly_order = order > PAGE_ALLOC_COSTLY_ORDER;
4797         struct page *page = NULL;
4798         unsigned int alloc_flags;
4799         unsigned long did_some_progress;
4800         enum compact_priority compact_priority;
4801         enum compact_result compact_result;
4802         int compaction_retries;
4803         int no_progress_loops;
4804         unsigned int cpuset_mems_cookie;
4805         int reserve_flags;
4806
4807         /*
4808          * We also sanity check to catch abuse of atomic reserves being used by
4809          * callers that are not in atomic context.
4810          */
4811         if (WARN_ON_ONCE((gfp_mask & (__GFP_ATOMIC|__GFP_DIRECT_RECLAIM)) ==
4812                                 (__GFP_ATOMIC|__GFP_DIRECT_RECLAIM)))
4813                 gfp_mask &= ~__GFP_ATOMIC;
4814
4815 retry_cpuset:
4816         compaction_retries = 0;
4817         no_progress_loops = 0;
4818         compact_priority = DEF_COMPACT_PRIORITY;
4819         cpuset_mems_cookie = read_mems_allowed_begin();
4820
4821         /*
4822          * The fast path uses conservative alloc_flags to succeed only until
4823          * kswapd needs to be woken up, and to avoid the cost of setting up
4824          * alloc_flags precisely. So we do that now.
4825          */
4826         alloc_flags = gfp_to_alloc_flags(gfp_mask);
4827
4828         /*
4829          * We need to recalculate the starting point for the zonelist iterator
4830          * because we might have used different nodemask in the fast path, or
4831          * there was a cpuset modification and we are retrying - otherwise we
4832          * could end up iterating over non-eligible zones endlessly.
4833          */
4834         ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
4835                                         ac->highest_zoneidx, ac->nodemask);
4836         if (!ac->preferred_zoneref->zone)
4837                 goto nopage;
4838
4839         if (alloc_flags & ALLOC_KSWAPD)
4840                 wake_all_kswapds(order, gfp_mask, ac);
4841
4842         /*
4843          * The adjusted alloc_flags might result in immediate success, so try
4844          * that first
4845          */
4846         page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4847         if (page)
4848                 goto got_pg;
4849
4850         /*
4851          * For costly allocations, try direct compaction first, as it's likely
4852          * that we have enough base pages and don't need to reclaim. For non-
4853          * movable high-order allocations, do that as well, as compaction will
4854          * try prevent permanent fragmentation by migrating from blocks of the
4855          * same migratetype.
4856          * Don't try this for allocations that are allowed to ignore
4857          * watermarks, as the ALLOC_NO_WATERMARKS attempt didn't yet happen.
4858          */
4859         if (can_direct_reclaim &&
4860                         (costly_order ||
4861                            (order > 0 && ac->migratetype != MIGRATE_MOVABLE))
4862                         && !gfp_pfmemalloc_allowed(gfp_mask)) {
4863                 page = __alloc_pages_direct_compact(gfp_mask, order,
4864                                                 alloc_flags, ac,
4865                                                 INIT_COMPACT_PRIORITY,
4866                                                 &compact_result);
4867                 if (page)
4868                         goto got_pg;
4869
4870                 /*
4871                  * Checks for costly allocations with __GFP_NORETRY, which
4872                  * includes some THP page fault allocations
4873                  */
4874                 if (costly_order && (gfp_mask & __GFP_NORETRY)) {
4875                         /*
4876                          * If allocating entire pageblock(s) and compaction
4877                          * failed because all zones are below low watermarks
4878                          * or is prohibited because it recently failed at this
4879                          * order, fail immediately unless the allocator has
4880                          * requested compaction and reclaim retry.
4881                          *
4882                          * Reclaim is
4883                          *  - potentially very expensive because zones are far
4884                          *    below their low watermarks or this is part of very
4885                          *    bursty high order allocations,
4886                          *  - not guaranteed to help because isolate_freepages()
4887                          *    may not iterate over freed pages as part of its
4888                          *    linear scan, and
4889                          *  - unlikely to make entire pageblocks free on its
4890                          *    own.
4891                          */
4892                         if (compact_result == COMPACT_SKIPPED ||
4893                             compact_result == COMPACT_DEFERRED)
4894                                 goto nopage;
4895
4896                         /*
4897                          * Looks like reclaim/compaction is worth trying, but
4898                          * sync compaction could be very expensive, so keep
4899                          * using async compaction.
4900                          */
4901                         compact_priority = INIT_COMPACT_PRIORITY;
4902                 }
4903         }
4904
4905 retry:
4906         /* Ensure kswapd doesn't accidentally go to sleep as long as we loop */
4907         if (alloc_flags & ALLOC_KSWAPD)
4908                 wake_all_kswapds(order, gfp_mask, ac);
4909
4910         reserve_flags = __gfp_pfmemalloc_flags(gfp_mask);
4911         if (reserve_flags)
4912                 alloc_flags = gfp_to_alloc_flags_cma(gfp_mask, reserve_flags);
4913
4914         /*
4915          * Reset the nodemask and zonelist iterators if memory policies can be
4916          * ignored. These allocations are high priority and system rather than
4917          * user oriented.
4918          */
4919         if (!(alloc_flags & ALLOC_CPUSET) || reserve_flags) {
4920                 ac->nodemask = NULL;
4921                 ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
4922                                         ac->highest_zoneidx, ac->nodemask);
4923         }
4924
4925         /* Attempt with potentially adjusted zonelist and alloc_flags */
4926         page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4927         if (page)
4928                 goto got_pg;
4929
4930         /* Caller is not willing to reclaim, we can't balance anything */
4931         if (!can_direct_reclaim)
4932                 goto nopage;
4933
4934         /* Avoid recursion of direct reclaim */
4935         if (current->flags & PF_MEMALLOC)
4936                 goto nopage;
4937
4938         /* Try direct reclaim and then allocating */
4939         page = __alloc_pages_direct_reclaim(gfp_mask, order, alloc_flags, ac,
4940                                                         &did_some_progress);
4941         if (page)
4942                 goto got_pg;
4943
4944         /* Try direct compaction and then allocating */
4945         page = __alloc_pages_direct_compact(gfp_mask, order, alloc_flags, ac,
4946                                         compact_priority, &compact_result);
4947         if (page)
4948                 goto got_pg;
4949
4950         /* Do not loop if specifically requested */
4951         if (gfp_mask & __GFP_NORETRY)
4952                 goto nopage;
4953
4954         /*
4955          * Do not retry costly high order allocations unless they are
4956          * __GFP_RETRY_MAYFAIL
4957          */
4958         if (costly_order && !(gfp_mask & __GFP_RETRY_MAYFAIL))
4959                 goto nopage;
4960
4961         if (should_reclaim_retry(gfp_mask, order, ac, alloc_flags,
4962                                  did_some_progress > 0, &no_progress_loops))
4963                 goto retry;
4964
4965         /*
4966          * It doesn't make any sense to retry for the compaction if the order-0
4967          * reclaim is not able to make any progress because the current
4968          * implementation of the compaction depends on the sufficient amount
4969          * of free memory (see __compaction_suitable)
4970          */
4971         if (did_some_progress > 0 &&
4972                         should_compact_retry(ac, order, alloc_flags,
4973                                 compact_result, &compact_priority,
4974                                 &compaction_retries))
4975                 goto retry;
4976
4977
4978         /* Deal with possible cpuset update races before we start OOM killing */
4979         if (check_retry_cpuset(cpuset_mems_cookie, ac))
4980                 goto retry_cpuset;
4981
4982         /* Reclaim has failed us, start killing things */
4983         page = __alloc_pages_may_oom(gfp_mask, order, ac, &did_some_progress);
4984         if (page)
4985                 goto got_pg;
4986
4987         /* Avoid allocations with no watermarks from looping endlessly */
4988         if (tsk_is_oom_victim(current) &&
4989             (alloc_flags & ALLOC_OOM ||
4990              (gfp_mask & __GFP_NOMEMALLOC)))
4991                 goto nopage;
4992
4993         /* Retry as long as the OOM killer is making progress */
4994         if (did_some_progress) {
4995                 no_progress_loops = 0;
4996                 goto retry;
4997         }
4998
4999 nopage:
5000         /* Deal with possible cpuset update races before we fail */
5001         if (check_retry_cpuset(cpuset_mems_cookie, ac))
5002                 goto retry_cpuset;
5003
5004         /*
5005          * Make sure that __GFP_NOFAIL request doesn't leak out and make sure
5006          * we always retry
5007          */
5008         if (gfp_mask & __GFP_NOFAIL) {
5009                 /*
5010                  * All existing users of the __GFP_NOFAIL are blockable, so warn
5011                  * of any new users that actually require GFP_NOWAIT
5012                  */
5013                 if (WARN_ON_ONCE(!can_direct_reclaim))
5014                         goto fail;
5015
5016                 /*
5017                  * PF_MEMALLOC request from this context is rather bizarre
5018                  * because we cannot reclaim anything and only can loop waiting
5019                  * for somebody to do a work for us
5020                  */
5021                 WARN_ON_ONCE(current->flags & PF_MEMALLOC);
5022
5023                 /*
5024                  * non failing costly orders are a hard requirement which we
5025                  * are not prepared for much so let's warn about these users
5026                  * so that we can identify them and convert them to something
5027                  * else.
5028                  */
5029                 WARN_ON_ONCE(order > PAGE_ALLOC_COSTLY_ORDER);
5030
5031                 /*
5032                  * Help non-failing allocations by giving them access to memory
5033                  * reserves but do not use ALLOC_NO_WATERMARKS because this
5034                  * could deplete whole memory reserves which would just make
5035                  * the situation worse
5036                  */
5037                 page = __alloc_pages_cpuset_fallback(gfp_mask, order, ALLOC_HARDER, ac);
5038                 if (page)
5039                         goto got_pg;
5040
5041                 cond_resched();
5042                 goto retry;
5043         }
5044 fail:
5045         warn_alloc(gfp_mask, ac->nodemask,
5046                         "page allocation failure: order:%u", order);
5047 got_pg:
5048         return page;
5049 }
5050
5051 static inline bool prepare_alloc_pages(gfp_t gfp_mask, unsigned int order,
5052                 int preferred_nid, nodemask_t *nodemask,
5053                 struct alloc_context *ac, gfp_t *alloc_gfp,
5054                 unsigned int *alloc_flags)
5055 {
5056         ac->highest_zoneidx = gfp_zone(gfp_mask);
5057         ac->zonelist = node_zonelist(preferred_nid, gfp_mask);
5058         ac->nodemask = nodemask;
5059         ac->migratetype = gfp_migratetype(gfp_mask);
5060
5061         if (cpusets_enabled()) {
5062                 *alloc_gfp |= __GFP_HARDWALL;
5063                 /*
5064                  * When we are in the interrupt context, it is irrelevant
5065                  * to the current task context. It means that any node ok.
5066                  */
5067                 if (!in_interrupt() && !ac->nodemask)
5068                         ac->nodemask = &cpuset_current_mems_allowed;
5069                 else
5070                         *alloc_flags |= ALLOC_CPUSET;
5071         }
5072
5073         fs_reclaim_acquire(gfp_mask);
5074         fs_reclaim_release(gfp_mask);
5075
5076         might_sleep_if(gfp_mask & __GFP_DIRECT_RECLAIM);
5077
5078         if (should_fail_alloc_page(gfp_mask, order))
5079                 return false;
5080
5081         *alloc_flags = gfp_to_alloc_flags_cma(gfp_mask, *alloc_flags);
5082
5083         /* Dirty zone balancing only done in the fast path */
5084         ac->spread_dirty_pages = (gfp_mask & __GFP_WRITE);
5085
5086         /*
5087          * The preferred zone is used for statistics but crucially it is
5088          * also used as the starting point for the zonelist iterator. It
5089          * may get reset for allocations that ignore memory policies.
5090          */
5091         ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
5092                                         ac->highest_zoneidx, ac->nodemask);
5093
5094         return true;
5095 }
5096
5097 /*
5098  * __alloc_pages_bulk - Allocate a number of order-0 pages to a list or array
5099  * @gfp: GFP flags for the allocation
5100  * @preferred_nid: The preferred NUMA node ID to allocate from
5101  * @nodemask: Set of nodes to allocate from, may be NULL
5102  * @nr_pages: The number of pages desired on the list or array
5103  * @page_list: Optional list to store the allocated pages
5104  * @page_array: Optional array to store the pages
5105  *
5106  * This is a batched version of the page allocator that attempts to
5107  * allocate nr_pages quickly. Pages are added to page_list if page_list
5108  * is not NULL, otherwise it is assumed that the page_array is valid.
5109  *
5110  * For lists, nr_pages is the number of pages that should be allocated.
5111  *
5112  * For arrays, only NULL elements are populated with pages and nr_pages
5113  * is the maximum number of pages that will be stored in the array.
5114  *
5115  * Returns the number of pages on the list or array.
5116  */
5117 unsigned long __alloc_pages_bulk(gfp_t gfp, int preferred_nid,
5118                         nodemask_t *nodemask, int nr_pages,
5119                         struct list_head *page_list,
5120                         struct page **page_array)
5121 {
5122         struct page *page;
5123         unsigned long flags;
5124         struct zone *zone;
5125         struct zoneref *z;
5126         struct per_cpu_pages *pcp;
5127         struct list_head *pcp_list;
5128         struct alloc_context ac;
5129         gfp_t alloc_gfp;
5130         unsigned int alloc_flags = ALLOC_WMARK_LOW;
5131         int nr_populated = 0, nr_account = 0;
5132
5133         if (unlikely(nr_pages <= 0))
5134                 return 0;
5135
5136         /*
5137          * Skip populated array elements to determine if any pages need
5138          * to be allocated before disabling IRQs.
5139          */
5140         while (page_array && nr_populated < nr_pages && page_array[nr_populated])
5141                 nr_populated++;
5142
5143         /* Already populated array? */
5144         if (unlikely(page_array && nr_pages - nr_populated == 0))
5145                 return nr_populated;
5146
5147         /* Use the single page allocator for one page. */
5148         if (nr_pages - nr_populated == 1)
5149                 goto failed;
5150
5151         /* May set ALLOC_NOFRAGMENT, fragmentation will return 1 page. */
5152         gfp &= gfp_allowed_mask;
5153         alloc_gfp = gfp;
5154         if (!prepare_alloc_pages(gfp, 0, preferred_nid, nodemask, &ac, &alloc_gfp, &alloc_flags))
5155                 return 0;
5156         gfp = alloc_gfp;
5157
5158         /* Find an allowed local zone that meets the low watermark. */
5159         for_each_zone_zonelist_nodemask(zone, z, ac.zonelist, ac.highest_zoneidx, ac.nodemask) {
5160                 unsigned long mark;
5161
5162                 if (cpusets_enabled() && (alloc_flags & ALLOC_CPUSET) &&
5163                     !__cpuset_zone_allowed(zone, gfp)) {
5164                         continue;
5165                 }
5166
5167                 if (nr_online_nodes > 1 && zone != ac.preferred_zoneref->zone &&
5168                     zone_to_nid(zone) != zone_to_nid(ac.preferred_zoneref->zone)) {
5169                         goto failed;
5170                 }
5171
5172                 mark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK) + nr_pages;
5173                 if (zone_watermark_fast(zone, 0,  mark,
5174                                 zonelist_zone_idx(ac.preferred_zoneref),
5175                                 alloc_flags, gfp)) {
5176                         break;
5177                 }
5178         }
5179
5180         /*
5181          * If there are no allowed local zones that meets the watermarks then
5182          * try to allocate a single page and reclaim if necessary.
5183          */
5184         if (unlikely(!zone))
5185                 goto failed;
5186
5187         /* Attempt the batch allocation */
5188         local_lock_irqsave(&pagesets.lock, flags);
5189         pcp = this_cpu_ptr(zone->per_cpu_pageset);
5190         pcp_list = &pcp->lists[ac.migratetype];
5191
5192         while (nr_populated < nr_pages) {
5193
5194                 /* Skip existing pages */
5195                 if (page_array && page_array[nr_populated]) {
5196                         nr_populated++;
5197                         continue;
5198                 }
5199
5200                 page = __rmqueue_pcplist(zone, ac.migratetype, alloc_flags,
5201                                                                 pcp, pcp_list);
5202                 if (unlikely(!page)) {
5203                         /* Try and get at least one page */
5204                         if (!nr_populated)
5205                                 goto failed_irq;
5206                         break;
5207                 }
5208                 nr_account++;
5209
5210                 prep_new_page(page, 0, gfp, 0);
5211                 if (page_list)
5212                         list_add(&page->lru, page_list);
5213                 else
5214                         page_array[nr_populated] = page;
5215                 nr_populated++;
5216         }
5217
5218         local_unlock_irqrestore(&pagesets.lock, flags);
5219
5220         __count_zid_vm_events(PGALLOC, zone_idx(zone), nr_account);
5221         zone_statistics(ac.preferred_zoneref->zone, zone, nr_account);
5222
5223         return nr_populated;
5224
5225 failed_irq:
5226         local_unlock_irqrestore(&pagesets.lock, flags);
5227
5228 failed:
5229         page = __alloc_pages(gfp, 0, preferred_nid, nodemask);
5230         if (page) {
5231                 if (page_list)
5232                         list_add(&page->lru, page_list);
5233                 else
5234                         page_array[nr_populated] = page;
5235                 nr_populated++;
5236         }
5237
5238         return nr_populated;
5239 }
5240 EXPORT_SYMBOL_GPL(__alloc_pages_bulk);
5241
5242 /*
5243  * This is the 'heart' of the zoned buddy allocator.
5244  */
5245 struct page *__alloc_pages(gfp_t gfp, unsigned int order, int preferred_nid,
5246                                                         nodemask_t *nodemask)
5247 {
5248         struct page *page;
5249         unsigned int alloc_flags = ALLOC_WMARK_LOW;
5250         gfp_t alloc_gfp; /* The gfp_t that was actually used for allocation */
5251         struct alloc_context ac = { };
5252
5253         /*
5254          * There are several places where we assume that the order value is sane
5255          * so bail out early if the request is out of bound.
5256          */
5257         if (unlikely(order >= MAX_ORDER)) {
5258                 WARN_ON_ONCE(!(gfp & __GFP_NOWARN));
5259                 return NULL;
5260         }
5261
5262         gfp &= gfp_allowed_mask;
5263         /*
5264          * Apply scoped allocation constraints. This is mainly about GFP_NOFS
5265          * resp. GFP_NOIO which has to be inherited for all allocation requests
5266          * from a particular context which has been marked by
5267          * memalloc_no{fs,io}_{save,restore}. And PF_MEMALLOC_PIN which ensures
5268          * movable zones are not used during allocation.
5269          */
5270         gfp = current_gfp_context(gfp);
5271         alloc_gfp = gfp;
5272         if (!prepare_alloc_pages(gfp, order, preferred_nid, nodemask, &ac,
5273                         &alloc_gfp, &alloc_flags))
5274                 return NULL;
5275
5276         /*
5277          * Forbid the first pass from falling back to types that fragment
5278          * memory until all local zones are considered.
5279          */
5280         alloc_flags |= alloc_flags_nofragment(ac.preferred_zoneref->zone, gfp);
5281
5282         /* First allocation attempt */
5283         page = get_page_from_freelist(alloc_gfp, order, alloc_flags, &ac);
5284         if (likely(page))
5285                 goto out;
5286
5287         alloc_gfp = gfp;
5288         ac.spread_dirty_pages = false;
5289
5290         /*
5291          * Restore the original nodemask if it was potentially replaced with
5292          * &cpuset_current_mems_allowed to optimize the fast-path attempt.
5293          */
5294         ac.nodemask = nodemask;
5295
5296         page = __alloc_pages_slowpath(alloc_gfp, order, &ac);
5297
5298 out:
5299         if (memcg_kmem_enabled() && (gfp & __GFP_ACCOUNT) && page &&
5300             unlikely(__memcg_kmem_charge_page(page, gfp, order) != 0)) {
5301                 __free_pages(page, order);
5302                 page = NULL;
5303         }
5304
5305         trace_mm_page_alloc(page, order, alloc_gfp, ac.migratetype);
5306
5307         return page;
5308 }
5309 EXPORT_SYMBOL(__alloc_pages);
5310
5311 /*
5312  * Common helper functions. Never use with __GFP_HIGHMEM because the returned
5313  * address cannot represent highmem pages. Use alloc_pages and then kmap if
5314  * you need to access high mem.
5315  */
5316 unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order)
5317 {
5318         struct page *page;
5319
5320         page = alloc_pages(gfp_mask & ~__GFP_HIGHMEM, order);
5321         if (!page)
5322                 return 0;
5323         return (unsigned long) page_address(page);
5324 }
5325 EXPORT_SYMBOL(__get_free_pages);
5326
5327 unsigned long get_zeroed_page(gfp_t gfp_mask)
5328 {
5329         return __get_free_pages(gfp_mask | __GFP_ZERO, 0);
5330 }
5331 EXPORT_SYMBOL(get_zeroed_page);
5332
5333 static inline void free_the_page(struct page *page, unsigned int order)
5334 {
5335         if (order == 0)         /* Via pcp? */
5336                 free_unref_page(page);
5337         else
5338                 __free_pages_ok(page, order, FPI_NONE);
5339 }
5340
5341 /**
5342  * __free_pages - Free pages allocated with alloc_pages().
5343  * @page: The page pointer returned from alloc_pages().
5344  * @order: The order of the allocation.
5345  *
5346  * This function can free multi-page allocations that are not compound
5347  * pages.  It does not check that the @order passed in matches that of
5348  * the allocation, so it is easy to leak memory.  Freeing more memory
5349  * than was allocated will probably emit a warning.
5350  *
5351  * If the last reference to this page is speculative, it will be released
5352  * by put_page() which only frees the first page of a non-compound
5353  * allocation.  To prevent the remaining pages from being leaked, we free
5354  * the subsequent pages here.  If you want to use the page's reference
5355  * count to decide when to free the allocation, you should allocate a
5356  * compound page, and use put_page() instead of __free_pages().
5357  *
5358  * Context: May be called in interrupt context or while holding a normal
5359  * spinlock, but not in NMI context or while holding a raw spinlock.
5360  */
5361 void __free_pages(struct page *page, unsigned int order)
5362 {
5363         if (put_page_testzero(page))
5364                 free_the_page(page, order);
5365         else if (!PageHead(page))
5366                 while (order-- > 0)
5367                         free_the_page(page + (1 << order), order);
5368 }
5369 EXPORT_SYMBOL(__free_pages);
5370
5371 void free_pages(unsigned long addr, unsigned int order)
5372 {
5373         if (addr != 0) {
5374                 VM_BUG_ON(!virt_addr_valid((void *)addr));
5375                 __free_pages(virt_to_page((void *)addr), order);
5376         }
5377 }
5378
5379 EXPORT_SYMBOL(free_pages);
5380
5381 /*
5382  * Page Fragment:
5383  *  An arbitrary-length arbitrary-offset area of memory which resides
5384  *  within a 0 or higher order page.  Multiple fragments within that page
5385  *  are individually refcounted, in the page's reference counter.
5386  *
5387  * The page_frag functions below provide a simple allocation framework for
5388  * page fragments.  This is used by the network stack and network device
5389  * drivers to provide a backing region of memory for use as either an
5390  * sk_buff->head, or to be used in the "frags" portion of skb_shared_info.
5391  */
5392 static struct page *__page_frag_cache_refill(struct page_frag_cache *nc,
5393                                              gfp_t gfp_mask)
5394 {
5395         struct page *page = NULL;
5396         gfp_t gfp = gfp_mask;
5397
5398 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
5399         gfp_mask |= __GFP_COMP | __GFP_NOWARN | __GFP_NORETRY |
5400                     __GFP_NOMEMALLOC;
5401         page = alloc_pages_node(NUMA_NO_NODE, gfp_mask,
5402                                 PAGE_FRAG_CACHE_MAX_ORDER);
5403         nc->size = page ? PAGE_FRAG_CACHE_MAX_SIZE : PAGE_SIZE;
5404 #endif
5405         if (unlikely(!page))
5406                 page = alloc_pages_node(NUMA_NO_NODE, gfp, 0);
5407
5408         nc->va = page ? page_address(page) : NULL;
5409
5410         return page;
5411 }
5412
5413 void __page_frag_cache_drain(struct page *page, unsigned int count)
5414 {
5415         VM_BUG_ON_PAGE(page_ref_count(page) == 0, page);
5416
5417         if (page_ref_sub_and_test(page, count))
5418                 free_the_page(page, compound_order(page));
5419 }
5420 EXPORT_SYMBOL(__page_frag_cache_drain);
5421
5422 void *page_frag_alloc_align(struct page_frag_cache *nc,
5423                       unsigned int fragsz, gfp_t gfp_mask,
5424                       unsigned int align_mask)
5425 {
5426         unsigned int size = PAGE_SIZE;
5427         struct page *page;
5428         int offset;
5429
5430         if (unlikely(!nc->va)) {
5431 refill:
5432                 page = __page_frag_cache_refill(nc, gfp_mask);
5433                 if (!page)
5434                         return NULL;
5435
5436 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
5437                 /* if size can vary use size else just use PAGE_SIZE */
5438                 size = nc->size;
5439 #endif
5440                 /* Even if we own the page, we do not use atomic_set().
5441                  * This would break get_page_unless_zero() users.
5442                  */
5443                 page_ref_add(page, PAGE_FRAG_CACHE_MAX_SIZE);
5444
5445                 /* reset page count bias and offset to start of new frag */
5446                 nc->pfmemalloc = page_is_pfmemalloc(page);
5447                 nc->pagecnt_bias = PAGE_FRAG_CACHE_MAX_SIZE + 1;
5448                 nc->offset = size;
5449         }
5450
5451         offset = nc->offset - fragsz;
5452         if (unlikely(offset < 0)) {
5453                 page = virt_to_page(nc->va);
5454
5455                 if (!page_ref_sub_and_test(page, nc->pagecnt_bias))
5456                         goto refill;
5457
5458                 if (unlikely(nc->pfmemalloc)) {
5459                         free_the_page(page, compound_order(page));
5460                         goto refill;
5461                 }
5462
5463 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
5464                 /* if size can vary use size else just use PAGE_SIZE */
5465                 size = nc->size;
5466 #endif
5467                 /* OK, page count is 0, we can safely set it */
5468                 set_page_count(page, PAGE_FRAG_CACHE_MAX_SIZE + 1);
5469
5470                 /* reset page count bias and offset to start of new frag */
5471                 nc->pagecnt_bias = PAGE_FRAG_CACHE_MAX_SIZE + 1;
5472                 offset = size - fragsz;
5473         }
5474
5475         nc->pagecnt_bias--;
5476         offset &= align_mask;
5477         nc->offset = offset;
5478
5479         return nc->va + offset;
5480 }
5481 EXPORT_SYMBOL(page_frag_alloc_align);
5482
5483 /*
5484  * Frees a page fragment allocated out of either a compound or order 0 page.
5485  */
5486 void page_frag_free(void *addr)
5487 {
5488         struct page *page = virt_to_head_page(addr);
5489
5490         if (unlikely(put_page_testzero(page)))
5491                 free_the_page(page, compound_order(page));
5492 }
5493 EXPORT_SYMBOL(page_frag_free);
5494
5495 static void *make_alloc_exact(unsigned long addr, unsigned int order,
5496                 size_t size)
5497 {
5498         if (addr) {
5499                 unsigned long alloc_end = addr + (PAGE_SIZE << order);
5500                 unsigned long used = addr + PAGE_ALIGN(size);
5501
5502                 split_page(virt_to_page((void *)addr), order);
5503                 while (used < alloc_end) {
5504                         free_page(used);
5505                         used += PAGE_SIZE;
5506                 }
5507         }
5508         return (void *)addr;
5509 }
5510
5511 /**
5512  * alloc_pages_exact - allocate an exact number physically-contiguous pages.
5513  * @size: the number of bytes to allocate
5514  * @gfp_mask: GFP flags for the allocation, must not contain __GFP_COMP
5515  *
5516  * This function is similar to alloc_pages(), except that it allocates the
5517  * minimum number of pages to satisfy the request.  alloc_pages() can only
5518  * allocate memory in power-of-two pages.
5519  *
5520  * This function is also limited by MAX_ORDER.
5521  *
5522  * Memory allocated by this function must be released by free_pages_exact().
5523  *
5524  * Return: pointer to the allocated area or %NULL in case of error.
5525  */
5526 void *alloc_pages_exact(size_t size, gfp_t gfp_mask)
5527 {
5528         unsigned int order = get_order(size);
5529         unsigned long addr;
5530
5531         if (WARN_ON_ONCE(gfp_mask & __GFP_COMP))
5532                 gfp_mask &= ~__GFP_COMP;
5533
5534         addr = __get_free_pages(gfp_mask, order);
5535         return make_alloc_exact(addr, order, size);
5536 }
5537 EXPORT_SYMBOL(alloc_pages_exact);
5538
5539 /**
5540  * alloc_pages_exact_nid - allocate an exact number of physically-contiguous
5541  *                         pages on a node.
5542  * @nid: the preferred node ID where memory should be allocated
5543  * @size: the number of bytes to allocate
5544  * @gfp_mask: GFP flags for the allocation, must not contain __GFP_COMP
5545  *
5546  * Like alloc_pages_exact(), but try to allocate on node nid first before falling
5547  * back.
5548  *
5549  * Return: pointer to the allocated area or %NULL in case of error.
5550  */
5551 void * __meminit alloc_pages_exact_nid(int nid, size_t size, gfp_t gfp_mask)
5552 {
5553         unsigned int order = get_order(size);
5554         struct page *p;
5555
5556         if (WARN_ON_ONCE(gfp_mask & __GFP_COMP))
5557                 gfp_mask &= ~__GFP_COMP;
5558
5559         p = alloc_pages_node(nid, gfp_mask, order);
5560         if (!p)
5561                 return NULL;
5562         return make_alloc_exact((unsigned long)page_address(p), order, size);
5563 }
5564
5565 /**
5566  * free_pages_exact - release memory allocated via alloc_pages_exact()
5567  * @virt: the value returned by alloc_pages_exact.
5568  * @size: size of allocation, same value as passed to alloc_pages_exact().
5569  *
5570  * Release the memory allocated by a previous call to alloc_pages_exact.
5571  */
5572 void free_pages_exact(void *virt, size_t size)
5573 {
5574         unsigned long addr = (unsigned long)virt;
5575         unsigned long end = addr + PAGE_ALIGN(size);
5576
5577         while (addr < end) {
5578                 free_page(addr);
5579                 addr += PAGE_SIZE;
5580         }
5581 }
5582 EXPORT_SYMBOL(free_pages_exact);
5583
5584 /**
5585  * nr_free_zone_pages - count number of pages beyond high watermark
5586  * @offset: The zone index of the highest zone
5587  *
5588  * nr_free_zone_pages() counts the number of pages which are beyond the
5589  * high watermark within all zones at or below a given zone index.  For each
5590  * zone, the number of pages is calculated as:
5591  *
5592  *     nr_free_zone_pages = managed_pages - high_pages
5593  *
5594  * Return: number of pages beyond high watermark.
5595  */
5596 static unsigned long nr_free_zone_pages(int offset)
5597 {
5598         struct zoneref *z;
5599         struct zone *zone;
5600
5601         /* Just pick one node, since fallback list is circular */
5602         unsigned long sum = 0;
5603
5604         struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL);
5605
5606         for_each_zone_zonelist(zone, z, zonelist, offset) {
5607                 unsigned long size = zone_managed_pages(zone);
5608                 unsigned long high = high_wmark_pages(zone);
5609                 if (size > high)
5610                         sum += size - high;
5611         }
5612
5613         return sum;
5614 }
5615
5616 /**
5617  * nr_free_buffer_pages - count number of pages beyond high watermark
5618  *
5619  * nr_free_buffer_pages() counts the number of pages which are beyond the high
5620  * watermark within ZONE_DMA and ZONE_NORMAL.
5621  *
5622  * Return: number of pages beyond high watermark within ZONE_DMA and
5623  * ZONE_NORMAL.
5624  */
5625 unsigned long nr_free_buffer_pages(void)
5626 {
5627         return nr_free_zone_pages(gfp_zone(GFP_USER));
5628 }
5629 EXPORT_SYMBOL_GPL(nr_free_buffer_pages);
5630
5631 static inline void show_node(struct zone *zone)
5632 {
5633         if (IS_ENABLED(CONFIG_NUMA))
5634                 printk("Node %d ", zone_to_nid(zone));
5635 }
5636
5637 long si_mem_available(void)
5638 {
5639         long available;
5640         unsigned long pagecache;
5641         unsigned long wmark_low = 0;
5642         unsigned long pages[NR_LRU_LISTS];
5643         unsigned long reclaimable;
5644         struct zone *zone;
5645         int lru;
5646
5647         for (lru = LRU_BASE; lru < NR_LRU_LISTS; lru++)
5648                 pages[lru] = global_node_page_state(NR_LRU_BASE + lru);
5649
5650         for_each_zone(zone)
5651                 wmark_low += low_wmark_pages(zone);
5652
5653         /*
5654          * Estimate the amount of memory available for userspace allocations,
5655          * without causing swapping.
5656          */
5657         available = global_zone_page_state(NR_FREE_PAGES) - totalreserve_pages;
5658
5659         /*
5660          * Not all the page cache can be freed, otherwise the system will
5661          * start swapping. Assume at least half of the page cache, or the
5662          * low watermark worth of cache, needs to stay.
5663          */
5664         pagecache = pages[LRU_ACTIVE_FILE] + pages[LRU_INACTIVE_FILE];
5665         pagecache -= min(pagecache / 2, wmark_low);
5666         available += pagecache;
5667
5668         /*
5669          * Part of the reclaimable slab and other kernel memory consists of
5670          * items that are in use, and cannot be freed. Cap this estimate at the
5671          * low watermark.
5672          */
5673         reclaimable = global_node_page_state_pages(NR_SLAB_RECLAIMABLE_B) +
5674                 global_node_page_state(NR_KERNEL_MISC_RECLAIMABLE);
5675         available += reclaimable - min(reclaimable / 2, wmark_low);
5676
5677         if (available < 0)
5678                 available = 0;
5679         return available;
5680 }
5681 EXPORT_SYMBOL_GPL(si_mem_available);
5682
5683 void si_meminfo(struct sysinfo *val)
5684 {
5685         val->totalram = totalram_pages();
5686         val->sharedram = global_node_page_state(NR_SHMEM);
5687         val->freeram = global_zone_page_state(NR_FREE_PAGES);
5688         val->bufferram = nr_blockdev_pages();
5689         val->totalhigh = totalhigh_pages();
5690         val->freehigh = nr_free_highpages();
5691         val->mem_unit = PAGE_SIZE;
5692 }
5693
5694 EXPORT_SYMBOL(si_meminfo);
5695
5696 #ifdef CONFIG_NUMA
5697 void si_meminfo_node(struct sysinfo *val, int nid)
5698 {
5699         int zone_type;          /* needs to be signed */
5700         unsigned long managed_pages = 0;
5701         unsigned long managed_highpages = 0;
5702         unsigned long free_highpages = 0;
5703         pg_data_t *pgdat = NODE_DATA(nid);
5704
5705         for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++)
5706                 managed_pages += zone_managed_pages(&pgdat->node_zones[zone_type]);
5707         val->totalram = managed_pages;
5708         val->sharedram = node_page_state(pgdat, NR_SHMEM);
5709         val->freeram = sum_zone_node_page_state(nid, NR_FREE_PAGES);
5710 #ifdef CONFIG_HIGHMEM
5711         for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
5712                 struct zone *zone = &pgdat->node_zones[zone_type];
5713
5714                 if (is_highmem(zone)) {
5715                         managed_highpages += zone_managed_pages(zone);
5716                         free_highpages += zone_page_state(zone, NR_FREE_PAGES);
5717                 }
5718         }
5719         val->totalhigh = managed_highpages;
5720         val->freehigh = free_highpages;
5721 #else
5722         val->totalhigh = managed_highpages;
5723         val->freehigh = free_highpages;
5724 #endif
5725         val->mem_unit = PAGE_SIZE;
5726 }
5727 #endif
5728
5729 /*
5730  * Determine whether the node should be displayed or not, depending on whether
5731  * SHOW_MEM_FILTER_NODES was passed to show_free_areas().
5732  */
5733 static bool show_mem_node_skip(unsigned int flags, int nid, nodemask_t *nodemask)
5734 {
5735         if (!(flags & SHOW_MEM_FILTER_NODES))
5736                 return false;
5737
5738         /*
5739          * no node mask - aka implicit memory numa policy. Do not bother with
5740          * the synchronization - read_mems_allowed_begin - because we do not
5741          * have to be precise here.
5742          */
5743         if (!nodemask)
5744                 nodemask = &cpuset_current_mems_allowed;
5745
5746         return !node_isset(nid, *nodemask);
5747 }
5748
5749 #define K(x) ((x) << (PAGE_SHIFT-10))
5750
5751 static void show_migration_types(unsigned char type)
5752 {
5753         static const char types[MIGRATE_TYPES] = {
5754                 [MIGRATE_UNMOVABLE]     = 'U',
5755                 [MIGRATE_MOVABLE]       = 'M',
5756                 [MIGRATE_RECLAIMABLE]   = 'E',
5757                 [MIGRATE_HIGHATOMIC]    = 'H',
5758 #ifdef CONFIG_CMA
5759                 [MIGRATE_CMA]           = 'C',
5760 #endif
5761 #ifdef CONFIG_MEMORY_ISOLATION
5762                 [MIGRATE_ISOLATE]       = 'I',
5763 #endif
5764         };
5765         char tmp[MIGRATE_TYPES + 1];
5766         char *p = tmp;
5767         int i;
5768
5769         for (i = 0; i < MIGRATE_TYPES; i++) {
5770                 if (type & (1 << i))
5771                         *p++ = types[i];
5772         }
5773
5774         *p = '\0';
5775         printk(KERN_CONT "(%s) ", tmp);
5776 }
5777
5778 /*
5779  * Show free area list (used inside shift_scroll-lock stuff)
5780  * We also calculate the percentage fragmentation. We do this by counting the
5781  * memory on each free list with the exception of the first item on the list.
5782  *
5783  * Bits in @filter:
5784  * SHOW_MEM_FILTER_NODES: suppress nodes that are not allowed by current's
5785  *   cpuset.
5786  */
5787 void show_free_areas(unsigned int filter, nodemask_t *nodemask)
5788 {
5789         unsigned long free_pcp = 0;
5790         int cpu;
5791         struct zone *zone;
5792         pg_data_t *pgdat;
5793
5794         for_each_populated_zone(zone) {
5795                 if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask))
5796                         continue;
5797
5798                 for_each_online_cpu(cpu)
5799                         free_pcp += per_cpu_ptr(zone->per_cpu_pageset, cpu)->count;
5800         }
5801
5802         printk("active_anon:%lu inactive_anon:%lu isolated_anon:%lu\n"
5803                 " active_file:%lu inactive_file:%lu isolated_file:%lu\n"
5804                 " unevictable:%lu dirty:%lu writeback:%lu\n"
5805                 " slab_reclaimable:%lu slab_unreclaimable:%lu\n"
5806                 " mapped:%lu shmem:%lu pagetables:%lu bounce:%lu\n"
5807                 " free:%lu free_pcp:%lu free_cma:%lu\n",
5808                 global_node_page_state(NR_ACTIVE_ANON),
5809                 global_node_page_state(NR_INACTIVE_ANON),
5810                 global_node_page_state(NR_ISOLATED_ANON),
5811                 global_node_page_state(NR_ACTIVE_FILE),
5812                 global_node_page_state(NR_INACTIVE_FILE),
5813                 global_node_page_state(NR_ISOLATED_FILE),
5814                 global_node_page_state(NR_UNEVICTABLE),
5815                 global_node_page_state(NR_FILE_DIRTY),
5816                 global_node_page_state(NR_WRITEBACK),
5817                 global_node_page_state_pages(NR_SLAB_RECLAIMABLE_B),
5818                 global_node_page_state_pages(NR_SLAB_UNRECLAIMABLE_B),
5819                 global_node_page_state(NR_FILE_MAPPED),
5820                 global_node_page_state(NR_SHMEM),
5821                 global_node_page_state(NR_PAGETABLE),
5822                 global_zone_page_state(NR_BOUNCE),
5823                 global_zone_page_state(NR_FREE_PAGES),
5824                 free_pcp,
5825                 global_zone_page_state(NR_FREE_CMA_PAGES));
5826
5827         for_each_online_pgdat(pgdat) {
5828                 if (show_mem_node_skip(filter, pgdat->node_id, nodemask))
5829                         continue;
5830
5831                 printk("Node %d"
5832                         " active_anon:%lukB"
5833                         " inactive_anon:%lukB"
5834                         " active_file:%lukB"
5835                         " inactive_file:%lukB"
5836                         " unevictable:%lukB"
5837                         " isolated(anon):%lukB"
5838                         " isolated(file):%lukB"
5839                         " mapped:%lukB"
5840                         " dirty:%lukB"
5841                         " writeback:%lukB"
5842                         " shmem:%lukB"
5843 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5844                         " shmem_thp: %lukB"
5845                         " shmem_pmdmapped: %lukB"
5846                         " anon_thp: %lukB"
5847 #endif
5848                         " writeback_tmp:%lukB"
5849                         " kernel_stack:%lukB"
5850 #ifdef CONFIG_SHADOW_CALL_STACK
5851                         " shadow_call_stack:%lukB"
5852 #endif
5853                         " pagetables:%lukB"
5854                         " all_unreclaimable? %s"
5855                         "\n",
5856                         pgdat->node_id,
5857                         K(node_page_state(pgdat, NR_ACTIVE_ANON)),
5858                         K(node_page_state(pgdat, NR_INACTIVE_ANON)),
5859                         K(node_page_state(pgdat, NR_ACTIVE_FILE)),
5860                         K(node_page_state(pgdat, NR_INACTIVE_FILE)),
5861                         K(node_page_state(pgdat, NR_UNEVICTABLE)),
5862                         K(node_page_state(pgdat, NR_ISOLATED_ANON)),
5863                         K(node_page_state(pgdat, NR_ISOLATED_FILE)),
5864                         K(node_page_state(pgdat, NR_FILE_MAPPED)),
5865                         K(node_page_state(pgdat, NR_FILE_DIRTY)),
5866                         K(node_page_state(pgdat, NR_WRITEBACK)),
5867                         K(node_page_state(pgdat, NR_SHMEM)),
5868 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5869                         K(node_page_state(pgdat, NR_SHMEM_THPS)),
5870                         K(node_page_state(pgdat, NR_SHMEM_PMDMAPPED)),
5871                         K(node_page_state(pgdat, NR_ANON_THPS)),
5872 #endif
5873                         K(node_page_state(pgdat, NR_WRITEBACK_TEMP)),
5874                         node_page_state(pgdat, NR_KERNEL_STACK_KB),
5875 #ifdef CONFIG_SHADOW_CALL_STACK
5876                         node_page_state(pgdat, NR_KERNEL_SCS_KB),
5877 #endif
5878                         K(node_page_state(pgdat, NR_PAGETABLE)),
5879                         pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ?
5880                                 "yes" : "no");
5881         }
5882
5883         for_each_populated_zone(zone) {
5884                 int i;
5885
5886                 if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask))
5887                         continue;
5888
5889                 free_pcp = 0;
5890                 for_each_online_cpu(cpu)
5891                         free_pcp += per_cpu_ptr(zone->per_cpu_pageset, cpu)->count;
5892
5893                 show_node(zone);
5894                 printk(KERN_CONT
5895                         "%s"
5896                         " free:%lukB"
5897                         " min:%lukB"
5898                         " low:%lukB"
5899                         " high:%lukB"
5900                         " reserved_highatomic:%luKB"
5901                         " active_anon:%lukB"
5902                         " inactive_anon:%lukB"
5903                         " active_file:%lukB"
5904                         " inactive_file:%lukB"
5905                         " unevictable:%lukB"
5906                         " writepending:%lukB"
5907                         " present:%lukB"
5908                         " managed:%lukB"
5909                         " mlocked:%lukB"
5910                         " bounce:%lukB"
5911                         " free_pcp:%lukB"
5912                         " local_pcp:%ukB"
5913                         " free_cma:%lukB"
5914                         "\n",
5915                         zone->name,
5916                         K(zone_page_state(zone, NR_FREE_PAGES)),
5917                         K(min_wmark_pages(zone)),
5918                         K(low_wmark_pages(zone)),
5919                         K(high_wmark_pages(zone)),
5920                         K(zone->nr_reserved_highatomic),
5921                         K(zone_page_state(zone, NR_ZONE_ACTIVE_ANON)),
5922                         K(zone_page_state(zone, NR_ZONE_INACTIVE_ANON)),
5923                         K(zone_page_state(zone, NR_ZONE_ACTIVE_FILE)),
5924                         K(zone_page_state(zone, NR_ZONE_INACTIVE_FILE)),
5925                         K(zone_page_state(zone, NR_ZONE_UNEVICTABLE)),
5926                         K(zone_page_state(zone, NR_ZONE_WRITE_PENDING)),
5927                         K(zone->present_pages),
5928                         K(zone_managed_pages(zone)),
5929                         K(zone_page_state(zone, NR_MLOCK)),
5930                         K(zone_page_state(zone, NR_BOUNCE)),
5931                         K(free_pcp),
5932                         K(this_cpu_read(zone->per_cpu_pageset->count)),
5933                         K(zone_page_state(zone, NR_FREE_CMA_PAGES)));
5934                 printk("lowmem_reserve[]:");
5935                 for (i = 0; i < MAX_NR_ZONES; i++)
5936                         printk(KERN_CONT " %ld", zone->lowmem_reserve[i]);
5937                 printk(KERN_CONT "\n");
5938         }
5939
5940         for_each_populated_zone(zone) {
5941                 unsigned int order;
5942                 unsigned long nr[MAX_ORDER], flags, total = 0;
5943                 unsigned char types[MAX_ORDER];
5944
5945                 if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask))
5946                         continue;
5947                 show_node(zone);
5948                 printk(KERN_CONT "%s: ", zone->name);
5949
5950                 spin_lock_irqsave(&zone->lock, flags);
5951                 for (order = 0; order < MAX_ORDER; order++) {
5952                         struct free_area *area = &zone->free_area[order];
5953                         int type;
5954
5955                         nr[order] = area->nr_free;
5956                         total += nr[order] << order;
5957
5958                         types[order] = 0;
5959                         for (type = 0; type < MIGRATE_TYPES; type++) {
5960                                 if (!free_area_empty(area, type))
5961                                         types[order] |= 1 << type;
5962                         }
5963                 }
5964                 spin_unlock_irqrestore(&zone->lock, flags);
5965                 for (order = 0; order < MAX_ORDER; order++) {
5966                         printk(KERN_CONT "%lu*%lukB ",
5967                                nr[order], K(1UL) << order);
5968                         if (nr[order])
5969                                 show_migration_types(types[order]);
5970                 }
5971                 printk(KERN_CONT "= %lukB\n", K(total));
5972         }
5973
5974         hugetlb_show_meminfo();
5975
5976         printk("%ld total pagecache pages\n", global_node_page_state(NR_FILE_PAGES));
5977
5978         show_swap_cache_info();
5979 }
5980
5981 static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref)
5982 {
5983         zoneref->zone = zone;
5984         zoneref->zone_idx = zone_idx(zone);
5985 }
5986
5987 /*
5988  * Builds allocation fallback zone lists.
5989  *
5990  * Add all populated zones of a node to the zonelist.
5991  */
5992 static int build_zonerefs_node(pg_data_t *pgdat, struct zoneref *zonerefs)
5993 {
5994         struct zone *zone;
5995         enum zone_type zone_type = MAX_NR_ZONES;
5996         int nr_zones = 0;
5997
5998         do {
5999                 zone_type--;
6000                 zone = pgdat->node_zones + zone_type;
6001                 if (managed_zone(zone)) {
6002                         zoneref_set_zone(zone, &zonerefs[nr_zones++]);
6003                         check_highest_zone(zone_type);
6004                 }
6005         } while (zone_type);
6006
6007         return nr_zones;
6008 }
6009
6010 #ifdef CONFIG_NUMA
6011
6012 static int __parse_numa_zonelist_order(char *s)
6013 {
6014         /*
6015          * We used to support different zonelists modes but they turned
6016          * out to be just not useful. Let's keep the warning in place
6017          * if somebody still use the cmd line parameter so that we do
6018          * not fail it silently
6019          */
6020         if (!(*s == 'd' || *s == 'D' || *s == 'n' || *s == 'N')) {
6021                 pr_warn("Ignoring unsupported numa_zonelist_order value:  %s\n", s);
6022                 return -EINVAL;
6023         }
6024         return 0;
6025 }
6026
6027 char numa_zonelist_order[] = "Node";
6028
6029 /*
6030  * sysctl handler for numa_zonelist_order
6031  */
6032 int numa_zonelist_order_handler(struct ctl_table *table, int write,
6033                 void *buffer, size_t *length, loff_t *ppos)
6034 {
6035         if (write)
6036                 return __parse_numa_zonelist_order(buffer);
6037         return proc_dostring(table, write, buffer, length, ppos);
6038 }
6039
6040
6041 #define MAX_NODE_LOAD (nr_online_nodes)
6042 static int node_load[MAX_NUMNODES];
6043
6044 /**
6045  * find_next_best_node - find the next node that should appear in a given node's fallback list
6046  * @node: node whose fallback list we're appending
6047  * @used_node_mask: nodemask_t of already used nodes
6048  *
6049  * We use a number of factors to determine which is the next node that should
6050  * appear on a given node's fallback list.  The node should not have appeared
6051  * already in @node's fallback list, and it should be the next closest node
6052  * according to the distance array (which contains arbitrary distance values
6053  * from each node to each node in the system), and should also prefer nodes
6054  * with no CPUs, since presumably they'll have very little allocation pressure
6055  * on them otherwise.
6056  *
6057  * Return: node id of the found node or %NUMA_NO_NODE if no node is found.
6058  */
6059 static int find_next_best_node(int node, nodemask_t *used_node_mask)
6060 {
6061         int n, val;
6062         int min_val = INT_MAX;
6063         int best_node = NUMA_NO_NODE;
6064
6065         /* Use the local node if we haven't already */
6066         if (!node_isset(node, *used_node_mask)) {
6067                 node_set(node, *used_node_mask);
6068                 return node;
6069         }
6070
6071         for_each_node_state(n, N_MEMORY) {
6072
6073                 /* Don't want a node to appear more than once */
6074                 if (node_isset(n, *used_node_mask))
6075                         continue;
6076
6077                 /* Use the distance array to find the distance */
6078                 val = node_distance(node, n);
6079
6080                 /* Penalize nodes under us ("prefer the next node") */
6081                 val += (n < node);
6082
6083                 /* Give preference to headless and unused nodes */
6084                 if (!cpumask_empty(cpumask_of_node(n)))
6085                         val += PENALTY_FOR_NODE_WITH_CPUS;
6086
6087                 /* Slight preference for less loaded node */
6088                 val *= (MAX_NODE_LOAD*MAX_NUMNODES);
6089                 val += node_load[n];
6090
6091                 if (val < min_val) {
6092                         min_val = val;
6093                         best_node = n;
6094                 }
6095         }
6096
6097         if (best_node >= 0)
6098                 node_set(best_node, *used_node_mask);
6099
6100         return best_node;
6101 }
6102
6103
6104 /*
6105  * Build zonelists ordered by node and zones within node.
6106  * This results in maximum locality--normal zone overflows into local
6107  * DMA zone, if any--but risks exhausting DMA zone.
6108  */
6109 static void build_zonelists_in_node_order(pg_data_t *pgdat, int *node_order,
6110                 unsigned nr_nodes)
6111 {
6112         struct zoneref *zonerefs;
6113         int i;
6114
6115         zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs;
6116
6117         for (i = 0; i < nr_nodes; i++) {
6118                 int nr_zones;
6119
6120                 pg_data_t *node = NODE_DATA(node_order[i]);
6121
6122                 nr_zones = build_zonerefs_node(node, zonerefs);
6123                 zonerefs += nr_zones;
6124         }
6125         zonerefs->zone = NULL;
6126         zonerefs->zone_idx = 0;
6127 }
6128
6129 /*
6130  * Build gfp_thisnode zonelists
6131  */
6132 static void build_thisnode_zonelists(pg_data_t *pgdat)
6133 {
6134         struct zoneref *zonerefs;
6135         int nr_zones;
6136
6137         zonerefs = pgdat->node_zonelists[ZONELIST_NOFALLBACK]._zonerefs;
6138         nr_zones = build_zonerefs_node(pgdat, zonerefs);
6139         zonerefs += nr_zones;
6140         zonerefs->zone = NULL;
6141         zonerefs->zone_idx = 0;
6142 }
6143
6144 /*
6145  * Build zonelists ordered by zone and nodes within zones.
6146  * This results in conserving DMA zone[s] until all Normal memory is
6147  * exhausted, but results in overflowing to remote node while memory
6148  * may still exist in local DMA zone.
6149  */
6150
6151 static void build_zonelists(pg_data_t *pgdat)
6152 {
6153         static int node_order[MAX_NUMNODES];
6154         int node, load, nr_nodes = 0;
6155         nodemask_t used_mask = NODE_MASK_NONE;
6156         int local_node, prev_node;
6157
6158         /* NUMA-aware ordering of nodes */
6159         local_node = pgdat->node_id;
6160         load = nr_online_nodes;
6161         prev_node = local_node;
6162
6163         memset(node_order, 0, sizeof(node_order));
6164         while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
6165                 /*
6166                  * We don't want to pressure a particular node.
6167                  * So adding penalty to the first node in same
6168                  * distance group to make it round-robin.
6169                  */
6170                 if (node_distance(local_node, node) !=
6171                     node_distance(local_node, prev_node))
6172                         node_load[node] = load;
6173
6174                 node_order[nr_nodes++] = node;
6175                 prev_node = node;
6176                 load--;
6177         }
6178
6179         build_zonelists_in_node_order(pgdat, node_order, nr_nodes);
6180         build_thisnode_zonelists(pgdat);
6181 }
6182
6183 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
6184 /*
6185  * Return node id of node used for "local" allocations.
6186  * I.e., first node id of first zone in arg node's generic zonelist.
6187  * Used for initializing percpu 'numa_mem', which is used primarily
6188  * for kernel allocations, so use GFP_KERNEL flags to locate zonelist.
6189  */
6190 int local_memory_node(int node)
6191 {
6192         struct zoneref *z;
6193
6194         z = first_zones_zonelist(node_zonelist(node, GFP_KERNEL),
6195                                    gfp_zone(GFP_KERNEL),
6196                                    NULL);
6197         return zone_to_nid(z->zone);
6198 }
6199 #endif
6200
6201 static void setup_min_unmapped_ratio(void);
6202 static void setup_min_slab_ratio(void);
6203 #else   /* CONFIG_NUMA */
6204
6205 static void build_zonelists(pg_data_t *pgdat)
6206 {
6207         int node, local_node;
6208         struct zoneref *zonerefs;
6209         int nr_zones;
6210
6211         local_node = pgdat->node_id;
6212
6213         zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs;
6214         nr_zones = build_zonerefs_node(pgdat, zonerefs);
6215         zonerefs += nr_zones;
6216
6217         /*
6218          * Now we build the zonelist so that it contains the zones
6219          * of all the other nodes.
6220          * We don't want to pressure a particular node, so when
6221          * building the zones for node N, we make sure that the
6222          * zones coming right after the local ones are those from
6223          * node N+1 (modulo N)
6224          */
6225         for (node = local_node + 1; node < MAX_NUMNODES; node++) {
6226                 if (!node_online(node))
6227                         continue;
6228                 nr_zones = build_zonerefs_node(NODE_DATA(node), zonerefs);
6229                 zonerefs += nr_zones;
6230         }
6231         for (node = 0; node < local_node; node++) {
6232                 if (!node_online(node))
6233                         continue;
6234                 nr_zones = build_zonerefs_node(NODE_DATA(node), zonerefs);
6235                 zonerefs += nr_zones;
6236         }
6237
6238         zonerefs->zone = NULL;
6239         zonerefs->zone_idx = 0;
6240 }
6241
6242 #endif  /* CONFIG_NUMA */
6243
6244 /*
6245  * Boot pageset table. One per cpu which is going to be used for all
6246  * zones and all nodes. The parameters will be set in such a way
6247  * that an item put on a list will immediately be handed over to
6248  * the buddy list. This is safe since pageset manipulation is done
6249  * with interrupts disabled.
6250  *
6251  * The boot_pagesets must be kept even after bootup is complete for
6252  * unused processors and/or zones. They do play a role for bootstrapping
6253  * hotplugged processors.
6254  *
6255  * zoneinfo_show() and maybe other functions do
6256  * not check if the processor is online before following the pageset pointer.
6257  * Other parts of the kernel may not check if the zone is available.
6258  */
6259 static void per_cpu_pages_init(struct per_cpu_pages *pcp, struct per_cpu_zonestat *pzstats);
6260 /* These effectively disable the pcplists in the boot pageset completely */
6261 #define BOOT_PAGESET_HIGH       0
6262 #define BOOT_PAGESET_BATCH      1
6263 static DEFINE_PER_CPU(struct per_cpu_pages, boot_pageset);
6264 static DEFINE_PER_CPU(struct per_cpu_zonestat, boot_zonestats);
6265 static DEFINE_PER_CPU(struct per_cpu_nodestat, boot_nodestats);
6266
6267 static void __build_all_zonelists(void *data)
6268 {
6269         int nid;
6270         int __maybe_unused cpu;
6271         pg_data_t *self = data;
6272         static DEFINE_SPINLOCK(lock);
6273
6274         spin_lock(&lock);
6275
6276 #ifdef CONFIG_NUMA
6277         memset(node_load, 0, sizeof(node_load));
6278 #endif
6279
6280         /*
6281          * This node is hotadded and no memory is yet present.   So just
6282          * building zonelists is fine - no need to touch other nodes.
6283          */
6284         if (self && !node_online(self->node_id)) {
6285                 build_zonelists(self);
6286         } else {
6287                 for_each_online_node(nid) {
6288                         pg_data_t *pgdat = NODE_DATA(nid);
6289
6290                         build_zonelists(pgdat);
6291                 }
6292
6293 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
6294                 /*
6295                  * We now know the "local memory node" for each node--
6296                  * i.e., the node of the first zone in the generic zonelist.
6297                  * Set up numa_mem percpu variable for on-line cpus.  During
6298                  * boot, only the boot cpu should be on-line;  we'll init the
6299                  * secondary cpus' numa_mem as they come on-line.  During
6300                  * node/memory hotplug, we'll fixup all on-line cpus.
6301                  */
6302                 for_each_online_cpu(cpu)
6303                         set_cpu_numa_mem(cpu, local_memory_node(cpu_to_node(cpu)));
6304 #endif
6305         }
6306
6307         spin_unlock(&lock);
6308 }
6309
6310 static noinline void __init
6311 build_all_zonelists_init(void)
6312 {
6313         int cpu;
6314
6315         __build_all_zonelists(NULL);
6316
6317         /*
6318          * Initialize the boot_pagesets that are going to be used
6319          * for bootstrapping processors. The real pagesets for
6320          * each zone will be allocated later when the per cpu
6321          * allocator is available.
6322          *
6323          * boot_pagesets are used also for bootstrapping offline
6324          * cpus if the system is already booted because the pagesets
6325          * are needed to initialize allocators on a specific cpu too.
6326          * F.e. the percpu allocator needs the page allocator which
6327          * needs the percpu allocator in order to allocate its pagesets
6328          * (a chicken-egg dilemma).
6329          */
6330         for_each_possible_cpu(cpu)
6331                 per_cpu_pages_init(&per_cpu(boot_pageset, cpu), &per_cpu(boot_zonestats, cpu));
6332
6333         mminit_verify_zonelist();
6334         cpuset_init_current_mems_allowed();
6335 }
6336
6337 /*
6338  * unless system_state == SYSTEM_BOOTING.
6339  *
6340  * __ref due to call of __init annotated helper build_all_zonelists_init
6341  * [protected by SYSTEM_BOOTING].
6342  */
6343 void __ref build_all_zonelists(pg_data_t *pgdat)
6344 {
6345         unsigned long vm_total_pages;
6346
6347         if (system_state == SYSTEM_BOOTING) {
6348                 build_all_zonelists_init();
6349         } else {
6350                 __build_all_zonelists(pgdat);
6351                 /* cpuset refresh routine should be here */
6352         }
6353         /* Get the number of free pages beyond high watermark in all zones. */
6354         vm_total_pages = nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE));
6355         /*
6356          * Disable grouping by mobility if the number of pages in the
6357          * system is too low to allow the mechanism to work. It would be
6358          * more accurate, but expensive to check per-zone. This check is
6359          * made on memory-hotadd so a system can start with mobility
6360          * disabled and enable it later
6361          */
6362         if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES))
6363                 page_group_by_mobility_disabled = 1;
6364         else
6365                 page_group_by_mobility_disabled = 0;
6366
6367         pr_info("Built %u zonelists, mobility grouping %s.  Total pages: %ld\n",
6368                 nr_online_nodes,
6369                 page_group_by_mobility_disabled ? "off" : "on",
6370                 vm_total_pages);
6371 #ifdef CONFIG_NUMA
6372         pr_info("Policy zone: %s\n", zone_names[policy_zone]);
6373 #endif
6374 }
6375
6376 /* If zone is ZONE_MOVABLE but memory is mirrored, it is an overlapped init */
6377 static bool __meminit
6378 overlap_memmap_init(unsigned long zone, unsigned long *pfn)
6379 {
6380         static struct memblock_region *r;
6381
6382         if (mirrored_kernelcore && zone == ZONE_MOVABLE) {
6383                 if (!r || *pfn >= memblock_region_memory_end_pfn(r)) {
6384                         for_each_mem_region(r) {
6385                                 if (*pfn < memblock_region_memory_end_pfn(r))
6386                                         break;
6387                         }
6388                 }
6389                 if (*pfn >= memblock_region_memory_base_pfn(r) &&
6390                     memblock_is_mirror(r)) {
6391                         *pfn = memblock_region_memory_end_pfn(r);
6392                         return true;
6393                 }
6394         }
6395         return false;
6396 }
6397
6398 /*
6399  * Initially all pages are reserved - free ones are freed
6400  * up by memblock_free_all() once the early boot process is
6401  * done. Non-atomic initialization, single-pass.
6402  *
6403  * All aligned pageblocks are initialized to the specified migratetype
6404  * (usually MIGRATE_MOVABLE). Besides setting the migratetype, no related
6405  * zone stats (e.g., nr_isolate_pageblock) are touched.
6406  */
6407 void __meminit memmap_init_range(unsigned long size, int nid, unsigned long zone,
6408                 unsigned long start_pfn, unsigned long zone_end_pfn,
6409                 enum meminit_context context,
6410                 struct vmem_altmap *altmap, int migratetype)
6411 {
6412         unsigned long pfn, end_pfn = start_pfn + size;
6413         struct page *page;
6414
6415         if (highest_memmap_pfn < end_pfn - 1)
6416                 highest_memmap_pfn = end_pfn - 1;
6417
6418 #ifdef CONFIG_ZONE_DEVICE
6419         /*
6420          * Honor reservation requested by the driver for this ZONE_DEVICE
6421          * memory. We limit the total number of pages to initialize to just
6422          * those that might contain the memory mapping. We will defer the
6423          * ZONE_DEVICE page initialization until after we have released
6424          * the hotplug lock.
6425          */
6426         if (zone == ZONE_DEVICE) {
6427                 if (!altmap)
6428                         return;
6429
6430                 if (start_pfn == altmap->base_pfn)
6431                         start_pfn += altmap->reserve;
6432                 end_pfn = altmap->base_pfn + vmem_altmap_offset(altmap);
6433         }
6434 #endif
6435
6436         for (pfn = start_pfn; pfn < end_pfn; ) {
6437                 /*
6438                  * There can be holes in boot-time mem_map[]s handed to this
6439                  * function.  They do not exist on hotplugged memory.
6440                  */
6441                 if (context == MEMINIT_EARLY) {
6442                         if (overlap_memmap_init(zone, &pfn))
6443                                 continue;
6444                         if (defer_init(nid, pfn, zone_end_pfn))
6445                                 break;
6446                 }
6447
6448                 page = pfn_to_page(pfn);
6449                 __init_single_page(page, pfn, zone, nid);
6450                 if (context == MEMINIT_HOTPLUG)
6451                         __SetPageReserved(page);
6452
6453                 /*
6454                  * Usually, we want to mark the pageblock MIGRATE_MOVABLE,
6455                  * such that unmovable allocations won't be scattered all
6456                  * over the place during system boot.
6457                  */
6458                 if (IS_ALIGNED(pfn, pageblock_nr_pages)) {
6459                         set_pageblock_migratetype(page, migratetype);
6460                         cond_resched();
6461                 }
6462                 pfn++;
6463         }
6464 }
6465
6466 #ifdef CONFIG_ZONE_DEVICE
6467 void __ref memmap_init_zone_device(struct zone *zone,
6468                                    unsigned long start_pfn,
6469                                    unsigned long nr_pages,
6470                                    struct dev_pagemap *pgmap)
6471 {
6472         unsigned long pfn, end_pfn = start_pfn + nr_pages;
6473         struct pglist_data *pgdat = zone->zone_pgdat;
6474         struct vmem_altmap *altmap = pgmap_altmap(pgmap);
6475         unsigned long zone_idx = zone_idx(zone);
6476         unsigned long start = jiffies;
6477         int nid = pgdat->node_id;
6478
6479         if (WARN_ON_ONCE(!pgmap || zone_idx(zone) != ZONE_DEVICE))
6480                 return;
6481
6482         /*
6483          * The call to memmap_init should have already taken care
6484          * of the pages reserved for the memmap, so we can just jump to
6485          * the end of that region and start processing the device pages.
6486          */
6487         if (altmap) {
6488                 start_pfn = altmap->base_pfn + vmem_altmap_offset(altmap);
6489                 nr_pages = end_pfn - start_pfn;
6490         }
6491
6492         for (pfn = start_pfn; pfn < end_pfn; pfn++) {
6493                 struct page *page = pfn_to_page(pfn);
6494
6495                 __init_single_page(page, pfn, zone_idx, nid);
6496
6497                 /*
6498                  * Mark page reserved as it will need to wait for onlining
6499                  * phase for it to be fully associated with a zone.
6500                  *
6501                  * We can use the non-atomic __set_bit operation for setting
6502                  * the flag as we are still initializing the pages.
6503                  */
6504                 __SetPageReserved(page);
6505
6506                 /*
6507                  * ZONE_DEVICE pages union ->lru with a ->pgmap back pointer
6508                  * and zone_device_data.  It is a bug if a ZONE_DEVICE page is
6509                  * ever freed or placed on a driver-private list.
6510                  */
6511                 page->pgmap = pgmap;
6512                 page->zone_device_data = NULL;
6513
6514                 /*
6515                  * Mark the block movable so that blocks are reserved for
6516                  * movable at startup. This will force kernel allocations
6517                  * to reserve their blocks rather than leaking throughout
6518                  * the address space during boot when many long-lived
6519                  * kernel allocations are made.
6520                  *
6521                  * Please note that MEMINIT_HOTPLUG path doesn't clear memmap
6522                  * because this is done early in section_activate()
6523                  */
6524                 if (IS_ALIGNED(pfn, pageblock_nr_pages)) {
6525                         set_pageblock_migratetype(page, MIGRATE_MOVABLE);
6526                         cond_resched();
6527                 }
6528         }
6529
6530         pr_info("%s initialised %lu pages in %ums\n", __func__,
6531                 nr_pages, jiffies_to_msecs(jiffies - start));
6532 }
6533
6534 #endif
6535 static void __meminit zone_init_free_lists(struct zone *zone)
6536 {
6537         unsigned int order, t;
6538         for_each_migratetype_order(order, t) {
6539                 INIT_LIST_HEAD(&zone->free_area[order].free_list[t]);
6540                 zone->free_area[order].nr_free = 0;
6541         }
6542 }
6543
6544 #if !defined(CONFIG_FLAT_NODE_MEM_MAP)
6545 /*
6546  * Only struct pages that correspond to ranges defined by memblock.memory
6547  * are zeroed and initialized by going through __init_single_page() during
6548  * memmap_init_zone_range().
6549  *
6550  * But, there could be struct pages that correspond to holes in
6551  * memblock.memory. This can happen because of the following reasons:
6552  * - physical memory bank size is not necessarily the exact multiple of the
6553  *   arbitrary section size
6554  * - early reserved memory may not be listed in memblock.memory
6555  * - memory layouts defined with memmap= kernel parameter may not align
6556  *   nicely with memmap sections
6557  *
6558  * Explicitly initialize those struct pages so that:
6559  * - PG_Reserved is set
6560  * - zone and node links point to zone and node that span the page if the
6561  *   hole is in the middle of a zone
6562  * - zone and node links point to adjacent zone/node if the hole falls on
6563  *   the zone boundary; the pages in such holes will be prepended to the
6564  *   zone/node above the hole except for the trailing pages in the last
6565  *   section that will be appended to the zone/node below.
6566  */
6567 static void __init init_unavailable_range(unsigned long spfn,
6568                                           unsigned long epfn,
6569                                           int zone, int node)
6570 {
6571         unsigned long pfn;
6572         u64 pgcnt = 0;
6573
6574         for (pfn = spfn; pfn < epfn; pfn++) {
6575                 if (!pfn_valid(ALIGN_DOWN(pfn, pageblock_nr_pages))) {
6576                         pfn = ALIGN_DOWN(pfn, pageblock_nr_pages)
6577                                 + pageblock_nr_pages - 1;
6578                         continue;
6579                 }
6580                 __init_single_page(pfn_to_page(pfn), pfn, zone, node);
6581                 __SetPageReserved(pfn_to_page(pfn));
6582                 pgcnt++;
6583         }
6584
6585         if (pgcnt)
6586                 pr_info("On node %d, zone %s: %lld pages in unavailable ranges",
6587                         node, zone_names[zone], pgcnt);
6588 }
6589 #else
6590 static inline void init_unavailable_range(unsigned long spfn,
6591                                           unsigned long epfn,
6592                                           int zone, int node)
6593 {
6594 }
6595 #endif
6596
6597 static void __init memmap_init_zone_range(struct zone *zone,
6598                                           unsigned long start_pfn,
6599                                           unsigned long end_pfn,
6600                                           unsigned long *hole_pfn)
6601 {
6602         unsigned long zone_start_pfn = zone->zone_start_pfn;
6603         unsigned long zone_end_pfn = zone_start_pfn + zone->spanned_pages;
6604         int nid = zone_to_nid(zone), zone_id = zone_idx(zone);
6605
6606         start_pfn = clamp(start_pfn, zone_start_pfn, zone_end_pfn);
6607         end_pfn = clamp(end_pfn, zone_start_pfn, zone_end_pfn);
6608
6609         if (start_pfn >= end_pfn)
6610                 return;
6611
6612         memmap_init_range(end_pfn - start_pfn, nid, zone_id, start_pfn,
6613                           zone_end_pfn, MEMINIT_EARLY, NULL, MIGRATE_MOVABLE);
6614
6615         if (*hole_pfn < start_pfn)
6616                 init_unavailable_range(*hole_pfn, start_pfn, zone_id, nid);
6617
6618         *hole_pfn = end_pfn;
6619 }
6620
6621 static void __init memmap_init(void)
6622 {
6623         unsigned long start_pfn, end_pfn;
6624         unsigned long hole_pfn = 0;
6625         int i, j, zone_id, nid;
6626
6627         for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
6628                 struct pglist_data *node = NODE_DATA(nid);
6629
6630                 for (j = 0; j < MAX_NR_ZONES; j++) {
6631                         struct zone *zone = node->node_zones + j;
6632
6633                         if (!populated_zone(zone))
6634                                 continue;
6635
6636                         memmap_init_zone_range(zone, start_pfn, end_pfn,
6637                                                &hole_pfn);
6638                         zone_id = j;
6639                 }
6640         }
6641
6642 #ifdef CONFIG_SPARSEMEM
6643         /*
6644          * Initialize the memory map for hole in the range [memory_end,
6645          * section_end].
6646          * Append the pages in this hole to the highest zone in the last
6647          * node.
6648          * The call to init_unavailable_range() is outside the ifdef to
6649          * silence the compiler warining about zone_id set but not used;
6650          * for FLATMEM it is a nop anyway
6651          */
6652         end_pfn = round_up(end_pfn, PAGES_PER_SECTION);
6653         if (hole_pfn < end_pfn)
6654 #endif
6655                 init_unavailable_range(hole_pfn, end_pfn, zone_id, nid);
6656 }
6657
6658 static int zone_batchsize(struct zone *zone)
6659 {
6660 #ifdef CONFIG_MMU
6661         int batch;
6662
6663         /*
6664          * The number of pages to batch allocate is either ~0.1%
6665          * of the zone or 1MB, whichever is smaller. The batch
6666          * size is striking a balance between allocation latency
6667          * and zone lock contention.
6668          */
6669         batch = min(zone_managed_pages(zone) >> 10, (1024 * 1024) / PAGE_SIZE);
6670         batch /= 4;             /* We effectively *= 4 below */
6671         if (batch < 1)
6672                 batch = 1;
6673
6674         /*
6675          * Clamp the batch to a 2^n - 1 value. Having a power
6676          * of 2 value was found to be more likely to have
6677          * suboptimal cache aliasing properties in some cases.
6678          *
6679          * For example if 2 tasks are alternately allocating
6680          * batches of pages, one task can end up with a lot
6681          * of pages of one half of the possible page colors
6682          * and the other with pages of the other colors.
6683          */
6684         batch = rounddown_pow_of_two(batch + batch/2) - 1;
6685
6686         return batch;
6687
6688 #else
6689         /* The deferral and batching of frees should be suppressed under NOMMU
6690          * conditions.
6691          *
6692          * The problem is that NOMMU needs to be able to allocate large chunks
6693          * of contiguous memory as there's no hardware page translation to
6694          * assemble apparent contiguous memory from discontiguous pages.
6695          *
6696          * Queueing large contiguous runs of pages for batching, however,
6697          * causes the pages to actually be freed in smaller chunks.  As there
6698          * can be a significant delay between the individual batches being
6699          * recycled, this leads to the once large chunks of space being
6700          * fragmented and becoming unavailable for high-order allocations.
6701          */
6702         return 0;
6703 #endif
6704 }
6705
6706 static int zone_highsize(struct zone *zone, int batch, int cpu_online)
6707 {
6708 #ifdef CONFIG_MMU
6709         int high;
6710         int nr_local_cpus;
6711
6712         /*
6713          * The high value of the pcp is based on the zone low watermark
6714          * so that if they are full then background reclaim will not be
6715          * started prematurely. The value is split across all online CPUs
6716          * local to the zone. Note that early in boot that CPUs may not be
6717          * online yet and that during CPU hotplug that the cpumask is not
6718          * yet updated when a CPU is being onlined.
6719          */
6720         nr_local_cpus = max(1U, cpumask_weight(cpumask_of_node(zone_to_nid(zone)))) + cpu_online;
6721         high = low_wmark_pages(zone) / nr_local_cpus;
6722
6723         /*
6724          * Ensure high is at least batch*4. The multiple is based on the
6725          * historical relationship between high and batch.
6726          */
6727         high = max(high, batch << 2);
6728
6729         return high;
6730 #else
6731         return 0;
6732 #endif
6733 }
6734
6735 /*
6736  * pcp->high and pcp->batch values are related and generally batch is lower
6737  * than high. They are also related to pcp->count such that count is lower
6738  * than high, and as soon as it reaches high, the pcplist is flushed.
6739  *
6740  * However, guaranteeing these relations at all times would require e.g. write
6741  * barriers here but also careful usage of read barriers at the read side, and
6742  * thus be prone to error and bad for performance. Thus the update only prevents
6743  * store tearing. Any new users of pcp->batch and pcp->high should ensure they
6744  * can cope with those fields changing asynchronously, and fully trust only the
6745  * pcp->count field on the local CPU with interrupts disabled.
6746  *
6747  * mutex_is_locked(&pcp_batch_high_lock) required when calling this function
6748  * outside of boot time (or some other assurance that no concurrent updaters
6749  * exist).
6750  */
6751 static void pageset_update(struct per_cpu_pages *pcp, unsigned long high,
6752                 unsigned long batch)
6753 {
6754         WRITE_ONCE(pcp->batch, batch);
6755         WRITE_ONCE(pcp->high, high);
6756 }
6757
6758 static void per_cpu_pages_init(struct per_cpu_pages *pcp, struct per_cpu_zonestat *pzstats)
6759 {
6760         int migratetype;
6761
6762         memset(pcp, 0, sizeof(*pcp));
6763         memset(pzstats, 0, sizeof(*pzstats));
6764
6765         for (migratetype = 0; migratetype < MIGRATE_PCPTYPES; migratetype++)
6766                 INIT_LIST_HEAD(&pcp->lists[migratetype]);
6767
6768         /*
6769          * Set batch and high values safe for a boot pageset. A true percpu
6770          * pageset's initialization will update them subsequently. Here we don't
6771          * need to be as careful as pageset_update() as nobody can access the
6772          * pageset yet.
6773          */
6774         pcp->high = BOOT_PAGESET_HIGH;
6775         pcp->batch = BOOT_PAGESET_BATCH;
6776         pcp->free_factor = 0;
6777 }
6778
6779 static void __zone_set_pageset_high_and_batch(struct zone *zone, unsigned long high,
6780                 unsigned long batch)
6781 {
6782         struct per_cpu_pages *pcp;
6783         int cpu;
6784
6785         for_each_possible_cpu(cpu) {
6786                 pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu);
6787                 pageset_update(pcp, high, batch);
6788         }
6789 }
6790
6791 /*
6792  * Calculate and set new high and batch values for all per-cpu pagesets of a
6793  * zone based on the zone's size.
6794  */
6795 static void zone_set_pageset_high_and_batch(struct zone *zone, int cpu_online)
6796 {
6797         int new_high, new_batch;
6798
6799         new_batch = max(1, zone_batchsize(zone));
6800         new_high = zone_highsize(zone, new_batch, cpu_online);
6801
6802         if (zone->pageset_high == new_high &&
6803             zone->pageset_batch == new_batch)
6804                 return;
6805
6806         zone->pageset_high = new_high;
6807         zone->pageset_batch = new_batch;
6808
6809         __zone_set_pageset_high_and_batch(zone, new_high, new_batch);
6810 }
6811
6812 void __meminit setup_zone_pageset(struct zone *zone)
6813 {
6814         int cpu;
6815
6816         /* Size may be 0 on !SMP && !NUMA */
6817         if (sizeof(struct per_cpu_zonestat) > 0)
6818                 zone->per_cpu_zonestats = alloc_percpu(struct per_cpu_zonestat);
6819
6820         zone->per_cpu_pageset = alloc_percpu(struct per_cpu_pages);
6821         for_each_possible_cpu(cpu) {
6822                 struct per_cpu_pages *pcp;
6823                 struct per_cpu_zonestat *pzstats;
6824
6825                 pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu);
6826                 pzstats = per_cpu_ptr(zone->per_cpu_zonestats, cpu);
6827                 per_cpu_pages_init(pcp, pzstats);
6828         }
6829
6830         zone_set_pageset_high_and_batch(zone, 0);
6831 }
6832
6833 /*
6834  * Allocate per cpu pagesets and initialize them.
6835  * Before this call only boot pagesets were available.
6836  */
6837 void __init setup_per_cpu_pageset(void)
6838 {
6839         struct pglist_data *pgdat;
6840         struct zone *zone;
6841         int __maybe_unused cpu;
6842
6843         for_each_populated_zone(zone)
6844                 setup_zone_pageset(zone);
6845
6846 #ifdef CONFIG_NUMA
6847         /*
6848          * Unpopulated zones continue using the boot pagesets.
6849          * The numa stats for these pagesets need to be reset.
6850          * Otherwise, they will end up skewing the stats of
6851          * the nodes these zones are associated with.
6852          */
6853         for_each_possible_cpu(cpu) {
6854                 struct per_cpu_zonestat *pzstats = &per_cpu(boot_zonestats, cpu);
6855                 memset(pzstats->vm_numa_event, 0,
6856                        sizeof(pzstats->vm_numa_event));
6857         }
6858 #endif
6859
6860         for_each_online_pgdat(pgdat)
6861                 pgdat->per_cpu_nodestats =
6862                         alloc_percpu(struct per_cpu_nodestat);
6863 }
6864
6865 static __meminit void zone_pcp_init(struct zone *zone)
6866 {
6867         /*
6868          * per cpu subsystem is not up at this point. The following code
6869          * relies on the ability of the linker to provide the
6870          * offset of a (static) per cpu variable into the per cpu area.
6871          */
6872         zone->per_cpu_pageset = &boot_pageset;
6873         zone->per_cpu_zonestats = &boot_zonestats;
6874         zone->pageset_high = BOOT_PAGESET_HIGH;
6875         zone->pageset_batch = BOOT_PAGESET_BATCH;
6876
6877         if (populated_zone(zone))
6878                 pr_debug("  %s zone: %lu pages, LIFO batch:%u\n", zone->name,
6879                          zone->present_pages, zone_batchsize(zone));
6880 }
6881
6882 void __meminit init_currently_empty_zone(struct zone *zone,
6883                                         unsigned long zone_start_pfn,
6884                                         unsigned long size)
6885 {
6886         struct pglist_data *pgdat = zone->zone_pgdat;
6887         int zone_idx = zone_idx(zone) + 1;
6888
6889         if (zone_idx > pgdat->nr_zones)
6890                 pgdat->nr_zones = zone_idx;
6891
6892         zone->zone_start_pfn = zone_start_pfn;
6893
6894         mminit_dprintk(MMINIT_TRACE, "memmap_init",
6895                         "Initialising map node %d zone %lu pfns %lu -> %lu\n",
6896                         pgdat->node_id,
6897                         (unsigned long)zone_idx(zone),
6898                         zone_start_pfn, (zone_start_pfn + size));
6899
6900         zone_init_free_lists(zone);
6901         zone->initialized = 1;
6902 }
6903
6904 /**
6905  * get_pfn_range_for_nid - Return the start and end page frames for a node
6906  * @nid: The nid to return the range for. If MAX_NUMNODES, the min and max PFN are returned.
6907  * @start_pfn: Passed by reference. On return, it will have the node start_pfn.
6908  * @end_pfn: Passed by reference. On return, it will have the node end_pfn.
6909  *
6910  * It returns the start and end page frame of a node based on information
6911  * provided by memblock_set_node(). If called for a node
6912  * with no available memory, a warning is printed and the start and end
6913  * PFNs will be 0.
6914  */
6915 void __init get_pfn_range_for_nid(unsigned int nid,
6916                         unsigned long *start_pfn, unsigned long *end_pfn)
6917 {
6918         unsigned long this_start_pfn, this_end_pfn;
6919         int i;
6920
6921         *start_pfn = -1UL;
6922         *end_pfn = 0;
6923
6924         for_each_mem_pfn_range(i, nid, &this_start_pfn, &this_end_pfn, NULL) {
6925                 *start_pfn = min(*start_pfn, this_start_pfn);
6926                 *end_pfn = max(*end_pfn, this_end_pfn);
6927         }
6928
6929         if (*start_pfn == -1UL)
6930                 *start_pfn = 0;
6931 }
6932
6933 /*
6934  * This finds a zone that can be used for ZONE_MOVABLE pages. The
6935  * assumption is made that zones within a node are ordered in monotonic
6936  * increasing memory addresses so that the "highest" populated zone is used
6937  */
6938 static void __init find_usable_zone_for_movable(void)
6939 {
6940         int zone_index;
6941         for (zone_index = MAX_NR_ZONES - 1; zone_index >= 0; zone_index--) {
6942                 if (zone_index == ZONE_MOVABLE)
6943                         continue;
6944
6945                 if (arch_zone_highest_possible_pfn[zone_index] >
6946                                 arch_zone_lowest_possible_pfn[zone_index])
6947                         break;
6948         }
6949
6950         VM_BUG_ON(zone_index == -1);
6951         movable_zone = zone_index;
6952 }
6953
6954 /*
6955  * The zone ranges provided by the architecture do not include ZONE_MOVABLE
6956  * because it is sized independent of architecture. Unlike the other zones,
6957  * the starting point for ZONE_MOVABLE is not fixed. It may be different
6958  * in each node depending on the size of each node and how evenly kernelcore
6959  * is distributed. This helper function adjusts the zone ranges
6960  * provided by the architecture for a given node by using the end of the
6961  * highest usable zone for ZONE_MOVABLE. This preserves the assumption that
6962  * zones within a node are in order of monotonic increases memory addresses
6963  */
6964 static void __init adjust_zone_range_for_zone_movable(int nid,
6965                                         unsigned long zone_type,
6966                                         unsigned long node_start_pfn,
6967                                         unsigned long node_end_pfn,
6968                                         unsigned long *zone_start_pfn,
6969                                         unsigned long *zone_end_pfn)
6970 {
6971         /* Only adjust if ZONE_MOVABLE is on this node */
6972         if (zone_movable_pfn[nid]) {
6973                 /* Size ZONE_MOVABLE */
6974                 if (zone_type == ZONE_MOVABLE) {
6975                         *zone_start_pfn = zone_movable_pfn[nid];
6976                         *zone_end_pfn = min(node_end_pfn,
6977                                 arch_zone_highest_possible_pfn[movable_zone]);
6978
6979                 /* Adjust for ZONE_MOVABLE starting within this range */
6980                 } else if (!mirrored_kernelcore &&
6981                         *zone_start_pfn < zone_movable_pfn[nid] &&
6982                         *zone_end_pfn > zone_movable_pfn[nid]) {
6983                         *zone_end_pfn = zone_movable_pfn[nid];
6984
6985                 /* Check if this whole range is within ZONE_MOVABLE */
6986                 } else if (*zone_start_pfn >= zone_movable_pfn[nid])
6987                         *zone_start_pfn = *zone_end_pfn;
6988         }
6989 }
6990
6991 /*
6992  * Return the number of pages a zone spans in a node, including holes
6993  * present_pages = zone_spanned_pages_in_node() - zone_absent_pages_in_node()
6994  */
6995 static unsigned long __init zone_spanned_pages_in_node(int nid,
6996                                         unsigned long zone_type,
6997                                         unsigned long node_start_pfn,
6998                                         unsigned long node_end_pfn,
6999                                         unsigned long *zone_start_pfn,
7000                                         unsigned long *zone_end_pfn)
7001 {
7002         unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type];
7003         unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type];
7004         /* When hotadd a new node from cpu_up(), the node should be empty */
7005         if (!node_start_pfn && !node_end_pfn)
7006                 return 0;
7007
7008         /* Get the start and end of the zone */
7009         *zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high);
7010         *zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high);
7011         adjust_zone_range_for_zone_movable(nid, zone_type,
7012                                 node_start_pfn, node_end_pfn,
7013                                 zone_start_pfn, zone_end_pfn);
7014
7015         /* Check that this node has pages within the zone's required range */
7016         if (*zone_end_pfn < node_start_pfn || *zone_start_pfn > node_end_pfn)
7017                 return 0;
7018
7019         /* Move the zone boundaries inside the node if necessary */
7020         *zone_end_pfn = min(*zone_end_pfn, node_end_pfn);
7021         *zone_start_pfn = max(*zone_start_pfn, node_start_pfn);
7022
7023         /* Return the spanned pages */
7024         return *zone_end_pfn - *zone_start_pfn;
7025 }
7026
7027 /*
7028  * Return the number of holes in a range on a node. If nid is MAX_NUMNODES,
7029  * then all holes in the requested range will be accounted for.
7030  */
7031 unsigned long __init __absent_pages_in_range(int nid,
7032                                 unsigned long range_start_pfn,
7033                                 unsigned long range_end_pfn)
7034 {
7035         unsigned long nr_absent = range_end_pfn - range_start_pfn;
7036         unsigned long start_pfn, end_pfn;
7037         int i;
7038
7039         for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
7040                 start_pfn = clamp(start_pfn, range_start_pfn, range_end_pfn);
7041                 end_pfn = clamp(end_pfn, range_start_pfn, range_end_pfn);
7042                 nr_absent -= end_pfn - start_pfn;
7043         }
7044         return nr_absent;
7045 }
7046
7047 /**
7048  * absent_pages_in_range - Return number of page frames in holes within a range
7049  * @start_pfn: The start PFN to start searching for holes
7050  * @end_pfn: The end PFN to stop searching for holes
7051  *
7052  * Return: the number of pages frames in memory holes within a range.
7053  */
7054 unsigned long __init absent_pages_in_range(unsigned long start_pfn,
7055                                                         unsigned long end_pfn)
7056 {
7057         return __absent_pages_in_range(MAX_NUMNODES, start_pfn, end_pfn);
7058 }
7059
7060 /* Return the number of page frames in holes in a zone on a node */
7061 static unsigned long __init zone_absent_pages_in_node(int nid,
7062                                         unsigned long zone_type,
7063                                         unsigned long node_start_pfn,
7064                                         unsigned long node_end_pfn)
7065 {
7066         unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type];
7067         unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type];
7068         unsigned long zone_start_pfn, zone_end_pfn;
7069         unsigned long nr_absent;
7070
7071         /* When hotadd a new node from cpu_up(), the node should be empty */
7072         if (!node_start_pfn && !node_end_pfn)
7073                 return 0;
7074
7075         zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high);
7076         zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high);
7077
7078         adjust_zone_range_for_zone_movable(nid, zone_type,
7079                         node_start_pfn, node_end_pfn,
7080                         &zone_start_pfn, &zone_end_pfn);
7081         nr_absent = __absent_pages_in_range(nid, zone_start_pfn, zone_end_pfn);
7082
7083         /*
7084          * ZONE_MOVABLE handling.
7085          * Treat pages to be ZONE_MOVABLE in ZONE_NORMAL as absent pages
7086          * and vice versa.
7087          */
7088         if (mirrored_kernelcore && zone_movable_pfn[nid]) {
7089                 unsigned long start_pfn, end_pfn;
7090                 struct memblock_region *r;
7091
7092                 for_each_mem_region(r) {
7093                         start_pfn = clamp(memblock_region_memory_base_pfn(r),
7094                                           zone_start_pfn, zone_end_pfn);
7095                         end_pfn = clamp(memblock_region_memory_end_pfn(r),
7096                                         zone_start_pfn, zone_end_pfn);
7097
7098                         if (zone_type == ZONE_MOVABLE &&
7099                             memblock_is_mirror(r))
7100                                 nr_absent += end_pfn - start_pfn;
7101
7102                         if (zone_type == ZONE_NORMAL &&
7103                             !memblock_is_mirror(r))
7104                                 nr_absent += end_pfn - start_pfn;
7105                 }
7106         }
7107
7108         return nr_absent;
7109 }
7110
7111 static void __init calculate_node_totalpages(struct pglist_data *pgdat,
7112                                                 unsigned long node_start_pfn,
7113                                                 unsigned long node_end_pfn)
7114 {
7115         unsigned long realtotalpages = 0, totalpages = 0;
7116         enum zone_type i;
7117
7118         for (i = 0; i < MAX_NR_ZONES; i++) {
7119                 struct zone *zone = pgdat->node_zones + i;
7120                 unsigned long zone_start_pfn, zone_end_pfn;
7121                 unsigned long spanned, absent;
7122                 unsigned long size, real_size;
7123
7124                 spanned = zone_spanned_pages_in_node(pgdat->node_id, i,
7125                                                      node_start_pfn,
7126                                                      node_end_pfn,
7127                                                      &zone_start_pfn,
7128                                                      &zone_end_pfn);
7129                 absent = zone_absent_pages_in_node(pgdat->node_id, i,
7130                                                    node_start_pfn,
7131                                                    node_end_pfn);
7132
7133                 size = spanned;
7134                 real_size = size - absent;
7135
7136                 if (size)
7137                         zone->zone_start_pfn = zone_start_pfn;
7138                 else
7139                         zone->zone_start_pfn = 0;
7140                 zone->spanned_pages = size;
7141                 zone->present_pages = real_size;
7142
7143                 totalpages += size;
7144                 realtotalpages += real_size;
7145         }
7146
7147         pgdat->node_spanned_pages = totalpages;
7148         pgdat->node_present_pages = realtotalpages;
7149         pr_debug("On node %d totalpages: %lu\n", pgdat->node_id, realtotalpages);
7150 }
7151
7152 #ifndef CONFIG_SPARSEMEM
7153 /*
7154  * Calculate the size of the zone->blockflags rounded to an unsigned long
7155  * Start by making sure zonesize is a multiple of pageblock_order by rounding
7156  * up. Then use 1 NR_PAGEBLOCK_BITS worth of bits per pageblock, finally
7157  * round what is now in bits to nearest long in bits, then return it in
7158  * bytes.
7159  */
7160 static unsigned long __init usemap_size(unsigned long zone_start_pfn, unsigned long zonesize)
7161 {
7162         unsigned long usemapsize;
7163
7164         zonesize += zone_start_pfn & (pageblock_nr_pages-1);
7165         usemapsize = roundup(zonesize, pageblock_nr_pages);
7166         usemapsize = usemapsize >> pageblock_order;
7167         usemapsize *= NR_PAGEBLOCK_BITS;
7168         usemapsize = roundup(usemapsize, 8 * sizeof(unsigned long));
7169
7170         return usemapsize / 8;
7171 }
7172
7173 static void __ref setup_usemap(struct zone *zone)
7174 {
7175         unsigned long usemapsize = usemap_size(zone->zone_start_pfn,
7176                                                zone->spanned_pages);
7177         zone->pageblock_flags = NULL;
7178         if (usemapsize) {
7179                 zone->pageblock_flags =
7180                         memblock_alloc_node(usemapsize, SMP_CACHE_BYTES,
7181                                             zone_to_nid(zone));
7182                 if (!zone->pageblock_flags)
7183                         panic("Failed to allocate %ld bytes for zone %s pageblock flags on node %d\n",
7184                               usemapsize, zone->name, zone_to_nid(zone));
7185         }
7186 }
7187 #else
7188 static inline void setup_usemap(struct zone *zone) {}
7189 #endif /* CONFIG_SPARSEMEM */
7190
7191 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
7192
7193 /* Initialise the number of pages represented by NR_PAGEBLOCK_BITS */
7194 void __init set_pageblock_order(void)
7195 {
7196         unsigned int order;
7197
7198         /* Check that pageblock_nr_pages has not already been setup */
7199         if (pageblock_order)
7200                 return;
7201
7202         if (HPAGE_SHIFT > PAGE_SHIFT)
7203                 order = HUGETLB_PAGE_ORDER;
7204         else
7205                 order = MAX_ORDER - 1;
7206
7207         /*
7208          * Assume the largest contiguous order of interest is a huge page.
7209          * This value may be variable depending on boot parameters on IA64 and
7210          * powerpc.
7211          */
7212         pageblock_order = order;
7213 }
7214 #else /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
7215
7216 /*
7217  * When CONFIG_HUGETLB_PAGE_SIZE_VARIABLE is not set, set_pageblock_order()
7218  * is unused as pageblock_order is set at compile-time. See
7219  * include/linux/pageblock-flags.h for the values of pageblock_order based on
7220  * the kernel config
7221  */
7222 void __init set_pageblock_order(void)
7223 {
7224 }
7225
7226 #endif /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
7227
7228 static unsigned long __init calc_memmap_size(unsigned long spanned_pages,
7229                                                 unsigned long present_pages)
7230 {
7231         unsigned long pages = spanned_pages;
7232
7233         /*
7234          * Provide a more accurate estimation if there are holes within
7235          * the zone and SPARSEMEM is in use. If there are holes within the
7236          * zone, each populated memory region may cost us one or two extra
7237          * memmap pages due to alignment because memmap pages for each
7238          * populated regions may not be naturally aligned on page boundary.
7239          * So the (present_pages >> 4) heuristic is a tradeoff for that.
7240          */
7241         if (spanned_pages > present_pages + (present_pages >> 4) &&
7242             IS_ENABLED(CONFIG_SPARSEMEM))
7243                 pages = present_pages;
7244
7245         return PAGE_ALIGN(pages * sizeof(struct page)) >> PAGE_SHIFT;
7246 }
7247
7248 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
7249 static void pgdat_init_split_queue(struct pglist_data *pgdat)
7250 {
7251         struct deferred_split *ds_queue = &pgdat->deferred_split_queue;
7252
7253         spin_lock_init(&ds_queue->split_queue_lock);
7254         INIT_LIST_HEAD(&ds_queue->split_queue);
7255         ds_queue->split_queue_len = 0;
7256 }
7257 #else
7258 static void pgdat_init_split_queue(struct pglist_data *pgdat) {}
7259 #endif
7260
7261 #ifdef CONFIG_COMPACTION
7262 static void pgdat_init_kcompactd(struct pglist_data *pgdat)
7263 {
7264         init_waitqueue_head(&pgdat->kcompactd_wait);
7265 }
7266 #else
7267 static void pgdat_init_kcompactd(struct pglist_data *pgdat) {}
7268 #endif
7269
7270 static void __meminit pgdat_init_internals(struct pglist_data *pgdat)
7271 {
7272         pgdat_resize_init(pgdat);
7273
7274         pgdat_init_split_queue(pgdat);
7275         pgdat_init_kcompactd(pgdat);
7276
7277         init_waitqueue_head(&pgdat->kswapd_wait);
7278         init_waitqueue_head(&pgdat->pfmemalloc_wait);
7279
7280         pgdat_page_ext_init(pgdat);
7281         lruvec_init(&pgdat->__lruvec);
7282 }
7283
7284 static void __meminit zone_init_internals(struct zone *zone, enum zone_type idx, int nid,
7285                                                         unsigned long remaining_pages)
7286 {
7287         atomic_long_set(&zone->managed_pages, remaining_pages);
7288         zone_set_nid(zone, nid);
7289         zone->name = zone_names[idx];
7290         zone->zone_pgdat = NODE_DATA(nid);
7291         spin_lock_init(&zone->lock);
7292         zone_seqlock_init(zone);
7293         zone_pcp_init(zone);
7294 }
7295
7296 /*
7297  * Set up the zone data structures
7298  * - init pgdat internals
7299  * - init all zones belonging to this node
7300  *
7301  * NOTE: this function is only called during memory hotplug
7302  */
7303 #ifdef CONFIG_MEMORY_HOTPLUG
7304 void __ref free_area_init_core_hotplug(int nid)
7305 {
7306         enum zone_type z;
7307         pg_data_t *pgdat = NODE_DATA(nid);
7308
7309         pgdat_init_internals(pgdat);
7310         for (z = 0; z < MAX_NR_ZONES; z++)
7311                 zone_init_internals(&pgdat->node_zones[z], z, nid, 0);
7312 }
7313 #endif
7314
7315 /*
7316  * Set up the zone data structures:
7317  *   - mark all pages reserved
7318  *   - mark all memory queues empty
7319  *   - clear the memory bitmaps
7320  *
7321  * NOTE: pgdat should get zeroed by caller.
7322  * NOTE: this function is only called during early init.
7323  */
7324 static void __init free_area_init_core(struct pglist_data *pgdat)
7325 {
7326         enum zone_type j;
7327         int nid = pgdat->node_id;
7328
7329         pgdat_init_internals(pgdat);
7330         pgdat->per_cpu_nodestats = &boot_nodestats;
7331
7332         for (j = 0; j < MAX_NR_ZONES; j++) {
7333                 struct zone *zone = pgdat->node_zones + j;
7334                 unsigned long size, freesize, memmap_pages;
7335
7336                 size = zone->spanned_pages;
7337                 freesize = zone->present_pages;
7338
7339                 /*
7340                  * Adjust freesize so that it accounts for how much memory
7341                  * is used by this zone for memmap. This affects the watermark
7342                  * and per-cpu initialisations
7343                  */
7344                 memmap_pages = calc_memmap_size(size, freesize);
7345                 if (!is_highmem_idx(j)) {
7346                         if (freesize >= memmap_pages) {
7347                                 freesize -= memmap_pages;
7348                                 if (memmap_pages)
7349                                         pr_debug("  %s zone: %lu pages used for memmap\n",
7350                                                  zone_names[j], memmap_pages);
7351                         } else
7352                                 pr_warn("  %s zone: %lu pages exceeds freesize %lu\n",
7353                                         zone_names[j], memmap_pages, freesize);
7354                 }
7355
7356                 /* Account for reserved pages */
7357                 if (j == 0 && freesize > dma_reserve) {
7358                         freesize -= dma_reserve;
7359                         pr_debug("  %s zone: %lu pages reserved\n", zone_names[0], dma_reserve);
7360                 }
7361
7362                 if (!is_highmem_idx(j))
7363                         nr_kernel_pages += freesize;
7364                 /* Charge for highmem memmap if there are enough kernel pages */
7365                 else if (nr_kernel_pages > memmap_pages * 2)
7366                         nr_kernel_pages -= memmap_pages;
7367                 nr_all_pages += freesize;
7368
7369                 /*
7370                  * Set an approximate value for lowmem here, it will be adjusted
7371                  * when the bootmem allocator frees pages into the buddy system.
7372                  * And all highmem pages will be managed by the buddy system.
7373                  */
7374                 zone_init_internals(zone, j, nid, freesize);
7375
7376                 if (!size)
7377                         continue;
7378
7379                 set_pageblock_order();
7380                 setup_usemap(zone);
7381                 init_currently_empty_zone(zone, zone->zone_start_pfn, size);
7382         }
7383 }
7384
7385 #ifdef CONFIG_FLAT_NODE_MEM_MAP
7386 static void __ref alloc_node_mem_map(struct pglist_data *pgdat)
7387 {
7388         unsigned long __maybe_unused start = 0;
7389         unsigned long __maybe_unused offset = 0;
7390
7391         /* Skip empty nodes */
7392         if (!pgdat->node_spanned_pages)
7393                 return;
7394
7395         start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1);
7396         offset = pgdat->node_start_pfn - start;
7397         /* ia64 gets its own node_mem_map, before this, without bootmem */
7398         if (!pgdat->node_mem_map) {
7399                 unsigned long size, end;
7400                 struct page *map;
7401
7402                 /*
7403                  * The zone's endpoints aren't required to be MAX_ORDER
7404                  * aligned but the node_mem_map endpoints must be in order
7405                  * for the buddy allocator to function correctly.
7406                  */
7407                 end = pgdat_end_pfn(pgdat);
7408                 end = ALIGN(end, MAX_ORDER_NR_PAGES);
7409                 size =  (end - start) * sizeof(struct page);
7410                 map = memblock_alloc_node(size, SMP_CACHE_BYTES,
7411                                           pgdat->node_id);
7412                 if (!map)
7413                         panic("Failed to allocate %ld bytes for node %d memory map\n",
7414                               size, pgdat->node_id);
7415                 pgdat->node_mem_map = map + offset;
7416         }
7417         pr_debug("%s: node %d, pgdat %08lx, node_mem_map %08lx\n",
7418                                 __func__, pgdat->node_id, (unsigned long)pgdat,
7419                                 (unsigned long)pgdat->node_mem_map);
7420 #ifndef CONFIG_NEED_MULTIPLE_NODES
7421         /*
7422          * With no DISCONTIG, the global mem_map is just set as node 0's
7423          */
7424         if (pgdat == NODE_DATA(0)) {
7425                 mem_map = NODE_DATA(0)->node_mem_map;
7426                 if (page_to_pfn(mem_map) != pgdat->node_start_pfn)
7427                         mem_map -= offset;
7428         }
7429 #endif
7430 }
7431 #else
7432 static void __ref alloc_node_mem_map(struct pglist_data *pgdat) { }
7433 #endif /* CONFIG_FLAT_NODE_MEM_MAP */
7434
7435 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
7436 static inline void pgdat_set_deferred_range(pg_data_t *pgdat)
7437 {
7438         pgdat->first_deferred_pfn = ULONG_MAX;
7439 }
7440 #else
7441 static inline void pgdat_set_deferred_range(pg_data_t *pgdat) {}
7442 #endif
7443
7444 static void __init free_area_init_node(int nid)
7445 {
7446         pg_data_t *pgdat = NODE_DATA(nid);
7447         unsigned long start_pfn = 0;
7448         unsigned long end_pfn = 0;
7449
7450         /* pg_data_t should be reset to zero when it's allocated */
7451         WARN_ON(pgdat->nr_zones || pgdat->kswapd_highest_zoneidx);
7452
7453         get_pfn_range_for_nid(nid, &start_pfn, &end_pfn);
7454
7455         pgdat->node_id = nid;
7456         pgdat->node_start_pfn = start_pfn;
7457         pgdat->per_cpu_nodestats = NULL;
7458
7459         pr_info("Initmem setup node %d [mem %#018Lx-%#018Lx]\n", nid,
7460                 (u64)start_pfn << PAGE_SHIFT,
7461                 end_pfn ? ((u64)end_pfn << PAGE_SHIFT) - 1 : 0);
7462         calculate_node_totalpages(pgdat, start_pfn, end_pfn);
7463
7464         alloc_node_mem_map(pgdat);
7465         pgdat_set_deferred_range(pgdat);
7466
7467         free_area_init_core(pgdat);
7468 }
7469
7470 void __init free_area_init_memoryless_node(int nid)
7471 {
7472         free_area_init_node(nid);
7473 }
7474
7475 #if MAX_NUMNODES > 1
7476 /*
7477  * Figure out the number of possible node ids.
7478  */
7479 void __init setup_nr_node_ids(void)
7480 {
7481         unsigned int highest;
7482
7483         highest = find_last_bit(node_possible_map.bits, MAX_NUMNODES);
7484         nr_node_ids = highest + 1;
7485 }
7486 #endif
7487
7488 /**
7489  * node_map_pfn_alignment - determine the maximum internode alignment
7490  *
7491  * This function should be called after node map is populated and sorted.
7492  * It calculates the maximum power of two alignment which can distinguish
7493  * all the nodes.
7494  *
7495  * For example, if all nodes are 1GiB and aligned to 1GiB, the return value
7496  * would indicate 1GiB alignment with (1 << (30 - PAGE_SHIFT)).  If the
7497  * nodes are shifted by 256MiB, 256MiB.  Note that if only the last node is
7498  * shifted, 1GiB is enough and this function will indicate so.
7499  *
7500  * This is used to test whether pfn -> nid mapping of the chosen memory
7501  * model has fine enough granularity to avoid incorrect mapping for the
7502  * populated node map.
7503  *
7504  * Return: the determined alignment in pfn's.  0 if there is no alignment
7505  * requirement (single node).
7506  */
7507 unsigned long __init node_map_pfn_alignment(void)
7508 {
7509         unsigned long accl_mask = 0, last_end = 0;
7510         unsigned long start, end, mask;
7511         int last_nid = NUMA_NO_NODE;
7512         int i, nid;
7513
7514         for_each_mem_pfn_range(i, MAX_NUMNODES, &start, &end, &nid) {
7515                 if (!start || last_nid < 0 || last_nid == nid) {
7516                         last_nid = nid;
7517                         last_end = end;
7518                         continue;
7519                 }
7520
7521                 /*
7522                  * Start with a mask granular enough to pin-point to the
7523                  * start pfn and tick off bits one-by-one until it becomes
7524                  * too coarse to separate the current node from the last.
7525                  */
7526                 mask = ~((1 << __ffs(start)) - 1);
7527                 while (mask && last_end <= (start & (mask << 1)))
7528                         mask <<= 1;
7529
7530                 /* accumulate all internode masks */
7531                 accl_mask |= mask;
7532         }
7533
7534         /* convert mask to number of pages */
7535         return ~accl_mask + 1;
7536 }
7537
7538 /**
7539  * find_min_pfn_with_active_regions - Find the minimum PFN registered
7540  *
7541  * Return: the minimum PFN based on information provided via
7542  * memblock_set_node().
7543  */
7544 unsigned long __init find_min_pfn_with_active_regions(void)
7545 {
7546         return PHYS_PFN(memblock_start_of_DRAM());
7547 }
7548
7549 /*
7550  * early_calculate_totalpages()
7551  * Sum pages in active regions for movable zone.
7552  * Populate N_MEMORY for calculating usable_nodes.
7553  */
7554 static unsigned long __init early_calculate_totalpages(void)
7555 {
7556         unsigned long totalpages = 0;
7557         unsigned long start_pfn, end_pfn;
7558         int i, nid;
7559
7560         for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
7561                 unsigned long pages = end_pfn - start_pfn;
7562
7563                 totalpages += pages;
7564                 if (pages)
7565                         node_set_state(nid, N_MEMORY);
7566         }
7567         return totalpages;
7568 }
7569
7570 /*
7571  * Find the PFN the Movable zone begins in each node. Kernel memory
7572  * is spread evenly between nodes as long as the nodes have enough
7573  * memory. When they don't, some nodes will have more kernelcore than
7574  * others
7575  */
7576 static void __init find_zone_movable_pfns_for_nodes(void)
7577 {
7578         int i, nid;
7579         unsigned long usable_startpfn;
7580         unsigned long kernelcore_node, kernelcore_remaining;
7581         /* save the state before borrow the nodemask */
7582         nodemask_t saved_node_state = node_states[N_MEMORY];
7583         unsigned long totalpages = early_calculate_totalpages();
7584         int usable_nodes = nodes_weight(node_states[N_MEMORY]);
7585         struct memblock_region *r;
7586
7587         /* Need to find movable_zone earlier when movable_node is specified. */
7588         find_usable_zone_for_movable();
7589
7590         /*
7591          * If movable_node is specified, ignore kernelcore and movablecore
7592          * options.
7593          */
7594         if (movable_node_is_enabled()) {
7595                 for_each_mem_region(r) {
7596                         if (!memblock_is_hotpluggable(r))
7597                                 continue;
7598
7599                         nid = memblock_get_region_node(r);
7600
7601                         usable_startpfn = PFN_DOWN(r->base);
7602                         zone_movable_pfn[nid] = zone_movable_pfn[nid] ?
7603                                 min(usable_startpfn, zone_movable_pfn[nid]) :
7604                                 usable_startpfn;
7605                 }
7606
7607                 goto out2;
7608         }
7609
7610         /*
7611          * If kernelcore=mirror is specified, ignore movablecore option
7612          */
7613         if (mirrored_kernelcore) {
7614                 bool mem_below_4gb_not_mirrored = false;
7615
7616                 for_each_mem_region(r) {
7617                         if (memblock_is_mirror(r))
7618                                 continue;
7619
7620                         nid = memblock_get_region_node(r);
7621
7622                         usable_startpfn = memblock_region_memory_base_pfn(r);
7623
7624                         if (usable_startpfn < 0x100000) {
7625                                 mem_below_4gb_not_mirrored = true;
7626                                 continue;
7627                         }
7628
7629                         zone_movable_pfn[nid] = zone_movable_pfn[nid] ?
7630                                 min(usable_startpfn, zone_movable_pfn[nid]) :
7631                                 usable_startpfn;
7632                 }
7633
7634                 if (mem_below_4gb_not_mirrored)
7635                         pr_warn("This configuration results in unmirrored kernel memory.\n");
7636
7637                 goto out2;
7638         }
7639
7640         /*
7641          * If kernelcore=nn% or movablecore=nn% was specified, calculate the
7642          * amount of necessary memory.
7643          */
7644         if (required_kernelcore_percent)
7645                 required_kernelcore = (totalpages * 100 * required_kernelcore_percent) /
7646                                        10000UL;
7647         if (required_movablecore_percent)
7648                 required_movablecore = (totalpages * 100 * required_movablecore_percent) /
7649                                         10000UL;
7650
7651         /*
7652          * If movablecore= was specified, calculate what size of
7653          * kernelcore that corresponds so that memory usable for
7654          * any allocation type is evenly spread. If both kernelcore
7655          * and movablecore are specified, then the value of kernelcore
7656          * will be used for required_kernelcore if it's greater than
7657          * what movablecore would have allowed.
7658          */
7659         if (required_movablecore) {
7660                 unsigned long corepages;
7661
7662                 /*
7663                  * Round-up so that ZONE_MOVABLE is at least as large as what
7664                  * was requested by the user
7665                  */
7666                 required_movablecore =
7667                         roundup(required_movablecore, MAX_ORDER_NR_PAGES);
7668                 required_movablecore = min(totalpages, required_movablecore);
7669                 corepages = totalpages - required_movablecore;
7670
7671                 required_kernelcore = max(required_kernelcore, corepages);
7672         }
7673
7674         /*
7675          * If kernelcore was not specified or kernelcore size is larger
7676          * than totalpages, there is no ZONE_MOVABLE.
7677          */
7678         if (!required_kernelcore || required_kernelcore >= totalpages)
7679                 goto out;
7680
7681         /* usable_startpfn is the lowest possible pfn ZONE_MOVABLE can be at */
7682         usable_startpfn = arch_zone_lowest_possible_pfn[movable_zone];
7683
7684 restart:
7685         /* Spread kernelcore memory as evenly as possible throughout nodes */
7686         kernelcore_node = required_kernelcore / usable_nodes;
7687         for_each_node_state(nid, N_MEMORY) {
7688                 unsigned long start_pfn, end_pfn;
7689
7690                 /*
7691                  * Recalculate kernelcore_node if the division per node
7692                  * now exceeds what is necessary to satisfy the requested
7693                  * amount of memory for the kernel
7694                  */
7695                 if (required_kernelcore < kernelcore_node)
7696                         kernelcore_node = required_kernelcore / usable_nodes;
7697
7698                 /*
7699                  * As the map is walked, we track how much memory is usable
7700                  * by the kernel using kernelcore_remaining. When it is
7701                  * 0, the rest of the node is usable by ZONE_MOVABLE
7702                  */
7703                 kernelcore_remaining = kernelcore_node;
7704
7705                 /* Go through each range of PFNs within this node */
7706                 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
7707                         unsigned long size_pages;
7708
7709                         start_pfn = max(start_pfn, zone_movable_pfn[nid]);
7710                         if (start_pfn >= end_pfn)
7711                                 continue;
7712
7713                         /* Account for what is only usable for kernelcore */
7714                         if (start_pfn < usable_startpfn) {
7715                                 unsigned long kernel_pages;
7716                                 kernel_pages = min(end_pfn, usable_startpfn)
7717                                                                 - start_pfn;
7718
7719                                 kernelcore_remaining -= min(kernel_pages,
7720                                                         kernelcore_remaining);
7721                                 required_kernelcore -= min(kernel_pages,
7722                                                         required_kernelcore);
7723
7724                                 /* Continue if range is now fully accounted */
7725                                 if (end_pfn <= usable_startpfn) {
7726
7727                                         /*
7728                                          * Push zone_movable_pfn to the end so
7729                                          * that if we have to rebalance
7730                                          * kernelcore across nodes, we will
7731                                          * not double account here
7732                                          */
7733                                         zone_movable_pfn[nid] = end_pfn;
7734                                         continue;
7735                                 }
7736                                 start_pfn = usable_startpfn;
7737                         }
7738
7739                         /*
7740                          * The usable PFN range for ZONE_MOVABLE is from
7741                          * start_pfn->end_pfn. Calculate size_pages as the
7742                          * number of pages used as kernelcore
7743                          */
7744                         size_pages = end_pfn - start_pfn;
7745                         if (size_pages > kernelcore_remaining)
7746                                 size_pages = kernelcore_remaining;
7747                         zone_movable_pfn[nid] = start_pfn + size_pages;
7748
7749                         /*
7750                          * Some kernelcore has been met, update counts and
7751                          * break if the kernelcore for this node has been
7752                          * satisfied
7753                          */
7754                         required_kernelcore -= min(required_kernelcore,
7755                                                                 size_pages);
7756                         kernelcore_remaining -= size_pages;
7757                         if (!kernelcore_remaining)
7758                                 break;
7759                 }
7760         }
7761
7762         /*
7763          * If there is still required_kernelcore, we do another pass with one
7764          * less node in the count. This will push zone_movable_pfn[nid] further
7765          * along on the nodes that still have memory until kernelcore is
7766          * satisfied
7767          */
7768         usable_nodes--;
7769         if (usable_nodes && required_kernelcore > usable_nodes)
7770                 goto restart;
7771
7772 out2:
7773         /* Align start of ZONE_MOVABLE on all nids to MAX_ORDER_NR_PAGES */
7774         for (nid = 0; nid < MAX_NUMNODES; nid++)
7775                 zone_movable_pfn[nid] =
7776                         roundup(zone_movable_pfn[nid], MAX_ORDER_NR_PAGES);
7777
7778 out:
7779         /* restore the node_state */
7780         node_states[N_MEMORY] = saved_node_state;
7781 }
7782
7783 /* Any regular or high memory on that node ? */
7784 static void check_for_memory(pg_data_t *pgdat, int nid)
7785 {
7786         enum zone_type zone_type;
7787
7788         for (zone_type = 0; zone_type <= ZONE_MOVABLE - 1; zone_type++) {
7789                 struct zone *zone = &pgdat->node_zones[zone_type];
7790                 if (populated_zone(zone)) {
7791                         if (IS_ENABLED(CONFIG_HIGHMEM))
7792                                 node_set_state(nid, N_HIGH_MEMORY);
7793                         if (zone_type <= ZONE_NORMAL)
7794                                 node_set_state(nid, N_NORMAL_MEMORY);
7795                         break;
7796                 }
7797         }
7798 }
7799
7800 /*
7801  * Some architectures, e.g. ARC may have ZONE_HIGHMEM below ZONE_NORMAL. For
7802  * such cases we allow max_zone_pfn sorted in the descending order
7803  */
7804 bool __weak arch_has_descending_max_zone_pfns(void)
7805 {
7806         return false;
7807 }
7808
7809 /**
7810  * free_area_init - Initialise all pg_data_t and zone data
7811  * @max_zone_pfn: an array of max PFNs for each zone
7812  *
7813  * This will call free_area_init_node() for each active node in the system.
7814  * Using the page ranges provided by memblock_set_node(), the size of each
7815  * zone in each node and their holes is calculated. If the maximum PFN
7816  * between two adjacent zones match, it is assumed that the zone is empty.
7817  * For example, if arch_max_dma_pfn == arch_max_dma32_pfn, it is assumed
7818  * that arch_max_dma32_pfn has no pages. It is also assumed that a zone
7819  * starts where the previous one ended. For example, ZONE_DMA32 starts
7820  * at arch_max_dma_pfn.
7821  */
7822 void __init free_area_init(unsigned long *max_zone_pfn)
7823 {
7824         unsigned long start_pfn, end_pfn;
7825         int i, nid, zone;
7826         bool descending;
7827
7828         /* Record where the zone boundaries are */
7829         memset(arch_zone_lowest_possible_pfn, 0,
7830                                 sizeof(arch_zone_lowest_possible_pfn));
7831         memset(arch_zone_highest_possible_pfn, 0,
7832                                 sizeof(arch_zone_highest_possible_pfn));
7833
7834         start_pfn = find_min_pfn_with_active_regions();
7835         descending = arch_has_descending_max_zone_pfns();
7836
7837         for (i = 0; i < MAX_NR_ZONES; i++) {
7838                 if (descending)
7839                         zone = MAX_NR_ZONES - i - 1;
7840                 else
7841                         zone = i;
7842
7843                 if (zone == ZONE_MOVABLE)
7844                         continue;
7845
7846                 end_pfn = max(max_zone_pfn[zone], start_pfn);
7847                 arch_zone_lowest_possible_pfn[zone] = start_pfn;
7848                 arch_zone_highest_possible_pfn[zone] = end_pfn;
7849
7850                 start_pfn = end_pfn;
7851         }
7852
7853         /* Find the PFNs that ZONE_MOVABLE begins at in each node */
7854         memset(zone_movable_pfn, 0, sizeof(zone_movable_pfn));
7855         find_zone_movable_pfns_for_nodes();
7856
7857         /* Print out the zone ranges */
7858         pr_info("Zone ranges:\n");
7859         for (i = 0; i < MAX_NR_ZONES; i++) {
7860                 if (i == ZONE_MOVABLE)
7861                         continue;
7862                 pr_info("  %-8s ", zone_names[i]);
7863                 if (arch_zone_lowest_possible_pfn[i] ==
7864                                 arch_zone_highest_possible_pfn[i])
7865                         pr_cont("empty\n");
7866                 else
7867                         pr_cont("[mem %#018Lx-%#018Lx]\n",
7868                                 (u64)arch_zone_lowest_possible_pfn[i]
7869                                         << PAGE_SHIFT,
7870                                 ((u64)arch_zone_highest_possible_pfn[i]
7871                                         << PAGE_SHIFT) - 1);
7872         }
7873
7874         /* Print out the PFNs ZONE_MOVABLE begins at in each node */
7875         pr_info("Movable zone start for each node\n");
7876         for (i = 0; i < MAX_NUMNODES; i++) {
7877                 if (zone_movable_pfn[i])
7878                         pr_info("  Node %d: %#018Lx\n", i,
7879                                (u64)zone_movable_pfn[i] << PAGE_SHIFT);
7880         }
7881
7882         /*
7883          * Print out the early node map, and initialize the
7884          * subsection-map relative to active online memory ranges to
7885          * enable future "sub-section" extensions of the memory map.
7886          */
7887         pr_info("Early memory node ranges\n");
7888         for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
7889                 pr_info("  node %3d: [mem %#018Lx-%#018Lx]\n", nid,
7890                         (u64)start_pfn << PAGE_SHIFT,
7891                         ((u64)end_pfn << PAGE_SHIFT) - 1);
7892                 subsection_map_init(start_pfn, end_pfn - start_pfn);
7893         }
7894
7895         /* Initialise every node */
7896         mminit_verify_pageflags_layout();
7897         setup_nr_node_ids();
7898         for_each_online_node(nid) {
7899                 pg_data_t *pgdat = NODE_DATA(nid);
7900                 free_area_init_node(nid);
7901
7902                 /* Any memory on that node */
7903                 if (pgdat->node_present_pages)
7904                         node_set_state(nid, N_MEMORY);
7905                 check_for_memory(pgdat, nid);
7906         }
7907
7908         memmap_init();
7909 }
7910
7911 static int __init cmdline_parse_core(char *p, unsigned long *core,
7912                                      unsigned long *percent)
7913 {
7914         unsigned long long coremem;
7915         char *endptr;
7916
7917         if (!p)
7918                 return -EINVAL;
7919
7920         /* Value may be a percentage of total memory, otherwise bytes */
7921         coremem = simple_strtoull(p, &endptr, 0);
7922         if (*endptr == '%') {
7923                 /* Paranoid check for percent values greater than 100 */
7924                 WARN_ON(coremem > 100);
7925
7926                 *percent = coremem;
7927         } else {
7928                 coremem = memparse(p, &p);
7929                 /* Paranoid check that UL is enough for the coremem value */
7930                 WARN_ON((coremem >> PAGE_SHIFT) > ULONG_MAX);
7931
7932                 *core = coremem >> PAGE_SHIFT;
7933                 *percent = 0UL;
7934         }
7935         return 0;
7936 }
7937
7938 /*
7939  * kernelcore=size sets the amount of memory for use for allocations that
7940  * cannot be reclaimed or migrated.
7941  */
7942 static int __init cmdline_parse_kernelcore(char *p)
7943 {
7944         /* parse kernelcore=mirror */
7945         if (parse_option_str(p, "mirror")) {
7946                 mirrored_kernelcore = true;
7947                 return 0;
7948         }
7949
7950         return cmdline_parse_core(p, &required_kernelcore,
7951                                   &required_kernelcore_percent);
7952 }
7953
7954 /*
7955  * movablecore=size sets the amount of memory for use for allocations that
7956  * can be reclaimed or migrated.
7957  */
7958 static int __init cmdline_parse_movablecore(char *p)
7959 {
7960         return cmdline_parse_core(p, &required_movablecore,
7961                                   &required_movablecore_percent);
7962 }
7963
7964 early_param("kernelcore", cmdline_parse_kernelcore);
7965 early_param("movablecore", cmdline_parse_movablecore);
7966
7967 void adjust_managed_page_count(struct page *page, long count)
7968 {
7969         atomic_long_add(count, &page_zone(page)->managed_pages);
7970         totalram_pages_add(count);
7971 #ifdef CONFIG_HIGHMEM
7972         if (PageHighMem(page))
7973                 totalhigh_pages_add(count);
7974 #endif
7975 }
7976 EXPORT_SYMBOL(adjust_managed_page_count);
7977
7978 unsigned long free_reserved_area(void *start, void *end, int poison, const char *s)
7979 {
7980         void *pos;
7981         unsigned long pages = 0;
7982
7983         start = (void *)PAGE_ALIGN((unsigned long)start);
7984         end = (void *)((unsigned long)end & PAGE_MASK);
7985         for (pos = start; pos < end; pos += PAGE_SIZE, pages++) {
7986                 struct page *page = virt_to_page(pos);
7987                 void *direct_map_addr;
7988
7989                 /*
7990                  * 'direct_map_addr' might be different from 'pos'
7991                  * because some architectures' virt_to_page()
7992                  * work with aliases.  Getting the direct map
7993                  * address ensures that we get a _writeable_
7994                  * alias for the memset().
7995                  */
7996                 direct_map_addr = page_address(page);
7997                 /*
7998                  * Perform a kasan-unchecked memset() since this memory
7999                  * has not been initialized.
8000                  */
8001                 direct_map_addr = kasan_reset_tag(direct_map_addr);
8002                 if ((unsigned int)poison <= 0xFF)
8003                         memset(direct_map_addr, poison, PAGE_SIZE);
8004
8005                 free_reserved_page(page);
8006         }
8007
8008         if (pages && s)
8009                 pr_info("Freeing %s memory: %ldK\n",
8010                         s, pages << (PAGE_SHIFT - 10));
8011
8012         return pages;
8013 }
8014
8015 void __init mem_init_print_info(void)
8016 {
8017         unsigned long physpages, codesize, datasize, rosize, bss_size;
8018         unsigned long init_code_size, init_data_size;
8019
8020         physpages = get_num_physpages();
8021         codesize = _etext - _stext;
8022         datasize = _edata - _sdata;
8023         rosize = __end_rodata - __start_rodata;
8024         bss_size = __bss_stop - __bss_start;
8025         init_data_size = __init_end - __init_begin;
8026         init_code_size = _einittext - _sinittext;
8027
8028         /*
8029          * Detect special cases and adjust section sizes accordingly:
8030          * 1) .init.* may be embedded into .data sections
8031          * 2) .init.text.* may be out of [__init_begin, __init_end],
8032          *    please refer to arch/tile/kernel/vmlinux.lds.S.
8033          * 3) .rodata.* may be embedded into .text or .data sections.
8034          */
8035 #define adj_init_size(start, end, size, pos, adj) \
8036         do { \
8037                 if (start <= pos && pos < end && size > adj) \
8038                         size -= adj; \
8039         } while (0)
8040
8041         adj_init_size(__init_begin, __init_end, init_data_size,
8042                      _sinittext, init_code_size);
8043         adj_init_size(_stext, _etext, codesize, _sinittext, init_code_size);
8044         adj_init_size(_sdata, _edata, datasize, __init_begin, init_data_size);
8045         adj_init_size(_stext, _etext, codesize, __start_rodata, rosize);
8046         adj_init_size(_sdata, _edata, datasize, __start_rodata, rosize);
8047
8048 #undef  adj_init_size
8049
8050         pr_info("Memory: %luK/%luK available (%luK kernel code, %luK rwdata, %luK rodata, %luK init, %luK bss, %luK reserved, %luK cma-reserved"
8051 #ifdef  CONFIG_HIGHMEM
8052                 ", %luK highmem"
8053 #endif
8054                 ")\n",
8055                 nr_free_pages() << (PAGE_SHIFT - 10),
8056                 physpages << (PAGE_SHIFT - 10),
8057                 codesize >> 10, datasize >> 10, rosize >> 10,
8058                 (init_data_size + init_code_size) >> 10, bss_size >> 10,
8059                 (physpages - totalram_pages() - totalcma_pages) << (PAGE_SHIFT - 10),
8060                 totalcma_pages << (PAGE_SHIFT - 10)
8061 #ifdef  CONFIG_HIGHMEM
8062                 , totalhigh_pages() << (PAGE_SHIFT - 10)
8063 #endif
8064                 );
8065 }
8066
8067 /**
8068  * set_dma_reserve - set the specified number of pages reserved in the first zone
8069  * @new_dma_reserve: The number of pages to mark reserved
8070  *
8071  * The per-cpu batchsize and zone watermarks are determined by managed_pages.
8072  * In the DMA zone, a significant percentage may be consumed by kernel image
8073  * and other unfreeable allocations which can skew the watermarks badly. This
8074  * function may optionally be used to account for unfreeable pages in the
8075  * first zone (e.g., ZONE_DMA). The effect will be lower watermarks and
8076  * smaller per-cpu batchsize.
8077  */
8078 void __init set_dma_reserve(unsigned long new_dma_reserve)
8079 {
8080         dma_reserve = new_dma_reserve;
8081 }
8082
8083 static int page_alloc_cpu_dead(unsigned int cpu)
8084 {
8085         struct zone *zone;
8086
8087         lru_add_drain_cpu(cpu);
8088         drain_pages(cpu);
8089
8090         /*
8091          * Spill the event counters of the dead processor
8092          * into the current processors event counters.
8093          * This artificially elevates the count of the current
8094          * processor.
8095          */
8096         vm_events_fold_cpu(cpu);
8097
8098         /*
8099          * Zero the differential counters of the dead processor
8100          * so that the vm statistics are consistent.
8101          *
8102          * This is only okay since the processor is dead and cannot
8103          * race with what we are doing.
8104          */
8105         cpu_vm_stats_fold(cpu);
8106
8107         for_each_populated_zone(zone)
8108                 zone_pcp_update(zone, 0);
8109
8110         return 0;
8111 }
8112
8113 static int page_alloc_cpu_online(unsigned int cpu)
8114 {
8115         struct zone *zone;
8116
8117         for_each_populated_zone(zone)
8118                 zone_pcp_update(zone, 1);
8119         return 0;
8120 }
8121
8122 #ifdef CONFIG_NUMA
8123 int hashdist = HASHDIST_DEFAULT;
8124
8125 static int __init set_hashdist(char *str)
8126 {
8127         if (!str)
8128                 return 0;
8129         hashdist = simple_strtoul(str, &str, 0);
8130         return 1;
8131 }
8132 __setup("hashdist=", set_hashdist);
8133 #endif
8134
8135 void __init page_alloc_init(void)
8136 {
8137         int ret;
8138
8139 #ifdef CONFIG_NUMA
8140         if (num_node_state(N_MEMORY) == 1)
8141                 hashdist = 0;
8142 #endif
8143
8144         ret = cpuhp_setup_state_nocalls(CPUHP_PAGE_ALLOC,
8145                                         "mm/page_alloc:pcp",
8146                                         page_alloc_cpu_online,
8147                                         page_alloc_cpu_dead);
8148         WARN_ON(ret < 0);
8149 }
8150
8151 /*
8152  * calculate_totalreserve_pages - called when sysctl_lowmem_reserve_ratio
8153  *      or min_free_kbytes changes.
8154  */
8155 static void calculate_totalreserve_pages(void)
8156 {
8157         struct pglist_data *pgdat;
8158         unsigned long reserve_pages = 0;
8159         enum zone_type i, j;
8160
8161         for_each_online_pgdat(pgdat) {
8162
8163                 pgdat->totalreserve_pages = 0;
8164
8165                 for (i = 0; i < MAX_NR_ZONES; i++) {
8166                         struct zone *zone = pgdat->node_zones + i;
8167                         long max = 0;
8168                         unsigned long managed_pages = zone_managed_pages(zone);
8169
8170                         /* Find valid and maximum lowmem_reserve in the zone */
8171                         for (j = i; j < MAX_NR_ZONES; j++) {
8172                                 if (zone->lowmem_reserve[j] > max)
8173                                         max = zone->lowmem_reserve[j];
8174                         }
8175
8176                         /* we treat the high watermark as reserved pages. */
8177                         max += high_wmark_pages(zone);
8178
8179                         if (max > managed_pages)
8180                                 max = managed_pages;
8181
8182                         pgdat->totalreserve_pages += max;
8183
8184                         reserve_pages += max;
8185                 }
8186         }
8187         totalreserve_pages = reserve_pages;
8188 }
8189
8190 /*
8191  * setup_per_zone_lowmem_reserve - called whenever
8192  *      sysctl_lowmem_reserve_ratio changes.  Ensures that each zone
8193  *      has a correct pages reserved value, so an adequate number of
8194  *      pages are left in the zone after a successful __alloc_pages().
8195  */
8196 static void setup_per_zone_lowmem_reserve(void)
8197 {
8198         struct pglist_data *pgdat;
8199         enum zone_type i, j;
8200
8201         for_each_online_pgdat(pgdat) {
8202                 for (i = 0; i < MAX_NR_ZONES - 1; i++) {
8203                         struct zone *zone = &pgdat->node_zones[i];
8204                         int ratio = sysctl_lowmem_reserve_ratio[i];
8205                         bool clear = !ratio || !zone_managed_pages(zone);
8206                         unsigned long managed_pages = 0;
8207
8208                         for (j = i + 1; j < MAX_NR_ZONES; j++) {
8209                                 if (clear) {
8210                                         zone->lowmem_reserve[j] = 0;
8211                                 } else {
8212                                         struct zone *upper_zone = &pgdat->node_zones[j];
8213
8214                                         managed_pages += zone_managed_pages(upper_zone);
8215                                         zone->lowmem_reserve[j] = managed_pages / ratio;
8216                                 }
8217                         }
8218                 }
8219         }
8220
8221         /* update totalreserve_pages */
8222         calculate_totalreserve_pages();
8223 }
8224
8225 static void __setup_per_zone_wmarks(void)
8226 {
8227         unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
8228         unsigned long lowmem_pages = 0;
8229         struct zone *zone;
8230         unsigned long flags;
8231
8232         /* Calculate total number of !ZONE_HIGHMEM pages */
8233         for_each_zone(zone) {
8234                 if (!is_highmem(zone))
8235                         lowmem_pages += zone_managed_pages(zone);
8236         }
8237
8238         for_each_zone(zone) {
8239                 u64 tmp;
8240
8241                 spin_lock_irqsave(&zone->lock, flags);
8242                 tmp = (u64)pages_min * zone_managed_pages(zone);
8243                 do_div(tmp, lowmem_pages);
8244                 if (is_highmem(zone)) {
8245                         /*
8246                          * __GFP_HIGH and PF_MEMALLOC allocations usually don't
8247                          * need highmem pages, so cap pages_min to a small
8248                          * value here.
8249                          *
8250                          * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN)
8251                          * deltas control async page reclaim, and so should
8252                          * not be capped for highmem.
8253                          */
8254                         unsigned long min_pages;
8255
8256                         min_pages = zone_managed_pages(zone) / 1024;
8257                         min_pages = clamp(min_pages, SWAP_CLUSTER_MAX, 128UL);
8258                         zone->_watermark[WMARK_MIN] = min_pages;
8259                 } else {
8260                         /*
8261                          * If it's a lowmem zone, reserve a number of pages
8262                          * proportionate to the zone's size.
8263                          */
8264                         zone->_watermark[WMARK_MIN] = tmp;
8265                 }
8266
8267                 /*
8268                  * Set the kswapd watermarks distance according to the
8269                  * scale factor in proportion to available memory, but
8270                  * ensure a minimum size on small systems.
8271                  */
8272                 tmp = max_t(u64, tmp >> 2,
8273                             mult_frac(zone_managed_pages(zone),
8274                                       watermark_scale_factor, 10000));
8275
8276                 zone->watermark_boost = 0;
8277                 zone->_watermark[WMARK_LOW]  = min_wmark_pages(zone) + tmp;
8278                 zone->_watermark[WMARK_HIGH] = min_wmark_pages(zone) + tmp * 2;
8279
8280                 spin_unlock_irqrestore(&zone->lock, flags);
8281         }
8282
8283         /* update totalreserve_pages */
8284         calculate_totalreserve_pages();
8285 }
8286
8287 /**
8288  * setup_per_zone_wmarks - called when min_free_kbytes changes
8289  * or when memory is hot-{added|removed}
8290  *
8291  * Ensures that the watermark[min,low,high] values for each zone are set
8292  * correctly with respect to min_free_kbytes.
8293  */
8294 void setup_per_zone_wmarks(void)
8295 {
8296         struct zone *zone;
8297         static DEFINE_SPINLOCK(lock);
8298
8299         spin_lock(&lock);
8300         __setup_per_zone_wmarks();
8301         spin_unlock(&lock);
8302
8303         /*
8304          * The watermark size have changed so update the pcpu batch
8305          * and high limits or the limits may be inappropriate.
8306          */
8307         for_each_zone(zone)
8308                 zone_pcp_update(zone, 0);
8309 }
8310
8311 /*
8312  * Initialise min_free_kbytes.
8313  *
8314  * For small machines we want it small (128k min).  For large machines
8315  * we want it large (256MB max).  But it is not linear, because network
8316  * bandwidth does not increase linearly with machine size.  We use
8317  *
8318  *      min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
8319  *      min_free_kbytes = sqrt(lowmem_kbytes * 16)
8320  *
8321  * which yields
8322  *
8323  * 16MB:        512k
8324  * 32MB:        724k
8325  * 64MB:        1024k
8326  * 128MB:       1448k
8327  * 256MB:       2048k
8328  * 512MB:       2896k
8329  * 1024MB:      4096k
8330  * 2048MB:      5792k
8331  * 4096MB:      8192k
8332  * 8192MB:      11584k
8333  * 16384MB:     16384k
8334  */
8335 int __meminit init_per_zone_wmark_min(void)
8336 {
8337         unsigned long lowmem_kbytes;
8338         int new_min_free_kbytes;
8339
8340         lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
8341         new_min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
8342
8343         if (new_min_free_kbytes > user_min_free_kbytes) {
8344                 min_free_kbytes = new_min_free_kbytes;
8345                 if (min_free_kbytes < 128)
8346                         min_free_kbytes = 128;
8347                 if (min_free_kbytes > 262144)
8348                         min_free_kbytes = 262144;
8349         } else {
8350                 pr_warn("min_free_kbytes is not updated to %d because user defined value %d is preferred\n",
8351                                 new_min_free_kbytes, user_min_free_kbytes);
8352         }
8353         setup_per_zone_wmarks();
8354         refresh_zone_stat_thresholds();
8355         setup_per_zone_lowmem_reserve();
8356
8357 #ifdef CONFIG_NUMA
8358         setup_min_unmapped_ratio();
8359         setup_min_slab_ratio();
8360 #endif
8361
8362         khugepaged_min_free_kbytes_update();
8363
8364         return 0;
8365 }
8366 postcore_initcall(init_per_zone_wmark_min)
8367
8368 /*
8369  * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
8370  *      that we can call two helper functions whenever min_free_kbytes
8371  *      changes.
8372  */
8373 int min_free_kbytes_sysctl_handler(struct ctl_table *table, int write,
8374                 void *buffer, size_t *length, loff_t *ppos)
8375 {
8376         int rc;
8377
8378         rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
8379         if (rc)
8380                 return rc;
8381
8382         if (write) {
8383                 user_min_free_kbytes = min_free_kbytes;
8384                 setup_per_zone_wmarks();
8385         }
8386         return 0;
8387 }
8388
8389 int watermark_scale_factor_sysctl_handler(struct ctl_table *table, int write,
8390                 void *buffer, size_t *length, loff_t *ppos)
8391 {
8392         int rc;
8393
8394         rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
8395         if (rc)
8396                 return rc;
8397
8398         if (write)
8399                 setup_per_zone_wmarks();
8400
8401         return 0;
8402 }
8403
8404 #ifdef CONFIG_NUMA
8405 static void setup_min_unmapped_ratio(void)
8406 {
8407         pg_data_t *pgdat;
8408         struct zone *zone;
8409
8410         for_each_online_pgdat(pgdat)
8411                 pgdat->min_unmapped_pages = 0;
8412
8413         for_each_zone(zone)
8414                 zone->zone_pgdat->min_unmapped_pages += (zone_managed_pages(zone) *
8415                                                          sysctl_min_unmapped_ratio) / 100;
8416 }
8417
8418
8419 int sysctl_min_unmapped_ratio_sysctl_handler(struct ctl_table *table, int write,
8420                 void *buffer, size_t *length, loff_t *ppos)
8421 {
8422         int rc;
8423
8424         rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
8425         if (rc)
8426                 return rc;
8427
8428         setup_min_unmapped_ratio();
8429
8430         return 0;
8431 }
8432
8433 static void setup_min_slab_ratio(void)
8434 {
8435         pg_data_t *pgdat;
8436         struct zone *zone;
8437
8438         for_each_online_pgdat(pgdat)
8439                 pgdat->min_slab_pages = 0;
8440
8441         for_each_zone(zone)
8442                 zone->zone_pgdat->min_slab_pages += (zone_managed_pages(zone) *
8443                                                      sysctl_min_slab_ratio) / 100;
8444 }
8445
8446 int sysctl_min_slab_ratio_sysctl_handler(struct ctl_table *table, int write,
8447                 void *buffer, size_t *length, loff_t *ppos)
8448 {
8449         int rc;
8450
8451         rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
8452         if (rc)
8453                 return rc;
8454
8455         setup_min_slab_ratio();
8456
8457         return 0;
8458 }
8459 #endif
8460
8461 /*
8462  * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
8463  *      proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
8464  *      whenever sysctl_lowmem_reserve_ratio changes.
8465  *
8466  * The reserve ratio obviously has absolutely no relation with the
8467  * minimum watermarks. The lowmem reserve ratio can only make sense
8468  * if in function of the boot time zone sizes.
8469  */
8470 int lowmem_reserve_ratio_sysctl_handler(struct ctl_table *table, int write,
8471                 void *buffer, size_t *length, loff_t *ppos)
8472 {
8473         int i;
8474
8475         proc_dointvec_minmax(table, write, buffer, length, ppos);
8476
8477         for (i = 0; i < MAX_NR_ZONES; i++) {
8478                 if (sysctl_lowmem_reserve_ratio[i] < 1)
8479                         sysctl_lowmem_reserve_ratio[i] = 0;
8480         }
8481
8482         setup_per_zone_lowmem_reserve();
8483         return 0;
8484 }
8485
8486 #ifndef __HAVE_ARCH_RESERVED_KERNEL_PAGES
8487 /*
8488  * Returns the number of pages that arch has reserved but
8489  * is not known to alloc_large_system_hash().
8490  */
8491 static unsigned long __init arch_reserved_kernel_pages(void)
8492 {
8493         return 0;
8494 }
8495 #endif
8496
8497 /*
8498  * Adaptive scale is meant to reduce sizes of hash tables on large memory
8499  * machines. As memory size is increased the scale is also increased but at
8500  * slower pace.  Starting from ADAPT_SCALE_BASE (64G), every time memory
8501  * quadruples the scale is increased by one, which means the size of hash table
8502  * only doubles, instead of quadrupling as well.
8503  * Because 32-bit systems cannot have large physical memory, where this scaling
8504  * makes sense, it is disabled on such platforms.
8505  */
8506 #if __BITS_PER_LONG > 32
8507 #define ADAPT_SCALE_BASE        (64ul << 30)
8508 #define ADAPT_SCALE_SHIFT       2
8509 #define ADAPT_SCALE_NPAGES      (ADAPT_SCALE_BASE >> PAGE_SHIFT)
8510 #endif
8511
8512 /*
8513  * allocate a large system hash table from bootmem
8514  * - it is assumed that the hash table must contain an exact power-of-2
8515  *   quantity of entries
8516  * - limit is the number of hash buckets, not the total allocation size
8517  */
8518 void *__init alloc_large_system_hash(const char *tablename,
8519                                      unsigned long bucketsize,
8520                                      unsigned long numentries,
8521                                      int scale,
8522                                      int flags,
8523                                      unsigned int *_hash_shift,
8524                                      unsigned int *_hash_mask,
8525                                      unsigned long low_limit,
8526                                      unsigned long high_limit)
8527 {
8528         unsigned long long max = high_limit;
8529         unsigned long log2qty, size;
8530         void *table = NULL;
8531         gfp_t gfp_flags;
8532         bool virt;
8533         bool huge;
8534
8535         /* allow the kernel cmdline to have a say */
8536         if (!numentries) {
8537                 /* round applicable memory size up to nearest megabyte */
8538                 numentries = nr_kernel_pages;
8539                 numentries -= arch_reserved_kernel_pages();
8540
8541                 /* It isn't necessary when PAGE_SIZE >= 1MB */
8542                 if (PAGE_SHIFT < 20)
8543                         numentries = round_up(numentries, (1<<20)/PAGE_SIZE);
8544
8545 #if __BITS_PER_LONG > 32
8546                 if (!high_limit) {
8547                         unsigned long adapt;
8548
8549                         for (adapt = ADAPT_SCALE_NPAGES; adapt < numentries;
8550                              adapt <<= ADAPT_SCALE_SHIFT)
8551                                 scale++;
8552                 }
8553 #endif
8554
8555                 /* limit to 1 bucket per 2^scale bytes of low memory */
8556                 if (scale > PAGE_SHIFT)
8557                         numentries >>= (scale - PAGE_SHIFT);
8558                 else
8559                         numentries <<= (PAGE_SHIFT - scale);
8560
8561                 /* Make sure we've got at least a 0-order allocation.. */
8562                 if (unlikely(flags & HASH_SMALL)) {
8563                         /* Makes no sense without HASH_EARLY */
8564                         WARN_ON(!(flags & HASH_EARLY));
8565                         if (!(numentries >> *_hash_shift)) {
8566                                 numentries = 1UL << *_hash_shift;
8567                                 BUG_ON(!numentries);
8568                         }
8569                 } else if (unlikely((numentries * bucketsize) < PAGE_SIZE))
8570                         numentries = PAGE_SIZE / bucketsize;
8571         }
8572         numentries = roundup_pow_of_two(numentries);
8573
8574         /* limit allocation size to 1/16 total memory by default */
8575         if (max == 0) {
8576                 max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
8577                 do_div(max, bucketsize);
8578         }
8579         max = min(max, 0x80000000ULL);
8580
8581         if (numentries < low_limit)
8582                 numentries = low_limit;
8583         if (numentries > max)
8584                 numentries = max;
8585
8586         log2qty = ilog2(numentries);
8587
8588         gfp_flags = (flags & HASH_ZERO) ? GFP_ATOMIC | __GFP_ZERO : GFP_ATOMIC;
8589         do {
8590                 virt = false;
8591                 size = bucketsize << log2qty;
8592                 if (flags & HASH_EARLY) {
8593                         if (flags & HASH_ZERO)
8594                                 table = memblock_alloc(size, SMP_CACHE_BYTES);
8595                         else
8596                                 table = memblock_alloc_raw(size,
8597                                                            SMP_CACHE_BYTES);
8598                 } else if (get_order(size) >= MAX_ORDER || hashdist) {
8599                         table = __vmalloc(size, gfp_flags);
8600                         virt = true;
8601                         huge = is_vm_area_hugepages(table);
8602                 } else {
8603                         /*
8604                          * If bucketsize is not a power-of-two, we may free
8605                          * some pages at the end of hash table which
8606                          * alloc_pages_exact() automatically does
8607                          */
8608                         table = alloc_pages_exact(size, gfp_flags);
8609                         kmemleak_alloc(table, size, 1, gfp_flags);
8610                 }
8611         } while (!table && size > PAGE_SIZE && --log2qty);
8612
8613         if (!table)
8614                 panic("Failed to allocate %s hash table\n", tablename);
8615
8616         pr_info("%s hash table entries: %ld (order: %d, %lu bytes, %s)\n",
8617                 tablename, 1UL << log2qty, ilog2(size) - PAGE_SHIFT, size,
8618                 virt ? (huge ? "vmalloc hugepage" : "vmalloc") : "linear");
8619
8620         if (_hash_shift)
8621                 *_hash_shift = log2qty;
8622         if (_hash_mask)
8623                 *_hash_mask = (1 << log2qty) - 1;
8624
8625         return table;
8626 }
8627
8628 /*
8629  * This function checks whether pageblock includes unmovable pages or not.
8630  *
8631  * PageLRU check without isolation or lru_lock could race so that
8632  * MIGRATE_MOVABLE block might include unmovable pages. And __PageMovable
8633  * check without lock_page also may miss some movable non-lru pages at
8634  * race condition. So you can't expect this function should be exact.
8635  *
8636  * Returns a page without holding a reference. If the caller wants to
8637  * dereference that page (e.g., dumping), it has to make sure that it
8638  * cannot get removed (e.g., via memory unplug) concurrently.
8639  *
8640  */
8641 struct page *has_unmovable_pages(struct zone *zone, struct page *page,
8642                                  int migratetype, int flags)
8643 {
8644         unsigned long iter = 0;
8645         unsigned long pfn = page_to_pfn(page);
8646         unsigned long offset = pfn % pageblock_nr_pages;
8647
8648         if (is_migrate_cma_page(page)) {
8649                 /*
8650                  * CMA allocations (alloc_contig_range) really need to mark
8651                  * isolate CMA pageblocks even when they are not movable in fact
8652                  * so consider them movable here.
8653                  */
8654                 if (is_migrate_cma(migratetype))
8655                         return NULL;
8656
8657                 return page;
8658         }
8659
8660         for (; iter < pageblock_nr_pages - offset; iter++) {
8661                 if (!pfn_valid_within(pfn + iter))
8662                         continue;
8663
8664                 page = pfn_to_page(pfn + iter);
8665
8666                 /*
8667                  * Both, bootmem allocations and memory holes are marked
8668                  * PG_reserved and are unmovable. We can even have unmovable
8669                  * allocations inside ZONE_MOVABLE, for example when
8670                  * specifying "movablecore".
8671                  */
8672                 if (PageReserved(page))
8673                         return page;
8674
8675                 /*
8676                  * If the zone is movable and we have ruled out all reserved
8677                  * pages then it should be reasonably safe to assume the rest
8678                  * is movable.
8679                  */
8680                 if (zone_idx(zone) == ZONE_MOVABLE)
8681                         continue;
8682
8683                 /*
8684                  * Hugepages are not in LRU lists, but they're movable.
8685                  * THPs are on the LRU, but need to be counted as #small pages.
8686                  * We need not scan over tail pages because we don't
8687                  * handle each tail page individually in migration.
8688                  */
8689                 if (PageHuge(page) || PageTransCompound(page)) {
8690                         struct page *head = compound_head(page);
8691                         unsigned int skip_pages;
8692
8693                         if (PageHuge(page)) {
8694                                 if (!hugepage_migration_supported(page_hstate(head)))
8695                                         return page;
8696                         } else if (!PageLRU(head) && !__PageMovable(head)) {
8697                                 return page;
8698                         }
8699
8700                         skip_pages = compound_nr(head) - (page - head);
8701                         iter += skip_pages - 1;
8702                         continue;
8703                 }
8704
8705                 /*
8706                  * We can't use page_count without pin a page
8707                  * because another CPU can free compound page.
8708                  * This check already skips compound tails of THP
8709                  * because their page->_refcount is zero at all time.
8710                  */
8711                 if (!page_ref_count(page)) {
8712                         if (PageBuddy(page))
8713                                 iter += (1 << buddy_order(page)) - 1;
8714                         continue;
8715                 }
8716
8717                 /*
8718                  * The HWPoisoned page may be not in buddy system, and
8719                  * page_count() is not 0.
8720                  */
8721                 if ((flags & MEMORY_OFFLINE) && PageHWPoison(page))
8722                         continue;
8723
8724                 /*
8725                  * We treat all PageOffline() pages as movable when offlining
8726                  * to give drivers a chance to decrement their reference count
8727                  * in MEM_GOING_OFFLINE in order to indicate that these pages
8728                  * can be offlined as there are no direct references anymore.
8729                  * For actually unmovable PageOffline() where the driver does
8730                  * not support this, we will fail later when trying to actually
8731                  * move these pages that still have a reference count > 0.
8732                  * (false negatives in this function only)
8733                  */
8734                 if ((flags & MEMORY_OFFLINE) && PageOffline(page))
8735                         continue;
8736
8737                 if (__PageMovable(page) || PageLRU(page))
8738                         continue;
8739
8740                 /*
8741                  * If there are RECLAIMABLE pages, we need to check
8742                  * it.  But now, memory offline itself doesn't call
8743                  * shrink_node_slabs() and it still to be fixed.
8744                  */
8745                 return page;
8746         }
8747         return NULL;
8748 }
8749
8750 #ifdef CONFIG_CONTIG_ALLOC
8751 static unsigned long pfn_max_align_down(unsigned long pfn)
8752 {
8753         return pfn & ~(max_t(unsigned long, MAX_ORDER_NR_PAGES,
8754                              pageblock_nr_pages) - 1);
8755 }
8756
8757 static unsigned long pfn_max_align_up(unsigned long pfn)
8758 {
8759         return ALIGN(pfn, max_t(unsigned long, MAX_ORDER_NR_PAGES,
8760                                 pageblock_nr_pages));
8761 }
8762
8763 #if defined(CONFIG_DYNAMIC_DEBUG) || \
8764         (defined(CONFIG_DYNAMIC_DEBUG_CORE) && defined(DYNAMIC_DEBUG_MODULE))
8765 /* Usage: See admin-guide/dynamic-debug-howto.rst */
8766 static void alloc_contig_dump_pages(struct list_head *page_list)
8767 {
8768         DEFINE_DYNAMIC_DEBUG_METADATA(descriptor, "migrate failure");
8769
8770         if (DYNAMIC_DEBUG_BRANCH(descriptor)) {
8771                 struct page *page;
8772
8773                 dump_stack();
8774                 list_for_each_entry(page, page_list, lru)
8775                         dump_page(page, "migration failure");
8776         }
8777 }
8778 #else
8779 static inline void alloc_contig_dump_pages(struct list_head *page_list)
8780 {
8781 }
8782 #endif
8783
8784 /* [start, end) must belong to a single zone. */
8785 static int __alloc_contig_migrate_range(struct compact_control *cc,
8786                                         unsigned long start, unsigned long end)
8787 {
8788         /* This function is based on compact_zone() from compaction.c. */
8789         unsigned int nr_reclaimed;
8790         unsigned long pfn = start;
8791         unsigned int tries = 0;
8792         int ret = 0;
8793         struct migration_target_control mtc = {
8794                 .nid = zone_to_nid(cc->zone),
8795                 .gfp_mask = GFP_USER | __GFP_MOVABLE | __GFP_RETRY_MAYFAIL,
8796         };
8797
8798         lru_cache_disable();
8799
8800         while (pfn < end || !list_empty(&cc->migratepages)) {
8801                 if (fatal_signal_pending(current)) {
8802                         ret = -EINTR;
8803                         break;
8804                 }
8805
8806                 if (list_empty(&cc->migratepages)) {
8807                         cc->nr_migratepages = 0;
8808                         ret = isolate_migratepages_range(cc, pfn, end);
8809                         if (ret && ret != -EAGAIN)
8810                                 break;
8811                         pfn = cc->migrate_pfn;
8812                         tries = 0;
8813                 } else if (++tries == 5) {
8814                         ret = -EBUSY;
8815                         break;
8816                 }
8817
8818                 nr_reclaimed = reclaim_clean_pages_from_list(cc->zone,
8819                                                         &cc->migratepages);
8820                 cc->nr_migratepages -= nr_reclaimed;
8821
8822                 ret = migrate_pages(&cc->migratepages, alloc_migration_target,
8823                                 NULL, (unsigned long)&mtc, cc->mode, MR_CONTIG_RANGE);
8824
8825                 /*
8826                  * On -ENOMEM, migrate_pages() bails out right away. It is pointless
8827                  * to retry again over this error, so do the same here.
8828                  */
8829                 if (ret == -ENOMEM)
8830                         break;
8831         }
8832
8833         lru_cache_enable();
8834         if (ret < 0) {
8835                 if (ret == -EBUSY)
8836                         alloc_contig_dump_pages(&cc->migratepages);
8837                 putback_movable_pages(&cc->migratepages);
8838                 return ret;
8839         }
8840         return 0;
8841 }
8842
8843 /**
8844  * alloc_contig_range() -- tries to allocate given range of pages
8845  * @start:      start PFN to allocate
8846  * @end:        one-past-the-last PFN to allocate
8847  * @migratetype:        migratetype of the underlying pageblocks (either
8848  *                      #MIGRATE_MOVABLE or #MIGRATE_CMA).  All pageblocks
8849  *                      in range must have the same migratetype and it must
8850  *                      be either of the two.
8851  * @gfp_mask:   GFP mask to use during compaction
8852  *
8853  * The PFN range does not have to be pageblock or MAX_ORDER_NR_PAGES
8854  * aligned.  The PFN range must belong to a single zone.
8855  *
8856  * The first thing this routine does is attempt to MIGRATE_ISOLATE all
8857  * pageblocks in the range.  Once isolated, the pageblocks should not
8858  * be modified by others.
8859  *
8860  * Return: zero on success or negative error code.  On success all
8861  * pages which PFN is in [start, end) are allocated for the caller and
8862  * need to be freed with free_contig_range().
8863  */
8864 int alloc_contig_range(unsigned long start, unsigned long end,
8865                        unsigned migratetype, gfp_t gfp_mask)
8866 {
8867         unsigned long outer_start, outer_end;
8868         unsigned int order;
8869         int ret = 0;
8870
8871         struct compact_control cc = {
8872                 .nr_migratepages = 0,
8873                 .order = -1,
8874                 .zone = page_zone(pfn_to_page(start)),
8875                 .mode = MIGRATE_SYNC,
8876                 .ignore_skip_hint = true,
8877                 .no_set_skip_hint = true,
8878                 .gfp_mask = current_gfp_context(gfp_mask),
8879                 .alloc_contig = true,
8880         };
8881         INIT_LIST_HEAD(&cc.migratepages);
8882
8883         /*
8884          * What we do here is we mark all pageblocks in range as
8885          * MIGRATE_ISOLATE.  Because pageblock and max order pages may
8886          * have different sizes, and due to the way page allocator
8887          * work, we align the range to biggest of the two pages so
8888          * that page allocator won't try to merge buddies from
8889          * different pageblocks and change MIGRATE_ISOLATE to some
8890          * other migration type.
8891          *
8892          * Once the pageblocks are marked as MIGRATE_ISOLATE, we
8893          * migrate the pages from an unaligned range (ie. pages that
8894          * we are interested in).  This will put all the pages in
8895          * range back to page allocator as MIGRATE_ISOLATE.
8896          *
8897          * When this is done, we take the pages in range from page
8898          * allocator removing them from the buddy system.  This way
8899          * page allocator will never consider using them.
8900          *
8901          * This lets us mark the pageblocks back as
8902          * MIGRATE_CMA/MIGRATE_MOVABLE so that free pages in the
8903          * aligned range but not in the unaligned, original range are
8904          * put back to page allocator so that buddy can use them.
8905          */
8906
8907         ret = start_isolate_page_range(pfn_max_align_down(start),
8908                                        pfn_max_align_up(end), migratetype, 0);
8909         if (ret)
8910                 return ret;
8911
8912         drain_all_pages(cc.zone);
8913
8914         /*
8915          * In case of -EBUSY, we'd like to know which page causes problem.
8916          * So, just fall through. test_pages_isolated() has a tracepoint
8917          * which will report the busy page.
8918          *
8919          * It is possible that busy pages could become available before
8920          * the call to test_pages_isolated, and the range will actually be
8921          * allocated.  So, if we fall through be sure to clear ret so that
8922          * -EBUSY is not accidentally used or returned to caller.
8923          */
8924         ret = __alloc_contig_migrate_range(&cc, start, end);
8925         if (ret && ret != -EBUSY)
8926                 goto done;
8927         ret = 0;
8928
8929         /*
8930          * Pages from [start, end) are within a MAX_ORDER_NR_PAGES
8931          * aligned blocks that are marked as MIGRATE_ISOLATE.  What's
8932          * more, all pages in [start, end) are free in page allocator.
8933          * What we are going to do is to allocate all pages from
8934          * [start, end) (that is remove them from page allocator).
8935          *
8936          * The only problem is that pages at the beginning and at the
8937          * end of interesting range may be not aligned with pages that
8938          * page allocator holds, ie. they can be part of higher order
8939          * pages.  Because of this, we reserve the bigger range and
8940          * once this is done free the pages we are not interested in.
8941          *
8942          * We don't have to hold zone->lock here because the pages are
8943          * isolated thus they won't get removed from buddy.
8944          */
8945
8946         order = 0;
8947         outer_start = start;
8948         while (!PageBuddy(pfn_to_page(outer_start))) {
8949                 if (++order >= MAX_ORDER) {
8950                         outer_start = start;
8951                         break;
8952                 }
8953                 outer_start &= ~0UL << order;
8954         }
8955
8956         if (outer_start != start) {
8957                 order = buddy_order(pfn_to_page(outer_start));
8958
8959                 /*
8960                  * outer_start page could be small order buddy page and
8961                  * it doesn't include start page. Adjust outer_start
8962                  * in this case to report failed page properly
8963                  * on tracepoint in test_pages_isolated()
8964                  */
8965                 if (outer_start + (1UL << order) <= start)
8966                         outer_start = start;
8967         }
8968
8969         /* Make sure the range is really isolated. */
8970         if (test_pages_isolated(outer_start, end, 0)) {
8971                 ret = -EBUSY;
8972                 goto done;
8973         }
8974
8975         /* Grab isolated pages from freelists. */
8976         outer_end = isolate_freepages_range(&cc, outer_start, end);
8977         if (!outer_end) {
8978                 ret = -EBUSY;
8979                 goto done;
8980         }
8981
8982         /* Free head and tail (if any) */
8983         if (start != outer_start)
8984                 free_contig_range(outer_start, start - outer_start);
8985         if (end != outer_end)
8986                 free_contig_range(end, outer_end - end);
8987
8988 done:
8989         undo_isolate_page_range(pfn_max_align_down(start),
8990                                 pfn_max_align_up(end), migratetype);
8991         return ret;
8992 }
8993 EXPORT_SYMBOL(alloc_contig_range);
8994
8995 static int __alloc_contig_pages(unsigned long start_pfn,
8996                                 unsigned long nr_pages, gfp_t gfp_mask)
8997 {
8998         unsigned long end_pfn = start_pfn + nr_pages;
8999
9000         return alloc_contig_range(start_pfn, end_pfn, MIGRATE_MOVABLE,
9001                                   gfp_mask);
9002 }
9003
9004 static bool pfn_range_valid_contig(struct zone *z, unsigned long start_pfn,
9005                                    unsigned long nr_pages)
9006 {
9007         unsigned long i, end_pfn = start_pfn + nr_pages;
9008         struct page *page;
9009
9010         for (i = start_pfn; i < end_pfn; i++) {
9011                 page = pfn_to_online_page(i);
9012                 if (!page)
9013                         return false;
9014
9015                 if (page_zone(page) != z)
9016                         return false;
9017
9018                 if (PageReserved(page))
9019                         return false;
9020         }
9021         return true;
9022 }
9023
9024 static bool zone_spans_last_pfn(const struct zone *zone,
9025                                 unsigned long start_pfn, unsigned long nr_pages)
9026 {
9027         unsigned long last_pfn = start_pfn + nr_pages - 1;
9028
9029         return zone_spans_pfn(zone, last_pfn);
9030 }
9031
9032 /**
9033  * alloc_contig_pages() -- tries to find and allocate contiguous range of pages
9034  * @nr_pages:   Number of contiguous pages to allocate
9035  * @gfp_mask:   GFP mask to limit search and used during compaction
9036  * @nid:        Target node
9037  * @nodemask:   Mask for other possible nodes
9038  *
9039  * This routine is a wrapper around alloc_contig_range(). It scans over zones
9040  * on an applicable zonelist to find a contiguous pfn range which can then be
9041  * tried for allocation with alloc_contig_range(). This routine is intended
9042  * for allocation requests which can not be fulfilled with the buddy allocator.
9043  *
9044  * The allocated memory is always aligned to a page boundary. If nr_pages is a
9045  * power of two then the alignment is guaranteed to be to the given nr_pages
9046  * (e.g. 1GB request would be aligned to 1GB).
9047  *
9048  * Allocated pages can be freed with free_contig_range() or by manually calling
9049  * __free_page() on each allocated page.
9050  *
9051  * Return: pointer to contiguous pages on success, or NULL if not successful.
9052  */
9053 struct page *alloc_contig_pages(unsigned long nr_pages, gfp_t gfp_mask,
9054                                 int nid, nodemask_t *nodemask)
9055 {
9056         unsigned long ret, pfn, flags;
9057         struct zonelist *zonelist;
9058         struct zone *zone;
9059         struct zoneref *z;
9060
9061         zonelist = node_zonelist(nid, gfp_mask);
9062         for_each_zone_zonelist_nodemask(zone, z, zonelist,
9063                                         gfp_zone(gfp_mask), nodemask) {
9064                 spin_lock_irqsave(&zone->lock, flags);
9065
9066                 pfn = ALIGN(zone->zone_start_pfn, nr_pages);
9067                 while (zone_spans_last_pfn(zone, pfn, nr_pages)) {
9068                         if (pfn_range_valid_contig(zone, pfn, nr_pages)) {
9069                                 /*
9070                                  * We release the zone lock here because
9071                                  * alloc_contig_range() will also lock the zone
9072                                  * at some point. If there's an allocation
9073                                  * spinning on this lock, it may win the race
9074                                  * and cause alloc_contig_range() to fail...
9075                                  */
9076                                 spin_unlock_irqrestore(&zone->lock, flags);
9077                                 ret = __alloc_contig_pages(pfn, nr_pages,
9078                                                         gfp_mask);
9079                                 if (!ret)
9080                                         return pfn_to_page(pfn);
9081                                 spin_lock_irqsave(&zone->lock, flags);
9082                         }
9083                         pfn += nr_pages;
9084                 }
9085                 spin_unlock_irqrestore(&zone->lock, flags);
9086         }
9087         return NULL;
9088 }
9089 #endif /* CONFIG_CONTIG_ALLOC */
9090
9091 void free_contig_range(unsigned long pfn, unsigned long nr_pages)
9092 {
9093         unsigned long count = 0;
9094
9095         for (; nr_pages--; pfn++) {
9096                 struct page *page = pfn_to_page(pfn);
9097
9098                 count += page_count(page) != 1;
9099                 __free_page(page);
9100         }
9101         WARN(count != 0, "%lu pages are still in use!\n", count);
9102 }
9103 EXPORT_SYMBOL(free_contig_range);
9104
9105 /*
9106  * The zone indicated has a new number of managed_pages; batch sizes and percpu
9107  * page high values need to be recalculated.
9108  */
9109 void zone_pcp_update(struct zone *zone, int cpu_online)
9110 {
9111         mutex_lock(&pcp_batch_high_lock);
9112         zone_set_pageset_high_and_batch(zone, cpu_online);
9113         mutex_unlock(&pcp_batch_high_lock);
9114 }
9115
9116 /*
9117  * Effectively disable pcplists for the zone by setting the high limit to 0
9118  * and draining all cpus. A concurrent page freeing on another CPU that's about
9119  * to put the page on pcplist will either finish before the drain and the page
9120  * will be drained, or observe the new high limit and skip the pcplist.
9121  *
9122  * Must be paired with a call to zone_pcp_enable().
9123  */
9124 void zone_pcp_disable(struct zone *zone)
9125 {
9126         mutex_lock(&pcp_batch_high_lock);
9127         __zone_set_pageset_high_and_batch(zone, 0, 1);
9128         __drain_all_pages(zone, true);
9129 }
9130
9131 void zone_pcp_enable(struct zone *zone)
9132 {
9133         __zone_set_pageset_high_and_batch(zone, zone->pageset_high, zone->pageset_batch);
9134         mutex_unlock(&pcp_batch_high_lock);
9135 }
9136
9137 void zone_pcp_reset(struct zone *zone)
9138 {
9139         int cpu;
9140         struct per_cpu_zonestat *pzstats;
9141
9142         if (zone->per_cpu_pageset != &boot_pageset) {
9143                 for_each_online_cpu(cpu) {
9144                         pzstats = per_cpu_ptr(zone->per_cpu_zonestats, cpu);
9145                         drain_zonestat(zone, pzstats);
9146                 }
9147                 free_percpu(zone->per_cpu_pageset);
9148                 free_percpu(zone->per_cpu_zonestats);
9149                 zone->per_cpu_pageset = &boot_pageset;
9150                 zone->per_cpu_zonestats = &boot_zonestats;
9151         }
9152 }
9153
9154 #ifdef CONFIG_MEMORY_HOTREMOVE
9155 /*
9156  * All pages in the range must be in a single zone, must not contain holes,
9157  * must span full sections, and must be isolated before calling this function.
9158  */
9159 void __offline_isolated_pages(unsigned long start_pfn, unsigned long end_pfn)
9160 {
9161         unsigned long pfn = start_pfn;
9162         struct page *page;
9163         struct zone *zone;
9164         unsigned int order;
9165         unsigned long flags;
9166
9167         offline_mem_sections(pfn, end_pfn);
9168         zone = page_zone(pfn_to_page(pfn));
9169         spin_lock_irqsave(&zone->lock, flags);
9170         while (pfn < end_pfn) {
9171                 page = pfn_to_page(pfn);
9172                 /*
9173                  * The HWPoisoned page may be not in buddy system, and
9174                  * page_count() is not 0.
9175                  */
9176                 if (unlikely(!PageBuddy(page) && PageHWPoison(page))) {
9177                         pfn++;
9178                         continue;
9179                 }
9180                 /*
9181                  * At this point all remaining PageOffline() pages have a
9182                  * reference count of 0 and can simply be skipped.
9183                  */
9184                 if (PageOffline(page)) {
9185                         BUG_ON(page_count(page));
9186                         BUG_ON(PageBuddy(page));
9187                         pfn++;
9188                         continue;
9189                 }
9190
9191                 BUG_ON(page_count(page));
9192                 BUG_ON(!PageBuddy(page));
9193                 order = buddy_order(page);
9194                 del_page_from_free_list(page, zone, order);
9195                 pfn += (1 << order);
9196         }
9197         spin_unlock_irqrestore(&zone->lock, flags);
9198 }
9199 #endif
9200
9201 bool is_free_buddy_page(struct page *page)
9202 {
9203         struct zone *zone = page_zone(page);
9204         unsigned long pfn = page_to_pfn(page);
9205         unsigned long flags;
9206         unsigned int order;
9207
9208         spin_lock_irqsave(&zone->lock, flags);
9209         for (order = 0; order < MAX_ORDER; order++) {
9210                 struct page *page_head = page - (pfn & ((1 << order) - 1));
9211
9212                 if (PageBuddy(page_head) && buddy_order(page_head) >= order)
9213                         break;
9214         }
9215         spin_unlock_irqrestore(&zone->lock, flags);
9216
9217         return order < MAX_ORDER;
9218 }
9219
9220 #ifdef CONFIG_MEMORY_FAILURE
9221 /*
9222  * Break down a higher-order page in sub-pages, and keep our target out of
9223  * buddy allocator.
9224  */
9225 static void break_down_buddy_pages(struct zone *zone, struct page *page,
9226                                    struct page *target, int low, int high,
9227                                    int migratetype)
9228 {
9229         unsigned long size = 1 << high;
9230         struct page *current_buddy, *next_page;
9231
9232         while (high > low) {
9233                 high--;
9234                 size >>= 1;
9235
9236                 if (target >= &page[size]) {
9237                         next_page = page + size;
9238                         current_buddy = page;
9239                 } else {
9240                         next_page = page;
9241                         current_buddy = page + size;
9242                 }
9243
9244                 if (set_page_guard(zone, current_buddy, high, migratetype))
9245                         continue;
9246
9247                 if (current_buddy != target) {
9248                         add_to_free_list(current_buddy, zone, high, migratetype);
9249                         set_buddy_order(current_buddy, high);
9250                         page = next_page;
9251                 }
9252         }
9253 }
9254
9255 /*
9256  * Take a page that will be marked as poisoned off the buddy allocator.
9257  */
9258 bool take_page_off_buddy(struct page *page)
9259 {
9260         struct zone *zone = page_zone(page);
9261         unsigned long pfn = page_to_pfn(page);
9262         unsigned long flags;
9263         unsigned int order;
9264         bool ret = false;
9265
9266         spin_lock_irqsave(&zone->lock, flags);
9267         for (order = 0; order < MAX_ORDER; order++) {
9268                 struct page *page_head = page - (pfn & ((1 << order) - 1));
9269                 int page_order = buddy_order(page_head);
9270
9271                 if (PageBuddy(page_head) && page_order >= order) {
9272                         unsigned long pfn_head = page_to_pfn(page_head);
9273                         int migratetype = get_pfnblock_migratetype(page_head,
9274                                                                    pfn_head);
9275
9276                         del_page_from_free_list(page_head, zone, page_order);
9277                         break_down_buddy_pages(zone, page_head, page, 0,
9278                                                 page_order, migratetype);
9279                         if (!is_migrate_isolate(migratetype))
9280                                 __mod_zone_freepage_state(zone, -1, migratetype);
9281                         ret = true;
9282                         break;
9283                 }
9284                 if (page_count(page_head) > 0)
9285                         break;
9286         }
9287         spin_unlock_irqrestore(&zone->lock, flags);
9288         return ret;
9289 }
9290 #endif