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/stddef.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>
45 #include <asm/tlbflush.h>
46 #include <asm/div64.h>
50 * Array of node states.
52 nodemask_t node_states[NR_NODE_STATES] __read_mostly = {
53 [N_POSSIBLE] = NODE_MASK_ALL,
54 [N_ONLINE] = { { [0] = 1UL } },
56 [N_NORMAL_MEMORY] = { { [0] = 1UL } },
58 [N_HIGH_MEMORY] = { { [0] = 1UL } },
60 [N_CPU] = { { [0] = 1UL } },
63 EXPORT_SYMBOL(node_states);
65 unsigned long totalram_pages __read_mostly;
66 unsigned long totalreserve_pages __read_mostly;
68 int percpu_pagelist_fraction;
70 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
71 int pageblock_order __read_mostly;
74 static void __free_pages_ok(struct page *page, unsigned int order);
77 * results with 256, 32 in the lowmem_reserve sysctl:
78 * 1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
79 * 1G machine -> (16M dma, 784M normal, 224M high)
80 * NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
81 * HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
82 * HIGHMEM allocation will (224M+784M)/256 of ram reserved in ZONE_DMA
84 * TBD: should special case ZONE_DMA32 machines here - in those we normally
85 * don't need any ZONE_NORMAL reservation
87 int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES-1] = {
88 #ifdef CONFIG_ZONE_DMA
91 #ifdef CONFIG_ZONE_DMA32
100 EXPORT_SYMBOL(totalram_pages);
102 static char * const zone_names[MAX_NR_ZONES] = {
103 #ifdef CONFIG_ZONE_DMA
106 #ifdef CONFIG_ZONE_DMA32
110 #ifdef CONFIG_HIGHMEM
116 int min_free_kbytes = 1024;
118 unsigned long __meminitdata nr_kernel_pages;
119 unsigned long __meminitdata nr_all_pages;
120 static unsigned long __meminitdata dma_reserve;
122 #ifdef CONFIG_ARCH_POPULATES_NODE_MAP
124 * MAX_ACTIVE_REGIONS determines the maxmimum number of distinct
125 * ranges of memory (RAM) that may be registered with add_active_range().
126 * Ranges passed to add_active_range() will be merged if possible
127 * so the number of times add_active_range() can be called is
128 * related to the number of nodes and the number of holes
130 #ifdef CONFIG_MAX_ACTIVE_REGIONS
131 /* Allow an architecture to set MAX_ACTIVE_REGIONS to save memory */
132 #define MAX_ACTIVE_REGIONS CONFIG_MAX_ACTIVE_REGIONS
134 #if MAX_NUMNODES >= 32
135 /* If there can be many nodes, allow up to 50 holes per node */
136 #define MAX_ACTIVE_REGIONS (MAX_NUMNODES*50)
138 /* By default, allow up to 256 distinct regions */
139 #define MAX_ACTIVE_REGIONS 256
143 static struct node_active_region __meminitdata early_node_map[MAX_ACTIVE_REGIONS];
144 static int __meminitdata nr_nodemap_entries;
145 static unsigned long __meminitdata arch_zone_lowest_possible_pfn[MAX_NR_ZONES];
146 static unsigned long __meminitdata arch_zone_highest_possible_pfn[MAX_NR_ZONES];
147 #ifdef CONFIG_MEMORY_HOTPLUG_RESERVE
148 static unsigned long __meminitdata node_boundary_start_pfn[MAX_NUMNODES];
149 static unsigned long __meminitdata node_boundary_end_pfn[MAX_NUMNODES];
150 #endif /* CONFIG_MEMORY_HOTPLUG_RESERVE */
151 unsigned long __initdata required_kernelcore;
152 unsigned long __initdata required_movablecore;
153 unsigned long __meminitdata zone_movable_pfn[MAX_NUMNODES];
155 /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
157 EXPORT_SYMBOL(movable_zone);
158 #endif /* CONFIG_ARCH_POPULATES_NODE_MAP */
161 int nr_node_ids __read_mostly = MAX_NUMNODES;
162 EXPORT_SYMBOL(nr_node_ids);
165 int page_group_by_mobility_disabled __read_mostly;
167 static inline int get_pageblock_migratetype(struct page *page)
169 if (unlikely(page_group_by_mobility_disabled))
170 return MIGRATE_UNMOVABLE;
172 return get_pageblock_flags_group(page, PB_migrate, PB_migrate_end);
175 static void set_pageblock_migratetype(struct page *page, int migratetype)
177 set_pageblock_flags_group(page, (unsigned long)migratetype,
178 PB_migrate, PB_migrate_end);
181 static inline int allocflags_to_migratetype(gfp_t gfp_flags)
183 WARN_ON((gfp_flags & GFP_MOVABLE_MASK) == GFP_MOVABLE_MASK);
185 if (unlikely(page_group_by_mobility_disabled))
186 return MIGRATE_UNMOVABLE;
188 /* Cluster based on mobility */
189 return (((gfp_flags & __GFP_MOVABLE) != 0) << 1) |
190 ((gfp_flags & __GFP_RECLAIMABLE) != 0);
193 #ifdef CONFIG_DEBUG_VM
194 static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
198 unsigned long pfn = page_to_pfn(page);
201 seq = zone_span_seqbegin(zone);
202 if (pfn >= zone->zone_start_pfn + zone->spanned_pages)
204 else if (pfn < zone->zone_start_pfn)
206 } while (zone_span_seqretry(zone, seq));
211 static int page_is_consistent(struct zone *zone, struct page *page)
213 if (!pfn_valid_within(page_to_pfn(page)))
215 if (zone != page_zone(page))
221 * Temporary debugging check for pages not lying within a given zone.
223 static int bad_range(struct zone *zone, struct page *page)
225 if (page_outside_zone_boundaries(zone, page))
227 if (!page_is_consistent(zone, page))
233 static inline int bad_range(struct zone *zone, struct page *page)
239 static void bad_page(struct page *page)
241 printk(KERN_EMERG "Bad page state in process '%s'\n"
242 KERN_EMERG "page:%p flags:0x%0*lx mapping:%p mapcount:%d count:%d\n"
243 KERN_EMERG "Trying to fix it up, but a reboot is needed\n"
244 KERN_EMERG "Backtrace:\n",
245 current->comm, page, (int)(2*sizeof(unsigned long)),
246 (unsigned long)page->flags, page->mapping,
247 page_mapcount(page), page_count(page));
249 page->flags &= ~(1 << PG_lru |
259 set_page_count(page, 0);
260 reset_page_mapcount(page);
261 page->mapping = NULL;
262 add_taint(TAINT_BAD_PAGE);
266 * Higher-order pages are called "compound pages". They are structured thusly:
268 * The first PAGE_SIZE page is called the "head page".
270 * The remaining PAGE_SIZE pages are called "tail pages".
272 * All pages have PG_compound set. All pages have their ->private pointing at
273 * the head page (even the head page has this).
275 * The first tail page's ->lru.next holds the address of the compound page's
276 * put_page() function. Its ->lru.prev holds the order of allocation.
277 * This usage means that zero-order pages may not be compound.
280 static void free_compound_page(struct page *page)
282 __free_pages_ok(page, compound_order(page));
285 static void prep_compound_page(struct page *page, unsigned long order)
288 int nr_pages = 1 << order;
290 set_compound_page_dtor(page, free_compound_page);
291 set_compound_order(page, order);
293 for (i = 1; i < nr_pages; i++) {
294 struct page *p = page + i;
297 p->first_page = page;
301 static void destroy_compound_page(struct page *page, unsigned long order)
304 int nr_pages = 1 << order;
306 if (unlikely(compound_order(page) != order))
309 if (unlikely(!PageHead(page)))
311 __ClearPageHead(page);
312 for (i = 1; i < nr_pages; i++) {
313 struct page *p = page + i;
315 if (unlikely(!PageTail(p) |
316 (p->first_page != page)))
322 static inline void prep_zero_page(struct page *page, int order, gfp_t gfp_flags)
326 VM_BUG_ON((gfp_flags & (__GFP_WAIT | __GFP_HIGHMEM)) == __GFP_HIGHMEM);
328 * clear_highpage() will use KM_USER0, so it's a bug to use __GFP_ZERO
329 * and __GFP_HIGHMEM from hard or soft interrupt context.
331 VM_BUG_ON((gfp_flags & __GFP_HIGHMEM) && in_interrupt());
332 for (i = 0; i < (1 << order); i++)
333 clear_highpage(page + i);
337 * function for dealing with page's order in buddy system.
338 * zone->lock is already acquired when we use these.
339 * So, we don't need atomic page->flags operations here.
341 static inline unsigned long page_order(struct page *page)
343 return page_private(page);
346 static inline void set_page_order(struct page *page, int order)
348 set_page_private(page, order);
349 __SetPageBuddy(page);
352 static inline void rmv_page_order(struct page *page)
354 __ClearPageBuddy(page);
355 set_page_private(page, 0);
359 * Locate the struct page for both the matching buddy in our
360 * pair (buddy1) and the combined O(n+1) page they form (page).
362 * 1) Any buddy B1 will have an order O twin B2 which satisfies
363 * the following equation:
365 * For example, if the starting buddy (buddy2) is #8 its order
367 * B2 = 8 ^ (1 << 1) = 8 ^ 2 = 10
369 * 2) Any buddy B will have an order O+1 parent P which
370 * satisfies the following equation:
373 * Assumption: *_mem_map is contiguous at least up to MAX_ORDER
375 static inline struct page *
376 __page_find_buddy(struct page *page, unsigned long page_idx, unsigned int order)
378 unsigned long buddy_idx = page_idx ^ (1 << order);
380 return page + (buddy_idx - page_idx);
383 static inline unsigned long
384 __find_combined_index(unsigned long page_idx, unsigned int order)
386 return (page_idx & ~(1 << order));
390 * This function checks whether a page is free && is the buddy
391 * we can do coalesce a page and its buddy if
392 * (a) the buddy is not in a hole &&
393 * (b) the buddy is in the buddy system &&
394 * (c) a page and its buddy have the same order &&
395 * (d) a page and its buddy are in the same zone.
397 * For recording whether a page is in the buddy system, we use PG_buddy.
398 * Setting, clearing, and testing PG_buddy is serialized by zone->lock.
400 * For recording page's order, we use page_private(page).
402 static inline int page_is_buddy(struct page *page, struct page *buddy,
405 if (!pfn_valid_within(page_to_pfn(buddy)))
408 if (page_zone_id(page) != page_zone_id(buddy))
411 if (PageBuddy(buddy) && page_order(buddy) == order) {
412 BUG_ON(page_count(buddy) != 0);
419 * Freeing function for a buddy system allocator.
421 * The concept of a buddy system is to maintain direct-mapped table
422 * (containing bit values) for memory blocks of various "orders".
423 * The bottom level table contains the map for the smallest allocatable
424 * units of memory (here, pages), and each level above it describes
425 * pairs of units from the levels below, hence, "buddies".
426 * At a high level, all that happens here is marking the table entry
427 * at the bottom level available, and propagating the changes upward
428 * as necessary, plus some accounting needed to play nicely with other
429 * parts of the VM system.
430 * At each level, we keep a list of pages, which are heads of continuous
431 * free pages of length of (1 << order) and marked with PG_buddy. Page's
432 * order is recorded in page_private(page) field.
433 * So when we are allocating or freeing one, we can derive the state of the
434 * other. That is, if we allocate a small block, and both were
435 * free, the remainder of the region must be split into blocks.
436 * If a block is freed, and its buddy is also free, then this
437 * triggers coalescing into a block of larger size.
442 static inline void __free_one_page(struct page *page,
443 struct zone *zone, unsigned int order)
445 unsigned long page_idx;
446 int order_size = 1 << order;
447 int migratetype = get_pageblock_migratetype(page);
449 if (unlikely(PageCompound(page)))
450 destroy_compound_page(page, order);
452 page_idx = page_to_pfn(page) & ((1 << MAX_ORDER) - 1);
454 VM_BUG_ON(page_idx & (order_size - 1));
455 VM_BUG_ON(bad_range(zone, page));
457 __mod_zone_page_state(zone, NR_FREE_PAGES, order_size);
458 while (order < MAX_ORDER-1) {
459 unsigned long combined_idx;
462 buddy = __page_find_buddy(page, page_idx, order);
463 if (!page_is_buddy(page, buddy, order))
464 break; /* Move the buddy up one level. */
466 list_del(&buddy->lru);
467 zone->free_area[order].nr_free--;
468 rmv_page_order(buddy);
469 combined_idx = __find_combined_index(page_idx, order);
470 page = page + (combined_idx - page_idx);
471 page_idx = combined_idx;
474 set_page_order(page, order);
476 &zone->free_area[order].free_list[migratetype]);
477 zone->free_area[order].nr_free++;
480 static inline int free_pages_check(struct page *page)
482 if (unlikely(page_mapcount(page) |
483 (page->mapping != NULL) |
484 (page_count(page) != 0) |
497 __ClearPageDirty(page);
499 * For now, we report if PG_reserved was found set, but do not
500 * clear it, and do not free the page. But we shall soon need
501 * to do more, for when the ZERO_PAGE count wraps negative.
503 return PageReserved(page);
507 * Frees a list of pages.
508 * Assumes all pages on list are in same zone, and of same order.
509 * count is the number of pages to free.
511 * If the zone was previously in an "all pages pinned" state then look to
512 * see if this freeing clears that state.
514 * And clear the zone's pages_scanned counter, to hold off the "all pages are
515 * pinned" detection logic.
517 static void free_pages_bulk(struct zone *zone, int count,
518 struct list_head *list, int order)
520 spin_lock(&zone->lock);
521 zone->all_unreclaimable = 0;
522 zone->pages_scanned = 0;
526 VM_BUG_ON(list_empty(list));
527 page = list_entry(list->prev, struct page, lru);
528 /* have to delete it as __free_one_page list manipulates */
529 list_del(&page->lru);
530 __free_one_page(page, zone, order);
532 spin_unlock(&zone->lock);
535 static void free_one_page(struct zone *zone, struct page *page, int order)
537 spin_lock(&zone->lock);
538 zone->all_unreclaimable = 0;
539 zone->pages_scanned = 0;
540 __free_one_page(page, zone, order);
541 spin_unlock(&zone->lock);
544 static void __free_pages_ok(struct page *page, unsigned int order)
550 for (i = 0 ; i < (1 << order) ; ++i)
551 reserved += free_pages_check(page + i);
555 if (!PageHighMem(page))
556 debug_check_no_locks_freed(page_address(page),PAGE_SIZE<<order);
557 arch_free_page(page, order);
558 kernel_map_pages(page, 1 << order, 0);
560 local_irq_save(flags);
561 __count_vm_events(PGFREE, 1 << order);
562 free_one_page(page_zone(page), page, order);
563 local_irq_restore(flags);
567 * permit the bootmem allocator to evade page validation on high-order frees
569 void fastcall __init __free_pages_bootmem(struct page *page, unsigned int order)
572 __ClearPageReserved(page);
573 set_page_count(page, 0);
574 set_page_refcounted(page);
580 for (loop = 0; loop < BITS_PER_LONG; loop++) {
581 struct page *p = &page[loop];
583 if (loop + 1 < BITS_PER_LONG)
585 __ClearPageReserved(p);
586 set_page_count(p, 0);
589 set_page_refcounted(page);
590 __free_pages(page, order);
596 * The order of subdivision here is critical for the IO subsystem.
597 * Please do not alter this order without good reasons and regression
598 * testing. Specifically, as large blocks of memory are subdivided,
599 * the order in which smaller blocks are delivered depends on the order
600 * they're subdivided in this function. This is the primary factor
601 * influencing the order in which pages are delivered to the IO
602 * subsystem according to empirical testing, and this is also justified
603 * by considering the behavior of a buddy system containing a single
604 * large block of memory acted on by a series of small allocations.
605 * This behavior is a critical factor in sglist merging's success.
609 static inline void expand(struct zone *zone, struct page *page,
610 int low, int high, struct free_area *area,
613 unsigned long size = 1 << high;
619 VM_BUG_ON(bad_range(zone, &page[size]));
620 list_add(&page[size].lru, &area->free_list[migratetype]);
622 set_page_order(&page[size], high);
627 * This page is about to be returned from the page allocator
629 static int prep_new_page(struct page *page, int order, gfp_t gfp_flags)
631 if (unlikely(page_mapcount(page) |
632 (page->mapping != NULL) |
633 (page_count(page) != 0) |
648 * For now, we report if PG_reserved was found set, but do not
649 * clear it, and do not allocate the page: as a safety net.
651 if (PageReserved(page))
654 page->flags &= ~(1 << PG_uptodate | 1 << PG_error | 1 << PG_readahead |
655 1 << PG_referenced | 1 << PG_arch_1 |
656 1 << PG_owner_priv_1 | 1 << PG_mappedtodisk);
657 set_page_private(page, 0);
658 set_page_refcounted(page);
660 arch_alloc_page(page, order);
661 kernel_map_pages(page, 1 << order, 1);
663 if (gfp_flags & __GFP_ZERO)
664 prep_zero_page(page, order, gfp_flags);
666 if (order && (gfp_flags & __GFP_COMP))
667 prep_compound_page(page, order);
673 * Go through the free lists for the given migratetype and remove
674 * the smallest available page from the freelists
676 static struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
679 unsigned int current_order;
680 struct free_area * area;
683 /* Find a page of the appropriate size in the preferred list */
684 for (current_order = order; current_order < MAX_ORDER; ++current_order) {
685 area = &(zone->free_area[current_order]);
686 if (list_empty(&area->free_list[migratetype]))
689 page = list_entry(area->free_list[migratetype].next,
691 list_del(&page->lru);
692 rmv_page_order(page);
694 __mod_zone_page_state(zone, NR_FREE_PAGES, - (1UL << order));
695 expand(zone, page, order, current_order, area, migratetype);
704 * This array describes the order lists are fallen back to when
705 * the free lists for the desirable migrate type are depleted
707 static int fallbacks[MIGRATE_TYPES][MIGRATE_TYPES-1] = {
708 [MIGRATE_UNMOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE, MIGRATE_RESERVE },
709 [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE, MIGRATE_MOVABLE, MIGRATE_RESERVE },
710 [MIGRATE_MOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_RESERVE },
711 [MIGRATE_RESERVE] = { MIGRATE_RESERVE, MIGRATE_RESERVE, MIGRATE_RESERVE }, /* Never used */
715 * Move the free pages in a range to the free lists of the requested type.
716 * Note that start_page and end_pages are not aligned on a pageblock
717 * boundary. If alignment is required, use move_freepages_block()
719 int move_freepages(struct zone *zone,
720 struct page *start_page, struct page *end_page,
727 #ifndef CONFIG_HOLES_IN_ZONE
729 * page_zone is not safe to call in this context when
730 * CONFIG_HOLES_IN_ZONE is set. This bug check is probably redundant
731 * anyway as we check zone boundaries in move_freepages_block().
732 * Remove at a later date when no bug reports exist related to
733 * grouping pages by mobility
735 BUG_ON(page_zone(start_page) != page_zone(end_page));
738 for (page = start_page; page <= end_page;) {
739 if (!pfn_valid_within(page_to_pfn(page))) {
744 if (!PageBuddy(page)) {
749 order = page_order(page);
750 list_del(&page->lru);
752 &zone->free_area[order].free_list[migratetype]);
754 pages_moved += 1 << order;
760 int move_freepages_block(struct zone *zone, struct page *page, int migratetype)
762 unsigned long start_pfn, end_pfn;
763 struct page *start_page, *end_page;
765 start_pfn = page_to_pfn(page);
766 start_pfn = start_pfn & ~(pageblock_nr_pages-1);
767 start_page = pfn_to_page(start_pfn);
768 end_page = start_page + pageblock_nr_pages - 1;
769 end_pfn = start_pfn + pageblock_nr_pages - 1;
771 /* Do not cross zone boundaries */
772 if (start_pfn < zone->zone_start_pfn)
774 if (end_pfn >= zone->zone_start_pfn + zone->spanned_pages)
777 return move_freepages(zone, start_page, end_page, migratetype);
780 /* Return the page with the lowest PFN in the list */
781 static struct page *min_page(struct list_head *list)
783 unsigned long min_pfn = -1UL;
784 struct page *min_page = NULL, *page;;
786 list_for_each_entry(page, list, lru) {
787 unsigned long pfn = page_to_pfn(page);
797 /* Remove an element from the buddy allocator from the fallback list */
798 static struct page *__rmqueue_fallback(struct zone *zone, int order,
799 int start_migratetype)
801 struct free_area * area;
806 /* Find the largest possible block of pages in the other list */
807 for (current_order = MAX_ORDER-1; current_order >= order;
809 for (i = 0; i < MIGRATE_TYPES - 1; i++) {
810 migratetype = fallbacks[start_migratetype][i];
812 /* MIGRATE_RESERVE handled later if necessary */
813 if (migratetype == MIGRATE_RESERVE)
816 area = &(zone->free_area[current_order]);
817 if (list_empty(&area->free_list[migratetype]))
820 /* Bias kernel allocations towards low pfns */
821 page = list_entry(area->free_list[migratetype].next,
823 if (unlikely(start_migratetype != MIGRATE_MOVABLE))
824 page = min_page(&area->free_list[migratetype]);
828 * If breaking a large block of pages, move all free
829 * pages to the preferred allocation list. If falling
830 * back for a reclaimable kernel allocation, be more
831 * agressive about taking ownership of free pages
833 if (unlikely(current_order >= (pageblock_order >> 1)) ||
834 start_migratetype == MIGRATE_RECLAIMABLE) {
836 pages = move_freepages_block(zone, page,
839 /* Claim the whole block if over half of it is free */
840 if (pages >= (1 << (pageblock_order-1)))
841 set_pageblock_migratetype(page,
844 migratetype = start_migratetype;
847 /* Remove the page from the freelists */
848 list_del(&page->lru);
849 rmv_page_order(page);
850 __mod_zone_page_state(zone, NR_FREE_PAGES,
853 if (current_order == pageblock_order)
854 set_pageblock_migratetype(page,
857 expand(zone, page, order, current_order, area, migratetype);
862 /* Use MIGRATE_RESERVE rather than fail an allocation */
863 return __rmqueue_smallest(zone, order, MIGRATE_RESERVE);
867 * Do the hard work of removing an element from the buddy allocator.
868 * Call me with the zone->lock already held.
870 static struct page *__rmqueue(struct zone *zone, unsigned int order,
875 page = __rmqueue_smallest(zone, order, migratetype);
878 page = __rmqueue_fallback(zone, order, migratetype);
884 * Obtain a specified number of elements from the buddy allocator, all under
885 * a single hold of the lock, for efficiency. Add them to the supplied list.
886 * Returns the number of new pages which were placed at *list.
888 static int rmqueue_bulk(struct zone *zone, unsigned int order,
889 unsigned long count, struct list_head *list,
894 spin_lock(&zone->lock);
895 for (i = 0; i < count; ++i) {
896 struct page *page = __rmqueue(zone, order, migratetype);
897 if (unlikely(page == NULL))
899 list_add(&page->lru, list);
900 set_page_private(page, migratetype);
902 spin_unlock(&zone->lock);
908 * Called from the vmstat counter updater to drain pagesets of this
909 * currently executing processor on remote nodes after they have
912 * Note that this function must be called with the thread pinned to
913 * a single processor.
915 void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp)
920 local_irq_save(flags);
921 if (pcp->count >= pcp->batch)
922 to_drain = pcp->batch;
924 to_drain = pcp->count;
925 free_pages_bulk(zone, to_drain, &pcp->list, 0);
926 pcp->count -= to_drain;
927 local_irq_restore(flags);
931 static void __drain_pages(unsigned int cpu)
937 for_each_zone(zone) {
938 struct per_cpu_pageset *pset;
940 if (!populated_zone(zone))
943 pset = zone_pcp(zone, cpu);
944 for (i = 0; i < ARRAY_SIZE(pset->pcp); i++) {
945 struct per_cpu_pages *pcp;
948 local_irq_save(flags);
949 free_pages_bulk(zone, pcp->count, &pcp->list, 0);
951 local_irq_restore(flags);
956 #ifdef CONFIG_HIBERNATION
958 void mark_free_pages(struct zone *zone)
960 unsigned long pfn, max_zone_pfn;
963 struct list_head *curr;
965 if (!zone->spanned_pages)
968 spin_lock_irqsave(&zone->lock, flags);
970 max_zone_pfn = zone->zone_start_pfn + zone->spanned_pages;
971 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
972 if (pfn_valid(pfn)) {
973 struct page *page = pfn_to_page(pfn);
975 if (!swsusp_page_is_forbidden(page))
976 swsusp_unset_page_free(page);
979 for_each_migratetype_order(order, t) {
980 list_for_each(curr, &zone->free_area[order].free_list[t]) {
983 pfn = page_to_pfn(list_entry(curr, struct page, lru));
984 for (i = 0; i < (1UL << order); i++)
985 swsusp_set_page_free(pfn_to_page(pfn + i));
988 spin_unlock_irqrestore(&zone->lock, flags);
990 #endif /* CONFIG_PM */
993 * Spill all of this CPU's per-cpu pages back into the buddy allocator.
995 void drain_local_pages(void)
999 local_irq_save(flags);
1000 __drain_pages(smp_processor_id());
1001 local_irq_restore(flags);
1004 void smp_drain_local_pages(void *arg)
1006 drain_local_pages();
1010 * Spill all the per-cpu pages from all CPUs back into the buddy allocator
1012 void drain_all_local_pages(void)
1014 unsigned long flags;
1016 local_irq_save(flags);
1017 __drain_pages(smp_processor_id());
1018 local_irq_restore(flags);
1020 smp_call_function(smp_drain_local_pages, NULL, 0, 1);
1024 * Free a 0-order page
1026 static void fastcall free_hot_cold_page(struct page *page, int cold)
1028 struct zone *zone = page_zone(page);
1029 struct per_cpu_pages *pcp;
1030 unsigned long flags;
1033 page->mapping = NULL;
1034 if (free_pages_check(page))
1037 if (!PageHighMem(page))
1038 debug_check_no_locks_freed(page_address(page), PAGE_SIZE);
1039 arch_free_page(page, 0);
1040 kernel_map_pages(page, 1, 0);
1042 pcp = &zone_pcp(zone, get_cpu())->pcp[cold];
1043 local_irq_save(flags);
1044 __count_vm_event(PGFREE);
1045 list_add(&page->lru, &pcp->list);
1046 set_page_private(page, get_pageblock_migratetype(page));
1048 if (pcp->count >= pcp->high) {
1049 free_pages_bulk(zone, pcp->batch, &pcp->list, 0);
1050 pcp->count -= pcp->batch;
1052 local_irq_restore(flags);
1056 void fastcall free_hot_page(struct page *page)
1058 free_hot_cold_page(page, 0);
1061 void fastcall free_cold_page(struct page *page)
1063 free_hot_cold_page(page, 1);
1067 * split_page takes a non-compound higher-order page, and splits it into
1068 * n (1<<order) sub-pages: page[0..n]
1069 * Each sub-page must be freed individually.
1071 * Note: this is probably too low level an operation for use in drivers.
1072 * Please consult with lkml before using this in your driver.
1074 void split_page(struct page *page, unsigned int order)
1078 VM_BUG_ON(PageCompound(page));
1079 VM_BUG_ON(!page_count(page));
1080 for (i = 1; i < (1 << order); i++)
1081 set_page_refcounted(page + i);
1085 * Really, prep_compound_page() should be called from __rmqueue_bulk(). But
1086 * we cheat by calling it from here, in the order > 0 path. Saves a branch
1089 static struct page *buffered_rmqueue(struct zonelist *zonelist,
1090 struct zone *zone, int order, gfp_t gfp_flags)
1092 unsigned long flags;
1094 int cold = !!(gfp_flags & __GFP_COLD);
1096 int migratetype = allocflags_to_migratetype(gfp_flags);
1100 if (likely(order == 0)) {
1101 struct per_cpu_pages *pcp;
1103 pcp = &zone_pcp(zone, cpu)->pcp[cold];
1104 local_irq_save(flags);
1106 pcp->count = rmqueue_bulk(zone, 0,
1107 pcp->batch, &pcp->list, migratetype);
1108 if (unlikely(!pcp->count))
1112 /* Find a page of the appropriate migrate type */
1113 list_for_each_entry(page, &pcp->list, lru)
1114 if (page_private(page) == migratetype)
1117 /* Allocate more to the pcp list if necessary */
1118 if (unlikely(&page->lru == &pcp->list)) {
1119 pcp->count += rmqueue_bulk(zone, 0,
1120 pcp->batch, &pcp->list, migratetype);
1121 page = list_entry(pcp->list.next, struct page, lru);
1124 list_del(&page->lru);
1127 spin_lock_irqsave(&zone->lock, flags);
1128 page = __rmqueue(zone, order, migratetype);
1129 spin_unlock(&zone->lock);
1134 __count_zone_vm_events(PGALLOC, zone, 1 << order);
1135 zone_statistics(zonelist, zone);
1136 local_irq_restore(flags);
1139 VM_BUG_ON(bad_range(zone, page));
1140 if (prep_new_page(page, order, gfp_flags))
1145 local_irq_restore(flags);
1150 #define ALLOC_NO_WATERMARKS 0x01 /* don't check watermarks at all */
1151 #define ALLOC_WMARK_MIN 0x02 /* use pages_min watermark */
1152 #define ALLOC_WMARK_LOW 0x04 /* use pages_low watermark */
1153 #define ALLOC_WMARK_HIGH 0x08 /* use pages_high watermark */
1154 #define ALLOC_HARDER 0x10 /* try to alloc harder */
1155 #define ALLOC_HIGH 0x20 /* __GFP_HIGH set */
1156 #define ALLOC_CPUSET 0x40 /* check for correct cpuset */
1158 #ifdef CONFIG_FAIL_PAGE_ALLOC
1160 static struct fail_page_alloc_attr {
1161 struct fault_attr attr;
1163 u32 ignore_gfp_highmem;
1164 u32 ignore_gfp_wait;
1167 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
1169 struct dentry *ignore_gfp_highmem_file;
1170 struct dentry *ignore_gfp_wait_file;
1171 struct dentry *min_order_file;
1173 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
1175 } fail_page_alloc = {
1176 .attr = FAULT_ATTR_INITIALIZER,
1177 .ignore_gfp_wait = 1,
1178 .ignore_gfp_highmem = 1,
1182 static int __init setup_fail_page_alloc(char *str)
1184 return setup_fault_attr(&fail_page_alloc.attr, str);
1186 __setup("fail_page_alloc=", setup_fail_page_alloc);
1188 static int should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
1190 if (order < fail_page_alloc.min_order)
1192 if (gfp_mask & __GFP_NOFAIL)
1194 if (fail_page_alloc.ignore_gfp_highmem && (gfp_mask & __GFP_HIGHMEM))
1196 if (fail_page_alloc.ignore_gfp_wait && (gfp_mask & __GFP_WAIT))
1199 return should_fail(&fail_page_alloc.attr, 1 << order);
1202 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
1204 static int __init fail_page_alloc_debugfs(void)
1206 mode_t mode = S_IFREG | S_IRUSR | S_IWUSR;
1210 err = init_fault_attr_dentries(&fail_page_alloc.attr,
1214 dir = fail_page_alloc.attr.dentries.dir;
1216 fail_page_alloc.ignore_gfp_wait_file =
1217 debugfs_create_bool("ignore-gfp-wait", mode, dir,
1218 &fail_page_alloc.ignore_gfp_wait);
1220 fail_page_alloc.ignore_gfp_highmem_file =
1221 debugfs_create_bool("ignore-gfp-highmem", mode, dir,
1222 &fail_page_alloc.ignore_gfp_highmem);
1223 fail_page_alloc.min_order_file =
1224 debugfs_create_u32("min-order", mode, dir,
1225 &fail_page_alloc.min_order);
1227 if (!fail_page_alloc.ignore_gfp_wait_file ||
1228 !fail_page_alloc.ignore_gfp_highmem_file ||
1229 !fail_page_alloc.min_order_file) {
1231 debugfs_remove(fail_page_alloc.ignore_gfp_wait_file);
1232 debugfs_remove(fail_page_alloc.ignore_gfp_highmem_file);
1233 debugfs_remove(fail_page_alloc.min_order_file);
1234 cleanup_fault_attr_dentries(&fail_page_alloc.attr);
1240 late_initcall(fail_page_alloc_debugfs);
1242 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
1244 #else /* CONFIG_FAIL_PAGE_ALLOC */
1246 static inline int should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
1251 #endif /* CONFIG_FAIL_PAGE_ALLOC */
1254 * Return 1 if free pages are above 'mark'. This takes into account the order
1255 * of the allocation.
1257 int zone_watermark_ok(struct zone *z, int order, unsigned long mark,
1258 int classzone_idx, int alloc_flags)
1260 /* free_pages my go negative - that's OK */
1262 long free_pages = zone_page_state(z, NR_FREE_PAGES) - (1 << order) + 1;
1265 if (alloc_flags & ALLOC_HIGH)
1267 if (alloc_flags & ALLOC_HARDER)
1270 if (free_pages <= min + z->lowmem_reserve[classzone_idx])
1272 for (o = 0; o < order; o++) {
1273 /* At the next order, this order's pages become unavailable */
1274 free_pages -= z->free_area[o].nr_free << o;
1276 /* Require fewer higher order pages to be free */
1279 if (free_pages <= min)
1287 * zlc_setup - Setup for "zonelist cache". Uses cached zone data to
1288 * skip over zones that are not allowed by the cpuset, or that have
1289 * been recently (in last second) found to be nearly full. See further
1290 * comments in mmzone.h. Reduces cache footprint of zonelist scans
1291 * that have to skip over alot of full or unallowed zones.
1293 * If the zonelist cache is present in the passed in zonelist, then
1294 * returns a pointer to the allowed node mask (either the current
1295 * tasks mems_allowed, or node_states[N_HIGH_MEMORY].)
1297 * If the zonelist cache is not available for this zonelist, does
1298 * nothing and returns NULL.
1300 * If the fullzones BITMAP in the zonelist cache is stale (more than
1301 * a second since last zap'd) then we zap it out (clear its bits.)
1303 * We hold off even calling zlc_setup, until after we've checked the
1304 * first zone in the zonelist, on the theory that most allocations will
1305 * be satisfied from that first zone, so best to examine that zone as
1306 * quickly as we can.
1308 static nodemask_t *zlc_setup(struct zonelist *zonelist, int alloc_flags)
1310 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1311 nodemask_t *allowednodes; /* zonelist_cache approximation */
1313 zlc = zonelist->zlcache_ptr;
1317 if (jiffies - zlc->last_full_zap > 1 * HZ) {
1318 bitmap_zero(zlc->fullzones, MAX_ZONES_PER_ZONELIST);
1319 zlc->last_full_zap = jiffies;
1322 allowednodes = !in_interrupt() && (alloc_flags & ALLOC_CPUSET) ?
1323 &cpuset_current_mems_allowed :
1324 &node_states[N_HIGH_MEMORY];
1325 return allowednodes;
1329 * Given 'z' scanning a zonelist, run a couple of quick checks to see
1330 * if it is worth looking at further for free memory:
1331 * 1) Check that the zone isn't thought to be full (doesn't have its
1332 * bit set in the zonelist_cache fullzones BITMAP).
1333 * 2) Check that the zones node (obtained from the zonelist_cache
1334 * z_to_n[] mapping) is allowed in the passed in allowednodes mask.
1335 * Return true (non-zero) if zone is worth looking at further, or
1336 * else return false (zero) if it is not.
1338 * This check -ignores- the distinction between various watermarks,
1339 * such as GFP_HIGH, GFP_ATOMIC, PF_MEMALLOC, ... If a zone is
1340 * found to be full for any variation of these watermarks, it will
1341 * be considered full for up to one second by all requests, unless
1342 * we are so low on memory on all allowed nodes that we are forced
1343 * into the second scan of the zonelist.
1345 * In the second scan we ignore this zonelist cache and exactly
1346 * apply the watermarks to all zones, even it is slower to do so.
1347 * We are low on memory in the second scan, and should leave no stone
1348 * unturned looking for a free page.
1350 static int zlc_zone_worth_trying(struct zonelist *zonelist, struct zone **z,
1351 nodemask_t *allowednodes)
1353 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1354 int i; /* index of *z in zonelist zones */
1355 int n; /* node that zone *z is on */
1357 zlc = zonelist->zlcache_ptr;
1361 i = z - zonelist->zones;
1364 /* This zone is worth trying if it is allowed but not full */
1365 return node_isset(n, *allowednodes) && !test_bit(i, zlc->fullzones);
1369 * Given 'z' scanning a zonelist, set the corresponding bit in
1370 * zlc->fullzones, so that subsequent attempts to allocate a page
1371 * from that zone don't waste time re-examining it.
1373 static void zlc_mark_zone_full(struct zonelist *zonelist, struct zone **z)
1375 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1376 int i; /* index of *z in zonelist zones */
1378 zlc = zonelist->zlcache_ptr;
1382 i = z - zonelist->zones;
1384 set_bit(i, zlc->fullzones);
1387 #else /* CONFIG_NUMA */
1389 static nodemask_t *zlc_setup(struct zonelist *zonelist, int alloc_flags)
1394 static int zlc_zone_worth_trying(struct zonelist *zonelist, struct zone **z,
1395 nodemask_t *allowednodes)
1400 static void zlc_mark_zone_full(struct zonelist *zonelist, struct zone **z)
1403 #endif /* CONFIG_NUMA */
1406 * get_page_from_freelist goes through the zonelist trying to allocate
1409 static struct page *
1410 get_page_from_freelist(gfp_t gfp_mask, unsigned int order,
1411 struct zonelist *zonelist, int alloc_flags)
1414 struct page *page = NULL;
1415 int classzone_idx = zone_idx(zonelist->zones[0]);
1417 nodemask_t *allowednodes = NULL;/* zonelist_cache approximation */
1418 int zlc_active = 0; /* set if using zonelist_cache */
1419 int did_zlc_setup = 0; /* just call zlc_setup() one time */
1420 enum zone_type highest_zoneidx = -1; /* Gets set for policy zonelists */
1424 * Scan zonelist, looking for a zone with enough free.
1425 * See also cpuset_zone_allowed() comment in kernel/cpuset.c.
1427 z = zonelist->zones;
1431 * In NUMA, this could be a policy zonelist which contains
1432 * zones that may not be allowed by the current gfp_mask.
1433 * Check the zone is allowed by the current flags
1435 if (unlikely(alloc_should_filter_zonelist(zonelist))) {
1436 if (highest_zoneidx == -1)
1437 highest_zoneidx = gfp_zone(gfp_mask);
1438 if (zone_idx(*z) > highest_zoneidx)
1442 if (NUMA_BUILD && zlc_active &&
1443 !zlc_zone_worth_trying(zonelist, z, allowednodes))
1446 if ((alloc_flags & ALLOC_CPUSET) &&
1447 !cpuset_zone_allowed_softwall(zone, gfp_mask))
1450 if (!(alloc_flags & ALLOC_NO_WATERMARKS)) {
1452 if (alloc_flags & ALLOC_WMARK_MIN)
1453 mark = zone->pages_min;
1454 else if (alloc_flags & ALLOC_WMARK_LOW)
1455 mark = zone->pages_low;
1457 mark = zone->pages_high;
1458 if (!zone_watermark_ok(zone, order, mark,
1459 classzone_idx, alloc_flags)) {
1460 if (!zone_reclaim_mode ||
1461 !zone_reclaim(zone, gfp_mask, order))
1462 goto this_zone_full;
1466 page = buffered_rmqueue(zonelist, zone, order, gfp_mask);
1471 zlc_mark_zone_full(zonelist, z);
1473 if (NUMA_BUILD && !did_zlc_setup) {
1474 /* we do zlc_setup after the first zone is tried */
1475 allowednodes = zlc_setup(zonelist, alloc_flags);
1479 } while (*(++z) != NULL);
1481 if (unlikely(NUMA_BUILD && page == NULL && zlc_active)) {
1482 /* Disable zlc cache for second zonelist scan */
1490 * This is the 'heart' of the zoned buddy allocator.
1492 struct page * fastcall
1493 __alloc_pages(gfp_t gfp_mask, unsigned int order,
1494 struct zonelist *zonelist)
1496 const gfp_t wait = gfp_mask & __GFP_WAIT;
1499 struct reclaim_state reclaim_state;
1500 struct task_struct *p = current;
1503 int did_some_progress;
1505 might_sleep_if(wait);
1507 if (should_fail_alloc_page(gfp_mask, order))
1511 z = zonelist->zones; /* the list of zones suitable for gfp_mask */
1513 if (unlikely(*z == NULL)) {
1515 * Happens if we have an empty zonelist as a result of
1516 * GFP_THISNODE being used on a memoryless node
1521 page = get_page_from_freelist(gfp_mask|__GFP_HARDWALL, order,
1522 zonelist, ALLOC_WMARK_LOW|ALLOC_CPUSET);
1527 * GFP_THISNODE (meaning __GFP_THISNODE, __GFP_NORETRY and
1528 * __GFP_NOWARN set) should not cause reclaim since the subsystem
1529 * (f.e. slab) using GFP_THISNODE may choose to trigger reclaim
1530 * using a larger set of nodes after it has established that the
1531 * allowed per node queues are empty and that nodes are
1534 if (NUMA_BUILD && (gfp_mask & GFP_THISNODE) == GFP_THISNODE)
1537 for (z = zonelist->zones; *z; z++)
1538 wakeup_kswapd(*z, order);
1541 * OK, we're below the kswapd watermark and have kicked background
1542 * reclaim. Now things get more complex, so set up alloc_flags according
1543 * to how we want to proceed.
1545 * The caller may dip into page reserves a bit more if the caller
1546 * cannot run direct reclaim, or if the caller has realtime scheduling
1547 * policy or is asking for __GFP_HIGH memory. GFP_ATOMIC requests will
1548 * set both ALLOC_HARDER (!wait) and ALLOC_HIGH (__GFP_HIGH).
1550 alloc_flags = ALLOC_WMARK_MIN;
1551 if ((unlikely(rt_task(p)) && !in_interrupt()) || !wait)
1552 alloc_flags |= ALLOC_HARDER;
1553 if (gfp_mask & __GFP_HIGH)
1554 alloc_flags |= ALLOC_HIGH;
1556 alloc_flags |= ALLOC_CPUSET;
1559 * Go through the zonelist again. Let __GFP_HIGH and allocations
1560 * coming from realtime tasks go deeper into reserves.
1562 * This is the last chance, in general, before the goto nopage.
1563 * Ignore cpuset if GFP_ATOMIC (!wait) rather than fail alloc.
1564 * See also cpuset_zone_allowed() comment in kernel/cpuset.c.
1566 page = get_page_from_freelist(gfp_mask, order, zonelist, alloc_flags);
1570 /* This allocation should allow future memory freeing. */
1573 if (((p->flags & PF_MEMALLOC) || unlikely(test_thread_flag(TIF_MEMDIE)))
1574 && !in_interrupt()) {
1575 if (!(gfp_mask & __GFP_NOMEMALLOC)) {
1577 /* go through the zonelist yet again, ignoring mins */
1578 page = get_page_from_freelist(gfp_mask, order,
1579 zonelist, ALLOC_NO_WATERMARKS);
1582 if (gfp_mask & __GFP_NOFAIL) {
1583 congestion_wait(WRITE, HZ/50);
1590 /* Atomic allocations - we can't balance anything */
1596 /* We now go into synchronous reclaim */
1597 cpuset_memory_pressure_bump();
1598 p->flags |= PF_MEMALLOC;
1599 reclaim_state.reclaimed_slab = 0;
1600 p->reclaim_state = &reclaim_state;
1602 did_some_progress = try_to_free_pages(zonelist->zones, order, gfp_mask);
1604 p->reclaim_state = NULL;
1605 p->flags &= ~PF_MEMALLOC;
1610 drain_all_local_pages();
1612 if (likely(did_some_progress)) {
1613 page = get_page_from_freelist(gfp_mask, order,
1614 zonelist, alloc_flags);
1617 } else if ((gfp_mask & __GFP_FS) && !(gfp_mask & __GFP_NORETRY)) {
1619 * Go through the zonelist yet one more time, keep
1620 * very high watermark here, this is only to catch
1621 * a parallel oom killing, we must fail if we're still
1622 * under heavy pressure.
1624 page = get_page_from_freelist(gfp_mask|__GFP_HARDWALL, order,
1625 zonelist, ALLOC_WMARK_HIGH|ALLOC_CPUSET);
1629 /* The OOM killer will not help higher order allocs so fail */
1630 if (order > PAGE_ALLOC_COSTLY_ORDER)
1633 out_of_memory(zonelist, gfp_mask, order);
1638 * Don't let big-order allocations loop unless the caller explicitly
1639 * requests that. Wait for some write requests to complete then retry.
1641 * In this implementation, __GFP_REPEAT means __GFP_NOFAIL for order
1642 * <= 3, but that may not be true in other implementations.
1645 if (!(gfp_mask & __GFP_NORETRY)) {
1646 if ((order <= PAGE_ALLOC_COSTLY_ORDER) ||
1647 (gfp_mask & __GFP_REPEAT))
1649 if (gfp_mask & __GFP_NOFAIL)
1653 congestion_wait(WRITE, HZ/50);
1658 if (!(gfp_mask & __GFP_NOWARN) && printk_ratelimit()) {
1659 printk(KERN_WARNING "%s: page allocation failure."
1660 " order:%d, mode:0x%x\n",
1661 p->comm, order, gfp_mask);
1669 EXPORT_SYMBOL(__alloc_pages);
1672 * Common helper functions.
1674 fastcall unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order)
1677 page = alloc_pages(gfp_mask, order);
1680 return (unsigned long) page_address(page);
1683 EXPORT_SYMBOL(__get_free_pages);
1685 fastcall unsigned long get_zeroed_page(gfp_t gfp_mask)
1690 * get_zeroed_page() returns a 32-bit address, which cannot represent
1693 VM_BUG_ON((gfp_mask & __GFP_HIGHMEM) != 0);
1695 page = alloc_pages(gfp_mask | __GFP_ZERO, 0);
1697 return (unsigned long) page_address(page);
1701 EXPORT_SYMBOL(get_zeroed_page);
1703 void __pagevec_free(struct pagevec *pvec)
1705 int i = pagevec_count(pvec);
1708 free_hot_cold_page(pvec->pages[i], pvec->cold);
1711 fastcall void __free_pages(struct page *page, unsigned int order)
1713 if (put_page_testzero(page)) {
1715 free_hot_page(page);
1717 __free_pages_ok(page, order);
1721 EXPORT_SYMBOL(__free_pages);
1723 fastcall void free_pages(unsigned long addr, unsigned int order)
1726 VM_BUG_ON(!virt_addr_valid((void *)addr));
1727 __free_pages(virt_to_page((void *)addr), order);
1731 EXPORT_SYMBOL(free_pages);
1733 static unsigned int nr_free_zone_pages(int offset)
1735 /* Just pick one node, since fallback list is circular */
1736 pg_data_t *pgdat = NODE_DATA(numa_node_id());
1737 unsigned int sum = 0;
1739 struct zonelist *zonelist = pgdat->node_zonelists + offset;
1740 struct zone **zonep = zonelist->zones;
1743 for (zone = *zonep++; zone; zone = *zonep++) {
1744 unsigned long size = zone->present_pages;
1745 unsigned long high = zone->pages_high;
1754 * Amount of free RAM allocatable within ZONE_DMA and ZONE_NORMAL
1756 unsigned int nr_free_buffer_pages(void)
1758 return nr_free_zone_pages(gfp_zone(GFP_USER));
1760 EXPORT_SYMBOL_GPL(nr_free_buffer_pages);
1763 * Amount of free RAM allocatable within all zones
1765 unsigned int nr_free_pagecache_pages(void)
1767 return nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE));
1770 static inline void show_node(struct zone *zone)
1773 printk("Node %d ", zone_to_nid(zone));
1776 void si_meminfo(struct sysinfo *val)
1778 val->totalram = totalram_pages;
1780 val->freeram = global_page_state(NR_FREE_PAGES);
1781 val->bufferram = nr_blockdev_pages();
1782 val->totalhigh = totalhigh_pages;
1783 val->freehigh = nr_free_highpages();
1784 val->mem_unit = PAGE_SIZE;
1787 EXPORT_SYMBOL(si_meminfo);
1790 void si_meminfo_node(struct sysinfo *val, int nid)
1792 pg_data_t *pgdat = NODE_DATA(nid);
1794 val->totalram = pgdat->node_present_pages;
1795 val->freeram = node_page_state(nid, NR_FREE_PAGES);
1796 #ifdef CONFIG_HIGHMEM
1797 val->totalhigh = pgdat->node_zones[ZONE_HIGHMEM].present_pages;
1798 val->freehigh = zone_page_state(&pgdat->node_zones[ZONE_HIGHMEM],
1804 val->mem_unit = PAGE_SIZE;
1808 #define K(x) ((x) << (PAGE_SHIFT-10))
1811 * Show free area list (used inside shift_scroll-lock stuff)
1812 * We also calculate the percentage fragmentation. We do this by counting the
1813 * memory on each free list with the exception of the first item on the list.
1815 void show_free_areas(void)
1820 for_each_zone(zone) {
1821 if (!populated_zone(zone))
1825 printk("%s per-cpu:\n", zone->name);
1827 for_each_online_cpu(cpu) {
1828 struct per_cpu_pageset *pageset;
1830 pageset = zone_pcp(zone, cpu);
1832 printk("CPU %4d: Hot: hi:%5d, btch:%4d usd:%4d "
1833 "Cold: hi:%5d, btch:%4d usd:%4d\n",
1834 cpu, pageset->pcp[0].high,
1835 pageset->pcp[0].batch, pageset->pcp[0].count,
1836 pageset->pcp[1].high, pageset->pcp[1].batch,
1837 pageset->pcp[1].count);
1841 printk("Active:%lu inactive:%lu dirty:%lu writeback:%lu unstable:%lu\n"
1842 " free:%lu slab:%lu mapped:%lu pagetables:%lu bounce:%lu\n",
1843 global_page_state(NR_ACTIVE),
1844 global_page_state(NR_INACTIVE),
1845 global_page_state(NR_FILE_DIRTY),
1846 global_page_state(NR_WRITEBACK),
1847 global_page_state(NR_UNSTABLE_NFS),
1848 global_page_state(NR_FREE_PAGES),
1849 global_page_state(NR_SLAB_RECLAIMABLE) +
1850 global_page_state(NR_SLAB_UNRECLAIMABLE),
1851 global_page_state(NR_FILE_MAPPED),
1852 global_page_state(NR_PAGETABLE),
1853 global_page_state(NR_BOUNCE));
1855 for_each_zone(zone) {
1858 if (!populated_zone(zone))
1870 " pages_scanned:%lu"
1871 " all_unreclaimable? %s"
1874 K(zone_page_state(zone, NR_FREE_PAGES)),
1877 K(zone->pages_high),
1878 K(zone_page_state(zone, NR_ACTIVE)),
1879 K(zone_page_state(zone, NR_INACTIVE)),
1880 K(zone->present_pages),
1881 zone->pages_scanned,
1882 (zone->all_unreclaimable ? "yes" : "no")
1884 printk("lowmem_reserve[]:");
1885 for (i = 0; i < MAX_NR_ZONES; i++)
1886 printk(" %lu", zone->lowmem_reserve[i]);
1890 for_each_zone(zone) {
1891 unsigned long nr[MAX_ORDER], flags, order, total = 0;
1893 if (!populated_zone(zone))
1897 printk("%s: ", zone->name);
1899 spin_lock_irqsave(&zone->lock, flags);
1900 for (order = 0; order < MAX_ORDER; order++) {
1901 nr[order] = zone->free_area[order].nr_free;
1902 total += nr[order] << order;
1904 spin_unlock_irqrestore(&zone->lock, flags);
1905 for (order = 0; order < MAX_ORDER; order++)
1906 printk("%lu*%lukB ", nr[order], K(1UL) << order);
1907 printk("= %lukB\n", K(total));
1910 show_swap_cache_info();
1914 * Builds allocation fallback zone lists.
1916 * Add all populated zones of a node to the zonelist.
1918 static int build_zonelists_node(pg_data_t *pgdat, struct zonelist *zonelist,
1919 int nr_zones, enum zone_type zone_type)
1923 BUG_ON(zone_type >= MAX_NR_ZONES);
1928 zone = pgdat->node_zones + zone_type;
1929 if (populated_zone(zone)) {
1930 zonelist->zones[nr_zones++] = zone;
1931 check_highest_zone(zone_type);
1934 } while (zone_type);
1941 * 0 = automatic detection of better ordering.
1942 * 1 = order by ([node] distance, -zonetype)
1943 * 2 = order by (-zonetype, [node] distance)
1945 * If not NUMA, ZONELIST_ORDER_ZONE and ZONELIST_ORDER_NODE will create
1946 * the same zonelist. So only NUMA can configure this param.
1948 #define ZONELIST_ORDER_DEFAULT 0
1949 #define ZONELIST_ORDER_NODE 1
1950 #define ZONELIST_ORDER_ZONE 2
1952 /* zonelist order in the kernel.
1953 * set_zonelist_order() will set this to NODE or ZONE.
1955 static int current_zonelist_order = ZONELIST_ORDER_DEFAULT;
1956 static char zonelist_order_name[3][8] = {"Default", "Node", "Zone"};
1960 /* The value user specified ....changed by config */
1961 static int user_zonelist_order = ZONELIST_ORDER_DEFAULT;
1962 /* string for sysctl */
1963 #define NUMA_ZONELIST_ORDER_LEN 16
1964 char numa_zonelist_order[16] = "default";
1967 * interface for configure zonelist ordering.
1968 * command line option "numa_zonelist_order"
1969 * = "[dD]efault - default, automatic configuration.
1970 * = "[nN]ode - order by node locality, then by zone within node
1971 * = "[zZ]one - order by zone, then by locality within zone
1974 static int __parse_numa_zonelist_order(char *s)
1976 if (*s == 'd' || *s == 'D') {
1977 user_zonelist_order = ZONELIST_ORDER_DEFAULT;
1978 } else if (*s == 'n' || *s == 'N') {
1979 user_zonelist_order = ZONELIST_ORDER_NODE;
1980 } else if (*s == 'z' || *s == 'Z') {
1981 user_zonelist_order = ZONELIST_ORDER_ZONE;
1984 "Ignoring invalid numa_zonelist_order value: "
1991 static __init int setup_numa_zonelist_order(char *s)
1994 return __parse_numa_zonelist_order(s);
1997 early_param("numa_zonelist_order", setup_numa_zonelist_order);
2000 * sysctl handler for numa_zonelist_order
2002 int numa_zonelist_order_handler(ctl_table *table, int write,
2003 struct file *file, void __user *buffer, size_t *length,
2006 char saved_string[NUMA_ZONELIST_ORDER_LEN];
2010 strncpy(saved_string, (char*)table->data,
2011 NUMA_ZONELIST_ORDER_LEN);
2012 ret = proc_dostring(table, write, file, buffer, length, ppos);
2016 int oldval = user_zonelist_order;
2017 if (__parse_numa_zonelist_order((char*)table->data)) {
2019 * bogus value. restore saved string
2021 strncpy((char*)table->data, saved_string,
2022 NUMA_ZONELIST_ORDER_LEN);
2023 user_zonelist_order = oldval;
2024 } else if (oldval != user_zonelist_order)
2025 build_all_zonelists();
2031 #define MAX_NODE_LOAD (num_online_nodes())
2032 static int node_load[MAX_NUMNODES];
2035 * find_next_best_node - find the next node that should appear in a given node's fallback list
2036 * @node: node whose fallback list we're appending
2037 * @used_node_mask: nodemask_t of already used nodes
2039 * We use a number of factors to determine which is the next node that should
2040 * appear on a given node's fallback list. The node should not have appeared
2041 * already in @node's fallback list, and it should be the next closest node
2042 * according to the distance array (which contains arbitrary distance values
2043 * from each node to each node in the system), and should also prefer nodes
2044 * with no CPUs, since presumably they'll have very little allocation pressure
2045 * on them otherwise.
2046 * It returns -1 if no node is found.
2048 static int find_next_best_node(int node, nodemask_t *used_node_mask)
2051 int min_val = INT_MAX;
2054 /* Use the local node if we haven't already */
2055 if (!node_isset(node, *used_node_mask)) {
2056 node_set(node, *used_node_mask);
2060 for_each_node_state(n, N_HIGH_MEMORY) {
2063 /* Don't want a node to appear more than once */
2064 if (node_isset(n, *used_node_mask))
2067 /* Use the distance array to find the distance */
2068 val = node_distance(node, n);
2070 /* Penalize nodes under us ("prefer the next node") */
2073 /* Give preference to headless and unused nodes */
2074 tmp = node_to_cpumask(n);
2075 if (!cpus_empty(tmp))
2076 val += PENALTY_FOR_NODE_WITH_CPUS;
2078 /* Slight preference for less loaded node */
2079 val *= (MAX_NODE_LOAD*MAX_NUMNODES);
2080 val += node_load[n];
2082 if (val < min_val) {
2089 node_set(best_node, *used_node_mask);
2096 * Build zonelists ordered by node and zones within node.
2097 * This results in maximum locality--normal zone overflows into local
2098 * DMA zone, if any--but risks exhausting DMA zone.
2100 static void build_zonelists_in_node_order(pg_data_t *pgdat, int node)
2104 struct zonelist *zonelist;
2106 for (i = 0; i < MAX_NR_ZONES; i++) {
2107 zonelist = pgdat->node_zonelists + i;
2108 for (j = 0; zonelist->zones[j] != NULL; j++)
2110 j = build_zonelists_node(NODE_DATA(node), zonelist, j, i);
2111 zonelist->zones[j] = NULL;
2116 * Build gfp_thisnode zonelists
2118 static void build_thisnode_zonelists(pg_data_t *pgdat)
2122 struct zonelist *zonelist;
2124 for (i = 0; i < MAX_NR_ZONES; i++) {
2125 zonelist = pgdat->node_zonelists + MAX_NR_ZONES + i;
2126 j = build_zonelists_node(pgdat, zonelist, 0, i);
2127 zonelist->zones[j] = NULL;
2132 * Build zonelists ordered by zone and nodes within zones.
2133 * This results in conserving DMA zone[s] until all Normal memory is
2134 * exhausted, but results in overflowing to remote node while memory
2135 * may still exist in local DMA zone.
2137 static int node_order[MAX_NUMNODES];
2139 static void build_zonelists_in_zone_order(pg_data_t *pgdat, int nr_nodes)
2143 int zone_type; /* needs to be signed */
2145 struct zonelist *zonelist;
2147 for (i = 0; i < MAX_NR_ZONES; i++) {
2148 zonelist = pgdat->node_zonelists + i;
2150 for (zone_type = i; zone_type >= 0; zone_type--) {
2151 for (j = 0; j < nr_nodes; j++) {
2152 node = node_order[j];
2153 z = &NODE_DATA(node)->node_zones[zone_type];
2154 if (populated_zone(z)) {
2155 zonelist->zones[pos++] = z;
2156 check_highest_zone(zone_type);
2160 zonelist->zones[pos] = NULL;
2164 static int default_zonelist_order(void)
2167 unsigned long low_kmem_size,total_size;
2171 * ZONE_DMA and ZONE_DMA32 can be very small area in the sytem.
2172 * If they are really small and used heavily, the system can fall
2173 * into OOM very easily.
2174 * This function detect ZONE_DMA/DMA32 size and confgigures zone order.
2176 /* Is there ZONE_NORMAL ? (ex. ppc has only DMA zone..) */
2179 for_each_online_node(nid) {
2180 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
2181 z = &NODE_DATA(nid)->node_zones[zone_type];
2182 if (populated_zone(z)) {
2183 if (zone_type < ZONE_NORMAL)
2184 low_kmem_size += z->present_pages;
2185 total_size += z->present_pages;
2189 if (!low_kmem_size || /* there are no DMA area. */
2190 low_kmem_size > total_size/2) /* DMA/DMA32 is big. */
2191 return ZONELIST_ORDER_NODE;
2193 * look into each node's config.
2194 * If there is a node whose DMA/DMA32 memory is very big area on
2195 * local memory, NODE_ORDER may be suitable.
2197 average_size = total_size /
2198 (nodes_weight(node_states[N_HIGH_MEMORY]) + 1);
2199 for_each_online_node(nid) {
2202 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
2203 z = &NODE_DATA(nid)->node_zones[zone_type];
2204 if (populated_zone(z)) {
2205 if (zone_type < ZONE_NORMAL)
2206 low_kmem_size += z->present_pages;
2207 total_size += z->present_pages;
2210 if (low_kmem_size &&
2211 total_size > average_size && /* ignore small node */
2212 low_kmem_size > total_size * 70/100)
2213 return ZONELIST_ORDER_NODE;
2215 return ZONELIST_ORDER_ZONE;
2218 static void set_zonelist_order(void)
2220 if (user_zonelist_order == ZONELIST_ORDER_DEFAULT)
2221 current_zonelist_order = default_zonelist_order();
2223 current_zonelist_order = user_zonelist_order;
2226 static void build_zonelists(pg_data_t *pgdat)
2230 nodemask_t used_mask;
2231 int local_node, prev_node;
2232 struct zonelist *zonelist;
2233 int order = current_zonelist_order;
2235 /* initialize zonelists */
2236 for (i = 0; i < MAX_ZONELISTS; i++) {
2237 zonelist = pgdat->node_zonelists + i;
2238 zonelist->zones[0] = NULL;
2241 /* NUMA-aware ordering of nodes */
2242 local_node = pgdat->node_id;
2243 load = num_online_nodes();
2244 prev_node = local_node;
2245 nodes_clear(used_mask);
2247 memset(node_load, 0, sizeof(node_load));
2248 memset(node_order, 0, sizeof(node_order));
2251 while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
2252 int distance = node_distance(local_node, node);
2255 * If another node is sufficiently far away then it is better
2256 * to reclaim pages in a zone before going off node.
2258 if (distance > RECLAIM_DISTANCE)
2259 zone_reclaim_mode = 1;
2262 * We don't want to pressure a particular node.
2263 * So adding penalty to the first node in same
2264 * distance group to make it round-robin.
2266 if (distance != node_distance(local_node, prev_node))
2267 node_load[node] = load;
2271 if (order == ZONELIST_ORDER_NODE)
2272 build_zonelists_in_node_order(pgdat, node);
2274 node_order[j++] = node; /* remember order */
2277 if (order == ZONELIST_ORDER_ZONE) {
2278 /* calculate node order -- i.e., DMA last! */
2279 build_zonelists_in_zone_order(pgdat, j);
2282 build_thisnode_zonelists(pgdat);
2285 /* Construct the zonelist performance cache - see further mmzone.h */
2286 static void build_zonelist_cache(pg_data_t *pgdat)
2290 for (i = 0; i < MAX_NR_ZONES; i++) {
2291 struct zonelist *zonelist;
2292 struct zonelist_cache *zlc;
2295 zonelist = pgdat->node_zonelists + i;
2296 zonelist->zlcache_ptr = zlc = &zonelist->zlcache;
2297 bitmap_zero(zlc->fullzones, MAX_ZONES_PER_ZONELIST);
2298 for (z = zonelist->zones; *z; z++)
2299 zlc->z_to_n[z - zonelist->zones] = zone_to_nid(*z);
2304 #else /* CONFIG_NUMA */
2306 static void set_zonelist_order(void)
2308 current_zonelist_order = ZONELIST_ORDER_ZONE;
2311 static void build_zonelists(pg_data_t *pgdat)
2313 int node, local_node;
2316 local_node = pgdat->node_id;
2317 for (i = 0; i < MAX_NR_ZONES; i++) {
2318 struct zonelist *zonelist;
2320 zonelist = pgdat->node_zonelists + i;
2322 j = build_zonelists_node(pgdat, zonelist, 0, i);
2324 * Now we build the zonelist so that it contains the zones
2325 * of all the other nodes.
2326 * We don't want to pressure a particular node, so when
2327 * building the zones for node N, we make sure that the
2328 * zones coming right after the local ones are those from
2329 * node N+1 (modulo N)
2331 for (node = local_node + 1; node < MAX_NUMNODES; node++) {
2332 if (!node_online(node))
2334 j = build_zonelists_node(NODE_DATA(node), zonelist, j, i);
2336 for (node = 0; node < local_node; node++) {
2337 if (!node_online(node))
2339 j = build_zonelists_node(NODE_DATA(node), zonelist, j, i);
2342 zonelist->zones[j] = NULL;
2346 /* non-NUMA variant of zonelist performance cache - just NULL zlcache_ptr */
2347 static void build_zonelist_cache(pg_data_t *pgdat)
2351 for (i = 0; i < MAX_NR_ZONES; i++)
2352 pgdat->node_zonelists[i].zlcache_ptr = NULL;
2355 #endif /* CONFIG_NUMA */
2357 /* return values int ....just for stop_machine_run() */
2358 static int __build_all_zonelists(void *dummy)
2362 for_each_online_node(nid) {
2363 pg_data_t *pgdat = NODE_DATA(nid);
2365 build_zonelists(pgdat);
2366 build_zonelist_cache(pgdat);
2371 void build_all_zonelists(void)
2373 set_zonelist_order();
2375 if (system_state == SYSTEM_BOOTING) {
2376 __build_all_zonelists(NULL);
2377 cpuset_init_current_mems_allowed();
2379 /* we have to stop all cpus to guaranntee there is no user
2381 stop_machine_run(__build_all_zonelists, NULL, NR_CPUS);
2382 /* cpuset refresh routine should be here */
2384 vm_total_pages = nr_free_pagecache_pages();
2386 * Disable grouping by mobility if the number of pages in the
2387 * system is too low to allow the mechanism to work. It would be
2388 * more accurate, but expensive to check per-zone. This check is
2389 * made on memory-hotadd so a system can start with mobility
2390 * disabled and enable it later
2392 if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES))
2393 page_group_by_mobility_disabled = 1;
2395 page_group_by_mobility_disabled = 0;
2397 printk("Built %i zonelists in %s order, mobility grouping %s. "
2398 "Total pages: %ld\n",
2400 zonelist_order_name[current_zonelist_order],
2401 page_group_by_mobility_disabled ? "off" : "on",
2404 printk("Policy zone: %s\n", zone_names[policy_zone]);
2409 * Helper functions to size the waitqueue hash table.
2410 * Essentially these want to choose hash table sizes sufficiently
2411 * large so that collisions trying to wait on pages are rare.
2412 * But in fact, the number of active page waitqueues on typical
2413 * systems is ridiculously low, less than 200. So this is even
2414 * conservative, even though it seems large.
2416 * The constant PAGES_PER_WAITQUEUE specifies the ratio of pages to
2417 * waitqueues, i.e. the size of the waitq table given the number of pages.
2419 #define PAGES_PER_WAITQUEUE 256
2421 #ifndef CONFIG_MEMORY_HOTPLUG
2422 static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
2424 unsigned long size = 1;
2426 pages /= PAGES_PER_WAITQUEUE;
2428 while (size < pages)
2432 * Once we have dozens or even hundreds of threads sleeping
2433 * on IO we've got bigger problems than wait queue collision.
2434 * Limit the size of the wait table to a reasonable size.
2436 size = min(size, 4096UL);
2438 return max(size, 4UL);
2442 * A zone's size might be changed by hot-add, so it is not possible to determine
2443 * a suitable size for its wait_table. So we use the maximum size now.
2445 * The max wait table size = 4096 x sizeof(wait_queue_head_t). ie:
2447 * i386 (preemption config) : 4096 x 16 = 64Kbyte.
2448 * ia64, x86-64 (no preemption): 4096 x 20 = 80Kbyte.
2449 * ia64, x86-64 (preemption) : 4096 x 24 = 96Kbyte.
2451 * The maximum entries are prepared when a zone's memory is (512K + 256) pages
2452 * or more by the traditional way. (See above). It equals:
2454 * i386, x86-64, powerpc(4K page size) : = ( 2G + 1M)byte.
2455 * ia64(16K page size) : = ( 8G + 4M)byte.
2456 * powerpc (64K page size) : = (32G +16M)byte.
2458 static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
2465 * This is an integer logarithm so that shifts can be used later
2466 * to extract the more random high bits from the multiplicative
2467 * hash function before the remainder is taken.
2469 static inline unsigned long wait_table_bits(unsigned long size)
2474 #define LONG_ALIGN(x) (((x)+(sizeof(long))-1)&~((sizeof(long))-1))
2477 * Mark a number of pageblocks as MIGRATE_RESERVE. The number
2478 * of blocks reserved is based on zone->pages_min. The memory within the
2479 * reserve will tend to store contiguous free pages. Setting min_free_kbytes
2480 * higher will lead to a bigger reserve which will get freed as contiguous
2481 * blocks as reclaim kicks in
2483 static void setup_zone_migrate_reserve(struct zone *zone)
2485 unsigned long start_pfn, pfn, end_pfn;
2487 unsigned long reserve, block_migratetype;
2489 /* Get the start pfn, end pfn and the number of blocks to reserve */
2490 start_pfn = zone->zone_start_pfn;
2491 end_pfn = start_pfn + zone->spanned_pages;
2492 reserve = roundup(zone->pages_min, pageblock_nr_pages) >>
2495 for (pfn = start_pfn; pfn < end_pfn; pfn += pageblock_nr_pages) {
2496 if (!pfn_valid(pfn))
2498 page = pfn_to_page(pfn);
2500 /* Blocks with reserved pages will never free, skip them. */
2501 if (PageReserved(page))
2504 block_migratetype = get_pageblock_migratetype(page);
2506 /* If this block is reserved, account for it */
2507 if (reserve > 0 && block_migratetype == MIGRATE_RESERVE) {
2512 /* Suitable for reserving if this block is movable */
2513 if (reserve > 0 && block_migratetype == MIGRATE_MOVABLE) {
2514 set_pageblock_migratetype(page, MIGRATE_RESERVE);
2515 move_freepages_block(zone, page, MIGRATE_RESERVE);
2521 * If the reserve is met and this is a previous reserved block,
2524 if (block_migratetype == MIGRATE_RESERVE) {
2525 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
2526 move_freepages_block(zone, page, MIGRATE_MOVABLE);
2532 * Initially all pages are reserved - free ones are freed
2533 * up by free_all_bootmem() once the early boot process is
2534 * done. Non-atomic initialization, single-pass.
2536 void __meminit memmap_init_zone(unsigned long size, int nid, unsigned long zone,
2537 unsigned long start_pfn, enum memmap_context context)
2540 unsigned long end_pfn = start_pfn + size;
2543 for (pfn = start_pfn; pfn < end_pfn; pfn++) {
2545 * There can be holes in boot-time mem_map[]s
2546 * handed to this function. They do not
2547 * exist on hotplugged memory.
2549 if (context == MEMMAP_EARLY) {
2550 if (!early_pfn_valid(pfn))
2552 if (!early_pfn_in_nid(pfn, nid))
2555 page = pfn_to_page(pfn);
2556 set_page_links(page, zone, nid, pfn);
2557 init_page_count(page);
2558 reset_page_mapcount(page);
2559 SetPageReserved(page);
2562 * Mark the block movable so that blocks are reserved for
2563 * movable at startup. This will force kernel allocations
2564 * to reserve their blocks rather than leaking throughout
2565 * the address space during boot when many long-lived
2566 * kernel allocations are made. Later some blocks near
2567 * the start are marked MIGRATE_RESERVE by
2568 * setup_zone_migrate_reserve()
2570 if ((pfn & (pageblock_nr_pages-1)))
2571 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
2573 INIT_LIST_HEAD(&page->lru);
2574 #ifdef WANT_PAGE_VIRTUAL
2575 /* The shift won't overflow because ZONE_NORMAL is below 4G. */
2576 if (!is_highmem_idx(zone))
2577 set_page_address(page, __va(pfn << PAGE_SHIFT));
2582 static void __meminit zone_init_free_lists(struct pglist_data *pgdat,
2583 struct zone *zone, unsigned long size)
2586 for_each_migratetype_order(order, t) {
2587 INIT_LIST_HEAD(&zone->free_area[order].free_list[t]);
2588 zone->free_area[order].nr_free = 0;
2592 #ifndef __HAVE_ARCH_MEMMAP_INIT
2593 #define memmap_init(size, nid, zone, start_pfn) \
2594 memmap_init_zone((size), (nid), (zone), (start_pfn), MEMMAP_EARLY)
2597 static int __devinit zone_batchsize(struct zone *zone)
2602 * The per-cpu-pages pools are set to around 1000th of the
2603 * size of the zone. But no more than 1/2 of a meg.
2605 * OK, so we don't know how big the cache is. So guess.
2607 batch = zone->present_pages / 1024;
2608 if (batch * PAGE_SIZE > 512 * 1024)
2609 batch = (512 * 1024) / PAGE_SIZE;
2610 batch /= 4; /* We effectively *= 4 below */
2615 * Clamp the batch to a 2^n - 1 value. Having a power
2616 * of 2 value was found to be more likely to have
2617 * suboptimal cache aliasing properties in some cases.
2619 * For example if 2 tasks are alternately allocating
2620 * batches of pages, one task can end up with a lot
2621 * of pages of one half of the possible page colors
2622 * and the other with pages of the other colors.
2624 batch = (1 << (fls(batch + batch/2)-1)) - 1;
2629 inline void setup_pageset(struct per_cpu_pageset *p, unsigned long batch)
2631 struct per_cpu_pages *pcp;
2633 memset(p, 0, sizeof(*p));
2635 pcp = &p->pcp[0]; /* hot */
2637 pcp->high = 6 * batch;
2638 pcp->batch = max(1UL, 1 * batch);
2639 INIT_LIST_HEAD(&pcp->list);
2641 pcp = &p->pcp[1]; /* cold*/
2643 pcp->high = 2 * batch;
2644 pcp->batch = max(1UL, batch/2);
2645 INIT_LIST_HEAD(&pcp->list);
2649 * setup_pagelist_highmark() sets the high water mark for hot per_cpu_pagelist
2650 * to the value high for the pageset p.
2653 static void setup_pagelist_highmark(struct per_cpu_pageset *p,
2656 struct per_cpu_pages *pcp;
2658 pcp = &p->pcp[0]; /* hot list */
2660 pcp->batch = max(1UL, high/4);
2661 if ((high/4) > (PAGE_SHIFT * 8))
2662 pcp->batch = PAGE_SHIFT * 8;
2668 * Boot pageset table. One per cpu which is going to be used for all
2669 * zones and all nodes. The parameters will be set in such a way
2670 * that an item put on a list will immediately be handed over to
2671 * the buddy list. This is safe since pageset manipulation is done
2672 * with interrupts disabled.
2674 * Some NUMA counter updates may also be caught by the boot pagesets.
2676 * The boot_pagesets must be kept even after bootup is complete for
2677 * unused processors and/or zones. They do play a role for bootstrapping
2678 * hotplugged processors.
2680 * zoneinfo_show() and maybe other functions do
2681 * not check if the processor is online before following the pageset pointer.
2682 * Other parts of the kernel may not check if the zone is available.
2684 static struct per_cpu_pageset boot_pageset[NR_CPUS];
2687 * Dynamically allocate memory for the
2688 * per cpu pageset array in struct zone.
2690 static int __cpuinit process_zones(int cpu)
2692 struct zone *zone, *dzone;
2693 int node = cpu_to_node(cpu);
2695 node_set_state(node, N_CPU); /* this node has a cpu */
2697 for_each_zone(zone) {
2699 if (!populated_zone(zone))
2702 zone_pcp(zone, cpu) = kmalloc_node(sizeof(struct per_cpu_pageset),
2704 if (!zone_pcp(zone, cpu))
2707 setup_pageset(zone_pcp(zone, cpu), zone_batchsize(zone));
2709 if (percpu_pagelist_fraction)
2710 setup_pagelist_highmark(zone_pcp(zone, cpu),
2711 (zone->present_pages / percpu_pagelist_fraction));
2716 for_each_zone(dzone) {
2717 if (!populated_zone(dzone))
2721 kfree(zone_pcp(dzone, cpu));
2722 zone_pcp(dzone, cpu) = NULL;
2727 static inline void free_zone_pagesets(int cpu)
2731 for_each_zone(zone) {
2732 struct per_cpu_pageset *pset = zone_pcp(zone, cpu);
2734 /* Free per_cpu_pageset if it is slab allocated */
2735 if (pset != &boot_pageset[cpu])
2737 zone_pcp(zone, cpu) = NULL;
2741 static int __cpuinit pageset_cpuup_callback(struct notifier_block *nfb,
2742 unsigned long action,
2745 int cpu = (long)hcpu;
2746 int ret = NOTIFY_OK;
2749 case CPU_UP_PREPARE:
2750 case CPU_UP_PREPARE_FROZEN:
2751 if (process_zones(cpu))
2754 case CPU_UP_CANCELED:
2755 case CPU_UP_CANCELED_FROZEN:
2757 case CPU_DEAD_FROZEN:
2758 free_zone_pagesets(cpu);
2766 static struct notifier_block __cpuinitdata pageset_notifier =
2767 { &pageset_cpuup_callback, NULL, 0 };
2769 void __init setup_per_cpu_pageset(void)
2773 /* Initialize per_cpu_pageset for cpu 0.
2774 * A cpuup callback will do this for every cpu
2775 * as it comes online
2777 err = process_zones(smp_processor_id());
2779 register_cpu_notifier(&pageset_notifier);
2784 static noinline __init_refok
2785 int zone_wait_table_init(struct zone *zone, unsigned long zone_size_pages)
2788 struct pglist_data *pgdat = zone->zone_pgdat;
2792 * The per-page waitqueue mechanism uses hashed waitqueues
2795 zone->wait_table_hash_nr_entries =
2796 wait_table_hash_nr_entries(zone_size_pages);
2797 zone->wait_table_bits =
2798 wait_table_bits(zone->wait_table_hash_nr_entries);
2799 alloc_size = zone->wait_table_hash_nr_entries
2800 * sizeof(wait_queue_head_t);
2802 if (system_state == SYSTEM_BOOTING) {
2803 zone->wait_table = (wait_queue_head_t *)
2804 alloc_bootmem_node(pgdat, alloc_size);
2807 * This case means that a zone whose size was 0 gets new memory
2808 * via memory hot-add.
2809 * But it may be the case that a new node was hot-added. In
2810 * this case vmalloc() will not be able to use this new node's
2811 * memory - this wait_table must be initialized to use this new
2812 * node itself as well.
2813 * To use this new node's memory, further consideration will be
2816 zone->wait_table = vmalloc(alloc_size);
2818 if (!zone->wait_table)
2821 for(i = 0; i < zone->wait_table_hash_nr_entries; ++i)
2822 init_waitqueue_head(zone->wait_table + i);
2827 static __meminit void zone_pcp_init(struct zone *zone)
2830 unsigned long batch = zone_batchsize(zone);
2832 for (cpu = 0; cpu < NR_CPUS; cpu++) {
2834 /* Early boot. Slab allocator not functional yet */
2835 zone_pcp(zone, cpu) = &boot_pageset[cpu];
2836 setup_pageset(&boot_pageset[cpu],0);
2838 setup_pageset(zone_pcp(zone,cpu), batch);
2841 if (zone->present_pages)
2842 printk(KERN_DEBUG " %s zone: %lu pages, LIFO batch:%lu\n",
2843 zone->name, zone->present_pages, batch);
2846 __meminit int init_currently_empty_zone(struct zone *zone,
2847 unsigned long zone_start_pfn,
2849 enum memmap_context context)
2851 struct pglist_data *pgdat = zone->zone_pgdat;
2853 ret = zone_wait_table_init(zone, size);
2856 pgdat->nr_zones = zone_idx(zone) + 1;
2858 zone->zone_start_pfn = zone_start_pfn;
2860 memmap_init(size, pgdat->node_id, zone_idx(zone), zone_start_pfn);
2862 zone_init_free_lists(pgdat, zone, zone->spanned_pages);
2867 #ifdef CONFIG_ARCH_POPULATES_NODE_MAP
2869 * Basic iterator support. Return the first range of PFNs for a node
2870 * Note: nid == MAX_NUMNODES returns first region regardless of node
2872 static int __meminit first_active_region_index_in_nid(int nid)
2876 for (i = 0; i < nr_nodemap_entries; i++)
2877 if (nid == MAX_NUMNODES || early_node_map[i].nid == nid)
2884 * Basic iterator support. Return the next active range of PFNs for a node
2885 * Note: nid == MAX_NUMNODES returns next region regardles of node
2887 static int __meminit next_active_region_index_in_nid(int index, int nid)
2889 for (index = index + 1; index < nr_nodemap_entries; index++)
2890 if (nid == MAX_NUMNODES || early_node_map[index].nid == nid)
2896 #ifndef CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID
2898 * Required by SPARSEMEM. Given a PFN, return what node the PFN is on.
2899 * Architectures may implement their own version but if add_active_range()
2900 * was used and there are no special requirements, this is a convenient
2903 int __meminit early_pfn_to_nid(unsigned long pfn)
2907 for (i = 0; i < nr_nodemap_entries; i++) {
2908 unsigned long start_pfn = early_node_map[i].start_pfn;
2909 unsigned long end_pfn = early_node_map[i].end_pfn;
2911 if (start_pfn <= pfn && pfn < end_pfn)
2912 return early_node_map[i].nid;
2917 #endif /* CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID */
2919 /* Basic iterator support to walk early_node_map[] */
2920 #define for_each_active_range_index_in_nid(i, nid) \
2921 for (i = first_active_region_index_in_nid(nid); i != -1; \
2922 i = next_active_region_index_in_nid(i, nid))
2925 * free_bootmem_with_active_regions - Call free_bootmem_node for each active range
2926 * @nid: The node to free memory on. If MAX_NUMNODES, all nodes are freed.
2927 * @max_low_pfn: The highest PFN that will be passed to free_bootmem_node
2929 * If an architecture guarantees that all ranges registered with
2930 * add_active_ranges() contain no holes and may be freed, this
2931 * this function may be used instead of calling free_bootmem() manually.
2933 void __init free_bootmem_with_active_regions(int nid,
2934 unsigned long max_low_pfn)
2938 for_each_active_range_index_in_nid(i, nid) {
2939 unsigned long size_pages = 0;
2940 unsigned long end_pfn = early_node_map[i].end_pfn;
2942 if (early_node_map[i].start_pfn >= max_low_pfn)
2945 if (end_pfn > max_low_pfn)
2946 end_pfn = max_low_pfn;
2948 size_pages = end_pfn - early_node_map[i].start_pfn;
2949 free_bootmem_node(NODE_DATA(early_node_map[i].nid),
2950 PFN_PHYS(early_node_map[i].start_pfn),
2951 size_pages << PAGE_SHIFT);
2956 * sparse_memory_present_with_active_regions - Call memory_present for each active range
2957 * @nid: The node to call memory_present for. If MAX_NUMNODES, all nodes will be used.
2959 * If an architecture guarantees that all ranges registered with
2960 * add_active_ranges() contain no holes and may be freed, this
2961 * function may be used instead of calling memory_present() manually.
2963 void __init sparse_memory_present_with_active_regions(int nid)
2967 for_each_active_range_index_in_nid(i, nid)
2968 memory_present(early_node_map[i].nid,
2969 early_node_map[i].start_pfn,
2970 early_node_map[i].end_pfn);
2974 * push_node_boundaries - Push node boundaries to at least the requested boundary
2975 * @nid: The nid of the node to push the boundary for
2976 * @start_pfn: The start pfn of the node
2977 * @end_pfn: The end pfn of the node
2979 * In reserve-based hot-add, mem_map is allocated that is unused until hotadd
2980 * time. Specifically, on x86_64, SRAT will report ranges that can potentially
2981 * be hotplugged even though no physical memory exists. This function allows
2982 * an arch to push out the node boundaries so mem_map is allocated that can
2985 #ifdef CONFIG_MEMORY_HOTPLUG_RESERVE
2986 void __init push_node_boundaries(unsigned int nid,
2987 unsigned long start_pfn, unsigned long end_pfn)
2989 printk(KERN_DEBUG "Entering push_node_boundaries(%u, %lu, %lu)\n",
2990 nid, start_pfn, end_pfn);
2992 /* Initialise the boundary for this node if necessary */
2993 if (node_boundary_end_pfn[nid] == 0)
2994 node_boundary_start_pfn[nid] = -1UL;
2996 /* Update the boundaries */
2997 if (node_boundary_start_pfn[nid] > start_pfn)
2998 node_boundary_start_pfn[nid] = start_pfn;
2999 if (node_boundary_end_pfn[nid] < end_pfn)
3000 node_boundary_end_pfn[nid] = end_pfn;
3003 /* If necessary, push the node boundary out for reserve hotadd */
3004 static void __meminit account_node_boundary(unsigned int nid,
3005 unsigned long *start_pfn, unsigned long *end_pfn)
3007 printk(KERN_DEBUG "Entering account_node_boundary(%u, %lu, %lu)\n",
3008 nid, *start_pfn, *end_pfn);
3010 /* Return if boundary information has not been provided */
3011 if (node_boundary_end_pfn[nid] == 0)
3014 /* Check the boundaries and update if necessary */
3015 if (node_boundary_start_pfn[nid] < *start_pfn)
3016 *start_pfn = node_boundary_start_pfn[nid];
3017 if (node_boundary_end_pfn[nid] > *end_pfn)
3018 *end_pfn = node_boundary_end_pfn[nid];
3021 void __init push_node_boundaries(unsigned int nid,
3022 unsigned long start_pfn, unsigned long end_pfn) {}
3024 static void __meminit account_node_boundary(unsigned int nid,
3025 unsigned long *start_pfn, unsigned long *end_pfn) {}
3030 * get_pfn_range_for_nid - Return the start and end page frames for a node
3031 * @nid: The nid to return the range for. If MAX_NUMNODES, the min and max PFN are returned.
3032 * @start_pfn: Passed by reference. On return, it will have the node start_pfn.
3033 * @end_pfn: Passed by reference. On return, it will have the node end_pfn.
3035 * It returns the start and end page frame of a node based on information
3036 * provided by an arch calling add_active_range(). If called for a node
3037 * with no available memory, a warning is printed and the start and end
3040 void __meminit get_pfn_range_for_nid(unsigned int nid,
3041 unsigned long *start_pfn, unsigned long *end_pfn)
3047 for_each_active_range_index_in_nid(i, nid) {
3048 *start_pfn = min(*start_pfn, early_node_map[i].start_pfn);
3049 *end_pfn = max(*end_pfn, early_node_map[i].end_pfn);
3052 if (*start_pfn == -1UL)
3055 /* Push the node boundaries out if requested */
3056 account_node_boundary(nid, start_pfn, end_pfn);
3060 * This finds a zone that can be used for ZONE_MOVABLE pages. The
3061 * assumption is made that zones within a node are ordered in monotonic
3062 * increasing memory addresses so that the "highest" populated zone is used
3064 void __init find_usable_zone_for_movable(void)
3067 for (zone_index = MAX_NR_ZONES - 1; zone_index >= 0; zone_index--) {
3068 if (zone_index == ZONE_MOVABLE)
3071 if (arch_zone_highest_possible_pfn[zone_index] >
3072 arch_zone_lowest_possible_pfn[zone_index])
3076 VM_BUG_ON(zone_index == -1);
3077 movable_zone = zone_index;
3081 * The zone ranges provided by the architecture do not include ZONE_MOVABLE
3082 * because it is sized independant of architecture. Unlike the other zones,
3083 * the starting point for ZONE_MOVABLE is not fixed. It may be different
3084 * in each node depending on the size of each node and how evenly kernelcore
3085 * is distributed. This helper function adjusts the zone ranges
3086 * provided by the architecture for a given node by using the end of the
3087 * highest usable zone for ZONE_MOVABLE. This preserves the assumption that
3088 * zones within a node are in order of monotonic increases memory addresses
3090 void __meminit adjust_zone_range_for_zone_movable(int nid,
3091 unsigned long zone_type,
3092 unsigned long node_start_pfn,
3093 unsigned long node_end_pfn,
3094 unsigned long *zone_start_pfn,
3095 unsigned long *zone_end_pfn)
3097 /* Only adjust if ZONE_MOVABLE is on this node */
3098 if (zone_movable_pfn[nid]) {
3099 /* Size ZONE_MOVABLE */
3100 if (zone_type == ZONE_MOVABLE) {
3101 *zone_start_pfn = zone_movable_pfn[nid];
3102 *zone_end_pfn = min(node_end_pfn,
3103 arch_zone_highest_possible_pfn[movable_zone]);
3105 /* Adjust for ZONE_MOVABLE starting within this range */
3106 } else if (*zone_start_pfn < zone_movable_pfn[nid] &&
3107 *zone_end_pfn > zone_movable_pfn[nid]) {
3108 *zone_end_pfn = zone_movable_pfn[nid];
3110 /* Check if this whole range is within ZONE_MOVABLE */
3111 } else if (*zone_start_pfn >= zone_movable_pfn[nid])
3112 *zone_start_pfn = *zone_end_pfn;
3117 * Return the number of pages a zone spans in a node, including holes
3118 * present_pages = zone_spanned_pages_in_node() - zone_absent_pages_in_node()
3120 static unsigned long __meminit zone_spanned_pages_in_node(int nid,
3121 unsigned long zone_type,
3122 unsigned long *ignored)
3124 unsigned long node_start_pfn, node_end_pfn;
3125 unsigned long zone_start_pfn, zone_end_pfn;
3127 /* Get the start and end of the node and zone */
3128 get_pfn_range_for_nid(nid, &node_start_pfn, &node_end_pfn);
3129 zone_start_pfn = arch_zone_lowest_possible_pfn[zone_type];
3130 zone_end_pfn = arch_zone_highest_possible_pfn[zone_type];
3131 adjust_zone_range_for_zone_movable(nid, zone_type,
3132 node_start_pfn, node_end_pfn,
3133 &zone_start_pfn, &zone_end_pfn);
3135 /* Check that this node has pages within the zone's required range */
3136 if (zone_end_pfn < node_start_pfn || zone_start_pfn > node_end_pfn)
3139 /* Move the zone boundaries inside the node if necessary */
3140 zone_end_pfn = min(zone_end_pfn, node_end_pfn);
3141 zone_start_pfn = max(zone_start_pfn, node_start_pfn);
3143 /* Return the spanned pages */
3144 return zone_end_pfn - zone_start_pfn;
3148 * Return the number of holes in a range on a node. If nid is MAX_NUMNODES,
3149 * then all holes in the requested range will be accounted for.
3151 unsigned long __meminit __absent_pages_in_range(int nid,
3152 unsigned long range_start_pfn,
3153 unsigned long range_end_pfn)
3156 unsigned long prev_end_pfn = 0, hole_pages = 0;
3157 unsigned long start_pfn;
3159 /* Find the end_pfn of the first active range of pfns in the node */
3160 i = first_active_region_index_in_nid(nid);
3164 prev_end_pfn = min(early_node_map[i].start_pfn, range_end_pfn);
3166 /* Account for ranges before physical memory on this node */
3167 if (early_node_map[i].start_pfn > range_start_pfn)
3168 hole_pages = prev_end_pfn - range_start_pfn;
3170 /* Find all holes for the zone within the node */
3171 for (; i != -1; i = next_active_region_index_in_nid(i, nid)) {
3173 /* No need to continue if prev_end_pfn is outside the zone */
3174 if (prev_end_pfn >= range_end_pfn)
3177 /* Make sure the end of the zone is not within the hole */
3178 start_pfn = min(early_node_map[i].start_pfn, range_end_pfn);
3179 prev_end_pfn = max(prev_end_pfn, range_start_pfn);
3181 /* Update the hole size cound and move on */
3182 if (start_pfn > range_start_pfn) {
3183 BUG_ON(prev_end_pfn > start_pfn);
3184 hole_pages += start_pfn - prev_end_pfn;
3186 prev_end_pfn = early_node_map[i].end_pfn;
3189 /* Account for ranges past physical memory on this node */
3190 if (range_end_pfn > prev_end_pfn)
3191 hole_pages += range_end_pfn -
3192 max(range_start_pfn, prev_end_pfn);
3198 * absent_pages_in_range - Return number of page frames in holes within a range
3199 * @start_pfn: The start PFN to start searching for holes
3200 * @end_pfn: The end PFN to stop searching for holes
3202 * It returns the number of pages frames in memory holes within a range.
3204 unsigned long __init absent_pages_in_range(unsigned long start_pfn,
3205 unsigned long end_pfn)
3207 return __absent_pages_in_range(MAX_NUMNODES, start_pfn, end_pfn);
3210 /* Return the number of page frames in holes in a zone on a node */
3211 static unsigned long __meminit zone_absent_pages_in_node(int nid,
3212 unsigned long zone_type,
3213 unsigned long *ignored)
3215 unsigned long node_start_pfn, node_end_pfn;
3216 unsigned long zone_start_pfn, zone_end_pfn;
3218 get_pfn_range_for_nid(nid, &node_start_pfn, &node_end_pfn);
3219 zone_start_pfn = max(arch_zone_lowest_possible_pfn[zone_type],
3221 zone_end_pfn = min(arch_zone_highest_possible_pfn[zone_type],
3224 adjust_zone_range_for_zone_movable(nid, zone_type,
3225 node_start_pfn, node_end_pfn,
3226 &zone_start_pfn, &zone_end_pfn);
3227 return __absent_pages_in_range(nid, zone_start_pfn, zone_end_pfn);
3231 static inline unsigned long __meminit zone_spanned_pages_in_node(int nid,
3232 unsigned long zone_type,
3233 unsigned long *zones_size)
3235 return zones_size[zone_type];
3238 static inline unsigned long __meminit zone_absent_pages_in_node(int nid,
3239 unsigned long zone_type,
3240 unsigned long *zholes_size)
3245 return zholes_size[zone_type];
3250 static void __meminit calculate_node_totalpages(struct pglist_data *pgdat,
3251 unsigned long *zones_size, unsigned long *zholes_size)
3253 unsigned long realtotalpages, totalpages = 0;
3256 for (i = 0; i < MAX_NR_ZONES; i++)
3257 totalpages += zone_spanned_pages_in_node(pgdat->node_id, i,
3259 pgdat->node_spanned_pages = totalpages;
3261 realtotalpages = totalpages;
3262 for (i = 0; i < MAX_NR_ZONES; i++)
3264 zone_absent_pages_in_node(pgdat->node_id, i,
3266 pgdat->node_present_pages = realtotalpages;
3267 printk(KERN_DEBUG "On node %d totalpages: %lu\n", pgdat->node_id,
3271 #ifndef CONFIG_SPARSEMEM
3273 * Calculate the size of the zone->blockflags rounded to an unsigned long
3274 * Start by making sure zonesize is a multiple of pageblock_order by rounding
3275 * up. Then use 1 NR_PAGEBLOCK_BITS worth of bits per pageblock, finally
3276 * round what is now in bits to nearest long in bits, then return it in
3279 static unsigned long __init usemap_size(unsigned long zonesize)
3281 unsigned long usemapsize;
3283 usemapsize = roundup(zonesize, pageblock_nr_pages);
3284 usemapsize = usemapsize >> pageblock_order;
3285 usemapsize *= NR_PAGEBLOCK_BITS;
3286 usemapsize = roundup(usemapsize, 8 * sizeof(unsigned long));
3288 return usemapsize / 8;
3291 static void __init setup_usemap(struct pglist_data *pgdat,
3292 struct zone *zone, unsigned long zonesize)
3294 unsigned long usemapsize = usemap_size(zonesize);
3295 zone->pageblock_flags = NULL;
3297 zone->pageblock_flags = alloc_bootmem_node(pgdat, usemapsize);
3298 memset(zone->pageblock_flags, 0, usemapsize);
3302 static void inline setup_usemap(struct pglist_data *pgdat,
3303 struct zone *zone, unsigned long zonesize) {}
3304 #endif /* CONFIG_SPARSEMEM */
3306 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
3307 /* Initialise the number of pages represented by NR_PAGEBLOCK_BITS */
3308 static inline void __init set_pageblock_order(unsigned int order)
3310 /* Check that pageblock_nr_pages has not already been setup */
3311 if (pageblock_order)
3315 * Assume the largest contiguous order of interest is a huge page.
3316 * This value may be variable depending on boot parameters on IA64
3318 pageblock_order = order;
3320 #else /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
3322 /* Defined this way to avoid accidently referencing HUGETLB_PAGE_ORDER */
3323 #define set_pageblock_order(x) do {} while (0)
3325 #endif /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
3328 * Set up the zone data structures:
3329 * - mark all pages reserved
3330 * - mark all memory queues empty
3331 * - clear the memory bitmaps
3333 static void __meminit free_area_init_core(struct pglist_data *pgdat,
3334 unsigned long *zones_size, unsigned long *zholes_size)
3337 int nid = pgdat->node_id;
3338 unsigned long zone_start_pfn = pgdat->node_start_pfn;
3341 pgdat_resize_init(pgdat);
3342 pgdat->nr_zones = 0;
3343 init_waitqueue_head(&pgdat->kswapd_wait);
3344 pgdat->kswapd_max_order = 0;
3346 for (j = 0; j < MAX_NR_ZONES; j++) {
3347 struct zone *zone = pgdat->node_zones + j;
3348 unsigned long size, realsize, memmap_pages;
3350 size = zone_spanned_pages_in_node(nid, j, zones_size);
3351 realsize = size - zone_absent_pages_in_node(nid, j,
3355 * Adjust realsize so that it accounts for how much memory
3356 * is used by this zone for memmap. This affects the watermark
3357 * and per-cpu initialisations
3359 memmap_pages = (size * sizeof(struct page)) >> PAGE_SHIFT;
3360 if (realsize >= memmap_pages) {
3361 realsize -= memmap_pages;
3363 " %s zone: %lu pages used for memmap\n",
3364 zone_names[j], memmap_pages);
3367 " %s zone: %lu pages exceeds realsize %lu\n",
3368 zone_names[j], memmap_pages, realsize);
3370 /* Account for reserved pages */
3371 if (j == 0 && realsize > dma_reserve) {
3372 realsize -= dma_reserve;
3373 printk(KERN_DEBUG " %s zone: %lu pages reserved\n",
3374 zone_names[0], dma_reserve);
3377 if (!is_highmem_idx(j))
3378 nr_kernel_pages += realsize;
3379 nr_all_pages += realsize;
3381 zone->spanned_pages = size;
3382 zone->present_pages = realsize;
3385 zone->min_unmapped_pages = (realsize*sysctl_min_unmapped_ratio)
3387 zone->min_slab_pages = (realsize * sysctl_min_slab_ratio) / 100;
3389 zone->name = zone_names[j];
3390 spin_lock_init(&zone->lock);
3391 spin_lock_init(&zone->lru_lock);
3392 zone_seqlock_init(zone);
3393 zone->zone_pgdat = pgdat;
3395 zone->prev_priority = DEF_PRIORITY;
3397 zone_pcp_init(zone);
3398 INIT_LIST_HEAD(&zone->active_list);
3399 INIT_LIST_HEAD(&zone->inactive_list);
3400 zone->nr_scan_active = 0;
3401 zone->nr_scan_inactive = 0;
3402 zap_zone_vm_stats(zone);
3403 atomic_set(&zone->reclaim_in_progress, 0);
3407 set_pageblock_order(HUGETLB_PAGE_ORDER);
3408 setup_usemap(pgdat, zone, size);
3409 ret = init_currently_empty_zone(zone, zone_start_pfn,
3410 size, MEMMAP_EARLY);
3412 zone_start_pfn += size;
3416 static void __init_refok alloc_node_mem_map(struct pglist_data *pgdat)
3418 /* Skip empty nodes */
3419 if (!pgdat->node_spanned_pages)
3422 #ifdef CONFIG_FLAT_NODE_MEM_MAP
3423 /* ia64 gets its own node_mem_map, before this, without bootmem */
3424 if (!pgdat->node_mem_map) {
3425 unsigned long size, start, end;
3429 * The zone's endpoints aren't required to be MAX_ORDER
3430 * aligned but the node_mem_map endpoints must be in order
3431 * for the buddy allocator to function correctly.
3433 start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1);
3434 end = pgdat->node_start_pfn + pgdat->node_spanned_pages;
3435 end = ALIGN(end, MAX_ORDER_NR_PAGES);
3436 size = (end - start) * sizeof(struct page);
3437 map = alloc_remap(pgdat->node_id, size);
3439 map = alloc_bootmem_node(pgdat, size);
3440 pgdat->node_mem_map = map + (pgdat->node_start_pfn - start);
3442 #ifndef CONFIG_NEED_MULTIPLE_NODES
3444 * With no DISCONTIG, the global mem_map is just set as node 0's
3446 if (pgdat == NODE_DATA(0)) {
3447 mem_map = NODE_DATA(0)->node_mem_map;
3448 #ifdef CONFIG_ARCH_POPULATES_NODE_MAP
3449 if (page_to_pfn(mem_map) != pgdat->node_start_pfn)
3450 mem_map -= pgdat->node_start_pfn;
3451 #endif /* CONFIG_ARCH_POPULATES_NODE_MAP */
3454 #endif /* CONFIG_FLAT_NODE_MEM_MAP */
3457 void __meminit free_area_init_node(int nid, struct pglist_data *pgdat,
3458 unsigned long *zones_size, unsigned long node_start_pfn,
3459 unsigned long *zholes_size)
3461 pgdat->node_id = nid;
3462 pgdat->node_start_pfn = node_start_pfn;
3463 calculate_node_totalpages(pgdat, zones_size, zholes_size);
3465 alloc_node_mem_map(pgdat);
3467 free_area_init_core(pgdat, zones_size, zholes_size);
3470 #ifdef CONFIG_ARCH_POPULATES_NODE_MAP
3472 #if MAX_NUMNODES > 1
3474 * Figure out the number of possible node ids.
3476 static void __init setup_nr_node_ids(void)
3479 unsigned int highest = 0;
3481 for_each_node_mask(node, node_possible_map)
3483 nr_node_ids = highest + 1;
3486 static inline void setup_nr_node_ids(void)
3492 * add_active_range - Register a range of PFNs backed by physical memory
3493 * @nid: The node ID the range resides on
3494 * @start_pfn: The start PFN of the available physical memory
3495 * @end_pfn: The end PFN of the available physical memory
3497 * These ranges are stored in an early_node_map[] and later used by
3498 * free_area_init_nodes() to calculate zone sizes and holes. If the
3499 * range spans a memory hole, it is up to the architecture to ensure
3500 * the memory is not freed by the bootmem allocator. If possible
3501 * the range being registered will be merged with existing ranges.
3503 void __init add_active_range(unsigned int nid, unsigned long start_pfn,
3504 unsigned long end_pfn)
3508 printk(KERN_DEBUG "Entering add_active_range(%d, %lu, %lu) "
3509 "%d entries of %d used\n",
3510 nid, start_pfn, end_pfn,
3511 nr_nodemap_entries, MAX_ACTIVE_REGIONS);
3513 /* Merge with existing active regions if possible */
3514 for (i = 0; i < nr_nodemap_entries; i++) {
3515 if (early_node_map[i].nid != nid)
3518 /* Skip if an existing region covers this new one */
3519 if (start_pfn >= early_node_map[i].start_pfn &&
3520 end_pfn <= early_node_map[i].end_pfn)
3523 /* Merge forward if suitable */
3524 if (start_pfn <= early_node_map[i].end_pfn &&
3525 end_pfn > early_node_map[i].end_pfn) {
3526 early_node_map[i].end_pfn = end_pfn;
3530 /* Merge backward if suitable */
3531 if (start_pfn < early_node_map[i].end_pfn &&
3532 end_pfn >= early_node_map[i].start_pfn) {
3533 early_node_map[i].start_pfn = start_pfn;
3538 /* Check that early_node_map is large enough */
3539 if (i >= MAX_ACTIVE_REGIONS) {
3540 printk(KERN_CRIT "More than %d memory regions, truncating\n",
3541 MAX_ACTIVE_REGIONS);
3545 early_node_map[i].nid = nid;
3546 early_node_map[i].start_pfn = start_pfn;
3547 early_node_map[i].end_pfn = end_pfn;
3548 nr_nodemap_entries = i + 1;
3552 * shrink_active_range - Shrink an existing registered range of PFNs
3553 * @nid: The node id the range is on that should be shrunk
3554 * @old_end_pfn: The old end PFN of the range
3555 * @new_end_pfn: The new PFN of the range
3557 * i386 with NUMA use alloc_remap() to store a node_mem_map on a local node.
3558 * The map is kept at the end physical page range that has already been
3559 * registered with add_active_range(). This function allows an arch to shrink
3560 * an existing registered range.
3562 void __init shrink_active_range(unsigned int nid, unsigned long old_end_pfn,
3563 unsigned long new_end_pfn)
3567 /* Find the old active region end and shrink */
3568 for_each_active_range_index_in_nid(i, nid)
3569 if (early_node_map[i].end_pfn == old_end_pfn) {
3570 early_node_map[i].end_pfn = new_end_pfn;
3576 * remove_all_active_ranges - Remove all currently registered regions
3578 * During discovery, it may be found that a table like SRAT is invalid
3579 * and an alternative discovery method must be used. This function removes
3580 * all currently registered regions.
3582 void __init remove_all_active_ranges(void)
3584 memset(early_node_map, 0, sizeof(early_node_map));
3585 nr_nodemap_entries = 0;
3586 #ifdef CONFIG_MEMORY_HOTPLUG_RESERVE
3587 memset(node_boundary_start_pfn, 0, sizeof(node_boundary_start_pfn));
3588 memset(node_boundary_end_pfn, 0, sizeof(node_boundary_end_pfn));
3589 #endif /* CONFIG_MEMORY_HOTPLUG_RESERVE */
3592 /* Compare two active node_active_regions */
3593 static int __init cmp_node_active_region(const void *a, const void *b)
3595 struct node_active_region *arange = (struct node_active_region *)a;
3596 struct node_active_region *brange = (struct node_active_region *)b;
3598 /* Done this way to avoid overflows */
3599 if (arange->start_pfn > brange->start_pfn)
3601 if (arange->start_pfn < brange->start_pfn)
3607 /* sort the node_map by start_pfn */
3608 static void __init sort_node_map(void)
3610 sort(early_node_map, (size_t)nr_nodemap_entries,
3611 sizeof(struct node_active_region),
3612 cmp_node_active_region, NULL);
3615 /* Find the lowest pfn for a node */
3616 unsigned long __init find_min_pfn_for_node(unsigned long nid)
3619 unsigned long min_pfn = ULONG_MAX;
3621 /* Assuming a sorted map, the first range found has the starting pfn */
3622 for_each_active_range_index_in_nid(i, nid)
3623 min_pfn = min(min_pfn, early_node_map[i].start_pfn);
3625 if (min_pfn == ULONG_MAX) {
3627 "Could not find start_pfn for node %lu\n", nid);
3635 * find_min_pfn_with_active_regions - Find the minimum PFN registered
3637 * It returns the minimum PFN based on information provided via
3638 * add_active_range().
3640 unsigned long __init find_min_pfn_with_active_regions(void)
3642 return find_min_pfn_for_node(MAX_NUMNODES);
3646 * find_max_pfn_with_active_regions - Find the maximum PFN registered
3648 * It returns the maximum PFN based on information provided via
3649 * add_active_range().
3651 unsigned long __init find_max_pfn_with_active_regions(void)
3654 unsigned long max_pfn = 0;
3656 for (i = 0; i < nr_nodemap_entries; i++)
3657 max_pfn = max(max_pfn, early_node_map[i].end_pfn);
3663 * early_calculate_totalpages()
3664 * Sum pages in active regions for movable zone.
3665 * Populate N_HIGH_MEMORY for calculating usable_nodes.
3667 unsigned long __init early_calculate_totalpages(void)
3670 unsigned long totalpages = 0;
3672 for (i = 0; i < nr_nodemap_entries; i++) {
3673 unsigned long pages = early_node_map[i].end_pfn -
3674 early_node_map[i].start_pfn;
3675 totalpages += pages;
3677 node_set_state(early_node_map[i].nid, N_HIGH_MEMORY);
3683 * Find the PFN the Movable zone begins in each node. Kernel memory
3684 * is spread evenly between nodes as long as the nodes have enough
3685 * memory. When they don't, some nodes will have more kernelcore than
3688 void __init find_zone_movable_pfns_for_nodes(unsigned long *movable_pfn)
3691 unsigned long usable_startpfn;
3692 unsigned long kernelcore_node, kernelcore_remaining;
3693 unsigned long totalpages = early_calculate_totalpages();
3694 int usable_nodes = nodes_weight(node_states[N_HIGH_MEMORY]);
3697 * If movablecore was specified, calculate what size of
3698 * kernelcore that corresponds so that memory usable for
3699 * any allocation type is evenly spread. If both kernelcore
3700 * and movablecore are specified, then the value of kernelcore
3701 * will be used for required_kernelcore if it's greater than
3702 * what movablecore would have allowed.
3704 if (required_movablecore) {
3705 unsigned long corepages;
3708 * Round-up so that ZONE_MOVABLE is at least as large as what
3709 * was requested by the user
3711 required_movablecore =
3712 roundup(required_movablecore, MAX_ORDER_NR_PAGES);
3713 corepages = totalpages - required_movablecore;
3715 required_kernelcore = max(required_kernelcore, corepages);
3718 /* If kernelcore was not specified, there is no ZONE_MOVABLE */
3719 if (!required_kernelcore)
3722 /* usable_startpfn is the lowest possible pfn ZONE_MOVABLE can be at */
3723 find_usable_zone_for_movable();
3724 usable_startpfn = arch_zone_lowest_possible_pfn[movable_zone];
3727 /* Spread kernelcore memory as evenly as possible throughout nodes */
3728 kernelcore_node = required_kernelcore / usable_nodes;
3729 for_each_node_state(nid, N_HIGH_MEMORY) {
3731 * Recalculate kernelcore_node if the division per node
3732 * now exceeds what is necessary to satisfy the requested
3733 * amount of memory for the kernel
3735 if (required_kernelcore < kernelcore_node)
3736 kernelcore_node = required_kernelcore / usable_nodes;
3739 * As the map is walked, we track how much memory is usable
3740 * by the kernel using kernelcore_remaining. When it is
3741 * 0, the rest of the node is usable by ZONE_MOVABLE
3743 kernelcore_remaining = kernelcore_node;
3745 /* Go through each range of PFNs within this node */
3746 for_each_active_range_index_in_nid(i, nid) {
3747 unsigned long start_pfn, end_pfn;
3748 unsigned long size_pages;
3750 start_pfn = max(early_node_map[i].start_pfn,
3751 zone_movable_pfn[nid]);
3752 end_pfn = early_node_map[i].end_pfn;
3753 if (start_pfn >= end_pfn)
3756 /* Account for what is only usable for kernelcore */
3757 if (start_pfn < usable_startpfn) {
3758 unsigned long kernel_pages;
3759 kernel_pages = min(end_pfn, usable_startpfn)
3762 kernelcore_remaining -= min(kernel_pages,
3763 kernelcore_remaining);
3764 required_kernelcore -= min(kernel_pages,
3765 required_kernelcore);
3767 /* Continue if range is now fully accounted */
3768 if (end_pfn <= usable_startpfn) {
3771 * Push zone_movable_pfn to the end so
3772 * that if we have to rebalance
3773 * kernelcore across nodes, we will
3774 * not double account here
3776 zone_movable_pfn[nid] = end_pfn;
3779 start_pfn = usable_startpfn;
3783 * The usable PFN range for ZONE_MOVABLE is from
3784 * start_pfn->end_pfn. Calculate size_pages as the
3785 * number of pages used as kernelcore
3787 size_pages = end_pfn - start_pfn;
3788 if (size_pages > kernelcore_remaining)
3789 size_pages = kernelcore_remaining;
3790 zone_movable_pfn[nid] = start_pfn + size_pages;
3793 * Some kernelcore has been met, update counts and
3794 * break if the kernelcore for this node has been
3797 required_kernelcore -= min(required_kernelcore,
3799 kernelcore_remaining -= size_pages;
3800 if (!kernelcore_remaining)
3806 * If there is still required_kernelcore, we do another pass with one
3807 * less node in the count. This will push zone_movable_pfn[nid] further
3808 * along on the nodes that still have memory until kernelcore is
3812 if (usable_nodes && required_kernelcore > usable_nodes)
3815 /* Align start of ZONE_MOVABLE on all nids to MAX_ORDER_NR_PAGES */
3816 for (nid = 0; nid < MAX_NUMNODES; nid++)
3817 zone_movable_pfn[nid] =
3818 roundup(zone_movable_pfn[nid], MAX_ORDER_NR_PAGES);
3821 /* Any regular memory on that node ? */
3822 static void check_for_regular_memory(pg_data_t *pgdat)
3824 #ifdef CONFIG_HIGHMEM
3825 enum zone_type zone_type;
3827 for (zone_type = 0; zone_type <= ZONE_NORMAL; zone_type++) {
3828 struct zone *zone = &pgdat->node_zones[zone_type];
3829 if (zone->present_pages)
3830 node_set_state(zone_to_nid(zone), N_NORMAL_MEMORY);
3836 * free_area_init_nodes - Initialise all pg_data_t and zone data
3837 * @max_zone_pfn: an array of max PFNs for each zone
3839 * This will call free_area_init_node() for each active node in the system.
3840 * Using the page ranges provided by add_active_range(), the size of each
3841 * zone in each node and their holes is calculated. If the maximum PFN
3842 * between two adjacent zones match, it is assumed that the zone is empty.
3843 * For example, if arch_max_dma_pfn == arch_max_dma32_pfn, it is assumed
3844 * that arch_max_dma32_pfn has no pages. It is also assumed that a zone
3845 * starts where the previous one ended. For example, ZONE_DMA32 starts
3846 * at arch_max_dma_pfn.
3848 void __init free_area_init_nodes(unsigned long *max_zone_pfn)
3853 /* Sort early_node_map as initialisation assumes it is sorted */
3856 /* Record where the zone boundaries are */
3857 memset(arch_zone_lowest_possible_pfn, 0,
3858 sizeof(arch_zone_lowest_possible_pfn));
3859 memset(arch_zone_highest_possible_pfn, 0,
3860 sizeof(arch_zone_highest_possible_pfn));
3861 arch_zone_lowest_possible_pfn[0] = find_min_pfn_with_active_regions();
3862 arch_zone_highest_possible_pfn[0] = max_zone_pfn[0];
3863 for (i = 1; i < MAX_NR_ZONES; i++) {
3864 if (i == ZONE_MOVABLE)
3866 arch_zone_lowest_possible_pfn[i] =
3867 arch_zone_highest_possible_pfn[i-1];
3868 arch_zone_highest_possible_pfn[i] =
3869 max(max_zone_pfn[i], arch_zone_lowest_possible_pfn[i]);
3871 arch_zone_lowest_possible_pfn[ZONE_MOVABLE] = 0;
3872 arch_zone_highest_possible_pfn[ZONE_MOVABLE] = 0;
3874 /* Find the PFNs that ZONE_MOVABLE begins at in each node */
3875 memset(zone_movable_pfn, 0, sizeof(zone_movable_pfn));
3876 find_zone_movable_pfns_for_nodes(zone_movable_pfn);
3878 /* Print out the zone ranges */
3879 printk("Zone PFN ranges:\n");
3880 for (i = 0; i < MAX_NR_ZONES; i++) {
3881 if (i == ZONE_MOVABLE)
3883 printk(" %-8s %8lu -> %8lu\n",
3885 arch_zone_lowest_possible_pfn[i],
3886 arch_zone_highest_possible_pfn[i]);
3889 /* Print out the PFNs ZONE_MOVABLE begins at in each node */
3890 printk("Movable zone start PFN for each node\n");
3891 for (i = 0; i < MAX_NUMNODES; i++) {
3892 if (zone_movable_pfn[i])
3893 printk(" Node %d: %lu\n", i, zone_movable_pfn[i]);
3896 /* Print out the early_node_map[] */
3897 printk("early_node_map[%d] active PFN ranges\n", nr_nodemap_entries);
3898 for (i = 0; i < nr_nodemap_entries; i++)
3899 printk(" %3d: %8lu -> %8lu\n", early_node_map[i].nid,
3900 early_node_map[i].start_pfn,
3901 early_node_map[i].end_pfn);
3903 /* Initialise every node */
3904 setup_nr_node_ids();
3905 for_each_online_node(nid) {
3906 pg_data_t *pgdat = NODE_DATA(nid);
3907 free_area_init_node(nid, pgdat, NULL,
3908 find_min_pfn_for_node(nid), NULL);
3910 /* Any memory on that node */
3911 if (pgdat->node_present_pages)
3912 node_set_state(nid, N_HIGH_MEMORY);
3913 check_for_regular_memory(pgdat);
3917 static int __init cmdline_parse_core(char *p, unsigned long *core)
3919 unsigned long long coremem;
3923 coremem = memparse(p, &p);
3924 *core = coremem >> PAGE_SHIFT;
3926 /* Paranoid check that UL is enough for the coremem value */
3927 WARN_ON((coremem >> PAGE_SHIFT) > ULONG_MAX);
3933 * kernelcore=size sets the amount of memory for use for allocations that
3934 * cannot be reclaimed or migrated.
3936 static int __init cmdline_parse_kernelcore(char *p)
3938 return cmdline_parse_core(p, &required_kernelcore);
3942 * movablecore=size sets the amount of memory for use for allocations that
3943 * can be reclaimed or migrated.
3945 static int __init cmdline_parse_movablecore(char *p)
3947 return cmdline_parse_core(p, &required_movablecore);
3950 early_param("kernelcore", cmdline_parse_kernelcore);
3951 early_param("movablecore", cmdline_parse_movablecore);
3953 #endif /* CONFIG_ARCH_POPULATES_NODE_MAP */
3956 * set_dma_reserve - set the specified number of pages reserved in the first zone
3957 * @new_dma_reserve: The number of pages to mark reserved
3959 * The per-cpu batchsize and zone watermarks are determined by present_pages.
3960 * In the DMA zone, a significant percentage may be consumed by kernel image
3961 * and other unfreeable allocations which can skew the watermarks badly. This
3962 * function may optionally be used to account for unfreeable pages in the
3963 * first zone (e.g., ZONE_DMA). The effect will be lower watermarks and
3964 * smaller per-cpu batchsize.
3966 void __init set_dma_reserve(unsigned long new_dma_reserve)
3968 dma_reserve = new_dma_reserve;
3971 #ifndef CONFIG_NEED_MULTIPLE_NODES
3972 static bootmem_data_t contig_bootmem_data;
3973 struct pglist_data contig_page_data = { .bdata = &contig_bootmem_data };
3975 EXPORT_SYMBOL(contig_page_data);
3978 void __init free_area_init(unsigned long *zones_size)
3980 free_area_init_node(0, NODE_DATA(0), zones_size,
3981 __pa(PAGE_OFFSET) >> PAGE_SHIFT, NULL);
3984 static int page_alloc_cpu_notify(struct notifier_block *self,
3985 unsigned long action, void *hcpu)
3987 int cpu = (unsigned long)hcpu;
3989 if (action == CPU_DEAD || action == CPU_DEAD_FROZEN) {
3990 local_irq_disable();
3992 vm_events_fold_cpu(cpu);
3994 refresh_cpu_vm_stats(cpu);
3999 void __init page_alloc_init(void)
4001 hotcpu_notifier(page_alloc_cpu_notify, 0);
4005 * calculate_totalreserve_pages - called when sysctl_lower_zone_reserve_ratio
4006 * or min_free_kbytes changes.
4008 static void calculate_totalreserve_pages(void)
4010 struct pglist_data *pgdat;
4011 unsigned long reserve_pages = 0;
4012 enum zone_type i, j;
4014 for_each_online_pgdat(pgdat) {
4015 for (i = 0; i < MAX_NR_ZONES; i++) {
4016 struct zone *zone = pgdat->node_zones + i;
4017 unsigned long max = 0;
4019 /* Find valid and maximum lowmem_reserve in the zone */
4020 for (j = i; j < MAX_NR_ZONES; j++) {
4021 if (zone->lowmem_reserve[j] > max)
4022 max = zone->lowmem_reserve[j];
4025 /* we treat pages_high as reserved pages. */
4026 max += zone->pages_high;
4028 if (max > zone->present_pages)
4029 max = zone->present_pages;
4030 reserve_pages += max;
4033 totalreserve_pages = reserve_pages;
4037 * setup_per_zone_lowmem_reserve - called whenever
4038 * sysctl_lower_zone_reserve_ratio changes. Ensures that each zone
4039 * has a correct pages reserved value, so an adequate number of
4040 * pages are left in the zone after a successful __alloc_pages().
4042 static void setup_per_zone_lowmem_reserve(void)
4044 struct pglist_data *pgdat;
4045 enum zone_type j, idx;
4047 for_each_online_pgdat(pgdat) {
4048 for (j = 0; j < MAX_NR_ZONES; j++) {
4049 struct zone *zone = pgdat->node_zones + j;
4050 unsigned long present_pages = zone->present_pages;
4052 zone->lowmem_reserve[j] = 0;
4056 struct zone *lower_zone;
4060 if (sysctl_lowmem_reserve_ratio[idx] < 1)
4061 sysctl_lowmem_reserve_ratio[idx] = 1;
4063 lower_zone = pgdat->node_zones + idx;
4064 lower_zone->lowmem_reserve[j] = present_pages /
4065 sysctl_lowmem_reserve_ratio[idx];
4066 present_pages += lower_zone->present_pages;
4071 /* update totalreserve_pages */
4072 calculate_totalreserve_pages();
4076 * setup_per_zone_pages_min - called when min_free_kbytes changes.
4078 * Ensures that the pages_{min,low,high} values for each zone are set correctly
4079 * with respect to min_free_kbytes.
4081 void setup_per_zone_pages_min(void)
4083 unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
4084 unsigned long lowmem_pages = 0;
4086 unsigned long flags;
4088 /* Calculate total number of !ZONE_HIGHMEM pages */
4089 for_each_zone(zone) {
4090 if (!is_highmem(zone))
4091 lowmem_pages += zone->present_pages;
4094 for_each_zone(zone) {
4097 spin_lock_irqsave(&zone->lru_lock, flags);
4098 tmp = (u64)pages_min * zone->present_pages;
4099 do_div(tmp, lowmem_pages);
4100 if (is_highmem(zone)) {
4102 * __GFP_HIGH and PF_MEMALLOC allocations usually don't
4103 * need highmem pages, so cap pages_min to a small
4106 * The (pages_high-pages_low) and (pages_low-pages_min)
4107 * deltas controls asynch page reclaim, and so should
4108 * not be capped for highmem.
4112 min_pages = zone->present_pages / 1024;
4113 if (min_pages < SWAP_CLUSTER_MAX)
4114 min_pages = SWAP_CLUSTER_MAX;
4115 if (min_pages > 128)
4117 zone->pages_min = min_pages;
4120 * If it's a lowmem zone, reserve a number of pages
4121 * proportionate to the zone's size.
4123 zone->pages_min = tmp;
4126 zone->pages_low = zone->pages_min + (tmp >> 2);
4127 zone->pages_high = zone->pages_min + (tmp >> 1);
4128 setup_zone_migrate_reserve(zone);
4129 spin_unlock_irqrestore(&zone->lru_lock, flags);
4132 /* update totalreserve_pages */
4133 calculate_totalreserve_pages();
4137 * Initialise min_free_kbytes.
4139 * For small machines we want it small (128k min). For large machines
4140 * we want it large (64MB max). But it is not linear, because network
4141 * bandwidth does not increase linearly with machine size. We use
4143 * min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
4144 * min_free_kbytes = sqrt(lowmem_kbytes * 16)
4160 static int __init init_per_zone_pages_min(void)
4162 unsigned long lowmem_kbytes;
4164 lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
4166 min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
4167 if (min_free_kbytes < 128)
4168 min_free_kbytes = 128;
4169 if (min_free_kbytes > 65536)
4170 min_free_kbytes = 65536;
4171 setup_per_zone_pages_min();
4172 setup_per_zone_lowmem_reserve();
4175 module_init(init_per_zone_pages_min)
4178 * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
4179 * that we can call two helper functions whenever min_free_kbytes
4182 int min_free_kbytes_sysctl_handler(ctl_table *table, int write,
4183 struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
4185 proc_dointvec(table, write, file, buffer, length, ppos);
4187 setup_per_zone_pages_min();
4192 int sysctl_min_unmapped_ratio_sysctl_handler(ctl_table *table, int write,
4193 struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
4198 rc = proc_dointvec_minmax(table, write, file, buffer, length, ppos);
4203 zone->min_unmapped_pages = (zone->present_pages *
4204 sysctl_min_unmapped_ratio) / 100;
4208 int sysctl_min_slab_ratio_sysctl_handler(ctl_table *table, int write,
4209 struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
4214 rc = proc_dointvec_minmax(table, write, file, buffer, length, ppos);
4219 zone->min_slab_pages = (zone->present_pages *
4220 sysctl_min_slab_ratio) / 100;
4226 * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
4227 * proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
4228 * whenever sysctl_lowmem_reserve_ratio changes.
4230 * The reserve ratio obviously has absolutely no relation with the
4231 * pages_min watermarks. The lowmem reserve ratio can only make sense
4232 * if in function of the boot time zone sizes.
4234 int lowmem_reserve_ratio_sysctl_handler(ctl_table *table, int write,
4235 struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
4237 proc_dointvec_minmax(table, write, file, buffer, length, ppos);
4238 setup_per_zone_lowmem_reserve();
4243 * percpu_pagelist_fraction - changes the pcp->high for each zone on each
4244 * cpu. It is the fraction of total pages in each zone that a hot per cpu pagelist
4245 * can have before it gets flushed back to buddy allocator.
4248 int percpu_pagelist_fraction_sysctl_handler(ctl_table *table, int write,
4249 struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
4255 ret = proc_dointvec_minmax(table, write, file, buffer, length, ppos);
4256 if (!write || (ret == -EINVAL))
4258 for_each_zone(zone) {
4259 for_each_online_cpu(cpu) {
4261 high = zone->present_pages / percpu_pagelist_fraction;
4262 setup_pagelist_highmark(zone_pcp(zone, cpu), high);
4268 int hashdist = HASHDIST_DEFAULT;
4271 static int __init set_hashdist(char *str)
4275 hashdist = simple_strtoul(str, &str, 0);
4278 __setup("hashdist=", set_hashdist);
4282 * allocate a large system hash table from bootmem
4283 * - it is assumed that the hash table must contain an exact power-of-2
4284 * quantity of entries
4285 * - limit is the number of hash buckets, not the total allocation size
4287 void *__init alloc_large_system_hash(const char *tablename,
4288 unsigned long bucketsize,
4289 unsigned long numentries,
4292 unsigned int *_hash_shift,
4293 unsigned int *_hash_mask,
4294 unsigned long limit)
4296 unsigned long long max = limit;
4297 unsigned long log2qty, size;
4300 /* allow the kernel cmdline to have a say */
4302 /* round applicable memory size up to nearest megabyte */
4303 numentries = nr_kernel_pages;
4304 numentries += (1UL << (20 - PAGE_SHIFT)) - 1;
4305 numentries >>= 20 - PAGE_SHIFT;
4306 numentries <<= 20 - PAGE_SHIFT;
4308 /* limit to 1 bucket per 2^scale bytes of low memory */
4309 if (scale > PAGE_SHIFT)
4310 numentries >>= (scale - PAGE_SHIFT);
4312 numentries <<= (PAGE_SHIFT - scale);
4314 /* Make sure we've got at least a 0-order allocation.. */
4315 if (unlikely((numentries * bucketsize) < PAGE_SIZE))
4316 numentries = PAGE_SIZE / bucketsize;
4318 numentries = roundup_pow_of_two(numentries);
4320 /* limit allocation size to 1/16 total memory by default */
4322 max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
4323 do_div(max, bucketsize);
4326 if (numentries > max)
4329 log2qty = ilog2(numentries);
4332 size = bucketsize << log2qty;
4333 if (flags & HASH_EARLY)
4334 table = alloc_bootmem(size);
4336 table = __vmalloc(size, GFP_ATOMIC, PAGE_KERNEL);
4338 unsigned long order;
4339 for (order = 0; ((1UL << order) << PAGE_SHIFT) < size; order++)
4341 table = (void*) __get_free_pages(GFP_ATOMIC, order);
4343 * If bucketsize is not a power-of-two, we may free
4344 * some pages at the end of hash table.
4347 unsigned long alloc_end = (unsigned long)table +
4348 (PAGE_SIZE << order);
4349 unsigned long used = (unsigned long)table +
4351 split_page(virt_to_page(table), order);
4352 while (used < alloc_end) {
4358 } while (!table && size > PAGE_SIZE && --log2qty);
4361 panic("Failed to allocate %s hash table\n", tablename);
4363 printk(KERN_INFO "%s hash table entries: %d (order: %d, %lu bytes)\n",
4366 ilog2(size) - PAGE_SHIFT,
4370 *_hash_shift = log2qty;
4372 *_hash_mask = (1 << log2qty) - 1;
4377 #ifdef CONFIG_OUT_OF_LINE_PFN_TO_PAGE
4378 struct page *pfn_to_page(unsigned long pfn)
4380 return __pfn_to_page(pfn);
4382 unsigned long page_to_pfn(struct page *page)
4384 return __page_to_pfn(page);
4386 EXPORT_SYMBOL(pfn_to_page);
4387 EXPORT_SYMBOL(page_to_pfn);
4388 #endif /* CONFIG_OUT_OF_LINE_PFN_TO_PAGE */
4390 /* Return a pointer to the bitmap storing bits affecting a block of pages */
4391 static inline unsigned long *get_pageblock_bitmap(struct zone *zone,
4394 #ifdef CONFIG_SPARSEMEM
4395 return __pfn_to_section(pfn)->pageblock_flags;
4397 return zone->pageblock_flags;
4398 #endif /* CONFIG_SPARSEMEM */
4401 static inline int pfn_to_bitidx(struct zone *zone, unsigned long pfn)
4403 #ifdef CONFIG_SPARSEMEM
4404 pfn &= (PAGES_PER_SECTION-1);
4405 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
4407 pfn = pfn - zone->zone_start_pfn;
4408 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
4409 #endif /* CONFIG_SPARSEMEM */
4413 * get_pageblock_flags_group - Return the requested group of flags for the pageblock_nr_pages block of pages
4414 * @page: The page within the block of interest
4415 * @start_bitidx: The first bit of interest to retrieve
4416 * @end_bitidx: The last bit of interest
4417 * returns pageblock_bits flags
4419 unsigned long get_pageblock_flags_group(struct page *page,
4420 int start_bitidx, int end_bitidx)
4423 unsigned long *bitmap;
4424 unsigned long pfn, bitidx;
4425 unsigned long flags = 0;
4426 unsigned long value = 1;
4428 zone = page_zone(page);
4429 pfn = page_to_pfn(page);
4430 bitmap = get_pageblock_bitmap(zone, pfn);
4431 bitidx = pfn_to_bitidx(zone, pfn);
4433 for (; start_bitidx <= end_bitidx; start_bitidx++, value <<= 1)
4434 if (test_bit(bitidx + start_bitidx, bitmap))
4441 * set_pageblock_flags_group - Set the requested group of flags for a pageblock_nr_pages block of pages
4442 * @page: The page within the block of interest
4443 * @start_bitidx: The first bit of interest
4444 * @end_bitidx: The last bit of interest
4445 * @flags: The flags to set
4447 void set_pageblock_flags_group(struct page *page, unsigned long flags,
4448 int start_bitidx, int end_bitidx)
4451 unsigned long *bitmap;
4452 unsigned long pfn, bitidx;
4453 unsigned long value = 1;
4455 zone = page_zone(page);
4456 pfn = page_to_pfn(page);
4457 bitmap = get_pageblock_bitmap(zone, pfn);
4458 bitidx = pfn_to_bitidx(zone, pfn);
4460 for (; start_bitidx <= end_bitidx; start_bitidx++, value <<= 1)
4462 __set_bit(bitidx + start_bitidx, bitmap);
4464 __clear_bit(bitidx + start_bitidx, bitmap);