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