Linux 3.16.75
[linux/fpc-iii.git] / mm / page_alloc.c
blobb491f75f7491418188b897484098ca3da593890b
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>
64 #include <linux/nmi.h>
66 #include <asm/sections.h>
67 #include <asm/tlbflush.h>
68 #include <asm/div64.h>
69 #include "internal.h"
71 /* prevent >1 _updater_ of zone percpu pageset ->high and ->batch fields */
72 static DEFINE_MUTEX(pcp_batch_high_lock);
73 #define MIN_PERCPU_PAGELIST_FRACTION (8)
75 #ifdef CONFIG_USE_PERCPU_NUMA_NODE_ID
76 DEFINE_PER_CPU(int, numa_node);
77 EXPORT_PER_CPU_SYMBOL(numa_node);
78 #endif
80 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
82 * N.B., Do NOT reference the '_numa_mem_' per cpu variable directly.
83 * It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined.
84 * Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem()
85 * defined in <linux/topology.h>.
87 DEFINE_PER_CPU(int, _numa_mem_); /* Kernel "local memory" node */
88 EXPORT_PER_CPU_SYMBOL(_numa_mem_);
89 #endif
92 * Array of node states.
94 nodemask_t node_states[NR_NODE_STATES] __read_mostly = {
95 [N_POSSIBLE] = NODE_MASK_ALL,
96 [N_ONLINE] = { { [0] = 1UL } },
97 #ifndef CONFIG_NUMA
98 [N_NORMAL_MEMORY] = { { [0] = 1UL } },
99 #ifdef CONFIG_HIGHMEM
100 [N_HIGH_MEMORY] = { { [0] = 1UL } },
101 #endif
102 #ifdef CONFIG_MOVABLE_NODE
103 [N_MEMORY] = { { [0] = 1UL } },
104 #endif
105 [N_CPU] = { { [0] = 1UL } },
106 #endif /* NUMA */
108 EXPORT_SYMBOL(node_states);
110 /* Protect totalram_pages and zone->managed_pages */
111 static DEFINE_SPINLOCK(managed_page_count_lock);
113 unsigned long totalram_pages __read_mostly;
114 unsigned long totalreserve_pages __read_mostly;
116 * When calculating the number of globally allowed dirty pages, there
117 * is a certain number of per-zone reserves that should not be
118 * considered dirtyable memory. This is the sum of those reserves
119 * over all existing zones that contribute dirtyable memory.
121 unsigned long dirty_balance_reserve __read_mostly;
123 int percpu_pagelist_fraction;
124 gfp_t gfp_allowed_mask __read_mostly = GFP_BOOT_MASK;
126 #ifdef CONFIG_PM_SLEEP
128 * The following functions are used by the suspend/hibernate code to temporarily
129 * change gfp_allowed_mask in order to avoid using I/O during memory allocations
130 * while devices are suspended. To avoid races with the suspend/hibernate code,
131 * they should always be called with pm_mutex held (gfp_allowed_mask also should
132 * only be modified with pm_mutex held, unless the suspend/hibernate code is
133 * guaranteed not to run in parallel with that modification).
136 static gfp_t saved_gfp_mask;
138 void pm_restore_gfp_mask(void)
140 WARN_ON(!mutex_is_locked(&pm_mutex));
141 if (saved_gfp_mask) {
142 gfp_allowed_mask = saved_gfp_mask;
143 saved_gfp_mask = 0;
147 void pm_restrict_gfp_mask(void)
149 WARN_ON(!mutex_is_locked(&pm_mutex));
150 WARN_ON(saved_gfp_mask);
151 saved_gfp_mask = gfp_allowed_mask;
152 gfp_allowed_mask &= ~GFP_IOFS;
155 bool pm_suspended_storage(void)
157 if ((gfp_allowed_mask & GFP_IOFS) == GFP_IOFS)
158 return false;
159 return true;
161 #endif /* CONFIG_PM_SLEEP */
163 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
164 int pageblock_order __read_mostly;
165 #endif
167 static void __free_pages_ok(struct page *page, unsigned int order);
170 * results with 256, 32 in the lowmem_reserve sysctl:
171 * 1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
172 * 1G machine -> (16M dma, 784M normal, 224M high)
173 * NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
174 * HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
175 * HIGHMEM allocation will (224M+784M)/256 of ram reserved in ZONE_DMA
177 * TBD: should special case ZONE_DMA32 machines here - in those we normally
178 * don't need any ZONE_NORMAL reservation
180 int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES-1] = {
181 #ifdef CONFIG_ZONE_DMA
182 256,
183 #endif
184 #ifdef CONFIG_ZONE_DMA32
185 256,
186 #endif
187 #ifdef CONFIG_HIGHMEM
189 #endif
193 EXPORT_SYMBOL(totalram_pages);
195 static char * const zone_names[MAX_NR_ZONES] = {
196 #ifdef CONFIG_ZONE_DMA
197 "DMA",
198 #endif
199 #ifdef CONFIG_ZONE_DMA32
200 "DMA32",
201 #endif
202 "Normal",
203 #ifdef CONFIG_HIGHMEM
204 "HighMem",
205 #endif
206 "Movable",
209 int min_free_kbytes = 1024;
210 int user_min_free_kbytes = -1;
212 static unsigned long __meminitdata nr_kernel_pages;
213 static unsigned long __meminitdata nr_all_pages;
214 static unsigned long __meminitdata dma_reserve;
216 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
217 static unsigned long __meminitdata arch_zone_lowest_possible_pfn[MAX_NR_ZONES];
218 static unsigned long __meminitdata arch_zone_highest_possible_pfn[MAX_NR_ZONES];
219 static unsigned long __initdata required_kernelcore;
220 static unsigned long __initdata required_movablecore;
221 static unsigned long __meminitdata zone_movable_pfn[MAX_NUMNODES];
223 /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
224 int movable_zone;
225 EXPORT_SYMBOL(movable_zone);
226 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
228 #if MAX_NUMNODES > 1
229 int nr_node_ids __read_mostly = MAX_NUMNODES;
230 int nr_online_nodes __read_mostly = 1;
231 EXPORT_SYMBOL(nr_node_ids);
232 EXPORT_SYMBOL(nr_online_nodes);
233 #endif
235 int page_group_by_mobility_disabled __read_mostly;
237 void set_pageblock_migratetype(struct page *page, int migratetype)
239 if (unlikely(page_group_by_mobility_disabled &&
240 migratetype < MIGRATE_PCPTYPES))
241 migratetype = MIGRATE_UNMOVABLE;
243 set_pageblock_flags_group(page, (unsigned long)migratetype,
244 PB_migrate, PB_migrate_end);
247 bool oom_killer_disabled __read_mostly;
249 #ifdef CONFIG_DEBUG_VM
250 static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
252 int ret = 0;
253 unsigned seq;
254 unsigned long pfn = page_to_pfn(page);
255 unsigned long sp, start_pfn;
257 do {
258 seq = zone_span_seqbegin(zone);
259 start_pfn = zone->zone_start_pfn;
260 sp = zone->spanned_pages;
261 if (!zone_spans_pfn(zone, pfn))
262 ret = 1;
263 } while (zone_span_seqretry(zone, seq));
265 if (ret)
266 pr_err("page 0x%lx outside node %d zone %s [ 0x%lx - 0x%lx ]\n",
267 pfn, zone_to_nid(zone), zone->name,
268 start_pfn, start_pfn + sp);
270 return ret;
273 static int page_is_consistent(struct zone *zone, struct page *page)
275 if (!pfn_valid_within(page_to_pfn(page)))
276 return 0;
277 if (zone != page_zone(page))
278 return 0;
280 return 1;
283 * Temporary debugging check for pages not lying within a given zone.
285 static int bad_range(struct zone *zone, struct page *page)
287 if (page_outside_zone_boundaries(zone, page))
288 return 1;
289 if (!page_is_consistent(zone, page))
290 return 1;
292 return 0;
294 #else
295 static inline int bad_range(struct zone *zone, struct page *page)
297 return 0;
299 #endif
301 static void bad_page(struct page *page, const char *reason,
302 unsigned long bad_flags)
304 static unsigned long resume;
305 static unsigned long nr_shown;
306 static unsigned long nr_unshown;
308 /* Don't complain about poisoned pages */
309 if (PageHWPoison(page)) {
310 page_mapcount_reset(page); /* remove PageBuddy */
311 return;
315 * Allow a burst of 60 reports, then keep quiet for that minute;
316 * or allow a steady drip of one report per second.
318 if (nr_shown == 60) {
319 if (time_before(jiffies, resume)) {
320 nr_unshown++;
321 goto out;
323 if (nr_unshown) {
324 printk(KERN_ALERT
325 "BUG: Bad page state: %lu messages suppressed\n",
326 nr_unshown);
327 nr_unshown = 0;
329 nr_shown = 0;
331 if (nr_shown++ == 0)
332 resume = jiffies + 60 * HZ;
334 printk(KERN_ALERT "BUG: Bad page state in process %s pfn:%05lx\n",
335 current->comm, page_to_pfn(page));
336 dump_page_badflags(page, reason, bad_flags);
338 print_modules();
339 dump_stack();
340 out:
341 /* Leave bad fields for debug, except PageBuddy could make trouble */
342 page_mapcount_reset(page); /* remove PageBuddy */
343 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
347 * Higher-order pages are called "compound pages". They are structured thusly:
349 * The first PAGE_SIZE page is called the "head page".
351 * The remaining PAGE_SIZE pages are called "tail pages".
353 * All pages have PG_compound set. All tail pages have their ->first_page
354 * pointing at the head page.
356 * The first tail page's ->lru.next holds the address of the compound page's
357 * put_page() function. Its ->lru.prev holds the order of allocation.
358 * This usage means that zero-order pages may not be compound.
361 static void free_compound_page(struct page *page)
363 __free_pages_ok(page, compound_order(page));
366 void prep_compound_page(struct page *page, unsigned long order)
368 int i;
369 int nr_pages = 1 << order;
371 set_compound_page_dtor(page, free_compound_page);
372 set_compound_order(page, order);
373 __SetPageHead(page);
374 for (i = 1; i < nr_pages; i++) {
375 struct page *p = page + i;
376 set_page_count(p, 0);
377 p->first_page = page;
378 /* Make sure p->first_page is always valid for PageTail() */
379 smp_wmb();
380 __SetPageTail(p);
384 /* update __split_huge_page_refcount if you change this function */
385 static int destroy_compound_page(struct page *page, unsigned long order)
387 int i;
388 int nr_pages = 1 << order;
389 int bad = 0;
391 if (unlikely(compound_order(page) != order)) {
392 bad_page(page, "wrong compound order", 0);
393 bad++;
396 __ClearPageHead(page);
398 for (i = 1; i < nr_pages; i++) {
399 struct page *p = page + i;
401 if (unlikely(!PageTail(p))) {
402 bad_page(page, "PageTail not set", 0);
403 bad++;
404 } else if (unlikely(p->first_page != page)) {
405 bad_page(page, "first_page not consistent", 0);
406 bad++;
408 __ClearPageTail(p);
411 return bad;
414 static inline void prep_zero_page(struct page *page, unsigned int order,
415 gfp_t gfp_flags)
417 int i;
420 * clear_highpage() will use KM_USER0, so it's a bug to use __GFP_ZERO
421 * and __GFP_HIGHMEM from hard or soft interrupt context.
423 VM_BUG_ON((gfp_flags & __GFP_HIGHMEM) && in_interrupt());
424 for (i = 0; i < (1 << order); i++)
425 clear_highpage(page + i);
428 #ifdef CONFIG_DEBUG_PAGEALLOC
429 unsigned int _debug_guardpage_minorder;
431 static int __init debug_guardpage_minorder_setup(char *buf)
433 unsigned long res;
435 if (kstrtoul(buf, 10, &res) < 0 || res > MAX_ORDER / 2) {
436 printk(KERN_ERR "Bad debug_guardpage_minorder value\n");
437 return 0;
439 _debug_guardpage_minorder = res;
440 printk(KERN_INFO "Setting debug_guardpage_minorder to %lu\n", res);
441 return 0;
443 __setup("debug_guardpage_minorder=", debug_guardpage_minorder_setup);
445 static inline void set_page_guard_flag(struct page *page)
447 __set_bit(PAGE_DEBUG_FLAG_GUARD, &page->debug_flags);
450 static inline void clear_page_guard_flag(struct page *page)
452 __clear_bit(PAGE_DEBUG_FLAG_GUARD, &page->debug_flags);
454 #else
455 static inline void set_page_guard_flag(struct page *page) { }
456 static inline void clear_page_guard_flag(struct page *page) { }
457 #endif
459 static inline void set_page_order(struct page *page, unsigned int order)
461 set_page_private(page, order);
462 __SetPageBuddy(page);
465 static inline void rmv_page_order(struct page *page)
467 __ClearPageBuddy(page);
468 set_page_private(page, 0);
472 * Locate the struct page for both the matching buddy in our
473 * pair (buddy1) and the combined O(n+1) page they form (page).
475 * 1) Any buddy B1 will have an order O twin B2 which satisfies
476 * the following equation:
477 * B2 = B1 ^ (1 << O)
478 * For example, if the starting buddy (buddy2) is #8 its order
479 * 1 buddy is #10:
480 * B2 = 8 ^ (1 << 1) = 8 ^ 2 = 10
482 * 2) Any buddy B will have an order O+1 parent P which
483 * satisfies the following equation:
484 * P = B & ~(1 << O)
486 * Assumption: *_mem_map is contiguous at least up to MAX_ORDER
488 static inline unsigned long
489 __find_buddy_index(unsigned long page_idx, unsigned int order)
491 return page_idx ^ (1 << order);
495 * This function checks whether a page is free && is the buddy
496 * we can do coalesce a page and its buddy if
497 * (a) the buddy is not in a hole &&
498 * (b) the buddy is in the buddy system &&
499 * (c) a page and its buddy have the same order &&
500 * (d) a page and its buddy are in the same zone.
502 * For recording whether a page is in the buddy system, we set ->_mapcount
503 * PAGE_BUDDY_MAPCOUNT_VALUE.
504 * Setting, clearing, and testing _mapcount PAGE_BUDDY_MAPCOUNT_VALUE is
505 * serialized by zone->lock.
507 * For recording page's order, we use page_private(page).
509 static inline int page_is_buddy(struct page *page, struct page *buddy,
510 unsigned int order)
512 if (!pfn_valid_within(page_to_pfn(buddy)))
513 return 0;
515 if (page_is_guard(buddy) && page_order(buddy) == order) {
516 VM_BUG_ON_PAGE(page_count(buddy) != 0, buddy);
518 if (page_zone_id(page) != page_zone_id(buddy))
519 return 0;
521 return 1;
524 if (PageBuddy(buddy) && page_order(buddy) == order) {
525 VM_BUG_ON_PAGE(page_count(buddy) != 0, buddy);
528 * zone check is done late to avoid uselessly
529 * calculating zone/node ids for pages that could
530 * never merge.
532 if (page_zone_id(page) != page_zone_id(buddy))
533 return 0;
535 return 1;
537 return 0;
541 * Freeing function for a buddy system allocator.
543 * The concept of a buddy system is to maintain direct-mapped table
544 * (containing bit values) for memory blocks of various "orders".
545 * The bottom level table contains the map for the smallest allocatable
546 * units of memory (here, pages), and each level above it describes
547 * pairs of units from the levels below, hence, "buddies".
548 * At a high level, all that happens here is marking the table entry
549 * at the bottom level available, and propagating the changes upward
550 * as necessary, plus some accounting needed to play nicely with other
551 * parts of the VM system.
552 * At each level, we keep a list of pages, which are heads of continuous
553 * free pages of length of (1 << order) and marked with _mapcount
554 * PAGE_BUDDY_MAPCOUNT_VALUE. Page's order is recorded in page_private(page)
555 * field.
556 * So when we are allocating or freeing one, we can derive the state of the
557 * other. That is, if we allocate a small block, and both were
558 * free, the remainder of the region must be split into blocks.
559 * If a block is freed, and its buddy is also free, then this
560 * triggers coalescing into a block of larger size.
562 * -- nyc
565 static inline void __free_one_page(struct page *page,
566 unsigned long pfn,
567 struct zone *zone, unsigned int order,
568 int migratetype)
570 unsigned long page_idx;
571 unsigned long combined_idx;
572 unsigned long uninitialized_var(buddy_idx);
573 struct page *buddy;
575 VM_BUG_ON(!zone_is_initialized(zone));
577 if (unlikely(PageCompound(page)))
578 if (unlikely(destroy_compound_page(page, order)))
579 return;
581 VM_BUG_ON(migratetype == -1);
583 page_idx = pfn & ((1 << MAX_ORDER) - 1);
585 VM_BUG_ON_PAGE(page_idx & ((1 << order) - 1), page);
586 VM_BUG_ON_PAGE(bad_range(zone, page), page);
588 while (order < MAX_ORDER-1) {
589 buddy_idx = __find_buddy_index(page_idx, order);
590 buddy = page + (buddy_idx - page_idx);
591 if (!page_is_buddy(page, buddy, order))
592 break;
594 * Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page,
595 * merge with it and move up one order.
597 if (page_is_guard(buddy)) {
598 clear_page_guard_flag(buddy);
599 set_page_private(page, 0);
600 __mod_zone_freepage_state(zone, 1 << order,
601 migratetype);
602 } else {
603 list_del(&buddy->lru);
604 zone->free_area[order].nr_free--;
605 rmv_page_order(buddy);
607 combined_idx = buddy_idx & page_idx;
608 page = page + (combined_idx - page_idx);
609 page_idx = combined_idx;
610 order++;
612 set_page_order(page, order);
615 * If this is not the largest possible page, check if the buddy
616 * of the next-highest order is free. If it is, it's possible
617 * that pages are being freed that will coalesce soon. In case,
618 * that is happening, add the free page to the tail of the list
619 * so it's less likely to be used soon and more likely to be merged
620 * as a higher order page
622 if ((order < MAX_ORDER-2) && pfn_valid_within(page_to_pfn(buddy))) {
623 struct page *higher_page, *higher_buddy;
624 combined_idx = buddy_idx & page_idx;
625 higher_page = page + (combined_idx - page_idx);
626 buddy_idx = __find_buddy_index(combined_idx, order + 1);
627 higher_buddy = higher_page + (buddy_idx - combined_idx);
628 if (page_is_buddy(higher_page, higher_buddy, order + 1)) {
629 list_add_tail(&page->lru,
630 &zone->free_area[order].free_list[migratetype]);
631 goto out;
635 list_add(&page->lru, &zone->free_area[order].free_list[migratetype]);
636 out:
637 zone->free_area[order].nr_free++;
640 static inline int free_pages_check(struct page *page)
642 const char *bad_reason = NULL;
643 unsigned long bad_flags = 0;
645 if (unlikely(page_mapcount(page)))
646 bad_reason = "nonzero mapcount";
647 if (unlikely(page->mapping != NULL))
648 bad_reason = "non-NULL mapping";
649 if (unlikely(atomic_read(&page->_count) != 0))
650 bad_reason = "nonzero _count";
651 if (unlikely(page->flags & PAGE_FLAGS_CHECK_AT_FREE)) {
652 bad_reason = "PAGE_FLAGS_CHECK_AT_FREE flag(s) set";
653 bad_flags = PAGE_FLAGS_CHECK_AT_FREE;
655 if (unlikely(mem_cgroup_bad_page_check(page)))
656 bad_reason = "cgroup check failed";
657 if (unlikely(bad_reason)) {
658 bad_page(page, bad_reason, bad_flags);
659 return 1;
661 page_cpupid_reset_last(page);
662 if (page->flags & PAGE_FLAGS_CHECK_AT_PREP)
663 page->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
664 return 0;
668 * Frees a number of pages from the PCP lists
669 * Assumes all pages on list are in same zone, and of same order.
670 * count is the number of pages to free.
672 * If the zone was previously in an "all pages pinned" state then look to
673 * see if this freeing clears that state.
675 * And clear the zone's pages_scanned counter, to hold off the "all pages are
676 * pinned" detection logic.
678 static void free_pcppages_bulk(struct zone *zone, int count,
679 struct per_cpu_pages *pcp)
681 int migratetype = 0;
682 int batch_free = 0;
683 int to_free = count;
685 spin_lock(&zone->lock);
686 zone->pages_scanned = 0;
688 while (to_free) {
689 struct page *page;
690 struct list_head *list;
693 * Remove pages from lists in a round-robin fashion. A
694 * batch_free count is maintained that is incremented when an
695 * empty list is encountered. This is so more pages are freed
696 * off fuller lists instead of spinning excessively around empty
697 * lists
699 do {
700 batch_free++;
701 if (++migratetype == MIGRATE_PCPTYPES)
702 migratetype = 0;
703 list = &pcp->lists[migratetype];
704 } while (list_empty(list));
706 /* This is the only non-empty list. Free them all. */
707 if (batch_free == MIGRATE_PCPTYPES)
708 batch_free = to_free;
710 do {
711 int mt; /* migratetype of the to-be-freed page */
713 page = list_entry(list->prev, struct page, lru);
714 /* must delete as __free_one_page list manipulates */
715 list_del(&page->lru);
716 mt = get_freepage_migratetype(page);
717 /* MIGRATE_MOVABLE list may include MIGRATE_RESERVEs */
718 __free_one_page(page, page_to_pfn(page), zone, 0, mt);
719 trace_mm_page_pcpu_drain(page, 0, mt);
720 if (likely(!is_migrate_isolate_page(page))) {
721 __mod_zone_page_state(zone, NR_FREE_PAGES, 1);
722 if (is_migrate_cma(mt))
723 __mod_zone_page_state(zone, NR_FREE_CMA_PAGES, 1);
725 } while (--to_free && --batch_free && !list_empty(list));
727 spin_unlock(&zone->lock);
730 static void free_one_page(struct zone *zone,
731 struct page *page, unsigned long pfn,
732 unsigned int order,
733 int migratetype)
735 spin_lock(&zone->lock);
736 zone->pages_scanned = 0;
738 __free_one_page(page, pfn, zone, order, migratetype);
739 if (unlikely(!is_migrate_isolate(migratetype)))
740 __mod_zone_freepage_state(zone, 1 << order, migratetype);
741 spin_unlock(&zone->lock);
744 static bool free_pages_prepare(struct page *page, unsigned int order)
746 int i;
747 int bad = 0;
749 trace_mm_page_free(page, order);
750 kmemcheck_free_shadow(page, order);
752 if (PageAnon(page))
753 page->mapping = NULL;
754 for (i = 0; i < (1 << order); i++)
755 bad += free_pages_check(page + i);
756 if (bad)
757 return false;
759 if (!PageHighMem(page)) {
760 debug_check_no_locks_freed(page_address(page),
761 PAGE_SIZE << order);
762 debug_check_no_obj_freed(page_address(page),
763 PAGE_SIZE << order);
765 arch_free_page(page, order);
766 kernel_map_pages(page, 1 << order, 0);
768 return true;
771 static void __free_pages_ok(struct page *page, unsigned int order)
773 unsigned long flags;
774 int migratetype;
775 unsigned long pfn = page_to_pfn(page);
777 if (!free_pages_prepare(page, order))
778 return;
780 migratetype = get_pfnblock_migratetype(page, pfn);
781 local_irq_save(flags);
782 __count_vm_events(PGFREE, 1 << order);
783 set_freepage_migratetype(page, migratetype);
784 free_one_page(page_zone(page), page, pfn, order, migratetype);
785 local_irq_restore(flags);
788 void __init __free_pages_bootmem(struct page *page, unsigned int order)
790 unsigned int nr_pages = 1 << order;
791 struct page *p = page;
792 unsigned int loop;
794 prefetchw(p);
795 for (loop = 0; loop < (nr_pages - 1); loop++, p++) {
796 prefetchw(p + 1);
797 __ClearPageReserved(p);
798 set_page_count(p, 0);
800 __ClearPageReserved(p);
801 set_page_count(p, 0);
803 page_zone(page)->managed_pages += nr_pages;
804 set_page_refcounted(page);
805 __free_pages(page, order);
808 #ifdef CONFIG_CMA
809 /* Free whole pageblock and set its migration type to MIGRATE_CMA. */
810 void __init init_cma_reserved_pageblock(struct page *page)
812 unsigned i = pageblock_nr_pages;
813 struct page *p = page;
815 do {
816 __ClearPageReserved(p);
817 set_page_count(p, 0);
818 } while (++p, --i);
820 set_pageblock_migratetype(page, MIGRATE_CMA);
822 if (pageblock_order >= MAX_ORDER) {
823 i = pageblock_nr_pages;
824 p = page;
825 do {
826 set_page_refcounted(p);
827 __free_pages(p, MAX_ORDER - 1);
828 p += MAX_ORDER_NR_PAGES;
829 } while (i -= MAX_ORDER_NR_PAGES);
830 } else {
831 set_page_refcounted(page);
832 __free_pages(page, pageblock_order);
835 adjust_managed_page_count(page, pageblock_nr_pages);
837 #endif
840 * The order of subdivision here is critical for the IO subsystem.
841 * Please do not alter this order without good reasons and regression
842 * testing. Specifically, as large blocks of memory are subdivided,
843 * the order in which smaller blocks are delivered depends on the order
844 * they're subdivided in this function. This is the primary factor
845 * influencing the order in which pages are delivered to the IO
846 * subsystem according to empirical testing, and this is also justified
847 * by considering the behavior of a buddy system containing a single
848 * large block of memory acted on by a series of small allocations.
849 * This behavior is a critical factor in sglist merging's success.
851 * -- nyc
853 static inline void expand(struct zone *zone, struct page *page,
854 int low, int high, struct free_area *area,
855 int migratetype)
857 unsigned long size = 1 << high;
859 while (high > low) {
860 area--;
861 high--;
862 size >>= 1;
863 VM_BUG_ON_PAGE(bad_range(zone, &page[size]), &page[size]);
865 #ifdef CONFIG_DEBUG_PAGEALLOC
866 if (high < debug_guardpage_minorder()) {
868 * Mark as guard pages (or page), that will allow to
869 * merge back to allocator when buddy will be freed.
870 * Corresponding page table entries will not be touched,
871 * pages will stay not present in virtual address space
873 INIT_LIST_HEAD(&page[size].lru);
874 set_page_guard_flag(&page[size]);
875 set_page_private(&page[size], high);
876 /* Guard pages are not available for any usage */
877 __mod_zone_freepage_state(zone, -(1 << high),
878 migratetype);
879 continue;
881 #endif
882 list_add(&page[size].lru, &area->free_list[migratetype]);
883 area->nr_free++;
884 set_page_order(&page[size], high);
889 * This page is about to be returned from the page allocator
891 static inline int check_new_page(struct page *page)
893 const char *bad_reason = NULL;
894 unsigned long bad_flags = 0;
896 if (unlikely(page_mapcount(page)))
897 bad_reason = "nonzero mapcount";
898 if (unlikely(page->mapping != NULL))
899 bad_reason = "non-NULL mapping";
900 if (unlikely(atomic_read(&page->_count) != 0))
901 bad_reason = "nonzero _count";
902 if (unlikely(page->flags & PAGE_FLAGS_CHECK_AT_PREP)) {
903 bad_reason = "PAGE_FLAGS_CHECK_AT_PREP flag set";
904 bad_flags = PAGE_FLAGS_CHECK_AT_PREP;
906 if (unlikely(mem_cgroup_bad_page_check(page)))
907 bad_reason = "cgroup check failed";
908 if (unlikely(bad_reason)) {
909 bad_page(page, bad_reason, bad_flags);
910 return 1;
912 return 0;
915 static int prep_new_page(struct page *page, unsigned int order, gfp_t gfp_flags)
917 int i;
919 for (i = 0; i < (1 << order); i++) {
920 struct page *p = page + i;
921 if (unlikely(check_new_page(p)))
922 return 1;
925 set_page_private(page, 0);
926 set_page_refcounted(page);
928 arch_alloc_page(page, order);
929 kernel_map_pages(page, 1 << order, 1);
931 if (gfp_flags & __GFP_ZERO)
932 prep_zero_page(page, order, gfp_flags);
934 if (order && (gfp_flags & __GFP_COMP))
935 prep_compound_page(page, order);
937 return 0;
941 * Go through the free lists for the given migratetype and remove
942 * the smallest available page from the freelists
944 static inline
945 struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
946 int migratetype)
948 unsigned int current_order;
949 struct free_area *area;
950 struct page *page;
952 /* Find a page of the appropriate size in the preferred list */
953 for (current_order = order; current_order < MAX_ORDER; ++current_order) {
954 area = &(zone->free_area[current_order]);
955 if (list_empty(&area->free_list[migratetype]))
956 continue;
958 page = list_entry(area->free_list[migratetype].next,
959 struct page, lru);
960 list_del(&page->lru);
961 rmv_page_order(page);
962 area->nr_free--;
963 expand(zone, page, order, current_order, area, migratetype);
964 set_freepage_migratetype(page, migratetype);
965 return page;
968 return NULL;
973 * This array describes the order lists are fallen back to when
974 * the free lists for the desirable migrate type are depleted
976 static int fallbacks[MIGRATE_TYPES][4] = {
977 [MIGRATE_UNMOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE, MIGRATE_RESERVE },
978 [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE, MIGRATE_MOVABLE, MIGRATE_RESERVE },
979 #ifdef CONFIG_CMA
980 [MIGRATE_MOVABLE] = { MIGRATE_CMA, MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_RESERVE },
981 [MIGRATE_CMA] = { MIGRATE_RESERVE }, /* Never used */
982 #else
983 [MIGRATE_MOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_RESERVE },
984 #endif
985 [MIGRATE_RESERVE] = { MIGRATE_RESERVE }, /* Never used */
986 #ifdef CONFIG_MEMORY_ISOLATION
987 [MIGRATE_ISOLATE] = { MIGRATE_RESERVE }, /* Never used */
988 #endif
992 * Move the free pages in a range to the free lists of the requested type.
993 * Note that start_page and end_pages are not aligned on a pageblock
994 * boundary. If alignment is required, use move_freepages_block()
996 int move_freepages(struct zone *zone,
997 struct page *start_page, struct page *end_page,
998 int migratetype)
1000 struct page *page;
1001 unsigned long order;
1002 int pages_moved = 0;
1004 #ifndef CONFIG_HOLES_IN_ZONE
1006 * page_zone is not safe to call in this context when
1007 * CONFIG_HOLES_IN_ZONE is set. This bug check is probably redundant
1008 * anyway as we check zone boundaries in move_freepages_block().
1009 * Remove at a later date when no bug reports exist related to
1010 * grouping pages by mobility
1012 BUG_ON(page_zone(start_page) != page_zone(end_page));
1013 #endif
1015 for (page = start_page; page <= end_page;) {
1016 /* Make sure we are not inadvertently changing nodes */
1017 VM_BUG_ON_PAGE(page_to_nid(page) != zone_to_nid(zone), page);
1019 if (!pfn_valid_within(page_to_pfn(page))) {
1020 page++;
1021 continue;
1024 if (!PageBuddy(page)) {
1025 page++;
1026 continue;
1029 order = page_order(page);
1030 list_move(&page->lru,
1031 &zone->free_area[order].free_list[migratetype]);
1032 set_freepage_migratetype(page, migratetype);
1033 page += 1 << order;
1034 pages_moved += 1 << order;
1037 return pages_moved;
1040 int move_freepages_block(struct zone *zone, struct page *page,
1041 int migratetype)
1043 unsigned long start_pfn, end_pfn;
1044 struct page *start_page, *end_page;
1046 start_pfn = page_to_pfn(page);
1047 start_pfn = start_pfn & ~(pageblock_nr_pages-1);
1048 start_page = pfn_to_page(start_pfn);
1049 end_page = start_page + pageblock_nr_pages - 1;
1050 end_pfn = start_pfn + pageblock_nr_pages - 1;
1052 /* Do not cross zone boundaries */
1053 if (!zone_spans_pfn(zone, start_pfn))
1054 start_page = page;
1055 if (!zone_spans_pfn(zone, end_pfn))
1056 return 0;
1058 return move_freepages(zone, start_page, end_page, migratetype);
1061 static void change_pageblock_range(struct page *pageblock_page,
1062 int start_order, int migratetype)
1064 int nr_pageblocks = 1 << (start_order - pageblock_order);
1066 while (nr_pageblocks--) {
1067 set_pageblock_migratetype(pageblock_page, migratetype);
1068 pageblock_page += pageblock_nr_pages;
1073 * If breaking a large block of pages, move all free pages to the preferred
1074 * allocation list. If falling back for a reclaimable kernel allocation, be
1075 * more aggressive about taking ownership of free pages.
1077 * On the other hand, never change migration type of MIGRATE_CMA pageblocks
1078 * nor move CMA pages to different free lists. We don't want unmovable pages
1079 * to be allocated from MIGRATE_CMA areas.
1081 * Returns the allocation migratetype if free pages were stolen, or the
1082 * fallback migratetype if it was decided not to steal.
1084 static int try_to_steal_freepages(struct zone *zone, struct page *page,
1085 int start_type, int fallback_type)
1087 int current_order = page_order(page);
1090 * When borrowing from MIGRATE_CMA, we need to release the excess
1091 * buddy pages to CMA itself. We also ensure the freepage_migratetype
1092 * is set to CMA so it is returned to the correct freelist in case
1093 * the page ends up being not actually allocated from the pcp lists.
1095 if (is_migrate_cma(fallback_type))
1096 return fallback_type;
1098 /* Take ownership for orders >= pageblock_order */
1099 if (current_order >= pageblock_order) {
1100 change_pageblock_range(page, current_order, start_type);
1101 return start_type;
1104 if (current_order >= pageblock_order / 2 ||
1105 start_type == MIGRATE_RECLAIMABLE ||
1106 page_group_by_mobility_disabled) {
1107 int pages;
1109 pages = move_freepages_block(zone, page, start_type);
1111 /* Claim the whole block if over half of it is free */
1112 if (pages >= (1 << (pageblock_order-1)) ||
1113 page_group_by_mobility_disabled)
1114 set_pageblock_migratetype(page, start_type);
1116 return start_type;
1119 return fallback_type;
1122 /* Remove an element from the buddy allocator from the fallback list */
1123 static inline struct page *
1124 __rmqueue_fallback(struct zone *zone, unsigned int order, int start_migratetype)
1126 struct free_area *area;
1127 unsigned int current_order;
1128 struct page *page;
1129 int migratetype, new_type, i;
1131 /* Find the largest possible block of pages in the other list */
1132 for (current_order = MAX_ORDER-1;
1133 current_order >= order && current_order <= MAX_ORDER-1;
1134 --current_order) {
1135 for (i = 0;; i++) {
1136 migratetype = fallbacks[start_migratetype][i];
1138 /* MIGRATE_RESERVE handled later if necessary */
1139 if (migratetype == MIGRATE_RESERVE)
1140 break;
1142 area = &(zone->free_area[current_order]);
1143 if (list_empty(&area->free_list[migratetype]))
1144 continue;
1146 page = list_entry(area->free_list[migratetype].next,
1147 struct page, lru);
1148 area->nr_free--;
1150 new_type = try_to_steal_freepages(zone, page,
1151 start_migratetype,
1152 migratetype);
1154 /* Remove the page from the freelists */
1155 list_del(&page->lru);
1156 rmv_page_order(page);
1158 expand(zone, page, order, current_order, area,
1159 new_type);
1160 /* The freepage_migratetype may differ from pageblock's
1161 * migratetype depending on the decisions in
1162 * try_to_steal_freepages. This is OK as long as it does
1163 * not differ for MIGRATE_CMA type.
1165 set_freepage_migratetype(page, new_type);
1167 trace_mm_page_alloc_extfrag(page, order, current_order,
1168 start_migratetype, migratetype);
1170 return page;
1174 return NULL;
1178 * Do the hard work of removing an element from the buddy allocator.
1179 * Call me with the zone->lock already held.
1181 static struct page *__rmqueue(struct zone *zone, unsigned int order,
1182 int migratetype)
1184 struct page *page;
1186 retry_reserve:
1187 page = __rmqueue_smallest(zone, order, migratetype);
1189 if (unlikely(!page) && migratetype != MIGRATE_RESERVE) {
1190 page = __rmqueue_fallback(zone, order, migratetype);
1193 * Use MIGRATE_RESERVE rather than fail an allocation. goto
1194 * is used because __rmqueue_smallest is an inline function
1195 * and we want just one call site
1197 if (!page) {
1198 migratetype = MIGRATE_RESERVE;
1199 goto retry_reserve;
1203 trace_mm_page_alloc_zone_locked(page, order, migratetype);
1204 return page;
1208 * Obtain a specified number of elements from the buddy allocator, all under
1209 * a single hold of the lock, for efficiency. Add them to the supplied list.
1210 * Returns the number of new pages which were placed at *list.
1212 static int rmqueue_bulk(struct zone *zone, unsigned int order,
1213 unsigned long count, struct list_head *list,
1214 int migratetype, bool cold)
1216 int i;
1218 spin_lock(&zone->lock);
1219 for (i = 0; i < count; ++i) {
1220 struct page *page = __rmqueue(zone, order, migratetype);
1221 if (unlikely(page == NULL))
1222 break;
1225 * Split buddy pages returned by expand() are received here
1226 * in physical page order. The page is added to the callers and
1227 * list and the list head then moves forward. From the callers
1228 * perspective, the linked list is ordered by page number in
1229 * some conditions. This is useful for IO devices that can
1230 * merge IO requests if the physical pages are ordered
1231 * properly.
1233 if (likely(!cold))
1234 list_add(&page->lru, list);
1235 else
1236 list_add_tail(&page->lru, list);
1237 list = &page->lru;
1238 if (is_migrate_cma(get_freepage_migratetype(page)))
1239 __mod_zone_page_state(zone, NR_FREE_CMA_PAGES,
1240 -(1 << order));
1242 __mod_zone_page_state(zone, NR_FREE_PAGES, -(i << order));
1243 spin_unlock(&zone->lock);
1244 return i;
1247 #ifdef CONFIG_NUMA
1249 * Called from the vmstat counter updater to drain pagesets of this
1250 * currently executing processor on remote nodes after they have
1251 * expired.
1253 * Note that this function must be called with the thread pinned to
1254 * a single processor.
1256 void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp)
1258 unsigned long flags;
1259 int to_drain;
1260 unsigned long batch;
1262 local_irq_save(flags);
1263 batch = ACCESS_ONCE(pcp->batch);
1264 if (pcp->count >= batch)
1265 to_drain = batch;
1266 else
1267 to_drain = pcp->count;
1268 if (to_drain > 0) {
1269 free_pcppages_bulk(zone, to_drain, pcp);
1270 pcp->count -= to_drain;
1272 local_irq_restore(flags);
1274 #endif
1277 * Drain pages of the indicated processor.
1279 * The processor must either be the current processor and the
1280 * thread pinned to the current processor or a processor that
1281 * is not online.
1283 static void drain_pages(unsigned int cpu)
1285 unsigned long flags;
1286 struct zone *zone;
1288 for_each_populated_zone(zone) {
1289 struct per_cpu_pageset *pset;
1290 struct per_cpu_pages *pcp;
1292 local_irq_save(flags);
1293 pset = per_cpu_ptr(zone->pageset, cpu);
1295 pcp = &pset->pcp;
1296 if (pcp->count) {
1297 free_pcppages_bulk(zone, pcp->count, pcp);
1298 pcp->count = 0;
1300 local_irq_restore(flags);
1305 * Spill all of this CPU's per-cpu pages back into the buddy allocator.
1307 void drain_local_pages(void *arg)
1309 drain_pages(smp_processor_id());
1313 * Spill all the per-cpu pages from all CPUs back into the buddy allocator.
1315 * Note that this code is protected against sending an IPI to an offline
1316 * CPU but does not guarantee sending an IPI to newly hotplugged CPUs:
1317 * on_each_cpu_mask() blocks hotplug and won't talk to offlined CPUs but
1318 * nothing keeps CPUs from showing up after we populated the cpumask and
1319 * before the call to on_each_cpu_mask().
1321 void drain_all_pages(void)
1323 int cpu;
1324 struct per_cpu_pageset *pcp;
1325 struct zone *zone;
1328 * Allocate in the BSS so we wont require allocation in
1329 * direct reclaim path for CONFIG_CPUMASK_OFFSTACK=y
1331 static cpumask_t cpus_with_pcps;
1334 * We don't care about racing with CPU hotplug event
1335 * as offline notification will cause the notified
1336 * cpu to drain that CPU pcps and on_each_cpu_mask
1337 * disables preemption as part of its processing
1339 for_each_online_cpu(cpu) {
1340 bool has_pcps = false;
1341 for_each_populated_zone(zone) {
1342 pcp = per_cpu_ptr(zone->pageset, cpu);
1343 if (pcp->pcp.count) {
1344 has_pcps = true;
1345 break;
1348 if (has_pcps)
1349 cpumask_set_cpu(cpu, &cpus_with_pcps);
1350 else
1351 cpumask_clear_cpu(cpu, &cpus_with_pcps);
1353 on_each_cpu_mask(&cpus_with_pcps, drain_local_pages, NULL, 1);
1356 #ifdef CONFIG_HIBERNATION
1359 * Touch the watchdog for every WD_PAGE_COUNT pages.
1361 #define WD_PAGE_COUNT (128*1024)
1363 void mark_free_pages(struct zone *zone)
1365 unsigned long pfn, max_zone_pfn, page_count = WD_PAGE_COUNT;
1366 unsigned long flags;
1367 unsigned int order, t;
1368 struct list_head *curr;
1370 if (zone_is_empty(zone))
1371 return;
1373 spin_lock_irqsave(&zone->lock, flags);
1375 max_zone_pfn = zone_end_pfn(zone);
1376 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
1377 if (pfn_valid(pfn)) {
1378 struct page *page = pfn_to_page(pfn);
1380 if (!--page_count) {
1381 touch_nmi_watchdog();
1382 page_count = WD_PAGE_COUNT;
1385 if (!swsusp_page_is_forbidden(page))
1386 swsusp_unset_page_free(page);
1389 for_each_migratetype_order(order, t) {
1390 list_for_each(curr, &zone->free_area[order].free_list[t]) {
1391 unsigned long i;
1393 pfn = page_to_pfn(list_entry(curr, struct page, lru));
1394 for (i = 0; i < (1UL << order); i++) {
1395 if (!--page_count) {
1396 touch_nmi_watchdog();
1397 page_count = WD_PAGE_COUNT;
1399 swsusp_set_page_free(pfn_to_page(pfn + i));
1403 spin_unlock_irqrestore(&zone->lock, flags);
1405 #endif /* CONFIG_PM */
1408 * Free a 0-order page
1409 * cold == true ? free a cold page : free a hot page
1411 void free_hot_cold_page(struct page *page, bool cold)
1413 struct zone *zone = page_zone(page);
1414 struct per_cpu_pages *pcp;
1415 unsigned long flags;
1416 unsigned long pfn = page_to_pfn(page);
1417 int migratetype;
1419 if (!free_pages_prepare(page, 0))
1420 return;
1422 migratetype = get_pfnblock_migratetype(page, pfn);
1423 set_freepage_migratetype(page, migratetype);
1424 local_irq_save(flags);
1425 __count_vm_event(PGFREE);
1428 * We only track unmovable, reclaimable and movable on pcp lists.
1429 * Free ISOLATE pages back to the allocator because they are being
1430 * offlined but treat RESERVE as movable pages so we can get those
1431 * areas back if necessary. Otherwise, we may have to free
1432 * excessively into the page allocator
1434 if (migratetype >= MIGRATE_PCPTYPES) {
1435 if (unlikely(is_migrate_isolate(migratetype))) {
1436 free_one_page(zone, page, pfn, 0, migratetype);
1437 goto out;
1439 migratetype = MIGRATE_MOVABLE;
1442 pcp = &this_cpu_ptr(zone->pageset)->pcp;
1443 if (!cold)
1444 list_add(&page->lru, &pcp->lists[migratetype]);
1445 else
1446 list_add_tail(&page->lru, &pcp->lists[migratetype]);
1447 pcp->count++;
1448 if (pcp->count >= pcp->high) {
1449 unsigned long batch = ACCESS_ONCE(pcp->batch);
1450 free_pcppages_bulk(zone, batch, pcp);
1451 pcp->count -= batch;
1454 out:
1455 local_irq_restore(flags);
1459 * Free a list of 0-order pages
1461 void free_hot_cold_page_list(struct list_head *list, bool cold)
1463 struct page *page, *next;
1465 list_for_each_entry_safe(page, next, list, lru) {
1466 trace_mm_page_free_batched(page, cold);
1467 free_hot_cold_page(page, cold);
1472 * split_page takes a non-compound higher-order page, and splits it into
1473 * n (1<<order) sub-pages: page[0..n]
1474 * Each sub-page must be freed individually.
1476 * Note: this is probably too low level an operation for use in drivers.
1477 * Please consult with lkml before using this in your driver.
1479 void split_page(struct page *page, unsigned int order)
1481 int i;
1483 VM_BUG_ON_PAGE(PageCompound(page), page);
1484 VM_BUG_ON_PAGE(!page_count(page), page);
1486 #ifdef CONFIG_KMEMCHECK
1488 * Split shadow pages too, because free(page[0]) would
1489 * otherwise free the whole shadow.
1491 if (kmemcheck_page_is_tracked(page))
1492 split_page(virt_to_page(page[0].shadow), order);
1493 #endif
1495 for (i = 1; i < (1 << order); i++)
1496 set_page_refcounted(page + i);
1498 EXPORT_SYMBOL_GPL(split_page);
1500 static int __isolate_free_page(struct page *page, unsigned int order)
1502 unsigned long watermark;
1503 struct zone *zone;
1504 int mt;
1506 BUG_ON(!PageBuddy(page));
1508 zone = page_zone(page);
1509 mt = get_pageblock_migratetype(page);
1511 if (!is_migrate_isolate(mt)) {
1512 /* Obey watermarks as if the page was being allocated */
1513 watermark = low_wmark_pages(zone) + (1 << order);
1514 if (!zone_watermark_ok(zone, 0, watermark, 0, 0))
1515 return 0;
1517 __mod_zone_freepage_state(zone, -(1UL << order), mt);
1520 /* Remove page from free list */
1521 list_del(&page->lru);
1522 zone->free_area[order].nr_free--;
1523 rmv_page_order(page);
1525 /* Set the pageblock if the isolated page is at least a pageblock */
1526 if (order >= pageblock_order - 1) {
1527 struct page *endpage = page + (1 << order) - 1;
1528 for (; page < endpage; page += pageblock_nr_pages) {
1529 int mt = get_pageblock_migratetype(page);
1530 if (!is_migrate_isolate(mt) && !is_migrate_cma(mt))
1531 set_pageblock_migratetype(page,
1532 MIGRATE_MOVABLE);
1536 return 1UL << order;
1540 * Similar to split_page except the page is already free. As this is only
1541 * being used for migration, the migratetype of the block also changes.
1542 * As this is called with interrupts disabled, the caller is responsible
1543 * for calling arch_alloc_page() and kernel_map_page() after interrupts
1544 * are enabled.
1546 * Note: this is probably too low level an operation for use in drivers.
1547 * Please consult with lkml before using this in your driver.
1549 int split_free_page(struct page *page)
1551 unsigned int order;
1552 int nr_pages;
1554 order = page_order(page);
1556 nr_pages = __isolate_free_page(page, order);
1557 if (!nr_pages)
1558 return 0;
1560 /* Split into individual pages */
1561 set_page_refcounted(page);
1562 split_page(page, order);
1563 return nr_pages;
1567 * Really, prep_compound_page() should be called from __rmqueue_bulk(). But
1568 * we cheat by calling it from here, in the order > 0 path. Saves a branch
1569 * or two.
1571 static inline
1572 struct page *buffered_rmqueue(struct zone *preferred_zone,
1573 struct zone *zone, unsigned int order,
1574 gfp_t gfp_flags, int migratetype)
1576 unsigned long flags;
1577 struct page *page;
1578 bool cold = ((gfp_flags & __GFP_COLD) != 0);
1580 again:
1581 if (likely(order == 0)) {
1582 struct per_cpu_pages *pcp;
1583 struct list_head *list;
1585 local_irq_save(flags);
1586 pcp = &this_cpu_ptr(zone->pageset)->pcp;
1587 list = &pcp->lists[migratetype];
1588 if (list_empty(list)) {
1589 pcp->count += rmqueue_bulk(zone, 0,
1590 pcp->batch, list,
1591 migratetype, cold);
1592 if (unlikely(list_empty(list)))
1593 goto failed;
1596 if (cold)
1597 page = list_entry(list->prev, struct page, lru);
1598 else
1599 page = list_entry(list->next, struct page, lru);
1601 list_del(&page->lru);
1602 pcp->count--;
1603 } else {
1604 if (unlikely(gfp_flags & __GFP_NOFAIL)) {
1606 * __GFP_NOFAIL is not to be used in new code.
1608 * All __GFP_NOFAIL callers should be fixed so that they
1609 * properly detect and handle allocation failures.
1611 * We most definitely don't want callers attempting to
1612 * allocate greater than order-1 page units with
1613 * __GFP_NOFAIL.
1615 WARN_ON_ONCE(order > 1);
1617 spin_lock_irqsave(&zone->lock, flags);
1618 page = __rmqueue(zone, order, migratetype);
1619 spin_unlock(&zone->lock);
1620 if (!page)
1621 goto failed;
1622 __mod_zone_freepage_state(zone, -(1 << order),
1623 get_freepage_migratetype(page));
1626 __mod_zone_page_state(zone, NR_ALLOC_BATCH, -(1 << order));
1628 __count_zone_vm_events(PGALLOC, zone, 1 << order);
1629 zone_statistics(preferred_zone, zone, gfp_flags);
1630 local_irq_restore(flags);
1632 VM_BUG_ON_PAGE(bad_range(zone, page), page);
1633 if (prep_new_page(page, order, gfp_flags))
1634 goto again;
1635 return page;
1637 failed:
1638 local_irq_restore(flags);
1639 return NULL;
1642 #ifdef CONFIG_FAIL_PAGE_ALLOC
1644 static struct {
1645 struct fault_attr attr;
1647 u32 ignore_gfp_highmem;
1648 u32 ignore_gfp_wait;
1649 u32 min_order;
1650 } fail_page_alloc = {
1651 .attr = FAULT_ATTR_INITIALIZER,
1652 .ignore_gfp_wait = 1,
1653 .ignore_gfp_highmem = 1,
1654 .min_order = 1,
1657 static int __init setup_fail_page_alloc(char *str)
1659 return setup_fault_attr(&fail_page_alloc.attr, str);
1661 __setup("fail_page_alloc=", setup_fail_page_alloc);
1663 static bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
1665 if (order < fail_page_alloc.min_order)
1666 return false;
1667 if (gfp_mask & __GFP_NOFAIL)
1668 return false;
1669 if (fail_page_alloc.ignore_gfp_highmem && (gfp_mask & __GFP_HIGHMEM))
1670 return false;
1671 if (fail_page_alloc.ignore_gfp_wait && (gfp_mask & __GFP_WAIT))
1672 return false;
1674 return should_fail(&fail_page_alloc.attr, 1 << order);
1677 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
1679 static int __init fail_page_alloc_debugfs(void)
1681 umode_t mode = S_IFREG | S_IRUSR | S_IWUSR;
1682 struct dentry *dir;
1684 dir = fault_create_debugfs_attr("fail_page_alloc", NULL,
1685 &fail_page_alloc.attr);
1686 if (IS_ERR(dir))
1687 return PTR_ERR(dir);
1689 if (!debugfs_create_bool("ignore-gfp-wait", mode, dir,
1690 &fail_page_alloc.ignore_gfp_wait))
1691 goto fail;
1692 if (!debugfs_create_bool("ignore-gfp-highmem", mode, dir,
1693 &fail_page_alloc.ignore_gfp_highmem))
1694 goto fail;
1695 if (!debugfs_create_u32("min-order", mode, dir,
1696 &fail_page_alloc.min_order))
1697 goto fail;
1699 return 0;
1700 fail:
1701 debugfs_remove_recursive(dir);
1703 return -ENOMEM;
1706 late_initcall(fail_page_alloc_debugfs);
1708 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
1710 #else /* CONFIG_FAIL_PAGE_ALLOC */
1712 static inline bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
1714 return false;
1717 #endif /* CONFIG_FAIL_PAGE_ALLOC */
1720 * Return true if free pages are above 'mark'. This takes into account the order
1721 * of the allocation.
1723 static bool __zone_watermark_ok(struct zone *z, unsigned int order,
1724 unsigned long mark, int classzone_idx, int alloc_flags,
1725 long free_pages)
1727 /* free_pages my go negative - that's OK */
1728 long min = mark;
1729 long lowmem_reserve = z->lowmem_reserve[classzone_idx];
1730 int o;
1731 long free_cma = 0;
1733 free_pages -= (1 << order) - 1;
1734 if (alloc_flags & ALLOC_HIGH)
1735 min -= min / 2;
1736 if (alloc_flags & ALLOC_HARDER)
1737 min -= min / 4;
1738 #ifdef CONFIG_CMA
1739 /* If allocation can't use CMA areas don't use free CMA pages */
1740 if (!(alloc_flags & ALLOC_CMA))
1741 free_cma = zone_page_state(z, NR_FREE_CMA_PAGES);
1742 #endif
1744 if (free_pages - free_cma <= min + lowmem_reserve)
1745 return false;
1746 for (o = 0; o < order; o++) {
1747 /* At the next order, this order's pages become unavailable */
1748 free_pages -= z->free_area[o].nr_free << o;
1750 /* Require fewer higher order pages to be free */
1751 min >>= 1;
1753 if (free_pages <= min)
1754 return false;
1756 return true;
1759 bool zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
1760 int classzone_idx, int alloc_flags)
1762 return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
1763 zone_page_state(z, NR_FREE_PAGES));
1766 bool zone_watermark_ok_safe(struct zone *z, unsigned int order,
1767 unsigned long mark, int classzone_idx, int alloc_flags)
1769 long free_pages = zone_page_state(z, NR_FREE_PAGES);
1771 if (z->percpu_drift_mark && free_pages < z->percpu_drift_mark)
1772 free_pages = zone_page_state_snapshot(z, NR_FREE_PAGES);
1774 return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
1775 free_pages);
1778 #ifdef CONFIG_NUMA
1780 * zlc_setup - Setup for "zonelist cache". Uses cached zone data to
1781 * skip over zones that are not allowed by the cpuset, or that have
1782 * been recently (in last second) found to be nearly full. See further
1783 * comments in mmzone.h. Reduces cache footprint of zonelist scans
1784 * that have to skip over a lot of full or unallowed zones.
1786 * If the zonelist cache is present in the passed zonelist, then
1787 * returns a pointer to the allowed node mask (either the current
1788 * tasks mems_allowed, or node_states[N_MEMORY].)
1790 * If the zonelist cache is not available for this zonelist, does
1791 * nothing and returns NULL.
1793 * If the fullzones BITMAP in the zonelist cache is stale (more than
1794 * a second since last zap'd) then we zap it out (clear its bits.)
1796 * We hold off even calling zlc_setup, until after we've checked the
1797 * first zone in the zonelist, on the theory that most allocations will
1798 * be satisfied from that first zone, so best to examine that zone as
1799 * quickly as we can.
1801 static nodemask_t *zlc_setup(struct zonelist *zonelist, int alloc_flags)
1803 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1804 nodemask_t *allowednodes; /* zonelist_cache approximation */
1806 zlc = zonelist->zlcache_ptr;
1807 if (!zlc)
1808 return NULL;
1810 if (time_after(jiffies, zlc->last_full_zap + HZ)) {
1811 bitmap_zero(zlc->fullzones, MAX_ZONES_PER_ZONELIST);
1812 zlc->last_full_zap = jiffies;
1815 allowednodes = !in_interrupt() && (alloc_flags & ALLOC_CPUSET) ?
1816 &cpuset_current_mems_allowed :
1817 &node_states[N_MEMORY];
1818 return allowednodes;
1822 * Given 'z' scanning a zonelist, run a couple of quick checks to see
1823 * if it is worth looking at further for free memory:
1824 * 1) Check that the zone isn't thought to be full (doesn't have its
1825 * bit set in the zonelist_cache fullzones BITMAP).
1826 * 2) Check that the zones node (obtained from the zonelist_cache
1827 * z_to_n[] mapping) is allowed in the passed in allowednodes mask.
1828 * Return true (non-zero) if zone is worth looking at further, or
1829 * else return false (zero) if it is not.
1831 * This check -ignores- the distinction between various watermarks,
1832 * such as GFP_HIGH, GFP_ATOMIC, PF_MEMALLOC, ... If a zone is
1833 * found to be full for any variation of these watermarks, it will
1834 * be considered full for up to one second by all requests, unless
1835 * we are so low on memory on all allowed nodes that we are forced
1836 * into the second scan of the zonelist.
1838 * In the second scan we ignore this zonelist cache and exactly
1839 * apply the watermarks to all zones, even it is slower to do so.
1840 * We are low on memory in the second scan, and should leave no stone
1841 * unturned looking for a free page.
1843 static int zlc_zone_worth_trying(struct zonelist *zonelist, struct zoneref *z,
1844 nodemask_t *allowednodes)
1846 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1847 int i; /* index of *z in zonelist zones */
1848 int n; /* node that zone *z is on */
1850 zlc = zonelist->zlcache_ptr;
1851 if (!zlc)
1852 return 1;
1854 i = z - zonelist->_zonerefs;
1855 n = zlc->z_to_n[i];
1857 /* This zone is worth trying if it is allowed but not full */
1858 return node_isset(n, *allowednodes) && !test_bit(i, zlc->fullzones);
1862 * Given 'z' scanning a zonelist, set the corresponding bit in
1863 * zlc->fullzones, so that subsequent attempts to allocate a page
1864 * from that zone don't waste time re-examining it.
1866 static void zlc_mark_zone_full(struct zonelist *zonelist, struct zoneref *z)
1868 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1869 int i; /* index of *z in zonelist zones */
1871 zlc = zonelist->zlcache_ptr;
1872 if (!zlc)
1873 return;
1875 i = z - zonelist->_zonerefs;
1877 set_bit(i, zlc->fullzones);
1881 * clear all zones full, called after direct reclaim makes progress so that
1882 * a zone that was recently full is not skipped over for up to a second
1884 static void zlc_clear_zones_full(struct zonelist *zonelist)
1886 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1888 zlc = zonelist->zlcache_ptr;
1889 if (!zlc)
1890 return;
1892 bitmap_zero(zlc->fullzones, MAX_ZONES_PER_ZONELIST);
1895 static bool zone_local(struct zone *local_zone, struct zone *zone)
1897 return local_zone->node == zone->node;
1900 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
1902 return node_distance(zone_to_nid(local_zone), zone_to_nid(zone)) <=
1903 RECLAIM_DISTANCE;
1906 #else /* CONFIG_NUMA */
1908 static nodemask_t *zlc_setup(struct zonelist *zonelist, int alloc_flags)
1910 return NULL;
1913 static int zlc_zone_worth_trying(struct zonelist *zonelist, struct zoneref *z,
1914 nodemask_t *allowednodes)
1916 return 1;
1919 static void zlc_mark_zone_full(struct zonelist *zonelist, struct zoneref *z)
1923 static void zlc_clear_zones_full(struct zonelist *zonelist)
1927 static bool zone_local(struct zone *local_zone, struct zone *zone)
1929 return true;
1932 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
1934 return true;
1937 #endif /* CONFIG_NUMA */
1940 * get_page_from_freelist goes through the zonelist trying to allocate
1941 * a page.
1943 static struct page *
1944 get_page_from_freelist(gfp_t gfp_mask, nodemask_t *nodemask, unsigned int order,
1945 struct zonelist *zonelist, int high_zoneidx, int alloc_flags,
1946 struct zone *preferred_zone, int classzone_idx, int migratetype)
1948 struct zoneref *z;
1949 struct page *page = NULL;
1950 struct zone *zone;
1951 nodemask_t *allowednodes = NULL;/* zonelist_cache approximation */
1952 int zlc_active = 0; /* set if using zonelist_cache */
1953 int did_zlc_setup = 0; /* just call zlc_setup() one time */
1954 bool consider_zone_dirty = (alloc_flags & ALLOC_WMARK_LOW) &&
1955 (gfp_mask & __GFP_WRITE);
1957 zonelist_scan:
1959 * Scan zonelist, looking for a zone with enough free.
1960 * See also __cpuset_node_allowed_softwall() comment in kernel/cpuset.c.
1962 for_each_zone_zonelist_nodemask(zone, z, zonelist,
1963 high_zoneidx, nodemask) {
1964 unsigned long mark;
1966 if (IS_ENABLED(CONFIG_NUMA) && zlc_active &&
1967 !zlc_zone_worth_trying(zonelist, z, allowednodes))
1968 continue;
1969 if (cpusets_enabled() &&
1970 (alloc_flags & ALLOC_CPUSET) &&
1971 !cpuset_zone_allowed_softwall(zone, gfp_mask))
1972 continue;
1974 * Distribute pages in proportion to the individual
1975 * zone size to ensure fair page aging. The zone a
1976 * page was allocated in should have no effect on the
1977 * time the page has in memory before being reclaimed.
1979 if (alloc_flags & ALLOC_FAIR) {
1980 if (!zone_local(preferred_zone, zone))
1981 continue;
1982 if (atomic_long_read(&zone->vm_stat[NR_ALLOC_BATCH]) <= 0)
1983 continue;
1986 * When allocating a page cache page for writing, we
1987 * want to get it from a zone that is within its dirty
1988 * limit, such that no single zone holds more than its
1989 * proportional share of globally allowed dirty pages.
1990 * The dirty limits take into account the zone's
1991 * lowmem reserves and high watermark so that kswapd
1992 * should be able to balance it without having to
1993 * write pages from its LRU list.
1995 * This may look like it could increase pressure on
1996 * lower zones by failing allocations in higher zones
1997 * before they are full. But the pages that do spill
1998 * over are limited as the lower zones are protected
1999 * by this very same mechanism. It should not become
2000 * a practical burden to them.
2002 * XXX: For now, allow allocations to potentially
2003 * exceed the per-zone dirty limit in the slowpath
2004 * (ALLOC_WMARK_LOW unset) before going into reclaim,
2005 * which is important when on a NUMA setup the allowed
2006 * zones are together not big enough to reach the
2007 * global limit. The proper fix for these situations
2008 * will require awareness of zones in the
2009 * dirty-throttling and the flusher threads.
2011 if (consider_zone_dirty && !zone_dirty_ok(zone))
2012 continue;
2014 mark = zone->watermark[alloc_flags & ALLOC_WMARK_MASK];
2015 if (!zone_watermark_ok(zone, order, mark,
2016 classzone_idx, alloc_flags)) {
2017 int ret;
2019 /* Checked here to keep the fast path fast */
2020 BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK);
2021 if (alloc_flags & ALLOC_NO_WATERMARKS)
2022 goto try_this_zone;
2024 if (IS_ENABLED(CONFIG_NUMA) &&
2025 !did_zlc_setup && nr_online_nodes > 1) {
2027 * we do zlc_setup if there are multiple nodes
2028 * and before considering the first zone allowed
2029 * by the cpuset.
2031 allowednodes = zlc_setup(zonelist, alloc_flags);
2032 zlc_active = 1;
2033 did_zlc_setup = 1;
2036 if (zone_reclaim_mode == 0 ||
2037 !zone_allows_reclaim(preferred_zone, zone))
2038 goto this_zone_full;
2041 * As we may have just activated ZLC, check if the first
2042 * eligible zone has failed zone_reclaim recently.
2044 if (IS_ENABLED(CONFIG_NUMA) && zlc_active &&
2045 !zlc_zone_worth_trying(zonelist, z, allowednodes))
2046 continue;
2048 ret = zone_reclaim(zone, gfp_mask, order);
2049 switch (ret) {
2050 case ZONE_RECLAIM_NOSCAN:
2051 /* did not scan */
2052 continue;
2053 case ZONE_RECLAIM_FULL:
2054 /* scanned but unreclaimable */
2055 continue;
2056 default:
2057 /* did we reclaim enough */
2058 if (zone_watermark_ok(zone, order, mark,
2059 classzone_idx, alloc_flags))
2060 goto try_this_zone;
2063 * Failed to reclaim enough to meet watermark.
2064 * Only mark the zone full if checking the min
2065 * watermark or if we failed to reclaim just
2066 * 1<<order pages or else the page allocator
2067 * fastpath will prematurely mark zones full
2068 * when the watermark is between the low and
2069 * min watermarks.
2071 if (((alloc_flags & ALLOC_WMARK_MASK) == ALLOC_WMARK_MIN) ||
2072 ret == ZONE_RECLAIM_SOME)
2073 goto this_zone_full;
2075 continue;
2079 try_this_zone:
2080 page = buffered_rmqueue(preferred_zone, zone, order,
2081 gfp_mask, migratetype);
2082 if (page)
2083 break;
2084 this_zone_full:
2085 if (IS_ENABLED(CONFIG_NUMA) && zlc_active)
2086 zlc_mark_zone_full(zonelist, z);
2089 if (unlikely(IS_ENABLED(CONFIG_NUMA) && page == NULL && zlc_active)) {
2090 /* Disable zlc cache for second zonelist scan */
2091 zlc_active = 0;
2092 goto zonelist_scan;
2095 if (page)
2097 * page->pfmemalloc is set when ALLOC_NO_WATERMARKS was
2098 * necessary to allocate the page. The expectation is
2099 * that the caller is taking steps that will free more
2100 * memory. The caller should avoid the page being used
2101 * for !PFMEMALLOC purposes.
2103 page->pfmemalloc = !!(alloc_flags & ALLOC_NO_WATERMARKS);
2105 return page;
2109 * Large machines with many possible nodes should not always dump per-node
2110 * meminfo in irq context.
2112 static inline bool should_suppress_show_mem(void)
2114 bool ret = false;
2116 #if NODES_SHIFT > 8
2117 ret = in_interrupt();
2118 #endif
2119 return ret;
2122 static DEFINE_RATELIMIT_STATE(nopage_rs,
2123 DEFAULT_RATELIMIT_INTERVAL,
2124 DEFAULT_RATELIMIT_BURST);
2126 void warn_alloc_failed(gfp_t gfp_mask, int order, const char *fmt, ...)
2128 unsigned int filter = SHOW_MEM_FILTER_NODES;
2130 if ((gfp_mask & __GFP_NOWARN) || !__ratelimit(&nopage_rs) ||
2131 debug_guardpage_minorder() > 0)
2132 return;
2135 * This documents exceptions given to allocations in certain
2136 * contexts that are allowed to allocate outside current's set
2137 * of allowed nodes.
2139 if (!(gfp_mask & __GFP_NOMEMALLOC))
2140 if (test_thread_flag(TIF_MEMDIE) ||
2141 (current->flags & (PF_MEMALLOC | PF_EXITING)))
2142 filter &= ~SHOW_MEM_FILTER_NODES;
2143 if (in_interrupt() || !(gfp_mask & __GFP_WAIT))
2144 filter &= ~SHOW_MEM_FILTER_NODES;
2146 if (fmt) {
2147 struct va_format vaf;
2148 va_list args;
2150 va_start(args, fmt);
2152 vaf.fmt = fmt;
2153 vaf.va = &args;
2155 pr_warn("%pV", &vaf);
2157 va_end(args);
2160 pr_warn("%s: page allocation failure: order:%d, mode:0x%x\n",
2161 current->comm, order, gfp_mask);
2163 dump_stack();
2164 if (!should_suppress_show_mem())
2165 show_mem(filter);
2168 static inline int
2169 should_alloc_retry(gfp_t gfp_mask, unsigned int order,
2170 unsigned long did_some_progress,
2171 unsigned long pages_reclaimed)
2173 /* Do not loop if specifically requested */
2174 if (gfp_mask & __GFP_NORETRY)
2175 return 0;
2177 /* Always retry if specifically requested */
2178 if (gfp_mask & __GFP_NOFAIL)
2179 return 1;
2182 * Suspend converts GFP_KERNEL to __GFP_WAIT which can prevent reclaim
2183 * making forward progress without invoking OOM. Suspend also disables
2184 * storage devices so kswapd will not help. Bail if we are suspending.
2186 if (!did_some_progress && pm_suspended_storage())
2187 return 0;
2190 * In this implementation, order <= PAGE_ALLOC_COSTLY_ORDER
2191 * means __GFP_NOFAIL, but that may not be true in other
2192 * implementations.
2194 if (order <= PAGE_ALLOC_COSTLY_ORDER)
2195 return 1;
2198 * For order > PAGE_ALLOC_COSTLY_ORDER, if __GFP_REPEAT is
2199 * specified, then we retry until we no longer reclaim any pages
2200 * (above), or we've reclaimed an order of pages at least as
2201 * large as the allocation's order. In both cases, if the
2202 * allocation still fails, we stop retrying.
2204 if (gfp_mask & __GFP_REPEAT && pages_reclaimed < (1 << order))
2205 return 1;
2207 return 0;
2210 static inline struct page *
2211 __alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order,
2212 struct zonelist *zonelist, enum zone_type high_zoneidx,
2213 nodemask_t *nodemask, struct zone *preferred_zone,
2214 int classzone_idx, int migratetype)
2216 struct page *page;
2218 /* Acquire the OOM killer lock for the zones in zonelist */
2219 if (!try_set_zonelist_oom(zonelist, gfp_mask)) {
2220 schedule_timeout_uninterruptible(1);
2221 return NULL;
2225 * PM-freezer should be notified that there might be an OOM killer on
2226 * its way to kill and wake somebody up. This is too early and we might
2227 * end up not killing anything but false positives are acceptable.
2228 * See freeze_processes.
2230 note_oom_kill();
2233 * Go through the zonelist yet one more time, keep very high watermark
2234 * here, this is only to catch a parallel oom killing, we must fail if
2235 * we're still under heavy pressure.
2237 page = get_page_from_freelist(gfp_mask|__GFP_HARDWALL, nodemask,
2238 order, zonelist, high_zoneidx,
2239 ALLOC_WMARK_HIGH|ALLOC_CPUSET,
2240 preferred_zone, classzone_idx, migratetype);
2241 if (page)
2242 goto out;
2244 if (!(gfp_mask & __GFP_NOFAIL)) {
2245 /* The OOM killer will not help higher order allocs */
2246 if (order > PAGE_ALLOC_COSTLY_ORDER)
2247 goto out;
2248 /* The OOM killer does not needlessly kill tasks for lowmem */
2249 if (high_zoneidx < ZONE_NORMAL)
2250 goto out;
2252 * GFP_THISNODE contains __GFP_NORETRY and we never hit this.
2253 * Sanity check for bare calls of __GFP_THISNODE, not real OOM.
2254 * The caller should handle page allocation failure by itself if
2255 * it specifies __GFP_THISNODE.
2256 * Note: Hugepage uses it but will hit PAGE_ALLOC_COSTLY_ORDER.
2258 if (gfp_mask & __GFP_THISNODE)
2259 goto out;
2261 /* Exhausted what can be done so it's blamo time */
2262 out_of_memory(zonelist, gfp_mask, order, nodemask, false);
2264 out:
2265 clear_zonelist_oom(zonelist, gfp_mask);
2266 return page;
2269 #ifdef CONFIG_COMPACTION
2270 /* Try memory compaction for high-order allocations before reclaim */
2271 static struct page *
2272 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
2273 struct zonelist *zonelist, enum zone_type high_zoneidx,
2274 nodemask_t *nodemask, int alloc_flags, struct zone *preferred_zone,
2275 int classzone_idx, int migratetype, enum migrate_mode mode,
2276 bool *contended_compaction, bool *deferred_compaction,
2277 unsigned long *did_some_progress)
2279 if (!order)
2280 return NULL;
2282 if (compaction_deferred(preferred_zone, order)) {
2283 *deferred_compaction = true;
2284 return NULL;
2287 current->flags |= PF_MEMALLOC;
2288 *did_some_progress = try_to_compact_pages(zonelist, order, gfp_mask,
2289 nodemask, mode,
2290 contended_compaction);
2291 current->flags &= ~PF_MEMALLOC;
2293 if (*did_some_progress != COMPACT_SKIPPED) {
2294 struct page *page;
2296 /* Page migration frees to the PCP lists but we want merging */
2297 drain_pages(get_cpu());
2298 put_cpu();
2300 page = get_page_from_freelist(gfp_mask, nodemask,
2301 order, zonelist, high_zoneidx,
2302 alloc_flags & ~ALLOC_NO_WATERMARKS,
2303 preferred_zone, classzone_idx, migratetype);
2304 if (page) {
2305 preferred_zone->compact_blockskip_flush = false;
2306 compaction_defer_reset(preferred_zone, order, true);
2307 count_vm_event(COMPACTSUCCESS);
2308 return page;
2312 * It's bad if compaction run occurs and fails.
2313 * The most likely reason is that pages exist,
2314 * but not enough to satisfy watermarks.
2316 count_vm_event(COMPACTFAIL);
2319 * As async compaction considers a subset of pageblocks, only
2320 * defer if the failure was a sync compaction failure.
2322 if (mode != MIGRATE_ASYNC)
2323 defer_compaction(preferred_zone, order);
2325 cond_resched();
2328 return NULL;
2330 #else
2331 static inline struct page *
2332 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
2333 struct zonelist *zonelist, enum zone_type high_zoneidx,
2334 nodemask_t *nodemask, int alloc_flags, struct zone *preferred_zone,
2335 int classzone_idx, int migratetype,
2336 enum migrate_mode mode, bool *contended_compaction,
2337 bool *deferred_compaction, unsigned long *did_some_progress)
2339 return NULL;
2341 #endif /* CONFIG_COMPACTION */
2343 /* Perform direct synchronous page reclaim */
2344 static int
2345 __perform_reclaim(gfp_t gfp_mask, unsigned int order, struct zonelist *zonelist,
2346 nodemask_t *nodemask)
2348 struct reclaim_state reclaim_state;
2349 int progress;
2351 cond_resched();
2353 /* We now go into synchronous reclaim */
2354 cpuset_memory_pressure_bump();
2355 current->flags |= PF_MEMALLOC;
2356 lockdep_set_current_reclaim_state(gfp_mask);
2357 reclaim_state.reclaimed_slab = 0;
2358 current->reclaim_state = &reclaim_state;
2360 progress = try_to_free_pages(zonelist, order, gfp_mask, nodemask);
2362 current->reclaim_state = NULL;
2363 lockdep_clear_current_reclaim_state();
2364 current->flags &= ~PF_MEMALLOC;
2366 cond_resched();
2368 return progress;
2371 /* The really slow allocator path where we enter direct reclaim */
2372 static inline struct page *
2373 __alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order,
2374 struct zonelist *zonelist, enum zone_type high_zoneidx,
2375 nodemask_t *nodemask, int alloc_flags, struct zone *preferred_zone,
2376 int classzone_idx, int migratetype, unsigned long *did_some_progress)
2378 struct page *page = NULL;
2379 bool drained = false;
2381 *did_some_progress = __perform_reclaim(gfp_mask, order, zonelist,
2382 nodemask);
2383 if (unlikely(!(*did_some_progress)))
2384 return NULL;
2386 /* After successful reclaim, reconsider all zones for allocation */
2387 if (IS_ENABLED(CONFIG_NUMA))
2388 zlc_clear_zones_full(zonelist);
2390 retry:
2391 page = get_page_from_freelist(gfp_mask, nodemask, order,
2392 zonelist, high_zoneidx,
2393 alloc_flags & ~ALLOC_NO_WATERMARKS,
2394 preferred_zone, classzone_idx,
2395 migratetype);
2398 * If an allocation failed after direct reclaim, it could be because
2399 * pages are pinned on the per-cpu lists. Drain them and try again
2401 if (!page && !drained) {
2402 drain_all_pages();
2403 drained = true;
2404 goto retry;
2407 return page;
2411 * This is called in the allocator slow-path if the allocation request is of
2412 * sufficient urgency to ignore watermarks and take other desperate measures
2414 static inline struct page *
2415 __alloc_pages_high_priority(gfp_t gfp_mask, unsigned int order,
2416 struct zonelist *zonelist, enum zone_type high_zoneidx,
2417 nodemask_t *nodemask, struct zone *preferred_zone,
2418 int classzone_idx, int migratetype)
2420 struct page *page;
2422 do {
2423 page = get_page_from_freelist(gfp_mask, nodemask, order,
2424 zonelist, high_zoneidx, ALLOC_NO_WATERMARKS,
2425 preferred_zone, classzone_idx, migratetype);
2427 if (!page && gfp_mask & __GFP_NOFAIL)
2428 wait_iff_congested(preferred_zone, BLK_RW_ASYNC, HZ/50);
2429 } while (!page && (gfp_mask & __GFP_NOFAIL));
2431 return page;
2434 static void reset_alloc_batches(struct zonelist *zonelist,
2435 enum zone_type high_zoneidx,
2436 struct zone *preferred_zone)
2438 struct zoneref *z;
2439 struct zone *zone;
2441 for_each_zone_zonelist(zone, z, zonelist, high_zoneidx) {
2443 * Only reset the batches of zones that were actually
2444 * considered in the fairness pass, we don't want to
2445 * trash fairness information for zones that are not
2446 * actually part of this zonelist's round-robin cycle.
2448 if (!zone_local(preferred_zone, zone))
2449 continue;
2450 mod_zone_page_state(zone, NR_ALLOC_BATCH,
2451 high_wmark_pages(zone) - low_wmark_pages(zone) -
2452 atomic_long_read(&zone->vm_stat[NR_ALLOC_BATCH]));
2456 static void wake_all_kswapds(unsigned int order,
2457 struct zonelist *zonelist,
2458 enum zone_type high_zoneidx,
2459 struct zone *preferred_zone)
2461 struct zoneref *z;
2462 struct zone *zone;
2464 for_each_zone_zonelist(zone, z, zonelist, high_zoneidx)
2465 wakeup_kswapd(zone, order, zone_idx(preferred_zone));
2468 static inline int
2469 gfp_to_alloc_flags(gfp_t gfp_mask)
2471 int alloc_flags = ALLOC_WMARK_MIN | ALLOC_CPUSET;
2472 const bool atomic = !(gfp_mask & (__GFP_WAIT | __GFP_NO_KSWAPD));
2474 /* __GFP_HIGH is assumed to be the same as ALLOC_HIGH to save a branch. */
2475 BUILD_BUG_ON(__GFP_HIGH != (__force gfp_t) ALLOC_HIGH);
2478 * The caller may dip into page reserves a bit more if the caller
2479 * cannot run direct reclaim, or if the caller has realtime scheduling
2480 * policy or is asking for __GFP_HIGH memory. GFP_ATOMIC requests will
2481 * set both ALLOC_HARDER (atomic == true) and ALLOC_HIGH (__GFP_HIGH).
2483 alloc_flags |= (__force int) (gfp_mask & __GFP_HIGH);
2485 if (atomic) {
2487 * Not worth trying to allocate harder for __GFP_NOMEMALLOC even
2488 * if it can't schedule.
2490 if (!(gfp_mask & __GFP_NOMEMALLOC))
2491 alloc_flags |= ALLOC_HARDER;
2493 * Ignore cpuset mems for GFP_ATOMIC rather than fail, see the
2494 * comment for __cpuset_node_allowed_softwall().
2496 alloc_flags &= ~ALLOC_CPUSET;
2497 } else if (unlikely(rt_task(current)) && !in_interrupt())
2498 alloc_flags |= ALLOC_HARDER;
2500 if (likely(!(gfp_mask & __GFP_NOMEMALLOC))) {
2501 if (gfp_mask & __GFP_MEMALLOC)
2502 alloc_flags |= ALLOC_NO_WATERMARKS;
2503 else if (in_serving_softirq() && (current->flags & PF_MEMALLOC))
2504 alloc_flags |= ALLOC_NO_WATERMARKS;
2505 else if (!in_interrupt() &&
2506 ((current->flags & PF_MEMALLOC) ||
2507 unlikely(test_thread_flag(TIF_MEMDIE))))
2508 alloc_flags |= ALLOC_NO_WATERMARKS;
2510 #ifdef CONFIG_CMA
2511 if (allocflags_to_migratetype(gfp_mask) == MIGRATE_MOVABLE)
2512 alloc_flags |= ALLOC_CMA;
2513 #endif
2514 return alloc_flags;
2517 bool gfp_pfmemalloc_allowed(gfp_t gfp_mask)
2519 return !!(gfp_to_alloc_flags(gfp_mask) & ALLOC_NO_WATERMARKS);
2522 static inline struct page *
2523 __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order,
2524 struct zonelist *zonelist, enum zone_type high_zoneidx,
2525 nodemask_t *nodemask, struct zone *preferred_zone,
2526 int classzone_idx, int migratetype)
2528 const gfp_t wait = gfp_mask & __GFP_WAIT;
2529 struct page *page = NULL;
2530 int alloc_flags;
2531 unsigned long pages_reclaimed = 0;
2532 unsigned long did_some_progress;
2533 enum migrate_mode migration_mode = MIGRATE_ASYNC;
2534 bool deferred_compaction = false;
2535 bool contended_compaction = false;
2538 * In the slowpath, we sanity check order to avoid ever trying to
2539 * reclaim >= MAX_ORDER areas which will never succeed. Callers may
2540 * be using allocators in order of preference for an area that is
2541 * too large.
2543 if (order >= MAX_ORDER) {
2544 WARN_ON_ONCE(!(gfp_mask & __GFP_NOWARN));
2545 return NULL;
2549 * GFP_THISNODE (meaning __GFP_THISNODE, __GFP_NORETRY and
2550 * __GFP_NOWARN set) should not cause reclaim since the subsystem
2551 * (f.e. slab) using GFP_THISNODE may choose to trigger reclaim
2552 * using a larger set of nodes after it has established that the
2553 * allowed per node queues are empty and that nodes are
2554 * over allocated.
2556 if (IS_ENABLED(CONFIG_NUMA) &&
2557 (gfp_mask & GFP_THISNODE) == GFP_THISNODE)
2558 goto nopage;
2560 restart:
2561 if (!(gfp_mask & __GFP_NO_KSWAPD))
2562 wake_all_kswapds(order, zonelist, high_zoneidx, preferred_zone);
2565 * OK, we're below the kswapd watermark and have kicked background
2566 * reclaim. Now things get more complex, so set up alloc_flags according
2567 * to how we want to proceed.
2569 alloc_flags = gfp_to_alloc_flags(gfp_mask);
2572 * Find the true preferred zone if the allocation is unconstrained by
2573 * cpusets.
2575 if (!(alloc_flags & ALLOC_CPUSET) && !nodemask) {
2576 struct zoneref *preferred_zoneref;
2577 preferred_zoneref = first_zones_zonelist(zonelist, high_zoneidx,
2578 NULL, &preferred_zone);
2579 classzone_idx = zonelist_zone_idx(preferred_zoneref);
2582 rebalance:
2583 /* This is the last chance, in general, before the goto nopage. */
2584 page = get_page_from_freelist(gfp_mask, nodemask, order, zonelist,
2585 high_zoneidx, alloc_flags & ~ALLOC_NO_WATERMARKS,
2586 preferred_zone, classzone_idx, migratetype);
2587 if (page)
2588 goto got_pg;
2590 /* Allocate without watermarks if the context allows */
2591 if (alloc_flags & ALLOC_NO_WATERMARKS) {
2593 * Ignore mempolicies if ALLOC_NO_WATERMARKS on the grounds
2594 * the allocation is high priority and these type of
2595 * allocations are system rather than user orientated
2597 if (!(gfp_mask & __GFP_THISNODE))
2598 zonelist = node_zonelist(numa_node_id(), gfp_mask);
2600 page = __alloc_pages_high_priority(gfp_mask, order,
2601 zonelist, high_zoneidx, nodemask,
2602 preferred_zone, classzone_idx, migratetype);
2603 if (page) {
2604 goto got_pg;
2608 /* Atomic allocations - we can't balance anything */
2609 if (!wait) {
2611 * All existing users of the deprecated __GFP_NOFAIL are
2612 * blockable, so warn of any new users that actually allow this
2613 * type of allocation to fail.
2615 WARN_ON_ONCE(gfp_mask & __GFP_NOFAIL);
2616 goto nopage;
2619 /* Avoid recursion of direct reclaim */
2620 if (current->flags & PF_MEMALLOC)
2621 goto nopage;
2623 /* Avoid allocations with no watermarks from looping endlessly */
2624 if (test_thread_flag(TIF_MEMDIE) && !(gfp_mask & __GFP_NOFAIL))
2625 goto nopage;
2628 * Try direct compaction. The first pass is asynchronous. Subsequent
2629 * attempts after direct reclaim are synchronous
2631 page = __alloc_pages_direct_compact(gfp_mask, order, zonelist,
2632 high_zoneidx, nodemask, alloc_flags,
2633 preferred_zone,
2634 classzone_idx, migratetype,
2635 migration_mode, &contended_compaction,
2636 &deferred_compaction,
2637 &did_some_progress);
2638 if (page)
2639 goto got_pg;
2642 * It can become very expensive to allocate transparent hugepages at
2643 * fault, so use asynchronous memory compaction for THP unless it is
2644 * khugepaged trying to collapse.
2646 if (!(gfp_mask & __GFP_NO_KSWAPD) || (current->flags & PF_KTHREAD))
2647 migration_mode = MIGRATE_SYNC_LIGHT;
2650 * If compaction is deferred for high-order allocations, it is because
2651 * sync compaction recently failed. In this is the case and the caller
2652 * requested a movable allocation that does not heavily disrupt the
2653 * system then fail the allocation instead of entering direct reclaim.
2655 if ((deferred_compaction || contended_compaction) &&
2656 (gfp_mask & __GFP_NO_KSWAPD))
2657 goto nopage;
2659 /* Try direct reclaim and then allocating */
2660 page = __alloc_pages_direct_reclaim(gfp_mask, order,
2661 zonelist, high_zoneidx,
2662 nodemask,
2663 alloc_flags, preferred_zone,
2664 classzone_idx, migratetype,
2665 &did_some_progress);
2666 if (page)
2667 goto got_pg;
2670 * If we failed to make any progress reclaiming, then we are
2671 * running out of options and have to consider going OOM
2673 if (!did_some_progress) {
2674 if (oom_gfp_allowed(gfp_mask)) {
2675 if (oom_killer_disabled)
2676 goto nopage;
2677 /* Coredumps can quickly deplete all memory reserves */
2678 if ((current->flags & PF_DUMPCORE) &&
2679 !(gfp_mask & __GFP_NOFAIL))
2680 goto nopage;
2681 page = __alloc_pages_may_oom(gfp_mask, order,
2682 zonelist, high_zoneidx,
2683 nodemask, preferred_zone,
2684 classzone_idx, migratetype);
2685 if (page)
2686 goto got_pg;
2688 if (!(gfp_mask & __GFP_NOFAIL)) {
2690 * The oom killer is not called for high-order
2691 * allocations that may fail, so if no progress
2692 * is being made, there are no other options and
2693 * retrying is unlikely to help.
2695 if (order > PAGE_ALLOC_COSTLY_ORDER)
2696 goto nopage;
2698 * The oom killer is not called for lowmem
2699 * allocations to prevent needlessly killing
2700 * innocent tasks.
2702 if (high_zoneidx < ZONE_NORMAL)
2703 goto nopage;
2706 goto restart;
2710 /* Check if we should retry the allocation */
2711 pages_reclaimed += did_some_progress;
2712 if (should_alloc_retry(gfp_mask, order, did_some_progress,
2713 pages_reclaimed)) {
2714 /* Wait for some write requests to complete then retry */
2715 wait_iff_congested(preferred_zone, BLK_RW_ASYNC, HZ/50);
2716 goto rebalance;
2717 } else {
2719 * High-order allocations do not necessarily loop after
2720 * direct reclaim and reclaim/compaction depends on compaction
2721 * being called after reclaim so call directly if necessary
2723 page = __alloc_pages_direct_compact(gfp_mask, order, zonelist,
2724 high_zoneidx, nodemask, alloc_flags,
2725 preferred_zone,
2726 classzone_idx, migratetype,
2727 migration_mode, &contended_compaction,
2728 &deferred_compaction,
2729 &did_some_progress);
2730 if (page)
2731 goto got_pg;
2734 nopage:
2735 warn_alloc_failed(gfp_mask, order, NULL);
2736 return page;
2737 got_pg:
2738 if (kmemcheck_enabled)
2739 kmemcheck_pagealloc_alloc(page, order, gfp_mask);
2741 return page;
2745 * This is the 'heart' of the zoned buddy allocator.
2747 struct page *
2748 __alloc_pages_nodemask(gfp_t gfp_mask, unsigned int order,
2749 struct zonelist *zonelist, nodemask_t *nodemask)
2751 enum zone_type high_zoneidx = gfp_zone(gfp_mask);
2752 struct zone *preferred_zone;
2753 struct zoneref *preferred_zoneref;
2754 struct page *page = NULL;
2755 int migratetype = allocflags_to_migratetype(gfp_mask);
2756 unsigned int cpuset_mems_cookie;
2757 int alloc_flags = ALLOC_WMARK_LOW|ALLOC_CPUSET|ALLOC_FAIR;
2758 int classzone_idx;
2760 gfp_mask &= gfp_allowed_mask;
2762 lockdep_trace_alloc(gfp_mask);
2764 might_sleep_if(gfp_mask & __GFP_WAIT);
2766 if (should_fail_alloc_page(gfp_mask, order))
2767 return NULL;
2770 * Check the zones suitable for the gfp_mask contain at least one
2771 * valid zone. It's possible to have an empty zonelist as a result
2772 * of GFP_THISNODE and a memoryless node
2774 if (unlikely(!zonelist->_zonerefs->zone))
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 retry:
2793 /* First allocation attempt */
2794 page = get_page_from_freelist(gfp_mask|__GFP_HARDWALL, nodemask, order,
2795 zonelist, high_zoneidx, alloc_flags,
2796 preferred_zone, classzone_idx, migratetype);
2797 if (unlikely(!page)) {
2799 * The first pass makes sure allocations are spread
2800 * fairly within the local node. However, the local
2801 * node might have free pages left after the fairness
2802 * batches are exhausted, and remote zones haven't
2803 * even been considered yet. Try once more without
2804 * fairness, and include remote zones now, before
2805 * entering the slowpath and waking kswapd: prefer
2806 * spilling to a remote zone over swapping locally.
2808 if (alloc_flags & ALLOC_FAIR) {
2809 reset_alloc_batches(zonelist, high_zoneidx,
2810 preferred_zone);
2811 alloc_flags &= ~ALLOC_FAIR;
2812 goto retry;
2815 * Runtime PM, block IO and its error handling path
2816 * can deadlock because I/O on the device might not
2817 * complete.
2819 gfp_mask = memalloc_noio_flags(gfp_mask);
2820 page = __alloc_pages_slowpath(gfp_mask, order,
2821 zonelist, high_zoneidx, nodemask,
2822 preferred_zone, classzone_idx, migratetype);
2825 trace_mm_page_alloc(page, order, gfp_mask, migratetype);
2827 out:
2829 * When updating a task's mems_allowed, it is possible to race with
2830 * parallel threads in such a way that an allocation can fail while
2831 * the mask is being updated. If a page allocation is about to fail,
2832 * check if the cpuset changed during allocation and if so, retry.
2834 if (unlikely(!page && read_mems_allowed_retry(cpuset_mems_cookie)))
2835 goto retry_cpuset;
2837 return page;
2839 EXPORT_SYMBOL(__alloc_pages_nodemask);
2842 * Common helper functions.
2844 unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order)
2846 struct page *page;
2849 * __get_free_pages() returns a 32-bit address, which cannot represent
2850 * a highmem page
2852 VM_BUG_ON((gfp_mask & __GFP_HIGHMEM) != 0);
2854 page = alloc_pages(gfp_mask, order);
2855 if (!page)
2856 return 0;
2857 return (unsigned long) page_address(page);
2859 EXPORT_SYMBOL(__get_free_pages);
2861 unsigned long get_zeroed_page(gfp_t gfp_mask)
2863 return __get_free_pages(gfp_mask | __GFP_ZERO, 0);
2865 EXPORT_SYMBOL(get_zeroed_page);
2867 void __free_pages(struct page *page, unsigned int order)
2869 if (put_page_testzero(page)) {
2870 if (order == 0)
2871 free_hot_cold_page(page, false);
2872 else
2873 __free_pages_ok(page, order);
2877 EXPORT_SYMBOL(__free_pages);
2879 void free_pages(unsigned long addr, unsigned int order)
2881 if (addr != 0) {
2882 VM_BUG_ON(!virt_addr_valid((void *)addr));
2883 __free_pages(virt_to_page((void *)addr), order);
2887 EXPORT_SYMBOL(free_pages);
2890 * alloc_kmem_pages charges newly allocated pages to the kmem resource counter
2891 * of the current memory cgroup.
2893 * It should be used when the caller would like to use kmalloc, but since the
2894 * allocation is large, it has to fall back to the page allocator.
2896 struct page *alloc_kmem_pages(gfp_t gfp_mask, unsigned int order)
2898 struct page *page;
2899 struct mem_cgroup *memcg = NULL;
2901 if (!memcg_kmem_newpage_charge(gfp_mask, &memcg, order))
2902 return NULL;
2903 page = alloc_pages(gfp_mask, order);
2904 memcg_kmem_commit_charge(page, memcg, order);
2905 return page;
2908 struct page *alloc_kmem_pages_node(int nid, gfp_t gfp_mask, unsigned int order)
2910 struct page *page;
2911 struct mem_cgroup *memcg = NULL;
2913 if (!memcg_kmem_newpage_charge(gfp_mask, &memcg, order))
2914 return NULL;
2915 page = alloc_pages_node(nid, gfp_mask, order);
2916 memcg_kmem_commit_charge(page, memcg, order);
2917 return page;
2921 * __free_kmem_pages and free_kmem_pages will free pages allocated with
2922 * alloc_kmem_pages.
2924 void __free_kmem_pages(struct page *page, unsigned int order)
2926 memcg_kmem_uncharge_pages(page, order);
2927 __free_pages(page, order);
2930 void free_kmem_pages(unsigned long addr, unsigned int order)
2932 if (addr != 0) {
2933 VM_BUG_ON(!virt_addr_valid((void *)addr));
2934 __free_kmem_pages(virt_to_page((void *)addr), order);
2938 static void *make_alloc_exact(unsigned long addr, unsigned order, size_t size)
2940 if (addr) {
2941 unsigned long alloc_end = addr + (PAGE_SIZE << order);
2942 unsigned long used = addr + PAGE_ALIGN(size);
2944 split_page(virt_to_page((void *)addr), order);
2945 while (used < alloc_end) {
2946 free_page(used);
2947 used += PAGE_SIZE;
2950 return (void *)addr;
2954 * alloc_pages_exact - allocate an exact number physically-contiguous pages.
2955 * @size: the number of bytes to allocate
2956 * @gfp_mask: GFP flags for the allocation
2958 * This function is similar to alloc_pages(), except that it allocates the
2959 * minimum number of pages to satisfy the request. alloc_pages() can only
2960 * allocate memory in power-of-two pages.
2962 * This function is also limited by MAX_ORDER.
2964 * Memory allocated by this function must be released by free_pages_exact().
2966 void *alloc_pages_exact(size_t size, gfp_t gfp_mask)
2968 unsigned int order = get_order(size);
2969 unsigned long addr;
2971 addr = __get_free_pages(gfp_mask, order);
2972 return make_alloc_exact(addr, order, size);
2974 EXPORT_SYMBOL(alloc_pages_exact);
2977 * alloc_pages_exact_nid - allocate an exact number of physically-contiguous
2978 * pages on a node.
2979 * @nid: the preferred node ID where memory should be allocated
2980 * @size: the number of bytes to allocate
2981 * @gfp_mask: GFP flags for the allocation
2983 * Like alloc_pages_exact(), but try to allocate on node nid first before falling
2984 * back.
2985 * Note this is not alloc_pages_exact_node() which allocates on a specific node,
2986 * but is not exact.
2988 void *alloc_pages_exact_nid(int nid, size_t size, gfp_t gfp_mask)
2990 unsigned order = get_order(size);
2991 struct page *p = alloc_pages_node(nid, gfp_mask, order);
2992 if (!p)
2993 return NULL;
2994 return make_alloc_exact((unsigned long)page_address(p), order, size);
2996 EXPORT_SYMBOL(alloc_pages_exact_nid);
2999 * free_pages_exact - release memory allocated via alloc_pages_exact()
3000 * @virt: the value returned by alloc_pages_exact.
3001 * @size: size of allocation, same value as passed to alloc_pages_exact().
3003 * Release the memory allocated by a previous call to alloc_pages_exact.
3005 void free_pages_exact(void *virt, size_t size)
3007 unsigned long addr = (unsigned long)virt;
3008 unsigned long end = addr + PAGE_ALIGN(size);
3010 while (addr < end) {
3011 free_page(addr);
3012 addr += PAGE_SIZE;
3015 EXPORT_SYMBOL(free_pages_exact);
3018 * nr_free_zone_pages - count number of pages beyond high watermark
3019 * @offset: The zone index of the highest zone
3021 * nr_free_zone_pages() counts the number of counts pages which are beyond the
3022 * high watermark within all zones at or below a given zone index. For each
3023 * zone, the number of pages is calculated as:
3024 * managed_pages - high_pages
3026 static unsigned long nr_free_zone_pages(int offset)
3028 struct zoneref *z;
3029 struct zone *zone;
3031 /* Just pick one node, since fallback list is circular */
3032 unsigned long sum = 0;
3034 struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL);
3036 for_each_zone_zonelist(zone, z, zonelist, offset) {
3037 unsigned long size = zone->managed_pages;
3038 unsigned long high = high_wmark_pages(zone);
3039 if (size > high)
3040 sum += size - high;
3043 return sum;
3047 * nr_free_buffer_pages - count number of pages beyond high watermark
3049 * nr_free_buffer_pages() counts the number of pages which are beyond the high
3050 * watermark within ZONE_DMA and ZONE_NORMAL.
3052 unsigned long nr_free_buffer_pages(void)
3054 return nr_free_zone_pages(gfp_zone(GFP_USER));
3056 EXPORT_SYMBOL_GPL(nr_free_buffer_pages);
3059 * nr_free_pagecache_pages - count number of pages beyond high watermark
3061 * nr_free_pagecache_pages() counts the number of pages which are beyond the
3062 * high watermark within all zones.
3064 unsigned long nr_free_pagecache_pages(void)
3066 return nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE));
3069 static inline void show_node(struct zone *zone)
3071 if (IS_ENABLED(CONFIG_NUMA))
3072 printk("Node %d ", zone_to_nid(zone));
3075 long si_mem_available(void)
3077 long available;
3078 unsigned long pagecache;
3079 unsigned long wmark_low = 0;
3080 unsigned long pages[NR_LRU_LISTS];
3081 struct zone *zone;
3082 int lru;
3084 for (lru = LRU_BASE; lru < NR_LRU_LISTS; lru++)
3085 pages[lru] = global_page_state(NR_LRU_BASE + lru);
3087 for_each_zone(zone)
3088 wmark_low += zone->watermark[WMARK_LOW];
3091 * Estimate the amount of memory available for userspace allocations,
3092 * without causing swapping.
3094 available = global_page_state(NR_FREE_PAGES) - totalreserve_pages;
3097 * Not all the page cache can be freed, otherwise the system will
3098 * start swapping. Assume at least half of the page cache, or the
3099 * low watermark worth of cache, needs to stay.
3101 pagecache = pages[LRU_ACTIVE_FILE] + pages[LRU_INACTIVE_FILE];
3102 pagecache -= min(pagecache / 2, wmark_low);
3103 available += pagecache;
3106 * Part of the reclaimable slab consists of items that are in use,
3107 * and cannot be freed. Cap this estimate at the low watermark.
3109 available += global_page_state(NR_SLAB_RECLAIMABLE) -
3110 min(global_page_state(NR_SLAB_RECLAIMABLE) / 2, wmark_low);
3112 if (available < 0)
3113 available = 0;
3114 return available;
3116 EXPORT_SYMBOL_GPL(si_mem_available);
3118 void si_meminfo(struct sysinfo *val)
3120 val->totalram = totalram_pages;
3121 val->sharedram = 0;
3122 val->freeram = global_page_state(NR_FREE_PAGES);
3123 val->bufferram = nr_blockdev_pages();
3124 val->totalhigh = totalhigh_pages;
3125 val->freehigh = nr_free_highpages();
3126 val->mem_unit = PAGE_SIZE;
3129 EXPORT_SYMBOL(si_meminfo);
3131 #ifdef CONFIG_NUMA
3132 void si_meminfo_node(struct sysinfo *val, int nid)
3134 int zone_type; /* needs to be signed */
3135 unsigned long managed_pages = 0;
3136 pg_data_t *pgdat = NODE_DATA(nid);
3138 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++)
3139 managed_pages += pgdat->node_zones[zone_type].managed_pages;
3140 val->totalram = managed_pages;
3141 val->freeram = node_page_state(nid, NR_FREE_PAGES);
3142 #ifdef CONFIG_HIGHMEM
3143 val->totalhigh = pgdat->node_zones[ZONE_HIGHMEM].managed_pages;
3144 val->freehigh = zone_page_state(&pgdat->node_zones[ZONE_HIGHMEM],
3145 NR_FREE_PAGES);
3146 #else
3147 val->totalhigh = 0;
3148 val->freehigh = 0;
3149 #endif
3150 val->mem_unit = PAGE_SIZE;
3152 #endif
3155 * Determine whether the node should be displayed or not, depending on whether
3156 * SHOW_MEM_FILTER_NODES was passed to show_free_areas().
3158 bool skip_free_areas_node(unsigned int flags, int nid)
3160 bool ret = false;
3161 unsigned int cpuset_mems_cookie;
3163 if (!(flags & SHOW_MEM_FILTER_NODES))
3164 goto out;
3166 do {
3167 cpuset_mems_cookie = read_mems_allowed_begin();
3168 ret = !node_isset(nid, cpuset_current_mems_allowed);
3169 } while (read_mems_allowed_retry(cpuset_mems_cookie));
3170 out:
3171 return ret;
3174 #define K(x) ((x) << (PAGE_SHIFT-10))
3176 static void show_migration_types(unsigned char type)
3178 static const char types[MIGRATE_TYPES] = {
3179 [MIGRATE_UNMOVABLE] = 'U',
3180 [MIGRATE_RECLAIMABLE] = 'E',
3181 [MIGRATE_MOVABLE] = 'M',
3182 [MIGRATE_RESERVE] = 'R',
3183 #ifdef CONFIG_CMA
3184 [MIGRATE_CMA] = 'C',
3185 #endif
3186 #ifdef CONFIG_MEMORY_ISOLATION
3187 [MIGRATE_ISOLATE] = 'I',
3188 #endif
3190 char tmp[MIGRATE_TYPES + 1];
3191 char *p = tmp;
3192 int i;
3194 for (i = 0; i < MIGRATE_TYPES; i++) {
3195 if (type & (1 << i))
3196 *p++ = types[i];
3199 *p = '\0';
3200 printk("(%s) ", tmp);
3204 * Show free area list (used inside shift_scroll-lock stuff)
3205 * We also calculate the percentage fragmentation. We do this by counting the
3206 * memory on each free list with the exception of the first item on the list.
3207 * Suppresses nodes that are not allowed by current's cpuset if
3208 * SHOW_MEM_FILTER_NODES is passed.
3210 void show_free_areas(unsigned int filter)
3212 int cpu;
3213 struct zone *zone;
3215 for_each_populated_zone(zone) {
3216 if (skip_free_areas_node(filter, zone_to_nid(zone)))
3217 continue;
3218 show_node(zone);
3219 printk("%s per-cpu:\n", zone->name);
3221 for_each_online_cpu(cpu) {
3222 struct per_cpu_pageset *pageset;
3224 pageset = per_cpu_ptr(zone->pageset, cpu);
3226 printk("CPU %4d: hi:%5d, btch:%4d usd:%4d\n",
3227 cpu, pageset->pcp.high,
3228 pageset->pcp.batch, pageset->pcp.count);
3232 printk("active_anon:%lu inactive_anon:%lu isolated_anon:%lu\n"
3233 " active_file:%lu inactive_file:%lu isolated_file:%lu\n"
3234 " unevictable:%lu"
3235 " dirty:%lu writeback:%lu unstable:%lu\n"
3236 " free:%lu slab_reclaimable:%lu slab_unreclaimable:%lu\n"
3237 " mapped:%lu shmem:%lu pagetables:%lu bounce:%lu\n"
3238 " free_cma:%lu\n",
3239 global_page_state(NR_ACTIVE_ANON),
3240 global_page_state(NR_INACTIVE_ANON),
3241 global_page_state(NR_ISOLATED_ANON),
3242 global_page_state(NR_ACTIVE_FILE),
3243 global_page_state(NR_INACTIVE_FILE),
3244 global_page_state(NR_ISOLATED_FILE),
3245 global_page_state(NR_UNEVICTABLE),
3246 global_page_state(NR_FILE_DIRTY),
3247 global_page_state(NR_WRITEBACK),
3248 global_page_state(NR_UNSTABLE_NFS),
3249 global_page_state(NR_FREE_PAGES),
3250 global_page_state(NR_SLAB_RECLAIMABLE),
3251 global_page_state(NR_SLAB_UNRECLAIMABLE),
3252 global_page_state(NR_FILE_MAPPED),
3253 global_page_state(NR_SHMEM),
3254 global_page_state(NR_PAGETABLE),
3255 global_page_state(NR_BOUNCE),
3256 global_page_state(NR_FREE_CMA_PAGES));
3258 for_each_populated_zone(zone) {
3259 int i;
3261 if (skip_free_areas_node(filter, zone_to_nid(zone)))
3262 continue;
3263 show_node(zone);
3264 printk("%s"
3265 " free:%lukB"
3266 " min:%lukB"
3267 " low:%lukB"
3268 " high:%lukB"
3269 " active_anon:%lukB"
3270 " inactive_anon:%lukB"
3271 " active_file:%lukB"
3272 " inactive_file:%lukB"
3273 " unevictable:%lukB"
3274 " isolated(anon):%lukB"
3275 " isolated(file):%lukB"
3276 " present:%lukB"
3277 " managed:%lukB"
3278 " mlocked:%lukB"
3279 " dirty:%lukB"
3280 " writeback:%lukB"
3281 " mapped:%lukB"
3282 " shmem:%lukB"
3283 " slab_reclaimable:%lukB"
3284 " slab_unreclaimable:%lukB"
3285 " kernel_stack:%lukB"
3286 " pagetables:%lukB"
3287 " unstable:%lukB"
3288 " bounce:%lukB"
3289 " free_cma:%lukB"
3290 " writeback_tmp:%lukB"
3291 " pages_scanned:%lu"
3292 " all_unreclaimable? %s"
3293 "\n",
3294 zone->name,
3295 K(zone_page_state(zone, NR_FREE_PAGES)),
3296 K(min_wmark_pages(zone)),
3297 K(low_wmark_pages(zone)),
3298 K(high_wmark_pages(zone)),
3299 K(zone_page_state(zone, NR_ACTIVE_ANON)),
3300 K(zone_page_state(zone, NR_INACTIVE_ANON)),
3301 K(zone_page_state(zone, NR_ACTIVE_FILE)),
3302 K(zone_page_state(zone, NR_INACTIVE_FILE)),
3303 K(zone_page_state(zone, NR_UNEVICTABLE)),
3304 K(zone_page_state(zone, NR_ISOLATED_ANON)),
3305 K(zone_page_state(zone, NR_ISOLATED_FILE)),
3306 K(zone->present_pages),
3307 K(zone->managed_pages),
3308 K(zone_page_state(zone, NR_MLOCK)),
3309 K(zone_page_state(zone, NR_FILE_DIRTY)),
3310 K(zone_page_state(zone, NR_WRITEBACK)),
3311 K(zone_page_state(zone, NR_FILE_MAPPED)),
3312 K(zone_page_state(zone, NR_SHMEM)),
3313 K(zone_page_state(zone, NR_SLAB_RECLAIMABLE)),
3314 K(zone_page_state(zone, NR_SLAB_UNRECLAIMABLE)),
3315 zone_page_state(zone, NR_KERNEL_STACK) *
3316 THREAD_SIZE / 1024,
3317 K(zone_page_state(zone, NR_PAGETABLE)),
3318 K(zone_page_state(zone, NR_UNSTABLE_NFS)),
3319 K(zone_page_state(zone, NR_BOUNCE)),
3320 K(zone_page_state(zone, NR_FREE_CMA_PAGES)),
3321 K(zone_page_state(zone, NR_WRITEBACK_TEMP)),
3322 zone->pages_scanned,
3323 (!zone_reclaimable(zone) ? "yes" : "no")
3325 printk("lowmem_reserve[]:");
3326 for (i = 0; i < MAX_NR_ZONES; i++)
3327 printk(" %lu", zone->lowmem_reserve[i]);
3328 printk("\n");
3331 for_each_populated_zone(zone) {
3332 unsigned long nr[MAX_ORDER], flags, order, total = 0;
3333 unsigned char types[MAX_ORDER];
3335 if (skip_free_areas_node(filter, zone_to_nid(zone)))
3336 continue;
3337 show_node(zone);
3338 printk("%s: ", zone->name);
3340 spin_lock_irqsave(&zone->lock, flags);
3341 for (order = 0; order < MAX_ORDER; order++) {
3342 struct free_area *area = &zone->free_area[order];
3343 int type;
3345 nr[order] = area->nr_free;
3346 total += nr[order] << order;
3348 types[order] = 0;
3349 for (type = 0; type < MIGRATE_TYPES; type++) {
3350 if (!list_empty(&area->free_list[type]))
3351 types[order] |= 1 << type;
3354 spin_unlock_irqrestore(&zone->lock, flags);
3355 for (order = 0; order < MAX_ORDER; order++) {
3356 printk("%lu*%lukB ", nr[order], K(1UL) << order);
3357 if (nr[order])
3358 show_migration_types(types[order]);
3360 printk("= %lukB\n", K(total));
3363 hugetlb_show_meminfo();
3365 printk("%ld total pagecache pages\n", global_page_state(NR_FILE_PAGES));
3367 show_swap_cache_info();
3370 static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref)
3372 zoneref->zone = zone;
3373 zoneref->zone_idx = zone_idx(zone);
3377 * Builds allocation fallback zone lists.
3379 * Add all populated zones of a node to the zonelist.
3381 static int build_zonelists_node(pg_data_t *pgdat, struct zonelist *zonelist,
3382 int nr_zones)
3384 struct zone *zone;
3385 enum zone_type zone_type = MAX_NR_ZONES;
3387 do {
3388 zone_type--;
3389 zone = pgdat->node_zones + zone_type;
3390 if (populated_zone(zone)) {
3391 zoneref_set_zone(zone,
3392 &zonelist->_zonerefs[nr_zones++]);
3393 check_highest_zone(zone_type);
3395 } while (zone_type);
3397 return nr_zones;
3402 * zonelist_order:
3403 * 0 = automatic detection of better ordering.
3404 * 1 = order by ([node] distance, -zonetype)
3405 * 2 = order by (-zonetype, [node] distance)
3407 * If not NUMA, ZONELIST_ORDER_ZONE and ZONELIST_ORDER_NODE will create
3408 * the same zonelist. So only NUMA can configure this param.
3410 #define ZONELIST_ORDER_DEFAULT 0
3411 #define ZONELIST_ORDER_NODE 1
3412 #define ZONELIST_ORDER_ZONE 2
3414 /* zonelist order in the kernel.
3415 * set_zonelist_order() will set this to NODE or ZONE.
3417 static int current_zonelist_order = ZONELIST_ORDER_DEFAULT;
3418 static char zonelist_order_name[3][8] = {"Default", "Node", "Zone"};
3421 #ifdef CONFIG_NUMA
3422 /* The value user specified ....changed by config */
3423 static int user_zonelist_order = ZONELIST_ORDER_DEFAULT;
3424 /* string for sysctl */
3425 #define NUMA_ZONELIST_ORDER_LEN 16
3426 char numa_zonelist_order[16] = "default";
3429 * interface for configure zonelist ordering.
3430 * command line option "numa_zonelist_order"
3431 * = "[dD]efault - default, automatic configuration.
3432 * = "[nN]ode - order by node locality, then by zone within node
3433 * = "[zZ]one - order by zone, then by locality within zone
3436 static int __parse_numa_zonelist_order(char *s)
3438 if (*s == 'd' || *s == 'D') {
3439 user_zonelist_order = ZONELIST_ORDER_DEFAULT;
3440 } else if (*s == 'n' || *s == 'N') {
3441 user_zonelist_order = ZONELIST_ORDER_NODE;
3442 } else if (*s == 'z' || *s == 'Z') {
3443 user_zonelist_order = ZONELIST_ORDER_ZONE;
3444 } else {
3445 printk(KERN_WARNING
3446 "Ignoring invalid numa_zonelist_order value: "
3447 "%s\n", s);
3448 return -EINVAL;
3450 return 0;
3453 static __init int setup_numa_zonelist_order(char *s)
3455 int ret;
3457 if (!s)
3458 return 0;
3460 ret = __parse_numa_zonelist_order(s);
3461 if (ret == 0)
3462 strlcpy(numa_zonelist_order, s, NUMA_ZONELIST_ORDER_LEN);
3464 return ret;
3466 early_param("numa_zonelist_order", setup_numa_zonelist_order);
3469 * sysctl handler for numa_zonelist_order
3471 int numa_zonelist_order_handler(struct ctl_table *table, int write,
3472 void __user *buffer, size_t *length,
3473 loff_t *ppos)
3475 char saved_string[NUMA_ZONELIST_ORDER_LEN];
3476 int ret;
3477 static DEFINE_MUTEX(zl_order_mutex);
3479 mutex_lock(&zl_order_mutex);
3480 if (write) {
3481 if (strlen((char *)table->data) >= NUMA_ZONELIST_ORDER_LEN) {
3482 ret = -EINVAL;
3483 goto out;
3485 strcpy(saved_string, (char *)table->data);
3487 ret = proc_dostring(table, write, buffer, length, ppos);
3488 if (ret)
3489 goto out;
3490 if (write) {
3491 int oldval = user_zonelist_order;
3493 ret = __parse_numa_zonelist_order((char *)table->data);
3494 if (ret) {
3496 * bogus value. restore saved string
3498 strncpy((char *)table->data, saved_string,
3499 NUMA_ZONELIST_ORDER_LEN);
3500 user_zonelist_order = oldval;
3501 } else if (oldval != user_zonelist_order) {
3502 mutex_lock(&zonelists_mutex);
3503 build_all_zonelists(NULL, NULL);
3504 mutex_unlock(&zonelists_mutex);
3507 out:
3508 mutex_unlock(&zl_order_mutex);
3509 return ret;
3513 #define MAX_NODE_LOAD (nr_online_nodes)
3514 static int node_load[MAX_NUMNODES];
3517 * find_next_best_node - find the next node that should appear in a given node's fallback list
3518 * @node: node whose fallback list we're appending
3519 * @used_node_mask: nodemask_t of already used nodes
3521 * We use a number of factors to determine which is the next node that should
3522 * appear on a given node's fallback list. The node should not have appeared
3523 * already in @node's fallback list, and it should be the next closest node
3524 * according to the distance array (which contains arbitrary distance values
3525 * from each node to each node in the system), and should also prefer nodes
3526 * with no CPUs, since presumably they'll have very little allocation pressure
3527 * on them otherwise.
3528 * It returns -1 if no node is found.
3530 static int find_next_best_node(int node, nodemask_t *used_node_mask)
3532 int n, val;
3533 int min_val = INT_MAX;
3534 int best_node = NUMA_NO_NODE;
3535 const struct cpumask *tmp = cpumask_of_node(0);
3537 /* Use the local node if we haven't already */
3538 if (!node_isset(node, *used_node_mask)) {
3539 node_set(node, *used_node_mask);
3540 return node;
3543 for_each_node_state(n, N_MEMORY) {
3545 /* Don't want a node to appear more than once */
3546 if (node_isset(n, *used_node_mask))
3547 continue;
3549 /* Use the distance array to find the distance */
3550 val = node_distance(node, n);
3552 /* Penalize nodes under us ("prefer the next node") */
3553 val += (n < node);
3555 /* Give preference to headless and unused nodes */
3556 tmp = cpumask_of_node(n);
3557 if (!cpumask_empty(tmp))
3558 val += PENALTY_FOR_NODE_WITH_CPUS;
3560 /* Slight preference for less loaded node */
3561 val *= (MAX_NODE_LOAD*MAX_NUMNODES);
3562 val += node_load[n];
3564 if (val < min_val) {
3565 min_val = val;
3566 best_node = n;
3570 if (best_node >= 0)
3571 node_set(best_node, *used_node_mask);
3573 return best_node;
3578 * Build zonelists ordered by node and zones within node.
3579 * This results in maximum locality--normal zone overflows into local
3580 * DMA zone, if any--but risks exhausting DMA zone.
3582 static void build_zonelists_in_node_order(pg_data_t *pgdat, int node)
3584 int j;
3585 struct zonelist *zonelist;
3587 zonelist = &pgdat->node_zonelists[0];
3588 for (j = 0; zonelist->_zonerefs[j].zone != NULL; j++)
3590 j = build_zonelists_node(NODE_DATA(node), zonelist, j);
3591 zonelist->_zonerefs[j].zone = NULL;
3592 zonelist->_zonerefs[j].zone_idx = 0;
3596 * Build gfp_thisnode zonelists
3598 static void build_thisnode_zonelists(pg_data_t *pgdat)
3600 int j;
3601 struct zonelist *zonelist;
3603 zonelist = &pgdat->node_zonelists[1];
3604 j = build_zonelists_node(pgdat, zonelist, 0);
3605 zonelist->_zonerefs[j].zone = NULL;
3606 zonelist->_zonerefs[j].zone_idx = 0;
3610 * Build zonelists ordered by zone and nodes within zones.
3611 * This results in conserving DMA zone[s] until all Normal memory is
3612 * exhausted, but results in overflowing to remote node while memory
3613 * may still exist in local DMA zone.
3615 static int node_order[MAX_NUMNODES];
3617 static void build_zonelists_in_zone_order(pg_data_t *pgdat, int nr_nodes)
3619 int pos, j, node;
3620 int zone_type; /* needs to be signed */
3621 struct zone *z;
3622 struct zonelist *zonelist;
3624 zonelist = &pgdat->node_zonelists[0];
3625 pos = 0;
3626 for (zone_type = MAX_NR_ZONES - 1; zone_type >= 0; zone_type--) {
3627 for (j = 0; j < nr_nodes; j++) {
3628 node = node_order[j];
3629 z = &NODE_DATA(node)->node_zones[zone_type];
3630 if (populated_zone(z)) {
3631 zoneref_set_zone(z,
3632 &zonelist->_zonerefs[pos++]);
3633 check_highest_zone(zone_type);
3637 zonelist->_zonerefs[pos].zone = NULL;
3638 zonelist->_zonerefs[pos].zone_idx = 0;
3641 static int default_zonelist_order(void)
3643 int nid, zone_type;
3644 unsigned long low_kmem_size, total_size;
3645 struct zone *z;
3646 int average_size;
3648 * ZONE_DMA and ZONE_DMA32 can be very small area in the system.
3649 * If they are really small and used heavily, the system can fall
3650 * into OOM very easily.
3651 * This function detect ZONE_DMA/DMA32 size and configures zone order.
3653 /* Is there ZONE_NORMAL ? (ex. ppc has only DMA zone..) */
3654 low_kmem_size = 0;
3655 total_size = 0;
3656 for_each_online_node(nid) {
3657 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
3658 z = &NODE_DATA(nid)->node_zones[zone_type];
3659 if (populated_zone(z)) {
3660 if (zone_type < ZONE_NORMAL)
3661 low_kmem_size += z->managed_pages;
3662 total_size += z->managed_pages;
3663 } else if (zone_type == ZONE_NORMAL) {
3665 * If any node has only lowmem, then node order
3666 * is preferred to allow kernel allocations
3667 * locally; otherwise, they can easily infringe
3668 * on other nodes when there is an abundance of
3669 * lowmem available to allocate from.
3671 return ZONELIST_ORDER_NODE;
3675 if (!low_kmem_size || /* there are no DMA area. */
3676 low_kmem_size > total_size/2) /* DMA/DMA32 is big. */
3677 return ZONELIST_ORDER_NODE;
3679 * look into each node's config.
3680 * If there is a node whose DMA/DMA32 memory is very big area on
3681 * local memory, NODE_ORDER may be suitable.
3683 average_size = total_size /
3684 (nodes_weight(node_states[N_MEMORY]) + 1);
3685 for_each_online_node(nid) {
3686 low_kmem_size = 0;
3687 total_size = 0;
3688 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
3689 z = &NODE_DATA(nid)->node_zones[zone_type];
3690 if (populated_zone(z)) {
3691 if (zone_type < ZONE_NORMAL)
3692 low_kmem_size += z->present_pages;
3693 total_size += z->present_pages;
3696 if (low_kmem_size &&
3697 total_size > average_size && /* ignore small node */
3698 low_kmem_size > total_size * 70/100)
3699 return ZONELIST_ORDER_NODE;
3701 return ZONELIST_ORDER_ZONE;
3704 static void set_zonelist_order(void)
3706 if (user_zonelist_order == ZONELIST_ORDER_DEFAULT)
3707 current_zonelist_order = default_zonelist_order();
3708 else
3709 current_zonelist_order = user_zonelist_order;
3712 static void build_zonelists(pg_data_t *pgdat)
3714 int j, node, load;
3715 enum zone_type i;
3716 nodemask_t used_mask;
3717 int local_node, prev_node;
3718 struct zonelist *zonelist;
3719 int order = current_zonelist_order;
3721 /* initialize zonelists */
3722 for (i = 0; i < MAX_ZONELISTS; i++) {
3723 zonelist = pgdat->node_zonelists + i;
3724 zonelist->_zonerefs[0].zone = NULL;
3725 zonelist->_zonerefs[0].zone_idx = 0;
3728 /* NUMA-aware ordering of nodes */
3729 local_node = pgdat->node_id;
3730 load = nr_online_nodes;
3731 prev_node = local_node;
3732 nodes_clear(used_mask);
3734 memset(node_order, 0, sizeof(node_order));
3735 j = 0;
3737 while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
3739 * We don't want to pressure a particular node.
3740 * So adding penalty to the first node in same
3741 * distance group to make it round-robin.
3743 if (node_distance(local_node, node) !=
3744 node_distance(local_node, prev_node))
3745 node_load[node] = load;
3747 prev_node = node;
3748 load--;
3749 if (order == ZONELIST_ORDER_NODE)
3750 build_zonelists_in_node_order(pgdat, node);
3751 else
3752 node_order[j++] = node; /* remember order */
3755 if (order == ZONELIST_ORDER_ZONE) {
3756 /* calculate node order -- i.e., DMA last! */
3757 build_zonelists_in_zone_order(pgdat, j);
3760 build_thisnode_zonelists(pgdat);
3763 /* Construct the zonelist performance cache - see further mmzone.h */
3764 static void build_zonelist_cache(pg_data_t *pgdat)
3766 struct zonelist *zonelist;
3767 struct zonelist_cache *zlc;
3768 struct zoneref *z;
3770 zonelist = &pgdat->node_zonelists[0];
3771 zonelist->zlcache_ptr = zlc = &zonelist->zlcache;
3772 bitmap_zero(zlc->fullzones, MAX_ZONES_PER_ZONELIST);
3773 for (z = zonelist->_zonerefs; z->zone; z++)
3774 zlc->z_to_n[z - zonelist->_zonerefs] = zonelist_node_idx(z);
3777 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
3779 * Return node id of node used for "local" allocations.
3780 * I.e., first node id of first zone in arg node's generic zonelist.
3781 * Used for initializing percpu 'numa_mem', which is used primarily
3782 * for kernel allocations, so use GFP_KERNEL flags to locate zonelist.
3784 int local_memory_node(int node)
3786 struct zone *zone;
3788 (void)first_zones_zonelist(node_zonelist(node, GFP_KERNEL),
3789 gfp_zone(GFP_KERNEL),
3790 NULL,
3791 &zone);
3792 return zone->node;
3794 #endif
3796 #else /* CONFIG_NUMA */
3798 static void set_zonelist_order(void)
3800 current_zonelist_order = ZONELIST_ORDER_ZONE;
3803 static void build_zonelists(pg_data_t *pgdat)
3805 int node, local_node;
3806 enum zone_type j;
3807 struct zonelist *zonelist;
3809 local_node = pgdat->node_id;
3811 zonelist = &pgdat->node_zonelists[0];
3812 j = build_zonelists_node(pgdat, zonelist, 0);
3815 * Now we build the zonelist so that it contains the zones
3816 * of all the other nodes.
3817 * We don't want to pressure a particular node, so when
3818 * building the zones for node N, we make sure that the
3819 * zones coming right after the local ones are those from
3820 * node N+1 (modulo N)
3822 for (node = local_node + 1; node < MAX_NUMNODES; node++) {
3823 if (!node_online(node))
3824 continue;
3825 j = build_zonelists_node(NODE_DATA(node), zonelist, j);
3827 for (node = 0; node < local_node; node++) {
3828 if (!node_online(node))
3829 continue;
3830 j = build_zonelists_node(NODE_DATA(node), zonelist, j);
3833 zonelist->_zonerefs[j].zone = NULL;
3834 zonelist->_zonerefs[j].zone_idx = 0;
3837 /* non-NUMA variant of zonelist performance cache - just NULL zlcache_ptr */
3838 static void build_zonelist_cache(pg_data_t *pgdat)
3840 pgdat->node_zonelists[0].zlcache_ptr = NULL;
3843 #endif /* CONFIG_NUMA */
3846 * Boot pageset table. One per cpu which is going to be used for all
3847 * zones and all nodes. The parameters will be set in such a way
3848 * that an item put on a list will immediately be handed over to
3849 * the buddy list. This is safe since pageset manipulation is done
3850 * with interrupts disabled.
3852 * The boot_pagesets must be kept even after bootup is complete for
3853 * unused processors and/or zones. They do play a role for bootstrapping
3854 * hotplugged processors.
3856 * zoneinfo_show() and maybe other functions do
3857 * not check if the processor is online before following the pageset pointer.
3858 * Other parts of the kernel may not check if the zone is available.
3860 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch);
3861 static DEFINE_PER_CPU(struct per_cpu_pageset, boot_pageset);
3862 static void setup_zone_pageset(struct zone *zone);
3865 * Global mutex to protect against size modification of zonelists
3866 * as well as to serialize pageset setup for the new populated zone.
3868 DEFINE_MUTEX(zonelists_mutex);
3870 /* return values int ....just for stop_machine() */
3871 static int __build_all_zonelists(void *data)
3873 int nid;
3874 int cpu;
3875 pg_data_t *self = data;
3877 #ifdef CONFIG_NUMA
3878 memset(node_load, 0, sizeof(node_load));
3879 #endif
3881 if (self && !node_online(self->node_id)) {
3882 build_zonelists(self);
3883 build_zonelist_cache(self);
3886 for_each_online_node(nid) {
3887 pg_data_t *pgdat = NODE_DATA(nid);
3889 build_zonelists(pgdat);
3890 build_zonelist_cache(pgdat);
3894 * Initialize the boot_pagesets that are going to be used
3895 * for bootstrapping processors. The real pagesets for
3896 * each zone will be allocated later when the per cpu
3897 * allocator is available.
3899 * boot_pagesets are used also for bootstrapping offline
3900 * cpus if the system is already booted because the pagesets
3901 * are needed to initialize allocators on a specific cpu too.
3902 * F.e. the percpu allocator needs the page allocator which
3903 * needs the percpu allocator in order to allocate its pagesets
3904 * (a chicken-egg dilemma).
3906 for_each_possible_cpu(cpu) {
3907 setup_pageset(&per_cpu(boot_pageset, cpu), 0);
3909 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
3911 * We now know the "local memory node" for each node--
3912 * i.e., the node of the first zone in the generic zonelist.
3913 * Set up numa_mem percpu variable for on-line cpus. During
3914 * boot, only the boot cpu should be on-line; we'll init the
3915 * secondary cpus' numa_mem as they come on-line. During
3916 * node/memory hotplug, we'll fixup all on-line cpus.
3918 if (cpu_online(cpu))
3919 set_cpu_numa_mem(cpu, local_memory_node(cpu_to_node(cpu)));
3920 #endif
3923 return 0;
3927 * Called with zonelists_mutex held always
3928 * unless system_state == SYSTEM_BOOTING.
3930 void __ref build_all_zonelists(pg_data_t *pgdat, struct zone *zone)
3932 set_zonelist_order();
3934 if (system_state == SYSTEM_BOOTING) {
3935 __build_all_zonelists(NULL);
3936 mminit_verify_zonelist();
3937 cpuset_init_current_mems_allowed();
3938 } else {
3939 #ifdef CONFIG_MEMORY_HOTPLUG
3940 if (zone)
3941 setup_zone_pageset(zone);
3942 #endif
3943 /* we have to stop all cpus to guarantee there is no user
3944 of zonelist */
3945 stop_machine(__build_all_zonelists, pgdat, NULL);
3946 /* cpuset refresh routine should be here */
3948 vm_total_pages = nr_free_pagecache_pages();
3950 * Disable grouping by mobility if the number of pages in the
3951 * system is too low to allow the mechanism to work. It would be
3952 * more accurate, but expensive to check per-zone. This check is
3953 * made on memory-hotadd so a system can start with mobility
3954 * disabled and enable it later
3956 if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES))
3957 page_group_by_mobility_disabled = 1;
3958 else
3959 page_group_by_mobility_disabled = 0;
3961 printk("Built %i zonelists in %s order, mobility grouping %s. "
3962 "Total pages: %ld\n",
3963 nr_online_nodes,
3964 zonelist_order_name[current_zonelist_order],
3965 page_group_by_mobility_disabled ? "off" : "on",
3966 vm_total_pages);
3967 #ifdef CONFIG_NUMA
3968 printk("Policy zone: %s\n", zone_names[policy_zone]);
3969 #endif
3973 * Helper functions to size the waitqueue hash table.
3974 * Essentially these want to choose hash table sizes sufficiently
3975 * large so that collisions trying to wait on pages are rare.
3976 * But in fact, the number of active page waitqueues on typical
3977 * systems is ridiculously low, less than 200. So this is even
3978 * conservative, even though it seems large.
3980 * The constant PAGES_PER_WAITQUEUE specifies the ratio of pages to
3981 * waitqueues, i.e. the size of the waitq table given the number of pages.
3983 #define PAGES_PER_WAITQUEUE 256
3985 #ifndef CONFIG_MEMORY_HOTPLUG
3986 static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
3988 unsigned long size = 1;
3990 pages /= PAGES_PER_WAITQUEUE;
3992 while (size < pages)
3993 size <<= 1;
3996 * Once we have dozens or even hundreds of threads sleeping
3997 * on IO we've got bigger problems than wait queue collision.
3998 * Limit the size of the wait table to a reasonable size.
4000 size = min(size, 4096UL);
4002 return max(size, 4UL);
4004 #else
4006 * A zone's size might be changed by hot-add, so it is not possible to determine
4007 * a suitable size for its wait_table. So we use the maximum size now.
4009 * The max wait table size = 4096 x sizeof(wait_queue_head_t). ie:
4011 * i386 (preemption config) : 4096 x 16 = 64Kbyte.
4012 * ia64, x86-64 (no preemption): 4096 x 20 = 80Kbyte.
4013 * ia64, x86-64 (preemption) : 4096 x 24 = 96Kbyte.
4015 * The maximum entries are prepared when a zone's memory is (512K + 256) pages
4016 * or more by the traditional way. (See above). It equals:
4018 * i386, x86-64, powerpc(4K page size) : = ( 2G + 1M)byte.
4019 * ia64(16K page size) : = ( 8G + 4M)byte.
4020 * powerpc (64K page size) : = (32G +16M)byte.
4022 static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
4024 return 4096UL;
4026 #endif
4029 * This is an integer logarithm so that shifts can be used later
4030 * to extract the more random high bits from the multiplicative
4031 * hash function before the remainder is taken.
4033 static inline unsigned long wait_table_bits(unsigned long size)
4035 return ffz(~size);
4039 * Check if a pageblock contains reserved pages
4041 static int pageblock_is_reserved(unsigned long start_pfn, unsigned long end_pfn)
4043 unsigned long pfn;
4045 for (pfn = start_pfn; pfn < end_pfn; pfn++) {
4046 if (!pfn_valid_within(pfn) || PageReserved(pfn_to_page(pfn)))
4047 return 1;
4049 return 0;
4053 * Mark a number of pageblocks as MIGRATE_RESERVE. The number
4054 * of blocks reserved is based on min_wmark_pages(zone). The memory within
4055 * the reserve will tend to store contiguous free pages. Setting min_free_kbytes
4056 * higher will lead to a bigger reserve which will get freed as contiguous
4057 * blocks as reclaim kicks in
4059 static void setup_zone_migrate_reserve(struct zone *zone)
4061 unsigned long start_pfn, pfn, end_pfn, block_end_pfn;
4062 struct page *page;
4063 unsigned long block_migratetype;
4064 int reserve;
4065 int old_reserve;
4068 * Get the start pfn, end pfn and the number of blocks to reserve
4069 * We have to be careful to be aligned to pageblock_nr_pages to
4070 * make sure that we always check pfn_valid for the first page in
4071 * the block.
4073 start_pfn = zone->zone_start_pfn;
4074 end_pfn = zone_end_pfn(zone);
4075 start_pfn = roundup(start_pfn, pageblock_nr_pages);
4076 reserve = roundup(min_wmark_pages(zone), pageblock_nr_pages) >>
4077 pageblock_order;
4080 * Reserve blocks are generally in place to help high-order atomic
4081 * allocations that are short-lived. A min_free_kbytes value that
4082 * would result in more than 2 reserve blocks for atomic allocations
4083 * is assumed to be in place to help anti-fragmentation for the
4084 * future allocation of hugepages at runtime.
4086 reserve = min(2, reserve);
4087 old_reserve = zone->nr_migrate_reserve_block;
4089 /* When memory hot-add, we almost always need to do nothing */
4090 if (reserve == old_reserve)
4091 return;
4092 zone->nr_migrate_reserve_block = reserve;
4094 for (pfn = start_pfn; pfn < end_pfn; pfn += pageblock_nr_pages) {
4095 if (!pfn_valid(pfn))
4096 continue;
4097 page = pfn_to_page(pfn);
4099 /* Watch out for overlapping nodes */
4100 if (page_to_nid(page) != zone_to_nid(zone))
4101 continue;
4103 block_migratetype = get_pageblock_migratetype(page);
4105 /* Only test what is necessary when the reserves are not met */
4106 if (reserve > 0) {
4108 * Blocks with reserved pages will never free, skip
4109 * them.
4111 block_end_pfn = min(pfn + pageblock_nr_pages, end_pfn);
4112 if (pageblock_is_reserved(pfn, block_end_pfn))
4113 continue;
4115 /* If this block is reserved, account for it */
4116 if (block_migratetype == MIGRATE_RESERVE) {
4117 reserve--;
4118 continue;
4121 /* Suitable for reserving if this block is movable */
4122 if (block_migratetype == MIGRATE_MOVABLE) {
4123 set_pageblock_migratetype(page,
4124 MIGRATE_RESERVE);
4125 move_freepages_block(zone, page,
4126 MIGRATE_RESERVE);
4127 reserve--;
4128 continue;
4130 } else if (!old_reserve) {
4132 * At boot time we don't need to scan the whole zone
4133 * for turning off MIGRATE_RESERVE.
4135 break;
4139 * If the reserve is met and this is a previous reserved block,
4140 * take it back
4142 if (block_migratetype == MIGRATE_RESERVE) {
4143 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
4144 move_freepages_block(zone, page, MIGRATE_MOVABLE);
4150 * Initially all pages are reserved - free ones are freed
4151 * up by free_all_bootmem() once the early boot process is
4152 * done. Non-atomic initialization, single-pass.
4154 void __meminit memmap_init_zone(unsigned long size, int nid, unsigned long zone,
4155 unsigned long start_pfn, enum memmap_context context)
4157 struct page *page;
4158 unsigned long end_pfn = start_pfn + size;
4159 unsigned long pfn;
4160 struct zone *z;
4162 if (highest_memmap_pfn < end_pfn - 1)
4163 highest_memmap_pfn = end_pfn - 1;
4165 z = &NODE_DATA(nid)->node_zones[zone];
4166 for (pfn = start_pfn; pfn < end_pfn; pfn++) {
4168 * There can be holes in boot-time mem_map[]s
4169 * handed to this function. They do not
4170 * exist on hotplugged memory.
4172 if (context == MEMMAP_EARLY) {
4173 if (!early_pfn_valid(pfn))
4174 continue;
4175 if (!early_pfn_in_nid(pfn, nid))
4176 continue;
4178 page = pfn_to_page(pfn);
4179 set_page_links(page, zone, nid, pfn);
4180 mminit_verify_page_links(page, zone, nid, pfn);
4181 init_page_count(page);
4182 page_mapcount_reset(page);
4183 page_cpupid_reset_last(page);
4184 SetPageReserved(page);
4186 * Mark the block movable so that blocks are reserved for
4187 * movable at startup. This will force kernel allocations
4188 * to reserve their blocks rather than leaking throughout
4189 * the address space during boot when many long-lived
4190 * kernel allocations are made. Later some blocks near
4191 * the start are marked MIGRATE_RESERVE by
4192 * setup_zone_migrate_reserve()
4194 * bitmap is created for zone's valid pfn range. but memmap
4195 * can be created for invalid pages (for alignment)
4196 * check here not to call set_pageblock_migratetype() against
4197 * pfn out of zone.
4199 if ((z->zone_start_pfn <= pfn)
4200 && (pfn < zone_end_pfn(z))
4201 && !(pfn & (pageblock_nr_pages - 1)))
4202 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
4204 INIT_LIST_HEAD(&page->lru);
4205 #ifdef WANT_PAGE_VIRTUAL
4206 /* The shift won't overflow because ZONE_NORMAL is below 4G. */
4207 if (!is_highmem_idx(zone))
4208 set_page_address(page, __va(pfn << PAGE_SHIFT));
4209 #endif
4213 static void __meminit zone_init_free_lists(struct zone *zone)
4215 unsigned int order, t;
4216 for_each_migratetype_order(order, t) {
4217 INIT_LIST_HEAD(&zone->free_area[order].free_list[t]);
4218 zone->free_area[order].nr_free = 0;
4222 #ifndef __HAVE_ARCH_MEMMAP_INIT
4223 #define memmap_init(size, nid, zone, start_pfn) \
4224 memmap_init_zone((size), (nid), (zone), (start_pfn), MEMMAP_EARLY)
4225 #endif
4227 static int zone_batchsize(struct zone *zone)
4229 #ifdef CONFIG_MMU
4230 int batch;
4233 * The per-cpu-pages pools are set to around 1000th of the
4234 * size of the zone. But no more than 1/2 of a meg.
4236 * OK, so we don't know how big the cache is. So guess.
4238 batch = zone->managed_pages / 1024;
4239 if (batch * PAGE_SIZE > 512 * 1024)
4240 batch = (512 * 1024) / PAGE_SIZE;
4241 batch /= 4; /* We effectively *= 4 below */
4242 if (batch < 1)
4243 batch = 1;
4246 * Clamp the batch to a 2^n - 1 value. Having a power
4247 * of 2 value was found to be more likely to have
4248 * suboptimal cache aliasing properties in some cases.
4250 * For example if 2 tasks are alternately allocating
4251 * batches of pages, one task can end up with a lot
4252 * of pages of one half of the possible page colors
4253 * and the other with pages of the other colors.
4255 batch = rounddown_pow_of_two(batch + batch/2) - 1;
4257 return batch;
4259 #else
4260 /* The deferral and batching of frees should be suppressed under NOMMU
4261 * conditions.
4263 * The problem is that NOMMU needs to be able to allocate large chunks
4264 * of contiguous memory as there's no hardware page translation to
4265 * assemble apparent contiguous memory from discontiguous pages.
4267 * Queueing large contiguous runs of pages for batching, however,
4268 * causes the pages to actually be freed in smaller chunks. As there
4269 * can be a significant delay between the individual batches being
4270 * recycled, this leads to the once large chunks of space being
4271 * fragmented and becoming unavailable for high-order allocations.
4273 return 0;
4274 #endif
4278 * pcp->high and pcp->batch values are related and dependent on one another:
4279 * ->batch must never be higher then ->high.
4280 * The following function updates them in a safe manner without read side
4281 * locking.
4283 * Any new users of pcp->batch and pcp->high should ensure they can cope with
4284 * those fields changing asynchronously (acording the the above rule).
4286 * mutex_is_locked(&pcp_batch_high_lock) required when calling this function
4287 * outside of boot time (or some other assurance that no concurrent updaters
4288 * exist).
4290 static void pageset_update(struct per_cpu_pages *pcp, unsigned long high,
4291 unsigned long batch)
4293 /* start with a fail safe value for batch */
4294 pcp->batch = 1;
4295 smp_wmb();
4297 /* Update high, then batch, in order */
4298 pcp->high = high;
4299 smp_wmb();
4301 pcp->batch = batch;
4304 /* a companion to pageset_set_high() */
4305 static void pageset_set_batch(struct per_cpu_pageset *p, unsigned long batch)
4307 pageset_update(&p->pcp, 6 * batch, max(1UL, 1 * batch));
4310 static void pageset_init(struct per_cpu_pageset *p)
4312 struct per_cpu_pages *pcp;
4313 int migratetype;
4315 memset(p, 0, sizeof(*p));
4317 pcp = &p->pcp;
4318 pcp->count = 0;
4319 for (migratetype = 0; migratetype < MIGRATE_PCPTYPES; migratetype++)
4320 INIT_LIST_HEAD(&pcp->lists[migratetype]);
4323 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch)
4325 pageset_init(p);
4326 pageset_set_batch(p, batch);
4330 * pageset_set_high() sets the high water mark for hot per_cpu_pagelist
4331 * to the value high for the pageset p.
4333 static void pageset_set_high(struct per_cpu_pageset *p,
4334 unsigned long high)
4336 unsigned long batch = max(1UL, high / 4);
4337 if ((high / 4) > (PAGE_SHIFT * 8))
4338 batch = PAGE_SHIFT * 8;
4340 pageset_update(&p->pcp, high, batch);
4343 static void pageset_set_high_and_batch(struct zone *zone,
4344 struct per_cpu_pageset *pcp)
4346 if (percpu_pagelist_fraction)
4347 pageset_set_high(pcp,
4348 (zone->managed_pages /
4349 percpu_pagelist_fraction));
4350 else
4351 pageset_set_batch(pcp, zone_batchsize(zone));
4354 static void __meminit zone_pageset_init(struct zone *zone, int cpu)
4356 struct per_cpu_pageset *pcp = per_cpu_ptr(zone->pageset, cpu);
4358 pageset_init(pcp);
4359 pageset_set_high_and_batch(zone, pcp);
4362 static void __meminit setup_zone_pageset(struct zone *zone)
4364 int cpu;
4365 zone->pageset = alloc_percpu(struct per_cpu_pageset);
4366 for_each_possible_cpu(cpu)
4367 zone_pageset_init(zone, cpu);
4371 * Allocate per cpu pagesets and initialize them.
4372 * Before this call only boot pagesets were available.
4374 void __init setup_per_cpu_pageset(void)
4376 struct zone *zone;
4378 for_each_populated_zone(zone)
4379 setup_zone_pageset(zone);
4382 static noinline __init_refok
4383 int zone_wait_table_init(struct zone *zone, unsigned long zone_size_pages)
4385 int i;
4386 size_t alloc_size;
4389 * The per-page waitqueue mechanism uses hashed waitqueues
4390 * per zone.
4392 zone->wait_table_hash_nr_entries =
4393 wait_table_hash_nr_entries(zone_size_pages);
4394 zone->wait_table_bits =
4395 wait_table_bits(zone->wait_table_hash_nr_entries);
4396 alloc_size = zone->wait_table_hash_nr_entries
4397 * sizeof(wait_queue_head_t);
4399 if (!slab_is_available()) {
4400 zone->wait_table = (wait_queue_head_t *)
4401 memblock_virt_alloc_node_nopanic(
4402 alloc_size, zone->zone_pgdat->node_id);
4403 } else {
4405 * This case means that a zone whose size was 0 gets new memory
4406 * via memory hot-add.
4407 * But it may be the case that a new node was hot-added. In
4408 * this case vmalloc() will not be able to use this new node's
4409 * memory - this wait_table must be initialized to use this new
4410 * node itself as well.
4411 * To use this new node's memory, further consideration will be
4412 * necessary.
4414 zone->wait_table = vmalloc(alloc_size);
4416 if (!zone->wait_table)
4417 return -ENOMEM;
4419 for (i = 0; i < zone->wait_table_hash_nr_entries; ++i)
4420 init_waitqueue_head(zone->wait_table + i);
4422 return 0;
4425 static __meminit void zone_pcp_init(struct zone *zone)
4428 * per cpu subsystem is not up at this point. The following code
4429 * relies on the ability of the linker to provide the
4430 * offset of a (static) per cpu variable into the per cpu area.
4432 zone->pageset = &boot_pageset;
4434 if (populated_zone(zone))
4435 printk(KERN_DEBUG " %s zone: %lu pages, LIFO batch:%u\n",
4436 zone->name, zone->present_pages,
4437 zone_batchsize(zone));
4440 int __meminit init_currently_empty_zone(struct zone *zone,
4441 unsigned long zone_start_pfn,
4442 unsigned long size,
4443 enum memmap_context context)
4445 struct pglist_data *pgdat = zone->zone_pgdat;
4446 int ret;
4447 ret = zone_wait_table_init(zone, size);
4448 if (ret)
4449 return ret;
4450 pgdat->nr_zones = zone_idx(zone) + 1;
4452 zone->zone_start_pfn = zone_start_pfn;
4454 mminit_dprintk(MMINIT_TRACE, "memmap_init",
4455 "Initialising map node %d zone %lu pfns %lu -> %lu\n",
4456 pgdat->node_id,
4457 (unsigned long)zone_idx(zone),
4458 zone_start_pfn, (zone_start_pfn + size));
4460 zone_init_free_lists(zone);
4462 return 0;
4465 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
4466 #ifndef CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID
4468 * Required by SPARSEMEM. Given a PFN, return what node the PFN is on.
4470 int __meminit __early_pfn_to_nid(unsigned long pfn)
4472 unsigned long start_pfn, end_pfn;
4473 int nid;
4475 * NOTE: The following SMP-unsafe globals are only used early in boot
4476 * when the kernel is running single-threaded.
4478 static unsigned long __meminitdata last_start_pfn, last_end_pfn;
4479 static int __meminitdata last_nid;
4481 if (last_start_pfn <= pfn && pfn < last_end_pfn)
4482 return last_nid;
4484 nid = memblock_search_pfn_nid(pfn, &start_pfn, &end_pfn);
4485 if (nid != -1) {
4486 last_start_pfn = start_pfn;
4487 last_end_pfn = end_pfn;
4488 last_nid = nid;
4491 return nid;
4493 #endif /* CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID */
4495 int __meminit early_pfn_to_nid(unsigned long pfn)
4497 int nid;
4499 nid = __early_pfn_to_nid(pfn);
4500 if (nid >= 0)
4501 return nid;
4502 /* just returns 0 */
4503 return 0;
4506 #ifdef CONFIG_NODES_SPAN_OTHER_NODES
4507 bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
4509 int nid;
4511 nid = __early_pfn_to_nid(pfn);
4512 if (nid >= 0 && nid != node)
4513 return false;
4514 return true;
4516 #endif
4519 * free_bootmem_with_active_regions - Call memblock_free_early_nid for each active range
4520 * @nid: The node to free memory on. If MAX_NUMNODES, all nodes are freed.
4521 * @max_low_pfn: The highest PFN that will be passed to memblock_free_early_nid
4523 * If an architecture guarantees that all ranges registered contain no holes
4524 * and may be freed, this this function may be used instead of calling
4525 * memblock_free_early_nid() manually.
4527 void __init free_bootmem_with_active_regions(int nid, unsigned long max_low_pfn)
4529 unsigned long start_pfn, end_pfn;
4530 int i, this_nid;
4532 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, &this_nid) {
4533 start_pfn = min(start_pfn, max_low_pfn);
4534 end_pfn = min(end_pfn, max_low_pfn);
4536 if (start_pfn < end_pfn)
4537 memblock_free_early_nid(PFN_PHYS(start_pfn),
4538 (end_pfn - start_pfn) << PAGE_SHIFT,
4539 this_nid);
4544 * sparse_memory_present_with_active_regions - Call memory_present for each active range
4545 * @nid: The node to call memory_present for. If MAX_NUMNODES, all nodes will be used.
4547 * If an architecture guarantees that all ranges registered contain no holes and may
4548 * be freed, this function may be used instead of calling memory_present() manually.
4550 void __init sparse_memory_present_with_active_regions(int nid)
4552 unsigned long start_pfn, end_pfn;
4553 int i, this_nid;
4555 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, &this_nid)
4556 memory_present(this_nid, start_pfn, end_pfn);
4560 * get_pfn_range_for_nid - Return the start and end page frames for a node
4561 * @nid: The nid to return the range for. If MAX_NUMNODES, the min and max PFN are returned.
4562 * @start_pfn: Passed by reference. On return, it will have the node start_pfn.
4563 * @end_pfn: Passed by reference. On return, it will have the node end_pfn.
4565 * It returns the start and end page frame of a node based on information
4566 * provided by memblock_set_node(). If called for a node
4567 * with no available memory, a warning is printed and the start and end
4568 * PFNs will be 0.
4570 void __meminit get_pfn_range_for_nid(unsigned int nid,
4571 unsigned long *start_pfn, unsigned long *end_pfn)
4573 unsigned long this_start_pfn, this_end_pfn;
4574 int i;
4576 *start_pfn = -1UL;
4577 *end_pfn = 0;
4579 for_each_mem_pfn_range(i, nid, &this_start_pfn, &this_end_pfn, NULL) {
4580 *start_pfn = min(*start_pfn, this_start_pfn);
4581 *end_pfn = max(*end_pfn, this_end_pfn);
4584 if (*start_pfn == -1UL)
4585 *start_pfn = 0;
4589 * This finds a zone that can be used for ZONE_MOVABLE pages. The
4590 * assumption is made that zones within a node are ordered in monotonic
4591 * increasing memory addresses so that the "highest" populated zone is used
4593 static void __init find_usable_zone_for_movable(void)
4595 int zone_index;
4596 for (zone_index = MAX_NR_ZONES - 1; zone_index >= 0; zone_index--) {
4597 if (zone_index == ZONE_MOVABLE)
4598 continue;
4600 if (arch_zone_highest_possible_pfn[zone_index] >
4601 arch_zone_lowest_possible_pfn[zone_index])
4602 break;
4605 VM_BUG_ON(zone_index == -1);
4606 movable_zone = zone_index;
4610 * The zone ranges provided by the architecture do not include ZONE_MOVABLE
4611 * because it is sized independent of architecture. Unlike the other zones,
4612 * the starting point for ZONE_MOVABLE is not fixed. It may be different
4613 * in each node depending on the size of each node and how evenly kernelcore
4614 * is distributed. This helper function adjusts the zone ranges
4615 * provided by the architecture for a given node by using the end of the
4616 * highest usable zone for ZONE_MOVABLE. This preserves the assumption that
4617 * zones within a node are in order of monotonic increases memory addresses
4619 static void __meminit adjust_zone_range_for_zone_movable(int nid,
4620 unsigned long zone_type,
4621 unsigned long node_start_pfn,
4622 unsigned long node_end_pfn,
4623 unsigned long *zone_start_pfn,
4624 unsigned long *zone_end_pfn)
4626 /* Only adjust if ZONE_MOVABLE is on this node */
4627 if (zone_movable_pfn[nid]) {
4628 /* Size ZONE_MOVABLE */
4629 if (zone_type == ZONE_MOVABLE) {
4630 *zone_start_pfn = zone_movable_pfn[nid];
4631 *zone_end_pfn = min(node_end_pfn,
4632 arch_zone_highest_possible_pfn[movable_zone]);
4634 /* Adjust for ZONE_MOVABLE starting within this range */
4635 } else if (*zone_start_pfn < zone_movable_pfn[nid] &&
4636 *zone_end_pfn > zone_movable_pfn[nid]) {
4637 *zone_end_pfn = zone_movable_pfn[nid];
4639 /* Check if this whole range is within ZONE_MOVABLE */
4640 } else if (*zone_start_pfn >= zone_movable_pfn[nid])
4641 *zone_start_pfn = *zone_end_pfn;
4646 * Return the number of pages a zone spans in a node, including holes
4647 * present_pages = zone_spanned_pages_in_node() - zone_absent_pages_in_node()
4649 static unsigned long __meminit zone_spanned_pages_in_node(int nid,
4650 unsigned long zone_type,
4651 unsigned long node_start_pfn,
4652 unsigned long node_end_pfn,
4653 unsigned long *ignored)
4655 unsigned long zone_start_pfn, zone_end_pfn;
4657 /* Get the start and end of the zone */
4658 zone_start_pfn = arch_zone_lowest_possible_pfn[zone_type];
4659 zone_end_pfn = arch_zone_highest_possible_pfn[zone_type];
4660 adjust_zone_range_for_zone_movable(nid, zone_type,
4661 node_start_pfn, node_end_pfn,
4662 &zone_start_pfn, &zone_end_pfn);
4664 /* Check that this node has pages within the zone's required range */
4665 if (zone_end_pfn < node_start_pfn || zone_start_pfn > node_end_pfn)
4666 return 0;
4668 /* Move the zone boundaries inside the node if necessary */
4669 zone_end_pfn = min(zone_end_pfn, node_end_pfn);
4670 zone_start_pfn = max(zone_start_pfn, node_start_pfn);
4672 /* Return the spanned pages */
4673 return zone_end_pfn - zone_start_pfn;
4677 * Return the number of holes in a range on a node. If nid is MAX_NUMNODES,
4678 * then all holes in the requested range will be accounted for.
4680 unsigned long __meminit __absent_pages_in_range(int nid,
4681 unsigned long range_start_pfn,
4682 unsigned long range_end_pfn)
4684 unsigned long nr_absent = range_end_pfn - range_start_pfn;
4685 unsigned long start_pfn, end_pfn;
4686 int i;
4688 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
4689 start_pfn = clamp(start_pfn, range_start_pfn, range_end_pfn);
4690 end_pfn = clamp(end_pfn, range_start_pfn, range_end_pfn);
4691 nr_absent -= end_pfn - start_pfn;
4693 return nr_absent;
4697 * absent_pages_in_range - Return number of page frames in holes within a range
4698 * @start_pfn: The start PFN to start searching for holes
4699 * @end_pfn: The end PFN to stop searching for holes
4701 * It returns the number of pages frames in memory holes within a range.
4703 unsigned long __init absent_pages_in_range(unsigned long start_pfn,
4704 unsigned long end_pfn)
4706 return __absent_pages_in_range(MAX_NUMNODES, start_pfn, end_pfn);
4709 /* Return the number of page frames in holes in a zone on a node */
4710 static unsigned long __meminit zone_absent_pages_in_node(int nid,
4711 unsigned long zone_type,
4712 unsigned long node_start_pfn,
4713 unsigned long node_end_pfn,
4714 unsigned long *ignored)
4716 unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type];
4717 unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type];
4718 unsigned long zone_start_pfn, zone_end_pfn;
4720 zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high);
4721 zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high);
4723 adjust_zone_range_for_zone_movable(nid, zone_type,
4724 node_start_pfn, node_end_pfn,
4725 &zone_start_pfn, &zone_end_pfn);
4726 return __absent_pages_in_range(nid, zone_start_pfn, zone_end_pfn);
4729 #else /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
4730 static inline unsigned long __meminit zone_spanned_pages_in_node(int nid,
4731 unsigned long zone_type,
4732 unsigned long node_start_pfn,
4733 unsigned long node_end_pfn,
4734 unsigned long *zones_size)
4736 return zones_size[zone_type];
4739 static inline unsigned long __meminit zone_absent_pages_in_node(int nid,
4740 unsigned long zone_type,
4741 unsigned long node_start_pfn,
4742 unsigned long node_end_pfn,
4743 unsigned long *zholes_size)
4745 if (!zholes_size)
4746 return 0;
4748 return zholes_size[zone_type];
4751 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
4753 static void __meminit calculate_node_totalpages(struct pglist_data *pgdat,
4754 unsigned long node_start_pfn,
4755 unsigned long node_end_pfn,
4756 unsigned long *zones_size,
4757 unsigned long *zholes_size)
4759 unsigned long realtotalpages, totalpages = 0;
4760 enum zone_type i;
4762 for (i = 0; i < MAX_NR_ZONES; i++)
4763 totalpages += zone_spanned_pages_in_node(pgdat->node_id, i,
4764 node_start_pfn,
4765 node_end_pfn,
4766 zones_size);
4767 pgdat->node_spanned_pages = totalpages;
4769 realtotalpages = totalpages;
4770 for (i = 0; i < MAX_NR_ZONES; i++)
4771 realtotalpages -=
4772 zone_absent_pages_in_node(pgdat->node_id, i,
4773 node_start_pfn, node_end_pfn,
4774 zholes_size);
4775 pgdat->node_present_pages = realtotalpages;
4776 printk(KERN_DEBUG "On node %d totalpages: %lu\n", pgdat->node_id,
4777 realtotalpages);
4780 #ifndef CONFIG_SPARSEMEM
4782 * Calculate the size of the zone->blockflags rounded to an unsigned long
4783 * Start by making sure zonesize is a multiple of pageblock_order by rounding
4784 * up. Then use 1 NR_PAGEBLOCK_BITS worth of bits per pageblock, finally
4785 * round what is now in bits to nearest long in bits, then return it in
4786 * bytes.
4788 static unsigned long __init usemap_size(unsigned long zone_start_pfn, unsigned long zonesize)
4790 unsigned long usemapsize;
4792 zonesize += zone_start_pfn & (pageblock_nr_pages-1);
4793 usemapsize = roundup(zonesize, pageblock_nr_pages);
4794 usemapsize = usemapsize >> pageblock_order;
4795 usemapsize *= NR_PAGEBLOCK_BITS;
4796 usemapsize = roundup(usemapsize, 8 * sizeof(unsigned long));
4798 return usemapsize / 8;
4801 static void __init setup_usemap(struct pglist_data *pgdat,
4802 struct zone *zone,
4803 unsigned long zone_start_pfn,
4804 unsigned long zonesize)
4806 unsigned long usemapsize = usemap_size(zone_start_pfn, zonesize);
4807 zone->pageblock_flags = NULL;
4808 if (usemapsize)
4809 zone->pageblock_flags =
4810 memblock_virt_alloc_node_nopanic(usemapsize,
4811 pgdat->node_id);
4813 #else
4814 static inline void setup_usemap(struct pglist_data *pgdat, struct zone *zone,
4815 unsigned long zone_start_pfn, unsigned long zonesize) {}
4816 #endif /* CONFIG_SPARSEMEM */
4818 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
4820 /* Initialise the number of pages represented by NR_PAGEBLOCK_BITS */
4821 void __paginginit set_pageblock_order(void)
4823 unsigned int order;
4825 /* Check that pageblock_nr_pages has not already been setup */
4826 if (pageblock_order)
4827 return;
4829 if (HPAGE_SHIFT > PAGE_SHIFT)
4830 order = HUGETLB_PAGE_ORDER;
4831 else
4832 order = MAX_ORDER - 1;
4835 * Assume the largest contiguous order of interest is a huge page.
4836 * This value may be variable depending on boot parameters on IA64 and
4837 * powerpc.
4839 pageblock_order = order;
4841 #else /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
4844 * When CONFIG_HUGETLB_PAGE_SIZE_VARIABLE is not set, set_pageblock_order()
4845 * is unused as pageblock_order is set at compile-time. See
4846 * include/linux/pageblock-flags.h for the values of pageblock_order based on
4847 * the kernel config
4849 void __paginginit set_pageblock_order(void)
4853 #endif /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
4855 static unsigned long __paginginit calc_memmap_size(unsigned long spanned_pages,
4856 unsigned long present_pages)
4858 unsigned long pages = spanned_pages;
4861 * Provide a more accurate estimation if there are holes within
4862 * the zone and SPARSEMEM is in use. If there are holes within the
4863 * zone, each populated memory region may cost us one or two extra
4864 * memmap pages due to alignment because memmap pages for each
4865 * populated regions may not naturally algined on page boundary.
4866 * So the (present_pages >> 4) heuristic is a tradeoff for that.
4868 if (spanned_pages > present_pages + (present_pages >> 4) &&
4869 IS_ENABLED(CONFIG_SPARSEMEM))
4870 pages = present_pages;
4872 return PAGE_ALIGN(pages * sizeof(struct page)) >> PAGE_SHIFT;
4876 * Set up the zone data structures:
4877 * - mark all pages reserved
4878 * - mark all memory queues empty
4879 * - clear the memory bitmaps
4881 * NOTE: pgdat should get zeroed by caller.
4883 static void __paginginit free_area_init_core(struct pglist_data *pgdat,
4884 unsigned long node_start_pfn, unsigned long node_end_pfn,
4885 unsigned long *zones_size, unsigned long *zholes_size)
4887 enum zone_type j;
4888 int nid = pgdat->node_id;
4889 unsigned long zone_start_pfn = pgdat->node_start_pfn;
4890 int ret;
4892 pgdat_resize_init(pgdat);
4893 #ifdef CONFIG_NUMA_BALANCING
4894 spin_lock_init(&pgdat->numabalancing_migrate_lock);
4895 pgdat->numabalancing_migrate_nr_pages = 0;
4896 pgdat->numabalancing_migrate_next_window = jiffies;
4897 #endif
4898 init_waitqueue_head(&pgdat->kswapd_wait);
4899 init_waitqueue_head(&pgdat->pfmemalloc_wait);
4900 pgdat_page_cgroup_init(pgdat);
4902 for (j = 0; j < MAX_NR_ZONES; j++) {
4903 struct zone *zone = pgdat->node_zones + j;
4904 unsigned long size, realsize, freesize, memmap_pages;
4906 size = zone_spanned_pages_in_node(nid, j, node_start_pfn,
4907 node_end_pfn, zones_size);
4908 realsize = freesize = size - zone_absent_pages_in_node(nid, j,
4909 node_start_pfn,
4910 node_end_pfn,
4911 zholes_size);
4914 * Adjust freesize so that it accounts for how much memory
4915 * is used by this zone for memmap. This affects the watermark
4916 * and per-cpu initialisations
4918 memmap_pages = calc_memmap_size(size, realsize);
4919 if (freesize >= memmap_pages) {
4920 freesize -= memmap_pages;
4921 if (memmap_pages)
4922 printk(KERN_DEBUG
4923 " %s zone: %lu pages used for memmap\n",
4924 zone_names[j], memmap_pages);
4925 } else
4926 printk(KERN_WARNING
4927 " %s zone: %lu pages exceeds freesize %lu\n",
4928 zone_names[j], memmap_pages, freesize);
4930 /* Account for reserved pages */
4931 if (j == 0 && freesize > dma_reserve) {
4932 freesize -= dma_reserve;
4933 printk(KERN_DEBUG " %s zone: %lu pages reserved\n",
4934 zone_names[0], dma_reserve);
4937 if (!is_highmem_idx(j))
4938 nr_kernel_pages += freesize;
4939 /* Charge for highmem memmap if there are enough kernel pages */
4940 else if (nr_kernel_pages > memmap_pages * 2)
4941 nr_kernel_pages -= memmap_pages;
4942 nr_all_pages += freesize;
4944 zone->spanned_pages = size;
4945 zone->present_pages = realsize;
4947 * Set an approximate value for lowmem here, it will be adjusted
4948 * when the bootmem allocator frees pages into the buddy system.
4949 * And all highmem pages will be managed by the buddy system.
4951 zone->managed_pages = is_highmem_idx(j) ? realsize : freesize;
4952 #ifdef CONFIG_NUMA
4953 zone->node = nid;
4954 zone->min_unmapped_pages = (freesize*sysctl_min_unmapped_ratio)
4955 / 100;
4956 zone->min_slab_pages = (freesize * sysctl_min_slab_ratio) / 100;
4957 #endif
4958 zone->name = zone_names[j];
4959 spin_lock_init(&zone->lock);
4960 spin_lock_init(&zone->lru_lock);
4961 zone_seqlock_init(zone);
4962 zone->zone_pgdat = pgdat;
4963 zone_pcp_init(zone);
4965 /* For bootup, initialized properly in watermark setup */
4966 mod_zone_page_state(zone, NR_ALLOC_BATCH, zone->managed_pages);
4968 lruvec_init(&zone->lruvec);
4969 if (!size)
4970 continue;
4972 set_pageblock_order();
4973 setup_usemap(pgdat, zone, zone_start_pfn, size);
4974 ret = init_currently_empty_zone(zone, zone_start_pfn,
4975 size, MEMMAP_EARLY);
4976 BUG_ON(ret);
4977 memmap_init(size, nid, j, zone_start_pfn);
4978 zone_start_pfn += size;
4982 static void __init_refok alloc_node_mem_map(struct pglist_data *pgdat)
4984 /* Skip empty nodes */
4985 if (!pgdat->node_spanned_pages)
4986 return;
4988 #ifdef CONFIG_FLAT_NODE_MEM_MAP
4989 /* ia64 gets its own node_mem_map, before this, without bootmem */
4990 if (!pgdat->node_mem_map) {
4991 unsigned long size, start, end;
4992 struct page *map;
4995 * The zone's endpoints aren't required to be MAX_ORDER
4996 * aligned but the node_mem_map endpoints must be in order
4997 * for the buddy allocator to function correctly.
4999 start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1);
5000 end = pgdat_end_pfn(pgdat);
5001 end = ALIGN(end, MAX_ORDER_NR_PAGES);
5002 size = (end - start) * sizeof(struct page);
5003 map = alloc_remap(pgdat->node_id, size);
5004 if (!map)
5005 map = memblock_virt_alloc_node_nopanic(size,
5006 pgdat->node_id);
5007 pgdat->node_mem_map = map + (pgdat->node_start_pfn - start);
5009 #ifndef CONFIG_NEED_MULTIPLE_NODES
5011 * With no DISCONTIG, the global mem_map is just set as node 0's
5013 if (pgdat == NODE_DATA(0)) {
5014 mem_map = NODE_DATA(0)->node_mem_map;
5015 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
5016 if (page_to_pfn(mem_map) != pgdat->node_start_pfn)
5017 mem_map -= (pgdat->node_start_pfn - ARCH_PFN_OFFSET);
5018 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
5020 #endif
5021 #endif /* CONFIG_FLAT_NODE_MEM_MAP */
5024 void __paginginit free_area_init_node(int nid, unsigned long *zones_size,
5025 unsigned long node_start_pfn, unsigned long *zholes_size)
5027 pg_data_t *pgdat = NODE_DATA(nid);
5028 unsigned long start_pfn = 0;
5029 unsigned long end_pfn = 0;
5031 /* pg_data_t should be reset to zero when it's allocated */
5032 WARN_ON(pgdat->nr_zones || pgdat->classzone_idx);
5034 pgdat->node_id = nid;
5035 pgdat->node_start_pfn = node_start_pfn;
5036 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
5037 get_pfn_range_for_nid(nid, &start_pfn, &end_pfn);
5038 #endif
5039 calculate_node_totalpages(pgdat, start_pfn, end_pfn,
5040 zones_size, zholes_size);
5042 alloc_node_mem_map(pgdat);
5043 #ifdef CONFIG_FLAT_NODE_MEM_MAP
5044 printk(KERN_DEBUG "free_area_init_node: node %d, pgdat %08lx, node_mem_map %08lx\n",
5045 nid, (unsigned long)pgdat,
5046 (unsigned long)pgdat->node_mem_map);
5047 #endif
5049 free_area_init_core(pgdat, start_pfn, end_pfn,
5050 zones_size, zholes_size);
5053 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
5055 #if MAX_NUMNODES > 1
5057 * Figure out the number of possible node ids.
5059 void __init setup_nr_node_ids(void)
5061 unsigned int node;
5062 unsigned int highest = 0;
5064 for_each_node_mask(node, node_possible_map)
5065 highest = node;
5066 nr_node_ids = highest + 1;
5068 #endif
5071 * node_map_pfn_alignment - determine the maximum internode alignment
5073 * This function should be called after node map is populated and sorted.
5074 * It calculates the maximum power of two alignment which can distinguish
5075 * all the nodes.
5077 * For example, if all nodes are 1GiB and aligned to 1GiB, the return value
5078 * would indicate 1GiB alignment with (1 << (30 - PAGE_SHIFT)). If the
5079 * nodes are shifted by 256MiB, 256MiB. Note that if only the last node is
5080 * shifted, 1GiB is enough and this function will indicate so.
5082 * This is used to test whether pfn -> nid mapping of the chosen memory
5083 * model has fine enough granularity to avoid incorrect mapping for the
5084 * populated node map.
5086 * Returns the determined alignment in pfn's. 0 if there is no alignment
5087 * requirement (single node).
5089 unsigned long __init node_map_pfn_alignment(void)
5091 unsigned long accl_mask = 0, last_end = 0;
5092 unsigned long start, end, mask;
5093 int last_nid = -1;
5094 int i, nid;
5096 for_each_mem_pfn_range(i, MAX_NUMNODES, &start, &end, &nid) {
5097 if (!start || last_nid < 0 || last_nid == nid) {
5098 last_nid = nid;
5099 last_end = end;
5100 continue;
5104 * Start with a mask granular enough to pin-point to the
5105 * start pfn and tick off bits one-by-one until it becomes
5106 * too coarse to separate the current node from the last.
5108 mask = ~((1 << __ffs(start)) - 1);
5109 while (mask && last_end <= (start & (mask << 1)))
5110 mask <<= 1;
5112 /* accumulate all internode masks */
5113 accl_mask |= mask;
5116 /* convert mask to number of pages */
5117 return ~accl_mask + 1;
5120 /* Find the lowest pfn for a node */
5121 static unsigned long __init find_min_pfn_for_node(int nid)
5123 unsigned long min_pfn = ULONG_MAX;
5124 unsigned long start_pfn;
5125 int i;
5127 for_each_mem_pfn_range(i, nid, &start_pfn, NULL, NULL)
5128 min_pfn = min(min_pfn, start_pfn);
5130 if (min_pfn == ULONG_MAX) {
5131 printk(KERN_WARNING
5132 "Could not find start_pfn for node %d\n", nid);
5133 return 0;
5136 return min_pfn;
5140 * find_min_pfn_with_active_regions - Find the minimum PFN registered
5142 * It returns the minimum PFN based on information provided via
5143 * memblock_set_node().
5145 unsigned long __init find_min_pfn_with_active_regions(void)
5147 return find_min_pfn_for_node(MAX_NUMNODES);
5151 * early_calculate_totalpages()
5152 * Sum pages in active regions for movable zone.
5153 * Populate N_MEMORY for calculating usable_nodes.
5155 static unsigned long __init early_calculate_totalpages(void)
5157 unsigned long totalpages = 0;
5158 unsigned long start_pfn, end_pfn;
5159 int i, nid;
5161 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
5162 unsigned long pages = end_pfn - start_pfn;
5164 totalpages += pages;
5165 if (pages)
5166 node_set_state(nid, N_MEMORY);
5168 return totalpages;
5172 * Find the PFN the Movable zone begins in each node. Kernel memory
5173 * is spread evenly between nodes as long as the nodes have enough
5174 * memory. When they don't, some nodes will have more kernelcore than
5175 * others
5177 static void __init find_zone_movable_pfns_for_nodes(void)
5179 int i, nid;
5180 unsigned long usable_startpfn;
5181 unsigned long kernelcore_node, kernelcore_remaining;
5182 /* save the state before borrow the nodemask */
5183 nodemask_t saved_node_state = node_states[N_MEMORY];
5184 unsigned long totalpages = early_calculate_totalpages();
5185 int usable_nodes = nodes_weight(node_states[N_MEMORY]);
5186 struct memblock_region *r;
5188 /* Need to find movable_zone earlier when movable_node is specified. */
5189 find_usable_zone_for_movable();
5192 * If movable_node is specified, ignore kernelcore and movablecore
5193 * options.
5195 if (movable_node_is_enabled()) {
5196 for_each_memblock(memory, r) {
5197 if (!memblock_is_hotpluggable(r))
5198 continue;
5200 nid = r->nid;
5202 usable_startpfn = PFN_DOWN(r->base);
5203 zone_movable_pfn[nid] = zone_movable_pfn[nid] ?
5204 min(usable_startpfn, zone_movable_pfn[nid]) :
5205 usable_startpfn;
5208 goto out2;
5212 * If movablecore=nn[KMG] was specified, calculate what size of
5213 * kernelcore that corresponds so that memory usable for
5214 * any allocation type is evenly spread. If both kernelcore
5215 * and movablecore are specified, then the value of kernelcore
5216 * will be used for required_kernelcore if it's greater than
5217 * what movablecore would have allowed.
5219 if (required_movablecore) {
5220 unsigned long corepages;
5223 * Round-up so that ZONE_MOVABLE is at least as large as what
5224 * was requested by the user
5226 required_movablecore =
5227 roundup(required_movablecore, MAX_ORDER_NR_PAGES);
5228 corepages = totalpages - required_movablecore;
5230 required_kernelcore = max(required_kernelcore, corepages);
5233 /* If kernelcore was not specified, there is no ZONE_MOVABLE */
5234 if (!required_kernelcore)
5235 goto out;
5237 /* usable_startpfn is the lowest possible pfn ZONE_MOVABLE can be at */
5238 usable_startpfn = arch_zone_lowest_possible_pfn[movable_zone];
5240 restart:
5241 /* Spread kernelcore memory as evenly as possible throughout nodes */
5242 kernelcore_node = required_kernelcore / usable_nodes;
5243 for_each_node_state(nid, N_MEMORY) {
5244 unsigned long start_pfn, end_pfn;
5247 * Recalculate kernelcore_node if the division per node
5248 * now exceeds what is necessary to satisfy the requested
5249 * amount of memory for the kernel
5251 if (required_kernelcore < kernelcore_node)
5252 kernelcore_node = required_kernelcore / usable_nodes;
5255 * As the map is walked, we track how much memory is usable
5256 * by the kernel using kernelcore_remaining. When it is
5257 * 0, the rest of the node is usable by ZONE_MOVABLE
5259 kernelcore_remaining = kernelcore_node;
5261 /* Go through each range of PFNs within this node */
5262 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
5263 unsigned long size_pages;
5265 start_pfn = max(start_pfn, zone_movable_pfn[nid]);
5266 if (start_pfn >= end_pfn)
5267 continue;
5269 /* Account for what is only usable for kernelcore */
5270 if (start_pfn < usable_startpfn) {
5271 unsigned long kernel_pages;
5272 kernel_pages = min(end_pfn, usable_startpfn)
5273 - start_pfn;
5275 kernelcore_remaining -= min(kernel_pages,
5276 kernelcore_remaining);
5277 required_kernelcore -= min(kernel_pages,
5278 required_kernelcore);
5280 /* Continue if range is now fully accounted */
5281 if (end_pfn <= usable_startpfn) {
5284 * Push zone_movable_pfn to the end so
5285 * that if we have to rebalance
5286 * kernelcore across nodes, we will
5287 * not double account here
5289 zone_movable_pfn[nid] = end_pfn;
5290 continue;
5292 start_pfn = usable_startpfn;
5296 * The usable PFN range for ZONE_MOVABLE is from
5297 * start_pfn->end_pfn. Calculate size_pages as the
5298 * number of pages used as kernelcore
5300 size_pages = end_pfn - start_pfn;
5301 if (size_pages > kernelcore_remaining)
5302 size_pages = kernelcore_remaining;
5303 zone_movable_pfn[nid] = start_pfn + size_pages;
5306 * Some kernelcore has been met, update counts and
5307 * break if the kernelcore for this node has been
5308 * satisfied
5310 required_kernelcore -= min(required_kernelcore,
5311 size_pages);
5312 kernelcore_remaining -= size_pages;
5313 if (!kernelcore_remaining)
5314 break;
5319 * If there is still required_kernelcore, we do another pass with one
5320 * less node in the count. This will push zone_movable_pfn[nid] further
5321 * along on the nodes that still have memory until kernelcore is
5322 * satisfied
5324 usable_nodes--;
5325 if (usable_nodes && required_kernelcore > usable_nodes)
5326 goto restart;
5328 out2:
5329 /* Align start of ZONE_MOVABLE on all nids to MAX_ORDER_NR_PAGES */
5330 for (nid = 0; nid < MAX_NUMNODES; nid++)
5331 zone_movable_pfn[nid] =
5332 roundup(zone_movable_pfn[nid], MAX_ORDER_NR_PAGES);
5334 out:
5335 /* restore the node_state */
5336 node_states[N_MEMORY] = saved_node_state;
5339 /* Any regular or high memory on that node ? */
5340 static void check_for_memory(pg_data_t *pgdat, int nid)
5342 enum zone_type zone_type;
5344 if (N_MEMORY == N_NORMAL_MEMORY)
5345 return;
5347 for (zone_type = 0; zone_type <= ZONE_MOVABLE - 1; zone_type++) {
5348 struct zone *zone = &pgdat->node_zones[zone_type];
5349 if (populated_zone(zone)) {
5350 node_set_state(nid, N_HIGH_MEMORY);
5351 if (N_NORMAL_MEMORY != N_HIGH_MEMORY &&
5352 zone_type <= ZONE_NORMAL)
5353 node_set_state(nid, N_NORMAL_MEMORY);
5354 break;
5360 * free_area_init_nodes - Initialise all pg_data_t and zone data
5361 * @max_zone_pfn: an array of max PFNs for each zone
5363 * This will call free_area_init_node() for each active node in the system.
5364 * Using the page ranges provided by memblock_set_node(), the size of each
5365 * zone in each node and their holes is calculated. If the maximum PFN
5366 * between two adjacent zones match, it is assumed that the zone is empty.
5367 * For example, if arch_max_dma_pfn == arch_max_dma32_pfn, it is assumed
5368 * that arch_max_dma32_pfn has no pages. It is also assumed that a zone
5369 * starts where the previous one ended. For example, ZONE_DMA32 starts
5370 * at arch_max_dma_pfn.
5372 void __init free_area_init_nodes(unsigned long *max_zone_pfn)
5374 unsigned long start_pfn, end_pfn;
5375 int i, nid;
5377 /* Record where the zone boundaries are */
5378 memset(arch_zone_lowest_possible_pfn, 0,
5379 sizeof(arch_zone_lowest_possible_pfn));
5380 memset(arch_zone_highest_possible_pfn, 0,
5381 sizeof(arch_zone_highest_possible_pfn));
5383 start_pfn = find_min_pfn_with_active_regions();
5385 for (i = 0; i < MAX_NR_ZONES; i++) {
5386 if (i == ZONE_MOVABLE)
5387 continue;
5389 end_pfn = max(max_zone_pfn[i], start_pfn);
5390 arch_zone_lowest_possible_pfn[i] = start_pfn;
5391 arch_zone_highest_possible_pfn[i] = end_pfn;
5393 start_pfn = end_pfn;
5395 arch_zone_lowest_possible_pfn[ZONE_MOVABLE] = 0;
5396 arch_zone_highest_possible_pfn[ZONE_MOVABLE] = 0;
5398 /* Find the PFNs that ZONE_MOVABLE begins at in each node */
5399 memset(zone_movable_pfn, 0, sizeof(zone_movable_pfn));
5400 find_zone_movable_pfns_for_nodes();
5402 /* Print out the zone ranges */
5403 printk("Zone ranges:\n");
5404 for (i = 0; i < MAX_NR_ZONES; i++) {
5405 if (i == ZONE_MOVABLE)
5406 continue;
5407 printk(KERN_CONT " %-8s ", zone_names[i]);
5408 if (arch_zone_lowest_possible_pfn[i] ==
5409 arch_zone_highest_possible_pfn[i])
5410 printk(KERN_CONT "empty\n");
5411 else
5412 printk(KERN_CONT "[mem %0#10lx-%0#10lx]\n",
5413 arch_zone_lowest_possible_pfn[i] << PAGE_SHIFT,
5414 (arch_zone_highest_possible_pfn[i]
5415 << PAGE_SHIFT) - 1);
5418 /* Print out the PFNs ZONE_MOVABLE begins at in each node */
5419 printk("Movable zone start for each node\n");
5420 for (i = 0; i < MAX_NUMNODES; i++) {
5421 if (zone_movable_pfn[i])
5422 printk(" Node %d: %#010lx\n", i,
5423 zone_movable_pfn[i] << PAGE_SHIFT);
5426 /* Print out the early node map */
5427 printk("Early memory node ranges\n");
5428 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid)
5429 printk(" node %3d: [mem %#010lx-%#010lx]\n", nid,
5430 start_pfn << PAGE_SHIFT, (end_pfn << PAGE_SHIFT) - 1);
5432 /* Initialise every node */
5433 mminit_verify_pageflags_layout();
5434 setup_nr_node_ids();
5435 for_each_online_node(nid) {
5436 pg_data_t *pgdat = NODE_DATA(nid);
5437 free_area_init_node(nid, NULL,
5438 find_min_pfn_for_node(nid), NULL);
5440 /* Any memory on that node */
5441 if (pgdat->node_present_pages)
5442 node_set_state(nid, N_MEMORY);
5443 check_for_memory(pgdat, nid);
5447 static int __init cmdline_parse_core(char *p, unsigned long *core)
5449 unsigned long long coremem;
5450 if (!p)
5451 return -EINVAL;
5453 coremem = memparse(p, &p);
5454 *core = coremem >> PAGE_SHIFT;
5456 /* Paranoid check that UL is enough for the coremem value */
5457 WARN_ON((coremem >> PAGE_SHIFT) > ULONG_MAX);
5459 return 0;
5463 * kernelcore=size sets the amount of memory for use for allocations that
5464 * cannot be reclaimed or migrated.
5466 static int __init cmdline_parse_kernelcore(char *p)
5468 return cmdline_parse_core(p, &required_kernelcore);
5472 * movablecore=size sets the amount of memory for use for allocations that
5473 * can be reclaimed or migrated.
5475 static int __init cmdline_parse_movablecore(char *p)
5477 return cmdline_parse_core(p, &required_movablecore);
5480 early_param("kernelcore", cmdline_parse_kernelcore);
5481 early_param("movablecore", cmdline_parse_movablecore);
5483 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
5485 void adjust_managed_page_count(struct page *page, long count)
5487 spin_lock(&managed_page_count_lock);
5488 page_zone(page)->managed_pages += count;
5489 totalram_pages += count;
5490 #ifdef CONFIG_HIGHMEM
5491 if (PageHighMem(page))
5492 totalhigh_pages += count;
5493 #endif
5494 spin_unlock(&managed_page_count_lock);
5496 EXPORT_SYMBOL(adjust_managed_page_count);
5498 unsigned long free_reserved_area(void *start, void *end, int poison, char *s)
5500 void *pos;
5501 unsigned long pages = 0;
5503 start = (void *)PAGE_ALIGN((unsigned long)start);
5504 end = (void *)((unsigned long)end & PAGE_MASK);
5505 for (pos = start; pos < end; pos += PAGE_SIZE, pages++) {
5506 if ((unsigned int)poison <= 0xFF)
5507 memset(pos, poison, PAGE_SIZE);
5508 free_reserved_page(virt_to_page(pos));
5511 if (pages && s)
5512 pr_info("Freeing %s memory: %ldK (%p - %p)\n",
5513 s, pages << (PAGE_SHIFT - 10), start, end);
5515 return pages;
5517 EXPORT_SYMBOL(free_reserved_area);
5519 #ifdef CONFIG_HIGHMEM
5520 void free_highmem_page(struct page *page)
5522 __free_reserved_page(page);
5523 totalram_pages++;
5524 page_zone(page)->managed_pages++;
5525 totalhigh_pages++;
5527 #endif
5530 void __init mem_init_print_info(const char *str)
5532 unsigned long physpages, codesize, datasize, rosize, bss_size;
5533 unsigned long init_code_size, init_data_size;
5535 physpages = get_num_physpages();
5536 codesize = _etext - _stext;
5537 datasize = _edata - _sdata;
5538 rosize = __end_rodata - __start_rodata;
5539 bss_size = __bss_stop - __bss_start;
5540 init_data_size = __init_end - __init_begin;
5541 init_code_size = _einittext - _sinittext;
5544 * Detect special cases and adjust section sizes accordingly:
5545 * 1) .init.* may be embedded into .data sections
5546 * 2) .init.text.* may be out of [__init_begin, __init_end],
5547 * please refer to arch/tile/kernel/vmlinux.lds.S.
5548 * 3) .rodata.* may be embedded into .text or .data sections.
5550 #define adj_init_size(start, end, size, pos, adj) \
5551 do { \
5552 if (start <= pos && pos < end && size > adj) \
5553 size -= adj; \
5554 } while (0)
5556 adj_init_size(__init_begin, __init_end, init_data_size,
5557 _sinittext, init_code_size);
5558 adj_init_size(_stext, _etext, codesize, _sinittext, init_code_size);
5559 adj_init_size(_sdata, _edata, datasize, __init_begin, init_data_size);
5560 adj_init_size(_stext, _etext, codesize, __start_rodata, rosize);
5561 adj_init_size(_sdata, _edata, datasize, __start_rodata, rosize);
5563 #undef adj_init_size
5565 printk("Memory: %luK/%luK available "
5566 "(%luK kernel code, %luK rwdata, %luK rodata, "
5567 "%luK init, %luK bss, %luK reserved"
5568 #ifdef CONFIG_HIGHMEM
5569 ", %luK highmem"
5570 #endif
5571 "%s%s)\n",
5572 nr_free_pages() << (PAGE_SHIFT-10), physpages << (PAGE_SHIFT-10),
5573 codesize >> 10, datasize >> 10, rosize >> 10,
5574 (init_data_size + init_code_size) >> 10, bss_size >> 10,
5575 (physpages - totalram_pages) << (PAGE_SHIFT-10),
5576 #ifdef CONFIG_HIGHMEM
5577 totalhigh_pages << (PAGE_SHIFT-10),
5578 #endif
5579 str ? ", " : "", str ? str : "");
5583 * set_dma_reserve - set the specified number of pages reserved in the first zone
5584 * @new_dma_reserve: The number of pages to mark reserved
5586 * The per-cpu batchsize and zone watermarks are determined by present_pages.
5587 * In the DMA zone, a significant percentage may be consumed by kernel image
5588 * and other unfreeable allocations which can skew the watermarks badly. This
5589 * function may optionally be used to account for unfreeable pages in the
5590 * first zone (e.g., ZONE_DMA). The effect will be lower watermarks and
5591 * smaller per-cpu batchsize.
5593 void __init set_dma_reserve(unsigned long new_dma_reserve)
5595 dma_reserve = new_dma_reserve;
5598 void __init free_area_init(unsigned long *zones_size)
5600 free_area_init_node(0, zones_size,
5601 __pa(PAGE_OFFSET) >> PAGE_SHIFT, NULL);
5604 static int page_alloc_cpu_notify(struct notifier_block *self,
5605 unsigned long action, void *hcpu)
5607 int cpu = (unsigned long)hcpu;
5609 if (action == CPU_DEAD || action == CPU_DEAD_FROZEN) {
5610 lru_add_drain_cpu(cpu);
5611 drain_pages(cpu);
5614 * Spill the event counters of the dead processor
5615 * into the current processors event counters.
5616 * This artificially elevates the count of the current
5617 * processor.
5619 vm_events_fold_cpu(cpu);
5622 * Zero the differential counters of the dead processor
5623 * so that the vm statistics are consistent.
5625 * This is only okay since the processor is dead and cannot
5626 * race with what we are doing.
5628 cpu_vm_stats_fold(cpu);
5630 return NOTIFY_OK;
5633 void __init page_alloc_init(void)
5635 hotcpu_notifier(page_alloc_cpu_notify, 0);
5639 * calculate_totalreserve_pages - called when sysctl_lower_zone_reserve_ratio
5640 * or min_free_kbytes changes.
5642 static void calculate_totalreserve_pages(void)
5644 struct pglist_data *pgdat;
5645 unsigned long reserve_pages = 0;
5646 enum zone_type i, j;
5648 for_each_online_pgdat(pgdat) {
5649 for (i = 0; i < MAX_NR_ZONES; i++) {
5650 struct zone *zone = pgdat->node_zones + i;
5651 unsigned long max = 0;
5653 /* Find valid and maximum lowmem_reserve in the zone */
5654 for (j = i; j < MAX_NR_ZONES; j++) {
5655 if (zone->lowmem_reserve[j] > max)
5656 max = zone->lowmem_reserve[j];
5659 /* we treat the high watermark as reserved pages. */
5660 max += high_wmark_pages(zone);
5662 if (max > zone->managed_pages)
5663 max = zone->managed_pages;
5664 reserve_pages += max;
5666 * Lowmem reserves are not available to
5667 * GFP_HIGHUSER page cache allocations and
5668 * kswapd tries to balance zones to their high
5669 * watermark. As a result, neither should be
5670 * regarded as dirtyable memory, to prevent a
5671 * situation where reclaim has to clean pages
5672 * in order to balance the zones.
5674 zone->dirty_balance_reserve = max;
5677 dirty_balance_reserve = reserve_pages;
5678 totalreserve_pages = reserve_pages;
5682 * setup_per_zone_lowmem_reserve - called whenever
5683 * sysctl_lower_zone_reserve_ratio changes. Ensures that each zone
5684 * has a correct pages reserved value, so an adequate number of
5685 * pages are left in the zone after a successful __alloc_pages().
5687 static void setup_per_zone_lowmem_reserve(void)
5689 struct pglist_data *pgdat;
5690 enum zone_type j, idx;
5692 for_each_online_pgdat(pgdat) {
5693 for (j = 0; j < MAX_NR_ZONES; j++) {
5694 struct zone *zone = pgdat->node_zones + j;
5695 unsigned long managed_pages = zone->managed_pages;
5697 zone->lowmem_reserve[j] = 0;
5699 idx = j;
5700 while (idx) {
5701 struct zone *lower_zone;
5703 idx--;
5705 if (sysctl_lowmem_reserve_ratio[idx] < 1)
5706 sysctl_lowmem_reserve_ratio[idx] = 1;
5708 lower_zone = pgdat->node_zones + idx;
5709 lower_zone->lowmem_reserve[j] = managed_pages /
5710 sysctl_lowmem_reserve_ratio[idx];
5711 managed_pages += lower_zone->managed_pages;
5716 /* update totalreserve_pages */
5717 calculate_totalreserve_pages();
5720 static void __setup_per_zone_wmarks(void)
5722 unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
5723 unsigned long lowmem_pages = 0;
5724 struct zone *zone;
5725 unsigned long flags;
5727 /* Calculate total number of !ZONE_HIGHMEM pages */
5728 for_each_zone(zone) {
5729 if (!is_highmem(zone))
5730 lowmem_pages += zone->managed_pages;
5733 for_each_zone(zone) {
5734 u64 tmp;
5736 spin_lock_irqsave(&zone->lock, flags);
5737 tmp = (u64)pages_min * zone->managed_pages;
5738 do_div(tmp, lowmem_pages);
5739 if (is_highmem(zone)) {
5741 * __GFP_HIGH and PF_MEMALLOC allocations usually don't
5742 * need highmem pages, so cap pages_min to a small
5743 * value here.
5745 * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN)
5746 * deltas controls asynch page reclaim, and so should
5747 * not be capped for highmem.
5749 unsigned long min_pages;
5751 min_pages = zone->managed_pages / 1024;
5752 min_pages = clamp(min_pages, SWAP_CLUSTER_MAX, 128UL);
5753 zone->watermark[WMARK_MIN] = min_pages;
5754 } else {
5756 * If it's a lowmem zone, reserve a number of pages
5757 * proportionate to the zone's size.
5759 zone->watermark[WMARK_MIN] = tmp;
5762 zone->watermark[WMARK_LOW] = min_wmark_pages(zone) + (tmp >> 2);
5763 zone->watermark[WMARK_HIGH] = min_wmark_pages(zone) + (tmp >> 1);
5765 __mod_zone_page_state(zone, NR_ALLOC_BATCH,
5766 high_wmark_pages(zone) - low_wmark_pages(zone) -
5767 atomic_long_read(&zone->vm_stat[NR_ALLOC_BATCH]));
5769 setup_zone_migrate_reserve(zone);
5770 spin_unlock_irqrestore(&zone->lock, flags);
5773 /* update totalreserve_pages */
5774 calculate_totalreserve_pages();
5778 * setup_per_zone_wmarks - called when min_free_kbytes changes
5779 * or when memory is hot-{added|removed}
5781 * Ensures that the watermark[min,low,high] values for each zone are set
5782 * correctly with respect to min_free_kbytes.
5784 void setup_per_zone_wmarks(void)
5786 mutex_lock(&zonelists_mutex);
5787 __setup_per_zone_wmarks();
5788 mutex_unlock(&zonelists_mutex);
5792 * The inactive anon list should be small enough that the VM never has to
5793 * do too much work, but large enough that each inactive page has a chance
5794 * to be referenced again before it is swapped out.
5796 * The inactive_anon ratio is the target ratio of ACTIVE_ANON to
5797 * INACTIVE_ANON pages on this zone's LRU, maintained by the
5798 * pageout code. A zone->inactive_ratio of 3 means 3:1 or 25% of
5799 * the anonymous pages are kept on the inactive list.
5801 * total target max
5802 * memory ratio inactive anon
5803 * -------------------------------------
5804 * 10MB 1 5MB
5805 * 100MB 1 50MB
5806 * 1GB 3 250MB
5807 * 10GB 10 0.9GB
5808 * 100GB 31 3GB
5809 * 1TB 101 10GB
5810 * 10TB 320 32GB
5812 static void __meminit calculate_zone_inactive_ratio(struct zone *zone)
5814 unsigned int gb, ratio;
5816 /* Zone size in gigabytes */
5817 gb = zone->managed_pages >> (30 - PAGE_SHIFT);
5818 if (gb)
5819 ratio = int_sqrt(10 * gb);
5820 else
5821 ratio = 1;
5823 zone->inactive_ratio = ratio;
5826 static void __meminit setup_per_zone_inactive_ratio(void)
5828 struct zone *zone;
5830 for_each_zone(zone)
5831 calculate_zone_inactive_ratio(zone);
5835 * Initialise min_free_kbytes.
5837 * For small machines we want it small (128k min). For large machines
5838 * we want it large (64MB max). But it is not linear, because network
5839 * bandwidth does not increase linearly with machine size. We use
5841 * min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
5842 * min_free_kbytes = sqrt(lowmem_kbytes * 16)
5844 * which yields
5846 * 16MB: 512k
5847 * 32MB: 724k
5848 * 64MB: 1024k
5849 * 128MB: 1448k
5850 * 256MB: 2048k
5851 * 512MB: 2896k
5852 * 1024MB: 4096k
5853 * 2048MB: 5792k
5854 * 4096MB: 8192k
5855 * 8192MB: 11584k
5856 * 16384MB: 16384k
5858 int __meminit init_per_zone_wmark_min(void)
5860 unsigned long lowmem_kbytes;
5861 int new_min_free_kbytes;
5863 lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
5864 new_min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
5866 if (new_min_free_kbytes > user_min_free_kbytes) {
5867 min_free_kbytes = new_min_free_kbytes;
5868 if (min_free_kbytes < 128)
5869 min_free_kbytes = 128;
5870 if (min_free_kbytes > 65536)
5871 min_free_kbytes = 65536;
5872 } else {
5873 pr_warn("min_free_kbytes is not updated to %d because user defined value %d is preferred\n",
5874 new_min_free_kbytes, user_min_free_kbytes);
5876 setup_per_zone_wmarks();
5877 refresh_zone_stat_thresholds();
5878 setup_per_zone_lowmem_reserve();
5879 setup_per_zone_inactive_ratio();
5880 return 0;
5882 module_init(init_per_zone_wmark_min)
5885 * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
5886 * that we can call two helper functions whenever min_free_kbytes
5887 * changes.
5889 int min_free_kbytes_sysctl_handler(struct ctl_table *table, int write,
5890 void __user *buffer, size_t *length, loff_t *ppos)
5892 int rc;
5894 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
5895 if (rc)
5896 return rc;
5898 if (write) {
5899 user_min_free_kbytes = min_free_kbytes;
5900 setup_per_zone_wmarks();
5902 return 0;
5905 #ifdef CONFIG_NUMA
5906 int sysctl_min_unmapped_ratio_sysctl_handler(struct ctl_table *table, int write,
5907 void __user *buffer, size_t *length, loff_t *ppos)
5909 struct zone *zone;
5910 int rc;
5912 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
5913 if (rc)
5914 return rc;
5916 for_each_zone(zone)
5917 zone->min_unmapped_pages = (zone->managed_pages *
5918 sysctl_min_unmapped_ratio) / 100;
5919 return 0;
5922 int sysctl_min_slab_ratio_sysctl_handler(struct ctl_table *table, int write,
5923 void __user *buffer, size_t *length, loff_t *ppos)
5925 struct zone *zone;
5926 int rc;
5928 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
5929 if (rc)
5930 return rc;
5932 for_each_zone(zone)
5933 zone->min_slab_pages = (zone->managed_pages *
5934 sysctl_min_slab_ratio) / 100;
5935 return 0;
5937 #endif
5940 * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
5941 * proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
5942 * whenever sysctl_lowmem_reserve_ratio changes.
5944 * The reserve ratio obviously has absolutely no relation with the
5945 * minimum watermarks. The lowmem reserve ratio can only make sense
5946 * if in function of the boot time zone sizes.
5948 int lowmem_reserve_ratio_sysctl_handler(struct ctl_table *table, int write,
5949 void __user *buffer, size_t *length, loff_t *ppos)
5951 proc_dointvec_minmax(table, write, buffer, length, ppos);
5952 setup_per_zone_lowmem_reserve();
5953 return 0;
5957 * percpu_pagelist_fraction - changes the pcp->high for each zone on each
5958 * cpu. It is the fraction of total pages in each zone that a hot per cpu
5959 * pagelist can have before it gets flushed back to buddy allocator.
5961 int percpu_pagelist_fraction_sysctl_handler(struct ctl_table *table, int write,
5962 void __user *buffer, size_t *length, loff_t *ppos)
5964 struct zone *zone;
5965 int old_percpu_pagelist_fraction;
5966 int ret;
5968 mutex_lock(&pcp_batch_high_lock);
5969 old_percpu_pagelist_fraction = percpu_pagelist_fraction;
5971 ret = proc_dointvec_minmax(table, write, buffer, length, ppos);
5972 if (!write || ret < 0)
5973 goto out;
5975 /* Sanity checking to avoid pcp imbalance */
5976 if (percpu_pagelist_fraction &&
5977 percpu_pagelist_fraction < MIN_PERCPU_PAGELIST_FRACTION) {
5978 percpu_pagelist_fraction = old_percpu_pagelist_fraction;
5979 ret = -EINVAL;
5980 goto out;
5983 /* No change? */
5984 if (percpu_pagelist_fraction == old_percpu_pagelist_fraction)
5985 goto out;
5987 for_each_populated_zone(zone) {
5988 unsigned int cpu;
5990 for_each_possible_cpu(cpu)
5991 pageset_set_high_and_batch(zone,
5992 per_cpu_ptr(zone->pageset, cpu));
5994 out:
5995 mutex_unlock(&pcp_batch_high_lock);
5996 return ret;
5999 int hashdist = HASHDIST_DEFAULT;
6001 #ifdef CONFIG_NUMA
6002 static int __init set_hashdist(char *str)
6004 if (!str)
6005 return 0;
6006 hashdist = simple_strtoul(str, &str, 0);
6007 return 1;
6009 __setup("hashdist=", set_hashdist);
6010 #endif
6013 * allocate a large system hash table from bootmem
6014 * - it is assumed that the hash table must contain an exact power-of-2
6015 * quantity of entries
6016 * - limit is the number of hash buckets, not the total allocation size
6018 void *__init alloc_large_system_hash(const char *tablename,
6019 unsigned long bucketsize,
6020 unsigned long numentries,
6021 int scale,
6022 int flags,
6023 unsigned int *_hash_shift,
6024 unsigned int *_hash_mask,
6025 unsigned long low_limit,
6026 unsigned long high_limit)
6028 unsigned long long max = high_limit;
6029 unsigned long log2qty, size;
6030 void *table = NULL;
6032 /* allow the kernel cmdline to have a say */
6033 if (!numentries) {
6034 /* round applicable memory size up to nearest megabyte */
6035 numentries = nr_kernel_pages;
6037 /* It isn't necessary when PAGE_SIZE >= 1MB */
6038 if (PAGE_SHIFT < 20)
6039 numentries = round_up(numentries, (1<<20)/PAGE_SIZE);
6041 /* limit to 1 bucket per 2^scale bytes of low memory */
6042 if (scale > PAGE_SHIFT)
6043 numentries >>= (scale - PAGE_SHIFT);
6044 else
6045 numentries <<= (PAGE_SHIFT - scale);
6047 /* Make sure we've got at least a 0-order allocation.. */
6048 if (unlikely(flags & HASH_SMALL)) {
6049 /* Makes no sense without HASH_EARLY */
6050 WARN_ON(!(flags & HASH_EARLY));
6051 if (!(numentries >> *_hash_shift)) {
6052 numentries = 1UL << *_hash_shift;
6053 BUG_ON(!numentries);
6055 } else if (unlikely((numentries * bucketsize) < PAGE_SIZE))
6056 numentries = PAGE_SIZE / bucketsize;
6058 numentries = roundup_pow_of_two(numentries);
6060 /* limit allocation size to 1/16 total memory by default */
6061 if (max == 0) {
6062 max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
6063 do_div(max, bucketsize);
6065 max = min(max, 0x80000000ULL);
6067 if (numentries < low_limit)
6068 numentries = low_limit;
6069 if (numentries > max)
6070 numentries = max;
6072 log2qty = ilog2(numentries);
6074 do {
6075 size = bucketsize << log2qty;
6076 if (flags & HASH_EARLY)
6077 table = memblock_virt_alloc_nopanic(size, 0);
6078 else if (hashdist)
6079 table = __vmalloc(size, GFP_ATOMIC, PAGE_KERNEL);
6080 else {
6082 * If bucketsize is not a power-of-two, we may free
6083 * some pages at the end of hash table which
6084 * alloc_pages_exact() automatically does
6086 if (get_order(size) < MAX_ORDER) {
6087 table = alloc_pages_exact(size, GFP_ATOMIC);
6088 kmemleak_alloc(table, size, 1, GFP_ATOMIC);
6091 } while (!table && size > PAGE_SIZE && --log2qty);
6093 if (!table)
6094 panic("Failed to allocate %s hash table\n", tablename);
6096 printk(KERN_INFO "%s hash table entries: %ld (order: %d, %lu bytes)\n",
6097 tablename,
6098 (1UL << log2qty),
6099 ilog2(size) - PAGE_SHIFT,
6100 size);
6102 if (_hash_shift)
6103 *_hash_shift = log2qty;
6104 if (_hash_mask)
6105 *_hash_mask = (1 << log2qty) - 1;
6107 return table;
6110 /* Return a pointer to the bitmap storing bits affecting a block of pages */
6111 static inline unsigned long *get_pageblock_bitmap(struct zone *zone,
6112 unsigned long pfn)
6114 #ifdef CONFIG_SPARSEMEM
6115 return __pfn_to_section(pfn)->pageblock_flags;
6116 #else
6117 return zone->pageblock_flags;
6118 #endif /* CONFIG_SPARSEMEM */
6121 static inline int pfn_to_bitidx(struct zone *zone, unsigned long pfn)
6123 #ifdef CONFIG_SPARSEMEM
6124 pfn &= (PAGES_PER_SECTION-1);
6125 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
6126 #else
6127 pfn = pfn - round_down(zone->zone_start_pfn, pageblock_nr_pages);
6128 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
6129 #endif /* CONFIG_SPARSEMEM */
6133 * get_pfnblock_flags_mask - Return the requested group of flags for the pageblock_nr_pages block of pages
6134 * @page: The page within the block of interest
6135 * @pfn: The target page frame number
6136 * @end_bitidx: The last bit of interest to retrieve
6137 * @mask: mask of bits that the caller is interested in
6139 * Return: pageblock_bits flags
6141 unsigned long get_pfnblock_flags_mask(struct page *page, unsigned long pfn,
6142 unsigned long end_bitidx,
6143 unsigned long mask)
6145 struct zone *zone;
6146 unsigned long *bitmap;
6147 unsigned long bitidx, word_bitidx;
6148 unsigned long word;
6150 zone = page_zone(page);
6151 bitmap = get_pageblock_bitmap(zone, pfn);
6152 bitidx = pfn_to_bitidx(zone, pfn);
6153 word_bitidx = bitidx / BITS_PER_LONG;
6154 bitidx &= (BITS_PER_LONG-1);
6156 word = bitmap[word_bitidx];
6157 bitidx += end_bitidx;
6158 return (word >> (BITS_PER_LONG - bitidx - 1)) & mask;
6162 * set_pfnblock_flags_mask - Set the requested group of flags for a pageblock_nr_pages block of pages
6163 * @page: The page within the block of interest
6164 * @flags: The flags to set
6165 * @pfn: The target page frame number
6166 * @end_bitidx: The last bit of interest
6167 * @mask: mask of bits that the caller is interested in
6169 void set_pfnblock_flags_mask(struct page *page, unsigned long flags,
6170 unsigned long pfn,
6171 unsigned long end_bitidx,
6172 unsigned long mask)
6174 struct zone *zone;
6175 unsigned long *bitmap;
6176 unsigned long bitidx, word_bitidx;
6177 unsigned long old_word, word;
6179 BUILD_BUG_ON(NR_PAGEBLOCK_BITS != 4);
6181 zone = page_zone(page);
6182 bitmap = get_pageblock_bitmap(zone, pfn);
6183 bitidx = pfn_to_bitidx(zone, pfn);
6184 word_bitidx = bitidx / BITS_PER_LONG;
6185 bitidx &= (BITS_PER_LONG-1);
6187 VM_BUG_ON_PAGE(!zone_spans_pfn(zone, pfn), page);
6189 bitidx += end_bitidx;
6190 mask <<= (BITS_PER_LONG - bitidx - 1);
6191 flags <<= (BITS_PER_LONG - bitidx - 1);
6193 word = ACCESS_ONCE(bitmap[word_bitidx]);
6194 for (;;) {
6195 old_word = cmpxchg(&bitmap[word_bitidx], word, (word & ~mask) | flags);
6196 if (word == old_word)
6197 break;
6198 word = old_word;
6203 * This function checks whether pageblock includes unmovable pages or not.
6204 * If @count is not zero, it is okay to include less @count unmovable pages
6206 * PageLRU check without isolation or lru_lock could race so that
6207 * MIGRATE_MOVABLE block might include unmovable pages. It means you can't
6208 * expect this function should be exact.
6210 bool has_unmovable_pages(struct zone *zone, struct page *page, int count,
6211 bool skip_hwpoisoned_pages)
6213 unsigned long pfn, iter, found;
6214 int mt;
6217 * For avoiding noise data, lru_add_drain_all() should be called
6218 * If ZONE_MOVABLE, the zone never contains unmovable pages
6220 if (zone_idx(zone) == ZONE_MOVABLE)
6221 return false;
6222 mt = get_pageblock_migratetype(page);
6223 if (mt == MIGRATE_MOVABLE || is_migrate_cma(mt))
6224 return false;
6226 pfn = page_to_pfn(page);
6227 for (found = 0, iter = 0; iter < pageblock_nr_pages; iter++) {
6228 unsigned long check = pfn + iter;
6230 if (!pfn_valid_within(check))
6231 continue;
6233 page = pfn_to_page(check);
6236 * Hugepages are not in LRU lists, but they're movable.
6237 * We need not scan over tail pages bacause we don't
6238 * handle each tail page individually in migration.
6240 if (PageHuge(page)) {
6241 iter = round_up(iter + 1, 1<<compound_order(page)) - 1;
6242 continue;
6246 * We can't use page_count without pin a page
6247 * because another CPU can free compound page.
6248 * This check already skips compound tails of THP
6249 * because their page->_count is zero at all time.
6251 if (!atomic_read(&page->_count)) {
6252 if (PageBuddy(page))
6253 iter += (1 << page_order(page)) - 1;
6254 continue;
6258 * The HWPoisoned page may be not in buddy system, and
6259 * page_count() is not 0.
6261 if (skip_hwpoisoned_pages && PageHWPoison(page))
6262 continue;
6264 if (!PageLRU(page))
6265 found++;
6267 * If there are RECLAIMABLE pages, we need to check it.
6268 * But now, memory offline itself doesn't call shrink_slab()
6269 * and it still to be fixed.
6272 * If the page is not RAM, page_count()should be 0.
6273 * we don't need more check. This is an _used_ not-movable page.
6275 * The problematic thing here is PG_reserved pages. PG_reserved
6276 * is set to both of a memory hole page and a _used_ kernel
6277 * page at boot.
6279 if (found > count)
6280 return true;
6282 return false;
6285 bool is_pageblock_removable_nolock(struct page *page)
6287 struct zone *zone;
6288 unsigned long pfn;
6291 * We have to be careful here because we are iterating over memory
6292 * sections which are not zone aware so we might end up outside of
6293 * the zone but still within the section.
6294 * We have to take care about the node as well. If the node is offline
6295 * its NODE_DATA will be NULL - see page_zone.
6297 if (!node_online(page_to_nid(page)))
6298 return false;
6300 zone = page_zone(page);
6301 pfn = page_to_pfn(page);
6302 if (!zone_spans_pfn(zone, pfn))
6303 return false;
6305 return !has_unmovable_pages(zone, page, 0, true);
6308 #ifdef CONFIG_CMA
6310 static unsigned long pfn_max_align_down(unsigned long pfn)
6312 return pfn & ~(max_t(unsigned long, MAX_ORDER_NR_PAGES,
6313 pageblock_nr_pages) - 1);
6316 static unsigned long pfn_max_align_up(unsigned long pfn)
6318 return ALIGN(pfn, max_t(unsigned long, MAX_ORDER_NR_PAGES,
6319 pageblock_nr_pages));
6322 /* [start, end) must belong to a single zone. */
6323 static int __alloc_contig_migrate_range(struct compact_control *cc,
6324 unsigned long start, unsigned long end)
6326 /* This function is based on compact_zone() from compaction.c. */
6327 unsigned long nr_reclaimed;
6328 unsigned long pfn = start;
6329 unsigned int tries = 0;
6330 int ret = 0;
6332 migrate_prep();
6334 while (pfn < end || !list_empty(&cc->migratepages)) {
6335 if (fatal_signal_pending(current)) {
6336 ret = -EINTR;
6337 break;
6340 if (list_empty(&cc->migratepages)) {
6341 cc->nr_migratepages = 0;
6342 pfn = isolate_migratepages_range(cc->zone, cc,
6343 pfn, end, true);
6344 if (!pfn) {
6345 ret = -EINTR;
6346 break;
6348 tries = 0;
6349 } else if (++tries == 5) {
6350 ret = ret < 0 ? ret : -EBUSY;
6351 break;
6354 nr_reclaimed = reclaim_clean_pages_from_list(cc->zone,
6355 &cc->migratepages);
6356 cc->nr_migratepages -= nr_reclaimed;
6358 ret = migrate_pages(&cc->migratepages, alloc_migrate_target,
6359 NULL, 0, cc->mode, MR_CMA);
6361 if (ret < 0) {
6362 putback_movable_pages(&cc->migratepages);
6363 return ret;
6365 return 0;
6369 * alloc_contig_range() -- tries to allocate given range of pages
6370 * @start: start PFN to allocate
6371 * @end: one-past-the-last PFN to allocate
6372 * @migratetype: migratetype of the underlaying pageblocks (either
6373 * #MIGRATE_MOVABLE or #MIGRATE_CMA). All pageblocks
6374 * in range must have the same migratetype and it must
6375 * be either of the two.
6377 * The PFN range does not have to be pageblock or MAX_ORDER_NR_PAGES
6378 * aligned, however it's the caller's responsibility to guarantee that
6379 * we are the only thread that changes migrate type of pageblocks the
6380 * pages fall in.
6382 * The PFN range must belong to a single zone.
6384 * Returns zero on success or negative error code. On success all
6385 * pages which PFN is in [start, end) are allocated for the caller and
6386 * need to be freed with free_contig_range().
6388 int alloc_contig_range(unsigned long start, unsigned long end,
6389 unsigned migratetype)
6391 unsigned long outer_start, outer_end;
6392 int ret = 0, order;
6394 struct compact_control cc = {
6395 .nr_migratepages = 0,
6396 .order = -1,
6397 .zone = page_zone(pfn_to_page(start)),
6398 .mode = MIGRATE_SYNC,
6399 .ignore_skip_hint = true,
6401 INIT_LIST_HEAD(&cc.migratepages);
6404 * What we do here is we mark all pageblocks in range as
6405 * MIGRATE_ISOLATE. Because pageblock and max order pages may
6406 * have different sizes, and due to the way page allocator
6407 * work, we align the range to biggest of the two pages so
6408 * that page allocator won't try to merge buddies from
6409 * different pageblocks and change MIGRATE_ISOLATE to some
6410 * other migration type.
6412 * Once the pageblocks are marked as MIGRATE_ISOLATE, we
6413 * migrate the pages from an unaligned range (ie. pages that
6414 * we are interested in). This will put all the pages in
6415 * range back to page allocator as MIGRATE_ISOLATE.
6417 * When this is done, we take the pages in range from page
6418 * allocator removing them from the buddy system. This way
6419 * page allocator will never consider using them.
6421 * This lets us mark the pageblocks back as
6422 * MIGRATE_CMA/MIGRATE_MOVABLE so that free pages in the
6423 * aligned range but not in the unaligned, original range are
6424 * put back to page allocator so that buddy can use them.
6427 ret = start_isolate_page_range(pfn_max_align_down(start),
6428 pfn_max_align_up(end), migratetype,
6429 false);
6430 if (ret)
6431 return ret;
6433 ret = __alloc_contig_migrate_range(&cc, start, end);
6434 if (ret)
6435 goto done;
6438 * Pages from [start, end) are within a MAX_ORDER_NR_PAGES
6439 * aligned blocks that are marked as MIGRATE_ISOLATE. What's
6440 * more, all pages in [start, end) are free in page allocator.
6441 * What we are going to do is to allocate all pages from
6442 * [start, end) (that is remove them from page allocator).
6444 * The only problem is that pages at the beginning and at the
6445 * end of interesting range may be not aligned with pages that
6446 * page allocator holds, ie. they can be part of higher order
6447 * pages. Because of this, we reserve the bigger range and
6448 * once this is done free the pages we are not interested in.
6450 * We don't have to hold zone->lock here because the pages are
6451 * isolated thus they won't get removed from buddy.
6454 lru_add_drain_all();
6455 drain_all_pages();
6457 order = 0;
6458 outer_start = start;
6459 while (!PageBuddy(pfn_to_page(outer_start))) {
6460 if (++order >= MAX_ORDER) {
6461 ret = -EBUSY;
6462 goto done;
6464 outer_start &= ~0UL << order;
6467 /* Make sure the range is really isolated. */
6468 if (test_pages_isolated(outer_start, end, false)) {
6469 pr_warn("alloc_contig_range test_pages_isolated(%lx, %lx) failed\n",
6470 outer_start, end);
6471 ret = -EBUSY;
6472 goto done;
6476 /* Grab isolated pages from freelists. */
6477 outer_end = isolate_freepages_range(&cc, outer_start, end);
6478 if (!outer_end) {
6479 ret = -EBUSY;
6480 goto done;
6483 /* Free head and tail (if any) */
6484 if (start != outer_start)
6485 free_contig_range(outer_start, start - outer_start);
6486 if (end != outer_end)
6487 free_contig_range(end, outer_end - end);
6489 done:
6490 undo_isolate_page_range(pfn_max_align_down(start),
6491 pfn_max_align_up(end), migratetype);
6492 return ret;
6495 void free_contig_range(unsigned long pfn, unsigned nr_pages)
6497 unsigned int count = 0;
6499 for (; nr_pages--; pfn++) {
6500 struct page *page = pfn_to_page(pfn);
6502 count += page_count(page) != 1;
6503 __free_page(page);
6505 WARN(count != 0, "%d pages are still in use!\n", count);
6507 #endif
6509 #ifdef CONFIG_MEMORY_HOTPLUG
6511 * The zone indicated has a new number of managed_pages; batch sizes and percpu
6512 * page high values need to be recalulated.
6514 void __meminit zone_pcp_update(struct zone *zone)
6516 unsigned cpu;
6517 mutex_lock(&pcp_batch_high_lock);
6518 for_each_possible_cpu(cpu)
6519 pageset_set_high_and_batch(zone,
6520 per_cpu_ptr(zone->pageset, cpu));
6521 mutex_unlock(&pcp_batch_high_lock);
6523 #endif
6525 void zone_pcp_reset(struct zone *zone)
6527 unsigned long flags;
6528 int cpu;
6529 struct per_cpu_pageset *pset;
6531 /* avoid races with drain_pages() */
6532 local_irq_save(flags);
6533 if (zone->pageset != &boot_pageset) {
6534 for_each_online_cpu(cpu) {
6535 pset = per_cpu_ptr(zone->pageset, cpu);
6536 drain_zonestat(zone, pset);
6538 free_percpu(zone->pageset);
6539 zone->pageset = &boot_pageset;
6541 local_irq_restore(flags);
6544 #ifdef CONFIG_MEMORY_HOTREMOVE
6546 * All pages in the range must be isolated before calling this.
6548 void
6549 __offline_isolated_pages(unsigned long start_pfn, unsigned long end_pfn)
6551 struct page *page;
6552 struct zone *zone;
6553 unsigned int order, i;
6554 unsigned long pfn;
6555 unsigned long flags;
6556 /* find the first valid pfn */
6557 for (pfn = start_pfn; pfn < end_pfn; pfn++)
6558 if (pfn_valid(pfn))
6559 break;
6560 if (pfn == end_pfn)
6561 return;
6562 zone = page_zone(pfn_to_page(pfn));
6563 spin_lock_irqsave(&zone->lock, flags);
6564 pfn = start_pfn;
6565 while (pfn < end_pfn) {
6566 if (!pfn_valid(pfn)) {
6567 pfn++;
6568 continue;
6570 page = pfn_to_page(pfn);
6572 * The HWPoisoned page may be not in buddy system, and
6573 * page_count() is not 0.
6575 if (unlikely(!PageBuddy(page) && PageHWPoison(page))) {
6576 pfn++;
6577 SetPageReserved(page);
6578 continue;
6581 BUG_ON(page_count(page));
6582 BUG_ON(!PageBuddy(page));
6583 order = page_order(page);
6584 #ifdef CONFIG_DEBUG_VM
6585 printk(KERN_INFO "remove from free list %lx %d %lx\n",
6586 pfn, 1 << order, end_pfn);
6587 #endif
6588 list_del(&page->lru);
6589 rmv_page_order(page);
6590 zone->free_area[order].nr_free--;
6591 for (i = 0; i < (1 << order); i++)
6592 SetPageReserved((page+i));
6593 pfn += (1 << order);
6595 spin_unlock_irqrestore(&zone->lock, flags);
6597 #endif
6599 #ifdef CONFIG_MEMORY_FAILURE
6600 bool is_free_buddy_page(struct page *page)
6602 struct zone *zone = page_zone(page);
6603 unsigned long pfn = page_to_pfn(page);
6604 unsigned long flags;
6605 unsigned int order;
6607 spin_lock_irqsave(&zone->lock, flags);
6608 for (order = 0; order < MAX_ORDER; order++) {
6609 struct page *page_head = page - (pfn & ((1 << order) - 1));
6611 if (PageBuddy(page_head) && page_order(page_head) >= order)
6612 break;
6614 spin_unlock_irqrestore(&zone->lock, flags);
6616 return order < MAX_ORDER;
6618 #endif
6620 static const struct trace_print_flags pageflag_names[] = {
6621 {1UL << PG_locked, "locked" },
6622 {1UL << PG_error, "error" },
6623 {1UL << PG_referenced, "referenced" },
6624 {1UL << PG_uptodate, "uptodate" },
6625 {1UL << PG_dirty, "dirty" },
6626 {1UL << PG_lru, "lru" },
6627 {1UL << PG_active, "active" },
6628 {1UL << PG_slab, "slab" },
6629 {1UL << PG_owner_priv_1, "owner_priv_1" },
6630 {1UL << PG_arch_1, "arch_1" },
6631 {1UL << PG_reserved, "reserved" },
6632 {1UL << PG_private, "private" },
6633 {1UL << PG_private_2, "private_2" },
6634 {1UL << PG_writeback, "writeback" },
6635 #ifdef CONFIG_PAGEFLAGS_EXTENDED
6636 {1UL << PG_head, "head" },
6637 {1UL << PG_tail, "tail" },
6638 #else
6639 {1UL << PG_compound, "compound" },
6640 #endif
6641 {1UL << PG_swapcache, "swapcache" },
6642 {1UL << PG_mappedtodisk, "mappedtodisk" },
6643 {1UL << PG_reclaim, "reclaim" },
6644 {1UL << PG_swapbacked, "swapbacked" },
6645 {1UL << PG_unevictable, "unevictable" },
6646 #ifdef CONFIG_MMU
6647 {1UL << PG_mlocked, "mlocked" },
6648 #endif
6649 #ifdef CONFIG_ARCH_USES_PG_UNCACHED
6650 {1UL << PG_uncached, "uncached" },
6651 #endif
6652 #ifdef CONFIG_MEMORY_FAILURE
6653 {1UL << PG_hwpoison, "hwpoison" },
6654 #endif
6655 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
6656 {1UL << PG_compound_lock, "compound_lock" },
6657 #endif
6660 static void dump_page_flags(unsigned long flags)
6662 const char *delim = "";
6663 unsigned long mask;
6664 int i;
6666 BUILD_BUG_ON(ARRAY_SIZE(pageflag_names) != __NR_PAGEFLAGS);
6668 printk(KERN_ALERT "page flags: %#lx(", flags);
6670 /* remove zone id */
6671 flags &= (1UL << NR_PAGEFLAGS) - 1;
6673 for (i = 0; i < ARRAY_SIZE(pageflag_names) && flags; i++) {
6675 mask = pageflag_names[i].mask;
6676 if ((flags & mask) != mask)
6677 continue;
6679 flags &= ~mask;
6680 printk("%s%s", delim, pageflag_names[i].name);
6681 delim = "|";
6684 /* check for left over flags */
6685 if (flags)
6686 printk("%s%#lx", delim, flags);
6688 printk(")\n");
6691 void dump_page_badflags(struct page *page, const char *reason,
6692 unsigned long badflags)
6694 printk(KERN_ALERT
6695 "page:%p count:%d mapcount:%d mapping:%p index:%#lx\n",
6696 page, atomic_read(&page->_count), page_mapcount(page),
6697 page->mapping, page->index);
6698 dump_page_flags(page->flags);
6699 if (reason)
6700 pr_alert("page dumped because: %s\n", reason);
6701 if (page->flags & badflags) {
6702 pr_alert("bad because of flags:\n");
6703 dump_page_flags(page->flags & badflags);
6705 mem_cgroup_print_bad_page(page);
6708 void dump_page(struct page *page, const char *reason)
6710 dump_page_badflags(page, reason, 0);
6712 EXPORT_SYMBOL(dump_page);