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