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