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