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