[PATCH] reduce MAX_NR_ZONES: make display of highmem counters conditional on CONFIG_H...
[pandora-kernel.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/stddef.h>
18 #include <linux/mm.h>
19 #include <linux/swap.h>
20 #include <linux/interrupt.h>
21 #include <linux/pagemap.h>
22 #include <linux/bootmem.h>
23 #include <linux/compiler.h>
24 #include <linux/kernel.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/cpuset.h>
35 #include <linux/memory_hotplug.h>
36 #include <linux/nodemask.h>
37 #include <linux/vmalloc.h>
38 #include <linux/mempolicy.h>
39 #include <linux/stop_machine.h>
40
41 #include <asm/tlbflush.h>
42 #include <asm/div64.h>
43 #include "internal.h"
44
45 /*
46  * MCD - HACK: Find somewhere to initialize this EARLY, or make this
47  * initializer cleaner
48  */
49 nodemask_t node_online_map __read_mostly = { { [0] = 1UL } };
50 EXPORT_SYMBOL(node_online_map);
51 nodemask_t node_possible_map __read_mostly = NODE_MASK_ALL;
52 EXPORT_SYMBOL(node_possible_map);
53 unsigned long totalram_pages __read_mostly;
54 unsigned long totalhigh_pages __read_mostly;
55 unsigned long totalreserve_pages __read_mostly;
56 long nr_swap_pages;
57 int percpu_pagelist_fraction;
58
59 static void __free_pages_ok(struct page *page, unsigned int order);
60
61 /*
62  * results with 256, 32 in the lowmem_reserve sysctl:
63  *      1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
64  *      1G machine -> (16M dma, 784M normal, 224M high)
65  *      NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
66  *      HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
67  *      HIGHMEM allocation will (224M+784M)/256 of ram reserved in ZONE_DMA
68  *
69  * TBD: should special case ZONE_DMA32 machines here - in those we normally
70  * don't need any ZONE_NORMAL reservation
71  */
72 int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES-1] = { 256, 256, 32 };
73
74 EXPORT_SYMBOL(totalram_pages);
75
76 /*
77  * Used by page_zone() to look up the address of the struct zone whose
78  * id is encoded in the upper bits of page->flags
79  */
80 struct zone *zone_table[1 << ZONETABLE_SHIFT] __read_mostly;
81 EXPORT_SYMBOL(zone_table);
82
83 static char *zone_names[MAX_NR_ZONES] = { "DMA", "DMA32", "Normal", "HighMem" };
84 int min_free_kbytes = 1024;
85
86 unsigned long __meminitdata nr_kernel_pages;
87 unsigned long __meminitdata nr_all_pages;
88
89 #ifdef CONFIG_DEBUG_VM
90 static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
91 {
92         int ret = 0;
93         unsigned seq;
94         unsigned long pfn = page_to_pfn(page);
95
96         do {
97                 seq = zone_span_seqbegin(zone);
98                 if (pfn >= zone->zone_start_pfn + zone->spanned_pages)
99                         ret = 1;
100                 else if (pfn < zone->zone_start_pfn)
101                         ret = 1;
102         } while (zone_span_seqretry(zone, seq));
103
104         return ret;
105 }
106
107 static int page_is_consistent(struct zone *zone, struct page *page)
108 {
109 #ifdef CONFIG_HOLES_IN_ZONE
110         if (!pfn_valid(page_to_pfn(page)))
111                 return 0;
112 #endif
113         if (zone != page_zone(page))
114                 return 0;
115
116         return 1;
117 }
118 /*
119  * Temporary debugging check for pages not lying within a given zone.
120  */
121 static int bad_range(struct zone *zone, struct page *page)
122 {
123         if (page_outside_zone_boundaries(zone, page))
124                 return 1;
125         if (!page_is_consistent(zone, page))
126                 return 1;
127
128         return 0;
129 }
130 #else
131 static inline int bad_range(struct zone *zone, struct page *page)
132 {
133         return 0;
134 }
135 #endif
136
137 static void bad_page(struct page *page)
138 {
139         printk(KERN_EMERG "Bad page state in process '%s'\n"
140                 KERN_EMERG "page:%p flags:0x%0*lx mapping:%p mapcount:%d count:%d\n"
141                 KERN_EMERG "Trying to fix it up, but a reboot is needed\n"
142                 KERN_EMERG "Backtrace:\n",
143                 current->comm, page, (int)(2*sizeof(unsigned long)),
144                 (unsigned long)page->flags, page->mapping,
145                 page_mapcount(page), page_count(page));
146         dump_stack();
147         page->flags &= ~(1 << PG_lru    |
148                         1 << PG_private |
149                         1 << PG_locked  |
150                         1 << PG_active  |
151                         1 << PG_dirty   |
152                         1 << PG_reclaim |
153                         1 << PG_slab    |
154                         1 << PG_swapcache |
155                         1 << PG_writeback |
156                         1 << PG_buddy );
157         set_page_count(page, 0);
158         reset_page_mapcount(page);
159         page->mapping = NULL;
160         add_taint(TAINT_BAD_PAGE);
161 }
162
163 /*
164  * Higher-order pages are called "compound pages".  They are structured thusly:
165  *
166  * The first PAGE_SIZE page is called the "head page".
167  *
168  * The remaining PAGE_SIZE pages are called "tail pages".
169  *
170  * All pages have PG_compound set.  All pages have their ->private pointing at
171  * the head page (even the head page has this).
172  *
173  * The first tail page's ->lru.next holds the address of the compound page's
174  * put_page() function.  Its ->lru.prev holds the order of allocation.
175  * This usage means that zero-order pages may not be compound.
176  */
177
178 static void free_compound_page(struct page *page)
179 {
180         __free_pages_ok(page, (unsigned long)page[1].lru.prev);
181 }
182
183 static void prep_compound_page(struct page *page, unsigned long order)
184 {
185         int i;
186         int nr_pages = 1 << order;
187
188         page[1].lru.next = (void *)free_compound_page;  /* set dtor */
189         page[1].lru.prev = (void *)order;
190         for (i = 0; i < nr_pages; i++) {
191                 struct page *p = page + i;
192
193                 __SetPageCompound(p);
194                 set_page_private(p, (unsigned long)page);
195         }
196 }
197
198 static void destroy_compound_page(struct page *page, unsigned long order)
199 {
200         int i;
201         int nr_pages = 1 << order;
202
203         if (unlikely((unsigned long)page[1].lru.prev != order))
204                 bad_page(page);
205
206         for (i = 0; i < nr_pages; i++) {
207                 struct page *p = page + i;
208
209                 if (unlikely(!PageCompound(p) |
210                                 (page_private(p) != (unsigned long)page)))
211                         bad_page(page);
212                 __ClearPageCompound(p);
213         }
214 }
215
216 static inline void prep_zero_page(struct page *page, int order, gfp_t gfp_flags)
217 {
218         int i;
219
220         VM_BUG_ON((gfp_flags & (__GFP_WAIT | __GFP_HIGHMEM)) == __GFP_HIGHMEM);
221         /*
222          * clear_highpage() will use KM_USER0, so it's a bug to use __GFP_ZERO
223          * and __GFP_HIGHMEM from hard or soft interrupt context.
224          */
225         VM_BUG_ON((gfp_flags & __GFP_HIGHMEM) && in_interrupt());
226         for (i = 0; i < (1 << order); i++)
227                 clear_highpage(page + i);
228 }
229
230 /*
231  * function for dealing with page's order in buddy system.
232  * zone->lock is already acquired when we use these.
233  * So, we don't need atomic page->flags operations here.
234  */
235 static inline unsigned long page_order(struct page *page)
236 {
237         return page_private(page);
238 }
239
240 static inline void set_page_order(struct page *page, int order)
241 {
242         set_page_private(page, order);
243         __SetPageBuddy(page);
244 }
245
246 static inline void rmv_page_order(struct page *page)
247 {
248         __ClearPageBuddy(page);
249         set_page_private(page, 0);
250 }
251
252 /*
253  * Locate the struct page for both the matching buddy in our
254  * pair (buddy1) and the combined O(n+1) page they form (page).
255  *
256  * 1) Any buddy B1 will have an order O twin B2 which satisfies
257  * the following equation:
258  *     B2 = B1 ^ (1 << O)
259  * For example, if the starting buddy (buddy2) is #8 its order
260  * 1 buddy is #10:
261  *     B2 = 8 ^ (1 << 1) = 8 ^ 2 = 10
262  *
263  * 2) Any buddy B will have an order O+1 parent P which
264  * satisfies the following equation:
265  *     P = B & ~(1 << O)
266  *
267  * Assumption: *_mem_map is contiguous at least up to MAX_ORDER
268  */
269 static inline struct page *
270 __page_find_buddy(struct page *page, unsigned long page_idx, unsigned int order)
271 {
272         unsigned long buddy_idx = page_idx ^ (1 << order);
273
274         return page + (buddy_idx - page_idx);
275 }
276
277 static inline unsigned long
278 __find_combined_index(unsigned long page_idx, unsigned int order)
279 {
280         return (page_idx & ~(1 << order));
281 }
282
283 /*
284  * This function checks whether a page is free && is the buddy
285  * we can do coalesce a page and its buddy if
286  * (a) the buddy is not in a hole &&
287  * (b) the buddy is in the buddy system &&
288  * (c) a page and its buddy have the same order &&
289  * (d) a page and its buddy are in the same zone.
290  *
291  * For recording whether a page is in the buddy system, we use PG_buddy.
292  * Setting, clearing, and testing PG_buddy is serialized by zone->lock.
293  *
294  * For recording page's order, we use page_private(page).
295  */
296 static inline int page_is_buddy(struct page *page, struct page *buddy,
297                                                                 int order)
298 {
299 #ifdef CONFIG_HOLES_IN_ZONE
300         if (!pfn_valid(page_to_pfn(buddy)))
301                 return 0;
302 #endif
303
304         if (page_zone_id(page) != page_zone_id(buddy))
305                 return 0;
306
307         if (PageBuddy(buddy) && page_order(buddy) == order) {
308                 BUG_ON(page_count(buddy) != 0);
309                 return 1;
310         }
311         return 0;
312 }
313
314 /*
315  * Freeing function for a buddy system allocator.
316  *
317  * The concept of a buddy system is to maintain direct-mapped table
318  * (containing bit values) for memory blocks of various "orders".
319  * The bottom level table contains the map for the smallest allocatable
320  * units of memory (here, pages), and each level above it describes
321  * pairs of units from the levels below, hence, "buddies".
322  * At a high level, all that happens here is marking the table entry
323  * at the bottom level available, and propagating the changes upward
324  * as necessary, plus some accounting needed to play nicely with other
325  * parts of the VM system.
326  * At each level, we keep a list of pages, which are heads of continuous
327  * free pages of length of (1 << order) and marked with PG_buddy. Page's
328  * order is recorded in page_private(page) field.
329  * So when we are allocating or freeing one, we can derive the state of the
330  * other.  That is, if we allocate a small block, and both were   
331  * free, the remainder of the region must be split into blocks.   
332  * If a block is freed, and its buddy is also free, then this
333  * triggers coalescing into a block of larger size.            
334  *
335  * -- wli
336  */
337
338 static inline void __free_one_page(struct page *page,
339                 struct zone *zone, unsigned int order)
340 {
341         unsigned long page_idx;
342         int order_size = 1 << order;
343
344         if (unlikely(PageCompound(page)))
345                 destroy_compound_page(page, order);
346
347         page_idx = page_to_pfn(page) & ((1 << MAX_ORDER) - 1);
348
349         VM_BUG_ON(page_idx & (order_size - 1));
350         VM_BUG_ON(bad_range(zone, page));
351
352         zone->free_pages += order_size;
353         while (order < MAX_ORDER-1) {
354                 unsigned long combined_idx;
355                 struct free_area *area;
356                 struct page *buddy;
357
358                 buddy = __page_find_buddy(page, page_idx, order);
359                 if (!page_is_buddy(page, buddy, order))
360                         break;          /* Move the buddy up one level. */
361
362                 list_del(&buddy->lru);
363                 area = zone->free_area + order;
364                 area->nr_free--;
365                 rmv_page_order(buddy);
366                 combined_idx = __find_combined_index(page_idx, order);
367                 page = page + (combined_idx - page_idx);
368                 page_idx = combined_idx;
369                 order++;
370         }
371         set_page_order(page, order);
372         list_add(&page->lru, &zone->free_area[order].free_list);
373         zone->free_area[order].nr_free++;
374 }
375
376 static inline int free_pages_check(struct page *page)
377 {
378         if (unlikely(page_mapcount(page) |
379                 (page->mapping != NULL)  |
380                 (page_count(page) != 0)  |
381                 (page->flags & (
382                         1 << PG_lru     |
383                         1 << PG_private |
384                         1 << PG_locked  |
385                         1 << PG_active  |
386                         1 << PG_reclaim |
387                         1 << PG_slab    |
388                         1 << PG_swapcache |
389                         1 << PG_writeback |
390                         1 << PG_reserved |
391                         1 << PG_buddy ))))
392                 bad_page(page);
393         if (PageDirty(page))
394                 __ClearPageDirty(page);
395         /*
396          * For now, we report if PG_reserved was found set, but do not
397          * clear it, and do not free the page.  But we shall soon need
398          * to do more, for when the ZERO_PAGE count wraps negative.
399          */
400         return PageReserved(page);
401 }
402
403 /*
404  * Frees a list of pages. 
405  * Assumes all pages on list are in same zone, and of same order.
406  * count is the number of pages to free.
407  *
408  * If the zone was previously in an "all pages pinned" state then look to
409  * see if this freeing clears that state.
410  *
411  * And clear the zone's pages_scanned counter, to hold off the "all pages are
412  * pinned" detection logic.
413  */
414 static void free_pages_bulk(struct zone *zone, int count,
415                                         struct list_head *list, int order)
416 {
417         spin_lock(&zone->lock);
418         zone->all_unreclaimable = 0;
419         zone->pages_scanned = 0;
420         while (count--) {
421                 struct page *page;
422
423                 VM_BUG_ON(list_empty(list));
424                 page = list_entry(list->prev, struct page, lru);
425                 /* have to delete it as __free_one_page list manipulates */
426                 list_del(&page->lru);
427                 __free_one_page(page, zone, order);
428         }
429         spin_unlock(&zone->lock);
430 }
431
432 static void free_one_page(struct zone *zone, struct page *page, int order)
433 {
434         LIST_HEAD(list);
435         list_add(&page->lru, &list);
436         free_pages_bulk(zone, 1, &list, order);
437 }
438
439 static void __free_pages_ok(struct page *page, unsigned int order)
440 {
441         unsigned long flags;
442         int i;
443         int reserved = 0;
444
445         arch_free_page(page, order);
446         if (!PageHighMem(page))
447                 debug_check_no_locks_freed(page_address(page),
448                                            PAGE_SIZE<<order);
449
450         for (i = 0 ; i < (1 << order) ; ++i)
451                 reserved += free_pages_check(page + i);
452         if (reserved)
453                 return;
454
455         kernel_map_pages(page, 1 << order, 0);
456         local_irq_save(flags);
457         __count_vm_events(PGFREE, 1 << order);
458         free_one_page(page_zone(page), page, order);
459         local_irq_restore(flags);
460 }
461
462 /*
463  * permit the bootmem allocator to evade page validation on high-order frees
464  */
465 void fastcall __init __free_pages_bootmem(struct page *page, unsigned int order)
466 {
467         if (order == 0) {
468                 __ClearPageReserved(page);
469                 set_page_count(page, 0);
470                 set_page_refcounted(page);
471                 __free_page(page);
472         } else {
473                 int loop;
474
475                 prefetchw(page);
476                 for (loop = 0; loop < BITS_PER_LONG; loop++) {
477                         struct page *p = &page[loop];
478
479                         if (loop + 1 < BITS_PER_LONG)
480                                 prefetchw(p + 1);
481                         __ClearPageReserved(p);
482                         set_page_count(p, 0);
483                 }
484
485                 set_page_refcounted(page);
486                 __free_pages(page, order);
487         }
488 }
489
490
491 /*
492  * The order of subdivision here is critical for the IO subsystem.
493  * Please do not alter this order without good reasons and regression
494  * testing. Specifically, as large blocks of memory are subdivided,
495  * the order in which smaller blocks are delivered depends on the order
496  * they're subdivided in this function. This is the primary factor
497  * influencing the order in which pages are delivered to the IO
498  * subsystem according to empirical testing, and this is also justified
499  * by considering the behavior of a buddy system containing a single
500  * large block of memory acted on by a series of small allocations.
501  * This behavior is a critical factor in sglist merging's success.
502  *
503  * -- wli
504  */
505 static inline void expand(struct zone *zone, struct page *page,
506         int low, int high, struct free_area *area)
507 {
508         unsigned long size = 1 << high;
509
510         while (high > low) {
511                 area--;
512                 high--;
513                 size >>= 1;
514                 VM_BUG_ON(bad_range(zone, &page[size]));
515                 list_add(&page[size].lru, &area->free_list);
516                 area->nr_free++;
517                 set_page_order(&page[size], high);
518         }
519 }
520
521 /*
522  * This page is about to be returned from the page allocator
523  */
524 static int prep_new_page(struct page *page, int order, gfp_t gfp_flags)
525 {
526         if (unlikely(page_mapcount(page) |
527                 (page->mapping != NULL)  |
528                 (page_count(page) != 0)  |
529                 (page->flags & (
530                         1 << PG_lru     |
531                         1 << PG_private |
532                         1 << PG_locked  |
533                         1 << PG_active  |
534                         1 << PG_dirty   |
535                         1 << PG_reclaim |
536                         1 << PG_slab    |
537                         1 << PG_swapcache |
538                         1 << PG_writeback |
539                         1 << PG_reserved |
540                         1 << PG_buddy ))))
541                 bad_page(page);
542
543         /*
544          * For now, we report if PG_reserved was found set, but do not
545          * clear it, and do not allocate the page: as a safety net.
546          */
547         if (PageReserved(page))
548                 return 1;
549
550         page->flags &= ~(1 << PG_uptodate | 1 << PG_error |
551                         1 << PG_referenced | 1 << PG_arch_1 |
552                         1 << PG_checked | 1 << PG_mappedtodisk);
553         set_page_private(page, 0);
554         set_page_refcounted(page);
555         kernel_map_pages(page, 1 << order, 1);
556
557         if (gfp_flags & __GFP_ZERO)
558                 prep_zero_page(page, order, gfp_flags);
559
560         if (order && (gfp_flags & __GFP_COMP))
561                 prep_compound_page(page, order);
562
563         return 0;
564 }
565
566 /* 
567  * Do the hard work of removing an element from the buddy allocator.
568  * Call me with the zone->lock already held.
569  */
570 static struct page *__rmqueue(struct zone *zone, unsigned int order)
571 {
572         struct free_area * area;
573         unsigned int current_order;
574         struct page *page;
575
576         for (current_order = order; current_order < MAX_ORDER; ++current_order) {
577                 area = zone->free_area + current_order;
578                 if (list_empty(&area->free_list))
579                         continue;
580
581                 page = list_entry(area->free_list.next, struct page, lru);
582                 list_del(&page->lru);
583                 rmv_page_order(page);
584                 area->nr_free--;
585                 zone->free_pages -= 1UL << order;
586                 expand(zone, page, order, current_order, area);
587                 return page;
588         }
589
590         return NULL;
591 }
592
593 /* 
594  * Obtain a specified number of elements from the buddy allocator, all under
595  * a single hold of the lock, for efficiency.  Add them to the supplied list.
596  * Returns the number of new pages which were placed at *list.
597  */
598 static int rmqueue_bulk(struct zone *zone, unsigned int order, 
599                         unsigned long count, struct list_head *list)
600 {
601         int i;
602         
603         spin_lock(&zone->lock);
604         for (i = 0; i < count; ++i) {
605                 struct page *page = __rmqueue(zone, order);
606                 if (unlikely(page == NULL))
607                         break;
608                 list_add_tail(&page->lru, list);
609         }
610         spin_unlock(&zone->lock);
611         return i;
612 }
613
614 #ifdef CONFIG_NUMA
615 /*
616  * Called from the slab reaper to drain pagesets on a particular node that
617  * belong to the currently executing processor.
618  * Note that this function must be called with the thread pinned to
619  * a single processor.
620  */
621 void drain_node_pages(int nodeid)
622 {
623         int i, z;
624         unsigned long flags;
625
626         for (z = 0; z < MAX_NR_ZONES; z++) {
627                 struct zone *zone = NODE_DATA(nodeid)->node_zones + z;
628                 struct per_cpu_pageset *pset;
629
630                 pset = zone_pcp(zone, smp_processor_id());
631                 for (i = 0; i < ARRAY_SIZE(pset->pcp); i++) {
632                         struct per_cpu_pages *pcp;
633
634                         pcp = &pset->pcp[i];
635                         if (pcp->count) {
636                                 local_irq_save(flags);
637                                 free_pages_bulk(zone, pcp->count, &pcp->list, 0);
638                                 pcp->count = 0;
639                                 local_irq_restore(flags);
640                         }
641                 }
642         }
643 }
644 #endif
645
646 #if defined(CONFIG_PM) || defined(CONFIG_HOTPLUG_CPU)
647 static void __drain_pages(unsigned int cpu)
648 {
649         unsigned long flags;
650         struct zone *zone;
651         int i;
652
653         for_each_zone(zone) {
654                 struct per_cpu_pageset *pset;
655
656                 pset = zone_pcp(zone, cpu);
657                 for (i = 0; i < ARRAY_SIZE(pset->pcp); i++) {
658                         struct per_cpu_pages *pcp;
659
660                         pcp = &pset->pcp[i];
661                         local_irq_save(flags);
662                         free_pages_bulk(zone, pcp->count, &pcp->list, 0);
663                         pcp->count = 0;
664                         local_irq_restore(flags);
665                 }
666         }
667 }
668 #endif /* CONFIG_PM || CONFIG_HOTPLUG_CPU */
669
670 #ifdef CONFIG_PM
671
672 void mark_free_pages(struct zone *zone)
673 {
674         unsigned long zone_pfn, flags;
675         int order;
676         struct list_head *curr;
677
678         if (!zone->spanned_pages)
679                 return;
680
681         spin_lock_irqsave(&zone->lock, flags);
682         for (zone_pfn = 0; zone_pfn < zone->spanned_pages; ++zone_pfn)
683                 ClearPageNosaveFree(pfn_to_page(zone_pfn + zone->zone_start_pfn));
684
685         for (order = MAX_ORDER - 1; order >= 0; --order)
686                 list_for_each(curr, &zone->free_area[order].free_list) {
687                         unsigned long start_pfn, i;
688
689                         start_pfn = page_to_pfn(list_entry(curr, struct page, lru));
690
691                         for (i=0; i < (1<<order); i++)
692                                 SetPageNosaveFree(pfn_to_page(start_pfn+i));
693         }
694         spin_unlock_irqrestore(&zone->lock, flags);
695 }
696
697 /*
698  * Spill all of this CPU's per-cpu pages back into the buddy allocator.
699  */
700 void drain_local_pages(void)
701 {
702         unsigned long flags;
703
704         local_irq_save(flags);  
705         __drain_pages(smp_processor_id());
706         local_irq_restore(flags);       
707 }
708 #endif /* CONFIG_PM */
709
710 /*
711  * Free a 0-order page
712  */
713 static void fastcall free_hot_cold_page(struct page *page, int cold)
714 {
715         struct zone *zone = page_zone(page);
716         struct per_cpu_pages *pcp;
717         unsigned long flags;
718
719         arch_free_page(page, 0);
720
721         if (PageAnon(page))
722                 page->mapping = NULL;
723         if (free_pages_check(page))
724                 return;
725
726         kernel_map_pages(page, 1, 0);
727
728         pcp = &zone_pcp(zone, get_cpu())->pcp[cold];
729         local_irq_save(flags);
730         __count_vm_event(PGFREE);
731         list_add(&page->lru, &pcp->list);
732         pcp->count++;
733         if (pcp->count >= pcp->high) {
734                 free_pages_bulk(zone, pcp->batch, &pcp->list, 0);
735                 pcp->count -= pcp->batch;
736         }
737         local_irq_restore(flags);
738         put_cpu();
739 }
740
741 void fastcall free_hot_page(struct page *page)
742 {
743         free_hot_cold_page(page, 0);
744 }
745         
746 void fastcall free_cold_page(struct page *page)
747 {
748         free_hot_cold_page(page, 1);
749 }
750
751 /*
752  * split_page takes a non-compound higher-order page, and splits it into
753  * n (1<<order) sub-pages: page[0..n]
754  * Each sub-page must be freed individually.
755  *
756  * Note: this is probably too low level an operation for use in drivers.
757  * Please consult with lkml before using this in your driver.
758  */
759 void split_page(struct page *page, unsigned int order)
760 {
761         int i;
762
763         VM_BUG_ON(PageCompound(page));
764         VM_BUG_ON(!page_count(page));
765         for (i = 1; i < (1 << order); i++)
766                 set_page_refcounted(page + i);
767 }
768
769 /*
770  * Really, prep_compound_page() should be called from __rmqueue_bulk().  But
771  * we cheat by calling it from here, in the order > 0 path.  Saves a branch
772  * or two.
773  */
774 static struct page *buffered_rmqueue(struct zonelist *zonelist,
775                         struct zone *zone, int order, gfp_t gfp_flags)
776 {
777         unsigned long flags;
778         struct page *page;
779         int cold = !!(gfp_flags & __GFP_COLD);
780         int cpu;
781
782 again:
783         cpu  = get_cpu();
784         if (likely(order == 0)) {
785                 struct per_cpu_pages *pcp;
786
787                 pcp = &zone_pcp(zone, cpu)->pcp[cold];
788                 local_irq_save(flags);
789                 if (!pcp->count) {
790                         pcp->count += rmqueue_bulk(zone, 0,
791                                                 pcp->batch, &pcp->list);
792                         if (unlikely(!pcp->count))
793                                 goto failed;
794                 }
795                 page = list_entry(pcp->list.next, struct page, lru);
796                 list_del(&page->lru);
797                 pcp->count--;
798         } else {
799                 spin_lock_irqsave(&zone->lock, flags);
800                 page = __rmqueue(zone, order);
801                 spin_unlock(&zone->lock);
802                 if (!page)
803                         goto failed;
804         }
805
806         __count_zone_vm_events(PGALLOC, zone, 1 << order);
807         zone_statistics(zonelist, zone);
808         local_irq_restore(flags);
809         put_cpu();
810
811         VM_BUG_ON(bad_range(zone, page));
812         if (prep_new_page(page, order, gfp_flags))
813                 goto again;
814         return page;
815
816 failed:
817         local_irq_restore(flags);
818         put_cpu();
819         return NULL;
820 }
821
822 #define ALLOC_NO_WATERMARKS     0x01 /* don't check watermarks at all */
823 #define ALLOC_WMARK_MIN         0x02 /* use pages_min watermark */
824 #define ALLOC_WMARK_LOW         0x04 /* use pages_low watermark */
825 #define ALLOC_WMARK_HIGH        0x08 /* use pages_high watermark */
826 #define ALLOC_HARDER            0x10 /* try to alloc harder */
827 #define ALLOC_HIGH              0x20 /* __GFP_HIGH set */
828 #define ALLOC_CPUSET            0x40 /* check for correct cpuset */
829
830 /*
831  * Return 1 if free pages are above 'mark'. This takes into account the order
832  * of the allocation.
833  */
834 int zone_watermark_ok(struct zone *z, int order, unsigned long mark,
835                       int classzone_idx, int alloc_flags)
836 {
837         /* free_pages my go negative - that's OK */
838         long min = mark, free_pages = z->free_pages - (1 << order) + 1;
839         int o;
840
841         if (alloc_flags & ALLOC_HIGH)
842                 min -= min / 2;
843         if (alloc_flags & ALLOC_HARDER)
844                 min -= min / 4;
845
846         if (free_pages <= min + z->lowmem_reserve[classzone_idx])
847                 return 0;
848         for (o = 0; o < order; o++) {
849                 /* At the next order, this order's pages become unavailable */
850                 free_pages -= z->free_area[o].nr_free << o;
851
852                 /* Require fewer higher order pages to be free */
853                 min >>= 1;
854
855                 if (free_pages <= min)
856                         return 0;
857         }
858         return 1;
859 }
860
861 /*
862  * get_page_from_freeliest goes through the zonelist trying to allocate
863  * a page.
864  */
865 static struct page *
866 get_page_from_freelist(gfp_t gfp_mask, unsigned int order,
867                 struct zonelist *zonelist, int alloc_flags)
868 {
869         struct zone **z = zonelist->zones;
870         struct page *page = NULL;
871         int classzone_idx = zone_idx(*z);
872
873         /*
874          * Go through the zonelist once, looking for a zone with enough free.
875          * See also cpuset_zone_allowed() comment in kernel/cpuset.c.
876          */
877         do {
878                 if ((alloc_flags & ALLOC_CPUSET) &&
879                                 !cpuset_zone_allowed(*z, gfp_mask))
880                         continue;
881
882                 if (!(alloc_flags & ALLOC_NO_WATERMARKS)) {
883                         unsigned long mark;
884                         if (alloc_flags & ALLOC_WMARK_MIN)
885                                 mark = (*z)->pages_min;
886                         else if (alloc_flags & ALLOC_WMARK_LOW)
887                                 mark = (*z)->pages_low;
888                         else
889                                 mark = (*z)->pages_high;
890                         if (!zone_watermark_ok(*z, order, mark,
891                                     classzone_idx, alloc_flags))
892                                 if (!zone_reclaim_mode ||
893                                     !zone_reclaim(*z, gfp_mask, order))
894                                         continue;
895                 }
896
897                 page = buffered_rmqueue(zonelist, *z, order, gfp_mask);
898                 if (page) {
899                         break;
900                 }
901         } while (*(++z) != NULL);
902         return page;
903 }
904
905 /*
906  * This is the 'heart' of the zoned buddy allocator.
907  */
908 struct page * fastcall
909 __alloc_pages(gfp_t gfp_mask, unsigned int order,
910                 struct zonelist *zonelist)
911 {
912         const gfp_t wait = gfp_mask & __GFP_WAIT;
913         struct zone **z;
914         struct page *page;
915         struct reclaim_state reclaim_state;
916         struct task_struct *p = current;
917         int do_retry;
918         int alloc_flags;
919         int did_some_progress;
920
921         might_sleep_if(wait);
922
923 restart:
924         z = zonelist->zones;  /* the list of zones suitable for gfp_mask */
925
926         if (unlikely(*z == NULL)) {
927                 /* Should this ever happen?? */
928                 return NULL;
929         }
930
931         page = get_page_from_freelist(gfp_mask|__GFP_HARDWALL, order,
932                                 zonelist, ALLOC_WMARK_LOW|ALLOC_CPUSET);
933         if (page)
934                 goto got_pg;
935
936         do {
937                 wakeup_kswapd(*z, order);
938         } while (*(++z));
939
940         /*
941          * OK, we're below the kswapd watermark and have kicked background
942          * reclaim. Now things get more complex, so set up alloc_flags according
943          * to how we want to proceed.
944          *
945          * The caller may dip into page reserves a bit more if the caller
946          * cannot run direct reclaim, or if the caller has realtime scheduling
947          * policy or is asking for __GFP_HIGH memory.  GFP_ATOMIC requests will
948          * set both ALLOC_HARDER (!wait) and ALLOC_HIGH (__GFP_HIGH).
949          */
950         alloc_flags = ALLOC_WMARK_MIN;
951         if ((unlikely(rt_task(p)) && !in_interrupt()) || !wait)
952                 alloc_flags |= ALLOC_HARDER;
953         if (gfp_mask & __GFP_HIGH)
954                 alloc_flags |= ALLOC_HIGH;
955         if (wait)
956                 alloc_flags |= ALLOC_CPUSET;
957
958         /*
959          * Go through the zonelist again. Let __GFP_HIGH and allocations
960          * coming from realtime tasks go deeper into reserves.
961          *
962          * This is the last chance, in general, before the goto nopage.
963          * Ignore cpuset if GFP_ATOMIC (!wait) rather than fail alloc.
964          * See also cpuset_zone_allowed() comment in kernel/cpuset.c.
965          */
966         page = get_page_from_freelist(gfp_mask, order, zonelist, alloc_flags);
967         if (page)
968                 goto got_pg;
969
970         /* This allocation should allow future memory freeing. */
971
972         if (((p->flags & PF_MEMALLOC) || unlikely(test_thread_flag(TIF_MEMDIE)))
973                         && !in_interrupt()) {
974                 if (!(gfp_mask & __GFP_NOMEMALLOC)) {
975 nofail_alloc:
976                         /* go through the zonelist yet again, ignoring mins */
977                         page = get_page_from_freelist(gfp_mask, order,
978                                 zonelist, ALLOC_NO_WATERMARKS);
979                         if (page)
980                                 goto got_pg;
981                         if (gfp_mask & __GFP_NOFAIL) {
982                                 blk_congestion_wait(WRITE, HZ/50);
983                                 goto nofail_alloc;
984                         }
985                 }
986                 goto nopage;
987         }
988
989         /* Atomic allocations - we can't balance anything */
990         if (!wait)
991                 goto nopage;
992
993 rebalance:
994         cond_resched();
995
996         /* We now go into synchronous reclaim */
997         cpuset_memory_pressure_bump();
998         p->flags |= PF_MEMALLOC;
999         reclaim_state.reclaimed_slab = 0;
1000         p->reclaim_state = &reclaim_state;
1001
1002         did_some_progress = try_to_free_pages(zonelist->zones, gfp_mask);
1003
1004         p->reclaim_state = NULL;
1005         p->flags &= ~PF_MEMALLOC;
1006
1007         cond_resched();
1008
1009         if (likely(did_some_progress)) {
1010                 page = get_page_from_freelist(gfp_mask, order,
1011                                                 zonelist, alloc_flags);
1012                 if (page)
1013                         goto got_pg;
1014         } else if ((gfp_mask & __GFP_FS) && !(gfp_mask & __GFP_NORETRY)) {
1015                 /*
1016                  * Go through the zonelist yet one more time, keep
1017                  * very high watermark here, this is only to catch
1018                  * a parallel oom killing, we must fail if we're still
1019                  * under heavy pressure.
1020                  */
1021                 page = get_page_from_freelist(gfp_mask|__GFP_HARDWALL, order,
1022                                 zonelist, ALLOC_WMARK_HIGH|ALLOC_CPUSET);
1023                 if (page)
1024                         goto got_pg;
1025
1026                 out_of_memory(zonelist, gfp_mask, order);
1027                 goto restart;
1028         }
1029
1030         /*
1031          * Don't let big-order allocations loop unless the caller explicitly
1032          * requests that.  Wait for some write requests to complete then retry.
1033          *
1034          * In this implementation, __GFP_REPEAT means __GFP_NOFAIL for order
1035          * <= 3, but that may not be true in other implementations.
1036          */
1037         do_retry = 0;
1038         if (!(gfp_mask & __GFP_NORETRY)) {
1039                 if ((order <= 3) || (gfp_mask & __GFP_REPEAT))
1040                         do_retry = 1;
1041                 if (gfp_mask & __GFP_NOFAIL)
1042                         do_retry = 1;
1043         }
1044         if (do_retry) {
1045                 blk_congestion_wait(WRITE, HZ/50);
1046                 goto rebalance;
1047         }
1048
1049 nopage:
1050         if (!(gfp_mask & __GFP_NOWARN) && printk_ratelimit()) {
1051                 printk(KERN_WARNING "%s: page allocation failure."
1052                         " order:%d, mode:0x%x\n",
1053                         p->comm, order, gfp_mask);
1054                 dump_stack();
1055                 show_mem();
1056         }
1057 got_pg:
1058         return page;
1059 }
1060
1061 EXPORT_SYMBOL(__alloc_pages);
1062
1063 /*
1064  * Common helper functions.
1065  */
1066 fastcall unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order)
1067 {
1068         struct page * page;
1069         page = alloc_pages(gfp_mask, order);
1070         if (!page)
1071                 return 0;
1072         return (unsigned long) page_address(page);
1073 }
1074
1075 EXPORT_SYMBOL(__get_free_pages);
1076
1077 fastcall unsigned long get_zeroed_page(gfp_t gfp_mask)
1078 {
1079         struct page * page;
1080
1081         /*
1082          * get_zeroed_page() returns a 32-bit address, which cannot represent
1083          * a highmem page
1084          */
1085         VM_BUG_ON((gfp_mask & __GFP_HIGHMEM) != 0);
1086
1087         page = alloc_pages(gfp_mask | __GFP_ZERO, 0);
1088         if (page)
1089                 return (unsigned long) page_address(page);
1090         return 0;
1091 }
1092
1093 EXPORT_SYMBOL(get_zeroed_page);
1094
1095 void __pagevec_free(struct pagevec *pvec)
1096 {
1097         int i = pagevec_count(pvec);
1098
1099         while (--i >= 0)
1100                 free_hot_cold_page(pvec->pages[i], pvec->cold);
1101 }
1102
1103 fastcall void __free_pages(struct page *page, unsigned int order)
1104 {
1105         if (put_page_testzero(page)) {
1106                 if (order == 0)
1107                         free_hot_page(page);
1108                 else
1109                         __free_pages_ok(page, order);
1110         }
1111 }
1112
1113 EXPORT_SYMBOL(__free_pages);
1114
1115 fastcall void free_pages(unsigned long addr, unsigned int order)
1116 {
1117         if (addr != 0) {
1118                 VM_BUG_ON(!virt_addr_valid((void *)addr));
1119                 __free_pages(virt_to_page((void *)addr), order);
1120         }
1121 }
1122
1123 EXPORT_SYMBOL(free_pages);
1124
1125 /*
1126  * Total amount of free (allocatable) RAM:
1127  */
1128 unsigned int nr_free_pages(void)
1129 {
1130         unsigned int sum = 0;
1131         struct zone *zone;
1132
1133         for_each_zone(zone)
1134                 sum += zone->free_pages;
1135
1136         return sum;
1137 }
1138
1139 EXPORT_SYMBOL(nr_free_pages);
1140
1141 #ifdef CONFIG_NUMA
1142 unsigned int nr_free_pages_pgdat(pg_data_t *pgdat)
1143 {
1144         unsigned int i, sum = 0;
1145
1146         for (i = 0; i < MAX_NR_ZONES; i++)
1147                 sum += pgdat->node_zones[i].free_pages;
1148
1149         return sum;
1150 }
1151 #endif
1152
1153 static unsigned int nr_free_zone_pages(int offset)
1154 {
1155         /* Just pick one node, since fallback list is circular */
1156         pg_data_t *pgdat = NODE_DATA(numa_node_id());
1157         unsigned int sum = 0;
1158
1159         struct zonelist *zonelist = pgdat->node_zonelists + offset;
1160         struct zone **zonep = zonelist->zones;
1161         struct zone *zone;
1162
1163         for (zone = *zonep++; zone; zone = *zonep++) {
1164                 unsigned long size = zone->present_pages;
1165                 unsigned long high = zone->pages_high;
1166                 if (size > high)
1167                         sum += size - high;
1168         }
1169
1170         return sum;
1171 }
1172
1173 /*
1174  * Amount of free RAM allocatable within ZONE_DMA and ZONE_NORMAL
1175  */
1176 unsigned int nr_free_buffer_pages(void)
1177 {
1178         return nr_free_zone_pages(gfp_zone(GFP_USER));
1179 }
1180
1181 /*
1182  * Amount of free RAM allocatable within all zones
1183  */
1184 unsigned int nr_free_pagecache_pages(void)
1185 {
1186         return nr_free_zone_pages(gfp_zone(GFP_HIGHUSER));
1187 }
1188
1189 #ifdef CONFIG_HIGHMEM
1190 unsigned int nr_free_highpages (void)
1191 {
1192         pg_data_t *pgdat;
1193         unsigned int pages = 0;
1194
1195         for_each_online_pgdat(pgdat)
1196                 pages += pgdat->node_zones[ZONE_HIGHMEM].free_pages;
1197
1198         return pages;
1199 }
1200 #endif
1201
1202 #ifdef CONFIG_NUMA
1203 static void show_node(struct zone *zone)
1204 {
1205         printk("Node %d ", zone->zone_pgdat->node_id);
1206 }
1207 #else
1208 #define show_node(zone) do { } while (0)
1209 #endif
1210
1211 void si_meminfo(struct sysinfo *val)
1212 {
1213         val->totalram = totalram_pages;
1214         val->sharedram = 0;
1215         val->freeram = nr_free_pages();
1216         val->bufferram = nr_blockdev_pages();
1217 #ifdef CONFIG_HIGHMEM
1218         val->totalhigh = totalhigh_pages;
1219         val->freehigh = nr_free_highpages();
1220 #else
1221         val->totalhigh = 0;
1222         val->freehigh = 0;
1223 #endif
1224         val->mem_unit = PAGE_SIZE;
1225 }
1226
1227 EXPORT_SYMBOL(si_meminfo);
1228
1229 #ifdef CONFIG_NUMA
1230 void si_meminfo_node(struct sysinfo *val, int nid)
1231 {
1232         pg_data_t *pgdat = NODE_DATA(nid);
1233
1234         val->totalram = pgdat->node_present_pages;
1235         val->freeram = nr_free_pages_pgdat(pgdat);
1236         val->totalhigh = pgdat->node_zones[ZONE_HIGHMEM].present_pages;
1237         val->freehigh = pgdat->node_zones[ZONE_HIGHMEM].free_pages;
1238         val->mem_unit = PAGE_SIZE;
1239 }
1240 #endif
1241
1242 #define K(x) ((x) << (PAGE_SHIFT-10))
1243
1244 /*
1245  * Show free area list (used inside shift_scroll-lock stuff)
1246  * We also calculate the percentage fragmentation. We do this by counting the
1247  * memory on each free list with the exception of the first item on the list.
1248  */
1249 void show_free_areas(void)
1250 {
1251         int cpu, temperature;
1252         unsigned long active;
1253         unsigned long inactive;
1254         unsigned long free;
1255         struct zone *zone;
1256
1257         for_each_zone(zone) {
1258                 show_node(zone);
1259                 printk("%s per-cpu:", zone->name);
1260
1261                 if (!populated_zone(zone)) {
1262                         printk(" empty\n");
1263                         continue;
1264                 } else
1265                         printk("\n");
1266
1267                 for_each_online_cpu(cpu) {
1268                         struct per_cpu_pageset *pageset;
1269
1270                         pageset = zone_pcp(zone, cpu);
1271
1272                         for (temperature = 0; temperature < 2; temperature++)
1273                                 printk("cpu %d %s: high %d, batch %d used:%d\n",
1274                                         cpu,
1275                                         temperature ? "cold" : "hot",
1276                                         pageset->pcp[temperature].high,
1277                                         pageset->pcp[temperature].batch,
1278                                         pageset->pcp[temperature].count);
1279                 }
1280         }
1281
1282         get_zone_counts(&active, &inactive, &free);
1283
1284         printk("Active:%lu inactive:%lu dirty:%lu writeback:%lu "
1285                 "unstable:%lu free:%u slab:%lu mapped:%lu pagetables:%lu\n",
1286                 active,
1287                 inactive,
1288                 global_page_state(NR_FILE_DIRTY),
1289                 global_page_state(NR_WRITEBACK),
1290                 global_page_state(NR_UNSTABLE_NFS),
1291                 nr_free_pages(),
1292                 global_page_state(NR_SLAB),
1293                 global_page_state(NR_FILE_MAPPED),
1294                 global_page_state(NR_PAGETABLE));
1295
1296         for_each_zone(zone) {
1297                 int i;
1298
1299                 show_node(zone);
1300                 printk("%s"
1301                         " free:%lukB"
1302                         " min:%lukB"
1303                         " low:%lukB"
1304                         " high:%lukB"
1305                         " active:%lukB"
1306                         " inactive:%lukB"
1307                         " present:%lukB"
1308                         " pages_scanned:%lu"
1309                         " all_unreclaimable? %s"
1310                         "\n",
1311                         zone->name,
1312                         K(zone->free_pages),
1313                         K(zone->pages_min),
1314                         K(zone->pages_low),
1315                         K(zone->pages_high),
1316                         K(zone->nr_active),
1317                         K(zone->nr_inactive),
1318                         K(zone->present_pages),
1319                         zone->pages_scanned,
1320                         (zone->all_unreclaimable ? "yes" : "no")
1321                         );
1322                 printk("lowmem_reserve[]:");
1323                 for (i = 0; i < MAX_NR_ZONES; i++)
1324                         printk(" %lu", zone->lowmem_reserve[i]);
1325                 printk("\n");
1326         }
1327
1328         for_each_zone(zone) {
1329                 unsigned long nr[MAX_ORDER], flags, order, total = 0;
1330
1331                 show_node(zone);
1332                 printk("%s: ", zone->name);
1333                 if (!populated_zone(zone)) {
1334                         printk("empty\n");
1335                         continue;
1336                 }
1337
1338                 spin_lock_irqsave(&zone->lock, flags);
1339                 for (order = 0; order < MAX_ORDER; order++) {
1340                         nr[order] = zone->free_area[order].nr_free;
1341                         total += nr[order] << order;
1342                 }
1343                 spin_unlock_irqrestore(&zone->lock, flags);
1344                 for (order = 0; order < MAX_ORDER; order++)
1345                         printk("%lu*%lukB ", nr[order], K(1UL) << order);
1346                 printk("= %lukB\n", K(total));
1347         }
1348
1349         show_swap_cache_info();
1350 }
1351
1352 /*
1353  * Builds allocation fallback zone lists.
1354  *
1355  * Add all populated zones of a node to the zonelist.
1356  */
1357 static int __meminit build_zonelists_node(pg_data_t *pgdat,
1358                         struct zonelist *zonelist, int nr_zones, int zone_type)
1359 {
1360         struct zone *zone;
1361
1362         BUG_ON(zone_type > ZONE_HIGHMEM);
1363
1364         do {
1365                 zone = pgdat->node_zones + zone_type;
1366                 if (populated_zone(zone)) {
1367 #ifndef CONFIG_HIGHMEM
1368                         BUG_ON(zone_type > ZONE_NORMAL);
1369 #endif
1370                         zonelist->zones[nr_zones++] = zone;
1371                         check_highest_zone(zone_type);
1372                 }
1373                 zone_type--;
1374
1375         } while (zone_type >= 0);
1376         return nr_zones;
1377 }
1378
1379 static inline int highest_zone(int zone_bits)
1380 {
1381         int res = ZONE_NORMAL;
1382         if (zone_bits & (__force int)__GFP_HIGHMEM)
1383                 res = ZONE_HIGHMEM;
1384         if (zone_bits & (__force int)__GFP_DMA32)
1385                 res = ZONE_DMA32;
1386         if (zone_bits & (__force int)__GFP_DMA)
1387                 res = ZONE_DMA;
1388         return res;
1389 }
1390
1391 #ifdef CONFIG_NUMA
1392 #define MAX_NODE_LOAD (num_online_nodes())
1393 static int __meminitdata node_load[MAX_NUMNODES];
1394 /**
1395  * find_next_best_node - find the next node that should appear in a given node's fallback list
1396  * @node: node whose fallback list we're appending
1397  * @used_node_mask: nodemask_t of already used nodes
1398  *
1399  * We use a number of factors to determine which is the next node that should
1400  * appear on a given node's fallback list.  The node should not have appeared
1401  * already in @node's fallback list, and it should be the next closest node
1402  * according to the distance array (which contains arbitrary distance values
1403  * from each node to each node in the system), and should also prefer nodes
1404  * with no CPUs, since presumably they'll have very little allocation pressure
1405  * on them otherwise.
1406  * It returns -1 if no node is found.
1407  */
1408 static int __meminit find_next_best_node(int node, nodemask_t *used_node_mask)
1409 {
1410         int n, val;
1411         int min_val = INT_MAX;
1412         int best_node = -1;
1413
1414         /* Use the local node if we haven't already */
1415         if (!node_isset(node, *used_node_mask)) {
1416                 node_set(node, *used_node_mask);
1417                 return node;
1418         }
1419
1420         for_each_online_node(n) {
1421                 cpumask_t tmp;
1422
1423                 /* Don't want a node to appear more than once */
1424                 if (node_isset(n, *used_node_mask))
1425                         continue;
1426
1427                 /* Use the distance array to find the distance */
1428                 val = node_distance(node, n);
1429
1430                 /* Penalize nodes under us ("prefer the next node") */
1431                 val += (n < node);
1432
1433                 /* Give preference to headless and unused nodes */
1434                 tmp = node_to_cpumask(n);
1435                 if (!cpus_empty(tmp))
1436                         val += PENALTY_FOR_NODE_WITH_CPUS;
1437
1438                 /* Slight preference for less loaded node */
1439                 val *= (MAX_NODE_LOAD*MAX_NUMNODES);
1440                 val += node_load[n];
1441
1442                 if (val < min_val) {
1443                         min_val = val;
1444                         best_node = n;
1445                 }
1446         }
1447
1448         if (best_node >= 0)
1449                 node_set(best_node, *used_node_mask);
1450
1451         return best_node;
1452 }
1453
1454 static void __meminit build_zonelists(pg_data_t *pgdat)
1455 {
1456         int i, j, k, node, local_node;
1457         int prev_node, load;
1458         struct zonelist *zonelist;
1459         nodemask_t used_mask;
1460
1461         /* initialize zonelists */
1462         for (i = 0; i < GFP_ZONETYPES; i++) {
1463                 zonelist = pgdat->node_zonelists + i;
1464                 zonelist->zones[0] = NULL;
1465         }
1466
1467         /* NUMA-aware ordering of nodes */
1468         local_node = pgdat->node_id;
1469         load = num_online_nodes();
1470         prev_node = local_node;
1471         nodes_clear(used_mask);
1472         while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
1473                 int distance = node_distance(local_node, node);
1474
1475                 /*
1476                  * If another node is sufficiently far away then it is better
1477                  * to reclaim pages in a zone before going off node.
1478                  */
1479                 if (distance > RECLAIM_DISTANCE)
1480                         zone_reclaim_mode = 1;
1481
1482                 /*
1483                  * We don't want to pressure a particular node.
1484                  * So adding penalty to the first node in same
1485                  * distance group to make it round-robin.
1486                  */
1487
1488                 if (distance != node_distance(local_node, prev_node))
1489                         node_load[node] += load;
1490                 prev_node = node;
1491                 load--;
1492                 for (i = 0; i < GFP_ZONETYPES; i++) {
1493                         zonelist = pgdat->node_zonelists + i;
1494                         for (j = 0; zonelist->zones[j] != NULL; j++);
1495
1496                         k = highest_zone(i);
1497
1498                         j = build_zonelists_node(NODE_DATA(node), zonelist, j, k);
1499                         zonelist->zones[j] = NULL;
1500                 }
1501         }
1502 }
1503
1504 #else   /* CONFIG_NUMA */
1505
1506 static void __meminit build_zonelists(pg_data_t *pgdat)
1507 {
1508         int i, j, k, node, local_node;
1509
1510         local_node = pgdat->node_id;
1511         for (i = 0; i < GFP_ZONETYPES; i++) {
1512                 struct zonelist *zonelist;
1513
1514                 zonelist = pgdat->node_zonelists + i;
1515
1516                 j = 0;
1517                 k = highest_zone(i);
1518                 j = build_zonelists_node(pgdat, zonelist, j, k);
1519                 /*
1520                  * Now we build the zonelist so that it contains the zones
1521                  * of all the other nodes.
1522                  * We don't want to pressure a particular node, so when
1523                  * building the zones for node N, we make sure that the
1524                  * zones coming right after the local ones are those from
1525                  * node N+1 (modulo N)
1526                  */
1527                 for (node = local_node + 1; node < MAX_NUMNODES; node++) {
1528                         if (!node_online(node))
1529                                 continue;
1530                         j = build_zonelists_node(NODE_DATA(node), zonelist, j, k);
1531                 }
1532                 for (node = 0; node < local_node; node++) {
1533                         if (!node_online(node))
1534                                 continue;
1535                         j = build_zonelists_node(NODE_DATA(node), zonelist, j, k);
1536                 }
1537
1538                 zonelist->zones[j] = NULL;
1539         }
1540 }
1541
1542 #endif  /* CONFIG_NUMA */
1543
1544 /* return values int ....just for stop_machine_run() */
1545 static int __meminit __build_all_zonelists(void *dummy)
1546 {
1547         int nid;
1548         for_each_online_node(nid)
1549                 build_zonelists(NODE_DATA(nid));
1550         return 0;
1551 }
1552
1553 void __meminit build_all_zonelists(void)
1554 {
1555         if (system_state == SYSTEM_BOOTING) {
1556                 __build_all_zonelists(0);
1557                 cpuset_init_current_mems_allowed();
1558         } else {
1559                 /* we have to stop all cpus to guaranntee there is no user
1560                    of zonelist */
1561                 stop_machine_run(__build_all_zonelists, NULL, NR_CPUS);
1562                 /* cpuset refresh routine should be here */
1563         }
1564         vm_total_pages = nr_free_pagecache_pages();
1565         printk("Built %i zonelists.  Total pages: %ld\n",
1566                         num_online_nodes(), vm_total_pages);
1567 }
1568
1569 /*
1570  * Helper functions to size the waitqueue hash table.
1571  * Essentially these want to choose hash table sizes sufficiently
1572  * large so that collisions trying to wait on pages are rare.
1573  * But in fact, the number of active page waitqueues on typical
1574  * systems is ridiculously low, less than 200. So this is even
1575  * conservative, even though it seems large.
1576  *
1577  * The constant PAGES_PER_WAITQUEUE specifies the ratio of pages to
1578  * waitqueues, i.e. the size of the waitq table given the number of pages.
1579  */
1580 #define PAGES_PER_WAITQUEUE     256
1581
1582 #ifndef CONFIG_MEMORY_HOTPLUG
1583 static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
1584 {
1585         unsigned long size = 1;
1586
1587         pages /= PAGES_PER_WAITQUEUE;
1588
1589         while (size < pages)
1590                 size <<= 1;
1591
1592         /*
1593          * Once we have dozens or even hundreds of threads sleeping
1594          * on IO we've got bigger problems than wait queue collision.
1595          * Limit the size of the wait table to a reasonable size.
1596          */
1597         size = min(size, 4096UL);
1598
1599         return max(size, 4UL);
1600 }
1601 #else
1602 /*
1603  * A zone's size might be changed by hot-add, so it is not possible to determine
1604  * a suitable size for its wait_table.  So we use the maximum size now.
1605  *
1606  * The max wait table size = 4096 x sizeof(wait_queue_head_t).   ie:
1607  *
1608  *    i386 (preemption config)    : 4096 x 16 = 64Kbyte.
1609  *    ia64, x86-64 (no preemption): 4096 x 20 = 80Kbyte.
1610  *    ia64, x86-64 (preemption)   : 4096 x 24 = 96Kbyte.
1611  *
1612  * The maximum entries are prepared when a zone's memory is (512K + 256) pages
1613  * or more by the traditional way. (See above).  It equals:
1614  *
1615  *    i386, x86-64, powerpc(4K page size) : =  ( 2G + 1M)byte.
1616  *    ia64(16K page size)                 : =  ( 8G + 4M)byte.
1617  *    powerpc (64K page size)             : =  (32G +16M)byte.
1618  */
1619 static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
1620 {
1621         return 4096UL;
1622 }
1623 #endif
1624
1625 /*
1626  * This is an integer logarithm so that shifts can be used later
1627  * to extract the more random high bits from the multiplicative
1628  * hash function before the remainder is taken.
1629  */
1630 static inline unsigned long wait_table_bits(unsigned long size)
1631 {
1632         return ffz(~size);
1633 }
1634
1635 #define LONG_ALIGN(x) (((x)+(sizeof(long))-1)&~((sizeof(long))-1))
1636
1637 static void __init calculate_zone_totalpages(struct pglist_data *pgdat,
1638                 unsigned long *zones_size, unsigned long *zholes_size)
1639 {
1640         unsigned long realtotalpages, totalpages = 0;
1641         int i;
1642
1643         for (i = 0; i < MAX_NR_ZONES; i++)
1644                 totalpages += zones_size[i];
1645         pgdat->node_spanned_pages = totalpages;
1646
1647         realtotalpages = totalpages;
1648         if (zholes_size)
1649                 for (i = 0; i < MAX_NR_ZONES; i++)
1650                         realtotalpages -= zholes_size[i];
1651         pgdat->node_present_pages = realtotalpages;
1652         printk(KERN_DEBUG "On node %d totalpages: %lu\n", pgdat->node_id, realtotalpages);
1653 }
1654
1655
1656 /*
1657  * Initially all pages are reserved - free ones are freed
1658  * up by free_all_bootmem() once the early boot process is
1659  * done. Non-atomic initialization, single-pass.
1660  */
1661 void __meminit memmap_init_zone(unsigned long size, int nid, unsigned long zone,
1662                 unsigned long start_pfn)
1663 {
1664         struct page *page;
1665         unsigned long end_pfn = start_pfn + size;
1666         unsigned long pfn;
1667
1668         for (pfn = start_pfn; pfn < end_pfn; pfn++) {
1669                 if (!early_pfn_valid(pfn))
1670                         continue;
1671                 page = pfn_to_page(pfn);
1672                 set_page_links(page, zone, nid, pfn);
1673                 init_page_count(page);
1674                 reset_page_mapcount(page);
1675                 SetPageReserved(page);
1676                 INIT_LIST_HEAD(&page->lru);
1677 #ifdef WANT_PAGE_VIRTUAL
1678                 /* The shift won't overflow because ZONE_NORMAL is below 4G. */
1679                 if (!is_highmem_idx(zone))
1680                         set_page_address(page, __va(pfn << PAGE_SHIFT));
1681 #endif
1682         }
1683 }
1684
1685 void zone_init_free_lists(struct pglist_data *pgdat, struct zone *zone,
1686                                 unsigned long size)
1687 {
1688         int order;
1689         for (order = 0; order < MAX_ORDER ; order++) {
1690                 INIT_LIST_HEAD(&zone->free_area[order].free_list);
1691                 zone->free_area[order].nr_free = 0;
1692         }
1693 }
1694
1695 #define ZONETABLE_INDEX(x, zone_nr)     ((x << ZONES_SHIFT) | zone_nr)
1696 void zonetable_add(struct zone *zone, int nid, int zid, unsigned long pfn,
1697                 unsigned long size)
1698 {
1699         unsigned long snum = pfn_to_section_nr(pfn);
1700         unsigned long end = pfn_to_section_nr(pfn + size);
1701
1702         if (FLAGS_HAS_NODE)
1703                 zone_table[ZONETABLE_INDEX(nid, zid)] = zone;
1704         else
1705                 for (; snum <= end; snum++)
1706                         zone_table[ZONETABLE_INDEX(snum, zid)] = zone;
1707 }
1708
1709 #ifndef __HAVE_ARCH_MEMMAP_INIT
1710 #define memmap_init(size, nid, zone, start_pfn) \
1711         memmap_init_zone((size), (nid), (zone), (start_pfn))
1712 #endif
1713
1714 static int __cpuinit zone_batchsize(struct zone *zone)
1715 {
1716         int batch;
1717
1718         /*
1719          * The per-cpu-pages pools are set to around 1000th of the
1720          * size of the zone.  But no more than 1/2 of a meg.
1721          *
1722          * OK, so we don't know how big the cache is.  So guess.
1723          */
1724         batch = zone->present_pages / 1024;
1725         if (batch * PAGE_SIZE > 512 * 1024)
1726                 batch = (512 * 1024) / PAGE_SIZE;
1727         batch /= 4;             /* We effectively *= 4 below */
1728         if (batch < 1)
1729                 batch = 1;
1730
1731         /*
1732          * Clamp the batch to a 2^n - 1 value. Having a power
1733          * of 2 value was found to be more likely to have
1734          * suboptimal cache aliasing properties in some cases.
1735          *
1736          * For example if 2 tasks are alternately allocating
1737          * batches of pages, one task can end up with a lot
1738          * of pages of one half of the possible page colors
1739          * and the other with pages of the other colors.
1740          */
1741         batch = (1 << (fls(batch + batch/2)-1)) - 1;
1742
1743         return batch;
1744 }
1745
1746 inline void setup_pageset(struct per_cpu_pageset *p, unsigned long batch)
1747 {
1748         struct per_cpu_pages *pcp;
1749
1750         memset(p, 0, sizeof(*p));
1751
1752         pcp = &p->pcp[0];               /* hot */
1753         pcp->count = 0;
1754         pcp->high = 6 * batch;
1755         pcp->batch = max(1UL, 1 * batch);
1756         INIT_LIST_HEAD(&pcp->list);
1757
1758         pcp = &p->pcp[1];               /* cold*/
1759         pcp->count = 0;
1760         pcp->high = 2 * batch;
1761         pcp->batch = max(1UL, batch/2);
1762         INIT_LIST_HEAD(&pcp->list);
1763 }
1764
1765 /*
1766  * setup_pagelist_highmark() sets the high water mark for hot per_cpu_pagelist
1767  * to the value high for the pageset p.
1768  */
1769
1770 static void setup_pagelist_highmark(struct per_cpu_pageset *p,
1771                                 unsigned long high)
1772 {
1773         struct per_cpu_pages *pcp;
1774
1775         pcp = &p->pcp[0]; /* hot list */
1776         pcp->high = high;
1777         pcp->batch = max(1UL, high/4);
1778         if ((high/4) > (PAGE_SHIFT * 8))
1779                 pcp->batch = PAGE_SHIFT * 8;
1780 }
1781
1782
1783 #ifdef CONFIG_NUMA
1784 /*
1785  * Boot pageset table. One per cpu which is going to be used for all
1786  * zones and all nodes. The parameters will be set in such a way
1787  * that an item put on a list will immediately be handed over to
1788  * the buddy list. This is safe since pageset manipulation is done
1789  * with interrupts disabled.
1790  *
1791  * Some NUMA counter updates may also be caught by the boot pagesets.
1792  *
1793  * The boot_pagesets must be kept even after bootup is complete for
1794  * unused processors and/or zones. They do play a role for bootstrapping
1795  * hotplugged processors.
1796  *
1797  * zoneinfo_show() and maybe other functions do
1798  * not check if the processor is online before following the pageset pointer.
1799  * Other parts of the kernel may not check if the zone is available.
1800  */
1801 static struct per_cpu_pageset boot_pageset[NR_CPUS];
1802
1803 /*
1804  * Dynamically allocate memory for the
1805  * per cpu pageset array in struct zone.
1806  */
1807 static int __cpuinit process_zones(int cpu)
1808 {
1809         struct zone *zone, *dzone;
1810
1811         for_each_zone(zone) {
1812
1813                 zone_pcp(zone, cpu) = kmalloc_node(sizeof(struct per_cpu_pageset),
1814                                          GFP_KERNEL, cpu_to_node(cpu));
1815                 if (!zone_pcp(zone, cpu))
1816                         goto bad;
1817
1818                 setup_pageset(zone_pcp(zone, cpu), zone_batchsize(zone));
1819
1820                 if (percpu_pagelist_fraction)
1821                         setup_pagelist_highmark(zone_pcp(zone, cpu),
1822                                 (zone->present_pages / percpu_pagelist_fraction));
1823         }
1824
1825         return 0;
1826 bad:
1827         for_each_zone(dzone) {
1828                 if (dzone == zone)
1829                         break;
1830                 kfree(zone_pcp(dzone, cpu));
1831                 zone_pcp(dzone, cpu) = NULL;
1832         }
1833         return -ENOMEM;
1834 }
1835
1836 static inline void free_zone_pagesets(int cpu)
1837 {
1838         struct zone *zone;
1839
1840         for_each_zone(zone) {
1841                 struct per_cpu_pageset *pset = zone_pcp(zone, cpu);
1842
1843                 /* Free per_cpu_pageset if it is slab allocated */
1844                 if (pset != &boot_pageset[cpu])
1845                         kfree(pset);
1846                 zone_pcp(zone, cpu) = NULL;
1847         }
1848 }
1849
1850 static int __cpuinit pageset_cpuup_callback(struct notifier_block *nfb,
1851                 unsigned long action,
1852                 void *hcpu)
1853 {
1854         int cpu = (long)hcpu;
1855         int ret = NOTIFY_OK;
1856
1857         switch (action) {
1858                 case CPU_UP_PREPARE:
1859                         if (process_zones(cpu))
1860                                 ret = NOTIFY_BAD;
1861                         break;
1862                 case CPU_UP_CANCELED:
1863                 case CPU_DEAD:
1864                         free_zone_pagesets(cpu);
1865                         break;
1866                 default:
1867                         break;
1868         }
1869         return ret;
1870 }
1871
1872 static struct notifier_block __cpuinitdata pageset_notifier =
1873         { &pageset_cpuup_callback, NULL, 0 };
1874
1875 void __init setup_per_cpu_pageset(void)
1876 {
1877         int err;
1878
1879         /* Initialize per_cpu_pageset for cpu 0.
1880          * A cpuup callback will do this for every cpu
1881          * as it comes online
1882          */
1883         err = process_zones(smp_processor_id());
1884         BUG_ON(err);
1885         register_cpu_notifier(&pageset_notifier);
1886 }
1887
1888 #endif
1889
1890 static __meminit
1891 int zone_wait_table_init(struct zone *zone, unsigned long zone_size_pages)
1892 {
1893         int i;
1894         struct pglist_data *pgdat = zone->zone_pgdat;
1895         size_t alloc_size;
1896
1897         /*
1898          * The per-page waitqueue mechanism uses hashed waitqueues
1899          * per zone.
1900          */
1901         zone->wait_table_hash_nr_entries =
1902                  wait_table_hash_nr_entries(zone_size_pages);
1903         zone->wait_table_bits =
1904                 wait_table_bits(zone->wait_table_hash_nr_entries);
1905         alloc_size = zone->wait_table_hash_nr_entries
1906                                         * sizeof(wait_queue_head_t);
1907
1908         if (system_state == SYSTEM_BOOTING) {
1909                 zone->wait_table = (wait_queue_head_t *)
1910                         alloc_bootmem_node(pgdat, alloc_size);
1911         } else {
1912                 /*
1913                  * This case means that a zone whose size was 0 gets new memory
1914                  * via memory hot-add.
1915                  * But it may be the case that a new node was hot-added.  In
1916                  * this case vmalloc() will not be able to use this new node's
1917                  * memory - this wait_table must be initialized to use this new
1918                  * node itself as well.
1919                  * To use this new node's memory, further consideration will be
1920                  * necessary.
1921                  */
1922                 zone->wait_table = (wait_queue_head_t *)vmalloc(alloc_size);
1923         }
1924         if (!zone->wait_table)
1925                 return -ENOMEM;
1926
1927         for(i = 0; i < zone->wait_table_hash_nr_entries; ++i)
1928                 init_waitqueue_head(zone->wait_table + i);
1929
1930         return 0;
1931 }
1932
1933 static __meminit void zone_pcp_init(struct zone *zone)
1934 {
1935         int cpu;
1936         unsigned long batch = zone_batchsize(zone);
1937
1938         for (cpu = 0; cpu < NR_CPUS; cpu++) {
1939 #ifdef CONFIG_NUMA
1940                 /* Early boot. Slab allocator not functional yet */
1941                 zone_pcp(zone, cpu) = &boot_pageset[cpu];
1942                 setup_pageset(&boot_pageset[cpu],0);
1943 #else
1944                 setup_pageset(zone_pcp(zone,cpu), batch);
1945 #endif
1946         }
1947         if (zone->present_pages)
1948                 printk(KERN_DEBUG "  %s zone: %lu pages, LIFO batch:%lu\n",
1949                         zone->name, zone->present_pages, batch);
1950 }
1951
1952 __meminit int init_currently_empty_zone(struct zone *zone,
1953                                         unsigned long zone_start_pfn,
1954                                         unsigned long size)
1955 {
1956         struct pglist_data *pgdat = zone->zone_pgdat;
1957         int ret;
1958         ret = zone_wait_table_init(zone, size);
1959         if (ret)
1960                 return ret;
1961         pgdat->nr_zones = zone_idx(zone) + 1;
1962
1963         zone->zone_start_pfn = zone_start_pfn;
1964
1965         memmap_init(size, pgdat->node_id, zone_idx(zone), zone_start_pfn);
1966
1967         zone_init_free_lists(pgdat, zone, zone->spanned_pages);
1968
1969         return 0;
1970 }
1971
1972 /*
1973  * Set up the zone data structures:
1974  *   - mark all pages reserved
1975  *   - mark all memory queues empty
1976  *   - clear the memory bitmaps
1977  */
1978 static void __meminit free_area_init_core(struct pglist_data *pgdat,
1979                 unsigned long *zones_size, unsigned long *zholes_size)
1980 {
1981         unsigned long j;
1982         int nid = pgdat->node_id;
1983         unsigned long zone_start_pfn = pgdat->node_start_pfn;
1984         int ret;
1985
1986         pgdat_resize_init(pgdat);
1987         pgdat->nr_zones = 0;
1988         init_waitqueue_head(&pgdat->kswapd_wait);
1989         pgdat->kswapd_max_order = 0;
1990         
1991         for (j = 0; j < MAX_NR_ZONES; j++) {
1992                 struct zone *zone = pgdat->node_zones + j;
1993                 unsigned long size, realsize;
1994
1995                 realsize = size = zones_size[j];
1996                 if (zholes_size)
1997                         realsize -= zholes_size[j];
1998
1999                 if (j < ZONE_HIGHMEM)
2000                         nr_kernel_pages += realsize;
2001                 nr_all_pages += realsize;
2002
2003                 zone->spanned_pages = size;
2004                 zone->present_pages = realsize;
2005 #ifdef CONFIG_NUMA
2006                 zone->min_unmapped_ratio = (realsize*sysctl_min_unmapped_ratio)
2007                                                 / 100;
2008 #endif
2009                 zone->name = zone_names[j];
2010                 spin_lock_init(&zone->lock);
2011                 spin_lock_init(&zone->lru_lock);
2012                 zone_seqlock_init(zone);
2013                 zone->zone_pgdat = pgdat;
2014                 zone->free_pages = 0;
2015
2016                 zone->temp_priority = zone->prev_priority = DEF_PRIORITY;
2017
2018                 zone_pcp_init(zone);
2019                 INIT_LIST_HEAD(&zone->active_list);
2020                 INIT_LIST_HEAD(&zone->inactive_list);
2021                 zone->nr_scan_active = 0;
2022                 zone->nr_scan_inactive = 0;
2023                 zone->nr_active = 0;
2024                 zone->nr_inactive = 0;
2025                 zap_zone_vm_stats(zone);
2026                 atomic_set(&zone->reclaim_in_progress, 0);
2027                 if (!size)
2028                         continue;
2029
2030                 zonetable_add(zone, nid, j, zone_start_pfn, size);
2031                 ret = init_currently_empty_zone(zone, zone_start_pfn, size);
2032                 BUG_ON(ret);
2033                 zone_start_pfn += size;
2034         }
2035 }
2036
2037 static void __init alloc_node_mem_map(struct pglist_data *pgdat)
2038 {
2039         /* Skip empty nodes */
2040         if (!pgdat->node_spanned_pages)
2041                 return;
2042
2043 #ifdef CONFIG_FLAT_NODE_MEM_MAP
2044         /* ia64 gets its own node_mem_map, before this, without bootmem */
2045         if (!pgdat->node_mem_map) {
2046                 unsigned long size, start, end;
2047                 struct page *map;
2048
2049                 /*
2050                  * The zone's endpoints aren't required to be MAX_ORDER
2051                  * aligned but the node_mem_map endpoints must be in order
2052                  * for the buddy allocator to function correctly.
2053                  */
2054                 start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1);
2055                 end = pgdat->node_start_pfn + pgdat->node_spanned_pages;
2056                 end = ALIGN(end, MAX_ORDER_NR_PAGES);
2057                 size =  (end - start) * sizeof(struct page);
2058                 map = alloc_remap(pgdat->node_id, size);
2059                 if (!map)
2060                         map = alloc_bootmem_node(pgdat, size);
2061                 pgdat->node_mem_map = map + (pgdat->node_start_pfn - start);
2062         }
2063 #ifdef CONFIG_FLATMEM
2064         /*
2065          * With no DISCONTIG, the global mem_map is just set as node 0's
2066          */
2067         if (pgdat == NODE_DATA(0))
2068                 mem_map = NODE_DATA(0)->node_mem_map;
2069 #endif
2070 #endif /* CONFIG_FLAT_NODE_MEM_MAP */
2071 }
2072
2073 void __meminit free_area_init_node(int nid, struct pglist_data *pgdat,
2074                 unsigned long *zones_size, unsigned long node_start_pfn,
2075                 unsigned long *zholes_size)
2076 {
2077         pgdat->node_id = nid;
2078         pgdat->node_start_pfn = node_start_pfn;
2079         calculate_zone_totalpages(pgdat, zones_size, zholes_size);
2080
2081         alloc_node_mem_map(pgdat);
2082
2083         free_area_init_core(pgdat, zones_size, zholes_size);
2084 }
2085
2086 #ifndef CONFIG_NEED_MULTIPLE_NODES
2087 static bootmem_data_t contig_bootmem_data;
2088 struct pglist_data contig_page_data = { .bdata = &contig_bootmem_data };
2089
2090 EXPORT_SYMBOL(contig_page_data);
2091 #endif
2092
2093 void __init free_area_init(unsigned long *zones_size)
2094 {
2095         free_area_init_node(0, NODE_DATA(0), zones_size,
2096                         __pa(PAGE_OFFSET) >> PAGE_SHIFT, NULL);
2097 }
2098
2099 #ifdef CONFIG_HOTPLUG_CPU
2100 static int page_alloc_cpu_notify(struct notifier_block *self,
2101                                  unsigned long action, void *hcpu)
2102 {
2103         int cpu = (unsigned long)hcpu;
2104
2105         if (action == CPU_DEAD) {
2106                 local_irq_disable();
2107                 __drain_pages(cpu);
2108                 vm_events_fold_cpu(cpu);
2109                 local_irq_enable();
2110                 refresh_cpu_vm_stats(cpu);
2111         }
2112         return NOTIFY_OK;
2113 }
2114 #endif /* CONFIG_HOTPLUG_CPU */
2115
2116 void __init page_alloc_init(void)
2117 {
2118         hotcpu_notifier(page_alloc_cpu_notify, 0);
2119 }
2120
2121 /*
2122  * calculate_totalreserve_pages - called when sysctl_lower_zone_reserve_ratio
2123  *      or min_free_kbytes changes.
2124  */
2125 static void calculate_totalreserve_pages(void)
2126 {
2127         struct pglist_data *pgdat;
2128         unsigned long reserve_pages = 0;
2129         int i, j;
2130
2131         for_each_online_pgdat(pgdat) {
2132                 for (i = 0; i < MAX_NR_ZONES; i++) {
2133                         struct zone *zone = pgdat->node_zones + i;
2134                         unsigned long max = 0;
2135
2136                         /* Find valid and maximum lowmem_reserve in the zone */
2137                         for (j = i; j < MAX_NR_ZONES; j++) {
2138                                 if (zone->lowmem_reserve[j] > max)
2139                                         max = zone->lowmem_reserve[j];
2140                         }
2141
2142                         /* we treat pages_high as reserved pages. */
2143                         max += zone->pages_high;
2144
2145                         if (max > zone->present_pages)
2146                                 max = zone->present_pages;
2147                         reserve_pages += max;
2148                 }
2149         }
2150         totalreserve_pages = reserve_pages;
2151 }
2152
2153 /*
2154  * setup_per_zone_lowmem_reserve - called whenever
2155  *      sysctl_lower_zone_reserve_ratio changes.  Ensures that each zone
2156  *      has a correct pages reserved value, so an adequate number of
2157  *      pages are left in the zone after a successful __alloc_pages().
2158  */
2159 static void setup_per_zone_lowmem_reserve(void)
2160 {
2161         struct pglist_data *pgdat;
2162         int j, idx;
2163
2164         for_each_online_pgdat(pgdat) {
2165                 for (j = 0; j < MAX_NR_ZONES; j++) {
2166                         struct zone *zone = pgdat->node_zones + j;
2167                         unsigned long present_pages = zone->present_pages;
2168
2169                         zone->lowmem_reserve[j] = 0;
2170
2171                         for (idx = j-1; idx >= 0; idx--) {
2172                                 struct zone *lower_zone;
2173
2174                                 if (sysctl_lowmem_reserve_ratio[idx] < 1)
2175                                         sysctl_lowmem_reserve_ratio[idx] = 1;
2176
2177                                 lower_zone = pgdat->node_zones + idx;
2178                                 lower_zone->lowmem_reserve[j] = present_pages /
2179                                         sysctl_lowmem_reserve_ratio[idx];
2180                                 present_pages += lower_zone->present_pages;
2181                         }
2182                 }
2183         }
2184
2185         /* update totalreserve_pages */
2186         calculate_totalreserve_pages();
2187 }
2188
2189 /*
2190  * setup_per_zone_pages_min - called when min_free_kbytes changes.  Ensures 
2191  *      that the pages_{min,low,high} values for each zone are set correctly 
2192  *      with respect to min_free_kbytes.
2193  */
2194 void setup_per_zone_pages_min(void)
2195 {
2196         unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
2197         unsigned long lowmem_pages = 0;
2198         struct zone *zone;
2199         unsigned long flags;
2200
2201         /* Calculate total number of !ZONE_HIGHMEM pages */
2202         for_each_zone(zone) {
2203                 if (!is_highmem(zone))
2204                         lowmem_pages += zone->present_pages;
2205         }
2206
2207         for_each_zone(zone) {
2208                 u64 tmp;
2209
2210                 spin_lock_irqsave(&zone->lru_lock, flags);
2211                 tmp = (u64)pages_min * zone->present_pages;
2212                 do_div(tmp, lowmem_pages);
2213                 if (is_highmem(zone)) {
2214                         /*
2215                          * __GFP_HIGH and PF_MEMALLOC allocations usually don't
2216                          * need highmem pages, so cap pages_min to a small
2217                          * value here.
2218                          *
2219                          * The (pages_high-pages_low) and (pages_low-pages_min)
2220                          * deltas controls asynch page reclaim, and so should
2221                          * not be capped for highmem.
2222                          */
2223                         int min_pages;
2224
2225                         min_pages = zone->present_pages / 1024;
2226                         if (min_pages < SWAP_CLUSTER_MAX)
2227                                 min_pages = SWAP_CLUSTER_MAX;
2228                         if (min_pages > 128)
2229                                 min_pages = 128;
2230                         zone->pages_min = min_pages;
2231                 } else {
2232                         /*
2233                          * If it's a lowmem zone, reserve a number of pages
2234                          * proportionate to the zone's size.
2235                          */
2236                         zone->pages_min = tmp;
2237                 }
2238
2239                 zone->pages_low   = zone->pages_min + (tmp >> 2);
2240                 zone->pages_high  = zone->pages_min + (tmp >> 1);
2241                 spin_unlock_irqrestore(&zone->lru_lock, flags);
2242         }
2243
2244         /* update totalreserve_pages */
2245         calculate_totalreserve_pages();
2246 }
2247
2248 /*
2249  * Initialise min_free_kbytes.
2250  *
2251  * For small machines we want it small (128k min).  For large machines
2252  * we want it large (64MB max).  But it is not linear, because network
2253  * bandwidth does not increase linearly with machine size.  We use
2254  *
2255  *      min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
2256  *      min_free_kbytes = sqrt(lowmem_kbytes * 16)
2257  *
2258  * which yields
2259  *
2260  * 16MB:        512k
2261  * 32MB:        724k
2262  * 64MB:        1024k
2263  * 128MB:       1448k
2264  * 256MB:       2048k
2265  * 512MB:       2896k
2266  * 1024MB:      4096k
2267  * 2048MB:      5792k
2268  * 4096MB:      8192k
2269  * 8192MB:      11584k
2270  * 16384MB:     16384k
2271  */
2272 static int __init init_per_zone_pages_min(void)
2273 {
2274         unsigned long lowmem_kbytes;
2275
2276         lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
2277
2278         min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
2279         if (min_free_kbytes < 128)
2280                 min_free_kbytes = 128;
2281         if (min_free_kbytes > 65536)
2282                 min_free_kbytes = 65536;
2283         setup_per_zone_pages_min();
2284         setup_per_zone_lowmem_reserve();
2285         return 0;
2286 }
2287 module_init(init_per_zone_pages_min)
2288
2289 /*
2290  * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so 
2291  *      that we can call two helper functions whenever min_free_kbytes
2292  *      changes.
2293  */
2294 int min_free_kbytes_sysctl_handler(ctl_table *table, int write, 
2295         struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
2296 {
2297         proc_dointvec(table, write, file, buffer, length, ppos);
2298         setup_per_zone_pages_min();
2299         return 0;
2300 }
2301
2302 #ifdef CONFIG_NUMA
2303 int sysctl_min_unmapped_ratio_sysctl_handler(ctl_table *table, int write,
2304         struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
2305 {
2306         struct zone *zone;
2307         int rc;
2308
2309         rc = proc_dointvec_minmax(table, write, file, buffer, length, ppos);
2310         if (rc)
2311                 return rc;
2312
2313         for_each_zone(zone)
2314                 zone->min_unmapped_ratio = (zone->present_pages *
2315                                 sysctl_min_unmapped_ratio) / 100;
2316         return 0;
2317 }
2318 #endif
2319
2320 /*
2321  * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
2322  *      proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
2323  *      whenever sysctl_lowmem_reserve_ratio changes.
2324  *
2325  * The reserve ratio obviously has absolutely no relation with the
2326  * pages_min watermarks. The lowmem reserve ratio can only make sense
2327  * if in function of the boot time zone sizes.
2328  */
2329 int lowmem_reserve_ratio_sysctl_handler(ctl_table *table, int write,
2330         struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
2331 {
2332         proc_dointvec_minmax(table, write, file, buffer, length, ppos);
2333         setup_per_zone_lowmem_reserve();
2334         return 0;
2335 }
2336
2337 /*
2338  * percpu_pagelist_fraction - changes the pcp->high for each zone on each
2339  * cpu.  It is the fraction of total pages in each zone that a hot per cpu pagelist
2340  * can have before it gets flushed back to buddy allocator.
2341  */
2342
2343 int percpu_pagelist_fraction_sysctl_handler(ctl_table *table, int write,
2344         struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
2345 {
2346         struct zone *zone;
2347         unsigned int cpu;
2348         int ret;
2349
2350         ret = proc_dointvec_minmax(table, write, file, buffer, length, ppos);
2351         if (!write || (ret == -EINVAL))
2352                 return ret;
2353         for_each_zone(zone) {
2354                 for_each_online_cpu(cpu) {
2355                         unsigned long  high;
2356                         high = zone->present_pages / percpu_pagelist_fraction;
2357                         setup_pagelist_highmark(zone_pcp(zone, cpu), high);
2358                 }
2359         }
2360         return 0;
2361 }
2362
2363 int hashdist = HASHDIST_DEFAULT;
2364
2365 #ifdef CONFIG_NUMA
2366 static int __init set_hashdist(char *str)
2367 {
2368         if (!str)
2369                 return 0;
2370         hashdist = simple_strtoul(str, &str, 0);
2371         return 1;
2372 }
2373 __setup("hashdist=", set_hashdist);
2374 #endif
2375
2376 /*
2377  * allocate a large system hash table from bootmem
2378  * - it is assumed that the hash table must contain an exact power-of-2
2379  *   quantity of entries
2380  * - limit is the number of hash buckets, not the total allocation size
2381  */
2382 void *__init alloc_large_system_hash(const char *tablename,
2383                                      unsigned long bucketsize,
2384                                      unsigned long numentries,
2385                                      int scale,
2386                                      int flags,
2387                                      unsigned int *_hash_shift,
2388                                      unsigned int *_hash_mask,
2389                                      unsigned long limit)
2390 {
2391         unsigned long long max = limit;
2392         unsigned long log2qty, size;
2393         void *table = NULL;
2394
2395         /* allow the kernel cmdline to have a say */
2396         if (!numentries) {
2397                 /* round applicable memory size up to nearest megabyte */
2398                 numentries = (flags & HASH_HIGHMEM) ? nr_all_pages : nr_kernel_pages;
2399                 numentries += (1UL << (20 - PAGE_SHIFT)) - 1;
2400                 numentries >>= 20 - PAGE_SHIFT;
2401                 numentries <<= 20 - PAGE_SHIFT;
2402
2403                 /* limit to 1 bucket per 2^scale bytes of low memory */
2404                 if (scale > PAGE_SHIFT)
2405                         numentries >>= (scale - PAGE_SHIFT);
2406                 else
2407                         numentries <<= (PAGE_SHIFT - scale);
2408         }
2409         numentries = roundup_pow_of_two(numentries);
2410
2411         /* limit allocation size to 1/16 total memory by default */
2412         if (max == 0) {
2413                 max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
2414                 do_div(max, bucketsize);
2415         }
2416
2417         if (numentries > max)
2418                 numentries = max;
2419
2420         log2qty = long_log2(numentries);
2421
2422         do {
2423                 size = bucketsize << log2qty;
2424                 if (flags & HASH_EARLY)
2425                         table = alloc_bootmem(size);
2426                 else if (hashdist)
2427                         table = __vmalloc(size, GFP_ATOMIC, PAGE_KERNEL);
2428                 else {
2429                         unsigned long order;
2430                         for (order = 0; ((1UL << order) << PAGE_SHIFT) < size; order++)
2431                                 ;
2432                         table = (void*) __get_free_pages(GFP_ATOMIC, order);
2433                 }
2434         } while (!table && size > PAGE_SIZE && --log2qty);
2435
2436         if (!table)
2437                 panic("Failed to allocate %s hash table\n", tablename);
2438
2439         printk("%s hash table entries: %d (order: %d, %lu bytes)\n",
2440                tablename,
2441                (1U << log2qty),
2442                long_log2(size) - PAGE_SHIFT,
2443                size);
2444
2445         if (_hash_shift)
2446                 *_hash_shift = log2qty;
2447         if (_hash_mask)
2448                 *_hash_mask = (1 << log2qty) - 1;
2449
2450         return table;
2451 }
2452
2453 #ifdef CONFIG_OUT_OF_LINE_PFN_TO_PAGE
2454 struct page *pfn_to_page(unsigned long pfn)
2455 {
2456         return __pfn_to_page(pfn);
2457 }
2458 unsigned long page_to_pfn(struct page *page)
2459 {
2460         return __page_to_pfn(page);
2461 }
2462 EXPORT_SYMBOL(pfn_to_page);
2463 EXPORT_SYMBOL(page_to_pfn);
2464 #endif /* CONFIG_OUT_OF_LINE_PFN_TO_PAGE */