uml-patch-2.6.6-1
[linux-2.6.git] / mm / page_alloc.c
1 /*
2  *  linux/mm/page_alloc.c
3  *
4  *  Manages the free list, the system allocates free pages here.
5  *  Note that kmalloc() lives in slab.c
6  *
7  *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
8  *  Swap reorganised 29.12.95, Stephen Tweedie
9  *  Support of BIGMEM added by Gerhard Wichert, Siemens AG, July 1999
10  *  Reshaped it to be a zoned allocator, Ingo Molnar, Red Hat, 1999
11  *  Discontiguous memory support, Kanoj Sarcar, SGI, Nov 1999
12  *  Zone balancing, Kanoj Sarcar, SGI, Jan 2000
13  *  Per cpu hot/cold page lists, bulk allocation, Martin J. Bligh, Sept 2002
14  *          (lots of bits borrowed from Ingo Molnar & Andrew Morton)
15  */
16
17 #include <linux/config.h>
18 #include <linux/stddef.h>
19 #include <linux/mm.h>
20 #include <linux/swap.h>
21 #include <linux/interrupt.h>
22 #include <linux/pagemap.h>
23 #include <linux/bootmem.h>
24 #include <linux/compiler.h>
25 #include <linux/module.h>
26 #include <linux/suspend.h>
27 #include <linux/pagevec.h>
28 #include <linux/blkdev.h>
29 #include <linux/slab.h>
30 #include <linux/notifier.h>
31 #include <linux/topology.h>
32 #include <linux/sysctl.h>
33 #include <linux/cpu.h>
34
35 #include <asm/tlbflush.h>
36
37 DECLARE_BITMAP(node_online_map, MAX_NUMNODES);
38 struct pglist_data *pgdat_list;
39 unsigned long totalram_pages;
40 unsigned long totalhigh_pages;
41 int nr_swap_pages;
42 int numnodes = 1;
43 int sysctl_lower_zone_protection = 0;
44
45 EXPORT_SYMBOL(totalram_pages);
46 EXPORT_SYMBOL(nr_swap_pages);
47
48 /*
49  * Used by page_zone() to look up the address of the struct zone whose
50  * id is encoded in the upper bits of page->flags
51  */
52 struct zone *zone_table[1 << (ZONES_SHIFT + NODES_SHIFT)];
53 EXPORT_SYMBOL(zone_table);
54
55 static char *zone_names[MAX_NR_ZONES] = { "DMA", "Normal", "HighMem" };
56 int min_free_kbytes = 1024;
57
58 /*
59  * Temporary debugging check for pages not lying within a given zone.
60  */
61 static int bad_range(struct zone *zone, struct page *page)
62 {
63         if (page_to_pfn(page) >= zone->zone_start_pfn + zone->spanned_pages)
64                 return 1;
65         if (page_to_pfn(page) < zone->zone_start_pfn)
66                 return 1;
67         if (zone != page_zone(page))
68                 return 1;
69         return 0;
70 }
71
72 static void bad_page(const char *function, struct page *page)
73 {
74         printk(KERN_EMERG "Bad page state at %s (in process '%s', page %p)\n",
75                 function, current->comm, page);
76         printk(KERN_EMERG "flags:0x%08lx mapping:%p mapped:%d count:%d\n",
77                 (unsigned long)page->flags, page->mapping,
78                 page_mapped(page), page_count(page));
79         printk(KERN_EMERG "Backtrace:\n");
80         dump_stack();
81         printk(KERN_EMERG "Trying to fix it up, but a reboot is needed\n");
82         page->flags &= ~(1 << PG_private        |
83                         1 << PG_locked  |
84                         1 << PG_lru     |
85                         1 << PG_active  |
86                         1 << PG_dirty   |
87                         1 << PG_maplock |
88                         1 << PG_anon    |
89                         1 << PG_swapcache |
90                         1 << PG_writeback);
91         set_page_count(page, 0);
92         page->mapping = NULL;
93 }
94
95 #ifndef CONFIG_HUGETLB_PAGE
96 #define prep_compound_page(page, order) do { } while (0)
97 #define destroy_compound_page(page, order) do { } while (0)
98 #else
99 /*
100  * Higher-order pages are called "compound pages".  They are structured thusly:
101  *
102  * The first PAGE_SIZE page is called the "head page".
103  *
104  * The remaining PAGE_SIZE pages are called "tail pages".
105  *
106  * All pages have PG_compound set.  All pages have their ->private pointing at
107  * the head page (even the head page has this).
108  *
109  * The first tail page's ->mapping, if non-zero, holds the address of the
110  * compound page's put_page() function.
111  *
112  * The order of the allocation is stored in the first tail page's ->index
113  * This is only for debug at present.  This usage means that zero-order pages
114  * may not be compound.
115  */
116 static void prep_compound_page(struct page *page, unsigned long order)
117 {
118         int i;
119         int nr_pages = 1 << order;
120
121         page[1].mapping = 0;
122         page[1].index = order;
123         for (i = 0; i < nr_pages; i++) {
124                 struct page *p = page + i;
125
126                 SetPageCompound(p);
127                 p->private = (unsigned long)page;
128         }
129 }
130
131 static void destroy_compound_page(struct page *page, unsigned long order)
132 {
133         int i;
134         int nr_pages = 1 << order;
135
136         if (!PageCompound(page))
137                 return;
138
139         if (page[1].index != order)
140                 bad_page(__FUNCTION__, page);
141
142         for (i = 0; i < nr_pages; i++) {
143                 struct page *p = page + i;
144
145                 if (!PageCompound(p))
146                         bad_page(__FUNCTION__, page);
147                 if (p->private != (unsigned long)page)
148                         bad_page(__FUNCTION__, page);
149                 ClearPageCompound(p);
150         }
151 }
152 #endif          /* CONFIG_HUGETLB_PAGE */
153
154 /*
155  * Freeing function for a buddy system allocator.
156  *
157  * The concept of a buddy system is to maintain direct-mapped table
158  * (containing bit values) for memory blocks of various "orders".
159  * The bottom level table contains the map for the smallest allocatable
160  * units of memory (here, pages), and each level above it describes
161  * pairs of units from the levels below, hence, "buddies".
162  * At a high level, all that happens here is marking the table entry
163  * at the bottom level available, and propagating the changes upward
164  * as necessary, plus some accounting needed to play nicely with other
165  * parts of the VM system.
166  * At each level, we keep one bit for each pair of blocks, which
167  * is set to 1 iff only one of the pair is allocated.  So when we
168  * are allocating or freeing one, we can derive the state of the
169  * other.  That is, if we allocate a small block, and both were   
170  * free, the remainder of the region must be split into blocks.   
171  * If a block is freed, and its buddy is also free, then this
172  * triggers coalescing into a block of larger size.            
173  *
174  * -- wli
175  */
176
177 static inline void __free_pages_bulk (struct page *page, struct page *base,
178                 struct zone *zone, struct free_area *area, unsigned long mask,
179                 unsigned int order)
180 {
181         unsigned long page_idx, index;
182
183         if (order)
184                 destroy_compound_page(page, order);
185         page_idx = page - base;
186         if (page_idx & ~mask)
187                 BUG();
188         index = page_idx >> (1 + order);
189
190         zone->free_pages -= mask;
191         while (mask + (1 << (MAX_ORDER-1))) {
192                 struct page *buddy1, *buddy2;
193
194                 BUG_ON(area >= zone->free_area + MAX_ORDER);
195                 if (!__test_and_change_bit(index, area->map))
196                         /*
197                          * the buddy page is still allocated.
198                          */
199                         break;
200                 /*
201                  * Move the buddy up one level.
202                  * This code is taking advantage of the identity:
203                  *      -mask = 1+~mask
204                  */
205                 buddy1 = base + (page_idx ^ -mask);
206                 buddy2 = base + page_idx;
207                 BUG_ON(bad_range(zone, buddy1));
208                 BUG_ON(bad_range(zone, buddy2));
209                 list_del(&buddy1->lru);
210                 mask <<= 1;
211                 area++;
212                 index >>= 1;
213                 page_idx &= mask;
214         }
215         list_add(&(base + page_idx)->lru, &area->free_list);
216 }
217
218 static inline void free_pages_check(const char *function, struct page *page)
219 {
220         if (    page_mapped(page) ||
221                 page->mapping != NULL ||
222                 page_count(page) != 0 ||
223                 (page->flags & (
224                         1 << PG_lru     |
225                         1 << PG_private |
226                         1 << PG_locked  |
227                         1 << PG_active  |
228                         1 << PG_reclaim |
229                         1 << PG_slab    |
230                         1 << PG_maplock |
231                         1 << PG_anon    |
232                         1 << PG_swapcache |
233                         1 << PG_writeback )))
234                 bad_page(function, page);
235         if (PageDirty(page))
236                 ClearPageDirty(page);
237 }
238
239 /*
240  * Frees a list of pages. 
241  * Assumes all pages on list are in same zone, and of same order.
242  * count is the number of pages to free, or 0 for all on the list.
243  *
244  * If the zone was previously in an "all pages pinned" state then look to
245  * see if this freeing clears that state.
246  *
247  * And clear the zone's pages_scanned counter, to hold off the "all pages are
248  * pinned" detection logic.
249  */
250 static int
251 free_pages_bulk(struct zone *zone, int count,
252                 struct list_head *list, unsigned int order)
253 {
254         unsigned long mask, flags;
255         struct free_area *area;
256         struct page *base, *page = NULL;
257         int ret = 0;
258
259         mask = (~0UL) << order;
260         base = zone->zone_mem_map;
261         area = zone->free_area + order;
262         spin_lock_irqsave(&zone->lock, flags);
263         zone->all_unreclaimable = 0;
264         zone->pages_scanned = 0;
265         while (!list_empty(list) && count--) {
266                 page = list_entry(list->prev, struct page, lru);
267                 /* have to delete it as __free_pages_bulk list manipulates */
268                 list_del(&page->lru);
269                 __free_pages_bulk(page, base, zone, area, mask, order);
270                 ret++;
271         }
272         spin_unlock_irqrestore(&zone->lock, flags);
273         return ret;
274 }
275
276 void __free_pages_ok(struct page *page, unsigned int order)
277 {
278         LIST_HEAD(list);
279         int i;
280
281         arch_free_page(page, order);
282
283         mod_page_state(pgfree, 1 << order);
284         for (i = 0 ; i < (1 << order) ; ++i)
285                 free_pages_check(__FUNCTION__, page + i);
286         list_add(&page->lru, &list);
287         kernel_map_pages(page, 1<<order, 0);
288         free_pages_bulk(page_zone(page), 1, &list, order);
289 }
290
291 #define MARK_USED(index, order, area) \
292         __change_bit((index) >> (1+(order)), (area)->map)
293
294 static inline struct page *
295 expand(struct zone *zone, struct page *page,
296          unsigned long index, int low, int high, struct free_area *area)
297 {
298         unsigned long size = 1 << high;
299
300         while (high > low) {
301                 BUG_ON(bad_range(zone, page));
302                 area--;
303                 high--;
304                 size >>= 1;
305                 list_add(&page->lru, &area->free_list);
306                 MARK_USED(index, high, area);
307                 index += size;
308                 page += size;
309         }
310         return page;
311 }
312
313 static inline void set_page_refs(struct page *page, int order)
314 {
315 #ifdef CONFIG_MMU
316         set_page_count(page, 1);
317 #else
318         int i;
319
320         /*
321          * We need to reference all the pages for this order, otherwise if
322          * anyone accesses one of the pages with (get/put) it will be freed.
323          */
324         for (i = 0; i < (1 << order); i++)
325                 set_page_count(page+i, 1);
326 #endif /* CONFIG_MMU */
327 }
328
329 /*
330  * This page is about to be returned from the page allocator
331  */
332 static void prep_new_page(struct page *page, int order)
333 {
334         if (page->mapping || page_mapped(page) ||
335             (page->flags & (
336                         1 << PG_private |
337                         1 << PG_locked  |
338                         1 << PG_lru     |
339                         1 << PG_active  |
340                         1 << PG_dirty   |
341                         1 << PG_reclaim |
342                         1 << PG_maplock |
343                         1 << PG_anon    |
344                         1 << PG_swapcache |
345                         1 << PG_writeback )))
346                 bad_page(__FUNCTION__, page);
347
348         page->flags &= ~(1 << PG_uptodate | 1 << PG_error |
349                         1 << PG_referenced | 1 << PG_arch_1 |
350                         1 << PG_checked | 1 << PG_mappedtodisk);
351         page->private = 0;
352         set_page_refs(page, order);
353 }
354
355 /* 
356  * Do the hard work of removing an element from the buddy allocator.
357  * Call me with the zone->lock already held.
358  */
359 static struct page *__rmqueue(struct zone *zone, unsigned int order)
360 {
361         struct free_area * area;
362         unsigned int current_order;
363         struct page *page;
364         unsigned int index;
365
366         for (current_order = order; current_order < MAX_ORDER; ++current_order) {
367                 area = zone->free_area + current_order;
368                 if (list_empty(&area->free_list))
369                         continue;
370
371                 page = list_entry(area->free_list.next, struct page, lru);
372                 list_del(&page->lru);
373                 index = page - zone->zone_mem_map;
374                 if (current_order != MAX_ORDER-1)
375                         MARK_USED(index, current_order, area);
376                 zone->free_pages -= 1UL << order;
377                 return expand(zone, page, index, order, current_order, area);
378         }
379
380         return NULL;
381 }
382
383 /* 
384  * Obtain a specified number of elements from the buddy allocator, all under
385  * a single hold of the lock, for efficiency.  Add them to the supplied list.
386  * Returns the number of new pages which were placed at *list.
387  */
388 static int rmqueue_bulk(struct zone *zone, unsigned int order, 
389                         unsigned long count, struct list_head *list)
390 {
391         unsigned long flags;
392         int i;
393         int allocated = 0;
394         struct page *page;
395         
396         spin_lock_irqsave(&zone->lock, flags);
397         for (i = 0; i < count; ++i) {
398                 page = __rmqueue(zone, order);
399                 if (page == NULL)
400                         break;
401                 allocated++;
402                 list_add_tail(&page->lru, list);
403         }
404         spin_unlock_irqrestore(&zone->lock, flags);
405         return allocated;
406 }
407
408 #if defined(CONFIG_PM) || defined(CONFIG_HOTPLUG_CPU)
409 static void __drain_pages(unsigned int cpu)
410 {
411         struct zone *zone;
412         int i;
413
414         for_each_zone(zone) {
415                 struct per_cpu_pageset *pset;
416
417                 pset = &zone->pageset[cpu];
418                 for (i = 0; i < ARRAY_SIZE(pset->pcp); i++) {
419                         struct per_cpu_pages *pcp;
420
421                         pcp = &pset->pcp[i];
422                         pcp->count -= free_pages_bulk(zone, pcp->count,
423                                                 &pcp->list, 0);
424                 }
425         }
426 }
427 #endif /* CONFIG_PM || CONFIG_HOTPLUG_CPU */
428
429 #ifdef CONFIG_PM
430 int is_head_of_free_region(struct page *page)
431 {
432         struct zone *zone = page_zone(page);
433         unsigned long flags;
434         int order;
435         struct list_head *curr;
436
437         /*
438          * Should not matter as we need quiescent system for
439          * suspend anyway, but...
440          */
441         spin_lock_irqsave(&zone->lock, flags);
442         for (order = MAX_ORDER - 1; order >= 0; --order)
443                 list_for_each(curr, &zone->free_area[order].free_list)
444                         if (page == list_entry(curr, struct page, lru)) {
445                                 spin_unlock_irqrestore(&zone->lock, flags);
446                                 return 1 << order;
447                         }
448         spin_unlock_irqrestore(&zone->lock, flags);
449         return 0;
450 }
451
452 /*
453  * Spill all of this CPU's per-cpu pages back into the buddy allocator.
454  */
455 void drain_local_pages(void)
456 {
457         unsigned long flags;
458
459         local_irq_save(flags);  
460         __drain_pages(smp_processor_id());
461         local_irq_restore(flags);       
462 }
463 #endif /* CONFIG_PM */
464
465 /*
466  * Free a 0-order page
467  */
468 static void FASTCALL(free_hot_cold_page(struct page *page, int cold));
469 static void fastcall free_hot_cold_page(struct page *page, int cold)
470 {
471         struct zone *zone = page_zone(page);
472         struct per_cpu_pages *pcp;
473         unsigned long flags;
474
475         arch_free_page(page, 0);
476
477         kernel_map_pages(page, 1, 0);
478         inc_page_state(pgfree);
479         free_pages_check(__FUNCTION__, page);
480         pcp = &zone->pageset[get_cpu()].pcp[cold];
481         local_irq_save(flags);
482         if (pcp->count >= pcp->high)
483                 pcp->count -= free_pages_bulk(zone, pcp->batch, &pcp->list, 0);
484         list_add(&page->lru, &pcp->list);
485         pcp->count++;
486         local_irq_restore(flags);
487         put_cpu();
488 }
489
490 void fastcall free_hot_page(struct page *page)
491 {
492         free_hot_cold_page(page, 0);
493 }
494         
495 void fastcall free_cold_page(struct page *page)
496 {
497         free_hot_cold_page(page, 1);
498 }
499
500 /*
501  * Really, prep_compound_page() should be called from __rmqueue_bulk().  But
502  * we cheat by calling it from here, in the order > 0 path.  Saves a branch
503  * or two.
504  */
505
506 static struct page *
507 buffered_rmqueue(struct zone *zone, int order, int gfp_flags)
508 {
509         unsigned long flags;
510         struct page *page = NULL;
511         int cold = !!(gfp_flags & __GFP_COLD);
512
513         if (order == 0) {
514                 struct per_cpu_pages *pcp;
515
516                 pcp = &zone->pageset[get_cpu()].pcp[cold];
517                 local_irq_save(flags);
518                 if (pcp->count <= pcp->low)
519                         pcp->count += rmqueue_bulk(zone, 0,
520                                                 pcp->batch, &pcp->list);
521                 if (pcp->count) {
522                         page = list_entry(pcp->list.next, struct page, lru);
523                         list_del(&page->lru);
524                         pcp->count--;
525                 }
526                 local_irq_restore(flags);
527                 put_cpu();
528         }
529
530         if (page == NULL) {
531                 spin_lock_irqsave(&zone->lock, flags);
532                 page = __rmqueue(zone, order);
533                 spin_unlock_irqrestore(&zone->lock, flags);
534         }
535
536         if (page != NULL) {
537                 BUG_ON(bad_range(zone, page));
538                 mod_page_state_zone(zone, pgalloc, 1 << order);
539                 prep_new_page(page, order);
540                 if (order && (gfp_flags & __GFP_COMP))
541                         prep_compound_page(page, order);
542         }
543         return page;
544 }
545
546 /*
547  * This is the 'heart' of the zoned buddy allocator.
548  *
549  * Herein lies the mysterious "incremental min".  That's the
550  *
551  *      local_low = z->pages_low;
552  *      min += local_low;
553  *
554  * thing.  The intent here is to provide additional protection to low zones for
555  * allocation requests which _could_ use higher zones.  So a GFP_HIGHMEM
556  * request is not allowed to dip as deeply into the normal zone as a GFP_KERNEL
557  * request.  This preserves additional space in those lower zones for requests
558  * which really do need memory from those zones.  It means that on a decent
559  * sized machine, GFP_HIGHMEM and GFP_KERNEL requests basically leave the DMA
560  * zone untouched.
561  */
562 struct page * fastcall
563 __alloc_pages(unsigned int gfp_mask, unsigned int order,
564                 struct zonelist *zonelist)
565 {
566         const int wait = gfp_mask & __GFP_WAIT;
567         unsigned long min;
568         struct zone **zones;
569         struct page *page;
570         struct reclaim_state reclaim_state;
571         struct task_struct *p = current;
572         int i;
573         int alloc_type;
574         int do_retry;
575
576         might_sleep_if(wait);
577
578         zones = zonelist->zones;  /* the list of zones suitable for gfp_mask */
579         if (zones[0] == NULL)     /* no zones in the zonelist */
580                 return NULL;
581
582         alloc_type = zone_idx(zones[0]);
583
584         /* Go through the zonelist once, looking for a zone with enough free */
585         for (i = 0; zones[i] != NULL; i++) {
586                 struct zone *z = zones[i];
587
588                 min = (1<<order) + z->protection[alloc_type];
589
590                 /*
591                  * We let real-time tasks dip their real-time paws a little
592                  * deeper into reserves.
593                  */
594                 if (rt_task(p))
595                         min -= z->pages_low >> 1;
596
597                 if (z->free_pages >= min ||
598                                 (!wait && z->free_pages >= z->pages_high)) {
599                         page = buffered_rmqueue(z, order, gfp_mask);
600                         if (page)
601                                 goto got_pg;
602                 }
603         }
604
605         /* we're somewhat low on memory, failed to find what we needed */
606         for (i = 0; zones[i] != NULL; i++)
607                 wakeup_kswapd(zones[i]);
608
609         /* Go through the zonelist again, taking __GFP_HIGH into account */
610         for (i = 0; zones[i] != NULL; i++) {
611                 struct zone *z = zones[i];
612
613                 min = (1<<order) + z->protection[alloc_type];
614
615                 if (gfp_mask & __GFP_HIGH)
616                         min -= z->pages_low >> 2;
617                 if (rt_task(p))
618                         min -= z->pages_low >> 1;
619
620                 if (z->free_pages >= min ||
621                                 (!wait && z->free_pages >= z->pages_high)) {
622                         page = buffered_rmqueue(z, order, gfp_mask);
623                         if (page)
624                                 goto got_pg;
625                 }
626         }
627
628         /* here we're in the low on memory slow path */
629
630 rebalance:
631         if ((p->flags & (PF_MEMALLOC | PF_MEMDIE)) && !in_interrupt()) {
632                 /* go through the zonelist yet again, ignoring mins */
633                 for (i = 0; zones[i] != NULL; i++) {
634                         struct zone *z = zones[i];
635
636                         page = buffered_rmqueue(z, order, gfp_mask);
637                         if (page)
638                                 goto got_pg;
639                 }
640                 goto nopage;
641         }
642
643         /* Atomic allocations - we can't balance anything */
644         if (!wait)
645                 goto nopage;
646
647         p->flags |= PF_MEMALLOC;
648         reclaim_state.reclaimed_slab = 0;
649         p->reclaim_state = &reclaim_state;
650
651         try_to_free_pages(zones, gfp_mask, order);
652
653         p->reclaim_state = NULL;
654         p->flags &= ~PF_MEMALLOC;
655
656         /* go through the zonelist yet one more time */
657         for (i = 0; zones[i] != NULL; i++) {
658                 struct zone *z = zones[i];
659
660                 min = (1UL << order) + z->protection[alloc_type];
661
662                 if (z->free_pages >= min ||
663                                 (!wait && z->free_pages >= z->pages_high)) {
664                         page = buffered_rmqueue(z, order, gfp_mask);
665                         if (page)
666                                 goto got_pg;
667                 }
668         }
669
670         /*
671          * Don't let big-order allocations loop unless the caller explicitly
672          * requests that.  Wait for some write requests to complete then retry.
673          *
674          * In this implementation, __GFP_REPEAT means __GFP_NOFAIL, but that
675          * may not be true in other implementations.
676          */
677         do_retry = 0;
678         if (!(gfp_mask & __GFP_NORETRY)) {
679                 if ((order <= 3) || (gfp_mask & __GFP_REPEAT))
680                         do_retry = 1;
681                 if (gfp_mask & __GFP_NOFAIL)
682                         do_retry = 1;
683         }
684         if (do_retry) {
685                 blk_congestion_wait(WRITE, HZ/50);
686                 goto rebalance;
687         }
688
689 nopage:
690         if (!(gfp_mask & __GFP_NOWARN) && printk_ratelimit()) {
691                 printk(KERN_WARNING "%s: page allocation failure."
692                         " order:%d, mode:0x%x\n",
693                         p->comm, order, gfp_mask);
694                 dump_stack();
695         }
696         return NULL;
697 got_pg:
698         kernel_map_pages(page, 1 << order, 1);
699         return page;
700 }
701
702 EXPORT_SYMBOL(__alloc_pages);
703
704 #ifdef CONFIG_NUMA
705 /* Early boot: Everything is done by one cpu, but the data structures will be
706  * used by all cpus - spread them on all nodes.
707  */
708 static __init unsigned long get_boot_pages(unsigned int gfp_mask, unsigned int order)
709 {
710 static int nodenr;
711         int i = nodenr;
712         struct page *page;
713
714         for (;;) {
715                 if (i > nodenr + numnodes)
716                         return 0;
717                 if (node_present_pages(i%numnodes)) {
718                         struct zone **z;
719                         /* The node contains memory. Check that there is
720                          * memory in the intended zonelist.
721                          */
722                         z = NODE_DATA(i%numnodes)->node_zonelists[gfp_mask & GFP_ZONEMASK].zones;
723                         while (*z) {
724                                 if ( (*z)->free_pages > (1UL<<order))
725                                         goto found_node;
726                                 z++;
727                         }
728                 }
729                 i++;
730         }
731 found_node:
732         nodenr = i+1;
733         page = alloc_pages_node(i%numnodes, gfp_mask, order);
734         if (!page)
735                 return 0;
736         return (unsigned long) page_address(page);
737 }
738 #endif
739
740 /*
741  * Common helper functions.
742  */
743 fastcall unsigned long __get_free_pages(unsigned int gfp_mask, unsigned int order)
744 {
745         struct page * page;
746
747 #ifdef CONFIG_NUMA
748         if (unlikely(system_state == SYSTEM_BOOTING))
749                 return get_boot_pages(gfp_mask, order);
750 #endif
751         page = alloc_pages(gfp_mask, order);
752         if (!page)
753                 return 0;
754         return (unsigned long) page_address(page);
755 }
756
757 EXPORT_SYMBOL(__get_free_pages);
758
759 fastcall unsigned long get_zeroed_page(unsigned int gfp_mask)
760 {
761         struct page * page;
762
763         /*
764          * get_zeroed_page() returns a 32-bit address, which cannot represent
765          * a highmem page
766          */
767         BUG_ON(gfp_mask & __GFP_HIGHMEM);
768
769         page = alloc_pages(gfp_mask, 0);
770         if (page) {
771                 void *address = page_address(page);
772                 clear_page(address);
773                 return (unsigned long) address;
774         }
775         return 0;
776 }
777
778 EXPORT_SYMBOL(get_zeroed_page);
779
780 void __pagevec_free(struct pagevec *pvec)
781 {
782         int i = pagevec_count(pvec);
783
784         while (--i >= 0)
785                 free_hot_cold_page(pvec->pages[i], pvec->cold);
786 }
787
788 fastcall void __free_pages(struct page *page, unsigned int order)
789 {
790         if (!PageReserved(page) && put_page_testzero(page)) {
791                 if (order == 0)
792                         free_hot_page(page);
793                 else
794                         __free_pages_ok(page, order);
795         }
796 }
797
798 EXPORT_SYMBOL(__free_pages);
799
800 fastcall void free_pages(unsigned long addr, unsigned int order)
801 {
802         if (addr != 0) {
803                 BUG_ON(!virt_addr_valid(addr));
804                 __free_pages(virt_to_page(addr), order);
805         }
806 }
807
808 EXPORT_SYMBOL(free_pages);
809
810 /*
811  * Total amount of free (allocatable) RAM:
812  */
813 unsigned int nr_free_pages(void)
814 {
815         unsigned int sum = 0;
816         struct zone *zone;
817
818         for_each_zone(zone)
819                 sum += zone->free_pages;
820
821         return sum;
822 }
823
824 EXPORT_SYMBOL(nr_free_pages);
825
826 unsigned int nr_used_zone_pages(void)
827 {
828         unsigned int pages = 0;
829         struct zone *zone;
830
831         for_each_zone(zone)
832                 pages += zone->nr_active + zone->nr_inactive;
833
834         return pages;
835 }
836
837 #ifdef CONFIG_NUMA
838 unsigned int nr_free_pages_pgdat(pg_data_t *pgdat)
839 {
840         unsigned int i, sum = 0;
841
842         for (i = 0; i < MAX_NR_ZONES; i++)
843                 sum += pgdat->node_zones[i].free_pages;
844
845         return sum;
846 }
847 #endif
848
849 static unsigned int nr_free_zone_pages(int offset)
850 {
851         pg_data_t *pgdat;
852         unsigned int sum = 0;
853
854         for_each_pgdat(pgdat) {
855                 struct zonelist *zonelist = pgdat->node_zonelists + offset;
856                 struct zone **zonep = zonelist->zones;
857                 struct zone *zone;
858
859                 for (zone = *zonep++; zone; zone = *zonep++) {
860                         unsigned long size = zone->present_pages;
861                         unsigned long high = zone->pages_high;
862                         if (size > high)
863                                 sum += size - high;
864                 }
865         }
866
867         return sum;
868 }
869
870 /*
871  * Amount of free RAM allocatable within ZONE_DMA and ZONE_NORMAL
872  */
873 unsigned int nr_free_buffer_pages(void)
874 {
875         return nr_free_zone_pages(GFP_USER & GFP_ZONEMASK);
876 }
877
878 /*
879  * Amount of free RAM allocatable within all zones
880  */
881 unsigned int nr_free_pagecache_pages(void)
882 {
883         return nr_free_zone_pages(GFP_HIGHUSER & GFP_ZONEMASK);
884 }
885
886 #ifdef CONFIG_HIGHMEM
887 unsigned int nr_free_highpages (void)
888 {
889         pg_data_t *pgdat;
890         unsigned int pages = 0;
891
892         for_each_pgdat(pgdat)
893                 pages += pgdat->node_zones[ZONE_HIGHMEM].free_pages;
894
895         return pages;
896 }
897 #endif
898
899 #ifdef CONFIG_NUMA
900 static void show_node(struct zone *zone)
901 {
902         printk("Node %d ", zone->zone_pgdat->node_id);
903 }
904 #else
905 #define show_node(zone) do { } while (0)
906 #endif
907
908 /*
909  * Accumulate the page_state information across all CPUs.
910  * The result is unavoidably approximate - it can change
911  * during and after execution of this function.
912  */
913 DEFINE_PER_CPU(struct page_state, page_states) = {0};
914 EXPORT_PER_CPU_SYMBOL(page_states);
915
916 atomic_t nr_pagecache = ATOMIC_INIT(0);
917 EXPORT_SYMBOL(nr_pagecache);
918 #ifdef CONFIG_SMP
919 DEFINE_PER_CPU(long, nr_pagecache_local) = 0;
920 #endif
921
922 void __get_page_state(struct page_state *ret, int nr)
923 {
924         int cpu = 0;
925
926         memset(ret, 0, sizeof(*ret));
927         while (cpu < NR_CPUS) {
928                 unsigned long *in, *out, off;
929
930                 if (!cpu_possible(cpu)) {
931                         cpu++;
932                         continue;
933                 }
934
935                 in = (unsigned long *)&per_cpu(page_states, cpu);
936                 cpu++;
937                 if (cpu < NR_CPUS && cpu_possible(cpu))
938                         prefetch(&per_cpu(page_states, cpu));
939                 out = (unsigned long *)ret;
940                 for (off = 0; off < nr; off++)
941                         *out++ += *in++;
942         }
943 }
944
945 void get_page_state(struct page_state *ret)
946 {
947         int nr;
948
949         nr = offsetof(struct page_state, GET_PAGE_STATE_LAST);
950         nr /= sizeof(unsigned long);
951
952         __get_page_state(ret, nr + 1);
953 }
954
955 void get_full_page_state(struct page_state *ret)
956 {
957         __get_page_state(ret, sizeof(*ret) / sizeof(unsigned long));
958 }
959
960 void get_zone_counts(unsigned long *active,
961                 unsigned long *inactive, unsigned long *free)
962 {
963         struct zone *zone;
964
965         *active = 0;
966         *inactive = 0;
967         *free = 0;
968         for_each_zone(zone) {
969                 *active += zone->nr_active;
970                 *inactive += zone->nr_inactive;
971                 *free += zone->free_pages;
972         }
973 }
974
975 void si_meminfo(struct sysinfo *val)
976 {
977         val->totalram = totalram_pages;
978         val->sharedram = 0;
979         val->freeram = nr_free_pages();
980         val->bufferram = nr_blockdev_pages();
981 #ifdef CONFIG_HIGHMEM
982         val->totalhigh = totalhigh_pages;
983         val->freehigh = nr_free_highpages();
984 #else
985         val->totalhigh = 0;
986         val->freehigh = 0;
987 #endif
988         val->mem_unit = PAGE_SIZE;
989 }
990
991 EXPORT_SYMBOL(si_meminfo);
992
993 #ifdef CONFIG_NUMA
994 void si_meminfo_node(struct sysinfo *val, int nid)
995 {
996         pg_data_t *pgdat = NODE_DATA(nid);
997
998         val->totalram = pgdat->node_present_pages;
999         val->freeram = nr_free_pages_pgdat(pgdat);
1000         val->totalhigh = pgdat->node_zones[ZONE_HIGHMEM].present_pages;
1001         val->freehigh = pgdat->node_zones[ZONE_HIGHMEM].free_pages;
1002         val->mem_unit = PAGE_SIZE;
1003 }
1004 #endif
1005
1006 #define K(x) ((x) << (PAGE_SHIFT-10))
1007
1008 /*
1009  * Show free area list (used inside shift_scroll-lock stuff)
1010  * We also calculate the percentage fragmentation. We do this by counting the
1011  * memory on each free list with the exception of the first item on the list.
1012  */
1013 void show_free_areas(void)
1014 {
1015         struct page_state ps;
1016         int cpu, temperature;
1017         unsigned long active;
1018         unsigned long inactive;
1019         unsigned long free;
1020         struct zone *zone;
1021
1022         for_each_zone(zone) {
1023                 show_node(zone);
1024                 printk("%s per-cpu:", zone->name);
1025
1026                 if (!zone->present_pages) {
1027                         printk(" empty\n");
1028                         continue;
1029                 } else
1030                         printk("\n");
1031
1032                 for (cpu = 0; cpu < NR_CPUS; ++cpu) {
1033                         struct per_cpu_pageset *pageset;
1034
1035                         if (!cpu_possible(cpu))
1036                                 continue;
1037
1038                         pageset = zone->pageset + cpu;
1039
1040                         for (temperature = 0; temperature < 2; temperature++)
1041                                 printk("cpu %d %s: low %d, high %d, batch %d\n",
1042                                         cpu,
1043                                         temperature ? "cold" : "hot",
1044                                         pageset->pcp[temperature].low,
1045                                         pageset->pcp[temperature].high,
1046                                         pageset->pcp[temperature].batch);
1047                 }
1048         }
1049
1050         get_page_state(&ps);
1051         get_zone_counts(&active, &inactive, &free);
1052
1053         printk("\nFree pages: %11ukB (%ukB HighMem)\n",
1054                 K(nr_free_pages()),
1055                 K(nr_free_highpages()));
1056
1057         printk("Active:%lu inactive:%lu dirty:%lu writeback:%lu "
1058                 "unstable:%lu free:%u slab:%lu mapped:%lu pagetables:%lu\n",
1059                 active,
1060                 inactive,
1061                 ps.nr_dirty,
1062                 ps.nr_writeback,
1063                 ps.nr_unstable,
1064                 nr_free_pages(),
1065                 ps.nr_slab,
1066                 ps.nr_mapped,
1067                 ps.nr_page_table_pages);
1068
1069         for_each_zone(zone) {
1070                 int i;
1071
1072                 show_node(zone);
1073                 printk("%s"
1074                         " free:%lukB"
1075                         " min:%lukB"
1076                         " low:%lukB"
1077                         " high:%lukB"
1078                         " active:%lukB"
1079                         " inactive:%lukB"
1080                         " present:%lukB"
1081                         "\n",
1082                         zone->name,
1083                         K(zone->free_pages),
1084                         K(zone->pages_min),
1085                         K(zone->pages_low),
1086                         K(zone->pages_high),
1087                         K(zone->nr_active),
1088                         K(zone->nr_inactive),
1089                         K(zone->present_pages)
1090                         );
1091                 printk("protections[]:");
1092                 for (i = 0; i < MAX_NR_ZONES; i++)
1093                         printk(" %lu", zone->protection[i]);
1094                 printk("\n");
1095         }
1096
1097         for_each_zone(zone) {
1098                 struct list_head *elem;
1099                 unsigned long nr, flags, order, total = 0;
1100
1101                 show_node(zone);
1102                 printk("%s: ", zone->name);
1103                 if (!zone->present_pages) {
1104                         printk("empty\n");
1105                         continue;
1106                 }
1107
1108                 spin_lock_irqsave(&zone->lock, flags);
1109                 for (order = 0; order < MAX_ORDER; order++) {
1110                         nr = 0;
1111                         list_for_each(elem, &zone->free_area[order].free_list)
1112                                 ++nr;
1113                         total += nr << order;
1114                         printk("%lu*%lukB ", nr, K(1UL) << order);
1115                 }
1116                 spin_unlock_irqrestore(&zone->lock, flags);
1117                 printk("= %lukB\n", K(total));
1118         }
1119
1120         show_swap_cache_info();
1121 }
1122
1123 /*
1124  * Builds allocation fallback zone lists.
1125  */
1126 static int __init build_zonelists_node(pg_data_t *pgdat, struct zonelist *zonelist, int j, int k)
1127 {
1128         switch (k) {
1129                 struct zone *zone;
1130         default:
1131                 BUG();
1132         case ZONE_HIGHMEM:
1133                 zone = pgdat->node_zones + ZONE_HIGHMEM;
1134                 if (zone->present_pages) {
1135 #ifndef CONFIG_HIGHMEM
1136                         BUG();
1137 #endif
1138                         zonelist->zones[j++] = zone;
1139                 }
1140         case ZONE_NORMAL:
1141                 zone = pgdat->node_zones + ZONE_NORMAL;
1142                 if (zone->present_pages)
1143                         zonelist->zones[j++] = zone;
1144         case ZONE_DMA:
1145                 zone = pgdat->node_zones + ZONE_DMA;
1146                 if (zone->present_pages)
1147                         zonelist->zones[j++] = zone;
1148         }
1149
1150         return j;
1151 }
1152
1153 #ifdef CONFIG_NUMA
1154 #define MAX_NODE_LOAD (numnodes)
1155 static int __initdata node_load[MAX_NUMNODES];
1156 /**
1157  * find_next_best_node - find the next node that should appear in a given
1158  *    node's fallback list
1159  * @node: node whose fallback list we're appending
1160  * @used_node_mask: pointer to the bitmap of already used nodes
1161  *
1162  * We use a number of factors to determine which is the next node that should
1163  * appear on a given node's fallback list.  The node should not have appeared
1164  * already in @node's fallback list, and it should be the next closest node
1165  * according to the distance array (which contains arbitrary distance values
1166  * from each node to each node in the system), and should also prefer nodes
1167  * with no CPUs, since presumably they'll have very little allocation pressure
1168  * on them otherwise.
1169  * It returns -1 if no node is found.
1170  */
1171 static int __init find_next_best_node(int node, void *used_node_mask)
1172 {
1173         int i, n, val;
1174         int min_val = INT_MAX;
1175         int best_node = -1;
1176
1177         for (i = 0; i < numnodes; i++) {
1178                 cpumask_t tmp;
1179
1180                 /* Start from local node */
1181                 n = (node+i)%numnodes;
1182
1183                 /* Don't want a node to appear more than once */
1184                 if (test_bit(n, used_node_mask))
1185                         continue;
1186
1187                 /* Use the distance array to find the distance */
1188                 val = node_distance(node, n);
1189
1190                 /* Give preference to headless and unused nodes */
1191                 tmp = node_to_cpumask(n);
1192                 if (!cpus_empty(tmp))
1193                         val += PENALTY_FOR_NODE_WITH_CPUS;
1194
1195                 /* Slight preference for less loaded node */
1196                 val *= (MAX_NODE_LOAD*MAX_NUMNODES);
1197                 val += node_load[n];
1198
1199                 if (val < min_val) {
1200                         min_val = val;
1201                         best_node = n;
1202                 }
1203         }
1204
1205         if (best_node >= 0)
1206                 set_bit(best_node, used_node_mask);
1207
1208         return best_node;
1209 }
1210
1211 static void __init build_zonelists(pg_data_t *pgdat)
1212 {
1213         int i, j, k, node, local_node;
1214         int prev_node, load;
1215         struct zonelist *zonelist;
1216         DECLARE_BITMAP(used_mask, MAX_NUMNODES);
1217
1218         /* initialize zonelists */
1219         for (i = 0; i < MAX_NR_ZONES; i++) {
1220                 zonelist = pgdat->node_zonelists + i;
1221                 memset(zonelist, 0, sizeof(*zonelist));
1222                 zonelist->zones[0] = NULL;
1223         }
1224
1225         /* NUMA-aware ordering of nodes */
1226         local_node = pgdat->node_id;
1227         load = numnodes;
1228         prev_node = local_node;
1229         bitmap_zero(used_mask, MAX_NUMNODES);
1230         while ((node = find_next_best_node(local_node, used_mask)) >= 0) {
1231                 /*
1232                  * We don't want to pressure a particular node.
1233                  * So adding penalty to the first node in same
1234                  * distance group to make it round-robin.
1235                  */
1236                 if (node_distance(local_node, node) !=
1237                                 node_distance(local_node, prev_node))
1238                         node_load[node] += load;
1239                 prev_node = node;
1240                 load--;
1241                 for (i = 0; i < MAX_NR_ZONES; i++) {
1242                         zonelist = pgdat->node_zonelists + i;
1243                         for (j = 0; zonelist->zones[j] != NULL; j++);
1244
1245                         k = ZONE_NORMAL;
1246                         if (i & __GFP_HIGHMEM)
1247                                 k = ZONE_HIGHMEM;
1248                         if (i & __GFP_DMA)
1249                                 k = ZONE_DMA;
1250
1251                         j = build_zonelists_node(NODE_DATA(node), zonelist, j, k);
1252                         zonelist->zones[j] = NULL;
1253                 }
1254         }
1255 }
1256
1257 #else   /* CONFIG_NUMA */
1258
1259 static void __init build_zonelists(pg_data_t *pgdat)
1260 {
1261         int i, j, k, node, local_node;
1262
1263         local_node = pgdat->node_id;
1264         for (i = 0; i < MAX_NR_ZONES; i++) {
1265                 struct zonelist *zonelist;
1266
1267                 zonelist = pgdat->node_zonelists + i;
1268                 memset(zonelist, 0, sizeof(*zonelist));
1269
1270                 j = 0;
1271                 k = ZONE_NORMAL;
1272                 if (i & __GFP_HIGHMEM)
1273                         k = ZONE_HIGHMEM;
1274                 if (i & __GFP_DMA)
1275                         k = ZONE_DMA;
1276
1277                 j = build_zonelists_node(pgdat, zonelist, j, k);
1278                 /*
1279                  * Now we build the zonelist so that it contains the zones
1280                  * of all the other nodes.
1281                  * We don't want to pressure a particular node, so when
1282                  * building the zones for node N, we make sure that the
1283                  * zones coming right after the local ones are those from
1284                  * node N+1 (modulo N)
1285                  */
1286                 for (node = local_node + 1; node < numnodes; node++)
1287                         j = build_zonelists_node(NODE_DATA(node), zonelist, j, k);
1288                 for (node = 0; node < local_node; node++)
1289                         j = build_zonelists_node(NODE_DATA(node), zonelist, j, k);
1290  
1291                 zonelist->zones[j++] = NULL;
1292         }
1293 }
1294
1295 #endif  /* CONFIG_NUMA */
1296
1297 void __init build_all_zonelists(void)
1298 {
1299         int i;
1300
1301         for(i = 0 ; i < numnodes ; i++)
1302                 build_zonelists(NODE_DATA(i));
1303         printk("Built %i zonelists\n", numnodes);
1304 }
1305
1306 /*
1307  * Helper functions to size the waitqueue hash table.
1308  * Essentially these want to choose hash table sizes sufficiently
1309  * large so that collisions trying to wait on pages are rare.
1310  * But in fact, the number of active page waitqueues on typical
1311  * systems is ridiculously low, less than 200. So this is even
1312  * conservative, even though it seems large.
1313  *
1314  * The constant PAGES_PER_WAITQUEUE specifies the ratio of pages to
1315  * waitqueues, i.e. the size of the waitq table given the number of pages.
1316  */
1317 #define PAGES_PER_WAITQUEUE     256
1318
1319 static inline unsigned long wait_table_size(unsigned long pages)
1320 {
1321         unsigned long size = 1;
1322
1323         pages /= PAGES_PER_WAITQUEUE;
1324
1325         while (size < pages)
1326                 size <<= 1;
1327
1328         /*
1329          * Once we have dozens or even hundreds of threads sleeping
1330          * on IO we've got bigger problems than wait queue collision.
1331          * Limit the size of the wait table to a reasonable size.
1332          */
1333         size = min(size, 4096UL);
1334
1335         return max(size, 4UL);
1336 }
1337
1338 /*
1339  * This is an integer logarithm so that shifts can be used later
1340  * to extract the more random high bits from the multiplicative
1341  * hash function before the remainder is taken.
1342  */
1343 static inline unsigned long wait_table_bits(unsigned long size)
1344 {
1345         return ffz(~size);
1346 }
1347
1348 #define LONG_ALIGN(x) (((x)+(sizeof(long))-1)&~((sizeof(long))-1))
1349
1350 static void __init calculate_zone_totalpages(struct pglist_data *pgdat,
1351                 unsigned long *zones_size, unsigned long *zholes_size)
1352 {
1353         unsigned long realtotalpages, totalpages = 0;
1354         int i;
1355
1356         for (i = 0; i < MAX_NR_ZONES; i++)
1357                 totalpages += zones_size[i];
1358         pgdat->node_spanned_pages = totalpages;
1359
1360         realtotalpages = totalpages;
1361         if (zholes_size)
1362                 for (i = 0; i < MAX_NR_ZONES; i++)
1363                         realtotalpages -= zholes_size[i];
1364         pgdat->node_present_pages = realtotalpages;
1365         printk("On node %d totalpages: %lu\n", pgdat->node_id, realtotalpages);
1366 }
1367
1368
1369 /*
1370  * Initially all pages are reserved - free ones are freed
1371  * up by free_all_bootmem() once the early boot process is
1372  * done. Non-atomic initialization, single-pass.
1373  */
1374 void __init memmap_init_zone(struct page *start, unsigned long size, int nid,
1375                 unsigned long zone, unsigned long start_pfn)
1376 {
1377         struct page *page;
1378
1379         for (page = start; page < (start + size); page++) {
1380                 set_page_zone(page, NODEZONE(nid, zone));
1381                 set_page_count(page, 0);
1382                 SetPageReserved(page);
1383                 INIT_LIST_HEAD(&page->lru);
1384 #ifdef WANT_PAGE_VIRTUAL
1385                 /* The shift won't overflow because ZONE_NORMAL is below 4G. */
1386                 if (zone != ZONE_HIGHMEM)
1387                         set_page_address(page, __va(start_pfn << PAGE_SHIFT));
1388 #endif
1389                 start_pfn++;
1390         }
1391 }
1392
1393 #ifndef __HAVE_ARCH_MEMMAP_INIT
1394 #define memmap_init(start, size, nid, zone, start_pfn) \
1395         memmap_init_zone((start), (size), (nid), (zone), (start_pfn))
1396 #endif
1397
1398 /*
1399  * Set up the zone data structures:
1400  *   - mark all pages reserved
1401  *   - mark all memory queues empty
1402  *   - clear the memory bitmaps
1403  */
1404 static void __init free_area_init_core(struct pglist_data *pgdat,
1405                 unsigned long *zones_size, unsigned long *zholes_size)
1406 {
1407         unsigned long i, j;
1408         const unsigned long zone_required_alignment = 1UL << (MAX_ORDER-1);
1409         int cpu, nid = pgdat->node_id;
1410         struct page *lmem_map = pgdat->node_mem_map;
1411         unsigned long zone_start_pfn = pgdat->node_start_pfn;
1412
1413         pgdat->nr_zones = 0;
1414         init_waitqueue_head(&pgdat->kswapd_wait);
1415         
1416         for (j = 0; j < MAX_NR_ZONES; j++) {
1417                 struct zone *zone = pgdat->node_zones + j;
1418                 unsigned long size, realsize;
1419                 unsigned long batch;
1420
1421                 zone_table[NODEZONE(nid, j)] = zone;
1422                 realsize = size = zones_size[j];
1423                 if (zholes_size)
1424                         realsize -= zholes_size[j];
1425
1426                 zone->spanned_pages = size;
1427                 zone->present_pages = realsize;
1428                 zone->name = zone_names[j];
1429                 spin_lock_init(&zone->lock);
1430                 spin_lock_init(&zone->lru_lock);
1431                 zone->zone_pgdat = pgdat;
1432                 zone->free_pages = 0;
1433
1434                 zone->temp_priority = zone->prev_priority = DEF_PRIORITY;
1435
1436                 /*
1437                  * The per-cpu-pages pools are set to around 1000th of the
1438                  * size of the zone.  But no more than 1/4 of a meg - there's
1439                  * no point in going beyond the size of L2 cache.
1440                  *
1441                  * OK, so we don't know how big the cache is.  So guess.
1442                  */
1443                 batch = zone->present_pages / 1024;
1444                 if (batch * PAGE_SIZE > 256 * 1024)
1445                         batch = (256 * 1024) / PAGE_SIZE;
1446                 batch /= 4;             /* We effectively *= 4 below */
1447                 if (batch < 1)
1448                         batch = 1;
1449
1450                 for (cpu = 0; cpu < NR_CPUS; cpu++) {
1451                         struct per_cpu_pages *pcp;
1452
1453                         pcp = &zone->pageset[cpu].pcp[0];       /* hot */
1454                         pcp->count = 0;
1455                         pcp->low = 2 * batch;
1456                         pcp->high = 6 * batch;
1457                         pcp->batch = 1 * batch;
1458                         INIT_LIST_HEAD(&pcp->list);
1459
1460                         pcp = &zone->pageset[cpu].pcp[1];       /* cold */
1461                         pcp->count = 0;
1462                         pcp->low = 0;
1463                         pcp->high = 2 * batch;
1464                         pcp->batch = 1 * batch;
1465                         INIT_LIST_HEAD(&pcp->list);
1466                 }
1467                 printk("  %s zone: %lu pages, LIFO batch:%lu\n",
1468                                 zone_names[j], realsize, batch);
1469                 INIT_LIST_HEAD(&zone->active_list);
1470                 INIT_LIST_HEAD(&zone->inactive_list);
1471                 atomic_set(&zone->nr_scan_active, 0);
1472                 atomic_set(&zone->nr_scan_inactive, 0);
1473                 zone->nr_active = 0;
1474                 zone->nr_inactive = 0;
1475                 if (!size)
1476                         continue;
1477
1478                 /*
1479                  * The per-page waitqueue mechanism uses hashed waitqueues
1480                  * per zone.
1481                  */
1482                 zone->wait_table_size = wait_table_size(size);
1483                 zone->wait_table_bits =
1484                         wait_table_bits(zone->wait_table_size);
1485                 zone->wait_table = (wait_queue_head_t *)
1486                         alloc_bootmem_node(pgdat, zone->wait_table_size
1487                                                 * sizeof(wait_queue_head_t));
1488
1489                 for(i = 0; i < zone->wait_table_size; ++i)
1490                         init_waitqueue_head(zone->wait_table + i);
1491
1492                 pgdat->nr_zones = j+1;
1493
1494                 zone->zone_mem_map = lmem_map;
1495                 zone->zone_start_pfn = zone_start_pfn;
1496
1497                 if ((zone_start_pfn) & (zone_required_alignment-1))
1498                         printk("BUG: wrong zone alignment, it will crash\n");
1499
1500                 memmap_init(lmem_map, size, nid, j, zone_start_pfn);
1501
1502                 zone_start_pfn += size;
1503                 lmem_map += size;
1504
1505                 for (i = 0; ; i++) {
1506                         unsigned long bitmap_size;
1507
1508                         INIT_LIST_HEAD(&zone->free_area[i].free_list);
1509                         if (i == MAX_ORDER-1) {
1510                                 zone->free_area[i].map = NULL;
1511                                 break;
1512                         }
1513
1514                         /*
1515                          * Page buddy system uses "index >> (i+1)",
1516                          * where "index" is at most "size-1".
1517                          *
1518                          * The extra "+3" is to round down to byte
1519                          * size (8 bits per byte assumption). Thus
1520                          * we get "(size-1) >> (i+4)" as the last byte
1521                          * we can access.
1522                          *
1523                          * The "+1" is because we want to round the
1524                          * byte allocation up rather than down. So
1525                          * we should have had a "+7" before we shifted
1526                          * down by three. Also, we have to add one as
1527                          * we actually _use_ the last bit (it's [0,n]
1528                          * inclusive, not [0,n[).
1529                          *
1530                          * So we actually had +7+1 before we shift
1531                          * down by 3. But (n+8) >> 3 == (n >> 3) + 1
1532                          * (modulo overflows, which we do not have).
1533                          *
1534                          * Finally, we LONG_ALIGN because all bitmap
1535                          * operations are on longs.
1536                          */
1537                         bitmap_size = (size-1) >> (i+4);
1538                         bitmap_size = LONG_ALIGN(bitmap_size+1);
1539                         zone->free_area[i].map = 
1540                           (unsigned long *) alloc_bootmem_node(pgdat, bitmap_size);
1541                 }
1542         }
1543 }
1544
1545 void __init free_area_init_node(int nid, struct pglist_data *pgdat,
1546                 struct page *node_mem_map, unsigned long *zones_size,
1547                 unsigned long node_start_pfn, unsigned long *zholes_size)
1548 {
1549         unsigned long size;
1550
1551         pgdat->node_id = nid;
1552         pgdat->node_start_pfn = node_start_pfn;
1553         calculate_zone_totalpages(pgdat, zones_size, zholes_size);
1554         if (!node_mem_map) {
1555                 size = (pgdat->node_spanned_pages + 1) * sizeof(struct page);
1556                 node_mem_map = alloc_bootmem_node(pgdat, size);
1557         }
1558         pgdat->node_mem_map = node_mem_map;
1559
1560         free_area_init_core(pgdat, zones_size, zholes_size);
1561 }
1562
1563 #ifndef CONFIG_DISCONTIGMEM
1564 static bootmem_data_t contig_bootmem_data;
1565 struct pglist_data contig_page_data = { .bdata = &contig_bootmem_data };
1566
1567 EXPORT_SYMBOL(contig_page_data);
1568
1569 void __init free_area_init(unsigned long *zones_size)
1570 {
1571         free_area_init_node(0, &contig_page_data, NULL, zones_size,
1572                         __pa(PAGE_OFFSET) >> PAGE_SHIFT, NULL);
1573         mem_map = contig_page_data.node_mem_map;
1574 }
1575 #endif
1576
1577 #ifdef CONFIG_PROC_FS
1578
1579 #include <linux/seq_file.h>
1580
1581 static void *frag_start(struct seq_file *m, loff_t *pos)
1582 {
1583         pg_data_t *pgdat;
1584         loff_t node = *pos;
1585
1586         for (pgdat = pgdat_list; pgdat && node; pgdat = pgdat->pgdat_next)
1587                 --node;
1588
1589         return pgdat;
1590 }
1591
1592 static void *frag_next(struct seq_file *m, void *arg, loff_t *pos)
1593 {
1594         pg_data_t *pgdat = (pg_data_t *)arg;
1595
1596         (*pos)++;
1597         return pgdat->pgdat_next;
1598 }
1599
1600 static void frag_stop(struct seq_file *m, void *arg)
1601 {
1602 }
1603
1604 /* 
1605  * This walks the freelist for each zone. Whilst this is slow, I'd rather 
1606  * be slow here than slow down the fast path by keeping stats - mjbligh
1607  */
1608 static int frag_show(struct seq_file *m, void *arg)
1609 {
1610         pg_data_t *pgdat = (pg_data_t *)arg;
1611         struct zone *zone;
1612         struct zone *node_zones = pgdat->node_zones;
1613         unsigned long flags;
1614         int order;
1615
1616         for (zone = node_zones; zone - node_zones < MAX_NR_ZONES; ++zone) {
1617                 if (!zone->present_pages)
1618                         continue;
1619
1620                 spin_lock_irqsave(&zone->lock, flags);
1621                 seq_printf(m, "Node %d, zone %8s ", pgdat->node_id, zone->name);
1622                 for (order = 0; order < MAX_ORDER; ++order) {
1623                         unsigned long nr_bufs = 0;
1624                         struct list_head *elem;
1625
1626                         list_for_each(elem, &(zone->free_area[order].free_list))
1627                                 ++nr_bufs;
1628                         seq_printf(m, "%6lu ", nr_bufs);
1629                 }
1630                 spin_unlock_irqrestore(&zone->lock, flags);
1631                 seq_putc(m, '\n');
1632         }
1633         return 0;
1634 }
1635
1636 struct seq_operations fragmentation_op = {
1637         .start  = frag_start,
1638         .next   = frag_next,
1639         .stop   = frag_stop,
1640         .show   = frag_show,
1641 };
1642
1643 static char *vmstat_text[] = {
1644         "nr_dirty",
1645         "nr_writeback",
1646         "nr_unstable",
1647         "nr_page_table_pages",
1648         "nr_mapped",
1649         "nr_slab",
1650
1651         "pgpgin",
1652         "pgpgout",
1653         "pswpin",
1654         "pswpout",
1655         "pgalloc_high",
1656
1657         "pgalloc_normal",
1658         "pgalloc_dma",
1659         "pgfree",
1660         "pgactivate",
1661         "pgdeactivate",
1662
1663         "pgfault",
1664         "pgmajfault",
1665         "pgrefill_high",
1666         "pgrefill_normal",
1667         "pgrefill_dma",
1668
1669         "pgsteal_high",
1670         "pgsteal_normal",
1671         "pgsteal_dma",
1672         "pgscan_kswapd_high",
1673         "pgscan_kswapd_normal",
1674
1675         "pgscan_kswapd_dma",
1676         "pgscan_direct_high",
1677         "pgscan_direct_normal",
1678         "pgscan_direct_dma",
1679         "pginodesteal",
1680
1681         "slabs_scanned",
1682         "kswapd_steal",
1683         "kswapd_inodesteal",
1684         "pageoutrun",
1685         "allocstall",
1686
1687         "pgrotated",
1688 };
1689
1690 static void *vmstat_start(struct seq_file *m, loff_t *pos)
1691 {
1692         struct page_state *ps;
1693
1694         if (*pos >= ARRAY_SIZE(vmstat_text))
1695                 return NULL;
1696
1697         ps = kmalloc(sizeof(*ps), GFP_KERNEL);
1698         m->private = ps;
1699         if (!ps)
1700                 return ERR_PTR(-ENOMEM);
1701         get_full_page_state(ps);
1702         ps->pgpgin /= 2;                /* sectors -> kbytes */
1703         ps->pgpgout /= 2;
1704         return (unsigned long *)ps + *pos;
1705 }
1706
1707 static void *vmstat_next(struct seq_file *m, void *arg, loff_t *pos)
1708 {
1709         (*pos)++;
1710         if (*pos >= ARRAY_SIZE(vmstat_text))
1711                 return NULL;
1712         return (unsigned long *)m->private + *pos;
1713 }
1714
1715 static int vmstat_show(struct seq_file *m, void *arg)
1716 {
1717         unsigned long *l = arg;
1718         unsigned long off = l - (unsigned long *)m->private;
1719
1720         seq_printf(m, "%s %lu\n", vmstat_text[off], *l);
1721         return 0;
1722 }
1723
1724 static void vmstat_stop(struct seq_file *m, void *arg)
1725 {
1726         kfree(m->private);
1727         m->private = NULL;
1728 }
1729
1730 struct seq_operations vmstat_op = {
1731         .start  = vmstat_start,
1732         .next   = vmstat_next,
1733         .stop   = vmstat_stop,
1734         .show   = vmstat_show,
1735 };
1736
1737 #endif /* CONFIG_PROC_FS */
1738
1739 #ifdef CONFIG_HOTPLUG_CPU
1740 static int page_alloc_cpu_notify(struct notifier_block *self,
1741                                  unsigned long action, void *hcpu)
1742 {
1743         int cpu = (unsigned long)hcpu;
1744         long *count;
1745
1746         if (action == CPU_DEAD) {
1747                 /* Drain local pagecache count. */
1748                 count = &per_cpu(nr_pagecache_local, cpu);
1749                 atomic_add(*count, &nr_pagecache);
1750                 *count = 0;
1751                 local_irq_disable();
1752                 __drain_pages(cpu);
1753                 local_irq_enable();
1754         }
1755         return NOTIFY_OK;
1756 }
1757 #endif /* CONFIG_HOTPLUG_CPU */
1758
1759 void __init page_alloc_init(void)
1760 {
1761         hotcpu_notifier(page_alloc_cpu_notify, 0);
1762 }
1763
1764 static unsigned long higherzone_val(struct zone *z, int max_zone,
1765                                         int alloc_type)
1766 {
1767         int z_idx = zone_idx(z);
1768         struct zone *higherzone;
1769         unsigned long pages;
1770
1771         /* there is no higher zone to get a contribution from */
1772         if (z_idx == MAX_NR_ZONES-1)
1773                 return 0;
1774
1775         higherzone = &z->zone_pgdat->node_zones[z_idx+1];
1776
1777         /* We always start with the higher zone's protection value */
1778         pages = higherzone->protection[alloc_type];
1779
1780         /*
1781          * We get a lower-zone-protection contribution only if there are
1782          * pages in the higher zone and if we're not the highest zone
1783          * in the current zonelist.  e.g., never happens for GFP_DMA. Happens
1784          * only for ZONE_DMA in a GFP_KERNEL allocation and happens for ZONE_DMA
1785          * and ZONE_NORMAL for a GFP_HIGHMEM allocation.
1786          */
1787         if (higherzone->present_pages && z_idx < alloc_type)
1788                 pages += higherzone->pages_low * sysctl_lower_zone_protection;
1789
1790         return pages;
1791 }
1792
1793 /*
1794  * setup_per_zone_protection - called whenver min_free_kbytes or
1795  *      sysctl_lower_zone_protection changes.  Ensures that each zone
1796  *      has a correct pages_protected value, so an adequate number of
1797  *      pages are left in the zone after a successful __alloc_pages().
1798  *
1799  *      This algorithm is way confusing.  I tries to keep the same behavior
1800  *      as we had with the incremental min iterative algorithm.
1801  */
1802 static void setup_per_zone_protection(void)
1803 {
1804         struct pglist_data *pgdat;
1805         struct zone *zones, *zone;
1806         int max_zone;
1807         int i, j;
1808
1809         for_each_pgdat(pgdat) {
1810                 zones = pgdat->node_zones;
1811
1812                 for (i = 0, max_zone = 0; i < MAX_NR_ZONES; i++)
1813                         if (zones[i].present_pages)
1814                                 max_zone = i;
1815
1816                 /*
1817                  * For each of the different allocation types:
1818                  * GFP_DMA -> GFP_KERNEL -> GFP_HIGHMEM
1819                  */
1820                 for (i = 0; i < MAX_NR_ZONES; i++) {
1821                         /*
1822                          * For each of the zones:
1823                          * ZONE_HIGHMEM -> ZONE_NORMAL -> ZONE_DMA
1824                          */
1825                         for (j = MAX_NR_ZONES-1; j >= 0; j--) {
1826                                 zone = &zones[j];
1827
1828                                 /*
1829                                  * We never protect zones that don't have memory
1830                                  * in them (j>max_zone) or zones that aren't in
1831                                  * the zonelists for a certain type of
1832                                  * allocation (j>i).  We have to assign these to
1833                                  * zero because the lower zones take
1834                                  * contributions from the higher zones.
1835                                  */
1836                                 if (j > max_zone || j > i) {
1837                                         zone->protection[i] = 0;
1838                                         continue;
1839                                 }
1840                                 /*
1841                                  * The contribution of the next higher zone
1842                                  */
1843                                 zone->protection[i] = higherzone_val(zone,
1844                                                                 max_zone, i);
1845                                 zone->protection[i] += zone->pages_low;
1846                         }
1847                 }
1848         }
1849 }
1850
1851 /*
1852  * setup_per_zone_pages_min - called when min_free_kbytes changes.  Ensures 
1853  *      that the pages_{min,low,high} values for each zone are set correctly 
1854  *      with respect to min_free_kbytes.
1855  */
1856 static void setup_per_zone_pages_min(void)
1857 {
1858         unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
1859         unsigned long lowmem_pages = 0;
1860         struct zone *zone;
1861         unsigned long flags;
1862
1863         /* Calculate total number of !ZONE_HIGHMEM pages */
1864         for_each_zone(zone) {
1865                 if (!is_highmem(zone))
1866                         lowmem_pages += zone->present_pages;
1867         }
1868
1869         for_each_zone(zone) {
1870                 spin_lock_irqsave(&zone->lru_lock, flags);
1871                 if (is_highmem(zone)) {
1872                         /*
1873                          * Often, highmem doesn't need to reserve any pages.
1874                          * But the pages_min/low/high values are also used for
1875                          * batching up page reclaim activity so we need a
1876                          * decent value here.
1877                          */
1878                         int min_pages;
1879
1880                         min_pages = zone->present_pages / 1024;
1881                         if (min_pages < SWAP_CLUSTER_MAX)
1882                                 min_pages = SWAP_CLUSTER_MAX;
1883                         if (min_pages > 128)
1884                                 min_pages = 128;
1885                         zone->pages_min = min_pages;
1886                 } else {
1887                         /* if it's a lowmem zone, reserve a number of pages 
1888                          * proportionate to the zone's size.
1889                          */
1890                         zone->pages_min = (pages_min * zone->present_pages) / 
1891                                            lowmem_pages;
1892                 }
1893
1894                 zone->pages_low = zone->pages_min * 2;
1895                 zone->pages_high = zone->pages_min * 3;
1896                 spin_unlock_irqrestore(&zone->lru_lock, flags);
1897         }
1898 }
1899
1900 /*
1901  * Initialise min_free_kbytes.
1902  *
1903  * For small machines we want it small (128k min).  For large machines
1904  * we want it large (16MB max).  But it is not linear, because network
1905  * bandwidth does not increase linearly with machine size.  We use
1906  *
1907  *      min_free_kbytes = sqrt(lowmem_kbytes)
1908  *
1909  * which yields
1910  *
1911  * 16MB:        128k
1912  * 32MB:        181k
1913  * 64MB:        256k
1914  * 128MB:       362k
1915  * 256MB:       512k
1916  * 512MB:       724k
1917  * 1024MB:      1024k
1918  * 2048MB:      1448k
1919  * 4096MB:      2048k
1920  * 8192MB:      2896k
1921  * 16384MB:     4096k
1922  */
1923 static int __init init_per_zone_pages_min(void)
1924 {
1925         unsigned long lowmem_kbytes;
1926
1927         lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
1928
1929         min_free_kbytes = int_sqrt(lowmem_kbytes);
1930         if (min_free_kbytes < 128)
1931                 min_free_kbytes = 128;
1932         if (min_free_kbytes > 16384)
1933                 min_free_kbytes = 16384;
1934         setup_per_zone_pages_min();
1935         setup_per_zone_protection();
1936         return 0;
1937 }
1938 module_init(init_per_zone_pages_min)
1939
1940 /*
1941  * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so 
1942  *      that we can call two helper functions whenever min_free_kbytes
1943  *      changes.
1944  */
1945 int min_free_kbytes_sysctl_handler(ctl_table *table, int write, 
1946                 struct file *file, void __user *buffer, size_t *length)
1947 {
1948         proc_dointvec(table, write, file, buffer, length);
1949         setup_per_zone_pages_min();
1950         setup_per_zone_protection();
1951         return 0;
1952 }
1953
1954 /*
1955  * lower_zone_protection_sysctl_handler - just a wrapper around
1956  *      proc_dointvec() so that we can call setup_per_zone_protection()
1957  *      whenever sysctl_lower_zone_protection changes.
1958  */
1959 int lower_zone_protection_sysctl_handler(ctl_table *table, int write,
1960                  struct file *file, void __user *buffer, size_t *length)
1961 {
1962         proc_dointvec_minmax(table, write, file, buffer, length);
1963         setup_per_zone_protection();
1964         return 0;
1965 }