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