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