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