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