OSDN Git Service

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