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