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