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