This commit was manufactured by cvs2svn to create tag
[linux-2.6.git] / mm / page_alloc.c
1 /*
2  *  linux/mm/page_alloc.c
3  *
4  *  Manages the free list, the system allocates free pages here.
5  *  Note that kmalloc() lives in slab.c
6  *
7  *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
8  *  Swap reorganised 29.12.95, Stephen Tweedie
9  *  Support of BIGMEM added by Gerhard Wichert, Siemens AG, July 1999
10  *  Reshaped it to be a zoned allocator, Ingo Molnar, Red Hat, 1999
11  *  Discontiguous memory support, Kanoj Sarcar, SGI, Nov 1999
12  *  Zone balancing, Kanoj Sarcar, SGI, Jan 2000
13  *  Per cpu hot/cold page lists, bulk allocation, Martin J. Bligh, Sept 2002
14  *          (lots of bits borrowed from Ingo Molnar & Andrew Morton)
15  */
16
17 #include <linux/config.h>
18 #include <linux/stddef.h>
19 #include <linux/mm.h>
20 #include <linux/swap.h>
21 #include <linux/interrupt.h>
22 #include <linux/pagemap.h>
23 #include <linux/bootmem.h>
24 #include <linux/compiler.h>
25 #include <linux/module.h>
26 #include <linux/suspend.h>
27 #include <linux/pagevec.h>
28 #include <linux/blkdev.h>
29 #include <linux/slab.h>
30 #include <linux/notifier.h>
31 #include <linux/topology.h>
32 #include <linux/sysctl.h>
33 #include <linux/cpu.h>
34 #include <linux/vs_base.h>
35 #include <linux/vs_limit.h>
36 #include <linux/ckrm_mem_inline.h>
37
38 #include <asm/tlbflush.h>
39
40 DECLARE_BITMAP(node_online_map, MAX_NUMNODES);
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 #ifdef CONFIG_CRASH_DUMP_MODULE
52 /* This symbol has to be exported to use 'for_each_pgdat' macro by modules. */
53 EXPORT_SYMBOL(pgdat_list);
54 #endif
55
56 /*
57  * Used by page_zone() to look up the address of the struct zone whose
58  * id is encoded in the upper bits of page->flags
59  */
60 struct zone *zone_table[1 << (ZONES_SHIFT + NODES_SHIFT)];
61 EXPORT_SYMBOL(zone_table);
62
63 static char *zone_names[MAX_NR_ZONES] = { "DMA", "Normal", "HighMem" };
64 int min_free_kbytes = 1024;
65
66 unsigned long __initdata nr_kernel_pages;
67 unsigned long __initdata nr_all_pages;
68
69 /*
70  * Temporary debugging check for pages not lying within a given zone.
71  */
72 static int bad_range(struct zone *zone, struct page *page)
73 {
74         if (page_to_pfn(page) >= zone->zone_start_pfn + zone->spanned_pages)
75                 return 1;
76         if (page_to_pfn(page) < zone->zone_start_pfn)
77                 return 1;
78         if (zone != page_zone(page))
79                 return 1;
80         return 0;
81 }
82
83 static void bad_page(const char *function, struct page *page)
84 {
85         printk(KERN_EMERG "Bad page state at %s (in process '%s', page %p)\n",
86                 function, current->comm, page);
87         printk(KERN_EMERG "flags:0x%0*lx mapping:%p mapcount:%d count:%d\n",
88                 (int)(2*sizeof(page_flags_t)), (unsigned long)page->flags,
89                 page->mapping, page_mapcount(page), page_count(page));
90         printk(KERN_EMERG "Backtrace:\n");
91         dump_stack();
92         printk(KERN_EMERG "Trying to fix it up, but a reboot is needed\n");
93         page->flags &= ~(1 << PG_private        |
94                         1 << PG_locked  |
95                         1 << PG_lru     |
96                         1 << PG_active  |
97                         1 << PG_dirty   |
98                         1 << PG_swapcache |
99                         1 << PG_writeback);
100         set_page_count(page, 0);
101         reset_page_mapcount(page);
102         page->mapping = NULL;
103         tainted |= TAINT_BAD_PAGE;
104 }
105
106 #if !defined(CONFIG_HUGETLB_PAGE) && !defined(CONFIG_CRASH_DUMP) \
107         && !defined(CONFIG_CRASH_DUMP_MODULE)
108 #define prep_compound_page(page, order) do { } while (0)
109 #define destroy_compound_page(page, order) do { } while (0)
110 #else
111 /*
112  * Higher-order pages are called "compound pages".  They are structured thusly:
113  *
114  * The first PAGE_SIZE page is called the "head page".
115  *
116  * The remaining PAGE_SIZE pages are called "tail pages".
117  *
118  * All pages have PG_compound set.  All pages have their ->private pointing at
119  * the head page (even the head page has this).
120  *
121  * The first tail page's ->mapping, if non-zero, holds the address of the
122  * compound page's put_page() function.
123  *
124  * The order of the allocation is stored in the first tail page's ->index
125  * This is only for debug at present.  This usage means that zero-order pages
126  * may not be compound.
127  */
128 static void prep_compound_page(struct page *page, unsigned long order)
129 {
130         int i;
131         int nr_pages = 1 << order;
132
133         page[1].mapping = NULL;
134         page[1].index = order;
135         for (i = 0; i < nr_pages; i++) {
136                 struct page *p = page + i;
137
138                 SetPageCompound(p);
139                 p->private = (unsigned long)page;
140         }
141 }
142
143 static void destroy_compound_page(struct page *page, unsigned long order)
144 {
145         int i;
146         int nr_pages = 1 << order;
147
148         if (!PageCompound(page))
149                 return;
150
151         if (page[1].index != order)
152                 bad_page(__FUNCTION__, page);
153
154         for (i = 0; i < nr_pages; i++) {
155                 struct page *p = page + i;
156
157                 if (!PageCompound(p))
158                         bad_page(__FUNCTION__, page);
159                 if (p->private != (unsigned long)page)
160                         bad_page(__FUNCTION__, page);
161                 ClearPageCompound(p);
162         }
163 }
164 #endif          /* CONFIG_HUGETLB_PAGE */
165
166 /*
167  * Freeing function for a buddy system allocator.
168  *
169  * The concept of a buddy system is to maintain direct-mapped table
170  * (containing bit values) for memory blocks of various "orders".
171  * The bottom level table contains the map for the smallest allocatable
172  * units of memory (here, pages), and each level above it describes
173  * pairs of units from the levels below, hence, "buddies".
174  * At a high level, all that happens here is marking the table entry
175  * at the bottom level available, and propagating the changes upward
176  * as necessary, plus some accounting needed to play nicely with other
177  * parts of the VM system.
178  * At each level, we keep one bit for each pair of blocks, which
179  * is set to 1 iff only one of the pair is allocated.  So when we
180  * are allocating or freeing one, we can derive the state of the
181  * other.  That is, if we allocate a small block, and both were   
182  * free, the remainder of the region must be split into blocks.   
183  * If a block is freed, and its buddy is also free, then this
184  * triggers coalescing into a block of larger size.            
185  *
186  * -- wli
187  */
188
189 static inline void __free_pages_bulk (struct page *page, struct page *base,
190                 struct zone *zone, struct free_area *area, unsigned int order)
191 {
192         unsigned long page_idx, index, mask;
193
194         if (order)
195                 destroy_compound_page(page, order);
196         mask = (~0UL) << order;
197         page_idx = page - base;
198         if (page_idx & ~mask)
199                 BUG();
200         index = page_idx >> (1 + order);
201
202         zone->free_pages += 1 << order;
203         while (order < MAX_ORDER-1) {
204                 struct page *buddy1, *buddy2;
205
206                 BUG_ON(area >= zone->free_area + MAX_ORDER);
207                 if (!__test_and_change_bit(index, area->map))
208                         /*
209                          * the buddy page is still allocated.
210                          */
211                         break;
212
213                 /* Move the buddy up one level. */
214                 buddy1 = base + (page_idx ^ (1 << order));
215                 buddy2 = base + page_idx;
216                 BUG_ON(bad_range(zone, buddy1));
217                 BUG_ON(bad_range(zone, buddy2));
218                 list_del(&buddy1->lru);
219                 mask <<= 1;
220                 order++;
221                 area++;
222                 index >>= 1;
223                 page_idx &= mask;
224         }
225         list_add(&(base + page_idx)->lru, &area->free_list);
226 }
227
228 static inline void free_pages_check(const char *function, struct page *page)
229 {
230         if (    page_mapped(page) ||
231                 page->mapping != NULL ||
232                 page_count(page) != 0 ||
233                 (page->flags & (
234                         1 << PG_lru     |
235                         1 << PG_private |
236                         1 << PG_locked  |
237                         1 << PG_active  |
238                         1 << PG_reclaim |
239                         1 << PG_slab    |
240                         1 << PG_swapcache |
241                         1 << PG_writeback )))
242                 bad_page(function, page);
243         if (PageDirty(page))
244                 ClearPageDirty(page);
245 }
246
247 /*
248  * Frees a list of pages. 
249  * Assumes all pages on list are in same zone, and of same order.
250  * count is the number of pages to free, or 0 for all on the list.
251  *
252  * If the zone was previously in an "all pages pinned" state then look to
253  * see if this freeing clears that state.
254  *
255  * And clear the zone's pages_scanned counter, to hold off the "all pages are
256  * pinned" detection logic.
257  */
258 static int
259 free_pages_bulk(struct zone *zone, int count,
260                 struct list_head *list, unsigned int order)
261 {
262         unsigned long flags;
263         struct free_area *area;
264         struct page *base, *page = NULL;
265         int ret = 0;
266
267         base = zone->zone_mem_map;
268         area = zone->free_area + order;
269         spin_lock_irqsave(&zone->lock, flags);
270         zone->all_unreclaimable = 0;
271         zone->pages_scanned = 0;
272         while (!list_empty(list) && count--) {
273                 page = list_entry(list->prev, struct page, lru);
274                 /* have to delete it as __free_pages_bulk list manipulates */
275                 list_del(&page->lru);
276                 __free_pages_bulk(page, base, zone, area, order);
277                 ckrm_clear_page_class(page);
278                 ret++;
279         }
280         spin_unlock_irqrestore(&zone->lock, flags);
281         return ret;
282 }
283
284 void __free_pages_ok(struct page *page, unsigned int order)
285 {
286         LIST_HEAD(list);
287         int i;
288
289         arch_free_page(page, order);
290
291         mod_page_state(pgfree, 1 << order);
292         for (i = 0 ; i < (1 << order) ; ++i)
293                 free_pages_check(__FUNCTION__, page + i);
294         list_add(&page->lru, &list);
295         kernel_map_pages(page, 1<<order, 0);
296         free_pages_bulk(page_zone(page), 1, &list, order);
297 }
298
299 #define MARK_USED(index, order, area) \
300         __change_bit((index) >> (1+(order)), (area)->map)
301
302 /*
303  * The order of subdivision here is critical for the IO subsystem.
304  * Please do not alter this order without good reasons and regression
305  * testing. Specifically, as large blocks of memory are subdivided,
306  * the order in which smaller blocks are delivered depends on the order
307  * they're subdivided in this function. This is the primary factor
308  * influencing the order in which pages are delivered to the IO
309  * subsystem according to empirical testing, and this is also justified
310  * by considering the behavior of a buddy system containing a single
311  * large block of memory acted on by a series of small allocations.
312  * This behavior is a critical factor in sglist merging's success.
313  *
314  * -- wli
315  */
316 static inline struct page *
317 expand(struct zone *zone, struct page *page,
318          unsigned long index, int low, int high, struct free_area *area)
319 {
320         unsigned long size = 1 << high;
321
322         while (high > low) {
323                 area--;
324                 high--;
325                 size >>= 1;
326                 BUG_ON(bad_range(zone, &page[size]));
327                 list_add(&page[size].lru, &area->free_list);
328                 MARK_USED(index + size, high, area);
329         }
330         return page;
331 }
332
333 static inline void set_page_refs(struct page *page, int order)
334 {
335 #ifdef CONFIG_MMU
336         set_page_count(page, 1);
337 #else
338         int i;
339
340         /*
341          * We need to reference all the pages for this order, otherwise if
342          * anyone accesses one of the pages with (get/put) it will be freed.
343          */
344         for (i = 0; i < (1 << order); i++)
345                 set_page_count(page+i, 1);
346 #endif /* CONFIG_MMU */
347 }
348
349 /*
350  * This page is about to be returned from the page allocator
351  */
352 static void prep_new_page(struct page *page, int order)
353 {
354         if (page->mapping || page_mapped(page) ||
355             (page->flags & (
356                         1 << PG_private |
357                         1 << PG_locked  |
358                         1 << PG_lru     |
359                         1 << PG_active  |
360                         1 << PG_dirty   |
361                         1 << PG_reclaim |
362                         1 << PG_swapcache |
363                         1 << PG_writeback )))
364                 bad_page(__FUNCTION__, page);
365
366         page->flags &= ~(1 << PG_uptodate | 1 << PG_error |
367                         1 << PG_referenced | 1 << PG_arch_1 |
368                         1 << PG_checked | 1 << PG_mappedtodisk);
369         page->private = 0;
370         set_page_refs(page, order);
371 }
372
373 /* 
374  * Do the hard work of removing an element from the buddy allocator.
375  * Call me with the zone->lock already held.
376  */
377 static struct page *__rmqueue(struct zone *zone, unsigned int order)
378 {
379         struct free_area * area;
380         unsigned int current_order;
381         struct page *page;
382         unsigned int index;
383
384         for (current_order = order; current_order < MAX_ORDER; ++current_order) {
385                 area = zone->free_area + current_order;
386                 if (list_empty(&area->free_list))
387                         continue;
388
389                 page = list_entry(area->free_list.next, struct page, lru);
390                 list_del(&page->lru);
391                 index = page - zone->zone_mem_map;
392                 if (current_order != MAX_ORDER-1)
393                         MARK_USED(index, current_order, area);
394                 zone->free_pages -= 1UL << order;
395                 return expand(zone, page, index, order, current_order, area);
396         }
397
398         return NULL;
399 }
400
401 /* 
402  * Obtain a specified number of elements from the buddy allocator, all under
403  * a single hold of the lock, for efficiency.  Add them to the supplied list.
404  * Returns the number of new pages which were placed at *list.
405  */
406 static int rmqueue_bulk(struct zone *zone, unsigned int order, 
407                         unsigned long count, struct list_head *list)
408 {
409         unsigned long flags;
410         int i;
411         int allocated = 0;
412         struct page *page;
413         
414         spin_lock_irqsave(&zone->lock, flags);
415         for (i = 0; i < count; ++i) {
416                 page = __rmqueue(zone, order);
417                 if (page == NULL)
418                         break;
419                 allocated++;
420                 list_add_tail(&page->lru, list);
421         }
422         spin_unlock_irqrestore(&zone->lock, flags);
423         return allocated;
424 }
425
426 #if defined(CONFIG_PM) || defined(CONFIG_HOTPLUG_CPU)
427 static void __drain_pages(unsigned int cpu)
428 {
429         struct zone *zone;
430         int i;
431
432         for_each_zone(zone) {
433                 struct per_cpu_pageset *pset;
434
435                 pset = &zone->pageset[cpu];
436                 for (i = 0; i < ARRAY_SIZE(pset->pcp); i++) {
437                         struct per_cpu_pages *pcp;
438
439                         pcp = &pset->pcp[i];
440                         pcp->count -= free_pages_bulk(zone, pcp->count,
441                                                 &pcp->list, 0);
442                 }
443         }
444 }
445 #endif /* CONFIG_PM || CONFIG_HOTPLUG_CPU */
446
447 #ifdef CONFIG_PM
448 int is_head_of_free_region(struct page *page)
449 {
450         struct zone *zone = page_zone(page);
451         unsigned long flags;
452         int order;
453         struct list_head *curr;
454
455         /*
456          * Should not matter as we need quiescent system for
457          * suspend anyway, but...
458          */
459         spin_lock_irqsave(&zone->lock, flags);
460         for (order = MAX_ORDER - 1; order >= 0; --order)
461                 list_for_each(curr, &zone->free_area[order].free_list)
462                         if (page == list_entry(curr, struct page, lru)) {
463                                 spin_unlock_irqrestore(&zone->lock, flags);
464                                 return 1 << order;
465                         }
466         spin_unlock_irqrestore(&zone->lock, flags);
467         return 0;
468 }
469
470 /*
471  * Spill all of this CPU's per-cpu pages back into the buddy allocator.
472  */
473 void drain_local_pages(void)
474 {
475         unsigned long flags;
476
477         local_irq_save(flags);  
478         __drain_pages(smp_processor_id());
479         local_irq_restore(flags);       
480 }
481 #endif /* CONFIG_PM */
482
483 static void zone_statistics(struct zonelist *zonelist, struct zone *z)
484 {
485 #ifdef CONFIG_NUMA
486         unsigned long flags;
487         int cpu;
488         pg_data_t *pg = z->zone_pgdat;
489         pg_data_t *orig = zonelist->zones[0]->zone_pgdat;
490         struct per_cpu_pageset *p;
491
492         local_irq_save(flags);
493         cpu = smp_processor_id();
494         p = &z->pageset[cpu];
495         if (pg == orig) {
496                 z->pageset[cpu].numa_hit++;
497         } else {
498                 p->numa_miss++;
499                 zonelist->zones[0]->pageset[cpu].numa_foreign++;
500         }
501         if (pg == NODE_DATA(numa_node_id()))
502                 p->local_node++;
503         else
504                 p->other_node++;
505         local_irq_restore(flags);
506 #endif
507 }
508
509 /*
510  * Free a 0-order page
511  */
512 static void FASTCALL(free_hot_cold_page(struct page *page, int cold));
513 static void fastcall free_hot_cold_page(struct page *page, int cold)
514 {
515         struct zone *zone = page_zone(page);
516         struct per_cpu_pages *pcp;
517         unsigned long flags;
518
519         arch_free_page(page, 0);
520
521         kernel_map_pages(page, 1, 0);
522         inc_page_state(pgfree);
523         if (PageAnon(page))
524                 page->mapping = NULL;
525         free_pages_check(__FUNCTION__, page);
526         pcp = &zone->pageset[get_cpu()].pcp[cold];
527         local_irq_save(flags);
528         if (pcp->count >= pcp->high)
529                 pcp->count -= free_pages_bulk(zone, pcp->batch, &pcp->list, 0);
530         list_add(&page->lru, &pcp->list);
531         pcp->count++;
532         local_irq_restore(flags);
533         put_cpu();
534 }
535
536 void fastcall free_hot_page(struct page *page)
537 {
538         free_hot_cold_page(page, 0);
539 }
540         
541 void fastcall free_cold_page(struct page *page)
542 {
543         free_hot_cold_page(page, 1);
544 }
545
546 /*
547  * Really, prep_compound_page() should be called from __rmqueue_bulk().  But
548  * we cheat by calling it from here, in the order > 0 path.  Saves a branch
549  * or two.
550  */
551
552 static struct page *
553 buffered_rmqueue(struct zone *zone, int order, int gfp_flags)
554 {
555         unsigned long flags;
556         struct page *page = NULL;
557         int cold = !!(gfp_flags & __GFP_COLD);
558
559         if (order == 0) {
560                 struct per_cpu_pages *pcp;
561
562                 pcp = &zone->pageset[get_cpu()].pcp[cold];
563                 local_irq_save(flags);
564                 if (pcp->count <= pcp->low)
565                         pcp->count += rmqueue_bulk(zone, 0,
566                                                 pcp->batch, &pcp->list);
567                 if (pcp->count) {
568                         page = list_entry(pcp->list.next, struct page, lru);
569                         list_del(&page->lru);
570                         pcp->count--;
571                 }
572                 local_irq_restore(flags);
573                 put_cpu();
574         }
575
576         if (page == NULL) {
577                 spin_lock_irqsave(&zone->lock, flags);
578                 page = __rmqueue(zone, order);
579                 spin_unlock_irqrestore(&zone->lock, flags);
580         }
581
582         if (page != NULL) {
583                 BUG_ON(bad_range(zone, page));
584                 mod_page_state_zone(zone, pgalloc, 1 << order);
585                 prep_new_page(page, order);
586                 if (order && (gfp_flags & __GFP_COMP))
587                         prep_compound_page(page, order);
588         }
589         return page;
590 }
591
592 /*
593  * This is the 'heart' of the zoned buddy allocator.
594  *
595  * Herein lies the mysterious "incremental min".  That's the
596  *
597  *      local_low = z->pages_low;
598  *      min += local_low;
599  *
600  * thing.  The intent here is to provide additional protection to low zones for
601  * allocation requests which _could_ use higher zones.  So a GFP_HIGHMEM
602  * request is not allowed to dip as deeply into the normal zone as a GFP_KERNEL
603  * request.  This preserves additional space in those lower zones for requests
604  * which really do need memory from those zones.  It means that on a decent
605  * sized machine, GFP_HIGHMEM and GFP_KERNEL requests basically leave the DMA
606  * zone untouched.
607  */
608 struct page * fastcall
609 __alloc_pages(unsigned int gfp_mask, unsigned int order,
610                 struct zonelist *zonelist)
611 {
612         const int wait = gfp_mask & __GFP_WAIT;
613         unsigned long min;
614         struct zone **zones, *z;
615         struct page *page;
616         struct reclaim_state reclaim_state;
617         struct task_struct *p = current;
618         int i;
619         int alloc_type;
620         int do_retry;
621         int can_try_harder;
622
623         might_sleep_if(wait);
624
625         if (!ckrm_class_limit_ok((GET_MEM_CLASS(current)))) {
626                 return NULL;
627         }
628
629         /*
630          * The caller may dip into page reserves a bit more if the caller
631          * cannot run direct reclaim, or is the caller has realtime scheduling
632          * policy
633          */
634         can_try_harder = (unlikely(rt_task(p)) && !in_interrupt()) || !wait;
635
636         zones = zonelist->zones;  /* the list of zones suitable for gfp_mask */
637
638         if (unlikely(zones[0] == NULL)) {
639                 /* Should this ever happen?? */
640                 return NULL;
641         }
642
643         alloc_type = zone_idx(zones[0]);
644
645         /* Go through the zonelist once, looking for a zone with enough free */
646         for (i = 0; (z = zones[i]) != NULL; i++) {
647                 min = z->pages_low + (1<<order) + z->protection[alloc_type];
648
649                 if (z->free_pages < min)
650                         continue;
651
652                 page = buffered_rmqueue(z, order, gfp_mask);
653                 if (page)
654                         goto got_pg;
655         }
656
657         for (i = 0; (z = zones[i]) != NULL; i++)
658                 wakeup_kswapd(z);
659
660         /*
661          * Go through the zonelist again. Let __GFP_HIGH and allocations
662          * coming from realtime tasks to go deeper into reserves
663          */
664         for (i = 0; (z = zones[i]) != NULL; i++) {
665                 min = z->pages_min;
666                 if (gfp_mask & __GFP_HIGH)
667                         min /= 2;
668                 if (can_try_harder)
669                         min -= min / 4;
670                 min += (1<<order) + z->protection[alloc_type];
671
672                 if (z->free_pages < min)
673                         continue;
674
675                 page = buffered_rmqueue(z, order, gfp_mask);
676                 if (page)
677                         goto got_pg;
678         }
679
680         /* This allocation should allow future memory freeing. */
681         if ((p->flags & (PF_MEMALLOC | PF_MEMDIE)) && !in_interrupt()) {
682                 /* go through the zonelist yet again, ignoring mins */
683                 for (i = 0; (z = zones[i]) != NULL; i++) {
684                         page = buffered_rmqueue(z, order, gfp_mask);
685                         if (page)
686                                 goto got_pg;
687                 }
688                 goto nopage;
689         }
690
691         /* Atomic allocations - we can't balance anything */
692         if (!wait)
693                 goto nopage;
694
695 rebalance:
696         /* We now go into synchronous reclaim */
697         p->flags |= PF_MEMALLOC;
698         reclaim_state.reclaimed_slab = 0;
699         p->reclaim_state = &reclaim_state;
700
701         try_to_free_pages(zones, gfp_mask, order);
702
703         p->reclaim_state = NULL;
704         p->flags &= ~PF_MEMALLOC;
705
706         /* go through the zonelist yet one more time */
707         for (i = 0; (z = zones[i]) != NULL; i++) {
708                 min = z->pages_min;
709                 if (gfp_mask & __GFP_HIGH)
710                         min /= 2;
711                 if (can_try_harder)
712                         min -= min / 4;
713                 min += (1<<order) + z->protection[alloc_type];
714
715                 if (z->free_pages < min)
716                         continue;
717
718                 page = buffered_rmqueue(z, order, gfp_mask);
719                 if (page)
720                         goto got_pg;
721         }
722
723         /*
724          * Don't let big-order allocations loop unless the caller explicitly
725          * requests that.  Wait for some write requests to complete then retry.
726          *
727          * In this implementation, __GFP_REPEAT means __GFP_NOFAIL for order
728          * <= 3, but that may not be true in other implementations.
729          */
730         do_retry = 0;
731         if (!(gfp_mask & __GFP_NORETRY)) {
732                 if ((order <= 3) || (gfp_mask & __GFP_REPEAT))
733                         do_retry = 1;
734                 if (gfp_mask & __GFP_NOFAIL)
735                         do_retry = 1;
736         }
737         if (do_retry) {
738                 blk_congestion_wait(WRITE, HZ/50);
739                 goto rebalance;
740         }
741
742 nopage:
743         if (!(gfp_mask & __GFP_NOWARN) && printk_ratelimit()) {
744                 printk(KERN_WARNING "%s: page allocation failure."
745                         " order:%d, mode:0x%x\n",
746                         p->comm, order, gfp_mask);
747                 dump_stack();
748         }
749         return NULL;
750 got_pg:
751         zone_statistics(zonelist, z);
752         kernel_map_pages(page, 1 << order, 1);
753         ckrm_set_pages_class(page, 1 << order, GET_MEM_CLASS(current));
754         return page;
755 }
756
757 EXPORT_SYMBOL(__alloc_pages);
758
759 /*
760  * Common helper functions.
761  */
762 fastcall unsigned long __get_free_pages(unsigned int gfp_mask, unsigned int order)
763 {
764         struct page * page;
765         page = alloc_pages(gfp_mask, order);
766         if (!page)
767                 return 0;
768         return (unsigned long) page_address(page);
769 }
770
771 EXPORT_SYMBOL(__get_free_pages);
772
773 fastcall unsigned long get_zeroed_page(unsigned int gfp_mask)
774 {
775         struct page * page;
776
777         /*
778          * get_zeroed_page() returns a 32-bit address, which cannot represent
779          * a highmem page
780          */
781         BUG_ON(gfp_mask & __GFP_HIGHMEM);
782
783         page = alloc_pages(gfp_mask, 0);
784         if (page) {
785                 void *address = page_address(page);
786                 clear_page(address);
787                 return (unsigned long) address;
788         }
789         return 0;
790 }
791
792 EXPORT_SYMBOL(get_zeroed_page);
793
794 void __pagevec_free(struct pagevec *pvec)
795 {
796         int i = pagevec_count(pvec);
797
798         while (--i >= 0)
799                 free_hot_cold_page(pvec->pages[i], pvec->cold);
800 }
801
802 fastcall void __free_pages(struct page *page, unsigned int order)
803 {
804         if (!PageReserved(page) && put_page_testzero(page)) {
805                 if (order == 0)
806                         free_hot_page(page);
807                 else
808                         __free_pages_ok(page, order);
809         }
810 }
811
812 EXPORT_SYMBOL(__free_pages);
813
814 fastcall void free_pages(unsigned long addr, unsigned int order)
815 {
816         if (addr != 0) {
817                 BUG_ON(!virt_addr_valid((void *)addr));
818                 __free_pages(virt_to_page((void *)addr), order);
819         }
820 }
821
822 EXPORT_SYMBOL(free_pages);
823
824 /*
825  * Total amount of free (allocatable) RAM:
826  */
827 unsigned int nr_free_pages(void)
828 {
829         unsigned int sum = 0;
830         struct zone *zone;
831
832         for_each_zone(zone)
833                 sum += zone->free_pages;
834
835         return sum;
836 }
837
838 EXPORT_SYMBOL(nr_free_pages);
839
840 #ifdef CONFIG_NUMA
841 unsigned int nr_free_pages_pgdat(pg_data_t *pgdat)
842 {
843         unsigned int i, sum = 0;
844
845         for (i = 0; i < MAX_NR_ZONES; i++)
846                 sum += pgdat->node_zones[i].free_pages;
847
848         return sum;
849 }
850 #endif
851
852 static unsigned int nr_free_zone_pages(int offset)
853 {
854         pg_data_t *pgdat;
855         unsigned int sum = 0;
856
857         for_each_pgdat(pgdat) {
858                 struct zonelist *zonelist = pgdat->node_zonelists + offset;
859                 struct zone **zonep = zonelist->zones;
860                 struct zone *zone;
861
862                 for (zone = *zonep++; zone; zone = *zonep++) {
863                         unsigned long size = zone->present_pages;
864                         unsigned long high = zone->pages_high;
865                         if (size > high)
866                                 sum += size - high;
867                 }
868         }
869
870         return sum;
871 }
872
873 /*
874  * Amount of free RAM allocatable within ZONE_DMA and ZONE_NORMAL
875  */
876 unsigned int nr_free_buffer_pages(void)
877 {
878         return nr_free_zone_pages(GFP_USER & GFP_ZONEMASK);
879 }
880
881 /*
882  * Amount of free RAM allocatable within all zones
883  */
884 unsigned int nr_free_pagecache_pages(void)
885 {
886         return nr_free_zone_pages(GFP_HIGHUSER & GFP_ZONEMASK);
887 }
888
889 #ifdef CONFIG_HIGHMEM
890 unsigned int nr_free_highpages (void)
891 {
892         pg_data_t *pgdat;
893         unsigned int pages = 0;
894
895         for_each_pgdat(pgdat)
896                 pages += pgdat->node_zones[ZONE_HIGHMEM].free_pages;
897
898         return pages;
899 }
900 #endif
901
902 #ifdef CONFIG_NUMA
903 static void show_node(struct zone *zone)
904 {
905         printk("Node %d ", zone->zone_pgdat->node_id);
906 }
907 #else
908 #define show_node(zone) do { } while (0)
909 #endif
910
911 /*
912  * Accumulate the page_state information across all CPUs.
913  * The result is unavoidably approximate - it can change
914  * during and after execution of this function.
915  */
916 DEFINE_PER_CPU(struct page_state, page_states) = {0};
917 EXPORT_PER_CPU_SYMBOL(page_states);
918
919 atomic_t nr_pagecache = ATOMIC_INIT(0);
920 EXPORT_SYMBOL(nr_pagecache);
921 #ifdef CONFIG_SMP
922 DEFINE_PER_CPU(long, nr_pagecache_local) = 0;
923 #endif
924
925 void __get_page_state(struct page_state *ret, int nr)
926 {
927         int cpu = 0;
928
929         memset(ret, 0, sizeof(*ret));
930         while (cpu < NR_CPUS) {
931                 unsigned long *in, *out, off;
932
933                 if (!cpu_possible(cpu)) {
934                         cpu++;
935                         continue;
936                 }
937
938                 in = (unsigned long *)&per_cpu(page_states, cpu);
939                 cpu++;
940                 if (cpu < NR_CPUS && cpu_possible(cpu))
941                         prefetch(&per_cpu(page_states, cpu));
942                 out = (unsigned long *)ret;
943                 for (off = 0; off < nr; off++)
944                         *out++ += *in++;
945         }
946 }
947
948 void get_page_state(struct page_state *ret)
949 {
950         int nr;
951
952         nr = offsetof(struct page_state, GET_PAGE_STATE_LAST);
953         nr /= sizeof(unsigned long);
954
955         __get_page_state(ret, nr + 1);
956 }
957
958 void get_full_page_state(struct page_state *ret)
959 {
960         __get_page_state(ret, sizeof(*ret) / sizeof(unsigned long));
961 }
962
963 unsigned long __read_page_state(unsigned offset)
964 {
965         unsigned long ret = 0;
966         int cpu;
967
968         for (cpu = 0; cpu < NR_CPUS; cpu++) {
969                 unsigned long in;
970
971                 if (!cpu_possible(cpu))
972                         continue;
973
974                 in = (unsigned long)&per_cpu(page_states, cpu) + offset;
975                 ret += *((unsigned long *)in);
976         }
977         return ret;
978 }
979
980 void __get_zone_counts(unsigned long *active, unsigned long *inactive,
981                         unsigned long *free, struct pglist_data *pgdat)
982 {
983         struct zone *zones = pgdat->node_zones;
984         int i;
985
986         *active = 0;
987         *inactive = 0;
988         *free = 0;
989         for (i = 0; i < MAX_NR_ZONES; i++) {
990                 *active += zones[i].nr_active;
991                 *inactive += zones[i].nr_inactive;
992                 *free += zones[i].free_pages;
993         }
994 }
995
996 void get_zone_counts(unsigned long *active,
997                 unsigned long *inactive, unsigned long *free)
998 {
999         struct pglist_data *pgdat;
1000
1001         *active = 0;
1002         *inactive = 0;
1003         *free = 0;
1004         for_each_pgdat(pgdat) {
1005                 unsigned long l, m, n;
1006                 __get_zone_counts(&l, &m, &n, pgdat);
1007                 *active += l;
1008                 *inactive += m;
1009                 *free += n;
1010         }
1011 }
1012
1013 void si_meminfo(struct sysinfo *val)
1014 {
1015         val->totalram = totalram_pages;
1016         val->sharedram = 0;
1017         val->freeram = nr_free_pages();
1018         val->bufferram = nr_blockdev_pages();
1019 #ifdef CONFIG_HIGHMEM
1020         val->totalhigh = totalhigh_pages;
1021         val->freehigh = nr_free_highpages();
1022 #else
1023         val->totalhigh = 0;
1024         val->freehigh = 0;
1025 #endif
1026         val->mem_unit = PAGE_SIZE;
1027         if (vx_flags(VXF_VIRT_MEM, 0))
1028                 vx_vsi_meminfo(val);
1029 }
1030
1031 EXPORT_SYMBOL(si_meminfo);
1032
1033 #ifdef CONFIG_NUMA
1034 void si_meminfo_node(struct sysinfo *val, int nid)
1035 {
1036         pg_data_t *pgdat = NODE_DATA(nid);
1037
1038         val->totalram = pgdat->node_present_pages;
1039         val->freeram = nr_free_pages_pgdat(pgdat);
1040         val->totalhigh = pgdat->node_zones[ZONE_HIGHMEM].present_pages;
1041         val->freehigh = pgdat->node_zones[ZONE_HIGHMEM].free_pages;
1042         val->mem_unit = PAGE_SIZE;
1043 }
1044 #endif
1045
1046 #define K(x) ((x) << (PAGE_SHIFT-10))
1047
1048 /*
1049  * Show free area list (used inside shift_scroll-lock stuff)
1050  * We also calculate the percentage fragmentation. We do this by counting the
1051  * memory on each free list with the exception of the first item on the list.
1052  */
1053 void show_free_areas(void)
1054 {
1055         struct page_state ps;
1056         int cpu, temperature;
1057         unsigned long active;
1058         unsigned long inactive;
1059         unsigned long free;
1060         struct zone *zone;
1061
1062         for_each_zone(zone) {
1063                 show_node(zone);
1064                 printk("%s per-cpu:", zone->name);
1065
1066                 if (!zone->present_pages) {
1067                         printk(" empty\n");
1068                         continue;
1069                 } else
1070                         printk("\n");
1071
1072                 for (cpu = 0; cpu < NR_CPUS; ++cpu) {
1073                         struct per_cpu_pageset *pageset;
1074
1075                         if (!cpu_possible(cpu))
1076                                 continue;
1077
1078                         pageset = zone->pageset + cpu;
1079
1080                         for (temperature = 0; temperature < 2; temperature++)
1081                                 printk("cpu %d %s: low %d, high %d, batch %d\n",
1082                                         cpu,
1083                                         temperature ? "cold" : "hot",
1084                                         pageset->pcp[temperature].low,
1085                                         pageset->pcp[temperature].high,
1086                                         pageset->pcp[temperature].batch);
1087                 }
1088         }
1089
1090         get_page_state(&ps);
1091         get_zone_counts(&active, &inactive, &free);
1092
1093         printk("\nFree pages: %11ukB (%ukB HighMem)\n",
1094                 K(nr_free_pages()),
1095                 K(nr_free_highpages()));
1096
1097         printk("Active:%lu inactive:%lu dirty:%lu writeback:%lu "
1098                 "unstable:%lu free:%u slab:%lu mapped:%lu pagetables:%lu\n",
1099                 active,
1100                 inactive,
1101                 ps.nr_dirty,
1102                 ps.nr_writeback,
1103                 ps.nr_unstable,
1104                 nr_free_pages(),
1105                 ps.nr_slab,
1106                 ps.nr_mapped,
1107                 ps.nr_page_table_pages);
1108
1109         for_each_zone(zone) {
1110                 int i;
1111
1112                 show_node(zone);
1113                 printk("%s"
1114                         " free:%lukB"
1115                         " min:%lukB"
1116                         " low:%lukB"
1117                         " high:%lukB"
1118                         " active:%lukB"
1119                         " inactive:%lukB"
1120                         " present:%lukB"
1121                         "\n",
1122                         zone->name,
1123                         K(zone->free_pages),
1124                         K(zone->pages_min),
1125                         K(zone->pages_low),
1126                         K(zone->pages_high),
1127                         K(zone->nr_active),
1128                         K(zone->nr_inactive),
1129                         K(zone->present_pages)
1130                         );
1131                 printk("protections[]:");
1132                 for (i = 0; i < MAX_NR_ZONES; i++)
1133                         printk(" %lu", zone->protection[i]);
1134                 printk("\n");
1135         }
1136
1137         for_each_zone(zone) {
1138                 struct list_head *elem;
1139                 unsigned long nr, flags, order, total = 0;
1140
1141                 show_node(zone);
1142                 printk("%s: ", zone->name);
1143                 if (!zone->present_pages) {
1144                         printk("empty\n");
1145                         continue;
1146                 }
1147
1148                 spin_lock_irqsave(&zone->lock, flags);
1149                 for (order = 0; order < MAX_ORDER; order++) {
1150                         nr = 0;
1151                         list_for_each(elem, &zone->free_area[order].free_list)
1152                                 ++nr;
1153                         total += nr << order;
1154                         printk("%lu*%lukB ", nr, K(1UL) << order);
1155                 }
1156                 spin_unlock_irqrestore(&zone->lock, flags);
1157                 printk("= %lukB\n", K(total));
1158         }
1159
1160         show_swap_cache_info();
1161 }
1162
1163 /*
1164  * Builds allocation fallback zone lists.
1165  */
1166 static int __init build_zonelists_node(pg_data_t *pgdat, struct zonelist *zonelist, int j, int k)
1167 {
1168         switch (k) {
1169                 struct zone *zone;
1170         default:
1171                 BUG();
1172         case ZONE_HIGHMEM:
1173                 zone = pgdat->node_zones + ZONE_HIGHMEM;
1174                 if (zone->present_pages) {
1175 #ifndef CONFIG_HIGHMEM
1176                         BUG();
1177 #endif
1178                         zonelist->zones[j++] = zone;
1179                 }
1180         case ZONE_NORMAL:
1181                 zone = pgdat->node_zones + ZONE_NORMAL;
1182                 if (zone->present_pages)
1183                         zonelist->zones[j++] = zone;
1184         case ZONE_DMA:
1185                 zone = pgdat->node_zones + ZONE_DMA;
1186                 if (zone->present_pages)
1187                         zonelist->zones[j++] = zone;
1188         }
1189
1190         return j;
1191 }
1192
1193 #ifdef CONFIG_NUMA
1194 #define MAX_NODE_LOAD (numnodes)
1195 static int __initdata node_load[MAX_NUMNODES];
1196 /**
1197  * find_next_best_node - find the next node that should appear in a given
1198  *    node's fallback list
1199  * @node: node whose fallback list we're appending
1200  * @used_node_mask: pointer to the bitmap of already used nodes
1201  *
1202  * We use a number of factors to determine which is the next node that should
1203  * appear on a given node's fallback list.  The node should not have appeared
1204  * already in @node's fallback list, and it should be the next closest node
1205  * according to the distance array (which contains arbitrary distance values
1206  * from each node to each node in the system), and should also prefer nodes
1207  * with no CPUs, since presumably they'll have very little allocation pressure
1208  * on them otherwise.
1209  * It returns -1 if no node is found.
1210  */
1211 static int __init find_next_best_node(int node, void *used_node_mask)
1212 {
1213         int i, n, val;
1214         int min_val = INT_MAX;
1215         int best_node = -1;
1216
1217         for (i = 0; i < numnodes; i++) {
1218                 cpumask_t tmp;
1219
1220                 /* Start from local node */
1221                 n = (node+i)%numnodes;
1222
1223                 /* Don't want a node to appear more than once */
1224                 if (test_bit(n, used_node_mask))
1225                         continue;
1226
1227                 /* Use the distance array to find the distance */
1228                 val = node_distance(node, n);
1229
1230                 /* Give preference to headless and unused nodes */
1231                 tmp = node_to_cpumask(n);
1232                 if (!cpus_empty(tmp))
1233                         val += PENALTY_FOR_NODE_WITH_CPUS;
1234
1235                 /* Slight preference for less loaded node */
1236                 val *= (MAX_NODE_LOAD*MAX_NUMNODES);
1237                 val += node_load[n];
1238
1239                 if (val < min_val) {
1240                         min_val = val;
1241                         best_node = n;
1242                 }
1243         }
1244
1245         if (best_node >= 0)
1246                 set_bit(best_node, used_node_mask);
1247
1248         return best_node;
1249 }
1250
1251 static void __init build_zonelists(pg_data_t *pgdat)
1252 {
1253         int i, j, k, node, local_node;
1254         int prev_node, load;
1255         struct zonelist *zonelist;
1256         DECLARE_BITMAP(used_mask, MAX_NUMNODES);
1257
1258         /* initialize zonelists */
1259         for (i = 0; i < GFP_ZONETYPES; i++) {
1260                 zonelist = pgdat->node_zonelists + i;
1261                 memset(zonelist, 0, sizeof(*zonelist));
1262                 zonelist->zones[0] = NULL;
1263         }
1264
1265         /* NUMA-aware ordering of nodes */
1266         local_node = pgdat->node_id;
1267         load = numnodes;
1268         prev_node = local_node;
1269         bitmap_zero(used_mask, MAX_NUMNODES);
1270         while ((node = find_next_best_node(local_node, used_mask)) >= 0) {
1271                 /*
1272                  * We don't want to pressure a particular node.
1273                  * So adding penalty to the first node in same
1274                  * distance group to make it round-robin.
1275                  */
1276                 if (node_distance(local_node, node) !=
1277                                 node_distance(local_node, prev_node))
1278                         node_load[node] += load;
1279                 prev_node = node;
1280                 load--;
1281                 for (i = 0; i < GFP_ZONETYPES; i++) {
1282                         zonelist = pgdat->node_zonelists + i;
1283                         for (j = 0; zonelist->zones[j] != NULL; j++);
1284
1285                         k = ZONE_NORMAL;
1286                         if (i & __GFP_HIGHMEM)
1287                                 k = ZONE_HIGHMEM;
1288                         if (i & __GFP_DMA)
1289                                 k = ZONE_DMA;
1290
1291                         j = build_zonelists_node(NODE_DATA(node), zonelist, j, k);
1292                         zonelist->zones[j] = NULL;
1293                 }
1294         }
1295 }
1296
1297 #else   /* CONFIG_NUMA */
1298
1299 static void __init build_zonelists(pg_data_t *pgdat)
1300 {
1301         int i, j, k, node, local_node;
1302
1303         local_node = pgdat->node_id;
1304         for (i = 0; i < GFP_ZONETYPES; i++) {
1305                 struct zonelist *zonelist;
1306
1307                 zonelist = pgdat->node_zonelists + i;
1308                 memset(zonelist, 0, sizeof(*zonelist));
1309
1310                 j = 0;
1311                 k = ZONE_NORMAL;
1312                 if (i & __GFP_HIGHMEM)
1313                         k = ZONE_HIGHMEM;
1314                 if (i & __GFP_DMA)
1315                         k = ZONE_DMA;
1316
1317                 j = build_zonelists_node(pgdat, zonelist, j, k);
1318                 /*
1319                  * Now we build the zonelist so that it contains the zones
1320                  * of all the other nodes.
1321                  * We don't want to pressure a particular node, so when
1322                  * building the zones for node N, we make sure that the
1323                  * zones coming right after the local ones are those from
1324                  * node N+1 (modulo N)
1325                  */
1326                 for (node = local_node + 1; node < numnodes; node++)
1327                         j = build_zonelists_node(NODE_DATA(node), zonelist, j, k);
1328                 for (node = 0; node < local_node; node++)
1329                         j = build_zonelists_node(NODE_DATA(node), zonelist, j, k);
1330  
1331                 zonelist->zones[j] = NULL;
1332         }
1333 }
1334
1335 #endif  /* CONFIG_NUMA */
1336
1337 void __init build_all_zonelists(void)
1338 {
1339         int i;
1340
1341         for(i = 0 ; i < numnodes ; i++)
1342                 build_zonelists(NODE_DATA(i));
1343         printk("Built %i zonelists\n", numnodes);
1344 }
1345
1346 /*
1347  * Helper functions to size the waitqueue hash table.
1348  * Essentially these want to choose hash table sizes sufficiently
1349  * large so that collisions trying to wait on pages are rare.
1350  * But in fact, the number of active page waitqueues on typical
1351  * systems is ridiculously low, less than 200. So this is even
1352  * conservative, even though it seems large.
1353  *
1354  * The constant PAGES_PER_WAITQUEUE specifies the ratio of pages to
1355  * waitqueues, i.e. the size of the waitq table given the number of pages.
1356  */
1357 #define PAGES_PER_WAITQUEUE     256
1358
1359 static inline unsigned long wait_table_size(unsigned long pages)
1360 {
1361         unsigned long size = 1;
1362
1363         pages /= PAGES_PER_WAITQUEUE;
1364
1365         while (size < pages)
1366                 size <<= 1;
1367
1368         /*
1369          * Once we have dozens or even hundreds of threads sleeping
1370          * on IO we've got bigger problems than wait queue collision.
1371          * Limit the size of the wait table to a reasonable size.
1372          */
1373         size = min(size, 4096UL);
1374
1375         return max(size, 4UL);
1376 }
1377
1378 /*
1379  * This is an integer logarithm so that shifts can be used later
1380  * to extract the more random high bits from the multiplicative
1381  * hash function before the remainder is taken.
1382  */
1383 static inline unsigned long wait_table_bits(unsigned long size)
1384 {
1385         return ffz(~size);
1386 }
1387
1388 #define LONG_ALIGN(x) (((x)+(sizeof(long))-1)&~((sizeof(long))-1))
1389
1390 static void __init calculate_zone_totalpages(struct pglist_data *pgdat,
1391                 unsigned long *zones_size, unsigned long *zholes_size)
1392 {
1393         unsigned long realtotalpages, totalpages = 0;
1394         int i;
1395
1396         for (i = 0; i < MAX_NR_ZONES; i++)
1397                 totalpages += zones_size[i];
1398         pgdat->node_spanned_pages = totalpages;
1399
1400         realtotalpages = totalpages;
1401         if (zholes_size)
1402                 for (i = 0; i < MAX_NR_ZONES; i++)
1403                         realtotalpages -= zholes_size[i];
1404         pgdat->node_present_pages = realtotalpages;
1405         printk(KERN_DEBUG "On node %d totalpages: %lu\n", pgdat->node_id, realtotalpages);
1406 }
1407
1408
1409 /*
1410  * Initially all pages are reserved - free ones are freed
1411  * up by free_all_bootmem() once the early boot process is
1412  * done. Non-atomic initialization, single-pass.
1413  */
1414 void __init memmap_init_zone(unsigned long size, int nid, unsigned long zone,
1415                 unsigned long start_pfn)
1416 {
1417         struct page *start = pfn_to_page(start_pfn);
1418         struct page *page;
1419
1420         for (page = start; page < (start + size); page++) {
1421                 set_page_zone(page, NODEZONE(nid, zone));
1422                 set_page_count(page, 0);
1423                 reset_page_mapcount(page);
1424                 SetPageReserved(page);
1425                 INIT_LIST_HEAD(&page->lru);
1426 #ifdef WANT_PAGE_VIRTUAL
1427                 /* The shift won't overflow because ZONE_NORMAL is below 4G. */
1428                 if (!is_highmem_idx(zone))
1429                         set_page_address(page, __va(start_pfn << PAGE_SHIFT));
1430 #endif
1431                 start_pfn++;
1432         }
1433 }
1434
1435 /*
1436  * Page buddy system uses "index >> (i+1)", where "index" is
1437  * at most "size-1".
1438  *
1439  * The extra "+3" is to round down to byte size (8 bits per byte
1440  * assumption). Thus we get "(size-1) >> (i+4)" as the last byte
1441  * we can access.
1442  *
1443  * The "+1" is because we want to round the byte allocation up
1444  * rather than down. So we should have had a "+7" before we shifted
1445  * down by three. Also, we have to add one as we actually _use_ the
1446  * last bit (it's [0,n] inclusive, not [0,n[).
1447  *
1448  * So we actually had +7+1 before we shift down by 3. But
1449  * (n+8) >> 3 == (n >> 3) + 1 (modulo overflows, which we do not have).
1450  *
1451  * Finally, we LONG_ALIGN because all bitmap operations are on longs.
1452  */
1453 unsigned long pages_to_bitmap_size(unsigned long order, unsigned long nr_pages)
1454 {
1455         unsigned long bitmap_size;
1456
1457         bitmap_size = (nr_pages-1) >> (order+4);
1458         bitmap_size = LONG_ALIGN(bitmap_size+1);
1459
1460         return bitmap_size;
1461 }
1462
1463 void zone_init_free_lists(struct pglist_data *pgdat, struct zone *zone, unsigned long size)
1464 {
1465         int order;
1466         for (order = 0; ; order++) {
1467                 unsigned long bitmap_size;
1468
1469                 INIT_LIST_HEAD(&zone->free_area[order].free_list);
1470                 if (order == MAX_ORDER-1) {
1471                         zone->free_area[order].map = NULL;
1472                         break;
1473                 }
1474
1475                 bitmap_size = pages_to_bitmap_size(order, size);
1476                 zone->free_area[order].map =
1477                   (unsigned long *) alloc_bootmem_node(pgdat, bitmap_size);
1478         }
1479 }
1480
1481 #ifndef __HAVE_ARCH_MEMMAP_INIT
1482 #define memmap_init(size, nid, zone, start_pfn) \
1483         memmap_init_zone((size), (nid), (zone), (start_pfn))
1484 #endif
1485
1486 /*
1487  * Set up the zone data structures:
1488  *   - mark all pages reserved
1489  *   - mark all memory queues empty
1490  *   - clear the memory bitmaps
1491  */
1492 static void __init free_area_init_core(struct pglist_data *pgdat,
1493                 unsigned long *zones_size, unsigned long *zholes_size)
1494 {
1495         unsigned long i, j;
1496         const unsigned long zone_required_alignment = 1UL << (MAX_ORDER-1);
1497         int cpu, nid = pgdat->node_id;
1498         unsigned long zone_start_pfn = pgdat->node_start_pfn;
1499
1500         pgdat->nr_zones = 0;
1501         init_waitqueue_head(&pgdat->kswapd_wait);
1502         
1503         for (j = 0; j < MAX_NR_ZONES; j++) {
1504                 struct zone *zone = pgdat->node_zones + j;
1505                 unsigned long size, realsize;
1506                 unsigned long batch;
1507
1508                 zone_table[NODEZONE(nid, j)] = zone;
1509                 realsize = size = zones_size[j];
1510                 if (zholes_size)
1511                         realsize -= zholes_size[j];
1512
1513                 if (j == ZONE_DMA || j == ZONE_NORMAL)
1514                         nr_kernel_pages += realsize;
1515                 nr_all_pages += realsize;
1516
1517                 zone->spanned_pages = size;
1518                 zone->present_pages = realsize;
1519                 zone->name = zone_names[j];
1520                 spin_lock_init(&zone->lock);
1521                 spin_lock_init(&zone->lru_lock);
1522                 zone->zone_pgdat = pgdat;
1523                 zone->free_pages = 0;
1524
1525                 zone->temp_priority = zone->prev_priority = DEF_PRIORITY;
1526
1527                 /*
1528                  * The per-cpu-pages pools are set to around 1000th of the
1529                  * size of the zone.  But no more than 1/4 of a meg - there's
1530                  * no point in going beyond the size of L2 cache.
1531                  *
1532                  * OK, so we don't know how big the cache is.  So guess.
1533                  */
1534                 batch = zone->present_pages / 1024;
1535                 if (batch * PAGE_SIZE > 256 * 1024)
1536                         batch = (256 * 1024) / PAGE_SIZE;
1537                 batch /= 4;             /* We effectively *= 4 below */
1538                 if (batch < 1)
1539                         batch = 1;
1540
1541                 for (cpu = 0; cpu < NR_CPUS; cpu++) {
1542                         struct per_cpu_pages *pcp;
1543
1544                         pcp = &zone->pageset[cpu].pcp[0];       /* hot */
1545                         pcp->count = 0;
1546                         pcp->low = 2 * batch;
1547                         pcp->high = 6 * batch;
1548                         pcp->batch = 1 * batch;
1549                         INIT_LIST_HEAD(&pcp->list);
1550
1551                         pcp = &zone->pageset[cpu].pcp[1];       /* cold */
1552                         pcp->count = 0;
1553                         pcp->low = 0;
1554                         pcp->high = 2 * batch;
1555                         pcp->batch = 1 * batch;
1556                         INIT_LIST_HEAD(&pcp->list);
1557                 }
1558                 printk(KERN_DEBUG "  %s zone: %lu pages, LIFO batch:%lu\n",
1559                                 zone_names[j], realsize, batch);
1560                 INIT_LIST_HEAD(&zone->active_list);
1561                 INIT_LIST_HEAD(&zone->inactive_list);
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                 zone->pages_low = zone->pages_min * 2;
1954                 zone->pages_high = zone->pages_min * 3;
1955                 spin_unlock_irqrestore(&zone->lru_lock, flags);
1956         }
1957 }
1958
1959 /*
1960  * Initialise min_free_kbytes.
1961  *
1962  * For small machines we want it small (128k min).  For large machines
1963  * we want it large (16MB max).  But it is not linear, because network
1964  * bandwidth does not increase linearly with machine size.  We use
1965  *
1966  *      min_free_kbytes = sqrt(lowmem_kbytes)
1967  *
1968  * which yields
1969  *
1970  * 16MB:        128k
1971  * 32MB:        181k
1972  * 64MB:        256k
1973  * 128MB:       362k
1974  * 256MB:       512k
1975  * 512MB:       724k
1976  * 1024MB:      1024k
1977  * 2048MB:      1448k
1978  * 4096MB:      2048k
1979  * 8192MB:      2896k
1980  * 16384MB:     4096k
1981  */
1982 static int __init init_per_zone_pages_min(void)
1983 {
1984         unsigned long lowmem_kbytes;
1985
1986         lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
1987
1988         min_free_kbytes = int_sqrt(lowmem_kbytes);
1989         if (min_free_kbytes < 128)
1990                 min_free_kbytes = 128;
1991         if (min_free_kbytes > 16384)
1992                 min_free_kbytes = 16384;
1993         setup_per_zone_pages_min();
1994         setup_per_zone_protection();
1995         return 0;
1996 }
1997 module_init(init_per_zone_pages_min)
1998
1999 /*
2000  * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so 
2001  *      that we can call two helper functions whenever min_free_kbytes
2002  *      changes.
2003  */
2004 int min_free_kbytes_sysctl_handler(ctl_table *table, int write, 
2005                 struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
2006 {
2007         proc_dointvec(table, write, file, buffer, length, ppos);
2008         setup_per_zone_pages_min();
2009         setup_per_zone_protection();
2010         return 0;
2011 }
2012
2013 /*
2014  * lower_zone_protection_sysctl_handler - just a wrapper around
2015  *      proc_dointvec() so that we can call setup_per_zone_protection()
2016  *      whenever sysctl_lower_zone_protection changes.
2017  */
2018 int lower_zone_protection_sysctl_handler(ctl_table *table, int write,
2019                  struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
2020 {
2021         proc_dointvec_minmax(table, write, file, buffer, length, ppos);
2022         setup_per_zone_protection();
2023         return 0;
2024 }
2025
2026 /*
2027  * allocate a large system hash table from bootmem
2028  * - it is assumed that the hash table must contain an exact power-of-2
2029  *   quantity of entries
2030  */
2031 void *__init alloc_large_system_hash(const char *tablename,
2032                                      unsigned long bucketsize,
2033                                      unsigned long numentries,
2034                                      int scale,
2035                                      int consider_highmem,
2036                                      unsigned int *_hash_shift,
2037                                      unsigned int *_hash_mask)
2038 {
2039         unsigned long long max;
2040         unsigned long log2qty, size;
2041         void *table;
2042
2043         /* allow the kernel cmdline to have a say */
2044         if (!numentries) {
2045                 /* round applicable memory size up to nearest megabyte */
2046                 numentries = consider_highmem ? nr_all_pages : nr_kernel_pages;
2047                 numentries += (1UL << (20 - PAGE_SHIFT)) - 1;
2048                 numentries >>= 20 - PAGE_SHIFT;
2049                 numentries <<= 20 - PAGE_SHIFT;
2050
2051                 /* limit to 1 bucket per 2^scale bytes of low memory */
2052                 if (scale > PAGE_SHIFT)
2053                         numentries >>= (scale - PAGE_SHIFT);
2054                 else
2055                         numentries <<= (PAGE_SHIFT - scale);
2056         }
2057         /* rounded up to nearest power of 2 in size */
2058         numentries = 1UL << (long_log2(numentries) + 1);
2059
2060         /* limit allocation size to 1/16 total memory */
2061         max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
2062         do_div(max, bucketsize);
2063
2064         if (numentries > max)
2065                 numentries = max;
2066
2067         log2qty = long_log2(numentries);
2068
2069         do {
2070                 size = bucketsize << log2qty;
2071                 table = alloc_bootmem(size);
2072         } while (!table && size > PAGE_SIZE && --log2qty);
2073
2074         if (!table)
2075                 panic("Failed to allocate %s hash table\n", tablename);
2076
2077         printk("%s hash table entries: %d (order: %d, %lu bytes)\n",
2078                tablename,
2079                (1U << log2qty),
2080                long_log2(size) - PAGE_SHIFT,
2081                size);
2082
2083         if (_hash_shift)
2084                 *_hash_shift = log2qty;
2085         if (_hash_mask)
2086                 *_hash_mask = (1 << log2qty) - 1;
2087
2088         return table;
2089 }