[PATCH] mempool: simplify alloc
[firewire-audio.git] / mm / page_alloc.c
blob04a35b3d32620cfc53f7b2a93b5a866d846aac0d
1 /*
2 * linux/mm/page_alloc.c
4 * Manages the free list, the system allocates free pages here.
5 * Note that kmalloc() lives in slab.c
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)
17 #include <linux/config.h>
18 #include <linux/stddef.h>
19 #include <linux/mm.h>
20 #include <linux/swap.h>
21 #include <linux/interrupt.h>
22 #include <linux/pagemap.h>
23 #include <linux/bootmem.h>
24 #include <linux/compiler.h>
25 #include <linux/module.h>
26 #include <linux/suspend.h>
27 #include <linux/pagevec.h>
28 #include <linux/blkdev.h>
29 #include <linux/slab.h>
30 #include <linux/notifier.h>
31 #include <linux/topology.h>
32 #include <linux/sysctl.h>
33 #include <linux/cpu.h>
34 #include <linux/cpuset.h>
35 #include <linux/nodemask.h>
36 #include <linux/vmalloc.h>
38 #include <asm/tlbflush.h>
39 #include "internal.h"
42 * MCD - HACK: Find somewhere to initialize this EARLY, or make this
43 * initializer cleaner
45 nodemask_t node_online_map = { { [0] = 1UL } };
46 nodemask_t node_possible_map = NODE_MASK_ALL;
47 struct pglist_data *pgdat_list;
48 unsigned long totalram_pages;
49 unsigned long totalhigh_pages;
50 long nr_swap_pages;
53 * results with 256, 32 in the lowmem_reserve sysctl:
54 * 1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
55 * 1G machine -> (16M dma, 784M normal, 224M high)
56 * NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
57 * HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
58 * HIGHMEM allocation will (224M+784M)/256 of ram reserved in ZONE_DMA
60 int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES-1] = { 256, 32 };
62 EXPORT_SYMBOL(totalram_pages);
63 EXPORT_SYMBOL(nr_swap_pages);
66 * Used by page_zone() to look up the address of the struct zone whose
67 * id is encoded in the upper bits of page->flags
69 struct zone *zone_table[1 << (ZONES_SHIFT + NODES_SHIFT)];
70 EXPORT_SYMBOL(zone_table);
72 static char *zone_names[MAX_NR_ZONES] = { "DMA", "Normal", "HighMem" };
73 int min_free_kbytes = 1024;
75 unsigned long __initdata nr_kernel_pages;
76 unsigned long __initdata nr_all_pages;
79 * Temporary debugging check for pages not lying within a given zone.
81 static int bad_range(struct zone *zone, struct page *page)
83 if (page_to_pfn(page) >= zone->zone_start_pfn + zone->spanned_pages)
84 return 1;
85 if (page_to_pfn(page) < zone->zone_start_pfn)
86 return 1;
87 #ifdef CONFIG_HOLES_IN_ZONE
88 if (!pfn_valid(page_to_pfn(page)))
89 return 1;
90 #endif
91 if (zone != page_zone(page))
92 return 1;
93 return 0;
96 static void bad_page(const char *function, struct page *page)
98 printk(KERN_EMERG "Bad page state at %s (in process '%s', page %p)\n",
99 function, current->comm, page);
100 printk(KERN_EMERG "flags:0x%0*lx mapping:%p mapcount:%d count:%d\n",
101 (int)(2*sizeof(page_flags_t)), (unsigned long)page->flags,
102 page->mapping, page_mapcount(page), page_count(page));
103 printk(KERN_EMERG "Backtrace:\n");
104 dump_stack();
105 printk(KERN_EMERG "Trying to fix it up, but a reboot is needed\n");
106 page->flags &= ~(1 << PG_private |
107 1 << PG_locked |
108 1 << PG_lru |
109 1 << PG_active |
110 1 << PG_dirty |
111 1 << PG_swapcache |
112 1 << PG_writeback);
113 set_page_count(page, 0);
114 reset_page_mapcount(page);
115 page->mapping = NULL;
116 tainted |= TAINT_BAD_PAGE;
119 #ifndef CONFIG_HUGETLB_PAGE
120 #define prep_compound_page(page, order) do { } while (0)
121 #define destroy_compound_page(page, order) do { } while (0)
122 #else
124 * Higher-order pages are called "compound pages". They are structured thusly:
126 * The first PAGE_SIZE page is called the "head page".
128 * The remaining PAGE_SIZE pages are called "tail pages".
130 * All pages have PG_compound set. All pages have their ->private pointing at
131 * the head page (even the head page has this).
133 * The first tail page's ->mapping, if non-zero, holds the address of the
134 * compound page's put_page() function.
136 * The order of the allocation is stored in the first tail page's ->index
137 * This is only for debug at present. This usage means that zero-order pages
138 * may not be compound.
140 static void prep_compound_page(struct page *page, unsigned long order)
142 int i;
143 int nr_pages = 1 << order;
145 page[1].mapping = NULL;
146 page[1].index = order;
147 for (i = 0; i < nr_pages; i++) {
148 struct page *p = page + i;
150 SetPageCompound(p);
151 p->private = (unsigned long)page;
155 static void destroy_compound_page(struct page *page, unsigned long order)
157 int i;
158 int nr_pages = 1 << order;
160 if (!PageCompound(page))
161 return;
163 if (page[1].index != order)
164 bad_page(__FUNCTION__, page);
166 for (i = 0; i < nr_pages; i++) {
167 struct page *p = page + i;
169 if (!PageCompound(p))
170 bad_page(__FUNCTION__, page);
171 if (p->private != (unsigned long)page)
172 bad_page(__FUNCTION__, page);
173 ClearPageCompound(p);
176 #endif /* CONFIG_HUGETLB_PAGE */
179 * function for dealing with page's order in buddy system.
180 * zone->lock is already acquired when we use these.
181 * So, we don't need atomic page->flags operations here.
183 static inline unsigned long page_order(struct page *page) {
184 return page->private;
187 static inline void set_page_order(struct page *page, int order) {
188 page->private = order;
189 __SetPagePrivate(page);
192 static inline void rmv_page_order(struct page *page)
194 __ClearPagePrivate(page);
195 page->private = 0;
199 * Locate the struct page for both the matching buddy in our
200 * pair (buddy1) and the combined O(n+1) page they form (page).
202 * 1) Any buddy B1 will have an order O twin B2 which satisfies
203 * the following equation:
204 * B2 = B1 ^ (1 << O)
205 * For example, if the starting buddy (buddy2) is #8 its order
206 * 1 buddy is #10:
207 * B2 = 8 ^ (1 << 1) = 8 ^ 2 = 10
209 * 2) Any buddy B will have an order O+1 parent P which
210 * satisfies the following equation:
211 * P = B & ~(1 << O)
213 * Assumption: *_mem_map is contigious at least up to MAX_ORDER
215 static inline struct page *
216 __page_find_buddy(struct page *page, unsigned long page_idx, unsigned int order)
218 unsigned long buddy_idx = page_idx ^ (1 << order);
220 return page + (buddy_idx - page_idx);
223 static inline unsigned long
224 __find_combined_index(unsigned long page_idx, unsigned int order)
226 return (page_idx & ~(1 << order));
230 * This function checks whether a page is free && is the buddy
231 * we can do coalesce a page and its buddy if
232 * (a) the buddy is free &&
233 * (b) the buddy is on the buddy system &&
234 * (c) a page and its buddy have the same order.
235 * for recording page's order, we use page->private and PG_private.
238 static inline int page_is_buddy(struct page *page, int order)
240 if (PagePrivate(page) &&
241 (page_order(page) == order) &&
242 !PageReserved(page) &&
243 page_count(page) == 0)
244 return 1;
245 return 0;
249 * Freeing function for a buddy system allocator.
251 * The concept of a buddy system is to maintain direct-mapped table
252 * (containing bit values) for memory blocks of various "orders".
253 * The bottom level table contains the map for the smallest allocatable
254 * units of memory (here, pages), and each level above it describes
255 * pairs of units from the levels below, hence, "buddies".
256 * At a high level, all that happens here is marking the table entry
257 * at the bottom level available, and propagating the changes upward
258 * as necessary, plus some accounting needed to play nicely with other
259 * parts of the VM system.
260 * At each level, we keep a list of pages, which are heads of continuous
261 * free pages of length of (1 << order) and marked with PG_Private.Page's
262 * order is recorded in page->private field.
263 * So when we are allocating or freeing one, we can derive the state of the
264 * other. That is, if we allocate a small block, and both were
265 * free, the remainder of the region must be split into blocks.
266 * If a block is freed, and its buddy is also free, then this
267 * triggers coalescing into a block of larger size.
269 * -- wli
272 static inline void __free_pages_bulk (struct page *page,
273 struct zone *zone, unsigned int order)
275 unsigned long page_idx;
276 int order_size = 1 << order;
278 if (unlikely(order))
279 destroy_compound_page(page, order);
281 page_idx = page_to_pfn(page) & ((1 << MAX_ORDER) - 1);
283 BUG_ON(page_idx & (order_size - 1));
284 BUG_ON(bad_range(zone, page));
286 zone->free_pages += order_size;
287 while (order < MAX_ORDER-1) {
288 unsigned long combined_idx;
289 struct free_area *area;
290 struct page *buddy;
292 combined_idx = __find_combined_index(page_idx, order);
293 buddy = __page_find_buddy(page, page_idx, order);
295 if (bad_range(zone, buddy))
296 break;
297 if (!page_is_buddy(buddy, order))
298 break; /* Move the buddy up one level. */
299 list_del(&buddy->lru);
300 area = zone->free_area + order;
301 area->nr_free--;
302 rmv_page_order(buddy);
303 page = page + (combined_idx - page_idx);
304 page_idx = combined_idx;
305 order++;
307 set_page_order(page, order);
308 list_add(&page->lru, &zone->free_area[order].free_list);
309 zone->free_area[order].nr_free++;
312 static inline void free_pages_check(const char *function, struct page *page)
314 if ( page_mapcount(page) ||
315 page->mapping != NULL ||
316 page_count(page) != 0 ||
317 (page->flags & (
318 1 << PG_lru |
319 1 << PG_private |
320 1 << PG_locked |
321 1 << PG_active |
322 1 << PG_reclaim |
323 1 << PG_slab |
324 1 << PG_swapcache |
325 1 << PG_writeback )))
326 bad_page(function, page);
327 if (PageDirty(page))
328 ClearPageDirty(page);
332 * Frees a list of pages.
333 * Assumes all pages on list are in same zone, and of same order.
334 * count is the number of pages to free, or 0 for all on the list.
336 * If the zone was previously in an "all pages pinned" state then look to
337 * see if this freeing clears that state.
339 * And clear the zone's pages_scanned counter, to hold off the "all pages are
340 * pinned" detection logic.
342 static int
343 free_pages_bulk(struct zone *zone, int count,
344 struct list_head *list, unsigned int order)
346 unsigned long flags;
347 struct page *page = NULL;
348 int ret = 0;
350 spin_lock_irqsave(&zone->lock, flags);
351 zone->all_unreclaimable = 0;
352 zone->pages_scanned = 0;
353 while (!list_empty(list) && count--) {
354 page = list_entry(list->prev, struct page, lru);
355 /* have to delete it as __free_pages_bulk list manipulates */
356 list_del(&page->lru);
357 __free_pages_bulk(page, zone, order);
358 ret++;
360 spin_unlock_irqrestore(&zone->lock, flags);
361 return ret;
364 void __free_pages_ok(struct page *page, unsigned int order)
366 LIST_HEAD(list);
367 int i;
369 arch_free_page(page, order);
371 mod_page_state(pgfree, 1 << order);
373 #ifndef CONFIG_MMU
374 if (order > 0)
375 for (i = 1 ; i < (1 << order) ; ++i)
376 __put_page(page + i);
377 #endif
379 for (i = 0 ; i < (1 << order) ; ++i)
380 free_pages_check(__FUNCTION__, page + i);
381 list_add(&page->lru, &list);
382 kernel_map_pages(page, 1<<order, 0);
383 free_pages_bulk(page_zone(page), 1, &list, order);
388 * The order of subdivision here is critical for the IO subsystem.
389 * Please do not alter this order without good reasons and regression
390 * testing. Specifically, as large blocks of memory are subdivided,
391 * the order in which smaller blocks are delivered depends on the order
392 * they're subdivided in this function. This is the primary factor
393 * influencing the order in which pages are delivered to the IO
394 * subsystem according to empirical testing, and this is also justified
395 * by considering the behavior of a buddy system containing a single
396 * large block of memory acted on by a series of small allocations.
397 * This behavior is a critical factor in sglist merging's success.
399 * -- wli
401 static inline struct page *
402 expand(struct zone *zone, struct page *page,
403 int low, int high, struct free_area *area)
405 unsigned long size = 1 << high;
407 while (high > low) {
408 area--;
409 high--;
410 size >>= 1;
411 BUG_ON(bad_range(zone, &page[size]));
412 list_add(&page[size].lru, &area->free_list);
413 area->nr_free++;
414 set_page_order(&page[size], high);
416 return page;
419 void set_page_refs(struct page *page, int order)
421 #ifdef CONFIG_MMU
422 set_page_count(page, 1);
423 #else
424 int i;
427 * We need to reference all the pages for this order, otherwise if
428 * anyone accesses one of the pages with (get/put) it will be freed.
429 * - eg: access_process_vm()
431 for (i = 0; i < (1 << order); i++)
432 set_page_count(page + i, 1);
433 #endif /* CONFIG_MMU */
437 * This page is about to be returned from the page allocator
439 static void prep_new_page(struct page *page, int order)
441 if (page->mapping || page_mapcount(page) ||
442 (page->flags & (
443 1 << PG_private |
444 1 << PG_locked |
445 1 << PG_lru |
446 1 << PG_active |
447 1 << PG_dirty |
448 1 << PG_reclaim |
449 1 << PG_swapcache |
450 1 << PG_writeback )))
451 bad_page(__FUNCTION__, page);
453 page->flags &= ~(1 << PG_uptodate | 1 << PG_error |
454 1 << PG_referenced | 1 << PG_arch_1 |
455 1 << PG_checked | 1 << PG_mappedtodisk);
456 page->private = 0;
457 set_page_refs(page, order);
458 kernel_map_pages(page, 1 << order, 1);
462 * Do the hard work of removing an element from the buddy allocator.
463 * Call me with the zone->lock already held.
465 static struct page *__rmqueue(struct zone *zone, unsigned int order)
467 struct free_area * area;
468 unsigned int current_order;
469 struct page *page;
471 for (current_order = order; current_order < MAX_ORDER; ++current_order) {
472 area = zone->free_area + current_order;
473 if (list_empty(&area->free_list))
474 continue;
476 page = list_entry(area->free_list.next, struct page, lru);
477 list_del(&page->lru);
478 rmv_page_order(page);
479 area->nr_free--;
480 zone->free_pages -= 1UL << order;
481 return expand(zone, page, order, current_order, area);
484 return NULL;
488 * Obtain a specified number of elements from the buddy allocator, all under
489 * a single hold of the lock, for efficiency. Add them to the supplied list.
490 * Returns the number of new pages which were placed at *list.
492 static int rmqueue_bulk(struct zone *zone, unsigned int order,
493 unsigned long count, struct list_head *list)
495 unsigned long flags;
496 int i;
497 int allocated = 0;
498 struct page *page;
500 spin_lock_irqsave(&zone->lock, flags);
501 for (i = 0; i < count; ++i) {
502 page = __rmqueue(zone, order);
503 if (page == NULL)
504 break;
505 allocated++;
506 list_add_tail(&page->lru, list);
508 spin_unlock_irqrestore(&zone->lock, flags);
509 return allocated;
512 #if defined(CONFIG_PM) || defined(CONFIG_HOTPLUG_CPU)
513 static void __drain_pages(unsigned int cpu)
515 struct zone *zone;
516 int i;
518 for_each_zone(zone) {
519 struct per_cpu_pageset *pset;
521 pset = &zone->pageset[cpu];
522 for (i = 0; i < ARRAY_SIZE(pset->pcp); i++) {
523 struct per_cpu_pages *pcp;
525 pcp = &pset->pcp[i];
526 pcp->count -= free_pages_bulk(zone, pcp->count,
527 &pcp->list, 0);
531 #endif /* CONFIG_PM || CONFIG_HOTPLUG_CPU */
533 #ifdef CONFIG_PM
535 void mark_free_pages(struct zone *zone)
537 unsigned long zone_pfn, flags;
538 int order;
539 struct list_head *curr;
541 if (!zone->spanned_pages)
542 return;
544 spin_lock_irqsave(&zone->lock, flags);
545 for (zone_pfn = 0; zone_pfn < zone->spanned_pages; ++zone_pfn)
546 ClearPageNosaveFree(pfn_to_page(zone_pfn + zone->zone_start_pfn));
548 for (order = MAX_ORDER - 1; order >= 0; --order)
549 list_for_each(curr, &zone->free_area[order].free_list) {
550 unsigned long start_pfn, i;
552 start_pfn = page_to_pfn(list_entry(curr, struct page, lru));
554 for (i=0; i < (1<<order); i++)
555 SetPageNosaveFree(pfn_to_page(start_pfn+i));
557 spin_unlock_irqrestore(&zone->lock, flags);
561 * Spill all of this CPU's per-cpu pages back into the buddy allocator.
563 void drain_local_pages(void)
565 unsigned long flags;
567 local_irq_save(flags);
568 __drain_pages(smp_processor_id());
569 local_irq_restore(flags);
571 #endif /* CONFIG_PM */
573 static void zone_statistics(struct zonelist *zonelist, struct zone *z)
575 #ifdef CONFIG_NUMA
576 unsigned long flags;
577 int cpu;
578 pg_data_t *pg = z->zone_pgdat;
579 pg_data_t *orig = zonelist->zones[0]->zone_pgdat;
580 struct per_cpu_pageset *p;
582 local_irq_save(flags);
583 cpu = smp_processor_id();
584 p = &z->pageset[cpu];
585 if (pg == orig) {
586 z->pageset[cpu].numa_hit++;
587 } else {
588 p->numa_miss++;
589 zonelist->zones[0]->pageset[cpu].numa_foreign++;
591 if (pg == NODE_DATA(numa_node_id()))
592 p->local_node++;
593 else
594 p->other_node++;
595 local_irq_restore(flags);
596 #endif
600 * Free a 0-order page
602 static void FASTCALL(free_hot_cold_page(struct page *page, int cold));
603 static void fastcall free_hot_cold_page(struct page *page, int cold)
605 struct zone *zone = page_zone(page);
606 struct per_cpu_pages *pcp;
607 unsigned long flags;
609 arch_free_page(page, 0);
611 kernel_map_pages(page, 1, 0);
612 inc_page_state(pgfree);
613 if (PageAnon(page))
614 page->mapping = NULL;
615 free_pages_check(__FUNCTION__, page);
616 pcp = &zone->pageset[get_cpu()].pcp[cold];
617 local_irq_save(flags);
618 if (pcp->count >= pcp->high)
619 pcp->count -= free_pages_bulk(zone, pcp->batch, &pcp->list, 0);
620 list_add(&page->lru, &pcp->list);
621 pcp->count++;
622 local_irq_restore(flags);
623 put_cpu();
626 void fastcall free_hot_page(struct page *page)
628 free_hot_cold_page(page, 0);
631 void fastcall free_cold_page(struct page *page)
633 free_hot_cold_page(page, 1);
636 static inline void prep_zero_page(struct page *page, int order, unsigned int __nocast gfp_flags)
638 int i;
640 BUG_ON((gfp_flags & (__GFP_WAIT | __GFP_HIGHMEM)) == __GFP_HIGHMEM);
641 for(i = 0; i < (1 << order); i++)
642 clear_highpage(page + i);
646 * Really, prep_compound_page() should be called from __rmqueue_bulk(). But
647 * we cheat by calling it from here, in the order > 0 path. Saves a branch
648 * or two.
650 static struct page *
651 buffered_rmqueue(struct zone *zone, int order, unsigned int __nocast gfp_flags)
653 unsigned long flags;
654 struct page *page = NULL;
655 int cold = !!(gfp_flags & __GFP_COLD);
657 if (order == 0) {
658 struct per_cpu_pages *pcp;
660 pcp = &zone->pageset[get_cpu()].pcp[cold];
661 local_irq_save(flags);
662 if (pcp->count <= pcp->low)
663 pcp->count += rmqueue_bulk(zone, 0,
664 pcp->batch, &pcp->list);
665 if (pcp->count) {
666 page = list_entry(pcp->list.next, struct page, lru);
667 list_del(&page->lru);
668 pcp->count--;
670 local_irq_restore(flags);
671 put_cpu();
674 if (page == NULL) {
675 spin_lock_irqsave(&zone->lock, flags);
676 page = __rmqueue(zone, order);
677 spin_unlock_irqrestore(&zone->lock, flags);
680 if (page != NULL) {
681 BUG_ON(bad_range(zone, page));
682 mod_page_state_zone(zone, pgalloc, 1 << order);
683 prep_new_page(page, order);
685 if (gfp_flags & __GFP_ZERO)
686 prep_zero_page(page, order, gfp_flags);
688 if (order && (gfp_flags & __GFP_COMP))
689 prep_compound_page(page, order);
691 return page;
695 * Return 1 if free pages are above 'mark'. This takes into account the order
696 * of the allocation.
698 int zone_watermark_ok(struct zone *z, int order, unsigned long mark,
699 int classzone_idx, int can_try_harder, int gfp_high)
701 /* free_pages my go negative - that's OK */
702 long min = mark, free_pages = z->free_pages - (1 << order) + 1;
703 int o;
705 if (gfp_high)
706 min -= min / 2;
707 if (can_try_harder)
708 min -= min / 4;
710 if (free_pages <= min + z->lowmem_reserve[classzone_idx])
711 return 0;
712 for (o = 0; o < order; o++) {
713 /* At the next order, this order's pages become unavailable */
714 free_pages -= z->free_area[o].nr_free << o;
716 /* Require fewer higher order pages to be free */
717 min >>= 1;
719 if (free_pages <= min)
720 return 0;
722 return 1;
726 * This is the 'heart' of the zoned buddy allocator.
728 struct page * fastcall
729 __alloc_pages(unsigned int __nocast gfp_mask, unsigned int order,
730 struct zonelist *zonelist)
732 const int wait = gfp_mask & __GFP_WAIT;
733 struct zone **zones, *z;
734 struct page *page;
735 struct reclaim_state reclaim_state;
736 struct task_struct *p = current;
737 int i;
738 int classzone_idx;
739 int do_retry;
740 int can_try_harder;
741 int did_some_progress;
743 might_sleep_if(wait);
746 * The caller may dip into page reserves a bit more if the caller
747 * cannot run direct reclaim, or is the caller has realtime scheduling
748 * policy
750 can_try_harder = (unlikely(rt_task(p)) && !in_interrupt()) || !wait;
752 zones = zonelist->zones; /* the list of zones suitable for gfp_mask */
754 if (unlikely(zones[0] == NULL)) {
755 /* Should this ever happen?? */
756 return NULL;
759 classzone_idx = zone_idx(zones[0]);
761 restart:
762 /* Go through the zonelist once, looking for a zone with enough free */
763 for (i = 0; (z = zones[i]) != NULL; i++) {
765 if (!zone_watermark_ok(z, order, z->pages_low,
766 classzone_idx, 0, 0))
767 continue;
769 if (!cpuset_zone_allowed(z))
770 continue;
772 page = buffered_rmqueue(z, order, gfp_mask);
773 if (page)
774 goto got_pg;
777 for (i = 0; (z = zones[i]) != NULL; i++)
778 wakeup_kswapd(z, order);
781 * Go through the zonelist again. Let __GFP_HIGH and allocations
782 * coming from realtime tasks to go deeper into reserves
784 * This is the last chance, in general, before the goto nopage.
785 * Ignore cpuset if GFP_ATOMIC (!wait) rather than fail alloc.
787 for (i = 0; (z = zones[i]) != NULL; i++) {
788 if (!zone_watermark_ok(z, order, z->pages_min,
789 classzone_idx, can_try_harder,
790 gfp_mask & __GFP_HIGH))
791 continue;
793 if (wait && !cpuset_zone_allowed(z))
794 continue;
796 page = buffered_rmqueue(z, order, gfp_mask);
797 if (page)
798 goto got_pg;
801 /* This allocation should allow future memory freeing. */
803 if (((p->flags & PF_MEMALLOC) || unlikely(test_thread_flag(TIF_MEMDIE)))
804 && !in_interrupt()) {
805 if (!(gfp_mask & __GFP_NOMEMALLOC)) {
806 /* go through the zonelist yet again, ignoring mins */
807 for (i = 0; (z = zones[i]) != NULL; i++) {
808 if (!cpuset_zone_allowed(z))
809 continue;
810 page = buffered_rmqueue(z, order, gfp_mask);
811 if (page)
812 goto got_pg;
815 goto nopage;
818 /* Atomic allocations - we can't balance anything */
819 if (!wait)
820 goto nopage;
822 rebalance:
823 cond_resched();
825 /* We now go into synchronous reclaim */
826 p->flags |= PF_MEMALLOC;
827 reclaim_state.reclaimed_slab = 0;
828 p->reclaim_state = &reclaim_state;
830 did_some_progress = try_to_free_pages(zones, gfp_mask, order);
832 p->reclaim_state = NULL;
833 p->flags &= ~PF_MEMALLOC;
835 cond_resched();
837 if (likely(did_some_progress)) {
839 * Go through the zonelist yet one more time, keep
840 * very high watermark here, this is only to catch
841 * a parallel oom killing, we must fail if we're still
842 * under heavy pressure.
844 for (i = 0; (z = zones[i]) != NULL; i++) {
845 if (!zone_watermark_ok(z, order, z->pages_min,
846 classzone_idx, can_try_harder,
847 gfp_mask & __GFP_HIGH))
848 continue;
850 if (!cpuset_zone_allowed(z))
851 continue;
853 page = buffered_rmqueue(z, order, gfp_mask);
854 if (page)
855 goto got_pg;
857 } else if ((gfp_mask & __GFP_FS) && !(gfp_mask & __GFP_NORETRY)) {
859 * Go through the zonelist yet one more time, keep
860 * very high watermark here, this is only to catch
861 * a parallel oom killing, we must fail if we're still
862 * under heavy pressure.
864 for (i = 0; (z = zones[i]) != NULL; i++) {
865 if (!zone_watermark_ok(z, order, z->pages_high,
866 classzone_idx, 0, 0))
867 continue;
869 if (!cpuset_zone_allowed(z))
870 continue;
872 page = buffered_rmqueue(z, order, gfp_mask);
873 if (page)
874 goto got_pg;
877 out_of_memory(gfp_mask);
878 goto restart;
882 * Don't let big-order allocations loop unless the caller explicitly
883 * requests that. Wait for some write requests to complete then retry.
885 * In this implementation, __GFP_REPEAT means __GFP_NOFAIL for order
886 * <= 3, but that may not be true in other implementations.
888 do_retry = 0;
889 if (!(gfp_mask & __GFP_NORETRY)) {
890 if ((order <= 3) || (gfp_mask & __GFP_REPEAT))
891 do_retry = 1;
892 if (gfp_mask & __GFP_NOFAIL)
893 do_retry = 1;
895 if (do_retry) {
896 blk_congestion_wait(WRITE, HZ/50);
897 goto rebalance;
900 nopage:
901 if (!(gfp_mask & __GFP_NOWARN) && printk_ratelimit()) {
902 printk(KERN_WARNING "%s: page allocation failure."
903 " order:%d, mode:0x%x\n",
904 p->comm, order, gfp_mask);
905 dump_stack();
907 return NULL;
908 got_pg:
909 zone_statistics(zonelist, z);
910 return page;
913 EXPORT_SYMBOL(__alloc_pages);
916 * Common helper functions.
918 fastcall unsigned long __get_free_pages(unsigned int __nocast gfp_mask, unsigned int order)
920 struct page * page;
921 page = alloc_pages(gfp_mask, order);
922 if (!page)
923 return 0;
924 return (unsigned long) page_address(page);
927 EXPORT_SYMBOL(__get_free_pages);
929 fastcall unsigned long get_zeroed_page(unsigned int __nocast gfp_mask)
931 struct page * page;
934 * get_zeroed_page() returns a 32-bit address, which cannot represent
935 * a highmem page
937 BUG_ON(gfp_mask & __GFP_HIGHMEM);
939 page = alloc_pages(gfp_mask | __GFP_ZERO, 0);
940 if (page)
941 return (unsigned long) page_address(page);
942 return 0;
945 EXPORT_SYMBOL(get_zeroed_page);
947 void __pagevec_free(struct pagevec *pvec)
949 int i = pagevec_count(pvec);
951 while (--i >= 0)
952 free_hot_cold_page(pvec->pages[i], pvec->cold);
955 fastcall void __free_pages(struct page *page, unsigned int order)
957 if (!PageReserved(page) && put_page_testzero(page)) {
958 if (order == 0)
959 free_hot_page(page);
960 else
961 __free_pages_ok(page, order);
965 EXPORT_SYMBOL(__free_pages);
967 fastcall void free_pages(unsigned long addr, unsigned int order)
969 if (addr != 0) {
970 BUG_ON(!virt_addr_valid((void *)addr));
971 __free_pages(virt_to_page((void *)addr), order);
975 EXPORT_SYMBOL(free_pages);
978 * Total amount of free (allocatable) RAM:
980 unsigned int nr_free_pages(void)
982 unsigned int sum = 0;
983 struct zone *zone;
985 for_each_zone(zone)
986 sum += zone->free_pages;
988 return sum;
991 EXPORT_SYMBOL(nr_free_pages);
993 #ifdef CONFIG_NUMA
994 unsigned int nr_free_pages_pgdat(pg_data_t *pgdat)
996 unsigned int i, sum = 0;
998 for (i = 0; i < MAX_NR_ZONES; i++)
999 sum += pgdat->node_zones[i].free_pages;
1001 return sum;
1003 #endif
1005 static unsigned int nr_free_zone_pages(int offset)
1007 pg_data_t *pgdat;
1008 unsigned int sum = 0;
1010 for_each_pgdat(pgdat) {
1011 struct zonelist *zonelist = pgdat->node_zonelists + offset;
1012 struct zone **zonep = zonelist->zones;
1013 struct zone *zone;
1015 for (zone = *zonep++; zone; zone = *zonep++) {
1016 unsigned long size = zone->present_pages;
1017 unsigned long high = zone->pages_high;
1018 if (size > high)
1019 sum += size - high;
1023 return sum;
1027 * Amount of free RAM allocatable within ZONE_DMA and ZONE_NORMAL
1029 unsigned int nr_free_buffer_pages(void)
1031 return nr_free_zone_pages(GFP_USER & GFP_ZONEMASK);
1035 * Amount of free RAM allocatable within all zones
1037 unsigned int nr_free_pagecache_pages(void)
1039 return nr_free_zone_pages(GFP_HIGHUSER & GFP_ZONEMASK);
1042 #ifdef CONFIG_HIGHMEM
1043 unsigned int nr_free_highpages (void)
1045 pg_data_t *pgdat;
1046 unsigned int pages = 0;
1048 for_each_pgdat(pgdat)
1049 pages += pgdat->node_zones[ZONE_HIGHMEM].free_pages;
1051 return pages;
1053 #endif
1055 #ifdef CONFIG_NUMA
1056 static void show_node(struct zone *zone)
1058 printk("Node %d ", zone->zone_pgdat->node_id);
1060 #else
1061 #define show_node(zone) do { } while (0)
1062 #endif
1065 * Accumulate the page_state information across all CPUs.
1066 * The result is unavoidably approximate - it can change
1067 * during and after execution of this function.
1069 static DEFINE_PER_CPU(struct page_state, page_states) = {0};
1071 atomic_t nr_pagecache = ATOMIC_INIT(0);
1072 EXPORT_SYMBOL(nr_pagecache);
1073 #ifdef CONFIG_SMP
1074 DEFINE_PER_CPU(long, nr_pagecache_local) = 0;
1075 #endif
1077 void __get_page_state(struct page_state *ret, int nr)
1079 int cpu = 0;
1081 memset(ret, 0, sizeof(*ret));
1083 cpu = first_cpu(cpu_online_map);
1084 while (cpu < NR_CPUS) {
1085 unsigned long *in, *out, off;
1087 in = (unsigned long *)&per_cpu(page_states, cpu);
1089 cpu = next_cpu(cpu, cpu_online_map);
1091 if (cpu < NR_CPUS)
1092 prefetch(&per_cpu(page_states, cpu));
1094 out = (unsigned long *)ret;
1095 for (off = 0; off < nr; off++)
1096 *out++ += *in++;
1100 void get_page_state(struct page_state *ret)
1102 int nr;
1104 nr = offsetof(struct page_state, GET_PAGE_STATE_LAST);
1105 nr /= sizeof(unsigned long);
1107 __get_page_state(ret, nr + 1);
1110 void get_full_page_state(struct page_state *ret)
1112 __get_page_state(ret, sizeof(*ret) / sizeof(unsigned long));
1115 unsigned long __read_page_state(unsigned offset)
1117 unsigned long ret = 0;
1118 int cpu;
1120 for_each_online_cpu(cpu) {
1121 unsigned long in;
1123 in = (unsigned long)&per_cpu(page_states, cpu) + offset;
1124 ret += *((unsigned long *)in);
1126 return ret;
1129 void __mod_page_state(unsigned offset, unsigned long delta)
1131 unsigned long flags;
1132 void* ptr;
1134 local_irq_save(flags);
1135 ptr = &__get_cpu_var(page_states);
1136 *(unsigned long*)(ptr + offset) += delta;
1137 local_irq_restore(flags);
1140 EXPORT_SYMBOL(__mod_page_state);
1142 void __get_zone_counts(unsigned long *active, unsigned long *inactive,
1143 unsigned long *free, struct pglist_data *pgdat)
1145 struct zone *zones = pgdat->node_zones;
1146 int i;
1148 *active = 0;
1149 *inactive = 0;
1150 *free = 0;
1151 for (i = 0; i < MAX_NR_ZONES; i++) {
1152 *active += zones[i].nr_active;
1153 *inactive += zones[i].nr_inactive;
1154 *free += zones[i].free_pages;
1158 void get_zone_counts(unsigned long *active,
1159 unsigned long *inactive, unsigned long *free)
1161 struct pglist_data *pgdat;
1163 *active = 0;
1164 *inactive = 0;
1165 *free = 0;
1166 for_each_pgdat(pgdat) {
1167 unsigned long l, m, n;
1168 __get_zone_counts(&l, &m, &n, pgdat);
1169 *active += l;
1170 *inactive += m;
1171 *free += n;
1175 void si_meminfo(struct sysinfo *val)
1177 val->totalram = totalram_pages;
1178 val->sharedram = 0;
1179 val->freeram = nr_free_pages();
1180 val->bufferram = nr_blockdev_pages();
1181 #ifdef CONFIG_HIGHMEM
1182 val->totalhigh = totalhigh_pages;
1183 val->freehigh = nr_free_highpages();
1184 #else
1185 val->totalhigh = 0;
1186 val->freehigh = 0;
1187 #endif
1188 val->mem_unit = PAGE_SIZE;
1191 EXPORT_SYMBOL(si_meminfo);
1193 #ifdef CONFIG_NUMA
1194 void si_meminfo_node(struct sysinfo *val, int nid)
1196 pg_data_t *pgdat = NODE_DATA(nid);
1198 val->totalram = pgdat->node_present_pages;
1199 val->freeram = nr_free_pages_pgdat(pgdat);
1200 val->totalhigh = pgdat->node_zones[ZONE_HIGHMEM].present_pages;
1201 val->freehigh = pgdat->node_zones[ZONE_HIGHMEM].free_pages;
1202 val->mem_unit = PAGE_SIZE;
1204 #endif
1206 #define K(x) ((x) << (PAGE_SHIFT-10))
1209 * Show free area list (used inside shift_scroll-lock stuff)
1210 * We also calculate the percentage fragmentation. We do this by counting the
1211 * memory on each free list with the exception of the first item on the list.
1213 void show_free_areas(void)
1215 struct page_state ps;
1216 int cpu, temperature;
1217 unsigned long active;
1218 unsigned long inactive;
1219 unsigned long free;
1220 struct zone *zone;
1222 for_each_zone(zone) {
1223 show_node(zone);
1224 printk("%s per-cpu:", zone->name);
1226 if (!zone->present_pages) {
1227 printk(" empty\n");
1228 continue;
1229 } else
1230 printk("\n");
1232 for (cpu = 0; cpu < NR_CPUS; ++cpu) {
1233 struct per_cpu_pageset *pageset;
1235 if (!cpu_possible(cpu))
1236 continue;
1238 pageset = zone->pageset + cpu;
1240 for (temperature = 0; temperature < 2; temperature++)
1241 printk("cpu %d %s: low %d, high %d, batch %d\n",
1242 cpu,
1243 temperature ? "cold" : "hot",
1244 pageset->pcp[temperature].low,
1245 pageset->pcp[temperature].high,
1246 pageset->pcp[temperature].batch);
1250 get_page_state(&ps);
1251 get_zone_counts(&active, &inactive, &free);
1253 printk("\nFree pages: %11ukB (%ukB HighMem)\n",
1254 K(nr_free_pages()),
1255 K(nr_free_highpages()));
1257 printk("Active:%lu inactive:%lu dirty:%lu writeback:%lu "
1258 "unstable:%lu free:%u slab:%lu mapped:%lu pagetables:%lu\n",
1259 active,
1260 inactive,
1261 ps.nr_dirty,
1262 ps.nr_writeback,
1263 ps.nr_unstable,
1264 nr_free_pages(),
1265 ps.nr_slab,
1266 ps.nr_mapped,
1267 ps.nr_page_table_pages);
1269 for_each_zone(zone) {
1270 int i;
1272 show_node(zone);
1273 printk("%s"
1274 " free:%lukB"
1275 " min:%lukB"
1276 " low:%lukB"
1277 " high:%lukB"
1278 " active:%lukB"
1279 " inactive:%lukB"
1280 " present:%lukB"
1281 " pages_scanned:%lu"
1282 " all_unreclaimable? %s"
1283 "\n",
1284 zone->name,
1285 K(zone->free_pages),
1286 K(zone->pages_min),
1287 K(zone->pages_low),
1288 K(zone->pages_high),
1289 K(zone->nr_active),
1290 K(zone->nr_inactive),
1291 K(zone->present_pages),
1292 zone->pages_scanned,
1293 (zone->all_unreclaimable ? "yes" : "no")
1295 printk("lowmem_reserve[]:");
1296 for (i = 0; i < MAX_NR_ZONES; i++)
1297 printk(" %lu", zone->lowmem_reserve[i]);
1298 printk("\n");
1301 for_each_zone(zone) {
1302 unsigned long nr, flags, order, total = 0;
1304 show_node(zone);
1305 printk("%s: ", zone->name);
1306 if (!zone->present_pages) {
1307 printk("empty\n");
1308 continue;
1311 spin_lock_irqsave(&zone->lock, flags);
1312 for (order = 0; order < MAX_ORDER; order++) {
1313 nr = zone->free_area[order].nr_free;
1314 total += nr << order;
1315 printk("%lu*%lukB ", nr, K(1UL) << order);
1317 spin_unlock_irqrestore(&zone->lock, flags);
1318 printk("= %lukB\n", K(total));
1321 show_swap_cache_info();
1325 * Builds allocation fallback zone lists.
1327 static int __init build_zonelists_node(pg_data_t *pgdat, struct zonelist *zonelist, int j, int k)
1329 switch (k) {
1330 struct zone *zone;
1331 default:
1332 BUG();
1333 case ZONE_HIGHMEM:
1334 zone = pgdat->node_zones + ZONE_HIGHMEM;
1335 if (zone->present_pages) {
1336 #ifndef CONFIG_HIGHMEM
1337 BUG();
1338 #endif
1339 zonelist->zones[j++] = zone;
1341 case ZONE_NORMAL:
1342 zone = pgdat->node_zones + ZONE_NORMAL;
1343 if (zone->present_pages)
1344 zonelist->zones[j++] = zone;
1345 case ZONE_DMA:
1346 zone = pgdat->node_zones + ZONE_DMA;
1347 if (zone->present_pages)
1348 zonelist->zones[j++] = zone;
1351 return j;
1354 #ifdef CONFIG_NUMA
1355 #define MAX_NODE_LOAD (num_online_nodes())
1356 static int __initdata node_load[MAX_NUMNODES];
1358 * find_next_best_node - find the next node that should appear in a given
1359 * node's fallback list
1360 * @node: node whose fallback list we're appending
1361 * @used_node_mask: nodemask_t of already used nodes
1363 * We use a number of factors to determine which is the next node that should
1364 * appear on a given node's fallback list. The node should not have appeared
1365 * already in @node's fallback list, and it should be the next closest node
1366 * according to the distance array (which contains arbitrary distance values
1367 * from each node to each node in the system), and should also prefer nodes
1368 * with no CPUs, since presumably they'll have very little allocation pressure
1369 * on them otherwise.
1370 * It returns -1 if no node is found.
1372 static int __init find_next_best_node(int node, nodemask_t *used_node_mask)
1374 int i, n, val;
1375 int min_val = INT_MAX;
1376 int best_node = -1;
1378 for_each_online_node(i) {
1379 cpumask_t tmp;
1381 /* Start from local node */
1382 n = (node+i) % num_online_nodes();
1384 /* Don't want a node to appear more than once */
1385 if (node_isset(n, *used_node_mask))
1386 continue;
1388 /* Use the local node if we haven't already */
1389 if (!node_isset(node, *used_node_mask)) {
1390 best_node = node;
1391 break;
1394 /* Use the distance array to find the distance */
1395 val = node_distance(node, n);
1397 /* Give preference to headless and unused nodes */
1398 tmp = node_to_cpumask(n);
1399 if (!cpus_empty(tmp))
1400 val += PENALTY_FOR_NODE_WITH_CPUS;
1402 /* Slight preference for less loaded node */
1403 val *= (MAX_NODE_LOAD*MAX_NUMNODES);
1404 val += node_load[n];
1406 if (val < min_val) {
1407 min_val = val;
1408 best_node = n;
1412 if (best_node >= 0)
1413 node_set(best_node, *used_node_mask);
1415 return best_node;
1418 static void __init build_zonelists(pg_data_t *pgdat)
1420 int i, j, k, node, local_node;
1421 int prev_node, load;
1422 struct zonelist *zonelist;
1423 nodemask_t used_mask;
1425 /* initialize zonelists */
1426 for (i = 0; i < GFP_ZONETYPES; i++) {
1427 zonelist = pgdat->node_zonelists + i;
1428 zonelist->zones[0] = NULL;
1431 /* NUMA-aware ordering of nodes */
1432 local_node = pgdat->node_id;
1433 load = num_online_nodes();
1434 prev_node = local_node;
1435 nodes_clear(used_mask);
1436 while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
1438 * We don't want to pressure a particular node.
1439 * So adding penalty to the first node in same
1440 * distance group to make it round-robin.
1442 if (node_distance(local_node, node) !=
1443 node_distance(local_node, prev_node))
1444 node_load[node] += load;
1445 prev_node = node;
1446 load--;
1447 for (i = 0; i < GFP_ZONETYPES; i++) {
1448 zonelist = pgdat->node_zonelists + i;
1449 for (j = 0; zonelist->zones[j] != NULL; j++);
1451 k = ZONE_NORMAL;
1452 if (i & __GFP_HIGHMEM)
1453 k = ZONE_HIGHMEM;
1454 if (i & __GFP_DMA)
1455 k = ZONE_DMA;
1457 j = build_zonelists_node(NODE_DATA(node), zonelist, j, k);
1458 zonelist->zones[j] = NULL;
1463 #else /* CONFIG_NUMA */
1465 static void __init build_zonelists(pg_data_t *pgdat)
1467 int i, j, k, node, local_node;
1469 local_node = pgdat->node_id;
1470 for (i = 0; i < GFP_ZONETYPES; i++) {
1471 struct zonelist *zonelist;
1473 zonelist = pgdat->node_zonelists + i;
1475 j = 0;
1476 k = ZONE_NORMAL;
1477 if (i & __GFP_HIGHMEM)
1478 k = ZONE_HIGHMEM;
1479 if (i & __GFP_DMA)
1480 k = ZONE_DMA;
1482 j = build_zonelists_node(pgdat, zonelist, j, k);
1484 * Now we build the zonelist so that it contains the zones
1485 * of all the other nodes.
1486 * We don't want to pressure a particular node, so when
1487 * building the zones for node N, we make sure that the
1488 * zones coming right after the local ones are those from
1489 * node N+1 (modulo N)
1491 for (node = local_node + 1; node < MAX_NUMNODES; node++) {
1492 if (!node_online(node))
1493 continue;
1494 j = build_zonelists_node(NODE_DATA(node), zonelist, j, k);
1496 for (node = 0; node < local_node; node++) {
1497 if (!node_online(node))
1498 continue;
1499 j = build_zonelists_node(NODE_DATA(node), zonelist, j, k);
1502 zonelist->zones[j] = NULL;
1506 #endif /* CONFIG_NUMA */
1508 void __init build_all_zonelists(void)
1510 int i;
1512 for_each_online_node(i)
1513 build_zonelists(NODE_DATA(i));
1514 printk("Built %i zonelists\n", num_online_nodes());
1515 cpuset_init_current_mems_allowed();
1519 * Helper functions to size the waitqueue hash table.
1520 * Essentially these want to choose hash table sizes sufficiently
1521 * large so that collisions trying to wait on pages are rare.
1522 * But in fact, the number of active page waitqueues on typical
1523 * systems is ridiculously low, less than 200. So this is even
1524 * conservative, even though it seems large.
1526 * The constant PAGES_PER_WAITQUEUE specifies the ratio of pages to
1527 * waitqueues, i.e. the size of the waitq table given the number of pages.
1529 #define PAGES_PER_WAITQUEUE 256
1531 static inline unsigned long wait_table_size(unsigned long pages)
1533 unsigned long size = 1;
1535 pages /= PAGES_PER_WAITQUEUE;
1537 while (size < pages)
1538 size <<= 1;
1541 * Once we have dozens or even hundreds of threads sleeping
1542 * on IO we've got bigger problems than wait queue collision.
1543 * Limit the size of the wait table to a reasonable size.
1545 size = min(size, 4096UL);
1547 return max(size, 4UL);
1551 * This is an integer logarithm so that shifts can be used later
1552 * to extract the more random high bits from the multiplicative
1553 * hash function before the remainder is taken.
1555 static inline unsigned long wait_table_bits(unsigned long size)
1557 return ffz(~size);
1560 #define LONG_ALIGN(x) (((x)+(sizeof(long))-1)&~((sizeof(long))-1))
1562 static void __init calculate_zone_totalpages(struct pglist_data *pgdat,
1563 unsigned long *zones_size, unsigned long *zholes_size)
1565 unsigned long realtotalpages, totalpages = 0;
1566 int i;
1568 for (i = 0; i < MAX_NR_ZONES; i++)
1569 totalpages += zones_size[i];
1570 pgdat->node_spanned_pages = totalpages;
1572 realtotalpages = totalpages;
1573 if (zholes_size)
1574 for (i = 0; i < MAX_NR_ZONES; i++)
1575 realtotalpages -= zholes_size[i];
1576 pgdat->node_present_pages = realtotalpages;
1577 printk(KERN_DEBUG "On node %d totalpages: %lu\n", pgdat->node_id, realtotalpages);
1582 * Initially all pages are reserved - free ones are freed
1583 * up by free_all_bootmem() once the early boot process is
1584 * done. Non-atomic initialization, single-pass.
1586 void __init memmap_init_zone(unsigned long size, int nid, unsigned long zone,
1587 unsigned long start_pfn)
1589 struct page *start = pfn_to_page(start_pfn);
1590 struct page *page;
1592 for (page = start; page < (start + size); page++) {
1593 set_page_zone(page, NODEZONE(nid, zone));
1594 set_page_count(page, 0);
1595 reset_page_mapcount(page);
1596 SetPageReserved(page);
1597 INIT_LIST_HEAD(&page->lru);
1598 #ifdef WANT_PAGE_VIRTUAL
1599 /* The shift won't overflow because ZONE_NORMAL is below 4G. */
1600 if (!is_highmem_idx(zone))
1601 set_page_address(page, __va(start_pfn << PAGE_SHIFT));
1602 #endif
1603 start_pfn++;
1607 void zone_init_free_lists(struct pglist_data *pgdat, struct zone *zone,
1608 unsigned long size)
1610 int order;
1611 for (order = 0; order < MAX_ORDER ; order++) {
1612 INIT_LIST_HEAD(&zone->free_area[order].free_list);
1613 zone->free_area[order].nr_free = 0;
1617 #ifndef __HAVE_ARCH_MEMMAP_INIT
1618 #define memmap_init(size, nid, zone, start_pfn) \
1619 memmap_init_zone((size), (nid), (zone), (start_pfn))
1620 #endif
1623 * Set up the zone data structures:
1624 * - mark all pages reserved
1625 * - mark all memory queues empty
1626 * - clear the memory bitmaps
1628 static void __init free_area_init_core(struct pglist_data *pgdat,
1629 unsigned long *zones_size, unsigned long *zholes_size)
1631 unsigned long i, j;
1632 const unsigned long zone_required_alignment = 1UL << (MAX_ORDER-1);
1633 int cpu, nid = pgdat->node_id;
1634 unsigned long zone_start_pfn = pgdat->node_start_pfn;
1636 pgdat->nr_zones = 0;
1637 init_waitqueue_head(&pgdat->kswapd_wait);
1638 pgdat->kswapd_max_order = 0;
1640 for (j = 0; j < MAX_NR_ZONES; j++) {
1641 struct zone *zone = pgdat->node_zones + j;
1642 unsigned long size, realsize;
1643 unsigned long batch;
1645 zone_table[NODEZONE(nid, j)] = zone;
1646 realsize = size = zones_size[j];
1647 if (zholes_size)
1648 realsize -= zholes_size[j];
1650 if (j == ZONE_DMA || j == ZONE_NORMAL)
1651 nr_kernel_pages += realsize;
1652 nr_all_pages += realsize;
1654 zone->spanned_pages = size;
1655 zone->present_pages = realsize;
1656 zone->name = zone_names[j];
1657 spin_lock_init(&zone->lock);
1658 spin_lock_init(&zone->lru_lock);
1659 zone->zone_pgdat = pgdat;
1660 zone->free_pages = 0;
1662 zone->temp_priority = zone->prev_priority = DEF_PRIORITY;
1665 * The per-cpu-pages pools are set to around 1000th of the
1666 * size of the zone. But no more than 1/4 of a meg - there's
1667 * no point in going beyond the size of L2 cache.
1669 * OK, so we don't know how big the cache is. So guess.
1671 batch = zone->present_pages / 1024;
1672 if (batch * PAGE_SIZE > 256 * 1024)
1673 batch = (256 * 1024) / PAGE_SIZE;
1674 batch /= 4; /* We effectively *= 4 below */
1675 if (batch < 1)
1676 batch = 1;
1679 * Clamp the batch to a 2^n - 1 value. Having a power
1680 * of 2 value was found to be more likely to have
1681 * suboptimal cache aliasing properties in some cases.
1683 * For example if 2 tasks are alternately allocating
1684 * batches of pages, one task can end up with a lot
1685 * of pages of one half of the possible page colors
1686 * and the other with pages of the other colors.
1688 batch = (1 << fls(batch + batch/2)) - 1;
1690 for (cpu = 0; cpu < NR_CPUS; cpu++) {
1691 struct per_cpu_pages *pcp;
1693 pcp = &zone->pageset[cpu].pcp[0]; /* hot */
1694 pcp->count = 0;
1695 pcp->low = 2 * batch;
1696 pcp->high = 6 * batch;
1697 pcp->batch = 1 * batch;
1698 INIT_LIST_HEAD(&pcp->list);
1700 pcp = &zone->pageset[cpu].pcp[1]; /* cold */
1701 pcp->count = 0;
1702 pcp->low = 0;
1703 pcp->high = 2 * batch;
1704 pcp->batch = 1 * batch;
1705 INIT_LIST_HEAD(&pcp->list);
1707 printk(KERN_DEBUG " %s zone: %lu pages, LIFO batch:%lu\n",
1708 zone_names[j], realsize, batch);
1709 INIT_LIST_HEAD(&zone->active_list);
1710 INIT_LIST_HEAD(&zone->inactive_list);
1711 zone->nr_scan_active = 0;
1712 zone->nr_scan_inactive = 0;
1713 zone->nr_active = 0;
1714 zone->nr_inactive = 0;
1715 if (!size)
1716 continue;
1719 * The per-page waitqueue mechanism uses hashed waitqueues
1720 * per zone.
1722 zone->wait_table_size = wait_table_size(size);
1723 zone->wait_table_bits =
1724 wait_table_bits(zone->wait_table_size);
1725 zone->wait_table = (wait_queue_head_t *)
1726 alloc_bootmem_node(pgdat, zone->wait_table_size
1727 * sizeof(wait_queue_head_t));
1729 for(i = 0; i < zone->wait_table_size; ++i)
1730 init_waitqueue_head(zone->wait_table + i);
1732 pgdat->nr_zones = j+1;
1734 zone->zone_mem_map = pfn_to_page(zone_start_pfn);
1735 zone->zone_start_pfn = zone_start_pfn;
1737 if ((zone_start_pfn) & (zone_required_alignment-1))
1738 printk(KERN_CRIT "BUG: wrong zone alignment, it will crash\n");
1740 memmap_init(size, nid, j, zone_start_pfn);
1742 zone_start_pfn += size;
1744 zone_init_free_lists(pgdat, zone, zone->spanned_pages);
1748 static void __init alloc_node_mem_map(struct pglist_data *pgdat)
1750 unsigned long size;
1752 /* Skip empty nodes */
1753 if (!pgdat->node_spanned_pages)
1754 return;
1756 /* ia64 gets its own node_mem_map, before this, without bootmem */
1757 if (!pgdat->node_mem_map) {
1758 size = (pgdat->node_spanned_pages + 1) * sizeof(struct page);
1759 pgdat->node_mem_map = alloc_bootmem_node(pgdat, size);
1761 #ifndef CONFIG_DISCONTIGMEM
1763 * With no DISCONTIG, the global mem_map is just set as node 0's
1765 if (pgdat == NODE_DATA(0))
1766 mem_map = NODE_DATA(0)->node_mem_map;
1767 #endif
1770 void __init free_area_init_node(int nid, struct pglist_data *pgdat,
1771 unsigned long *zones_size, unsigned long node_start_pfn,
1772 unsigned long *zholes_size)
1774 pgdat->node_id = nid;
1775 pgdat->node_start_pfn = node_start_pfn;
1776 calculate_zone_totalpages(pgdat, zones_size, zholes_size);
1778 alloc_node_mem_map(pgdat);
1780 free_area_init_core(pgdat, zones_size, zholes_size);
1783 #ifndef CONFIG_DISCONTIGMEM
1784 static bootmem_data_t contig_bootmem_data;
1785 struct pglist_data contig_page_data = { .bdata = &contig_bootmem_data };
1787 EXPORT_SYMBOL(contig_page_data);
1789 void __init free_area_init(unsigned long *zones_size)
1791 free_area_init_node(0, &contig_page_data, zones_size,
1792 __pa(PAGE_OFFSET) >> PAGE_SHIFT, NULL);
1794 #endif
1796 #ifdef CONFIG_PROC_FS
1798 #include <linux/seq_file.h>
1800 static void *frag_start(struct seq_file *m, loff_t *pos)
1802 pg_data_t *pgdat;
1803 loff_t node = *pos;
1805 for (pgdat = pgdat_list; pgdat && node; pgdat = pgdat->pgdat_next)
1806 --node;
1808 return pgdat;
1811 static void *frag_next(struct seq_file *m, void *arg, loff_t *pos)
1813 pg_data_t *pgdat = (pg_data_t *)arg;
1815 (*pos)++;
1816 return pgdat->pgdat_next;
1819 static void frag_stop(struct seq_file *m, void *arg)
1824 * This walks the free areas for each zone.
1826 static int frag_show(struct seq_file *m, void *arg)
1828 pg_data_t *pgdat = (pg_data_t *)arg;
1829 struct zone *zone;
1830 struct zone *node_zones = pgdat->node_zones;
1831 unsigned long flags;
1832 int order;
1834 for (zone = node_zones; zone - node_zones < MAX_NR_ZONES; ++zone) {
1835 if (!zone->present_pages)
1836 continue;
1838 spin_lock_irqsave(&zone->lock, flags);
1839 seq_printf(m, "Node %d, zone %8s ", pgdat->node_id, zone->name);
1840 for (order = 0; order < MAX_ORDER; ++order)
1841 seq_printf(m, "%6lu ", zone->free_area[order].nr_free);
1842 spin_unlock_irqrestore(&zone->lock, flags);
1843 seq_putc(m, '\n');
1845 return 0;
1848 struct seq_operations fragmentation_op = {
1849 .start = frag_start,
1850 .next = frag_next,
1851 .stop = frag_stop,
1852 .show = frag_show,
1855 static char *vmstat_text[] = {
1856 "nr_dirty",
1857 "nr_writeback",
1858 "nr_unstable",
1859 "nr_page_table_pages",
1860 "nr_mapped",
1861 "nr_slab",
1863 "pgpgin",
1864 "pgpgout",
1865 "pswpin",
1866 "pswpout",
1867 "pgalloc_high",
1869 "pgalloc_normal",
1870 "pgalloc_dma",
1871 "pgfree",
1872 "pgactivate",
1873 "pgdeactivate",
1875 "pgfault",
1876 "pgmajfault",
1877 "pgrefill_high",
1878 "pgrefill_normal",
1879 "pgrefill_dma",
1881 "pgsteal_high",
1882 "pgsteal_normal",
1883 "pgsteal_dma",
1884 "pgscan_kswapd_high",
1885 "pgscan_kswapd_normal",
1887 "pgscan_kswapd_dma",
1888 "pgscan_direct_high",
1889 "pgscan_direct_normal",
1890 "pgscan_direct_dma",
1891 "pginodesteal",
1893 "slabs_scanned",
1894 "kswapd_steal",
1895 "kswapd_inodesteal",
1896 "pageoutrun",
1897 "allocstall",
1899 "pgrotated",
1902 static void *vmstat_start(struct seq_file *m, loff_t *pos)
1904 struct page_state *ps;
1906 if (*pos >= ARRAY_SIZE(vmstat_text))
1907 return NULL;
1909 ps = kmalloc(sizeof(*ps), GFP_KERNEL);
1910 m->private = ps;
1911 if (!ps)
1912 return ERR_PTR(-ENOMEM);
1913 get_full_page_state(ps);
1914 ps->pgpgin /= 2; /* sectors -> kbytes */
1915 ps->pgpgout /= 2;
1916 return (unsigned long *)ps + *pos;
1919 static void *vmstat_next(struct seq_file *m, void *arg, loff_t *pos)
1921 (*pos)++;
1922 if (*pos >= ARRAY_SIZE(vmstat_text))
1923 return NULL;
1924 return (unsigned long *)m->private + *pos;
1927 static int vmstat_show(struct seq_file *m, void *arg)
1929 unsigned long *l = arg;
1930 unsigned long off = l - (unsigned long *)m->private;
1932 seq_printf(m, "%s %lu\n", vmstat_text[off], *l);
1933 return 0;
1936 static void vmstat_stop(struct seq_file *m, void *arg)
1938 kfree(m->private);
1939 m->private = NULL;
1942 struct seq_operations vmstat_op = {
1943 .start = vmstat_start,
1944 .next = vmstat_next,
1945 .stop = vmstat_stop,
1946 .show = vmstat_show,
1949 #endif /* CONFIG_PROC_FS */
1951 #ifdef CONFIG_HOTPLUG_CPU
1952 static int page_alloc_cpu_notify(struct notifier_block *self,
1953 unsigned long action, void *hcpu)
1955 int cpu = (unsigned long)hcpu;
1956 long *count;
1957 unsigned long *src, *dest;
1959 if (action == CPU_DEAD) {
1960 int i;
1962 /* Drain local pagecache count. */
1963 count = &per_cpu(nr_pagecache_local, cpu);
1964 atomic_add(*count, &nr_pagecache);
1965 *count = 0;
1966 local_irq_disable();
1967 __drain_pages(cpu);
1969 /* Add dead cpu's page_states to our own. */
1970 dest = (unsigned long *)&__get_cpu_var(page_states);
1971 src = (unsigned long *)&per_cpu(page_states, cpu);
1973 for (i = 0; i < sizeof(struct page_state)/sizeof(unsigned long);
1974 i++) {
1975 dest[i] += src[i];
1976 src[i] = 0;
1979 local_irq_enable();
1981 return NOTIFY_OK;
1983 #endif /* CONFIG_HOTPLUG_CPU */
1985 void __init page_alloc_init(void)
1987 hotcpu_notifier(page_alloc_cpu_notify, 0);
1991 * setup_per_zone_lowmem_reserve - called whenever
1992 * sysctl_lower_zone_reserve_ratio changes. Ensures that each zone
1993 * has a correct pages reserved value, so an adequate number of
1994 * pages are left in the zone after a successful __alloc_pages().
1996 static void setup_per_zone_lowmem_reserve(void)
1998 struct pglist_data *pgdat;
1999 int j, idx;
2001 for_each_pgdat(pgdat) {
2002 for (j = 0; j < MAX_NR_ZONES; j++) {
2003 struct zone *zone = pgdat->node_zones + j;
2004 unsigned long present_pages = zone->present_pages;
2006 zone->lowmem_reserve[j] = 0;
2008 for (idx = j-1; idx >= 0; idx--) {
2009 struct zone *lower_zone;
2011 if (sysctl_lowmem_reserve_ratio[idx] < 1)
2012 sysctl_lowmem_reserve_ratio[idx] = 1;
2014 lower_zone = pgdat->node_zones + idx;
2015 lower_zone->lowmem_reserve[j] = present_pages /
2016 sysctl_lowmem_reserve_ratio[idx];
2017 present_pages += lower_zone->present_pages;
2024 * setup_per_zone_pages_min - called when min_free_kbytes changes. Ensures
2025 * that the pages_{min,low,high} values for each zone are set correctly
2026 * with respect to min_free_kbytes.
2028 static void setup_per_zone_pages_min(void)
2030 unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
2031 unsigned long lowmem_pages = 0;
2032 struct zone *zone;
2033 unsigned long flags;
2035 /* Calculate total number of !ZONE_HIGHMEM pages */
2036 for_each_zone(zone) {
2037 if (!is_highmem(zone))
2038 lowmem_pages += zone->present_pages;
2041 for_each_zone(zone) {
2042 spin_lock_irqsave(&zone->lru_lock, flags);
2043 if (is_highmem(zone)) {
2045 * Often, highmem doesn't need to reserve any pages.
2046 * But the pages_min/low/high values are also used for
2047 * batching up page reclaim activity so we need a
2048 * decent value here.
2050 int min_pages;
2052 min_pages = zone->present_pages / 1024;
2053 if (min_pages < SWAP_CLUSTER_MAX)
2054 min_pages = SWAP_CLUSTER_MAX;
2055 if (min_pages > 128)
2056 min_pages = 128;
2057 zone->pages_min = min_pages;
2058 } else {
2059 /* if it's a lowmem zone, reserve a number of pages
2060 * proportionate to the zone's size.
2062 zone->pages_min = (pages_min * zone->present_pages) /
2063 lowmem_pages;
2067 * When interpreting these watermarks, just keep in mind that:
2068 * zone->pages_min == (zone->pages_min * 4) / 4;
2070 zone->pages_low = (zone->pages_min * 5) / 4;
2071 zone->pages_high = (zone->pages_min * 6) / 4;
2072 spin_unlock_irqrestore(&zone->lru_lock, flags);
2077 * Initialise min_free_kbytes.
2079 * For small machines we want it small (128k min). For large machines
2080 * we want it large (64MB max). But it is not linear, because network
2081 * bandwidth does not increase linearly with machine size. We use
2083 * min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
2084 * min_free_kbytes = sqrt(lowmem_kbytes * 16)
2086 * which yields
2088 * 16MB: 512k
2089 * 32MB: 724k
2090 * 64MB: 1024k
2091 * 128MB: 1448k
2092 * 256MB: 2048k
2093 * 512MB: 2896k
2094 * 1024MB: 4096k
2095 * 2048MB: 5792k
2096 * 4096MB: 8192k
2097 * 8192MB: 11584k
2098 * 16384MB: 16384k
2100 static int __init init_per_zone_pages_min(void)
2102 unsigned long lowmem_kbytes;
2104 lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
2106 min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
2107 if (min_free_kbytes < 128)
2108 min_free_kbytes = 128;
2109 if (min_free_kbytes > 65536)
2110 min_free_kbytes = 65536;
2111 setup_per_zone_pages_min();
2112 setup_per_zone_lowmem_reserve();
2113 return 0;
2115 module_init(init_per_zone_pages_min)
2118 * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
2119 * that we can call two helper functions whenever min_free_kbytes
2120 * changes.
2122 int min_free_kbytes_sysctl_handler(ctl_table *table, int write,
2123 struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
2125 proc_dointvec(table, write, file, buffer, length, ppos);
2126 setup_per_zone_pages_min();
2127 return 0;
2131 * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
2132 * proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
2133 * whenever sysctl_lowmem_reserve_ratio changes.
2135 * The reserve ratio obviously has absolutely no relation with the
2136 * pages_min watermarks. The lowmem reserve ratio can only make sense
2137 * if in function of the boot time zone sizes.
2139 int lowmem_reserve_ratio_sysctl_handler(ctl_table *table, int write,
2140 struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
2142 proc_dointvec_minmax(table, write, file, buffer, length, ppos);
2143 setup_per_zone_lowmem_reserve();
2144 return 0;
2147 __initdata int hashdist = HASHDIST_DEFAULT;
2149 #ifdef CONFIG_NUMA
2150 static int __init set_hashdist(char *str)
2152 if (!str)
2153 return 0;
2154 hashdist = simple_strtoul(str, &str, 0);
2155 return 1;
2157 __setup("hashdist=", set_hashdist);
2158 #endif
2161 * allocate a large system hash table from bootmem
2162 * - it is assumed that the hash table must contain an exact power-of-2
2163 * quantity of entries
2164 * - limit is the number of hash buckets, not the total allocation size
2166 void *__init alloc_large_system_hash(const char *tablename,
2167 unsigned long bucketsize,
2168 unsigned long numentries,
2169 int scale,
2170 int flags,
2171 unsigned int *_hash_shift,
2172 unsigned int *_hash_mask,
2173 unsigned long limit)
2175 unsigned long long max = limit;
2176 unsigned long log2qty, size;
2177 void *table = NULL;
2179 /* allow the kernel cmdline to have a say */
2180 if (!numentries) {
2181 /* round applicable memory size up to nearest megabyte */
2182 numentries = (flags & HASH_HIGHMEM) ? nr_all_pages : nr_kernel_pages;
2183 numentries += (1UL << (20 - PAGE_SHIFT)) - 1;
2184 numentries >>= 20 - PAGE_SHIFT;
2185 numentries <<= 20 - PAGE_SHIFT;
2187 /* limit to 1 bucket per 2^scale bytes of low memory */
2188 if (scale > PAGE_SHIFT)
2189 numentries >>= (scale - PAGE_SHIFT);
2190 else
2191 numentries <<= (PAGE_SHIFT - scale);
2193 /* rounded up to nearest power of 2 in size */
2194 numentries = 1UL << (long_log2(numentries) + 1);
2196 /* limit allocation size to 1/16 total memory by default */
2197 if (max == 0) {
2198 max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
2199 do_div(max, bucketsize);
2202 if (numentries > max)
2203 numentries = max;
2205 log2qty = long_log2(numentries);
2207 do {
2208 size = bucketsize << log2qty;
2209 if (flags & HASH_EARLY)
2210 table = alloc_bootmem(size);
2211 else if (hashdist)
2212 table = __vmalloc(size, GFP_ATOMIC, PAGE_KERNEL);
2213 else {
2214 unsigned long order;
2215 for (order = 0; ((1UL << order) << PAGE_SHIFT) < size; order++)
2217 table = (void*) __get_free_pages(GFP_ATOMIC, order);
2219 } while (!table && size > PAGE_SIZE && --log2qty);
2221 if (!table)
2222 panic("Failed to allocate %s hash table\n", tablename);
2224 printk("%s hash table entries: %d (order: %d, %lu bytes)\n",
2225 tablename,
2226 (1U << log2qty),
2227 long_log2(size) - PAGE_SHIFT,
2228 size);
2230 if (_hash_shift)
2231 *_hash_shift = log2qty;
2232 if (_hash_mask)
2233 *_hash_mask = (1 << log2qty) - 1;
2235 return table;