]> www.pilppa.org Git - linux-2.6-omap-h63xx.git/blob - mm/page_alloc.c
Do not depend on MAX_ORDER when grouping pages by mobility
[linux-2.6-omap-h63xx.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/bootmem.h>
23 #include <linux/compiler.h>
24 #include <linux/kernel.h>
25 #include <linux/module.h>
26 #include <linux/suspend.h>
27 #include <linux/pagevec.h>
28 #include <linux/blkdev.h>
29 #include <linux/slab.h>
30 #include <linux/notifier.h>
31 #include <linux/topology.h>
32 #include <linux/sysctl.h>
33 #include <linux/cpu.h>
34 #include <linux/cpuset.h>
35 #include <linux/memory_hotplug.h>
36 #include <linux/nodemask.h>
37 #include <linux/vmalloc.h>
38 #include <linux/mempolicy.h>
39 #include <linux/stop_machine.h>
40 #include <linux/sort.h>
41 #include <linux/pfn.h>
42 #include <linux/backing-dev.h>
43 #include <linux/fault-inject.h>
44
45 #include <asm/tlbflush.h>
46 #include <asm/div64.h>
47 #include "internal.h"
48
49 /*
50  * Array of node states.
51  */
52 nodemask_t node_states[NR_NODE_STATES] __read_mostly = {
53         [N_POSSIBLE] = NODE_MASK_ALL,
54         [N_ONLINE] = { { [0] = 1UL } },
55 #ifndef CONFIG_NUMA
56         [N_NORMAL_MEMORY] = { { [0] = 1UL } },
57 #ifdef CONFIG_HIGHMEM
58         [N_HIGH_MEMORY] = { { [0] = 1UL } },
59 #endif
60         [N_CPU] = { { [0] = 1UL } },
61 #endif  /* NUMA */
62 };
63 EXPORT_SYMBOL(node_states);
64
65 unsigned long totalram_pages __read_mostly;
66 unsigned long totalreserve_pages __read_mostly;
67 long nr_swap_pages;
68 int percpu_pagelist_fraction;
69
70 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
71 int pageblock_order __read_mostly;
72 #endif
73
74 static void __free_pages_ok(struct page *page, unsigned int order);
75
76 /*
77  * results with 256, 32 in the lowmem_reserve sysctl:
78  *      1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
79  *      1G machine -> (16M dma, 784M normal, 224M high)
80  *      NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
81  *      HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
82  *      HIGHMEM allocation will (224M+784M)/256 of ram reserved in ZONE_DMA
83  *
84  * TBD: should special case ZONE_DMA32 machines here - in those we normally
85  * don't need any ZONE_NORMAL reservation
86  */
87 int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES-1] = {
88 #ifdef CONFIG_ZONE_DMA
89          256,
90 #endif
91 #ifdef CONFIG_ZONE_DMA32
92          256,
93 #endif
94 #ifdef CONFIG_HIGHMEM
95          32,
96 #endif
97          32,
98 };
99
100 EXPORT_SYMBOL(totalram_pages);
101
102 static char * const zone_names[MAX_NR_ZONES] = {
103 #ifdef CONFIG_ZONE_DMA
104          "DMA",
105 #endif
106 #ifdef CONFIG_ZONE_DMA32
107          "DMA32",
108 #endif
109          "Normal",
110 #ifdef CONFIG_HIGHMEM
111          "HighMem",
112 #endif
113          "Movable",
114 };
115
116 int min_free_kbytes = 1024;
117
118 unsigned long __meminitdata nr_kernel_pages;
119 unsigned long __meminitdata nr_all_pages;
120 static unsigned long __meminitdata dma_reserve;
121
122 #ifdef CONFIG_ARCH_POPULATES_NODE_MAP
123   /*
124    * MAX_ACTIVE_REGIONS determines the maxmimum number of distinct
125    * ranges of memory (RAM) that may be registered with add_active_range().
126    * Ranges passed to add_active_range() will be merged if possible
127    * so the number of times add_active_range() can be called is
128    * related to the number of nodes and the number of holes
129    */
130   #ifdef CONFIG_MAX_ACTIVE_REGIONS
131     /* Allow an architecture to set MAX_ACTIVE_REGIONS to save memory */
132     #define MAX_ACTIVE_REGIONS CONFIG_MAX_ACTIVE_REGIONS
133   #else
134     #if MAX_NUMNODES >= 32
135       /* If there can be many nodes, allow up to 50 holes per node */
136       #define MAX_ACTIVE_REGIONS (MAX_NUMNODES*50)
137     #else
138       /* By default, allow up to 256 distinct regions */
139       #define MAX_ACTIVE_REGIONS 256
140     #endif
141   #endif
142
143   static struct node_active_region __meminitdata early_node_map[MAX_ACTIVE_REGIONS];
144   static int __meminitdata nr_nodemap_entries;
145   static unsigned long __meminitdata arch_zone_lowest_possible_pfn[MAX_NR_ZONES];
146   static unsigned long __meminitdata arch_zone_highest_possible_pfn[MAX_NR_ZONES];
147 #ifdef CONFIG_MEMORY_HOTPLUG_RESERVE
148   static unsigned long __meminitdata node_boundary_start_pfn[MAX_NUMNODES];
149   static unsigned long __meminitdata node_boundary_end_pfn[MAX_NUMNODES];
150 #endif /* CONFIG_MEMORY_HOTPLUG_RESERVE */
151   unsigned long __initdata required_kernelcore;
152   unsigned long __initdata required_movablecore;
153   unsigned long __meminitdata zone_movable_pfn[MAX_NUMNODES];
154
155   /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
156   int movable_zone;
157   EXPORT_SYMBOL(movable_zone);
158 #endif /* CONFIG_ARCH_POPULATES_NODE_MAP */
159
160 #if MAX_NUMNODES > 1
161 int nr_node_ids __read_mostly = MAX_NUMNODES;
162 EXPORT_SYMBOL(nr_node_ids);
163 #endif
164
165 int page_group_by_mobility_disabled __read_mostly;
166
167 static inline int get_pageblock_migratetype(struct page *page)
168 {
169         if (unlikely(page_group_by_mobility_disabled))
170                 return MIGRATE_UNMOVABLE;
171
172         return get_pageblock_flags_group(page, PB_migrate, PB_migrate_end);
173 }
174
175 static void set_pageblock_migratetype(struct page *page, int migratetype)
176 {
177         set_pageblock_flags_group(page, (unsigned long)migratetype,
178                                         PB_migrate, PB_migrate_end);
179 }
180
181 static inline int allocflags_to_migratetype(gfp_t gfp_flags)
182 {
183         WARN_ON((gfp_flags & GFP_MOVABLE_MASK) == GFP_MOVABLE_MASK);
184
185         if (unlikely(page_group_by_mobility_disabled))
186                 return MIGRATE_UNMOVABLE;
187
188         /* Cluster based on mobility */
189         return (((gfp_flags & __GFP_MOVABLE) != 0) << 1) |
190                 ((gfp_flags & __GFP_RECLAIMABLE) != 0);
191 }
192
193 #ifdef CONFIG_DEBUG_VM
194 static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
195 {
196         int ret = 0;
197         unsigned seq;
198         unsigned long pfn = page_to_pfn(page);
199
200         do {
201                 seq = zone_span_seqbegin(zone);
202                 if (pfn >= zone->zone_start_pfn + zone->spanned_pages)
203                         ret = 1;
204                 else if (pfn < zone->zone_start_pfn)
205                         ret = 1;
206         } while (zone_span_seqretry(zone, seq));
207
208         return ret;
209 }
210
211 static int page_is_consistent(struct zone *zone, struct page *page)
212 {
213         if (!pfn_valid_within(page_to_pfn(page)))
214                 return 0;
215         if (zone != page_zone(page))
216                 return 0;
217
218         return 1;
219 }
220 /*
221  * Temporary debugging check for pages not lying within a given zone.
222  */
223 static int bad_range(struct zone *zone, struct page *page)
224 {
225         if (page_outside_zone_boundaries(zone, page))
226                 return 1;
227         if (!page_is_consistent(zone, page))
228                 return 1;
229
230         return 0;
231 }
232 #else
233 static inline int bad_range(struct zone *zone, struct page *page)
234 {
235         return 0;
236 }
237 #endif
238
239 static void bad_page(struct page *page)
240 {
241         printk(KERN_EMERG "Bad page state in process '%s'\n"
242                 KERN_EMERG "page:%p flags:0x%0*lx mapping:%p mapcount:%d count:%d\n"
243                 KERN_EMERG "Trying to fix it up, but a reboot is needed\n"
244                 KERN_EMERG "Backtrace:\n",
245                 current->comm, page, (int)(2*sizeof(unsigned long)),
246                 (unsigned long)page->flags, page->mapping,
247                 page_mapcount(page), page_count(page));
248         dump_stack();
249         page->flags &= ~(1 << PG_lru    |
250                         1 << PG_private |
251                         1 << PG_locked  |
252                         1 << PG_active  |
253                         1 << PG_dirty   |
254                         1 << PG_reclaim |
255                         1 << PG_slab    |
256                         1 << PG_swapcache |
257                         1 << PG_writeback |
258                         1 << PG_buddy );
259         set_page_count(page, 0);
260         reset_page_mapcount(page);
261         page->mapping = NULL;
262         add_taint(TAINT_BAD_PAGE);
263 }
264
265 /*
266  * Higher-order pages are called "compound pages".  They are structured thusly:
267  *
268  * The first PAGE_SIZE page is called the "head page".
269  *
270  * The remaining PAGE_SIZE pages are called "tail pages".
271  *
272  * All pages have PG_compound set.  All pages have their ->private pointing at
273  * the head page (even the head page has this).
274  *
275  * The first tail page's ->lru.next holds the address of the compound page's
276  * put_page() function.  Its ->lru.prev holds the order of allocation.
277  * This usage means that zero-order pages may not be compound.
278  */
279
280 static void free_compound_page(struct page *page)
281 {
282         __free_pages_ok(page, compound_order(page));
283 }
284
285 static void prep_compound_page(struct page *page, unsigned long order)
286 {
287         int i;
288         int nr_pages = 1 << order;
289
290         set_compound_page_dtor(page, free_compound_page);
291         set_compound_order(page, order);
292         __SetPageHead(page);
293         for (i = 1; i < nr_pages; i++) {
294                 struct page *p = page + i;
295
296                 __SetPageTail(p);
297                 p->first_page = page;
298         }
299 }
300
301 static void destroy_compound_page(struct page *page, unsigned long order)
302 {
303         int i;
304         int nr_pages = 1 << order;
305
306         if (unlikely(compound_order(page) != order))
307                 bad_page(page);
308
309         if (unlikely(!PageHead(page)))
310                         bad_page(page);
311         __ClearPageHead(page);
312         for (i = 1; i < nr_pages; i++) {
313                 struct page *p = page + i;
314
315                 if (unlikely(!PageTail(p) |
316                                 (p->first_page != page)))
317                         bad_page(page);
318                 __ClearPageTail(p);
319         }
320 }
321
322 static inline void prep_zero_page(struct page *page, int order, gfp_t gfp_flags)
323 {
324         int i;
325
326         VM_BUG_ON((gfp_flags & (__GFP_WAIT | __GFP_HIGHMEM)) == __GFP_HIGHMEM);
327         /*
328          * clear_highpage() will use KM_USER0, so it's a bug to use __GFP_ZERO
329          * and __GFP_HIGHMEM from hard or soft interrupt context.
330          */
331         VM_BUG_ON((gfp_flags & __GFP_HIGHMEM) && in_interrupt());
332         for (i = 0; i < (1 << order); i++)
333                 clear_highpage(page + i);
334 }
335
336 /*
337  * function for dealing with page's order in buddy system.
338  * zone->lock is already acquired when we use these.
339  * So, we don't need atomic page->flags operations here.
340  */
341 static inline unsigned long page_order(struct page *page)
342 {
343         return page_private(page);
344 }
345
346 static inline void set_page_order(struct page *page, int order)
347 {
348         set_page_private(page, order);
349         __SetPageBuddy(page);
350 }
351
352 static inline void rmv_page_order(struct page *page)
353 {
354         __ClearPageBuddy(page);
355         set_page_private(page, 0);
356 }
357
358 /*
359  * Locate the struct page for both the matching buddy in our
360  * pair (buddy1) and the combined O(n+1) page they form (page).
361  *
362  * 1) Any buddy B1 will have an order O twin B2 which satisfies
363  * the following equation:
364  *     B2 = B1 ^ (1 << O)
365  * For example, if the starting buddy (buddy2) is #8 its order
366  * 1 buddy is #10:
367  *     B2 = 8 ^ (1 << 1) = 8 ^ 2 = 10
368  *
369  * 2) Any buddy B will have an order O+1 parent P which
370  * satisfies the following equation:
371  *     P = B & ~(1 << O)
372  *
373  * Assumption: *_mem_map is contiguous at least up to MAX_ORDER
374  */
375 static inline struct page *
376 __page_find_buddy(struct page *page, unsigned long page_idx, unsigned int order)
377 {
378         unsigned long buddy_idx = page_idx ^ (1 << order);
379
380         return page + (buddy_idx - page_idx);
381 }
382
383 static inline unsigned long
384 __find_combined_index(unsigned long page_idx, unsigned int order)
385 {
386         return (page_idx & ~(1 << order));
387 }
388
389 /*
390  * This function checks whether a page is free && is the buddy
391  * we can do coalesce a page and its buddy if
392  * (a) the buddy is not in a hole &&
393  * (b) the buddy is in the buddy system &&
394  * (c) a page and its buddy have the same order &&
395  * (d) a page and its buddy are in the same zone.
396  *
397  * For recording whether a page is in the buddy system, we use PG_buddy.
398  * Setting, clearing, and testing PG_buddy is serialized by zone->lock.
399  *
400  * For recording page's order, we use page_private(page).
401  */
402 static inline int page_is_buddy(struct page *page, struct page *buddy,
403                                                                 int order)
404 {
405         if (!pfn_valid_within(page_to_pfn(buddy)))
406                 return 0;
407
408         if (page_zone_id(page) != page_zone_id(buddy))
409                 return 0;
410
411         if (PageBuddy(buddy) && page_order(buddy) == order) {
412                 BUG_ON(page_count(buddy) != 0);
413                 return 1;
414         }
415         return 0;
416 }
417
418 /*
419  * Freeing function for a buddy system allocator.
420  *
421  * The concept of a buddy system is to maintain direct-mapped table
422  * (containing bit values) for memory blocks of various "orders".
423  * The bottom level table contains the map for the smallest allocatable
424  * units of memory (here, pages), and each level above it describes
425  * pairs of units from the levels below, hence, "buddies".
426  * At a high level, all that happens here is marking the table entry
427  * at the bottom level available, and propagating the changes upward
428  * as necessary, plus some accounting needed to play nicely with other
429  * parts of the VM system.
430  * At each level, we keep a list of pages, which are heads of continuous
431  * free pages of length of (1 << order) and marked with PG_buddy. Page's
432  * order is recorded in page_private(page) field.
433  * So when we are allocating or freeing one, we can derive the state of the
434  * other.  That is, if we allocate a small block, and both were   
435  * free, the remainder of the region must be split into blocks.   
436  * If a block is freed, and its buddy is also free, then this
437  * triggers coalescing into a block of larger size.            
438  *
439  * -- wli
440  */
441
442 static inline void __free_one_page(struct page *page,
443                 struct zone *zone, unsigned int order)
444 {
445         unsigned long page_idx;
446         int order_size = 1 << order;
447         int migratetype = get_pageblock_migratetype(page);
448
449         if (unlikely(PageCompound(page)))
450                 destroy_compound_page(page, order);
451
452         page_idx = page_to_pfn(page) & ((1 << MAX_ORDER) - 1);
453
454         VM_BUG_ON(page_idx & (order_size - 1));
455         VM_BUG_ON(bad_range(zone, page));
456
457         __mod_zone_page_state(zone, NR_FREE_PAGES, order_size);
458         while (order < MAX_ORDER-1) {
459                 unsigned long combined_idx;
460                 struct page *buddy;
461
462                 buddy = __page_find_buddy(page, page_idx, order);
463                 if (!page_is_buddy(page, buddy, order))
464                         break;          /* Move the buddy up one level. */
465
466                 list_del(&buddy->lru);
467                 zone->free_area[order].nr_free--;
468                 rmv_page_order(buddy);
469                 combined_idx = __find_combined_index(page_idx, order);
470                 page = page + (combined_idx - page_idx);
471                 page_idx = combined_idx;
472                 order++;
473         }
474         set_page_order(page, order);
475         list_add(&page->lru,
476                 &zone->free_area[order].free_list[migratetype]);
477         zone->free_area[order].nr_free++;
478 }
479
480 static inline int free_pages_check(struct page *page)
481 {
482         if (unlikely(page_mapcount(page) |
483                 (page->mapping != NULL)  |
484                 (page_count(page) != 0)  |
485                 (page->flags & (
486                         1 << PG_lru     |
487                         1 << PG_private |
488                         1 << PG_locked  |
489                         1 << PG_active  |
490                         1 << PG_slab    |
491                         1 << PG_swapcache |
492                         1 << PG_writeback |
493                         1 << PG_reserved |
494                         1 << PG_buddy ))))
495                 bad_page(page);
496         if (PageDirty(page))
497                 __ClearPageDirty(page);
498         /*
499          * For now, we report if PG_reserved was found set, but do not
500          * clear it, and do not free the page.  But we shall soon need
501          * to do more, for when the ZERO_PAGE count wraps negative.
502          */
503         return PageReserved(page);
504 }
505
506 /*
507  * Frees a list of pages. 
508  * Assumes all pages on list are in same zone, and of same order.
509  * count is the number of pages to free.
510  *
511  * If the zone was previously in an "all pages pinned" state then look to
512  * see if this freeing clears that state.
513  *
514  * And clear the zone's pages_scanned counter, to hold off the "all pages are
515  * pinned" detection logic.
516  */
517 static void free_pages_bulk(struct zone *zone, int count,
518                                         struct list_head *list, int order)
519 {
520         spin_lock(&zone->lock);
521         zone->all_unreclaimable = 0;
522         zone->pages_scanned = 0;
523         while (count--) {
524                 struct page *page;
525
526                 VM_BUG_ON(list_empty(list));
527                 page = list_entry(list->prev, struct page, lru);
528                 /* have to delete it as __free_one_page list manipulates */
529                 list_del(&page->lru);
530                 __free_one_page(page, zone, order);
531         }
532         spin_unlock(&zone->lock);
533 }
534
535 static void free_one_page(struct zone *zone, struct page *page, int order)
536 {
537         spin_lock(&zone->lock);
538         zone->all_unreclaimable = 0;
539         zone->pages_scanned = 0;
540         __free_one_page(page, zone, order);
541         spin_unlock(&zone->lock);
542 }
543
544 static void __free_pages_ok(struct page *page, unsigned int order)
545 {
546         unsigned long flags;
547         int i;
548         int reserved = 0;
549
550         for (i = 0 ; i < (1 << order) ; ++i)
551                 reserved += free_pages_check(page + i);
552         if (reserved)
553                 return;
554
555         if (!PageHighMem(page))
556                 debug_check_no_locks_freed(page_address(page),PAGE_SIZE<<order);
557         arch_free_page(page, order);
558         kernel_map_pages(page, 1 << order, 0);
559
560         local_irq_save(flags);
561         __count_vm_events(PGFREE, 1 << order);
562         free_one_page(page_zone(page), page, order);
563         local_irq_restore(flags);
564 }
565
566 /*
567  * permit the bootmem allocator to evade page validation on high-order frees
568  */
569 void fastcall __init __free_pages_bootmem(struct page *page, unsigned int order)
570 {
571         if (order == 0) {
572                 __ClearPageReserved(page);
573                 set_page_count(page, 0);
574                 set_page_refcounted(page);
575                 __free_page(page);
576         } else {
577                 int loop;
578
579                 prefetchw(page);
580                 for (loop = 0; loop < BITS_PER_LONG; loop++) {
581                         struct page *p = &page[loop];
582
583                         if (loop + 1 < BITS_PER_LONG)
584                                 prefetchw(p + 1);
585                         __ClearPageReserved(p);
586                         set_page_count(p, 0);
587                 }
588
589                 set_page_refcounted(page);
590                 __free_pages(page, order);
591         }
592 }
593
594
595 /*
596  * The order of subdivision here is critical for the IO subsystem.
597  * Please do not alter this order without good reasons and regression
598  * testing. Specifically, as large blocks of memory are subdivided,
599  * the order in which smaller blocks are delivered depends on the order
600  * they're subdivided in this function. This is the primary factor
601  * influencing the order in which pages are delivered to the IO
602  * subsystem according to empirical testing, and this is also justified
603  * by considering the behavior of a buddy system containing a single
604  * large block of memory acted on by a series of small allocations.
605  * This behavior is a critical factor in sglist merging's success.
606  *
607  * -- wli
608  */
609 static inline void expand(struct zone *zone, struct page *page,
610         int low, int high, struct free_area *area,
611         int migratetype)
612 {
613         unsigned long size = 1 << high;
614
615         while (high > low) {
616                 area--;
617                 high--;
618                 size >>= 1;
619                 VM_BUG_ON(bad_range(zone, &page[size]));
620                 list_add(&page[size].lru, &area->free_list[migratetype]);
621                 area->nr_free++;
622                 set_page_order(&page[size], high);
623         }
624 }
625
626 /*
627  * This page is about to be returned from the page allocator
628  */
629 static int prep_new_page(struct page *page, int order, gfp_t gfp_flags)
630 {
631         if (unlikely(page_mapcount(page) |
632                 (page->mapping != NULL)  |
633                 (page_count(page) != 0)  |
634                 (page->flags & (
635                         1 << PG_lru     |
636                         1 << PG_private |
637                         1 << PG_locked  |
638                         1 << PG_active  |
639                         1 << PG_dirty   |
640                         1 << PG_slab    |
641                         1 << PG_swapcache |
642                         1 << PG_writeback |
643                         1 << PG_reserved |
644                         1 << PG_buddy ))))
645                 bad_page(page);
646
647         /*
648          * For now, we report if PG_reserved was found set, but do not
649          * clear it, and do not allocate the page: as a safety net.
650          */
651         if (PageReserved(page))
652                 return 1;
653
654         page->flags &= ~(1 << PG_uptodate | 1 << PG_error | 1 << PG_readahead |
655                         1 << PG_referenced | 1 << PG_arch_1 |
656                         1 << PG_owner_priv_1 | 1 << PG_mappedtodisk);
657         set_page_private(page, 0);
658         set_page_refcounted(page);
659
660         arch_alloc_page(page, order);
661         kernel_map_pages(page, 1 << order, 1);
662
663         if (gfp_flags & __GFP_ZERO)
664                 prep_zero_page(page, order, gfp_flags);
665
666         if (order && (gfp_flags & __GFP_COMP))
667                 prep_compound_page(page, order);
668
669         return 0;
670 }
671
672 /*
673  * Go through the free lists for the given migratetype and remove
674  * the smallest available page from the freelists
675  */
676 static struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
677                                                 int migratetype)
678 {
679         unsigned int current_order;
680         struct free_area * area;
681         struct page *page;
682
683         /* Find a page of the appropriate size in the preferred list */
684         for (current_order = order; current_order < MAX_ORDER; ++current_order) {
685                 area = &(zone->free_area[current_order]);
686                 if (list_empty(&area->free_list[migratetype]))
687                         continue;
688
689                 page = list_entry(area->free_list[migratetype].next,
690                                                         struct page, lru);
691                 list_del(&page->lru);
692                 rmv_page_order(page);
693                 area->nr_free--;
694                 __mod_zone_page_state(zone, NR_FREE_PAGES, - (1UL << order));
695                 expand(zone, page, order, current_order, area, migratetype);
696                 return page;
697         }
698
699         return NULL;
700 }
701
702
703 /*
704  * This array describes the order lists are fallen back to when
705  * the free lists for the desirable migrate type are depleted
706  */
707 static int fallbacks[MIGRATE_TYPES][MIGRATE_TYPES-1] = {
708         [MIGRATE_UNMOVABLE]   = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE,   MIGRATE_RESERVE },
709         [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE,   MIGRATE_MOVABLE,   MIGRATE_RESERVE },
710         [MIGRATE_MOVABLE]     = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_RESERVE },
711         [MIGRATE_RESERVE]     = { MIGRATE_RESERVE,     MIGRATE_RESERVE,   MIGRATE_RESERVE }, /* Never used */
712 };
713
714 /*
715  * Move the free pages in a range to the free lists of the requested type.
716  * Note that start_page and end_pages are not aligned on a pageblock
717  * boundary. If alignment is required, use move_freepages_block()
718  */
719 int move_freepages(struct zone *zone,
720                         struct page *start_page, struct page *end_page,
721                         int migratetype)
722 {
723         struct page *page;
724         unsigned long order;
725         int pages_moved = 0;
726
727 #ifndef CONFIG_HOLES_IN_ZONE
728         /*
729          * page_zone is not safe to call in this context when
730          * CONFIG_HOLES_IN_ZONE is set. This bug check is probably redundant
731          * anyway as we check zone boundaries in move_freepages_block().
732          * Remove at a later date when no bug reports exist related to
733          * grouping pages by mobility
734          */
735         BUG_ON(page_zone(start_page) != page_zone(end_page));
736 #endif
737
738         for (page = start_page; page <= end_page;) {
739                 if (!pfn_valid_within(page_to_pfn(page))) {
740                         page++;
741                         continue;
742                 }
743
744                 if (!PageBuddy(page)) {
745                         page++;
746                         continue;
747                 }
748
749                 order = page_order(page);
750                 list_del(&page->lru);
751                 list_add(&page->lru,
752                         &zone->free_area[order].free_list[migratetype]);
753                 page += 1 << order;
754                 pages_moved += 1 << order;
755         }
756
757         return pages_moved;
758 }
759
760 int move_freepages_block(struct zone *zone, struct page *page, int migratetype)
761 {
762         unsigned long start_pfn, end_pfn;
763         struct page *start_page, *end_page;
764
765         start_pfn = page_to_pfn(page);
766         start_pfn = start_pfn & ~(pageblock_nr_pages-1);
767         start_page = pfn_to_page(start_pfn);
768         end_page = start_page + pageblock_nr_pages - 1;
769         end_pfn = start_pfn + pageblock_nr_pages - 1;
770
771         /* Do not cross zone boundaries */
772         if (start_pfn < zone->zone_start_pfn)
773                 start_page = page;
774         if (end_pfn >= zone->zone_start_pfn + zone->spanned_pages)
775                 return 0;
776
777         return move_freepages(zone, start_page, end_page, migratetype);
778 }
779
780 /* Return the page with the lowest PFN in the list */
781 static struct page *min_page(struct list_head *list)
782 {
783         unsigned long min_pfn = -1UL;
784         struct page *min_page = NULL, *page;;
785
786         list_for_each_entry(page, list, lru) {
787                 unsigned long pfn = page_to_pfn(page);
788                 if (pfn < min_pfn) {
789                         min_pfn = pfn;
790                         min_page = page;
791                 }
792         }
793
794         return min_page;
795 }
796
797 /* Remove an element from the buddy allocator from the fallback list */
798 static struct page *__rmqueue_fallback(struct zone *zone, int order,
799                                                 int start_migratetype)
800 {
801         struct free_area * area;
802         int current_order;
803         struct page *page;
804         int migratetype, i;
805
806         /* Find the largest possible block of pages in the other list */
807         for (current_order = MAX_ORDER-1; current_order >= order;
808                                                 --current_order) {
809                 for (i = 0; i < MIGRATE_TYPES - 1; i++) {
810                         migratetype = fallbacks[start_migratetype][i];
811
812                         /* MIGRATE_RESERVE handled later if necessary */
813                         if (migratetype == MIGRATE_RESERVE)
814                                 continue;
815
816                         area = &(zone->free_area[current_order]);
817                         if (list_empty(&area->free_list[migratetype]))
818                                 continue;
819
820                         /* Bias kernel allocations towards low pfns */
821                         page = list_entry(area->free_list[migratetype].next,
822                                         struct page, lru);
823                         if (unlikely(start_migratetype != MIGRATE_MOVABLE))
824                                 page = min_page(&area->free_list[migratetype]);
825                         area->nr_free--;
826
827                         /*
828                          * If breaking a large block of pages, move all free
829                          * pages to the preferred allocation list. If falling
830                          * back for a reclaimable kernel allocation, be more
831                          * agressive about taking ownership of free pages
832                          */
833                         if (unlikely(current_order >= (pageblock_order >> 1)) ||
834                                         start_migratetype == MIGRATE_RECLAIMABLE) {
835                                 unsigned long pages;
836                                 pages = move_freepages_block(zone, page,
837                                                                 start_migratetype);
838
839                                 /* Claim the whole block if over half of it is free */
840                                 if (pages >= (1 << (pageblock_order-1)))
841                                         set_pageblock_migratetype(page,
842                                                                 start_migratetype);
843
844                                 migratetype = start_migratetype;
845                         }
846
847                         /* Remove the page from the freelists */
848                         list_del(&page->lru);
849                         rmv_page_order(page);
850                         __mod_zone_page_state(zone, NR_FREE_PAGES,
851                                                         -(1UL << order));
852
853                         if (current_order == pageblock_order)
854                                 set_pageblock_migratetype(page,
855                                                         start_migratetype);
856
857                         expand(zone, page, order, current_order, area, migratetype);
858                         return page;
859                 }
860         }
861
862         /* Use MIGRATE_RESERVE rather than fail an allocation */
863         return __rmqueue_smallest(zone, order, MIGRATE_RESERVE);
864 }
865
866 /*
867  * Do the hard work of removing an element from the buddy allocator.
868  * Call me with the zone->lock already held.
869  */
870 static struct page *__rmqueue(struct zone *zone, unsigned int order,
871                                                 int migratetype)
872 {
873         struct page *page;
874
875         page = __rmqueue_smallest(zone, order, migratetype);
876
877         if (unlikely(!page))
878                 page = __rmqueue_fallback(zone, order, migratetype);
879
880         return page;
881 }
882
883 /* 
884  * Obtain a specified number of elements from the buddy allocator, all under
885  * a single hold of the lock, for efficiency.  Add them to the supplied list.
886  * Returns the number of new pages which were placed at *list.
887  */
888 static int rmqueue_bulk(struct zone *zone, unsigned int order, 
889                         unsigned long count, struct list_head *list,
890                         int migratetype)
891 {
892         int i;
893         
894         spin_lock(&zone->lock);
895         for (i = 0; i < count; ++i) {
896                 struct page *page = __rmqueue(zone, order, migratetype);
897                 if (unlikely(page == NULL))
898                         break;
899                 list_add(&page->lru, list);
900                 set_page_private(page, migratetype);
901         }
902         spin_unlock(&zone->lock);
903         return i;
904 }
905
906 #ifdef CONFIG_NUMA
907 /*
908  * Called from the vmstat counter updater to drain pagesets of this
909  * currently executing processor on remote nodes after they have
910  * expired.
911  *
912  * Note that this function must be called with the thread pinned to
913  * a single processor.
914  */
915 void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp)
916 {
917         unsigned long flags;
918         int to_drain;
919
920         local_irq_save(flags);
921         if (pcp->count >= pcp->batch)
922                 to_drain = pcp->batch;
923         else
924                 to_drain = pcp->count;
925         free_pages_bulk(zone, to_drain, &pcp->list, 0);
926         pcp->count -= to_drain;
927         local_irq_restore(flags);
928 }
929 #endif
930
931 static void __drain_pages(unsigned int cpu)
932 {
933         unsigned long flags;
934         struct zone *zone;
935         int i;
936
937         for_each_zone(zone) {
938                 struct per_cpu_pageset *pset;
939
940                 if (!populated_zone(zone))
941                         continue;
942
943                 pset = zone_pcp(zone, cpu);
944                 for (i = 0; i < ARRAY_SIZE(pset->pcp); i++) {
945                         struct per_cpu_pages *pcp;
946
947                         pcp = &pset->pcp[i];
948                         local_irq_save(flags);
949                         free_pages_bulk(zone, pcp->count, &pcp->list, 0);
950                         pcp->count = 0;
951                         local_irq_restore(flags);
952                 }
953         }
954 }
955
956 #ifdef CONFIG_HIBERNATION
957
958 void mark_free_pages(struct zone *zone)
959 {
960         unsigned long pfn, max_zone_pfn;
961         unsigned long flags;
962         int order, t;
963         struct list_head *curr;
964
965         if (!zone->spanned_pages)
966                 return;
967
968         spin_lock_irqsave(&zone->lock, flags);
969
970         max_zone_pfn = zone->zone_start_pfn + zone->spanned_pages;
971         for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
972                 if (pfn_valid(pfn)) {
973                         struct page *page = pfn_to_page(pfn);
974
975                         if (!swsusp_page_is_forbidden(page))
976                                 swsusp_unset_page_free(page);
977                 }
978
979         for_each_migratetype_order(order, t) {
980                 list_for_each(curr, &zone->free_area[order].free_list[t]) {
981                         unsigned long i;
982
983                         pfn = page_to_pfn(list_entry(curr, struct page, lru));
984                         for (i = 0; i < (1UL << order); i++)
985                                 swsusp_set_page_free(pfn_to_page(pfn + i));
986                 }
987         }
988         spin_unlock_irqrestore(&zone->lock, flags);
989 }
990 #endif /* CONFIG_PM */
991
992 /*
993  * Spill all of this CPU's per-cpu pages back into the buddy allocator.
994  */
995 void drain_local_pages(void)
996 {
997         unsigned long flags;
998
999         local_irq_save(flags);  
1000         __drain_pages(smp_processor_id());
1001         local_irq_restore(flags);       
1002 }
1003
1004 void smp_drain_local_pages(void *arg)
1005 {
1006         drain_local_pages();
1007 }
1008
1009 /*
1010  * Spill all the per-cpu pages from all CPUs back into the buddy allocator
1011  */
1012 void drain_all_local_pages(void)
1013 {
1014         unsigned long flags;
1015
1016         local_irq_save(flags);
1017         __drain_pages(smp_processor_id());
1018         local_irq_restore(flags);
1019
1020         smp_call_function(smp_drain_local_pages, NULL, 0, 1);
1021 }
1022
1023 /*
1024  * Free a 0-order page
1025  */
1026 static void fastcall free_hot_cold_page(struct page *page, int cold)
1027 {
1028         struct zone *zone = page_zone(page);
1029         struct per_cpu_pages *pcp;
1030         unsigned long flags;
1031
1032         if (PageAnon(page))
1033                 page->mapping = NULL;
1034         if (free_pages_check(page))
1035                 return;
1036
1037         if (!PageHighMem(page))
1038                 debug_check_no_locks_freed(page_address(page), PAGE_SIZE);
1039         arch_free_page(page, 0);
1040         kernel_map_pages(page, 1, 0);
1041
1042         pcp = &zone_pcp(zone, get_cpu())->pcp[cold];
1043         local_irq_save(flags);
1044         __count_vm_event(PGFREE);
1045         list_add(&page->lru, &pcp->list);
1046         set_page_private(page, get_pageblock_migratetype(page));
1047         pcp->count++;
1048         if (pcp->count >= pcp->high) {
1049                 free_pages_bulk(zone, pcp->batch, &pcp->list, 0);
1050                 pcp->count -= pcp->batch;
1051         }
1052         local_irq_restore(flags);
1053         put_cpu();
1054 }
1055
1056 void fastcall free_hot_page(struct page *page)
1057 {
1058         free_hot_cold_page(page, 0);
1059 }
1060         
1061 void fastcall free_cold_page(struct page *page)
1062 {
1063         free_hot_cold_page(page, 1);
1064 }
1065
1066 /*
1067  * split_page takes a non-compound higher-order page, and splits it into
1068  * n (1<<order) sub-pages: page[0..n]
1069  * Each sub-page must be freed individually.
1070  *
1071  * Note: this is probably too low level an operation for use in drivers.
1072  * Please consult with lkml before using this in your driver.
1073  */
1074 void split_page(struct page *page, unsigned int order)
1075 {
1076         int i;
1077
1078         VM_BUG_ON(PageCompound(page));
1079         VM_BUG_ON(!page_count(page));
1080         for (i = 1; i < (1 << order); i++)
1081                 set_page_refcounted(page + i);
1082 }
1083
1084 /*
1085  * Really, prep_compound_page() should be called from __rmqueue_bulk().  But
1086  * we cheat by calling it from here, in the order > 0 path.  Saves a branch
1087  * or two.
1088  */
1089 static struct page *buffered_rmqueue(struct zonelist *zonelist,
1090                         struct zone *zone, int order, gfp_t gfp_flags)
1091 {
1092         unsigned long flags;
1093         struct page *page;
1094         int cold = !!(gfp_flags & __GFP_COLD);
1095         int cpu;
1096         int migratetype = allocflags_to_migratetype(gfp_flags);
1097
1098 again:
1099         cpu  = get_cpu();
1100         if (likely(order == 0)) {
1101                 struct per_cpu_pages *pcp;
1102
1103                 pcp = &zone_pcp(zone, cpu)->pcp[cold];
1104                 local_irq_save(flags);
1105                 if (!pcp->count) {
1106                         pcp->count = rmqueue_bulk(zone, 0,
1107                                         pcp->batch, &pcp->list, migratetype);
1108                         if (unlikely(!pcp->count))
1109                                 goto failed;
1110                 }
1111
1112                 /* Find a page of the appropriate migrate type */
1113                 list_for_each_entry(page, &pcp->list, lru)
1114                         if (page_private(page) == migratetype)
1115                                 break;
1116
1117                 /* Allocate more to the pcp list if necessary */
1118                 if (unlikely(&page->lru == &pcp->list)) {
1119                         pcp->count += rmqueue_bulk(zone, 0,
1120                                         pcp->batch, &pcp->list, migratetype);
1121                         page = list_entry(pcp->list.next, struct page, lru);
1122                 }
1123
1124                 list_del(&page->lru);
1125                 pcp->count--;
1126         } else {
1127                 spin_lock_irqsave(&zone->lock, flags);
1128                 page = __rmqueue(zone, order, migratetype);
1129                 spin_unlock(&zone->lock);
1130                 if (!page)
1131                         goto failed;
1132         }
1133
1134         __count_zone_vm_events(PGALLOC, zone, 1 << order);
1135         zone_statistics(zonelist, zone);
1136         local_irq_restore(flags);
1137         put_cpu();
1138
1139         VM_BUG_ON(bad_range(zone, page));
1140         if (prep_new_page(page, order, gfp_flags))
1141                 goto again;
1142         return page;
1143
1144 failed:
1145         local_irq_restore(flags);
1146         put_cpu();
1147         return NULL;
1148 }
1149
1150 #define ALLOC_NO_WATERMARKS     0x01 /* don't check watermarks at all */
1151 #define ALLOC_WMARK_MIN         0x02 /* use pages_min watermark */
1152 #define ALLOC_WMARK_LOW         0x04 /* use pages_low watermark */
1153 #define ALLOC_WMARK_HIGH        0x08 /* use pages_high watermark */
1154 #define ALLOC_HARDER            0x10 /* try to alloc harder */
1155 #define ALLOC_HIGH              0x20 /* __GFP_HIGH set */
1156 #define ALLOC_CPUSET            0x40 /* check for correct cpuset */
1157
1158 #ifdef CONFIG_FAIL_PAGE_ALLOC
1159
1160 static struct fail_page_alloc_attr {
1161         struct fault_attr attr;
1162
1163         u32 ignore_gfp_highmem;
1164         u32 ignore_gfp_wait;
1165         u32 min_order;
1166
1167 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
1168
1169         struct dentry *ignore_gfp_highmem_file;
1170         struct dentry *ignore_gfp_wait_file;
1171         struct dentry *min_order_file;
1172
1173 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
1174
1175 } fail_page_alloc = {
1176         .attr = FAULT_ATTR_INITIALIZER,
1177         .ignore_gfp_wait = 1,
1178         .ignore_gfp_highmem = 1,
1179         .min_order = 1,
1180 };
1181
1182 static int __init setup_fail_page_alloc(char *str)
1183 {
1184         return setup_fault_attr(&fail_page_alloc.attr, str);
1185 }
1186 __setup("fail_page_alloc=", setup_fail_page_alloc);
1187
1188 static int should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
1189 {
1190         if (order < fail_page_alloc.min_order)
1191                 return 0;
1192         if (gfp_mask & __GFP_NOFAIL)
1193                 return 0;
1194         if (fail_page_alloc.ignore_gfp_highmem && (gfp_mask & __GFP_HIGHMEM))
1195                 return 0;
1196         if (fail_page_alloc.ignore_gfp_wait && (gfp_mask & __GFP_WAIT))
1197                 return 0;
1198
1199         return should_fail(&fail_page_alloc.attr, 1 << order);
1200 }
1201
1202 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
1203
1204 static int __init fail_page_alloc_debugfs(void)
1205 {
1206         mode_t mode = S_IFREG | S_IRUSR | S_IWUSR;
1207         struct dentry *dir;
1208         int err;
1209
1210         err = init_fault_attr_dentries(&fail_page_alloc.attr,
1211                                        "fail_page_alloc");
1212         if (err)
1213                 return err;
1214         dir = fail_page_alloc.attr.dentries.dir;
1215
1216         fail_page_alloc.ignore_gfp_wait_file =
1217                 debugfs_create_bool("ignore-gfp-wait", mode, dir,
1218                                       &fail_page_alloc.ignore_gfp_wait);
1219
1220         fail_page_alloc.ignore_gfp_highmem_file =
1221                 debugfs_create_bool("ignore-gfp-highmem", mode, dir,
1222                                       &fail_page_alloc.ignore_gfp_highmem);
1223         fail_page_alloc.min_order_file =
1224                 debugfs_create_u32("min-order", mode, dir,
1225                                    &fail_page_alloc.min_order);
1226
1227         if (!fail_page_alloc.ignore_gfp_wait_file ||
1228             !fail_page_alloc.ignore_gfp_highmem_file ||
1229             !fail_page_alloc.min_order_file) {
1230                 err = -ENOMEM;
1231                 debugfs_remove(fail_page_alloc.ignore_gfp_wait_file);
1232                 debugfs_remove(fail_page_alloc.ignore_gfp_highmem_file);
1233                 debugfs_remove(fail_page_alloc.min_order_file);
1234                 cleanup_fault_attr_dentries(&fail_page_alloc.attr);
1235         }
1236
1237         return err;
1238 }
1239
1240 late_initcall(fail_page_alloc_debugfs);
1241
1242 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
1243
1244 #else /* CONFIG_FAIL_PAGE_ALLOC */
1245
1246 static inline int should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
1247 {
1248         return 0;
1249 }
1250
1251 #endif /* CONFIG_FAIL_PAGE_ALLOC */
1252
1253 /*
1254  * Return 1 if free pages are above 'mark'. This takes into account the order
1255  * of the allocation.
1256  */
1257 int zone_watermark_ok(struct zone *z, int order, unsigned long mark,
1258                       int classzone_idx, int alloc_flags)
1259 {
1260         /* free_pages my go negative - that's OK */
1261         long min = mark;
1262         long free_pages = zone_page_state(z, NR_FREE_PAGES) - (1 << order) + 1;
1263         int o;
1264
1265         if (alloc_flags & ALLOC_HIGH)
1266                 min -= min / 2;
1267         if (alloc_flags & ALLOC_HARDER)
1268                 min -= min / 4;
1269
1270         if (free_pages <= min + z->lowmem_reserve[classzone_idx])
1271                 return 0;
1272         for (o = 0; o < order; o++) {
1273                 /* At the next order, this order's pages become unavailable */
1274                 free_pages -= z->free_area[o].nr_free << o;
1275
1276                 /* Require fewer higher order pages to be free */
1277                 min >>= 1;
1278
1279                 if (free_pages <= min)
1280                         return 0;
1281         }
1282         return 1;
1283 }
1284
1285 #ifdef CONFIG_NUMA
1286 /*
1287  * zlc_setup - Setup for "zonelist cache".  Uses cached zone data to
1288  * skip over zones that are not allowed by the cpuset, or that have
1289  * been recently (in last second) found to be nearly full.  See further
1290  * comments in mmzone.h.  Reduces cache footprint of zonelist scans
1291  * that have to skip over alot of full or unallowed zones.
1292  *
1293  * If the zonelist cache is present in the passed in zonelist, then
1294  * returns a pointer to the allowed node mask (either the current
1295  * tasks mems_allowed, or node_states[N_HIGH_MEMORY].)
1296  *
1297  * If the zonelist cache is not available for this zonelist, does
1298  * nothing and returns NULL.
1299  *
1300  * If the fullzones BITMAP in the zonelist cache is stale (more than
1301  * a second since last zap'd) then we zap it out (clear its bits.)
1302  *
1303  * We hold off even calling zlc_setup, until after we've checked the
1304  * first zone in the zonelist, on the theory that most allocations will
1305  * be satisfied from that first zone, so best to examine that zone as
1306  * quickly as we can.
1307  */
1308 static nodemask_t *zlc_setup(struct zonelist *zonelist, int alloc_flags)
1309 {
1310         struct zonelist_cache *zlc;     /* cached zonelist speedup info */
1311         nodemask_t *allowednodes;       /* zonelist_cache approximation */
1312
1313         zlc = zonelist->zlcache_ptr;
1314         if (!zlc)
1315                 return NULL;
1316
1317         if (jiffies - zlc->last_full_zap > 1 * HZ) {
1318                 bitmap_zero(zlc->fullzones, MAX_ZONES_PER_ZONELIST);
1319                 zlc->last_full_zap = jiffies;
1320         }
1321
1322         allowednodes = !in_interrupt() && (alloc_flags & ALLOC_CPUSET) ?
1323                                         &cpuset_current_mems_allowed :
1324                                         &node_states[N_HIGH_MEMORY];
1325         return allowednodes;
1326 }
1327
1328 /*
1329  * Given 'z' scanning a zonelist, run a couple of quick checks to see
1330  * if it is worth looking at further for free memory:
1331  *  1) Check that the zone isn't thought to be full (doesn't have its
1332  *     bit set in the zonelist_cache fullzones BITMAP).
1333  *  2) Check that the zones node (obtained from the zonelist_cache
1334  *     z_to_n[] mapping) is allowed in the passed in allowednodes mask.
1335  * Return true (non-zero) if zone is worth looking at further, or
1336  * else return false (zero) if it is not.
1337  *
1338  * This check -ignores- the distinction between various watermarks,
1339  * such as GFP_HIGH, GFP_ATOMIC, PF_MEMALLOC, ...  If a zone is
1340  * found to be full for any variation of these watermarks, it will
1341  * be considered full for up to one second by all requests, unless
1342  * we are so low on memory on all allowed nodes that we are forced
1343  * into the second scan of the zonelist.
1344  *
1345  * In the second scan we ignore this zonelist cache and exactly
1346  * apply the watermarks to all zones, even it is slower to do so.
1347  * We are low on memory in the second scan, and should leave no stone
1348  * unturned looking for a free page.
1349  */
1350 static int zlc_zone_worth_trying(struct zonelist *zonelist, struct zone **z,
1351                                                 nodemask_t *allowednodes)
1352 {
1353         struct zonelist_cache *zlc;     /* cached zonelist speedup info */
1354         int i;                          /* index of *z in zonelist zones */
1355         int n;                          /* node that zone *z is on */
1356
1357         zlc = zonelist->zlcache_ptr;
1358         if (!zlc)
1359                 return 1;
1360
1361         i = z - zonelist->zones;
1362         n = zlc->z_to_n[i];
1363
1364         /* This zone is worth trying if it is allowed but not full */
1365         return node_isset(n, *allowednodes) && !test_bit(i, zlc->fullzones);
1366 }
1367
1368 /*
1369  * Given 'z' scanning a zonelist, set the corresponding bit in
1370  * zlc->fullzones, so that subsequent attempts to allocate a page
1371  * from that zone don't waste time re-examining it.
1372  */
1373 static void zlc_mark_zone_full(struct zonelist *zonelist, struct zone **z)
1374 {
1375         struct zonelist_cache *zlc;     /* cached zonelist speedup info */
1376         int i;                          /* index of *z in zonelist zones */
1377
1378         zlc = zonelist->zlcache_ptr;
1379         if (!zlc)
1380                 return;
1381
1382         i = z - zonelist->zones;
1383
1384         set_bit(i, zlc->fullzones);
1385 }
1386
1387 #else   /* CONFIG_NUMA */
1388
1389 static nodemask_t *zlc_setup(struct zonelist *zonelist, int alloc_flags)
1390 {
1391         return NULL;
1392 }
1393
1394 static int zlc_zone_worth_trying(struct zonelist *zonelist, struct zone **z,
1395                                 nodemask_t *allowednodes)
1396 {
1397         return 1;
1398 }
1399
1400 static void zlc_mark_zone_full(struct zonelist *zonelist, struct zone **z)
1401 {
1402 }
1403 #endif  /* CONFIG_NUMA */
1404
1405 /*
1406  * get_page_from_freelist goes through the zonelist trying to allocate
1407  * a page.
1408  */
1409 static struct page *
1410 get_page_from_freelist(gfp_t gfp_mask, unsigned int order,
1411                 struct zonelist *zonelist, int alloc_flags)
1412 {
1413         struct zone **z;
1414         struct page *page = NULL;
1415         int classzone_idx = zone_idx(zonelist->zones[0]);
1416         struct zone *zone;
1417         nodemask_t *allowednodes = NULL;/* zonelist_cache approximation */
1418         int zlc_active = 0;             /* set if using zonelist_cache */
1419         int did_zlc_setup = 0;          /* just call zlc_setup() one time */
1420         enum zone_type highest_zoneidx = -1; /* Gets set for policy zonelists */
1421
1422 zonelist_scan:
1423         /*
1424          * Scan zonelist, looking for a zone with enough free.
1425          * See also cpuset_zone_allowed() comment in kernel/cpuset.c.
1426          */
1427         z = zonelist->zones;
1428
1429         do {
1430                 /*
1431                  * In NUMA, this could be a policy zonelist which contains
1432                  * zones that may not be allowed by the current gfp_mask.
1433                  * Check the zone is allowed by the current flags
1434                  */
1435                 if (unlikely(alloc_should_filter_zonelist(zonelist))) {
1436                         if (highest_zoneidx == -1)
1437                                 highest_zoneidx = gfp_zone(gfp_mask);
1438                         if (zone_idx(*z) > highest_zoneidx)
1439                                 continue;
1440                 }
1441
1442                 if (NUMA_BUILD && zlc_active &&
1443                         !zlc_zone_worth_trying(zonelist, z, allowednodes))
1444                                 continue;
1445                 zone = *z;
1446                 if ((alloc_flags & ALLOC_CPUSET) &&
1447                         !cpuset_zone_allowed_softwall(zone, gfp_mask))
1448                                 goto try_next_zone;
1449
1450                 if (!(alloc_flags & ALLOC_NO_WATERMARKS)) {
1451                         unsigned long mark;
1452                         if (alloc_flags & ALLOC_WMARK_MIN)
1453                                 mark = zone->pages_min;
1454                         else if (alloc_flags & ALLOC_WMARK_LOW)
1455                                 mark = zone->pages_low;
1456                         else
1457                                 mark = zone->pages_high;
1458                         if (!zone_watermark_ok(zone, order, mark,
1459                                     classzone_idx, alloc_flags)) {
1460                                 if (!zone_reclaim_mode ||
1461                                     !zone_reclaim(zone, gfp_mask, order))
1462                                         goto this_zone_full;
1463                         }
1464                 }
1465
1466                 page = buffered_rmqueue(zonelist, zone, order, gfp_mask);
1467                 if (page)
1468                         break;
1469 this_zone_full:
1470                 if (NUMA_BUILD)
1471                         zlc_mark_zone_full(zonelist, z);
1472 try_next_zone:
1473                 if (NUMA_BUILD && !did_zlc_setup) {
1474                         /* we do zlc_setup after the first zone is tried */
1475                         allowednodes = zlc_setup(zonelist, alloc_flags);
1476                         zlc_active = 1;
1477                         did_zlc_setup = 1;
1478                 }
1479         } while (*(++z) != NULL);
1480
1481         if (unlikely(NUMA_BUILD && page == NULL && zlc_active)) {
1482                 /* Disable zlc cache for second zonelist scan */
1483                 zlc_active = 0;
1484                 goto zonelist_scan;
1485         }
1486         return page;
1487 }
1488
1489 /*
1490  * This is the 'heart' of the zoned buddy allocator.
1491  */
1492 struct page * fastcall
1493 __alloc_pages(gfp_t gfp_mask, unsigned int order,
1494                 struct zonelist *zonelist)
1495 {
1496         const gfp_t wait = gfp_mask & __GFP_WAIT;
1497         struct zone **z;
1498         struct page *page;
1499         struct reclaim_state reclaim_state;
1500         struct task_struct *p = current;
1501         int do_retry;
1502         int alloc_flags;
1503         int did_some_progress;
1504
1505         might_sleep_if(wait);
1506
1507         if (should_fail_alloc_page(gfp_mask, order))
1508                 return NULL;
1509
1510 restart:
1511         z = zonelist->zones;  /* the list of zones suitable for gfp_mask */
1512
1513         if (unlikely(*z == NULL)) {
1514                 /*
1515                  * Happens if we have an empty zonelist as a result of
1516                  * GFP_THISNODE being used on a memoryless node
1517                  */
1518                 return NULL;
1519         }
1520
1521         page = get_page_from_freelist(gfp_mask|__GFP_HARDWALL, order,
1522                                 zonelist, ALLOC_WMARK_LOW|ALLOC_CPUSET);
1523         if (page)
1524                 goto got_pg;
1525
1526         /*
1527          * GFP_THISNODE (meaning __GFP_THISNODE, __GFP_NORETRY and
1528          * __GFP_NOWARN set) should not cause reclaim since the subsystem
1529          * (f.e. slab) using GFP_THISNODE may choose to trigger reclaim
1530          * using a larger set of nodes after it has established that the
1531          * allowed per node queues are empty and that nodes are
1532          * over allocated.
1533          */
1534         if (NUMA_BUILD && (gfp_mask & GFP_THISNODE) == GFP_THISNODE)
1535                 goto nopage;
1536
1537         for (z = zonelist->zones; *z; z++)
1538                 wakeup_kswapd(*z, order);
1539
1540         /*
1541          * OK, we're below the kswapd watermark and have kicked background
1542          * reclaim. Now things get more complex, so set up alloc_flags according
1543          * to how we want to proceed.
1544          *
1545          * The caller may dip into page reserves a bit more if the caller
1546          * cannot run direct reclaim, or if the caller has realtime scheduling
1547          * policy or is asking for __GFP_HIGH memory.  GFP_ATOMIC requests will
1548          * set both ALLOC_HARDER (!wait) and ALLOC_HIGH (__GFP_HIGH).
1549          */
1550         alloc_flags = ALLOC_WMARK_MIN;
1551         if ((unlikely(rt_task(p)) && !in_interrupt()) || !wait)
1552                 alloc_flags |= ALLOC_HARDER;
1553         if (gfp_mask & __GFP_HIGH)
1554                 alloc_flags |= ALLOC_HIGH;
1555         if (wait)
1556                 alloc_flags |= ALLOC_CPUSET;
1557
1558         /*
1559          * Go through the zonelist again. Let __GFP_HIGH and allocations
1560          * coming from realtime tasks go deeper into reserves.
1561          *
1562          * This is the last chance, in general, before the goto nopage.
1563          * Ignore cpuset if GFP_ATOMIC (!wait) rather than fail alloc.
1564          * See also cpuset_zone_allowed() comment in kernel/cpuset.c.
1565          */
1566         page = get_page_from_freelist(gfp_mask, order, zonelist, alloc_flags);
1567         if (page)
1568                 goto got_pg;
1569
1570         /* This allocation should allow future memory freeing. */
1571
1572 rebalance:
1573         if (((p->flags & PF_MEMALLOC) || unlikely(test_thread_flag(TIF_MEMDIE)))
1574                         && !in_interrupt()) {
1575                 if (!(gfp_mask & __GFP_NOMEMALLOC)) {
1576 nofail_alloc:
1577                         /* go through the zonelist yet again, ignoring mins */
1578                         page = get_page_from_freelist(gfp_mask, order,
1579                                 zonelist, ALLOC_NO_WATERMARKS);
1580                         if (page)
1581                                 goto got_pg;
1582                         if (gfp_mask & __GFP_NOFAIL) {
1583                                 congestion_wait(WRITE, HZ/50);
1584                                 goto nofail_alloc;
1585                         }
1586                 }
1587                 goto nopage;
1588         }
1589
1590         /* Atomic allocations - we can't balance anything */
1591         if (!wait)
1592                 goto nopage;
1593
1594         cond_resched();
1595
1596         /* We now go into synchronous reclaim */
1597         cpuset_memory_pressure_bump();
1598         p->flags |= PF_MEMALLOC;
1599         reclaim_state.reclaimed_slab = 0;
1600         p->reclaim_state = &reclaim_state;
1601
1602         did_some_progress = try_to_free_pages(zonelist->zones, order, gfp_mask);
1603
1604         p->reclaim_state = NULL;
1605         p->flags &= ~PF_MEMALLOC;
1606
1607         cond_resched();
1608
1609         if (order != 0)
1610                 drain_all_local_pages();
1611
1612         if (likely(did_some_progress)) {
1613                 page = get_page_from_freelist(gfp_mask, order,
1614                                                 zonelist, alloc_flags);
1615                 if (page)
1616                         goto got_pg;
1617         } else if ((gfp_mask & __GFP_FS) && !(gfp_mask & __GFP_NORETRY)) {
1618                 /*
1619                  * Go through the zonelist yet one more time, keep
1620                  * very high watermark here, this is only to catch
1621                  * a parallel oom killing, we must fail if we're still
1622                  * under heavy pressure.
1623                  */
1624                 page = get_page_from_freelist(gfp_mask|__GFP_HARDWALL, order,
1625                                 zonelist, ALLOC_WMARK_HIGH|ALLOC_CPUSET);
1626                 if (page)
1627                         goto got_pg;
1628
1629                 /* The OOM killer will not help higher order allocs so fail */
1630                 if (order > PAGE_ALLOC_COSTLY_ORDER)
1631                         goto nopage;
1632
1633                 out_of_memory(zonelist, gfp_mask, order);
1634                 goto restart;
1635         }
1636
1637         /*
1638          * Don't let big-order allocations loop unless the caller explicitly
1639          * requests that.  Wait for some write requests to complete then retry.
1640          *
1641          * In this implementation, __GFP_REPEAT means __GFP_NOFAIL for order
1642          * <= 3, but that may not be true in other implementations.
1643          */
1644         do_retry = 0;
1645         if (!(gfp_mask & __GFP_NORETRY)) {
1646                 if ((order <= PAGE_ALLOC_COSTLY_ORDER) ||
1647                                                 (gfp_mask & __GFP_REPEAT))
1648                         do_retry = 1;
1649                 if (gfp_mask & __GFP_NOFAIL)
1650                         do_retry = 1;
1651         }
1652         if (do_retry) {
1653                 congestion_wait(WRITE, HZ/50);
1654                 goto rebalance;
1655         }
1656
1657 nopage:
1658         if (!(gfp_mask & __GFP_NOWARN) && printk_ratelimit()) {
1659                 printk(KERN_WARNING "%s: page allocation failure."
1660                         " order:%d, mode:0x%x\n",
1661                         p->comm, order, gfp_mask);
1662                 dump_stack();
1663                 show_mem();
1664         }
1665 got_pg:
1666         return page;
1667 }
1668
1669 EXPORT_SYMBOL(__alloc_pages);
1670
1671 /*
1672  * Common helper functions.
1673  */
1674 fastcall unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order)
1675 {
1676         struct page * page;
1677         page = alloc_pages(gfp_mask, order);
1678         if (!page)
1679                 return 0;
1680         return (unsigned long) page_address(page);
1681 }
1682
1683 EXPORT_SYMBOL(__get_free_pages);
1684
1685 fastcall unsigned long get_zeroed_page(gfp_t gfp_mask)
1686 {
1687         struct page * page;
1688
1689         /*
1690          * get_zeroed_page() returns a 32-bit address, which cannot represent
1691          * a highmem page
1692          */
1693         VM_BUG_ON((gfp_mask & __GFP_HIGHMEM) != 0);
1694
1695         page = alloc_pages(gfp_mask | __GFP_ZERO, 0);
1696         if (page)
1697                 return (unsigned long) page_address(page);
1698         return 0;
1699 }
1700
1701 EXPORT_SYMBOL(get_zeroed_page);
1702
1703 void __pagevec_free(struct pagevec *pvec)
1704 {
1705         int i = pagevec_count(pvec);
1706
1707         while (--i >= 0)
1708                 free_hot_cold_page(pvec->pages[i], pvec->cold);
1709 }
1710
1711 fastcall void __free_pages(struct page *page, unsigned int order)
1712 {
1713         if (put_page_testzero(page)) {
1714                 if (order == 0)
1715                         free_hot_page(page);
1716                 else
1717                         __free_pages_ok(page, order);
1718         }
1719 }
1720
1721 EXPORT_SYMBOL(__free_pages);
1722
1723 fastcall void free_pages(unsigned long addr, unsigned int order)
1724 {
1725         if (addr != 0) {
1726                 VM_BUG_ON(!virt_addr_valid((void *)addr));
1727                 __free_pages(virt_to_page((void *)addr), order);
1728         }
1729 }
1730
1731 EXPORT_SYMBOL(free_pages);
1732
1733 static unsigned int nr_free_zone_pages(int offset)
1734 {
1735         /* Just pick one node, since fallback list is circular */
1736         pg_data_t *pgdat = NODE_DATA(numa_node_id());
1737         unsigned int sum = 0;
1738
1739         struct zonelist *zonelist = pgdat->node_zonelists + offset;
1740         struct zone **zonep = zonelist->zones;
1741         struct zone *zone;
1742
1743         for (zone = *zonep++; zone; zone = *zonep++) {
1744                 unsigned long size = zone->present_pages;
1745                 unsigned long high = zone->pages_high;
1746                 if (size > high)
1747                         sum += size - high;
1748         }
1749
1750         return sum;
1751 }
1752
1753 /*
1754  * Amount of free RAM allocatable within ZONE_DMA and ZONE_NORMAL
1755  */
1756 unsigned int nr_free_buffer_pages(void)
1757 {
1758         return nr_free_zone_pages(gfp_zone(GFP_USER));
1759 }
1760 EXPORT_SYMBOL_GPL(nr_free_buffer_pages);
1761
1762 /*
1763  * Amount of free RAM allocatable within all zones
1764  */
1765 unsigned int nr_free_pagecache_pages(void)
1766 {
1767         return nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE));
1768 }
1769
1770 static inline void show_node(struct zone *zone)
1771 {
1772         if (NUMA_BUILD)
1773                 printk("Node %d ", zone_to_nid(zone));
1774 }
1775
1776 void si_meminfo(struct sysinfo *val)
1777 {
1778         val->totalram = totalram_pages;
1779         val->sharedram = 0;
1780         val->freeram = global_page_state(NR_FREE_PAGES);
1781         val->bufferram = nr_blockdev_pages();
1782         val->totalhigh = totalhigh_pages;
1783         val->freehigh = nr_free_highpages();
1784         val->mem_unit = PAGE_SIZE;
1785 }
1786
1787 EXPORT_SYMBOL(si_meminfo);
1788
1789 #ifdef CONFIG_NUMA
1790 void si_meminfo_node(struct sysinfo *val, int nid)
1791 {
1792         pg_data_t *pgdat = NODE_DATA(nid);
1793
1794         val->totalram = pgdat->node_present_pages;
1795         val->freeram = node_page_state(nid, NR_FREE_PAGES);
1796 #ifdef CONFIG_HIGHMEM
1797         val->totalhigh = pgdat->node_zones[ZONE_HIGHMEM].present_pages;
1798         val->freehigh = zone_page_state(&pgdat->node_zones[ZONE_HIGHMEM],
1799                         NR_FREE_PAGES);
1800 #else
1801         val->totalhigh = 0;
1802         val->freehigh = 0;
1803 #endif
1804         val->mem_unit = PAGE_SIZE;
1805 }
1806 #endif
1807
1808 #define K(x) ((x) << (PAGE_SHIFT-10))
1809
1810 /*
1811  * Show free area list (used inside shift_scroll-lock stuff)
1812  * We also calculate the percentage fragmentation. We do this by counting the
1813  * memory on each free list with the exception of the first item on the list.
1814  */
1815 void show_free_areas(void)
1816 {
1817         int cpu;
1818         struct zone *zone;
1819
1820         for_each_zone(zone) {
1821                 if (!populated_zone(zone))
1822                         continue;
1823
1824                 show_node(zone);
1825                 printk("%s per-cpu:\n", zone->name);
1826
1827                 for_each_online_cpu(cpu) {
1828                         struct per_cpu_pageset *pageset;
1829
1830                         pageset = zone_pcp(zone, cpu);
1831
1832                         printk("CPU %4d: Hot: hi:%5d, btch:%4d usd:%4d   "
1833                                "Cold: hi:%5d, btch:%4d usd:%4d\n",
1834                                cpu, pageset->pcp[0].high,
1835                                pageset->pcp[0].batch, pageset->pcp[0].count,
1836                                pageset->pcp[1].high, pageset->pcp[1].batch,
1837                                pageset->pcp[1].count);
1838                 }
1839         }
1840
1841         printk("Active:%lu inactive:%lu dirty:%lu writeback:%lu unstable:%lu\n"
1842                 " free:%lu slab:%lu mapped:%lu pagetables:%lu bounce:%lu\n",
1843                 global_page_state(NR_ACTIVE),
1844                 global_page_state(NR_INACTIVE),
1845                 global_page_state(NR_FILE_DIRTY),
1846                 global_page_state(NR_WRITEBACK),
1847                 global_page_state(NR_UNSTABLE_NFS),
1848                 global_page_state(NR_FREE_PAGES),
1849                 global_page_state(NR_SLAB_RECLAIMABLE) +
1850                         global_page_state(NR_SLAB_UNRECLAIMABLE),
1851                 global_page_state(NR_FILE_MAPPED),
1852                 global_page_state(NR_PAGETABLE),
1853                 global_page_state(NR_BOUNCE));
1854
1855         for_each_zone(zone) {
1856                 int i;
1857
1858                 if (!populated_zone(zone))
1859                         continue;
1860
1861                 show_node(zone);
1862                 printk("%s"
1863                         " free:%lukB"
1864                         " min:%lukB"
1865                         " low:%lukB"
1866                         " high:%lukB"
1867                         " active:%lukB"
1868                         " inactive:%lukB"
1869                         " present:%lukB"
1870                         " pages_scanned:%lu"
1871                         " all_unreclaimable? %s"
1872                         "\n",
1873                         zone->name,
1874                         K(zone_page_state(zone, NR_FREE_PAGES)),
1875                         K(zone->pages_min),
1876                         K(zone->pages_low),
1877                         K(zone->pages_high),
1878                         K(zone_page_state(zone, NR_ACTIVE)),
1879                         K(zone_page_state(zone, NR_INACTIVE)),
1880                         K(zone->present_pages),
1881                         zone->pages_scanned,
1882                         (zone->all_unreclaimable ? "yes" : "no")
1883                         );
1884                 printk("lowmem_reserve[]:");
1885                 for (i = 0; i < MAX_NR_ZONES; i++)
1886                         printk(" %lu", zone->lowmem_reserve[i]);
1887                 printk("\n");
1888         }
1889
1890         for_each_zone(zone) {
1891                 unsigned long nr[MAX_ORDER], flags, order, total = 0;
1892
1893                 if (!populated_zone(zone))
1894                         continue;
1895
1896                 show_node(zone);
1897                 printk("%s: ", zone->name);
1898
1899                 spin_lock_irqsave(&zone->lock, flags);
1900                 for (order = 0; order < MAX_ORDER; order++) {
1901                         nr[order] = zone->free_area[order].nr_free;
1902                         total += nr[order] << order;
1903                 }
1904                 spin_unlock_irqrestore(&zone->lock, flags);
1905                 for (order = 0; order < MAX_ORDER; order++)
1906                         printk("%lu*%lukB ", nr[order], K(1UL) << order);
1907                 printk("= %lukB\n", K(total));
1908         }
1909
1910         show_swap_cache_info();
1911 }
1912
1913 /*
1914  * Builds allocation fallback zone lists.
1915  *
1916  * Add all populated zones of a node to the zonelist.
1917  */
1918 static int build_zonelists_node(pg_data_t *pgdat, struct zonelist *zonelist,
1919                                 int nr_zones, enum zone_type zone_type)
1920 {
1921         struct zone *zone;
1922
1923         BUG_ON(zone_type >= MAX_NR_ZONES);
1924         zone_type++;
1925
1926         do {
1927                 zone_type--;
1928                 zone = pgdat->node_zones + zone_type;
1929                 if (populated_zone(zone)) {
1930                         zonelist->zones[nr_zones++] = zone;
1931                         check_highest_zone(zone_type);
1932                 }
1933
1934         } while (zone_type);
1935         return nr_zones;
1936 }
1937
1938
1939 /*
1940  *  zonelist_order:
1941  *  0 = automatic detection of better ordering.
1942  *  1 = order by ([node] distance, -zonetype)
1943  *  2 = order by (-zonetype, [node] distance)
1944  *
1945  *  If not NUMA, ZONELIST_ORDER_ZONE and ZONELIST_ORDER_NODE will create
1946  *  the same zonelist. So only NUMA can configure this param.
1947  */
1948 #define ZONELIST_ORDER_DEFAULT  0
1949 #define ZONELIST_ORDER_NODE     1
1950 #define ZONELIST_ORDER_ZONE     2
1951
1952 /* zonelist order in the kernel.
1953  * set_zonelist_order() will set this to NODE or ZONE.
1954  */
1955 static int current_zonelist_order = ZONELIST_ORDER_DEFAULT;
1956 static char zonelist_order_name[3][8] = {"Default", "Node", "Zone"};
1957
1958
1959 #ifdef CONFIG_NUMA
1960 /* The value user specified ....changed by config */
1961 static int user_zonelist_order = ZONELIST_ORDER_DEFAULT;
1962 /* string for sysctl */
1963 #define NUMA_ZONELIST_ORDER_LEN 16
1964 char numa_zonelist_order[16] = "default";
1965
1966 /*
1967  * interface for configure zonelist ordering.
1968  * command line option "numa_zonelist_order"
1969  *      = "[dD]efault   - default, automatic configuration.
1970  *      = "[nN]ode      - order by node locality, then by zone within node
1971  *      = "[zZ]one      - order by zone, then by locality within zone
1972  */
1973
1974 static int __parse_numa_zonelist_order(char *s)
1975 {
1976         if (*s == 'd' || *s == 'D') {
1977                 user_zonelist_order = ZONELIST_ORDER_DEFAULT;
1978         } else if (*s == 'n' || *s == 'N') {
1979                 user_zonelist_order = ZONELIST_ORDER_NODE;
1980         } else if (*s == 'z' || *s == 'Z') {
1981                 user_zonelist_order = ZONELIST_ORDER_ZONE;
1982         } else {
1983                 printk(KERN_WARNING
1984                         "Ignoring invalid numa_zonelist_order value:  "
1985                         "%s\n", s);
1986                 return -EINVAL;
1987         }
1988         return 0;
1989 }
1990
1991 static __init int setup_numa_zonelist_order(char *s)
1992 {
1993         if (s)
1994                 return __parse_numa_zonelist_order(s);
1995         return 0;
1996 }
1997 early_param("numa_zonelist_order", setup_numa_zonelist_order);
1998
1999 /*
2000  * sysctl handler for numa_zonelist_order
2001  */
2002 int numa_zonelist_order_handler(ctl_table *table, int write,
2003                 struct file *file, void __user *buffer, size_t *length,
2004                 loff_t *ppos)
2005 {
2006         char saved_string[NUMA_ZONELIST_ORDER_LEN];
2007         int ret;
2008
2009         if (write)
2010                 strncpy(saved_string, (char*)table->data,
2011                         NUMA_ZONELIST_ORDER_LEN);
2012         ret = proc_dostring(table, write, file, buffer, length, ppos);
2013         if (ret)
2014                 return ret;
2015         if (write) {
2016                 int oldval = user_zonelist_order;
2017                 if (__parse_numa_zonelist_order((char*)table->data)) {
2018                         /*
2019                          * bogus value.  restore saved string
2020                          */
2021                         strncpy((char*)table->data, saved_string,
2022                                 NUMA_ZONELIST_ORDER_LEN);
2023                         user_zonelist_order = oldval;
2024                 } else if (oldval != user_zonelist_order)
2025                         build_all_zonelists();
2026         }
2027         return 0;
2028 }
2029
2030
2031 #define MAX_NODE_LOAD (num_online_nodes())
2032 static int node_load[MAX_NUMNODES];
2033
2034 /**
2035  * find_next_best_node - find the next node that should appear in a given node's fallback list
2036  * @node: node whose fallback list we're appending
2037  * @used_node_mask: nodemask_t of already used nodes
2038  *
2039  * We use a number of factors to determine which is the next node that should
2040  * appear on a given node's fallback list.  The node should not have appeared
2041  * already in @node's fallback list, and it should be the next closest node
2042  * according to the distance array (which contains arbitrary distance values
2043  * from each node to each node in the system), and should also prefer nodes
2044  * with no CPUs, since presumably they'll have very little allocation pressure
2045  * on them otherwise.
2046  * It returns -1 if no node is found.
2047  */
2048 static int find_next_best_node(int node, nodemask_t *used_node_mask)
2049 {
2050         int n, val;
2051         int min_val = INT_MAX;
2052         int best_node = -1;
2053
2054         /* Use the local node if we haven't already */
2055         if (!node_isset(node, *used_node_mask)) {
2056                 node_set(node, *used_node_mask);
2057                 return node;
2058         }
2059
2060         for_each_node_state(n, N_HIGH_MEMORY) {
2061                 cpumask_t tmp;
2062
2063                 /* Don't want a node to appear more than once */
2064                 if (node_isset(n, *used_node_mask))
2065                         continue;
2066
2067                 /* Use the distance array to find the distance */
2068                 val = node_distance(node, n);
2069
2070                 /* Penalize nodes under us ("prefer the next node") */
2071                 val += (n < node);
2072
2073                 /* Give preference to headless and unused nodes */
2074                 tmp = node_to_cpumask(n);
2075                 if (!cpus_empty(tmp))
2076                         val += PENALTY_FOR_NODE_WITH_CPUS;
2077
2078                 /* Slight preference for less loaded node */
2079                 val *= (MAX_NODE_LOAD*MAX_NUMNODES);
2080                 val += node_load[n];
2081
2082                 if (val < min_val) {
2083                         min_val = val;
2084                         best_node = n;
2085                 }
2086         }
2087
2088         if (best_node >= 0)
2089                 node_set(best_node, *used_node_mask);
2090
2091         return best_node;
2092 }
2093
2094
2095 /*
2096  * Build zonelists ordered by node and zones within node.
2097  * This results in maximum locality--normal zone overflows into local
2098  * DMA zone, if any--but risks exhausting DMA zone.
2099  */
2100 static void build_zonelists_in_node_order(pg_data_t *pgdat, int node)
2101 {
2102         enum zone_type i;
2103         int j;
2104         struct zonelist *zonelist;
2105
2106         for (i = 0; i < MAX_NR_ZONES; i++) {
2107                 zonelist = pgdat->node_zonelists + i;
2108                 for (j = 0; zonelist->zones[j] != NULL; j++)
2109                         ;
2110                 j = build_zonelists_node(NODE_DATA(node), zonelist, j, i);
2111                 zonelist->zones[j] = NULL;
2112         }
2113 }
2114
2115 /*
2116  * Build gfp_thisnode zonelists
2117  */
2118 static void build_thisnode_zonelists(pg_data_t *pgdat)
2119 {
2120         enum zone_type i;
2121         int j;
2122         struct zonelist *zonelist;
2123
2124         for (i = 0; i < MAX_NR_ZONES; i++) {
2125                 zonelist = pgdat->node_zonelists + MAX_NR_ZONES + i;
2126                 j = build_zonelists_node(pgdat, zonelist, 0, i);
2127                 zonelist->zones[j] = NULL;
2128         }
2129 }
2130
2131 /*
2132  * Build zonelists ordered by zone and nodes within zones.
2133  * This results in conserving DMA zone[s] until all Normal memory is
2134  * exhausted, but results in overflowing to remote node while memory
2135  * may still exist in local DMA zone.
2136  */
2137 static int node_order[MAX_NUMNODES];
2138
2139 static void build_zonelists_in_zone_order(pg_data_t *pgdat, int nr_nodes)
2140 {
2141         enum zone_type i;
2142         int pos, j, node;
2143         int zone_type;          /* needs to be signed */
2144         struct zone *z;
2145         struct zonelist *zonelist;
2146
2147         for (i = 0; i < MAX_NR_ZONES; i++) {
2148                 zonelist = pgdat->node_zonelists + i;
2149                 pos = 0;
2150                 for (zone_type = i; zone_type >= 0; zone_type--) {
2151                         for (j = 0; j < nr_nodes; j++) {
2152                                 node = node_order[j];
2153                                 z = &NODE_DATA(node)->node_zones[zone_type];
2154                                 if (populated_zone(z)) {
2155                                         zonelist->zones[pos++] = z;
2156                                         check_highest_zone(zone_type);
2157                                 }
2158                         }
2159                 }
2160                 zonelist->zones[pos] = NULL;
2161         }
2162 }
2163
2164 static int default_zonelist_order(void)
2165 {
2166         int nid, zone_type;
2167         unsigned long low_kmem_size,total_size;
2168         struct zone *z;
2169         int average_size;
2170         /*
2171          * ZONE_DMA and ZONE_DMA32 can be very small area in the sytem.
2172          * If they are really small and used heavily, the system can fall
2173          * into OOM very easily.
2174          * This function detect ZONE_DMA/DMA32 size and confgigures zone order.
2175          */
2176         /* Is there ZONE_NORMAL ? (ex. ppc has only DMA zone..) */
2177         low_kmem_size = 0;
2178         total_size = 0;
2179         for_each_online_node(nid) {
2180                 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
2181                         z = &NODE_DATA(nid)->node_zones[zone_type];
2182                         if (populated_zone(z)) {
2183                                 if (zone_type < ZONE_NORMAL)
2184                                         low_kmem_size += z->present_pages;
2185                                 total_size += z->present_pages;
2186                         }
2187                 }
2188         }
2189         if (!low_kmem_size ||  /* there are no DMA area. */
2190             low_kmem_size > total_size/2) /* DMA/DMA32 is big. */
2191                 return ZONELIST_ORDER_NODE;
2192         /*
2193          * look into each node's config.
2194          * If there is a node whose DMA/DMA32 memory is very big area on
2195          * local memory, NODE_ORDER may be suitable.
2196          */
2197         average_size = total_size /
2198                                 (nodes_weight(node_states[N_HIGH_MEMORY]) + 1);
2199         for_each_online_node(nid) {
2200                 low_kmem_size = 0;
2201                 total_size = 0;
2202                 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
2203                         z = &NODE_DATA(nid)->node_zones[zone_type];
2204                         if (populated_zone(z)) {
2205                                 if (zone_type < ZONE_NORMAL)
2206                                         low_kmem_size += z->present_pages;
2207                                 total_size += z->present_pages;
2208                         }
2209                 }
2210                 if (low_kmem_size &&
2211                     total_size > average_size && /* ignore small node */
2212                     low_kmem_size > total_size * 70/100)
2213                         return ZONELIST_ORDER_NODE;
2214         }
2215         return ZONELIST_ORDER_ZONE;
2216 }
2217
2218 static void set_zonelist_order(void)
2219 {
2220         if (user_zonelist_order == ZONELIST_ORDER_DEFAULT)
2221                 current_zonelist_order = default_zonelist_order();
2222         else
2223                 current_zonelist_order = user_zonelist_order;
2224 }
2225
2226 static void build_zonelists(pg_data_t *pgdat)
2227 {
2228         int j, node, load;
2229         enum zone_type i;
2230         nodemask_t used_mask;
2231         int local_node, prev_node;
2232         struct zonelist *zonelist;
2233         int order = current_zonelist_order;
2234
2235         /* initialize zonelists */
2236         for (i = 0; i < MAX_ZONELISTS; i++) {
2237                 zonelist = pgdat->node_zonelists + i;
2238                 zonelist->zones[0] = NULL;
2239         }
2240
2241         /* NUMA-aware ordering of nodes */
2242         local_node = pgdat->node_id;
2243         load = num_online_nodes();
2244         prev_node = local_node;
2245         nodes_clear(used_mask);
2246
2247         memset(node_load, 0, sizeof(node_load));
2248         memset(node_order, 0, sizeof(node_order));
2249         j = 0;
2250
2251         while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
2252                 int distance = node_distance(local_node, node);
2253
2254                 /*
2255                  * If another node is sufficiently far away then it is better
2256                  * to reclaim pages in a zone before going off node.
2257                  */
2258                 if (distance > RECLAIM_DISTANCE)
2259                         zone_reclaim_mode = 1;
2260
2261                 /*
2262                  * We don't want to pressure a particular node.
2263                  * So adding penalty to the first node in same
2264                  * distance group to make it round-robin.
2265                  */
2266                 if (distance != node_distance(local_node, prev_node))
2267                         node_load[node] = load;
2268
2269                 prev_node = node;
2270                 load--;
2271                 if (order == ZONELIST_ORDER_NODE)
2272                         build_zonelists_in_node_order(pgdat, node);
2273                 else
2274                         node_order[j++] = node; /* remember order */
2275         }
2276
2277         if (order == ZONELIST_ORDER_ZONE) {
2278                 /* calculate node order -- i.e., DMA last! */
2279                 build_zonelists_in_zone_order(pgdat, j);
2280         }
2281
2282         build_thisnode_zonelists(pgdat);
2283 }
2284
2285 /* Construct the zonelist performance cache - see further mmzone.h */
2286 static void build_zonelist_cache(pg_data_t *pgdat)
2287 {
2288         int i;
2289
2290         for (i = 0; i < MAX_NR_ZONES; i++) {
2291                 struct zonelist *zonelist;
2292                 struct zonelist_cache *zlc;
2293                 struct zone **z;
2294
2295                 zonelist = pgdat->node_zonelists + i;
2296                 zonelist->zlcache_ptr = zlc = &zonelist->zlcache;
2297                 bitmap_zero(zlc->fullzones, MAX_ZONES_PER_ZONELIST);
2298                 for (z = zonelist->zones; *z; z++)
2299                         zlc->z_to_n[z - zonelist->zones] = zone_to_nid(*z);
2300         }
2301 }
2302
2303
2304 #else   /* CONFIG_NUMA */
2305
2306 static void set_zonelist_order(void)
2307 {
2308         current_zonelist_order = ZONELIST_ORDER_ZONE;
2309 }
2310
2311 static void build_zonelists(pg_data_t *pgdat)
2312 {
2313         int node, local_node;
2314         enum zone_type i,j;
2315
2316         local_node = pgdat->node_id;
2317         for (i = 0; i < MAX_NR_ZONES; i++) {
2318                 struct zonelist *zonelist;
2319
2320                 zonelist = pgdat->node_zonelists + i;
2321
2322                 j = build_zonelists_node(pgdat, zonelist, 0, i);
2323                 /*
2324                  * Now we build the zonelist so that it contains the zones
2325                  * of all the other nodes.
2326                  * We don't want to pressure a particular node, so when
2327                  * building the zones for node N, we make sure that the
2328                  * zones coming right after the local ones are those from
2329                  * node N+1 (modulo N)
2330                  */
2331                 for (node = local_node + 1; node < MAX_NUMNODES; node++) {
2332                         if (!node_online(node))
2333                                 continue;
2334                         j = build_zonelists_node(NODE_DATA(node), zonelist, j, i);
2335                 }
2336                 for (node = 0; node < local_node; node++) {
2337                         if (!node_online(node))
2338                                 continue;
2339                         j = build_zonelists_node(NODE_DATA(node), zonelist, j, i);
2340                 }
2341
2342                 zonelist->zones[j] = NULL;
2343         }
2344 }
2345
2346 /* non-NUMA variant of zonelist performance cache - just NULL zlcache_ptr */
2347 static void build_zonelist_cache(pg_data_t *pgdat)
2348 {
2349         int i;
2350
2351         for (i = 0; i < MAX_NR_ZONES; i++)
2352                 pgdat->node_zonelists[i].zlcache_ptr = NULL;
2353 }
2354
2355 #endif  /* CONFIG_NUMA */
2356
2357 /* return values int ....just for stop_machine_run() */
2358 static int __build_all_zonelists(void *dummy)
2359 {
2360         int nid;
2361
2362         for_each_online_node(nid) {
2363                 pg_data_t *pgdat = NODE_DATA(nid);
2364
2365                 build_zonelists(pgdat);
2366                 build_zonelist_cache(pgdat);
2367         }
2368         return 0;
2369 }
2370
2371 void build_all_zonelists(void)
2372 {
2373         set_zonelist_order();
2374
2375         if (system_state == SYSTEM_BOOTING) {
2376                 __build_all_zonelists(NULL);
2377                 cpuset_init_current_mems_allowed();
2378         } else {
2379                 /* we have to stop all cpus to guaranntee there is no user
2380                    of zonelist */
2381                 stop_machine_run(__build_all_zonelists, NULL, NR_CPUS);
2382                 /* cpuset refresh routine should be here */
2383         }
2384         vm_total_pages = nr_free_pagecache_pages();
2385         /*
2386          * Disable grouping by mobility if the number of pages in the
2387          * system is too low to allow the mechanism to work. It would be
2388          * more accurate, but expensive to check per-zone. This check is
2389          * made on memory-hotadd so a system can start with mobility
2390          * disabled and enable it later
2391          */
2392         if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES))
2393                 page_group_by_mobility_disabled = 1;
2394         else
2395                 page_group_by_mobility_disabled = 0;
2396
2397         printk("Built %i zonelists in %s order, mobility grouping %s.  "
2398                 "Total pages: %ld\n",
2399                         num_online_nodes(),
2400                         zonelist_order_name[current_zonelist_order],
2401                         page_group_by_mobility_disabled ? "off" : "on",
2402                         vm_total_pages);
2403 #ifdef CONFIG_NUMA
2404         printk("Policy zone: %s\n", zone_names[policy_zone]);
2405 #endif
2406 }
2407
2408 /*
2409  * Helper functions to size the waitqueue hash table.
2410  * Essentially these want to choose hash table sizes sufficiently
2411  * large so that collisions trying to wait on pages are rare.
2412  * But in fact, the number of active page waitqueues on typical
2413  * systems is ridiculously low, less than 200. So this is even
2414  * conservative, even though it seems large.
2415  *
2416  * The constant PAGES_PER_WAITQUEUE specifies the ratio of pages to
2417  * waitqueues, i.e. the size of the waitq table given the number of pages.
2418  */
2419 #define PAGES_PER_WAITQUEUE     256
2420
2421 #ifndef CONFIG_MEMORY_HOTPLUG
2422 static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
2423 {
2424         unsigned long size = 1;
2425
2426         pages /= PAGES_PER_WAITQUEUE;
2427
2428         while (size < pages)
2429                 size <<= 1;
2430
2431         /*
2432          * Once we have dozens or even hundreds of threads sleeping
2433          * on IO we've got bigger problems than wait queue collision.
2434          * Limit the size of the wait table to a reasonable size.
2435          */
2436         size = min(size, 4096UL);
2437
2438         return max(size, 4UL);
2439 }
2440 #else
2441 /*
2442  * A zone's size might be changed by hot-add, so it is not possible to determine
2443  * a suitable size for its wait_table.  So we use the maximum size now.
2444  *
2445  * The max wait table size = 4096 x sizeof(wait_queue_head_t).   ie:
2446  *
2447  *    i386 (preemption config)    : 4096 x 16 = 64Kbyte.
2448  *    ia64, x86-64 (no preemption): 4096 x 20 = 80Kbyte.
2449  *    ia64, x86-64 (preemption)   : 4096 x 24 = 96Kbyte.
2450  *
2451  * The maximum entries are prepared when a zone's memory is (512K + 256) pages
2452  * or more by the traditional way. (See above).  It equals:
2453  *
2454  *    i386, x86-64, powerpc(4K page size) : =  ( 2G + 1M)byte.
2455  *    ia64(16K page size)                 : =  ( 8G + 4M)byte.
2456  *    powerpc (64K page size)             : =  (32G +16M)byte.
2457  */
2458 static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
2459 {
2460         return 4096UL;
2461 }
2462 #endif
2463
2464 /*
2465  * This is an integer logarithm so that shifts can be used later
2466  * to extract the more random high bits from the multiplicative
2467  * hash function before the remainder is taken.
2468  */
2469 static inline unsigned long wait_table_bits(unsigned long size)
2470 {
2471         return ffz(~size);
2472 }
2473
2474 #define LONG_ALIGN(x) (((x)+(sizeof(long))-1)&~((sizeof(long))-1))
2475
2476 /*
2477  * Mark a number of pageblocks as MIGRATE_RESERVE. The number
2478  * of blocks reserved is based on zone->pages_min. The memory within the
2479  * reserve will tend to store contiguous free pages. Setting min_free_kbytes
2480  * higher will lead to a bigger reserve which will get freed as contiguous
2481  * blocks as reclaim kicks in
2482  */
2483 static void setup_zone_migrate_reserve(struct zone *zone)
2484 {
2485         unsigned long start_pfn, pfn, end_pfn;
2486         struct page *page;
2487         unsigned long reserve, block_migratetype;
2488
2489         /* Get the start pfn, end pfn and the number of blocks to reserve */
2490         start_pfn = zone->zone_start_pfn;
2491         end_pfn = start_pfn + zone->spanned_pages;
2492         reserve = roundup(zone->pages_min, pageblock_nr_pages) >>
2493                                                         pageblock_order;
2494
2495         for (pfn = start_pfn; pfn < end_pfn; pfn += pageblock_nr_pages) {
2496                 if (!pfn_valid(pfn))
2497                         continue;
2498                 page = pfn_to_page(pfn);
2499
2500                 /* Blocks with reserved pages will never free, skip them. */
2501                 if (PageReserved(page))
2502                         continue;
2503
2504                 block_migratetype = get_pageblock_migratetype(page);
2505
2506                 /* If this block is reserved, account for it */
2507                 if (reserve > 0 && block_migratetype == MIGRATE_RESERVE) {
2508                         reserve--;
2509                         continue;
2510                 }
2511
2512                 /* Suitable for reserving if this block is movable */
2513                 if (reserve > 0 && block_migratetype == MIGRATE_MOVABLE) {
2514                         set_pageblock_migratetype(page, MIGRATE_RESERVE);
2515                         move_freepages_block(zone, page, MIGRATE_RESERVE);
2516                         reserve--;
2517                         continue;
2518                 }
2519
2520                 /*
2521                  * If the reserve is met and this is a previous reserved block,
2522                  * take it back
2523                  */
2524                 if (block_migratetype == MIGRATE_RESERVE) {
2525                         set_pageblock_migratetype(page, MIGRATE_MOVABLE);
2526                         move_freepages_block(zone, page, MIGRATE_MOVABLE);
2527                 }
2528         }
2529 }
2530
2531 /*
2532  * Initially all pages are reserved - free ones are freed
2533  * up by free_all_bootmem() once the early boot process is
2534  * done. Non-atomic initialization, single-pass.
2535  */
2536 void __meminit memmap_init_zone(unsigned long size, int nid, unsigned long zone,
2537                 unsigned long start_pfn, enum memmap_context context)
2538 {
2539         struct page *page;
2540         unsigned long end_pfn = start_pfn + size;
2541         unsigned long pfn;
2542
2543         for (pfn = start_pfn; pfn < end_pfn; pfn++) {
2544                 /*
2545                  * There can be holes in boot-time mem_map[]s
2546                  * handed to this function.  They do not
2547                  * exist on hotplugged memory.
2548                  */
2549                 if (context == MEMMAP_EARLY) {
2550                         if (!early_pfn_valid(pfn))
2551                                 continue;
2552                         if (!early_pfn_in_nid(pfn, nid))
2553                                 continue;
2554                 }
2555                 page = pfn_to_page(pfn);
2556                 set_page_links(page, zone, nid, pfn);
2557                 init_page_count(page);
2558                 reset_page_mapcount(page);
2559                 SetPageReserved(page);
2560
2561                 /*
2562                  * Mark the block movable so that blocks are reserved for
2563                  * movable at startup. This will force kernel allocations
2564                  * to reserve their blocks rather than leaking throughout
2565                  * the address space during boot when many long-lived
2566                  * kernel allocations are made. Later some blocks near
2567                  * the start are marked MIGRATE_RESERVE by
2568                  * setup_zone_migrate_reserve()
2569                  */
2570                 if ((pfn & (pageblock_nr_pages-1)))
2571                         set_pageblock_migratetype(page, MIGRATE_MOVABLE);
2572
2573                 INIT_LIST_HEAD(&page->lru);
2574 #ifdef WANT_PAGE_VIRTUAL
2575                 /* The shift won't overflow because ZONE_NORMAL is below 4G. */
2576                 if (!is_highmem_idx(zone))
2577                         set_page_address(page, __va(pfn << PAGE_SHIFT));
2578 #endif
2579         }
2580 }
2581
2582 static void __meminit zone_init_free_lists(struct pglist_data *pgdat,
2583                                 struct zone *zone, unsigned long size)
2584 {
2585         int order, t;
2586         for_each_migratetype_order(order, t) {
2587                 INIT_LIST_HEAD(&zone->free_area[order].free_list[t]);
2588                 zone->free_area[order].nr_free = 0;
2589         }
2590 }
2591
2592 #ifndef __HAVE_ARCH_MEMMAP_INIT
2593 #define memmap_init(size, nid, zone, start_pfn) \
2594         memmap_init_zone((size), (nid), (zone), (start_pfn), MEMMAP_EARLY)
2595 #endif
2596
2597 static int __devinit zone_batchsize(struct zone *zone)
2598 {
2599         int batch;
2600
2601         /*
2602          * The per-cpu-pages pools are set to around 1000th of the
2603          * size of the zone.  But no more than 1/2 of a meg.
2604          *
2605          * OK, so we don't know how big the cache is.  So guess.
2606          */
2607         batch = zone->present_pages / 1024;
2608         if (batch * PAGE_SIZE > 512 * 1024)
2609                 batch = (512 * 1024) / PAGE_SIZE;
2610         batch /= 4;             /* We effectively *= 4 below */
2611         if (batch < 1)
2612                 batch = 1;
2613
2614         /*
2615          * Clamp the batch to a 2^n - 1 value. Having a power
2616          * of 2 value was found to be more likely to have
2617          * suboptimal cache aliasing properties in some cases.
2618          *
2619          * For example if 2 tasks are alternately allocating
2620          * batches of pages, one task can end up with a lot
2621          * of pages of one half of the possible page colors
2622          * and the other with pages of the other colors.
2623          */
2624         batch = (1 << (fls(batch + batch/2)-1)) - 1;
2625
2626         return batch;
2627 }
2628
2629 inline void setup_pageset(struct per_cpu_pageset *p, unsigned long batch)
2630 {
2631         struct per_cpu_pages *pcp;
2632
2633         memset(p, 0, sizeof(*p));
2634
2635         pcp = &p->pcp[0];               /* hot */
2636         pcp->count = 0;
2637         pcp->high = 6 * batch;
2638         pcp->batch = max(1UL, 1 * batch);
2639         INIT_LIST_HEAD(&pcp->list);
2640
2641         pcp = &p->pcp[1];               /* cold*/
2642         pcp->count = 0;
2643         pcp->high = 2 * batch;
2644         pcp->batch = max(1UL, batch/2);
2645         INIT_LIST_HEAD(&pcp->list);
2646 }
2647
2648 /*
2649  * setup_pagelist_highmark() sets the high water mark for hot per_cpu_pagelist
2650  * to the value high for the pageset p.
2651  */
2652
2653 static void setup_pagelist_highmark(struct per_cpu_pageset *p,
2654                                 unsigned long high)
2655 {
2656         struct per_cpu_pages *pcp;
2657
2658         pcp = &p->pcp[0]; /* hot list */
2659         pcp->high = high;
2660         pcp->batch = max(1UL, high/4);
2661         if ((high/4) > (PAGE_SHIFT * 8))
2662                 pcp->batch = PAGE_SHIFT * 8;
2663 }
2664
2665
2666 #ifdef CONFIG_NUMA
2667 /*
2668  * Boot pageset table. One per cpu which is going to be used for all
2669  * zones and all nodes. The parameters will be set in such a way
2670  * that an item put on a list will immediately be handed over to
2671  * the buddy list. This is safe since pageset manipulation is done
2672  * with interrupts disabled.
2673  *
2674  * Some NUMA counter updates may also be caught by the boot pagesets.
2675  *
2676  * The boot_pagesets must be kept even after bootup is complete for
2677  * unused processors and/or zones. They do play a role for bootstrapping
2678  * hotplugged processors.
2679  *
2680  * zoneinfo_show() and maybe other functions do
2681  * not check if the processor is online before following the pageset pointer.
2682  * Other parts of the kernel may not check if the zone is available.
2683  */
2684 static struct per_cpu_pageset boot_pageset[NR_CPUS];
2685
2686 /*
2687  * Dynamically allocate memory for the
2688  * per cpu pageset array in struct zone.
2689  */
2690 static int __cpuinit process_zones(int cpu)
2691 {
2692         struct zone *zone, *dzone;
2693         int node = cpu_to_node(cpu);
2694
2695         node_set_state(node, N_CPU);    /* this node has a cpu */
2696
2697         for_each_zone(zone) {
2698
2699                 if (!populated_zone(zone))
2700                         continue;
2701
2702                 zone_pcp(zone, cpu) = kmalloc_node(sizeof(struct per_cpu_pageset),
2703                                          GFP_KERNEL, node);
2704                 if (!zone_pcp(zone, cpu))
2705                         goto bad;
2706
2707                 setup_pageset(zone_pcp(zone, cpu), zone_batchsize(zone));
2708
2709                 if (percpu_pagelist_fraction)
2710                         setup_pagelist_highmark(zone_pcp(zone, cpu),
2711                                 (zone->present_pages / percpu_pagelist_fraction));
2712         }
2713
2714         return 0;
2715 bad:
2716         for_each_zone(dzone) {
2717                 if (!populated_zone(dzone))
2718                         continue;
2719                 if (dzone == zone)
2720                         break;
2721                 kfree(zone_pcp(dzone, cpu));
2722                 zone_pcp(dzone, cpu) = NULL;
2723         }
2724         return -ENOMEM;
2725 }
2726
2727 static inline void free_zone_pagesets(int cpu)
2728 {
2729         struct zone *zone;
2730
2731         for_each_zone(zone) {
2732                 struct per_cpu_pageset *pset = zone_pcp(zone, cpu);
2733
2734                 /* Free per_cpu_pageset if it is slab allocated */
2735                 if (pset != &boot_pageset[cpu])
2736                         kfree(pset);
2737                 zone_pcp(zone, cpu) = NULL;
2738         }
2739 }
2740
2741 static int __cpuinit pageset_cpuup_callback(struct notifier_block *nfb,
2742                 unsigned long action,
2743                 void *hcpu)
2744 {
2745         int cpu = (long)hcpu;
2746         int ret = NOTIFY_OK;
2747
2748         switch (action) {
2749         case CPU_UP_PREPARE:
2750         case CPU_UP_PREPARE_FROZEN:
2751                 if (process_zones(cpu))
2752                         ret = NOTIFY_BAD;
2753                 break;
2754         case CPU_UP_CANCELED:
2755         case CPU_UP_CANCELED_FROZEN:
2756         case CPU_DEAD:
2757         case CPU_DEAD_FROZEN:
2758                 free_zone_pagesets(cpu);
2759                 break;
2760         default:
2761                 break;
2762         }
2763         return ret;
2764 }
2765
2766 static struct notifier_block __cpuinitdata pageset_notifier =
2767         { &pageset_cpuup_callback, NULL, 0 };
2768
2769 void __init setup_per_cpu_pageset(void)
2770 {
2771         int err;
2772
2773         /* Initialize per_cpu_pageset for cpu 0.
2774          * A cpuup callback will do this for every cpu
2775          * as it comes online
2776          */
2777         err = process_zones(smp_processor_id());
2778         BUG_ON(err);
2779         register_cpu_notifier(&pageset_notifier);
2780 }
2781
2782 #endif
2783
2784 static noinline __init_refok
2785 int zone_wait_table_init(struct zone *zone, unsigned long zone_size_pages)
2786 {
2787         int i;
2788         struct pglist_data *pgdat = zone->zone_pgdat;
2789         size_t alloc_size;
2790
2791         /*
2792          * The per-page waitqueue mechanism uses hashed waitqueues
2793          * per zone.
2794          */
2795         zone->wait_table_hash_nr_entries =
2796                  wait_table_hash_nr_entries(zone_size_pages);
2797         zone->wait_table_bits =
2798                 wait_table_bits(zone->wait_table_hash_nr_entries);
2799         alloc_size = zone->wait_table_hash_nr_entries
2800                                         * sizeof(wait_queue_head_t);
2801
2802         if (system_state == SYSTEM_BOOTING) {
2803                 zone->wait_table = (wait_queue_head_t *)
2804                         alloc_bootmem_node(pgdat, alloc_size);
2805         } else {
2806                 /*
2807                  * This case means that a zone whose size was 0 gets new memory
2808                  * via memory hot-add.
2809                  * But it may be the case that a new node was hot-added.  In
2810                  * this case vmalloc() will not be able to use this new node's
2811                  * memory - this wait_table must be initialized to use this new
2812                  * node itself as well.
2813                  * To use this new node's memory, further consideration will be
2814                  * necessary.
2815                  */
2816                 zone->wait_table = vmalloc(alloc_size);
2817         }
2818         if (!zone->wait_table)
2819                 return -ENOMEM;
2820
2821         for(i = 0; i < zone->wait_table_hash_nr_entries; ++i)
2822                 init_waitqueue_head(zone->wait_table + i);
2823
2824         return 0;
2825 }
2826
2827 static __meminit void zone_pcp_init(struct zone *zone)
2828 {
2829         int cpu;
2830         unsigned long batch = zone_batchsize(zone);
2831
2832         for (cpu = 0; cpu < NR_CPUS; cpu++) {
2833 #ifdef CONFIG_NUMA
2834                 /* Early boot. Slab allocator not functional yet */
2835                 zone_pcp(zone, cpu) = &boot_pageset[cpu];
2836                 setup_pageset(&boot_pageset[cpu],0);
2837 #else
2838                 setup_pageset(zone_pcp(zone,cpu), batch);
2839 #endif
2840         }
2841         if (zone->present_pages)
2842                 printk(KERN_DEBUG "  %s zone: %lu pages, LIFO batch:%lu\n",
2843                         zone->name, zone->present_pages, batch);
2844 }
2845
2846 __meminit int init_currently_empty_zone(struct zone *zone,
2847                                         unsigned long zone_start_pfn,
2848                                         unsigned long size,
2849                                         enum memmap_context context)
2850 {
2851         struct pglist_data *pgdat = zone->zone_pgdat;
2852         int ret;
2853         ret = zone_wait_table_init(zone, size);
2854         if (ret)
2855                 return ret;
2856         pgdat->nr_zones = zone_idx(zone) + 1;
2857
2858         zone->zone_start_pfn = zone_start_pfn;
2859
2860         memmap_init(size, pgdat->node_id, zone_idx(zone), zone_start_pfn);
2861
2862         zone_init_free_lists(pgdat, zone, zone->spanned_pages);
2863
2864         return 0;
2865 }
2866
2867 #ifdef CONFIG_ARCH_POPULATES_NODE_MAP
2868 /*
2869  * Basic iterator support. Return the first range of PFNs for a node
2870  * Note: nid == MAX_NUMNODES returns first region regardless of node
2871  */
2872 static int __meminit first_active_region_index_in_nid(int nid)
2873 {
2874         int i;
2875
2876         for (i = 0; i < nr_nodemap_entries; i++)
2877                 if (nid == MAX_NUMNODES || early_node_map[i].nid == nid)
2878                         return i;
2879
2880         return -1;
2881 }
2882
2883 /*
2884  * Basic iterator support. Return the next active range of PFNs for a node
2885  * Note: nid == MAX_NUMNODES returns next region regardles of node
2886  */
2887 static int __meminit next_active_region_index_in_nid(int index, int nid)
2888 {
2889         for (index = index + 1; index < nr_nodemap_entries; index++)
2890                 if (nid == MAX_NUMNODES || early_node_map[index].nid == nid)
2891                         return index;
2892
2893         return -1;
2894 }
2895
2896 #ifndef CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID
2897 /*
2898  * Required by SPARSEMEM. Given a PFN, return what node the PFN is on.
2899  * Architectures may implement their own version but if add_active_range()
2900  * was used and there are no special requirements, this is a convenient
2901  * alternative
2902  */
2903 int __meminit early_pfn_to_nid(unsigned long pfn)
2904 {
2905         int i;
2906
2907         for (i = 0; i < nr_nodemap_entries; i++) {
2908                 unsigned long start_pfn = early_node_map[i].start_pfn;
2909                 unsigned long end_pfn = early_node_map[i].end_pfn;
2910
2911                 if (start_pfn <= pfn && pfn < end_pfn)
2912                         return early_node_map[i].nid;
2913         }
2914
2915         return 0;
2916 }
2917 #endif /* CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID */
2918
2919 /* Basic iterator support to walk early_node_map[] */
2920 #define for_each_active_range_index_in_nid(i, nid) \
2921         for (i = first_active_region_index_in_nid(nid); i != -1; \
2922                                 i = next_active_region_index_in_nid(i, nid))
2923
2924 /**
2925  * free_bootmem_with_active_regions - Call free_bootmem_node for each active range
2926  * @nid: The node to free memory on. If MAX_NUMNODES, all nodes are freed.
2927  * @max_low_pfn: The highest PFN that will be passed to free_bootmem_node
2928  *
2929  * If an architecture guarantees that all ranges registered with
2930  * add_active_ranges() contain no holes and may be freed, this
2931  * this function may be used instead of calling free_bootmem() manually.
2932  */
2933 void __init free_bootmem_with_active_regions(int nid,
2934                                                 unsigned long max_low_pfn)
2935 {
2936         int i;
2937
2938         for_each_active_range_index_in_nid(i, nid) {
2939                 unsigned long size_pages = 0;
2940                 unsigned long end_pfn = early_node_map[i].end_pfn;
2941
2942                 if (early_node_map[i].start_pfn >= max_low_pfn)
2943                         continue;
2944
2945                 if (end_pfn > max_low_pfn)
2946                         end_pfn = max_low_pfn;
2947
2948                 size_pages = end_pfn - early_node_map[i].start_pfn;
2949                 free_bootmem_node(NODE_DATA(early_node_map[i].nid),
2950                                 PFN_PHYS(early_node_map[i].start_pfn),
2951                                 size_pages << PAGE_SHIFT);
2952         }
2953 }
2954
2955 /**
2956  * sparse_memory_present_with_active_regions - Call memory_present for each active range
2957  * @nid: The node to call memory_present for. If MAX_NUMNODES, all nodes will be used.
2958  *
2959  * If an architecture guarantees that all ranges registered with
2960  * add_active_ranges() contain no holes and may be freed, this
2961  * function may be used instead of calling memory_present() manually.
2962  */
2963 void __init sparse_memory_present_with_active_regions(int nid)
2964 {
2965         int i;
2966
2967         for_each_active_range_index_in_nid(i, nid)
2968                 memory_present(early_node_map[i].nid,
2969                                 early_node_map[i].start_pfn,
2970                                 early_node_map[i].end_pfn);
2971 }
2972
2973 /**
2974  * push_node_boundaries - Push node boundaries to at least the requested boundary
2975  * @nid: The nid of the node to push the boundary for
2976  * @start_pfn: The start pfn of the node
2977  * @end_pfn: The end pfn of the node
2978  *
2979  * In reserve-based hot-add, mem_map is allocated that is unused until hotadd
2980  * time. Specifically, on x86_64, SRAT will report ranges that can potentially
2981  * be hotplugged even though no physical memory exists. This function allows
2982  * an arch to push out the node boundaries so mem_map is allocated that can
2983  * be used later.
2984  */
2985 #ifdef CONFIG_MEMORY_HOTPLUG_RESERVE
2986 void __init push_node_boundaries(unsigned int nid,
2987                 unsigned long start_pfn, unsigned long end_pfn)
2988 {
2989         printk(KERN_DEBUG "Entering push_node_boundaries(%u, %lu, %lu)\n",
2990                         nid, start_pfn, end_pfn);
2991
2992         /* Initialise the boundary for this node if necessary */
2993         if (node_boundary_end_pfn[nid] == 0)
2994                 node_boundary_start_pfn[nid] = -1UL;
2995
2996         /* Update the boundaries */
2997         if (node_boundary_start_pfn[nid] > start_pfn)
2998                 node_boundary_start_pfn[nid] = start_pfn;
2999         if (node_boundary_end_pfn[nid] < end_pfn)
3000                 node_boundary_end_pfn[nid] = end_pfn;
3001 }
3002
3003 /* If necessary, push the node boundary out for reserve hotadd */
3004 static void __meminit account_node_boundary(unsigned int nid,
3005                 unsigned long *start_pfn, unsigned long *end_pfn)
3006 {
3007         printk(KERN_DEBUG "Entering account_node_boundary(%u, %lu, %lu)\n",
3008                         nid, *start_pfn, *end_pfn);
3009
3010         /* Return if boundary information has not been provided */
3011         if (node_boundary_end_pfn[nid] == 0)
3012                 return;
3013
3014         /* Check the boundaries and update if necessary */
3015         if (node_boundary_start_pfn[nid] < *start_pfn)
3016                 *start_pfn = node_boundary_start_pfn[nid];
3017         if (node_boundary_end_pfn[nid] > *end_pfn)
3018                 *end_pfn = node_boundary_end_pfn[nid];
3019 }
3020 #else
3021 void __init push_node_boundaries(unsigned int nid,
3022                 unsigned long start_pfn, unsigned long end_pfn) {}
3023
3024 static void __meminit account_node_boundary(unsigned int nid,
3025                 unsigned long *start_pfn, unsigned long *end_pfn) {}
3026 #endif
3027
3028
3029 /**
3030  * get_pfn_range_for_nid - Return the start and end page frames for a node
3031  * @nid: The nid to return the range for. If MAX_NUMNODES, the min and max PFN are returned.
3032  * @start_pfn: Passed by reference. On return, it will have the node start_pfn.
3033  * @end_pfn: Passed by reference. On return, it will have the node end_pfn.
3034  *
3035  * It returns the start and end page frame of a node based on information
3036  * provided by an arch calling add_active_range(). If called for a node
3037  * with no available memory, a warning is printed and the start and end
3038  * PFNs will be 0.
3039  */
3040 void __meminit get_pfn_range_for_nid(unsigned int nid,
3041                         unsigned long *start_pfn, unsigned long *end_pfn)
3042 {
3043         int i;
3044         *start_pfn = -1UL;
3045         *end_pfn = 0;
3046
3047         for_each_active_range_index_in_nid(i, nid) {
3048                 *start_pfn = min(*start_pfn, early_node_map[i].start_pfn);
3049                 *end_pfn = max(*end_pfn, early_node_map[i].end_pfn);
3050         }
3051
3052         if (*start_pfn == -1UL)
3053                 *start_pfn = 0;
3054
3055         /* Push the node boundaries out if requested */
3056         account_node_boundary(nid, start_pfn, end_pfn);
3057 }
3058
3059 /*
3060  * This finds a zone that can be used for ZONE_MOVABLE pages. The
3061  * assumption is made that zones within a node are ordered in monotonic
3062  * increasing memory addresses so that the "highest" populated zone is used
3063  */
3064 void __init find_usable_zone_for_movable(void)
3065 {
3066         int zone_index;
3067         for (zone_index = MAX_NR_ZONES - 1; zone_index >= 0; zone_index--) {
3068                 if (zone_index == ZONE_MOVABLE)
3069                         continue;
3070
3071                 if (arch_zone_highest_possible_pfn[zone_index] >
3072                                 arch_zone_lowest_possible_pfn[zone_index])
3073                         break;
3074         }
3075
3076         VM_BUG_ON(zone_index == -1);
3077         movable_zone = zone_index;
3078 }
3079
3080 /*
3081  * The zone ranges provided by the architecture do not include ZONE_MOVABLE
3082  * because it is sized independant of architecture. Unlike the other zones,
3083  * the starting point for ZONE_MOVABLE is not fixed. It may be different
3084  * in each node depending on the size of each node and how evenly kernelcore
3085  * is distributed. This helper function adjusts the zone ranges
3086  * provided by the architecture for a given node by using the end of the
3087  * highest usable zone for ZONE_MOVABLE. This preserves the assumption that
3088  * zones within a node are in order of monotonic increases memory addresses
3089  */
3090 void __meminit adjust_zone_range_for_zone_movable(int nid,
3091                                         unsigned long zone_type,
3092                                         unsigned long node_start_pfn,
3093                                         unsigned long node_end_pfn,
3094                                         unsigned long *zone_start_pfn,
3095                                         unsigned long *zone_end_pfn)
3096 {
3097         /* Only adjust if ZONE_MOVABLE is on this node */
3098         if (zone_movable_pfn[nid]) {
3099                 /* Size ZONE_MOVABLE */
3100                 if (zone_type == ZONE_MOVABLE) {
3101                         *zone_start_pfn = zone_movable_pfn[nid];
3102                         *zone_end_pfn = min(node_end_pfn,
3103                                 arch_zone_highest_possible_pfn[movable_zone]);
3104
3105                 /* Adjust for ZONE_MOVABLE starting within this range */
3106                 } else if (*zone_start_pfn < zone_movable_pfn[nid] &&
3107                                 *zone_end_pfn > zone_movable_pfn[nid]) {
3108                         *zone_end_pfn = zone_movable_pfn[nid];
3109
3110                 /* Check if this whole range is within ZONE_MOVABLE */
3111                 } else if (*zone_start_pfn >= zone_movable_pfn[nid])
3112                         *zone_start_pfn = *zone_end_pfn;
3113         }
3114 }
3115
3116 /*
3117  * Return the number of pages a zone spans in a node, including holes
3118  * present_pages = zone_spanned_pages_in_node() - zone_absent_pages_in_node()
3119  */
3120 static unsigned long __meminit zone_spanned_pages_in_node(int nid,
3121                                         unsigned long zone_type,
3122                                         unsigned long *ignored)
3123 {
3124         unsigned long node_start_pfn, node_end_pfn;
3125         unsigned long zone_start_pfn, zone_end_pfn;
3126
3127         /* Get the start and end of the node and zone */
3128         get_pfn_range_for_nid(nid, &node_start_pfn, &node_end_pfn);
3129         zone_start_pfn = arch_zone_lowest_possible_pfn[zone_type];
3130         zone_end_pfn = arch_zone_highest_possible_pfn[zone_type];
3131         adjust_zone_range_for_zone_movable(nid, zone_type,
3132                                 node_start_pfn, node_end_pfn,
3133                                 &zone_start_pfn, &zone_end_pfn);
3134
3135         /* Check that this node has pages within the zone's required range */
3136         if (zone_end_pfn < node_start_pfn || zone_start_pfn > node_end_pfn)
3137                 return 0;
3138
3139         /* Move the zone boundaries inside the node if necessary */
3140         zone_end_pfn = min(zone_end_pfn, node_end_pfn);
3141         zone_start_pfn = max(zone_start_pfn, node_start_pfn);
3142
3143         /* Return the spanned pages */
3144         return zone_end_pfn - zone_start_pfn;
3145 }
3146
3147 /*
3148  * Return the number of holes in a range on a node. If nid is MAX_NUMNODES,
3149  * then all holes in the requested range will be accounted for.
3150  */
3151 unsigned long __meminit __absent_pages_in_range(int nid,
3152                                 unsigned long range_start_pfn,
3153                                 unsigned long range_end_pfn)
3154 {
3155         int i = 0;
3156         unsigned long prev_end_pfn = 0, hole_pages = 0;
3157         unsigned long start_pfn;
3158
3159         /* Find the end_pfn of the first active range of pfns in the node */
3160         i = first_active_region_index_in_nid(nid);
3161         if (i == -1)
3162                 return 0;
3163
3164         prev_end_pfn = min(early_node_map[i].start_pfn, range_end_pfn);
3165
3166         /* Account for ranges before physical memory on this node */
3167         if (early_node_map[i].start_pfn > range_start_pfn)
3168                 hole_pages = prev_end_pfn - range_start_pfn;
3169
3170         /* Find all holes for the zone within the node */
3171         for (; i != -1; i = next_active_region_index_in_nid(i, nid)) {
3172
3173                 /* No need to continue if prev_end_pfn is outside the zone */
3174                 if (prev_end_pfn >= range_end_pfn)
3175                         break;
3176
3177                 /* Make sure the end of the zone is not within the hole */
3178                 start_pfn = min(early_node_map[i].start_pfn, range_end_pfn);
3179                 prev_end_pfn = max(prev_end_pfn, range_start_pfn);
3180
3181                 /* Update the hole size cound and move on */
3182                 if (start_pfn > range_start_pfn) {
3183                         BUG_ON(prev_end_pfn > start_pfn);
3184                         hole_pages += start_pfn - prev_end_pfn;
3185                 }
3186                 prev_end_pfn = early_node_map[i].end_pfn;
3187         }
3188
3189         /* Account for ranges past physical memory on this node */
3190         if (range_end_pfn > prev_end_pfn)
3191                 hole_pages += range_end_pfn -
3192                                 max(range_start_pfn, prev_end_pfn);
3193
3194         return hole_pages;
3195 }
3196
3197 /**
3198  * absent_pages_in_range - Return number of page frames in holes within a range
3199  * @start_pfn: The start PFN to start searching for holes
3200  * @end_pfn: The end PFN to stop searching for holes
3201  *
3202  * It returns the number of pages frames in memory holes within a range.
3203  */
3204 unsigned long __init absent_pages_in_range(unsigned long start_pfn,
3205                                                         unsigned long end_pfn)
3206 {
3207         return __absent_pages_in_range(MAX_NUMNODES, start_pfn, end_pfn);
3208 }
3209
3210 /* Return the number of page frames in holes in a zone on a node */
3211 static unsigned long __meminit zone_absent_pages_in_node(int nid,
3212                                         unsigned long zone_type,
3213                                         unsigned long *ignored)
3214 {
3215         unsigned long node_start_pfn, node_end_pfn;
3216         unsigned long zone_start_pfn, zone_end_pfn;
3217
3218         get_pfn_range_for_nid(nid, &node_start_pfn, &node_end_pfn);
3219         zone_start_pfn = max(arch_zone_lowest_possible_pfn[zone_type],
3220                                                         node_start_pfn);
3221         zone_end_pfn = min(arch_zone_highest_possible_pfn[zone_type],
3222                                                         node_end_pfn);
3223
3224         adjust_zone_range_for_zone_movable(nid, zone_type,
3225                         node_start_pfn, node_end_pfn,
3226                         &zone_start_pfn, &zone_end_pfn);
3227         return __absent_pages_in_range(nid, zone_start_pfn, zone_end_pfn);
3228 }
3229
3230 #else
3231 static inline unsigned long __meminit zone_spanned_pages_in_node(int nid,
3232                                         unsigned long zone_type,
3233                                         unsigned long *zones_size)
3234 {
3235         return zones_size[zone_type];
3236 }
3237
3238 static inline unsigned long __meminit zone_absent_pages_in_node(int nid,
3239                                                 unsigned long zone_type,
3240                                                 unsigned long *zholes_size)
3241 {
3242         if (!zholes_size)
3243                 return 0;
3244
3245         return zholes_size[zone_type];
3246 }
3247
3248 #endif
3249
3250 static void __meminit calculate_node_totalpages(struct pglist_data *pgdat,
3251                 unsigned long *zones_size, unsigned long *zholes_size)
3252 {
3253         unsigned long realtotalpages, totalpages = 0;
3254         enum zone_type i;
3255
3256         for (i = 0; i < MAX_NR_ZONES; i++)
3257                 totalpages += zone_spanned_pages_in_node(pgdat->node_id, i,
3258                                                                 zones_size);
3259         pgdat->node_spanned_pages = totalpages;
3260
3261         realtotalpages = totalpages;
3262         for (i = 0; i < MAX_NR_ZONES; i++)
3263                 realtotalpages -=
3264                         zone_absent_pages_in_node(pgdat->node_id, i,
3265                                                                 zholes_size);
3266         pgdat->node_present_pages = realtotalpages;
3267         printk(KERN_DEBUG "On node %d totalpages: %lu\n", pgdat->node_id,
3268                                                         realtotalpages);
3269 }
3270
3271 #ifndef CONFIG_SPARSEMEM
3272 /*
3273  * Calculate the size of the zone->blockflags rounded to an unsigned long
3274  * Start by making sure zonesize is a multiple of pageblock_order by rounding
3275  * up. Then use 1 NR_PAGEBLOCK_BITS worth of bits per pageblock, finally
3276  * round what is now in bits to nearest long in bits, then return it in
3277  * bytes.
3278  */
3279 static unsigned long __init usemap_size(unsigned long zonesize)
3280 {
3281         unsigned long usemapsize;
3282
3283         usemapsize = roundup(zonesize, pageblock_nr_pages);
3284         usemapsize = usemapsize >> pageblock_order;
3285         usemapsize *= NR_PAGEBLOCK_BITS;
3286         usemapsize = roundup(usemapsize, 8 * sizeof(unsigned long));
3287
3288         return usemapsize / 8;
3289 }
3290
3291 static void __init setup_usemap(struct pglist_data *pgdat,
3292                                 struct zone *zone, unsigned long zonesize)
3293 {
3294         unsigned long usemapsize = usemap_size(zonesize);
3295         zone->pageblock_flags = NULL;
3296         if (usemapsize) {
3297                 zone->pageblock_flags = alloc_bootmem_node(pgdat, usemapsize);
3298                 memset(zone->pageblock_flags, 0, usemapsize);
3299         }
3300 }
3301 #else
3302 static void inline setup_usemap(struct pglist_data *pgdat,
3303                                 struct zone *zone, unsigned long zonesize) {}
3304 #endif /* CONFIG_SPARSEMEM */
3305
3306 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
3307 /* Initialise the number of pages represented by NR_PAGEBLOCK_BITS */
3308 static inline void __init set_pageblock_order(unsigned int order)
3309 {
3310         /* Check that pageblock_nr_pages has not already been setup */
3311         if (pageblock_order)
3312                 return;
3313
3314         /*
3315          * Assume the largest contiguous order of interest is a huge page.
3316          * This value may be variable depending on boot parameters on IA64
3317          */
3318         pageblock_order = order;
3319 }
3320 #else /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
3321
3322 /* Defined this way to avoid accidently referencing HUGETLB_PAGE_ORDER */
3323 #define set_pageblock_order(x)  do {} while (0)
3324
3325 #endif /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
3326
3327 /*
3328  * Set up the zone data structures:
3329  *   - mark all pages reserved
3330  *   - mark all memory queues empty
3331  *   - clear the memory bitmaps
3332  */
3333 static void __meminit free_area_init_core(struct pglist_data *pgdat,
3334                 unsigned long *zones_size, unsigned long *zholes_size)
3335 {
3336         enum zone_type j;
3337         int nid = pgdat->node_id;
3338         unsigned long zone_start_pfn = pgdat->node_start_pfn;
3339         int ret;
3340
3341         pgdat_resize_init(pgdat);
3342         pgdat->nr_zones = 0;
3343         init_waitqueue_head(&pgdat->kswapd_wait);
3344         pgdat->kswapd_max_order = 0;
3345         
3346         for (j = 0; j < MAX_NR_ZONES; j++) {
3347                 struct zone *zone = pgdat->node_zones + j;
3348                 unsigned long size, realsize, memmap_pages;
3349
3350                 size = zone_spanned_pages_in_node(nid, j, zones_size);
3351                 realsize = size - zone_absent_pages_in_node(nid, j,
3352                                                                 zholes_size);
3353
3354                 /*
3355                  * Adjust realsize so that it accounts for how much memory
3356                  * is used by this zone for memmap. This affects the watermark
3357                  * and per-cpu initialisations
3358                  */
3359                 memmap_pages = (size * sizeof(struct page)) >> PAGE_SHIFT;
3360                 if (realsize >= memmap_pages) {
3361                         realsize -= memmap_pages;
3362                         printk(KERN_DEBUG
3363                                 "  %s zone: %lu pages used for memmap\n",
3364                                 zone_names[j], memmap_pages);
3365                 } else
3366                         printk(KERN_WARNING
3367                                 "  %s zone: %lu pages exceeds realsize %lu\n",
3368                                 zone_names[j], memmap_pages, realsize);
3369
3370                 /* Account for reserved pages */
3371                 if (j == 0 && realsize > dma_reserve) {
3372                         realsize -= dma_reserve;
3373                         printk(KERN_DEBUG "  %s zone: %lu pages reserved\n",
3374                                         zone_names[0], dma_reserve);
3375                 }
3376
3377                 if (!is_highmem_idx(j))
3378                         nr_kernel_pages += realsize;
3379                 nr_all_pages += realsize;
3380
3381                 zone->spanned_pages = size;
3382                 zone->present_pages = realsize;
3383 #ifdef CONFIG_NUMA
3384                 zone->node = nid;
3385                 zone->min_unmapped_pages = (realsize*sysctl_min_unmapped_ratio)
3386                                                 / 100;
3387                 zone->min_slab_pages = (realsize * sysctl_min_slab_ratio) / 100;
3388 #endif
3389                 zone->name = zone_names[j];
3390                 spin_lock_init(&zone->lock);
3391                 spin_lock_init(&zone->lru_lock);
3392                 zone_seqlock_init(zone);
3393                 zone->zone_pgdat = pgdat;
3394
3395                 zone->prev_priority = DEF_PRIORITY;
3396
3397                 zone_pcp_init(zone);
3398                 INIT_LIST_HEAD(&zone->active_list);
3399                 INIT_LIST_HEAD(&zone->inactive_list);
3400                 zone->nr_scan_active = 0;
3401                 zone->nr_scan_inactive = 0;
3402                 zap_zone_vm_stats(zone);
3403                 atomic_set(&zone->reclaim_in_progress, 0);
3404                 if (!size)
3405                         continue;
3406
3407                 set_pageblock_order(HUGETLB_PAGE_ORDER);
3408                 setup_usemap(pgdat, zone, size);
3409                 ret = init_currently_empty_zone(zone, zone_start_pfn,
3410                                                 size, MEMMAP_EARLY);
3411                 BUG_ON(ret);
3412                 zone_start_pfn += size;
3413         }
3414 }
3415
3416 static void __init_refok alloc_node_mem_map(struct pglist_data *pgdat)
3417 {
3418         /* Skip empty nodes */
3419         if (!pgdat->node_spanned_pages)
3420                 return;
3421
3422 #ifdef CONFIG_FLAT_NODE_MEM_MAP
3423         /* ia64 gets its own node_mem_map, before this, without bootmem */
3424         if (!pgdat->node_mem_map) {
3425                 unsigned long size, start, end;
3426                 struct page *map;
3427
3428                 /*
3429                  * The zone's endpoints aren't required to be MAX_ORDER
3430                  * aligned but the node_mem_map endpoints must be in order
3431                  * for the buddy allocator to function correctly.
3432                  */
3433                 start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1);
3434                 end = pgdat->node_start_pfn + pgdat->node_spanned_pages;
3435                 end = ALIGN(end, MAX_ORDER_NR_PAGES);
3436                 size =  (end - start) * sizeof(struct page);
3437                 map = alloc_remap(pgdat->node_id, size);
3438                 if (!map)
3439                         map = alloc_bootmem_node(pgdat, size);
3440                 pgdat->node_mem_map = map + (pgdat->node_start_pfn - start);
3441         }
3442 #ifndef CONFIG_NEED_MULTIPLE_NODES
3443         /*
3444          * With no DISCONTIG, the global mem_map is just set as node 0's
3445          */
3446         if (pgdat == NODE_DATA(0)) {
3447                 mem_map = NODE_DATA(0)->node_mem_map;
3448 #ifdef CONFIG_ARCH_POPULATES_NODE_MAP
3449                 if (page_to_pfn(mem_map) != pgdat->node_start_pfn)
3450                         mem_map -= pgdat->node_start_pfn;
3451 #endif /* CONFIG_ARCH_POPULATES_NODE_MAP */
3452         }
3453 #endif
3454 #endif /* CONFIG_FLAT_NODE_MEM_MAP */
3455 }
3456
3457 void __meminit free_area_init_node(int nid, struct pglist_data *pgdat,
3458                 unsigned long *zones_size, unsigned long node_start_pfn,
3459                 unsigned long *zholes_size)
3460 {
3461         pgdat->node_id = nid;
3462         pgdat->node_start_pfn = node_start_pfn;
3463         calculate_node_totalpages(pgdat, zones_size, zholes_size);
3464
3465         alloc_node_mem_map(pgdat);
3466
3467         free_area_init_core(pgdat, zones_size, zholes_size);
3468 }
3469
3470 #ifdef CONFIG_ARCH_POPULATES_NODE_MAP
3471
3472 #if MAX_NUMNODES > 1
3473 /*
3474  * Figure out the number of possible node ids.
3475  */
3476 static void __init setup_nr_node_ids(void)
3477 {
3478         unsigned int node;
3479         unsigned int highest = 0;
3480
3481         for_each_node_mask(node, node_possible_map)
3482                 highest = node;
3483         nr_node_ids = highest + 1;
3484 }
3485 #else
3486 static inline void setup_nr_node_ids(void)
3487 {
3488 }
3489 #endif
3490
3491 /**
3492  * add_active_range - Register a range of PFNs backed by physical memory
3493  * @nid: The node ID the range resides on
3494  * @start_pfn: The start PFN of the available physical memory
3495  * @end_pfn: The end PFN of the available physical memory
3496  *
3497  * These ranges are stored in an early_node_map[] and later used by
3498  * free_area_init_nodes() to calculate zone sizes and holes. If the
3499  * range spans a memory hole, it is up to the architecture to ensure
3500  * the memory is not freed by the bootmem allocator. If possible
3501  * the range being registered will be merged with existing ranges.
3502  */
3503 void __init add_active_range(unsigned int nid, unsigned long start_pfn,
3504                                                 unsigned long end_pfn)
3505 {
3506         int i;
3507
3508         printk(KERN_DEBUG "Entering add_active_range(%d, %lu, %lu) "
3509                           "%d entries of %d used\n",
3510                           nid, start_pfn, end_pfn,
3511                           nr_nodemap_entries, MAX_ACTIVE_REGIONS);
3512
3513         /* Merge with existing active regions if possible */
3514         for (i = 0; i < nr_nodemap_entries; i++) {
3515                 if (early_node_map[i].nid != nid)
3516                         continue;
3517
3518                 /* Skip if an existing region covers this new one */
3519                 if (start_pfn >= early_node_map[i].start_pfn &&
3520                                 end_pfn <= early_node_map[i].end_pfn)
3521                         return;
3522
3523                 /* Merge forward if suitable */
3524                 if (start_pfn <= early_node_map[i].end_pfn &&
3525                                 end_pfn > early_node_map[i].end_pfn) {
3526                         early_node_map[i].end_pfn = end_pfn;
3527                         return;
3528                 }
3529
3530                 /* Merge backward if suitable */
3531                 if (start_pfn < early_node_map[i].end_pfn &&
3532                                 end_pfn >= early_node_map[i].start_pfn) {
3533                         early_node_map[i].start_pfn = start_pfn;
3534                         return;
3535                 }
3536         }
3537
3538         /* Check that early_node_map is large enough */
3539         if (i >= MAX_ACTIVE_REGIONS) {
3540                 printk(KERN_CRIT "More than %d memory regions, truncating\n",
3541                                                         MAX_ACTIVE_REGIONS);
3542                 return;
3543         }
3544
3545         early_node_map[i].nid = nid;
3546         early_node_map[i].start_pfn = start_pfn;
3547         early_node_map[i].end_pfn = end_pfn;
3548         nr_nodemap_entries = i + 1;
3549 }
3550
3551 /**
3552  * shrink_active_range - Shrink an existing registered range of PFNs
3553  * @nid: The node id the range is on that should be shrunk
3554  * @old_end_pfn: The old end PFN of the range
3555  * @new_end_pfn: The new PFN of the range
3556  *
3557  * i386 with NUMA use alloc_remap() to store a node_mem_map on a local node.
3558  * The map is kept at the end physical page range that has already been
3559  * registered with add_active_range(). This function allows an arch to shrink
3560  * an existing registered range.
3561  */
3562 void __init shrink_active_range(unsigned int nid, unsigned long old_end_pfn,
3563                                                 unsigned long new_end_pfn)
3564 {
3565         int i;
3566
3567         /* Find the old active region end and shrink */
3568         for_each_active_range_index_in_nid(i, nid)
3569                 if (early_node_map[i].end_pfn == old_end_pfn) {
3570                         early_node_map[i].end_pfn = new_end_pfn;
3571                         break;
3572                 }
3573 }
3574
3575 /**
3576  * remove_all_active_ranges - Remove all currently registered regions
3577  *
3578  * During discovery, it may be found that a table like SRAT is invalid
3579  * and an alternative discovery method must be used. This function removes
3580  * all currently registered regions.
3581  */
3582 void __init remove_all_active_ranges(void)
3583 {
3584         memset(early_node_map, 0, sizeof(early_node_map));
3585         nr_nodemap_entries = 0;
3586 #ifdef CONFIG_MEMORY_HOTPLUG_RESERVE
3587         memset(node_boundary_start_pfn, 0, sizeof(node_boundary_start_pfn));
3588         memset(node_boundary_end_pfn, 0, sizeof(node_boundary_end_pfn));
3589 #endif /* CONFIG_MEMORY_HOTPLUG_RESERVE */
3590 }
3591
3592 /* Compare two active node_active_regions */
3593 static int __init cmp_node_active_region(const void *a, const void *b)
3594 {
3595         struct node_active_region *arange = (struct node_active_region *)a;
3596         struct node_active_region *brange = (struct node_active_region *)b;
3597
3598         /* Done this way to avoid overflows */
3599         if (arange->start_pfn > brange->start_pfn)
3600                 return 1;
3601         if (arange->start_pfn < brange->start_pfn)
3602                 return -1;
3603
3604         return 0;
3605 }
3606
3607 /* sort the node_map by start_pfn */
3608 static void __init sort_node_map(void)
3609 {
3610         sort(early_node_map, (size_t)nr_nodemap_entries,
3611                         sizeof(struct node_active_region),
3612                         cmp_node_active_region, NULL);
3613 }
3614
3615 /* Find the lowest pfn for a node */
3616 unsigned long __init find_min_pfn_for_node(unsigned long nid)
3617 {
3618         int i;
3619         unsigned long min_pfn = ULONG_MAX;
3620
3621         /* Assuming a sorted map, the first range found has the starting pfn */
3622         for_each_active_range_index_in_nid(i, nid)
3623                 min_pfn = min(min_pfn, early_node_map[i].start_pfn);
3624
3625         if (min_pfn == ULONG_MAX) {
3626                 printk(KERN_WARNING
3627                         "Could not find start_pfn for node %lu\n", nid);
3628                 return 0;
3629         }
3630
3631         return min_pfn;
3632 }
3633
3634 /**
3635  * find_min_pfn_with_active_regions - Find the minimum PFN registered
3636  *
3637  * It returns the minimum PFN based on information provided via
3638  * add_active_range().
3639  */
3640 unsigned long __init find_min_pfn_with_active_regions(void)
3641 {
3642         return find_min_pfn_for_node(MAX_NUMNODES);
3643 }
3644
3645 /**
3646  * find_max_pfn_with_active_regions - Find the maximum PFN registered
3647  *
3648  * It returns the maximum PFN based on information provided via
3649  * add_active_range().
3650  */
3651 unsigned long __init find_max_pfn_with_active_regions(void)
3652 {
3653         int i;
3654         unsigned long max_pfn = 0;
3655
3656         for (i = 0; i < nr_nodemap_entries; i++)
3657                 max_pfn = max(max_pfn, early_node_map[i].end_pfn);
3658
3659         return max_pfn;
3660 }
3661
3662 /*
3663  * early_calculate_totalpages()
3664  * Sum pages in active regions for movable zone.
3665  * Populate N_HIGH_MEMORY for calculating usable_nodes.
3666  */
3667 unsigned long __init early_calculate_totalpages(void)
3668 {
3669         int i;
3670         unsigned long totalpages = 0;
3671
3672         for (i = 0; i < nr_nodemap_entries; i++) {
3673                 unsigned long pages = early_node_map[i].end_pfn -
3674                                                 early_node_map[i].start_pfn;
3675                 totalpages += pages;
3676                 if (pages)
3677                         node_set_state(early_node_map[i].nid, N_HIGH_MEMORY);
3678         }
3679         return totalpages;
3680 }
3681
3682 /*
3683  * Find the PFN the Movable zone begins in each node. Kernel memory
3684  * is spread evenly between nodes as long as the nodes have enough
3685  * memory. When they don't, some nodes will have more kernelcore than
3686  * others
3687  */
3688 void __init find_zone_movable_pfns_for_nodes(unsigned long *movable_pfn)
3689 {
3690         int i, nid;
3691         unsigned long usable_startpfn;
3692         unsigned long kernelcore_node, kernelcore_remaining;
3693         unsigned long totalpages = early_calculate_totalpages();
3694         int usable_nodes = nodes_weight(node_states[N_HIGH_MEMORY]);
3695
3696         /*
3697          * If movablecore was specified, calculate what size of
3698          * kernelcore that corresponds so that memory usable for
3699          * any allocation type is evenly spread. If both kernelcore
3700          * and movablecore are specified, then the value of kernelcore
3701          * will be used for required_kernelcore if it's greater than
3702          * what movablecore would have allowed.
3703          */
3704         if (required_movablecore) {
3705                 unsigned long corepages;
3706
3707                 /*
3708                  * Round-up so that ZONE_MOVABLE is at least as large as what
3709                  * was requested by the user
3710                  */
3711                 required_movablecore =
3712                         roundup(required_movablecore, MAX_ORDER_NR_PAGES);
3713                 corepages = totalpages - required_movablecore;
3714
3715                 required_kernelcore = max(required_kernelcore, corepages);
3716         }
3717
3718         /* If kernelcore was not specified, there is no ZONE_MOVABLE */
3719         if (!required_kernelcore)
3720                 return;
3721
3722         /* usable_startpfn is the lowest possible pfn ZONE_MOVABLE can be at */
3723         find_usable_zone_for_movable();
3724         usable_startpfn = arch_zone_lowest_possible_pfn[movable_zone];
3725
3726 restart:
3727         /* Spread kernelcore memory as evenly as possible throughout nodes */
3728         kernelcore_node = required_kernelcore / usable_nodes;
3729         for_each_node_state(nid, N_HIGH_MEMORY) {
3730                 /*
3731                  * Recalculate kernelcore_node if the division per node
3732                  * now exceeds what is necessary to satisfy the requested
3733                  * amount of memory for the kernel
3734                  */
3735                 if (required_kernelcore < kernelcore_node)
3736                         kernelcore_node = required_kernelcore / usable_nodes;
3737
3738                 /*
3739                  * As the map is walked, we track how much memory is usable
3740                  * by the kernel using kernelcore_remaining. When it is
3741                  * 0, the rest of the node is usable by ZONE_MOVABLE
3742                  */
3743                 kernelcore_remaining = kernelcore_node;
3744
3745                 /* Go through each range of PFNs within this node */
3746                 for_each_active_range_index_in_nid(i, nid) {
3747                         unsigned long start_pfn, end_pfn;
3748                         unsigned long size_pages;
3749
3750                         start_pfn = max(early_node_map[i].start_pfn,
3751                                                 zone_movable_pfn[nid]);
3752                         end_pfn = early_node_map[i].end_pfn;
3753                         if (start_pfn >= end_pfn)
3754                                 continue;
3755
3756                         /* Account for what is only usable for kernelcore */
3757                         if (start_pfn < usable_startpfn) {
3758                                 unsigned long kernel_pages;
3759                                 kernel_pages = min(end_pfn, usable_startpfn)
3760                                                                 - start_pfn;
3761
3762                                 kernelcore_remaining -= min(kernel_pages,
3763                                                         kernelcore_remaining);
3764                                 required_kernelcore -= min(kernel_pages,
3765                                                         required_kernelcore);
3766
3767                                 /* Continue if range is now fully accounted */
3768                                 if (end_pfn <= usable_startpfn) {
3769
3770                                         /*
3771                                          * Push zone_movable_pfn to the end so
3772                                          * that if we have to rebalance
3773                                          * kernelcore across nodes, we will
3774                                          * not double account here
3775                                          */
3776                                         zone_movable_pfn[nid] = end_pfn;
3777                                         continue;
3778                                 }
3779                                 start_pfn = usable_startpfn;
3780                         }
3781
3782                         /*
3783                          * The usable PFN range for ZONE_MOVABLE is from
3784                          * start_pfn->end_pfn. Calculate size_pages as the
3785                          * number of pages used as kernelcore
3786                          */
3787                         size_pages = end_pfn - start_pfn;
3788                         if (size_pages > kernelcore_remaining)
3789                                 size_pages = kernelcore_remaining;
3790                         zone_movable_pfn[nid] = start_pfn + size_pages;
3791
3792                         /*
3793                          * Some kernelcore has been met, update counts and
3794                          * break if the kernelcore for this node has been
3795                          * satisified
3796                          */
3797                         required_kernelcore -= min(required_kernelcore,
3798                                                                 size_pages);
3799                         kernelcore_remaining -= size_pages;
3800                         if (!kernelcore_remaining)
3801                                 break;
3802                 }
3803         }
3804
3805         /*
3806          * If there is still required_kernelcore, we do another pass with one
3807          * less node in the count. This will push zone_movable_pfn[nid] further
3808          * along on the nodes that still have memory until kernelcore is
3809          * satisified
3810          */
3811         usable_nodes--;
3812         if (usable_nodes && required_kernelcore > usable_nodes)
3813                 goto restart;
3814
3815         /* Align start of ZONE_MOVABLE on all nids to MAX_ORDER_NR_PAGES */
3816         for (nid = 0; nid < MAX_NUMNODES; nid++)
3817                 zone_movable_pfn[nid] =
3818                         roundup(zone_movable_pfn[nid], MAX_ORDER_NR_PAGES);
3819 }
3820
3821 /* Any regular memory on that node ? */
3822 static void check_for_regular_memory(pg_data_t *pgdat)
3823 {
3824 #ifdef CONFIG_HIGHMEM
3825         enum zone_type zone_type;
3826
3827         for (zone_type = 0; zone_type <= ZONE_NORMAL; zone_type++) {
3828                 struct zone *zone = &pgdat->node_zones[zone_type];
3829                 if (zone->present_pages)
3830                         node_set_state(zone_to_nid(zone), N_NORMAL_MEMORY);
3831         }
3832 #endif
3833 }
3834
3835 /**
3836  * free_area_init_nodes - Initialise all pg_data_t and zone data
3837  * @max_zone_pfn: an array of max PFNs for each zone
3838  *
3839  * This will call free_area_init_node() for each active node in the system.
3840  * Using the page ranges provided by add_active_range(), the size of each
3841  * zone in each node and their holes is calculated. If the maximum PFN
3842  * between two adjacent zones match, it is assumed that the zone is empty.
3843  * For example, if arch_max_dma_pfn == arch_max_dma32_pfn, it is assumed
3844  * that arch_max_dma32_pfn has no pages. It is also assumed that a zone
3845  * starts where the previous one ended. For example, ZONE_DMA32 starts
3846  * at arch_max_dma_pfn.
3847  */
3848 void __init free_area_init_nodes(unsigned long *max_zone_pfn)
3849 {
3850         unsigned long nid;
3851         enum zone_type i;
3852
3853         /* Sort early_node_map as initialisation assumes it is sorted */
3854         sort_node_map();
3855
3856         /* Record where the zone boundaries are */
3857         memset(arch_zone_lowest_possible_pfn, 0,
3858                                 sizeof(arch_zone_lowest_possible_pfn));
3859         memset(arch_zone_highest_possible_pfn, 0,
3860                                 sizeof(arch_zone_highest_possible_pfn));
3861         arch_zone_lowest_possible_pfn[0] = find_min_pfn_with_active_regions();
3862         arch_zone_highest_possible_pfn[0] = max_zone_pfn[0];
3863         for (i = 1; i < MAX_NR_ZONES; i++) {
3864                 if (i == ZONE_MOVABLE)
3865                         continue;
3866                 arch_zone_lowest_possible_pfn[i] =
3867                         arch_zone_highest_possible_pfn[i-1];
3868                 arch_zone_highest_possible_pfn[i] =
3869                         max(max_zone_pfn[i], arch_zone_lowest_possible_pfn[i]);
3870         }
3871         arch_zone_lowest_possible_pfn[ZONE_MOVABLE] = 0;
3872         arch_zone_highest_possible_pfn[ZONE_MOVABLE] = 0;
3873
3874         /* Find the PFNs that ZONE_MOVABLE begins at in each node */
3875         memset(zone_movable_pfn, 0, sizeof(zone_movable_pfn));
3876         find_zone_movable_pfns_for_nodes(zone_movable_pfn);
3877
3878         /* Print out the zone ranges */
3879         printk("Zone PFN ranges:\n");
3880         for (i = 0; i < MAX_NR_ZONES; i++) {
3881                 if (i == ZONE_MOVABLE)
3882                         continue;
3883                 printk("  %-8s %8lu -> %8lu\n",
3884                                 zone_names[i],
3885                                 arch_zone_lowest_possible_pfn[i],
3886                                 arch_zone_highest_possible_pfn[i]);
3887         }
3888
3889         /* Print out the PFNs ZONE_MOVABLE begins at in each node */
3890         printk("Movable zone start PFN for each node\n");
3891         for (i = 0; i < MAX_NUMNODES; i++) {
3892                 if (zone_movable_pfn[i])
3893                         printk("  Node %d: %lu\n", i, zone_movable_pfn[i]);
3894         }
3895
3896         /* Print out the early_node_map[] */
3897         printk("early_node_map[%d] active PFN ranges\n", nr_nodemap_entries);
3898         for (i = 0; i < nr_nodemap_entries; i++)
3899                 printk("  %3d: %8lu -> %8lu\n", early_node_map[i].nid,
3900                                                 early_node_map[i].start_pfn,
3901                                                 early_node_map[i].end_pfn);
3902
3903         /* Initialise every node */
3904         setup_nr_node_ids();
3905         for_each_online_node(nid) {
3906                 pg_data_t *pgdat = NODE_DATA(nid);
3907                 free_area_init_node(nid, pgdat, NULL,
3908                                 find_min_pfn_for_node(nid), NULL);
3909
3910                 /* Any memory on that node */
3911                 if (pgdat->node_present_pages)
3912                         node_set_state(nid, N_HIGH_MEMORY);
3913                 check_for_regular_memory(pgdat);
3914         }
3915 }
3916
3917 static int __init cmdline_parse_core(char *p, unsigned long *core)
3918 {
3919         unsigned long long coremem;
3920         if (!p)
3921                 return -EINVAL;
3922
3923         coremem = memparse(p, &p);
3924         *core = coremem >> PAGE_SHIFT;
3925
3926         /* Paranoid check that UL is enough for the coremem value */
3927         WARN_ON((coremem >> PAGE_SHIFT) > ULONG_MAX);
3928
3929         return 0;
3930 }
3931
3932 /*
3933  * kernelcore=size sets the amount of memory for use for allocations that
3934  * cannot be reclaimed or migrated.
3935  */
3936 static int __init cmdline_parse_kernelcore(char *p)
3937 {
3938         return cmdline_parse_core(p, &required_kernelcore);
3939 }
3940
3941 /*
3942  * movablecore=size sets the amount of memory for use for allocations that
3943  * can be reclaimed or migrated.
3944  */
3945 static int __init cmdline_parse_movablecore(char *p)
3946 {
3947         return cmdline_parse_core(p, &required_movablecore);
3948 }
3949
3950 early_param("kernelcore", cmdline_parse_kernelcore);
3951 early_param("movablecore", cmdline_parse_movablecore);
3952
3953 #endif /* CONFIG_ARCH_POPULATES_NODE_MAP */
3954
3955 /**
3956  * set_dma_reserve - set the specified number of pages reserved in the first zone
3957  * @new_dma_reserve: The number of pages to mark reserved
3958  *
3959  * The per-cpu batchsize and zone watermarks are determined by present_pages.
3960  * In the DMA zone, a significant percentage may be consumed by kernel image
3961  * and other unfreeable allocations which can skew the watermarks badly. This
3962  * function may optionally be used to account for unfreeable pages in the
3963  * first zone (e.g., ZONE_DMA). The effect will be lower watermarks and
3964  * smaller per-cpu batchsize.
3965  */
3966 void __init set_dma_reserve(unsigned long new_dma_reserve)
3967 {
3968         dma_reserve = new_dma_reserve;
3969 }
3970
3971 #ifndef CONFIG_NEED_MULTIPLE_NODES
3972 static bootmem_data_t contig_bootmem_data;
3973 struct pglist_data contig_page_data = { .bdata = &contig_bootmem_data };
3974
3975 EXPORT_SYMBOL(contig_page_data);
3976 #endif
3977
3978 void __init free_area_init(unsigned long *zones_size)
3979 {
3980         free_area_init_node(0, NODE_DATA(0), zones_size,
3981                         __pa(PAGE_OFFSET) >> PAGE_SHIFT, NULL);
3982 }
3983
3984 static int page_alloc_cpu_notify(struct notifier_block *self,
3985                                  unsigned long action, void *hcpu)
3986 {
3987         int cpu = (unsigned long)hcpu;
3988
3989         if (action == CPU_DEAD || action == CPU_DEAD_FROZEN) {
3990                 local_irq_disable();
3991                 __drain_pages(cpu);
3992                 vm_events_fold_cpu(cpu);
3993                 local_irq_enable();
3994                 refresh_cpu_vm_stats(cpu);
3995         }
3996         return NOTIFY_OK;
3997 }
3998
3999 void __init page_alloc_init(void)
4000 {
4001         hotcpu_notifier(page_alloc_cpu_notify, 0);
4002 }
4003
4004 /*
4005  * calculate_totalreserve_pages - called when sysctl_lower_zone_reserve_ratio
4006  *      or min_free_kbytes changes.
4007  */
4008 static void calculate_totalreserve_pages(void)
4009 {
4010         struct pglist_data *pgdat;
4011         unsigned long reserve_pages = 0;
4012         enum zone_type i, j;
4013
4014         for_each_online_pgdat(pgdat) {
4015                 for (i = 0; i < MAX_NR_ZONES; i++) {
4016                         struct zone *zone = pgdat->node_zones + i;
4017                         unsigned long max = 0;
4018
4019                         /* Find valid and maximum lowmem_reserve in the zone */
4020                         for (j = i; j < MAX_NR_ZONES; j++) {
4021                                 if (zone->lowmem_reserve[j] > max)
4022                                         max = zone->lowmem_reserve[j];
4023                         }
4024
4025                         /* we treat pages_high as reserved pages. */
4026                         max += zone->pages_high;
4027
4028                         if (max > zone->present_pages)
4029                                 max = zone->present_pages;
4030                         reserve_pages += max;
4031                 }
4032         }
4033         totalreserve_pages = reserve_pages;
4034 }
4035
4036 /*
4037  * setup_per_zone_lowmem_reserve - called whenever
4038  *      sysctl_lower_zone_reserve_ratio changes.  Ensures that each zone
4039  *      has a correct pages reserved value, so an adequate number of
4040  *      pages are left in the zone after a successful __alloc_pages().
4041  */
4042 static void setup_per_zone_lowmem_reserve(void)
4043 {
4044         struct pglist_data *pgdat;
4045         enum zone_type j, idx;
4046
4047         for_each_online_pgdat(pgdat) {
4048                 for (j = 0; j < MAX_NR_ZONES; j++) {
4049                         struct zone *zone = pgdat->node_zones + j;
4050                         unsigned long present_pages = zone->present_pages;
4051
4052                         zone->lowmem_reserve[j] = 0;
4053
4054                         idx = j;
4055                         while (idx) {
4056                                 struct zone *lower_zone;
4057
4058                                 idx--;
4059
4060                                 if (sysctl_lowmem_reserve_ratio[idx] < 1)
4061                                         sysctl_lowmem_reserve_ratio[idx] = 1;
4062
4063                                 lower_zone = pgdat->node_zones + idx;
4064                                 lower_zone->lowmem_reserve[j] = present_pages /
4065                                         sysctl_lowmem_reserve_ratio[idx];
4066                                 present_pages += lower_zone->present_pages;
4067                         }
4068                 }
4069         }
4070
4071         /* update totalreserve_pages */
4072         calculate_totalreserve_pages();
4073 }
4074
4075 /**
4076  * setup_per_zone_pages_min - called when min_free_kbytes changes.
4077  *
4078  * Ensures that the pages_{min,low,high} values for each zone are set correctly
4079  * with respect to min_free_kbytes.
4080  */
4081 void setup_per_zone_pages_min(void)
4082 {
4083         unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
4084         unsigned long lowmem_pages = 0;
4085         struct zone *zone;
4086         unsigned long flags;
4087
4088         /* Calculate total number of !ZONE_HIGHMEM pages */
4089         for_each_zone(zone) {
4090                 if (!is_highmem(zone))
4091                         lowmem_pages += zone->present_pages;
4092         }
4093
4094         for_each_zone(zone) {
4095                 u64 tmp;
4096
4097                 spin_lock_irqsave(&zone->lru_lock, flags);
4098                 tmp = (u64)pages_min * zone->present_pages;
4099                 do_div(tmp, lowmem_pages);
4100                 if (is_highmem(zone)) {
4101                         /*
4102                          * __GFP_HIGH and PF_MEMALLOC allocations usually don't
4103                          * need highmem pages, so cap pages_min to a small
4104                          * value here.
4105                          *
4106                          * The (pages_high-pages_low) and (pages_low-pages_min)
4107                          * deltas controls asynch page reclaim, and so should
4108                          * not be capped for highmem.
4109                          */
4110                         int min_pages;
4111
4112                         min_pages = zone->present_pages / 1024;
4113                         if (min_pages < SWAP_CLUSTER_MAX)
4114                                 min_pages = SWAP_CLUSTER_MAX;
4115                         if (min_pages > 128)
4116                                 min_pages = 128;
4117                         zone->pages_min = min_pages;
4118                 } else {
4119                         /*
4120                          * If it's a lowmem zone, reserve a number of pages
4121                          * proportionate to the zone's size.
4122                          */
4123                         zone->pages_min = tmp;
4124                 }
4125
4126                 zone->pages_low   = zone->pages_min + (tmp >> 2);
4127                 zone->pages_high  = zone->pages_min + (tmp >> 1);
4128                 setup_zone_migrate_reserve(zone);
4129                 spin_unlock_irqrestore(&zone->lru_lock, flags);
4130         }
4131
4132         /* update totalreserve_pages */
4133         calculate_totalreserve_pages();
4134 }
4135
4136 /*
4137  * Initialise min_free_kbytes.
4138  *
4139  * For small machines we want it small (128k min).  For large machines
4140  * we want it large (64MB max).  But it is not linear, because network
4141  * bandwidth does not increase linearly with machine size.  We use
4142  *
4143  *      min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
4144  *      min_free_kbytes = sqrt(lowmem_kbytes * 16)
4145  *
4146  * which yields
4147  *
4148  * 16MB:        512k
4149  * 32MB:        724k
4150  * 64MB:        1024k
4151  * 128MB:       1448k
4152  * 256MB:       2048k
4153  * 512MB:       2896k
4154  * 1024MB:      4096k
4155  * 2048MB:      5792k
4156  * 4096MB:      8192k
4157  * 8192MB:      11584k
4158  * 16384MB:     16384k
4159  */
4160 static int __init init_per_zone_pages_min(void)
4161 {
4162         unsigned long lowmem_kbytes;
4163
4164         lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
4165
4166         min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
4167         if (min_free_kbytes < 128)
4168                 min_free_kbytes = 128;
4169         if (min_free_kbytes > 65536)
4170                 min_free_kbytes = 65536;
4171         setup_per_zone_pages_min();
4172         setup_per_zone_lowmem_reserve();
4173         return 0;
4174 }
4175 module_init(init_per_zone_pages_min)
4176
4177 /*
4178  * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so 
4179  *      that we can call two helper functions whenever min_free_kbytes
4180  *      changes.
4181  */
4182 int min_free_kbytes_sysctl_handler(ctl_table *table, int write, 
4183         struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
4184 {
4185         proc_dointvec(table, write, file, buffer, length, ppos);
4186         if (write)
4187                 setup_per_zone_pages_min();
4188         return 0;
4189 }
4190
4191 #ifdef CONFIG_NUMA
4192 int sysctl_min_unmapped_ratio_sysctl_handler(ctl_table *table, int write,
4193         struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
4194 {
4195         struct zone *zone;
4196         int rc;
4197
4198         rc = proc_dointvec_minmax(table, write, file, buffer, length, ppos);
4199         if (rc)
4200                 return rc;
4201
4202         for_each_zone(zone)
4203                 zone->min_unmapped_pages = (zone->present_pages *
4204                                 sysctl_min_unmapped_ratio) / 100;
4205         return 0;
4206 }
4207
4208 int sysctl_min_slab_ratio_sysctl_handler(ctl_table *table, int write,
4209         struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
4210 {
4211         struct zone *zone;
4212         int rc;
4213
4214         rc = proc_dointvec_minmax(table, write, file, buffer, length, ppos);
4215         if (rc)
4216                 return rc;
4217
4218         for_each_zone(zone)
4219                 zone->min_slab_pages = (zone->present_pages *
4220                                 sysctl_min_slab_ratio) / 100;
4221         return 0;
4222 }
4223 #endif
4224
4225 /*
4226  * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
4227  *      proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
4228  *      whenever sysctl_lowmem_reserve_ratio changes.
4229  *
4230  * The reserve ratio obviously has absolutely no relation with the
4231  * pages_min watermarks. The lowmem reserve ratio can only make sense
4232  * if in function of the boot time zone sizes.
4233  */
4234 int lowmem_reserve_ratio_sysctl_handler(ctl_table *table, int write,
4235         struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
4236 {
4237         proc_dointvec_minmax(table, write, file, buffer, length, ppos);
4238         setup_per_zone_lowmem_reserve();
4239         return 0;
4240 }
4241
4242 /*
4243  * percpu_pagelist_fraction - changes the pcp->high for each zone on each
4244  * cpu.  It is the fraction of total pages in each zone that a hot per cpu pagelist
4245  * can have before it gets flushed back to buddy allocator.
4246  */
4247
4248 int percpu_pagelist_fraction_sysctl_handler(ctl_table *table, int write,
4249         struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
4250 {
4251         struct zone *zone;
4252         unsigned int cpu;
4253         int ret;
4254
4255         ret = proc_dointvec_minmax(table, write, file, buffer, length, ppos);
4256         if (!write || (ret == -EINVAL))
4257                 return ret;
4258         for_each_zone(zone) {
4259                 for_each_online_cpu(cpu) {
4260                         unsigned long  high;
4261                         high = zone->present_pages / percpu_pagelist_fraction;
4262                         setup_pagelist_highmark(zone_pcp(zone, cpu), high);
4263                 }
4264         }
4265         return 0;
4266 }
4267
4268 int hashdist = HASHDIST_DEFAULT;
4269
4270 #ifdef CONFIG_NUMA
4271 static int __init set_hashdist(char *str)
4272 {
4273         if (!str)
4274                 return 0;
4275         hashdist = simple_strtoul(str, &str, 0);
4276         return 1;
4277 }
4278 __setup("hashdist=", set_hashdist);
4279 #endif
4280
4281 /*
4282  * allocate a large system hash table from bootmem
4283  * - it is assumed that the hash table must contain an exact power-of-2
4284  *   quantity of entries
4285  * - limit is the number of hash buckets, not the total allocation size
4286  */
4287 void *__init alloc_large_system_hash(const char *tablename,
4288                                      unsigned long bucketsize,
4289                                      unsigned long numentries,
4290                                      int scale,
4291                                      int flags,
4292                                      unsigned int *_hash_shift,
4293                                      unsigned int *_hash_mask,
4294                                      unsigned long limit)
4295 {
4296         unsigned long long max = limit;
4297         unsigned long log2qty, size;
4298         void *table = NULL;
4299
4300         /* allow the kernel cmdline to have a say */
4301         if (!numentries) {
4302                 /* round applicable memory size up to nearest megabyte */
4303                 numentries = nr_kernel_pages;
4304                 numentries += (1UL << (20 - PAGE_SHIFT)) - 1;
4305                 numentries >>= 20 - PAGE_SHIFT;
4306                 numentries <<= 20 - PAGE_SHIFT;
4307
4308                 /* limit to 1 bucket per 2^scale bytes of low memory */
4309                 if (scale > PAGE_SHIFT)
4310                         numentries >>= (scale - PAGE_SHIFT);
4311                 else
4312                         numentries <<= (PAGE_SHIFT - scale);
4313
4314                 /* Make sure we've got at least a 0-order allocation.. */
4315                 if (unlikely((numentries * bucketsize) < PAGE_SIZE))
4316                         numentries = PAGE_SIZE / bucketsize;
4317         }
4318         numentries = roundup_pow_of_two(numentries);
4319
4320         /* limit allocation size to 1/16 total memory by default */
4321         if (max == 0) {
4322                 max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
4323                 do_div(max, bucketsize);
4324         }
4325
4326         if (numentries > max)
4327                 numentries = max;
4328
4329         log2qty = ilog2(numentries);
4330
4331         do {
4332                 size = bucketsize << log2qty;
4333                 if (flags & HASH_EARLY)
4334                         table = alloc_bootmem(size);
4335                 else if (hashdist)
4336                         table = __vmalloc(size, GFP_ATOMIC, PAGE_KERNEL);
4337                 else {
4338                         unsigned long order;
4339                         for (order = 0; ((1UL << order) << PAGE_SHIFT) < size; order++)
4340                                 ;
4341                         table = (void*) __get_free_pages(GFP_ATOMIC, order);
4342                         /*
4343                          * If bucketsize is not a power-of-two, we may free
4344                          * some pages at the end of hash table.
4345                          */
4346                         if (table) {
4347                                 unsigned long alloc_end = (unsigned long)table +
4348                                                 (PAGE_SIZE << order);
4349                                 unsigned long used = (unsigned long)table +
4350                                                 PAGE_ALIGN(size);
4351                                 split_page(virt_to_page(table), order);
4352                                 while (used < alloc_end) {
4353                                         free_page(used);
4354                                         used += PAGE_SIZE;
4355                                 }
4356                         }
4357                 }
4358         } while (!table && size > PAGE_SIZE && --log2qty);
4359
4360         if (!table)
4361                 panic("Failed to allocate %s hash table\n", tablename);
4362
4363         printk(KERN_INFO "%s hash table entries: %d (order: %d, %lu bytes)\n",
4364                tablename,
4365                (1U << log2qty),
4366                ilog2(size) - PAGE_SHIFT,
4367                size);
4368
4369         if (_hash_shift)
4370                 *_hash_shift = log2qty;
4371         if (_hash_mask)
4372                 *_hash_mask = (1 << log2qty) - 1;
4373
4374         return table;
4375 }
4376
4377 #ifdef CONFIG_OUT_OF_LINE_PFN_TO_PAGE
4378 struct page *pfn_to_page(unsigned long pfn)
4379 {
4380         return __pfn_to_page(pfn);
4381 }
4382 unsigned long page_to_pfn(struct page *page)
4383 {
4384         return __page_to_pfn(page);
4385 }
4386 EXPORT_SYMBOL(pfn_to_page);
4387 EXPORT_SYMBOL(page_to_pfn);
4388 #endif /* CONFIG_OUT_OF_LINE_PFN_TO_PAGE */
4389
4390 /* Return a pointer to the bitmap storing bits affecting a block of pages */
4391 static inline unsigned long *get_pageblock_bitmap(struct zone *zone,
4392                                                         unsigned long pfn)
4393 {
4394 #ifdef CONFIG_SPARSEMEM
4395         return __pfn_to_section(pfn)->pageblock_flags;
4396 #else
4397         return zone->pageblock_flags;
4398 #endif /* CONFIG_SPARSEMEM */
4399 }
4400
4401 static inline int pfn_to_bitidx(struct zone *zone, unsigned long pfn)
4402 {
4403 #ifdef CONFIG_SPARSEMEM
4404         pfn &= (PAGES_PER_SECTION-1);
4405         return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
4406 #else
4407         pfn = pfn - zone->zone_start_pfn;
4408         return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
4409 #endif /* CONFIG_SPARSEMEM */
4410 }
4411
4412 /**
4413  * get_pageblock_flags_group - Return the requested group of flags for the pageblock_nr_pages block of pages
4414  * @page: The page within the block of interest
4415  * @start_bitidx: The first bit of interest to retrieve
4416  * @end_bitidx: The last bit of interest
4417  * returns pageblock_bits flags
4418  */
4419 unsigned long get_pageblock_flags_group(struct page *page,
4420                                         int start_bitidx, int end_bitidx)
4421 {
4422         struct zone *zone;
4423         unsigned long *bitmap;
4424         unsigned long pfn, bitidx;
4425         unsigned long flags = 0;
4426         unsigned long value = 1;
4427
4428         zone = page_zone(page);
4429         pfn = page_to_pfn(page);
4430         bitmap = get_pageblock_bitmap(zone, pfn);
4431         bitidx = pfn_to_bitidx(zone, pfn);
4432
4433         for (; start_bitidx <= end_bitidx; start_bitidx++, value <<= 1)
4434                 if (test_bit(bitidx + start_bitidx, bitmap))
4435                         flags |= value;
4436
4437         return flags;
4438 }
4439
4440 /**
4441  * set_pageblock_flags_group - Set the requested group of flags for a pageblock_nr_pages block of pages
4442  * @page: The page within the block of interest
4443  * @start_bitidx: The first bit of interest
4444  * @end_bitidx: The last bit of interest
4445  * @flags: The flags to set
4446  */
4447 void set_pageblock_flags_group(struct page *page, unsigned long flags,
4448                                         int start_bitidx, int end_bitidx)
4449 {
4450         struct zone *zone;
4451         unsigned long *bitmap;
4452         unsigned long pfn, bitidx;
4453         unsigned long value = 1;
4454
4455         zone = page_zone(page);
4456         pfn = page_to_pfn(page);
4457         bitmap = get_pageblock_bitmap(zone, pfn);
4458         bitidx = pfn_to_bitidx(zone, pfn);
4459
4460         for (; start_bitidx <= end_bitidx; start_bitidx++, value <<= 1)
4461                 if (flags & value)
4462                         __set_bit(bitidx + start_bitidx, bitmap);
4463                 else
4464                         __clear_bit(bitidx + start_bitidx, bitmap);
4465 }