b747cbf8ba1b94003ee96fc9301190af66e6582c
[linux-2.6.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/config.h>
18 #include <linux/stddef.h>
19 #include <linux/mm.h>
20 #include <linux/swap.h>
21 #include <linux/interrupt.h>
22 #include <linux/pagemap.h>
23 #include <linux/bootmem.h>
24 #include <linux/compiler.h>
25 #include <linux/kernel.h>
26 #include <linux/module.h>
27 #include <linux/suspend.h>
28 #include <linux/pagevec.h>
29 #include <linux/blkdev.h>
30 #include <linux/slab.h>
31 #include <linux/notifier.h>
32 #include <linux/topology.h>
33 #include <linux/sysctl.h>
34 #include <linux/cpu.h>
35 #include <linux/cpuset.h>
36 #include <linux/memory_hotplug.h>
37 #include <linux/nodemask.h>
38 #include <linux/vmalloc.h>
39 #include <linux/mempolicy.h>
40 #include <linux/vs_limit.h>
41
42 #include <asm/tlbflush.h>
43 #include <asm/div64.h>
44 #include "internal.h"
45
46 /*
47  * MCD - HACK: Find somewhere to initialize this EARLY, or make this
48  * initializer cleaner
49  */
50 nodemask_t node_online_map __read_mostly = { { [0] = 1UL } };
51 EXPORT_SYMBOL(node_online_map);
52 nodemask_t node_possible_map __read_mostly = NODE_MASK_ALL;
53 EXPORT_SYMBOL(node_possible_map);
54 unsigned long totalram_pages __read_mostly;
55 unsigned long totalhigh_pages __read_mostly;
56 unsigned long totalreserve_pages __read_mostly;
57 long nr_swap_pages;
58 int percpu_pagelist_fraction;
59
60 static void __free_pages_ok(struct page *page, unsigned int order);
61
62 /*
63  * results with 256, 32 in the lowmem_reserve sysctl:
64  *      1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
65  *      1G machine -> (16M dma, 784M normal, 224M high)
66  *      NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
67  *      HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
68  *      HIGHMEM allocation will (224M+784M)/256 of ram reserved in ZONE_DMA
69  *
70  * TBD: should special case ZONE_DMA32 machines here - in those we normally
71  * don't need any ZONE_NORMAL reservation
72  */
73 int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES-1] = { 256, 256, 32 };
74
75 EXPORT_SYMBOL(totalram_pages);
76
77 /*
78  * Used by page_zone() to look up the address of the struct zone whose
79  * id is encoded in the upper bits of page->flags
80  */
81 struct zone *zone_table[1 << ZONETABLE_SHIFT] __read_mostly;
82 EXPORT_SYMBOL(zone_table);
83
84 static char *zone_names[MAX_NR_ZONES] = { "DMA", "DMA32", "Normal", "HighMem" };
85 int min_free_kbytes = 1024;
86
87 unsigned long __initdata nr_kernel_pages;
88 unsigned long __initdata nr_all_pages;
89
90 #ifdef CONFIG_DEBUG_VM
91 static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
92 {
93         int ret = 0;
94         unsigned seq;
95         unsigned long pfn = page_to_pfn(page);
96
97         do {
98                 seq = zone_span_seqbegin(zone);
99                 if (pfn >= zone->zone_start_pfn + zone->spanned_pages)
100                         ret = 1;
101                 else if (pfn < zone->zone_start_pfn)
102                         ret = 1;
103         } while (zone_span_seqretry(zone, seq));
104
105         return ret;
106 }
107
108 static int page_is_consistent(struct zone *zone, struct page *page)
109 {
110 #ifdef CONFIG_HOLES_IN_ZONE
111         if (!pfn_valid(page_to_pfn(page)))
112                 return 0;
113 #endif
114         if (zone != page_zone(page))
115                 return 0;
116
117         return 1;
118 }
119 /*
120  * Temporary debugging check for pages not lying within a given zone.
121  */
122 static int bad_range(struct zone *zone, struct page *page)
123 {
124         if (page_outside_zone_boundaries(zone, page))
125                 return 1;
126         if (!page_is_consistent(zone, page))
127                 return 1;
128
129         return 0;
130 }
131
132 #else
133 static inline int bad_range(struct zone *zone, struct page *page)
134 {
135         return 0;
136 }
137 #endif
138
139 static void bad_page(struct page *page)
140 {
141         printk(KERN_EMERG "Bad page state in process '%s'\n"
142                 KERN_EMERG "page:%p flags:0x%0*lx mapping:%p mapcount:%d count:%d (%s)\n"
143                 KERN_EMERG "Trying to fix it up, but a reboot is needed\n"
144                 KERN_EMERG "Backtrace:\n",
145                 current->comm, page, (int)(2*sizeof(unsigned long)),
146                 (unsigned long)page->flags, page->mapping,
147                 page_mapcount(page), page_count(page), print_tainted());
148         dump_stack();
149         page->flags &= ~(1 << PG_lru    |
150                         1 << PG_private |
151                         1 << PG_locked  |
152                         1 << PG_active  |
153                         1 << PG_dirty   |
154                         1 << PG_reclaim |
155                         1 << PG_slab    |
156                         1 << PG_swapcache |
157                         1 << PG_writeback |
158                         1 << PG_buddy );
159         set_page_count(page, 0);
160         reset_page_mapcount(page);
161         page->mapping = NULL;
162         add_taint(TAINT_BAD_PAGE);
163 }
164
165 /*
166  * Higher-order pages are called "compound pages".  They are structured thusly:
167  *
168  * The first PAGE_SIZE page is called the "head page".
169  *
170  * The remaining PAGE_SIZE pages are called "tail pages".
171  *
172  * All pages have PG_compound set.  All pages have their ->private pointing at
173  * the head page (even the head page has this).
174  *
175  * The first tail page's ->lru.next holds the address of the compound page's
176  * put_page() function.  Its ->lru.prev holds the order of allocation.
177  * This usage means that zero-order pages may not be compound.
178  */
179
180 static void free_compound_page(struct page *page)
181 {
182         __free_pages_ok(page, (unsigned long)page[1].lru.prev);
183 }
184
185 static void prep_compound_page(struct page *page, unsigned long order)
186 {
187         int i;
188         int nr_pages = 1 << order;
189
190         page[1].lru.next = (void *)free_compound_page;  /* set dtor */
191         page[1].lru.prev = (void *)order;
192         for (i = 0; i < nr_pages; i++) {
193                 struct page *p = page + i;
194
195                 __SetPageCompound(p);
196                 set_page_private(p, (unsigned long)page);
197         }
198 }
199
200 static void destroy_compound_page(struct page *page, unsigned long order)
201 {
202         int i;
203         int nr_pages = 1 << order;
204
205         if (unlikely((unsigned long)page[1].lru.prev != order))
206                 bad_page(page);
207
208         for (i = 0; i < nr_pages; i++) {
209                 struct page *p = page + i;
210
211                 if (unlikely(!PageCompound(p) |
212                                 (page_private(p) != (unsigned long)page)))
213                         bad_page(page);
214                 __ClearPageCompound(p);
215         }
216 }
217
218 static inline void prep_zero_page(struct page *page, int order, gfp_t gfp_flags)
219 {
220         int i;
221
222         BUG_ON((gfp_flags & (__GFP_WAIT | __GFP_HIGHMEM)) == __GFP_HIGHMEM);
223         /*
224          * clear_highpage() will use KM_USER0, so it's a bug to use __GFP_ZERO
225          * and __GFP_HIGHMEM from hard or soft interrupt context.
226          */
227         BUG_ON((gfp_flags & __GFP_HIGHMEM) && in_interrupt());
228         for (i = 0; i < (1 << order); i++)
229                 clear_highpage(page + i);
230 }
231
232 /*
233  * function for dealing with page's order in buddy system.
234  * zone->lock is already acquired when we use these.
235  * So, we don't need atomic page->flags operations here.
236  */
237 static inline unsigned long page_order(struct page *page)
238 {
239         return page_private(page);
240 }
241
242 static inline void set_page_order(struct page *page, int order)
243 {
244         set_page_private(page, order);
245         __SetPageBuddy(page);
246 }
247
248 static inline void rmv_page_order(struct page *page)
249 {
250         __ClearPageBuddy(page);
251         set_page_private(page, 0);
252 }
253
254 /*
255  * Locate the struct page for both the matching buddy in our
256  * pair (buddy1) and the combined O(n+1) page they form (page).
257  *
258  * 1) Any buddy B1 will have an order O twin B2 which satisfies
259  * the following equation:
260  *     B2 = B1 ^ (1 << O)
261  * For example, if the starting buddy (buddy2) is #8 its order
262  * 1 buddy is #10:
263  *     B2 = 8 ^ (1 << 1) = 8 ^ 2 = 10
264  *
265  * 2) Any buddy B will have an order O+1 parent P which
266  * satisfies the following equation:
267  *     P = B & ~(1 << O)
268  *
269  * Assumption: *_mem_map is contigious at least up to MAX_ORDER
270  */
271 static inline struct page *
272 __page_find_buddy(struct page *page, unsigned long page_idx, unsigned int order)
273 {
274         unsigned long buddy_idx = page_idx ^ (1 << order);
275
276         return page + (buddy_idx - page_idx);
277 }
278
279 static inline unsigned long
280 __find_combined_index(unsigned long page_idx, unsigned int order)
281 {
282         return (page_idx & ~(1 << order));
283 }
284
285 /*
286  * This function checks whether a page is free && is the buddy
287  * we can do coalesce a page and its buddy if
288  * (a) the buddy is not in a hole &&
289  * (b) the buddy is in the buddy system &&
290  * (c) a page and its buddy have the same order.
291  *
292  * For recording whether a page is in the buddy system, we use PG_buddy.
293  * Setting, clearing, and testing PG_buddy is serialized by zone->lock.
294  *
295  * For recording page's order, we use page_private(page).
296  */
297 static inline int page_is_buddy(struct page *page, int order)
298 {
299 #ifdef CONFIG_HOLES_IN_ZONE
300         if (!pfn_valid(page_to_pfn(page)))
301                 return 0;
302 #endif
303
304         if (PageBuddy(page) && page_order(page) == order) {
305                 BUG_ON(page_count(page) != 0);
306                 return 1;
307         }
308         return 0;
309 }
310
311 /*
312  * Freeing function for a buddy system allocator.
313  *
314  * The concept of a buddy system is to maintain direct-mapped table
315  * (containing bit values) for memory blocks of various "orders".
316  * The bottom level table contains the map for the smallest allocatable
317  * units of memory (here, pages), and each level above it describes
318  * pairs of units from the levels below, hence, "buddies".
319  * At a high level, all that happens here is marking the table entry
320  * at the bottom level available, and propagating the changes upward
321  * as necessary, plus some accounting needed to play nicely with other
322  * parts of the VM system.
323  * At each level, we keep a list of pages, which are heads of continuous
324  * free pages of length of (1 << order) and marked with PG_buddy. Page's
325  * order is recorded in page_private(page) field.
326  * So when we are allocating or freeing one, we can derive the state of the
327  * other.  That is, if we allocate a small block, and both were   
328  * free, the remainder of the region must be split into blocks.   
329  * If a block is freed, and its buddy is also free, then this
330  * triggers coalescing into a block of larger size.            
331  *
332  * -- wli
333  */
334
335 static inline void __free_one_page(struct page *page,
336                 struct zone *zone, unsigned int order)
337 {
338         unsigned long page_idx;
339         int order_size = 1 << order;
340
341         if (unlikely(PageCompound(page)))
342                 destroy_compound_page(page, order);
343
344         page_idx = page_to_pfn(page) & ((1 << MAX_ORDER) - 1);
345
346         BUG_ON(page_idx & (order_size - 1));
347         BUG_ON(bad_range(zone, page));
348
349         zone->free_pages += order_size;
350         while (order < MAX_ORDER-1) {
351                 unsigned long combined_idx;
352                 struct free_area *area;
353                 struct page *buddy;
354
355                 buddy = __page_find_buddy(page, page_idx, order);
356                 if (!page_is_buddy(buddy, order))
357                         break;          /* Move the buddy up one level. */
358
359                 list_del(&buddy->lru);
360                 area = zone->free_area + order;
361                 area->nr_free--;
362                 rmv_page_order(buddy);
363                 combined_idx = __find_combined_index(page_idx, order);
364                 page = page + (combined_idx - page_idx);
365                 page_idx = combined_idx;
366                 order++;
367         }
368         set_page_order(page, order);
369         list_add(&page->lru, &zone->free_area[order].free_list);
370         zone->free_area[order].nr_free++;
371 }
372
373 static inline int free_pages_check(struct page *page)
374 {
375         if (unlikely(page_mapcount(page) |
376                 (page->mapping != NULL)  |
377                 (page_count(page) != 0)  |
378                 (page->flags & (
379                         1 << PG_lru     |
380                         1 << PG_private |
381                         1 << PG_locked  |
382                         1 << PG_active  |
383                         1 << PG_reclaim |
384                         1 << PG_slab    |
385                         1 << PG_swapcache |
386                         1 << PG_writeback |
387                         1 << PG_reserved |
388                         1 << PG_buddy ))))
389                 bad_page(page);
390         if (PageDirty(page))
391                 __ClearPageDirty(page);
392         /*
393          * For now, we report if PG_reserved was found set, but do not
394          * clear it, and do not free the page.  But we shall soon need
395          * to do more, for when the ZERO_PAGE count wraps negative.
396          */
397         return PageReserved(page);
398 }
399
400 /*
401  * Frees a list of pages. 
402  * Assumes all pages on list are in same zone, and of same order.
403  * count is the number of pages to free.
404  *
405  * If the zone was previously in an "all pages pinned" state then look to
406  * see if this freeing clears that state.
407  *
408  * And clear the zone's pages_scanned counter, to hold off the "all pages are
409  * pinned" detection logic.
410  */
411 static void free_pages_bulk(struct zone *zone, int count,
412                                         struct list_head *list, int order)
413 {
414         spin_lock(&zone->lock);
415         zone->all_unreclaimable = 0;
416         zone->pages_scanned = 0;
417         while (count--) {
418                 struct page *page;
419
420                 BUG_ON(list_empty(list));
421                 page = list_entry(list->prev, struct page, lru);
422                 /* have to delete it as __free_one_page list manipulates */
423                 list_del(&page->lru);
424                 __free_one_page(page, zone, order);
425         }
426         spin_unlock(&zone->lock);
427 }
428
429 static void free_one_page(struct zone *zone, struct page *page, int order)
430 {
431         LIST_HEAD(list);
432         list_add(&page->lru, &list);
433         free_pages_bulk(zone, 1, &list, order);
434 }
435
436 static void __free_pages_ok(struct page *page, unsigned int order)
437 {
438         unsigned long flags;
439         int i;
440         int reserved = 0;
441
442         arch_free_page(page, order);
443         if (!PageHighMem(page))
444                 mutex_debug_check_no_locks_freed(page_address(page),
445                                                  PAGE_SIZE<<order);
446
447         for (i = 0 ; i < (1 << order) ; ++i)
448                 reserved += free_pages_check(page + i);
449         if (reserved)
450                 return;
451
452         kernel_map_pages(page, 1 << order, 0);
453         local_irq_save(flags);
454         __mod_page_state(pgfree, 1 << order);
455         free_one_page(page_zone(page), page, order);
456         local_irq_restore(flags);
457 }
458
459 /*
460  * permit the bootmem allocator to evade page validation on high-order frees
461  */
462 void fastcall __init __free_pages_bootmem(struct page *page, unsigned int order)
463 {
464         if (order == 0) {
465                 __ClearPageReserved(page);
466                 set_page_count(page, 0);
467                 set_page_refcounted(page);
468                 __free_page(page);
469         } else {
470                 int loop;
471
472                 prefetchw(page);
473                 for (loop = 0; loop < BITS_PER_LONG; loop++) {
474                         struct page *p = &page[loop];
475
476                         if (loop + 1 < BITS_PER_LONG)
477                                 prefetchw(p + 1);
478                         __ClearPageReserved(p);
479                         set_page_count(p, 0);
480                 }
481
482                 set_page_refcounted(page);
483                 __free_pages(page, order);
484         }
485 }
486
487
488 /*
489  * The order of subdivision here is critical for the IO subsystem.
490  * Please do not alter this order without good reasons and regression
491  * testing. Specifically, as large blocks of memory are subdivided,
492  * the order in which smaller blocks are delivered depends on the order
493  * they're subdivided in this function. This is the primary factor
494  * influencing the order in which pages are delivered to the IO
495  * subsystem according to empirical testing, and this is also justified
496  * by considering the behavior of a buddy system containing a single
497  * large block of memory acted on by a series of small allocations.
498  * This behavior is a critical factor in sglist merging's success.
499  *
500  * -- wli
501  */
502 static inline void expand(struct zone *zone, struct page *page,
503         int low, int high, struct free_area *area)
504 {
505         unsigned long size = 1 << high;
506
507         while (high > low) {
508                 area--;
509                 high--;
510                 size >>= 1;
511                 BUG_ON(bad_range(zone, &page[size]));
512                 list_add(&page[size].lru, &area->free_list);
513                 area->nr_free++;
514                 set_page_order(&page[size], high);
515         }
516 }
517
518 /*
519  * This page is about to be returned from the page allocator
520  */
521 static int prep_new_page(struct page *page, int order, gfp_t gfp_flags)
522 {
523         if (unlikely(page_mapcount(page) |
524                 (page->mapping != NULL)  |
525                 (page_count(page) != 0)  |
526                 (page->flags & (
527                         1 << PG_lru     |
528                         1 << PG_private |
529                         1 << PG_locked  |
530                         1 << PG_active  |
531                         1 << PG_dirty   |
532                         1 << PG_reclaim |
533                         1 << PG_slab    |
534                         1 << PG_swapcache |
535                         1 << PG_writeback |
536                         1 << PG_reserved |
537                         1 << PG_buddy ))))
538                 bad_page(page);
539
540         /*
541          * For now, we report if PG_reserved was found set, but do not
542          * clear it, and do not allocate the page: as a safety net.
543          */
544         if (PageReserved(page))
545                 return 1;
546
547         page->flags &= ~(1 << PG_uptodate | 1 << PG_error |
548                         1 << PG_referenced | 1 << PG_arch_1 |
549                         1 << PG_checked | 1 << PG_mappedtodisk);
550         set_page_private(page, 0);
551         set_page_refcounted(page);
552         kernel_map_pages(page, 1 << order, 1);
553
554         if (gfp_flags & __GFP_ZERO)
555                 prep_zero_page(page, order, gfp_flags);
556
557         if (order && (gfp_flags & __GFP_COMP))
558                 prep_compound_page(page, order);
559
560         return 0;
561 }
562
563 /* 
564  * Do the hard work of removing an element from the buddy allocator.
565  * Call me with the zone->lock already held.
566  */
567 static struct page *__rmqueue(struct zone *zone, unsigned int order)
568 {
569         struct free_area * area;
570         unsigned int current_order;
571         struct page *page;
572
573         for (current_order = order; current_order < MAX_ORDER; ++current_order) {
574                 area = zone->free_area + current_order;
575                 if (list_empty(&area->free_list))
576                         continue;
577
578                 page = list_entry(area->free_list.next, struct page, lru);
579                 list_del(&page->lru);
580                 rmv_page_order(page);
581                 area->nr_free--;
582                 zone->free_pages -= 1UL << order;
583                 expand(zone, page, order, current_order, area);
584                 return page;
585         }
586
587         return NULL;
588 }
589
590 /* 
591  * Obtain a specified number of elements from the buddy allocator, all under
592  * a single hold of the lock, for efficiency.  Add them to the supplied list.
593  * Returns the number of new pages which were placed at *list.
594  */
595 static int rmqueue_bulk(struct zone *zone, unsigned int order, 
596                         unsigned long count, struct list_head *list)
597 {
598         int i;
599         
600         spin_lock(&zone->lock);
601         for (i = 0; i < count; ++i) {
602                 struct page *page = __rmqueue(zone, order);
603                 if (unlikely(page == NULL))
604                         break;
605                 list_add_tail(&page->lru, list);
606         }
607         spin_unlock(&zone->lock);
608         return i;
609 }
610
611 #ifdef CONFIG_NUMA
612 /*
613  * Called from the slab reaper to drain pagesets on a particular node that
614  * belong to the currently executing processor.
615  * Note that this function must be called with the thread pinned to
616  * a single processor.
617  */
618 void drain_node_pages(int nodeid)
619 {
620         int i, z;
621         unsigned long flags;
622
623         for (z = 0; z < MAX_NR_ZONES; z++) {
624                 struct zone *zone = NODE_DATA(nodeid)->node_zones + z;
625                 struct per_cpu_pageset *pset;
626
627                 pset = zone_pcp(zone, smp_processor_id());
628                 for (i = 0; i < ARRAY_SIZE(pset->pcp); i++) {
629                         struct per_cpu_pages *pcp;
630
631                         pcp = &pset->pcp[i];
632                         if (pcp->count) {
633                                 local_irq_save(flags);
634                                 free_pages_bulk(zone, pcp->count, &pcp->list, 0);
635                                 pcp->count = 0;
636                                 local_irq_restore(flags);
637                         }
638                 }
639         }
640 }
641 #endif
642
643 #if defined(CONFIG_PM) || defined(CONFIG_HOTPLUG_CPU)
644 static void __drain_pages(unsigned int cpu)
645 {
646         unsigned long flags;
647         struct zone *zone;
648         int i;
649
650         for_each_zone(zone) {
651                 struct per_cpu_pageset *pset;
652
653                 pset = zone_pcp(zone, cpu);
654                 for (i = 0; i < ARRAY_SIZE(pset->pcp); i++) {
655                         struct per_cpu_pages *pcp;
656
657                         pcp = &pset->pcp[i];
658                         local_irq_save(flags);
659                         free_pages_bulk(zone, pcp->count, &pcp->list, 0);
660                         pcp->count = 0;
661                         local_irq_restore(flags);
662                 }
663         }
664 }
665 #endif /* CONFIG_PM || CONFIG_HOTPLUG_CPU */
666
667 #ifdef CONFIG_PM
668
669 void mark_free_pages(struct zone *zone)
670 {
671         unsigned long zone_pfn, flags;
672         int order;
673         struct list_head *curr;
674
675         if (!zone->spanned_pages)
676                 return;
677
678         spin_lock_irqsave(&zone->lock, flags);
679         for (zone_pfn = 0; zone_pfn < zone->spanned_pages; ++zone_pfn)
680                 ClearPageNosaveFree(pfn_to_page(zone_pfn + zone->zone_start_pfn));
681
682         for (order = MAX_ORDER - 1; order >= 0; --order)
683                 list_for_each(curr, &zone->free_area[order].free_list) {
684                         unsigned long start_pfn, i;
685
686                         start_pfn = page_to_pfn(list_entry(curr, struct page, lru));
687
688                         for (i=0; i < (1<<order); i++)
689                                 SetPageNosaveFree(pfn_to_page(start_pfn+i));
690         }
691         spin_unlock_irqrestore(&zone->lock, flags);
692 }
693
694 /*
695  * Spill all of this CPU's per-cpu pages back into the buddy allocator.
696  */
697 void drain_local_pages(void)
698 {
699         unsigned long flags;
700
701         local_irq_save(flags);  
702         __drain_pages(smp_processor_id());
703         local_irq_restore(flags);       
704 }
705 #endif /* CONFIG_PM */
706
707 static void zone_statistics(struct zonelist *zonelist, struct zone *z, int cpu)
708 {
709 #ifdef CONFIG_NUMA
710         pg_data_t *pg = z->zone_pgdat;
711         pg_data_t *orig = zonelist->zones[0]->zone_pgdat;
712         struct per_cpu_pageset *p;
713
714         p = zone_pcp(z, cpu);
715         if (pg == orig) {
716                 p->numa_hit++;
717         } else {
718                 p->numa_miss++;
719                 zone_pcp(zonelist->zones[0], cpu)->numa_foreign++;
720         }
721         if (pg == NODE_DATA(numa_node_id()))
722                 p->local_node++;
723         else
724                 p->other_node++;
725 #endif
726 }
727
728 /*
729  * Free a 0-order page
730  */
731 static void fastcall free_hot_cold_page(struct page *page, int cold)
732 {
733         struct zone *zone = page_zone(page);
734         struct per_cpu_pages *pcp;
735         unsigned long flags;
736
737         arch_free_page(page, 0);
738
739         if (PageAnon(page))
740                 page->mapping = NULL;
741         if (free_pages_check(page))
742                 return;
743
744         kernel_map_pages(page, 1, 0);
745
746         pcp = &zone_pcp(zone, get_cpu())->pcp[cold];
747         local_irq_save(flags);
748         __inc_page_state(pgfree);
749         list_add(&page->lru, &pcp->list);
750         pcp->count++;
751         if (pcp->count >= pcp->high) {
752                 free_pages_bulk(zone, pcp->batch, &pcp->list, 0);
753                 pcp->count -= pcp->batch;
754         } else if (zone->all_unreclaimable) {
755                 spin_lock(&zone->lock);
756                 zone->all_unreclaimable = 0;
757                 zone->pages_scanned = 0;
758                 spin_unlock(&zone->lock);
759         }
760         local_irq_restore(flags);
761         put_cpu();
762 }
763
764 void fastcall free_hot_page(struct page *page)
765 {
766         free_hot_cold_page(page, 0);
767 }
768         
769 void fastcall free_cold_page(struct page *page)
770 {
771         free_hot_cold_page(page, 1);
772 }
773
774 /*
775  * split_page takes a non-compound higher-order page, and splits it into
776  * n (1<<order) sub-pages: page[0..n]
777  * Each sub-page must be freed individually.
778  *
779  * Note: this is probably too low level an operation for use in drivers.
780  * Please consult with lkml before using this in your driver.
781  */
782 void split_page(struct page *page, unsigned int order)
783 {
784         int i;
785
786         BUG_ON(PageCompound(page));
787         BUG_ON(!page_count(page));
788         for (i = 1; i < (1 << order); i++)
789                 set_page_refcounted(page + i);
790 }
791
792 /*
793  * Really, prep_compound_page() should be called from __rmqueue_bulk().  But
794  * we cheat by calling it from here, in the order > 0 path.  Saves a branch
795  * or two.
796  */
797 static struct page *buffered_rmqueue(struct zonelist *zonelist,
798                         struct zone *zone, int order, gfp_t gfp_flags)
799 {
800         unsigned long flags;
801         struct page *page;
802         int cold = !!(gfp_flags & __GFP_COLD);
803         int cpu;
804
805 again:
806         cpu  = get_cpu();
807         if (likely(order == 0)) {
808                 struct per_cpu_pages *pcp;
809
810                 pcp = &zone_pcp(zone, cpu)->pcp[cold];
811                 local_irq_save(flags);
812                 if (!pcp->count) {
813                         pcp->count += rmqueue_bulk(zone, 0,
814                                                 pcp->batch, &pcp->list);
815                         if (unlikely(!pcp->count))
816                                 goto failed;
817                 }
818                 page = list_entry(pcp->list.next, struct page, lru);
819                 list_del(&page->lru);
820                 pcp->count--;
821         } else {
822                 spin_lock_irqsave(&zone->lock, flags);
823                 page = __rmqueue(zone, order);
824                 spin_unlock(&zone->lock);
825                 if (!page)
826                         goto failed;
827         }
828
829         __mod_page_state_zone(zone, pgalloc, 1 << order);
830         zone_statistics(zonelist, zone, cpu);
831         local_irq_restore(flags);
832         put_cpu();
833
834         BUG_ON(bad_range(zone, page));
835         if (prep_new_page(page, order, gfp_flags))
836                 goto again;
837         return page;
838
839 failed:
840         local_irq_restore(flags);
841         put_cpu();
842         return NULL;
843 }
844
845 #define ALLOC_NO_WATERMARKS     0x01 /* don't check watermarks at all */
846 #define ALLOC_WMARK_MIN         0x02 /* use pages_min watermark */
847 #define ALLOC_WMARK_LOW         0x04 /* use pages_low watermark */
848 #define ALLOC_WMARK_HIGH        0x08 /* use pages_high watermark */
849 #define ALLOC_HARDER            0x10 /* try to alloc harder */
850 #define ALLOC_HIGH              0x20 /* __GFP_HIGH set */
851 #define ALLOC_CPUSET            0x40 /* check for correct cpuset */
852
853 /*
854  * Return 1 if free pages are above 'mark'. This takes into account the order
855  * of the allocation.
856  */
857 int zone_watermark_ok(struct zone *z, int order, unsigned long mark,
858                       int classzone_idx, int alloc_flags)
859 {
860         /* free_pages my go negative - that's OK */
861         long min = mark, free_pages = z->free_pages - (1 << order) + 1;
862         int o;
863
864         if (alloc_flags & ALLOC_HIGH)
865                 min -= min / 2;
866         if (alloc_flags & ALLOC_HARDER)
867                 min -= min / 4;
868
869         if (free_pages <= min + z->lowmem_reserve[classzone_idx])
870                 return 0;
871         for (o = 0; o < order; o++) {
872                 /* At the next order, this order's pages become unavailable */
873                 free_pages -= z->free_area[o].nr_free << o;
874
875                 /* Require fewer higher order pages to be free */
876                 min >>= 1;
877
878                 if (free_pages <= min)
879                         return 0;
880         }
881         return 1;
882 }
883
884 /*
885  * get_page_from_freeliest goes through the zonelist trying to allocate
886  * a page.
887  */
888 static struct page *
889 get_page_from_freelist(gfp_t gfp_mask, unsigned int order,
890                 struct zonelist *zonelist, int alloc_flags)
891 {
892         struct zone **z = zonelist->zones;
893         struct page *page = NULL;
894         int classzone_idx = zone_idx(*z);
895
896         /*
897          * Go through the zonelist once, looking for a zone with enough free.
898          * See also cpuset_zone_allowed() comment in kernel/cpuset.c.
899          */
900         do {
901                 if ((alloc_flags & ALLOC_CPUSET) &&
902                                 !cpuset_zone_allowed(*z, gfp_mask))
903                         continue;
904
905                 if (!(alloc_flags & ALLOC_NO_WATERMARKS)) {
906                         unsigned long mark;
907                         if (alloc_flags & ALLOC_WMARK_MIN)
908                                 mark = (*z)->pages_min;
909                         else if (alloc_flags & ALLOC_WMARK_LOW)
910                                 mark = (*z)->pages_low;
911                         else
912                                 mark = (*z)->pages_high;
913                         if (!zone_watermark_ok(*z, order, mark,
914                                     classzone_idx, alloc_flags))
915                                 if (!zone_reclaim_mode ||
916                                     !zone_reclaim(*z, gfp_mask, order))
917                                         continue;
918                 }
919
920                 page = buffered_rmqueue(zonelist, *z, order, gfp_mask);
921                 if (page) {
922                         break;
923                 }
924         } while (*(++z) != NULL);
925         return page;
926 }
927
928 /*
929  * This is the 'heart' of the zoned buddy allocator.
930  */
931 struct page * fastcall
932 __alloc_pages(gfp_t gfp_mask, unsigned int order,
933                 struct zonelist *zonelist)
934 {
935         const gfp_t wait = gfp_mask & __GFP_WAIT;
936         struct zone **z;
937         struct page *page;
938         struct reclaim_state reclaim_state;
939         struct task_struct *p = current;
940         int do_retry;
941         int alloc_flags;
942         int did_some_progress;
943
944         might_sleep_if(wait);
945
946 restart:
947         z = zonelist->zones;  /* the list of zones suitable for gfp_mask */
948
949         if (unlikely(*z == NULL)) {
950                 /* Should this ever happen?? */
951                 return NULL;
952         }
953
954         page = get_page_from_freelist(gfp_mask|__GFP_HARDWALL, order,
955                                 zonelist, ALLOC_WMARK_LOW|ALLOC_CPUSET);
956         if (page)
957                 goto got_pg;
958
959         do {
960                 if (cpuset_zone_allowed(*z, gfp_mask|__GFP_HARDWALL))
961                         wakeup_kswapd(*z, order);
962         } while (*(++z));
963
964         /*
965          * OK, we're below the kswapd watermark and have kicked background
966          * reclaim. Now things get more complex, so set up alloc_flags according
967          * to how we want to proceed.
968          *
969          * The caller may dip into page reserves a bit more if the caller
970          * cannot run direct reclaim, or if the caller has realtime scheduling
971          * policy or is asking for __GFP_HIGH memory.  GFP_ATOMIC requests will
972          * set both ALLOC_HARDER (!wait) and ALLOC_HIGH (__GFP_HIGH).
973          */
974         alloc_flags = ALLOC_WMARK_MIN;
975         if ((unlikely(rt_task(p)) && !in_interrupt()) || !wait)
976                 alloc_flags |= ALLOC_HARDER;
977         if (gfp_mask & __GFP_HIGH)
978                 alloc_flags |= ALLOC_HIGH;
979         if (wait)
980                 alloc_flags |= ALLOC_CPUSET;
981
982         /*
983          * Go through the zonelist again. Let __GFP_HIGH and allocations
984          * coming from realtime tasks go deeper into reserves.
985          *
986          * This is the last chance, in general, before the goto nopage.
987          * Ignore cpuset if GFP_ATOMIC (!wait) rather than fail alloc.
988          * See also cpuset_zone_allowed() comment in kernel/cpuset.c.
989          */
990         page = get_page_from_freelist(gfp_mask, order, zonelist, alloc_flags);
991         if (page)
992                 goto got_pg;
993
994         /* This allocation should allow future memory freeing. */
995
996         if (((p->flags & PF_MEMALLOC) || unlikely(test_thread_flag(TIF_MEMDIE)))
997                         && !in_interrupt()) {
998                 if (!(gfp_mask & __GFP_NOMEMALLOC)) {
999 nofail_alloc:
1000                         /* go through the zonelist yet again, ignoring mins */
1001                         page = get_page_from_freelist(gfp_mask, order,
1002                                 zonelist, ALLOC_NO_WATERMARKS);
1003                         if (page)
1004                                 goto got_pg;
1005                         if (gfp_mask & __GFP_NOFAIL) {
1006                                 blk_congestion_wait(WRITE, HZ/50);
1007                                 goto nofail_alloc;
1008                         }
1009                 }
1010                 goto nopage;
1011         }
1012
1013         /* Atomic allocations - we can't balance anything */
1014         if (!wait)
1015                 goto nopage;
1016
1017 rebalance:
1018         cond_resched();
1019
1020         /* We now go into synchronous reclaim */
1021         cpuset_memory_pressure_bump();
1022         p->flags |= PF_MEMALLOC;
1023         reclaim_state.reclaimed_slab = 0;
1024         p->reclaim_state = &reclaim_state;
1025
1026         did_some_progress = try_to_free_pages(zonelist->zones, gfp_mask);
1027
1028         p->reclaim_state = NULL;
1029         p->flags &= ~PF_MEMALLOC;
1030
1031         cond_resched();
1032
1033         if (likely(did_some_progress)) {
1034                 page = get_page_from_freelist(gfp_mask, order,
1035                                                 zonelist, alloc_flags);
1036                 if (page)
1037                         goto got_pg;
1038         } else if ((gfp_mask & __GFP_FS) && !(gfp_mask & __GFP_NORETRY)) {
1039                 /*
1040                  * Go through the zonelist yet one more time, keep
1041                  * very high watermark here, this is only to catch
1042                  * a parallel oom killing, we must fail if we're still
1043                  * under heavy pressure.
1044                  */
1045                 page = get_page_from_freelist(gfp_mask|__GFP_HARDWALL, order,
1046                                 zonelist, ALLOC_WMARK_HIGH|ALLOC_CPUSET);
1047                 if (page)
1048                         goto got_pg;
1049
1050                 out_of_memory(zonelist, gfp_mask, order);
1051                 goto restart;
1052         }
1053
1054         /*
1055          * Don't let big-order allocations loop unless the caller explicitly
1056          * requests that.  Wait for some write requests to complete then retry.
1057          *
1058          * In this implementation, __GFP_REPEAT means __GFP_NOFAIL for order
1059          * <= 3, but that may not be true in other implementations.
1060          */
1061         do_retry = 0;
1062         if (!(gfp_mask & __GFP_NORETRY)) {
1063                 if ((order <= 3) || (gfp_mask & __GFP_REPEAT))
1064                         do_retry = 1;
1065                 if (gfp_mask & __GFP_NOFAIL)
1066                         do_retry = 1;
1067         }
1068         if (do_retry) {
1069                 blk_congestion_wait(WRITE, HZ/50);
1070                 goto rebalance;
1071         }
1072
1073 nopage:
1074         if (!(gfp_mask & __GFP_NOWARN) && printk_ratelimit()) {
1075                 printk(KERN_WARNING "%s: page allocation failure."
1076                         " order:%d, mode:0x%x\n",
1077                         p->comm, order, gfp_mask);
1078                 dump_stack();
1079                 show_mem();
1080         }
1081 got_pg:
1082         return page;
1083 }
1084
1085 EXPORT_SYMBOL(__alloc_pages);
1086
1087 /*
1088  * Common helper functions.
1089  */
1090 fastcall unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order)
1091 {
1092         struct page * page;
1093         page = alloc_pages(gfp_mask, order);
1094         if (!page)
1095                 return 0;
1096         return (unsigned long) page_address(page);
1097 }
1098
1099 EXPORT_SYMBOL(__get_free_pages);
1100
1101 fastcall unsigned long get_zeroed_page(gfp_t gfp_mask)
1102 {
1103         struct page * page;
1104
1105         /*
1106          * get_zeroed_page() returns a 32-bit address, which cannot represent
1107          * a highmem page
1108          */
1109         BUG_ON((gfp_mask & __GFP_HIGHMEM) != 0);
1110
1111         page = alloc_pages(gfp_mask | __GFP_ZERO, 0);
1112         if (page)
1113                 return (unsigned long) page_address(page);
1114         return 0;
1115 }
1116
1117 EXPORT_SYMBOL(get_zeroed_page);
1118
1119 void __pagevec_free(struct pagevec *pvec)
1120 {
1121         int i = pagevec_count(pvec);
1122
1123         while (--i >= 0)
1124                 free_hot_cold_page(pvec->pages[i], pvec->cold);
1125 }
1126
1127 fastcall void __free_pages(struct page *page, unsigned int order)
1128 {
1129         if (put_page_testzero(page)) {
1130                 if (order == 0)
1131                         free_hot_page(page);
1132                 else
1133                         __free_pages_ok(page, order);
1134         }
1135 }
1136
1137 EXPORT_SYMBOL(__free_pages);
1138
1139 fastcall void free_pages(unsigned long addr, unsigned int order)
1140 {
1141         if (addr != 0) {
1142                 BUG_ON(!virt_addr_valid((void *)addr));
1143                 __free_pages(virt_to_page((void *)addr), order);
1144         }
1145 }
1146
1147 EXPORT_SYMBOL(free_pages);
1148
1149 /*
1150  * Total amount of free (allocatable) RAM:
1151  */
1152 unsigned int nr_free_pages(void)
1153 {
1154         unsigned int sum = 0;
1155         struct zone *zone;
1156
1157         for_each_zone(zone)
1158                 sum += zone->free_pages;
1159
1160         return sum;
1161 }
1162
1163 EXPORT_SYMBOL(nr_free_pages);
1164
1165 #ifdef CONFIG_NUMA
1166 unsigned int nr_free_pages_pgdat(pg_data_t *pgdat)
1167 {
1168         unsigned int i, sum = 0;
1169
1170         for (i = 0; i < MAX_NR_ZONES; i++)
1171                 sum += pgdat->node_zones[i].free_pages;
1172
1173         return sum;
1174 }
1175 #endif
1176
1177 static unsigned int nr_free_zone_pages(int offset)
1178 {
1179         /* Just pick one node, since fallback list is circular */
1180         pg_data_t *pgdat = NODE_DATA(numa_node_id());
1181         unsigned int sum = 0;
1182
1183         struct zonelist *zonelist = pgdat->node_zonelists + offset;
1184         struct zone **zonep = zonelist->zones;
1185         struct zone *zone;
1186
1187         for (zone = *zonep++; zone; zone = *zonep++) {
1188                 unsigned long size = zone->present_pages;
1189                 unsigned long high = zone->pages_high;
1190                 if (size > high)
1191                         sum += size - high;
1192         }
1193
1194         return sum;
1195 }
1196
1197 /*
1198  * Amount of free RAM allocatable within ZONE_DMA and ZONE_NORMAL
1199  */
1200 unsigned int nr_free_buffer_pages(void)
1201 {
1202         return nr_free_zone_pages(gfp_zone(GFP_USER));
1203 }
1204
1205 /*
1206  * Amount of free RAM allocatable within all zones
1207  */
1208 unsigned int nr_free_pagecache_pages(void)
1209 {
1210         return nr_free_zone_pages(gfp_zone(GFP_HIGHUSER));
1211 }
1212
1213 #ifdef CONFIG_HIGHMEM
1214 unsigned int nr_free_highpages (void)
1215 {
1216         pg_data_t *pgdat;
1217         unsigned int pages = 0;
1218
1219         for_each_online_pgdat(pgdat)
1220                 pages += pgdat->node_zones[ZONE_HIGHMEM].free_pages;
1221
1222         return pages;
1223 }
1224 #endif
1225
1226 #ifdef CONFIG_NUMA
1227 static void show_node(struct zone *zone)
1228 {
1229         printk("Node %d ", zone->zone_pgdat->node_id);
1230 }
1231 #else
1232 #define show_node(zone) do { } while (0)
1233 #endif
1234
1235 /*
1236  * Accumulate the page_state information across all CPUs.
1237  * The result is unavoidably approximate - it can change
1238  * during and after execution of this function.
1239  */
1240 static DEFINE_PER_CPU(struct page_state, page_states) = {0};
1241
1242 atomic_t nr_pagecache = ATOMIC_INIT(0);
1243 EXPORT_SYMBOL(nr_pagecache);
1244 #ifdef CONFIG_SMP
1245 DEFINE_PER_CPU(long, nr_pagecache_local) = 0;
1246 #endif
1247
1248 static void __get_page_state(struct page_state *ret, int nr, cpumask_t *cpumask)
1249 {
1250         unsigned cpu;
1251
1252         memset(ret, 0, nr * sizeof(unsigned long));
1253         cpus_and(*cpumask, *cpumask, cpu_online_map);
1254
1255         for_each_cpu_mask(cpu, *cpumask) {
1256                 unsigned long *in;
1257                 unsigned long *out;
1258                 unsigned off;
1259                 unsigned next_cpu;
1260
1261                 in = (unsigned long *)&per_cpu(page_states, cpu);
1262
1263                 next_cpu = next_cpu(cpu, *cpumask);
1264                 if (likely(next_cpu < NR_CPUS))
1265                         prefetch(&per_cpu(page_states, next_cpu));
1266
1267                 out = (unsigned long *)ret;
1268                 for (off = 0; off < nr; off++)
1269                         *out++ += *in++;
1270         }
1271 }
1272
1273 void get_page_state_node(struct page_state *ret, int node)
1274 {
1275         int nr;
1276         cpumask_t mask = node_to_cpumask(node);
1277
1278         nr = offsetof(struct page_state, GET_PAGE_STATE_LAST);
1279         nr /= sizeof(unsigned long);
1280
1281         __get_page_state(ret, nr+1, &mask);
1282 }
1283
1284 void get_page_state(struct page_state *ret)
1285 {
1286         int nr;
1287         cpumask_t mask = CPU_MASK_ALL;
1288
1289         nr = offsetof(struct page_state, GET_PAGE_STATE_LAST);
1290         nr /= sizeof(unsigned long);
1291
1292         __get_page_state(ret, nr + 1, &mask);
1293 }
1294
1295 void get_full_page_state(struct page_state *ret)
1296 {
1297         cpumask_t mask = CPU_MASK_ALL;
1298
1299         __get_page_state(ret, sizeof(*ret) / sizeof(unsigned long), &mask);
1300 }
1301
1302 unsigned long read_page_state_offset(unsigned long offset)
1303 {
1304         unsigned long ret = 0;
1305         int cpu;
1306
1307         for_each_online_cpu(cpu) {
1308                 unsigned long in;
1309
1310                 in = (unsigned long)&per_cpu(page_states, cpu) + offset;
1311                 ret += *((unsigned long *)in);
1312         }
1313         return ret;
1314 }
1315
1316 void __mod_page_state_offset(unsigned long offset, unsigned long delta)
1317 {
1318         void *ptr;
1319
1320         ptr = &__get_cpu_var(page_states);
1321         *(unsigned long *)(ptr + offset) += delta;
1322 }
1323 EXPORT_SYMBOL(__mod_page_state_offset);
1324
1325 void mod_page_state_offset(unsigned long offset, unsigned long delta)
1326 {
1327         unsigned long flags;
1328         void *ptr;
1329
1330         local_irq_save(flags);
1331         ptr = &__get_cpu_var(page_states);
1332         *(unsigned long *)(ptr + offset) += delta;
1333         local_irq_restore(flags);
1334 }
1335 EXPORT_SYMBOL(mod_page_state_offset);
1336
1337 void __get_zone_counts(unsigned long *active, unsigned long *inactive,
1338                         unsigned long *free, struct pglist_data *pgdat)
1339 {
1340         struct zone *zones = pgdat->node_zones;
1341         int i;
1342
1343         *active = 0;
1344         *inactive = 0;
1345         *free = 0;
1346         for (i = 0; i < MAX_NR_ZONES; i++) {
1347                 *active += zones[i].nr_active;
1348                 *inactive += zones[i].nr_inactive;
1349                 *free += zones[i].free_pages;
1350         }
1351 }
1352
1353 void get_zone_counts(unsigned long *active,
1354                 unsigned long *inactive, unsigned long *free)
1355 {
1356         struct pglist_data *pgdat;
1357
1358         *active = 0;
1359         *inactive = 0;
1360         *free = 0;
1361         for_each_online_pgdat(pgdat) {
1362                 unsigned long l, m, n;
1363                 __get_zone_counts(&l, &m, &n, pgdat);
1364                 *active += l;
1365                 *inactive += m;
1366                 *free += n;
1367         }
1368 }
1369
1370 void si_meminfo(struct sysinfo *val)
1371 {
1372         val->totalram = totalram_pages;
1373         val->sharedram = 0;
1374         val->freeram = nr_free_pages();
1375         val->bufferram = nr_blockdev_pages();
1376 #ifdef CONFIG_HIGHMEM
1377         val->totalhigh = totalhigh_pages;
1378         val->freehigh = nr_free_highpages();
1379 #else
1380         val->totalhigh = 0;
1381         val->freehigh = 0;
1382 #endif
1383         val->mem_unit = PAGE_SIZE;
1384         if (vx_flags(VXF_VIRT_MEM, 0))
1385                 vx_vsi_meminfo(val);
1386 }
1387
1388 EXPORT_SYMBOL(si_meminfo);
1389
1390 #ifdef CONFIG_NUMA
1391 void si_meminfo_node(struct sysinfo *val, int nid)
1392 {
1393         pg_data_t *pgdat = NODE_DATA(nid);
1394
1395         val->totalram = pgdat->node_present_pages;
1396         val->freeram = nr_free_pages_pgdat(pgdat);
1397         val->totalhigh = pgdat->node_zones[ZONE_HIGHMEM].present_pages;
1398         val->freehigh = pgdat->node_zones[ZONE_HIGHMEM].free_pages;
1399         val->mem_unit = PAGE_SIZE;
1400         if (vx_flags(VXF_VIRT_MEM, 0))
1401                 vx_vsi_meminfo(val);
1402 }
1403 #endif
1404
1405 #define K(x) ((x) << (PAGE_SHIFT-10))
1406
1407 /*
1408  * Show free area list (used inside shift_scroll-lock stuff)
1409  * We also calculate the percentage fragmentation. We do this by counting the
1410  * memory on each free list with the exception of the first item on the list.
1411  */
1412 void show_free_areas(void)
1413 {
1414         struct page_state ps;
1415         int cpu, temperature;
1416         unsigned long active;
1417         unsigned long inactive;
1418         unsigned long free;
1419         struct zone *zone;
1420
1421         for_each_zone(zone) {
1422                 show_node(zone);
1423                 printk("%s per-cpu:", zone->name);
1424
1425                 if (!populated_zone(zone)) {
1426                         printk(" empty\n");
1427                         continue;
1428                 } else
1429                         printk("\n");
1430
1431                 for_each_online_cpu(cpu) {
1432                         struct per_cpu_pageset *pageset;
1433
1434                         pageset = zone_pcp(zone, cpu);
1435
1436                         for (temperature = 0; temperature < 2; temperature++)
1437                                 printk("cpu %d %s: high %d, batch %d used:%d\n",
1438                                         cpu,
1439                                         temperature ? "cold" : "hot",
1440                                         pageset->pcp[temperature].high,
1441                                         pageset->pcp[temperature].batch,
1442                                         pageset->pcp[temperature].count);
1443                 }
1444         }
1445
1446         get_page_state(&ps);
1447         get_zone_counts(&active, &inactive, &free);
1448
1449         printk("Free pages: %11ukB (%ukB HighMem)\n",
1450                 K(nr_free_pages()),
1451                 K(nr_free_highpages()));
1452
1453         printk("Active:%lu inactive:%lu dirty:%lu writeback:%lu "
1454                 "unstable:%lu free:%u slab:%lu mapped:%lu pagetables:%lu\n",
1455                 active,
1456                 inactive,
1457                 ps.nr_dirty,
1458                 ps.nr_writeback,
1459                 ps.nr_unstable,
1460                 nr_free_pages(),
1461                 ps.nr_slab,
1462                 ps.nr_mapped,
1463                 ps.nr_page_table_pages);
1464
1465         for_each_zone(zone) {
1466                 int i;
1467
1468                 show_node(zone);
1469                 printk("%s"
1470                         " free:%lukB"
1471                         " min:%lukB"
1472                         " low:%lukB"
1473                         " high:%lukB"
1474                         " active:%lukB"
1475                         " inactive:%lukB"
1476                         " present:%lukB"
1477                         " pages_scanned:%lu"
1478                         " all_unreclaimable? %s"
1479                         "\n",
1480                         zone->name,
1481                         K(zone->free_pages),
1482                         K(zone->pages_min),
1483                         K(zone->pages_low),
1484                         K(zone->pages_high),
1485                         K(zone->nr_active),
1486                         K(zone->nr_inactive),
1487                         K(zone->present_pages),
1488                         zone->pages_scanned,
1489                         (zone->all_unreclaimable ? "yes" : "no")
1490                         );
1491                 printk("lowmem_reserve[]:");
1492                 for (i = 0; i < MAX_NR_ZONES; i++)
1493                         printk(" %lu", zone->lowmem_reserve[i]);
1494                 printk("\n");
1495         }
1496
1497         for_each_zone(zone) {
1498                 unsigned long nr, flags, order, total = 0;
1499
1500                 show_node(zone);
1501                 printk("%s: ", zone->name);
1502                 if (!populated_zone(zone)) {
1503                         printk("empty\n");
1504                         continue;
1505                 }
1506
1507                 spin_lock_irqsave(&zone->lock, flags);
1508                 for (order = 0; order < MAX_ORDER; order++) {
1509                         nr = zone->free_area[order].nr_free;
1510                         total += nr << order;
1511                         printk("%lu*%lukB ", nr, K(1UL) << order);
1512                 }
1513                 spin_unlock_irqrestore(&zone->lock, flags);
1514                 printk("= %lukB\n", K(total));
1515         }
1516
1517         show_swap_cache_info();
1518 }
1519
1520 /*
1521  * Builds allocation fallback zone lists.
1522  *
1523  * Add all populated zones of a node to the zonelist.
1524  */
1525 static int __init build_zonelists_node(pg_data_t *pgdat,
1526                         struct zonelist *zonelist, int nr_zones, int zone_type)
1527 {
1528         struct zone *zone;
1529
1530         BUG_ON(zone_type > ZONE_HIGHMEM);
1531
1532         do {
1533                 zone = pgdat->node_zones + zone_type;
1534                 if (populated_zone(zone)) {
1535 #ifndef CONFIG_HIGHMEM
1536                         BUG_ON(zone_type > ZONE_NORMAL);
1537 #endif
1538                         zonelist->zones[nr_zones++] = zone;
1539                         check_highest_zone(zone_type);
1540                 }
1541                 zone_type--;
1542
1543         } while (zone_type >= 0);
1544         return nr_zones;
1545 }
1546
1547 static inline int highest_zone(int zone_bits)
1548 {
1549         int res = ZONE_NORMAL;
1550         if (zone_bits & (__force int)__GFP_HIGHMEM)
1551                 res = ZONE_HIGHMEM;
1552         if (zone_bits & (__force int)__GFP_DMA32)
1553                 res = ZONE_DMA32;
1554         if (zone_bits & (__force int)__GFP_DMA)
1555                 res = ZONE_DMA;
1556         return res;
1557 }
1558
1559 #ifdef CONFIG_NUMA
1560 #define MAX_NODE_LOAD (num_online_nodes())
1561 static int __initdata node_load[MAX_NUMNODES];
1562 /**
1563  * find_next_best_node - find the next node that should appear in a given node's fallback list
1564  * @node: node whose fallback list we're appending
1565  * @used_node_mask: nodemask_t of already used nodes
1566  *
1567  * We use a number of factors to determine which is the next node that should
1568  * appear on a given node's fallback list.  The node should not have appeared
1569  * already in @node's fallback list, and it should be the next closest node
1570  * according to the distance array (which contains arbitrary distance values
1571  * from each node to each node in the system), and should also prefer nodes
1572  * with no CPUs, since presumably they'll have very little allocation pressure
1573  * on them otherwise.
1574  * It returns -1 if no node is found.
1575  */
1576 static int __init find_next_best_node(int node, nodemask_t *used_node_mask)
1577 {
1578         int n, val;
1579         int min_val = INT_MAX;
1580         int best_node = -1;
1581
1582         /* Use the local node if we haven't already */
1583         if (!node_isset(node, *used_node_mask)) {
1584                 node_set(node, *used_node_mask);
1585                 return node;
1586         }
1587
1588         for_each_online_node(n) {
1589                 cpumask_t tmp;
1590
1591                 /* Don't want a node to appear more than once */
1592                 if (node_isset(n, *used_node_mask))
1593                         continue;
1594
1595                 /* Use the distance array to find the distance */
1596                 val = node_distance(node, n);
1597
1598                 /* Penalize nodes under us ("prefer the next node") */
1599                 val += (n < node);
1600
1601                 /* Give preference to headless and unused nodes */
1602                 tmp = node_to_cpumask(n);
1603                 if (!cpus_empty(tmp))
1604                         val += PENALTY_FOR_NODE_WITH_CPUS;
1605
1606                 /* Slight preference for less loaded node */
1607                 val *= (MAX_NODE_LOAD*MAX_NUMNODES);
1608                 val += node_load[n];
1609
1610                 if (val < min_val) {
1611                         min_val = val;
1612                         best_node = n;
1613                 }
1614         }
1615
1616         if (best_node >= 0)
1617                 node_set(best_node, *used_node_mask);
1618
1619         return best_node;
1620 }
1621
1622 static void __init build_zonelists(pg_data_t *pgdat)
1623 {
1624         int i, j, k, node, local_node;
1625         int prev_node, load;
1626         struct zonelist *zonelist;
1627         nodemask_t used_mask;
1628
1629         /* initialize zonelists */
1630         for (i = 0; i < GFP_ZONETYPES; i++) {
1631                 zonelist = pgdat->node_zonelists + i;
1632                 zonelist->zones[0] = NULL;
1633         }
1634
1635         /* NUMA-aware ordering of nodes */
1636         local_node = pgdat->node_id;
1637         load = num_online_nodes();
1638         prev_node = local_node;
1639         nodes_clear(used_mask);
1640         while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
1641                 int distance = node_distance(local_node, node);
1642
1643                 /*
1644                  * If another node is sufficiently far away then it is better
1645                  * to reclaim pages in a zone before going off node.
1646                  */
1647                 if (distance > RECLAIM_DISTANCE)
1648                         zone_reclaim_mode = 1;
1649
1650                 /*
1651                  * We don't want to pressure a particular node.
1652                  * So adding penalty to the first node in same
1653                  * distance group to make it round-robin.
1654                  */
1655
1656                 if (distance != node_distance(local_node, prev_node))
1657                         node_load[node] += load;
1658                 prev_node = node;
1659                 load--;
1660                 for (i = 0; i < GFP_ZONETYPES; i++) {
1661                         zonelist = pgdat->node_zonelists + i;
1662                         for (j = 0; zonelist->zones[j] != NULL; j++);
1663
1664                         k = highest_zone(i);
1665
1666                         j = build_zonelists_node(NODE_DATA(node), zonelist, j, k);
1667                         zonelist->zones[j] = NULL;
1668                 }
1669         }
1670 }
1671
1672 #else   /* CONFIG_NUMA */
1673
1674 static void __init build_zonelists(pg_data_t *pgdat)
1675 {
1676         int i, j, k, node, local_node;
1677
1678         local_node = pgdat->node_id;
1679         for (i = 0; i < GFP_ZONETYPES; i++) {
1680                 struct zonelist *zonelist;
1681
1682                 zonelist = pgdat->node_zonelists + i;
1683
1684                 j = 0;
1685                 k = highest_zone(i);
1686                 j = build_zonelists_node(pgdat, zonelist, j, k);
1687                 /*
1688                  * Now we build the zonelist so that it contains the zones
1689                  * of all the other nodes.
1690                  * We don't want to pressure a particular node, so when
1691                  * building the zones for node N, we make sure that the
1692                  * zones coming right after the local ones are those from
1693                  * node N+1 (modulo N)
1694                  */
1695                 for (node = local_node + 1; node < MAX_NUMNODES; node++) {
1696                         if (!node_online(node))
1697                                 continue;
1698                         j = build_zonelists_node(NODE_DATA(node), zonelist, j, k);
1699                 }
1700                 for (node = 0; node < local_node; node++) {
1701                         if (!node_online(node))
1702                                 continue;
1703                         j = build_zonelists_node(NODE_DATA(node), zonelist, j, k);
1704                 }
1705
1706                 zonelist->zones[j] = NULL;
1707         }
1708 }
1709
1710 #endif  /* CONFIG_NUMA */
1711
1712 void __init build_all_zonelists(void)
1713 {
1714         int i;
1715
1716         for_each_online_node(i)
1717                 build_zonelists(NODE_DATA(i));
1718         printk("Built %i zonelists\n", num_online_nodes());
1719         cpuset_init_current_mems_allowed();
1720 }
1721
1722 /*
1723  * Helper functions to size the waitqueue hash table.
1724  * Essentially these want to choose hash table sizes sufficiently
1725  * large so that collisions trying to wait on pages are rare.
1726  * But in fact, the number of active page waitqueues on typical
1727  * systems is ridiculously low, less than 200. So this is even
1728  * conservative, even though it seems large.
1729  *
1730  * The constant PAGES_PER_WAITQUEUE specifies the ratio of pages to
1731  * waitqueues, i.e. the size of the waitq table given the number of pages.
1732  */
1733 #define PAGES_PER_WAITQUEUE     256
1734
1735 static inline unsigned long wait_table_size(unsigned long pages)
1736 {
1737         unsigned long size = 1;
1738
1739         pages /= PAGES_PER_WAITQUEUE;
1740
1741         while (size < pages)
1742                 size <<= 1;
1743
1744         /*
1745          * Once we have dozens or even hundreds of threads sleeping
1746          * on IO we've got bigger problems than wait queue collision.
1747          * Limit the size of the wait table to a reasonable size.
1748          */
1749         size = min(size, 4096UL);
1750
1751         return max(size, 4UL);
1752 }
1753
1754 /*
1755  * This is an integer logarithm so that shifts can be used later
1756  * to extract the more random high bits from the multiplicative
1757  * hash function before the remainder is taken.
1758  */
1759 static inline unsigned long wait_table_bits(unsigned long size)
1760 {
1761         return ffz(~size);
1762 }
1763
1764 #define LONG_ALIGN(x) (((x)+(sizeof(long))-1)&~((sizeof(long))-1))
1765
1766 static void __init calculate_zone_totalpages(struct pglist_data *pgdat,
1767                 unsigned long *zones_size, unsigned long *zholes_size)
1768 {
1769         unsigned long realtotalpages, totalpages = 0;
1770         int i;
1771
1772         for (i = 0; i < MAX_NR_ZONES; i++)
1773                 totalpages += zones_size[i];
1774         pgdat->node_spanned_pages = totalpages;
1775
1776         realtotalpages = totalpages;
1777         if (zholes_size)
1778                 for (i = 0; i < MAX_NR_ZONES; i++)
1779                         realtotalpages -= zholes_size[i];
1780         pgdat->node_present_pages = realtotalpages;
1781         printk(KERN_DEBUG "On node %d totalpages: %lu\n", pgdat->node_id, realtotalpages);
1782 }
1783
1784
1785 /*
1786  * Initially all pages are reserved - free ones are freed
1787  * up by free_all_bootmem() once the early boot process is
1788  * done. Non-atomic initialization, single-pass.
1789  */
1790 void __meminit memmap_init_zone(unsigned long size, int nid, unsigned long zone,
1791                 unsigned long start_pfn)
1792 {
1793         struct page *page;
1794         unsigned long end_pfn = start_pfn + size;
1795         unsigned long pfn;
1796
1797         for (pfn = start_pfn; pfn < end_pfn; pfn++) {
1798                 if (!early_pfn_valid(pfn))
1799                         continue;
1800                 page = pfn_to_page(pfn);
1801                 set_page_links(page, zone, nid, pfn);
1802                 init_page_count(page);
1803                 reset_page_mapcount(page);
1804                 SetPageReserved(page);
1805                 INIT_LIST_HEAD(&page->lru);
1806 #ifdef WANT_PAGE_VIRTUAL
1807                 /* The shift won't overflow because ZONE_NORMAL is below 4G. */
1808                 if (!is_highmem_idx(zone))
1809                         set_page_address(page, __va(pfn << PAGE_SHIFT));
1810 #endif
1811         }
1812 }
1813
1814 void zone_init_free_lists(struct pglist_data *pgdat, struct zone *zone,
1815                                 unsigned long size)
1816 {
1817         int order;
1818         for (order = 0; order < MAX_ORDER ; order++) {
1819                 INIT_LIST_HEAD(&zone->free_area[order].free_list);
1820                 zone->free_area[order].nr_free = 0;
1821         }
1822 }
1823
1824 #define ZONETABLE_INDEX(x, zone_nr)     ((x << ZONES_SHIFT) | zone_nr)
1825 void zonetable_add(struct zone *zone, int nid, int zid, unsigned long pfn,
1826                 unsigned long size)
1827 {
1828         unsigned long snum = pfn_to_section_nr(pfn);
1829         unsigned long end = pfn_to_section_nr(pfn + size);
1830
1831         if (FLAGS_HAS_NODE)
1832                 zone_table[ZONETABLE_INDEX(nid, zid)] = zone;
1833         else
1834                 for (; snum <= end; snum++)
1835                         zone_table[ZONETABLE_INDEX(snum, zid)] = zone;
1836 }
1837
1838 #ifndef __HAVE_ARCH_MEMMAP_INIT
1839 #define memmap_init(size, nid, zone, start_pfn) \
1840         memmap_init_zone((size), (nid), (zone), (start_pfn))
1841 #endif
1842
1843 static int __cpuinit zone_batchsize(struct zone *zone)
1844 {
1845         int batch;
1846
1847         /*
1848          * The per-cpu-pages pools are set to around 1000th of the
1849          * size of the zone.  But no more than 1/2 of a meg.
1850          *
1851          * OK, so we don't know how big the cache is.  So guess.
1852          */
1853         batch = zone->present_pages / 1024;
1854         if (batch * PAGE_SIZE > 512 * 1024)
1855                 batch = (512 * 1024) / PAGE_SIZE;
1856         batch /= 4;             /* We effectively *= 4 below */
1857         if (batch < 1)
1858                 batch = 1;
1859
1860         /*
1861          * Clamp the batch to a 2^n - 1 value. Having a power
1862          * of 2 value was found to be more likely to have
1863          * suboptimal cache aliasing properties in some cases.
1864          *
1865          * For example if 2 tasks are alternately allocating
1866          * batches of pages, one task can end up with a lot
1867          * of pages of one half of the possible page colors
1868          * and the other with pages of the other colors.
1869          */
1870         batch = (1 << (fls(batch + batch/2)-1)) - 1;
1871
1872         return batch;
1873 }
1874
1875 inline void setup_pageset(struct per_cpu_pageset *p, unsigned long batch)
1876 {
1877         struct per_cpu_pages *pcp;
1878
1879         memset(p, 0, sizeof(*p));
1880
1881         pcp = &p->pcp[0];               /* hot */
1882         pcp->count = 0;
1883         pcp->high = 6 * batch;
1884         pcp->batch = max(1UL, 1 * batch);
1885         INIT_LIST_HEAD(&pcp->list);
1886
1887         pcp = &p->pcp[1];               /* cold*/
1888         pcp->count = 0;
1889         pcp->high = 2 * batch;
1890         pcp->batch = max(1UL, batch/2);
1891         INIT_LIST_HEAD(&pcp->list);
1892 }
1893
1894 /*
1895  * setup_pagelist_highmark() sets the high water mark for hot per_cpu_pagelist
1896  * to the value high for the pageset p.
1897  */
1898
1899 static void setup_pagelist_highmark(struct per_cpu_pageset *p,
1900                                 unsigned long high)
1901 {
1902         struct per_cpu_pages *pcp;
1903
1904         pcp = &p->pcp[0]; /* hot list */
1905         pcp->high = high;
1906         pcp->batch = max(1UL, high/4);
1907         if ((high/4) > (PAGE_SHIFT * 8))
1908                 pcp->batch = PAGE_SHIFT * 8;
1909 }
1910
1911
1912 #ifdef CONFIG_NUMA
1913 /*
1914  * Boot pageset table. One per cpu which is going to be used for all
1915  * zones and all nodes. The parameters will be set in such a way
1916  * that an item put on a list will immediately be handed over to
1917  * the buddy list. This is safe since pageset manipulation is done
1918  * with interrupts disabled.
1919  *
1920  * Some NUMA counter updates may also be caught by the boot pagesets.
1921  *
1922  * The boot_pagesets must be kept even after bootup is complete for
1923  * unused processors and/or zones. They do play a role for bootstrapping
1924  * hotplugged processors.
1925  *
1926  * zoneinfo_show() and maybe other functions do
1927  * not check if the processor is online before following the pageset pointer.
1928  * Other parts of the kernel may not check if the zone is available.
1929  */
1930 static struct per_cpu_pageset boot_pageset[NR_CPUS];
1931
1932 /*
1933  * Dynamically allocate memory for the
1934  * per cpu pageset array in struct zone.
1935  */
1936 static int __cpuinit process_zones(int cpu)
1937 {
1938         struct zone *zone, *dzone;
1939
1940         for_each_zone(zone) {
1941
1942                 zone_pcp(zone, cpu) = kmalloc_node(sizeof(struct per_cpu_pageset),
1943                                          GFP_KERNEL, cpu_to_node(cpu));
1944                 if (!zone_pcp(zone, cpu))
1945                         goto bad;
1946
1947                 setup_pageset(zone_pcp(zone, cpu), zone_batchsize(zone));
1948
1949                 if (percpu_pagelist_fraction)
1950                         setup_pagelist_highmark(zone_pcp(zone, cpu),
1951                                 (zone->present_pages / percpu_pagelist_fraction));
1952         }
1953
1954         return 0;
1955 bad:
1956         for_each_zone(dzone) {
1957                 if (dzone == zone)
1958                         break;
1959                 kfree(zone_pcp(dzone, cpu));
1960                 zone_pcp(dzone, cpu) = NULL;
1961         }
1962         return -ENOMEM;
1963 }
1964
1965 static inline void free_zone_pagesets(int cpu)
1966 {
1967         struct zone *zone;
1968
1969         for_each_zone(zone) {
1970                 struct per_cpu_pageset *pset = zone_pcp(zone, cpu);
1971
1972                 zone_pcp(zone, cpu) = NULL;
1973                 kfree(pset);
1974         }
1975 }
1976
1977 static int pageset_cpuup_callback(struct notifier_block *nfb,
1978                 unsigned long action,
1979                 void *hcpu)
1980 {
1981         int cpu = (long)hcpu;
1982         int ret = NOTIFY_OK;
1983
1984         switch (action) {
1985                 case CPU_UP_PREPARE:
1986                         if (process_zones(cpu))
1987                                 ret = NOTIFY_BAD;
1988                         break;
1989                 case CPU_UP_CANCELED:
1990                 case CPU_DEAD:
1991                         free_zone_pagesets(cpu);
1992                         break;
1993                 default:
1994                         break;
1995         }
1996         return ret;
1997 }
1998
1999 static struct notifier_block pageset_notifier =
2000         { &pageset_cpuup_callback, NULL, 0 };
2001
2002 void __init setup_per_cpu_pageset(void)
2003 {
2004         int err;
2005
2006         /* Initialize per_cpu_pageset for cpu 0.
2007          * A cpuup callback will do this for every cpu
2008          * as it comes online
2009          */
2010         err = process_zones(smp_processor_id());
2011         BUG_ON(err);
2012         register_cpu_notifier(&pageset_notifier);
2013 }
2014
2015 #endif
2016
2017 static __meminit
2018 void zone_wait_table_init(struct zone *zone, unsigned long zone_size_pages)
2019 {
2020         int i;
2021         struct pglist_data *pgdat = zone->zone_pgdat;
2022
2023         /*
2024          * The per-page waitqueue mechanism uses hashed waitqueues
2025          * per zone.
2026          */
2027         zone->wait_table_size = wait_table_size(zone_size_pages);
2028         zone->wait_table_bits = wait_table_bits(zone->wait_table_size);
2029         zone->wait_table = (wait_queue_head_t *)
2030                 alloc_bootmem_node(pgdat, zone->wait_table_size
2031                                         * sizeof(wait_queue_head_t));
2032
2033         for(i = 0; i < zone->wait_table_size; ++i)
2034                 init_waitqueue_head(zone->wait_table + i);
2035 }
2036
2037 static __meminit void zone_pcp_init(struct zone *zone)
2038 {
2039         int cpu;
2040         unsigned long batch = zone_batchsize(zone);
2041
2042         for (cpu = 0; cpu < NR_CPUS; cpu++) {
2043 #ifdef CONFIG_NUMA
2044                 /* Early boot. Slab allocator not functional yet */
2045                 zone_pcp(zone, cpu) = &boot_pageset[cpu];
2046                 setup_pageset(&boot_pageset[cpu],0);
2047 #else
2048                 setup_pageset(zone_pcp(zone,cpu), batch);
2049 #endif
2050         }
2051         if (zone->present_pages)
2052                 printk(KERN_DEBUG "  %s zone: %lu pages, LIFO batch:%lu\n",
2053                         zone->name, zone->present_pages, batch);
2054 }
2055
2056 static __meminit void init_currently_empty_zone(struct zone *zone,
2057                 unsigned long zone_start_pfn, unsigned long size)
2058 {
2059         struct pglist_data *pgdat = zone->zone_pgdat;
2060
2061         zone_wait_table_init(zone, size);
2062         pgdat->nr_zones = zone_idx(zone) + 1;
2063
2064         zone->zone_start_pfn = zone_start_pfn;
2065
2066         memmap_init(size, pgdat->node_id, zone_idx(zone), zone_start_pfn);
2067
2068         zone_init_free_lists(pgdat, zone, zone->spanned_pages);
2069 }
2070
2071 /*
2072  * Set up the zone data structures:
2073  *   - mark all pages reserved
2074  *   - mark all memory queues empty
2075  *   - clear the memory bitmaps
2076  */
2077 static void __init free_area_init_core(struct pglist_data *pgdat,
2078                 unsigned long *zones_size, unsigned long *zholes_size)
2079 {
2080         unsigned long j;
2081         int nid = pgdat->node_id;
2082         unsigned long zone_start_pfn = pgdat->node_start_pfn;
2083
2084         pgdat_resize_init(pgdat);
2085         pgdat->nr_zones = 0;
2086         init_waitqueue_head(&pgdat->kswapd_wait);
2087         pgdat->kswapd_max_order = 0;
2088         
2089         for (j = 0; j < MAX_NR_ZONES; j++) {
2090                 struct zone *zone = pgdat->node_zones + j;
2091                 unsigned long size, realsize;
2092
2093                 realsize = size = zones_size[j];
2094                 if (zholes_size)
2095                         realsize -= zholes_size[j];
2096
2097                 if (j < ZONE_HIGHMEM)
2098                         nr_kernel_pages += realsize;
2099                 nr_all_pages += realsize;
2100
2101                 zone->spanned_pages = size;
2102                 zone->present_pages = realsize;
2103                 zone->name = zone_names[j];
2104                 spin_lock_init(&zone->lock);
2105                 spin_lock_init(&zone->lru_lock);
2106                 zone_seqlock_init(zone);
2107                 zone->zone_pgdat = pgdat;
2108                 zone->free_pages = 0;
2109
2110                 zone->temp_priority = zone->prev_priority = DEF_PRIORITY;
2111
2112                 zone_pcp_init(zone);
2113                 INIT_LIST_HEAD(&zone->active_list);
2114                 INIT_LIST_HEAD(&zone->inactive_list);
2115                 zone->nr_scan_active = 0;
2116                 zone->nr_scan_inactive = 0;
2117                 zone->nr_active = 0;
2118                 zone->nr_inactive = 0;
2119                 atomic_set(&zone->reclaim_in_progress, 0);
2120                 if (!size)
2121                         continue;
2122
2123                 zonetable_add(zone, nid, j, zone_start_pfn, size);
2124                 init_currently_empty_zone(zone, zone_start_pfn, size);
2125                 zone_start_pfn += size;
2126         }
2127 }
2128
2129 static void __init alloc_node_mem_map(struct pglist_data *pgdat)
2130 {
2131         /* Skip empty nodes */
2132         if (!pgdat->node_spanned_pages)
2133                 return;
2134
2135 #ifdef CONFIG_FLAT_NODE_MEM_MAP
2136         /* ia64 gets its own node_mem_map, before this, without bootmem */
2137         if (!pgdat->node_mem_map) {
2138                 unsigned long size, start, end;
2139                 struct page *map;
2140
2141                 /*
2142                  * The zone's endpoints aren't required to be MAX_ORDER
2143                  * aligned but the node_mem_map endpoints must be in order
2144                  * for the buddy allocator to function correctly.
2145                  */
2146                 start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1);
2147                 end = pgdat->node_start_pfn + pgdat->node_spanned_pages;
2148                 end = ALIGN(end, MAX_ORDER_NR_PAGES);
2149                 size =  (end - start) * sizeof(struct page);
2150                 map = alloc_remap(pgdat->node_id, size);
2151                 if (!map)
2152                         map = alloc_bootmem_node(pgdat, size);
2153                 pgdat->node_mem_map = map + (pgdat->node_start_pfn - start);
2154         }
2155 #ifdef CONFIG_FLATMEM
2156         /*
2157          * With no DISCONTIG, the global mem_map is just set as node 0's
2158          */
2159         if (pgdat == NODE_DATA(0))
2160                 mem_map = NODE_DATA(0)->node_mem_map;
2161 #endif
2162 #endif /* CONFIG_FLAT_NODE_MEM_MAP */
2163 }
2164
2165 void __init free_area_init_node(int nid, struct pglist_data *pgdat,
2166                 unsigned long *zones_size, unsigned long node_start_pfn,
2167                 unsigned long *zholes_size)
2168 {
2169         pgdat->node_id = nid;
2170         pgdat->node_start_pfn = node_start_pfn;
2171         calculate_zone_totalpages(pgdat, zones_size, zholes_size);
2172
2173         alloc_node_mem_map(pgdat);
2174
2175         free_area_init_core(pgdat, zones_size, zholes_size);
2176 }
2177
2178 #ifndef CONFIG_NEED_MULTIPLE_NODES
2179 static bootmem_data_t contig_bootmem_data;
2180 struct pglist_data contig_page_data = { .bdata = &contig_bootmem_data };
2181
2182 EXPORT_SYMBOL(contig_page_data);
2183 #endif
2184
2185 void __init free_area_init(unsigned long *zones_size)
2186 {
2187         free_area_init_node(0, NODE_DATA(0), zones_size,
2188                         __pa(PAGE_OFFSET) >> PAGE_SHIFT, NULL);
2189 }
2190
2191 #ifdef CONFIG_PROC_FS
2192
2193 #include <linux/seq_file.h>
2194
2195 static void *frag_start(struct seq_file *m, loff_t *pos)
2196 {
2197         pg_data_t *pgdat;
2198         loff_t node = *pos;
2199         for (pgdat = first_online_pgdat();
2200              pgdat && node;
2201              pgdat = next_online_pgdat(pgdat))
2202                 --node;
2203
2204         return pgdat;
2205 }
2206
2207 static void *frag_next(struct seq_file *m, void *arg, loff_t *pos)
2208 {
2209         pg_data_t *pgdat = (pg_data_t *)arg;
2210
2211         (*pos)++;
2212         return next_online_pgdat(pgdat);
2213 }
2214
2215 static void frag_stop(struct seq_file *m, void *arg)
2216 {
2217 }
2218
2219 /* 
2220  * This walks the free areas for each zone.
2221  */
2222 static int frag_show(struct seq_file *m, void *arg)
2223 {
2224         pg_data_t *pgdat = (pg_data_t *)arg;
2225         struct zone *zone;
2226         struct zone *node_zones = pgdat->node_zones;
2227         unsigned long flags;
2228         int order;
2229
2230         for (zone = node_zones; zone - node_zones < MAX_NR_ZONES; ++zone) {
2231                 if (!populated_zone(zone))
2232                         continue;
2233
2234                 spin_lock_irqsave(&zone->lock, flags);
2235                 seq_printf(m, "Node %d, zone %8s ", pgdat->node_id, zone->name);
2236                 for (order = 0; order < MAX_ORDER; ++order)
2237                         seq_printf(m, "%6lu ", zone->free_area[order].nr_free);
2238                 spin_unlock_irqrestore(&zone->lock, flags);
2239                 seq_putc(m, '\n');
2240         }
2241         return 0;
2242 }
2243
2244 struct seq_operations fragmentation_op = {
2245         .start  = frag_start,
2246         .next   = frag_next,
2247         .stop   = frag_stop,
2248         .show   = frag_show,
2249 };
2250
2251 /*
2252  * Output information about zones in @pgdat.
2253  */
2254 static int zoneinfo_show(struct seq_file *m, void *arg)
2255 {
2256         pg_data_t *pgdat = arg;
2257         struct zone *zone;
2258         struct zone *node_zones = pgdat->node_zones;
2259         unsigned long flags;
2260
2261         for (zone = node_zones; zone - node_zones < MAX_NR_ZONES; zone++) {
2262                 int i;
2263
2264                 if (!populated_zone(zone))
2265                         continue;
2266
2267                 spin_lock_irqsave(&zone->lock, flags);
2268                 seq_printf(m, "Node %d, zone %8s", pgdat->node_id, zone->name);
2269                 seq_printf(m,
2270                            "\n  pages free     %lu"
2271                            "\n        min      %lu"
2272                            "\n        low      %lu"
2273                            "\n        high     %lu"
2274                            "\n        active   %lu"
2275                            "\n        inactive %lu"
2276                            "\n        scanned  %lu (a: %lu i: %lu)"
2277                            "\n        spanned  %lu"
2278                            "\n        present  %lu",
2279                            zone->free_pages,
2280                            zone->pages_min,
2281                            zone->pages_low,
2282                            zone->pages_high,
2283                            zone->nr_active,
2284                            zone->nr_inactive,
2285                            zone->pages_scanned,
2286                            zone->nr_scan_active, zone->nr_scan_inactive,
2287                            zone->spanned_pages,
2288                            zone->present_pages);
2289                 seq_printf(m,
2290                            "\n        protection: (%lu",
2291                            zone->lowmem_reserve[0]);
2292                 for (i = 1; i < ARRAY_SIZE(zone->lowmem_reserve); i++)
2293                         seq_printf(m, ", %lu", zone->lowmem_reserve[i]);
2294                 seq_printf(m,
2295                            ")"
2296                            "\n  pagesets");
2297                 for_each_online_cpu(i) {
2298                         struct per_cpu_pageset *pageset;
2299                         int j;
2300
2301                         pageset = zone_pcp(zone, i);
2302                         for (j = 0; j < ARRAY_SIZE(pageset->pcp); j++) {
2303                                 if (pageset->pcp[j].count)
2304                                         break;
2305                         }
2306                         if (j == ARRAY_SIZE(pageset->pcp))
2307                                 continue;
2308                         for (j = 0; j < ARRAY_SIZE(pageset->pcp); j++) {
2309                                 seq_printf(m,
2310                                            "\n    cpu: %i pcp: %i"
2311                                            "\n              count: %i"
2312                                            "\n              high:  %i"
2313                                            "\n              batch: %i",
2314                                            i, j,
2315                                            pageset->pcp[j].count,
2316                                            pageset->pcp[j].high,
2317                                            pageset->pcp[j].batch);
2318                         }
2319 #ifdef CONFIG_NUMA
2320                         seq_printf(m,
2321                                    "\n            numa_hit:       %lu"
2322                                    "\n            numa_miss:      %lu"
2323                                    "\n            numa_foreign:   %lu"
2324                                    "\n            interleave_hit: %lu"
2325                                    "\n            local_node:     %lu"
2326                                    "\n            other_node:     %lu",
2327                                    pageset->numa_hit,
2328                                    pageset->numa_miss,
2329                                    pageset->numa_foreign,
2330                                    pageset->interleave_hit,
2331                                    pageset->local_node,
2332                                    pageset->other_node);
2333 #endif
2334                 }
2335                 seq_printf(m,
2336                            "\n  all_unreclaimable: %u"
2337                            "\n  prev_priority:     %i"
2338                            "\n  temp_priority:     %i"
2339                            "\n  start_pfn:         %lu",
2340                            zone->all_unreclaimable,
2341                            zone->prev_priority,
2342                            zone->temp_priority,
2343                            zone->zone_start_pfn);
2344                 spin_unlock_irqrestore(&zone->lock, flags);
2345                 seq_putc(m, '\n');
2346         }
2347         return 0;
2348 }
2349
2350 struct seq_operations zoneinfo_op = {
2351         .start  = frag_start, /* iterate over all zones. The same as in
2352                                * fragmentation. */
2353         .next   = frag_next,
2354         .stop   = frag_stop,
2355         .show   = zoneinfo_show,
2356 };
2357
2358 static char *vmstat_text[] = {
2359         "nr_dirty",
2360         "nr_writeback",
2361         "nr_unstable",
2362         "nr_page_table_pages",
2363         "nr_mapped",
2364         "nr_slab",
2365
2366         "pgpgin",
2367         "pgpgout",
2368         "pswpin",
2369         "pswpout",
2370
2371         "pgalloc_high",
2372         "pgalloc_normal",
2373         "pgalloc_dma32",
2374         "pgalloc_dma",
2375
2376         "pgfree",
2377         "pgactivate",
2378         "pgdeactivate",
2379
2380         "pgfault",
2381         "pgmajfault",
2382
2383         "pgrefill_high",
2384         "pgrefill_normal",
2385         "pgrefill_dma32",
2386         "pgrefill_dma",
2387
2388         "pgsteal_high",
2389         "pgsteal_normal",
2390         "pgsteal_dma32",
2391         "pgsteal_dma",
2392
2393         "pgscan_kswapd_high",
2394         "pgscan_kswapd_normal",
2395         "pgscan_kswapd_dma32",
2396         "pgscan_kswapd_dma",
2397
2398         "pgscan_direct_high",
2399         "pgscan_direct_normal",
2400         "pgscan_direct_dma32",
2401         "pgscan_direct_dma",
2402
2403         "pginodesteal",
2404         "slabs_scanned",
2405         "kswapd_steal",
2406         "kswapd_inodesteal",
2407         "pageoutrun",
2408         "allocstall",
2409
2410         "pgrotated",
2411         "nr_bounce",
2412 };
2413
2414 static void *vmstat_start(struct seq_file *m, loff_t *pos)
2415 {
2416         struct page_state *ps;
2417
2418         if (*pos >= ARRAY_SIZE(vmstat_text))
2419                 return NULL;
2420
2421         ps = kmalloc(sizeof(*ps), GFP_KERNEL);
2422         m->private = ps;
2423         if (!ps)
2424                 return ERR_PTR(-ENOMEM);
2425         get_full_page_state(ps);
2426         ps->pgpgin /= 2;                /* sectors -> kbytes */
2427         ps->pgpgout /= 2;
2428         return (unsigned long *)ps + *pos;
2429 }
2430
2431 static void *vmstat_next(struct seq_file *m, void *arg, loff_t *pos)
2432 {
2433         (*pos)++;
2434         if (*pos >= ARRAY_SIZE(vmstat_text))
2435                 return NULL;
2436         return (unsigned long *)m->private + *pos;
2437 }
2438
2439 static int vmstat_show(struct seq_file *m, void *arg)
2440 {
2441         unsigned long *l = arg;
2442         unsigned long off = l - (unsigned long *)m->private;
2443
2444         seq_printf(m, "%s %lu\n", vmstat_text[off], *l);
2445         return 0;
2446 }
2447
2448 static void vmstat_stop(struct seq_file *m, void *arg)
2449 {
2450         kfree(m->private);
2451         m->private = NULL;
2452 }
2453
2454 struct seq_operations vmstat_op = {
2455         .start  = vmstat_start,
2456         .next   = vmstat_next,
2457         .stop   = vmstat_stop,
2458         .show   = vmstat_show,
2459 };
2460
2461 #endif /* CONFIG_PROC_FS */
2462
2463 #ifdef CONFIG_HOTPLUG_CPU
2464 static int page_alloc_cpu_notify(struct notifier_block *self,
2465                                  unsigned long action, void *hcpu)
2466 {
2467         int cpu = (unsigned long)hcpu;
2468         long *count;
2469         unsigned long *src, *dest;
2470
2471         if (action == CPU_DEAD) {
2472                 int i;
2473
2474                 /* Drain local pagecache count. */
2475                 count = &per_cpu(nr_pagecache_local, cpu);
2476                 atomic_add(*count, &nr_pagecache);
2477                 *count = 0;
2478                 local_irq_disable();
2479                 __drain_pages(cpu);
2480
2481                 /* Add dead cpu's page_states to our own. */
2482                 dest = (unsigned long *)&__get_cpu_var(page_states);
2483                 src = (unsigned long *)&per_cpu(page_states, cpu);
2484
2485                 for (i = 0; i < sizeof(struct page_state)/sizeof(unsigned long);
2486                                 i++) {
2487                         dest[i] += src[i];
2488                         src[i] = 0;
2489                 }
2490
2491                 local_irq_enable();
2492         }
2493         return NOTIFY_OK;
2494 }
2495 #endif /* CONFIG_HOTPLUG_CPU */
2496
2497 void __init page_alloc_init(void)
2498 {
2499         hotcpu_notifier(page_alloc_cpu_notify, 0);
2500 }
2501
2502 /*
2503  * calculate_totalreserve_pages - called when sysctl_lower_zone_reserve_ratio
2504  *      or min_free_kbytes changes.
2505  */
2506 static void calculate_totalreserve_pages(void)
2507 {
2508         struct pglist_data *pgdat;
2509         unsigned long reserve_pages = 0;
2510         int i, j;
2511
2512         for_each_online_pgdat(pgdat) {
2513                 for (i = 0; i < MAX_NR_ZONES; i++) {
2514                         struct zone *zone = pgdat->node_zones + i;
2515                         unsigned long max = 0;
2516
2517                         /* Find valid and maximum lowmem_reserve in the zone */
2518                         for (j = i; j < MAX_NR_ZONES; j++) {
2519                                 if (zone->lowmem_reserve[j] > max)
2520                                         max = zone->lowmem_reserve[j];
2521                         }
2522
2523                         /* we treat pages_high as reserved pages. */
2524                         max += zone->pages_high;
2525
2526                         if (max > zone->present_pages)
2527                                 max = zone->present_pages;
2528                         reserve_pages += max;
2529                 }
2530         }
2531         totalreserve_pages = reserve_pages;
2532 }
2533
2534 /*
2535  * setup_per_zone_lowmem_reserve - called whenever
2536  *      sysctl_lower_zone_reserve_ratio changes.  Ensures that each zone
2537  *      has a correct pages reserved value, so an adequate number of
2538  *      pages are left in the zone after a successful __alloc_pages().
2539  */
2540 static void setup_per_zone_lowmem_reserve(void)
2541 {
2542         struct pglist_data *pgdat;
2543         int j, idx;
2544
2545         for_each_online_pgdat(pgdat) {
2546                 for (j = 0; j < MAX_NR_ZONES; j++) {
2547                         struct zone *zone = pgdat->node_zones + j;
2548                         unsigned long present_pages = zone->present_pages;
2549
2550                         zone->lowmem_reserve[j] = 0;
2551
2552                         for (idx = j-1; idx >= 0; idx--) {
2553                                 struct zone *lower_zone;
2554
2555                                 if (sysctl_lowmem_reserve_ratio[idx] < 1)
2556                                         sysctl_lowmem_reserve_ratio[idx] = 1;
2557
2558                                 lower_zone = pgdat->node_zones + idx;
2559                                 lower_zone->lowmem_reserve[j] = present_pages /
2560                                         sysctl_lowmem_reserve_ratio[idx];
2561                                 present_pages += lower_zone->present_pages;
2562                         }
2563                 }
2564         }
2565
2566         /* update totalreserve_pages */
2567         calculate_totalreserve_pages();
2568 }
2569
2570 /*
2571  * setup_per_zone_pages_min - called when min_free_kbytes changes.  Ensures 
2572  *      that the pages_{min,low,high} values for each zone are set correctly 
2573  *      with respect to min_free_kbytes.
2574  */
2575 void setup_per_zone_pages_min(void)
2576 {
2577         unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
2578         unsigned long lowmem_pages = 0;
2579         struct zone *zone;
2580         unsigned long flags;
2581
2582         /* Calculate total number of !ZONE_HIGHMEM pages */
2583         for_each_zone(zone) {
2584                 if (!is_highmem(zone))
2585                         lowmem_pages += zone->present_pages;
2586         }
2587
2588         for_each_zone(zone) {
2589                 u64 tmp;
2590
2591                 spin_lock_irqsave(&zone->lru_lock, flags);
2592                 tmp = (u64)pages_min * zone->present_pages;
2593                 do_div(tmp, lowmem_pages);
2594                 if (is_highmem(zone)) {
2595                         /*
2596                          * __GFP_HIGH and PF_MEMALLOC allocations usually don't
2597                          * need highmem pages, so cap pages_min to a small
2598                          * value here.
2599                          *
2600                          * The (pages_high-pages_low) and (pages_low-pages_min)
2601                          * deltas controls asynch page reclaim, and so should
2602                          * not be capped for highmem.
2603                          */
2604                         int min_pages;
2605
2606                         min_pages = zone->present_pages / 1024;
2607                         if (min_pages < SWAP_CLUSTER_MAX)
2608                                 min_pages = SWAP_CLUSTER_MAX;
2609                         if (min_pages > 128)
2610                                 min_pages = 128;
2611                         zone->pages_min = min_pages;
2612                 } else {
2613                         /*
2614                          * If it's a lowmem zone, reserve a number of pages
2615                          * proportionate to the zone's size.
2616                          */
2617                         zone->pages_min = tmp;
2618                 }
2619
2620                 zone->pages_low   = zone->pages_min + (tmp >> 2);
2621                 zone->pages_high  = zone->pages_min + (tmp >> 1);
2622                 spin_unlock_irqrestore(&zone->lru_lock, flags);
2623         }
2624
2625         /* update totalreserve_pages */
2626         calculate_totalreserve_pages();
2627 }
2628
2629 /*
2630  * Initialise min_free_kbytes.
2631  *
2632  * For small machines we want it small (128k min).  For large machines
2633  * we want it large (64MB max).  But it is not linear, because network
2634  * bandwidth does not increase linearly with machine size.  We use
2635  *
2636  *      min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
2637  *      min_free_kbytes = sqrt(lowmem_kbytes * 16)
2638  *
2639  * which yields
2640  *
2641  * 16MB:        512k
2642  * 32MB:        724k
2643  * 64MB:        1024k
2644  * 128MB:       1448k
2645  * 256MB:       2048k
2646  * 512MB:       2896k
2647  * 1024MB:      4096k
2648  * 2048MB:      5792k
2649  * 4096MB:      8192k
2650  * 8192MB:      11584k
2651  * 16384MB:     16384k
2652  */
2653 static int __init init_per_zone_pages_min(void)
2654 {
2655         unsigned long lowmem_kbytes;
2656
2657         lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
2658
2659         min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
2660         if (min_free_kbytes < 128)
2661                 min_free_kbytes = 128;
2662         if (min_free_kbytes > 65536)
2663                 min_free_kbytes = 65536;
2664         setup_per_zone_pages_min();
2665         setup_per_zone_lowmem_reserve();
2666         return 0;
2667 }
2668 module_init(init_per_zone_pages_min)
2669
2670 /*
2671  * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so 
2672  *      that we can call two helper functions whenever min_free_kbytes
2673  *      changes.
2674  */
2675 int min_free_kbytes_sysctl_handler(ctl_table *table, int write, 
2676         struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
2677 {
2678         proc_dointvec(table, write, file, buffer, length, ppos);
2679         setup_per_zone_pages_min();
2680         return 0;
2681 }
2682
2683 /*
2684  * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
2685  *      proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
2686  *      whenever sysctl_lowmem_reserve_ratio changes.
2687  *
2688  * The reserve ratio obviously has absolutely no relation with the
2689  * pages_min watermarks. The lowmem reserve ratio can only make sense
2690  * if in function of the boot time zone sizes.
2691  */
2692 int lowmem_reserve_ratio_sysctl_handler(ctl_table *table, int write,
2693         struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
2694 {
2695         proc_dointvec_minmax(table, write, file, buffer, length, ppos);
2696         setup_per_zone_lowmem_reserve();
2697         return 0;
2698 }
2699
2700 /*
2701  * percpu_pagelist_fraction - changes the pcp->high for each zone on each
2702  * cpu.  It is the fraction of total pages in each zone that a hot per cpu pagelist
2703  * can have before it gets flushed back to buddy allocator.
2704  */
2705
2706 int percpu_pagelist_fraction_sysctl_handler(ctl_table *table, int write,
2707         struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
2708 {
2709         struct zone *zone;
2710         unsigned int cpu;
2711         int ret;
2712
2713         ret = proc_dointvec_minmax(table, write, file, buffer, length, ppos);
2714         if (!write || (ret == -EINVAL))
2715                 return ret;
2716         for_each_zone(zone) {
2717                 for_each_online_cpu(cpu) {
2718                         unsigned long  high;
2719                         high = zone->present_pages / percpu_pagelist_fraction;
2720                         setup_pagelist_highmark(zone_pcp(zone, cpu), high);
2721                 }
2722         }
2723         return 0;
2724 }
2725
2726 __initdata int hashdist = HASHDIST_DEFAULT;
2727
2728 #ifdef CONFIG_NUMA
2729 static int __init set_hashdist(char *str)
2730 {
2731         if (!str)
2732                 return 0;
2733         hashdist = simple_strtoul(str, &str, 0);
2734         return 1;
2735 }
2736 __setup("hashdist=", set_hashdist);
2737 #endif
2738
2739 /*
2740  * allocate a large system hash table from bootmem
2741  * - it is assumed that the hash table must contain an exact power-of-2
2742  *   quantity of entries
2743  * - limit is the number of hash buckets, not the total allocation size
2744  */
2745 void *__init alloc_large_system_hash(const char *tablename,
2746                                      unsigned long bucketsize,
2747                                      unsigned long numentries,
2748                                      int scale,
2749                                      int flags,
2750                                      unsigned int *_hash_shift,
2751                                      unsigned int *_hash_mask,
2752                                      unsigned long limit)
2753 {
2754         unsigned long long max = limit;
2755         unsigned long log2qty, size;
2756         void *table = NULL;
2757
2758         /* allow the kernel cmdline to have a say */
2759         if (!numentries) {
2760                 /* round applicable memory size up to nearest megabyte */
2761                 numentries = (flags & HASH_HIGHMEM) ? nr_all_pages : nr_kernel_pages;
2762                 numentries += (1UL << (20 - PAGE_SHIFT)) - 1;
2763                 numentries >>= 20 - PAGE_SHIFT;
2764                 numentries <<= 20 - PAGE_SHIFT;
2765
2766                 /* limit to 1 bucket per 2^scale bytes of low memory */
2767                 if (scale > PAGE_SHIFT)
2768                         numentries >>= (scale - PAGE_SHIFT);
2769                 else
2770                         numentries <<= (PAGE_SHIFT - scale);
2771         }
2772         numentries = roundup_pow_of_two(numentries);
2773
2774         /* limit allocation size to 1/16 total memory by default */
2775         if (max == 0) {
2776                 max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
2777                 do_div(max, bucketsize);
2778         }
2779
2780         if (numentries > max)
2781                 numentries = max;
2782
2783         log2qty = long_log2(numentries);
2784
2785         do {
2786                 size = bucketsize << log2qty;
2787                 if (flags & HASH_EARLY)
2788                         table = alloc_bootmem(size);
2789                 else if (hashdist)
2790                         table = __vmalloc(size, GFP_ATOMIC, PAGE_KERNEL);
2791                 else {
2792                         unsigned long order;
2793                         for (order = 0; ((1UL << order) << PAGE_SHIFT) < size; order++)
2794                                 ;
2795                         table = (void*) __get_free_pages(GFP_ATOMIC, order);
2796                 }
2797         } while (!table && size > PAGE_SIZE && --log2qty);
2798
2799         if (!table)
2800                 panic("Failed to allocate %s hash table\n", tablename);
2801
2802         printk("%s hash table entries: %d (order: %d, %lu bytes)\n",
2803                tablename,
2804                (1U << log2qty),
2805                long_log2(size) - PAGE_SHIFT,
2806                size);
2807
2808         if (_hash_shift)
2809                 *_hash_shift = log2qty;
2810         if (_hash_mask)
2811                 *_hash_mask = (1 << log2qty) - 1;
2812
2813         return table;
2814 }
2815
2816 #ifdef CONFIG_OUT_OF_LINE_PFN_TO_PAGE
2817 /*
2818  * pfn <-> page translation. out-of-line version.
2819  * (see asm-generic/memory_model.h)
2820  */
2821 #if defined(CONFIG_FLATMEM)
2822 struct page *pfn_to_page(unsigned long pfn)
2823 {
2824         return mem_map + (pfn - ARCH_PFN_OFFSET);
2825 }
2826 unsigned long page_to_pfn(struct page *page)
2827 {
2828         return (page - mem_map) + ARCH_PFN_OFFSET;
2829 }
2830 #elif defined(CONFIG_DISCONTIGMEM)
2831 struct page *pfn_to_page(unsigned long pfn)
2832 {
2833         int nid = arch_pfn_to_nid(pfn);
2834         return NODE_DATA(nid)->node_mem_map + arch_local_page_offset(pfn,nid);
2835 }
2836 unsigned long page_to_pfn(struct page *page)
2837 {
2838         struct pglist_data *pgdat = NODE_DATA(page_to_nid(page));
2839         return (page - pgdat->node_mem_map) + pgdat->node_start_pfn;
2840 }
2841 #elif defined(CONFIG_SPARSEMEM)
2842 struct page *pfn_to_page(unsigned long pfn)
2843 {
2844         return __section_mem_map_addr(__pfn_to_section(pfn)) + pfn;
2845 }
2846
2847 unsigned long page_to_pfn(struct page *page)
2848 {
2849         long section_id = page_to_section(page);
2850         return page - __section_mem_map_addr(__nr_to_section(section_id));
2851 }
2852 #endif /* CONFIG_FLATMEM/DISCONTIGMME/SPARSEMEM */
2853 EXPORT_SYMBOL(pfn_to_page);
2854 EXPORT_SYMBOL(page_to_pfn);
2855 #endif /* CONFIG_OUT_OF_LINE_PFN_TO_PAGE */