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