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