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