mm/memory_hotplug: optimize memory hotplug
[muen/linux.git] / mm / page_alloc.c
1 /*
2  *  linux/mm/page_alloc.c
3  *
4  *  Manages the free list, the system allocates free pages here.
5  *  Note that kmalloc() lives in slab.c
6  *
7  *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
8  *  Swap reorganised 29.12.95, Stephen Tweedie
9  *  Support of BIGMEM added by Gerhard Wichert, Siemens AG, July 1999
10  *  Reshaped it to be a zoned allocator, Ingo Molnar, Red Hat, 1999
11  *  Discontiguous memory support, Kanoj Sarcar, SGI, Nov 1999
12  *  Zone balancing, Kanoj Sarcar, SGI, Jan 2000
13  *  Per cpu hot/cold page lists, bulk allocation, Martin J. Bligh, Sept 2002
14  *          (lots of bits borrowed from Ingo Molnar & Andrew Morton)
15  */
16
17 #include <linux/stddef.h>
18 #include <linux/mm.h>
19 #include <linux/swap.h>
20 #include <linux/interrupt.h>
21 #include <linux/pagemap.h>
22 #include <linux/jiffies.h>
23 #include <linux/bootmem.h>
24 #include <linux/memblock.h>
25 #include <linux/compiler.h>
26 #include <linux/kernel.h>
27 #include <linux/kasan.h>
28 #include <linux/module.h>
29 #include <linux/suspend.h>
30 #include <linux/pagevec.h>
31 #include <linux/blkdev.h>
32 #include <linux/slab.h>
33 #include <linux/ratelimit.h>
34 #include <linux/oom.h>
35 #include <linux/notifier.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/sort.h>
48 #include <linux/pfn.h>
49 #include <xen/xen.h>
50 #include <linux/backing-dev.h>
51 #include <linux/fault-inject.h>
52 #include <linux/page-isolation.h>
53 #include <linux/page_ext.h>
54 #include <linux/debugobjects.h>
55 #include <linux/kmemleak.h>
56 #include <linux/compaction.h>
57 #include <trace/events/kmem.h>
58 #include <trace/events/oom.h>
59 #include <linux/prefetch.h>
60 #include <linux/mm_inline.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
72 #include <asm/sections.h>
73 #include <asm/tlbflush.h>
74 #include <asm/div64.h>
75 #include "internal.h"
76
77 /* prevent >1 _updater_ of zone percpu pageset ->high and ->batch fields */
78 static DEFINE_MUTEX(pcp_batch_high_lock);
79 #define MIN_PERCPU_PAGELIST_FRACTION    (8)
80
81 #ifdef CONFIG_USE_PERCPU_NUMA_NODE_ID
82 DEFINE_PER_CPU(int, numa_node);
83 EXPORT_PER_CPU_SYMBOL(numa_node);
84 #endif
85
86 DEFINE_STATIC_KEY_TRUE(vm_numa_stat_key);
87
88 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
89 /*
90  * N.B., Do NOT reference the '_numa_mem_' per cpu variable directly.
91  * It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined.
92  * Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem()
93  * defined in <linux/topology.h>.
94  */
95 DEFINE_PER_CPU(int, _numa_mem_);                /* Kernel "local memory" node */
96 EXPORT_PER_CPU_SYMBOL(_numa_mem_);
97 int _node_numa_mem_[MAX_NUMNODES];
98 #endif
99
100 /* work_structs for global per-cpu drains */
101 DEFINE_MUTEX(pcpu_drain_mutex);
102 DEFINE_PER_CPU(struct work_struct, pcpu_drain);
103
104 #ifdef CONFIG_GCC_PLUGIN_LATENT_ENTROPY
105 volatile unsigned long latent_entropy __latent_entropy;
106 EXPORT_SYMBOL(latent_entropy);
107 #endif
108
109 /*
110  * Array of node states.
111  */
112 nodemask_t node_states[NR_NODE_STATES] __read_mostly = {
113         [N_POSSIBLE] = NODE_MASK_ALL,
114         [N_ONLINE] = { { [0] = 1UL } },
115 #ifndef CONFIG_NUMA
116         [N_NORMAL_MEMORY] = { { [0] = 1UL } },
117 #ifdef CONFIG_HIGHMEM
118         [N_HIGH_MEMORY] = { { [0] = 1UL } },
119 #endif
120         [N_MEMORY] = { { [0] = 1UL } },
121         [N_CPU] = { { [0] = 1UL } },
122 #endif  /* NUMA */
123 };
124 EXPORT_SYMBOL(node_states);
125
126 /* Protect totalram_pages and zone->managed_pages */
127 static DEFINE_SPINLOCK(managed_page_count_lock);
128
129 unsigned long totalram_pages __read_mostly;
130 unsigned long totalreserve_pages __read_mostly;
131 unsigned long totalcma_pages __read_mostly;
132
133 int percpu_pagelist_fraction;
134 gfp_t gfp_allowed_mask __read_mostly = GFP_BOOT_MASK;
135
136 /*
137  * A cached value of the page's pageblock's migratetype, used when the page is
138  * put on a pcplist. Used to avoid the pageblock migratetype lookup when
139  * freeing from pcplists in most cases, at the cost of possibly becoming stale.
140  * Also the migratetype set in the page does not necessarily match the pcplist
141  * index, e.g. page might have MIGRATE_CMA set but be on a pcplist with any
142  * other index - this ensures that it will be put on the correct CMA freelist.
143  */
144 static inline int get_pcppage_migratetype(struct page *page)
145 {
146         return page->index;
147 }
148
149 static inline void set_pcppage_migratetype(struct page *page, int migratetype)
150 {
151         page->index = migratetype;
152 }
153
154 #ifdef CONFIG_PM_SLEEP
155 /*
156  * The following functions are used by the suspend/hibernate code to temporarily
157  * change gfp_allowed_mask in order to avoid using I/O during memory allocations
158  * while devices are suspended.  To avoid races with the suspend/hibernate code,
159  * they should always be called with pm_mutex held (gfp_allowed_mask also should
160  * only be modified with pm_mutex held, unless the suspend/hibernate code is
161  * guaranteed not to run in parallel with that modification).
162  */
163
164 static gfp_t saved_gfp_mask;
165
166 void pm_restore_gfp_mask(void)
167 {
168         WARN_ON(!mutex_is_locked(&pm_mutex));
169         if (saved_gfp_mask) {
170                 gfp_allowed_mask = saved_gfp_mask;
171                 saved_gfp_mask = 0;
172         }
173 }
174
175 void pm_restrict_gfp_mask(void)
176 {
177         WARN_ON(!mutex_is_locked(&pm_mutex));
178         WARN_ON(saved_gfp_mask);
179         saved_gfp_mask = gfp_allowed_mask;
180         gfp_allowed_mask &= ~(__GFP_IO | __GFP_FS);
181 }
182
183 bool pm_suspended_storage(void)
184 {
185         if ((gfp_allowed_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
186                 return false;
187         return true;
188 }
189 #endif /* CONFIG_PM_SLEEP */
190
191 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
192 unsigned int pageblock_order __read_mostly;
193 #endif
194
195 static void __free_pages_ok(struct page *page, unsigned int order);
196
197 /*
198  * results with 256, 32 in the lowmem_reserve sysctl:
199  *      1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
200  *      1G machine -> (16M dma, 784M normal, 224M high)
201  *      NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
202  *      HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
203  *      HIGHMEM allocation will leave (224M+784M)/256 of ram reserved in ZONE_DMA
204  *
205  * TBD: should special case ZONE_DMA32 machines here - in those we normally
206  * don't need any ZONE_NORMAL reservation
207  */
208 int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES-1] = {
209 #ifdef CONFIG_ZONE_DMA
210          256,
211 #endif
212 #ifdef CONFIG_ZONE_DMA32
213          256,
214 #endif
215 #ifdef CONFIG_HIGHMEM
216          32,
217 #endif
218          32,
219 };
220
221 EXPORT_SYMBOL(totalram_pages);
222
223 static char * const zone_names[MAX_NR_ZONES] = {
224 #ifdef CONFIG_ZONE_DMA
225          "DMA",
226 #endif
227 #ifdef CONFIG_ZONE_DMA32
228          "DMA32",
229 #endif
230          "Normal",
231 #ifdef CONFIG_HIGHMEM
232          "HighMem",
233 #endif
234          "Movable",
235 #ifdef CONFIG_ZONE_DEVICE
236          "Device",
237 #endif
238 };
239
240 char * const migratetype_names[MIGRATE_TYPES] = {
241         "Unmovable",
242         "Movable",
243         "Reclaimable",
244         "HighAtomic",
245 #ifdef CONFIG_CMA
246         "CMA",
247 #endif
248 #ifdef CONFIG_MEMORY_ISOLATION
249         "Isolate",
250 #endif
251 };
252
253 compound_page_dtor * const compound_page_dtors[] = {
254         NULL,
255         free_compound_page,
256 #ifdef CONFIG_HUGETLB_PAGE
257         free_huge_page,
258 #endif
259 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
260         free_transhuge_page,
261 #endif
262 };
263
264 int min_free_kbytes = 1024;
265 int user_min_free_kbytes = -1;
266 int watermark_scale_factor = 10;
267
268 static unsigned long __meminitdata nr_kernel_pages;
269 static unsigned long __meminitdata nr_all_pages;
270 static unsigned long __meminitdata dma_reserve;
271
272 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
273 static unsigned long __meminitdata arch_zone_lowest_possible_pfn[MAX_NR_ZONES];
274 static unsigned long __meminitdata arch_zone_highest_possible_pfn[MAX_NR_ZONES];
275 static unsigned long __initdata required_kernelcore;
276 static unsigned long __initdata required_movablecore;
277 static unsigned long __meminitdata zone_movable_pfn[MAX_NUMNODES];
278 static bool mirrored_kernelcore;
279
280 /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
281 int movable_zone;
282 EXPORT_SYMBOL(movable_zone);
283 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
284
285 #if MAX_NUMNODES > 1
286 int nr_node_ids __read_mostly = MAX_NUMNODES;
287 int nr_online_nodes __read_mostly = 1;
288 EXPORT_SYMBOL(nr_node_ids);
289 EXPORT_SYMBOL(nr_online_nodes);
290 #endif
291
292 int page_group_by_mobility_disabled __read_mostly;
293
294 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
295 /* Returns true if the struct page for the pfn is uninitialised */
296 static inline bool __meminit early_page_uninitialised(unsigned long pfn)
297 {
298         int nid = early_pfn_to_nid(pfn);
299
300         if (node_online(nid) && pfn >= NODE_DATA(nid)->first_deferred_pfn)
301                 return true;
302
303         return false;
304 }
305
306 /*
307  * Returns false when the remaining initialisation should be deferred until
308  * later in the boot cycle when it can be parallelised.
309  */
310 static inline bool update_defer_init(pg_data_t *pgdat,
311                                 unsigned long pfn, unsigned long zone_end,
312                                 unsigned long *nr_initialised)
313 {
314         /* Always populate low zones for address-constrained allocations */
315         if (zone_end < pgdat_end_pfn(pgdat))
316                 return true;
317         /* Xen PV domains need page structures early */
318         if (xen_pv_domain())
319                 return true;
320         (*nr_initialised)++;
321         if ((*nr_initialised > pgdat->static_init_pgcnt) &&
322             (pfn & (PAGES_PER_SECTION - 1)) == 0) {
323                 pgdat->first_deferred_pfn = pfn;
324                 return false;
325         }
326
327         return true;
328 }
329 #else
330 static inline bool early_page_uninitialised(unsigned long pfn)
331 {
332         return false;
333 }
334
335 static inline bool update_defer_init(pg_data_t *pgdat,
336                                 unsigned long pfn, unsigned long zone_end,
337                                 unsigned long *nr_initialised)
338 {
339         return true;
340 }
341 #endif
342
343 /* Return a pointer to the bitmap storing bits affecting a block of pages */
344 static inline unsigned long *get_pageblock_bitmap(struct page *page,
345                                                         unsigned long pfn)
346 {
347 #ifdef CONFIG_SPARSEMEM
348         return __pfn_to_section(pfn)->pageblock_flags;
349 #else
350         return page_zone(page)->pageblock_flags;
351 #endif /* CONFIG_SPARSEMEM */
352 }
353
354 static inline int pfn_to_bitidx(struct page *page, unsigned long pfn)
355 {
356 #ifdef CONFIG_SPARSEMEM
357         pfn &= (PAGES_PER_SECTION-1);
358         return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
359 #else
360         pfn = pfn - round_down(page_zone(page)->zone_start_pfn, pageblock_nr_pages);
361         return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
362 #endif /* CONFIG_SPARSEMEM */
363 }
364
365 /**
366  * get_pfnblock_flags_mask - Return the requested group of flags for the pageblock_nr_pages block of pages
367  * @page: The page within the block of interest
368  * @pfn: The target page frame number
369  * @end_bitidx: The last bit of interest to retrieve
370  * @mask: mask of bits that the caller is interested in
371  *
372  * Return: pageblock_bits flags
373  */
374 static __always_inline unsigned long __get_pfnblock_flags_mask(struct page *page,
375                                         unsigned long pfn,
376                                         unsigned long end_bitidx,
377                                         unsigned long mask)
378 {
379         unsigned long *bitmap;
380         unsigned long bitidx, word_bitidx;
381         unsigned long word;
382
383         bitmap = get_pageblock_bitmap(page, pfn);
384         bitidx = pfn_to_bitidx(page, pfn);
385         word_bitidx = bitidx / BITS_PER_LONG;
386         bitidx &= (BITS_PER_LONG-1);
387
388         word = bitmap[word_bitidx];
389         bitidx += end_bitidx;
390         return (word >> (BITS_PER_LONG - bitidx - 1)) & mask;
391 }
392
393 unsigned long get_pfnblock_flags_mask(struct page *page, unsigned long pfn,
394                                         unsigned long end_bitidx,
395                                         unsigned long mask)
396 {
397         return __get_pfnblock_flags_mask(page, pfn, end_bitidx, mask);
398 }
399
400 static __always_inline int get_pfnblock_migratetype(struct page *page, unsigned long pfn)
401 {
402         return __get_pfnblock_flags_mask(page, pfn, PB_migrate_end, MIGRATETYPE_MASK);
403 }
404
405 /**
406  * set_pfnblock_flags_mask - Set the requested group of flags for a pageblock_nr_pages block of pages
407  * @page: The page within the block of interest
408  * @flags: The flags to set
409  * @pfn: The target page frame number
410  * @end_bitidx: The last bit of interest
411  * @mask: mask of bits that the caller is interested in
412  */
413 void set_pfnblock_flags_mask(struct page *page, unsigned long flags,
414                                         unsigned long pfn,
415                                         unsigned long end_bitidx,
416                                         unsigned long mask)
417 {
418         unsigned long *bitmap;
419         unsigned long bitidx, word_bitidx;
420         unsigned long old_word, word;
421
422         BUILD_BUG_ON(NR_PAGEBLOCK_BITS != 4);
423
424         bitmap = get_pageblock_bitmap(page, pfn);
425         bitidx = pfn_to_bitidx(page, pfn);
426         word_bitidx = bitidx / BITS_PER_LONG;
427         bitidx &= (BITS_PER_LONG-1);
428
429         VM_BUG_ON_PAGE(!zone_spans_pfn(page_zone(page), pfn), page);
430
431         bitidx += end_bitidx;
432         mask <<= (BITS_PER_LONG - bitidx - 1);
433         flags <<= (BITS_PER_LONG - bitidx - 1);
434
435         word = READ_ONCE(bitmap[word_bitidx]);
436         for (;;) {
437                 old_word = cmpxchg(&bitmap[word_bitidx], word, (word & ~mask) | flags);
438                 if (word == old_word)
439                         break;
440                 word = old_word;
441         }
442 }
443
444 void set_pageblock_migratetype(struct page *page, int migratetype)
445 {
446         if (unlikely(page_group_by_mobility_disabled &&
447                      migratetype < MIGRATE_PCPTYPES))
448                 migratetype = MIGRATE_UNMOVABLE;
449
450         set_pageblock_flags_group(page, (unsigned long)migratetype,
451                                         PB_migrate, PB_migrate_end);
452 }
453
454 #ifdef CONFIG_DEBUG_VM
455 static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
456 {
457         int ret = 0;
458         unsigned seq;
459         unsigned long pfn = page_to_pfn(page);
460         unsigned long sp, start_pfn;
461
462         do {
463                 seq = zone_span_seqbegin(zone);
464                 start_pfn = zone->zone_start_pfn;
465                 sp = zone->spanned_pages;
466                 if (!zone_spans_pfn(zone, pfn))
467                         ret = 1;
468         } while (zone_span_seqretry(zone, seq));
469
470         if (ret)
471                 pr_err("page 0x%lx outside node %d zone %s [ 0x%lx - 0x%lx ]\n",
472                         pfn, zone_to_nid(zone), zone->name,
473                         start_pfn, start_pfn + sp);
474
475         return ret;
476 }
477
478 static int page_is_consistent(struct zone *zone, struct page *page)
479 {
480         if (!pfn_valid_within(page_to_pfn(page)))
481                 return 0;
482         if (zone != page_zone(page))
483                 return 0;
484
485         return 1;
486 }
487 /*
488  * Temporary debugging check for pages not lying within a given zone.
489  */
490 static int __maybe_unused bad_range(struct zone *zone, struct page *page)
491 {
492         if (page_outside_zone_boundaries(zone, page))
493                 return 1;
494         if (!page_is_consistent(zone, page))
495                 return 1;
496
497         return 0;
498 }
499 #else
500 static inline int __maybe_unused bad_range(struct zone *zone, struct page *page)
501 {
502         return 0;
503 }
504 #endif
505
506 static void bad_page(struct page *page, const char *reason,
507                 unsigned long bad_flags)
508 {
509         static unsigned long resume;
510         static unsigned long nr_shown;
511         static unsigned long nr_unshown;
512
513         /*
514          * Allow a burst of 60 reports, then keep quiet for that minute;
515          * or allow a steady drip of one report per second.
516          */
517         if (nr_shown == 60) {
518                 if (time_before(jiffies, resume)) {
519                         nr_unshown++;
520                         goto out;
521                 }
522                 if (nr_unshown) {
523                         pr_alert(
524                               "BUG: Bad page state: %lu messages suppressed\n",
525                                 nr_unshown);
526                         nr_unshown = 0;
527                 }
528                 nr_shown = 0;
529         }
530         if (nr_shown++ == 0)
531                 resume = jiffies + 60 * HZ;
532
533         pr_alert("BUG: Bad page state in process %s  pfn:%05lx\n",
534                 current->comm, page_to_pfn(page));
535         __dump_page(page, reason);
536         bad_flags &= page->flags;
537         if (bad_flags)
538                 pr_alert("bad because of flags: %#lx(%pGp)\n",
539                                                 bad_flags, &bad_flags);
540         dump_page_owner(page);
541
542         print_modules();
543         dump_stack();
544 out:
545         /* Leave bad fields for debug, except PageBuddy could make trouble */
546         page_mapcount_reset(page); /* remove PageBuddy */
547         add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
548 }
549
550 /*
551  * Higher-order pages are called "compound pages".  They are structured thusly:
552  *
553  * The first PAGE_SIZE page is called the "head page" and have PG_head set.
554  *
555  * The remaining PAGE_SIZE pages are called "tail pages". PageTail() is encoded
556  * in bit 0 of page->compound_head. The rest of bits is pointer to head page.
557  *
558  * The first tail page's ->compound_dtor holds the offset in array of compound
559  * page destructors. See compound_page_dtors.
560  *
561  * The first tail page's ->compound_order holds the order of allocation.
562  * This usage means that zero-order pages may not be compound.
563  */
564
565 void free_compound_page(struct page *page)
566 {
567         __free_pages_ok(page, compound_order(page));
568 }
569
570 void prep_compound_page(struct page *page, unsigned int order)
571 {
572         int i;
573         int nr_pages = 1 << order;
574
575         set_compound_page_dtor(page, COMPOUND_PAGE_DTOR);
576         set_compound_order(page, order);
577         __SetPageHead(page);
578         for (i = 1; i < nr_pages; i++) {
579                 struct page *p = page + i;
580                 set_page_count(p, 0);
581                 p->mapping = TAIL_MAPPING;
582                 set_compound_head(p, page);
583         }
584         atomic_set(compound_mapcount_ptr(page), -1);
585 }
586
587 #ifdef CONFIG_DEBUG_PAGEALLOC
588 unsigned int _debug_guardpage_minorder;
589 bool _debug_pagealloc_enabled __read_mostly
590                         = IS_ENABLED(CONFIG_DEBUG_PAGEALLOC_ENABLE_DEFAULT);
591 EXPORT_SYMBOL(_debug_pagealloc_enabled);
592 bool _debug_guardpage_enabled __read_mostly;
593
594 static int __init early_debug_pagealloc(char *buf)
595 {
596         if (!buf)
597                 return -EINVAL;
598         return kstrtobool(buf, &_debug_pagealloc_enabled);
599 }
600 early_param("debug_pagealloc", early_debug_pagealloc);
601
602 static bool need_debug_guardpage(void)
603 {
604         /* If we don't use debug_pagealloc, we don't need guard page */
605         if (!debug_pagealloc_enabled())
606                 return false;
607
608         if (!debug_guardpage_minorder())
609                 return false;
610
611         return true;
612 }
613
614 static void init_debug_guardpage(void)
615 {
616         if (!debug_pagealloc_enabled())
617                 return;
618
619         if (!debug_guardpage_minorder())
620                 return;
621
622         _debug_guardpage_enabled = true;
623 }
624
625 struct page_ext_operations debug_guardpage_ops = {
626         .need = need_debug_guardpage,
627         .init = init_debug_guardpage,
628 };
629
630 static int __init debug_guardpage_minorder_setup(char *buf)
631 {
632         unsigned long res;
633
634         if (kstrtoul(buf, 10, &res) < 0 ||  res > MAX_ORDER / 2) {
635                 pr_err("Bad debug_guardpage_minorder value\n");
636                 return 0;
637         }
638         _debug_guardpage_minorder = res;
639         pr_info("Setting debug_guardpage_minorder to %lu\n", res);
640         return 0;
641 }
642 early_param("debug_guardpage_minorder", debug_guardpage_minorder_setup);
643
644 static inline bool set_page_guard(struct zone *zone, struct page *page,
645                                 unsigned int order, int migratetype)
646 {
647         struct page_ext *page_ext;
648
649         if (!debug_guardpage_enabled())
650                 return false;
651
652         if (order >= debug_guardpage_minorder())
653                 return false;
654
655         page_ext = lookup_page_ext(page);
656         if (unlikely(!page_ext))
657                 return false;
658
659         __set_bit(PAGE_EXT_DEBUG_GUARD, &page_ext->flags);
660
661         INIT_LIST_HEAD(&page->lru);
662         set_page_private(page, order);
663         /* Guard pages are not available for any usage */
664         __mod_zone_freepage_state(zone, -(1 << order), migratetype);
665
666         return true;
667 }
668
669 static inline void clear_page_guard(struct zone *zone, struct page *page,
670                                 unsigned int order, int migratetype)
671 {
672         struct page_ext *page_ext;
673
674         if (!debug_guardpage_enabled())
675                 return;
676
677         page_ext = lookup_page_ext(page);
678         if (unlikely(!page_ext))
679                 return;
680
681         __clear_bit(PAGE_EXT_DEBUG_GUARD, &page_ext->flags);
682
683         set_page_private(page, 0);
684         if (!is_migrate_isolate(migratetype))
685                 __mod_zone_freepage_state(zone, (1 << order), migratetype);
686 }
687 #else
688 struct page_ext_operations debug_guardpage_ops;
689 static inline bool set_page_guard(struct zone *zone, struct page *page,
690                         unsigned int order, int migratetype) { return false; }
691 static inline void clear_page_guard(struct zone *zone, struct page *page,
692                                 unsigned int order, int migratetype) {}
693 #endif
694
695 static inline void set_page_order(struct page *page, unsigned int order)
696 {
697         set_page_private(page, order);
698         __SetPageBuddy(page);
699 }
700
701 static inline void rmv_page_order(struct page *page)
702 {
703         __ClearPageBuddy(page);
704         set_page_private(page, 0);
705 }
706
707 /*
708  * This function checks whether a page is free && is the buddy
709  * we can do coalesce a page and its buddy if
710  * (a) the buddy is not in a hole (check before calling!) &&
711  * (b) the buddy is in the buddy system &&
712  * (c) a page and its buddy have the same order &&
713  * (d) a page and its buddy are in the same zone.
714  *
715  * For recording whether a page is in the buddy system, we set ->_mapcount
716  * PAGE_BUDDY_MAPCOUNT_VALUE.
717  * Setting, clearing, and testing _mapcount PAGE_BUDDY_MAPCOUNT_VALUE is
718  * serialized by zone->lock.
719  *
720  * For recording page's order, we use page_private(page).
721  */
722 static inline int page_is_buddy(struct page *page, struct page *buddy,
723                                                         unsigned int order)
724 {
725         if (page_is_guard(buddy) && page_order(buddy) == order) {
726                 if (page_zone_id(page) != page_zone_id(buddy))
727                         return 0;
728
729                 VM_BUG_ON_PAGE(page_count(buddy) != 0, buddy);
730
731                 return 1;
732         }
733
734         if (PageBuddy(buddy) && page_order(buddy) == order) {
735                 /*
736                  * zone check is done late to avoid uselessly
737                  * calculating zone/node ids for pages that could
738                  * never merge.
739                  */
740                 if (page_zone_id(page) != page_zone_id(buddy))
741                         return 0;
742
743                 VM_BUG_ON_PAGE(page_count(buddy) != 0, buddy);
744
745                 return 1;
746         }
747         return 0;
748 }
749
750 /*
751  * Freeing function for a buddy system allocator.
752  *
753  * The concept of a buddy system is to maintain direct-mapped table
754  * (containing bit values) for memory blocks of various "orders".
755  * The bottom level table contains the map for the smallest allocatable
756  * units of memory (here, pages), and each level above it describes
757  * pairs of units from the levels below, hence, "buddies".
758  * At a high level, all that happens here is marking the table entry
759  * at the bottom level available, and propagating the changes upward
760  * as necessary, plus some accounting needed to play nicely with other
761  * parts of the VM system.
762  * At each level, we keep a list of pages, which are heads of continuous
763  * free pages of length of (1 << order) and marked with _mapcount
764  * PAGE_BUDDY_MAPCOUNT_VALUE. Page's order is recorded in page_private(page)
765  * field.
766  * So when we are allocating or freeing one, we can derive the state of the
767  * other.  That is, if we allocate a small block, and both were
768  * free, the remainder of the region must be split into blocks.
769  * If a block is freed, and its buddy is also free, then this
770  * triggers coalescing into a block of larger size.
771  *
772  * -- nyc
773  */
774
775 static inline void __free_one_page(struct page *page,
776                 unsigned long pfn,
777                 struct zone *zone, unsigned int order,
778                 int migratetype)
779 {
780         unsigned long combined_pfn;
781         unsigned long uninitialized_var(buddy_pfn);
782         struct page *buddy;
783         unsigned int max_order;
784
785         max_order = min_t(unsigned int, MAX_ORDER, pageblock_order + 1);
786
787         VM_BUG_ON(!zone_is_initialized(zone));
788         VM_BUG_ON_PAGE(page->flags & PAGE_FLAGS_CHECK_AT_PREP, page);
789
790         VM_BUG_ON(migratetype == -1);
791         if (likely(!is_migrate_isolate(migratetype)))
792                 __mod_zone_freepage_state(zone, 1 << order, migratetype);
793
794         VM_BUG_ON_PAGE(pfn & ((1 << order) - 1), page);
795         VM_BUG_ON_PAGE(bad_range(zone, page), page);
796
797 continue_merging:
798         while (order < max_order - 1) {
799                 buddy_pfn = __find_buddy_pfn(pfn, order);
800                 buddy = page + (buddy_pfn - pfn);
801
802                 if (!pfn_valid_within(buddy_pfn))
803                         goto done_merging;
804                 if (!page_is_buddy(page, buddy, order))
805                         goto done_merging;
806                 /*
807                  * Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page,
808                  * merge with it and move up one order.
809                  */
810                 if (page_is_guard(buddy)) {
811                         clear_page_guard(zone, buddy, order, migratetype);
812                 } else {
813                         list_del(&buddy->lru);
814                         zone->free_area[order].nr_free--;
815                         rmv_page_order(buddy);
816                 }
817                 combined_pfn = buddy_pfn & pfn;
818                 page = page + (combined_pfn - pfn);
819                 pfn = combined_pfn;
820                 order++;
821         }
822         if (max_order < MAX_ORDER) {
823                 /* If we are here, it means order is >= pageblock_order.
824                  * We want to prevent merge between freepages on isolate
825                  * pageblock and normal pageblock. Without this, pageblock
826                  * isolation could cause incorrect freepage or CMA accounting.
827                  *
828                  * We don't want to hit this code for the more frequent
829                  * low-order merging.
830                  */
831                 if (unlikely(has_isolate_pageblock(zone))) {
832                         int buddy_mt;
833
834                         buddy_pfn = __find_buddy_pfn(pfn, order);
835                         buddy = page + (buddy_pfn - pfn);
836                         buddy_mt = get_pageblock_migratetype(buddy);
837
838                         if (migratetype != buddy_mt
839                                         && (is_migrate_isolate(migratetype) ||
840                                                 is_migrate_isolate(buddy_mt)))
841                                 goto done_merging;
842                 }
843                 max_order++;
844                 goto continue_merging;
845         }
846
847 done_merging:
848         set_page_order(page, order);
849
850         /*
851          * If this is not the largest possible page, check if the buddy
852          * of the next-highest order is free. If it is, it's possible
853          * that pages are being freed that will coalesce soon. In case,
854          * that is happening, add the free page to the tail of the list
855          * so it's less likely to be used soon and more likely to be merged
856          * as a higher order page
857          */
858         if ((order < MAX_ORDER-2) && pfn_valid_within(buddy_pfn)) {
859                 struct page *higher_page, *higher_buddy;
860                 combined_pfn = buddy_pfn & pfn;
861                 higher_page = page + (combined_pfn - pfn);
862                 buddy_pfn = __find_buddy_pfn(combined_pfn, order + 1);
863                 higher_buddy = higher_page + (buddy_pfn - combined_pfn);
864                 if (pfn_valid_within(buddy_pfn) &&
865                     page_is_buddy(higher_page, higher_buddy, order + 1)) {
866                         list_add_tail(&page->lru,
867                                 &zone->free_area[order].free_list[migratetype]);
868                         goto out;
869                 }
870         }
871
872         list_add(&page->lru, &zone->free_area[order].free_list[migratetype]);
873 out:
874         zone->free_area[order].nr_free++;
875 }
876
877 /*
878  * A bad page could be due to a number of fields. Instead of multiple branches,
879  * try and check multiple fields with one check. The caller must do a detailed
880  * check if necessary.
881  */
882 static inline bool page_expected_state(struct page *page,
883                                         unsigned long check_flags)
884 {
885         if (unlikely(atomic_read(&page->_mapcount) != -1))
886                 return false;
887
888         if (unlikely((unsigned long)page->mapping |
889                         page_ref_count(page) |
890 #ifdef CONFIG_MEMCG
891                         (unsigned long)page->mem_cgroup |
892 #endif
893                         (page->flags & check_flags)))
894                 return false;
895
896         return true;
897 }
898
899 static void free_pages_check_bad(struct page *page)
900 {
901         const char *bad_reason;
902         unsigned long bad_flags;
903
904         bad_reason = NULL;
905         bad_flags = 0;
906
907         if (unlikely(atomic_read(&page->_mapcount) != -1))
908                 bad_reason = "nonzero mapcount";
909         if (unlikely(page->mapping != NULL))
910                 bad_reason = "non-NULL mapping";
911         if (unlikely(page_ref_count(page) != 0))
912                 bad_reason = "nonzero _refcount";
913         if (unlikely(page->flags & PAGE_FLAGS_CHECK_AT_FREE)) {
914                 bad_reason = "PAGE_FLAGS_CHECK_AT_FREE flag(s) set";
915                 bad_flags = PAGE_FLAGS_CHECK_AT_FREE;
916         }
917 #ifdef CONFIG_MEMCG
918         if (unlikely(page->mem_cgroup))
919                 bad_reason = "page still charged to cgroup";
920 #endif
921         bad_page(page, bad_reason, bad_flags);
922 }
923
924 static inline int free_pages_check(struct page *page)
925 {
926         if (likely(page_expected_state(page, PAGE_FLAGS_CHECK_AT_FREE)))
927                 return 0;
928
929         /* Something has gone sideways, find it */
930         free_pages_check_bad(page);
931         return 1;
932 }
933
934 static int free_tail_pages_check(struct page *head_page, struct page *page)
935 {
936         int ret = 1;
937
938         /*
939          * We rely page->lru.next never has bit 0 set, unless the page
940          * is PageTail(). Let's make sure that's true even for poisoned ->lru.
941          */
942         BUILD_BUG_ON((unsigned long)LIST_POISON1 & 1);
943
944         if (!IS_ENABLED(CONFIG_DEBUG_VM)) {
945                 ret = 0;
946                 goto out;
947         }
948         switch (page - head_page) {
949         case 1:
950                 /* the first tail page: ->mapping is compound_mapcount() */
951                 if (unlikely(compound_mapcount(page))) {
952                         bad_page(page, "nonzero compound_mapcount", 0);
953                         goto out;
954                 }
955                 break;
956         case 2:
957                 /*
958                  * the second tail page: ->mapping is
959                  * page_deferred_list().next -- ignore value.
960                  */
961                 break;
962         default:
963                 if (page->mapping != TAIL_MAPPING) {
964                         bad_page(page, "corrupted mapping in tail page", 0);
965                         goto out;
966                 }
967                 break;
968         }
969         if (unlikely(!PageTail(page))) {
970                 bad_page(page, "PageTail not set", 0);
971                 goto out;
972         }
973         if (unlikely(compound_head(page) != head_page)) {
974                 bad_page(page, "compound_head not consistent", 0);
975                 goto out;
976         }
977         ret = 0;
978 out:
979         page->mapping = NULL;
980         clear_compound_head(page);
981         return ret;
982 }
983
984 static __always_inline bool free_pages_prepare(struct page *page,
985                                         unsigned int order, bool check_free)
986 {
987         int bad = 0;
988
989         VM_BUG_ON_PAGE(PageTail(page), page);
990
991         trace_mm_page_free(page, order);
992
993         /*
994          * Check tail pages before head page information is cleared to
995          * avoid checking PageCompound for order-0 pages.
996          */
997         if (unlikely(order)) {
998                 bool compound = PageCompound(page);
999                 int i;
1000
1001                 VM_BUG_ON_PAGE(compound && compound_order(page) != order, page);
1002
1003                 if (compound)
1004                         ClearPageDoubleMap(page);
1005                 for (i = 1; i < (1 << order); i++) {
1006                         if (compound)
1007                                 bad += free_tail_pages_check(page, page + i);
1008                         if (unlikely(free_pages_check(page + i))) {
1009                                 bad++;
1010                                 continue;
1011                         }
1012                         (page + i)->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
1013                 }
1014         }
1015         if (PageMappingFlags(page))
1016                 page->mapping = NULL;
1017         if (memcg_kmem_enabled() && PageKmemcg(page))
1018                 memcg_kmem_uncharge(page, order);
1019         if (check_free)
1020                 bad += free_pages_check(page);
1021         if (bad)
1022                 return false;
1023
1024         page_cpupid_reset_last(page);
1025         page->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
1026         reset_page_owner(page, order);
1027
1028         if (!PageHighMem(page)) {
1029                 debug_check_no_locks_freed(page_address(page),
1030                                            PAGE_SIZE << order);
1031                 debug_check_no_obj_freed(page_address(page),
1032                                            PAGE_SIZE << order);
1033         }
1034         arch_free_page(page, order);
1035         kernel_poison_pages(page, 1 << order, 0);
1036         kernel_map_pages(page, 1 << order, 0);
1037         kasan_free_pages(page, order);
1038
1039         return true;
1040 }
1041
1042 #ifdef CONFIG_DEBUG_VM
1043 static inline bool free_pcp_prepare(struct page *page)
1044 {
1045         return free_pages_prepare(page, 0, true);
1046 }
1047
1048 static inline bool bulkfree_pcp_prepare(struct page *page)
1049 {
1050         return false;
1051 }
1052 #else
1053 static bool free_pcp_prepare(struct page *page)
1054 {
1055         return free_pages_prepare(page, 0, false);
1056 }
1057
1058 static bool bulkfree_pcp_prepare(struct page *page)
1059 {
1060         return free_pages_check(page);
1061 }
1062 #endif /* CONFIG_DEBUG_VM */
1063
1064 /*
1065  * Frees a number of pages from the PCP lists
1066  * Assumes all pages on list are in same zone, and of same order.
1067  * count is the number of pages to free.
1068  *
1069  * If the zone was previously in an "all pages pinned" state then look to
1070  * see if this freeing clears that state.
1071  *
1072  * And clear the zone's pages_scanned counter, to hold off the "all pages are
1073  * pinned" detection logic.
1074  */
1075 static void free_pcppages_bulk(struct zone *zone, int count,
1076                                         struct per_cpu_pages *pcp)
1077 {
1078         int migratetype = 0;
1079         int batch_free = 0;
1080         bool isolated_pageblocks;
1081
1082         spin_lock(&zone->lock);
1083         isolated_pageblocks = has_isolate_pageblock(zone);
1084
1085         while (count) {
1086                 struct page *page;
1087                 struct list_head *list;
1088
1089                 /*
1090                  * Remove pages from lists in a round-robin fashion. A
1091                  * batch_free count is maintained that is incremented when an
1092                  * empty list is encountered.  This is so more pages are freed
1093                  * off fuller lists instead of spinning excessively around empty
1094                  * lists
1095                  */
1096                 do {
1097                         batch_free++;
1098                         if (++migratetype == MIGRATE_PCPTYPES)
1099                                 migratetype = 0;
1100                         list = &pcp->lists[migratetype];
1101                 } while (list_empty(list));
1102
1103                 /* This is the only non-empty list. Free them all. */
1104                 if (batch_free == MIGRATE_PCPTYPES)
1105                         batch_free = count;
1106
1107                 do {
1108                         int mt; /* migratetype of the to-be-freed page */
1109
1110                         page = list_last_entry(list, struct page, lru);
1111                         /* must delete as __free_one_page list manipulates */
1112                         list_del(&page->lru);
1113
1114                         mt = get_pcppage_migratetype(page);
1115                         /* MIGRATE_ISOLATE page should not go to pcplists */
1116                         VM_BUG_ON_PAGE(is_migrate_isolate(mt), page);
1117                         /* Pageblock could have been isolated meanwhile */
1118                         if (unlikely(isolated_pageblocks))
1119                                 mt = get_pageblock_migratetype(page);
1120
1121                         if (bulkfree_pcp_prepare(page))
1122                                 continue;
1123
1124                         __free_one_page(page, page_to_pfn(page), zone, 0, mt);
1125                         trace_mm_page_pcpu_drain(page, 0, mt);
1126                 } while (--count && --batch_free && !list_empty(list));
1127         }
1128         spin_unlock(&zone->lock);
1129 }
1130
1131 static void free_one_page(struct zone *zone,
1132                                 struct page *page, unsigned long pfn,
1133                                 unsigned int order,
1134                                 int migratetype)
1135 {
1136         spin_lock(&zone->lock);
1137         if (unlikely(has_isolate_pageblock(zone) ||
1138                 is_migrate_isolate(migratetype))) {
1139                 migratetype = get_pfnblock_migratetype(page, pfn);
1140         }
1141         __free_one_page(page, pfn, zone, order, migratetype);
1142         spin_unlock(&zone->lock);
1143 }
1144
1145 static void __meminit __init_single_page(struct page *page, unsigned long pfn,
1146                                 unsigned long zone, int nid)
1147 {
1148         mm_zero_struct_page(page);
1149         set_page_links(page, zone, nid, pfn);
1150         init_page_count(page);
1151         page_mapcount_reset(page);
1152         page_cpupid_reset_last(page);
1153
1154         INIT_LIST_HEAD(&page->lru);
1155 #ifdef WANT_PAGE_VIRTUAL
1156         /* The shift won't overflow because ZONE_NORMAL is below 4G. */
1157         if (!is_highmem_idx(zone))
1158                 set_page_address(page, __va(pfn << PAGE_SHIFT));
1159 #endif
1160 }
1161
1162 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1163 static void __meminit init_reserved_page(unsigned long pfn)
1164 {
1165         pg_data_t *pgdat;
1166         int nid, zid;
1167
1168         if (!early_page_uninitialised(pfn))
1169                 return;
1170
1171         nid = early_pfn_to_nid(pfn);
1172         pgdat = NODE_DATA(nid);
1173
1174         for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1175                 struct zone *zone = &pgdat->node_zones[zid];
1176
1177                 if (pfn >= zone->zone_start_pfn && pfn < zone_end_pfn(zone))
1178                         break;
1179         }
1180         __init_single_page(pfn_to_page(pfn), pfn, zid, nid);
1181 }
1182 #else
1183 static inline void init_reserved_page(unsigned long pfn)
1184 {
1185 }
1186 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
1187
1188 /*
1189  * Initialised pages do not have PageReserved set. This function is
1190  * called for each range allocated by the bootmem allocator and
1191  * marks the pages PageReserved. The remaining valid pages are later
1192  * sent to the buddy page allocator.
1193  */
1194 void __meminit reserve_bootmem_region(phys_addr_t start, phys_addr_t end)
1195 {
1196         unsigned long start_pfn = PFN_DOWN(start);
1197         unsigned long end_pfn = PFN_UP(end);
1198
1199         for (; start_pfn < end_pfn; start_pfn++) {
1200                 if (pfn_valid(start_pfn)) {
1201                         struct page *page = pfn_to_page(start_pfn);
1202
1203                         init_reserved_page(start_pfn);
1204
1205                         /* Avoid false-positive PageTail() */
1206                         INIT_LIST_HEAD(&page->lru);
1207
1208                         SetPageReserved(page);
1209                 }
1210         }
1211 }
1212
1213 static void __free_pages_ok(struct page *page, unsigned int order)
1214 {
1215         unsigned long flags;
1216         int migratetype;
1217         unsigned long pfn = page_to_pfn(page);
1218
1219         if (!free_pages_prepare(page, order, true))
1220                 return;
1221
1222         migratetype = get_pfnblock_migratetype(page, pfn);
1223         local_irq_save(flags);
1224         __count_vm_events(PGFREE, 1 << order);
1225         free_one_page(page_zone(page), page, pfn, order, migratetype);
1226         local_irq_restore(flags);
1227 }
1228
1229 static void __init __free_pages_boot_core(struct page *page, unsigned int order)
1230 {
1231         unsigned int nr_pages = 1 << order;
1232         struct page *p = page;
1233         unsigned int loop;
1234
1235         prefetchw(p);
1236         for (loop = 0; loop < (nr_pages - 1); loop++, p++) {
1237                 prefetchw(p + 1);
1238                 __ClearPageReserved(p);
1239                 set_page_count(p, 0);
1240         }
1241         __ClearPageReserved(p);
1242         set_page_count(p, 0);
1243
1244         page_zone(page)->managed_pages += nr_pages;
1245         set_page_refcounted(page);
1246         __free_pages(page, order);
1247 }
1248
1249 #if defined(CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID) || \
1250         defined(CONFIG_HAVE_MEMBLOCK_NODE_MAP)
1251
1252 static struct mminit_pfnnid_cache early_pfnnid_cache __meminitdata;
1253
1254 int __meminit early_pfn_to_nid(unsigned long pfn)
1255 {
1256         static DEFINE_SPINLOCK(early_pfn_lock);
1257         int nid;
1258
1259         spin_lock(&early_pfn_lock);
1260         nid = __early_pfn_to_nid(pfn, &early_pfnnid_cache);
1261         if (nid < 0)
1262                 nid = first_online_node;
1263         spin_unlock(&early_pfn_lock);
1264
1265         return nid;
1266 }
1267 #endif
1268
1269 #ifdef CONFIG_NODES_SPAN_OTHER_NODES
1270 static inline bool __meminit __maybe_unused
1271 meminit_pfn_in_nid(unsigned long pfn, int node,
1272                    struct mminit_pfnnid_cache *state)
1273 {
1274         int nid;
1275
1276         nid = __early_pfn_to_nid(pfn, state);
1277         if (nid >= 0 && nid != node)
1278                 return false;
1279         return true;
1280 }
1281
1282 /* Only safe to use early in boot when initialisation is single-threaded */
1283 static inline bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
1284 {
1285         return meminit_pfn_in_nid(pfn, node, &early_pfnnid_cache);
1286 }
1287
1288 #else
1289
1290 static inline bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
1291 {
1292         return true;
1293 }
1294 static inline bool __meminit  __maybe_unused
1295 meminit_pfn_in_nid(unsigned long pfn, int node,
1296                    struct mminit_pfnnid_cache *state)
1297 {
1298         return true;
1299 }
1300 #endif
1301
1302
1303 void __init __free_pages_bootmem(struct page *page, unsigned long pfn,
1304                                                         unsigned int order)
1305 {
1306         if (early_page_uninitialised(pfn))
1307                 return;
1308         return __free_pages_boot_core(page, order);
1309 }
1310
1311 /*
1312  * Check that the whole (or subset of) a pageblock given by the interval of
1313  * [start_pfn, end_pfn) is valid and within the same zone, before scanning it
1314  * with the migration of free compaction scanner. The scanners then need to
1315  * use only pfn_valid_within() check for arches that allow holes within
1316  * pageblocks.
1317  *
1318  * Return struct page pointer of start_pfn, or NULL if checks were not passed.
1319  *
1320  * It's possible on some configurations to have a setup like node0 node1 node0
1321  * i.e. it's possible that all pages within a zones range of pages do not
1322  * belong to a single zone. We assume that a border between node0 and node1
1323  * can occur within a single pageblock, but not a node0 node1 node0
1324  * interleaving within a single pageblock. It is therefore sufficient to check
1325  * the first and last page of a pageblock and avoid checking each individual
1326  * page in a pageblock.
1327  */
1328 struct page *__pageblock_pfn_to_page(unsigned long start_pfn,
1329                                      unsigned long end_pfn, struct zone *zone)
1330 {
1331         struct page *start_page;
1332         struct page *end_page;
1333
1334         /* end_pfn is one past the range we are checking */
1335         end_pfn--;
1336
1337         if (!pfn_valid(start_pfn) || !pfn_valid(end_pfn))
1338                 return NULL;
1339
1340         start_page = pfn_to_online_page(start_pfn);
1341         if (!start_page)
1342                 return NULL;
1343
1344         if (page_zone(start_page) != zone)
1345                 return NULL;
1346
1347         end_page = pfn_to_page(end_pfn);
1348
1349         /* This gives a shorter code than deriving page_zone(end_page) */
1350         if (page_zone_id(start_page) != page_zone_id(end_page))
1351                 return NULL;
1352
1353         return start_page;
1354 }
1355
1356 void set_zone_contiguous(struct zone *zone)
1357 {
1358         unsigned long block_start_pfn = zone->zone_start_pfn;
1359         unsigned long block_end_pfn;
1360
1361         block_end_pfn = ALIGN(block_start_pfn + 1, pageblock_nr_pages);
1362         for (; block_start_pfn < zone_end_pfn(zone);
1363                         block_start_pfn = block_end_pfn,
1364                          block_end_pfn += pageblock_nr_pages) {
1365
1366                 block_end_pfn = min(block_end_pfn, zone_end_pfn(zone));
1367
1368                 if (!__pageblock_pfn_to_page(block_start_pfn,
1369                                              block_end_pfn, zone))
1370                         return;
1371         }
1372
1373         /* We confirm that there is no hole */
1374         zone->contiguous = true;
1375 }
1376
1377 void clear_zone_contiguous(struct zone *zone)
1378 {
1379         zone->contiguous = false;
1380 }
1381
1382 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1383 static void __init deferred_free_range(unsigned long pfn,
1384                                        unsigned long nr_pages)
1385 {
1386         struct page *page;
1387         unsigned long i;
1388
1389         if (!nr_pages)
1390                 return;
1391
1392         page = pfn_to_page(pfn);
1393
1394         /* Free a large naturally-aligned chunk if possible */
1395         if (nr_pages == pageblock_nr_pages &&
1396             (pfn & (pageblock_nr_pages - 1)) == 0) {
1397                 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
1398                 __free_pages_boot_core(page, pageblock_order);
1399                 return;
1400         }
1401
1402         for (i = 0; i < nr_pages; i++, page++, pfn++) {
1403                 if ((pfn & (pageblock_nr_pages - 1)) == 0)
1404                         set_pageblock_migratetype(page, MIGRATE_MOVABLE);
1405                 __free_pages_boot_core(page, 0);
1406         }
1407 }
1408
1409 /* Completion tracking for deferred_init_memmap() threads */
1410 static atomic_t pgdat_init_n_undone __initdata;
1411 static __initdata DECLARE_COMPLETION(pgdat_init_all_done_comp);
1412
1413 static inline void __init pgdat_init_report_one_done(void)
1414 {
1415         if (atomic_dec_and_test(&pgdat_init_n_undone))
1416                 complete(&pgdat_init_all_done_comp);
1417 }
1418
1419 /*
1420  * Returns true if page needs to be initialized or freed to buddy allocator.
1421  *
1422  * First we check if pfn is valid on architectures where it is possible to have
1423  * holes within pageblock_nr_pages. On systems where it is not possible, this
1424  * function is optimized out.
1425  *
1426  * Then, we check if a current large page is valid by only checking the validity
1427  * of the head pfn.
1428  *
1429  * Finally, meminit_pfn_in_nid is checked on systems where pfns can interleave
1430  * within a node: a pfn is between start and end of a node, but does not belong
1431  * to this memory node.
1432  */
1433 static inline bool __init
1434 deferred_pfn_valid(int nid, unsigned long pfn,
1435                    struct mminit_pfnnid_cache *nid_init_state)
1436 {
1437         if (!pfn_valid_within(pfn))
1438                 return false;
1439         if (!(pfn & (pageblock_nr_pages - 1)) && !pfn_valid(pfn))
1440                 return false;
1441         if (!meminit_pfn_in_nid(pfn, nid, nid_init_state))
1442                 return false;
1443         return true;
1444 }
1445
1446 /*
1447  * Free pages to buddy allocator. Try to free aligned pages in
1448  * pageblock_nr_pages sizes.
1449  */
1450 static void __init deferred_free_pages(int nid, int zid, unsigned long pfn,
1451                                        unsigned long end_pfn)
1452 {
1453         struct mminit_pfnnid_cache nid_init_state = { };
1454         unsigned long nr_pgmask = pageblock_nr_pages - 1;
1455         unsigned long nr_free = 0;
1456
1457         for (; pfn < end_pfn; pfn++) {
1458                 if (!deferred_pfn_valid(nid, pfn, &nid_init_state)) {
1459                         deferred_free_range(pfn - nr_free, nr_free);
1460                         nr_free = 0;
1461                 } else if (!(pfn & nr_pgmask)) {
1462                         deferred_free_range(pfn - nr_free, nr_free);
1463                         nr_free = 1;
1464                         touch_nmi_watchdog();
1465                 } else {
1466                         nr_free++;
1467                 }
1468         }
1469         /* Free the last block of pages to allocator */
1470         deferred_free_range(pfn - nr_free, nr_free);
1471 }
1472
1473 /*
1474  * Initialize struct pages.  We minimize pfn page lookups and scheduler checks
1475  * by performing it only once every pageblock_nr_pages.
1476  * Return number of pages initialized.
1477  */
1478 static unsigned long  __init deferred_init_pages(int nid, int zid,
1479                                                  unsigned long pfn,
1480                                                  unsigned long end_pfn)
1481 {
1482         struct mminit_pfnnid_cache nid_init_state = { };
1483         unsigned long nr_pgmask = pageblock_nr_pages - 1;
1484         unsigned long nr_pages = 0;
1485         struct page *page = NULL;
1486
1487         for (; pfn < end_pfn; pfn++) {
1488                 if (!deferred_pfn_valid(nid, pfn, &nid_init_state)) {
1489                         page = NULL;
1490                         continue;
1491                 } else if (!page || !(pfn & nr_pgmask)) {
1492                         page = pfn_to_page(pfn);
1493                         touch_nmi_watchdog();
1494                 } else {
1495                         page++;
1496                 }
1497                 __init_single_page(page, pfn, zid, nid);
1498                 nr_pages++;
1499         }
1500         return (nr_pages);
1501 }
1502
1503 /* Initialise remaining memory on a node */
1504 static int __init deferred_init_memmap(void *data)
1505 {
1506         pg_data_t *pgdat = data;
1507         int nid = pgdat->node_id;
1508         unsigned long start = jiffies;
1509         unsigned long nr_pages = 0;
1510         unsigned long spfn, epfn, first_init_pfn, flags;
1511         phys_addr_t spa, epa;
1512         int zid;
1513         struct zone *zone;
1514         const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
1515         u64 i;
1516
1517         /* Bind memory initialisation thread to a local node if possible */
1518         if (!cpumask_empty(cpumask))
1519                 set_cpus_allowed_ptr(current, cpumask);
1520
1521         pgdat_resize_lock(pgdat, &flags);
1522         first_init_pfn = pgdat->first_deferred_pfn;
1523         if (first_init_pfn == ULONG_MAX) {
1524                 pgdat_resize_unlock(pgdat, &flags);
1525                 pgdat_init_report_one_done();
1526                 return 0;
1527         }
1528
1529         /* Sanity check boundaries */
1530         BUG_ON(pgdat->first_deferred_pfn < pgdat->node_start_pfn);
1531         BUG_ON(pgdat->first_deferred_pfn > pgdat_end_pfn(pgdat));
1532         pgdat->first_deferred_pfn = ULONG_MAX;
1533
1534         /* Only the highest zone is deferred so find it */
1535         for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1536                 zone = pgdat->node_zones + zid;
1537                 if (first_init_pfn < zone_end_pfn(zone))
1538                         break;
1539         }
1540         first_init_pfn = max(zone->zone_start_pfn, first_init_pfn);
1541
1542         /*
1543          * Initialize and free pages. We do it in two loops: first we initialize
1544          * struct page, than free to buddy allocator, because while we are
1545          * freeing pages we can access pages that are ahead (computing buddy
1546          * page in __free_one_page()).
1547          */
1548         for_each_free_mem_range(i, nid, MEMBLOCK_NONE, &spa, &epa, NULL) {
1549                 spfn = max_t(unsigned long, first_init_pfn, PFN_UP(spa));
1550                 epfn = min_t(unsigned long, zone_end_pfn(zone), PFN_DOWN(epa));
1551                 nr_pages += deferred_init_pages(nid, zid, spfn, epfn);
1552         }
1553         for_each_free_mem_range(i, nid, MEMBLOCK_NONE, &spa, &epa, NULL) {
1554                 spfn = max_t(unsigned long, first_init_pfn, PFN_UP(spa));
1555                 epfn = min_t(unsigned long, zone_end_pfn(zone), PFN_DOWN(epa));
1556                 deferred_free_pages(nid, zid, spfn, epfn);
1557         }
1558         pgdat_resize_unlock(pgdat, &flags);
1559
1560         /* Sanity check that the next zone really is unpopulated */
1561         WARN_ON(++zid < MAX_NR_ZONES && populated_zone(++zone));
1562
1563         pr_info("node %d initialised, %lu pages in %ums\n", nid, nr_pages,
1564                                         jiffies_to_msecs(jiffies - start));
1565
1566         pgdat_init_report_one_done();
1567         return 0;
1568 }
1569
1570 /*
1571  * During boot we initialize deferred pages on-demand, as needed, but once
1572  * page_alloc_init_late() has finished, the deferred pages are all initialized,
1573  * and we can permanently disable that path.
1574  */
1575 static DEFINE_STATIC_KEY_TRUE(deferred_pages);
1576
1577 /*
1578  * If this zone has deferred pages, try to grow it by initializing enough
1579  * deferred pages to satisfy the allocation specified by order, rounded up to
1580  * the nearest PAGES_PER_SECTION boundary.  So we're adding memory in increments
1581  * of SECTION_SIZE bytes by initializing struct pages in increments of
1582  * PAGES_PER_SECTION * sizeof(struct page) bytes.
1583  *
1584  * Return true when zone was grown, otherwise return false. We return true even
1585  * when we grow less than requested, to let the caller decide if there are
1586  * enough pages to satisfy the allocation.
1587  *
1588  * Note: We use noinline because this function is needed only during boot, and
1589  * it is called from a __ref function _deferred_grow_zone. This way we are
1590  * making sure that it is not inlined into permanent text section.
1591  */
1592 static noinline bool __init
1593 deferred_grow_zone(struct zone *zone, unsigned int order)
1594 {
1595         int zid = zone_idx(zone);
1596         int nid = zone_to_nid(zone);
1597         pg_data_t *pgdat = NODE_DATA(nid);
1598         unsigned long nr_pages_needed = ALIGN(1 << order, PAGES_PER_SECTION);
1599         unsigned long nr_pages = 0;
1600         unsigned long first_init_pfn, spfn, epfn, t, flags;
1601         unsigned long first_deferred_pfn = pgdat->first_deferred_pfn;
1602         phys_addr_t spa, epa;
1603         u64 i;
1604
1605         /* Only the last zone may have deferred pages */
1606         if (zone_end_pfn(zone) != pgdat_end_pfn(pgdat))
1607                 return false;
1608
1609         pgdat_resize_lock(pgdat, &flags);
1610
1611         /*
1612          * If deferred pages have been initialized while we were waiting for
1613          * the lock, return true, as the zone was grown.  The caller will retry
1614          * this zone.  We won't return to this function since the caller also
1615          * has this static branch.
1616          */
1617         if (!static_branch_unlikely(&deferred_pages)) {
1618                 pgdat_resize_unlock(pgdat, &flags);
1619                 return true;
1620         }
1621
1622         /*
1623          * If someone grew this zone while we were waiting for spinlock, return
1624          * true, as there might be enough pages already.
1625          */
1626         if (first_deferred_pfn != pgdat->first_deferred_pfn) {
1627                 pgdat_resize_unlock(pgdat, &flags);
1628                 return true;
1629         }
1630
1631         first_init_pfn = max(zone->zone_start_pfn, first_deferred_pfn);
1632
1633         if (first_init_pfn >= pgdat_end_pfn(pgdat)) {
1634                 pgdat_resize_unlock(pgdat, &flags);
1635                 return false;
1636         }
1637
1638         for_each_free_mem_range(i, nid, MEMBLOCK_NONE, &spa, &epa, NULL) {
1639                 spfn = max_t(unsigned long, first_init_pfn, PFN_UP(spa));
1640                 epfn = min_t(unsigned long, zone_end_pfn(zone), PFN_DOWN(epa));
1641
1642                 while (spfn < epfn && nr_pages < nr_pages_needed) {
1643                         t = ALIGN(spfn + PAGES_PER_SECTION, PAGES_PER_SECTION);
1644                         first_deferred_pfn = min(t, epfn);
1645                         nr_pages += deferred_init_pages(nid, zid, spfn,
1646                                                         first_deferred_pfn);
1647                         spfn = first_deferred_pfn;
1648                 }
1649
1650                 if (nr_pages >= nr_pages_needed)
1651                         break;
1652         }
1653
1654         for_each_free_mem_range(i, nid, MEMBLOCK_NONE, &spa, &epa, NULL) {
1655                 spfn = max_t(unsigned long, first_init_pfn, PFN_UP(spa));
1656                 epfn = min_t(unsigned long, first_deferred_pfn, PFN_DOWN(epa));
1657                 deferred_free_pages(nid, zid, spfn, epfn);
1658
1659                 if (first_deferred_pfn == epfn)
1660                         break;
1661         }
1662         pgdat->first_deferred_pfn = first_deferred_pfn;
1663         pgdat_resize_unlock(pgdat, &flags);
1664
1665         return nr_pages > 0;
1666 }
1667
1668 /*
1669  * deferred_grow_zone() is __init, but it is called from
1670  * get_page_from_freelist() during early boot until deferred_pages permanently
1671  * disables this call. This is why we have refdata wrapper to avoid warning,
1672  * and to ensure that the function body gets unloaded.
1673  */
1674 static bool __ref
1675 _deferred_grow_zone(struct zone *zone, unsigned int order)
1676 {
1677         return deferred_grow_zone(zone, order);
1678 }
1679
1680 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
1681
1682 void __init page_alloc_init_late(void)
1683 {
1684         struct zone *zone;
1685
1686 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1687         int nid;
1688
1689         /* There will be num_node_state(N_MEMORY) threads */
1690         atomic_set(&pgdat_init_n_undone, num_node_state(N_MEMORY));
1691         for_each_node_state(nid, N_MEMORY) {
1692                 kthread_run(deferred_init_memmap, NODE_DATA(nid), "pgdatinit%d", nid);
1693         }
1694
1695         /* Block until all are initialised */
1696         wait_for_completion(&pgdat_init_all_done_comp);
1697
1698         /*
1699          * We initialized the rest of the deferred pages.  Permanently disable
1700          * on-demand struct page initialization.
1701          */
1702         static_branch_disable(&deferred_pages);
1703
1704         /* Reinit limits that are based on free pages after the kernel is up */
1705         files_maxfiles_init();
1706 #endif
1707 #ifdef CONFIG_ARCH_DISCARD_MEMBLOCK
1708         /* Discard memblock private memory */
1709         memblock_discard();
1710 #endif
1711
1712         for_each_populated_zone(zone)
1713                 set_zone_contiguous(zone);
1714 }
1715
1716 #ifdef CONFIG_CMA
1717 /* Free whole pageblock and set its migration type to MIGRATE_CMA. */
1718 void __init init_cma_reserved_pageblock(struct page *page)
1719 {
1720         unsigned i = pageblock_nr_pages;
1721         struct page *p = page;
1722
1723         do {
1724                 __ClearPageReserved(p);
1725                 set_page_count(p, 0);
1726         } while (++p, --i);
1727
1728         set_pageblock_migratetype(page, MIGRATE_CMA);
1729
1730         if (pageblock_order >= MAX_ORDER) {
1731                 i = pageblock_nr_pages;
1732                 p = page;
1733                 do {
1734                         set_page_refcounted(p);
1735                         __free_pages(p, MAX_ORDER - 1);
1736                         p += MAX_ORDER_NR_PAGES;
1737                 } while (i -= MAX_ORDER_NR_PAGES);
1738         } else {
1739                 set_page_refcounted(page);
1740                 __free_pages(page, pageblock_order);
1741         }
1742
1743         adjust_managed_page_count(page, pageblock_nr_pages);
1744 }
1745 #endif
1746
1747 /*
1748  * The order of subdivision here is critical for the IO subsystem.
1749  * Please do not alter this order without good reasons and regression
1750  * testing. Specifically, as large blocks of memory are subdivided,
1751  * the order in which smaller blocks are delivered depends on the order
1752  * they're subdivided in this function. This is the primary factor
1753  * influencing the order in which pages are delivered to the IO
1754  * subsystem according to empirical testing, and this is also justified
1755  * by considering the behavior of a buddy system containing a single
1756  * large block of memory acted on by a series of small allocations.
1757  * This behavior is a critical factor in sglist merging's success.
1758  *
1759  * -- nyc
1760  */
1761 static inline void expand(struct zone *zone, struct page *page,
1762         int low, int high, struct free_area *area,
1763         int migratetype)
1764 {
1765         unsigned long size = 1 << high;
1766
1767         while (high > low) {
1768                 area--;
1769                 high--;
1770                 size >>= 1;
1771                 VM_BUG_ON_PAGE(bad_range(zone, &page[size]), &page[size]);
1772
1773                 /*
1774                  * Mark as guard pages (or page), that will allow to
1775                  * merge back to allocator when buddy will be freed.
1776                  * Corresponding page table entries will not be touched,
1777                  * pages will stay not present in virtual address space
1778                  */
1779                 if (set_page_guard(zone, &page[size], high, migratetype))
1780                         continue;
1781
1782                 list_add(&page[size].lru, &area->free_list[migratetype]);
1783                 area->nr_free++;
1784                 set_page_order(&page[size], high);
1785         }
1786 }
1787
1788 static void check_new_page_bad(struct page *page)
1789 {
1790         const char *bad_reason = NULL;
1791         unsigned long bad_flags = 0;
1792
1793         if (unlikely(atomic_read(&page->_mapcount) != -1))
1794                 bad_reason = "nonzero mapcount";
1795         if (unlikely(page->mapping != NULL))
1796                 bad_reason = "non-NULL mapping";
1797         if (unlikely(page_ref_count(page) != 0))
1798                 bad_reason = "nonzero _count";
1799         if (unlikely(page->flags & __PG_HWPOISON)) {
1800                 bad_reason = "HWPoisoned (hardware-corrupted)";
1801                 bad_flags = __PG_HWPOISON;
1802                 /* Don't complain about hwpoisoned pages */
1803                 page_mapcount_reset(page); /* remove PageBuddy */
1804                 return;
1805         }
1806         if (unlikely(page->flags & PAGE_FLAGS_CHECK_AT_PREP)) {
1807                 bad_reason = "PAGE_FLAGS_CHECK_AT_PREP flag set";
1808                 bad_flags = PAGE_FLAGS_CHECK_AT_PREP;
1809         }
1810 #ifdef CONFIG_MEMCG
1811         if (unlikely(page->mem_cgroup))
1812                 bad_reason = "page still charged to cgroup";
1813 #endif
1814         bad_page(page, bad_reason, bad_flags);
1815 }
1816
1817 /*
1818  * This page is about to be returned from the page allocator
1819  */
1820 static inline int check_new_page(struct page *page)
1821 {
1822         if (likely(page_expected_state(page,
1823                                 PAGE_FLAGS_CHECK_AT_PREP|__PG_HWPOISON)))
1824                 return 0;
1825
1826         check_new_page_bad(page);
1827         return 1;
1828 }
1829
1830 static inline bool free_pages_prezeroed(void)
1831 {
1832         return IS_ENABLED(CONFIG_PAGE_POISONING_ZERO) &&
1833                 page_poisoning_enabled();
1834 }
1835
1836 #ifdef CONFIG_DEBUG_VM
1837 static bool check_pcp_refill(struct page *page)
1838 {
1839         return false;
1840 }
1841
1842 static bool check_new_pcp(struct page *page)
1843 {
1844         return check_new_page(page);
1845 }
1846 #else
1847 static bool check_pcp_refill(struct page *page)
1848 {
1849         return check_new_page(page);
1850 }
1851 static bool check_new_pcp(struct page *page)
1852 {
1853         return false;
1854 }
1855 #endif /* CONFIG_DEBUG_VM */
1856
1857 static bool check_new_pages(struct page *page, unsigned int order)
1858 {
1859         int i;
1860         for (i = 0; i < (1 << order); i++) {
1861                 struct page *p = page + i;
1862
1863                 if (unlikely(check_new_page(p)))
1864                         return true;
1865         }
1866
1867         return false;
1868 }
1869
1870 inline void post_alloc_hook(struct page *page, unsigned int order,
1871                                 gfp_t gfp_flags)
1872 {
1873         set_page_private(page, 0);
1874         set_page_refcounted(page);
1875
1876         arch_alloc_page(page, order);
1877         kernel_map_pages(page, 1 << order, 1);
1878         kernel_poison_pages(page, 1 << order, 1);
1879         kasan_alloc_pages(page, order);
1880         set_page_owner(page, order, gfp_flags);
1881 }
1882
1883 static void prep_new_page(struct page *page, unsigned int order, gfp_t gfp_flags,
1884                                                         unsigned int alloc_flags)
1885 {
1886         int i;
1887
1888         post_alloc_hook(page, order, gfp_flags);
1889
1890         if (!free_pages_prezeroed() && (gfp_flags & __GFP_ZERO))
1891                 for (i = 0; i < (1 << order); i++)
1892                         clear_highpage(page + i);
1893
1894         if (order && (gfp_flags & __GFP_COMP))
1895                 prep_compound_page(page, order);
1896
1897         /*
1898          * page is set pfmemalloc when ALLOC_NO_WATERMARKS was necessary to
1899          * allocate the page. The expectation is that the caller is taking
1900          * steps that will free more memory. The caller should avoid the page
1901          * being used for !PFMEMALLOC purposes.
1902          */
1903         if (alloc_flags & ALLOC_NO_WATERMARKS)
1904                 set_page_pfmemalloc(page);
1905         else
1906                 clear_page_pfmemalloc(page);
1907 }
1908
1909 /*
1910  * Go through the free lists for the given migratetype and remove
1911  * the smallest available page from the freelists
1912  */
1913 static __always_inline
1914 struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
1915                                                 int migratetype)
1916 {
1917         unsigned int current_order;
1918         struct free_area *area;
1919         struct page *page;
1920
1921         /* Find a page of the appropriate size in the preferred list */
1922         for (current_order = order; current_order < MAX_ORDER; ++current_order) {
1923                 area = &(zone->free_area[current_order]);
1924                 page = list_first_entry_or_null(&area->free_list[migratetype],
1925                                                         struct page, lru);
1926                 if (!page)
1927                         continue;
1928                 list_del(&page->lru);
1929                 rmv_page_order(page);
1930                 area->nr_free--;
1931                 expand(zone, page, order, current_order, area, migratetype);
1932                 set_pcppage_migratetype(page, migratetype);
1933                 return page;
1934         }
1935
1936         return NULL;
1937 }
1938
1939
1940 /*
1941  * This array describes the order lists are fallen back to when
1942  * the free lists for the desirable migrate type are depleted
1943  */
1944 static int fallbacks[MIGRATE_TYPES][4] = {
1945         [MIGRATE_UNMOVABLE]   = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE,   MIGRATE_TYPES },
1946         [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE,   MIGRATE_MOVABLE,   MIGRATE_TYPES },
1947         [MIGRATE_MOVABLE]     = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_TYPES },
1948 #ifdef CONFIG_CMA
1949         [MIGRATE_CMA]         = { MIGRATE_TYPES }, /* Never used */
1950 #endif
1951 #ifdef CONFIG_MEMORY_ISOLATION
1952         [MIGRATE_ISOLATE]     = { MIGRATE_TYPES }, /* Never used */
1953 #endif
1954 };
1955
1956 #ifdef CONFIG_CMA
1957 static __always_inline struct page *__rmqueue_cma_fallback(struct zone *zone,
1958                                         unsigned int order)
1959 {
1960         return __rmqueue_smallest(zone, order, MIGRATE_CMA);
1961 }
1962 #else
1963 static inline struct page *__rmqueue_cma_fallback(struct zone *zone,
1964                                         unsigned int order) { return NULL; }
1965 #endif
1966
1967 /*
1968  * Move the free pages in a range to the free lists of the requested type.
1969  * Note that start_page and end_pages are not aligned on a pageblock
1970  * boundary. If alignment is required, use move_freepages_block()
1971  */
1972 static int move_freepages(struct zone *zone,
1973                           struct page *start_page, struct page *end_page,
1974                           int migratetype, int *num_movable)
1975 {
1976         struct page *page;
1977         unsigned int order;
1978         int pages_moved = 0;
1979
1980 #ifndef CONFIG_HOLES_IN_ZONE
1981         /*
1982          * page_zone is not safe to call in this context when
1983          * CONFIG_HOLES_IN_ZONE is set. This bug check is probably redundant
1984          * anyway as we check zone boundaries in move_freepages_block().
1985          * Remove at a later date when no bug reports exist related to
1986          * grouping pages by mobility
1987          */
1988         VM_BUG_ON(pfn_valid(page_to_pfn(start_page)) &&
1989                   pfn_valid(page_to_pfn(end_page)) &&
1990                   page_zone(start_page) != page_zone(end_page));
1991 #endif
1992
1993         if (num_movable)
1994                 *num_movable = 0;
1995
1996         for (page = start_page; page <= end_page;) {
1997                 if (!pfn_valid_within(page_to_pfn(page))) {
1998                         page++;
1999                         continue;
2000                 }
2001
2002                 /* Make sure we are not inadvertently changing nodes */
2003                 VM_BUG_ON_PAGE(page_to_nid(page) != zone_to_nid(zone), page);
2004
2005                 if (!PageBuddy(page)) {
2006                         /*
2007                          * We assume that pages that could be isolated for
2008                          * migration are movable. But we don't actually try
2009                          * isolating, as that would be expensive.
2010                          */
2011                         if (num_movable &&
2012                                         (PageLRU(page) || __PageMovable(page)))
2013                                 (*num_movable)++;
2014
2015                         page++;
2016                         continue;
2017                 }
2018
2019                 order = page_order(page);
2020                 list_move(&page->lru,
2021                           &zone->free_area[order].free_list[migratetype]);
2022                 page += 1 << order;
2023                 pages_moved += 1 << order;
2024         }
2025
2026         return pages_moved;
2027 }
2028
2029 int move_freepages_block(struct zone *zone, struct page *page,
2030                                 int migratetype, int *num_movable)
2031 {
2032         unsigned long start_pfn, end_pfn;
2033         struct page *start_page, *end_page;
2034
2035         start_pfn = page_to_pfn(page);
2036         start_pfn = start_pfn & ~(pageblock_nr_pages-1);
2037         start_page = pfn_to_page(start_pfn);
2038         end_page = start_page + pageblock_nr_pages - 1;
2039         end_pfn = start_pfn + pageblock_nr_pages - 1;
2040
2041         /* Do not cross zone boundaries */
2042         if (!zone_spans_pfn(zone, start_pfn))
2043                 start_page = page;
2044         if (!zone_spans_pfn(zone, end_pfn))
2045                 return 0;
2046
2047         return move_freepages(zone, start_page, end_page, migratetype,
2048                                                                 num_movable);
2049 }
2050
2051 static void change_pageblock_range(struct page *pageblock_page,
2052                                         int start_order, int migratetype)
2053 {
2054         int nr_pageblocks = 1 << (start_order - pageblock_order);
2055
2056         while (nr_pageblocks--) {
2057                 set_pageblock_migratetype(pageblock_page, migratetype);
2058                 pageblock_page += pageblock_nr_pages;
2059         }
2060 }
2061
2062 /*
2063  * When we are falling back to another migratetype during allocation, try to
2064  * steal extra free pages from the same pageblocks to satisfy further
2065  * allocations, instead of polluting multiple pageblocks.
2066  *
2067  * If we are stealing a relatively large buddy page, it is likely there will
2068  * be more free pages in the pageblock, so try to steal them all. For
2069  * reclaimable and unmovable allocations, we steal regardless of page size,
2070  * as fragmentation caused by those allocations polluting movable pageblocks
2071  * is worse than movable allocations stealing from unmovable and reclaimable
2072  * pageblocks.
2073  */
2074 static bool can_steal_fallback(unsigned int order, int start_mt)
2075 {
2076         /*
2077          * Leaving this order check is intended, although there is
2078          * relaxed order check in next check. The reason is that
2079          * we can actually steal whole pageblock if this condition met,
2080          * but, below check doesn't guarantee it and that is just heuristic
2081          * so could be changed anytime.
2082          */
2083         if (order >= pageblock_order)
2084                 return true;
2085
2086         if (order >= pageblock_order / 2 ||
2087                 start_mt == MIGRATE_RECLAIMABLE ||
2088                 start_mt == MIGRATE_UNMOVABLE ||
2089                 page_group_by_mobility_disabled)
2090                 return true;
2091
2092         return false;
2093 }
2094
2095 /*
2096  * This function implements actual steal behaviour. If order is large enough,
2097  * we can steal whole pageblock. If not, we first move freepages in this
2098  * pageblock to our migratetype and determine how many already-allocated pages
2099  * are there in the pageblock with a compatible migratetype. If at least half
2100  * of pages are free or compatible, we can change migratetype of the pageblock
2101  * itself, so pages freed in the future will be put on the correct free list.
2102  */
2103 static void steal_suitable_fallback(struct zone *zone, struct page *page,
2104                                         int start_type, bool whole_block)
2105 {
2106         unsigned int current_order = page_order(page);
2107         struct free_area *area;
2108         int free_pages, movable_pages, alike_pages;
2109         int old_block_type;
2110
2111         old_block_type = get_pageblock_migratetype(page);
2112
2113         /*
2114          * This can happen due to races and we want to prevent broken
2115          * highatomic accounting.
2116          */
2117         if (is_migrate_highatomic(old_block_type))
2118                 goto single_page;
2119
2120         /* Take ownership for orders >= pageblock_order */
2121         if (current_order >= pageblock_order) {
2122                 change_pageblock_range(page, current_order, start_type);
2123                 goto single_page;
2124         }
2125
2126         /* We are not allowed to try stealing from the whole block */
2127         if (!whole_block)
2128                 goto single_page;
2129
2130         free_pages = move_freepages_block(zone, page, start_type,
2131                                                 &movable_pages);
2132         /*
2133          * Determine how many pages are compatible with our allocation.
2134          * For movable allocation, it's the number of movable pages which
2135          * we just obtained. For other types it's a bit more tricky.
2136          */
2137         if (start_type == MIGRATE_MOVABLE) {
2138                 alike_pages = movable_pages;
2139         } else {
2140                 /*
2141                  * If we are falling back a RECLAIMABLE or UNMOVABLE allocation
2142                  * to MOVABLE pageblock, consider all non-movable pages as
2143                  * compatible. If it's UNMOVABLE falling back to RECLAIMABLE or
2144                  * vice versa, be conservative since we can't distinguish the
2145                  * exact migratetype of non-movable pages.
2146                  */
2147                 if (old_block_type == MIGRATE_MOVABLE)
2148                         alike_pages = pageblock_nr_pages
2149                                                 - (free_pages + movable_pages);
2150                 else
2151                         alike_pages = 0;
2152         }
2153
2154         /* moving whole block can fail due to zone boundary conditions */
2155         if (!free_pages)
2156                 goto single_page;
2157
2158         /*
2159          * If a sufficient number of pages in the block are either free or of
2160          * comparable migratability as our allocation, claim the whole block.
2161          */
2162         if (free_pages + alike_pages >= (1 << (pageblock_order-1)) ||
2163                         page_group_by_mobility_disabled)
2164                 set_pageblock_migratetype(page, start_type);
2165
2166         return;
2167
2168 single_page:
2169         area = &zone->free_area[current_order];
2170         list_move(&page->lru, &area->free_list[start_type]);
2171 }
2172
2173 /*
2174  * Check whether there is a suitable fallback freepage with requested order.
2175  * If only_stealable is true, this function returns fallback_mt only if
2176  * we can steal other freepages all together. This would help to reduce
2177  * fragmentation due to mixed migratetype pages in one pageblock.
2178  */
2179 int find_suitable_fallback(struct free_area *area, unsigned int order,
2180                         int migratetype, bool only_stealable, bool *can_steal)
2181 {
2182         int i;
2183         int fallback_mt;
2184
2185         if (area->nr_free == 0)
2186                 return -1;
2187
2188         *can_steal = false;
2189         for (i = 0;; i++) {
2190                 fallback_mt = fallbacks[migratetype][i];
2191                 if (fallback_mt == MIGRATE_TYPES)
2192                         break;
2193
2194                 if (list_empty(&area->free_list[fallback_mt]))
2195                         continue;
2196
2197                 if (can_steal_fallback(order, migratetype))
2198                         *can_steal = true;
2199
2200                 if (!only_stealable)
2201                         return fallback_mt;
2202
2203                 if (*can_steal)
2204                         return fallback_mt;
2205         }
2206
2207         return -1;
2208 }
2209
2210 /*
2211  * Reserve a pageblock for exclusive use of high-order atomic allocations if
2212  * there are no empty page blocks that contain a page with a suitable order
2213  */
2214 static void reserve_highatomic_pageblock(struct page *page, struct zone *zone,
2215                                 unsigned int alloc_order)
2216 {
2217         int mt;
2218         unsigned long max_managed, flags;
2219
2220         /*
2221          * Limit the number reserved to 1 pageblock or roughly 1% of a zone.
2222          * Check is race-prone but harmless.
2223          */
2224         max_managed = (zone->managed_pages / 100) + pageblock_nr_pages;
2225         if (zone->nr_reserved_highatomic >= max_managed)
2226                 return;
2227
2228         spin_lock_irqsave(&zone->lock, flags);
2229
2230         /* Recheck the nr_reserved_highatomic limit under the lock */
2231         if (zone->nr_reserved_highatomic >= max_managed)
2232                 goto out_unlock;
2233
2234         /* Yoink! */
2235         mt = get_pageblock_migratetype(page);
2236         if (!is_migrate_highatomic(mt) && !is_migrate_isolate(mt)
2237             && !is_migrate_cma(mt)) {
2238                 zone->nr_reserved_highatomic += pageblock_nr_pages;
2239                 set_pageblock_migratetype(page, MIGRATE_HIGHATOMIC);
2240                 move_freepages_block(zone, page, MIGRATE_HIGHATOMIC, NULL);
2241         }
2242
2243 out_unlock:
2244         spin_unlock_irqrestore(&zone->lock, flags);
2245 }
2246
2247 /*
2248  * Used when an allocation is about to fail under memory pressure. This
2249  * potentially hurts the reliability of high-order allocations when under
2250  * intense memory pressure but failed atomic allocations should be easier
2251  * to recover from than an OOM.
2252  *
2253  * If @force is true, try to unreserve a pageblock even though highatomic
2254  * pageblock is exhausted.
2255  */
2256 static bool unreserve_highatomic_pageblock(const struct alloc_context *ac,
2257                                                 bool force)
2258 {
2259         struct zonelist *zonelist = ac->zonelist;
2260         unsigned long flags;
2261         struct zoneref *z;
2262         struct zone *zone;
2263         struct page *page;
2264         int order;
2265         bool ret;
2266
2267         for_each_zone_zonelist_nodemask(zone, z, zonelist, ac->high_zoneidx,
2268                                                                 ac->nodemask) {
2269                 /*
2270                  * Preserve at least one pageblock unless memory pressure
2271                  * is really high.
2272                  */
2273                 if (!force && zone->nr_reserved_highatomic <=
2274                                         pageblock_nr_pages)
2275                         continue;
2276
2277                 spin_lock_irqsave(&zone->lock, flags);
2278                 for (order = 0; order < MAX_ORDER; order++) {
2279                         struct free_area *area = &(zone->free_area[order]);
2280
2281                         page = list_first_entry_or_null(
2282                                         &area->free_list[MIGRATE_HIGHATOMIC],
2283                                         struct page, lru);
2284                         if (!page)
2285                                 continue;
2286
2287                         /*
2288                          * In page freeing path, migratetype change is racy so
2289                          * we can counter several free pages in a pageblock
2290                          * in this loop althoug we changed the pageblock type
2291                          * from highatomic to ac->migratetype. So we should
2292                          * adjust the count once.
2293                          */
2294                         if (is_migrate_highatomic_page(page)) {
2295                                 /*
2296                                  * It should never happen but changes to
2297                                  * locking could inadvertently allow a per-cpu
2298                                  * drain to add pages to MIGRATE_HIGHATOMIC
2299                                  * while unreserving so be safe and watch for
2300                                  * underflows.
2301                                  */
2302                                 zone->nr_reserved_highatomic -= min(
2303                                                 pageblock_nr_pages,
2304                                                 zone->nr_reserved_highatomic);
2305                         }
2306
2307                         /*
2308                          * Convert to ac->migratetype and avoid the normal
2309                          * pageblock stealing heuristics. Minimally, the caller
2310                          * is doing the work and needs the pages. More
2311                          * importantly, if the block was always converted to
2312                          * MIGRATE_UNMOVABLE or another type then the number
2313                          * of pageblocks that cannot be completely freed
2314                          * may increase.
2315                          */
2316                         set_pageblock_migratetype(page, ac->migratetype);
2317                         ret = move_freepages_block(zone, page, ac->migratetype,
2318                                                                         NULL);
2319                         if (ret) {
2320                                 spin_unlock_irqrestore(&zone->lock, flags);
2321                                 return ret;
2322                         }
2323                 }
2324                 spin_unlock_irqrestore(&zone->lock, flags);
2325         }
2326
2327         return false;
2328 }
2329
2330 /*
2331  * Try finding a free buddy page on the fallback list and put it on the free
2332  * list of requested migratetype, possibly along with other pages from the same
2333  * block, depending on fragmentation avoidance heuristics. Returns true if
2334  * fallback was found so that __rmqueue_smallest() can grab it.
2335  *
2336  * The use of signed ints for order and current_order is a deliberate
2337  * deviation from the rest of this file, to make the for loop
2338  * condition simpler.
2339  */
2340 static __always_inline bool
2341 __rmqueue_fallback(struct zone *zone, int order, int start_migratetype)
2342 {
2343         struct free_area *area;
2344         int current_order;
2345         struct page *page;
2346         int fallback_mt;
2347         bool can_steal;
2348
2349         /*
2350          * Find the largest available free page in the other list. This roughly
2351          * approximates finding the pageblock with the most free pages, which
2352          * would be too costly to do exactly.
2353          */
2354         for (current_order = MAX_ORDER - 1; current_order >= order;
2355                                 --current_order) {
2356                 area = &(zone->free_area[current_order]);
2357                 fallback_mt = find_suitable_fallback(area, current_order,
2358                                 start_migratetype, false, &can_steal);
2359                 if (fallback_mt == -1)
2360                         continue;
2361
2362                 /*
2363                  * We cannot steal all free pages from the pageblock and the
2364                  * requested migratetype is movable. In that case it's better to
2365                  * steal and split the smallest available page instead of the
2366                  * largest available page, because even if the next movable
2367                  * allocation falls back into a different pageblock than this
2368                  * one, it won't cause permanent fragmentation.
2369                  */
2370                 if (!can_steal && start_migratetype == MIGRATE_MOVABLE
2371                                         && current_order > order)
2372                         goto find_smallest;
2373
2374                 goto do_steal;
2375         }
2376
2377         return false;
2378
2379 find_smallest:
2380         for (current_order = order; current_order < MAX_ORDER;
2381                                                         current_order++) {
2382                 area = &(zone->free_area[current_order]);
2383                 fallback_mt = find_suitable_fallback(area, current_order,
2384                                 start_migratetype, false, &can_steal);
2385                 if (fallback_mt != -1)
2386                         break;
2387         }
2388
2389         /*
2390          * This should not happen - we already found a suitable fallback
2391          * when looking for the largest page.
2392          */
2393         VM_BUG_ON(current_order == MAX_ORDER);
2394
2395 do_steal:
2396         page = list_first_entry(&area->free_list[fallback_mt],
2397                                                         struct page, lru);
2398
2399         steal_suitable_fallback(zone, page, start_migratetype, can_steal);
2400
2401         trace_mm_page_alloc_extfrag(page, order, current_order,
2402                 start_migratetype, fallback_mt);
2403
2404         return true;
2405
2406 }
2407
2408 /*
2409  * Do the hard work of removing an element from the buddy allocator.
2410  * Call me with the zone->lock already held.
2411  */
2412 static __always_inline struct page *
2413 __rmqueue(struct zone *zone, unsigned int order, int migratetype)
2414 {
2415         struct page *page;
2416
2417 retry:
2418         page = __rmqueue_smallest(zone, order, migratetype);
2419         if (unlikely(!page)) {
2420                 if (migratetype == MIGRATE_MOVABLE)
2421                         page = __rmqueue_cma_fallback(zone, order);
2422
2423                 if (!page && __rmqueue_fallback(zone, order, migratetype))
2424                         goto retry;
2425         }
2426
2427         trace_mm_page_alloc_zone_locked(page, order, migratetype);
2428         return page;
2429 }
2430
2431 /*
2432  * Obtain a specified number of elements from the buddy allocator, all under
2433  * a single hold of the lock, for efficiency.  Add them to the supplied list.
2434  * Returns the number of new pages which were placed at *list.
2435  */
2436 static int rmqueue_bulk(struct zone *zone, unsigned int order,
2437                         unsigned long count, struct list_head *list,
2438                         int migratetype)
2439 {
2440         int i, alloced = 0;
2441
2442         spin_lock(&zone->lock);
2443         for (i = 0; i < count; ++i) {
2444                 struct page *page = __rmqueue(zone, order, migratetype);
2445                 if (unlikely(page == NULL))
2446                         break;
2447
2448                 if (unlikely(check_pcp_refill(page)))
2449                         continue;
2450
2451                 /*
2452                  * Split buddy pages returned by expand() are received here in
2453                  * physical page order. The page is added to the tail of
2454                  * caller's list. From the callers perspective, the linked list
2455                  * is ordered by page number under some conditions. This is
2456                  * useful for IO devices that can forward direction from the
2457                  * head, thus also in the physical page order. This is useful
2458                  * for IO devices that can merge IO requests if the physical
2459                  * pages are ordered properly.
2460                  */
2461                 list_add_tail(&page->lru, list);
2462                 alloced++;
2463                 if (is_migrate_cma(get_pcppage_migratetype(page)))
2464                         __mod_zone_page_state(zone, NR_FREE_CMA_PAGES,
2465                                               -(1 << order));
2466         }
2467
2468         /*
2469          * i pages were removed from the buddy list even if some leak due
2470          * to check_pcp_refill failing so adjust NR_FREE_PAGES based
2471          * on i. Do not confuse with 'alloced' which is the number of
2472          * pages added to the pcp list.
2473          */
2474         __mod_zone_page_state(zone, NR_FREE_PAGES, -(i << order));
2475         spin_unlock(&zone->lock);
2476         return alloced;
2477 }
2478
2479 #ifdef CONFIG_NUMA
2480 /*
2481  * Called from the vmstat counter updater to drain pagesets of this
2482  * currently executing processor on remote nodes after they have
2483  * expired.
2484  *
2485  * Note that this function must be called with the thread pinned to
2486  * a single processor.
2487  */
2488 void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp)
2489 {
2490         unsigned long flags;
2491         int to_drain, batch;
2492
2493         local_irq_save(flags);
2494         batch = READ_ONCE(pcp->batch);
2495         to_drain = min(pcp->count, batch);
2496         if (to_drain > 0) {
2497                 free_pcppages_bulk(zone, to_drain, pcp);
2498                 pcp->count -= to_drain;
2499         }
2500         local_irq_restore(flags);
2501 }
2502 #endif
2503
2504 /*
2505  * Drain pcplists of the indicated processor and zone.
2506  *
2507  * The processor must either be the current processor and the
2508  * thread pinned to the current processor or a processor that
2509  * is not online.
2510  */
2511 static void drain_pages_zone(unsigned int cpu, struct zone *zone)
2512 {
2513         unsigned long flags;
2514         struct per_cpu_pageset *pset;
2515         struct per_cpu_pages *pcp;
2516
2517         local_irq_save(flags);
2518         pset = per_cpu_ptr(zone->pageset, cpu);
2519
2520         pcp = &pset->pcp;
2521         if (pcp->count) {
2522                 free_pcppages_bulk(zone, pcp->count, pcp);
2523                 pcp->count = 0;
2524         }
2525         local_irq_restore(flags);
2526 }
2527
2528 /*
2529  * Drain pcplists of all zones on the indicated processor.
2530  *
2531  * The processor must either be the current processor and the
2532  * thread pinned to the current processor or a processor that
2533  * is not online.
2534  */
2535 static void drain_pages(unsigned int cpu)
2536 {
2537         struct zone *zone;
2538
2539         for_each_populated_zone(zone) {
2540                 drain_pages_zone(cpu, zone);
2541         }
2542 }
2543
2544 /*
2545  * Spill all of this CPU's per-cpu pages back into the buddy allocator.
2546  *
2547  * The CPU has to be pinned. When zone parameter is non-NULL, spill just
2548  * the single zone's pages.
2549  */
2550 void drain_local_pages(struct zone *zone)
2551 {
2552         int cpu = smp_processor_id();
2553
2554         if (zone)
2555                 drain_pages_zone(cpu, zone);
2556         else
2557                 drain_pages(cpu);
2558 }
2559
2560 static void drain_local_pages_wq(struct work_struct *work)
2561 {
2562         /*
2563          * drain_all_pages doesn't use proper cpu hotplug protection so
2564          * we can race with cpu offline when the WQ can move this from
2565          * a cpu pinned worker to an unbound one. We can operate on a different
2566          * cpu which is allright but we also have to make sure to not move to
2567          * a different one.
2568          */
2569         preempt_disable();
2570         drain_local_pages(NULL);
2571         preempt_enable();
2572 }
2573
2574 /*
2575  * Spill all the per-cpu pages from all CPUs back into the buddy allocator.
2576  *
2577  * When zone parameter is non-NULL, spill just the single zone's pages.
2578  *
2579  * Note that this can be extremely slow as the draining happens in a workqueue.
2580  */
2581 void drain_all_pages(struct zone *zone)
2582 {
2583         int cpu;
2584
2585         /*
2586          * Allocate in the BSS so we wont require allocation in
2587          * direct reclaim path for CONFIG_CPUMASK_OFFSTACK=y
2588          */
2589         static cpumask_t cpus_with_pcps;
2590
2591         /*
2592          * Make sure nobody triggers this path before mm_percpu_wq is fully
2593          * initialized.
2594          */
2595         if (WARN_ON_ONCE(!mm_percpu_wq))
2596                 return;
2597
2598         /*
2599          * Do not drain if one is already in progress unless it's specific to
2600          * a zone. Such callers are primarily CMA and memory hotplug and need
2601          * the drain to be complete when the call returns.
2602          */
2603         if (unlikely(!mutex_trylock(&pcpu_drain_mutex))) {
2604                 if (!zone)
2605                         return;
2606                 mutex_lock(&pcpu_drain_mutex);
2607         }
2608
2609         /*
2610          * We don't care about racing with CPU hotplug event
2611          * as offline notification will cause the notified
2612          * cpu to drain that CPU pcps and on_each_cpu_mask
2613          * disables preemption as part of its processing
2614          */
2615         for_each_online_cpu(cpu) {
2616                 struct per_cpu_pageset *pcp;
2617                 struct zone *z;
2618                 bool has_pcps = false;
2619
2620                 if (zone) {
2621                         pcp = per_cpu_ptr(zone->pageset, cpu);
2622                         if (pcp->pcp.count)
2623                                 has_pcps = true;
2624                 } else {
2625                         for_each_populated_zone(z) {
2626                                 pcp = per_cpu_ptr(z->pageset, cpu);
2627                                 if (pcp->pcp.count) {
2628                                         has_pcps = true;
2629                                         break;
2630                                 }
2631                         }
2632                 }
2633
2634                 if (has_pcps)
2635                         cpumask_set_cpu(cpu, &cpus_with_pcps);
2636                 else
2637                         cpumask_clear_cpu(cpu, &cpus_with_pcps);
2638         }
2639
2640         for_each_cpu(cpu, &cpus_with_pcps) {
2641                 struct work_struct *work = per_cpu_ptr(&pcpu_drain, cpu);
2642                 INIT_WORK(work, drain_local_pages_wq);
2643                 queue_work_on(cpu, mm_percpu_wq, work);
2644         }
2645         for_each_cpu(cpu, &cpus_with_pcps)
2646                 flush_work(per_cpu_ptr(&pcpu_drain, cpu));
2647
2648         mutex_unlock(&pcpu_drain_mutex);
2649 }
2650
2651 #ifdef CONFIG_HIBERNATION
2652
2653 /*
2654  * Touch the watchdog for every WD_PAGE_COUNT pages.
2655  */
2656 #define WD_PAGE_COUNT   (128*1024)
2657
2658 void mark_free_pages(struct zone *zone)
2659 {
2660         unsigned long pfn, max_zone_pfn, page_count = WD_PAGE_COUNT;
2661         unsigned long flags;
2662         unsigned int order, t;
2663         struct page *page;
2664
2665         if (zone_is_empty(zone))
2666                 return;
2667
2668         spin_lock_irqsave(&zone->lock, flags);
2669
2670         max_zone_pfn = zone_end_pfn(zone);
2671         for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
2672                 if (pfn_valid(pfn)) {
2673                         page = pfn_to_page(pfn);
2674
2675                         if (!--page_count) {
2676                                 touch_nmi_watchdog();
2677                                 page_count = WD_PAGE_COUNT;
2678                         }
2679
2680                         if (page_zone(page) != zone)
2681                                 continue;
2682
2683                         if (!swsusp_page_is_forbidden(page))
2684                                 swsusp_unset_page_free(page);
2685                 }
2686
2687         for_each_migratetype_order(order, t) {
2688                 list_for_each_entry(page,
2689                                 &zone->free_area[order].free_list[t], lru) {
2690                         unsigned long i;
2691
2692                         pfn = page_to_pfn(page);
2693                         for (i = 0; i < (1UL << order); i++) {
2694                                 if (!--page_count) {
2695                                         touch_nmi_watchdog();
2696                                         page_count = WD_PAGE_COUNT;
2697                                 }
2698                                 swsusp_set_page_free(pfn_to_page(pfn + i));
2699                         }
2700                 }
2701         }
2702         spin_unlock_irqrestore(&zone->lock, flags);
2703 }
2704 #endif /* CONFIG_PM */
2705
2706 static bool free_unref_page_prepare(struct page *page, unsigned long pfn)
2707 {
2708         int migratetype;
2709
2710         if (!free_pcp_prepare(page))
2711                 return false;
2712
2713         migratetype = get_pfnblock_migratetype(page, pfn);
2714         set_pcppage_migratetype(page, migratetype);
2715         return true;
2716 }
2717
2718 static void free_unref_page_commit(struct page *page, unsigned long pfn)
2719 {
2720         struct zone *zone = page_zone(page);
2721         struct per_cpu_pages *pcp;
2722         int migratetype;
2723
2724         migratetype = get_pcppage_migratetype(page);
2725         __count_vm_event(PGFREE);
2726
2727         /*
2728          * We only track unmovable, reclaimable and movable on pcp lists.
2729          * Free ISOLATE pages back to the allocator because they are being
2730          * offlined but treat HIGHATOMIC as movable pages so we can get those
2731          * areas back if necessary. Otherwise, we may have to free
2732          * excessively into the page allocator
2733          */
2734         if (migratetype >= MIGRATE_PCPTYPES) {
2735                 if (unlikely(is_migrate_isolate(migratetype))) {
2736                         free_one_page(zone, page, pfn, 0, migratetype);
2737                         return;
2738                 }
2739                 migratetype = MIGRATE_MOVABLE;
2740         }
2741
2742         pcp = &this_cpu_ptr(zone->pageset)->pcp;
2743         list_add(&page->lru, &pcp->lists[migratetype]);
2744         pcp->count++;
2745         if (pcp->count >= pcp->high) {
2746                 unsigned long batch = READ_ONCE(pcp->batch);
2747                 free_pcppages_bulk(zone, batch, pcp);
2748                 pcp->count -= batch;
2749         }
2750 }
2751
2752 /*
2753  * Free a 0-order page
2754  */
2755 void free_unref_page(struct page *page)
2756 {
2757         unsigned long flags;
2758         unsigned long pfn = page_to_pfn(page);
2759
2760         if (!free_unref_page_prepare(page, pfn))
2761                 return;
2762
2763         local_irq_save(flags);
2764         free_unref_page_commit(page, pfn);
2765         local_irq_restore(flags);
2766 }
2767
2768 /*
2769  * Free a list of 0-order pages
2770  */
2771 void free_unref_page_list(struct list_head *list)
2772 {
2773         struct page *page, *next;
2774         unsigned long flags, pfn;
2775         int batch_count = 0;
2776
2777         /* Prepare pages for freeing */
2778         list_for_each_entry_safe(page, next, list, lru) {
2779                 pfn = page_to_pfn(page);
2780                 if (!free_unref_page_prepare(page, pfn))
2781                         list_del(&page->lru);
2782                 set_page_private(page, pfn);
2783         }
2784
2785         local_irq_save(flags);
2786         list_for_each_entry_safe(page, next, list, lru) {
2787                 unsigned long pfn = page_private(page);
2788
2789                 set_page_private(page, 0);
2790                 trace_mm_page_free_batched(page);
2791                 free_unref_page_commit(page, pfn);
2792
2793                 /*
2794                  * Guard against excessive IRQ disabled times when we get
2795                  * a large list of pages to free.
2796                  */
2797                 if (++batch_count == SWAP_CLUSTER_MAX) {
2798                         local_irq_restore(flags);
2799                         batch_count = 0;
2800                         local_irq_save(flags);
2801                 }
2802         }
2803         local_irq_restore(flags);
2804 }
2805
2806 /*
2807  * split_page takes a non-compound higher-order page, and splits it into
2808  * n (1<<order) sub-pages: page[0..n]
2809  * Each sub-page must be freed individually.
2810  *
2811  * Note: this is probably too low level an operation for use in drivers.
2812  * Please consult with lkml before using this in your driver.
2813  */
2814 void split_page(struct page *page, unsigned int order)
2815 {
2816         int i;
2817
2818         VM_BUG_ON_PAGE(PageCompound(page), page);
2819         VM_BUG_ON_PAGE(!page_count(page), page);
2820
2821         for (i = 1; i < (1 << order); i++)
2822                 set_page_refcounted(page + i);
2823         split_page_owner(page, order);
2824 }
2825 EXPORT_SYMBOL_GPL(split_page);
2826
2827 int __isolate_free_page(struct page *page, unsigned int order)
2828 {
2829         unsigned long watermark;
2830         struct zone *zone;
2831         int mt;
2832
2833         BUG_ON(!PageBuddy(page));
2834
2835         zone = page_zone(page);
2836         mt = get_pageblock_migratetype(page);
2837
2838         if (!is_migrate_isolate(mt)) {
2839                 /*
2840                  * Obey watermarks as if the page was being allocated. We can
2841                  * emulate a high-order watermark check with a raised order-0
2842                  * watermark, because we already know our high-order page
2843                  * exists.
2844                  */
2845                 watermark = min_wmark_pages(zone) + (1UL << order);
2846                 if (!zone_watermark_ok(zone, 0, watermark, 0, ALLOC_CMA))
2847                         return 0;
2848
2849                 __mod_zone_freepage_state(zone, -(1UL << order), mt);
2850         }
2851
2852         /* Remove page from free list */
2853         list_del(&page->lru);
2854         zone->free_area[order].nr_free--;
2855         rmv_page_order(page);
2856
2857         /*
2858          * Set the pageblock if the isolated page is at least half of a
2859          * pageblock
2860          */
2861         if (order >= pageblock_order - 1) {
2862                 struct page *endpage = page + (1 << order) - 1;
2863                 for (; page < endpage; page += pageblock_nr_pages) {
2864                         int mt = get_pageblock_migratetype(page);
2865                         if (!is_migrate_isolate(mt) && !is_migrate_cma(mt)
2866                             && !is_migrate_highatomic(mt))
2867                                 set_pageblock_migratetype(page,
2868                                                           MIGRATE_MOVABLE);
2869                 }
2870         }
2871
2872
2873         return 1UL << order;
2874 }
2875
2876 /*
2877  * Update NUMA hit/miss statistics
2878  *
2879  * Must be called with interrupts disabled.
2880  */
2881 static inline void zone_statistics(struct zone *preferred_zone, struct zone *z)
2882 {
2883 #ifdef CONFIG_NUMA
2884         enum numa_stat_item local_stat = NUMA_LOCAL;
2885
2886         /* skip numa counters update if numa stats is disabled */
2887         if (!static_branch_likely(&vm_numa_stat_key))
2888                 return;
2889
2890         if (z->node != numa_node_id())
2891                 local_stat = NUMA_OTHER;
2892
2893         if (z->node == preferred_zone->node)
2894                 __inc_numa_state(z, NUMA_HIT);
2895         else {
2896                 __inc_numa_state(z, NUMA_MISS);
2897                 __inc_numa_state(preferred_zone, NUMA_FOREIGN);
2898         }
2899         __inc_numa_state(z, local_stat);
2900 #endif
2901 }
2902
2903 /* Remove page from the per-cpu list, caller must protect the list */
2904 static struct page *__rmqueue_pcplist(struct zone *zone, int migratetype,
2905                         struct per_cpu_pages *pcp,
2906                         struct list_head *list)
2907 {
2908         struct page *page;
2909
2910         do {
2911                 if (list_empty(list)) {
2912                         pcp->count += rmqueue_bulk(zone, 0,
2913                                         pcp->batch, list,
2914                                         migratetype);
2915                         if (unlikely(list_empty(list)))
2916                                 return NULL;
2917                 }
2918
2919                 page = list_first_entry(list, struct page, lru);
2920                 list_del(&page->lru);
2921                 pcp->count--;
2922         } while (check_new_pcp(page));
2923
2924         return page;
2925 }
2926
2927 /* Lock and remove page from the per-cpu list */
2928 static struct page *rmqueue_pcplist(struct zone *preferred_zone,
2929                         struct zone *zone, unsigned int order,
2930                         gfp_t gfp_flags, int migratetype)
2931 {
2932         struct per_cpu_pages *pcp;
2933         struct list_head *list;
2934         struct page *page;
2935         unsigned long flags;
2936
2937         local_irq_save(flags);
2938         pcp = &this_cpu_ptr(zone->pageset)->pcp;
2939         list = &pcp->lists[migratetype];
2940         page = __rmqueue_pcplist(zone,  migratetype, pcp, list);
2941         if (page) {
2942                 __count_zid_vm_events(PGALLOC, page_zonenum(page), 1 << order);
2943                 zone_statistics(preferred_zone, zone);
2944         }
2945         local_irq_restore(flags);
2946         return page;
2947 }
2948
2949 /*
2950  * Allocate a page from the given zone. Use pcplists for order-0 allocations.
2951  */
2952 static inline
2953 struct page *rmqueue(struct zone *preferred_zone,
2954                         struct zone *zone, unsigned int order,
2955                         gfp_t gfp_flags, unsigned int alloc_flags,
2956                         int migratetype)
2957 {
2958         unsigned long flags;
2959         struct page *page;
2960
2961         if (likely(order == 0)) {
2962                 page = rmqueue_pcplist(preferred_zone, zone, order,
2963                                 gfp_flags, migratetype);
2964                 goto out;
2965         }
2966
2967         /*
2968          * We most definitely don't want callers attempting to
2969          * allocate greater than order-1 page units with __GFP_NOFAIL.
2970          */
2971         WARN_ON_ONCE((gfp_flags & __GFP_NOFAIL) && (order > 1));
2972         spin_lock_irqsave(&zone->lock, flags);
2973
2974         do {
2975                 page = NULL;
2976                 if (alloc_flags & ALLOC_HARDER) {
2977                         page = __rmqueue_smallest(zone, order, MIGRATE_HIGHATOMIC);
2978                         if (page)
2979                                 trace_mm_page_alloc_zone_locked(page, order, migratetype);
2980                 }
2981                 if (!page)
2982                         page = __rmqueue(zone, order, migratetype);
2983         } while (page && check_new_pages(page, order));
2984         spin_unlock(&zone->lock);
2985         if (!page)
2986                 goto failed;
2987         __mod_zone_freepage_state(zone, -(1 << order),
2988                                   get_pcppage_migratetype(page));
2989
2990         __count_zid_vm_events(PGALLOC, page_zonenum(page), 1 << order);
2991         zone_statistics(preferred_zone, zone);
2992         local_irq_restore(flags);
2993
2994 out:
2995         VM_BUG_ON_PAGE(page && bad_range(zone, page), page);
2996         return page;
2997
2998 failed:
2999         local_irq_restore(flags);
3000         return NULL;
3001 }
3002
3003 #ifdef CONFIG_FAIL_PAGE_ALLOC
3004
3005 static struct {
3006         struct fault_attr attr;
3007
3008         bool ignore_gfp_highmem;
3009         bool ignore_gfp_reclaim;
3010         u32 min_order;
3011 } fail_page_alloc = {
3012         .attr = FAULT_ATTR_INITIALIZER,
3013         .ignore_gfp_reclaim = true,
3014         .ignore_gfp_highmem = true,
3015         .min_order = 1,
3016 };
3017
3018 static int __init setup_fail_page_alloc(char *str)
3019 {
3020         return setup_fault_attr(&fail_page_alloc.attr, str);
3021 }
3022 __setup("fail_page_alloc=", setup_fail_page_alloc);
3023
3024 static bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
3025 {
3026         if (order < fail_page_alloc.min_order)
3027                 return false;
3028         if (gfp_mask & __GFP_NOFAIL)
3029                 return false;
3030         if (fail_page_alloc.ignore_gfp_highmem && (gfp_mask & __GFP_HIGHMEM))
3031                 return false;
3032         if (fail_page_alloc.ignore_gfp_reclaim &&
3033                         (gfp_mask & __GFP_DIRECT_RECLAIM))
3034                 return false;
3035
3036         return should_fail(&fail_page_alloc.attr, 1 << order);
3037 }
3038
3039 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
3040
3041 static int __init fail_page_alloc_debugfs(void)
3042 {
3043         umode_t mode = S_IFREG | S_IRUSR | S_IWUSR;
3044         struct dentry *dir;
3045
3046         dir = fault_create_debugfs_attr("fail_page_alloc", NULL,
3047                                         &fail_page_alloc.attr);
3048         if (IS_ERR(dir))
3049                 return PTR_ERR(dir);
3050
3051         if (!debugfs_create_bool("ignore-gfp-wait", mode, dir,
3052                                 &fail_page_alloc.ignore_gfp_reclaim))
3053                 goto fail;
3054         if (!debugfs_create_bool("ignore-gfp-highmem", mode, dir,
3055                                 &fail_page_alloc.ignore_gfp_highmem))
3056                 goto fail;
3057         if (!debugfs_create_u32("min-order", mode, dir,
3058                                 &fail_page_alloc.min_order))
3059                 goto fail;
3060
3061         return 0;
3062 fail:
3063         debugfs_remove_recursive(dir);
3064
3065         return -ENOMEM;
3066 }
3067
3068 late_initcall(fail_page_alloc_debugfs);
3069
3070 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
3071
3072 #else /* CONFIG_FAIL_PAGE_ALLOC */
3073
3074 static inline bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
3075 {
3076         return false;
3077 }
3078
3079 #endif /* CONFIG_FAIL_PAGE_ALLOC */
3080
3081 /*
3082  * Return true if free base pages are above 'mark'. For high-order checks it
3083  * will return true of the order-0 watermark is reached and there is at least
3084  * one free page of a suitable size. Checking now avoids taking the zone lock
3085  * to check in the allocation paths if no pages are free.
3086  */
3087 bool __zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
3088                          int classzone_idx, unsigned int alloc_flags,
3089                          long free_pages)
3090 {
3091         long min = mark;
3092         int o;
3093         const bool alloc_harder = (alloc_flags & (ALLOC_HARDER|ALLOC_OOM));
3094
3095         /* free_pages may go negative - that's OK */
3096         free_pages -= (1 << order) - 1;
3097
3098         if (alloc_flags & ALLOC_HIGH)
3099                 min -= min / 2;
3100
3101         /*
3102          * If the caller does not have rights to ALLOC_HARDER then subtract
3103          * the high-atomic reserves. This will over-estimate the size of the
3104          * atomic reserve but it avoids a search.
3105          */
3106         if (likely(!alloc_harder)) {
3107                 free_pages -= z->nr_reserved_highatomic;
3108         } else {
3109                 /*
3110                  * OOM victims can try even harder than normal ALLOC_HARDER
3111                  * users on the grounds that it's definitely going to be in
3112                  * the exit path shortly and free memory. Any allocation it
3113                  * makes during the free path will be small and short-lived.
3114                  */
3115                 if (alloc_flags & ALLOC_OOM)
3116                         min -= min / 2;
3117                 else
3118                         min -= min / 4;
3119         }
3120
3121
3122 #ifdef CONFIG_CMA
3123         /* If allocation can't use CMA areas don't use free CMA pages */
3124         if (!(alloc_flags & ALLOC_CMA))
3125                 free_pages -= zone_page_state(z, NR_FREE_CMA_PAGES);
3126 #endif
3127
3128         /*
3129          * Check watermarks for an order-0 allocation request. If these
3130          * are not met, then a high-order request also cannot go ahead
3131          * even if a suitable page happened to be free.
3132          */
3133         if (free_pages <= min + z->lowmem_reserve[classzone_idx])
3134                 return false;
3135
3136         /* If this is an order-0 request then the watermark is fine */
3137         if (!order)
3138                 return true;
3139
3140         /* For a high-order request, check at least one suitable page is free */
3141         for (o = order; o < MAX_ORDER; o++) {
3142                 struct free_area *area = &z->free_area[o];
3143                 int mt;
3144
3145                 if (!area->nr_free)
3146                         continue;
3147
3148                 for (mt = 0; mt < MIGRATE_PCPTYPES; mt++) {
3149                         if (!list_empty(&area->free_list[mt]))
3150                                 return true;
3151                 }
3152
3153 #ifdef CONFIG_CMA
3154                 if ((alloc_flags & ALLOC_CMA) &&
3155                     !list_empty(&area->free_list[MIGRATE_CMA])) {
3156                         return true;
3157                 }
3158 #endif
3159                 if (alloc_harder &&
3160                         !list_empty(&area->free_list[MIGRATE_HIGHATOMIC]))
3161                         return true;
3162         }
3163         return false;
3164 }
3165
3166 bool zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
3167                       int classzone_idx, unsigned int alloc_flags)
3168 {
3169         return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
3170                                         zone_page_state(z, NR_FREE_PAGES));
3171 }
3172
3173 static inline bool zone_watermark_fast(struct zone *z, unsigned int order,
3174                 unsigned long mark, int classzone_idx, unsigned int alloc_flags)
3175 {
3176         long free_pages = zone_page_state(z, NR_FREE_PAGES);
3177         long cma_pages = 0;
3178
3179 #ifdef CONFIG_CMA
3180         /* If allocation can't use CMA areas don't use free CMA pages */
3181         if (!(alloc_flags & ALLOC_CMA))
3182                 cma_pages = zone_page_state(z, NR_FREE_CMA_PAGES);
3183 #endif
3184
3185         /*
3186          * Fast check for order-0 only. If this fails then the reserves
3187          * need to be calculated. There is a corner case where the check
3188          * passes but only the high-order atomic reserve are free. If
3189          * the caller is !atomic then it'll uselessly search the free
3190          * list. That corner case is then slower but it is harmless.
3191          */
3192         if (!order && (free_pages - cma_pages) > mark + z->lowmem_reserve[classzone_idx])
3193                 return true;
3194
3195         return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
3196                                         free_pages);
3197 }
3198
3199 bool zone_watermark_ok_safe(struct zone *z, unsigned int order,
3200                         unsigned long mark, int classzone_idx)
3201 {
3202         long free_pages = zone_page_state(z, NR_FREE_PAGES);
3203
3204         if (z->percpu_drift_mark && free_pages < z->percpu_drift_mark)
3205                 free_pages = zone_page_state_snapshot(z, NR_FREE_PAGES);
3206
3207         return __zone_watermark_ok(z, order, mark, classzone_idx, 0,
3208                                                                 free_pages);
3209 }
3210
3211 #ifdef CONFIG_NUMA
3212 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
3213 {
3214         return node_distance(zone_to_nid(local_zone), zone_to_nid(zone)) <=
3215                                 RECLAIM_DISTANCE;
3216 }
3217 #else   /* CONFIG_NUMA */
3218 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
3219 {
3220         return true;
3221 }
3222 #endif  /* CONFIG_NUMA */
3223
3224 /*
3225  * get_page_from_freelist goes through the zonelist trying to allocate
3226  * a page.
3227  */
3228 static struct page *
3229 get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags,
3230                                                 const struct alloc_context *ac)
3231 {
3232         struct zoneref *z = ac->preferred_zoneref;
3233         struct zone *zone;
3234         struct pglist_data *last_pgdat_dirty_limit = NULL;
3235
3236         /*
3237          * Scan zonelist, looking for a zone with enough free.
3238          * See also __cpuset_node_allowed() comment in kernel/cpuset.c.
3239          */
3240         for_next_zone_zonelist_nodemask(zone, z, ac->zonelist, ac->high_zoneidx,
3241                                                                 ac->nodemask) {
3242                 struct page *page;
3243                 unsigned long mark;
3244
3245                 if (cpusets_enabled() &&
3246                         (alloc_flags & ALLOC_CPUSET) &&
3247                         !__cpuset_zone_allowed(zone, gfp_mask))
3248                                 continue;
3249                 /*
3250                  * When allocating a page cache page for writing, we
3251                  * want to get it from a node that is within its dirty
3252                  * limit, such that no single node holds more than its
3253                  * proportional share of globally allowed dirty pages.
3254                  * The dirty limits take into account the node's
3255                  * lowmem reserves and high watermark so that kswapd
3256                  * should be able to balance it without having to
3257                  * write pages from its LRU list.
3258                  *
3259                  * XXX: For now, allow allocations to potentially
3260                  * exceed the per-node dirty limit in the slowpath
3261                  * (spread_dirty_pages unset) before going into reclaim,
3262                  * which is important when on a NUMA setup the allowed
3263                  * nodes are together not big enough to reach the
3264                  * global limit.  The proper fix for these situations
3265                  * will require awareness of nodes in the
3266                  * dirty-throttling and the flusher threads.
3267                  */
3268                 if (ac->spread_dirty_pages) {
3269                         if (last_pgdat_dirty_limit == zone->zone_pgdat)
3270                                 continue;
3271
3272                         if (!node_dirty_ok(zone->zone_pgdat)) {
3273                                 last_pgdat_dirty_limit = zone->zone_pgdat;
3274                                 continue;
3275                         }
3276                 }
3277
3278                 mark = zone->watermark[alloc_flags & ALLOC_WMARK_MASK];
3279                 if (!zone_watermark_fast(zone, order, mark,
3280                                        ac_classzone_idx(ac), alloc_flags)) {
3281                         int ret;
3282
3283 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
3284                         /*
3285                          * Watermark failed for this zone, but see if we can
3286                          * grow this zone if it contains deferred pages.
3287                          */
3288                         if (static_branch_unlikely(&deferred_pages)) {
3289                                 if (_deferred_grow_zone(zone, order))
3290                                         goto try_this_zone;
3291                         }
3292 #endif
3293                         /* Checked here to keep the fast path fast */
3294                         BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK);
3295                         if (alloc_flags & ALLOC_NO_WATERMARKS)
3296                                 goto try_this_zone;
3297
3298                         if (node_reclaim_mode == 0 ||
3299                             !zone_allows_reclaim(ac->preferred_zoneref->zone, zone))
3300                                 continue;
3301
3302                         ret = node_reclaim(zone->zone_pgdat, gfp_mask, order);
3303                         switch (ret) {
3304                         case NODE_RECLAIM_NOSCAN:
3305                                 /* did not scan */
3306                                 continue;
3307                         case NODE_RECLAIM_FULL:
3308                                 /* scanned but unreclaimable */
3309                                 continue;
3310                         default:
3311                                 /* did we reclaim enough */
3312                                 if (zone_watermark_ok(zone, order, mark,
3313                                                 ac_classzone_idx(ac), alloc_flags))
3314                                         goto try_this_zone;
3315
3316                                 continue;
3317                         }
3318                 }
3319
3320 try_this_zone:
3321                 page = rmqueue(ac->preferred_zoneref->zone, zone, order,
3322                                 gfp_mask, alloc_flags, ac->migratetype);
3323                 if (page) {
3324                         prep_new_page(page, order, gfp_mask, alloc_flags);
3325
3326                         /*
3327                          * If this is a high-order atomic allocation then check
3328                          * if the pageblock should be reserved for the future
3329                          */
3330                         if (unlikely(order && (alloc_flags & ALLOC_HARDER)))
3331                                 reserve_highatomic_pageblock(page, zone, order);
3332
3333                         return page;
3334                 } else {
3335 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
3336                         /* Try again if zone has deferred pages */
3337                         if (static_branch_unlikely(&deferred_pages)) {
3338                                 if (_deferred_grow_zone(zone, order))
3339                                         goto try_this_zone;
3340                         }
3341 #endif
3342                 }
3343         }
3344
3345         return NULL;
3346 }
3347
3348 /*
3349  * Large machines with many possible nodes should not always dump per-node
3350  * meminfo in irq context.
3351  */
3352 static inline bool should_suppress_show_mem(void)
3353 {
3354         bool ret = false;
3355
3356 #if NODES_SHIFT > 8
3357         ret = in_interrupt();
3358 #endif
3359         return ret;
3360 }
3361
3362 static void warn_alloc_show_mem(gfp_t gfp_mask, nodemask_t *nodemask)
3363 {
3364         unsigned int filter = SHOW_MEM_FILTER_NODES;
3365         static DEFINE_RATELIMIT_STATE(show_mem_rs, HZ, 1);
3366
3367         if (should_suppress_show_mem() || !__ratelimit(&show_mem_rs))
3368                 return;
3369
3370         /*
3371          * This documents exceptions given to allocations in certain
3372          * contexts that are allowed to allocate outside current's set
3373          * of allowed nodes.
3374          */
3375         if (!(gfp_mask & __GFP_NOMEMALLOC))
3376                 if (tsk_is_oom_victim(current) ||
3377                     (current->flags & (PF_MEMALLOC | PF_EXITING)))
3378                         filter &= ~SHOW_MEM_FILTER_NODES;
3379         if (in_interrupt() || !(gfp_mask & __GFP_DIRECT_RECLAIM))
3380                 filter &= ~SHOW_MEM_FILTER_NODES;
3381
3382         show_mem(filter, nodemask);
3383 }
3384
3385 void warn_alloc(gfp_t gfp_mask, nodemask_t *nodemask, const char *fmt, ...)
3386 {
3387         struct va_format vaf;
3388         va_list args;
3389         static DEFINE_RATELIMIT_STATE(nopage_rs, DEFAULT_RATELIMIT_INTERVAL,
3390                                       DEFAULT_RATELIMIT_BURST);
3391
3392         if ((gfp_mask & __GFP_NOWARN) || !__ratelimit(&nopage_rs))
3393                 return;
3394
3395         va_start(args, fmt);
3396         vaf.fmt = fmt;
3397         vaf.va = &args;
3398         pr_warn("%s: %pV, mode:%#x(%pGg), nodemask=%*pbl\n",
3399                         current->comm, &vaf, gfp_mask, &gfp_mask,
3400                         nodemask_pr_args(nodemask));
3401         va_end(args);
3402
3403         cpuset_print_current_mems_allowed();
3404
3405         dump_stack();
3406         warn_alloc_show_mem(gfp_mask, nodemask);
3407 }
3408
3409 static inline struct page *
3410 __alloc_pages_cpuset_fallback(gfp_t gfp_mask, unsigned int order,
3411                               unsigned int alloc_flags,
3412                               const struct alloc_context *ac)
3413 {
3414         struct page *page;
3415
3416         page = get_page_from_freelist(gfp_mask, order,
3417                         alloc_flags|ALLOC_CPUSET, ac);
3418         /*
3419          * fallback to ignore cpuset restriction if our nodes
3420          * are depleted
3421          */
3422         if (!page)
3423                 page = get_page_from_freelist(gfp_mask, order,
3424                                 alloc_flags, ac);
3425
3426         return page;
3427 }
3428
3429 static inline struct page *
3430 __alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order,
3431         const struct alloc_context *ac, unsigned long *did_some_progress)
3432 {
3433         struct oom_control oc = {
3434                 .zonelist = ac->zonelist,
3435                 .nodemask = ac->nodemask,
3436                 .memcg = NULL,
3437                 .gfp_mask = gfp_mask,
3438                 .order = order,
3439         };
3440         struct page *page;
3441
3442         *did_some_progress = 0;
3443
3444         /*
3445          * Acquire the oom lock.  If that fails, somebody else is
3446          * making progress for us.
3447          */
3448         if (!mutex_trylock(&oom_lock)) {
3449                 *did_some_progress = 1;
3450                 schedule_timeout_uninterruptible(1);
3451                 return NULL;
3452         }
3453
3454         /*
3455          * Go through the zonelist yet one more time, keep very high watermark
3456          * here, this is only to catch a parallel oom killing, we must fail if
3457          * we're still under heavy pressure. But make sure that this reclaim
3458          * attempt shall not depend on __GFP_DIRECT_RECLAIM && !__GFP_NORETRY
3459          * allocation which will never fail due to oom_lock already held.
3460          */
3461         page = get_page_from_freelist((gfp_mask | __GFP_HARDWALL) &
3462                                       ~__GFP_DIRECT_RECLAIM, order,
3463                                       ALLOC_WMARK_HIGH|ALLOC_CPUSET, ac);
3464         if (page)
3465                 goto out;
3466
3467         /* Coredumps can quickly deplete all memory reserves */
3468         if (current->flags & PF_DUMPCORE)
3469                 goto out;
3470         /* The OOM killer will not help higher order allocs */
3471         if (order > PAGE_ALLOC_COSTLY_ORDER)
3472                 goto out;
3473         /*
3474          * We have already exhausted all our reclaim opportunities without any
3475          * success so it is time to admit defeat. We will skip the OOM killer
3476          * because it is very likely that the caller has a more reasonable
3477          * fallback than shooting a random task.
3478          */
3479         if (gfp_mask & __GFP_RETRY_MAYFAIL)
3480                 goto out;
3481         /* The OOM killer does not needlessly kill tasks for lowmem */
3482         if (ac->high_zoneidx < ZONE_NORMAL)
3483                 goto out;
3484         if (pm_suspended_storage())
3485                 goto out;
3486         /*
3487          * XXX: GFP_NOFS allocations should rather fail than rely on
3488          * other request to make a forward progress.
3489          * We are in an unfortunate situation where out_of_memory cannot
3490          * do much for this context but let's try it to at least get
3491          * access to memory reserved if the current task is killed (see
3492          * out_of_memory). Once filesystems are ready to handle allocation
3493          * failures more gracefully we should just bail out here.
3494          */
3495
3496         /* The OOM killer may not free memory on a specific node */
3497         if (gfp_mask & __GFP_THISNODE)
3498                 goto out;
3499
3500         /* Exhausted what can be done so it's blame time */
3501         if (out_of_memory(&oc) || WARN_ON_ONCE(gfp_mask & __GFP_NOFAIL)) {
3502                 *did_some_progress = 1;
3503
3504                 /*
3505                  * Help non-failing allocations by giving them access to memory
3506                  * reserves
3507                  */
3508                 if (gfp_mask & __GFP_NOFAIL)
3509                         page = __alloc_pages_cpuset_fallback(gfp_mask, order,
3510                                         ALLOC_NO_WATERMARKS, ac);
3511         }
3512 out:
3513         mutex_unlock(&oom_lock);
3514         return page;
3515 }
3516
3517 /*
3518  * Maximum number of compaction retries wit a progress before OOM
3519  * killer is consider as the only way to move forward.
3520  */
3521 #define MAX_COMPACT_RETRIES 16
3522
3523 #ifdef CONFIG_COMPACTION
3524 /* Try memory compaction for high-order allocations before reclaim */
3525 static struct page *
3526 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
3527                 unsigned int alloc_flags, const struct alloc_context *ac,
3528                 enum compact_priority prio, enum compact_result *compact_result)
3529 {
3530         struct page *page;
3531         unsigned int noreclaim_flag;
3532
3533         if (!order)
3534                 return NULL;
3535
3536         noreclaim_flag = memalloc_noreclaim_save();
3537         *compact_result = try_to_compact_pages(gfp_mask, order, alloc_flags, ac,
3538                                                                         prio);
3539         memalloc_noreclaim_restore(noreclaim_flag);
3540
3541         if (*compact_result <= COMPACT_INACTIVE)
3542                 return NULL;
3543
3544         /*
3545          * At least in one zone compaction wasn't deferred or skipped, so let