Linux 3.12.39
[linux/fpc-iii.git] / mm / page_alloc.c
blob7abab3b7d1401b2662e2f8ed0b4d377f3190e215
1 /*
2 * linux/mm/page_alloc.c
4 * Manages the free list, the system allocates free pages here.
5 * Note that kmalloc() lives in slab.c
7 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
8 * Swap reorganised 29.12.95, Stephen Tweedie
9 * Support of BIGMEM added by Gerhard Wichert, Siemens AG, July 1999
10 * Reshaped it to be a zoned allocator, Ingo Molnar, Red Hat, 1999
11 * Discontiguous memory support, Kanoj Sarcar, SGI, Nov 1999
12 * Zone balancing, Kanoj Sarcar, SGI, Jan 2000
13 * Per cpu hot/cold page lists, bulk allocation, Martin J. Bligh, Sept 2002
14 * (lots of bits borrowed from Ingo Molnar & Andrew Morton)
17 #include <linux/stddef.h>
18 #include <linux/mm.h>
19 #include <linux/swap.h>
20 #include <linux/interrupt.h>
21 #include <linux/pagemap.h>
22 #include <linux/jiffies.h>
23 #include <linux/bootmem.h>
24 #include <linux/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/compaction.h>
55 #include <trace/events/kmem.h>
56 #include <linux/ftrace_event.h>
57 #include <linux/memcontrol.h>
58 #include <linux/prefetch.h>
59 #include <linux/mm_inline.h>
60 #include <linux/migrate.h>
61 #include <linux/page-debug-flags.h>
62 #include <linux/hugetlb.h>
63 #include <linux/sched/rt.h>
65 #include <asm/sections.h>
66 #include <asm/tlbflush.h>
67 #include <asm/div64.h>
68 #include "internal.h"
70 /* prevent >1 _updater_ of zone percpu pageset ->high and ->batch fields */
71 static DEFINE_MUTEX(pcp_batch_high_lock);
72 #define MIN_PERCPU_PAGELIST_FRACTION (8)
74 #ifdef CONFIG_USE_PERCPU_NUMA_NODE_ID
75 DEFINE_PER_CPU(int, numa_node);
76 EXPORT_PER_CPU_SYMBOL(numa_node);
77 #endif
79 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
81 * N.B., Do NOT reference the '_numa_mem_' per cpu variable directly.
82 * It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined.
83 * Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem()
84 * defined in <linux/topology.h>.
86 DEFINE_PER_CPU(int, _numa_mem_); /* Kernel "local memory" node */
87 EXPORT_PER_CPU_SYMBOL(_numa_mem_);
88 #endif
91 * Array of node states.
93 nodemask_t node_states[NR_NODE_STATES] __read_mostly = {
94 [N_POSSIBLE] = NODE_MASK_ALL,
95 [N_ONLINE] = { { [0] = 1UL } },
96 #ifndef CONFIG_NUMA
97 [N_NORMAL_MEMORY] = { { [0] = 1UL } },
98 #ifdef CONFIG_HIGHMEM
99 [N_HIGH_MEMORY] = { { [0] = 1UL } },
100 #endif
101 #ifdef CONFIG_MOVABLE_NODE
102 [N_MEMORY] = { { [0] = 1UL } },
103 #endif
104 [N_CPU] = { { [0] = 1UL } },
105 #endif /* NUMA */
107 EXPORT_SYMBOL(node_states);
109 /* Protect totalram_pages and zone->managed_pages */
110 static DEFINE_SPINLOCK(managed_page_count_lock);
112 unsigned long totalram_pages __read_mostly;
113 unsigned long totalreserve_pages __read_mostly;
115 * When calculating the number of globally allowed dirty pages, there
116 * is a certain number of per-zone reserves that should not be
117 * considered dirtyable memory. This is the sum of those reserves
118 * over all existing zones that contribute dirtyable memory.
120 unsigned long dirty_balance_reserve __read_mostly;
122 int percpu_pagelist_fraction;
123 gfp_t gfp_allowed_mask __read_mostly = GFP_BOOT_MASK;
125 #ifdef CONFIG_PM_SLEEP
127 * The following functions are used by the suspend/hibernate code to temporarily
128 * change gfp_allowed_mask in order to avoid using I/O during memory allocations
129 * while devices are suspended. To avoid races with the suspend/hibernate code,
130 * they should always be called with pm_mutex held (gfp_allowed_mask also should
131 * only be modified with pm_mutex held, unless the suspend/hibernate code is
132 * guaranteed not to run in parallel with that modification).
135 static gfp_t saved_gfp_mask;
137 void pm_restore_gfp_mask(void)
139 WARN_ON(!mutex_is_locked(&pm_mutex));
140 if (saved_gfp_mask) {
141 gfp_allowed_mask = saved_gfp_mask;
142 saved_gfp_mask = 0;
146 void pm_restrict_gfp_mask(void)
148 WARN_ON(!mutex_is_locked(&pm_mutex));
149 WARN_ON(saved_gfp_mask);
150 saved_gfp_mask = gfp_allowed_mask;
151 gfp_allowed_mask &= ~GFP_IOFS;
154 bool pm_suspended_storage(void)
156 if ((gfp_allowed_mask & GFP_IOFS) == GFP_IOFS)
157 return false;
158 return true;
160 #endif /* CONFIG_PM_SLEEP */
162 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
163 int pageblock_order __read_mostly;
164 #endif
166 static void __free_pages_ok(struct page *page, unsigned int order);
169 * results with 256, 32 in the lowmem_reserve sysctl:
170 * 1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
171 * 1G machine -> (16M dma, 784M normal, 224M high)
172 * NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
173 * HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
174 * HIGHMEM allocation will (224M+784M)/256 of ram reserved in ZONE_DMA
176 * TBD: should special case ZONE_DMA32 machines here - in those we normally
177 * don't need any ZONE_NORMAL reservation
179 int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES-1] = {
180 #ifdef CONFIG_ZONE_DMA
181 256,
182 #endif
183 #ifdef CONFIG_ZONE_DMA32
184 256,
185 #endif
186 #ifdef CONFIG_HIGHMEM
188 #endif
192 EXPORT_SYMBOL(totalram_pages);
194 static char * const zone_names[MAX_NR_ZONES] = {
195 #ifdef CONFIG_ZONE_DMA
196 "DMA",
197 #endif
198 #ifdef CONFIG_ZONE_DMA32
199 "DMA32",
200 #endif
201 "Normal",
202 #ifdef CONFIG_HIGHMEM
203 "HighMem",
204 #endif
205 "Movable",
208 int min_free_kbytes = 1024;
209 int user_min_free_kbytes;
211 static unsigned long __meminitdata nr_kernel_pages;
212 static unsigned long __meminitdata nr_all_pages;
213 static unsigned long __meminitdata dma_reserve;
215 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
216 static unsigned long __meminitdata arch_zone_lowest_possible_pfn[MAX_NR_ZONES];
217 static unsigned long __meminitdata arch_zone_highest_possible_pfn[MAX_NR_ZONES];
218 static unsigned long __initdata required_kernelcore;
219 static unsigned long __initdata required_movablecore;
220 static unsigned long __meminitdata zone_movable_pfn[MAX_NUMNODES];
222 /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
223 int movable_zone;
224 EXPORT_SYMBOL(movable_zone);
225 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
227 #if MAX_NUMNODES > 1
228 int nr_node_ids __read_mostly = MAX_NUMNODES;
229 int nr_online_nodes __read_mostly = 1;
230 EXPORT_SYMBOL(nr_node_ids);
231 EXPORT_SYMBOL(nr_online_nodes);
232 #endif
234 int page_group_by_mobility_disabled __read_mostly;
236 void set_pageblock_migratetype(struct page *page, int migratetype)
239 if (unlikely(page_group_by_mobility_disabled))
240 migratetype = MIGRATE_UNMOVABLE;
242 set_pageblock_flags_group(page, (unsigned long)migratetype,
243 PB_migrate, PB_migrate_end);
246 bool oom_killer_disabled __read_mostly;
248 #ifdef CONFIG_DEBUG_VM
249 static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
251 int ret = 0;
252 unsigned seq;
253 unsigned long pfn = page_to_pfn(page);
254 unsigned long sp, start_pfn;
256 do {
257 seq = zone_span_seqbegin(zone);
258 start_pfn = zone->zone_start_pfn;
259 sp = zone->spanned_pages;
260 if (!zone_spans_pfn(zone, pfn))
261 ret = 1;
262 } while (zone_span_seqretry(zone, seq));
264 if (ret)
265 pr_err("page %lu outside zone [ %lu - %lu ]\n",
266 pfn, start_pfn, start_pfn + sp);
268 return ret;
271 static int page_is_consistent(struct zone *zone, struct page *page)
273 if (!pfn_valid_within(page_to_pfn(page)))
274 return 0;
275 if (zone != page_zone(page))
276 return 0;
278 return 1;
281 * Temporary debugging check for pages not lying within a given zone.
283 static int bad_range(struct zone *zone, struct page *page)
285 if (page_outside_zone_boundaries(zone, page))
286 return 1;
287 if (!page_is_consistent(zone, page))
288 return 1;
290 return 0;
292 #else
293 static inline int bad_range(struct zone *zone, struct page *page)
295 return 0;
297 #endif
299 static void bad_page(struct page *page)
301 static unsigned long resume;
302 static unsigned long nr_shown;
303 static unsigned long nr_unshown;
305 /* Don't complain about poisoned pages */
306 if (PageHWPoison(page)) {
307 page_mapcount_reset(page); /* remove PageBuddy */
308 return;
312 * Allow a burst of 60 reports, then keep quiet for that minute;
313 * or allow a steady drip of one report per second.
315 if (nr_shown == 60) {
316 if (time_before(jiffies, resume)) {
317 nr_unshown++;
318 goto out;
320 if (nr_unshown) {
321 printk(KERN_ALERT
322 "BUG: Bad page state: %lu messages suppressed\n",
323 nr_unshown);
324 nr_unshown = 0;
326 nr_shown = 0;
328 if (nr_shown++ == 0)
329 resume = jiffies + 60 * HZ;
331 printk(KERN_ALERT "BUG: Bad page state in process %s pfn:%05lx\n",
332 current->comm, page_to_pfn(page));
333 dump_page(page);
335 print_modules();
336 dump_stack();
337 out:
338 /* Leave bad fields for debug, except PageBuddy could make trouble */
339 page_mapcount_reset(page); /* remove PageBuddy */
340 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
344 * Higher-order pages are called "compound pages". They are structured thusly:
346 * The first PAGE_SIZE page is called the "head page".
348 * The remaining PAGE_SIZE pages are called "tail pages".
350 * All pages have PG_compound set. All tail pages have their ->first_page
351 * pointing at the head page.
353 * The first tail page's ->lru.next holds the address of the compound page's
354 * put_page() function. Its ->lru.prev holds the order of allocation.
355 * This usage means that zero-order pages may not be compound.
358 static void free_compound_page(struct page *page)
360 __free_pages_ok(page, compound_order(page));
363 void prep_compound_page(struct page *page, unsigned long order)
365 int i;
366 int nr_pages = 1 << order;
368 set_compound_page_dtor(page, free_compound_page);
369 set_compound_order(page, order);
370 __SetPageHead(page);
371 for (i = 1; i < nr_pages; i++) {
372 struct page *p = page + i;
373 set_page_count(p, 0);
374 p->first_page = page;
375 /* Make sure p->first_page is always valid for PageTail() */
376 smp_wmb();
377 __SetPageTail(p);
381 /* update __split_huge_page_refcount if you change this function */
382 static int destroy_compound_page(struct page *page, unsigned long order)
384 int i;
385 int nr_pages = 1 << order;
386 int bad = 0;
388 if (unlikely(compound_order(page) != order)) {
389 bad_page(page);
390 bad++;
393 __ClearPageHead(page);
395 for (i = 1; i < nr_pages; i++) {
396 struct page *p = page + i;
398 if (unlikely(!PageTail(p) || (p->first_page != page))) {
399 bad_page(page);
400 bad++;
402 __ClearPageTail(p);
405 return bad;
408 static inline void prep_zero_page(struct page *page, unsigned int order,
409 gfp_t gfp_flags)
411 int i;
414 * clear_highpage() will use KM_USER0, so it's a bug to use __GFP_ZERO
415 * and __GFP_HIGHMEM from hard or soft interrupt context.
417 VM_BUG_ON((gfp_flags & __GFP_HIGHMEM) && in_interrupt());
418 for (i = 0; i < (1 << order); i++)
419 clear_highpage(page + i);
422 #ifdef CONFIG_DEBUG_PAGEALLOC
423 unsigned int _debug_guardpage_minorder;
425 static int __init debug_guardpage_minorder_setup(char *buf)
427 unsigned long res;
429 if (kstrtoul(buf, 10, &res) < 0 || res > MAX_ORDER / 2) {
430 printk(KERN_ERR "Bad debug_guardpage_minorder value\n");
431 return 0;
433 _debug_guardpage_minorder = res;
434 printk(KERN_INFO "Setting debug_guardpage_minorder to %lu\n", res);
435 return 0;
437 __setup("debug_guardpage_minorder=", debug_guardpage_minorder_setup);
439 static inline void set_page_guard_flag(struct page *page)
441 __set_bit(PAGE_DEBUG_FLAG_GUARD, &page->debug_flags);
444 static inline void clear_page_guard_flag(struct page *page)
446 __clear_bit(PAGE_DEBUG_FLAG_GUARD, &page->debug_flags);
448 #else
449 static inline void set_page_guard_flag(struct page *page) { }
450 static inline void clear_page_guard_flag(struct page *page) { }
451 #endif
453 static inline void set_page_order(struct page *page, unsigned int order)
455 set_page_private(page, order);
456 __SetPageBuddy(page);
459 static inline void rmv_page_order(struct page *page)
461 __ClearPageBuddy(page);
462 set_page_private(page, 0);
466 * Locate the struct page for both the matching buddy in our
467 * pair (buddy1) and the combined O(n+1) page they form (page).
469 * 1) Any buddy B1 will have an order O twin B2 which satisfies
470 * the following equation:
471 * B2 = B1 ^ (1 << O)
472 * For example, if the starting buddy (buddy2) is #8 its order
473 * 1 buddy is #10:
474 * B2 = 8 ^ (1 << 1) = 8 ^ 2 = 10
476 * 2) Any buddy B will have an order O+1 parent P which
477 * satisfies the following equation:
478 * P = B & ~(1 << O)
480 * Assumption: *_mem_map is contiguous at least up to MAX_ORDER
482 static inline unsigned long
483 __find_buddy_index(unsigned long page_idx, unsigned int order)
485 return page_idx ^ (1 << order);
489 * This function checks whether a page is free && is the buddy
490 * we can do coalesce a page and its buddy if
491 * (a) the buddy is not in a hole &&
492 * (b) the buddy is in the buddy system &&
493 * (c) a page and its buddy have the same order &&
494 * (d) a page and its buddy are in the same zone.
496 * For recording whether a page is in the buddy system, we set ->_mapcount
497 * PAGE_BUDDY_MAPCOUNT_VALUE.
498 * Setting, clearing, and testing _mapcount PAGE_BUDDY_MAPCOUNT_VALUE is
499 * serialized by zone->lock.
501 * For recording page's order, we use page_private(page).
503 static inline int page_is_buddy(struct page *page, struct page *buddy,
504 unsigned int order)
506 if (!pfn_valid_within(page_to_pfn(buddy)))
507 return 0;
509 if (page_is_guard(buddy) && page_order(buddy) == order) {
510 VM_BUG_ON(page_count(buddy) != 0);
512 if (page_zone_id(page) != page_zone_id(buddy))
513 return 0;
515 return 1;
518 if (PageBuddy(buddy) && page_order(buddy) == order) {
519 VM_BUG_ON(page_count(buddy) != 0);
522 * zone check is done late to avoid uselessly
523 * calculating zone/node ids for pages that could
524 * never merge.
526 if (page_zone_id(page) != page_zone_id(buddy))
527 return 0;
529 return 1;
531 return 0;
535 * Freeing function for a buddy system allocator.
537 * The concept of a buddy system is to maintain direct-mapped table
538 * (containing bit values) for memory blocks of various "orders".
539 * The bottom level table contains the map for the smallest allocatable
540 * units of memory (here, pages), and each level above it describes
541 * pairs of units from the levels below, hence, "buddies".
542 * At a high level, all that happens here is marking the table entry
543 * at the bottom level available, and propagating the changes upward
544 * as necessary, plus some accounting needed to play nicely with other
545 * parts of the VM system.
546 * At each level, we keep a list of pages, which are heads of continuous
547 * free pages of length of (1 << order) and marked with _mapcount
548 * PAGE_BUDDY_MAPCOUNT_VALUE. Page's order is recorded in page_private(page)
549 * field.
550 * So when we are allocating or freeing one, we can derive the state of the
551 * other. That is, if we allocate a small block, and both were
552 * free, the remainder of the region must be split into blocks.
553 * If a block is freed, and its buddy is also free, then this
554 * triggers coalescing into a block of larger size.
556 * -- nyc
559 static inline void __free_one_page(struct page *page,
560 unsigned long pfn,
561 struct zone *zone, unsigned int order,
562 int migratetype)
564 unsigned long page_idx;
565 unsigned long combined_idx;
566 unsigned long uninitialized_var(buddy_idx);
567 struct page *buddy;
569 VM_BUG_ON(!zone_is_initialized(zone));
571 if (unlikely(PageCompound(page)))
572 if (unlikely(destroy_compound_page(page, order)))
573 return;
575 VM_BUG_ON(migratetype == -1);
577 page_idx = pfn & ((1 << MAX_ORDER) - 1);
579 VM_BUG_ON(page_idx & ((1 << order) - 1));
580 VM_BUG_ON(bad_range(zone, page));
582 while (order < MAX_ORDER-1) {
583 buddy_idx = __find_buddy_index(page_idx, order);
584 buddy = page + (buddy_idx - page_idx);
585 if (!page_is_buddy(page, buddy, order))
586 break;
588 * Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page,
589 * merge with it and move up one order.
591 if (page_is_guard(buddy)) {
592 clear_page_guard_flag(buddy);
593 set_page_private(page, 0);
594 __mod_zone_freepage_state(zone, 1 << order,
595 migratetype);
596 } else {
597 list_del(&buddy->lru);
598 zone->free_area[order].nr_free--;
599 rmv_page_order(buddy);
601 combined_idx = buddy_idx & page_idx;
602 page = page + (combined_idx - page_idx);
603 page_idx = combined_idx;
604 order++;
606 set_page_order(page, order);
609 * If this is not the largest possible page, check if the buddy
610 * of the next-highest order is free. If it is, it's possible
611 * that pages are being freed that will coalesce soon. In case,
612 * that is happening, add the free page to the tail of the list
613 * so it's less likely to be used soon and more likely to be merged
614 * as a higher order page
616 if ((order < MAX_ORDER-2) && pfn_valid_within(page_to_pfn(buddy))) {
617 struct page *higher_page, *higher_buddy;
618 combined_idx = buddy_idx & page_idx;
619 higher_page = page + (combined_idx - page_idx);
620 buddy_idx = __find_buddy_index(combined_idx, order + 1);
621 higher_buddy = higher_page + (buddy_idx - combined_idx);
622 if (page_is_buddy(higher_page, higher_buddy, order + 1)) {
623 list_add_tail(&page->lru,
624 &zone->free_area[order].free_list[migratetype]);
625 goto out;
629 list_add(&page->lru, &zone->free_area[order].free_list[migratetype]);
630 out:
631 zone->free_area[order].nr_free++;
634 static inline int free_pages_check(struct page *page)
636 if (unlikely(page_mapcount(page) |
637 (page->mapping != NULL) |
638 (atomic_read(&page->_count) != 0) |
639 (page->flags & PAGE_FLAGS_CHECK_AT_FREE) |
640 (mem_cgroup_bad_page_check(page)))) {
641 bad_page(page);
642 return 1;
644 page_nid_reset_last(page);
645 if (page->flags & PAGE_FLAGS_CHECK_AT_PREP)
646 page->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
647 return 0;
651 * Frees a number of pages from the PCP lists
652 * Assumes all pages on list are in same zone, and of same order.
653 * count is the number of pages to free.
655 * If the zone was previously in an "all pages pinned" state then look to
656 * see if this freeing clears that state.
658 * And clear the zone's pages_scanned counter, to hold off the "all pages are
659 * pinned" detection logic.
661 static void free_pcppages_bulk(struct zone *zone, int count,
662 struct per_cpu_pages *pcp)
664 int migratetype = 0;
665 int batch_free = 0;
666 int to_free = count;
667 unsigned long nr_scanned;
669 spin_lock(&zone->lock);
670 nr_scanned = zone_page_state(zone, NR_PAGES_SCANNED);
671 if (nr_scanned)
672 __mod_zone_page_state(zone, NR_PAGES_SCANNED, -nr_scanned);
674 while (to_free) {
675 struct page *page;
676 struct list_head *list;
679 * Remove pages from lists in a round-robin fashion. A
680 * batch_free count is maintained that is incremented when an
681 * empty list is encountered. This is so more pages are freed
682 * off fuller lists instead of spinning excessively around empty
683 * lists
685 do {
686 batch_free++;
687 if (++migratetype == MIGRATE_PCPTYPES)
688 migratetype = 0;
689 list = &pcp->lists[migratetype];
690 } while (list_empty(list));
692 /* This is the only non-empty list. Free them all. */
693 if (batch_free == MIGRATE_PCPTYPES)
694 batch_free = to_free;
696 do {
697 int mt; /* migratetype of the to-be-freed page */
699 page = list_entry(list->prev, struct page, lru);
700 /* must delete as __free_one_page list manipulates */
701 list_del(&page->lru);
702 mt = get_freepage_migratetype(page);
703 /* MIGRATE_MOVABLE list may include MIGRATE_RESERVEs */
704 __free_one_page(page, page_to_pfn(page), zone, 0, mt);
705 trace_mm_page_pcpu_drain(page, 0, mt);
706 if (likely(!is_migrate_isolate_page(page))) {
707 __mod_zone_page_state(zone, NR_FREE_PAGES, 1);
708 if (is_migrate_cma(mt))
709 __mod_zone_page_state(zone, NR_FREE_CMA_PAGES, 1);
711 } while (--to_free && --batch_free && !list_empty(list));
713 spin_unlock(&zone->lock);
716 static void free_one_page(struct zone *zone,
717 struct page *page, unsigned long pfn,
718 unsigned int order,
719 int migratetype)
721 unsigned long nr_scanned;
722 spin_lock(&zone->lock);
723 nr_scanned = zone_page_state(zone, NR_PAGES_SCANNED);
724 if (nr_scanned)
725 __mod_zone_page_state(zone, NR_PAGES_SCANNED, -nr_scanned);
727 __free_one_page(page, pfn, zone, order, migratetype);
728 if (unlikely(!is_migrate_isolate(migratetype)))
729 __mod_zone_freepage_state(zone, 1 << order, migratetype);
730 spin_unlock(&zone->lock);
733 static bool free_pages_prepare(struct page *page, unsigned int order)
735 int i;
736 int bad = 0;
738 trace_mm_page_free(page, order);
739 kmemcheck_free_shadow(page, order);
741 if (PageAnon(page))
742 page->mapping = NULL;
743 for (i = 0; i < (1 << order); i++)
744 bad += free_pages_check(page + i);
745 if (bad)
746 return false;
748 if (!PageHighMem(page)) {
749 debug_check_no_locks_freed(page_address(page),
750 PAGE_SIZE << order);
751 debug_check_no_obj_freed(page_address(page),
752 PAGE_SIZE << order);
754 arch_free_page(page, order);
755 kernel_map_pages(page, 1 << order, 0);
757 return true;
760 static void __free_pages_ok(struct page *page, unsigned int order)
762 unsigned long flags;
763 int migratetype;
764 unsigned long pfn = page_to_pfn(page);
766 if (!free_pages_prepare(page, order))
767 return;
769 migratetype = get_pfnblock_migratetype(page, pfn);
770 local_irq_save(flags);
771 __count_vm_events(PGFREE, 1 << order);
772 set_freepage_migratetype(page, migratetype);
773 free_one_page(page_zone(page), page, pfn, order, migratetype);
774 local_irq_restore(flags);
777 void __init __free_pages_bootmem(struct page *page, unsigned int order)
779 unsigned int nr_pages = 1 << order;
780 struct page *p = page;
781 unsigned int loop;
783 prefetchw(p);
784 for (loop = 0; loop < (nr_pages - 1); loop++, p++) {
785 prefetchw(p + 1);
786 __ClearPageReserved(p);
787 set_page_count(p, 0);
789 __ClearPageReserved(p);
790 set_page_count(p, 0);
792 page_zone(page)->managed_pages += nr_pages;
793 set_page_refcounted(page);
794 __free_pages(page, order);
797 #ifdef CONFIG_CMA
798 /* Free whole pageblock and set its migration type to MIGRATE_CMA. */
799 void __init init_cma_reserved_pageblock(struct page *page)
801 unsigned i = pageblock_nr_pages;
802 struct page *p = page;
804 do {
805 __ClearPageReserved(p);
806 set_page_count(p, 0);
807 } while (++p, --i);
809 set_pageblock_migratetype(page, MIGRATE_CMA);
811 if (pageblock_order >= MAX_ORDER) {
812 i = pageblock_nr_pages;
813 p = page;
814 do {
815 set_page_refcounted(p);
816 __free_pages(p, MAX_ORDER - 1);
817 p += MAX_ORDER_NR_PAGES;
818 } while (i -= MAX_ORDER_NR_PAGES);
819 } else {
820 set_page_refcounted(page);
821 __free_pages(page, pageblock_order);
824 adjust_managed_page_count(page, pageblock_nr_pages);
826 #endif
829 * The order of subdivision here is critical for the IO subsystem.
830 * Please do not alter this order without good reasons and regression
831 * testing. Specifically, as large blocks of memory are subdivided,
832 * the order in which smaller blocks are delivered depends on the order
833 * they're subdivided in this function. This is the primary factor
834 * influencing the order in which pages are delivered to the IO
835 * subsystem according to empirical testing, and this is also justified
836 * by considering the behavior of a buddy system containing a single
837 * large block of memory acted on by a series of small allocations.
838 * This behavior is a critical factor in sglist merging's success.
840 * -- nyc
842 static inline void expand(struct zone *zone, struct page *page,
843 int low, int high, struct free_area *area,
844 int migratetype)
846 unsigned long size = 1 << high;
848 while (high > low) {
849 area--;
850 high--;
851 size >>= 1;
852 VM_BUG_ON(bad_range(zone, &page[size]));
854 #ifdef CONFIG_DEBUG_PAGEALLOC
855 if (high < debug_guardpage_minorder()) {
857 * Mark as guard pages (or page), that will allow to
858 * merge back to allocator when buddy will be freed.
859 * Corresponding page table entries will not be touched,
860 * pages will stay not present in virtual address space
862 INIT_LIST_HEAD(&page[size].lru);
863 set_page_guard_flag(&page[size]);
864 set_page_private(&page[size], high);
865 /* Guard pages are not available for any usage */
866 __mod_zone_freepage_state(zone, -(1 << high),
867 migratetype);
868 continue;
870 #endif
871 list_add(&page[size].lru, &area->free_list[migratetype]);
872 area->nr_free++;
873 set_page_order(&page[size], high);
878 * This page is about to be returned from the page allocator
880 static inline int check_new_page(struct page *page)
882 if (unlikely(page_mapcount(page) |
883 (page->mapping != NULL) |
884 (atomic_read(&page->_count) != 0) |
885 (page->flags & PAGE_FLAGS_CHECK_AT_PREP) |
886 (mem_cgroup_bad_page_check(page)))) {
887 bad_page(page);
888 return 1;
890 return 0;
893 static int prep_new_page(struct page *page, unsigned int order, gfp_t gfp_flags)
895 int i;
897 for (i = 0; i < (1 << order); i++) {
898 struct page *p = page + i;
899 if (unlikely(check_new_page(p)))
900 return 1;
903 set_page_private(page, 0);
904 set_page_refcounted(page);
906 arch_alloc_page(page, order);
907 kernel_map_pages(page, 1 << order, 1);
909 if (gfp_flags & __GFP_ZERO)
910 prep_zero_page(page, order, gfp_flags);
912 if (order && (gfp_flags & __GFP_COMP))
913 prep_compound_page(page, order);
915 return 0;
919 * Go through the free lists for the given migratetype and remove
920 * the smallest available page from the freelists
922 static inline
923 struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
924 int migratetype)
926 unsigned int current_order;
927 struct free_area *area;
928 struct page *page;
930 /* Find a page of the appropriate size in the preferred list */
931 for (current_order = order; current_order < MAX_ORDER; ++current_order) {
932 area = &(zone->free_area[current_order]);
933 if (list_empty(&area->free_list[migratetype]))
934 continue;
936 page = list_entry(area->free_list[migratetype].next,
937 struct page, lru);
938 list_del(&page->lru);
939 rmv_page_order(page);
940 area->nr_free--;
941 expand(zone, page, order, current_order, area, migratetype);
942 set_freepage_migratetype(page, migratetype);
943 return page;
946 return NULL;
951 * This array describes the order lists are fallen back to when
952 * the free lists for the desirable migrate type are depleted
954 static int fallbacks[MIGRATE_TYPES][4] = {
955 [MIGRATE_UNMOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE, MIGRATE_RESERVE },
956 [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE, MIGRATE_MOVABLE, MIGRATE_RESERVE },
957 #ifdef CONFIG_CMA
958 [MIGRATE_MOVABLE] = { MIGRATE_CMA, MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_RESERVE },
959 [MIGRATE_CMA] = { MIGRATE_RESERVE }, /* Never used */
960 #else
961 [MIGRATE_MOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_RESERVE },
962 #endif
963 [MIGRATE_RESERVE] = { MIGRATE_RESERVE }, /* Never used */
964 #ifdef CONFIG_MEMORY_ISOLATION
965 [MIGRATE_ISOLATE] = { MIGRATE_RESERVE }, /* Never used */
966 #endif
970 * Move the free pages in a range to the free lists of the requested type.
971 * Note that start_page and end_pages are not aligned on a pageblock
972 * boundary. If alignment is required, use move_freepages_block()
974 int move_freepages(struct zone *zone,
975 struct page *start_page, struct page *end_page,
976 int migratetype)
978 struct page *page;
979 unsigned long order;
980 int pages_moved = 0;
982 #ifndef CONFIG_HOLES_IN_ZONE
984 * page_zone is not safe to call in this context when
985 * CONFIG_HOLES_IN_ZONE is set. This bug check is probably redundant
986 * anyway as we check zone boundaries in move_freepages_block().
987 * Remove at a later date when no bug reports exist related to
988 * grouping pages by mobility
990 BUG_ON(page_zone(start_page) != page_zone(end_page));
991 #endif
993 for (page = start_page; page <= end_page;) {
994 /* Make sure we are not inadvertently changing nodes */
995 VM_BUG_ON(page_to_nid(page) != zone_to_nid(zone));
997 if (!pfn_valid_within(page_to_pfn(page))) {
998 page++;
999 continue;
1002 if (!PageBuddy(page)) {
1003 page++;
1004 continue;
1007 order = page_order(page);
1008 list_move(&page->lru,
1009 &zone->free_area[order].free_list[migratetype]);
1010 set_freepage_migratetype(page, migratetype);
1011 page += 1 << order;
1012 pages_moved += 1 << order;
1015 return pages_moved;
1018 int move_freepages_block(struct zone *zone, struct page *page,
1019 int migratetype)
1021 unsigned long start_pfn, end_pfn;
1022 struct page *start_page, *end_page;
1024 start_pfn = page_to_pfn(page);
1025 start_pfn = start_pfn & ~(pageblock_nr_pages-1);
1026 start_page = pfn_to_page(start_pfn);
1027 end_page = start_page + pageblock_nr_pages - 1;
1028 end_pfn = start_pfn + pageblock_nr_pages - 1;
1030 /* Do not cross zone boundaries */
1031 if (!zone_spans_pfn(zone, start_pfn))
1032 start_page = page;
1033 if (!zone_spans_pfn(zone, end_pfn))
1034 return 0;
1036 return move_freepages(zone, start_page, end_page, migratetype);
1039 static void change_pageblock_range(struct page *pageblock_page,
1040 int start_order, int migratetype)
1042 int nr_pageblocks = 1 << (start_order - pageblock_order);
1044 while (nr_pageblocks--) {
1045 set_pageblock_migratetype(pageblock_page, migratetype);
1046 pageblock_page += pageblock_nr_pages;
1051 * If breaking a large block of pages, move all free pages to the preferred
1052 * allocation list. If falling back for a reclaimable kernel allocation, be
1053 * more aggressive about taking ownership of free pages.
1055 * On the other hand, never change migration type of MIGRATE_CMA pageblocks
1056 * nor move CMA pages to different free lists. We don't want unmovable pages
1057 * to be allocated from MIGRATE_CMA areas.
1059 * Returns the new migratetype of the pageblock (or the same old migratetype
1060 * if it was unchanged).
1062 static int try_to_steal_freepages(struct zone *zone, struct page *page,
1063 int start_type, int fallback_type)
1065 int current_order = page_order(page);
1068 * When borrowing from MIGRATE_CMA, we need to release the excess
1069 * buddy pages to CMA itself. We also ensure the freepage_migratetype
1070 * is set to CMA so it is returned to the correct freelist in case
1071 * the page ends up being not actually allocated from the pcp lists.
1073 if (is_migrate_cma(fallback_type))
1074 return fallback_type;
1076 /* Take ownership for orders >= pageblock_order */
1077 if (current_order >= pageblock_order) {
1078 change_pageblock_range(page, current_order, start_type);
1079 return start_type;
1082 if (current_order >= pageblock_order / 2 ||
1083 start_type == MIGRATE_RECLAIMABLE ||
1084 page_group_by_mobility_disabled) {
1085 int pages;
1087 pages = move_freepages_block(zone, page, start_type);
1089 /* Claim the whole block if over half of it is free */
1090 if (pages >= (1 << (pageblock_order-1)) ||
1091 page_group_by_mobility_disabled) {
1093 set_pageblock_migratetype(page, start_type);
1094 return start_type;
1099 return fallback_type;
1102 /* Remove an element from the buddy allocator from the fallback list */
1103 static inline struct page *
1104 __rmqueue_fallback(struct zone *zone, unsigned int order, int start_migratetype)
1106 struct free_area *area;
1107 unsigned int current_order;
1108 struct page *page;
1109 int migratetype, new_type, i;
1111 /* Find the largest possible block of pages in the other list */
1112 for (current_order = MAX_ORDER-1;
1113 current_order >= order && current_order <= MAX_ORDER-1;
1114 --current_order) {
1115 for (i = 0;; i++) {
1116 migratetype = fallbacks[start_migratetype][i];
1118 /* MIGRATE_RESERVE handled later if necessary */
1119 if (migratetype == MIGRATE_RESERVE)
1120 break;
1122 area = &(zone->free_area[current_order]);
1123 if (list_empty(&area->free_list[migratetype]))
1124 continue;
1126 page = list_entry(area->free_list[migratetype].next,
1127 struct page, lru);
1128 area->nr_free--;
1130 new_type = try_to_steal_freepages(zone, page,
1131 start_migratetype,
1132 migratetype);
1134 /* Remove the page from the freelists */
1135 list_del(&page->lru);
1136 rmv_page_order(page);
1138 expand(zone, page, order, current_order, area,
1139 new_type);
1140 /* The freepage_migratetype may differ from pageblock's
1141 * migratetype depending on the decisions in
1142 * try_to_steal_freepages. This is OK as long as it does
1143 * not differ for MIGRATE_CMA type.
1145 set_freepage_migratetype(page, new_type);
1147 trace_mm_page_alloc_extfrag(page, order, current_order,
1148 start_migratetype, migratetype, new_type);
1150 return page;
1154 return NULL;
1158 * Do the hard work of removing an element from the buddy allocator.
1159 * Call me with the zone->lock already held.
1161 static struct page *__rmqueue(struct zone *zone, unsigned int order,
1162 int migratetype)
1164 struct page *page;
1166 retry_reserve:
1167 page = __rmqueue_smallest(zone, order, migratetype);
1169 if (unlikely(!page) && migratetype != MIGRATE_RESERVE) {
1170 page = __rmqueue_fallback(zone, order, migratetype);
1173 * Use MIGRATE_RESERVE rather than fail an allocation. goto
1174 * is used because __rmqueue_smallest is an inline function
1175 * and we want just one call site
1177 if (!page) {
1178 migratetype = MIGRATE_RESERVE;
1179 goto retry_reserve;
1183 trace_mm_page_alloc_zone_locked(page, order, migratetype);
1184 return page;
1188 * Obtain a specified number of elements from the buddy allocator, all under
1189 * a single hold of the lock, for efficiency. Add them to the supplied list.
1190 * Returns the number of new pages which were placed at *list.
1192 static int rmqueue_bulk(struct zone *zone, unsigned int order,
1193 unsigned long count, struct list_head *list,
1194 int migratetype, bool cold)
1196 int i;
1198 spin_lock(&zone->lock);
1199 for (i = 0; i < count; ++i) {
1200 struct page *page = __rmqueue(zone, order, migratetype);
1201 if (unlikely(page == NULL))
1202 break;
1205 * Split buddy pages returned by expand() are received here
1206 * in physical page order. The page is added to the callers and
1207 * list and the list head then moves forward. From the callers
1208 * perspective, the linked list is ordered by page number in
1209 * some conditions. This is useful for IO devices that can
1210 * merge IO requests if the physical pages are ordered
1211 * properly.
1213 if (likely(!cold))
1214 list_add(&page->lru, list);
1215 else
1216 list_add_tail(&page->lru, list);
1217 list = &page->lru;
1218 if (is_migrate_cma(get_freepage_migratetype(page)))
1219 __mod_zone_page_state(zone, NR_FREE_CMA_PAGES,
1220 -(1 << order));
1222 __mod_zone_page_state(zone, NR_FREE_PAGES, -(i << order));
1223 spin_unlock(&zone->lock);
1224 return i;
1227 #ifdef CONFIG_NUMA
1229 * Called from the vmstat counter updater to drain pagesets of this
1230 * currently executing processor on remote nodes after they have
1231 * expired.
1233 * Note that this function must be called with the thread pinned to
1234 * a single processor.
1236 void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp)
1238 unsigned long flags;
1239 int to_drain;
1240 unsigned long batch;
1242 local_irq_save(flags);
1243 batch = ACCESS_ONCE(pcp->batch);
1244 if (pcp->count >= batch)
1245 to_drain = batch;
1246 else
1247 to_drain = pcp->count;
1248 if (to_drain > 0) {
1249 free_pcppages_bulk(zone, to_drain, pcp);
1250 pcp->count -= to_drain;
1252 local_irq_restore(flags);
1254 #endif
1257 * Drain pages of the indicated processor.
1259 * The processor must either be the current processor and the
1260 * thread pinned to the current processor or a processor that
1261 * is not online.
1263 static void drain_pages(unsigned int cpu)
1265 unsigned long flags;
1266 struct zone *zone;
1268 for_each_populated_zone(zone) {
1269 struct per_cpu_pageset *pset;
1270 struct per_cpu_pages *pcp;
1272 local_irq_save(flags);
1273 pset = per_cpu_ptr(zone->pageset, cpu);
1275 pcp = &pset->pcp;
1276 if (pcp->count) {
1277 free_pcppages_bulk(zone, pcp->count, pcp);
1278 pcp->count = 0;
1280 local_irq_restore(flags);
1285 * Spill all of this CPU's per-cpu pages back into the buddy allocator.
1287 void drain_local_pages(void *arg)
1289 drain_pages(smp_processor_id());
1293 * Spill all the per-cpu pages from all CPUs back into the buddy allocator.
1295 * Note that this code is protected against sending an IPI to an offline
1296 * CPU but does not guarantee sending an IPI to newly hotplugged CPUs:
1297 * on_each_cpu_mask() blocks hotplug and won't talk to offlined CPUs but
1298 * nothing keeps CPUs from showing up after we populated the cpumask and
1299 * before the call to on_each_cpu_mask().
1301 void drain_all_pages(void)
1303 int cpu;
1304 struct per_cpu_pageset *pcp;
1305 struct zone *zone;
1308 * Allocate in the BSS so we wont require allocation in
1309 * direct reclaim path for CONFIG_CPUMASK_OFFSTACK=y
1311 static cpumask_t cpus_with_pcps;
1314 * We don't care about racing with CPU hotplug event
1315 * as offline notification will cause the notified
1316 * cpu to drain that CPU pcps and on_each_cpu_mask
1317 * disables preemption as part of its processing
1319 for_each_online_cpu(cpu) {
1320 bool has_pcps = false;
1321 for_each_populated_zone(zone) {
1322 pcp = per_cpu_ptr(zone->pageset, cpu);
1323 if (pcp->pcp.count) {
1324 has_pcps = true;
1325 break;
1328 if (has_pcps)
1329 cpumask_set_cpu(cpu, &cpus_with_pcps);
1330 else
1331 cpumask_clear_cpu(cpu, &cpus_with_pcps);
1333 on_each_cpu_mask(&cpus_with_pcps, drain_local_pages, NULL, 1);
1336 #ifdef CONFIG_HIBERNATION
1338 void mark_free_pages(struct zone *zone)
1340 unsigned long pfn, max_zone_pfn;
1341 unsigned long flags;
1342 unsigned int order, t;
1343 struct list_head *curr;
1345 if (zone_is_empty(zone))
1346 return;
1348 spin_lock_irqsave(&zone->lock, flags);
1350 max_zone_pfn = zone_end_pfn(zone);
1351 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
1352 if (pfn_valid(pfn)) {
1353 struct page *page = pfn_to_page(pfn);
1355 if (!swsusp_page_is_forbidden(page))
1356 swsusp_unset_page_free(page);
1359 for_each_migratetype_order(order, t) {
1360 list_for_each(curr, &zone->free_area[order].free_list[t]) {
1361 unsigned long i;
1363 pfn = page_to_pfn(list_entry(curr, struct page, lru));
1364 for (i = 0; i < (1UL << order); i++)
1365 swsusp_set_page_free(pfn_to_page(pfn + i));
1368 spin_unlock_irqrestore(&zone->lock, flags);
1370 #endif /* CONFIG_PM */
1373 * Free a 0-order page
1374 * cold == true ? free a cold page : free a hot page
1376 void free_hot_cold_page(struct page *page, bool cold)
1378 struct zone *zone = page_zone(page);
1379 struct per_cpu_pages *pcp;
1380 unsigned long flags;
1381 unsigned long pfn = page_to_pfn(page);
1382 int migratetype;
1384 if (!free_pages_prepare(page, 0))
1385 return;
1387 migratetype = get_pfnblock_migratetype(page, pfn);
1388 set_freepage_migratetype(page, migratetype);
1389 local_irq_save(flags);
1390 __count_vm_event(PGFREE);
1393 * We only track unmovable, reclaimable and movable on pcp lists.
1394 * Free ISOLATE pages back to the allocator because they are being
1395 * offlined but treat RESERVE as movable pages so we can get those
1396 * areas back if necessary. Otherwise, we may have to free
1397 * excessively into the page allocator
1399 if (migratetype >= MIGRATE_PCPTYPES) {
1400 if (unlikely(is_migrate_isolate(migratetype))) {
1401 free_one_page(zone, page, pfn, 0, migratetype);
1402 goto out;
1404 migratetype = MIGRATE_MOVABLE;
1407 pcp = &this_cpu_ptr(zone->pageset)->pcp;
1408 if (!cold)
1409 list_add(&page->lru, &pcp->lists[migratetype]);
1410 else
1411 list_add_tail(&page->lru, &pcp->lists[migratetype]);
1412 pcp->count++;
1413 if (pcp->count >= pcp->high) {
1414 unsigned long batch = ACCESS_ONCE(pcp->batch);
1415 free_pcppages_bulk(zone, batch, pcp);
1416 pcp->count -= batch;
1419 out:
1420 local_irq_restore(flags);
1424 * Free a list of 0-order pages
1426 void free_hot_cold_page_list(struct list_head *list, bool cold)
1428 struct page *page, *next;
1430 list_for_each_entry_safe(page, next, list, lru) {
1431 trace_mm_page_free_batched(page, cold);
1432 free_hot_cold_page(page, cold);
1437 * split_page takes a non-compound higher-order page, and splits it into
1438 * n (1<<order) sub-pages: page[0..n]
1439 * Each sub-page must be freed individually.
1441 * Note: this is probably too low level an operation for use in drivers.
1442 * Please consult with lkml before using this in your driver.
1444 void split_page(struct page *page, unsigned int order)
1446 int i;
1448 VM_BUG_ON(PageCompound(page));
1449 VM_BUG_ON(!page_count(page));
1451 #ifdef CONFIG_KMEMCHECK
1453 * Split shadow pages too, because free(page[0]) would
1454 * otherwise free the whole shadow.
1456 if (kmemcheck_page_is_tracked(page))
1457 split_page(virt_to_page(page[0].shadow), order);
1458 #endif
1460 for (i = 1; i < (1 << order); i++)
1461 set_page_refcounted(page + i);
1463 EXPORT_SYMBOL_GPL(split_page);
1465 static int __isolate_free_page(struct page *page, unsigned int order)
1467 unsigned long watermark;
1468 struct zone *zone;
1469 int mt;
1471 BUG_ON(!PageBuddy(page));
1473 zone = page_zone(page);
1474 mt = get_pageblock_migratetype(page);
1476 if (!is_migrate_isolate(mt)) {
1477 /* Obey watermarks as if the page was being allocated */
1478 watermark = low_wmark_pages(zone) + (1 << order);
1479 if (!zone_watermark_ok(zone, 0, watermark, 0, 0))
1480 return 0;
1482 __mod_zone_freepage_state(zone, -(1UL << order), mt);
1485 /* Remove page from free list */
1486 list_del(&page->lru);
1487 zone->free_area[order].nr_free--;
1488 rmv_page_order(page);
1490 /* Set the pageblock if the isolated page is at least a pageblock */
1491 if (order >= pageblock_order - 1) {
1492 struct page *endpage = page + (1 << order) - 1;
1493 for (; page < endpage; page += pageblock_nr_pages) {
1494 int mt = get_pageblock_migratetype(page);
1495 if (!is_migrate_isolate(mt) && !is_migrate_cma(mt))
1496 set_pageblock_migratetype(page,
1497 MIGRATE_MOVABLE);
1501 return 1UL << order;
1505 * Similar to split_page except the page is already free. As this is only
1506 * being used for migration, the migratetype of the block also changes.
1507 * As this is called with interrupts disabled, the caller is responsible
1508 * for calling arch_alloc_page() and kernel_map_page() after interrupts
1509 * are enabled.
1511 * Note: this is probably too low level an operation for use in drivers.
1512 * Please consult with lkml before using this in your driver.
1514 int split_free_page(struct page *page)
1516 unsigned int order;
1517 int nr_pages;
1519 order = page_order(page);
1521 nr_pages = __isolate_free_page(page, order);
1522 if (!nr_pages)
1523 return 0;
1525 /* Split into individual pages */
1526 set_page_refcounted(page);
1527 split_page(page, order);
1528 return nr_pages;
1532 * Really, prep_compound_page() should be called from __rmqueue_bulk(). But
1533 * we cheat by calling it from here, in the order > 0 path. Saves a branch
1534 * or two.
1536 static inline
1537 struct page *buffered_rmqueue(struct zone *preferred_zone,
1538 struct zone *zone, unsigned int order,
1539 gfp_t gfp_flags, int migratetype)
1541 unsigned long flags;
1542 struct page *page;
1543 bool cold = ((gfp_flags & __GFP_COLD) != 0);
1545 again:
1546 if (likely(order == 0)) {
1547 struct per_cpu_pages *pcp;
1548 struct list_head *list;
1550 local_irq_save(flags);
1551 pcp = &this_cpu_ptr(zone->pageset)->pcp;
1552 list = &pcp->lists[migratetype];
1553 if (list_empty(list)) {
1554 pcp->count += rmqueue_bulk(zone, 0,
1555 pcp->batch, list,
1556 migratetype, cold);
1557 if (unlikely(list_empty(list)))
1558 goto failed;
1561 if (cold)
1562 page = list_entry(list->prev, struct page, lru);
1563 else
1564 page = list_entry(list->next, struct page, lru);
1566 list_del(&page->lru);
1567 pcp->count--;
1568 } else {
1569 if (unlikely(gfp_flags & __GFP_NOFAIL)) {
1571 * __GFP_NOFAIL is not to be used in new code.
1573 * All __GFP_NOFAIL callers should be fixed so that they
1574 * properly detect and handle allocation failures.
1576 * We most definitely don't want callers attempting to
1577 * allocate greater than order-1 page units with
1578 * __GFP_NOFAIL.
1580 WARN_ON_ONCE(order > 1);
1582 spin_lock_irqsave(&zone->lock, flags);
1583 page = __rmqueue(zone, order, migratetype);
1584 spin_unlock(&zone->lock);
1585 if (!page)
1586 goto failed;
1587 __mod_zone_freepage_state(zone, -(1 << order),
1588 get_freepage_migratetype(page));
1591 __mod_zone_page_state(zone, NR_ALLOC_BATCH, -(1 << order));
1592 if (atomic_long_read(&zone->vm_stat[NR_ALLOC_BATCH]) <= 0 &&
1593 !zone_is_fair_depleted(zone))
1594 zone_set_flag(zone, ZONE_FAIR_DEPLETED);
1596 __count_zone_vm_events(PGALLOC, zone, 1 << order);
1597 zone_statistics(preferred_zone, zone, gfp_flags);
1598 local_irq_restore(flags);
1600 VM_BUG_ON(bad_range(zone, page));
1601 if (prep_new_page(page, order, gfp_flags))
1602 goto again;
1603 return page;
1605 failed:
1606 local_irq_restore(flags);
1607 return NULL;
1610 #ifdef CONFIG_FAIL_PAGE_ALLOC
1612 static struct {
1613 struct fault_attr attr;
1615 u32 ignore_gfp_highmem;
1616 u32 ignore_gfp_wait;
1617 u32 min_order;
1618 } fail_page_alloc = {
1619 .attr = FAULT_ATTR_INITIALIZER,
1620 .ignore_gfp_wait = 1,
1621 .ignore_gfp_highmem = 1,
1622 .min_order = 1,
1625 static int __init setup_fail_page_alloc(char *str)
1627 return setup_fault_attr(&fail_page_alloc.attr, str);
1629 __setup("fail_page_alloc=", setup_fail_page_alloc);
1631 static bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
1633 if (order < fail_page_alloc.min_order)
1634 return false;
1635 if (gfp_mask & __GFP_NOFAIL)
1636 return false;
1637 if (fail_page_alloc.ignore_gfp_highmem && (gfp_mask & __GFP_HIGHMEM))
1638 return false;
1639 if (fail_page_alloc.ignore_gfp_wait && (gfp_mask & __GFP_WAIT))
1640 return false;
1642 return should_fail(&fail_page_alloc.attr, 1 << order);
1645 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
1647 static int __init fail_page_alloc_debugfs(void)
1649 umode_t mode = S_IFREG | S_IRUSR | S_IWUSR;
1650 struct dentry *dir;
1652 dir = fault_create_debugfs_attr("fail_page_alloc", NULL,
1653 &fail_page_alloc.attr);
1654 if (IS_ERR(dir))
1655 return PTR_ERR(dir);
1657 if (!debugfs_create_bool("ignore-gfp-wait", mode, dir,
1658 &fail_page_alloc.ignore_gfp_wait))
1659 goto fail;
1660 if (!debugfs_create_bool("ignore-gfp-highmem", mode, dir,
1661 &fail_page_alloc.ignore_gfp_highmem))
1662 goto fail;
1663 if (!debugfs_create_u32("min-order", mode, dir,
1664 &fail_page_alloc.min_order))
1665 goto fail;
1667 return 0;
1668 fail:
1669 debugfs_remove_recursive(dir);
1671 return -ENOMEM;
1674 late_initcall(fail_page_alloc_debugfs);
1676 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
1678 #else /* CONFIG_FAIL_PAGE_ALLOC */
1680 static inline bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
1682 return false;
1685 #endif /* CONFIG_FAIL_PAGE_ALLOC */
1688 * Return true if free pages are above 'mark'. This takes into account the order
1689 * of the allocation.
1691 static bool __zone_watermark_ok(struct zone *z, unsigned int order,
1692 unsigned long mark, int classzone_idx, int alloc_flags,
1693 long free_pages)
1695 /* free_pages my go negative - that's OK */
1696 long min = mark;
1697 int o;
1698 long free_cma = 0;
1700 free_pages -= (1 << order) - 1;
1701 if (alloc_flags & ALLOC_HIGH)
1702 min -= min / 2;
1703 if (alloc_flags & ALLOC_HARDER)
1704 min -= min / 4;
1705 #ifdef CONFIG_CMA
1706 /* If allocation can't use CMA areas don't use free CMA pages */
1707 if (!(alloc_flags & ALLOC_CMA))
1708 free_cma = zone_page_state(z, NR_FREE_CMA_PAGES);
1709 #endif
1711 if (free_pages - free_cma <= min + z->lowmem_reserve[classzone_idx])
1712 return false;
1713 for (o = 0; o < order; o++) {
1714 /* At the next order, this order's pages become unavailable */
1715 free_pages -= z->free_area[o].nr_free << o;
1717 /* Require fewer higher order pages to be free */
1718 min >>= 1;
1720 if (free_pages <= min)
1721 return false;
1723 return true;
1726 bool zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
1727 int classzone_idx, int alloc_flags)
1729 return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
1730 zone_page_state(z, NR_FREE_PAGES));
1733 bool zone_watermark_ok_safe(struct zone *z, unsigned int order,
1734 unsigned long mark, int classzone_idx, int alloc_flags)
1736 long free_pages = zone_page_state(z, NR_FREE_PAGES);
1738 if (z->percpu_drift_mark && free_pages < z->percpu_drift_mark)
1739 free_pages = zone_page_state_snapshot(z, NR_FREE_PAGES);
1741 return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
1742 free_pages);
1745 #ifdef CONFIG_NUMA
1747 * zlc_setup - Setup for "zonelist cache". Uses cached zone data to
1748 * skip over zones that are not allowed by the cpuset, or that have
1749 * been recently (in last second) found to be nearly full. See further
1750 * comments in mmzone.h. Reduces cache footprint of zonelist scans
1751 * that have to skip over a lot of full or unallowed zones.
1753 * If the zonelist cache is present in the passed in zonelist, then
1754 * returns a pointer to the allowed node mask (either the current
1755 * tasks mems_allowed, or node_states[N_MEMORY].)
1757 * If the zonelist cache is not available for this zonelist, does
1758 * nothing and returns NULL.
1760 * If the fullzones BITMAP in the zonelist cache is stale (more than
1761 * a second since last zap'd) then we zap it out (clear its bits.)
1763 * We hold off even calling zlc_setup, until after we've checked the
1764 * first zone in the zonelist, on the theory that most allocations will
1765 * be satisfied from that first zone, so best to examine that zone as
1766 * quickly as we can.
1768 static nodemask_t *zlc_setup(struct zonelist *zonelist, int alloc_flags)
1770 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1771 nodemask_t *allowednodes; /* zonelist_cache approximation */
1773 zlc = zonelist->zlcache_ptr;
1774 if (!zlc)
1775 return NULL;
1777 if (time_after(jiffies, zlc->last_full_zap + HZ)) {
1778 bitmap_zero(zlc->fullzones, MAX_ZONES_PER_ZONELIST);
1779 zlc->last_full_zap = jiffies;
1782 allowednodes = !in_interrupt() && (alloc_flags & ALLOC_CPUSET) ?
1783 &cpuset_current_mems_allowed :
1784 &node_states[N_MEMORY];
1785 return allowednodes;
1789 * Given 'z' scanning a zonelist, run a couple of quick checks to see
1790 * if it is worth looking at further for free memory:
1791 * 1) Check that the zone isn't thought to be full (doesn't have its
1792 * bit set in the zonelist_cache fullzones BITMAP).
1793 * 2) Check that the zones node (obtained from the zonelist_cache
1794 * z_to_n[] mapping) is allowed in the passed in allowednodes mask.
1795 * Return true (non-zero) if zone is worth looking at further, or
1796 * else return false (zero) if it is not.
1798 * This check -ignores- the distinction between various watermarks,
1799 * such as GFP_HIGH, GFP_ATOMIC, PF_MEMALLOC, ... If a zone is
1800 * found to be full for any variation of these watermarks, it will
1801 * be considered full for up to one second by all requests, unless
1802 * we are so low on memory on all allowed nodes that we are forced
1803 * into the second scan of the zonelist.
1805 * In the second scan we ignore this zonelist cache and exactly
1806 * apply the watermarks to all zones, even it is slower to do so.
1807 * We are low on memory in the second scan, and should leave no stone
1808 * unturned looking for a free page.
1810 static int zlc_zone_worth_trying(struct zonelist *zonelist, struct zoneref *z,
1811 nodemask_t *allowednodes)
1813 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1814 int i; /* index of *z in zonelist zones */
1815 int n; /* node that zone *z is on */
1817 zlc = zonelist->zlcache_ptr;
1818 if (!zlc)
1819 return 1;
1821 i = z - zonelist->_zonerefs;
1822 n = zlc->z_to_n[i];
1824 /* This zone is worth trying if it is allowed but not full */
1825 return node_isset(n, *allowednodes) && !test_bit(i, zlc->fullzones);
1829 * Given 'z' scanning a zonelist, set the corresponding bit in
1830 * zlc->fullzones, so that subsequent attempts to allocate a page
1831 * from that zone don't waste time re-examining it.
1833 static void zlc_mark_zone_full(struct zonelist *zonelist, struct zoneref *z)
1835 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1836 int i; /* index of *z in zonelist zones */
1838 zlc = zonelist->zlcache_ptr;
1839 if (!zlc)
1840 return;
1842 i = z - zonelist->_zonerefs;
1844 set_bit(i, zlc->fullzones);
1848 * clear all zones full, called after direct reclaim makes progress so that
1849 * a zone that was recently full is not skipped over for up to a second
1851 static void zlc_clear_zones_full(struct zonelist *zonelist)
1853 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1855 zlc = zonelist->zlcache_ptr;
1856 if (!zlc)
1857 return;
1859 bitmap_zero(zlc->fullzones, MAX_ZONES_PER_ZONELIST);
1862 static bool zone_local(struct zone *local_zone, struct zone *zone)
1864 return local_zone->node == zone->node;
1867 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
1869 return node_isset(local_zone->node, zone->zone_pgdat->reclaim_nodes);
1872 static void __paginginit init_zone_allows_reclaim(int nid)
1874 int i;
1876 for_each_node_state(i, N_MEMORY)
1877 if (node_distance(nid, i) <= RECLAIM_DISTANCE)
1878 node_set(i, NODE_DATA(nid)->reclaim_nodes);
1879 else
1880 zone_reclaim_mode = 1;
1883 #else /* CONFIG_NUMA */
1885 static nodemask_t *zlc_setup(struct zonelist *zonelist, int alloc_flags)
1887 return NULL;
1890 static int zlc_zone_worth_trying(struct zonelist *zonelist, struct zoneref *z,
1891 nodemask_t *allowednodes)
1893 return 1;
1896 static void zlc_mark_zone_full(struct zonelist *zonelist, struct zoneref *z)
1900 static void zlc_clear_zones_full(struct zonelist *zonelist)
1904 static bool zone_local(struct zone *local_zone, struct zone *zone)
1906 return true;
1909 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
1911 return true;
1914 static inline void init_zone_allows_reclaim(int nid)
1917 #endif /* CONFIG_NUMA */
1919 static void reset_alloc_batches(struct zone *preferred_zone)
1921 struct zone *zone = preferred_zone->zone_pgdat->node_zones;
1923 do {
1924 mod_zone_page_state(zone, NR_ALLOC_BATCH,
1925 high_wmark_pages(zone) - low_wmark_pages(zone) -
1926 atomic_long_read(&zone->vm_stat[NR_ALLOC_BATCH]));
1927 zone_clear_flag(zone, ZONE_FAIR_DEPLETED);
1928 } while (zone++ != preferred_zone);
1932 * get_page_from_freelist goes through the zonelist trying to allocate
1933 * a page.
1935 static struct page *
1936 get_page_from_freelist(gfp_t gfp_mask, nodemask_t *nodemask, unsigned int order,
1937 struct zonelist *zonelist, int high_zoneidx, int alloc_flags,
1938 struct zone *preferred_zone, int classzone_idx, int migratetype)
1940 struct zoneref *z;
1941 struct page *page = NULL;
1942 struct zone *zone;
1943 nodemask_t *allowednodes = NULL;/* zonelist_cache approximation */
1944 int zlc_active = 0; /* set if using zonelist_cache */
1945 int did_zlc_setup = 0; /* just call zlc_setup() one time */
1946 bool consider_zone_dirty = (alloc_flags & ALLOC_WMARK_LOW) &&
1947 (gfp_mask & __GFP_WRITE);
1948 int nr_fair_skipped = 0;
1949 bool zonelist_rescan;
1951 zonelist_scan:
1952 zonelist_rescan = false;
1955 * Scan zonelist, looking for a zone with enough free.
1956 * See also __cpuset_node_allowed_softwall() comment in kernel/cpuset.c.
1958 for_each_zone_zonelist_nodemask(zone, z, zonelist,
1959 high_zoneidx, nodemask) {
1960 unsigned long mark;
1962 if (IS_ENABLED(CONFIG_NUMA) && zlc_active &&
1963 !zlc_zone_worth_trying(zonelist, z, allowednodes))
1964 continue;
1965 if (cpusets_enabled() &&
1966 (alloc_flags & ALLOC_CPUSET) &&
1967 !cpuset_zone_allowed_softwall(zone, gfp_mask))
1968 continue;
1970 * Distribute pages in proportion to the individual
1971 * zone size to ensure fair page aging. The zone a
1972 * page was allocated in should have no effect on the
1973 * time the page has in memory before being reclaimed.
1975 if (alloc_flags & ALLOC_FAIR) {
1976 if (!zone_local(preferred_zone, zone))
1977 break;
1978 if (zone_is_fair_depleted(zone)) {
1979 nr_fair_skipped++;
1980 continue;
1984 * When allocating a page cache page for writing, we
1985 * want to get it from a zone that is within its dirty
1986 * limit, such that no single zone holds more than its
1987 * proportional share of globally allowed dirty pages.
1988 * The dirty limits take into account the zone's
1989 * lowmem reserves and high watermark so that kswapd
1990 * should be able to balance it without having to
1991 * write pages from its LRU list.
1993 * This may look like it could increase pressure on
1994 * lower zones by failing allocations in higher zones
1995 * before they are full. But the pages that do spill
1996 * over are limited as the lower zones are protected
1997 * by this very same mechanism. It should not become
1998 * a practical burden to them.
2000 * XXX: For now, allow allocations to potentially
2001 * exceed the per-zone dirty limit in the slowpath
2002 * (ALLOC_WMARK_LOW unset) before going into reclaim,
2003 * which is important when on a NUMA setup the allowed
2004 * zones are together not big enough to reach the
2005 * global limit. The proper fix for these situations
2006 * will require awareness of zones in the
2007 * dirty-throttling and the flusher threads.
2009 if (consider_zone_dirty && !zone_dirty_ok(zone))
2010 continue;
2012 mark = zone->watermark[alloc_flags & ALLOC_WMARK_MASK];
2013 if (!zone_watermark_ok(zone, order, mark,
2014 classzone_idx, alloc_flags)) {
2015 int ret;
2017 /* Checked here to keep the fast path fast */
2018 BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK);
2019 if (alloc_flags & ALLOC_NO_WATERMARKS)
2020 goto try_this_zone;
2022 if (IS_ENABLED(CONFIG_NUMA) &&
2023 !did_zlc_setup && nr_online_nodes > 1) {
2025 * we do zlc_setup if there are multiple nodes
2026 * and before considering the first zone allowed
2027 * by the cpuset.
2029 allowednodes = zlc_setup(zonelist, alloc_flags);
2030 zlc_active = 1;
2031 did_zlc_setup = 1;
2034 if (zone_reclaim_mode == 0 ||
2035 !zone_allows_reclaim(preferred_zone, zone))
2036 goto this_zone_full;
2039 * As we may have just activated ZLC, check if the first
2040 * eligible zone has failed zone_reclaim recently.
2042 if (IS_ENABLED(CONFIG_NUMA) && zlc_active &&
2043 !zlc_zone_worth_trying(zonelist, z, allowednodes))
2044 continue;
2046 ret = zone_reclaim(zone, gfp_mask, order);
2047 switch (ret) {
2048 case ZONE_RECLAIM_NOSCAN:
2049 /* did not scan */
2050 continue;
2051 case ZONE_RECLAIM_FULL:
2052 /* scanned but unreclaimable */
2053 continue;
2054 default:
2055 /* did we reclaim enough */
2056 if (zone_watermark_ok(zone, order, mark,
2057 classzone_idx, alloc_flags))
2058 goto try_this_zone;
2061 * Failed to reclaim enough to meet watermark.
2062 * Only mark the zone full if checking the min
2063 * watermark or if we failed to reclaim just
2064 * 1<<order pages or else the page allocator
2065 * fastpath will prematurely mark zones full
2066 * when the watermark is between the low and
2067 * min watermarks.
2069 if (((alloc_flags & ALLOC_WMARK_MASK) == ALLOC_WMARK_MIN) ||
2070 ret == ZONE_RECLAIM_SOME)
2071 goto this_zone_full;
2073 continue;
2077 try_this_zone:
2078 page = buffered_rmqueue(preferred_zone, zone, order,
2079 gfp_mask, migratetype);
2080 if (page)
2081 break;
2082 this_zone_full:
2083 if (IS_ENABLED(CONFIG_NUMA) && zlc_active)
2084 zlc_mark_zone_full(zonelist, z);
2087 if (page) {
2089 * page->pfmemalloc is set when ALLOC_NO_WATERMARKS was
2090 * necessary to allocate the page. The expectation is
2091 * that the caller is taking steps that will free more
2092 * memory. The caller should avoid the page being used
2093 * for !PFMEMALLOC purposes.
2095 page->pfmemalloc = !!(alloc_flags & ALLOC_NO_WATERMARKS);
2096 return page;
2100 * The first pass makes sure allocations are spread fairly within the
2101 * local node. However, the local node might have free pages left
2102 * after the fairness batches are exhausted, and remote zones haven't
2103 * even been considered yet. Try once more without fairness, and
2104 * include remote zones now, before entering the slowpath and waking
2105 * kswapd: prefer spilling to a remote zone over swapping locally.
2107 if (alloc_flags & ALLOC_FAIR) {
2108 alloc_flags &= ~ALLOC_FAIR;
2109 if (nr_fair_skipped) {
2110 zonelist_rescan = true;
2111 reset_alloc_batches(preferred_zone);
2113 if (nr_online_nodes > 1)
2114 zonelist_rescan = true;
2117 if (unlikely(IS_ENABLED(CONFIG_NUMA) && zlc_active)) {
2118 /* Disable zlc cache for second zonelist scan */
2119 zlc_active = 0;
2120 zonelist_rescan = true;
2123 if (zonelist_rescan)
2124 goto zonelist_scan;
2126 return NULL;
2130 * Large machines with many possible nodes should not always dump per-node
2131 * meminfo in irq context.
2133 static inline bool should_suppress_show_mem(void)
2135 bool ret = false;
2137 #if NODES_SHIFT > 8
2138 ret = in_interrupt();
2139 #endif
2140 return ret;
2143 static DEFINE_RATELIMIT_STATE(nopage_rs,
2144 DEFAULT_RATELIMIT_INTERVAL,
2145 DEFAULT_RATELIMIT_BURST);
2147 void warn_alloc_failed(gfp_t gfp_mask, int order, const char *fmt, ...)
2149 unsigned int filter = SHOW_MEM_FILTER_NODES;
2151 if ((gfp_mask & __GFP_NOWARN) || !__ratelimit(&nopage_rs) ||
2152 debug_guardpage_minorder() > 0)
2153 return;
2156 * Walking all memory to count page types is very expensive and should
2157 * be inhibited in non-blockable contexts.
2159 if (!(gfp_mask & __GFP_WAIT))
2160 filter |= SHOW_MEM_FILTER_PAGE_COUNT;
2163 * This documents exceptions given to allocations in certain
2164 * contexts that are allowed to allocate outside current's set
2165 * of allowed nodes.
2167 if (!(gfp_mask & __GFP_NOMEMALLOC))
2168 if (test_thread_flag(TIF_MEMDIE) ||
2169 (current->flags & (PF_MEMALLOC | PF_EXITING)))
2170 filter &= ~SHOW_MEM_FILTER_NODES;
2171 if (in_interrupt() || !(gfp_mask & __GFP_WAIT))
2172 filter &= ~SHOW_MEM_FILTER_NODES;
2174 if (fmt) {
2175 struct va_format vaf;
2176 va_list args;
2178 va_start(args, fmt);
2180 vaf.fmt = fmt;
2181 vaf.va = &args;
2183 pr_warn("%pV", &vaf);
2185 va_end(args);
2188 pr_warn("%s: page allocation failure: order:%d, mode:0x%x\n",
2189 current->comm, order, gfp_mask);
2191 dump_stack();
2192 if (!should_suppress_show_mem())
2193 show_mem(filter);
2196 static inline int
2197 should_alloc_retry(gfp_t gfp_mask, unsigned int order,
2198 unsigned long did_some_progress,
2199 unsigned long pages_reclaimed)
2201 /* Do not loop if specifically requested */
2202 if (gfp_mask & __GFP_NORETRY)
2203 return 0;
2205 /* Always retry if specifically requested */
2206 if (gfp_mask & __GFP_NOFAIL)
2207 return 1;
2210 * Suspend converts GFP_KERNEL to __GFP_WAIT which can prevent reclaim
2211 * making forward progress without invoking OOM. Suspend also disables
2212 * storage devices so kswapd will not help. Bail if we are suspending.
2214 if (!did_some_progress && pm_suspended_storage())
2215 return 0;
2218 * In this implementation, order <= PAGE_ALLOC_COSTLY_ORDER
2219 * means __GFP_NOFAIL, but that may not be true in other
2220 * implementations.
2222 if (order <= PAGE_ALLOC_COSTLY_ORDER)
2223 return 1;
2226 * For order > PAGE_ALLOC_COSTLY_ORDER, if __GFP_REPEAT is
2227 * specified, then we retry until we no longer reclaim any pages
2228 * (above), or we've reclaimed an order of pages at least as
2229 * large as the allocation's order. In both cases, if the
2230 * allocation still fails, we stop retrying.
2232 if (gfp_mask & __GFP_REPEAT && pages_reclaimed < (1 << order))
2233 return 1;
2235 return 0;
2238 static inline struct page *
2239 __alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order,
2240 struct zonelist *zonelist, enum zone_type high_zoneidx,
2241 nodemask_t *nodemask, struct zone *preferred_zone,
2242 int classzone_idx, int migratetype)
2244 struct page *page;
2246 /* Acquire the OOM killer lock for the zones in zonelist */
2247 if (!try_set_zonelist_oom(zonelist, gfp_mask)) {
2248 schedule_timeout_uninterruptible(1);
2249 return NULL;
2253 * PM-freezer should be notified that there might be an OOM killer on
2254 * its way to kill and wake somebody up. This is too early and we might
2255 * end up not killing anything but false positives are acceptable.
2256 * See freeze_processes.
2258 note_oom_kill();
2261 * Go through the zonelist yet one more time, keep very high watermark
2262 * here, this is only to catch a parallel oom killing, we must fail if
2263 * we're still under heavy pressure.
2265 page = get_page_from_freelist(gfp_mask|__GFP_HARDWALL, nodemask,
2266 order, zonelist, high_zoneidx,
2267 ALLOC_WMARK_HIGH|ALLOC_CPUSET,
2268 preferred_zone, classzone_idx, migratetype);
2269 if (page)
2270 goto out;
2272 if (!(gfp_mask & __GFP_NOFAIL)) {
2273 /* The OOM killer will not help higher order allocs */
2274 if (order > PAGE_ALLOC_COSTLY_ORDER)
2275 goto out;
2276 /* The OOM killer does not needlessly kill tasks for lowmem */
2277 if (high_zoneidx < ZONE_NORMAL)
2278 goto out;
2280 * GFP_THISNODE contains __GFP_NORETRY and we never hit this.
2281 * Sanity check for bare calls of __GFP_THISNODE, not real OOM.
2282 * The caller should handle page allocation failure by itself if
2283 * it specifies __GFP_THISNODE.
2284 * Note: Hugepage uses it but will hit PAGE_ALLOC_COSTLY_ORDER.
2286 if (gfp_mask & __GFP_THISNODE)
2287 goto out;
2289 /* Exhausted what can be done so it's blamo time */
2290 out_of_memory(zonelist, gfp_mask, order, nodemask, false);
2292 out:
2293 clear_zonelist_oom(zonelist, gfp_mask);
2294 return page;
2297 #ifdef CONFIG_COMPACTION
2298 /* Try memory compaction for high-order allocations before reclaim */
2299 static struct page *
2300 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
2301 struct zonelist *zonelist, enum zone_type high_zoneidx,
2302 nodemask_t *nodemask, int alloc_flags, struct zone *preferred_zone,
2303 int classzone_idx, int migratetype, enum migrate_mode mode,
2304 bool *contended_compaction, bool *deferred_compaction,
2305 unsigned long *did_some_progress)
2307 if (!order)
2308 return NULL;
2310 if (compaction_deferred(preferred_zone, order)) {
2311 *deferred_compaction = true;
2312 return NULL;
2315 current->flags |= PF_MEMALLOC;
2316 *did_some_progress = try_to_compact_pages(zonelist, order, gfp_mask,
2317 nodemask, mode,
2318 contended_compaction);
2319 current->flags &= ~PF_MEMALLOC;
2321 if (*did_some_progress != COMPACT_SKIPPED) {
2322 struct page *page;
2324 /* Page migration frees to the PCP lists but we want merging */
2325 drain_pages(get_cpu());
2326 put_cpu();
2328 page = get_page_from_freelist(gfp_mask, nodemask,
2329 order, zonelist, high_zoneidx,
2330 alloc_flags & ~ALLOC_NO_WATERMARKS,
2331 preferred_zone, classzone_idx, migratetype);
2332 if (page) {
2333 preferred_zone->compact_blockskip_flush = false;
2334 compaction_defer_reset(preferred_zone, order, true);
2335 count_vm_event(COMPACTSUCCESS);
2336 return page;
2340 * It's bad if compaction run occurs and fails.
2341 * The most likely reason is that pages exist,
2342 * but not enough to satisfy watermarks.
2344 count_vm_event(COMPACTFAIL);
2347 * As async compaction considers a subset of pageblocks, only
2348 * defer if the failure was a sync compaction failure.
2350 if (mode != MIGRATE_ASYNC)
2351 defer_compaction(preferred_zone, order);
2353 cond_resched();
2356 return NULL;
2358 #else
2359 static inline struct page *
2360 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
2361 struct zonelist *zonelist, enum zone_type high_zoneidx,
2362 nodemask_t *nodemask, int alloc_flags, struct zone *preferred_zone,
2363 int classzone_idx, int migratetype,
2364 enum migrate_mode mode, bool *contended_compaction,
2365 bool *deferred_compaction, unsigned long *did_some_progress)
2367 return NULL;
2369 #endif /* CONFIG_COMPACTION */
2371 /* Perform direct synchronous page reclaim */
2372 static int
2373 __perform_reclaim(gfp_t gfp_mask, unsigned int order, struct zonelist *zonelist,
2374 nodemask_t *nodemask)
2376 struct reclaim_state reclaim_state;
2377 int progress;
2379 cond_resched();
2381 /* We now go into synchronous reclaim */
2382 cpuset_memory_pressure_bump();
2383 current->flags |= PF_MEMALLOC;
2384 lockdep_set_current_reclaim_state(gfp_mask);
2385 reclaim_state.reclaimed_slab = 0;
2386 current->reclaim_state = &reclaim_state;
2388 progress = try_to_free_pages(zonelist, order, gfp_mask, nodemask);
2390 current->reclaim_state = NULL;
2391 lockdep_clear_current_reclaim_state();
2392 current->flags &= ~PF_MEMALLOC;
2394 cond_resched();
2396 return progress;
2399 /* The really slow allocator path where we enter direct reclaim */
2400 static inline struct page *
2401 __alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order,
2402 struct zonelist *zonelist, enum zone_type high_zoneidx,
2403 nodemask_t *nodemask, int alloc_flags, struct zone *preferred_zone,
2404 int classzone_idx, int migratetype, unsigned long *did_some_progress)
2406 struct page *page = NULL;
2407 bool drained = false;
2409 *did_some_progress = __perform_reclaim(gfp_mask, order, zonelist,
2410 nodemask);
2411 if (unlikely(!(*did_some_progress)))
2412 return NULL;
2414 /* After successful reclaim, reconsider all zones for allocation */
2415 if (IS_ENABLED(CONFIG_NUMA))
2416 zlc_clear_zones_full(zonelist);
2418 retry:
2419 page = get_page_from_freelist(gfp_mask, nodemask, order,
2420 zonelist, high_zoneidx,
2421 alloc_flags & ~ALLOC_NO_WATERMARKS,
2422 preferred_zone, classzone_idx,
2423 migratetype);
2426 * If an allocation failed after direct reclaim, it could be because
2427 * pages are pinned on the per-cpu lists. Drain them and try again
2429 if (!page && !drained) {
2430 drain_all_pages();
2431 drained = true;
2432 goto retry;
2435 return page;
2439 * This is called in the allocator slow-path if the allocation request is of
2440 * sufficient urgency to ignore watermarks and take other desperate measures
2442 static inline struct page *
2443 __alloc_pages_high_priority(gfp_t gfp_mask, unsigned int order,
2444 struct zonelist *zonelist, enum zone_type high_zoneidx,
2445 nodemask_t *nodemask, struct zone *preferred_zone,
2446 int classzone_idx, int migratetype)
2448 struct page *page;
2450 do {
2451 page = get_page_from_freelist(gfp_mask, nodemask, order,
2452 zonelist, high_zoneidx, ALLOC_NO_WATERMARKS,
2453 preferred_zone, classzone_idx, migratetype);
2455 if (!page && gfp_mask & __GFP_NOFAIL)
2456 wait_iff_congested(preferred_zone, BLK_RW_ASYNC, HZ/50);
2457 } while (!page && (gfp_mask & __GFP_NOFAIL));
2459 return page;
2462 static void wake_all_kswapds(unsigned int order,
2463 struct zonelist *zonelist,
2464 enum zone_type high_zoneidx,
2465 struct zone *preferred_zone)
2467 struct zoneref *z;
2468 struct zone *zone;
2470 for_each_zone_zonelist(zone, z, zonelist, high_zoneidx)
2471 wakeup_kswapd(zone, order, zone_idx(preferred_zone));
2474 static inline int
2475 gfp_to_alloc_flags(gfp_t gfp_mask)
2477 int alloc_flags = ALLOC_WMARK_MIN | ALLOC_CPUSET;
2478 const bool atomic = !(gfp_mask & (__GFP_WAIT | __GFP_NO_KSWAPD));
2480 /* __GFP_HIGH is assumed to be the same as ALLOC_HIGH to save a branch. */
2481 BUILD_BUG_ON(__GFP_HIGH != (__force gfp_t) ALLOC_HIGH);
2484 * The caller may dip into page reserves a bit more if the caller
2485 * cannot run direct reclaim, or if the caller has realtime scheduling
2486 * policy or is asking for __GFP_HIGH memory. GFP_ATOMIC requests will
2487 * set both ALLOC_HARDER (atomic == true) and ALLOC_HIGH (__GFP_HIGH).
2489 alloc_flags |= (__force int) (gfp_mask & __GFP_HIGH);
2491 if (atomic) {
2493 * Not worth trying to allocate harder for __GFP_NOMEMALLOC even
2494 * if it can't schedule.
2496 if (!(gfp_mask & __GFP_NOMEMALLOC))
2497 alloc_flags |= ALLOC_HARDER;
2499 * Ignore cpuset mems for GFP_ATOMIC rather than fail, see the
2500 * comment for __cpuset_node_allowed_softwall().
2502 alloc_flags &= ~ALLOC_CPUSET;
2503 } else if (unlikely(rt_task(current)) && !in_interrupt())
2504 alloc_flags |= ALLOC_HARDER;
2506 if (likely(!(gfp_mask & __GFP_NOMEMALLOC))) {
2507 if (gfp_mask & __GFP_MEMALLOC)
2508 alloc_flags |= ALLOC_NO_WATERMARKS;
2509 else if (in_serving_softirq() && (current->flags & PF_MEMALLOC))
2510 alloc_flags |= ALLOC_NO_WATERMARKS;
2511 else if (!in_interrupt() &&
2512 ((current->flags & PF_MEMALLOC) ||
2513 unlikely(test_thread_flag(TIF_MEMDIE))))
2514 alloc_flags |= ALLOC_NO_WATERMARKS;
2516 #ifdef CONFIG_CMA
2517 if (allocflags_to_migratetype(gfp_mask) == MIGRATE_MOVABLE)
2518 alloc_flags |= ALLOC_CMA;
2519 #endif
2520 return alloc_flags;
2523 bool gfp_pfmemalloc_allowed(gfp_t gfp_mask)
2525 return !!(gfp_to_alloc_flags(gfp_mask) & ALLOC_NO_WATERMARKS);
2528 static inline struct page *
2529 __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order,
2530 struct zonelist *zonelist, enum zone_type high_zoneidx,
2531 nodemask_t *nodemask, struct zone *preferred_zone,
2532 int classzone_idx, int migratetype)
2534 const gfp_t wait = gfp_mask & __GFP_WAIT;
2535 struct page *page = NULL;
2536 int alloc_flags;
2537 unsigned long pages_reclaimed = 0;
2538 unsigned long did_some_progress;
2539 enum migrate_mode migration_mode = MIGRATE_ASYNC;
2540 bool deferred_compaction = false;
2541 bool contended_compaction = false;
2544 * In the slowpath, we sanity check order to avoid ever trying to
2545 * reclaim >= MAX_ORDER areas which will never succeed. Callers may
2546 * be using allocators in order of preference for an area that is
2547 * too large.
2549 if (order >= MAX_ORDER) {
2550 WARN_ON_ONCE(!(gfp_mask & __GFP_NOWARN));
2551 return NULL;
2555 * GFP_THISNODE (meaning __GFP_THISNODE, __GFP_NORETRY and
2556 * __GFP_NOWARN set) should not cause reclaim since the subsystem
2557 * (f.e. slab) using GFP_THISNODE may choose to trigger reclaim
2558 * using a larger set of nodes after it has established that the
2559 * allowed per node queues are empty and that nodes are
2560 * over allocated.
2562 if (IS_ENABLED(CONFIG_NUMA) &&
2563 (gfp_mask & GFP_THISNODE) == GFP_THISNODE)
2564 goto nopage;
2566 restart:
2567 if (!(gfp_mask & __GFP_NO_KSWAPD))
2568 wake_all_kswapds(order, zonelist, high_zoneidx, preferred_zone);
2571 * OK, we're below the kswapd watermark and have kicked background
2572 * reclaim. Now things get more complex, so set up alloc_flags according
2573 * to how we want to proceed.
2575 alloc_flags = gfp_to_alloc_flags(gfp_mask);
2578 * Find the true preferred zone if the allocation is unconstrained by
2579 * cpusets.
2581 if (!(alloc_flags & ALLOC_CPUSET) && !nodemask) {
2582 struct zoneref *preferred_zoneref;
2583 preferred_zoneref = first_zones_zonelist(zonelist, high_zoneidx,
2584 NULL,
2585 &preferred_zone);
2586 classzone_idx = zonelist_zone_idx(preferred_zoneref);
2589 rebalance:
2590 /* This is the last chance, in general, before the goto nopage. */
2591 page = get_page_from_freelist(gfp_mask, nodemask, order, zonelist,
2592 high_zoneidx, alloc_flags & ~ALLOC_NO_WATERMARKS,
2593 preferred_zone, classzone_idx, migratetype);
2594 if (page)
2595 goto got_pg;
2597 /* Allocate without watermarks if the context allows */
2598 if (alloc_flags & ALLOC_NO_WATERMARKS) {
2600 * Ignore mempolicies if ALLOC_NO_WATERMARKS on the grounds
2601 * the allocation is high priority and these type of
2602 * allocations are system rather than user orientated
2604 zonelist = node_zonelist(numa_node_id(), gfp_mask);
2606 page = __alloc_pages_high_priority(gfp_mask, order,
2607 zonelist, high_zoneidx, nodemask,
2608 preferred_zone, classzone_idx, migratetype);
2609 if (page) {
2610 goto got_pg;
2614 /* Atomic allocations - we can't balance anything */
2615 if (!wait)
2616 goto nopage;
2618 /* Avoid recursion of direct reclaim */
2619 if (current->flags & PF_MEMALLOC)
2620 goto nopage;
2622 /* Avoid allocations with no watermarks from looping endlessly */
2623 if (test_thread_flag(TIF_MEMDIE) && !(gfp_mask & __GFP_NOFAIL))
2624 goto nopage;
2627 * Try direct compaction. The first pass is asynchronous. Subsequent
2628 * attempts after direct reclaim are synchronous
2630 page = __alloc_pages_direct_compact(gfp_mask, order, zonelist,
2631 high_zoneidx, nodemask, alloc_flags,
2632 preferred_zone,
2633 classzone_idx, migratetype,
2634 migration_mode, &contended_compaction,
2635 &deferred_compaction,
2636 &did_some_progress);
2637 if (page)
2638 goto got_pg;
2639 migration_mode = MIGRATE_SYNC_LIGHT;
2642 * If compaction is deferred for high-order allocations, it is because
2643 * sync compaction recently failed. In this is the case and the caller
2644 * requested a movable allocation that does not heavily disrupt the
2645 * system then fail the allocation instead of entering direct reclaim.
2647 if ((deferred_compaction || contended_compaction) &&
2648 (gfp_mask & __GFP_NO_KSWAPD))
2649 goto nopage;
2651 /* Try direct reclaim and then allocating */
2652 page = __alloc_pages_direct_reclaim(gfp_mask, order,
2653 zonelist, high_zoneidx,
2654 nodemask,
2655 alloc_flags, preferred_zone,
2656 classzone_idx, migratetype,
2657 &did_some_progress);
2658 if (page)
2659 goto got_pg;
2662 * If we failed to make any progress reclaiming, then we are
2663 * running out of options and have to consider going OOM
2665 if (!did_some_progress) {
2666 if ((gfp_mask & __GFP_FS) && !(gfp_mask & __GFP_NORETRY)) {
2667 if (oom_killer_disabled)
2668 goto nopage;
2669 /* Coredumps can quickly deplete all memory reserves */
2670 if ((current->flags & PF_DUMPCORE) &&
2671 !(gfp_mask & __GFP_NOFAIL))
2672 goto nopage;
2673 page = __alloc_pages_may_oom(gfp_mask, order,
2674 zonelist, high_zoneidx,
2675 nodemask, preferred_zone,
2676 classzone_idx, migratetype);
2677 if (page)
2678 goto got_pg;
2680 if (!(gfp_mask & __GFP_NOFAIL)) {
2682 * The oom killer is not called for high-order
2683 * allocations that may fail, so if no progress
2684 * is being made, there are no other options and
2685 * retrying is unlikely to help.
2687 if (order > PAGE_ALLOC_COSTLY_ORDER)
2688 goto nopage;
2690 * The oom killer is not called for lowmem
2691 * allocations to prevent needlessly killing
2692 * innocent tasks.
2694 if (high_zoneidx < ZONE_NORMAL)
2695 goto nopage;
2698 goto restart;
2702 /* Check if we should retry the allocation */
2703 pages_reclaimed += did_some_progress;
2704 if (should_alloc_retry(gfp_mask, order, did_some_progress,
2705 pages_reclaimed)) {
2706 /* Wait for some write requests to complete then retry */
2707 wait_iff_congested(preferred_zone, BLK_RW_ASYNC, HZ/50);
2708 goto rebalance;
2709 } else {
2711 * High-order allocations do not necessarily loop after
2712 * direct reclaim and reclaim/compaction depends on compaction
2713 * being called after reclaim so call directly if necessary
2715 page = __alloc_pages_direct_compact(gfp_mask, order, zonelist,
2716 high_zoneidx, nodemask, alloc_flags,
2717 preferred_zone,
2718 classzone_idx, migratetype,
2719 migration_mode, &contended_compaction,
2720 &deferred_compaction,
2721 &did_some_progress);
2722 if (page)
2723 goto got_pg;
2726 nopage:
2727 warn_alloc_failed(gfp_mask, order, NULL);
2728 return page;
2729 got_pg:
2730 if (kmemcheck_enabled)
2731 kmemcheck_pagealloc_alloc(page, order, gfp_mask);
2733 return page;
2737 * This is the 'heart' of the zoned buddy allocator.
2739 struct page *
2740 __alloc_pages_nodemask(gfp_t gfp_mask, unsigned int order,
2741 struct zonelist *zonelist, nodemask_t *nodemask)
2743 enum zone_type high_zoneidx = gfp_zone(gfp_mask);
2744 struct zone *preferred_zone;
2745 struct zoneref *preferred_zoneref;
2746 struct page *page = NULL;
2747 int migratetype = allocflags_to_migratetype(gfp_mask);
2748 unsigned int cpuset_mems_cookie;
2749 int alloc_flags = ALLOC_WMARK_LOW|ALLOC_CPUSET|ALLOC_FAIR;
2750 struct mem_cgroup *memcg = NULL;
2751 int classzone_idx;
2753 gfp_mask &= gfp_allowed_mask;
2755 lockdep_trace_alloc(gfp_mask);
2757 might_sleep_if(gfp_mask & __GFP_WAIT);
2759 if (should_fail_alloc_page(gfp_mask, order))
2760 return NULL;
2763 * Check the zones suitable for the gfp_mask contain at least one
2764 * valid zone. It's possible to have an empty zonelist as a result
2765 * of GFP_THISNODE and a memoryless node
2767 if (unlikely(!zonelist->_zonerefs->zone))
2768 return NULL;
2771 * Will only have any effect when __GFP_KMEMCG is set. This is
2772 * verified in the (always inline) callee
2774 if (!memcg_kmem_newpage_charge(gfp_mask, &memcg, order))
2775 return NULL;
2777 retry_cpuset:
2778 cpuset_mems_cookie = read_mems_allowed_begin();
2780 /* The preferred zone is used for statistics later */
2781 preferred_zoneref = first_zones_zonelist(zonelist, high_zoneidx,
2782 nodemask ? : &cpuset_current_mems_allowed,
2783 &preferred_zone);
2784 if (!preferred_zone)
2785 goto out;
2786 classzone_idx = zonelist_zone_idx(preferred_zoneref);
2788 #ifdef CONFIG_CMA
2789 if (allocflags_to_migratetype(gfp_mask) == MIGRATE_MOVABLE)
2790 alloc_flags |= ALLOC_CMA;
2791 #endif
2792 /* First allocation attempt */
2793 page = get_page_from_freelist(gfp_mask|__GFP_HARDWALL, nodemask, order,
2794 zonelist, high_zoneidx, alloc_flags,
2795 preferred_zone, classzone_idx, migratetype);
2796 if (unlikely(!page)) {
2798 * Runtime PM, block IO and its error handling path
2799 * can deadlock because I/O on the device might not
2800 * complete.
2802 gfp_mask = memalloc_noio_flags(gfp_mask);
2803 page = __alloc_pages_slowpath(gfp_mask, order,
2804 zonelist, high_zoneidx, nodemask,
2805 preferred_zone, classzone_idx, migratetype);
2808 trace_mm_page_alloc(page, order, gfp_mask, migratetype);
2810 out:
2812 * When updating a task's mems_allowed, it is possible to race with
2813 * parallel threads in such a way that an allocation can fail while
2814 * the mask is being updated. If a page allocation is about to fail,
2815 * check if the cpuset changed during allocation and if so, retry.
2817 if (unlikely(!page && read_mems_allowed_retry(cpuset_mems_cookie)))
2818 goto retry_cpuset;
2820 memcg_kmem_commit_charge(page, memcg, order);
2822 return page;
2824 EXPORT_SYMBOL(__alloc_pages_nodemask);
2827 * Common helper functions.
2829 unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order)
2831 struct page *page;
2834 * __get_free_pages() returns a 32-bit address, which cannot represent
2835 * a highmem page
2837 VM_BUG_ON((gfp_mask & __GFP_HIGHMEM) != 0);
2839 page = alloc_pages(gfp_mask, order);
2840 if (!page)
2841 return 0;
2842 return (unsigned long) page_address(page);
2844 EXPORT_SYMBOL(__get_free_pages);
2846 unsigned long get_zeroed_page(gfp_t gfp_mask)
2848 return __get_free_pages(gfp_mask | __GFP_ZERO, 0);
2850 EXPORT_SYMBOL(get_zeroed_page);
2852 void __free_pages(struct page *page, unsigned int order)
2854 if (put_page_testzero(page)) {
2855 if (order == 0)
2856 free_hot_cold_page(page, false);
2857 else
2858 __free_pages_ok(page, order);
2862 EXPORT_SYMBOL(__free_pages);
2864 void free_pages(unsigned long addr, unsigned int order)
2866 if (addr != 0) {
2867 VM_BUG_ON(!virt_addr_valid((void *)addr));
2868 __free_pages(virt_to_page((void *)addr), order);
2872 EXPORT_SYMBOL(free_pages);
2875 * __free_memcg_kmem_pages and free_memcg_kmem_pages will free
2876 * pages allocated with __GFP_KMEMCG.
2878 * Those pages are accounted to a particular memcg, embedded in the
2879 * corresponding page_cgroup. To avoid adding a hit in the allocator to search
2880 * for that information only to find out that it is NULL for users who have no
2881 * interest in that whatsoever, we provide these functions.
2883 * The caller knows better which flags it relies on.
2885 void __free_memcg_kmem_pages(struct page *page, unsigned int order)
2887 memcg_kmem_uncharge_pages(page, order);
2888 __free_pages(page, order);
2891 void free_memcg_kmem_pages(unsigned long addr, unsigned int order)
2893 if (addr != 0) {
2894 VM_BUG_ON(!virt_addr_valid((void *)addr));
2895 __free_memcg_kmem_pages(virt_to_page((void *)addr), order);
2899 static void *make_alloc_exact(unsigned long addr, unsigned order, size_t size)
2901 if (addr) {
2902 unsigned long alloc_end = addr + (PAGE_SIZE << order);
2903 unsigned long used = addr + PAGE_ALIGN(size);
2905 split_page(virt_to_page((void *)addr), order);
2906 while (used < alloc_end) {
2907 free_page(used);
2908 used += PAGE_SIZE;
2911 return (void *)addr;
2915 * alloc_pages_exact - allocate an exact number physically-contiguous pages.
2916 * @size: the number of bytes to allocate
2917 * @gfp_mask: GFP flags for the allocation
2919 * This function is similar to alloc_pages(), except that it allocates the
2920 * minimum number of pages to satisfy the request. alloc_pages() can only
2921 * allocate memory in power-of-two pages.
2923 * This function is also limited by MAX_ORDER.
2925 * Memory allocated by this function must be released by free_pages_exact().
2927 void *alloc_pages_exact(size_t size, gfp_t gfp_mask)
2929 unsigned int order = get_order(size);
2930 unsigned long addr;
2932 addr = __get_free_pages(gfp_mask, order);
2933 return make_alloc_exact(addr, order, size);
2935 EXPORT_SYMBOL(alloc_pages_exact);
2938 * alloc_pages_exact_nid - allocate an exact number of physically-contiguous
2939 * pages on a node.
2940 * @nid: the preferred node ID where memory should be allocated
2941 * @size: the number of bytes to allocate
2942 * @gfp_mask: GFP flags for the allocation
2944 * Like alloc_pages_exact(), but try to allocate on node nid first before falling
2945 * back.
2946 * Note this is not alloc_pages_exact_node() which allocates on a specific node,
2947 * but is not exact.
2949 void *alloc_pages_exact_nid(int nid, size_t size, gfp_t gfp_mask)
2951 unsigned order = get_order(size);
2952 struct page *p = alloc_pages_node(nid, gfp_mask, order);
2953 if (!p)
2954 return NULL;
2955 return make_alloc_exact((unsigned long)page_address(p), order, size);
2957 EXPORT_SYMBOL(alloc_pages_exact_nid);
2960 * free_pages_exact - release memory allocated via alloc_pages_exact()
2961 * @virt: the value returned by alloc_pages_exact.
2962 * @size: size of allocation, same value as passed to alloc_pages_exact().
2964 * Release the memory allocated by a previous call to alloc_pages_exact.
2966 void free_pages_exact(void *virt, size_t size)
2968 unsigned long addr = (unsigned long)virt;
2969 unsigned long end = addr + PAGE_ALIGN(size);
2971 while (addr < end) {
2972 free_page(addr);
2973 addr += PAGE_SIZE;
2976 EXPORT_SYMBOL(free_pages_exact);
2979 * nr_free_zone_pages - count number of pages beyond high watermark
2980 * @offset: The zone index of the highest zone
2982 * nr_free_zone_pages() counts the number of counts pages which are beyond the
2983 * high watermark within all zones at or below a given zone index. For each
2984 * zone, the number of pages is calculated as:
2985 * managed_pages - high_pages
2987 static unsigned long nr_free_zone_pages(int offset)
2989 struct zoneref *z;
2990 struct zone *zone;
2992 /* Just pick one node, since fallback list is circular */
2993 unsigned long sum = 0;
2995 struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL);
2997 for_each_zone_zonelist(zone, z, zonelist, offset) {
2998 unsigned long size = zone->managed_pages;
2999 unsigned long high = high_wmark_pages(zone);
3000 if (size > high)
3001 sum += size - high;
3004 return sum;
3008 * nr_free_buffer_pages - count number of pages beyond high watermark
3010 * nr_free_buffer_pages() counts the number of pages which are beyond the high
3011 * watermark within ZONE_DMA and ZONE_NORMAL.
3013 unsigned long nr_free_buffer_pages(void)
3015 return nr_free_zone_pages(gfp_zone(GFP_USER));
3017 EXPORT_SYMBOL_GPL(nr_free_buffer_pages);
3020 * nr_free_pagecache_pages - count number of pages beyond high watermark
3022 * nr_free_pagecache_pages() counts the number of pages which are beyond the
3023 * high watermark within all zones.
3025 unsigned long nr_free_pagecache_pages(void)
3027 return nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE));
3030 static inline void show_node(struct zone *zone)
3032 if (IS_ENABLED(CONFIG_NUMA))
3033 printk("Node %d ", zone_to_nid(zone));
3036 void si_meminfo(struct sysinfo *val)
3038 val->totalram = totalram_pages;
3039 val->sharedram = 0;
3040 val->freeram = global_page_state(NR_FREE_PAGES);
3041 val->bufferram = nr_blockdev_pages();
3042 val->totalhigh = totalhigh_pages;
3043 val->freehigh = nr_free_highpages();
3044 val->mem_unit = PAGE_SIZE;
3047 EXPORT_SYMBOL(si_meminfo);
3049 #ifdef CONFIG_NUMA
3050 void si_meminfo_node(struct sysinfo *val, int nid)
3052 int zone_type; /* needs to be signed */
3053 unsigned long managed_pages = 0;
3054 pg_data_t *pgdat = NODE_DATA(nid);
3056 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++)
3057 managed_pages += pgdat->node_zones[zone_type].managed_pages;
3058 val->totalram = managed_pages;
3059 val->freeram = node_page_state(nid, NR_FREE_PAGES);
3060 #ifdef CONFIG_HIGHMEM
3061 val->totalhigh = pgdat->node_zones[ZONE_HIGHMEM].managed_pages;
3062 val->freehigh = zone_page_state(&pgdat->node_zones[ZONE_HIGHMEM],
3063 NR_FREE_PAGES);
3064 #else
3065 val->totalhigh = 0;
3066 val->freehigh = 0;
3067 #endif
3068 val->mem_unit = PAGE_SIZE;
3070 #endif
3073 * Determine whether the node should be displayed or not, depending on whether
3074 * SHOW_MEM_FILTER_NODES was passed to show_free_areas().
3076 bool skip_free_areas_node(unsigned int flags, int nid)
3078 bool ret = false;
3079 unsigned int cpuset_mems_cookie;
3081 if (!(flags & SHOW_MEM_FILTER_NODES))
3082 goto out;
3084 do {
3085 cpuset_mems_cookie = read_mems_allowed_begin();
3086 ret = !node_isset(nid, cpuset_current_mems_allowed);
3087 } while (read_mems_allowed_retry(cpuset_mems_cookie));
3088 out:
3089 return ret;
3092 #define K(x) ((x) << (PAGE_SHIFT-10))
3094 static void show_migration_types(unsigned char type)
3096 static const char types[MIGRATE_TYPES] = {
3097 [MIGRATE_UNMOVABLE] = 'U',
3098 [MIGRATE_RECLAIMABLE] = 'E',
3099 [MIGRATE_MOVABLE] = 'M',
3100 [MIGRATE_RESERVE] = 'R',
3101 #ifdef CONFIG_CMA
3102 [MIGRATE_CMA] = 'C',
3103 #endif
3104 #ifdef CONFIG_MEMORY_ISOLATION
3105 [MIGRATE_ISOLATE] = 'I',
3106 #endif
3108 char tmp[MIGRATE_TYPES + 1];
3109 char *p = tmp;
3110 int i;
3112 for (i = 0; i < MIGRATE_TYPES; i++) {
3113 if (type & (1 << i))
3114 *p++ = types[i];
3117 *p = '\0';
3118 printk("(%s) ", tmp);
3122 * Show free area list (used inside shift_scroll-lock stuff)
3123 * We also calculate the percentage fragmentation. We do this by counting the
3124 * memory on each free list with the exception of the first item on the list.
3125 * Suppresses nodes that are not allowed by current's cpuset if
3126 * SHOW_MEM_FILTER_NODES is passed.
3128 void show_free_areas(unsigned int filter)
3130 int cpu;
3131 struct zone *zone;
3133 for_each_populated_zone(zone) {
3134 if (skip_free_areas_node(filter, zone_to_nid(zone)))
3135 continue;
3136 show_node(zone);
3137 printk("%s per-cpu:\n", zone->name);
3139 for_each_online_cpu(cpu) {
3140 struct per_cpu_pageset *pageset;
3142 pageset = per_cpu_ptr(zone->pageset, cpu);
3144 printk("CPU %4d: hi:%5d, btch:%4d usd:%4d\n",
3145 cpu, pageset->pcp.high,
3146 pageset->pcp.batch, pageset->pcp.count);
3150 printk("active_anon:%lu inactive_anon:%lu isolated_anon:%lu\n"
3151 " active_file:%lu inactive_file:%lu isolated_file:%lu\n"
3152 " unevictable:%lu"
3153 " dirty:%lu writeback:%lu unstable:%lu\n"
3154 " free:%lu slab_reclaimable:%lu slab_unreclaimable:%lu\n"
3155 " mapped:%lu shmem:%lu pagetables:%lu bounce:%lu\n"
3156 " free_cma:%lu\n",
3157 global_page_state(NR_ACTIVE_ANON),
3158 global_page_state(NR_INACTIVE_ANON),
3159 global_page_state(NR_ISOLATED_ANON),
3160 global_page_state(NR_ACTIVE_FILE),
3161 global_page_state(NR_INACTIVE_FILE),
3162 global_page_state(NR_ISOLATED_FILE),
3163 global_page_state(NR_UNEVICTABLE),
3164 global_page_state(NR_FILE_DIRTY),
3165 global_page_state(NR_WRITEBACK),
3166 global_page_state(NR_UNSTABLE_NFS),
3167 global_page_state(NR_FREE_PAGES),
3168 global_page_state(NR_SLAB_RECLAIMABLE),
3169 global_page_state(NR_SLAB_UNRECLAIMABLE),
3170 global_page_state(NR_FILE_MAPPED),
3171 global_page_state(NR_SHMEM),
3172 global_page_state(NR_PAGETABLE),
3173 global_page_state(NR_BOUNCE),
3174 global_page_state(NR_FREE_CMA_PAGES));
3176 for_each_populated_zone(zone) {
3177 int i;
3179 if (skip_free_areas_node(filter, zone_to_nid(zone)))
3180 continue;
3181 show_node(zone);
3182 printk("%s"
3183 " free:%lukB"
3184 " min:%lukB"
3185 " low:%lukB"
3186 " high:%lukB"
3187 " active_anon:%lukB"
3188 " inactive_anon:%lukB"
3189 " active_file:%lukB"
3190 " inactive_file:%lukB"
3191 " unevictable:%lukB"
3192 " isolated(anon):%lukB"
3193 " isolated(file):%lukB"
3194 " present:%lukB"
3195 " managed:%lukB"
3196 " mlocked:%lukB"
3197 " dirty:%lukB"
3198 " writeback:%lukB"
3199 " mapped:%lukB"
3200 " shmem:%lukB"
3201 " slab_reclaimable:%lukB"
3202 " slab_unreclaimable:%lukB"
3203 " kernel_stack:%lukB"
3204 " pagetables:%lukB"
3205 " unstable:%lukB"
3206 " bounce:%lukB"
3207 " free_cma:%lukB"
3208 " writeback_tmp:%lukB"
3209 " pages_scanned:%lu"
3210 " all_unreclaimable? %s"
3211 "\n",
3212 zone->name,
3213 K(zone_page_state(zone, NR_FREE_PAGES)),
3214 K(min_wmark_pages(zone)),
3215 K(low_wmark_pages(zone)),
3216 K(high_wmark_pages(zone)),
3217 K(zone_page_state(zone, NR_ACTIVE_ANON)),
3218 K(zone_page_state(zone, NR_INACTIVE_ANON)),
3219 K(zone_page_state(zone, NR_ACTIVE_FILE)),
3220 K(zone_page_state(zone, NR_INACTIVE_FILE)),
3221 K(zone_page_state(zone, NR_UNEVICTABLE)),
3222 K(zone_page_state(zone, NR_ISOLATED_ANON)),
3223 K(zone_page_state(zone, NR_ISOLATED_FILE)),
3224 K(zone->present_pages),
3225 K(zone->managed_pages),
3226 K(zone_page_state(zone, NR_MLOCK)),
3227 K(zone_page_state(zone, NR_FILE_DIRTY)),
3228 K(zone_page_state(zone, NR_WRITEBACK)),
3229 K(zone_page_state(zone, NR_FILE_MAPPED)),
3230 K(zone_page_state(zone, NR_SHMEM)),
3231 K(zone_page_state(zone, NR_SLAB_RECLAIMABLE)),
3232 K(zone_page_state(zone, NR_SLAB_UNRECLAIMABLE)),
3233 zone_page_state(zone, NR_KERNEL_STACK) *
3234 THREAD_SIZE / 1024,
3235 K(zone_page_state(zone, NR_PAGETABLE)),
3236 K(zone_page_state(zone, NR_UNSTABLE_NFS)),
3237 K(zone_page_state(zone, NR_BOUNCE)),
3238 K(zone_page_state(zone, NR_FREE_CMA_PAGES)),
3239 K(zone_page_state(zone, NR_WRITEBACK_TEMP)),
3240 K(zone_page_state(zone, NR_PAGES_SCANNED)),
3241 (!zone_reclaimable(zone) ? "yes" : "no")
3243 printk("lowmem_reserve[]:");
3244 for (i = 0; i < MAX_NR_ZONES; i++)
3245 printk(" %ld", zone->lowmem_reserve[i]);
3246 printk("\n");
3249 for_each_populated_zone(zone) {
3250 unsigned long nr[MAX_ORDER], flags, order, total = 0;
3251 unsigned char types[MAX_ORDER];
3253 if (skip_free_areas_node(filter, zone_to_nid(zone)))
3254 continue;
3255 show_node(zone);
3256 printk("%s: ", zone->name);
3258 spin_lock_irqsave(&zone->lock, flags);
3259 for (order = 0; order < MAX_ORDER; order++) {
3260 struct free_area *area = &zone->free_area[order];
3261 int type;
3263 nr[order] = area->nr_free;
3264 total += nr[order] << order;
3266 types[order] = 0;
3267 for (type = 0; type < MIGRATE_TYPES; type++) {
3268 if (!list_empty(&area->free_list[type]))
3269 types[order] |= 1 << type;
3272 spin_unlock_irqrestore(&zone->lock, flags);
3273 for (order = 0; order < MAX_ORDER; order++) {
3274 printk("%lu*%lukB ", nr[order], K(1UL) << order);
3275 if (nr[order])
3276 show_migration_types(types[order]);
3278 printk("= %lukB\n", K(total));
3281 hugetlb_show_meminfo();
3283 printk("%ld total pagecache pages\n", global_page_state(NR_FILE_PAGES));
3285 show_swap_cache_info();
3288 static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref)
3290 zoneref->zone = zone;
3291 zoneref->zone_idx = zone_idx(zone);
3295 * Builds allocation fallback zone lists.
3297 * Add all populated zones of a node to the zonelist.
3299 static int build_zonelists_node(pg_data_t *pgdat, struct zonelist *zonelist,
3300 int nr_zones)
3302 struct zone *zone;
3303 enum zone_type zone_type = MAX_NR_ZONES;
3305 do {
3306 zone_type--;
3307 zone = pgdat->node_zones + zone_type;
3308 if (populated_zone(zone)) {
3309 zoneref_set_zone(zone,
3310 &zonelist->_zonerefs[nr_zones++]);
3311 check_highest_zone(zone_type);
3313 } while (zone_type);
3315 return nr_zones;
3320 * zonelist_order:
3321 * 0 = automatic detection of better ordering.
3322 * 1 = order by ([node] distance, -zonetype)
3323 * 2 = order by (-zonetype, [node] distance)
3325 * If not NUMA, ZONELIST_ORDER_ZONE and ZONELIST_ORDER_NODE will create
3326 * the same zonelist. So only NUMA can configure this param.
3328 #define ZONELIST_ORDER_DEFAULT 0
3329 #define ZONELIST_ORDER_NODE 1
3330 #define ZONELIST_ORDER_ZONE 2
3332 /* zonelist order in the kernel.
3333 * set_zonelist_order() will set this to NODE or ZONE.
3335 static int current_zonelist_order = ZONELIST_ORDER_DEFAULT;
3336 static char zonelist_order_name[3][8] = {"Default", "Node", "Zone"};
3339 #ifdef CONFIG_NUMA
3340 /* The value user specified ....changed by config */
3341 static int user_zonelist_order = ZONELIST_ORDER_DEFAULT;
3342 /* string for sysctl */
3343 #define NUMA_ZONELIST_ORDER_LEN 16
3344 char numa_zonelist_order[16] = "default";
3347 * interface for configure zonelist ordering.
3348 * command line option "numa_zonelist_order"
3349 * = "[dD]efault - default, automatic configuration.
3350 * = "[nN]ode - order by node locality, then by zone within node
3351 * = "[zZ]one - order by zone, then by locality within zone
3354 static int __parse_numa_zonelist_order(char *s)
3356 if (*s == 'd' || *s == 'D') {
3357 user_zonelist_order = ZONELIST_ORDER_DEFAULT;
3358 } else if (*s == 'n' || *s == 'N') {
3359 user_zonelist_order = ZONELIST_ORDER_NODE;
3360 } else if (*s == 'z' || *s == 'Z') {
3361 user_zonelist_order = ZONELIST_ORDER_ZONE;
3362 } else {
3363 printk(KERN_WARNING
3364 "Ignoring invalid numa_zonelist_order value: "
3365 "%s\n", s);
3366 return -EINVAL;
3368 return 0;
3371 static __init int setup_numa_zonelist_order(char *s)
3373 int ret;
3375 if (!s)
3376 return 0;
3378 ret = __parse_numa_zonelist_order(s);
3379 if (ret == 0)
3380 strlcpy(numa_zonelist_order, s, NUMA_ZONELIST_ORDER_LEN);
3382 return ret;
3384 early_param("numa_zonelist_order", setup_numa_zonelist_order);
3387 * sysctl handler for numa_zonelist_order
3389 int numa_zonelist_order_handler(ctl_table *table, int write,
3390 void __user *buffer, size_t *length,
3391 loff_t *ppos)
3393 char saved_string[NUMA_ZONELIST_ORDER_LEN];
3394 int ret;
3395 static DEFINE_MUTEX(zl_order_mutex);
3397 mutex_lock(&zl_order_mutex);
3398 if (write) {
3399 if (strlen((char *)table->data) >= NUMA_ZONELIST_ORDER_LEN) {
3400 ret = -EINVAL;
3401 goto out;
3403 strcpy(saved_string, (char *)table->data);
3405 ret = proc_dostring(table, write, buffer, length, ppos);
3406 if (ret)
3407 goto out;
3408 if (write) {
3409 int oldval = user_zonelist_order;
3411 ret = __parse_numa_zonelist_order((char *)table->data);
3412 if (ret) {
3414 * bogus value. restore saved string
3416 strncpy((char *)table->data, saved_string,
3417 NUMA_ZONELIST_ORDER_LEN);
3418 user_zonelist_order = oldval;
3419 } else if (oldval != user_zonelist_order) {
3420 mutex_lock(&zonelists_mutex);
3421 build_all_zonelists(NULL, NULL);
3422 mutex_unlock(&zonelists_mutex);
3425 out:
3426 mutex_unlock(&zl_order_mutex);
3427 return ret;
3431 #define MAX_NODE_LOAD (nr_online_nodes)
3432 static int node_load[MAX_NUMNODES];
3435 * find_next_best_node - find the next node that should appear in a given node's fallback list
3436 * @node: node whose fallback list we're appending
3437 * @used_node_mask: nodemask_t of already used nodes
3439 * We use a number of factors to determine which is the next node that should
3440 * appear on a given node's fallback list. The node should not have appeared
3441 * already in @node's fallback list, and it should be the next closest node
3442 * according to the distance array (which contains arbitrary distance values
3443 * from each node to each node in the system), and should also prefer nodes
3444 * with no CPUs, since presumably they'll have very little allocation pressure
3445 * on them otherwise.
3446 * It returns -1 if no node is found.
3448 static int find_next_best_node(int node, nodemask_t *used_node_mask)
3450 int n, val;
3451 int min_val = INT_MAX;
3452 int best_node = NUMA_NO_NODE;
3453 const struct cpumask *tmp = cpumask_of_node(0);
3455 /* Use the local node if we haven't already */
3456 if (!node_isset(node, *used_node_mask)) {
3457 node_set(node, *used_node_mask);
3458 return node;
3461 for_each_node_state(n, N_MEMORY) {
3463 /* Don't want a node to appear more than once */
3464 if (node_isset(n, *used_node_mask))
3465 continue;
3467 /* Use the distance array to find the distance */
3468 val = node_distance(node, n);
3470 /* Penalize nodes under us ("prefer the next node") */
3471 val += (n < node);
3473 /* Give preference to headless and unused nodes */
3474 tmp = cpumask_of_node(n);
3475 if (!cpumask_empty(tmp))
3476 val += PENALTY_FOR_NODE_WITH_CPUS;
3478 /* Slight preference for less loaded node */
3479 val *= (MAX_NODE_LOAD*MAX_NUMNODES);
3480 val += node_load[n];
3482 if (val < min_val) {
3483 min_val = val;
3484 best_node = n;
3488 if (best_node >= 0)
3489 node_set(best_node, *used_node_mask);
3491 return best_node;
3496 * Build zonelists ordered by node and zones within node.
3497 * This results in maximum locality--normal zone overflows into local
3498 * DMA zone, if any--but risks exhausting DMA zone.
3500 static void build_zonelists_in_node_order(pg_data_t *pgdat, int node)
3502 int j;
3503 struct zonelist *zonelist;
3505 zonelist = &pgdat->node_zonelists[0];
3506 for (j = 0; zonelist->_zonerefs[j].zone != NULL; j++)
3508 j = build_zonelists_node(NODE_DATA(node), zonelist, j);
3509 zonelist->_zonerefs[j].zone = NULL;
3510 zonelist->_zonerefs[j].zone_idx = 0;
3514 * Build gfp_thisnode zonelists
3516 static void build_thisnode_zonelists(pg_data_t *pgdat)
3518 int j;
3519 struct zonelist *zonelist;
3521 zonelist = &pgdat->node_zonelists[1];
3522 j = build_zonelists_node(pgdat, zonelist, 0);
3523 zonelist->_zonerefs[j].zone = NULL;
3524 zonelist->_zonerefs[j].zone_idx = 0;
3528 * Build zonelists ordered by zone and nodes within zones.
3529 * This results in conserving DMA zone[s] until all Normal memory is
3530 * exhausted, but results in overflowing to remote node while memory
3531 * may still exist in local DMA zone.
3533 static int node_order[MAX_NUMNODES];
3535 static void build_zonelists_in_zone_order(pg_data_t *pgdat, int nr_nodes)
3537 int pos, j, node;
3538 int zone_type; /* needs to be signed */
3539 struct zone *z;
3540 struct zonelist *zonelist;
3542 zonelist = &pgdat->node_zonelists[0];
3543 pos = 0;
3544 for (zone_type = MAX_NR_ZONES - 1; zone_type >= 0; zone_type--) {
3545 for (j = 0; j < nr_nodes; j++) {
3546 node = node_order[j];
3547 z = &NODE_DATA(node)->node_zones[zone_type];
3548 if (populated_zone(z)) {
3549 zoneref_set_zone(z,
3550 &zonelist->_zonerefs[pos++]);
3551 check_highest_zone(zone_type);
3555 zonelist->_zonerefs[pos].zone = NULL;
3556 zonelist->_zonerefs[pos].zone_idx = 0;
3559 static int default_zonelist_order(void)
3561 int nid, zone_type;
3562 unsigned long low_kmem_size, total_size;
3563 struct zone *z;
3564 int average_size;
3566 * ZONE_DMA and ZONE_DMA32 can be very small area in the system.
3567 * If they are really small and used heavily, the system can fall
3568 * into OOM very easily.
3569 * This function detect ZONE_DMA/DMA32 size and configures zone order.
3571 /* Is there ZONE_NORMAL ? (ex. ppc has only DMA zone..) */
3572 low_kmem_size = 0;
3573 total_size = 0;
3574 for_each_online_node(nid) {
3575 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
3576 z = &NODE_DATA(nid)->node_zones[zone_type];
3577 if (populated_zone(z)) {
3578 if (zone_type < ZONE_NORMAL)
3579 low_kmem_size += z->managed_pages;
3580 total_size += z->managed_pages;
3581 } else if (zone_type == ZONE_NORMAL) {
3583 * If any node has only lowmem, then node order
3584 * is preferred to allow kernel allocations
3585 * locally; otherwise, they can easily infringe
3586 * on other nodes when there is an abundance of
3587 * lowmem available to allocate from.
3589 return ZONELIST_ORDER_NODE;
3593 if (!low_kmem_size || /* there are no DMA area. */
3594 low_kmem_size > total_size/2) /* DMA/DMA32 is big. */
3595 return ZONELIST_ORDER_NODE;
3597 * look into each node's config.
3598 * If there is a node whose DMA/DMA32 memory is very big area on
3599 * local memory, NODE_ORDER may be suitable.
3601 average_size = total_size /
3602 (nodes_weight(node_states[N_MEMORY]) + 1);
3603 for_each_online_node(nid) {
3604 low_kmem_size = 0;
3605 total_size = 0;
3606 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
3607 z = &NODE_DATA(nid)->node_zones[zone_type];
3608 if (populated_zone(z)) {
3609 if (zone_type < ZONE_NORMAL)
3610 low_kmem_size += z->present_pages;
3611 total_size += z->present_pages;
3614 if (low_kmem_size &&
3615 total_size > average_size && /* ignore small node */
3616 low_kmem_size > total_size * 70/100)
3617 return ZONELIST_ORDER_NODE;
3619 return ZONELIST_ORDER_ZONE;
3622 static void set_zonelist_order(void)
3624 if (user_zonelist_order == ZONELIST_ORDER_DEFAULT)
3625 current_zonelist_order = default_zonelist_order();
3626 else
3627 current_zonelist_order = user_zonelist_order;
3630 static void build_zonelists(pg_data_t *pgdat)
3632 int j, node, load;
3633 enum zone_type i;
3634 nodemask_t used_mask;
3635 int local_node, prev_node;
3636 struct zonelist *zonelist;
3637 int order = current_zonelist_order;
3639 /* initialize zonelists */
3640 for (i = 0; i < MAX_ZONELISTS; i++) {
3641 zonelist = pgdat->node_zonelists + i;
3642 zonelist->_zonerefs[0].zone = NULL;
3643 zonelist->_zonerefs[0].zone_idx = 0;
3646 /* NUMA-aware ordering of nodes */
3647 local_node = pgdat->node_id;
3648 load = nr_online_nodes;
3649 prev_node = local_node;
3650 nodes_clear(used_mask);
3652 memset(node_order, 0, sizeof(node_order));
3653 j = 0;
3655 while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
3657 * We don't want to pressure a particular node.
3658 * So adding penalty to the first node in same
3659 * distance group to make it round-robin.
3661 if (node_distance(local_node, node) !=
3662 node_distance(local_node, prev_node))
3663 node_load[node] = load;
3665 prev_node = node;
3666 load--;
3667 if (order == ZONELIST_ORDER_NODE)
3668 build_zonelists_in_node_order(pgdat, node);
3669 else
3670 node_order[j++] = node; /* remember order */
3673 if (order == ZONELIST_ORDER_ZONE) {
3674 /* calculate node order -- i.e., DMA last! */
3675 build_zonelists_in_zone_order(pgdat, j);
3678 build_thisnode_zonelists(pgdat);
3681 /* Construct the zonelist performance cache - see further mmzone.h */
3682 static void build_zonelist_cache(pg_data_t *pgdat)
3684 struct zonelist *zonelist;
3685 struct zonelist_cache *zlc;
3686 struct zoneref *z;
3688 zonelist = &pgdat->node_zonelists[0];
3689 zonelist->zlcache_ptr = zlc = &zonelist->zlcache;
3690 bitmap_zero(zlc->fullzones, MAX_ZONES_PER_ZONELIST);
3691 for (z = zonelist->_zonerefs; z->zone; z++)
3692 zlc->z_to_n[z - zonelist->_zonerefs] = zonelist_node_idx(z);
3695 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
3697 * Return node id of node used for "local" allocations.
3698 * I.e., first node id of first zone in arg node's generic zonelist.
3699 * Used for initializing percpu 'numa_mem', which is used primarily
3700 * for kernel allocations, so use GFP_KERNEL flags to locate zonelist.
3702 int local_memory_node(int node)
3704 struct zone *zone;
3706 (void)first_zones_zonelist(node_zonelist(node, GFP_KERNEL),
3707 gfp_zone(GFP_KERNEL),
3708 NULL,
3709 &zone);
3710 return zone->node;
3712 #endif
3714 #else /* CONFIG_NUMA */
3716 static void set_zonelist_order(void)
3718 current_zonelist_order = ZONELIST_ORDER_ZONE;
3721 static void build_zonelists(pg_data_t *pgdat)
3723 int node, local_node;
3724 enum zone_type j;
3725 struct zonelist *zonelist;
3727 local_node = pgdat->node_id;
3729 zonelist = &pgdat->node_zonelists[0];
3730 j = build_zonelists_node(pgdat, zonelist, 0);
3733 * Now we build the zonelist so that it contains the zones
3734 * of all the other nodes.
3735 * We don't want to pressure a particular node, so when
3736 * building the zones for node N, we make sure that the
3737 * zones coming right after the local ones are those from
3738 * node N+1 (modulo N)
3740 for (node = local_node + 1; node < MAX_NUMNODES; node++) {
3741 if (!node_online(node))
3742 continue;
3743 j = build_zonelists_node(NODE_DATA(node), zonelist, j);
3745 for (node = 0; node < local_node; node++) {
3746 if (!node_online(node))
3747 continue;
3748 j = build_zonelists_node(NODE_DATA(node), zonelist, j);
3751 zonelist->_zonerefs[j].zone = NULL;
3752 zonelist->_zonerefs[j].zone_idx = 0;
3755 /* non-NUMA variant of zonelist performance cache - just NULL zlcache_ptr */
3756 static void build_zonelist_cache(pg_data_t *pgdat)
3758 pgdat->node_zonelists[0].zlcache_ptr = NULL;
3761 #endif /* CONFIG_NUMA */
3764 * Boot pageset table. One per cpu which is going to be used for all
3765 * zones and all nodes. The parameters will be set in such a way
3766 * that an item put on a list will immediately be handed over to
3767 * the buddy list. This is safe since pageset manipulation is done
3768 * with interrupts disabled.
3770 * The boot_pagesets must be kept even after bootup is complete for
3771 * unused processors and/or zones. They do play a role for bootstrapping
3772 * hotplugged processors.
3774 * zoneinfo_show() and maybe other functions do
3775 * not check if the processor is online before following the pageset pointer.
3776 * Other parts of the kernel may not check if the zone is available.
3778 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch);
3779 static DEFINE_PER_CPU(struct per_cpu_pageset, boot_pageset);
3780 static void setup_zone_pageset(struct zone *zone);
3783 * Global mutex to protect against size modification of zonelists
3784 * as well as to serialize pageset setup for the new populated zone.
3786 DEFINE_MUTEX(zonelists_mutex);
3788 /* return values int ....just for stop_machine() */
3789 static int __build_all_zonelists(void *data)
3791 int nid;
3792 int cpu;
3793 pg_data_t *self = data;
3795 #ifdef CONFIG_NUMA
3796 memset(node_load, 0, sizeof(node_load));
3797 #endif
3799 if (self && !node_online(self->node_id)) {
3800 build_zonelists(self);
3801 build_zonelist_cache(self);
3804 for_each_online_node(nid) {
3805 pg_data_t *pgdat = NODE_DATA(nid);
3807 build_zonelists(pgdat);
3808 build_zonelist_cache(pgdat);
3812 * Initialize the boot_pagesets that are going to be used
3813 * for bootstrapping processors. The real pagesets for
3814 * each zone will be allocated later when the per cpu
3815 * allocator is available.
3817 * boot_pagesets are used also for bootstrapping offline
3818 * cpus if the system is already booted because the pagesets
3819 * are needed to initialize allocators on a specific cpu too.
3820 * F.e. the percpu allocator needs the page allocator which
3821 * needs the percpu allocator in order to allocate its pagesets
3822 * (a chicken-egg dilemma).
3824 for_each_possible_cpu(cpu) {
3825 setup_pageset(&per_cpu(boot_pageset, cpu), 0);
3827 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
3829 * We now know the "local memory node" for each node--
3830 * i.e., the node of the first zone in the generic zonelist.
3831 * Set up numa_mem percpu variable for on-line cpus. During
3832 * boot, only the boot cpu should be on-line; we'll init the
3833 * secondary cpus' numa_mem as they come on-line. During
3834 * node/memory hotplug, we'll fixup all on-line cpus.
3836 if (cpu_online(cpu))
3837 set_cpu_numa_mem(cpu, local_memory_node(cpu_to_node(cpu)));
3838 #endif
3841 return 0;
3845 * Called with zonelists_mutex held always
3846 * unless system_state == SYSTEM_BOOTING.
3848 void __ref build_all_zonelists(pg_data_t *pgdat, struct zone *zone)
3850 set_zonelist_order();
3852 if (system_state == SYSTEM_BOOTING) {
3853 __build_all_zonelists(NULL);
3854 mminit_verify_zonelist();
3855 cpuset_init_current_mems_allowed();
3856 } else {
3857 #ifdef CONFIG_MEMORY_HOTPLUG
3858 if (zone)
3859 setup_zone_pageset(zone);
3860 #endif
3861 /* we have to stop all cpus to guarantee there is no user
3862 of zonelist */
3863 stop_machine(__build_all_zonelists, pgdat, NULL);
3864 /* cpuset refresh routine should be here */
3866 vm_total_pages = nr_free_pagecache_pages();
3868 * Disable grouping by mobility if the number of pages in the
3869 * system is too low to allow the mechanism to work. It would be
3870 * more accurate, but expensive to check per-zone. This check is
3871 * made on memory-hotadd so a system can start with mobility
3872 * disabled and enable it later
3874 if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES))
3875 page_group_by_mobility_disabled = 1;
3876 else
3877 page_group_by_mobility_disabled = 0;
3879 printk("Built %i zonelists in %s order, mobility grouping %s. "
3880 "Total pages: %ld\n",
3881 nr_online_nodes,
3882 zonelist_order_name[current_zonelist_order],
3883 page_group_by_mobility_disabled ? "off" : "on",
3884 vm_total_pages);
3885 #ifdef CONFIG_NUMA
3886 printk("Policy zone: %s\n", zone_names[policy_zone]);
3887 #endif
3891 * Helper functions to size the waitqueue hash table.
3892 * Essentially these want to choose hash table sizes sufficiently
3893 * large so that collisions trying to wait on pages are rare.
3894 * But in fact, the number of active page waitqueues on typical
3895 * systems is ridiculously low, less than 200. So this is even
3896 * conservative, even though it seems large.
3898 * The constant PAGES_PER_WAITQUEUE specifies the ratio of pages to
3899 * waitqueues, i.e. the size of the waitq table given the number of pages.
3901 #define PAGES_PER_WAITQUEUE 256
3903 #ifndef CONFIG_MEMORY_HOTPLUG
3904 static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
3906 unsigned long size = 1;
3908 pages /= PAGES_PER_WAITQUEUE;
3910 while (size < pages)
3911 size <<= 1;
3914 * Once we have dozens or even hundreds of threads sleeping
3915 * on IO we've got bigger problems than wait queue collision.
3916 * Limit the size of the wait table to a reasonable size.
3918 size = min(size, 4096UL);
3920 return max(size, 4UL);
3922 #else
3924 * A zone's size might be changed by hot-add, so it is not possible to determine
3925 * a suitable size for its wait_table. So we use the maximum size now.
3927 * The max wait table size = 4096 x sizeof(wait_queue_head_t). ie:
3929 * i386 (preemption config) : 4096 x 16 = 64Kbyte.
3930 * ia64, x86-64 (no preemption): 4096 x 20 = 80Kbyte.
3931 * ia64, x86-64 (preemption) : 4096 x 24 = 96Kbyte.
3933 * The maximum entries are prepared when a zone's memory is (512K + 256) pages
3934 * or more by the traditional way. (See above). It equals:
3936 * i386, x86-64, powerpc(4K page size) : = ( 2G + 1M)byte.
3937 * ia64(16K page size) : = ( 8G + 4M)byte.
3938 * powerpc (64K page size) : = (32G +16M)byte.
3940 static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
3942 return 4096UL;
3944 #endif
3947 * This is an integer logarithm so that shifts can be used later
3948 * to extract the more random high bits from the multiplicative
3949 * hash function before the remainder is taken.
3951 static inline unsigned long wait_table_bits(unsigned long size)
3953 return ffz(~size);
3956 #define LONG_ALIGN(x) (((x)+(sizeof(long))-1)&~((sizeof(long))-1))
3959 * Check if a pageblock contains reserved pages
3961 static int pageblock_is_reserved(unsigned long start_pfn, unsigned long end_pfn)
3963 unsigned long pfn;
3965 for (pfn = start_pfn; pfn < end_pfn; pfn++) {
3966 if (!pfn_valid_within(pfn) || PageReserved(pfn_to_page(pfn)))
3967 return 1;
3969 return 0;
3973 * Mark a number of pageblocks as MIGRATE_RESERVE. The number
3974 * of blocks reserved is based on min_wmark_pages(zone). The memory within
3975 * the reserve will tend to store contiguous free pages. Setting min_free_kbytes
3976 * higher will lead to a bigger reserve which will get freed as contiguous
3977 * blocks as reclaim kicks in
3979 static void setup_zone_migrate_reserve(struct zone *zone)
3981 unsigned long start_pfn, pfn, end_pfn, block_end_pfn;
3982 struct page *page;
3983 unsigned long block_migratetype;
3984 int reserve;
3985 int old_reserve;
3988 * Get the start pfn, end pfn and the number of blocks to reserve
3989 * We have to be careful to be aligned to pageblock_nr_pages to
3990 * make sure that we always check pfn_valid for the first page in
3991 * the block.
3993 start_pfn = zone->zone_start_pfn;
3994 end_pfn = zone_end_pfn(zone);
3995 start_pfn = roundup(start_pfn, pageblock_nr_pages);
3996 reserve = roundup(min_wmark_pages(zone), pageblock_nr_pages) >>
3997 pageblock_order;
4000 * Reserve blocks are generally in place to help high-order atomic
4001 * allocations that are short-lived. A min_free_kbytes value that
4002 * would result in more than 2 reserve blocks for atomic allocations
4003 * is assumed to be in place to help anti-fragmentation for the
4004 * future allocation of hugepages at runtime.
4006 reserve = min(2, reserve);
4007 old_reserve = zone->nr_migrate_reserve_block;
4009 /* When memory hot-add, we almost always need to do nothing */
4010 if (reserve == old_reserve)
4011 return;
4012 zone->nr_migrate_reserve_block = reserve;
4014 for (pfn = start_pfn; pfn < end_pfn; pfn += pageblock_nr_pages) {
4015 if (!pfn_valid(pfn))
4016 continue;
4017 page = pfn_to_page(pfn);
4019 /* Watch out for overlapping nodes */
4020 if (page_to_nid(page) != zone_to_nid(zone))
4021 continue;
4023 block_migratetype = get_pageblock_migratetype(page);
4025 /* Only test what is necessary when the reserves are not met */
4026 if (reserve > 0) {
4028 * Blocks with reserved pages will never free, skip
4029 * them.
4031 block_end_pfn = min(pfn + pageblock_nr_pages, end_pfn);
4032 if (pageblock_is_reserved(pfn, block_end_pfn))
4033 continue;
4035 /* If this block is reserved, account for it */
4036 if (block_migratetype == MIGRATE_RESERVE) {
4037 reserve--;
4038 continue;
4041 /* Suitable for reserving if this block is movable */
4042 if (block_migratetype == MIGRATE_MOVABLE) {
4043 set_pageblock_migratetype(page,
4044 MIGRATE_RESERVE);
4045 move_freepages_block(zone, page,
4046 MIGRATE_RESERVE);
4047 reserve--;
4048 continue;
4050 } else if (!old_reserve) {
4052 * At boot time we don't need to scan the whole zone
4053 * for turning off MIGRATE_RESERVE.
4055 break;
4059 * If the reserve is met and this is a previous reserved block,
4060 * take it back
4062 if (block_migratetype == MIGRATE_RESERVE) {
4063 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
4064 move_freepages_block(zone, page, MIGRATE_MOVABLE);
4070 * Initially all pages are reserved - free ones are freed
4071 * up by free_all_bootmem() once the early boot process is
4072 * done. Non-atomic initialization, single-pass.
4074 void __meminit memmap_init_zone(unsigned long size, int nid, unsigned long zone,
4075 unsigned long start_pfn, enum memmap_context context)
4077 struct page *page;
4078 unsigned long end_pfn = start_pfn + size;
4079 unsigned long pfn;
4080 struct zone *z;
4082 if (highest_memmap_pfn < end_pfn - 1)
4083 highest_memmap_pfn = end_pfn - 1;
4085 z = &NODE_DATA(nid)->node_zones[zone];
4086 for (pfn = start_pfn; pfn < end_pfn; pfn++) {
4088 * There can be holes in boot-time mem_map[]s
4089 * handed to this function. They do not
4090 * exist on hotplugged memory.
4092 if (context == MEMMAP_EARLY) {
4093 if (!early_pfn_valid(pfn))
4094 continue;
4095 if (!early_pfn_in_nid(pfn, nid))
4096 continue;
4098 page = pfn_to_page(pfn);
4099 set_page_links(page, zone, nid, pfn);
4100 mminit_verify_page_links(page, zone, nid, pfn);
4101 init_page_count(page);
4102 page_mapcount_reset(page);
4103 page_nid_reset_last(page);
4104 SetPageReserved(page);
4106 * Mark the block movable so that blocks are reserved for
4107 * movable at startup. This will force kernel allocations
4108 * to reserve their blocks rather than leaking throughout
4109 * the address space during boot when many long-lived
4110 * kernel allocations are made. Later some blocks near
4111 * the start are marked MIGRATE_RESERVE by
4112 * setup_zone_migrate_reserve()
4114 * bitmap is created for zone's valid pfn range. but memmap
4115 * can be created for invalid pages (for alignment)
4116 * check here not to call set_pageblock_migratetype() against
4117 * pfn out of zone.
4119 if ((z->zone_start_pfn <= pfn)
4120 && (pfn < zone_end_pfn(z))
4121 && !(pfn & (pageblock_nr_pages - 1)))
4122 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
4124 INIT_LIST_HEAD(&page->lru);
4125 #ifdef WANT_PAGE_VIRTUAL
4126 /* The shift won't overflow because ZONE_NORMAL is below 4G. */
4127 if (!is_highmem_idx(zone))
4128 set_page_address(page, __va(pfn << PAGE_SHIFT));
4129 #endif
4133 static void __meminit zone_init_free_lists(struct zone *zone)
4135 unsigned int order, t;
4136 for_each_migratetype_order(order, t) {
4137 INIT_LIST_HEAD(&zone->free_area[order].free_list[t]);
4138 zone->free_area[order].nr_free = 0;
4142 #ifndef __HAVE_ARCH_MEMMAP_INIT
4143 #define memmap_init(size, nid, zone, start_pfn) \
4144 memmap_init_zone((size), (nid), (zone), (start_pfn), MEMMAP_EARLY)
4145 #endif
4147 static int zone_batchsize(struct zone *zone)
4149 #ifdef CONFIG_MMU
4150 int batch;
4153 * The per-cpu-pages pools are set to around 1000th of the
4154 * size of the zone. But no more than 1/2 of a meg.
4156 * OK, so we don't know how big the cache is. So guess.
4158 batch = zone->managed_pages / 1024;
4159 if (batch * PAGE_SIZE > 512 * 1024)
4160 batch = (512 * 1024) / PAGE_SIZE;
4161 batch /= 4; /* We effectively *= 4 below */
4162 if (batch < 1)
4163 batch = 1;
4166 * Clamp the batch to a 2^n - 1 value. Having a power
4167 * of 2 value was found to be more likely to have
4168 * suboptimal cache aliasing properties in some cases.
4170 * For example if 2 tasks are alternately allocating
4171 * batches of pages, one task can end up with a lot
4172 * of pages of one half of the possible page colors
4173 * and the other with pages of the other colors.
4175 batch = rounddown_pow_of_two(batch + batch/2) - 1;
4177 return batch;
4179 #else
4180 /* The deferral and batching of frees should be suppressed under NOMMU
4181 * conditions.
4183 * The problem is that NOMMU needs to be able to allocate large chunks
4184 * of contiguous memory as there's no hardware page translation to
4185 * assemble apparent contiguous memory from discontiguous pages.
4187 * Queueing large contiguous runs of pages for batching, however,
4188 * causes the pages to actually be freed in smaller chunks. As there
4189 * can be a significant delay between the individual batches being
4190 * recycled, this leads to the once large chunks of space being
4191 * fragmented and becoming unavailable for high-order allocations.
4193 return 0;
4194 #endif
4198 * pcp->high and pcp->batch values are related and dependent on one another:
4199 * ->batch must never be higher then ->high.
4200 * The following function updates them in a safe manner without read side
4201 * locking.
4203 * Any new users of pcp->batch and pcp->high should ensure they can cope with
4204 * those fields changing asynchronously (acording the the above rule).
4206 * mutex_is_locked(&pcp_batch_high_lock) required when calling this function
4207 * outside of boot time (or some other assurance that no concurrent updaters
4208 * exist).
4210 static void pageset_update(struct per_cpu_pages *pcp, unsigned long high,
4211 unsigned long batch)
4213 /* start with a fail safe value for batch */
4214 pcp->batch = 1;
4215 smp_wmb();
4217 /* Update high, then batch, in order */
4218 pcp->high = high;
4219 smp_wmb();
4221 pcp->batch = batch;
4224 /* a companion to pageset_set_high() */
4225 static void pageset_set_batch(struct per_cpu_pageset *p, unsigned long batch)
4227 pageset_update(&p->pcp, 6 * batch, max(1UL, 1 * batch));
4230 static void pageset_init(struct per_cpu_pageset *p)
4232 struct per_cpu_pages *pcp;
4233 int migratetype;
4235 memset(p, 0, sizeof(*p));
4237 pcp = &p->pcp;
4238 pcp->count = 0;
4239 for (migratetype = 0; migratetype < MIGRATE_PCPTYPES; migratetype++)
4240 INIT_LIST_HEAD(&pcp->lists[migratetype]);
4243 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch)
4245 pageset_init(p);
4246 pageset_set_batch(p, batch);
4250 * pageset_set_high() sets the high water mark for hot per_cpu_pagelist
4251 * to the value high for the pageset p.
4253 static void pageset_set_high(struct per_cpu_pageset *p,
4254 unsigned long high)
4256 unsigned long batch = max(1UL, high / 4);
4257 if ((high / 4) > (PAGE_SHIFT * 8))
4258 batch = PAGE_SHIFT * 8;
4260 pageset_update(&p->pcp, high, batch);
4263 static void pageset_set_high_and_batch(struct zone *zone,
4264 struct per_cpu_pageset *pcp)
4266 if (percpu_pagelist_fraction)
4267 pageset_set_high(pcp,
4268 (zone->managed_pages /
4269 percpu_pagelist_fraction));
4270 else
4271 pageset_set_batch(pcp, zone_batchsize(zone));
4274 static void __meminit zone_pageset_init(struct zone *zone, int cpu)
4276 struct per_cpu_pageset *pcp = per_cpu_ptr(zone->pageset, cpu);
4278 pageset_init(pcp);
4279 pageset_set_high_and_batch(zone, pcp);
4282 static void __meminit setup_zone_pageset(struct zone *zone)
4284 int cpu;
4285 zone->pageset = alloc_percpu(struct per_cpu_pageset);
4286 for_each_possible_cpu(cpu)
4287 zone_pageset_init(zone, cpu);
4291 * Allocate per cpu pagesets and initialize them.
4292 * Before this call only boot pagesets were available.
4294 void __init setup_per_cpu_pageset(void)
4296 struct zone *zone;
4298 for_each_populated_zone(zone)
4299 setup_zone_pageset(zone);
4302 static noinline __init_refok
4303 int zone_wait_table_init(struct zone *zone, unsigned long zone_size_pages)
4305 int i;
4306 struct pglist_data *pgdat = zone->zone_pgdat;
4307 size_t alloc_size;
4310 * The per-page waitqueue mechanism uses hashed waitqueues
4311 * per zone.
4313 zone->wait_table_hash_nr_entries =
4314 wait_table_hash_nr_entries(zone_size_pages);
4315 zone->wait_table_bits =
4316 wait_table_bits(zone->wait_table_hash_nr_entries);
4317 alloc_size = zone->wait_table_hash_nr_entries
4318 * sizeof(wait_queue_head_t);
4320 if (!slab_is_available()) {
4321 zone->wait_table = (wait_queue_head_t *)
4322 alloc_bootmem_node_nopanic(pgdat, alloc_size);
4323 } else {
4325 * This case means that a zone whose size was 0 gets new memory
4326 * via memory hot-add.
4327 * But it may be the case that a new node was hot-added. In
4328 * this case vmalloc() will not be able to use this new node's
4329 * memory - this wait_table must be initialized to use this new
4330 * node itself as well.
4331 * To use this new node's memory, further consideration will be
4332 * necessary.
4334 zone->wait_table = vmalloc(alloc_size);
4336 if (!zone->wait_table)
4337 return -ENOMEM;
4339 for (i = 0; i < zone->wait_table_hash_nr_entries; ++i)
4340 init_waitqueue_head(zone->wait_table + i);
4342 return 0;
4345 static __meminit void zone_pcp_init(struct zone *zone)
4348 * per cpu subsystem is not up at this point. The following code
4349 * relies on the ability of the linker to provide the
4350 * offset of a (static) per cpu variable into the per cpu area.
4352 zone->pageset = &boot_pageset;
4354 if (zone->present_pages)
4355 printk(KERN_DEBUG " %s zone: %lu pages, LIFO batch:%u\n",
4356 zone->name, zone->present_pages,
4357 zone_batchsize(zone));
4360 int __meminit init_currently_empty_zone(struct zone *zone,
4361 unsigned long zone_start_pfn,
4362 unsigned long size,
4363 enum memmap_context context)
4365 struct pglist_data *pgdat = zone->zone_pgdat;
4366 int ret;
4367 ret = zone_wait_table_init(zone, size);
4368 if (ret)
4369 return ret;
4370 pgdat->nr_zones = zone_idx(zone) + 1;
4372 zone->zone_start_pfn = zone_start_pfn;
4374 mminit_dprintk(MMINIT_TRACE, "memmap_init",
4375 "Initialising map node %d zone %lu pfns %lu -> %lu\n",
4376 pgdat->node_id,
4377 (unsigned long)zone_idx(zone),
4378 zone_start_pfn, (zone_start_pfn + size));
4380 zone_init_free_lists(zone);
4382 return 0;
4385 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
4386 #ifndef CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID
4388 * Required by SPARSEMEM. Given a PFN, return what node the PFN is on.
4389 * Architectures may implement their own version but if add_active_range()
4390 * was used and there are no special requirements, this is a convenient
4391 * alternative
4393 int __meminit __early_pfn_to_nid(unsigned long pfn)
4395 unsigned long start_pfn, end_pfn;
4396 int nid;
4398 * NOTE: The following SMP-unsafe globals are only used early in boot
4399 * when the kernel is running single-threaded.
4401 static unsigned long __meminitdata last_start_pfn, last_end_pfn;
4402 static int __meminitdata last_nid;
4404 if (last_start_pfn <= pfn && pfn < last_end_pfn)
4405 return last_nid;
4407 nid = memblock_search_pfn_nid(pfn, &start_pfn, &end_pfn);
4408 if (nid != -1) {
4409 last_start_pfn = start_pfn;
4410 last_end_pfn = end_pfn;
4411 last_nid = nid;
4414 return nid;
4416 #endif /* CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID */
4418 int __meminit early_pfn_to_nid(unsigned long pfn)
4420 int nid;
4422 nid = __early_pfn_to_nid(pfn);
4423 if (nid >= 0)
4424 return nid;
4425 /* just returns 0 */
4426 return 0;
4429 #ifdef CONFIG_NODES_SPAN_OTHER_NODES
4430 bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
4432 int nid;
4434 nid = __early_pfn_to_nid(pfn);
4435 if (nid >= 0 && nid != node)
4436 return false;
4437 return true;
4439 #endif
4442 * free_bootmem_with_active_regions - Call free_bootmem_node for each active range
4443 * @nid: The node to free memory on. If MAX_NUMNODES, all nodes are freed.
4444 * @max_low_pfn: The highest PFN that will be passed to free_bootmem_node
4446 * If an architecture guarantees that all ranges registered with
4447 * add_active_ranges() contain no holes and may be freed, this
4448 * this function may be used instead of calling free_bootmem() manually.
4450 void __init free_bootmem_with_active_regions(int nid, unsigned long max_low_pfn)
4452 unsigned long start_pfn, end_pfn;
4453 int i, this_nid;
4455 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, &this_nid) {
4456 start_pfn = min(start_pfn, max_low_pfn);
4457 end_pfn = min(end_pfn, max_low_pfn);
4459 if (start_pfn < end_pfn)
4460 free_bootmem_node(NODE_DATA(this_nid),
4461 PFN_PHYS(start_pfn),
4462 (end_pfn - start_pfn) << PAGE_SHIFT);
4467 * sparse_memory_present_with_active_regions - Call memory_present for each active range
4468 * @nid: The node to call memory_present for. If MAX_NUMNODES, all nodes will be used.
4470 * If an architecture guarantees that all ranges registered with
4471 * add_active_ranges() contain no holes and may be freed, this
4472 * function may be used instead of calling memory_present() manually.
4474 void __init sparse_memory_present_with_active_regions(int nid)
4476 unsigned long start_pfn, end_pfn;
4477 int i, this_nid;
4479 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, &this_nid)
4480 memory_present(this_nid, start_pfn, end_pfn);
4484 * get_pfn_range_for_nid - Return the start and end page frames for a node
4485 * @nid: The nid to return the range for. If MAX_NUMNODES, the min and max PFN are returned.
4486 * @start_pfn: Passed by reference. On return, it will have the node start_pfn.
4487 * @end_pfn: Passed by reference. On return, it will have the node end_pfn.
4489 * It returns the start and end page frame of a node based on information
4490 * provided by an arch calling add_active_range(). If called for a node
4491 * with no available memory, a warning is printed and the start and end
4492 * PFNs will be 0.
4494 void __meminit get_pfn_range_for_nid(unsigned int nid,
4495 unsigned long *start_pfn, unsigned long *end_pfn)
4497 unsigned long this_start_pfn, this_end_pfn;
4498 int i;
4500 *start_pfn = -1UL;
4501 *end_pfn = 0;
4503 for_each_mem_pfn_range(i, nid, &this_start_pfn, &this_end_pfn, NULL) {
4504 *start_pfn = min(*start_pfn, this_start_pfn);
4505 *end_pfn = max(*end_pfn, this_end_pfn);
4508 if (*start_pfn == -1UL)
4509 *start_pfn = 0;
4513 * This finds a zone that can be used for ZONE_MOVABLE pages. The
4514 * assumption is made that zones within a node are ordered in monotonic
4515 * increasing memory addresses so that the "highest" populated zone is used
4517 static void __init find_usable_zone_for_movable(void)
4519 int zone_index;
4520 for (zone_index = MAX_NR_ZONES - 1; zone_index >= 0; zone_index--) {
4521 if (zone_index == ZONE_MOVABLE)
4522 continue;
4524 if (arch_zone_highest_possible_pfn[zone_index] >
4525 arch_zone_lowest_possible_pfn[zone_index])
4526 break;
4529 VM_BUG_ON(zone_index == -1);
4530 movable_zone = zone_index;
4534 * The zone ranges provided by the architecture do not include ZONE_MOVABLE
4535 * because it is sized independent of architecture. Unlike the other zones,
4536 * the starting point for ZONE_MOVABLE is not fixed. It may be different
4537 * in each node depending on the size of each node and how evenly kernelcore
4538 * is distributed. This helper function adjusts the zone ranges
4539 * provided by the architecture for a given node by using the end of the
4540 * highest usable zone for ZONE_MOVABLE. This preserves the assumption that
4541 * zones within a node are in order of monotonic increases memory addresses
4543 static void __meminit adjust_zone_range_for_zone_movable(int nid,
4544 unsigned long zone_type,
4545 unsigned long node_start_pfn,
4546 unsigned long node_end_pfn,
4547 unsigned long *zone_start_pfn,
4548 unsigned long *zone_end_pfn)
4550 /* Only adjust if ZONE_MOVABLE is on this node */
4551 if (zone_movable_pfn[nid]) {
4552 /* Size ZONE_MOVABLE */
4553 if (zone_type == ZONE_MOVABLE) {
4554 *zone_start_pfn = zone_movable_pfn[nid];
4555 *zone_end_pfn = min(node_end_pfn,
4556 arch_zone_highest_possible_pfn[movable_zone]);
4558 /* Adjust for ZONE_MOVABLE starting within this range */
4559 } else if (*zone_start_pfn < zone_movable_pfn[nid] &&
4560 *zone_end_pfn > zone_movable_pfn[nid]) {
4561 *zone_end_pfn = zone_movable_pfn[nid];
4563 /* Check if this whole range is within ZONE_MOVABLE */
4564 } else if (*zone_start_pfn >= zone_movable_pfn[nid])
4565 *zone_start_pfn = *zone_end_pfn;
4570 * Return the number of pages a zone spans in a node, including holes
4571 * present_pages = zone_spanned_pages_in_node() - zone_absent_pages_in_node()
4573 static unsigned long __meminit zone_spanned_pages_in_node(int nid,
4574 unsigned long zone_type,
4575 unsigned long node_start_pfn,
4576 unsigned long node_end_pfn,
4577 unsigned long *ignored)
4579 unsigned long zone_start_pfn, zone_end_pfn;
4581 /* Get the start and end of the zone */
4582 zone_start_pfn = arch_zone_lowest_possible_pfn[zone_type];
4583 zone_end_pfn = arch_zone_highest_possible_pfn[zone_type];
4584 adjust_zone_range_for_zone_movable(nid, zone_type,
4585 node_start_pfn, node_end_pfn,
4586 &zone_start_pfn, &zone_end_pfn);
4588 /* Check that this node has pages within the zone's required range */
4589 if (zone_end_pfn < node_start_pfn || zone_start_pfn > node_end_pfn)
4590 return 0;
4592 /* Move the zone boundaries inside the node if necessary */
4593 zone_end_pfn = min(zone_end_pfn, node_end_pfn);
4594 zone_start_pfn = max(zone_start_pfn, node_start_pfn);
4596 /* Return the spanned pages */
4597 return zone_end_pfn - zone_start_pfn;
4601 * Return the number of holes in a range on a node. If nid is MAX_NUMNODES,
4602 * then all holes in the requested range will be accounted for.
4604 unsigned long __meminit __absent_pages_in_range(int nid,
4605 unsigned long range_start_pfn,
4606 unsigned long range_end_pfn)
4608 unsigned long nr_absent = range_end_pfn - range_start_pfn;
4609 unsigned long start_pfn, end_pfn;
4610 int i;
4612 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
4613 start_pfn = clamp(start_pfn, range_start_pfn, range_end_pfn);
4614 end_pfn = clamp(end_pfn, range_start_pfn, range_end_pfn);
4615 nr_absent -= end_pfn - start_pfn;
4617 return nr_absent;
4621 * absent_pages_in_range - Return number of page frames in holes within a range
4622 * @start_pfn: The start PFN to start searching for holes
4623 * @end_pfn: The end PFN to stop searching for holes
4625 * It returns the number of pages frames in memory holes within a range.
4627 unsigned long __init absent_pages_in_range(unsigned long start_pfn,
4628 unsigned long end_pfn)
4630 return __absent_pages_in_range(MAX_NUMNODES, start_pfn, end_pfn);
4633 /* Return the number of page frames in holes in a zone on a node */
4634 static unsigned long __meminit zone_absent_pages_in_node(int nid,
4635 unsigned long zone_type,
4636 unsigned long node_start_pfn,
4637 unsigned long node_end_pfn,
4638 unsigned long *ignored)
4640 unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type];
4641 unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type];
4642 unsigned long zone_start_pfn, zone_end_pfn;
4644 zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high);
4645 zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high);
4647 adjust_zone_range_for_zone_movable(nid, zone_type,
4648 node_start_pfn, node_end_pfn,
4649 &zone_start_pfn, &zone_end_pfn);
4650 return __absent_pages_in_range(nid, zone_start_pfn, zone_end_pfn);
4653 #else /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
4654 static inline unsigned long __meminit zone_spanned_pages_in_node(int nid,
4655 unsigned long zone_type,
4656 unsigned long node_start_pfn,
4657 unsigned long node_end_pfn,
4658 unsigned long *zones_size)
4660 return zones_size[zone_type];
4663 static inline unsigned long __meminit zone_absent_pages_in_node(int nid,
4664 unsigned long zone_type,
4665 unsigned long node_start_pfn,
4666 unsigned long node_end_pfn,
4667 unsigned long *zholes_size)
4669 if (!zholes_size)
4670 return 0;
4672 return zholes_size[zone_type];
4675 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
4677 static void __meminit calculate_node_totalpages(struct pglist_data *pgdat,
4678 unsigned long node_start_pfn,
4679 unsigned long node_end_pfn,
4680 unsigned long *zones_size,
4681 unsigned long *zholes_size)
4683 unsigned long realtotalpages, totalpages = 0;
4684 enum zone_type i;
4686 for (i = 0; i < MAX_NR_ZONES; i++)
4687 totalpages += zone_spanned_pages_in_node(pgdat->node_id, i,
4688 node_start_pfn,
4689 node_end_pfn,
4690 zones_size);
4691 pgdat->node_spanned_pages = totalpages;
4693 realtotalpages = totalpages;
4694 for (i = 0; i < MAX_NR_ZONES; i++)
4695 realtotalpages -=
4696 zone_absent_pages_in_node(pgdat->node_id, i,
4697 node_start_pfn, node_end_pfn,
4698 zholes_size);
4699 pgdat->node_present_pages = realtotalpages;
4700 printk(KERN_DEBUG "On node %d totalpages: %lu\n", pgdat->node_id,
4701 realtotalpages);
4704 #ifndef CONFIG_SPARSEMEM
4706 * Calculate the size of the zone->blockflags rounded to an unsigned long
4707 * Start by making sure zonesize is a multiple of pageblock_order by rounding
4708 * up. Then use 1 NR_PAGEBLOCK_BITS worth of bits per pageblock, finally
4709 * round what is now in bits to nearest long in bits, then return it in
4710 * bytes.
4712 static unsigned long __init usemap_size(unsigned long zone_start_pfn, unsigned long zonesize)
4714 unsigned long usemapsize;
4716 zonesize += zone_start_pfn & (pageblock_nr_pages-1);
4717 usemapsize = roundup(zonesize, pageblock_nr_pages);
4718 usemapsize = usemapsize >> pageblock_order;
4719 usemapsize *= NR_PAGEBLOCK_BITS;
4720 usemapsize = roundup(usemapsize, 8 * sizeof(unsigned long));
4722 return usemapsize / 8;
4725 static void __init setup_usemap(struct pglist_data *pgdat,
4726 struct zone *zone,
4727 unsigned long zone_start_pfn,
4728 unsigned long zonesize)
4730 unsigned long usemapsize = usemap_size(zone_start_pfn, zonesize);
4731 zone->pageblock_flags = NULL;
4732 if (usemapsize)
4733 zone->pageblock_flags = alloc_bootmem_node_nopanic(pgdat,
4734 usemapsize);
4736 #else
4737 static inline void setup_usemap(struct pglist_data *pgdat, struct zone *zone,
4738 unsigned long zone_start_pfn, unsigned long zonesize) {}
4739 #endif /* CONFIG_SPARSEMEM */
4741 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
4743 /* Initialise the number of pages represented by NR_PAGEBLOCK_BITS */
4744 void __paginginit set_pageblock_order(void)
4746 unsigned int order;
4748 /* Check that pageblock_nr_pages has not already been setup */
4749 if (pageblock_order)
4750 return;
4752 if (HPAGE_SHIFT > PAGE_SHIFT)
4753 order = HUGETLB_PAGE_ORDER;
4754 else
4755 order = MAX_ORDER - 1;
4758 * Assume the largest contiguous order of interest is a huge page.
4759 * This value may be variable depending on boot parameters on IA64 and
4760 * powerpc.
4762 pageblock_order = order;
4764 #else /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
4767 * When CONFIG_HUGETLB_PAGE_SIZE_VARIABLE is not set, set_pageblock_order()
4768 * is unused as pageblock_order is set at compile-time. See
4769 * include/linux/pageblock-flags.h for the values of pageblock_order based on
4770 * the kernel config
4772 void __paginginit set_pageblock_order(void)
4776 #endif /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
4778 static unsigned long __paginginit calc_memmap_size(unsigned long spanned_pages,
4779 unsigned long present_pages)
4781 unsigned long pages = spanned_pages;
4784 * Provide a more accurate estimation if there are holes within
4785 * the zone and SPARSEMEM is in use. If there are holes within the
4786 * zone, each populated memory region may cost us one or two extra
4787 * memmap pages due to alignment because memmap pages for each
4788 * populated regions may not naturally algined on page boundary.
4789 * So the (present_pages >> 4) heuristic is a tradeoff for that.
4791 if (spanned_pages > present_pages + (present_pages >> 4) &&
4792 IS_ENABLED(CONFIG_SPARSEMEM))
4793 pages = present_pages;
4795 return PAGE_ALIGN(pages * sizeof(struct page)) >> PAGE_SHIFT;
4799 * Set up the zone data structures:
4800 * - mark all pages reserved
4801 * - mark all memory queues empty
4802 * - clear the memory bitmaps
4804 * NOTE: pgdat should get zeroed by caller.
4806 static void __paginginit free_area_init_core(struct pglist_data *pgdat,
4807 unsigned long node_start_pfn, unsigned long node_end_pfn,
4808 unsigned long *zones_size, unsigned long *zholes_size)
4810 enum zone_type j;
4811 int nid = pgdat->node_id;
4812 unsigned long zone_start_pfn = pgdat->node_start_pfn;
4813 int ret;
4815 pgdat_resize_init(pgdat);
4816 #ifdef CONFIG_NUMA_BALANCING
4817 spin_lock_init(&pgdat->numabalancing_migrate_lock);
4818 pgdat->numabalancing_migrate_nr_pages = 0;
4819 pgdat->numabalancing_migrate_next_window = jiffies;
4820 #endif
4821 init_waitqueue_head(&pgdat->kswapd_wait);
4822 init_waitqueue_head(&pgdat->pfmemalloc_wait);
4823 pgdat_page_cgroup_init(pgdat);
4825 for (j = 0; j < MAX_NR_ZONES; j++) {
4826 struct zone *zone = pgdat->node_zones + j;
4827 unsigned long size, realsize, freesize, memmap_pages;
4829 size = zone_spanned_pages_in_node(nid, j, node_start_pfn,
4830 node_end_pfn, zones_size);
4831 realsize = freesize = size - zone_absent_pages_in_node(nid, j,
4832 node_start_pfn,
4833 node_end_pfn,
4834 zholes_size);
4837 * Adjust freesize so that it accounts for how much memory
4838 * is used by this zone for memmap. This affects the watermark
4839 * and per-cpu initialisations
4841 memmap_pages = calc_memmap_size(size, realsize);
4842 if (freesize >= memmap_pages) {
4843 freesize -= memmap_pages;
4844 if (memmap_pages)
4845 printk(KERN_DEBUG
4846 " %s zone: %lu pages used for memmap\n",
4847 zone_names[j], memmap_pages);
4848 } else
4849 printk(KERN_WARNING
4850 " %s zone: %lu pages exceeds freesize %lu\n",
4851 zone_names[j], memmap_pages, freesize);
4853 /* Account for reserved pages */
4854 if (j == 0 && freesize > dma_reserve) {
4855 freesize -= dma_reserve;
4856 printk(KERN_DEBUG " %s zone: %lu pages reserved\n",
4857 zone_names[0], dma_reserve);
4860 if (!is_highmem_idx(j))
4861 nr_kernel_pages += freesize;
4862 /* Charge for highmem memmap if there are enough kernel pages */
4863 else if (nr_kernel_pages > memmap_pages * 2)
4864 nr_kernel_pages -= memmap_pages;
4865 nr_all_pages += freesize;
4867 zone->spanned_pages = size;
4868 zone->present_pages = realsize;
4870 * Set an approximate value for lowmem here, it will be adjusted
4871 * when the bootmem allocator frees pages into the buddy system.
4872 * And all highmem pages will be managed by the buddy system.
4874 zone->managed_pages = is_highmem_idx(j) ? realsize : freesize;
4875 #ifdef CONFIG_NUMA
4876 zone->node = nid;
4877 zone->min_unmapped_pages = (freesize*sysctl_min_unmapped_ratio)
4878 / 100;
4879 zone->min_slab_pages = (freesize * sysctl_min_slab_ratio) / 100;
4880 #endif
4881 zone->name = zone_names[j];
4882 spin_lock_init(&zone->lock);
4883 spin_lock_init(&zone->lru_lock);
4884 zone_seqlock_init(zone);
4885 zone->zone_pgdat = pgdat;
4886 zone_pcp_init(zone);
4888 /* For bootup, initialized properly in watermark setup */
4889 mod_zone_page_state(zone, NR_ALLOC_BATCH, zone->managed_pages);
4891 lruvec_init(&zone->lruvec);
4892 if (!size)
4893 continue;
4895 set_pageblock_order();
4896 setup_usemap(pgdat, zone, zone_start_pfn, size);
4897 ret = init_currently_empty_zone(zone, zone_start_pfn,
4898 size, MEMMAP_EARLY);
4899 BUG_ON(ret);
4900 memmap_init(size, nid, j, zone_start_pfn);
4901 zone_start_pfn += size;
4905 static void __init_refok alloc_node_mem_map(struct pglist_data *pgdat)
4907 /* Skip empty nodes */
4908 if (!pgdat->node_spanned_pages)
4909 return;
4911 #ifdef CONFIG_FLAT_NODE_MEM_MAP
4912 /* ia64 gets its own node_mem_map, before this, without bootmem */
4913 if (!pgdat->node_mem_map) {
4914 unsigned long size, start, end;
4915 struct page *map;
4918 * The zone's endpoints aren't required to be MAX_ORDER
4919 * aligned but the node_mem_map endpoints must be in order
4920 * for the buddy allocator to function correctly.
4922 start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1);
4923 end = pgdat_end_pfn(pgdat);
4924 end = ALIGN(end, MAX_ORDER_NR_PAGES);
4925 size = (end - start) * sizeof(struct page);
4926 map = alloc_remap(pgdat->node_id, size);
4927 if (!map)
4928 map = alloc_bootmem_node_nopanic(pgdat, size);
4929 pgdat->node_mem_map = map + (pgdat->node_start_pfn - start);
4931 #ifndef CONFIG_NEED_MULTIPLE_NODES
4933 * With no DISCONTIG, the global mem_map is just set as node 0's
4935 if (pgdat == NODE_DATA(0)) {
4936 mem_map = NODE_DATA(0)->node_mem_map;
4937 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
4938 if (page_to_pfn(mem_map) != pgdat->node_start_pfn)
4939 mem_map -= (pgdat->node_start_pfn - ARCH_PFN_OFFSET);
4940 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
4942 #endif
4943 #endif /* CONFIG_FLAT_NODE_MEM_MAP */
4946 void __paginginit free_area_init_node(int nid, unsigned long *zones_size,
4947 unsigned long node_start_pfn, unsigned long *zholes_size)
4949 pg_data_t *pgdat = NODE_DATA(nid);
4950 unsigned long start_pfn = 0;
4951 unsigned long end_pfn = 0;
4953 /* pg_data_t should be reset to zero when it's allocated */
4954 WARN_ON(pgdat->nr_zones || pgdat->classzone_idx);
4956 pgdat->node_id = nid;
4957 pgdat->node_start_pfn = node_start_pfn;
4958 if (node_state(nid, N_MEMORY))
4959 init_zone_allows_reclaim(nid);
4960 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
4961 get_pfn_range_for_nid(nid, &start_pfn, &end_pfn);
4962 #endif
4963 calculate_node_totalpages(pgdat, start_pfn, end_pfn,
4964 zones_size, zholes_size);
4966 alloc_node_mem_map(pgdat);
4967 #ifdef CONFIG_FLAT_NODE_MEM_MAP
4968 printk(KERN_DEBUG "free_area_init_node: node %d, pgdat %08lx, node_mem_map %08lx\n",
4969 nid, (unsigned long)pgdat,
4970 (unsigned long)pgdat->node_mem_map);
4971 #endif
4973 free_area_init_core(pgdat, start_pfn, end_pfn,
4974 zones_size, zholes_size);
4977 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
4979 #if MAX_NUMNODES > 1
4981 * Figure out the number of possible node ids.
4983 void __init setup_nr_node_ids(void)
4985 unsigned int node;
4986 unsigned int highest = 0;
4988 for_each_node_mask(node, node_possible_map)
4989 highest = node;
4990 nr_node_ids = highest + 1;
4992 #endif
4995 * node_map_pfn_alignment - determine the maximum internode alignment
4997 * This function should be called after node map is populated and sorted.
4998 * It calculates the maximum power of two alignment which can distinguish
4999 * all the nodes.
5001 * For example, if all nodes are 1GiB and aligned to 1GiB, the return value
5002 * would indicate 1GiB alignment with (1 << (30 - PAGE_SHIFT)). If the
5003 * nodes are shifted by 256MiB, 256MiB. Note that if only the last node is
5004 * shifted, 1GiB is enough and this function will indicate so.
5006 * This is used to test whether pfn -> nid mapping of the chosen memory
5007 * model has fine enough granularity to avoid incorrect mapping for the
5008 * populated node map.
5010 * Returns the determined alignment in pfn's. 0 if there is no alignment
5011 * requirement (single node).
5013 unsigned long __init node_map_pfn_alignment(void)
5015 unsigned long accl_mask = 0, last_end = 0;
5016 unsigned long start, end, mask;
5017 int last_nid = -1;
5018 int i, nid;
5020 for_each_mem_pfn_range(i, MAX_NUMNODES, &start, &end, &nid) {
5021 if (!start || last_nid < 0 || last_nid == nid) {
5022 last_nid = nid;
5023 last_end = end;
5024 continue;
5028 * Start with a mask granular enough to pin-point to the
5029 * start pfn and tick off bits one-by-one until it becomes
5030 * too coarse to separate the current node from the last.
5032 mask = ~((1 << __ffs(start)) - 1);
5033 while (mask && last_end <= (start & (mask << 1)))
5034 mask <<= 1;
5036 /* accumulate all internode masks */
5037 accl_mask |= mask;
5040 /* convert mask to number of pages */
5041 return ~accl_mask + 1;
5044 /* Find the lowest pfn for a node */
5045 static unsigned long __init find_min_pfn_for_node(int nid)
5047 unsigned long min_pfn = ULONG_MAX;
5048 unsigned long start_pfn;
5049 int i;
5051 for_each_mem_pfn_range(i, nid, &start_pfn, NULL, NULL)
5052 min_pfn = min(min_pfn, start_pfn);
5054 if (min_pfn == ULONG_MAX) {
5055 printk(KERN_WARNING
5056 "Could not find start_pfn for node %d\n", nid);
5057 return 0;
5060 return min_pfn;
5064 * find_min_pfn_with_active_regions - Find the minimum PFN registered
5066 * It returns the minimum PFN based on information provided via
5067 * add_active_range().
5069 unsigned long __init find_min_pfn_with_active_regions(void)
5071 return find_min_pfn_for_node(MAX_NUMNODES);
5075 * early_calculate_totalpages()
5076 * Sum pages in active regions for movable zone.
5077 * Populate N_MEMORY for calculating usable_nodes.
5079 static unsigned long __init early_calculate_totalpages(void)
5081 unsigned long totalpages = 0;
5082 unsigned long start_pfn, end_pfn;
5083 int i, nid;
5085 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
5086 unsigned long pages = end_pfn - start_pfn;
5088 totalpages += pages;
5089 if (pages)
5090 node_set_state(nid, N_MEMORY);
5092 return totalpages;
5096 * Find the PFN the Movable zone begins in each node. Kernel memory
5097 * is spread evenly between nodes as long as the nodes have enough
5098 * memory. When they don't, some nodes will have more kernelcore than
5099 * others
5101 static void __init find_zone_movable_pfns_for_nodes(void)
5103 int i, nid;
5104 unsigned long usable_startpfn;
5105 unsigned long kernelcore_node, kernelcore_remaining;
5106 /* save the state before borrow the nodemask */
5107 nodemask_t saved_node_state = node_states[N_MEMORY];
5108 unsigned long totalpages = early_calculate_totalpages();
5109 int usable_nodes = nodes_weight(node_states[N_MEMORY]);
5112 * If movablecore was specified, calculate what size of
5113 * kernelcore that corresponds so that memory usable for
5114 * any allocation type is evenly spread. If both kernelcore
5115 * and movablecore are specified, then the value of kernelcore
5116 * will be used for required_kernelcore if it's greater than
5117 * what movablecore would have allowed.
5119 if (required_movablecore) {
5120 unsigned long corepages;
5123 * Round-up so that ZONE_MOVABLE is at least as large as what
5124 * was requested by the user
5126 required_movablecore =
5127 roundup(required_movablecore, MAX_ORDER_NR_PAGES);
5128 corepages = totalpages - required_movablecore;
5130 required_kernelcore = max(required_kernelcore, corepages);
5133 /* If kernelcore was not specified, there is no ZONE_MOVABLE */
5134 if (!required_kernelcore)
5135 goto out;
5137 /* usable_startpfn is the lowest possible pfn ZONE_MOVABLE can be at */
5138 find_usable_zone_for_movable();
5139 usable_startpfn = arch_zone_lowest_possible_pfn[movable_zone];
5141 restart:
5142 /* Spread kernelcore memory as evenly as possible throughout nodes */
5143 kernelcore_node = required_kernelcore / usable_nodes;
5144 for_each_node_state(nid, N_MEMORY) {
5145 unsigned long start_pfn, end_pfn;
5148 * Recalculate kernelcore_node if the division per node
5149 * now exceeds what is necessary to satisfy the requested
5150 * amount of memory for the kernel
5152 if (required_kernelcore < kernelcore_node)
5153 kernelcore_node = required_kernelcore / usable_nodes;
5156 * As the map is walked, we track how much memory is usable
5157 * by the kernel using kernelcore_remaining. When it is
5158 * 0, the rest of the node is usable by ZONE_MOVABLE
5160 kernelcore_remaining = kernelcore_node;
5162 /* Go through each range of PFNs within this node */
5163 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
5164 unsigned long size_pages;
5166 start_pfn = max(start_pfn, zone_movable_pfn[nid]);
5167 if (start_pfn >= end_pfn)
5168 continue;
5170 /* Account for what is only usable for kernelcore */
5171 if (start_pfn < usable_startpfn) {
5172 unsigned long kernel_pages;
5173 kernel_pages = min(end_pfn, usable_startpfn)
5174 - start_pfn;
5176 kernelcore_remaining -= min(kernel_pages,
5177 kernelcore_remaining);
5178 required_kernelcore -= min(kernel_pages,
5179 required_kernelcore);
5181 /* Continue if range is now fully accounted */
5182 if (end_pfn <= usable_startpfn) {
5185 * Push zone_movable_pfn to the end so
5186 * that if we have to rebalance
5187 * kernelcore across nodes, we will
5188 * not double account here
5190 zone_movable_pfn[nid] = end_pfn;
5191 continue;
5193 start_pfn = usable_startpfn;
5197 * The usable PFN range for ZONE_MOVABLE is from
5198 * start_pfn->end_pfn. Calculate size_pages as the
5199 * number of pages used as kernelcore
5201 size_pages = end_pfn - start_pfn;
5202 if (size_pages > kernelcore_remaining)
5203 size_pages = kernelcore_remaining;
5204 zone_movable_pfn[nid] = start_pfn + size_pages;
5207 * Some kernelcore has been met, update counts and
5208 * break if the kernelcore for this node has been
5209 * satisfied
5211 required_kernelcore -= min(required_kernelcore,
5212 size_pages);
5213 kernelcore_remaining -= size_pages;
5214 if (!kernelcore_remaining)
5215 break;
5220 * If there is still required_kernelcore, we do another pass with one
5221 * less node in the count. This will push zone_movable_pfn[nid] further
5222 * along on the nodes that still have memory until kernelcore is
5223 * satisfied
5225 usable_nodes--;
5226 if (usable_nodes && required_kernelcore > usable_nodes)
5227 goto restart;
5229 /* Align start of ZONE_MOVABLE on all nids to MAX_ORDER_NR_PAGES */
5230 for (nid = 0; nid < MAX_NUMNODES; nid++)
5231 zone_movable_pfn[nid] =
5232 roundup(zone_movable_pfn[nid], MAX_ORDER_NR_PAGES);
5234 out:
5235 /* restore the node_state */
5236 node_states[N_MEMORY] = saved_node_state;
5239 /* Any regular or high memory on that node ? */
5240 static void check_for_memory(pg_data_t *pgdat, int nid)
5242 enum zone_type zone_type;
5244 if (N_MEMORY == N_NORMAL_MEMORY)
5245 return;
5247 for (zone_type = 0; zone_type <= ZONE_MOVABLE - 1; zone_type++) {
5248 struct zone *zone = &pgdat->node_zones[zone_type];
5249 if (zone->present_pages) {
5250 node_set_state(nid, N_HIGH_MEMORY);
5251 if (N_NORMAL_MEMORY != N_HIGH_MEMORY &&
5252 zone_type <= ZONE_NORMAL)
5253 node_set_state(nid, N_NORMAL_MEMORY);
5254 break;
5260 * free_area_init_nodes - Initialise all pg_data_t and zone data
5261 * @max_zone_pfn: an array of max PFNs for each zone
5263 * This will call free_area_init_node() for each active node in the system.
5264 * Using the page ranges provided by add_active_range(), the size of each
5265 * zone in each node and their holes is calculated. If the maximum PFN
5266 * between two adjacent zones match, it is assumed that the zone is empty.
5267 * For example, if arch_max_dma_pfn == arch_max_dma32_pfn, it is assumed
5268 * that arch_max_dma32_pfn has no pages. It is also assumed that a zone
5269 * starts where the previous one ended. For example, ZONE_DMA32 starts
5270 * at arch_max_dma_pfn.
5272 void __init free_area_init_nodes(unsigned long *max_zone_pfn)
5274 unsigned long start_pfn, end_pfn;
5275 int i, nid;
5277 /* Record where the zone boundaries are */
5278 memset(arch_zone_lowest_possible_pfn, 0,
5279 sizeof(arch_zone_lowest_possible_pfn));
5280 memset(arch_zone_highest_possible_pfn, 0,
5281 sizeof(arch_zone_highest_possible_pfn));
5282 arch_zone_lowest_possible_pfn[0] = find_min_pfn_with_active_regions();
5283 arch_zone_highest_possible_pfn[0] = max_zone_pfn[0];
5284 for (i = 1; i < MAX_NR_ZONES; i++) {
5285 if (i == ZONE_MOVABLE)
5286 continue;
5287 arch_zone_lowest_possible_pfn[i] =
5288 arch_zone_highest_possible_pfn[i-1];
5289 arch_zone_highest_possible_pfn[i] =
5290 max(max_zone_pfn[i], arch_zone_lowest_possible_pfn[i]);
5292 arch_zone_lowest_possible_pfn[ZONE_MOVABLE] = 0;
5293 arch_zone_highest_possible_pfn[ZONE_MOVABLE] = 0;
5295 /* Find the PFNs that ZONE_MOVABLE begins at in each node */
5296 memset(zone_movable_pfn, 0, sizeof(zone_movable_pfn));
5297 find_zone_movable_pfns_for_nodes();
5299 /* Print out the zone ranges */
5300 printk("Zone ranges:\n");
5301 for (i = 0; i < MAX_NR_ZONES; i++) {
5302 if (i == ZONE_MOVABLE)
5303 continue;
5304 printk(KERN_CONT " %-8s ", zone_names[i]);
5305 if (arch_zone_lowest_possible_pfn[i] ==
5306 arch_zone_highest_possible_pfn[i])
5307 printk(KERN_CONT "empty\n");
5308 else
5309 printk(KERN_CONT "[mem %0#10lx-%0#10lx]\n",
5310 arch_zone_lowest_possible_pfn[i] << PAGE_SHIFT,
5311 (arch_zone_highest_possible_pfn[i]
5312 << PAGE_SHIFT) - 1);
5315 /* Print out the PFNs ZONE_MOVABLE begins at in each node */
5316 printk("Movable zone start for each node\n");
5317 for (i = 0; i < MAX_NUMNODES; i++) {
5318 if (zone_movable_pfn[i])
5319 printk(" Node %d: %#010lx\n", i,
5320 zone_movable_pfn[i] << PAGE_SHIFT);
5323 /* Print out the early node map */
5324 printk("Early memory node ranges\n");
5325 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid)
5326 printk(" node %3d: [mem %#010lx-%#010lx]\n", nid,
5327 start_pfn << PAGE_SHIFT, (end_pfn << PAGE_SHIFT) - 1);
5329 /* Initialise every node */
5330 mminit_verify_pageflags_layout();
5331 setup_nr_node_ids();
5332 for_each_online_node(nid) {
5333 pg_data_t *pgdat = NODE_DATA(nid);
5334 free_area_init_node(nid, NULL,
5335 find_min_pfn_for_node(nid), NULL);
5337 /* Any memory on that node */
5338 if (pgdat->node_present_pages)
5339 node_set_state(nid, N_MEMORY);
5340 check_for_memory(pgdat, nid);
5344 static int __init cmdline_parse_core(char *p, unsigned long *core)
5346 unsigned long long coremem;
5347 if (!p)
5348 return -EINVAL;
5350 coremem = memparse(p, &p);
5351 *core = coremem >> PAGE_SHIFT;
5353 /* Paranoid check that UL is enough for the coremem value */
5354 WARN_ON((coremem >> PAGE_SHIFT) > ULONG_MAX);
5356 return 0;
5360 * kernelcore=size sets the amount of memory for use for allocations that
5361 * cannot be reclaimed or migrated.
5363 static int __init cmdline_parse_kernelcore(char *p)
5365 return cmdline_parse_core(p, &required_kernelcore);
5369 * movablecore=size sets the amount of memory for use for allocations that
5370 * can be reclaimed or migrated.
5372 static int __init cmdline_parse_movablecore(char *p)
5374 return cmdline_parse_core(p, &required_movablecore);
5377 early_param("kernelcore", cmdline_parse_kernelcore);
5378 early_param("movablecore", cmdline_parse_movablecore);
5380 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
5382 void adjust_managed_page_count(struct page *page, long count)
5384 spin_lock(&managed_page_count_lock);
5385 page_zone(page)->managed_pages += count;
5386 totalram_pages += count;
5387 #ifdef CONFIG_HIGHMEM
5388 if (PageHighMem(page))
5389 totalhigh_pages += count;
5390 #endif
5391 spin_unlock(&managed_page_count_lock);
5393 EXPORT_SYMBOL(adjust_managed_page_count);
5395 unsigned long free_reserved_area(void *start, void *end, int poison, char *s)
5397 void *pos;
5398 unsigned long pages = 0;
5400 start = (void *)PAGE_ALIGN((unsigned long)start);
5401 end = (void *)((unsigned long)end & PAGE_MASK);
5402 for (pos = start; pos < end; pos += PAGE_SIZE, pages++) {
5403 if ((unsigned int)poison <= 0xFF)
5404 memset(pos, poison, PAGE_SIZE);
5405 free_reserved_page(virt_to_page(pos));
5408 if (pages && s)
5409 pr_info("Freeing %s memory: %ldK (%p - %p)\n",
5410 s, pages << (PAGE_SHIFT - 10), start, end);
5412 return pages;
5414 EXPORT_SYMBOL(free_reserved_area);
5416 #ifdef CONFIG_HIGHMEM
5417 void free_highmem_page(struct page *page)
5419 __free_reserved_page(page);
5420 totalram_pages++;
5421 page_zone(page)->managed_pages++;
5422 totalhigh_pages++;
5424 #endif
5427 void __init mem_init_print_info(const char *str)
5429 unsigned long physpages, codesize, datasize, rosize, bss_size;
5430 unsigned long init_code_size, init_data_size;
5432 physpages = get_num_physpages();
5433 codesize = _etext - _stext;
5434 datasize = _edata - _sdata;
5435 rosize = __end_rodata - __start_rodata;
5436 bss_size = __bss_stop - __bss_start;
5437 init_data_size = __init_end - __init_begin;
5438 init_code_size = _einittext - _sinittext;
5441 * Detect special cases and adjust section sizes accordingly:
5442 * 1) .init.* may be embedded into .data sections
5443 * 2) .init.text.* may be out of [__init_begin, __init_end],
5444 * please refer to arch/tile/kernel/vmlinux.lds.S.
5445 * 3) .rodata.* may be embedded into .text or .data sections.
5447 #define adj_init_size(start, end, size, pos, adj) \
5448 do { \
5449 if (start <= pos && pos < end && size > adj) \
5450 size -= adj; \
5451 } while (0)
5453 adj_init_size(__init_begin, __init_end, init_data_size,
5454 _sinittext, init_code_size);
5455 adj_init_size(_stext, _etext, codesize, _sinittext, init_code_size);
5456 adj_init_size(_sdata, _edata, datasize, __init_begin, init_data_size);
5457 adj_init_size(_stext, _etext, codesize, __start_rodata, rosize);
5458 adj_init_size(_sdata, _edata, datasize, __start_rodata, rosize);
5460 #undef adj_init_size
5462 printk("Memory: %luK/%luK available "
5463 "(%luK kernel code, %luK rwdata, %luK rodata, "
5464 "%luK init, %luK bss, %luK reserved"
5465 #ifdef CONFIG_HIGHMEM
5466 ", %luK highmem"
5467 #endif
5468 "%s%s)\n",
5469 nr_free_pages() << (PAGE_SHIFT-10), physpages << (PAGE_SHIFT-10),
5470 codesize >> 10, datasize >> 10, rosize >> 10,
5471 (init_data_size + init_code_size) >> 10, bss_size >> 10,
5472 (physpages - totalram_pages) << (PAGE_SHIFT-10),
5473 #ifdef CONFIG_HIGHMEM
5474 totalhigh_pages << (PAGE_SHIFT-10),
5475 #endif
5476 str ? ", " : "", str ? str : "");
5480 * set_dma_reserve - set the specified number of pages reserved in the first zone
5481 * @new_dma_reserve: The number of pages to mark reserved
5483 * The per-cpu batchsize and zone watermarks are determined by present_pages.
5484 * In the DMA zone, a significant percentage may be consumed by kernel image
5485 * and other unfreeable allocations which can skew the watermarks badly. This
5486 * function may optionally be used to account for unfreeable pages in the
5487 * first zone (e.g., ZONE_DMA). The effect will be lower watermarks and
5488 * smaller per-cpu batchsize.
5490 void __init set_dma_reserve(unsigned long new_dma_reserve)
5492 dma_reserve = new_dma_reserve;
5495 void __init free_area_init(unsigned long *zones_size)
5497 free_area_init_node(0, zones_size,
5498 __pa(PAGE_OFFSET) >> PAGE_SHIFT, NULL);
5501 static int page_alloc_cpu_notify(struct notifier_block *self,
5502 unsigned long action, void *hcpu)
5504 int cpu = (unsigned long)hcpu;
5506 if (action == CPU_DEAD || action == CPU_DEAD_FROZEN) {
5507 lru_add_drain_cpu(cpu);
5508 drain_pages(cpu);
5511 * Spill the event counters of the dead processor
5512 * into the current processors event counters.
5513 * This artificially elevates the count of the current
5514 * processor.
5516 vm_events_fold_cpu(cpu);
5519 * Zero the differential counters of the dead processor
5520 * so that the vm statistics are consistent.
5522 * This is only okay since the processor is dead and cannot
5523 * race with what we are doing.
5525 cpu_vm_stats_fold(cpu);
5527 return NOTIFY_OK;
5530 void __init page_alloc_init(void)
5532 hotcpu_notifier(page_alloc_cpu_notify, 0);
5536 * calculate_totalreserve_pages - called when sysctl_lower_zone_reserve_ratio
5537 * or min_free_kbytes changes.
5539 static void calculate_totalreserve_pages(void)
5541 struct pglist_data *pgdat;
5542 unsigned long reserve_pages = 0;
5543 enum zone_type i, j;
5545 for_each_online_pgdat(pgdat) {
5546 for (i = 0; i < MAX_NR_ZONES; i++) {
5547 struct zone *zone = pgdat->node_zones + i;
5548 long max = 0;
5550 /* Find valid and maximum lowmem_reserve in the zone */
5551 for (j = i; j < MAX_NR_ZONES; j++) {
5552 if (zone->lowmem_reserve[j] > max)
5553 max = zone->lowmem_reserve[j];
5556 /* we treat the high watermark as reserved pages. */
5557 max += high_wmark_pages(zone);
5559 if (max > zone->managed_pages)
5560 max = zone->managed_pages;
5561 reserve_pages += max;
5563 * Lowmem reserves are not available to
5564 * GFP_HIGHUSER page cache allocations and
5565 * kswapd tries to balance zones to their high
5566 * watermark. As a result, neither should be
5567 * regarded as dirtyable memory, to prevent a
5568 * situation where reclaim has to clean pages
5569 * in order to balance the zones.
5571 zone->dirty_balance_reserve = max;
5574 dirty_balance_reserve = reserve_pages;
5575 totalreserve_pages = reserve_pages;
5579 * setup_per_zone_lowmem_reserve - called whenever
5580 * sysctl_lower_zone_reserve_ratio changes. Ensures that each zone
5581 * has a correct pages reserved value, so an adequate number of
5582 * pages are left in the zone after a successful __alloc_pages().
5584 static void setup_per_zone_lowmem_reserve(void)
5586 struct pglist_data *pgdat;
5587 enum zone_type j, idx;
5589 for_each_online_pgdat(pgdat) {
5590 for (j = 0; j < MAX_NR_ZONES; j++) {
5591 struct zone *zone = pgdat->node_zones + j;
5592 unsigned long managed_pages = zone->managed_pages;
5594 zone->lowmem_reserve[j] = 0;
5596 idx = j;
5597 while (idx) {
5598 struct zone *lower_zone;
5600 idx--;
5602 if (sysctl_lowmem_reserve_ratio[idx] < 1)
5603 sysctl_lowmem_reserve_ratio[idx] = 1;
5605 lower_zone = pgdat->node_zones + idx;
5606 lower_zone->lowmem_reserve[j] = managed_pages /
5607 sysctl_lowmem_reserve_ratio[idx];
5608 managed_pages += lower_zone->managed_pages;
5613 /* update totalreserve_pages */
5614 calculate_totalreserve_pages();
5617 static void __setup_per_zone_wmarks(void)
5619 unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
5620 unsigned long lowmem_pages = 0;
5621 struct zone *zone;
5622 unsigned long flags;
5624 /* Calculate total number of !ZONE_HIGHMEM pages */
5625 for_each_zone(zone) {
5626 if (!is_highmem(zone))
5627 lowmem_pages += zone->managed_pages;
5630 for_each_zone(zone) {
5631 u64 tmp;
5633 spin_lock_irqsave(&zone->lock, flags);
5634 tmp = (u64)pages_min * zone->managed_pages;
5635 do_div(tmp, lowmem_pages);
5636 if (is_highmem(zone)) {
5638 * __GFP_HIGH and PF_MEMALLOC allocations usually don't
5639 * need highmem pages, so cap pages_min to a small
5640 * value here.
5642 * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN)
5643 * deltas controls asynch page reclaim, and so should
5644 * not be capped for highmem.
5646 unsigned long min_pages;
5648 min_pages = zone->managed_pages / 1024;
5649 min_pages = clamp(min_pages, SWAP_CLUSTER_MAX, 128UL);
5650 zone->watermark[WMARK_MIN] = min_pages;
5651 } else {
5653 * If it's a lowmem zone, reserve a number of pages
5654 * proportionate to the zone's size.
5656 zone->watermark[WMARK_MIN] = tmp;
5659 zone->watermark[WMARK_LOW] = min_wmark_pages(zone) + (tmp >> 2);
5660 zone->watermark[WMARK_HIGH] = min_wmark_pages(zone) + (tmp >> 1);
5662 __mod_zone_page_state(zone, NR_ALLOC_BATCH,
5663 high_wmark_pages(zone) - low_wmark_pages(zone) -
5664 atomic_long_read(&zone->vm_stat[NR_ALLOC_BATCH]));
5666 setup_zone_migrate_reserve(zone);
5667 spin_unlock_irqrestore(&zone->lock, flags);
5670 /* update totalreserve_pages */
5671 calculate_totalreserve_pages();
5675 * setup_per_zone_wmarks - called when min_free_kbytes changes
5676 * or when memory is hot-{added|removed}
5678 * Ensures that the watermark[min,low,high] values for each zone are set
5679 * correctly with respect to min_free_kbytes.
5681 void setup_per_zone_wmarks(void)
5683 mutex_lock(&zonelists_mutex);
5684 __setup_per_zone_wmarks();
5685 mutex_unlock(&zonelists_mutex);
5689 * The inactive anon list should be small enough that the VM never has to
5690 * do too much work, but large enough that each inactive page has a chance
5691 * to be referenced again before it is swapped out.
5693 * The inactive_anon ratio is the target ratio of ACTIVE_ANON to
5694 * INACTIVE_ANON pages on this zone's LRU, maintained by the
5695 * pageout code. A zone->inactive_ratio of 3 means 3:1 or 25% of
5696 * the anonymous pages are kept on the inactive list.
5698 * total target max
5699 * memory ratio inactive anon
5700 * -------------------------------------
5701 * 10MB 1 5MB
5702 * 100MB 1 50MB
5703 * 1GB 3 250MB
5704 * 10GB 10 0.9GB
5705 * 100GB 31 3GB
5706 * 1TB 101 10GB
5707 * 10TB 320 32GB
5709 static void __meminit calculate_zone_inactive_ratio(struct zone *zone)
5711 unsigned int gb, ratio;
5713 /* Zone size in gigabytes */
5714 gb = zone->managed_pages >> (30 - PAGE_SHIFT);
5715 if (gb)
5716 ratio = int_sqrt(10 * gb);
5717 else
5718 ratio = 1;
5720 zone->inactive_ratio = ratio;
5723 static void __meminit setup_per_zone_inactive_ratio(void)
5725 struct zone *zone;
5727 for_each_zone(zone)
5728 calculate_zone_inactive_ratio(zone);
5732 * Initialise min_free_kbytes.
5734 * For small machines we want it small (128k min). For large machines
5735 * we want it large (64MB max). But it is not linear, because network
5736 * bandwidth does not increase linearly with machine size. We use
5738 * min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
5739 * min_free_kbytes = sqrt(lowmem_kbytes * 16)
5741 * which yields
5743 * 16MB: 512k
5744 * 32MB: 724k
5745 * 64MB: 1024k
5746 * 128MB: 1448k
5747 * 256MB: 2048k
5748 * 512MB: 2896k
5749 * 1024MB: 4096k
5750 * 2048MB: 5792k
5751 * 4096MB: 8192k
5752 * 8192MB: 11584k
5753 * 16384MB: 16384k
5755 int __meminit init_per_zone_wmark_min(void)
5757 unsigned long lowmem_kbytes;
5758 int new_min_free_kbytes;
5760 lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
5761 new_min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
5763 if (new_min_free_kbytes > user_min_free_kbytes) {
5764 min_free_kbytes = new_min_free_kbytes;
5765 if (min_free_kbytes < 128)
5766 min_free_kbytes = 128;
5767 if (min_free_kbytes > 65536)
5768 min_free_kbytes = 65536;
5769 } else {
5770 pr_warn("min_free_kbytes is not updated to %d because user defined value %d is preferred\n",
5771 new_min_free_kbytes, user_min_free_kbytes);
5773 setup_per_zone_wmarks();
5774 refresh_zone_stat_thresholds();
5775 setup_per_zone_lowmem_reserve();
5776 setup_per_zone_inactive_ratio();
5777 return 0;
5779 module_init(init_per_zone_wmark_min)
5782 * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
5783 * that we can call two helper functions whenever min_free_kbytes
5784 * changes.
5786 int min_free_kbytes_sysctl_handler(ctl_table *table, int write,
5787 void __user *buffer, size_t *length, loff_t *ppos)
5789 int rc;
5791 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
5792 if (rc)
5793 return rc;
5795 if (write) {
5796 user_min_free_kbytes = min_free_kbytes;
5797 setup_per_zone_wmarks();
5799 return 0;
5802 #ifdef CONFIG_NUMA
5803 int sysctl_min_unmapped_ratio_sysctl_handler(ctl_table *table, int write,
5804 void __user *buffer, size_t *length, loff_t *ppos)
5806 struct zone *zone;
5807 int rc;
5809 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
5810 if (rc)
5811 return rc;
5813 for_each_zone(zone)
5814 zone->min_unmapped_pages = (zone->managed_pages *
5815 sysctl_min_unmapped_ratio) / 100;
5816 return 0;
5819 int sysctl_min_slab_ratio_sysctl_handler(ctl_table *table, int write,
5820 void __user *buffer, size_t *length, loff_t *ppos)
5822 struct zone *zone;
5823 int rc;
5825 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
5826 if (rc)
5827 return rc;
5829 for_each_zone(zone)
5830 zone->min_slab_pages = (zone->managed_pages *
5831 sysctl_min_slab_ratio) / 100;
5832 return 0;
5834 #endif
5837 * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
5838 * proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
5839 * whenever sysctl_lowmem_reserve_ratio changes.
5841 * The reserve ratio obviously has absolutely no relation with the
5842 * minimum watermarks. The lowmem reserve ratio can only make sense
5843 * if in function of the boot time zone sizes.
5845 int lowmem_reserve_ratio_sysctl_handler(ctl_table *table, int write,
5846 void __user *buffer, size_t *length, loff_t *ppos)
5848 proc_dointvec_minmax(table, write, buffer, length, ppos);
5849 setup_per_zone_lowmem_reserve();
5850 return 0;
5854 * percpu_pagelist_fraction - changes the pcp->high for each zone on each
5855 * cpu. It is the fraction of total pages in each zone that a hot per cpu
5856 * pagelist can have before it gets flushed back to buddy allocator.
5858 int percpu_pagelist_fraction_sysctl_handler(ctl_table *table, int write,
5859 void __user *buffer, size_t *length, loff_t *ppos)
5861 struct zone *zone;
5862 int old_percpu_pagelist_fraction;
5863 int ret;
5865 mutex_lock(&pcp_batch_high_lock);
5866 old_percpu_pagelist_fraction = percpu_pagelist_fraction;
5868 ret = proc_dointvec_minmax(table, write, buffer, length, ppos);
5869 if (!write || ret < 0)
5870 goto out;
5872 /* Sanity checking to avoid pcp imbalance */
5873 if (percpu_pagelist_fraction &&
5874 percpu_pagelist_fraction < MIN_PERCPU_PAGELIST_FRACTION) {
5875 percpu_pagelist_fraction = old_percpu_pagelist_fraction;
5876 ret = -EINVAL;
5877 goto out;
5880 /* No change? */
5881 if (percpu_pagelist_fraction == old_percpu_pagelist_fraction)
5882 goto out;
5884 for_each_populated_zone(zone) {
5885 unsigned int cpu;
5887 for_each_possible_cpu(cpu)
5888 pageset_set_high_and_batch(zone,
5889 per_cpu_ptr(zone->pageset, cpu));
5891 out:
5892 mutex_unlock(&pcp_batch_high_lock);
5893 return ret;
5896 int hashdist = HASHDIST_DEFAULT;
5898 #ifdef CONFIG_NUMA
5899 static int __init set_hashdist(char *str)
5901 if (!str)
5902 return 0;
5903 hashdist = simple_strtoul(str, &str, 0);
5904 return 1;
5906 __setup("hashdist=", set_hashdist);
5907 #endif
5910 * allocate a large system hash table from bootmem
5911 * - it is assumed that the hash table must contain an exact power-of-2
5912 * quantity of entries
5913 * - limit is the number of hash buckets, not the total allocation size
5915 void *__init alloc_large_system_hash(const char *tablename,
5916 unsigned long bucketsize,
5917 unsigned long numentries,
5918 int scale,
5919 int flags,
5920 unsigned int *_hash_shift,
5921 unsigned int *_hash_mask,
5922 unsigned long low_limit,
5923 unsigned long high_limit)
5925 unsigned long long max = high_limit;
5926 unsigned long log2qty, size;
5927 void *table = NULL;
5929 /* allow the kernel cmdline to have a say */
5930 if (!numentries) {
5931 /* round applicable memory size up to nearest megabyte */
5932 numentries = nr_kernel_pages;
5934 /* It isn't necessary when PAGE_SIZE >= 1MB */
5935 if (PAGE_SHIFT < 20)
5936 numentries = round_up(numentries, (1<<20)/PAGE_SIZE);
5938 /* limit to 1 bucket per 2^scale bytes of low memory */
5939 if (scale > PAGE_SHIFT)
5940 numentries >>= (scale - PAGE_SHIFT);
5941 else
5942 numentries <<= (PAGE_SHIFT - scale);
5944 /* Make sure we've got at least a 0-order allocation.. */
5945 if (unlikely(flags & HASH_SMALL)) {
5946 /* Makes no sense without HASH_EARLY */
5947 WARN_ON(!(flags & HASH_EARLY));
5948 if (!(numentries >> *_hash_shift)) {
5949 numentries = 1UL << *_hash_shift;
5950 BUG_ON(!numentries);
5952 } else if (unlikely((numentries * bucketsize) < PAGE_SIZE))
5953 numentries = PAGE_SIZE / bucketsize;
5955 numentries = roundup_pow_of_two(numentries);
5957 /* limit allocation size to 1/16 total memory by default */
5958 if (max == 0) {
5959 max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
5960 do_div(max, bucketsize);
5962 max = min(max, 0x80000000ULL);
5964 if (numentries < low_limit)
5965 numentries = low_limit;
5966 if (numentries > max)
5967 numentries = max;
5969 log2qty = ilog2(numentries);
5971 do {
5972 size = bucketsize << log2qty;
5973 if (flags & HASH_EARLY)
5974 table = alloc_bootmem_nopanic(size);
5975 else if (hashdist)
5976 table = __vmalloc(size, GFP_ATOMIC, PAGE_KERNEL);
5977 else {
5979 * If bucketsize is not a power-of-two, we may free
5980 * some pages at the end of hash table which
5981 * alloc_pages_exact() automatically does
5983 if (get_order(size) < MAX_ORDER) {
5984 table = alloc_pages_exact(size, GFP_ATOMIC);
5985 kmemleak_alloc(table, size, 1, GFP_ATOMIC);
5988 } while (!table && size > PAGE_SIZE && --log2qty);
5990 if (!table)
5991 panic("Failed to allocate %s hash table\n", tablename);
5993 printk(KERN_INFO "%s hash table entries: %ld (order: %d, %lu bytes)\n",
5994 tablename,
5995 (1UL << log2qty),
5996 ilog2(size) - PAGE_SHIFT,
5997 size);
5999 if (_hash_shift)
6000 *_hash_shift = log2qty;
6001 if (_hash_mask)
6002 *_hash_mask = (1 << log2qty) - 1;
6004 return table;
6007 /* Return a pointer to the bitmap storing bits affecting a block of pages */
6008 static inline unsigned long *get_pageblock_bitmap(struct zone *zone,
6009 unsigned long pfn)
6011 #ifdef CONFIG_SPARSEMEM
6012 return __pfn_to_section(pfn)->pageblock_flags;
6013 #else
6014 return zone->pageblock_flags;
6015 #endif /* CONFIG_SPARSEMEM */
6018 static inline int pfn_to_bitidx(struct zone *zone, unsigned long pfn)
6020 #ifdef CONFIG_SPARSEMEM
6021 pfn &= (PAGES_PER_SECTION-1);
6022 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
6023 #else
6024 pfn = pfn - round_down(zone->zone_start_pfn, pageblock_nr_pages);
6025 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
6026 #endif /* CONFIG_SPARSEMEM */
6030 * get_pageblock_flags_group - Return the requested group of flags for the pageblock_nr_pages block of pages
6031 * @page: The page within the block of interest
6032 * @start_bitidx: The first bit of interest to retrieve
6033 * @end_bitidx: The last bit of interest
6034 * returns pageblock_bits flags
6036 unsigned long get_pfnblock_flags_mask(struct page *page, unsigned long pfn,
6037 unsigned long end_bitidx,
6038 unsigned long mask)
6040 struct zone *zone;
6041 unsigned long *bitmap;
6042 unsigned long bitidx, word_bitidx;
6043 unsigned long word;
6045 zone = page_zone(page);
6046 bitmap = get_pageblock_bitmap(zone, pfn);
6047 bitidx = pfn_to_bitidx(zone, pfn);
6048 word_bitidx = bitidx / BITS_PER_LONG;
6049 bitidx &= (BITS_PER_LONG-1);
6051 word = bitmap[word_bitidx];
6052 bitidx += end_bitidx;
6053 return (word >> (BITS_PER_LONG - bitidx - 1)) & mask;
6057 * set_pfnblock_flags_mask - Set the requested group of flags for a pageblock_nr_pages block of pages
6058 * @page: The page within the block of interest
6059 * @start_bitidx: The first bit of interest
6060 * @end_bitidx: The last bit of interest
6061 * @flags: The flags to set
6063 void set_pfnblock_flags_mask(struct page *page, unsigned long flags,
6064 unsigned long pfn,
6065 unsigned long end_bitidx,
6066 unsigned long mask)
6068 struct zone *zone;
6069 unsigned long *bitmap;
6070 unsigned long bitidx, word_bitidx;
6071 unsigned long old_word, word;
6073 BUILD_BUG_ON(NR_PAGEBLOCK_BITS != 4);
6075 zone = page_zone(page);
6076 bitmap = get_pageblock_bitmap(zone, pfn);
6077 bitidx = pfn_to_bitidx(zone, pfn);
6078 word_bitidx = bitidx / BITS_PER_LONG;
6079 bitidx &= (BITS_PER_LONG-1);
6081 VM_BUG_ON(!zone_spans_pfn(zone, pfn));
6083 bitidx += end_bitidx;
6084 mask <<= (BITS_PER_LONG - bitidx - 1);
6085 flags <<= (BITS_PER_LONG - bitidx - 1);
6087 word = ACCESS_ONCE(bitmap[word_bitidx]);
6088 for (;;) {
6089 old_word = cmpxchg(&bitmap[word_bitidx], word, (word & ~mask) | flags);
6090 if (word == old_word)
6091 break;
6092 word = old_word;
6097 * This function checks whether pageblock includes unmovable pages or not.
6098 * If @count is not zero, it is okay to include less @count unmovable pages
6100 * PageLRU check without isolation or lru_lock could race so that
6101 * MIGRATE_MOVABLE block might include unmovable pages. It means you can't
6102 * expect this function should be exact.
6104 bool has_unmovable_pages(struct zone *zone, struct page *page, int count,
6105 bool skip_hwpoisoned_pages)
6107 unsigned long pfn, iter, found;
6108 int mt;
6111 * For avoiding noise data, lru_add_drain_all() should be called
6112 * If ZONE_MOVABLE, the zone never contains unmovable pages
6114 if (zone_idx(zone) == ZONE_MOVABLE)
6115 return false;
6116 mt = get_pageblock_migratetype(page);
6117 if (mt == MIGRATE_MOVABLE || is_migrate_cma(mt))
6118 return false;
6120 pfn = page_to_pfn(page);
6121 for (found = 0, iter = 0; iter < pageblock_nr_pages; iter++) {
6122 unsigned long check = pfn + iter;
6124 if (!pfn_valid_within(check))
6125 continue;
6127 page = pfn_to_page(check);
6130 * Hugepages are not in LRU lists, but they're movable.
6131 * We need not scan over tail pages bacause we don't
6132 * handle each tail page individually in migration.
6134 if (PageHuge(page)) {
6135 iter = round_up(iter + 1, 1<<compound_order(page)) - 1;
6136 continue;
6140 * We can't use page_count without pin a page
6141 * because another CPU can free compound page.
6142 * This check already skips compound tails of THP
6143 * because their page->_count is zero at all time.
6145 if (!atomic_read(&page->_count)) {
6146 if (PageBuddy(page))
6147 iter += (1 << page_order(page)) - 1;
6148 continue;
6152 * The HWPoisoned page may be not in buddy system, and
6153 * page_count() is not 0.
6155 if (skip_hwpoisoned_pages && PageHWPoison(page))
6156 continue;
6158 if (!PageLRU(page))
6159 found++;
6161 * If there are RECLAIMABLE pages, we need to check it.
6162 * But now, memory offline itself doesn't call shrink_slab()
6163 * and it still to be fixed.
6166 * If the page is not RAM, page_count()should be 0.
6167 * we don't need more check. This is an _used_ not-movable page.
6169 * The problematic thing here is PG_reserved pages. PG_reserved
6170 * is set to both of a memory hole page and a _used_ kernel
6171 * page at boot.
6173 if (found > count)
6174 return true;
6176 return false;
6179 bool is_pageblock_removable_nolock(struct page *page)
6181 struct zone *zone;
6182 unsigned long pfn;
6185 * We have to be careful here because we are iterating over memory
6186 * sections which are not zone aware so we might end up outside of
6187 * the zone but still within the section.
6188 * We have to take care about the node as well. If the node is offline
6189 * its NODE_DATA will be NULL - see page_zone.
6191 if (!node_online(page_to_nid(page)))
6192 return false;
6194 zone = page_zone(page);
6195 pfn = page_to_pfn(page);
6196 if (!zone_spans_pfn(zone, pfn))
6197 return false;
6199 return !has_unmovable_pages(zone, page, 0, true);
6202 #ifdef CONFIG_CMA
6204 static unsigned long pfn_max_align_down(unsigned long pfn)
6206 return pfn & ~(max_t(unsigned long, MAX_ORDER_NR_PAGES,
6207 pageblock_nr_pages) - 1);
6210 static unsigned long pfn_max_align_up(unsigned long pfn)
6212 return ALIGN(pfn, max_t(unsigned long, MAX_ORDER_NR_PAGES,
6213 pageblock_nr_pages));
6216 /* [start, end) must belong to a single zone. */
6217 static int __alloc_contig_migrate_range(struct compact_control *cc,
6218 unsigned long start, unsigned long end)
6220 /* This function is based on compact_zone() from compaction.c. */
6221 unsigned long nr_reclaimed;
6222 unsigned long pfn = start;
6223 unsigned int tries = 0;
6224 int ret = 0;
6226 migrate_prep();
6228 while (pfn < end || !list_empty(&cc->migratepages)) {
6229 if (fatal_signal_pending(current)) {
6230 ret = -EINTR;
6231 break;
6234 if (list_empty(&cc->migratepages)) {
6235 cc->nr_migratepages = 0;
6236 pfn = isolate_migratepages_range(cc->zone, cc,
6237 pfn, end, true);
6238 if (!pfn) {
6239 ret = -EINTR;
6240 break;
6242 tries = 0;
6243 } else if (++tries == 5) {
6244 ret = ret < 0 ? ret : -EBUSY;
6245 break;
6248 nr_reclaimed = reclaim_clean_pages_from_list(cc->zone,
6249 &cc->migratepages);
6250 cc->nr_migratepages -= nr_reclaimed;
6252 ret = migrate_pages(&cc->migratepages, alloc_migrate_target,
6253 NULL, 0, cc->mode, MR_CMA);
6255 if (ret < 0) {
6256 putback_movable_pages(&cc->migratepages);
6257 return ret;
6259 return 0;
6263 * alloc_contig_range() -- tries to allocate given range of pages
6264 * @start: start PFN to allocate
6265 * @end: one-past-the-last PFN to allocate
6266 * @migratetype: migratetype of the underlaying pageblocks (either
6267 * #MIGRATE_MOVABLE or #MIGRATE_CMA). All pageblocks
6268 * in range must have the same migratetype and it must
6269 * be either of the two.
6271 * The PFN range does not have to be pageblock or MAX_ORDER_NR_PAGES
6272 * aligned, however it's the caller's responsibility to guarantee that
6273 * we are the only thread that changes migrate type of pageblocks the
6274 * pages fall in.
6276 * The PFN range must belong to a single zone.
6278 * Returns zero on success or negative error code. On success all
6279 * pages which PFN is in [start, end) are allocated for the caller and
6280 * need to be freed with free_contig_range().
6282 int alloc_contig_range(unsigned long start, unsigned long end,
6283 unsigned migratetype)
6285 unsigned long outer_start, outer_end;
6286 int ret = 0, order;
6288 struct compact_control cc = {
6289 .nr_migratepages = 0,
6290 .order = -1,
6291 .zone = page_zone(pfn_to_page(start)),
6292 .mode = MIGRATE_SYNC,
6293 .ignore_skip_hint = true,
6295 INIT_LIST_HEAD(&cc.migratepages);
6298 * What we do here is we mark all pageblocks in range as
6299 * MIGRATE_ISOLATE. Because pageblock and max order pages may
6300 * have different sizes, and due to the way page allocator
6301 * work, we align the range to biggest of the two pages so
6302 * that page allocator won't try to merge buddies from
6303 * different pageblocks and change MIGRATE_ISOLATE to some
6304 * other migration type.
6306 * Once the pageblocks are marked as MIGRATE_ISOLATE, we
6307 * migrate the pages from an unaligned range (ie. pages that
6308 * we are interested in). This will put all the pages in
6309 * range back to page allocator as MIGRATE_ISOLATE.
6311 * When this is done, we take the pages in range from page
6312 * allocator removing them from the buddy system. This way
6313 * page allocator will never consider using them.
6315 * This lets us mark the pageblocks back as
6316 * MIGRATE_CMA/MIGRATE_MOVABLE so that free pages in the
6317 * aligned range but not in the unaligned, original range are
6318 * put back to page allocator so that buddy can use them.
6321 ret = start_isolate_page_range(pfn_max_align_down(start),
6322 pfn_max_align_up(end), migratetype,
6323 false);
6324 if (ret)
6325 return ret;
6327 ret = __alloc_contig_migrate_range(&cc, start, end);
6328 if (ret)
6329 goto done;
6332 * Pages from [start, end) are within a MAX_ORDER_NR_PAGES
6333 * aligned blocks that are marked as MIGRATE_ISOLATE. What's
6334 * more, all pages in [start, end) are free in page allocator.
6335 * What we are going to do is to allocate all pages from
6336 * [start, end) (that is remove them from page allocator).
6338 * The only problem is that pages at the beginning and at the
6339 * end of interesting range may be not aligned with pages that
6340 * page allocator holds, ie. they can be part of higher order
6341 * pages. Because of this, we reserve the bigger range and
6342 * once this is done free the pages we are not interested in.
6344 * We don't have to hold zone->lock here because the pages are
6345 * isolated thus they won't get removed from buddy.
6348 lru_add_drain_all();
6349 drain_all_pages();
6351 order = 0;
6352 outer_start = start;
6353 while (!PageBuddy(pfn_to_page(outer_start))) {
6354 if (++order >= MAX_ORDER) {
6355 ret = -EBUSY;
6356 goto done;
6358 outer_start &= ~0UL << order;
6361 /* Make sure the range is really isolated. */
6362 if (test_pages_isolated(outer_start, end, false)) {
6363 pr_warn("alloc_contig_range test_pages_isolated(%lx, %lx) failed\n",
6364 outer_start, end);
6365 ret = -EBUSY;
6366 goto done;
6370 /* Grab isolated pages from freelists. */
6371 outer_end = isolate_freepages_range(&cc, outer_start, end);
6372 if (!outer_end) {
6373 ret = -EBUSY;
6374 goto done;
6377 /* Free head and tail (if any) */
6378 if (start != outer_start)
6379 free_contig_range(outer_start, start - outer_start);
6380 if (end != outer_end)
6381 free_contig_range(end, outer_end - end);
6383 done:
6384 undo_isolate_page_range(pfn_max_align_down(start),
6385 pfn_max_align_up(end), migratetype);
6386 return ret;
6389 void free_contig_range(unsigned long pfn, unsigned nr_pages)
6391 unsigned int count = 0;
6393 for (; nr_pages--; pfn++) {
6394 struct page *page = pfn_to_page(pfn);
6396 count += page_count(page) != 1;
6397 __free_page(page);
6399 WARN(count != 0, "%d pages are still in use!\n", count);
6401 #endif
6403 #ifdef CONFIG_MEMORY_HOTPLUG
6405 * The zone indicated has a new number of managed_pages; batch sizes and percpu
6406 * page high values need to be recalulated.
6408 void __meminit zone_pcp_update(struct zone *zone)
6410 unsigned cpu;
6411 mutex_lock(&pcp_batch_high_lock);
6412 for_each_possible_cpu(cpu)
6413 pageset_set_high_and_batch(zone,
6414 per_cpu_ptr(zone->pageset, cpu));
6415 mutex_unlock(&pcp_batch_high_lock);
6417 #endif
6419 void zone_pcp_reset(struct zone *zone)
6421 unsigned long flags;
6422 int cpu;
6423 struct per_cpu_pageset *pset;
6425 /* avoid races with drain_pages() */
6426 local_irq_save(flags);
6427 if (zone->pageset != &boot_pageset) {
6428 for_each_online_cpu(cpu) {
6429 pset = per_cpu_ptr(zone->pageset, cpu);
6430 drain_zonestat(zone, pset);
6432 free_percpu(zone->pageset);
6433 zone->pageset = &boot_pageset;
6435 local_irq_restore(flags);
6438 #ifdef CONFIG_MEMORY_HOTREMOVE
6440 * All pages in the range must be isolated before calling this.
6442 void
6443 __offline_isolated_pages(unsigned long start_pfn, unsigned long end_pfn)
6445 struct page *page;
6446 struct zone *zone;
6447 unsigned int order, i;
6448 unsigned long pfn;
6449 unsigned long flags;
6450 /* find the first valid pfn */
6451 for (pfn = start_pfn; pfn < end_pfn; pfn++)
6452 if (pfn_valid(pfn))
6453 break;
6454 if (pfn == end_pfn)
6455 return;
6456 zone = page_zone(pfn_to_page(pfn));
6457 spin_lock_irqsave(&zone->lock, flags);
6458 pfn = start_pfn;
6459 while (pfn < end_pfn) {
6460 if (!pfn_valid(pfn)) {
6461 pfn++;
6462 continue;
6464 page = pfn_to_page(pfn);
6466 * The HWPoisoned page may be not in buddy system, and
6467 * page_count() is not 0.
6469 if (unlikely(!PageBuddy(page) && PageHWPoison(page))) {
6470 pfn++;
6471 SetPageReserved(page);
6472 continue;
6475 BUG_ON(page_count(page));
6476 BUG_ON(!PageBuddy(page));
6477 order = page_order(page);
6478 #ifdef CONFIG_DEBUG_VM
6479 printk(KERN_INFO "remove from free list %lx %d %lx\n",
6480 pfn, 1 << order, end_pfn);
6481 #endif
6482 list_del(&page->lru);
6483 rmv_page_order(page);
6484 zone->free_area[order].nr_free--;
6485 for (i = 0; i < (1 << order); i++)
6486 SetPageReserved((page+i));
6487 pfn += (1 << order);
6489 spin_unlock_irqrestore(&zone->lock, flags);
6491 #endif
6493 #ifdef CONFIG_MEMORY_FAILURE
6494 bool is_free_buddy_page(struct page *page)
6496 struct zone *zone = page_zone(page);
6497 unsigned long pfn = page_to_pfn(page);
6498 unsigned long flags;
6499 unsigned int order;
6501 spin_lock_irqsave(&zone->lock, flags);
6502 for (order = 0; order < MAX_ORDER; order++) {
6503 struct page *page_head = page - (pfn & ((1 << order) - 1));
6505 if (PageBuddy(page_head) && page_order(page_head) >= order)
6506 break;
6508 spin_unlock_irqrestore(&zone->lock, flags);
6510 return order < MAX_ORDER;
6512 #endif
6514 static const struct trace_print_flags pageflag_names[] = {
6515 {1UL << PG_locked, "locked" },
6516 {1UL << PG_error, "error" },
6517 {1UL << PG_referenced, "referenced" },
6518 {1UL << PG_uptodate, "uptodate" },
6519 {1UL << PG_dirty, "dirty" },
6520 {1UL << PG_lru, "lru" },
6521 {1UL << PG_active, "active" },
6522 {1UL << PG_slab, "slab" },
6523 {1UL << PG_owner_priv_1, "owner_priv_1" },
6524 {1UL << PG_arch_1, "arch_1" },
6525 {1UL << PG_reserved, "reserved" },
6526 {1UL << PG_private, "private" },
6527 {1UL << PG_private_2, "private_2" },
6528 {1UL << PG_writeback, "writeback" },
6529 #ifdef CONFIG_PAGEFLAGS_EXTENDED
6530 {1UL << PG_head, "head" },
6531 {1UL << PG_tail, "tail" },
6532 #else
6533 {1UL << PG_compound, "compound" },
6534 #endif
6535 {1UL << PG_swapcache, "swapcache" },
6536 {1UL << PG_mappedtodisk, "mappedtodisk" },
6537 {1UL << PG_reclaim, "reclaim" },
6538 {1UL << PG_swapbacked, "swapbacked" },
6539 {1UL << PG_unevictable, "unevictable" },
6540 #ifdef CONFIG_MMU
6541 {1UL << PG_mlocked, "mlocked" },
6542 #endif
6543 #ifdef CONFIG_ARCH_USES_PG_UNCACHED
6544 {1UL << PG_uncached, "uncached" },
6545 #endif
6546 #ifdef CONFIG_MEMORY_FAILURE
6547 {1UL << PG_hwpoison, "hwpoison" },
6548 #endif
6549 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
6550 {1UL << PG_compound_lock, "compound_lock" },
6551 #endif
6554 static void dump_page_flags(unsigned long flags)
6556 const char *delim = "";
6557 unsigned long mask;
6558 int i;
6560 BUILD_BUG_ON(ARRAY_SIZE(pageflag_names) != __NR_PAGEFLAGS);
6562 printk(KERN_ALERT "page flags: %#lx(", flags);
6564 /* remove zone id */
6565 flags &= (1UL << NR_PAGEFLAGS) - 1;
6567 for (i = 0; i < ARRAY_SIZE(pageflag_names) && flags; i++) {
6569 mask = pageflag_names[i].mask;
6570 if ((flags & mask) != mask)
6571 continue;
6573 flags &= ~mask;
6574 printk("%s%s", delim, pageflag_names[i].name);
6575 delim = "|";
6578 /* check for left over flags */
6579 if (flags)
6580 printk("%s%#lx", delim, flags);
6582 printk(")\n");
6585 void dump_page(struct page *page)
6587 printk(KERN_ALERT
6588 "page:%p count:%d mapcount:%d mapping:%p index:%#lx\n",
6589 page, atomic_read(&page->_count), page_mapcount(page),
6590 page->mapping, page->index);
6591 dump_page_flags(page->flags);
6592 mem_cgroup_print_bad_page(page);