2 * linux/mm/page_alloc.c
4 * Manages the free list, the system allocates free pages here.
5 * Note that kmalloc() lives in slab.c
7 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
8 * Swap reorganised 29.12.95, Stephen Tweedie
9 * Support of BIGMEM added by Gerhard Wichert, Siemens AG, July 1999
10 * Reshaped it to be a zoned allocator, Ingo Molnar, Red Hat, 1999
11 * Discontiguous memory support, Kanoj Sarcar, SGI, Nov 1999
12 * Zone balancing, Kanoj Sarcar, SGI, Jan 2000
13 * Per cpu hot/cold page lists, bulk allocation, Martin J. Bligh, Sept 2002
14 * (lots of bits borrowed from Ingo Molnar & Andrew Morton)
17 #include <linux/stddef.h>
19 #include <linux/swap.h>
20 #include <linux/interrupt.h>
21 #include <linux/pagemap.h>
22 #include <linux/jiffies.h>
23 #include <linux/bootmem.h>
24 #include <linux/memblock.h>
25 #include <linux/compiler.h>
26 #include <linux/kernel.h>
27 #include <linux/kmemcheck.h>
28 #include <linux/module.h>
29 #include <linux/suspend.h>
30 #include <linux/pagevec.h>
31 #include <linux/blkdev.h>
32 #include <linux/slab.h>
33 #include <linux/ratelimit.h>
34 #include <linux/oom.h>
35 #include <linux/notifier.h>
36 #include <linux/topology.h>
37 #include <linux/sysctl.h>
38 #include <linux/cpu.h>
39 #include <linux/cpuset.h>
40 #include <linux/memory_hotplug.h>
41 #include <linux/nodemask.h>
42 #include <linux/vmalloc.h>
43 #include <linux/vmstat.h>
44 #include <linux/mempolicy.h>
45 #include <linux/stop_machine.h>
46 #include <linux/sort.h>
47 #include <linux/pfn.h>
48 #include <linux/backing-dev.h>
49 #include <linux/fault-inject.h>
50 #include <linux/page-isolation.h>
51 #include <linux/page_cgroup.h>
52 #include <linux/debugobjects.h>
53 #include <linux/kmemleak.h>
54 #include <linux/memory.h>
55 #include <linux/compaction.h>
56 #include <trace/events/kmem.h>
57 #include <linux/ftrace_event.h>
58 #include <linux/memcontrol.h>
59 #include <linux/prefetch.h>
60 #include <linux/page-debug-flags.h>
62 #include <asm/tlbflush.h>
63 #include <asm/div64.h>
66 #ifdef CONFIG_USE_PERCPU_NUMA_NODE_ID
67 DEFINE_PER_CPU(int, numa_node);
68 EXPORT_PER_CPU_SYMBOL(numa_node);
71 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
73 * N.B., Do NOT reference the '_numa_mem_' per cpu variable directly.
74 * It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined.
75 * Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem()
76 * defined in <linux/topology.h>.
78 DEFINE_PER_CPU(int, _numa_mem_); /* Kernel "local memory" node */
79 EXPORT_PER_CPU_SYMBOL(_numa_mem_);
83 * Array of node states.
85 nodemask_t node_states[NR_NODE_STATES] __read_mostly = {
86 [N_POSSIBLE] = NODE_MASK_ALL,
87 [N_ONLINE] = { { [0] = 1UL } },
89 [N_NORMAL_MEMORY] = { { [0] = 1UL } },
91 [N_HIGH_MEMORY] = { { [0] = 1UL } },
93 [N_CPU] = { { [0] = 1UL } },
96 EXPORT_SYMBOL(node_states);
98 unsigned long totalram_pages __read_mostly;
99 unsigned long totalreserve_pages __read_mostly;
101 * When calculating the number of globally allowed dirty pages, there
102 * is a certain number of per-zone reserves that should not be
103 * considered dirtyable memory. This is the sum of those reserves
104 * over all existing zones that contribute dirtyable memory.
106 unsigned long dirty_balance_reserve __read_mostly;
108 int percpu_pagelist_fraction;
109 gfp_t gfp_allowed_mask __read_mostly = GFP_BOOT_MASK;
111 #ifdef CONFIG_PM_SLEEP
113 * The following functions are used by the suspend/hibernate code to temporarily
114 * change gfp_allowed_mask in order to avoid using I/O during memory allocations
115 * while devices are suspended. To avoid races with the suspend/hibernate code,
116 * they should always be called with pm_mutex held (gfp_allowed_mask also should
117 * only be modified with pm_mutex held, unless the suspend/hibernate code is
118 * guaranteed not to run in parallel with that modification).
121 static gfp_t saved_gfp_mask;
123 void pm_restore_gfp_mask(void)
125 WARN_ON(!mutex_is_locked(&pm_mutex));
126 if (saved_gfp_mask) {
127 gfp_allowed_mask = saved_gfp_mask;
132 void pm_restrict_gfp_mask(void)
134 WARN_ON(!mutex_is_locked(&pm_mutex));
135 WARN_ON(saved_gfp_mask);
136 saved_gfp_mask = gfp_allowed_mask;
137 gfp_allowed_mask &= ~GFP_IOFS;
140 bool pm_suspended_storage(void)
142 if ((gfp_allowed_mask & GFP_IOFS) == GFP_IOFS)
146 #endif /* CONFIG_PM_SLEEP */
148 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
149 int pageblock_order __read_mostly;
152 static void __free_pages_ok(struct page *page, unsigned int order);
155 * results with 256, 32 in the lowmem_reserve sysctl:
156 * 1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
157 * 1G machine -> (16M dma, 784M normal, 224M high)
158 * NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
159 * HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
160 * HIGHMEM allocation will (224M+784M)/256 of ram reserved in ZONE_DMA
162 * TBD: should special case ZONE_DMA32 machines here - in those we normally
163 * don't need any ZONE_NORMAL reservation
165 int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES-1] = {
166 #ifdef CONFIG_ZONE_DMA
169 #ifdef CONFIG_ZONE_DMA32
172 #ifdef CONFIG_HIGHMEM
178 EXPORT_SYMBOL(totalram_pages);
180 static char * const zone_names[MAX_NR_ZONES] = {
181 #ifdef CONFIG_ZONE_DMA
184 #ifdef CONFIG_ZONE_DMA32
188 #ifdef CONFIG_HIGHMEM
194 int min_free_kbytes = 1024;
196 static unsigned long __meminitdata nr_kernel_pages;
197 static unsigned long __meminitdata nr_all_pages;
198 static unsigned long __meminitdata dma_reserve;
200 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
201 static unsigned long __meminitdata arch_zone_lowest_possible_pfn[MAX_NR_ZONES];
202 static unsigned long __meminitdata arch_zone_highest_possible_pfn[MAX_NR_ZONES];
203 static unsigned long __initdata required_kernelcore;
204 static unsigned long __initdata required_movablecore;
205 static unsigned long __meminitdata zone_movable_pfn[MAX_NUMNODES];
207 /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
209 EXPORT_SYMBOL(movable_zone);
210 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
213 int nr_node_ids __read_mostly = MAX_NUMNODES;
214 int nr_online_nodes __read_mostly = 1;
215 EXPORT_SYMBOL(nr_node_ids);
216 EXPORT_SYMBOL(nr_online_nodes);
219 int page_group_by_mobility_disabled __read_mostly;
221 static void set_pageblock_migratetype(struct page *page, int migratetype)
224 if (unlikely(page_group_by_mobility_disabled))
225 migratetype = MIGRATE_UNMOVABLE;
227 set_pageblock_flags_group(page, (unsigned long)migratetype,
228 PB_migrate, PB_migrate_end);
231 bool oom_killer_disabled __read_mostly;
233 #ifdef CONFIG_DEBUG_VM
234 static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
238 unsigned long pfn = page_to_pfn(page);
241 seq = zone_span_seqbegin(zone);
242 if (pfn >= zone->zone_start_pfn + zone->spanned_pages)
244 else if (pfn < zone->zone_start_pfn)
246 } while (zone_span_seqretry(zone, seq));
251 static int page_is_consistent(struct zone *zone, struct page *page)
253 if (!pfn_valid_within(page_to_pfn(page)))
255 if (zone != page_zone(page))
261 * Temporary debugging check for pages not lying within a given zone.
263 static int bad_range(struct zone *zone, struct page *page)
265 if (page_outside_zone_boundaries(zone, page))
267 if (!page_is_consistent(zone, page))
273 static inline int bad_range(struct zone *zone, struct page *page)
279 static void bad_page(struct page *page)
281 static unsigned long resume;
282 static unsigned long nr_shown;
283 static unsigned long nr_unshown;
285 /* Don't complain about poisoned pages */
286 if (PageHWPoison(page)) {
287 reset_page_mapcount(page); /* remove PageBuddy */
292 * Allow a burst of 60 reports, then keep quiet for that minute;
293 * or allow a steady drip of one report per second.
295 if (nr_shown == 60) {
296 if (time_before(jiffies, resume)) {
302 "BUG: Bad page state: %lu messages suppressed\n",
309 resume = jiffies + 60 * HZ;
311 printk(KERN_ALERT "BUG: Bad page state in process %s pfn:%05lx\n",
312 current->comm, page_to_pfn(page));
318 /* Leave bad fields for debug, except PageBuddy could make trouble */
319 reset_page_mapcount(page); /* remove PageBuddy */
320 add_taint(TAINT_BAD_PAGE);
324 * Higher-order pages are called "compound pages". They are structured thusly:
326 * The first PAGE_SIZE page is called the "head page".
328 * The remaining PAGE_SIZE pages are called "tail pages".
330 * All pages have PG_compound set. All tail pages have their ->first_page
331 * pointing at the head page.
333 * The first tail page's ->lru.next holds the address of the compound page's
334 * put_page() function. Its ->lru.prev holds the order of allocation.
335 * This usage means that zero-order pages may not be compound.
338 static void free_compound_page(struct page *page)
340 __free_pages_ok(page, compound_order(page));
343 void prep_compound_page(struct page *page, unsigned long order)
346 int nr_pages = 1 << order;
348 set_compound_page_dtor(page, free_compound_page);
349 set_compound_order(page, order);
351 for (i = 1; i < nr_pages; i++) {
352 struct page *p = page + i;
354 set_page_count(p, 0);
355 p->first_page = page;
359 /* update __split_huge_page_refcount if you change this function */
360 static int destroy_compound_page(struct page *page, unsigned long order)
363 int nr_pages = 1 << order;
366 if (unlikely(compound_order(page) != order) ||
367 unlikely(!PageHead(page))) {
372 __ClearPageHead(page);
374 for (i = 1; i < nr_pages; i++) {
375 struct page *p = page + i;
377 if (unlikely(!PageTail(p) || (p->first_page != page))) {
387 static inline void prep_zero_page(struct page *page, int order, gfp_t gfp_flags)
392 * clear_highpage() will use KM_USER0, so it's a bug to use __GFP_ZERO
393 * and __GFP_HIGHMEM from hard or soft interrupt context.
395 VM_BUG_ON((gfp_flags & __GFP_HIGHMEM) && in_interrupt());
396 for (i = 0; i < (1 << order); i++)
397 clear_highpage(page + i);
400 #ifdef CONFIG_DEBUG_PAGEALLOC
401 unsigned int _debug_guardpage_minorder;
403 static int __init debug_guardpage_minorder_setup(char *buf)
407 if (kstrtoul(buf, 10, &res) < 0 || res > MAX_ORDER / 2) {
408 printk(KERN_ERR "Bad debug_guardpage_minorder value\n");
411 _debug_guardpage_minorder = res;
412 printk(KERN_INFO "Setting debug_guardpage_minorder to %lu\n", res);
415 __setup("debug_guardpage_minorder=", debug_guardpage_minorder_setup);
417 static inline void set_page_guard_flag(struct page *page)
419 __set_bit(PAGE_DEBUG_FLAG_GUARD, &page->debug_flags);
422 static inline void clear_page_guard_flag(struct page *page)
424 __clear_bit(PAGE_DEBUG_FLAG_GUARD, &page->debug_flags);
427 static inline void set_page_guard_flag(struct page *page) { }
428 static inline void clear_page_guard_flag(struct page *page) { }
431 static inline void set_page_order(struct page *page, int order)
433 set_page_private(page, order);
434 __SetPageBuddy(page);
437 static inline void rmv_page_order(struct page *page)
439 __ClearPageBuddy(page);
440 set_page_private(page, 0);
444 * Locate the struct page for both the matching buddy in our
445 * pair (buddy1) and the combined O(n+1) page they form (page).
447 * 1) Any buddy B1 will have an order O twin B2 which satisfies
448 * the following equation:
450 * For example, if the starting buddy (buddy2) is #8 its order
452 * B2 = 8 ^ (1 << 1) = 8 ^ 2 = 10
454 * 2) Any buddy B will have an order O+1 parent P which
455 * satisfies the following equation:
458 * Assumption: *_mem_map is contiguous at least up to MAX_ORDER
460 static inline unsigned long
461 __find_buddy_index(unsigned long page_idx, unsigned int order)
463 return page_idx ^ (1 << order);
467 * This function checks whether a page is free && is the buddy
468 * we can do coalesce a page and its buddy if
469 * (a) the buddy is not in a hole &&
470 * (b) the buddy is in the buddy system &&
471 * (c) a page and its buddy have the same order &&
472 * (d) a page and its buddy are in the same zone.
474 * For recording whether a page is in the buddy system, we set ->_mapcount -2.
475 * Setting, clearing, and testing _mapcount -2 is serialized by zone->lock.
477 * For recording page's order, we use page_private(page).
479 static inline int page_is_buddy(struct page *page, struct page *buddy,
482 if (!pfn_valid_within(page_to_pfn(buddy)))
485 if (page_zone_id(page) != page_zone_id(buddy))
488 if (page_is_guard(buddy) && page_order(buddy) == order) {
489 VM_BUG_ON(page_count(buddy) != 0);
493 if (PageBuddy(buddy) && page_order(buddy) == order) {
494 VM_BUG_ON(page_count(buddy) != 0);
501 * Freeing function for a buddy system allocator.
503 * The concept of a buddy system is to maintain direct-mapped table
504 * (containing bit values) for memory blocks of various "orders".
505 * The bottom level table contains the map for the smallest allocatable
506 * units of memory (here, pages), and each level above it describes
507 * pairs of units from the levels below, hence, "buddies".
508 * At a high level, all that happens here is marking the table entry
509 * at the bottom level available, and propagating the changes upward
510 * as necessary, plus some accounting needed to play nicely with other
511 * parts of the VM system.
512 * At each level, we keep a list of pages, which are heads of continuous
513 * free pages of length of (1 << order) and marked with _mapcount -2. Page's
514 * order is recorded in page_private(page) field.
515 * So when we are allocating or freeing one, we can derive the state of the
516 * other. That is, if we allocate a small block, and both were
517 * free, the remainder of the region must be split into blocks.
518 * If a block is freed, and its buddy is also free, then this
519 * triggers coalescing into a block of larger size.
524 static inline void __free_one_page(struct page *page,
525 struct zone *zone, unsigned int order,
528 unsigned long page_idx;
529 unsigned long combined_idx;
530 unsigned long uninitialized_var(buddy_idx);
533 if (unlikely(PageCompound(page)))
534 if (unlikely(destroy_compound_page(page, order)))
537 VM_BUG_ON(migratetype == -1);
539 page_idx = page_to_pfn(page) & ((1 << MAX_ORDER) - 1);
541 VM_BUG_ON(page_idx & ((1 << order) - 1));
542 VM_BUG_ON(bad_range(zone, page));
544 while (order < MAX_ORDER-1) {
545 buddy_idx = __find_buddy_index(page_idx, order);
546 buddy = page + (buddy_idx - page_idx);
547 if (!page_is_buddy(page, buddy, order))
550 * Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page,
551 * merge with it and move up one order.
553 if (page_is_guard(buddy)) {
554 clear_page_guard_flag(buddy);
555 set_page_private(page, 0);
556 __mod_zone_page_state(zone, NR_FREE_PAGES, 1 << order);
558 list_del(&buddy->lru);
559 zone->free_area[order].nr_free--;
560 rmv_page_order(buddy);
562 combined_idx = buddy_idx & page_idx;
563 page = page + (combined_idx - page_idx);
564 page_idx = combined_idx;
567 set_page_order(page, order);
570 * If this is not the largest possible page, check if the buddy
571 * of the next-highest order is free. If it is, it's possible
572 * that pages are being freed that will coalesce soon. In case,
573 * that is happening, add the free page to the tail of the list
574 * so it's less likely to be used soon and more likely to be merged
575 * as a higher order page
577 if ((order < MAX_ORDER-2) && pfn_valid_within(page_to_pfn(buddy))) {
578 struct page *higher_page, *higher_buddy;
579 combined_idx = buddy_idx & page_idx;
580 higher_page = page + (combined_idx - page_idx);
581 buddy_idx = __find_buddy_index(combined_idx, order + 1);
582 higher_buddy = page + (buddy_idx - combined_idx);
583 if (page_is_buddy(higher_page, higher_buddy, order + 1)) {
584 list_add_tail(&page->lru,
585 &zone->free_area[order].free_list[migratetype]);
590 list_add(&page->lru, &zone->free_area[order].free_list[migratetype]);
592 zone->free_area[order].nr_free++;
596 * free_page_mlock() -- clean up attempts to free and mlocked() page.
597 * Page should not be on lru, so no need to fix that up.
598 * free_pages_check() will verify...
600 static inline void free_page_mlock(struct page *page)
602 __dec_zone_page_state(page, NR_MLOCK);
603 __count_vm_event(UNEVICTABLE_MLOCKFREED);
606 static inline int free_pages_check(struct page *page)
608 if (unlikely(page_mapcount(page) |
609 (page->mapping != NULL) |
610 (atomic_read(&page->_count) != 0) |
611 (page->flags & PAGE_FLAGS_CHECK_AT_FREE) |
612 (mem_cgroup_bad_page_check(page)))) {
616 if (page->flags & PAGE_FLAGS_CHECK_AT_PREP)
617 page->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
622 * Frees a number of pages from the PCP lists
623 * Assumes all pages on list are in same zone, and of same order.
624 * count is the number of pages to free.
626 * If the zone was previously in an "all pages pinned" state then look to
627 * see if this freeing clears that state.
629 * And clear the zone's pages_scanned counter, to hold off the "all pages are
630 * pinned" detection logic.
632 static void free_pcppages_bulk(struct zone *zone, int count,
633 struct per_cpu_pages *pcp)
639 spin_lock(&zone->lock);
640 zone->all_unreclaimable = 0;
641 zone->pages_scanned = 0;
645 struct list_head *list;
648 * Remove pages from lists in a round-robin fashion. A
649 * batch_free count is maintained that is incremented when an
650 * empty list is encountered. This is so more pages are freed
651 * off fuller lists instead of spinning excessively around empty
656 if (++migratetype == MIGRATE_PCPTYPES)
658 list = &pcp->lists[migratetype];
659 } while (list_empty(list));
661 /* This is the only non-empty list. Free them all. */
662 if (batch_free == MIGRATE_PCPTYPES)
663 batch_free = to_free;
666 page = list_entry(list->prev, struct page, lru);
667 /* must delete as __free_one_page list manipulates */
668 list_del(&page->lru);
669 /* MIGRATE_MOVABLE list may include MIGRATE_RESERVEs */
670 __free_one_page(page, zone, 0, page_private(page));
671 trace_mm_page_pcpu_drain(page, 0, page_private(page));
672 } while (--to_free && --batch_free && !list_empty(list));
674 __mod_zone_page_state(zone, NR_FREE_PAGES, count);
675 spin_unlock(&zone->lock);
678 static void free_one_page(struct zone *zone, struct page *page, int order,
681 spin_lock(&zone->lock);
682 zone->all_unreclaimable = 0;
683 zone->pages_scanned = 0;
685 __free_one_page(page, zone, order, migratetype);
686 __mod_zone_page_state(zone, NR_FREE_PAGES, 1 << order);
687 spin_unlock(&zone->lock);
690 static bool free_pages_prepare(struct page *page, unsigned int order)
696 if (PageForeign(page)) {
697 PageForeignDestructor(page, order);
702 trace_mm_page_free(page, order);
703 kmemcheck_free_shadow(page, order);
706 page->mapping = NULL;
707 for (i = 0; i < (1 << order); i++)
708 bad += free_pages_check(page + i);
712 if (!PageHighMem(page)) {
713 debug_check_no_locks_freed(page_address(page),PAGE_SIZE<<order);
714 debug_check_no_obj_freed(page_address(page),
717 arch_free_page(page, order);
718 kernel_map_pages(page, 1 << order, 0);
723 static void __free_pages_ok(struct page *page, unsigned int order)
726 int wasMlocked = __TestClearPageMlocked(page);
729 WARN_ON(PageForeign(page) && wasMlocked);
731 if (!free_pages_prepare(page, order))
734 local_irq_save(flags);
735 if (unlikely(wasMlocked))
736 free_page_mlock(page);
737 __count_vm_events(PGFREE, 1 << order);
738 free_one_page(page_zone(page), page, order,
739 get_pageblock_migratetype(page));
740 local_irq_restore(flags);
743 void __meminit __free_pages_bootmem(struct page *page, unsigned int order)
745 unsigned int nr_pages = 1 << order;
749 for (loop = 0; loop < nr_pages; loop++) {
750 struct page *p = &page[loop];
752 if (loop + 1 < nr_pages)
754 __ClearPageReserved(p);
755 set_page_count(p, 0);
758 set_page_refcounted(page);
759 __free_pages(page, order);
764 * The order of subdivision here is critical for the IO subsystem.
765 * Please do not alter this order without good reasons and regression
766 * testing. Specifically, as large blocks of memory are subdivided,
767 * the order in which smaller blocks are delivered depends on the order
768 * they're subdivided in this function. This is the primary factor
769 * influencing the order in which pages are delivered to the IO
770 * subsystem according to empirical testing, and this is also justified
771 * by considering the behavior of a buddy system containing a single
772 * large block of memory acted on by a series of small allocations.
773 * This behavior is a critical factor in sglist merging's success.
777 static inline void expand(struct zone *zone, struct page *page,
778 int low, int high, struct free_area *area,
781 unsigned long size = 1 << high;
787 VM_BUG_ON(bad_range(zone, &page[size]));
789 #ifdef CONFIG_DEBUG_PAGEALLOC
790 if (high < debug_guardpage_minorder()) {
792 * Mark as guard pages (or page), that will allow to
793 * merge back to allocator when buddy will be freed.
794 * Corresponding page table entries will not be touched,
795 * pages will stay not present in virtual address space
797 INIT_LIST_HEAD(&page[size].lru);
798 set_page_guard_flag(&page[size]);
799 set_page_private(&page[size], high);
800 /* Guard pages are not available for any usage */
801 __mod_zone_page_state(zone, NR_FREE_PAGES, -(1 << high));
805 list_add(&page[size].lru, &area->free_list[migratetype]);
807 set_page_order(&page[size], high);
812 * This page is about to be returned from the page allocator
814 static inline int check_new_page(struct page *page)
816 if (unlikely(page_mapcount(page) |
817 (page->mapping != NULL) |
818 (atomic_read(&page->_count) != 0) |
819 (page->flags & PAGE_FLAGS_CHECK_AT_PREP) |
820 (mem_cgroup_bad_page_check(page)))) {
827 static int prep_new_page(struct page *page, int order, gfp_t gfp_flags)
831 for (i = 0; i < (1 << order); i++) {
832 struct page *p = page + i;
833 if (unlikely(check_new_page(p)))
837 set_page_private(page, 0);
838 set_page_refcounted(page);
840 arch_alloc_page(page, order);
841 kernel_map_pages(page, 1 << order, 1);
843 if (gfp_flags & __GFP_ZERO)
844 prep_zero_page(page, order, gfp_flags);
846 if (order && (gfp_flags & __GFP_COMP))
847 prep_compound_page(page, order);
853 * Go through the free lists for the given migratetype and remove
854 * the smallest available page from the freelists
857 struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
860 unsigned int current_order;
861 struct free_area * area;
864 /* Find a page of the appropriate size in the preferred list */
865 for (current_order = order; current_order < MAX_ORDER; ++current_order) {
866 area = &(zone->free_area[current_order]);
867 if (list_empty(&area->free_list[migratetype]))
870 page = list_entry(area->free_list[migratetype].next,
872 list_del(&page->lru);
873 rmv_page_order(page);
875 expand(zone, page, order, current_order, area, migratetype);
884 * This array describes the order lists are fallen back to when
885 * the free lists for the desirable migrate type are depleted
887 static int fallbacks[MIGRATE_TYPES][MIGRATE_TYPES-1] = {
888 [MIGRATE_UNMOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE, MIGRATE_RESERVE },
889 [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE, MIGRATE_MOVABLE, MIGRATE_RESERVE },
890 [MIGRATE_MOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_RESERVE },
891 [MIGRATE_RESERVE] = { MIGRATE_RESERVE, MIGRATE_RESERVE, MIGRATE_RESERVE }, /* Never used */
895 * Move the free pages in a range to the free lists of the requested type.
896 * Note that start_page and end_pages are not aligned on a pageblock
897 * boundary. If alignment is required, use move_freepages_block()
899 static int move_freepages(struct zone *zone,
900 struct page *start_page, struct page *end_page,
907 #ifndef CONFIG_HOLES_IN_ZONE
909 * page_zone is not safe to call in this context when
910 * CONFIG_HOLES_IN_ZONE is set. This bug check is probably redundant
911 * anyway as we check zone boundaries in move_freepages_block().
912 * Remove at a later date when no bug reports exist related to
913 * grouping pages by mobility
915 BUG_ON(page_zone(start_page) != page_zone(end_page));
918 for (page = start_page; page <= end_page;) {
919 /* Make sure we are not inadvertently changing nodes */
920 VM_BUG_ON(page_to_nid(page) != zone_to_nid(zone));
922 if (!pfn_valid_within(page_to_pfn(page))) {
927 if (!PageBuddy(page)) {
932 order = page_order(page);
933 list_move(&page->lru,
934 &zone->free_area[order].free_list[migratetype]);
936 pages_moved += 1 << order;
942 static int move_freepages_block(struct zone *zone, struct page *page,
945 unsigned long start_pfn, end_pfn;
946 struct page *start_page, *end_page;
948 start_pfn = page_to_pfn(page);
949 start_pfn = start_pfn & ~(pageblock_nr_pages-1);
950 start_page = pfn_to_page(start_pfn);
951 end_page = start_page + pageblock_nr_pages - 1;
952 end_pfn = start_pfn + pageblock_nr_pages - 1;
954 /* Do not cross zone boundaries */
955 if (start_pfn < zone->zone_start_pfn)
957 if (end_pfn >= zone->zone_start_pfn + zone->spanned_pages)
960 return move_freepages(zone, start_page, end_page, migratetype);
963 static void change_pageblock_range(struct page *pageblock_page,
964 int start_order, int migratetype)
966 int nr_pageblocks = 1 << (start_order - pageblock_order);
968 while (nr_pageblocks--) {
969 set_pageblock_migratetype(pageblock_page, migratetype);
970 pageblock_page += pageblock_nr_pages;
974 /* Remove an element from the buddy allocator from the fallback list */
975 static inline struct page *
976 __rmqueue_fallback(struct zone *zone, int order, int start_migratetype)
978 struct free_area * area;
983 /* Find the largest possible block of pages in the other list */
984 for (current_order = MAX_ORDER-1; current_order >= order;
986 for (i = 0; i < MIGRATE_TYPES - 1; i++) {
987 migratetype = fallbacks[start_migratetype][i];
989 /* MIGRATE_RESERVE handled later if necessary */
990 if (migratetype == MIGRATE_RESERVE)
993 area = &(zone->free_area[current_order]);
994 if (list_empty(&area->free_list[migratetype]))
997 page = list_entry(area->free_list[migratetype].next,
1002 * If breaking a large block of pages, move all free
1003 * pages to the preferred allocation list. If falling
1004 * back for a reclaimable kernel allocation, be more
1005 * aggressive about taking ownership of free pages
1007 if (unlikely(current_order >= (pageblock_order >> 1)) ||
1008 start_migratetype == MIGRATE_RECLAIMABLE ||
1009 page_group_by_mobility_disabled) {
1010 unsigned long pages;
1011 pages = move_freepages_block(zone, page,
1014 /* Claim the whole block if over half of it is free */
1015 if (pages >= (1 << (pageblock_order-1)) ||
1016 page_group_by_mobility_disabled)
1017 set_pageblock_migratetype(page,
1020 migratetype = start_migratetype;
1023 /* Remove the page from the freelists */
1024 list_del(&page->lru);
1025 rmv_page_order(page);
1027 /* Take ownership for orders >= pageblock_order */
1028 if (current_order >= pageblock_order)
1029 change_pageblock_range(page, current_order,
1032 expand(zone, page, order, current_order, area, migratetype);
1034 trace_mm_page_alloc_extfrag(page, order, current_order,
1035 start_migratetype, migratetype);
1045 * Do the hard work of removing an element from the buddy allocator.
1046 * Call me with the zone->lock already held.
1048 static struct page *__rmqueue(struct zone *zone, unsigned int order,
1054 page = __rmqueue_smallest(zone, order, migratetype);
1056 if (unlikely(!page) && migratetype != MIGRATE_RESERVE) {
1057 page = __rmqueue_fallback(zone, order, migratetype);
1060 * Use MIGRATE_RESERVE rather than fail an allocation. goto
1061 * is used because __rmqueue_smallest is an inline function
1062 * and we want just one call site
1065 migratetype = MIGRATE_RESERVE;
1070 trace_mm_page_alloc_zone_locked(page, order, migratetype);
1075 * Obtain a specified number of elements from the buddy allocator, all under
1076 * a single hold of the lock, for efficiency. Add them to the supplied list.
1077 * Returns the number of new pages which were placed at *list.
1079 static int rmqueue_bulk(struct zone *zone, unsigned int order,
1080 unsigned long count, struct list_head *list,
1081 int migratetype, int cold)
1085 spin_lock(&zone->lock);
1086 for (i = 0; i < count; ++i) {
1087 struct page *page = __rmqueue(zone, order, migratetype);
1088 if (unlikely(page == NULL))
1092 * Split buddy pages returned by expand() are received here
1093 * in physical page order. The page is added to the callers and
1094 * list and the list head then moves forward. From the callers
1095 * perspective, the linked list is ordered by page number in
1096 * some conditions. This is useful for IO devices that can
1097 * merge IO requests if the physical pages are ordered
1100 if (likely(cold == 0))
1101 list_add(&page->lru, list);
1103 list_add_tail(&page->lru, list);
1104 set_page_private(page, migratetype);
1107 __mod_zone_page_state(zone, NR_FREE_PAGES, -(i << order));
1108 spin_unlock(&zone->lock);
1114 * Called from the vmstat counter updater to drain pagesets of this
1115 * currently executing processor on remote nodes after they have
1118 * Note that this function must be called with the thread pinned to
1119 * a single processor.
1121 void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp)
1123 unsigned long flags;
1126 local_irq_save(flags);
1127 if (pcp->count >= pcp->batch)
1128 to_drain = pcp->batch;
1130 to_drain = pcp->count;
1131 free_pcppages_bulk(zone, to_drain, pcp);
1132 pcp->count -= to_drain;
1133 local_irq_restore(flags);
1138 * Drain pages of the indicated processor.
1140 * The processor must either be the current processor and the
1141 * thread pinned to the current processor or a processor that
1144 static void drain_pages(unsigned int cpu)
1146 unsigned long flags;
1149 for_each_populated_zone(zone) {
1150 struct per_cpu_pageset *pset;
1151 struct per_cpu_pages *pcp;
1153 local_irq_save(flags);
1154 pset = per_cpu_ptr(zone->pageset, cpu);
1158 free_pcppages_bulk(zone, pcp->count, pcp);
1161 local_irq_restore(flags);
1166 * Spill all of this CPU's per-cpu pages back into the buddy allocator.
1168 void drain_local_pages(void *arg)
1170 drain_pages(smp_processor_id());
1174 * Spill all the per-cpu pages from all CPUs back into the buddy allocator.
1176 * Note that this code is protected against sending an IPI to an offline
1177 * CPU but does not guarantee sending an IPI to newly hotplugged CPUs:
1178 * on_each_cpu_mask() blocks hotplug and won't talk to offlined CPUs but
1179 * nothing keeps CPUs from showing up after we populated the cpumask and
1180 * before the call to on_each_cpu_mask().
1182 void drain_all_pages(void)
1185 struct per_cpu_pageset *pcp;
1189 * Allocate in the BSS so we wont require allocation in
1190 * direct reclaim path for CONFIG_CPUMASK_OFFSTACK=y
1192 static cpumask_t cpus_with_pcps;
1195 * We don't care about racing with CPU hotplug event
1196 * as offline notification will cause the notified
1197 * cpu to drain that CPU pcps and on_each_cpu_mask
1198 * disables preemption as part of its processing
1200 for_each_online_cpu(cpu) {
1201 bool has_pcps = false;
1202 for_each_populated_zone(zone) {
1203 pcp = per_cpu_ptr(zone->pageset, cpu);
1204 if (pcp->pcp.count) {
1210 cpumask_set_cpu(cpu, &cpus_with_pcps);
1212 cpumask_clear_cpu(cpu, &cpus_with_pcps);
1214 on_each_cpu_mask(&cpus_with_pcps, drain_local_pages, NULL, 1);
1217 #ifdef CONFIG_HIBERNATION
1219 void mark_free_pages(struct zone *zone)
1221 unsigned long pfn, max_zone_pfn;
1222 unsigned long flags;
1224 struct list_head *curr;
1226 if (!zone->spanned_pages)
1229 spin_lock_irqsave(&zone->lock, flags);
1231 max_zone_pfn = zone->zone_start_pfn + zone->spanned_pages;
1232 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
1233 if (pfn_valid(pfn)) {
1234 struct page *page = pfn_to_page(pfn);
1236 if (!swsusp_page_is_forbidden(page))
1237 swsusp_unset_page_free(page);
1240 for_each_migratetype_order(order, t) {
1241 list_for_each(curr, &zone->free_area[order].free_list[t]) {
1244 pfn = page_to_pfn(list_entry(curr, struct page, lru));
1245 for (i = 0; i < (1UL << order); i++)
1246 swsusp_set_page_free(pfn_to_page(pfn + i));
1249 spin_unlock_irqrestore(&zone->lock, flags);
1251 #endif /* CONFIG_PM */
1254 * Free a 0-order page
1255 * cold == 1 ? free a cold page : free a hot page
1257 void free_hot_cold_page(struct page *page, int cold)
1259 struct zone *zone = page_zone(page);
1260 struct per_cpu_pages *pcp;
1261 unsigned long flags;
1263 int wasMlocked = __TestClearPageMlocked(page);
1266 WARN_ON(PageForeign(page) && wasMlocked);
1268 if (!free_pages_prepare(page, 0))
1271 migratetype = get_pageblock_migratetype(page);
1272 set_page_private(page, migratetype);
1273 local_irq_save(flags);
1274 if (unlikely(wasMlocked))
1275 free_page_mlock(page);
1276 __count_vm_event(PGFREE);
1279 * We only track unmovable, reclaimable and movable on pcp lists.
1280 * Free ISOLATE pages back to the allocator because they are being
1281 * offlined but treat RESERVE as movable pages so we can get those
1282 * areas back if necessary. Otherwise, we may have to free
1283 * excessively into the page allocator
1285 if (migratetype >= MIGRATE_PCPTYPES) {
1286 if (unlikely(migratetype == MIGRATE_ISOLATE)) {
1287 free_one_page(zone, page, 0, migratetype);
1290 migratetype = MIGRATE_MOVABLE;
1293 pcp = &this_cpu_ptr(zone->pageset)->pcp;
1295 list_add_tail(&page->lru, &pcp->lists[migratetype]);
1297 list_add(&page->lru, &pcp->lists[migratetype]);
1299 if (pcp->count >= pcp->high) {
1300 free_pcppages_bulk(zone, pcp->batch, pcp);
1301 pcp->count -= pcp->batch;
1305 local_irq_restore(flags);
1309 * Free a list of 0-order pages
1311 void free_hot_cold_page_list(struct list_head *list, int cold)
1313 struct page *page, *next;
1315 list_for_each_entry_safe(page, next, list, lru) {
1316 trace_mm_page_free_batched(page, cold);
1317 free_hot_cold_page(page, cold);
1322 * split_page takes a non-compound higher-order page, and splits it into
1323 * n (1<<order) sub-pages: page[0..n]
1324 * Each sub-page must be freed individually.
1326 * Note: this is probably too low level an operation for use in drivers.
1327 * Please consult with lkml before using this in your driver.
1329 void split_page(struct page *page, unsigned int order)
1333 VM_BUG_ON(PageCompound(page));
1334 VM_BUG_ON(!page_count(page));
1336 #ifdef CONFIG_KMEMCHECK
1338 * Split shadow pages too, because free(page[0]) would
1339 * otherwise free the whole shadow.
1341 if (kmemcheck_page_is_tracked(page))
1342 split_page(virt_to_page(page[0].shadow), order);
1345 for (i = 1; i < (1 << order); i++)
1346 set_page_refcounted(page + i);
1350 * Similar to split_page except the page is already free. As this is only
1351 * being used for migration, the migratetype of the block also changes.
1352 * As this is called with interrupts disabled, the caller is responsible
1353 * for calling arch_alloc_page() and kernel_map_page() after interrupts
1356 * Note: this is probably too low level an operation for use in drivers.
1357 * Please consult with lkml before using this in your driver.
1359 int split_free_page(struct page *page)
1362 unsigned long watermark;
1365 BUG_ON(!PageBuddy(page));
1367 zone = page_zone(page);
1368 order = page_order(page);
1370 /* Obey watermarks as if the page was being allocated */
1371 watermark = low_wmark_pages(zone) + (1 << order);
1372 if (!zone_watermark_ok(zone, 0, watermark, 0, 0))
1375 /* Remove page from free list */
1376 list_del(&page->lru);
1377 zone->free_area[order].nr_free--;
1378 rmv_page_order(page);
1379 __mod_zone_page_state(zone, NR_FREE_PAGES, -(1UL << order));
1381 /* Split into individual pages */
1382 set_page_refcounted(page);
1383 split_page(page, order);
1385 if (order >= pageblock_order - 1) {
1386 struct page *endpage = page + (1 << order) - 1;
1387 for (; page < endpage; page += pageblock_nr_pages)
1388 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
1395 * Really, prep_compound_page() should be called from __rmqueue_bulk(). But
1396 * we cheat by calling it from here, in the order > 0 path. Saves a branch
1400 struct page *buffered_rmqueue(struct zone *preferred_zone,
1401 struct zone *zone, int order, gfp_t gfp_flags,
1404 unsigned long flags;
1406 int cold = !!(gfp_flags & __GFP_COLD);
1409 if (likely(order == 0)) {
1410 struct per_cpu_pages *pcp;
1411 struct list_head *list;
1413 local_irq_save(flags);
1414 pcp = &this_cpu_ptr(zone->pageset)->pcp;
1415 list = &pcp->lists[migratetype];
1416 if (list_empty(list)) {
1417 pcp->count += rmqueue_bulk(zone, 0,
1420 if (unlikely(list_empty(list)))
1425 page = list_entry(list->prev, struct page, lru);
1427 page = list_entry(list->next, struct page, lru);
1429 list_del(&page->lru);
1432 if (unlikely(gfp_flags & __GFP_NOFAIL)) {
1434 * __GFP_NOFAIL is not to be used in new code.
1436 * All __GFP_NOFAIL callers should be fixed so that they
1437 * properly detect and handle allocation failures.
1439 * We most definitely don't want callers attempting to
1440 * allocate greater than order-1 page units with
1443 WARN_ON_ONCE(order > 1);
1445 spin_lock_irqsave(&zone->lock, flags);
1446 page = __rmqueue(zone, order, migratetype);
1447 spin_unlock(&zone->lock);
1450 __mod_zone_page_state(zone, NR_FREE_PAGES, -(1 << order));
1453 __count_zone_vm_events(PGALLOC, zone, 1 << order);
1454 zone_statistics(preferred_zone, zone, gfp_flags);
1455 local_irq_restore(flags);
1457 VM_BUG_ON(bad_range(zone, page));
1458 if (prep_new_page(page, order, gfp_flags))
1463 local_irq_restore(flags);
1467 /* The ALLOC_WMARK bits are used as an index to zone->watermark */
1468 #define ALLOC_WMARK_MIN WMARK_MIN
1469 #define ALLOC_WMARK_LOW WMARK_LOW
1470 #define ALLOC_WMARK_HIGH WMARK_HIGH
1471 #define ALLOC_NO_WATERMARKS 0x04 /* don't check watermarks at all */
1473 /* Mask to get the watermark bits */
1474 #define ALLOC_WMARK_MASK (ALLOC_NO_WATERMARKS-1)
1476 #define ALLOC_HARDER 0x10 /* try to alloc harder */
1477 #define ALLOC_HIGH 0x20 /* __GFP_HIGH set */
1478 #define ALLOC_CPUSET 0x40 /* check for correct cpuset */
1480 #ifdef CONFIG_FAIL_PAGE_ALLOC
1483 struct fault_attr attr;
1485 u32 ignore_gfp_highmem;
1486 u32 ignore_gfp_wait;
1488 } fail_page_alloc = {
1489 .attr = FAULT_ATTR_INITIALIZER,
1490 .ignore_gfp_wait = 1,
1491 .ignore_gfp_highmem = 1,
1495 static int __init setup_fail_page_alloc(char *str)
1497 return setup_fault_attr(&fail_page_alloc.attr, str);
1499 __setup("fail_page_alloc=", setup_fail_page_alloc);
1501 static int should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
1503 if (order < fail_page_alloc.min_order)
1505 if (gfp_mask & __GFP_NOFAIL)
1507 if (fail_page_alloc.ignore_gfp_highmem && (gfp_mask & __GFP_HIGHMEM))
1509 if (fail_page_alloc.ignore_gfp_wait && (gfp_mask & __GFP_WAIT))
1512 return should_fail(&fail_page_alloc.attr, 1 << order);
1515 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
1517 static int __init fail_page_alloc_debugfs(void)
1519 umode_t mode = S_IFREG | S_IRUSR | S_IWUSR;
1522 dir = fault_create_debugfs_attr("fail_page_alloc", NULL,
1523 &fail_page_alloc.attr);
1525 return PTR_ERR(dir);
1527 if (!debugfs_create_bool("ignore-gfp-wait", mode, dir,
1528 &fail_page_alloc.ignore_gfp_wait))
1530 if (!debugfs_create_bool("ignore-gfp-highmem", mode, dir,
1531 &fail_page_alloc.ignore_gfp_highmem))
1533 if (!debugfs_create_u32("min-order", mode, dir,
1534 &fail_page_alloc.min_order))
1539 debugfs_remove_recursive(dir);
1544 late_initcall(fail_page_alloc_debugfs);
1546 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
1548 #else /* CONFIG_FAIL_PAGE_ALLOC */
1550 static inline int should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
1555 #endif /* CONFIG_FAIL_PAGE_ALLOC */
1558 * Return true if free pages are above 'mark'. This takes into account the order
1559 * of the allocation.
1561 static bool __zone_watermark_ok(struct zone *z, int order, unsigned long mark,
1562 int classzone_idx, int alloc_flags, long free_pages)
1564 /* free_pages my go negative - that's OK */
1568 free_pages -= (1 << order) - 1;
1569 if (alloc_flags & ALLOC_HIGH)
1571 if (alloc_flags & ALLOC_HARDER)
1574 if (free_pages <= min + z->lowmem_reserve[classzone_idx])
1576 for (o = 0; o < order; o++) {
1577 /* At the next order, this order's pages become unavailable */
1578 free_pages -= z->free_area[o].nr_free << o;
1580 /* Require fewer higher order pages to be free */
1583 if (free_pages <= min)
1589 bool zone_watermark_ok(struct zone *z, int order, unsigned long mark,
1590 int classzone_idx, int alloc_flags)
1592 return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
1593 zone_page_state(z, NR_FREE_PAGES));
1596 bool zone_watermark_ok_safe(struct zone *z, int order, unsigned long mark,
1597 int classzone_idx, int alloc_flags)
1599 long free_pages = zone_page_state(z, NR_FREE_PAGES);
1601 if (z->percpu_drift_mark && free_pages < z->percpu_drift_mark)
1602 free_pages = zone_page_state_snapshot(z, NR_FREE_PAGES);
1604 return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
1610 * zlc_setup - Setup for "zonelist cache". Uses cached zone data to
1611 * skip over zones that are not allowed by the cpuset, or that have
1612 * been recently (in last second) found to be nearly full. See further
1613 * comments in mmzone.h. Reduces cache footprint of zonelist scans
1614 * that have to skip over a lot of full or unallowed zones.
1616 * If the zonelist cache is present in the passed in zonelist, then
1617 * returns a pointer to the allowed node mask (either the current
1618 * tasks mems_allowed, or node_states[N_HIGH_MEMORY].)
1620 * If the zonelist cache is not available for this zonelist, does
1621 * nothing and returns NULL.
1623 * If the fullzones BITMAP in the zonelist cache is stale (more than
1624 * a second since last zap'd) then we zap it out (clear its bits.)
1626 * We hold off even calling zlc_setup, until after we've checked the
1627 * first zone in the zonelist, on the theory that most allocations will
1628 * be satisfied from that first zone, so best to examine that zone as
1629 * quickly as we can.
1631 static nodemask_t *zlc_setup(struct zonelist *zonelist, int alloc_flags)
1633 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1634 nodemask_t *allowednodes; /* zonelist_cache approximation */
1636 zlc = zonelist->zlcache_ptr;
1640 if (time_after(jiffies, zlc->last_full_zap + HZ)) {
1641 bitmap_zero(zlc->fullzones, MAX_ZONES_PER_ZONELIST);
1642 zlc->last_full_zap = jiffies;
1645 allowednodes = !in_interrupt() && (alloc_flags & ALLOC_CPUSET) ?
1646 &cpuset_current_mems_allowed :
1647 &node_states[N_HIGH_MEMORY];
1648 return allowednodes;
1652 * Given 'z' scanning a zonelist, run a couple of quick checks to see
1653 * if it is worth looking at further for free memory:
1654 * 1) Check that the zone isn't thought to be full (doesn't have its
1655 * bit set in the zonelist_cache fullzones BITMAP).
1656 * 2) Check that the zones node (obtained from the zonelist_cache
1657 * z_to_n[] mapping) is allowed in the passed in allowednodes mask.
1658 * Return true (non-zero) if zone is worth looking at further, or
1659 * else return false (zero) if it is not.
1661 * This check -ignores- the distinction between various watermarks,
1662 * such as GFP_HIGH, GFP_ATOMIC, PF_MEMALLOC, ... If a zone is
1663 * found to be full for any variation of these watermarks, it will
1664 * be considered full for up to one second by all requests, unless
1665 * we are so low on memory on all allowed nodes that we are forced
1666 * into the second scan of the zonelist.
1668 * In the second scan we ignore this zonelist cache and exactly
1669 * apply the watermarks to all zones, even it is slower to do so.
1670 * We are low on memory in the second scan, and should leave no stone
1671 * unturned looking for a free page.
1673 static int zlc_zone_worth_trying(struct zonelist *zonelist, struct zoneref *z,
1674 nodemask_t *allowednodes)
1676 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1677 int i; /* index of *z in zonelist zones */
1678 int n; /* node that zone *z is on */
1680 zlc = zonelist->zlcache_ptr;
1684 i = z - zonelist->_zonerefs;
1687 /* This zone is worth trying if it is allowed but not full */
1688 return node_isset(n, *allowednodes) && !test_bit(i, zlc->fullzones);
1692 * Given 'z' scanning a zonelist, set the corresponding bit in
1693 * zlc->fullzones, so that subsequent attempts to allocate a page
1694 * from that zone don't waste time re-examining it.
1696 static void zlc_mark_zone_full(struct zonelist *zonelist, struct zoneref *z)
1698 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1699 int i; /* index of *z in zonelist zones */
1701 zlc = zonelist->zlcache_ptr;
1705 i = z - zonelist->_zonerefs;
1707 set_bit(i, zlc->fullzones);
1711 * clear all zones full, called after direct reclaim makes progress so that
1712 * a zone that was recently full is not skipped over for up to a second
1714 static void zlc_clear_zones_full(struct zonelist *zonelist)
1716 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1718 zlc = zonelist->zlcache_ptr;
1722 bitmap_zero(zlc->fullzones, MAX_ZONES_PER_ZONELIST);
1725 #else /* CONFIG_NUMA */
1727 static nodemask_t *zlc_setup(struct zonelist *zonelist, int alloc_flags)
1732 static int zlc_zone_worth_trying(struct zonelist *zonelist, struct zoneref *z,
1733 nodemask_t *allowednodes)
1738 static void zlc_mark_zone_full(struct zonelist *zonelist, struct zoneref *z)
1742 static void zlc_clear_zones_full(struct zonelist *zonelist)
1745 #endif /* CONFIG_NUMA */
1748 * get_page_from_freelist goes through the zonelist trying to allocate
1751 static struct page *
1752 get_page_from_freelist(gfp_t gfp_mask, nodemask_t *nodemask, unsigned int order,
1753 struct zonelist *zonelist, int high_zoneidx, int alloc_flags,
1754 struct zone *preferred_zone, int migratetype)
1757 struct page *page = NULL;
1760 nodemask_t *allowednodes = NULL;/* zonelist_cache approximation */
1761 int zlc_active = 0; /* set if using zonelist_cache */
1762 int did_zlc_setup = 0; /* just call zlc_setup() one time */
1764 classzone_idx = zone_idx(preferred_zone);
1767 * Scan zonelist, looking for a zone with enough free.
1768 * See also cpuset_zone_allowed() comment in kernel/cpuset.c.
1770 for_each_zone_zonelist_nodemask(zone, z, zonelist,
1771 high_zoneidx, nodemask) {
1772 if (NUMA_BUILD && zlc_active &&
1773 !zlc_zone_worth_trying(zonelist, z, allowednodes))
1775 if ((alloc_flags & ALLOC_CPUSET) &&
1776 !cpuset_zone_allowed_softwall(zone, gfp_mask))
1779 * When allocating a page cache page for writing, we
1780 * want to get it from a zone that is within its dirty
1781 * limit, such that no single zone holds more than its
1782 * proportional share of globally allowed dirty pages.
1783 * The dirty limits take into account the zone's
1784 * lowmem reserves and high watermark so that kswapd
1785 * should be able to balance it without having to
1786 * write pages from its LRU list.
1788 * This may look like it could increase pressure on
1789 * lower zones by failing allocations in higher zones
1790 * before they are full. But the pages that do spill
1791 * over are limited as the lower zones are protected
1792 * by this very same mechanism. It should not become
1793 * a practical burden to them.
1795 * XXX: For now, allow allocations to potentially
1796 * exceed the per-zone dirty limit in the slowpath
1797 * (ALLOC_WMARK_LOW unset) before going into reclaim,
1798 * which is important when on a NUMA setup the allowed
1799 * zones are together not big enough to reach the
1800 * global limit. The proper fix for these situations
1801 * will require awareness of zones in the
1802 * dirty-throttling and the flusher threads.
1804 if ((alloc_flags & ALLOC_WMARK_LOW) &&
1805 (gfp_mask & __GFP_WRITE) && !zone_dirty_ok(zone))
1806 goto this_zone_full;
1808 BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK);
1809 if (!(alloc_flags & ALLOC_NO_WATERMARKS)) {
1813 mark = zone->watermark[alloc_flags & ALLOC_WMARK_MASK];
1814 if (zone_watermark_ok(zone, order, mark,
1815 classzone_idx, alloc_flags))
1818 if (NUMA_BUILD && !did_zlc_setup && nr_online_nodes > 1) {
1820 * we do zlc_setup if there are multiple nodes
1821 * and before considering the first zone allowed
1824 allowednodes = zlc_setup(zonelist, alloc_flags);
1829 if (zone_reclaim_mode == 0)
1830 goto this_zone_full;
1833 * As we may have just activated ZLC, check if the first
1834 * eligible zone has failed zone_reclaim recently.
1836 if (NUMA_BUILD && zlc_active &&
1837 !zlc_zone_worth_trying(zonelist, z, allowednodes))
1840 ret = zone_reclaim(zone, gfp_mask, order);
1842 case ZONE_RECLAIM_NOSCAN:
1845 case ZONE_RECLAIM_FULL:
1846 /* scanned but unreclaimable */
1849 /* did we reclaim enough */
1850 if (!zone_watermark_ok(zone, order, mark,
1851 classzone_idx, alloc_flags))
1852 goto this_zone_full;
1857 page = buffered_rmqueue(preferred_zone, zone, order,
1858 gfp_mask, migratetype);
1863 zlc_mark_zone_full(zonelist, z);
1866 if (unlikely(NUMA_BUILD && page == NULL && zlc_active)) {
1867 /* Disable zlc cache for second zonelist scan */
1875 * Large machines with many possible nodes should not always dump per-node
1876 * meminfo in irq context.
1878 static inline bool should_suppress_show_mem(void)
1883 ret = in_interrupt();
1888 static DEFINE_RATELIMIT_STATE(nopage_rs,
1889 DEFAULT_RATELIMIT_INTERVAL,
1890 DEFAULT_RATELIMIT_BURST);
1892 void warn_alloc_failed(gfp_t gfp_mask, int order, const char *fmt, ...)
1894 unsigned int filter = SHOW_MEM_FILTER_NODES;
1896 if ((gfp_mask & __GFP_NOWARN) || !__ratelimit(&nopage_rs) ||
1897 debug_guardpage_minorder() > 0)
1901 * This documents exceptions given to allocations in certain
1902 * contexts that are allowed to allocate outside current's set
1905 if (!(gfp_mask & __GFP_NOMEMALLOC))
1906 if (test_thread_flag(TIF_MEMDIE) ||
1907 (current->flags & (PF_MEMALLOC | PF_EXITING)))
1908 filter &= ~SHOW_MEM_FILTER_NODES;
1909 if (in_interrupt() || !(gfp_mask & __GFP_WAIT))
1910 filter &= ~SHOW_MEM_FILTER_NODES;
1913 struct va_format vaf;
1916 va_start(args, fmt);
1921 pr_warn("%pV", &vaf);
1926 if (!(gfp_mask & __GFP_WAIT)) {
1927 pr_info("The following is only an harmless informational message.\n");
1928 pr_info("Unless you get a _continuous_flood_ of these messages it means\n");
1929 pr_info("everything is working fine. Allocations from irqs cannot be\n");
1930 pr_info("perfectly reliable and the kernel is designed to handle that.\n");
1932 pr_info("%s: page allocation failure. order:%d, mode:0x%x\n",
1933 current->comm, order, gfp_mask);
1936 if (!should_suppress_show_mem())
1941 should_alloc_retry(gfp_t gfp_mask, unsigned int order,
1942 unsigned long did_some_progress,
1943 unsigned long pages_reclaimed)
1945 /* Do not loop if specifically requested */
1946 if (gfp_mask & __GFP_NORETRY)
1949 /* Always retry if specifically requested */
1950 if (gfp_mask & __GFP_NOFAIL)
1954 * Suspend converts GFP_KERNEL to __GFP_WAIT which can prevent reclaim
1955 * making forward progress without invoking OOM. Suspend also disables
1956 * storage devices so kswapd will not help. Bail if we are suspending.
1958 if (!did_some_progress && pm_suspended_storage())
1962 * In this implementation, order <= PAGE_ALLOC_COSTLY_ORDER
1963 * means __GFP_NOFAIL, but that may not be true in other
1966 if (order <= PAGE_ALLOC_COSTLY_ORDER)
1970 * For order > PAGE_ALLOC_COSTLY_ORDER, if __GFP_REPEAT is
1971 * specified, then we retry until we no longer reclaim any pages
1972 * (above), or we've reclaimed an order of pages at least as
1973 * large as the allocation's order. In both cases, if the
1974 * allocation still fails, we stop retrying.
1976 if (gfp_mask & __GFP_REPEAT && pages_reclaimed < (1 << order))
1982 static inline struct page *
1983 __alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order,
1984 struct zonelist *zonelist, enum zone_type high_zoneidx,
1985 nodemask_t *nodemask, struct zone *preferred_zone,
1990 /* Acquire the OOM killer lock for the zones in zonelist */
1991 if (!try_set_zonelist_oom(zonelist, gfp_mask)) {
1992 schedule_timeout_uninterruptible(1);
1997 * Go through the zonelist yet one more time, keep very high watermark
1998 * here, this is only to catch a parallel oom killing, we must fail if
1999 * we're still under heavy pressure.
2001 page = get_page_from_freelist(gfp_mask|__GFP_HARDWALL, nodemask,
2002 order, zonelist, high_zoneidx,
2003 ALLOC_WMARK_HIGH|ALLOC_CPUSET,
2004 preferred_zone, migratetype);
2008 if (!(gfp_mask & __GFP_NOFAIL)) {
2009 /* The OOM killer will not help higher order allocs */
2010 if (order > PAGE_ALLOC_COSTLY_ORDER)
2012 /* The OOM killer does not needlessly kill tasks for lowmem */
2013 if (high_zoneidx < ZONE_NORMAL)
2016 * GFP_THISNODE contains __GFP_NORETRY and we never hit this.
2017 * Sanity check for bare calls of __GFP_THISNODE, not real OOM.
2018 * The caller should handle page allocation failure by itself if
2019 * it specifies __GFP_THISNODE.
2020 * Note: Hugepage uses it but will hit PAGE_ALLOC_COSTLY_ORDER.
2022 if (gfp_mask & __GFP_THISNODE)
2025 /* Exhausted what can be done so it's blamo time */
2026 out_of_memory(zonelist, gfp_mask, order, nodemask, false);
2029 clear_zonelist_oom(zonelist, gfp_mask);
2033 #ifdef CONFIG_COMPACTION
2034 /* Try memory compaction for high-order allocations before reclaim */
2035 static struct page *
2036 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
2037 struct zonelist *zonelist, enum zone_type high_zoneidx,
2038 nodemask_t *nodemask, int alloc_flags, struct zone *preferred_zone,
2039 int migratetype, bool sync_migration,
2040 bool *deferred_compaction,
2041 unsigned long *did_some_progress)
2048 if (compaction_deferred(preferred_zone, order)) {
2049 *deferred_compaction = true;
2053 current->flags |= PF_MEMALLOC;
2054 *did_some_progress = try_to_compact_pages(zonelist, order, gfp_mask,
2055 nodemask, sync_migration);
2056 current->flags &= ~PF_MEMALLOC;
2057 if (*did_some_progress != COMPACT_SKIPPED) {
2059 /* Page migration frees to the PCP lists but we want merging */
2060 drain_pages(get_cpu());
2063 page = get_page_from_freelist(gfp_mask, nodemask,
2064 order, zonelist, high_zoneidx,
2065 alloc_flags, preferred_zone,
2068 preferred_zone->compact_considered = 0;
2069 preferred_zone->compact_defer_shift = 0;
2070 if (order >= preferred_zone->compact_order_failed)
2071 preferred_zone->compact_order_failed = order + 1;
2072 count_vm_event(COMPACTSUCCESS);
2077 * It's bad if compaction run occurs and fails.
2078 * The most likely reason is that pages exist,
2079 * but not enough to satisfy watermarks.
2081 count_vm_event(COMPACTFAIL);
2084 * As async compaction considers a subset of pageblocks, only
2085 * defer if the failure was a sync compaction failure.
2088 defer_compaction(preferred_zone, order);
2096 static inline struct page *
2097 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
2098 struct zonelist *zonelist, enum zone_type high_zoneidx,
2099 nodemask_t *nodemask, int alloc_flags, struct zone *preferred_zone,
2100 int migratetype, bool sync_migration,
2101 bool *deferred_compaction,
2102 unsigned long *did_some_progress)
2106 #endif /* CONFIG_COMPACTION */
2108 /* The really slow allocator path where we enter direct reclaim */
2109 static inline struct page *
2110 __alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order,
2111 struct zonelist *zonelist, enum zone_type high_zoneidx,
2112 nodemask_t *nodemask, int alloc_flags, struct zone *preferred_zone,
2113 int migratetype, unsigned long *did_some_progress)
2115 struct page *page = NULL;
2116 struct reclaim_state reclaim_state;
2117 bool drained = false;
2121 /* We now go into synchronous reclaim */
2122 cpuset_memory_pressure_bump();
2123 current->flags |= PF_MEMALLOC;
2124 lockdep_set_current_reclaim_state(gfp_mask);
2125 reclaim_state.reclaimed_slab = 0;
2126 current->reclaim_state = &reclaim_state;
2128 *did_some_progress = try_to_free_pages(zonelist, order, gfp_mask, nodemask);
2130 current->reclaim_state = NULL;
2131 lockdep_clear_current_reclaim_state();
2132 current->flags &= ~PF_MEMALLOC;
2136 if (unlikely(!(*did_some_progress)))
2139 /* After successful reclaim, reconsider all zones for allocation */
2141 zlc_clear_zones_full(zonelist);
2144 page = get_page_from_freelist(gfp_mask, nodemask, order,
2145 zonelist, high_zoneidx,
2146 alloc_flags, preferred_zone,
2150 * If an allocation failed after direct reclaim, it could be because
2151 * pages are pinned on the per-cpu lists. Drain them and try again
2153 if (!page && !drained) {
2163 * This is called in the allocator slow-path if the allocation request is of
2164 * sufficient urgency to ignore watermarks and take other desperate measures
2166 static inline struct page *
2167 __alloc_pages_high_priority(gfp_t gfp_mask, unsigned int order,
2168 struct zonelist *zonelist, enum zone_type high_zoneidx,
2169 nodemask_t *nodemask, struct zone *preferred_zone,
2175 page = get_page_from_freelist(gfp_mask, nodemask, order,
2176 zonelist, high_zoneidx, ALLOC_NO_WATERMARKS,
2177 preferred_zone, migratetype);
2179 if (!page && gfp_mask & __GFP_NOFAIL)
2180 wait_iff_congested(preferred_zone, BLK_RW_ASYNC, HZ/50);
2181 } while (!page && (gfp_mask & __GFP_NOFAIL));
2187 void wake_all_kswapd(unsigned int order, struct zonelist *zonelist,
2188 enum zone_type high_zoneidx,
2189 enum zone_type classzone_idx)
2194 for_each_zone_zonelist(zone, z, zonelist, high_zoneidx)
2195 wakeup_kswapd(zone, order, classzone_idx);
2199 gfp_to_alloc_flags(gfp_t gfp_mask)
2201 int alloc_flags = ALLOC_WMARK_MIN | ALLOC_CPUSET;
2202 const gfp_t wait = gfp_mask & __GFP_WAIT;
2204 /* __GFP_HIGH is assumed to be the same as ALLOC_HIGH to save a branch. */
2205 BUILD_BUG_ON(__GFP_HIGH != (__force gfp_t) ALLOC_HIGH);
2208 * The caller may dip into page reserves a bit more if the caller
2209 * cannot run direct reclaim, or if the caller has realtime scheduling
2210 * policy or is asking for __GFP_HIGH memory. GFP_ATOMIC requests will
2211 * set both ALLOC_HARDER (!wait) and ALLOC_HIGH (__GFP_HIGH).
2213 alloc_flags |= (__force int) (gfp_mask & __GFP_HIGH);
2217 * Not worth trying to allocate harder for
2218 * __GFP_NOMEMALLOC even if it can't schedule.
2220 if (!(gfp_mask & __GFP_NOMEMALLOC))
2221 alloc_flags |= ALLOC_HARDER;
2223 * Ignore cpuset if GFP_ATOMIC (!wait) rather than fail alloc.
2224 * See also cpuset_zone_allowed() comment in kernel/cpuset.c.
2226 alloc_flags &= ~ALLOC_CPUSET;
2227 } else if (unlikely(rt_task(current)) && !in_interrupt())
2228 alloc_flags |= ALLOC_HARDER;
2230 if (likely(!(gfp_mask & __GFP_NOMEMALLOC))) {
2231 if (!in_interrupt() &&
2232 ((current->flags & PF_MEMALLOC) ||
2233 unlikely(test_thread_flag(TIF_MEMDIE))))
2234 alloc_flags |= ALLOC_NO_WATERMARKS;
2240 static inline struct page *
2241 __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order,
2242 struct zonelist *zonelist, enum zone_type high_zoneidx,
2243 nodemask_t *nodemask, struct zone *preferred_zone,
2246 const gfp_t wait = gfp_mask & __GFP_WAIT;
2247 struct page *page = NULL;
2249 unsigned long pages_reclaimed = 0;
2250 unsigned long did_some_progress;
2251 bool sync_migration = false;
2252 bool deferred_compaction = false;
2255 * In the slowpath, we sanity check order to avoid ever trying to
2256 * reclaim >= MAX_ORDER areas which will never succeed. Callers may
2257 * be using allocators in order of preference for an area that is
2260 if (order >= MAX_ORDER) {
2261 WARN_ON_ONCE(!(gfp_mask & __GFP_NOWARN));
2266 * GFP_THISNODE (meaning __GFP_THISNODE, __GFP_NORETRY and
2267 * __GFP_NOWARN set) should not cause reclaim since the subsystem
2268 * (f.e. slab) using GFP_THISNODE may choose to trigger reclaim
2269 * using a larger set of nodes after it has established that the
2270 * allowed per node queues are empty and that nodes are
2273 if (NUMA_BUILD && (gfp_mask & GFP_THISNODE) == GFP_THISNODE)
2277 if (!(gfp_mask & __GFP_NO_KSWAPD))
2278 wake_all_kswapd(order, zonelist, high_zoneidx,
2279 zone_idx(preferred_zone));
2282 * OK, we're below the kswapd watermark and have kicked background
2283 * reclaim. Now things get more complex, so set up alloc_flags according
2284 * to how we want to proceed.
2286 alloc_flags = gfp_to_alloc_flags(gfp_mask);
2289 * Find the true preferred zone if the allocation is unconstrained by
2292 if (!(alloc_flags & ALLOC_CPUSET) && !nodemask)
2293 first_zones_zonelist(zonelist, high_zoneidx, NULL,
2297 /* This is the last chance, in general, before the goto nopage. */
2298 page = get_page_from_freelist(gfp_mask, nodemask, order, zonelist,
2299 high_zoneidx, alloc_flags & ~ALLOC_NO_WATERMARKS,
2300 preferred_zone, migratetype);
2304 /* Allocate without watermarks if the context allows */
2305 if (alloc_flags & ALLOC_NO_WATERMARKS) {
2306 page = __alloc_pages_high_priority(gfp_mask, order,
2307 zonelist, high_zoneidx, nodemask,
2308 preferred_zone, migratetype);
2313 /* Atomic allocations - we can't balance anything */
2317 /* Avoid recursion of direct reclaim */
2318 if (current->flags & PF_MEMALLOC)
2321 /* Avoid allocations with no watermarks from looping endlessly */
2322 if (test_thread_flag(TIF_MEMDIE) && !(gfp_mask & __GFP_NOFAIL))
2326 * Try direct compaction. The first pass is asynchronous. Subsequent
2327 * attempts after direct reclaim are synchronous
2329 page = __alloc_pages_direct_compact(gfp_mask, order,
2330 zonelist, high_zoneidx,
2332 alloc_flags, preferred_zone,
2333 migratetype, sync_migration,
2334 &deferred_compaction,
2335 &did_some_progress);
2338 sync_migration = true;
2341 * If compaction is deferred for high-order allocations, it is because
2342 * sync compaction recently failed. In this is the case and the caller
2343 * has requested the system not be heavily disrupted, fail the
2344 * allocation now instead of entering direct reclaim
2346 if (deferred_compaction && (gfp_mask & __GFP_NO_KSWAPD))
2349 /* Try direct reclaim and then allocating */
2350 page = __alloc_pages_direct_reclaim(gfp_mask, order,
2351 zonelist, high_zoneidx,
2353 alloc_flags, preferred_zone,
2354 migratetype, &did_some_progress);
2359 * If we failed to make any progress reclaiming, then we are
2360 * running out of options and have to consider going OOM
2362 if (!did_some_progress) {
2363 if ((gfp_mask & __GFP_FS) && !(gfp_mask & __GFP_NORETRY)) {
2364 if (oom_killer_disabled)
2366 /* Coredumps can quickly deplete all memory reserves */
2367 if ((current->flags & PF_DUMPCORE) &&
2368 !(gfp_mask & __GFP_NOFAIL))
2370 page = __alloc_pages_may_oom(gfp_mask, order,
2371 zonelist, high_zoneidx,
2372 nodemask, preferred_zone,
2377 if (!(gfp_mask & __GFP_NOFAIL)) {
2379 * The oom killer is not called for high-order
2380 * allocations that may fail, so if no progress
2381 * is being made, there are no other options and
2382 * retrying is unlikely to help.
2384 if (order > PAGE_ALLOC_COSTLY_ORDER)
2387 * The oom killer is not called for lowmem
2388 * allocations to prevent needlessly killing
2391 if (high_zoneidx < ZONE_NORMAL)
2399 /* Check if we should retry the allocation */
2400 pages_reclaimed += did_some_progress;
2401 if (should_alloc_retry(gfp_mask, order, did_some_progress,
2403 /* Wait for some write requests to complete then retry */
2404 wait_iff_congested(preferred_zone, BLK_RW_ASYNC, HZ/50);
2408 * High-order allocations do not necessarily loop after
2409 * direct reclaim and reclaim/compaction depends on compaction
2410 * being called after reclaim so call directly if necessary
2412 page = __alloc_pages_direct_compact(gfp_mask, order,
2413 zonelist, high_zoneidx,
2415 alloc_flags, preferred_zone,
2416 migratetype, sync_migration,
2417 &deferred_compaction,
2418 &did_some_progress);
2424 warn_alloc_failed(gfp_mask, order, NULL);
2427 if (kmemcheck_enabled)
2428 kmemcheck_pagealloc_alloc(page, order, gfp_mask);
2434 * This is the 'heart' of the zoned buddy allocator.
2437 __alloc_pages_nodemask(gfp_t gfp_mask, unsigned int order,
2438 struct zonelist *zonelist, nodemask_t *nodemask)
2440 enum zone_type high_zoneidx = gfp_zone(gfp_mask);
2441 struct zone *preferred_zone;
2442 struct page *page = NULL;
2443 int migratetype = allocflags_to_migratetype(gfp_mask);
2444 unsigned int cpuset_mems_cookie;
2446 gfp_mask &= gfp_allowed_mask;
2448 lockdep_trace_alloc(gfp_mask);
2450 might_sleep_if(gfp_mask & __GFP_WAIT);
2452 if (should_fail_alloc_page(gfp_mask, order))
2456 * Check the zones suitable for the gfp_mask contain at least one
2457 * valid zone. It's possible to have an empty zonelist as a result
2458 * of GFP_THISNODE and a memoryless node
2460 if (unlikely(!zonelist->_zonerefs->zone))
2464 cpuset_mems_cookie = get_mems_allowed();
2466 /* The preferred zone is used for statistics later */
2467 first_zones_zonelist(zonelist, high_zoneidx,
2468 nodemask ? : &cpuset_current_mems_allowed,
2470 if (!preferred_zone)
2473 /* First allocation attempt */
2474 page = get_page_from_freelist(gfp_mask|__GFP_HARDWALL, nodemask, order,
2475 zonelist, high_zoneidx, ALLOC_WMARK_LOW|ALLOC_CPUSET,
2476 preferred_zone, migratetype);
2477 if (unlikely(!page))
2478 page = __alloc_pages_slowpath(gfp_mask, order,
2479 zonelist, high_zoneidx, nodemask,
2480 preferred_zone, migratetype);
2482 trace_mm_page_alloc(page, order, gfp_mask, migratetype);
2486 * When updating a task's mems_allowed, it is possible to race with
2487 * parallel threads in such a way that an allocation can fail while
2488 * the mask is being updated. If a page allocation is about to fail,
2489 * check if the cpuset changed during allocation and if so, retry.
2491 if (unlikely(!put_mems_allowed(cpuset_mems_cookie) && !page))
2496 EXPORT_SYMBOL(__alloc_pages_nodemask);
2499 * Common helper functions.
2501 unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order)
2506 * __get_free_pages() returns a 32-bit address, which cannot represent
2509 VM_BUG_ON((gfp_mask & __GFP_HIGHMEM) != 0);
2511 page = alloc_pages(gfp_mask, order);
2514 return (unsigned long) page_address(page);
2516 EXPORT_SYMBOL(__get_free_pages);
2518 unsigned long get_zeroed_page(gfp_t gfp_mask)
2520 return __get_free_pages(gfp_mask | __GFP_ZERO, 0);
2522 EXPORT_SYMBOL(get_zeroed_page);
2524 void __free_pages(struct page *page, unsigned int order)
2526 if (put_page_testzero(page)) {
2528 free_hot_cold_page(page, 0);
2530 __free_pages_ok(page, order);
2534 EXPORT_SYMBOL(__free_pages);
2536 void free_pages(unsigned long addr, unsigned int order)
2539 VM_BUG_ON(!virt_addr_valid((void *)addr));
2540 __free_pages(virt_to_page((void *)addr), order);
2544 EXPORT_SYMBOL(free_pages);
2546 static void *make_alloc_exact(unsigned long addr, unsigned order, size_t size)
2549 unsigned long alloc_end = addr + (PAGE_SIZE << order);
2550 unsigned long used = addr + PAGE_ALIGN(size);
2552 split_page(virt_to_page((void *)addr), order);
2553 while (used < alloc_end) {
2558 return (void *)addr;
2562 * alloc_pages_exact - allocate an exact number physically-contiguous pages.
2563 * @size: the number of bytes to allocate
2564 * @gfp_mask: GFP flags for the allocation
2566 * This function is similar to alloc_pages(), except that it allocates the
2567 * minimum number of pages to satisfy the request. alloc_pages() can only
2568 * allocate memory in power-of-two pages.
2570 * This function is also limited by MAX_ORDER.
2572 * Memory allocated by this function must be released by free_pages_exact().
2574 void *alloc_pages_exact(size_t size, gfp_t gfp_mask)
2576 unsigned int order = get_order(size);
2579 addr = __get_free_pages(gfp_mask, order);
2580 return make_alloc_exact(addr, order, size);
2582 EXPORT_SYMBOL(alloc_pages_exact);
2585 * alloc_pages_exact_nid - allocate an exact number of physically-contiguous
2587 * @nid: the preferred node ID where memory should be allocated
2588 * @size: the number of bytes to allocate
2589 * @gfp_mask: GFP flags for the allocation
2591 * Like alloc_pages_exact(), but try to allocate on node nid first before falling
2593 * Note this is not alloc_pages_exact_node() which allocates on a specific node,
2596 void *alloc_pages_exact_nid(int nid, size_t size, gfp_t gfp_mask)
2598 unsigned order = get_order(size);
2599 struct page *p = alloc_pages_node(nid, gfp_mask, order);
2602 return make_alloc_exact((unsigned long)page_address(p), order, size);
2604 EXPORT_SYMBOL(alloc_pages_exact_nid);
2607 * free_pages_exact - release memory allocated via alloc_pages_exact()
2608 * @virt: the value returned by alloc_pages_exact.
2609 * @size: size of allocation, same value as passed to alloc_pages_exact().
2611 * Release the memory allocated by a previous call to alloc_pages_exact.
2613 void free_pages_exact(void *virt, size_t size)
2615 unsigned long addr = (unsigned long)virt;
2616 unsigned long end = addr + PAGE_ALIGN(size);
2618 while (addr < end) {
2623 EXPORT_SYMBOL(free_pages_exact);
2625 static unsigned int nr_free_zone_pages(int offset)
2630 /* Just pick one node, since fallback list is circular */
2631 unsigned int sum = 0;
2633 struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL);
2635 for_each_zone_zonelist(zone, z, zonelist, offset) {
2636 unsigned long size = zone->present_pages;
2637 unsigned long high = high_wmark_pages(zone);
2646 * Amount of free RAM allocatable within ZONE_DMA and ZONE_NORMAL
2648 unsigned int nr_free_buffer_pages(void)
2650 return nr_free_zone_pages(gfp_zone(GFP_USER));
2652 EXPORT_SYMBOL_GPL(nr_free_buffer_pages);
2655 * Amount of free RAM allocatable within all zones
2657 unsigned int nr_free_pagecache_pages(void)
2659 return nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE));
2662 static inline void show_node(struct zone *zone)
2665 printk("Node %d ", zone_to_nid(zone));
2668 void si_meminfo(struct sysinfo *val)
2670 val->totalram = totalram_pages;
2672 val->freeram = global_page_state(NR_FREE_PAGES);
2673 val->bufferram = nr_blockdev_pages();
2674 val->totalhigh = totalhigh_pages;
2675 val->freehigh = nr_free_highpages();
2676 val->mem_unit = PAGE_SIZE;
2679 EXPORT_SYMBOL(si_meminfo);
2682 void si_meminfo_node(struct sysinfo *val, int nid)
2684 pg_data_t *pgdat = NODE_DATA(nid);
2686 val->totalram = pgdat->node_present_pages;
2687 val->freeram = node_page_state(nid, NR_FREE_PAGES);
2688 #ifdef CONFIG_HIGHMEM
2689 val->totalhigh = pgdat->node_zones[ZONE_HIGHMEM].present_pages;
2690 val->freehigh = zone_page_state(&pgdat->node_zones[ZONE_HIGHMEM],
2696 val->mem_unit = PAGE_SIZE;
2701 * Determine whether the node should be displayed or not, depending on whether
2702 * SHOW_MEM_FILTER_NODES was passed to show_free_areas().
2704 bool skip_free_areas_node(unsigned int flags, int nid)
2707 unsigned int cpuset_mems_cookie;
2709 if (!(flags & SHOW_MEM_FILTER_NODES))
2713 cpuset_mems_cookie = get_mems_allowed();
2714 ret = !node_isset(nid, cpuset_current_mems_allowed);
2715 } while (!put_mems_allowed(cpuset_mems_cookie));
2720 #define K(x) ((x) << (PAGE_SHIFT-10))
2723 * Show free area list (used inside shift_scroll-lock stuff)
2724 * We also calculate the percentage fragmentation. We do this by counting the
2725 * memory on each free list with the exception of the first item on the list.
2726 * Suppresses nodes that are not allowed by current's cpuset if
2727 * SHOW_MEM_FILTER_NODES is passed.
2729 void show_free_areas(unsigned int filter)
2734 for_each_populated_zone(zone) {
2735 if (skip_free_areas_node(filter, zone_to_nid(zone)))
2738 printk("%s per-cpu:\n", zone->name);
2740 for_each_online_cpu(cpu) {
2741 struct per_cpu_pageset *pageset;
2743 pageset = per_cpu_ptr(zone->pageset, cpu);
2745 printk("CPU %4d: hi:%5d, btch:%4d usd:%4d\n",
2746 cpu, pageset->pcp.high,
2747 pageset->pcp.batch, pageset->pcp.count);
2751 printk("active_anon:%lu inactive_anon:%lu isolated_anon:%lu\n"
2752 " active_file:%lu inactive_file:%lu isolated_file:%lu\n"
2754 " dirty:%lu writeback:%lu unstable:%lu\n"
2755 " free:%lu slab_reclaimable:%lu slab_unreclaimable:%lu\n"
2756 " mapped:%lu shmem:%lu pagetables:%lu bounce:%lu\n",
2757 global_page_state(NR_ACTIVE_ANON),
2758 global_page_state(NR_INACTIVE_ANON),
2759 global_page_state(NR_ISOLATED_ANON),
2760 global_page_state(NR_ACTIVE_FILE),
2761 global_page_state(NR_INACTIVE_FILE),
2762 global_page_state(NR_ISOLATED_FILE),
2763 global_page_state(NR_UNEVICTABLE),
2764 global_page_state(NR_FILE_DIRTY),
2765 global_page_state(NR_WRITEBACK),
2766 global_page_state(NR_UNSTABLE_NFS),
2767 global_page_state(NR_FREE_PAGES),
2768 global_page_state(NR_SLAB_RECLAIMABLE),
2769 global_page_state(NR_SLAB_UNRECLAIMABLE),
2770 global_page_state(NR_FILE_MAPPED),
2771 global_page_state(NR_SHMEM),
2772 global_page_state(NR_PAGETABLE),
2773 global_page_state(NR_BOUNCE));
2775 for_each_populated_zone(zone) {
2778 if (skip_free_areas_node(filter, zone_to_nid(zone)))
2786 " active_anon:%lukB"
2787 " inactive_anon:%lukB"
2788 " active_file:%lukB"
2789 " inactive_file:%lukB"
2790 " unevictable:%lukB"
2791 " isolated(anon):%lukB"
2792 " isolated(file):%lukB"
2799 " slab_reclaimable:%lukB"
2800 " slab_unreclaimable:%lukB"
2801 " kernel_stack:%lukB"
2805 " writeback_tmp:%lukB"
2806 " pages_scanned:%lu"
2807 " all_unreclaimable? %s"
2810 K(zone_page_state(zone, NR_FREE_PAGES)),
2811 K(min_wmark_pages(zone)),
2812 K(low_wmark_pages(zone)),
2813 K(high_wmark_pages(zone)),
2814 K(zone_page_state(zone, NR_ACTIVE_ANON)),
2815 K(zone_page_state(zone, NR_INACTIVE_ANON)),
2816 K(zone_page_state(zone, NR_ACTIVE_FILE)),
2817 K(zone_page_state(zone, NR_INACTIVE_FILE)),
2818 K(zone_page_state(zone, NR_UNEVICTABLE)),
2819 K(zone_page_state(zone, NR_ISOLATED_ANON)),
2820 K(zone_page_state(zone, NR_ISOLATED_FILE)),
2821 K(zone->present_pages),
2822 K(zone_page_state(zone, NR_MLOCK)),
2823 K(zone_page_state(zone, NR_FILE_DIRTY)),
2824 K(zone_page_state(zone, NR_WRITEBACK)),
2825 K(zone_page_state(zone, NR_FILE_MAPPED)),
2826 K(zone_page_state(zone, NR_SHMEM)),
2827 K(zone_page_state(zone, NR_SLAB_RECLAIMABLE)),
2828 K(zone_page_state(zone, NR_SLAB_UNRECLAIMABLE)),
2829 zone_page_state(zone, NR_KERNEL_STACK) *
2831 K(zone_page_state(zone, NR_PAGETABLE)),
2832 K(zone_page_state(zone, NR_UNSTABLE_NFS)),
2833 K(zone_page_state(zone, NR_BOUNCE)),
2834 K(zone_page_state(zone, NR_WRITEBACK_TEMP)),
2835 zone->pages_scanned,
2836 (zone->all_unreclaimable ? "yes" : "no")
2838 printk("lowmem_reserve[]:");
2839 for (i = 0; i < MAX_NR_ZONES; i++)
2840 printk(" %lu", zone->lowmem_reserve[i]);
2844 for_each_populated_zone(zone) {
2845 unsigned long nr[MAX_ORDER], flags, order, total = 0;
2847 if (skip_free_areas_node(filter, zone_to_nid(zone)))
2850 printk("%s: ", zone->name);
2852 spin_lock_irqsave(&zone->lock, flags);
2853 for (order = 0; order < MAX_ORDER; order++) {
2854 nr[order] = zone->free_area[order].nr_free;
2855 total += nr[order] << order;
2857 spin_unlock_irqrestore(&zone->lock, flags);
2858 for (order = 0; order < MAX_ORDER; order++)
2859 printk("%lu*%lukB ", nr[order], K(1UL) << order);
2860 printk("= %lukB\n", K(total));
2863 printk("%ld total pagecache pages\n", global_page_state(NR_FILE_PAGES));
2865 show_swap_cache_info();
2868 static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref)
2870 zoneref->zone = zone;
2871 zoneref->zone_idx = zone_idx(zone);
2875 * Builds allocation fallback zone lists.
2877 * Add all populated zones of a node to the zonelist.
2879 static int build_zonelists_node(pg_data_t *pgdat, struct zonelist *zonelist,
2880 int nr_zones, enum zone_type zone_type)
2884 BUG_ON(zone_type >= MAX_NR_ZONES);
2889 zone = pgdat->node_zones + zone_type;
2890 if (populated_zone(zone)) {
2891 zoneref_set_zone(zone,
2892 &zonelist->_zonerefs[nr_zones++]);
2893 check_highest_zone(zone_type);
2896 } while (zone_type);
2903 * 0 = automatic detection of better ordering.
2904 * 1 = order by ([node] distance, -zonetype)
2905 * 2 = order by (-zonetype, [node] distance)
2907 * If not NUMA, ZONELIST_ORDER_ZONE and ZONELIST_ORDER_NODE will create
2908 * the same zonelist. So only NUMA can configure this param.
2910 #define ZONELIST_ORDER_DEFAULT 0
2911 #define ZONELIST_ORDER_NODE 1
2912 #define ZONELIST_ORDER_ZONE 2
2914 /* zonelist order in the kernel.
2915 * set_zonelist_order() will set this to NODE or ZONE.
2917 static int current_zonelist_order = ZONELIST_ORDER_DEFAULT;
2918 static char zonelist_order_name[3][8] = {"Default", "Node", "Zone"};
2922 /* The value user specified ....changed by config */
2923 static int user_zonelist_order = ZONELIST_ORDER_DEFAULT;
2924 /* string for sysctl */
2925 #define NUMA_ZONELIST_ORDER_LEN 16
2926 char numa_zonelist_order[16] = "default";
2929 * interface for configure zonelist ordering.
2930 * command line option "numa_zonelist_order"
2931 * = "[dD]efault - default, automatic configuration.
2932 * = "[nN]ode - order by node locality, then by zone within node
2933 * = "[zZ]one - order by zone, then by locality within zone
2936 static int __parse_numa_zonelist_order(char *s)
2938 if (*s == 'd' || *s == 'D') {
2939 user_zonelist_order = ZONELIST_ORDER_DEFAULT;
2940 } else if (*s == 'n' || *s == 'N') {
2941 user_zonelist_order = ZONELIST_ORDER_NODE;
2942 } else if (*s == 'z' || *s == 'Z') {
2943 user_zonelist_order = ZONELIST_ORDER_ZONE;
2946 "Ignoring invalid numa_zonelist_order value: "
2953 static __init int setup_numa_zonelist_order(char *s)
2960 ret = __parse_numa_zonelist_order(s);
2962 strlcpy(numa_zonelist_order, s, NUMA_ZONELIST_ORDER_LEN);
2966 early_param("numa_zonelist_order", setup_numa_zonelist_order);
2969 * sysctl handler for numa_zonelist_order
2971 int numa_zonelist_order_handler(ctl_table *table, int write,
2972 void __user *buffer, size_t *length,
2975 char saved_string[NUMA_ZONELIST_ORDER_LEN];
2977 static DEFINE_MUTEX(zl_order_mutex);
2979 mutex_lock(&zl_order_mutex);
2981 strcpy(saved_string, (char*)table->data);
2982 ret = proc_dostring(table, write, buffer, length, ppos);
2986 int oldval = user_zonelist_order;
2987 if (__parse_numa_zonelist_order((char*)table->data)) {
2989 * bogus value. restore saved string
2991 strncpy((char*)table->data, saved_string,
2992 NUMA_ZONELIST_ORDER_LEN);
2993 user_zonelist_order = oldval;
2994 } else if (oldval != user_zonelist_order) {
2995 mutex_lock(&zonelists_mutex);
2996 build_all_zonelists(NULL);
2997 mutex_unlock(&zonelists_mutex);
3001 mutex_unlock(&zl_order_mutex);
3006 #define MAX_NODE_LOAD (nr_online_nodes)
3007 static int node_load[MAX_NUMNODES];
3010 * find_next_best_node - find the next node that should appear in a given node's fallback list
3011 * @node: node whose fallback list we're appending
3012 * @used_node_mask: nodemask_t of already used nodes
3014 * We use a number of factors to determine which is the next node that should
3015 * appear on a given node's fallback list. The node should not have appeared
3016 * already in @node's fallback list, and it should be the next closest node
3017 * according to the distance array (which contains arbitrary distance values
3018 * from each node to each node in the system), and should also prefer nodes
3019 * with no CPUs, since presumably they'll have very little allocation pressure
3020 * on them otherwise.
3021 * It returns -1 if no node is found.
3023 static int find_next_best_node(int node, nodemask_t *used_node_mask)
3026 int min_val = INT_MAX;
3028 const struct cpumask *tmp = cpumask_of_node(0);
3030 /* Use the local node if we haven't already */
3031 if (!node_isset(node, *used_node_mask)) {
3032 node_set(node, *used_node_mask);
3036 for_each_node_state(n, N_HIGH_MEMORY) {
3038 /* Don't want a node to appear more than once */
3039 if (node_isset(n, *used_node_mask))
3042 /* Use the distance array to find the distance */
3043 val = node_distance(node, n);
3045 /* Penalize nodes under us ("prefer the next node") */
3048 /* Give preference to headless and unused nodes */
3049 tmp = cpumask_of_node(n);
3050 if (!cpumask_empty(tmp))
3051 val += PENALTY_FOR_NODE_WITH_CPUS;
3053 /* Slight preference for less loaded node */
3054 val *= (MAX_NODE_LOAD*MAX_NUMNODES);
3055 val += node_load[n];
3057 if (val < min_val) {
3064 node_set(best_node, *used_node_mask);
3071 * Build zonelists ordered by node and zones within node.
3072 * This results in maximum locality--normal zone overflows into local
3073 * DMA zone, if any--but risks exhausting DMA zone.
3075 static void build_zonelists_in_node_order(pg_data_t *pgdat, int node)
3078 struct zonelist *zonelist;
3080 zonelist = &pgdat->node_zonelists[0];
3081 for (j = 0; zonelist->_zonerefs[j].zone != NULL; j++)
3083 j = build_zonelists_node(NODE_DATA(node), zonelist, j,
3085 zonelist->_zonerefs[j].zone = NULL;
3086 zonelist->_zonerefs[j].zone_idx = 0;
3090 * Build gfp_thisnode zonelists
3092 static void build_thisnode_zonelists(pg_data_t *pgdat)
3095 struct zonelist *zonelist;
3097 zonelist = &pgdat->node_zonelists[1];
3098 j = build_zonelists_node(pgdat, zonelist, 0, MAX_NR_ZONES - 1);
3099 zonelist->_zonerefs[j].zone = NULL;
3100 zonelist->_zonerefs[j].zone_idx = 0;
3104 * Build zonelists ordered by zone and nodes within zones.
3105 * This results in conserving DMA zone[s] until all Normal memory is
3106 * exhausted, but results in overflowing to remote node while memory
3107 * may still exist in local DMA zone.
3109 static int node_order[MAX_NUMNODES];
3111 static void build_zonelists_in_zone_order(pg_data_t *pgdat, int nr_nodes)
3114 int zone_type; /* needs to be signed */
3116 struct zonelist *zonelist;
3118 zonelist = &pgdat->node_zonelists[0];
3120 for (zone_type = MAX_NR_ZONES - 1; zone_type >= 0; zone_type--) {
3121 for (j = 0; j < nr_nodes; j++) {
3122 node = node_order[j];
3123 z = &NODE_DATA(node)->node_zones[zone_type];
3124 if (populated_zone(z)) {
3126 &zonelist->_zonerefs[pos++]);
3127 check_highest_zone(zone_type);
3131 zonelist->_zonerefs[pos].zone = NULL;
3132 zonelist->_zonerefs[pos].zone_idx = 0;
3135 static int default_zonelist_order(void)
3138 unsigned long low_kmem_size,total_size;
3142 * ZONE_DMA and ZONE_DMA32 can be very small area in the system.
3143 * If they are really small and used heavily, the system can fall
3144 * into OOM very easily.
3145 * This function detect ZONE_DMA/DMA32 size and configures zone order.
3147 /* Is there ZONE_NORMAL ? (ex. ppc has only DMA zone..) */
3150 for_each_online_node(nid) {
3151 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
3152 z = &NODE_DATA(nid)->node_zones[zone_type];
3153 if (populated_zone(z)) {
3154 if (zone_type < ZONE_NORMAL)
3155 low_kmem_size += z->present_pages;
3156 total_size += z->present_pages;
3157 } else if (zone_type == ZONE_NORMAL) {
3159 * If any node has only lowmem, then node order
3160 * is preferred to allow kernel allocations
3161 * locally; otherwise, they can easily infringe
3162 * on other nodes when there is an abundance of
3163 * lowmem available to allocate from.
3165 return ZONELIST_ORDER_NODE;
3169 if (!low_kmem_size || /* there are no DMA area. */
3170 low_kmem_size > total_size/2) /* DMA/DMA32 is big. */
3171 return ZONELIST_ORDER_NODE;
3173 * look into each node's config.
3174 * If there is a node whose DMA/DMA32 memory is very big area on
3175 * local memory, NODE_ORDER may be suitable.
3177 average_size = total_size /
3178 (nodes_weight(node_states[N_HIGH_MEMORY]) + 1);
3179 for_each_online_node(nid) {
3182 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
3183 z = &NODE_DATA(nid)->node_zones[zone_type];
3184 if (populated_zone(z)) {
3185 if (zone_type < ZONE_NORMAL)
3186 low_kmem_size += z->present_pages;
3187 total_size += z->present_pages;
3190 if (low_kmem_size &&
3191 total_size > average_size && /* ignore small node */
3192 low_kmem_size > total_size * 70/100)
3193 return ZONELIST_ORDER_NODE;
3195 return ZONELIST_ORDER_ZONE;
3198 static void set_zonelist_order(void)
3200 if (user_zonelist_order == ZONELIST_ORDER_DEFAULT)
3201 current_zonelist_order = default_zonelist_order();
3203 current_zonelist_order = user_zonelist_order;
3206 static void build_zonelists(pg_data_t *pgdat)
3210 nodemask_t used_mask;
3211 int local_node, prev_node;
3212 struct zonelist *zonelist;
3213 int order = current_zonelist_order;
3215 /* initialize zonelists */
3216 for (i = 0; i < MAX_ZONELISTS; i++) {
3217 zonelist = pgdat->node_zonelists + i;
3218 zonelist->_zonerefs[0].zone = NULL;
3219 zonelist->_zonerefs[0].zone_idx = 0;
3222 /* NUMA-aware ordering of nodes */
3223 local_node = pgdat->node_id;
3224 load = nr_online_nodes;
3225 prev_node = local_node;
3226 nodes_clear(used_mask);
3228 memset(node_order, 0, sizeof(node_order));
3231 while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
3232 int distance = node_distance(local_node, node);
3235 * If another node is sufficiently far away then it is better
3236 * to reclaim pages in a zone before going off node.
3238 if (distance > RECLAIM_DISTANCE)
3239 zone_reclaim_mode = 1;
3242 * We don't want to pressure a particular node.
3243 * So adding penalty to the first node in same
3244 * distance group to make it round-robin.
3246 if (distance != node_distance(local_node, prev_node))
3247 node_load[node] = load;
3251 if (order == ZONELIST_ORDER_NODE)
3252 build_zonelists_in_node_order(pgdat, node);
3254 node_order[j++] = node; /* remember order */
3257 if (order == ZONELIST_ORDER_ZONE) {
3258 /* calculate node order -- i.e., DMA last! */
3259 build_zonelists_in_zone_order(pgdat, j);
3262 build_thisnode_zonelists(pgdat);
3265 /* Construct the zonelist performance cache - see further mmzone.h */
3266 static void build_zonelist_cache(pg_data_t *pgdat)
3268 struct zonelist *zonelist;
3269 struct zonelist_cache *zlc;
3272 zonelist = &pgdat->node_zonelists[0];
3273 zonelist->zlcache_ptr = zlc = &zonelist->zlcache;
3274 bitmap_zero(zlc->fullzones, MAX_ZONES_PER_ZONELIST);
3275 for (z = zonelist->_zonerefs; z->zone; z++)
3276 zlc->z_to_n[z - zonelist->_zonerefs] = zonelist_node_idx(z);
3279 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
3281 * Return node id of node used for "local" allocations.
3282 * I.e., first node id of first zone in arg node's generic zonelist.
3283 * Used for initializing percpu 'numa_mem', which is used primarily
3284 * for kernel allocations, so use GFP_KERNEL flags to locate zonelist.
3286 int local_memory_node(int node)
3290 (void)first_zones_zonelist(node_zonelist(node, GFP_KERNEL),
3291 gfp_zone(GFP_KERNEL),
3298 #else /* CONFIG_NUMA */
3300 static void set_zonelist_order(void)
3302 current_zonelist_order = ZONELIST_ORDER_ZONE;
3305 static void build_zonelists(pg_data_t *pgdat)
3307 int node, local_node;
3309 struct zonelist *zonelist;
3311 local_node = pgdat->node_id;
3313 zonelist = &pgdat->node_zonelists[0];
3314 j = build_zonelists_node(pgdat, zonelist, 0, MAX_NR_ZONES - 1);
3317 * Now we build the zonelist so that it contains the zones
3318 * of all the other nodes.
3319 * We don't want to pressure a particular node, so when
3320 * building the zones for node N, we make sure that the
3321 * zones coming right after the local ones are those from
3322 * node N+1 (modulo N)
3324 for (node = local_node + 1; node < MAX_NUMNODES; node++) {
3325 if (!node_online(node))
3327 j = build_zonelists_node(NODE_DATA(node), zonelist, j,
3330 for (node = 0; node < local_node; node++) {
3331 if (!node_online(node))
3333 j = build_zonelists_node(NODE_DATA(node), zonelist, j,
3337 zonelist->_zonerefs[j].zone = NULL;
3338 zonelist->_zonerefs[j].zone_idx = 0;
3341 /* non-NUMA variant of zonelist performance cache - just NULL zlcache_ptr */
3342 static void build_zonelist_cache(pg_data_t *pgdat)
3344 pgdat->node_zonelists[0].zlcache_ptr = NULL;
3347 #endif /* CONFIG_NUMA */
3350 * Boot pageset table. One per cpu which is going to be used for all
3351 * zones and all nodes. The parameters will be set in such a way
3352 * that an item put on a list will immediately be handed over to
3353 * the buddy list. This is safe since pageset manipulation is done
3354 * with interrupts disabled.
3356 * The boot_pagesets must be kept even after bootup is complete for
3357 * unused processors and/or zones. They do play a role for bootstrapping
3358 * hotplugged processors.
3360 * zoneinfo_show() and maybe other functions do
3361 * not check if the processor is online before following the pageset pointer.
3362 * Other parts of the kernel may not check if the zone is available.
3364 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch);
3365 static DEFINE_PER_CPU(struct per_cpu_pageset, boot_pageset);
3366 static void setup_zone_pageset(struct zone *zone);
3369 * Global mutex to protect against size modification of zonelists
3370 * as well as to serialize pageset setup for the new populated zone.
3372 DEFINE_MUTEX(zonelists_mutex);
3374 /* return values int ....just for stop_machine() */
3375 static __init_refok int __build_all_zonelists(void *data)
3381 memset(node_load, 0, sizeof(node_load));
3383 for_each_online_node(nid) {
3384 pg_data_t *pgdat = NODE_DATA(nid);
3386 build_zonelists(pgdat);
3387 build_zonelist_cache(pgdat);
3391 * Initialize the boot_pagesets that are going to be used
3392 * for bootstrapping processors. The real pagesets for
3393 * each zone will be allocated later when the per cpu
3394 * allocator is available.
3396 * boot_pagesets are used also for bootstrapping offline
3397 * cpus if the system is already booted because the pagesets
3398 * are needed to initialize allocators on a specific cpu too.
3399 * F.e. the percpu allocator needs the page allocator which
3400 * needs the percpu allocator in order to allocate its pagesets
3401 * (a chicken-egg dilemma).
3403 for_each_possible_cpu(cpu) {
3404 setup_pageset(&per_cpu(boot_pageset, cpu), 0);
3406 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
3408 * We now know the "local memory node" for each node--
3409 * i.e., the node of the first zone in the generic zonelist.
3410 * Set up numa_mem percpu variable for on-line cpus. During
3411 * boot, only the boot cpu should be on-line; we'll init the
3412 * secondary cpus' numa_mem as they come on-line. During
3413 * node/memory hotplug, we'll fixup all on-line cpus.
3415 if (cpu_online(cpu))
3416 set_cpu_numa_mem(cpu, local_memory_node(cpu_to_node(cpu)));
3424 * Called with zonelists_mutex held always
3425 * unless system_state == SYSTEM_BOOTING.
3427 void __ref build_all_zonelists(void *data)
3429 set_zonelist_order();
3431 if (system_state == SYSTEM_BOOTING) {
3432 __build_all_zonelists(NULL);
3433 mminit_verify_zonelist();
3434 cpuset_init_current_mems_allowed();
3436 /* we have to stop all cpus to guarantee there is no user
3438 #ifdef CONFIG_MEMORY_HOTPLUG
3440 setup_zone_pageset((struct zone *)data);
3442 stop_machine(__build_all_zonelists, NULL, NULL);
3443 /* cpuset refresh routine should be here */
3445 vm_total_pages = nr_free_pagecache_pages();
3447 * Disable grouping by mobility if the number of pages in the
3448 * system is too low to allow the mechanism to work. It would be
3449 * more accurate, but expensive to check per-zone. This check is
3450 * made on memory-hotadd so a system can start with mobility
3451 * disabled and enable it later
3453 if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES))
3454 page_group_by_mobility_disabled = 1;
3456 page_group_by_mobility_disabled = 0;
3458 printk("Built %i zonelists in %s order, mobility grouping %s. "
3459 "Total pages: %ld\n",
3461 zonelist_order_name[current_zonelist_order],
3462 page_group_by_mobility_disabled ? "off" : "on",
3465 printk("Policy zone: %s\n", zone_names[policy_zone]);
3470 * Helper functions to size the waitqueue hash table.
3471 * Essentially these want to choose hash table sizes sufficiently
3472 * large so that collisions trying to wait on pages are rare.
3473 * But in fact, the number of active page waitqueues on typical
3474 * systems is ridiculously low, less than 200. So this is even
3475 * conservative, even though it seems large.
3477 * The constant PAGES_PER_WAITQUEUE specifies the ratio of pages to
3478 * waitqueues, i.e. the size of the waitq table given the number of pages.
3480 #define PAGES_PER_WAITQUEUE 256
3482 #ifndef CONFIG_MEMORY_HOTPLUG
3483 static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
3485 unsigned long size = 1;
3487 pages /= PAGES_PER_WAITQUEUE;
3489 while (size < pages)
3493 * Once we have dozens or even hundreds of threads sleeping
3494 * on IO we've got bigger problems than wait queue collision.
3495 * Limit the size of the wait table to a reasonable size.
3497 size = min(size, 4096UL);
3499 return max(size, 4UL);
3503 * A zone's size might be changed by hot-add, so it is not possible to determine
3504 * a suitable size for its wait_table. So we use the maximum size now.
3506 * The max wait table size = 4096 x sizeof(wait_queue_head_t). ie:
3508 * i386 (preemption config) : 4096 x 16 = 64Kbyte.
3509 * ia64, x86-64 (no preemption): 4096 x 20 = 80Kbyte.
3510 * ia64, x86-64 (preemption) : 4096 x 24 = 96Kbyte.
3512 * The maximum entries are prepared when a zone's memory is (512K + 256) pages
3513 * or more by the traditional way. (See above). It equals:
3515 * i386, x86-64, powerpc(4K page size) : = ( 2G + 1M)byte.
3516 * ia64(16K page size) : = ( 8G + 4M)byte.
3517 * powerpc (64K page size) : = (32G +16M)byte.
3519 static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
3526 * This is an integer logarithm so that shifts can be used later
3527 * to extract the more random high bits from the multiplicative
3528 * hash function before the remainder is taken.
3530 static inline unsigned long wait_table_bits(unsigned long size)
3535 #define LONG_ALIGN(x) (((x)+(sizeof(long))-1)&~((sizeof(long))-1))
3538 * Check if a pageblock contains reserved pages
3540 static int pageblock_is_reserved(unsigned long start_pfn, unsigned long end_pfn)
3544 for (pfn = start_pfn; pfn < end_pfn; pfn++) {
3545 if (!pfn_valid_within(pfn) || PageReserved(pfn_to_page(pfn)))
3552 * Mark a number of pageblocks as MIGRATE_RESERVE. The number
3553 * of blocks reserved is based on min_wmark_pages(zone). The memory within
3554 * the reserve will tend to store contiguous free pages. Setting min_free_kbytes
3555 * higher will lead to a bigger reserve which will get freed as contiguous
3556 * blocks as reclaim kicks in
3558 static void setup_zone_migrate_reserve(struct zone *zone)
3560 unsigned long start_pfn, pfn, end_pfn, block_end_pfn;
3562 unsigned long block_migratetype;
3566 * Get the start pfn, end pfn and the number of blocks to reserve
3567 * We have to be careful to be aligned to pageblock_nr_pages to
3568 * make sure that we always check pfn_valid for the first page in
3571 start_pfn = zone->zone_start_pfn;
3572 end_pfn = start_pfn + zone->spanned_pages;
3573 start_pfn = roundup(start_pfn, pageblock_nr_pages);
3574 reserve = roundup(min_wmark_pages(zone), pageblock_nr_pages) >>
3578 * Reserve blocks are generally in place to help high-order atomic
3579 * allocations that are short-lived. A min_free_kbytes value that
3580 * would result in more than 2 reserve blocks for atomic allocations
3581 * is assumed to be in place to help anti-fragmentation for the
3582 * future allocation of hugepages at runtime.
3584 reserve = min(2, reserve);
3586 for (pfn = start_pfn; pfn < end_pfn; pfn += pageblock_nr_pages) {
3587 if (!pfn_valid(pfn))
3589 page = pfn_to_page(pfn);
3591 /* Watch out for overlapping nodes */
3592 if (page_to_nid(page) != zone_to_nid(zone))
3595 block_migratetype = get_pageblock_migratetype(page);
3597 /* Only test what is necessary when the reserves are not met */
3600 * Blocks with reserved pages will never free, skip
3603 block_end_pfn = min(pfn + pageblock_nr_pages, end_pfn);
3604 if (pageblock_is_reserved(pfn, block_end_pfn))
3607 /* If this block is reserved, account for it */
3608 if (block_migratetype == MIGRATE_RESERVE) {
3613 /* Suitable for reserving if this block is movable */
3614 if (block_migratetype == MIGRATE_MOVABLE) {
3615 set_pageblock_migratetype(page,
3617 move_freepages_block(zone, page,
3625 * If the reserve is met and this is a previous reserved block,
3628 if (block_migratetype == MIGRATE_RESERVE) {
3629 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
3630 move_freepages_block(zone, page, MIGRATE_MOVABLE);
3636 * Initially all pages are reserved - free ones are freed
3637 * up by free_all_bootmem() once the early boot process is
3638 * done. Non-atomic initialization, single-pass.
3640 void __meminit memmap_init_zone(unsigned long size, int nid, unsigned long zone,
3641 unsigned long start_pfn, enum memmap_context context)
3644 unsigned long end_pfn = start_pfn + size;
3648 if (highest_memmap_pfn < end_pfn - 1)
3649 highest_memmap_pfn = end_pfn - 1;
3651 z = &NODE_DATA(nid)->node_zones[zone];
3652 for (pfn = start_pfn; pfn < end_pfn; pfn++) {
3654 * There can be holes in boot-time mem_map[]s
3655 * handed to this function. They do not
3656 * exist on hotplugged memory.
3658 if (context == MEMMAP_EARLY) {
3659 if (!early_pfn_valid(pfn))
3661 if (!early_pfn_in_nid(pfn, nid))
3664 page = pfn_to_page(pfn);
3665 set_page_links(page, zone, nid, pfn);
3666 mminit_verify_page_links(page, zone, nid, pfn);
3667 init_page_count(page);
3668 reset_page_mapcount(page);
3669 SetPageReserved(page);
3671 * Mark the block movable so that blocks are reserved for
3672 * movable at startup. This will force kernel allocations
3673 * to reserve their blocks rather than leaking throughout
3674 * the address space during boot when many long-lived
3675 * kernel allocations are made. Later some blocks near
3676 * the start are marked MIGRATE_RESERVE by
3677 * setup_zone_migrate_reserve()
3679 * bitmap is created for zone's valid pfn range. but memmap
3680 * can be created for invalid pages (for alignment)
3681 * check here not to call set_pageblock_migratetype() against
3684 if ((z->zone_start_pfn <= pfn)
3685 && (pfn < z->zone_start_pfn + z->spanned_pages)
3686 && !(pfn & (pageblock_nr_pages - 1)))
3687 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
3689 INIT_LIST_HEAD(&page->lru);
3690 #ifdef WANT_PAGE_VIRTUAL
3691 /* The shift won't overflow because ZONE_NORMAL is below 4G. */
3692 if (!is_highmem_idx(zone))
3693 set_page_address(page, __va(pfn << PAGE_SHIFT));
3698 static void __meminit zone_init_free_lists(struct zone *zone)
3701 for_each_migratetype_order(order, t) {
3702 INIT_LIST_HEAD(&zone->free_area[order].free_list[t]);
3703 zone->free_area[order].nr_free = 0;
3707 #ifndef __HAVE_ARCH_MEMMAP_INIT
3708 #define memmap_init(size, nid, zone, start_pfn) \
3709 memmap_init_zone((size), (nid), (zone), (start_pfn), MEMMAP_EARLY)
3712 static int zone_batchsize(struct zone *zone)
3718 * The per-cpu-pages pools are set to around 1000th of the
3719 * size of the zone. But no more than 1/2 of a meg.
3721 * OK, so we don't know how big the cache is. So guess.
3723 batch = zone->present_pages / 1024;
3724 if (batch * PAGE_SIZE > 512 * 1024)
3725 batch = (512 * 1024) / PAGE_SIZE;
3726 batch /= 4; /* We effectively *= 4 below */
3731 * Clamp the batch to a 2^n - 1 value. Having a power
3732 * of 2 value was found to be more likely to have
3733 * suboptimal cache aliasing properties in some cases.
3735 * For example if 2 tasks are alternately allocating
3736 * batches of pages, one task can end up with a lot
3737 * of pages of one half of the possible page colors
3738 * and the other with pages of the other colors.
3740 batch = rounddown_pow_of_two(batch + batch/2) - 1;
3745 /* The deferral and batching of frees should be suppressed under NOMMU
3748 * The problem is that NOMMU needs to be able to allocate large chunks
3749 * of contiguous memory as there's no hardware page translation to
3750 * assemble apparent contiguous memory from discontiguous pages.
3752 * Queueing large contiguous runs of pages for batching, however,
3753 * causes the pages to actually be freed in smaller chunks. As there
3754 * can be a significant delay between the individual batches being
3755 * recycled, this leads to the once large chunks of space being
3756 * fragmented and becoming unavailable for high-order allocations.
3762 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch)
3764 struct per_cpu_pages *pcp;
3767 memset(p, 0, sizeof(*p));
3771 pcp->high = 6 * batch;
3772 pcp->batch = max(1UL, 1 * batch);
3773 for (migratetype = 0; migratetype < MIGRATE_PCPTYPES; migratetype++)
3774 INIT_LIST_HEAD(&pcp->lists[migratetype]);
3778 * setup_pagelist_highmark() sets the high water mark for hot per_cpu_pagelist
3779 * to the value high for the pageset p.
3782 static void setup_pagelist_highmark(struct per_cpu_pageset *p,
3785 struct per_cpu_pages *pcp;
3789 pcp->batch = max(1UL, high/4);
3790 if ((high/4) > (PAGE_SHIFT * 8))
3791 pcp->batch = PAGE_SHIFT * 8;
3794 static void setup_zone_pageset(struct zone *zone)
3798 zone->pageset = alloc_percpu(struct per_cpu_pageset);
3800 for_each_possible_cpu(cpu) {
3801 struct per_cpu_pageset *pcp = per_cpu_ptr(zone->pageset, cpu);
3803 setup_pageset(pcp, zone_batchsize(zone));
3805 if (percpu_pagelist_fraction)
3806 setup_pagelist_highmark(pcp,
3807 (zone->present_pages /
3808 percpu_pagelist_fraction));
3813 * Allocate per cpu pagesets and initialize them.
3814 * Before this call only boot pagesets were available.
3816 void __init setup_per_cpu_pageset(void)
3820 for_each_populated_zone(zone)
3821 setup_zone_pageset(zone);
3824 static noinline __init_refok
3825 int zone_wait_table_init(struct zone *zone, unsigned long zone_size_pages)
3828 struct pglist_data *pgdat = zone->zone_pgdat;
3832 * The per-page waitqueue mechanism uses hashed waitqueues
3835 zone->wait_table_hash_nr_entries =
3836 wait_table_hash_nr_entries(zone_size_pages);
3837 zone->wait_table_bits =
3838 wait_table_bits(zone->wait_table_hash_nr_entries);
3839 alloc_size = zone->wait_table_hash_nr_entries
3840 * sizeof(wait_queue_head_t);
3842 if (!slab_is_available()) {
3843 zone->wait_table = (wait_queue_head_t *)
3844 alloc_bootmem_node_nopanic(pgdat, alloc_size);
3847 * This case means that a zone whose size was 0 gets new memory
3848 * via memory hot-add.
3849 * But it may be the case that a new node was hot-added. In
3850 * this case vmalloc() will not be able to use this new node's
3851 * memory - this wait_table must be initialized to use this new
3852 * node itself as well.
3853 * To use this new node's memory, further consideration will be
3856 zone->wait_table = vmalloc(alloc_size);
3858 if (!zone->wait_table)
3861 for(i = 0; i < zone->wait_table_hash_nr_entries; ++i)
3862 init_waitqueue_head(zone->wait_table + i);
3867 static int __zone_pcp_update(void *data)
3869 struct zone *zone = data;
3871 unsigned long batch = zone_batchsize(zone), flags;
3873 for_each_possible_cpu(cpu) {
3874 struct per_cpu_pageset *pset;
3875 struct per_cpu_pages *pcp;
3877 pset = per_cpu_ptr(zone->pageset, cpu);
3880 local_irq_save(flags);
3881 free_pcppages_bulk(zone, pcp->count, pcp);
3882 setup_pageset(pset, batch);
3883 local_irq_restore(flags);
3888 void zone_pcp_update(struct zone *zone)
3890 stop_machine(__zone_pcp_update, zone, NULL);
3893 static __meminit void zone_pcp_init(struct zone *zone)
3896 * per cpu subsystem is not up at this point. The following code
3897 * relies on the ability of the linker to provide the
3898 * offset of a (static) per cpu variable into the per cpu area.
3900 zone->pageset = &boot_pageset;
3902 if (zone->present_pages)
3903 printk(KERN_DEBUG " %s zone: %lu pages, LIFO batch:%u\n",
3904 zone->name, zone->present_pages,
3905 zone_batchsize(zone));
3908 __meminit int init_currently_empty_zone(struct zone *zone,
3909 unsigned long zone_start_pfn,
3911 enum memmap_context context)
3913 struct pglist_data *pgdat = zone->zone_pgdat;
3915 ret = zone_wait_table_init(zone, size);
3918 pgdat->nr_zones = zone_idx(zone) + 1;
3920 zone->zone_start_pfn = zone_start_pfn;
3922 mminit_dprintk(MMINIT_TRACE, "memmap_init",
3923 "Initialising map node %d zone %lu pfns %lu -> %lu\n",
3925 (unsigned long)zone_idx(zone),
3926 zone_start_pfn, (zone_start_pfn + size));
3928 zone_init_free_lists(zone);
3933 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
3934 #ifndef CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID
3936 * Required by SPARSEMEM. Given a PFN, return what node the PFN is on.
3937 * Architectures may implement their own version but if add_active_range()
3938 * was used and there are no special requirements, this is a convenient
3941 int __meminit __early_pfn_to_nid(unsigned long pfn)
3943 unsigned long start_pfn, end_pfn;
3946 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid)
3947 if (start_pfn <= pfn && pfn < end_pfn)
3949 /* This is a memory hole */
3952 #endif /* CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID */
3954 int __meminit early_pfn_to_nid(unsigned long pfn)
3958 nid = __early_pfn_to_nid(pfn);
3961 /* just returns 0 */
3965 #ifdef CONFIG_NODES_SPAN_OTHER_NODES
3966 bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
3970 nid = __early_pfn_to_nid(pfn);
3971 if (nid >= 0 && nid != node)
3978 * free_bootmem_with_active_regions - Call free_bootmem_node for each active range
3979 * @nid: The node to free memory on. If MAX_NUMNODES, all nodes are freed.
3980 * @max_low_pfn: The highest PFN that will be passed to free_bootmem_node
3982 * If an architecture guarantees that all ranges registered with
3983 * add_active_ranges() contain no holes and may be freed, this
3984 * this function may be used instead of calling free_bootmem() manually.
3986 void __init free_bootmem_with_active_regions(int nid, unsigned long max_low_pfn)
3988 unsigned long start_pfn, end_pfn;
3991 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, &this_nid) {
3992 start_pfn = min(start_pfn, max_low_pfn);
3993 end_pfn = min(end_pfn, max_low_pfn);
3995 if (start_pfn < end_pfn)
3996 free_bootmem_node(NODE_DATA(this_nid),
3997 PFN_PHYS(start_pfn),
3998 (end_pfn - start_pfn) << PAGE_SHIFT);
4003 * sparse_memory_present_with_active_regions - Call memory_present for each active range
4004 * @nid: The node to call memory_present for. If MAX_NUMNODES, all nodes will be used.
4006 * If an architecture guarantees that all ranges registered with
4007 * add_active_ranges() contain no holes and may be freed, this
4008 * function may be used instead of calling memory_present() manually.
4010 void __init sparse_memory_present_with_active_regions(int nid)
4012 unsigned long start_pfn, end_pfn;
4015 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, &this_nid)
4016 memory_present(this_nid, start_pfn, end_pfn);
4020 * get_pfn_range_for_nid - Return the start and end page frames for a node
4021 * @nid: The nid to return the range for. If MAX_NUMNODES, the min and max PFN are returned.
4022 * @start_pfn: Passed by reference. On return, it will have the node start_pfn.
4023 * @end_pfn: Passed by reference. On return, it will have the node end_pfn.
4025 * It returns the start and end page frame of a node based on information
4026 * provided by an arch calling add_active_range(). If called for a node
4027 * with no available memory, a warning is printed and the start and end
4030 void __meminit get_pfn_range_for_nid(unsigned int nid,
4031 unsigned long *start_pfn, unsigned long *end_pfn)
4033 unsigned long this_start_pfn, this_end_pfn;
4039 for_each_mem_pfn_range(i, nid, &this_start_pfn, &this_end_pfn, NULL) {
4040 *start_pfn = min(*start_pfn, this_start_pfn);
4041 *end_pfn = max(*end_pfn, this_end_pfn);
4044 if (*start_pfn == -1UL)
4049 * This finds a zone that can be used for ZONE_MOVABLE pages. The
4050 * assumption is made that zones within a node are ordered in monotonic
4051 * increasing memory addresses so that the "highest" populated zone is used
4053 static void __init find_usable_zone_for_movable(void)
4056 for (zone_index = MAX_NR_ZONES - 1; zone_index >= 0; zone_index--) {
4057 if (zone_index == ZONE_MOVABLE)
4060 if (arch_zone_highest_possible_pfn[zone_index] >
4061 arch_zone_lowest_possible_pfn[zone_index])
4065 VM_BUG_ON(zone_index == -1);
4066 movable_zone = zone_index;
4070 * The zone ranges provided by the architecture do not include ZONE_MOVABLE
4071 * because it is sized independent of architecture. Unlike the other zones,
4072 * the starting point for ZONE_MOVABLE is not fixed. It may be different
4073 * in each node depending on the size of each node and how evenly kernelcore
4074 * is distributed. This helper function adjusts the zone ranges
4075 * provided by the architecture for a given node by using the end of the
4076 * highest usable zone for ZONE_MOVABLE. This preserves the assumption that
4077 * zones within a node are in order of monotonic increases memory addresses
4079 static void __meminit adjust_zone_range_for_zone_movable(int nid,
4080 unsigned long zone_type,
4081 unsigned long node_start_pfn,
4082 unsigned long node_end_pfn,
4083 unsigned long *zone_start_pfn,
4084 unsigned long *zone_end_pfn)
4086 /* Only adjust if ZONE_MOVABLE is on this node */
4087 if (zone_movable_pfn[nid]) {
4088 /* Size ZONE_MOVABLE */
4089 if (zone_type == ZONE_MOVABLE) {
4090 *zone_start_pfn = zone_movable_pfn[nid];
4091 *zone_end_pfn = min(node_end_pfn,
4092 arch_zone_highest_possible_pfn[movable_zone]);
4094 /* Adjust for ZONE_MOVABLE starting within this range */
4095 } else if (*zone_start_pfn < zone_movable_pfn[nid] &&
4096 *zone_end_pfn > zone_movable_pfn[nid]) {
4097 *zone_end_pfn = zone_movable_pfn[nid];
4099 /* Check if this whole range is within ZONE_MOVABLE */
4100 } else if (*zone_start_pfn >= zone_movable_pfn[nid])
4101 *zone_start_pfn = *zone_end_pfn;
4106 * Return the number of pages a zone spans in a node, including holes
4107 * present_pages = zone_spanned_pages_in_node() - zone_absent_pages_in_node()
4109 static unsigned long __meminit zone_spanned_pages_in_node(int nid,
4110 unsigned long zone_type,
4111 unsigned long *ignored)
4113 unsigned long node_start_pfn, node_end_pfn;
4114 unsigned long zone_start_pfn, zone_end_pfn;
4116 /* Get the start and end of the node and zone */
4117 get_pfn_range_for_nid(nid, &node_start_pfn, &node_end_pfn);
4118 zone_start_pfn = arch_zone_lowest_possible_pfn[zone_type];
4119 zone_end_pfn = arch_zone_highest_possible_pfn[zone_type];
4120 adjust_zone_range_for_zone_movable(nid, zone_type,
4121 node_start_pfn, node_end_pfn,
4122 &zone_start_pfn, &zone_end_pfn);
4124 /* Check that this node has pages within the zone's required range */
4125 if (zone_end_pfn < node_start_pfn || zone_start_pfn > node_end_pfn)
4128 /* Move the zone boundaries inside the node if necessary */
4129 zone_end_pfn = min(zone_end_pfn, node_end_pfn);
4130 zone_start_pfn = max(zone_start_pfn, node_start_pfn);
4132 /* Return the spanned pages */
4133 return zone_end_pfn - zone_start_pfn;
4137 * Return the number of holes in a range on a node. If nid is MAX_NUMNODES,
4138 * then all holes in the requested range will be accounted for.
4140 unsigned long __meminit __absent_pages_in_range(int nid,
4141 unsigned long range_start_pfn,
4142 unsigned long range_end_pfn)
4144 unsigned long nr_absent = range_end_pfn - range_start_pfn;
4145 unsigned long start_pfn, end_pfn;
4148 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
4149 start_pfn = clamp(start_pfn, range_start_pfn, range_end_pfn);
4150 end_pfn = clamp(end_pfn, range_start_pfn, range_end_pfn);
4151 nr_absent -= end_pfn - start_pfn;
4157 * absent_pages_in_range - Return number of page frames in holes within a range
4158 * @start_pfn: The start PFN to start searching for holes
4159 * @end_pfn: The end PFN to stop searching for holes
4161 * It returns the number of pages frames in memory holes within a range.
4163 unsigned long __init absent_pages_in_range(unsigned long start_pfn,
4164 unsigned long end_pfn)
4166 return __absent_pages_in_range(MAX_NUMNODES, start_pfn, end_pfn);
4169 /* Return the number of page frames in holes in a zone on a node */
4170 static unsigned long __meminit zone_absent_pages_in_node(int nid,
4171 unsigned long zone_type,
4172 unsigned long *ignored)
4174 unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type];
4175 unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type];
4176 unsigned long node_start_pfn, node_end_pfn;
4177 unsigned long zone_start_pfn, zone_end_pfn;
4179 get_pfn_range_for_nid(nid, &node_start_pfn, &node_end_pfn);
4180 zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high);
4181 zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high);
4183 adjust_zone_range_for_zone_movable(nid, zone_type,
4184 node_start_pfn, node_end_pfn,
4185 &zone_start_pfn, &zone_end_pfn);
4186 return __absent_pages_in_range(nid, zone_start_pfn, zone_end_pfn);
4189 #else /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
4190 static inline unsigned long __meminit zone_spanned_pages_in_node(int nid,
4191 unsigned long zone_type,
4192 unsigned long *zones_size)
4194 return zones_size[zone_type];
4197 static inline unsigned long __meminit zone_absent_pages_in_node(int nid,
4198 unsigned long zone_type,
4199 unsigned long *zholes_size)
4204 return zholes_size[zone_type];
4207 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
4209 static void __meminit calculate_node_totalpages(struct pglist_data *pgdat,
4210 unsigned long *zones_size, unsigned long *zholes_size)
4212 unsigned long realtotalpages, totalpages = 0;
4215 for (i = 0; i < MAX_NR_ZONES; i++)
4216 totalpages += zone_spanned_pages_in_node(pgdat->node_id, i,
4218 pgdat->node_spanned_pages = totalpages;
4220 realtotalpages = totalpages;
4221 for (i = 0; i < MAX_NR_ZONES; i++)
4223 zone_absent_pages_in_node(pgdat->node_id, i,
4225 pgdat->node_present_pages = realtotalpages;
4226 printk(KERN_DEBUG "On node %d totalpages: %lu\n", pgdat->node_id,
4230 #ifndef CONFIG_SPARSEMEM
4232 * Calculate the size of the zone->blockflags rounded to an unsigned long
4233 * Start by making sure zonesize is a multiple of pageblock_order by rounding
4234 * up. Then use 1 NR_PAGEBLOCK_BITS worth of bits per pageblock, finally
4235 * round what is now in bits to nearest long in bits, then return it in
4238 static unsigned long __init usemap_size(unsigned long zonesize)
4240 unsigned long usemapsize;
4242 usemapsize = roundup(zonesize, pageblock_nr_pages);
4243 usemapsize = usemapsize >> pageblock_order;
4244 usemapsize *= NR_PAGEBLOCK_BITS;
4245 usemapsize = roundup(usemapsize, 8 * sizeof(unsigned long));
4247 return usemapsize / 8;
4250 static void __init setup_usemap(struct pglist_data *pgdat,
4251 struct zone *zone, unsigned long zonesize)
4253 unsigned long usemapsize = usemap_size(zonesize);
4254 zone->pageblock_flags = NULL;
4256 zone->pageblock_flags = alloc_bootmem_node_nopanic(pgdat,
4260 static inline void setup_usemap(struct pglist_data *pgdat,
4261 struct zone *zone, unsigned long zonesize) {}
4262 #endif /* CONFIG_SPARSEMEM */
4264 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
4266 /* Return a sensible default order for the pageblock size. */
4267 static inline int pageblock_default_order(void)
4269 if (HPAGE_SHIFT > PAGE_SHIFT)
4270 return HUGETLB_PAGE_ORDER;
4275 /* Initialise the number of pages represented by NR_PAGEBLOCK_BITS */
4276 static inline void __init set_pageblock_order(unsigned int order)
4278 /* Check that pageblock_nr_pages has not already been setup */
4279 if (pageblock_order)
4283 * Assume the largest contiguous order of interest is a huge page.
4284 * This value may be variable depending on boot parameters on IA64
4286 pageblock_order = order;
4288 #else /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
4291 * When CONFIG_HUGETLB_PAGE_SIZE_VARIABLE is not set, set_pageblock_order()
4292 * and pageblock_default_order() are unused as pageblock_order is set
4293 * at compile-time. See include/linux/pageblock-flags.h for the values of
4294 * pageblock_order based on the kernel config
4296 static inline int pageblock_default_order(unsigned int order)
4300 #define set_pageblock_order(x) do {} while (0)
4302 #endif /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
4305 * Set up the zone data structures:
4306 * - mark all pages reserved
4307 * - mark all memory queues empty
4308 * - clear the memory bitmaps
4310 static void __paginginit free_area_init_core(struct pglist_data *pgdat,
4311 unsigned long *zones_size, unsigned long *zholes_size)
4314 int nid = pgdat->node_id;
4315 unsigned long zone_start_pfn = pgdat->node_start_pfn;
4318 pgdat_resize_init(pgdat);
4319 pgdat->nr_zones = 0;
4320 init_waitqueue_head(&pgdat->kswapd_wait);
4321 pgdat->kswapd_max_order = 0;
4322 pgdat_page_cgroup_init(pgdat);
4324 for (j = 0; j < MAX_NR_ZONES; j++) {
4325 struct zone *zone = pgdat->node_zones + j;
4326 unsigned long size, realsize, memmap_pages;
4329 size = zone_spanned_pages_in_node(nid, j, zones_size);
4330 realsize = size - zone_absent_pages_in_node(nid, j,
4334 * Adjust realsize so that it accounts for how much memory
4335 * is used by this zone for memmap. This affects the watermark
4336 * and per-cpu initialisations
4339 PAGE_ALIGN(size * sizeof(struct page)) >> PAGE_SHIFT;
4340 if (realsize >= memmap_pages) {
4341 realsize -= memmap_pages;
4344 " %s zone: %lu pages used for memmap\n",
4345 zone_names[j], memmap_pages);
4348 " %s zone: %lu pages exceeds realsize %lu\n",
4349 zone_names[j], memmap_pages, realsize);
4351 /* Account for reserved pages */
4352 if (j == 0 && realsize > dma_reserve) {
4353 realsize -= dma_reserve;
4354 printk(KERN_DEBUG " %s zone: %lu pages reserved\n",
4355 zone_names[0], dma_reserve);
4358 if (!is_highmem_idx(j))
4359 nr_kernel_pages += realsize;
4360 nr_all_pages += realsize;
4362 zone->spanned_pages = size;
4363 zone->present_pages = realsize;
4366 zone->min_unmapped_pages = (realsize*sysctl_min_unmapped_ratio)
4368 zone->min_slab_pages = (realsize * sysctl_min_slab_ratio) / 100;
4370 zone->name = zone_names[j];
4371 spin_lock_init(&zone->lock);
4372 spin_lock_init(&zone->lru_lock);
4373 zone_seqlock_init(zone);
4374 zone->zone_pgdat = pgdat;
4376 zone_pcp_init(zone);
4378 INIT_LIST_HEAD(&zone->lruvec.lists[lru]);
4379 zone->reclaim_stat.recent_rotated[0] = 0;
4380 zone->reclaim_stat.recent_rotated[1] = 0;
4381 zone->reclaim_stat.recent_scanned[0] = 0;
4382 zone->reclaim_stat.recent_scanned[1] = 0;
4383 zap_zone_vm_stats(zone);
4388 set_pageblock_order(pageblock_default_order());
4389 setup_usemap(pgdat, zone, size);
4390 ret = init_currently_empty_zone(zone, zone_start_pfn,
4391 size, MEMMAP_EARLY);
4393 memmap_init(size, nid, j, zone_start_pfn);
4394 zone_start_pfn += size;
4398 static void __init_refok alloc_node_mem_map(struct pglist_data *pgdat)
4400 /* Skip empty nodes */
4401 if (!pgdat->node_spanned_pages)
4404 #ifdef CONFIG_FLAT_NODE_MEM_MAP
4405 /* ia64 gets its own node_mem_map, before this, without bootmem */
4406 if (!pgdat->node_mem_map) {
4407 unsigned long size, start, end;
4411 * The zone's endpoints aren't required to be MAX_ORDER
4412 * aligned but the node_mem_map endpoints must be in order
4413 * for the buddy allocator to function correctly.
4415 start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1);
4416 end = pgdat->node_start_pfn + pgdat->node_spanned_pages;
4417 end = ALIGN(end, MAX_ORDER_NR_PAGES);
4418 size = (end - start) * sizeof(struct page);
4419 map = alloc_remap(pgdat->node_id, size);
4421 map = alloc_bootmem_node_nopanic(pgdat, size);
4422 pgdat->node_mem_map = map + (pgdat->node_start_pfn - start);
4424 #ifndef CONFIG_NEED_MULTIPLE_NODES
4426 * With no DISCONTIG, the global mem_map is just set as node 0's
4428 if (pgdat == NODE_DATA(0)) {
4429 mem_map = NODE_DATA(0)->node_mem_map;
4430 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
4431 if (page_to_pfn(mem_map) != pgdat->node_start_pfn)
4432 mem_map -= (pgdat->node_start_pfn - ARCH_PFN_OFFSET);
4433 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
4436 #endif /* CONFIG_FLAT_NODE_MEM_MAP */
4439 void __paginginit free_area_init_node(int nid, unsigned long *zones_size,
4440 unsigned long node_start_pfn, unsigned long *zholes_size)
4442 pg_data_t *pgdat = NODE_DATA(nid);
4444 pgdat->node_id = nid;
4445 pgdat->node_start_pfn = node_start_pfn;
4446 calculate_node_totalpages(pgdat, zones_size, zholes_size);
4448 alloc_node_mem_map(pgdat);
4449 #ifdef CONFIG_FLAT_NODE_MEM_MAP
4450 printk(KERN_DEBUG "free_area_init_node: node %d, pgdat %08lx, node_mem_map %08lx\n",
4451 nid, (unsigned long)pgdat,
4452 (unsigned long)pgdat->node_mem_map);
4455 free_area_init_core(pgdat, zones_size, zholes_size);
4458 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
4460 #if MAX_NUMNODES > 1
4462 * Figure out the number of possible node ids.
4464 static void __init setup_nr_node_ids(void)
4467 unsigned int highest = 0;
4469 for_each_node_mask(node, node_possible_map)
4471 nr_node_ids = highest + 1;
4474 static inline void setup_nr_node_ids(void)
4480 * node_map_pfn_alignment - determine the maximum internode alignment
4482 * This function should be called after node map is populated and sorted.
4483 * It calculates the maximum power of two alignment which can distinguish
4486 * For example, if all nodes are 1GiB and aligned to 1GiB, the return value
4487 * would indicate 1GiB alignment with (1 << (30 - PAGE_SHIFT)). If the
4488 * nodes are shifted by 256MiB, 256MiB. Note that if only the last node is
4489 * shifted, 1GiB is enough and this function will indicate so.
4491 * This is used to test whether pfn -> nid mapping of the chosen memory
4492 * model has fine enough granularity to avoid incorrect mapping for the
4493 * populated node map.
4495 * Returns the determined alignment in pfn's. 0 if there is no alignment
4496 * requirement (single node).
4498 unsigned long __init node_map_pfn_alignment(void)
4500 unsigned long accl_mask = 0, last_end = 0;
4501 unsigned long start, end, mask;
4505 for_each_mem_pfn_range(i, MAX_NUMNODES, &start, &end, &nid) {
4506 if (!start || last_nid < 0 || last_nid == nid) {
4513 * Start with a mask granular enough to pin-point to the
4514 * start pfn and tick off bits one-by-one until it becomes
4515 * too coarse to separate the current node from the last.
4517 mask = ~((1 << __ffs(start)) - 1);
4518 while (mask && last_end <= (start & (mask << 1)))
4521 /* accumulate all internode masks */
4525 /* convert mask to number of pages */
4526 return ~accl_mask + 1;
4529 /* Find the lowest pfn for a node */
4530 static unsigned long __init find_min_pfn_for_node(int nid)
4532 unsigned long min_pfn = ULONG_MAX;
4533 unsigned long start_pfn;
4536 for_each_mem_pfn_range(i, nid, &start_pfn, NULL, NULL)
4537 min_pfn = min(min_pfn, start_pfn);
4539 if (min_pfn == ULONG_MAX) {
4541 "Could not find start_pfn for node %d\n", nid);
4549 * find_min_pfn_with_active_regions - Find the minimum PFN registered
4551 * It returns the minimum PFN based on information provided via
4552 * add_active_range().
4554 unsigned long __init find_min_pfn_with_active_regions(void)
4556 return find_min_pfn_for_node(MAX_NUMNODES);
4560 * early_calculate_totalpages()
4561 * Sum pages in active regions for movable zone.
4562 * Populate N_HIGH_MEMORY for calculating usable_nodes.
4564 static unsigned long __init early_calculate_totalpages(void)
4566 unsigned long totalpages = 0;
4567 unsigned long start_pfn, end_pfn;
4570 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
4571 unsigned long pages = end_pfn - start_pfn;
4573 totalpages += pages;
4575 node_set_state(nid, N_HIGH_MEMORY);
4581 * Find the PFN the Movable zone begins in each node. Kernel memory
4582 * is spread evenly between nodes as long as the nodes have enough
4583 * memory. When they don't, some nodes will have more kernelcore than
4586 static void __init find_zone_movable_pfns_for_nodes(void)
4589 unsigned long usable_startpfn;
4590 unsigned long kernelcore_node, kernelcore_remaining;
4591 /* save the state before borrow the nodemask */
4592 nodemask_t saved_node_state = node_states[N_HIGH_MEMORY];
4593 unsigned long totalpages = early_calculate_totalpages();
4594 int usable_nodes = nodes_weight(node_states[N_HIGH_MEMORY]);
4597 * If movablecore was specified, calculate what size of
4598 * kernelcore that corresponds so that memory usable for
4599 * any allocation type is evenly spread. If both kernelcore
4600 * and movablecore are specified, then the value of kernelcore
4601 * will be used for required_kernelcore if it's greater than
4602 * what movablecore would have allowed.
4604 if (required_movablecore) {
4605 unsigned long corepages;
4608 * Round-up so that ZONE_MOVABLE is at least as large as what
4609 * was requested by the user
4611 required_movablecore =
4612 roundup(required_movablecore, MAX_ORDER_NR_PAGES);
4613 corepages = totalpages - required_movablecore;
4615 required_kernelcore = max(required_kernelcore, corepages);
4618 /* If kernelcore was not specified, there is no ZONE_MOVABLE */
4619 if (!required_kernelcore)
4622 /* usable_startpfn is the lowest possible pfn ZONE_MOVABLE can be at */
4623 find_usable_zone_for_movable();
4624 usable_startpfn = arch_zone_lowest_possible_pfn[movable_zone];
4627 /* Spread kernelcore memory as evenly as possible throughout nodes */
4628 kernelcore_node = required_kernelcore / usable_nodes;
4629 for_each_node_state(nid, N_HIGH_MEMORY) {
4630 unsigned long start_pfn, end_pfn;
4633 * Recalculate kernelcore_node if the division per node
4634 * now exceeds what is necessary to satisfy the requested
4635 * amount of memory for the kernel
4637 if (required_kernelcore < kernelcore_node)
4638 kernelcore_node = required_kernelcore / usable_nodes;
4641 * As the map is walked, we track how much memory is usable
4642 * by the kernel using kernelcore_remaining. When it is
4643 * 0, the rest of the node is usable by ZONE_MOVABLE
4645 kernelcore_remaining = kernelcore_node;
4647 /* Go through each range of PFNs within this node */
4648 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
4649 unsigned long size_pages;
4651 start_pfn = max(start_pfn, zone_movable_pfn[nid]);
4652 if (start_pfn >= end_pfn)
4655 /* Account for what is only usable for kernelcore */
4656 if (start_pfn < usable_startpfn) {
4657 unsigned long kernel_pages;
4658 kernel_pages = min(end_pfn, usable_startpfn)
4661 kernelcore_remaining -= min(kernel_pages,
4662 kernelcore_remaining);
4663 required_kernelcore -= min(kernel_pages,
4664 required_kernelcore);
4666 /* Continue if range is now fully accounted */
4667 if (end_pfn <= usable_startpfn) {
4670 * Push zone_movable_pfn to the end so
4671 * that if we have to rebalance
4672 * kernelcore across nodes, we will
4673 * not double account here
4675 zone_movable_pfn[nid] = end_pfn;
4678 start_pfn = usable_startpfn;
4682 * The usable PFN range for ZONE_MOVABLE is from
4683 * start_pfn->end_pfn. Calculate size_pages as the
4684 * number of pages used as kernelcore
4686 size_pages = end_pfn - start_pfn;
4687 if (size_pages > kernelcore_remaining)
4688 size_pages = kernelcore_remaining;
4689 zone_movable_pfn[nid] = start_pfn + size_pages;
4692 * Some kernelcore has been met, update counts and
4693 * break if the kernelcore for this node has been
4696 required_kernelcore -= min(required_kernelcore,
4698 kernelcore_remaining -= size_pages;
4699 if (!kernelcore_remaining)
4705 * If there is still required_kernelcore, we do another pass with one
4706 * less node in the count. This will push zone_movable_pfn[nid] further
4707 * along on the nodes that still have memory until kernelcore is
4711 if (usable_nodes && required_kernelcore > usable_nodes)
4714 /* Align start of ZONE_MOVABLE on all nids to MAX_ORDER_NR_PAGES */
4715 for (nid = 0; nid < MAX_NUMNODES; nid++)
4716 zone_movable_pfn[nid] =
4717 roundup(zone_movable_pfn[nid], MAX_ORDER_NR_PAGES);
4720 /* restore the node_state */
4721 node_states[N_HIGH_MEMORY] = saved_node_state;
4724 /* Any regular memory on that node ? */
4725 static void check_for_regular_memory(pg_data_t *pgdat)
4727 #ifdef CONFIG_HIGHMEM
4728 enum zone_type zone_type;
4730 for (zone_type = 0; zone_type <= ZONE_NORMAL; zone_type++) {
4731 struct zone *zone = &pgdat->node_zones[zone_type];
4732 if (zone->present_pages) {
4733 node_set_state(zone_to_nid(zone), N_NORMAL_MEMORY);
4741 * free_area_init_nodes - Initialise all pg_data_t and zone data
4742 * @max_zone_pfn: an array of max PFNs for each zone
4744 * This will call free_area_init_node() for each active node in the system.
4745 * Using the page ranges provided by add_active_range(), the size of each
4746 * zone in each node and their holes is calculated. If the maximum PFN
4747 * between two adjacent zones match, it is assumed that the zone is empty.
4748 * For example, if arch_max_dma_pfn == arch_max_dma32_pfn, it is assumed
4749 * that arch_max_dma32_pfn has no pages. It is also assumed that a zone
4750 * starts where the previous one ended. For example, ZONE_DMA32 starts
4751 * at arch_max_dma_pfn.
4753 void __init free_area_init_nodes(unsigned long *max_zone_pfn)
4755 unsigned long start_pfn, end_pfn;
4758 /* Record where the zone boundaries are */
4759 memset(arch_zone_lowest_possible_pfn, 0,
4760 sizeof(arch_zone_lowest_possible_pfn));
4761 memset(arch_zone_highest_possible_pfn, 0,
4762 sizeof(arch_zone_highest_possible_pfn));
4763 arch_zone_lowest_possible_pfn[0] = find_min_pfn_with_active_regions();
4764 arch_zone_highest_possible_pfn[0] = max_zone_pfn[0];
4765 for (i = 1; i < MAX_NR_ZONES; i++) {
4766 if (i == ZONE_MOVABLE)
4768 arch_zone_lowest_possible_pfn[i] =
4769 arch_zone_highest_possible_pfn[i-1];
4770 arch_zone_highest_possible_pfn[i] =
4771 max(max_zone_pfn[i], arch_zone_lowest_possible_pfn[i]);
4773 arch_zone_lowest_possible_pfn[ZONE_MOVABLE] = 0;
4774 arch_zone_highest_possible_pfn[ZONE_MOVABLE] = 0;
4776 /* Find the PFNs that ZONE_MOVABLE begins at in each node */
4777 memset(zone_movable_pfn, 0, sizeof(zone_movable_pfn));
4778 find_zone_movable_pfns_for_nodes();
4780 /* Print out the zone ranges */
4781 printk("Zone PFN ranges:\n");
4782 for (i = 0; i < MAX_NR_ZONES; i++) {
4783 if (i == ZONE_MOVABLE)
4785 printk(" %-8s ", zone_names[i]);
4786 if (arch_zone_lowest_possible_pfn[i] ==
4787 arch_zone_highest_possible_pfn[i])
4790 printk("%0#10lx -> %0#10lx\n",
4791 arch_zone_lowest_possible_pfn[i],
4792 arch_zone_highest_possible_pfn[i]);
4795 /* Print out the PFNs ZONE_MOVABLE begins at in each node */
4796 printk("Movable zone start PFN for each node\n");
4797 for (i = 0; i < MAX_NUMNODES; i++) {
4798 if (zone_movable_pfn[i])
4799 printk(" Node %d: %lu\n", i, zone_movable_pfn[i]);
4802 /* Print out the early_node_map[] */
4803 printk("Early memory PFN ranges\n");
4804 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid)
4805 printk(" %3d: %0#10lx -> %0#10lx\n", nid, start_pfn, end_pfn);
4807 /* Initialise every node */
4808 mminit_verify_pageflags_layout();
4809 setup_nr_node_ids();
4810 for_each_online_node(nid) {
4811 pg_data_t *pgdat = NODE_DATA(nid);
4812 free_area_init_node(nid, NULL,
4813 find_min_pfn_for_node(nid), NULL);
4815 /* Any memory on that node */
4816 if (pgdat->node_present_pages)
4817 node_set_state(nid, N_HIGH_MEMORY);
4818 check_for_regular_memory(pgdat);
4822 static int __init cmdline_parse_core(char *p, unsigned long *core)
4824 unsigned long long coremem;
4828 coremem = memparse(p, &p);
4829 *core = coremem >> PAGE_SHIFT;
4831 /* Paranoid check that UL is enough for the coremem value */
4832 WARN_ON((coremem >> PAGE_SHIFT) > ULONG_MAX);
4838 * kernelcore=size sets the amount of memory for use for allocations that
4839 * cannot be reclaimed or migrated.
4841 static int __init cmdline_parse_kernelcore(char *p)
4843 return cmdline_parse_core(p, &required_kernelcore);
4847 * movablecore=size sets the amount of memory for use for allocations that
4848 * can be reclaimed or migrated.
4850 static int __init cmdline_parse_movablecore(char *p)
4852 return cmdline_parse_core(p, &required_movablecore);
4855 early_param("kernelcore", cmdline_parse_kernelcore);
4856 early_param("movablecore", cmdline_parse_movablecore);
4858 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
4861 * set_dma_reserve - set the specified number of pages reserved in the first zone
4862 * @new_dma_reserve: The number of pages to mark reserved
4864 * The per-cpu batchsize and zone watermarks are determined by present_pages.
4865 * In the DMA zone, a significant percentage may be consumed by kernel image
4866 * and other unfreeable allocations which can skew the watermarks badly. This
4867 * function may optionally be used to account for unfreeable pages in the
4868 * first zone (e.g., ZONE_DMA). The effect will be lower watermarks and
4869 * smaller per-cpu batchsize.
4871 void __init set_dma_reserve(unsigned long new_dma_reserve)
4873 dma_reserve = new_dma_reserve;
4876 void __init free_area_init(unsigned long *zones_size)
4878 free_area_init_node(0, zones_size,
4879 __pa(PAGE_OFFSET) >> PAGE_SHIFT, NULL);
4882 static int page_alloc_cpu_notify(struct notifier_block *self,
4883 unsigned long action, void *hcpu)
4885 int cpu = (unsigned long)hcpu;
4887 if (action == CPU_DEAD || action == CPU_DEAD_FROZEN) {
4888 lru_add_drain_cpu(cpu);
4892 * Spill the event counters of the dead processor
4893 * into the current processors event counters.
4894 * This artificially elevates the count of the current
4897 vm_events_fold_cpu(cpu);
4900 * Zero the differential counters of the dead processor
4901 * so that the vm statistics are consistent.
4903 * This is only okay since the processor is dead and cannot
4904 * race with what we are doing.
4906 refresh_cpu_vm_stats(cpu);
4911 void __init page_alloc_init(void)
4913 hotcpu_notifier(page_alloc_cpu_notify, 0);
4917 * calculate_totalreserve_pages - called when sysctl_lower_zone_reserve_ratio
4918 * or min_free_kbytes changes.
4920 static void calculate_totalreserve_pages(void)
4922 struct pglist_data *pgdat;
4923 unsigned long reserve_pages = 0;
4924 enum zone_type i, j;
4926 for_each_online_pgdat(pgdat) {
4927 for (i = 0; i < MAX_NR_ZONES; i++) {
4928 struct zone *zone = pgdat->node_zones + i;
4929 unsigned long max = 0;
4931 /* Find valid and maximum lowmem_reserve in the zone */
4932 for (j = i; j < MAX_NR_ZONES; j++) {
4933 if (zone->lowmem_reserve[j] > max)
4934 max = zone->lowmem_reserve[j];
4937 /* we treat the high watermark as reserved pages. */
4938 max += high_wmark_pages(zone);
4940 if (max > zone->present_pages)
4941 max = zone->present_pages;
4942 reserve_pages += max;
4944 * Lowmem reserves are not available to
4945 * GFP_HIGHUSER page cache allocations and
4946 * kswapd tries to balance zones to their high
4947 * watermark. As a result, neither should be
4948 * regarded as dirtyable memory, to prevent a
4949 * situation where reclaim has to clean pages
4950 * in order to balance the zones.
4952 zone->dirty_balance_reserve = max;
4955 dirty_balance_reserve = reserve_pages;
4956 totalreserve_pages = reserve_pages;
4960 * setup_per_zone_lowmem_reserve - called whenever
4961 * sysctl_lower_zone_reserve_ratio changes. Ensures that each zone
4962 * has a correct pages reserved value, so an adequate number of
4963 * pages are left in the zone after a successful __alloc_pages().
4965 static void setup_per_zone_lowmem_reserve(void)
4967 struct pglist_data *pgdat;
4968 enum zone_type j, idx;
4970 for_each_online_pgdat(pgdat) {
4971 for (j = 0; j < MAX_NR_ZONES; j++) {
4972 struct zone *zone = pgdat->node_zones + j;
4973 unsigned long present_pages = zone->present_pages;
4975 zone->lowmem_reserve[j] = 0;
4979 struct zone *lower_zone;
4983 if (sysctl_lowmem_reserve_ratio[idx] < 1)
4984 sysctl_lowmem_reserve_ratio[idx] = 1;
4986 lower_zone = pgdat->node_zones + idx;
4987 lower_zone->lowmem_reserve[j] = present_pages /
4988 sysctl_lowmem_reserve_ratio[idx];
4989 present_pages += lower_zone->present_pages;
4994 /* update totalreserve_pages */
4995 calculate_totalreserve_pages();
4999 * setup_per_zone_wmarks - called when min_free_kbytes changes
5000 * or when memory is hot-{added|removed}
5002 * Ensures that the watermark[min,low,high] values for each zone are set
5003 * correctly with respect to min_free_kbytes.
5005 void setup_per_zone_wmarks(void)
5007 unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
5008 unsigned long lowmem_pages = 0;
5010 unsigned long flags;
5012 /* Calculate total number of !ZONE_HIGHMEM pages */
5013 for_each_zone(zone) {
5014 if (!is_highmem(zone))
5015 lowmem_pages += zone->present_pages;
5018 for_each_zone(zone) {
5021 spin_lock_irqsave(&zone->lock, flags);
5022 tmp = (u64)pages_min * zone->present_pages;
5023 do_div(tmp, lowmem_pages);
5024 if (is_highmem(zone)) {
5026 * __GFP_HIGH and PF_MEMALLOC allocations usually don't
5027 * need highmem pages, so cap pages_min to a small
5030 * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN)
5031 * deltas controls asynch page reclaim, and so should
5032 * not be capped for highmem.
5036 min_pages = zone->present_pages / 1024;
5037 if (min_pages < SWAP_CLUSTER_MAX)
5038 min_pages = SWAP_CLUSTER_MAX;
5039 if (min_pages > 128)
5041 zone->watermark[WMARK_MIN] = min_pages;
5044 * If it's a lowmem zone, reserve a number of pages
5045 * proportionate to the zone's size.
5047 zone->watermark[WMARK_MIN] = tmp;
5050 zone->watermark[WMARK_LOW] = min_wmark_pages(zone) + (tmp >> 2);
5051 zone->watermark[WMARK_HIGH] = min_wmark_pages(zone) + (tmp >> 1);
5052 setup_zone_migrate_reserve(zone);
5053 spin_unlock_irqrestore(&zone->lock, flags);
5057 for_each_populated_zone(zone) {
5060 for_each_online_cpu(cpu) {
5063 high = percpu_pagelist_fraction
5064 ? zone->present_pages / percpu_pagelist_fraction
5065 : 5 * zone_batchsize(zone);
5066 setup_pagelist_highmark(
5067 per_cpu_ptr(zone->pageset, cpu), high);
5072 /* update totalreserve_pages */
5073 calculate_totalreserve_pages();
5077 * The inactive anon list should be small enough that the VM never has to
5078 * do too much work, but large enough that each inactive page has a chance
5079 * to be referenced again before it is swapped out.
5081 * The inactive_anon ratio is the target ratio of ACTIVE_ANON to
5082 * INACTIVE_ANON pages on this zone's LRU, maintained by the
5083 * pageout code. A zone->inactive_ratio of 3 means 3:1 or 25% of
5084 * the anonymous pages are kept on the inactive list.
5087 * memory ratio inactive anon
5088 * -------------------------------------
5097 static void __meminit calculate_zone_inactive_ratio(struct zone *zone)
5099 unsigned int gb, ratio;
5101 /* Zone size in gigabytes */
5102 gb = zone->present_pages >> (30 - PAGE_SHIFT);
5104 ratio = int_sqrt(10 * gb);
5108 zone->inactive_ratio = ratio;
5111 static void __meminit setup_per_zone_inactive_ratio(void)
5116 calculate_zone_inactive_ratio(zone);
5120 * Initialise min_free_kbytes.
5122 * For small machines we want it small (128k min). For large machines
5123 * we want it large (64MB max). But it is not linear, because network
5124 * bandwidth does not increase linearly with machine size. We use
5126 * min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
5127 * min_free_kbytes = sqrt(lowmem_kbytes * 16)
5143 int __meminit init_per_zone_wmark_min(void)
5145 unsigned long lowmem_kbytes;
5147 lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
5149 min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
5150 if (min_free_kbytes < 128)
5151 min_free_kbytes = 128;
5152 if (min_free_kbytes > 65536)
5153 min_free_kbytes = 65536;
5154 setup_per_zone_wmarks();
5155 refresh_zone_stat_thresholds();
5156 setup_per_zone_lowmem_reserve();
5157 setup_per_zone_inactive_ratio();
5160 module_init(init_per_zone_wmark_min)
5163 * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
5164 * that we can call two helper functions whenever min_free_kbytes
5167 int min_free_kbytes_sysctl_handler(ctl_table *table, int write,
5168 void __user *buffer, size_t *length, loff_t *ppos)
5170 proc_dointvec(table, write, buffer, length, ppos);
5172 setup_per_zone_wmarks();
5177 int sysctl_min_unmapped_ratio_sysctl_handler(ctl_table *table, int write,
5178 void __user *buffer, size_t *length, loff_t *ppos)
5183 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
5188 zone->min_unmapped_pages = (zone->present_pages *
5189 sysctl_min_unmapped_ratio) / 100;
5193 int sysctl_min_slab_ratio_sysctl_handler(ctl_table *table, int write,
5194 void __user *buffer, size_t *length, loff_t *ppos)
5199 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
5204 zone->min_slab_pages = (zone->present_pages *
5205 sysctl_min_slab_ratio) / 100;
5211 * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
5212 * proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
5213 * whenever sysctl_lowmem_reserve_ratio changes.
5215 * The reserve ratio obviously has absolutely no relation with the
5216 * minimum watermarks. The lowmem reserve ratio can only make sense
5217 * if in function of the boot time zone sizes.
5219 int lowmem_reserve_ratio_sysctl_handler(ctl_table *table, int write,
5220 void __user *buffer, size_t *length, loff_t *ppos)
5222 proc_dointvec_minmax(table, write, buffer, length, ppos);
5223 setup_per_zone_lowmem_reserve();
5228 * percpu_pagelist_fraction - changes the pcp->high for each zone on each
5229 * cpu. It is the fraction of total pages in each zone that a hot per cpu pagelist
5230 * can have before it gets flushed back to buddy allocator.
5233 int percpu_pagelist_fraction_sysctl_handler(ctl_table *table, int write,
5234 void __user *buffer, size_t *length, loff_t *ppos)
5240 ret = proc_dointvec_minmax(table, write, buffer, length, ppos);
5241 if (!write || (ret == -EINVAL))
5243 for_each_populated_zone(zone) {
5244 for_each_possible_cpu(cpu) {
5246 high = zone->present_pages / percpu_pagelist_fraction;
5247 setup_pagelist_highmark(
5248 per_cpu_ptr(zone->pageset, cpu), high);
5254 int hashdist = HASHDIST_DEFAULT;
5257 static int __init set_hashdist(char *str)
5261 hashdist = simple_strtoul(str, &str, 0);
5264 __setup("hashdist=", set_hashdist);
5268 * allocate a large system hash table from bootmem
5269 * - it is assumed that the hash table must contain an exact power-of-2
5270 * quantity of entries
5271 * - limit is the number of hash buckets, not the total allocation size
5273 void *__init alloc_large_system_hash(const char *tablename,
5274 unsigned long bucketsize,
5275 unsigned long numentries,
5278 unsigned int *_hash_shift,
5279 unsigned int *_hash_mask,
5280 unsigned long limit)
5282 unsigned long long max = limit;
5283 unsigned long log2qty, size;
5286 /* allow the kernel cmdline to have a say */
5288 /* round applicable memory size up to nearest megabyte */
5289 numentries = nr_kernel_pages;
5290 numentries += (1UL << (20 - PAGE_SHIFT)) - 1;
5291 numentries >>= 20 - PAGE_SHIFT;
5292 numentries <<= 20 - PAGE_SHIFT;
5294 /* limit to 1 bucket per 2^scale bytes of low memory */
5295 if (scale > PAGE_SHIFT)
5296 numentries >>= (scale - PAGE_SHIFT);
5298 numentries <<= (PAGE_SHIFT - scale);
5300 /* Make sure we've got at least a 0-order allocation.. */
5301 if (unlikely(flags & HASH_SMALL)) {
5302 /* Makes no sense without HASH_EARLY */
5303 WARN_ON(!(flags & HASH_EARLY));
5304 if (!(numentries >> *_hash_shift)) {
5305 numentries = 1UL << *_hash_shift;
5306 BUG_ON(!numentries);
5308 } else if (unlikely((numentries * bucketsize) < PAGE_SIZE))
5309 numentries = PAGE_SIZE / bucketsize;
5311 numentries = roundup_pow_of_two(numentries);
5313 /* limit allocation size to 1/16 total memory by default */
5315 max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
5316 do_div(max, bucketsize);
5318 max = min(max, 0x80000000ULL);
5320 if (numentries > max)
5323 log2qty = ilog2(numentries);
5326 size = bucketsize << log2qty;
5327 if (flags & HASH_EARLY)
5328 table = alloc_bootmem_nopanic(size);
5330 table = __vmalloc(size, GFP_ATOMIC, PAGE_KERNEL);
5333 * If bucketsize is not a power-of-two, we may free
5334 * some pages at the end of hash table which
5335 * alloc_pages_exact() automatically does
5337 if (get_order(size) < MAX_ORDER) {
5338 table = alloc_pages_exact(size, GFP_ATOMIC);
5339 kmemleak_alloc(table, size, 1, GFP_ATOMIC);
5342 } while (!table && size > PAGE_SIZE && --log2qty);
5345 panic("Failed to allocate %s hash table\n", tablename);
5347 printk(KERN_INFO "%s hash table entries: %ld (order: %d, %lu bytes)\n",
5350 ilog2(size) - PAGE_SHIFT,
5354 *_hash_shift = log2qty;
5356 *_hash_mask = (1 << log2qty) - 1;
5361 /* Return a pointer to the bitmap storing bits affecting a block of pages */
5362 static inline unsigned long *get_pageblock_bitmap(struct zone *zone,
5365 #ifdef CONFIG_SPARSEMEM
5366 return __pfn_to_section(pfn)->pageblock_flags;
5368 return zone->pageblock_flags;
5369 #endif /* CONFIG_SPARSEMEM */
5372 static inline int pfn_to_bitidx(struct zone *zone, unsigned long pfn)
5374 #ifdef CONFIG_SPARSEMEM
5375 pfn &= (PAGES_PER_SECTION-1);
5376 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
5378 pfn = pfn - zone->zone_start_pfn;
5379 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
5380 #endif /* CONFIG_SPARSEMEM */
5384 * get_pageblock_flags_group - Return the requested group of flags for the pageblock_nr_pages block of pages
5385 * @page: The page within the block of interest
5386 * @start_bitidx: The first bit of interest to retrieve
5387 * @end_bitidx: The last bit of interest
5388 * returns pageblock_bits flags
5390 unsigned long get_pageblock_flags_group(struct page *page,
5391 int start_bitidx, int end_bitidx)
5394 unsigned long *bitmap;
5395 unsigned long pfn, bitidx;
5396 unsigned long flags = 0;
5397 unsigned long value = 1;
5399 zone = page_zone(page);
5400 pfn = page_to_pfn(page);
5401 bitmap = get_pageblock_bitmap(zone, pfn);
5402 bitidx = pfn_to_bitidx(zone, pfn);
5404 for (; start_bitidx <= end_bitidx; start_bitidx++, value <<= 1)
5405 if (test_bit(bitidx + start_bitidx, bitmap))
5412 * set_pageblock_flags_group - Set the requested group of flags for a pageblock_nr_pages block of pages
5413 * @page: The page within the block of interest
5414 * @start_bitidx: The first bit of interest
5415 * @end_bitidx: The last bit of interest
5416 * @flags: The flags to set
5418 void set_pageblock_flags_group(struct page *page, unsigned long flags,
5419 int start_bitidx, int end_bitidx)
5422 unsigned long *bitmap;
5423 unsigned long pfn, bitidx;
5424 unsigned long value = 1;
5426 zone = page_zone(page);
5427 pfn = page_to_pfn(page);
5428 bitmap = get_pageblock_bitmap(zone, pfn);
5429 bitidx = pfn_to_bitidx(zone, pfn);
5430 VM_BUG_ON(pfn < zone->zone_start_pfn);
5431 VM_BUG_ON(pfn >= zone->zone_start_pfn + zone->spanned_pages);
5433 for (; start_bitidx <= end_bitidx; start_bitidx++, value <<= 1)
5435 __set_bit(bitidx + start_bitidx, bitmap);
5437 __clear_bit(bitidx + start_bitidx, bitmap);
5441 * This is designed as sub function...plz see page_isolation.c also.
5442 * set/clear page block's type to be ISOLATE.
5443 * page allocater never alloc memory from ISOLATE block.
5447 __count_immobile_pages(struct zone *zone, struct page *page, int count)
5449 unsigned long pfn, iter, found;
5451 * For avoiding noise data, lru_add_drain_all() should be called
5452 * If ZONE_MOVABLE, the zone never contains immobile pages
5454 if (zone_idx(zone) == ZONE_MOVABLE)
5457 if (get_pageblock_migratetype(page) == MIGRATE_MOVABLE)
5460 pfn = page_to_pfn(page);
5461 for (found = 0, iter = 0; iter < pageblock_nr_pages; iter++) {
5462 unsigned long check = pfn + iter;
5464 if (!pfn_valid_within(check))
5467 page = pfn_to_page(check);
5468 if (!page_count(page)) {
5469 if (PageBuddy(page))
5470 iter += (1 << page_order(page)) - 1;
5476 * If there are RECLAIMABLE pages, we need to check it.
5477 * But now, memory offline itself doesn't call shrink_slab()
5478 * and it still to be fixed.
5481 * If the page is not RAM, page_count()should be 0.
5482 * we don't need more check. This is an _used_ not-movable page.
5484 * The problematic thing here is PG_reserved pages. PG_reserved
5485 * is set to both of a memory hole page and a _used_ kernel
5494 bool is_pageblock_removable_nolock(struct page *page)
5500 * We have to be careful here because we are iterating over memory
5501 * sections which are not zone aware so we might end up outside of
5502 * the zone but still within the section.
5503 * We have to take care about the node as well. If the node is offline
5504 * its NODE_DATA will be NULL - see page_zone.
5506 if (!node_online(page_to_nid(page)))
5509 zone = page_zone(page);
5510 pfn = page_to_pfn(page);
5511 if (zone->zone_start_pfn > pfn ||
5512 zone->zone_start_pfn + zone->spanned_pages <= pfn)
5515 return __count_immobile_pages(zone, page, 0);
5518 int set_migratetype_isolate(struct page *page)
5521 unsigned long flags, pfn;
5522 struct memory_isolate_notify arg;
5526 zone = page_zone(page);
5528 spin_lock_irqsave(&zone->lock, flags);
5530 pfn = page_to_pfn(page);
5531 arg.start_pfn = pfn;
5532 arg.nr_pages = pageblock_nr_pages;
5533 arg.pages_found = 0;
5536 * It may be possible to isolate a pageblock even if the
5537 * migratetype is not MIGRATE_MOVABLE. The memory isolation
5538 * notifier chain is used by balloon drivers to return the
5539 * number of pages in a range that are held by the balloon
5540 * driver to shrink memory. If all the pages are accounted for
5541 * by balloons, are free, or on the LRU, isolation can continue.
5542 * Later, for example, when memory hotplug notifier runs, these
5543 * pages reported as "can be isolated" should be isolated(freed)
5544 * by the balloon driver through the memory notifier chain.
5546 notifier_ret = memory_isolate_notify(MEM_ISOLATE_COUNT, &arg);
5547 notifier_ret = notifier_to_errno(notifier_ret);
5551 * FIXME: Now, memory hotplug doesn't call shrink_slab() by itself.
5552 * We just check MOVABLE pages.
5554 if (__count_immobile_pages(zone, page, arg.pages_found))
5558 * immobile means "not-on-lru" paes. If immobile is larger than
5559 * removable-by-driver pages reported by notifier, we'll fail.
5564 set_pageblock_migratetype(page, MIGRATE_ISOLATE);
5565 move_freepages_block(zone, page, MIGRATE_ISOLATE);
5568 spin_unlock_irqrestore(&zone->lock, flags);
5574 void unset_migratetype_isolate(struct page *page)
5577 unsigned long flags;
5578 zone = page_zone(page);
5579 spin_lock_irqsave(&zone->lock, flags);
5580 if (get_pageblock_migratetype(page) != MIGRATE_ISOLATE)
5582 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
5583 move_freepages_block(zone, page, MIGRATE_MOVABLE);
5585 spin_unlock_irqrestore(&zone->lock, flags);
5588 #ifdef CONFIG_MEMORY_HOTREMOVE
5590 * All pages in the range must be isolated before calling this.
5593 __offline_isolated_pages(unsigned long start_pfn, unsigned long end_pfn)
5599 unsigned long flags;
5600 /* find the first valid pfn */
5601 for (pfn = start_pfn; pfn < end_pfn; pfn++)
5606 zone = page_zone(pfn_to_page(pfn));
5607 spin_lock_irqsave(&zone->lock, flags);
5609 while (pfn < end_pfn) {
5610 if (!pfn_valid(pfn)) {
5614 page = pfn_to_page(pfn);
5615 BUG_ON(page_count(page));
5616 BUG_ON(!PageBuddy(page));
5617 order = page_order(page);
5618 #ifdef CONFIG_DEBUG_VM
5619 printk(KERN_INFO "remove from free list %lx %d %lx\n",
5620 pfn, 1 << order, end_pfn);
5622 list_del(&page->lru);
5623 rmv_page_order(page);
5624 zone->free_area[order].nr_free--;
5625 __mod_zone_page_state(zone, NR_FREE_PAGES,
5627 for (i = 0; i < (1 << order); i++)
5628 SetPageReserved((page+i));
5629 pfn += (1 << order);
5631 spin_unlock_irqrestore(&zone->lock, flags);
5635 #ifdef CONFIG_MEMORY_FAILURE
5636 bool is_free_buddy_page(struct page *page)
5638 struct zone *zone = page_zone(page);
5639 unsigned long pfn = page_to_pfn(page);
5640 unsigned long flags;
5643 spin_lock_irqsave(&zone->lock, flags);
5644 for (order = 0; order < MAX_ORDER; order++) {
5645 struct page *page_head = page - (pfn & ((1 << order) - 1));
5647 if (PageBuddy(page_head) && page_order(page_head) >= order)
5650 spin_unlock_irqrestore(&zone->lock, flags);
5652 return order < MAX_ORDER;
5656 static struct trace_print_flags pageflag_names[] = {
5657 {1UL << PG_locked, "locked" },
5658 {1UL << PG_error, "error" },
5659 {1UL << PG_referenced, "referenced" },
5660 {1UL << PG_uptodate, "uptodate" },
5661 {1UL << PG_dirty, "dirty" },
5662 {1UL << PG_lru, "lru" },
5663 {1UL << PG_active, "active" },
5664 {1UL << PG_slab, "slab" },
5665 {1UL << PG_owner_priv_1, "owner_priv_1" },
5666 {1UL << PG_arch_1, "arch_1" },
5667 {1UL << PG_reserved, "reserved" },
5668 {1UL << PG_private, "private" },
5669 {1UL << PG_private_2, "private_2" },
5670 {1UL << PG_writeback, "writeback" },
5671 #ifdef CONFIG_PAGEFLAGS_EXTENDED
5672 {1UL << PG_head, "head" },
5673 {1UL << PG_tail, "tail" },
5675 {1UL << PG_compound, "compound" },
5677 {1UL << PG_swapcache, "swapcache" },
5678 {1UL << PG_mappedtodisk, "mappedtodisk" },
5679 {1UL << PG_reclaim, "reclaim" },
5680 {1UL << PG_swapbacked, "swapbacked" },
5681 {1UL << PG_unevictable, "unevictable" },
5683 {1UL << PG_mlocked, "mlocked" },
5685 #ifdef CONFIG_ARCH_USES_PG_UNCACHED
5686 {1UL << PG_uncached, "uncached" },
5688 #ifdef CONFIG_MEMORY_FAILURE
5689 {1UL << PG_hwpoison, "hwpoison" },
5694 static void dump_page_flags(unsigned long flags)
5696 const char *delim = "";
5700 printk(KERN_ALERT "page flags: %#lx(", flags);
5702 /* remove zone id */
5703 flags &= (1UL << NR_PAGEFLAGS) - 1;
5705 for (i = 0; pageflag_names[i].name && flags; i++) {
5707 mask = pageflag_names[i].mask;
5708 if ((flags & mask) != mask)
5712 printk("%s%s", delim, pageflag_names[i].name);
5716 /* check for left over flags */
5718 printk("%s%#lx", delim, flags);
5723 void dump_page(struct page *page)
5726 "page:%p count:%d mapcount:%d mapping:%p index:%#lx\n",
5727 page, atomic_read(&page->_count), page_mapcount(page),
5728 page->mapping, page->index);
5729 dump_page_flags(page->flags);
5730 mem_cgroup_print_bad_page(page);