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