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