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