mm, x86: remove MEMORY_HOTPLUG_RESERVE related code
[linux-2.6/kvm.git] / mm / page_alloc.c
blob474c7e9dd51ac66f97b027bf5b384a1bacd42da7
1 /*
2 * linux/mm/page_alloc.c
4 * Manages the free list, the system allocates free pages here.
5 * Note that kmalloc() lives in slab.c
7 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
8 * Swap reorganised 29.12.95, Stephen Tweedie
9 * Support of BIGMEM added by Gerhard Wichert, Siemens AG, July 1999
10 * Reshaped it to be a zoned allocator, Ingo Molnar, Red Hat, 1999
11 * Discontiguous memory support, Kanoj Sarcar, SGI, Nov 1999
12 * Zone balancing, Kanoj Sarcar, SGI, Jan 2000
13 * Per cpu hot/cold page lists, bulk allocation, Martin J. Bligh, Sept 2002
14 * (lots of bits borrowed from Ingo Molnar & Andrew Morton)
17 #include <linux/stddef.h>
18 #include <linux/mm.h>
19 #include <linux/swap.h>
20 #include <linux/interrupt.h>
21 #include <linux/pagemap.h>
22 #include <linux/jiffies.h>
23 #include <linux/bootmem.h>
24 #include <linux/compiler.h>
25 #include <linux/kernel.h>
26 #include <linux/module.h>
27 #include <linux/suspend.h>
28 #include <linux/pagevec.h>
29 #include <linux/blkdev.h>
30 #include <linux/slab.h>
31 #include <linux/oom.h>
32 #include <linux/notifier.h>
33 #include <linux/topology.h>
34 #include <linux/sysctl.h>
35 #include <linux/cpu.h>
36 #include <linux/cpuset.h>
37 #include <linux/memory_hotplug.h>
38 #include <linux/nodemask.h>
39 #include <linux/vmalloc.h>
40 #include <linux/mempolicy.h>
41 #include <linux/stop_machine.h>
42 #include <linux/sort.h>
43 #include <linux/pfn.h>
44 #include <linux/backing-dev.h>
45 #include <linux/fault-inject.h>
46 #include <linux/page-isolation.h>
47 #include <linux/page_cgroup.h>
48 #include <linux/debugobjects.h>
50 #include <asm/tlbflush.h>
51 #include <asm/div64.h>
52 #include "internal.h"
55 * Array of node states.
57 nodemask_t node_states[NR_NODE_STATES] __read_mostly = {
58 [N_POSSIBLE] = NODE_MASK_ALL,
59 [N_ONLINE] = { { [0] = 1UL } },
60 #ifndef CONFIG_NUMA
61 [N_NORMAL_MEMORY] = { { [0] = 1UL } },
62 #ifdef CONFIG_HIGHMEM
63 [N_HIGH_MEMORY] = { { [0] = 1UL } },
64 #endif
65 [N_CPU] = { { [0] = 1UL } },
66 #endif /* NUMA */
68 EXPORT_SYMBOL(node_states);
70 unsigned long totalram_pages __read_mostly;
71 unsigned long totalreserve_pages __read_mostly;
72 unsigned long highest_memmap_pfn __read_mostly;
73 int percpu_pagelist_fraction;
75 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
76 int pageblock_order __read_mostly;
77 #endif
79 static void __free_pages_ok(struct page *page, unsigned int order);
82 * results with 256, 32 in the lowmem_reserve sysctl:
83 * 1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
84 * 1G machine -> (16M dma, 784M normal, 224M high)
85 * NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
86 * HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
87 * HIGHMEM allocation will (224M+784M)/256 of ram reserved in ZONE_DMA
89 * TBD: should special case ZONE_DMA32 machines here - in those we normally
90 * don't need any ZONE_NORMAL reservation
92 int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES-1] = {
93 #ifdef CONFIG_ZONE_DMA
94 256,
95 #endif
96 #ifdef CONFIG_ZONE_DMA32
97 256,
98 #endif
99 #ifdef CONFIG_HIGHMEM
101 #endif
105 EXPORT_SYMBOL(totalram_pages);
107 static char * const zone_names[MAX_NR_ZONES] = {
108 #ifdef CONFIG_ZONE_DMA
109 "DMA",
110 #endif
111 #ifdef CONFIG_ZONE_DMA32
112 "DMA32",
113 #endif
114 "Normal",
115 #ifdef CONFIG_HIGHMEM
116 "HighMem",
117 #endif
118 "Movable",
121 int min_free_kbytes = 1024;
123 unsigned long __meminitdata nr_kernel_pages;
124 unsigned long __meminitdata nr_all_pages;
125 static unsigned long __meminitdata dma_reserve;
127 #ifdef CONFIG_ARCH_POPULATES_NODE_MAP
129 * MAX_ACTIVE_REGIONS determines the maximum number of distinct
130 * ranges of memory (RAM) that may be registered with add_active_range().
131 * Ranges passed to add_active_range() will be merged if possible
132 * so the number of times add_active_range() can be called is
133 * related to the number of nodes and the number of holes
135 #ifdef CONFIG_MAX_ACTIVE_REGIONS
136 /* Allow an architecture to set MAX_ACTIVE_REGIONS to save memory */
137 #define MAX_ACTIVE_REGIONS CONFIG_MAX_ACTIVE_REGIONS
138 #else
139 #if MAX_NUMNODES >= 32
140 /* If there can be many nodes, allow up to 50 holes per node */
141 #define MAX_ACTIVE_REGIONS (MAX_NUMNODES*50)
142 #else
143 /* By default, allow up to 256 distinct regions */
144 #define MAX_ACTIVE_REGIONS 256
145 #endif
146 #endif
148 static struct node_active_region __meminitdata early_node_map[MAX_ACTIVE_REGIONS];
149 static int __meminitdata nr_nodemap_entries;
150 static unsigned long __meminitdata arch_zone_lowest_possible_pfn[MAX_NR_ZONES];
151 static unsigned long __meminitdata arch_zone_highest_possible_pfn[MAX_NR_ZONES];
152 static unsigned long __initdata required_kernelcore;
153 static unsigned long __initdata required_movablecore;
154 static unsigned long __meminitdata zone_movable_pfn[MAX_NUMNODES];
156 /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
157 int movable_zone;
158 EXPORT_SYMBOL(movable_zone);
159 #endif /* CONFIG_ARCH_POPULATES_NODE_MAP */
161 #if MAX_NUMNODES > 1
162 int nr_node_ids __read_mostly = MAX_NUMNODES;
163 EXPORT_SYMBOL(nr_node_ids);
164 #endif
166 int page_group_by_mobility_disabled __read_mostly;
168 static void set_pageblock_migratetype(struct page *page, int migratetype)
170 set_pageblock_flags_group(page, (unsigned long)migratetype,
171 PB_migrate, PB_migrate_end);
174 #ifdef CONFIG_DEBUG_VM
175 static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
177 int ret = 0;
178 unsigned seq;
179 unsigned long pfn = page_to_pfn(page);
181 do {
182 seq = zone_span_seqbegin(zone);
183 if (pfn >= zone->zone_start_pfn + zone->spanned_pages)
184 ret = 1;
185 else if (pfn < zone->zone_start_pfn)
186 ret = 1;
187 } while (zone_span_seqretry(zone, seq));
189 return ret;
192 static int page_is_consistent(struct zone *zone, struct page *page)
194 if (!pfn_valid_within(page_to_pfn(page)))
195 return 0;
196 if (zone != page_zone(page))
197 return 0;
199 return 1;
202 * Temporary debugging check for pages not lying within a given zone.
204 static int bad_range(struct zone *zone, struct page *page)
206 if (page_outside_zone_boundaries(zone, page))
207 return 1;
208 if (!page_is_consistent(zone, page))
209 return 1;
211 return 0;
213 #else
214 static inline int bad_range(struct zone *zone, struct page *page)
216 return 0;
218 #endif
220 static void bad_page(struct page *page)
222 static unsigned long resume;
223 static unsigned long nr_shown;
224 static unsigned long nr_unshown;
227 * Allow a burst of 60 reports, then keep quiet for that minute;
228 * or allow a steady drip of one report per second.
230 if (nr_shown == 60) {
231 if (time_before(jiffies, resume)) {
232 nr_unshown++;
233 goto out;
235 if (nr_unshown) {
236 printk(KERN_ALERT
237 "BUG: Bad page state: %lu messages suppressed\n",
238 nr_unshown);
239 nr_unshown = 0;
241 nr_shown = 0;
243 if (nr_shown++ == 0)
244 resume = jiffies + 60 * HZ;
246 printk(KERN_ALERT "BUG: Bad page state in process %s pfn:%05lx\n",
247 current->comm, page_to_pfn(page));
248 printk(KERN_ALERT
249 "page:%p flags:%p count:%d mapcount:%d mapping:%p index:%lx\n",
250 page, (void *)page->flags, page_count(page),
251 page_mapcount(page), page->mapping, page->index);
253 dump_stack();
254 out:
255 /* Leave bad fields for debug, except PageBuddy could make trouble */
256 __ClearPageBuddy(page);
257 add_taint(TAINT_BAD_PAGE);
261 * Higher-order pages are called "compound pages". They are structured thusly:
263 * The first PAGE_SIZE page is called the "head page".
265 * The remaining PAGE_SIZE pages are called "tail pages".
267 * All pages have PG_compound set. All pages have their ->private pointing at
268 * the head page (even the head page has this).
270 * The first tail page's ->lru.next holds the address of the compound page's
271 * put_page() function. Its ->lru.prev holds the order of allocation.
272 * This usage means that zero-order pages may not be compound.
275 static void free_compound_page(struct page *page)
277 __free_pages_ok(page, compound_order(page));
280 void prep_compound_page(struct page *page, unsigned long order)
282 int i;
283 int nr_pages = 1 << order;
285 set_compound_page_dtor(page, free_compound_page);
286 set_compound_order(page, order);
287 __SetPageHead(page);
288 for (i = 1; i < nr_pages; i++) {
289 struct page *p = page + i;
291 __SetPageTail(p);
292 p->first_page = page;
296 #ifdef CONFIG_HUGETLBFS
297 void prep_compound_gigantic_page(struct page *page, unsigned long order)
299 int i;
300 int nr_pages = 1 << order;
301 struct page *p = page + 1;
303 set_compound_page_dtor(page, free_compound_page);
304 set_compound_order(page, order);
305 __SetPageHead(page);
306 for (i = 1; i < nr_pages; i++, p = mem_map_next(p, page, i)) {
307 __SetPageTail(p);
308 p->first_page = page;
311 #endif
313 static int destroy_compound_page(struct page *page, unsigned long order)
315 int i;
316 int nr_pages = 1 << order;
317 int bad = 0;
319 if (unlikely(compound_order(page) != order) ||
320 unlikely(!PageHead(page))) {
321 bad_page(page);
322 bad++;
325 __ClearPageHead(page);
327 for (i = 1; i < nr_pages; i++) {
328 struct page *p = page + i;
330 if (unlikely(!PageTail(p) || (p->first_page != page))) {
331 bad_page(page);
332 bad++;
334 __ClearPageTail(p);
337 return bad;
340 static inline void prep_zero_page(struct page *page, int order, gfp_t gfp_flags)
342 int i;
345 * clear_highpage() will use KM_USER0, so it's a bug to use __GFP_ZERO
346 * and __GFP_HIGHMEM from hard or soft interrupt context.
348 VM_BUG_ON((gfp_flags & __GFP_HIGHMEM) && in_interrupt());
349 for (i = 0; i < (1 << order); i++)
350 clear_highpage(page + i);
353 static inline void set_page_order(struct page *page, int order)
355 set_page_private(page, order);
356 __SetPageBuddy(page);
359 static inline void rmv_page_order(struct page *page)
361 __ClearPageBuddy(page);
362 set_page_private(page, 0);
366 * Locate the struct page for both the matching buddy in our
367 * pair (buddy1) and the combined O(n+1) page they form (page).
369 * 1) Any buddy B1 will have an order O twin B2 which satisfies
370 * the following equation:
371 * B2 = B1 ^ (1 << O)
372 * For example, if the starting buddy (buddy2) is #8 its order
373 * 1 buddy is #10:
374 * B2 = 8 ^ (1 << 1) = 8 ^ 2 = 10
376 * 2) Any buddy B will have an order O+1 parent P which
377 * satisfies the following equation:
378 * P = B & ~(1 << O)
380 * Assumption: *_mem_map is contiguous at least up to MAX_ORDER
382 static inline struct page *
383 __page_find_buddy(struct page *page, unsigned long page_idx, unsigned int order)
385 unsigned long buddy_idx = page_idx ^ (1 << order);
387 return page + (buddy_idx - page_idx);
390 static inline unsigned long
391 __find_combined_index(unsigned long page_idx, unsigned int order)
393 return (page_idx & ~(1 << order));
397 * This function checks whether a page is free && is the buddy
398 * we can do coalesce a page and its buddy if
399 * (a) the buddy is not in a hole &&
400 * (b) the buddy is in the buddy system &&
401 * (c) a page and its buddy have the same order &&
402 * (d) a page and its buddy are in the same zone.
404 * For recording whether a page is in the buddy system, we use PG_buddy.
405 * Setting, clearing, and testing PG_buddy is serialized by zone->lock.
407 * For recording page's order, we use page_private(page).
409 static inline int page_is_buddy(struct page *page, struct page *buddy,
410 int order)
412 if (!pfn_valid_within(page_to_pfn(buddy)))
413 return 0;
415 if (page_zone_id(page) != page_zone_id(buddy))
416 return 0;
418 if (PageBuddy(buddy) && page_order(buddy) == order) {
419 BUG_ON(page_count(buddy) != 0);
420 return 1;
422 return 0;
426 * Freeing function for a buddy system allocator.
428 * The concept of a buddy system is to maintain direct-mapped table
429 * (containing bit values) for memory blocks of various "orders".
430 * The bottom level table contains the map for the smallest allocatable
431 * units of memory (here, pages), and each level above it describes
432 * pairs of units from the levels below, hence, "buddies".
433 * At a high level, all that happens here is marking the table entry
434 * at the bottom level available, and propagating the changes upward
435 * as necessary, plus some accounting needed to play nicely with other
436 * parts of the VM system.
437 * At each level, we keep a list of pages, which are heads of continuous
438 * free pages of length of (1 << order) and marked with PG_buddy. Page's
439 * order is recorded in page_private(page) field.
440 * So when we are allocating or freeing one, we can derive the state of the
441 * other. That is, if we allocate a small block, and both were
442 * free, the remainder of the region must be split into blocks.
443 * If a block is freed, and its buddy is also free, then this
444 * triggers coalescing into a block of larger size.
446 * -- wli
449 static inline void __free_one_page(struct page *page,
450 struct zone *zone, unsigned int order)
452 unsigned long page_idx;
453 int order_size = 1 << order;
454 int migratetype = get_pageblock_migratetype(page);
456 if (unlikely(PageCompound(page)))
457 if (unlikely(destroy_compound_page(page, order)))
458 return;
460 page_idx = page_to_pfn(page) & ((1 << MAX_ORDER) - 1);
462 VM_BUG_ON(page_idx & (order_size - 1));
463 VM_BUG_ON(bad_range(zone, page));
465 __mod_zone_page_state(zone, NR_FREE_PAGES, order_size);
466 while (order < MAX_ORDER-1) {
467 unsigned long combined_idx;
468 struct page *buddy;
470 buddy = __page_find_buddy(page, page_idx, order);
471 if (!page_is_buddy(page, buddy, order))
472 break;
474 /* Our buddy is free, merge with it and move up one order. */
475 list_del(&buddy->lru);
476 zone->free_area[order].nr_free--;
477 rmv_page_order(buddy);
478 combined_idx = __find_combined_index(page_idx, order);
479 page = page + (combined_idx - page_idx);
480 page_idx = combined_idx;
481 order++;
483 set_page_order(page, order);
484 list_add(&page->lru,
485 &zone->free_area[order].free_list[migratetype]);
486 zone->free_area[order].nr_free++;
489 static inline int free_pages_check(struct page *page)
491 free_page_mlock(page);
492 if (unlikely(page_mapcount(page) |
493 (page->mapping != NULL) |
494 (page_count(page) != 0) |
495 (page->flags & PAGE_FLAGS_CHECK_AT_FREE))) {
496 bad_page(page);
497 return 1;
499 if (page->flags & PAGE_FLAGS_CHECK_AT_PREP)
500 page->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
501 return 0;
505 * Frees a list of pages.
506 * Assumes all pages on list are in same zone, and of same order.
507 * count is the number of pages to free.
509 * If the zone was previously in an "all pages pinned" state then look to
510 * see if this freeing clears that state.
512 * And clear the zone's pages_scanned counter, to hold off the "all pages are
513 * pinned" detection logic.
515 static void free_pages_bulk(struct zone *zone, int count,
516 struct list_head *list, int order)
518 spin_lock(&zone->lock);
519 zone_clear_flag(zone, ZONE_ALL_UNRECLAIMABLE);
520 zone->pages_scanned = 0;
521 while (count--) {
522 struct page *page;
524 VM_BUG_ON(list_empty(list));
525 page = list_entry(list->prev, struct page, lru);
526 /* have to delete it as __free_one_page list manipulates */
527 list_del(&page->lru);
528 __free_one_page(page, zone, order);
530 spin_unlock(&zone->lock);
533 static void free_one_page(struct zone *zone, struct page *page, int order)
535 spin_lock(&zone->lock);
536 zone_clear_flag(zone, ZONE_ALL_UNRECLAIMABLE);
537 zone->pages_scanned = 0;
538 __free_one_page(page, zone, order);
539 spin_unlock(&zone->lock);
542 static void __free_pages_ok(struct page *page, unsigned int order)
544 unsigned long flags;
545 int i;
546 int bad = 0;
548 for (i = 0 ; i < (1 << order) ; ++i)
549 bad += free_pages_check(page + i);
550 if (bad)
551 return;
553 if (!PageHighMem(page)) {
554 debug_check_no_locks_freed(page_address(page),PAGE_SIZE<<order);
555 debug_check_no_obj_freed(page_address(page),
556 PAGE_SIZE << order);
558 arch_free_page(page, order);
559 kernel_map_pages(page, 1 << order, 0);
561 local_irq_save(flags);
562 __count_vm_events(PGFREE, 1 << order);
563 free_one_page(page_zone(page), page, order);
564 local_irq_restore(flags);
568 * permit the bootmem allocator to evade page validation on high-order frees
570 void __meminit __free_pages_bootmem(struct page *page, unsigned int order)
572 if (order == 0) {
573 __ClearPageReserved(page);
574 set_page_count(page, 0);
575 set_page_refcounted(page);
576 __free_page(page);
577 } else {
578 int loop;
580 prefetchw(page);
581 for (loop = 0; loop < BITS_PER_LONG; loop++) {
582 struct page *p = &page[loop];
584 if (loop + 1 < BITS_PER_LONG)
585 prefetchw(p + 1);
586 __ClearPageReserved(p);
587 set_page_count(p, 0);
590 set_page_refcounted(page);
591 __free_pages(page, order);
597 * The order of subdivision here is critical for the IO subsystem.
598 * Please do not alter this order without good reasons and regression
599 * testing. Specifically, as large blocks of memory are subdivided,
600 * the order in which smaller blocks are delivered depends on the order
601 * they're subdivided in this function. This is the primary factor
602 * influencing the order in which pages are delivered to the IO
603 * subsystem according to empirical testing, and this is also justified
604 * by considering the behavior of a buddy system containing a single
605 * large block of memory acted on by a series of small allocations.
606 * This behavior is a critical factor in sglist merging's success.
608 * -- wli
610 static inline void expand(struct zone *zone, struct page *page,
611 int low, int high, struct free_area *area,
612 int migratetype)
614 unsigned long size = 1 << high;
616 while (high > low) {
617 area--;
618 high--;
619 size >>= 1;
620 VM_BUG_ON(bad_range(zone, &page[size]));
621 list_add(&page[size].lru, &area->free_list[migratetype]);
622 area->nr_free++;
623 set_page_order(&page[size], high);
628 * This page is about to be returned from the page allocator
630 static int prep_new_page(struct page *page, int order, gfp_t gfp_flags)
632 if (unlikely(page_mapcount(page) |
633 (page->mapping != NULL) |
634 (page_count(page) != 0) |
635 (page->flags & PAGE_FLAGS_CHECK_AT_PREP))) {
636 bad_page(page);
637 return 1;
640 set_page_private(page, 0);
641 set_page_refcounted(page);
643 arch_alloc_page(page, order);
644 kernel_map_pages(page, 1 << order, 1);
646 if (gfp_flags & __GFP_ZERO)
647 prep_zero_page(page, order, gfp_flags);
649 if (order && (gfp_flags & __GFP_COMP))
650 prep_compound_page(page, order);
652 return 0;
656 * Go through the free lists for the given migratetype and remove
657 * the smallest available page from the freelists
659 static struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
660 int migratetype)
662 unsigned int current_order;
663 struct free_area * area;
664 struct page *page;
666 /* Find a page of the appropriate size in the preferred list */
667 for (current_order = order; current_order < MAX_ORDER; ++current_order) {
668 area = &(zone->free_area[current_order]);
669 if (list_empty(&area->free_list[migratetype]))
670 continue;
672 page = list_entry(area->free_list[migratetype].next,
673 struct page, lru);
674 list_del(&page->lru);
675 rmv_page_order(page);
676 area->nr_free--;
677 __mod_zone_page_state(zone, NR_FREE_PAGES, - (1UL << order));
678 expand(zone, page, order, current_order, area, migratetype);
679 return page;
682 return NULL;
687 * This array describes the order lists are fallen back to when
688 * the free lists for the desirable migrate type are depleted
690 static int fallbacks[MIGRATE_TYPES][MIGRATE_TYPES-1] = {
691 [MIGRATE_UNMOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE, MIGRATE_RESERVE },
692 [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE, MIGRATE_MOVABLE, MIGRATE_RESERVE },
693 [MIGRATE_MOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_RESERVE },
694 [MIGRATE_RESERVE] = { MIGRATE_RESERVE, MIGRATE_RESERVE, MIGRATE_RESERVE }, /* Never used */
698 * Move the free pages in a range to the free lists of the requested type.
699 * Note that start_page and end_pages are not aligned on a pageblock
700 * boundary. If alignment is required, use move_freepages_block()
702 static int move_freepages(struct zone *zone,
703 struct page *start_page, struct page *end_page,
704 int migratetype)
706 struct page *page;
707 unsigned long order;
708 int pages_moved = 0;
710 #ifndef CONFIG_HOLES_IN_ZONE
712 * page_zone is not safe to call in this context when
713 * CONFIG_HOLES_IN_ZONE is set. This bug check is probably redundant
714 * anyway as we check zone boundaries in move_freepages_block().
715 * Remove at a later date when no bug reports exist related to
716 * grouping pages by mobility
718 BUG_ON(page_zone(start_page) != page_zone(end_page));
719 #endif
721 for (page = start_page; page <= end_page;) {
722 /* Make sure we are not inadvertently changing nodes */
723 VM_BUG_ON(page_to_nid(page) != zone_to_nid(zone));
725 if (!pfn_valid_within(page_to_pfn(page))) {
726 page++;
727 continue;
730 if (!PageBuddy(page)) {
731 page++;
732 continue;
735 order = page_order(page);
736 list_del(&page->lru);
737 list_add(&page->lru,
738 &zone->free_area[order].free_list[migratetype]);
739 page += 1 << order;
740 pages_moved += 1 << order;
743 return pages_moved;
746 static int move_freepages_block(struct zone *zone, struct page *page,
747 int migratetype)
749 unsigned long start_pfn, end_pfn;
750 struct page *start_page, *end_page;
752 start_pfn = page_to_pfn(page);
753 start_pfn = start_pfn & ~(pageblock_nr_pages-1);
754 start_page = pfn_to_page(start_pfn);
755 end_page = start_page + pageblock_nr_pages - 1;
756 end_pfn = start_pfn + pageblock_nr_pages - 1;
758 /* Do not cross zone boundaries */
759 if (start_pfn < zone->zone_start_pfn)
760 start_page = page;
761 if (end_pfn >= zone->zone_start_pfn + zone->spanned_pages)
762 return 0;
764 return move_freepages(zone, start_page, end_page, migratetype);
767 /* Remove an element from the buddy allocator from the fallback list */
768 static struct page *__rmqueue_fallback(struct zone *zone, int order,
769 int start_migratetype)
771 struct free_area * area;
772 int current_order;
773 struct page *page;
774 int migratetype, i;
776 /* Find the largest possible block of pages in the other list */
777 for (current_order = MAX_ORDER-1; current_order >= order;
778 --current_order) {
779 for (i = 0; i < MIGRATE_TYPES - 1; i++) {
780 migratetype = fallbacks[start_migratetype][i];
782 /* MIGRATE_RESERVE handled later if necessary */
783 if (migratetype == MIGRATE_RESERVE)
784 continue;
786 area = &(zone->free_area[current_order]);
787 if (list_empty(&area->free_list[migratetype]))
788 continue;
790 page = list_entry(area->free_list[migratetype].next,
791 struct page, lru);
792 area->nr_free--;
795 * If breaking a large block of pages, move all free
796 * pages to the preferred allocation list. If falling
797 * back for a reclaimable kernel allocation, be more
798 * agressive about taking ownership of free pages
800 if (unlikely(current_order >= (pageblock_order >> 1)) ||
801 start_migratetype == MIGRATE_RECLAIMABLE) {
802 unsigned long pages;
803 pages = move_freepages_block(zone, page,
804 start_migratetype);
806 /* Claim the whole block if over half of it is free */
807 if (pages >= (1 << (pageblock_order-1)))
808 set_pageblock_migratetype(page,
809 start_migratetype);
811 migratetype = start_migratetype;
814 /* Remove the page from the freelists */
815 list_del(&page->lru);
816 rmv_page_order(page);
817 __mod_zone_page_state(zone, NR_FREE_PAGES,
818 -(1UL << order));
820 if (current_order == pageblock_order)
821 set_pageblock_migratetype(page,
822 start_migratetype);
824 expand(zone, page, order, current_order, area, migratetype);
825 return page;
829 /* Use MIGRATE_RESERVE rather than fail an allocation */
830 return __rmqueue_smallest(zone, order, MIGRATE_RESERVE);
834 * Do the hard work of removing an element from the buddy allocator.
835 * Call me with the zone->lock already held.
837 static struct page *__rmqueue(struct zone *zone, unsigned int order,
838 int migratetype)
840 struct page *page;
842 page = __rmqueue_smallest(zone, order, migratetype);
844 if (unlikely(!page))
845 page = __rmqueue_fallback(zone, order, migratetype);
847 return page;
851 * Obtain a specified number of elements from the buddy allocator, all under
852 * a single hold of the lock, for efficiency. Add them to the supplied list.
853 * Returns the number of new pages which were placed at *list.
855 static int rmqueue_bulk(struct zone *zone, unsigned int order,
856 unsigned long count, struct list_head *list,
857 int migratetype)
859 int i;
861 spin_lock(&zone->lock);
862 for (i = 0; i < count; ++i) {
863 struct page *page = __rmqueue(zone, order, migratetype);
864 if (unlikely(page == NULL))
865 break;
868 * Split buddy pages returned by expand() are received here
869 * in physical page order. The page is added to the callers and
870 * list and the list head then moves forward. From the callers
871 * perspective, the linked list is ordered by page number in
872 * some conditions. This is useful for IO devices that can
873 * merge IO requests if the physical pages are ordered
874 * properly.
876 list_add(&page->lru, list);
877 set_page_private(page, migratetype);
878 list = &page->lru;
880 spin_unlock(&zone->lock);
881 return i;
884 #ifdef CONFIG_NUMA
886 * Called from the vmstat counter updater to drain pagesets of this
887 * currently executing processor on remote nodes after they have
888 * expired.
890 * Note that this function must be called with the thread pinned to
891 * a single processor.
893 void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp)
895 unsigned long flags;
896 int to_drain;
898 local_irq_save(flags);
899 if (pcp->count >= pcp->batch)
900 to_drain = pcp->batch;
901 else
902 to_drain = pcp->count;
903 free_pages_bulk(zone, to_drain, &pcp->list, 0);
904 pcp->count -= to_drain;
905 local_irq_restore(flags);
907 #endif
910 * Drain pages of the indicated processor.
912 * The processor must either be the current processor and the
913 * thread pinned to the current processor or a processor that
914 * is not online.
916 static void drain_pages(unsigned int cpu)
918 unsigned long flags;
919 struct zone *zone;
921 for_each_populated_zone(zone) {
922 struct per_cpu_pageset *pset;
923 struct per_cpu_pages *pcp;
925 pset = zone_pcp(zone, cpu);
927 pcp = &pset->pcp;
928 local_irq_save(flags);
929 free_pages_bulk(zone, pcp->count, &pcp->list, 0);
930 pcp->count = 0;
931 local_irq_restore(flags);
936 * Spill all of this CPU's per-cpu pages back into the buddy allocator.
938 void drain_local_pages(void *arg)
940 drain_pages(smp_processor_id());
944 * Spill all the per-cpu pages from all CPUs back into the buddy allocator
946 void drain_all_pages(void)
948 on_each_cpu(drain_local_pages, NULL, 1);
951 #ifdef CONFIG_HIBERNATION
953 void mark_free_pages(struct zone *zone)
955 unsigned long pfn, max_zone_pfn;
956 unsigned long flags;
957 int order, t;
958 struct list_head *curr;
960 if (!zone->spanned_pages)
961 return;
963 spin_lock_irqsave(&zone->lock, flags);
965 max_zone_pfn = zone->zone_start_pfn + zone->spanned_pages;
966 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
967 if (pfn_valid(pfn)) {
968 struct page *page = pfn_to_page(pfn);
970 if (!swsusp_page_is_forbidden(page))
971 swsusp_unset_page_free(page);
974 for_each_migratetype_order(order, t) {
975 list_for_each(curr, &zone->free_area[order].free_list[t]) {
976 unsigned long i;
978 pfn = page_to_pfn(list_entry(curr, struct page, lru));
979 for (i = 0; i < (1UL << order); i++)
980 swsusp_set_page_free(pfn_to_page(pfn + i));
983 spin_unlock_irqrestore(&zone->lock, flags);
985 #endif /* CONFIG_PM */
988 * Free a 0-order page
990 static void free_hot_cold_page(struct page *page, int cold)
992 struct zone *zone = page_zone(page);
993 struct per_cpu_pages *pcp;
994 unsigned long flags;
996 if (PageAnon(page))
997 page->mapping = NULL;
998 if (free_pages_check(page))
999 return;
1001 if (!PageHighMem(page)) {
1002 debug_check_no_locks_freed(page_address(page), PAGE_SIZE);
1003 debug_check_no_obj_freed(page_address(page), PAGE_SIZE);
1005 arch_free_page(page, 0);
1006 kernel_map_pages(page, 1, 0);
1008 pcp = &zone_pcp(zone, get_cpu())->pcp;
1009 local_irq_save(flags);
1010 __count_vm_event(PGFREE);
1011 if (cold)
1012 list_add_tail(&page->lru, &pcp->list);
1013 else
1014 list_add(&page->lru, &pcp->list);
1015 set_page_private(page, get_pageblock_migratetype(page));
1016 pcp->count++;
1017 if (pcp->count >= pcp->high) {
1018 free_pages_bulk(zone, pcp->batch, &pcp->list, 0);
1019 pcp->count -= pcp->batch;
1021 local_irq_restore(flags);
1022 put_cpu();
1025 void free_hot_page(struct page *page)
1027 free_hot_cold_page(page, 0);
1030 void free_cold_page(struct page *page)
1032 free_hot_cold_page(page, 1);
1036 * split_page takes a non-compound higher-order page, and splits it into
1037 * n (1<<order) sub-pages: page[0..n]
1038 * Each sub-page must be freed individually.
1040 * Note: this is probably too low level an operation for use in drivers.
1041 * Please consult with lkml before using this in your driver.
1043 void split_page(struct page *page, unsigned int order)
1045 int i;
1047 VM_BUG_ON(PageCompound(page));
1048 VM_BUG_ON(!page_count(page));
1049 for (i = 1; i < (1 << order); i++)
1050 set_page_refcounted(page + i);
1054 * Really, prep_compound_page() should be called from __rmqueue_bulk(). But
1055 * we cheat by calling it from here, in the order > 0 path. Saves a branch
1056 * or two.
1058 static struct page *buffered_rmqueue(struct zone *preferred_zone,
1059 struct zone *zone, int order, gfp_t gfp_flags)
1061 unsigned long flags;
1062 struct page *page;
1063 int cold = !!(gfp_flags & __GFP_COLD);
1064 int cpu;
1065 int migratetype = allocflags_to_migratetype(gfp_flags);
1067 again:
1068 cpu = get_cpu();
1069 if (likely(order == 0)) {
1070 struct per_cpu_pages *pcp;
1072 pcp = &zone_pcp(zone, cpu)->pcp;
1073 local_irq_save(flags);
1074 if (!pcp->count) {
1075 pcp->count = rmqueue_bulk(zone, 0,
1076 pcp->batch, &pcp->list, migratetype);
1077 if (unlikely(!pcp->count))
1078 goto failed;
1081 /* Find a page of the appropriate migrate type */
1082 if (cold) {
1083 list_for_each_entry_reverse(page, &pcp->list, lru)
1084 if (page_private(page) == migratetype)
1085 break;
1086 } else {
1087 list_for_each_entry(page, &pcp->list, lru)
1088 if (page_private(page) == migratetype)
1089 break;
1092 /* Allocate more to the pcp list if necessary */
1093 if (unlikely(&page->lru == &pcp->list)) {
1094 pcp->count += rmqueue_bulk(zone, 0,
1095 pcp->batch, &pcp->list, migratetype);
1096 page = list_entry(pcp->list.next, struct page, lru);
1099 list_del(&page->lru);
1100 pcp->count--;
1101 } else {
1102 spin_lock_irqsave(&zone->lock, flags);
1103 page = __rmqueue(zone, order, migratetype);
1104 spin_unlock(&zone->lock);
1105 if (!page)
1106 goto failed;
1109 __count_zone_vm_events(PGALLOC, zone, 1 << order);
1110 zone_statistics(preferred_zone, zone);
1111 local_irq_restore(flags);
1112 put_cpu();
1114 VM_BUG_ON(bad_range(zone, page));
1115 if (prep_new_page(page, order, gfp_flags))
1116 goto again;
1117 return page;
1119 failed:
1120 local_irq_restore(flags);
1121 put_cpu();
1122 return NULL;
1125 #define ALLOC_NO_WATERMARKS 0x01 /* don't check watermarks at all */
1126 #define ALLOC_WMARK_MIN 0x02 /* use pages_min watermark */
1127 #define ALLOC_WMARK_LOW 0x04 /* use pages_low watermark */
1128 #define ALLOC_WMARK_HIGH 0x08 /* use pages_high watermark */
1129 #define ALLOC_HARDER 0x10 /* try to alloc harder */
1130 #define ALLOC_HIGH 0x20 /* __GFP_HIGH set */
1131 #define ALLOC_CPUSET 0x40 /* check for correct cpuset */
1133 #ifdef CONFIG_FAIL_PAGE_ALLOC
1135 static struct fail_page_alloc_attr {
1136 struct fault_attr attr;
1138 u32 ignore_gfp_highmem;
1139 u32 ignore_gfp_wait;
1140 u32 min_order;
1142 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
1144 struct dentry *ignore_gfp_highmem_file;
1145 struct dentry *ignore_gfp_wait_file;
1146 struct dentry *min_order_file;
1148 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
1150 } fail_page_alloc = {
1151 .attr = FAULT_ATTR_INITIALIZER,
1152 .ignore_gfp_wait = 1,
1153 .ignore_gfp_highmem = 1,
1154 .min_order = 1,
1157 static int __init setup_fail_page_alloc(char *str)
1159 return setup_fault_attr(&fail_page_alloc.attr, str);
1161 __setup("fail_page_alloc=", setup_fail_page_alloc);
1163 static int should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
1165 if (order < fail_page_alloc.min_order)
1166 return 0;
1167 if (gfp_mask & __GFP_NOFAIL)
1168 return 0;
1169 if (fail_page_alloc.ignore_gfp_highmem && (gfp_mask & __GFP_HIGHMEM))
1170 return 0;
1171 if (fail_page_alloc.ignore_gfp_wait && (gfp_mask & __GFP_WAIT))
1172 return 0;
1174 return should_fail(&fail_page_alloc.attr, 1 << order);
1177 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
1179 static int __init fail_page_alloc_debugfs(void)
1181 mode_t mode = S_IFREG | S_IRUSR | S_IWUSR;
1182 struct dentry *dir;
1183 int err;
1185 err = init_fault_attr_dentries(&fail_page_alloc.attr,
1186 "fail_page_alloc");
1187 if (err)
1188 return err;
1189 dir = fail_page_alloc.attr.dentries.dir;
1191 fail_page_alloc.ignore_gfp_wait_file =
1192 debugfs_create_bool("ignore-gfp-wait", mode, dir,
1193 &fail_page_alloc.ignore_gfp_wait);
1195 fail_page_alloc.ignore_gfp_highmem_file =
1196 debugfs_create_bool("ignore-gfp-highmem", mode, dir,
1197 &fail_page_alloc.ignore_gfp_highmem);
1198 fail_page_alloc.min_order_file =
1199 debugfs_create_u32("min-order", mode, dir,
1200 &fail_page_alloc.min_order);
1202 if (!fail_page_alloc.ignore_gfp_wait_file ||
1203 !fail_page_alloc.ignore_gfp_highmem_file ||
1204 !fail_page_alloc.min_order_file) {
1205 err = -ENOMEM;
1206 debugfs_remove(fail_page_alloc.ignore_gfp_wait_file);
1207 debugfs_remove(fail_page_alloc.ignore_gfp_highmem_file);
1208 debugfs_remove(fail_page_alloc.min_order_file);
1209 cleanup_fault_attr_dentries(&fail_page_alloc.attr);
1212 return err;
1215 late_initcall(fail_page_alloc_debugfs);
1217 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
1219 #else /* CONFIG_FAIL_PAGE_ALLOC */
1221 static inline int should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
1223 return 0;
1226 #endif /* CONFIG_FAIL_PAGE_ALLOC */
1229 * Return 1 if free pages are above 'mark'. This takes into account the order
1230 * of the allocation.
1232 int zone_watermark_ok(struct zone *z, int order, unsigned long mark,
1233 int classzone_idx, int alloc_flags)
1235 /* free_pages my go negative - that's OK */
1236 long min = mark;
1237 long free_pages = zone_page_state(z, NR_FREE_PAGES) - (1 << order) + 1;
1238 int o;
1240 if (alloc_flags & ALLOC_HIGH)
1241 min -= min / 2;
1242 if (alloc_flags & ALLOC_HARDER)
1243 min -= min / 4;
1245 if (free_pages <= min + z->lowmem_reserve[classzone_idx])
1246 return 0;
1247 for (o = 0; o < order; o++) {
1248 /* At the next order, this order's pages become unavailable */
1249 free_pages -= z->free_area[o].nr_free << o;
1251 /* Require fewer higher order pages to be free */
1252 min >>= 1;
1254 if (free_pages <= min)
1255 return 0;
1257 return 1;
1260 #ifdef CONFIG_NUMA
1262 * zlc_setup - Setup for "zonelist cache". Uses cached zone data to
1263 * skip over zones that are not allowed by the cpuset, or that have
1264 * been recently (in last second) found to be nearly full. See further
1265 * comments in mmzone.h. Reduces cache footprint of zonelist scans
1266 * that have to skip over a lot of full or unallowed zones.
1268 * If the zonelist cache is present in the passed in zonelist, then
1269 * returns a pointer to the allowed node mask (either the current
1270 * tasks mems_allowed, or node_states[N_HIGH_MEMORY].)
1272 * If the zonelist cache is not available for this zonelist, does
1273 * nothing and returns NULL.
1275 * If the fullzones BITMAP in the zonelist cache is stale (more than
1276 * a second since last zap'd) then we zap it out (clear its bits.)
1278 * We hold off even calling zlc_setup, until after we've checked the
1279 * first zone in the zonelist, on the theory that most allocations will
1280 * be satisfied from that first zone, so best to examine that zone as
1281 * quickly as we can.
1283 static nodemask_t *zlc_setup(struct zonelist *zonelist, int alloc_flags)
1285 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1286 nodemask_t *allowednodes; /* zonelist_cache approximation */
1288 zlc = zonelist->zlcache_ptr;
1289 if (!zlc)
1290 return NULL;
1292 if (time_after(jiffies, zlc->last_full_zap + HZ)) {
1293 bitmap_zero(zlc->fullzones, MAX_ZONES_PER_ZONELIST);
1294 zlc->last_full_zap = jiffies;
1297 allowednodes = !in_interrupt() && (alloc_flags & ALLOC_CPUSET) ?
1298 &cpuset_current_mems_allowed :
1299 &node_states[N_HIGH_MEMORY];
1300 return allowednodes;
1304 * Given 'z' scanning a zonelist, run a couple of quick checks to see
1305 * if it is worth looking at further for free memory:
1306 * 1) Check that the zone isn't thought to be full (doesn't have its
1307 * bit set in the zonelist_cache fullzones BITMAP).
1308 * 2) Check that the zones node (obtained from the zonelist_cache
1309 * z_to_n[] mapping) is allowed in the passed in allowednodes mask.
1310 * Return true (non-zero) if zone is worth looking at further, or
1311 * else return false (zero) if it is not.
1313 * This check -ignores- the distinction between various watermarks,
1314 * such as GFP_HIGH, GFP_ATOMIC, PF_MEMALLOC, ... If a zone is
1315 * found to be full for any variation of these watermarks, it will
1316 * be considered full for up to one second by all requests, unless
1317 * we are so low on memory on all allowed nodes that we are forced
1318 * into the second scan of the zonelist.
1320 * In the second scan we ignore this zonelist cache and exactly
1321 * apply the watermarks to all zones, even it is slower to do so.
1322 * We are low on memory in the second scan, and should leave no stone
1323 * unturned looking for a free page.
1325 static int zlc_zone_worth_trying(struct zonelist *zonelist, struct zoneref *z,
1326 nodemask_t *allowednodes)
1328 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1329 int i; /* index of *z in zonelist zones */
1330 int n; /* node that zone *z is on */
1332 zlc = zonelist->zlcache_ptr;
1333 if (!zlc)
1334 return 1;
1336 i = z - zonelist->_zonerefs;
1337 n = zlc->z_to_n[i];
1339 /* This zone is worth trying if it is allowed but not full */
1340 return node_isset(n, *allowednodes) && !test_bit(i, zlc->fullzones);
1344 * Given 'z' scanning a zonelist, set the corresponding bit in
1345 * zlc->fullzones, so that subsequent attempts to allocate a page
1346 * from that zone don't waste time re-examining it.
1348 static void zlc_mark_zone_full(struct zonelist *zonelist, struct zoneref *z)
1350 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1351 int i; /* index of *z in zonelist zones */
1353 zlc = zonelist->zlcache_ptr;
1354 if (!zlc)
1355 return;
1357 i = z - zonelist->_zonerefs;
1359 set_bit(i, zlc->fullzones);
1362 #else /* CONFIG_NUMA */
1364 static nodemask_t *zlc_setup(struct zonelist *zonelist, int alloc_flags)
1366 return NULL;
1369 static int zlc_zone_worth_trying(struct zonelist *zonelist, struct zoneref *z,
1370 nodemask_t *allowednodes)
1372 return 1;
1375 static void zlc_mark_zone_full(struct zonelist *zonelist, struct zoneref *z)
1378 #endif /* CONFIG_NUMA */
1381 * get_page_from_freelist goes through the zonelist trying to allocate
1382 * a page.
1384 static struct page *
1385 get_page_from_freelist(gfp_t gfp_mask, nodemask_t *nodemask, unsigned int order,
1386 struct zonelist *zonelist, int high_zoneidx, int alloc_flags)
1388 struct zoneref *z;
1389 struct page *page = NULL;
1390 int classzone_idx;
1391 struct zone *zone, *preferred_zone;
1392 nodemask_t *allowednodes = NULL;/* zonelist_cache approximation */
1393 int zlc_active = 0; /* set if using zonelist_cache */
1394 int did_zlc_setup = 0; /* just call zlc_setup() one time */
1396 (void)first_zones_zonelist(zonelist, high_zoneidx, nodemask,
1397 &preferred_zone);
1398 if (!preferred_zone)
1399 return NULL;
1401 classzone_idx = zone_idx(preferred_zone);
1403 zonelist_scan:
1405 * Scan zonelist, looking for a zone with enough free.
1406 * See also cpuset_zone_allowed() comment in kernel/cpuset.c.
1408 for_each_zone_zonelist_nodemask(zone, z, zonelist,
1409 high_zoneidx, nodemask) {
1410 if (NUMA_BUILD && zlc_active &&
1411 !zlc_zone_worth_trying(zonelist, z, allowednodes))
1412 continue;
1413 if ((alloc_flags & ALLOC_CPUSET) &&
1414 !cpuset_zone_allowed_softwall(zone, gfp_mask))
1415 goto try_next_zone;
1417 if (!(alloc_flags & ALLOC_NO_WATERMARKS)) {
1418 unsigned long mark;
1419 if (alloc_flags & ALLOC_WMARK_MIN)
1420 mark = zone->pages_min;
1421 else if (alloc_flags & ALLOC_WMARK_LOW)
1422 mark = zone->pages_low;
1423 else
1424 mark = zone->pages_high;
1425 if (!zone_watermark_ok(zone, order, mark,
1426 classzone_idx, alloc_flags)) {
1427 if (!zone_reclaim_mode ||
1428 !zone_reclaim(zone, gfp_mask, order))
1429 goto this_zone_full;
1433 page = buffered_rmqueue(preferred_zone, zone, order, gfp_mask);
1434 if (page)
1435 break;
1436 this_zone_full:
1437 if (NUMA_BUILD)
1438 zlc_mark_zone_full(zonelist, z);
1439 try_next_zone:
1440 if (NUMA_BUILD && !did_zlc_setup) {
1441 /* we do zlc_setup after the first zone is tried */
1442 allowednodes = zlc_setup(zonelist, alloc_flags);
1443 zlc_active = 1;
1444 did_zlc_setup = 1;
1448 if (unlikely(NUMA_BUILD && page == NULL && zlc_active)) {
1449 /* Disable zlc cache for second zonelist scan */
1450 zlc_active = 0;
1451 goto zonelist_scan;
1453 return page;
1457 * This is the 'heart' of the zoned buddy allocator.
1459 struct page *
1460 __alloc_pages_internal(gfp_t gfp_mask, unsigned int order,
1461 struct zonelist *zonelist, nodemask_t *nodemask)
1463 const gfp_t wait = gfp_mask & __GFP_WAIT;
1464 enum zone_type high_zoneidx = gfp_zone(gfp_mask);
1465 struct zoneref *z;
1466 struct zone *zone;
1467 struct page *page;
1468 struct reclaim_state reclaim_state;
1469 struct task_struct *p = current;
1470 int do_retry;
1471 int alloc_flags;
1472 unsigned long did_some_progress;
1473 unsigned long pages_reclaimed = 0;
1475 lockdep_trace_alloc(gfp_mask);
1477 might_sleep_if(wait);
1479 if (should_fail_alloc_page(gfp_mask, order))
1480 return NULL;
1482 restart:
1483 z = zonelist->_zonerefs; /* the list of zones suitable for gfp_mask */
1485 if (unlikely(!z->zone)) {
1487 * Happens if we have an empty zonelist as a result of
1488 * GFP_THISNODE being used on a memoryless node
1490 return NULL;
1493 page = get_page_from_freelist(gfp_mask|__GFP_HARDWALL, nodemask, order,
1494 zonelist, high_zoneidx, ALLOC_WMARK_LOW|ALLOC_CPUSET);
1495 if (page)
1496 goto got_pg;
1499 * GFP_THISNODE (meaning __GFP_THISNODE, __GFP_NORETRY and
1500 * __GFP_NOWARN set) should not cause reclaim since the subsystem
1501 * (f.e. slab) using GFP_THISNODE may choose to trigger reclaim
1502 * using a larger set of nodes after it has established that the
1503 * allowed per node queues are empty and that nodes are
1504 * over allocated.
1506 if (NUMA_BUILD && (gfp_mask & GFP_THISNODE) == GFP_THISNODE)
1507 goto nopage;
1509 for_each_zone_zonelist(zone, z, zonelist, high_zoneidx)
1510 wakeup_kswapd(zone, order);
1513 * OK, we're below the kswapd watermark and have kicked background
1514 * reclaim. Now things get more complex, so set up alloc_flags according
1515 * to how we want to proceed.
1517 * The caller may dip into page reserves a bit more if the caller
1518 * cannot run direct reclaim, or if the caller has realtime scheduling
1519 * policy or is asking for __GFP_HIGH memory. GFP_ATOMIC requests will
1520 * set both ALLOC_HARDER (!wait) and ALLOC_HIGH (__GFP_HIGH).
1522 alloc_flags = ALLOC_WMARK_MIN;
1523 if ((unlikely(rt_task(p)) && !in_interrupt()) || !wait)
1524 alloc_flags |= ALLOC_HARDER;
1525 if (gfp_mask & __GFP_HIGH)
1526 alloc_flags |= ALLOC_HIGH;
1527 if (wait)
1528 alloc_flags |= ALLOC_CPUSET;
1531 * Go through the zonelist again. Let __GFP_HIGH and allocations
1532 * coming from realtime tasks go deeper into reserves.
1534 * This is the last chance, in general, before the goto nopage.
1535 * Ignore cpuset if GFP_ATOMIC (!wait) rather than fail alloc.
1536 * See also cpuset_zone_allowed() comment in kernel/cpuset.c.
1538 page = get_page_from_freelist(gfp_mask, nodemask, order, zonelist,
1539 high_zoneidx, alloc_flags);
1540 if (page)
1541 goto got_pg;
1543 /* This allocation should allow future memory freeing. */
1545 rebalance:
1546 if (((p->flags & PF_MEMALLOC) || unlikely(test_thread_flag(TIF_MEMDIE)))
1547 && !in_interrupt()) {
1548 if (!(gfp_mask & __GFP_NOMEMALLOC)) {
1549 nofail_alloc:
1550 /* go through the zonelist yet again, ignoring mins */
1551 page = get_page_from_freelist(gfp_mask, nodemask, order,
1552 zonelist, high_zoneidx, ALLOC_NO_WATERMARKS);
1553 if (page)
1554 goto got_pg;
1555 if (gfp_mask & __GFP_NOFAIL) {
1556 congestion_wait(WRITE, HZ/50);
1557 goto nofail_alloc;
1560 goto nopage;
1563 /* Atomic allocations - we can't balance anything */
1564 if (!wait)
1565 goto nopage;
1567 cond_resched();
1569 /* We now go into synchronous reclaim */
1570 cpuset_memory_pressure_bump();
1572 * The task's cpuset might have expanded its set of allowable nodes
1574 cpuset_update_task_memory_state();
1575 p->flags |= PF_MEMALLOC;
1577 lockdep_set_current_reclaim_state(gfp_mask);
1578 reclaim_state.reclaimed_slab = 0;
1579 p->reclaim_state = &reclaim_state;
1581 did_some_progress = try_to_free_pages(zonelist, order,
1582 gfp_mask, nodemask);
1584 p->reclaim_state = NULL;
1585 lockdep_clear_current_reclaim_state();
1586 p->flags &= ~PF_MEMALLOC;
1588 cond_resched();
1590 if (order != 0)
1591 drain_all_pages();
1593 if (likely(did_some_progress)) {
1594 page = get_page_from_freelist(gfp_mask, nodemask, order,
1595 zonelist, high_zoneidx, alloc_flags);
1596 if (page)
1597 goto got_pg;
1598 } else if ((gfp_mask & __GFP_FS) && !(gfp_mask & __GFP_NORETRY)) {
1599 if (!try_set_zone_oom(zonelist, gfp_mask)) {
1600 schedule_timeout_uninterruptible(1);
1601 goto restart;
1605 * Go through the zonelist yet one more time, keep
1606 * very high watermark here, this is only to catch
1607 * a parallel oom killing, we must fail if we're still
1608 * under heavy pressure.
1610 page = get_page_from_freelist(gfp_mask|__GFP_HARDWALL, nodemask,
1611 order, zonelist, high_zoneidx,
1612 ALLOC_WMARK_HIGH|ALLOC_CPUSET);
1613 if (page) {
1614 clear_zonelist_oom(zonelist, gfp_mask);
1615 goto got_pg;
1618 /* The OOM killer will not help higher order allocs so fail */
1619 if (order > PAGE_ALLOC_COSTLY_ORDER) {
1620 clear_zonelist_oom(zonelist, gfp_mask);
1621 goto nopage;
1624 out_of_memory(zonelist, gfp_mask, order);
1625 clear_zonelist_oom(zonelist, gfp_mask);
1626 goto restart;
1630 * Don't let big-order allocations loop unless the caller explicitly
1631 * requests that. Wait for some write requests to complete then retry.
1633 * In this implementation, order <= PAGE_ALLOC_COSTLY_ORDER
1634 * means __GFP_NOFAIL, but that may not be true in other
1635 * implementations.
1637 * For order > PAGE_ALLOC_COSTLY_ORDER, if __GFP_REPEAT is
1638 * specified, then we retry until we no longer reclaim any pages
1639 * (above), or we've reclaimed an order of pages at least as
1640 * large as the allocation's order. In both cases, if the
1641 * allocation still fails, we stop retrying.
1643 pages_reclaimed += did_some_progress;
1644 do_retry = 0;
1645 if (!(gfp_mask & __GFP_NORETRY)) {
1646 if (order <= PAGE_ALLOC_COSTLY_ORDER) {
1647 do_retry = 1;
1648 } else {
1649 if (gfp_mask & __GFP_REPEAT &&
1650 pages_reclaimed < (1 << order))
1651 do_retry = 1;
1653 if (gfp_mask & __GFP_NOFAIL)
1654 do_retry = 1;
1656 if (do_retry) {
1657 congestion_wait(WRITE, HZ/50);
1658 goto rebalance;
1661 nopage:
1662 if (!(gfp_mask & __GFP_NOWARN) && printk_ratelimit()) {
1663 printk(KERN_WARNING "%s: page allocation failure."
1664 " order:%d, mode:0x%x\n",
1665 p->comm, order, gfp_mask);
1666 dump_stack();
1667 show_mem();
1669 got_pg:
1670 return page;
1672 EXPORT_SYMBOL(__alloc_pages_internal);
1675 * Common helper functions.
1677 unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order)
1679 struct page * page;
1680 page = alloc_pages(gfp_mask, order);
1681 if (!page)
1682 return 0;
1683 return (unsigned long) page_address(page);
1686 EXPORT_SYMBOL(__get_free_pages);
1688 unsigned long get_zeroed_page(gfp_t gfp_mask)
1690 struct page * page;
1693 * get_zeroed_page() returns a 32-bit address, which cannot represent
1694 * a highmem page
1696 VM_BUG_ON((gfp_mask & __GFP_HIGHMEM) != 0);
1698 page = alloc_pages(gfp_mask | __GFP_ZERO, 0);
1699 if (page)
1700 return (unsigned long) page_address(page);
1701 return 0;
1704 EXPORT_SYMBOL(get_zeroed_page);
1706 void __pagevec_free(struct pagevec *pvec)
1708 int i = pagevec_count(pvec);
1710 while (--i >= 0)
1711 free_hot_cold_page(pvec->pages[i], pvec->cold);
1714 void __free_pages(struct page *page, unsigned int order)
1716 if (put_page_testzero(page)) {
1717 if (order == 0)
1718 free_hot_page(page);
1719 else
1720 __free_pages_ok(page, order);
1724 EXPORT_SYMBOL(__free_pages);
1726 void free_pages(unsigned long addr, unsigned int order)
1728 if (addr != 0) {
1729 VM_BUG_ON(!virt_addr_valid((void *)addr));
1730 __free_pages(virt_to_page((void *)addr), order);
1734 EXPORT_SYMBOL(free_pages);
1737 * alloc_pages_exact - allocate an exact number physically-contiguous pages.
1738 * @size: the number of bytes to allocate
1739 * @gfp_mask: GFP flags for the allocation
1741 * This function is similar to alloc_pages(), except that it allocates the
1742 * minimum number of pages to satisfy the request. alloc_pages() can only
1743 * allocate memory in power-of-two pages.
1745 * This function is also limited by MAX_ORDER.
1747 * Memory allocated by this function must be released by free_pages_exact().
1749 void *alloc_pages_exact(size_t size, gfp_t gfp_mask)
1751 unsigned int order = get_order(size);
1752 unsigned long addr;
1754 addr = __get_free_pages(gfp_mask, order);
1755 if (addr) {
1756 unsigned long alloc_end = addr + (PAGE_SIZE << order);
1757 unsigned long used = addr + PAGE_ALIGN(size);
1759 split_page(virt_to_page(addr), order);
1760 while (used < alloc_end) {
1761 free_page(used);
1762 used += PAGE_SIZE;
1766 return (void *)addr;
1768 EXPORT_SYMBOL(alloc_pages_exact);
1771 * free_pages_exact - release memory allocated via alloc_pages_exact()
1772 * @virt: the value returned by alloc_pages_exact.
1773 * @size: size of allocation, same value as passed to alloc_pages_exact().
1775 * Release the memory allocated by a previous call to alloc_pages_exact.
1777 void free_pages_exact(void *virt, size_t size)
1779 unsigned long addr = (unsigned long)virt;
1780 unsigned long end = addr + PAGE_ALIGN(size);
1782 while (addr < end) {
1783 free_page(addr);
1784 addr += PAGE_SIZE;
1787 EXPORT_SYMBOL(free_pages_exact);
1789 static unsigned int nr_free_zone_pages(int offset)
1791 struct zoneref *z;
1792 struct zone *zone;
1794 /* Just pick one node, since fallback list is circular */
1795 unsigned int sum = 0;
1797 struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL);
1799 for_each_zone_zonelist(zone, z, zonelist, offset) {
1800 unsigned long size = zone->present_pages;
1801 unsigned long high = zone->pages_high;
1802 if (size > high)
1803 sum += size - high;
1806 return sum;
1810 * Amount of free RAM allocatable within ZONE_DMA and ZONE_NORMAL
1812 unsigned int nr_free_buffer_pages(void)
1814 return nr_free_zone_pages(gfp_zone(GFP_USER));
1816 EXPORT_SYMBOL_GPL(nr_free_buffer_pages);
1819 * Amount of free RAM allocatable within all zones
1821 unsigned int nr_free_pagecache_pages(void)
1823 return nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE));
1826 static inline void show_node(struct zone *zone)
1828 if (NUMA_BUILD)
1829 printk("Node %d ", zone_to_nid(zone));
1832 void si_meminfo(struct sysinfo *val)
1834 val->totalram = totalram_pages;
1835 val->sharedram = 0;
1836 val->freeram = global_page_state(NR_FREE_PAGES);
1837 val->bufferram = nr_blockdev_pages();
1838 val->totalhigh = totalhigh_pages;
1839 val->freehigh = nr_free_highpages();
1840 val->mem_unit = PAGE_SIZE;
1843 EXPORT_SYMBOL(si_meminfo);
1845 #ifdef CONFIG_NUMA
1846 void si_meminfo_node(struct sysinfo *val, int nid)
1848 pg_data_t *pgdat = NODE_DATA(nid);
1850 val->totalram = pgdat->node_present_pages;
1851 val->freeram = node_page_state(nid, NR_FREE_PAGES);
1852 #ifdef CONFIG_HIGHMEM
1853 val->totalhigh = pgdat->node_zones[ZONE_HIGHMEM].present_pages;
1854 val->freehigh = zone_page_state(&pgdat->node_zones[ZONE_HIGHMEM],
1855 NR_FREE_PAGES);
1856 #else
1857 val->totalhigh = 0;
1858 val->freehigh = 0;
1859 #endif
1860 val->mem_unit = PAGE_SIZE;
1862 #endif
1864 #define K(x) ((x) << (PAGE_SHIFT-10))
1867 * Show free area list (used inside shift_scroll-lock stuff)
1868 * We also calculate the percentage fragmentation. We do this by counting the
1869 * memory on each free list with the exception of the first item on the list.
1871 void show_free_areas(void)
1873 int cpu;
1874 struct zone *zone;
1876 for_each_populated_zone(zone) {
1877 show_node(zone);
1878 printk("%s per-cpu:\n", zone->name);
1880 for_each_online_cpu(cpu) {
1881 struct per_cpu_pageset *pageset;
1883 pageset = zone_pcp(zone, cpu);
1885 printk("CPU %4d: hi:%5d, btch:%4d usd:%4d\n",
1886 cpu, pageset->pcp.high,
1887 pageset->pcp.batch, pageset->pcp.count);
1891 printk("Active_anon:%lu active_file:%lu inactive_anon:%lu\n"
1892 " inactive_file:%lu"
1893 //TODO: check/adjust line lengths
1894 #ifdef CONFIG_UNEVICTABLE_LRU
1895 " unevictable:%lu"
1896 #endif
1897 " dirty:%lu writeback:%lu unstable:%lu\n"
1898 " free:%lu slab:%lu mapped:%lu pagetables:%lu bounce:%lu\n",
1899 global_page_state(NR_ACTIVE_ANON),
1900 global_page_state(NR_ACTIVE_FILE),
1901 global_page_state(NR_INACTIVE_ANON),
1902 global_page_state(NR_INACTIVE_FILE),
1903 #ifdef CONFIG_UNEVICTABLE_LRU
1904 global_page_state(NR_UNEVICTABLE),
1905 #endif
1906 global_page_state(NR_FILE_DIRTY),
1907 global_page_state(NR_WRITEBACK),
1908 global_page_state(NR_UNSTABLE_NFS),
1909 global_page_state(NR_FREE_PAGES),
1910 global_page_state(NR_SLAB_RECLAIMABLE) +
1911 global_page_state(NR_SLAB_UNRECLAIMABLE),
1912 global_page_state(NR_FILE_MAPPED),
1913 global_page_state(NR_PAGETABLE),
1914 global_page_state(NR_BOUNCE));
1916 for_each_populated_zone(zone) {
1917 int i;
1919 show_node(zone);
1920 printk("%s"
1921 " free:%lukB"
1922 " min:%lukB"
1923 " low:%lukB"
1924 " high:%lukB"
1925 " active_anon:%lukB"
1926 " inactive_anon:%lukB"
1927 " active_file:%lukB"
1928 " inactive_file:%lukB"
1929 #ifdef CONFIG_UNEVICTABLE_LRU
1930 " unevictable:%lukB"
1931 #endif
1932 " present:%lukB"
1933 " pages_scanned:%lu"
1934 " all_unreclaimable? %s"
1935 "\n",
1936 zone->name,
1937 K(zone_page_state(zone, NR_FREE_PAGES)),
1938 K(zone->pages_min),
1939 K(zone->pages_low),
1940 K(zone->pages_high),
1941 K(zone_page_state(zone, NR_ACTIVE_ANON)),
1942 K(zone_page_state(zone, NR_INACTIVE_ANON)),
1943 K(zone_page_state(zone, NR_ACTIVE_FILE)),
1944 K(zone_page_state(zone, NR_INACTIVE_FILE)),
1945 #ifdef CONFIG_UNEVICTABLE_LRU
1946 K(zone_page_state(zone, NR_UNEVICTABLE)),
1947 #endif
1948 K(zone->present_pages),
1949 zone->pages_scanned,
1950 (zone_is_all_unreclaimable(zone) ? "yes" : "no")
1952 printk("lowmem_reserve[]:");
1953 for (i = 0; i < MAX_NR_ZONES; i++)
1954 printk(" %lu", zone->lowmem_reserve[i]);
1955 printk("\n");
1958 for_each_populated_zone(zone) {
1959 unsigned long nr[MAX_ORDER], flags, order, total = 0;
1961 show_node(zone);
1962 printk("%s: ", zone->name);
1964 spin_lock_irqsave(&zone->lock, flags);
1965 for (order = 0; order < MAX_ORDER; order++) {
1966 nr[order] = zone->free_area[order].nr_free;
1967 total += nr[order] << order;
1969 spin_unlock_irqrestore(&zone->lock, flags);
1970 for (order = 0; order < MAX_ORDER; order++)
1971 printk("%lu*%lukB ", nr[order], K(1UL) << order);
1972 printk("= %lukB\n", K(total));
1975 printk("%ld total pagecache pages\n", global_page_state(NR_FILE_PAGES));
1977 show_swap_cache_info();
1980 static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref)
1982 zoneref->zone = zone;
1983 zoneref->zone_idx = zone_idx(zone);
1987 * Builds allocation fallback zone lists.
1989 * Add all populated zones of a node to the zonelist.
1991 static int build_zonelists_node(pg_data_t *pgdat, struct zonelist *zonelist,
1992 int nr_zones, enum zone_type zone_type)
1994 struct zone *zone;
1996 BUG_ON(zone_type >= MAX_NR_ZONES);
1997 zone_type++;
1999 do {
2000 zone_type--;
2001 zone = pgdat->node_zones + zone_type;
2002 if (populated_zone(zone)) {
2003 zoneref_set_zone(zone,
2004 &zonelist->_zonerefs[nr_zones++]);
2005 check_highest_zone(zone_type);
2008 } while (zone_type);
2009 return nr_zones;
2014 * zonelist_order:
2015 * 0 = automatic detection of better ordering.
2016 * 1 = order by ([node] distance, -zonetype)
2017 * 2 = order by (-zonetype, [node] distance)
2019 * If not NUMA, ZONELIST_ORDER_ZONE and ZONELIST_ORDER_NODE will create
2020 * the same zonelist. So only NUMA can configure this param.
2022 #define ZONELIST_ORDER_DEFAULT 0
2023 #define ZONELIST_ORDER_NODE 1
2024 #define ZONELIST_ORDER_ZONE 2
2026 /* zonelist order in the kernel.
2027 * set_zonelist_order() will set this to NODE or ZONE.
2029 static int current_zonelist_order = ZONELIST_ORDER_DEFAULT;
2030 static char zonelist_order_name[3][8] = {"Default", "Node", "Zone"};
2033 #ifdef CONFIG_NUMA
2034 /* The value user specified ....changed by config */
2035 static int user_zonelist_order = ZONELIST_ORDER_DEFAULT;
2036 /* string for sysctl */
2037 #define NUMA_ZONELIST_ORDER_LEN 16
2038 char numa_zonelist_order[16] = "default";
2041 * interface for configure zonelist ordering.
2042 * command line option "numa_zonelist_order"
2043 * = "[dD]efault - default, automatic configuration.
2044 * = "[nN]ode - order by node locality, then by zone within node
2045 * = "[zZ]one - order by zone, then by locality within zone
2048 static int __parse_numa_zonelist_order(char *s)
2050 if (*s == 'd' || *s == 'D') {
2051 user_zonelist_order = ZONELIST_ORDER_DEFAULT;
2052 } else if (*s == 'n' || *s == 'N') {
2053 user_zonelist_order = ZONELIST_ORDER_NODE;
2054 } else if (*s == 'z' || *s == 'Z') {
2055 user_zonelist_order = ZONELIST_ORDER_ZONE;
2056 } else {
2057 printk(KERN_WARNING
2058 "Ignoring invalid numa_zonelist_order value: "
2059 "%s\n", s);
2060 return -EINVAL;
2062 return 0;
2065 static __init int setup_numa_zonelist_order(char *s)
2067 if (s)
2068 return __parse_numa_zonelist_order(s);
2069 return 0;
2071 early_param("numa_zonelist_order", setup_numa_zonelist_order);
2074 * sysctl handler for numa_zonelist_order
2076 int numa_zonelist_order_handler(ctl_table *table, int write,
2077 struct file *file, void __user *buffer, size_t *length,
2078 loff_t *ppos)
2080 char saved_string[NUMA_ZONELIST_ORDER_LEN];
2081 int ret;
2083 if (write)
2084 strncpy(saved_string, (char*)table->data,
2085 NUMA_ZONELIST_ORDER_LEN);
2086 ret = proc_dostring(table, write, file, buffer, length, ppos);
2087 if (ret)
2088 return ret;
2089 if (write) {
2090 int oldval = user_zonelist_order;
2091 if (__parse_numa_zonelist_order((char*)table->data)) {
2093 * bogus value. restore saved string
2095 strncpy((char*)table->data, saved_string,
2096 NUMA_ZONELIST_ORDER_LEN);
2097 user_zonelist_order = oldval;
2098 } else if (oldval != user_zonelist_order)
2099 build_all_zonelists();
2101 return 0;
2105 #define MAX_NODE_LOAD (num_online_nodes())
2106 static int node_load[MAX_NUMNODES];
2109 * find_next_best_node - find the next node that should appear in a given node's fallback list
2110 * @node: node whose fallback list we're appending
2111 * @used_node_mask: nodemask_t of already used nodes
2113 * We use a number of factors to determine which is the next node that should
2114 * appear on a given node's fallback list. The node should not have appeared
2115 * already in @node's fallback list, and it should be the next closest node
2116 * according to the distance array (which contains arbitrary distance values
2117 * from each node to each node in the system), and should also prefer nodes
2118 * with no CPUs, since presumably they'll have very little allocation pressure
2119 * on them otherwise.
2120 * It returns -1 if no node is found.
2122 static int find_next_best_node(int node, nodemask_t *used_node_mask)
2124 int n, val;
2125 int min_val = INT_MAX;
2126 int best_node = -1;
2127 const struct cpumask *tmp = cpumask_of_node(0);
2129 /* Use the local node if we haven't already */
2130 if (!node_isset(node, *used_node_mask)) {
2131 node_set(node, *used_node_mask);
2132 return node;
2135 for_each_node_state(n, N_HIGH_MEMORY) {
2137 /* Don't want a node to appear more than once */
2138 if (node_isset(n, *used_node_mask))
2139 continue;
2141 /* Use the distance array to find the distance */
2142 val = node_distance(node, n);
2144 /* Penalize nodes under us ("prefer the next node") */
2145 val += (n < node);
2147 /* Give preference to headless and unused nodes */
2148 tmp = cpumask_of_node(n);
2149 if (!cpumask_empty(tmp))
2150 val += PENALTY_FOR_NODE_WITH_CPUS;
2152 /* Slight preference for less loaded node */
2153 val *= (MAX_NODE_LOAD*MAX_NUMNODES);
2154 val += node_load[n];
2156 if (val < min_val) {
2157 min_val = val;
2158 best_node = n;
2162 if (best_node >= 0)
2163 node_set(best_node, *used_node_mask);
2165 return best_node;
2170 * Build zonelists ordered by node and zones within node.
2171 * This results in maximum locality--normal zone overflows into local
2172 * DMA zone, if any--but risks exhausting DMA zone.
2174 static void build_zonelists_in_node_order(pg_data_t *pgdat, int node)
2176 int j;
2177 struct zonelist *zonelist;
2179 zonelist = &pgdat->node_zonelists[0];
2180 for (j = 0; zonelist->_zonerefs[j].zone != NULL; j++)
2182 j = build_zonelists_node(NODE_DATA(node), zonelist, j,
2183 MAX_NR_ZONES - 1);
2184 zonelist->_zonerefs[j].zone = NULL;
2185 zonelist->_zonerefs[j].zone_idx = 0;
2189 * Build gfp_thisnode zonelists
2191 static void build_thisnode_zonelists(pg_data_t *pgdat)
2193 int j;
2194 struct zonelist *zonelist;
2196 zonelist = &pgdat->node_zonelists[1];
2197 j = build_zonelists_node(pgdat, zonelist, 0, MAX_NR_ZONES - 1);
2198 zonelist->_zonerefs[j].zone = NULL;
2199 zonelist->_zonerefs[j].zone_idx = 0;
2203 * Build zonelists ordered by zone and nodes within zones.
2204 * This results in conserving DMA zone[s] until all Normal memory is
2205 * exhausted, but results in overflowing to remote node while memory
2206 * may still exist in local DMA zone.
2208 static int node_order[MAX_NUMNODES];
2210 static void build_zonelists_in_zone_order(pg_data_t *pgdat, int nr_nodes)
2212 int pos, j, node;
2213 int zone_type; /* needs to be signed */
2214 struct zone *z;
2215 struct zonelist *zonelist;
2217 zonelist = &pgdat->node_zonelists[0];
2218 pos = 0;
2219 for (zone_type = MAX_NR_ZONES - 1; zone_type >= 0; zone_type--) {
2220 for (j = 0; j < nr_nodes; j++) {
2221 node = node_order[j];
2222 z = &NODE_DATA(node)->node_zones[zone_type];
2223 if (populated_zone(z)) {
2224 zoneref_set_zone(z,
2225 &zonelist->_zonerefs[pos++]);
2226 check_highest_zone(zone_type);
2230 zonelist->_zonerefs[pos].zone = NULL;
2231 zonelist->_zonerefs[pos].zone_idx = 0;
2234 static int default_zonelist_order(void)
2236 int nid, zone_type;
2237 unsigned long low_kmem_size,total_size;
2238 struct zone *z;
2239 int average_size;
2241 * ZONE_DMA and ZONE_DMA32 can be very small area in the sytem.
2242 * If they are really small and used heavily, the system can fall
2243 * into OOM very easily.
2244 * This function detect ZONE_DMA/DMA32 size and confgigures zone order.
2246 /* Is there ZONE_NORMAL ? (ex. ppc has only DMA zone..) */
2247 low_kmem_size = 0;
2248 total_size = 0;
2249 for_each_online_node(nid) {
2250 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
2251 z = &NODE_DATA(nid)->node_zones[zone_type];
2252 if (populated_zone(z)) {
2253 if (zone_type < ZONE_NORMAL)
2254 low_kmem_size += z->present_pages;
2255 total_size += z->present_pages;
2259 if (!low_kmem_size || /* there are no DMA area. */
2260 low_kmem_size > total_size/2) /* DMA/DMA32 is big. */
2261 return ZONELIST_ORDER_NODE;
2263 * look into each node's config.
2264 * If there is a node whose DMA/DMA32 memory is very big area on
2265 * local memory, NODE_ORDER may be suitable.
2267 average_size = total_size /
2268 (nodes_weight(node_states[N_HIGH_MEMORY]) + 1);
2269 for_each_online_node(nid) {
2270 low_kmem_size = 0;
2271 total_size = 0;
2272 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
2273 z = &NODE_DATA(nid)->node_zones[zone_type];
2274 if (populated_zone(z)) {
2275 if (zone_type < ZONE_NORMAL)
2276 low_kmem_size += z->present_pages;
2277 total_size += z->present_pages;
2280 if (low_kmem_size &&
2281 total_size > average_size && /* ignore small node */
2282 low_kmem_size > total_size * 70/100)
2283 return ZONELIST_ORDER_NODE;
2285 return ZONELIST_ORDER_ZONE;
2288 static void set_zonelist_order(void)
2290 if (user_zonelist_order == ZONELIST_ORDER_DEFAULT)
2291 current_zonelist_order = default_zonelist_order();
2292 else
2293 current_zonelist_order = user_zonelist_order;
2296 static void build_zonelists(pg_data_t *pgdat)
2298 int j, node, load;
2299 enum zone_type i;
2300 nodemask_t used_mask;
2301 int local_node, prev_node;
2302 struct zonelist *zonelist;
2303 int order = current_zonelist_order;
2305 /* initialize zonelists */
2306 for (i = 0; i < MAX_ZONELISTS; i++) {
2307 zonelist = pgdat->node_zonelists + i;
2308 zonelist->_zonerefs[0].zone = NULL;
2309 zonelist->_zonerefs[0].zone_idx = 0;
2312 /* NUMA-aware ordering of nodes */
2313 local_node = pgdat->node_id;
2314 load = num_online_nodes();
2315 prev_node = local_node;
2316 nodes_clear(used_mask);
2318 memset(node_load, 0, sizeof(node_load));
2319 memset(node_order, 0, sizeof(node_order));
2320 j = 0;
2322 while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
2323 int distance = node_distance(local_node, node);
2326 * If another node is sufficiently far away then it is better
2327 * to reclaim pages in a zone before going off node.
2329 if (distance > RECLAIM_DISTANCE)
2330 zone_reclaim_mode = 1;
2333 * We don't want to pressure a particular node.
2334 * So adding penalty to the first node in same
2335 * distance group to make it round-robin.
2337 if (distance != node_distance(local_node, prev_node))
2338 node_load[node] = load;
2340 prev_node = node;
2341 load--;
2342 if (order == ZONELIST_ORDER_NODE)
2343 build_zonelists_in_node_order(pgdat, node);
2344 else
2345 node_order[j++] = node; /* remember order */
2348 if (order == ZONELIST_ORDER_ZONE) {
2349 /* calculate node order -- i.e., DMA last! */
2350 build_zonelists_in_zone_order(pgdat, j);
2353 build_thisnode_zonelists(pgdat);
2356 /* Construct the zonelist performance cache - see further mmzone.h */
2357 static void build_zonelist_cache(pg_data_t *pgdat)
2359 struct zonelist *zonelist;
2360 struct zonelist_cache *zlc;
2361 struct zoneref *z;
2363 zonelist = &pgdat->node_zonelists[0];
2364 zonelist->zlcache_ptr = zlc = &zonelist->zlcache;
2365 bitmap_zero(zlc->fullzones, MAX_ZONES_PER_ZONELIST);
2366 for (z = zonelist->_zonerefs; z->zone; z++)
2367 zlc->z_to_n[z - zonelist->_zonerefs] = zonelist_node_idx(z);
2371 #else /* CONFIG_NUMA */
2373 static void set_zonelist_order(void)
2375 current_zonelist_order = ZONELIST_ORDER_ZONE;
2378 static void build_zonelists(pg_data_t *pgdat)
2380 int node, local_node;
2381 enum zone_type j;
2382 struct zonelist *zonelist;
2384 local_node = pgdat->node_id;
2386 zonelist = &pgdat->node_zonelists[0];
2387 j = build_zonelists_node(pgdat, zonelist, 0, MAX_NR_ZONES - 1);
2390 * Now we build the zonelist so that it contains the zones
2391 * of all the other nodes.
2392 * We don't want to pressure a particular node, so when
2393 * building the zones for node N, we make sure that the
2394 * zones coming right after the local ones are those from
2395 * node N+1 (modulo N)
2397 for (node = local_node + 1; node < MAX_NUMNODES; node++) {
2398 if (!node_online(node))
2399 continue;
2400 j = build_zonelists_node(NODE_DATA(node), zonelist, j,
2401 MAX_NR_ZONES - 1);
2403 for (node = 0; node < local_node; node++) {
2404 if (!node_online(node))
2405 continue;
2406 j = build_zonelists_node(NODE_DATA(node), zonelist, j,
2407 MAX_NR_ZONES - 1);
2410 zonelist->_zonerefs[j].zone = NULL;
2411 zonelist->_zonerefs[j].zone_idx = 0;
2414 /* non-NUMA variant of zonelist performance cache - just NULL zlcache_ptr */
2415 static void build_zonelist_cache(pg_data_t *pgdat)
2417 pgdat->node_zonelists[0].zlcache_ptr = NULL;
2420 #endif /* CONFIG_NUMA */
2422 /* return values int ....just for stop_machine() */
2423 static int __build_all_zonelists(void *dummy)
2425 int nid;
2427 for_each_online_node(nid) {
2428 pg_data_t *pgdat = NODE_DATA(nid);
2430 build_zonelists(pgdat);
2431 build_zonelist_cache(pgdat);
2433 return 0;
2436 void build_all_zonelists(void)
2438 set_zonelist_order();
2440 if (system_state == SYSTEM_BOOTING) {
2441 __build_all_zonelists(NULL);
2442 mminit_verify_zonelist();
2443 cpuset_init_current_mems_allowed();
2444 } else {
2445 /* we have to stop all cpus to guarantee there is no user
2446 of zonelist */
2447 stop_machine(__build_all_zonelists, NULL, NULL);
2448 /* cpuset refresh routine should be here */
2450 vm_total_pages = nr_free_pagecache_pages();
2452 * Disable grouping by mobility if the number of pages in the
2453 * system is too low to allow the mechanism to work. It would be
2454 * more accurate, but expensive to check per-zone. This check is
2455 * made on memory-hotadd so a system can start with mobility
2456 * disabled and enable it later
2458 if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES))
2459 page_group_by_mobility_disabled = 1;
2460 else
2461 page_group_by_mobility_disabled = 0;
2463 printk("Built %i zonelists in %s order, mobility grouping %s. "
2464 "Total pages: %ld\n",
2465 num_online_nodes(),
2466 zonelist_order_name[current_zonelist_order],
2467 page_group_by_mobility_disabled ? "off" : "on",
2468 vm_total_pages);
2469 #ifdef CONFIG_NUMA
2470 printk("Policy zone: %s\n", zone_names[policy_zone]);
2471 #endif
2475 * Helper functions to size the waitqueue hash table.
2476 * Essentially these want to choose hash table sizes sufficiently
2477 * large so that collisions trying to wait on pages are rare.
2478 * But in fact, the number of active page waitqueues on typical
2479 * systems is ridiculously low, less than 200. So this is even
2480 * conservative, even though it seems large.
2482 * The constant PAGES_PER_WAITQUEUE specifies the ratio of pages to
2483 * waitqueues, i.e. the size of the waitq table given the number of pages.
2485 #define PAGES_PER_WAITQUEUE 256
2487 #ifndef CONFIG_MEMORY_HOTPLUG
2488 static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
2490 unsigned long size = 1;
2492 pages /= PAGES_PER_WAITQUEUE;
2494 while (size < pages)
2495 size <<= 1;
2498 * Once we have dozens or even hundreds of threads sleeping
2499 * on IO we've got bigger problems than wait queue collision.
2500 * Limit the size of the wait table to a reasonable size.
2502 size = min(size, 4096UL);
2504 return max(size, 4UL);
2506 #else
2508 * A zone's size might be changed by hot-add, so it is not possible to determine
2509 * a suitable size for its wait_table. So we use the maximum size now.
2511 * The max wait table size = 4096 x sizeof(wait_queue_head_t). ie:
2513 * i386 (preemption config) : 4096 x 16 = 64Kbyte.
2514 * ia64, x86-64 (no preemption): 4096 x 20 = 80Kbyte.
2515 * ia64, x86-64 (preemption) : 4096 x 24 = 96Kbyte.
2517 * The maximum entries are prepared when a zone's memory is (512K + 256) pages
2518 * or more by the traditional way. (See above). It equals:
2520 * i386, x86-64, powerpc(4K page size) : = ( 2G + 1M)byte.
2521 * ia64(16K page size) : = ( 8G + 4M)byte.
2522 * powerpc (64K page size) : = (32G +16M)byte.
2524 static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
2526 return 4096UL;
2528 #endif
2531 * This is an integer logarithm so that shifts can be used later
2532 * to extract the more random high bits from the multiplicative
2533 * hash function before the remainder is taken.
2535 static inline unsigned long wait_table_bits(unsigned long size)
2537 return ffz(~size);
2540 #define LONG_ALIGN(x) (((x)+(sizeof(long))-1)&~((sizeof(long))-1))
2543 * Mark a number of pageblocks as MIGRATE_RESERVE. The number
2544 * of blocks reserved is based on zone->pages_min. The memory within the
2545 * reserve will tend to store contiguous free pages. Setting min_free_kbytes
2546 * higher will lead to a bigger reserve which will get freed as contiguous
2547 * blocks as reclaim kicks in
2549 static void setup_zone_migrate_reserve(struct zone *zone)
2551 unsigned long start_pfn, pfn, end_pfn;
2552 struct page *page;
2553 unsigned long reserve, block_migratetype;
2555 /* Get the start pfn, end pfn and the number of blocks to reserve */
2556 start_pfn = zone->zone_start_pfn;
2557 end_pfn = start_pfn + zone->spanned_pages;
2558 reserve = roundup(zone->pages_min, pageblock_nr_pages) >>
2559 pageblock_order;
2561 for (pfn = start_pfn; pfn < end_pfn; pfn += pageblock_nr_pages) {
2562 if (!pfn_valid(pfn))
2563 continue;
2564 page = pfn_to_page(pfn);
2566 /* Watch out for overlapping nodes */
2567 if (page_to_nid(page) != zone_to_nid(zone))
2568 continue;
2570 /* Blocks with reserved pages will never free, skip them. */
2571 if (PageReserved(page))
2572 continue;
2574 block_migratetype = get_pageblock_migratetype(page);
2576 /* If this block is reserved, account for it */
2577 if (reserve > 0 && block_migratetype == MIGRATE_RESERVE) {
2578 reserve--;
2579 continue;
2582 /* Suitable for reserving if this block is movable */
2583 if (reserve > 0 && block_migratetype == MIGRATE_MOVABLE) {
2584 set_pageblock_migratetype(page, MIGRATE_RESERVE);
2585 move_freepages_block(zone, page, MIGRATE_RESERVE);
2586 reserve--;
2587 continue;
2591 * If the reserve is met and this is a previous reserved block,
2592 * take it back
2594 if (block_migratetype == MIGRATE_RESERVE) {
2595 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
2596 move_freepages_block(zone, page, MIGRATE_MOVABLE);
2602 * Initially all pages are reserved - free ones are freed
2603 * up by free_all_bootmem() once the early boot process is
2604 * done. Non-atomic initialization, single-pass.
2606 void __meminit memmap_init_zone(unsigned long size, int nid, unsigned long zone,
2607 unsigned long start_pfn, enum memmap_context context)
2609 struct page *page;
2610 unsigned long end_pfn = start_pfn + size;
2611 unsigned long pfn;
2612 struct zone *z;
2614 if (highest_memmap_pfn < end_pfn - 1)
2615 highest_memmap_pfn = end_pfn - 1;
2617 z = &NODE_DATA(nid)->node_zones[zone];
2618 for (pfn = start_pfn; pfn < end_pfn; pfn++) {
2620 * There can be holes in boot-time mem_map[]s
2621 * handed to this function. They do not
2622 * exist on hotplugged memory.
2624 if (context == MEMMAP_EARLY) {
2625 if (!early_pfn_valid(pfn))
2626 continue;
2627 if (!early_pfn_in_nid(pfn, nid))
2628 continue;
2630 page = pfn_to_page(pfn);
2631 set_page_links(page, zone, nid, pfn);
2632 mminit_verify_page_links(page, zone, nid, pfn);
2633 init_page_count(page);
2634 reset_page_mapcount(page);
2635 SetPageReserved(page);
2637 * Mark the block movable so that blocks are reserved for
2638 * movable at startup. This will force kernel allocations
2639 * to reserve their blocks rather than leaking throughout
2640 * the address space during boot when many long-lived
2641 * kernel allocations are made. Later some blocks near
2642 * the start are marked MIGRATE_RESERVE by
2643 * setup_zone_migrate_reserve()
2645 * bitmap is created for zone's valid pfn range. but memmap
2646 * can be created for invalid pages (for alignment)
2647 * check here not to call set_pageblock_migratetype() against
2648 * pfn out of zone.
2650 if ((z->zone_start_pfn <= pfn)
2651 && (pfn < z->zone_start_pfn + z->spanned_pages)
2652 && !(pfn & (pageblock_nr_pages - 1)))
2653 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
2655 INIT_LIST_HEAD(&page->lru);
2656 #ifdef WANT_PAGE_VIRTUAL
2657 /* The shift won't overflow because ZONE_NORMAL is below 4G. */
2658 if (!is_highmem_idx(zone))
2659 set_page_address(page, __va(pfn << PAGE_SHIFT));
2660 #endif
2664 static void __meminit zone_init_free_lists(struct zone *zone)
2666 int order, t;
2667 for_each_migratetype_order(order, t) {
2668 INIT_LIST_HEAD(&zone->free_area[order].free_list[t]);
2669 zone->free_area[order].nr_free = 0;
2673 #ifndef __HAVE_ARCH_MEMMAP_INIT
2674 #define memmap_init(size, nid, zone, start_pfn) \
2675 memmap_init_zone((size), (nid), (zone), (start_pfn), MEMMAP_EARLY)
2676 #endif
2678 static int zone_batchsize(struct zone *zone)
2680 #ifdef CONFIG_MMU
2681 int batch;
2684 * The per-cpu-pages pools are set to around 1000th of the
2685 * size of the zone. But no more than 1/2 of a meg.
2687 * OK, so we don't know how big the cache is. So guess.
2689 batch = zone->present_pages / 1024;
2690 if (batch * PAGE_SIZE > 512 * 1024)
2691 batch = (512 * 1024) / PAGE_SIZE;
2692 batch /= 4; /* We effectively *= 4 below */
2693 if (batch < 1)
2694 batch = 1;
2697 * Clamp the batch to a 2^n - 1 value. Having a power
2698 * of 2 value was found to be more likely to have
2699 * suboptimal cache aliasing properties in some cases.
2701 * For example if 2 tasks are alternately allocating
2702 * batches of pages, one task can end up with a lot
2703 * of pages of one half of the possible page colors
2704 * and the other with pages of the other colors.
2706 batch = rounddown_pow_of_two(batch + batch/2) - 1;
2708 return batch;
2710 #else
2711 /* The deferral and batching of frees should be suppressed under NOMMU
2712 * conditions.
2714 * The problem is that NOMMU needs to be able to allocate large chunks
2715 * of contiguous memory as there's no hardware page translation to
2716 * assemble apparent contiguous memory from discontiguous pages.
2718 * Queueing large contiguous runs of pages for batching, however,
2719 * causes the pages to actually be freed in smaller chunks. As there
2720 * can be a significant delay between the individual batches being
2721 * recycled, this leads to the once large chunks of space being
2722 * fragmented and becoming unavailable for high-order allocations.
2724 return 0;
2725 #endif
2728 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch)
2730 struct per_cpu_pages *pcp;
2732 memset(p, 0, sizeof(*p));
2734 pcp = &p->pcp;
2735 pcp->count = 0;
2736 pcp->high = 6 * batch;
2737 pcp->batch = max(1UL, 1 * batch);
2738 INIT_LIST_HEAD(&pcp->list);
2742 * setup_pagelist_highmark() sets the high water mark for hot per_cpu_pagelist
2743 * to the value high for the pageset p.
2746 static void setup_pagelist_highmark(struct per_cpu_pageset *p,
2747 unsigned long high)
2749 struct per_cpu_pages *pcp;
2751 pcp = &p->pcp;
2752 pcp->high = high;
2753 pcp->batch = max(1UL, high/4);
2754 if ((high/4) > (PAGE_SHIFT * 8))
2755 pcp->batch = PAGE_SHIFT * 8;
2759 #ifdef CONFIG_NUMA
2761 * Boot pageset table. One per cpu which is going to be used for all
2762 * zones and all nodes. The parameters will be set in such a way
2763 * that an item put on a list will immediately be handed over to
2764 * the buddy list. This is safe since pageset manipulation is done
2765 * with interrupts disabled.
2767 * Some NUMA counter updates may also be caught by the boot pagesets.
2769 * The boot_pagesets must be kept even after bootup is complete for
2770 * unused processors and/or zones. They do play a role for bootstrapping
2771 * hotplugged processors.
2773 * zoneinfo_show() and maybe other functions do
2774 * not check if the processor is online before following the pageset pointer.
2775 * Other parts of the kernel may not check if the zone is available.
2777 static struct per_cpu_pageset boot_pageset[NR_CPUS];
2780 * Dynamically allocate memory for the
2781 * per cpu pageset array in struct zone.
2783 static int __cpuinit process_zones(int cpu)
2785 struct zone *zone, *dzone;
2786 int node = cpu_to_node(cpu);
2788 node_set_state(node, N_CPU); /* this node has a cpu */
2790 for_each_populated_zone(zone) {
2791 zone_pcp(zone, cpu) = kmalloc_node(sizeof(struct per_cpu_pageset),
2792 GFP_KERNEL, node);
2793 if (!zone_pcp(zone, cpu))
2794 goto bad;
2796 setup_pageset(zone_pcp(zone, cpu), zone_batchsize(zone));
2798 if (percpu_pagelist_fraction)
2799 setup_pagelist_highmark(zone_pcp(zone, cpu),
2800 (zone->present_pages / percpu_pagelist_fraction));
2803 return 0;
2804 bad:
2805 for_each_zone(dzone) {
2806 if (!populated_zone(dzone))
2807 continue;
2808 if (dzone == zone)
2809 break;
2810 kfree(zone_pcp(dzone, cpu));
2811 zone_pcp(dzone, cpu) = NULL;
2813 return -ENOMEM;
2816 static inline void free_zone_pagesets(int cpu)
2818 struct zone *zone;
2820 for_each_zone(zone) {
2821 struct per_cpu_pageset *pset = zone_pcp(zone, cpu);
2823 /* Free per_cpu_pageset if it is slab allocated */
2824 if (pset != &boot_pageset[cpu])
2825 kfree(pset);
2826 zone_pcp(zone, cpu) = NULL;
2830 static int __cpuinit pageset_cpuup_callback(struct notifier_block *nfb,
2831 unsigned long action,
2832 void *hcpu)
2834 int cpu = (long)hcpu;
2835 int ret = NOTIFY_OK;
2837 switch (action) {
2838 case CPU_UP_PREPARE:
2839 case CPU_UP_PREPARE_FROZEN:
2840 if (process_zones(cpu))
2841 ret = NOTIFY_BAD;
2842 break;
2843 case CPU_UP_CANCELED:
2844 case CPU_UP_CANCELED_FROZEN:
2845 case CPU_DEAD:
2846 case CPU_DEAD_FROZEN:
2847 free_zone_pagesets(cpu);
2848 break;
2849 default:
2850 break;
2852 return ret;
2855 static struct notifier_block __cpuinitdata pageset_notifier =
2856 { &pageset_cpuup_callback, NULL, 0 };
2858 void __init setup_per_cpu_pageset(void)
2860 int err;
2862 /* Initialize per_cpu_pageset for cpu 0.
2863 * A cpuup callback will do this for every cpu
2864 * as it comes online
2866 err = process_zones(smp_processor_id());
2867 BUG_ON(err);
2868 register_cpu_notifier(&pageset_notifier);
2871 #endif
2873 static noinline __init_refok
2874 int zone_wait_table_init(struct zone *zone, unsigned long zone_size_pages)
2876 int i;
2877 struct pglist_data *pgdat = zone->zone_pgdat;
2878 size_t alloc_size;
2881 * The per-page waitqueue mechanism uses hashed waitqueues
2882 * per zone.
2884 zone->wait_table_hash_nr_entries =
2885 wait_table_hash_nr_entries(zone_size_pages);
2886 zone->wait_table_bits =
2887 wait_table_bits(zone->wait_table_hash_nr_entries);
2888 alloc_size = zone->wait_table_hash_nr_entries
2889 * sizeof(wait_queue_head_t);
2891 if (!slab_is_available()) {
2892 zone->wait_table = (wait_queue_head_t *)
2893 alloc_bootmem_node(pgdat, alloc_size);
2894 } else {
2896 * This case means that a zone whose size was 0 gets new memory
2897 * via memory hot-add.
2898 * But it may be the case that a new node was hot-added. In
2899 * this case vmalloc() will not be able to use this new node's
2900 * memory - this wait_table must be initialized to use this new
2901 * node itself as well.
2902 * To use this new node's memory, further consideration will be
2903 * necessary.
2905 zone->wait_table = vmalloc(alloc_size);
2907 if (!zone->wait_table)
2908 return -ENOMEM;
2910 for(i = 0; i < zone->wait_table_hash_nr_entries; ++i)
2911 init_waitqueue_head(zone->wait_table + i);
2913 return 0;
2916 static __meminit void zone_pcp_init(struct zone *zone)
2918 int cpu;
2919 unsigned long batch = zone_batchsize(zone);
2921 for (cpu = 0; cpu < NR_CPUS; cpu++) {
2922 #ifdef CONFIG_NUMA
2923 /* Early boot. Slab allocator not functional yet */
2924 zone_pcp(zone, cpu) = &boot_pageset[cpu];
2925 setup_pageset(&boot_pageset[cpu],0);
2926 #else
2927 setup_pageset(zone_pcp(zone,cpu), batch);
2928 #endif
2930 if (zone->present_pages)
2931 printk(KERN_DEBUG " %s zone: %lu pages, LIFO batch:%lu\n",
2932 zone->name, zone->present_pages, batch);
2935 __meminit int init_currently_empty_zone(struct zone *zone,
2936 unsigned long zone_start_pfn,
2937 unsigned long size,
2938 enum memmap_context context)
2940 struct pglist_data *pgdat = zone->zone_pgdat;
2941 int ret;
2942 ret = zone_wait_table_init(zone, size);
2943 if (ret)
2944 return ret;
2945 pgdat->nr_zones = zone_idx(zone) + 1;
2947 zone->zone_start_pfn = zone_start_pfn;
2949 mminit_dprintk(MMINIT_TRACE, "memmap_init",
2950 "Initialising map node %d zone %lu pfns %lu -> %lu\n",
2951 pgdat->node_id,
2952 (unsigned long)zone_idx(zone),
2953 zone_start_pfn, (zone_start_pfn + size));
2955 zone_init_free_lists(zone);
2957 return 0;
2960 #ifdef CONFIG_ARCH_POPULATES_NODE_MAP
2962 * Basic iterator support. Return the first range of PFNs for a node
2963 * Note: nid == MAX_NUMNODES returns first region regardless of node
2965 static int __meminit first_active_region_index_in_nid(int nid)
2967 int i;
2969 for (i = 0; i < nr_nodemap_entries; i++)
2970 if (nid == MAX_NUMNODES || early_node_map[i].nid == nid)
2971 return i;
2973 return -1;
2977 * Basic iterator support. Return the next active range of PFNs for a node
2978 * Note: nid == MAX_NUMNODES returns next region regardless of node
2980 static int __meminit next_active_region_index_in_nid(int index, int nid)
2982 for (index = index + 1; index < nr_nodemap_entries; index++)
2983 if (nid == MAX_NUMNODES || early_node_map[index].nid == nid)
2984 return index;
2986 return -1;
2989 #ifndef CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID
2991 * Required by SPARSEMEM. Given a PFN, return what node the PFN is on.
2992 * Architectures may implement their own version but if add_active_range()
2993 * was used and there are no special requirements, this is a convenient
2994 * alternative
2996 int __meminit __early_pfn_to_nid(unsigned long pfn)
2998 int i;
3000 for (i = 0; i < nr_nodemap_entries; i++) {
3001 unsigned long start_pfn = early_node_map[i].start_pfn;
3002 unsigned long end_pfn = early_node_map[i].end_pfn;
3004 if (start_pfn <= pfn && pfn < end_pfn)
3005 return early_node_map[i].nid;
3007 /* This is a memory hole */
3008 return -1;
3010 #endif /* CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID */
3012 int __meminit early_pfn_to_nid(unsigned long pfn)
3014 int nid;
3016 nid = __early_pfn_to_nid(pfn);
3017 if (nid >= 0)
3018 return nid;
3019 /* just returns 0 */
3020 return 0;
3023 #ifdef CONFIG_NODES_SPAN_OTHER_NODES
3024 bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
3026 int nid;
3028 nid = __early_pfn_to_nid(pfn);
3029 if (nid >= 0 && nid != node)
3030 return false;
3031 return true;
3033 #endif
3035 /* Basic iterator support to walk early_node_map[] */
3036 #define for_each_active_range_index_in_nid(i, nid) \
3037 for (i = first_active_region_index_in_nid(nid); i != -1; \
3038 i = next_active_region_index_in_nid(i, nid))
3041 * free_bootmem_with_active_regions - Call free_bootmem_node for each active range
3042 * @nid: The node to free memory on. If MAX_NUMNODES, all nodes are freed.
3043 * @max_low_pfn: The highest PFN that will be passed to free_bootmem_node
3045 * If an architecture guarantees that all ranges registered with
3046 * add_active_ranges() contain no holes and may be freed, this
3047 * this function may be used instead of calling free_bootmem() manually.
3049 void __init free_bootmem_with_active_regions(int nid,
3050 unsigned long max_low_pfn)
3052 int i;
3054 for_each_active_range_index_in_nid(i, nid) {
3055 unsigned long size_pages = 0;
3056 unsigned long end_pfn = early_node_map[i].end_pfn;
3058 if (early_node_map[i].start_pfn >= max_low_pfn)
3059 continue;
3061 if (end_pfn > max_low_pfn)
3062 end_pfn = max_low_pfn;
3064 size_pages = end_pfn - early_node_map[i].start_pfn;
3065 free_bootmem_node(NODE_DATA(early_node_map[i].nid),
3066 PFN_PHYS(early_node_map[i].start_pfn),
3067 size_pages << PAGE_SHIFT);
3071 void __init work_with_active_regions(int nid, work_fn_t work_fn, void *data)
3073 int i;
3074 int ret;
3076 for_each_active_range_index_in_nid(i, nid) {
3077 ret = work_fn(early_node_map[i].start_pfn,
3078 early_node_map[i].end_pfn, data);
3079 if (ret)
3080 break;
3084 * sparse_memory_present_with_active_regions - Call memory_present for each active range
3085 * @nid: The node to call memory_present for. If MAX_NUMNODES, all nodes will be used.
3087 * If an architecture guarantees that all ranges registered with
3088 * add_active_ranges() contain no holes and may be freed, this
3089 * function may be used instead of calling memory_present() manually.
3091 void __init sparse_memory_present_with_active_regions(int nid)
3093 int i;
3095 for_each_active_range_index_in_nid(i, nid)
3096 memory_present(early_node_map[i].nid,
3097 early_node_map[i].start_pfn,
3098 early_node_map[i].end_pfn);
3102 * get_pfn_range_for_nid - Return the start and end page frames for a node
3103 * @nid: The nid to return the range for. If MAX_NUMNODES, the min and max PFN are returned.
3104 * @start_pfn: Passed by reference. On return, it will have the node start_pfn.
3105 * @end_pfn: Passed by reference. On return, it will have the node end_pfn.
3107 * It returns the start and end page frame of a node based on information
3108 * provided by an arch calling add_active_range(). If called for a node
3109 * with no available memory, a warning is printed and the start and end
3110 * PFNs will be 0.
3112 void __meminit get_pfn_range_for_nid(unsigned int nid,
3113 unsigned long *start_pfn, unsigned long *end_pfn)
3115 int i;
3116 *start_pfn = -1UL;
3117 *end_pfn = 0;
3119 for_each_active_range_index_in_nid(i, nid) {
3120 *start_pfn = min(*start_pfn, early_node_map[i].start_pfn);
3121 *end_pfn = max(*end_pfn, early_node_map[i].end_pfn);
3124 if (*start_pfn == -1UL)
3125 *start_pfn = 0;
3129 * This finds a zone that can be used for ZONE_MOVABLE pages. The
3130 * assumption is made that zones within a node are ordered in monotonic
3131 * increasing memory addresses so that the "highest" populated zone is used
3133 static void __init find_usable_zone_for_movable(void)
3135 int zone_index;
3136 for (zone_index = MAX_NR_ZONES - 1; zone_index >= 0; zone_index--) {
3137 if (zone_index == ZONE_MOVABLE)
3138 continue;
3140 if (arch_zone_highest_possible_pfn[zone_index] >
3141 arch_zone_lowest_possible_pfn[zone_index])
3142 break;
3145 VM_BUG_ON(zone_index == -1);
3146 movable_zone = zone_index;
3150 * The zone ranges provided by the architecture do not include ZONE_MOVABLE
3151 * because it is sized independant of architecture. Unlike the other zones,
3152 * the starting point for ZONE_MOVABLE is not fixed. It may be different
3153 * in each node depending on the size of each node and how evenly kernelcore
3154 * is distributed. This helper function adjusts the zone ranges
3155 * provided by the architecture for a given node by using the end of the
3156 * highest usable zone for ZONE_MOVABLE. This preserves the assumption that
3157 * zones within a node are in order of monotonic increases memory addresses
3159 static void __meminit adjust_zone_range_for_zone_movable(int nid,
3160 unsigned long zone_type,
3161 unsigned long node_start_pfn,
3162 unsigned long node_end_pfn,
3163 unsigned long *zone_start_pfn,
3164 unsigned long *zone_end_pfn)
3166 /* Only adjust if ZONE_MOVABLE is on this node */
3167 if (zone_movable_pfn[nid]) {
3168 /* Size ZONE_MOVABLE */
3169 if (zone_type == ZONE_MOVABLE) {
3170 *zone_start_pfn = zone_movable_pfn[nid];
3171 *zone_end_pfn = min(node_end_pfn,
3172 arch_zone_highest_possible_pfn[movable_zone]);
3174 /* Adjust for ZONE_MOVABLE starting within this range */
3175 } else if (*zone_start_pfn < zone_movable_pfn[nid] &&
3176 *zone_end_pfn > zone_movable_pfn[nid]) {
3177 *zone_end_pfn = zone_movable_pfn[nid];
3179 /* Check if this whole range is within ZONE_MOVABLE */
3180 } else if (*zone_start_pfn >= zone_movable_pfn[nid])
3181 *zone_start_pfn = *zone_end_pfn;
3186 * Return the number of pages a zone spans in a node, including holes
3187 * present_pages = zone_spanned_pages_in_node() - zone_absent_pages_in_node()
3189 static unsigned long __meminit zone_spanned_pages_in_node(int nid,
3190 unsigned long zone_type,
3191 unsigned long *ignored)
3193 unsigned long node_start_pfn, node_end_pfn;
3194 unsigned long zone_start_pfn, zone_end_pfn;
3196 /* Get the start and end of the node and zone */
3197 get_pfn_range_for_nid(nid, &node_start_pfn, &node_end_pfn);
3198 zone_start_pfn = arch_zone_lowest_possible_pfn[zone_type];
3199 zone_end_pfn = arch_zone_highest_possible_pfn[zone_type];
3200 adjust_zone_range_for_zone_movable(nid, zone_type,
3201 node_start_pfn, node_end_pfn,
3202 &zone_start_pfn, &zone_end_pfn);
3204 /* Check that this node has pages within the zone's required range */
3205 if (zone_end_pfn < node_start_pfn || zone_start_pfn > node_end_pfn)
3206 return 0;
3208 /* Move the zone boundaries inside the node if necessary */
3209 zone_end_pfn = min(zone_end_pfn, node_end_pfn);
3210 zone_start_pfn = max(zone_start_pfn, node_start_pfn);
3212 /* Return the spanned pages */
3213 return zone_end_pfn - zone_start_pfn;
3217 * Return the number of holes in a range on a node. If nid is MAX_NUMNODES,
3218 * then all holes in the requested range will be accounted for.
3220 static unsigned long __meminit __absent_pages_in_range(int nid,
3221 unsigned long range_start_pfn,
3222 unsigned long range_end_pfn)
3224 int i = 0;
3225 unsigned long prev_end_pfn = 0, hole_pages = 0;
3226 unsigned long start_pfn;
3228 /* Find the end_pfn of the first active range of pfns in the node */
3229 i = first_active_region_index_in_nid(nid);
3230 if (i == -1)
3231 return 0;
3233 prev_end_pfn = min(early_node_map[i].start_pfn, range_end_pfn);
3235 /* Account for ranges before physical memory on this node */
3236 if (early_node_map[i].start_pfn > range_start_pfn)
3237 hole_pages = prev_end_pfn - range_start_pfn;
3239 /* Find all holes for the zone within the node */
3240 for (; i != -1; i = next_active_region_index_in_nid(i, nid)) {
3242 /* No need to continue if prev_end_pfn is outside the zone */
3243 if (prev_end_pfn >= range_end_pfn)
3244 break;
3246 /* Make sure the end of the zone is not within the hole */
3247 start_pfn = min(early_node_map[i].start_pfn, range_end_pfn);
3248 prev_end_pfn = max(prev_end_pfn, range_start_pfn);
3250 /* Update the hole size cound and move on */
3251 if (start_pfn > range_start_pfn) {
3252 BUG_ON(prev_end_pfn > start_pfn);
3253 hole_pages += start_pfn - prev_end_pfn;
3255 prev_end_pfn = early_node_map[i].end_pfn;
3258 /* Account for ranges past physical memory on this node */
3259 if (range_end_pfn > prev_end_pfn)
3260 hole_pages += range_end_pfn -
3261 max(range_start_pfn, prev_end_pfn);
3263 return hole_pages;
3267 * absent_pages_in_range - Return number of page frames in holes within a range
3268 * @start_pfn: The start PFN to start searching for holes
3269 * @end_pfn: The end PFN to stop searching for holes
3271 * It returns the number of pages frames in memory holes within a range.
3273 unsigned long __init absent_pages_in_range(unsigned long start_pfn,
3274 unsigned long end_pfn)
3276 return __absent_pages_in_range(MAX_NUMNODES, start_pfn, end_pfn);
3279 /* Return the number of page frames in holes in a zone on a node */
3280 static unsigned long __meminit zone_absent_pages_in_node(int nid,
3281 unsigned long zone_type,
3282 unsigned long *ignored)
3284 unsigned long node_start_pfn, node_end_pfn;
3285 unsigned long zone_start_pfn, zone_end_pfn;
3287 get_pfn_range_for_nid(nid, &node_start_pfn, &node_end_pfn);
3288 zone_start_pfn = max(arch_zone_lowest_possible_pfn[zone_type],
3289 node_start_pfn);
3290 zone_end_pfn = min(arch_zone_highest_possible_pfn[zone_type],
3291 node_end_pfn);
3293 adjust_zone_range_for_zone_movable(nid, zone_type,
3294 node_start_pfn, node_end_pfn,
3295 &zone_start_pfn, &zone_end_pfn);
3296 return __absent_pages_in_range(nid, zone_start_pfn, zone_end_pfn);
3299 #else
3300 static inline unsigned long __meminit zone_spanned_pages_in_node(int nid,
3301 unsigned long zone_type,
3302 unsigned long *zones_size)
3304 return zones_size[zone_type];
3307 static inline unsigned long __meminit zone_absent_pages_in_node(int nid,
3308 unsigned long zone_type,
3309 unsigned long *zholes_size)
3311 if (!zholes_size)
3312 return 0;
3314 return zholes_size[zone_type];
3317 #endif
3319 static void __meminit calculate_node_totalpages(struct pglist_data *pgdat,
3320 unsigned long *zones_size, unsigned long *zholes_size)
3322 unsigned long realtotalpages, totalpages = 0;
3323 enum zone_type i;
3325 for (i = 0; i < MAX_NR_ZONES; i++)
3326 totalpages += zone_spanned_pages_in_node(pgdat->node_id, i,
3327 zones_size);
3328 pgdat->node_spanned_pages = totalpages;
3330 realtotalpages = totalpages;
3331 for (i = 0; i < MAX_NR_ZONES; i++)
3332 realtotalpages -=
3333 zone_absent_pages_in_node(pgdat->node_id, i,
3334 zholes_size);
3335 pgdat->node_present_pages = realtotalpages;
3336 printk(KERN_DEBUG "On node %d totalpages: %lu\n", pgdat->node_id,
3337 realtotalpages);
3340 #ifndef CONFIG_SPARSEMEM
3342 * Calculate the size of the zone->blockflags rounded to an unsigned long
3343 * Start by making sure zonesize is a multiple of pageblock_order by rounding
3344 * up. Then use 1 NR_PAGEBLOCK_BITS worth of bits per pageblock, finally
3345 * round what is now in bits to nearest long in bits, then return it in
3346 * bytes.
3348 static unsigned long __init usemap_size(unsigned long zonesize)
3350 unsigned long usemapsize;
3352 usemapsize = roundup(zonesize, pageblock_nr_pages);
3353 usemapsize = usemapsize >> pageblock_order;
3354 usemapsize *= NR_PAGEBLOCK_BITS;
3355 usemapsize = roundup(usemapsize, 8 * sizeof(unsigned long));
3357 return usemapsize / 8;
3360 static void __init setup_usemap(struct pglist_data *pgdat,
3361 struct zone *zone, unsigned long zonesize)
3363 unsigned long usemapsize = usemap_size(zonesize);
3364 zone->pageblock_flags = NULL;
3365 if (usemapsize)
3366 zone->pageblock_flags = alloc_bootmem_node(pgdat, usemapsize);
3368 #else
3369 static void inline setup_usemap(struct pglist_data *pgdat,
3370 struct zone *zone, unsigned long zonesize) {}
3371 #endif /* CONFIG_SPARSEMEM */
3373 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
3375 /* Return a sensible default order for the pageblock size. */
3376 static inline int pageblock_default_order(void)
3378 if (HPAGE_SHIFT > PAGE_SHIFT)
3379 return HUGETLB_PAGE_ORDER;
3381 return MAX_ORDER-1;
3384 /* Initialise the number of pages represented by NR_PAGEBLOCK_BITS */
3385 static inline void __init set_pageblock_order(unsigned int order)
3387 /* Check that pageblock_nr_pages has not already been setup */
3388 if (pageblock_order)
3389 return;
3392 * Assume the largest contiguous order of interest is a huge page.
3393 * This value may be variable depending on boot parameters on IA64
3395 pageblock_order = order;
3397 #else /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
3400 * When CONFIG_HUGETLB_PAGE_SIZE_VARIABLE is not set, set_pageblock_order()
3401 * and pageblock_default_order() are unused as pageblock_order is set
3402 * at compile-time. See include/linux/pageblock-flags.h for the values of
3403 * pageblock_order based on the kernel config
3405 static inline int pageblock_default_order(unsigned int order)
3407 return MAX_ORDER-1;
3409 #define set_pageblock_order(x) do {} while (0)
3411 #endif /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
3414 * Set up the zone data structures:
3415 * - mark all pages reserved
3416 * - mark all memory queues empty
3417 * - clear the memory bitmaps
3419 static void __paginginit free_area_init_core(struct pglist_data *pgdat,
3420 unsigned long *zones_size, unsigned long *zholes_size)
3422 enum zone_type j;
3423 int nid = pgdat->node_id;
3424 unsigned long zone_start_pfn = pgdat->node_start_pfn;
3425 int ret;
3427 pgdat_resize_init(pgdat);
3428 pgdat->nr_zones = 0;
3429 init_waitqueue_head(&pgdat->kswapd_wait);
3430 pgdat->kswapd_max_order = 0;
3431 pgdat_page_cgroup_init(pgdat);
3433 for (j = 0; j < MAX_NR_ZONES; j++) {
3434 struct zone *zone = pgdat->node_zones + j;
3435 unsigned long size, realsize, memmap_pages;
3436 enum lru_list l;
3438 size = zone_spanned_pages_in_node(nid, j, zones_size);
3439 realsize = size - zone_absent_pages_in_node(nid, j,
3440 zholes_size);
3443 * Adjust realsize so that it accounts for how much memory
3444 * is used by this zone for memmap. This affects the watermark
3445 * and per-cpu initialisations
3447 memmap_pages =
3448 PAGE_ALIGN(size * sizeof(struct page)) >> PAGE_SHIFT;
3449 if (realsize >= memmap_pages) {
3450 realsize -= memmap_pages;
3451 if (memmap_pages)
3452 printk(KERN_DEBUG
3453 " %s zone: %lu pages used for memmap\n",
3454 zone_names[j], memmap_pages);
3455 } else
3456 printk(KERN_WARNING
3457 " %s zone: %lu pages exceeds realsize %lu\n",
3458 zone_names[j], memmap_pages, realsize);
3460 /* Account for reserved pages */
3461 if (j == 0 && realsize > dma_reserve) {
3462 realsize -= dma_reserve;
3463 printk(KERN_DEBUG " %s zone: %lu pages reserved\n",
3464 zone_names[0], dma_reserve);
3467 if (!is_highmem_idx(j))
3468 nr_kernel_pages += realsize;
3469 nr_all_pages += realsize;
3471 zone->spanned_pages = size;
3472 zone->present_pages = realsize;
3473 #ifdef CONFIG_NUMA
3474 zone->node = nid;
3475 zone->min_unmapped_pages = (realsize*sysctl_min_unmapped_ratio)
3476 / 100;
3477 zone->min_slab_pages = (realsize * sysctl_min_slab_ratio) / 100;
3478 #endif
3479 zone->name = zone_names[j];
3480 spin_lock_init(&zone->lock);
3481 spin_lock_init(&zone->lru_lock);
3482 zone_seqlock_init(zone);
3483 zone->zone_pgdat = pgdat;
3485 zone->prev_priority = DEF_PRIORITY;
3487 zone_pcp_init(zone);
3488 for_each_lru(l) {
3489 INIT_LIST_HEAD(&zone->lru[l].list);
3490 zone->lru[l].nr_scan = 0;
3492 zone->reclaim_stat.recent_rotated[0] = 0;
3493 zone->reclaim_stat.recent_rotated[1] = 0;
3494 zone->reclaim_stat.recent_scanned[0] = 0;
3495 zone->reclaim_stat.recent_scanned[1] = 0;
3496 zap_zone_vm_stats(zone);
3497 zone->flags = 0;
3498 if (!size)
3499 continue;
3501 set_pageblock_order(pageblock_default_order());
3502 setup_usemap(pgdat, zone, size);
3503 ret = init_currently_empty_zone(zone, zone_start_pfn,
3504 size, MEMMAP_EARLY);
3505 BUG_ON(ret);
3506 memmap_init(size, nid, j, zone_start_pfn);
3507 zone_start_pfn += size;
3511 static void __init_refok alloc_node_mem_map(struct pglist_data *pgdat)
3513 /* Skip empty nodes */
3514 if (!pgdat->node_spanned_pages)
3515 return;
3517 #ifdef CONFIG_FLAT_NODE_MEM_MAP
3518 /* ia64 gets its own node_mem_map, before this, without bootmem */
3519 if (!pgdat->node_mem_map) {
3520 unsigned long size, start, end;
3521 struct page *map;
3524 * The zone's endpoints aren't required to be MAX_ORDER
3525 * aligned but the node_mem_map endpoints must be in order
3526 * for the buddy allocator to function correctly.
3528 start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1);
3529 end = pgdat->node_start_pfn + pgdat->node_spanned_pages;
3530 end = ALIGN(end, MAX_ORDER_NR_PAGES);
3531 size = (end - start) * sizeof(struct page);
3532 map = alloc_remap(pgdat->node_id, size);
3533 if (!map)
3534 map = alloc_bootmem_node(pgdat, size);
3535 pgdat->node_mem_map = map + (pgdat->node_start_pfn - start);
3537 #ifndef CONFIG_NEED_MULTIPLE_NODES
3539 * With no DISCONTIG, the global mem_map is just set as node 0's
3541 if (pgdat == NODE_DATA(0)) {
3542 mem_map = NODE_DATA(0)->node_mem_map;
3543 #ifdef CONFIG_ARCH_POPULATES_NODE_MAP
3544 if (page_to_pfn(mem_map) != pgdat->node_start_pfn)
3545 mem_map -= (pgdat->node_start_pfn - ARCH_PFN_OFFSET);
3546 #endif /* CONFIG_ARCH_POPULATES_NODE_MAP */
3548 #endif
3549 #endif /* CONFIG_FLAT_NODE_MEM_MAP */
3552 void __paginginit free_area_init_node(int nid, unsigned long *zones_size,
3553 unsigned long node_start_pfn, unsigned long *zholes_size)
3555 pg_data_t *pgdat = NODE_DATA(nid);
3557 pgdat->node_id = nid;
3558 pgdat->node_start_pfn = node_start_pfn;
3559 calculate_node_totalpages(pgdat, zones_size, zholes_size);
3561 alloc_node_mem_map(pgdat);
3562 #ifdef CONFIG_FLAT_NODE_MEM_MAP
3563 printk(KERN_DEBUG "free_area_init_node: node %d, pgdat %08lx, node_mem_map %08lx\n",
3564 nid, (unsigned long)pgdat,
3565 (unsigned long)pgdat->node_mem_map);
3566 #endif
3568 free_area_init_core(pgdat, zones_size, zholes_size);
3571 #ifdef CONFIG_ARCH_POPULATES_NODE_MAP
3573 #if MAX_NUMNODES > 1
3575 * Figure out the number of possible node ids.
3577 static void __init setup_nr_node_ids(void)
3579 unsigned int node;
3580 unsigned int highest = 0;
3582 for_each_node_mask(node, node_possible_map)
3583 highest = node;
3584 nr_node_ids = highest + 1;
3586 #else
3587 static inline void setup_nr_node_ids(void)
3590 #endif
3593 * add_active_range - Register a range of PFNs backed by physical memory
3594 * @nid: The node ID the range resides on
3595 * @start_pfn: The start PFN of the available physical memory
3596 * @end_pfn: The end PFN of the available physical memory
3598 * These ranges are stored in an early_node_map[] and later used by
3599 * free_area_init_nodes() to calculate zone sizes and holes. If the
3600 * range spans a memory hole, it is up to the architecture to ensure
3601 * the memory is not freed by the bootmem allocator. If possible
3602 * the range being registered will be merged with existing ranges.
3604 void __init add_active_range(unsigned int nid, unsigned long start_pfn,
3605 unsigned long end_pfn)
3607 int i;
3609 mminit_dprintk(MMINIT_TRACE, "memory_register",
3610 "Entering add_active_range(%d, %#lx, %#lx) "
3611 "%d entries of %d used\n",
3612 nid, start_pfn, end_pfn,
3613 nr_nodemap_entries, MAX_ACTIVE_REGIONS);
3615 mminit_validate_memmodel_limits(&start_pfn, &end_pfn);
3617 /* Merge with existing active regions if possible */
3618 for (i = 0; i < nr_nodemap_entries; i++) {
3619 if (early_node_map[i].nid != nid)
3620 continue;
3622 /* Skip if an existing region covers this new one */
3623 if (start_pfn >= early_node_map[i].start_pfn &&
3624 end_pfn <= early_node_map[i].end_pfn)
3625 return;
3627 /* Merge forward if suitable */
3628 if (start_pfn <= early_node_map[i].end_pfn &&
3629 end_pfn > early_node_map[i].end_pfn) {
3630 early_node_map[i].end_pfn = end_pfn;
3631 return;
3634 /* Merge backward if suitable */
3635 if (start_pfn < early_node_map[i].end_pfn &&
3636 end_pfn >= early_node_map[i].start_pfn) {
3637 early_node_map[i].start_pfn = start_pfn;
3638 return;
3642 /* Check that early_node_map is large enough */
3643 if (i >= MAX_ACTIVE_REGIONS) {
3644 printk(KERN_CRIT "More than %d memory regions, truncating\n",
3645 MAX_ACTIVE_REGIONS);
3646 return;
3649 early_node_map[i].nid = nid;
3650 early_node_map[i].start_pfn = start_pfn;
3651 early_node_map[i].end_pfn = end_pfn;
3652 nr_nodemap_entries = i + 1;
3656 * remove_active_range - Shrink an existing registered range of PFNs
3657 * @nid: The node id the range is on that should be shrunk
3658 * @start_pfn: The new PFN of the range
3659 * @end_pfn: The new PFN of the range
3661 * i386 with NUMA use alloc_remap() to store a node_mem_map on a local node.
3662 * The map is kept near the end physical page range that has already been
3663 * registered. This function allows an arch to shrink an existing registered
3664 * range.
3666 void __init remove_active_range(unsigned int nid, unsigned long start_pfn,
3667 unsigned long end_pfn)
3669 int i, j;
3670 int removed = 0;
3672 printk(KERN_DEBUG "remove_active_range (%d, %lu, %lu)\n",
3673 nid, start_pfn, end_pfn);
3675 /* Find the old active region end and shrink */
3676 for_each_active_range_index_in_nid(i, nid) {
3677 if (early_node_map[i].start_pfn >= start_pfn &&
3678 early_node_map[i].end_pfn <= end_pfn) {
3679 /* clear it */
3680 early_node_map[i].start_pfn = 0;
3681 early_node_map[i].end_pfn = 0;
3682 removed = 1;
3683 continue;
3685 if (early_node_map[i].start_pfn < start_pfn &&
3686 early_node_map[i].end_pfn > start_pfn) {
3687 unsigned long temp_end_pfn = early_node_map[i].end_pfn;
3688 early_node_map[i].end_pfn = start_pfn;
3689 if (temp_end_pfn > end_pfn)
3690 add_active_range(nid, end_pfn, temp_end_pfn);
3691 continue;
3693 if (early_node_map[i].start_pfn >= start_pfn &&
3694 early_node_map[i].end_pfn > end_pfn &&
3695 early_node_map[i].start_pfn < end_pfn) {
3696 early_node_map[i].start_pfn = end_pfn;
3697 continue;
3701 if (!removed)
3702 return;
3704 /* remove the blank ones */
3705 for (i = nr_nodemap_entries - 1; i > 0; i--) {
3706 if (early_node_map[i].nid != nid)
3707 continue;
3708 if (early_node_map[i].end_pfn)
3709 continue;
3710 /* we found it, get rid of it */
3711 for (j = i; j < nr_nodemap_entries - 1; j++)
3712 memcpy(&early_node_map[j], &early_node_map[j+1],
3713 sizeof(early_node_map[j]));
3714 j = nr_nodemap_entries - 1;
3715 memset(&early_node_map[j], 0, sizeof(early_node_map[j]));
3716 nr_nodemap_entries--;
3721 * remove_all_active_ranges - Remove all currently registered regions
3723 * During discovery, it may be found that a table like SRAT is invalid
3724 * and an alternative discovery method must be used. This function removes
3725 * all currently registered regions.
3727 void __init remove_all_active_ranges(void)
3729 memset(early_node_map, 0, sizeof(early_node_map));
3730 nr_nodemap_entries = 0;
3733 /* Compare two active node_active_regions */
3734 static int __init cmp_node_active_region(const void *a, const void *b)
3736 struct node_active_region *arange = (struct node_active_region *)a;
3737 struct node_active_region *brange = (struct node_active_region *)b;
3739 /* Done this way to avoid overflows */
3740 if (arange->start_pfn > brange->start_pfn)
3741 return 1;
3742 if (arange->start_pfn < brange->start_pfn)
3743 return -1;
3745 return 0;
3748 /* sort the node_map by start_pfn */
3749 static void __init sort_node_map(void)
3751 sort(early_node_map, (size_t)nr_nodemap_entries,
3752 sizeof(struct node_active_region),
3753 cmp_node_active_region, NULL);
3756 /* Find the lowest pfn for a node */
3757 static unsigned long __init find_min_pfn_for_node(int nid)
3759 int i;
3760 unsigned long min_pfn = ULONG_MAX;
3762 /* Assuming a sorted map, the first range found has the starting pfn */
3763 for_each_active_range_index_in_nid(i, nid)
3764 min_pfn = min(min_pfn, early_node_map[i].start_pfn);
3766 if (min_pfn == ULONG_MAX) {
3767 printk(KERN_WARNING
3768 "Could not find start_pfn for node %d\n", nid);
3769 return 0;
3772 return min_pfn;
3776 * find_min_pfn_with_active_regions - Find the minimum PFN registered
3778 * It returns the minimum PFN based on information provided via
3779 * add_active_range().
3781 unsigned long __init find_min_pfn_with_active_regions(void)
3783 return find_min_pfn_for_node(MAX_NUMNODES);
3787 * early_calculate_totalpages()
3788 * Sum pages in active regions for movable zone.
3789 * Populate N_HIGH_MEMORY for calculating usable_nodes.
3791 static unsigned long __init early_calculate_totalpages(void)
3793 int i;
3794 unsigned long totalpages = 0;
3796 for (i = 0; i < nr_nodemap_entries; i++) {
3797 unsigned long pages = early_node_map[i].end_pfn -
3798 early_node_map[i].start_pfn;
3799 totalpages += pages;
3800 if (pages)
3801 node_set_state(early_node_map[i].nid, N_HIGH_MEMORY);
3803 return totalpages;
3807 * Find the PFN the Movable zone begins in each node. Kernel memory
3808 * is spread evenly between nodes as long as the nodes have enough
3809 * memory. When they don't, some nodes will have more kernelcore than
3810 * others
3812 static void __init find_zone_movable_pfns_for_nodes(unsigned long *movable_pfn)
3814 int i, nid;
3815 unsigned long usable_startpfn;
3816 unsigned long kernelcore_node, kernelcore_remaining;
3817 unsigned long totalpages = early_calculate_totalpages();
3818 int usable_nodes = nodes_weight(node_states[N_HIGH_MEMORY]);
3821 * If movablecore was specified, calculate what size of
3822 * kernelcore that corresponds so that memory usable for
3823 * any allocation type is evenly spread. If both kernelcore
3824 * and movablecore are specified, then the value of kernelcore
3825 * will be used for required_kernelcore if it's greater than
3826 * what movablecore would have allowed.
3828 if (required_movablecore) {
3829 unsigned long corepages;
3832 * Round-up so that ZONE_MOVABLE is at least as large as what
3833 * was requested by the user
3835 required_movablecore =
3836 roundup(required_movablecore, MAX_ORDER_NR_PAGES);
3837 corepages = totalpages - required_movablecore;
3839 required_kernelcore = max(required_kernelcore, corepages);
3842 /* If kernelcore was not specified, there is no ZONE_MOVABLE */
3843 if (!required_kernelcore)
3844 return;
3846 /* usable_startpfn is the lowest possible pfn ZONE_MOVABLE can be at */
3847 find_usable_zone_for_movable();
3848 usable_startpfn = arch_zone_lowest_possible_pfn[movable_zone];
3850 restart:
3851 /* Spread kernelcore memory as evenly as possible throughout nodes */
3852 kernelcore_node = required_kernelcore / usable_nodes;
3853 for_each_node_state(nid, N_HIGH_MEMORY) {
3855 * Recalculate kernelcore_node if the division per node
3856 * now exceeds what is necessary to satisfy the requested
3857 * amount of memory for the kernel
3859 if (required_kernelcore < kernelcore_node)
3860 kernelcore_node = required_kernelcore / usable_nodes;
3863 * As the map is walked, we track how much memory is usable
3864 * by the kernel using kernelcore_remaining. When it is
3865 * 0, the rest of the node is usable by ZONE_MOVABLE
3867 kernelcore_remaining = kernelcore_node;
3869 /* Go through each range of PFNs within this node */
3870 for_each_active_range_index_in_nid(i, nid) {
3871 unsigned long start_pfn, end_pfn;
3872 unsigned long size_pages;
3874 start_pfn = max(early_node_map[i].start_pfn,
3875 zone_movable_pfn[nid]);
3876 end_pfn = early_node_map[i].end_pfn;
3877 if (start_pfn >= end_pfn)
3878 continue;
3880 /* Account for what is only usable for kernelcore */
3881 if (start_pfn < usable_startpfn) {
3882 unsigned long kernel_pages;
3883 kernel_pages = min(end_pfn, usable_startpfn)
3884 - start_pfn;
3886 kernelcore_remaining -= min(kernel_pages,
3887 kernelcore_remaining);
3888 required_kernelcore -= min(kernel_pages,
3889 required_kernelcore);
3891 /* Continue if range is now fully accounted */
3892 if (end_pfn <= usable_startpfn) {
3895 * Push zone_movable_pfn to the end so
3896 * that if we have to rebalance
3897 * kernelcore across nodes, we will
3898 * not double account here
3900 zone_movable_pfn[nid] = end_pfn;
3901 continue;
3903 start_pfn = usable_startpfn;
3907 * The usable PFN range for ZONE_MOVABLE is from
3908 * start_pfn->end_pfn. Calculate size_pages as the
3909 * number of pages used as kernelcore
3911 size_pages = end_pfn - start_pfn;
3912 if (size_pages > kernelcore_remaining)
3913 size_pages = kernelcore_remaining;
3914 zone_movable_pfn[nid] = start_pfn + size_pages;
3917 * Some kernelcore has been met, update counts and
3918 * break if the kernelcore for this node has been
3919 * satisified
3921 required_kernelcore -= min(required_kernelcore,
3922 size_pages);
3923 kernelcore_remaining -= size_pages;
3924 if (!kernelcore_remaining)
3925 break;
3930 * If there is still required_kernelcore, we do another pass with one
3931 * less node in the count. This will push zone_movable_pfn[nid] further
3932 * along on the nodes that still have memory until kernelcore is
3933 * satisified
3935 usable_nodes--;
3936 if (usable_nodes && required_kernelcore > usable_nodes)
3937 goto restart;
3939 /* Align start of ZONE_MOVABLE on all nids to MAX_ORDER_NR_PAGES */
3940 for (nid = 0; nid < MAX_NUMNODES; nid++)
3941 zone_movable_pfn[nid] =
3942 roundup(zone_movable_pfn[nid], MAX_ORDER_NR_PAGES);
3945 /* Any regular memory on that node ? */
3946 static void check_for_regular_memory(pg_data_t *pgdat)
3948 #ifdef CONFIG_HIGHMEM
3949 enum zone_type zone_type;
3951 for (zone_type = 0; zone_type <= ZONE_NORMAL; zone_type++) {
3952 struct zone *zone = &pgdat->node_zones[zone_type];
3953 if (zone->present_pages)
3954 node_set_state(zone_to_nid(zone), N_NORMAL_MEMORY);
3956 #endif
3960 * free_area_init_nodes - Initialise all pg_data_t and zone data
3961 * @max_zone_pfn: an array of max PFNs for each zone
3963 * This will call free_area_init_node() for each active node in the system.
3964 * Using the page ranges provided by add_active_range(), the size of each
3965 * zone in each node and their holes is calculated. If the maximum PFN
3966 * between two adjacent zones match, it is assumed that the zone is empty.
3967 * For example, if arch_max_dma_pfn == arch_max_dma32_pfn, it is assumed
3968 * that arch_max_dma32_pfn has no pages. It is also assumed that a zone
3969 * starts where the previous one ended. For example, ZONE_DMA32 starts
3970 * at arch_max_dma_pfn.
3972 void __init free_area_init_nodes(unsigned long *max_zone_pfn)
3974 unsigned long nid;
3975 int i;
3977 /* Sort early_node_map as initialisation assumes it is sorted */
3978 sort_node_map();
3980 /* Record where the zone boundaries are */
3981 memset(arch_zone_lowest_possible_pfn, 0,
3982 sizeof(arch_zone_lowest_possible_pfn));
3983 memset(arch_zone_highest_possible_pfn, 0,
3984 sizeof(arch_zone_highest_possible_pfn));
3985 arch_zone_lowest_possible_pfn[0] = find_min_pfn_with_active_regions();
3986 arch_zone_highest_possible_pfn[0] = max_zone_pfn[0];
3987 for (i = 1; i < MAX_NR_ZONES; i++) {
3988 if (i == ZONE_MOVABLE)
3989 continue;
3990 arch_zone_lowest_possible_pfn[i] =
3991 arch_zone_highest_possible_pfn[i-1];
3992 arch_zone_highest_possible_pfn[i] =
3993 max(max_zone_pfn[i], arch_zone_lowest_possible_pfn[i]);
3995 arch_zone_lowest_possible_pfn[ZONE_MOVABLE] = 0;
3996 arch_zone_highest_possible_pfn[ZONE_MOVABLE] = 0;
3998 /* Find the PFNs that ZONE_MOVABLE begins at in each node */
3999 memset(zone_movable_pfn, 0, sizeof(zone_movable_pfn));
4000 find_zone_movable_pfns_for_nodes(zone_movable_pfn);
4002 /* Print out the zone ranges */
4003 printk("Zone PFN ranges:\n");
4004 for (i = 0; i < MAX_NR_ZONES; i++) {
4005 if (i == ZONE_MOVABLE)
4006 continue;
4007 printk(" %-8s %0#10lx -> %0#10lx\n",
4008 zone_names[i],
4009 arch_zone_lowest_possible_pfn[i],
4010 arch_zone_highest_possible_pfn[i]);
4013 /* Print out the PFNs ZONE_MOVABLE begins at in each node */
4014 printk("Movable zone start PFN for each node\n");
4015 for (i = 0; i < MAX_NUMNODES; i++) {
4016 if (zone_movable_pfn[i])
4017 printk(" Node %d: %lu\n", i, zone_movable_pfn[i]);
4020 /* Print out the early_node_map[] */
4021 printk("early_node_map[%d] active PFN ranges\n", nr_nodemap_entries);
4022 for (i = 0; i < nr_nodemap_entries; i++)
4023 printk(" %3d: %0#10lx -> %0#10lx\n", early_node_map[i].nid,
4024 early_node_map[i].start_pfn,
4025 early_node_map[i].end_pfn);
4027 /* Initialise every node */
4028 mminit_verify_pageflags_layout();
4029 setup_nr_node_ids();
4030 for_each_online_node(nid) {
4031 pg_data_t *pgdat = NODE_DATA(nid);
4032 free_area_init_node(nid, NULL,
4033 find_min_pfn_for_node(nid), NULL);
4035 /* Any memory on that node */
4036 if (pgdat->node_present_pages)
4037 node_set_state(nid, N_HIGH_MEMORY);
4038 check_for_regular_memory(pgdat);
4042 static int __init cmdline_parse_core(char *p, unsigned long *core)
4044 unsigned long long coremem;
4045 if (!p)
4046 return -EINVAL;
4048 coremem = memparse(p, &p);
4049 *core = coremem >> PAGE_SHIFT;
4051 /* Paranoid check that UL is enough for the coremem value */
4052 WARN_ON((coremem >> PAGE_SHIFT) > ULONG_MAX);
4054 return 0;
4058 * kernelcore=size sets the amount of memory for use for allocations that
4059 * cannot be reclaimed or migrated.
4061 static int __init cmdline_parse_kernelcore(char *p)
4063 return cmdline_parse_core(p, &required_kernelcore);
4067 * movablecore=size sets the amount of memory for use for allocations that
4068 * can be reclaimed or migrated.
4070 static int __init cmdline_parse_movablecore(char *p)
4072 return cmdline_parse_core(p, &required_movablecore);
4075 early_param("kernelcore", cmdline_parse_kernelcore);
4076 early_param("movablecore", cmdline_parse_movablecore);
4078 #endif /* CONFIG_ARCH_POPULATES_NODE_MAP */
4081 * set_dma_reserve - set the specified number of pages reserved in the first zone
4082 * @new_dma_reserve: The number of pages to mark reserved
4084 * The per-cpu batchsize and zone watermarks are determined by present_pages.
4085 * In the DMA zone, a significant percentage may be consumed by kernel image
4086 * and other unfreeable allocations which can skew the watermarks badly. This
4087 * function may optionally be used to account for unfreeable pages in the
4088 * first zone (e.g., ZONE_DMA). The effect will be lower watermarks and
4089 * smaller per-cpu batchsize.
4091 void __init set_dma_reserve(unsigned long new_dma_reserve)
4093 dma_reserve = new_dma_reserve;
4096 #ifndef CONFIG_NEED_MULTIPLE_NODES
4097 struct pglist_data __refdata contig_page_data = { .bdata = &bootmem_node_data[0] };
4098 EXPORT_SYMBOL(contig_page_data);
4099 #endif
4101 void __init free_area_init(unsigned long *zones_size)
4103 free_area_init_node(0, zones_size,
4104 __pa(PAGE_OFFSET) >> PAGE_SHIFT, NULL);
4107 static int page_alloc_cpu_notify(struct notifier_block *self,
4108 unsigned long action, void *hcpu)
4110 int cpu = (unsigned long)hcpu;
4112 if (action == CPU_DEAD || action == CPU_DEAD_FROZEN) {
4113 drain_pages(cpu);
4116 * Spill the event counters of the dead processor
4117 * into the current processors event counters.
4118 * This artificially elevates the count of the current
4119 * processor.
4121 vm_events_fold_cpu(cpu);
4124 * Zero the differential counters of the dead processor
4125 * so that the vm statistics are consistent.
4127 * This is only okay since the processor is dead and cannot
4128 * race with what we are doing.
4130 refresh_cpu_vm_stats(cpu);
4132 return NOTIFY_OK;
4135 void __init page_alloc_init(void)
4137 hotcpu_notifier(page_alloc_cpu_notify, 0);
4141 * calculate_totalreserve_pages - called when sysctl_lower_zone_reserve_ratio
4142 * or min_free_kbytes changes.
4144 static void calculate_totalreserve_pages(void)
4146 struct pglist_data *pgdat;
4147 unsigned long reserve_pages = 0;
4148 enum zone_type i, j;
4150 for_each_online_pgdat(pgdat) {
4151 for (i = 0; i < MAX_NR_ZONES; i++) {
4152 struct zone *zone = pgdat->node_zones + i;
4153 unsigned long max = 0;
4155 /* Find valid and maximum lowmem_reserve in the zone */
4156 for (j = i; j < MAX_NR_ZONES; j++) {
4157 if (zone->lowmem_reserve[j] > max)
4158 max = zone->lowmem_reserve[j];
4161 /* we treat pages_high as reserved pages. */
4162 max += zone->pages_high;
4164 if (max > zone->present_pages)
4165 max = zone->present_pages;
4166 reserve_pages += max;
4169 totalreserve_pages = reserve_pages;
4173 * setup_per_zone_lowmem_reserve - called whenever
4174 * sysctl_lower_zone_reserve_ratio changes. Ensures that each zone
4175 * has a correct pages reserved value, so an adequate number of
4176 * pages are left in the zone after a successful __alloc_pages().
4178 static void setup_per_zone_lowmem_reserve(void)
4180 struct pglist_data *pgdat;
4181 enum zone_type j, idx;
4183 for_each_online_pgdat(pgdat) {
4184 for (j = 0; j < MAX_NR_ZONES; j++) {
4185 struct zone *zone = pgdat->node_zones + j;
4186 unsigned long present_pages = zone->present_pages;
4188 zone->lowmem_reserve[j] = 0;
4190 idx = j;
4191 while (idx) {
4192 struct zone *lower_zone;
4194 idx--;
4196 if (sysctl_lowmem_reserve_ratio[idx] < 1)
4197 sysctl_lowmem_reserve_ratio[idx] = 1;
4199 lower_zone = pgdat->node_zones + idx;
4200 lower_zone->lowmem_reserve[j] = present_pages /
4201 sysctl_lowmem_reserve_ratio[idx];
4202 present_pages += lower_zone->present_pages;
4207 /* update totalreserve_pages */
4208 calculate_totalreserve_pages();
4212 * setup_per_zone_pages_min - called when min_free_kbytes changes.
4214 * Ensures that the pages_{min,low,high} values for each zone are set correctly
4215 * with respect to min_free_kbytes.
4217 void setup_per_zone_pages_min(void)
4219 unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
4220 unsigned long lowmem_pages = 0;
4221 struct zone *zone;
4222 unsigned long flags;
4224 /* Calculate total number of !ZONE_HIGHMEM pages */
4225 for_each_zone(zone) {
4226 if (!is_highmem(zone))
4227 lowmem_pages += zone->present_pages;
4230 for_each_zone(zone) {
4231 u64 tmp;
4233 spin_lock_irqsave(&zone->lock, flags);
4234 tmp = (u64)pages_min * zone->present_pages;
4235 do_div(tmp, lowmem_pages);
4236 if (is_highmem(zone)) {
4238 * __GFP_HIGH and PF_MEMALLOC allocations usually don't
4239 * need highmem pages, so cap pages_min to a small
4240 * value here.
4242 * The (pages_high-pages_low) and (pages_low-pages_min)
4243 * deltas controls asynch page reclaim, and so should
4244 * not be capped for highmem.
4246 int min_pages;
4248 min_pages = zone->present_pages / 1024;
4249 if (min_pages < SWAP_CLUSTER_MAX)
4250 min_pages = SWAP_CLUSTER_MAX;
4251 if (min_pages > 128)
4252 min_pages = 128;
4253 zone->pages_min = min_pages;
4254 } else {
4256 * If it's a lowmem zone, reserve a number of pages
4257 * proportionate to the zone's size.
4259 zone->pages_min = tmp;
4262 zone->pages_low = zone->pages_min + (tmp >> 2);
4263 zone->pages_high = zone->pages_min + (tmp >> 1);
4264 setup_zone_migrate_reserve(zone);
4265 spin_unlock_irqrestore(&zone->lock, flags);
4268 /* update totalreserve_pages */
4269 calculate_totalreserve_pages();
4273 * setup_per_zone_inactive_ratio - called when min_free_kbytes changes.
4275 * The inactive anon list should be small enough that the VM never has to
4276 * do too much work, but large enough that each inactive page has a chance
4277 * to be referenced again before it is swapped out.
4279 * The inactive_anon ratio is the target ratio of ACTIVE_ANON to
4280 * INACTIVE_ANON pages on this zone's LRU, maintained by the
4281 * pageout code. A zone->inactive_ratio of 3 means 3:1 or 25% of
4282 * the anonymous pages are kept on the inactive list.
4284 * total target max
4285 * memory ratio inactive anon
4286 * -------------------------------------
4287 * 10MB 1 5MB
4288 * 100MB 1 50MB
4289 * 1GB 3 250MB
4290 * 10GB 10 0.9GB
4291 * 100GB 31 3GB
4292 * 1TB 101 10GB
4293 * 10TB 320 32GB
4295 static void setup_per_zone_inactive_ratio(void)
4297 struct zone *zone;
4299 for_each_zone(zone) {
4300 unsigned int gb, ratio;
4302 /* Zone size in gigabytes */
4303 gb = zone->present_pages >> (30 - PAGE_SHIFT);
4304 ratio = int_sqrt(10 * gb);
4305 if (!ratio)
4306 ratio = 1;
4308 zone->inactive_ratio = ratio;
4313 * Initialise min_free_kbytes.
4315 * For small machines we want it small (128k min). For large machines
4316 * we want it large (64MB max). But it is not linear, because network
4317 * bandwidth does not increase linearly with machine size. We use
4319 * min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
4320 * min_free_kbytes = sqrt(lowmem_kbytes * 16)
4322 * which yields
4324 * 16MB: 512k
4325 * 32MB: 724k
4326 * 64MB: 1024k
4327 * 128MB: 1448k
4328 * 256MB: 2048k
4329 * 512MB: 2896k
4330 * 1024MB: 4096k
4331 * 2048MB: 5792k
4332 * 4096MB: 8192k
4333 * 8192MB: 11584k
4334 * 16384MB: 16384k
4336 static int __init init_per_zone_pages_min(void)
4338 unsigned long lowmem_kbytes;
4340 lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
4342 min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
4343 if (min_free_kbytes < 128)
4344 min_free_kbytes = 128;
4345 if (min_free_kbytes > 65536)
4346 min_free_kbytes = 65536;
4347 setup_per_zone_pages_min();
4348 setup_per_zone_lowmem_reserve();
4349 setup_per_zone_inactive_ratio();
4350 return 0;
4352 module_init(init_per_zone_pages_min)
4355 * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
4356 * that we can call two helper functions whenever min_free_kbytes
4357 * changes.
4359 int min_free_kbytes_sysctl_handler(ctl_table *table, int write,
4360 struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
4362 proc_dointvec(table, write, file, buffer, length, ppos);
4363 if (write)
4364 setup_per_zone_pages_min();
4365 return 0;
4368 #ifdef CONFIG_NUMA
4369 int sysctl_min_unmapped_ratio_sysctl_handler(ctl_table *table, int write,
4370 struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
4372 struct zone *zone;
4373 int rc;
4375 rc = proc_dointvec_minmax(table, write, file, buffer, length, ppos);
4376 if (rc)
4377 return rc;
4379 for_each_zone(zone)
4380 zone->min_unmapped_pages = (zone->present_pages *
4381 sysctl_min_unmapped_ratio) / 100;
4382 return 0;
4385 int sysctl_min_slab_ratio_sysctl_handler(ctl_table *table, int write,
4386 struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
4388 struct zone *zone;
4389 int rc;
4391 rc = proc_dointvec_minmax(table, write, file, buffer, length, ppos);
4392 if (rc)
4393 return rc;
4395 for_each_zone(zone)
4396 zone->min_slab_pages = (zone->present_pages *
4397 sysctl_min_slab_ratio) / 100;
4398 return 0;
4400 #endif
4403 * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
4404 * proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
4405 * whenever sysctl_lowmem_reserve_ratio changes.
4407 * The reserve ratio obviously has absolutely no relation with the
4408 * pages_min watermarks. The lowmem reserve ratio can only make sense
4409 * if in function of the boot time zone sizes.
4411 int lowmem_reserve_ratio_sysctl_handler(ctl_table *table, int write,
4412 struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
4414 proc_dointvec_minmax(table, write, file, buffer, length, ppos);
4415 setup_per_zone_lowmem_reserve();
4416 return 0;
4420 * percpu_pagelist_fraction - changes the pcp->high for each zone on each
4421 * cpu. It is the fraction of total pages in each zone that a hot per cpu pagelist
4422 * can have before it gets flushed back to buddy allocator.
4425 int percpu_pagelist_fraction_sysctl_handler(ctl_table *table, int write,
4426 struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
4428 struct zone *zone;
4429 unsigned int cpu;
4430 int ret;
4432 ret = proc_dointvec_minmax(table, write, file, buffer, length, ppos);
4433 if (!write || (ret == -EINVAL))
4434 return ret;
4435 for_each_zone(zone) {
4436 for_each_online_cpu(cpu) {
4437 unsigned long high;
4438 high = zone->present_pages / percpu_pagelist_fraction;
4439 setup_pagelist_highmark(zone_pcp(zone, cpu), high);
4442 return 0;
4445 int hashdist = HASHDIST_DEFAULT;
4447 #ifdef CONFIG_NUMA
4448 static int __init set_hashdist(char *str)
4450 if (!str)
4451 return 0;
4452 hashdist = simple_strtoul(str, &str, 0);
4453 return 1;
4455 __setup("hashdist=", set_hashdist);
4456 #endif
4459 * allocate a large system hash table from bootmem
4460 * - it is assumed that the hash table must contain an exact power-of-2
4461 * quantity of entries
4462 * - limit is the number of hash buckets, not the total allocation size
4464 void *__init alloc_large_system_hash(const char *tablename,
4465 unsigned long bucketsize,
4466 unsigned long numentries,
4467 int scale,
4468 int flags,
4469 unsigned int *_hash_shift,
4470 unsigned int *_hash_mask,
4471 unsigned long limit)
4473 unsigned long long max = limit;
4474 unsigned long log2qty, size;
4475 void *table = NULL;
4477 /* allow the kernel cmdline to have a say */
4478 if (!numentries) {
4479 /* round applicable memory size up to nearest megabyte */
4480 numentries = nr_kernel_pages;
4481 numentries += (1UL << (20 - PAGE_SHIFT)) - 1;
4482 numentries >>= 20 - PAGE_SHIFT;
4483 numentries <<= 20 - PAGE_SHIFT;
4485 /* limit to 1 bucket per 2^scale bytes of low memory */
4486 if (scale > PAGE_SHIFT)
4487 numentries >>= (scale - PAGE_SHIFT);
4488 else
4489 numentries <<= (PAGE_SHIFT - scale);
4491 /* Make sure we've got at least a 0-order allocation.. */
4492 if (unlikely((numentries * bucketsize) < PAGE_SIZE))
4493 numentries = PAGE_SIZE / bucketsize;
4495 numentries = roundup_pow_of_two(numentries);
4497 /* limit allocation size to 1/16 total memory by default */
4498 if (max == 0) {
4499 max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
4500 do_div(max, bucketsize);
4503 if (numentries > max)
4504 numentries = max;
4506 log2qty = ilog2(numentries);
4508 do {
4509 size = bucketsize << log2qty;
4510 if (flags & HASH_EARLY)
4511 table = alloc_bootmem_nopanic(size);
4512 else if (hashdist)
4513 table = __vmalloc(size, GFP_ATOMIC, PAGE_KERNEL);
4514 else {
4515 unsigned long order = get_order(size);
4516 table = (void*) __get_free_pages(GFP_ATOMIC, order);
4518 * If bucketsize is not a power-of-two, we may free
4519 * some pages at the end of hash table.
4521 if (table) {
4522 unsigned long alloc_end = (unsigned long)table +
4523 (PAGE_SIZE << order);
4524 unsigned long used = (unsigned long)table +
4525 PAGE_ALIGN(size);
4526 split_page(virt_to_page(table), order);
4527 while (used < alloc_end) {
4528 free_page(used);
4529 used += PAGE_SIZE;
4533 } while (!table && size > PAGE_SIZE && --log2qty);
4535 if (!table)
4536 panic("Failed to allocate %s hash table\n", tablename);
4538 printk(KERN_INFO "%s hash table entries: %d (order: %d, %lu bytes)\n",
4539 tablename,
4540 (1U << log2qty),
4541 ilog2(size) - PAGE_SHIFT,
4542 size);
4544 if (_hash_shift)
4545 *_hash_shift = log2qty;
4546 if (_hash_mask)
4547 *_hash_mask = (1 << log2qty) - 1;
4549 return table;
4552 /* Return a pointer to the bitmap storing bits affecting a block of pages */
4553 static inline unsigned long *get_pageblock_bitmap(struct zone *zone,
4554 unsigned long pfn)
4556 #ifdef CONFIG_SPARSEMEM
4557 return __pfn_to_section(pfn)->pageblock_flags;
4558 #else
4559 return zone->pageblock_flags;
4560 #endif /* CONFIG_SPARSEMEM */
4563 static inline int pfn_to_bitidx(struct zone *zone, unsigned long pfn)
4565 #ifdef CONFIG_SPARSEMEM
4566 pfn &= (PAGES_PER_SECTION-1);
4567 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
4568 #else
4569 pfn = pfn - zone->zone_start_pfn;
4570 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
4571 #endif /* CONFIG_SPARSEMEM */
4575 * get_pageblock_flags_group - Return the requested group of flags for the pageblock_nr_pages block of pages
4576 * @page: The page within the block of interest
4577 * @start_bitidx: The first bit of interest to retrieve
4578 * @end_bitidx: The last bit of interest
4579 * returns pageblock_bits flags
4581 unsigned long get_pageblock_flags_group(struct page *page,
4582 int start_bitidx, int end_bitidx)
4584 struct zone *zone;
4585 unsigned long *bitmap;
4586 unsigned long pfn, bitidx;
4587 unsigned long flags = 0;
4588 unsigned long value = 1;
4590 zone = page_zone(page);
4591 pfn = page_to_pfn(page);
4592 bitmap = get_pageblock_bitmap(zone, pfn);
4593 bitidx = pfn_to_bitidx(zone, pfn);
4595 for (; start_bitidx <= end_bitidx; start_bitidx++, value <<= 1)
4596 if (test_bit(bitidx + start_bitidx, bitmap))
4597 flags |= value;
4599 return flags;
4603 * set_pageblock_flags_group - Set the requested group of flags for a pageblock_nr_pages block of pages
4604 * @page: The page within the block of interest
4605 * @start_bitidx: The first bit of interest
4606 * @end_bitidx: The last bit of interest
4607 * @flags: The flags to set
4609 void set_pageblock_flags_group(struct page *page, unsigned long flags,
4610 int start_bitidx, int end_bitidx)
4612 struct zone *zone;
4613 unsigned long *bitmap;
4614 unsigned long pfn, bitidx;
4615 unsigned long value = 1;
4617 zone = page_zone(page);
4618 pfn = page_to_pfn(page);
4619 bitmap = get_pageblock_bitmap(zone, pfn);
4620 bitidx = pfn_to_bitidx(zone, pfn);
4621 VM_BUG_ON(pfn < zone->zone_start_pfn);
4622 VM_BUG_ON(pfn >= zone->zone_start_pfn + zone->spanned_pages);
4624 for (; start_bitidx <= end_bitidx; start_bitidx++, value <<= 1)
4625 if (flags & value)
4626 __set_bit(bitidx + start_bitidx, bitmap);
4627 else
4628 __clear_bit(bitidx + start_bitidx, bitmap);
4632 * This is designed as sub function...plz see page_isolation.c also.
4633 * set/clear page block's type to be ISOLATE.
4634 * page allocater never alloc memory from ISOLATE block.
4637 int set_migratetype_isolate(struct page *page)
4639 struct zone *zone;
4640 unsigned long flags;
4641 int ret = -EBUSY;
4643 zone = page_zone(page);
4644 spin_lock_irqsave(&zone->lock, flags);
4646 * In future, more migrate types will be able to be isolation target.
4648 if (get_pageblock_migratetype(page) != MIGRATE_MOVABLE)
4649 goto out;
4650 set_pageblock_migratetype(page, MIGRATE_ISOLATE);
4651 move_freepages_block(zone, page, MIGRATE_ISOLATE);
4652 ret = 0;
4653 out:
4654 spin_unlock_irqrestore(&zone->lock, flags);
4655 if (!ret)
4656 drain_all_pages();
4657 return ret;
4660 void unset_migratetype_isolate(struct page *page)
4662 struct zone *zone;
4663 unsigned long flags;
4664 zone = page_zone(page);
4665 spin_lock_irqsave(&zone->lock, flags);
4666 if (get_pageblock_migratetype(page) != MIGRATE_ISOLATE)
4667 goto out;
4668 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
4669 move_freepages_block(zone, page, MIGRATE_MOVABLE);
4670 out:
4671 spin_unlock_irqrestore(&zone->lock, flags);
4674 #ifdef CONFIG_MEMORY_HOTREMOVE
4676 * All pages in the range must be isolated before calling this.
4678 void
4679 __offline_isolated_pages(unsigned long start_pfn, unsigned long end_pfn)
4681 struct page *page;
4682 struct zone *zone;
4683 int order, i;
4684 unsigned long pfn;
4685 unsigned long flags;
4686 /* find the first valid pfn */
4687 for (pfn = start_pfn; pfn < end_pfn; pfn++)
4688 if (pfn_valid(pfn))
4689 break;
4690 if (pfn == end_pfn)
4691 return;
4692 zone = page_zone(pfn_to_page(pfn));
4693 spin_lock_irqsave(&zone->lock, flags);
4694 pfn = start_pfn;
4695 while (pfn < end_pfn) {
4696 if (!pfn_valid(pfn)) {
4697 pfn++;
4698 continue;
4700 page = pfn_to_page(pfn);
4701 BUG_ON(page_count(page));
4702 BUG_ON(!PageBuddy(page));
4703 order = page_order(page);
4704 #ifdef CONFIG_DEBUG_VM
4705 printk(KERN_INFO "remove from free list %lx %d %lx\n",
4706 pfn, 1 << order, end_pfn);
4707 #endif
4708 list_del(&page->lru);
4709 rmv_page_order(page);
4710 zone->free_area[order].nr_free--;
4711 __mod_zone_page_state(zone, NR_FREE_PAGES,
4712 - (1UL << order));
4713 for (i = 0; i < (1 << order); i++)
4714 SetPageReserved((page+i));
4715 pfn += (1 << order);
4717 spin_unlock_irqrestore(&zone->lock, flags);
4719 #endif