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