vserver 2.0 rc7
[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/module.h>
26 #include <linux/suspend.h>
27 #include <linux/pagevec.h>
28 #include <linux/blkdev.h>
29 #include <linux/slab.h>
30 #include <linux/notifier.h>
31 #include <linux/topology.h>
32 #include <linux/sysctl.h>
33 #include <linux/cpu.h>
34 #include <linux/cpuset.h>
35 #include <linux/nodemask.h>
36 #include <linux/vmalloc.h>
37 #include <linux/vs_limit.h>
38
39 #include <asm/tlbflush.h>
40 #include "internal.h"
41
42 /*
43  * MCD - HACK: Find somewhere to initialize this EARLY, or make this
44  * initializer cleaner
45  */
46 nodemask_t node_online_map = { { [0] = 1UL } };
47 EXPORT_SYMBOL(node_online_map);
48 nodemask_t node_possible_map = NODE_MASK_ALL;
49 EXPORT_SYMBOL(node_possible_map);
50 struct pglist_data *pgdat_list;
51 unsigned long totalram_pages;
52 unsigned long totalhigh_pages;
53 long nr_swap_pages;
54
55 /*
56  * results with 256, 32 in the lowmem_reserve sysctl:
57  *      1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
58  *      1G machine -> (16M dma, 784M normal, 224M high)
59  *      NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
60  *      HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
61  *      HIGHMEM allocation will (224M+784M)/256 of ram reserved in ZONE_DMA
62  */
63 int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES-1] = { 256, 32 };
64
65 EXPORT_SYMBOL(totalram_pages);
66 EXPORT_SYMBOL(nr_swap_pages);
67
68 /*
69  * Used by page_zone() to look up the address of the struct zone whose
70  * id is encoded in the upper bits of page->flags
71  */
72 struct zone *zone_table[1 << (ZONES_SHIFT + NODES_SHIFT)];
73 EXPORT_SYMBOL(zone_table);
74
75 static char *zone_names[MAX_NR_ZONES] = { "DMA", "Normal", "HighMem" };
76 int min_free_kbytes = 1024;
77
78 unsigned long __initdata nr_kernel_pages;
79 unsigned long __initdata nr_all_pages;
80
81 /*
82  * Temporary debugging check for pages not lying within a given zone.
83  */
84 static int bad_range(struct zone *zone, struct page *page)
85 {
86         if (page_to_pfn(page) >= zone->zone_start_pfn + zone->spanned_pages)
87                 return 1;
88         if (page_to_pfn(page) < zone->zone_start_pfn)
89                 return 1;
90 #ifdef CONFIG_HOLES_IN_ZONE
91         if (!pfn_valid(page_to_pfn(page)))
92                 return 1;
93 #endif
94         if (zone != page_zone(page))
95                 return 1;
96         return 0;
97 }
98
99 static void bad_page(const char *function, struct page *page)
100 {
101         printk(KERN_EMERG "Bad page state at %s (in process '%s', page %p)\n",
102                 function, current->comm, page);
103         printk(KERN_EMERG "flags:0x%0*lx mapping:%p mapcount:%d count:%d\n",
104                 (int)(2*sizeof(page_flags_t)), (unsigned long)page->flags,
105                 page->mapping, page_mapcount(page), page_count(page));
106         printk(KERN_EMERG "Backtrace:\n");
107         dump_stack();
108         printk(KERN_EMERG "Trying to fix it up, but a reboot is needed\n");
109         page->flags &= ~(1 << PG_private        |
110                         1 << PG_locked  |
111                         1 << PG_lru     |
112                         1 << PG_active  |
113                         1 << PG_dirty   |
114                         1 << PG_swapcache |
115                         1 << PG_writeback);
116         set_page_count(page, 0);
117         reset_page_mapcount(page);
118         page->mapping = NULL;
119         tainted |= TAINT_BAD_PAGE;
120 }
121
122 #ifndef CONFIG_HUGETLB_PAGE
123 #define prep_compound_page(page, order) do { } while (0)
124 #define destroy_compound_page(page, order) do { } while (0)
125 #else
126 /*
127  * Higher-order pages are called "compound pages".  They are structured thusly:
128  *
129  * The first PAGE_SIZE page is called the "head page".
130  *
131  * The remaining PAGE_SIZE pages are called "tail pages".
132  *
133  * All pages have PG_compound set.  All pages have their ->private pointing at
134  * the head page (even the head page has this).
135  *
136  * The first tail page's ->mapping, if non-zero, holds the address of the
137  * compound page's put_page() function.
138  *
139  * The order of the allocation is stored in the first tail page's ->index
140  * This is only for debug at present.  This usage means that zero-order pages
141  * may not be compound.
142  */
143 static void prep_compound_page(struct page *page, unsigned long order)
144 {
145         int i;
146         int nr_pages = 1 << order;
147
148         page[1].mapping = NULL;
149         page[1].index = order;
150         for (i = 0; i < nr_pages; i++) {
151                 struct page *p = page + i;
152
153                 SetPageCompound(p);
154                 p->private = (unsigned long)page;
155         }
156 }
157
158 static void destroy_compound_page(struct page *page, unsigned long order)
159 {
160         int i;
161         int nr_pages = 1 << order;
162
163         if (!PageCompound(page))
164                 return;
165
166         if (page[1].index != order)
167                 bad_page(__FUNCTION__, page);
168
169         for (i = 0; i < nr_pages; i++) {
170                 struct page *p = page + i;
171
172                 if (!PageCompound(p))
173                         bad_page(__FUNCTION__, page);
174                 if (p->private != (unsigned long)page)
175                         bad_page(__FUNCTION__, page);
176                 ClearPageCompound(p);
177         }
178 }
179 #endif          /* CONFIG_HUGETLB_PAGE */
180
181 /*
182  * function for dealing with page's order in buddy system.
183  * zone->lock is already acquired when we use these.
184  * So, we don't need atomic page->flags operations here.
185  */
186 static inline unsigned long page_order(struct page *page) {
187         return page->private;
188 }
189
190 static inline void set_page_order(struct page *page, int order) {
191         page->private = order;
192         __SetPagePrivate(page);
193 }
194
195 static inline void rmv_page_order(struct page *page)
196 {
197         __ClearPagePrivate(page);
198         page->private = 0;
199 }
200
201 /*
202  * Locate the struct page for both the matching buddy in our
203  * pair (buddy1) and the combined O(n+1) page they form (page).
204  *
205  * 1) Any buddy B1 will have an order O twin B2 which satisfies
206  * the following equation:
207  *     B2 = B1 ^ (1 << O)
208  * For example, if the starting buddy (buddy2) is #8 its order
209  * 1 buddy is #10:
210  *     B2 = 8 ^ (1 << 1) = 8 ^ 2 = 10
211  *
212  * 2) Any buddy B will have an order O+1 parent P which
213  * satisfies the following equation:
214  *     P = B & ~(1 << O)
215  *
216  * Assumption: *_mem_map is contigious at least up to MAX_ORDER
217  */
218 static inline struct page *
219 __page_find_buddy(struct page *page, unsigned long page_idx, unsigned int order)
220 {
221         unsigned long buddy_idx = page_idx ^ (1 << order);
222
223         return page + (buddy_idx - page_idx);
224 }
225
226 static inline unsigned long
227 __find_combined_index(unsigned long page_idx, unsigned int order)
228 {
229         return (page_idx & ~(1 << order));
230 }
231
232 /*
233  * This function checks whether a page is free && is the buddy
234  * we can do coalesce a page and its buddy if
235  * (a) the buddy is free &&
236  * (b) the buddy is on the buddy system &&
237  * (c) a page and its buddy have the same order.
238  * for recording page's order, we use page->private and PG_private.
239  *
240  */
241 static inline int page_is_buddy(struct page *page, int order)
242 {
243        if (PagePrivate(page)           &&
244            (page_order(page) == order) &&
245            !PageReserved(page)         &&
246             page_count(page) == 0)
247                return 1;
248        return 0;
249 }
250
251 /*
252  * Freeing function for a buddy system allocator.
253  *
254  * The concept of a buddy system is to maintain direct-mapped table
255  * (containing bit values) for memory blocks of various "orders".
256  * The bottom level table contains the map for the smallest allocatable
257  * units of memory (here, pages), and each level above it describes
258  * pairs of units from the levels below, hence, "buddies".
259  * At a high level, all that happens here is marking the table entry
260  * at the bottom level available, and propagating the changes upward
261  * as necessary, plus some accounting needed to play nicely with other
262  * parts of the VM system.
263  * At each level, we keep a list of pages, which are heads of continuous
264  * free pages of length of (1 << order) and marked with PG_Private.Page's
265  * order is recorded in page->private field.
266  * So when we are allocating or freeing one, we can derive the state of the
267  * other.  That is, if we allocate a small block, and both were   
268  * free, the remainder of the region must be split into blocks.   
269  * If a block is freed, and its buddy is also free, then this
270  * triggers coalescing into a block of larger size.            
271  *
272  * -- wli
273  */
274
275 static inline void __free_pages_bulk (struct page *page,
276                 struct zone *zone, unsigned int order)
277 {
278         unsigned long page_idx;
279         int order_size = 1 << order;
280
281         if (unlikely(order))
282                 destroy_compound_page(page, order);
283
284         page_idx = page_to_pfn(page) & ((1 << MAX_ORDER) - 1);
285
286         BUG_ON(page_idx & (order_size - 1));
287         BUG_ON(bad_range(zone, page));
288
289         zone->free_pages += order_size;
290         while (order < MAX_ORDER-1) {
291                 unsigned long combined_idx;
292                 struct free_area *area;
293                 struct page *buddy;
294
295                 combined_idx = __find_combined_index(page_idx, order);
296                 buddy = __page_find_buddy(page, page_idx, order);
297
298                 if (bad_range(zone, buddy))
299                         break;
300                 if (!page_is_buddy(buddy, order))
301                         break;          /* Move the buddy up one level. */
302                 list_del(&buddy->lru);
303                 area = zone->free_area + order;
304                 area->nr_free--;
305                 rmv_page_order(buddy);
306                 page = page + (combined_idx - page_idx);
307                 page_idx = combined_idx;
308                 order++;
309         }
310         set_page_order(page, order);
311         list_add(&page->lru, &zone->free_area[order].free_list);
312         zone->free_area[order].nr_free++;
313 }
314
315 static inline void free_pages_check(const char *function, struct page *page)
316 {
317         if (    page_mapcount(page) ||
318                 page->mapping != NULL ||
319                 page_count(page) != 0 ||
320                 (page->flags & (
321                         1 << PG_lru     |
322                         1 << PG_private |
323                         1 << PG_locked  |
324                         1 << PG_active  |
325                         1 << PG_reclaim |
326                         1 << PG_slab    |
327                         1 << PG_swapcache |
328                         1 << PG_writeback )))
329                 bad_page(function, page);
330         if (PageDirty(page))
331                 ClearPageDirty(page);
332 }
333
334 /*
335  * Frees a list of pages. 
336  * Assumes all pages on list are in same zone, and of same order.
337  * count is the number of pages to free, or 0 for all on the list.
338  *
339  * If the zone was previously in an "all pages pinned" state then look to
340  * see if this freeing clears that state.
341  *
342  * And clear the zone's pages_scanned counter, to hold off the "all pages are
343  * pinned" detection logic.
344  */
345 static int
346 free_pages_bulk(struct zone *zone, int count,
347                 struct list_head *list, unsigned int order)
348 {
349         unsigned long flags;
350         struct page *page = NULL;
351         int ret = 0;
352
353         spin_lock_irqsave(&zone->lock, flags);
354         zone->all_unreclaimable = 0;
355         zone->pages_scanned = 0;
356         while (!list_empty(list) && count--) {
357                 page = list_entry(list->prev, struct page, lru);
358                 /* have to delete it as __free_pages_bulk list manipulates */
359                 list_del(&page->lru);
360                 __free_pages_bulk(page, zone, order);
361                 ret++;
362         }
363         spin_unlock_irqrestore(&zone->lock, flags);
364         return ret;
365 }
366
367 void __free_pages_ok(struct page *page, unsigned int order)
368 {
369         LIST_HEAD(list);
370         int i;
371
372         arch_free_page(page, order);
373
374         mod_page_state(pgfree, 1 << order);
375
376 #ifndef CONFIG_MMU
377         if (order > 0)
378                 for (i = 1 ; i < (1 << order) ; ++i)
379                         __put_page(page + i);
380 #endif
381
382         for (i = 0 ; i < (1 << order) ; ++i)
383                 free_pages_check(__FUNCTION__, page + i);
384         list_add(&page->lru, &list);
385         kernel_map_pages(page, 1<<order, 0);
386         free_pages_bulk(page_zone(page), 1, &list, order);
387 }
388
389
390 /*
391  * The order of subdivision here is critical for the IO subsystem.
392  * Please do not alter this order without good reasons and regression
393  * testing. Specifically, as large blocks of memory are subdivided,
394  * the order in which smaller blocks are delivered depends on the order
395  * they're subdivided in this function. This is the primary factor
396  * influencing the order in which pages are delivered to the IO
397  * subsystem according to empirical testing, and this is also justified
398  * by considering the behavior of a buddy system containing a single
399  * large block of memory acted on by a series of small allocations.
400  * This behavior is a critical factor in sglist merging's success.
401  *
402  * -- wli
403  */
404 static inline struct page *
405 expand(struct zone *zone, struct page *page,
406         int low, int high, struct free_area *area)
407 {
408         unsigned long size = 1 << high;
409
410         while (high > low) {
411                 area--;
412                 high--;
413                 size >>= 1;
414                 BUG_ON(bad_range(zone, &page[size]));
415                 list_add(&page[size].lru, &area->free_list);
416                 area->nr_free++;
417                 set_page_order(&page[size], high);
418         }
419         return page;
420 }
421
422 void set_page_refs(struct page *page, int order)
423 {
424 #ifdef CONFIG_MMU
425         set_page_count(page, 1);
426 #else
427         int i;
428
429         /*
430          * We need to reference all the pages for this order, otherwise if
431          * anyone accesses one of the pages with (get/put) it will be freed.
432          * - eg: access_process_vm()
433          */
434         for (i = 0; i < (1 << order); i++)
435                 set_page_count(page + i, 1);
436 #endif /* CONFIG_MMU */
437 }
438
439 /*
440  * This page is about to be returned from the page allocator
441  */
442 static void prep_new_page(struct page *page, int order)
443 {
444         if (page->mapping || page_mapcount(page) ||
445             (page->flags & (
446                         1 << PG_private |
447                         1 << PG_locked  |
448                         1 << PG_lru     |
449                         1 << PG_active  |
450                         1 << PG_dirty   |
451                         1 << PG_reclaim |
452                         1 << PG_swapcache |
453                         1 << PG_writeback )))
454                 bad_page(__FUNCTION__, page);
455
456         page->flags &= ~(1 << PG_uptodate | 1 << PG_error |
457                         1 << PG_referenced | 1 << PG_arch_1 |
458                         1 << PG_checked | 1 << PG_mappedtodisk);
459         page->private = 0;
460         set_page_refs(page, order);
461         kernel_map_pages(page, 1 << order, 1);
462 }
463
464 /* 
465  * Do the hard work of removing an element from the buddy allocator.
466  * Call me with the zone->lock already held.
467  */
468 static struct page *__rmqueue(struct zone *zone, unsigned int order)
469 {
470         struct free_area * area;
471         unsigned int current_order;
472         struct page *page;
473
474         for (current_order = order; current_order < MAX_ORDER; ++current_order) {
475                 area = zone->free_area + current_order;
476                 if (list_empty(&area->free_list))
477                         continue;
478
479                 page = list_entry(area->free_list.next, struct page, lru);
480                 list_del(&page->lru);
481                 rmv_page_order(page);
482                 area->nr_free--;
483                 zone->free_pages -= 1UL << order;
484                 return expand(zone, page, order, current_order, area);
485         }
486
487         return NULL;
488 }
489
490 /* 
491  * Obtain a specified number of elements from the buddy allocator, all under
492  * a single hold of the lock, for efficiency.  Add them to the supplied list.
493  * Returns the number of new pages which were placed at *list.
494  */
495 static int rmqueue_bulk(struct zone *zone, unsigned int order, 
496                         unsigned long count, struct list_head *list)
497 {
498         unsigned long flags;
499         int i;
500         int allocated = 0;
501         struct page *page;
502         
503         spin_lock_irqsave(&zone->lock, flags);
504         for (i = 0; i < count; ++i) {
505                 page = __rmqueue(zone, order);
506                 if (page == NULL)
507                         break;
508                 allocated++;
509                 list_add_tail(&page->lru, list);
510         }
511         spin_unlock_irqrestore(&zone->lock, flags);
512         return allocated;
513 }
514
515 #if defined(CONFIG_PM) || defined(CONFIG_HOTPLUG_CPU)
516 static void __drain_pages(unsigned int cpu)
517 {
518         struct zone *zone;
519         int i;
520
521         for_each_zone(zone) {
522                 struct per_cpu_pageset *pset;
523
524                 pset = &zone->pageset[cpu];
525                 for (i = 0; i < ARRAY_SIZE(pset->pcp); i++) {
526                         struct per_cpu_pages *pcp;
527
528                         pcp = &pset->pcp[i];
529                         pcp->count -= free_pages_bulk(zone, pcp->count,
530                                                 &pcp->list, 0);
531                 }
532         }
533 }
534 #endif /* CONFIG_PM || CONFIG_HOTPLUG_CPU */
535
536 #ifdef CONFIG_PM
537
538 void mark_free_pages(struct zone *zone)
539 {
540         unsigned long zone_pfn, flags;
541         int order;
542         struct list_head *curr;
543
544         if (!zone->spanned_pages)
545                 return;
546
547         spin_lock_irqsave(&zone->lock, flags);
548         for (zone_pfn = 0; zone_pfn < zone->spanned_pages; ++zone_pfn)
549                 ClearPageNosaveFree(pfn_to_page(zone_pfn + zone->zone_start_pfn));
550
551         for (order = MAX_ORDER - 1; order >= 0; --order)
552                 list_for_each(curr, &zone->free_area[order].free_list) {
553                         unsigned long start_pfn, i;
554
555                         start_pfn = page_to_pfn(list_entry(curr, struct page, lru));
556
557                         for (i=0; i < (1<<order); i++)
558                                 SetPageNosaveFree(pfn_to_page(start_pfn+i));
559         }
560         spin_unlock_irqrestore(&zone->lock, flags);
561 }
562
563 /*
564  * Spill all of this CPU's per-cpu pages back into the buddy allocator.
565  */
566 void drain_local_pages(void)
567 {
568         unsigned long flags;
569
570         local_irq_save(flags);  
571         __drain_pages(smp_processor_id());
572         local_irq_restore(flags);       
573 }
574 #endif /* CONFIG_PM */
575
576 static void zone_statistics(struct zonelist *zonelist, struct zone *z)
577 {
578 #ifdef CONFIG_NUMA
579         unsigned long flags;
580         int cpu;
581         pg_data_t *pg = z->zone_pgdat;
582         pg_data_t *orig = zonelist->zones[0]->zone_pgdat;
583         struct per_cpu_pageset *p;
584
585         local_irq_save(flags);
586         cpu = smp_processor_id();
587         p = &z->pageset[cpu];
588         if (pg == orig) {
589                 z->pageset[cpu].numa_hit++;
590         } else {
591                 p->numa_miss++;
592                 zonelist->zones[0]->pageset[cpu].numa_foreign++;
593         }
594         if (pg == NODE_DATA(numa_node_id()))
595                 p->local_node++;
596         else
597                 p->other_node++;
598         local_irq_restore(flags);
599 #endif
600 }
601
602 /*
603  * Free a 0-order page
604  */
605 static void FASTCALL(free_hot_cold_page(struct page *page, int cold));
606 static void fastcall free_hot_cold_page(struct page *page, int cold)
607 {
608         struct zone *zone = page_zone(page);
609         struct per_cpu_pages *pcp;
610         unsigned long flags;
611
612         arch_free_page(page, 0);
613
614         kernel_map_pages(page, 1, 0);
615         inc_page_state(pgfree);
616         if (PageAnon(page))
617                 page->mapping = NULL;
618         free_pages_check(__FUNCTION__, page);
619         pcp = &zone->pageset[get_cpu()].pcp[cold];
620         local_irq_save(flags);
621         if (pcp->count >= pcp->high)
622                 pcp->count -= free_pages_bulk(zone, pcp->batch, &pcp->list, 0);
623         list_add(&page->lru, &pcp->list);
624         pcp->count++;
625         local_irq_restore(flags);
626         put_cpu();
627 }
628
629 void fastcall free_hot_page(struct page *page)
630 {
631         free_hot_cold_page(page, 0);
632 }
633         
634 void fastcall free_cold_page(struct page *page)
635 {
636         free_hot_cold_page(page, 1);
637 }
638
639 static inline void prep_zero_page(struct page *page, int order, unsigned int __nocast gfp_flags)
640 {
641         int i;
642
643         BUG_ON((gfp_flags & (__GFP_WAIT | __GFP_HIGHMEM)) == __GFP_HIGHMEM);
644         for(i = 0; i < (1 << order); i++)
645                 clear_highpage(page + i);
646 }
647
648 /*
649  * Really, prep_compound_page() should be called from __rmqueue_bulk().  But
650  * we cheat by calling it from here, in the order > 0 path.  Saves a branch
651  * or two.
652  */
653 static struct page *
654 buffered_rmqueue(struct zone *zone, int order, unsigned int __nocast gfp_flags)
655 {
656         unsigned long flags;
657         struct page *page = NULL;
658         int cold = !!(gfp_flags & __GFP_COLD);
659
660         if (order == 0) {
661                 struct per_cpu_pages *pcp;
662
663                 pcp = &zone->pageset[get_cpu()].pcp[cold];
664                 local_irq_save(flags);
665                 if (pcp->count <= pcp->low)
666                         pcp->count += rmqueue_bulk(zone, 0,
667                                                 pcp->batch, &pcp->list);
668                 if (pcp->count) {
669                         page = list_entry(pcp->list.next, struct page, lru);
670                         list_del(&page->lru);
671                         pcp->count--;
672                 }
673                 local_irq_restore(flags);
674                 put_cpu();
675         }
676
677         if (page == NULL) {
678                 spin_lock_irqsave(&zone->lock, flags);
679                 page = __rmqueue(zone, order);
680                 spin_unlock_irqrestore(&zone->lock, flags);
681         }
682
683         if (page != NULL) {
684                 BUG_ON(bad_range(zone, page));
685                 mod_page_state_zone(zone, pgalloc, 1 << order);
686                 prep_new_page(page, order);
687
688                 if (gfp_flags & __GFP_ZERO)
689                         prep_zero_page(page, order, gfp_flags);
690
691                 if (order && (gfp_flags & __GFP_COMP))
692                         prep_compound_page(page, order);
693         }
694         return page;
695 }
696
697 /*
698  * Return 1 if free pages are above 'mark'. This takes into account the order
699  * of the allocation.
700  */
701 int zone_watermark_ok(struct zone *z, int order, unsigned long mark,
702                       int classzone_idx, int can_try_harder, int gfp_high)
703 {
704         /* free_pages my go negative - that's OK */
705         long min = mark, free_pages = z->free_pages - (1 << order) + 1;
706         int o;
707
708         if (gfp_high)
709                 min -= min / 2;
710         if (can_try_harder)
711                 min -= min / 4;
712
713         if (free_pages <= min + z->lowmem_reserve[classzone_idx])
714                 return 0;
715         for (o = 0; o < order; o++) {
716                 /* At the next order, this order's pages become unavailable */
717                 free_pages -= z->free_area[o].nr_free << o;
718
719                 /* Require fewer higher order pages to be free */
720                 min >>= 1;
721
722                 if (free_pages <= min)
723                         return 0;
724         }
725         return 1;
726 }
727
728 /*
729  * This is the 'heart' of the zoned buddy allocator.
730  */
731 struct page * fastcall
732 __alloc_pages(unsigned int __nocast gfp_mask, unsigned int order,
733                 struct zonelist *zonelist)
734 {
735         const int wait = gfp_mask & __GFP_WAIT;
736         struct zone **zones, *z;
737         struct page *page;
738         struct reclaim_state reclaim_state;
739         struct task_struct *p = current;
740         int i;
741         int classzone_idx;
742         int do_retry;
743         int can_try_harder;
744         int did_some_progress;
745
746         might_sleep_if(wait);
747
748         /*
749          * The caller may dip into page reserves a bit more if the caller
750          * cannot run direct reclaim, or is the caller has realtime scheduling
751          * policy
752          */
753         can_try_harder = (unlikely(rt_task(p)) && !in_interrupt()) || !wait;
754
755         zones = zonelist->zones;  /* the list of zones suitable for gfp_mask */
756
757         if (unlikely(zones[0] == NULL)) {
758                 /* Should this ever happen?? */
759                 return NULL;
760         }
761
762         classzone_idx = zone_idx(zones[0]);
763
764  restart:
765         /* Go through the zonelist once, looking for a zone with enough free */
766         for (i = 0; (z = zones[i]) != NULL; i++) {
767
768                 if (!zone_watermark_ok(z, order, z->pages_low,
769                                        classzone_idx, 0, 0))
770                         continue;
771
772                 if (!cpuset_zone_allowed(z))
773                         continue;
774
775                 page = buffered_rmqueue(z, order, gfp_mask);
776                 if (page)
777                         goto got_pg;
778         }
779
780         for (i = 0; (z = zones[i]) != NULL; i++)
781                 wakeup_kswapd(z, order);
782
783         /*
784          * Go through the zonelist again. Let __GFP_HIGH and allocations
785          * coming from realtime tasks to go deeper into reserves
786          *
787          * This is the last chance, in general, before the goto nopage.
788          * Ignore cpuset if GFP_ATOMIC (!wait) rather than fail alloc.
789          */
790         for (i = 0; (z = zones[i]) != NULL; i++) {
791                 if (!zone_watermark_ok(z, order, z->pages_min,
792                                        classzone_idx, can_try_harder,
793                                        gfp_mask & __GFP_HIGH))
794                         continue;
795
796                 if (wait && !cpuset_zone_allowed(z))
797                         continue;
798
799                 page = buffered_rmqueue(z, order, gfp_mask);
800                 if (page)
801                         goto got_pg;
802         }
803
804         /* This allocation should allow future memory freeing. */
805
806         if (((p->flags & PF_MEMALLOC) || unlikely(test_thread_flag(TIF_MEMDIE)))
807                         && !in_interrupt()) {
808                 if (!(gfp_mask & __GFP_NOMEMALLOC)) {
809                         /* go through the zonelist yet again, ignoring mins */
810                         for (i = 0; (z = zones[i]) != NULL; i++) {
811                                 if (!cpuset_zone_allowed(z))
812                                         continue;
813                                 page = buffered_rmqueue(z, order, gfp_mask);
814                                 if (page)
815                                         goto got_pg;
816                         }
817                 }
818                 goto nopage;
819         }
820
821         /* Atomic allocations - we can't balance anything */
822         if (!wait)
823                 goto nopage;
824
825 rebalance:
826         cond_resched();
827
828         /* We now go into synchronous reclaim */
829         p->flags |= PF_MEMALLOC;
830         reclaim_state.reclaimed_slab = 0;
831         p->reclaim_state = &reclaim_state;
832
833         did_some_progress = try_to_free_pages(zones, gfp_mask, order);
834
835         p->reclaim_state = NULL;
836         p->flags &= ~PF_MEMALLOC;
837
838         cond_resched();
839
840         if (likely(did_some_progress)) {
841                 /*
842                  * Go through the zonelist yet one more time, keep
843                  * very high watermark here, this is only to catch
844                  * a parallel oom killing, we must fail if we're still
845                  * under heavy pressure.
846                  */
847                 for (i = 0; (z = zones[i]) != NULL; i++) {
848                         if (!zone_watermark_ok(z, order, z->pages_min,
849                                                classzone_idx, can_try_harder,
850                                                gfp_mask & __GFP_HIGH))
851                                 continue;
852
853                         if (!cpuset_zone_allowed(z))
854                                 continue;
855
856                         page = buffered_rmqueue(z, order, gfp_mask);
857                         if (page)
858                                 goto got_pg;
859                 }
860         } else if ((gfp_mask & __GFP_FS) && !(gfp_mask & __GFP_NORETRY)) {
861                 /*
862                  * Go through the zonelist yet one more time, keep
863                  * very high watermark here, this is only to catch
864                  * a parallel oom killing, we must fail if we're still
865                  * under heavy pressure.
866                  */
867                 for (i = 0; (z = zones[i]) != NULL; i++) {
868                         if (!zone_watermark_ok(z, order, z->pages_high,
869                                                classzone_idx, 0, 0))
870                                 continue;
871
872                         if (!cpuset_zone_allowed(z))
873                                 continue;
874
875                         page = buffered_rmqueue(z, order, gfp_mask);
876                         if (page)
877                                 goto got_pg;
878                 }
879
880                 out_of_memory(gfp_mask);
881                 goto restart;
882         }
883
884         /*
885          * Don't let big-order allocations loop unless the caller explicitly
886          * requests that.  Wait for some write requests to complete then retry.
887          *
888          * In this implementation, __GFP_REPEAT means __GFP_NOFAIL for order
889          * <= 3, but that may not be true in other implementations.
890          */
891         do_retry = 0;
892         if (!(gfp_mask & __GFP_NORETRY)) {
893                 if ((order <= 3) || (gfp_mask & __GFP_REPEAT))
894                         do_retry = 1;
895                 if (gfp_mask & __GFP_NOFAIL)
896                         do_retry = 1;
897         }
898         if (do_retry) {
899                 blk_congestion_wait(WRITE, HZ/50);
900                 goto rebalance;
901         }
902
903 nopage:
904         if (!(gfp_mask & __GFP_NOWARN) && printk_ratelimit()) {
905                 printk(KERN_WARNING "%s: page allocation failure."
906                         " order:%d, mode:0x%x\n",
907                         p->comm, order, gfp_mask);
908                 dump_stack();
909         }
910         return NULL;
911 got_pg:
912         zone_statistics(zonelist, z);
913         return page;
914 }
915
916 EXPORT_SYMBOL(__alloc_pages);
917
918 /*
919  * Common helper functions.
920  */
921 fastcall unsigned long __get_free_pages(unsigned int __nocast gfp_mask, unsigned int order)
922 {
923         struct page * page;
924         page = alloc_pages(gfp_mask, order);
925         if (!page)
926                 return 0;
927         return (unsigned long) page_address(page);
928 }
929
930 EXPORT_SYMBOL(__get_free_pages);
931
932 fastcall unsigned long get_zeroed_page(unsigned int __nocast gfp_mask)
933 {
934         struct page * page;
935
936         /*
937          * get_zeroed_page() returns a 32-bit address, which cannot represent
938          * a highmem page
939          */
940         BUG_ON(gfp_mask & __GFP_HIGHMEM);
941
942         page = alloc_pages(gfp_mask | __GFP_ZERO, 0);
943         if (page)
944                 return (unsigned long) page_address(page);
945         return 0;
946 }
947
948 EXPORT_SYMBOL(get_zeroed_page);
949
950 void __pagevec_free(struct pagevec *pvec)
951 {
952         int i = pagevec_count(pvec);
953
954         while (--i >= 0)
955                 free_hot_cold_page(pvec->pages[i], pvec->cold);
956 }
957
958 fastcall void __free_pages(struct page *page, unsigned int order)
959 {
960         if (!PageReserved(page) && put_page_testzero(page)) {
961                 if (order == 0)
962                         free_hot_page(page);
963                 else
964                         __free_pages_ok(page, order);
965         }
966 }
967
968 EXPORT_SYMBOL(__free_pages);
969
970 fastcall void free_pages(unsigned long addr, unsigned int order)
971 {
972         if (addr != 0) {
973                 BUG_ON(!virt_addr_valid((void *)addr));
974                 __free_pages(virt_to_page((void *)addr), order);
975         }
976 }
977
978 EXPORT_SYMBOL(free_pages);
979
980 /*
981  * Total amount of free (allocatable) RAM:
982  */
983 unsigned int nr_free_pages(void)
984 {
985         unsigned int sum = 0;
986         struct zone *zone;
987
988         for_each_zone(zone)
989                 sum += zone->free_pages;
990
991         return sum;
992 }
993
994 EXPORT_SYMBOL(nr_free_pages);
995
996 #ifdef CONFIG_NUMA
997 unsigned int nr_free_pages_pgdat(pg_data_t *pgdat)
998 {
999         unsigned int i, sum = 0;
1000
1001         for (i = 0; i < MAX_NR_ZONES; i++)
1002                 sum += pgdat->node_zones[i].free_pages;
1003
1004         return sum;
1005 }
1006 #endif
1007
1008 static unsigned int nr_free_zone_pages(int offset)
1009 {
1010         pg_data_t *pgdat;
1011         unsigned int sum = 0;
1012
1013         for_each_pgdat(pgdat) {
1014                 struct zonelist *zonelist = pgdat->node_zonelists + offset;
1015                 struct zone **zonep = zonelist->zones;
1016                 struct zone *zone;
1017
1018                 for (zone = *zonep++; zone; zone = *zonep++) {
1019                         unsigned long size = zone->present_pages;
1020                         unsigned long high = zone->pages_high;
1021                         if (size > high)
1022                                 sum += size - high;
1023                 }
1024         }
1025
1026         return sum;
1027 }
1028
1029 /*
1030  * Amount of free RAM allocatable within ZONE_DMA and ZONE_NORMAL
1031  */
1032 unsigned int nr_free_buffer_pages(void)
1033 {
1034         return nr_free_zone_pages(GFP_USER & GFP_ZONEMASK);
1035 }
1036
1037 /*
1038  * Amount of free RAM allocatable within all zones
1039  */
1040 unsigned int nr_free_pagecache_pages(void)
1041 {
1042         return nr_free_zone_pages(GFP_HIGHUSER & GFP_ZONEMASK);
1043 }
1044
1045 #ifdef CONFIG_HIGHMEM
1046 unsigned int nr_free_highpages (void)
1047 {
1048         pg_data_t *pgdat;
1049         unsigned int pages = 0;
1050
1051         for_each_pgdat(pgdat)
1052                 pages += pgdat->node_zones[ZONE_HIGHMEM].free_pages;
1053
1054         return pages;
1055 }
1056 #endif
1057
1058 #ifdef CONFIG_NUMA
1059 static void show_node(struct zone *zone)
1060 {
1061         printk("Node %d ", zone->zone_pgdat->node_id);
1062 }
1063 #else
1064 #define show_node(zone) do { } while (0)
1065 #endif
1066
1067 /*
1068  * Accumulate the page_state information across all CPUs.
1069  * The result is unavoidably approximate - it can change
1070  * during and after execution of this function.
1071  */
1072 static DEFINE_PER_CPU(struct page_state, page_states) = {0};
1073
1074 atomic_t nr_pagecache = ATOMIC_INIT(0);
1075 EXPORT_SYMBOL(nr_pagecache);
1076 #ifdef CONFIG_SMP
1077 DEFINE_PER_CPU(long, nr_pagecache_local) = 0;
1078 #endif
1079
1080 void __get_page_state(struct page_state *ret, int nr)
1081 {
1082         int cpu = 0;
1083
1084         memset(ret, 0, sizeof(*ret));
1085
1086         cpu = first_cpu(cpu_online_map);
1087         while (cpu < NR_CPUS) {
1088                 unsigned long *in, *out, off;
1089
1090                 in = (unsigned long *)&per_cpu(page_states, cpu);
1091
1092                 cpu = next_cpu(cpu, cpu_online_map);
1093
1094                 if (cpu < NR_CPUS)
1095                         prefetch(&per_cpu(page_states, cpu));
1096
1097                 out = (unsigned long *)ret;
1098                 for (off = 0; off < nr; off++)
1099                         *out++ += *in++;
1100         }
1101 }
1102
1103 void get_page_state(struct page_state *ret)
1104 {
1105         int nr;
1106
1107         nr = offsetof(struct page_state, GET_PAGE_STATE_LAST);
1108         nr /= sizeof(unsigned long);
1109
1110         __get_page_state(ret, nr + 1);
1111 }
1112
1113 void get_full_page_state(struct page_state *ret)
1114 {
1115         __get_page_state(ret, sizeof(*ret) / sizeof(unsigned long));
1116 }
1117
1118 unsigned long __read_page_state(unsigned offset)
1119 {
1120         unsigned long ret = 0;
1121         int cpu;
1122
1123         for_each_online_cpu(cpu) {
1124                 unsigned long in;
1125
1126                 in = (unsigned long)&per_cpu(page_states, cpu) + offset;
1127                 ret += *((unsigned long *)in);
1128         }
1129         return ret;
1130 }
1131
1132 void __mod_page_state(unsigned offset, unsigned long delta)
1133 {
1134         unsigned long flags;
1135         void* ptr;
1136
1137         local_irq_save(flags);
1138         ptr = &__get_cpu_var(page_states);
1139         *(unsigned long*)(ptr + offset) += delta;
1140         local_irq_restore(flags);
1141 }
1142
1143 EXPORT_SYMBOL(__mod_page_state);
1144
1145 void __get_zone_counts(unsigned long *active, unsigned long *inactive,
1146                         unsigned long *free, struct pglist_data *pgdat)
1147 {
1148         struct zone *zones = pgdat->node_zones;
1149         int i;
1150
1151         *active = 0;
1152         *inactive = 0;
1153         *free = 0;
1154         for (i = 0; i < MAX_NR_ZONES; i++) {
1155                 *active += zones[i].nr_active;
1156                 *inactive += zones[i].nr_inactive;
1157                 *free += zones[i].free_pages;
1158         }
1159 }
1160
1161 void get_zone_counts(unsigned long *active,
1162                 unsigned long *inactive, unsigned long *free)
1163 {
1164         struct pglist_data *pgdat;
1165
1166         *active = 0;
1167         *inactive = 0;
1168         *free = 0;
1169         for_each_pgdat(pgdat) {
1170                 unsigned long l, m, n;
1171                 __get_zone_counts(&l, &m, &n, pgdat);
1172                 *active += l;
1173                 *inactive += m;
1174                 *free += n;
1175         }
1176 }
1177
1178 void si_meminfo(struct sysinfo *val)
1179 {
1180         val->totalram = totalram_pages;
1181         val->sharedram = 0;
1182         val->freeram = nr_free_pages();
1183         val->bufferram = nr_blockdev_pages();
1184 #ifdef CONFIG_HIGHMEM
1185         val->totalhigh = totalhigh_pages;
1186         val->freehigh = nr_free_highpages();
1187 #else
1188         val->totalhigh = 0;
1189         val->freehigh = 0;
1190 #endif
1191         val->mem_unit = PAGE_SIZE;
1192         if (vx_flags(VXF_VIRT_MEM, 0))
1193                 vx_vsi_meminfo(val);
1194 }
1195
1196 EXPORT_SYMBOL(si_meminfo);
1197
1198 #ifdef CONFIG_NUMA
1199 void si_meminfo_node(struct sysinfo *val, int nid)
1200 {
1201         pg_data_t *pgdat = NODE_DATA(nid);
1202
1203         val->totalram = pgdat->node_present_pages;
1204         val->freeram = nr_free_pages_pgdat(pgdat);
1205         val->totalhigh = pgdat->node_zones[ZONE_HIGHMEM].present_pages;
1206         val->freehigh = pgdat->node_zones[ZONE_HIGHMEM].free_pages;
1207         val->mem_unit = PAGE_SIZE;
1208 }
1209 #endif
1210
1211 #define K(x) ((x) << (PAGE_SHIFT-10))
1212
1213 /*
1214  * Show free area list (used inside shift_scroll-lock stuff)
1215  * We also calculate the percentage fragmentation. We do this by counting the
1216  * memory on each free list with the exception of the first item on the list.
1217  */
1218 void show_free_areas(void)
1219 {
1220         struct page_state ps;
1221         int cpu, temperature;
1222         unsigned long active;
1223         unsigned long inactive;
1224         unsigned long free;
1225         struct zone *zone;
1226
1227         for_each_zone(zone) {
1228                 show_node(zone);
1229                 printk("%s per-cpu:", zone->name);
1230
1231                 if (!zone->present_pages) {
1232                         printk(" empty\n");
1233                         continue;
1234                 } else
1235                         printk("\n");
1236
1237                 for (cpu = 0; cpu < NR_CPUS; ++cpu) {
1238                         struct per_cpu_pageset *pageset;
1239
1240                         if (!cpu_possible(cpu))
1241                                 continue;
1242
1243                         pageset = zone->pageset + cpu;
1244
1245                         for (temperature = 0; temperature < 2; temperature++)
1246                                 printk("cpu %d %s: low %d, high %d, batch %d\n",
1247                                         cpu,
1248                                         temperature ? "cold" : "hot",
1249                                         pageset->pcp[temperature].low,
1250                                         pageset->pcp[temperature].high,
1251                                         pageset->pcp[temperature].batch);
1252                 }
1253         }
1254
1255         get_page_state(&ps);
1256         get_zone_counts(&active, &inactive, &free);
1257
1258         printk("\nFree pages: %11ukB (%ukB HighMem)\n",
1259                 K(nr_free_pages()),
1260                 K(nr_free_highpages()));
1261
1262         printk("Active:%lu inactive:%lu dirty:%lu writeback:%lu "
1263                 "unstable:%lu free:%u slab:%lu mapped:%lu pagetables:%lu\n",
1264                 active,
1265                 inactive,
1266                 ps.nr_dirty,
1267                 ps.nr_writeback,
1268                 ps.nr_unstable,
1269                 nr_free_pages(),
1270                 ps.nr_slab,
1271                 ps.nr_mapped,
1272                 ps.nr_page_table_pages);
1273
1274         for_each_zone(zone) {
1275                 int i;
1276
1277                 show_node(zone);
1278                 printk("%s"
1279                         " free:%lukB"
1280                         " min:%lukB"
1281                         " low:%lukB"
1282                         " high:%lukB"
1283                         " active:%lukB"
1284                         " inactive:%lukB"
1285                         " present:%lukB"
1286                         " pages_scanned:%lu"
1287                         " all_unreclaimable? %s"
1288                         "\n",
1289                         zone->name,
1290                         K(zone->free_pages),
1291                         K(zone->pages_min),
1292                         K(zone->pages_low),
1293                         K(zone->pages_high),
1294                         K(zone->nr_active),
1295                         K(zone->nr_inactive),
1296                         K(zone->present_pages),
1297                         zone->pages_scanned,
1298                         (zone->all_unreclaimable ? "yes" : "no")
1299                         );
1300                 printk("lowmem_reserve[]:");
1301                 for (i = 0; i < MAX_NR_ZONES; i++)
1302                         printk(" %lu", zone->lowmem_reserve[i]);
1303                 printk("\n");
1304         }
1305
1306         for_each_zone(zone) {
1307                 unsigned long nr, flags, order, total = 0;
1308
1309                 show_node(zone);
1310                 printk("%s: ", zone->name);
1311                 if (!zone->present_pages) {
1312                         printk("empty\n");
1313                         continue;
1314                 }
1315
1316                 spin_lock_irqsave(&zone->lock, flags);
1317                 for (order = 0; order < MAX_ORDER; order++) {
1318                         nr = zone->free_area[order].nr_free;
1319                         total += nr << order;
1320                         printk("%lu*%lukB ", nr, K(1UL) << order);
1321                 }
1322                 spin_unlock_irqrestore(&zone->lock, flags);
1323                 printk("= %lukB\n", K(total));
1324         }
1325
1326         show_swap_cache_info();
1327 }
1328
1329 /*
1330  * Builds allocation fallback zone lists.
1331  */
1332 static int __init build_zonelists_node(pg_data_t *pgdat, struct zonelist *zonelist, int j, int k)
1333 {
1334         switch (k) {
1335                 struct zone *zone;
1336         default:
1337                 BUG();
1338         case ZONE_HIGHMEM:
1339                 zone = pgdat->node_zones + ZONE_HIGHMEM;
1340                 if (zone->present_pages) {
1341 #ifndef CONFIG_HIGHMEM
1342                         BUG();
1343 #endif
1344                         zonelist->zones[j++] = zone;
1345                 }
1346         case ZONE_NORMAL:
1347                 zone = pgdat->node_zones + ZONE_NORMAL;
1348                 if (zone->present_pages)
1349                         zonelist->zones[j++] = zone;
1350         case ZONE_DMA:
1351                 zone = pgdat->node_zones + ZONE_DMA;
1352                 if (zone->present_pages)
1353                         zonelist->zones[j++] = zone;
1354         }
1355
1356         return j;
1357 }
1358
1359 #ifdef CONFIG_NUMA
1360 #define MAX_NODE_LOAD (num_online_nodes())
1361 static int __initdata node_load[MAX_NUMNODES];
1362 /**
1363  * find_next_best_node - find the next node that should appear in a given node's fallback list
1364  * @node: node whose fallback list we're appending
1365  * @used_node_mask: nodemask_t of already used nodes
1366  *
1367  * We use a number of factors to determine which is the next node that should
1368  * appear on a given node's fallback list.  The node should not have appeared
1369  * already in @node's fallback list, and it should be the next closest node
1370  * according to the distance array (which contains arbitrary distance values
1371  * from each node to each node in the system), and should also prefer nodes
1372  * with no CPUs, since presumably they'll have very little allocation pressure
1373  * on them otherwise.
1374  * It returns -1 if no node is found.
1375  */
1376 static int __init find_next_best_node(int node, nodemask_t *used_node_mask)
1377 {
1378         int i, n, val;
1379         int min_val = INT_MAX;
1380         int best_node = -1;
1381
1382         for_each_online_node(i) {
1383                 cpumask_t tmp;
1384
1385                 /* Start from local node */
1386                 n = (node+i) % num_online_nodes();
1387
1388                 /* Don't want a node to appear more than once */
1389                 if (node_isset(n, *used_node_mask))
1390                         continue;
1391
1392                 /* Use the local node if we haven't already */
1393                 if (!node_isset(node, *used_node_mask)) {
1394                         best_node = node;
1395                         break;
1396                 }
1397
1398                 /* Use the distance array to find the distance */
1399                 val = node_distance(node, n);
1400
1401                 /* Give preference to headless and unused nodes */
1402                 tmp = node_to_cpumask(n);
1403                 if (!cpus_empty(tmp))
1404                         val += PENALTY_FOR_NODE_WITH_CPUS;
1405
1406                 /* Slight preference for less loaded node */
1407                 val *= (MAX_NODE_LOAD*MAX_NUMNODES);
1408                 val += node_load[n];
1409
1410                 if (val < min_val) {
1411                         min_val = val;
1412                         best_node = n;
1413                 }
1414         }
1415
1416         if (best_node >= 0)
1417                 node_set(best_node, *used_node_mask);
1418
1419         return best_node;
1420 }
1421
1422 static void __init build_zonelists(pg_data_t *pgdat)
1423 {
1424         int i, j, k, node, local_node;
1425         int prev_node, load;
1426         struct zonelist *zonelist;
1427         nodemask_t used_mask;
1428
1429         /* initialize zonelists */
1430         for (i = 0; i < GFP_ZONETYPES; i++) {
1431                 zonelist = pgdat->node_zonelists + i;
1432                 zonelist->zones[0] = NULL;
1433         }
1434
1435         /* NUMA-aware ordering of nodes */
1436         local_node = pgdat->node_id;
1437         load = num_online_nodes();
1438         prev_node = local_node;
1439         nodes_clear(used_mask);
1440         while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
1441                 /*
1442                  * We don't want to pressure a particular node.
1443                  * So adding penalty to the first node in same
1444                  * distance group to make it round-robin.
1445                  */
1446                 if (node_distance(local_node, node) !=
1447                                 node_distance(local_node, prev_node))
1448                         node_load[node] += load;
1449                 prev_node = node;
1450                 load--;
1451                 for (i = 0; i < GFP_ZONETYPES; i++) {
1452                         zonelist = pgdat->node_zonelists + i;
1453                         for (j = 0; zonelist->zones[j] != NULL; j++);
1454
1455                         k = ZONE_NORMAL;
1456                         if (i & __GFP_HIGHMEM)
1457                                 k = ZONE_HIGHMEM;
1458                         if (i & __GFP_DMA)
1459                                 k = ZONE_DMA;
1460
1461                         j = build_zonelists_node(NODE_DATA(node), zonelist, j, k);
1462                         zonelist->zones[j] = NULL;
1463                 }
1464         }
1465 }
1466
1467 #else   /* CONFIG_NUMA */
1468
1469 static void __init build_zonelists(pg_data_t *pgdat)
1470 {
1471         int i, j, k, node, local_node;
1472
1473         local_node = pgdat->node_id;
1474         for (i = 0; i < GFP_ZONETYPES; i++) {
1475                 struct zonelist *zonelist;
1476
1477                 zonelist = pgdat->node_zonelists + i;
1478
1479                 j = 0;
1480                 k = ZONE_NORMAL;
1481                 if (i & __GFP_HIGHMEM)
1482                         k = ZONE_HIGHMEM;
1483                 if (i & __GFP_DMA)
1484                         k = ZONE_DMA;
1485
1486                 j = build_zonelists_node(pgdat, zonelist, j, k);
1487                 /*
1488                  * Now we build the zonelist so that it contains the zones
1489                  * of all the other nodes.
1490                  * We don't want to pressure a particular node, so when
1491                  * building the zones for node N, we make sure that the
1492                  * zones coming right after the local ones are those from
1493                  * node N+1 (modulo N)
1494                  */
1495                 for (node = local_node + 1; node < MAX_NUMNODES; node++) {
1496                         if (!node_online(node))
1497                                 continue;
1498                         j = build_zonelists_node(NODE_DATA(node), zonelist, j, k);
1499                 }
1500                 for (node = 0; node < local_node; node++) {
1501                         if (!node_online(node))
1502                                 continue;
1503                         j = build_zonelists_node(NODE_DATA(node), zonelist, j, k);
1504                 }
1505
1506                 zonelist->zones[j] = NULL;
1507         }
1508 }
1509
1510 #endif  /* CONFIG_NUMA */
1511
1512 void __init build_all_zonelists(void)
1513 {
1514         int i;
1515
1516         for_each_online_node(i)
1517                 build_zonelists(NODE_DATA(i));
1518         printk("Built %i zonelists\n", num_online_nodes());
1519         cpuset_init_current_mems_allowed();
1520 }
1521
1522 /*
1523  * Helper functions to size the waitqueue hash table.
1524  * Essentially these want to choose hash table sizes sufficiently
1525  * large so that collisions trying to wait on pages are rare.
1526  * But in fact, the number of active page waitqueues on typical
1527  * systems is ridiculously low, less than 200. So this is even
1528  * conservative, even though it seems large.
1529  *
1530  * The constant PAGES_PER_WAITQUEUE specifies the ratio of pages to
1531  * waitqueues, i.e. the size of the waitq table given the number of pages.
1532  */
1533 #define PAGES_PER_WAITQUEUE     256
1534
1535 static inline unsigned long wait_table_size(unsigned long pages)
1536 {
1537         unsigned long size = 1;
1538
1539         pages /= PAGES_PER_WAITQUEUE;
1540
1541         while (size < pages)
1542                 size <<= 1;
1543
1544         /*
1545          * Once we have dozens or even hundreds of threads sleeping
1546          * on IO we've got bigger problems than wait queue collision.
1547          * Limit the size of the wait table to a reasonable size.
1548          */
1549         size = min(size, 4096UL);
1550
1551         return max(size, 4UL);
1552 }
1553
1554 /*
1555  * This is an integer logarithm so that shifts can be used later
1556  * to extract the more random high bits from the multiplicative
1557  * hash function before the remainder is taken.
1558  */
1559 static inline unsigned long wait_table_bits(unsigned long size)
1560 {
1561         return ffz(~size);
1562 }
1563
1564 #define LONG_ALIGN(x) (((x)+(sizeof(long))-1)&~((sizeof(long))-1))
1565
1566 static void __init calculate_zone_totalpages(struct pglist_data *pgdat,
1567                 unsigned long *zones_size, unsigned long *zholes_size)
1568 {
1569         unsigned long realtotalpages, totalpages = 0;
1570         int i;
1571
1572         for (i = 0; i < MAX_NR_ZONES; i++)
1573                 totalpages += zones_size[i];
1574         pgdat->node_spanned_pages = totalpages;
1575
1576         realtotalpages = totalpages;
1577         if (zholes_size)
1578                 for (i = 0; i < MAX_NR_ZONES; i++)
1579                         realtotalpages -= zholes_size[i];
1580         pgdat->node_present_pages = realtotalpages;
1581         printk(KERN_DEBUG "On node %d totalpages: %lu\n", pgdat->node_id, realtotalpages);
1582 }
1583
1584
1585 /*
1586  * Initially all pages are reserved - free ones are freed
1587  * up by free_all_bootmem() once the early boot process is
1588  * done. Non-atomic initialization, single-pass.
1589  */
1590 void __init memmap_init_zone(unsigned long size, int nid, unsigned long zone,
1591                 unsigned long start_pfn)
1592 {
1593         struct page *start = pfn_to_page(start_pfn);
1594         struct page *page;
1595
1596         for (page = start; page < (start + size); page++) {
1597                 set_page_zone(page, NODEZONE(nid, zone));
1598                 set_page_count(page, 0);
1599                 reset_page_mapcount(page);
1600                 SetPageReserved(page);
1601                 INIT_LIST_HEAD(&page->lru);
1602 #ifdef WANT_PAGE_VIRTUAL
1603                 /* The shift won't overflow because ZONE_NORMAL is below 4G. */
1604                 if (!is_highmem_idx(zone))
1605                         set_page_address(page, __va(start_pfn << PAGE_SHIFT));
1606 #endif
1607                 start_pfn++;
1608         }
1609 }
1610
1611 void zone_init_free_lists(struct pglist_data *pgdat, struct zone *zone,
1612                                 unsigned long size)
1613 {
1614         int order;
1615         for (order = 0; order < MAX_ORDER ; order++) {
1616                 INIT_LIST_HEAD(&zone->free_area[order].free_list);
1617                 zone->free_area[order].nr_free = 0;
1618         }
1619 }
1620
1621 #ifndef __HAVE_ARCH_MEMMAP_INIT
1622 #define memmap_init(size, nid, zone, start_pfn) \
1623         memmap_init_zone((size), (nid), (zone), (start_pfn))
1624 #endif
1625
1626 /*
1627  * Set up the zone data structures:
1628  *   - mark all pages reserved
1629  *   - mark all memory queues empty
1630  *   - clear the memory bitmaps
1631  */
1632 static void __init free_area_init_core(struct pglist_data *pgdat,
1633                 unsigned long *zones_size, unsigned long *zholes_size)
1634 {
1635         unsigned long i, j;
1636         const unsigned long zone_required_alignment = 1UL << (MAX_ORDER-1);
1637         int cpu, nid = pgdat->node_id;
1638         unsigned long zone_start_pfn = pgdat->node_start_pfn;
1639
1640         pgdat->nr_zones = 0;
1641         init_waitqueue_head(&pgdat->kswapd_wait);
1642         pgdat->kswapd_max_order = 0;
1643         
1644         for (j = 0; j < MAX_NR_ZONES; j++) {
1645                 struct zone *zone = pgdat->node_zones + j;
1646                 unsigned long size, realsize;
1647                 unsigned long batch;
1648
1649                 zone_table[NODEZONE(nid, j)] = zone;
1650                 realsize = size = zones_size[j];
1651                 if (zholes_size)
1652                         realsize -= zholes_size[j];
1653
1654                 if (j == ZONE_DMA || j == ZONE_NORMAL)
1655                         nr_kernel_pages += realsize;
1656                 nr_all_pages += realsize;
1657
1658                 zone->spanned_pages = size;
1659                 zone->present_pages = realsize;
1660                 zone->name = zone_names[j];
1661                 spin_lock_init(&zone->lock);
1662                 spin_lock_init(&zone->lru_lock);
1663                 zone->zone_pgdat = pgdat;
1664                 zone->free_pages = 0;
1665
1666                 zone->temp_priority = zone->prev_priority = DEF_PRIORITY;
1667
1668                 /*
1669                  * The per-cpu-pages pools are set to around 1000th of the
1670                  * size of the zone.  But no more than 1/4 of a meg - there's
1671                  * no point in going beyond the size of L2 cache.
1672                  *
1673                  * OK, so we don't know how big the cache is.  So guess.
1674                  */
1675                 batch = zone->present_pages / 1024;
1676                 if (batch * PAGE_SIZE > 256 * 1024)
1677                         batch = (256 * 1024) / PAGE_SIZE;
1678                 batch /= 4;             /* We effectively *= 4 below */
1679                 if (batch < 1)
1680                         batch = 1;
1681
1682                 /*
1683                  * Clamp the batch to a 2^n - 1 value. Having a power
1684                  * of 2 value was found to be more likely to have
1685                  * suboptimal cache aliasing properties in some cases.
1686                  *
1687                  * For example if 2 tasks are alternately allocating
1688                  * batches of pages, one task can end up with a lot
1689                  * of pages of one half of the possible page colors
1690                  * and the other with pages of the other colors.
1691                  */
1692                 batch = (1 << fls(batch + batch/2)) - 1;
1693
1694                 for (cpu = 0; cpu < NR_CPUS; cpu++) {
1695                         struct per_cpu_pages *pcp;
1696
1697                         pcp = &zone->pageset[cpu].pcp[0];       /* hot */
1698                         pcp->count = 0;
1699                         pcp->low = 2 * batch;
1700                         pcp->high = 6 * batch;
1701                         pcp->batch = 1 * batch;
1702                         INIT_LIST_HEAD(&pcp->list);
1703
1704                         pcp = &zone->pageset[cpu].pcp[1];       /* cold */
1705                         pcp->count = 0;
1706                         pcp->low = 0;
1707                         pcp->high = 2 * batch;
1708                         pcp->batch = 1 * batch;
1709                         INIT_LIST_HEAD(&pcp->list);
1710                 }
1711                 printk(KERN_DEBUG "  %s zone: %lu pages, LIFO batch:%lu\n",
1712                                 zone_names[j], realsize, batch);
1713                 INIT_LIST_HEAD(&zone->active_list);
1714                 INIT_LIST_HEAD(&zone->inactive_list);
1715                 zone->nr_scan_active = 0;
1716                 zone->nr_scan_inactive = 0;
1717                 zone->nr_active = 0;
1718                 zone->nr_inactive = 0;
1719                 if (!size)
1720                         continue;
1721
1722                 /*
1723                  * The per-page waitqueue mechanism uses hashed waitqueues
1724                  * per zone.
1725                  */
1726                 zone->wait_table_size = wait_table_size(size);
1727                 zone->wait_table_bits =
1728                         wait_table_bits(zone->wait_table_size);
1729                 zone->wait_table = (wait_queue_head_t *)
1730                         alloc_bootmem_node(pgdat, zone->wait_table_size
1731                                                 * sizeof(wait_queue_head_t));
1732
1733                 for(i = 0; i < zone->wait_table_size; ++i)
1734                         init_waitqueue_head(zone->wait_table + i);
1735
1736                 pgdat->nr_zones = j+1;
1737
1738                 zone->zone_mem_map = pfn_to_page(zone_start_pfn);
1739                 zone->zone_start_pfn = zone_start_pfn;
1740
1741                 if ((zone_start_pfn) & (zone_required_alignment-1))
1742                         printk(KERN_CRIT "BUG: wrong zone alignment, it will crash\n");
1743
1744                 memmap_init(size, nid, j, zone_start_pfn);
1745
1746                 zone_start_pfn += size;
1747
1748                 zone_init_free_lists(pgdat, zone, zone->spanned_pages);
1749         }
1750 }
1751
1752 static void __init alloc_node_mem_map(struct pglist_data *pgdat)
1753 {
1754         unsigned long size;
1755
1756         /* Skip empty nodes */
1757         if (!pgdat->node_spanned_pages)
1758                 return;
1759
1760         /* ia64 gets its own node_mem_map, before this, without bootmem */
1761         if (!pgdat->node_mem_map) {
1762                 size = (pgdat->node_spanned_pages + 1) * sizeof(struct page);
1763                 pgdat->node_mem_map = alloc_bootmem_node(pgdat, size);
1764         }
1765 #ifndef CONFIG_DISCONTIGMEM
1766         /*
1767          * With no DISCONTIG, the global mem_map is just set as node 0's
1768          */
1769         if (pgdat == NODE_DATA(0))
1770                 mem_map = NODE_DATA(0)->node_mem_map;
1771 #endif
1772 }
1773
1774 void __init free_area_init_node(int nid, struct pglist_data *pgdat,
1775                 unsigned long *zones_size, unsigned long node_start_pfn,
1776                 unsigned long *zholes_size)
1777 {
1778         pgdat->node_id = nid;
1779         pgdat->node_start_pfn = node_start_pfn;
1780         calculate_zone_totalpages(pgdat, zones_size, zholes_size);
1781
1782         alloc_node_mem_map(pgdat);
1783
1784         free_area_init_core(pgdat, zones_size, zholes_size);
1785 }
1786
1787 #ifndef CONFIG_DISCONTIGMEM
1788 static bootmem_data_t contig_bootmem_data;
1789 struct pglist_data contig_page_data = { .bdata = &contig_bootmem_data };
1790
1791 EXPORT_SYMBOL(contig_page_data);
1792
1793 void __init free_area_init(unsigned long *zones_size)
1794 {
1795         free_area_init_node(0, &contig_page_data, zones_size,
1796                         __pa(PAGE_OFFSET) >> PAGE_SHIFT, NULL);
1797 }
1798 #endif
1799
1800 #ifdef CONFIG_PROC_FS
1801
1802 #include <linux/seq_file.h>
1803
1804 static void *frag_start(struct seq_file *m, loff_t *pos)
1805 {
1806         pg_data_t *pgdat;
1807         loff_t node = *pos;
1808
1809         for (pgdat = pgdat_list; pgdat && node; pgdat = pgdat->pgdat_next)
1810                 --node;
1811
1812         return pgdat;
1813 }
1814
1815 static void *frag_next(struct seq_file *m, void *arg, loff_t *pos)
1816 {
1817         pg_data_t *pgdat = (pg_data_t *)arg;
1818
1819         (*pos)++;
1820         return pgdat->pgdat_next;
1821 }
1822
1823 static void frag_stop(struct seq_file *m, void *arg)
1824 {
1825 }
1826
1827 /* 
1828  * This walks the free areas for each zone.
1829  */
1830 static int frag_show(struct seq_file *m, void *arg)
1831 {
1832         pg_data_t *pgdat = (pg_data_t *)arg;
1833         struct zone *zone;
1834         struct zone *node_zones = pgdat->node_zones;
1835         unsigned long flags;
1836         int order;
1837
1838         for (zone = node_zones; zone - node_zones < MAX_NR_ZONES; ++zone) {
1839                 if (!zone->present_pages)
1840                         continue;
1841
1842                 spin_lock_irqsave(&zone->lock, flags);
1843                 seq_printf(m, "Node %d, zone %8s ", pgdat->node_id, zone->name);
1844                 for (order = 0; order < MAX_ORDER; ++order)
1845                         seq_printf(m, "%6lu ", zone->free_area[order].nr_free);
1846                 spin_unlock_irqrestore(&zone->lock, flags);
1847                 seq_putc(m, '\n');
1848         }
1849         return 0;
1850 }
1851
1852 struct seq_operations fragmentation_op = {
1853         .start  = frag_start,
1854         .next   = frag_next,
1855         .stop   = frag_stop,
1856         .show   = frag_show,
1857 };
1858
1859 static char *vmstat_text[] = {
1860         "nr_dirty",
1861         "nr_writeback",
1862         "nr_unstable",
1863         "nr_page_table_pages",
1864         "nr_mapped",
1865         "nr_slab",
1866
1867         "pgpgin",
1868         "pgpgout",
1869         "pswpin",
1870         "pswpout",
1871         "pgalloc_high",
1872
1873         "pgalloc_normal",
1874         "pgalloc_dma",
1875         "pgfree",
1876         "pgactivate",
1877         "pgdeactivate",
1878
1879         "pgfault",
1880         "pgmajfault",
1881         "pgrefill_high",
1882         "pgrefill_normal",
1883         "pgrefill_dma",
1884
1885         "pgsteal_high",
1886         "pgsteal_normal",
1887         "pgsteal_dma",
1888         "pgscan_kswapd_high",
1889         "pgscan_kswapd_normal",
1890
1891         "pgscan_kswapd_dma",
1892         "pgscan_direct_high",
1893         "pgscan_direct_normal",
1894         "pgscan_direct_dma",
1895         "pginodesteal",
1896
1897         "slabs_scanned",
1898         "kswapd_steal",
1899         "kswapd_inodesteal",
1900         "pageoutrun",
1901         "allocstall",
1902
1903         "pgrotated",
1904         "nr_bounce",
1905 };
1906
1907 static void *vmstat_start(struct seq_file *m, loff_t *pos)
1908 {
1909         struct page_state *ps;
1910
1911         if (*pos >= ARRAY_SIZE(vmstat_text))
1912                 return NULL;
1913
1914         ps = kmalloc(sizeof(*ps), GFP_KERNEL);
1915         m->private = ps;
1916         if (!ps)
1917                 return ERR_PTR(-ENOMEM);
1918         get_full_page_state(ps);
1919         ps->pgpgin /= 2;                /* sectors -> kbytes */
1920         ps->pgpgout /= 2;
1921         return (unsigned long *)ps + *pos;
1922 }
1923
1924 static void *vmstat_next(struct seq_file *m, void *arg, loff_t *pos)
1925 {
1926         (*pos)++;
1927         if (*pos >= ARRAY_SIZE(vmstat_text))
1928                 return NULL;
1929         return (unsigned long *)m->private + *pos;
1930 }
1931
1932 static int vmstat_show(struct seq_file *m, void *arg)
1933 {
1934         unsigned long *l = arg;
1935         unsigned long off = l - (unsigned long *)m->private;
1936
1937         seq_printf(m, "%s %lu\n", vmstat_text[off], *l);
1938         return 0;
1939 }
1940
1941 static void vmstat_stop(struct seq_file *m, void *arg)
1942 {
1943         kfree(m->private);
1944         m->private = NULL;
1945 }
1946
1947 struct seq_operations vmstat_op = {
1948         .start  = vmstat_start,
1949         .next   = vmstat_next,
1950         .stop   = vmstat_stop,
1951         .show   = vmstat_show,
1952 };
1953
1954 #endif /* CONFIG_PROC_FS */
1955
1956 #ifdef CONFIG_HOTPLUG_CPU
1957 static int page_alloc_cpu_notify(struct notifier_block *self,
1958                                  unsigned long action, void *hcpu)
1959 {
1960         int cpu = (unsigned long)hcpu;
1961         long *count;
1962         unsigned long *src, *dest;
1963
1964         if (action == CPU_DEAD) {
1965                 int i;
1966
1967                 /* Drain local pagecache count. */
1968                 count = &per_cpu(nr_pagecache_local, cpu);
1969                 atomic_add(*count, &nr_pagecache);
1970                 *count = 0;
1971                 local_irq_disable();
1972                 __drain_pages(cpu);
1973
1974                 /* Add dead cpu's page_states to our own. */
1975                 dest = (unsigned long *)&__get_cpu_var(page_states);
1976                 src = (unsigned long *)&per_cpu(page_states, cpu);
1977
1978                 for (i = 0; i < sizeof(struct page_state)/sizeof(unsigned long);
1979                                 i++) {
1980                         dest[i] += src[i];
1981                         src[i] = 0;
1982                 }
1983
1984                 local_irq_enable();
1985         }
1986         return NOTIFY_OK;
1987 }
1988 #endif /* CONFIG_HOTPLUG_CPU */
1989
1990 void __init page_alloc_init(void)
1991 {
1992         hotcpu_notifier(page_alloc_cpu_notify, 0);
1993 }
1994
1995 /*
1996  * setup_per_zone_lowmem_reserve - called whenever
1997  *      sysctl_lower_zone_reserve_ratio changes.  Ensures that each zone
1998  *      has a correct pages reserved value, so an adequate number of
1999  *      pages are left in the zone after a successful __alloc_pages().
2000  */
2001 static void setup_per_zone_lowmem_reserve(void)
2002 {
2003         struct pglist_data *pgdat;
2004         int j, idx;
2005
2006         for_each_pgdat(pgdat) {
2007                 for (j = 0; j < MAX_NR_ZONES; j++) {
2008                         struct zone *zone = pgdat->node_zones + j;
2009                         unsigned long present_pages = zone->present_pages;
2010
2011                         zone->lowmem_reserve[j] = 0;
2012
2013                         for (idx = j-1; idx >= 0; idx--) {
2014                                 struct zone *lower_zone;
2015
2016                                 if (sysctl_lowmem_reserve_ratio[idx] < 1)
2017                                         sysctl_lowmem_reserve_ratio[idx] = 1;
2018
2019                                 lower_zone = pgdat->node_zones + idx;
2020                                 lower_zone->lowmem_reserve[j] = present_pages /
2021                                         sysctl_lowmem_reserve_ratio[idx];
2022                                 present_pages += lower_zone->present_pages;
2023                         }
2024                 }
2025         }
2026 }
2027
2028 /*
2029  * setup_per_zone_pages_min - called when min_free_kbytes changes.  Ensures 
2030  *      that the pages_{min,low,high} values for each zone are set correctly 
2031  *      with respect to min_free_kbytes.
2032  */
2033 static void setup_per_zone_pages_min(void)
2034 {
2035         unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
2036         unsigned long lowmem_pages = 0;
2037         struct zone *zone;
2038         unsigned long flags;
2039
2040         /* Calculate total number of !ZONE_HIGHMEM pages */
2041         for_each_zone(zone) {
2042                 if (!is_highmem(zone))
2043                         lowmem_pages += zone->present_pages;
2044         }
2045
2046         for_each_zone(zone) {
2047                 spin_lock_irqsave(&zone->lru_lock, flags);
2048                 if (is_highmem(zone)) {
2049                         /*
2050                          * Often, highmem doesn't need to reserve any pages.
2051                          * But the pages_min/low/high values are also used for
2052                          * batching up page reclaim activity so we need a
2053                          * decent value here.
2054                          */
2055                         int min_pages;
2056
2057                         min_pages = zone->present_pages / 1024;
2058                         if (min_pages < SWAP_CLUSTER_MAX)
2059                                 min_pages = SWAP_CLUSTER_MAX;
2060                         if (min_pages > 128)
2061                                 min_pages = 128;
2062                         zone->pages_min = min_pages;
2063                 } else {
2064                         /* if it's a lowmem zone, reserve a number of pages 
2065                          * proportionate to the zone's size.
2066                          */
2067                         zone->pages_min = (pages_min * zone->present_pages) / 
2068                                            lowmem_pages;
2069                 }
2070
2071                 /*
2072                  * When interpreting these watermarks, just keep in mind that:
2073                  * zone->pages_min == (zone->pages_min * 4) / 4;
2074                  */
2075                 zone->pages_low   = (zone->pages_min * 5) / 4;
2076                 zone->pages_high  = (zone->pages_min * 6) / 4;
2077                 spin_unlock_irqrestore(&zone->lru_lock, flags);
2078         }
2079 }
2080
2081 /*
2082  * Initialise min_free_kbytes.
2083  *
2084  * For small machines we want it small (128k min).  For large machines
2085  * we want it large (64MB max).  But it is not linear, because network
2086  * bandwidth does not increase linearly with machine size.  We use
2087  *
2088  *      min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
2089  *      min_free_kbytes = sqrt(lowmem_kbytes * 16)
2090  *
2091  * which yields
2092  *
2093  * 16MB:        512k
2094  * 32MB:        724k
2095  * 64MB:        1024k
2096  * 128MB:       1448k
2097  * 256MB:       2048k
2098  * 512MB:       2896k
2099  * 1024MB:      4096k
2100  * 2048MB:      5792k
2101  * 4096MB:      8192k
2102  * 8192MB:      11584k
2103  * 16384MB:     16384k
2104  */
2105 static int __init init_per_zone_pages_min(void)
2106 {
2107         unsigned long lowmem_kbytes;
2108
2109         lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
2110
2111         min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
2112         if (min_free_kbytes < 128)
2113                 min_free_kbytes = 128;
2114         if (min_free_kbytes > 65536)
2115                 min_free_kbytes = 65536;
2116         setup_per_zone_pages_min();
2117         setup_per_zone_lowmem_reserve();
2118         return 0;
2119 }
2120 module_init(init_per_zone_pages_min)
2121
2122 /*
2123  * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so 
2124  *      that we can call two helper functions whenever min_free_kbytes
2125  *      changes.
2126  */
2127 int min_free_kbytes_sysctl_handler(ctl_table *table, int write, 
2128         struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
2129 {
2130         proc_dointvec(table, write, file, buffer, length, ppos);
2131         setup_per_zone_pages_min();
2132         return 0;
2133 }
2134
2135 /*
2136  * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
2137  *      proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
2138  *      whenever sysctl_lowmem_reserve_ratio changes.
2139  *
2140  * The reserve ratio obviously has absolutely no relation with the
2141  * pages_min watermarks. The lowmem reserve ratio can only make sense
2142  * if in function of the boot time zone sizes.
2143  */
2144 int lowmem_reserve_ratio_sysctl_handler(ctl_table *table, int write,
2145         struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
2146 {
2147         proc_dointvec_minmax(table, write, file, buffer, length, ppos);
2148         setup_per_zone_lowmem_reserve();
2149         return 0;
2150 }
2151
2152 __initdata int hashdist = HASHDIST_DEFAULT;
2153
2154 #ifdef CONFIG_NUMA
2155 static int __init set_hashdist(char *str)
2156 {
2157         if (!str)
2158                 return 0;
2159         hashdist = simple_strtoul(str, &str, 0);
2160         return 1;
2161 }
2162 __setup("hashdist=", set_hashdist);
2163 #endif
2164
2165 /*
2166  * allocate a large system hash table from bootmem
2167  * - it is assumed that the hash table must contain an exact power-of-2
2168  *   quantity of entries
2169  * - limit is the number of hash buckets, not the total allocation size
2170  */
2171 void *__init alloc_large_system_hash(const char *tablename,
2172                                      unsigned long bucketsize,
2173                                      unsigned long numentries,
2174                                      int scale,
2175                                      int flags,
2176                                      unsigned int *_hash_shift,
2177                                      unsigned int *_hash_mask,
2178                                      unsigned long limit)
2179 {
2180         unsigned long long max = limit;
2181         unsigned long log2qty, size;
2182         void *table = NULL;
2183
2184         /* allow the kernel cmdline to have a say */
2185         if (!numentries) {
2186                 /* round applicable memory size up to nearest megabyte */
2187                 numentries = (flags & HASH_HIGHMEM) ? nr_all_pages : nr_kernel_pages;
2188                 numentries += (1UL << (20 - PAGE_SHIFT)) - 1;
2189                 numentries >>= 20 - PAGE_SHIFT;
2190                 numentries <<= 20 - PAGE_SHIFT;
2191
2192                 /* limit to 1 bucket per 2^scale bytes of low memory */
2193                 if (scale > PAGE_SHIFT)
2194                         numentries >>= (scale - PAGE_SHIFT);
2195                 else
2196                         numentries <<= (PAGE_SHIFT - scale);
2197         }
2198         /* rounded up to nearest power of 2 in size */
2199         numentries = 1UL << (long_log2(numentries) + 1);
2200
2201         /* limit allocation size to 1/16 total memory by default */
2202         if (max == 0) {
2203                 max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
2204                 do_div(max, bucketsize);
2205         }
2206
2207         if (numentries > max)
2208                 numentries = max;
2209
2210         log2qty = long_log2(numentries);
2211
2212         do {
2213                 size = bucketsize << log2qty;
2214                 if (flags & HASH_EARLY)
2215                         table = alloc_bootmem(size);
2216                 else if (hashdist)
2217                         table = __vmalloc(size, GFP_ATOMIC, PAGE_KERNEL);
2218                 else {
2219                         unsigned long order;
2220                         for (order = 0; ((1UL << order) << PAGE_SHIFT) < size; order++)
2221                                 ;
2222                         table = (void*) __get_free_pages(GFP_ATOMIC, order);
2223                 }
2224         } while (!table && size > PAGE_SIZE && --log2qty);
2225
2226         if (!table)
2227                 panic("Failed to allocate %s hash table\n", tablename);
2228
2229         printk("%s hash table entries: %d (order: %d, %lu bytes)\n",
2230                tablename,
2231                (1U << log2qty),
2232                long_log2(size) - PAGE_SHIFT,
2233                size);
2234
2235         if (_hash_shift)
2236                 *_hash_shift = log2qty;
2237         if (_hash_mask)
2238                 *_hash_mask = (1 << log2qty) - 1;
2239
2240         return table;
2241 }