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