arm64: dts: rk3368-android: enable isp
[firefly-linux-kernel-4.4.55.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/kmemcheck.h>
28 #include <linux/kasan.h>
29 #include <linux/module.h>
30 #include <linux/suspend.h>
31 #include <linux/pagevec.h>
32 #include <linux/blkdev.h>
33 #include <linux/slab.h>
34 #include <linux/ratelimit.h>
35 #include <linux/oom.h>
36 #include <linux/notifier.h>
37 #include <linux/topology.h>
38 #include <linux/sysctl.h>
39 #include <linux/cpu.h>
40 #include <linux/cpuset.h>
41 #include <linux/memory_hotplug.h>
42 #include <linux/nodemask.h>
43 #include <linux/vmalloc.h>
44 #include <linux/vmstat.h>
45 #include <linux/mempolicy.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 <linux/prefetch.h>
58 #include <linux/mm_inline.h>
59 #include <linux/migrate.h>
60 #include <linux/page_ext.h>
61 #include <linux/hugetlb.h>
62 #include <linux/sched/rt.h>
63 #include <linux/page_owner.h>
64 #include <linux/kthread.h>
65
66 #include <asm/sections.h>
67 #include <asm/tlbflush.h>
68 #include <asm/div64.h>
69 #include "internal.h"
70
71 /* prevent >1 _updater_ of zone percpu pageset ->high and ->batch fields */
72 static DEFINE_MUTEX(pcp_batch_high_lock);
73 #define MIN_PERCPU_PAGELIST_FRACTION    (8)
74
75 #ifdef CONFIG_USE_PERCPU_NUMA_NODE_ID
76 DEFINE_PER_CPU(int, numa_node);
77 EXPORT_PER_CPU_SYMBOL(numa_node);
78 #endif
79
80 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
81 /*
82  * N.B., Do NOT reference the '_numa_mem_' per cpu variable directly.
83  * It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined.
84  * Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem()
85  * defined in <linux/topology.h>.
86  */
87 DEFINE_PER_CPU(int, _numa_mem_);                /* Kernel "local memory" node */
88 EXPORT_PER_CPU_SYMBOL(_numa_mem_);
89 int _node_numa_mem_[MAX_NUMNODES];
90 #endif
91
92 /*
93  * Array of node states.
94  */
95 nodemask_t node_states[NR_NODE_STATES] __read_mostly = {
96         [N_POSSIBLE] = NODE_MASK_ALL,
97         [N_ONLINE] = { { [0] = 1UL } },
98 #ifndef CONFIG_NUMA
99         [N_NORMAL_MEMORY] = { { [0] = 1UL } },
100 #ifdef CONFIG_HIGHMEM
101         [N_HIGH_MEMORY] = { { [0] = 1UL } },
102 #endif
103 #ifdef CONFIG_MOVABLE_NODE
104         [N_MEMORY] = { { [0] = 1UL } },
105 #endif
106         [N_CPU] = { { [0] = 1UL } },
107 #endif  /* NUMA */
108 };
109 EXPORT_SYMBOL(node_states);
110
111 /* Protect totalram_pages and zone->managed_pages */
112 static DEFINE_SPINLOCK(managed_page_count_lock);
113
114 unsigned long totalram_pages __read_mostly;
115 unsigned long totalreserve_pages __read_mostly;
116 unsigned long totalcma_pages __read_mostly;
117
118 int percpu_pagelist_fraction;
119 gfp_t gfp_allowed_mask __read_mostly = GFP_BOOT_MASK;
120
121 /*
122  * A cached value of the page's pageblock's migratetype, used when the page is
123  * put on a pcplist. Used to avoid the pageblock migratetype lookup when
124  * freeing from pcplists in most cases, at the cost of possibly becoming stale.
125  * Also the migratetype set in the page does not necessarily match the pcplist
126  * index, e.g. page might have MIGRATE_CMA set but be on a pcplist with any
127  * other index - this ensures that it will be put on the correct CMA freelist.
128  */
129 static inline int get_pcppage_migratetype(struct page *page)
130 {
131         return page->index;
132 }
133
134 static inline void set_pcppage_migratetype(struct page *page, int migratetype)
135 {
136         page->index = migratetype;
137 }
138
139 #ifdef CONFIG_PM_SLEEP
140 /*
141  * The following functions are used by the suspend/hibernate code to temporarily
142  * change gfp_allowed_mask in order to avoid using I/O during memory allocations
143  * while devices are suspended.  To avoid races with the suspend/hibernate code,
144  * they should always be called with pm_mutex held (gfp_allowed_mask also should
145  * only be modified with pm_mutex held, unless the suspend/hibernate code is
146  * guaranteed not to run in parallel with that modification).
147  */
148
149 static gfp_t saved_gfp_mask;
150
151 void pm_restore_gfp_mask(void)
152 {
153         WARN_ON(!mutex_is_locked(&pm_mutex));
154         if (saved_gfp_mask) {
155                 gfp_allowed_mask = saved_gfp_mask;
156                 saved_gfp_mask = 0;
157         }
158 }
159
160 void pm_restrict_gfp_mask(void)
161 {
162         WARN_ON(!mutex_is_locked(&pm_mutex));
163         WARN_ON(saved_gfp_mask);
164         saved_gfp_mask = gfp_allowed_mask;
165         gfp_allowed_mask &= ~(__GFP_IO | __GFP_FS);
166 }
167
168 bool pm_suspended_storage(void)
169 {
170         if ((gfp_allowed_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
171                 return false;
172         return true;
173 }
174 #endif /* CONFIG_PM_SLEEP */
175
176 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
177 unsigned int pageblock_order __read_mostly;
178 #endif
179
180 static void __free_pages_ok(struct page *page, unsigned int order);
181
182 /*
183  * results with 256, 32 in the lowmem_reserve sysctl:
184  *      1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
185  *      1G machine -> (16M dma, 784M normal, 224M high)
186  *      NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
187  *      HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
188  *      HIGHMEM allocation will leave (224M+784M)/256 of ram reserved in ZONE_DMA
189  *
190  * TBD: should special case ZONE_DMA32 machines here - in those we normally
191  * don't need any ZONE_NORMAL reservation
192  */
193 int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES-1] = {
194 #ifdef CONFIG_ZONE_DMA
195          256,
196 #endif
197 #ifdef CONFIG_ZONE_DMA32
198          256,
199 #endif
200 #ifdef CONFIG_HIGHMEM
201          32,
202 #endif
203          32,
204 };
205
206 EXPORT_SYMBOL(totalram_pages);
207
208 static char * const zone_names[MAX_NR_ZONES] = {
209 #ifdef CONFIG_ZONE_DMA
210          "DMA",
211 #endif
212 #ifdef CONFIG_ZONE_DMA32
213          "DMA32",
214 #endif
215          "Normal",
216 #ifdef CONFIG_HIGHMEM
217          "HighMem",
218 #endif
219          "Movable",
220 #ifdef CONFIG_ZONE_DEVICE
221          "Device",
222 #endif
223 };
224
225 static void free_compound_page(struct page *page);
226 compound_page_dtor * const compound_page_dtors[] = {
227         NULL,
228         free_compound_page,
229 #ifdef CONFIG_HUGETLB_PAGE
230         free_huge_page,
231 #endif
232 };
233
234 /*
235  * Try to keep at least this much lowmem free.  Do not allow normal
236  * allocations below this point, only high priority ones. Automatically
237  * tuned according to the amount of memory in the system.
238  */
239 int min_free_kbytes = 1024;
240 int user_min_free_kbytes = -1;
241
242 /*
243  * Extra memory for the system to try freeing. Used to temporarily
244  * free memory, to make space for new workloads. Anyone can allocate
245  * down to the min watermarks controlled by min_free_kbytes above.
246  */
247 int extra_free_kbytes = 0;
248
249 static unsigned long __meminitdata nr_kernel_pages;
250 static unsigned long __meminitdata nr_all_pages;
251 static unsigned long __meminitdata dma_reserve;
252
253 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
254 static unsigned long __meminitdata arch_zone_lowest_possible_pfn[MAX_NR_ZONES];
255 static unsigned long __meminitdata arch_zone_highest_possible_pfn[MAX_NR_ZONES];
256 static unsigned long __initdata required_kernelcore;
257 static unsigned long __initdata required_movablecore;
258 static unsigned long __meminitdata zone_movable_pfn[MAX_NUMNODES];
259
260 /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
261 int movable_zone;
262 EXPORT_SYMBOL(movable_zone);
263 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
264
265 #if MAX_NUMNODES > 1
266 int nr_node_ids __read_mostly = MAX_NUMNODES;
267 int nr_online_nodes __read_mostly = 1;
268 EXPORT_SYMBOL(nr_node_ids);
269 EXPORT_SYMBOL(nr_online_nodes);
270 #endif
271
272 int page_group_by_mobility_disabled __read_mostly;
273
274 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
275 static inline void reset_deferred_meminit(pg_data_t *pgdat)
276 {
277         pgdat->first_deferred_pfn = ULONG_MAX;
278 }
279
280 /* Returns true if the struct page for the pfn is uninitialised */
281 static inline bool __meminit early_page_uninitialised(unsigned long pfn)
282 {
283         int nid = early_pfn_to_nid(pfn);
284
285         if (node_online(nid) && pfn >= NODE_DATA(nid)->first_deferred_pfn)
286                 return true;
287
288         return false;
289 }
290
291 static inline bool early_page_nid_uninitialised(unsigned long pfn, int nid)
292 {
293         if (pfn >= NODE_DATA(nid)->first_deferred_pfn)
294                 return true;
295
296         return false;
297 }
298
299 /*
300  * Returns false when the remaining initialisation should be deferred until
301  * later in the boot cycle when it can be parallelised.
302  */
303 static inline bool update_defer_init(pg_data_t *pgdat,
304                                 unsigned long pfn, unsigned long zone_end,
305                                 unsigned long *nr_initialised)
306 {
307         /* Always populate low zones for address-contrained allocations */
308         if (zone_end < pgdat_end_pfn(pgdat))
309                 return true;
310
311         /* Initialise at least 2G of the highest zone */
312         (*nr_initialised)++;
313         if (*nr_initialised > (2UL << (30 - PAGE_SHIFT)) &&
314             (pfn & (PAGES_PER_SECTION - 1)) == 0) {
315                 pgdat->first_deferred_pfn = pfn;
316                 return false;
317         }
318
319         return true;
320 }
321 #else
322 static inline void reset_deferred_meminit(pg_data_t *pgdat)
323 {
324 }
325
326 static inline bool early_page_uninitialised(unsigned long pfn)
327 {
328         return false;
329 }
330
331 static inline bool early_page_nid_uninitialised(unsigned long pfn, int nid)
332 {
333         return false;
334 }
335
336 static inline bool update_defer_init(pg_data_t *pgdat,
337                                 unsigned long pfn, unsigned long zone_end,
338                                 unsigned long *nr_initialised)
339 {
340         return true;
341 }
342 #endif
343
344
345 void set_pageblock_migratetype(struct page *page, int migratetype)
346 {
347         if (unlikely(page_group_by_mobility_disabled &&
348                      migratetype < MIGRATE_PCPTYPES))
349                 migratetype = MIGRATE_UNMOVABLE;
350
351         set_pageblock_flags_group(page, (unsigned long)migratetype,
352                                         PB_migrate, PB_migrate_end);
353 }
354
355 #ifdef CONFIG_DEBUG_VM
356 static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
357 {
358         int ret = 0;
359         unsigned seq;
360         unsigned long pfn = page_to_pfn(page);
361         unsigned long sp, start_pfn;
362
363         do {
364                 seq = zone_span_seqbegin(zone);
365                 start_pfn = zone->zone_start_pfn;
366                 sp = zone->spanned_pages;
367                 if (!zone_spans_pfn(zone, pfn))
368                         ret = 1;
369         } while (zone_span_seqretry(zone, seq));
370
371         if (ret)
372                 pr_err("page 0x%lx outside node %d zone %s [ 0x%lx - 0x%lx ]\n",
373                         pfn, zone_to_nid(zone), zone->name,
374                         start_pfn, start_pfn + sp);
375
376         return ret;
377 }
378
379 static int page_is_consistent(struct zone *zone, struct page *page)
380 {
381         if (!pfn_valid_within(page_to_pfn(page)))
382                 return 0;
383         if (zone != page_zone(page))
384                 return 0;
385
386         return 1;
387 }
388 /*
389  * Temporary debugging check for pages not lying within a given zone.
390  */
391 static int bad_range(struct zone *zone, struct page *page)
392 {
393         if (page_outside_zone_boundaries(zone, page))
394                 return 1;
395         if (!page_is_consistent(zone, page))
396                 return 1;
397
398         return 0;
399 }
400 #else
401 static inline int bad_range(struct zone *zone, struct page *page)
402 {
403         return 0;
404 }
405 #endif
406
407 static void bad_page(struct page *page, const char *reason,
408                 unsigned long bad_flags)
409 {
410         static unsigned long resume;
411         static unsigned long nr_shown;
412         static unsigned long nr_unshown;
413
414         /* Don't complain about poisoned pages */
415         if (PageHWPoison(page)) {
416                 page_mapcount_reset(page); /* remove PageBuddy */
417                 return;
418         }
419
420         /*
421          * Allow a burst of 60 reports, then keep quiet for that minute;
422          * or allow a steady drip of one report per second.
423          */
424         if (nr_shown == 60) {
425                 if (time_before(jiffies, resume)) {
426                         nr_unshown++;
427                         goto out;
428                 }
429                 if (nr_unshown) {
430                         printk(KERN_ALERT
431                               "BUG: Bad page state: %lu messages suppressed\n",
432                                 nr_unshown);
433                         nr_unshown = 0;
434                 }
435                 nr_shown = 0;
436         }
437         if (nr_shown++ == 0)
438                 resume = jiffies + 60 * HZ;
439
440         printk(KERN_ALERT "BUG: Bad page state in process %s  pfn:%05lx\n",
441                 current->comm, page_to_pfn(page));
442         dump_page_badflags(page, reason, bad_flags);
443
444         print_modules();
445         dump_stack();
446 out:
447         /* Leave bad fields for debug, except PageBuddy could make trouble */
448         page_mapcount_reset(page); /* remove PageBuddy */
449         add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
450 }
451
452 /*
453  * Higher-order pages are called "compound pages".  They are structured thusly:
454  *
455  * The first PAGE_SIZE page is called the "head page" and have PG_head set.
456  *
457  * The remaining PAGE_SIZE pages are called "tail pages". PageTail() is encoded
458  * in bit 0 of page->compound_head. The rest of bits is pointer to head page.
459  *
460  * The first tail page's ->compound_dtor holds the offset in array of compound
461  * page destructors. See compound_page_dtors.
462  *
463  * The first tail page's ->compound_order holds the order of allocation.
464  * This usage means that zero-order pages may not be compound.
465  */
466
467 static void free_compound_page(struct page *page)
468 {
469         __free_pages_ok(page, compound_order(page));
470 }
471
472 void prep_compound_page(struct page *page, unsigned int order)
473 {
474         int i;
475         int nr_pages = 1 << order;
476
477         set_compound_page_dtor(page, COMPOUND_PAGE_DTOR);
478         set_compound_order(page, order);
479         __SetPageHead(page);
480         for (i = 1; i < nr_pages; i++) {
481                 struct page *p = page + i;
482                 set_page_count(p, 0);
483                 set_compound_head(p, page);
484         }
485 }
486
487 #ifdef CONFIG_DEBUG_PAGEALLOC
488 unsigned int _debug_guardpage_minorder;
489 bool _debug_pagealloc_enabled __read_mostly;
490 bool _debug_guardpage_enabled __read_mostly;
491
492 static int __init early_debug_pagealloc(char *buf)
493 {
494         if (!buf)
495                 return -EINVAL;
496
497         if (strcmp(buf, "on") == 0)
498                 _debug_pagealloc_enabled = true;
499
500         return 0;
501 }
502 early_param("debug_pagealloc", early_debug_pagealloc);
503
504 static bool need_debug_guardpage(void)
505 {
506         /* If we don't use debug_pagealloc, we don't need guard page */
507         if (!debug_pagealloc_enabled())
508                 return false;
509
510         return true;
511 }
512
513 static void init_debug_guardpage(void)
514 {
515         if (!debug_pagealloc_enabled())
516                 return;
517
518         _debug_guardpage_enabled = true;
519 }
520
521 struct page_ext_operations debug_guardpage_ops = {
522         .need = need_debug_guardpage,
523         .init = init_debug_guardpage,
524 };
525
526 static int __init debug_guardpage_minorder_setup(char *buf)
527 {
528         unsigned long res;
529
530         if (kstrtoul(buf, 10, &res) < 0 ||  res > MAX_ORDER / 2) {
531                 printk(KERN_ERR "Bad debug_guardpage_minorder value\n");
532                 return 0;
533         }
534         _debug_guardpage_minorder = res;
535         printk(KERN_INFO "Setting debug_guardpage_minorder to %lu\n", res);
536         return 0;
537 }
538 __setup("debug_guardpage_minorder=", debug_guardpage_minorder_setup);
539
540 static inline void set_page_guard(struct zone *zone, struct page *page,
541                                 unsigned int order, int migratetype)
542 {
543         struct page_ext *page_ext;
544
545         if (!debug_guardpage_enabled())
546                 return;
547
548         page_ext = lookup_page_ext(page);
549         __set_bit(PAGE_EXT_DEBUG_GUARD, &page_ext->flags);
550
551         INIT_LIST_HEAD(&page->lru);
552         set_page_private(page, order);
553         /* Guard pages are not available for any usage */
554         __mod_zone_freepage_state(zone, -(1 << order), migratetype);
555 }
556
557 static inline void clear_page_guard(struct zone *zone, struct page *page,
558                                 unsigned int order, int migratetype)
559 {
560         struct page_ext *page_ext;
561
562         if (!debug_guardpage_enabled())
563                 return;
564
565         page_ext = lookup_page_ext(page);
566         __clear_bit(PAGE_EXT_DEBUG_GUARD, &page_ext->flags);
567
568         set_page_private(page, 0);
569         if (!is_migrate_isolate(migratetype))
570                 __mod_zone_freepage_state(zone, (1 << order), migratetype);
571 }
572 #else
573 struct page_ext_operations debug_guardpage_ops = { NULL, };
574 static inline void set_page_guard(struct zone *zone, struct page *page,
575                                 unsigned int order, int migratetype) {}
576 static inline void clear_page_guard(struct zone *zone, struct page *page,
577                                 unsigned int order, int migratetype) {}
578 #endif
579
580 static inline void set_page_order(struct page *page, unsigned int order)
581 {
582         set_page_private(page, order);
583         __SetPageBuddy(page);
584 }
585
586 static inline void rmv_page_order(struct page *page)
587 {
588         __ClearPageBuddy(page);
589         set_page_private(page, 0);
590 }
591
592 /*
593  * This function checks whether a page is free && is the buddy
594  * we can do coalesce a page and its buddy if
595  * (a) the buddy is not in a hole &&
596  * (b) the buddy is in the buddy system &&
597  * (c) a page and its buddy have the same order &&
598  * (d) a page and its buddy are in the same zone.
599  *
600  * For recording whether a page is in the buddy system, we set ->_mapcount
601  * PAGE_BUDDY_MAPCOUNT_VALUE.
602  * Setting, clearing, and testing _mapcount PAGE_BUDDY_MAPCOUNT_VALUE is
603  * serialized by zone->lock.
604  *
605  * For recording page's order, we use page_private(page).
606  */
607 static inline int page_is_buddy(struct page *page, struct page *buddy,
608                                                         unsigned int order)
609 {
610         if (!pfn_valid_within(page_to_pfn(buddy)))
611                 return 0;
612
613         if (page_is_guard(buddy) && page_order(buddy) == order) {
614                 if (page_zone_id(page) != page_zone_id(buddy))
615                         return 0;
616
617                 VM_BUG_ON_PAGE(page_count(buddy) != 0, buddy);
618
619                 return 1;
620         }
621
622         if (PageBuddy(buddy) && page_order(buddy) == order) {
623                 /*
624                  * zone check is done late to avoid uselessly
625                  * calculating zone/node ids for pages that could
626                  * never merge.
627                  */
628                 if (page_zone_id(page) != page_zone_id(buddy))
629                         return 0;
630
631                 VM_BUG_ON_PAGE(page_count(buddy) != 0, buddy);
632
633                 return 1;
634         }
635         return 0;
636 }
637
638 /*
639  * Freeing function for a buddy system allocator.
640  *
641  * The concept of a buddy system is to maintain direct-mapped table
642  * (containing bit values) for memory blocks of various "orders".
643  * The bottom level table contains the map for the smallest allocatable
644  * units of memory (here, pages), and each level above it describes
645  * pairs of units from the levels below, hence, "buddies".
646  * At a high level, all that happens here is marking the table entry
647  * at the bottom level available, and propagating the changes upward
648  * as necessary, plus some accounting needed to play nicely with other
649  * parts of the VM system.
650  * At each level, we keep a list of pages, which are heads of continuous
651  * free pages of length of (1 << order) and marked with _mapcount
652  * PAGE_BUDDY_MAPCOUNT_VALUE. Page's order is recorded in page_private(page)
653  * field.
654  * So when we are allocating or freeing one, we can derive the state of the
655  * other.  That is, if we allocate a small block, and both were
656  * free, the remainder of the region must be split into blocks.
657  * If a block is freed, and its buddy is also free, then this
658  * triggers coalescing into a block of larger size.
659  *
660  * -- nyc
661  */
662
663 static inline void __free_one_page(struct page *page,
664                 unsigned long pfn,
665                 struct zone *zone, unsigned int order,
666                 int migratetype)
667 {
668         unsigned long page_idx;
669         unsigned long combined_idx;
670         unsigned long uninitialized_var(buddy_idx);
671         struct page *buddy;
672         unsigned int max_order;
673
674         max_order = min_t(unsigned int, MAX_ORDER, pageblock_order + 1);
675
676         VM_BUG_ON(!zone_is_initialized(zone));
677         VM_BUG_ON_PAGE(page->flags & PAGE_FLAGS_CHECK_AT_PREP, page);
678
679         VM_BUG_ON(migratetype == -1);
680         if (likely(!is_migrate_isolate(migratetype)))
681                 __mod_zone_freepage_state(zone, 1 << order, migratetype);
682
683         page_idx = pfn & ((1 << MAX_ORDER) - 1);
684
685         VM_BUG_ON_PAGE(page_idx & ((1 << order) - 1), page);
686         VM_BUG_ON_PAGE(bad_range(zone, page), page);
687
688 continue_merging:
689         while (order < max_order - 1) {
690                 buddy_idx = __find_buddy_index(page_idx, order);
691                 buddy = page + (buddy_idx - page_idx);
692                 if (!page_is_buddy(page, buddy, order))
693                         goto done_merging;
694                 /*
695                  * Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page,
696                  * merge with it and move up one order.
697                  */
698                 if (page_is_guard(buddy)) {
699                         clear_page_guard(zone, buddy, order, migratetype);
700                 } else {
701                         list_del(&buddy->lru);
702                         zone->free_area[order].nr_free--;
703                         rmv_page_order(buddy);
704                 }
705                 combined_idx = buddy_idx & page_idx;
706                 page = page + (combined_idx - page_idx);
707                 page_idx = combined_idx;
708                 order++;
709         }
710         if (max_order < MAX_ORDER) {
711                 /* If we are here, it means order is >= pageblock_order.
712                  * We want to prevent merge between freepages on isolate
713                  * pageblock and normal pageblock. Without this, pageblock
714                  * isolation could cause incorrect freepage or CMA accounting.
715                  *
716                  * We don't want to hit this code for the more frequent
717                  * low-order merging.
718                  */
719                 if (unlikely(has_isolate_pageblock(zone))) {
720                         int buddy_mt;
721
722                         buddy_idx = __find_buddy_index(page_idx, order);
723                         buddy = page + (buddy_idx - page_idx);
724                         buddy_mt = get_pageblock_migratetype(buddy);
725
726                         if (migratetype != buddy_mt
727                                         && (is_migrate_isolate(migratetype) ||
728                                                 is_migrate_isolate(buddy_mt)))
729                                 goto done_merging;
730                 }
731                 max_order++;
732                 goto continue_merging;
733         }
734
735 done_merging:
736         set_page_order(page, order);
737
738         /*
739          * If this is not the largest possible page, check if the buddy
740          * of the next-highest order is free. If it is, it's possible
741          * that pages are being freed that will coalesce soon. In case,
742          * that is happening, add the free page to the tail of the list
743          * so it's less likely to be used soon and more likely to be merged
744          * as a higher order page
745          */
746         if ((order < MAX_ORDER-2) && pfn_valid_within(page_to_pfn(buddy))) {
747                 struct page *higher_page, *higher_buddy;
748                 combined_idx = buddy_idx & page_idx;
749                 higher_page = page + (combined_idx - page_idx);
750                 buddy_idx = __find_buddy_index(combined_idx, order + 1);
751                 higher_buddy = higher_page + (buddy_idx - combined_idx);
752                 if (page_is_buddy(higher_page, higher_buddy, order + 1)) {
753                         list_add_tail(&page->lru,
754                                 &zone->free_area[order].free_list[migratetype]);
755                         goto out;
756                 }
757         }
758
759         list_add(&page->lru, &zone->free_area[order].free_list[migratetype]);
760 out:
761         zone->free_area[order].nr_free++;
762 }
763
764 static inline int free_pages_check(struct page *page)
765 {
766         const char *bad_reason = NULL;
767         unsigned long bad_flags = 0;
768
769         if (unlikely(page_mapcount(page)))
770                 bad_reason = "nonzero mapcount";
771         if (unlikely(page->mapping != NULL))
772                 bad_reason = "non-NULL mapping";
773         if (unlikely(atomic_read(&page->_count) != 0))
774                 bad_reason = "nonzero _count";
775         if (unlikely(page->flags & PAGE_FLAGS_CHECK_AT_FREE)) {
776                 bad_reason = "PAGE_FLAGS_CHECK_AT_FREE flag(s) set";
777                 bad_flags = PAGE_FLAGS_CHECK_AT_FREE;
778         }
779 #ifdef CONFIG_MEMCG
780         if (unlikely(page->mem_cgroup))
781                 bad_reason = "page still charged to cgroup";
782 #endif
783         if (unlikely(bad_reason)) {
784                 bad_page(page, bad_reason, bad_flags);
785                 return 1;
786         }
787         page_cpupid_reset_last(page);
788         if (page->flags & PAGE_FLAGS_CHECK_AT_PREP)
789                 page->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
790         return 0;
791 }
792
793 /*
794  * Frees a number of pages from the PCP lists
795  * Assumes all pages on list are in same zone, and of same order.
796  * count is the number of pages to free.
797  *
798  * If the zone was previously in an "all pages pinned" state then look to
799  * see if this freeing clears that state.
800  *
801  * And clear the zone's pages_scanned counter, to hold off the "all pages are
802  * pinned" detection logic.
803  */
804 static void free_pcppages_bulk(struct zone *zone, int count,
805                                         struct per_cpu_pages *pcp)
806 {
807         int migratetype = 0;
808         int batch_free = 0;
809         int to_free = count;
810         unsigned long nr_scanned;
811
812         spin_lock(&zone->lock);
813         nr_scanned = zone_page_state(zone, NR_PAGES_SCANNED);
814         if (nr_scanned)
815                 __mod_zone_page_state(zone, NR_PAGES_SCANNED, -nr_scanned);
816
817         while (to_free) {
818                 struct page *page;
819                 struct list_head *list;
820
821                 /*
822                  * Remove pages from lists in a round-robin fashion. A
823                  * batch_free count is maintained that is incremented when an
824                  * empty list is encountered.  This is so more pages are freed
825                  * off fuller lists instead of spinning excessively around empty
826                  * lists
827                  */
828                 do {
829                         batch_free++;
830                         if (++migratetype == MIGRATE_PCPTYPES)
831                                 migratetype = 0;
832                         list = &pcp->lists[migratetype];
833                 } while (list_empty(list));
834
835                 /* This is the only non-empty list. Free them all. */
836                 if (batch_free == MIGRATE_PCPTYPES)
837                         batch_free = to_free;
838
839                 do {
840                         int mt; /* migratetype of the to-be-freed page */
841
842                         page = list_entry(list->prev, struct page, lru);
843                         /* must delete as __free_one_page list manipulates */
844                         list_del(&page->lru);
845
846                         mt = get_pcppage_migratetype(page);
847                         /* MIGRATE_ISOLATE page should not go to pcplists */
848                         VM_BUG_ON_PAGE(is_migrate_isolate(mt), page);
849                         /* Pageblock could have been isolated meanwhile */
850                         if (unlikely(has_isolate_pageblock(zone)))
851                                 mt = get_pageblock_migratetype(page);
852
853                         __free_one_page(page, page_to_pfn(page), zone, 0, mt);
854                         trace_mm_page_pcpu_drain(page, 0, mt);
855                 } while (--to_free && --batch_free && !list_empty(list));
856         }
857         spin_unlock(&zone->lock);
858 }
859
860 static void free_one_page(struct zone *zone,
861                                 struct page *page, unsigned long pfn,
862                                 unsigned int order,
863                                 int migratetype)
864 {
865         unsigned long nr_scanned;
866         spin_lock(&zone->lock);
867         nr_scanned = zone_page_state(zone, NR_PAGES_SCANNED);
868         if (nr_scanned)
869                 __mod_zone_page_state(zone, NR_PAGES_SCANNED, -nr_scanned);
870
871         if (unlikely(has_isolate_pageblock(zone) ||
872                 is_migrate_isolate(migratetype))) {
873                 migratetype = get_pfnblock_migratetype(page, pfn);
874         }
875         __free_one_page(page, pfn, zone, order, migratetype);
876         spin_unlock(&zone->lock);
877 }
878
879 static int free_tail_pages_check(struct page *head_page, struct page *page)
880 {
881         int ret = 1;
882
883         /*
884          * We rely page->lru.next never has bit 0 set, unless the page
885          * is PageTail(). Let's make sure that's true even for poisoned ->lru.
886          */
887         BUILD_BUG_ON((unsigned long)LIST_POISON1 & 1);
888
889         if (!IS_ENABLED(CONFIG_DEBUG_VM)) {
890                 ret = 0;
891                 goto out;
892         }
893         if (unlikely(!PageTail(page))) {
894                 bad_page(page, "PageTail not set", 0);
895                 goto out;
896         }
897         if (unlikely(compound_head(page) != head_page)) {
898                 bad_page(page, "compound_head not consistent", 0);
899                 goto out;
900         }
901         ret = 0;
902 out:
903         clear_compound_head(page);
904         return ret;
905 }
906
907 static void __meminit __init_single_page(struct page *page, unsigned long pfn,
908                                 unsigned long zone, int nid)
909 {
910         set_page_links(page, zone, nid, pfn);
911         init_page_count(page);
912         page_mapcount_reset(page);
913         page_cpupid_reset_last(page);
914
915         INIT_LIST_HEAD(&page->lru);
916 #ifdef WANT_PAGE_VIRTUAL
917         /* The shift won't overflow because ZONE_NORMAL is below 4G. */
918         if (!is_highmem_idx(zone))
919                 set_page_address(page, __va(pfn << PAGE_SHIFT));
920 #endif
921 }
922
923 static void __meminit __init_single_pfn(unsigned long pfn, unsigned long zone,
924                                         int nid)
925 {
926         return __init_single_page(pfn_to_page(pfn), pfn, zone, nid);
927 }
928
929 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
930 static void init_reserved_page(unsigned long pfn)
931 {
932         pg_data_t *pgdat;
933         int nid, zid;
934
935         if (!early_page_uninitialised(pfn))
936                 return;
937
938         nid = early_pfn_to_nid(pfn);
939         pgdat = NODE_DATA(nid);
940
941         for (zid = 0; zid < MAX_NR_ZONES; zid++) {
942                 struct zone *zone = &pgdat->node_zones[zid];
943
944                 if (pfn >= zone->zone_start_pfn && pfn < zone_end_pfn(zone))
945                         break;
946         }
947         __init_single_pfn(pfn, zid, nid);
948 }
949 #else
950 static inline void init_reserved_page(unsigned long pfn)
951 {
952 }
953 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
954
955 /*
956  * Initialised pages do not have PageReserved set. This function is
957  * called for each range allocated by the bootmem allocator and
958  * marks the pages PageReserved. The remaining valid pages are later
959  * sent to the buddy page allocator.
960  */
961 void __meminit reserve_bootmem_region(phys_addr_t start, phys_addr_t end)
962 {
963         unsigned long start_pfn = PFN_DOWN(start);
964         unsigned long end_pfn = PFN_UP(end);
965
966         for (; start_pfn < end_pfn; start_pfn++) {
967                 if (pfn_valid(start_pfn)) {
968                         struct page *page = pfn_to_page(start_pfn);
969
970                         init_reserved_page(start_pfn);
971
972                         /* Avoid false-positive PageTail() */
973                         INIT_LIST_HEAD(&page->lru);
974
975                         SetPageReserved(page);
976                 }
977         }
978 }
979
980 static bool free_pages_prepare(struct page *page, unsigned int order)
981 {
982         bool compound = PageCompound(page);
983         int i, bad = 0;
984
985         VM_BUG_ON_PAGE(PageTail(page), page);
986         VM_BUG_ON_PAGE(compound && compound_order(page) != order, page);
987
988         trace_mm_page_free(page, order);
989         kmemcheck_free_shadow(page, order);
990         kasan_free_pages(page, order);
991
992         if (PageAnon(page))
993                 page->mapping = NULL;
994         bad += free_pages_check(page);
995         for (i = 1; i < (1 << order); i++) {
996                 if (compound)
997                         bad += free_tail_pages_check(page, page + i);
998                 bad += free_pages_check(page + i);
999         }
1000         if (bad)
1001                 return false;
1002
1003         reset_page_owner(page, order);
1004
1005         if (!PageHighMem(page)) {
1006                 debug_check_no_locks_freed(page_address(page),
1007                                            PAGE_SIZE << order);
1008                 debug_check_no_obj_freed(page_address(page),
1009                                            PAGE_SIZE << order);
1010         }
1011         arch_free_page(page, order);
1012         kernel_map_pages(page, 1 << order, 0);
1013
1014         return true;
1015 }
1016
1017 static void __free_pages_ok(struct page *page, unsigned int order)
1018 {
1019         unsigned long flags;
1020         int migratetype;
1021         unsigned long pfn = page_to_pfn(page);
1022
1023         if (!free_pages_prepare(page, order))
1024                 return;
1025
1026         migratetype = get_pfnblock_migratetype(page, pfn);
1027         local_irq_save(flags);
1028         __count_vm_events(PGFREE, 1 << order);
1029         free_one_page(page_zone(page), page, pfn, order, migratetype);
1030         local_irq_restore(flags);
1031 }
1032
1033 static void __init __free_pages_boot_core(struct page *page,
1034                                         unsigned long pfn, unsigned int order)
1035 {
1036         unsigned int nr_pages = 1 << order;
1037         struct page *p = page;
1038         unsigned int loop;
1039
1040         prefetchw(p);
1041         for (loop = 0; loop < (nr_pages - 1); loop++, p++) {
1042                 prefetchw(p + 1);
1043                 __ClearPageReserved(p);
1044                 set_page_count(p, 0);
1045         }
1046         __ClearPageReserved(p);
1047         set_page_count(p, 0);
1048
1049         page_zone(page)->managed_pages += nr_pages;
1050         set_page_refcounted(page);
1051         __free_pages(page, order);
1052 }
1053
1054 #if defined(CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID) || \
1055         defined(CONFIG_HAVE_MEMBLOCK_NODE_MAP)
1056
1057 static struct mminit_pfnnid_cache early_pfnnid_cache __meminitdata;
1058
1059 int __meminit early_pfn_to_nid(unsigned long pfn)
1060 {
1061         static DEFINE_SPINLOCK(early_pfn_lock);
1062         int nid;
1063
1064         spin_lock(&early_pfn_lock);
1065         nid = __early_pfn_to_nid(pfn, &early_pfnnid_cache);
1066         if (nid < 0)
1067                 nid = first_online_node;
1068         spin_unlock(&early_pfn_lock);
1069
1070         return nid;
1071 }
1072 #endif
1073
1074 #ifdef CONFIG_NODES_SPAN_OTHER_NODES
1075 static inline bool __meminit meminit_pfn_in_nid(unsigned long pfn, int node,
1076                                         struct mminit_pfnnid_cache *state)
1077 {
1078         int nid;
1079
1080         nid = __early_pfn_to_nid(pfn, state);
1081         if (nid >= 0 && nid != node)
1082                 return false;
1083         return true;
1084 }
1085
1086 /* Only safe to use early in boot when initialisation is single-threaded */
1087 static inline bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
1088 {
1089         return meminit_pfn_in_nid(pfn, node, &early_pfnnid_cache);
1090 }
1091
1092 #else
1093
1094 static inline bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
1095 {
1096         return true;
1097 }
1098 static inline bool __meminit meminit_pfn_in_nid(unsigned long pfn, int node,
1099                                         struct mminit_pfnnid_cache *state)
1100 {
1101         return true;
1102 }
1103 #endif
1104
1105
1106 void __init __free_pages_bootmem(struct page *page, unsigned long pfn,
1107                                                         unsigned int order)
1108 {
1109         if (early_page_uninitialised(pfn))
1110                 return;
1111         return __free_pages_boot_core(page, pfn, order);
1112 }
1113
1114 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1115 static void __init deferred_free_range(struct page *page,
1116                                         unsigned long pfn, int nr_pages)
1117 {
1118         int i;
1119
1120         if (!page)
1121                 return;
1122
1123         /* Free a large naturally-aligned chunk if possible */
1124         if (nr_pages == MAX_ORDER_NR_PAGES &&
1125             (pfn & (MAX_ORDER_NR_PAGES-1)) == 0) {
1126                 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
1127                 __free_pages_boot_core(page, pfn, MAX_ORDER-1);
1128                 return;
1129         }
1130
1131         for (i = 0; i < nr_pages; i++, page++, pfn++)
1132                 __free_pages_boot_core(page, pfn, 0);
1133 }
1134
1135 /* Completion tracking for deferred_init_memmap() threads */
1136 static atomic_t pgdat_init_n_undone __initdata;
1137 static __initdata DECLARE_COMPLETION(pgdat_init_all_done_comp);
1138
1139 static inline void __init pgdat_init_report_one_done(void)
1140 {
1141         if (atomic_dec_and_test(&pgdat_init_n_undone))
1142                 complete(&pgdat_init_all_done_comp);
1143 }
1144
1145 /* Initialise remaining memory on a node */
1146 static int __init deferred_init_memmap(void *data)
1147 {
1148         pg_data_t *pgdat = data;
1149         int nid = pgdat->node_id;
1150         struct mminit_pfnnid_cache nid_init_state = { };
1151         unsigned long start = jiffies;
1152         unsigned long nr_pages = 0;
1153         unsigned long walk_start, walk_end;
1154         int i, zid;
1155         struct zone *zone;
1156         unsigned long first_init_pfn = pgdat->first_deferred_pfn;
1157         const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
1158
1159         if (first_init_pfn == ULONG_MAX) {
1160                 pgdat_init_report_one_done();
1161                 return 0;
1162         }
1163
1164         /* Bind memory initialisation thread to a local node if possible */
1165         if (!cpumask_empty(cpumask))
1166                 set_cpus_allowed_ptr(current, cpumask);
1167
1168         /* Sanity check boundaries */
1169         BUG_ON(pgdat->first_deferred_pfn < pgdat->node_start_pfn);
1170         BUG_ON(pgdat->first_deferred_pfn > pgdat_end_pfn(pgdat));
1171         pgdat->first_deferred_pfn = ULONG_MAX;
1172
1173         /* Only the highest zone is deferred so find it */
1174         for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1175                 zone = pgdat->node_zones + zid;
1176                 if (first_init_pfn < zone_end_pfn(zone))
1177                         break;
1178         }
1179
1180         for_each_mem_pfn_range(i, nid, &walk_start, &walk_end, NULL) {
1181                 unsigned long pfn, end_pfn;
1182                 struct page *page = NULL;
1183                 struct page *free_base_page = NULL;
1184                 unsigned long free_base_pfn = 0;
1185                 int nr_to_free = 0;
1186
1187                 end_pfn = min(walk_end, zone_end_pfn(zone));
1188                 pfn = first_init_pfn;
1189                 if (pfn < walk_start)
1190                         pfn = walk_start;
1191                 if (pfn < zone->zone_start_pfn)
1192                         pfn = zone->zone_start_pfn;
1193
1194                 for (; pfn < end_pfn; pfn++) {
1195                         if (!pfn_valid_within(pfn))
1196                                 goto free_range;
1197
1198                         /*
1199                          * Ensure pfn_valid is checked every
1200                          * MAX_ORDER_NR_PAGES for memory holes
1201                          */
1202                         if ((pfn & (MAX_ORDER_NR_PAGES - 1)) == 0) {
1203                                 if (!pfn_valid(pfn)) {
1204                                         page = NULL;
1205                                         goto free_range;
1206                                 }
1207                         }
1208
1209                         if (!meminit_pfn_in_nid(pfn, nid, &nid_init_state)) {
1210                                 page = NULL;
1211                                 goto free_range;
1212                         }
1213
1214                         /* Minimise pfn page lookups and scheduler checks */
1215                         if (page && (pfn & (MAX_ORDER_NR_PAGES - 1)) != 0) {
1216                                 page++;
1217                         } else {
1218                                 nr_pages += nr_to_free;
1219                                 deferred_free_range(free_base_page,
1220                                                 free_base_pfn, nr_to_free);
1221                                 free_base_page = NULL;
1222                                 free_base_pfn = nr_to_free = 0;
1223
1224                                 page = pfn_to_page(pfn);
1225                                 cond_resched();
1226                         }
1227
1228                         if (page->flags) {
1229                                 VM_BUG_ON(page_zone(page) != zone);
1230                                 goto free_range;
1231                         }
1232
1233                         __init_single_page(page, pfn, zid, nid);
1234                         if (!free_base_page) {
1235                                 free_base_page = page;
1236                                 free_base_pfn = pfn;
1237                                 nr_to_free = 0;
1238                         }
1239                         nr_to_free++;
1240
1241                         /* Where possible, batch up pages for a single free */
1242                         continue;
1243 free_range:
1244                         /* Free the current block of pages to allocator */
1245                         nr_pages += nr_to_free;
1246                         deferred_free_range(free_base_page, free_base_pfn,
1247                                                                 nr_to_free);
1248                         free_base_page = NULL;
1249                         free_base_pfn = nr_to_free = 0;
1250                 }
1251
1252                 first_init_pfn = max(end_pfn, first_init_pfn);
1253         }
1254
1255         /* Sanity check that the next zone really is unpopulated */
1256         WARN_ON(++zid < MAX_NR_ZONES && populated_zone(++zone));
1257
1258         pr_info("node %d initialised, %lu pages in %ums\n", nid, nr_pages,
1259                                         jiffies_to_msecs(jiffies - start));
1260
1261         pgdat_init_report_one_done();
1262         return 0;
1263 }
1264
1265 void __init page_alloc_init_late(void)
1266 {
1267         int nid;
1268
1269         /* There will be num_node_state(N_MEMORY) threads */
1270         atomic_set(&pgdat_init_n_undone, num_node_state(N_MEMORY));
1271         for_each_node_state(nid, N_MEMORY) {
1272                 kthread_run(deferred_init_memmap, NODE_DATA(nid), "pgdatinit%d", nid);
1273         }
1274
1275         /* Block until all are initialised */
1276         wait_for_completion(&pgdat_init_all_done_comp);
1277
1278         /* Reinit limits that are based on free pages after the kernel is up */
1279         files_maxfiles_init();
1280 }
1281 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
1282
1283 #ifdef CONFIG_CMA
1284 /* Free whole pageblock and set its migration type to MIGRATE_CMA. */
1285 void __init init_cma_reserved_pageblock(struct page *page)
1286 {
1287         unsigned i = pageblock_nr_pages;
1288         struct page *p = page;
1289
1290         do {
1291                 __ClearPageReserved(p);
1292                 set_page_count(p, 0);
1293         } while (++p, --i);
1294
1295         set_pageblock_migratetype(page, MIGRATE_CMA);
1296
1297         if (pageblock_order >= MAX_ORDER) {
1298                 i = pageblock_nr_pages;
1299                 p = page;
1300                 do {
1301                         set_page_refcounted(p);
1302                         __free_pages(p, MAX_ORDER - 1);
1303                         p += MAX_ORDER_NR_PAGES;
1304                 } while (i -= MAX_ORDER_NR_PAGES);
1305         } else {
1306                 set_page_refcounted(page);
1307                 __free_pages(page, pageblock_order);
1308         }
1309
1310         adjust_managed_page_count(page, pageblock_nr_pages);
1311 }
1312 #endif
1313
1314 /*
1315  * The order of subdivision here is critical for the IO subsystem.
1316  * Please do not alter this order without good reasons and regression
1317  * testing. Specifically, as large blocks of memory are subdivided,
1318  * the order in which smaller blocks are delivered depends on the order
1319  * they're subdivided in this function. This is the primary factor
1320  * influencing the order in which pages are delivered to the IO
1321  * subsystem according to empirical testing, and this is also justified
1322  * by considering the behavior of a buddy system containing a single
1323  * large block of memory acted on by a series of small allocations.
1324  * This behavior is a critical factor in sglist merging's success.
1325  *
1326  * -- nyc
1327  */
1328 static inline void expand(struct zone *zone, struct page *page,
1329         int low, int high, struct free_area *area,
1330         int migratetype)
1331 {
1332         unsigned long size = 1 << high;
1333
1334         while (high > low) {
1335                 area--;
1336                 high--;
1337                 size >>= 1;
1338                 VM_BUG_ON_PAGE(bad_range(zone, &page[size]), &page[size]);
1339
1340                 if (IS_ENABLED(CONFIG_DEBUG_PAGEALLOC) &&
1341                         debug_guardpage_enabled() &&
1342                         high < debug_guardpage_minorder()) {
1343                         /*
1344                          * Mark as guard pages (or page), that will allow to
1345                          * merge back to allocator when buddy will be freed.
1346                          * Corresponding page table entries will not be touched,
1347                          * pages will stay not present in virtual address space
1348                          */
1349                         set_page_guard(zone, &page[size], high, migratetype);
1350                         continue;
1351                 }
1352                 list_add(&page[size].lru, &area->free_list[migratetype]);
1353                 area->nr_free++;
1354                 set_page_order(&page[size], high);
1355         }
1356 }
1357
1358 /*
1359  * This page is about to be returned from the page allocator
1360  */
1361 static inline int check_new_page(struct page *page)
1362 {
1363         const char *bad_reason = NULL;
1364         unsigned long bad_flags = 0;
1365
1366         if (unlikely(page_mapcount(page)))
1367                 bad_reason = "nonzero mapcount";
1368         if (unlikely(page->mapping != NULL))
1369                 bad_reason = "non-NULL mapping";
1370         if (unlikely(atomic_read(&page->_count) != 0))
1371                 bad_reason = "nonzero _count";
1372         if (unlikely(page->flags & __PG_HWPOISON)) {
1373                 bad_reason = "HWPoisoned (hardware-corrupted)";
1374                 bad_flags = __PG_HWPOISON;
1375         }
1376         if (unlikely(page->flags & PAGE_FLAGS_CHECK_AT_PREP)) {
1377                 bad_reason = "PAGE_FLAGS_CHECK_AT_PREP flag set";
1378                 bad_flags = PAGE_FLAGS_CHECK_AT_PREP;
1379         }
1380 #ifdef CONFIG_MEMCG
1381         if (unlikely(page->mem_cgroup))
1382                 bad_reason = "page still charged to cgroup";
1383 #endif
1384         if (unlikely(bad_reason)) {
1385                 bad_page(page, bad_reason, bad_flags);
1386                 return 1;
1387         }
1388         return 0;
1389 }
1390
1391 static int prep_new_page(struct page *page, unsigned int order, gfp_t gfp_flags,
1392                                                                 int alloc_flags)
1393 {
1394         int i;
1395
1396         for (i = 0; i < (1 << order); i++) {
1397                 struct page *p = page + i;
1398                 if (unlikely(check_new_page(p)))
1399                         return 1;
1400         }
1401
1402         set_page_private(page, 0);
1403         set_page_refcounted(page);
1404
1405         arch_alloc_page(page, order);
1406         kernel_map_pages(page, 1 << order, 1);
1407         kasan_alloc_pages(page, order);
1408
1409         if (gfp_flags & __GFP_ZERO)
1410                 for (i = 0; i < (1 << order); i++)
1411                         clear_highpage(page + i);
1412
1413         if (order && (gfp_flags & __GFP_COMP))
1414                 prep_compound_page(page, order);
1415
1416         set_page_owner(page, order, gfp_flags);
1417
1418         /*
1419          * page is set pfmemalloc when ALLOC_NO_WATERMARKS was necessary to
1420          * allocate the page. The expectation is that the caller is taking
1421          * steps that will free more memory. The caller should avoid the page
1422          * being used for !PFMEMALLOC purposes.
1423          */
1424         if (alloc_flags & ALLOC_NO_WATERMARKS)
1425                 set_page_pfmemalloc(page);
1426         else
1427                 clear_page_pfmemalloc(page);
1428
1429         return 0;
1430 }
1431
1432 /*
1433  * Go through the free lists for the given migratetype and remove
1434  * the smallest available page from the freelists
1435  */
1436 static inline
1437 struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
1438                                                 int migratetype)
1439 {
1440         unsigned int current_order;
1441         struct free_area *area;
1442         struct page *page;
1443
1444         /* Find a page of the appropriate size in the preferred list */
1445         for (current_order = order; current_order < MAX_ORDER; ++current_order) {
1446                 area = &(zone->free_area[current_order]);
1447                 if (list_empty(&area->free_list[migratetype]))
1448                         continue;
1449
1450                 page = list_entry(area->free_list[migratetype].next,
1451                                                         struct page, lru);
1452                 list_del(&page->lru);
1453                 rmv_page_order(page);
1454                 area->nr_free--;
1455                 expand(zone, page, order, current_order, area, migratetype);
1456                 set_pcppage_migratetype(page, migratetype);
1457                 return page;
1458         }
1459
1460         return NULL;
1461 }
1462
1463
1464 /*
1465  * This array describes the order lists are fallen back to when
1466  * the free lists for the desirable migrate type are depleted
1467  */
1468 static int fallbacks[MIGRATE_TYPES][4] = {
1469         [MIGRATE_UNMOVABLE]   = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE,   MIGRATE_TYPES },
1470         [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE,   MIGRATE_MOVABLE,   MIGRATE_TYPES },
1471         [MIGRATE_MOVABLE]     = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_TYPES },
1472 #ifdef CONFIG_CMA
1473         [MIGRATE_CMA]         = { MIGRATE_TYPES }, /* Never used */
1474 #endif
1475 #ifdef CONFIG_MEMORY_ISOLATION
1476         [MIGRATE_ISOLATE]     = { MIGRATE_TYPES }, /* Never used */
1477 #endif
1478 };
1479
1480 #ifdef CONFIG_CMA
1481 static struct page *__rmqueue_cma_fallback(struct zone *zone,
1482                                         unsigned int order)
1483 {
1484         return __rmqueue_smallest(zone, order, MIGRATE_CMA);
1485 }
1486 #else
1487 static inline struct page *__rmqueue_cma_fallback(struct zone *zone,
1488                                         unsigned int order) { return NULL; }
1489 #endif
1490
1491 /*
1492  * Move the free pages in a range to the free lists of the requested type.
1493  * Note that start_page and end_pages are not aligned on a pageblock
1494  * boundary. If alignment is required, use move_freepages_block()
1495  */
1496 int move_freepages(struct zone *zone,
1497                           struct page *start_page, struct page *end_page,
1498                           int migratetype)
1499 {
1500         struct page *page;
1501         unsigned int order;
1502         int pages_moved = 0;
1503
1504 #ifndef CONFIG_HOLES_IN_ZONE
1505         /*
1506          * page_zone is not safe to call in this context when
1507          * CONFIG_HOLES_IN_ZONE is set. This bug check is probably redundant
1508          * anyway as we check zone boundaries in move_freepages_block().
1509          * Remove at a later date when no bug reports exist related to
1510          * grouping pages by mobility
1511          */
1512         VM_BUG_ON(page_zone(start_page) != page_zone(end_page));
1513 #endif
1514
1515         for (page = start_page; page <= end_page;) {
1516                 /* Make sure we are not inadvertently changing nodes */
1517                 VM_BUG_ON_PAGE(page_to_nid(page) != zone_to_nid(zone), page);
1518
1519                 if (!pfn_valid_within(page_to_pfn(page))) {
1520                         page++;
1521                         continue;
1522                 }
1523
1524                 if (!PageBuddy(page)) {
1525                         page++;
1526                         continue;
1527                 }
1528
1529                 order = page_order(page);
1530                 list_move(&page->lru,
1531                           &zone->free_area[order].free_list[migratetype]);
1532                 page += 1 << order;
1533                 pages_moved += 1 << order;
1534         }
1535
1536         return pages_moved;
1537 }
1538
1539 int move_freepages_block(struct zone *zone, struct page *page,
1540                                 int migratetype)
1541 {
1542         unsigned long start_pfn, end_pfn;
1543         struct page *start_page, *end_page;
1544
1545         start_pfn = page_to_pfn(page);
1546         start_pfn = start_pfn & ~(pageblock_nr_pages-1);
1547         start_page = pfn_to_page(start_pfn);
1548         end_page = start_page + pageblock_nr_pages - 1;
1549         end_pfn = start_pfn + pageblock_nr_pages - 1;
1550
1551         /* Do not cross zone boundaries */
1552         if (!zone_spans_pfn(zone, start_pfn))
1553                 start_page = page;
1554         if (!zone_spans_pfn(zone, end_pfn))
1555                 return 0;
1556
1557         return move_freepages(zone, start_page, end_page, migratetype);
1558 }
1559
1560 static void change_pageblock_range(struct page *pageblock_page,
1561                                         int start_order, int migratetype)
1562 {
1563         int nr_pageblocks = 1 << (start_order - pageblock_order);
1564
1565         while (nr_pageblocks--) {
1566                 set_pageblock_migratetype(pageblock_page, migratetype);
1567                 pageblock_page += pageblock_nr_pages;
1568         }
1569 }
1570
1571 /*
1572  * When we are falling back to another migratetype during allocation, try to
1573  * steal extra free pages from the same pageblocks to satisfy further
1574  * allocations, instead of polluting multiple pageblocks.
1575  *
1576  * If we are stealing a relatively large buddy page, it is likely there will
1577  * be more free pages in the pageblock, so try to steal them all. For
1578  * reclaimable and unmovable allocations, we steal regardless of page size,
1579  * as fragmentation caused by those allocations polluting movable pageblocks
1580  * is worse than movable allocations stealing from unmovable and reclaimable
1581  * pageblocks.
1582  */
1583 static bool can_steal_fallback(unsigned int order, int start_mt)
1584 {
1585         /*
1586          * Leaving this order check is intended, although there is
1587          * relaxed order check in next check. The reason is that
1588          * we can actually steal whole pageblock if this condition met,
1589          * but, below check doesn't guarantee it and that is just heuristic
1590          * so could be changed anytime.
1591          */
1592         if (order >= pageblock_order)
1593                 return true;
1594
1595         if (order >= pageblock_order / 2 ||
1596                 start_mt == MIGRATE_RECLAIMABLE ||
1597                 start_mt == MIGRATE_UNMOVABLE ||
1598                 page_group_by_mobility_disabled)
1599                 return true;
1600
1601         return false;
1602 }
1603
1604 /*
1605  * This function implements actual steal behaviour. If order is large enough,
1606  * we can steal whole pageblock. If not, we first move freepages in this
1607  * pageblock and check whether half of pages are moved or not. If half of
1608  * pages are moved, we can change migratetype of pageblock and permanently
1609  * use it's pages as requested migratetype in the future.
1610  */
1611 static void steal_suitable_fallback(struct zone *zone, struct page *page,
1612                                                           int start_type)
1613 {
1614         unsigned int current_order = page_order(page);
1615         int pages;
1616
1617         /* Take ownership for orders >= pageblock_order */
1618         if (current_order >= pageblock_order) {
1619                 change_pageblock_range(page, current_order, start_type);
1620                 return;
1621         }
1622
1623         pages = move_freepages_block(zone, page, start_type);
1624
1625         /* Claim the whole block if over half of it is free */
1626         if (pages >= (1 << (pageblock_order-1)) ||
1627                         page_group_by_mobility_disabled)
1628                 set_pageblock_migratetype(page, start_type);
1629 }
1630
1631 /*
1632  * Check whether there is a suitable fallback freepage with requested order.
1633  * If only_stealable is true, this function returns fallback_mt only if
1634  * we can steal other freepages all together. This would help to reduce
1635  * fragmentation due to mixed migratetype pages in one pageblock.
1636  */
1637 int find_suitable_fallback(struct free_area *area, unsigned int order,
1638                         int migratetype, bool only_stealable, bool *can_steal)
1639 {
1640         int i;
1641         int fallback_mt;
1642
1643         if (area->nr_free == 0)
1644                 return -1;
1645
1646         *can_steal = false;
1647         for (i = 0;; i++) {
1648                 fallback_mt = fallbacks[migratetype][i];
1649                 if (fallback_mt == MIGRATE_TYPES)
1650                         break;
1651
1652                 if (list_empty(&area->free_list[fallback_mt]))
1653                         continue;
1654
1655                 if (can_steal_fallback(order, migratetype))
1656                         *can_steal = true;
1657
1658                 if (!only_stealable)
1659                         return fallback_mt;
1660
1661                 if (*can_steal)
1662                         return fallback_mt;
1663         }
1664
1665         return -1;
1666 }
1667
1668 /*
1669  * Reserve a pageblock for exclusive use of high-order atomic allocations if
1670  * there are no empty page blocks that contain a page with a suitable order
1671  */
1672 static void reserve_highatomic_pageblock(struct page *page, struct zone *zone,
1673                                 unsigned int alloc_order)
1674 {
1675         int mt;
1676         unsigned long max_managed, flags;
1677
1678         /*
1679          * Limit the number reserved to 1 pageblock or roughly 1% of a zone.
1680          * Check is race-prone but harmless.
1681          */
1682         max_managed = (zone->managed_pages / 100) + pageblock_nr_pages;
1683         if (zone->nr_reserved_highatomic >= max_managed)
1684                 return;
1685
1686         spin_lock_irqsave(&zone->lock, flags);
1687
1688         /* Recheck the nr_reserved_highatomic limit under the lock */
1689         if (zone->nr_reserved_highatomic >= max_managed)
1690                 goto out_unlock;
1691
1692         /* Yoink! */
1693         mt = get_pageblock_migratetype(page);
1694         if (mt != MIGRATE_HIGHATOMIC &&
1695                         !is_migrate_isolate(mt) && !is_migrate_cma(mt)) {
1696                 zone->nr_reserved_highatomic += pageblock_nr_pages;
1697                 set_pageblock_migratetype(page, MIGRATE_HIGHATOMIC);
1698                 move_freepages_block(zone, page, MIGRATE_HIGHATOMIC);
1699         }
1700
1701 out_unlock:
1702         spin_unlock_irqrestore(&zone->lock, flags);
1703 }
1704
1705 /*
1706  * Used when an allocation is about to fail under memory pressure. This
1707  * potentially hurts the reliability of high-order allocations when under
1708  * intense memory pressure but failed atomic allocations should be easier
1709  * to recover from than an OOM.
1710  */
1711 static void unreserve_highatomic_pageblock(const struct alloc_context *ac)
1712 {
1713         struct zonelist *zonelist = ac->zonelist;
1714         unsigned long flags;
1715         struct zoneref *z;
1716         struct zone *zone;
1717         struct page *page;
1718         int order;
1719
1720         for_each_zone_zonelist_nodemask(zone, z, zonelist, ac->high_zoneidx,
1721                                                                 ac->nodemask) {
1722                 /* Preserve at least one pageblock */
1723                 if (zone->nr_reserved_highatomic <= pageblock_nr_pages)
1724                         continue;
1725
1726                 spin_lock_irqsave(&zone->lock, flags);
1727                 for (order = 0; order < MAX_ORDER; order++) {
1728                         struct free_area *area = &(zone->free_area[order]);
1729
1730                         if (list_empty(&area->free_list[MIGRATE_HIGHATOMIC]))
1731                                 continue;
1732
1733                         page = list_entry(area->free_list[MIGRATE_HIGHATOMIC].next,
1734                                                 struct page, lru);
1735
1736                         /*
1737                          * It should never happen but changes to locking could
1738                          * inadvertently allow a per-cpu drain to add pages
1739                          * to MIGRATE_HIGHATOMIC while unreserving so be safe
1740                          * and watch for underflows.
1741                          */
1742                         zone->nr_reserved_highatomic -= min(pageblock_nr_pages,
1743                                 zone->nr_reserved_highatomic);
1744
1745                         /*
1746                          * Convert to ac->migratetype and avoid the normal
1747                          * pageblock stealing heuristics. Minimally, the caller
1748                          * is doing the work and needs the pages. More
1749                          * importantly, if the block was always converted to
1750                          * MIGRATE_UNMOVABLE or another type then the number
1751                          * of pageblocks that cannot be completely freed
1752                          * may increase.
1753                          */
1754                         set_pageblock_migratetype(page, ac->migratetype);
1755                         move_freepages_block(zone, page, ac->migratetype);
1756                         spin_unlock_irqrestore(&zone->lock, flags);
1757                         return;
1758                 }
1759                 spin_unlock_irqrestore(&zone->lock, flags);
1760         }
1761 }
1762
1763 /* Remove an element from the buddy allocator from the fallback list */
1764 static inline struct page *
1765 __rmqueue_fallback(struct zone *zone, unsigned int order, int start_migratetype)
1766 {
1767         struct free_area *area;
1768         unsigned int current_order;
1769         struct page *page;
1770         int fallback_mt;
1771         bool can_steal;
1772
1773         /* Find the largest possible block of pages in the other list */
1774         for (current_order = MAX_ORDER-1;
1775                                 current_order >= order && current_order <= MAX_ORDER-1;
1776                                 --current_order) {
1777                 area = &(zone->free_area[current_order]);
1778                 fallback_mt = find_suitable_fallback(area, current_order,
1779                                 start_migratetype, false, &can_steal);
1780                 if (fallback_mt == -1)
1781                         continue;
1782
1783                 page = list_entry(area->free_list[fallback_mt].next,
1784                                                 struct page, lru);
1785                 if (can_steal)
1786                         steal_suitable_fallback(zone, page, start_migratetype);
1787
1788                 /* Remove the page from the freelists */
1789                 area->nr_free--;
1790                 list_del(&page->lru);
1791                 rmv_page_order(page);
1792
1793                 expand(zone, page, order, current_order, area,
1794                                         start_migratetype);
1795                 /*
1796                  * The pcppage_migratetype may differ from pageblock's
1797                  * migratetype depending on the decisions in
1798                  * find_suitable_fallback(). This is OK as long as it does not
1799                  * differ for MIGRATE_CMA pageblocks. Those can be used as
1800                  * fallback only via special __rmqueue_cma_fallback() function
1801                  */
1802                 set_pcppage_migratetype(page, start_migratetype);
1803
1804                 trace_mm_page_alloc_extfrag(page, order, current_order,
1805                         start_migratetype, fallback_mt);
1806
1807                 return page;
1808         }
1809
1810         return NULL;
1811 }
1812
1813 /*
1814  * Do the hard work of removing an element from the buddy allocator.
1815  * Call me with the zone->lock already held.
1816  */
1817 static struct page *__rmqueue(struct zone *zone, unsigned int order,
1818                                 int migratetype, gfp_t gfp_flags)
1819 {
1820         struct page *page;
1821
1822         page = __rmqueue_smallest(zone, order, migratetype);
1823         if (unlikely(!page)) {
1824                 if (migratetype == MIGRATE_MOVABLE)
1825                         page = __rmqueue_cma_fallback(zone, order);
1826
1827                 if (!page)
1828                         page = __rmqueue_fallback(zone, order, migratetype);
1829         }
1830
1831         trace_mm_page_alloc_zone_locked(page, order, migratetype);
1832         return page;
1833 }
1834
1835 /*
1836  * Obtain a specified number of elements from the buddy allocator, all under
1837  * a single hold of the lock, for efficiency.  Add them to the supplied list.
1838  * Returns the number of new pages which were placed at *list.
1839  */
1840 static int rmqueue_bulk(struct zone *zone, unsigned int order,
1841                         unsigned long count, struct list_head *list,
1842                         int migratetype, bool cold)
1843 {
1844         int i;
1845
1846         spin_lock(&zone->lock);
1847         for (i = 0; i < count; ++i) {
1848                 struct page *page = __rmqueue(zone, order, migratetype, 0);
1849                 if (unlikely(page == NULL))
1850                         break;
1851
1852                 /*
1853                  * Split buddy pages returned by expand() are received here
1854                  * in physical page order. The page is added to the callers and
1855                  * list and the list head then moves forward. From the callers
1856                  * perspective, the linked list is ordered by page number in
1857                  * some conditions. This is useful for IO devices that can
1858                  * merge IO requests if the physical pages are ordered
1859                  * properly.
1860                  */
1861                 if (likely(!cold))
1862                         list_add(&page->lru, list);
1863                 else
1864                         list_add_tail(&page->lru, list);
1865                 list = &page->lru;
1866                 if (is_migrate_cma(get_pcppage_migratetype(page)))
1867                         __mod_zone_page_state(zone, NR_FREE_CMA_PAGES,
1868                                               -(1 << order));
1869         }
1870         __mod_zone_page_state(zone, NR_FREE_PAGES, -(i << order));
1871         spin_unlock(&zone->lock);
1872         return i;
1873 }
1874
1875 #ifdef CONFIG_NUMA
1876 /*
1877  * Called from the vmstat counter updater to drain pagesets of this
1878  * currently executing processor on remote nodes after they have
1879  * expired.
1880  *
1881  * Note that this function must be called with the thread pinned to
1882  * a single processor.
1883  */
1884 void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp)
1885 {
1886         unsigned long flags;
1887         int to_drain, batch;
1888
1889         local_irq_save(flags);
1890         batch = READ_ONCE(pcp->batch);
1891         to_drain = min(pcp->count, batch);
1892         if (to_drain > 0) {
1893                 free_pcppages_bulk(zone, to_drain, pcp);
1894                 pcp->count -= to_drain;
1895         }
1896         local_irq_restore(flags);
1897 }
1898 #endif
1899
1900 /*
1901  * Drain pcplists of the indicated processor and zone.
1902  *
1903  * The processor must either be the current processor and the
1904  * thread pinned to the current processor or a processor that
1905  * is not online.
1906  */
1907 static void drain_pages_zone(unsigned int cpu, struct zone *zone)
1908 {
1909         unsigned long flags;
1910         struct per_cpu_pageset *pset;
1911         struct per_cpu_pages *pcp;
1912
1913         local_irq_save(flags);
1914         pset = per_cpu_ptr(zone->pageset, cpu);
1915
1916         pcp = &pset->pcp;
1917         if (pcp->count) {
1918                 free_pcppages_bulk(zone, pcp->count, pcp);
1919                 pcp->count = 0;
1920         }
1921         local_irq_restore(flags);
1922 }
1923
1924 /*
1925  * Drain pcplists of all zones on the indicated processor.
1926  *
1927  * The processor must either be the current processor and the
1928  * thread pinned to the current processor or a processor that
1929  * is not online.
1930  */
1931 static void drain_pages(unsigned int cpu)
1932 {
1933         struct zone *zone;
1934
1935         for_each_populated_zone(zone) {
1936                 drain_pages_zone(cpu, zone);
1937         }
1938 }
1939
1940 /*
1941  * Spill all of this CPU's per-cpu pages back into the buddy allocator.
1942  *
1943  * The CPU has to be pinned. When zone parameter is non-NULL, spill just
1944  * the single zone's pages.
1945  */
1946 void drain_local_pages(struct zone *zone)
1947 {
1948         int cpu = smp_processor_id();
1949
1950         if (zone)
1951                 drain_pages_zone(cpu, zone);
1952         else
1953                 drain_pages(cpu);
1954 }
1955
1956 /*
1957  * Spill all the per-cpu pages from all CPUs back into the buddy allocator.
1958  *
1959  * When zone parameter is non-NULL, spill just the single zone's pages.
1960  *
1961  * Note that this code is protected against sending an IPI to an offline
1962  * CPU but does not guarantee sending an IPI to newly hotplugged CPUs:
1963  * on_each_cpu_mask() blocks hotplug and won't talk to offlined CPUs but
1964  * nothing keeps CPUs from showing up after we populated the cpumask and
1965  * before the call to on_each_cpu_mask().
1966  */
1967 void drain_all_pages(struct zone *zone)
1968 {
1969         int cpu;
1970
1971         /*
1972          * Allocate in the BSS so we wont require allocation in
1973          * direct reclaim path for CONFIG_CPUMASK_OFFSTACK=y
1974          */
1975         static cpumask_t cpus_with_pcps;
1976
1977         /*
1978          * We don't care about racing with CPU hotplug event
1979          * as offline notification will cause the notified
1980          * cpu to drain that CPU pcps and on_each_cpu_mask
1981          * disables preemption as part of its processing
1982          */
1983         for_each_online_cpu(cpu) {
1984                 struct per_cpu_pageset *pcp;
1985                 struct zone *z;
1986                 bool has_pcps = false;
1987
1988                 if (zone) {
1989                         pcp = per_cpu_ptr(zone->pageset, cpu);
1990                         if (pcp->pcp.count)
1991                                 has_pcps = true;
1992                 } else {
1993                         for_each_populated_zone(z) {
1994                                 pcp = per_cpu_ptr(z->pageset, cpu);
1995                                 if (pcp->pcp.count) {
1996                                         has_pcps = true;
1997                                         break;
1998                                 }
1999                         }
2000                 }
2001
2002                 if (has_pcps)
2003                         cpumask_set_cpu(cpu, &cpus_with_pcps);
2004                 else
2005                         cpumask_clear_cpu(cpu, &cpus_with_pcps);
2006         }
2007         on_each_cpu_mask(&cpus_with_pcps, (smp_call_func_t) drain_local_pages,
2008                                                                 zone, 1);
2009 }
2010
2011 #ifdef CONFIG_HIBERNATION
2012
2013 void mark_free_pages(struct zone *zone)
2014 {
2015         unsigned long pfn, max_zone_pfn;
2016         unsigned long flags;
2017         unsigned int order, t;
2018         struct list_head *curr;
2019
2020         if (zone_is_empty(zone))
2021                 return;
2022
2023         spin_lock_irqsave(&zone->lock, flags);
2024
2025         max_zone_pfn = zone_end_pfn(zone);
2026         for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
2027                 if (pfn_valid(pfn)) {
2028                         struct page *page = pfn_to_page(pfn);
2029
2030                         if (!swsusp_page_is_forbidden(page))
2031                                 swsusp_unset_page_free(page);
2032                 }
2033
2034         for_each_migratetype_order(order, t) {
2035                 list_for_each(curr, &zone->free_area[order].free_list[t]) {
2036                         unsigned long i;
2037
2038                         pfn = page_to_pfn(list_entry(curr, struct page, lru));
2039                         for (i = 0; i < (1UL << order); i++)
2040                                 swsusp_set_page_free(pfn_to_page(pfn + i));
2041                 }
2042         }
2043         spin_unlock_irqrestore(&zone->lock, flags);
2044 }
2045 #endif /* CONFIG_PM */
2046
2047 /*
2048  * Free a 0-order page
2049  * cold == true ? free a cold page : free a hot page
2050  */
2051 void free_hot_cold_page(struct page *page, bool cold)
2052 {
2053         struct zone *zone = page_zone(page);
2054         struct per_cpu_pages *pcp;
2055         unsigned long flags;
2056         unsigned long pfn = page_to_pfn(page);
2057         int migratetype;
2058
2059         if (!free_pages_prepare(page, 0))
2060                 return;
2061
2062         migratetype = get_pfnblock_migratetype(page, pfn);
2063         set_pcppage_migratetype(page, migratetype);
2064         local_irq_save(flags);
2065         __count_vm_event(PGFREE);
2066
2067         /*
2068          * We only track unmovable, reclaimable and movable on pcp lists.
2069          * Free ISOLATE pages back to the allocator because they are being
2070          * offlined but treat RESERVE as movable pages so we can get those
2071          * areas back if necessary. Otherwise, we may have to free
2072          * excessively into the page allocator
2073          */
2074         if (migratetype >= MIGRATE_PCPTYPES) {
2075                 if (unlikely(is_migrate_isolate(migratetype))) {
2076                         free_one_page(zone, page, pfn, 0, migratetype);
2077                         goto out;
2078                 }
2079                 migratetype = MIGRATE_MOVABLE;
2080         }
2081
2082         pcp = &this_cpu_ptr(zone->pageset)->pcp;
2083         if (!cold)
2084                 list_add(&page->lru, &pcp->lists[migratetype]);
2085         else
2086                 list_add_tail(&page->lru, &pcp->lists[migratetype]);
2087         pcp->count++;
2088         if (pcp->count >= pcp->high) {
2089                 unsigned long batch = READ_ONCE(pcp->batch);
2090                 free_pcppages_bulk(zone, batch, pcp);
2091                 pcp->count -= batch;
2092         }
2093
2094 out:
2095         local_irq_restore(flags);
2096 }
2097
2098 /*
2099  * Free a list of 0-order pages
2100  */
2101 void free_hot_cold_page_list(struct list_head *list, bool cold)
2102 {
2103         struct page *page, *next;
2104
2105         list_for_each_entry_safe(page, next, list, lru) {
2106                 trace_mm_page_free_batched(page, cold);
2107                 free_hot_cold_page(page, cold);
2108         }
2109 }
2110
2111 /*
2112  * split_page takes a non-compound higher-order page, and splits it into
2113  * n (1<<order) sub-pages: page[0..n]
2114  * Each sub-page must be freed individually.
2115  *
2116  * Note: this is probably too low level an operation for use in drivers.
2117  * Please consult with lkml before using this in your driver.
2118  */
2119 void split_page(struct page *page, unsigned int order)
2120 {
2121         int i;
2122         gfp_t gfp_mask;
2123
2124         VM_BUG_ON_PAGE(PageCompound(page), page);
2125         VM_BUG_ON_PAGE(!page_count(page), page);
2126
2127 #ifdef CONFIG_KMEMCHECK
2128         /*
2129          * Split shadow pages too, because free(page[0]) would
2130          * otherwise free the whole shadow.
2131          */
2132         if (kmemcheck_page_is_tracked(page))
2133                 split_page(virt_to_page(page[0].shadow), order);
2134 #endif
2135
2136         gfp_mask = get_page_owner_gfp(page);
2137         set_page_owner(page, 0, gfp_mask);
2138         for (i = 1; i < (1 << order); i++) {
2139                 set_page_refcounted(page + i);
2140                 set_page_owner(page + i, 0, gfp_mask);
2141         }
2142 }
2143 EXPORT_SYMBOL_GPL(split_page);
2144
2145 int __isolate_free_page(struct page *page, unsigned int order)
2146 {
2147         unsigned long watermark;
2148         struct zone *zone;
2149         int mt;
2150
2151         BUG_ON(!PageBuddy(page));
2152
2153         zone = page_zone(page);
2154         mt = get_pageblock_migratetype(page);
2155
2156         if (!is_migrate_isolate(mt)) {
2157                 /* Obey watermarks as if the page was being allocated */
2158                 watermark = low_wmark_pages(zone) + (1 << order);
2159                 if (!zone_watermark_ok(zone, 0, watermark, 0, 0))
2160                         return 0;
2161
2162                 __mod_zone_freepage_state(zone, -(1UL << order), mt);
2163         }
2164
2165         /* Remove page from free list */
2166         list_del(&page->lru);
2167         zone->free_area[order].nr_free--;
2168         rmv_page_order(page);
2169
2170         set_page_owner(page, order, __GFP_MOVABLE);
2171
2172         /* Set the pageblock if the isolated page is at least a pageblock */
2173         if (order >= pageblock_order - 1) {
2174                 struct page *endpage = page + (1 << order) - 1;
2175                 for (; page < endpage; page += pageblock_nr_pages) {
2176                         int mt = get_pageblock_migratetype(page);
2177                         if (!is_migrate_isolate(mt) && !is_migrate_cma(mt))
2178                                 set_pageblock_migratetype(page,
2179                                                           MIGRATE_MOVABLE);
2180                 }
2181         }
2182
2183
2184         return 1UL << order;
2185 }
2186
2187 /*
2188  * Similar to split_page except the page is already free. As this is only
2189  * being used for migration, the migratetype of the block also changes.
2190  * As this is called with interrupts disabled, the caller is responsible
2191  * for calling arch_alloc_page() and kernel_map_page() after interrupts
2192  * are enabled.
2193  *
2194  * Note: this is probably too low level an operation for use in drivers.
2195  * Please consult with lkml before using this in your driver.
2196  */
2197 int split_free_page(struct page *page)
2198 {
2199         unsigned int order;
2200         int nr_pages;
2201
2202         order = page_order(page);
2203
2204         nr_pages = __isolate_free_page(page, order);
2205         if (!nr_pages)
2206                 return 0;
2207
2208         /* Split into individual pages */
2209         set_page_refcounted(page);
2210         split_page(page, order);
2211         return nr_pages;
2212 }
2213
2214 /*
2215  * Allocate a page from the given zone. Use pcplists for order-0 allocations.
2216  */
2217 static inline
2218 struct page *buffered_rmqueue(struct zone *preferred_zone,
2219                         struct zone *zone, unsigned int order,
2220                         gfp_t gfp_flags, int alloc_flags, int migratetype)
2221 {
2222         unsigned long flags;
2223         struct page *page;
2224         bool cold = ((gfp_flags & __GFP_COLD) != 0);
2225
2226         if (likely(order == 0)) {
2227                 struct per_cpu_pages *pcp;
2228                 struct list_head *list;
2229
2230                 local_irq_save(flags);
2231                 pcp = &this_cpu_ptr(zone->pageset)->pcp;
2232                 list = &pcp->lists[migratetype];
2233                 if (list_empty(list)) {
2234                         pcp->count += rmqueue_bulk(zone, 0,
2235                                         pcp->batch, list,
2236                                         migratetype, cold);
2237                         if (unlikely(list_empty(list)))
2238                                 goto failed;
2239                 }
2240
2241                 if (cold)
2242                         page = list_entry(list->prev, struct page, lru);
2243                 else
2244                         page = list_entry(list->next, struct page, lru);
2245
2246                 list_del(&page->lru);
2247                 pcp->count--;
2248         } else {
2249                 if (unlikely(gfp_flags & __GFP_NOFAIL)) {
2250                         /*
2251                          * __GFP_NOFAIL is not to be used in new code.
2252                          *
2253                          * All __GFP_NOFAIL callers should be fixed so that they
2254                          * properly detect and handle allocation failures.
2255                          *
2256                          * We most definitely don't want callers attempting to
2257                          * allocate greater than order-1 page units with
2258                          * __GFP_NOFAIL.
2259                          */
2260                         WARN_ON_ONCE(order > 1);
2261                 }
2262                 spin_lock_irqsave(&zone->lock, flags);
2263
2264                 page = NULL;
2265                 if (alloc_flags & ALLOC_HARDER) {
2266                         page = __rmqueue_smallest(zone, order, MIGRATE_HIGHATOMIC);
2267                         if (page)
2268                                 trace_mm_page_alloc_zone_locked(page, order, migratetype);
2269                 }
2270                 if (!page)
2271                         page = __rmqueue(zone, order, migratetype, gfp_flags);
2272                 spin_unlock(&zone->lock);
2273                 if (!page)
2274                         goto failed;
2275                 __mod_zone_freepage_state(zone, -(1 << order),
2276                                           get_pcppage_migratetype(page));
2277         }
2278
2279         __mod_zone_page_state(zone, NR_ALLOC_BATCH, -(1 << order));
2280         if (atomic_long_read(&zone->vm_stat[NR_ALLOC_BATCH]) <= 0 &&
2281             !test_bit(ZONE_FAIR_DEPLETED, &zone->flags))
2282                 set_bit(ZONE_FAIR_DEPLETED, &zone->flags);
2283
2284         __count_zone_vm_events(PGALLOC, zone, 1 << order);
2285         zone_statistics(preferred_zone, zone, gfp_flags);
2286         local_irq_restore(flags);
2287
2288         VM_BUG_ON_PAGE(bad_range(zone, page), page);
2289         return page;
2290
2291 failed:
2292         local_irq_restore(flags);
2293         return NULL;
2294 }
2295
2296 #ifdef CONFIG_FAIL_PAGE_ALLOC
2297
2298 static struct {
2299         struct fault_attr attr;
2300
2301         bool ignore_gfp_highmem;
2302         bool ignore_gfp_reclaim;
2303         u32 min_order;
2304 } fail_page_alloc = {
2305         .attr = FAULT_ATTR_INITIALIZER,
2306         .ignore_gfp_reclaim = true,
2307         .ignore_gfp_highmem = true,
2308         .min_order = 1,
2309 };
2310
2311 static int __init setup_fail_page_alloc(char *str)
2312 {
2313         return setup_fault_attr(&fail_page_alloc.attr, str);
2314 }
2315 __setup("fail_page_alloc=", setup_fail_page_alloc);
2316
2317 static bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
2318 {
2319         if (order < fail_page_alloc.min_order)
2320                 return false;
2321         if (gfp_mask & __GFP_NOFAIL)
2322                 return false;
2323         if (fail_page_alloc.ignore_gfp_highmem && (gfp_mask & __GFP_HIGHMEM))
2324                 return false;
2325         if (fail_page_alloc.ignore_gfp_reclaim &&
2326                         (gfp_mask & __GFP_DIRECT_RECLAIM))
2327                 return false;
2328
2329         return should_fail(&fail_page_alloc.attr, 1 << order);
2330 }
2331
2332 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
2333
2334 static int __init fail_page_alloc_debugfs(void)
2335 {
2336         umode_t mode = S_IFREG | S_IRUSR | S_IWUSR;
2337         struct dentry *dir;
2338
2339         dir = fault_create_debugfs_attr("fail_page_alloc", NULL,
2340                                         &fail_page_alloc.attr);
2341         if (IS_ERR(dir))
2342                 return PTR_ERR(dir);
2343
2344         if (!debugfs_create_bool("ignore-gfp-wait", mode, dir,
2345                                 &fail_page_alloc.ignore_gfp_reclaim))
2346                 goto fail;
2347         if (!debugfs_create_bool("ignore-gfp-highmem", mode, dir,
2348                                 &fail_page_alloc.ignore_gfp_highmem))
2349                 goto fail;
2350         if (!debugfs_create_u32("min-order", mode, dir,
2351                                 &fail_page_alloc.min_order))
2352                 goto fail;
2353
2354         return 0;
2355 fail:
2356         debugfs_remove_recursive(dir);
2357
2358         return -ENOMEM;
2359 }
2360
2361 late_initcall(fail_page_alloc_debugfs);
2362
2363 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
2364
2365 #else /* CONFIG_FAIL_PAGE_ALLOC */
2366
2367 static inline bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
2368 {
2369         return false;
2370 }
2371
2372 #endif /* CONFIG_FAIL_PAGE_ALLOC */
2373
2374 /*
2375  * Return true if free base pages are above 'mark'. For high-order checks it
2376  * will return true of the order-0 watermark is reached and there is at least
2377  * one free page of a suitable size. Checking now avoids taking the zone lock
2378  * to check in the allocation paths if no pages are free.
2379  */
2380 static bool __zone_watermark_ok(struct zone *z, unsigned int order,
2381                         unsigned long mark, int classzone_idx, int alloc_flags,
2382                         long free_pages)
2383 {
2384         long min = mark;
2385         int o;
2386         const int alloc_harder = (alloc_flags & ALLOC_HARDER);
2387
2388         /* free_pages may go negative - that's OK */
2389         free_pages -= (1 << order) - 1;
2390
2391         if (alloc_flags & ALLOC_HIGH)
2392                 min -= min / 2;
2393
2394         /*
2395          * If the caller does not have rights to ALLOC_HARDER then subtract
2396          * the high-atomic reserves. This will over-estimate the size of the
2397          * atomic reserve but it avoids a search.
2398          */
2399         if (likely(!alloc_harder))
2400                 free_pages -= z->nr_reserved_highatomic;
2401         else
2402                 min -= min / 4;
2403
2404 #ifdef CONFIG_CMA
2405         /* If allocation can't use CMA areas don't use free CMA pages */
2406         if (!(alloc_flags & ALLOC_CMA))
2407                 free_pages -= zone_page_state(z, NR_FREE_CMA_PAGES);
2408 #endif
2409
2410         /*
2411          * Check watermarks for an order-0 allocation request. If these
2412          * are not met, then a high-order request also cannot go ahead
2413          * even if a suitable page happened to be free.
2414          */
2415         if (free_pages <= min + z->lowmem_reserve[classzone_idx])
2416                 return false;
2417
2418         /* If this is an order-0 request then the watermark is fine */
2419         if (!order)
2420                 return true;
2421
2422         /* For a high-order request, check at least one suitable page is free */
2423         for (o = order; o < MAX_ORDER; o++) {
2424                 struct free_area *area = &z->free_area[o];
2425                 int mt;
2426
2427                 if (!area->nr_free)
2428                         continue;
2429
2430                 if (alloc_harder)
2431                         return true;
2432
2433                 for (mt = 0; mt < MIGRATE_PCPTYPES; mt++) {
2434                         if (!list_empty(&area->free_list[mt]))
2435                                 return true;
2436                 }
2437
2438 #ifdef CONFIG_CMA
2439                 if ((alloc_flags & ALLOC_CMA) &&
2440                     !list_empty(&area->free_list[MIGRATE_CMA])) {
2441                         return true;
2442                 }
2443 #endif
2444         }
2445         return false;
2446 }
2447
2448 bool zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
2449                       int classzone_idx, int alloc_flags)
2450 {
2451         return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
2452                                         zone_page_state(z, NR_FREE_PAGES));
2453 }
2454
2455 bool zone_watermark_ok_safe(struct zone *z, unsigned int order,
2456                         unsigned long mark, int classzone_idx)
2457 {
2458         long free_pages = zone_page_state(z, NR_FREE_PAGES);
2459
2460         if (z->percpu_drift_mark && free_pages < z->percpu_drift_mark)
2461                 free_pages = zone_page_state_snapshot(z, NR_FREE_PAGES);
2462
2463         return __zone_watermark_ok(z, order, mark, classzone_idx, 0,
2464                                                                 free_pages);
2465 }
2466
2467 #ifdef CONFIG_NUMA
2468 static bool zone_local(struct zone *local_zone, struct zone *zone)
2469 {
2470         return local_zone->node == zone->node;
2471 }
2472
2473 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
2474 {
2475         return node_distance(zone_to_nid(local_zone), zone_to_nid(zone)) <
2476                                 RECLAIM_DISTANCE;
2477 }
2478 #else   /* CONFIG_NUMA */
2479 static bool zone_local(struct zone *local_zone, struct zone *zone)
2480 {
2481         return true;
2482 }
2483
2484 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
2485 {
2486         return true;
2487 }
2488 #endif  /* CONFIG_NUMA */
2489
2490 static void reset_alloc_batches(struct zone *preferred_zone)
2491 {
2492         struct zone *zone = preferred_zone->zone_pgdat->node_zones;
2493
2494         do {
2495                 mod_zone_page_state(zone, NR_ALLOC_BATCH,
2496                         high_wmark_pages(zone) - low_wmark_pages(zone) -
2497                         atomic_long_read(&zone->vm_stat[NR_ALLOC_BATCH]));
2498                 clear_bit(ZONE_FAIR_DEPLETED, &zone->flags);
2499         } while (zone++ != preferred_zone);
2500 }
2501
2502 /*
2503  * get_page_from_freelist goes through the zonelist trying to allocate
2504  * a page.
2505  */
2506 static struct page *
2507 get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags,
2508                                                 const struct alloc_context *ac)
2509 {
2510         struct zonelist *zonelist = ac->zonelist;
2511         struct zoneref *z;
2512         struct page *page = NULL;
2513         struct zone *zone;
2514         int nr_fair_skipped = 0;
2515         bool zonelist_rescan;
2516
2517 zonelist_scan:
2518         zonelist_rescan = false;
2519
2520         /*
2521          * Scan zonelist, looking for a zone with enough free.
2522          * See also __cpuset_node_allowed() comment in kernel/cpuset.c.
2523          */
2524         for_each_zone_zonelist_nodemask(zone, z, zonelist, ac->high_zoneidx,
2525                                                                 ac->nodemask) {
2526                 unsigned long mark;
2527
2528                 if (cpusets_enabled() &&
2529                         (alloc_flags & ALLOC_CPUSET) &&
2530                         !cpuset_zone_allowed(zone, gfp_mask))
2531                                 continue;
2532                 /*
2533                  * Distribute pages in proportion to the individual
2534                  * zone size to ensure fair page aging.  The zone a
2535                  * page was allocated in should have no effect on the
2536                  * time the page has in memory before being reclaimed.
2537                  */
2538                 if (alloc_flags & ALLOC_FAIR) {
2539                         if (!zone_local(ac->preferred_zone, zone))
2540                                 break;
2541                         if (test_bit(ZONE_FAIR_DEPLETED, &zone->flags)) {
2542                                 nr_fair_skipped++;
2543                                 continue;
2544                         }
2545                 }
2546                 /*
2547                  * When allocating a page cache page for writing, we
2548                  * want to get it from a zone that is within its dirty
2549                  * limit, such that no single zone holds more than its
2550                  * proportional share of globally allowed dirty pages.
2551                  * The dirty limits take into account the zone's
2552                  * lowmem reserves and high watermark so that kswapd
2553                  * should be able to balance it without having to
2554                  * write pages from its LRU list.
2555                  *
2556                  * This may look like it could increase pressure on
2557                  * lower zones by failing allocations in higher zones
2558                  * before they are full.  But the pages that do spill
2559                  * over are limited as the lower zones are protected
2560                  * by this very same mechanism.  It should not become
2561                  * a practical burden to them.
2562                  *
2563                  * XXX: For now, allow allocations to potentially
2564                  * exceed the per-zone dirty limit in the slowpath
2565                  * (spread_dirty_pages unset) before going into reclaim,
2566                  * which is important when on a NUMA setup the allowed
2567                  * zones are together not big enough to reach the
2568                  * global limit.  The proper fix for these situations
2569                  * will require awareness of zones in the
2570                  * dirty-throttling and the flusher threads.
2571                  */
2572                 if (ac->spread_dirty_pages && !zone_dirty_ok(zone))
2573                         continue;
2574
2575                 mark = zone->watermark[alloc_flags & ALLOC_WMARK_MASK];
2576                 if (!zone_watermark_ok(zone, order, mark,
2577                                        ac->classzone_idx, alloc_flags)) {
2578                         int ret;
2579
2580                         /* Checked here to keep the fast path fast */
2581                         BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK);
2582                         if (alloc_flags & ALLOC_NO_WATERMARKS)
2583                                 goto try_this_zone;
2584
2585                         if (zone_reclaim_mode == 0 ||
2586                             !zone_allows_reclaim(ac->preferred_zone, zone))
2587                                 continue;
2588
2589                         ret = zone_reclaim(zone, gfp_mask, order);
2590                         switch (ret) {
2591                         case ZONE_RECLAIM_NOSCAN:
2592                                 /* did not scan */
2593                                 continue;
2594                         case ZONE_RECLAIM_FULL:
2595                                 /* scanned but unreclaimable */
2596                                 continue;
2597                         default:
2598                                 /* did we reclaim enough */
2599                                 if (zone_watermark_ok(zone, order, mark,
2600                                                 ac->classzone_idx, alloc_flags))
2601                                         goto try_this_zone;
2602
2603                                 continue;
2604                         }
2605                 }
2606
2607 try_this_zone:
2608                 page = buffered_rmqueue(ac->preferred_zone, zone, order,
2609                                 gfp_mask, alloc_flags, ac->migratetype);
2610                 if (page) {
2611                         if (prep_new_page(page, order, gfp_mask, alloc_flags))
2612                                 goto try_this_zone;
2613
2614                         /*
2615                          * If this is a high-order atomic allocation then check
2616                          * if the pageblock should be reserved for the future
2617                          */
2618                         if (unlikely(order && (alloc_flags & ALLOC_HARDER)))
2619                                 reserve_highatomic_pageblock(page, zone, order);
2620
2621                         return page;
2622                 }
2623         }
2624
2625         /*
2626          * The first pass makes sure allocations are spread fairly within the
2627          * local node.  However, the local node might have free pages left
2628          * after the fairness batches are exhausted, and remote zones haven't
2629          * even been considered yet.  Try once more without fairness, and
2630          * include remote zones now, before entering the slowpath and waking
2631          * kswapd: prefer spilling to a remote zone over swapping locally.
2632          */
2633         if (alloc_flags & ALLOC_FAIR) {
2634                 alloc_flags &= ~ALLOC_FAIR;
2635                 if (nr_fair_skipped) {
2636                         zonelist_rescan = true;
2637                         reset_alloc_batches(ac->preferred_zone);
2638                 }
2639                 if (nr_online_nodes > 1)
2640                         zonelist_rescan = true;
2641         }
2642
2643         if (zonelist_rescan)
2644                 goto zonelist_scan;
2645
2646         return NULL;
2647 }
2648
2649 /*
2650  * Large machines with many possible nodes should not always dump per-node
2651  * meminfo in irq context.
2652  */
2653 static inline bool should_suppress_show_mem(void)
2654 {
2655         bool ret = false;
2656
2657 #if NODES_SHIFT > 8
2658         ret = in_interrupt();
2659 #endif
2660         return ret;
2661 }
2662
2663 static DEFINE_RATELIMIT_STATE(nopage_rs,
2664                 DEFAULT_RATELIMIT_INTERVAL,
2665                 DEFAULT_RATELIMIT_BURST);
2666
2667 void warn_alloc_failed(gfp_t gfp_mask, unsigned int order, const char *fmt, ...)
2668 {
2669         unsigned int filter = SHOW_MEM_FILTER_NODES;
2670
2671         if ((gfp_mask & __GFP_NOWARN) || !__ratelimit(&nopage_rs) ||
2672             debug_guardpage_minorder() > 0)
2673                 return;
2674
2675         /*
2676          * This documents exceptions given to allocations in certain
2677          * contexts that are allowed to allocate outside current's set
2678          * of allowed nodes.
2679          */
2680         if (!(gfp_mask & __GFP_NOMEMALLOC))
2681                 if (test_thread_flag(TIF_MEMDIE) ||
2682                     (current->flags & (PF_MEMALLOC | PF_EXITING)))
2683                         filter &= ~SHOW_MEM_FILTER_NODES;
2684         if (in_interrupt() || !(gfp_mask & __GFP_DIRECT_RECLAIM))
2685                 filter &= ~SHOW_MEM_FILTER_NODES;
2686
2687         if (fmt) {
2688                 struct va_format vaf;
2689                 va_list args;
2690
2691                 va_start(args, fmt);
2692
2693                 vaf.fmt = fmt;
2694                 vaf.va = &args;
2695
2696                 pr_warn("%pV", &vaf);
2697
2698                 va_end(args);
2699         }
2700
2701         pr_warn("%s: page allocation failure: order:%u, mode:0x%x\n",
2702                 current->comm, order, gfp_mask);
2703
2704         dump_stack();
2705         if (!should_suppress_show_mem())
2706                 show_mem(filter);
2707 }
2708
2709 static inline struct page *
2710 __alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order,
2711         const struct alloc_context *ac, unsigned long *did_some_progress)
2712 {
2713         struct oom_control oc = {
2714                 .zonelist = ac->zonelist,
2715                 .nodemask = ac->nodemask,
2716                 .gfp_mask = gfp_mask,
2717                 .order = order,
2718         };
2719         struct page *page;
2720
2721         *did_some_progress = 0;
2722
2723         /*
2724          * Acquire the oom lock.  If that fails, somebody else is
2725          * making progress for us.
2726          */
2727         if (!mutex_trylock(&oom_lock)) {
2728                 *did_some_progress = 1;
2729                 schedule_timeout_uninterruptible(1);
2730                 return NULL;
2731         }
2732
2733         /*
2734          * Go through the zonelist yet one more time, keep very high watermark
2735          * here, this is only to catch a parallel oom killing, we must fail if
2736          * we're still under heavy pressure.
2737          */
2738         page = get_page_from_freelist(gfp_mask | __GFP_HARDWALL, order,
2739                                         ALLOC_WMARK_HIGH|ALLOC_CPUSET, ac);
2740         if (page)
2741                 goto out;
2742
2743         if (!(gfp_mask & __GFP_NOFAIL)) {
2744                 /* Coredumps can quickly deplete all memory reserves */
2745                 if (current->flags & PF_DUMPCORE)
2746                         goto out;
2747                 /* The OOM killer will not help higher order allocs */
2748                 if (order > PAGE_ALLOC_COSTLY_ORDER)
2749                         goto out;
2750                 /* The OOM killer does not needlessly kill tasks for lowmem */
2751                 if (ac->high_zoneidx < ZONE_NORMAL)
2752                         goto out;
2753                 /* The OOM killer does not compensate for IO-less reclaim */
2754                 if (!(gfp_mask & __GFP_FS)) {
2755                         /*
2756                          * XXX: Page reclaim didn't yield anything,
2757                          * and the OOM killer can't be invoked, but
2758                          * keep looping as per tradition.
2759                          */
2760                         *did_some_progress = 1;
2761                         goto out;
2762                 }
2763                 if (pm_suspended_storage())
2764                         goto out;
2765                 /* The OOM killer may not free memory on a specific node */
2766                 if (gfp_mask & __GFP_THISNODE)
2767                         goto out;
2768         }
2769         /* Exhausted what can be done so it's blamo time */
2770         if (out_of_memory(&oc) || WARN_ON_ONCE(gfp_mask & __GFP_NOFAIL))
2771                 *did_some_progress = 1;
2772 out:
2773         mutex_unlock(&oom_lock);
2774         return page;
2775 }
2776
2777 #ifdef CONFIG_COMPACTION
2778 /* Try memory compaction for high-order allocations before reclaim */
2779 static struct page *
2780 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
2781                 int alloc_flags, const struct alloc_context *ac,
2782                 enum migrate_mode mode, int *contended_compaction,
2783                 bool *deferred_compaction)
2784 {
2785         unsigned long compact_result;
2786         struct page *page;
2787
2788         if (!order)
2789                 return NULL;
2790
2791         current->flags |= PF_MEMALLOC;
2792         compact_result = try_to_compact_pages(gfp_mask, order, alloc_flags, ac,
2793                                                 mode, contended_compaction);
2794         current->flags &= ~PF_MEMALLOC;
2795
2796         switch (compact_result) {
2797         case COMPACT_DEFERRED:
2798                 *deferred_compaction = true;
2799                 /* fall-through */
2800         case COMPACT_SKIPPED:
2801                 return NULL;
2802         default:
2803                 break;
2804         }
2805
2806         /*
2807          * At least in one zone compaction wasn't deferred or skipped, so let's
2808          * count a compaction stall
2809          */
2810         count_vm_event(COMPACTSTALL);
2811
2812         page = get_page_from_freelist(gfp_mask, order,
2813                                         alloc_flags & ~ALLOC_NO_WATERMARKS, ac);
2814
2815         if (page) {
2816                 struct zone *zone = page_zone(page);
2817
2818                 zone->compact_blockskip_flush = false;
2819                 compaction_defer_reset(zone, order, true);
2820                 count_vm_event(COMPACTSUCCESS);
2821                 return page;
2822         }
2823
2824         /*
2825          * It's bad if compaction run occurs and fails. The most likely reason
2826          * is that pages exist, but not enough to satisfy watermarks.
2827          */
2828         count_vm_event(COMPACTFAIL);
2829
2830         cond_resched();
2831
2832         return NULL;
2833 }
2834 #else
2835 static inline struct page *
2836 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
2837                 int alloc_flags, const struct alloc_context *ac,
2838                 enum migrate_mode mode, int *contended_compaction,
2839                 bool *deferred_compaction)
2840 {
2841         return NULL;
2842 }
2843 #endif /* CONFIG_COMPACTION */
2844
2845 /* Perform direct synchronous page reclaim */
2846 static int
2847 __perform_reclaim(gfp_t gfp_mask, unsigned int order,
2848                                         const struct alloc_context *ac)
2849 {
2850         struct reclaim_state reclaim_state;
2851         int progress;
2852
2853         cond_resched();
2854
2855         /* We now go into synchronous reclaim */
2856         cpuset_memory_pressure_bump();
2857         current->flags |= PF_MEMALLOC;
2858         lockdep_set_current_reclaim_state(gfp_mask);
2859         reclaim_state.reclaimed_slab = 0;
2860         current->reclaim_state = &reclaim_state;
2861
2862         progress = try_to_free_pages(ac->zonelist, order, gfp_mask,
2863                                                                 ac->nodemask);
2864
2865         current->reclaim_state = NULL;
2866         lockdep_clear_current_reclaim_state();
2867         current->flags &= ~PF_MEMALLOC;
2868
2869         cond_resched();
2870
2871         return progress;
2872 }
2873
2874 /* The really slow allocator path where we enter direct reclaim */
2875 static inline struct page *
2876 __alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order,
2877                 int alloc_flags, const struct alloc_context *ac,
2878                 unsigned long *did_some_progress)
2879 {
2880         struct page *page = NULL;
2881         bool drained = false;
2882
2883         *did_some_progress = __perform_reclaim(gfp_mask, order, ac);
2884         if (unlikely(!(*did_some_progress)))
2885                 return NULL;
2886
2887 retry:
2888         page = get_page_from_freelist(gfp_mask, order,
2889                                         alloc_flags & ~ALLOC_NO_WATERMARKS, ac);
2890
2891         /*
2892          * If an allocation failed after direct reclaim, it could be because
2893          * pages are pinned on the per-cpu lists or in high alloc reserves.
2894          * Shrink them them and try again
2895          */
2896         if (!page && !drained) {
2897                 unreserve_highatomic_pageblock(ac);
2898                 drain_all_pages(NULL);
2899                 drained = true;
2900                 goto retry;
2901         }
2902
2903         return page;
2904 }
2905
2906 /*
2907  * This is called in the allocator slow-path if the allocation request is of
2908  * sufficient urgency to ignore watermarks and take other desperate measures
2909  */
2910 static inline struct page *
2911 __alloc_pages_high_priority(gfp_t gfp_mask, unsigned int order,
2912                                 const struct alloc_context *ac)
2913 {
2914         struct page *page;
2915
2916         do {
2917                 page = get_page_from_freelist(gfp_mask, order,
2918                                                 ALLOC_NO_WATERMARKS, ac);
2919
2920                 if (!page && gfp_mask & __GFP_NOFAIL)
2921                         wait_iff_congested(ac->preferred_zone, BLK_RW_ASYNC,
2922                                                                         HZ/50);
2923         } while (!page && (gfp_mask & __GFP_NOFAIL));
2924
2925         return page;
2926 }
2927
2928 static void wake_all_kswapds(unsigned int order, const struct alloc_context *ac)
2929 {
2930         struct zoneref *z;
2931         struct zone *zone;
2932
2933         for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
2934                                                 ac->high_zoneidx, ac->nodemask)
2935                 wakeup_kswapd(zone, order, zone_idx(ac->preferred_zone));
2936 }
2937
2938 static inline int
2939 gfp_to_alloc_flags(gfp_t gfp_mask)
2940 {
2941         int alloc_flags = ALLOC_WMARK_MIN | ALLOC_CPUSET;
2942
2943         /* __GFP_HIGH is assumed to be the same as ALLOC_HIGH to save a branch. */
2944         BUILD_BUG_ON(__GFP_HIGH != (__force gfp_t) ALLOC_HIGH);
2945
2946         /*
2947          * The caller may dip into page reserves a bit more if the caller
2948          * cannot run direct reclaim, or if the caller has realtime scheduling
2949          * policy or is asking for __GFP_HIGH memory.  GFP_ATOMIC requests will
2950          * set both ALLOC_HARDER (__GFP_ATOMIC) and ALLOC_HIGH (__GFP_HIGH).
2951          */
2952         alloc_flags |= (__force int) (gfp_mask & __GFP_HIGH);
2953
2954         if (gfp_mask & __GFP_ATOMIC) {
2955                 /*
2956                  * Not worth trying to allocate harder for __GFP_NOMEMALLOC even
2957                  * if it can't schedule.
2958                  */
2959                 if (!(gfp_mask & __GFP_NOMEMALLOC))
2960                         alloc_flags |= ALLOC_HARDER;
2961                 /*
2962                  * Ignore cpuset mems for GFP_ATOMIC rather than fail, see the
2963                  * comment for __cpuset_node_allowed().
2964                  */
2965                 alloc_flags &= ~ALLOC_CPUSET;
2966         } else if (unlikely(rt_task(current)) && !in_interrupt())
2967                 alloc_flags |= ALLOC_HARDER;
2968
2969         if (likely(!(gfp_mask & __GFP_NOMEMALLOC))) {
2970                 if (gfp_mask & __GFP_MEMALLOC)
2971                         alloc_flags |= ALLOC_NO_WATERMARKS;
2972                 else if (in_serving_softirq() && (current->flags & PF_MEMALLOC))
2973                         alloc_flags |= ALLOC_NO_WATERMARKS;
2974                 else if (!in_interrupt() &&
2975                                 ((current->flags & PF_MEMALLOC) ||
2976                                  unlikely(test_thread_flag(TIF_MEMDIE))))
2977                         alloc_flags |= ALLOC_NO_WATERMARKS;
2978         }
2979 #ifdef CONFIG_CMA
2980         if (gfpflags_to_migratetype(gfp_mask) == MIGRATE_MOVABLE)
2981                 alloc_flags |= ALLOC_CMA;
2982 #endif
2983         return alloc_flags;
2984 }
2985
2986 bool gfp_pfmemalloc_allowed(gfp_t gfp_mask)
2987 {
2988         return !!(gfp_to_alloc_flags(gfp_mask) & ALLOC_NO_WATERMARKS);
2989 }
2990
2991 static inline bool is_thp_gfp_mask(gfp_t gfp_mask)
2992 {
2993         return (gfp_mask & (GFP_TRANSHUGE | __GFP_KSWAPD_RECLAIM)) == GFP_TRANSHUGE;
2994 }
2995
2996 static inline struct page *
2997 __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order,
2998                                                 struct alloc_context *ac)
2999 {
3000         bool can_direct_reclaim = gfp_mask & __GFP_DIRECT_RECLAIM;
3001         struct page *page = NULL;
3002         int alloc_flags;
3003         unsigned long pages_reclaimed = 0;
3004         unsigned long did_some_progress;
3005         enum migrate_mode migration_mode = MIGRATE_ASYNC;
3006         bool deferred_compaction = false;
3007         int contended_compaction = COMPACT_CONTENDED_NONE;
3008
3009         /*
3010          * In the slowpath, we sanity check order to avoid ever trying to
3011          * reclaim >= MAX_ORDER areas which will never succeed. Callers may
3012          * be using allocators in order of preference for an area that is
3013          * too large.
3014          */
3015         if (order >= MAX_ORDER) {
3016                 WARN_ON_ONCE(!(gfp_mask & __GFP_NOWARN));
3017                 return NULL;
3018         }
3019
3020         /*
3021          * We also sanity check to catch abuse of atomic reserves being used by
3022          * callers that are not in atomic context.
3023          */
3024         if (WARN_ON_ONCE((gfp_mask & (__GFP_ATOMIC|__GFP_DIRECT_RECLAIM)) ==
3025                                 (__GFP_ATOMIC|__GFP_DIRECT_RECLAIM)))
3026                 gfp_mask &= ~__GFP_ATOMIC;
3027
3028         /*
3029          * If this allocation cannot block and it is for a specific node, then
3030          * fail early.  There's no need to wakeup kswapd or retry for a
3031          * speculative node-specific allocation.
3032          */
3033         if (IS_ENABLED(CONFIG_NUMA) && (gfp_mask & __GFP_THISNODE) && !can_direct_reclaim)
3034                 goto nopage;
3035
3036 retry:
3037         if (gfp_mask & __GFP_KSWAPD_RECLAIM)
3038                 wake_all_kswapds(order, ac);
3039
3040         /*
3041          * OK, we're below the kswapd watermark and have kicked background
3042          * reclaim. Now things get more complex, so set up alloc_flags according
3043          * to how we want to proceed.
3044          */
3045         alloc_flags = gfp_to_alloc_flags(gfp_mask);
3046
3047         /*
3048          * Find the true preferred zone if the allocation is unconstrained by
3049          * cpusets.
3050          */
3051         if (!(alloc_flags & ALLOC_CPUSET) && !ac->nodemask) {
3052                 struct zoneref *preferred_zoneref;
3053                 preferred_zoneref = first_zones_zonelist(ac->zonelist,
3054                                 ac->high_zoneidx, NULL, &ac->preferred_zone);
3055                 ac->classzone_idx = zonelist_zone_idx(preferred_zoneref);
3056         }
3057
3058         /* This is the last chance, in general, before the goto nopage. */
3059         page = get_page_from_freelist(gfp_mask, order,
3060                                 alloc_flags & ~ALLOC_NO_WATERMARKS, ac);
3061         if (page)
3062                 goto got_pg;
3063
3064         /* Allocate without watermarks if the context allows */
3065         if (alloc_flags & ALLOC_NO_WATERMARKS) {
3066                 /*
3067                  * Ignore mempolicies if ALLOC_NO_WATERMARKS on the grounds
3068                  * the allocation is high priority and these type of
3069                  * allocations are system rather than user orientated
3070                  */
3071                 ac->zonelist = node_zonelist(numa_node_id(), gfp_mask);
3072
3073                 page = __alloc_pages_high_priority(gfp_mask, order, ac);
3074
3075                 if (page) {
3076                         goto got_pg;
3077                 }
3078         }
3079
3080         /* Caller is not willing to reclaim, we can't balance anything */
3081         if (!can_direct_reclaim) {
3082                 /*
3083                  * All existing users of the deprecated __GFP_NOFAIL are
3084                  * blockable, so warn of any new users that actually allow this
3085                  * type of allocation to fail.
3086                  */
3087                 WARN_ON_ONCE(gfp_mask & __GFP_NOFAIL);
3088                 goto nopage;
3089         }
3090
3091         /* Avoid recursion of direct reclaim */
3092         if (current->flags & PF_MEMALLOC)
3093                 goto nopage;
3094
3095         /* Avoid allocations with no watermarks from looping endlessly */
3096         if (test_thread_flag(TIF_MEMDIE) && !(gfp_mask & __GFP_NOFAIL))
3097                 goto nopage;
3098
3099         /*
3100          * Try direct compaction. The first pass is asynchronous. Subsequent
3101          * attempts after direct reclaim are synchronous
3102          */
3103         page = __alloc_pages_direct_compact(gfp_mask, order, alloc_flags, ac,
3104                                         migration_mode,
3105                                         &contended_compaction,
3106                                         &deferred_compaction);
3107         if (page)
3108                 goto got_pg;
3109
3110         /* Checks for THP-specific high-order allocations */
3111         if (is_thp_gfp_mask(gfp_mask)) {
3112                 /*
3113                  * If compaction is deferred for high-order allocations, it is
3114                  * because sync compaction recently failed. If this is the case
3115                  * and the caller requested a THP allocation, we do not want
3116                  * to heavily disrupt the system, so we fail the allocation
3117                  * instead of entering direct reclaim.
3118                  */
3119                 if (deferred_compaction)
3120                         goto nopage;
3121
3122                 /*
3123                  * In all zones where compaction was attempted (and not
3124                  * deferred or skipped), lock contention has been detected.
3125                  * For THP allocation we do not want to disrupt the others
3126                  * so we fallback to base pages instead.
3127                  */
3128                 if (contended_compaction == COMPACT_CONTENDED_LOCK)
3129                         goto nopage;
3130
3131                 /*
3132                  * If compaction was aborted due to need_resched(), we do not
3133                  * want to further increase allocation latency, unless it is
3134                  * khugepaged trying to collapse.
3135                  */
3136                 if (contended_compaction == COMPACT_CONTENDED_SCHED
3137                         && !(current->flags & PF_KTHREAD))
3138                         goto nopage;
3139         }
3140
3141         /*
3142          * It can become very expensive to allocate transparent hugepages at
3143          * fault, so use asynchronous memory compaction for THP unless it is
3144          * khugepaged trying to collapse.
3145          */
3146         if (!is_thp_gfp_mask(gfp_mask) || (current->flags & PF_KTHREAD))
3147                 migration_mode = MIGRATE_SYNC_LIGHT;
3148
3149         /* Try direct reclaim and then allocating */
3150         page = __alloc_pages_direct_reclaim(gfp_mask, order, alloc_flags, ac,
3151                                                         &did_some_progress);
3152         if (page)
3153                 goto got_pg;
3154
3155         /* Do not loop if specifically requested */
3156         if (gfp_mask & __GFP_NORETRY)
3157                 goto noretry;
3158
3159         /* Keep reclaiming pages as long as there is reasonable progress */
3160         pages_reclaimed += did_some_progress;
3161         if ((did_some_progress && order <= PAGE_ALLOC_COSTLY_ORDER) ||
3162             ((gfp_mask & __GFP_REPEAT) && pages_reclaimed < (1 << order))) {
3163                 /* Wait for some write requests to complete then retry */
3164                 wait_iff_congested(ac->preferred_zone, BLK_RW_ASYNC, HZ/50);
3165                 goto retry;
3166         }
3167
3168         /* Reclaim has failed us, start killing things */
3169         page = __alloc_pages_may_oom(gfp_mask, order, ac, &did_some_progress);
3170         if (page)
3171                 goto got_pg;
3172
3173         /* Retry as long as the OOM killer is making progress */
3174         if (did_some_progress)
3175                 goto retry;
3176
3177 noretry:
3178         /*
3179          * High-order allocations do not necessarily loop after
3180          * direct reclaim and reclaim/compaction depends on compaction
3181          * being called after reclaim so call directly if necessary
3182          */
3183         page = __alloc_pages_direct_compact(gfp_mask, order, alloc_flags,
3184                                             ac, migration_mode,
3185                                             &contended_compaction,
3186                                             &deferred_compaction);
3187         if (page)
3188                 goto got_pg;
3189 nopage:
3190         warn_alloc_failed(gfp_mask, order, NULL);
3191 got_pg:
3192         return page;
3193 }
3194
3195 /*
3196  * This is the 'heart' of the zoned buddy allocator.
3197  */
3198 struct page *
3199 __alloc_pages_nodemask(gfp_t gfp_mask, unsigned int order,
3200                         struct zonelist *zonelist, nodemask_t *nodemask)
3201 {
3202         struct zoneref *preferred_zoneref;
3203         struct page *page = NULL;
3204         unsigned int cpuset_mems_cookie;
3205         int alloc_flags = ALLOC_WMARK_LOW|ALLOC_CPUSET|ALLOC_FAIR;
3206         gfp_t alloc_mask; /* The gfp_t that was actually used for allocation */
3207         struct alloc_context ac = {
3208                 .high_zoneidx = gfp_zone(gfp_mask),
3209                 .nodemask = nodemask,
3210                 .migratetype = gfpflags_to_migratetype(gfp_mask),
3211         };
3212
3213         gfp_mask &= gfp_allowed_mask;
3214
3215         lockdep_trace_alloc(gfp_mask);
3216
3217         might_sleep_if(gfp_mask & __GFP_DIRECT_RECLAIM);
3218
3219         if (should_fail_alloc_page(gfp_mask, order))
3220                 return NULL;
3221
3222         /*
3223          * Check the zones suitable for the gfp_mask contain at least one
3224          * valid zone. It's possible to have an empty zonelist as a result
3225          * of __GFP_THISNODE and a memoryless node
3226          */
3227         if (unlikely(!zonelist->_zonerefs->zone))
3228                 return NULL;
3229
3230         if (IS_ENABLED(CONFIG_CMA) && ac.migratetype == MIGRATE_MOVABLE)
3231                 alloc_flags |= ALLOC_CMA;
3232
3233 retry_cpuset:
3234         cpuset_mems_cookie = read_mems_allowed_begin();
3235
3236         /* We set it here, as __alloc_pages_slowpath might have changed it */
3237         ac.zonelist = zonelist;
3238
3239         /* Dirty zone balancing only done in the fast path */
3240         ac.spread_dirty_pages = (gfp_mask & __GFP_WRITE);
3241
3242         /* The preferred zone is used for statistics later */
3243         preferred_zoneref = first_zones_zonelist(ac.zonelist, ac.high_zoneidx,
3244                                 ac.nodemask ? : &cpuset_current_mems_allowed,
3245                                 &ac.preferred_zone);
3246         if (!ac.preferred_zone)
3247                 goto out;
3248         ac.classzone_idx = zonelist_zone_idx(preferred_zoneref);
3249
3250         /* First allocation attempt */
3251         alloc_mask = gfp_mask|__GFP_HARDWALL;
3252         page = get_page_from_freelist(alloc_mask, order, alloc_flags, &ac);
3253         if (unlikely(!page)) {
3254                 /*
3255                  * Runtime PM, block IO and its error handling path
3256                  * can deadlock because I/O on the device might not
3257                  * complete.
3258                  */
3259                 alloc_mask = memalloc_noio_flags(gfp_mask);
3260                 ac.spread_dirty_pages = false;
3261
3262                 page = __alloc_pages_slowpath(alloc_mask, order, &ac);
3263         }
3264
3265         if (kmemcheck_enabled && page)
3266                 kmemcheck_pagealloc_alloc(page, order, gfp_mask);
3267
3268         trace_mm_page_alloc(page, order, alloc_mask, ac.migratetype);
3269
3270 out:
3271         /*
3272          * When updating a task's mems_allowed, it is possible to race with
3273          * parallel threads in such a way that an allocation can fail while
3274          * the mask is being updated. If a page allocation is about to fail,
3275          * check if the cpuset changed during allocation and if so, retry.
3276          */
3277         if (unlikely(!page && read_mems_allowed_retry(cpuset_mems_cookie)))
3278                 goto retry_cpuset;
3279
3280         return page;
3281 }
3282 EXPORT_SYMBOL(__alloc_pages_nodemask);
3283
3284 /*
3285  * Common helper functions.
3286  */
3287 unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order)
3288 {
3289         struct page *page;
3290
3291         /*
3292          * __get_free_pages() returns a 32-bit address, which cannot represent
3293          * a highmem page
3294          */
3295         VM_BUG_ON((gfp_mask & __GFP_HIGHMEM) != 0);
3296
3297         page = alloc_pages(gfp_mask, order);
3298         if (!page)
3299                 return 0;
3300         return (unsigned long) page_address(page);
3301 }
3302 EXPORT_SYMBOL(__get_free_pages);
3303
3304 unsigned long get_zeroed_page(gfp_t gfp_mask)
3305 {
3306         return __get_free_pages(gfp_mask | __GFP_ZERO, 0);
3307 }
3308 EXPORT_SYMBOL(get_zeroed_page);
3309
3310 void __free_pages(struct page *page, unsigned int order)
3311 {
3312         if (put_page_testzero(page)) {
3313                 if (order == 0)
3314                         free_hot_cold_page(page, false);
3315                 else
3316                         __free_pages_ok(page, order);
3317         }
3318 }
3319
3320 EXPORT_SYMBOL(__free_pages);
3321
3322 void free_pages(unsigned long addr, unsigned int order)
3323 {
3324         if (addr != 0) {
3325                 VM_BUG_ON(!virt_addr_valid((void *)addr));
3326                 __free_pages(virt_to_page((void *)addr), order);
3327         }
3328 }
3329
3330 EXPORT_SYMBOL(free_pages);
3331
3332 /*
3333  * Page Fragment:
3334  *  An arbitrary-length arbitrary-offset area of memory which resides
3335  *  within a 0 or higher order page.  Multiple fragments within that page
3336  *  are individually refcounted, in the page's reference counter.
3337  *
3338  * The page_frag functions below provide a simple allocation framework for
3339  * page fragments.  This is used by the network stack and network device
3340  * drivers to provide a backing region of memory for use as either an
3341  * sk_buff->head, or to be used in the "frags" portion of skb_shared_info.
3342  */
3343 static struct page *__page_frag_refill(struct page_frag_cache *nc,
3344                                        gfp_t gfp_mask)
3345 {
3346         struct page *page = NULL;
3347         gfp_t gfp = gfp_mask;
3348
3349 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
3350         gfp_mask |= __GFP_COMP | __GFP_NOWARN | __GFP_NORETRY |
3351                     __GFP_NOMEMALLOC;
3352         page = alloc_pages_node(NUMA_NO_NODE, gfp_mask,
3353                                 PAGE_FRAG_CACHE_MAX_ORDER);
3354         nc->size = page ? PAGE_FRAG_CACHE_MAX_SIZE : PAGE_SIZE;
3355 #endif
3356         if (unlikely(!page))
3357                 page = alloc_pages_node(NUMA_NO_NODE, gfp, 0);
3358
3359         nc->va = page ? page_address(page) : NULL;
3360
3361         return page;
3362 }
3363
3364 void *__alloc_page_frag(struct page_frag_cache *nc,
3365                         unsigned int fragsz, gfp_t gfp_mask)
3366 {
3367         unsigned int size = PAGE_SIZE;
3368         struct page *page;
3369         int offset;
3370
3371         if (unlikely(!nc->va)) {
3372 refill:
3373                 page = __page_frag_refill(nc, gfp_mask);
3374                 if (!page)
3375                         return NULL;
3376
3377 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
3378                 /* if size can vary use size else just use PAGE_SIZE */
3379                 size = nc->size;
3380 #endif
3381                 /* Even if we own the page, we do not use atomic_set().
3382                  * This would break get_page_unless_zero() users.
3383                  */
3384                 atomic_add(size - 1, &page->_count);
3385
3386                 /* reset page count bias and offset to start of new frag */
3387                 nc->pfmemalloc = page_is_pfmemalloc(page);
3388                 nc->pagecnt_bias = size;
3389                 nc->offset = size;
3390         }
3391
3392         offset = nc->offset - fragsz;
3393         if (unlikely(offset < 0)) {
3394                 page = virt_to_page(nc->va);
3395
3396                 if (!atomic_sub_and_test(nc->pagecnt_bias, &page->_count))
3397                         goto refill;
3398
3399 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
3400                 /* if size can vary use size else just use PAGE_SIZE */
3401                 size = nc->size;
3402 #endif
3403                 /* OK, page count is 0, we can safely set it */
3404                 atomic_set(&page->_count, size);
3405
3406                 /* reset page count bias and offset to start of new frag */
3407                 nc->pagecnt_bias = size;
3408                 offset = size - fragsz;
3409         }
3410
3411         nc->pagecnt_bias--;
3412         nc->offset = offset;
3413
3414         return nc->va + offset;
3415 }
3416 EXPORT_SYMBOL(__alloc_page_frag);
3417
3418 /*
3419  * Frees a page fragment allocated out of either a compound or order 0 page.
3420  */
3421 void __free_page_frag(void *addr)
3422 {
3423         struct page *page = virt_to_head_page(addr);
3424
3425         if (unlikely(put_page_testzero(page)))
3426                 __free_pages_ok(page, compound_order(page));
3427 }
3428 EXPORT_SYMBOL(__free_page_frag);
3429
3430 /*
3431  * alloc_kmem_pages charges newly allocated pages to the kmem resource counter
3432  * of the current memory cgroup.
3433  *
3434  * It should be used when the caller would like to use kmalloc, but since the
3435  * allocation is large, it has to fall back to the page allocator.
3436  */
3437 struct page *alloc_kmem_pages(gfp_t gfp_mask, unsigned int order)
3438 {
3439         struct page *page;
3440
3441         page = alloc_pages(gfp_mask, order);
3442         if (page && memcg_kmem_charge(page, gfp_mask, order) != 0) {
3443                 __free_pages(page, order);
3444                 page = NULL;
3445         }
3446         return page;
3447 }
3448
3449 struct page *alloc_kmem_pages_node(int nid, gfp_t gfp_mask, unsigned int order)
3450 {
3451         struct page *page;
3452
3453         page = alloc_pages_node(nid, gfp_mask, order);
3454         if (page && memcg_kmem_charge(page, gfp_mask, order) != 0) {
3455                 __free_pages(page, order);
3456                 page = NULL;
3457         }
3458         return page;
3459 }
3460
3461 /*
3462  * __free_kmem_pages and free_kmem_pages will free pages allocated with
3463  * alloc_kmem_pages.
3464  */
3465 void __free_kmem_pages(struct page *page, unsigned int order)
3466 {
3467         memcg_kmem_uncharge(page, order);
3468         __free_pages(page, order);
3469 }
3470
3471 void free_kmem_pages(unsigned long addr, unsigned int order)
3472 {
3473         if (addr != 0) {
3474                 VM_BUG_ON(!virt_addr_valid((void *)addr));
3475                 __free_kmem_pages(virt_to_page((void *)addr), order);
3476         }
3477 }
3478
3479 static void *make_alloc_exact(unsigned long addr, unsigned int order,
3480                 size_t size)
3481 {
3482         if (addr) {
3483                 unsigned long alloc_end = addr + (PAGE_SIZE << order);
3484                 unsigned long used = addr + PAGE_ALIGN(size);
3485
3486                 split_page(virt_to_page((void *)addr), order);
3487                 while (used < alloc_end) {
3488                         free_page(used);
3489                         used += PAGE_SIZE;
3490                 }
3491         }
3492         return (void *)addr;
3493 }
3494
3495 /**
3496  * alloc_pages_exact - allocate an exact number physically-contiguous pages.
3497  * @size: the number of bytes to allocate
3498  * @gfp_mask: GFP flags for the allocation
3499  *
3500  * This function is similar to alloc_pages(), except that it allocates the
3501  * minimum number of pages to satisfy the request.  alloc_pages() can only
3502  * allocate memory in power-of-two pages.
3503  *
3504  * This function is also limited by MAX_ORDER.
3505  *
3506  * Memory allocated by this function must be released by free_pages_exact().
3507  */
3508 void *alloc_pages_exact(size_t size, gfp_t gfp_mask)
3509 {
3510         unsigned int order = get_order(size);
3511         unsigned long addr;
3512
3513         addr = __get_free_pages(gfp_mask, order);
3514         return make_alloc_exact(addr, order, size);
3515 }
3516 EXPORT_SYMBOL(alloc_pages_exact);
3517
3518 /**
3519  * alloc_pages_exact_nid - allocate an exact number of physically-contiguous
3520  *                         pages on a node.
3521  * @nid: the preferred node ID where memory should be allocated
3522  * @size: the number of bytes to allocate
3523  * @gfp_mask: GFP flags for the allocation
3524  *
3525  * Like alloc_pages_exact(), but try to allocate on node nid first before falling
3526  * back.
3527  */
3528 void * __meminit alloc_pages_exact_nid(int nid, size_t size, gfp_t gfp_mask)
3529 {
3530         unsigned int order = get_order(size);
3531         struct page *p = alloc_pages_node(nid, gfp_mask, order);
3532         if (!p)
3533                 return NULL;
3534         return make_alloc_exact((unsigned long)page_address(p), order, size);
3535 }
3536
3537 /**
3538  * free_pages_exact - release memory allocated via alloc_pages_exact()
3539  * @virt: the value returned by alloc_pages_exact.
3540  * @size: size of allocation, same value as passed to alloc_pages_exact().
3541  *
3542  * Release the memory allocated by a previous call to alloc_pages_exact.
3543  */
3544 void free_pages_exact(void *virt, size_t size)
3545 {
3546         unsigned long addr = (unsigned long)virt;
3547         unsigned long end = addr + PAGE_ALIGN(size);
3548
3549         while (addr < end) {
3550                 free_page(addr);
3551                 addr += PAGE_SIZE;
3552         }
3553 }
3554 EXPORT_SYMBOL(free_pages_exact);
3555
3556 /**
3557  * nr_free_zone_pages - count number of pages beyond high watermark
3558  * @offset: The zone index of the highest zone
3559  *
3560  * nr_free_zone_pages() counts the number of counts pages which are beyond the
3561  * high watermark within all zones at or below a given zone index.  For each
3562  * zone, the number of pages is calculated as:
3563  *     managed_pages - high_pages
3564  */
3565 static unsigned long nr_free_zone_pages(int offset)
3566 {
3567         struct zoneref *z;
3568         struct zone *zone;
3569
3570         /* Just pick one node, since fallback list is circular */
3571         unsigned long sum = 0;
3572
3573         struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL);
3574
3575         for_each_zone_zonelist(zone, z, zonelist, offset) {
3576                 unsigned long size = zone->managed_pages;
3577                 unsigned long high = high_wmark_pages(zone);
3578                 if (size > high)
3579                         sum += size - high;
3580         }
3581
3582         return sum;
3583 }
3584
3585 /**
3586  * nr_free_buffer_pages - count number of pages beyond high watermark
3587  *
3588  * nr_free_buffer_pages() counts the number of pages which are beyond the high
3589  * watermark within ZONE_DMA and ZONE_NORMAL.
3590  */
3591 unsigned long nr_free_buffer_pages(void)
3592 {
3593         return nr_free_zone_pages(gfp_zone(GFP_USER));
3594 }
3595 EXPORT_SYMBOL_GPL(nr_free_buffer_pages);
3596
3597 /**
3598  * nr_free_pagecache_pages - count number of pages beyond high watermark
3599  *
3600  * nr_free_pagecache_pages() counts the number of pages which are beyond the
3601  * high watermark within all zones.
3602  */
3603 unsigned long nr_free_pagecache_pages(void)
3604 {
3605         return nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE));
3606 }
3607
3608 static inline void show_node(struct zone *zone)
3609 {
3610         if (IS_ENABLED(CONFIG_NUMA))
3611                 printk("Node %d ", zone_to_nid(zone));
3612 }
3613
3614 void si_meminfo(struct sysinfo *val)
3615 {
3616         val->totalram = totalram_pages;
3617         val->sharedram = global_page_state(NR_SHMEM);
3618         val->freeram = global_page_state(NR_FREE_PAGES);
3619         val->bufferram = nr_blockdev_pages();
3620         val->totalhigh = totalhigh_pages;
3621         val->freehigh = nr_free_highpages();
3622         val->mem_unit = PAGE_SIZE;
3623 }
3624
3625 EXPORT_SYMBOL(si_meminfo);
3626
3627 #ifdef CONFIG_NUMA
3628 void si_meminfo_node(struct sysinfo *val, int nid)
3629 {
3630         int zone_type;          /* needs to be signed */
3631         unsigned long managed_pages = 0;
3632         pg_data_t *pgdat = NODE_DATA(nid);
3633
3634         for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++)
3635                 managed_pages += pgdat->node_zones[zone_type].managed_pages;
3636         val->totalram = managed_pages;
3637         val->sharedram = node_page_state(nid, NR_SHMEM);
3638         val->freeram = node_page_state(nid, NR_FREE_PAGES);
3639 #ifdef CONFIG_HIGHMEM
3640         val->totalhigh = pgdat->node_zones[ZONE_HIGHMEM].managed_pages;
3641         val->freehigh = zone_page_state(&pgdat->node_zones[ZONE_HIGHMEM],
3642                         NR_FREE_PAGES);
3643 #else
3644         val->totalhigh = 0;
3645         val->freehigh = 0;
3646 #endif
3647         val->mem_unit = PAGE_SIZE;
3648 }
3649 #endif
3650
3651 /*
3652  * Determine whether the node should be displayed or not, depending on whether
3653  * SHOW_MEM_FILTER_NODES was passed to show_free_areas().
3654  */
3655 bool skip_free_areas_node(unsigned int flags, int nid)
3656 {
3657         bool ret = false;
3658         unsigned int cpuset_mems_cookie;
3659
3660         if (!(flags & SHOW_MEM_FILTER_NODES))
3661                 goto out;
3662
3663         do {
3664                 cpuset_mems_cookie = read_mems_allowed_begin();
3665                 ret = !node_isset(nid, cpuset_current_mems_allowed);
3666         } while (read_mems_allowed_retry(cpuset_mems_cookie));
3667 out:
3668         return ret;
3669 }
3670
3671 #define K(x) ((x) << (PAGE_SHIFT-10))
3672
3673 static void show_migration_types(unsigned char type)
3674 {
3675         static const char types[MIGRATE_TYPES] = {
3676                 [MIGRATE_UNMOVABLE]     = 'U',
3677                 [MIGRATE_MOVABLE]       = 'M',
3678                 [MIGRATE_RECLAIMABLE]   = 'E',
3679                 [MIGRATE_HIGHATOMIC]    = 'H',
3680 #ifdef CONFIG_CMA
3681                 [MIGRATE_CMA]           = 'C',
3682 #endif
3683 #ifdef CONFIG_MEMORY_ISOLATION
3684                 [MIGRATE_ISOLATE]       = 'I',
3685 #endif
3686         };
3687         char tmp[MIGRATE_TYPES + 1];
3688         char *p = tmp;
3689         int i;
3690
3691         for (i = 0; i < MIGRATE_TYPES; i++) {
3692                 if (type & (1 << i))
3693                         *p++ = types[i];
3694         }
3695
3696         *p = '\0';
3697         printk("(%s) ", tmp);
3698 }
3699
3700 /*
3701  * Show free area list (used inside shift_scroll-lock stuff)
3702  * We also calculate the percentage fragmentation. We do this by counting the
3703  * memory on each free list with the exception of the first item on the list.
3704  *
3705  * Bits in @filter:
3706  * SHOW_MEM_FILTER_NODES: suppress nodes that are not allowed by current's
3707  *   cpuset.
3708  */
3709 void show_free_areas(unsigned int filter)
3710 {
3711         unsigned long free_pcp = 0;
3712         int cpu;
3713         struct zone *zone;
3714
3715         for_each_populated_zone(zone) {
3716                 if (skip_free_areas_node(filter, zone_to_nid(zone)))
3717                         continue;
3718
3719                 for_each_online_cpu(cpu)
3720                         free_pcp += per_cpu_ptr(zone->pageset, cpu)->pcp.count;
3721         }
3722
3723         printk("active_anon:%lu inactive_anon:%lu isolated_anon:%lu\n"
3724                 " active_file:%lu inactive_file:%lu isolated_file:%lu\n"
3725                 " unevictable:%lu dirty:%lu writeback:%lu unstable:%lu\n"
3726                 " slab_reclaimable:%lu slab_unreclaimable:%lu\n"
3727                 " mapped:%lu shmem:%lu pagetables:%lu bounce:%lu\n"
3728                 " free:%lu free_pcp:%lu free_cma:%lu\n",
3729                 global_page_state(NR_ACTIVE_ANON),
3730                 global_page_state(NR_INACTIVE_ANON),
3731                 global_page_state(NR_ISOLATED_ANON),
3732                 global_page_state(NR_ACTIVE_FILE),
3733                 global_page_state(NR_INACTIVE_FILE),
3734                 global_page_state(NR_ISOLATED_FILE),
3735                 global_page_state(NR_UNEVICTABLE),
3736                 global_page_state(NR_FILE_DIRTY),
3737                 global_page_state(NR_WRITEBACK),
3738                 global_page_state(NR_UNSTABLE_NFS),
3739                 global_page_state(NR_SLAB_RECLAIMABLE),
3740                 global_page_state(NR_SLAB_UNRECLAIMABLE),
3741                 global_page_state(NR_FILE_MAPPED),
3742                 global_page_state(NR_SHMEM),
3743                 global_page_state(NR_PAGETABLE),
3744                 global_page_state(NR_BOUNCE),
3745                 global_page_state(NR_FREE_PAGES),
3746                 free_pcp,
3747                 global_page_state(NR_FREE_CMA_PAGES));
3748
3749         for_each_populated_zone(zone) {
3750                 int i;
3751
3752                 if (skip_free_areas_node(filter, zone_to_nid(zone)))
3753                         continue;
3754
3755                 free_pcp = 0;
3756                 for_each_online_cpu(cpu)
3757                         free_pcp += per_cpu_ptr(zone->pageset, cpu)->pcp.count;
3758
3759                 show_node(zone);
3760                 printk("%s"
3761                         " free:%lukB"
3762                         " min:%lukB"
3763                         " low:%lukB"
3764                         " high:%lukB"
3765                         " active_anon:%lukB"
3766                         " inactive_anon:%lukB"
3767                         " active_file:%lukB"
3768                         " inactive_file:%lukB"
3769                         " unevictable:%lukB"
3770                         " isolated(anon):%lukB"
3771                         " isolated(file):%lukB"
3772                         " present:%lukB"
3773                         " managed:%lukB"
3774                         " mlocked:%lukB"
3775                         " dirty:%lukB"
3776                         " writeback:%lukB"
3777                         " mapped:%lukB"
3778                         " shmem:%lukB"
3779                         " slab_reclaimable:%lukB"
3780                         " slab_unreclaimable:%lukB"
3781                         " kernel_stack:%lukB"
3782                         " pagetables:%lukB"
3783                         " unstable:%lukB"
3784                         " bounce:%lukB"
3785                         " free_pcp:%lukB"
3786                         " local_pcp:%ukB"
3787                         " free_cma:%lukB"
3788                         " writeback_tmp:%lukB"
3789                         " pages_scanned:%lu"
3790                         " all_unreclaimable? %s"
3791                         "\n",
3792                         zone->name,
3793                         K(zone_page_state(zone, NR_FREE_PAGES)),
3794                         K(min_wmark_pages(zone)),
3795                         K(low_wmark_pages(zone)),
3796                         K(high_wmark_pages(zone)),
3797                         K(zone_page_state(zone, NR_ACTIVE_ANON)),
3798                         K(zone_page_state(zone, NR_INACTIVE_ANON)),
3799                         K(zone_page_state(zone, NR_ACTIVE_FILE)),
3800                         K(zone_page_state(zone, NR_INACTIVE_FILE)),
3801                         K(zone_page_state(zone, NR_UNEVICTABLE)),
3802                         K(zone_page_state(zone, NR_ISOLATED_ANON)),
3803                         K(zone_page_state(zone, NR_ISOLATED_FILE)),
3804                         K(zone->present_pages),
3805                         K(zone->managed_pages),
3806                         K(zone_page_state(zone, NR_MLOCK)),
3807                         K(zone_page_state(zone, NR_FILE_DIRTY)),
3808                         K(zone_page_state(zone, NR_WRITEBACK)),
3809                         K(zone_page_state(zone, NR_FILE_MAPPED)),
3810                         K(zone_page_state(zone, NR_SHMEM)),
3811                         K(zone_page_state(zone, NR_SLAB_RECLAIMABLE)),
3812                         K(zone_page_state(zone, NR_SLAB_UNRECLAIMABLE)),
3813                         zone_page_state(zone, NR_KERNEL_STACK) *
3814                                 THREAD_SIZE / 1024,
3815                         K(zone_page_state(zone, NR_PAGETABLE)),
3816                         K(zone_page_state(zone, NR_UNSTABLE_NFS)),
3817                         K(zone_page_state(zone, NR_BOUNCE)),
3818                         K(free_pcp),
3819                         K(this_cpu_read(zone->pageset->pcp.count)),
3820                         K(zone_page_state(zone, NR_FREE_CMA_PAGES)),
3821                         K(zone_page_state(zone, NR_WRITEBACK_TEMP)),
3822                         K(zone_page_state(zone, NR_PAGES_SCANNED)),
3823                         (!zone_reclaimable(zone) ? "yes" : "no")
3824                         );
3825                 printk("lowmem_reserve[]:");
3826                 for (i = 0; i < MAX_NR_ZONES; i++)
3827                         printk(" %ld", zone->lowmem_reserve[i]);
3828                 printk("\n");
3829         }
3830
3831         for_each_populated_zone(zone) {
3832                 unsigned int order;
3833                 unsigned long nr[MAX_ORDER], flags, total = 0;
3834                 unsigned char types[MAX_ORDER];
3835
3836                 if (skip_free_areas_node(filter, zone_to_nid(zone)))
3837                         continue;
3838                 show_node(zone);
3839                 printk("%s: ", zone->name);
3840
3841                 spin_lock_irqsave(&zone->lock, flags);
3842                 for (order = 0; order < MAX_ORDER; order++) {
3843                         struct free_area *area = &zone->free_area[order];
3844                         int type;
3845
3846                         nr[order] = area->nr_free;
3847                         total += nr[order] << order;
3848
3849                         types[order] = 0;
3850                         for (type = 0; type < MIGRATE_TYPES; type++) {
3851                                 if (!list_empty(&area->free_list[type]))
3852                                         types[order] |= 1 << type;
3853                         }
3854                 }
3855                 spin_unlock_irqrestore(&zone->lock, flags);
3856                 for (order = 0; order < MAX_ORDER; order++) {
3857                         printk("%lu*%lukB ", nr[order], K(1UL) << order);
3858                         if (nr[order])
3859                                 show_migration_types(types[order]);
3860                 }
3861                 printk("= %lukB\n", K(total));
3862         }
3863
3864         hugetlb_show_meminfo();
3865
3866         printk("%ld total pagecache pages\n", global_page_state(NR_FILE_PAGES));
3867
3868         show_swap_cache_info();
3869 }
3870
3871 static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref)
3872 {
3873         zoneref->zone = zone;
3874         zoneref->zone_idx = zone_idx(zone);
3875 }
3876
3877 /*
3878  * Builds allocation fallback zone lists.
3879  *
3880  * Add all populated zones of a node to the zonelist.
3881  */
3882 static int build_zonelists_node(pg_data_t *pgdat, struct zonelist *zonelist,
3883                                 int nr_zones)
3884 {
3885         struct zone *zone;
3886         enum zone_type zone_type = MAX_NR_ZONES;
3887
3888         do {
3889                 zone_type--;
3890                 zone = pgdat->node_zones + zone_type;
3891                 if (populated_zone(zone)) {
3892                         zoneref_set_zone(zone,
3893                                 &zonelist->_zonerefs[nr_zones++]);
3894                         check_highest_zone(zone_type);
3895                 }
3896         } while (zone_type);
3897
3898         return nr_zones;
3899 }
3900
3901
3902 /*
3903  *  zonelist_order:
3904  *  0 = automatic detection of better ordering.
3905  *  1 = order by ([node] distance, -zonetype)
3906  *  2 = order by (-zonetype, [node] distance)
3907  *
3908  *  If not NUMA, ZONELIST_ORDER_ZONE and ZONELIST_ORDER_NODE will create
3909  *  the same zonelist. So only NUMA can configure this param.
3910  */
3911 #define ZONELIST_ORDER_DEFAULT  0
3912 #define ZONELIST_ORDER_NODE     1
3913 #define ZONELIST_ORDER_ZONE     2
3914
3915 /* zonelist order in the kernel.
3916  * set_zonelist_order() will set this to NODE or ZONE.
3917  */
3918 static int current_zonelist_order = ZONELIST_ORDER_DEFAULT;
3919 static char zonelist_order_name[3][8] = {"Default", "Node", "Zone"};
3920
3921
3922 #ifdef CONFIG_NUMA
3923 /* The value user specified ....changed by config */
3924 static int user_zonelist_order = ZONELIST_ORDER_DEFAULT;
3925 /* string for sysctl */
3926 #define NUMA_ZONELIST_ORDER_LEN 16
3927 char numa_zonelist_order[16] = "default";
3928
3929 /*
3930  * interface for configure zonelist ordering.
3931  * command line option "numa_zonelist_order"
3932  *      = "[dD]efault   - default, automatic configuration.
3933  *      = "[nN]ode      - order by node locality, then by zone within node
3934  *      = "[zZ]one      - order by zone, then by locality within zone
3935  */
3936
3937 static int __parse_numa_zonelist_order(char *s)
3938 {
3939         if (*s == 'd' || *s == 'D') {
3940                 user_zonelist_order = ZONELIST_ORDER_DEFAULT;
3941         } else if (*s == 'n' || *s == 'N') {
3942                 user_zonelist_order = ZONELIST_ORDER_NODE;
3943         } else if (*s == 'z' || *s == 'Z') {
3944                 user_zonelist_order = ZONELIST_ORDER_ZONE;
3945         } else {
3946                 printk(KERN_WARNING
3947                         "Ignoring invalid numa_zonelist_order value:  "
3948                         "%s\n", s);
3949                 return -EINVAL;
3950         }
3951         return 0;
3952 }
3953
3954 static __init int setup_numa_zonelist_order(char *s)
3955 {
3956         int ret;
3957
3958         if (!s)
3959                 return 0;
3960
3961         ret = __parse_numa_zonelist_order(s);
3962         if (ret == 0)
3963                 strlcpy(numa_zonelist_order, s, NUMA_ZONELIST_ORDER_LEN);
3964
3965         return ret;
3966 }
3967 early_param("numa_zonelist_order", setup_numa_zonelist_order);
3968
3969 /*
3970  * sysctl handler for numa_zonelist_order
3971  */
3972 int numa_zonelist_order_handler(struct ctl_table *table, int write,
3973                 void __user *buffer, size_t *length,
3974                 loff_t *ppos)
3975 {
3976         char saved_string[NUMA_ZONELIST_ORDER_LEN];
3977         int ret;
3978         static DEFINE_MUTEX(zl_order_mutex);
3979
3980         mutex_lock(&zl_order_mutex);
3981         if (write) {
3982                 if (strlen((char *)table->data) >= NUMA_ZONELIST_ORDER_LEN) {
3983                         ret = -EINVAL;
3984                         goto out;
3985                 }
3986                 strcpy(saved_string, (char *)table->data);
3987         }
3988         ret = proc_dostring(table, write, buffer, length, ppos);
3989         if (ret)
3990                 goto out;
3991         if (write) {
3992                 int oldval = user_zonelist_order;
3993
3994                 ret = __parse_numa_zonelist_order((char *)table->data);
3995                 if (ret) {
3996                         /*
3997                          * bogus value.  restore saved string
3998                          */
3999                         strncpy((char *)table->data, saved_string,
4000                                 NUMA_ZONELIST_ORDER_LEN);
4001                         user_zonelist_order = oldval;
4002                 } else if (oldval != user_zonelist_order) {
4003                         mutex_lock(&zonelists_mutex);
4004                         build_all_zonelists(NULL, NULL);
4005                         mutex_unlock(&zonelists_mutex);
4006                 }
4007         }
4008 out:
4009         mutex_unlock(&zl_order_mutex);
4010         return ret;
4011 }
4012
4013
4014 #define MAX_NODE_LOAD (nr_online_nodes)
4015 static int node_load[MAX_NUMNODES];
4016
4017 /**
4018  * find_next_best_node - find the next node that should appear in a given node's fallback list
4019  * @node: node whose fallback list we're appending
4020  * @used_node_mask: nodemask_t of already used nodes
4021  *
4022  * We use a number of factors to determine which is the next node that should
4023  * appear on a given node's fallback list.  The node should not have appeared
4024  * already in @node's fallback list, and it should be the next closest node
4025  * according to the distance array (which contains arbitrary distance values
4026  * from each node to each node in the system), and should also prefer nodes
4027  * with no CPUs, since presumably they'll have very little allocation pressure
4028  * on them otherwise.
4029  * It returns -1 if no node is found.
4030  */
4031 static int find_next_best_node(int node, nodemask_t *used_node_mask)
4032 {
4033         int n, val;
4034         int min_val = INT_MAX;
4035         int best_node = NUMA_NO_NODE;
4036         const struct cpumask *tmp = cpumask_of_node(0);
4037
4038         /* Use the local node if we haven't already */
4039         if (!node_isset(node, *used_node_mask)) {
4040                 node_set(node, *used_node_mask);
4041                 return node;
4042         }
4043
4044         for_each_node_state(n, N_MEMORY) {
4045
4046                 /* Don't want a node to appear more than once */
4047                 if (node_isset(n, *used_node_mask))
4048                         continue;
4049
4050                 /* Use the distance array to find the distance */
4051                 val = node_distance(node, n);
4052
4053                 /* Penalize nodes under us ("prefer the next node") */
4054                 val += (n < node);
4055
4056                 /* Give preference to headless and unused nodes */
4057                 tmp = cpumask_of_node(n);
4058                 if (!cpumask_empty(tmp))
4059                         val += PENALTY_FOR_NODE_WITH_CPUS;
4060
4061                 /* Slight preference for less loaded node */
4062                 val *= (MAX_NODE_LOAD*MAX_NUMNODES);
4063                 val += node_load[n];
4064
4065                 if (val < min_val) {
4066                         min_val = val;
4067                         best_node = n;
4068                 }
4069         }
4070
4071         if (best_node >= 0)
4072                 node_set(best_node, *used_node_mask);
4073
4074         return best_node;
4075 }
4076
4077
4078 /*
4079  * Build zonelists ordered by node and zones within node.
4080  * This results in maximum locality--normal zone overflows into local
4081  * DMA zone, if any--but risks exhausting DMA zone.
4082  */
4083 static void build_zonelists_in_node_order(pg_data_t *pgdat, int node)
4084 {
4085         int j;
4086         struct zonelist *zonelist;
4087
4088         zonelist = &pgdat->node_zonelists[0];
4089         for (j = 0; zonelist->_zonerefs[j].zone != NULL; j++)
4090                 ;
4091         j = build_zonelists_node(NODE_DATA(node), zonelist, j);
4092         zonelist->_zonerefs[j].zone = NULL;
4093         zonelist->_zonerefs[j].zone_idx = 0;
4094 }
4095
4096 /*
4097  * Build gfp_thisnode zonelists
4098  */
4099 static void build_thisnode_zonelists(pg_data_t *pgdat)
4100 {
4101         int j;
4102         struct zonelist *zonelist;
4103
4104         zonelist = &pgdat->node_zonelists[1];
4105         j = build_zonelists_node(pgdat, zonelist, 0);
4106         zonelist->_zonerefs[j].zone = NULL;
4107         zonelist->_zonerefs[j].zone_idx = 0;
4108 }
4109
4110 /*
4111  * Build zonelists ordered by zone and nodes within zones.
4112  * This results in conserving DMA zone[s] until all Normal memory is
4113  * exhausted, but results in overflowing to remote node while memory
4114  * may still exist in local DMA zone.
4115  */
4116 static int node_order[MAX_NUMNODES];
4117
4118 static void build_zonelists_in_zone_order(pg_data_t *pgdat, int nr_nodes)
4119 {
4120         int pos, j, node;
4121         int zone_type;          /* needs to be signed */
4122         struct zone *z;
4123         struct zonelist *zonelist;
4124
4125         zonelist = &pgdat->node_zonelists[0];
4126         pos = 0;
4127         for (zone_type = MAX_NR_ZONES - 1; zone_type >= 0; zone_type--) {
4128                 for (j = 0; j < nr_nodes; j++) {
4129                         node = node_order[j];
4130                         z = &NODE_DATA(node)->node_zones[zone_type];
4131                         if (populated_zone(z)) {
4132                                 zoneref_set_zone(z,
4133                                         &zonelist->_zonerefs[pos++]);
4134                                 check_highest_zone(zone_type);
4135                         }
4136                 }
4137         }
4138         zonelist->_zonerefs[pos].zone = NULL;
4139         zonelist->_zonerefs[pos].zone_idx = 0;
4140 }
4141
4142 #if defined(CONFIG_64BIT)
4143 /*
4144  * Devices that require DMA32/DMA are relatively rare and do not justify a
4145  * penalty to every machine in case the specialised case applies. Default
4146  * to Node-ordering on 64-bit NUMA machines
4147  */
4148 static int default_zonelist_order(void)
4149 {
4150         return ZONELIST_ORDER_NODE;
4151 }
4152 #else
4153 /*
4154  * On 32-bit, the Normal zone needs to be preserved for allocations accessible
4155  * by the kernel. If processes running on node 0 deplete the low memory zone
4156  * then reclaim will occur more frequency increasing stalls and potentially
4157  * be easier to OOM if a large percentage of the zone is under writeback or
4158  * dirty. The problem is significantly worse if CONFIG_HIGHPTE is not set.
4159  * Hence, default to zone ordering on 32-bit.
4160  */
4161 static int default_zonelist_order(void)
4162 {
4163         return ZONELIST_ORDER_ZONE;
4164 }
4165 #endif /* CONFIG_64BIT */
4166
4167 static void set_zonelist_order(void)
4168 {
4169         if (user_zonelist_order == ZONELIST_ORDER_DEFAULT)
4170                 current_zonelist_order = default_zonelist_order();
4171         else
4172                 current_zonelist_order = user_zonelist_order;
4173 }
4174
4175 static void build_zonelists(pg_data_t *pgdat)
4176 {
4177         int j, node, load;
4178         enum zone_type i;
4179         nodemask_t used_mask;
4180         int local_node, prev_node;
4181         struct zonelist *zonelist;
4182         unsigned int order = current_zonelist_order;
4183
4184         /* initialize zonelists */
4185         for (i = 0; i < MAX_ZONELISTS; i++) {
4186                 zonelist = pgdat->node_zonelists + i;
4187                 zonelist->_zonerefs[0].zone = NULL;
4188                 zonelist->_zonerefs[0].zone_idx = 0;
4189         }
4190
4191         /* NUMA-aware ordering of nodes */
4192         local_node = pgdat->node_id;
4193         load = nr_online_nodes;
4194         prev_node = local_node;
4195         nodes_clear(used_mask);
4196
4197         memset(node_order, 0, sizeof(node_order));
4198         j = 0;
4199
4200         while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
4201                 /*
4202                  * We don't want to pressure a particular node.
4203                  * So adding penalty to the first node in same
4204                  * distance group to make it round-robin.
4205                  */
4206                 if (node_distance(local_node, node) !=
4207                     node_distance(local_node, prev_node))
4208                         node_load[node] = load;
4209
4210                 prev_node = node;
4211                 load--;
4212                 if (order == ZONELIST_ORDER_NODE)
4213                         build_zonelists_in_node_order(pgdat, node);
4214                 else
4215                         node_order[j++] = node; /* remember order */
4216         }
4217
4218         if (order == ZONELIST_ORDER_ZONE) {
4219                 /* calculate node order -- i.e., DMA last! */
4220                 build_zonelists_in_zone_order(pgdat, j);
4221         }
4222
4223         build_thisnode_zonelists(pgdat);
4224 }
4225
4226 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
4227 /*
4228  * Return node id of node used for "local" allocations.
4229  * I.e., first node id of first zone in arg node's generic zonelist.
4230  * Used for initializing percpu 'numa_mem', which is used primarily
4231  * for kernel allocations, so use GFP_KERNEL flags to locate zonelist.
4232  */
4233 int local_memory_node(int node)
4234 {
4235         struct zone *zone;
4236
4237         (void)first_zones_zonelist(node_zonelist(node, GFP_KERNEL),
4238                                    gfp_zone(GFP_KERNEL),
4239                                    NULL,
4240                                    &zone);
4241         return zone->node;
4242 }
4243 #endif
4244
4245 #else   /* CONFIG_NUMA */
4246
4247 static void set_zonelist_order(void)
4248 {
4249         current_zonelist_order = ZONELIST_ORDER_ZONE;
4250 }
4251
4252 static void build_zonelists(pg_data_t *pgdat)
4253 {
4254         int node, local_node;
4255         enum zone_type j;
4256         struct zonelist *zonelist;
4257
4258         local_node = pgdat->node_id;
4259
4260         zonelist = &pgdat->node_zonelists[0];
4261         j = build_zonelists_node(pgdat, zonelist, 0);
4262
4263         /*
4264          * Now we build the zonelist so that it contains the zones
4265          * of all the other nodes.
4266          * We don't want to pressure a particular node, so when
4267          * building the zones for node N, we make sure that the
4268          * zones coming right after the local ones are those from
4269          * node N+1 (modulo N)
4270          */
4271         for (node = local_node + 1; node < MAX_NUMNODES; node++) {
4272                 if (!node_online(node))
4273                         continue;
4274                 j = build_zonelists_node(NODE_DATA(node), zonelist, j);
4275         }
4276         for (node = 0; node < local_node; node++) {
4277                 if (!node_online(node))
4278                         continue;
4279                 j = build_zonelists_node(NODE_DATA(node), zonelist, j);
4280         }
4281
4282         zonelist->_zonerefs[j].zone = NULL;
4283         zonelist->_zonerefs[j].zone_idx = 0;
4284 }
4285
4286 #endif  /* CONFIG_NUMA */
4287
4288 /*
4289  * Boot pageset table. One per cpu which is going to be used for all
4290  * zones and all nodes. The parameters will be set in such a way
4291  * that an item put on a list will immediately be handed over to
4292  * the buddy list. This is safe since pageset manipulation is done
4293  * with interrupts disabled.
4294  *
4295  * The boot_pagesets must be kept even after bootup is complete for
4296  * unused processors and/or zones. They do play a role for bootstrapping
4297  * hotplugged processors.
4298  *
4299  * zoneinfo_show() and maybe other functions do
4300  * not check if the processor is online before following the pageset pointer.
4301  * Other parts of the kernel may not check if the zone is available.
4302  */
4303 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch);
4304 static DEFINE_PER_CPU(struct per_cpu_pageset, boot_pageset);
4305 static void setup_zone_pageset(struct zone *zone);
4306
4307 /*
4308  * Global mutex to protect against size modification of zonelists
4309  * as well as to serialize pageset setup for the new populated zone.
4310  */
4311 DEFINE_MUTEX(zonelists_mutex);
4312
4313 /* return values int ....just for stop_machine() */
4314 static int __build_all_zonelists(void *data)
4315 {
4316         int nid;
4317         int cpu;
4318         pg_data_t *self = data;
4319
4320 #ifdef CONFIG_NUMA
4321         memset(node_load, 0, sizeof(node_load));
4322 #endif
4323
4324         if (self && !node_online(self->node_id)) {
4325                 build_zonelists(self);
4326         }
4327
4328         for_each_online_node(nid) {
4329                 pg_data_t *pgdat = NODE_DATA(nid);
4330
4331                 build_zonelists(pgdat);
4332         }
4333
4334         /*
4335          * Initialize the boot_pagesets that are going to be used
4336          * for bootstrapping processors. The real pagesets for
4337          * each zone will be allocated later when the per cpu
4338          * allocator is available.
4339          *
4340          * boot_pagesets are used also for bootstrapping offline
4341          * cpus if the system is already booted because the pagesets
4342          * are needed to initialize allocators on a specific cpu too.
4343          * F.e. the percpu allocator needs the page allocator which
4344          * needs the percpu allocator in order to allocate its pagesets
4345          * (a chicken-egg dilemma).
4346          */
4347         for_each_possible_cpu(cpu) {
4348                 setup_pageset(&per_cpu(boot_pageset, cpu), 0);
4349
4350 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
4351                 /*
4352                  * We now know the "local memory node" for each node--
4353                  * i.e., the node of the first zone in the generic zonelist.
4354                  * Set up numa_mem percpu variable for on-line cpus.  During
4355                  * boot, only the boot cpu should be on-line;  we'll init the
4356                  * secondary cpus' numa_mem as they come on-line.  During
4357                  * node/memory hotplug, we'll fixup all on-line cpus.
4358                  */
4359                 if (cpu_online(cpu))
4360                         set_cpu_numa_mem(cpu, local_memory_node(cpu_to_node(cpu)));
4361 #endif
4362         }
4363
4364         return 0;
4365 }
4366
4367 static noinline void __init
4368 build_all_zonelists_init(void)
4369 {
4370         __build_all_zonelists(NULL);
4371         mminit_verify_zonelist();
4372         cpuset_init_current_mems_allowed();
4373 }
4374
4375 /*
4376  * Called with zonelists_mutex held always
4377  * unless system_state == SYSTEM_BOOTING.
4378  *
4379  * __ref due to (1) call of __meminit annotated setup_zone_pageset
4380  * [we're only called with non-NULL zone through __meminit paths] and
4381  * (2) call of __init annotated helper build_all_zonelists_init
4382  * [protected by SYSTEM_BOOTING].
4383  */
4384 void __ref build_all_zonelists(pg_data_t *pgdat, struct zone *zone)
4385 {
4386         set_zonelist_order();
4387
4388         if (system_state == SYSTEM_BOOTING) {
4389                 build_all_zonelists_init();
4390         } else {
4391 #ifdef CONFIG_MEMORY_HOTPLUG
4392                 if (zone)
4393                         setup_zone_pageset(zone);
4394 #endif
4395                 /* we have to stop all cpus to guarantee there is no user
4396                    of zonelist */
4397                 stop_machine(__build_all_zonelists, pgdat, NULL);
4398                 /* cpuset refresh routine should be here */
4399         }
4400         vm_total_pages = nr_free_pagecache_pages();
4401         /*
4402          * Disable grouping by mobility if the number of pages in the
4403          * system is too low to allow the mechanism to work. It would be
4404          * more accurate, but expensive to check per-zone. This check is
4405          * made on memory-hotadd so a system can start with mobility
4406          * disabled and enable it later
4407          */
4408         if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES))
4409                 page_group_by_mobility_disabled = 1;
4410         else
4411                 page_group_by_mobility_disabled = 0;
4412
4413         pr_info("Built %i zonelists in %s order, mobility grouping %s.  "
4414                 "Total pages: %ld\n",
4415                         nr_online_nodes,
4416                         zonelist_order_name[current_zonelist_order],
4417                         page_group_by_mobility_disabled ? "off" : "on",
4418                         vm_total_pages);
4419 #ifdef CONFIG_NUMA
4420         pr_info("Policy zone: %s\n", zone_names[policy_zone]);
4421 #endif
4422 }
4423
4424 /*
4425  * Helper functions to size the waitqueue hash table.
4426  * Essentially these want to choose hash table sizes sufficiently
4427  * large so that collisions trying to wait on pages are rare.
4428  * But in fact, the number of active page waitqueues on typical
4429  * systems is ridiculously low, less than 200. So this is even
4430  * conservative, even though it seems large.
4431  *
4432  * The constant PAGES_PER_WAITQUEUE specifies the ratio of pages to
4433  * waitqueues, i.e. the size of the waitq table given the number of pages.
4434  */
4435 #define PAGES_PER_WAITQUEUE     256
4436
4437 #ifndef CONFIG_MEMORY_HOTPLUG
4438 static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
4439 {
4440         unsigned long size = 1;
4441
4442         pages /= PAGES_PER_WAITQUEUE;
4443
4444         while (size < pages)
4445                 size <<= 1;
4446
4447         /*
4448          * Once we have dozens or even hundreds of threads sleeping
4449          * on IO we've got bigger problems than wait queue collision.
4450          * Limit the size of the wait table to a reasonable size.
4451          */
4452         size = min(size, 4096UL);
4453
4454         return max(size, 4UL);
4455 }
4456 #else
4457 /*
4458  * A zone's size might be changed by hot-add, so it is not possible to determine
4459  * a suitable size for its wait_table.  So we use the maximum size now.
4460  *
4461  * The max wait table size = 4096 x sizeof(wait_queue_head_t).   ie:
4462  *
4463  *    i386 (preemption config)    : 4096 x 16 = 64Kbyte.
4464  *    ia64, x86-64 (no preemption): 4096 x 20 = 80Kbyte.
4465  *    ia64, x86-64 (preemption)   : 4096 x 24 = 96Kbyte.
4466  *
4467  * The maximum entries are prepared when a zone's memory is (512K + 256) pages
4468  * or more by the traditional way. (See above).  It equals:
4469  *
4470  *    i386, x86-64, powerpc(4K page size) : =  ( 2G + 1M)byte.
4471  *    ia64(16K page size)                 : =  ( 8G + 4M)byte.
4472  *    powerpc (64K page size)             : =  (32G +16M)byte.
4473  */
4474 static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
4475 {
4476         return 4096UL;
4477 }
4478 #endif
4479
4480 /*
4481  * This is an integer logarithm so that shifts can be used later
4482  * to extract the more random high bits from the multiplicative
4483  * hash function before the remainder is taken.
4484  */
4485 static inline unsigned long wait_table_bits(unsigned long size)
4486 {
4487         return ffz(~size);
4488 }
4489
4490 /*
4491  * Initially all pages are reserved - free ones are freed
4492  * up by free_all_bootmem() once the early boot process is
4493  * done. Non-atomic initialization, single-pass.
4494  */
4495 void __meminit memmap_init_zone(unsigned long size, int nid, unsigned long zone,
4496                 unsigned long start_pfn, enum memmap_context context)
4497 {
4498         pg_data_t *pgdat = NODE_DATA(nid);
4499         unsigned long end_pfn = start_pfn + size;
4500         unsigned long pfn;
4501         struct zone *z;
4502         unsigned long nr_initialised = 0;
4503
4504         if (highest_memmap_pfn < end_pfn - 1)
4505                 highest_memmap_pfn = end_pfn - 1;
4506
4507         z = &pgdat->node_zones[zone];
4508         for (pfn = start_pfn; pfn < end_pfn; pfn++) {
4509                 /*
4510                  * There can be holes in boot-time mem_map[]s
4511                  * handed to this function.  They do not
4512                  * exist on hotplugged memory.
4513                  */
4514                 if (context == MEMMAP_EARLY) {
4515                         if (!early_pfn_valid(pfn))
4516                                 continue;
4517                         if (!early_pfn_in_nid(pfn, nid))
4518                                 continue;
4519                         if (!update_defer_init(pgdat, pfn, end_pfn,
4520                                                 &nr_initialised))
4521                                 break;
4522                 }
4523
4524                 /*
4525                  * Mark the block movable so that blocks are reserved for
4526                  * movable at startup. This will force kernel allocations
4527                  * to reserve their blocks rather than leaking throughout
4528                  * the address space during boot when many long-lived
4529                  * kernel allocations are made.
4530                  *
4531                  * bitmap is created for zone's valid pfn range. but memmap
4532                  * can be created for invalid pages (for alignment)
4533                  * check here not to call set_pageblock_migratetype() against
4534                  * pfn out of zone.
4535                  */
4536                 if (!(pfn & (pageblock_nr_pages - 1))) {
4537                         struct page *page = pfn_to_page(pfn);
4538
4539                         __init_single_page(page, pfn, zone, nid);
4540                         set_pageblock_migratetype(page, MIGRATE_MOVABLE);
4541                 } else {
4542                         __init_single_pfn(pfn, zone, nid);
4543                 }
4544         }
4545 }
4546
4547 static void __meminit zone_init_free_lists(struct zone *zone)
4548 {
4549         unsigned int order, t;
4550         for_each_migratetype_order(order, t) {
4551                 INIT_LIST_HEAD(&zone->free_area[order].free_list[t]);
4552                 zone->free_area[order].nr_free = 0;
4553         }
4554 }
4555
4556 #ifndef __HAVE_ARCH_MEMMAP_INIT
4557 #define memmap_init(size, nid, zone, start_pfn) \
4558         memmap_init_zone((size), (nid), (zone), (start_pfn), MEMMAP_EARLY)
4559 #endif
4560
4561 static int zone_batchsize(struct zone *zone)
4562 {
4563 #ifdef CONFIG_MMU
4564         int batch;
4565
4566         /*
4567          * The per-cpu-pages pools are set to around 1000th of the
4568          * size of the zone.  But no more than 1/2 of a meg.
4569          *
4570          * OK, so we don't know how big the cache is.  So guess.
4571          */
4572         batch = zone->managed_pages / 1024;
4573         if (batch * PAGE_SIZE > 512 * 1024)
4574                 batch = (512 * 1024) / PAGE_SIZE;
4575         batch /= 4;             /* We effectively *= 4 below */
4576         if (batch < 1)
4577                 batch = 1;
4578
4579         /*
4580          * Clamp the batch to a 2^n - 1 value. Having a power
4581          * of 2 value was found to be more likely to have
4582          * suboptimal cache aliasing properties in some cases.
4583          *
4584          * For example if 2 tasks are alternately allocating
4585          * batches of pages, one task can end up with a lot
4586          * of pages of one half of the possible page colors
4587          * and the other with pages of the other colors.
4588          */
4589         batch = rounddown_pow_of_two(batch + batch/2) - 1;
4590
4591         return batch;
4592
4593 #else
4594         /* The deferral and batching of frees should be suppressed under NOMMU
4595          * conditions.
4596          *
4597          * The problem is that NOMMU needs to be able to allocate large chunks
4598          * of contiguous memory as there's no hardware page translation to
4599          * assemble apparent contiguous memory from discontiguous pages.
4600          *
4601          * Queueing large contiguous runs of pages for batching, however,
4602          * causes the pages to actually be freed in smaller chunks.  As there
4603          * can be a significant delay between the individual batches being
4604          * recycled, this leads to the once large chunks of space being
4605          * fragmented and becoming unavailable for high-order allocations.
4606          */
4607         return 0;
4608 #endif
4609 }
4610
4611 /*
4612  * pcp->high and pcp->batch values are related and dependent on one another:
4613  * ->batch must never be higher then ->high.
4614  * The following function updates them in a safe manner without read side
4615  * locking.
4616  *
4617  * Any new users of pcp->batch and pcp->high should ensure they can cope with
4618  * those fields changing asynchronously (acording the the above rule).
4619  *
4620  * mutex_is_locked(&pcp_batch_high_lock) required when calling this function
4621  * outside of boot time (or some other assurance that no concurrent updaters
4622  * exist).
4623  */
4624 static void pageset_update(struct per_cpu_pages *pcp, unsigned long high,
4625                 unsigned long batch)
4626 {
4627        /* start with a fail safe value for batch */
4628         pcp->batch = 1;
4629         smp_wmb();
4630
4631        /* Update high, then batch, in order */
4632         pcp->high = high;
4633         smp_wmb();
4634
4635         pcp->batch = batch;
4636 }
4637
4638 /* a companion to pageset_set_high() */
4639 static void pageset_set_batch(struct per_cpu_pageset *p, unsigned long batch)
4640 {
4641         pageset_update(&p->pcp, 6 * batch, max(1UL, 1 * batch));
4642 }
4643
4644 static void pageset_init(struct per_cpu_pageset *p)
4645 {
4646         struct per_cpu_pages *pcp;
4647         int migratetype;
4648
4649         memset(p, 0, sizeof(*p));
4650
4651         pcp = &p->pcp;
4652         pcp->count = 0;
4653         for (migratetype = 0; migratetype < MIGRATE_PCPTYPES; migratetype++)
4654                 INIT_LIST_HEAD(&pcp->lists[migratetype]);
4655 }
4656
4657 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch)
4658 {
4659         pageset_init(p);
4660         pageset_set_batch(p, batch);
4661 }
4662
4663 /*
4664  * pageset_set_high() sets the high water mark for hot per_cpu_pagelist
4665  * to the value high for the pageset p.
4666  */
4667 static void pageset_set_high(struct per_cpu_pageset *p,
4668                                 unsigned long high)
4669 {
4670         unsigned long batch = max(1UL, high / 4);
4671         if ((high / 4) > (PAGE_SHIFT * 8))
4672                 batch = PAGE_SHIFT * 8;
4673
4674         pageset_update(&p->pcp, high, batch);
4675 }
4676
4677 static void pageset_set_high_and_batch(struct zone *zone,
4678                                        struct per_cpu_pageset *pcp)
4679 {
4680         if (percpu_pagelist_fraction)
4681                 pageset_set_high(pcp,
4682                         (zone->managed_pages /
4683                                 percpu_pagelist_fraction));
4684         else
4685                 pageset_set_batch(pcp, zone_batchsize(zone));
4686 }
4687
4688 static void __meminit zone_pageset_init(struct zone *zone, int cpu)
4689 {
4690         struct per_cpu_pageset *pcp = per_cpu_ptr(zone->pageset, cpu);
4691
4692         pageset_init(pcp);
4693         pageset_set_high_and_batch(zone, pcp);
4694 }
4695
4696 static void __meminit setup_zone_pageset(struct zone *zone)
4697 {
4698         int cpu;
4699         zone->pageset = alloc_percpu(struct per_cpu_pageset);
4700         for_each_possible_cpu(cpu)
4701                 zone_pageset_init(zone, cpu);
4702 }
4703
4704 /*
4705  * Allocate per cpu pagesets and initialize them.
4706  * Before this call only boot pagesets were available.
4707  */
4708 void __init setup_per_cpu_pageset(void)
4709 {
4710         struct zone *zone;
4711
4712         for_each_populated_zone(zone)
4713                 setup_zone_pageset(zone);
4714 }
4715
4716 static noinline __init_refok
4717 int zone_wait_table_init(struct zone *zone, unsigned long zone_size_pages)
4718 {
4719         int i;
4720         size_t alloc_size;
4721
4722         /*
4723          * The per-page waitqueue mechanism uses hashed waitqueues
4724          * per zone.
4725          */
4726         zone->wait_table_hash_nr_entries =
4727                  wait_table_hash_nr_entries(zone_size_pages);
4728         zone->wait_table_bits =
4729                 wait_table_bits(zone->wait_table_hash_nr_entries);
4730         alloc_size = zone->wait_table_hash_nr_entries
4731                                         * sizeof(wait_queue_head_t);
4732
4733         if (!slab_is_available()) {
4734                 zone->wait_table = (wait_queue_head_t *)
4735                         memblock_virt_alloc_node_nopanic(
4736                                 alloc_size, zone->zone_pgdat->node_id);
4737         } else {
4738                 /*
4739                  * This case means that a zone whose size was 0 gets new memory
4740                  * via memory hot-add.
4741                  * But it may be the case that a new node was hot-added.  In
4742                  * this case vmalloc() will not be able to use this new node's
4743                  * memory - this wait_table must be initialized to use this new
4744                  * node itself as well.
4745                  * To use this new node's memory, further consideration will be
4746                  * necessary.
4747                  */
4748                 zone->wait_table = vmalloc(alloc_size);
4749         }
4750         if (!zone->wait_table)
4751                 return -ENOMEM;
4752
4753         for (i = 0; i < zone->wait_table_hash_nr_entries; ++i)
4754                 init_waitqueue_head(zone->wait_table + i);
4755
4756         return 0;
4757 }
4758
4759 static __meminit void zone_pcp_init(struct zone *zone)
4760 {
4761         /*
4762          * per cpu subsystem is not up at this point. The following code
4763          * relies on the ability of the linker to provide the
4764          * offset of a (static) per cpu variable into the per cpu area.
4765          */
4766         zone->pageset = &boot_pageset;
4767
4768         if (populated_zone(zone))
4769                 printk(KERN_DEBUG "  %s zone: %lu pages, LIFO batch:%u\n",
4770                         zone->name, zone->present_pages,
4771                                          zone_batchsize(zone));
4772 }
4773
4774 int __meminit init_currently_empty_zone(struct zone *zone,
4775                                         unsigned long zone_start_pfn,
4776                                         unsigned long size)
4777 {
4778         struct pglist_data *pgdat = zone->zone_pgdat;
4779         int ret;
4780         ret = zone_wait_table_init(zone, size);
4781         if (ret)
4782                 return ret;
4783         pgdat->nr_zones = zone_idx(zone) + 1;
4784
4785         zone->zone_start_pfn = zone_start_pfn;
4786
4787         mminit_dprintk(MMINIT_TRACE, "memmap_init",
4788                         "Initialising map node %d zone %lu pfns %lu -> %lu\n",
4789                         pgdat->node_id,
4790                         (unsigned long)zone_idx(zone),
4791                         zone_start_pfn, (zone_start_pfn + size));
4792
4793         zone_init_free_lists(zone);
4794
4795         return 0;
4796 }
4797
4798 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
4799 #ifndef CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID
4800
4801 /*
4802  * Required by SPARSEMEM. Given a PFN, return what node the PFN is on.
4803  */
4804 int __meminit __early_pfn_to_nid(unsigned long pfn,
4805                                         struct mminit_pfnnid_cache *state)
4806 {
4807         unsigned long start_pfn, end_pfn;
4808         int nid;
4809
4810         if (state->last_start <= pfn && pfn < state->last_end)
4811                 return state->last_nid;
4812
4813         nid = memblock_search_pfn_nid(pfn, &start_pfn, &end_pfn);
4814         if (nid != -1) {
4815                 state->last_start = start_pfn;
4816                 state->last_end = end_pfn;
4817                 state->last_nid = nid;
4818         }
4819
4820         return nid;
4821 }
4822 #endif /* CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID */
4823
4824 /**
4825  * free_bootmem_with_active_regions - Call memblock_free_early_nid for each active range
4826  * @nid: The node to free memory on. If MAX_NUMNODES, all nodes are freed.
4827  * @max_low_pfn: The highest PFN that will be passed to memblock_free_early_nid
4828  *
4829  * If an architecture guarantees that all ranges registered contain no holes
4830  * and may be freed, this this function may be used instead of calling
4831  * memblock_free_early_nid() manually.
4832  */
4833 void __init free_bootmem_with_active_regions(int nid, unsigned long max_low_pfn)
4834 {
4835         unsigned long start_pfn, end_pfn;
4836         int i, this_nid;
4837
4838         for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, &this_nid) {
4839                 start_pfn = min(start_pfn, max_low_pfn);
4840                 end_pfn = min(end_pfn, max_low_pfn);
4841
4842                 if (start_pfn < end_pfn)
4843                         memblock_free_early_nid(PFN_PHYS(start_pfn),
4844                                         (end_pfn - start_pfn) << PAGE_SHIFT,
4845                                         this_nid);
4846         }
4847 }
4848
4849 /**
4850  * sparse_memory_present_with_active_regions - Call memory_present for each active range
4851  * @nid: The node to call memory_present for. If MAX_NUMNODES, all nodes will be used.
4852  *
4853  * If an architecture guarantees that all ranges registered contain no holes and may
4854  * be freed, this function may be used instead of calling memory_present() manually.
4855  */
4856 void __init sparse_memory_present_with_active_regions(int nid)
4857 {
4858         unsigned long start_pfn, end_pfn;
4859         int i, this_nid;
4860
4861         for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, &this_nid)
4862                 memory_present(this_nid, start_pfn, end_pfn);
4863 }
4864
4865 /**
4866  * get_pfn_range_for_nid - Return the start and end page frames for a node
4867  * @nid: The nid to return the range for. If MAX_NUMNODES, the min and max PFN are returned.
4868  * @start_pfn: Passed by reference. On return, it will have the node start_pfn.
4869  * @end_pfn: Passed by reference. On return, it will have the node end_pfn.
4870  *
4871  * It returns the start and end page frame of a node based on information
4872  * provided by memblock_set_node(). If called for a node
4873  * with no available memory, a warning is printed and the start and end
4874  * PFNs will be 0.
4875  */
4876 void __meminit get_pfn_range_for_nid(unsigned int nid,
4877                         unsigned long *start_pfn, unsigned long *end_pfn)
4878 {
4879         unsigned long this_start_pfn, this_end_pfn;
4880         int i;
4881
4882         *start_pfn = -1UL;
4883         *end_pfn = 0;
4884
4885         for_each_mem_pfn_range(i, nid, &this_start_pfn, &this_end_pfn, NULL) {
4886                 *start_pfn = min(*start_pfn, this_start_pfn);
4887                 *end_pfn = max(*end_pfn, this_end_pfn);
4888         }
4889
4890         if (*start_pfn == -1UL)
4891                 *start_pfn = 0;
4892 }
4893
4894 /*
4895  * This finds a zone that can be used for ZONE_MOVABLE pages. The
4896  * assumption is made that zones within a node are ordered in monotonic
4897  * increasing memory addresses so that the "highest" populated zone is used
4898  */
4899 static void __init find_usable_zone_for_movable(void)
4900 {
4901         int zone_index;
4902         for (zone_index = MAX_NR_ZONES - 1; zone_index >= 0; zone_index--) {
4903                 if (zone_index == ZONE_MOVABLE)
4904                         continue;
4905
4906                 if (arch_zone_highest_possible_pfn[zone_index] >
4907                                 arch_zone_lowest_possible_pfn[zone_index])
4908                         break;
4909         }
4910
4911         VM_BUG_ON(zone_index == -1);
4912         movable_zone = zone_index;
4913 }
4914
4915 /*
4916  * The zone ranges provided by the architecture do not include ZONE_MOVABLE
4917  * because it is sized independent of architecture. Unlike the other zones,
4918  * the starting point for ZONE_MOVABLE is not fixed. It may be different
4919  * in each node depending on the size of each node and how evenly kernelcore
4920  * is distributed. This helper function adjusts the zone ranges
4921  * provided by the architecture for a given node by using the end of the
4922  * highest usable zone for ZONE_MOVABLE. This preserves the assumption that
4923  * zones within a node are in order of monotonic increases memory addresses
4924  */
4925 static void __meminit adjust_zone_range_for_zone_movable(int nid,
4926                                         unsigned long zone_type,
4927                                         unsigned long node_start_pfn,
4928                                         unsigned long node_end_pfn,
4929                                         unsigned long *zone_start_pfn,
4930                                         unsigned long *zone_end_pfn)
4931 {
4932         /* Only adjust if ZONE_MOVABLE is on this node */
4933         if (zone_movable_pfn[nid]) {
4934                 /* Size ZONE_MOVABLE */
4935                 if (zone_type == ZONE_MOVABLE) {
4936                         *zone_start_pfn = zone_movable_pfn[nid];
4937                         *zone_end_pfn = min(node_end_pfn,
4938                                 arch_zone_highest_possible_pfn[movable_zone]);
4939
4940                 /* Adjust for ZONE_MOVABLE starting within this range */
4941                 } else if (*zone_start_pfn < zone_movable_pfn[nid] &&
4942                                 *zone_end_pfn > zone_movable_pfn[nid]) {
4943                         *zone_end_pfn = zone_movable_pfn[nid];
4944
4945                 /* Check if this whole range is within ZONE_MOVABLE */
4946                 } else if (*zone_start_pfn >= zone_movable_pfn[nid])
4947                         *zone_start_pfn = *zone_end_pfn;
4948         }
4949 }
4950
4951 /*
4952  * Return the number of pages a zone spans in a node, including holes
4953  * present_pages = zone_spanned_pages_in_node() - zone_absent_pages_in_node()
4954  */
4955 static unsigned long __meminit zone_spanned_pages_in_node(int nid,
4956                                         unsigned long zone_type,
4957                                         unsigned long node_start_pfn,
4958                                         unsigned long node_end_pfn,
4959                                         unsigned long *ignored)
4960 {
4961         unsigned long zone_start_pfn, zone_end_pfn;
4962
4963         /* When hotadd a new node from cpu_up(), the node should be empty */
4964         if (!node_start_pfn && !node_end_pfn)
4965                 return 0;
4966
4967         /* Get the start and end of the zone */
4968         zone_start_pfn = arch_zone_lowest_possible_pfn[zone_type];
4969         zone_end_pfn = arch_zone_highest_possible_pfn[zone_type];
4970         adjust_zone_range_for_zone_movable(nid, zone_type,
4971                                 node_start_pfn, node_end_pfn,
4972                                 &zone_start_pfn, &zone_end_pfn);
4973
4974         /* Check that this node has pages within the zone's required range */
4975         if (zone_end_pfn < node_start_pfn || zone_start_pfn > node_end_pfn)
4976                 return 0;
4977
4978         /* Move the zone boundaries inside the node if necessary */
4979         zone_end_pfn = min(zone_end_pfn, node_end_pfn);
4980         zone_start_pfn = max(zone_start_pfn, node_start_pfn);
4981
4982         /* Return the spanned pages */
4983         return zone_end_pfn - zone_start_pfn;
4984 }
4985
4986 /*
4987  * Return the number of holes in a range on a node. If nid is MAX_NUMNODES,
4988  * then all holes in the requested range will be accounted for.
4989  */
4990 unsigned long __meminit __absent_pages_in_range(int nid,
4991                                 unsigned long range_start_pfn,
4992                                 unsigned long range_end_pfn)
4993 {
4994         unsigned long nr_absent = range_end_pfn - range_start_pfn;
4995         unsigned long start_pfn, end_pfn;
4996         int i;
4997
4998         for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
4999                 start_pfn = clamp(start_pfn, range_start_pfn, range_end_pfn);
5000                 end_pfn = clamp(end_pfn, range_start_pfn, range_end_pfn);
5001                 nr_absent -= end_pfn - start_pfn;
5002         }
5003         return nr_absent;
5004 }
5005
5006 /**
5007  * absent_pages_in_range - Return number of page frames in holes within a range
5008  * @start_pfn: The start PFN to start searching for holes
5009  * @end_pfn: The end PFN to stop searching for holes
5010  *
5011  * It returns the number of pages frames in memory holes within a range.
5012  */
5013 unsigned long __init absent_pages_in_range(unsigned long start_pfn,
5014                                                         unsigned long end_pfn)
5015 {
5016         return __absent_pages_in_range(MAX_NUMNODES, start_pfn, end_pfn);
5017 }
5018
5019 /* Return the number of page frames in holes in a zone on a node */
5020 static unsigned long __meminit zone_absent_pages_in_node(int nid,
5021                                         unsigned long zone_type,
5022                                         unsigned long node_start_pfn,
5023                                         unsigned long node_end_pfn,
5024                                         unsigned long *ignored)
5025 {
5026         unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type];
5027         unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type];
5028         unsigned long zone_start_pfn, zone_end_pfn;
5029
5030         /* When hotadd a new node from cpu_up(), the node should be empty */
5031         if (!node_start_pfn && !node_end_pfn)
5032                 return 0;
5033
5034         zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high);
5035         zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high);
5036
5037         adjust_zone_range_for_zone_movable(nid, zone_type,
5038                         node_start_pfn, node_end_pfn,
5039                         &zone_start_pfn, &zone_end_pfn);
5040         return __absent_pages_in_range(nid, zone_start_pfn, zone_end_pfn);
5041 }
5042
5043 #else /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
5044 static inline unsigned long __meminit zone_spanned_pages_in_node(int nid,
5045                                         unsigned long zone_type,
5046                                         unsigned long node_start_pfn,
5047                                         unsigned long node_end_pfn,
5048                                         unsigned long *zones_size)
5049 {
5050         return zones_size[zone_type];
5051 }
5052
5053 static inline unsigned long __meminit zone_absent_pages_in_node(int nid,
5054                                                 unsigned long zone_type,
5055                                                 unsigned long node_start_pfn,
5056                                                 unsigned long node_end_pfn,
5057                                                 unsigned long *zholes_size)
5058 {
5059         if (!zholes_size)
5060                 return 0;
5061
5062         return zholes_size[zone_type];
5063 }
5064
5065 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
5066
5067 static void __meminit calculate_node_totalpages(struct pglist_data *pgdat,
5068                                                 unsigned long node_start_pfn,
5069                                                 unsigned long node_end_pfn,
5070                                                 unsigned long *zones_size,
5071                                                 unsigned long *zholes_size)
5072 {
5073         unsigned long realtotalpages = 0, totalpages = 0;
5074         enum zone_type i;
5075
5076         for (i = 0; i < MAX_NR_ZONES; i++) {
5077                 struct zone *zone = pgdat->node_zones + i;
5078                 unsigned long size, real_size;
5079
5080                 size = zone_spanned_pages_in_node(pgdat->node_id, i,
5081                                                   node_start_pfn,
5082                                                   node_end_pfn,
5083                                                   zones_size);
5084                 real_size = size - zone_absent_pages_in_node(pgdat->node_id, i,
5085                                                   node_start_pfn, node_end_pfn,
5086                                                   zholes_size);
5087                 zone->spanned_pages = size;
5088                 zone->present_pages = real_size;
5089
5090                 totalpages += size;
5091                 realtotalpages += real_size;
5092         }
5093
5094         pgdat->node_spanned_pages = totalpages;
5095         pgdat->node_present_pages = realtotalpages;
5096         printk(KERN_DEBUG "On node %d totalpages: %lu\n", pgdat->node_id,
5097                                                         realtotalpages);
5098 }
5099
5100 #ifndef CONFIG_SPARSEMEM
5101 /*
5102  * Calculate the size of the zone->blockflags rounded to an unsigned long
5103  * Start by making sure zonesize is a multiple of pageblock_order by rounding
5104  * up. Then use 1 NR_PAGEBLOCK_BITS worth of bits per pageblock, finally
5105  * round what is now in bits to nearest long in bits, then return it in
5106  * bytes.
5107  */
5108 static unsigned long __init usemap_size(unsigned long zone_start_pfn, unsigned long zonesize)
5109 {
5110         unsigned long usemapsize;
5111
5112         zonesize += zone_start_pfn & (pageblock_nr_pages-1);
5113         usemapsize = roundup(zonesize, pageblock_nr_pages);
5114         usemapsize = usemapsize >> pageblock_order;
5115         usemapsize *= NR_PAGEBLOCK_BITS;
5116         usemapsize = roundup(usemapsize, 8 * sizeof(unsigned long));
5117
5118         return usemapsize / 8;
5119 }
5120
5121 static void __init setup_usemap(struct pglist_data *pgdat,
5122                                 struct zone *zone,
5123                                 unsigned long zone_start_pfn,
5124                                 unsigned long zonesize)
5125 {
5126         unsigned long usemapsize = usemap_size(zone_start_pfn, zonesize);
5127         zone->pageblock_flags = NULL;
5128         if (usemapsize)
5129                 zone->pageblock_flags =
5130                         memblock_virt_alloc_node_nopanic(usemapsize,
5131                                                          pgdat->node_id);
5132 }
5133 #else
5134 static inline void setup_usemap(struct pglist_data *pgdat, struct zone *zone,
5135                                 unsigned long zone_start_pfn, unsigned long zonesize) {}
5136 #endif /* CONFIG_SPARSEMEM */
5137
5138 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
5139
5140 /* Initialise the number of pages represented by NR_PAGEBLOCK_BITS */
5141 void __paginginit set_pageblock_order(void)
5142 {
5143         unsigned int order;
5144
5145         /* Check that pageblock_nr_pages has not already been setup */
5146         if (pageblock_order)
5147                 return;
5148
5149         if (HPAGE_SHIFT > PAGE_SHIFT)
5150                 order = HUGETLB_PAGE_ORDER;
5151         else
5152                 order = MAX_ORDER - 1;
5153
5154         /*
5155          * Assume the largest contiguous order of interest is a huge page.
5156          * This value may be variable depending on boot parameters on IA64 and
5157          * powerpc.
5158          */
5159         pageblock_order = order;
5160 }
5161 #else /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
5162
5163 /*
5164  * When CONFIG_HUGETLB_PAGE_SIZE_VARIABLE is not set, set_pageblock_order()
5165  * is unused as pageblock_order is set at compile-time. See
5166  * include/linux/pageblock-flags.h for the values of pageblock_order based on
5167  * the kernel config
5168  */
5169 void __paginginit set_pageblock_order(void)
5170 {
5171 }
5172
5173 #endif /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
5174
5175 static unsigned long __paginginit calc_memmap_size(unsigned long spanned_pages,
5176                                                    unsigned long present_pages)
5177 {
5178         unsigned long pages = spanned_pages;
5179
5180         /*
5181          * Provide a more accurate estimation if there are holes within
5182          * the zone and SPARSEMEM is in use. If there are holes within the
5183          * zone, each populated memory region may cost us one or two extra
5184          * memmap pages due to alignment because memmap pages for each
5185          * populated regions may not naturally algined on page boundary.
5186          * So the (present_pages >> 4) heuristic is a tradeoff for that.
5187          */
5188         if (spanned_pages > present_pages + (present_pages >> 4) &&
5189             IS_ENABLED(CONFIG_SPARSEMEM))
5190                 pages = present_pages;
5191
5192         return PAGE_ALIGN(pages * sizeof(struct page)) >> PAGE_SHIFT;
5193 }
5194
5195 /*
5196  * Set up the zone data structures:
5197  *   - mark all pages reserved
5198  *   - mark all memory queues empty
5199  *   - clear the memory bitmaps
5200  *
5201  * NOTE: pgdat should get zeroed by caller.
5202  */
5203 static void __paginginit free_area_init_core(struct pglist_data *pgdat)
5204 {
5205         enum zone_type j;
5206         int nid = pgdat->node_id;
5207         unsigned long zone_start_pfn = pgdat->node_start_pfn;
5208         int ret;
5209
5210         pgdat_resize_init(pgdat);
5211 #ifdef CONFIG_NUMA_BALANCING
5212         spin_lock_init(&pgdat->numabalancing_migrate_lock);
5213         pgdat->numabalancing_migrate_nr_pages = 0;
5214         pgdat->numabalancing_migrate_next_window = jiffies;
5215 #endif
5216         init_waitqueue_head(&pgdat->kswapd_wait);
5217         init_waitqueue_head(&pgdat->pfmemalloc_wait);
5218         pgdat_page_ext_init(pgdat);
5219
5220         for (j = 0; j < MAX_NR_ZONES; j++) {
5221                 struct zone *zone = pgdat->node_zones + j;
5222                 unsigned long size, realsize, freesize, memmap_pages;
5223
5224                 size = zone->spanned_pages;
5225                 realsize = freesize = zone->present_pages;
5226
5227                 /*
5228                  * Adjust freesize so that it accounts for how much memory
5229                  * is used by this zone for memmap. This affects the watermark
5230                  * and per-cpu initialisations
5231                  */
5232                 memmap_pages = calc_memmap_size(size, realsize);
5233                 if (!is_highmem_idx(j)) {
5234                         if (freesize >= memmap_pages) {
5235                                 freesize -= memmap_pages;
5236                                 if (memmap_pages)
5237                                         printk(KERN_DEBUG
5238                                                "  %s zone: %lu pages used for memmap\n",
5239                                                zone_names[j], memmap_pages);
5240                         } else
5241                                 printk(KERN_WARNING
5242                                         "  %s zone: %lu pages exceeds freesize %lu\n",
5243                                         zone_names[j], memmap_pages, freesize);
5244                 }
5245
5246                 /* Account for reserved pages */
5247                 if (j == 0 && freesize > dma_reserve) {
5248                         freesize -= dma_reserve;
5249                         printk(KERN_DEBUG "  %s zone: %lu pages reserved\n",
5250                                         zone_names[0], dma_reserve);
5251                 }
5252
5253                 if (!is_highmem_idx(j))
5254                         nr_kernel_pages += freesize;
5255                 /* Charge for highmem memmap if there are enough kernel pages */
5256                 else if (nr_kernel_pages > memmap_pages * 2)
5257                         nr_kernel_pages -= memmap_pages;
5258                 nr_all_pages += freesize;
5259
5260                 /*
5261                  * Set an approximate value for lowmem here, it will be adjusted
5262                  * when the bootmem allocator frees pages into the buddy system.
5263                  * And all highmem pages will be managed by the buddy system.
5264                  */
5265                 zone->managed_pages = is_highmem_idx(j) ? realsize : freesize;
5266 #ifdef CONFIG_NUMA
5267                 zone->node = nid;
5268                 zone->min_unmapped_pages = (freesize*sysctl_min_unmapped_ratio)
5269                                                 / 100;
5270                 zone->min_slab_pages = (freesize * sysctl_min_slab_ratio) / 100;
5271 #endif
5272                 zone->name = zone_names[j];
5273                 spin_lock_init(&zone->lock);
5274                 spin_lock_init(&zone->lru_lock);
5275                 zone_seqlock_init(zone);
5276                 zone->zone_pgdat = pgdat;
5277                 zone_pcp_init(zone);
5278
5279                 /* For bootup, initialized properly in watermark setup */
5280                 mod_zone_page_state(zone, NR_ALLOC_BATCH, zone->managed_pages);
5281
5282                 lruvec_init(&zone->lruvec);
5283                 if (!size)
5284                         continue;
5285
5286                 set_pageblock_order();
5287                 setup_usemap(pgdat, zone, zone_start_pfn, size);
5288                 ret = init_currently_empty_zone(zone, zone_start_pfn, size);
5289                 BUG_ON(ret);
5290                 memmap_init(size, nid, j, zone_start_pfn);
5291                 zone_start_pfn += size;
5292         }
5293 }
5294
5295 static void __init_refok alloc_node_mem_map(struct pglist_data *pgdat)
5296 {
5297         unsigned long __maybe_unused start = 0;
5298         unsigned long __maybe_unused offset = 0;
5299
5300         /* Skip empty nodes */
5301         if (!pgdat->node_spanned_pages)
5302                 return;
5303
5304 #ifdef CONFIG_FLAT_NODE_MEM_MAP
5305         start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1);
5306         offset = pgdat->node_start_pfn - start;
5307         /* ia64 gets its own node_mem_map, before this, without bootmem */
5308         if (!pgdat->node_mem_map) {
5309                 unsigned long size, end;
5310                 struct page *map;
5311
5312                 /*
5313                  * The zone's endpoints aren't required to be MAX_ORDER
5314                  * aligned but the node_mem_map endpoints must be in order
5315                  * for the buddy allocator to function correctly.
5316                  */
5317                 end = pgdat_end_pfn(pgdat);
5318                 end = ALIGN(end, MAX_ORDER_NR_PAGES);
5319                 size =  (end - start) * sizeof(struct page);
5320                 map = alloc_remap(pgdat->node_id, size);
5321                 if (!map)
5322                         map = memblock_virt_alloc_node_nopanic(size,
5323                                                                pgdat->node_id);
5324                 pgdat->node_mem_map = map + offset;
5325         }
5326 #ifndef CONFIG_NEED_MULTIPLE_NODES
5327         /*
5328          * With no DISCONTIG, the global mem_map is just set as node 0's
5329          */
5330         if (pgdat == NODE_DATA(0)) {
5331                 mem_map = NODE_DATA(0)->node_mem_map;
5332 #if defined(CONFIG_HAVE_MEMBLOCK_NODE_MAP) || defined(CONFIG_FLATMEM)
5333                 if (page_to_pfn(mem_map) != pgdat->node_start_pfn)
5334                         mem_map -= offset;
5335 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
5336         }
5337 #endif
5338 #endif /* CONFIG_FLAT_NODE_MEM_MAP */
5339 }
5340
5341 void __paginginit free_area_init_node(int nid, unsigned long *zones_size,
5342                 unsigned long node_start_pfn, unsigned long *zholes_size)
5343 {
5344         pg_data_t *pgdat = NODE_DATA(nid);
5345         unsigned long start_pfn = 0;
5346         unsigned long end_pfn = 0;
5347
5348         /* pg_data_t should be reset to zero when it's allocated */
5349         WARN_ON(pgdat->nr_zones || pgdat->classzone_idx);
5350
5351         reset_deferred_meminit(pgdat);
5352         pgdat->node_id = nid;
5353         pgdat->node_start_pfn = node_start_pfn;
5354 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
5355         get_pfn_range_for_nid(nid, &start_pfn, &end_pfn);
5356         pr_info("Initmem setup node %d [mem %#018Lx-%#018Lx]\n", nid,
5357                 (u64)start_pfn << PAGE_SHIFT,
5358                 end_pfn ? ((u64)end_pfn << PAGE_SHIFT) - 1 : 0);
5359 #endif
5360         calculate_node_totalpages(pgdat, start_pfn, end_pfn,
5361                                   zones_size, zholes_size);
5362
5363         alloc_node_mem_map(pgdat);
5364 #ifdef CONFIG_FLAT_NODE_MEM_MAP
5365         printk(KERN_DEBUG "free_area_init_node: node %d, pgdat %08lx, node_mem_map %08lx\n",
5366                 nid, (unsigned long)pgdat,
5367                 (unsigned long)pgdat->node_mem_map);
5368 #endif
5369
5370         free_area_init_core(pgdat);
5371 }
5372
5373 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
5374
5375 #if MAX_NUMNODES > 1
5376 /*
5377  * Figure out the number of possible node ids.
5378  */
5379 void __init setup_nr_node_ids(void)
5380 {
5381         unsigned int highest;
5382
5383         highest = find_last_bit(node_possible_map.bits, MAX_NUMNODES);
5384         nr_node_ids = highest + 1;
5385 }
5386 #endif
5387
5388 /**
5389  * node_map_pfn_alignment - determine the maximum internode alignment
5390  *
5391  * This function should be called after node map is populated and sorted.
5392  * It calculates the maximum power of two alignment which can distinguish
5393  * all the nodes.
5394  *
5395  * For example, if all nodes are 1GiB and aligned to 1GiB, the return value
5396  * would indicate 1GiB alignment with (1 << (30 - PAGE_SHIFT)).  If the
5397  * nodes are shifted by 256MiB, 256MiB.  Note that if only the last node is
5398  * shifted, 1GiB is enough and this function will indicate so.
5399  *
5400  * This is used to test whether pfn -> nid mapping of the chosen memory
5401  * model has fine enough granularity to avoid incorrect mapping for the
5402  * populated node map.
5403  *
5404  * Returns the determined alignment in pfn's.  0 if there is no alignment
5405  * requirement (single node).
5406  */
5407 unsigned long __init node_map_pfn_alignment(void)
5408 {
5409         unsigned long accl_mask = 0, last_end = 0;
5410         unsigned long start, end, mask;
5411         int last_nid = -1;
5412         int i, nid;
5413
5414         for_each_mem_pfn_range(i, MAX_NUMNODES, &start, &end, &nid) {
5415                 if (!start || last_nid < 0 || last_nid == nid) {
5416                         last_nid = nid;
5417                         last_end = end;
5418                         continue;
5419                 }
5420
5421                 /*
5422                  * Start with a mask granular enough to pin-point to the
5423                  * start pfn and tick off bits one-by-one until it becomes
5424                  * too coarse to separate the current node from the last.
5425                  */
5426                 mask = ~((1 << __ffs(start)) - 1);
5427                 while (mask && last_end <= (start & (mask << 1)))
5428                         mask <<= 1;
5429
5430                 /* accumulate all internode masks */
5431                 accl_mask |= mask;
5432         }
5433
5434         /* convert mask to number of pages */
5435         return ~accl_mask + 1;
5436 }
5437
5438 /* Find the lowest pfn for a node */
5439 static unsigned long __init find_min_pfn_for_node(int nid)
5440 {
5441         unsigned long min_pfn = ULONG_MAX;
5442         unsigned long start_pfn;
5443         int i;
5444
5445         for_each_mem_pfn_range(i, nid, &start_pfn, NULL, NULL)
5446                 min_pfn = min(min_pfn, start_pfn);
5447
5448         if (min_pfn == ULONG_MAX) {
5449                 printk(KERN_WARNING
5450                         "Could not find start_pfn for node %d\n", nid);
5451                 return 0;
5452         }
5453
5454         return min_pfn;
5455 }
5456
5457 /**
5458  * find_min_pfn_with_active_regions - Find the minimum PFN registered
5459  *
5460  * It returns the minimum PFN based on information provided via
5461  * memblock_set_node().
5462  */
5463 unsigned long __init find_min_pfn_with_active_regions(void)
5464 {
5465         return find_min_pfn_for_node(MAX_NUMNODES);
5466 }
5467
5468 /*
5469  * early_calculate_totalpages()
5470  * Sum pages in active regions for movable zone.
5471  * Populate N_MEMORY for calculating usable_nodes.
5472  */
5473 static unsigned long __init early_calculate_totalpages(void)
5474 {
5475         unsigned long totalpages = 0;
5476         unsigned long start_pfn, end_pfn;
5477         int i, nid;
5478
5479         for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
5480                 unsigned long pages = end_pfn - start_pfn;
5481
5482                 totalpages += pages;
5483                 if (pages)
5484                         node_set_state(nid, N_MEMORY);
5485         }
5486         return totalpages;
5487 }
5488
5489 /*
5490  * Find the PFN the Movable zone begins in each node. Kernel memory
5491  * is spread evenly between nodes as long as the nodes have enough
5492  * memory. When they don't, some nodes will have more kernelcore than
5493  * others
5494  */
5495 static void __init find_zone_movable_pfns_for_nodes(void)
5496 {
5497         int i, nid;
5498         unsigned long usable_startpfn;
5499         unsigned long kernelcore_node, kernelcore_remaining;
5500         /* save the state before borrow the nodemask */
5501         nodemask_t saved_node_state = node_states[N_MEMORY];
5502         unsigned long totalpages = early_calculate_totalpages();
5503         int usable_nodes = nodes_weight(node_states[N_MEMORY]);
5504         struct memblock_region *r;
5505
5506         /* Need to find movable_zone earlier when movable_node is specified. */
5507         find_usable_zone_for_movable();
5508
5509         /*
5510          * If movable_node is specified, ignore kernelcore and movablecore
5511          * options.
5512          */
5513         if (movable_node_is_enabled()) {
5514                 for_each_memblock(memory, r) {
5515                         if (!memblock_is_hotpluggable(r))
5516                                 continue;
5517
5518                         nid = r->nid;
5519
5520                         usable_startpfn = PFN_DOWN(r->base);
5521                         zone_movable_pfn[nid] = zone_movable_pfn[nid] ?
5522                                 min(usable_startpfn, zone_movable_pfn[nid]) :
5523                                 usable_startpfn;
5524                 }
5525
5526                 goto out2;
5527         }
5528
5529         /*
5530          * If movablecore=nn[KMG] was specified, calculate what size of
5531          * kernelcore that corresponds so that memory usable for
5532          * any allocation type is evenly spread. If both kernelcore
5533          * and movablecore are specified, then the value of kernelcore
5534          * will be used for required_kernelcore if it's greater than
5535          * what movablecore would have allowed.
5536          */
5537         if (required_movablecore) {
5538                 unsigned long corepages;
5539
5540                 /*
5541                  * Round-up so that ZONE_MOVABLE is at least as large as what
5542                  * was requested by the user
5543                  */
5544                 required_movablecore =
5545                         roundup(required_movablecore, MAX_ORDER_NR_PAGES);
5546                 required_movablecore = min(totalpages, required_movablecore);
5547                 corepages = totalpages - required_movablecore;
5548
5549                 required_kernelcore = max(required_kernelcore, corepages);
5550         }
5551
5552         /*
5553          * If kernelcore was not specified or kernelcore size is larger
5554          * than totalpages, there is no ZONE_MOVABLE.
5555          */
5556         if (!required_kernelcore || required_kernelcore >= totalpages)
5557                 goto out;
5558
5559         /* usable_startpfn is the lowest possible pfn ZONE_MOVABLE can be at */
5560         usable_startpfn = arch_zone_lowest_possible_pfn[movable_zone];
5561
5562 restart:
5563         /* Spread kernelcore memory as evenly as possible throughout nodes */
5564         kernelcore_node = required_kernelcore / usable_nodes;
5565         for_each_node_state(nid, N_MEMORY) {
5566                 unsigned long start_pfn, end_pfn;
5567
5568                 /*
5569                  * Recalculate kernelcore_node if the division per node
5570                  * now exceeds what is necessary to satisfy the requested
5571                  * amount of memory for the kernel
5572                  */
5573                 if (required_kernelcore < kernelcore_node)
5574                         kernelcore_node = required_kernelcore / usable_nodes;
5575
5576                 /*
5577                  * As the map is walked, we track how much memory is usable
5578                  * by the kernel using kernelcore_remaining. When it is
5579                  * 0, the rest of the node is usable by ZONE_MOVABLE
5580                  */
5581                 kernelcore_remaining = kernelcore_node;
5582
5583                 /* Go through each range of PFNs within this node */
5584                 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
5585                         unsigned long size_pages;
5586
5587                         start_pfn = max(start_pfn, zone_movable_pfn[nid]);
5588                         if (start_pfn >= end_pfn)
5589                                 continue;
5590
5591                         /* Account for what is only usable for kernelcore */
5592                         if (start_pfn < usable_startpfn) {
5593                                 unsigned long kernel_pages;
5594                                 kernel_pages = min(end_pfn, usable_startpfn)
5595                                                                 - start_pfn;
5596
5597                                 kernelcore_remaining -= min(kernel_pages,
5598                                                         kernelcore_remaining);
5599                                 required_kernelcore -= min(kernel_pages,
5600                                                         required_kernelcore);
5601
5602                                 /* Continue if range is now fully accounted */
5603                                 if (end_pfn <= usable_startpfn) {
5604
5605                                         /*
5606                                          * Push zone_movable_pfn to the end so
5607                                          * that if we have to rebalance
5608                                          * kernelcore across nodes, we will
5609                                          * not double account here
5610                                          */
5611                                         zone_movable_pfn[nid] = end_pfn;
5612                                         continue;
5613                                 }
5614                                 start_pfn = usable_startpfn;
5615                         }
5616
5617                         /*
5618                          * The usable PFN range for ZONE_MOVABLE is from
5619                          * start_pfn->end_pfn. Calculate size_pages as the
5620                          * number of pages used as kernelcore
5621                          */
5622                         size_pages = end_pfn - start_pfn;
5623                         if (size_pages > kernelcore_remaining)
5624                                 size_pages = kernelcore_remaining;
5625                         zone_movable_pfn[nid] = start_pfn + size_pages;
5626
5627                         /*
5628                          * Some kernelcore has been met, update counts and
5629                          * break if the kernelcore for this node has been
5630                          * satisfied
5631                          */
5632                         required_kernelcore -= min(required_kernelcore,
5633                                                                 size_pages);
5634                         kernelcore_remaining -= size_pages;
5635                         if (!kernelcore_remaining)
5636                                 break;
5637                 }
5638         }
5639
5640         /*
5641          * If there is still required_kernelcore, we do another pass with one
5642          * less node in the count. This will push zone_movable_pfn[nid] further
5643          * along on the nodes that still have memory until kernelcore is
5644          * satisfied
5645          */
5646         usable_nodes--;
5647         if (usable_nodes && required_kernelcore > usable_nodes)
5648                 goto restart;
5649
5650 out2:
5651         /* Align start of ZONE_MOVABLE on all nids to MAX_ORDER_NR_PAGES */
5652         for (nid = 0; nid < MAX_NUMNODES; nid++)
5653                 zone_movable_pfn[nid] =
5654                         roundup(zone_movable_pfn[nid], MAX_ORDER_NR_PAGES);
5655
5656 out:
5657         /* restore the node_state */
5658         node_states[N_MEMORY] = saved_node_state;
5659 }
5660
5661 /* Any regular or high memory on that node ? */
5662 static void check_for_memory(pg_data_t *pgdat, int nid)
5663 {
5664         enum zone_type zone_type;
5665
5666         if (N_MEMORY == N_NORMAL_MEMORY)
5667                 return;
5668
5669         for (zone_type = 0; zone_type <= ZONE_MOVABLE - 1; zone_type++) {
5670                 struct zone *zone = &pgdat->node_zones[zone_type];
5671                 if (populated_zone(zone)) {
5672                         node_set_state(nid, N_HIGH_MEMORY);
5673                         if (N_NORMAL_MEMORY != N_HIGH_MEMORY &&
5674                             zone_type <= ZONE_NORMAL)
5675                                 node_set_state(nid, N_NORMAL_MEMORY);
5676                         break;
5677                 }
5678         }
5679 }
5680
5681 /**
5682  * free_area_init_nodes - Initialise all pg_data_t and zone data
5683  * @max_zone_pfn: an array of max PFNs for each zone
5684  *
5685  * This will call free_area_init_node() for each active node in the system.
5686  * Using the page ranges provided by memblock_set_node(), the size of each
5687  * zone in each node and their holes is calculated. If the maximum PFN
5688  * between two adjacent zones match, it is assumed that the zone is empty.
5689  * For example, if arch_max_dma_pfn == arch_max_dma32_pfn, it is assumed
5690  * that arch_max_dma32_pfn has no pages. It is also assumed that a zone
5691  * starts where the previous one ended. For example, ZONE_DMA32 starts
5692  * at arch_max_dma_pfn.
5693  */
5694 void __init free_area_init_nodes(unsigned long *max_zone_pfn)
5695 {
5696         unsigned long start_pfn, end_pfn;
5697         int i, nid;
5698
5699         /* Record where the zone boundaries are */
5700         memset(arch_zone_lowest_possible_pfn, 0,
5701                                 sizeof(arch_zone_lowest_possible_pfn));
5702         memset(arch_zone_highest_possible_pfn, 0,
5703                                 sizeof(arch_zone_highest_possible_pfn));
5704
5705         start_pfn = find_min_pfn_with_active_regions();
5706
5707         for (i = 0; i < MAX_NR_ZONES; i++) {
5708                 if (i == ZONE_MOVABLE)
5709                         continue;
5710
5711                 end_pfn = max(max_zone_pfn[i], start_pfn);
5712                 arch_zone_lowest_possible_pfn[i] = start_pfn;
5713                 arch_zone_highest_possible_pfn[i] = end_pfn;
5714
5715                 start_pfn = end_pfn;
5716         }
5717         arch_zone_lowest_possible_pfn[ZONE_MOVABLE] = 0;
5718         arch_zone_highest_possible_pfn[ZONE_MOVABLE] = 0;
5719
5720         /* Find the PFNs that ZONE_MOVABLE begins at in each node */
5721         memset(zone_movable_pfn, 0, sizeof(zone_movable_pfn));
5722         find_zone_movable_pfns_for_nodes();
5723
5724         /* Print out the zone ranges */
5725         pr_info("Zone ranges:\n");
5726         for (i = 0; i < MAX_NR_ZONES; i++) {
5727                 if (i == ZONE_MOVABLE)
5728                         continue;
5729                 pr_info("  %-8s ", zone_names[i]);
5730                 if (arch_zone_lowest_possible_pfn[i] ==
5731                                 arch_zone_highest_possible_pfn[i])
5732                         pr_cont("empty\n");
5733                 else
5734                         pr_cont("[mem %#018Lx-%#018Lx]\n",
5735                                 (u64)arch_zone_lowest_possible_pfn[i]
5736                                         << PAGE_SHIFT,
5737                                 ((u64)arch_zone_highest_possible_pfn[i]
5738                                         << PAGE_SHIFT) - 1);
5739         }
5740
5741         /* Print out the PFNs ZONE_MOVABLE begins at in each node */
5742         pr_info("Movable zone start for each node\n");
5743         for (i = 0; i < MAX_NUMNODES; i++) {
5744                 if (zone_movable_pfn[i])
5745                         pr_info("  Node %d: %#018Lx\n", i,
5746                                (u64)zone_movable_pfn[i] << PAGE_SHIFT);
5747         }
5748
5749         /* Print out the early node map */
5750         pr_info("Early memory node ranges\n");
5751         for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid)
5752                 pr_info("  node %3d: [mem %#018Lx-%#018Lx]\n", nid,
5753                         (u64)start_pfn << PAGE_SHIFT,
5754                         ((u64)end_pfn << PAGE_SHIFT) - 1);
5755
5756         /* Initialise every node */
5757         mminit_verify_pageflags_layout();
5758         setup_nr_node_ids();
5759         for_each_online_node(nid) {
5760                 pg_data_t *pgdat = NODE_DATA(nid);
5761                 free_area_init_node(nid, NULL,
5762                                 find_min_pfn_for_node(nid), NULL);
5763
5764                 /* Any memory on that node */
5765                 if (pgdat->node_present_pages)
5766                         node_set_state(nid, N_MEMORY);
5767                 check_for_memory(pgdat, nid);
5768         }
5769 }
5770
5771 static int __init cmdline_parse_core(char *p, unsigned long *core)
5772 {
5773         unsigned long long coremem;
5774         if (!p)
5775                 return -EINVAL;
5776
5777         coremem = memparse(p, &p);
5778         *core = coremem >> PAGE_SHIFT;
5779
5780         /* Paranoid check that UL is enough for the coremem value */
5781         WARN_ON((coremem >> PAGE_SHIFT) > ULONG_MAX);
5782
5783         return 0;
5784 }
5785
5786 /*
5787  * kernelcore=size sets the amount of memory for use for allocations that
5788  * cannot be reclaimed or migrated.
5789  */
5790 static int __init cmdline_parse_kernelcore(char *p)
5791 {
5792         return cmdline_parse_core(p, &required_kernelcore);
5793 }
5794
5795 /*
5796  * movablecore=size sets the amount of memory for use for allocations that
5797  * can be reclaimed or migrated.
5798  */
5799 static int __init cmdline_parse_movablecore(char *p)
5800 {
5801         return cmdline_parse_core(p, &required_movablecore);
5802 }
5803
5804 early_param("kernelcore", cmdline_parse_kernelcore);
5805 early_param("movablecore", cmdline_parse_movablecore);
5806
5807 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
5808
5809 void adjust_managed_page_count(struct page *page, long count)
5810 {
5811         spin_lock(&managed_page_count_lock);
5812         page_zone(page)->managed_pages += count;
5813         totalram_pages += count;
5814 #ifdef CONFIG_HIGHMEM
5815         if (PageHighMem(page))
5816                 totalhigh_pages += count;
5817 #endif
5818         spin_unlock(&managed_page_count_lock);
5819 }
5820 EXPORT_SYMBOL(adjust_managed_page_count);
5821
5822 unsigned long free_reserved_area(void *start, void *end, int poison, char *s)
5823 {
5824         void *pos;
5825         unsigned long pages = 0;
5826
5827         start = (void *)PAGE_ALIGN((unsigned long)start);
5828         end = (void *)((unsigned long)end & PAGE_MASK);
5829         for (pos = start; pos < end; pos += PAGE_SIZE, pages++) {
5830                 if ((unsigned int)poison <= 0xFF)
5831                         memset(pos, poison, PAGE_SIZE);
5832                 free_reserved_page(virt_to_page(pos));
5833         }
5834
5835         if (pages && s)
5836                 pr_info("Freeing %s memory: %ldK (%p - %p)\n",
5837                         s, pages << (PAGE_SHIFT - 10), start, end);
5838
5839         return pages;
5840 }
5841 EXPORT_SYMBOL(free_reserved_area);
5842
5843 #ifdef  CONFIG_HIGHMEM
5844 void free_highmem_page(struct page *page)
5845 {
5846         __free_reserved_page(page);
5847         totalram_pages++;
5848         page_zone(page)->managed_pages++;
5849         totalhigh_pages++;
5850 }
5851 #endif
5852
5853
5854 void __init mem_init_print_info(const char *str)
5855 {
5856         unsigned long physpages, codesize, datasize, rosize, bss_size;
5857         unsigned long init_code_size, init_data_size;
5858
5859         physpages = get_num_physpages();
5860         codesize = _etext - _stext;
5861         datasize = _edata - _sdata;
5862         rosize = __end_rodata - __start_rodata;
5863         bss_size = __bss_stop - __bss_start;
5864         init_data_size = __init_end - __init_begin;
5865         init_code_size = _einittext - _sinittext;
5866
5867         /*
5868          * Detect special cases and adjust section sizes accordingly:
5869          * 1) .init.* may be embedded into .data sections
5870          * 2) .init.text.* may be out of [__init_begin, __init_end],
5871          *    please refer to arch/tile/kernel/vmlinux.lds.S.
5872          * 3) .rodata.* may be embedded into .text or .data sections.
5873          */
5874 #define adj_init_size(start, end, size, pos, adj) \
5875         do { \
5876                 if (start <= pos && pos < end && size > adj) \
5877                         size -= adj; \
5878         } while (0)
5879
5880         adj_init_size(__init_begin, __init_end, init_data_size,
5881                      _sinittext, init_code_size);
5882         adj_init_size(_stext, _etext, codesize, _sinittext, init_code_size);
5883         adj_init_size(_sdata, _edata, datasize, __init_begin, init_data_size);
5884         adj_init_size(_stext, _etext, codesize, __start_rodata, rosize);
5885         adj_init_size(_sdata, _edata, datasize, __start_rodata, rosize);
5886
5887 #undef  adj_init_size
5888
5889         pr_info("Memory: %luK/%luK available "
5890                "(%luK kernel code, %luK rwdata, %luK rodata, "
5891                "%luK init, %luK bss, %luK reserved, %luK cma-reserved"
5892 #ifdef  CONFIG_HIGHMEM
5893                ", %luK highmem"
5894 #endif
5895                "%s%s)\n",
5896                nr_free_pages() << (PAGE_SHIFT-10), physpages << (PAGE_SHIFT-10),
5897                codesize >> 10, datasize >> 10, rosize >> 10,
5898                (init_data_size + init_code_size) >> 10, bss_size >> 10,
5899                (physpages - totalram_pages - totalcma_pages) << (PAGE_SHIFT-10),
5900                totalcma_pages << (PAGE_SHIFT-10),
5901 #ifdef  CONFIG_HIGHMEM
5902                totalhigh_pages << (PAGE_SHIFT-10),
5903 #endif
5904                str ? ", " : "", str ? str : "");
5905 }
5906
5907 /**
5908  * set_dma_reserve - set the specified number of pages reserved in the first zone
5909  * @new_dma_reserve: The number of pages to mark reserved
5910  *
5911  * The per-cpu batchsize and zone watermarks are determined by managed_pages.
5912  * In the DMA zone, a significant percentage may be consumed by kernel image
5913  * and other unfreeable allocations which can skew the watermarks badly. This
5914  * function may optionally be used to account for unfreeable pages in the
5915  * first zone (e.g., ZONE_DMA). The effect will be lower watermarks and
5916  * smaller per-cpu batchsize.
5917  */
5918 void __init set_dma_reserve(unsigned long new_dma_reserve)
5919 {
5920         dma_reserve = new_dma_reserve;
5921 }
5922
5923 void __init free_area_init(unsigned long *zones_size)
5924 {
5925         free_area_init_node(0, zones_size,
5926                         __pa(PAGE_OFFSET) >> PAGE_SHIFT, NULL);
5927 }
5928
5929 static int page_alloc_cpu_notify(struct notifier_block *self,
5930                                  unsigned long action, void *hcpu)
5931 {
5932         int cpu = (unsigned long)hcpu;
5933
5934         if (action == CPU_DEAD || action == CPU_DEAD_FROZEN) {
5935                 lru_add_drain_cpu(cpu);
5936                 drain_pages(cpu);
5937
5938                 /*
5939                  * Spill the event counters of the dead processor
5940                  * into the current processors event counters.
5941                  * This artificially elevates the count of the current
5942                  * processor.
5943                  */
5944                 vm_events_fold_cpu(cpu);
5945
5946                 /*
5947                  * Zero the differential counters of the dead processor
5948                  * so that the vm statistics are consistent.
5949                  *
5950                  * This is only okay since the processor is dead and cannot
5951                  * race with what we are doing.
5952                  */
5953                 cpu_vm_stats_fold(cpu);
5954         }
5955         return NOTIFY_OK;
5956 }
5957
5958 void __init page_alloc_init(void)
5959 {
5960         hotcpu_notifier(page_alloc_cpu_notify, 0);
5961 }
5962
5963 /*
5964  * calculate_totalreserve_pages - called when sysctl_lowmem_reserve_ratio
5965  *      or min_free_kbytes changes.
5966  */
5967 static void calculate_totalreserve_pages(void)
5968 {
5969         struct pglist_data *pgdat;
5970         unsigned long reserve_pages = 0;
5971         enum zone_type i, j;
5972
5973         for_each_online_pgdat(pgdat) {
5974                 for (i = 0; i < MAX_NR_ZONES; i++) {
5975                         struct zone *zone = pgdat->node_zones + i;
5976                         long max = 0;
5977
5978                         /* Find valid and maximum lowmem_reserve in the zone */
5979                         for (j = i; j < MAX_NR_ZONES; j++) {
5980                                 if (zone->lowmem_reserve[j] > max)
5981                                         max = zone->lowmem_reserve[j];
5982                         }
5983
5984                         /* we treat the high watermark as reserved pages. */
5985                         max += high_wmark_pages(zone);
5986
5987                         if (max > zone->managed_pages)
5988                                 max = zone->managed_pages;
5989
5990                         zone->totalreserve_pages = max;
5991
5992                         reserve_pages += max;
5993                 }
5994         }
5995         totalreserve_pages = reserve_pages;
5996 }
5997
5998 /*
5999  * setup_per_zone_lowmem_reserve - called whenever
6000  *      sysctl_lowmem_reserve_ratio changes.  Ensures that each zone
6001  *      has a correct pages reserved value, so an adequate number of
6002  *      pages are left in the zone after a successful __alloc_pages().
6003  */
6004 static void setup_per_zone_lowmem_reserve(void)
6005 {
6006         struct pglist_data *pgdat;
6007         enum zone_type j, idx;
6008
6009         for_each_online_pgdat(pgdat) {
6010                 for (j = 0; j < MAX_NR_ZONES; j++) {
6011                         struct zone *zone = pgdat->node_zones + j;
6012                         unsigned long managed_pages = zone->managed_pages;
6013
6014                         zone->lowmem_reserve[j] = 0;
6015
6016                         idx = j;
6017                         while (idx) {
6018                                 struct zone *lower_zone;
6019
6020                                 idx--;
6021
6022                                 if (sysctl_lowmem_reserve_ratio[idx] < 1)
6023                                         sysctl_lowmem_reserve_ratio[idx] = 1;
6024
6025                                 lower_zone = pgdat->node_zones + idx;
6026                                 lower_zone->lowmem_reserve[j] = managed_pages /
6027                                         sysctl_lowmem_reserve_ratio[idx];
6028                                 managed_pages += lower_zone->managed_pages;
6029                         }
6030                 }
6031         }
6032
6033         /* update totalreserve_pages */
6034         calculate_totalreserve_pages();
6035 }
6036
6037 static void __setup_per_zone_wmarks(void)
6038 {
6039         unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
6040         unsigned long pages_low = extra_free_kbytes >> (PAGE_SHIFT - 10);
6041         unsigned long lowmem_pages = 0;
6042         struct zone *zone;
6043         unsigned long flags;
6044
6045         /* Calculate total number of !ZONE_HIGHMEM pages */
6046         for_each_zone(zone) {
6047                 if (!is_highmem(zone))
6048                         lowmem_pages += zone->managed_pages;
6049         }
6050
6051         for_each_zone(zone) {
6052                 u64 min, low;
6053
6054                 spin_lock_irqsave(&zone->lock, flags);
6055                 min = (u64)pages_min * zone->managed_pages;
6056                 do_div(min, lowmem_pages);
6057                 low = (u64)pages_low * zone->managed_pages;
6058                 do_div(low, vm_total_pages);
6059
6060                 if (is_highmem(zone)) {
6061                         /*
6062                          * __GFP_HIGH and PF_MEMALLOC allocations usually don't
6063                          * need highmem pages, so cap pages_min to a small
6064                          * value here.
6065                          *
6066                          * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN)
6067                          * deltas control asynch page reclaim, and so should
6068                          * not be capped for highmem.
6069                          */
6070                         unsigned long min_pages;
6071
6072                         min_pages = zone->managed_pages / 1024;
6073                         min_pages = clamp(min_pages, SWAP_CLUSTER_MAX, 128UL);
6074                         zone->watermark[WMARK_MIN] = min_pages;
6075                 } else {
6076                         /*
6077                          * If it's a lowmem zone, reserve a number of pages
6078                          * proportionate to the zone's size.
6079                          */
6080                         zone->watermark[WMARK_MIN] = min;
6081                 }
6082
6083                 zone->watermark[WMARK_LOW]  = min_wmark_pages(zone) +
6084                                         low + (min >> 2);
6085                 zone->watermark[WMARK_HIGH] = min_wmark_pages(zone) +
6086                                         low + (min >> 1);
6087
6088                 __mod_zone_page_state(zone, NR_ALLOC_BATCH,
6089                         high_wmark_pages(zone) - low_wmark_pages(zone) -
6090                         atomic_long_read(&zone->vm_stat[NR_ALLOC_BATCH]));
6091
6092                 spin_unlock_irqrestore(&zone->lock, flags);
6093         }
6094
6095         /* update totalreserve_pages */
6096         calculate_totalreserve_pages();
6097 }
6098
6099 /**
6100  * setup_per_zone_wmarks - called when min_free_kbytes changes
6101  * or when memory is hot-{added|removed}
6102  *
6103  * Ensures that the watermark[min,low,high] values for each zone are set
6104  * correctly with respect to min_free_kbytes.
6105  */
6106 void setup_per_zone_wmarks(void)
6107 {
6108         mutex_lock(&zonelists_mutex);
6109         __setup_per_zone_wmarks();
6110         mutex_unlock(&zonelists_mutex);
6111 }
6112
6113 /*
6114  * The inactive anon list should be small enough that the VM never has to
6115  * do too much work, but large enough that each inactive page has a chance
6116  * to be referenced again before it is swapped out.
6117  *
6118  * The inactive_anon ratio is the target ratio of ACTIVE_ANON to
6119  * INACTIVE_ANON pages on this zone's LRU, maintained by the
6120  * pageout code. A zone->inactive_ratio of 3 means 3:1 or 25% of
6121  * the anonymous pages are kept on the inactive list.
6122  *
6123  * total     target    max
6124  * memory    ratio     inactive anon
6125  * -------------------------------------
6126  *   10MB       1         5MB
6127  *  100MB       1        50MB
6128  *    1GB       3       250MB
6129  *   10GB      10       0.9GB
6130  *  100GB      31         3GB
6131  *    1TB     101        10GB
6132  *   10TB     320        32GB
6133  */
6134 static void __meminit calculate_zone_inactive_ratio(struct zone *zone)
6135 {
6136         unsigned int gb, ratio;
6137
6138         /* Zone size in gigabytes */
6139         gb = zone->managed_pages >> (30 - PAGE_SHIFT);
6140         if (gb)
6141                 ratio = int_sqrt(10 * gb);
6142         else
6143                 ratio = 1;
6144
6145         zone->inactive_ratio = ratio;
6146 }
6147
6148 static void __meminit setup_per_zone_inactive_ratio(void)
6149 {
6150         struct zone *zone;
6151
6152         for_each_zone(zone)
6153                 calculate_zone_inactive_ratio(zone);
6154 }
6155
6156 /*
6157  * Initialise min_free_kbytes.
6158  *
6159  * For small machines we want it small (128k min).  For large machines
6160  * we want it large (64MB max).  But it is not linear, because network
6161  * bandwidth does not increase linearly with machine size.  We use
6162  *
6163  *      min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
6164  *      min_free_kbytes = sqrt(lowmem_kbytes * 16)
6165  *
6166  * which yields
6167  *
6168  * 16MB:        512k
6169  * 32MB:        724k
6170  * 64MB:        1024k
6171  * 128MB:       1448k
6172  * 256MB:       2048k
6173  * 512MB:       2896k
6174  * 1024MB:      4096k
6175  * 2048MB:      5792k
6176  * 4096MB:      8192k
6177  * 8192MB:      11584k
6178  * 16384MB:     16384k
6179  */
6180 int __meminit init_per_zone_wmark_min(void)
6181 {
6182         unsigned long lowmem_kbytes;
6183         int new_min_free_kbytes;
6184
6185         lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
6186         new_min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
6187
6188         if (new_min_free_kbytes > user_min_free_kbytes) {
6189                 min_free_kbytes = new_min_free_kbytes;
6190                 if (min_free_kbytes < 128)
6191                         min_free_kbytes = 128;
6192                 if (min_free_kbytes > 65536)
6193                         min_free_kbytes = 65536;
6194         } else {
6195                 pr_warn("min_free_kbytes is not updated to %d because user defined value %d is preferred\n",
6196                                 new_min_free_kbytes, user_min_free_kbytes);
6197         }
6198         setup_per_zone_wmarks();
6199         refresh_zone_stat_thresholds();
6200         setup_per_zone_lowmem_reserve();
6201         setup_per_zone_inactive_ratio();
6202         return 0;
6203 }
6204 core_initcall(init_per_zone_wmark_min)
6205
6206 /*
6207  * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
6208  *      that we can call two helper functions whenever min_free_kbytes
6209  *      or extra_free_kbytes changes.
6210  */
6211 int min_free_kbytes_sysctl_handler(struct ctl_table *table, int write,
6212         void __user *buffer, size_t *length, loff_t *ppos)
6213 {
6214         int rc;
6215
6216         rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
6217         if (rc)
6218                 return rc;
6219
6220         if (write) {
6221                 user_min_free_kbytes = min_free_kbytes;
6222                 setup_per_zone_wmarks();
6223         }
6224         return 0;
6225 }
6226
6227 #ifdef CONFIG_NUMA
6228 int sysctl_min_unmapped_ratio_sysctl_handler(struct ctl_table *table, int write,
6229         void __user *buffer, size_t *length, loff_t *ppos)
6230 {
6231         struct zone *zone;
6232         int rc;
6233
6234         rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
6235         if (rc)
6236                 return rc;
6237
6238         for_each_zone(zone)
6239                 zone->min_unmapped_pages = (zone->managed_pages *
6240                                 sysctl_min_unmapped_ratio) / 100;
6241         return 0;
6242 }
6243
6244 int sysctl_min_slab_ratio_sysctl_handler(struct ctl_table *table, int write,
6245         void __user *buffer, size_t *length, loff_t *ppos)
6246 {
6247         struct zone *zone;
6248         int rc;
6249
6250         rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
6251         if (rc)
6252                 return rc;
6253
6254         for_each_zone(zone)
6255                 zone->min_slab_pages = (zone->managed_pages *
6256                                 sysctl_min_slab_ratio) / 100;
6257         return 0;
6258 }
6259 #endif
6260
6261 /*
6262  * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
6263  *      proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
6264  *      whenever sysctl_lowmem_reserve_ratio changes.
6265  *
6266  * The reserve ratio obviously has absolutely no relation with the
6267  * minimum watermarks. The lowmem reserve ratio can only make sense
6268  * if in function of the boot time zone sizes.
6269  */
6270 int lowmem_reserve_ratio_sysctl_handler(struct ctl_table *table, int write,
6271         void __user *buffer, size_t *length, loff_t *ppos)
6272 {
6273         proc_dointvec_minmax(table, write, buffer, length, ppos);
6274         setup_per_zone_lowmem_reserve();
6275         return 0;
6276 }
6277
6278 /*
6279  * percpu_pagelist_fraction - changes the pcp->high for each zone on each
6280  * cpu.  It is the fraction of total pages in each zone that a hot per cpu
6281  * pagelist can have before it gets flushed back to buddy allocator.
6282  */
6283 int percpu_pagelist_fraction_sysctl_handler(struct ctl_table *table, int write,
6284         void __user *buffer, size_t *length, loff_t *ppos)
6285 {
6286         struct zone *zone;
6287         int old_percpu_pagelist_fraction;
6288         int ret;
6289
6290         mutex_lock(&pcp_batch_high_lock);
6291         old_percpu_pagelist_fraction = percpu_pagelist_fraction;
6292
6293         ret = proc_dointvec_minmax(table, write, buffer, length, ppos);
6294         if (!write || ret < 0)
6295                 goto out;
6296
6297         /* Sanity checking to avoid pcp imbalance */
6298         if (percpu_pagelist_fraction &&
6299             percpu_pagelist_fraction < MIN_PERCPU_PAGELIST_FRACTION) {
6300                 percpu_pagelist_fraction = old_percpu_pagelist_fraction;
6301                 ret = -EINVAL;
6302                 goto out;
6303         }
6304
6305         /* No change? */
6306         if (percpu_pagelist_fraction == old_percpu_pagelist_fraction)
6307                 goto out;
6308
6309         for_each_populated_zone(zone) {
6310                 unsigned int cpu;
6311
6312                 for_each_possible_cpu(cpu)
6313                         pageset_set_high_and_batch(zone,
6314                                         per_cpu_ptr(zone->pageset, cpu));
6315         }
6316 out:
6317         mutex_unlock(&pcp_batch_high_lock);
6318         return ret;
6319 }
6320
6321 #ifdef CONFIG_NUMA
6322 int hashdist = HASHDIST_DEFAULT;
6323
6324 static int __init set_hashdist(char *str)
6325 {
6326         if (!str)
6327                 return 0;
6328         hashdist = simple_strtoul(str, &str, 0);
6329         return 1;
6330 }
6331 __setup("hashdist=", set_hashdist);
6332 #endif
6333
6334 /*
6335  * allocate a large system hash table from bootmem
6336  * - it is assumed that the hash table must contain an exact power-of-2
6337  *   quantity of entries
6338  * - limit is the number of hash buckets, not the total allocation size
6339  */
6340 void *__init alloc_large_system_hash(const char *tablename,
6341                                      unsigned long bucketsize,
6342                                      unsigned long numentries,
6343                                      int scale,
6344                                      int flags,
6345                                      unsigned int *_hash_shift,
6346                                      unsigned int *_hash_mask,
6347                                      unsigned long low_limit,
6348                                      unsigned long high_limit)
6349 {
6350         unsigned long long max = high_limit;
6351         unsigned long log2qty, size;
6352         void *table = NULL;
6353
6354         /* allow the kernel cmdline to have a say */
6355         if (!numentries) {
6356                 /* round applicable memory size up to nearest megabyte */
6357                 numentries = nr_kernel_pages;
6358
6359                 /* It isn't necessary when PAGE_SIZE >= 1MB */
6360                 if (PAGE_SHIFT < 20)
6361                         numentries = round_up(numentries, (1<<20)/PAGE_SIZE);
6362
6363                 /* limit to 1 bucket per 2^scale bytes of low memory */
6364                 if (scale > PAGE_SHIFT)
6365                         numentries >>= (scale - PAGE_SHIFT);
6366                 else
6367                         numentries <<= (PAGE_SHIFT - scale);
6368
6369                 /* Make sure we've got at least a 0-order allocation.. */
6370                 if (unlikely(flags & HASH_SMALL)) {
6371                         /* Makes no sense without HASH_EARLY */
6372                         WARN_ON(!(flags & HASH_EARLY));
6373                         if (!(numentries >> *_hash_shift)) {
6374                                 numentries = 1UL << *_hash_shift;
6375                                 BUG_ON(!numentries);
6376                         }
6377                 } else if (unlikely((numentries * bucketsize) < PAGE_SIZE))
6378                         numentries = PAGE_SIZE / bucketsize;
6379         }
6380         numentries = roundup_pow_of_two(numentries);
6381
6382         /* limit allocation size to 1/16 total memory by default */
6383         if (max == 0) {
6384                 max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
6385                 do_div(max, bucketsize);
6386         }
6387         max = min(max, 0x80000000ULL);
6388
6389         if (numentries < low_limit)
6390                 numentries = low_limit;
6391         if (numentries > max)
6392                 numentries = max;
6393
6394         log2qty = ilog2(numentries);
6395
6396         do {
6397                 size = bucketsize << log2qty;
6398                 if (flags & HASH_EARLY)
6399                         table = memblock_virt_alloc_nopanic(size, 0);
6400                 else if (hashdist)
6401                         table = __vmalloc(size, GFP_ATOMIC, PAGE_KERNEL);
6402                 else {
6403                         /*
6404                          * If bucketsize is not a power-of-two, we may free
6405                          * some pages at the end of hash table which
6406                          * alloc_pages_exact() automatically does
6407                          */
6408                         if (get_order(size) < MAX_ORDER) {
6409                                 table = alloc_pages_exact(size, GFP_ATOMIC);
6410                                 kmemleak_alloc(table, size, 1, GFP_ATOMIC);
6411                         }
6412                 }
6413         } while (!table && size > PAGE_SIZE && --log2qty);
6414
6415         if (!table)
6416                 panic("Failed to allocate %s hash table\n", tablename);
6417
6418         printk(KERN_INFO "%s hash table entries: %ld (order: %d, %lu bytes)\n",
6419                tablename,
6420                (1UL << log2qty),
6421                ilog2(size) - PAGE_SHIFT,
6422                size);
6423
6424         if (_hash_shift)
6425                 *_hash_shift = log2qty;
6426         if (_hash_mask)
6427                 *_hash_mask = (1 << log2qty) - 1;
6428
6429         return table;
6430 }
6431
6432 /* Return a pointer to the bitmap storing bits affecting a block of pages */
6433 static inline unsigned long *get_pageblock_bitmap(struct zone *zone,
6434                                                         unsigned long pfn)
6435 {
6436 #ifdef CONFIG_SPARSEMEM
6437         return __pfn_to_section(pfn)->pageblock_flags;
6438 #else
6439         return zone->pageblock_flags;
6440 #endif /* CONFIG_SPARSEMEM */
6441 }
6442
6443 static inline int pfn_to_bitidx(struct zone *zone, unsigned long pfn)
6444 {
6445 #ifdef CONFIG_SPARSEMEM
6446         pfn &= (PAGES_PER_SECTION-1);
6447         return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
6448 #else
6449         pfn = pfn - round_down(zone->zone_start_pfn, pageblock_nr_pages);
6450         return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
6451 #endif /* CONFIG_SPARSEMEM */
6452 }
6453
6454 /**
6455  * get_pfnblock_flags_mask - Return the requested group of flags for the pageblock_nr_pages block of pages
6456  * @page: The page within the block of interest
6457  * @pfn: The target page frame number
6458  * @end_bitidx: The last bit of interest to retrieve
6459  * @mask: mask of bits that the caller is interested in
6460  *
6461  * Return: pageblock_bits flags
6462  */
6463 unsigned long get_pfnblock_flags_mask(struct page *page, unsigned long pfn,
6464                                         unsigned long end_bitidx,
6465                                         unsigned long mask)
6466 {
6467         struct zone *zone;
6468         unsigned long *bitmap;
6469         unsigned long bitidx, word_bitidx;
6470         unsigned long word;
6471
6472         zone = page_zone(page);
6473         bitmap = get_pageblock_bitmap(zone, pfn);
6474         bitidx = pfn_to_bitidx(zone, pfn);
6475         word_bitidx = bitidx / BITS_PER_LONG;
6476         bitidx &= (BITS_PER_LONG-1);
6477
6478         word = bitmap[word_bitidx];
6479         bitidx += end_bitidx;
6480         return (word >> (BITS_PER_LONG - bitidx - 1)) & mask;
6481 }
6482
6483 /**
6484  * set_pfnblock_flags_mask - Set the requested group of flags for a pageblock_nr_pages block of pages
6485  * @page: The page within the block of interest
6486  * @flags: The flags to set
6487  * @pfn: The target page frame number
6488  * @end_bitidx: The last bit of interest
6489  * @mask: mask of bits that the caller is interested in
6490  */
6491 void set_pfnblock_flags_mask(struct page *page, unsigned long flags,
6492                                         unsigned long pfn,
6493                                         unsigned long end_bitidx,
6494                                         unsigned long mask)
6495 {
6496         struct zone *zone;
6497         unsigned long *bitmap;
6498         unsigned long bitidx, word_bitidx;
6499         unsigned long old_word, word;
6500
6501         BUILD_BUG_ON(NR_PAGEBLOCK_BITS != 4);
6502
6503         zone = page_zone(page);
6504         bitmap = get_pageblock_bitmap(zone, pfn);
6505         bitidx = pfn_to_bitidx(zone, pfn);
6506         word_bitidx = bitidx / BITS_PER_LONG;
6507         bitidx &= (BITS_PER_LONG-1);
6508
6509         VM_BUG_ON_PAGE(!zone_spans_pfn(zone, pfn), page);
6510
6511         bitidx += end_bitidx;
6512         mask <<= (BITS_PER_LONG - bitidx - 1);
6513         flags <<= (BITS_PER_LONG - bitidx - 1);
6514
6515         word = READ_ONCE(bitmap[word_bitidx]);
6516         for (;;) {
6517                 old_word = cmpxchg(&bitmap[word_bitidx], word, (word & ~mask) | flags);
6518                 if (word == old_word)
6519                         break;
6520                 word = old_word;
6521         }
6522 }
6523
6524 /*
6525  * This function checks whether pageblock includes unmovable pages or not.
6526  * If @count is not zero, it is okay to include less @count unmovable pages
6527  *
6528  * PageLRU check without isolation or lru_lock could race so that
6529  * MIGRATE_MOVABLE block might include unmovable pages. It means you can't
6530  * expect this function should be exact.
6531  */
6532 bool has_unmovable_pages(struct zone *zone, struct page *page, int count,
6533                          bool skip_hwpoisoned_pages)
6534 {
6535         unsigned long pfn, iter, found;
6536         int mt;
6537
6538         /*
6539          * For avoiding noise data, lru_add_drain_all() should be called
6540          * If ZONE_MOVABLE, the zone never contains unmovable pages
6541          */
6542         if (zone_idx(zone) == ZONE_MOVABLE)
6543                 return false;
6544         mt = get_pageblock_migratetype(page);
6545         if (mt == MIGRATE_MOVABLE || is_migrate_cma(mt))
6546                 return false;
6547
6548         pfn = page_to_pfn(page);
6549         for (found = 0, iter = 0; iter < pageblock_nr_pages; iter++) {
6550                 unsigned long check = pfn + iter;
6551
6552                 if (!pfn_valid_within(check))
6553                         continue;
6554
6555                 page = pfn_to_page(check);
6556
6557                 /*
6558                  * Hugepages are not in LRU lists, but they're movable.
6559                  * We need not scan over tail pages bacause we don't
6560                  * handle each tail page individually in migration.
6561                  */
6562                 if (PageHuge(page)) {
6563                         iter = round_up(iter + 1, 1<<compound_order(page)) - 1;
6564                         continue;
6565                 }
6566
6567                 /*
6568                  * We can't use page_count without pin a page
6569                  * because another CPU can free compound page.
6570                  * This check already skips compound tails of THP
6571                  * because their page->_count is zero at all time.
6572                  */
6573                 if (!atomic_read(&page->_count)) {
6574                         if (PageBuddy(page))
6575                                 iter += (1 << page_order(page)) - 1;
6576                         continue;
6577                 }
6578
6579                 /*
6580                  * The HWPoisoned page may be not in buddy system, and
6581                  * page_count() is not 0.
6582                  */
6583                 if (skip_hwpoisoned_pages && PageHWPoison(page))
6584                         continue;
6585
6586                 if (!PageLRU(page))
6587                         found++;
6588                 /*
6589                  * If there are RECLAIMABLE pages, we need to check
6590                  * it.  But now, memory offline itself doesn't call
6591                  * shrink_node_slabs() and it still to be fixed.
6592                  */
6593                 /*
6594                  * If the page is not RAM, page_count()should be 0.
6595                  * we don't need more check. This is an _used_ not-movable page.
6596                  *
6597                  * The problematic thing here is PG_reserved pages. PG_reserved
6598                  * is set to both of a memory hole page and a _used_ kernel
6599                  * page at boot.
6600                  */
6601                 if (found > count)
6602                         return true;
6603         }
6604         return false;
6605 }
6606
6607 bool is_pageblock_removable_nolock(struct page *page)
6608 {
6609         struct zone *zone;
6610         unsigned long pfn;
6611
6612         /*
6613          * We have to be careful here because we are iterating over memory
6614          * sections which are not zone aware so we might end up outside of
6615          * the zone but still within the section.
6616          * We have to take care about the node as well. If the node is offline
6617          * its NODE_DATA will be NULL - see page_zone.
6618          */
6619         if (!node_online(page_to_nid(page)))
6620                 return false;
6621
6622         zone = page_zone(page);
6623         pfn = page_to_pfn(page);
6624         if (!zone_spans_pfn(zone, pfn))
6625                 return false;
6626
6627         return !has_unmovable_pages(zone, page, 0, true);
6628 }
6629
6630 #ifdef CONFIG_CMA
6631
6632 static unsigned long pfn_max_align_down(unsigned long pfn)
6633 {
6634         return pfn & ~(max_t(unsigned long, MAX_ORDER_NR_PAGES,
6635                              pageblock_nr_pages) - 1);
6636 }
6637
6638 static unsigned long pfn_max_align_up(unsigned long pfn)
6639 {
6640         return ALIGN(pfn, max_t(unsigned long, MAX_ORDER_NR_PAGES,
6641                                 pageblock_nr_pages));
6642 }
6643
6644 /* [start, end) must belong to a single zone. */
6645 static int __alloc_contig_migrate_range(struct compact_control *cc,
6646                                         unsigned long start, unsigned long end)
6647 {
6648         /* This function is based on compact_zone() from compaction.c. */
6649         unsigned long nr_reclaimed;
6650         unsigned long pfn = start;
6651         unsigned int tries = 0;
6652         int ret = 0;
6653
6654         migrate_prep();
6655
6656         while (pfn < end || !list_empty(&cc->migratepages)) {
6657                 if (fatal_signal_pending(current)) {
6658                         ret = -EINTR;
6659                         break;
6660                 }
6661
6662                 if (list_empty(&cc->migratepages)) {
6663                         cc->nr_migratepages = 0;
6664                         pfn = isolate_migratepages_range(cc, pfn, end);
6665                         if (!pfn) {
6666                                 ret = -EINTR;
6667                                 break;
6668                         }
6669                         tries = 0;
6670                 } else if (++tries == 5) {
6671                         ret = ret < 0 ? ret : -EBUSY;
6672                         break;
6673                 }
6674
6675                 nr_reclaimed = reclaim_clean_pages_from_list(cc->zone,
6676                                                         &cc->migratepages);
6677                 cc->nr_migratepages -= nr_reclaimed;
6678
6679                 ret = migrate_pages(&cc->migratepages, alloc_migrate_target,
6680                                     NULL, 0, cc->mode, MR_CMA);
6681         }
6682         if (ret < 0) {
6683                 putback_movable_pages(&cc->migratepages);
6684                 return ret;
6685         }
6686         return 0;
6687 }
6688
6689 /**
6690  * alloc_contig_range() -- tries to allocate given range of pages
6691  * @start:      start PFN to allocate
6692  * @end:        one-past-the-last PFN to allocate
6693  * @migratetype:        migratetype of the underlaying pageblocks (either
6694  *                      #MIGRATE_MOVABLE or #MIGRATE_CMA).  All pageblocks
6695  *                      in range must have the same migratetype and it must
6696  *                      be either of the two.
6697  *
6698  * The PFN range does not have to be pageblock or MAX_ORDER_NR_PAGES
6699  * aligned, however it's the caller's responsibility to guarantee that
6700  * we are the only thread that changes migrate type of pageblocks the
6701  * pages fall in.
6702  *
6703  * The PFN range must belong to a single zone.
6704  *
6705  * Returns zero on success or negative error code.  On success all
6706  * pages which PFN is in [start, end) are allocated for the caller and
6707  * need to be freed with free_contig_range().
6708  */
6709 int alloc_contig_range(unsigned long start, unsigned long end,
6710                        unsigned migratetype)
6711 {
6712         unsigned long outer_start, outer_end;
6713         unsigned int order;
6714         int ret = 0;
6715
6716         struct compact_control cc = {
6717                 .nr_migratepages = 0,
6718                 .order = -1,
6719                 .zone = page_zone(pfn_to_page(start)),
6720                 .mode = MIGRATE_SYNC,
6721                 .ignore_skip_hint = true,
6722         };
6723         INIT_LIST_HEAD(&cc.migratepages);
6724
6725         /*
6726          * What we do here is we mark all pageblocks in range as
6727          * MIGRATE_ISOLATE.  Because pageblock and max order pages may
6728          * have different sizes, and due to the way page allocator
6729          * work, we align the range to biggest of the two pages so
6730          * that page allocator won't try to merge buddies from
6731          * different pageblocks and change MIGRATE_ISOLATE to some
6732          * other migration type.
6733          *
6734          * Once the pageblocks are marked as MIGRATE_ISOLATE, we
6735          * migrate the pages from an unaligned range (ie. pages that
6736          * we are interested in).  This will put all the pages in
6737          * range back to page allocator as MIGRATE_ISOLATE.
6738          *
6739          * When this is done, we take the pages in range from page
6740          * allocator removing them from the buddy system.  This way
6741          * page allocator will never consider using them.
6742          *
6743          * This lets us mark the pageblocks back as
6744          * MIGRATE_CMA/MIGRATE_MOVABLE so that free pages in the
6745          * aligned range but not in the unaligned, original range are
6746          * put back to page allocator so that buddy can use them.
6747          */
6748
6749         ret = start_isolate_page_range(pfn_max_align_down(start),
6750                                        pfn_max_align_up(end), migratetype,
6751                                        false);
6752         if (ret)
6753                 return ret;
6754
6755         ret = __alloc_contig_migrate_range(&cc, start, end);
6756         if (ret)
6757                 goto done;
6758
6759         /*
6760          * Pages from [start, end) are within a MAX_ORDER_NR_PAGES
6761          * aligned blocks that are marked as MIGRATE_ISOLATE.  What's
6762          * more, all pages in [start, end) are free in page allocator.
6763          * What we are going to do is to allocate all pages from
6764          * [start, end) (that is remove them from page allocator).
6765          *
6766          * The only problem is that pages at the beginning and at the
6767          * end of interesting range may be not aligned with pages that
6768          * page allocator holds, ie. they can be part of higher order
6769          * pages.  Because of this, we reserve the bigger range and
6770          * once this is done free the pages we are not interested in.
6771          *
6772          * We don't have to hold zone->lock here because the pages are
6773          * isolated thus they won't get removed from buddy.
6774          */
6775
6776         lru_add_drain_all();
6777         drain_all_pages(cc.zone);
6778
6779         order = 0;
6780         outer_start = start;
6781         while (!PageBuddy(pfn_to_page(outer_start))) {
6782                 if (++order >= MAX_ORDER) {
6783                         ret = -EBUSY;
6784                         goto done;
6785                 }
6786                 outer_start &= ~0UL << order;
6787         }
6788
6789         /* Make sure the range is really isolated. */
6790         if (test_pages_isolated(outer_start, end, false)) {
6791                 pr_info("%s: [%lx, %lx) PFNs busy\n",
6792                         __func__, outer_start, end);
6793                 ret = -EBUSY;
6794                 goto done;
6795         }
6796
6797         /* Grab isolated pages from freelists. */
6798         outer_end = isolate_freepages_range(&cc, outer_start, end);
6799         if (!outer_end) {
6800                 ret = -EBUSY;
6801                 goto done;
6802         }
6803
6804         /* Free head and tail (if any) */
6805         if (start != outer_start)
6806                 free_contig_range(outer_start, start - outer_start);
6807         if (end != outer_end)
6808                 free_contig_range(end, outer_end - end);
6809
6810 done:
6811         undo_isolate_page_range(pfn_max_align_down(start),
6812                                 pfn_max_align_up(end), migratetype);
6813         return ret;
6814 }
6815
6816 void free_contig_range(unsigned long pfn, unsigned nr_pages)
6817 {
6818         unsigned int count = 0;
6819
6820         for (; nr_pages--; pfn++) {
6821                 struct page *page = pfn_to_page(pfn);
6822
6823                 count += page_count(page) != 1;
6824                 __free_page(page);
6825         }
6826         WARN(count != 0, "%d pages are still in use!\n", count);
6827 }
6828 #endif
6829
6830 #ifdef CONFIG_MEMORY_HOTPLUG
6831 /*
6832  * The zone indicated has a new number of managed_pages; batch sizes and percpu
6833  * page high values need to be recalulated.
6834  */
6835 void __meminit zone_pcp_update(struct zone *zone)
6836 {
6837         unsigned cpu;
6838         mutex_lock(&pcp_batch_high_lock);
6839         for_each_possible_cpu(cpu)
6840                 pageset_set_high_and_batch(zone,
6841                                 per_cpu_ptr(zone->pageset, cpu));
6842         mutex_unlock(&pcp_batch_high_lock);
6843 }
6844 #endif
6845
6846 void zone_pcp_reset(struct zone *zone)
6847 {
6848         unsigned long flags;
6849         int cpu;
6850         struct per_cpu_pageset *pset;
6851
6852         /* avoid races with drain_pages()  */
6853         local_irq_save(flags);
6854         if (zone->pageset != &boot_pageset) {
6855                 for_each_online_cpu(cpu) {
6856                         pset = per_cpu_ptr(zone->pageset, cpu);
6857                         drain_zonestat(zone, pset);
6858                 }
6859                 free_percpu(zone->pageset);
6860                 zone->pageset = &boot_pageset;
6861         }
6862         local_irq_restore(flags);
6863 }
6864
6865 #ifdef CONFIG_MEMORY_HOTREMOVE
6866 /*
6867  * All pages in the range must be isolated before calling this.
6868  */
6869 void
6870 __offline_isolated_pages(unsigned long start_pfn, unsigned long end_pfn)
6871 {
6872         struct page *page;
6873         struct zone *zone;
6874         unsigned int order, i;
6875         unsigned long pfn;
6876         unsigned long flags;
6877         /* find the first valid pfn */
6878         for (pfn = start_pfn; pfn < end_pfn; pfn++)
6879                 if (pfn_valid(pfn))
6880                         break;
6881         if (pfn == end_pfn)
6882                 return;
6883         zone = page_zone(pfn_to_page(pfn));
6884         spin_lock_irqsave(&zone->lock, flags);
6885         pfn = start_pfn;
6886         while (pfn < end_pfn) {
6887                 if (!pfn_valid(pfn)) {
6888                         pfn++;
6889                         continue;
6890                 }
6891                 page = pfn_to_page(pfn);
6892                 /*
6893                  * The HWPoisoned page may be not in buddy system, and
6894                  * page_count() is not 0.
6895                  */
6896                 if (unlikely(!PageBuddy(page) && PageHWPoison(page))) {
6897                         pfn++;
6898                         SetPageReserved(page);
6899                         continue;
6900                 }
6901
6902                 BUG_ON(page_count(page));
6903                 BUG_ON(!PageBuddy(page));
6904                 order = page_order(page);
6905 #ifdef CONFIG_DEBUG_VM
6906                 printk(KERN_INFO "remove from free list %lx %d %lx\n",
6907                        pfn, 1 << order, end_pfn);
6908 #endif
6909                 list_del(&page->lru);
6910                 rmv_page_order(page);
6911                 zone->free_area[order].nr_free--;
6912                 for (i = 0; i < (1 << order); i++)
6913                         SetPageReserved((page+i));
6914                 pfn += (1 << order);
6915         }
6916         spin_unlock_irqrestore(&zone->lock, flags);
6917 }
6918 #endif
6919
6920 #ifdef CONFIG_MEMORY_FAILURE
6921 bool is_free_buddy_page(struct page *page)
6922 {
6923         struct zone *zone = page_zone(page);
6924         unsigned long pfn = page_to_pfn(page);
6925         unsigned long flags;
6926         unsigned int order;
6927
6928         spin_lock_irqsave(&zone->lock, flags);
6929         for (order = 0; order < MAX_ORDER; order++) {
6930                 struct page *page_head = page - (pfn & ((1 << order) - 1));
6931
6932                 if (PageBuddy(page_head) && page_order(page_head) >= order)
6933                         break;
6934         }
6935         spin_unlock_irqrestore(&zone->lock, flags);
6936
6937         return order < MAX_ORDER;
6938 }
6939 #endif