root/src/linux/ar531x/linux-2.6.23/mm/page_alloc.c

Revision 12400, 107.2 kB (checked in by BrainSlayer, 5 months ago)

more flexible EOC5610 partition layout, small performance increase by module remapping, lzma decoder speed improvements

Line 
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 #include <linux/sort.h>
41 #include <linux/pfn.h>
42 #include <linux/backing-dev.h>
43 #include <linux/fault-inject.h>
44
45 #include <asm/tlbflush.h>
46 #include <asm/div64.h>
47 #include "internal.h"
48
49 /*
50  * MCD - HACK: Find somewhere to initialize this EARLY, or make this
51  * initializer cleaner
52  */
53 nodemask_t node_online_map __read_mostly = { { [0] = 1UL } };
54 EXPORT_SYMBOL(node_online_map);
55 nodemask_t node_possible_map __read_mostly = NODE_MASK_ALL;
56 EXPORT_SYMBOL(node_possible_map);
57 unsigned long totalram_pages __read_mostly;
58 unsigned long totalreserve_pages __read_mostly;
59 long nr_swap_pages;
60 int percpu_pagelist_fraction;
61
62 static void __free_pages_ok(struct page *page, unsigned int order);
63
64 /*
65  * results with 256, 32 in the lowmem_reserve sysctl:
66  *      1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
67  *      1G machine -> (16M dma, 784M normal, 224M high)
68  *      NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
69  *      HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
70  *      HIGHMEM allocation will (224M+784M)/256 of ram reserved in ZONE_DMA
71  *
72  * TBD: should special case ZONE_DMA32 machines here - in those we normally
73  * don't need any ZONE_NORMAL reservation
74  */
75 int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES-1] = {
76 #ifdef CONFIG_ZONE_DMA
77          256,
78 #endif
79 #ifdef CONFIG_ZONE_DMA32
80          256,
81 #endif
82 #ifdef CONFIG_HIGHMEM
83          32,
84 #endif
85          32,
86 };
87
88 EXPORT_SYMBOL(totalram_pages);
89
90 static char * const zone_names[MAX_NR_ZONES] = {
91 #ifdef CONFIG_ZONE_DMA
92          "DMA",
93 #endif
94 #ifdef CONFIG_ZONE_DMA32
95          "DMA32",
96 #endif
97          "Normal",
98 #ifdef CONFIG_HIGHMEM
99          "HighMem",
100 #endif
101          "Movable",
102 };
103
104 int min_free_kbytes = 1024;
105
106 unsigned long __meminitdata nr_kernel_pages;
107 unsigned long __meminitdata nr_all_pages;
108 static unsigned long __meminitdata dma_reserve;
109
110 #ifdef CONFIG_ARCH_POPULATES_NODE_MAP
111   /*
112    * MAX_ACTIVE_REGIONS determines the maxmimum number of distinct
113    * ranges of memory (RAM) that may be registered with add_active_range().
114    * Ranges passed to add_active_range() will be merged if possible
115    * so the number of times add_active_range() can be called is
116    * related to the number of nodes and the number of holes
117    */
118   #ifdef CONFIG_MAX_ACTIVE_REGIONS
119     /* Allow an architecture to set MAX_ACTIVE_REGIONS to save memory */
120     #define MAX_ACTIVE_REGIONS CONFIG_MAX_ACTIVE_REGIONS
121   #else
122     #if MAX_NUMNODES >= 32
123       /* If there can be many nodes, allow up to 50 holes per node */
124       #define MAX_ACTIVE_REGIONS (MAX_NUMNODES*50)
125     #else
126       /* By default, allow up to 256 distinct regions */
127       #define MAX_ACTIVE_REGIONS 256
128     #endif
129   #endif
130
131   static struct node_active_region __meminitdata early_node_map[MAX_ACTIVE_REGIONS];
132   static int __meminitdata nr_nodemap_entries;
133   static unsigned long __meminitdata arch_zone_lowest_possible_pfn[MAX_NR_ZONES];
134   static unsigned long __meminitdata arch_zone_highest_possible_pfn[MAX_NR_ZONES];
135 #ifdef CONFIG_MEMORY_HOTPLUG_RESERVE
136   static unsigned long __meminitdata node_boundary_start_pfn[MAX_NUMNODES];
137   static unsigned long __meminitdata node_boundary_end_pfn[MAX_NUMNODES];
138 #endif /* CONFIG_MEMORY_HOTPLUG_RESERVE */
139   unsigned long __initdata required_kernelcore;
140   unsigned long __initdata required_movablecore;
141   unsigned long __meminitdata zone_movable_pfn[MAX_NUMNODES];
142
143   /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
144   int movable_zone;
145   EXPORT_SYMBOL(movable_zone);
146 #endif /* CONFIG_ARCH_POPULATES_NODE_MAP */
147
148 #if MAX_NUMNODES > 1
149 int nr_node_ids __read_mostly = MAX_NUMNODES;
150 EXPORT_SYMBOL(nr_node_ids);
151 #endif
152
153 #ifdef CONFIG_DEBUG_VM
154 static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
155 {
156         int ret = 0;
157         unsigned seq;
158         unsigned long pfn = page_to_pfn(page);
159
160         do {
161                 seq = zone_span_seqbegin(zone);
162                 if (pfn >= zone->zone_start_pfn + zone->spanned_pages)
163                         ret = 1;
164                 else if (pfn < zone->zone_start_pfn)
165                         ret = 1;
166         } while (zone_span_seqretry(zone, seq));
167
168         return ret;
169 }
170
171 static int page_is_consistent(struct zone *zone, struct page *page)
172 {
173         if (!pfn_valid_within(page_to_pfn(page)))
174                 return 0;
175         if (zone != page_zone(page))
176                 return 0;
177
178         return 1;
179 }
180 /*
181  * Temporary debugging check for pages not lying within a given zone.
182  */
183 static int bad_range(struct zone *zone, struct page *page)
184 {
185         if (page_outside_zone_boundaries(zone, page))
186                 return 1;
187         if (!page_is_consistent(zone, page))
188                 return 1;
189
190         return 0;
191 }
192 #else
193 static inline int bad_range(struct zone *zone, struct page *page)
194 {
195         return 0;
196 }
197 #endif
198
199 static void bad_page(struct page *page)
200 {
201         printk(KERN_EMERG "Bad page state in process '%s'\n"
202                 KERN_EMERG "page:%p flags:0x%0*lx mapping:%p mapcount:%d count:%d\n"
203                 KERN_EMERG "Trying to fix it up, but a reboot is needed\n"
204                 KERN_EMERG "Backtrace:\n",
205                 current->comm, page, (int)(2*sizeof(unsigned long)),
206                 (unsigned long)page->flags, page->mapping,
207                 page_mapcount(page), page_count(page));
208         dump_stack();
209         page->flags &= ~(1 << PG_lru    |
210                         1 << PG_private |
211                         1 << PG_locked  |
212                         1 << PG_active  |
213                         1 << PG_dirty   |
214                         1 << PG_reclaim |
215                         1 << PG_slab    |
216                         1 << PG_swapcache |
217                         1 << PG_writeback |
218                         1 << PG_buddy );
219         set_page_count(page, 0);
220         reset_page_mapcount(page);
221         page->mapping = NULL;
222         add_taint(TAINT_BAD_PAGE);
223 }
224
225 /*
226  * Higher-order pages are called "compound pages".  They are structured thusly:
227  *
228  * The first PAGE_SIZE page is called the "head page".
229  *
230  * The remaining PAGE_SIZE pages are called "tail pages".
231  *
232  * All pages have PG_compound set.  All pages have their ->private pointing at
233  * the head page (even the head page has this).
234  *
235  * The first tail page's ->lru.next holds the address of the compound page's
236  * put_page() function.  Its ->lru.prev holds the order of allocation.
237  * This usage means that zero-order pages may not be compound.
238  */
239
240 static void free_compound_page(struct page *page)
241 {
242         __free_pages_ok(page, compound_order(page));
243 }
244
245 static void prep_compound_page(struct page *page, unsigned long order)
246 {
247         int i;
248         int nr_pages = 1 << order;
249
250         set_compound_page_dtor(page, free_compound_page);
251         set_compound_order(page, order);
252         __SetPageHead(page);
253         for (i = 1; i < nr_pages; i++) {
254                 struct page *p = page + i;
255
256                 __SetPageTail(p);
257                 p->first_page = page;
258         }
259 }
260
261 static void destroy_compound_page(struct page *page, unsigned long order)
262 {
263         int i;
264         int nr_pages = 1 << order;
265
266         if (unlikely(compound_order(page) != order))
267                 bad_page(page);
268
269         if (unlikely(!PageHead(page)))
270                         bad_page(page);
271         __ClearPageHead(page);
272         for (i = 1; i < nr_pages; i++) {
273                 struct page *p = page + i;
274
275                 if (unlikely(!PageTail(p) |
276                                 (p->first_page != page)))
277                         bad_page(page);
278                 __ClearPageTail(p);
279         }
280 }
281
282 static inline void prep_zero_page(struct page *page, int order, gfp_t gfp_flags)
283 {
284         int i;
285
286         VM_BUG_ON((gfp_flags & (__GFP_WAIT | __GFP_HIGHMEM)) == __GFP_HIGHMEM);
287         /*
288          * clear_highpage() will use KM_USER0, so it's a bug to use __GFP_ZERO
289          * and __GFP_HIGHMEM from hard or soft interrupt context.
290          */
291         VM_BUG_ON((gfp_flags & __GFP_HIGHMEM) && in_interrupt());
292         for (i = 0; i < (1 << order); i++)
293                 clear_highpage(page + i);
294 }
295
296 /*
297  * function for dealing with page's order in buddy system.
298  * zone->lock is already acquired when we use these.
299  * So, we don't need atomic page->flags operations here.
300  */
301 static inline unsigned long page_order(struct page *page)
302 {
303         return page_private(page);
304 }
305
306 static inline void set_page_order(struct page *page, int order)
307 {
308         set_page_private(page, order);
309         __SetPageBuddy(page);
310 }
311
312 static inline void rmv_page_order(struct page *page)
313 {
314         __ClearPageBuddy(page);
315         set_page_private(page, 0);
316 }
317
318 /*
319  * Locate the struct page for both the matching buddy in our
320  * pair (buddy1) and the combined O(n+1) page they form (page).
321  *
322  * 1) Any buddy B1 will have an order O twin B2 which satisfies
323  * the following equation:
324  *     B2 = B1 ^ (1 << O)
325  * For example, if the starting buddy (buddy2) is #8 its order
326  * 1 buddy is #10:
327  *     B2 = 8 ^ (1 << 1) = 8 ^ 2 = 10
328  *
329  * 2) Any buddy B will have an order O+1 parent P which
330  * satisfies the following equation:
331  *     P = B & ~(1 << O)
332  *
333  * Assumption: *_mem_map is contiguous at least up to MAX_ORDER
334  */
335 static inline struct page *
336 __page_find_buddy(struct page *page, unsigned long page_idx, unsigned int order)
337 {
338         unsigned long buddy_idx = page_idx ^ (1 << order);
339
340         return page + (buddy_idx - page_idx);
341 }
342
343 static inline unsigned long
344 __find_combined_index(unsigned long page_idx, unsigned int order)
345 {
346         return (page_idx & ~(1 << order));
347 }
348
349 /*
350  * This function checks whether a page is free && is the buddy
351  * we can do coalesce a page and its buddy if
352  * (a) the buddy is not in a hole &&
353  * (b) the buddy is in the buddy system &&
354  * (c) a page and its buddy have the same order &&
355  * (d) a page and its buddy are in the same zone.
356  *
357  * For recording whether a page is in the buddy system, we use PG_buddy.
358  * Setting, clearing, and testing PG_buddy is serialized by zone->lock.
359  *
360  * For recording page's order, we use page_private(page).
361  */
362 static inline int page_is_buddy(struct page *page, struct page *buddy,
363                                                                 int order)
364 {
365         if (!pfn_valid_within(page_to_pfn(buddy)))
366                 return 0;
367
368         if (page_zone_id(page) != page_zone_id(buddy))
369                 return 0;
370
371         if (PageBuddy(buddy) && page_order(buddy) == order) {
372                 BUG_ON(page_count(buddy) != 0);
373                 return 1;
374         }
375         return 0;
376 }
377
378 /*
379  * Freeing function for a buddy system allocator.
380  *
381  * The concept of a buddy system is to maintain direct-mapped table
382  * (containing bit values) for memory blocks of various "orders".
383  * The bottom level table contains the map for the smallest allocatable
384  * units of memory (here, pages), and each level above it describes
385  * pairs of units from the levels below, hence, "buddies".
386  * At a high level, all that happens here is marking the table entry
387  * at the bottom level available, and propagating the changes upward
388  * as necessary, plus some accounting needed to play nicely with other
389  * parts of the VM system.
390  * At each level, we keep a list of pages, which are heads of continuous
391  * free pages of length of (1 << order) and marked with PG_buddy. Page's
392  * order is recorded in page_private(page) field.
393  * So when we are allocating or freeing one, we can derive the state of the
394  * other.  That is, if we allocate a small block, and both were   
395  * free, the remainder of the region must be split into blocks.   
396  * If a block is freed, and its buddy is also free, then this
397  * triggers coalescing into a block of larger size.           
398  *
399  * -- wli
400  */
401
402 static inline void __free_one_page(struct page *page,
403                 struct zone *zone, unsigned int order)
404 {
405         unsigned long page_idx;
406         int order_size = 1 << order;
407
408         if (unlikely(PageCompound(page)))
409                 destroy_compound_page(page, order);
410
411         page_idx = page_to_pfn(page) & ((1 << MAX_ORDER) - 1);
412
413         VM_BUG_ON(page_idx & (order_size - 1));
414         VM_BUG_ON(bad_range(zone, page));
415
416         __mod_zone_page_state(zone, NR_FREE_PAGES, order_size);
417         while (order < MAX_ORDER-1) {
418                 unsigned long combined_idx;
419                 struct free_area *area;
420                 struct page *buddy;
421
422                 buddy = __page_find_buddy(page, page_idx, order);
423                 if (!page_is_buddy(page, buddy, order))
424                         break;          /* Move the buddy up one level. */
425
426                 list_del(&buddy->lru);
427                 area = zone->free_area + order;
428                 area->nr_free--;
429                 rmv_page_order(buddy);
430                 combined_idx = __find_combined_index(page_idx, order);
431                 page = page + (combined_idx - page_idx);
432                 page_idx = combined_idx;
433                 order++;
434         }
435         set_page_order(page, order);
436         list_add(&page->lru, &zone->free_area[order].free_list);
437         zone->free_area[order].nr_free++;
438 }
439
440 static inline int free_pages_check(struct page *page)
441 {
442         if (unlikely(page_mapcount(page) |
443                 (page->mapping != NULL)  |
444                 (page_count(page) != 0)  |
445                 (page->flags & (
446                         1 << PG_lru     |
447                         1 << PG_private |
448                         1 << PG_locked  |
449                         1 << PG_active  |
450                         1 << PG_slab    |
451                         1 << PG_swapcache |
452                         1 << PG_writeback |
453                         1 << PG_reserved |
454                         1 << PG_buddy ))))
455                 bad_page(page);
456         if (PageDirty(page))
457                 __ClearPageDirty(page);
458         /*
459          * For now, we report if PG_reserved was found set, but do not
460          * clear it, and do not free the page.  But we shall soon need
461          * to do more, for when the ZERO_PAGE count wraps negative.
462          */
463         return PageReserved(page);
464 }
465
466 /*
467  * Frees a list of pages.
468  * Assumes all pages on list are in same zone, and of same order.
469  * count is the number of pages to free.
470  *
471  * If the zone was previously in an "all pages pinned" state then look to
472  * see if this freeing clears that state.
473  *
474  * And clear the zone's pages_scanned counter, to hold off the "all pages are
475  * pinned" detection logic.
476  */
477 static void free_pages_bulk(struct zone *zone, int count,
478                                         struct list_head *list, int order)
479 {
480         spin_lock(&zone->lock);
481         zone->all_unreclaimable = 0;
482         zone->pages_scanned = 0;
483         while (count--) {
484                 struct page *page;
485
486                 VM_BUG_ON(list_empty(list));
487                 page = list_entry(list->prev, struct page, lru);
488                 /* have to delete it as __free_one_page list manipulates */
489                 list_del(&page->lru);
490                 __free_one_page(page, zone, order);
491         }
492         spin_unlock(&zone->lock);
493 }
494
495 static void free_one_page(struct zone *zone, struct page *page, int order)
496 {
497         spin_lock(&zone->lock);
498         zone->all_unreclaimable = 0;
499         zone->pages_scanned = 0;
500         __free_one_page(page, zone, order);
501         spin_unlock(&zone->lock);
502 }
503
504 static void __free_pages_ok(struct page *page, unsigned int order)
505 {
506         unsigned long flags;
507         int i;
508         int reserved = 0;
509
510         for (i = 0 ; i < (1 << order) ; ++i)
511                 reserved += free_pages_check(page + i);
512         if (reserved)
513                 return;
514
515         if (!PageHighMem(page))
516                 debug_check_no_locks_freed(page_address(page),PAGE_SIZE<<order);
517         arch_free_page(page, order);
518         kernel_map_pages(page, 1 << order, 0);
519
520         local_irq_save(flags);
521         __count_vm_events(PGFREE, 1 << order);
522         free_one_page(page_zone(page), page, order);
523         local_irq_restore(flags);
524 }
525
526 /*
527  * permit the bootmem allocator to evade page validation on high-order frees
528  */
529 void fastcall __init __free_pages_bootmem(struct page *page, unsigned int order)
530 {
531         if (order == 0) {
532                 __ClearPageReserved(page);
533                 set_page_count(page, 0);
534                 set_page_refcounted(page);
535                 __free_page(page);
536         } else {
537                 int loop;
538
539                 prefetchw(page);
540                 for (loop = 0; loop < BITS_PER_LONG; loop++) {
541                         struct page *p = &page[loop];
542
543                         if (loop + 1 < BITS_PER_LONG)
544                                 prefetchw(p + 1);
545                         __ClearPageReserved(p);
546                         set_page_count(p, 0);
547                 }
548
549                 set_page_refcounted(page);
550                 __free_pages(page, order);
551         }
552 }
553
554
555 /*
556  * The order of subdivision here is critical for the IO subsystem.
557  * Please do not alter this order without good reasons and regression
558  * testing. Specifically, as large blocks of memory are subdivided,
559  * the order in which smaller blocks are delivered depends on the order
560  * they're subdivided in this function. This is the primary factor
561  * influencing the order in which pages are delivered to the IO
562  * subsystem according to empirical testing, and this is also justified
563  * by considering the behavior of a buddy system containing a single
564  * large block of memory acted on by a series of small allocations.
565  * This behavior is a critical factor in sglist merging's success.
566  *
567  * -- wli
568  */
569 static inline void expand(struct zone *zone, struct page *page,
570         int low, int high, struct free_area *area)
571 {
572         unsigned long size = 1 << high;
573
574         while (high > low) {
575                 area--;
576                 high--;
577                 size >>= 1;
578                 VM_BUG_ON(bad_range(zone, &page[size]));
579                 list_add(&page[size].lru, &area->free_list);
580                 area->nr_free++;
581                 set_page_order(&page[size], high);
582         }
583 }
584
585 /*
586  * This page is about to be returned from the page allocator
587  */
588 static int prep_new_page(struct page *page, int order, gfp_t gfp_flags)
589 {
590         if (unlikely(page_mapcount(page) |
591                 (page->mapping != NULL)  |
592                 (page_count(page) != 0)  |
593                 (page->flags & (
594                         1 << PG_lru     |
595                         1 << PG_private |
596                         1 << PG_locked  |
597                         1 << PG_active  |
598                         1 << PG_dirty   |
599                         1 << PG_slab    |
600                         1 << PG_swapcache |
601                         1 << PG_writeback |
602                         1 << PG_reserved |
603                         1 << PG_buddy ))))
604                 bad_page(page);
605
606         /*
607          * For now, we report if PG_reserved was found set, but do not
608          * clear it, and do not allocate the page: as a safety net.
609          */
610         if (PageReserved(page))
611                 return 1;
612
613         page->flags &= ~(1 << PG_uptodate | 1 << PG_error | 1 << PG_readahead |
614                         1 << PG_referenced | 1 << PG_arch_1 |
615                         1 << PG_owner_priv_1 | 1 << PG_mappedtodisk);
616         set_page_private(page, 0);
617         set_page_refcounted(page);
618
619         arch_alloc_page(page, order);
620         kernel_map_pages(page, 1 << order, 1);
621
622         if (gfp_flags & __GFP_ZERO)
623                 prep_zero_page(page, order, gfp_flags);
624
625         if (order && (gfp_flags & __GFP_COMP))
626                 prep_compound_page(page, order);
627
628         return 0;
629 }
630
631 /*
632  * Do the hard work of removing an element from the buddy allocator.
633  * Call me with the zone->lock already held.
634  */
635 static struct page *__rmqueue(struct zone *zone, unsigned int order)
636 {
637         struct free_area * area;
638         unsigned int current_order;
639         struct page *page;
640
641         for (current_order = order; current_order < MAX_ORDER; ++current_order) {
642                 area = zone->free_area + current_order;
643                 if (list_empty(&area->free_list))
644                         continue;
645
646                 page = list_entry(area->free_list.next, struct page, lru);
647                 list_del(&page->lru);
648                 rmv_page_order(page);
649                 area->nr_free--;
650                 __mod_zone_page_state(zone, NR_FREE_PAGES, - (1UL << order));
651                 expand(zone, page, order, current_order, area);
652                 return page;
653         }
654
655         return NULL;
656 }
657
658 /*
659  * Obtain a specified number of elements from the buddy allocator, all under
660  * a single hold of the lock, for efficiency.  Add them to the supplied list.
661  * Returns the number of new pages which were placed at *list.
662  */
663 static int rmqueue_bulk(struct zone *zone, unsigned int order,
664                         unsigned long count, struct list_head *list)
665 {
666         int i;
667        
668         spin_lock(&zone->lock);
669         for (i = 0; i < count; ++i) {
670                 struct page *page = __rmqueue(zone, order);
671                 if (unlikely(page == NULL))
672                         break;
673                 list_add_tail(&page->lru, list);
674         }
675         spin_unlock(&zone->lock);
676         return i;
677 }
678
679 #ifdef CONFIG_NUMA
680 /*
681  * Called from the vmstat counter updater to drain pagesets of this
682  * currently executing processor on remote nodes after they have
683  * expired.
684  *
685  * Note that this function must be called with the thread pinned to
686  * a single processor.
687  */
688 void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp)
689 {
690         unsigned long flags;
691         int to_drain;
692
693         local_irq_save(flags);
694         if (pcp->count >= pcp->batch)
695                 to_drain = pcp->batch;
696         else
697                 to_drain = pcp->count;
698         free_pages_bulk(zone, to_drain, &pcp->list, 0);
699         pcp->count -= to_drain;
700         local_irq_restore(flags);
701 }
702 #endif
703
704 static void __drain_pages(unsigned int cpu)
705 {
706         unsigned long flags;
707         struct zone *zone;
708         int i;
709
710         for_each_zone(zone) {
711                 struct per_cpu_pageset *pset;
712
713                 if (!populated_zone(zone))
714                         continue;
715
716                 pset = zone_pcp(zone, cpu);
717                 for (i = 0; i < ARRAY_SIZE(pset->pcp); i++) {
718                         struct per_cpu_pages *pcp;
719
720                         pcp = &pset->pcp[i];
721                         local_irq_save(flags);
722                         free_pages_bulk(zone, pcp->count, &pcp->list, 0);
723                         pcp->count = 0;
724                         local_irq_restore(flags);
725                 }
726         }
727 }
728
729 #ifdef CONFIG_HIBERNATION
730
731 void mark_free_pages(struct zone *zone)
732 {
733         unsigned long pfn, max_zone_pfn;
734         unsigned long flags;
735         int order;
736         struct list_head *curr;
737
738         if (!zone->spanned_pages)
739                 return;
740
741         spin_lock_irqsave(&zone->lock, flags);
742
743         max_zone_pfn = zone->zone_start_pfn + zone->spanned_pages;
744         for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
745                 if (pfn_valid(pfn)) {
746                         struct page *page = pfn_to_page(pfn);
747
748                         if (!swsusp_page_is_forbidden(page))
749                                 swsusp_unset_page_free(page);
750                 }
751
752         for (order = MAX_ORDER - 1; order >= 0; --order)
753                 list_for_each(curr, &zone->free_area[order].free_list) {
754                         unsigned long i;
755
756                         pfn = page_to_pfn(list_entry(curr, struct page, lru));
757                         for (i = 0; i < (1UL << order); i++)
758                                 swsusp_set_page_free(pfn_to_page(pfn + i));
759                 }
760
761         spin_unlock_irqrestore(&zone->lock, flags);
762 }
763
764 /*
765  * Spill all of this CPU's per-cpu pages back into the buddy allocator.
766  */
767 void drain_local_pages(void)
768 {
769         unsigned long flags;
770
771         local_irq_save(flags); 
772         __drain_pages(smp_processor_id());
773         local_irq_restore(flags);       
774 }
775 #endif /* CONFIG_HIBERNATION */
776
777 /*
778  * Free a 0-order page
779  */
780 static void fastcall free_hot_cold_page(struct page *page, int cold)
781 {
782         struct zone *zone = page_zone(page);
783         struct per_cpu_pages *pcp;
784         unsigned long flags;
785
786         if (PageAnon(page))
787                 page->mapping = NULL;
788         if (free_pages_check(page))
789                 return;
790
791         if (!PageHighMem(page))
792                 debug_check_no_locks_freed(page_address(page), PAGE_SIZE);
793         arch_free_page(page, 0);
794         kernel_map_pages(page, 1, 0);
795
796         pcp = &zone_pcp(zone, get_cpu())->pcp[cold];
797         local_irq_save(flags);
798         __count_vm_event(PGFREE);
799         list_add(&page->lru, &pcp->list);
800         pcp->count++;
801         if (pcp->count >= pcp->high) {
802                 free_pages_bulk(zone, pcp->batch, &pcp->list, 0);
803                 pcp->count -= pcp->batch;
804         }
805         local_irq_restore(flags);
806         put_cpu();
807 }
808
809 void fastcall free_hot_page(struct page *page)
810 {
811         free_hot_cold_page(page, 0);
812 }
813        
814 void fastcall free_cold_page(struct page *page)
815 {
816         free_hot_cold_page(page, 1);
817 }
818
819 /*
820  * split_page takes a non-compound higher-order page, and splits it into
821  * n (1<<order) sub-pages: page[0..n]
822  * Each sub-page must be freed individually.
823  *
824  * Note: this is probably too low level an operation for use in drivers.
825  * Please consult with lkml before using this in your driver.
826  */
827 void split_page(struct page *page, unsigned int order)
828 {
829         int i;
830
831         VM_BUG_ON(PageCompound(page));
832         VM_BUG_ON(!page_count(page));
833         for (i = 1; i < (1 << order); i++)
834                 set_page_refcounted(page + i);
835 }
836
837 /*
838  * Really, prep_compound_page() should be called from __rmqueue_bulk().  But
839  * we cheat by calling it from here, in the order > 0 path.  Saves a branch
840  * or two.
841  */
842 static struct page *buffered_rmqueue(struct zonelist *zonelist,
843                         struct zone *zone, int order, gfp_t gfp_flags)
844 {
845         unsigned long flags;
846         struct page *page;
847         int cold = !!(gfp_flags & __GFP_COLD);
848         int cpu;
849
850 again:
851         cpu  = get_cpu();
852         if (likely(order == 0)) {
853                 struct per_cpu_pages *pcp;
854
855                 pcp = &zone_pcp(zone, cpu)->pcp[cold];
856                 local_irq_save(flags);
857                 if (!pcp->count) {
858                         pcp->count = rmqueue_bulk(zone, 0,
859                                                 pcp->batch, &pcp->list);
860                         if (unlikely(!pcp->count))
861                                 goto failed;
862                 }
863                 page = list_entry(pcp->list.next, struct page, lru);
864                 list_del(&page->lru);
865                 pcp->count--;
866         } else {
867                 spin_lock_irqsave(&zone->lock, flags);
868                 page = __rmqueue(zone, order);
869                 spin_unlock(&zone->lock);
870                 if (!page)
871                         goto failed;
872         }
873
874         __count_zone_vm_events(PGALLOC, zone, 1 << order);
875         zone_statistics(zonelist, zone);
876         local_irq_restore(flags);
877         put_cpu();
878
879         VM_BUG_ON(bad_range(zone, page));
880         if (prep_new_page(page, order, gfp_flags))
881                 goto again;
882         return page;
883
884 failed:
885         local_irq_restore(flags);
886         put_cpu();
887         return NULL;
888 }
889
890 #define ALLOC_NO_WATERMARKS     0x01 /* don't check watermarks at all */
891 #define ALLOC_WMARK_MIN         0x02 /* use pages_min watermark */
892 #define ALLOC_WMARK_LOW         0x04 /* use pages_low watermark */
893 #define ALLOC_WMARK_HIGH        0x08 /* use pages_high watermark */
894 #define ALLOC_HARDER            0x10 /* try to alloc harder */
895 #define ALLOC_HIGH              0x20 /* __GFP_HIGH set */
896 #define ALLOC_CPUSET            0x40 /* check for correct cpuset */
897
898 #ifdef CONFIG_FAIL_PAGE_ALLOC
899
900 static struct fail_page_alloc_attr {
901         struct fault_attr attr;
902
903         u32 ignore_gfp_highmem;
904         u32 ignore_gfp_wait;
905         u32 min_order;
906
907 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
908
909         struct dentry *ignore_gfp_highmem_file;
910         struct dentry *ignore_gfp_wait_file;
911         struct dentry *min_order_file;
912
913 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
914
915 } fail_page_alloc = {
916         .attr = FAULT_ATTR_INITIALIZER,
917         .ignore_gfp_wait = 1,
918         .ignore_gfp_highmem = 1,
919         .min_order = 1,
920 };
921
922 static int __init setup_fail_page_alloc(char *str)
923 {
924         return setup_fault_attr(&fail_page_alloc.attr, str);
925 }
926 __setup("fail_page_alloc=", setup_fail_page_alloc);
927
928 static int should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
929 {
930         if (order < fail_page_alloc.min_order)
931                 return 0;
932         if (gfp_mask & __GFP_NOFAIL)
933                 return 0;
934         if (fail_page_alloc.ignore_gfp_highmem && (gfp_mask & __GFP_HIGHMEM))
935                 return 0;
936         if (fail_page_alloc.ignore_gfp_wait && (gfp_mask & __GFP_WAIT))
937                 return 0;
938
939         return should_fail(&fail_page_alloc.attr, 1 << order);
940 }
941
942 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
943
944 static int __init fail_page_alloc_debugfs(void)
945 {
946         mode_t mode = S_IFREG | S_IRUSR | S_IWUSR;
947         struct dentry *dir;
948         int err;
949
950         err = init_fault_attr_dentries(&fail_page_alloc.attr,
951                                        "fail_page_alloc");
952         if (err)
953                 return err;
954         dir = fail_page_alloc.attr.dentries.dir;
955
956         fail_page_alloc.ignore_gfp_wait_file =
957                 debugfs_create_bool("ignore-gfp-wait", mode, dir,
958                                       &fail_page_alloc.ignore_gfp_wait);
959
960         fail_page_alloc.ignore_gfp_highmem_file =
961                 debugfs_create_bool("ignore-gfp-highmem", mode, dir,
962                                       &fail_page_alloc.ignore_gfp_highmem);
963         fail_page_alloc.min_order_file =
964                 debugfs_create_u32("min-order", mode, dir,
965                                    &fail_page_alloc.min_order);
966
967         if (!fail_page_alloc.ignore_gfp_wait_file ||
968             !fail_page_alloc.ignore_gfp_highmem_file ||
969             !fail_page_alloc.min_order_file) {
970                 err = -ENOMEM;
971                 debugfs_remove(fail_page_alloc.ignore_gfp_wait_file);
972                 debugfs_remove(fail_page_alloc.ignore_gfp_highmem_file);
973                 debugfs_remove(fail_page_alloc.min_order_file);
974                 cleanup_fault_attr_dentries(&fail_page_alloc.attr);
975         }
976
977         return err;
978 }
979
980 late_initcall(fail_page_alloc_debugfs);
981
982 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
983
984 #else /* CONFIG_FAIL_PAGE_ALLOC */
985
986 static inline int should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
987 {
988         return 0;
989 }
990
991 #endif /* CONFIG_FAIL_PAGE_ALLOC */
992
993 /*
994  * Return 1 if free pages are above 'mark'. This takes into account the order
995  * of the allocation.
996  */
997 int zone_watermark_ok(struct zone *z, int order, unsigned long mark,
998                       int classzone_idx, int alloc_flags)
999 {
1000         /* free_pages my go negative - that's OK */
1001         long min = mark;
1002         long free_pages = zone_page_state(z, NR_FREE_PAGES) - (1 << order) + 1;
1003         int o;
1004
1005         if (alloc_flags & ALLOC_HIGH)
1006                 min -= min / 2;
1007         if (alloc_flags & ALLOC_HARDER)
1008                 min -= min / 4;
1009
1010         if (free_pages <= min + z->lowmem_reserve[classzone_idx])
1011                 return 0;
1012         for (o = 0; o < order; o++) {
1013                 /* At the next order, this order's pages become unavailable */
1014                 free_pages -= z->free_area[o].nr_free << o;
1015
1016                 /* Require fewer higher order pages to be free */
1017                 min >>= 1;
1018
1019                 if (free_pages <= min)
1020                         return 0;
1021         }
1022         return 1;
1023 }
1024
1025 #ifdef CONFIG_NUMA
1026 /*
1027  * zlc_setup - Setup for "zonelist cache".  Uses cached zone data to
1028  * skip over zones that are not allowed by the cpuset, or that have
1029  * been recently (in last second) found to be nearly full.  See further
1030  * comments in mmzone.h.  Reduces cache footprint of zonelist scans
1031  * that have to skip over alot of full or unallowed zones.
1032  *
1033  * If the zonelist cache is present in the passed in zonelist, then
1034  * returns a pointer to the allowed node mask (either the current
1035  * tasks mems_allowed, or node_online_map.)
1036  *
1037  * If the zonelist cache is not available for this zonelist, does
1038  * nothing and returns NULL.
1039  *
1040  * If the fullzones BITMAP in the zonelist cache is stale (more than
1041  * a second since last zap'd) then we zap it out (clear its bits.)
1042  *
1043  * We hold off even calling zlc_setup, until after we've checked the
1044  * first zone in the zonelist, on the theory that most allocations will
1045  * be satisfied from that first zone, so best to examine that zone as
1046  * quickly as we can.
1047  */
1048 static nodemask_t *zlc_setup(struct zonelist *zonelist, int alloc_flags)
1049 {
1050         struct zonelist_cache *zlc;     /* cached zonelist speedup info */
1051         nodemask_t *allowednodes;       /* zonelist_cache approximation */
1052
1053         zlc = zonelist->zlcache_ptr;
1054         if (!zlc)
1055                 return NULL;
1056
1057         if (jiffies - zlc->last_full_zap > 1 * HZ) {
1058                 bitmap_zero(zlc->fullzones, MAX_ZONES_PER_ZONELIST);
1059                 zlc->last_full_zap = jiffies;
1060         }
1061
1062         allowednodes = !in_interrupt() && (alloc_flags & ALLOC_CPUSET) ?
1063                                         &cpuset_current_mems_allowed :
1064                                         &node_online_map;
1065         return allowednodes;
1066 }
1067
1068 /*
1069  * Given 'z' scanning a zonelist, run a couple of quick checks to see
1070  * if it is worth looking at further for free memory:
1071  *  1) Check that the zone isn't thought to be full (doesn't have its
1072  *     bit set in the zonelist_cache fullzones BITMAP).
1073  *  2) Check that the zones node (obtained from the zonelist_cache
1074  *     z_to_n[] mapping) is allowed in the passed in allowednodes mask.
1075  * Return true (non-zero) if zone is worth looking at further, or
1076  * else return false (zero) if it is not.
1077  *
1078  * This check -ignores- the distinction between various watermarks,
1079  * such as GFP_HIGH, GFP_ATOMIC, PF_MEMALLOC, ...  If a zone is
1080  * found to be full for any variation of these watermarks, it will
1081  * be considered full for up to one second by all requests, unless
1082  * we are so low on memory on all allowed nodes that we are forced
1083  * into the second scan of the zonelist.
1084  *
1085  * In the second scan we ignore this zonelist cache and exactly
1086  * apply the watermarks to all zones, even it is slower to do so.
1087  * We are low on memory in the second scan, and should leave no stone
1088  * unturned looking for a free page.
1089  */
1090 static int zlc_zone_worth_trying(struct zonelist *zonelist, struct zone **z,
1091                                                 nodemask_t *allowednodes)
1092 {
1093         struct zonelist_cache *zlc;     /* cached zonelist speedup info */
1094         int i;                          /* index of *z in zonelist zones */
1095         int n;                          /* node that zone *z is on */
1096
1097         zlc = zonelist->zlcache_ptr;
1098         if (!zlc)
1099                 return 1;
1100
1101         i = z - zonelist->zones;
1102         n = zlc->z_to_n[i];
1103
1104         /* This zone is worth trying if it is allowed but not full */
1105         return node_isset(n, *allowednodes) && !test_bit(i, zlc->fullzones);
1106 }
1107
1108 /*
1109  * Given 'z' scanning a zonelist, set the corresponding bit in
1110  * zlc->fullzones, so that subsequent attempts to allocate a page
1111  * from that zone don't waste time re-examining it.
1112  */
1113 static void zlc_mark_zone_full(struct zonelist *zonelist, struct zone **z)
1114 {
1115         struct zonelist_cache *zlc;     /* cached zonelist speedup info */
1116         int i;                          /* index of *z in zonelist zones */
1117
1118         zlc = zonelist->zlcache_ptr;
1119         if (!zlc)
1120                 return;
1121
1122         i = z - zonelist->zones;
1123
1124         set_bit(i, zlc->fullzones);
1125 }
1126
1127 #else   /* CONFIG_NUMA */
1128
1129 static nodemask_t *zlc_setup(struct zonelist *zonelist, int alloc_flags)
1130 {
1131         return NULL;
1132 }
1133
1134 static int zlc_zone_worth_trying(struct zonelist *zonelist, struct zone **z,
1135                                 nodemask_t *allowednodes)
1136 {
1137         return 1;
1138 }
1139
1140 static void zlc_mark_zone_full(struct zonelist *zonelist, struct zone **z)
1141 {
1142 }
1143 #endif  /* CONFIG_NUMA */
1144
1145 /*
1146  * get_page_from_freelist goes through the zonelist trying to allocate
1147  * a page.
1148  */
1149 static struct page *
1150 get_page_from_freelist(gfp_t gfp_mask, unsigned int order,
1151                 struct zonelist *zonelist, int alloc_flags)
1152 {
1153         struct zone **z;
1154         struct page *page = NULL;
1155         int classzone_idx = zone_idx(zonelist->zones[0]);
1156         struct zone *zone;
1157         nodemask_t *allowednodes = NULL;/* zonelist_cache approximation */
1158         int zlc_active = 0;             /* set if using zonelist_cache */
1159         int did_zlc_setup = 0;          /* just call zlc_setup() one time */
1160         enum zone_type highest_zoneidx = -1; /* Gets set for policy zonelists */
1161
1162 zonelist_scan:
1163         /*
1164          * Scan zonelist, looking for a zone with enough free.
1165          * See also cpuset_zone_allowed() comment in kernel/cpuset.c.
1166          */
1167         z = zonelist->zones;
1168
1169         do {
1170                 /*
1171                  * In NUMA, this could be a policy zonelist which contains
1172                  * zones that may not be allowed by the current gfp_mask.
1173                  * Check the zone is allowed by the current flags
1174                  */
1175                 if (unlikely(alloc_should_filter_zonelist(zonelist))) {
1176                         if (highest_zoneidx == -1)
1177                                 highest_zoneidx = gfp_zone(gfp_mask);
1178                         if (zone_idx(*z) > highest_zoneidx)
1179                                 continue;
1180                 }
1181
1182                 if (NUMA_BUILD && zlc_active &&
1183                         !zlc_zone_worth_trying(zonelist, z, allowednodes))
1184                                 continue;
1185                 zone = *z;
1186                 if (unlikely(NUMA_BUILD && (gfp_mask & __GFP_THISNODE) &&
1187                         zone->zone_pgdat != zonelist->zones[0]->zone_pgdat))
1188                                 break;
1189                 if ((alloc_flags & ALLOC_CPUSET) &&
1190                         !cpuset_zone_allowed_softwall(zone, gfp_mask))
1191                                 goto try_next_zone;
1192
1193                 if (!(alloc_flags & ALLOC_NO_WATERMARKS)) {
1194                         unsigned long mark;
1195                         if (alloc_flags & ALLOC_WMARK_MIN)
1196                                 mark = zone->pages_min;
1197                         else if (alloc_flags & ALLOC_WMARK_LOW)
1198                                 mark = zone->pages_low;
1199                         else
1200                                 mark = zone->pages_high;
1201                         if (!zone_watermark_ok(zone, order, mark,
1202                                     classzone_idx, alloc_flags)) {
1203                                 if (!zone_reclaim_mode ||
1204                                     !zone_reclaim(zone, gfp_mask, order))
1205                                         goto this_zone_full;
1206                         }
1207                 }
1208
1209                 page = buffered_rmqueue(zonelist, zone, order, gfp_mask);
1210                 if (page)
1211                         break;
1212 this_zone_full:
1213                 if (NUMA_BUILD)
1214                         zlc_mark_zone_full(zonelist, z);
1215 try_next_zone:
1216                 if (NUMA_BUILD && !did_zlc_setup) {
1217                         /* we do zlc_setup after the first zone is tried */
1218                         allowednodes = zlc_setup(zonelist, alloc_flags);
1219                         zlc_active = 1;
1220                         did_zlc_setup = 1;
1221                 }
1222         } while (*(++z) != NULL);
1223
1224         if (unlikely(NUMA_BUILD && page == NULL && zlc_active)) {
1225                 /* Disable zlc cache for second zonelist scan */
1226                 zlc_active = 0;
1227                 goto zonelist_scan;
1228         }
1229         return page;
1230 }
1231
1232 /*
1233  * This is the 'heart' of the zoned buddy allocator.
1234  */
1235 struct page * fastcall
1236 __alloc_pages(gfp_t gfp_mask, unsigned int order,
1237                 struct zonelist *zonelist)
1238 {
1239         const gfp_t wait = gfp_mask & __GFP_WAIT;
1240         struct zone **z;
1241         struct page *page;
1242         struct reclaim_state reclaim_state;
1243         struct task_struct *p = current;
1244         int do_retry;
1245         int alloc_flags;
1246         int did_some_progress;
1247
1248         might_sleep_if(wait);
1249
1250         if (should_fail_alloc_page(gfp_mask, order))
1251                 return NULL;
1252
1253 restart:
1254         z = zonelist->zones;  /* the list of zones suitable for gfp_mask */
1255
1256         if (unlikely(*z == NULL)) {
1257                 /* Should this ever happen?? */
1258                 return NULL;
1259         }
1260
1261         page = get_page_from_freelist(gfp_mask|__GFP_HARDWALL, order,
1262                                 zonelist, ALLOC_WMARK_LOW|ALLOC_CPUSET);
1263         if (page)
1264                 goto got_pg;
1265
1266         /*
1267          * Code in arch/mips/kernel/module.c wants physically
1268          * contiguous memory only if there is plenty of free of them.
1269          */
1270         if ((gfp_mask & (__GFP_THISNODE | __GFP_NORETRY | __GFP_NOWARN))
1271             == (__GFP_THISNODE | __GFP_NORETRY | __GFP_NOWARN))
1272                 goto nopage;
1273
1274         /*
1275          * GFP_THISNODE (meaning __GFP_THISNODE, __GFP_NORETRY and
1276          * __GFP_NOWARN set) should not cause reclaim since the subsystem
1277          * (f.e. slab) using GFP_THISNODE may choose to trigger reclaim
1278          * using a larger set of nodes after it has established that the
1279          * allowed per node queues are empty and that nodes are
1280          * over allocated.
1281          */
1282         if (NUMA_BUILD && (gfp_mask & GFP_THISNODE) == GFP_THISNODE)
1283                 goto nopage;
1284
1285         for (z = zonelist->zones; *z; z++)
1286                 wakeup_kswapd(*z, order);
1287
1288         if (gfp_mask & 0x80000000)
1289             goto nopage;
1290
1291         /*
1292          * OK, we're below the kswapd watermark and have kicked background
1293          * reclaim. Now things get more complex, so set up alloc_flags according
1294          * to how we want to proceed.
1295          *
1296          * The caller may dip into page reserves a bit more if the caller
1297          * cannot run direct reclaim, or if the caller has realtime scheduling
1298          * policy or is asking for __GFP_HIGH memory.  GFP_ATOMIC requests will
1299          * set both ALLOC_HARDER (!wait) and ALLOC_HIGH (__GFP_HIGH).
1300          */
1301         alloc_flags = ALLOC_WMARK_MIN;
1302         if ((unlikely(rt_task(p)) && !in_interrupt()) || !wait)
1303                 alloc_flags |= ALLOC_HARDER;
1304         if (gfp_mask & __GFP_HIGH)
1305                 alloc_flags |= ALLOC_HIGH;
1306         if (wait)
1307                 alloc_flags |= ALLOC_CPUSET;
1308
1309         /*
1310          * Go through the zonelist again. Let __GFP_HIGH and allocations
1311          * coming from realtime tasks go deeper into reserves.
1312          *
1313          * This is the last chance, in general, before the goto nopage.
1314          * Ignore cpuset if GFP_ATOMIC (!wait) rather than fail alloc.
1315          * See also cpuset_zone_allowed() comment in kernel/cpuset.c.
1316          */
1317         page = get_page_from_freelist(gfp_mask, order, zonelist, alloc_flags);
1318         if (page)
1319                 goto got_pg;
1320
1321         /* This allocation should allow future memory freeing. */
1322
1323 rebalance:
1324         if (((p->flags & PF_MEMALLOC) || unlikely(test_thread_flag(TIF_MEMDIE)))
1325                         && !in_interrupt()) {
1326                 if (!(gfp_mask & __GFP_NOMEMALLOC)) {
1327 nofail_alloc:
1328                         /* go through the zonelist yet again, ignoring mins */
1329                         page = get_page_from_freelist(gfp_mask, order,
1330                                 zonelist, ALLOC_NO_WATERMARKS);
1331                         if (page)
1332                                 goto got_pg;
1333                         if (gfp_mask & __GFP_NOFAIL) {
1334                                 congestion_wait(WRITE, HZ/50);
1335                                 goto nofail_alloc;
1336                         }
1337                 }
1338                 goto nopage;
1339         }
1340
1341         /* Atomic allocations - we can't balance anything */
1342         if (!wait)
1343                 goto nopage;
1344
1345         cond_resched();
1346
1347         /* We now go into synchronous reclaim */
1348         cpuset_memory_pressure_bump();
1349         p->flags |= PF_MEMALLOC;
1350         reclaim_state.reclaimed_slab = 0;
1351         p->reclaim_state = &reclaim_state;
1352
1353         did_some_progress = try_to_free_pages(zonelist->zones, order, gfp_mask);
1354
1355         p->reclaim_state = NULL;
1356         p->flags &= ~PF_MEMALLOC;
1357
1358         cond_resched();
1359
1360         if (likely(did_some_progress)) {
1361                 page = get_page_from_freelist(gfp_mask, order,
1362                                                 zonelist, alloc_flags);
1363                 if (page)
1364                         goto got_pg;
1365         } else if ((gfp_mask & __GFP_FS) && !(gfp_mask & __GFP_NORETRY)) {
1366                 /*
1367                  * Go through the zonelist yet one more time, keep
1368                  * very high watermark here, this is only to catch
1369                  * a parallel oom killing, we must fail if we're still
1370                  * under heavy pressure.
1371                  */
1372                 page = get_page_from_freelist(gfp_mask|__GFP_HARDWALL, order,
1373                                 zonelist, ALLOC_WMARK_HIGH|ALLOC_CPUSET);
1374                 if (page)
1375                         goto got_pg;
1376
1377                 /* The OOM killer will not help higher order allocs so fail */
1378                 if (order > PAGE_ALLOC_COSTLY_ORDER)
1379                         goto nopage;
1380
1381                 out_of_memory(zonelist, gfp_mask, order);
1382                 goto restart;
1383         }
1384
1385         /*
1386          * Don't let big-order allocations loop unless the caller explicitly
1387          * requests that.  Wait for some write requests to complete then retry.
1388          *
1389          * In this implementation, __GFP_REPEAT means __GFP_NOFAIL for order
1390          * <= 3, but that may not be true in other implementations.
1391          */
1392         do_retry = 0;
1393         if (!(gfp_mask & __GFP_NORETRY)) {
1394                 if ((order <= PAGE_ALLOC_COSTLY_ORDER) ||
1395                                                 (gfp_mask & __GFP_REPEAT))
1396                         do_retry = 1;
1397                 if (gfp_mask & __GFP_NOFAIL)
1398                         do_retry = 1;
1399         }
1400         if (do_retry) {
1401                 congestion_wait(WRITE, HZ/50);
1402                 goto rebalance;
1403         }
1404
1405 nopage:
1406         if (!(gfp_mask & __GFP_NOWARN) && printk_ratelimit()) {
1407                 printk(KERN_WARNING "%s: page allocation failure."
1408                         " order:%d, mode:0x%x\n",
1409                         p->comm, order, gfp_mask);
1410                 dump_stack();
1411                 show_mem();
1412         }
1413 got_pg:
1414         return page;
1415 }
1416
1417 EXPORT_SYMBOL(__alloc_pages);
1418
1419 /*
1420  * Common helper functions.
1421  */
1422 fastcall unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order)
1423 {
1424         struct page * page;
1425         page = alloc_pages(gfp_mask, order);
1426         if (!page)
1427                 return 0;
1428         return (unsigned long) page_address(page);
1429 }
1430
1431 EXPORT_SYMBOL(__get_free_pages);
1432
1433 fastcall unsigned long get_zeroed_page(gfp_t gfp_mask)
1434 {
1435         struct page * page;
1436
1437         /*
1438          * get_zeroed_page() returns a 32-bit address, which cannot represent
1439          * a highmem page
1440          */
1441         VM_BUG_ON((gfp_mask & __GFP_HIGHMEM) != 0);
1442
1443         page = alloc_pages(gfp_mask | __GFP_ZERO, 0);
1444         if (page)
1445                 return (unsigned long) page_address(page);
1446         return 0;
1447 }
1448
1449 EXPORT_SYMBOL(get_zeroed_page);
1450
1451 void __pagevec_free(struct pagevec *pvec)
1452 {
1453         int i = pagevec_count(pvec);
1454
1455         while (--i >= 0)
1456                 free_hot_cold_page(pvec->pages[i], pvec->cold);
1457 }
1458
1459 fastcall void __free_pages(struct page *page, unsigned int order)
1460 {
1461         if (put_page_testzero(page)) {
1462                 if (order == 0)
1463                         free_hot_page(page);
1464                 else
1465                         __free_pages_ok(page, order);
1466         }
1467 }
1468
1469 EXPORT_SYMBOL(__free_pages);
1470
1471 fastcall void free_pages(unsigned long addr, unsigned int order)
1472 {
1473         if (addr != 0) {
1474                 VM_BUG_ON(!virt_addr_valid((void *)addr));
1475                 __free_pages(virt_to_page((void *)addr), order);
1476         }
1477 }
1478
1479 EXPORT_SYMBOL(free_pages);
1480
1481 static unsigned int nr_free_zone_pages(int offset)
1482 {
1483         /* Just pick one node, since fallback list is circular */
1484         pg_data_t *pgdat = NODE_DATA(numa_node_id());
1485         unsigned int sum = 0;
1486
1487         struct zonelist *zonelist = pgdat->node_zonelists + offset;
1488         struct zone **zonep = zonelist->zones;
1489         struct zone *zone;
1490
1491         for (zone = *zonep++; zone; zone = *zonep++) {
1492                 unsigned long size = zone->present_pages;
1493                 unsigned long high = zone->pages_high;
1494                 if (size > high)
1495                         sum += size - high;
1496         }
1497
1498         return sum;
1499 }
1500
1501 /*
1502  * Amount of free RAM allocatable within ZONE_DMA and ZONE_NORMAL
1503  */
1504 unsigned int nr_free_buffer_pages(void)
1505 {
1506         return nr_free_zone_pages(gfp_zone(GFP_USER));
1507 }
1508 EXPORT_SYMBOL_GPL(nr_free_buffer_pages);
1509
1510 /*
1511  * Amount of free RAM allocatable within all zones
1512  */
1513 unsigned int nr_free_pagecache_pages(void)
1514 {
1515         return nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE));
1516 }
1517
1518 static inline void show_node(struct zone *zone)
1519 {
1520         if (NUMA_BUILD)
1521                 printk("Node %d ", zone_to_nid(zone));
1522 }
1523
1524 void si_meminfo(struct sysinfo *val)
1525 {
1526         val->totalram = totalram_pages;
1527         val->sharedram = 0;
1528         val->freeram = global_page_state(NR_FREE_PAGES);
1529         val->bufferram = nr_blockdev_pages();
1530         val->totalhigh = totalhigh_pages;
1531         val->freehigh = nr_free_highpages();
1532         val->mem_unit = PAGE_SIZE;
1533 }
1534
1535 EXPORT_SYMBOL(si_meminfo);
1536
1537 #ifdef CONFIG_NUMA
1538 void si_meminfo_node(struct sysinfo *val, int nid)
1539 {
1540         pg_data_t *pgdat = NODE_DATA(nid);
1541
1542         val->totalram = pgdat->node_present_pages;
1543         val->freeram = node_page_state(nid, NR_FREE_PAGES);
1544 #ifdef CONFIG_HIGHMEM
1545         val->totalhigh = pgdat->node_zones[ZONE_HIGHMEM].present_pages;
1546         val->freehigh = zone_page_state(&pgdat->node_zones[ZONE_HIGHMEM],
1547                         NR_FREE_PAGES);
1548 #else
1549         val->totalhigh = 0;
1550         val->freehigh = 0;
1551 #endif
1552         val->mem_unit = PAGE_SIZE;
1553 }
1554 #endif
1555
1556 #define K(x) ((x) << (PAGE_SHIFT-10))
1557
1558 /*
1559  * Show free area list (used inside shift_scroll-lock stuff)
1560  * We also calculate the percentage fragmentation. We do this by counting the
1561  * memory on each free list with the exception of the first item on the list.
1562  */
1563 void show_free_areas(void)
1564 {
1565         int cpu;
1566         struct zone *zone;
1567
1568         for_each_zone(zone) {
1569                 if (!populated_zone(zone))
1570                         continue;
1571
1572                 show_node(zone);
1573                 printk("%s per-cpu:\n", zone->name);
1574
1575                 for_each_online_cpu(cpu) {
1576                         struct per_cpu_pageset *pageset;
1577
1578                         pageset = zone_pcp(zone, cpu);
1579
1580                         printk("CPU %4d: Hot: hi:%5d, btch:%4d usd:%4d   "
1581                                "Cold: hi:%5d, btch:%4d usd:%4d\n",
1582                                cpu, pageset->pcp[0].high,
1583                                pageset->pcp[0].batch, pageset->pcp[0].count,
1584                                pageset->pcp[1].high, pageset->pcp[1].batch,
1585                                pageset->pcp[1].count);
1586                 }
1587         }
1588
1589         printk("Active:%lu inactive:%lu dirty:%lu writeback:%lu unstable:%lu\n"
1590                 " free:%lu slab:%lu mapped:%lu pagetables:%lu bounce:%lu\n",
1591                 global_page_state(NR_ACTIVE),
1592                 global_page_state(NR_INACTIVE),
1593                 global_page_state(NR_FILE_DIRTY),
1594                 global_page_state(NR_WRITEBACK),
1595                 global_page_state(NR_UNSTABLE_NFS),
1596                 global_page_state(NR_FREE_PAGES),
1597                 global_page_state(NR_SLAB_RECLAIMABLE) +
1598                         global_page_state(NR_SLAB_UNRECLAIMABLE),
1599                 global_page_state(NR_FILE_MAPPED),
1600                 global_page_state(NR_PAGETABLE),
1601                 global_page_state(NR_BOUNCE));
1602
1603         for_each_zone(zone) {
1604                 int i;
1605
1606                 if (!populated_zone(zone))
1607                         continue;
1608
1609                 show_node(zone);
1610                 printk("%s"
1611                         " free:%lukB"
1612                         " min:%lukB"
1613                         " low:%lukB"
1614                         " high:%lukB"
1615                         " active:%lukB"
1616                         " inactive:%lukB"
1617                         " present:%lukB"
1618                         " pages_scanned:%lu"
1619                         " all_unreclaimable? %s"
1620                         "\n",
1621                         zone->name,
1622                         K(zone_page_state(zone, NR_FREE_PAGES)),
1623                         K(zone->pages_min),
1624                         K(zone->pages_low),
1625                         K(zone->pages_high),
1626                         K(zone_page_state(zone, NR_ACTIVE)),
1627                         K(zone_page_state(zone, NR_INACTIVE)),
1628                         K(zone->present_pages),
1629                         zone->pages_scanned,
1630                         (zone->all_unreclaimable ? "yes" : "no")
1631                         );
1632                 printk("lowmem_reserve[]:");
1633                 for (i = 0; i < MAX_NR_ZONES; i++)
1634                         printk(" %lu", zone->lowmem_reserve[i]);
1635                 printk("\n");
1636         }
1637
1638         for_each_zone(zone) {
1639                 unsigned long nr[MAX_ORDER], flags, order, total = 0;
1640
1641                 if (!populated_zone(zone))
1642                         continue;
1643
1644                 show_node(zone);
1645                 printk("%s: ", zone->name);
1646
1647                 spin_lock_irqsave(&zone->lock, flags);
1648                 for (order = 0; order < MAX_ORDER; order++) {
1649                         nr[order] = zone->free_area[order].nr_free;
1650                         total += nr[order] << order;
1651                 }
1652                 spin_unlock_irqrestore(&zone->lock, flags);
1653                 for (order = 0; order < MAX_ORDER; order++)
1654                         printk("%lu*%lukB ", nr[order], K(1UL) << order);
1655                 printk("= %lukB\n", K(total));
1656         }
1657
1658         show_swap_cache_info();
1659 }
1660
1661 /*
1662  * Builds allocation fallback zone lists.
1663  *
1664  * Add all populated zones of a node to the zonelist.
1665  */
1666 static int build_zonelists_node(pg_data_t *pgdat, struct zonelist *zonelist,
1667                                 int nr_zones, enum zone_type zone_type)
1668 {
1669         struct zone *zone;
1670
1671         BUG_ON(zone_type >= MAX_NR_ZONES);
1672         zone_type++;
1673
1674         do {
1675                 zone_type--;
1676                 zone = pgdat->node_zones + zone_type;
1677                 if (populated_zone(zone)) {
1678                         zonelist->zones[nr_zones++] = zone;
1679                         check_highest_zone(zone_type);
1680                 }
1681
1682         } while (zone_type);
1683         return nr_zones;
1684 }
1685
1686
1687 /*
1688  *  zonelist_order:
1689  *  0 = automatic detection of better ordering.
1690  *  1 = order by ([node] distance, -zonetype)
1691  *  2 = order by (-zonetype, [node] distance)
1692  *
1693  *  If not NUMA, ZONELIST_ORDER_ZONE and ZONELIST_ORDER_NODE will create
1694  *  the same zonelist. So only NUMA can configure this param.
1695  */
1696 #define ZONELIST_ORDER_DEFAULT  0
1697 #define ZONELIST_ORDER_NODE     1
1698 #define ZONELIST_ORDER_ZONE     2
1699
1700 /* zonelist order in the kernel.
1701  * set_zonelist_order() will set this to NODE or ZONE.
1702  */
1703 static int current_zonelist_order = ZONELIST_ORDER_DEFAULT;
1704 static char zonelist_order_name[3][8] = {"Default", "Node", "Zone"};
1705
1706
1707 #ifdef CONFIG_NUMA
1708 /* The value user specified ....changed by config */
1709 static int user_zonelist_order = ZONELIST_ORDER_DEFAULT;
1710 /* string for sysctl */
1711 #define NUMA_ZONELIST_ORDER_LEN 16
1712 char numa_zonelist_order[16] = "default";
1713
1714 /*
1715  * interface for configure zonelist ordering.
1716  * command line option "numa_zonelist_order"
1717  *      = "[dD]efault   - default, automatic configuration.
1718  *      = "[nN]ode      - order by node locality, then by zone within node
1719  *      = "[zZ]one      - order by zone, then by locality within zone
1720  */
1721
1722 static int __parse_numa_zonelist_order(char *s)
1723 {
1724         if (*s == 'd' || *s == 'D') {
1725                 user_zonelist_order = ZONELIST_ORDER_DEFAULT;
1726         } else if (*s == 'n' || *s == 'N') {
1727                 user_zonelist_order = ZONELIST_ORDER_NODE;
1728         } else if (*s == 'z' || *s == 'Z') {
1729                 user_zonelist_order = ZONELIST_ORDER_ZONE;
1730         } else {
1731                 printk(KERN_WARNING
1732                         "Ignoring invalid numa_zonelist_order value:  "
1733                         "%s\n", s);
1734                 return -EINVAL;
1735         }
1736         return 0;
1737 }
1738
1739 static __init int setup_numa_zonelist_order(char *s)
1740 {
1741         if (s)
1742                 return __parse_numa_zonelist_order(s);
1743         return 0;
1744 }
1745 early_param("numa_zonelist_order", setup_numa_zonelist_order);
1746
1747 /*
1748  * sysctl handler for numa_zonelist_order
1749  */
1750 int numa_zonelist_order_handler(ctl_table *table, int write,
1751                 struct file *file, void __user *buffer, size_t *length,
1752                 loff_t *ppos)
1753 {
1754         char saved_string[NUMA_ZONELIST_ORDER_LEN];
1755         int ret;
1756
1757         if (write)
1758                 strncpy(saved_string, (char*)table->data,
1759                         NUMA_ZONELIST_ORDER_LEN);
1760         ret = proc_dostring(table, write, file, buffer, length, ppos);
1761         if (ret)
1762                 return ret;
1763         if (write) {
1764                 int oldval = user_zonelist_order;
1765                 if (__parse_numa_zonelist_order((char*)table->data)) {
1766                         /*
1767                          * bogus value.  restore saved string
1768                          */
1769                         strncpy((char*)table->data, saved_string,
1770                                 NUMA_ZONELIST_ORDER_LEN);
1771                         user_zonelist_order = oldval;
1772                 } else if (oldval != user_zonelist_order)
1773                         build_all_zonelists();
1774         }
1775         return 0;
1776 }
1777
1778
1779 #define MAX_NODE_LOAD (num_online_nodes())
1780 static int node_load[MAX_NUMNODES];
1781
1782 /**
1783  * find_next_best_node - find the next node that should appear in a given node's fallback list
1784  * @node: node whose fallback list we're appending
1785  * @used_node_mask: nodemask_t of already used nodes
1786  *
1787  * We use a number of factors to determine which is the next node that should
1788  * appear on a given node's fallback list.  The node should not have appeared
1789  * already in @node's fallback list, and it should be the next closest node
1790  * according to the distance array (which contains arbitrary distance values
1791  * from each node to each node in the system), and should also prefer nodes
1792  * with no CPUs, since presumably they'll have very little allocation pressure
1793  * on them otherwise.
1794  * It returns -1 if no node is found.
1795  */
1796 static int find_next_best_node(int node, nodemask_t *used_node_mask)
1797 {
1798         int n, val;
1799         int min_val = INT_MAX;
1800         int best_node = -1;
1801
1802         /* Use the local node if we haven't already */
1803         if (!node_isset(node, *used_node_mask)) {
1804                 node_set(node, *used_node_mask);
1805                 return node;
1806         }
1807
1808         for_each_online_node(n) {
1809                 cpumask_t tmp;
1810
1811                 /* Don't want a node to appear more than once */
1812                 if (node_isset(n, *used_node_mask))
1813                         continue;
1814
1815                 /* Use the distance array to find the distance */
1816                 val = node_distance(node, n);
1817
1818                 /* Penalize nodes under us ("prefer the next node") */
1819                 val += (n < node);
1820
1821                 /* Give preference to headless and unused nodes */
1822                 tmp = node_to_cpumask(n);
1823                 if (!cpus_empty(tmp))
1824                         val += PENALTY_FOR_NODE_WITH_CPUS;
1825
1826                 /* Slight preference for less loaded node */
1827                 val *= (MAX_NODE_LOAD*MAX_NUMNODES);
1828                 val += node_load[n];
1829
1830                 if (val < min_val) {
1831                         min_val = val;
1832                         best_node = n;
1833                 }
1834         }
1835
1836         if (best_node >= 0)
1837                 node_set(best_node, *used_node_mask);
1838
1839         return best_node;
1840 }
1841
1842
1843 /*
1844  * Build zonelists ordered by node and zones within node.
1845  * This results in maximum locality--normal zone overflows into local
1846  * DMA zone, if any--but risks exhausting DMA zone.
1847  */
1848 static void build_zonelists_in_node_order(pg_data_t *pgdat, int node)
1849 {
1850         enum zone_type i;
1851         int j;
1852         struct zonelist *zonelist;
1853
1854         for (i = 0; i < MAX_NR_ZONES; i++) {
1855                 zonelist = pgdat->node_zonelists + i;
1856                 for (j = 0; zonelist->zones[j] != NULL; j++)
1857                         ;
1858                 j = build_zonelists_node(NODE_DATA(node), zonelist, j, i);
1859                 zonelist->zones[j] = NULL;
1860         }
1861 }
1862
1863 /*
1864  * Build zonelists ordered by zone and nodes within zones.
1865  * This results in conserving DMA zone[s] until all Normal memory is
1866  * exhausted, but results in overflowing to remote node while memory
1867  * may still exist in local DMA zone.
1868  */
1869 static int node_order[MAX_NUMNODES];
1870
1871 static void build_zonelists_in_zone_order(pg_data_t *pgdat, int nr_nodes)
1872 {
1873         enum zone_type i;
1874         int pos, j, node;
1875         int zone_type;          /* needs to be signed */
1876         struct zone *z;
1877         struct zonelist *zonelist;
1878
1879         for (i = 0; i < MAX_NR_ZONES; i++) {
1880                 zonelist = pgdat->node_zonelists + i;
1881                 pos = 0;
1882                 for (zone_type = i; zone_type >= 0; zone_type--) {
1883                         for (j = 0; j < nr_nodes; j++) {
1884                                 node = node_order[j];
1885                                 z = &NODE_DATA(node)->node_zones[zone_type];
1886                                 if (populated_zone(z)) {
1887                                         zonelist->zones[pos++] = z;
1888                                         check_highest_zone(zone_type);
1889                                 }
1890                         }
1891                 }
1892                 zonelist->zones[pos] = NULL;
1893         }
1894 }
1895
1896 static int default_zonelist_order(void)
1897 {
1898         int nid, zone_type;
1899         unsigned long low_kmem_size,total_size;
1900         struct zone *z;
1901         int average_size;
1902         /*
1903          * ZONE_DMA and ZONE_DMA32 can be very small area in the sytem.
1904          * If they are really small and used heavily, the system can fall
1905          * into OOM very easily.
1906          * This function detect ZONE_DMA/DMA32 size and confgigures zone order.
1907          */
1908         /* Is there ZONE_NORMAL ? (ex. ppc has only DMA zone..) */
1909         low_kmem_size = 0;
1910         total_size = 0;
1911         for_each_online_node(nid) {
1912                 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
1913                         z = &NODE_DATA(nid)->node_zones[zone_type];
1914                         if (populated_zone(z)) {
1915                                 if (zone_type < ZONE_NORMAL)
1916                                         low_kmem_size += z->present_pages;
1917                                 total_size += z->present_pages;
1918                         }
1919                 }
1920         }
1921         if (!low_kmem_size ||  /* there are no DMA area. */
1922             low_kmem_size > total_size/2) /* DMA/DMA32 is big. */
1923                 return ZONELIST_ORDER_NODE;
1924         /*
1925          * look into each node's config.
1926          * If there is a node whose DMA/DMA32 memory is very big area on
1927          * local memory, NODE_ORDER may be suitable.
1928          */
1929         average_size = total_size / (num_online_nodes() + 1);
1930         for_each_online_node(nid) {
1931                 low_kmem_size = 0;
1932                 total_size = 0;
1933                 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
1934                         z = &NODE_DATA(nid)->node_zones[zone_type];
1935                         if (populated_zone(z)) {
1936                                 if (zone_type < ZONE_NORMAL)
1937                                         low_kmem_size += z->present_pages;
1938                                 total_size += z->present_pages;
1939                         }
1940                 }
1941                 if (low_kmem_size &&
1942                     total_size > average_size && /* ignore small node */
1943                     low_kmem_size > total_size * 70/100)
1944                         return ZONELIST_ORDER_NODE;
1945         }
1946         return ZONELIST_ORDER_ZONE;
1947 }
1948
1949 static void set_zonelist_order(void)
1950 {
1951         if (user_zonelist_order == ZONELIST_ORDER_DEFAULT)
1952                 current_zonelist_order = default_zonelist_order();
1953         else
1954                 current_zonelist_order = user_zonelist_order;
1955 }
1956
1957 static void build_zonelists(pg_data_t *pgdat)
1958 {
1959         int j, node, load;
1960         enum zone_type i;
1961         nodemask_t used_mask;
1962         int local_node, prev_node;
1963         struct zonelist *zonelist;
1964         int order = current_zonelist_order;
1965
1966         /* initialize zonelists */
1967         for (i = 0; i < MAX_NR_ZONES; i++) {
1968                 zonelist = pgdat->node_zonelists + i;
1969                 zonelist->zones[0] = NULL;
1970         }
1971
1972         /* NUMA-aware ordering of nodes */
1973         local_node = pgdat->node_id;
1974         load = num_online_nodes();
1975         prev_node = local_node;
1976         nodes_clear(used_mask);
1977
1978         memset(node_load, 0, sizeof(node_load));
1979         memset(node_order, 0, sizeof(node_order));
1980         j = 0;
1981
1982         while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
1983                 int distance = node_distance(local_node, node);
1984
1985                 /*
1986                  * If another node is sufficiently far away then it is better
1987                  * to reclaim pages in a zone before going off node.
1988                  */
1989                 if (distance > RECLAIM_DISTANCE)
1990                         zone_reclaim_mode = 1;
1991
1992                 /*
1993                  * We don't want to pressure a particular node.
1994                  * So adding penalty to the first node in same
1995                  * distance group to make it round-robin.
1996                  */
1997                 if (distance != node_distance(local_node, prev_node))
1998                         node_load[node] = load;
1999
2000                 prev_node = node;
2001                 load--;
2002                 if (order == ZONELIST_ORDER_NODE)
2003                         build_zonelists_in_node_order(pgdat, node);
2004                 else
2005                         node_order[j++] = node; /* remember order */
2006         }
2007
2008         if (order == ZONELIST_ORDER_ZONE) {
2009                 /* calculate node order -- i.e., DMA last! */
2010                 build_zonelists_in_zone_order(pgdat, j);
2011         }
2012 }
2013
2014 /* Construct the zonelist performance cache - see further mmzone.h */
2015 static void build_zonelist_cache(pg_data_t *pgdat)
2016 {
2017         int i;
2018
2019         for (i = 0; i < MAX_NR_ZONES; i++) {
2020                 struct zonelist *zonelist;
2021                 struct zonelist_cache *zlc;
2022                 struct zone **z;
2023
2024                 zonelist = pgdat->node_zonelists + i;
2025                 zonelist->zlcache_ptr = zlc = &zonelist->zlcache;
2026                 bitmap_zero(zlc->fullzones, MAX_ZONES_PER_ZONELIST);
2027                 for (z = zonelist->zones; *z; z++)
2028                         zlc->z_to_n[z - zonelist->zones] = zone_to_nid(*z);
2029         }
2030 }
2031
2032
2033 #else   /* CONFIG_NUMA */
2034
2035 static void set_zonelist_order(void)
2036 {
2037         current_zonelist_order = ZONELIST_ORDER_ZONE;
2038 }
2039
2040 static void build_zonelists(pg_data_t *pgdat)
2041 {
2042         int node, local_node;
2043         enum zone_type i,j;
2044
2045         local_node = pgdat->node_id;
2046         for (i = 0; i < MAX_NR_ZONES; i++) {
2047                 struct zonelist *zonelist;
2048
2049                 zonelist = pgdat->node_zonelists + i;
2050
2051                 j = build_zonelists_node(pgdat, zonelist, 0, i);
2052                 /*
2053                  * Now we build the zonelist so that it contains the zones
2054                  * of all the other nodes.
2055                  * We don't want to pressure a particular node, so when
2056                  * building the zones for node N, we make sure that the
2057                  * zones coming right after the local ones are those from
2058                  * node N+1 (modulo N)
2059                  */
2060                 for (node = local_node + 1; node < MAX_NUMNODES; node++) {
2061                         if (!node_online(node))
2062                                 continue;
2063                         j = build_zonelists_node(NODE_DATA(node), zonelist, j, i);
2064                 }
2065                 for (node = 0; node < local_node; node++) {
2066                         if (!node_online(node))
2067                                 continue;
2068                         j = build_zonelists_node(NODE_DATA(node), zonelist, j, i);
2069                 }
2070
2071                 zonelist->zones[j] = NULL;
2072         }
2073 }
2074
2075 /* non-NUMA variant of zonelist performance cache - just NULL zlcache_ptr */
2076 static void build_zonelist_cache(pg_data_t *pgdat)
2077 {
2078         int i;
2079
2080         for (i = 0; i < MAX_NR_ZONES; i++)
2081                 pgdat->node_zonelists[i].zlcache_ptr = NULL;
2082 }
2083
2084 #endif  /* CONFIG_NUMA */
2085
2086 /* return values int ....just for stop_machine_run() */
2087 static int __build_all_zonelists(void *dummy)
2088 {
2089         int nid;
2090
2091         for_each_online_node(nid) {
2092                 build_zonelists(NODE_DATA(nid));
2093                 build_zonelist_cache(NODE_DATA(nid));
2094         }
2095         return 0;
2096 }
2097
2098 void build_all_zonelists(void)
2099 {
2100         set_zonelist_order();
2101
2102         if (system_state == SYSTEM_BOOTING) {
2103                 __build_all_zonelists(NULL);
2104                 cpuset_init_current_mems_allowed();
2105         } else {
2106                 /* we have to stop all cpus to guaranntee there is no user
2107                    of zonelist */
2108                 stop_machine_run(__build_all_zonelists, NULL, NR_CPUS);
2109                 /* cpuset refresh routine should be here */
2110         }
2111         vm_total_pages = nr_free_pagecache_pages();
2112         printk("Built %i zonelists in %s order.  Total pages: %ld\n",
2113                         num_online_nodes(),
2114                         zonelist_order_name[current_zonelist_order],
2115                         vm_total_pages);
2116 #ifdef CONFIG_NUMA
2117         printk("Policy zone: %s\n", zone_names[policy_zone]);
2118 #endif
2119 }
2120
2121 /*
2122  * Helper functions to size the waitqueue hash table.
2123  * Essentially these want to choose hash table sizes sufficiently
2124  * large so that collisions trying to wait on pages are rare.
2125  * But in fact, the number of active page waitqueues on typical
2126  * systems is ridiculously low, less than 200. So this is even
2127  * conservative, even though it seems large.
2128  *
2129  * The constant PAGES_PER_WAITQUEUE specifies the ratio of pages to
2130  * waitqueues, i.e. the size of the waitq table given the number of pages.
2131  */
2132 #define PAGES_PER_WAITQUEUE     256
2133
2134 #ifndef CONFIG_MEMORY_HOTPLUG
2135 static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
2136 {
2137         unsigned long size = 1;
2138
2139         pages /= PAGES_PER_WAITQUEUE;
2140
2141         while (size < pages)
2142                 size <<= 1;
2143
2144         /*
2145          * Once we have dozens or even hundreds of threads sleeping
2146          * on IO we've got bigger problems than wait queue collision.
2147          * Limit the size of the wait table to a reasonable size.
2148          */
2149         size = min(size, 4096UL);
2150
2151         return max(size, 4UL);
2152 }
2153 #else
2154 /*
2155  * A zone's size might be changed by hot-add, so it is not possible to determine
2156  * a suitable size for its wait_table.  So we use the maximum size now.
2157  *
2158  * The max wait table size = 4096 x sizeof(wait_queue_head_t).   ie:
2159  *
2160  *    i386 (preemption config)    : 4096 x 16 = 64Kbyte.
2161  *    ia64, x86-64 (no preemption): 4096 x 20 = 80Kbyte.
2162  *    ia64, x86-64 (preemption)   : 4096 x 24 = 96Kbyte.
2163  *
2164  * The maximum entries are prepared when a zone's memory is (512K + 256) pages
2165  * or more by the traditional way. (See above).  It equals:
2166  *
2167  *    i386, x86-64, powerpc(4K page size) : =  ( 2G + 1M)byte.
2168  *    ia64(16K page size)                 : =  ( 8G + 4M)byte.
2169  *    powerpc (64K page size)             : =  (32G +16M)byte.
2170  */
2171 static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
2172 {
2173         return 4096UL;
2174 }
2175 #endif
2176
2177 /*
2178  * This is an integer logarithm so that shifts can be used later
2179  * to extract the more random high bits from the multiplicative
2180  * hash function before the remainder is taken.
2181  */
2182 static inline unsigned long wait_table_bits(unsigned long size)
2183 {
2184         return ffz(~size);
2185 }
2186
2187 #define LONG_ALIGN(x) (((x)+(sizeof(long))-1)&~((sizeof(long))-1))
2188
2189 /*
2190  * Initially all pages are reserved - free ones are freed
2191  * up by free_all_bootmem() once the early boot process is
2192  * done. Non-atomic initialization, single-pass.
2193  */
2194 void __meminit memmap_init_zone(unsigned long size, int nid, unsigned long zone,
2195                 unsigned long start_pfn, enum memmap_context context)
2196 {
2197         struct page *page;
2198         unsigned long end_pfn = start_pfn + size;
2199         unsigned long pfn;
2200
2201         for (pfn = start_pfn; pfn < end_pfn; pfn++) {
2202                 /*
2203                  * There can be holes in boot-time mem_map[]s
2204                  * handed to this function.  They do not
2205                  * exist on hotplugged memory.
2206                  */
2207                 if (context == MEMMAP_EARLY) {
2208                         if (!early_pfn_valid(pfn))
2209                                 continue;
2210                         if (!early_pfn_in_nid(pfn, nid))
2211                                 continue;
2212                 }
2213                 page = pfn_to_page(pfn);
2214                 set_page_links(page, zone, nid, pfn);
2215                 init_page_count(page);
2216                 reset_page_mapcount(page);
2217                 SetPageReserved(page);
2218                 INIT_LIST_HEAD(&page->lru);
2219 #ifdef WANT_PAGE_VIRTUAL
2220                 /* The shift won't overflow because ZONE_NORMAL is below 4G. */
2221                 if (!is_highmem_idx(zone))
2222                         set_page_address(page, __va(pfn << PAGE_SHIFT));
2223 #endif
2224         }
2225 }
2226
2227 static void __meminit zone_init_free_lists(struct pglist_data *pgdat,
2228                                 struct zone *zone, unsigned long size)
2229 {
2230         int order;
2231         for (order = 0; order < MAX_ORDER ; order++) {
2232                 INIT_LIST_HEAD(&zone->free_area[order].free_list);
2233                 zone->free_area[order].nr_free = 0;
2234         }
2235 }
2236
2237 #ifndef __HAVE_ARCH_MEMMAP_INIT
2238 #define memmap_init(size, nid, zone, start_pfn) \
2239         memmap_init_zone((size), (nid), (zone), (start_pfn), MEMMAP_EARLY)
2240 #endif
2241
2242 static int __devinit zone_batchsize(struct zone *zone)
2243 {
2244         int batch;
2245
2246         /*
2247          * The per-cpu-pages pools are set to around 1000th of the
2248          * size of the zone.  But no more than 1/2 of a meg.
2249          *
2250          * OK, so we don't know how big the cache is.  So guess.
2251          */
2252         batch = zone->present_pages / 1024;
2253         if (batch * PAGE_SIZE > 512 * 1024)
2254                 batch = (512 * 1024) / PAGE_SIZE;
2255         batch /= 4;             /* We effectively *= 4 below */
2256         if (batch < 1)
2257                 batch = 1;
2258
2259         /*
2260          * Clamp the batch to a 2^n - 1 value. Having a power
2261          * of 2 value was found to be more likely to have
2262          * suboptimal cache aliasing properties in some cases.
2263          *
2264          * For example if 2 tasks are alternately allocating
2265          * batches of pages, one task can end up with a lot
2266          * of pages of one half of the possible page colors
2267          * and the other with pages of the other colors.
2268          */
2269         batch = (1 << (fls(batch + batch/2)-1)) - 1;
2270
2271         return batch;
2272 }
2273
2274 inline void setup_pageset(struct per_cpu_pageset *p, unsigned long batch)
2275 {
2276         struct per_cpu_pages *pcp;
2277
2278         memset(p, 0, sizeof(*p));
2279
2280         pcp = &p->pcp[0];               /* hot */
2281         pcp->count = 0;
2282         pcp->high = 6 * batch;
2283         pcp->batch = max(1UL, 1 * batch);
2284         INIT_LIST_HEAD(&pcp->list);
2285
2286         pcp = &p->pcp[1];               /* cold*/
2287         pcp->count = 0;
2288         pcp->high = 2 * batch;
2289         pcp->batch = max(1UL, batch/2);
2290         INIT_LIST_HEAD(&pcp->list);
2291 }
2292
2293 /*
2294  * setup_pagelist_highmark() sets the high water mark for hot per_cpu_pagelist
2295  * to the value high for the pageset p.
2296  */
2297
2298 static void setup_pagelist_highmark(struct per_cpu_pageset *p,
2299                                 unsigned long high)
2300 {
2301         struct per_cpu_pages *pcp;
2302
2303         pcp = &p->pcp[0]; /* hot list */
2304         pcp->high = high;
2305         pcp->batch = max(1UL, high/4);
2306         if ((high/4) > (PAGE_SHIFT * 8))
2307                 pcp->batch = PAGE_SHIFT * 8;
2308 }
2309
2310
2311 #ifdef CONFIG_NUMA
2312 /*
2313  * Boot pageset table. One per cpu which is going to be used for all
2314  * zones and all nodes. The parameters will be set in such a way
2315  * that an item put on a list will immediately be handed over to
2316  * the buddy list. This is safe since pageset manipulation is done
2317  * with interrupts disabled.
2318  *
2319  * Some NUMA counter updates may also be caught by the boot pagesets.
2320  *
2321  * The boot_pagesets must be kept even after bootup is complete for
2322  * unused processors and/or zones. They do play a role for bootstrapping
2323  * hotplugged processors.
2324  *
2325  * zoneinfo_show() and maybe other functions do
2326  * not check if the processor is online before following the pageset pointer.
2327  * Other parts of the kernel may not check if the zone is available.
2328  */
2329 static struct per_cpu_pageset boot_pageset[NR_CPUS];
2330
2331 /*
2332  * Dynamically allocate memory for the
2333  * per cpu pageset array in struct zone.
2334  */
2335 static int __cpuinit process_zones(int cpu)
2336 {
2337         struct zone *zone, *dzone;
2338
2339         for_each_zone(zone) {
2340
2341                 if (!populated_zone(zone))
2342                         continue;
2343
2344                 zone_pcp(zone, cpu) = kmalloc_node(sizeof(struct per_cpu_pageset),
2345                                          GFP_KERNEL, cpu_to_node(cpu));
2346                 if (!zone_pcp(zone, cpu))
2347                         goto bad;
2348
2349                 setup_pageset(zone_pcp(zone, cpu), zone_batchsize(zone));
2350
2351                 if (percpu_pagelist_fraction)
2352                         setup_pagelist_highmark(zone_pcp(zone, cpu),
2353                                 (zone->present_pages / percpu_pagelist_fraction));
2354         }
2355
2356         return 0;
2357 bad:
2358         for_each_zone(dzone) {
2359                 if (!populated_zone(dzone))
2360                         continue;
2361                 if (dzone == zone)
2362                         break;
2363                 kfree(zone_pcp(dzone, cpu));
2364                 zone_pcp(dzone, cpu) = NULL;
2365         }
2366         return -ENOMEM;
2367 }
2368
2369 static inline void free_zone_pagesets(int cpu)
2370 {
2371         struct zone *zone;
2372
2373         for_each_zone(zone) {
2374                 struct per_cpu_pageset *pset = zone_pcp(zone, cpu);
2375
2376                 /* Free per_cpu_pageset if it is slab allocated */
2377                 if (pset != &boot_pageset[cpu])
2378                         kfree(pset);
2379                 zone_pcp(zone, cpu) = NULL;
2380         }
2381 }
2382
2383 static int __cpuinit pageset_cpuup_callback(struct notifier_block *nfb,
2384                 unsigned long action,
2385                 void *hcpu)
2386 {
2387         int cpu = (long)hcpu;
2388         int ret = NOTIFY_OK;
2389
2390         switch (action) {
2391         case CPU_UP_PREPARE:
2392         case CPU_UP_PREPARE_FROZEN:
2393                 if (process_zones(cpu))
2394                         ret = NOTIFY_BAD;
2395                 break;
2396         case CPU_UP_CANCELED:
2397         case CPU_UP_CANCELED_FROZEN:
2398         case CPU_DEAD:
2399         case CPU_DEAD_FROZEN:
2400                 free_zone_pagesets(cpu);
2401                 break;
2402         default:
2403                 break;
2404         }
2405         return ret;
2406 }
2407
2408 static struct notifier_block __cpuinitdata pageset_notifier =
2409         { &pageset_cpuup_callback, NULL, 0 };
2410
2411 void __init setup_per_cpu_pageset(void)
2412 {
2413         int err;
2414
2415         /* Initialize per_cpu_pageset for cpu 0.
2416          * A cpuup callback will do this for every cpu
2417          * as it comes online
2418          */
2419         err = process_zones(smp_processor_id());
2420         BUG_ON(err);
2421         register_cpu_notifier(&pageset_notifier);
2422 }
2423
2424 #endif
2425
2426 static noinline __init_refok
2427 int zone_wait_table_init(struct zone *zone, unsigned long zone_size_pages)
2428 {
2429         int i;
2430         struct pglist_data *pgdat = zone->zone_pgdat;
2431         size_t alloc_size;
2432
2433         /*
2434          * The per-page waitqueue mechanism uses hashed waitqueues
2435          * per zone.
2436          */
2437         zone->wait_table_hash_nr_entries =
2438                  wait_table_hash_nr_entries(zone_size_pages);
2439         zone->wait_table_bits =
2440                 wait_table_bits(zone->wait_table_hash_nr_entries);
2441         alloc_size = zone->wait_table_hash_nr_entries
2442                                         * sizeof(wait_queue_head_t);
2443
2444         if (system_state == SYSTEM_BOOTING) {
2445                 zone->wait_table = (wait_queue_head_t *)
2446                         alloc_bootmem_node(pgdat, alloc_size);
2447         } else {
2448                 /*
2449                  * This case means that a zone whose size was 0 gets new memory
2450                  * via memory hot-add.
2451                  * But it may be the case that a new node was hot-added.  In
2452                  * this case vmalloc() will not be able to use this new node's
2453                  * memory - this wait_table must be initialized to use this new
2454                  * node itself as well.
2455                  * To use this new node's memory, further consideration will be
2456                  * necessary.
2457                  */
2458                 zone->wait_table = (wait_queue_head_t *)vmalloc(alloc_size);
2459         }
2460         if (!zone->wait_table)
2461                 return -ENOMEM;
2462
2463         for(i = 0; i < zone->wait_table_hash_nr_entries; ++i)
2464                 init_waitqueue_head(zone->wait_table + i);
2465
2466         return 0;
2467 }
2468
2469 static __meminit void zone_pcp_init(struct zone *zone)
2470 {
2471         int cpu;
2472         unsigned long batch = zone_batchsize(zone);
2473
2474         for (cpu = 0; cpu < NR_CPUS; cpu++) {
2475 #ifdef CONFIG_NUMA
2476                 /* Early boot. Slab allocator not functional yet */
2477                 zone_pcp(zone, cpu) = &boot_pageset[cpu];
2478                 setup_pageset(&boot_pageset[cpu],0);
2479 #else
2480                 setup_pageset(zone_pcp(zone,cpu), batch);
2481 #endif
2482         }
2483         if (zone->present_pages)
2484                 printk(KERN_DEBUG "  %s zone: %lu pages, LIFO batch:%lu\n",
2485                         zone->name, zone->present_pages, batch);
2486 }
2487
2488 __meminit int init_currently_empty_zone(struct zone *zone,
2489                                         unsigned long zone_start_pfn,
2490                                         unsigned long size,
2491                                         enum memmap_context context)
2492 {
2493         struct pglist_data *pgdat = zone->zone_pgdat;
2494         int ret;
2495         ret = zone_wait_table_init(zone, size);
2496         if (ret)
2497                 return ret;
2498         pgdat->nr_zones = zone_idx(zone) + 1;
2499
2500         zone->zone_start_pfn = zone_start_pfn;
2501
2502         memmap_init(size, pgdat->node_id, zone_idx(zone), zone_start_pfn);
2503
2504         zone_init_free_lists(pgdat, zone, zone->spanned_pages);
2505
2506         return 0;
2507 }
2508
2509 #ifdef CONFIG_ARCH_POPULATES_NODE_MAP
2510 /*
2511  * Basic iterator support. Return the first range of PFNs for a node
2512  * Note: nid == MAX_NUMNODES returns first region regardless of node
2513  */
2514 static int __meminit first_active_region_index_in_nid(int nid)
2515 {
2516         int i;
2517
2518         for (i = 0; i < nr_nodemap_entries; i++)
2519                 if (nid == MAX_NUMNODES || early_node_map[i].nid == nid)
2520                         return i;
2521
2522         return -1;
2523 }
2524
2525 /*
2526  * Basic iterator support. Return the next active range of PFNs for a node
2527  * Note: nid == MAX_NUMNODES returns next region regardles of node
2528  */
2529 static int __meminit next_active_region_index_in_nid(int index, int nid)
2530 {
2531         for (index = index + 1; index < nr_nodemap_entries; index++)
2532                 if (nid == MAX_NUMNODES || early_node_map[index].nid == nid)
2533                         return index;
2534
2535         return -1;
2536 }
2537
2538 #ifndef CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID
2539 /*
2540  * Required by SPARSEMEM. Given a PFN, return what node the PFN is on.
2541  * Architectures may implement their own version but if add_active_range()
2542  * was used and there are no special requirements, this is a convenient
2543  * alternative
2544  */
2545 int __meminit early_pfn_to_nid(unsigned long pfn)
2546 {
2547         int i;
2548
2549         for (i = 0; i < nr_nodemap_entries; i++) {
2550                 unsigned long start_pfn = early_node_map[i].start_pfn;
2551                 unsigned long end_pfn = early_node_map[i].end_pfn;
2552
2553                 if (start_pfn <= pfn && pfn < end_pfn)
2554                         return early_node_map[i].nid;
2555         }
2556
2557         return 0;
2558 }
2559 #endif /* CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID */
2560
2561 /* Basic iterator support to walk early_node_map[] */
2562 #define for_each_active_range_index_in_nid(i, nid) \
2563         for (i = first_active_region_index_in_nid(nid); i != -1; \
2564                                 i = next_active_region_index_in_nid(i, nid))
2565
2566 /**
2567  * free_bootmem_with_active_regions - Call free_bootmem_node for each active range
2568  * @nid: The node to free memory on. If MAX_NUMNODES, all nodes are freed.
2569  * @max_low_pfn: The highest PFN that will be passed to free_bootmem_node
2570  *
2571  * If an architecture guarantees that all ranges registered with
2572  * add_active_ranges() contain no holes and may be freed, this
2573  * this function may be used instead of calling free_bootmem() manually.
2574  */
2575 void __init free_bootmem_with_active_regions(int nid,
2576                                                 unsigned long max_low_pfn)
2577 {
2578         int i;
2579
2580         for_each_active_range_index_in_nid(i, nid) {
2581                 unsigned long size_pages = 0;
2582                 unsigned long end_pfn = early_node_map[i].end_pfn;
2583
2584                 if (early_node_map[i].start_pfn >= max_low_pfn)
2585                         continue;
2586
2587                 if (end_pfn > max_low_pfn)
2588                         end_pfn = max_low_pfn;
2589
2590                 size_pages = end_pfn - early_node_map[i].start_pfn;
2591                 free_bootmem_node(NODE_DATA(early_node_map[i].nid),
2592                                 PFN_PHYS(early_node_map[i].start_pfn),
2593                                 size_pages << PAGE_SHIFT);
2594         }
2595 }
2596
2597 /**
2598  * sparse_memory_present_with_active_regions - Call memory_present for each active range
2599  * @nid: The node to call memory_present for. If MAX_NUMNODES, all nodes will be used.
2600  *
2601  * If an architecture guarantees that all ranges registered with
2602  * add_active_ranges() contain no holes and may be freed, this
2603  * function may be used instead of calling memory_present() manually.
2604  */
2605 void __init sparse_memory_present_with_active_regions(int nid)
2606 {
2607         int i;
2608
2609         for_each_active_range_index_in_nid(i, nid)
2610                 memory_present(early_node_map[i].nid,
2611                                 early_node_map[i].start_pfn,
2612                                 early_node_map[i].end_pfn);
2613 }
2614
2615 /**
2616  * push_node_boundaries - Push node boundaries to at least the requested boundary
2617  * @nid: The nid of the node to push the boundary for
2618  * @start_pfn: The start pfn of the node
2619  * @end_pfn: The end pfn of the node
2620  *
2621  * In reserve-based hot-add, mem_map is allocated that is unused until hotadd
2622  * time. Specifically, on x86_64, SRAT will report ranges that can potentially
2623  * be hotplugged even though no physical memory exists. This function allows
2624  * an arch to push out the node boundaries so mem_map is allocated that can
2625  * be used later.
2626  */
2627 #ifdef CONFIG_MEMORY_HOTPLUG_RESERVE
2628 void __init push_node_boundaries(unsigned int nid,
2629                 unsigned long start_pfn, unsigned long end_pfn)
2630 {
2631         printk(KERN_DEBUG "Entering push_node_boundaries(%u, %lu, %lu)\n",
2632                         nid, start_pfn, end_pfn);
2633
2634         /* Initialise the boundary for this node if necessary */
2635         if (node_boundary_end_pfn[nid] == 0)
2636                 node_boundary_start_pfn[nid] = -1UL;
2637
2638         /* Update the boundaries */
2639         if (node_boundary_start_pfn[nid] > start_pfn)
2640                 node_boundary_start_pfn[nid] = start_pfn;
2641         if (node_boundary_end_pfn[nid] < end_pfn)
2642                 node_boundary_end_pfn[nid] = end_pfn;
2643 }
2644
2645 /* If necessary, push the node boundary out for reserve hotadd */
2646 static void __meminit account_node_boundary(unsigned int nid,
2647                 unsigned long *start_pfn, unsigned long *end_pfn)
2648 {
2649         printk(KERN_DEBUG "Entering account_node_boundary(%u, %lu, %lu)\n",
2650                         nid, *start_pfn, *end_pfn);
2651
2652         /* Return if boundary information has not been provided */
2653         if (node_boundary_end_pfn[nid] == 0)
2654                 return;
2655
2656         /* Check the boundaries and update if necessary */
2657         if (node_boundary_start_pfn[nid] < *start_pfn)
2658                 *start_pfn = node_boundary_start_pfn[nid];
2659         if (node_boundary_end_pfn[nid] > *end_pfn)
2660                 *end_pfn = node_boundary_end_pfn[nid];
2661 }
2662 #else
2663 void __init push_node_boundaries(unsigned int nid,
2664                 unsigned long start_pfn, unsigned long end_pfn) {}
2665
2666 static void __meminit account_node_boundary(unsigned int nid,
2667                 unsigned long *start_pfn, unsigned long *end_pfn) {}
2668 #endif
2669
2670
2671 /**
2672  * get_pfn_range_for_nid - Return the start and end page frames for a node
2673  * @nid: The nid to return the range for. If MAX_NUMNODES, the min and max PFN are returned.
2674  * @start_pfn: Passed by reference. On return, it will have the node start_pfn.
2675  * @end_pfn: Passed by reference. On return, it will have the node end_pfn.
2676  *
2677  * It returns the start and end page frame of a node based on information
2678  * provided by an arch calling add_active_range(). If called for a node
2679  * with no available memory, a warning is printed and the start and end
2680  * PFNs will be 0.
2681  */
2682 void __meminit get_pfn_range_for_nid(unsigned int nid,
2683                         unsigned long *start_pfn, unsigned long *end_pfn)
2684 {
2685         int i;
2686         *start_pfn = -1UL;
2687         *end_pfn = 0;
2688
2689         for_each_active_range_index_in_nid(i, nid) {
2690                 *start_pfn = min(*start_pfn, early_node_map[i].start_pfn);
2691                 *end_pfn = max(*end_pfn, early_node_map[i].end_pfn);
2692         }
2693
2694         if (*start_pfn == -1UL) {
2695                 printk(KERN_WARNING "Node %u active with no memory\n", nid);
2696                 *start_pfn = 0;
2697         }
2698
2699         /* Push the node boundaries out if requested */
2700         account_node_boundary(nid, start_pfn, end_pfn);
2701 }
2702
2703 /*
2704  * This finds a zone that can be used for ZONE_MOVABLE pages. The
2705  * assumption is made that zones within a node are ordered in monotonic
2706  * increasing memory addresses so that the "highest" populated zone is used
2707  */
2708 void __init find_usable_zone_for_movable(void)
2709 {
2710         int zone_index;
2711         for (zone_index = MAX_NR_ZONES - 1; zone_index >= 0; zone_index--) {
2712                 if (zone_index == ZONE_MOVABLE)
2713                         continue;
2714
2715                 if (arch_zone_highest_possible_pfn[zone_index] >
2716                                 arch_zone_lowest_possible_pfn[zone_index])
2717                         break;
2718         }
2719
2720         VM_BUG_ON(zone_index == -1);
2721         movable_zone = zone_index;
2722 }
2723
2724 /*
2725  * The zone ranges provided by the architecture do not include ZONE_MOVABLE
2726  * because it is sized independant of architecture. Unlike the other zones,
2727  * the starting point for ZONE_MOVABLE is not fixed. It may be different
2728  * in each node depending on the size of each node and how evenly kernelcore
2729  * is distributed. This helper function adjusts the zone ranges
2730  * provided by the architecture for a given node by using the end of the
2731  * highest usable zone for ZONE_MOVABLE. This preserves the assumption that
2732  * zones within a node are in order of monotonic increases memory addresses
2733  */
2734 void __meminit adjust_zone_range_for_zone_movable(int nid,
2735                                         unsigned long zone_type,
2736                                         unsigned long node_start_pfn,
2737                                         unsigned long node_end_pfn,
2738                                         unsigned long *zone_start_pfn,
2739                                         unsigned long *zone_end_pfn)
2740 {
2741         /* Only adjust if ZONE_MOVABLE is on this node */
2742         if (zone_movable_pfn[nid]) {
2743                 /* Size ZONE_MOVABLE */
2744                 if (zone_type == ZONE_MOVABLE) {
2745                         *zone_start_pfn = zone_movable_pfn[nid];
2746                         *zone_end_pfn = min(node_end_pfn,
2747                                 arch_zone_highest_possible_pfn[movable_zone]);
2748
2749                 /* Adjust for ZONE_MOVABLE starting within this range */
2750                 } else if (*zone_start_pfn < zone_movable_pfn[nid] &&
2751                                 *zone_end_pfn > zone_movable_pfn[nid]) {
2752                         *zone_end_pfn = zone_movable_pfn[nid];
2753
2754                 /* Check if this whole range is within ZONE_MOVABLE */
2755                 } else if (*zone_start_pfn >= zone_movable_pfn[nid])
2756                         *zone_start_pfn = *zone_end_pfn;
2757         }
2758 }
2759
2760 /*
2761  * Return the number of pages a zone spans in a node, including holes
2762  * present_pages = zone_spanned_pages_in_node() - zone_absent_pages_in_node()
2763  */
2764 static unsigned long __meminit zone_spanned_pages_in_node(int nid,
2765                                         unsigned long zone_type,
2766                                         unsigned long *ignored)
2767 {
2768         unsigned long node_start_pfn, node_end_pfn;
2769         unsigned long zone_start_pfn, zone_end_pfn;
2770
2771         /* Get the start and end of the node and zone */
2772         get_pfn_range_for_nid(nid, &node_start_pfn, &node_end_pfn);
2773         zone_start_pfn = arch_zone_lowest_possible_pfn[zone_type];
2774         zone_end_pfn = arch_zone_highest_possible_pfn[zone_type];
2775         adjust_zone_range_for_zone_movable(nid, zone_type,
2776                                 node_start_pfn, node_end_pfn,
2777                                 &zone_start_pfn, &zone_end_pfn);
2778
2779         /* Check that this node has pages within the zone's required range */
2780         if (zone_end_pfn < node_start_pfn || zone_start_pfn > node_end_pfn)
2781                 return 0;
2782
2783         /* Move the zone boundaries inside the node if necessary */
2784         zone_end_pfn = min(zone_end_pfn, node_end_pfn);
2785         zone_start_pfn = max(zone_start_pfn, node_start_pfn);
2786
2787         /* Return the spanned pages */
2788         return zone_end_pfn - zone_start_pfn;
2789 }
2790
2791 /*
2792  * Return the number of holes in a range on a node. If nid is MAX_NUMNODES,
2793  * then all holes in the requested range will be accounted for.
2794  */
2795 unsigned long __meminit __absent_pages_in_range(int nid,
2796                                 unsigned long range_start_pfn,
2797                                 unsigned long range_end_pfn)
2798 {
2799         int i = 0;
2800         unsigned long prev_end_pfn = 0, hole_pages = 0;
2801         unsigned long start_pfn;
2802
2803         /* Find the end_pfn of the first active range of pfns in the node */
2804         i = first_active_region_index_in_nid(nid);
2805         if (i == -1)
2806                 return 0;
2807
2808         prev_end_pfn = min(early_node_map[i].start_pfn, range_end_pfn);
2809
2810         /* Account for ranges before physical memory on this node */
2811         if (early_node_map[i].start_pfn > range_start_pfn)
2812                 hole_pages = prev_end_pfn - range_start_pfn;
2813
2814         /* Find all holes for the zone within the node */
2815         for (; i != -1; i = next_active_region_index_in_nid(i, nid)) {
2816
2817                 /* No need to continue if prev_end_pfn is outside the zone */
2818                 if (prev_end_pfn >= range_end_pfn)
2819                         break;
2820
2821                 /* Make sure the end of the zone is not within the hole */
2822                 start_pfn = min(early_node_map[i].start_pfn, range_end_pfn);
2823                 prev_end_pfn = max(prev_end_pfn, range_start_pfn);
2824
2825                 /* Update the hole size cound and move on */
2826                 if (start_pfn > range_start_pfn) {
2827                         BUG_ON(prev_end_pfn > start_pfn);
2828                         hole_pages += start_pfn - prev_end_pfn;
2829                 }
2830                 prev_end_pfn = early_node_map[i].end_pfn;
2831         }
2832
2833         /* Account for ranges past physical memory on this node */
2834         if (range_end_pfn > prev_end_pfn)
2835                 hole_pages += range_end_pfn -
2836                                 max(range_start_pfn, prev_end_pfn);
2837
2838         return hole_pages;
2839 }
2840
2841 /**
2842  * absent_pages_in_range - Return number of page frames in holes within a range
2843  * @start_pfn: The start PFN to start searching for holes
2844  * @end_pfn: The end PFN to stop searching for holes
2845  *
2846  * It returns the number of pages frames in memory holes within a range.
2847  */
2848 unsigned long __init absent_pages_in_range(unsigned long start_pfn,
2849                                                         unsigned long end_pfn)
2850 {
2851         return __absent_pages_in_range(MAX_NUMNODES, start_pfn, end_pfn);
2852 }
2853
2854 /* Return the number of page frames in holes in a zone on a node */
2855 static unsigned long __meminit zone_absent_pages_in_node(int nid,
2856                                         unsigned long zone_type,
2857                                         unsigned long *ignored)
2858 {
2859         unsigned long node_start_pfn, node_end_pfn;
2860         unsigned long zone_start_pfn, zone_end_pfn;
2861
2862         get_pfn_range_for_nid(nid, &node_start_pfn, &node_end_pfn);
2863         zone_start_pfn = max(arch_zone_lowest_possible_pfn[zone_type],
2864                                                         node_start_pfn);
2865         zone_end_pfn = min(arch_zone_highest_possible_pfn[zone_type],
2866                                                         node_end_pfn);
2867
2868         adjust_zone_range_for_zone_movable(nid, zone_type,
2869                         node_start_pfn, node_end_pfn,
2870                         &zone_start_pfn, &zone_end_pfn);
2871         return __absent_pages_in_range(nid, zone_start_pfn, zone_end_pfn);
2872 }
2873
2874 #else
2875 static inline unsigned long __meminit zone_spanned_pages_in_node(int nid,
2876                                         unsigned long zone_type,
2877                                         unsigned long *zones_size)
2878 {
2879         return zones_size[zone_type];
2880 }
2881
2882 static inline unsigned long __meminit zone_absent_pages_in_node(int nid,
2883                                                 unsigned long zone_type,
2884                                                 unsigned long *zholes_size)
2885 {
2886         if (!zholes_size)
2887                 return 0;
2888
2889         return zholes_size[zone_type];
2890 }
2891
2892 #endif
2893
2894 static void __meminit calculate_node_totalpages(struct pglist_data *pgdat,
2895                 unsigned long *zones_size, unsigned long *zholes_size)
2896 {
2897         unsigned long realtotalpages, totalpages = 0;
2898         enum zone_type i;
2899
2900         for (i = 0; i < MAX_NR_ZONES; i++)
2901                 totalpages += zone_spanned_pages_in_node(pgdat->node_id, i,
2902                                                                 zones_size);
2903         pgdat->node_spanned_pages = totalpages;
2904
2905         realtotalpages = totalpages;
2906         for (i = 0; i < MAX_NR_ZONES; i++)
2907                 realtotalpages -=
2908                         zone_absent_pages_in_node(pgdat->node_id, i,
2909                                                                 zholes_size);
2910         pgdat->node_present_pages = realtotalpages;
2911         printk(KERN_DEBUG "On node %d totalpages: %lu\n", pgdat->node_id,
2912                                                         realtotalpages);
2913 }
2914
2915 /*
2916  * Set up the zone data structures:
2917  *   - mark all pages reserved
2918  *   - mark all memory queues empty
2919  *   - clear the memory bitmaps
2920  */
2921 static void __meminit free_area_init_core(struct pglist_data *pgdat,
2922                 unsigned long *zones_size, unsigned long *zholes_size)
2923 {
2924         enum zone_type j;
2925         int nid = pgdat->node_id;
2926         unsigned long zone_start_pfn = pgdat->node_start_pfn;
2927         int ret;
2928
2929         pgdat_resize_init(pgdat);
2930         pgdat->nr_zones = 0;
2931         init_waitqueue_head(&pgdat->kswapd_wait);
2932         pgdat->kswapd_max_order = 0;
2933        
2934         for (j = 0; j < MAX_NR_ZONES; j++) {
2935                 struct zone *zone = pgdat->node_zones + j;
2936                 unsigned long size, realsize, memmap_pages;
2937
2938                 size = zone_spanned_pages_in_node(nid, j, zones_size);
2939                 realsize = size - zone_absent_pages_in_node(nid, j,
2940                                                                 zholes_size);
2941
2942                 /*
2943                  * Adjust realsize so that it accounts for how much memory
2944                  * is used by this zone for memmap. This affects the watermark
2945                  * and per-cpu initialisations
2946                  */
2947                 memmap_pages = (size * sizeof(struct page)) >> PAGE_SHIFT;
2948                 if (realsize >= memmap_pages) {
2949                         realsize -= memmap_pages;
2950                         printk(KERN_DEBUG
2951                                 "  %s zone: %lu pages used for memmap\n",
2952                                 zone_names[j], memmap_pages);
2953                 } else
2954                         printk(KERN_WARNING
2955                                 "  %s zone: %lu pages exceeds realsize %lu\n",
2956                                 zone_names[j], memmap_pages, realsize);
2957
2958                 /* Account for reserved pages */
2959                 if (j == 0 && realsize > dma_reserve) {
2960                         realsize -= dma_reserve;
2961                         printk(KERN_DEBUG "  %s zone: %lu pages reserved\n",
2962                                         zone_names[0], dma_reserve);
2963                 }
2964
2965                 if (!is_highmem_idx(j))
2966                         nr_kernel_pages += realsize;
2967                 nr_all_pages += realsize;
2968
2969                 zone->spanned_pages = size;
2970                 zone->present_pages = realsize;
2971 #ifdef CONFIG_NUMA
2972                 zone->node = nid;
2973                 zone->min_unmapped_pages = (realsize*sysctl_min_unmapped_ratio)
2974                                                 / 100;
2975                 zone->min_slab_pages = (realsize * sysctl_min_slab_ratio) / 100;
2976 #endif
2977                 zone->name = zone_names[j];
2978                 spin_lock_init(&zone->lock);
2979                 spin_lock_init(&zone->lru_lock);
2980                 zone_seqlock_init(zone);
2981                 zone->zone_pgdat = pgdat;
2982
2983                 zone->prev_priority = DEF_PRIORITY;
2984
2985                 zone_pcp_init(zone);
2986                 INIT_LIST_HEAD(&zone->active_list);
2987                 INIT_LIST_HEAD(&zone->inactive_list);
2988                 zone->nr_scan_active = 0;
2989                 zone->nr_scan_inactive = 0;
2990                 zap_zone_vm_stats(zone);
2991                 atomic_set(&zone->reclaim_in_progress, 0);
2992                 if (!size)
2993                         continue;
2994
2995                 ret = init_currently_empty_zone(zone, zone_start_pfn,
2996                                                 size, MEMMAP_EARLY);
2997                 BUG_ON(ret);
2998                 zone_start_pfn += size;
2999         }
3000 }
3001
3002 static void __init_refok alloc_node_mem_map(struct pglist_data *pgdat)
3003 {
3004         /* Skip empty nodes */
3005         if (!pgdat->node_spanned_pages)
3006                 return;
3007
3008 #ifdef CONFIG_FLAT_NODE_MEM_MAP
3009         /* ia64 gets its own node_mem_map, before this, without bootmem */
3010         if (!pgdat->node_mem_map) {
3011                 unsigned long size, start, end;
3012                 struct page *map;
3013
3014                 /*
3015                  * The zone's endpoints aren't required to be MAX_ORDER
3016                  * aligned but the node_mem_map endpoints must be in order
3017                  * for the buddy allocator to function correctly.
3018                  */
3019                 start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1);
3020                 end = pgdat->node_start_pfn + pgdat->node_spanned_pages;
3021                 end = ALIGN(end, MAX_ORDER_NR_PAGES);
3022                 size =  (end - start) * sizeof(struct page);
3023                 map = alloc_remap(pgdat->node_id, size);
3024                 if (!map)
3025                         map = alloc_bootmem_node(pgdat, size);
3026                 pgdat->node_mem_map = map + (pgdat->node_start_pfn - start);
3027         }
3028 #ifndef CONFIG_NEED_MULTIPLE_NODES
3029         /*
3030          * With no DISCONTIG, the global mem_map is just set as node 0's
3031          */
3032         if (pgdat == NODE_DATA(0)) {
3033                 mem_map = NODE_DATA(0)->node_mem_map;
3034 #ifdef CONFIG_ARCH_POPULATES_NODE_MAP
3035                 if (page_to_pfn(mem_map) != pgdat->node_start_pfn)
3036                         mem_map -= pgdat->node_start_pfn;
3037 #endif /* CONFIG_ARCH_POPULATES_NODE_MAP */
3038         }
3039 #endif
3040 #endif /* CONFIG_FLAT_NODE_MEM_MAP */
3041 }
3042
3043 void __meminit free_area_init_node(int nid, struct pglist_data *pgdat,
3044                 unsigned long *zones_size, unsigned long node_start_pfn,
3045                 unsigned long *zholes_size)
3046 {
3047         pgdat->node_id = nid;
3048         pgdat->node_start_pfn = node_start_pfn;
3049         calculate_node_totalpages(pgdat, zones_size, zholes_size);
3050
3051         alloc_node_mem_map(pgdat);
3052
3053         free_area_init_core(pgdat, zones_size, zholes_size);
3054 }
3055
3056 #ifdef CONFIG_ARCH_POPULATES_NODE_MAP
3057
3058 #if MAX_NUMNODES > 1
3059 /*
3060  * Figure out the number of possible node ids.
3061  */
3062 static void __init setup_nr_node_ids(void)
3063 {
3064         unsigned int node;
3065         unsigned int highest = 0;
3066
3067         for_each_node_mask(node, node_possible_map)
3068                 highest = node;
3069         nr_node_ids = highest + 1;
3070 }
3071 #else
3072 static inline void setup_nr_node_ids(void)
3073 {
3074 }
3075 #endif
3076
3077 /**
3078  * add_active_range - Register a range of PFNs backed by physical memory
3079  * @nid: The node ID the range resides on
3080  * @start_pfn: The start PFN of the available physical memory
3081  * @end_pfn: The end PFN of the available physical memory
3082  *
3083  * These ranges are stored in an early_node_map[] and later used by
3084  * free_area_init_nodes() to calculate zone sizes and holes. If the
3085  * range spans a memory hole, it is up to the architecture to ensure
3086  * the memory is not freed by the bootmem allocator. If possible
3087  * the range being registered will be merged with existing ranges.
3088  */
3089 void __init add_active_range(unsigned int nid, unsigned long start_pfn,
3090                                                 unsigned long end_pfn)
3091 {
3092         int i;
3093
3094         printk(KERN_DEBUG "Entering add_active_range(%d, %lu, %lu) "
3095                           "%d entries of %d used\n",
3096                           nid, start_pfn, end_pfn,
3097                           nr_nodemap_entries, MAX_ACTIVE_REGIONS);
3098
3099         /* Merge with existing active regions if possible */
3100         for (i = 0; i < nr_nodemap_entries; i++) {
3101                 if (early_node_map[i].nid != nid)
3102                         continue;
3103
3104                 /* Skip if an existing region covers this new one */
3105                 if (start_pfn >= early_node_map[i].start_pfn &&
3106                                 end_pfn <= early_node_map[i].end_pfn)
3107                         return;
3108
3109                 /* Merge forward if suitable */
3110                 if (start_pfn <= early_node_map[i].end_pfn &&
3111                                 end_pfn > early_node_map[i].end_pfn) {
3112                         early_node_map[i].end_pfn = end_pfn;
3113                         return;
3114                 }
3115
3116                 /* Merge backward if suitable */
3117                 if (start_pfn < early_node_map[i].end_pfn &&
3118                                 end_pfn >= early_node_map[i].start_pfn) {
3119                         early_node_map[i].start_pfn = start_pfn;
3120                         return;
3121                 }
3122         }
3123
3124         /* Check that early_node_map is large enough */
3125         if (i >= MAX_ACTIVE_REGIONS) {
3126                 printk(KERN_CRIT "More than %d memory regions, truncating\n",
3127                                                         MAX_ACTIVE_REGIONS);
3128                 return;
3129         }
3130
3131         early_node_map[i].nid = nid;
3132         early_node_map[i].start_pfn = start_pfn;
3133         early_node_map[i].end_pfn = end_pfn;
3134         nr_nodemap_entries = i + 1;
3135 }
3136
3137 /**
3138  * shrink_active_range - Shrink an existing registered range of PFNs
3139  * @nid: The node id the range is on that should be shrunk
3140  * @old_end_pfn: The old end PFN of the range
3141  * @new_end_pfn: The new PFN of the range
3142  *
3143  * i386 with NUMA use alloc_remap() to store a node_mem_map on a local node.
3144  * The map is kept at the end physical page range that has already been
3145  * registered with add_active_range(). This function allows an arch to shrink
3146  * an existing registered range.
3147  */
3148 void __init shrink_active_range(unsigned int nid, unsigned long old_end_pfn,
3149                                                 unsigned long new_end_pfn)
3150 {
3151         int i;
3152
3153         /* Find the old active region end and shrink */
3154         for_each_active_range_index_in_nid(i, nid)
3155                 if (early_node_map[i].end_pfn == old_end_pfn) {
3156                         early_node_map[i].end_pfn = new_end_pfn;
3157                         break;
3158                 }
3159 }
3160
3161 /**
3162  * remove_all_active_ranges - Remove all currently registered regions
3163  *
3164  * During discovery, it may be found that a table like SRAT is invalid
3165  * and an alternative discovery method must be used. This function removes
3166  * all currently registered regions.
3167  */
3168 void __init remove_all_active_ranges(void)
3169 {
3170         memset(early_node_map, 0, sizeof(early_node_map));
3171         nr_nodemap_entries = 0;
3172 #ifdef CONFIG_MEMORY_HOTPLUG_RESERVE
3173         memset(node_boundary_start_pfn, 0, sizeof(node_boundary_start_pfn));
3174         memset(node_boundary_end_pfn, 0, sizeof(node_boundary_end_pfn));
3175 #endif /* CONFIG_MEMORY_HOTPLUG_RESERVE */
3176 }
3177
3178 /* Compare two active node_active_regions */
3179 static int __init cmp_node_active_region(const void *a, const void *b)
3180 {
3181         struct node_active_region *arange = (struct node_active_region *)a;
3182         struct node_active_region *brange = (struct node_active_region *)b;
3183
3184         /* Done this way to avoid overflows */
3185         if (arange->start_pfn > brange->start_pfn)
3186                 return 1;
3187         if (arange->start_pfn < brange->start_pfn)
3188                 return -1;
3189
3190         return 0;
3191 }
3192
3193 /* sort the node_map by start_pfn */
3194 static void __init sort_node_map(void)
3195 {
3196         sort(early_node_map, (size_t)nr_nodemap_entries,
3197                         sizeof(struct node_active_region),
3198                         cmp_node_active_region, NULL);
3199 }
3200
3201 /* Find the lowest pfn for a node */
3202 unsigned long __init find_min_pfn_for_node(unsigned long nid)
3203 {
3204         int i;
3205         unsigned long min_pfn = ULONG_MAX;
3206
3207         /* Assuming a sorted map, the first range found has the starting pfn */
3208         for_each_active_range_index_in_nid(i, nid)
3209                 min_pfn = min(min_pfn, early_node_map[i].start_pfn);
3210
3211         if (min_pfn == ULONG_MAX) {
3212                 printk(KERN_WARNING
3213                         "Could not find start_pfn for node %lu\n", nid);
3214                 return 0;
3215         }
3216
3217         return min_pfn;
3218 }
3219
3220 /**
3221  * find_min_pfn_with_active_regions - Find the minimum PFN registered
3222  *
3223  * It returns the minimum PFN based on information provided via
3224  * add_active_range().
3225  */
3226 unsigned long __init find_min_pfn_with_active_regions(void)
3227 {
3228         return find_min_pfn_for_node(MAX_NUMNODES);
3229 }
3230
3231 /**
3232  * find_max_pfn_with_active_regions - Find the maximum PFN registered
3233  *
3234  * It returns the maximum PFN based on information provided via
3235  * add_active_range().
3236  */
3237 unsigned long __init find_max_pfn_with_active_regions(void)
3238 {
3239         int i;
3240         unsigned long max_pfn = 0;
3241
3242         for (i = 0; i < nr_nodemap_entries; i++)
3243                 max_pfn = max(max_pfn, early_node_map[i].end_pfn);
3244
3245         return max_pfn;
3246 }
3247
3248 unsigned long __init early_calculate_totalpages(void)
3249 {
3250         int i;
3251         unsigned long totalpages = 0;
3252
3253         for (i = 0; i < nr_nodemap_entries; i++)
3254                 totalpages += early_node_map[i].end_pfn -
3255                                                 early_node_map[i].start_pfn;
3256
3257         return totalpages;
3258 }
3259
3260 /*
3261  * Find the PFN the Movable zone begins in each node. Kernel memory
3262  * is spread evenly between nodes as long as the nodes have enough
3263  * memory. When they don't, some nodes will have more kernelcore than
3264  * others
3265  */
3266 void __init find_zone_movable_pfns_for_nodes(unsigned long *movable_pfn)
3267 {
3268         int i, nid;
3269         unsigned long usable_startpfn;
3270         unsigned long kernelcore_node, kernelcore_remaining;
3271         int usable_nodes = num_online_nodes();
3272
3273         /*
3274          * If movablecore was specified, calculate what size of
3275          * kernelcore that corresponds so that memory usable for
3276          * any allocation type is evenly spread. If both kernelcore
3277          * and movablecore are specified, then the value of kernelcore
3278          * will be used for required_kernelcore if it's greater than
3279          * what movablecore would have allowed.
3280          */
3281         if (required_movablecore) {
3282                 unsigned long totalpages = early_calculate_totalpages();
3283                 unsigned long corepages;
3284
3285                 /*
3286                  * Round-up so that ZONE_MOVABLE is at least as large as what
3287                  * was requested by the user
3288                  */
3289                 required_movablecore =
3290                         roundup(required_movablecore, MAX_ORDER_NR_PAGES);
3291                 corepages = totalpages - required_movablecore;
3292
3293                 required_kernelcore = max(required_kernelcore, corepages);
3294         }
3295
3296         /* If kernelcore was not specified, there is no ZONE_MOVABLE */
3297         if (!required_kernelcore)
3298                 return;
3299
3300         /* usable_startpfn is the lowest possible pfn ZONE_MOVABLE can be at */
3301         find_usable_zone_for_movable();
3302         usable_startpfn = arch_zone_lowest_possible_pfn[movable_zone];
3303
3304 restart:
3305         /* Spread kernelcore memory as evenly as possible throughout nodes */
3306         kernelcore_node = required_kernelcore / usable_nodes;
3307         for_each_online_node(nid) {
3308                 /*
3309                  * Recalculate kernelcore_node if the division per node
3310                  * now exceeds what is necessary to satisfy the requested
3311                  * amount of memory for the kernel
3312                  */
3313                 if (required_kernelcore < kernelcore_node)
3314                         kernelcore_node = required_kernelcore / usable_nodes;
3315
3316                 /*
3317                  * As the map is walked, we track how much memory is usable
3318                  * by the kernel using kernelcore_remaining. When it is
3319                  * 0, the rest of the node is usable by ZONE_MOVABLE
3320                  */
3321                 kernelcore_remaining = kernelcore_node;
3322
3323                 /* Go through each range of PFNs within this node */
3324                 for_each_active_range_index_in_nid(i, nid) {
3325                         unsigned long start_pfn, end_pfn;
3326                         unsigned long size_pages;
3327
3328                         start_pfn = max(early_node_map[i].start_pfn,
3329                                                 zone_movable_pfn[nid]);
3330                         end_pfn = early_node_map[i].end_pfn;
3331                         if (start_pfn >= end_pfn)
3332                                 continue;
3333
3334                         /* Account for what is only usable for kernelcore */
3335                         if (start_pfn < usable_startpfn) {
3336                                 unsigned long kernel_pages;
3337                                 kernel_pages = min(end_pfn, usable_startpfn)
3338                                                                 - start_pfn;
3339
3340                                 kernelcore_remaining -= min(kernel_pages,
3341                                                         kernelcore_remaining);
3342                                 required_kernelcore -= min(kernel_pages,
3343                                                         required_kernelcore);
3344
3345                                 /* Continue if range is now fully accounted */
3346                                 if (end_pfn <= usable_startpfn) {
3347
3348                                         /*
3349                                          * Push zone_movable_pfn to the end so
3350                                          * that if we have to rebalance
3351                                          * kernelcore across nodes, we will
3352                                          * not double account here
3353                                          */
3354                                         zone_movable_pfn[nid] = end_pfn;
3355                                         continue;
3356                                 }
3357                                 start_pfn = usable_startpfn;
3358                         }
3359
3360                         /*
3361                          * The usable PFN range for ZONE_MOVABLE is from
3362                          * start_pfn->end_pfn. Calculate size_pages as the
3363                          * number of pages used as kernelcore
3364                          */
3365                         size_pages = end_pfn - start_pfn;
3366                         if (size_pages > kernelcore_remaining)
3367                                 size_pages = kernelcore_remaining;
3368                         zone_movable_pfn[nid] = start_pfn + size_pages;
3369
3370                         /*
3371                          * Some kernelcore has been met, update counts and
3372                          * break if the kernelcore for this node has been
3373                          * satisified
3374                          */
3375                         required_kernelcore -= min(required_kernelcore,
3376                                                                 size_pages);
3377                         kernelcore_remaining -= size_pages;
3378                         if (!kernelcore_remaining)
3379                                 break;
3380                 }
3381         }
3382
3383         /*
3384          * If there is still required_kernelcore, we do another pass with one
3385          * less node in the count. This will push zone_movable_pfn[nid] further
3386          * along on the nodes that still have memory until kernelcore is
3387          * satisified
3388          */
3389         usable_nodes--;
3390         if (usable_nodes && required_kernelcore > usable_nodes)
3391                 goto restart;
3392
3393         /* Align start of ZONE_MOVABLE on all nids to MAX_ORDER_NR_PAGES */
3394         for (nid = 0; nid < MAX_NUMNODES; nid++)
3395                 zone_movable_pfn[nid] =
3396                         roundup(zone_movable_pfn[nid], MAX_ORDER_NR_PAGES);
3397 }
3398
3399 /**
3400  * free_area_init_nodes - Initialise all pg_data_t and zone data
3401  * @max_zone_pfn: an array of max PFNs for each zone
3402  *
3403  * This will call free_area_init_node() for each active node in the system.
3404  * Using the page ranges provided by add_active_range(), the size of each
3405  * zone in each node and their holes is calculated. If the maximum PFN
3406  * between two adjacent zones match, it is assumed that the zone is empty.
3407  * For example, if arch_max_dma_pfn == arch_max_dma32_pfn, it is assumed
3408  * that arch_max_dma32_pfn has no pages. It is also assumed that a zone
3409  * starts where the previous one ended. For example, ZONE_DMA32 starts
3410  * at arch_max_dma_pfn.
3411  */
3412 void __init free_area_init_nodes(unsigned long *max_zone_pfn)
3413 {
3414         unsigned long nid;
3415         enum zone_type i;
3416
3417         /* Sort early_node_map as initialisation assumes it is sorted */
3418         sort_node_map();
3419
3420         /* Record where the zone boundaries are */
3421         memset(arch_zone_lowest_possible_pfn, 0,
3422                                 sizeof(arch_zone_lowest_possible_pfn));
3423         memset(arch_zone_highest_possible_pfn, 0,
3424                                 sizeof(arch_zone_highest_possible_pfn));
3425         arch_zone_lowest_possible_pfn[0] = find_min_pfn_with_active_regions();
3426         arch_zone_highest_possible_pfn[0] = max_zone_pfn[0];
3427         for (i = 1; i < MAX_NR_ZONES; i++) {
3428                 if (i == ZONE_MOVABLE)
3429                         continue;
3430                 arch_zone_lowest_possible_pfn[i] =
3431                         arch_zone_highest_possible_pfn[i-1];
3432                 arch_zone_highest_possible_pfn[i] =
3433                         max(max_zone_pfn[i], arch_zone_lowest_possible_pfn[i]);
3434         }
3435         arch_zone_lowest_possible_pfn[ZONE_MOVABLE] = 0;
3436         arch_zone_highest_possible_pfn[ZONE_MOVABLE] = 0;
3437
3438         /* Find the PFNs that ZONE_MOVABLE begins at in each node */
3439         memset(zone_movable_pfn, 0, sizeof(zone_movable_pfn));
3440         find_zone_movable_pfns_for_nodes(zone_movable_pfn);
3441
3442         /* Print out the zone ranges */
3443         printk("Zone PFN ranges:\n");
3444         for (i = 0; i < MAX_NR_ZONES; i++) {
3445                 if (i == ZONE_MOVABLE)
3446                         continue;
3447                 printk("  %-8s %8lu -> %8lu\n",
3448                                 zone_names[i],
3449                                 arch_zone_lowest_possible_pfn[i],
3450                                 arch_zone_highest_possible_pfn[i]);
3451         }
3452
3453         /* Print out the PFNs ZONE_MOVABLE begins at in each node */
3454         printk("Movable zone start PFN for each node\n");
3455         for (i = 0; i < MAX_NUMNODES; i++) {
3456                 if (zone_movable_pfn[i])
3457                         printk("  Node %d: %lu\n", i, zone_movable_pfn[i]);
3458         }
3459
3460         /* Print out the early_node_map[] */
3461         printk("early_node_map[%d] active PFN ranges\n", nr_nodemap_entries);
3462         for (i = 0; i < nr_nodemap_entries; i++)
3463                 printk("  %3d: %8lu -> %8lu\n", early_node_map[i].nid,
3464                                                 early_node_map[i].start_pfn,
3465                                                 early_node_map[i].end_pfn);
3466
3467         /* Initialise every node */
3468         setup_nr_node_ids();
3469         for_each_online_node(nid) {
3470                 pg_data_t *pgdat = NODE_DATA(nid);
3471                 free_area_init_node(nid, pgdat, NULL,
3472                                 find_min_pfn_for_node(nid), NULL);
3473         }
3474 }
3475
3476 static int __init cmdline_parse_core(char *p, unsigned long *core)
3477 {
3478         unsigned long long coremem;
3479         if (!p)
3480                 return -EINVAL;
3481
3482         coremem = memparse(p, &p);
3483         *core = coremem >> PAGE_SHIFT;
3484
3485         /* Paranoid check that UL is enough for the coremem value */
3486         WARN_ON((coremem >> PAGE_SHIFT) > ULONG_MAX);
3487
3488         return 0;
3489 }
3490
3491 /*
3492  * kernelcore=size sets the amount of memory for use for allocations that
3493  * cannot be reclaimed or migrated.
3494  */
3495 static int __init cmdline_parse_kernelcore(char *p)
3496 {
3497         return cmdline_parse_core(p, &required_kernelcore);
3498 }
3499
3500 /*
3501  * movablecore=size sets the amount of memory for use for allocations that
3502  * can be reclaimed or migrated.
3503  */
3504 static int __init cmdline_parse_movablecore(char *p)
3505 {
3506         return cmdline_parse_core(p, &required_movablecore);
3507 }
3508
3509 early_param("kernelcore", cmdline_parse_kernelcore);
3510 early_param("movablecore", cmdline_parse_movablecore);
3511
3512 #endif /* CONFIG_ARCH_POPULATES_NODE_MAP */
3513
3514 /**
3515  * set_dma_reserve - set the specified number of pages reserved in the first zone
3516  * @new_dma_reserve: The number of pages to mark reserved
3517  *
3518  * The per-cpu batchsize and zone watermarks are determined by present_pages.
3519  * In the DMA zone, a significant percentage may be consumed by kernel image
3520  * and other unfreeable allocations which can skew the watermarks badly. This
3521  * function may optionally be used to account for unfreeable pages in the
3522  * first zone (e.g., ZONE_DMA). The effect will be lower watermarks and
3523  * smaller per-cpu batchsize.
3524  */
3525 void __init set_dma_reserve(unsigned long new_dma_reserve)
3526 {
3527         dma_reserve = new_dma_reserve;
3528 }
3529
3530 #ifndef CONFIG_NEED_MULTIPLE_NODES
3531 static bootmem_data_t contig_bootmem_data;
3532 struct pglist_data contig_page_data = { .bdata = &contig_bootmem_data };
3533
3534 EXPORT_SYMBOL(contig_page_data);
3535 #endif
3536
3537 void __init free_area_init(unsigned long *zones_size)
3538 {
3539         free_area_init_node(0, NODE_DATA(0), zones_size,
3540                         __pa(PAGE_OFFSET) >> PAGE_SHIFT, NULL);
3541 }
3542
3543 static int page_alloc_cpu_notify(struct notifier_block *self,
3544                                  unsigned long action, void *hcpu)
3545 {
3546         int cpu = (unsigned long)hcpu;
3547
3548         if (action == CPU_DEAD || action == CPU_DEAD_FROZEN) {
3549                 local_irq_disable();
3550                 __drain_pages(cpu);
3551                 vm_events_fold_cpu(cpu);
3552                 local_irq_enable();
3553                 refresh_cpu_vm_stats(cpu);
3554         }
3555         return NOTIFY_OK;
3556 }
3557
3558 void __init page_alloc_init(void)
3559 {
3560         hotcpu_notifier(page_alloc_cpu_notify, 0);
3561 }
3562
3563 /*
3564  * calculate_totalreserve_pages - called when sysctl_lower_zone_reserve_ratio
3565  *      or min_free_kbytes changes.
3566  */
3567 static void calculate_totalreserve_pages(void)
3568 {
3569         struct pglist_data *pgdat;
3570         unsigned long reserve_pages = 0;
3571         enum zone_type i, j;
3572
3573         for_each_online_pgdat(pgdat) {
3574                 for (i = 0; i < MAX_NR_ZONES; i++) {
3575                         struct zone *zone = pgdat->node_zones + i;
3576                         unsigned long max = 0;
3577
3578                         /* Find valid and maximum lowmem_reserve in the zone */
3579                         for (j = i; j < MAX_NR_ZONES; j++) {
3580                                 if (zone->lowmem_reserve[j] > max)
3581                                         max = zone->lowmem_reserve[j];
3582                         }
3583
3584                         /* we treat pages_high as reserved pages. */
3585                         max += zone->pages_high;
3586
3587                         if (max > zone->present_pages)
3588                                 max = zone->present_pages;
3589                         reserve_pages += max;
3590                 }
3591         }
3592         totalreserve_pages = reserve_pages;
3593 }
3594
3595 /*
3596  * setup_per_zone_lowmem_reserve - called whenever
3597  *      sysctl_lower_zone_reserve_ratio changes.  Ensures that each zone
3598  *      has a correct pages reserved value, so an adequate number of
3599  *      pages are left in the zone after a successful __alloc_pages().
3600  */
3601 static void setup_per_zone_lowmem_reserve(void)
3602 {
3603         struct pglist_data *pgdat;
3604         enum zone_type j, idx;
3605
3606         for_each_online_pgdat(pgdat) {
3607                 for (j = 0; j < MAX_NR_ZONES; j++) {
3608                         struct zone *zone = pgdat->node_zones + j;
3609                         unsigned long present_pages = zone->present_pages;
3610
3611                         zone->lowmem_reserve[j] = 0;
3612
3613                         idx = j;
3614                         while (idx) {
3615                                 struct zone *lower_zone;
3616
3617                                 idx--;
3618
3619                                 if (sysctl_lowmem_reserve_ratio[idx] < 1)
3620                                         sysctl_lowmem_reserve_ratio[idx] = 1;
3621
3622                                 lower_zone = pgdat->node_zones + idx;
3623                                 lower_zone->lowmem_reserve[j] = present_pages /
3624                                         sysctl_lowmem_reserve_ratio[idx];
3625                                 present_pages += lower_zone->present_pages;
3626                         }
3627                 }
3628         }
3629
3630         /* update totalreserve_pages */
3631         calculate_totalreserve_pages();
3632 }
3633
3634 /**
3635  * setup_per_zone_pages_min - called when min_free_kbytes changes.
3636  *
3637  * Ensures that the pages_{min,low,high} values for each zone are set correctly
3638  * with respect to min_free_kbytes.
3639  */
3640 void setup_per_zone_pages_min(void)
3641 {
3642         unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
3643         unsigned long lowmem_pages = 0;
3644         struct zone *zone;
3645         unsigned long flags;
3646
3647         /* Calculate total number of !ZONE_HIGHMEM pages */
3648         for_each_zone(zone) {
3649                 if (!is_highmem(zone))
3650                         lowmem_pages += zone->present_pages;
3651         }
3652
3653         for_each_zone(zone) {
3654                 u64 tmp;
3655
3656                 spin_lock_irqsave(&zone->lru_lock, flags);
3657                 tmp = (u64)pages_min * zone->present_pages;
3658                 do_div(tmp, lowmem_pages);
3659                 if (is_highmem(zone)) {
3660                         /*
3661                          * __GFP_HIGH and PF_MEMALLOC allocations usually don't
3662                          * need highmem pages, so cap pages_min to a small
3663                          * value here.
3664                          *
3665                          * The (pages_high-pages_low) and (pages_low-pages_min)
3666                          * deltas controls asynch page reclaim, and so should
3667                          * not be capped for highmem.
3668                          */
3669                         int min_pages;
3670
3671                         min_pages = zone->present_pages / 1024;
3672                         if (min_pages < SWAP_CLUSTER_MAX)
3673                                 min_pages = SWAP_CLUSTER_MAX;
3674                         if (min_pages > 128)
3675                                 min_pages = 128;
3676                         zone->pages_min = min_pages;
3677                 } else {
3678                         /*
3679                          * If it's a lowmem zone, reserve a number of pages
3680                          * proportionate to the zone's size.
3681                          */
3682                         zone->pages_min = tmp;
3683                 }
3684
3685                 zone->pages_low   = zone->pages_min + (tmp >> 2);
3686                 zone->pages_high  = zone->pages_min + (tmp >> 1);
3687                 spin_unlock_irqrestore(&zone->lru_lock, flags);
3688         }
3689
3690         /* update totalreserve_pages */
3691         calculate_totalreserve_pages();
3692 }
3693
3694 /*
3695  * Initialise min_free_kbytes.
3696  *
3697  * For small machines we want it small (128k min).  For large machines
3698  * we want it large (64MB max).  But it is not linear, because network
3699  * bandwidth does not increase linearly with machine size.  We use
3700  *
3701  *      min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
3702  *      min_free_kbytes = sqrt(lowmem_kbytes * 16)
3703  *
3704  * which yields
3705  *
3706  * 16MB:        512k
3707  * 32MB:        724k
3708  * 64MB:        1024k
3709  * 128MB:       1448k
3710  * 256MB:       2048k
3711  * 512MB:       2896k
3712  * 1024MB:      4096k
3713  * 2048MB:      5792k
3714  * 4096MB:      8192k
3715  * 8192MB:      11584k
3716  * 16384MB:     16384k
3717  */
3718 static int __init init_per_zone_pages_min(void)
3719 {
3720         unsigned long lowmem_kbytes;
3721
3722         lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
3723
3724         min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
3725         if (min_free_kbytes < 128)
3726                 min_free_kbytes = 128;
3727         if (min_free_kbytes > 65536)
3728                 min_free_kbytes = 65536;
3729         setup_per_zone_pages_min();
3730         setup_per_zone_lowmem_reserve();
3731         return 0;
3732 }
3733 module_init(init_per_zone_pages_min)
3734
3735 /*
3736  * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
3737  *      that we can call two helper functions whenever min_free_kbytes
3738  *      changes.
3739  */
3740 int min_free_kbytes_sysctl_handler(ctl_table *table, int write,
3741         struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
3742 {
3743         proc_dointvec(table, write, file, buffer, length, ppos);
3744         if (write)
3745                 setup_per_zone_pages_min();
3746         return 0;
3747 }
3748
3749 #ifdef CONFIG_NUMA
3750 int sysctl_min_unmapped_ratio_sysctl_handler(ctl_table *table, int write,
3751         struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
3752 {
3753         struct zone *zone;
3754         int rc;
3755
3756         rc = proc_dointvec_minmax(table, write, file, buffer, length, ppos);
3757         if (rc)
3758                 return rc;
3759
3760         for_each_zone(zone)
3761                 zone->min_unmapped_pages = (zone->present_pages *
3762                                 sysctl_min_unmapped_ratio) / 100;
3763         return 0;
3764 }
3765
3766 int sysctl_min_slab_ratio_sysctl_handler(ctl_table *table, int write,
3767         struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
3768 {
3769         struct zone *zone;
3770         int rc;
3771
3772         rc = proc_dointvec_minmax(table, write, file, buffer, length, ppos);
3773         if (rc)
3774                 return rc;
3775
3776         for_each_zone(zone)
3777                 zone->min_slab_pages = (zone->present_pages *
3778                                 sysctl_min_slab_ratio) / 100;
3779         return 0;
3780 }
3781 #endif
3782
3783 /*
3784  * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
3785  *      proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
3786  *      whenever sysctl_lowmem_reserve_ratio changes.
3787  *
3788  * The reserve ratio obviously has absolutely no relation with the
3789  * pages_min watermarks. The lowmem reserve ratio can only make sense
3790  * if in function of the boot time zone sizes.
3791  */
3792 int lowmem_reserve_ratio_sysctl_handler(ctl_table *table, int write,
3793         struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
3794 {
3795         proc_dointvec_minmax(table, write, file, buffer, length, ppos);
3796         setup_per_zone_lowmem_reserve();
3797         return 0;
3798 }
3799
3800 /*
3801  * percpu_pagelist_fraction - changes the pcp->high for each zone on each
3802  * cpu.  It is the fraction of total pages in each zone that a hot per cpu pagelist
3803  * can have before it gets flushed back to buddy allocator.
3804  */
3805
3806 int percpu_pagelist_fraction_sysctl_handler(ctl_table *table, int write,
3807         struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
3808 {
3809         struct zone *zone;
3810         unsigned int cpu;
3811         int ret;
3812
3813         ret = proc_dointvec_minmax(table, write, file, buffer, length, ppos);
3814         if (!write || (ret == -EINVAL))
3815                 return ret;
3816         for_each_zone(zone) {
3817                 for_each_online_cpu(cpu) {
3818                         unsigned long  high;
3819                         high = zone->present_pages / percpu_pagelist_fraction;
3820                         setup_pagelist_highmark(zone_pcp(zone, cpu), high);
3821                 }
3822         }
3823         return 0;
3824 }
3825
3826 int hashdist = HASHDIST_DEFAULT;
3827
3828 #ifdef CONFIG_NUMA
3829 static int __init set_hashdist(char *str)
3830 {
3831         if (!str)
3832                 return 0;
3833         hashdist = simple_strtoul(str, &str, 0);
3834         return 1;
3835 }
3836 __setup("hashdist=", set_hashdist);
3837 #endif
3838
3839 /*
3840  * allocate a large system hash table from bootmem
3841  * - it is assumed that the hash table must contain an exact power-of-2
3842  *   quantity of entries
3843  * - limit is the number of hash buckets, not the total allocation size
3844  */
3845 void *__init alloc_large_system_hash(const char *tablename,
3846                                      unsigned long bucketsize,
3847                                      unsigned long numentries,
3848                                      int scale,
3849                                      int flags,
3850                                      unsigned int *_hash_shift,
3851                                      unsigned int *_hash_mask,
3852                                      unsigned long limit)
3853 {
3854         unsigned long long max = limit;
3855         unsigned long log2qty, size;
3856         void *table = NULL;
3857
3858         /* allow the kernel cmdline to have a say */
3859         if (!numentries) {
3860                 /* round applicable memory size up to nearest megabyte */
3861                 numentries = nr_kernel_pages;
3862                 numentries += (1UL << (20 - PAGE_SHIFT)) - 1;
3863                 numentries >>= 20 - PAGE_SHIFT;
3864                 numentries <<= 20 - PAGE_SHIFT;
3865
3866                 /* limit to 1 bucket per 2^scale bytes of low memory */
3867                 if (scale > PAGE_SHIFT)
3868                         numentries >>= (scale - PAGE_SHIFT);
3869                 else
3870                         numentries <<= (PAGE_SHIFT - scale);
3871
3872                 /* Make sure we've got at least a 0-order allocation.. */
3873                 if (unlikely((numentries * bucketsize) < PAGE_SIZE))
3874                         numentries = PAGE_SIZE / bucketsize;
3875         }
3876         numentries = roundup_pow_of_two(numentries);
3877
3878         /* limit allocation size to 1/16 total memory by default */
3879         if (max == 0) {
3880                 max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
3881                 do_div(max, bucketsize);
3882         }
3883
3884         if (numentries > max)
3885                 numentries = max;
3886
3887         log2qty = ilog2(numentries);
3888
3889         do {
3890                 size = bucketsize << log2qty;
3891                 if (flags & HASH_EARLY)
3892                         table = alloc_bootmem(size);
3893                 else if (hashdist)
3894                         table = __vmalloc(size, GFP_ATOMIC, PAGE_KERNEL);
3895                 else {
3896                         unsigned long order;
3897                         for (order = 0; ((1UL << order) << PAGE_SHIFT) < size; order++)
3898                                 ;
3899                         table = (void*) __get_free_pages(GFP_ATOMIC, order);
3900                         /*
3901                          * If bucketsize is not a power-of-two, we may free
3902                          * some pages at the end of hash table.
3903                          */
3904                         if (table) {
3905                                 unsigned long alloc_end = (unsigned long)table +
3906                                                 (PAGE_SIZE << order);
3907                                 unsigned long used = (unsigned long)table +
3908                                                 PAGE_ALIGN(size);
3909                                 split_page(virt_to_page(table), order);
3910                                 while (used < alloc_end) {
3911                                         free_page(used);
3912                                         used += PAGE_SIZE;
3913                                 }
3914                         }
3915                 }
3916         } while (!table && size > PAGE_SIZE && --log2qty);
3917
3918         if (!table)
3919                 panic("Failed to allocate %s hash table\n", tablename);
3920
3921         printk(KERN_INFO "%s hash table entries: %d (order: %d, %lu bytes)\n",
3922                tablename,
3923                (1U << log2qty),
3924                ilog2(size) - PAGE_SHIFT,
3925                size);
3926
3927         if (_hash_shift)
3928                 *_hash_shift = log2qty;
3929         if (_hash_mask)
3930                 *_hash_mask = (1 << log2qty) - 1;
3931
3932         return table;
3933 }
3934
3935 #ifdef CONFIG_OUT_OF_LINE_PFN_TO_PAGE
3936 struct page *pfn_to_page(unsigned long pfn)
3937 {
3938         return __pfn_to_page(pfn);
3939 }
3940 unsigned long page_to_pfn(struct page *page)
3941 {
3942         return __page_to_pfn(page);
3943 }
3944 EXPORT_SYMBOL(pfn_to_page);
3945 EXPORT_SYMBOL(page_to_pfn);
3946 #endif /* CONFIG_OUT_OF_LINE_PFN_TO_PAGE */
3947
3948
Note: See TracBrowser for help on using the browser.