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