hpsa: fix bad -ENOMEM return value in hpsa_big_passthru_ioctl
[linux/fpc-iii.git] / mm / page_alloc.c
bloba280f772bc6661b4f0c23ad57daf02630d2cccdb
1 /*
2 * linux/mm/page_alloc.c
4 * Manages the free list, the system allocates free pages here.
5 * Note that kmalloc() lives in slab.c
7 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
8 * Swap reorganised 29.12.95, Stephen Tweedie
9 * Support of BIGMEM added by Gerhard Wichert, Siemens AG, July 1999
10 * Reshaped it to be a zoned allocator, Ingo Molnar, Red Hat, 1999
11 * Discontiguous memory support, Kanoj Sarcar, SGI, Nov 1999
12 * Zone balancing, Kanoj Sarcar, SGI, Jan 2000
13 * Per cpu hot/cold page lists, bulk allocation, Martin J. Bligh, Sept 2002
14 * (lots of bits borrowed from Ingo Molnar & Andrew Morton)
17 #include <linux/stddef.h>
18 #include <linux/mm.h>
19 #include <linux/swap.h>
20 #include <linux/interrupt.h>
21 #include <linux/pagemap.h>
22 #include <linux/jiffies.h>
23 #include <linux/bootmem.h>
24 #include <linux/memblock.h>
25 #include <linux/compiler.h>
26 #include <linux/kernel.h>
27 #include <linux/kmemcheck.h>
28 #include <linux/module.h>
29 #include <linux/suspend.h>
30 #include <linux/pagevec.h>
31 #include <linux/blkdev.h>
32 #include <linux/slab.h>
33 #include <linux/ratelimit.h>
34 #include <linux/oom.h>
35 #include <linux/notifier.h>
36 #include <linux/topology.h>
37 #include <linux/sysctl.h>
38 #include <linux/cpu.h>
39 #include <linux/cpuset.h>
40 #include <linux/memory_hotplug.h>
41 #include <linux/nodemask.h>
42 #include <linux/vmalloc.h>
43 #include <linux/vmstat.h>
44 #include <linux/mempolicy.h>
45 #include <linux/stop_machine.h>
46 #include <linux/sort.h>
47 #include <linux/pfn.h>
48 #include <linux/backing-dev.h>
49 #include <linux/fault-inject.h>
50 #include <linux/page-isolation.h>
51 #include <linux/page_cgroup.h>
52 #include <linux/debugobjects.h>
53 #include <linux/kmemleak.h>
54 #include <linux/compaction.h>
55 #include <trace/events/kmem.h>
56 #include <linux/ftrace_event.h>
57 #include <linux/memcontrol.h>
58 #include <linux/prefetch.h>
59 #include <linux/mm_inline.h>
60 #include <linux/migrate.h>
61 #include <linux/page-debug-flags.h>
62 #include <linux/hugetlb.h>
63 #include <linux/sched/rt.h>
65 #include <asm/sections.h>
66 #include <asm/tlbflush.h>
67 #include <asm/div64.h>
68 #include "internal.h"
70 /* prevent >1 _updater_ of zone percpu pageset ->high and ->batch fields */
71 static DEFINE_MUTEX(pcp_batch_high_lock);
72 #define MIN_PERCPU_PAGELIST_FRACTION (8)
74 #ifdef CONFIG_USE_PERCPU_NUMA_NODE_ID
75 DEFINE_PER_CPU(int, numa_node);
76 EXPORT_PER_CPU_SYMBOL(numa_node);
77 #endif
79 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
81 * N.B., Do NOT reference the '_numa_mem_' per cpu variable directly.
82 * It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined.
83 * Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem()
84 * defined in <linux/topology.h>.
86 DEFINE_PER_CPU(int, _numa_mem_); /* Kernel "local memory" node */
87 EXPORT_PER_CPU_SYMBOL(_numa_mem_);
88 #endif
91 * Array of node states.
93 nodemask_t node_states[NR_NODE_STATES] __read_mostly = {
94 [N_POSSIBLE] = NODE_MASK_ALL,
95 [N_ONLINE] = { { [0] = 1UL } },
96 #ifndef CONFIG_NUMA
97 [N_NORMAL_MEMORY] = { { [0] = 1UL } },
98 #ifdef CONFIG_HIGHMEM
99 [N_HIGH_MEMORY] = { { [0] = 1UL } },
100 #endif
101 #ifdef CONFIG_MOVABLE_NODE
102 [N_MEMORY] = { { [0] = 1UL } },
103 #endif
104 [N_CPU] = { { [0] = 1UL } },
105 #endif /* NUMA */
107 EXPORT_SYMBOL(node_states);
109 /* Protect totalram_pages and zone->managed_pages */
110 static DEFINE_SPINLOCK(managed_page_count_lock);
112 unsigned long totalram_pages __read_mostly;
113 unsigned long totalreserve_pages __read_mostly;
115 * When calculating the number of globally allowed dirty pages, there
116 * is a certain number of per-zone reserves that should not be
117 * considered dirtyable memory. This is the sum of those reserves
118 * over all existing zones that contribute dirtyable memory.
120 unsigned long dirty_balance_reserve __read_mostly;
122 int percpu_pagelist_fraction;
123 gfp_t gfp_allowed_mask __read_mostly = GFP_BOOT_MASK;
125 #ifdef CONFIG_PM_SLEEP
127 * The following functions are used by the suspend/hibernate code to temporarily
128 * change gfp_allowed_mask in order to avoid using I/O during memory allocations
129 * while devices are suspended. To avoid races with the suspend/hibernate code,
130 * they should always be called with pm_mutex held (gfp_allowed_mask also should
131 * only be modified with pm_mutex held, unless the suspend/hibernate code is
132 * guaranteed not to run in parallel with that modification).
135 static gfp_t saved_gfp_mask;
137 void pm_restore_gfp_mask(void)
139 WARN_ON(!mutex_is_locked(&pm_mutex));
140 if (saved_gfp_mask) {
141 gfp_allowed_mask = saved_gfp_mask;
142 saved_gfp_mask = 0;
146 void pm_restrict_gfp_mask(void)
148 WARN_ON(!mutex_is_locked(&pm_mutex));
149 WARN_ON(saved_gfp_mask);
150 saved_gfp_mask = gfp_allowed_mask;
151 gfp_allowed_mask &= ~GFP_IOFS;
154 bool pm_suspended_storage(void)
156 if ((gfp_allowed_mask & GFP_IOFS) == GFP_IOFS)
157 return false;
158 return true;
160 #endif /* CONFIG_PM_SLEEP */
162 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
163 int pageblock_order __read_mostly;
164 #endif
166 static void __free_pages_ok(struct page *page, unsigned int order);
169 * results with 256, 32 in the lowmem_reserve sysctl:
170 * 1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
171 * 1G machine -> (16M dma, 784M normal, 224M high)
172 * NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
173 * HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
174 * HIGHMEM allocation will (224M+784M)/256 of ram reserved in ZONE_DMA
176 * TBD: should special case ZONE_DMA32 machines here - in those we normally
177 * don't need any ZONE_NORMAL reservation
179 int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES-1] = {
180 #ifdef CONFIG_ZONE_DMA
181 256,
182 #endif
183 #ifdef CONFIG_ZONE_DMA32
184 256,
185 #endif
186 #ifdef CONFIG_HIGHMEM
188 #endif
192 EXPORT_SYMBOL(totalram_pages);
194 static char * const zone_names[MAX_NR_ZONES] = {
195 #ifdef CONFIG_ZONE_DMA
196 "DMA",
197 #endif
198 #ifdef CONFIG_ZONE_DMA32
199 "DMA32",
200 #endif
201 "Normal",
202 #ifdef CONFIG_HIGHMEM
203 "HighMem",
204 #endif
205 "Movable",
208 int min_free_kbytes = 1024;
209 int user_min_free_kbytes;
211 static unsigned long __meminitdata nr_kernel_pages;
212 static unsigned long __meminitdata nr_all_pages;
213 static unsigned long __meminitdata dma_reserve;
215 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
216 static unsigned long __meminitdata arch_zone_lowest_possible_pfn[MAX_NR_ZONES];
217 static unsigned long __meminitdata arch_zone_highest_possible_pfn[MAX_NR_ZONES];
218 static unsigned long __initdata required_kernelcore;
219 static unsigned long __initdata required_movablecore;
220 static unsigned long __meminitdata zone_movable_pfn[MAX_NUMNODES];
222 /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
223 int movable_zone;
224 EXPORT_SYMBOL(movable_zone);
225 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
227 #if MAX_NUMNODES > 1
228 int nr_node_ids __read_mostly = MAX_NUMNODES;
229 int nr_online_nodes __read_mostly = 1;
230 EXPORT_SYMBOL(nr_node_ids);
231 EXPORT_SYMBOL(nr_online_nodes);
232 #endif
234 int page_group_by_mobility_disabled __read_mostly;
236 void set_pageblock_migratetype(struct page *page, int migratetype)
239 if (unlikely(page_group_by_mobility_disabled))
240 migratetype = MIGRATE_UNMOVABLE;
242 set_pageblock_flags_group(page, (unsigned long)migratetype,
243 PB_migrate, PB_migrate_end);
246 bool oom_killer_disabled __read_mostly;
248 #ifdef CONFIG_DEBUG_VM
249 static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
251 int ret = 0;
252 unsigned seq;
253 unsigned long pfn = page_to_pfn(page);
254 unsigned long sp, start_pfn;
256 do {
257 seq = zone_span_seqbegin(zone);
258 start_pfn = zone->zone_start_pfn;
259 sp = zone->spanned_pages;
260 if (!zone_spans_pfn(zone, pfn))
261 ret = 1;
262 } while (zone_span_seqretry(zone, seq));
264 if (ret)
265 pr_err("page %lu outside zone [ %lu - %lu ]\n",
266 pfn, start_pfn, start_pfn + sp);
268 return ret;
271 static int page_is_consistent(struct zone *zone, struct page *page)
273 if (!pfn_valid_within(page_to_pfn(page)))
274 return 0;
275 if (zone != page_zone(page))
276 return 0;
278 return 1;
281 * Temporary debugging check for pages not lying within a given zone.
283 static int bad_range(struct zone *zone, struct page *page)
285 if (page_outside_zone_boundaries(zone, page))
286 return 1;
287 if (!page_is_consistent(zone, page))
288 return 1;
290 return 0;
292 #else
293 static inline int bad_range(struct zone *zone, struct page *page)
295 return 0;
297 #endif
299 static void bad_page(struct page *page)
301 static unsigned long resume;
302 static unsigned long nr_shown;
303 static unsigned long nr_unshown;
305 /* Don't complain about poisoned pages */
306 if (PageHWPoison(page)) {
307 page_mapcount_reset(page); /* remove PageBuddy */
308 return;
312 * Allow a burst of 60 reports, then keep quiet for that minute;
313 * or allow a steady drip of one report per second.
315 if (nr_shown == 60) {
316 if (time_before(jiffies, resume)) {
317 nr_unshown++;
318 goto out;
320 if (nr_unshown) {
321 printk(KERN_ALERT
322 "BUG: Bad page state: %lu messages suppressed\n",
323 nr_unshown);
324 nr_unshown = 0;
326 nr_shown = 0;
328 if (nr_shown++ == 0)
329 resume = jiffies + 60 * HZ;
331 printk(KERN_ALERT "BUG: Bad page state in process %s pfn:%05lx\n",
332 current->comm, page_to_pfn(page));
333 dump_page(page);
335 print_modules();
336 dump_stack();
337 out:
338 /* Leave bad fields for debug, except PageBuddy could make trouble */
339 page_mapcount_reset(page); /* remove PageBuddy */
340 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
344 * Higher-order pages are called "compound pages". They are structured thusly:
346 * The first PAGE_SIZE page is called the "head page".
348 * The remaining PAGE_SIZE pages are called "tail pages".
350 * All pages have PG_compound set. All tail pages have their ->first_page
351 * pointing at the head page.
353 * The first tail page's ->lru.next holds the address of the compound page's
354 * put_page() function. Its ->lru.prev holds the order of allocation.
355 * This usage means that zero-order pages may not be compound.
358 static void free_compound_page(struct page *page)
360 __free_pages_ok(page, compound_order(page));
363 void prep_compound_page(struct page *page, unsigned long order)
365 int i;
366 int nr_pages = 1 << order;
368 set_compound_page_dtor(page, free_compound_page);
369 set_compound_order(page, order);
370 __SetPageHead(page);
371 for (i = 1; i < nr_pages; i++) {
372 struct page *p = page + i;
373 set_page_count(p, 0);
374 p->first_page = page;
375 /* Make sure p->first_page is always valid for PageTail() */
376 smp_wmb();
377 __SetPageTail(p);
381 /* update __split_huge_page_refcount if you change this function */
382 static int destroy_compound_page(struct page *page, unsigned long order)
384 int i;
385 int nr_pages = 1 << order;
386 int bad = 0;
388 if (unlikely(compound_order(page) != order)) {
389 bad_page(page);
390 bad++;
393 __ClearPageHead(page);
395 for (i = 1; i < nr_pages; i++) {
396 struct page *p = page + i;
398 if (unlikely(!PageTail(p) || (p->first_page != page))) {
399 bad_page(page);
400 bad++;
402 __ClearPageTail(p);
405 return bad;
408 static inline void prep_zero_page(struct page *page, int order, gfp_t gfp_flags)
410 int i;
413 * clear_highpage() will use KM_USER0, so it's a bug to use __GFP_ZERO
414 * and __GFP_HIGHMEM from hard or soft interrupt context.
416 VM_BUG_ON((gfp_flags & __GFP_HIGHMEM) && in_interrupt());
417 for (i = 0; i < (1 << order); i++)
418 clear_highpage(page + i);
421 #ifdef CONFIG_DEBUG_PAGEALLOC
422 unsigned int _debug_guardpage_minorder;
424 static int __init debug_guardpage_minorder_setup(char *buf)
426 unsigned long res;
428 if (kstrtoul(buf, 10, &res) < 0 || res > MAX_ORDER / 2) {
429 printk(KERN_ERR "Bad debug_guardpage_minorder value\n");
430 return 0;
432 _debug_guardpage_minorder = res;
433 printk(KERN_INFO "Setting debug_guardpage_minorder to %lu\n", res);
434 return 0;
436 __setup("debug_guardpage_minorder=", debug_guardpage_minorder_setup);
438 static inline void set_page_guard_flag(struct page *page)
440 __set_bit(PAGE_DEBUG_FLAG_GUARD, &page->debug_flags);
443 static inline void clear_page_guard_flag(struct page *page)
445 __clear_bit(PAGE_DEBUG_FLAG_GUARD, &page->debug_flags);
447 #else
448 static inline void set_page_guard_flag(struct page *page) { }
449 static inline void clear_page_guard_flag(struct page *page) { }
450 #endif
452 static inline void set_page_order(struct page *page, int order)
454 set_page_private(page, order);
455 __SetPageBuddy(page);
458 static inline void rmv_page_order(struct page *page)
460 __ClearPageBuddy(page);
461 set_page_private(page, 0);
465 * Locate the struct page for both the matching buddy in our
466 * pair (buddy1) and the combined O(n+1) page they form (page).
468 * 1) Any buddy B1 will have an order O twin B2 which satisfies
469 * the following equation:
470 * B2 = B1 ^ (1 << O)
471 * For example, if the starting buddy (buddy2) is #8 its order
472 * 1 buddy is #10:
473 * B2 = 8 ^ (1 << 1) = 8 ^ 2 = 10
475 * 2) Any buddy B will have an order O+1 parent P which
476 * satisfies the following equation:
477 * P = B & ~(1 << O)
479 * Assumption: *_mem_map is contiguous at least up to MAX_ORDER
481 static inline unsigned long
482 __find_buddy_index(unsigned long page_idx, unsigned int order)
484 return page_idx ^ (1 << order);
488 * This function checks whether a page is free && is the buddy
489 * we can do coalesce a page and its buddy if
490 * (a) the buddy is not in a hole &&
491 * (b) the buddy is in the buddy system &&
492 * (c) a page and its buddy have the same order &&
493 * (d) a page and its buddy are in the same zone.
495 * For recording whether a page is in the buddy system, we set ->_mapcount
496 * PAGE_BUDDY_MAPCOUNT_VALUE.
497 * Setting, clearing, and testing _mapcount PAGE_BUDDY_MAPCOUNT_VALUE is
498 * serialized by zone->lock.
500 * For recording page's order, we use page_private(page).
502 static inline int page_is_buddy(struct page *page, struct page *buddy,
503 int order)
505 if (!pfn_valid_within(page_to_pfn(buddy)))
506 return 0;
508 if (page_zone_id(page) != page_zone_id(buddy))
509 return 0;
511 if (page_is_guard(buddy) && page_order(buddy) == order) {
512 VM_BUG_ON(page_count(buddy) != 0);
513 return 1;
516 if (PageBuddy(buddy) && page_order(buddy) == order) {
517 VM_BUG_ON(page_count(buddy) != 0);
518 return 1;
520 return 0;
524 * Freeing function for a buddy system allocator.
526 * The concept of a buddy system is to maintain direct-mapped table
527 * (containing bit values) for memory blocks of various "orders".
528 * The bottom level table contains the map for the smallest allocatable
529 * units of memory (here, pages), and each level above it describes
530 * pairs of units from the levels below, hence, "buddies".
531 * At a high level, all that happens here is marking the table entry
532 * at the bottom level available, and propagating the changes upward
533 * as necessary, plus some accounting needed to play nicely with other
534 * parts of the VM system.
535 * At each level, we keep a list of pages, which are heads of continuous
536 * free pages of length of (1 << order) and marked with _mapcount
537 * PAGE_BUDDY_MAPCOUNT_VALUE. Page's order is recorded in page_private(page)
538 * field.
539 * So when we are allocating or freeing one, we can derive the state of the
540 * other. That is, if we allocate a small block, and both were
541 * free, the remainder of the region must be split into blocks.
542 * If a block is freed, and its buddy is also free, then this
543 * triggers coalescing into a block of larger size.
545 * -- nyc
548 static inline void __free_one_page(struct page *page,
549 struct zone *zone, unsigned int order,
550 int migratetype)
552 unsigned long page_idx;
553 unsigned long combined_idx;
554 unsigned long uninitialized_var(buddy_idx);
555 struct page *buddy;
557 VM_BUG_ON(!zone_is_initialized(zone));
559 if (unlikely(PageCompound(page)))
560 if (unlikely(destroy_compound_page(page, order)))
561 return;
563 VM_BUG_ON(migratetype == -1);
565 page_idx = page_to_pfn(page) & ((1 << MAX_ORDER) - 1);
567 VM_BUG_ON(page_idx & ((1 << order) - 1));
568 VM_BUG_ON(bad_range(zone, page));
570 while (order < MAX_ORDER-1) {
571 buddy_idx = __find_buddy_index(page_idx, order);
572 buddy = page + (buddy_idx - page_idx);
573 if (!page_is_buddy(page, buddy, order))
574 break;
576 * Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page,
577 * merge with it and move up one order.
579 if (page_is_guard(buddy)) {
580 clear_page_guard_flag(buddy);
581 set_page_private(page, 0);
582 __mod_zone_freepage_state(zone, 1 << order,
583 migratetype);
584 } else {
585 list_del(&buddy->lru);
586 zone->free_area[order].nr_free--;
587 rmv_page_order(buddy);
589 combined_idx = buddy_idx & page_idx;
590 page = page + (combined_idx - page_idx);
591 page_idx = combined_idx;
592 order++;
594 set_page_order(page, order);
597 * If this is not the largest possible page, check if the buddy
598 * of the next-highest order is free. If it is, it's possible
599 * that pages are being freed that will coalesce soon. In case,
600 * that is happening, add the free page to the tail of the list
601 * so it's less likely to be used soon and more likely to be merged
602 * as a higher order page
604 if ((order < MAX_ORDER-2) && pfn_valid_within(page_to_pfn(buddy))) {
605 struct page *higher_page, *higher_buddy;
606 combined_idx = buddy_idx & page_idx;
607 higher_page = page + (combined_idx - page_idx);
608 buddy_idx = __find_buddy_index(combined_idx, order + 1);
609 higher_buddy = higher_page + (buddy_idx - combined_idx);
610 if (page_is_buddy(higher_page, higher_buddy, order + 1)) {
611 list_add_tail(&page->lru,
612 &zone->free_area[order].free_list[migratetype]);
613 goto out;
617 list_add(&page->lru, &zone->free_area[order].free_list[migratetype]);
618 out:
619 zone->free_area[order].nr_free++;
622 static inline int free_pages_check(struct page *page)
624 if (unlikely(page_mapcount(page) |
625 (page->mapping != NULL) |
626 (atomic_read(&page->_count) != 0) |
627 (page->flags & PAGE_FLAGS_CHECK_AT_FREE) |
628 (mem_cgroup_bad_page_check(page)))) {
629 bad_page(page);
630 return 1;
632 page_nid_reset_last(page);
633 if (page->flags & PAGE_FLAGS_CHECK_AT_PREP)
634 page->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
635 return 0;
639 * Frees a number of pages from the PCP lists
640 * Assumes all pages on list are in same zone, and of same order.
641 * count is the number of pages to free.
643 * If the zone was previously in an "all pages pinned" state then look to
644 * see if this freeing clears that state.
646 * And clear the zone's pages_scanned counter, to hold off the "all pages are
647 * pinned" detection logic.
649 static void free_pcppages_bulk(struct zone *zone, int count,
650 struct per_cpu_pages *pcp)
652 int migratetype = 0;
653 int batch_free = 0;
654 int to_free = count;
656 spin_lock(&zone->lock);
657 zone->pages_scanned = 0;
659 while (to_free) {
660 struct page *page;
661 struct list_head *list;
664 * Remove pages from lists in a round-robin fashion. A
665 * batch_free count is maintained that is incremented when an
666 * empty list is encountered. This is so more pages are freed
667 * off fuller lists instead of spinning excessively around empty
668 * lists
670 do {
671 batch_free++;
672 if (++migratetype == MIGRATE_PCPTYPES)
673 migratetype = 0;
674 list = &pcp->lists[migratetype];
675 } while (list_empty(list));
677 /* This is the only non-empty list. Free them all. */
678 if (batch_free == MIGRATE_PCPTYPES)
679 batch_free = to_free;
681 do {
682 int mt; /* migratetype of the to-be-freed page */
684 page = list_entry(list->prev, struct page, lru);
685 /* must delete as __free_one_page list manipulates */
686 list_del(&page->lru);
687 mt = get_freepage_migratetype(page);
688 /* MIGRATE_MOVABLE list may include MIGRATE_RESERVEs */
689 __free_one_page(page, zone, 0, mt);
690 trace_mm_page_pcpu_drain(page, 0, mt);
691 if (likely(!is_migrate_isolate_page(page))) {
692 __mod_zone_page_state(zone, NR_FREE_PAGES, 1);
693 if (is_migrate_cma(mt))
694 __mod_zone_page_state(zone, NR_FREE_CMA_PAGES, 1);
696 } while (--to_free && --batch_free && !list_empty(list));
698 spin_unlock(&zone->lock);
701 static void free_one_page(struct zone *zone, struct page *page, int order,
702 int migratetype)
704 spin_lock(&zone->lock);
705 zone->pages_scanned = 0;
707 __free_one_page(page, zone, order, migratetype);
708 if (unlikely(!is_migrate_isolate(migratetype)))
709 __mod_zone_freepage_state(zone, 1 << order, migratetype);
710 spin_unlock(&zone->lock);
713 static bool free_pages_prepare(struct page *page, unsigned int order)
715 int i;
716 int bad = 0;
718 trace_mm_page_free(page, order);
719 kmemcheck_free_shadow(page, order);
721 if (PageAnon(page))
722 page->mapping = NULL;
723 for (i = 0; i < (1 << order); i++)
724 bad += free_pages_check(page + i);
725 if (bad)
726 return false;
728 if (!PageHighMem(page)) {
729 debug_check_no_locks_freed(page_address(page),
730 PAGE_SIZE << order);
731 debug_check_no_obj_freed(page_address(page),
732 PAGE_SIZE << order);
734 arch_free_page(page, order);
735 kernel_map_pages(page, 1 << order, 0);
737 return true;
740 static void __free_pages_ok(struct page *page, unsigned int order)
742 unsigned long flags;
743 int migratetype;
745 if (!free_pages_prepare(page, order))
746 return;
748 local_irq_save(flags);
749 __count_vm_events(PGFREE, 1 << order);
750 migratetype = get_pageblock_migratetype(page);
751 set_freepage_migratetype(page, migratetype);
752 free_one_page(page_zone(page), page, order, migratetype);
753 local_irq_restore(flags);
756 void __init __free_pages_bootmem(struct page *page, unsigned int order)
758 unsigned int nr_pages = 1 << order;
759 struct page *p = page;
760 unsigned int loop;
762 prefetchw(p);
763 for (loop = 0; loop < (nr_pages - 1); loop++, p++) {
764 prefetchw(p + 1);
765 __ClearPageReserved(p);
766 set_page_count(p, 0);
768 __ClearPageReserved(p);
769 set_page_count(p, 0);
771 page_zone(page)->managed_pages += nr_pages;
772 set_page_refcounted(page);
773 __free_pages(page, order);
776 #ifdef CONFIG_CMA
777 /* Free whole pageblock and set its migration type to MIGRATE_CMA. */
778 void __init init_cma_reserved_pageblock(struct page *page)
780 unsigned i = pageblock_nr_pages;
781 struct page *p = page;
783 do {
784 __ClearPageReserved(p);
785 set_page_count(p, 0);
786 } while (++p, --i);
788 set_pageblock_migratetype(page, MIGRATE_CMA);
790 if (pageblock_order >= MAX_ORDER) {
791 i = pageblock_nr_pages;
792 p = page;
793 do {
794 set_page_refcounted(p);
795 __free_pages(p, MAX_ORDER - 1);
796 p += MAX_ORDER_NR_PAGES;
797 } while (i -= MAX_ORDER_NR_PAGES);
798 } else {
799 set_page_refcounted(page);
800 __free_pages(page, pageblock_order);
803 adjust_managed_page_count(page, pageblock_nr_pages);
805 #endif
808 * The order of subdivision here is critical for the IO subsystem.
809 * Please do not alter this order without good reasons and regression
810 * testing. Specifically, as large blocks of memory are subdivided,
811 * the order in which smaller blocks are delivered depends on the order
812 * they're subdivided in this function. This is the primary factor
813 * influencing the order in which pages are delivered to the IO
814 * subsystem according to empirical testing, and this is also justified
815 * by considering the behavior of a buddy system containing a single
816 * large block of memory acted on by a series of small allocations.
817 * This behavior is a critical factor in sglist merging's success.
819 * -- nyc
821 static inline void expand(struct zone *zone, struct page *page,
822 int low, int high, struct free_area *area,
823 int migratetype)
825 unsigned long size = 1 << high;
827 while (high > low) {
828 area--;
829 high--;
830 size >>= 1;
831 VM_BUG_ON(bad_range(zone, &page[size]));
833 #ifdef CONFIG_DEBUG_PAGEALLOC
834 if (high < debug_guardpage_minorder()) {
836 * Mark as guard pages (or page), that will allow to
837 * merge back to allocator when buddy will be freed.
838 * Corresponding page table entries will not be touched,
839 * pages will stay not present in virtual address space
841 INIT_LIST_HEAD(&page[size].lru);
842 set_page_guard_flag(&page[size]);
843 set_page_private(&page[size], high);
844 /* Guard pages are not available for any usage */
845 __mod_zone_freepage_state(zone, -(1 << high),
846 migratetype);
847 continue;
849 #endif
850 list_add(&page[size].lru, &area->free_list[migratetype]);
851 area->nr_free++;
852 set_page_order(&page[size], high);
857 * This page is about to be returned from the page allocator
859 static inline int check_new_page(struct page *page)
861 if (unlikely(page_mapcount(page) |
862 (page->mapping != NULL) |
863 (atomic_read(&page->_count) != 0) |
864 (page->flags & PAGE_FLAGS_CHECK_AT_PREP) |
865 (mem_cgroup_bad_page_check(page)))) {
866 bad_page(page);
867 return 1;
869 return 0;
872 static int prep_new_page(struct page *page, int order, gfp_t gfp_flags)
874 int i;
876 for (i = 0; i < (1 << order); i++) {
877 struct page *p = page + i;
878 if (unlikely(check_new_page(p)))
879 return 1;
882 set_page_private(page, 0);
883 set_page_refcounted(page);
885 arch_alloc_page(page, order);
886 kernel_map_pages(page, 1 << order, 1);
888 if (gfp_flags & __GFP_ZERO)
889 prep_zero_page(page, order, gfp_flags);
891 if (order && (gfp_flags & __GFP_COMP))
892 prep_compound_page(page, order);
894 return 0;
898 * Go through the free lists for the given migratetype and remove
899 * the smallest available page from the freelists
901 static inline
902 struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
903 int migratetype)
905 unsigned int current_order;
906 struct free_area *area;
907 struct page *page;
909 /* Find a page of the appropriate size in the preferred list */
910 for (current_order = order; current_order < MAX_ORDER; ++current_order) {
911 area = &(zone->free_area[current_order]);
912 if (list_empty(&area->free_list[migratetype]))
913 continue;
915 page = list_entry(area->free_list[migratetype].next,
916 struct page, lru);
917 list_del(&page->lru);
918 rmv_page_order(page);
919 area->nr_free--;
920 expand(zone, page, order, current_order, area, migratetype);
921 return page;
924 return NULL;
929 * This array describes the order lists are fallen back to when
930 * the free lists for the desirable migrate type are depleted
932 static int fallbacks[MIGRATE_TYPES][4] = {
933 [MIGRATE_UNMOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE, MIGRATE_RESERVE },
934 [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE, MIGRATE_MOVABLE, MIGRATE_RESERVE },
935 #ifdef CONFIG_CMA
936 [MIGRATE_MOVABLE] = { MIGRATE_CMA, MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_RESERVE },
937 [MIGRATE_CMA] = { MIGRATE_RESERVE }, /* Never used */
938 #else
939 [MIGRATE_MOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_RESERVE },
940 #endif
941 [MIGRATE_RESERVE] = { MIGRATE_RESERVE }, /* Never used */
942 #ifdef CONFIG_MEMORY_ISOLATION
943 [MIGRATE_ISOLATE] = { MIGRATE_RESERVE }, /* Never used */
944 #endif
948 * Move the free pages in a range to the free lists of the requested type.
949 * Note that start_page and end_pages are not aligned on a pageblock
950 * boundary. If alignment is required, use move_freepages_block()
952 int move_freepages(struct zone *zone,
953 struct page *start_page, struct page *end_page,
954 int migratetype)
956 struct page *page;
957 unsigned long order;
958 int pages_moved = 0;
960 #ifndef CONFIG_HOLES_IN_ZONE
962 * page_zone is not safe to call in this context when
963 * CONFIG_HOLES_IN_ZONE is set. This bug check is probably redundant
964 * anyway as we check zone boundaries in move_freepages_block().
965 * Remove at a later date when no bug reports exist related to
966 * grouping pages by mobility
968 BUG_ON(page_zone(start_page) != page_zone(end_page));
969 #endif
971 for (page = start_page; page <= end_page;) {
972 /* Make sure we are not inadvertently changing nodes */
973 VM_BUG_ON(page_to_nid(page) != zone_to_nid(zone));
975 if (!pfn_valid_within(page_to_pfn(page))) {
976 page++;
977 continue;
980 if (!PageBuddy(page)) {
981 page++;
982 continue;
985 order = page_order(page);
986 list_move(&page->lru,
987 &zone->free_area[order].free_list[migratetype]);
988 set_freepage_migratetype(page, migratetype);
989 page += 1 << order;
990 pages_moved += 1 << order;
993 return pages_moved;
996 int move_freepages_block(struct zone *zone, struct page *page,
997 int migratetype)
999 unsigned long start_pfn, end_pfn;
1000 struct page *start_page, *end_page;
1002 start_pfn = page_to_pfn(page);
1003 start_pfn = start_pfn & ~(pageblock_nr_pages-1);
1004 start_page = pfn_to_page(start_pfn);
1005 end_page = start_page + pageblock_nr_pages - 1;
1006 end_pfn = start_pfn + pageblock_nr_pages - 1;
1008 /* Do not cross zone boundaries */
1009 if (!zone_spans_pfn(zone, start_pfn))
1010 start_page = page;
1011 if (!zone_spans_pfn(zone, end_pfn))
1012 return 0;
1014 return move_freepages(zone, start_page, end_page, migratetype);
1017 static void change_pageblock_range(struct page *pageblock_page,
1018 int start_order, int migratetype)
1020 int nr_pageblocks = 1 << (start_order - pageblock_order);
1022 while (nr_pageblocks--) {
1023 set_pageblock_migratetype(pageblock_page, migratetype);
1024 pageblock_page += pageblock_nr_pages;
1029 * If breaking a large block of pages, move all free pages to the preferred
1030 * allocation list. If falling back for a reclaimable kernel allocation, be
1031 * more aggressive about taking ownership of free pages.
1033 * On the other hand, never change migration type of MIGRATE_CMA pageblocks
1034 * nor move CMA pages to different free lists. We don't want unmovable pages
1035 * to be allocated from MIGRATE_CMA areas.
1037 * Returns the new migratetype of the pageblock (or the same old migratetype
1038 * if it was unchanged).
1040 static int try_to_steal_freepages(struct zone *zone, struct page *page,
1041 int start_type, int fallback_type)
1043 int current_order = page_order(page);
1045 if (is_migrate_cma(fallback_type))
1046 return fallback_type;
1048 /* Take ownership for orders >= pageblock_order */
1049 if (current_order >= pageblock_order) {
1050 change_pageblock_range(page, current_order, start_type);
1051 return start_type;
1054 if (current_order >= pageblock_order / 2 ||
1055 start_type == MIGRATE_RECLAIMABLE ||
1056 page_group_by_mobility_disabled) {
1057 int pages;
1059 pages = move_freepages_block(zone, page, start_type);
1061 /* Claim the whole block if over half of it is free */
1062 if (pages >= (1 << (pageblock_order-1)) ||
1063 page_group_by_mobility_disabled) {
1065 set_pageblock_migratetype(page, start_type);
1066 return start_type;
1071 return fallback_type;
1074 /* Remove an element from the buddy allocator from the fallback list */
1075 static inline struct page *
1076 __rmqueue_fallback(struct zone *zone, int order, int start_migratetype)
1078 struct free_area *area;
1079 int current_order;
1080 struct page *page;
1081 int migratetype, new_type, i;
1083 /* Find the largest possible block of pages in the other list */
1084 for (current_order = MAX_ORDER-1; current_order >= order;
1085 --current_order) {
1086 for (i = 0;; i++) {
1087 migratetype = fallbacks[start_migratetype][i];
1089 /* MIGRATE_RESERVE handled later if necessary */
1090 if (migratetype == MIGRATE_RESERVE)
1091 break;
1093 area = &(zone->free_area[current_order]);
1094 if (list_empty(&area->free_list[migratetype]))
1095 continue;
1097 page = list_entry(area->free_list[migratetype].next,
1098 struct page, lru);
1099 area->nr_free--;
1101 new_type = try_to_steal_freepages(zone, page,
1102 start_migratetype,
1103 migratetype);
1105 /* Remove the page from the freelists */
1106 list_del(&page->lru);
1107 rmv_page_order(page);
1110 * Borrow the excess buddy pages as well, irrespective
1111 * of whether we stole freepages, or took ownership of
1112 * the pageblock or not.
1114 * Exception: When borrowing from MIGRATE_CMA, release
1115 * the excess buddy pages to CMA itself.
1117 expand(zone, page, order, current_order, area,
1118 is_migrate_cma(migratetype)
1119 ? migratetype : start_migratetype);
1121 trace_mm_page_alloc_extfrag(page, order,
1122 current_order, start_migratetype, migratetype,
1123 new_type == start_migratetype);
1125 return page;
1129 return NULL;
1133 * Do the hard work of removing an element from the buddy allocator.
1134 * Call me with the zone->lock already held.
1136 static struct page *__rmqueue(struct zone *zone, unsigned int order,
1137 int migratetype)
1139 struct page *page;
1141 retry_reserve:
1142 page = __rmqueue_smallest(zone, order, migratetype);
1144 if (unlikely(!page) && migratetype != MIGRATE_RESERVE) {
1145 page = __rmqueue_fallback(zone, order, migratetype);
1148 * Use MIGRATE_RESERVE rather than fail an allocation. goto
1149 * is used because __rmqueue_smallest is an inline function
1150 * and we want just one call site
1152 if (!page) {
1153 migratetype = MIGRATE_RESERVE;
1154 goto retry_reserve;
1158 trace_mm_page_alloc_zone_locked(page, order, migratetype);
1159 return page;
1163 * Obtain a specified number of elements from the buddy allocator, all under
1164 * a single hold of the lock, for efficiency. Add them to the supplied list.
1165 * Returns the number of new pages which were placed at *list.
1167 static int rmqueue_bulk(struct zone *zone, unsigned int order,
1168 unsigned long count, struct list_head *list,
1169 int migratetype, int cold)
1171 int mt = migratetype, i;
1173 spin_lock(&zone->lock);
1174 for (i = 0; i < count; ++i) {
1175 struct page *page = __rmqueue(zone, order, migratetype);
1176 if (unlikely(page == NULL))
1177 break;
1180 * Split buddy pages returned by expand() are received here
1181 * in physical page order. The page is added to the callers and
1182 * list and the list head then moves forward. From the callers
1183 * perspective, the linked list is ordered by page number in
1184 * some conditions. This is useful for IO devices that can
1185 * merge IO requests if the physical pages are ordered
1186 * properly.
1188 if (likely(cold == 0))
1189 list_add(&page->lru, list);
1190 else
1191 list_add_tail(&page->lru, list);
1192 if (IS_ENABLED(CONFIG_CMA)) {
1193 mt = get_pageblock_migratetype(page);
1194 if (!is_migrate_cma(mt) && !is_migrate_isolate(mt))
1195 mt = migratetype;
1197 set_freepage_migratetype(page, mt);
1198 list = &page->lru;
1199 if (is_migrate_cma(mt))
1200 __mod_zone_page_state(zone, NR_FREE_CMA_PAGES,
1201 -(1 << order));
1203 __mod_zone_page_state(zone, NR_FREE_PAGES, -(i << order));
1204 spin_unlock(&zone->lock);
1205 return i;
1208 #ifdef CONFIG_NUMA
1210 * Called from the vmstat counter updater to drain pagesets of this
1211 * currently executing processor on remote nodes after they have
1212 * expired.
1214 * Note that this function must be called with the thread pinned to
1215 * a single processor.
1217 void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp)
1219 unsigned long flags;
1220 int to_drain;
1221 unsigned long batch;
1223 local_irq_save(flags);
1224 batch = ACCESS_ONCE(pcp->batch);
1225 if (pcp->count >= batch)
1226 to_drain = batch;
1227 else
1228 to_drain = pcp->count;
1229 if (to_drain > 0) {
1230 free_pcppages_bulk(zone, to_drain, pcp);
1231 pcp->count -= to_drain;
1233 local_irq_restore(flags);
1235 #endif
1238 * Drain pages of the indicated processor.
1240 * The processor must either be the current processor and the
1241 * thread pinned to the current processor or a processor that
1242 * is not online.
1244 static void drain_pages(unsigned int cpu)
1246 unsigned long flags;
1247 struct zone *zone;
1249 for_each_populated_zone(zone) {
1250 struct per_cpu_pageset *pset;
1251 struct per_cpu_pages *pcp;
1253 local_irq_save(flags);
1254 pset = per_cpu_ptr(zone->pageset, cpu);
1256 pcp = &pset->pcp;
1257 if (pcp->count) {
1258 free_pcppages_bulk(zone, pcp->count, pcp);
1259 pcp->count = 0;
1261 local_irq_restore(flags);
1266 * Spill all of this CPU's per-cpu pages back into the buddy allocator.
1268 void drain_local_pages(void *arg)
1270 drain_pages(smp_processor_id());
1274 * Spill all the per-cpu pages from all CPUs back into the buddy allocator.
1276 * Note that this code is protected against sending an IPI to an offline
1277 * CPU but does not guarantee sending an IPI to newly hotplugged CPUs:
1278 * on_each_cpu_mask() blocks hotplug and won't talk to offlined CPUs but
1279 * nothing keeps CPUs from showing up after we populated the cpumask and
1280 * before the call to on_each_cpu_mask().
1282 void drain_all_pages(void)
1284 int cpu;
1285 struct per_cpu_pageset *pcp;
1286 struct zone *zone;
1289 * Allocate in the BSS so we wont require allocation in
1290 * direct reclaim path for CONFIG_CPUMASK_OFFSTACK=y
1292 static cpumask_t cpus_with_pcps;
1295 * We don't care about racing with CPU hotplug event
1296 * as offline notification will cause the notified
1297 * cpu to drain that CPU pcps and on_each_cpu_mask
1298 * disables preemption as part of its processing
1300 for_each_online_cpu(cpu) {
1301 bool has_pcps = false;
1302 for_each_populated_zone(zone) {
1303 pcp = per_cpu_ptr(zone->pageset, cpu);
1304 if (pcp->pcp.count) {
1305 has_pcps = true;
1306 break;
1309 if (has_pcps)
1310 cpumask_set_cpu(cpu, &cpus_with_pcps);
1311 else
1312 cpumask_clear_cpu(cpu, &cpus_with_pcps);
1314 on_each_cpu_mask(&cpus_with_pcps, drain_local_pages, NULL, 1);
1317 #ifdef CONFIG_HIBERNATION
1319 void mark_free_pages(struct zone *zone)
1321 unsigned long pfn, max_zone_pfn;
1322 unsigned long flags;
1323 int order, t;
1324 struct list_head *curr;
1326 if (zone_is_empty(zone))
1327 return;
1329 spin_lock_irqsave(&zone->lock, flags);
1331 max_zone_pfn = zone_end_pfn(zone);
1332 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
1333 if (pfn_valid(pfn)) {
1334 struct page *page = pfn_to_page(pfn);
1336 if (!swsusp_page_is_forbidden(page))
1337 swsusp_unset_page_free(page);
1340 for_each_migratetype_order(order, t) {
1341 list_for_each(curr, &zone->free_area[order].free_list[t]) {
1342 unsigned long i;
1344 pfn = page_to_pfn(list_entry(curr, struct page, lru));
1345 for (i = 0; i < (1UL << order); i++)
1346 swsusp_set_page_free(pfn_to_page(pfn + i));
1349 spin_unlock_irqrestore(&zone->lock, flags);
1351 #endif /* CONFIG_PM */
1354 * Free a 0-order page
1355 * cold == 1 ? free a cold page : free a hot page
1357 void free_hot_cold_page(struct page *page, int cold)
1359 struct zone *zone = page_zone(page);
1360 struct per_cpu_pages *pcp;
1361 unsigned long flags;
1362 int migratetype;
1364 if (!free_pages_prepare(page, 0))
1365 return;
1367 migratetype = get_pageblock_migratetype(page);
1368 set_freepage_migratetype(page, migratetype);
1369 local_irq_save(flags);
1370 __count_vm_event(PGFREE);
1373 * We only track unmovable, reclaimable and movable on pcp lists.
1374 * Free ISOLATE pages back to the allocator because they are being
1375 * offlined but treat RESERVE as movable pages so we can get those
1376 * areas back if necessary. Otherwise, we may have to free
1377 * excessively into the page allocator
1379 if (migratetype >= MIGRATE_PCPTYPES) {
1380 if (unlikely(is_migrate_isolate(migratetype))) {
1381 free_one_page(zone, page, 0, migratetype);
1382 goto out;
1384 migratetype = MIGRATE_MOVABLE;
1387 pcp = &this_cpu_ptr(zone->pageset)->pcp;
1388 if (cold)
1389 list_add_tail(&page->lru, &pcp->lists[migratetype]);
1390 else
1391 list_add(&page->lru, &pcp->lists[migratetype]);
1392 pcp->count++;
1393 if (pcp->count >= pcp->high) {
1394 unsigned long batch = ACCESS_ONCE(pcp->batch);
1395 free_pcppages_bulk(zone, batch, pcp);
1396 pcp->count -= batch;
1399 out:
1400 local_irq_restore(flags);
1404 * Free a list of 0-order pages
1406 void free_hot_cold_page_list(struct list_head *list, int cold)
1408 struct page *page, *next;
1410 list_for_each_entry_safe(page, next, list, lru) {
1411 trace_mm_page_free_batched(page, cold);
1412 free_hot_cold_page(page, cold);
1417 * split_page takes a non-compound higher-order page, and splits it into
1418 * n (1<<order) sub-pages: page[0..n]
1419 * Each sub-page must be freed individually.
1421 * Note: this is probably too low level an operation for use in drivers.
1422 * Please consult with lkml before using this in your driver.
1424 void split_page(struct page *page, unsigned int order)
1426 int i;
1428 VM_BUG_ON(PageCompound(page));
1429 VM_BUG_ON(!page_count(page));
1431 #ifdef CONFIG_KMEMCHECK
1433 * Split shadow pages too, because free(page[0]) would
1434 * otherwise free the whole shadow.
1436 if (kmemcheck_page_is_tracked(page))
1437 split_page(virt_to_page(page[0].shadow), order);
1438 #endif
1440 for (i = 1; i < (1 << order); i++)
1441 set_page_refcounted(page + i);
1443 EXPORT_SYMBOL_GPL(split_page);
1445 static int __isolate_free_page(struct page *page, unsigned int order)
1447 unsigned long watermark;
1448 struct zone *zone;
1449 int mt;
1451 BUG_ON(!PageBuddy(page));
1453 zone = page_zone(page);
1454 mt = get_pageblock_migratetype(page);
1456 if (!is_migrate_isolate(mt)) {
1457 /* Obey watermarks as if the page was being allocated */
1458 watermark = low_wmark_pages(zone) + (1 << order);
1459 if (!zone_watermark_ok(zone, 0, watermark, 0, 0))
1460 return 0;
1462 __mod_zone_freepage_state(zone, -(1UL << order), mt);
1465 /* Remove page from free list */
1466 list_del(&page->lru);
1467 zone->free_area[order].nr_free--;
1468 rmv_page_order(page);
1470 /* Set the pageblock if the isolated page is at least a pageblock */
1471 if (order >= pageblock_order - 1) {
1472 struct page *endpage = page + (1 << order) - 1;
1473 for (; page < endpage; page += pageblock_nr_pages) {
1474 int mt = get_pageblock_migratetype(page);
1475 if (!is_migrate_isolate(mt) && !is_migrate_cma(mt))
1476 set_pageblock_migratetype(page,
1477 MIGRATE_MOVABLE);
1481 return 1UL << order;
1485 * Similar to split_page except the page is already free. As this is only
1486 * being used for migration, the migratetype of the block also changes.
1487 * As this is called with interrupts disabled, the caller is responsible
1488 * for calling arch_alloc_page() and kernel_map_page() after interrupts
1489 * are enabled.
1491 * Note: this is probably too low level an operation for use in drivers.
1492 * Please consult with lkml before using this in your driver.
1494 int split_free_page(struct page *page)
1496 unsigned int order;
1497 int nr_pages;
1499 order = page_order(page);
1501 nr_pages = __isolate_free_page(page, order);
1502 if (!nr_pages)
1503 return 0;
1505 /* Split into individual pages */
1506 set_page_refcounted(page);
1507 split_page(page, order);
1508 return nr_pages;
1512 * Really, prep_compound_page() should be called from __rmqueue_bulk(). But
1513 * we cheat by calling it from here, in the order > 0 path. Saves a branch
1514 * or two.
1516 static inline
1517 struct page *buffered_rmqueue(struct zone *preferred_zone,
1518 struct zone *zone, int order, gfp_t gfp_flags,
1519 int migratetype)
1521 unsigned long flags;
1522 struct page *page;
1523 int cold = !!(gfp_flags & __GFP_COLD);
1525 again:
1526 if (likely(order == 0)) {
1527 struct per_cpu_pages *pcp;
1528 struct list_head *list;
1530 local_irq_save(flags);
1531 pcp = &this_cpu_ptr(zone->pageset)->pcp;
1532 list = &pcp->lists[migratetype];
1533 if (list_empty(list)) {
1534 pcp->count += rmqueue_bulk(zone, 0,
1535 pcp->batch, list,
1536 migratetype, cold);
1537 if (unlikely(list_empty(list)))
1538 goto failed;
1541 if (cold)
1542 page = list_entry(list->prev, struct page, lru);
1543 else
1544 page = list_entry(list->next, struct page, lru);
1546 list_del(&page->lru);
1547 pcp->count--;
1548 } else {
1549 if (unlikely(gfp_flags & __GFP_NOFAIL)) {
1551 * __GFP_NOFAIL is not to be used in new code.
1553 * All __GFP_NOFAIL callers should be fixed so that they
1554 * properly detect and handle allocation failures.
1556 * We most definitely don't want callers attempting to
1557 * allocate greater than order-1 page units with
1558 * __GFP_NOFAIL.
1560 WARN_ON_ONCE(order > 1);
1562 spin_lock_irqsave(&zone->lock, flags);
1563 page = __rmqueue(zone, order, migratetype);
1564 spin_unlock(&zone->lock);
1565 if (!page)
1566 goto failed;
1567 __mod_zone_freepage_state(zone, -(1 << order),
1568 get_pageblock_migratetype(page));
1571 __mod_zone_page_state(zone, NR_ALLOC_BATCH, -(1 << order));
1573 __count_zone_vm_events(PGALLOC, zone, 1 << order);
1574 zone_statistics(preferred_zone, zone, gfp_flags);
1575 local_irq_restore(flags);
1577 VM_BUG_ON(bad_range(zone, page));
1578 if (prep_new_page(page, order, gfp_flags))
1579 goto again;
1580 return page;
1582 failed:
1583 local_irq_restore(flags);
1584 return NULL;
1587 #ifdef CONFIG_FAIL_PAGE_ALLOC
1589 static struct {
1590 struct fault_attr attr;
1592 u32 ignore_gfp_highmem;
1593 u32 ignore_gfp_wait;
1594 u32 min_order;
1595 } fail_page_alloc = {
1596 .attr = FAULT_ATTR_INITIALIZER,
1597 .ignore_gfp_wait = 1,
1598 .ignore_gfp_highmem = 1,
1599 .min_order = 1,
1602 static int __init setup_fail_page_alloc(char *str)
1604 return setup_fault_attr(&fail_page_alloc.attr, str);
1606 __setup("fail_page_alloc=", setup_fail_page_alloc);
1608 static bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
1610 if (order < fail_page_alloc.min_order)
1611 return false;
1612 if (gfp_mask & __GFP_NOFAIL)
1613 return false;
1614 if (fail_page_alloc.ignore_gfp_highmem && (gfp_mask & __GFP_HIGHMEM))
1615 return false;
1616 if (fail_page_alloc.ignore_gfp_wait && (gfp_mask & __GFP_WAIT))
1617 return false;
1619 return should_fail(&fail_page_alloc.attr, 1 << order);
1622 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
1624 static int __init fail_page_alloc_debugfs(void)
1626 umode_t mode = S_IFREG | S_IRUSR | S_IWUSR;
1627 struct dentry *dir;
1629 dir = fault_create_debugfs_attr("fail_page_alloc", NULL,
1630 &fail_page_alloc.attr);
1631 if (IS_ERR(dir))
1632 return PTR_ERR(dir);
1634 if (!debugfs_create_bool("ignore-gfp-wait", mode, dir,
1635 &fail_page_alloc.ignore_gfp_wait))
1636 goto fail;
1637 if (!debugfs_create_bool("ignore-gfp-highmem", mode, dir,
1638 &fail_page_alloc.ignore_gfp_highmem))
1639 goto fail;
1640 if (!debugfs_create_u32("min-order", mode, dir,
1641 &fail_page_alloc.min_order))
1642 goto fail;
1644 return 0;
1645 fail:
1646 debugfs_remove_recursive(dir);
1648 return -ENOMEM;
1651 late_initcall(fail_page_alloc_debugfs);
1653 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
1655 #else /* CONFIG_FAIL_PAGE_ALLOC */
1657 static inline bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
1659 return false;
1662 #endif /* CONFIG_FAIL_PAGE_ALLOC */
1665 * Return true if free pages are above 'mark'. This takes into account the order
1666 * of the allocation.
1668 static bool __zone_watermark_ok(struct zone *z, int order, unsigned long mark,
1669 int classzone_idx, int alloc_flags, long free_pages)
1671 /* free_pages my go negative - that's OK */
1672 long min = mark;
1673 long lowmem_reserve = z->lowmem_reserve[classzone_idx];
1674 int o;
1675 long free_cma = 0;
1677 free_pages -= (1 << order) - 1;
1678 if (alloc_flags & ALLOC_HIGH)
1679 min -= min / 2;
1680 if (alloc_flags & ALLOC_HARDER)
1681 min -= min / 4;
1682 #ifdef CONFIG_CMA
1683 /* If allocation can't use CMA areas don't use free CMA pages */
1684 if (!(alloc_flags & ALLOC_CMA))
1685 free_cma = zone_page_state(z, NR_FREE_CMA_PAGES);
1686 #endif
1688 if (free_pages - free_cma <= min + lowmem_reserve)
1689 return false;
1690 for (o = 0; o < order; o++) {
1691 /* At the next order, this order's pages become unavailable */
1692 free_pages -= z->free_area[o].nr_free << o;
1694 /* Require fewer higher order pages to be free */
1695 min >>= 1;
1697 if (free_pages <= min)
1698 return false;
1700 return true;
1703 bool zone_watermark_ok(struct zone *z, int order, unsigned long mark,
1704 int classzone_idx, int alloc_flags)
1706 return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
1707 zone_page_state(z, NR_FREE_PAGES));
1710 bool zone_watermark_ok_safe(struct zone *z, int order, unsigned long mark,
1711 int classzone_idx, int alloc_flags)
1713 long free_pages = zone_page_state(z, NR_FREE_PAGES);
1715 if (z->percpu_drift_mark && free_pages < z->percpu_drift_mark)
1716 free_pages = zone_page_state_snapshot(z, NR_FREE_PAGES);
1718 return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
1719 free_pages);
1722 #ifdef CONFIG_NUMA
1724 * zlc_setup - Setup for "zonelist cache". Uses cached zone data to
1725 * skip over zones that are not allowed by the cpuset, or that have
1726 * been recently (in last second) found to be nearly full. See further
1727 * comments in mmzone.h. Reduces cache footprint of zonelist scans
1728 * that have to skip over a lot of full or unallowed zones.
1730 * If the zonelist cache is present in the passed in zonelist, then
1731 * returns a pointer to the allowed node mask (either the current
1732 * tasks mems_allowed, or node_states[N_MEMORY].)
1734 * If the zonelist cache is not available for this zonelist, does
1735 * nothing and returns NULL.
1737 * If the fullzones BITMAP in the zonelist cache is stale (more than
1738 * a second since last zap'd) then we zap it out (clear its bits.)
1740 * We hold off even calling zlc_setup, until after we've checked the
1741 * first zone in the zonelist, on the theory that most allocations will
1742 * be satisfied from that first zone, so best to examine that zone as
1743 * quickly as we can.
1745 static nodemask_t *zlc_setup(struct zonelist *zonelist, int alloc_flags)
1747 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1748 nodemask_t *allowednodes; /* zonelist_cache approximation */
1750 zlc = zonelist->zlcache_ptr;
1751 if (!zlc)
1752 return NULL;
1754 if (time_after(jiffies, zlc->last_full_zap + HZ)) {
1755 bitmap_zero(zlc->fullzones, MAX_ZONES_PER_ZONELIST);
1756 zlc->last_full_zap = jiffies;
1759 allowednodes = !in_interrupt() && (alloc_flags & ALLOC_CPUSET) ?
1760 &cpuset_current_mems_allowed :
1761 &node_states[N_MEMORY];
1762 return allowednodes;
1766 * Given 'z' scanning a zonelist, run a couple of quick checks to see
1767 * if it is worth looking at further for free memory:
1768 * 1) Check that the zone isn't thought to be full (doesn't have its
1769 * bit set in the zonelist_cache fullzones BITMAP).
1770 * 2) Check that the zones node (obtained from the zonelist_cache
1771 * z_to_n[] mapping) is allowed in the passed in allowednodes mask.
1772 * Return true (non-zero) if zone is worth looking at further, or
1773 * else return false (zero) if it is not.
1775 * This check -ignores- the distinction between various watermarks,
1776 * such as GFP_HIGH, GFP_ATOMIC, PF_MEMALLOC, ... If a zone is
1777 * found to be full for any variation of these watermarks, it will
1778 * be considered full for up to one second by all requests, unless
1779 * we are so low on memory on all allowed nodes that we are forced
1780 * into the second scan of the zonelist.
1782 * In the second scan we ignore this zonelist cache and exactly
1783 * apply the watermarks to all zones, even it is slower to do so.
1784 * We are low on memory in the second scan, and should leave no stone
1785 * unturned looking for a free page.
1787 static int zlc_zone_worth_trying(struct zonelist *zonelist, struct zoneref *z,
1788 nodemask_t *allowednodes)
1790 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1791 int i; /* index of *z in zonelist zones */
1792 int n; /* node that zone *z is on */
1794 zlc = zonelist->zlcache_ptr;
1795 if (!zlc)
1796 return 1;
1798 i = z - zonelist->_zonerefs;
1799 n = zlc->z_to_n[i];
1801 /* This zone is worth trying if it is allowed but not full */
1802 return node_isset(n, *allowednodes) && !test_bit(i, zlc->fullzones);
1806 * Given 'z' scanning a zonelist, set the corresponding bit in
1807 * zlc->fullzones, so that subsequent attempts to allocate a page
1808 * from that zone don't waste time re-examining it.
1810 static void zlc_mark_zone_full(struct zonelist *zonelist, struct zoneref *z)
1812 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1813 int i; /* index of *z in zonelist zones */
1815 zlc = zonelist->zlcache_ptr;
1816 if (!zlc)
1817 return;
1819 i = z - zonelist->_zonerefs;
1821 set_bit(i, zlc->fullzones);
1825 * clear all zones full, called after direct reclaim makes progress so that
1826 * a zone that was recently full is not skipped over for up to a second
1828 static void zlc_clear_zones_full(struct zonelist *zonelist)
1830 struct zonelist_cache *zlc; /* cached zonelist speedup info */
1832 zlc = zonelist->zlcache_ptr;
1833 if (!zlc)
1834 return;
1836 bitmap_zero(zlc->fullzones, MAX_ZONES_PER_ZONELIST);
1839 static bool zone_local(struct zone *local_zone, struct zone *zone)
1841 return local_zone->node == zone->node;
1844 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
1846 return node_isset(local_zone->node, zone->zone_pgdat->reclaim_nodes);
1849 static void __paginginit init_zone_allows_reclaim(int nid)
1851 int i;
1853 for_each_online_node(i)
1854 if (node_distance(nid, i) <= RECLAIM_DISTANCE)
1855 node_set(i, NODE_DATA(nid)->reclaim_nodes);
1856 else
1857 zone_reclaim_mode = 1;
1860 #else /* CONFIG_NUMA */
1862 static nodemask_t *zlc_setup(struct zonelist *zonelist, int alloc_flags)
1864 return NULL;
1867 static int zlc_zone_worth_trying(struct zonelist *zonelist, struct zoneref *z,
1868 nodemask_t *allowednodes)
1870 return 1;
1873 static void zlc_mark_zone_full(struct zonelist *zonelist, struct zoneref *z)
1877 static void zlc_clear_zones_full(struct zonelist *zonelist)
1881 static bool zone_local(struct zone *local_zone, struct zone *zone)
1883 return true;
1886 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
1888 return true;
1891 static inline void init_zone_allows_reclaim(int nid)
1894 #endif /* CONFIG_NUMA */
1897 * get_page_from_freelist goes through the zonelist trying to allocate
1898 * a page.
1900 static struct page *
1901 get_page_from_freelist(gfp_t gfp_mask, nodemask_t *nodemask, unsigned int order,
1902 struct zonelist *zonelist, int high_zoneidx, int alloc_flags,
1903 struct zone *preferred_zone, int migratetype)
1905 struct zoneref *z;
1906 struct page *page = NULL;
1907 int classzone_idx;
1908 struct zone *zone;
1909 nodemask_t *allowednodes = NULL;/* zonelist_cache approximation */
1910 int zlc_active = 0; /* set if using zonelist_cache */
1911 int did_zlc_setup = 0; /* just call zlc_setup() one time */
1913 classzone_idx = zone_idx(preferred_zone);
1914 zonelist_scan:
1916 * Scan zonelist, looking for a zone with enough free.
1917 * See also __cpuset_node_allowed_softwall() comment in kernel/cpuset.c.
1919 for_each_zone_zonelist_nodemask(zone, z, zonelist,
1920 high_zoneidx, nodemask) {
1921 unsigned long mark;
1923 if (IS_ENABLED(CONFIG_NUMA) && zlc_active &&
1924 !zlc_zone_worth_trying(zonelist, z, allowednodes))
1925 continue;
1926 if ((alloc_flags & ALLOC_CPUSET) &&
1927 !cpuset_zone_allowed_softwall(zone, gfp_mask))
1928 continue;
1929 BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK);
1930 if (unlikely(alloc_flags & ALLOC_NO_WATERMARKS))
1931 goto try_this_zone;
1933 * Distribute pages in proportion to the individual
1934 * zone size to ensure fair page aging. The zone a
1935 * page was allocated in should have no effect on the
1936 * time the page has in memory before being reclaimed.
1938 if (alloc_flags & ALLOC_FAIR) {
1939 if (!zone_local(preferred_zone, zone))
1940 continue;
1941 if (zone_page_state(zone, NR_ALLOC_BATCH) <= 0)
1942 continue;
1945 * When allocating a page cache page for writing, we
1946 * want to get it from a zone that is within its dirty
1947 * limit, such that no single zone holds more than its
1948 * proportional share of globally allowed dirty pages.
1949 * The dirty limits take into account the zone's
1950 * lowmem reserves and high watermark so that kswapd
1951 * should be able to balance it without having to
1952 * write pages from its LRU list.
1954 * This may look like it could increase pressure on
1955 * lower zones by failing allocations in higher zones
1956 * before they are full. But the pages that do spill
1957 * over are limited as the lower zones are protected
1958 * by this very same mechanism. It should not become
1959 * a practical burden to them.
1961 * XXX: For now, allow allocations to potentially
1962 * exceed the per-zone dirty limit in the slowpath
1963 * (ALLOC_WMARK_LOW unset) before going into reclaim,
1964 * which is important when on a NUMA setup the allowed
1965 * zones are together not big enough to reach the
1966 * global limit. The proper fix for these situations
1967 * will require awareness of zones in the
1968 * dirty-throttling and the flusher threads.
1970 if ((alloc_flags & ALLOC_WMARK_LOW) &&
1971 (gfp_mask & __GFP_WRITE) && !zone_dirty_ok(zone))
1972 goto this_zone_full;
1974 mark = zone->watermark[alloc_flags & ALLOC_WMARK_MASK];
1975 if (!zone_watermark_ok(zone, order, mark,
1976 classzone_idx, alloc_flags)) {
1977 int ret;
1979 if (IS_ENABLED(CONFIG_NUMA) &&
1980 !did_zlc_setup && nr_online_nodes > 1) {
1982 * we do zlc_setup if there are multiple nodes
1983 * and before considering the first zone allowed
1984 * by the cpuset.
1986 allowednodes = zlc_setup(zonelist, alloc_flags);
1987 zlc_active = 1;
1988 did_zlc_setup = 1;
1991 if (zone_reclaim_mode == 0 ||
1992 !zone_allows_reclaim(preferred_zone, zone))
1993 goto this_zone_full;
1996 * As we may have just activated ZLC, check if the first
1997 * eligible zone has failed zone_reclaim recently.
1999 if (IS_ENABLED(CONFIG_NUMA) && zlc_active &&
2000 !zlc_zone_worth_trying(zonelist, z, allowednodes))
2001 continue;
2003 ret = zone_reclaim(zone, gfp_mask, order);
2004 switch (ret) {
2005 case ZONE_RECLAIM_NOSCAN:
2006 /* did not scan */
2007 continue;
2008 case ZONE_RECLAIM_FULL:
2009 /* scanned but unreclaimable */
2010 continue;
2011 default:
2012 /* did we reclaim enough */
2013 if (zone_watermark_ok(zone, order, mark,
2014 classzone_idx, alloc_flags))
2015 goto try_this_zone;
2018 * Failed to reclaim enough to meet watermark.
2019 * Only mark the zone full if checking the min
2020 * watermark or if we failed to reclaim just
2021 * 1<<order pages or else the page allocator
2022 * fastpath will prematurely mark zones full
2023 * when the watermark is between the low and
2024 * min watermarks.
2026 if (((alloc_flags & ALLOC_WMARK_MASK) == ALLOC_WMARK_MIN) ||
2027 ret == ZONE_RECLAIM_SOME)
2028 goto this_zone_full;
2030 continue;
2034 try_this_zone:
2035 page = buffered_rmqueue(preferred_zone, zone, order,
2036 gfp_mask, migratetype);
2037 if (page)
2038 break;
2039 this_zone_full:
2040 if (IS_ENABLED(CONFIG_NUMA))
2041 zlc_mark_zone_full(zonelist, z);
2044 if (unlikely(IS_ENABLED(CONFIG_NUMA) && page == NULL && zlc_active)) {
2045 /* Disable zlc cache for second zonelist scan */
2046 zlc_active = 0;
2047 goto zonelist_scan;
2050 if (page)
2052 * page->pfmemalloc is set when ALLOC_NO_WATERMARKS was
2053 * necessary to allocate the page. The expectation is
2054 * that the caller is taking steps that will free more
2055 * memory. The caller should avoid the page being used
2056 * for !PFMEMALLOC purposes.
2058 page->pfmemalloc = !!(alloc_flags & ALLOC_NO_WATERMARKS);
2060 return page;
2064 * Large machines with many possible nodes should not always dump per-node
2065 * meminfo in irq context.
2067 static inline bool should_suppress_show_mem(void)
2069 bool ret = false;
2071 #if NODES_SHIFT > 8
2072 ret = in_interrupt();
2073 #endif
2074 return ret;
2077 static DEFINE_RATELIMIT_STATE(nopage_rs,
2078 DEFAULT_RATELIMIT_INTERVAL,
2079 DEFAULT_RATELIMIT_BURST);
2081 void warn_alloc_failed(gfp_t gfp_mask, int order, const char *fmt, ...)
2083 unsigned int filter = SHOW_MEM_FILTER_NODES;
2085 if ((gfp_mask & __GFP_NOWARN) || !__ratelimit(&nopage_rs) ||
2086 debug_guardpage_minorder() > 0)
2087 return;
2090 * Walking all memory to count page types is very expensive and should
2091 * be inhibited in non-blockable contexts.
2093 if (!(gfp_mask & __GFP_WAIT))
2094 filter |= SHOW_MEM_FILTER_PAGE_COUNT;
2097 * This documents exceptions given to allocations in certain
2098 * contexts that are allowed to allocate outside current's set
2099 * of allowed nodes.
2101 if (!(gfp_mask & __GFP_NOMEMALLOC))
2102 if (test_thread_flag(TIF_MEMDIE) ||
2103 (current->flags & (PF_MEMALLOC | PF_EXITING)))
2104 filter &= ~SHOW_MEM_FILTER_NODES;
2105 if (in_interrupt() || !(gfp_mask & __GFP_WAIT))
2106 filter &= ~SHOW_MEM_FILTER_NODES;
2108 if (fmt) {
2109 struct va_format vaf;
2110 va_list args;
2112 va_start(args, fmt);
2114 vaf.fmt = fmt;
2115 vaf.va = &args;
2117 pr_warn("%pV", &vaf);
2119 va_end(args);
2122 pr_warn("%s: page allocation failure: order:%d, mode:0x%x\n",
2123 current->comm, order, gfp_mask);
2125 dump_stack();
2126 if (!should_suppress_show_mem())
2127 show_mem(filter);
2130 static inline int
2131 should_alloc_retry(gfp_t gfp_mask, unsigned int order,
2132 unsigned long did_some_progress,
2133 unsigned long pages_reclaimed)
2135 /* Do not loop if specifically requested */
2136 if (gfp_mask & __GFP_NORETRY)
2137 return 0;
2139 /* Always retry if specifically requested */
2140 if (gfp_mask & __GFP_NOFAIL)
2141 return 1;
2144 * Suspend converts GFP_KERNEL to __GFP_WAIT which can prevent reclaim
2145 * making forward progress without invoking OOM. Suspend also disables
2146 * storage devices so kswapd will not help. Bail if we are suspending.
2148 if (!did_some_progress && pm_suspended_storage())
2149 return 0;
2152 * In this implementation, order <= PAGE_ALLOC_COSTLY_ORDER
2153 * means __GFP_NOFAIL, but that may not be true in other
2154 * implementations.
2156 if (order <= PAGE_ALLOC_COSTLY_ORDER)
2157 return 1;
2160 * For order > PAGE_ALLOC_COSTLY_ORDER, if __GFP_REPEAT is
2161 * specified, then we retry until we no longer reclaim any pages
2162 * (above), or we've reclaimed an order of pages at least as
2163 * large as the allocation's order. In both cases, if the
2164 * allocation still fails, we stop retrying.
2166 if (gfp_mask & __GFP_REPEAT && pages_reclaimed < (1 << order))
2167 return 1;
2169 return 0;
2172 static inline struct page *
2173 __alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order,
2174 struct zonelist *zonelist, enum zone_type high_zoneidx,
2175 nodemask_t *nodemask, struct zone *preferred_zone,
2176 int migratetype)
2178 struct page *page;
2180 /* Acquire the OOM killer lock for the zones in zonelist */
2181 if (!try_set_zonelist_oom(zonelist, gfp_mask)) {
2182 schedule_timeout_uninterruptible(1);
2183 return NULL;
2187 * Go through the zonelist yet one more time, keep very high watermark
2188 * here, this is only to catch a parallel oom killing, we must fail if
2189 * we're still under heavy pressure.
2191 page = get_page_from_freelist(gfp_mask|__GFP_HARDWALL, nodemask,
2192 order, zonelist, high_zoneidx,
2193 ALLOC_WMARK_HIGH|ALLOC_CPUSET,
2194 preferred_zone, migratetype);
2195 if (page)
2196 goto out;
2198 if (!(gfp_mask & __GFP_NOFAIL)) {
2199 /* The OOM killer will not help higher order allocs */
2200 if (order > PAGE_ALLOC_COSTLY_ORDER)
2201 goto out;
2202 /* The OOM killer does not needlessly kill tasks for lowmem */
2203 if (high_zoneidx < ZONE_NORMAL)
2204 goto out;
2206 * GFP_THISNODE contains __GFP_NORETRY and we never hit this.
2207 * Sanity check for bare calls of __GFP_THISNODE, not real OOM.
2208 * The caller should handle page allocation failure by itself if
2209 * it specifies __GFP_THISNODE.
2210 * Note: Hugepage uses it but will hit PAGE_ALLOC_COSTLY_ORDER.
2212 if (gfp_mask & __GFP_THISNODE)
2213 goto out;
2215 /* Exhausted what can be done so it's blamo time */
2216 out_of_memory(zonelist, gfp_mask, order, nodemask, false);
2218 out:
2219 clear_zonelist_oom(zonelist, gfp_mask);
2220 return page;
2223 #ifdef CONFIG_COMPACTION
2224 /* Try memory compaction for high-order allocations before reclaim */
2225 static struct page *
2226 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
2227 struct zonelist *zonelist, enum zone_type high_zoneidx,
2228 nodemask_t *nodemask, int alloc_flags, struct zone *preferred_zone,
2229 int migratetype, bool sync_migration,
2230 bool *contended_compaction, bool *deferred_compaction,
2231 unsigned long *did_some_progress)
2233 if (!order)
2234 return NULL;
2236 if (compaction_deferred(preferred_zone, order)) {
2237 *deferred_compaction = true;
2238 return NULL;
2241 current->flags |= PF_MEMALLOC;
2242 *did_some_progress = try_to_compact_pages(zonelist, order, gfp_mask,
2243 nodemask, sync_migration,
2244 contended_compaction);
2245 current->flags &= ~PF_MEMALLOC;
2247 if (*did_some_progress != COMPACT_SKIPPED) {
2248 struct page *page;
2250 /* Page migration frees to the PCP lists but we want merging */
2251 drain_pages(get_cpu());
2252 put_cpu();
2254 page = get_page_from_freelist(gfp_mask, nodemask,
2255 order, zonelist, high_zoneidx,
2256 alloc_flags & ~ALLOC_NO_WATERMARKS,
2257 preferred_zone, migratetype);
2258 if (page) {
2259 preferred_zone->compact_blockskip_flush = false;
2260 preferred_zone->compact_considered = 0;
2261 preferred_zone->compact_defer_shift = 0;
2262 if (order >= preferred_zone->compact_order_failed)
2263 preferred_zone->compact_order_failed = order + 1;
2264 count_vm_event(COMPACTSUCCESS);
2265 return page;
2269 * It's bad if compaction run occurs and fails.
2270 * The most likely reason is that pages exist,
2271 * but not enough to satisfy watermarks.
2273 count_vm_event(COMPACTFAIL);
2276 * As async compaction considers a subset of pageblocks, only
2277 * defer if the failure was a sync compaction failure.
2279 if (sync_migration)
2280 defer_compaction(preferred_zone, order);
2282 cond_resched();
2285 return NULL;
2287 #else
2288 static inline struct page *
2289 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
2290 struct zonelist *zonelist, enum zone_type high_zoneidx,
2291 nodemask_t *nodemask, int alloc_flags, struct zone *preferred_zone,
2292 int migratetype, bool sync_migration,
2293 bool *contended_compaction, bool *deferred_compaction,
2294 unsigned long *did_some_progress)
2296 return NULL;
2298 #endif /* CONFIG_COMPACTION */
2300 /* Perform direct synchronous page reclaim */
2301 static int
2302 __perform_reclaim(gfp_t gfp_mask, unsigned int order, struct zonelist *zonelist,
2303 nodemask_t *nodemask)
2305 struct reclaim_state reclaim_state;
2306 int progress;
2308 cond_resched();
2310 /* We now go into synchronous reclaim */
2311 cpuset_memory_pressure_bump();
2312 current->flags |= PF_MEMALLOC;
2313 lockdep_set_current_reclaim_state(gfp_mask);
2314 reclaim_state.reclaimed_slab = 0;
2315 current->reclaim_state = &reclaim_state;
2317 progress = try_to_free_pages(zonelist, order, gfp_mask, nodemask);
2319 current->reclaim_state = NULL;
2320 lockdep_clear_current_reclaim_state();
2321 current->flags &= ~PF_MEMALLOC;
2323 cond_resched();
2325 return progress;
2328 /* The really slow allocator path where we enter direct reclaim */
2329 static inline struct page *
2330 __alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order,
2331 struct zonelist *zonelist, enum zone_type high_zoneidx,
2332 nodemask_t *nodemask, int alloc_flags, struct zone *preferred_zone,
2333 int migratetype, unsigned long *did_some_progress)
2335 struct page *page = NULL;
2336 bool drained = false;
2338 *did_some_progress = __perform_reclaim(gfp_mask, order, zonelist,
2339 nodemask);
2340 if (unlikely(!(*did_some_progress)))
2341 return NULL;
2343 /* After successful reclaim, reconsider all zones for allocation */
2344 if (IS_ENABLED(CONFIG_NUMA))
2345 zlc_clear_zones_full(zonelist);
2347 retry:
2348 page = get_page_from_freelist(gfp_mask, nodemask, order,
2349 zonelist, high_zoneidx,
2350 alloc_flags & ~ALLOC_NO_WATERMARKS,
2351 preferred_zone, migratetype);
2354 * If an allocation failed after direct reclaim, it could be because
2355 * pages are pinned on the per-cpu lists. Drain them and try again
2357 if (!page && !drained) {
2358 drain_all_pages();
2359 drained = true;
2360 goto retry;
2363 return page;
2367 * This is called in the allocator slow-path if the allocation request is of
2368 * sufficient urgency to ignore watermarks and take other desperate measures
2370 static inline struct page *
2371 __alloc_pages_high_priority(gfp_t gfp_mask, unsigned int order,
2372 struct zonelist *zonelist, enum zone_type high_zoneidx,
2373 nodemask_t *nodemask, struct zone *preferred_zone,
2374 int migratetype)
2376 struct page *page;
2378 do {
2379 page = get_page_from_freelist(gfp_mask, nodemask, order,
2380 zonelist, high_zoneidx, ALLOC_NO_WATERMARKS,
2381 preferred_zone, migratetype);
2383 if (!page && gfp_mask & __GFP_NOFAIL)
2384 wait_iff_congested(preferred_zone, BLK_RW_ASYNC, HZ/50);
2385 } while (!page && (gfp_mask & __GFP_NOFAIL));
2387 return page;
2390 static void reset_alloc_batches(struct zonelist *zonelist,
2391 enum zone_type high_zoneidx,
2392 struct zone *preferred_zone)
2394 struct zoneref *z;
2395 struct zone *zone;
2397 for_each_zone_zonelist(zone, z, zonelist, high_zoneidx) {
2399 * Only reset the batches of zones that were actually
2400 * considered in the fairness pass, we don't want to
2401 * trash fairness information for zones that are not
2402 * actually part of this zonelist's round-robin cycle.
2404 if (!zone_local(preferred_zone, zone))
2405 continue;
2406 mod_zone_page_state(zone, NR_ALLOC_BATCH,
2407 high_wmark_pages(zone) - low_wmark_pages(zone) -
2408 atomic_long_read(&zone->vm_stat[NR_ALLOC_BATCH]));
2412 static void wake_all_kswapds(unsigned int order,
2413 struct zonelist *zonelist,
2414 enum zone_type high_zoneidx,
2415 struct zone *preferred_zone)
2417 struct zoneref *z;
2418 struct zone *zone;
2420 for_each_zone_zonelist(zone, z, zonelist, high_zoneidx)
2421 wakeup_kswapd(zone, order, zone_idx(preferred_zone));
2424 static inline int
2425 gfp_to_alloc_flags(gfp_t gfp_mask)
2427 int alloc_flags = ALLOC_WMARK_MIN | ALLOC_CPUSET;
2428 const bool atomic = !(gfp_mask & (__GFP_WAIT | __GFP_NO_KSWAPD));
2430 /* __GFP_HIGH is assumed to be the same as ALLOC_HIGH to save a branch. */
2431 BUILD_BUG_ON(__GFP_HIGH != (__force gfp_t) ALLOC_HIGH);
2434 * The caller may dip into page reserves a bit more if the caller
2435 * cannot run direct reclaim, or if the caller has realtime scheduling
2436 * policy or is asking for __GFP_HIGH memory. GFP_ATOMIC requests will
2437 * set both ALLOC_HARDER (atomic == true) and ALLOC_HIGH (__GFP_HIGH).
2439 alloc_flags |= (__force int) (gfp_mask & __GFP_HIGH);
2441 if (atomic) {
2443 * Not worth trying to allocate harder for __GFP_NOMEMALLOC even
2444 * if it can't schedule.
2446 if (!(gfp_mask & __GFP_NOMEMALLOC))
2447 alloc_flags |= ALLOC_HARDER;
2449 * Ignore cpuset mems for GFP_ATOMIC rather than fail, see the
2450 * comment for __cpuset_node_allowed_softwall().
2452 alloc_flags &= ~ALLOC_CPUSET;
2453 } else if (unlikely(rt_task(current)) && !in_interrupt())
2454 alloc_flags |= ALLOC_HARDER;
2456 if (likely(!(gfp_mask & __GFP_NOMEMALLOC))) {
2457 if (gfp_mask & __GFP_MEMALLOC)
2458 alloc_flags |= ALLOC_NO_WATERMARKS;
2459 else if (in_serving_softirq() && (current->flags & PF_MEMALLOC))
2460 alloc_flags |= ALLOC_NO_WATERMARKS;
2461 else if (!in_interrupt() &&
2462 ((current->flags & PF_MEMALLOC) ||
2463 unlikely(test_thread_flag(TIF_MEMDIE))))
2464 alloc_flags |= ALLOC_NO_WATERMARKS;
2466 #ifdef CONFIG_CMA
2467 if (allocflags_to_migratetype(gfp_mask) == MIGRATE_MOVABLE)
2468 alloc_flags |= ALLOC_CMA;
2469 #endif
2470 return alloc_flags;
2473 bool gfp_pfmemalloc_allowed(gfp_t gfp_mask)
2475 return !!(gfp_to_alloc_flags(gfp_mask) & ALLOC_NO_WATERMARKS);
2478 static inline struct page *
2479 __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order,
2480 struct zonelist *zonelist, enum zone_type high_zoneidx,
2481 nodemask_t *nodemask, struct zone *preferred_zone,
2482 int migratetype)
2484 const gfp_t wait = gfp_mask & __GFP_WAIT;
2485 struct page *page = NULL;
2486 int alloc_flags;
2487 unsigned long pages_reclaimed = 0;
2488 unsigned long did_some_progress;
2489 bool sync_migration = false;
2490 bool deferred_compaction = false;
2491 bool contended_compaction = false;
2494 * In the slowpath, we sanity check order to avoid ever trying to
2495 * reclaim >= MAX_ORDER areas which will never succeed. Callers may
2496 * be using allocators in order of preference for an area that is
2497 * too large.
2499 if (order >= MAX_ORDER) {
2500 WARN_ON_ONCE(!(gfp_mask & __GFP_NOWARN));
2501 return NULL;
2505 * GFP_THISNODE (meaning __GFP_THISNODE, __GFP_NORETRY and
2506 * __GFP_NOWARN set) should not cause reclaim since the subsystem
2507 * (f.e. slab) using GFP_THISNODE may choose to trigger reclaim
2508 * using a larger set of nodes after it has established that the
2509 * allowed per node queues are empty and that nodes are
2510 * over allocated.
2512 if (IS_ENABLED(CONFIG_NUMA) &&
2513 (gfp_mask & GFP_THISNODE) == GFP_THISNODE)
2514 goto nopage;
2516 restart:
2517 if (!(gfp_mask & __GFP_NO_KSWAPD))
2518 wake_all_kswapds(order, zonelist, high_zoneidx, preferred_zone);
2521 * OK, we're below the kswapd watermark and have kicked background
2522 * reclaim. Now things get more complex, so set up alloc_flags according
2523 * to how we want to proceed.
2525 alloc_flags = gfp_to_alloc_flags(gfp_mask);
2528 * Find the true preferred zone if the allocation is unconstrained by
2529 * cpusets.
2531 if (!(alloc_flags & ALLOC_CPUSET) && !nodemask)
2532 first_zones_zonelist(zonelist, high_zoneidx, NULL,
2533 &preferred_zone);
2535 rebalance:
2536 /* This is the last chance, in general, before the goto nopage. */
2537 page = get_page_from_freelist(gfp_mask, nodemask, order, zonelist,
2538 high_zoneidx, alloc_flags & ~ALLOC_NO_WATERMARKS,
2539 preferred_zone, migratetype);
2540 if (page)
2541 goto got_pg;
2543 /* Allocate without watermarks if the context allows */
2544 if (alloc_flags & ALLOC_NO_WATERMARKS) {
2546 * Ignore mempolicies if ALLOC_NO_WATERMARKS on the grounds
2547 * the allocation is high priority and these type of
2548 * allocations are system rather than user orientated
2550 zonelist = node_zonelist(numa_node_id(), gfp_mask);
2552 page = __alloc_pages_high_priority(gfp_mask, order,
2553 zonelist, high_zoneidx, nodemask,
2554 preferred_zone, migratetype);
2555 if (page) {
2556 goto got_pg;
2560 /* Atomic allocations - we can't balance anything */
2561 if (!wait)
2562 goto nopage;
2564 /* Avoid recursion of direct reclaim */
2565 if (current->flags & PF_MEMALLOC)
2566 goto nopage;
2568 /* Avoid allocations with no watermarks from looping endlessly */
2569 if (test_thread_flag(TIF_MEMDIE) && !(gfp_mask & __GFP_NOFAIL))
2570 goto nopage;
2573 * Try direct compaction. The first pass is asynchronous. Subsequent
2574 * attempts after direct reclaim are synchronous
2576 page = __alloc_pages_direct_compact(gfp_mask, order,
2577 zonelist, high_zoneidx,
2578 nodemask,
2579 alloc_flags, preferred_zone,
2580 migratetype, sync_migration,
2581 &contended_compaction,
2582 &deferred_compaction,
2583 &did_some_progress);
2584 if (page)
2585 goto got_pg;
2586 sync_migration = true;
2589 * If compaction is deferred for high-order allocations, it is because
2590 * sync compaction recently failed. In this is the case and the caller
2591 * requested a movable allocation that does not heavily disrupt the
2592 * system then fail the allocation instead of entering direct reclaim.
2594 if ((deferred_compaction || contended_compaction) &&
2595 (gfp_mask & __GFP_NO_KSWAPD))
2596 goto nopage;
2598 /* Try direct reclaim and then allocating */
2599 page = __alloc_pages_direct_reclaim(gfp_mask, order,
2600 zonelist, high_zoneidx,
2601 nodemask,
2602 alloc_flags, preferred_zone,
2603 migratetype, &did_some_progress);
2604 if (page)
2605 goto got_pg;
2608 * If we failed to make any progress reclaiming, then we are
2609 * running out of options and have to consider going OOM
2611 if (!did_some_progress) {
2612 if ((gfp_mask & __GFP_FS) && !(gfp_mask & __GFP_NORETRY)) {
2613 if (oom_killer_disabled)
2614 goto nopage;
2615 /* Coredumps can quickly deplete all memory reserves */
2616 if ((current->flags & PF_DUMPCORE) &&
2617 !(gfp_mask & __GFP_NOFAIL))
2618 goto nopage;
2619 page = __alloc_pages_may_oom(gfp_mask, order,
2620 zonelist, high_zoneidx,
2621 nodemask, preferred_zone,
2622 migratetype);
2623 if (page)
2624 goto got_pg;
2626 if (!(gfp_mask & __GFP_NOFAIL)) {
2628 * The oom killer is not called for high-order
2629 * allocations that may fail, so if no progress
2630 * is being made, there are no other options and
2631 * retrying is unlikely to help.
2633 if (order > PAGE_ALLOC_COSTLY_ORDER)
2634 goto nopage;
2636 * The oom killer is not called for lowmem
2637 * allocations to prevent needlessly killing
2638 * innocent tasks.
2640 if (high_zoneidx < ZONE_NORMAL)
2641 goto nopage;
2644 goto restart;
2648 /* Check if we should retry the allocation */
2649 pages_reclaimed += did_some_progress;
2650 if (should_alloc_retry(gfp_mask, order, did_some_progress,
2651 pages_reclaimed)) {
2652 /* Wait for some write requests to complete then retry */
2653 wait_iff_congested(preferred_zone, BLK_RW_ASYNC, HZ/50);
2654 goto rebalance;
2655 } else {
2657 * High-order allocations do not necessarily loop after
2658 * direct reclaim and reclaim/compaction depends on compaction
2659 * being called after reclaim so call directly if necessary
2661 page = __alloc_pages_direct_compact(gfp_mask, order,
2662 zonelist, high_zoneidx,
2663 nodemask,
2664 alloc_flags, preferred_zone,
2665 migratetype, sync_migration,
2666 &contended_compaction,
2667 &deferred_compaction,
2668 &did_some_progress);
2669 if (page)
2670 goto got_pg;
2673 nopage:
2674 warn_alloc_failed(gfp_mask, order, NULL);
2675 return page;
2676 got_pg:
2677 if (kmemcheck_enabled)
2678 kmemcheck_pagealloc_alloc(page, order, gfp_mask);
2680 return page;
2684 * This is the 'heart' of the zoned buddy allocator.
2686 struct page *
2687 __alloc_pages_nodemask(gfp_t gfp_mask, unsigned int order,
2688 struct zonelist *zonelist, nodemask_t *nodemask)
2690 enum zone_type high_zoneidx = gfp_zone(gfp_mask);
2691 struct zone *preferred_zone;
2692 struct page *page = NULL;
2693 int migratetype = allocflags_to_migratetype(gfp_mask);
2694 unsigned int cpuset_mems_cookie;
2695 int alloc_flags = ALLOC_WMARK_LOW|ALLOC_CPUSET|ALLOC_FAIR;
2696 struct mem_cgroup *memcg = NULL;
2698 gfp_mask &= gfp_allowed_mask;
2700 lockdep_trace_alloc(gfp_mask);
2702 might_sleep_if(gfp_mask & __GFP_WAIT);
2704 if (should_fail_alloc_page(gfp_mask, order))
2705 return NULL;
2708 * Check the zones suitable for the gfp_mask contain at least one
2709 * valid zone. It's possible to have an empty zonelist as a result
2710 * of GFP_THISNODE and a memoryless node
2712 if (unlikely(!zonelist->_zonerefs->zone))
2713 return NULL;
2716 * Will only have any effect when __GFP_KMEMCG is set. This is
2717 * verified in the (always inline) callee
2719 if (!memcg_kmem_newpage_charge(gfp_mask, &memcg, order))
2720 return NULL;
2722 retry_cpuset:
2723 cpuset_mems_cookie = get_mems_allowed();
2725 /* The preferred zone is used for statistics later */
2726 first_zones_zonelist(zonelist, high_zoneidx,
2727 nodemask ? : &cpuset_current_mems_allowed,
2728 &preferred_zone);
2729 if (!preferred_zone)
2730 goto out;
2732 #ifdef CONFIG_CMA
2733 if (allocflags_to_migratetype(gfp_mask) == MIGRATE_MOVABLE)
2734 alloc_flags |= ALLOC_CMA;
2735 #endif
2736 retry:
2737 /* First allocation attempt */
2738 page = get_page_from_freelist(gfp_mask|__GFP_HARDWALL, nodemask, order,
2739 zonelist, high_zoneidx, alloc_flags,
2740 preferred_zone, migratetype);
2741 if (unlikely(!page)) {
2743 * The first pass makes sure allocations are spread
2744 * fairly within the local node. However, the local
2745 * node might have free pages left after the fairness
2746 * batches are exhausted, and remote zones haven't
2747 * even been considered yet. Try once more without
2748 * fairness, and include remote zones now, before
2749 * entering the slowpath and waking kswapd: prefer
2750 * spilling to a remote zone over swapping locally.
2752 if (alloc_flags & ALLOC_FAIR) {
2753 reset_alloc_batches(zonelist, high_zoneidx,
2754 preferred_zone);
2755 alloc_flags &= ~ALLOC_FAIR;
2756 goto retry;
2759 * Runtime PM, block IO and its error handling path
2760 * can deadlock because I/O on the device might not
2761 * complete.
2763 gfp_mask = memalloc_noio_flags(gfp_mask);
2764 page = __alloc_pages_slowpath(gfp_mask, order,
2765 zonelist, high_zoneidx, nodemask,
2766 preferred_zone, migratetype);
2769 trace_mm_page_alloc(page, order, gfp_mask, migratetype);
2771 out:
2773 * When updating a task's mems_allowed, it is possible to race with
2774 * parallel threads in such a way that an allocation can fail while
2775 * the mask is being updated. If a page allocation is about to fail,
2776 * check if the cpuset changed during allocation and if so, retry.
2778 if (unlikely(!put_mems_allowed(cpuset_mems_cookie) && !page))
2779 goto retry_cpuset;
2781 memcg_kmem_commit_charge(page, memcg, order);
2783 return page;
2785 EXPORT_SYMBOL(__alloc_pages_nodemask);
2788 * Common helper functions.
2790 unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order)
2792 struct page *page;
2795 * __get_free_pages() returns a 32-bit address, which cannot represent
2796 * a highmem page
2798 VM_BUG_ON((gfp_mask & __GFP_HIGHMEM) != 0);
2800 page = alloc_pages(gfp_mask, order);
2801 if (!page)
2802 return 0;
2803 return (unsigned long) page_address(page);
2805 EXPORT_SYMBOL(__get_free_pages);
2807 unsigned long get_zeroed_page(gfp_t gfp_mask)
2809 return __get_free_pages(gfp_mask | __GFP_ZERO, 0);
2811 EXPORT_SYMBOL(get_zeroed_page);
2813 void __free_pages(struct page *page, unsigned int order)
2815 if (put_page_testzero(page)) {
2816 if (order == 0)
2817 free_hot_cold_page(page, 0);
2818 else
2819 __free_pages_ok(page, order);
2823 EXPORT_SYMBOL(__free_pages);
2825 void free_pages(unsigned long addr, unsigned int order)
2827 if (addr != 0) {
2828 VM_BUG_ON(!virt_addr_valid((void *)addr));
2829 __free_pages(virt_to_page((void *)addr), order);
2833 EXPORT_SYMBOL(free_pages);
2836 * __free_memcg_kmem_pages and free_memcg_kmem_pages will free
2837 * pages allocated with __GFP_KMEMCG.
2839 * Those pages are accounted to a particular memcg, embedded in the
2840 * corresponding page_cgroup. To avoid adding a hit in the allocator to search
2841 * for that information only to find out that it is NULL for users who have no
2842 * interest in that whatsoever, we provide these functions.
2844 * The caller knows better which flags it relies on.
2846 void __free_memcg_kmem_pages(struct page *page, unsigned int order)
2848 memcg_kmem_uncharge_pages(page, order);
2849 __free_pages(page, order);
2852 void free_memcg_kmem_pages(unsigned long addr, unsigned int order)
2854 if (addr != 0) {
2855 VM_BUG_ON(!virt_addr_valid((void *)addr));
2856 __free_memcg_kmem_pages(virt_to_page((void *)addr), order);
2860 static void *make_alloc_exact(unsigned long addr, unsigned order, size_t size)
2862 if (addr) {
2863 unsigned long alloc_end = addr + (PAGE_SIZE << order);
2864 unsigned long used = addr + PAGE_ALIGN(size);
2866 split_page(virt_to_page((void *)addr), order);
2867 while (used < alloc_end) {
2868 free_page(used);
2869 used += PAGE_SIZE;
2872 return (void *)addr;
2876 * alloc_pages_exact - allocate an exact number physically-contiguous pages.
2877 * @size: the number of bytes to allocate
2878 * @gfp_mask: GFP flags for the allocation
2880 * This function is similar to alloc_pages(), except that it allocates the
2881 * minimum number of pages to satisfy the request. alloc_pages() can only
2882 * allocate memory in power-of-two pages.
2884 * This function is also limited by MAX_ORDER.
2886 * Memory allocated by this function must be released by free_pages_exact().
2888 void *alloc_pages_exact(size_t size, gfp_t gfp_mask)
2890 unsigned int order = get_order(size);
2891 unsigned long addr;
2893 addr = __get_free_pages(gfp_mask, order);
2894 return make_alloc_exact(addr, order, size);
2896 EXPORT_SYMBOL(alloc_pages_exact);
2899 * alloc_pages_exact_nid - allocate an exact number of physically-contiguous
2900 * pages on a node.
2901 * @nid: the preferred node ID where memory should be allocated
2902 * @size: the number of bytes to allocate
2903 * @gfp_mask: GFP flags for the allocation
2905 * Like alloc_pages_exact(), but try to allocate on node nid first before falling
2906 * back.
2907 * Note this is not alloc_pages_exact_node() which allocates on a specific node,
2908 * but is not exact.
2910 void *alloc_pages_exact_nid(int nid, size_t size, gfp_t gfp_mask)
2912 unsigned order = get_order(size);
2913 struct page *p = alloc_pages_node(nid, gfp_mask, order);
2914 if (!p)
2915 return NULL;
2916 return make_alloc_exact((unsigned long)page_address(p), order, size);
2918 EXPORT_SYMBOL(alloc_pages_exact_nid);
2921 * free_pages_exact - release memory allocated via alloc_pages_exact()
2922 * @virt: the value returned by alloc_pages_exact.
2923 * @size: size of allocation, same value as passed to alloc_pages_exact().
2925 * Release the memory allocated by a previous call to alloc_pages_exact.
2927 void free_pages_exact(void *virt, size_t size)
2929 unsigned long addr = (unsigned long)virt;
2930 unsigned long end = addr + PAGE_ALIGN(size);
2932 while (addr < end) {
2933 free_page(addr);
2934 addr += PAGE_SIZE;
2937 EXPORT_SYMBOL(free_pages_exact);
2940 * nr_free_zone_pages - count number of pages beyond high watermark
2941 * @offset: The zone index of the highest zone
2943 * nr_free_zone_pages() counts the number of counts pages which are beyond the
2944 * high watermark within all zones at or below a given zone index. For each
2945 * zone, the number of pages is calculated as:
2946 * managed_pages - high_pages
2948 static unsigned long nr_free_zone_pages(int offset)
2950 struct zoneref *z;
2951 struct zone *zone;
2953 /* Just pick one node, since fallback list is circular */
2954 unsigned long sum = 0;
2956 struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL);
2958 for_each_zone_zonelist(zone, z, zonelist, offset) {
2959 unsigned long size = zone->managed_pages;
2960 unsigned long high = high_wmark_pages(zone);
2961 if (size > high)
2962 sum += size - high;
2965 return sum;
2969 * nr_free_buffer_pages - count number of pages beyond high watermark
2971 * nr_free_buffer_pages() counts the number of pages which are beyond the high
2972 * watermark within ZONE_DMA and ZONE_NORMAL.
2974 unsigned long nr_free_buffer_pages(void)
2976 return nr_free_zone_pages(gfp_zone(GFP_USER));
2978 EXPORT_SYMBOL_GPL(nr_free_buffer_pages);
2981 * nr_free_pagecache_pages - count number of pages beyond high watermark
2983 * nr_free_pagecache_pages() counts the number of pages which are beyond the
2984 * high watermark within all zones.
2986 unsigned long nr_free_pagecache_pages(void)
2988 return nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE));
2991 static inline void show_node(struct zone *zone)
2993 if (IS_ENABLED(CONFIG_NUMA))
2994 printk("Node %d ", zone_to_nid(zone));
2997 void si_meminfo(struct sysinfo *val)
2999 val->totalram = totalram_pages;
3000 val->sharedram = 0;
3001 val->freeram = global_page_state(NR_FREE_PAGES);
3002 val->bufferram = nr_blockdev_pages();
3003 val->totalhigh = totalhigh_pages;
3004 val->freehigh = nr_free_highpages();
3005 val->mem_unit = PAGE_SIZE;
3008 EXPORT_SYMBOL(si_meminfo);
3010 #ifdef CONFIG_NUMA
3011 void si_meminfo_node(struct sysinfo *val, int nid)
3013 int zone_type; /* needs to be signed */
3014 unsigned long managed_pages = 0;
3015 pg_data_t *pgdat = NODE_DATA(nid);
3017 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++)
3018 managed_pages += pgdat->node_zones[zone_type].managed_pages;
3019 val->totalram = managed_pages;
3020 val->freeram = node_page_state(nid, NR_FREE_PAGES);
3021 #ifdef CONFIG_HIGHMEM
3022 val->totalhigh = pgdat->node_zones[ZONE_HIGHMEM].managed_pages;
3023 val->freehigh = zone_page_state(&pgdat->node_zones[ZONE_HIGHMEM],
3024 NR_FREE_PAGES);
3025 #else
3026 val->totalhigh = 0;
3027 val->freehigh = 0;
3028 #endif
3029 val->mem_unit = PAGE_SIZE;
3031 #endif
3034 * Determine whether the node should be displayed or not, depending on whether
3035 * SHOW_MEM_FILTER_NODES was passed to show_free_areas().
3037 bool skip_free_areas_node(unsigned int flags, int nid)
3039 bool ret = false;
3040 unsigned int cpuset_mems_cookie;
3042 if (!(flags & SHOW_MEM_FILTER_NODES))
3043 goto out;
3045 do {
3046 cpuset_mems_cookie = get_mems_allowed();
3047 ret = !node_isset(nid, cpuset_current_mems_allowed);
3048 } while (!put_mems_allowed(cpuset_mems_cookie));
3049 out:
3050 return ret;
3053 #define K(x) ((x) << (PAGE_SHIFT-10))
3055 static void show_migration_types(unsigned char type)
3057 static const char types[MIGRATE_TYPES] = {
3058 [MIGRATE_UNMOVABLE] = 'U',
3059 [MIGRATE_RECLAIMABLE] = 'E',
3060 [MIGRATE_MOVABLE] = 'M',
3061 [MIGRATE_RESERVE] = 'R',
3062 #ifdef CONFIG_CMA
3063 [MIGRATE_CMA] = 'C',
3064 #endif
3065 #ifdef CONFIG_MEMORY_ISOLATION
3066 [MIGRATE_ISOLATE] = 'I',
3067 #endif
3069 char tmp[MIGRATE_TYPES + 1];
3070 char *p = tmp;
3071 int i;
3073 for (i = 0; i < MIGRATE_TYPES; i++) {
3074 if (type & (1 << i))
3075 *p++ = types[i];
3078 *p = '\0';
3079 printk("(%s) ", tmp);
3083 * Show free area list (used inside shift_scroll-lock stuff)
3084 * We also calculate the percentage fragmentation. We do this by counting the
3085 * memory on each free list with the exception of the first item on the list.
3086 * Suppresses nodes that are not allowed by current's cpuset if
3087 * SHOW_MEM_FILTER_NODES is passed.
3089 void show_free_areas(unsigned int filter)
3091 int cpu;
3092 struct zone *zone;
3094 for_each_populated_zone(zone) {
3095 if (skip_free_areas_node(filter, zone_to_nid(zone)))
3096 continue;
3097 show_node(zone);
3098 printk("%s per-cpu:\n", zone->name);
3100 for_each_online_cpu(cpu) {
3101 struct per_cpu_pageset *pageset;
3103 pageset = per_cpu_ptr(zone->pageset, cpu);
3105 printk("CPU %4d: hi:%5d, btch:%4d usd:%4d\n",
3106 cpu, pageset->pcp.high,
3107 pageset->pcp.batch, pageset->pcp.count);
3111 printk("active_anon:%lu inactive_anon:%lu isolated_anon:%lu\n"
3112 " active_file:%lu inactive_file:%lu isolated_file:%lu\n"
3113 " unevictable:%lu"
3114 " dirty:%lu writeback:%lu unstable:%lu\n"
3115 " free:%lu slab_reclaimable:%lu slab_unreclaimable:%lu\n"
3116 " mapped:%lu shmem:%lu pagetables:%lu bounce:%lu\n"
3117 " free_cma:%lu\n",
3118 global_page_state(NR_ACTIVE_ANON),
3119 global_page_state(NR_INACTIVE_ANON),
3120 global_page_state(NR_ISOLATED_ANON),
3121 global_page_state(NR_ACTIVE_FILE),
3122 global_page_state(NR_INACTIVE_FILE),
3123 global_page_state(NR_ISOLATED_FILE),
3124 global_page_state(NR_UNEVICTABLE),
3125 global_page_state(NR_FILE_DIRTY),
3126 global_page_state(NR_WRITEBACK),
3127 global_page_state(NR_UNSTABLE_NFS),
3128 global_page_state(NR_FREE_PAGES),
3129 global_page_state(NR_SLAB_RECLAIMABLE),
3130 global_page_state(NR_SLAB_UNRECLAIMABLE),
3131 global_page_state(NR_FILE_MAPPED),
3132 global_page_state(NR_SHMEM),
3133 global_page_state(NR_PAGETABLE),
3134 global_page_state(NR_BOUNCE),
3135 global_page_state(NR_FREE_CMA_PAGES));
3137 for_each_populated_zone(zone) {
3138 int i;
3140 if (skip_free_areas_node(filter, zone_to_nid(zone)))
3141 continue;
3142 show_node(zone);
3143 printk("%s"
3144 " free:%lukB"
3145 " min:%lukB"
3146 " low:%lukB"
3147 " high:%lukB"
3148 " active_anon:%lukB"
3149 " inactive_anon:%lukB"
3150 " active_file:%lukB"
3151 " inactive_file:%lukB"
3152 " unevictable:%lukB"
3153 " isolated(anon):%lukB"
3154 " isolated(file):%lukB"
3155 " present:%lukB"
3156 " managed:%lukB"
3157 " mlocked:%lukB"
3158 " dirty:%lukB"
3159 " writeback:%lukB"
3160 " mapped:%lukB"
3161 " shmem:%lukB"
3162 " slab_reclaimable:%lukB"
3163 " slab_unreclaimable:%lukB"
3164 " kernel_stack:%lukB"
3165 " pagetables:%lukB"
3166 " unstable:%lukB"
3167 " bounce:%lukB"
3168 " free_cma:%lukB"
3169 " writeback_tmp:%lukB"
3170 " pages_scanned:%lu"
3171 " all_unreclaimable? %s"
3172 "\n",
3173 zone->name,
3174 K(zone_page_state(zone, NR_FREE_PAGES)),
3175 K(min_wmark_pages(zone)),
3176 K(low_wmark_pages(zone)),
3177 K(high_wmark_pages(zone)),
3178 K(zone_page_state(zone, NR_ACTIVE_ANON)),
3179 K(zone_page_state(zone, NR_INACTIVE_ANON)),
3180 K(zone_page_state(zone, NR_ACTIVE_FILE)),
3181 K(zone_page_state(zone, NR_INACTIVE_FILE)),
3182 K(zone_page_state(zone, NR_UNEVICTABLE)),
3183 K(zone_page_state(zone, NR_ISOLATED_ANON)),
3184 K(zone_page_state(zone, NR_ISOLATED_FILE)),
3185 K(zone->present_pages),
3186 K(zone->managed_pages),
3187 K(zone_page_state(zone, NR_MLOCK)),
3188 K(zone_page_state(zone, NR_FILE_DIRTY)),
3189 K(zone_page_state(zone, NR_WRITEBACK)),
3190 K(zone_page_state(zone, NR_FILE_MAPPED)),
3191 K(zone_page_state(zone, NR_SHMEM)),
3192 K(zone_page_state(zone, NR_SLAB_RECLAIMABLE)),
3193 K(zone_page_state(zone, NR_SLAB_UNRECLAIMABLE)),
3194 zone_page_state(zone, NR_KERNEL_STACK) *
3195 THREAD_SIZE / 1024,
3196 K(zone_page_state(zone, NR_PAGETABLE)),
3197 K(zone_page_state(zone, NR_UNSTABLE_NFS)),
3198 K(zone_page_state(zone, NR_BOUNCE)),
3199 K(zone_page_state(zone, NR_FREE_CMA_PAGES)),
3200 K(zone_page_state(zone, NR_WRITEBACK_TEMP)),
3201 zone->pages_scanned,
3202 (!zone_reclaimable(zone) ? "yes" : "no")
3204 printk("lowmem_reserve[]:");
3205 for (i = 0; i < MAX_NR_ZONES; i++)
3206 printk(" %lu", zone->lowmem_reserve[i]);
3207 printk("\n");
3210 for_each_populated_zone(zone) {
3211 unsigned long nr[MAX_ORDER], flags, order, total = 0;
3212 unsigned char types[MAX_ORDER];
3214 if (skip_free_areas_node(filter, zone_to_nid(zone)))
3215 continue;
3216 show_node(zone);
3217 printk("%s: ", zone->name);
3219 spin_lock_irqsave(&zone->lock, flags);
3220 for (order = 0; order < MAX_ORDER; order++) {
3221 struct free_area *area = &zone->free_area[order];
3222 int type;
3224 nr[order] = area->nr_free;
3225 total += nr[order] << order;
3227 types[order] = 0;
3228 for (type = 0; type < MIGRATE_TYPES; type++) {
3229 if (!list_empty(&area->free_list[type]))
3230 types[order] |= 1 << type;
3233 spin_unlock_irqrestore(&zone->lock, flags);
3234 for (order = 0; order < MAX_ORDER; order++) {
3235 printk("%lu*%lukB ", nr[order], K(1UL) << order);
3236 if (nr[order])
3237 show_migration_types(types[order]);
3239 printk("= %lukB\n", K(total));
3242 hugetlb_show_meminfo();
3244 printk("%ld total pagecache pages\n", global_page_state(NR_FILE_PAGES));
3246 show_swap_cache_info();
3249 static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref)
3251 zoneref->zone = zone;
3252 zoneref->zone_idx = zone_idx(zone);
3256 * Builds allocation fallback zone lists.
3258 * Add all populated zones of a node to the zonelist.
3260 static int build_zonelists_node(pg_data_t *pgdat, struct zonelist *zonelist,
3261 int nr_zones)
3263 struct zone *zone;
3264 enum zone_type zone_type = MAX_NR_ZONES;
3266 do {
3267 zone_type--;
3268 zone = pgdat->node_zones + zone_type;
3269 if (populated_zone(zone)) {
3270 zoneref_set_zone(zone,
3271 &zonelist->_zonerefs[nr_zones++]);
3272 check_highest_zone(zone_type);
3274 } while (zone_type);
3276 return nr_zones;
3281 * zonelist_order:
3282 * 0 = automatic detection of better ordering.
3283 * 1 = order by ([node] distance, -zonetype)
3284 * 2 = order by (-zonetype, [node] distance)
3286 * If not NUMA, ZONELIST_ORDER_ZONE and ZONELIST_ORDER_NODE will create
3287 * the same zonelist. So only NUMA can configure this param.
3289 #define ZONELIST_ORDER_DEFAULT 0
3290 #define ZONELIST_ORDER_NODE 1
3291 #define ZONELIST_ORDER_ZONE 2
3293 /* zonelist order in the kernel.
3294 * set_zonelist_order() will set this to NODE or ZONE.
3296 static int current_zonelist_order = ZONELIST_ORDER_DEFAULT;
3297 static char zonelist_order_name[3][8] = {"Default", "Node", "Zone"};
3300 #ifdef CONFIG_NUMA
3301 /* The value user specified ....changed by config */
3302 static int user_zonelist_order = ZONELIST_ORDER_DEFAULT;
3303 /* string for sysctl */
3304 #define NUMA_ZONELIST_ORDER_LEN 16
3305 char numa_zonelist_order[16] = "default";
3308 * interface for configure zonelist ordering.
3309 * command line option "numa_zonelist_order"
3310 * = "[dD]efault - default, automatic configuration.
3311 * = "[nN]ode - order by node locality, then by zone within node
3312 * = "[zZ]one - order by zone, then by locality within zone
3315 static int __parse_numa_zonelist_order(char *s)
3317 if (*s == 'd' || *s == 'D') {
3318 user_zonelist_order = ZONELIST_ORDER_DEFAULT;
3319 } else if (*s == 'n' || *s == 'N') {
3320 user_zonelist_order = ZONELIST_ORDER_NODE;
3321 } else if (*s == 'z' || *s == 'Z') {
3322 user_zonelist_order = ZONELIST_ORDER_ZONE;
3323 } else {
3324 printk(KERN_WARNING
3325 "Ignoring invalid numa_zonelist_order value: "
3326 "%s\n", s);
3327 return -EINVAL;
3329 return 0;
3332 static __init int setup_numa_zonelist_order(char *s)
3334 int ret;
3336 if (!s)
3337 return 0;
3339 ret = __parse_numa_zonelist_order(s);
3340 if (ret == 0)
3341 strlcpy(numa_zonelist_order, s, NUMA_ZONELIST_ORDER_LEN);
3343 return ret;
3345 early_param("numa_zonelist_order", setup_numa_zonelist_order);
3348 * sysctl handler for numa_zonelist_order
3350 int numa_zonelist_order_handler(ctl_table *table, int write,
3351 void __user *buffer, size_t *length,
3352 loff_t *ppos)
3354 char saved_string[NUMA_ZONELIST_ORDER_LEN];
3355 int ret;
3356 static DEFINE_MUTEX(zl_order_mutex);
3358 mutex_lock(&zl_order_mutex);
3359 if (write) {
3360 if (strlen((char *)table->data) >= NUMA_ZONELIST_ORDER_LEN) {
3361 ret = -EINVAL;
3362 goto out;
3364 strcpy(saved_string, (char *)table->data);
3366 ret = proc_dostring(table, write, buffer, length, ppos);
3367 if (ret)
3368 goto out;
3369 if (write) {
3370 int oldval = user_zonelist_order;
3372 ret = __parse_numa_zonelist_order((char *)table->data);
3373 if (ret) {
3375 * bogus value. restore saved string
3377 strncpy((char *)table->data, saved_string,
3378 NUMA_ZONELIST_ORDER_LEN);
3379 user_zonelist_order = oldval;
3380 } else if (oldval != user_zonelist_order) {
3381 mutex_lock(&zonelists_mutex);
3382 build_all_zonelists(NULL, NULL);
3383 mutex_unlock(&zonelists_mutex);
3386 out:
3387 mutex_unlock(&zl_order_mutex);
3388 return ret;
3392 #define MAX_NODE_LOAD (nr_online_nodes)
3393 static int node_load[MAX_NUMNODES];
3396 * find_next_best_node - find the next node that should appear in a given node's fallback list
3397 * @node: node whose fallback list we're appending
3398 * @used_node_mask: nodemask_t of already used nodes
3400 * We use a number of factors to determine which is the next node that should
3401 * appear on a given node's fallback list. The node should not have appeared
3402 * already in @node's fallback list, and it should be the next closest node
3403 * according to the distance array (which contains arbitrary distance values
3404 * from each node to each node in the system), and should also prefer nodes
3405 * with no CPUs, since presumably they'll have very little allocation pressure
3406 * on them otherwise.
3407 * It returns -1 if no node is found.
3409 static int find_next_best_node(int node, nodemask_t *used_node_mask)
3411 int n, val;
3412 int min_val = INT_MAX;
3413 int best_node = NUMA_NO_NODE;
3414 const struct cpumask *tmp = cpumask_of_node(0);
3416 /* Use the local node if we haven't already */
3417 if (!node_isset(node, *used_node_mask)) {
3418 node_set(node, *used_node_mask);
3419 return node;
3422 for_each_node_state(n, N_MEMORY) {
3424 /* Don't want a node to appear more than once */
3425 if (node_isset(n, *used_node_mask))
3426 continue;
3428 /* Use the distance array to find the distance */
3429 val = node_distance(node, n);
3431 /* Penalize nodes under us ("prefer the next node") */
3432 val += (n < node);
3434 /* Give preference to headless and unused nodes */
3435 tmp = cpumask_of_node(n);
3436 if (!cpumask_empty(tmp))
3437 val += PENALTY_FOR_NODE_WITH_CPUS;
3439 /* Slight preference for less loaded node */
3440 val *= (MAX_NODE_LOAD*MAX_NUMNODES);
3441 val += node_load[n];
3443 if (val < min_val) {
3444 min_val = val;
3445 best_node = n;
3449 if (best_node >= 0)
3450 node_set(best_node, *used_node_mask);
3452 return best_node;
3457 * Build zonelists ordered by node and zones within node.
3458 * This results in maximum locality--normal zone overflows into local
3459 * DMA zone, if any--but risks exhausting DMA zone.
3461 static void build_zonelists_in_node_order(pg_data_t *pgdat, int node)
3463 int j;
3464 struct zonelist *zonelist;
3466 zonelist = &pgdat->node_zonelists[0];
3467 for (j = 0; zonelist->_zonerefs[j].zone != NULL; j++)
3469 j = build_zonelists_node(NODE_DATA(node), zonelist, j);
3470 zonelist->_zonerefs[j].zone = NULL;
3471 zonelist->_zonerefs[j].zone_idx = 0;
3475 * Build gfp_thisnode zonelists
3477 static void build_thisnode_zonelists(pg_data_t *pgdat)
3479 int j;
3480 struct zonelist *zonelist;
3482 zonelist = &pgdat->node_zonelists[1];
3483 j = build_zonelists_node(pgdat, zonelist, 0);
3484 zonelist->_zonerefs[j].zone = NULL;
3485 zonelist->_zonerefs[j].zone_idx = 0;
3489 * Build zonelists ordered by zone and nodes within zones.
3490 * This results in conserving DMA zone[s] until all Normal memory is
3491 * exhausted, but results in overflowing to remote node while memory
3492 * may still exist in local DMA zone.
3494 static int node_order[MAX_NUMNODES];
3496 static void build_zonelists_in_zone_order(pg_data_t *pgdat, int nr_nodes)
3498 int pos, j, node;
3499 int zone_type; /* needs to be signed */
3500 struct zone *z;
3501 struct zonelist *zonelist;
3503 zonelist = &pgdat->node_zonelists[0];
3504 pos = 0;
3505 for (zone_type = MAX_NR_ZONES - 1; zone_type >= 0; zone_type--) {
3506 for (j = 0; j < nr_nodes; j++) {
3507 node = node_order[j];
3508 z = &NODE_DATA(node)->node_zones[zone_type];
3509 if (populated_zone(z)) {
3510 zoneref_set_zone(z,
3511 &zonelist->_zonerefs[pos++]);
3512 check_highest_zone(zone_type);
3516 zonelist->_zonerefs[pos].zone = NULL;
3517 zonelist->_zonerefs[pos].zone_idx = 0;
3520 static int default_zonelist_order(void)
3522 int nid, zone_type;
3523 unsigned long low_kmem_size, total_size;
3524 struct zone *z;
3525 int average_size;
3527 * ZONE_DMA and ZONE_DMA32 can be very small area in the system.
3528 * If they are really small and used heavily, the system can fall
3529 * into OOM very easily.
3530 * This function detect ZONE_DMA/DMA32 size and configures zone order.
3532 /* Is there ZONE_NORMAL ? (ex. ppc has only DMA zone..) */
3533 low_kmem_size = 0;
3534 total_size = 0;
3535 for_each_online_node(nid) {
3536 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
3537 z = &NODE_DATA(nid)->node_zones[zone_type];
3538 if (populated_zone(z)) {
3539 if (zone_type < ZONE_NORMAL)
3540 low_kmem_size += z->managed_pages;
3541 total_size += z->managed_pages;
3542 } else if (zone_type == ZONE_NORMAL) {
3544 * If any node has only lowmem, then node order
3545 * is preferred to allow kernel allocations
3546 * locally; otherwise, they can easily infringe
3547 * on other nodes when there is an abundance of
3548 * lowmem available to allocate from.
3550 return ZONELIST_ORDER_NODE;
3554 if (!low_kmem_size || /* there are no DMA area. */
3555 low_kmem_size > total_size/2) /* DMA/DMA32 is big. */
3556 return ZONELIST_ORDER_NODE;
3558 * look into each node's config.
3559 * If there is a node whose DMA/DMA32 memory is very big area on
3560 * local memory, NODE_ORDER may be suitable.
3562 average_size = total_size /
3563 (nodes_weight(node_states[N_MEMORY]) + 1);
3564 for_each_online_node(nid) {
3565 low_kmem_size = 0;
3566 total_size = 0;
3567 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
3568 z = &NODE_DATA(nid)->node_zones[zone_type];
3569 if (populated_zone(z)) {
3570 if (zone_type < ZONE_NORMAL)
3571 low_kmem_size += z->present_pages;
3572 total_size += z->present_pages;
3575 if (low_kmem_size &&
3576 total_size > average_size && /* ignore small node */
3577 low_kmem_size > total_size * 70/100)
3578 return ZONELIST_ORDER_NODE;
3580 return ZONELIST_ORDER_ZONE;
3583 static void set_zonelist_order(void)
3585 if (user_zonelist_order == ZONELIST_ORDER_DEFAULT)
3586 current_zonelist_order = default_zonelist_order();
3587 else
3588 current_zonelist_order = user_zonelist_order;
3591 static void build_zonelists(pg_data_t *pgdat)
3593 int j, node, load;
3594 enum zone_type i;
3595 nodemask_t used_mask;
3596 int local_node, prev_node;
3597 struct zonelist *zonelist;
3598 int order = current_zonelist_order;
3600 /* initialize zonelists */
3601 for (i = 0; i < MAX_ZONELISTS; i++) {
3602 zonelist = pgdat->node_zonelists + i;
3603 zonelist->_zonerefs[0].zone = NULL;
3604 zonelist->_zonerefs[0].zone_idx = 0;
3607 /* NUMA-aware ordering of nodes */
3608 local_node = pgdat->node_id;
3609 load = nr_online_nodes;
3610 prev_node = local_node;
3611 nodes_clear(used_mask);
3613 memset(node_order, 0, sizeof(node_order));
3614 j = 0;
3616 while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
3618 * We don't want to pressure a particular node.
3619 * So adding penalty to the first node in same
3620 * distance group to make it round-robin.
3622 if (node_distance(local_node, node) !=
3623 node_distance(local_node, prev_node))
3624 node_load[node] = load;
3626 prev_node = node;
3627 load--;
3628 if (order == ZONELIST_ORDER_NODE)
3629 build_zonelists_in_node_order(pgdat, node);
3630 else
3631 node_order[j++] = node; /* remember order */
3634 if (order == ZONELIST_ORDER_ZONE) {
3635 /* calculate node order -- i.e., DMA last! */
3636 build_zonelists_in_zone_order(pgdat, j);
3639 build_thisnode_zonelists(pgdat);
3642 /* Construct the zonelist performance cache - see further mmzone.h */
3643 static void build_zonelist_cache(pg_data_t *pgdat)
3645 struct zonelist *zonelist;
3646 struct zonelist_cache *zlc;
3647 struct zoneref *z;
3649 zonelist = &pgdat->node_zonelists[0];
3650 zonelist->zlcache_ptr = zlc = &zonelist->zlcache;
3651 bitmap_zero(zlc->fullzones, MAX_ZONES_PER_ZONELIST);
3652 for (z = zonelist->_zonerefs; z->zone; z++)
3653 zlc->z_to_n[z - zonelist->_zonerefs] = zonelist_node_idx(z);
3656 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
3658 * Return node id of node used for "local" allocations.
3659 * I.e., first node id of first zone in arg node's generic zonelist.
3660 * Used for initializing percpu 'numa_mem', which is used primarily
3661 * for kernel allocations, so use GFP_KERNEL flags to locate zonelist.
3663 int local_memory_node(int node)
3665 struct zone *zone;
3667 (void)first_zones_zonelist(node_zonelist(node, GFP_KERNEL),
3668 gfp_zone(GFP_KERNEL),
3669 NULL,
3670 &zone);
3671 return zone->node;
3673 #endif
3675 #else /* CONFIG_NUMA */
3677 static void set_zonelist_order(void)
3679 current_zonelist_order = ZONELIST_ORDER_ZONE;
3682 static void build_zonelists(pg_data_t *pgdat)
3684 int node, local_node;
3685 enum zone_type j;
3686 struct zonelist *zonelist;
3688 local_node = pgdat->node_id;
3690 zonelist = &pgdat->node_zonelists[0];
3691 j = build_zonelists_node(pgdat, zonelist, 0);
3694 * Now we build the zonelist so that it contains the zones
3695 * of all the other nodes.
3696 * We don't want to pressure a particular node, so when
3697 * building the zones for node N, we make sure that the
3698 * zones coming right after the local ones are those from
3699 * node N+1 (modulo N)
3701 for (node = local_node + 1; node < MAX_NUMNODES; node++) {
3702 if (!node_online(node))
3703 continue;
3704 j = build_zonelists_node(NODE_DATA(node), zonelist, j);
3706 for (node = 0; node < local_node; node++) {
3707 if (!node_online(node))
3708 continue;
3709 j = build_zonelists_node(NODE_DATA(node), zonelist, j);
3712 zonelist->_zonerefs[j].zone = NULL;
3713 zonelist->_zonerefs[j].zone_idx = 0;
3716 /* non-NUMA variant of zonelist performance cache - just NULL zlcache_ptr */
3717 static void build_zonelist_cache(pg_data_t *pgdat)
3719 pgdat->node_zonelists[0].zlcache_ptr = NULL;
3722 #endif /* CONFIG_NUMA */
3725 * Boot pageset table. One per cpu which is going to be used for all
3726 * zones and all nodes. The parameters will be set in such a way
3727 * that an item put on a list will immediately be handed over to
3728 * the buddy list. This is safe since pageset manipulation is done
3729 * with interrupts disabled.
3731 * The boot_pagesets must be kept even after bootup is complete for
3732 * unused processors and/or zones. They do play a role for bootstrapping
3733 * hotplugged processors.
3735 * zoneinfo_show() and maybe other functions do
3736 * not check if the processor is online before following the pageset pointer.
3737 * Other parts of the kernel may not check if the zone is available.
3739 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch);
3740 static DEFINE_PER_CPU(struct per_cpu_pageset, boot_pageset);
3741 static void setup_zone_pageset(struct zone *zone);
3744 * Global mutex to protect against size modification of zonelists
3745 * as well as to serialize pageset setup for the new populated zone.
3747 DEFINE_MUTEX(zonelists_mutex);
3749 /* return values int ....just for stop_machine() */
3750 static int __build_all_zonelists(void *data)
3752 int nid;
3753 int cpu;
3754 pg_data_t *self = data;
3756 #ifdef CONFIG_NUMA
3757 memset(node_load, 0, sizeof(node_load));
3758 #endif
3760 if (self && !node_online(self->node_id)) {
3761 build_zonelists(self);
3762 build_zonelist_cache(self);
3765 for_each_online_node(nid) {
3766 pg_data_t *pgdat = NODE_DATA(nid);
3768 build_zonelists(pgdat);
3769 build_zonelist_cache(pgdat);
3773 * Initialize the boot_pagesets that are going to be used
3774 * for bootstrapping processors. The real pagesets for
3775 * each zone will be allocated later when the per cpu
3776 * allocator is available.
3778 * boot_pagesets are used also for bootstrapping offline
3779 * cpus if the system is already booted because the pagesets
3780 * are needed to initialize allocators on a specific cpu too.
3781 * F.e. the percpu allocator needs the page allocator which
3782 * needs the percpu allocator in order to allocate its pagesets
3783 * (a chicken-egg dilemma).
3785 for_each_possible_cpu(cpu) {
3786 setup_pageset(&per_cpu(boot_pageset, cpu), 0);
3788 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
3790 * We now know the "local memory node" for each node--
3791 * i.e., the node of the first zone in the generic zonelist.
3792 * Set up numa_mem percpu variable for on-line cpus. During
3793 * boot, only the boot cpu should be on-line; we'll init the
3794 * secondary cpus' numa_mem as they come on-line. During
3795 * node/memory hotplug, we'll fixup all on-line cpus.
3797 if (cpu_online(cpu))
3798 set_cpu_numa_mem(cpu, local_memory_node(cpu_to_node(cpu)));
3799 #endif
3802 return 0;
3806 * Called with zonelists_mutex held always
3807 * unless system_state == SYSTEM_BOOTING.
3809 void __ref build_all_zonelists(pg_data_t *pgdat, struct zone *zone)
3811 set_zonelist_order();
3813 if (system_state == SYSTEM_BOOTING) {
3814 __build_all_zonelists(NULL);
3815 mminit_verify_zonelist();
3816 cpuset_init_current_mems_allowed();
3817 } else {
3818 #ifdef CONFIG_MEMORY_HOTPLUG
3819 if (zone)
3820 setup_zone_pageset(zone);
3821 #endif
3822 /* we have to stop all cpus to guarantee there is no user
3823 of zonelist */
3824 stop_machine(__build_all_zonelists, pgdat, NULL);
3825 /* cpuset refresh routine should be here */
3827 vm_total_pages = nr_free_pagecache_pages();
3829 * Disable grouping by mobility if the number of pages in the
3830 * system is too low to allow the mechanism to work. It would be
3831 * more accurate, but expensive to check per-zone. This check is
3832 * made on memory-hotadd so a system can start with mobility
3833 * disabled and enable it later
3835 if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES))
3836 page_group_by_mobility_disabled = 1;
3837 else
3838 page_group_by_mobility_disabled = 0;
3840 printk("Built %i zonelists in %s order, mobility grouping %s. "
3841 "Total pages: %ld\n",
3842 nr_online_nodes,
3843 zonelist_order_name[current_zonelist_order],
3844 page_group_by_mobility_disabled ? "off" : "on",
3845 vm_total_pages);
3846 #ifdef CONFIG_NUMA
3847 printk("Policy zone: %s\n", zone_names[policy_zone]);
3848 #endif
3852 * Helper functions to size the waitqueue hash table.
3853 * Essentially these want to choose hash table sizes sufficiently
3854 * large so that collisions trying to wait on pages are rare.
3855 * But in fact, the number of active page waitqueues on typical
3856 * systems is ridiculously low, less than 200. So this is even
3857 * conservative, even though it seems large.
3859 * The constant PAGES_PER_WAITQUEUE specifies the ratio of pages to
3860 * waitqueues, i.e. the size of the waitq table given the number of pages.
3862 #define PAGES_PER_WAITQUEUE 256
3864 #ifndef CONFIG_MEMORY_HOTPLUG
3865 static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
3867 unsigned long size = 1;
3869 pages /= PAGES_PER_WAITQUEUE;
3871 while (size < pages)
3872 size <<= 1;
3875 * Once we have dozens or even hundreds of threads sleeping
3876 * on IO we've got bigger problems than wait queue collision.
3877 * Limit the size of the wait table to a reasonable size.
3879 size = min(size, 4096UL);
3881 return max(size, 4UL);
3883 #else
3885 * A zone's size might be changed by hot-add, so it is not possible to determine
3886 * a suitable size for its wait_table. So we use the maximum size now.
3888 * The max wait table size = 4096 x sizeof(wait_queue_head_t). ie:
3890 * i386 (preemption config) : 4096 x 16 = 64Kbyte.
3891 * ia64, x86-64 (no preemption): 4096 x 20 = 80Kbyte.
3892 * ia64, x86-64 (preemption) : 4096 x 24 = 96Kbyte.
3894 * The maximum entries are prepared when a zone's memory is (512K + 256) pages
3895 * or more by the traditional way. (See above). It equals:
3897 * i386, x86-64, powerpc(4K page size) : = ( 2G + 1M)byte.
3898 * ia64(16K page size) : = ( 8G + 4M)byte.
3899 * powerpc (64K page size) : = (32G +16M)byte.
3901 static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
3903 return 4096UL;
3905 #endif
3908 * This is an integer logarithm so that shifts can be used later
3909 * to extract the more random high bits from the multiplicative
3910 * hash function before the remainder is taken.
3912 static inline unsigned long wait_table_bits(unsigned long size)
3914 return ffz(~size);
3917 #define LONG_ALIGN(x) (((x)+(sizeof(long))-1)&~((sizeof(long))-1))
3920 * Check if a pageblock contains reserved pages
3922 static int pageblock_is_reserved(unsigned long start_pfn, unsigned long end_pfn)
3924 unsigned long pfn;
3926 for (pfn = start_pfn; pfn < end_pfn; pfn++) {
3927 if (!pfn_valid_within(pfn) || PageReserved(pfn_to_page(pfn)))
3928 return 1;
3930 return 0;
3934 * Mark a number of pageblocks as MIGRATE_RESERVE. The number
3935 * of blocks reserved is based on min_wmark_pages(zone). The memory within
3936 * the reserve will tend to store contiguous free pages. Setting min_free_kbytes
3937 * higher will lead to a bigger reserve which will get freed as contiguous
3938 * blocks as reclaim kicks in
3940 static void setup_zone_migrate_reserve(struct zone *zone)
3942 unsigned long start_pfn, pfn, end_pfn, block_end_pfn;
3943 struct page *page;
3944 unsigned long block_migratetype;
3945 int reserve;
3948 * Get the start pfn, end pfn and the number of blocks to reserve
3949 * We have to be careful to be aligned to pageblock_nr_pages to
3950 * make sure that we always check pfn_valid for the first page in
3951 * the block.
3953 start_pfn = zone->zone_start_pfn;
3954 end_pfn = zone_end_pfn(zone);
3955 start_pfn = roundup(start_pfn, pageblock_nr_pages);
3956 reserve = roundup(min_wmark_pages(zone), pageblock_nr_pages) >>
3957 pageblock_order;
3960 * Reserve blocks are generally in place to help high-order atomic
3961 * allocations that are short-lived. A min_free_kbytes value that
3962 * would result in more than 2 reserve blocks for atomic allocations
3963 * is assumed to be in place to help anti-fragmentation for the
3964 * future allocation of hugepages at runtime.
3966 reserve = min(2, reserve);
3968 for (pfn = start_pfn; pfn < end_pfn; pfn += pageblock_nr_pages) {
3969 if (!pfn_valid(pfn))
3970 continue;
3971 page = pfn_to_page(pfn);
3973 /* Watch out for overlapping nodes */
3974 if (page_to_nid(page) != zone_to_nid(zone))
3975 continue;
3977 block_migratetype = get_pageblock_migratetype(page);
3979 /* Only test what is necessary when the reserves are not met */
3980 if (reserve > 0) {
3982 * Blocks with reserved pages will never free, skip
3983 * them.
3985 block_end_pfn = min(pfn + pageblock_nr_pages, end_pfn);
3986 if (pageblock_is_reserved(pfn, block_end_pfn))
3987 continue;
3989 /* If this block is reserved, account for it */
3990 if (block_migratetype == MIGRATE_RESERVE) {
3991 reserve--;
3992 continue;
3995 /* Suitable for reserving if this block is movable */
3996 if (block_migratetype == MIGRATE_MOVABLE) {
3997 set_pageblock_migratetype(page,
3998 MIGRATE_RESERVE);
3999 move_freepages_block(zone, page,
4000 MIGRATE_RESERVE);
4001 reserve--;
4002 continue;
4007 * If the reserve is met and this is a previous reserved block,
4008 * take it back
4010 if (block_migratetype == MIGRATE_RESERVE) {
4011 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
4012 move_freepages_block(zone, page, MIGRATE_MOVABLE);
4018 * Initially all pages are reserved - free ones are freed
4019 * up by free_all_bootmem() once the early boot process is
4020 * done. Non-atomic initialization, single-pass.
4022 void __meminit memmap_init_zone(unsigned long size, int nid, unsigned long zone,
4023 unsigned long start_pfn, enum memmap_context context)
4025 struct page *page;
4026 unsigned long end_pfn = start_pfn + size;
4027 unsigned long pfn;
4028 struct zone *z;
4030 if (highest_memmap_pfn < end_pfn - 1)
4031 highest_memmap_pfn = end_pfn - 1;
4033 z = &NODE_DATA(nid)->node_zones[zone];
4034 for (pfn = start_pfn; pfn < end_pfn; pfn++) {
4036 * There can be holes in boot-time mem_map[]s
4037 * handed to this function. They do not
4038 * exist on hotplugged memory.
4040 if (context == MEMMAP_EARLY) {
4041 if (!early_pfn_valid(pfn))
4042 continue;
4043 if (!early_pfn_in_nid(pfn, nid))
4044 continue;
4046 page = pfn_to_page(pfn);
4047 set_page_links(page, zone, nid, pfn);
4048 mminit_verify_page_links(page, zone, nid, pfn);
4049 init_page_count(page);
4050 page_mapcount_reset(page);
4051 page_nid_reset_last(page);
4052 SetPageReserved(page);
4054 * Mark the block movable so that blocks are reserved for
4055 * movable at startup. This will force kernel allocations
4056 * to reserve their blocks rather than leaking throughout
4057 * the address space during boot when many long-lived
4058 * kernel allocations are made. Later some blocks near
4059 * the start are marked MIGRATE_RESERVE by
4060 * setup_zone_migrate_reserve()
4062 * bitmap is created for zone's valid pfn range. but memmap
4063 * can be created for invalid pages (for alignment)
4064 * check here not to call set_pageblock_migratetype() against
4065 * pfn out of zone.
4067 if ((z->zone_start_pfn <= pfn)
4068 && (pfn < zone_end_pfn(z))
4069 && !(pfn & (pageblock_nr_pages - 1)))
4070 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
4072 INIT_LIST_HEAD(&page->lru);
4073 #ifdef WANT_PAGE_VIRTUAL
4074 /* The shift won't overflow because ZONE_NORMAL is below 4G. */
4075 if (!is_highmem_idx(zone))
4076 set_page_address(page, __va(pfn << PAGE_SHIFT));
4077 #endif
4081 static void __meminit zone_init_free_lists(struct zone *zone)
4083 int order, t;
4084 for_each_migratetype_order(order, t) {
4085 INIT_LIST_HEAD(&zone->free_area[order].free_list[t]);
4086 zone->free_area[order].nr_free = 0;
4090 #ifndef __HAVE_ARCH_MEMMAP_INIT
4091 #define memmap_init(size, nid, zone, start_pfn) \
4092 memmap_init_zone((size), (nid), (zone), (start_pfn), MEMMAP_EARLY)
4093 #endif
4095 static int zone_batchsize(struct zone *zone)
4097 #ifdef CONFIG_MMU
4098 int batch;
4101 * The per-cpu-pages pools are set to around 1000th of the
4102 * size of the zone. But no more than 1/2 of a meg.
4104 * OK, so we don't know how big the cache is. So guess.
4106 batch = zone->managed_pages / 1024;
4107 if (batch * PAGE_SIZE > 512 * 1024)
4108 batch = (512 * 1024) / PAGE_SIZE;
4109 batch /= 4; /* We effectively *= 4 below */
4110 if (batch < 1)
4111 batch = 1;
4114 * Clamp the batch to a 2^n - 1 value. Having a power
4115 * of 2 value was found to be more likely to have
4116 * suboptimal cache aliasing properties in some cases.
4118 * For example if 2 tasks are alternately allocating
4119 * batches of pages, one task can end up with a lot
4120 * of pages of one half of the possible page colors
4121 * and the other with pages of the other colors.
4123 batch = rounddown_pow_of_two(batch + batch/2) - 1;
4125 return batch;
4127 #else
4128 /* The deferral and batching of frees should be suppressed under NOMMU
4129 * conditions.
4131 * The problem is that NOMMU needs to be able to allocate large chunks
4132 * of contiguous memory as there's no hardware page translation to
4133 * assemble apparent contiguous memory from discontiguous pages.
4135 * Queueing large contiguous runs of pages for batching, however,
4136 * causes the pages to actually be freed in smaller chunks. As there
4137 * can be a significant delay between the individual batches being
4138 * recycled, this leads to the once large chunks of space being
4139 * fragmented and becoming unavailable for high-order allocations.
4141 return 0;
4142 #endif
4146 * pcp->high and pcp->batch values are related and dependent on one another:
4147 * ->batch must never be higher then ->high.
4148 * The following function updates them in a safe manner without read side
4149 * locking.
4151 * Any new users of pcp->batch and pcp->high should ensure they can cope with
4152 * those fields changing asynchronously (acording the the above rule).
4154 * mutex_is_locked(&pcp_batch_high_lock) required when calling this function
4155 * outside of boot time (or some other assurance that no concurrent updaters
4156 * exist).
4158 static void pageset_update(struct per_cpu_pages *pcp, unsigned long high,
4159 unsigned long batch)
4161 /* start with a fail safe value for batch */
4162 pcp->batch = 1;
4163 smp_wmb();
4165 /* Update high, then batch, in order */
4166 pcp->high = high;
4167 smp_wmb();
4169 pcp->batch = batch;
4172 /* a companion to pageset_set_high() */
4173 static void pageset_set_batch(struct per_cpu_pageset *p, unsigned long batch)
4175 pageset_update(&p->pcp, 6 * batch, max(1UL, 1 * batch));
4178 static void pageset_init(struct per_cpu_pageset *p)
4180 struct per_cpu_pages *pcp;
4181 int migratetype;
4183 memset(p, 0, sizeof(*p));
4185 pcp = &p->pcp;
4186 pcp->count = 0;
4187 for (migratetype = 0; migratetype < MIGRATE_PCPTYPES; migratetype++)
4188 INIT_LIST_HEAD(&pcp->lists[migratetype]);
4191 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch)
4193 pageset_init(p);
4194 pageset_set_batch(p, batch);
4198 * pageset_set_high() sets the high water mark for hot per_cpu_pagelist
4199 * to the value high for the pageset p.
4201 static void pageset_set_high(struct per_cpu_pageset *p,
4202 unsigned long high)
4204 unsigned long batch = max(1UL, high / 4);
4205 if ((high / 4) > (PAGE_SHIFT * 8))
4206 batch = PAGE_SHIFT * 8;
4208 pageset_update(&p->pcp, high, batch);
4211 static void pageset_set_high_and_batch(struct zone *zone,
4212 struct per_cpu_pageset *pcp)
4214 if (percpu_pagelist_fraction)
4215 pageset_set_high(pcp,
4216 (zone->managed_pages /
4217 percpu_pagelist_fraction));
4218 else
4219 pageset_set_batch(pcp, zone_batchsize(zone));
4222 static void __meminit zone_pageset_init(struct zone *zone, int cpu)
4224 struct per_cpu_pageset *pcp = per_cpu_ptr(zone->pageset, cpu);
4226 pageset_init(pcp);
4227 pageset_set_high_and_batch(zone, pcp);
4230 static void __meminit setup_zone_pageset(struct zone *zone)
4232 int cpu;
4233 zone->pageset = alloc_percpu(struct per_cpu_pageset);
4234 for_each_possible_cpu(cpu)
4235 zone_pageset_init(zone, cpu);
4239 * Allocate per cpu pagesets and initialize them.
4240 * Before this call only boot pagesets were available.
4242 void __init setup_per_cpu_pageset(void)
4244 struct zone *zone;
4246 for_each_populated_zone(zone)
4247 setup_zone_pageset(zone);
4250 static noinline __init_refok
4251 int zone_wait_table_init(struct zone *zone, unsigned long zone_size_pages)
4253 int i;
4254 struct pglist_data *pgdat = zone->zone_pgdat;
4255 size_t alloc_size;
4258 * The per-page waitqueue mechanism uses hashed waitqueues
4259 * per zone.
4261 zone->wait_table_hash_nr_entries =
4262 wait_table_hash_nr_entries(zone_size_pages);
4263 zone->wait_table_bits =
4264 wait_table_bits(zone->wait_table_hash_nr_entries);
4265 alloc_size = zone->wait_table_hash_nr_entries
4266 * sizeof(wait_queue_head_t);
4268 if (!slab_is_available()) {
4269 zone->wait_table = (wait_queue_head_t *)
4270 alloc_bootmem_node_nopanic(pgdat, alloc_size);
4271 } else {
4273 * This case means that a zone whose size was 0 gets new memory
4274 * via memory hot-add.
4275 * But it may be the case that a new node was hot-added. In
4276 * this case vmalloc() will not be able to use this new node's
4277 * memory - this wait_table must be initialized to use this new
4278 * node itself as well.
4279 * To use this new node's memory, further consideration will be
4280 * necessary.
4282 zone->wait_table = vmalloc(alloc_size);
4284 if (!zone->wait_table)
4285 return -ENOMEM;
4287 for (i = 0; i < zone->wait_table_hash_nr_entries; ++i)
4288 init_waitqueue_head(zone->wait_table + i);
4290 return 0;
4293 static __meminit void zone_pcp_init(struct zone *zone)
4296 * per cpu subsystem is not up at this point. The following code
4297 * relies on the ability of the linker to provide the
4298 * offset of a (static) per cpu variable into the per cpu area.
4300 zone->pageset = &boot_pageset;
4302 if (zone->present_pages)
4303 printk(KERN_DEBUG " %s zone: %lu pages, LIFO batch:%u\n",
4304 zone->name, zone->present_pages,
4305 zone_batchsize(zone));
4308 int __meminit init_currently_empty_zone(struct zone *zone,
4309 unsigned long zone_start_pfn,
4310 unsigned long size,
4311 enum memmap_context context)
4313 struct pglist_data *pgdat = zone->zone_pgdat;
4314 int ret;
4315 ret = zone_wait_table_init(zone, size);
4316 if (ret)
4317 return ret;
4318 pgdat->nr_zones = zone_idx(zone) + 1;
4320 zone->zone_start_pfn = zone_start_pfn;
4322 mminit_dprintk(MMINIT_TRACE, "memmap_init",
4323 "Initialising map node %d zone %lu pfns %lu -> %lu\n",
4324 pgdat->node_id,
4325 (unsigned long)zone_idx(zone),
4326 zone_start_pfn, (zone_start_pfn + size));
4328 zone_init_free_lists(zone);
4330 return 0;
4333 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
4334 #ifndef CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID
4336 * Required by SPARSEMEM. Given a PFN, return what node the PFN is on.
4337 * Architectures may implement their own version but if add_active_range()
4338 * was used and there are no special requirements, this is a convenient
4339 * alternative
4341 int __meminit __early_pfn_to_nid(unsigned long pfn)
4343 unsigned long start_pfn, end_pfn;
4344 int nid;
4346 * NOTE: The following SMP-unsafe globals are only used early in boot
4347 * when the kernel is running single-threaded.
4349 static unsigned long __meminitdata last_start_pfn, last_end_pfn;
4350 static int __meminitdata last_nid;
4352 if (last_start_pfn <= pfn && pfn < last_end_pfn)
4353 return last_nid;
4355 nid = memblock_search_pfn_nid(pfn, &start_pfn, &end_pfn);
4356 if (nid != -1) {
4357 last_start_pfn = start_pfn;
4358 last_end_pfn = end_pfn;
4359 last_nid = nid;
4362 return nid;
4364 #endif /* CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID */
4366 int __meminit early_pfn_to_nid(unsigned long pfn)
4368 int nid;
4370 nid = __early_pfn_to_nid(pfn);
4371 if (nid >= 0)
4372 return nid;
4373 /* just returns 0 */
4374 return 0;
4377 #ifdef CONFIG_NODES_SPAN_OTHER_NODES
4378 bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
4380 int nid;
4382 nid = __early_pfn_to_nid(pfn);
4383 if (nid >= 0 && nid != node)
4384 return false;
4385 return true;
4387 #endif
4390 * free_bootmem_with_active_regions - Call free_bootmem_node for each active range
4391 * @nid: The node to free memory on. If MAX_NUMNODES, all nodes are freed.
4392 * @max_low_pfn: The highest PFN that will be passed to free_bootmem_node
4394 * If an architecture guarantees that all ranges registered with
4395 * add_active_ranges() contain no holes and may be freed, this
4396 * this function may be used instead of calling free_bootmem() manually.
4398 void __init free_bootmem_with_active_regions(int nid, unsigned long max_low_pfn)
4400 unsigned long start_pfn, end_pfn;
4401 int i, this_nid;
4403 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, &this_nid) {
4404 start_pfn = min(start_pfn, max_low_pfn);
4405 end_pfn = min(end_pfn, max_low_pfn);
4407 if (start_pfn < end_pfn)
4408 free_bootmem_node(NODE_DATA(this_nid),
4409 PFN_PHYS(start_pfn),
4410 (end_pfn - start_pfn) << PAGE_SHIFT);
4415 * sparse_memory_present_with_active_regions - Call memory_present for each active range
4416 * @nid: The node to call memory_present for. If MAX_NUMNODES, all nodes will be used.
4418 * If an architecture guarantees that all ranges registered with
4419 * add_active_ranges() contain no holes and may be freed, this
4420 * function may be used instead of calling memory_present() manually.
4422 void __init sparse_memory_present_with_active_regions(int nid)
4424 unsigned long start_pfn, end_pfn;
4425 int i, this_nid;
4427 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, &this_nid)
4428 memory_present(this_nid, start_pfn, end_pfn);
4432 * get_pfn_range_for_nid - Return the start and end page frames for a node
4433 * @nid: The nid to return the range for. If MAX_NUMNODES, the min and max PFN are returned.
4434 * @start_pfn: Passed by reference. On return, it will have the node start_pfn.
4435 * @end_pfn: Passed by reference. On return, it will have the node end_pfn.
4437 * It returns the start and end page frame of a node based on information
4438 * provided by an arch calling add_active_range(). If called for a node
4439 * with no available memory, a warning is printed and the start and end
4440 * PFNs will be 0.
4442 void __meminit get_pfn_range_for_nid(unsigned int nid,
4443 unsigned long *start_pfn, unsigned long *end_pfn)
4445 unsigned long this_start_pfn, this_end_pfn;
4446 int i;
4448 *start_pfn = -1UL;
4449 *end_pfn = 0;
4451 for_each_mem_pfn_range(i, nid, &this_start_pfn, &this_end_pfn, NULL) {
4452 *start_pfn = min(*start_pfn, this_start_pfn);
4453 *end_pfn = max(*end_pfn, this_end_pfn);
4456 if (*start_pfn == -1UL)
4457 *start_pfn = 0;
4461 * This finds a zone that can be used for ZONE_MOVABLE pages. The
4462 * assumption is made that zones within a node are ordered in monotonic
4463 * increasing memory addresses so that the "highest" populated zone is used
4465 static void __init find_usable_zone_for_movable(void)
4467 int zone_index;
4468 for (zone_index = MAX_NR_ZONES - 1; zone_index >= 0; zone_index--) {
4469 if (zone_index == ZONE_MOVABLE)
4470 continue;
4472 if (arch_zone_highest_possible_pfn[zone_index] >
4473 arch_zone_lowest_possible_pfn[zone_index])
4474 break;
4477 VM_BUG_ON(zone_index == -1);
4478 movable_zone = zone_index;
4482 * The zone ranges provided by the architecture do not include ZONE_MOVABLE
4483 * because it is sized independent of architecture. Unlike the other zones,
4484 * the starting point for ZONE_MOVABLE is not fixed. It may be different
4485 * in each node depending on the size of each node and how evenly kernelcore
4486 * is distributed. This helper function adjusts the zone ranges
4487 * provided by the architecture for a given node by using the end of the
4488 * highest usable zone for ZONE_MOVABLE. This preserves the assumption that
4489 * zones within a node are in order of monotonic increases memory addresses
4491 static void __meminit adjust_zone_range_for_zone_movable(int nid,
4492 unsigned long zone_type,
4493 unsigned long node_start_pfn,
4494 unsigned long node_end_pfn,
4495 unsigned long *zone_start_pfn,
4496 unsigned long *zone_end_pfn)
4498 /* Only adjust if ZONE_MOVABLE is on this node */
4499 if (zone_movable_pfn[nid]) {
4500 /* Size ZONE_MOVABLE */
4501 if (zone_type == ZONE_MOVABLE) {
4502 *zone_start_pfn = zone_movable_pfn[nid];
4503 *zone_end_pfn = min(node_end_pfn,
4504 arch_zone_highest_possible_pfn[movable_zone]);
4506 /* Adjust for ZONE_MOVABLE starting within this range */
4507 } else if (*zone_start_pfn < zone_movable_pfn[nid] &&
4508 *zone_end_pfn > zone_movable_pfn[nid]) {
4509 *zone_end_pfn = zone_movable_pfn[nid];
4511 /* Check if this whole range is within ZONE_MOVABLE */
4512 } else if (*zone_start_pfn >= zone_movable_pfn[nid])
4513 *zone_start_pfn = *zone_end_pfn;
4518 * Return the number of pages a zone spans in a node, including holes
4519 * present_pages = zone_spanned_pages_in_node() - zone_absent_pages_in_node()
4521 static unsigned long __meminit zone_spanned_pages_in_node(int nid,
4522 unsigned long zone_type,
4523 unsigned long node_start_pfn,
4524 unsigned long node_end_pfn,
4525 unsigned long *ignored)
4527 unsigned long zone_start_pfn, zone_end_pfn;
4529 /* Get the start and end of the zone */
4530 zone_start_pfn = arch_zone_lowest_possible_pfn[zone_type];
4531 zone_end_pfn = arch_zone_highest_possible_pfn[zone_type];
4532 adjust_zone_range_for_zone_movable(nid, zone_type,
4533 node_start_pfn, node_end_pfn,
4534 &zone_start_pfn, &zone_end_pfn);
4536 /* Check that this node has pages within the zone's required range */
4537 if (zone_end_pfn < node_start_pfn || zone_start_pfn > node_end_pfn)
4538 return 0;
4540 /* Move the zone boundaries inside the node if necessary */
4541 zone_end_pfn = min(zone_end_pfn, node_end_pfn);
4542 zone_start_pfn = max(zone_start_pfn, node_start_pfn);
4544 /* Return the spanned pages */
4545 return zone_end_pfn - zone_start_pfn;
4549 * Return the number of holes in a range on a node. If nid is MAX_NUMNODES,
4550 * then all holes in the requested range will be accounted for.
4552 unsigned long __meminit __absent_pages_in_range(int nid,
4553 unsigned long range_start_pfn,
4554 unsigned long range_end_pfn)
4556 unsigned long nr_absent = range_end_pfn - range_start_pfn;
4557 unsigned long start_pfn, end_pfn;
4558 int i;
4560 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
4561 start_pfn = clamp(start_pfn, range_start_pfn, range_end_pfn);
4562 end_pfn = clamp(end_pfn, range_start_pfn, range_end_pfn);
4563 nr_absent -= end_pfn - start_pfn;
4565 return nr_absent;
4569 * absent_pages_in_range - Return number of page frames in holes within a range
4570 * @start_pfn: The start PFN to start searching for holes
4571 * @end_pfn: The end PFN to stop searching for holes
4573 * It returns the number of pages frames in memory holes within a range.
4575 unsigned long __init absent_pages_in_range(unsigned long start_pfn,
4576 unsigned long end_pfn)
4578 return __absent_pages_in_range(MAX_NUMNODES, start_pfn, end_pfn);
4581 /* Return the number of page frames in holes in a zone on a node */
4582 static unsigned long __meminit zone_absent_pages_in_node(int nid,
4583 unsigned long zone_type,
4584 unsigned long node_start_pfn,
4585 unsigned long node_end_pfn,
4586 unsigned long *ignored)
4588 unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type];
4589 unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type];
4590 unsigned long zone_start_pfn, zone_end_pfn;
4592 zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high);
4593 zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high);
4595 adjust_zone_range_for_zone_movable(nid, zone_type,
4596 node_start_pfn, node_end_pfn,
4597 &zone_start_pfn, &zone_end_pfn);
4598 return __absent_pages_in_range(nid, zone_start_pfn, zone_end_pfn);
4601 #else /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
4602 static inline unsigned long __meminit zone_spanned_pages_in_node(int nid,
4603 unsigned long zone_type,
4604 unsigned long node_start_pfn,
4605 unsigned long node_end_pfn,
4606 unsigned long *zones_size)
4608 return zones_size[zone_type];
4611 static inline unsigned long __meminit zone_absent_pages_in_node(int nid,
4612 unsigned long zone_type,
4613 unsigned long node_start_pfn,
4614 unsigned long node_end_pfn,
4615 unsigned long *zholes_size)
4617 if (!zholes_size)
4618 return 0;
4620 return zholes_size[zone_type];
4623 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
4625 static void __meminit calculate_node_totalpages(struct pglist_data *pgdat,
4626 unsigned long node_start_pfn,
4627 unsigned long node_end_pfn,
4628 unsigned long *zones_size,
4629 unsigned long *zholes_size)
4631 unsigned long realtotalpages, totalpages = 0;
4632 enum zone_type i;
4634 for (i = 0; i < MAX_NR_ZONES; i++)
4635 totalpages += zone_spanned_pages_in_node(pgdat->node_id, i,
4636 node_start_pfn,
4637 node_end_pfn,
4638 zones_size);
4639 pgdat->node_spanned_pages = totalpages;
4641 realtotalpages = totalpages;
4642 for (i = 0; i < MAX_NR_ZONES; i++)
4643 realtotalpages -=
4644 zone_absent_pages_in_node(pgdat->node_id, i,
4645 node_start_pfn, node_end_pfn,
4646 zholes_size);
4647 pgdat->node_present_pages = realtotalpages;
4648 printk(KERN_DEBUG "On node %d totalpages: %lu\n", pgdat->node_id,
4649 realtotalpages);
4652 #ifndef CONFIG_SPARSEMEM
4654 * Calculate the size of the zone->blockflags rounded to an unsigned long
4655 * Start by making sure zonesize is a multiple of pageblock_order by rounding
4656 * up. Then use 1 NR_PAGEBLOCK_BITS worth of bits per pageblock, finally
4657 * round what is now in bits to nearest long in bits, then return it in
4658 * bytes.
4660 static unsigned long __init usemap_size(unsigned long zone_start_pfn, unsigned long zonesize)
4662 unsigned long usemapsize;
4664 zonesize += zone_start_pfn & (pageblock_nr_pages-1);
4665 usemapsize = roundup(zonesize, pageblock_nr_pages);
4666 usemapsize = usemapsize >> pageblock_order;
4667 usemapsize *= NR_PAGEBLOCK_BITS;
4668 usemapsize = roundup(usemapsize, 8 * sizeof(unsigned long));
4670 return usemapsize / 8;
4673 static void __init setup_usemap(struct pglist_data *pgdat,
4674 struct zone *zone,
4675 unsigned long zone_start_pfn,
4676 unsigned long zonesize)
4678 unsigned long usemapsize = usemap_size(zone_start_pfn, zonesize);
4679 zone->pageblock_flags = NULL;
4680 if (usemapsize)
4681 zone->pageblock_flags = alloc_bootmem_node_nopanic(pgdat,
4682 usemapsize);
4684 #else
4685 static inline void setup_usemap(struct pglist_data *pgdat, struct zone *zone,
4686 unsigned long zone_start_pfn, unsigned long zonesize) {}
4687 #endif /* CONFIG_SPARSEMEM */
4689 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
4691 /* Initialise the number of pages represented by NR_PAGEBLOCK_BITS */
4692 void __paginginit set_pageblock_order(void)
4694 unsigned int order;
4696 /* Check that pageblock_nr_pages has not already been setup */
4697 if (pageblock_order)
4698 return;
4700 if (HPAGE_SHIFT > PAGE_SHIFT)
4701 order = HUGETLB_PAGE_ORDER;
4702 else
4703 order = MAX_ORDER - 1;
4706 * Assume the largest contiguous order of interest is a huge page.
4707 * This value may be variable depending on boot parameters on IA64 and
4708 * powerpc.
4710 pageblock_order = order;
4712 #else /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
4715 * When CONFIG_HUGETLB_PAGE_SIZE_VARIABLE is not set, set_pageblock_order()
4716 * is unused as pageblock_order is set at compile-time. See
4717 * include/linux/pageblock-flags.h for the values of pageblock_order based on
4718 * the kernel config
4720 void __paginginit set_pageblock_order(void)
4724 #endif /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
4726 static unsigned long __paginginit calc_memmap_size(unsigned long spanned_pages,
4727 unsigned long present_pages)
4729 unsigned long pages = spanned_pages;
4732 * Provide a more accurate estimation if there are holes within
4733 * the zone and SPARSEMEM is in use. If there are holes within the
4734 * zone, each populated memory region may cost us one or two extra
4735 * memmap pages due to alignment because memmap pages for each
4736 * populated regions may not naturally algined on page boundary.
4737 * So the (present_pages >> 4) heuristic is a tradeoff for that.
4739 if (spanned_pages > present_pages + (present_pages >> 4) &&
4740 IS_ENABLED(CONFIG_SPARSEMEM))
4741 pages = present_pages;
4743 return PAGE_ALIGN(pages * sizeof(struct page)) >> PAGE_SHIFT;
4747 * Set up the zone data structures:
4748 * - mark all pages reserved
4749 * - mark all memory queues empty
4750 * - clear the memory bitmaps
4752 * NOTE: pgdat should get zeroed by caller.
4754 static void __paginginit free_area_init_core(struct pglist_data *pgdat,
4755 unsigned long node_start_pfn, unsigned long node_end_pfn,
4756 unsigned long *zones_size, unsigned long *zholes_size)
4758 enum zone_type j;
4759 int nid = pgdat->node_id;
4760 unsigned long zone_start_pfn = pgdat->node_start_pfn;
4761 int ret;
4763 pgdat_resize_init(pgdat);
4764 #ifdef CONFIG_NUMA_BALANCING
4765 spin_lock_init(&pgdat->numabalancing_migrate_lock);
4766 pgdat->numabalancing_migrate_nr_pages = 0;
4767 pgdat->numabalancing_migrate_next_window = jiffies;
4768 #endif
4769 init_waitqueue_head(&pgdat->kswapd_wait);
4770 init_waitqueue_head(&pgdat->pfmemalloc_wait);
4771 pgdat_page_cgroup_init(pgdat);
4773 for (j = 0; j < MAX_NR_ZONES; j++) {
4774 struct zone *zone = pgdat->node_zones + j;
4775 unsigned long size, realsize, freesize, memmap_pages;
4777 size = zone_spanned_pages_in_node(nid, j, node_start_pfn,
4778 node_end_pfn, zones_size);
4779 realsize = freesize = size - zone_absent_pages_in_node(nid, j,
4780 node_start_pfn,
4781 node_end_pfn,
4782 zholes_size);
4785 * Adjust freesize so that it accounts for how much memory
4786 * is used by this zone for memmap. This affects the watermark
4787 * and per-cpu initialisations
4789 memmap_pages = calc_memmap_size(size, realsize);
4790 if (freesize >= memmap_pages) {
4791 freesize -= memmap_pages;
4792 if (memmap_pages)
4793 printk(KERN_DEBUG
4794 " %s zone: %lu pages used for memmap\n",
4795 zone_names[j], memmap_pages);
4796 } else
4797 printk(KERN_WARNING
4798 " %s zone: %lu pages exceeds freesize %lu\n",
4799 zone_names[j], memmap_pages, freesize);
4801 /* Account for reserved pages */
4802 if (j == 0 && freesize > dma_reserve) {
4803 freesize -= dma_reserve;
4804 printk(KERN_DEBUG " %s zone: %lu pages reserved\n",
4805 zone_names[0], dma_reserve);
4808 if (!is_highmem_idx(j))
4809 nr_kernel_pages += freesize;
4810 /* Charge for highmem memmap if there are enough kernel pages */
4811 else if (nr_kernel_pages > memmap_pages * 2)
4812 nr_kernel_pages -= memmap_pages;
4813 nr_all_pages += freesize;
4815 zone->spanned_pages = size;
4816 zone->present_pages = realsize;
4818 * Set an approximate value for lowmem here, it will be adjusted
4819 * when the bootmem allocator frees pages into the buddy system.
4820 * And all highmem pages will be managed by the buddy system.
4822 zone->managed_pages = is_highmem_idx(j) ? realsize : freesize;
4823 #ifdef CONFIG_NUMA
4824 zone->node = nid;
4825 zone->min_unmapped_pages = (freesize*sysctl_min_unmapped_ratio)
4826 / 100;
4827 zone->min_slab_pages = (freesize * sysctl_min_slab_ratio) / 100;
4828 #endif
4829 zone->name = zone_names[j];
4830 spin_lock_init(&zone->lock);
4831 spin_lock_init(&zone->lru_lock);
4832 zone_seqlock_init(zone);
4833 zone->zone_pgdat = pgdat;
4834 zone_pcp_init(zone);
4836 /* For bootup, initialized properly in watermark setup */
4837 mod_zone_page_state(zone, NR_ALLOC_BATCH, zone->managed_pages);
4839 lruvec_init(&zone->lruvec);
4840 if (!size)
4841 continue;
4843 set_pageblock_order();
4844 setup_usemap(pgdat, zone, zone_start_pfn, size);
4845 ret = init_currently_empty_zone(zone, zone_start_pfn,
4846 size, MEMMAP_EARLY);
4847 BUG_ON(ret);
4848 memmap_init(size, nid, j, zone_start_pfn);
4849 zone_start_pfn += size;
4853 static void __init_refok alloc_node_mem_map(struct pglist_data *pgdat)
4855 /* Skip empty nodes */
4856 if (!pgdat->node_spanned_pages)
4857 return;
4859 #ifdef CONFIG_FLAT_NODE_MEM_MAP
4860 /* ia64 gets its own node_mem_map, before this, without bootmem */
4861 if (!pgdat->node_mem_map) {
4862 unsigned long size, start, end;
4863 struct page *map;
4866 * The zone's endpoints aren't required to be MAX_ORDER
4867 * aligned but the node_mem_map endpoints must be in order
4868 * for the buddy allocator to function correctly.
4870 start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1);
4871 end = pgdat_end_pfn(pgdat);
4872 end = ALIGN(end, MAX_ORDER_NR_PAGES);
4873 size = (end - start) * sizeof(struct page);
4874 map = alloc_remap(pgdat->node_id, size);
4875 if (!map)
4876 map = alloc_bootmem_node_nopanic(pgdat, size);
4877 pgdat->node_mem_map = map + (pgdat->node_start_pfn - start);
4879 #ifndef CONFIG_NEED_MULTIPLE_NODES
4881 * With no DISCONTIG, the global mem_map is just set as node 0's
4883 if (pgdat == NODE_DATA(0)) {
4884 mem_map = NODE_DATA(0)->node_mem_map;
4885 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
4886 if (page_to_pfn(mem_map) != pgdat->node_start_pfn)
4887 mem_map -= (pgdat->node_start_pfn - ARCH_PFN_OFFSET);
4888 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
4890 #endif
4891 #endif /* CONFIG_FLAT_NODE_MEM_MAP */
4894 void __paginginit free_area_init_node(int nid, unsigned long *zones_size,
4895 unsigned long node_start_pfn, unsigned long *zholes_size)
4897 pg_data_t *pgdat = NODE_DATA(nid);
4898 unsigned long start_pfn = 0;
4899 unsigned long end_pfn = 0;
4901 /* pg_data_t should be reset to zero when it's allocated */
4902 WARN_ON(pgdat->nr_zones || pgdat->classzone_idx);
4904 pgdat->node_id = nid;
4905 pgdat->node_start_pfn = node_start_pfn;
4906 init_zone_allows_reclaim(nid);
4907 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
4908 get_pfn_range_for_nid(nid, &start_pfn, &end_pfn);
4909 #endif
4910 calculate_node_totalpages(pgdat, start_pfn, end_pfn,
4911 zones_size, zholes_size);
4913 alloc_node_mem_map(pgdat);
4914 #ifdef CONFIG_FLAT_NODE_MEM_MAP
4915 printk(KERN_DEBUG "free_area_init_node: node %d, pgdat %08lx, node_mem_map %08lx\n",
4916 nid, (unsigned long)pgdat,
4917 (unsigned long)pgdat->node_mem_map);
4918 #endif
4920 free_area_init_core(pgdat, start_pfn, end_pfn,
4921 zones_size, zholes_size);
4924 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
4926 #if MAX_NUMNODES > 1
4928 * Figure out the number of possible node ids.
4930 void __init setup_nr_node_ids(void)
4932 unsigned int node;
4933 unsigned int highest = 0;
4935 for_each_node_mask(node, node_possible_map)
4936 highest = node;
4937 nr_node_ids = highest + 1;
4939 #endif
4942 * node_map_pfn_alignment - determine the maximum internode alignment
4944 * This function should be called after node map is populated and sorted.
4945 * It calculates the maximum power of two alignment which can distinguish
4946 * all the nodes.
4948 * For example, if all nodes are 1GiB and aligned to 1GiB, the return value
4949 * would indicate 1GiB alignment with (1 << (30 - PAGE_SHIFT)). If the
4950 * nodes are shifted by 256MiB, 256MiB. Note that if only the last node is
4951 * shifted, 1GiB is enough and this function will indicate so.
4953 * This is used to test whether pfn -> nid mapping of the chosen memory
4954 * model has fine enough granularity to avoid incorrect mapping for the
4955 * populated node map.
4957 * Returns the determined alignment in pfn's. 0 if there is no alignment
4958 * requirement (single node).
4960 unsigned long __init node_map_pfn_alignment(void)
4962 unsigned long accl_mask = 0, last_end = 0;
4963 unsigned long start, end, mask;
4964 int last_nid = -1;
4965 int i, nid;
4967 for_each_mem_pfn_range(i, MAX_NUMNODES, &start, &end, &nid) {
4968 if (!start || last_nid < 0 || last_nid == nid) {
4969 last_nid = nid;
4970 last_end = end;
4971 continue;
4975 * Start with a mask granular enough to pin-point to the
4976 * start pfn and tick off bits one-by-one until it becomes
4977 * too coarse to separate the current node from the last.
4979 mask = ~((1 << __ffs(start)) - 1);
4980 while (mask && last_end <= (start & (mask << 1)))
4981 mask <<= 1;
4983 /* accumulate all internode masks */
4984 accl_mask |= mask;
4987 /* convert mask to number of pages */
4988 return ~accl_mask + 1;
4991 /* Find the lowest pfn for a node */
4992 static unsigned long __init find_min_pfn_for_node(int nid)
4994 unsigned long min_pfn = ULONG_MAX;
4995 unsigned long start_pfn;
4996 int i;
4998 for_each_mem_pfn_range(i, nid, &start_pfn, NULL, NULL)
4999 min_pfn = min(min_pfn, start_pfn);
5001 if (min_pfn == ULONG_MAX) {
5002 printk(KERN_WARNING
5003 "Could not find start_pfn for node %d\n", nid);
5004 return 0;
5007 return min_pfn;
5011 * find_min_pfn_with_active_regions - Find the minimum PFN registered
5013 * It returns the minimum PFN based on information provided via
5014 * add_active_range().
5016 unsigned long __init find_min_pfn_with_active_regions(void)
5018 return find_min_pfn_for_node(MAX_NUMNODES);
5022 * early_calculate_totalpages()
5023 * Sum pages in active regions for movable zone.
5024 * Populate N_MEMORY for calculating usable_nodes.
5026 static unsigned long __init early_calculate_totalpages(void)
5028 unsigned long totalpages = 0;
5029 unsigned long start_pfn, end_pfn;
5030 int i, nid;
5032 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
5033 unsigned long pages = end_pfn - start_pfn;
5035 totalpages += pages;
5036 if (pages)
5037 node_set_state(nid, N_MEMORY);
5039 return totalpages;
5043 * Find the PFN the Movable zone begins in each node. Kernel memory
5044 * is spread evenly between nodes as long as the nodes have enough
5045 * memory. When they don't, some nodes will have more kernelcore than
5046 * others
5048 static void __init find_zone_movable_pfns_for_nodes(void)
5050 int i, nid;
5051 unsigned long usable_startpfn;
5052 unsigned long kernelcore_node, kernelcore_remaining;
5053 /* save the state before borrow the nodemask */
5054 nodemask_t saved_node_state = node_states[N_MEMORY];
5055 unsigned long totalpages = early_calculate_totalpages();
5056 int usable_nodes = nodes_weight(node_states[N_MEMORY]);
5059 * If movablecore was specified, calculate what size of
5060 * kernelcore that corresponds so that memory usable for
5061 * any allocation type is evenly spread. If both kernelcore
5062 * and movablecore are specified, then the value of kernelcore
5063 * will be used for required_kernelcore if it's greater than
5064 * what movablecore would have allowed.
5066 if (required_movablecore) {
5067 unsigned long corepages;
5070 * Round-up so that ZONE_MOVABLE is at least as large as what
5071 * was requested by the user
5073 required_movablecore =
5074 roundup(required_movablecore, MAX_ORDER_NR_PAGES);
5075 corepages = totalpages - required_movablecore;
5077 required_kernelcore = max(required_kernelcore, corepages);
5080 /* If kernelcore was not specified, there is no ZONE_MOVABLE */
5081 if (!required_kernelcore)
5082 goto out;
5084 /* usable_startpfn is the lowest possible pfn ZONE_MOVABLE can be at */
5085 find_usable_zone_for_movable();
5086 usable_startpfn = arch_zone_lowest_possible_pfn[movable_zone];
5088 restart:
5089 /* Spread kernelcore memory as evenly as possible throughout nodes */
5090 kernelcore_node = required_kernelcore / usable_nodes;
5091 for_each_node_state(nid, N_MEMORY) {
5092 unsigned long start_pfn, end_pfn;
5095 * Recalculate kernelcore_node if the division per node
5096 * now exceeds what is necessary to satisfy the requested
5097 * amount of memory for the kernel
5099 if (required_kernelcore < kernelcore_node)
5100 kernelcore_node = required_kernelcore / usable_nodes;
5103 * As the map is walked, we track how much memory is usable
5104 * by the kernel using kernelcore_remaining. When it is
5105 * 0, the rest of the node is usable by ZONE_MOVABLE
5107 kernelcore_remaining = kernelcore_node;
5109 /* Go through each range of PFNs within this node */
5110 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
5111 unsigned long size_pages;
5113 start_pfn = max(start_pfn, zone_movable_pfn[nid]);
5114 if (start_pfn >= end_pfn)
5115 continue;
5117 /* Account for what is only usable for kernelcore */
5118 if (start_pfn < usable_startpfn) {
5119 unsigned long kernel_pages;
5120 kernel_pages = min(end_pfn, usable_startpfn)
5121 - start_pfn;
5123 kernelcore_remaining -= min(kernel_pages,
5124 kernelcore_remaining);
5125 required_kernelcore -= min(kernel_pages,
5126 required_kernelcore);
5128 /* Continue if range is now fully accounted */
5129 if (end_pfn <= usable_startpfn) {
5132 * Push zone_movable_pfn to the end so
5133 * that if we have to rebalance
5134 * kernelcore across nodes, we will
5135 * not double account here
5137 zone_movable_pfn[nid] = end_pfn;
5138 continue;
5140 start_pfn = usable_startpfn;
5144 * The usable PFN range for ZONE_MOVABLE is from
5145 * start_pfn->end_pfn. Calculate size_pages as the
5146 * number of pages used as kernelcore
5148 size_pages = end_pfn - start_pfn;
5149 if (size_pages > kernelcore_remaining)
5150 size_pages = kernelcore_remaining;
5151 zone_movable_pfn[nid] = start_pfn + size_pages;
5154 * Some kernelcore has been met, update counts and
5155 * break if the kernelcore for this node has been
5156 * satisfied
5158 required_kernelcore -= min(required_kernelcore,
5159 size_pages);
5160 kernelcore_remaining -= size_pages;
5161 if (!kernelcore_remaining)
5162 break;
5167 * If there is still required_kernelcore, we do another pass with one
5168 * less node in the count. This will push zone_movable_pfn[nid] further
5169 * along on the nodes that still have memory until kernelcore is
5170 * satisfied
5172 usable_nodes--;
5173 if (usable_nodes && required_kernelcore > usable_nodes)
5174 goto restart;
5176 /* Align start of ZONE_MOVABLE on all nids to MAX_ORDER_NR_PAGES */
5177 for (nid = 0; nid < MAX_NUMNODES; nid++)
5178 zone_movable_pfn[nid] =
5179 roundup(zone_movable_pfn[nid], MAX_ORDER_NR_PAGES);
5181 out:
5182 /* restore the node_state */
5183 node_states[N_MEMORY] = saved_node_state;
5186 /* Any regular or high memory on that node ? */
5187 static void check_for_memory(pg_data_t *pgdat, int nid)
5189 enum zone_type zone_type;
5191 if (N_MEMORY == N_NORMAL_MEMORY)
5192 return;
5194 for (zone_type = 0; zone_type <= ZONE_MOVABLE - 1; zone_type++) {
5195 struct zone *zone = &pgdat->node_zones[zone_type];
5196 if (zone->present_pages) {
5197 node_set_state(nid, N_HIGH_MEMORY);
5198 if (N_NORMAL_MEMORY != N_HIGH_MEMORY &&
5199 zone_type <= ZONE_NORMAL)
5200 node_set_state(nid, N_NORMAL_MEMORY);
5201 break;
5207 * free_area_init_nodes - Initialise all pg_data_t and zone data
5208 * @max_zone_pfn: an array of max PFNs for each zone
5210 * This will call free_area_init_node() for each active node in the system.
5211 * Using the page ranges provided by add_active_range(), the size of each
5212 * zone in each node and their holes is calculated. If the maximum PFN
5213 * between two adjacent zones match, it is assumed that the zone is empty.
5214 * For example, if arch_max_dma_pfn == arch_max_dma32_pfn, it is assumed
5215 * that arch_max_dma32_pfn has no pages. It is also assumed that a zone
5216 * starts where the previous one ended. For example, ZONE_DMA32 starts
5217 * at arch_max_dma_pfn.
5219 void __init free_area_init_nodes(unsigned long *max_zone_pfn)
5221 unsigned long start_pfn, end_pfn;
5222 int i, nid;
5224 /* Record where the zone boundaries are */
5225 memset(arch_zone_lowest_possible_pfn, 0,
5226 sizeof(arch_zone_lowest_possible_pfn));
5227 memset(arch_zone_highest_possible_pfn, 0,
5228 sizeof(arch_zone_highest_possible_pfn));
5229 arch_zone_lowest_possible_pfn[0] = find_min_pfn_with_active_regions();
5230 arch_zone_highest_possible_pfn[0] = max_zone_pfn[0];
5231 for (i = 1; i < MAX_NR_ZONES; i++) {
5232 if (i == ZONE_MOVABLE)
5233 continue;
5234 arch_zone_lowest_possible_pfn[i] =
5235 arch_zone_highest_possible_pfn[i-1];
5236 arch_zone_highest_possible_pfn[i] =
5237 max(max_zone_pfn[i], arch_zone_lowest_possible_pfn[i]);
5239 arch_zone_lowest_possible_pfn[ZONE_MOVABLE] = 0;
5240 arch_zone_highest_possible_pfn[ZONE_MOVABLE] = 0;
5242 /* Find the PFNs that ZONE_MOVABLE begins at in each node */
5243 memset(zone_movable_pfn, 0, sizeof(zone_movable_pfn));
5244 find_zone_movable_pfns_for_nodes();
5246 /* Print out the zone ranges */
5247 printk("Zone ranges:\n");
5248 for (i = 0; i < MAX_NR_ZONES; i++) {
5249 if (i == ZONE_MOVABLE)
5250 continue;
5251 printk(KERN_CONT " %-8s ", zone_names[i]);
5252 if (arch_zone_lowest_possible_pfn[i] ==
5253 arch_zone_highest_possible_pfn[i])
5254 printk(KERN_CONT "empty\n");
5255 else
5256 printk(KERN_CONT "[mem %0#10lx-%0#10lx]\n",
5257 arch_zone_lowest_possible_pfn[i] << PAGE_SHIFT,
5258 (arch_zone_highest_possible_pfn[i]
5259 << PAGE_SHIFT) - 1);
5262 /* Print out the PFNs ZONE_MOVABLE begins at in each node */
5263 printk("Movable zone start for each node\n");
5264 for (i = 0; i < MAX_NUMNODES; i++) {
5265 if (zone_movable_pfn[i])
5266 printk(" Node %d: %#010lx\n", i,
5267 zone_movable_pfn[i] << PAGE_SHIFT);
5270 /* Print out the early node map */
5271 printk("Early memory node ranges\n");
5272 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid)
5273 printk(" node %3d: [mem %#010lx-%#010lx]\n", nid,
5274 start_pfn << PAGE_SHIFT, (end_pfn << PAGE_SHIFT) - 1);
5276 /* Initialise every node */
5277 mminit_verify_pageflags_layout();
5278 setup_nr_node_ids();
5279 for_each_online_node(nid) {
5280 pg_data_t *pgdat = NODE_DATA(nid);
5281 free_area_init_node(nid, NULL,
5282 find_min_pfn_for_node(nid), NULL);
5284 /* Any memory on that node */
5285 if (pgdat->node_present_pages)
5286 node_set_state(nid, N_MEMORY);
5287 check_for_memory(pgdat, nid);
5291 static int __init cmdline_parse_core(char *p, unsigned long *core)
5293 unsigned long long coremem;
5294 if (!p)
5295 return -EINVAL;
5297 coremem = memparse(p, &p);
5298 *core = coremem >> PAGE_SHIFT;
5300 /* Paranoid check that UL is enough for the coremem value */
5301 WARN_ON((coremem >> PAGE_SHIFT) > ULONG_MAX);
5303 return 0;
5307 * kernelcore=size sets the amount of memory for use for allocations that
5308 * cannot be reclaimed or migrated.
5310 static int __init cmdline_parse_kernelcore(char *p)
5312 return cmdline_parse_core(p, &required_kernelcore);
5316 * movablecore=size sets the amount of memory for use for allocations that
5317 * can be reclaimed or migrated.
5319 static int __init cmdline_parse_movablecore(char *p)
5321 return cmdline_parse_core(p, &required_movablecore);
5324 early_param("kernelcore", cmdline_parse_kernelcore);
5325 early_param("movablecore", cmdline_parse_movablecore);
5327 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
5329 void adjust_managed_page_count(struct page *page, long count)
5331 spin_lock(&managed_page_count_lock);
5332 page_zone(page)->managed_pages += count;
5333 totalram_pages += count;
5334 #ifdef CONFIG_HIGHMEM
5335 if (PageHighMem(page))
5336 totalhigh_pages += count;
5337 #endif
5338 spin_unlock(&managed_page_count_lock);
5340 EXPORT_SYMBOL(adjust_managed_page_count);
5342 unsigned long free_reserved_area(void *start, void *end, int poison, char *s)
5344 void *pos;
5345 unsigned long pages = 0;
5347 start = (void *)PAGE_ALIGN((unsigned long)start);
5348 end = (void *)((unsigned long)end & PAGE_MASK);
5349 for (pos = start; pos < end; pos += PAGE_SIZE, pages++) {
5350 if ((unsigned int)poison <= 0xFF)
5351 memset(pos, poison, PAGE_SIZE);
5352 free_reserved_page(virt_to_page(pos));
5355 if (pages && s)
5356 pr_info("Freeing %s memory: %ldK (%p - %p)\n",
5357 s, pages << (PAGE_SHIFT - 10), start, end);
5359 return pages;
5361 EXPORT_SYMBOL(free_reserved_area);
5363 #ifdef CONFIG_HIGHMEM
5364 void free_highmem_page(struct page *page)
5366 __free_reserved_page(page);
5367 totalram_pages++;
5368 page_zone(page)->managed_pages++;
5369 totalhigh_pages++;
5371 #endif
5374 void __init mem_init_print_info(const char *str)
5376 unsigned long physpages, codesize, datasize, rosize, bss_size;
5377 unsigned long init_code_size, init_data_size;
5379 physpages = get_num_physpages();
5380 codesize = _etext - _stext;
5381 datasize = _edata - _sdata;
5382 rosize = __end_rodata - __start_rodata;
5383 bss_size = __bss_stop - __bss_start;
5384 init_data_size = __init_end - __init_begin;
5385 init_code_size = _einittext - _sinittext;
5388 * Detect special cases and adjust section sizes accordingly:
5389 * 1) .init.* may be embedded into .data sections
5390 * 2) .init.text.* may be out of [__init_begin, __init_end],
5391 * please refer to arch/tile/kernel/vmlinux.lds.S.
5392 * 3) .rodata.* may be embedded into .text or .data sections.
5394 #define adj_init_size(start, end, size, pos, adj) \
5395 do { \
5396 if (start <= pos && pos < end && size > adj) \
5397 size -= adj; \
5398 } while (0)
5400 adj_init_size(__init_begin, __init_end, init_data_size,
5401 _sinittext, init_code_size);
5402 adj_init_size(_stext, _etext, codesize, _sinittext, init_code_size);
5403 adj_init_size(_sdata, _edata, datasize, __init_begin, init_data_size);
5404 adj_init_size(_stext, _etext, codesize, __start_rodata, rosize);
5405 adj_init_size(_sdata, _edata, datasize, __start_rodata, rosize);
5407 #undef adj_init_size
5409 printk("Memory: %luK/%luK available "
5410 "(%luK kernel code, %luK rwdata, %luK rodata, "
5411 "%luK init, %luK bss, %luK reserved"
5412 #ifdef CONFIG_HIGHMEM
5413 ", %luK highmem"
5414 #endif
5415 "%s%s)\n",
5416 nr_free_pages() << (PAGE_SHIFT-10), physpages << (PAGE_SHIFT-10),
5417 codesize >> 10, datasize >> 10, rosize >> 10,
5418 (init_data_size + init_code_size) >> 10, bss_size >> 10,
5419 (physpages - totalram_pages) << (PAGE_SHIFT-10),
5420 #ifdef CONFIG_HIGHMEM
5421 totalhigh_pages << (PAGE_SHIFT-10),
5422 #endif
5423 str ? ", " : "", str ? str : "");
5427 * set_dma_reserve - set the specified number of pages reserved in the first zone
5428 * @new_dma_reserve: The number of pages to mark reserved
5430 * The per-cpu batchsize and zone watermarks are determined by present_pages.
5431 * In the DMA zone, a significant percentage may be consumed by kernel image
5432 * and other unfreeable allocations which can skew the watermarks badly. This
5433 * function may optionally be used to account for unfreeable pages in the
5434 * first zone (e.g., ZONE_DMA). The effect will be lower watermarks and
5435 * smaller per-cpu batchsize.
5437 void __init set_dma_reserve(unsigned long new_dma_reserve)
5439 dma_reserve = new_dma_reserve;
5442 void __init free_area_init(unsigned long *zones_size)
5444 free_area_init_node(0, zones_size,
5445 __pa(PAGE_OFFSET) >> PAGE_SHIFT, NULL);
5448 static int page_alloc_cpu_notify(struct notifier_block *self,
5449 unsigned long action, void *hcpu)
5451 int cpu = (unsigned long)hcpu;
5453 if (action == CPU_DEAD || action == CPU_DEAD_FROZEN) {
5454 lru_add_drain_cpu(cpu);
5455 drain_pages(cpu);
5458 * Spill the event counters of the dead processor
5459 * into the current processors event counters.
5460 * This artificially elevates the count of the current
5461 * processor.
5463 vm_events_fold_cpu(cpu);
5466 * Zero the differential counters of the dead processor
5467 * so that the vm statistics are consistent.
5469 * This is only okay since the processor is dead and cannot
5470 * race with what we are doing.
5472 cpu_vm_stats_fold(cpu);
5474 return NOTIFY_OK;
5477 void __init page_alloc_init(void)
5479 hotcpu_notifier(page_alloc_cpu_notify, 0);
5483 * calculate_totalreserve_pages - called when sysctl_lower_zone_reserve_ratio
5484 * or min_free_kbytes changes.
5486 static void calculate_totalreserve_pages(void)
5488 struct pglist_data *pgdat;
5489 unsigned long reserve_pages = 0;
5490 enum zone_type i, j;
5492 for_each_online_pgdat(pgdat) {
5493 for (i = 0; i < MAX_NR_ZONES; i++) {
5494 struct zone *zone = pgdat->node_zones + i;
5495 unsigned long max = 0;
5497 /* Find valid and maximum lowmem_reserve in the zone */
5498 for (j = i; j < MAX_NR_ZONES; j++) {
5499 if (zone->lowmem_reserve[j] > max)
5500 max = zone->lowmem_reserve[j];
5503 /* we treat the high watermark as reserved pages. */
5504 max += high_wmark_pages(zone);
5506 if (max > zone->managed_pages)
5507 max = zone->managed_pages;
5508 reserve_pages += max;
5510 * Lowmem reserves are not available to
5511 * GFP_HIGHUSER page cache allocations and
5512 * kswapd tries to balance zones to their high
5513 * watermark. As a result, neither should be
5514 * regarded as dirtyable memory, to prevent a
5515 * situation where reclaim has to clean pages
5516 * in order to balance the zones.
5518 zone->dirty_balance_reserve = max;
5521 dirty_balance_reserve = reserve_pages;
5522 totalreserve_pages = reserve_pages;
5526 * setup_per_zone_lowmem_reserve - called whenever
5527 * sysctl_lower_zone_reserve_ratio changes. Ensures that each zone
5528 * has a correct pages reserved value, so an adequate number of
5529 * pages are left in the zone after a successful __alloc_pages().
5531 static void setup_per_zone_lowmem_reserve(void)
5533 struct pglist_data *pgdat;
5534 enum zone_type j, idx;
5536 for_each_online_pgdat(pgdat) {
5537 for (j = 0; j < MAX_NR_ZONES; j++) {
5538 struct zone *zone = pgdat->node_zones + j;
5539 unsigned long managed_pages = zone->managed_pages;
5541 zone->lowmem_reserve[j] = 0;
5543 idx = j;
5544 while (idx) {
5545 struct zone *lower_zone;
5547 idx--;
5549 if (sysctl_lowmem_reserve_ratio[idx] < 1)
5550 sysctl_lowmem_reserve_ratio[idx] = 1;
5552 lower_zone = pgdat->node_zones + idx;
5553 lower_zone->lowmem_reserve[j] = managed_pages /
5554 sysctl_lowmem_reserve_ratio[idx];
5555 managed_pages += lower_zone->managed_pages;
5560 /* update totalreserve_pages */
5561 calculate_totalreserve_pages();
5564 static void __setup_per_zone_wmarks(void)
5566 unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
5567 unsigned long lowmem_pages = 0;
5568 struct zone *zone;
5569 unsigned long flags;
5571 /* Calculate total number of !ZONE_HIGHMEM pages */
5572 for_each_zone(zone) {
5573 if (!is_highmem(zone))
5574 lowmem_pages += zone->managed_pages;
5577 for_each_zone(zone) {
5578 u64 tmp;
5580 spin_lock_irqsave(&zone->lock, flags);
5581 tmp = (u64)pages_min * zone->managed_pages;
5582 do_div(tmp, lowmem_pages);
5583 if (is_highmem(zone)) {
5585 * __GFP_HIGH and PF_MEMALLOC allocations usually don't
5586 * need highmem pages, so cap pages_min to a small
5587 * value here.
5589 * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN)
5590 * deltas controls asynch page reclaim, and so should
5591 * not be capped for highmem.
5593 unsigned long min_pages;
5595 min_pages = zone->managed_pages / 1024;
5596 min_pages = clamp(min_pages, SWAP_CLUSTER_MAX, 128UL);
5597 zone->watermark[WMARK_MIN] = min_pages;
5598 } else {
5600 * If it's a lowmem zone, reserve a number of pages
5601 * proportionate to the zone's size.
5603 zone->watermark[WMARK_MIN] = tmp;
5606 zone->watermark[WMARK_LOW] = min_wmark_pages(zone) + (tmp >> 2);
5607 zone->watermark[WMARK_HIGH] = min_wmark_pages(zone) + (tmp >> 1);
5609 __mod_zone_page_state(zone, NR_ALLOC_BATCH,
5610 high_wmark_pages(zone) -
5611 low_wmark_pages(zone) -
5612 zone_page_state(zone, NR_ALLOC_BATCH));
5614 setup_zone_migrate_reserve(zone);
5615 spin_unlock_irqrestore(&zone->lock, flags);
5618 /* update totalreserve_pages */
5619 calculate_totalreserve_pages();
5623 * setup_per_zone_wmarks - called when min_free_kbytes changes
5624 * or when memory is hot-{added|removed}
5626 * Ensures that the watermark[min,low,high] values for each zone are set
5627 * correctly with respect to min_free_kbytes.
5629 void setup_per_zone_wmarks(void)
5631 mutex_lock(&zonelists_mutex);
5632 __setup_per_zone_wmarks();
5633 mutex_unlock(&zonelists_mutex);
5637 * The inactive anon list should be small enough that the VM never has to
5638 * do too much work, but large enough that each inactive page has a chance
5639 * to be referenced again before it is swapped out.
5641 * The inactive_anon ratio is the target ratio of ACTIVE_ANON to
5642 * INACTIVE_ANON pages on this zone's LRU, maintained by the
5643 * pageout code. A zone->inactive_ratio of 3 means 3:1 or 25% of
5644 * the anonymous pages are kept on the inactive list.
5646 * total target max
5647 * memory ratio inactive anon
5648 * -------------------------------------
5649 * 10MB 1 5MB
5650 * 100MB 1 50MB
5651 * 1GB 3 250MB
5652 * 10GB 10 0.9GB
5653 * 100GB 31 3GB
5654 * 1TB 101 10GB
5655 * 10TB 320 32GB
5657 static void __meminit calculate_zone_inactive_ratio(struct zone *zone)
5659 unsigned int gb, ratio;
5661 /* Zone size in gigabytes */
5662 gb = zone->managed_pages >> (30 - PAGE_SHIFT);
5663 if (gb)
5664 ratio = int_sqrt(10 * gb);
5665 else
5666 ratio = 1;
5668 zone->inactive_ratio = ratio;
5671 static void __meminit setup_per_zone_inactive_ratio(void)
5673 struct zone *zone;
5675 for_each_zone(zone)
5676 calculate_zone_inactive_ratio(zone);
5680 * Initialise min_free_kbytes.
5682 * For small machines we want it small (128k min). For large machines
5683 * we want it large (64MB max). But it is not linear, because network
5684 * bandwidth does not increase linearly with machine size. We use
5686 * min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
5687 * min_free_kbytes = sqrt(lowmem_kbytes * 16)
5689 * which yields
5691 * 16MB: 512k
5692 * 32MB: 724k
5693 * 64MB: 1024k
5694 * 128MB: 1448k
5695 * 256MB: 2048k
5696 * 512MB: 2896k
5697 * 1024MB: 4096k
5698 * 2048MB: 5792k
5699 * 4096MB: 8192k
5700 * 8192MB: 11584k
5701 * 16384MB: 16384k
5703 int __meminit init_per_zone_wmark_min(void)
5705 unsigned long lowmem_kbytes;
5706 int new_min_free_kbytes;
5708 lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
5709 new_min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
5711 if (new_min_free_kbytes > user_min_free_kbytes) {
5712 min_free_kbytes = new_min_free_kbytes;
5713 if (min_free_kbytes < 128)
5714 min_free_kbytes = 128;
5715 if (min_free_kbytes > 65536)
5716 min_free_kbytes = 65536;
5717 } else {
5718 pr_warn("min_free_kbytes is not updated to %d because user defined value %d is preferred\n",
5719 new_min_free_kbytes, user_min_free_kbytes);
5721 setup_per_zone_wmarks();
5722 refresh_zone_stat_thresholds();
5723 setup_per_zone_lowmem_reserve();
5724 setup_per_zone_inactive_ratio();
5725 return 0;
5727 module_init(init_per_zone_wmark_min)
5730 * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
5731 * that we can call two helper functions whenever min_free_kbytes
5732 * changes.
5734 int min_free_kbytes_sysctl_handler(ctl_table *table, int write,
5735 void __user *buffer, size_t *length, loff_t *ppos)
5737 proc_dointvec(table, write, buffer, length, ppos);
5738 if (write) {
5739 user_min_free_kbytes = min_free_kbytes;
5740 setup_per_zone_wmarks();
5742 return 0;
5745 #ifdef CONFIG_NUMA
5746 int sysctl_min_unmapped_ratio_sysctl_handler(ctl_table *table, int write,
5747 void __user *buffer, size_t *length, loff_t *ppos)
5749 struct zone *zone;
5750 int rc;
5752 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
5753 if (rc)
5754 return rc;
5756 for_each_zone(zone)
5757 zone->min_unmapped_pages = (zone->managed_pages *
5758 sysctl_min_unmapped_ratio) / 100;
5759 return 0;
5762 int sysctl_min_slab_ratio_sysctl_handler(ctl_table *table, int write,
5763 void __user *buffer, size_t *length, loff_t *ppos)
5765 struct zone *zone;
5766 int rc;
5768 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
5769 if (rc)
5770 return rc;
5772 for_each_zone(zone)
5773 zone->min_slab_pages = (zone->managed_pages *
5774 sysctl_min_slab_ratio) / 100;
5775 return 0;
5777 #endif
5780 * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
5781 * proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
5782 * whenever sysctl_lowmem_reserve_ratio changes.
5784 * The reserve ratio obviously has absolutely no relation with the
5785 * minimum watermarks. The lowmem reserve ratio can only make sense
5786 * if in function of the boot time zone sizes.
5788 int lowmem_reserve_ratio_sysctl_handler(ctl_table *table, int write,
5789 void __user *buffer, size_t *length, loff_t *ppos)
5791 proc_dointvec_minmax(table, write, buffer, length, ppos);
5792 setup_per_zone_lowmem_reserve();
5793 return 0;
5797 * percpu_pagelist_fraction - changes the pcp->high for each zone on each
5798 * cpu. It is the fraction of total pages in each zone that a hot per cpu
5799 * pagelist can have before it gets flushed back to buddy allocator.
5801 int percpu_pagelist_fraction_sysctl_handler(ctl_table *table, int write,
5802 void __user *buffer, size_t *length, loff_t *ppos)
5804 struct zone *zone;
5805 int old_percpu_pagelist_fraction;
5806 int ret;
5808 mutex_lock(&pcp_batch_high_lock);
5809 old_percpu_pagelist_fraction = percpu_pagelist_fraction;
5811 ret = proc_dointvec_minmax(table, write, buffer, length, ppos);
5812 if (!write || ret < 0)
5813 goto out;
5815 /* Sanity checking to avoid pcp imbalance */
5816 if (percpu_pagelist_fraction &&
5817 percpu_pagelist_fraction < MIN_PERCPU_PAGELIST_FRACTION) {
5818 percpu_pagelist_fraction = old_percpu_pagelist_fraction;
5819 ret = -EINVAL;
5820 goto out;
5823 /* No change? */
5824 if (percpu_pagelist_fraction == old_percpu_pagelist_fraction)
5825 goto out;
5827 for_each_populated_zone(zone) {
5828 unsigned int cpu;
5830 for_each_possible_cpu(cpu)
5831 pageset_set_high_and_batch(zone,
5832 per_cpu_ptr(zone->pageset, cpu));
5834 out:
5835 mutex_unlock(&pcp_batch_high_lock);
5836 return ret;
5839 int hashdist = HASHDIST_DEFAULT;
5841 #ifdef CONFIG_NUMA
5842 static int __init set_hashdist(char *str)
5844 if (!str)
5845 return 0;
5846 hashdist = simple_strtoul(str, &str, 0);
5847 return 1;
5849 __setup("hashdist=", set_hashdist);
5850 #endif
5853 * allocate a large system hash table from bootmem
5854 * - it is assumed that the hash table must contain an exact power-of-2
5855 * quantity of entries
5856 * - limit is the number of hash buckets, not the total allocation size
5858 void *__init alloc_large_system_hash(const char *tablename,
5859 unsigned long bucketsize,
5860 unsigned long numentries,
5861 int scale,
5862 int flags,
5863 unsigned int *_hash_shift,
5864 unsigned int *_hash_mask,
5865 unsigned long low_limit,
5866 unsigned long high_limit)
5868 unsigned long long max = high_limit;
5869 unsigned long log2qty, size;
5870 void *table = NULL;
5872 /* allow the kernel cmdline to have a say */
5873 if (!numentries) {
5874 /* round applicable memory size up to nearest megabyte */
5875 numentries = nr_kernel_pages;
5877 /* It isn't necessary when PAGE_SIZE >= 1MB */
5878 if (PAGE_SHIFT < 20)
5879 numentries = round_up(numentries, (1<<20)/PAGE_SIZE);
5881 /* limit to 1 bucket per 2^scale bytes of low memory */
5882 if (scale > PAGE_SHIFT)
5883 numentries >>= (scale - PAGE_SHIFT);
5884 else
5885 numentries <<= (PAGE_SHIFT - scale);
5887 /* Make sure we've got at least a 0-order allocation.. */
5888 if (unlikely(flags & HASH_SMALL)) {
5889 /* Makes no sense without HASH_EARLY */
5890 WARN_ON(!(flags & HASH_EARLY));
5891 if (!(numentries >> *_hash_shift)) {
5892 numentries = 1UL << *_hash_shift;
5893 BUG_ON(!numentries);
5895 } else if (unlikely((numentries * bucketsize) < PAGE_SIZE))
5896 numentries = PAGE_SIZE / bucketsize;
5898 numentries = roundup_pow_of_two(numentries);
5900 /* limit allocation size to 1/16 total memory by default */
5901 if (max == 0) {
5902 max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
5903 do_div(max, bucketsize);
5905 max = min(max, 0x80000000ULL);
5907 if (numentries < low_limit)
5908 numentries = low_limit;
5909 if (numentries > max)
5910 numentries = max;
5912 log2qty = ilog2(numentries);
5914 do {
5915 size = bucketsize << log2qty;
5916 if (flags & HASH_EARLY)
5917 table = alloc_bootmem_nopanic(size);
5918 else if (hashdist)
5919 table = __vmalloc(size, GFP_ATOMIC, PAGE_KERNEL);
5920 else {
5922 * If bucketsize is not a power-of-two, we may free
5923 * some pages at the end of hash table which
5924 * alloc_pages_exact() automatically does
5926 if (get_order(size) < MAX_ORDER) {
5927 table = alloc_pages_exact(size, GFP_ATOMIC);
5928 kmemleak_alloc(table, size, 1, GFP_ATOMIC);
5931 } while (!table && size > PAGE_SIZE && --log2qty);
5933 if (!table)
5934 panic("Failed to allocate %s hash table\n", tablename);
5936 printk(KERN_INFO "%s hash table entries: %ld (order: %d, %lu bytes)\n",
5937 tablename,
5938 (1UL << log2qty),
5939 ilog2(size) - PAGE_SHIFT,
5940 size);
5942 if (_hash_shift)
5943 *_hash_shift = log2qty;
5944 if (_hash_mask)
5945 *_hash_mask = (1 << log2qty) - 1;
5947 return table;
5950 /* Return a pointer to the bitmap storing bits affecting a block of pages */
5951 static inline unsigned long *get_pageblock_bitmap(struct zone *zone,
5952 unsigned long pfn)
5954 #ifdef CONFIG_SPARSEMEM
5955 return __pfn_to_section(pfn)->pageblock_flags;
5956 #else
5957 return zone->pageblock_flags;
5958 #endif /* CONFIG_SPARSEMEM */
5961 static inline int pfn_to_bitidx(struct zone *zone, unsigned long pfn)
5963 #ifdef CONFIG_SPARSEMEM
5964 pfn &= (PAGES_PER_SECTION-1);
5965 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
5966 #else
5967 pfn = pfn - round_down(zone->zone_start_pfn, pageblock_nr_pages);
5968 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
5969 #endif /* CONFIG_SPARSEMEM */
5973 * get_pageblock_flags_group - Return the requested group of flags for the pageblock_nr_pages block of pages
5974 * @page: The page within the block of interest
5975 * @start_bitidx: The first bit of interest to retrieve
5976 * @end_bitidx: The last bit of interest
5977 * returns pageblock_bits flags
5979 unsigned long get_pageblock_flags_mask(struct page *page,
5980 unsigned long end_bitidx,
5981 unsigned long mask)
5983 struct zone *zone;
5984 unsigned long *bitmap;
5985 unsigned long pfn, bitidx, word_bitidx;
5986 unsigned long word;
5988 zone = page_zone(page);
5989 pfn = page_to_pfn(page);
5990 bitmap = get_pageblock_bitmap(zone, pfn);
5991 bitidx = pfn_to_bitidx(zone, pfn);
5992 word_bitidx = bitidx / BITS_PER_LONG;
5993 bitidx &= (BITS_PER_LONG-1);
5995 word = bitmap[word_bitidx];
5996 bitidx += end_bitidx;
5997 return (word >> (BITS_PER_LONG - bitidx - 1)) & mask;
6001 * set_pageblock_flags_mask - Set the requested group of flags for a pageblock_nr_pages block of pages
6002 * @page: The page within the block of interest
6003 * @start_bitidx: The first bit of interest
6004 * @end_bitidx: The last bit of interest
6005 * @flags: The flags to set
6007 void set_pageblock_flags_mask(struct page *page, unsigned long flags,
6008 unsigned long end_bitidx,
6009 unsigned long mask)
6011 struct zone *zone;
6012 unsigned long *bitmap;
6013 unsigned long pfn, bitidx, word_bitidx;
6014 unsigned long old_word, word;
6016 BUILD_BUG_ON(NR_PAGEBLOCK_BITS != 4);
6018 zone = page_zone(page);
6019 pfn = page_to_pfn(page);
6020 bitmap = get_pageblock_bitmap(zone, pfn);
6021 bitidx = pfn_to_bitidx(zone, pfn);
6022 word_bitidx = bitidx / BITS_PER_LONG;
6023 bitidx &= (BITS_PER_LONG-1);
6025 VM_BUG_ON(!zone_spans_pfn(zone, pfn));
6027 bitidx += end_bitidx;
6028 mask <<= (BITS_PER_LONG - bitidx - 1);
6029 flags <<= (BITS_PER_LONG - bitidx - 1);
6031 word = ACCESS_ONCE(bitmap[word_bitidx]);
6032 for (;;) {
6033 old_word = cmpxchg(&bitmap[word_bitidx], word, (word & ~mask) | flags);
6034 if (word == old_word)
6035 break;
6036 word = old_word;
6041 * This function checks whether pageblock includes unmovable pages or not.
6042 * If @count is not zero, it is okay to include less @count unmovable pages
6044 * PageLRU check without isolation or lru_lock could race so that
6045 * MIGRATE_MOVABLE block might include unmovable pages. It means you can't
6046 * expect this function should be exact.
6048 bool has_unmovable_pages(struct zone *zone, struct page *page, int count,
6049 bool skip_hwpoisoned_pages)
6051 unsigned long pfn, iter, found;
6052 int mt;
6055 * For avoiding noise data, lru_add_drain_all() should be called
6056 * If ZONE_MOVABLE, the zone never contains unmovable pages
6058 if (zone_idx(zone) == ZONE_MOVABLE)
6059 return false;
6060 mt = get_pageblock_migratetype(page);
6061 if (mt == MIGRATE_MOVABLE || is_migrate_cma(mt))
6062 return false;
6064 pfn = page_to_pfn(page);
6065 for (found = 0, iter = 0; iter < pageblock_nr_pages; iter++) {
6066 unsigned long check = pfn + iter;
6068 if (!pfn_valid_within(check))
6069 continue;
6071 page = pfn_to_page(check);
6074 * Hugepages are not in LRU lists, but they're movable.
6075 * We need not scan over tail pages bacause we don't
6076 * handle each tail page individually in migration.
6078 if (PageHuge(page)) {
6079 iter = round_up(iter + 1, 1<<compound_order(page)) - 1;
6080 continue;
6084 * We can't use page_count without pin a page
6085 * because another CPU can free compound page.
6086 * This check already skips compound tails of THP
6087 * because their page->_count is zero at all time.
6089 if (!atomic_read(&page->_count)) {
6090 if (PageBuddy(page))
6091 iter += (1 << page_order(page)) - 1;
6092 continue;
6096 * The HWPoisoned page may be not in buddy system, and
6097 * page_count() is not 0.
6099 if (skip_hwpoisoned_pages && PageHWPoison(page))
6100 continue;
6102 if (!PageLRU(page))
6103 found++;
6105 * If there are RECLAIMABLE pages, we need to check it.
6106 * But now, memory offline itself doesn't call shrink_slab()
6107 * and it still to be fixed.
6110 * If the page is not RAM, page_count()should be 0.
6111 * we don't need more check. This is an _used_ not-movable page.
6113 * The problematic thing here is PG_reserved pages. PG_reserved
6114 * is set to both of a memory hole page and a _used_ kernel
6115 * page at boot.
6117 if (found > count)
6118 return true;
6120 return false;
6123 bool is_pageblock_removable_nolock(struct page *page)
6125 struct zone *zone;
6126 unsigned long pfn;
6129 * We have to be careful here because we are iterating over memory
6130 * sections which are not zone aware so we might end up outside of
6131 * the zone but still within the section.
6132 * We have to take care about the node as well. If the node is offline
6133 * its NODE_DATA will be NULL - see page_zone.
6135 if (!node_online(page_to_nid(page)))
6136 return false;
6138 zone = page_zone(page);
6139 pfn = page_to_pfn(page);
6140 if (!zone_spans_pfn(zone, pfn))
6141 return false;
6143 return !has_unmovable_pages(zone, page, 0, true);
6146 #ifdef CONFIG_CMA
6148 static unsigned long pfn_max_align_down(unsigned long pfn)
6150 return pfn & ~(max_t(unsigned long, MAX_ORDER_NR_PAGES,
6151 pageblock_nr_pages) - 1);
6154 static unsigned long pfn_max_align_up(unsigned long pfn)
6156 return ALIGN(pfn, max_t(unsigned long, MAX_ORDER_NR_PAGES,
6157 pageblock_nr_pages));
6160 /* [start, end) must belong to a single zone. */
6161 static int __alloc_contig_migrate_range(struct compact_control *cc,
6162 unsigned long start, unsigned long end)
6164 /* This function is based on compact_zone() from compaction.c. */
6165 unsigned long nr_reclaimed;
6166 unsigned long pfn = start;
6167 unsigned int tries = 0;
6168 int ret = 0;
6170 migrate_prep();
6172 while (pfn < end || !list_empty(&cc->migratepages)) {
6173 if (fatal_signal_pending(current)) {
6174 ret = -EINTR;
6175 break;
6178 if (list_empty(&cc->migratepages)) {
6179 cc->nr_migratepages = 0;
6180 pfn = isolate_migratepages_range(cc->zone, cc,
6181 pfn, end, true);
6182 if (!pfn) {
6183 ret = -EINTR;
6184 break;
6186 tries = 0;
6187 } else if (++tries == 5) {
6188 ret = ret < 0 ? ret : -EBUSY;
6189 break;
6192 nr_reclaimed = reclaim_clean_pages_from_list(cc->zone,
6193 &cc->migratepages);
6194 cc->nr_migratepages -= nr_reclaimed;
6196 ret = migrate_pages(&cc->migratepages, alloc_migrate_target,
6197 0, MIGRATE_SYNC, MR_CMA);
6199 if (ret < 0) {
6200 putback_movable_pages(&cc->migratepages);
6201 return ret;
6203 return 0;
6207 * alloc_contig_range() -- tries to allocate given range of pages
6208 * @start: start PFN to allocate
6209 * @end: one-past-the-last PFN to allocate
6210 * @migratetype: migratetype of the underlaying pageblocks (either
6211 * #MIGRATE_MOVABLE or #MIGRATE_CMA). All pageblocks
6212 * in range must have the same migratetype and it must
6213 * be either of the two.
6215 * The PFN range does not have to be pageblock or MAX_ORDER_NR_PAGES
6216 * aligned, however it's the caller's responsibility to guarantee that
6217 * we are the only thread that changes migrate type of pageblocks the
6218 * pages fall in.
6220 * The PFN range must belong to a single zone.
6222 * Returns zero on success or negative error code. On success all
6223 * pages which PFN is in [start, end) are allocated for the caller and
6224 * need to be freed with free_contig_range().
6226 int alloc_contig_range(unsigned long start, unsigned long end,
6227 unsigned migratetype)
6229 unsigned long outer_start, outer_end;
6230 int ret = 0, order;
6232 struct compact_control cc = {
6233 .nr_migratepages = 0,
6234 .order = -1,
6235 .zone = page_zone(pfn_to_page(start)),
6236 .sync = true,
6237 .ignore_skip_hint = true,
6239 INIT_LIST_HEAD(&cc.migratepages);
6242 * What we do here is we mark all pageblocks in range as
6243 * MIGRATE_ISOLATE. Because pageblock and max order pages may
6244 * have different sizes, and due to the way page allocator
6245 * work, we align the range to biggest of the two pages so
6246 * that page allocator won't try to merge buddies from
6247 * different pageblocks and change MIGRATE_ISOLATE to some
6248 * other migration type.
6250 * Once the pageblocks are marked as MIGRATE_ISOLATE, we
6251 * migrate the pages from an unaligned range (ie. pages that
6252 * we are interested in). This will put all the pages in
6253 * range back to page allocator as MIGRATE_ISOLATE.
6255 * When this is done, we take the pages in range from page
6256 * allocator removing them from the buddy system. This way
6257 * page allocator will never consider using them.
6259 * This lets us mark the pageblocks back as
6260 * MIGRATE_CMA/MIGRATE_MOVABLE so that free pages in the
6261 * aligned range but not in the unaligned, original range are
6262 * put back to page allocator so that buddy can use them.
6265 ret = start_isolate_page_range(pfn_max_align_down(start),
6266 pfn_max_align_up(end), migratetype,
6267 false);
6268 if (ret)
6269 return ret;
6271 ret = __alloc_contig_migrate_range(&cc, start, end);
6272 if (ret)
6273 goto done;
6276 * Pages from [start, end) are within a MAX_ORDER_NR_PAGES
6277 * aligned blocks that are marked as MIGRATE_ISOLATE. What's
6278 * more, all pages in [start, end) are free in page allocator.
6279 * What we are going to do is to allocate all pages from
6280 * [start, end) (that is remove them from page allocator).
6282 * The only problem is that pages at the beginning and at the
6283 * end of interesting range may be not aligned with pages that
6284 * page allocator holds, ie. they can be part of higher order
6285 * pages. Because of this, we reserve the bigger range and
6286 * once this is done free the pages we are not interested in.
6288 * We don't have to hold zone->lock here because the pages are
6289 * isolated thus they won't get removed from buddy.
6292 lru_add_drain_all();
6293 drain_all_pages();
6295 order = 0;
6296 outer_start = start;
6297 while (!PageBuddy(pfn_to_page(outer_start))) {
6298 if (++order >= MAX_ORDER) {
6299 ret = -EBUSY;
6300 goto done;
6302 outer_start &= ~0UL << order;
6305 /* Make sure the range is really isolated. */
6306 if (test_pages_isolated(outer_start, end, false)) {
6307 pr_warn("alloc_contig_range test_pages_isolated(%lx, %lx) failed\n",
6308 outer_start, end);
6309 ret = -EBUSY;
6310 goto done;
6314 /* Grab isolated pages from freelists. */
6315 outer_end = isolate_freepages_range(&cc, outer_start, end);
6316 if (!outer_end) {
6317 ret = -EBUSY;
6318 goto done;
6321 /* Free head and tail (if any) */
6322 if (start != outer_start)
6323 free_contig_range(outer_start, start - outer_start);
6324 if (end != outer_end)
6325 free_contig_range(end, outer_end - end);
6327 done:
6328 undo_isolate_page_range(pfn_max_align_down(start),
6329 pfn_max_align_up(end), migratetype);
6330 return ret;
6333 void free_contig_range(unsigned long pfn, unsigned nr_pages)
6335 unsigned int count = 0;
6337 for (; nr_pages--; pfn++) {
6338 struct page *page = pfn_to_page(pfn);
6340 count += page_count(page) != 1;
6341 __free_page(page);
6343 WARN(count != 0, "%d pages are still in use!\n", count);
6345 #endif
6347 #ifdef CONFIG_MEMORY_HOTPLUG
6349 * The zone indicated has a new number of managed_pages; batch sizes and percpu
6350 * page high values need to be recalulated.
6352 void __meminit zone_pcp_update(struct zone *zone)
6354 unsigned cpu;
6355 mutex_lock(&pcp_batch_high_lock);
6356 for_each_possible_cpu(cpu)
6357 pageset_set_high_and_batch(zone,
6358 per_cpu_ptr(zone->pageset, cpu));
6359 mutex_unlock(&pcp_batch_high_lock);
6361 #endif
6363 void zone_pcp_reset(struct zone *zone)
6365 unsigned long flags;
6366 int cpu;
6367 struct per_cpu_pageset *pset;
6369 /* avoid races with drain_pages() */
6370 local_irq_save(flags);
6371 if (zone->pageset != &boot_pageset) {
6372 for_each_online_cpu(cpu) {
6373 pset = per_cpu_ptr(zone->pageset, cpu);
6374 drain_zonestat(zone, pset);
6376 free_percpu(zone->pageset);
6377 zone->pageset = &boot_pageset;
6379 local_irq_restore(flags);
6382 #ifdef CONFIG_MEMORY_HOTREMOVE
6384 * All pages in the range must be isolated before calling this.
6386 void
6387 __offline_isolated_pages(unsigned long start_pfn, unsigned long end_pfn)
6389 struct page *page;
6390 struct zone *zone;
6391 int order, i;
6392 unsigned long pfn;
6393 unsigned long flags;
6394 /* find the first valid pfn */
6395 for (pfn = start_pfn; pfn < end_pfn; pfn++)
6396 if (pfn_valid(pfn))
6397 break;
6398 if (pfn == end_pfn)
6399 return;
6400 zone = page_zone(pfn_to_page(pfn));
6401 spin_lock_irqsave(&zone->lock, flags);
6402 pfn = start_pfn;
6403 while (pfn < end_pfn) {
6404 if (!pfn_valid(pfn)) {
6405 pfn++;
6406 continue;
6408 page = pfn_to_page(pfn);
6410 * The HWPoisoned page may be not in buddy system, and
6411 * page_count() is not 0.
6413 if (unlikely(!PageBuddy(page) && PageHWPoison(page))) {
6414 pfn++;
6415 SetPageReserved(page);
6416 continue;
6419 BUG_ON(page_count(page));
6420 BUG_ON(!PageBuddy(page));
6421 order = page_order(page);
6422 #ifdef CONFIG_DEBUG_VM
6423 printk(KERN_INFO "remove from free list %lx %d %lx\n",
6424 pfn, 1 << order, end_pfn);
6425 #endif
6426 list_del(&page->lru);
6427 rmv_page_order(page);
6428 zone->free_area[order].nr_free--;
6429 for (i = 0; i < (1 << order); i++)
6430 SetPageReserved((page+i));
6431 pfn += (1 << order);
6433 spin_unlock_irqrestore(&zone->lock, flags);
6435 #endif
6437 #ifdef CONFIG_MEMORY_FAILURE
6438 bool is_free_buddy_page(struct page *page)
6440 struct zone *zone = page_zone(page);
6441 unsigned long pfn = page_to_pfn(page);
6442 unsigned long flags;
6443 int order;
6445 spin_lock_irqsave(&zone->lock, flags);
6446 for (order = 0; order < MAX_ORDER; order++) {
6447 struct page *page_head = page - (pfn & ((1 << order) - 1));
6449 if (PageBuddy(page_head) && page_order(page_head) >= order)
6450 break;
6452 spin_unlock_irqrestore(&zone->lock, flags);
6454 return order < MAX_ORDER;
6456 #endif
6458 static const struct trace_print_flags pageflag_names[] = {
6459 {1UL << PG_locked, "locked" },
6460 {1UL << PG_error, "error" },
6461 {1UL << PG_referenced, "referenced" },
6462 {1UL << PG_uptodate, "uptodate" },
6463 {1UL << PG_dirty, "dirty" },
6464 {1UL << PG_lru, "lru" },
6465 {1UL << PG_active, "active" },
6466 {1UL << PG_slab, "slab" },
6467 {1UL << PG_owner_priv_1, "owner_priv_1" },
6468 {1UL << PG_arch_1, "arch_1" },
6469 {1UL << PG_reserved, "reserved" },
6470 {1UL << PG_private, "private" },
6471 {1UL << PG_private_2, "private_2" },
6472 {1UL << PG_writeback, "writeback" },
6473 #ifdef CONFIG_PAGEFLAGS_EXTENDED
6474 {1UL << PG_head, "head" },
6475 {1UL << PG_tail, "tail" },
6476 #else
6477 {1UL << PG_compound, "compound" },
6478 #endif
6479 {1UL << PG_swapcache, "swapcache" },
6480 {1UL << PG_mappedtodisk, "mappedtodisk" },
6481 {1UL << PG_reclaim, "reclaim" },
6482 {1UL << PG_swapbacked, "swapbacked" },
6483 {1UL << PG_unevictable, "unevictable" },
6484 #ifdef CONFIG_MMU
6485 {1UL << PG_mlocked, "mlocked" },
6486 #endif
6487 #ifdef CONFIG_ARCH_USES_PG_UNCACHED
6488 {1UL << PG_uncached, "uncached" },
6489 #endif
6490 #ifdef CONFIG_MEMORY_FAILURE
6491 {1UL << PG_hwpoison, "hwpoison" },
6492 #endif
6493 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
6494 {1UL << PG_compound_lock, "compound_lock" },
6495 #endif
6498 static void dump_page_flags(unsigned long flags)
6500 const char *delim = "";
6501 unsigned long mask;
6502 int i;
6504 BUILD_BUG_ON(ARRAY_SIZE(pageflag_names) != __NR_PAGEFLAGS);
6506 printk(KERN_ALERT "page flags: %#lx(", flags);
6508 /* remove zone id */
6509 flags &= (1UL << NR_PAGEFLAGS) - 1;
6511 for (i = 0; i < ARRAY_SIZE(pageflag_names) && flags; i++) {
6513 mask = pageflag_names[i].mask;
6514 if ((flags & mask) != mask)
6515 continue;
6517 flags &= ~mask;
6518 printk("%s%s", delim, pageflag_names[i].name);
6519 delim = "|";
6522 /* check for left over flags */
6523 if (flags)
6524 printk("%s%#lx", delim, flags);
6526 printk(")\n");
6529 void dump_page(struct page *page)
6531 printk(KERN_ALERT
6532 "page:%p count:%d mapcount:%d mapping:%p index:%#lx\n",
6533 page, atomic_read(&page->_count), page_mapcount(page),
6534 page->mapping, page->index);
6535 dump_page_flags(page->flags);
6536 mem_cgroup_print_bad_page(page);