• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  linux/mm/page_alloc.c
3  *
4  *  Manages the free list, the system allocates free pages here.
5  *  Note that kmalloc() lives in slab.c
6  *
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)
15  */
16 
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/kasan.h>
29 #include <linux/module.h>
30 #include <linux/suspend.h>
31 #include <linux/pagevec.h>
32 #include <linux/blkdev.h>
33 #include <linux/slab.h>
34 #include <linux/ratelimit.h>
35 #include <linux/oom.h>
36 #include <linux/notifier.h>
37 #include <linux/topology.h>
38 #include <linux/sysctl.h>
39 #include <linux/cpu.h>
40 #include <linux/cpuset.h>
41 #include <linux/memory_hotplug.h>
42 #include <linux/nodemask.h>
43 #include <linux/vmalloc.h>
44 #include <linux/vmstat.h>
45 #include <linux/mempolicy.h>
46 #include <linux/stop_machine.h>
47 #include <linux/sort.h>
48 #include <linux/pfn.h>
49 #include <linux/backing-dev.h>
50 #include <linux/fault-inject.h>
51 #include <linux/page-isolation.h>
52 #include <linux/page_ext.h>
53 #include <linux/debugobjects.h>
54 #include <linux/kmemleak.h>
55 #include <linux/compaction.h>
56 #include <trace/events/kmem.h>
57 #include <linux/prefetch.h>
58 #include <linux/mm_inline.h>
59 #include <linux/migrate.h>
60 #include <linux/page_ext.h>
61 #include <linux/hugetlb.h>
62 #include <linux/sched/rt.h>
63 #include <linux/page_owner.h>
64 #include <linux/kthread.h>
65 
66 #include <asm/sections.h>
67 #include <asm/tlbflush.h>
68 #include <asm/div64.h>
69 #include "internal.h"
70 
71 /* prevent >1 _updater_ of zone percpu pageset ->high and ->batch fields */
72 static DEFINE_MUTEX(pcp_batch_high_lock);
73 #define MIN_PERCPU_PAGELIST_FRACTION	(8)
74 
75 #ifdef CONFIG_USE_PERCPU_NUMA_NODE_ID
76 DEFINE_PER_CPU(int, numa_node);
77 EXPORT_PER_CPU_SYMBOL(numa_node);
78 #endif
79 
80 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
81 /*
82  * N.B., Do NOT reference the '_numa_mem_' per cpu variable directly.
83  * It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined.
84  * Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem()
85  * defined in <linux/topology.h>.
86  */
87 DEFINE_PER_CPU(int, _numa_mem_);		/* Kernel "local memory" node */
88 EXPORT_PER_CPU_SYMBOL(_numa_mem_);
89 int _node_numa_mem_[MAX_NUMNODES];
90 #endif
91 
92 /*
93  * Array of node states.
94  */
95 nodemask_t node_states[NR_NODE_STATES] __read_mostly = {
96 	[N_POSSIBLE] = NODE_MASK_ALL,
97 	[N_ONLINE] = { { [0] = 1UL } },
98 #ifndef CONFIG_NUMA
99 	[N_NORMAL_MEMORY] = { { [0] = 1UL } },
100 #ifdef CONFIG_HIGHMEM
101 	[N_HIGH_MEMORY] = { { [0] = 1UL } },
102 #endif
103 #ifdef CONFIG_MOVABLE_NODE
104 	[N_MEMORY] = { { [0] = 1UL } },
105 #endif
106 	[N_CPU] = { { [0] = 1UL } },
107 #endif	/* NUMA */
108 };
109 EXPORT_SYMBOL(node_states);
110 
111 /* Protect totalram_pages and zone->managed_pages */
112 static DEFINE_SPINLOCK(managed_page_count_lock);
113 
114 unsigned long totalram_pages __read_mostly;
115 unsigned long totalreserve_pages __read_mostly;
116 unsigned long totalcma_pages __read_mostly;
117 /*
118  * When calculating the number of globally allowed dirty pages, there
119  * is a certain number of per-zone reserves that should not be
120  * considered dirtyable memory.  This is the sum of those reserves
121  * over all existing zones that contribute dirtyable memory.
122  */
123 unsigned long dirty_balance_reserve __read_mostly;
124 
125 int percpu_pagelist_fraction;
126 gfp_t gfp_allowed_mask __read_mostly = GFP_BOOT_MASK;
127 
128 /*
129  * A cached value of the page's pageblock's migratetype, used when the page is
130  * put on a pcplist. Used to avoid the pageblock migratetype lookup when
131  * freeing from pcplists in most cases, at the cost of possibly becoming stale.
132  * Also the migratetype set in the page does not necessarily match the pcplist
133  * index, e.g. page might have MIGRATE_CMA set but be on a pcplist with any
134  * other index - this ensures that it will be put on the correct CMA freelist.
135  */
get_pcppage_migratetype(struct page * page)136 static inline int get_pcppage_migratetype(struct page *page)
137 {
138 	return page->index;
139 }
140 
set_pcppage_migratetype(struct page * page,int migratetype)141 static inline void set_pcppage_migratetype(struct page *page, int migratetype)
142 {
143 	page->index = migratetype;
144 }
145 
146 #ifdef CONFIG_PM_SLEEP
147 /*
148  * The following functions are used by the suspend/hibernate code to temporarily
149  * change gfp_allowed_mask in order to avoid using I/O during memory allocations
150  * while devices are suspended.  To avoid races with the suspend/hibernate code,
151  * they should always be called with pm_mutex held (gfp_allowed_mask also should
152  * only be modified with pm_mutex held, unless the suspend/hibernate code is
153  * guaranteed not to run in parallel with that modification).
154  */
155 
156 static gfp_t saved_gfp_mask;
157 
pm_restore_gfp_mask(void)158 void pm_restore_gfp_mask(void)
159 {
160 	WARN_ON(!mutex_is_locked(&pm_mutex));
161 	if (saved_gfp_mask) {
162 		gfp_allowed_mask = saved_gfp_mask;
163 		saved_gfp_mask = 0;
164 	}
165 }
166 
pm_restrict_gfp_mask(void)167 void pm_restrict_gfp_mask(void)
168 {
169 	WARN_ON(!mutex_is_locked(&pm_mutex));
170 	WARN_ON(saved_gfp_mask);
171 	saved_gfp_mask = gfp_allowed_mask;
172 	gfp_allowed_mask &= ~(__GFP_IO | __GFP_FS);
173 }
174 
pm_suspended_storage(void)175 bool pm_suspended_storage(void)
176 {
177 	if ((gfp_allowed_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
178 		return false;
179 	return true;
180 }
181 #endif /* CONFIG_PM_SLEEP */
182 
183 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
184 unsigned int pageblock_order __read_mostly;
185 #endif
186 
187 static void __free_pages_ok(struct page *page, unsigned int order);
188 
189 /*
190  * results with 256, 32 in the lowmem_reserve sysctl:
191  *	1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
192  *	1G machine -> (16M dma, 784M normal, 224M high)
193  *	NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
194  *	HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
195  *	HIGHMEM allocation will leave (224M+784M)/256 of ram reserved in ZONE_DMA
196  *
197  * TBD: should special case ZONE_DMA32 machines here - in those we normally
198  * don't need any ZONE_NORMAL reservation
199  */
200 int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES-1] = {
201 #ifdef CONFIG_ZONE_DMA
202 	 256,
203 #endif
204 #ifdef CONFIG_ZONE_DMA32
205 	 256,
206 #endif
207 #ifdef CONFIG_HIGHMEM
208 	 32,
209 #endif
210 	 32,
211 };
212 
213 EXPORT_SYMBOL(totalram_pages);
214 
215 static char * const zone_names[MAX_NR_ZONES] = {
216 #ifdef CONFIG_ZONE_DMA
217 	 "DMA",
218 #endif
219 #ifdef CONFIG_ZONE_DMA32
220 	 "DMA32",
221 #endif
222 	 "Normal",
223 #ifdef CONFIG_HIGHMEM
224 	 "HighMem",
225 #endif
226 	 "Movable",
227 #ifdef CONFIG_ZONE_DEVICE
228 	 "Device",
229 #endif
230 };
231 
232 static void free_compound_page(struct page *page);
233 compound_page_dtor * const compound_page_dtors[] = {
234 	NULL,
235 	free_compound_page,
236 #ifdef CONFIG_HUGETLB_PAGE
237 	free_huge_page,
238 #endif
239 };
240 
241 /*
242  * Try to keep at least this much lowmem free.  Do not allow normal
243  * allocations below this point, only high priority ones. Automatically
244  * tuned according to the amount of memory in the system.
245  */
246 int min_free_kbytes = 1024;
247 int user_min_free_kbytes = -1;
248 
249 /*
250  * Extra memory for the system to try freeing. Used to temporarily
251  * free memory, to make space for new workloads. Anyone can allocate
252  * down to the min watermarks controlled by min_free_kbytes above.
253  */
254 int extra_free_kbytes = 0;
255 
256 static unsigned long __meminitdata nr_kernel_pages;
257 static unsigned long __meminitdata nr_all_pages;
258 static unsigned long __meminitdata dma_reserve;
259 
260 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
261 static unsigned long __meminitdata arch_zone_lowest_possible_pfn[MAX_NR_ZONES];
262 static unsigned long __meminitdata arch_zone_highest_possible_pfn[MAX_NR_ZONES];
263 static unsigned long __initdata required_kernelcore;
264 static unsigned long __initdata required_movablecore;
265 static unsigned long __meminitdata zone_movable_pfn[MAX_NUMNODES];
266 
267 /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
268 int movable_zone;
269 EXPORT_SYMBOL(movable_zone);
270 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
271 
272 #if MAX_NUMNODES > 1
273 int nr_node_ids __read_mostly = MAX_NUMNODES;
274 int nr_online_nodes __read_mostly = 1;
275 EXPORT_SYMBOL(nr_node_ids);
276 EXPORT_SYMBOL(nr_online_nodes);
277 #endif
278 
279 int page_group_by_mobility_disabled __read_mostly;
280 
281 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
282 
283 /*
284  * Determine how many pages need to be initialized durig early boot
285  * (non-deferred initialization).
286  * The value of first_deferred_pfn will be set later, once non-deferred pages
287  * are initialized, but for now set it ULONG_MAX.
288  */
reset_deferred_meminit(pg_data_t * pgdat)289 static inline void reset_deferred_meminit(pg_data_t *pgdat)
290 {
291 	phys_addr_t start_addr, end_addr;
292 	unsigned long max_pgcnt;
293 	unsigned long reserved;
294 
295 	/*
296 	 * Initialise at least 2G of a node but also take into account that
297 	 * two large system hashes that can take up 1GB for 0.25TB/node.
298 	 */
299 	max_pgcnt = max(2UL << (30 - PAGE_SHIFT),
300 			(pgdat->node_spanned_pages >> 8));
301 
302 	/*
303 	 * Compensate the all the memblock reservations (e.g. crash kernel)
304 	 * from the initial estimation to make sure we will initialize enough
305 	 * memory to boot.
306 	 */
307 	start_addr = PFN_PHYS(pgdat->node_start_pfn);
308 	end_addr = PFN_PHYS(pgdat->node_start_pfn + max_pgcnt);
309 	reserved = memblock_reserved_memory_within(start_addr, end_addr);
310 	max_pgcnt += PHYS_PFN(reserved);
311 
312 	pgdat->static_init_pgcnt = min(max_pgcnt, pgdat->node_spanned_pages);
313 	pgdat->first_deferred_pfn = ULONG_MAX;
314 }
315 
316 /* Returns true if the struct page for the pfn is uninitialised */
early_page_uninitialised(unsigned long pfn)317 static inline bool __meminit early_page_uninitialised(unsigned long pfn)
318 {
319 	int nid = early_pfn_to_nid(pfn);
320 
321 	if (node_online(nid) && pfn >= NODE_DATA(nid)->first_deferred_pfn)
322 		return true;
323 
324 	return false;
325 }
326 
early_page_nid_uninitialised(unsigned long pfn,int nid)327 static inline bool early_page_nid_uninitialised(unsigned long pfn, int nid)
328 {
329 	if (pfn >= NODE_DATA(nid)->first_deferred_pfn)
330 		return true;
331 
332 	return false;
333 }
334 
335 /*
336  * Returns false when the remaining initialisation should be deferred until
337  * later in the boot cycle when it can be parallelised.
338  */
update_defer_init(pg_data_t * pgdat,unsigned long pfn,unsigned long zone_end,unsigned long * nr_initialised)339 static inline bool update_defer_init(pg_data_t *pgdat,
340 				unsigned long pfn, unsigned long zone_end,
341 				unsigned long *nr_initialised)
342 {
343 	/* Always populate low zones for address-contrained allocations */
344 	if (zone_end < pgdat_end_pfn(pgdat))
345 		return true;
346 	/* Initialise at least 2G of the highest zone */
347 	(*nr_initialised)++;
348 	if ((*nr_initialised > pgdat->static_init_pgcnt) &&
349 	    (pfn & (PAGES_PER_SECTION - 1)) == 0) {
350 		pgdat->first_deferred_pfn = pfn;
351 		return false;
352 	}
353 
354 	return true;
355 }
356 #else
reset_deferred_meminit(pg_data_t * pgdat)357 static inline void reset_deferred_meminit(pg_data_t *pgdat)
358 {
359 }
360 
early_page_uninitialised(unsigned long pfn)361 static inline bool early_page_uninitialised(unsigned long pfn)
362 {
363 	return false;
364 }
365 
early_page_nid_uninitialised(unsigned long pfn,int nid)366 static inline bool early_page_nid_uninitialised(unsigned long pfn, int nid)
367 {
368 	return false;
369 }
370 
update_defer_init(pg_data_t * pgdat,unsigned long pfn,unsigned long zone_end,unsigned long * nr_initialised)371 static inline bool update_defer_init(pg_data_t *pgdat,
372 				unsigned long pfn, unsigned long zone_end,
373 				unsigned long *nr_initialised)
374 {
375 	return true;
376 }
377 #endif
378 
379 
set_pageblock_migratetype(struct page * page,int migratetype)380 void set_pageblock_migratetype(struct page *page, int migratetype)
381 {
382 	if (unlikely(page_group_by_mobility_disabled &&
383 		     migratetype < MIGRATE_PCPTYPES))
384 		migratetype = MIGRATE_UNMOVABLE;
385 
386 	set_pageblock_flags_group(page, (unsigned long)migratetype,
387 					PB_migrate, PB_migrate_end);
388 }
389 
390 #ifdef CONFIG_DEBUG_VM
page_outside_zone_boundaries(struct zone * zone,struct page * page)391 static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
392 {
393 	int ret = 0;
394 	unsigned seq;
395 	unsigned long pfn = page_to_pfn(page);
396 	unsigned long sp, start_pfn;
397 
398 	do {
399 		seq = zone_span_seqbegin(zone);
400 		start_pfn = zone->zone_start_pfn;
401 		sp = zone->spanned_pages;
402 		if (!zone_spans_pfn(zone, pfn))
403 			ret = 1;
404 	} while (zone_span_seqretry(zone, seq));
405 
406 	if (ret)
407 		pr_err("page 0x%lx outside node %d zone %s [ 0x%lx - 0x%lx ]\n",
408 			pfn, zone_to_nid(zone), zone->name,
409 			start_pfn, start_pfn + sp);
410 
411 	return ret;
412 }
413 
page_is_consistent(struct zone * zone,struct page * page)414 static int page_is_consistent(struct zone *zone, struct page *page)
415 {
416 	if (!pfn_valid_within(page_to_pfn(page)))
417 		return 0;
418 	if (zone != page_zone(page))
419 		return 0;
420 
421 	return 1;
422 }
423 /*
424  * Temporary debugging check for pages not lying within a given zone.
425  */
bad_range(struct zone * zone,struct page * page)426 static int bad_range(struct zone *zone, struct page *page)
427 {
428 	if (page_outside_zone_boundaries(zone, page))
429 		return 1;
430 	if (!page_is_consistent(zone, page))
431 		return 1;
432 
433 	return 0;
434 }
435 #else
bad_range(struct zone * zone,struct page * page)436 static inline int bad_range(struct zone *zone, struct page *page)
437 {
438 	return 0;
439 }
440 #endif
441 
bad_page(struct page * page,const char * reason,unsigned long bad_flags)442 static void bad_page(struct page *page, const char *reason,
443 		unsigned long bad_flags)
444 {
445 	static unsigned long resume;
446 	static unsigned long nr_shown;
447 	static unsigned long nr_unshown;
448 
449 	/* Don't complain about poisoned pages */
450 	if (PageHWPoison(page)) {
451 		page_mapcount_reset(page); /* remove PageBuddy */
452 		return;
453 	}
454 
455 	/*
456 	 * Allow a burst of 60 reports, then keep quiet for that minute;
457 	 * or allow a steady drip of one report per second.
458 	 */
459 	if (nr_shown == 60) {
460 		if (time_before(jiffies, resume)) {
461 			nr_unshown++;
462 			goto out;
463 		}
464 		if (nr_unshown) {
465 			printk(KERN_ALERT
466 			      "BUG: Bad page state: %lu messages suppressed\n",
467 				nr_unshown);
468 			nr_unshown = 0;
469 		}
470 		nr_shown = 0;
471 	}
472 	if (nr_shown++ == 0)
473 		resume = jiffies + 60 * HZ;
474 
475 	printk(KERN_ALERT "BUG: Bad page state in process %s  pfn:%05lx\n",
476 		current->comm, page_to_pfn(page));
477 	dump_page_badflags(page, reason, bad_flags);
478 
479 	print_modules();
480 	dump_stack();
481 out:
482 	/* Leave bad fields for debug, except PageBuddy could make trouble */
483 	page_mapcount_reset(page); /* remove PageBuddy */
484 	add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
485 }
486 
487 /*
488  * Higher-order pages are called "compound pages".  They are structured thusly:
489  *
490  * The first PAGE_SIZE page is called the "head page" and have PG_head set.
491  *
492  * The remaining PAGE_SIZE pages are called "tail pages". PageTail() is encoded
493  * in bit 0 of page->compound_head. The rest of bits is pointer to head page.
494  *
495  * The first tail page's ->compound_dtor holds the offset in array of compound
496  * page destructors. See compound_page_dtors.
497  *
498  * The first tail page's ->compound_order holds the order of allocation.
499  * This usage means that zero-order pages may not be compound.
500  */
501 
free_compound_page(struct page * page)502 static void free_compound_page(struct page *page)
503 {
504 	__free_pages_ok(page, compound_order(page));
505 }
506 
prep_compound_page(struct page * page,unsigned int order)507 void prep_compound_page(struct page *page, unsigned int order)
508 {
509 	int i;
510 	int nr_pages = 1 << order;
511 
512 	set_compound_page_dtor(page, COMPOUND_PAGE_DTOR);
513 	set_compound_order(page, order);
514 	__SetPageHead(page);
515 	for (i = 1; i < nr_pages; i++) {
516 		struct page *p = page + i;
517 		set_page_count(p, 0);
518 		set_compound_head(p, page);
519 	}
520 }
521 
522 #ifdef CONFIG_DEBUG_PAGEALLOC
523 unsigned int _debug_guardpage_minorder;
524 bool _debug_pagealloc_enabled __read_mostly;
525 bool _debug_guardpage_enabled __read_mostly;
526 
early_debug_pagealloc(char * buf)527 static int __init early_debug_pagealloc(char *buf)
528 {
529 	if (!buf)
530 		return -EINVAL;
531 
532 	if (strcmp(buf, "on") == 0)
533 		_debug_pagealloc_enabled = true;
534 
535 	return 0;
536 }
537 early_param("debug_pagealloc", early_debug_pagealloc);
538 
need_debug_guardpage(void)539 static bool need_debug_guardpage(void)
540 {
541 	/* If we don't use debug_pagealloc, we don't need guard page */
542 	if (!debug_pagealloc_enabled())
543 		return false;
544 
545 	return true;
546 }
547 
init_debug_guardpage(void)548 static void init_debug_guardpage(void)
549 {
550 	if (!debug_pagealloc_enabled())
551 		return;
552 
553 	_debug_guardpage_enabled = true;
554 }
555 
556 struct page_ext_operations debug_guardpage_ops = {
557 	.need = need_debug_guardpage,
558 	.init = init_debug_guardpage,
559 };
560 
debug_guardpage_minorder_setup(char * buf)561 static int __init debug_guardpage_minorder_setup(char *buf)
562 {
563 	unsigned long res;
564 
565 	if (kstrtoul(buf, 10, &res) < 0 ||  res > MAX_ORDER / 2) {
566 		printk(KERN_ERR "Bad debug_guardpage_minorder value\n");
567 		return 0;
568 	}
569 	_debug_guardpage_minorder = res;
570 	printk(KERN_INFO "Setting debug_guardpage_minorder to %lu\n", res);
571 	return 0;
572 }
573 __setup("debug_guardpage_minorder=", debug_guardpage_minorder_setup);
574 
set_page_guard(struct zone * zone,struct page * page,unsigned int order,int migratetype)575 static inline void set_page_guard(struct zone *zone, struct page *page,
576 				unsigned int order, int migratetype)
577 {
578 	struct page_ext *page_ext;
579 
580 	if (!debug_guardpage_enabled())
581 		return;
582 
583 	page_ext = lookup_page_ext(page);
584 	if (unlikely(!page_ext))
585 		return;
586 
587 	__set_bit(PAGE_EXT_DEBUG_GUARD, &page_ext->flags);
588 
589 	INIT_LIST_HEAD(&page->lru);
590 	set_page_private(page, order);
591 	/* Guard pages are not available for any usage */
592 	__mod_zone_freepage_state(zone, -(1 << order), migratetype);
593 }
594 
clear_page_guard(struct zone * zone,struct page * page,unsigned int order,int migratetype)595 static inline void clear_page_guard(struct zone *zone, struct page *page,
596 				unsigned int order, int migratetype)
597 {
598 	struct page_ext *page_ext;
599 
600 	if (!debug_guardpage_enabled())
601 		return;
602 
603 	page_ext = lookup_page_ext(page);
604 	if (unlikely(!page_ext))
605 		return;
606 
607 	__clear_bit(PAGE_EXT_DEBUG_GUARD, &page_ext->flags);
608 
609 	set_page_private(page, 0);
610 	if (!is_migrate_isolate(migratetype))
611 		__mod_zone_freepage_state(zone, (1 << order), migratetype);
612 }
613 #else
614 struct page_ext_operations debug_guardpage_ops = { NULL, };
set_page_guard(struct zone * zone,struct page * page,unsigned int order,int migratetype)615 static inline void set_page_guard(struct zone *zone, struct page *page,
616 				unsigned int order, int migratetype) {}
clear_page_guard(struct zone * zone,struct page * page,unsigned int order,int migratetype)617 static inline void clear_page_guard(struct zone *zone, struct page *page,
618 				unsigned int order, int migratetype) {}
619 #endif
620 
set_page_order(struct page * page,unsigned int order)621 static inline void set_page_order(struct page *page, unsigned int order)
622 {
623 	set_page_private(page, order);
624 	__SetPageBuddy(page);
625 }
626 
rmv_page_order(struct page * page)627 static inline void rmv_page_order(struct page *page)
628 {
629 	__ClearPageBuddy(page);
630 	set_page_private(page, 0);
631 }
632 
633 /*
634  * This function checks whether a page is free && is the buddy
635  * we can do coalesce a page and its buddy if
636  * (a) the buddy is not in a hole &&
637  * (b) the buddy is in the buddy system &&
638  * (c) a page and its buddy have the same order &&
639  * (d) a page and its buddy are in the same zone.
640  *
641  * For recording whether a page is in the buddy system, we set ->_mapcount
642  * PAGE_BUDDY_MAPCOUNT_VALUE.
643  * Setting, clearing, and testing _mapcount PAGE_BUDDY_MAPCOUNT_VALUE is
644  * serialized by zone->lock.
645  *
646  * For recording page's order, we use page_private(page).
647  */
page_is_buddy(struct page * page,struct page * buddy,unsigned int order)648 static inline int page_is_buddy(struct page *page, struct page *buddy,
649 							unsigned int order)
650 {
651 	if (!pfn_valid_within(page_to_pfn(buddy)))
652 		return 0;
653 
654 	if (page_is_guard(buddy) && page_order(buddy) == order) {
655 		if (page_zone_id(page) != page_zone_id(buddy))
656 			return 0;
657 
658 		VM_BUG_ON_PAGE(page_count(buddy) != 0, buddy);
659 
660 		return 1;
661 	}
662 
663 	if (PageBuddy(buddy) && page_order(buddy) == order) {
664 		/*
665 		 * zone check is done late to avoid uselessly
666 		 * calculating zone/node ids for pages that could
667 		 * never merge.
668 		 */
669 		if (page_zone_id(page) != page_zone_id(buddy))
670 			return 0;
671 
672 		VM_BUG_ON_PAGE(page_count(buddy) != 0, buddy);
673 
674 		return 1;
675 	}
676 	return 0;
677 }
678 
679 /*
680  * Freeing function for a buddy system allocator.
681  *
682  * The concept of a buddy system is to maintain direct-mapped table
683  * (containing bit values) for memory blocks of various "orders".
684  * The bottom level table contains the map for the smallest allocatable
685  * units of memory (here, pages), and each level above it describes
686  * pairs of units from the levels below, hence, "buddies".
687  * At a high level, all that happens here is marking the table entry
688  * at the bottom level available, and propagating the changes upward
689  * as necessary, plus some accounting needed to play nicely with other
690  * parts of the VM system.
691  * At each level, we keep a list of pages, which are heads of continuous
692  * free pages of length of (1 << order) and marked with _mapcount
693  * PAGE_BUDDY_MAPCOUNT_VALUE. Page's order is recorded in page_private(page)
694  * field.
695  * So when we are allocating or freeing one, we can derive the state of the
696  * other.  That is, if we allocate a small block, and both were
697  * free, the remainder of the region must be split into blocks.
698  * If a block is freed, and its buddy is also free, then this
699  * triggers coalescing into a block of larger size.
700  *
701  * -- nyc
702  */
703 
__free_one_page(struct page * page,unsigned long pfn,struct zone * zone,unsigned int order,int migratetype)704 static inline void __free_one_page(struct page *page,
705 		unsigned long pfn,
706 		struct zone *zone, unsigned int order,
707 		int migratetype)
708 {
709 	unsigned long page_idx;
710 	unsigned long combined_idx;
711 	unsigned long uninitialized_var(buddy_idx);
712 	struct page *buddy;
713 	unsigned int max_order;
714 
715 	max_order = min_t(unsigned int, MAX_ORDER - 1, pageblock_order);
716 
717 	VM_BUG_ON(!zone_is_initialized(zone));
718 	VM_BUG_ON_PAGE(page->flags & PAGE_FLAGS_CHECK_AT_PREP, page);
719 
720 	VM_BUG_ON(migratetype == -1);
721 	if (likely(!is_migrate_isolate(migratetype)))
722 		__mod_zone_freepage_state(zone, 1 << order, migratetype);
723 
724 	page_idx = pfn & ((1 << MAX_ORDER) - 1);
725 
726 	VM_BUG_ON_PAGE(page_idx & ((1 << order) - 1), page);
727 	VM_BUG_ON_PAGE(bad_range(zone, page), page);
728 
729 continue_merging:
730 	while (order < max_order) {
731 		buddy_idx = __find_buddy_index(page_idx, order);
732 		buddy = page + (buddy_idx - page_idx);
733 		if (!page_is_buddy(page, buddy, order))
734 			goto done_merging;
735 		/*
736 		 * Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page,
737 		 * merge with it and move up one order.
738 		 */
739 		if (page_is_guard(buddy)) {
740 			clear_page_guard(zone, buddy, order, migratetype);
741 		} else {
742 			list_del(&buddy->lru);
743 			zone->free_area[order].nr_free--;
744 			rmv_page_order(buddy);
745 		}
746 		combined_idx = buddy_idx & page_idx;
747 		page = page + (combined_idx - page_idx);
748 		page_idx = combined_idx;
749 		order++;
750 	}
751 	if (order < MAX_ORDER - 1) {
752 		/* If we are here, it means order is >= pageblock_order.
753 		 * We want to prevent merge between freepages on isolate
754 		 * pageblock and normal pageblock. Without this, pageblock
755 		 * isolation could cause incorrect freepage or CMA accounting.
756 		 *
757 		 * We don't want to hit this code for the more frequent
758 		 * low-order merging.
759 		 */
760 		if (unlikely(has_isolate_pageblock(zone))) {
761 			int buddy_mt;
762 
763 			buddy_idx = __find_buddy_index(page_idx, order);
764 			buddy = page + (buddy_idx - page_idx);
765 			buddy_mt = get_pageblock_migratetype(buddy);
766 
767 			if (migratetype != buddy_mt
768 					&& (is_migrate_isolate(migratetype) ||
769 						is_migrate_isolate(buddy_mt)))
770 				goto done_merging;
771 		}
772 		max_order = order + 1;
773 		goto continue_merging;
774 	}
775 
776 done_merging:
777 	set_page_order(page, order);
778 
779 	/*
780 	 * If this is not the largest possible page, check if the buddy
781 	 * of the next-highest order is free. If it is, it's possible
782 	 * that pages are being freed that will coalesce soon. In case,
783 	 * that is happening, add the free page to the tail of the list
784 	 * so it's less likely to be used soon and more likely to be merged
785 	 * as a higher order page
786 	 */
787 	if ((order < MAX_ORDER-2) && pfn_valid_within(page_to_pfn(buddy))) {
788 		struct page *higher_page, *higher_buddy;
789 		combined_idx = buddy_idx & page_idx;
790 		higher_page = page + (combined_idx - page_idx);
791 		buddy_idx = __find_buddy_index(combined_idx, order + 1);
792 		higher_buddy = higher_page + (buddy_idx - combined_idx);
793 		if (page_is_buddy(higher_page, higher_buddy, order + 1)) {
794 			list_add_tail(&page->lru,
795 				&zone->free_area[order].free_list[migratetype]);
796 			goto out;
797 		}
798 	}
799 
800 	list_add(&page->lru, &zone->free_area[order].free_list[migratetype]);
801 out:
802 	zone->free_area[order].nr_free++;
803 }
804 
free_pages_check(struct page * page)805 static inline int free_pages_check(struct page *page)
806 {
807 	const char *bad_reason = NULL;
808 	unsigned long bad_flags = 0;
809 
810 	if (unlikely(page_mapcount(page)))
811 		bad_reason = "nonzero mapcount";
812 	if (unlikely(page->mapping != NULL))
813 		bad_reason = "non-NULL mapping";
814 	if (unlikely(atomic_read(&page->_count) != 0))
815 		bad_reason = "nonzero _count";
816 	if (unlikely(page->flags & PAGE_FLAGS_CHECK_AT_FREE)) {
817 		bad_reason = "PAGE_FLAGS_CHECK_AT_FREE flag(s) set";
818 		bad_flags = PAGE_FLAGS_CHECK_AT_FREE;
819 	}
820 #ifdef CONFIG_MEMCG
821 	if (unlikely(page->mem_cgroup))
822 		bad_reason = "page still charged to cgroup";
823 #endif
824 	if (unlikely(bad_reason)) {
825 		bad_page(page, bad_reason, bad_flags);
826 		return 1;
827 	}
828 	page_cpupid_reset_last(page);
829 	if (page->flags & PAGE_FLAGS_CHECK_AT_PREP)
830 		page->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
831 	return 0;
832 }
833 
834 /*
835  * Frees a number of pages from the PCP lists
836  * Assumes all pages on list are in same zone, and of same order.
837  * count is the number of pages to free.
838  *
839  * If the zone was previously in an "all pages pinned" state then look to
840  * see if this freeing clears that state.
841  *
842  * And clear the zone's pages_scanned counter, to hold off the "all pages are
843  * pinned" detection logic.
844  */
free_pcppages_bulk(struct zone * zone,int count,struct per_cpu_pages * pcp)845 static void free_pcppages_bulk(struct zone *zone, int count,
846 					struct per_cpu_pages *pcp)
847 {
848 	int migratetype = 0;
849 	int batch_free = 0;
850 	unsigned long nr_scanned;
851 
852 	spin_lock(&zone->lock);
853 	nr_scanned = zone_page_state(zone, NR_PAGES_SCANNED);
854 	if (nr_scanned)
855 		__mod_zone_page_state(zone, NR_PAGES_SCANNED, -nr_scanned);
856 
857 	/*
858 	 * Ensure proper count is passed which otherwise would stuck in the
859 	 * below while (list_empty(list)) loop.
860 	 */
861 	count = min(pcp->count, count);
862 	while (count) {
863 		struct page *page;
864 		struct list_head *list;
865 
866 		/*
867 		 * Remove pages from lists in a round-robin fashion. A
868 		 * batch_free count is maintained that is incremented when an
869 		 * empty list is encountered.  This is so more pages are freed
870 		 * off fuller lists instead of spinning excessively around empty
871 		 * lists
872 		 */
873 		do {
874 			batch_free++;
875 			if (++migratetype == MIGRATE_PCPTYPES)
876 				migratetype = 0;
877 			list = &pcp->lists[migratetype];
878 		} while (list_empty(list));
879 
880 		/* This is the only non-empty list. Free them all. */
881 		if (batch_free == MIGRATE_PCPTYPES)
882 			batch_free = count;
883 
884 		do {
885 			int mt;	/* migratetype of the to-be-freed page */
886 
887 			page = list_entry(list->prev, struct page, lru);
888 			/* must delete as __free_one_page list manipulates */
889 			list_del(&page->lru);
890 
891 			mt = get_pcppage_migratetype(page);
892 			/* MIGRATE_ISOLATE page should not go to pcplists */
893 			VM_BUG_ON_PAGE(is_migrate_isolate(mt), page);
894 			/* Pageblock could have been isolated meanwhile */
895 			if (unlikely(has_isolate_pageblock(zone)))
896 				mt = get_pageblock_migratetype(page);
897 
898 			__free_one_page(page, page_to_pfn(page), zone, 0, mt);
899 			trace_mm_page_pcpu_drain(page, 0, mt);
900 		} while (--count && --batch_free && !list_empty(list));
901 	}
902 	spin_unlock(&zone->lock);
903 }
904 
free_one_page(struct zone * zone,struct page * page,unsigned long pfn,unsigned int order,int migratetype)905 static void free_one_page(struct zone *zone,
906 				struct page *page, unsigned long pfn,
907 				unsigned int order,
908 				int migratetype)
909 {
910 	unsigned long nr_scanned;
911 	spin_lock(&zone->lock);
912 	nr_scanned = zone_page_state(zone, NR_PAGES_SCANNED);
913 	if (nr_scanned)
914 		__mod_zone_page_state(zone, NR_PAGES_SCANNED, -nr_scanned);
915 
916 	if (unlikely(has_isolate_pageblock(zone) ||
917 		is_migrate_isolate(migratetype))) {
918 		migratetype = get_pfnblock_migratetype(page, pfn);
919 	}
920 	__free_one_page(page, pfn, zone, order, migratetype);
921 	spin_unlock(&zone->lock);
922 }
923 
free_tail_pages_check(struct page * head_page,struct page * page)924 static int free_tail_pages_check(struct page *head_page, struct page *page)
925 {
926 	int ret = 1;
927 
928 	/*
929 	 * We rely page->lru.next never has bit 0 set, unless the page
930 	 * is PageTail(). Let's make sure that's true even for poisoned ->lru.
931 	 */
932 	BUILD_BUG_ON((unsigned long)LIST_POISON1 & 1);
933 
934 	if (!IS_ENABLED(CONFIG_DEBUG_VM)) {
935 		ret = 0;
936 		goto out;
937 	}
938 	if (unlikely(!PageTail(page))) {
939 		bad_page(page, "PageTail not set", 0);
940 		goto out;
941 	}
942 	if (unlikely(compound_head(page) != head_page)) {
943 		bad_page(page, "compound_head not consistent", 0);
944 		goto out;
945 	}
946 	ret = 0;
947 out:
948 	clear_compound_head(page);
949 	return ret;
950 }
951 
__init_single_page(struct page * page,unsigned long pfn,unsigned long zone,int nid)952 static void __meminit __init_single_page(struct page *page, unsigned long pfn,
953 				unsigned long zone, int nid)
954 {
955 	set_page_links(page, zone, nid, pfn);
956 	init_page_count(page);
957 	page_mapcount_reset(page);
958 	page_cpupid_reset_last(page);
959 
960 	INIT_LIST_HEAD(&page->lru);
961 #ifdef WANT_PAGE_VIRTUAL
962 	/* The shift won't overflow because ZONE_NORMAL is below 4G. */
963 	if (!is_highmem_idx(zone))
964 		set_page_address(page, __va(pfn << PAGE_SHIFT));
965 #endif
966 }
967 
__init_single_pfn(unsigned long pfn,unsigned long zone,int nid)968 static void __meminit __init_single_pfn(unsigned long pfn, unsigned long zone,
969 					int nid)
970 {
971 	return __init_single_page(pfn_to_page(pfn), pfn, zone, nid);
972 }
973 
974 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
init_reserved_page(unsigned long pfn)975 static void init_reserved_page(unsigned long pfn)
976 {
977 	pg_data_t *pgdat;
978 	int nid, zid;
979 
980 	if (!early_page_uninitialised(pfn))
981 		return;
982 
983 	nid = early_pfn_to_nid(pfn);
984 	pgdat = NODE_DATA(nid);
985 
986 	for (zid = 0; zid < MAX_NR_ZONES; zid++) {
987 		struct zone *zone = &pgdat->node_zones[zid];
988 
989 		if (pfn >= zone->zone_start_pfn && pfn < zone_end_pfn(zone))
990 			break;
991 	}
992 	__init_single_pfn(pfn, zid, nid);
993 }
994 #else
init_reserved_page(unsigned long pfn)995 static inline void init_reserved_page(unsigned long pfn)
996 {
997 }
998 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
999 
1000 /*
1001  * Initialised pages do not have PageReserved set. This function is
1002  * called for each range allocated by the bootmem allocator and
1003  * marks the pages PageReserved. The remaining valid pages are later
1004  * sent to the buddy page allocator.
1005  */
reserve_bootmem_region(phys_addr_t start,phys_addr_t end)1006 void __meminit reserve_bootmem_region(phys_addr_t start, phys_addr_t end)
1007 {
1008 	unsigned long start_pfn = PFN_DOWN(start);
1009 	unsigned long end_pfn = PFN_UP(end);
1010 
1011 	for (; start_pfn < end_pfn; start_pfn++) {
1012 		if (pfn_valid(start_pfn)) {
1013 			struct page *page = pfn_to_page(start_pfn);
1014 
1015 			init_reserved_page(start_pfn);
1016 
1017 			/* Avoid false-positive PageTail() */
1018 			INIT_LIST_HEAD(&page->lru);
1019 
1020 			SetPageReserved(page);
1021 		}
1022 	}
1023 }
1024 
free_pages_prepare(struct page * page,unsigned int order)1025 static bool free_pages_prepare(struct page *page, unsigned int order)
1026 {
1027 	bool compound = PageCompound(page);
1028 	int i, bad = 0;
1029 
1030 	VM_BUG_ON_PAGE(PageTail(page), page);
1031 	VM_BUG_ON_PAGE(compound && compound_order(page) != order, page);
1032 
1033 	trace_mm_page_free(page, order);
1034 	kmemcheck_free_shadow(page, order);
1035 	kasan_free_pages(page, order);
1036 
1037 	if (PageAnon(page))
1038 		page->mapping = NULL;
1039 	bad += free_pages_check(page);
1040 	for (i = 1; i < (1 << order); i++) {
1041 		if (compound)
1042 			bad += free_tail_pages_check(page, page + i);
1043 		bad += free_pages_check(page + i);
1044 	}
1045 	if (bad)
1046 		return false;
1047 
1048 	reset_page_owner(page, order);
1049 
1050 	if (!PageHighMem(page)) {
1051 		debug_check_no_locks_freed(page_address(page),
1052 					   PAGE_SIZE << order);
1053 		debug_check_no_obj_freed(page_address(page),
1054 					   PAGE_SIZE << order);
1055 	}
1056 	arch_free_page(page, order);
1057 	kernel_map_pages(page, 1 << order, 0);
1058 
1059 	return true;
1060 }
1061 
__free_pages_ok(struct page * page,unsigned int order)1062 static void __free_pages_ok(struct page *page, unsigned int order)
1063 {
1064 	unsigned long flags;
1065 	int migratetype;
1066 	unsigned long pfn = page_to_pfn(page);
1067 
1068 	if (!free_pages_prepare(page, order))
1069 		return;
1070 
1071 	migratetype = get_pfnblock_migratetype(page, pfn);
1072 	local_irq_save(flags);
1073 	__count_vm_events(PGFREE, 1 << order);
1074 	free_one_page(page_zone(page), page, pfn, order, migratetype);
1075 	local_irq_restore(flags);
1076 }
1077 
__free_pages_boot_core(struct page * page,unsigned long pfn,unsigned int order)1078 static void __init __free_pages_boot_core(struct page *page,
1079 					unsigned long pfn, unsigned int order)
1080 {
1081 	unsigned int nr_pages = 1 << order;
1082 	struct page *p = page;
1083 	unsigned int loop;
1084 
1085 	prefetchw(p);
1086 	for (loop = 0; loop < (nr_pages - 1); loop++, p++) {
1087 		prefetchw(p + 1);
1088 		__ClearPageReserved(p);
1089 		set_page_count(p, 0);
1090 	}
1091 	__ClearPageReserved(p);
1092 	set_page_count(p, 0);
1093 
1094 	page_zone(page)->managed_pages += nr_pages;
1095 	set_page_refcounted(page);
1096 	__free_pages(page, order);
1097 }
1098 
1099 #if defined(CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID) || \
1100 	defined(CONFIG_HAVE_MEMBLOCK_NODE_MAP)
1101 
1102 static struct mminit_pfnnid_cache early_pfnnid_cache __meminitdata;
1103 
early_pfn_to_nid(unsigned long pfn)1104 int __meminit early_pfn_to_nid(unsigned long pfn)
1105 {
1106 	static DEFINE_SPINLOCK(early_pfn_lock);
1107 	int nid;
1108 
1109 	spin_lock(&early_pfn_lock);
1110 	nid = __early_pfn_to_nid(pfn, &early_pfnnid_cache);
1111 	if (nid < 0)
1112 		nid = first_online_node;
1113 	spin_unlock(&early_pfn_lock);
1114 
1115 	return nid;
1116 }
1117 #endif
1118 
1119 #ifdef CONFIG_NODES_SPAN_OTHER_NODES
meminit_pfn_in_nid(unsigned long pfn,int node,struct mminit_pfnnid_cache * state)1120 static inline bool __meminit meminit_pfn_in_nid(unsigned long pfn, int node,
1121 					struct mminit_pfnnid_cache *state)
1122 {
1123 	int nid;
1124 
1125 	nid = __early_pfn_to_nid(pfn, state);
1126 	if (nid >= 0 && nid != node)
1127 		return false;
1128 	return true;
1129 }
1130 
1131 /* Only safe to use early in boot when initialisation is single-threaded */
early_pfn_in_nid(unsigned long pfn,int node)1132 static inline bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
1133 {
1134 	return meminit_pfn_in_nid(pfn, node, &early_pfnnid_cache);
1135 }
1136 
1137 #else
1138 
early_pfn_in_nid(unsigned long pfn,int node)1139 static inline bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
1140 {
1141 	return true;
1142 }
meminit_pfn_in_nid(unsigned long pfn,int node,struct mminit_pfnnid_cache * state)1143 static inline bool __meminit meminit_pfn_in_nid(unsigned long pfn, int node,
1144 					struct mminit_pfnnid_cache *state)
1145 {
1146 	return true;
1147 }
1148 #endif
1149 
1150 
__free_pages_bootmem(struct page * page,unsigned long pfn,unsigned int order)1151 void __init __free_pages_bootmem(struct page *page, unsigned long pfn,
1152 							unsigned int order)
1153 {
1154 	if (early_page_uninitialised(pfn))
1155 		return;
1156 	return __free_pages_boot_core(page, pfn, order);
1157 }
1158 
1159 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
deferred_free_range(struct page * page,unsigned long pfn,int nr_pages)1160 static void __init deferred_free_range(struct page *page,
1161 					unsigned long pfn, int nr_pages)
1162 {
1163 	int i;
1164 
1165 	if (!page)
1166 		return;
1167 
1168 	/* Free a large naturally-aligned chunk if possible */
1169 	if (nr_pages == MAX_ORDER_NR_PAGES &&
1170 	    (pfn & (MAX_ORDER_NR_PAGES-1)) == 0) {
1171 		set_pageblock_migratetype(page, MIGRATE_MOVABLE);
1172 		__free_pages_boot_core(page, pfn, MAX_ORDER-1);
1173 		return;
1174 	}
1175 
1176 	for (i = 0; i < nr_pages; i++, page++, pfn++)
1177 		__free_pages_boot_core(page, pfn, 0);
1178 }
1179 
1180 /* Completion tracking for deferred_init_memmap() threads */
1181 static atomic_t pgdat_init_n_undone __initdata;
1182 static __initdata DECLARE_COMPLETION(pgdat_init_all_done_comp);
1183 
pgdat_init_report_one_done(void)1184 static inline void __init pgdat_init_report_one_done(void)
1185 {
1186 	if (atomic_dec_and_test(&pgdat_init_n_undone))
1187 		complete(&pgdat_init_all_done_comp);
1188 }
1189 
1190 /* Initialise remaining memory on a node */
deferred_init_memmap(void * data)1191 static int __init deferred_init_memmap(void *data)
1192 {
1193 	pg_data_t *pgdat = data;
1194 	int nid = pgdat->node_id;
1195 	struct mminit_pfnnid_cache nid_init_state = { };
1196 	unsigned long start = jiffies;
1197 	unsigned long nr_pages = 0;
1198 	unsigned long walk_start, walk_end;
1199 	int i, zid;
1200 	struct zone *zone;
1201 	unsigned long first_init_pfn = pgdat->first_deferred_pfn;
1202 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
1203 
1204 	if (first_init_pfn == ULONG_MAX) {
1205 		pgdat_init_report_one_done();
1206 		return 0;
1207 	}
1208 
1209 	/* Bind memory initialisation thread to a local node if possible */
1210 	if (!cpumask_empty(cpumask))
1211 		set_cpus_allowed_ptr(current, cpumask);
1212 
1213 	/* Sanity check boundaries */
1214 	BUG_ON(pgdat->first_deferred_pfn < pgdat->node_start_pfn);
1215 	BUG_ON(pgdat->first_deferred_pfn > pgdat_end_pfn(pgdat));
1216 	pgdat->first_deferred_pfn = ULONG_MAX;
1217 
1218 	/* Only the highest zone is deferred so find it */
1219 	for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1220 		zone = pgdat->node_zones + zid;
1221 		if (first_init_pfn < zone_end_pfn(zone))
1222 			break;
1223 	}
1224 
1225 	for_each_mem_pfn_range(i, nid, &walk_start, &walk_end, NULL) {
1226 		unsigned long pfn, end_pfn;
1227 		struct page *page = NULL;
1228 		struct page *free_base_page = NULL;
1229 		unsigned long free_base_pfn = 0;
1230 		int nr_to_free = 0;
1231 
1232 		end_pfn = min(walk_end, zone_end_pfn(zone));
1233 		pfn = first_init_pfn;
1234 		if (pfn < walk_start)
1235 			pfn = walk_start;
1236 		if (pfn < zone->zone_start_pfn)
1237 			pfn = zone->zone_start_pfn;
1238 
1239 		for (; pfn < end_pfn; pfn++) {
1240 			if (!pfn_valid_within(pfn))
1241 				goto free_range;
1242 
1243 			/*
1244 			 * Ensure pfn_valid is checked every
1245 			 * MAX_ORDER_NR_PAGES for memory holes
1246 			 */
1247 			if ((pfn & (MAX_ORDER_NR_PAGES - 1)) == 0) {
1248 				if (!pfn_valid(pfn)) {
1249 					page = NULL;
1250 					goto free_range;
1251 				}
1252 			}
1253 
1254 			if (!meminit_pfn_in_nid(pfn, nid, &nid_init_state)) {
1255 				page = NULL;
1256 				goto free_range;
1257 			}
1258 
1259 			/* Minimise pfn page lookups and scheduler checks */
1260 			if (page && (pfn & (MAX_ORDER_NR_PAGES - 1)) != 0) {
1261 				page++;
1262 			} else {
1263 				nr_pages += nr_to_free;
1264 				deferred_free_range(free_base_page,
1265 						free_base_pfn, nr_to_free);
1266 				free_base_page = NULL;
1267 				free_base_pfn = nr_to_free = 0;
1268 
1269 				page = pfn_to_page(pfn);
1270 				cond_resched();
1271 			}
1272 
1273 			if (page->flags) {
1274 				VM_BUG_ON(page_zone(page) != zone);
1275 				goto free_range;
1276 			}
1277 
1278 			__init_single_page(page, pfn, zid, nid);
1279 			if (!free_base_page) {
1280 				free_base_page = page;
1281 				free_base_pfn = pfn;
1282 				nr_to_free = 0;
1283 			}
1284 			nr_to_free++;
1285 
1286 			/* Where possible, batch up pages for a single free */
1287 			continue;
1288 free_range:
1289 			/* Free the current block of pages to allocator */
1290 			nr_pages += nr_to_free;
1291 			deferred_free_range(free_base_page, free_base_pfn,
1292 								nr_to_free);
1293 			free_base_page = NULL;
1294 			free_base_pfn = nr_to_free = 0;
1295 		}
1296 
1297 		first_init_pfn = max(end_pfn, first_init_pfn);
1298 	}
1299 
1300 	/* Sanity check that the next zone really is unpopulated */
1301 	WARN_ON(++zid < MAX_NR_ZONES && populated_zone(++zone));
1302 
1303 	pr_info("node %d initialised, %lu pages in %ums\n", nid, nr_pages,
1304 					jiffies_to_msecs(jiffies - start));
1305 
1306 	pgdat_init_report_one_done();
1307 	return 0;
1308 }
1309 
page_alloc_init_late(void)1310 void __init page_alloc_init_late(void)
1311 {
1312 	int nid;
1313 
1314 	/* There will be num_node_state(N_MEMORY) threads */
1315 	atomic_set(&pgdat_init_n_undone, num_node_state(N_MEMORY));
1316 	for_each_node_state(nid, N_MEMORY) {
1317 		kthread_run(deferred_init_memmap, NODE_DATA(nid), "pgdatinit%d", nid);
1318 	}
1319 
1320 	/* Block until all are initialised */
1321 	wait_for_completion(&pgdat_init_all_done_comp);
1322 
1323 	/* Reinit limits that are based on free pages after the kernel is up */
1324 	files_maxfiles_init();
1325 }
1326 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
1327 
1328 #ifdef CONFIG_CMA
1329 /* Free whole pageblock and set its migration type to MIGRATE_CMA. */
init_cma_reserved_pageblock(struct page * page)1330 void __init init_cma_reserved_pageblock(struct page *page)
1331 {
1332 	unsigned i = pageblock_nr_pages;
1333 	struct page *p = page;
1334 
1335 	do {
1336 		__ClearPageReserved(p);
1337 		set_page_count(p, 0);
1338 	} while (++p, --i);
1339 
1340 	set_pageblock_migratetype(page, MIGRATE_CMA);
1341 
1342 	if (pageblock_order >= MAX_ORDER) {
1343 		i = pageblock_nr_pages;
1344 		p = page;
1345 		do {
1346 			set_page_refcounted(p);
1347 			__free_pages(p, MAX_ORDER - 1);
1348 			p += MAX_ORDER_NR_PAGES;
1349 		} while (i -= MAX_ORDER_NR_PAGES);
1350 	} else {
1351 		set_page_refcounted(page);
1352 		__free_pages(page, pageblock_order);
1353 	}
1354 
1355 	adjust_managed_page_count(page, pageblock_nr_pages);
1356 }
1357 #endif
1358 
1359 /*
1360  * The order of subdivision here is critical for the IO subsystem.
1361  * Please do not alter this order without good reasons and regression
1362  * testing. Specifically, as large blocks of memory are subdivided,
1363  * the order in which smaller blocks are delivered depends on the order
1364  * they're subdivided in this function. This is the primary factor
1365  * influencing the order in which pages are delivered to the IO
1366  * subsystem according to empirical testing, and this is also justified
1367  * by considering the behavior of a buddy system containing a single
1368  * large block of memory acted on by a series of small allocations.
1369  * This behavior is a critical factor in sglist merging's success.
1370  *
1371  * -- nyc
1372  */
expand(struct zone * zone,struct page * page,int low,int high,struct free_area * area,int migratetype)1373 static inline void expand(struct zone *zone, struct page *page,
1374 	int low, int high, struct free_area *area,
1375 	int migratetype)
1376 {
1377 	unsigned long size = 1 << high;
1378 
1379 	while (high > low) {
1380 		area--;
1381 		high--;
1382 		size >>= 1;
1383 		VM_BUG_ON_PAGE(bad_range(zone, &page[size]), &page[size]);
1384 
1385 		if (IS_ENABLED(CONFIG_DEBUG_PAGEALLOC) &&
1386 			debug_guardpage_enabled() &&
1387 			high < debug_guardpage_minorder()) {
1388 			/*
1389 			 * Mark as guard pages (or page), that will allow to
1390 			 * merge back to allocator when buddy will be freed.
1391 			 * Corresponding page table entries will not be touched,
1392 			 * pages will stay not present in virtual address space
1393 			 */
1394 			set_page_guard(zone, &page[size], high, migratetype);
1395 			continue;
1396 		}
1397 		list_add(&page[size].lru, &area->free_list[migratetype]);
1398 		area->nr_free++;
1399 		set_page_order(&page[size], high);
1400 	}
1401 }
1402 
1403 /*
1404  * This page is about to be returned from the page allocator
1405  */
check_new_page(struct page * page)1406 static inline int check_new_page(struct page *page)
1407 {
1408 	const char *bad_reason = NULL;
1409 	unsigned long bad_flags = 0;
1410 
1411 	if (unlikely(page_mapcount(page)))
1412 		bad_reason = "nonzero mapcount";
1413 	if (unlikely(page->mapping != NULL))
1414 		bad_reason = "non-NULL mapping";
1415 	if (unlikely(atomic_read(&page->_count) != 0))
1416 		bad_reason = "nonzero _count";
1417 	if (unlikely(page->flags & __PG_HWPOISON)) {
1418 		bad_reason = "HWPoisoned (hardware-corrupted)";
1419 		bad_flags = __PG_HWPOISON;
1420 	}
1421 	if (unlikely(page->flags & PAGE_FLAGS_CHECK_AT_PREP)) {
1422 		bad_reason = "PAGE_FLAGS_CHECK_AT_PREP flag set";
1423 		bad_flags = PAGE_FLAGS_CHECK_AT_PREP;
1424 	}
1425 #ifdef CONFIG_MEMCG
1426 	if (unlikely(page->mem_cgroup))
1427 		bad_reason = "page still charged to cgroup";
1428 #endif
1429 	if (unlikely(bad_reason)) {
1430 		bad_page(page, bad_reason, bad_flags);
1431 		return 1;
1432 	}
1433 	return 0;
1434 }
1435 
prep_new_page(struct page * page,unsigned int order,gfp_t gfp_flags,int alloc_flags)1436 static int prep_new_page(struct page *page, unsigned int order, gfp_t gfp_flags,
1437 								int alloc_flags)
1438 {
1439 	int i;
1440 
1441 	for (i = 0; i < (1 << order); i++) {
1442 		struct page *p = page + i;
1443 		if (unlikely(check_new_page(p)))
1444 			return 1;
1445 	}
1446 
1447 	set_page_private(page, 0);
1448 	set_page_refcounted(page);
1449 
1450 	arch_alloc_page(page, order);
1451 	kernel_map_pages(page, 1 << order, 1);
1452 	kasan_alloc_pages(page, order);
1453 
1454 	if (gfp_flags & __GFP_ZERO)
1455 		for (i = 0; i < (1 << order); i++)
1456 			clear_highpage(page + i);
1457 
1458 	if (order && (gfp_flags & __GFP_COMP))
1459 		prep_compound_page(page, order);
1460 
1461 	set_page_owner(page, order, gfp_flags);
1462 
1463 	/*
1464 	 * page is set pfmemalloc when ALLOC_NO_WATERMARKS was necessary to
1465 	 * allocate the page. The expectation is that the caller is taking
1466 	 * steps that will free more memory. The caller should avoid the page
1467 	 * being used for !PFMEMALLOC purposes.
1468 	 */
1469 	if (alloc_flags & ALLOC_NO_WATERMARKS)
1470 		set_page_pfmemalloc(page);
1471 	else
1472 		clear_page_pfmemalloc(page);
1473 
1474 	return 0;
1475 }
1476 
1477 /*
1478  * Go through the free lists for the given migratetype and remove
1479  * the smallest available page from the freelists
1480  */
1481 static inline
__rmqueue_smallest(struct zone * zone,unsigned int order,int migratetype)1482 struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
1483 						int migratetype)
1484 {
1485 	unsigned int current_order;
1486 	struct free_area *area;
1487 	struct page *page;
1488 
1489 	/* Find a page of the appropriate size in the preferred list */
1490 	for (current_order = order; current_order < MAX_ORDER; ++current_order) {
1491 		area = &(zone->free_area[current_order]);
1492 		if (list_empty(&area->free_list[migratetype]))
1493 			continue;
1494 
1495 		page = list_entry(area->free_list[migratetype].next,
1496 							struct page, lru);
1497 		list_del(&page->lru);
1498 		rmv_page_order(page);
1499 		area->nr_free--;
1500 		expand(zone, page, order, current_order, area, migratetype);
1501 		set_pcppage_migratetype(page, migratetype);
1502 		return page;
1503 	}
1504 
1505 	return NULL;
1506 }
1507 
1508 
1509 /*
1510  * This array describes the order lists are fallen back to when
1511  * the free lists for the desirable migrate type are depleted
1512  */
1513 static int fallbacks[MIGRATE_TYPES][4] = {
1514 	[MIGRATE_UNMOVABLE]   = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE,   MIGRATE_TYPES },
1515 	[MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE,   MIGRATE_MOVABLE,   MIGRATE_TYPES },
1516 	[MIGRATE_MOVABLE]     = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_TYPES },
1517 #ifdef CONFIG_CMA
1518 	[MIGRATE_CMA]         = { MIGRATE_TYPES }, /* Never used */
1519 #endif
1520 #ifdef CONFIG_MEMORY_ISOLATION
1521 	[MIGRATE_ISOLATE]     = { MIGRATE_TYPES }, /* Never used */
1522 #endif
1523 };
1524 
1525 #ifdef CONFIG_CMA
__rmqueue_cma_fallback(struct zone * zone,unsigned int order)1526 static struct page *__rmqueue_cma_fallback(struct zone *zone,
1527 					unsigned int order)
1528 {
1529 	return __rmqueue_smallest(zone, order, MIGRATE_CMA);
1530 }
1531 #else
__rmqueue_cma_fallback(struct zone * zone,unsigned int order)1532 static inline struct page *__rmqueue_cma_fallback(struct zone *zone,
1533 					unsigned int order) { return NULL; }
1534 #endif
1535 
1536 /*
1537  * Move the free pages in a range to the free lists of the requested type.
1538  * Note that start_page and end_pages are not aligned on a pageblock
1539  * boundary. If alignment is required, use move_freepages_block()
1540  */
move_freepages(struct zone * zone,struct page * start_page,struct page * end_page,int migratetype)1541 int move_freepages(struct zone *zone,
1542 			  struct page *start_page, struct page *end_page,
1543 			  int migratetype)
1544 {
1545 	struct page *page;
1546 	unsigned int order;
1547 	int pages_moved = 0;
1548 
1549 #ifndef CONFIG_HOLES_IN_ZONE
1550 	/*
1551 	 * page_zone is not safe to call in this context when
1552 	 * CONFIG_HOLES_IN_ZONE is set. This bug check is probably redundant
1553 	 * anyway as we check zone boundaries in move_freepages_block().
1554 	 * Remove at a later date when no bug reports exist related to
1555 	 * grouping pages by mobility
1556 	 */
1557 	VM_BUG_ON(page_zone(start_page) != page_zone(end_page));
1558 #endif
1559 
1560 	for (page = start_page; page <= end_page;) {
1561 		if (!pfn_valid_within(page_to_pfn(page))) {
1562 			page++;
1563 			continue;
1564 		}
1565 
1566 		/* Make sure we are not inadvertently changing nodes */
1567 		VM_BUG_ON_PAGE(page_to_nid(page) != zone_to_nid(zone), page);
1568 
1569 		if (!PageBuddy(page)) {
1570 			page++;
1571 			continue;
1572 		}
1573 
1574 		order = page_order(page);
1575 		list_move(&page->lru,
1576 			  &zone->free_area[order].free_list[migratetype]);
1577 		page += 1 << order;
1578 		pages_moved += 1 << order;
1579 	}
1580 
1581 	return pages_moved;
1582 }
1583 
move_freepages_block(struct zone * zone,struct page * page,int migratetype)1584 int move_freepages_block(struct zone *zone, struct page *page,
1585 				int migratetype)
1586 {
1587 	unsigned long start_pfn, end_pfn;
1588 	struct page *start_page, *end_page;
1589 
1590 	start_pfn = page_to_pfn(page);
1591 	start_pfn = start_pfn & ~(pageblock_nr_pages-1);
1592 	start_page = pfn_to_page(start_pfn);
1593 	end_page = start_page + pageblock_nr_pages - 1;
1594 	end_pfn = start_pfn + pageblock_nr_pages - 1;
1595 
1596 	/* Do not cross zone boundaries */
1597 	if (!zone_spans_pfn(zone, start_pfn))
1598 		start_page = page;
1599 	if (!zone_spans_pfn(zone, end_pfn))
1600 		return 0;
1601 
1602 	return move_freepages(zone, start_page, end_page, migratetype);
1603 }
1604 
change_pageblock_range(struct page * pageblock_page,int start_order,int migratetype)1605 static void change_pageblock_range(struct page *pageblock_page,
1606 					int start_order, int migratetype)
1607 {
1608 	int nr_pageblocks = 1 << (start_order - pageblock_order);
1609 
1610 	while (nr_pageblocks--) {
1611 		set_pageblock_migratetype(pageblock_page, migratetype);
1612 		pageblock_page += pageblock_nr_pages;
1613 	}
1614 }
1615 
1616 /*
1617  * When we are falling back to another migratetype during allocation, try to
1618  * steal extra free pages from the same pageblocks to satisfy further
1619  * allocations, instead of polluting multiple pageblocks.
1620  *
1621  * If we are stealing a relatively large buddy page, it is likely there will
1622  * be more free pages in the pageblock, so try to steal them all. For
1623  * reclaimable and unmovable allocations, we steal regardless of page size,
1624  * as fragmentation caused by those allocations polluting movable pageblocks
1625  * is worse than movable allocations stealing from unmovable and reclaimable
1626  * pageblocks.
1627  */
can_steal_fallback(unsigned int order,int start_mt)1628 static bool can_steal_fallback(unsigned int order, int start_mt)
1629 {
1630 	/*
1631 	 * Leaving this order check is intended, although there is
1632 	 * relaxed order check in next check. The reason is that
1633 	 * we can actually steal whole pageblock if this condition met,
1634 	 * but, below check doesn't guarantee it and that is just heuristic
1635 	 * so could be changed anytime.
1636 	 */
1637 	if (order >= pageblock_order)
1638 		return true;
1639 
1640 	if (order >= pageblock_order / 2 ||
1641 		start_mt == MIGRATE_RECLAIMABLE ||
1642 		start_mt == MIGRATE_UNMOVABLE ||
1643 		page_group_by_mobility_disabled)
1644 		return true;
1645 
1646 	return false;
1647 }
1648 
1649 /*
1650  * This function implements actual steal behaviour. If order is large enough,
1651  * we can steal whole pageblock. If not, we first move freepages in this
1652  * pageblock and check whether half of pages are moved or not. If half of
1653  * pages are moved, we can change migratetype of pageblock and permanently
1654  * use it's pages as requested migratetype in the future.
1655  */
steal_suitable_fallback(struct zone * zone,struct page * page,int start_type)1656 static void steal_suitable_fallback(struct zone *zone, struct page *page,
1657 							  int start_type)
1658 {
1659 	unsigned int current_order = page_order(page);
1660 	int pages;
1661 
1662 	/* Take ownership for orders >= pageblock_order */
1663 	if (current_order >= pageblock_order) {
1664 		change_pageblock_range(page, current_order, start_type);
1665 		return;
1666 	}
1667 
1668 	pages = move_freepages_block(zone, page, start_type);
1669 
1670 	/* Claim the whole block if over half of it is free */
1671 	if (pages >= (1 << (pageblock_order-1)) ||
1672 			page_group_by_mobility_disabled)
1673 		set_pageblock_migratetype(page, start_type);
1674 }
1675 
1676 /*
1677  * Check whether there is a suitable fallback freepage with requested order.
1678  * If only_stealable is true, this function returns fallback_mt only if
1679  * we can steal other freepages all together. This would help to reduce
1680  * fragmentation due to mixed migratetype pages in one pageblock.
1681  */
find_suitable_fallback(struct free_area * area,unsigned int order,int migratetype,bool only_stealable,bool * can_steal)1682 int find_suitable_fallback(struct free_area *area, unsigned int order,
1683 			int migratetype, bool only_stealable, bool *can_steal)
1684 {
1685 	int i;
1686 	int fallback_mt;
1687 
1688 	if (area->nr_free == 0)
1689 		return -1;
1690 
1691 	*can_steal = false;
1692 	for (i = 0;; i++) {
1693 		fallback_mt = fallbacks[migratetype][i];
1694 		if (fallback_mt == MIGRATE_TYPES)
1695 			break;
1696 
1697 		if (list_empty(&area->free_list[fallback_mt]))
1698 			continue;
1699 
1700 		if (can_steal_fallback(order, migratetype))
1701 			*can_steal = true;
1702 
1703 		if (!only_stealable)
1704 			return fallback_mt;
1705 
1706 		if (*can_steal)
1707 			return fallback_mt;
1708 	}
1709 
1710 	return -1;
1711 }
1712 
1713 /*
1714  * Reserve a pageblock for exclusive use of high-order atomic allocations if
1715  * there are no empty page blocks that contain a page with a suitable order
1716  */
reserve_highatomic_pageblock(struct page * page,struct zone * zone,unsigned int alloc_order)1717 static void reserve_highatomic_pageblock(struct page *page, struct zone *zone,
1718 				unsigned int alloc_order)
1719 {
1720 	int mt;
1721 	unsigned long max_managed, flags;
1722 
1723 	/*
1724 	 * Limit the number reserved to 1 pageblock or roughly 1% of a zone.
1725 	 * Check is race-prone but harmless.
1726 	 */
1727 	max_managed = (zone->managed_pages / 100) + pageblock_nr_pages;
1728 	if (zone->nr_reserved_highatomic >= max_managed)
1729 		return;
1730 
1731 	spin_lock_irqsave(&zone->lock, flags);
1732 
1733 	/* Recheck the nr_reserved_highatomic limit under the lock */
1734 	if (zone->nr_reserved_highatomic >= max_managed)
1735 		goto out_unlock;
1736 
1737 	/* Yoink! */
1738 	mt = get_pageblock_migratetype(page);
1739 	if (mt != MIGRATE_HIGHATOMIC &&
1740 			!is_migrate_isolate(mt) && !is_migrate_cma(mt)) {
1741 		zone->nr_reserved_highatomic += pageblock_nr_pages;
1742 		set_pageblock_migratetype(page, MIGRATE_HIGHATOMIC);
1743 		move_freepages_block(zone, page, MIGRATE_HIGHATOMIC);
1744 	}
1745 
1746 out_unlock:
1747 	spin_unlock_irqrestore(&zone->lock, flags);
1748 }
1749 
1750 /*
1751  * Used when an allocation is about to fail under memory pressure. This
1752  * potentially hurts the reliability of high-order allocations when under
1753  * intense memory pressure but failed atomic allocations should be easier
1754  * to recover from than an OOM.
1755  */
unreserve_highatomic_pageblock(const struct alloc_context * ac)1756 static void unreserve_highatomic_pageblock(const struct alloc_context *ac)
1757 {
1758 	struct zonelist *zonelist = ac->zonelist;
1759 	unsigned long flags;
1760 	struct zoneref *z;
1761 	struct zone *zone;
1762 	struct page *page;
1763 	int order;
1764 
1765 	for_each_zone_zonelist_nodemask(zone, z, zonelist, ac->high_zoneidx,
1766 								ac->nodemask) {
1767 		/* Preserve at least one pageblock */
1768 		if (zone->nr_reserved_highatomic <= pageblock_nr_pages)
1769 			continue;
1770 
1771 		spin_lock_irqsave(&zone->lock, flags);
1772 		for (order = 0; order < MAX_ORDER; order++) {
1773 			struct free_area *area = &(zone->free_area[order]);
1774 
1775 			if (list_empty(&area->free_list[MIGRATE_HIGHATOMIC]))
1776 				continue;
1777 
1778 			page = list_entry(area->free_list[MIGRATE_HIGHATOMIC].next,
1779 						struct page, lru);
1780 
1781 			/*
1782 			 * In page freeing path, migratetype change is racy so
1783 			 * we can counter several free pages in a pageblock
1784 			 * in this loop althoug we changed the pageblock type
1785 			 * from highatomic to ac->migratetype. So we should
1786 			 * adjust the count once.
1787 			 */
1788 			if (get_pageblock_migratetype(page) ==
1789 							MIGRATE_HIGHATOMIC) {
1790 				/*
1791 				 * It should never happen but changes to
1792 				 * locking could inadvertently allow a per-cpu
1793 				 * drain to add pages to MIGRATE_HIGHATOMIC
1794 				 * while unreserving so be safe and watch for
1795 				 * underflows.
1796 				 */
1797 				zone->nr_reserved_highatomic -= min(
1798 						pageblock_nr_pages,
1799 						zone->nr_reserved_highatomic);
1800 			}
1801 
1802 			/*
1803 			 * Convert to ac->migratetype and avoid the normal
1804 			 * pageblock stealing heuristics. Minimally, the caller
1805 			 * is doing the work and needs the pages. More
1806 			 * importantly, if the block was always converted to
1807 			 * MIGRATE_UNMOVABLE or another type then the number
1808 			 * of pageblocks that cannot be completely freed
1809 			 * may increase.
1810 			 */
1811 			set_pageblock_migratetype(page, ac->migratetype);
1812 			move_freepages_block(zone, page, ac->migratetype);
1813 			spin_unlock_irqrestore(&zone->lock, flags);
1814 			return;
1815 		}
1816 		spin_unlock_irqrestore(&zone->lock, flags);
1817 	}
1818 }
1819 
1820 /* Remove an element from the buddy allocator from the fallback list */
1821 static inline struct page *
__rmqueue_fallback(struct zone * zone,unsigned int order,int start_migratetype)1822 __rmqueue_fallback(struct zone *zone, unsigned int order, int start_migratetype)
1823 {
1824 	struct free_area *area;
1825 	unsigned int current_order;
1826 	struct page *page;
1827 	int fallback_mt;
1828 	bool can_steal;
1829 
1830 	/* Find the largest possible block of pages in the other list */
1831 	for (current_order = MAX_ORDER-1;
1832 				current_order >= order && current_order <= MAX_ORDER-1;
1833 				--current_order) {
1834 		area = &(zone->free_area[current_order]);
1835 		fallback_mt = find_suitable_fallback(area, current_order,
1836 				start_migratetype, false, &can_steal);
1837 		if (fallback_mt == -1)
1838 			continue;
1839 
1840 		page = list_entry(area->free_list[fallback_mt].next,
1841 						struct page, lru);
1842 		if (can_steal)
1843 			steal_suitable_fallback(zone, page, start_migratetype);
1844 
1845 		/* Remove the page from the freelists */
1846 		area->nr_free--;
1847 		list_del(&page->lru);
1848 		rmv_page_order(page);
1849 
1850 		expand(zone, page, order, current_order, area,
1851 					start_migratetype);
1852 		/*
1853 		 * The pcppage_migratetype may differ from pageblock's
1854 		 * migratetype depending on the decisions in
1855 		 * find_suitable_fallback(). This is OK as long as it does not
1856 		 * differ for MIGRATE_CMA pageblocks. Those can be used as
1857 		 * fallback only via special __rmqueue_cma_fallback() function
1858 		 */
1859 		set_pcppage_migratetype(page, start_migratetype);
1860 
1861 		trace_mm_page_alloc_extfrag(page, order, current_order,
1862 			start_migratetype, fallback_mt);
1863 
1864 		return page;
1865 	}
1866 
1867 	return NULL;
1868 }
1869 
1870 /*
1871  * Do the hard work of removing an element from the buddy allocator.
1872  * Call me with the zone->lock already held.
1873  */
__rmqueue(struct zone * zone,unsigned int order,int migratetype,gfp_t gfp_flags)1874 static struct page *__rmqueue(struct zone *zone, unsigned int order,
1875 				int migratetype, gfp_t gfp_flags)
1876 {
1877 	struct page *page;
1878 
1879 	page = __rmqueue_smallest(zone, order, migratetype);
1880 	if (unlikely(!page)) {
1881 		if (migratetype == MIGRATE_MOVABLE)
1882 			page = __rmqueue_cma_fallback(zone, order);
1883 
1884 		if (!page)
1885 			page = __rmqueue_fallback(zone, order, migratetype);
1886 	}
1887 
1888 	trace_mm_page_alloc_zone_locked(page, order, migratetype);
1889 	return page;
1890 }
1891 
1892 /*
1893  * Obtain a specified number of elements from the buddy allocator, all under
1894  * a single hold of the lock, for efficiency.  Add them to the supplied list.
1895  * Returns the number of new pages which were placed at *list.
1896  */
rmqueue_bulk(struct zone * zone,unsigned int order,unsigned long count,struct list_head * list,int migratetype,bool cold)1897 static int rmqueue_bulk(struct zone *zone, unsigned int order,
1898 			unsigned long count, struct list_head *list,
1899 			int migratetype, bool cold)
1900 {
1901 	int i;
1902 
1903 	spin_lock(&zone->lock);
1904 	for (i = 0; i < count; ++i) {
1905 		struct page *page = __rmqueue(zone, order, migratetype, 0);
1906 		if (unlikely(page == NULL))
1907 			break;
1908 
1909 		/*
1910 		 * Split buddy pages returned by expand() are received here
1911 		 * in physical page order. The page is added to the callers and
1912 		 * list and the list head then moves forward. From the callers
1913 		 * perspective, the linked list is ordered by page number in
1914 		 * some conditions. This is useful for IO devices that can
1915 		 * merge IO requests if the physical pages are ordered
1916 		 * properly.
1917 		 */
1918 		if (likely(!cold))
1919 			list_add(&page->lru, list);
1920 		else
1921 			list_add_tail(&page->lru, list);
1922 		list = &page->lru;
1923 		if (is_migrate_cma(get_pcppage_migratetype(page)))
1924 			__mod_zone_page_state(zone, NR_FREE_CMA_PAGES,
1925 					      -(1 << order));
1926 	}
1927 	__mod_zone_page_state(zone, NR_FREE_PAGES, -(i << order));
1928 	spin_unlock(&zone->lock);
1929 	return i;
1930 }
1931 
1932 #ifdef CONFIG_NUMA
1933 /*
1934  * Called from the vmstat counter updater to drain pagesets of this
1935  * currently executing processor on remote nodes after they have
1936  * expired.
1937  *
1938  * Note that this function must be called with the thread pinned to
1939  * a single processor.
1940  */
drain_zone_pages(struct zone * zone,struct per_cpu_pages * pcp)1941 void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp)
1942 {
1943 	unsigned long flags;
1944 	int to_drain, batch;
1945 
1946 	local_irq_save(flags);
1947 	batch = READ_ONCE(pcp->batch);
1948 	to_drain = min(pcp->count, batch);
1949 	if (to_drain > 0) {
1950 		free_pcppages_bulk(zone, to_drain, pcp);
1951 		pcp->count -= to_drain;
1952 	}
1953 	local_irq_restore(flags);
1954 }
1955 #endif
1956 
1957 /*
1958  * Drain pcplists of the indicated processor and zone.
1959  *
1960  * The processor must either be the current processor and the
1961  * thread pinned to the current processor or a processor that
1962  * is not online.
1963  */
drain_pages_zone(unsigned int cpu,struct zone * zone)1964 static void drain_pages_zone(unsigned int cpu, struct zone *zone)
1965 {
1966 	unsigned long flags;
1967 	struct per_cpu_pageset *pset;
1968 	struct per_cpu_pages *pcp;
1969 
1970 	local_irq_save(flags);
1971 	pset = per_cpu_ptr(zone->pageset, cpu);
1972 
1973 	pcp = &pset->pcp;
1974 	if (pcp->count) {
1975 		free_pcppages_bulk(zone, pcp->count, pcp);
1976 		pcp->count = 0;
1977 	}
1978 	local_irq_restore(flags);
1979 }
1980 
1981 /*
1982  * Drain pcplists of all zones on the indicated processor.
1983  *
1984  * The processor must either be the current processor and the
1985  * thread pinned to the current processor or a processor that
1986  * is not online.
1987  */
drain_pages(unsigned int cpu)1988 static void drain_pages(unsigned int cpu)
1989 {
1990 	struct zone *zone;
1991 
1992 	for_each_populated_zone(zone) {
1993 		drain_pages_zone(cpu, zone);
1994 	}
1995 }
1996 
1997 /*
1998  * Spill all of this CPU's per-cpu pages back into the buddy allocator.
1999  *
2000  * The CPU has to be pinned. When zone parameter is non-NULL, spill just
2001  * the single zone's pages.
2002  */
drain_local_pages(struct zone * zone)2003 void drain_local_pages(struct zone *zone)
2004 {
2005 	int cpu = smp_processor_id();
2006 
2007 	if (zone)
2008 		drain_pages_zone(cpu, zone);
2009 	else
2010 		drain_pages(cpu);
2011 }
2012 
2013 /*
2014  * Spill all the per-cpu pages from all CPUs back into the buddy allocator.
2015  *
2016  * When zone parameter is non-NULL, spill just the single zone's pages.
2017  *
2018  * Note that this code is protected against sending an IPI to an offline
2019  * CPU but does not guarantee sending an IPI to newly hotplugged CPUs:
2020  * on_each_cpu_mask() blocks hotplug and won't talk to offlined CPUs but
2021  * nothing keeps CPUs from showing up after we populated the cpumask and
2022  * before the call to on_each_cpu_mask().
2023  */
drain_all_pages(struct zone * zone)2024 void drain_all_pages(struct zone *zone)
2025 {
2026 	int cpu;
2027 
2028 	/*
2029 	 * Allocate in the BSS so we wont require allocation in
2030 	 * direct reclaim path for CONFIG_CPUMASK_OFFSTACK=y
2031 	 */
2032 	static cpumask_t cpus_with_pcps;
2033 
2034 	/*
2035 	 * We don't care about racing with CPU hotplug event
2036 	 * as offline notification will cause the notified
2037 	 * cpu to drain that CPU pcps and on_each_cpu_mask
2038 	 * disables preemption as part of its processing
2039 	 */
2040 	for_each_online_cpu(cpu) {
2041 		struct per_cpu_pageset *pcp;
2042 		struct zone *z;
2043 		bool has_pcps = false;
2044 
2045 		if (zone) {
2046 			pcp = per_cpu_ptr(zone->pageset, cpu);
2047 			if (pcp->pcp.count)
2048 				has_pcps = true;
2049 		} else {
2050 			for_each_populated_zone(z) {
2051 				pcp = per_cpu_ptr(z->pageset, cpu);
2052 				if (pcp->pcp.count) {
2053 					has_pcps = true;
2054 					break;
2055 				}
2056 			}
2057 		}
2058 
2059 		if (has_pcps)
2060 			cpumask_set_cpu(cpu, &cpus_with_pcps);
2061 		else
2062 			cpumask_clear_cpu(cpu, &cpus_with_pcps);
2063 	}
2064 	on_each_cpu_mask(&cpus_with_pcps, (smp_call_func_t) drain_local_pages,
2065 								zone, 1);
2066 }
2067 
2068 #ifdef CONFIG_HIBERNATION
2069 
mark_free_pages(struct zone * zone)2070 void mark_free_pages(struct zone *zone)
2071 {
2072 	unsigned long pfn, max_zone_pfn;
2073 	unsigned long flags;
2074 	unsigned int order, t;
2075 	struct list_head *curr;
2076 
2077 	if (zone_is_empty(zone))
2078 		return;
2079 
2080 	spin_lock_irqsave(&zone->lock, flags);
2081 
2082 	max_zone_pfn = zone_end_pfn(zone);
2083 	for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
2084 		if (pfn_valid(pfn)) {
2085 			struct page *page = pfn_to_page(pfn);
2086 
2087 			if (!swsusp_page_is_forbidden(page))
2088 				swsusp_unset_page_free(page);
2089 		}
2090 
2091 	for_each_migratetype_order(order, t) {
2092 		list_for_each(curr, &zone->free_area[order].free_list[t]) {
2093 			unsigned long i;
2094 
2095 			pfn = page_to_pfn(list_entry(curr, struct page, lru));
2096 			for (i = 0; i < (1UL << order); i++)
2097 				swsusp_set_page_free(pfn_to_page(pfn + i));
2098 		}
2099 	}
2100 	spin_unlock_irqrestore(&zone->lock, flags);
2101 }
2102 #endif /* CONFIG_PM */
2103 
2104 /*
2105  * Free a 0-order page
2106  * cold == true ? free a cold page : free a hot page
2107  */
free_hot_cold_page(struct page * page,bool cold)2108 void free_hot_cold_page(struct page *page, bool cold)
2109 {
2110 	struct zone *zone = page_zone(page);
2111 	struct per_cpu_pages *pcp;
2112 	unsigned long flags;
2113 	unsigned long pfn = page_to_pfn(page);
2114 	int migratetype;
2115 
2116 	if (!free_pages_prepare(page, 0))
2117 		return;
2118 
2119 	migratetype = get_pfnblock_migratetype(page, pfn);
2120 	set_pcppage_migratetype(page, migratetype);
2121 	local_irq_save(flags);
2122 	__count_vm_event(PGFREE);
2123 
2124 	/*
2125 	 * We only track unmovable, reclaimable and movable on pcp lists.
2126 	 * Free ISOLATE pages back to the allocator because they are being
2127 	 * offlined but treat RESERVE as movable pages so we can get those
2128 	 * areas back if necessary. Otherwise, we may have to free
2129 	 * excessively into the page allocator
2130 	 */
2131 	if (migratetype >= MIGRATE_PCPTYPES) {
2132 		if (unlikely(is_migrate_isolate(migratetype))) {
2133 			free_one_page(zone, page, pfn, 0, migratetype);
2134 			goto out;
2135 		}
2136 		migratetype = MIGRATE_MOVABLE;
2137 	}
2138 
2139 	pcp = &this_cpu_ptr(zone->pageset)->pcp;
2140 	if (!cold)
2141 		list_add(&page->lru, &pcp->lists[migratetype]);
2142 	else
2143 		list_add_tail(&page->lru, &pcp->lists[migratetype]);
2144 	pcp->count++;
2145 	if (pcp->count >= pcp->high) {
2146 		unsigned long batch = READ_ONCE(pcp->batch);
2147 		free_pcppages_bulk(zone, batch, pcp);
2148 		pcp->count -= batch;
2149 	}
2150 
2151 out:
2152 	local_irq_restore(flags);
2153 }
2154 
2155 /*
2156  * Free a list of 0-order pages
2157  */
free_hot_cold_page_list(struct list_head * list,bool cold)2158 void free_hot_cold_page_list(struct list_head *list, bool cold)
2159 {
2160 	struct page *page, *next;
2161 
2162 	list_for_each_entry_safe(page, next, list, lru) {
2163 		trace_mm_page_free_batched(page, cold);
2164 		free_hot_cold_page(page, cold);
2165 	}
2166 }
2167 
2168 /*
2169  * split_page takes a non-compound higher-order page, and splits it into
2170  * n (1<<order) sub-pages: page[0..n]
2171  * Each sub-page must be freed individually.
2172  *
2173  * Note: this is probably too low level an operation for use in drivers.
2174  * Please consult with lkml before using this in your driver.
2175  */
split_page(struct page * page,unsigned int order)2176 void split_page(struct page *page, unsigned int order)
2177 {
2178 	int i;
2179 	gfp_t gfp_mask;
2180 
2181 	VM_BUG_ON_PAGE(PageCompound(page), page);
2182 	VM_BUG_ON_PAGE(!page_count(page), page);
2183 
2184 #ifdef CONFIG_KMEMCHECK
2185 	/*
2186 	 * Split shadow pages too, because free(page[0]) would
2187 	 * otherwise free the whole shadow.
2188 	 */
2189 	if (kmemcheck_page_is_tracked(page))
2190 		split_page(virt_to_page(page[0].shadow), order);
2191 #endif
2192 
2193 	gfp_mask = get_page_owner_gfp(page);
2194 	set_page_owner(page, 0, gfp_mask);
2195 	for (i = 1; i < (1 << order); i++) {
2196 		set_page_refcounted(page + i);
2197 		set_page_owner(page + i, 0, gfp_mask);
2198 	}
2199 }
2200 EXPORT_SYMBOL_GPL(split_page);
2201 
__isolate_free_page(struct page * page,unsigned int order)2202 int __isolate_free_page(struct page *page, unsigned int order)
2203 {
2204 	unsigned long watermark;
2205 	struct zone *zone;
2206 	int mt;
2207 
2208 	BUG_ON(!PageBuddy(page));
2209 
2210 	zone = page_zone(page);
2211 	mt = get_pageblock_migratetype(page);
2212 
2213 	if (!is_migrate_isolate(mt)) {
2214 		/* Obey watermarks as if the page was being allocated */
2215 		watermark = low_wmark_pages(zone) + (1 << order);
2216 		if (!zone_watermark_ok(zone, 0, watermark, 0, 0))
2217 			return 0;
2218 
2219 		__mod_zone_freepage_state(zone, -(1UL << order), mt);
2220 	}
2221 
2222 	/* Remove page from free list */
2223 	list_del(&page->lru);
2224 	zone->free_area[order].nr_free--;
2225 	rmv_page_order(page);
2226 
2227 	set_page_owner(page, order, __GFP_MOVABLE);
2228 
2229 	/* Set the pageblock if the isolated page is at least a pageblock */
2230 	if (order >= pageblock_order - 1) {
2231 		struct page *endpage = page + (1 << order) - 1;
2232 		for (; page < endpage; page += pageblock_nr_pages) {
2233 			int mt = get_pageblock_migratetype(page);
2234 			if (!is_migrate_isolate(mt) && !is_migrate_cma(mt))
2235 				set_pageblock_migratetype(page,
2236 							  MIGRATE_MOVABLE);
2237 		}
2238 	}
2239 
2240 
2241 	return 1UL << order;
2242 }
2243 
2244 /*
2245  * Similar to split_page except the page is already free. As this is only
2246  * being used for migration, the migratetype of the block also changes.
2247  * As this is called with interrupts disabled, the caller is responsible
2248  * for calling arch_alloc_page() and kernel_map_page() after interrupts
2249  * are enabled.
2250  *
2251  * Note: this is probably too low level an operation for use in drivers.
2252  * Please consult with lkml before using this in your driver.
2253  */
split_free_page(struct page * page)2254 int split_free_page(struct page *page)
2255 {
2256 	unsigned int order;
2257 	int nr_pages;
2258 
2259 	order = page_order(page);
2260 
2261 	nr_pages = __isolate_free_page(page, order);
2262 	if (!nr_pages)
2263 		return 0;
2264 
2265 	/* Split into individual pages */
2266 	set_page_refcounted(page);
2267 	split_page(page, order);
2268 	return nr_pages;
2269 }
2270 
2271 /*
2272  * Allocate a page from the given zone. Use pcplists for order-0 allocations.
2273  */
2274 static inline
buffered_rmqueue(struct zone * preferred_zone,struct zone * zone,unsigned int order,gfp_t gfp_flags,int alloc_flags,int migratetype)2275 struct page *buffered_rmqueue(struct zone *preferred_zone,
2276 			struct zone *zone, unsigned int order,
2277 			gfp_t gfp_flags, int alloc_flags, int migratetype)
2278 {
2279 	unsigned long flags;
2280 	struct page *page;
2281 	bool cold = ((gfp_flags & __GFP_COLD) != 0);
2282 
2283 	if (likely(order == 0)) {
2284 		struct per_cpu_pages *pcp;
2285 		struct list_head *list;
2286 
2287 		local_irq_save(flags);
2288 		pcp = &this_cpu_ptr(zone->pageset)->pcp;
2289 		list = &pcp->lists[migratetype];
2290 		if (list_empty(list)) {
2291 			pcp->count += rmqueue_bulk(zone, 0,
2292 					pcp->batch, list,
2293 					migratetype, cold);
2294 			if (unlikely(list_empty(list)))
2295 				goto failed;
2296 		}
2297 
2298 		if (cold)
2299 			page = list_entry(list->prev, struct page, lru);
2300 		else
2301 			page = list_entry(list->next, struct page, lru);
2302 
2303 		list_del(&page->lru);
2304 		pcp->count--;
2305 	} else {
2306 		if (unlikely(gfp_flags & __GFP_NOFAIL)) {
2307 			/*
2308 			 * __GFP_NOFAIL is not to be used in new code.
2309 			 *
2310 			 * All __GFP_NOFAIL callers should be fixed so that they
2311 			 * properly detect and handle allocation failures.
2312 			 *
2313 			 * We most definitely don't want callers attempting to
2314 			 * allocate greater than order-1 page units with
2315 			 * __GFP_NOFAIL.
2316 			 */
2317 			WARN_ON_ONCE(order > 1);
2318 		}
2319 		spin_lock_irqsave(&zone->lock, flags);
2320 
2321 		page = NULL;
2322 		if (alloc_flags & ALLOC_HARDER) {
2323 			page = __rmqueue_smallest(zone, order, MIGRATE_HIGHATOMIC);
2324 			if (page)
2325 				trace_mm_page_alloc_zone_locked(page, order, migratetype);
2326 		}
2327 		if (!page)
2328 			page = __rmqueue(zone, order, migratetype, gfp_flags);
2329 		spin_unlock(&zone->lock);
2330 		if (!page)
2331 			goto failed;
2332 		__mod_zone_freepage_state(zone, -(1 << order),
2333 					  get_pcppage_migratetype(page));
2334 	}
2335 
2336 	__mod_zone_page_state(zone, NR_ALLOC_BATCH, -(1 << order));
2337 	if (atomic_long_read(&zone->vm_stat[NR_ALLOC_BATCH]) <= 0 &&
2338 	    !test_bit(ZONE_FAIR_DEPLETED, &zone->flags))
2339 		set_bit(ZONE_FAIR_DEPLETED, &zone->flags);
2340 
2341 	__count_zone_vm_events(PGALLOC, zone, 1 << order);
2342 	zone_statistics(preferred_zone, zone, gfp_flags);
2343 	local_irq_restore(flags);
2344 
2345 	VM_BUG_ON_PAGE(bad_range(zone, page), page);
2346 	return page;
2347 
2348 failed:
2349 	local_irq_restore(flags);
2350 	return NULL;
2351 }
2352 
2353 #ifdef CONFIG_FAIL_PAGE_ALLOC
2354 
2355 static struct {
2356 	struct fault_attr attr;
2357 
2358 	bool ignore_gfp_highmem;
2359 	bool ignore_gfp_reclaim;
2360 	u32 min_order;
2361 } fail_page_alloc = {
2362 	.attr = FAULT_ATTR_INITIALIZER,
2363 	.ignore_gfp_reclaim = true,
2364 	.ignore_gfp_highmem = true,
2365 	.min_order = 1,
2366 };
2367 
setup_fail_page_alloc(char * str)2368 static int __init setup_fail_page_alloc(char *str)
2369 {
2370 	return setup_fault_attr(&fail_page_alloc.attr, str);
2371 }
2372 __setup("fail_page_alloc=", setup_fail_page_alloc);
2373 
should_fail_alloc_page(gfp_t gfp_mask,unsigned int order)2374 static bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
2375 {
2376 	if (order < fail_page_alloc.min_order)
2377 		return false;
2378 	if (gfp_mask & __GFP_NOFAIL)
2379 		return false;
2380 	if (fail_page_alloc.ignore_gfp_highmem && (gfp_mask & __GFP_HIGHMEM))
2381 		return false;
2382 	if (fail_page_alloc.ignore_gfp_reclaim &&
2383 			(gfp_mask & __GFP_DIRECT_RECLAIM))
2384 		return false;
2385 
2386 	return should_fail(&fail_page_alloc.attr, 1 << order);
2387 }
2388 
2389 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
2390 
fail_page_alloc_debugfs(void)2391 static int __init fail_page_alloc_debugfs(void)
2392 {
2393 	umode_t mode = S_IFREG | S_IRUSR | S_IWUSR;
2394 	struct dentry *dir;
2395 
2396 	dir = fault_create_debugfs_attr("fail_page_alloc", NULL,
2397 					&fail_page_alloc.attr);
2398 	if (IS_ERR(dir))
2399 		return PTR_ERR(dir);
2400 
2401 	if (!debugfs_create_bool("ignore-gfp-wait", mode, dir,
2402 				&fail_page_alloc.ignore_gfp_reclaim))
2403 		goto fail;
2404 	if (!debugfs_create_bool("ignore-gfp-highmem", mode, dir,
2405 				&fail_page_alloc.ignore_gfp_highmem))
2406 		goto fail;
2407 	if (!debugfs_create_u32("min-order", mode, dir,
2408 				&fail_page_alloc.min_order))
2409 		goto fail;
2410 
2411 	return 0;
2412 fail:
2413 	debugfs_remove_recursive(dir);
2414 
2415 	return -ENOMEM;
2416 }
2417 
2418 late_initcall(fail_page_alloc_debugfs);
2419 
2420 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
2421 
2422 #else /* CONFIG_FAIL_PAGE_ALLOC */
2423 
should_fail_alloc_page(gfp_t gfp_mask,unsigned int order)2424 static inline bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
2425 {
2426 	return false;
2427 }
2428 
2429 #endif /* CONFIG_FAIL_PAGE_ALLOC */
2430 
2431 /*
2432  * Return true if free base pages are above 'mark'. For high-order checks it
2433  * will return true of the order-0 watermark is reached and there is at least
2434  * one free page of a suitable size. Checking now avoids taking the zone lock
2435  * to check in the allocation paths if no pages are free.
2436  */
__zone_watermark_ok(struct zone * z,unsigned int order,unsigned long mark,int classzone_idx,int alloc_flags,long free_pages)2437 static bool __zone_watermark_ok(struct zone *z, unsigned int order,
2438 			unsigned long mark, int classzone_idx, int alloc_flags,
2439 			long free_pages)
2440 {
2441 	long min = mark;
2442 	int o;
2443 	const int alloc_harder = (alloc_flags & ALLOC_HARDER);
2444 
2445 	/* free_pages may go negative - that's OK */
2446 	free_pages -= (1 << order) - 1;
2447 
2448 	if (alloc_flags & ALLOC_HIGH)
2449 		min -= min / 2;
2450 
2451 	/*
2452 	 * If the caller does not have rights to ALLOC_HARDER then subtract
2453 	 * the high-atomic reserves. This will over-estimate the size of the
2454 	 * atomic reserve but it avoids a search.
2455 	 */
2456 	if (likely(!alloc_harder))
2457 		free_pages -= z->nr_reserved_highatomic;
2458 	else
2459 		min -= min / 4;
2460 
2461 #ifdef CONFIG_CMA
2462 	/* If allocation can't use CMA areas don't use free CMA pages */
2463 	if (!(alloc_flags & ALLOC_CMA))
2464 		free_pages -= zone_page_state(z, NR_FREE_CMA_PAGES);
2465 #endif
2466 
2467 	/*
2468 	 * Check watermarks for an order-0 allocation request. If these
2469 	 * are not met, then a high-order request also cannot go ahead
2470 	 * even if a suitable page happened to be free.
2471 	 */
2472 	if (free_pages <= min + z->lowmem_reserve[classzone_idx])
2473 		return false;
2474 
2475 	/* If this is an order-0 request then the watermark is fine */
2476 	if (!order)
2477 		return true;
2478 
2479 	/* For a high-order request, check at least one suitable page is free */
2480 	for (o = order; o < MAX_ORDER; o++) {
2481 		struct free_area *area = &z->free_area[o];
2482 		int mt;
2483 
2484 		if (!area->nr_free)
2485 			continue;
2486 
2487 		for (mt = 0; mt < MIGRATE_PCPTYPES; mt++) {
2488 			if (!list_empty(&area->free_list[mt]))
2489 				return true;
2490 		}
2491 
2492 #ifdef CONFIG_CMA
2493 		if ((alloc_flags & ALLOC_CMA) &&
2494 		    !list_empty(&area->free_list[MIGRATE_CMA])) {
2495 			return true;
2496 		}
2497 #endif
2498 		if (alloc_harder &&
2499 			!list_empty(&area->free_list[MIGRATE_HIGHATOMIC]))
2500 			return true;
2501 	}
2502 	return false;
2503 }
2504 
zone_watermark_ok(struct zone * z,unsigned int order,unsigned long mark,int classzone_idx,int alloc_flags)2505 bool zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
2506 		      int classzone_idx, int alloc_flags)
2507 {
2508 	return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
2509 					zone_page_state(z, NR_FREE_PAGES));
2510 }
2511 
zone_watermark_ok_safe(struct zone * z,unsigned int order,unsigned long mark,int classzone_idx)2512 bool zone_watermark_ok_safe(struct zone *z, unsigned int order,
2513 			unsigned long mark, int classzone_idx)
2514 {
2515 	long free_pages = zone_page_state(z, NR_FREE_PAGES);
2516 
2517 	if (z->percpu_drift_mark && free_pages < z->percpu_drift_mark)
2518 		free_pages = zone_page_state_snapshot(z, NR_FREE_PAGES);
2519 
2520 	return __zone_watermark_ok(z, order, mark, classzone_idx, 0,
2521 								free_pages);
2522 }
2523 
2524 #ifdef CONFIG_NUMA
zone_local(struct zone * local_zone,struct zone * zone)2525 static bool zone_local(struct zone *local_zone, struct zone *zone)
2526 {
2527 	return local_zone->node == zone->node;
2528 }
2529 
zone_allows_reclaim(struct zone * local_zone,struct zone * zone)2530 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
2531 {
2532 	return node_distance(zone_to_nid(local_zone), zone_to_nid(zone)) <=
2533 				RECLAIM_DISTANCE;
2534 }
2535 #else	/* CONFIG_NUMA */
zone_local(struct zone * local_zone,struct zone * zone)2536 static bool zone_local(struct zone *local_zone, struct zone *zone)
2537 {
2538 	return true;
2539 }
2540 
zone_allows_reclaim(struct zone * local_zone,struct zone * zone)2541 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
2542 {
2543 	return true;
2544 }
2545 #endif	/* CONFIG_NUMA */
2546 
reset_alloc_batches(struct zone * preferred_zone)2547 static void reset_alloc_batches(struct zone *preferred_zone)
2548 {
2549 	struct zone *zone = preferred_zone->zone_pgdat->node_zones;
2550 
2551 	do {
2552 		mod_zone_page_state(zone, NR_ALLOC_BATCH,
2553 			high_wmark_pages(zone) - low_wmark_pages(zone) -
2554 			atomic_long_read(&zone->vm_stat[NR_ALLOC_BATCH]));
2555 		clear_bit(ZONE_FAIR_DEPLETED, &zone->flags);
2556 	} while (zone++ != preferred_zone);
2557 }
2558 
2559 /*
2560  * get_page_from_freelist goes through the zonelist trying to allocate
2561  * a page.
2562  */
2563 static struct page *
get_page_from_freelist(gfp_t gfp_mask,unsigned int order,int alloc_flags,const struct alloc_context * ac)2564 get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags,
2565 						const struct alloc_context *ac)
2566 {
2567 	struct zonelist *zonelist = ac->zonelist;
2568 	struct zoneref *z;
2569 	struct page *page = NULL;
2570 	struct zone *zone;
2571 	int nr_fair_skipped = 0;
2572 	bool zonelist_rescan;
2573 
2574 zonelist_scan:
2575 	zonelist_rescan = false;
2576 
2577 	/*
2578 	 * Scan zonelist, looking for a zone with enough free.
2579 	 * See also __cpuset_node_allowed() comment in kernel/cpuset.c.
2580 	 */
2581 	for_each_zone_zonelist_nodemask(zone, z, zonelist, ac->high_zoneidx,
2582 								ac->nodemask) {
2583 		unsigned long mark;
2584 
2585 		if (cpusets_enabled() &&
2586 			(alloc_flags & ALLOC_CPUSET) &&
2587 			!cpuset_zone_allowed(zone, gfp_mask))
2588 				continue;
2589 		/*
2590 		 * Distribute pages in proportion to the individual
2591 		 * zone size to ensure fair page aging.  The zone a
2592 		 * page was allocated in should have no effect on the
2593 		 * time the page has in memory before being reclaimed.
2594 		 */
2595 		if (alloc_flags & ALLOC_FAIR) {
2596 			if (!zone_local(ac->preferred_zone, zone))
2597 				break;
2598 			if (test_bit(ZONE_FAIR_DEPLETED, &zone->flags)) {
2599 				nr_fair_skipped++;
2600 				continue;
2601 			}
2602 		}
2603 		/*
2604 		 * When allocating a page cache page for writing, we
2605 		 * want to get it from a zone that is within its dirty
2606 		 * limit, such that no single zone holds more than its
2607 		 * proportional share of globally allowed dirty pages.
2608 		 * The dirty limits take into account the zone's
2609 		 * lowmem reserves and high watermark so that kswapd
2610 		 * should be able to balance it without having to
2611 		 * write pages from its LRU list.
2612 		 *
2613 		 * This may look like it could increase pressure on
2614 		 * lower zones by failing allocations in higher zones
2615 		 * before they are full.  But the pages that do spill
2616 		 * over are limited as the lower zones are protected
2617 		 * by this very same mechanism.  It should not become
2618 		 * a practical burden to them.
2619 		 *
2620 		 * XXX: For now, allow allocations to potentially
2621 		 * exceed the per-zone dirty limit in the slowpath
2622 		 * (spread_dirty_pages unset) before going into reclaim,
2623 		 * which is important when on a NUMA setup the allowed
2624 		 * zones are together not big enough to reach the
2625 		 * global limit.  The proper fix for these situations
2626 		 * will require awareness of zones in the
2627 		 * dirty-throttling and the flusher threads.
2628 		 */
2629 		if (ac->spread_dirty_pages && !zone_dirty_ok(zone))
2630 			continue;
2631 
2632 		mark = zone->watermark[alloc_flags & ALLOC_WMARK_MASK];
2633 		if (!zone_watermark_ok(zone, order, mark,
2634 				       ac->classzone_idx, alloc_flags)) {
2635 			int ret;
2636 
2637 			/* Checked here to keep the fast path fast */
2638 			BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK);
2639 			if (alloc_flags & ALLOC_NO_WATERMARKS)
2640 				goto try_this_zone;
2641 
2642 			if (zone_reclaim_mode == 0 ||
2643 			    !zone_allows_reclaim(ac->preferred_zone, zone))
2644 				continue;
2645 
2646 			ret = zone_reclaim(zone, gfp_mask, order);
2647 			switch (ret) {
2648 			case ZONE_RECLAIM_NOSCAN:
2649 				/* did not scan */
2650 				continue;
2651 			case ZONE_RECLAIM_FULL:
2652 				/* scanned but unreclaimable */
2653 				continue;
2654 			default:
2655 				/* did we reclaim enough */
2656 				if (zone_watermark_ok(zone, order, mark,
2657 						ac->classzone_idx, alloc_flags))
2658 					goto try_this_zone;
2659 
2660 				continue;
2661 			}
2662 		}
2663 
2664 try_this_zone:
2665 		page = buffered_rmqueue(ac->preferred_zone, zone, order,
2666 				gfp_mask, alloc_flags, ac->migratetype);
2667 		if (page) {
2668 			if (prep_new_page(page, order, gfp_mask, alloc_flags))
2669 				goto try_this_zone;
2670 
2671 			/*
2672 			 * If this is a high-order atomic allocation then check
2673 			 * if the pageblock should be reserved for the future
2674 			 */
2675 			if (unlikely(order && (alloc_flags & ALLOC_HARDER)))
2676 				reserve_highatomic_pageblock(page, zone, order);
2677 
2678 			return page;
2679 		}
2680 	}
2681 
2682 	/*
2683 	 * The first pass makes sure allocations are spread fairly within the
2684 	 * local node.  However, the local node might have free pages left
2685 	 * after the fairness batches are exhausted, and remote zones haven't
2686 	 * even been considered yet.  Try once more without fairness, and
2687 	 * include remote zones now, before entering the slowpath and waking
2688 	 * kswapd: prefer spilling to a remote zone over swapping locally.
2689 	 */
2690 	if (alloc_flags & ALLOC_FAIR) {
2691 		alloc_flags &= ~ALLOC_FAIR;
2692 		if (nr_fair_skipped) {
2693 			zonelist_rescan = true;
2694 			reset_alloc_batches(ac->preferred_zone);
2695 		}
2696 		if (nr_online_nodes > 1)
2697 			zonelist_rescan = true;
2698 	}
2699 
2700 	if (zonelist_rescan)
2701 		goto zonelist_scan;
2702 
2703 	return NULL;
2704 }
2705 
2706 /*
2707  * Large machines with many possible nodes should not always dump per-node
2708  * meminfo in irq context.
2709  */
should_suppress_show_mem(void)2710 static inline bool should_suppress_show_mem(void)
2711 {
2712 	bool ret = false;
2713 
2714 #if NODES_SHIFT > 8
2715 	ret = in_interrupt();
2716 #endif
2717 	return ret;
2718 }
2719 
2720 static DEFINE_RATELIMIT_STATE(nopage_rs,
2721 		DEFAULT_RATELIMIT_INTERVAL,
2722 		DEFAULT_RATELIMIT_BURST);
2723 
warn_alloc_failed(gfp_t gfp_mask,unsigned int order,const char * fmt,...)2724 void warn_alloc_failed(gfp_t gfp_mask, unsigned int order, const char *fmt, ...)
2725 {
2726 	unsigned int filter = SHOW_MEM_FILTER_NODES;
2727 
2728 	if ((gfp_mask & __GFP_NOWARN) || !__ratelimit(&nopage_rs) ||
2729 	    debug_guardpage_minorder() > 0)
2730 		return;
2731 
2732 	/*
2733 	 * This documents exceptions given to allocations in certain
2734 	 * contexts that are allowed to allocate outside current's set
2735 	 * of allowed nodes.
2736 	 */
2737 	if (!(gfp_mask & __GFP_NOMEMALLOC))
2738 		if (test_thread_flag(TIF_MEMDIE) ||
2739 		    (current->flags & (PF_MEMALLOC | PF_EXITING)))
2740 			filter &= ~SHOW_MEM_FILTER_NODES;
2741 	if (in_interrupt() || !(gfp_mask & __GFP_DIRECT_RECLAIM))
2742 		filter &= ~SHOW_MEM_FILTER_NODES;
2743 
2744 	if (fmt) {
2745 		struct va_format vaf;
2746 		va_list args;
2747 
2748 		va_start(args, fmt);
2749 
2750 		vaf.fmt = fmt;
2751 		vaf.va = &args;
2752 
2753 		pr_warn("%pV", &vaf);
2754 
2755 		va_end(args);
2756 	}
2757 
2758 	pr_warn("%s: page allocation failure: order:%u, mode:0x%x\n",
2759 		current->comm, order, gfp_mask);
2760 
2761 	dump_stack();
2762 	if (!should_suppress_show_mem())
2763 		show_mem(filter);
2764 }
2765 
2766 static inline struct page *
__alloc_pages_may_oom(gfp_t gfp_mask,unsigned int order,const struct alloc_context * ac,unsigned long * did_some_progress)2767 __alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order,
2768 	const struct alloc_context *ac, unsigned long *did_some_progress)
2769 {
2770 	struct oom_control oc = {
2771 		.zonelist = ac->zonelist,
2772 		.nodemask = ac->nodemask,
2773 		.gfp_mask = gfp_mask,
2774 		.order = order,
2775 	};
2776 	struct page *page;
2777 
2778 	*did_some_progress = 0;
2779 
2780 	/*
2781 	 * Acquire the oom lock.  If that fails, somebody else is
2782 	 * making progress for us.
2783 	 */
2784 	if (!mutex_trylock(&oom_lock)) {
2785 		*did_some_progress = 1;
2786 		schedule_timeout_uninterruptible(1);
2787 		return NULL;
2788 	}
2789 
2790 	/*
2791 	 * Go through the zonelist yet one more time, keep very high watermark
2792 	 * here, this is only to catch a parallel oom killing, we must fail if
2793 	 * we're still under heavy pressure.
2794 	 */
2795 	page = get_page_from_freelist(gfp_mask | __GFP_HARDWALL, order,
2796 					ALLOC_WMARK_HIGH|ALLOC_CPUSET, ac);
2797 	if (page)
2798 		goto out;
2799 
2800 	if (!(gfp_mask & __GFP_NOFAIL)) {
2801 		/* Coredumps can quickly deplete all memory reserves */
2802 		if (current->flags & PF_DUMPCORE)
2803 			goto out;
2804 		/* The OOM killer will not help higher order allocs */
2805 		if (order > PAGE_ALLOC_COSTLY_ORDER)
2806 			goto out;
2807 		/* The OOM killer does not needlessly kill tasks for lowmem */
2808 		if (ac->high_zoneidx < ZONE_NORMAL)
2809 			goto out;
2810 		/* The OOM killer does not compensate for IO-less reclaim */
2811 		if (!(gfp_mask & __GFP_FS)) {
2812 			/*
2813 			 * XXX: Page reclaim didn't yield anything,
2814 			 * and the OOM killer can't be invoked, but
2815 			 * keep looping as per tradition.
2816 			 */
2817 			*did_some_progress = 1;
2818 			goto out;
2819 		}
2820 		if (pm_suspended_storage())
2821 			goto out;
2822 		/* The OOM killer may not free memory on a specific node */
2823 		if (gfp_mask & __GFP_THISNODE)
2824 			goto out;
2825 	}
2826 	/* Exhausted what can be done so it's blamo time */
2827 	if (out_of_memory(&oc) || WARN_ON_ONCE(gfp_mask & __GFP_NOFAIL))
2828 		*did_some_progress = 1;
2829 out:
2830 	mutex_unlock(&oom_lock);
2831 	return page;
2832 }
2833 
2834 #ifdef CONFIG_COMPACTION
2835 /* Try memory compaction for high-order allocations before reclaim */
2836 static struct page *
__alloc_pages_direct_compact(gfp_t gfp_mask,unsigned int order,int alloc_flags,const struct alloc_context * ac,enum migrate_mode mode,int * contended_compaction,bool * deferred_compaction)2837 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
2838 		int alloc_flags, const struct alloc_context *ac,
2839 		enum migrate_mode mode, int *contended_compaction,
2840 		bool *deferred_compaction)
2841 {
2842 	unsigned long compact_result;
2843 	struct page *page;
2844 
2845 	if (!order)
2846 		return NULL;
2847 
2848 	current->flags |= PF_MEMALLOC;
2849 	compact_result = try_to_compact_pages(gfp_mask, order, alloc_flags, ac,
2850 						mode, contended_compaction);
2851 	current->flags &= ~PF_MEMALLOC;
2852 
2853 	switch (compact_result) {
2854 	case COMPACT_DEFERRED:
2855 		*deferred_compaction = true;
2856 		/* fall-through */
2857 	case COMPACT_SKIPPED:
2858 		return NULL;
2859 	default:
2860 		break;
2861 	}
2862 
2863 	/*
2864 	 * At least in one zone compaction wasn't deferred or skipped, so let's
2865 	 * count a compaction stall
2866 	 */
2867 	count_vm_event(COMPACTSTALL);
2868 
2869 	page = get_page_from_freelist(gfp_mask, order,
2870 					alloc_flags & ~ALLOC_NO_WATERMARKS, ac);
2871 
2872 	if (page) {
2873 		struct zone *zone = page_zone(page);
2874 
2875 		zone->compact_blockskip_flush = false;
2876 		compaction_defer_reset(zone, order, true);
2877 		count_vm_event(COMPACTSUCCESS);
2878 		return page;
2879 	}
2880 
2881 	/*
2882 	 * It's bad if compaction run occurs and fails. The most likely reason
2883 	 * is that pages exist, but not enough to satisfy watermarks.
2884 	 */
2885 	count_vm_event(COMPACTFAIL);
2886 
2887 	cond_resched();
2888 
2889 	return NULL;
2890 }
2891 #else
2892 static inline struct page *
__alloc_pages_direct_compact(gfp_t gfp_mask,unsigned int order,int alloc_flags,const struct alloc_context * ac,enum migrate_mode mode,int * contended_compaction,bool * deferred_compaction)2893 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
2894 		int alloc_flags, const struct alloc_context *ac,
2895 		enum migrate_mode mode, int *contended_compaction,
2896 		bool *deferred_compaction)
2897 {
2898 	return NULL;
2899 }
2900 #endif /* CONFIG_COMPACTION */
2901 
2902 /* Perform direct synchronous page reclaim */
2903 static int
__perform_reclaim(gfp_t gfp_mask,unsigned int order,const struct alloc_context * ac)2904 __perform_reclaim(gfp_t gfp_mask, unsigned int order,
2905 					const struct alloc_context *ac)
2906 {
2907 	struct reclaim_state reclaim_state;
2908 	int progress;
2909 
2910 	cond_resched();
2911 
2912 	/* We now go into synchronous reclaim */
2913 	cpuset_memory_pressure_bump();
2914 	current->flags |= PF_MEMALLOC;
2915 	lockdep_set_current_reclaim_state(gfp_mask);
2916 	reclaim_state.reclaimed_slab = 0;
2917 	current->reclaim_state = &reclaim_state;
2918 
2919 	progress = try_to_free_pages(ac->zonelist, order, gfp_mask,
2920 								ac->nodemask);
2921 
2922 	current->reclaim_state = NULL;
2923 	lockdep_clear_current_reclaim_state();
2924 	current->flags &= ~PF_MEMALLOC;
2925 
2926 	cond_resched();
2927 
2928 	return progress;
2929 }
2930 
2931 /* The really slow allocator path where we enter direct reclaim */
2932 static inline struct page *
__alloc_pages_direct_reclaim(gfp_t gfp_mask,unsigned int order,int alloc_flags,const struct alloc_context * ac,unsigned long * did_some_progress)2933 __alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order,
2934 		int alloc_flags, const struct alloc_context *ac,
2935 		unsigned long *did_some_progress)
2936 {
2937 	struct page *page = NULL;
2938 	bool drained = false;
2939 
2940 	*did_some_progress = __perform_reclaim(gfp_mask, order, ac);
2941 	if (unlikely(!(*did_some_progress)))
2942 		return NULL;
2943 
2944 retry:
2945 	page = get_page_from_freelist(gfp_mask, order,
2946 					alloc_flags & ~ALLOC_NO_WATERMARKS, ac);
2947 
2948 	/*
2949 	 * If an allocation failed after direct reclaim, it could be because
2950 	 * pages are pinned on the per-cpu lists or in high alloc reserves.
2951 	 * Shrink them them and try again
2952 	 */
2953 	if (!page && !drained) {
2954 		unreserve_highatomic_pageblock(ac);
2955 		drain_all_pages(NULL);
2956 		drained = true;
2957 		goto retry;
2958 	}
2959 
2960 	return page;
2961 }
2962 
2963 /*
2964  * This is called in the allocator slow-path if the allocation request is of
2965  * sufficient urgency to ignore watermarks and take other desperate measures
2966  */
2967 static inline struct page *
__alloc_pages_high_priority(gfp_t gfp_mask,unsigned int order,const struct alloc_context * ac)2968 __alloc_pages_high_priority(gfp_t gfp_mask, unsigned int order,
2969 				const struct alloc_context *ac)
2970 {
2971 	struct page *page;
2972 
2973 	do {
2974 		page = get_page_from_freelist(gfp_mask, order,
2975 						ALLOC_NO_WATERMARKS, ac);
2976 
2977 		if (!page && gfp_mask & __GFP_NOFAIL)
2978 			wait_iff_congested(ac->preferred_zone, BLK_RW_ASYNC,
2979 									HZ/50);
2980 	} while (!page && (gfp_mask & __GFP_NOFAIL));
2981 
2982 	return page;
2983 }
2984 
wake_all_kswapds(unsigned int order,const struct alloc_context * ac)2985 static void wake_all_kswapds(unsigned int order, const struct alloc_context *ac)
2986 {
2987 	struct zoneref *z;
2988 	struct zone *zone;
2989 
2990 	for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
2991 						ac->high_zoneidx, ac->nodemask)
2992 		wakeup_kswapd(zone, order, zone_idx(ac->preferred_zone));
2993 }
2994 
2995 static inline int
gfp_to_alloc_flags(gfp_t gfp_mask)2996 gfp_to_alloc_flags(gfp_t gfp_mask)
2997 {
2998 	int alloc_flags = ALLOC_WMARK_MIN | ALLOC_CPUSET;
2999 
3000 	/* __GFP_HIGH is assumed to be the same as ALLOC_HIGH to save a branch. */
3001 	BUILD_BUG_ON(__GFP_HIGH != (__force gfp_t) ALLOC_HIGH);
3002 
3003 	/*
3004 	 * The caller may dip into page reserves a bit more if the caller
3005 	 * cannot run direct reclaim, or if the caller has realtime scheduling
3006 	 * policy or is asking for __GFP_HIGH memory.  GFP_ATOMIC requests will
3007 	 * set both ALLOC_HARDER (__GFP_ATOMIC) and ALLOC_HIGH (__GFP_HIGH).
3008 	 */
3009 	alloc_flags |= (__force int) (gfp_mask & __GFP_HIGH);
3010 
3011 	if (gfp_mask & __GFP_ATOMIC) {
3012 		/*
3013 		 * Not worth trying to allocate harder for __GFP_NOMEMALLOC even
3014 		 * if it can't schedule.
3015 		 */
3016 		if (!(gfp_mask & __GFP_NOMEMALLOC))
3017 			alloc_flags |= ALLOC_HARDER;
3018 		/*
3019 		 * Ignore cpuset mems for GFP_ATOMIC rather than fail, see the
3020 		 * comment for __cpuset_node_allowed().
3021 		 */
3022 		alloc_flags &= ~ALLOC_CPUSET;
3023 	} else if (unlikely(rt_task(current)) && !in_interrupt())
3024 		alloc_flags |= ALLOC_HARDER;
3025 
3026 	if (likely(!(gfp_mask & __GFP_NOMEMALLOC))) {
3027 		if (gfp_mask & __GFP_MEMALLOC)
3028 			alloc_flags |= ALLOC_NO_WATERMARKS;
3029 		else if (in_serving_softirq() && (current->flags & PF_MEMALLOC))
3030 			alloc_flags |= ALLOC_NO_WATERMARKS;
3031 		else if (!in_interrupt() &&
3032 				((current->flags & PF_MEMALLOC) ||
3033 				 unlikely(test_thread_flag(TIF_MEMDIE))))
3034 			alloc_flags |= ALLOC_NO_WATERMARKS;
3035 	}
3036 #ifdef CONFIG_CMA
3037 	if (gfpflags_to_migratetype(gfp_mask) == MIGRATE_MOVABLE)
3038 		alloc_flags |= ALLOC_CMA;
3039 #endif
3040 	return alloc_flags;
3041 }
3042 
gfp_pfmemalloc_allowed(gfp_t gfp_mask)3043 bool gfp_pfmemalloc_allowed(gfp_t gfp_mask)
3044 {
3045 	return !!(gfp_to_alloc_flags(gfp_mask) & ALLOC_NO_WATERMARKS);
3046 }
3047 
is_thp_gfp_mask(gfp_t gfp_mask)3048 static inline bool is_thp_gfp_mask(gfp_t gfp_mask)
3049 {
3050 	return (gfp_mask & (GFP_TRANSHUGE | __GFP_KSWAPD_RECLAIM)) == GFP_TRANSHUGE;
3051 }
3052 
3053 static inline struct page *
__alloc_pages_slowpath(gfp_t gfp_mask,unsigned int order,struct alloc_context * ac)3054 __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order,
3055 						struct alloc_context *ac)
3056 {
3057 	bool can_direct_reclaim = gfp_mask & __GFP_DIRECT_RECLAIM;
3058 	struct page *page = NULL;
3059 	int alloc_flags;
3060 	unsigned long pages_reclaimed = 0;
3061 	unsigned long did_some_progress;
3062 	enum migrate_mode migration_mode = MIGRATE_ASYNC;
3063 	bool deferred_compaction = false;
3064 	int contended_compaction = COMPACT_CONTENDED_NONE;
3065 
3066 	/*
3067 	 * In the slowpath, we sanity check order to avoid ever trying to
3068 	 * reclaim >= MAX_ORDER areas which will never succeed. Callers may
3069 	 * be using allocators in order of preference for an area that is
3070 	 * too large.
3071 	 */
3072 	if (order >= MAX_ORDER) {
3073 		WARN_ON_ONCE(!(gfp_mask & __GFP_NOWARN));
3074 		return NULL;
3075 	}
3076 
3077 	/*
3078 	 * We also sanity check to catch abuse of atomic reserves being used by
3079 	 * callers that are not in atomic context.
3080 	 */
3081 	if (WARN_ON_ONCE((gfp_mask & (__GFP_ATOMIC|__GFP_DIRECT_RECLAIM)) ==
3082 				(__GFP_ATOMIC|__GFP_DIRECT_RECLAIM)))
3083 		gfp_mask &= ~__GFP_ATOMIC;
3084 
3085 	/*
3086 	 * If this allocation cannot block and it is for a specific node, then
3087 	 * fail early.  There's no need to wakeup kswapd or retry for a
3088 	 * speculative node-specific allocation.
3089 	 */
3090 	if (IS_ENABLED(CONFIG_NUMA) && (gfp_mask & __GFP_THISNODE) && !can_direct_reclaim)
3091 		goto nopage;
3092 
3093 retry:
3094 	if (gfp_mask & __GFP_KSWAPD_RECLAIM)
3095 		wake_all_kswapds(order, ac);
3096 
3097 	/*
3098 	 * OK, we're below the kswapd watermark and have kicked background
3099 	 * reclaim. Now things get more complex, so set up alloc_flags according
3100 	 * to how we want to proceed.
3101 	 */
3102 	alloc_flags = gfp_to_alloc_flags(gfp_mask);
3103 
3104 	/*
3105 	 * Find the true preferred zone if the allocation is unconstrained by
3106 	 * cpusets.
3107 	 */
3108 	if (!(alloc_flags & ALLOC_CPUSET) && !ac->nodemask) {
3109 		struct zoneref *preferred_zoneref;
3110 		preferred_zoneref = first_zones_zonelist(ac->zonelist,
3111 				ac->high_zoneidx, NULL, &ac->preferred_zone);
3112 		ac->classzone_idx = zonelist_zone_idx(preferred_zoneref);
3113 	}
3114 
3115 	/* This is the last chance, in general, before the goto nopage. */
3116 	page = get_page_from_freelist(gfp_mask, order,
3117 				alloc_flags & ~ALLOC_NO_WATERMARKS, ac);
3118 	if (page)
3119 		goto got_pg;
3120 
3121 	/* Allocate without watermarks if the context allows */
3122 	if (alloc_flags & ALLOC_NO_WATERMARKS) {
3123 		/*
3124 		 * Ignore mempolicies if ALLOC_NO_WATERMARKS on the grounds
3125 		 * the allocation is high priority and these type of
3126 		 * allocations are system rather than user orientated
3127 		 */
3128 		page = __alloc_pages_high_priority(gfp_mask, order, ac);
3129 
3130 		if (page) {
3131 			goto got_pg;
3132 		}
3133 	}
3134 
3135 	/* Caller is not willing to reclaim, we can't balance anything */
3136 	if (!can_direct_reclaim) {
3137 		/*
3138 		 * All existing users of the deprecated __GFP_NOFAIL are
3139 		 * blockable, so warn of any new users that actually allow this
3140 		 * type of allocation to fail.
3141 		 */
3142 		WARN_ON_ONCE(gfp_mask & __GFP_NOFAIL);
3143 		goto nopage;
3144 	}
3145 
3146 	/* Avoid recursion of direct reclaim */
3147 	if (current->flags & PF_MEMALLOC)
3148 		goto nopage;
3149 
3150 	/* Avoid allocations with no watermarks from looping endlessly */
3151 	if (test_thread_flag(TIF_MEMDIE) && !(gfp_mask & __GFP_NOFAIL))
3152 		goto nopage;
3153 
3154 	/*
3155 	 * Try direct compaction. The first pass is asynchronous. Subsequent
3156 	 * attempts after direct reclaim are synchronous
3157 	 */
3158 	page = __alloc_pages_direct_compact(gfp_mask, order, alloc_flags, ac,
3159 					migration_mode,
3160 					&contended_compaction,
3161 					&deferred_compaction);
3162 	if (page)
3163 		goto got_pg;
3164 
3165 	/* Checks for THP-specific high-order allocations */
3166 	if (is_thp_gfp_mask(gfp_mask)) {
3167 		/*
3168 		 * If compaction is deferred for high-order allocations, it is
3169 		 * because sync compaction recently failed. If this is the case
3170 		 * and the caller requested a THP allocation, we do not want
3171 		 * to heavily disrupt the system, so we fail the allocation
3172 		 * instead of entering direct reclaim.
3173 		 */
3174 		if (deferred_compaction)
3175 			goto nopage;
3176 
3177 		/*
3178 		 * In all zones where compaction was attempted (and not
3179 		 * deferred or skipped), lock contention has been detected.
3180 		 * For THP allocation we do not want to disrupt the others
3181 		 * so we fallback to base pages instead.
3182 		 */
3183 		if (contended_compaction == COMPACT_CONTENDED_LOCK)
3184 			goto nopage;
3185 
3186 		/*
3187 		 * If compaction was aborted due to need_resched(), we do not
3188 		 * want to further increase allocation latency, unless it is
3189 		 * khugepaged trying to collapse.
3190 		 */
3191 		if (contended_compaction == COMPACT_CONTENDED_SCHED
3192 			&& !(current->flags & PF_KTHREAD))
3193 			goto nopage;
3194 	}
3195 
3196 	/*
3197 	 * It can become very expensive to allocate transparent hugepages at
3198 	 * fault, so use asynchronous memory compaction for THP unless it is
3199 	 * khugepaged trying to collapse.
3200 	 */
3201 	if (!is_thp_gfp_mask(gfp_mask) || (current->flags & PF_KTHREAD))
3202 		migration_mode = MIGRATE_SYNC_LIGHT;
3203 
3204 	/* Try direct reclaim and then allocating */
3205 	page = __alloc_pages_direct_reclaim(gfp_mask, order, alloc_flags, ac,
3206 							&did_some_progress);
3207 	if (page)
3208 		goto got_pg;
3209 
3210 	/* Do not loop if specifically requested */
3211 	if (gfp_mask & __GFP_NORETRY)
3212 		goto noretry;
3213 
3214 	/* Keep reclaiming pages as long as there is reasonable progress */
3215 	pages_reclaimed += did_some_progress;
3216 	if ((did_some_progress && order <= PAGE_ALLOC_COSTLY_ORDER) ||
3217 	    ((gfp_mask & __GFP_REPEAT) && pages_reclaimed < (1 << order))) {
3218 		/* Wait for some write requests to complete then retry */
3219 		wait_iff_congested(ac->preferred_zone, BLK_RW_ASYNC, HZ/50);
3220 		goto retry;
3221 	}
3222 
3223 	/* Reclaim has failed us, start killing things */
3224 	page = __alloc_pages_may_oom(gfp_mask, order, ac, &did_some_progress);
3225 	if (page)
3226 		goto got_pg;
3227 
3228 	/* Retry as long as the OOM killer is making progress */
3229 	if (did_some_progress)
3230 		goto retry;
3231 
3232 noretry:
3233 	/*
3234 	 * High-order allocations do not necessarily loop after
3235 	 * direct reclaim and reclaim/compaction depends on compaction
3236 	 * being called after reclaim so call directly if necessary
3237 	 */
3238 	page = __alloc_pages_direct_compact(gfp_mask, order, alloc_flags,
3239 					    ac, migration_mode,
3240 					    &contended_compaction,
3241 					    &deferred_compaction);
3242 	if (page)
3243 		goto got_pg;
3244 nopage:
3245 	warn_alloc_failed(gfp_mask, order, NULL);
3246 got_pg:
3247 	return page;
3248 }
3249 
3250 /*
3251  * This is the 'heart' of the zoned buddy allocator.
3252  */
3253 struct page *
__alloc_pages_nodemask(gfp_t gfp_mask,unsigned int order,struct zonelist * zonelist,nodemask_t * nodemask)3254 __alloc_pages_nodemask(gfp_t gfp_mask, unsigned int order,
3255 			struct zonelist *zonelist, nodemask_t *nodemask)
3256 {
3257 	struct zoneref *preferred_zoneref;
3258 	struct page *page = NULL;
3259 	unsigned int cpuset_mems_cookie;
3260 	int alloc_flags = ALLOC_WMARK_LOW|ALLOC_CPUSET|ALLOC_FAIR;
3261 	gfp_t alloc_mask; /* The gfp_t that was actually used for allocation */
3262 	struct alloc_context ac = {
3263 		.high_zoneidx = gfp_zone(gfp_mask),
3264 		.nodemask = nodemask,
3265 		.migratetype = gfpflags_to_migratetype(gfp_mask),
3266 	};
3267 
3268 	gfp_mask &= gfp_allowed_mask;
3269 
3270 	lockdep_trace_alloc(gfp_mask);
3271 
3272 	might_sleep_if(gfp_mask & __GFP_DIRECT_RECLAIM);
3273 
3274 	if (should_fail_alloc_page(gfp_mask, order))
3275 		return NULL;
3276 
3277 	/*
3278 	 * Check the zones suitable for the gfp_mask contain at least one
3279 	 * valid zone. It's possible to have an empty zonelist as a result
3280 	 * of __GFP_THISNODE and a memoryless node
3281 	 */
3282 	if (unlikely(!zonelist->_zonerefs->zone))
3283 		return NULL;
3284 
3285 	if (IS_ENABLED(CONFIG_CMA) && ac.migratetype == MIGRATE_MOVABLE)
3286 		alloc_flags |= ALLOC_CMA;
3287 
3288 retry_cpuset:
3289 	cpuset_mems_cookie = read_mems_allowed_begin();
3290 
3291 	/* We set it here, as __alloc_pages_slowpath might have changed it */
3292 	ac.zonelist = zonelist;
3293 
3294 	/* Dirty zone balancing only done in the fast path */
3295 	ac.spread_dirty_pages = (gfp_mask & __GFP_WRITE);
3296 
3297 	/* The preferred zone is used for statistics later */
3298 	preferred_zoneref = first_zones_zonelist(ac.zonelist, ac.high_zoneidx,
3299 				ac.nodemask ? : &cpuset_current_mems_allowed,
3300 				&ac.preferred_zone);
3301 	if (!ac.preferred_zone)
3302 		goto out;
3303 	ac.classzone_idx = zonelist_zone_idx(preferred_zoneref);
3304 
3305 	/* First allocation attempt */
3306 	alloc_mask = gfp_mask|__GFP_HARDWALL;
3307 	page = get_page_from_freelist(alloc_mask, order, alloc_flags, &ac);
3308 	if (unlikely(!page)) {
3309 		/*
3310 		 * Runtime PM, block IO and its error handling path
3311 		 * can deadlock because I/O on the device might not
3312 		 * complete.
3313 		 */
3314 		alloc_mask = memalloc_noio_flags(gfp_mask);
3315 		ac.spread_dirty_pages = false;
3316 
3317 		page = __alloc_pages_slowpath(alloc_mask, order, &ac);
3318 	}
3319 
3320 	if (kmemcheck_enabled && page)
3321 		kmemcheck_pagealloc_alloc(page, order, gfp_mask);
3322 
3323 	trace_mm_page_alloc(page, order, alloc_mask, ac.migratetype);
3324 
3325 out:
3326 	/*
3327 	 * When updating a task's mems_allowed, it is possible to race with
3328 	 * parallel threads in such a way that an allocation can fail while
3329 	 * the mask is being updated. If a page allocation is about to fail,
3330 	 * check if the cpuset changed during allocation and if so, retry.
3331 	 */
3332 	if (unlikely(!page && read_mems_allowed_retry(cpuset_mems_cookie)))
3333 		goto retry_cpuset;
3334 
3335 	return page;
3336 }
3337 EXPORT_SYMBOL(__alloc_pages_nodemask);
3338 
3339 /*
3340  * Common helper functions.
3341  */
__get_free_pages(gfp_t gfp_mask,unsigned int order)3342 unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order)
3343 {
3344 	struct page *page;
3345 
3346 	/*
3347 	 * __get_free_pages() returns a 32-bit address, which cannot represent
3348 	 * a highmem page
3349 	 */
3350 	VM_BUG_ON((gfp_mask & __GFP_HIGHMEM) != 0);
3351 
3352 	page = alloc_pages(gfp_mask, order);
3353 	if (!page)
3354 		return 0;
3355 	return (unsigned long) page_address(page);
3356 }
3357 EXPORT_SYMBOL(__get_free_pages);
3358 
get_zeroed_page(gfp_t gfp_mask)3359 unsigned long get_zeroed_page(gfp_t gfp_mask)
3360 {
3361 	return __get_free_pages(gfp_mask | __GFP_ZERO, 0);
3362 }
3363 EXPORT_SYMBOL(get_zeroed_page);
3364 
__free_pages(struct page * page,unsigned int order)3365 void __free_pages(struct page *page, unsigned int order)
3366 {
3367 	if (put_page_testzero(page)) {
3368 		if (order == 0)
3369 			free_hot_cold_page(page, false);
3370 		else
3371 			__free_pages_ok(page, order);
3372 	}
3373 }
3374 
3375 EXPORT_SYMBOL(__free_pages);
3376 
free_pages(unsigned long addr,unsigned int order)3377 void free_pages(unsigned long addr, unsigned int order)
3378 {
3379 	if (addr != 0) {
3380 		VM_BUG_ON(!virt_addr_valid((void *)addr));
3381 		__free_pages(virt_to_page((void *)addr), order);
3382 	}
3383 }
3384 
3385 EXPORT_SYMBOL(free_pages);
3386 
3387 /*
3388  * Page Fragment:
3389  *  An arbitrary-length arbitrary-offset area of memory which resides
3390  *  within a 0 or higher order page.  Multiple fragments within that page
3391  *  are individually refcounted, in the page's reference counter.
3392  *
3393  * The page_frag functions below provide a simple allocation framework for
3394  * page fragments.  This is used by the network stack and network device
3395  * drivers to provide a backing region of memory for use as either an
3396  * sk_buff->head, or to be used in the "frags" portion of skb_shared_info.
3397  */
__page_frag_refill(struct page_frag_cache * nc,gfp_t gfp_mask)3398 static struct page *__page_frag_refill(struct page_frag_cache *nc,
3399 				       gfp_t gfp_mask)
3400 {
3401 	struct page *page = NULL;
3402 	gfp_t gfp = gfp_mask;
3403 
3404 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
3405 	gfp_mask |= __GFP_COMP | __GFP_NOWARN | __GFP_NORETRY |
3406 		    __GFP_NOMEMALLOC;
3407 	page = alloc_pages_node(NUMA_NO_NODE, gfp_mask,
3408 				PAGE_FRAG_CACHE_MAX_ORDER);
3409 	nc->size = page ? PAGE_FRAG_CACHE_MAX_SIZE : PAGE_SIZE;
3410 #endif
3411 	if (unlikely(!page))
3412 		page = alloc_pages_node(NUMA_NO_NODE, gfp, 0);
3413 
3414 	nc->va = page ? page_address(page) : NULL;
3415 
3416 	return page;
3417 }
3418 
__alloc_page_frag(struct page_frag_cache * nc,unsigned int fragsz,gfp_t gfp_mask)3419 void *__alloc_page_frag(struct page_frag_cache *nc,
3420 			unsigned int fragsz, gfp_t gfp_mask)
3421 {
3422 	unsigned int size = PAGE_SIZE;
3423 	struct page *page;
3424 	int offset;
3425 
3426 	if (unlikely(!nc->va)) {
3427 refill:
3428 		page = __page_frag_refill(nc, gfp_mask);
3429 		if (!page)
3430 			return NULL;
3431 
3432 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
3433 		/* if size can vary use size else just use PAGE_SIZE */
3434 		size = nc->size;
3435 #endif
3436 		/* Even if we own the page, we do not use atomic_set().
3437 		 * This would break get_page_unless_zero() users.
3438 		 */
3439 		atomic_add(size - 1, &page->_count);
3440 
3441 		/* reset page count bias and offset to start of new frag */
3442 		nc->pfmemalloc = page_is_pfmemalloc(page);
3443 		nc->pagecnt_bias = size;
3444 		nc->offset = size;
3445 	}
3446 
3447 	offset = nc->offset - fragsz;
3448 	if (unlikely(offset < 0)) {
3449 		page = virt_to_page(nc->va);
3450 
3451 		if (!atomic_sub_and_test(nc->pagecnt_bias, &page->_count))
3452 			goto refill;
3453 
3454 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
3455 		/* if size can vary use size else just use PAGE_SIZE */
3456 		size = nc->size;
3457 #endif
3458 		/* OK, page count is 0, we can safely set it */
3459 		atomic_set(&page->_count, size);
3460 
3461 		/* reset page count bias and offset to start of new frag */
3462 		nc->pagecnt_bias = size;
3463 		offset = size - fragsz;
3464 	}
3465 
3466 	nc->pagecnt_bias--;
3467 	nc->offset = offset;
3468 
3469 	return nc->va + offset;
3470 }
3471 EXPORT_SYMBOL(__alloc_page_frag);
3472 
3473 /*
3474  * Frees a page fragment allocated out of either a compound or order 0 page.
3475  */
__free_page_frag(void * addr)3476 void __free_page_frag(void *addr)
3477 {
3478 	struct page *page = virt_to_head_page(addr);
3479 
3480 	if (unlikely(put_page_testzero(page)))
3481 		__free_pages_ok(page, compound_order(page));
3482 }
3483 EXPORT_SYMBOL(__free_page_frag);
3484 
3485 /*
3486  * alloc_kmem_pages charges newly allocated pages to the kmem resource counter
3487  * of the current memory cgroup.
3488  *
3489  * It should be used when the caller would like to use kmalloc, but since the
3490  * allocation is large, it has to fall back to the page allocator.
3491  */
alloc_kmem_pages(gfp_t gfp_mask,unsigned int order)3492 struct page *alloc_kmem_pages(gfp_t gfp_mask, unsigned int order)
3493 {
3494 	struct page *page;
3495 
3496 	page = alloc_pages(gfp_mask, order);
3497 	if (page && memcg_kmem_charge(page, gfp_mask, order) != 0) {
3498 		__free_pages(page, order);
3499 		page = NULL;
3500 	}
3501 	return page;
3502 }
3503 
alloc_kmem_pages_node(int nid,gfp_t gfp_mask,unsigned int order)3504 struct page *alloc_kmem_pages_node(int nid, gfp_t gfp_mask, unsigned int order)
3505 {
3506 	struct page *page;
3507 
3508 	page = alloc_pages_node(nid, gfp_mask, order);
3509 	if (page && memcg_kmem_charge(page, gfp_mask, order) != 0) {
3510 		__free_pages(page, order);
3511 		page = NULL;
3512 	}
3513 	return page;
3514 }
3515 
3516 /*
3517  * __free_kmem_pages and free_kmem_pages will free pages allocated with
3518  * alloc_kmem_pages.
3519  */
__free_kmem_pages(struct page * page,unsigned int order)3520 void __free_kmem_pages(struct page *page, unsigned int order)
3521 {
3522 	memcg_kmem_uncharge(page, order);
3523 	__free_pages(page, order);
3524 }
3525 
free_kmem_pages(unsigned long addr,unsigned int order)3526 void free_kmem_pages(unsigned long addr, unsigned int order)
3527 {
3528 	if (addr != 0) {
3529 		VM_BUG_ON(!virt_addr_valid((void *)addr));
3530 		__free_kmem_pages(virt_to_page((void *)addr), order);
3531 	}
3532 }
3533 
make_alloc_exact(unsigned long addr,unsigned int order,size_t size)3534 static void *make_alloc_exact(unsigned long addr, unsigned int order,
3535 		size_t size)
3536 {
3537 	if (addr) {
3538 		unsigned long alloc_end = addr + (PAGE_SIZE << order);
3539 		unsigned long used = addr + PAGE_ALIGN(size);
3540 
3541 		split_page(virt_to_page((void *)addr), order);
3542 		while (used < alloc_end) {
3543 			free_page(used);
3544 			used += PAGE_SIZE;
3545 		}
3546 	}
3547 	return (void *)addr;
3548 }
3549 
3550 /**
3551  * alloc_pages_exact - allocate an exact number physically-contiguous pages.
3552  * @size: the number of bytes to allocate
3553  * @gfp_mask: GFP flags for the allocation
3554  *
3555  * This function is similar to alloc_pages(), except that it allocates the
3556  * minimum number of pages to satisfy the request.  alloc_pages() can only
3557  * allocate memory in power-of-two pages.
3558  *
3559  * This function is also limited by MAX_ORDER.
3560  *
3561  * Memory allocated by this function must be released by free_pages_exact().
3562  */
alloc_pages_exact(size_t size,gfp_t gfp_mask)3563 void *alloc_pages_exact(size_t size, gfp_t gfp_mask)
3564 {
3565 	unsigned int order = get_order(size);
3566 	unsigned long addr;
3567 
3568 	addr = __get_free_pages(gfp_mask, order);
3569 	return make_alloc_exact(addr, order, size);
3570 }
3571 EXPORT_SYMBOL(alloc_pages_exact);
3572 
3573 /**
3574  * alloc_pages_exact_nid - allocate an exact number of physically-contiguous
3575  *			   pages on a node.
3576  * @nid: the preferred node ID where memory should be allocated
3577  * @size: the number of bytes to allocate
3578  * @gfp_mask: GFP flags for the allocation
3579  *
3580  * Like alloc_pages_exact(), but try to allocate on node nid first before falling
3581  * back.
3582  */
alloc_pages_exact_nid(int nid,size_t size,gfp_t gfp_mask)3583 void * __meminit alloc_pages_exact_nid(int nid, size_t size, gfp_t gfp_mask)
3584 {
3585 	unsigned int order = get_order(size);
3586 	struct page *p = alloc_pages_node(nid, gfp_mask, order);
3587 	if (!p)
3588 		return NULL;
3589 	return make_alloc_exact((unsigned long)page_address(p), order, size);
3590 }
3591 
3592 /**
3593  * free_pages_exact - release memory allocated via alloc_pages_exact()
3594  * @virt: the value returned by alloc_pages_exact.
3595  * @size: size of allocation, same value as passed to alloc_pages_exact().
3596  *
3597  * Release the memory allocated by a previous call to alloc_pages_exact.
3598  */
free_pages_exact(void * virt,size_t size)3599 void free_pages_exact(void *virt, size_t size)
3600 {
3601 	unsigned long addr = (unsigned long)virt;
3602 	unsigned long end = addr + PAGE_ALIGN(size);
3603 
3604 	while (addr < end) {
3605 		free_page(addr);
3606 		addr += PAGE_SIZE;
3607 	}
3608 }
3609 EXPORT_SYMBOL(free_pages_exact);
3610 
3611 /**
3612  * nr_free_zone_pages - count number of pages beyond high watermark
3613  * @offset: The zone index of the highest zone
3614  *
3615  * nr_free_zone_pages() counts the number of counts pages which are beyond the
3616  * high watermark within all zones at or below a given zone index.  For each
3617  * zone, the number of pages is calculated as:
3618  *     managed_pages - high_pages
3619  */
nr_free_zone_pages(int offset)3620 static unsigned long nr_free_zone_pages(int offset)
3621 {
3622 	struct zoneref *z;
3623 	struct zone *zone;
3624 
3625 	/* Just pick one node, since fallback list is circular */
3626 	unsigned long sum = 0;
3627 
3628 	struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL);
3629 
3630 	for_each_zone_zonelist(zone, z, zonelist, offset) {
3631 		unsigned long size = zone->managed_pages;
3632 		unsigned long high = high_wmark_pages(zone);
3633 		if (size > high)
3634 			sum += size - high;
3635 	}
3636 
3637 	return sum;
3638 }
3639 
3640 /**
3641  * nr_free_buffer_pages - count number of pages beyond high watermark
3642  *
3643  * nr_free_buffer_pages() counts the number of pages which are beyond the high
3644  * watermark within ZONE_DMA and ZONE_NORMAL.
3645  */
nr_free_buffer_pages(void)3646 unsigned long nr_free_buffer_pages(void)
3647 {
3648 	return nr_free_zone_pages(gfp_zone(GFP_USER));
3649 }
3650 EXPORT_SYMBOL_GPL(nr_free_buffer_pages);
3651 
3652 /**
3653  * nr_free_pagecache_pages - count number of pages beyond high watermark
3654  *
3655  * nr_free_pagecache_pages() counts the number of pages which are beyond the
3656  * high watermark within all zones.
3657  */
nr_free_pagecache_pages(void)3658 unsigned long nr_free_pagecache_pages(void)
3659 {
3660 	return nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE));
3661 }
3662 
show_node(struct zone * zone)3663 static inline void show_node(struct zone *zone)
3664 {
3665 	if (IS_ENABLED(CONFIG_NUMA))
3666 		printk("Node %d ", zone_to_nid(zone));
3667 }
3668 
si_mem_available(void)3669 long si_mem_available(void)
3670 {
3671 	long available;
3672 	unsigned long pagecache;
3673 	unsigned long wmark_low = 0;
3674 	unsigned long pages[NR_LRU_LISTS];
3675 	struct zone *zone;
3676 	int lru;
3677 
3678 	for (lru = LRU_BASE; lru < NR_LRU_LISTS; lru++)
3679 		pages[lru] = global_page_state(NR_LRU_BASE + lru);
3680 
3681 	for_each_zone(zone)
3682 		wmark_low += zone->watermark[WMARK_LOW];
3683 
3684 	/*
3685 	 * Estimate the amount of memory available for userspace allocations,
3686 	 * without causing swapping.
3687 	 */
3688 	available = global_page_state(NR_FREE_PAGES) - totalreserve_pages;
3689 
3690 	/*
3691 	 * Not all the page cache can be freed, otherwise the system will
3692 	 * start swapping. Assume at least half of the page cache, or the
3693 	 * low watermark worth of cache, needs to stay.
3694 	 */
3695 	pagecache = pages[LRU_ACTIVE_FILE] + pages[LRU_INACTIVE_FILE];
3696 	pagecache -= min(pagecache / 2, wmark_low);
3697 	available += pagecache;
3698 
3699 	/*
3700 	 * Part of the reclaimable slab consists of items that are in use,
3701 	 * and cannot be freed. Cap this estimate at the low watermark.
3702 	 */
3703 	available += global_page_state(NR_SLAB_RECLAIMABLE) -
3704 		     min(global_page_state(NR_SLAB_RECLAIMABLE) / 2, wmark_low);
3705 
3706 	if (available < 0)
3707 		available = 0;
3708 	return available;
3709 }
3710 EXPORT_SYMBOL_GPL(si_mem_available);
3711 
si_meminfo(struct sysinfo * val)3712 void si_meminfo(struct sysinfo *val)
3713 {
3714 	val->totalram = totalram_pages;
3715 	val->sharedram = global_page_state(NR_SHMEM);
3716 	val->freeram = global_page_state(NR_FREE_PAGES);
3717 	val->bufferram = nr_blockdev_pages();
3718 	val->totalhigh = totalhigh_pages;
3719 	val->freehigh = nr_free_highpages();
3720 	val->mem_unit = PAGE_SIZE;
3721 }
3722 
3723 EXPORT_SYMBOL(si_meminfo);
3724 
3725 #ifdef CONFIG_NUMA
si_meminfo_node(struct sysinfo * val,int nid)3726 void si_meminfo_node(struct sysinfo *val, int nid)
3727 {
3728 	int zone_type;		/* needs to be signed */
3729 	unsigned long managed_pages = 0;
3730 	pg_data_t *pgdat = NODE_DATA(nid);
3731 
3732 	for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++)
3733 		managed_pages += pgdat->node_zones[zone_type].managed_pages;
3734 	val->totalram = managed_pages;
3735 	val->sharedram = node_page_state(nid, NR_SHMEM);
3736 	val->freeram = node_page_state(nid, NR_FREE_PAGES);
3737 #ifdef CONFIG_HIGHMEM
3738 	val->totalhigh = pgdat->node_zones[ZONE_HIGHMEM].managed_pages;
3739 	val->freehigh = zone_page_state(&pgdat->node_zones[ZONE_HIGHMEM],
3740 			NR_FREE_PAGES);
3741 #else
3742 	val->totalhigh = 0;
3743 	val->freehigh = 0;
3744 #endif
3745 	val->mem_unit = PAGE_SIZE;
3746 }
3747 #endif
3748 
3749 /*
3750  * Determine whether the node should be displayed or not, depending on whether
3751  * SHOW_MEM_FILTER_NODES was passed to show_free_areas().
3752  */
skip_free_areas_node(unsigned int flags,int nid)3753 bool skip_free_areas_node(unsigned int flags, int nid)
3754 {
3755 	bool ret = false;
3756 	unsigned int cpuset_mems_cookie;
3757 
3758 	if (!(flags & SHOW_MEM_FILTER_NODES))
3759 		goto out;
3760 
3761 	do {
3762 		cpuset_mems_cookie = read_mems_allowed_begin();
3763 		ret = !node_isset(nid, cpuset_current_mems_allowed);
3764 	} while (read_mems_allowed_retry(cpuset_mems_cookie));
3765 out:
3766 	return ret;
3767 }
3768 
3769 #define K(x) ((x) << (PAGE_SHIFT-10))
3770 
show_migration_types(unsigned char type)3771 static void show_migration_types(unsigned char type)
3772 {
3773 	static const char types[MIGRATE_TYPES] = {
3774 		[MIGRATE_UNMOVABLE]	= 'U',
3775 		[MIGRATE_MOVABLE]	= 'M',
3776 		[MIGRATE_RECLAIMABLE]	= 'E',
3777 		[MIGRATE_HIGHATOMIC]	= 'H',
3778 #ifdef CONFIG_CMA
3779 		[MIGRATE_CMA]		= 'C',
3780 #endif
3781 #ifdef CONFIG_MEMORY_ISOLATION
3782 		[MIGRATE_ISOLATE]	= 'I',
3783 #endif
3784 	};
3785 	char tmp[MIGRATE_TYPES + 1];
3786 	char *p = tmp;
3787 	int i;
3788 
3789 	for (i = 0; i < MIGRATE_TYPES; i++) {
3790 		if (type & (1 << i))
3791 			*p++ = types[i];
3792 	}
3793 
3794 	*p = '\0';
3795 	printk("(%s) ", tmp);
3796 }
3797 
3798 /*
3799  * Show free area list (used inside shift_scroll-lock stuff)
3800  * We also calculate the percentage fragmentation. We do this by counting the
3801  * memory on each free list with the exception of the first item on the list.
3802  *
3803  * Bits in @filter:
3804  * SHOW_MEM_FILTER_NODES: suppress nodes that are not allowed by current's
3805  *   cpuset.
3806  */
show_free_areas(unsigned int filter)3807 void show_free_areas(unsigned int filter)
3808 {
3809 	unsigned long free_pcp = 0;
3810 	int cpu;
3811 	struct zone *zone;
3812 
3813 	for_each_populated_zone(zone) {
3814 		if (skip_free_areas_node(filter, zone_to_nid(zone)))
3815 			continue;
3816 
3817 		for_each_online_cpu(cpu)
3818 			free_pcp += per_cpu_ptr(zone->pageset, cpu)->pcp.count;
3819 	}
3820 
3821 	printk("active_anon:%lu inactive_anon:%lu isolated_anon:%lu\n"
3822 		" active_file:%lu inactive_file:%lu isolated_file:%lu\n"
3823 		" unevictable:%lu dirty:%lu writeback:%lu unstable:%lu\n"
3824 		" slab_reclaimable:%lu slab_unreclaimable:%lu\n"
3825 		" mapped:%lu shmem:%lu pagetables:%lu bounce:%lu\n"
3826 		" free:%lu free_pcp:%lu free_cma:%lu\n",
3827 		global_page_state(NR_ACTIVE_ANON),
3828 		global_page_state(NR_INACTIVE_ANON),
3829 		global_page_state(NR_ISOLATED_ANON),
3830 		global_page_state(NR_ACTIVE_FILE),
3831 		global_page_state(NR_INACTIVE_FILE),
3832 		global_page_state(NR_ISOLATED_FILE),
3833 		global_page_state(NR_UNEVICTABLE),
3834 		global_page_state(NR_FILE_DIRTY),
3835 		global_page_state(NR_WRITEBACK),
3836 		global_page_state(NR_UNSTABLE_NFS),
3837 		global_page_state(NR_SLAB_RECLAIMABLE),
3838 		global_page_state(NR_SLAB_UNRECLAIMABLE),
3839 		global_page_state(NR_FILE_MAPPED),
3840 		global_page_state(NR_SHMEM),
3841 		global_page_state(NR_PAGETABLE),
3842 		global_page_state(NR_BOUNCE),
3843 		global_page_state(NR_FREE_PAGES),
3844 		free_pcp,
3845 		global_page_state(NR_FREE_CMA_PAGES));
3846 
3847 	for_each_populated_zone(zone) {
3848 		int i;
3849 
3850 		if (skip_free_areas_node(filter, zone_to_nid(zone)))
3851 			continue;
3852 
3853 		free_pcp = 0;
3854 		for_each_online_cpu(cpu)
3855 			free_pcp += per_cpu_ptr(zone->pageset, cpu)->pcp.count;
3856 
3857 		show_node(zone);
3858 		printk("%s"
3859 			" free:%lukB"
3860 			" min:%lukB"
3861 			" low:%lukB"
3862 			" high:%lukB"
3863 			" active_anon:%lukB"
3864 			" inactive_anon:%lukB"
3865 			" active_file:%lukB"
3866 			" inactive_file:%lukB"
3867 			" unevictable:%lukB"
3868 			" isolated(anon):%lukB"
3869 			" isolated(file):%lukB"
3870 			" present:%lukB"
3871 			" managed:%lukB"
3872 			" mlocked:%lukB"
3873 			" dirty:%lukB"
3874 			" writeback:%lukB"
3875 			" mapped:%lukB"
3876 			" shmem:%lukB"
3877 			" slab_reclaimable:%lukB"
3878 			" slab_unreclaimable:%lukB"
3879 			" kernel_stack:%lukB"
3880 			" pagetables:%lukB"
3881 			" unstable:%lukB"
3882 			" bounce:%lukB"
3883 			" free_pcp:%lukB"
3884 			" local_pcp:%ukB"
3885 			" free_cma:%lukB"
3886 			" writeback_tmp:%lukB"
3887 			" pages_scanned:%lu"
3888 			" all_unreclaimable? %s"
3889 			"\n",
3890 			zone->name,
3891 			K(zone_page_state(zone, NR_FREE_PAGES)),
3892 			K(min_wmark_pages(zone)),
3893 			K(low_wmark_pages(zone)),
3894 			K(high_wmark_pages(zone)),
3895 			K(zone_page_state(zone, NR_ACTIVE_ANON)),
3896 			K(zone_page_state(zone, NR_INACTIVE_ANON)),
3897 			K(zone_page_state(zone, NR_ACTIVE_FILE)),
3898 			K(zone_page_state(zone, NR_INACTIVE_FILE)),
3899 			K(zone_page_state(zone, NR_UNEVICTABLE)),
3900 			K(zone_page_state(zone, NR_ISOLATED_ANON)),
3901 			K(zone_page_state(zone, NR_ISOLATED_FILE)),
3902 			K(zone->present_pages),
3903 			K(zone->managed_pages),
3904 			K(zone_page_state(zone, NR_MLOCK)),
3905 			K(zone_page_state(zone, NR_FILE_DIRTY)),
3906 			K(zone_page_state(zone, NR_WRITEBACK)),
3907 			K(zone_page_state(zone, NR_FILE_MAPPED)),
3908 			K(zone_page_state(zone, NR_SHMEM)),
3909 			K(zone_page_state(zone, NR_SLAB_RECLAIMABLE)),
3910 			K(zone_page_state(zone, NR_SLAB_UNRECLAIMABLE)),
3911 			zone_page_state(zone, NR_KERNEL_STACK) *
3912 				THREAD_SIZE / 1024,
3913 			K(zone_page_state(zone, NR_PAGETABLE)),
3914 			K(zone_page_state(zone, NR_UNSTABLE_NFS)),
3915 			K(zone_page_state(zone, NR_BOUNCE)),
3916 			K(free_pcp),
3917 			K(this_cpu_read(zone->pageset->pcp.count)),
3918 			K(zone_page_state(zone, NR_FREE_CMA_PAGES)),
3919 			K(zone_page_state(zone, NR_WRITEBACK_TEMP)),
3920 			K(zone_page_state(zone, NR_PAGES_SCANNED)),
3921 			(!zone_reclaimable(zone) ? "yes" : "no")
3922 			);
3923 		printk("lowmem_reserve[]:");
3924 		for (i = 0; i < MAX_NR_ZONES; i++)
3925 			printk(" %ld", zone->lowmem_reserve[i]);
3926 		printk("\n");
3927 	}
3928 
3929 	for_each_populated_zone(zone) {
3930 		unsigned int order;
3931 		unsigned long nr[MAX_ORDER], flags, total = 0;
3932 		unsigned char types[MAX_ORDER];
3933 
3934 		if (skip_free_areas_node(filter, zone_to_nid(zone)))
3935 			continue;
3936 		show_node(zone);
3937 		printk("%s: ", zone->name);
3938 
3939 		spin_lock_irqsave(&zone->lock, flags);
3940 		for (order = 0; order < MAX_ORDER; order++) {
3941 			struct free_area *area = &zone->free_area[order];
3942 			int type;
3943 
3944 			nr[order] = area->nr_free;
3945 			total += nr[order] << order;
3946 
3947 			types[order] = 0;
3948 			for (type = 0; type < MIGRATE_TYPES; type++) {
3949 				if (!list_empty(&area->free_list[type]))
3950 					types[order] |= 1 << type;
3951 			}
3952 		}
3953 		spin_unlock_irqrestore(&zone->lock, flags);
3954 		for (order = 0; order < MAX_ORDER; order++) {
3955 			printk("%lu*%lukB ", nr[order], K(1UL) << order);
3956 			if (nr[order])
3957 				show_migration_types(types[order]);
3958 		}
3959 		printk("= %lukB\n", K(total));
3960 	}
3961 
3962 	hugetlb_show_meminfo();
3963 
3964 	printk("%ld total pagecache pages\n", global_page_state(NR_FILE_PAGES));
3965 
3966 	show_swap_cache_info();
3967 }
3968 
zoneref_set_zone(struct zone * zone,struct zoneref * zoneref)3969 static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref)
3970 {
3971 	zoneref->zone = zone;
3972 	zoneref->zone_idx = zone_idx(zone);
3973 }
3974 
3975 /*
3976  * Builds allocation fallback zone lists.
3977  *
3978  * Add all populated zones of a node to the zonelist.
3979  */
build_zonelists_node(pg_data_t * pgdat,struct zonelist * zonelist,int nr_zones)3980 static int build_zonelists_node(pg_data_t *pgdat, struct zonelist *zonelist,
3981 				int nr_zones)
3982 {
3983 	struct zone *zone;
3984 	enum zone_type zone_type = MAX_NR_ZONES;
3985 
3986 	do {
3987 		zone_type--;
3988 		zone = pgdat->node_zones + zone_type;
3989 		if (populated_zone(zone)) {
3990 			zoneref_set_zone(zone,
3991 				&zonelist->_zonerefs[nr_zones++]);
3992 			check_highest_zone(zone_type);
3993 		}
3994 	} while (zone_type);
3995 
3996 	return nr_zones;
3997 }
3998 
3999 
4000 /*
4001  *  zonelist_order:
4002  *  0 = automatic detection of better ordering.
4003  *  1 = order by ([node] distance, -zonetype)
4004  *  2 = order by (-zonetype, [node] distance)
4005  *
4006  *  If not NUMA, ZONELIST_ORDER_ZONE and ZONELIST_ORDER_NODE will create
4007  *  the same zonelist. So only NUMA can configure this param.
4008  */
4009 #define ZONELIST_ORDER_DEFAULT  0
4010 #define ZONELIST_ORDER_NODE     1
4011 #define ZONELIST_ORDER_ZONE     2
4012 
4013 /* zonelist order in the kernel.
4014  * set_zonelist_order() will set this to NODE or ZONE.
4015  */
4016 static int current_zonelist_order = ZONELIST_ORDER_DEFAULT;
4017 static char zonelist_order_name[3][8] = {"Default", "Node", "Zone"};
4018 
4019 
4020 #ifdef CONFIG_NUMA
4021 /* The value user specified ....changed by config */
4022 static int user_zonelist_order = ZONELIST_ORDER_DEFAULT;
4023 /* string for sysctl */
4024 #define NUMA_ZONELIST_ORDER_LEN	16
4025 char numa_zonelist_order[16] = "default";
4026 
4027 /*
4028  * interface for configure zonelist ordering.
4029  * command line option "numa_zonelist_order"
4030  *	= "[dD]efault	- default, automatic configuration.
4031  *	= "[nN]ode 	- order by node locality, then by zone within node
4032  *	= "[zZ]one      - order by zone, then by locality within zone
4033  */
4034 
__parse_numa_zonelist_order(char * s)4035 static int __parse_numa_zonelist_order(char *s)
4036 {
4037 	if (*s == 'd' || *s == 'D') {
4038 		user_zonelist_order = ZONELIST_ORDER_DEFAULT;
4039 	} else if (*s == 'n' || *s == 'N') {
4040 		user_zonelist_order = ZONELIST_ORDER_NODE;
4041 	} else if (*s == 'z' || *s == 'Z') {
4042 		user_zonelist_order = ZONELIST_ORDER_ZONE;
4043 	} else {
4044 		printk(KERN_WARNING
4045 		       "Ignoring invalid numa_zonelist_order value:  %s\n", s);
4046 		return -EINVAL;
4047 	}
4048 	return 0;
4049 }
4050 
setup_numa_zonelist_order(char * s)4051 static __init int setup_numa_zonelist_order(char *s)
4052 {
4053 	int ret;
4054 
4055 	if (!s)
4056 		return 0;
4057 
4058 	ret = __parse_numa_zonelist_order(s);
4059 	if (ret == 0)
4060 		strlcpy(numa_zonelist_order, s, NUMA_ZONELIST_ORDER_LEN);
4061 
4062 	return ret;
4063 }
4064 early_param("numa_zonelist_order", setup_numa_zonelist_order);
4065 
4066 /*
4067  * sysctl handler for numa_zonelist_order
4068  */
numa_zonelist_order_handler(struct ctl_table * table,int write,void __user * buffer,size_t * length,loff_t * ppos)4069 int numa_zonelist_order_handler(struct ctl_table *table, int write,
4070 		void __user *buffer, size_t *length,
4071 		loff_t *ppos)
4072 {
4073 	char saved_string[NUMA_ZONELIST_ORDER_LEN];
4074 	int ret;
4075 	static DEFINE_MUTEX(zl_order_mutex);
4076 
4077 	mutex_lock(&zl_order_mutex);
4078 	if (write) {
4079 		if (strlen((char *)table->data) >= NUMA_ZONELIST_ORDER_LEN) {
4080 			ret = -EINVAL;
4081 			goto out;
4082 		}
4083 		strcpy(saved_string, (char *)table->data);
4084 	}
4085 	ret = proc_dostring(table, write, buffer, length, ppos);
4086 	if (ret)
4087 		goto out;
4088 	if (write) {
4089 		int oldval = user_zonelist_order;
4090 
4091 		ret = __parse_numa_zonelist_order((char *)table->data);
4092 		if (ret) {
4093 			/*
4094 			 * bogus value.  restore saved string
4095 			 */
4096 			strncpy((char *)table->data, saved_string,
4097 				NUMA_ZONELIST_ORDER_LEN);
4098 			user_zonelist_order = oldval;
4099 		} else if (oldval != user_zonelist_order) {
4100 			mutex_lock(&zonelists_mutex);
4101 			build_all_zonelists(NULL, NULL);
4102 			mutex_unlock(&zonelists_mutex);
4103 		}
4104 	}
4105 out:
4106 	mutex_unlock(&zl_order_mutex);
4107 	return ret;
4108 }
4109 
4110 
4111 #define MAX_NODE_LOAD (nr_online_nodes)
4112 static int node_load[MAX_NUMNODES];
4113 
4114 /**
4115  * find_next_best_node - find the next node that should appear in a given node's fallback list
4116  * @node: node whose fallback list we're appending
4117  * @used_node_mask: nodemask_t of already used nodes
4118  *
4119  * We use a number of factors to determine which is the next node that should
4120  * appear on a given node's fallback list.  The node should not have appeared
4121  * already in @node's fallback list, and it should be the next closest node
4122  * according to the distance array (which contains arbitrary distance values
4123  * from each node to each node in the system), and should also prefer nodes
4124  * with no CPUs, since presumably they'll have very little allocation pressure
4125  * on them otherwise.
4126  * It returns -1 if no node is found.
4127  */
find_next_best_node(int node,nodemask_t * used_node_mask)4128 static int find_next_best_node(int node, nodemask_t *used_node_mask)
4129 {
4130 	int n, val;
4131 	int min_val = INT_MAX;
4132 	int best_node = NUMA_NO_NODE;
4133 	const struct cpumask *tmp = cpumask_of_node(0);
4134 
4135 	/* Use the local node if we haven't already */
4136 	if (!node_isset(node, *used_node_mask)) {
4137 		node_set(node, *used_node_mask);
4138 		return node;
4139 	}
4140 
4141 	for_each_node_state(n, N_MEMORY) {
4142 
4143 		/* Don't want a node to appear more than once */
4144 		if (node_isset(n, *used_node_mask))
4145 			continue;
4146 
4147 		/* Use the distance array to find the distance */
4148 		val = node_distance(node, n);
4149 
4150 		/* Penalize nodes under us ("prefer the next node") */
4151 		val += (n < node);
4152 
4153 		/* Give preference to headless and unused nodes */
4154 		tmp = cpumask_of_node(n);
4155 		if (!cpumask_empty(tmp))
4156 			val += PENALTY_FOR_NODE_WITH_CPUS;
4157 
4158 		/* Slight preference for less loaded node */
4159 		val *= (MAX_NODE_LOAD*MAX_NUMNODES);
4160 		val += node_load[n];
4161 
4162 		if (val < min_val) {
4163 			min_val = val;
4164 			best_node = n;
4165 		}
4166 	}
4167 
4168 	if (best_node >= 0)
4169 		node_set(best_node, *used_node_mask);
4170 
4171 	return best_node;
4172 }
4173 
4174 
4175 /*
4176  * Build zonelists ordered by node and zones within node.
4177  * This results in maximum locality--normal zone overflows into local
4178  * DMA zone, if any--but risks exhausting DMA zone.
4179  */
build_zonelists_in_node_order(pg_data_t * pgdat,int node)4180 static void build_zonelists_in_node_order(pg_data_t *pgdat, int node)
4181 {
4182 	int j;
4183 	struct zonelist *zonelist;
4184 
4185 	zonelist = &pgdat->node_zonelists[0];
4186 	for (j = 0; zonelist->_zonerefs[j].zone != NULL; j++)
4187 		;
4188 	j = build_zonelists_node(NODE_DATA(node), zonelist, j);
4189 	zonelist->_zonerefs[j].zone = NULL;
4190 	zonelist->_zonerefs[j].zone_idx = 0;
4191 }
4192 
4193 /*
4194  * Build gfp_thisnode zonelists
4195  */
build_thisnode_zonelists(pg_data_t * pgdat)4196 static void build_thisnode_zonelists(pg_data_t *pgdat)
4197 {
4198 	int j;
4199 	struct zonelist *zonelist;
4200 
4201 	zonelist = &pgdat->node_zonelists[1];
4202 	j = build_zonelists_node(pgdat, zonelist, 0);
4203 	zonelist->_zonerefs[j].zone = NULL;
4204 	zonelist->_zonerefs[j].zone_idx = 0;
4205 }
4206 
4207 /*
4208  * Build zonelists ordered by zone and nodes within zones.
4209  * This results in conserving DMA zone[s] until all Normal memory is
4210  * exhausted, but results in overflowing to remote node while memory
4211  * may still exist in local DMA zone.
4212  */
4213 static int node_order[MAX_NUMNODES];
4214 
build_zonelists_in_zone_order(pg_data_t * pgdat,int nr_nodes)4215 static void build_zonelists_in_zone_order(pg_data_t *pgdat, int nr_nodes)
4216 {
4217 	int pos, j, node;
4218 	int zone_type;		/* needs to be signed */
4219 	struct zone *z;
4220 	struct zonelist *zonelist;
4221 
4222 	zonelist = &pgdat->node_zonelists[0];
4223 	pos = 0;
4224 	for (zone_type = MAX_NR_ZONES - 1; zone_type >= 0; zone_type--) {
4225 		for (j = 0; j < nr_nodes; j++) {
4226 			node = node_order[j];
4227 			z = &NODE_DATA(node)->node_zones[zone_type];
4228 			if (populated_zone(z)) {
4229 				zoneref_set_zone(z,
4230 					&zonelist->_zonerefs[pos++]);
4231 				check_highest_zone(zone_type);
4232 			}
4233 		}
4234 	}
4235 	zonelist->_zonerefs[pos].zone = NULL;
4236 	zonelist->_zonerefs[pos].zone_idx = 0;
4237 }
4238 
4239 #if defined(CONFIG_64BIT)
4240 /*
4241  * Devices that require DMA32/DMA are relatively rare and do not justify a
4242  * penalty to every machine in case the specialised case applies. Default
4243  * to Node-ordering on 64-bit NUMA machines
4244  */
default_zonelist_order(void)4245 static int default_zonelist_order(void)
4246 {
4247 	return ZONELIST_ORDER_NODE;
4248 }
4249 #else
4250 /*
4251  * On 32-bit, the Normal zone needs to be preserved for allocations accessible
4252  * by the kernel. If processes running on node 0 deplete the low memory zone
4253  * then reclaim will occur more frequency increasing stalls and potentially
4254  * be easier to OOM if a large percentage of the zone is under writeback or
4255  * dirty. The problem is significantly worse if CONFIG_HIGHPTE is not set.
4256  * Hence, default to zone ordering on 32-bit.
4257  */
default_zonelist_order(void)4258 static int default_zonelist_order(void)
4259 {
4260 	return ZONELIST_ORDER_ZONE;
4261 }
4262 #endif /* CONFIG_64BIT */
4263 
set_zonelist_order(void)4264 static void set_zonelist_order(void)
4265 {
4266 	if (user_zonelist_order == ZONELIST_ORDER_DEFAULT)
4267 		current_zonelist_order = default_zonelist_order();
4268 	else
4269 		current_zonelist_order = user_zonelist_order;
4270 }
4271 
build_zonelists(pg_data_t * pgdat)4272 static void build_zonelists(pg_data_t *pgdat)
4273 {
4274 	int j, node, load;
4275 	enum zone_type i;
4276 	nodemask_t used_mask;
4277 	int local_node, prev_node;
4278 	struct zonelist *zonelist;
4279 	unsigned int order = current_zonelist_order;
4280 
4281 	/* initialize zonelists */
4282 	for (i = 0; i < MAX_ZONELISTS; i++) {
4283 		zonelist = pgdat->node_zonelists + i;
4284 		zonelist->_zonerefs[0].zone = NULL;
4285 		zonelist->_zonerefs[0].zone_idx = 0;
4286 	}
4287 
4288 	/* NUMA-aware ordering of nodes */
4289 	local_node = pgdat->node_id;
4290 	load = nr_online_nodes;
4291 	prev_node = local_node;
4292 	nodes_clear(used_mask);
4293 
4294 	memset(node_order, 0, sizeof(node_order));
4295 	j = 0;
4296 
4297 	while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
4298 		/*
4299 		 * We don't want to pressure a particular node.
4300 		 * So adding penalty to the first node in same
4301 		 * distance group to make it round-robin.
4302 		 */
4303 		if (node_distance(local_node, node) !=
4304 		    node_distance(local_node, prev_node))
4305 			node_load[node] = load;
4306 
4307 		prev_node = node;
4308 		load--;
4309 		if (order == ZONELIST_ORDER_NODE)
4310 			build_zonelists_in_node_order(pgdat, node);
4311 		else
4312 			node_order[j++] = node;	/* remember order */
4313 	}
4314 
4315 	if (order == ZONELIST_ORDER_ZONE) {
4316 		/* calculate node order -- i.e., DMA last! */
4317 		build_zonelists_in_zone_order(pgdat, j);
4318 	}
4319 
4320 	build_thisnode_zonelists(pgdat);
4321 }
4322 
4323 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
4324 /*
4325  * Return node id of node used for "local" allocations.
4326  * I.e., first node id of first zone in arg node's generic zonelist.
4327  * Used for initializing percpu 'numa_mem', which is used primarily
4328  * for kernel allocations, so use GFP_KERNEL flags to locate zonelist.
4329  */
local_memory_node(int node)4330 int local_memory_node(int node)
4331 {
4332 	struct zone *zone;
4333 
4334 	(void)first_zones_zonelist(node_zonelist(node, GFP_KERNEL),
4335 				   gfp_zone(GFP_KERNEL),
4336 				   NULL,
4337 				   &zone);
4338 	return zone->node;
4339 }
4340 #endif
4341 
4342 #else	/* CONFIG_NUMA */
4343 
set_zonelist_order(void)4344 static void set_zonelist_order(void)
4345 {
4346 	current_zonelist_order = ZONELIST_ORDER_ZONE;
4347 }
4348 
build_zonelists(pg_data_t * pgdat)4349 static void build_zonelists(pg_data_t *pgdat)
4350 {
4351 	int node, local_node;
4352 	enum zone_type j;
4353 	struct zonelist *zonelist;
4354 
4355 	local_node = pgdat->node_id;
4356 
4357 	zonelist = &pgdat->node_zonelists[0];
4358 	j = build_zonelists_node(pgdat, zonelist, 0);
4359 
4360 	/*
4361 	 * Now we build the zonelist so that it contains the zones
4362 	 * of all the other nodes.
4363 	 * We don't want to pressure a particular node, so when
4364 	 * building the zones for node N, we make sure that the
4365 	 * zones coming right after the local ones are those from
4366 	 * node N+1 (modulo N)
4367 	 */
4368 	for (node = local_node + 1; node < MAX_NUMNODES; node++) {
4369 		if (!node_online(node))
4370 			continue;
4371 		j = build_zonelists_node(NODE_DATA(node), zonelist, j);
4372 	}
4373 	for (node = 0; node < local_node; node++) {
4374 		if (!node_online(node))
4375 			continue;
4376 		j = build_zonelists_node(NODE_DATA(node), zonelist, j);
4377 	}
4378 
4379 	zonelist->_zonerefs[j].zone = NULL;
4380 	zonelist->_zonerefs[j].zone_idx = 0;
4381 }
4382 
4383 #endif	/* CONFIG_NUMA */
4384 
4385 /*
4386  * Boot pageset table. One per cpu which is going to be used for all
4387  * zones and all nodes. The parameters will be set in such a way
4388  * that an item put on a list will immediately be handed over to
4389  * the buddy list. This is safe since pageset manipulation is done
4390  * with interrupts disabled.
4391  *
4392  * The boot_pagesets must be kept even after bootup is complete for
4393  * unused processors and/or zones. They do play a role for bootstrapping
4394  * hotplugged processors.
4395  *
4396  * zoneinfo_show() and maybe other functions do
4397  * not check if the processor is online before following the pageset pointer.
4398  * Other parts of the kernel may not check if the zone is available.
4399  */
4400 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch);
4401 static DEFINE_PER_CPU(struct per_cpu_pageset, boot_pageset);
4402 static void setup_zone_pageset(struct zone *zone);
4403 
4404 /*
4405  * Global mutex to protect against size modification of zonelists
4406  * as well as to serialize pageset setup for the new populated zone.
4407  */
4408 DEFINE_MUTEX(zonelists_mutex);
4409 
4410 /* return values int ....just for stop_machine() */
__build_all_zonelists(void * data)4411 static int __build_all_zonelists(void *data)
4412 {
4413 	int nid;
4414 	int cpu;
4415 	pg_data_t *self = data;
4416 
4417 #ifdef CONFIG_NUMA
4418 	memset(node_load, 0, sizeof(node_load));
4419 #endif
4420 
4421 	if (self && !node_online(self->node_id)) {
4422 		build_zonelists(self);
4423 	}
4424 
4425 	for_each_online_node(nid) {
4426 		pg_data_t *pgdat = NODE_DATA(nid);
4427 
4428 		build_zonelists(pgdat);
4429 	}
4430 
4431 	/*
4432 	 * Initialize the boot_pagesets that are going to be used
4433 	 * for bootstrapping processors. The real pagesets for
4434 	 * each zone will be allocated later when the per cpu
4435 	 * allocator is available.
4436 	 *
4437 	 * boot_pagesets are used also for bootstrapping offline
4438 	 * cpus if the system is already booted because the pagesets
4439 	 * are needed to initialize allocators on a specific cpu too.
4440 	 * F.e. the percpu allocator needs the page allocator which
4441 	 * needs the percpu allocator in order to allocate its pagesets
4442 	 * (a chicken-egg dilemma).
4443 	 */
4444 	for_each_possible_cpu(cpu) {
4445 		setup_pageset(&per_cpu(boot_pageset, cpu), 0);
4446 
4447 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
4448 		/*
4449 		 * We now know the "local memory node" for each node--
4450 		 * i.e., the node of the first zone in the generic zonelist.
4451 		 * Set up numa_mem percpu variable for on-line cpus.  During
4452 		 * boot, only the boot cpu should be on-line;  we'll init the
4453 		 * secondary cpus' numa_mem as they come on-line.  During
4454 		 * node/memory hotplug, we'll fixup all on-line cpus.
4455 		 */
4456 		if (cpu_online(cpu))
4457 			set_cpu_numa_mem(cpu, local_memory_node(cpu_to_node(cpu)));
4458 #endif
4459 	}
4460 
4461 	return 0;
4462 }
4463 
4464 static noinline void __init
build_all_zonelists_init(void)4465 build_all_zonelists_init(void)
4466 {
4467 	__build_all_zonelists(NULL);
4468 	mminit_verify_zonelist();
4469 	cpuset_init_current_mems_allowed();
4470 }
4471 
4472 /*
4473  * Called with zonelists_mutex held always
4474  * unless system_state == SYSTEM_BOOTING.
4475  *
4476  * __ref due to (1) call of __meminit annotated setup_zone_pageset
4477  * [we're only called with non-NULL zone through __meminit paths] and
4478  * (2) call of __init annotated helper build_all_zonelists_init
4479  * [protected by SYSTEM_BOOTING].
4480  */
build_all_zonelists(pg_data_t * pgdat,struct zone * zone)4481 void __ref build_all_zonelists(pg_data_t *pgdat, struct zone *zone)
4482 {
4483 	set_zonelist_order();
4484 
4485 	if (system_state == SYSTEM_BOOTING) {
4486 		build_all_zonelists_init();
4487 	} else {
4488 #ifdef CONFIG_MEMORY_HOTPLUG
4489 		if (zone)
4490 			setup_zone_pageset(zone);
4491 #endif
4492 		/* we have to stop all cpus to guarantee there is no user
4493 		   of zonelist */
4494 		stop_machine(__build_all_zonelists, pgdat, NULL);
4495 		/* cpuset refresh routine should be here */
4496 	}
4497 	vm_total_pages = nr_free_pagecache_pages();
4498 	/*
4499 	 * Disable grouping by mobility if the number of pages in the
4500 	 * system is too low to allow the mechanism to work. It would be
4501 	 * more accurate, but expensive to check per-zone. This check is
4502 	 * made on memory-hotadd so a system can start with mobility
4503 	 * disabled and enable it later
4504 	 */
4505 	if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES))
4506 		page_group_by_mobility_disabled = 1;
4507 	else
4508 		page_group_by_mobility_disabled = 0;
4509 
4510 	pr_info("Built %i zonelists in %s order, mobility grouping %s.  Total pages: %ld\n",
4511 		nr_online_nodes,
4512 		zonelist_order_name[current_zonelist_order],
4513 		page_group_by_mobility_disabled ? "off" : "on",
4514 		vm_total_pages);
4515 #ifdef CONFIG_NUMA
4516 	pr_info("Policy zone: %s\n", zone_names[policy_zone]);
4517 #endif
4518 }
4519 
4520 /*
4521  * Helper functions to size the waitqueue hash table.
4522  * Essentially these want to choose hash table sizes sufficiently
4523  * large so that collisions trying to wait on pages are rare.
4524  * But in fact, the number of active page waitqueues on typical
4525  * systems is ridiculously low, less than 200. So this is even
4526  * conservative, even though it seems large.
4527  *
4528  * The constant PAGES_PER_WAITQUEUE specifies the ratio of pages to
4529  * waitqueues, i.e. the size of the waitq table given the number of pages.
4530  */
4531 #define PAGES_PER_WAITQUEUE	256
4532 
4533 #ifndef CONFIG_MEMORY_HOTPLUG
wait_table_hash_nr_entries(unsigned long pages)4534 static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
4535 {
4536 	unsigned long size = 1;
4537 
4538 	pages /= PAGES_PER_WAITQUEUE;
4539 
4540 	while (size < pages)
4541 		size <<= 1;
4542 
4543 	/*
4544 	 * Once we have dozens or even hundreds of threads sleeping
4545 	 * on IO we've got bigger problems than wait queue collision.
4546 	 * Limit the size of the wait table to a reasonable size.
4547 	 */
4548 	size = min(size, 4096UL);
4549 
4550 	return max(size, 4UL);
4551 }
4552 #else
4553 /*
4554  * A zone's size might be changed by hot-add, so it is not possible to determine
4555  * a suitable size for its wait_table.  So we use the maximum size now.
4556  *
4557  * The max wait table size = 4096 x sizeof(wait_queue_head_t).   ie:
4558  *
4559  *    i386 (preemption config)    : 4096 x 16 = 64Kbyte.
4560  *    ia64, x86-64 (no preemption): 4096 x 20 = 80Kbyte.
4561  *    ia64, x86-64 (preemption)   : 4096 x 24 = 96Kbyte.
4562  *
4563  * The maximum entries are prepared when a zone's memory is (512K + 256) pages
4564  * or more by the traditional way. (See above).  It equals:
4565  *
4566  *    i386, x86-64, powerpc(4K page size) : =  ( 2G + 1M)byte.
4567  *    ia64(16K page size)                 : =  ( 8G + 4M)byte.
4568  *    powerpc (64K page size)             : =  (32G +16M)byte.
4569  */
wait_table_hash_nr_entries(unsigned long pages)4570 static inline unsigned long wait_table_hash_nr_entries(unsigned long pages)
4571 {
4572 	return 4096UL;
4573 }
4574 #endif
4575 
4576 /*
4577  * This is an integer logarithm so that shifts can be used later
4578  * to extract the more random high bits from the multiplicative
4579  * hash function before the remainder is taken.
4580  */
wait_table_bits(unsigned long size)4581 static inline unsigned long wait_table_bits(unsigned long size)
4582 {
4583 	return ffz(~size);
4584 }
4585 
4586 /*
4587  * Initially all pages are reserved - free ones are freed
4588  * up by free_all_bootmem() once the early boot process is
4589  * done. Non-atomic initialization, single-pass.
4590  */
memmap_init_zone(unsigned long size,int nid,unsigned long zone,unsigned long start_pfn,enum memmap_context context)4591 void __meminit memmap_init_zone(unsigned long size, int nid, unsigned long zone,
4592 		unsigned long start_pfn, enum memmap_context context)
4593 {
4594 	pg_data_t *pgdat = NODE_DATA(nid);
4595 	unsigned long end_pfn = start_pfn + size;
4596 	unsigned long pfn;
4597 	struct zone *z;
4598 	unsigned long nr_initialised = 0;
4599 
4600 	if (highest_memmap_pfn < end_pfn - 1)
4601 		highest_memmap_pfn = end_pfn - 1;
4602 
4603 	z = &pgdat->node_zones[zone];
4604 	for (pfn = start_pfn; pfn < end_pfn; pfn++) {
4605 		/*
4606 		 * There can be holes in boot-time mem_map[]s
4607 		 * handed to this function.  They do not
4608 		 * exist on hotplugged memory.
4609 		 */
4610 		if (context == MEMMAP_EARLY) {
4611 			if (!early_pfn_valid(pfn))
4612 				continue;
4613 			if (!early_pfn_in_nid(pfn, nid))
4614 				continue;
4615 			if (!update_defer_init(pgdat, pfn, end_pfn,
4616 						&nr_initialised))
4617 				break;
4618 		}
4619 
4620 		/*
4621 		 * Mark the block movable so that blocks are reserved for
4622 		 * movable at startup. This will force kernel allocations
4623 		 * to reserve their blocks rather than leaking throughout
4624 		 * the address space during boot when many long-lived
4625 		 * kernel allocations are made.
4626 		 *
4627 		 * bitmap is created for zone's valid pfn range. but memmap
4628 		 * can be created for invalid pages (for alignment)
4629 		 * check here not to call set_pageblock_migratetype() against
4630 		 * pfn out of zone.
4631 		 */
4632 		if (!(pfn & (pageblock_nr_pages - 1))) {
4633 			struct page *page = pfn_to_page(pfn);
4634 
4635 			__init_single_page(page, pfn, zone, nid);
4636 			set_pageblock_migratetype(page, MIGRATE_MOVABLE);
4637 		} else {
4638 			__init_single_pfn(pfn, zone, nid);
4639 		}
4640 	}
4641 }
4642 
zone_init_free_lists(struct zone * zone)4643 static void __meminit zone_init_free_lists(struct zone *zone)
4644 {
4645 	unsigned int order, t;
4646 	for_each_migratetype_order(order, t) {
4647 		INIT_LIST_HEAD(&zone->free_area[order].free_list[t]);
4648 		zone->free_area[order].nr_free = 0;
4649 	}
4650 }
4651 
4652 #ifndef __HAVE_ARCH_MEMMAP_INIT
4653 #define memmap_init(size, nid, zone, start_pfn) \
4654 	memmap_init_zone((size), (nid), (zone), (start_pfn), MEMMAP_EARLY)
4655 #endif
4656 
zone_batchsize(struct zone * zone)4657 static int zone_batchsize(struct zone *zone)
4658 {
4659 #ifdef CONFIG_MMU
4660 	int batch;
4661 
4662 	/*
4663 	 * The per-cpu-pages pools are set to around 1000th of the
4664 	 * size of the zone.  But no more than 1/2 of a meg.
4665 	 *
4666 	 * OK, so we don't know how big the cache is.  So guess.
4667 	 */
4668 	batch = zone->managed_pages / 1024;
4669 	if (batch * PAGE_SIZE > 512 * 1024)
4670 		batch = (512 * 1024) / PAGE_SIZE;
4671 	batch /= 4;		/* We effectively *= 4 below */
4672 	if (batch < 1)
4673 		batch = 1;
4674 
4675 	/*
4676 	 * Clamp the batch to a 2^n - 1 value. Having a power
4677 	 * of 2 value was found to be more likely to have
4678 	 * suboptimal cache aliasing properties in some cases.
4679 	 *
4680 	 * For example if 2 tasks are alternately allocating
4681 	 * batches of pages, one task can end up with a lot
4682 	 * of pages of one half of the possible page colors
4683 	 * and the other with pages of the other colors.
4684 	 */
4685 	batch = rounddown_pow_of_two(batch + batch/2) - 1;
4686 
4687 	return batch;
4688 
4689 #else
4690 	/* The deferral and batching of frees should be suppressed under NOMMU
4691 	 * conditions.
4692 	 *
4693 	 * The problem is that NOMMU needs to be able to allocate large chunks
4694 	 * of contiguous memory as there's no hardware page translation to
4695 	 * assemble apparent contiguous memory from discontiguous pages.
4696 	 *
4697 	 * Queueing large contiguous runs of pages for batching, however,
4698 	 * causes the pages to actually be freed in smaller chunks.  As there
4699 	 * can be a significant delay between the individual batches being
4700 	 * recycled, this leads to the once large chunks of space being
4701 	 * fragmented and becoming unavailable for high-order allocations.
4702 	 */
4703 	return 0;
4704 #endif
4705 }
4706 
4707 /*
4708  * pcp->high and pcp->batch values are related and dependent on one another:
4709  * ->batch must never be higher then ->high.
4710  * The following function updates them in a safe manner without read side
4711  * locking.
4712  *
4713  * Any new users of pcp->batch and pcp->high should ensure they can cope with
4714  * those fields changing asynchronously (acording the the above rule).
4715  *
4716  * mutex_is_locked(&pcp_batch_high_lock) required when calling this function
4717  * outside of boot time (or some other assurance that no concurrent updaters
4718  * exist).
4719  */
pageset_update(struct per_cpu_pages * pcp,unsigned long high,unsigned long batch)4720 static void pageset_update(struct per_cpu_pages *pcp, unsigned long high,
4721 		unsigned long batch)
4722 {
4723        /* start with a fail safe value for batch */
4724 	pcp->batch = 1;
4725 	smp_wmb();
4726 
4727        /* Update high, then batch, in order */
4728 	pcp->high = high;
4729 	smp_wmb();
4730 
4731 	pcp->batch = batch;
4732 }
4733 
4734 /* a companion to pageset_set_high() */
pageset_set_batch(struct per_cpu_pageset * p,unsigned long batch)4735 static void pageset_set_batch(struct per_cpu_pageset *p, unsigned long batch)
4736 {
4737 	pageset_update(&p->pcp, 6 * batch, max(1UL, 1 * batch));
4738 }
4739 
pageset_init(struct per_cpu_pageset * p)4740 static void pageset_init(struct per_cpu_pageset *p)
4741 {
4742 	struct per_cpu_pages *pcp;
4743 	int migratetype;
4744 
4745 	memset(p, 0, sizeof(*p));
4746 
4747 	pcp = &p->pcp;
4748 	pcp->count = 0;
4749 	for (migratetype = 0; migratetype < MIGRATE_PCPTYPES; migratetype++)
4750 		INIT_LIST_HEAD(&pcp->lists[migratetype]);
4751 }
4752 
setup_pageset(struct per_cpu_pageset * p,unsigned long batch)4753 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch)
4754 {
4755 	pageset_init(p);
4756 	pageset_set_batch(p, batch);
4757 }
4758 
4759 /*
4760  * pageset_set_high() sets the high water mark for hot per_cpu_pagelist
4761  * to the value high for the pageset p.
4762  */
pageset_set_high(struct per_cpu_pageset * p,unsigned long high)4763 static void pageset_set_high(struct per_cpu_pageset *p,
4764 				unsigned long high)
4765 {
4766 	unsigned long batch = max(1UL, high / 4);
4767 	if ((high / 4) > (PAGE_SHIFT * 8))
4768 		batch = PAGE_SHIFT * 8;
4769 
4770 	pageset_update(&p->pcp, high, batch);
4771 }
4772 
pageset_set_high_and_batch(struct zone * zone,struct per_cpu_pageset * pcp)4773 static void pageset_set_high_and_batch(struct zone *zone,
4774 				       struct per_cpu_pageset *pcp)
4775 {
4776 	if (percpu_pagelist_fraction)
4777 		pageset_set_high(pcp,
4778 			(zone->managed_pages /
4779 				percpu_pagelist_fraction));
4780 	else
4781 		pageset_set_batch(pcp, zone_batchsize(zone));
4782 }
4783 
zone_pageset_init(struct zone * zone,int cpu)4784 static void __meminit zone_pageset_init(struct zone *zone, int cpu)
4785 {
4786 	struct per_cpu_pageset *pcp = per_cpu_ptr(zone->pageset, cpu);
4787 
4788 	pageset_init(pcp);
4789 	pageset_set_high_and_batch(zone, pcp);
4790 }
4791 
setup_zone_pageset(struct zone * zone)4792 static void __meminit setup_zone_pageset(struct zone *zone)
4793 {
4794 	int cpu;
4795 	zone->pageset = alloc_percpu(struct per_cpu_pageset);
4796 	for_each_possible_cpu(cpu)
4797 		zone_pageset_init(zone, cpu);
4798 }
4799 
4800 /*
4801  * Allocate per cpu pagesets and initialize them.
4802  * Before this call only boot pagesets were available.
4803  */
setup_per_cpu_pageset(void)4804 void __init setup_per_cpu_pageset(void)
4805 {
4806 	struct zone *zone;
4807 
4808 	for_each_populated_zone(zone)
4809 		setup_zone_pageset(zone);
4810 }
4811 
4812 static noinline __init_refok
zone_wait_table_init(struct zone * zone,unsigned long zone_size_pages)4813 int zone_wait_table_init(struct zone *zone, unsigned long zone_size_pages)
4814 {
4815 	int i;
4816 	size_t alloc_size;
4817 
4818 	/*
4819 	 * The per-page waitqueue mechanism uses hashed waitqueues
4820 	 * per zone.
4821 	 */
4822 	zone->wait_table_hash_nr_entries =
4823 		 wait_table_hash_nr_entries(zone_size_pages);
4824 	zone->wait_table_bits =
4825 		wait_table_bits(zone->wait_table_hash_nr_entries);
4826 	alloc_size = zone->wait_table_hash_nr_entries
4827 					* sizeof(wait_queue_head_t);
4828 
4829 	if (!slab_is_available()) {
4830 		zone->wait_table = (wait_queue_head_t *)
4831 			memblock_virt_alloc_node_nopanic(
4832 				alloc_size, zone->zone_pgdat->node_id);
4833 	} else {
4834 		/*
4835 		 * This case means that a zone whose size was 0 gets new memory
4836 		 * via memory hot-add.
4837 		 * But it may be the case that a new node was hot-added.  In
4838 		 * this case vmalloc() will not be able to use this new node's
4839 		 * memory - this wait_table must be initialized to use this new
4840 		 * node itself as well.
4841 		 * To use this new node's memory, further consideration will be
4842 		 * necessary.
4843 		 */
4844 		zone->wait_table = vmalloc(alloc_size);
4845 	}
4846 	if (!zone->wait_table)
4847 		return -ENOMEM;
4848 
4849 	for (i = 0; i < zone->wait_table_hash_nr_entries; ++i)
4850 		init_waitqueue_head(zone->wait_table + i);
4851 
4852 	return 0;
4853 }
4854 
zone_pcp_init(struct zone * zone)4855 static __meminit void zone_pcp_init(struct zone *zone)
4856 {
4857 	/*
4858 	 * per cpu subsystem is not up at this point. The following code
4859 	 * relies on the ability of the linker to provide the
4860 	 * offset of a (static) per cpu variable into the per cpu area.
4861 	 */
4862 	zone->pageset = &boot_pageset;
4863 
4864 	if (populated_zone(zone))
4865 		printk(KERN_DEBUG "  %s zone: %lu pages, LIFO batch:%u\n",
4866 			zone->name, zone->present_pages,
4867 					 zone_batchsize(zone));
4868 }
4869 
init_currently_empty_zone(struct zone * zone,unsigned long zone_start_pfn,unsigned long size)4870 int __meminit init_currently_empty_zone(struct zone *zone,
4871 					unsigned long zone_start_pfn,
4872 					unsigned long size)
4873 {
4874 	struct pglist_data *pgdat = zone->zone_pgdat;
4875 	int ret;
4876 	ret = zone_wait_table_init(zone, size);
4877 	if (ret)
4878 		return ret;
4879 	pgdat->nr_zones = zone_idx(zone) + 1;
4880 
4881 	zone->zone_start_pfn = zone_start_pfn;
4882 
4883 	mminit_dprintk(MMINIT_TRACE, "memmap_init",
4884 			"Initialising map node %d zone %lu pfns %lu -> %lu\n",
4885 			pgdat->node_id,
4886 			(unsigned long)zone_idx(zone),
4887 			zone_start_pfn, (zone_start_pfn + size));
4888 
4889 	zone_init_free_lists(zone);
4890 
4891 	return 0;
4892 }
4893 
4894 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
4895 #ifndef CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID
4896 
4897 /*
4898  * Required by SPARSEMEM. Given a PFN, return what node the PFN is on.
4899  */
__early_pfn_to_nid(unsigned long pfn,struct mminit_pfnnid_cache * state)4900 int __meminit __early_pfn_to_nid(unsigned long pfn,
4901 					struct mminit_pfnnid_cache *state)
4902 {
4903 	unsigned long start_pfn, end_pfn;
4904 	int nid;
4905 
4906 	if (state->last_start <= pfn && pfn < state->last_end)
4907 		return state->last_nid;
4908 
4909 	nid = memblock_search_pfn_nid(pfn, &start_pfn, &end_pfn);
4910 	if (nid != -1) {
4911 		state->last_start = start_pfn;
4912 		state->last_end = end_pfn;
4913 		state->last_nid = nid;
4914 	}
4915 
4916 	return nid;
4917 }
4918 #endif /* CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID */
4919 
4920 /**
4921  * free_bootmem_with_active_regions - Call memblock_free_early_nid for each active range
4922  * @nid: The node to free memory on. If MAX_NUMNODES, all nodes are freed.
4923  * @max_low_pfn: The highest PFN that will be passed to memblock_free_early_nid
4924  *
4925  * If an architecture guarantees that all ranges registered contain no holes
4926  * and may be freed, this this function may be used instead of calling
4927  * memblock_free_early_nid() manually.
4928  */
free_bootmem_with_active_regions(int nid,unsigned long max_low_pfn)4929 void __init free_bootmem_with_active_regions(int nid, unsigned long max_low_pfn)
4930 {
4931 	unsigned long start_pfn, end_pfn;
4932 	int i, this_nid;
4933 
4934 	for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, &this_nid) {
4935 		start_pfn = min(start_pfn, max_low_pfn);
4936 		end_pfn = min(end_pfn, max_low_pfn);
4937 
4938 		if (start_pfn < end_pfn)
4939 			memblock_free_early_nid(PFN_PHYS(start_pfn),
4940 					(end_pfn - start_pfn) << PAGE_SHIFT,
4941 					this_nid);
4942 	}
4943 }
4944 
4945 /**
4946  * sparse_memory_present_with_active_regions - Call memory_present for each active range
4947  * @nid: The node to call memory_present for. If MAX_NUMNODES, all nodes will be used.
4948  *
4949  * If an architecture guarantees that all ranges registered contain no holes and may
4950  * be freed, this function may be used instead of calling memory_present() manually.
4951  */
sparse_memory_present_with_active_regions(int nid)4952 void __init sparse_memory_present_with_active_regions(int nid)
4953 {
4954 	unsigned long start_pfn, end_pfn;
4955 	int i, this_nid;
4956 
4957 	for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, &this_nid)
4958 		memory_present(this_nid, start_pfn, end_pfn);
4959 }
4960 
4961 /**
4962  * get_pfn_range_for_nid - Return the start and end page frames for a node
4963  * @nid: The nid to return the range for. If MAX_NUMNODES, the min and max PFN are returned.
4964  * @start_pfn: Passed by reference. On return, it will have the node start_pfn.
4965  * @end_pfn: Passed by reference. On return, it will have the node end_pfn.
4966  *
4967  * It returns the start and end page frame of a node based on information
4968  * provided by memblock_set_node(). If called for a node
4969  * with no available memory, a warning is printed and the start and end
4970  * PFNs will be 0.
4971  */
get_pfn_range_for_nid(unsigned int nid,unsigned long * start_pfn,unsigned long * end_pfn)4972 void __meminit get_pfn_range_for_nid(unsigned int nid,
4973 			unsigned long *start_pfn, unsigned long *end_pfn)
4974 {
4975 	unsigned long this_start_pfn, this_end_pfn;
4976 	int i;
4977 
4978 	*start_pfn = -1UL;
4979 	*end_pfn = 0;
4980 
4981 	for_each_mem_pfn_range(i, nid, &this_start_pfn, &this_end_pfn, NULL) {
4982 		*start_pfn = min(*start_pfn, this_start_pfn);
4983 		*end_pfn = max(*end_pfn, this_end_pfn);
4984 	}
4985 
4986 	if (*start_pfn == -1UL)
4987 		*start_pfn = 0;
4988 }
4989 
4990 /*
4991  * This finds a zone that can be used for ZONE_MOVABLE pages. The
4992  * assumption is made that zones within a node are ordered in monotonic
4993  * increasing memory addresses so that the "highest" populated zone is used
4994  */
find_usable_zone_for_movable(void)4995 static void __init find_usable_zone_for_movable(void)
4996 {
4997 	int zone_index;
4998 	for (zone_index = MAX_NR_ZONES - 1; zone_index >= 0; zone_index--) {
4999 		if (zone_index == ZONE_MOVABLE)
5000 			continue;
5001 
5002 		if (arch_zone_highest_possible_pfn[zone_index] >
5003 				arch_zone_lowest_possible_pfn[zone_index])
5004 			break;
5005 	}
5006 
5007 	VM_BUG_ON(zone_index == -1);
5008 	movable_zone = zone_index;
5009 }
5010 
5011 /*
5012  * The zone ranges provided by the architecture do not include ZONE_MOVABLE
5013  * because it is sized independent of architecture. Unlike the other zones,
5014  * the starting point for ZONE_MOVABLE is not fixed. It may be different
5015  * in each node depending on the size of each node and how evenly kernelcore
5016  * is distributed. This helper function adjusts the zone ranges
5017  * provided by the architecture for a given node by using the end of the
5018  * highest usable zone for ZONE_MOVABLE. This preserves the assumption that
5019  * zones within a node are in order of monotonic increases memory addresses
5020  */
adjust_zone_range_for_zone_movable(int nid,unsigned long zone_type,unsigned long node_start_pfn,unsigned long node_end_pfn,unsigned long * zone_start_pfn,unsigned long * zone_end_pfn)5021 static void __meminit adjust_zone_range_for_zone_movable(int nid,
5022 					unsigned long zone_type,
5023 					unsigned long node_start_pfn,
5024 					unsigned long node_end_pfn,
5025 					unsigned long *zone_start_pfn,
5026 					unsigned long *zone_end_pfn)
5027 {
5028 	/* Only adjust if ZONE_MOVABLE is on this node */
5029 	if (zone_movable_pfn[nid]) {
5030 		/* Size ZONE_MOVABLE */
5031 		if (zone_type == ZONE_MOVABLE) {
5032 			*zone_start_pfn = zone_movable_pfn[nid];
5033 			*zone_end_pfn = min(node_end_pfn,
5034 				arch_zone_highest_possible_pfn[movable_zone]);
5035 
5036 		/* Adjust for ZONE_MOVABLE starting within this range */
5037 		} else if (*zone_start_pfn < zone_movable_pfn[nid] &&
5038 				*zone_end_pfn > zone_movable_pfn[nid]) {
5039 			*zone_end_pfn = zone_movable_pfn[nid];
5040 
5041 		/* Check if this whole range is within ZONE_MOVABLE */
5042 		} else if (*zone_start_pfn >= zone_movable_pfn[nid])
5043 			*zone_start_pfn = *zone_end_pfn;
5044 	}
5045 }
5046 
5047 /*
5048  * Return the number of pages a zone spans in a node, including holes
5049  * present_pages = zone_spanned_pages_in_node() - zone_absent_pages_in_node()
5050  */
zone_spanned_pages_in_node(int nid,unsigned long zone_type,unsigned long node_start_pfn,unsigned long node_end_pfn,unsigned long * ignored)5051 static unsigned long __meminit zone_spanned_pages_in_node(int nid,
5052 					unsigned long zone_type,
5053 					unsigned long node_start_pfn,
5054 					unsigned long node_end_pfn,
5055 					unsigned long *ignored)
5056 {
5057 	unsigned long zone_start_pfn, zone_end_pfn;
5058 
5059 	/* When hotadd a new node from cpu_up(), the node should be empty */
5060 	if (!node_start_pfn && !node_end_pfn)
5061 		return 0;
5062 
5063 	/* Get the start and end of the zone */
5064 	zone_start_pfn = arch_zone_lowest_possible_pfn[zone_type];
5065 	zone_end_pfn = arch_zone_highest_possible_pfn[zone_type];
5066 	adjust_zone_range_for_zone_movable(nid, zone_type,
5067 				node_start_pfn, node_end_pfn,
5068 				&zone_start_pfn, &zone_end_pfn);
5069 
5070 	/* Check that this node has pages within the zone's required range */
5071 	if (zone_end_pfn < node_start_pfn || zone_start_pfn > node_end_pfn)
5072 		return 0;
5073 
5074 	/* Move the zone boundaries inside the node if necessary */
5075 	zone_end_pfn = min(zone_end_pfn, node_end_pfn);
5076 	zone_start_pfn = max(zone_start_pfn, node_start_pfn);
5077 
5078 	/* Return the spanned pages */
5079 	return zone_end_pfn - zone_start_pfn;
5080 }
5081 
5082 /*
5083  * Return the number of holes in a range on a node. If nid is MAX_NUMNODES,
5084  * then all holes in the requested range will be accounted for.
5085  */
__absent_pages_in_range(int nid,unsigned long range_start_pfn,unsigned long range_end_pfn)5086 unsigned long __meminit __absent_pages_in_range(int nid,
5087 				unsigned long range_start_pfn,
5088 				unsigned long range_end_pfn)
5089 {
5090 	unsigned long nr_absent = range_end_pfn - range_start_pfn;
5091 	unsigned long start_pfn, end_pfn;
5092 	int i;
5093 
5094 	for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
5095 		start_pfn = clamp(start_pfn, range_start_pfn, range_end_pfn);
5096 		end_pfn = clamp(end_pfn, range_start_pfn, range_end_pfn);
5097 		nr_absent -= end_pfn - start_pfn;
5098 	}
5099 	return nr_absent;
5100 }
5101 
5102 /**
5103  * absent_pages_in_range - Return number of page frames in holes within a range
5104  * @start_pfn: The start PFN to start searching for holes
5105  * @end_pfn: The end PFN to stop searching for holes
5106  *
5107  * It returns the number of pages frames in memory holes within a range.
5108  */
absent_pages_in_range(unsigned long start_pfn,unsigned long end_pfn)5109 unsigned long __init absent_pages_in_range(unsigned long start_pfn,
5110 							unsigned long end_pfn)
5111 {
5112 	return __absent_pages_in_range(MAX_NUMNODES, start_pfn, end_pfn);
5113 }
5114 
5115 /* Return the number of page frames in holes in a zone on a node */
zone_absent_pages_in_node(int nid,unsigned long zone_type,unsigned long node_start_pfn,unsigned long node_end_pfn,unsigned long * ignored)5116 static unsigned long __meminit zone_absent_pages_in_node(int nid,
5117 					unsigned long zone_type,
5118 					unsigned long node_start_pfn,
5119 					unsigned long node_end_pfn,
5120 					unsigned long *ignored)
5121 {
5122 	unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type];
5123 	unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type];
5124 	unsigned long zone_start_pfn, zone_end_pfn;
5125 
5126 	/* When hotadd a new node from cpu_up(), the node should be empty */
5127 	if (!node_start_pfn && !node_end_pfn)
5128 		return 0;
5129 
5130 	zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high);
5131 	zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high);
5132 
5133 	adjust_zone_range_for_zone_movable(nid, zone_type,
5134 			node_start_pfn, node_end_pfn,
5135 			&zone_start_pfn, &zone_end_pfn);
5136 	return __absent_pages_in_range(nid, zone_start_pfn, zone_end_pfn);
5137 }
5138 
5139 #else /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
zone_spanned_pages_in_node(int nid,unsigned long zone_type,unsigned long node_start_pfn,unsigned long node_end_pfn,unsigned long * zones_size)5140 static inline unsigned long __meminit zone_spanned_pages_in_node(int nid,
5141 					unsigned long zone_type,
5142 					unsigned long node_start_pfn,
5143 					unsigned long node_end_pfn,
5144 					unsigned long *zones_size)
5145 {
5146 	return zones_size[zone_type];
5147 }
5148 
zone_absent_pages_in_node(int nid,unsigned long zone_type,unsigned long node_start_pfn,unsigned long node_end_pfn,unsigned long * zholes_size)5149 static inline unsigned long __meminit zone_absent_pages_in_node(int nid,
5150 						unsigned long zone_type,
5151 						unsigned long node_start_pfn,
5152 						unsigned long node_end_pfn,
5153 						unsigned long *zholes_size)
5154 {
5155 	if (!zholes_size)
5156 		return 0;
5157 
5158 	return zholes_size[zone_type];
5159 }
5160 
5161 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
5162 
calculate_node_totalpages(struct pglist_data * pgdat,unsigned long node_start_pfn,unsigned long node_end_pfn,unsigned long * zones_size,unsigned long * zholes_size)5163 static void __meminit calculate_node_totalpages(struct pglist_data *pgdat,
5164 						unsigned long node_start_pfn,
5165 						unsigned long node_end_pfn,
5166 						unsigned long *zones_size,
5167 						unsigned long *zholes_size)
5168 {
5169 	unsigned long realtotalpages = 0, totalpages = 0;
5170 	enum zone_type i;
5171 
5172 	for (i = 0; i < MAX_NR_ZONES; i++) {
5173 		struct zone *zone = pgdat->node_zones + i;
5174 		unsigned long size, real_size;
5175 
5176 		size = zone_spanned_pages_in_node(pgdat->node_id, i,
5177 						  node_start_pfn,
5178 						  node_end_pfn,
5179 						  zones_size);
5180 		real_size = size - zone_absent_pages_in_node(pgdat->node_id, i,
5181 						  node_start_pfn, node_end_pfn,
5182 						  zholes_size);
5183 		zone->spanned_pages = size;
5184 		zone->present_pages = real_size;
5185 
5186 		totalpages += size;
5187 		realtotalpages += real_size;
5188 	}
5189 
5190 	pgdat->node_spanned_pages = totalpages;
5191 	pgdat->node_present_pages = realtotalpages;
5192 	printk(KERN_DEBUG "On node %d totalpages: %lu\n", pgdat->node_id,
5193 							realtotalpages);
5194 }
5195 
5196 #ifndef CONFIG_SPARSEMEM
5197 /*
5198  * Calculate the size of the zone->blockflags rounded to an unsigned long
5199  * Start by making sure zonesize is a multiple of pageblock_order by rounding
5200  * up. Then use 1 NR_PAGEBLOCK_BITS worth of bits per pageblock, finally
5201  * round what is now in bits to nearest long in bits, then return it in
5202  * bytes.
5203  */
usemap_size(unsigned long zone_start_pfn,unsigned long zonesize)5204 static unsigned long __init usemap_size(unsigned long zone_start_pfn, unsigned long zonesize)
5205 {
5206 	unsigned long usemapsize;
5207 
5208 	zonesize += zone_start_pfn & (pageblock_nr_pages-1);
5209 	usemapsize = roundup(zonesize, pageblock_nr_pages);
5210 	usemapsize = usemapsize >> pageblock_order;
5211 	usemapsize *= NR_PAGEBLOCK_BITS;
5212 	usemapsize = roundup(usemapsize, 8 * sizeof(unsigned long));
5213 
5214 	return usemapsize / 8;
5215 }
5216 
setup_usemap(struct pglist_data * pgdat,struct zone * zone,unsigned long zone_start_pfn,unsigned long zonesize)5217 static void __init setup_usemap(struct pglist_data *pgdat,
5218 				struct zone *zone,
5219 				unsigned long zone_start_pfn,
5220 				unsigned long zonesize)
5221 {
5222 	unsigned long usemapsize = usemap_size(zone_start_pfn, zonesize);
5223 	zone->pageblock_flags = NULL;
5224 	if (usemapsize)
5225 		zone->pageblock_flags =
5226 			memblock_virt_alloc_node_nopanic(usemapsize,
5227 							 pgdat->node_id);
5228 }
5229 #else
setup_usemap(struct pglist_data * pgdat,struct zone * zone,unsigned long zone_start_pfn,unsigned long zonesize)5230 static inline void setup_usemap(struct pglist_data *pgdat, struct zone *zone,
5231 				unsigned long zone_start_pfn, unsigned long zonesize) {}
5232 #endif /* CONFIG_SPARSEMEM */
5233 
5234 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
5235 
5236 /* Initialise the number of pages represented by NR_PAGEBLOCK_BITS */
set_pageblock_order(void)5237 void __paginginit set_pageblock_order(void)
5238 {
5239 	unsigned int order;
5240 
5241 	/* Check that pageblock_nr_pages has not already been setup */
5242 	if (pageblock_order)
5243 		return;
5244 
5245 	if (HPAGE_SHIFT > PAGE_SHIFT)
5246 		order = HUGETLB_PAGE_ORDER;
5247 	else
5248 		order = MAX_ORDER - 1;
5249 
5250 	/*
5251 	 * Assume the largest contiguous order of interest is a huge page.
5252 	 * This value may be variable depending on boot parameters on IA64 and
5253 	 * powerpc.
5254 	 */
5255 	pageblock_order = order;
5256 }
5257 #else /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
5258 
5259 /*
5260  * When CONFIG_HUGETLB_PAGE_SIZE_VARIABLE is not set, set_pageblock_order()
5261  * is unused as pageblock_order is set at compile-time. See
5262  * include/linux/pageblock-flags.h for the values of pageblock_order based on
5263  * the kernel config
5264  */
set_pageblock_order(void)5265 void __paginginit set_pageblock_order(void)
5266 {
5267 }
5268 
5269 #endif /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
5270 
calc_memmap_size(unsigned long spanned_pages,unsigned long present_pages)5271 static unsigned long __paginginit calc_memmap_size(unsigned long spanned_pages,
5272 						   unsigned long present_pages)
5273 {
5274 	unsigned long pages = spanned_pages;
5275 
5276 	/*
5277 	 * Provide a more accurate estimation if there are holes within
5278 	 * the zone and SPARSEMEM is in use. If there are holes within the
5279 	 * zone, each populated memory region may cost us one or two extra
5280 	 * memmap pages due to alignment because memmap pages for each
5281 	 * populated regions may not naturally algined on page boundary.
5282 	 * So the (present_pages >> 4) heuristic is a tradeoff for that.
5283 	 */
5284 	if (spanned_pages > present_pages + (present_pages >> 4) &&
5285 	    IS_ENABLED(CONFIG_SPARSEMEM))
5286 		pages = present_pages;
5287 
5288 	return PAGE_ALIGN(pages * sizeof(struct page)) >> PAGE_SHIFT;
5289 }
5290 
5291 /*
5292  * Set up the zone data structures:
5293  *   - mark all pages reserved
5294  *   - mark all memory queues empty
5295  *   - clear the memory bitmaps
5296  *
5297  * NOTE: pgdat should get zeroed by caller.
5298  */
free_area_init_core(struct pglist_data * pgdat)5299 static void __paginginit free_area_init_core(struct pglist_data *pgdat)
5300 {
5301 	enum zone_type j;
5302 	int nid = pgdat->node_id;
5303 	unsigned long zone_start_pfn = pgdat->node_start_pfn;
5304 	int ret;
5305 
5306 	pgdat_resize_init(pgdat);
5307 #ifdef CONFIG_NUMA_BALANCING
5308 	spin_lock_init(&pgdat->numabalancing_migrate_lock);
5309 	pgdat->numabalancing_migrate_nr_pages = 0;
5310 	pgdat->numabalancing_migrate_next_window = jiffies;
5311 #endif
5312 	init_waitqueue_head(&pgdat->kswapd_wait);
5313 	init_waitqueue_head(&pgdat->pfmemalloc_wait);
5314 	pgdat_page_ext_init(pgdat);
5315 
5316 	for (j = 0; j < MAX_NR_ZONES; j++) {
5317 		struct zone *zone = pgdat->node_zones + j;
5318 		unsigned long size, realsize, freesize, memmap_pages;
5319 
5320 		size = zone->spanned_pages;
5321 		realsize = freesize = zone->present_pages;
5322 
5323 		/*
5324 		 * Adjust freesize so that it accounts for how much memory
5325 		 * is used by this zone for memmap. This affects the watermark
5326 		 * and per-cpu initialisations
5327 		 */
5328 		memmap_pages = calc_memmap_size(size, realsize);
5329 		if (!is_highmem_idx(j)) {
5330 			if (freesize >= memmap_pages) {
5331 				freesize -= memmap_pages;
5332 				if (memmap_pages)
5333 					printk(KERN_DEBUG
5334 					       "  %s zone: %lu pages used for memmap\n",
5335 					       zone_names[j], memmap_pages);
5336 			} else
5337 				printk(KERN_WARNING
5338 					"  %s zone: %lu pages exceeds freesize %lu\n",
5339 					zone_names[j], memmap_pages, freesize);
5340 		}
5341 
5342 		/* Account for reserved pages */
5343 		if (j == 0 && freesize > dma_reserve) {
5344 			freesize -= dma_reserve;
5345 			printk(KERN_DEBUG "  %s zone: %lu pages reserved\n",
5346 					zone_names[0], dma_reserve);
5347 		}
5348 
5349 		if (!is_highmem_idx(j))
5350 			nr_kernel_pages += freesize;
5351 		/* Charge for highmem memmap if there are enough kernel pages */
5352 		else if (nr_kernel_pages > memmap_pages * 2)
5353 			nr_kernel_pages -= memmap_pages;
5354 		nr_all_pages += freesize;
5355 
5356 		/*
5357 		 * Set an approximate value for lowmem here, it will be adjusted
5358 		 * when the bootmem allocator frees pages into the buddy system.
5359 		 * And all highmem pages will be managed by the buddy system.
5360 		 */
5361 		zone->managed_pages = is_highmem_idx(j) ? realsize : freesize;
5362 #ifdef CONFIG_NUMA
5363 		zone->node = nid;
5364 		zone->min_unmapped_pages = (freesize*sysctl_min_unmapped_ratio)
5365 						/ 100;
5366 		zone->min_slab_pages = (freesize * sysctl_min_slab_ratio) / 100;
5367 #endif
5368 		zone->name = zone_names[j];
5369 		spin_lock_init(&zone->lock);
5370 		spin_lock_init(&zone->lru_lock);
5371 		zone_seqlock_init(zone);
5372 		zone->zone_pgdat = pgdat;
5373 		zone_pcp_init(zone);
5374 
5375 		/* For bootup, initialized properly in watermark setup */
5376 		mod_zone_page_state(zone, NR_ALLOC_BATCH, zone->managed_pages);
5377 
5378 		lruvec_init(&zone->lruvec);
5379 		if (!size)
5380 			continue;
5381 
5382 		set_pageblock_order();
5383 		setup_usemap(pgdat, zone, zone_start_pfn, size);
5384 		ret = init_currently_empty_zone(zone, zone_start_pfn, size);
5385 		BUG_ON(ret);
5386 		memmap_init(size, nid, j, zone_start_pfn);
5387 		zone_start_pfn += size;
5388 	}
5389 }
5390 
alloc_node_mem_map(struct pglist_data * pgdat)5391 static void __init_refok alloc_node_mem_map(struct pglist_data *pgdat)
5392 {
5393 	unsigned long __maybe_unused start = 0;
5394 	unsigned long __maybe_unused offset = 0;
5395 
5396 	/* Skip empty nodes */
5397 	if (!pgdat->node_spanned_pages)
5398 		return;
5399 
5400 #ifdef CONFIG_FLAT_NODE_MEM_MAP
5401 	start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1);
5402 	offset = pgdat->node_start_pfn - start;
5403 	/* ia64 gets its own node_mem_map, before this, without bootmem */
5404 	if (!pgdat->node_mem_map) {
5405 		unsigned long size, end;
5406 		struct page *map;
5407 
5408 		/*
5409 		 * The zone's endpoints aren't required to be MAX_ORDER
5410 		 * aligned but the node_mem_map endpoints must be in order
5411 		 * for the buddy allocator to function correctly.
5412 		 */
5413 		end = pgdat_end_pfn(pgdat);
5414 		end = ALIGN(end, MAX_ORDER_NR_PAGES);
5415 		size =  (end - start) * sizeof(struct page);
5416 		map = alloc_remap(pgdat->node_id, size);
5417 		if (!map)
5418 			map = memblock_virt_alloc_node_nopanic(size,
5419 							       pgdat->node_id);
5420 		pgdat->node_mem_map = map + offset;
5421 	}
5422 #ifndef CONFIG_NEED_MULTIPLE_NODES
5423 	/*
5424 	 * With no DISCONTIG, the global mem_map is just set as node 0's
5425 	 */
5426 	if (pgdat == NODE_DATA(0)) {
5427 		mem_map = NODE_DATA(0)->node_mem_map;
5428 #if defined(CONFIG_HAVE_MEMBLOCK_NODE_MAP) || defined(CONFIG_FLATMEM)
5429 		if (page_to_pfn(mem_map) != pgdat->node_start_pfn)
5430 			mem_map -= offset;
5431 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
5432 	}
5433 #endif
5434 #endif /* CONFIG_FLAT_NODE_MEM_MAP */
5435 }
5436 
free_area_init_node(int nid,unsigned long * zones_size,unsigned long node_start_pfn,unsigned long * zholes_size)5437 void __paginginit free_area_init_node(int nid, unsigned long *zones_size,
5438 		unsigned long node_start_pfn, unsigned long *zholes_size)
5439 {
5440 	pg_data_t *pgdat = NODE_DATA(nid);
5441 	unsigned long start_pfn = 0;
5442 	unsigned long end_pfn = 0;
5443 
5444 	/* pg_data_t should be reset to zero when it's allocated */
5445 	WARN_ON(pgdat->nr_zones || pgdat->classzone_idx);
5446 
5447 	pgdat->node_id = nid;
5448 	pgdat->node_start_pfn = node_start_pfn;
5449 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
5450 	get_pfn_range_for_nid(nid, &start_pfn, &end_pfn);
5451 	pr_info("Initmem setup node %d [mem %#018Lx-%#018Lx]\n", nid,
5452 		(u64)start_pfn << PAGE_SHIFT,
5453 		end_pfn ? ((u64)end_pfn << PAGE_SHIFT) - 1 : 0);
5454 #endif
5455 	calculate_node_totalpages(pgdat, start_pfn, end_pfn,
5456 				  zones_size, zholes_size);
5457 
5458 	alloc_node_mem_map(pgdat);
5459 #ifdef CONFIG_FLAT_NODE_MEM_MAP
5460 	printk(KERN_DEBUG "free_area_init_node: node %d, pgdat %08lx, node_mem_map %08lx\n",
5461 		nid, (unsigned long)pgdat,
5462 		(unsigned long)pgdat->node_mem_map);
5463 #endif
5464 
5465 	reset_deferred_meminit(pgdat);
5466 	free_area_init_core(pgdat);
5467 }
5468 
5469 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
5470 
5471 #if MAX_NUMNODES > 1
5472 /*
5473  * Figure out the number of possible node ids.
5474  */
setup_nr_node_ids(void)5475 void __init setup_nr_node_ids(void)
5476 {
5477 	unsigned int highest;
5478 
5479 	highest = find_last_bit(node_possible_map.bits, MAX_NUMNODES);
5480 	nr_node_ids = highest + 1;
5481 }
5482 #endif
5483 
5484 /**
5485  * node_map_pfn_alignment - determine the maximum internode alignment
5486  *
5487  * This function should be called after node map is populated and sorted.
5488  * It calculates the maximum power of two alignment which can distinguish
5489  * all the nodes.
5490  *
5491  * For example, if all nodes are 1GiB and aligned to 1GiB, the return value
5492  * would indicate 1GiB alignment with (1 << (30 - PAGE_SHIFT)).  If the
5493  * nodes are shifted by 256MiB, 256MiB.  Note that if only the last node is
5494  * shifted, 1GiB is enough and this function will indicate so.
5495  *
5496  * This is used to test whether pfn -> nid mapping of the chosen memory
5497  * model has fine enough granularity to avoid incorrect mapping for the
5498  * populated node map.
5499  *
5500  * Returns the determined alignment in pfn's.  0 if there is no alignment
5501  * requirement (single node).
5502  */
node_map_pfn_alignment(void)5503 unsigned long __init node_map_pfn_alignment(void)
5504 {
5505 	unsigned long accl_mask = 0, last_end = 0;
5506 	unsigned long start, end, mask;
5507 	int last_nid = -1;
5508 	int i, nid;
5509 
5510 	for_each_mem_pfn_range(i, MAX_NUMNODES, &start, &end, &nid) {
5511 		if (!start || last_nid < 0 || last_nid == nid) {
5512 			last_nid = nid;
5513 			last_end = end;
5514 			continue;
5515 		}
5516 
5517 		/*
5518 		 * Start with a mask granular enough to pin-point to the
5519 		 * start pfn and tick off bits one-by-one until it becomes
5520 		 * too coarse to separate the current node from the last.
5521 		 */
5522 		mask = ~((1 << __ffs(start)) - 1);
5523 		while (mask && last_end <= (start & (mask << 1)))
5524 			mask <<= 1;
5525 
5526 		/* accumulate all internode masks */
5527 		accl_mask |= mask;
5528 	}
5529 
5530 	/* convert mask to number of pages */
5531 	return ~accl_mask + 1;
5532 }
5533 
5534 /* Find the lowest pfn for a node */
find_min_pfn_for_node(int nid)5535 static unsigned long __init find_min_pfn_for_node(int nid)
5536 {
5537 	unsigned long min_pfn = ULONG_MAX;
5538 	unsigned long start_pfn;
5539 	int i;
5540 
5541 	for_each_mem_pfn_range(i, nid, &start_pfn, NULL, NULL)
5542 		min_pfn = min(min_pfn, start_pfn);
5543 
5544 	if (min_pfn == ULONG_MAX) {
5545 		printk(KERN_WARNING
5546 			"Could not find start_pfn for node %d\n", nid);
5547 		return 0;
5548 	}
5549 
5550 	return min_pfn;
5551 }
5552 
5553 /**
5554  * find_min_pfn_with_active_regions - Find the minimum PFN registered
5555  *
5556  * It returns the minimum PFN based on information provided via
5557  * memblock_set_node().
5558  */
find_min_pfn_with_active_regions(void)5559 unsigned long __init find_min_pfn_with_active_regions(void)
5560 {
5561 	return find_min_pfn_for_node(MAX_NUMNODES);
5562 }
5563 
5564 /*
5565  * early_calculate_totalpages()
5566  * Sum pages in active regions for movable zone.
5567  * Populate N_MEMORY for calculating usable_nodes.
5568  */
early_calculate_totalpages(void)5569 static unsigned long __init early_calculate_totalpages(void)
5570 {
5571 	unsigned long totalpages = 0;
5572 	unsigned long start_pfn, end_pfn;
5573 	int i, nid;
5574 
5575 	for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
5576 		unsigned long pages = end_pfn - start_pfn;
5577 
5578 		totalpages += pages;
5579 		if (pages)
5580 			node_set_state(nid, N_MEMORY);
5581 	}
5582 	return totalpages;
5583 }
5584 
5585 /*
5586  * Find the PFN the Movable zone begins in each node. Kernel memory
5587  * is spread evenly between nodes as long as the nodes have enough
5588  * memory. When they don't, some nodes will have more kernelcore than
5589  * others
5590  */
find_zone_movable_pfns_for_nodes(void)5591 static void __init find_zone_movable_pfns_for_nodes(void)
5592 {
5593 	int i, nid;
5594 	unsigned long usable_startpfn;
5595 	unsigned long kernelcore_node, kernelcore_remaining;
5596 	/* save the state before borrow the nodemask */
5597 	nodemask_t saved_node_state = node_states[N_MEMORY];
5598 	unsigned long totalpages = early_calculate_totalpages();
5599 	int usable_nodes = nodes_weight(node_states[N_MEMORY]);
5600 	struct memblock_region *r;
5601 
5602 	/* Need to find movable_zone earlier when movable_node is specified. */
5603 	find_usable_zone_for_movable();
5604 
5605 	/*
5606 	 * If movable_node is specified, ignore kernelcore and movablecore
5607 	 * options.
5608 	 */
5609 	if (movable_node_is_enabled()) {
5610 		for_each_memblock(memory, r) {
5611 			if (!memblock_is_hotpluggable(r))
5612 				continue;
5613 
5614 			nid = r->nid;
5615 
5616 			usable_startpfn = PFN_DOWN(r->base);
5617 			zone_movable_pfn[nid] = zone_movable_pfn[nid] ?
5618 				min(usable_startpfn, zone_movable_pfn[nid]) :
5619 				usable_startpfn;
5620 		}
5621 
5622 		goto out2;
5623 	}
5624 
5625 	/*
5626 	 * If movablecore=nn[KMG] was specified, calculate what size of
5627 	 * kernelcore that corresponds so that memory usable for
5628 	 * any allocation type is evenly spread. If both kernelcore
5629 	 * and movablecore are specified, then the value of kernelcore
5630 	 * will be used for required_kernelcore if it's greater than
5631 	 * what movablecore would have allowed.
5632 	 */
5633 	if (required_movablecore) {
5634 		unsigned long corepages;
5635 
5636 		/*
5637 		 * Round-up so that ZONE_MOVABLE is at least as large as what
5638 		 * was requested by the user
5639 		 */
5640 		required_movablecore =
5641 			roundup(required_movablecore, MAX_ORDER_NR_PAGES);
5642 		required_movablecore = min(totalpages, required_movablecore);
5643 		corepages = totalpages - required_movablecore;
5644 
5645 		required_kernelcore = max(required_kernelcore, corepages);
5646 	}
5647 
5648 	/*
5649 	 * If kernelcore was not specified or kernelcore size is larger
5650 	 * than totalpages, there is no ZONE_MOVABLE.
5651 	 */
5652 	if (!required_kernelcore || required_kernelcore >= totalpages)
5653 		goto out;
5654 
5655 	/* usable_startpfn is the lowest possible pfn ZONE_MOVABLE can be at */
5656 	usable_startpfn = arch_zone_lowest_possible_pfn[movable_zone];
5657 
5658 restart:
5659 	/* Spread kernelcore memory as evenly as possible throughout nodes */
5660 	kernelcore_node = required_kernelcore / usable_nodes;
5661 	for_each_node_state(nid, N_MEMORY) {
5662 		unsigned long start_pfn, end_pfn;
5663 
5664 		/*
5665 		 * Recalculate kernelcore_node if the division per node
5666 		 * now exceeds what is necessary to satisfy the requested
5667 		 * amount of memory for the kernel
5668 		 */
5669 		if (required_kernelcore < kernelcore_node)
5670 			kernelcore_node = required_kernelcore / usable_nodes;
5671 
5672 		/*
5673 		 * As the map is walked, we track how much memory is usable
5674 		 * by the kernel using kernelcore_remaining. When it is
5675 		 * 0, the rest of the node is usable by ZONE_MOVABLE
5676 		 */
5677 		kernelcore_remaining = kernelcore_node;
5678 
5679 		/* Go through each range of PFNs within this node */
5680 		for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
5681 			unsigned long size_pages;
5682 
5683 			start_pfn = max(start_pfn, zone_movable_pfn[nid]);
5684 			if (start_pfn >= end_pfn)
5685 				continue;
5686 
5687 			/* Account for what is only usable for kernelcore */
5688 			if (start_pfn < usable_startpfn) {
5689 				unsigned long kernel_pages;
5690 				kernel_pages = min(end_pfn, usable_startpfn)
5691 								- start_pfn;
5692 
5693 				kernelcore_remaining -= min(kernel_pages,
5694 							kernelcore_remaining);
5695 				required_kernelcore -= min(kernel_pages,
5696 							required_kernelcore);
5697 
5698 				/* Continue if range is now fully accounted */
5699 				if (end_pfn <= usable_startpfn) {
5700 
5701 					/*
5702 					 * Push zone_movable_pfn to the end so
5703 					 * that if we have to rebalance
5704 					 * kernelcore across nodes, we will
5705 					 * not double account here
5706 					 */
5707 					zone_movable_pfn[nid] = end_pfn;
5708 					continue;
5709 				}
5710 				start_pfn = usable_startpfn;
5711 			}
5712 
5713 			/*
5714 			 * The usable PFN range for ZONE_MOVABLE is from
5715 			 * start_pfn->end_pfn. Calculate size_pages as the
5716 			 * number of pages used as kernelcore
5717 			 */
5718 			size_pages = end_pfn - start_pfn;
5719 			if (size_pages > kernelcore_remaining)
5720 				size_pages = kernelcore_remaining;
5721 			zone_movable_pfn[nid] = start_pfn + size_pages;
5722 
5723 			/*
5724 			 * Some kernelcore has been met, update counts and
5725 			 * break if the kernelcore for this node has been
5726 			 * satisfied
5727 			 */
5728 			required_kernelcore -= min(required_kernelcore,
5729 								size_pages);
5730 			kernelcore_remaining -= size_pages;
5731 			if (!kernelcore_remaining)
5732 				break;
5733 		}
5734 	}
5735 
5736 	/*
5737 	 * If there is still required_kernelcore, we do another pass with one
5738 	 * less node in the count. This will push zone_movable_pfn[nid] further
5739 	 * along on the nodes that still have memory until kernelcore is
5740 	 * satisfied
5741 	 */
5742 	usable_nodes--;
5743 	if (usable_nodes && required_kernelcore > usable_nodes)
5744 		goto restart;
5745 
5746 out2:
5747 	/* Align start of ZONE_MOVABLE on all nids to MAX_ORDER_NR_PAGES */
5748 	for (nid = 0; nid < MAX_NUMNODES; nid++)
5749 		zone_movable_pfn[nid] =
5750 			roundup(zone_movable_pfn[nid], MAX_ORDER_NR_PAGES);
5751 
5752 out:
5753 	/* restore the node_state */
5754 	node_states[N_MEMORY] = saved_node_state;
5755 }
5756 
5757 /* Any regular or high memory on that node ? */
check_for_memory(pg_data_t * pgdat,int nid)5758 static void check_for_memory(pg_data_t *pgdat, int nid)
5759 {
5760 	enum zone_type zone_type;
5761 
5762 	if (N_MEMORY == N_NORMAL_MEMORY)
5763 		return;
5764 
5765 	for (zone_type = 0; zone_type <= ZONE_MOVABLE - 1; zone_type++) {
5766 		struct zone *zone = &pgdat->node_zones[zone_type];
5767 		if (populated_zone(zone)) {
5768 			node_set_state(nid, N_HIGH_MEMORY);
5769 			if (N_NORMAL_MEMORY != N_HIGH_MEMORY &&
5770 			    zone_type <= ZONE_NORMAL)
5771 				node_set_state(nid, N_NORMAL_MEMORY);
5772 			break;
5773 		}
5774 	}
5775 }
5776 
5777 /**
5778  * free_area_init_nodes - Initialise all pg_data_t and zone data
5779  * @max_zone_pfn: an array of max PFNs for each zone
5780  *
5781  * This will call free_area_init_node() for each active node in the system.
5782  * Using the page ranges provided by memblock_set_node(), the size of each
5783  * zone in each node and their holes is calculated. If the maximum PFN
5784  * between two adjacent zones match, it is assumed that the zone is empty.
5785  * For example, if arch_max_dma_pfn == arch_max_dma32_pfn, it is assumed
5786  * that arch_max_dma32_pfn has no pages. It is also assumed that a zone
5787  * starts where the previous one ended. For example, ZONE_DMA32 starts
5788  * at arch_max_dma_pfn.
5789  */
free_area_init_nodes(unsigned long * max_zone_pfn)5790 void __init free_area_init_nodes(unsigned long *max_zone_pfn)
5791 {
5792 	unsigned long start_pfn, end_pfn;
5793 	int i, nid;
5794 
5795 	/* Record where the zone boundaries are */
5796 	memset(arch_zone_lowest_possible_pfn, 0,
5797 				sizeof(arch_zone_lowest_possible_pfn));
5798 	memset(arch_zone_highest_possible_pfn, 0,
5799 				sizeof(arch_zone_highest_possible_pfn));
5800 
5801 	start_pfn = find_min_pfn_with_active_regions();
5802 
5803 	for (i = 0; i < MAX_NR_ZONES; i++) {
5804 		if (i == ZONE_MOVABLE)
5805 			continue;
5806 
5807 		end_pfn = max(max_zone_pfn[i], start_pfn);
5808 		arch_zone_lowest_possible_pfn[i] = start_pfn;
5809 		arch_zone_highest_possible_pfn[i] = end_pfn;
5810 
5811 		start_pfn = end_pfn;
5812 	}
5813 	arch_zone_lowest_possible_pfn[ZONE_MOVABLE] = 0;
5814 	arch_zone_highest_possible_pfn[ZONE_MOVABLE] = 0;
5815 
5816 	/* Find the PFNs that ZONE_MOVABLE begins at in each node */
5817 	memset(zone_movable_pfn, 0, sizeof(zone_movable_pfn));
5818 	find_zone_movable_pfns_for_nodes();
5819 
5820 	/* Print out the zone ranges */
5821 	pr_info("Zone ranges:\n");
5822 	for (i = 0; i < MAX_NR_ZONES; i++) {
5823 		if (i == ZONE_MOVABLE)
5824 			continue;
5825 		pr_info("  %-8s ", zone_names[i]);
5826 		if (arch_zone_lowest_possible_pfn[i] ==
5827 				arch_zone_highest_possible_pfn[i])
5828 			pr_cont("empty\n");
5829 		else
5830 			pr_cont("[mem %#018Lx-%#018Lx]\n",
5831 				(u64)arch_zone_lowest_possible_pfn[i]
5832 					<< PAGE_SHIFT,
5833 				((u64)arch_zone_highest_possible_pfn[i]
5834 					<< PAGE_SHIFT) - 1);
5835 	}
5836 
5837 	/* Print out the PFNs ZONE_MOVABLE begins at in each node */
5838 	pr_info("Movable zone start for each node\n");
5839 	for (i = 0; i < MAX_NUMNODES; i++) {
5840 		if (zone_movable_pfn[i])
5841 			pr_info("  Node %d: %#018Lx\n", i,
5842 			       (u64)zone_movable_pfn[i] << PAGE_SHIFT);
5843 	}
5844 
5845 	/* Print out the early node map */
5846 	pr_info("Early memory node ranges\n");
5847 	for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid)
5848 		pr_info("  node %3d: [mem %#018Lx-%#018Lx]\n", nid,
5849 			(u64)start_pfn << PAGE_SHIFT,
5850 			((u64)end_pfn << PAGE_SHIFT) - 1);
5851 
5852 	/* Initialise every node */
5853 	mminit_verify_pageflags_layout();
5854 	setup_nr_node_ids();
5855 	for_each_online_node(nid) {
5856 		pg_data_t *pgdat = NODE_DATA(nid);
5857 		free_area_init_node(nid, NULL,
5858 				find_min_pfn_for_node(nid), NULL);
5859 
5860 		/* Any memory on that node */
5861 		if (pgdat->node_present_pages)
5862 			node_set_state(nid, N_MEMORY);
5863 		check_for_memory(pgdat, nid);
5864 	}
5865 }
5866 
cmdline_parse_core(char * p,unsigned long * core)5867 static int __init cmdline_parse_core(char *p, unsigned long *core)
5868 {
5869 	unsigned long long coremem;
5870 	if (!p)
5871 		return -EINVAL;
5872 
5873 	coremem = memparse(p, &p);
5874 	*core = coremem >> PAGE_SHIFT;
5875 
5876 	/* Paranoid check that UL is enough for the coremem value */
5877 	WARN_ON((coremem >> PAGE_SHIFT) > ULONG_MAX);
5878 
5879 	return 0;
5880 }
5881 
5882 /*
5883  * kernelcore=size sets the amount of memory for use for allocations that
5884  * cannot be reclaimed or migrated.
5885  */
cmdline_parse_kernelcore(char * p)5886 static int __init cmdline_parse_kernelcore(char *p)
5887 {
5888 	return cmdline_parse_core(p, &required_kernelcore);
5889 }
5890 
5891 /*
5892  * movablecore=size sets the amount of memory for use for allocations that
5893  * can be reclaimed or migrated.
5894  */
cmdline_parse_movablecore(char * p)5895 static int __init cmdline_parse_movablecore(char *p)
5896 {
5897 	return cmdline_parse_core(p, &required_movablecore);
5898 }
5899 
5900 early_param("kernelcore", cmdline_parse_kernelcore);
5901 early_param("movablecore", cmdline_parse_movablecore);
5902 
5903 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
5904 
adjust_managed_page_count(struct page * page,long count)5905 void adjust_managed_page_count(struct page *page, long count)
5906 {
5907 	spin_lock(&managed_page_count_lock);
5908 	page_zone(page)->managed_pages += count;
5909 	totalram_pages += count;
5910 #ifdef CONFIG_HIGHMEM
5911 	if (PageHighMem(page))
5912 		totalhigh_pages += count;
5913 #endif
5914 	spin_unlock(&managed_page_count_lock);
5915 }
5916 EXPORT_SYMBOL(adjust_managed_page_count);
5917 
free_reserved_area(void * start,void * end,int poison,char * s)5918 unsigned long free_reserved_area(void *start, void *end, int poison, char *s)
5919 {
5920 	void *pos;
5921 	unsigned long pages = 0;
5922 
5923 	start = (void *)PAGE_ALIGN((unsigned long)start);
5924 	end = (void *)((unsigned long)end & PAGE_MASK);
5925 	for (pos = start; pos < end; pos += PAGE_SIZE, pages++) {
5926 		if ((unsigned int)poison <= 0xFF)
5927 			memset(pos, poison, PAGE_SIZE);
5928 		free_reserved_page(virt_to_page(pos));
5929 	}
5930 
5931 	if (pages && s)
5932 		pr_info("Freeing %s memory: %ldK\n",
5933 			s, pages << (PAGE_SHIFT - 10));
5934 
5935 	return pages;
5936 }
5937 EXPORT_SYMBOL(free_reserved_area);
5938 
5939 #ifdef	CONFIG_HIGHMEM
free_highmem_page(struct page * page)5940 void free_highmem_page(struct page *page)
5941 {
5942 	__free_reserved_page(page);
5943 	totalram_pages++;
5944 	page_zone(page)->managed_pages++;
5945 	totalhigh_pages++;
5946 }
5947 #endif
5948 
5949 
mem_init_print_info(const char * str)5950 void __init mem_init_print_info(const char *str)
5951 {
5952 	unsigned long physpages, codesize, datasize, rosize, bss_size;
5953 	unsigned long init_code_size, init_data_size;
5954 
5955 	physpages = get_num_physpages();
5956 	codesize = _etext - _stext;
5957 	datasize = _edata - _sdata;
5958 	rosize = __end_rodata - __start_rodata;
5959 	bss_size = __bss_stop - __bss_start;
5960 	init_data_size = __init_end - __init_begin;
5961 	init_code_size = _einittext - _sinittext;
5962 
5963 	/*
5964 	 * Detect special cases and adjust section sizes accordingly:
5965 	 * 1) .init.* may be embedded into .data sections
5966 	 * 2) .init.text.* may be out of [__init_begin, __init_end],
5967 	 *    please refer to arch/tile/kernel/vmlinux.lds.S.
5968 	 * 3) .rodata.* may be embedded into .text or .data sections.
5969 	 */
5970 #define adj_init_size(start, end, size, pos, adj) \
5971 	do { \
5972 		if (start <= pos && pos < end && size > adj) \
5973 			size -= adj; \
5974 	} while (0)
5975 
5976 	adj_init_size(__init_begin, __init_end, init_data_size,
5977 		     _sinittext, init_code_size);
5978 	adj_init_size(_stext, _etext, codesize, _sinittext, init_code_size);
5979 	adj_init_size(_sdata, _edata, datasize, __init_begin, init_data_size);
5980 	adj_init_size(_stext, _etext, codesize, __start_rodata, rosize);
5981 	adj_init_size(_sdata, _edata, datasize, __start_rodata, rosize);
5982 
5983 #undef	adj_init_size
5984 
5985 	pr_info("Memory: %luK/%luK available (%luK kernel code, %luK rwdata, %luK rodata, %luK init, %luK bss, %luK reserved, %luK cma-reserved"
5986 #ifdef	CONFIG_HIGHMEM
5987 		", %luK highmem"
5988 #endif
5989 		"%s%s)\n",
5990 		nr_free_pages() << (PAGE_SHIFT - 10),
5991 		physpages << (PAGE_SHIFT - 10),
5992 		codesize >> 10, datasize >> 10, rosize >> 10,
5993 		(init_data_size + init_code_size) >> 10, bss_size >> 10,
5994 		(physpages - totalram_pages - totalcma_pages) << (PAGE_SHIFT - 10),
5995 		totalcma_pages << (PAGE_SHIFT - 10),
5996 #ifdef	CONFIG_HIGHMEM
5997 		totalhigh_pages << (PAGE_SHIFT - 10),
5998 #endif
5999 		str ? ", " : "", str ? str : "");
6000 }
6001 
6002 /**
6003  * set_dma_reserve - set the specified number of pages reserved in the first zone
6004  * @new_dma_reserve: The number of pages to mark reserved
6005  *
6006  * The per-cpu batchsize and zone watermarks are determined by managed_pages.
6007  * In the DMA zone, a significant percentage may be consumed by kernel image
6008  * and other unfreeable allocations which can skew the watermarks badly. This
6009  * function may optionally be used to account for unfreeable pages in the
6010  * first zone (e.g., ZONE_DMA). The effect will be lower watermarks and
6011  * smaller per-cpu batchsize.
6012  */
set_dma_reserve(unsigned long new_dma_reserve)6013 void __init set_dma_reserve(unsigned long new_dma_reserve)
6014 {
6015 	dma_reserve = new_dma_reserve;
6016 }
6017 
free_area_init(unsigned long * zones_size)6018 void __init free_area_init(unsigned long *zones_size)
6019 {
6020 	free_area_init_node(0, zones_size,
6021 			__pa(PAGE_OFFSET) >> PAGE_SHIFT, NULL);
6022 }
6023 
page_alloc_cpu_notify(struct notifier_block * self,unsigned long action,void * hcpu)6024 static int page_alloc_cpu_notify(struct notifier_block *self,
6025 				 unsigned long action, void *hcpu)
6026 {
6027 	int cpu = (unsigned long)hcpu;
6028 
6029 	if (action == CPU_DEAD || action == CPU_DEAD_FROZEN) {
6030 		lru_add_drain_cpu(cpu);
6031 		drain_pages(cpu);
6032 
6033 		/*
6034 		 * Spill the event counters of the dead processor
6035 		 * into the current processors event counters.
6036 		 * This artificially elevates the count of the current
6037 		 * processor.
6038 		 */
6039 		vm_events_fold_cpu(cpu);
6040 
6041 		/*
6042 		 * Zero the differential counters of the dead processor
6043 		 * so that the vm statistics are consistent.
6044 		 *
6045 		 * This is only okay since the processor is dead and cannot
6046 		 * race with what we are doing.
6047 		 */
6048 		cpu_vm_stats_fold(cpu);
6049 	}
6050 	return NOTIFY_OK;
6051 }
6052 
page_alloc_init(void)6053 void __init page_alloc_init(void)
6054 {
6055 	hotcpu_notifier(page_alloc_cpu_notify, 0);
6056 }
6057 
6058 /*
6059  * calculate_totalreserve_pages - called when sysctl_lowmem_reserve_ratio
6060  *	or min_free_kbytes changes.
6061  */
calculate_totalreserve_pages(void)6062 static void calculate_totalreserve_pages(void)
6063 {
6064 	struct pglist_data *pgdat;
6065 	unsigned long reserve_pages = 0;
6066 	enum zone_type i, j;
6067 
6068 	for_each_online_pgdat(pgdat) {
6069 		for (i = 0; i < MAX_NR_ZONES; i++) {
6070 			struct zone *zone = pgdat->node_zones + i;
6071 			long max = 0;
6072 
6073 			/* Find valid and maximum lowmem_reserve in the zone */
6074 			for (j = i; j < MAX_NR_ZONES; j++) {
6075 				if (zone->lowmem_reserve[j] > max)
6076 					max = zone->lowmem_reserve[j];
6077 			}
6078 
6079 			/* we treat the high watermark as reserved pages. */
6080 			max += high_wmark_pages(zone);
6081 
6082 			if (max > zone->managed_pages)
6083 				max = zone->managed_pages;
6084 			reserve_pages += max;
6085 			/*
6086 			 * Lowmem reserves are not available to
6087 			 * GFP_HIGHUSER page cache allocations and
6088 			 * kswapd tries to balance zones to their high
6089 			 * watermark.  As a result, neither should be
6090 			 * regarded as dirtyable memory, to prevent a
6091 			 * situation where reclaim has to clean pages
6092 			 * in order to balance the zones.
6093 			 */
6094 			zone->dirty_balance_reserve = max;
6095 		}
6096 	}
6097 	dirty_balance_reserve = reserve_pages;
6098 	totalreserve_pages = reserve_pages;
6099 }
6100 
6101 /*
6102  * setup_per_zone_lowmem_reserve - called whenever
6103  *	sysctl_lowmem_reserve_ratio changes.  Ensures that each zone
6104  *	has a correct pages reserved value, so an adequate number of
6105  *	pages are left in the zone after a successful __alloc_pages().
6106  */
setup_per_zone_lowmem_reserve(void)6107 static void setup_per_zone_lowmem_reserve(void)
6108 {
6109 	struct pglist_data *pgdat;
6110 	enum zone_type j, idx;
6111 
6112 	for_each_online_pgdat(pgdat) {
6113 		for (j = 0; j < MAX_NR_ZONES; j++) {
6114 			struct zone *zone = pgdat->node_zones + j;
6115 			unsigned long managed_pages = zone->managed_pages;
6116 
6117 			zone->lowmem_reserve[j] = 0;
6118 
6119 			idx = j;
6120 			while (idx) {
6121 				struct zone *lower_zone;
6122 
6123 				idx--;
6124 
6125 				if (sysctl_lowmem_reserve_ratio[idx] < 1)
6126 					sysctl_lowmem_reserve_ratio[idx] = 1;
6127 
6128 				lower_zone = pgdat->node_zones + idx;
6129 				lower_zone->lowmem_reserve[j] = managed_pages /
6130 					sysctl_lowmem_reserve_ratio[idx];
6131 				managed_pages += lower_zone->managed_pages;
6132 			}
6133 		}
6134 	}
6135 
6136 	/* update totalreserve_pages */
6137 	calculate_totalreserve_pages();
6138 }
6139 
__setup_per_zone_wmarks(void)6140 static void __setup_per_zone_wmarks(void)
6141 {
6142 	unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
6143 	unsigned long pages_low = extra_free_kbytes >> (PAGE_SHIFT - 10);
6144 	unsigned long lowmem_pages = 0;
6145 	struct zone *zone;
6146 	unsigned long flags;
6147 
6148 	/* Calculate total number of !ZONE_HIGHMEM pages */
6149 	for_each_zone(zone) {
6150 		if (!is_highmem(zone))
6151 			lowmem_pages += zone->managed_pages;
6152 	}
6153 
6154 	for_each_zone(zone) {
6155 		u64 min, low;
6156 
6157 		spin_lock_irqsave(&zone->lock, flags);
6158 		min = (u64)pages_min * zone->managed_pages;
6159 		do_div(min, lowmem_pages);
6160 		low = (u64)pages_low * zone->managed_pages;
6161 		do_div(low, vm_total_pages);
6162 
6163 		if (is_highmem(zone)) {
6164 			/*
6165 			 * __GFP_HIGH and PF_MEMALLOC allocations usually don't
6166 			 * need highmem pages, so cap pages_min to a small
6167 			 * value here.
6168 			 *
6169 			 * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN)
6170 			 * deltas control asynch page reclaim, and so should
6171 			 * not be capped for highmem.
6172 			 */
6173 			unsigned long min_pages;
6174 
6175 			min_pages = zone->managed_pages / 1024;
6176 			min_pages = clamp(min_pages, SWAP_CLUSTER_MAX, 128UL);
6177 			zone->watermark[WMARK_MIN] = min_pages;
6178 		} else {
6179 			/*
6180 			 * If it's a lowmem zone, reserve a number of pages
6181 			 * proportionate to the zone's size.
6182 			 */
6183 			zone->watermark[WMARK_MIN] = min;
6184 		}
6185 
6186 		zone->watermark[WMARK_LOW]  = min_wmark_pages(zone) +
6187 					low + (min >> 2);
6188 		zone->watermark[WMARK_HIGH] = min_wmark_pages(zone) +
6189 					low + (min >> 1);
6190 
6191 		__mod_zone_page_state(zone, NR_ALLOC_BATCH,
6192 			high_wmark_pages(zone) - low_wmark_pages(zone) -
6193 			atomic_long_read(&zone->vm_stat[NR_ALLOC_BATCH]));
6194 
6195 		spin_unlock_irqrestore(&zone->lock, flags);
6196 	}
6197 
6198 	/* update totalreserve_pages */
6199 	calculate_totalreserve_pages();
6200 }
6201 
6202 /**
6203  * setup_per_zone_wmarks - called when min_free_kbytes changes
6204  * or when memory is hot-{added|removed}
6205  *
6206  * Ensures that the watermark[min,low,high] values for each zone are set
6207  * correctly with respect to min_free_kbytes.
6208  */
setup_per_zone_wmarks(void)6209 void setup_per_zone_wmarks(void)
6210 {
6211 	mutex_lock(&zonelists_mutex);
6212 	__setup_per_zone_wmarks();
6213 	mutex_unlock(&zonelists_mutex);
6214 }
6215 
6216 /*
6217  * The inactive anon list should be small enough that the VM never has to
6218  * do too much work, but large enough that each inactive page has a chance
6219  * to be referenced again before it is swapped out.
6220  *
6221  * The inactive_anon ratio is the target ratio of ACTIVE_ANON to
6222  * INACTIVE_ANON pages on this zone's LRU, maintained by the
6223  * pageout code. A zone->inactive_ratio of 3 means 3:1 or 25% of
6224  * the anonymous pages are kept on the inactive list.
6225  *
6226  * total     target    max
6227  * memory    ratio     inactive anon
6228  * -------------------------------------
6229  *   10MB       1         5MB
6230  *  100MB       1        50MB
6231  *    1GB       3       250MB
6232  *   10GB      10       0.9GB
6233  *  100GB      31         3GB
6234  *    1TB     101        10GB
6235  *   10TB     320        32GB
6236  */
calculate_zone_inactive_ratio(struct zone * zone)6237 static void __meminit calculate_zone_inactive_ratio(struct zone *zone)
6238 {
6239 	unsigned int gb, ratio;
6240 
6241 	/* Zone size in gigabytes */
6242 	gb = zone->managed_pages >> (30 - PAGE_SHIFT);
6243 	if (gb)
6244 		ratio = int_sqrt(10 * gb);
6245 	else
6246 		ratio = 1;
6247 
6248 	zone->inactive_ratio = ratio;
6249 }
6250 
setup_per_zone_inactive_ratio(void)6251 static void __meminit setup_per_zone_inactive_ratio(void)
6252 {
6253 	struct zone *zone;
6254 
6255 	for_each_zone(zone)
6256 		calculate_zone_inactive_ratio(zone);
6257 }
6258 
6259 /*
6260  * Initialise min_free_kbytes.
6261  *
6262  * For small machines we want it small (128k min).  For large machines
6263  * we want it large (64MB max).  But it is not linear, because network
6264  * bandwidth does not increase linearly with machine size.  We use
6265  *
6266  *	min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
6267  *	min_free_kbytes = sqrt(lowmem_kbytes * 16)
6268  *
6269  * which yields
6270  *
6271  * 16MB:	512k
6272  * 32MB:	724k
6273  * 64MB:	1024k
6274  * 128MB:	1448k
6275  * 256MB:	2048k
6276  * 512MB:	2896k
6277  * 1024MB:	4096k
6278  * 2048MB:	5792k
6279  * 4096MB:	8192k
6280  * 8192MB:	11584k
6281  * 16384MB:	16384k
6282  */
init_per_zone_wmark_min(void)6283 int __meminit init_per_zone_wmark_min(void)
6284 {
6285 	unsigned long lowmem_kbytes;
6286 	int new_min_free_kbytes;
6287 
6288 	lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
6289 	new_min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
6290 
6291 	if (new_min_free_kbytes > user_min_free_kbytes) {
6292 		min_free_kbytes = new_min_free_kbytes;
6293 		if (min_free_kbytes < 128)
6294 			min_free_kbytes = 128;
6295 		if (min_free_kbytes > 65536)
6296 			min_free_kbytes = 65536;
6297 	} else {
6298 		pr_warn("min_free_kbytes is not updated to %d because user defined value %d is preferred\n",
6299 				new_min_free_kbytes, user_min_free_kbytes);
6300 	}
6301 	setup_per_zone_wmarks();
6302 	refresh_zone_stat_thresholds();
6303 	setup_per_zone_lowmem_reserve();
6304 	setup_per_zone_inactive_ratio();
6305 	return 0;
6306 }
postcore_initcall(init_per_zone_wmark_min)6307 postcore_initcall(init_per_zone_wmark_min)
6308 
6309 /*
6310  * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
6311  *	that we can call two helper functions whenever min_free_kbytes
6312  *	or extra_free_kbytes changes.
6313  */
6314 int min_free_kbytes_sysctl_handler(struct ctl_table *table, int write,
6315 	void __user *buffer, size_t *length, loff_t *ppos)
6316 {
6317 	int rc;
6318 
6319 	rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
6320 	if (rc)
6321 		return rc;
6322 
6323 	if (write) {
6324 		user_min_free_kbytes = min_free_kbytes;
6325 		setup_per_zone_wmarks();
6326 	}
6327 	return 0;
6328 }
6329 
6330 #ifdef CONFIG_NUMA
sysctl_min_unmapped_ratio_sysctl_handler(struct ctl_table * table,int write,void __user * buffer,size_t * length,loff_t * ppos)6331 int sysctl_min_unmapped_ratio_sysctl_handler(struct ctl_table *table, int write,
6332 	void __user *buffer, size_t *length, loff_t *ppos)
6333 {
6334 	struct zone *zone;
6335 	int rc;
6336 
6337 	rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
6338 	if (rc)
6339 		return rc;
6340 
6341 	for_each_zone(zone)
6342 		zone->min_unmapped_pages = (zone->managed_pages *
6343 				sysctl_min_unmapped_ratio) / 100;
6344 	return 0;
6345 }
6346 
sysctl_min_slab_ratio_sysctl_handler(struct ctl_table * table,int write,void __user * buffer,size_t * length,loff_t * ppos)6347 int sysctl_min_slab_ratio_sysctl_handler(struct ctl_table *table, int write,
6348 	void __user *buffer, size_t *length, loff_t *ppos)
6349 {
6350 	struct zone *zone;
6351 	int rc;
6352 
6353 	rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
6354 	if (rc)
6355 		return rc;
6356 
6357 	for_each_zone(zone)
6358 		zone->min_slab_pages = (zone->managed_pages *
6359 				sysctl_min_slab_ratio) / 100;
6360 	return 0;
6361 }
6362 #endif
6363 
6364 /*
6365  * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
6366  *	proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
6367  *	whenever sysctl_lowmem_reserve_ratio changes.
6368  *
6369  * The reserve ratio obviously has absolutely no relation with the
6370  * minimum watermarks. The lowmem reserve ratio can only make sense
6371  * if in function of the boot time zone sizes.
6372  */
lowmem_reserve_ratio_sysctl_handler(struct ctl_table * table,int write,void __user * buffer,size_t * length,loff_t * ppos)6373 int lowmem_reserve_ratio_sysctl_handler(struct ctl_table *table, int write,
6374 	void __user *buffer, size_t *length, loff_t *ppos)
6375 {
6376 	proc_dointvec_minmax(table, write, buffer, length, ppos);
6377 	setup_per_zone_lowmem_reserve();
6378 	return 0;
6379 }
6380 
6381 /*
6382  * percpu_pagelist_fraction - changes the pcp->high for each zone on each
6383  * cpu.  It is the fraction of total pages in each zone that a hot per cpu
6384  * pagelist can have before it gets flushed back to buddy allocator.
6385  */
percpu_pagelist_fraction_sysctl_handler(struct ctl_table * table,int write,void __user * buffer,size_t * length,loff_t * ppos)6386 int percpu_pagelist_fraction_sysctl_handler(struct ctl_table *table, int write,
6387 	void __user *buffer, size_t *length, loff_t *ppos)
6388 {
6389 	struct zone *zone;
6390 	int old_percpu_pagelist_fraction;
6391 	int ret;
6392 
6393 	mutex_lock(&pcp_batch_high_lock);
6394 	old_percpu_pagelist_fraction = percpu_pagelist_fraction;
6395 
6396 	ret = proc_dointvec_minmax(table, write, buffer, length, ppos);
6397 	if (!write || ret < 0)
6398 		goto out;
6399 
6400 	/* Sanity checking to avoid pcp imbalance */
6401 	if (percpu_pagelist_fraction &&
6402 	    percpu_pagelist_fraction < MIN_PERCPU_PAGELIST_FRACTION) {
6403 		percpu_pagelist_fraction = old_percpu_pagelist_fraction;
6404 		ret = -EINVAL;
6405 		goto out;
6406 	}
6407 
6408 	/* No change? */
6409 	if (percpu_pagelist_fraction == old_percpu_pagelist_fraction)
6410 		goto out;
6411 
6412 	for_each_populated_zone(zone) {
6413 		unsigned int cpu;
6414 
6415 		for_each_possible_cpu(cpu)
6416 			pageset_set_high_and_batch(zone,
6417 					per_cpu_ptr(zone->pageset, cpu));
6418 	}
6419 out:
6420 	mutex_unlock(&pcp_batch_high_lock);
6421 	return ret;
6422 }
6423 
6424 #ifdef CONFIG_NUMA
6425 int hashdist = HASHDIST_DEFAULT;
6426 
set_hashdist(char * str)6427 static int __init set_hashdist(char *str)
6428 {
6429 	if (!str)
6430 		return 0;
6431 	hashdist = simple_strtoul(str, &str, 0);
6432 	return 1;
6433 }
6434 __setup("hashdist=", set_hashdist);
6435 #endif
6436 
6437 /*
6438  * allocate a large system hash table from bootmem
6439  * - it is assumed that the hash table must contain an exact power-of-2
6440  *   quantity of entries
6441  * - limit is the number of hash buckets, not the total allocation size
6442  */
alloc_large_system_hash(const char * tablename,unsigned long bucketsize,unsigned long numentries,int scale,int flags,unsigned int * _hash_shift,unsigned int * _hash_mask,unsigned long low_limit,unsigned long high_limit)6443 void *__init alloc_large_system_hash(const char *tablename,
6444 				     unsigned long bucketsize,
6445 				     unsigned long numentries,
6446 				     int scale,
6447 				     int flags,
6448 				     unsigned int *_hash_shift,
6449 				     unsigned int *_hash_mask,
6450 				     unsigned long low_limit,
6451 				     unsigned long high_limit)
6452 {
6453 	unsigned long long max = high_limit;
6454 	unsigned long log2qty, size;
6455 	void *table = NULL;
6456 
6457 	/* allow the kernel cmdline to have a say */
6458 	if (!numentries) {
6459 		/* round applicable memory size up to nearest megabyte */
6460 		numentries = nr_kernel_pages;
6461 
6462 		/* It isn't necessary when PAGE_SIZE >= 1MB */
6463 		if (PAGE_SHIFT < 20)
6464 			numentries = round_up(numentries, (1<<20)/PAGE_SIZE);
6465 
6466 		/* limit to 1 bucket per 2^scale bytes of low memory */
6467 		if (scale > PAGE_SHIFT)
6468 			numentries >>= (scale - PAGE_SHIFT);
6469 		else
6470 			numentries <<= (PAGE_SHIFT - scale);
6471 
6472 		/* Make sure we've got at least a 0-order allocation.. */
6473 		if (unlikely(flags & HASH_SMALL)) {
6474 			/* Makes no sense without HASH_EARLY */
6475 			WARN_ON(!(flags & HASH_EARLY));
6476 			if (!(numentries >> *_hash_shift)) {
6477 				numentries = 1UL << *_hash_shift;
6478 				BUG_ON(!numentries);
6479 			}
6480 		} else if (unlikely((numentries * bucketsize) < PAGE_SIZE))
6481 			numentries = PAGE_SIZE / bucketsize;
6482 	}
6483 	numentries = roundup_pow_of_two(numentries);
6484 
6485 	/* limit allocation size to 1/16 total memory by default */
6486 	if (max == 0) {
6487 		max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
6488 		do_div(max, bucketsize);
6489 	}
6490 	max = min(max, 0x80000000ULL);
6491 
6492 	if (numentries < low_limit)
6493 		numentries = low_limit;
6494 	if (numentries > max)
6495 		numentries = max;
6496 
6497 	log2qty = ilog2(numentries);
6498 
6499 	do {
6500 		size = bucketsize << log2qty;
6501 		if (flags & HASH_EARLY)
6502 			table = memblock_virt_alloc_nopanic(size, 0);
6503 		else if (hashdist)
6504 			table = __vmalloc(size, GFP_ATOMIC, PAGE_KERNEL);
6505 		else {
6506 			/*
6507 			 * If bucketsize is not a power-of-two, we may free
6508 			 * some pages at the end of hash table which
6509 			 * alloc_pages_exact() automatically does
6510 			 */
6511 			if (get_order(size) < MAX_ORDER) {
6512 				table = alloc_pages_exact(size, GFP_ATOMIC);
6513 				kmemleak_alloc(table, size, 1, GFP_ATOMIC);
6514 			}
6515 		}
6516 	} while (!table && size > PAGE_SIZE && --log2qty);
6517 
6518 	if (!table)
6519 		panic("Failed to allocate %s hash table\n", tablename);
6520 
6521 	printk(KERN_INFO "%s hash table entries: %ld (order: %d, %lu bytes)\n",
6522 	       tablename,
6523 	       (1UL << log2qty),
6524 	       ilog2(size) - PAGE_SHIFT,
6525 	       size);
6526 
6527 	if (_hash_shift)
6528 		*_hash_shift = log2qty;
6529 	if (_hash_mask)
6530 		*_hash_mask = (1 << log2qty) - 1;
6531 
6532 	return table;
6533 }
6534 
6535 /* Return a pointer to the bitmap storing bits affecting a block of pages */
get_pageblock_bitmap(struct zone * zone,unsigned long pfn)6536 static inline unsigned long *get_pageblock_bitmap(struct zone *zone,
6537 							unsigned long pfn)
6538 {
6539 #ifdef CONFIG_SPARSEMEM
6540 	return __pfn_to_section(pfn)->pageblock_flags;
6541 #else
6542 	return zone->pageblock_flags;
6543 #endif /* CONFIG_SPARSEMEM */
6544 }
6545 
pfn_to_bitidx(struct zone * zone,unsigned long pfn)6546 static inline int pfn_to_bitidx(struct zone *zone, unsigned long pfn)
6547 {
6548 #ifdef CONFIG_SPARSEMEM
6549 	pfn &= (PAGES_PER_SECTION-1);
6550 	return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
6551 #else
6552 	pfn = pfn - round_down(zone->zone_start_pfn, pageblock_nr_pages);
6553 	return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
6554 #endif /* CONFIG_SPARSEMEM */
6555 }
6556 
6557 /**
6558  * get_pfnblock_flags_mask - Return the requested group of flags for the pageblock_nr_pages block of pages
6559  * @page: The page within the block of interest
6560  * @pfn: The target page frame number
6561  * @end_bitidx: The last bit of interest to retrieve
6562  * @mask: mask of bits that the caller is interested in
6563  *
6564  * Return: pageblock_bits flags
6565  */
get_pfnblock_flags_mask(struct page * page,unsigned long pfn,unsigned long end_bitidx,unsigned long mask)6566 unsigned long get_pfnblock_flags_mask(struct page *page, unsigned long pfn,
6567 					unsigned long end_bitidx,
6568 					unsigned long mask)
6569 {
6570 	struct zone *zone;
6571 	unsigned long *bitmap;
6572 	unsigned long bitidx, word_bitidx;
6573 	unsigned long word;
6574 
6575 	zone = page_zone(page);
6576 	bitmap = get_pageblock_bitmap(zone, pfn);
6577 	bitidx = pfn_to_bitidx(zone, pfn);
6578 	word_bitidx = bitidx / BITS_PER_LONG;
6579 	bitidx &= (BITS_PER_LONG-1);
6580 
6581 	word = bitmap[word_bitidx];
6582 	bitidx += end_bitidx;
6583 	return (word >> (BITS_PER_LONG - bitidx - 1)) & mask;
6584 }
6585 
6586 /**
6587  * set_pfnblock_flags_mask - Set the requested group of flags for a pageblock_nr_pages block of pages
6588  * @page: The page within the block of interest
6589  * @flags: The flags to set
6590  * @pfn: The target page frame number
6591  * @end_bitidx: The last bit of interest
6592  * @mask: mask of bits that the caller is interested in
6593  */
set_pfnblock_flags_mask(struct page * page,unsigned long flags,unsigned long pfn,unsigned long end_bitidx,unsigned long mask)6594 void set_pfnblock_flags_mask(struct page *page, unsigned long flags,
6595 					unsigned long pfn,
6596 					unsigned long end_bitidx,
6597 					unsigned long mask)
6598 {
6599 	struct zone *zone;
6600 	unsigned long *bitmap;
6601 	unsigned long bitidx, word_bitidx;
6602 	unsigned long old_word, word;
6603 
6604 	BUILD_BUG_ON(NR_PAGEBLOCK_BITS != 4);
6605 
6606 	zone = page_zone(page);
6607 	bitmap = get_pageblock_bitmap(zone, pfn);
6608 	bitidx = pfn_to_bitidx(zone, pfn);
6609 	word_bitidx = bitidx / BITS_PER_LONG;
6610 	bitidx &= (BITS_PER_LONG-1);
6611 
6612 	VM_BUG_ON_PAGE(!zone_spans_pfn(zone, pfn), page);
6613 
6614 	bitidx += end_bitidx;
6615 	mask <<= (BITS_PER_LONG - bitidx - 1);
6616 	flags <<= (BITS_PER_LONG - bitidx - 1);
6617 
6618 	word = READ_ONCE(bitmap[word_bitidx]);
6619 	for (;;) {
6620 		old_word = cmpxchg(&bitmap[word_bitidx], word, (word & ~mask) | flags);
6621 		if (word == old_word)
6622 			break;
6623 		word = old_word;
6624 	}
6625 }
6626 
6627 /*
6628  * This function checks whether pageblock includes unmovable pages or not.
6629  * If @count is not zero, it is okay to include less @count unmovable pages
6630  *
6631  * PageLRU check without isolation or lru_lock could race so that
6632  * MIGRATE_MOVABLE block might include unmovable pages. It means you can't
6633  * expect this function should be exact.
6634  */
has_unmovable_pages(struct zone * zone,struct page * page,int count,bool skip_hwpoisoned_pages)6635 bool has_unmovable_pages(struct zone *zone, struct page *page, int count,
6636 			 bool skip_hwpoisoned_pages)
6637 {
6638 	unsigned long pfn, iter, found;
6639 	int mt;
6640 
6641 	/*
6642 	 * For avoiding noise data, lru_add_drain_all() should be called
6643 	 * If ZONE_MOVABLE, the zone never contains unmovable pages
6644 	 */
6645 	if (zone_idx(zone) == ZONE_MOVABLE)
6646 		return false;
6647 	mt = get_pageblock_migratetype(page);
6648 	if (mt == MIGRATE_MOVABLE || is_migrate_cma(mt))
6649 		return false;
6650 
6651 	pfn = page_to_pfn(page);
6652 	for (found = 0, iter = 0; iter < pageblock_nr_pages; iter++) {
6653 		unsigned long check = pfn + iter;
6654 
6655 		if (!pfn_valid_within(check))
6656 			continue;
6657 
6658 		page = pfn_to_page(check);
6659 
6660 		/*
6661 		 * Hugepages are not in LRU lists, but they're movable.
6662 		 * We need not scan over tail pages bacause we don't
6663 		 * handle each tail page individually in migration.
6664 		 */
6665 		if (PageHuge(page)) {
6666 			iter = round_up(iter + 1, 1<<compound_order(page)) - 1;
6667 			continue;
6668 		}
6669 
6670 		/*
6671 		 * We can't use page_count without pin a page
6672 		 * because another CPU can free compound page.
6673 		 * This check already skips compound tails of THP
6674 		 * because their page->_count is zero at all time.
6675 		 */
6676 		if (!atomic_read(&page->_count)) {
6677 			if (PageBuddy(page))
6678 				iter += (1 << page_order(page)) - 1;
6679 			continue;
6680 		}
6681 
6682 		/*
6683 		 * The HWPoisoned page may be not in buddy system, and
6684 		 * page_count() is not 0.
6685 		 */
6686 		if (skip_hwpoisoned_pages && PageHWPoison(page))
6687 			continue;
6688 
6689 		if (!PageLRU(page))
6690 			found++;
6691 		/*
6692 		 * If there are RECLAIMABLE pages, we need to check
6693 		 * it.  But now, memory offline itself doesn't call
6694 		 * shrink_node_slabs() and it still to be fixed.
6695 		 */
6696 		/*
6697 		 * If the page is not RAM, page_count()should be 0.
6698 		 * we don't need more check. This is an _used_ not-movable page.
6699 		 *
6700 		 * The problematic thing here is PG_reserved pages. PG_reserved
6701 		 * is set to both of a memory hole page and a _used_ kernel
6702 		 * page at boot.
6703 		 */
6704 		if (found > count)
6705 			return true;
6706 	}
6707 	return false;
6708 }
6709 
is_pageblock_removable_nolock(struct page * page)6710 bool is_pageblock_removable_nolock(struct page *page)
6711 {
6712 	struct zone *zone;
6713 	unsigned long pfn;
6714 
6715 	/*
6716 	 * We have to be careful here because we are iterating over memory
6717 	 * sections which are not zone aware so we might end up outside of
6718 	 * the zone but still within the section.
6719 	 * We have to take care about the node as well. If the node is offline
6720 	 * its NODE_DATA will be NULL - see page_zone.
6721 	 */
6722 	if (!node_online(page_to_nid(page)))
6723 		return false;
6724 
6725 	zone = page_zone(page);
6726 	pfn = page_to_pfn(page);
6727 	if (!zone_spans_pfn(zone, pfn))
6728 		return false;
6729 
6730 	return !has_unmovable_pages(zone, page, 0, true);
6731 }
6732 
6733 #ifdef CONFIG_CMA
6734 
pfn_max_align_down(unsigned long pfn)6735 static unsigned long pfn_max_align_down(unsigned long pfn)
6736 {
6737 	return pfn & ~(max_t(unsigned long, MAX_ORDER_NR_PAGES,
6738 			     pageblock_nr_pages) - 1);
6739 }
6740 
pfn_max_align_up(unsigned long pfn)6741 static unsigned long pfn_max_align_up(unsigned long pfn)
6742 {
6743 	return ALIGN(pfn, max_t(unsigned long, MAX_ORDER_NR_PAGES,
6744 				pageblock_nr_pages));
6745 }
6746 
6747 /* [start, end) must belong to a single zone. */
__alloc_contig_migrate_range(struct compact_control * cc,unsigned long start,unsigned long end)6748 static int __alloc_contig_migrate_range(struct compact_control *cc,
6749 					unsigned long start, unsigned long end)
6750 {
6751 	/* This function is based on compact_zone() from compaction.c. */
6752 	unsigned long nr_reclaimed;
6753 	unsigned long pfn = start;
6754 	unsigned int tries = 0;
6755 	int ret = 0;
6756 
6757 	migrate_prep();
6758 
6759 	while (pfn < end || !list_empty(&cc->migratepages)) {
6760 		if (fatal_signal_pending(current)) {
6761 			ret = -EINTR;
6762 			break;
6763 		}
6764 
6765 		if (list_empty(&cc->migratepages)) {
6766 			cc->nr_migratepages = 0;
6767 			pfn = isolate_migratepages_range(cc, pfn, end);
6768 			if (!pfn) {
6769 				ret = -EINTR;
6770 				break;
6771 			}
6772 			tries = 0;
6773 		} else if (++tries == 5) {
6774 			ret = ret < 0 ? ret : -EBUSY;
6775 			break;
6776 		}
6777 
6778 		nr_reclaimed = reclaim_clean_pages_from_list(cc->zone,
6779 							&cc->migratepages);
6780 		cc->nr_migratepages -= nr_reclaimed;
6781 
6782 		ret = migrate_pages(&cc->migratepages, alloc_migrate_target,
6783 				    NULL, 0, cc->mode, MR_CMA);
6784 	}
6785 	if (ret < 0) {
6786 		putback_movable_pages(&cc->migratepages);
6787 		return ret;
6788 	}
6789 	return 0;
6790 }
6791 
6792 /**
6793  * alloc_contig_range() -- tries to allocate given range of pages
6794  * @start:	start PFN to allocate
6795  * @end:	one-past-the-last PFN to allocate
6796  * @migratetype:	migratetype of the underlaying pageblocks (either
6797  *			#MIGRATE_MOVABLE or #MIGRATE_CMA).  All pageblocks
6798  *			in range must have the same migratetype and it must
6799  *			be either of the two.
6800  *
6801  * The PFN range does not have to be pageblock or MAX_ORDER_NR_PAGES
6802  * aligned, however it's the caller's responsibility to guarantee that
6803  * we are the only thread that changes migrate type of pageblocks the
6804  * pages fall in.
6805  *
6806  * The PFN range must belong to a single zone.
6807  *
6808  * Returns zero on success or negative error code.  On success all
6809  * pages which PFN is in [start, end) are allocated for the caller and
6810  * need to be freed with free_contig_range().
6811  */
alloc_contig_range(unsigned long start,unsigned long end,unsigned migratetype)6812 int alloc_contig_range(unsigned long start, unsigned long end,
6813 		       unsigned migratetype)
6814 {
6815 	unsigned long outer_start, outer_end;
6816 	unsigned int order;
6817 	int ret = 0;
6818 
6819 	struct compact_control cc = {
6820 		.nr_migratepages = 0,
6821 		.order = -1,
6822 		.zone = page_zone(pfn_to_page(start)),
6823 		.mode = MIGRATE_SYNC,
6824 		.ignore_skip_hint = true,
6825 	};
6826 	INIT_LIST_HEAD(&cc.migratepages);
6827 
6828 	/*
6829 	 * What we do here is we mark all pageblocks in range as
6830 	 * MIGRATE_ISOLATE.  Because pageblock and max order pages may
6831 	 * have different sizes, and due to the way page allocator
6832 	 * work, we align the range to biggest of the two pages so
6833 	 * that page allocator won't try to merge buddies from
6834 	 * different pageblocks and change MIGRATE_ISOLATE to some
6835 	 * other migration type.
6836 	 *
6837 	 * Once the pageblocks are marked as MIGRATE_ISOLATE, we
6838 	 * migrate the pages from an unaligned range (ie. pages that
6839 	 * we are interested in).  This will put all the pages in
6840 	 * range back to page allocator as MIGRATE_ISOLATE.
6841 	 *
6842 	 * When this is done, we take the pages in range from page
6843 	 * allocator removing them from the buddy system.  This way
6844 	 * page allocator will never consider using them.
6845 	 *
6846 	 * This lets us mark the pageblocks back as
6847 	 * MIGRATE_CMA/MIGRATE_MOVABLE so that free pages in the
6848 	 * aligned range but not in the unaligned, original range are
6849 	 * put back to page allocator so that buddy can use them.
6850 	 */
6851 
6852 	ret = start_isolate_page_range(pfn_max_align_down(start),
6853 				       pfn_max_align_up(end), migratetype,
6854 				       false);
6855 	if (ret)
6856 		return ret;
6857 
6858 	ret = __alloc_contig_migrate_range(&cc, start, end);
6859 	if (ret)
6860 		goto done;
6861 
6862 	/*
6863 	 * Pages from [start, end) are within a MAX_ORDER_NR_PAGES
6864 	 * aligned blocks that are marked as MIGRATE_ISOLATE.  What's
6865 	 * more, all pages in [start, end) are free in page allocator.
6866 	 * What we are going to do is to allocate all pages from
6867 	 * [start, end) (that is remove them from page allocator).
6868 	 *
6869 	 * The only problem is that pages at the beginning and at the
6870 	 * end of interesting range may be not aligned with pages that
6871 	 * page allocator holds, ie. they can be part of higher order
6872 	 * pages.  Because of this, we reserve the bigger range and
6873 	 * once this is done free the pages we are not interested in.
6874 	 *
6875 	 * We don't have to hold zone->lock here because the pages are
6876 	 * isolated thus they won't get removed from buddy.
6877 	 */
6878 
6879 	lru_add_drain_all();
6880 	drain_all_pages(cc.zone);
6881 
6882 	order = 0;
6883 	outer_start = start;
6884 	while (!PageBuddy(pfn_to_page(outer_start))) {
6885 		if (++order >= MAX_ORDER) {
6886 			ret = -EBUSY;
6887 			goto done;
6888 		}
6889 		outer_start &= ~0UL << order;
6890 	}
6891 
6892 	/* Make sure the range is really isolated. */
6893 	if (test_pages_isolated(outer_start, end, false)) {
6894 		pr_info_ratelimited("%s: [%lx, %lx) PFNs busy\n",
6895 			__func__, outer_start, end);
6896 		ret = -EBUSY;
6897 		goto done;
6898 	}
6899 
6900 	/* Grab isolated pages from freelists. */
6901 	outer_end = isolate_freepages_range(&cc, outer_start, end);
6902 	if (!outer_end) {
6903 		ret = -EBUSY;
6904 		goto done;
6905 	}
6906 
6907 	/* Free head and tail (if any) */
6908 	if (start != outer_start)
6909 		free_contig_range(outer_start, start - outer_start);
6910 	if (end != outer_end)
6911 		free_contig_range(end, outer_end - end);
6912 
6913 done:
6914 	undo_isolate_page_range(pfn_max_align_down(start),
6915 				pfn_max_align_up(end), migratetype);
6916 	return ret;
6917 }
6918 
free_contig_range(unsigned long pfn,unsigned nr_pages)6919 void free_contig_range(unsigned long pfn, unsigned nr_pages)
6920 {
6921 	unsigned int count = 0;
6922 
6923 	for (; nr_pages--; pfn++) {
6924 		struct page *page = pfn_to_page(pfn);
6925 
6926 		count += page_count(page) != 1;
6927 		__free_page(page);
6928 	}
6929 	WARN(count != 0, "%d pages are still in use!\n", count);
6930 }
6931 #endif
6932 
6933 #ifdef CONFIG_MEMORY_HOTPLUG
6934 /*
6935  * The zone indicated has a new number of managed_pages; batch sizes and percpu
6936  * page high values need to be recalulated.
6937  */
zone_pcp_update(struct zone * zone)6938 void __meminit zone_pcp_update(struct zone *zone)
6939 {
6940 	unsigned cpu;
6941 	mutex_lock(&pcp_batch_high_lock);
6942 	for_each_possible_cpu(cpu)
6943 		pageset_set_high_and_batch(zone,
6944 				per_cpu_ptr(zone->pageset, cpu));
6945 	mutex_unlock(&pcp_batch_high_lock);
6946 }
6947 #endif
6948 
zone_pcp_reset(struct zone * zone)6949 void zone_pcp_reset(struct zone *zone)
6950 {
6951 	unsigned long flags;
6952 	int cpu;
6953 	struct per_cpu_pageset *pset;
6954 
6955 	/* avoid races with drain_pages()  */
6956 	local_irq_save(flags);
6957 	if (zone->pageset != &boot_pageset) {
6958 		for_each_online_cpu(cpu) {
6959 			pset = per_cpu_ptr(zone->pageset, cpu);
6960 			drain_zonestat(zone, pset);
6961 		}
6962 		free_percpu(zone->pageset);
6963 		zone->pageset = &boot_pageset;
6964 	}
6965 	local_irq_restore(flags);
6966 }
6967 
6968 #ifdef CONFIG_MEMORY_HOTREMOVE
6969 /*
6970  * All pages in the range must be isolated before calling this.
6971  */
6972 void
__offline_isolated_pages(unsigned long start_pfn,unsigned long end_pfn)6973 __offline_isolated_pages(unsigned long start_pfn, unsigned long end_pfn)
6974 {
6975 	struct page *page;
6976 	struct zone *zone;
6977 	unsigned int order, i;
6978 	unsigned long pfn;
6979 	unsigned long flags;
6980 	/* find the first valid pfn */
6981 	for (pfn = start_pfn; pfn < end_pfn; pfn++)
6982 		if (pfn_valid(pfn))
6983 			break;
6984 	if (pfn == end_pfn)
6985 		return;
6986 	zone = page_zone(pfn_to_page(pfn));
6987 	spin_lock_irqsave(&zone->lock, flags);
6988 	pfn = start_pfn;
6989 	while (pfn < end_pfn) {
6990 		if (!pfn_valid(pfn)) {
6991 			pfn++;
6992 			continue;
6993 		}
6994 		page = pfn_to_page(pfn);
6995 		/*
6996 		 * The HWPoisoned page may be not in buddy system, and
6997 		 * page_count() is not 0.
6998 		 */
6999 		if (unlikely(!PageBuddy(page) && PageHWPoison(page))) {
7000 			pfn++;
7001 			SetPageReserved(page);
7002 			continue;
7003 		}
7004 
7005 		BUG_ON(page_count(page));
7006 		BUG_ON(!PageBuddy(page));
7007 		order = page_order(page);
7008 #ifdef CONFIG_DEBUG_VM
7009 		printk(KERN_INFO "remove from free list %lx %d %lx\n",
7010 		       pfn, 1 << order, end_pfn);
7011 #endif
7012 		list_del(&page->lru);
7013 		rmv_page_order(page);
7014 		zone->free_area[order].nr_free--;
7015 		for (i = 0; i < (1 << order); i++)
7016 			SetPageReserved((page+i));
7017 		pfn += (1 << order);
7018 	}
7019 	spin_unlock_irqrestore(&zone->lock, flags);
7020 }
7021 #endif
7022 
7023 #ifdef CONFIG_MEMORY_FAILURE
is_free_buddy_page(struct page * page)7024 bool is_free_buddy_page(struct page *page)
7025 {
7026 	struct zone *zone = page_zone(page);
7027 	unsigned long pfn = page_to_pfn(page);
7028 	unsigned long flags;
7029 	unsigned int order;
7030 
7031 	spin_lock_irqsave(&zone->lock, flags);
7032 	for (order = 0; order < MAX_ORDER; order++) {
7033 		struct page *page_head = page - (pfn & ((1 << order) - 1));
7034 
7035 		if (PageBuddy(page_head) && page_order(page_head) >= order)
7036 			break;
7037 	}
7038 	spin_unlock_irqrestore(&zone->lock, flags);
7039 
7040 	return order < MAX_ORDER;
7041 }
7042 #endif
7043