1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * linux/mm/page_alloc.c
4 *
5 * Manages the free list, the system allocates free pages here.
6 * Note that kmalloc() lives in slab.c
7 *
8 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
9 * Swap reorganised 29.12.95, Stephen Tweedie
10 * Support of BIGMEM added by Gerhard Wichert, Siemens AG, July 1999
11 * Reshaped it to be a zoned allocator, Ingo Molnar, Red Hat, 1999
12 * Discontiguous memory support, Kanoj Sarcar, SGI, Nov 1999
13 * Zone balancing, Kanoj Sarcar, SGI, Jan 2000
14 * Per cpu hot/cold page lists, bulk allocation, Martin J. Bligh, Sept 2002
15 * (lots of bits borrowed from Ingo Molnar & Andrew Morton)
16 */
17
18 #include <linux/stddef.h>
19 #include <linux/mm.h>
20 #include <linux/highmem.h>
21 #include <linux/swap.h>
22 #include <linux/interrupt.h>
23 #include <linux/pagemap.h>
24 #include <linux/jiffies.h>
25 #include <linux/memblock.h>
26 #include <linux/compiler.h>
27 #include <linux/kernel.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/topology.h>
37 #include <linux/sysctl.h>
38 #include <linux/cpu.h>
39 #include <linux/cpuset.h>
40 #include <linux/memory_hotplug.h>
41 #include <linux/nodemask.h>
42 #include <linux/vmalloc.h>
43 #include <linux/vmstat.h>
44 #include <linux/mempolicy.h>
45 #include <linux/memremap.h>
46 #include <linux/stop_machine.h>
47 #include <linux/random.h>
48 #include <linux/sort.h>
49 #include <linux/pfn.h>
50 #include <linux/backing-dev.h>
51 #include <linux/fault-inject.h>
52 #include <linux/page-isolation.h>
53 #include <linux/debugobjects.h>
54 #include <linux/kmemleak.h>
55 #include <linux/compaction.h>
56 #include <trace/events/kmem.h>
57 #include <trace/events/oom.h>
58 #include <linux/prefetch.h>
59 #include <linux/mm_inline.h>
60 #include <linux/migrate.h>
61 #include <linux/hugetlb.h>
62 #include <linux/sched/rt.h>
63 #include <linux/sched/mm.h>
64 #include <linux/page_owner.h>
65 #include <linux/page_pinner.h>
66 #include <linux/kthread.h>
67 #include <linux/memcontrol.h>
68 #include <linux/ftrace.h>
69 #include <linux/lockdep.h>
70 #include <linux/nmi.h>
71 #include <linux/psi.h>
72 #include <linux/padata.h>
73 #include <linux/khugepaged.h>
74 #include <trace/hooks/mm.h>
75 #include <trace/hooks/vmscan.h>
76
77 #include <asm/sections.h>
78 #include <asm/tlbflush.h>
79 #include <asm/div64.h>
80 #include "internal.h"
81 #include "shuffle.h"
82 #include "page_reporting.h"
83
84 /* Free Page Internal flags: for internal, non-pcp variants of free_pages(). */
85 typedef int __bitwise fpi_t;
86
87 /* No special request */
88 #define FPI_NONE ((__force fpi_t)0)
89
90 /*
91 * Skip free page reporting notification for the (possibly merged) page.
92 * This does not hinder free page reporting from grabbing the page,
93 * reporting it and marking it "reported" - it only skips notifying
94 * the free page reporting infrastructure about a newly freed page. For
95 * example, used when temporarily pulling a page from a freelist and
96 * putting it back unmodified.
97 */
98 #define FPI_SKIP_REPORT_NOTIFY ((__force fpi_t)BIT(0))
99
100 /*
101 * Place the (possibly merged) page to the tail of the freelist. Will ignore
102 * page shuffling (relevant code - e.g., memory onlining - is expected to
103 * shuffle the whole zone).
104 *
105 * Note: No code should rely on this flag for correctness - it's purely
106 * to allow for optimizations when handing back either fresh pages
107 * (memory onlining) or untouched pages (page isolation, free page
108 * reporting).
109 */
110 #define FPI_TO_TAIL ((__force fpi_t)BIT(1))
111
112 /*
113 * Don't poison memory with KASAN (only for the tag-based modes).
114 * During boot, all non-reserved memblock memory is exposed to page_alloc.
115 * Poisoning all that memory lengthens boot time, especially on systems with
116 * large amount of RAM. This flag is used to skip that poisoning.
117 * This is only done for the tag-based KASAN modes, as those are able to
118 * detect memory corruptions with the memory tags assigned by default.
119 * All memory allocated normally after boot gets poisoned as usual.
120 */
121 #define FPI_SKIP_KASAN_POISON ((__force fpi_t)BIT(2))
122
123 /* prevent >1 _updater_ of zone percpu pageset ->high and ->batch fields */
124 static DEFINE_MUTEX(pcp_batch_high_lock);
125 #define MIN_PERCPU_PAGELIST_FRACTION (8)
126
127 #ifdef CONFIG_USE_PERCPU_NUMA_NODE_ID
128 DEFINE_PER_CPU(int, numa_node);
129 EXPORT_PER_CPU_SYMBOL(numa_node);
130 #endif
131
132 DEFINE_STATIC_KEY_TRUE(vm_numa_stat_key);
133
134 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
135 /*
136 * N.B., Do NOT reference the '_numa_mem_' per cpu variable directly.
137 * It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined.
138 * Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem()
139 * defined in <linux/topology.h>.
140 */
141 DEFINE_PER_CPU(int, _numa_mem_); /* Kernel "local memory" node */
142 EXPORT_PER_CPU_SYMBOL(_numa_mem_);
143 #endif
144
145 /* work_structs for global per-cpu drains */
146 struct pcpu_drain {
147 struct zone *zone;
148 struct work_struct work;
149 };
150 static DEFINE_MUTEX(pcpu_drain_mutex);
151 static DEFINE_PER_CPU(struct pcpu_drain, pcpu_drain);
152
153 #ifdef CONFIG_GCC_PLUGIN_LATENT_ENTROPY
154 volatile unsigned long latent_entropy __latent_entropy;
155 EXPORT_SYMBOL(latent_entropy);
156 #endif
157
158 /*
159 * Array of node states.
160 */
161 nodemask_t node_states[NR_NODE_STATES] __read_mostly = {
162 [N_POSSIBLE] = NODE_MASK_ALL,
163 [N_ONLINE] = { { [0] = 1UL } },
164 #ifndef CONFIG_NUMA
165 [N_NORMAL_MEMORY] = { { [0] = 1UL } },
166 #ifdef CONFIG_HIGHMEM
167 [N_HIGH_MEMORY] = { { [0] = 1UL } },
168 #endif
169 [N_MEMORY] = { { [0] = 1UL } },
170 [N_CPU] = { { [0] = 1UL } },
171 #endif /* NUMA */
172 };
173 EXPORT_SYMBOL(node_states);
174
175 atomic_long_t _totalram_pages __read_mostly;
176 EXPORT_SYMBOL(_totalram_pages);
177 unsigned long totalreserve_pages __read_mostly;
178 unsigned long totalcma_pages __read_mostly;
179
180 int percpu_pagelist_fraction;
181 gfp_t gfp_allowed_mask __read_mostly = GFP_BOOT_MASK;
182 DEFINE_STATIC_KEY_FALSE(init_on_alloc);
183 EXPORT_SYMBOL(init_on_alloc);
184
185 DEFINE_STATIC_KEY_FALSE(init_on_free);
186 EXPORT_SYMBOL(init_on_free);
187
188 static bool _init_on_alloc_enabled_early __read_mostly
189 = IS_ENABLED(CONFIG_INIT_ON_ALLOC_DEFAULT_ON);
early_init_on_alloc(char * buf)190 static int __init early_init_on_alloc(char *buf)
191 {
192
193 return kstrtobool(buf, &_init_on_alloc_enabled_early);
194 }
195 early_param("init_on_alloc", early_init_on_alloc);
196
197 static bool _init_on_free_enabled_early __read_mostly
198 = IS_ENABLED(CONFIG_INIT_ON_FREE_DEFAULT_ON);
early_init_on_free(char * buf)199 static int __init early_init_on_free(char *buf)
200 {
201 return kstrtobool(buf, &_init_on_free_enabled_early);
202 }
203 early_param("init_on_free", early_init_on_free);
204
205 /*
206 * A cached value of the page's pageblock's migratetype, used when the page is
207 * put on a pcplist. Used to avoid the pageblock migratetype lookup when
208 * freeing from pcplists in most cases, at the cost of possibly becoming stale.
209 * Also the migratetype set in the page does not necessarily match the pcplist
210 * index, e.g. page might have MIGRATE_CMA set but be on a pcplist with any
211 * other index - this ensures that it will be put on the correct CMA freelist.
212 */
get_pcppage_migratetype(struct page * page)213 static inline int get_pcppage_migratetype(struct page *page)
214 {
215 return page->index;
216 }
217
set_pcppage_migratetype(struct page * page,int migratetype)218 static inline void set_pcppage_migratetype(struct page *page, int migratetype)
219 {
220 page->index = migratetype;
221 }
222
223 #ifdef CONFIG_PM_SLEEP
224 /*
225 * The following functions are used by the suspend/hibernate code to temporarily
226 * change gfp_allowed_mask in order to avoid using I/O during memory allocations
227 * while devices are suspended. To avoid races with the suspend/hibernate code,
228 * they should always be called with system_transition_mutex held
229 * (gfp_allowed_mask also should only be modified with system_transition_mutex
230 * held, unless the suspend/hibernate code is guaranteed not to run in parallel
231 * with that modification).
232 */
233
234 static gfp_t saved_gfp_mask;
235
pm_restore_gfp_mask(void)236 void pm_restore_gfp_mask(void)
237 {
238 WARN_ON(!mutex_is_locked(&system_transition_mutex));
239 if (saved_gfp_mask) {
240 gfp_allowed_mask = saved_gfp_mask;
241 saved_gfp_mask = 0;
242 }
243 }
244
pm_restrict_gfp_mask(void)245 void pm_restrict_gfp_mask(void)
246 {
247 WARN_ON(!mutex_is_locked(&system_transition_mutex));
248 WARN_ON(saved_gfp_mask);
249 saved_gfp_mask = gfp_allowed_mask;
250 gfp_allowed_mask &= ~(__GFP_IO | __GFP_FS);
251 }
252
pm_suspended_storage(void)253 bool pm_suspended_storage(void)
254 {
255 if ((gfp_allowed_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
256 return false;
257 return true;
258 }
259 #endif /* CONFIG_PM_SLEEP */
260
261 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
262 unsigned int pageblock_order __read_mostly;
263 #endif
264
265 static void __free_pages_ok(struct page *page, unsigned int order,
266 fpi_t fpi_flags);
267
268 /*
269 * results with 256, 32 in the lowmem_reserve sysctl:
270 * 1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
271 * 1G machine -> (16M dma, 784M normal, 224M high)
272 * NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
273 * HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
274 * HIGHMEM allocation will leave (224M+784M)/256 of ram reserved in ZONE_DMA
275 *
276 * TBD: should special case ZONE_DMA32 machines here - in those we normally
277 * don't need any ZONE_NORMAL reservation
278 */
279 int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES] = {
280 #ifdef CONFIG_ZONE_DMA
281 [ZONE_DMA] = 256,
282 #endif
283 #ifdef CONFIG_ZONE_DMA32
284 [ZONE_DMA32] = 256,
285 #endif
286 [ZONE_NORMAL] = 32,
287 #ifdef CONFIG_HIGHMEM
288 [ZONE_HIGHMEM] = 0,
289 #endif
290 [ZONE_MOVABLE] = 0,
291 };
292
293 static char * const zone_names[MAX_NR_ZONES] = {
294 #ifdef CONFIG_ZONE_DMA
295 "DMA",
296 #endif
297 #ifdef CONFIG_ZONE_DMA32
298 "DMA32",
299 #endif
300 "Normal",
301 #ifdef CONFIG_HIGHMEM
302 "HighMem",
303 #endif
304 "Movable",
305 #ifdef CONFIG_ZONE_DEVICE
306 "Device",
307 #endif
308 };
309
310 const char * const migratetype_names[MIGRATE_TYPES] = {
311 "Unmovable",
312 "Movable",
313 "Reclaimable",
314 #ifdef CONFIG_CMA
315 "CMA",
316 #endif
317 "HighAtomic",
318 #ifdef CONFIG_MEMORY_ISOLATION
319 "Isolate",
320 #endif
321 };
322
323 compound_page_dtor * const compound_page_dtors[NR_COMPOUND_DTORS] = {
324 [NULL_COMPOUND_DTOR] = NULL,
325 [COMPOUND_PAGE_DTOR] = free_compound_page,
326 #ifdef CONFIG_HUGETLB_PAGE
327 [HUGETLB_PAGE_DTOR] = free_huge_page,
328 #endif
329 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
330 [TRANSHUGE_PAGE_DTOR] = free_transhuge_page,
331 #endif
332 };
333
334 /*
335 * Try to keep at least this much lowmem free. Do not allow normal
336 * allocations below this point, only high priority ones. Automatically
337 * tuned according to the amount of memory in the system.
338 */
339 int min_free_kbytes = 1024;
340 int user_min_free_kbytes = -1;
341 #ifdef CONFIG_DISCONTIGMEM
342 /*
343 * DiscontigMem defines memory ranges as separate pg_data_t even if the ranges
344 * are not on separate NUMA nodes. Functionally this works but with
345 * watermark_boost_factor, it can reclaim prematurely as the ranges can be
346 * quite small. By default, do not boost watermarks on discontigmem as in
347 * many cases very high-order allocations like THP are likely to be
348 * unsupported and the premature reclaim offsets the advantage of long-term
349 * fragmentation avoidance.
350 */
351 int watermark_boost_factor __read_mostly;
352 #else
353 int watermark_boost_factor __read_mostly = 15000;
354 #endif
355 int watermark_scale_factor = 10;
356
357 /*
358 * Extra memory for the system to try freeing. Used to temporarily
359 * free memory, to make space for new workloads. Anyone can allocate
360 * down to the min watermarks controlled by min_free_kbytes above.
361 */
362 int extra_free_kbytes = 0;
363
364 static unsigned long nr_kernel_pages __initdata;
365 static unsigned long nr_all_pages __initdata;
366 static unsigned long dma_reserve __initdata;
367
368 static unsigned long arch_zone_lowest_possible_pfn[MAX_NR_ZONES] __initdata;
369 static unsigned long arch_zone_highest_possible_pfn[MAX_NR_ZONES] __initdata;
370 static unsigned long required_kernelcore __initdata;
371 static unsigned long required_kernelcore_percent __initdata;
372 static unsigned long required_movablecore __initdata;
373 static unsigned long required_movablecore_percent __initdata;
374 static unsigned long zone_movable_pfn[MAX_NUMNODES] __initdata;
375 static bool mirrored_kernelcore __meminitdata;
376
377 /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
378 int movable_zone;
379 EXPORT_SYMBOL(movable_zone);
380
381 #if MAX_NUMNODES > 1
382 unsigned int nr_node_ids __read_mostly = MAX_NUMNODES;
383 unsigned int nr_online_nodes __read_mostly = 1;
384 EXPORT_SYMBOL(nr_node_ids);
385 EXPORT_SYMBOL(nr_online_nodes);
386 #endif
387
388 int page_group_by_mobility_disabled __read_mostly;
389
390 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
391 /*
392 * During boot we initialize deferred pages on-demand, as needed, but once
393 * page_alloc_init_late() has finished, the deferred pages are all initialized,
394 * and we can permanently disable that path.
395 */
396 static DEFINE_STATIC_KEY_TRUE(deferred_pages);
397
398 /*
399 * Calling kasan_poison_pages() only after deferred memory initialization
400 * has completed. Poisoning pages during deferred memory init will greatly
401 * lengthen the process and cause problem in large memory systems as the
402 * deferred pages initialization is done with interrupt disabled.
403 *
404 * Assuming that there will be no reference to those newly initialized
405 * pages before they are ever allocated, this should have no effect on
406 * KASAN memory tracking as the poison will be properly inserted at page
407 * allocation time. The only corner case is when pages are allocated by
408 * on-demand allocation and then freed again before the deferred pages
409 * initialization is done, but this is not likely to happen.
410 */
should_skip_kasan_poison(struct page * page,fpi_t fpi_flags)411 static inline bool should_skip_kasan_poison(struct page *page, fpi_t fpi_flags)
412 {
413 return static_branch_unlikely(&deferred_pages) ||
414 (!IS_ENABLED(CONFIG_KASAN_GENERIC) &&
415 (fpi_flags & FPI_SKIP_KASAN_POISON)) ||
416 PageSkipKASanPoison(page);
417 }
418
419 /* Returns true if the struct page for the pfn is uninitialised */
early_page_uninitialised(unsigned long pfn)420 static inline bool __meminit early_page_uninitialised(unsigned long pfn)
421 {
422 int nid = early_pfn_to_nid(pfn);
423
424 if (node_online(nid) && pfn >= NODE_DATA(nid)->first_deferred_pfn)
425 return true;
426
427 return false;
428 }
429
430 /*
431 * Returns true when the remaining initialisation should be deferred until
432 * later in the boot cycle when it can be parallelised.
433 */
434 static bool __meminit
defer_init(int nid,unsigned long pfn,unsigned long end_pfn)435 defer_init(int nid, unsigned long pfn, unsigned long end_pfn)
436 {
437 static unsigned long prev_end_pfn, nr_initialised;
438
439 /*
440 * prev_end_pfn static that contains the end of previous zone
441 * No need to protect because called very early in boot before smp_init.
442 */
443 if (prev_end_pfn != end_pfn) {
444 prev_end_pfn = end_pfn;
445 nr_initialised = 0;
446 }
447
448 /* Always populate low zones for address-constrained allocations */
449 if (end_pfn < pgdat_end_pfn(NODE_DATA(nid)))
450 return false;
451
452 if (NODE_DATA(nid)->first_deferred_pfn != ULONG_MAX)
453 return true;
454 /*
455 * We start only with one section of pages, more pages are added as
456 * needed until the rest of deferred pages are initialized.
457 */
458 nr_initialised++;
459 if ((nr_initialised > PAGES_PER_SECTION) &&
460 (pfn & (PAGES_PER_SECTION - 1)) == 0) {
461 NODE_DATA(nid)->first_deferred_pfn = pfn;
462 return true;
463 }
464 return false;
465 }
466 #else
should_skip_kasan_poison(struct page * page,fpi_t fpi_flags)467 static inline bool should_skip_kasan_poison(struct page *page, fpi_t fpi_flags)
468 {
469 return (!IS_ENABLED(CONFIG_KASAN_GENERIC) &&
470 (fpi_flags & FPI_SKIP_KASAN_POISON)) ||
471 PageSkipKASanPoison(page);
472 }
473
early_page_uninitialised(unsigned long pfn)474 static inline bool early_page_uninitialised(unsigned long pfn)
475 {
476 return false;
477 }
478
defer_init(int nid,unsigned long pfn,unsigned long end_pfn)479 static inline bool defer_init(int nid, unsigned long pfn, unsigned long end_pfn)
480 {
481 return false;
482 }
483 #endif
484
485 /* Return a pointer to the bitmap storing bits affecting a block of pages */
get_pageblock_bitmap(struct page * page,unsigned long pfn)486 static inline unsigned long *get_pageblock_bitmap(struct page *page,
487 unsigned long pfn)
488 {
489 #ifdef CONFIG_SPARSEMEM
490 return section_to_usemap(__pfn_to_section(pfn));
491 #else
492 return page_zone(page)->pageblock_flags;
493 #endif /* CONFIG_SPARSEMEM */
494 }
495
pfn_to_bitidx(struct page * page,unsigned long pfn)496 static inline int pfn_to_bitidx(struct page *page, unsigned long pfn)
497 {
498 #ifdef CONFIG_SPARSEMEM
499 pfn &= (PAGES_PER_SECTION-1);
500 #else
501 pfn = pfn - round_down(page_zone(page)->zone_start_pfn, pageblock_nr_pages);
502 #endif /* CONFIG_SPARSEMEM */
503 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
504 }
505
506 /**
507 * get_pfnblock_flags_mask - Return the requested group of flags for the pageblock_nr_pages block of pages
508 * @page: The page within the block of interest
509 * @pfn: The target page frame number
510 * @mask: mask of bits that the caller is interested in
511 *
512 * Return: pageblock_bits flags
513 */
514 static __always_inline
__get_pfnblock_flags_mask(struct page * page,unsigned long pfn,unsigned long mask)515 unsigned long __get_pfnblock_flags_mask(struct page *page,
516 unsigned long pfn,
517 unsigned long mask)
518 {
519 unsigned long *bitmap;
520 unsigned long bitidx, word_bitidx;
521 unsigned long word;
522
523 bitmap = get_pageblock_bitmap(page, pfn);
524 bitidx = pfn_to_bitidx(page, pfn);
525 word_bitidx = bitidx / BITS_PER_LONG;
526 bitidx &= (BITS_PER_LONG-1);
527
528 word = bitmap[word_bitidx];
529 return (word >> bitidx) & mask;
530 }
531
get_pfnblock_flags_mask(struct page * page,unsigned long pfn,unsigned long mask)532 unsigned long get_pfnblock_flags_mask(struct page *page, unsigned long pfn,
533 unsigned long mask)
534 {
535 return __get_pfnblock_flags_mask(page, pfn, mask);
536 }
537 EXPORT_SYMBOL_GPL(get_pfnblock_flags_mask);
538
isolate_anon_lru_page(struct page * page)539 int isolate_anon_lru_page(struct page *page)
540 {
541 int ret;
542
543 if (!PageLRU(page) || !PageAnon(page))
544 return -EINVAL;
545
546 if (!get_page_unless_zero(page))
547 return -EINVAL;
548
549 ret = isolate_lru_page(page);
550 put_page(page);
551
552 return ret;
553 }
554 EXPORT_SYMBOL_GPL(isolate_anon_lru_page);
555
get_pfnblock_migratetype(struct page * page,unsigned long pfn)556 static __always_inline int get_pfnblock_migratetype(struct page *page, unsigned long pfn)
557 {
558 return __get_pfnblock_flags_mask(page, pfn, MIGRATETYPE_MASK);
559 }
560
561 /**
562 * set_pfnblock_flags_mask - Set the requested group of flags for a pageblock_nr_pages block of pages
563 * @page: The page within the block of interest
564 * @flags: The flags to set
565 * @pfn: The target page frame number
566 * @mask: mask of bits that the caller is interested in
567 */
set_pfnblock_flags_mask(struct page * page,unsigned long flags,unsigned long pfn,unsigned long mask)568 void set_pfnblock_flags_mask(struct page *page, unsigned long flags,
569 unsigned long pfn,
570 unsigned long mask)
571 {
572 unsigned long *bitmap;
573 unsigned long bitidx, word_bitidx;
574 unsigned long old_word, word;
575
576 BUILD_BUG_ON(NR_PAGEBLOCK_BITS != 4);
577 BUILD_BUG_ON(MIGRATE_TYPES > (1 << PB_migratetype_bits));
578
579 bitmap = get_pageblock_bitmap(page, pfn);
580 bitidx = pfn_to_bitidx(page, pfn);
581 word_bitidx = bitidx / BITS_PER_LONG;
582 bitidx &= (BITS_PER_LONG-1);
583
584 VM_BUG_ON_PAGE(!zone_spans_pfn(page_zone(page), pfn), page);
585
586 mask <<= bitidx;
587 flags <<= bitidx;
588
589 word = READ_ONCE(bitmap[word_bitidx]);
590 for (;;) {
591 old_word = cmpxchg(&bitmap[word_bitidx], word, (word & ~mask) | flags);
592 if (word == old_word)
593 break;
594 word = old_word;
595 }
596 }
597
set_pageblock_migratetype(struct page * page,int migratetype)598 void set_pageblock_migratetype(struct page *page, int migratetype)
599 {
600 if (unlikely(page_group_by_mobility_disabled &&
601 migratetype < MIGRATE_PCPTYPES))
602 migratetype = MIGRATE_UNMOVABLE;
603
604 set_pfnblock_flags_mask(page, (unsigned long)migratetype,
605 page_to_pfn(page), MIGRATETYPE_MASK);
606 }
607
608 #ifdef CONFIG_DEBUG_VM
page_outside_zone_boundaries(struct zone * zone,struct page * page)609 static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
610 {
611 int ret = 0;
612 unsigned seq;
613 unsigned long pfn = page_to_pfn(page);
614 unsigned long sp, start_pfn;
615
616 do {
617 seq = zone_span_seqbegin(zone);
618 start_pfn = zone->zone_start_pfn;
619 sp = zone->spanned_pages;
620 if (!zone_spans_pfn(zone, pfn))
621 ret = 1;
622 } while (zone_span_seqretry(zone, seq));
623
624 if (ret)
625 pr_err("page 0x%lx outside node %d zone %s [ 0x%lx - 0x%lx ]\n",
626 pfn, zone_to_nid(zone), zone->name,
627 start_pfn, start_pfn + sp);
628
629 return ret;
630 }
631
page_is_consistent(struct zone * zone,struct page * page)632 static int page_is_consistent(struct zone *zone, struct page *page)
633 {
634 if (!pfn_valid_within(page_to_pfn(page)))
635 return 0;
636 if (zone != page_zone(page))
637 return 0;
638
639 return 1;
640 }
641 /*
642 * Temporary debugging check for pages not lying within a given zone.
643 */
bad_range(struct zone * zone,struct page * page)644 static int __maybe_unused bad_range(struct zone *zone, struct page *page)
645 {
646 if (page_outside_zone_boundaries(zone, page))
647 return 1;
648 if (!page_is_consistent(zone, page))
649 return 1;
650
651 return 0;
652 }
653 #else
bad_range(struct zone * zone,struct page * page)654 static inline int __maybe_unused bad_range(struct zone *zone, struct page *page)
655 {
656 return 0;
657 }
658 #endif
659
bad_page(struct page * page,const char * reason)660 static void bad_page(struct page *page, const char *reason)
661 {
662 static unsigned long resume;
663 static unsigned long nr_shown;
664 static unsigned long nr_unshown;
665
666 /*
667 * Allow a burst of 60 reports, then keep quiet for that minute;
668 * or allow a steady drip of one report per second.
669 */
670 if (nr_shown == 60) {
671 if (time_before(jiffies, resume)) {
672 nr_unshown++;
673 goto out;
674 }
675 if (nr_unshown) {
676 pr_alert(
677 "BUG: Bad page state: %lu messages suppressed\n",
678 nr_unshown);
679 nr_unshown = 0;
680 }
681 nr_shown = 0;
682 }
683 if (nr_shown++ == 0)
684 resume = jiffies + 60 * HZ;
685
686 pr_alert("BUG: Bad page state in process %s pfn:%05lx\n",
687 current->comm, page_to_pfn(page));
688 __dump_page(page, reason);
689 dump_page_owner(page);
690
691 print_modules();
692 dump_stack();
693 out:
694 /* Leave bad fields for debug, except PageBuddy could make trouble */
695 page_mapcount_reset(page); /* remove PageBuddy */
696 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
697 }
698
699 /*
700 * Higher-order pages are called "compound pages". They are structured thusly:
701 *
702 * The first PAGE_SIZE page is called the "head page" and have PG_head set.
703 *
704 * The remaining PAGE_SIZE pages are called "tail pages". PageTail() is encoded
705 * in bit 0 of page->compound_head. The rest of bits is pointer to head page.
706 *
707 * The first tail page's ->compound_dtor holds the offset in array of compound
708 * page destructors. See compound_page_dtors.
709 *
710 * The first tail page's ->compound_order holds the order of allocation.
711 * This usage means that zero-order pages may not be compound.
712 */
713
free_compound_page(struct page * page)714 void free_compound_page(struct page *page)
715 {
716 mem_cgroup_uncharge(page);
717 __free_pages_ok(page, compound_order(page), FPI_NONE);
718 }
719
prep_compound_page(struct page * page,unsigned int order)720 void prep_compound_page(struct page *page, unsigned int order)
721 {
722 int i;
723 int nr_pages = 1 << order;
724
725 __SetPageHead(page);
726 for (i = 1; i < nr_pages; i++) {
727 struct page *p = page + i;
728 set_page_count(p, 0);
729 p->mapping = TAIL_MAPPING;
730 set_compound_head(p, page);
731 }
732
733 set_compound_page_dtor(page, COMPOUND_PAGE_DTOR);
734 set_compound_order(page, order);
735 atomic_set(compound_mapcount_ptr(page), -1);
736 if (hpage_pincount_available(page))
737 atomic_set(compound_pincount_ptr(page), 0);
738 }
739
740 #ifdef CONFIG_DEBUG_PAGEALLOC
741 unsigned int _debug_guardpage_minorder;
742
743 bool _debug_pagealloc_enabled_early __read_mostly
744 = IS_ENABLED(CONFIG_DEBUG_PAGEALLOC_ENABLE_DEFAULT);
745 EXPORT_SYMBOL(_debug_pagealloc_enabled_early);
746 DEFINE_STATIC_KEY_FALSE(_debug_pagealloc_enabled);
747 EXPORT_SYMBOL(_debug_pagealloc_enabled);
748
749 DEFINE_STATIC_KEY_FALSE(_debug_guardpage_enabled);
750
early_debug_pagealloc(char * buf)751 static int __init early_debug_pagealloc(char *buf)
752 {
753 return kstrtobool(buf, &_debug_pagealloc_enabled_early);
754 }
755 early_param("debug_pagealloc", early_debug_pagealloc);
756
debug_guardpage_minorder_setup(char * buf)757 static int __init debug_guardpage_minorder_setup(char *buf)
758 {
759 unsigned long res;
760
761 if (kstrtoul(buf, 10, &res) < 0 || res > MAX_ORDER / 2) {
762 pr_err("Bad debug_guardpage_minorder value\n");
763 return 0;
764 }
765 _debug_guardpage_minorder = res;
766 pr_info("Setting debug_guardpage_minorder to %lu\n", res);
767 return 0;
768 }
769 early_param("debug_guardpage_minorder", debug_guardpage_minorder_setup);
770
set_page_guard(struct zone * zone,struct page * page,unsigned int order,int migratetype)771 static inline bool set_page_guard(struct zone *zone, struct page *page,
772 unsigned int order, int migratetype)
773 {
774 if (!debug_guardpage_enabled())
775 return false;
776
777 if (order >= debug_guardpage_minorder())
778 return false;
779
780 __SetPageGuard(page);
781 INIT_LIST_HEAD(&page->lru);
782 set_page_private(page, order);
783 /* Guard pages are not available for any usage */
784 __mod_zone_freepage_state(zone, -(1 << order), migratetype);
785
786 return true;
787 }
788
clear_page_guard(struct zone * zone,struct page * page,unsigned int order,int migratetype)789 static inline void clear_page_guard(struct zone *zone, struct page *page,
790 unsigned int order, int migratetype)
791 {
792 if (!debug_guardpage_enabled())
793 return;
794
795 __ClearPageGuard(page);
796
797 set_page_private(page, 0);
798 if (!is_migrate_isolate(migratetype))
799 __mod_zone_freepage_state(zone, (1 << order), migratetype);
800 }
801 #else
set_page_guard(struct zone * zone,struct page * page,unsigned int order,int migratetype)802 static inline bool set_page_guard(struct zone *zone, struct page *page,
803 unsigned int order, int migratetype) { return false; }
clear_page_guard(struct zone * zone,struct page * page,unsigned int order,int migratetype)804 static inline void clear_page_guard(struct zone *zone, struct page *page,
805 unsigned int order, int migratetype) {}
806 #endif
807
808 /*
809 * Enable static keys related to various memory debugging and hardening options.
810 * Some override others, and depend on early params that are evaluated in the
811 * order of appearance. So we need to first gather the full picture of what was
812 * enabled, and then make decisions.
813 */
init_mem_debugging_and_hardening(void)814 void init_mem_debugging_and_hardening(void)
815 {
816 bool page_poisoning_requested = false;
817
818 #ifdef CONFIG_PAGE_POISONING
819 /*
820 * Page poisoning is debug page alloc for some arches. If
821 * either of those options are enabled, enable poisoning.
822 */
823 if (page_poisoning_enabled() ||
824 (!IS_ENABLED(CONFIG_ARCH_SUPPORTS_DEBUG_PAGEALLOC) &&
825 debug_pagealloc_enabled())) {
826 static_branch_enable(&_page_poisoning_enabled);
827 page_poisoning_requested = true;
828 }
829 #endif
830
831 if (_init_on_alloc_enabled_early) {
832 if (page_poisoning_requested)
833 pr_info("mem auto-init: CONFIG_PAGE_POISONING is on, "
834 "will take precedence over init_on_alloc\n");
835 else
836 static_branch_enable(&init_on_alloc);
837 }
838 if (_init_on_free_enabled_early) {
839 if (page_poisoning_requested)
840 pr_info("mem auto-init: CONFIG_PAGE_POISONING is on, "
841 "will take precedence over init_on_free\n");
842 else
843 static_branch_enable(&init_on_free);
844 }
845
846 #ifdef CONFIG_DEBUG_PAGEALLOC
847 if (!debug_pagealloc_enabled())
848 return;
849
850 static_branch_enable(&_debug_pagealloc_enabled);
851
852 if (!debug_guardpage_minorder())
853 return;
854
855 static_branch_enable(&_debug_guardpage_enabled);
856 #endif
857 }
858
set_buddy_order(struct page * page,unsigned int order)859 static inline void set_buddy_order(struct page *page, unsigned int order)
860 {
861 set_page_private(page, order);
862 __SetPageBuddy(page);
863 }
864
865 /*
866 * This function checks whether a page is free && is the buddy
867 * we can coalesce a page and its buddy if
868 * (a) the buddy is not in a hole (check before calling!) &&
869 * (b) the buddy is in the buddy system &&
870 * (c) a page and its buddy have the same order &&
871 * (d) a page and its buddy are in the same zone.
872 *
873 * For recording whether a page is in the buddy system, we set PageBuddy.
874 * Setting, clearing, and testing PageBuddy is serialized by zone->lock.
875 *
876 * For recording page's order, we use page_private(page).
877 */
page_is_buddy(struct page * page,struct page * buddy,unsigned int order)878 static inline bool page_is_buddy(struct page *page, struct page *buddy,
879 unsigned int order)
880 {
881 if (!page_is_guard(buddy) && !PageBuddy(buddy))
882 return false;
883
884 if (buddy_order(buddy) != order)
885 return false;
886
887 /*
888 * zone check is done late to avoid uselessly calculating
889 * zone/node ids for pages that could never merge.
890 */
891 if (page_zone_id(page) != page_zone_id(buddy))
892 return false;
893
894 VM_BUG_ON_PAGE(page_count(buddy) != 0, buddy);
895
896 return true;
897 }
898
899 #ifdef CONFIG_COMPACTION
task_capc(struct zone * zone)900 static inline struct capture_control *task_capc(struct zone *zone)
901 {
902 struct capture_control *capc = current->capture_control;
903
904 return unlikely(capc) &&
905 !(current->flags & PF_KTHREAD) &&
906 !capc->page &&
907 capc->cc->zone == zone ? capc : NULL;
908 }
909
910 static inline bool
compaction_capture(struct capture_control * capc,struct page * page,int order,int migratetype)911 compaction_capture(struct capture_control *capc, struct page *page,
912 int order, int migratetype)
913 {
914 if (!capc || order != capc->cc->order)
915 return false;
916
917 /* Do not accidentally pollute CMA or isolated regions*/
918 if (is_migrate_cma(migratetype) ||
919 is_migrate_isolate(migratetype))
920 return false;
921
922 /*
923 * Do not let lower order allocations polluate a movable pageblock.
924 * This might let an unmovable request use a reclaimable pageblock
925 * and vice-versa but no more than normal fallback logic which can
926 * have trouble finding a high-order free page.
927 */
928 if (order < pageblock_order && migratetype == MIGRATE_MOVABLE)
929 return false;
930
931 capc->page = page;
932 return true;
933 }
934
935 #else
task_capc(struct zone * zone)936 static inline struct capture_control *task_capc(struct zone *zone)
937 {
938 return NULL;
939 }
940
941 static inline bool
compaction_capture(struct capture_control * capc,struct page * page,int order,int migratetype)942 compaction_capture(struct capture_control *capc, struct page *page,
943 int order, int migratetype)
944 {
945 return false;
946 }
947 #endif /* CONFIG_COMPACTION */
948
949 /* Used for pages not on another list */
add_to_free_list(struct page * page,struct zone * zone,unsigned int order,int migratetype)950 static inline void add_to_free_list(struct page *page, struct zone *zone,
951 unsigned int order, int migratetype)
952 {
953 struct free_area *area = &zone->free_area[order];
954
955 list_add(&page->lru, &area->free_list[migratetype]);
956 area->nr_free++;
957 }
958
959 /* Used for pages not on another list */
add_to_free_list_tail(struct page * page,struct zone * zone,unsigned int order,int migratetype)960 static inline void add_to_free_list_tail(struct page *page, struct zone *zone,
961 unsigned int order, int migratetype)
962 {
963 struct free_area *area = &zone->free_area[order];
964
965 list_add_tail(&page->lru, &area->free_list[migratetype]);
966 area->nr_free++;
967 }
968
969 /*
970 * Used for pages which are on another list. Move the pages to the tail
971 * of the list - so the moved pages won't immediately be considered for
972 * allocation again (e.g., optimization for memory onlining).
973 */
move_to_free_list(struct page * page,struct zone * zone,unsigned int order,int migratetype)974 static inline void move_to_free_list(struct page *page, struct zone *zone,
975 unsigned int order, int migratetype)
976 {
977 struct free_area *area = &zone->free_area[order];
978
979 list_move_tail(&page->lru, &area->free_list[migratetype]);
980 }
981
del_page_from_free_list(struct page * page,struct zone * zone,unsigned int order)982 static inline void del_page_from_free_list(struct page *page, struct zone *zone,
983 unsigned int order)
984 {
985 /* clear reported state and update reported page count */
986 if (page_reported(page))
987 __ClearPageReported(page);
988
989 list_del(&page->lru);
990 __ClearPageBuddy(page);
991 set_page_private(page, 0);
992 zone->free_area[order].nr_free--;
993 }
994
995 /*
996 * If this is not the largest possible page, check if the buddy
997 * of the next-highest order is free. If it is, it's possible
998 * that pages are being freed that will coalesce soon. In case,
999 * that is happening, add the free page to the tail of the list
1000 * so it's less likely to be used soon and more likely to be merged
1001 * as a higher order page
1002 */
1003 static inline bool
buddy_merge_likely(unsigned long pfn,unsigned long buddy_pfn,struct page * page,unsigned int order)1004 buddy_merge_likely(unsigned long pfn, unsigned long buddy_pfn,
1005 struct page *page, unsigned int order)
1006 {
1007 struct page *higher_page, *higher_buddy;
1008 unsigned long combined_pfn;
1009
1010 if (order >= MAX_ORDER - 2)
1011 return false;
1012
1013 if (!pfn_valid_within(buddy_pfn))
1014 return false;
1015
1016 combined_pfn = buddy_pfn & pfn;
1017 higher_page = page + (combined_pfn - pfn);
1018 buddy_pfn = __find_buddy_pfn(combined_pfn, order + 1);
1019 higher_buddy = higher_page + (buddy_pfn - combined_pfn);
1020
1021 return pfn_valid_within(buddy_pfn) &&
1022 page_is_buddy(higher_page, higher_buddy, order + 1);
1023 }
1024
1025 /*
1026 * Freeing function for a buddy system allocator.
1027 *
1028 * The concept of a buddy system is to maintain direct-mapped table
1029 * (containing bit values) for memory blocks of various "orders".
1030 * The bottom level table contains the map for the smallest allocatable
1031 * units of memory (here, pages), and each level above it describes
1032 * pairs of units from the levels below, hence, "buddies".
1033 * At a high level, all that happens here is marking the table entry
1034 * at the bottom level available, and propagating the changes upward
1035 * as necessary, plus some accounting needed to play nicely with other
1036 * parts of the VM system.
1037 * At each level, we keep a list of pages, which are heads of continuous
1038 * free pages of length of (1 << order) and marked with PageBuddy.
1039 * Page's order is recorded in page_private(page) field.
1040 * So when we are allocating or freeing one, we can derive the state of the
1041 * other. That is, if we allocate a small block, and both were
1042 * free, the remainder of the region must be split into blocks.
1043 * If a block is freed, and its buddy is also free, then this
1044 * triggers coalescing into a block of larger size.
1045 *
1046 * -- nyc
1047 */
1048
__free_one_page(struct page * page,unsigned long pfn,struct zone * zone,unsigned int order,int migratetype,fpi_t fpi_flags)1049 static inline void __free_one_page(struct page *page,
1050 unsigned long pfn,
1051 struct zone *zone, unsigned int order,
1052 int migratetype, fpi_t fpi_flags)
1053 {
1054 struct capture_control *capc = task_capc(zone);
1055 unsigned long buddy_pfn;
1056 unsigned long combined_pfn;
1057 unsigned int max_order;
1058 struct page *buddy;
1059 bool to_tail;
1060
1061 max_order = min_t(unsigned int, MAX_ORDER - 1, pageblock_order);
1062
1063 VM_BUG_ON(!zone_is_initialized(zone));
1064 VM_BUG_ON_PAGE(page->flags & PAGE_FLAGS_CHECK_AT_PREP, page);
1065
1066 VM_BUG_ON(migratetype == -1);
1067 if (likely(!is_migrate_isolate(migratetype)))
1068 __mod_zone_freepage_state(zone, 1 << order, migratetype);
1069
1070 VM_BUG_ON_PAGE(pfn & ((1 << order) - 1), page);
1071 VM_BUG_ON_PAGE(bad_range(zone, page), page);
1072
1073 continue_merging:
1074 while (order < max_order) {
1075 if (compaction_capture(capc, page, order, migratetype)) {
1076 __mod_zone_freepage_state(zone, -(1 << order),
1077 migratetype);
1078 return;
1079 }
1080 buddy_pfn = __find_buddy_pfn(pfn, order);
1081 buddy = page + (buddy_pfn - pfn);
1082
1083 if (!pfn_valid_within(buddy_pfn))
1084 goto done_merging;
1085 if (!page_is_buddy(page, buddy, order))
1086 goto done_merging;
1087 /*
1088 * Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page,
1089 * merge with it and move up one order.
1090 */
1091 if (page_is_guard(buddy))
1092 clear_page_guard(zone, buddy, order, migratetype);
1093 else
1094 del_page_from_free_list(buddy, zone, order);
1095 combined_pfn = buddy_pfn & pfn;
1096 page = page + (combined_pfn - pfn);
1097 pfn = combined_pfn;
1098 order++;
1099 }
1100 if (order < MAX_ORDER - 1) {
1101 /* If we are here, it means order is >= pageblock_order.
1102 * We want to prevent merge between freepages on isolate
1103 * pageblock and normal pageblock. Without this, pageblock
1104 * isolation could cause incorrect freepage or CMA accounting.
1105 *
1106 * We don't want to hit this code for the more frequent
1107 * low-order merging.
1108 */
1109 if (unlikely(has_isolate_pageblock(zone))) {
1110 int buddy_mt;
1111
1112 buddy_pfn = __find_buddy_pfn(pfn, order);
1113 buddy = page + (buddy_pfn - pfn);
1114 buddy_mt = get_pageblock_migratetype(buddy);
1115
1116 if (migratetype != buddy_mt
1117 && (is_migrate_isolate(migratetype) ||
1118 is_migrate_isolate(buddy_mt)))
1119 goto done_merging;
1120 }
1121 max_order = order + 1;
1122 goto continue_merging;
1123 }
1124
1125 done_merging:
1126 set_buddy_order(page, order);
1127
1128 if (fpi_flags & FPI_TO_TAIL)
1129 to_tail = true;
1130 else if (is_shuffle_order(order))
1131 to_tail = shuffle_pick_tail();
1132 else
1133 to_tail = buddy_merge_likely(pfn, buddy_pfn, page, order);
1134
1135 if (to_tail)
1136 add_to_free_list_tail(page, zone, order, migratetype);
1137 else
1138 add_to_free_list(page, zone, order, migratetype);
1139
1140 /* Notify page reporting subsystem of freed page */
1141 if (!(fpi_flags & FPI_SKIP_REPORT_NOTIFY))
1142 page_reporting_notify_free(order);
1143 }
1144
1145 /*
1146 * A bad page could be due to a number of fields. Instead of multiple branches,
1147 * try and check multiple fields with one check. The caller must do a detailed
1148 * check if necessary.
1149 */
page_expected_state(struct page * page,unsigned long check_flags)1150 static inline bool page_expected_state(struct page *page,
1151 unsigned long check_flags)
1152 {
1153 if (unlikely(atomic_read(&page->_mapcount) != -1))
1154 return false;
1155
1156 if (unlikely((unsigned long)page->mapping |
1157 page_ref_count(page) |
1158 #ifdef CONFIG_MEMCG
1159 (unsigned long)page->mem_cgroup |
1160 #endif
1161 (page->flags & check_flags)))
1162 return false;
1163
1164 return true;
1165 }
1166
page_bad_reason(struct page * page,unsigned long flags)1167 static const char *page_bad_reason(struct page *page, unsigned long flags)
1168 {
1169 const char *bad_reason = NULL;
1170
1171 if (unlikely(atomic_read(&page->_mapcount) != -1))
1172 bad_reason = "nonzero mapcount";
1173 if (unlikely(page->mapping != NULL))
1174 bad_reason = "non-NULL mapping";
1175 if (unlikely(page_ref_count(page) != 0))
1176 bad_reason = "nonzero _refcount";
1177 if (unlikely(page->flags & flags)) {
1178 if (flags == PAGE_FLAGS_CHECK_AT_PREP)
1179 bad_reason = "PAGE_FLAGS_CHECK_AT_PREP flag(s) set";
1180 else
1181 bad_reason = "PAGE_FLAGS_CHECK_AT_FREE flag(s) set";
1182 }
1183 #ifdef CONFIG_MEMCG
1184 if (unlikely(page->mem_cgroup))
1185 bad_reason = "page still charged to cgroup";
1186 #endif
1187 return bad_reason;
1188 }
1189
check_free_page_bad(struct page * page)1190 static void check_free_page_bad(struct page *page)
1191 {
1192 bad_page(page,
1193 page_bad_reason(page, PAGE_FLAGS_CHECK_AT_FREE));
1194 }
1195
check_free_page(struct page * page)1196 static inline int check_free_page(struct page *page)
1197 {
1198 if (likely(page_expected_state(page, PAGE_FLAGS_CHECK_AT_FREE)))
1199 return 0;
1200
1201 /* Something has gone sideways, find it */
1202 check_free_page_bad(page);
1203 return 1;
1204 }
1205
free_tail_pages_check(struct page * head_page,struct page * page)1206 static int free_tail_pages_check(struct page *head_page, struct page *page)
1207 {
1208 int ret = 1;
1209
1210 /*
1211 * We rely page->lru.next never has bit 0 set, unless the page
1212 * is PageTail(). Let's make sure that's true even for poisoned ->lru.
1213 */
1214 BUILD_BUG_ON((unsigned long)LIST_POISON1 & 1);
1215
1216 if (!IS_ENABLED(CONFIG_DEBUG_VM)) {
1217 ret = 0;
1218 goto out;
1219 }
1220 switch (page - head_page) {
1221 case 1:
1222 /* the first tail page: ->mapping may be compound_mapcount() */
1223 if (unlikely(compound_mapcount(page))) {
1224 bad_page(page, "nonzero compound_mapcount");
1225 goto out;
1226 }
1227 break;
1228 case 2:
1229 /*
1230 * the second tail page: ->mapping is
1231 * deferred_list.next -- ignore value.
1232 */
1233 break;
1234 default:
1235 if (page->mapping != TAIL_MAPPING) {
1236 bad_page(page, "corrupted mapping in tail page");
1237 goto out;
1238 }
1239 break;
1240 }
1241 if (unlikely(!PageTail(page))) {
1242 bad_page(page, "PageTail not set");
1243 goto out;
1244 }
1245 if (unlikely(compound_head(page) != head_page)) {
1246 bad_page(page, "compound_head not consistent");
1247 goto out;
1248 }
1249 ret = 0;
1250 out:
1251 page->mapping = NULL;
1252 clear_compound_head(page);
1253 return ret;
1254 }
1255
kernel_init_free_pages(struct page * page,int numpages,bool zero_tags)1256 static void kernel_init_free_pages(struct page *page, int numpages, bool zero_tags)
1257 {
1258 int i;
1259
1260 if (zero_tags) {
1261 for (i = 0; i < numpages; i++)
1262 tag_clear_highpage(page + i);
1263 return;
1264 }
1265
1266 /* s390's use of memset() could override KASAN redzones. */
1267 kasan_disable_current();
1268 for (i = 0; i < numpages; i++) {
1269 u8 tag = page_kasan_tag(page + i);
1270 page_kasan_tag_reset(page + i);
1271 clear_highpage(page + i);
1272 page_kasan_tag_set(page + i, tag);
1273 }
1274 kasan_enable_current();
1275 }
1276
free_pages_prepare(struct page * page,unsigned int order,bool check_free,fpi_t fpi_flags)1277 static __always_inline bool free_pages_prepare(struct page *page,
1278 unsigned int order, bool check_free, fpi_t fpi_flags)
1279 {
1280 int bad = 0;
1281 bool skip_kasan_poison = should_skip_kasan_poison(page, fpi_flags);
1282
1283 VM_BUG_ON_PAGE(PageTail(page), page);
1284
1285 trace_mm_page_free(page, order);
1286
1287 if (unlikely(PageHWPoison(page)) && !order) {
1288 /*
1289 * Do not let hwpoison pages hit pcplists/buddy
1290 * Untie memcg state and reset page's owner
1291 */
1292 if (memcg_kmem_enabled() && PageKmemcg(page))
1293 __memcg_kmem_uncharge_page(page, order);
1294 reset_page_owner(page, order);
1295 free_page_pinner(page, order);
1296 return false;
1297 }
1298
1299 /*
1300 * Check tail pages before head page information is cleared to
1301 * avoid checking PageCompound for order-0 pages.
1302 */
1303 if (unlikely(order)) {
1304 bool compound = PageCompound(page);
1305 int i;
1306
1307 VM_BUG_ON_PAGE(compound && compound_order(page) != order, page);
1308
1309 if (compound)
1310 ClearPageDoubleMap(page);
1311 for (i = 1; i < (1 << order); i++) {
1312 if (compound)
1313 bad += free_tail_pages_check(page, page + i);
1314 if (unlikely(check_free_page(page + i))) {
1315 bad++;
1316 continue;
1317 }
1318 (page + i)->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
1319 }
1320 }
1321 if (PageMappingFlags(page))
1322 page->mapping = NULL;
1323 if (memcg_kmem_enabled() && PageKmemcg(page))
1324 __memcg_kmem_uncharge_page(page, order);
1325 if (check_free)
1326 bad += check_free_page(page);
1327 if (bad)
1328 return false;
1329
1330 page_cpupid_reset_last(page);
1331 page->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
1332 reset_page_owner(page, order);
1333 free_page_pinner(page, order);
1334
1335 if (!PageHighMem(page)) {
1336 debug_check_no_locks_freed(page_address(page),
1337 PAGE_SIZE << order);
1338 debug_check_no_obj_freed(page_address(page),
1339 PAGE_SIZE << order);
1340 }
1341
1342 kernel_poison_pages(page, 1 << order);
1343
1344 /*
1345 * As memory initialization might be integrated into KASAN,
1346 * kasan_free_pages and kernel_init_free_pages must be
1347 * kept together to avoid discrepancies in behavior.
1348 *
1349 * With hardware tag-based KASAN, memory tags must be set before the
1350 * page becomes unavailable via debug_pagealloc or arch_free_page.
1351 */
1352 if (kasan_has_integrated_init()) {
1353 if (!skip_kasan_poison)
1354 kasan_free_pages(page, order);
1355 } else {
1356 bool init = want_init_on_free();
1357
1358 if (init)
1359 kernel_init_free_pages(page, 1 << order, false);
1360 if (!skip_kasan_poison)
1361 kasan_poison_pages(page, order, init);
1362 }
1363
1364 /*
1365 * arch_free_page() can make the page's contents inaccessible. s390
1366 * does this. So nothing which can access the page's contents should
1367 * happen after this.
1368 */
1369 arch_free_page(page, order);
1370
1371 debug_pagealloc_unmap_pages(page, 1 << order);
1372
1373 return true;
1374 }
1375
1376 #ifdef CONFIG_DEBUG_VM
1377 /*
1378 * With DEBUG_VM enabled, order-0 pages are checked immediately when being freed
1379 * to pcp lists. With debug_pagealloc also enabled, they are also rechecked when
1380 * moved from pcp lists to free lists.
1381 */
free_pcp_prepare(struct page * page)1382 static bool free_pcp_prepare(struct page *page)
1383 {
1384 return free_pages_prepare(page, 0, true, FPI_NONE);
1385 }
1386
bulkfree_pcp_prepare(struct page * page)1387 static bool bulkfree_pcp_prepare(struct page *page)
1388 {
1389 if (debug_pagealloc_enabled_static())
1390 return check_free_page(page);
1391 else
1392 return false;
1393 }
1394 #else
1395 /*
1396 * With DEBUG_VM disabled, order-0 pages being freed are checked only when
1397 * moving from pcp lists to free list in order to reduce overhead. With
1398 * debug_pagealloc enabled, they are checked also immediately when being freed
1399 * to the pcp lists.
1400 */
free_pcp_prepare(struct page * page)1401 static bool free_pcp_prepare(struct page *page)
1402 {
1403 if (debug_pagealloc_enabled_static())
1404 return free_pages_prepare(page, 0, true, FPI_NONE);
1405 else
1406 return free_pages_prepare(page, 0, false, FPI_NONE);
1407 }
1408
bulkfree_pcp_prepare(struct page * page)1409 static bool bulkfree_pcp_prepare(struct page *page)
1410 {
1411 return check_free_page(page);
1412 }
1413 #endif /* CONFIG_DEBUG_VM */
1414
prefetch_buddy(struct page * page)1415 static inline void prefetch_buddy(struct page *page)
1416 {
1417 unsigned long pfn = page_to_pfn(page);
1418 unsigned long buddy_pfn = __find_buddy_pfn(pfn, 0);
1419 struct page *buddy = page + (buddy_pfn - pfn);
1420
1421 prefetch(buddy);
1422 }
1423
1424 /*
1425 * Frees a number of pages from the PCP lists
1426 * Assumes all pages on list are in same zone, and of same order.
1427 * count is the number of pages to free.
1428 *
1429 * If the zone was previously in an "all pages pinned" state then look to
1430 * see if this freeing clears that state.
1431 *
1432 * And clear the zone's pages_scanned counter, to hold off the "all pages are
1433 * pinned" detection logic.
1434 */
free_pcppages_bulk(struct zone * zone,int count,struct per_cpu_pages * pcp)1435 static void free_pcppages_bulk(struct zone *zone, int count,
1436 struct per_cpu_pages *pcp)
1437 {
1438 int migratetype = 0;
1439 int batch_free = 0;
1440 int prefetch_nr = 0;
1441 bool isolated_pageblocks;
1442 struct page *page, *tmp;
1443 LIST_HEAD(head);
1444
1445 /*
1446 * Ensure proper count is passed which otherwise would stuck in the
1447 * below while (list_empty(list)) loop.
1448 */
1449 count = min(pcp->count, count);
1450 while (count) {
1451 struct list_head *list;
1452
1453 /*
1454 * Remove pages from lists in a round-robin fashion. A
1455 * batch_free count is maintained that is incremented when an
1456 * empty list is encountered. This is so more pages are freed
1457 * off fuller lists instead of spinning excessively around empty
1458 * lists
1459 */
1460 do {
1461 batch_free++;
1462 if (++migratetype == MIGRATE_PCPTYPES)
1463 migratetype = 0;
1464 list = &pcp->lists[migratetype];
1465 } while (list_empty(list));
1466
1467 /* This is the only non-empty list. Free them all. */
1468 if (batch_free == MIGRATE_PCPTYPES)
1469 batch_free = count;
1470
1471 do {
1472 page = list_last_entry(list, struct page, lru);
1473 /* must delete to avoid corrupting pcp list */
1474 list_del(&page->lru);
1475 pcp->count--;
1476
1477 if (bulkfree_pcp_prepare(page))
1478 continue;
1479
1480 list_add_tail(&page->lru, &head);
1481
1482 /*
1483 * We are going to put the page back to the global
1484 * pool, prefetch its buddy to speed up later access
1485 * under zone->lock. It is believed the overhead of
1486 * an additional test and calculating buddy_pfn here
1487 * can be offset by reduced memory latency later. To
1488 * avoid excessive prefetching due to large count, only
1489 * prefetch buddy for the first pcp->batch nr of pages.
1490 */
1491 if (prefetch_nr++ < pcp->batch)
1492 prefetch_buddy(page);
1493 } while (--count && --batch_free && !list_empty(list));
1494 }
1495
1496 spin_lock(&zone->lock);
1497 isolated_pageblocks = has_isolate_pageblock(zone);
1498
1499 /*
1500 * Use safe version since after __free_one_page(),
1501 * page->lru.next will not point to original list.
1502 */
1503 list_for_each_entry_safe(page, tmp, &head, lru) {
1504 int mt = get_pcppage_migratetype(page);
1505 /* MIGRATE_ISOLATE page should not go to pcplists */
1506 VM_BUG_ON_PAGE(is_migrate_isolate(mt), page);
1507 /* Pageblock could have been isolated meanwhile */
1508 if (unlikely(isolated_pageblocks))
1509 mt = get_pageblock_migratetype(page);
1510
1511 __free_one_page(page, page_to_pfn(page), zone, 0, mt, FPI_NONE);
1512 trace_mm_page_pcpu_drain(page, 0, mt);
1513 }
1514 spin_unlock(&zone->lock);
1515 }
1516
free_one_page(struct zone * zone,struct page * page,unsigned long pfn,unsigned int order,int migratetype,fpi_t fpi_flags)1517 static void free_one_page(struct zone *zone,
1518 struct page *page, unsigned long pfn,
1519 unsigned int order,
1520 int migratetype, fpi_t fpi_flags)
1521 {
1522 spin_lock(&zone->lock);
1523 if (unlikely(has_isolate_pageblock(zone) ||
1524 is_migrate_isolate(migratetype))) {
1525 migratetype = get_pfnblock_migratetype(page, pfn);
1526 }
1527 __free_one_page(page, pfn, zone, order, migratetype, fpi_flags);
1528 spin_unlock(&zone->lock);
1529 }
1530
__init_single_page(struct page * page,unsigned long pfn,unsigned long zone,int nid,bool zero_page_struct __maybe_unused)1531 static void __meminit __init_single_page(struct page *page, unsigned long pfn,
1532 unsigned long zone, int nid,
1533 bool zero_page_struct __maybe_unused)
1534 {
1535 #ifdef CONFIG_ROCKCHIP_THUNDER_BOOT
1536 if (zero_page_struct)
1537 mm_zero_struct_page(page);
1538 #else
1539 mm_zero_struct_page(page);
1540 #endif
1541 set_page_links(page, zone, nid, pfn);
1542 init_page_count(page);
1543 page_mapcount_reset(page);
1544 page_cpupid_reset_last(page);
1545 page_kasan_tag_reset(page);
1546
1547 INIT_LIST_HEAD(&page->lru);
1548 #ifdef WANT_PAGE_VIRTUAL
1549 /* The shift won't overflow because ZONE_NORMAL is below 4G. */
1550 if (!is_highmem_idx(zone))
1551 set_page_address(page, __va(pfn << PAGE_SHIFT));
1552 #endif
1553 }
1554
1555 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
init_reserved_page(unsigned long pfn)1556 static void __meminit init_reserved_page(unsigned long pfn)
1557 {
1558 pg_data_t *pgdat;
1559 int nid, zid;
1560
1561 if (!early_page_uninitialised(pfn))
1562 return;
1563
1564 nid = early_pfn_to_nid(pfn);
1565 pgdat = NODE_DATA(nid);
1566
1567 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1568 struct zone *zone = &pgdat->node_zones[zid];
1569
1570 if (pfn >= zone->zone_start_pfn && pfn < zone_end_pfn(zone))
1571 break;
1572 }
1573 __init_single_page(pfn_to_page(pfn), pfn, zid, nid, true);
1574 }
1575 #else
init_reserved_page(unsigned long pfn)1576 static inline void init_reserved_page(unsigned long pfn)
1577 {
1578 }
1579 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
1580
1581 /*
1582 * Initialised pages do not have PageReserved set. This function is
1583 * called for each range allocated by the bootmem allocator and
1584 * marks the pages PageReserved. The remaining valid pages are later
1585 * sent to the buddy page allocator.
1586 */
reserve_bootmem_region(phys_addr_t start,phys_addr_t end)1587 void __meminit reserve_bootmem_region(phys_addr_t start, phys_addr_t end)
1588 {
1589 unsigned long start_pfn = PFN_DOWN(start);
1590 unsigned long end_pfn = PFN_UP(end);
1591
1592 for (; start_pfn < end_pfn; start_pfn++) {
1593 if (pfn_valid(start_pfn)) {
1594 struct page *page = pfn_to_page(start_pfn);
1595
1596 init_reserved_page(start_pfn);
1597
1598 /* Avoid false-positive PageTail() */
1599 INIT_LIST_HEAD(&page->lru);
1600
1601 /*
1602 * no need for atomic set_bit because the struct
1603 * page is not visible yet so nobody should
1604 * access it yet.
1605 */
1606 __SetPageReserved(page);
1607 }
1608 }
1609 }
1610
__free_pages_ok(struct page * page,unsigned int order,fpi_t fpi_flags)1611 static void __free_pages_ok(struct page *page, unsigned int order,
1612 fpi_t fpi_flags)
1613 {
1614 unsigned long flags;
1615 int migratetype;
1616 unsigned long pfn = page_to_pfn(page);
1617
1618 if (!free_pages_prepare(page, order, true, fpi_flags))
1619 return;
1620
1621 migratetype = get_pfnblock_migratetype(page, pfn);
1622 local_irq_save(flags);
1623 __count_vm_events(PGFREE, 1 << order);
1624 free_one_page(page_zone(page), page, pfn, order, migratetype,
1625 fpi_flags);
1626 local_irq_restore(flags);
1627 }
1628
__free_pages_core(struct page * page,unsigned int order)1629 void __free_pages_core(struct page *page, unsigned int order)
1630 {
1631 unsigned int nr_pages = 1 << order;
1632 struct page *p = page;
1633 unsigned int loop;
1634
1635 /*
1636 * When initializing the memmap, __init_single_page() sets the refcount
1637 * of all pages to 1 ("allocated"/"not free"). We have to set the
1638 * refcount of all involved pages to 0.
1639 */
1640 prefetchw(p);
1641 for (loop = 0; loop < (nr_pages - 1); loop++, p++) {
1642 prefetchw(p + 1);
1643 __ClearPageReserved(p);
1644 set_page_count(p, 0);
1645 }
1646 __ClearPageReserved(p);
1647 set_page_count(p, 0);
1648
1649 atomic_long_add(nr_pages, &page_zone(page)->managed_pages);
1650
1651 /*
1652 * Bypass PCP and place fresh pages right to the tail, primarily
1653 * relevant for memory onlining.
1654 */
1655 __free_pages_ok(page, order, FPI_TO_TAIL | FPI_SKIP_KASAN_POISON);
1656 }
1657
1658 #ifdef CONFIG_NEED_MULTIPLE_NODES
1659
1660 static struct mminit_pfnnid_cache early_pfnnid_cache __meminitdata;
1661
1662 #ifndef CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID
1663
1664 /*
1665 * Required by SPARSEMEM. Given a PFN, return what node the PFN is on.
1666 */
__early_pfn_to_nid(unsigned long pfn,struct mminit_pfnnid_cache * state)1667 int __meminit __early_pfn_to_nid(unsigned long pfn,
1668 struct mminit_pfnnid_cache *state)
1669 {
1670 unsigned long start_pfn, end_pfn;
1671 int nid;
1672
1673 if (state->last_start <= pfn && pfn < state->last_end)
1674 return state->last_nid;
1675
1676 nid = memblock_search_pfn_nid(pfn, &start_pfn, &end_pfn);
1677 if (nid != NUMA_NO_NODE) {
1678 state->last_start = start_pfn;
1679 state->last_end = end_pfn;
1680 state->last_nid = nid;
1681 }
1682
1683 return nid;
1684 }
1685 #endif /* CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID */
1686
early_pfn_to_nid(unsigned long pfn)1687 int __meminit early_pfn_to_nid(unsigned long pfn)
1688 {
1689 static DEFINE_SPINLOCK(early_pfn_lock);
1690 int nid;
1691
1692 spin_lock(&early_pfn_lock);
1693 nid = __early_pfn_to_nid(pfn, &early_pfnnid_cache);
1694 if (nid < 0)
1695 nid = first_online_node;
1696 spin_unlock(&early_pfn_lock);
1697
1698 return nid;
1699 }
1700 #endif /* CONFIG_NEED_MULTIPLE_NODES */
1701
memblock_free_pages(struct page * page,unsigned long pfn,unsigned int order)1702 void __init memblock_free_pages(struct page *page, unsigned long pfn,
1703 unsigned int order)
1704 {
1705 if (early_page_uninitialised(pfn))
1706 return;
1707 __free_pages_core(page, order);
1708 }
1709
1710 /*
1711 * Check that the whole (or subset of) a pageblock given by the interval of
1712 * [start_pfn, end_pfn) is valid and within the same zone, before scanning it
1713 * with the migration of free compaction scanner. The scanners then need to
1714 * use only pfn_valid_within() check for arches that allow holes within
1715 * pageblocks.
1716 *
1717 * Return struct page pointer of start_pfn, or NULL if checks were not passed.
1718 *
1719 * It's possible on some configurations to have a setup like node0 node1 node0
1720 * i.e. it's possible that all pages within a zones range of pages do not
1721 * belong to a single zone. We assume that a border between node0 and node1
1722 * can occur within a single pageblock, but not a node0 node1 node0
1723 * interleaving within a single pageblock. It is therefore sufficient to check
1724 * the first and last page of a pageblock and avoid checking each individual
1725 * page in a pageblock.
1726 */
__pageblock_pfn_to_page(unsigned long start_pfn,unsigned long end_pfn,struct zone * zone)1727 struct page *__pageblock_pfn_to_page(unsigned long start_pfn,
1728 unsigned long end_pfn, struct zone *zone)
1729 {
1730 struct page *start_page;
1731 struct page *end_page;
1732
1733 /* end_pfn is one past the range we are checking */
1734 end_pfn--;
1735
1736 if (!pfn_valid(start_pfn) || !pfn_valid(end_pfn))
1737 return NULL;
1738
1739 start_page = pfn_to_online_page(start_pfn);
1740 if (!start_page)
1741 return NULL;
1742
1743 if (page_zone(start_page) != zone)
1744 return NULL;
1745
1746 end_page = pfn_to_page(end_pfn);
1747
1748 /* This gives a shorter code than deriving page_zone(end_page) */
1749 if (page_zone_id(start_page) != page_zone_id(end_page))
1750 return NULL;
1751
1752 return start_page;
1753 }
1754
set_zone_contiguous(struct zone * zone)1755 void set_zone_contiguous(struct zone *zone)
1756 {
1757 unsigned long block_start_pfn = zone->zone_start_pfn;
1758 unsigned long block_end_pfn;
1759
1760 block_end_pfn = ALIGN(block_start_pfn + 1, pageblock_nr_pages);
1761 for (; block_start_pfn < zone_end_pfn(zone);
1762 block_start_pfn = block_end_pfn,
1763 block_end_pfn += pageblock_nr_pages) {
1764
1765 block_end_pfn = min(block_end_pfn, zone_end_pfn(zone));
1766
1767 if (!__pageblock_pfn_to_page(block_start_pfn,
1768 block_end_pfn, zone))
1769 return;
1770 cond_resched();
1771 }
1772
1773 /* We confirm that there is no hole */
1774 zone->contiguous = true;
1775 }
1776
clear_zone_contiguous(struct zone * zone)1777 void clear_zone_contiguous(struct zone *zone)
1778 {
1779 zone->contiguous = false;
1780 }
1781
1782 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
deferred_free_range(unsigned long pfn,unsigned long nr_pages)1783 static void __init deferred_free_range(unsigned long pfn,
1784 unsigned long nr_pages)
1785 {
1786 struct page *page;
1787 unsigned long i;
1788
1789 if (!nr_pages)
1790 return;
1791
1792 page = pfn_to_page(pfn);
1793
1794 /* Free a large naturally-aligned chunk if possible */
1795 if (nr_pages == pageblock_nr_pages &&
1796 (pfn & (pageblock_nr_pages - 1)) == 0) {
1797 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
1798 __free_pages_core(page, pageblock_order);
1799 return;
1800 }
1801
1802 for (i = 0; i < nr_pages; i++, page++, pfn++) {
1803 if ((pfn & (pageblock_nr_pages - 1)) == 0)
1804 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
1805 __free_pages_core(page, 0);
1806 }
1807 }
1808
1809 /* Completion tracking for deferred_init_memmap() threads */
1810 static atomic_t pgdat_init_n_undone __initdata;
1811 static __initdata DECLARE_COMPLETION(pgdat_init_all_done_comp);
1812
pgdat_init_report_one_done(void)1813 static inline void __init pgdat_init_report_one_done(void)
1814 {
1815 if (atomic_dec_and_test(&pgdat_init_n_undone))
1816 complete(&pgdat_init_all_done_comp);
1817 }
1818
1819 /*
1820 * Returns true if page needs to be initialized or freed to buddy allocator.
1821 *
1822 * First we check if pfn is valid on architectures where it is possible to have
1823 * holes within pageblock_nr_pages. On systems where it is not possible, this
1824 * function is optimized out.
1825 *
1826 * Then, we check if a current large page is valid by only checking the validity
1827 * of the head pfn.
1828 */
deferred_pfn_valid(unsigned long pfn)1829 static inline bool __init deferred_pfn_valid(unsigned long pfn)
1830 {
1831 if (!pfn_valid_within(pfn))
1832 return false;
1833 if (!(pfn & (pageblock_nr_pages - 1)) && !pfn_valid(pfn))
1834 return false;
1835 return true;
1836 }
1837
1838 /*
1839 * Free pages to buddy allocator. Try to free aligned pages in
1840 * pageblock_nr_pages sizes.
1841 */
deferred_free_pages(unsigned long pfn,unsigned long end_pfn)1842 static void __init deferred_free_pages(unsigned long pfn,
1843 unsigned long end_pfn)
1844 {
1845 unsigned long nr_pgmask = pageblock_nr_pages - 1;
1846 unsigned long nr_free = 0;
1847
1848 for (; pfn < end_pfn; pfn++) {
1849 if (!deferred_pfn_valid(pfn)) {
1850 deferred_free_range(pfn - nr_free, nr_free);
1851 nr_free = 0;
1852 } else if (!(pfn & nr_pgmask)) {
1853 deferred_free_range(pfn - nr_free, nr_free);
1854 nr_free = 1;
1855 } else {
1856 nr_free++;
1857 }
1858 }
1859 /* Free the last block of pages to allocator */
1860 deferred_free_range(pfn - nr_free, nr_free);
1861 }
1862
1863 /*
1864 * Initialize struct pages. We minimize pfn page lookups and scheduler checks
1865 * by performing it only once every pageblock_nr_pages.
1866 * Return number of pages initialized.
1867 */
deferred_init_pages(struct zone * zone,unsigned long pfn,unsigned long end_pfn)1868 static unsigned long __init deferred_init_pages(struct zone *zone,
1869 unsigned long pfn,
1870 unsigned long end_pfn)
1871 {
1872 unsigned long nr_pgmask = pageblock_nr_pages - 1;
1873 int nid = zone_to_nid(zone);
1874 unsigned long nr_pages = 0;
1875 int zid = zone_idx(zone);
1876 struct page *page = NULL;
1877
1878 for (; pfn < end_pfn; pfn++) {
1879 if (!deferred_pfn_valid(pfn)) {
1880 page = NULL;
1881 continue;
1882 } else if (!page || !(pfn & nr_pgmask)) {
1883 page = pfn_to_page(pfn);
1884 } else {
1885 page++;
1886 }
1887 __init_single_page(page, pfn, zid, nid, true);
1888 nr_pages++;
1889 }
1890 return (nr_pages);
1891 }
1892
1893 /*
1894 * This function is meant to pre-load the iterator for the zone init.
1895 * Specifically it walks through the ranges until we are caught up to the
1896 * first_init_pfn value and exits there. If we never encounter the value we
1897 * return false indicating there are no valid ranges left.
1898 */
1899 static bool __init
deferred_init_mem_pfn_range_in_zone(u64 * i,struct zone * zone,unsigned long * spfn,unsigned long * epfn,unsigned long first_init_pfn)1900 deferred_init_mem_pfn_range_in_zone(u64 *i, struct zone *zone,
1901 unsigned long *spfn, unsigned long *epfn,
1902 unsigned long first_init_pfn)
1903 {
1904 u64 j;
1905
1906 /*
1907 * Start out by walking through the ranges in this zone that have
1908 * already been initialized. We don't need to do anything with them
1909 * so we just need to flush them out of the system.
1910 */
1911 for_each_free_mem_pfn_range_in_zone(j, zone, spfn, epfn) {
1912 if (*epfn <= first_init_pfn)
1913 continue;
1914 if (*spfn < first_init_pfn)
1915 *spfn = first_init_pfn;
1916 *i = j;
1917 return true;
1918 }
1919
1920 return false;
1921 }
1922
1923 /*
1924 * Initialize and free pages. We do it in two loops: first we initialize
1925 * struct page, then free to buddy allocator, because while we are
1926 * freeing pages we can access pages that are ahead (computing buddy
1927 * page in __free_one_page()).
1928 *
1929 * In order to try and keep some memory in the cache we have the loop
1930 * broken along max page order boundaries. This way we will not cause
1931 * any issues with the buddy page computation.
1932 */
1933 static unsigned long __init
deferred_init_maxorder(u64 * i,struct zone * zone,unsigned long * start_pfn,unsigned long * end_pfn)1934 deferred_init_maxorder(u64 *i, struct zone *zone, unsigned long *start_pfn,
1935 unsigned long *end_pfn)
1936 {
1937 unsigned long mo_pfn = ALIGN(*start_pfn + 1, MAX_ORDER_NR_PAGES);
1938 unsigned long spfn = *start_pfn, epfn = *end_pfn;
1939 unsigned long nr_pages = 0;
1940 u64 j = *i;
1941
1942 /* First we loop through and initialize the page values */
1943 for_each_free_mem_pfn_range_in_zone_from(j, zone, start_pfn, end_pfn) {
1944 unsigned long t;
1945
1946 if (mo_pfn <= *start_pfn)
1947 break;
1948
1949 t = min(mo_pfn, *end_pfn);
1950 nr_pages += deferred_init_pages(zone, *start_pfn, t);
1951
1952 if (mo_pfn < *end_pfn) {
1953 *start_pfn = mo_pfn;
1954 break;
1955 }
1956 }
1957
1958 /* Reset values and now loop through freeing pages as needed */
1959 swap(j, *i);
1960
1961 for_each_free_mem_pfn_range_in_zone_from(j, zone, &spfn, &epfn) {
1962 unsigned long t;
1963
1964 if (mo_pfn <= spfn)
1965 break;
1966
1967 t = min(mo_pfn, epfn);
1968 deferred_free_pages(spfn, t);
1969
1970 if (mo_pfn <= epfn)
1971 break;
1972 }
1973
1974 return nr_pages;
1975 }
1976
1977 static void __init
deferred_init_memmap_chunk(unsigned long start_pfn,unsigned long end_pfn,void * arg)1978 deferred_init_memmap_chunk(unsigned long start_pfn, unsigned long end_pfn,
1979 void *arg)
1980 {
1981 unsigned long spfn, epfn;
1982 struct zone *zone = arg;
1983 u64 i;
1984
1985 deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn, start_pfn);
1986
1987 /*
1988 * Initialize and free pages in MAX_ORDER sized increments so that we
1989 * can avoid introducing any issues with the buddy allocator.
1990 */
1991 while (spfn < end_pfn) {
1992 deferred_init_maxorder(&i, zone, &spfn, &epfn);
1993 cond_resched();
1994 }
1995 }
1996
1997 /* An arch may override for more concurrency. */
1998 __weak int __init
deferred_page_init_max_threads(const struct cpumask * node_cpumask)1999 deferred_page_init_max_threads(const struct cpumask *node_cpumask)
2000 {
2001 return 1;
2002 }
2003
2004 /* Initialise remaining memory on a node */
deferred_init_memmap(void * data)2005 static int __init deferred_init_memmap(void *data)
2006 {
2007 pg_data_t *pgdat = data;
2008 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
2009 unsigned long spfn = 0, epfn = 0;
2010 unsigned long first_init_pfn, flags;
2011 unsigned long start = jiffies;
2012 struct zone *zone;
2013 int zid, max_threads;
2014 u64 i;
2015
2016 /* Bind memory initialisation thread to a local node if possible */
2017 if (!cpumask_empty(cpumask))
2018 set_cpus_allowed_ptr(current, cpumask);
2019
2020 pgdat_resize_lock(pgdat, &flags);
2021 first_init_pfn = pgdat->first_deferred_pfn;
2022 if (first_init_pfn == ULONG_MAX) {
2023 pgdat_resize_unlock(pgdat, &flags);
2024 pgdat_init_report_one_done();
2025 return 0;
2026 }
2027
2028 /* Sanity check boundaries */
2029 BUG_ON(pgdat->first_deferred_pfn < pgdat->node_start_pfn);
2030 BUG_ON(pgdat->first_deferred_pfn > pgdat_end_pfn(pgdat));
2031 pgdat->first_deferred_pfn = ULONG_MAX;
2032
2033 /*
2034 * Once we unlock here, the zone cannot be grown anymore, thus if an
2035 * interrupt thread must allocate this early in boot, zone must be
2036 * pre-grown prior to start of deferred page initialization.
2037 */
2038 pgdat_resize_unlock(pgdat, &flags);
2039
2040 /* Only the highest zone is deferred so find it */
2041 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2042 zone = pgdat->node_zones + zid;
2043 if (first_init_pfn < zone_end_pfn(zone))
2044 break;
2045 }
2046
2047 /* If the zone is empty somebody else may have cleared out the zone */
2048 if (!deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn,
2049 first_init_pfn))
2050 goto zone_empty;
2051
2052 max_threads = deferred_page_init_max_threads(cpumask);
2053
2054 while (spfn < epfn) {
2055 unsigned long epfn_align = ALIGN(epfn, PAGES_PER_SECTION);
2056 struct padata_mt_job job = {
2057 .thread_fn = deferred_init_memmap_chunk,
2058 .fn_arg = zone,
2059 .start = spfn,
2060 .size = epfn_align - spfn,
2061 .align = PAGES_PER_SECTION,
2062 .min_chunk = PAGES_PER_SECTION,
2063 .max_threads = max_threads,
2064 };
2065
2066 padata_do_multithreaded(&job);
2067 deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn,
2068 epfn_align);
2069 }
2070 zone_empty:
2071 /* Sanity check that the next zone really is unpopulated */
2072 WARN_ON(++zid < MAX_NR_ZONES && populated_zone(++zone));
2073
2074 pr_info("node %d deferred pages initialised in %ums\n",
2075 pgdat->node_id, jiffies_to_msecs(jiffies - start));
2076
2077 pgdat_init_report_one_done();
2078 return 0;
2079 }
2080
2081 /*
2082 * If this zone has deferred pages, try to grow it by initializing enough
2083 * deferred pages to satisfy the allocation specified by order, rounded up to
2084 * the nearest PAGES_PER_SECTION boundary. So we're adding memory in increments
2085 * of SECTION_SIZE bytes by initializing struct pages in increments of
2086 * PAGES_PER_SECTION * sizeof(struct page) bytes.
2087 *
2088 * Return true when zone was grown, otherwise return false. We return true even
2089 * when we grow less than requested, to let the caller decide if there are
2090 * enough pages to satisfy the allocation.
2091 *
2092 * Note: We use noinline because this function is needed only during boot, and
2093 * it is called from a __ref function _deferred_grow_zone. This way we are
2094 * making sure that it is not inlined into permanent text section.
2095 */
2096 static noinline bool __init
deferred_grow_zone(struct zone * zone,unsigned int order)2097 deferred_grow_zone(struct zone *zone, unsigned int order)
2098 {
2099 unsigned long nr_pages_needed = ALIGN(1 << order, PAGES_PER_SECTION);
2100 pg_data_t *pgdat = zone->zone_pgdat;
2101 unsigned long first_deferred_pfn = pgdat->first_deferred_pfn;
2102 unsigned long spfn, epfn, flags;
2103 unsigned long nr_pages = 0;
2104 u64 i;
2105
2106 /* Only the last zone may have deferred pages */
2107 if (zone_end_pfn(zone) != pgdat_end_pfn(pgdat))
2108 return false;
2109
2110 pgdat_resize_lock(pgdat, &flags);
2111
2112 /*
2113 * If someone grew this zone while we were waiting for spinlock, return
2114 * true, as there might be enough pages already.
2115 */
2116 if (first_deferred_pfn != pgdat->first_deferred_pfn) {
2117 pgdat_resize_unlock(pgdat, &flags);
2118 return true;
2119 }
2120
2121 /* If the zone is empty somebody else may have cleared out the zone */
2122 if (!deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn,
2123 first_deferred_pfn)) {
2124 pgdat->first_deferred_pfn = ULONG_MAX;
2125 pgdat_resize_unlock(pgdat, &flags);
2126 /* Retry only once. */
2127 return first_deferred_pfn != ULONG_MAX;
2128 }
2129
2130 /*
2131 * Initialize and free pages in MAX_ORDER sized increments so
2132 * that we can avoid introducing any issues with the buddy
2133 * allocator.
2134 */
2135 while (spfn < epfn) {
2136 /* update our first deferred PFN for this section */
2137 first_deferred_pfn = spfn;
2138
2139 nr_pages += deferred_init_maxorder(&i, zone, &spfn, &epfn);
2140 touch_nmi_watchdog();
2141
2142 /* We should only stop along section boundaries */
2143 if ((first_deferred_pfn ^ spfn) < PAGES_PER_SECTION)
2144 continue;
2145
2146 /* If our quota has been met we can stop here */
2147 if (nr_pages >= nr_pages_needed)
2148 break;
2149 }
2150
2151 pgdat->first_deferred_pfn = spfn;
2152 pgdat_resize_unlock(pgdat, &flags);
2153
2154 return nr_pages > 0;
2155 }
2156
2157 /*
2158 * deferred_grow_zone() is __init, but it is called from
2159 * get_page_from_freelist() during early boot until deferred_pages permanently
2160 * disables this call. This is why we have refdata wrapper to avoid warning,
2161 * and to ensure that the function body gets unloaded.
2162 */
2163 static bool __ref
_deferred_grow_zone(struct zone * zone,unsigned int order)2164 _deferred_grow_zone(struct zone *zone, unsigned int order)
2165 {
2166 return deferred_grow_zone(zone, order);
2167 }
2168
2169 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
2170
page_alloc_init_late(void)2171 void __init page_alloc_init_late(void)
2172 {
2173 struct zone *zone;
2174 int nid;
2175
2176 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
2177
2178 /* There will be num_node_state(N_MEMORY) threads */
2179 atomic_set(&pgdat_init_n_undone, num_node_state(N_MEMORY));
2180 for_each_node_state(nid, N_MEMORY) {
2181 kthread_run(deferred_init_memmap, NODE_DATA(nid), "pgdatinit%d", nid);
2182 }
2183
2184 /* Block until all are initialised */
2185 wait_for_completion(&pgdat_init_all_done_comp);
2186
2187 /*
2188 * The number of managed pages has changed due to the initialisation
2189 * so the pcpu batch and high limits needs to be updated or the limits
2190 * will be artificially small.
2191 */
2192 for_each_populated_zone(zone)
2193 zone_pcp_update(zone);
2194
2195 /*
2196 * We initialized the rest of the deferred pages. Permanently disable
2197 * on-demand struct page initialization.
2198 */
2199 static_branch_disable(&deferred_pages);
2200
2201 /* Reinit limits that are based on free pages after the kernel is up */
2202 files_maxfiles_init();
2203 #endif
2204
2205 /* Discard memblock private memory */
2206 memblock_discard();
2207
2208 for_each_node_state(nid, N_MEMORY)
2209 shuffle_free_memory(NODE_DATA(nid));
2210
2211 for_each_populated_zone(zone)
2212 set_zone_contiguous(zone);
2213 }
2214
2215 #ifdef CONFIG_CMA
2216 /* Free whole pageblock and set its migration type to MIGRATE_CMA. */
init_cma_reserved_pageblock(struct page * page)2217 void __init init_cma_reserved_pageblock(struct page *page)
2218 {
2219 unsigned i = pageblock_nr_pages;
2220 struct page *p = page;
2221
2222 do {
2223 __ClearPageReserved(p);
2224 set_page_count(p, 0);
2225 } while (++p, --i);
2226
2227 set_pageblock_migratetype(page, MIGRATE_CMA);
2228
2229 if (pageblock_order >= MAX_ORDER) {
2230 i = pageblock_nr_pages;
2231 p = page;
2232 do {
2233 set_page_refcounted(p);
2234 __free_pages(p, MAX_ORDER - 1);
2235 p += MAX_ORDER_NR_PAGES;
2236 } while (i -= MAX_ORDER_NR_PAGES);
2237 } else {
2238 set_page_refcounted(page);
2239 __free_pages(page, pageblock_order);
2240 }
2241
2242 adjust_managed_page_count(page, pageblock_nr_pages);
2243 page_zone(page)->cma_pages += pageblock_nr_pages;
2244 }
2245 #endif
2246
2247 /*
2248 * The order of subdivision here is critical for the IO subsystem.
2249 * Please do not alter this order without good reasons and regression
2250 * testing. Specifically, as large blocks of memory are subdivided,
2251 * the order in which smaller blocks are delivered depends on the order
2252 * they're subdivided in this function. This is the primary factor
2253 * influencing the order in which pages are delivered to the IO
2254 * subsystem according to empirical testing, and this is also justified
2255 * by considering the behavior of a buddy system containing a single
2256 * large block of memory acted on by a series of small allocations.
2257 * This behavior is a critical factor in sglist merging's success.
2258 *
2259 * -- nyc
2260 */
expand(struct zone * zone,struct page * page,int low,int high,int migratetype)2261 static inline void expand(struct zone *zone, struct page *page,
2262 int low, int high, int migratetype)
2263 {
2264 unsigned long size = 1 << high;
2265
2266 while (high > low) {
2267 high--;
2268 size >>= 1;
2269 VM_BUG_ON_PAGE(bad_range(zone, &page[size]), &page[size]);
2270
2271 /*
2272 * Mark as guard pages (or page), that will allow to
2273 * merge back to allocator when buddy will be freed.
2274 * Corresponding page table entries will not be touched,
2275 * pages will stay not present in virtual address space
2276 */
2277 if (set_page_guard(zone, &page[size], high, migratetype))
2278 continue;
2279
2280 add_to_free_list(&page[size], zone, high, migratetype);
2281 set_buddy_order(&page[size], high);
2282 }
2283 }
2284
check_new_page_bad(struct page * page)2285 static void check_new_page_bad(struct page *page)
2286 {
2287 if (unlikely(page->flags & __PG_HWPOISON)) {
2288 /* Don't complain about hwpoisoned pages */
2289 page_mapcount_reset(page); /* remove PageBuddy */
2290 return;
2291 }
2292
2293 bad_page(page,
2294 page_bad_reason(page, PAGE_FLAGS_CHECK_AT_PREP));
2295 }
2296
2297 /*
2298 * This page is about to be returned from the page allocator
2299 */
check_new_page(struct page * page)2300 static inline int check_new_page(struct page *page)
2301 {
2302 if (likely(page_expected_state(page,
2303 PAGE_FLAGS_CHECK_AT_PREP|__PG_HWPOISON)))
2304 return 0;
2305
2306 check_new_page_bad(page);
2307 return 1;
2308 }
2309
2310 #ifdef CONFIG_DEBUG_VM
2311 /*
2312 * With DEBUG_VM enabled, order-0 pages are checked for expected state when
2313 * being allocated from pcp lists. With debug_pagealloc also enabled, they are
2314 * also checked when pcp lists are refilled from the free lists.
2315 */
check_pcp_refill(struct page * page)2316 static inline bool check_pcp_refill(struct page *page)
2317 {
2318 if (debug_pagealloc_enabled_static())
2319 return check_new_page(page);
2320 else
2321 return false;
2322 }
2323
check_new_pcp(struct page * page)2324 static inline bool check_new_pcp(struct page *page)
2325 {
2326 return check_new_page(page);
2327 }
2328 #else
2329 /*
2330 * With DEBUG_VM disabled, free order-0 pages are checked for expected state
2331 * when pcp lists are being refilled from the free lists. With debug_pagealloc
2332 * enabled, they are also checked when being allocated from the pcp lists.
2333 */
check_pcp_refill(struct page * page)2334 static inline bool check_pcp_refill(struct page *page)
2335 {
2336 return check_new_page(page);
2337 }
check_new_pcp(struct page * page)2338 static inline bool check_new_pcp(struct page *page)
2339 {
2340 if (debug_pagealloc_enabled_static())
2341 return check_new_page(page);
2342 else
2343 return false;
2344 }
2345 #endif /* CONFIG_DEBUG_VM */
2346
check_new_pages(struct page * page,unsigned int order)2347 static bool check_new_pages(struct page *page, unsigned int order)
2348 {
2349 int i;
2350 for (i = 0; i < (1 << order); i++) {
2351 struct page *p = page + i;
2352
2353 if (unlikely(check_new_page(p)))
2354 return true;
2355 }
2356
2357 return false;
2358 }
2359
post_alloc_hook(struct page * page,unsigned int order,gfp_t gfp_flags)2360 inline void post_alloc_hook(struct page *page, unsigned int order,
2361 gfp_t gfp_flags)
2362 {
2363 set_page_private(page, 0);
2364 set_page_refcounted(page);
2365
2366 arch_alloc_page(page, order);
2367 debug_pagealloc_map_pages(page, 1 << order);
2368
2369 /*
2370 * Page unpoisoning must happen before memory initialization.
2371 * Otherwise, the poison pattern will be overwritten for __GFP_ZERO
2372 * allocations and the page unpoisoning code will complain.
2373 */
2374 kernel_unpoison_pages(page, 1 << order);
2375
2376 /*
2377 * As memory initialization might be integrated into KASAN,
2378 * kasan_alloc_pages and kernel_init_free_pages must be
2379 * kept together to avoid discrepancies in behavior.
2380 */
2381 if (kasan_has_integrated_init()) {
2382 kasan_alloc_pages(page, order, gfp_flags);
2383 } else {
2384 bool init = !want_init_on_free() && want_init_on_alloc(gfp_flags);
2385
2386 kasan_unpoison_pages(page, order, init);
2387 if (init)
2388 kernel_init_free_pages(page, 1 << order,
2389 gfp_flags & __GFP_ZEROTAGS);
2390 }
2391
2392 set_page_owner(page, order, gfp_flags);
2393 }
2394
prep_new_page(struct page * page,unsigned int order,gfp_t gfp_flags,unsigned int alloc_flags)2395 static void prep_new_page(struct page *page, unsigned int order, gfp_t gfp_flags,
2396 unsigned int alloc_flags)
2397 {
2398 post_alloc_hook(page, order, gfp_flags);
2399
2400 if (order && (gfp_flags & __GFP_COMP))
2401 prep_compound_page(page, order);
2402
2403 /*
2404 * page is set pfmemalloc when ALLOC_NO_WATERMARKS was necessary to
2405 * allocate the page. The expectation is that the caller is taking
2406 * steps that will free more memory. The caller should avoid the page
2407 * being used for !PFMEMALLOC purposes.
2408 */
2409 if (alloc_flags & ALLOC_NO_WATERMARKS)
2410 set_page_pfmemalloc(page);
2411 else
2412 clear_page_pfmemalloc(page);
2413 trace_android_vh_test_clear_look_around_ref(page);
2414 }
2415
2416 /*
2417 * Go through the free lists for the given migratetype and remove
2418 * the smallest available page from the freelists
2419 */
2420 static __always_inline
__rmqueue_smallest(struct zone * zone,unsigned int order,int migratetype)2421 struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
2422 int migratetype)
2423 {
2424 unsigned int current_order;
2425 struct free_area *area;
2426 struct page *page;
2427
2428 /* Find a page of the appropriate size in the preferred list */
2429 for (current_order = order; current_order < MAX_ORDER; ++current_order) {
2430 area = &(zone->free_area[current_order]);
2431 page = get_page_from_free_area(area, migratetype);
2432 if (!page)
2433 continue;
2434 del_page_from_free_list(page, zone, current_order);
2435 expand(zone, page, order, current_order, migratetype);
2436 set_pcppage_migratetype(page, migratetype);
2437 return page;
2438 }
2439
2440 return NULL;
2441 }
2442
2443
2444 /*
2445 * This array describes the order lists are fallen back to when
2446 * the free lists for the desirable migrate type are depleted
2447 */
2448 static int fallbacks[MIGRATE_TYPES][3] = {
2449 [MIGRATE_UNMOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE, MIGRATE_TYPES },
2450 [MIGRATE_MOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_TYPES },
2451 [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE, MIGRATE_MOVABLE, MIGRATE_TYPES },
2452 #ifdef CONFIG_CMA
2453 [MIGRATE_CMA] = { MIGRATE_TYPES }, /* Never used */
2454 #endif
2455 #ifdef CONFIG_MEMORY_ISOLATION
2456 [MIGRATE_ISOLATE] = { MIGRATE_TYPES }, /* Never used */
2457 #endif
2458 };
2459
2460 #ifdef CONFIG_CMA
__rmqueue_cma_fallback(struct zone * zone,unsigned int order)2461 static __always_inline struct page *__rmqueue_cma_fallback(struct zone *zone,
2462 unsigned int order)
2463 {
2464 return __rmqueue_smallest(zone, order, MIGRATE_CMA);
2465 }
2466 #else
__rmqueue_cma_fallback(struct zone * zone,unsigned int order)2467 static inline struct page *__rmqueue_cma_fallback(struct zone *zone,
2468 unsigned int order) { return NULL; }
2469 #endif
2470
2471 /*
2472 * Move the free pages in a range to the freelist tail of the requested type.
2473 * Note that start_page and end_pages are not aligned on a pageblock
2474 * boundary. If alignment is required, use move_freepages_block()
2475 */
move_freepages(struct zone * zone,struct page * start_page,struct page * end_page,int migratetype,int * num_movable)2476 static int move_freepages(struct zone *zone,
2477 struct page *start_page, struct page *end_page,
2478 int migratetype, int *num_movable)
2479 {
2480 struct page *page;
2481 unsigned int order;
2482 int pages_moved = 0;
2483
2484 for (page = start_page; page <= end_page;) {
2485 if (!pfn_valid_within(page_to_pfn(page))) {
2486 page++;
2487 continue;
2488 }
2489
2490 if (!PageBuddy(page)) {
2491 /*
2492 * We assume that pages that could be isolated for
2493 * migration are movable. But we don't actually try
2494 * isolating, as that would be expensive.
2495 */
2496 if (num_movable &&
2497 (PageLRU(page) || __PageMovable(page)))
2498 (*num_movable)++;
2499
2500 page++;
2501 continue;
2502 }
2503
2504 /* Make sure we are not inadvertently changing nodes */
2505 VM_BUG_ON_PAGE(page_to_nid(page) != zone_to_nid(zone), page);
2506 VM_BUG_ON_PAGE(page_zone(page) != zone, page);
2507
2508 order = buddy_order(page);
2509 move_to_free_list(page, zone, order, migratetype);
2510 page += 1 << order;
2511 pages_moved += 1 << order;
2512 }
2513
2514 return pages_moved;
2515 }
2516
move_freepages_block(struct zone * zone,struct page * page,int migratetype,int * num_movable)2517 int move_freepages_block(struct zone *zone, struct page *page,
2518 int migratetype, int *num_movable)
2519 {
2520 unsigned long start_pfn, end_pfn;
2521 struct page *start_page, *end_page;
2522
2523 if (num_movable)
2524 *num_movable = 0;
2525
2526 start_pfn = page_to_pfn(page);
2527 start_pfn = start_pfn & ~(pageblock_nr_pages-1);
2528 start_page = pfn_to_page(start_pfn);
2529 end_page = start_page + pageblock_nr_pages - 1;
2530 end_pfn = start_pfn + pageblock_nr_pages - 1;
2531
2532 /* Do not cross zone boundaries */
2533 if (!zone_spans_pfn(zone, start_pfn))
2534 start_page = page;
2535 if (!zone_spans_pfn(zone, end_pfn))
2536 return 0;
2537
2538 return move_freepages(zone, start_page, end_page, migratetype,
2539 num_movable);
2540 }
2541
change_pageblock_range(struct page * pageblock_page,int start_order,int migratetype)2542 static void change_pageblock_range(struct page *pageblock_page,
2543 int start_order, int migratetype)
2544 {
2545 int nr_pageblocks = 1 << (start_order - pageblock_order);
2546
2547 while (nr_pageblocks--) {
2548 set_pageblock_migratetype(pageblock_page, migratetype);
2549 pageblock_page += pageblock_nr_pages;
2550 }
2551 }
2552
2553 /*
2554 * When we are falling back to another migratetype during allocation, try to
2555 * steal extra free pages from the same pageblocks to satisfy further
2556 * allocations, instead of polluting multiple pageblocks.
2557 *
2558 * If we are stealing a relatively large buddy page, it is likely there will
2559 * be more free pages in the pageblock, so try to steal them all. For
2560 * reclaimable and unmovable allocations, we steal regardless of page size,
2561 * as fragmentation caused by those allocations polluting movable pageblocks
2562 * is worse than movable allocations stealing from unmovable and reclaimable
2563 * pageblocks.
2564 */
can_steal_fallback(unsigned int order,int start_mt)2565 static bool can_steal_fallback(unsigned int order, int start_mt)
2566 {
2567 /*
2568 * Leaving this order check is intended, although there is
2569 * relaxed order check in next check. The reason is that
2570 * we can actually steal whole pageblock if this condition met,
2571 * but, below check doesn't guarantee it and that is just heuristic
2572 * so could be changed anytime.
2573 */
2574 if (order >= pageblock_order)
2575 return true;
2576
2577 if (order >= pageblock_order / 2 ||
2578 start_mt == MIGRATE_RECLAIMABLE ||
2579 start_mt == MIGRATE_UNMOVABLE ||
2580 page_group_by_mobility_disabled)
2581 return true;
2582
2583 return false;
2584 }
2585
boost_watermark(struct zone * zone)2586 static inline bool boost_watermark(struct zone *zone)
2587 {
2588 unsigned long max_boost;
2589
2590 if (!watermark_boost_factor)
2591 return false;
2592 /*
2593 * Don't bother in zones that are unlikely to produce results.
2594 * On small machines, including kdump capture kernels running
2595 * in a small area, boosting the watermark can cause an out of
2596 * memory situation immediately.
2597 */
2598 if ((pageblock_nr_pages * 4) > zone_managed_pages(zone))
2599 return false;
2600
2601 max_boost = mult_frac(zone->_watermark[WMARK_HIGH],
2602 watermark_boost_factor, 10000);
2603
2604 /*
2605 * high watermark may be uninitialised if fragmentation occurs
2606 * very early in boot so do not boost. We do not fall
2607 * through and boost by pageblock_nr_pages as failing
2608 * allocations that early means that reclaim is not going
2609 * to help and it may even be impossible to reclaim the
2610 * boosted watermark resulting in a hang.
2611 */
2612 if (!max_boost)
2613 return false;
2614
2615 max_boost = max(pageblock_nr_pages, max_boost);
2616
2617 zone->watermark_boost = min(zone->watermark_boost + pageblock_nr_pages,
2618 max_boost);
2619
2620 return true;
2621 }
2622
2623 /*
2624 * This function implements actual steal behaviour. If order is large enough,
2625 * we can steal whole pageblock. If not, we first move freepages in this
2626 * pageblock to our migratetype and determine how many already-allocated pages
2627 * are there in the pageblock with a compatible migratetype. If at least half
2628 * of pages are free or compatible, we can change migratetype of the pageblock
2629 * itself, so pages freed in the future will be put on the correct free list.
2630 */
steal_suitable_fallback(struct zone * zone,struct page * page,unsigned int alloc_flags,int start_type,bool whole_block)2631 static void steal_suitable_fallback(struct zone *zone, struct page *page,
2632 unsigned int alloc_flags, int start_type, bool whole_block)
2633 {
2634 unsigned int current_order = buddy_order(page);
2635 int free_pages, movable_pages, alike_pages;
2636 int old_block_type;
2637
2638 old_block_type = get_pageblock_migratetype(page);
2639
2640 /*
2641 * This can happen due to races and we want to prevent broken
2642 * highatomic accounting.
2643 */
2644 if (is_migrate_highatomic(old_block_type))
2645 goto single_page;
2646
2647 /* Take ownership for orders >= pageblock_order */
2648 if (current_order >= pageblock_order) {
2649 change_pageblock_range(page, current_order, start_type);
2650 goto single_page;
2651 }
2652
2653 /*
2654 * Boost watermarks to increase reclaim pressure to reduce the
2655 * likelihood of future fallbacks. Wake kswapd now as the node
2656 * may be balanced overall and kswapd will not wake naturally.
2657 */
2658 if (boost_watermark(zone) && (alloc_flags & ALLOC_KSWAPD))
2659 set_bit(ZONE_BOOSTED_WATERMARK, &zone->flags);
2660
2661 /* We are not allowed to try stealing from the whole block */
2662 if (!whole_block)
2663 goto single_page;
2664
2665 free_pages = move_freepages_block(zone, page, start_type,
2666 &movable_pages);
2667 /*
2668 * Determine how many pages are compatible with our allocation.
2669 * For movable allocation, it's the number of movable pages which
2670 * we just obtained. For other types it's a bit more tricky.
2671 */
2672 if (start_type == MIGRATE_MOVABLE) {
2673 alike_pages = movable_pages;
2674 } else {
2675 /*
2676 * If we are falling back a RECLAIMABLE or UNMOVABLE allocation
2677 * to MOVABLE pageblock, consider all non-movable pages as
2678 * compatible. If it's UNMOVABLE falling back to RECLAIMABLE or
2679 * vice versa, be conservative since we can't distinguish the
2680 * exact migratetype of non-movable pages.
2681 */
2682 if (old_block_type == MIGRATE_MOVABLE)
2683 alike_pages = pageblock_nr_pages
2684 - (free_pages + movable_pages);
2685 else
2686 alike_pages = 0;
2687 }
2688
2689 /* moving whole block can fail due to zone boundary conditions */
2690 if (!free_pages)
2691 goto single_page;
2692
2693 /*
2694 * If a sufficient number of pages in the block are either free or of
2695 * comparable migratability as our allocation, claim the whole block.
2696 */
2697 if (free_pages + alike_pages >= (1 << (pageblock_order-1)) ||
2698 page_group_by_mobility_disabled)
2699 set_pageblock_migratetype(page, start_type);
2700
2701 return;
2702
2703 single_page:
2704 move_to_free_list(page, zone, current_order, start_type);
2705 }
2706
2707 /*
2708 * Check whether there is a suitable fallback freepage with requested order.
2709 * If only_stealable is true, this function returns fallback_mt only if
2710 * we can steal other freepages all together. This would help to reduce
2711 * fragmentation due to mixed migratetype pages in one pageblock.
2712 */
find_suitable_fallback(struct free_area * area,unsigned int order,int migratetype,bool only_stealable,bool * can_steal)2713 int find_suitable_fallback(struct free_area *area, unsigned int order,
2714 int migratetype, bool only_stealable, bool *can_steal)
2715 {
2716 int i;
2717 int fallback_mt;
2718
2719 if (area->nr_free == 0)
2720 return -1;
2721
2722 *can_steal = false;
2723 for (i = 0;; i++) {
2724 fallback_mt = fallbacks[migratetype][i];
2725 if (fallback_mt == MIGRATE_TYPES)
2726 break;
2727
2728 if (free_area_empty(area, fallback_mt))
2729 continue;
2730
2731 if (can_steal_fallback(order, migratetype))
2732 *can_steal = true;
2733
2734 if (!only_stealable)
2735 return fallback_mt;
2736
2737 if (*can_steal)
2738 return fallback_mt;
2739 }
2740
2741 return -1;
2742 }
2743
2744 /*
2745 * Reserve a pageblock for exclusive use of high-order atomic allocations if
2746 * there are no empty page blocks that contain a page with a suitable order
2747 */
reserve_highatomic_pageblock(struct page * page,struct zone * zone,unsigned int alloc_order)2748 static void reserve_highatomic_pageblock(struct page *page, struct zone *zone,
2749 unsigned int alloc_order)
2750 {
2751 int mt;
2752 unsigned long max_managed, flags;
2753
2754 /*
2755 * Limit the number reserved to 1 pageblock or roughly 1% of a zone.
2756 * Check is race-prone but harmless.
2757 */
2758 max_managed = (zone_managed_pages(zone) / 100) + pageblock_nr_pages;
2759 if (zone->nr_reserved_highatomic >= max_managed)
2760 return;
2761
2762 spin_lock_irqsave(&zone->lock, flags);
2763
2764 /* Recheck the nr_reserved_highatomic limit under the lock */
2765 if (zone->nr_reserved_highatomic >= max_managed)
2766 goto out_unlock;
2767
2768 /* Yoink! */
2769 mt = get_pageblock_migratetype(page);
2770 if (!is_migrate_highatomic(mt) && !is_migrate_isolate(mt)
2771 && !is_migrate_cma(mt)) {
2772 zone->nr_reserved_highatomic += pageblock_nr_pages;
2773 set_pageblock_migratetype(page, MIGRATE_HIGHATOMIC);
2774 move_freepages_block(zone, page, MIGRATE_HIGHATOMIC, NULL);
2775 }
2776
2777 out_unlock:
2778 spin_unlock_irqrestore(&zone->lock, flags);
2779 }
2780
2781 /*
2782 * Used when an allocation is about to fail under memory pressure. This
2783 * potentially hurts the reliability of high-order allocations when under
2784 * intense memory pressure but failed atomic allocations should be easier
2785 * to recover from than an OOM.
2786 *
2787 * If @force is true, try to unreserve a pageblock even though highatomic
2788 * pageblock is exhausted.
2789 */
unreserve_highatomic_pageblock(const struct alloc_context * ac,bool force)2790 static bool unreserve_highatomic_pageblock(const struct alloc_context *ac,
2791 bool force)
2792 {
2793 struct zonelist *zonelist = ac->zonelist;
2794 unsigned long flags;
2795 struct zoneref *z;
2796 struct zone *zone;
2797 struct page *page;
2798 int order;
2799 bool ret;
2800
2801 for_each_zone_zonelist_nodemask(zone, z, zonelist, ac->highest_zoneidx,
2802 ac->nodemask) {
2803 /*
2804 * Preserve at least one pageblock unless memory pressure
2805 * is really high.
2806 */
2807 if (!force && zone->nr_reserved_highatomic <=
2808 pageblock_nr_pages)
2809 continue;
2810
2811 spin_lock_irqsave(&zone->lock, flags);
2812 for (order = 0; order < MAX_ORDER; order++) {
2813 struct free_area *area = &(zone->free_area[order]);
2814
2815 page = get_page_from_free_area(area, MIGRATE_HIGHATOMIC);
2816 if (!page)
2817 continue;
2818
2819 /*
2820 * In page freeing path, migratetype change is racy so
2821 * we can counter several free pages in a pageblock
2822 * in this loop althoug we changed the pageblock type
2823 * from highatomic to ac->migratetype. So we should
2824 * adjust the count once.
2825 */
2826 if (is_migrate_highatomic_page(page)) {
2827 /*
2828 * It should never happen but changes to
2829 * locking could inadvertently allow a per-cpu
2830 * drain to add pages to MIGRATE_HIGHATOMIC
2831 * while unreserving so be safe and watch for
2832 * underflows.
2833 */
2834 zone->nr_reserved_highatomic -= min(
2835 pageblock_nr_pages,
2836 zone->nr_reserved_highatomic);
2837 }
2838
2839 /*
2840 * Convert to ac->migratetype and avoid the normal
2841 * pageblock stealing heuristics. Minimally, the caller
2842 * is doing the work and needs the pages. More
2843 * importantly, if the block was always converted to
2844 * MIGRATE_UNMOVABLE or another type then the number
2845 * of pageblocks that cannot be completely freed
2846 * may increase.
2847 */
2848 set_pageblock_migratetype(page, ac->migratetype);
2849 ret = move_freepages_block(zone, page, ac->migratetype,
2850 NULL);
2851 if (ret) {
2852 spin_unlock_irqrestore(&zone->lock, flags);
2853 return ret;
2854 }
2855 }
2856 spin_unlock_irqrestore(&zone->lock, flags);
2857 }
2858
2859 return false;
2860 }
2861
2862 /*
2863 * Try finding a free buddy page on the fallback list and put it on the free
2864 * list of requested migratetype, possibly along with other pages from the same
2865 * block, depending on fragmentation avoidance heuristics. Returns true if
2866 * fallback was found so that __rmqueue_smallest() can grab it.
2867 *
2868 * The use of signed ints for order and current_order is a deliberate
2869 * deviation from the rest of this file, to make the for loop
2870 * condition simpler.
2871 */
2872 static __always_inline bool
__rmqueue_fallback(struct zone * zone,int order,int start_migratetype,unsigned int alloc_flags)2873 __rmqueue_fallback(struct zone *zone, int order, int start_migratetype,
2874 unsigned int alloc_flags)
2875 {
2876 struct free_area *area;
2877 int current_order;
2878 int min_order = order;
2879 struct page *page;
2880 int fallback_mt;
2881 bool can_steal;
2882
2883 /*
2884 * Do not steal pages from freelists belonging to other pageblocks
2885 * i.e. orders < pageblock_order. If there are no local zones free,
2886 * the zonelists will be reiterated without ALLOC_NOFRAGMENT.
2887 */
2888 if (alloc_flags & ALLOC_NOFRAGMENT)
2889 min_order = pageblock_order;
2890
2891 /*
2892 * Find the largest available free page in the other list. This roughly
2893 * approximates finding the pageblock with the most free pages, which
2894 * would be too costly to do exactly.
2895 */
2896 for (current_order = MAX_ORDER - 1; current_order >= min_order;
2897 --current_order) {
2898 area = &(zone->free_area[current_order]);
2899 fallback_mt = find_suitable_fallback(area, current_order,
2900 start_migratetype, false, &can_steal);
2901 if (fallback_mt == -1)
2902 continue;
2903
2904 /*
2905 * We cannot steal all free pages from the pageblock and the
2906 * requested migratetype is movable. In that case it's better to
2907 * steal and split the smallest available page instead of the
2908 * largest available page, because even if the next movable
2909 * allocation falls back into a different pageblock than this
2910 * one, it won't cause permanent fragmentation.
2911 */
2912 if (!can_steal && start_migratetype == MIGRATE_MOVABLE
2913 && current_order > order)
2914 goto find_smallest;
2915
2916 goto do_steal;
2917 }
2918
2919 return false;
2920
2921 find_smallest:
2922 for (current_order = order; current_order < MAX_ORDER;
2923 current_order++) {
2924 area = &(zone->free_area[current_order]);
2925 fallback_mt = find_suitable_fallback(area, current_order,
2926 start_migratetype, false, &can_steal);
2927 if (fallback_mt != -1)
2928 break;
2929 }
2930
2931 /*
2932 * This should not happen - we already found a suitable fallback
2933 * when looking for the largest page.
2934 */
2935 VM_BUG_ON(current_order == MAX_ORDER);
2936
2937 do_steal:
2938 page = get_page_from_free_area(area, fallback_mt);
2939
2940 steal_suitable_fallback(zone, page, alloc_flags, start_migratetype,
2941 can_steal);
2942
2943 trace_mm_page_alloc_extfrag(page, order, current_order,
2944 start_migratetype, fallback_mt);
2945
2946 return true;
2947
2948 }
2949
2950 /*
2951 * Do the hard work of removing an element from the buddy allocator.
2952 * Call me with the zone->lock already held.
2953 */
2954 static __always_inline struct page *
__rmqueue(struct zone * zone,unsigned int order,int migratetype,unsigned int alloc_flags)2955 __rmqueue(struct zone *zone, unsigned int order, int migratetype,
2956 unsigned int alloc_flags)
2957 {
2958 struct page *page;
2959
2960 retry:
2961 page = __rmqueue_smallest(zone, order, migratetype);
2962
2963 if (unlikely(!page) && __rmqueue_fallback(zone, order, migratetype,
2964 alloc_flags))
2965 goto retry;
2966
2967 trace_mm_page_alloc_zone_locked(page, order, migratetype);
2968 return page;
2969 }
2970
2971 #ifdef CONFIG_CMA
__rmqueue_cma(struct zone * zone,unsigned int order,int migratetype,unsigned int alloc_flags)2972 static struct page *__rmqueue_cma(struct zone *zone, unsigned int order,
2973 int migratetype,
2974 unsigned int alloc_flags)
2975 {
2976 struct page *page = __rmqueue_cma_fallback(zone, order);
2977 trace_mm_page_alloc_zone_locked(page, order, MIGRATE_CMA);
2978 return page;
2979 }
2980 #else
__rmqueue_cma(struct zone * zone,unsigned int order,int migratetype,unsigned int alloc_flags)2981 static inline struct page *__rmqueue_cma(struct zone *zone, unsigned int order,
2982 int migratetype,
2983 unsigned int alloc_flags)
2984 {
2985 return NULL;
2986 }
2987 #endif
2988
2989 /*
2990 * Obtain a specified number of elements from the buddy allocator, all under
2991 * a single hold of the lock, for efficiency. Add them to the supplied list.
2992 * Returns the number of new pages which were placed at *list.
2993 */
rmqueue_bulk(struct zone * zone,unsigned int order,unsigned long count,struct list_head * list,int migratetype,unsigned int alloc_flags)2994 static int rmqueue_bulk(struct zone *zone, unsigned int order,
2995 unsigned long count, struct list_head *list,
2996 int migratetype, unsigned int alloc_flags)
2997 {
2998 int i, alloced = 0;
2999
3000 spin_lock(&zone->lock);
3001 for (i = 0; i < count; ++i) {
3002 struct page *page;
3003
3004 if (is_migrate_cma(migratetype))
3005 page = __rmqueue_cma(zone, order, migratetype,
3006 alloc_flags);
3007 else
3008 page = __rmqueue(zone, order, migratetype, alloc_flags);
3009
3010 if (unlikely(page == NULL))
3011 break;
3012
3013 if (unlikely(check_pcp_refill(page)))
3014 continue;
3015
3016 /*
3017 * Split buddy pages returned by expand() are received here in
3018 * physical page order. The page is added to the tail of
3019 * caller's list. From the callers perspective, the linked list
3020 * is ordered by page number under some conditions. This is
3021 * useful for IO devices that can forward direction from the
3022 * head, thus also in the physical page order. This is useful
3023 * for IO devices that can merge IO requests if the physical
3024 * pages are ordered properly.
3025 */
3026 list_add_tail(&page->lru, list);
3027 alloced++;
3028 if (is_migrate_cma(get_pcppage_migratetype(page)))
3029 __mod_zone_page_state(zone, NR_FREE_CMA_PAGES,
3030 -(1 << order));
3031 }
3032
3033 /*
3034 * i pages were removed from the buddy list even if some leak due
3035 * to check_pcp_refill failing so adjust NR_FREE_PAGES based
3036 * on i. Do not confuse with 'alloced' which is the number of
3037 * pages added to the pcp list.
3038 */
3039 __mod_zone_page_state(zone, NR_FREE_PAGES, -(i << order));
3040 spin_unlock(&zone->lock);
3041 return alloced;
3042 }
3043
3044 /*
3045 * Return the pcp list that corresponds to the migrate type if that list isn't
3046 * empty.
3047 * If the list is empty return NULL.
3048 */
get_populated_pcp_list(struct zone * zone,unsigned int order,struct per_cpu_pages * pcp,int migratetype,unsigned int alloc_flags)3049 static struct list_head *get_populated_pcp_list(struct zone *zone,
3050 unsigned int order, struct per_cpu_pages *pcp,
3051 int migratetype, unsigned int alloc_flags)
3052 {
3053 struct list_head *list = &pcp->lists[migratetype];
3054
3055 if (list_empty(list)) {
3056 pcp->count += rmqueue_bulk(zone, order,
3057 pcp->batch, list,
3058 migratetype, alloc_flags);
3059
3060 if (list_empty(list))
3061 list = NULL;
3062 }
3063 return list;
3064 }
3065
3066 #ifdef CONFIG_NUMA
3067 /*
3068 * Called from the vmstat counter updater to drain pagesets of this
3069 * currently executing processor on remote nodes after they have
3070 * expired.
3071 *
3072 * Note that this function must be called with the thread pinned to
3073 * a single processor.
3074 */
drain_zone_pages(struct zone * zone,struct per_cpu_pages * pcp)3075 void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp)
3076 {
3077 unsigned long flags;
3078 int to_drain, batch;
3079
3080 local_irq_save(flags);
3081 batch = READ_ONCE(pcp->batch);
3082 to_drain = min(pcp->count, batch);
3083 if (to_drain > 0)
3084 free_pcppages_bulk(zone, to_drain, pcp);
3085 local_irq_restore(flags);
3086 }
3087 #endif
3088
3089 /*
3090 * Drain pcplists of the indicated processor and zone.
3091 *
3092 * The processor must either be the current processor and the
3093 * thread pinned to the current processor or a processor that
3094 * is not online.
3095 */
drain_pages_zone(unsigned int cpu,struct zone * zone)3096 static void drain_pages_zone(unsigned int cpu, struct zone *zone)
3097 {
3098 unsigned long flags;
3099 struct per_cpu_pageset *pset;
3100 struct per_cpu_pages *pcp;
3101
3102 local_irq_save(flags);
3103 pset = per_cpu_ptr(zone->pageset, cpu);
3104
3105 pcp = &pset->pcp;
3106 if (pcp->count)
3107 free_pcppages_bulk(zone, pcp->count, pcp);
3108 local_irq_restore(flags);
3109 }
3110
3111 /*
3112 * Drain pcplists of all zones on the indicated processor.
3113 *
3114 * The processor must either be the current processor and the
3115 * thread pinned to the current processor or a processor that
3116 * is not online.
3117 */
drain_pages(unsigned int cpu)3118 static void drain_pages(unsigned int cpu)
3119 {
3120 struct zone *zone;
3121
3122 for_each_populated_zone(zone) {
3123 drain_pages_zone(cpu, zone);
3124 }
3125 }
3126
3127 /*
3128 * Spill all of this CPU's per-cpu pages back into the buddy allocator.
3129 *
3130 * The CPU has to be pinned. When zone parameter is non-NULL, spill just
3131 * the single zone's pages.
3132 */
drain_local_pages(struct zone * zone)3133 void drain_local_pages(struct zone *zone)
3134 {
3135 int cpu = smp_processor_id();
3136
3137 if (zone)
3138 drain_pages_zone(cpu, zone);
3139 else
3140 drain_pages(cpu);
3141 }
3142
drain_local_pages_wq(struct work_struct * work)3143 static void drain_local_pages_wq(struct work_struct *work)
3144 {
3145 struct pcpu_drain *drain;
3146
3147 drain = container_of(work, struct pcpu_drain, work);
3148
3149 /*
3150 * drain_all_pages doesn't use proper cpu hotplug protection so
3151 * we can race with cpu offline when the WQ can move this from
3152 * a cpu pinned worker to an unbound one. We can operate on a different
3153 * cpu which is allright but we also have to make sure to not move to
3154 * a different one.
3155 */
3156 preempt_disable();
3157 drain_local_pages(drain->zone);
3158 preempt_enable();
3159 }
3160
3161 /*
3162 * Spill all the per-cpu pages from all CPUs back into the buddy allocator.
3163 *
3164 * When zone parameter is non-NULL, spill just the single zone's pages.
3165 *
3166 * Note that this can be extremely slow as the draining happens in a workqueue.
3167 */
drain_all_pages(struct zone * zone)3168 void drain_all_pages(struct zone *zone)
3169 {
3170 int cpu;
3171
3172 /*
3173 * Allocate in the BSS so we wont require allocation in
3174 * direct reclaim path for CONFIG_CPUMASK_OFFSTACK=y
3175 */
3176 static cpumask_t cpus_with_pcps;
3177
3178 /*
3179 * Make sure nobody triggers this path before mm_percpu_wq is fully
3180 * initialized.
3181 */
3182 if (WARN_ON_ONCE(!mm_percpu_wq))
3183 return;
3184
3185 /*
3186 * Do not drain if one is already in progress unless it's specific to
3187 * a zone. Such callers are primarily CMA and memory hotplug and need
3188 * the drain to be complete when the call returns.
3189 */
3190 if (unlikely(!mutex_trylock(&pcpu_drain_mutex))) {
3191 if (!zone)
3192 return;
3193 mutex_lock(&pcpu_drain_mutex);
3194 }
3195
3196 /*
3197 * We don't care about racing with CPU hotplug event
3198 * as offline notification will cause the notified
3199 * cpu to drain that CPU pcps and on_each_cpu_mask
3200 * disables preemption as part of its processing
3201 */
3202 for_each_online_cpu(cpu) {
3203 struct per_cpu_pageset *pcp;
3204 struct zone *z;
3205 bool has_pcps = false;
3206
3207 if (zone) {
3208 pcp = per_cpu_ptr(zone->pageset, cpu);
3209 if (pcp->pcp.count)
3210 has_pcps = true;
3211 } else {
3212 for_each_populated_zone(z) {
3213 pcp = per_cpu_ptr(z->pageset, cpu);
3214 if (pcp->pcp.count) {
3215 has_pcps = true;
3216 break;
3217 }
3218 }
3219 }
3220
3221 if (has_pcps)
3222 cpumask_set_cpu(cpu, &cpus_with_pcps);
3223 else
3224 cpumask_clear_cpu(cpu, &cpus_with_pcps);
3225 }
3226
3227 for_each_cpu(cpu, &cpus_with_pcps) {
3228 struct pcpu_drain *drain = per_cpu_ptr(&pcpu_drain, cpu);
3229
3230 drain->zone = zone;
3231 INIT_WORK(&drain->work, drain_local_pages_wq);
3232 queue_work_on(cpu, mm_percpu_wq, &drain->work);
3233 }
3234 for_each_cpu(cpu, &cpus_with_pcps)
3235 flush_work(&per_cpu_ptr(&pcpu_drain, cpu)->work);
3236
3237 mutex_unlock(&pcpu_drain_mutex);
3238 }
3239
3240 #ifdef CONFIG_HIBERNATION
3241
3242 /*
3243 * Touch the watchdog for every WD_PAGE_COUNT pages.
3244 */
3245 #define WD_PAGE_COUNT (128*1024)
3246
mark_free_pages(struct zone * zone)3247 void mark_free_pages(struct zone *zone)
3248 {
3249 unsigned long pfn, max_zone_pfn, page_count = WD_PAGE_COUNT;
3250 unsigned long flags;
3251 unsigned int order, t;
3252 struct page *page;
3253
3254 if (zone_is_empty(zone))
3255 return;
3256
3257 spin_lock_irqsave(&zone->lock, flags);
3258
3259 max_zone_pfn = zone_end_pfn(zone);
3260 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
3261 if (pfn_valid(pfn)) {
3262 page = pfn_to_page(pfn);
3263
3264 if (!--page_count) {
3265 touch_nmi_watchdog();
3266 page_count = WD_PAGE_COUNT;
3267 }
3268
3269 if (page_zone(page) != zone)
3270 continue;
3271
3272 if (!swsusp_page_is_forbidden(page))
3273 swsusp_unset_page_free(page);
3274 }
3275
3276 for_each_migratetype_order(order, t) {
3277 list_for_each_entry(page,
3278 &zone->free_area[order].free_list[t], lru) {
3279 unsigned long i;
3280
3281 pfn = page_to_pfn(page);
3282 for (i = 0; i < (1UL << order); i++) {
3283 if (!--page_count) {
3284 touch_nmi_watchdog();
3285 page_count = WD_PAGE_COUNT;
3286 }
3287 swsusp_set_page_free(pfn_to_page(pfn + i));
3288 }
3289 }
3290 }
3291 spin_unlock_irqrestore(&zone->lock, flags);
3292 }
3293 #endif /* CONFIG_PM */
3294
free_unref_page_prepare(struct page * page,unsigned long pfn)3295 static bool free_unref_page_prepare(struct page *page, unsigned long pfn)
3296 {
3297 int migratetype;
3298
3299 if (!free_pcp_prepare(page))
3300 return false;
3301
3302 migratetype = get_pfnblock_migratetype(page, pfn);
3303 set_pcppage_migratetype(page, migratetype);
3304 return true;
3305 }
3306
free_unref_page_commit(struct page * page,unsigned long pfn)3307 static void free_unref_page_commit(struct page *page, unsigned long pfn)
3308 {
3309 struct zone *zone = page_zone(page);
3310 struct per_cpu_pages *pcp;
3311 int migratetype;
3312 bool pcp_skip_cma_pages = false;
3313
3314 migratetype = get_pcppage_migratetype(page);
3315 __count_vm_event(PGFREE);
3316
3317 /*
3318 * We only track unmovable, reclaimable and movable on pcp lists.
3319 * Free ISOLATE pages back to the allocator because they are being
3320 * offlined but treat HIGHATOMIC as movable pages so we can get those
3321 * areas back if necessary. Otherwise, we may have to free
3322 * excessively into the page allocator
3323 */
3324 if (migratetype >= MIGRATE_PCPTYPES) {
3325 trace_android_vh_pcplist_add_cma_pages_bypass(migratetype,
3326 &pcp_skip_cma_pages);
3327 if (unlikely(is_migrate_isolate(migratetype)) ||
3328 pcp_skip_cma_pages) {
3329 free_one_page(zone, page, pfn, 0, migratetype,
3330 FPI_NONE);
3331 return;
3332 }
3333 migratetype = MIGRATE_MOVABLE;
3334 }
3335
3336 pcp = &this_cpu_ptr(zone->pageset)->pcp;
3337 list_add(&page->lru, &pcp->lists[migratetype]);
3338 pcp->count++;
3339 if (pcp->count >= pcp->high) {
3340 unsigned long batch = READ_ONCE(pcp->batch);
3341 free_pcppages_bulk(zone, batch, pcp);
3342 }
3343 }
3344
3345 /*
3346 * Free a 0-order page
3347 */
free_unref_page(struct page * page)3348 void free_unref_page(struct page *page)
3349 {
3350 unsigned long flags;
3351 unsigned long pfn = page_to_pfn(page);
3352
3353 if (!free_unref_page_prepare(page, pfn))
3354 return;
3355
3356 local_irq_save(flags);
3357 free_unref_page_commit(page, pfn);
3358 local_irq_restore(flags);
3359 }
3360
3361 /*
3362 * Free a list of 0-order pages
3363 */
free_unref_page_list(struct list_head * list)3364 void free_unref_page_list(struct list_head *list)
3365 {
3366 struct page *page, *next;
3367 unsigned long flags, pfn;
3368 int batch_count = 0;
3369
3370 /* Prepare pages for freeing */
3371 list_for_each_entry_safe(page, next, list, lru) {
3372 pfn = page_to_pfn(page);
3373 if (!free_unref_page_prepare(page, pfn))
3374 list_del(&page->lru);
3375 set_page_private(page, pfn);
3376 }
3377
3378 local_irq_save(flags);
3379 list_for_each_entry_safe(page, next, list, lru) {
3380 unsigned long pfn = page_private(page);
3381
3382 set_page_private(page, 0);
3383 trace_mm_page_free_batched(page);
3384 free_unref_page_commit(page, pfn);
3385
3386 /*
3387 * Guard against excessive IRQ disabled times when we get
3388 * a large list of pages to free.
3389 */
3390 if (++batch_count == SWAP_CLUSTER_MAX) {
3391 local_irq_restore(flags);
3392 batch_count = 0;
3393 local_irq_save(flags);
3394 }
3395 }
3396 local_irq_restore(flags);
3397 }
3398
3399 /*
3400 * split_page takes a non-compound higher-order page, and splits it into
3401 * n (1<<order) sub-pages: page[0..n]
3402 * Each sub-page must be freed individually.
3403 *
3404 * Note: this is probably too low level an operation for use in drivers.
3405 * Please consult with lkml before using this in your driver.
3406 */
split_page(struct page * page,unsigned int order)3407 void split_page(struct page *page, unsigned int order)
3408 {
3409 int i;
3410
3411 VM_BUG_ON_PAGE(PageCompound(page), page);
3412 VM_BUG_ON_PAGE(!page_count(page), page);
3413
3414 for (i = 1; i < (1 << order); i++)
3415 set_page_refcounted(page + i);
3416 split_page_owner(page, 1 << order);
3417 split_page_memcg(page, 1 << order);
3418 }
3419 EXPORT_SYMBOL_GPL(split_page);
3420
__isolate_free_page(struct page * page,unsigned int order)3421 int __isolate_free_page(struct page *page, unsigned int order)
3422 {
3423 unsigned long watermark;
3424 struct zone *zone;
3425 int mt;
3426
3427 BUG_ON(!PageBuddy(page));
3428
3429 zone = page_zone(page);
3430 mt = get_pageblock_migratetype(page);
3431
3432 if (!is_migrate_isolate(mt)) {
3433 /*
3434 * Obey watermarks as if the page was being allocated. We can
3435 * emulate a high-order watermark check with a raised order-0
3436 * watermark, because we already know our high-order page
3437 * exists.
3438 */
3439 watermark = zone->_watermark[WMARK_MIN] + (1UL << order);
3440 if (!zone_watermark_ok(zone, 0, watermark, 0, ALLOC_CMA))
3441 return 0;
3442
3443 __mod_zone_freepage_state(zone, -(1UL << order), mt);
3444 }
3445
3446 /* Remove page from free list */
3447
3448 del_page_from_free_list(page, zone, order);
3449
3450 /*
3451 * Set the pageblock if the isolated page is at least half of a
3452 * pageblock
3453 */
3454 if (order >= pageblock_order - 1) {
3455 struct page *endpage = page + (1 << order) - 1;
3456 for (; page < endpage; page += pageblock_nr_pages) {
3457 int mt = get_pageblock_migratetype(page);
3458 if (!is_migrate_isolate(mt) && !is_migrate_cma(mt)
3459 && !is_migrate_highatomic(mt))
3460 set_pageblock_migratetype(page,
3461 MIGRATE_MOVABLE);
3462 }
3463 }
3464
3465
3466 return 1UL << order;
3467 }
3468
3469 /**
3470 * __putback_isolated_page - Return a now-isolated page back where we got it
3471 * @page: Page that was isolated
3472 * @order: Order of the isolated page
3473 * @mt: The page's pageblock's migratetype
3474 *
3475 * This function is meant to return a page pulled from the free lists via
3476 * __isolate_free_page back to the free lists they were pulled from.
3477 */
__putback_isolated_page(struct page * page,unsigned int order,int mt)3478 void __putback_isolated_page(struct page *page, unsigned int order, int mt)
3479 {
3480 struct zone *zone = page_zone(page);
3481
3482 /* zone lock should be held when this function is called */
3483 lockdep_assert_held(&zone->lock);
3484
3485 /* Return isolated page to tail of freelist. */
3486 __free_one_page(page, page_to_pfn(page), zone, order, mt,
3487 FPI_SKIP_REPORT_NOTIFY | FPI_TO_TAIL);
3488 }
3489
3490 /*
3491 * Update NUMA hit/miss statistics
3492 *
3493 * Must be called with interrupts disabled.
3494 */
zone_statistics(struct zone * preferred_zone,struct zone * z)3495 static inline void zone_statistics(struct zone *preferred_zone, struct zone *z)
3496 {
3497 #ifdef CONFIG_NUMA
3498 enum numa_stat_item local_stat = NUMA_LOCAL;
3499
3500 /* skip numa counters update if numa stats is disabled */
3501 if (!static_branch_likely(&vm_numa_stat_key))
3502 return;
3503
3504 if (zone_to_nid(z) != numa_node_id())
3505 local_stat = NUMA_OTHER;
3506
3507 if (zone_to_nid(z) == zone_to_nid(preferred_zone))
3508 __inc_numa_state(z, NUMA_HIT);
3509 else {
3510 __inc_numa_state(z, NUMA_MISS);
3511 __inc_numa_state(preferred_zone, NUMA_FOREIGN);
3512 }
3513 __inc_numa_state(z, local_stat);
3514 #endif
3515 }
3516
3517 /* Remove page from the per-cpu list, caller must protect the list */
__rmqueue_pcplist(struct zone * zone,int migratetype,unsigned int alloc_flags,struct per_cpu_pages * pcp,gfp_t gfp_flags)3518 static struct page *__rmqueue_pcplist(struct zone *zone, int migratetype,
3519 unsigned int alloc_flags,
3520 struct per_cpu_pages *pcp,
3521 gfp_t gfp_flags)
3522 {
3523 struct page *page = NULL;
3524 struct list_head *list = NULL;
3525
3526 do {
3527 /* First try to get CMA pages */
3528 if (migratetype == MIGRATE_MOVABLE &&
3529 alloc_flags & ALLOC_CMA) {
3530 list = get_populated_pcp_list(zone, 0, pcp,
3531 get_cma_migrate_type(), alloc_flags);
3532 }
3533
3534 if (list == NULL) {
3535 /*
3536 * Either CMA is not suitable or there are no
3537 * free CMA pages.
3538 */
3539 list = get_populated_pcp_list(zone, 0, pcp,
3540 migratetype, alloc_flags);
3541 if (unlikely(list == NULL) ||
3542 unlikely(list_empty(list)))
3543 return NULL;
3544 }
3545
3546 page = list_first_entry(list, struct page, lru);
3547 list_del(&page->lru);
3548 pcp->count--;
3549 } while (check_new_pcp(page));
3550
3551 return page;
3552 }
3553
3554 /* Lock and remove page from the per-cpu list */
rmqueue_pcplist(struct zone * preferred_zone,struct zone * zone,gfp_t gfp_flags,int migratetype,unsigned int alloc_flags)3555 static struct page *rmqueue_pcplist(struct zone *preferred_zone,
3556 struct zone *zone, gfp_t gfp_flags,
3557 int migratetype, unsigned int alloc_flags)
3558 {
3559 struct per_cpu_pages *pcp;
3560 struct page *page;
3561 unsigned long flags;
3562
3563 local_irq_save(flags);
3564 pcp = &this_cpu_ptr(zone->pageset)->pcp;
3565 page = __rmqueue_pcplist(zone, migratetype, alloc_flags, pcp,
3566 gfp_flags);
3567 if (page) {
3568 __count_zid_vm_events(PGALLOC, page_zonenum(page), 1);
3569 zone_statistics(preferred_zone, zone);
3570 }
3571 local_irq_restore(flags);
3572 return page;
3573 }
3574
3575 /*
3576 * Allocate a page from the given zone. Use pcplists for order-0 allocations.
3577 */
3578 static inline
rmqueue(struct zone * preferred_zone,struct zone * zone,unsigned int order,gfp_t gfp_flags,unsigned int alloc_flags,int migratetype)3579 struct page *rmqueue(struct zone *preferred_zone,
3580 struct zone *zone, unsigned int order,
3581 gfp_t gfp_flags, unsigned int alloc_flags,
3582 int migratetype)
3583 {
3584 unsigned long flags;
3585 struct page *page;
3586
3587 if (likely(order == 0)) {
3588 page = rmqueue_pcplist(preferred_zone, zone, gfp_flags,
3589 migratetype, alloc_flags);
3590 goto out;
3591 }
3592
3593 /*
3594 * We most definitely don't want callers attempting to
3595 * allocate greater than order-1 page units with __GFP_NOFAIL.
3596 */
3597 WARN_ON_ONCE((gfp_flags & __GFP_NOFAIL) && (order > 1));
3598 spin_lock_irqsave(&zone->lock, flags);
3599
3600 do {
3601 page = NULL;
3602 /*
3603 * order-0 request can reach here when the pcplist is skipped
3604 * due to non-CMA allocation context. HIGHATOMIC area is
3605 * reserved for high-order atomic allocation, so order-0
3606 * request should skip it.
3607 */
3608 if (order > 0 && alloc_flags & ALLOC_HARDER) {
3609 page = __rmqueue_smallest(zone, order, MIGRATE_HIGHATOMIC);
3610 if (page)
3611 trace_mm_page_alloc_zone_locked(page, order, migratetype);
3612 }
3613 if (!page) {
3614 if (migratetype == MIGRATE_MOVABLE &&
3615 alloc_flags & ALLOC_CMA)
3616 page = __rmqueue_cma(zone, order, migratetype,
3617 alloc_flags);
3618 if (!page)
3619 page = __rmqueue(zone, order, migratetype,
3620 alloc_flags);
3621 }
3622 } while (page && check_new_pages(page, order));
3623 spin_unlock(&zone->lock);
3624 if (!page)
3625 goto failed;
3626 __mod_zone_freepage_state(zone, -(1 << order),
3627 get_pcppage_migratetype(page));
3628
3629 __count_zid_vm_events(PGALLOC, page_zonenum(page), 1 << order);
3630 zone_statistics(preferred_zone, zone);
3631 trace_android_vh_rmqueue(preferred_zone, zone, order,
3632 gfp_flags, alloc_flags, migratetype);
3633 local_irq_restore(flags);
3634
3635 out:
3636 /* Separate test+clear to avoid unnecessary atomics */
3637 if (test_bit(ZONE_BOOSTED_WATERMARK, &zone->flags)) {
3638 clear_bit(ZONE_BOOSTED_WATERMARK, &zone->flags);
3639 wakeup_kswapd(zone, 0, 0, zone_idx(zone));
3640 }
3641
3642 VM_BUG_ON_PAGE(page && bad_range(zone, page), page);
3643 return page;
3644
3645 failed:
3646 local_irq_restore(flags);
3647 return NULL;
3648 }
3649
3650 #ifdef CONFIG_FAIL_PAGE_ALLOC
3651
3652 static struct {
3653 struct fault_attr attr;
3654
3655 bool ignore_gfp_highmem;
3656 bool ignore_gfp_reclaim;
3657 u32 min_order;
3658 } fail_page_alloc = {
3659 .attr = FAULT_ATTR_INITIALIZER,
3660 .ignore_gfp_reclaim = true,
3661 .ignore_gfp_highmem = true,
3662 .min_order = 1,
3663 };
3664
setup_fail_page_alloc(char * str)3665 static int __init setup_fail_page_alloc(char *str)
3666 {
3667 return setup_fault_attr(&fail_page_alloc.attr, str);
3668 }
3669 __setup("fail_page_alloc=", setup_fail_page_alloc);
3670
__should_fail_alloc_page(gfp_t gfp_mask,unsigned int order)3671 static bool __should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
3672 {
3673 if (order < fail_page_alloc.min_order)
3674 return false;
3675 if (gfp_mask & __GFP_NOFAIL)
3676 return false;
3677 if (fail_page_alloc.ignore_gfp_highmem && (gfp_mask & __GFP_HIGHMEM))
3678 return false;
3679 if (fail_page_alloc.ignore_gfp_reclaim &&
3680 (gfp_mask & __GFP_DIRECT_RECLAIM))
3681 return false;
3682
3683 return should_fail(&fail_page_alloc.attr, 1 << order);
3684 }
3685
3686 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
3687
fail_page_alloc_debugfs(void)3688 static int __init fail_page_alloc_debugfs(void)
3689 {
3690 umode_t mode = S_IFREG | 0600;
3691 struct dentry *dir;
3692
3693 dir = fault_create_debugfs_attr("fail_page_alloc", NULL,
3694 &fail_page_alloc.attr);
3695
3696 debugfs_create_bool("ignore-gfp-wait", mode, dir,
3697 &fail_page_alloc.ignore_gfp_reclaim);
3698 debugfs_create_bool("ignore-gfp-highmem", mode, dir,
3699 &fail_page_alloc.ignore_gfp_highmem);
3700 debugfs_create_u32("min-order", mode, dir, &fail_page_alloc.min_order);
3701
3702 return 0;
3703 }
3704
3705 late_initcall(fail_page_alloc_debugfs);
3706
3707 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
3708
3709 #else /* CONFIG_FAIL_PAGE_ALLOC */
3710
__should_fail_alloc_page(gfp_t gfp_mask,unsigned int order)3711 static inline bool __should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
3712 {
3713 return false;
3714 }
3715
3716 #endif /* CONFIG_FAIL_PAGE_ALLOC */
3717
should_fail_alloc_page(gfp_t gfp_mask,unsigned int order)3718 noinline bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
3719 {
3720 return __should_fail_alloc_page(gfp_mask, order);
3721 }
3722 ALLOW_ERROR_INJECTION(should_fail_alloc_page, TRUE);
3723
__zone_watermark_unusable_free(struct zone * z,unsigned int order,unsigned int alloc_flags)3724 static inline long __zone_watermark_unusable_free(struct zone *z,
3725 unsigned int order, unsigned int alloc_flags)
3726 {
3727 const bool alloc_harder = (alloc_flags & (ALLOC_HARDER|ALLOC_OOM));
3728 long unusable_free = (1 << order) - 1;
3729
3730 /*
3731 * If the caller does not have rights to ALLOC_HARDER then subtract
3732 * the high-atomic reserves. This will over-estimate the size of the
3733 * atomic reserve but it avoids a search.
3734 */
3735 if (likely(!alloc_harder))
3736 unusable_free += z->nr_reserved_highatomic;
3737
3738 #ifdef CONFIG_CMA
3739 /* If allocation can't use CMA areas don't use free CMA pages */
3740 if (!(alloc_flags & ALLOC_CMA))
3741 unusable_free += zone_page_state(z, NR_FREE_CMA_PAGES);
3742 #endif
3743
3744 return unusable_free;
3745 }
3746
3747 /*
3748 * Return true if free base pages are above 'mark'. For high-order checks it
3749 * will return true of the order-0 watermark is reached and there is at least
3750 * one free page of a suitable size. Checking now avoids taking the zone lock
3751 * to check in the allocation paths if no pages are free.
3752 */
__zone_watermark_ok(struct zone * z,unsigned int order,unsigned long mark,int highest_zoneidx,unsigned int alloc_flags,long free_pages)3753 bool __zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
3754 int highest_zoneidx, unsigned int alloc_flags,
3755 long free_pages)
3756 {
3757 long min = mark;
3758 int o;
3759 const bool alloc_harder = (alloc_flags & (ALLOC_HARDER|ALLOC_OOM));
3760
3761 /* free_pages may go negative - that's OK */
3762 free_pages -= __zone_watermark_unusable_free(z, order, alloc_flags);
3763
3764 if (alloc_flags & ALLOC_HIGH)
3765 min -= min / 2;
3766
3767 if (unlikely(alloc_harder)) {
3768 /*
3769 * OOM victims can try even harder than normal ALLOC_HARDER
3770 * users on the grounds that it's definitely going to be in
3771 * the exit path shortly and free memory. Any allocation it
3772 * makes during the free path will be small and short-lived.
3773 */
3774 if (alloc_flags & ALLOC_OOM)
3775 min -= min / 2;
3776 else
3777 min -= min / 4;
3778 }
3779
3780 /*
3781 * Check watermarks for an order-0 allocation request. If these
3782 * are not met, then a high-order request also cannot go ahead
3783 * even if a suitable page happened to be free.
3784 */
3785 if (free_pages <= min + z->lowmem_reserve[highest_zoneidx])
3786 return false;
3787
3788 /* If this is an order-0 request then the watermark is fine */
3789 if (!order)
3790 return true;
3791
3792 /* For a high-order request, check at least one suitable page is free */
3793 for (o = order; o < MAX_ORDER; o++) {
3794 struct free_area *area = &z->free_area[o];
3795 int mt;
3796
3797 if (!area->nr_free)
3798 continue;
3799
3800 for (mt = 0; mt < MIGRATE_PCPTYPES; mt++) {
3801 #ifdef CONFIG_CMA
3802 /*
3803 * Note that this check is needed only
3804 * when MIGRATE_CMA < MIGRATE_PCPTYPES.
3805 */
3806 if (mt == MIGRATE_CMA)
3807 continue;
3808 #endif
3809 if (!free_area_empty(area, mt))
3810 return true;
3811 }
3812
3813 #ifdef CONFIG_CMA
3814 if ((alloc_flags & ALLOC_CMA) &&
3815 !free_area_empty(area, MIGRATE_CMA)) {
3816 return true;
3817 }
3818 #endif
3819 if (alloc_harder && !free_area_empty(area, MIGRATE_HIGHATOMIC))
3820 return true;
3821 }
3822 return false;
3823 }
3824
zone_watermark_ok(struct zone * z,unsigned int order,unsigned long mark,int highest_zoneidx,unsigned int alloc_flags)3825 bool zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
3826 int highest_zoneidx, unsigned int alloc_flags)
3827 {
3828 return __zone_watermark_ok(z, order, mark, highest_zoneidx, alloc_flags,
3829 zone_page_state(z, NR_FREE_PAGES));
3830 }
3831 EXPORT_SYMBOL_GPL(zone_watermark_ok);
3832
zone_watermark_fast(struct zone * z,unsigned int order,unsigned long mark,int highest_zoneidx,unsigned int alloc_flags,gfp_t gfp_mask)3833 static inline bool zone_watermark_fast(struct zone *z, unsigned int order,
3834 unsigned long mark, int highest_zoneidx,
3835 unsigned int alloc_flags, gfp_t gfp_mask)
3836 {
3837 long free_pages;
3838
3839 free_pages = zone_page_state(z, NR_FREE_PAGES);
3840
3841 /*
3842 * Fast check for order-0 only. If this fails then the reserves
3843 * need to be calculated.
3844 */
3845 if (!order) {
3846 long usable_free;
3847 long reserved;
3848
3849 usable_free = free_pages;
3850 reserved = __zone_watermark_unusable_free(z, 0, alloc_flags);
3851
3852 /* reserved may over estimate high-atomic reserves. */
3853 usable_free -= min(usable_free, reserved);
3854 if (usable_free > mark + z->lowmem_reserve[highest_zoneidx])
3855 return true;
3856 }
3857
3858 if (__zone_watermark_ok(z, order, mark, highest_zoneidx, alloc_flags,
3859 free_pages))
3860 return true;
3861 /*
3862 * Ignore watermark boosting for GFP_ATOMIC order-0 allocations
3863 * when checking the min watermark. The min watermark is the
3864 * point where boosting is ignored so that kswapd is woken up
3865 * when below the low watermark.
3866 */
3867 if (unlikely(!order && (gfp_mask & __GFP_ATOMIC) && z->watermark_boost
3868 && ((alloc_flags & ALLOC_WMARK_MASK) == WMARK_MIN))) {
3869 mark = z->_watermark[WMARK_MIN];
3870 return __zone_watermark_ok(z, order, mark, highest_zoneidx,
3871 alloc_flags, free_pages);
3872 }
3873
3874 return false;
3875 }
3876
zone_watermark_ok_safe(struct zone * z,unsigned int order,unsigned long mark,int highest_zoneidx)3877 bool zone_watermark_ok_safe(struct zone *z, unsigned int order,
3878 unsigned long mark, int highest_zoneidx)
3879 {
3880 long free_pages = zone_page_state(z, NR_FREE_PAGES);
3881
3882 if (z->percpu_drift_mark && free_pages < z->percpu_drift_mark)
3883 free_pages = zone_page_state_snapshot(z, NR_FREE_PAGES);
3884
3885 return __zone_watermark_ok(z, order, mark, highest_zoneidx, 0,
3886 free_pages);
3887 }
3888 EXPORT_SYMBOL_GPL(zone_watermark_ok_safe);
3889
3890 #ifdef CONFIG_NUMA
zone_allows_reclaim(struct zone * local_zone,struct zone * zone)3891 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
3892 {
3893 return node_distance(zone_to_nid(local_zone), zone_to_nid(zone)) <=
3894 node_reclaim_distance;
3895 }
3896 #else /* CONFIG_NUMA */
zone_allows_reclaim(struct zone * local_zone,struct zone * zone)3897 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
3898 {
3899 return true;
3900 }
3901 #endif /* CONFIG_NUMA */
3902
3903 /*
3904 * The restriction on ZONE_DMA32 as being a suitable zone to use to avoid
3905 * fragmentation is subtle. If the preferred zone was HIGHMEM then
3906 * premature use of a lower zone may cause lowmem pressure problems that
3907 * are worse than fragmentation. If the next zone is ZONE_DMA then it is
3908 * probably too small. It only makes sense to spread allocations to avoid
3909 * fragmentation between the Normal and DMA32 zones.
3910 */
3911 static inline unsigned int
alloc_flags_nofragment(struct zone * zone,gfp_t gfp_mask)3912 alloc_flags_nofragment(struct zone *zone, gfp_t gfp_mask)
3913 {
3914 unsigned int alloc_flags;
3915
3916 /*
3917 * __GFP_KSWAPD_RECLAIM is assumed to be the same as ALLOC_KSWAPD
3918 * to save a branch.
3919 */
3920 alloc_flags = (__force int) (gfp_mask & __GFP_KSWAPD_RECLAIM);
3921
3922 #ifdef CONFIG_ZONE_DMA32
3923 if (!zone)
3924 return alloc_flags;
3925
3926 if (zone_idx(zone) != ZONE_NORMAL)
3927 return alloc_flags;
3928
3929 /*
3930 * If ZONE_DMA32 exists, assume it is the one after ZONE_NORMAL and
3931 * the pointer is within zone->zone_pgdat->node_zones[]. Also assume
3932 * on UMA that if Normal is populated then so is DMA32.
3933 */
3934 BUILD_BUG_ON(ZONE_NORMAL - ZONE_DMA32 != 1);
3935 if (nr_online_nodes > 1 && !populated_zone(--zone))
3936 return alloc_flags;
3937
3938 alloc_flags |= ALLOC_NOFRAGMENT;
3939 #endif /* CONFIG_ZONE_DMA32 */
3940 return alloc_flags;
3941 }
3942
current_alloc_flags(gfp_t gfp_mask,unsigned int alloc_flags)3943 static inline unsigned int current_alloc_flags(gfp_t gfp_mask,
3944 unsigned int alloc_flags)
3945 {
3946 #ifdef CONFIG_CMA
3947 unsigned int pflags = current->flags;
3948
3949 if (!(pflags & PF_MEMALLOC_NOCMA) &&
3950 gfp_migratetype(gfp_mask) == MIGRATE_MOVABLE &&
3951 gfp_mask & __GFP_CMA)
3952 alloc_flags |= ALLOC_CMA;
3953
3954 #endif
3955 return alloc_flags;
3956 }
3957
3958 /*
3959 * get_page_from_freelist goes through the zonelist trying to allocate
3960 * a page.
3961 */
3962 static struct page *
get_page_from_freelist(gfp_t gfp_mask,unsigned int order,int alloc_flags,const struct alloc_context * ac)3963 get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags,
3964 const struct alloc_context *ac)
3965 {
3966 struct zoneref *z;
3967 struct zone *zone;
3968 struct pglist_data *last_pgdat_dirty_limit = NULL;
3969 bool no_fallback;
3970
3971 retry:
3972 /*
3973 * Scan zonelist, looking for a zone with enough free.
3974 * See also __cpuset_node_allowed() comment in kernel/cpuset.c.
3975 */
3976 no_fallback = alloc_flags & ALLOC_NOFRAGMENT;
3977 z = ac->preferred_zoneref;
3978 for_next_zone_zonelist_nodemask(zone, z, ac->highest_zoneidx,
3979 ac->nodemask) {
3980 struct page *page;
3981 unsigned long mark;
3982
3983 if (cpusets_enabled() &&
3984 (alloc_flags & ALLOC_CPUSET) &&
3985 !__cpuset_zone_allowed(zone, gfp_mask))
3986 continue;
3987 /*
3988 * When allocating a page cache page for writing, we
3989 * want to get it from a node that is within its dirty
3990 * limit, such that no single node holds more than its
3991 * proportional share of globally allowed dirty pages.
3992 * The dirty limits take into account the node's
3993 * lowmem reserves and high watermark so that kswapd
3994 * should be able to balance it without having to
3995 * write pages from its LRU list.
3996 *
3997 * XXX: For now, allow allocations to potentially
3998 * exceed the per-node dirty limit in the slowpath
3999 * (spread_dirty_pages unset) before going into reclaim,
4000 * which is important when on a NUMA setup the allowed
4001 * nodes are together not big enough to reach the
4002 * global limit. The proper fix for these situations
4003 * will require awareness of nodes in the
4004 * dirty-throttling and the flusher threads.
4005 */
4006 if (ac->spread_dirty_pages) {
4007 if (last_pgdat_dirty_limit == zone->zone_pgdat)
4008 continue;
4009
4010 if (!node_dirty_ok(zone->zone_pgdat)) {
4011 last_pgdat_dirty_limit = zone->zone_pgdat;
4012 continue;
4013 }
4014 }
4015
4016 if (no_fallback && nr_online_nodes > 1 &&
4017 zone != ac->preferred_zoneref->zone) {
4018 int local_nid;
4019
4020 /*
4021 * If moving to a remote node, retry but allow
4022 * fragmenting fallbacks. Locality is more important
4023 * than fragmentation avoidance.
4024 */
4025 local_nid = zone_to_nid(ac->preferred_zoneref->zone);
4026 if (zone_to_nid(zone) != local_nid) {
4027 alloc_flags &= ~ALLOC_NOFRAGMENT;
4028 goto retry;
4029 }
4030 }
4031
4032 mark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK);
4033 if (!zone_watermark_fast(zone, order, mark,
4034 ac->highest_zoneidx, alloc_flags,
4035 gfp_mask)) {
4036 int ret;
4037
4038 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
4039 /*
4040 * Watermark failed for this zone, but see if we can
4041 * grow this zone if it contains deferred pages.
4042 */
4043 if (static_branch_unlikely(&deferred_pages)) {
4044 if (_deferred_grow_zone(zone, order))
4045 goto try_this_zone;
4046 }
4047 #endif
4048 /* Checked here to keep the fast path fast */
4049 BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK);
4050 if (alloc_flags & ALLOC_NO_WATERMARKS)
4051 goto try_this_zone;
4052
4053 if (node_reclaim_mode == 0 ||
4054 !zone_allows_reclaim(ac->preferred_zoneref->zone, zone))
4055 continue;
4056
4057 ret = node_reclaim(zone->zone_pgdat, gfp_mask, order);
4058 switch (ret) {
4059 case NODE_RECLAIM_NOSCAN:
4060 /* did not scan */
4061 continue;
4062 case NODE_RECLAIM_FULL:
4063 /* scanned but unreclaimable */
4064 continue;
4065 default:
4066 /* did we reclaim enough */
4067 if (zone_watermark_ok(zone, order, mark,
4068 ac->highest_zoneidx, alloc_flags))
4069 goto try_this_zone;
4070
4071 continue;
4072 }
4073 }
4074
4075 try_this_zone:
4076 page = rmqueue(ac->preferred_zoneref->zone, zone, order,
4077 gfp_mask, alloc_flags, ac->migratetype);
4078 if (page) {
4079 prep_new_page(page, order, gfp_mask, alloc_flags);
4080
4081 /*
4082 * If this is a high-order atomic allocation then check
4083 * if the pageblock should be reserved for the future
4084 */
4085 if (unlikely(order && (alloc_flags & ALLOC_HARDER)))
4086 reserve_highatomic_pageblock(page, zone, order);
4087
4088 return page;
4089 } else {
4090 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
4091 /* Try again if zone has deferred pages */
4092 if (static_branch_unlikely(&deferred_pages)) {
4093 if (_deferred_grow_zone(zone, order))
4094 goto try_this_zone;
4095 }
4096 #endif
4097 }
4098 }
4099
4100 /*
4101 * It's possible on a UMA machine to get through all zones that are
4102 * fragmented. If avoiding fragmentation, reset and try again.
4103 */
4104 if (no_fallback) {
4105 alloc_flags &= ~ALLOC_NOFRAGMENT;
4106 goto retry;
4107 }
4108
4109 return NULL;
4110 }
4111
warn_alloc_show_mem(gfp_t gfp_mask,nodemask_t * nodemask)4112 static void warn_alloc_show_mem(gfp_t gfp_mask, nodemask_t *nodemask)
4113 {
4114 unsigned int filter = SHOW_MEM_FILTER_NODES;
4115
4116 /*
4117 * This documents exceptions given to allocations in certain
4118 * contexts that are allowed to allocate outside current's set
4119 * of allowed nodes.
4120 */
4121 if (!(gfp_mask & __GFP_NOMEMALLOC))
4122 if (tsk_is_oom_victim(current) ||
4123 (current->flags & (PF_MEMALLOC | PF_EXITING)))
4124 filter &= ~SHOW_MEM_FILTER_NODES;
4125 if (in_interrupt() || !(gfp_mask & __GFP_DIRECT_RECLAIM))
4126 filter &= ~SHOW_MEM_FILTER_NODES;
4127
4128 show_mem(filter, nodemask);
4129 }
4130
warn_alloc(gfp_t gfp_mask,nodemask_t * nodemask,const char * fmt,...)4131 void warn_alloc(gfp_t gfp_mask, nodemask_t *nodemask, const char *fmt, ...)
4132 {
4133 struct va_format vaf;
4134 va_list args;
4135 static DEFINE_RATELIMIT_STATE(nopage_rs, 10*HZ, 1);
4136
4137 if ((gfp_mask & __GFP_NOWARN) ||
4138 !__ratelimit(&nopage_rs) ||
4139 ((gfp_mask & __GFP_DMA) && !has_managed_dma()))
4140 return;
4141
4142 va_start(args, fmt);
4143 vaf.fmt = fmt;
4144 vaf.va = &args;
4145 pr_warn("%s: %pV, mode:%#x(%pGg), nodemask=%*pbl",
4146 current->comm, &vaf, gfp_mask, &gfp_mask,
4147 nodemask_pr_args(nodemask));
4148 va_end(args);
4149
4150 cpuset_print_current_mems_allowed();
4151 pr_cont("\n");
4152 dump_stack();
4153 warn_alloc_show_mem(gfp_mask, nodemask);
4154 }
4155
4156 static inline struct page *
__alloc_pages_cpuset_fallback(gfp_t gfp_mask,unsigned int order,unsigned int alloc_flags,const struct alloc_context * ac)4157 __alloc_pages_cpuset_fallback(gfp_t gfp_mask, unsigned int order,
4158 unsigned int alloc_flags,
4159 const struct alloc_context *ac)
4160 {
4161 struct page *page;
4162
4163 page = get_page_from_freelist(gfp_mask, order,
4164 alloc_flags|ALLOC_CPUSET, ac);
4165 /*
4166 * fallback to ignore cpuset restriction if our nodes
4167 * are depleted
4168 */
4169 if (!page)
4170 page = get_page_from_freelist(gfp_mask, order,
4171 alloc_flags, ac);
4172
4173 return page;
4174 }
4175
4176 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)4177 __alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order,
4178 const struct alloc_context *ac, unsigned long *did_some_progress)
4179 {
4180 struct oom_control oc = {
4181 .zonelist = ac->zonelist,
4182 .nodemask = ac->nodemask,
4183 .memcg = NULL,
4184 .gfp_mask = gfp_mask,
4185 .order = order,
4186 };
4187 struct page *page;
4188
4189 *did_some_progress = 0;
4190
4191 /*
4192 * Acquire the oom lock. If that fails, somebody else is
4193 * making progress for us.
4194 */
4195 if (!mutex_trylock(&oom_lock)) {
4196 *did_some_progress = 1;
4197 schedule_timeout_uninterruptible(1);
4198 return NULL;
4199 }
4200
4201 /*
4202 * Go through the zonelist yet one more time, keep very high watermark
4203 * here, this is only to catch a parallel oom killing, we must fail if
4204 * we're still under heavy pressure. But make sure that this reclaim
4205 * attempt shall not depend on __GFP_DIRECT_RECLAIM && !__GFP_NORETRY
4206 * allocation which will never fail due to oom_lock already held.
4207 */
4208 page = get_page_from_freelist((gfp_mask | __GFP_HARDWALL) &
4209 ~__GFP_DIRECT_RECLAIM, order,
4210 ALLOC_WMARK_HIGH|ALLOC_CPUSET, ac);
4211 if (page)
4212 goto out;
4213
4214 /* Coredumps can quickly deplete all memory reserves */
4215 if (current->flags & PF_DUMPCORE)
4216 goto out;
4217 /* The OOM killer will not help higher order allocs */
4218 if (order > PAGE_ALLOC_COSTLY_ORDER)
4219 goto out;
4220 /*
4221 * We have already exhausted all our reclaim opportunities without any
4222 * success so it is time to admit defeat. We will skip the OOM killer
4223 * because it is very likely that the caller has a more reasonable
4224 * fallback than shooting a random task.
4225 *
4226 * The OOM killer may not free memory on a specific node.
4227 */
4228 if (gfp_mask & (__GFP_RETRY_MAYFAIL | __GFP_THISNODE))
4229 goto out;
4230 /* The OOM killer does not needlessly kill tasks for lowmem */
4231 if (ac->highest_zoneidx < ZONE_NORMAL)
4232 goto out;
4233 if (pm_suspended_storage())
4234 goto out;
4235 /*
4236 * XXX: GFP_NOFS allocations should rather fail than rely on
4237 * other request to make a forward progress.
4238 * We are in an unfortunate situation where out_of_memory cannot
4239 * do much for this context but let's try it to at least get
4240 * access to memory reserved if the current task is killed (see
4241 * out_of_memory). Once filesystems are ready to handle allocation
4242 * failures more gracefully we should just bail out here.
4243 */
4244
4245 /* Exhausted what can be done so it's blame time */
4246 if (out_of_memory(&oc) || WARN_ON_ONCE(gfp_mask & __GFP_NOFAIL)) {
4247 *did_some_progress = 1;
4248
4249 /*
4250 * Help non-failing allocations by giving them access to memory
4251 * reserves
4252 */
4253 if (gfp_mask & __GFP_NOFAIL)
4254 page = __alloc_pages_cpuset_fallback(gfp_mask, order,
4255 ALLOC_NO_WATERMARKS, ac);
4256 }
4257 out:
4258 mutex_unlock(&oom_lock);
4259 return page;
4260 }
4261
4262 /*
4263 * Maximum number of compaction retries wit a progress before OOM
4264 * killer is consider as the only way to move forward.
4265 */
4266 #define MAX_COMPACT_RETRIES 16
4267
4268 #ifdef CONFIG_COMPACTION
4269 /* Try memory compaction for high-order allocations before reclaim */
4270 static struct page *
__alloc_pages_direct_compact(gfp_t gfp_mask,unsigned int order,unsigned int alloc_flags,const struct alloc_context * ac,enum compact_priority prio,enum compact_result * compact_result)4271 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
4272 unsigned int alloc_flags, const struct alloc_context *ac,
4273 enum compact_priority prio, enum compact_result *compact_result)
4274 {
4275 struct page *page = NULL;
4276 unsigned long pflags;
4277 unsigned int noreclaim_flag;
4278
4279 if (!order)
4280 return NULL;
4281
4282 psi_memstall_enter(&pflags);
4283 noreclaim_flag = memalloc_noreclaim_save();
4284
4285 *compact_result = try_to_compact_pages(gfp_mask, order, alloc_flags, ac,
4286 prio, &page);
4287
4288 memalloc_noreclaim_restore(noreclaim_flag);
4289 psi_memstall_leave(&pflags);
4290
4291 /*
4292 * At least in one zone compaction wasn't deferred or skipped, so let's
4293 * count a compaction stall
4294 */
4295 count_vm_event(COMPACTSTALL);
4296
4297 /* Prep a captured page if available */
4298 if (page)
4299 prep_new_page(page, order, gfp_mask, alloc_flags);
4300
4301 /* Try get a page from the freelist if available */
4302 if (!page)
4303 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4304
4305 if (page) {
4306 struct zone *zone = page_zone(page);
4307
4308 zone->compact_blockskip_flush = false;
4309 compaction_defer_reset(zone, order, true);
4310 count_vm_event(COMPACTSUCCESS);
4311 return page;
4312 }
4313
4314 /*
4315 * It's bad if compaction run occurs and fails. The most likely reason
4316 * is that pages exist, but not enough to satisfy watermarks.
4317 */
4318 count_vm_event(COMPACTFAIL);
4319
4320 cond_resched();
4321
4322 return NULL;
4323 }
4324
4325 static inline bool
should_compact_retry(struct alloc_context * ac,int order,int alloc_flags,enum compact_result compact_result,enum compact_priority * compact_priority,int * compaction_retries)4326 should_compact_retry(struct alloc_context *ac, int order, int alloc_flags,
4327 enum compact_result compact_result,
4328 enum compact_priority *compact_priority,
4329 int *compaction_retries)
4330 {
4331 int max_retries = MAX_COMPACT_RETRIES;
4332 int min_priority;
4333 bool ret = false;
4334 int retries = *compaction_retries;
4335 enum compact_priority priority = *compact_priority;
4336
4337 if (!order)
4338 return false;
4339
4340 if (compaction_made_progress(compact_result))
4341 (*compaction_retries)++;
4342
4343 /*
4344 * compaction considers all the zone as desperately out of memory
4345 * so it doesn't really make much sense to retry except when the
4346 * failure could be caused by insufficient priority
4347 */
4348 if (compaction_failed(compact_result))
4349 goto check_priority;
4350
4351 /*
4352 * compaction was skipped because there are not enough order-0 pages
4353 * to work with, so we retry only if it looks like reclaim can help.
4354 */
4355 if (compaction_needs_reclaim(compact_result)) {
4356 ret = compaction_zonelist_suitable(ac, order, alloc_flags);
4357 goto out;
4358 }
4359
4360 /*
4361 * make sure the compaction wasn't deferred or didn't bail out early
4362 * due to locks contention before we declare that we should give up.
4363 * But the next retry should use a higher priority if allowed, so
4364 * we don't just keep bailing out endlessly.
4365 */
4366 if (compaction_withdrawn(compact_result)) {
4367 goto check_priority;
4368 }
4369
4370 /*
4371 * !costly requests are much more important than __GFP_RETRY_MAYFAIL
4372 * costly ones because they are de facto nofail and invoke OOM
4373 * killer to move on while costly can fail and users are ready
4374 * to cope with that. 1/4 retries is rather arbitrary but we
4375 * would need much more detailed feedback from compaction to
4376 * make a better decision.
4377 */
4378 if (order > PAGE_ALLOC_COSTLY_ORDER)
4379 max_retries /= 4;
4380 if (*compaction_retries <= max_retries) {
4381 ret = true;
4382 goto out;
4383 }
4384
4385 /*
4386 * Make sure there are attempts at the highest priority if we exhausted
4387 * all retries or failed at the lower priorities.
4388 */
4389 check_priority:
4390 min_priority = (order > PAGE_ALLOC_COSTLY_ORDER) ?
4391 MIN_COMPACT_COSTLY_PRIORITY : MIN_COMPACT_PRIORITY;
4392
4393 if (*compact_priority > min_priority) {
4394 (*compact_priority)--;
4395 *compaction_retries = 0;
4396 ret = true;
4397 }
4398 out:
4399 trace_compact_retry(order, priority, compact_result, retries, max_retries, ret);
4400 return ret;
4401 }
4402 #else
4403 static inline struct page *
__alloc_pages_direct_compact(gfp_t gfp_mask,unsigned int order,unsigned int alloc_flags,const struct alloc_context * ac,enum compact_priority prio,enum compact_result * compact_result)4404 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
4405 unsigned int alloc_flags, const struct alloc_context *ac,
4406 enum compact_priority prio, enum compact_result *compact_result)
4407 {
4408 *compact_result = COMPACT_SKIPPED;
4409 return NULL;
4410 }
4411
4412 static inline bool
should_compact_retry(struct alloc_context * ac,unsigned int order,int alloc_flags,enum compact_result compact_result,enum compact_priority * compact_priority,int * compaction_retries)4413 should_compact_retry(struct alloc_context *ac, unsigned int order, int alloc_flags,
4414 enum compact_result compact_result,
4415 enum compact_priority *compact_priority,
4416 int *compaction_retries)
4417 {
4418 struct zone *zone;
4419 struct zoneref *z;
4420
4421 if (!order || order > PAGE_ALLOC_COSTLY_ORDER)
4422 return false;
4423
4424 /*
4425 * There are setups with compaction disabled which would prefer to loop
4426 * inside the allocator rather than hit the oom killer prematurely.
4427 * Let's give them a good hope and keep retrying while the order-0
4428 * watermarks are OK.
4429 */
4430 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
4431 ac->highest_zoneidx, ac->nodemask) {
4432 if (zone_watermark_ok(zone, 0, min_wmark_pages(zone),
4433 ac->highest_zoneidx, alloc_flags))
4434 return true;
4435 }
4436 return false;
4437 }
4438 #endif /* CONFIG_COMPACTION */
4439
4440 #ifdef CONFIG_LOCKDEP
4441 static struct lockdep_map __fs_reclaim_map =
4442 STATIC_LOCKDEP_MAP_INIT("fs_reclaim", &__fs_reclaim_map);
4443
__need_fs_reclaim(gfp_t gfp_mask)4444 static bool __need_fs_reclaim(gfp_t gfp_mask)
4445 {
4446 gfp_mask = current_gfp_context(gfp_mask);
4447
4448 /* no reclaim without waiting on it */
4449 if (!(gfp_mask & __GFP_DIRECT_RECLAIM))
4450 return false;
4451
4452 /* this guy won't enter reclaim */
4453 if (current->flags & PF_MEMALLOC)
4454 return false;
4455
4456 /* We're only interested __GFP_FS allocations for now */
4457 if (!(gfp_mask & __GFP_FS))
4458 return false;
4459
4460 if (gfp_mask & __GFP_NOLOCKDEP)
4461 return false;
4462
4463 return true;
4464 }
4465
__fs_reclaim_acquire(void)4466 void __fs_reclaim_acquire(void)
4467 {
4468 lock_map_acquire(&__fs_reclaim_map);
4469 }
4470
__fs_reclaim_release(void)4471 void __fs_reclaim_release(void)
4472 {
4473 lock_map_release(&__fs_reclaim_map);
4474 }
4475
fs_reclaim_acquire(gfp_t gfp_mask)4476 void fs_reclaim_acquire(gfp_t gfp_mask)
4477 {
4478 if (__need_fs_reclaim(gfp_mask))
4479 __fs_reclaim_acquire();
4480 }
4481 EXPORT_SYMBOL_GPL(fs_reclaim_acquire);
4482
fs_reclaim_release(gfp_t gfp_mask)4483 void fs_reclaim_release(gfp_t gfp_mask)
4484 {
4485 if (__need_fs_reclaim(gfp_mask))
4486 __fs_reclaim_release();
4487 }
4488 EXPORT_SYMBOL_GPL(fs_reclaim_release);
4489 #endif
4490
4491 /*
4492 * Zonelists may change due to hotplug during allocation. Detect when zonelists
4493 * have been rebuilt so allocation retries. Reader side does not lock and
4494 * retries the allocation if zonelist changes. Writer side is protected by the
4495 * embedded spin_lock.
4496 */
4497 static DEFINE_SEQLOCK(zonelist_update_seq);
4498
zonelist_iter_begin(void)4499 static unsigned int zonelist_iter_begin(void)
4500 {
4501 if (IS_ENABLED(CONFIG_MEMORY_HOTREMOVE))
4502 return read_seqbegin(&zonelist_update_seq);
4503
4504 return 0;
4505 }
4506
check_retry_zonelist(unsigned int seq)4507 static unsigned int check_retry_zonelist(unsigned int seq)
4508 {
4509 if (IS_ENABLED(CONFIG_MEMORY_HOTREMOVE))
4510 return read_seqretry(&zonelist_update_seq, seq);
4511
4512 return seq;
4513 }
4514
4515 /* Perform direct synchronous page reclaim */
4516 static unsigned long
__perform_reclaim(gfp_t gfp_mask,unsigned int order,const struct alloc_context * ac)4517 __perform_reclaim(gfp_t gfp_mask, unsigned int order,
4518 const struct alloc_context *ac)
4519 {
4520 unsigned int noreclaim_flag;
4521 unsigned long progress;
4522
4523 cond_resched();
4524
4525 /* We now go into synchronous reclaim */
4526 cpuset_memory_pressure_bump();
4527 fs_reclaim_acquire(gfp_mask);
4528 noreclaim_flag = memalloc_noreclaim_save();
4529
4530 progress = try_to_free_pages(ac->zonelist, order, gfp_mask,
4531 ac->nodemask);
4532
4533 memalloc_noreclaim_restore(noreclaim_flag);
4534 fs_reclaim_release(gfp_mask);
4535
4536 cond_resched();
4537
4538 return progress;
4539 }
4540
4541 /* The really slow allocator path where we enter direct reclaim */
4542 static inline struct page *
__alloc_pages_direct_reclaim(gfp_t gfp_mask,unsigned int order,unsigned int alloc_flags,const struct alloc_context * ac,unsigned long * did_some_progress)4543 __alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order,
4544 unsigned int alloc_flags, const struct alloc_context *ac,
4545 unsigned long *did_some_progress)
4546 {
4547 struct page *page = NULL;
4548 unsigned long pflags;
4549 bool drained = false;
4550 bool skip_pcp_drain = false;
4551
4552 psi_memstall_enter(&pflags);
4553 *did_some_progress = __perform_reclaim(gfp_mask, order, ac);
4554 if (unlikely(!(*did_some_progress)))
4555 goto out;
4556
4557 retry:
4558 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4559
4560 /*
4561 * If an allocation failed after direct reclaim, it could be because
4562 * pages are pinned on the per-cpu lists or in high alloc reserves.
4563 * Shrink them and try again
4564 */
4565 if (!page && !drained) {
4566 unreserve_highatomic_pageblock(ac, false);
4567 trace_android_vh_drain_all_pages_bypass(gfp_mask, order,
4568 alloc_flags, ac->migratetype, *did_some_progress, &skip_pcp_drain);
4569 if (!skip_pcp_drain)
4570 drain_all_pages(NULL);
4571 drained = true;
4572 goto retry;
4573 }
4574 out:
4575 psi_memstall_leave(&pflags);
4576
4577 return page;
4578 }
4579
wake_all_kswapds(unsigned int order,gfp_t gfp_mask,const struct alloc_context * ac)4580 static void wake_all_kswapds(unsigned int order, gfp_t gfp_mask,
4581 const struct alloc_context *ac)
4582 {
4583 struct zoneref *z;
4584 struct zone *zone;
4585 pg_data_t *last_pgdat = NULL;
4586 enum zone_type highest_zoneidx = ac->highest_zoneidx;
4587
4588 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, highest_zoneidx,
4589 ac->nodemask) {
4590 if (last_pgdat != zone->zone_pgdat)
4591 wakeup_kswapd(zone, gfp_mask, order, highest_zoneidx);
4592 last_pgdat = zone->zone_pgdat;
4593 }
4594 }
4595
4596 static inline unsigned int
gfp_to_alloc_flags(gfp_t gfp_mask)4597 gfp_to_alloc_flags(gfp_t gfp_mask)
4598 {
4599 unsigned int alloc_flags = ALLOC_WMARK_MIN | ALLOC_CPUSET;
4600
4601 /*
4602 * __GFP_HIGH is assumed to be the same as ALLOC_HIGH
4603 * and __GFP_KSWAPD_RECLAIM is assumed to be the same as ALLOC_KSWAPD
4604 * to save two branches.
4605 */
4606 BUILD_BUG_ON(__GFP_HIGH != (__force gfp_t) ALLOC_HIGH);
4607 BUILD_BUG_ON(__GFP_KSWAPD_RECLAIM != (__force gfp_t) ALLOC_KSWAPD);
4608
4609 /*
4610 * The caller may dip into page reserves a bit more if the caller
4611 * cannot run direct reclaim, or if the caller has realtime scheduling
4612 * policy or is asking for __GFP_HIGH memory. GFP_ATOMIC requests will
4613 * set both ALLOC_HARDER (__GFP_ATOMIC) and ALLOC_HIGH (__GFP_HIGH).
4614 */
4615 alloc_flags |= (__force int)
4616 (gfp_mask & (__GFP_HIGH | __GFP_KSWAPD_RECLAIM));
4617
4618 if (gfp_mask & __GFP_ATOMIC) {
4619 /*
4620 * Not worth trying to allocate harder for __GFP_NOMEMALLOC even
4621 * if it can't schedule.
4622 */
4623 if (!(gfp_mask & __GFP_NOMEMALLOC))
4624 alloc_flags |= ALLOC_HARDER;
4625 /*
4626 * Ignore cpuset mems for GFP_ATOMIC rather than fail, see the
4627 * comment for __cpuset_node_allowed().
4628 */
4629 alloc_flags &= ~ALLOC_CPUSET;
4630 } else if (unlikely(rt_task(current)) && !in_interrupt())
4631 alloc_flags |= ALLOC_HARDER;
4632
4633 alloc_flags = current_alloc_flags(gfp_mask, alloc_flags);
4634
4635 return alloc_flags;
4636 }
4637
oom_reserves_allowed(struct task_struct * tsk)4638 static bool oom_reserves_allowed(struct task_struct *tsk)
4639 {
4640 if (!tsk_is_oom_victim(tsk))
4641 return false;
4642
4643 /*
4644 * !MMU doesn't have oom reaper so give access to memory reserves
4645 * only to the thread with TIF_MEMDIE set
4646 */
4647 if (!IS_ENABLED(CONFIG_MMU) && !test_thread_flag(TIF_MEMDIE))
4648 return false;
4649
4650 return true;
4651 }
4652
4653 /*
4654 * Distinguish requests which really need access to full memory
4655 * reserves from oom victims which can live with a portion of it
4656 */
__gfp_pfmemalloc_flags(gfp_t gfp_mask)4657 static inline int __gfp_pfmemalloc_flags(gfp_t gfp_mask)
4658 {
4659 if (unlikely(gfp_mask & __GFP_NOMEMALLOC))
4660 return 0;
4661 if (gfp_mask & __GFP_MEMALLOC)
4662 return ALLOC_NO_WATERMARKS;
4663 if (in_serving_softirq() && (current->flags & PF_MEMALLOC))
4664 return ALLOC_NO_WATERMARKS;
4665 if (!in_interrupt()) {
4666 if (current->flags & PF_MEMALLOC)
4667 return ALLOC_NO_WATERMARKS;
4668 else if (oom_reserves_allowed(current))
4669 return ALLOC_OOM;
4670 }
4671
4672 return 0;
4673 }
4674
gfp_pfmemalloc_allowed(gfp_t gfp_mask)4675 bool gfp_pfmemalloc_allowed(gfp_t gfp_mask)
4676 {
4677 return !!__gfp_pfmemalloc_flags(gfp_mask);
4678 }
4679
4680 /*
4681 * Checks whether it makes sense to retry the reclaim to make a forward progress
4682 * for the given allocation request.
4683 *
4684 * We give up when we either have tried MAX_RECLAIM_RETRIES in a row
4685 * without success, or when we couldn't even meet the watermark if we
4686 * reclaimed all remaining pages on the LRU lists.
4687 *
4688 * Returns true if a retry is viable or false to enter the oom path.
4689 */
4690 static inline bool
should_reclaim_retry(gfp_t gfp_mask,unsigned order,struct alloc_context * ac,int alloc_flags,bool did_some_progress,int * no_progress_loops)4691 should_reclaim_retry(gfp_t gfp_mask, unsigned order,
4692 struct alloc_context *ac, int alloc_flags,
4693 bool did_some_progress, int *no_progress_loops)
4694 {
4695 struct zone *zone;
4696 struct zoneref *z;
4697 bool ret = false;
4698
4699 /*
4700 * Costly allocations might have made a progress but this doesn't mean
4701 * their order will become available due to high fragmentation so
4702 * always increment the no progress counter for them
4703 */
4704 if (did_some_progress && order <= PAGE_ALLOC_COSTLY_ORDER)
4705 *no_progress_loops = 0;
4706 else
4707 (*no_progress_loops)++;
4708
4709 /*
4710 * Make sure we converge to OOM if we cannot make any progress
4711 * several times in the row.
4712 */
4713 if (*no_progress_loops > MAX_RECLAIM_RETRIES) {
4714 /* Before OOM, exhaust highatomic_reserve */
4715 return unreserve_highatomic_pageblock(ac, true);
4716 }
4717
4718 /*
4719 * Keep reclaiming pages while there is a chance this will lead
4720 * somewhere. If none of the target zones can satisfy our allocation
4721 * request even if all reclaimable pages are considered then we are
4722 * screwed and have to go OOM.
4723 */
4724 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
4725 ac->highest_zoneidx, ac->nodemask) {
4726 unsigned long available;
4727 unsigned long reclaimable;
4728 unsigned long min_wmark = min_wmark_pages(zone);
4729 bool wmark;
4730
4731 available = reclaimable = zone_reclaimable_pages(zone);
4732 available += zone_page_state_snapshot(zone, NR_FREE_PAGES);
4733
4734 /*
4735 * Would the allocation succeed if we reclaimed all
4736 * reclaimable pages?
4737 */
4738 wmark = __zone_watermark_ok(zone, order, min_wmark,
4739 ac->highest_zoneidx, alloc_flags, available);
4740 trace_reclaim_retry_zone(z, order, reclaimable,
4741 available, min_wmark, *no_progress_loops, wmark);
4742 if (wmark) {
4743 /*
4744 * If we didn't make any progress and have a lot of
4745 * dirty + writeback pages then we should wait for
4746 * an IO to complete to slow down the reclaim and
4747 * prevent from pre mature OOM
4748 */
4749 if (!did_some_progress) {
4750 unsigned long write_pending;
4751
4752 write_pending = zone_page_state_snapshot(zone,
4753 NR_ZONE_WRITE_PENDING);
4754
4755 if (2 * write_pending > reclaimable) {
4756 congestion_wait(BLK_RW_ASYNC, HZ/10);
4757 return true;
4758 }
4759 }
4760
4761 ret = true;
4762 goto out;
4763 }
4764 }
4765
4766 out:
4767 /*
4768 * Memory allocation/reclaim might be called from a WQ context and the
4769 * current implementation of the WQ concurrency control doesn't
4770 * recognize that a particular WQ is congested if the worker thread is
4771 * looping without ever sleeping. Therefore we have to do a short sleep
4772 * here rather than calling cond_resched().
4773 */
4774 if (current->flags & PF_WQ_WORKER)
4775 schedule_timeout_uninterruptible(1);
4776 else
4777 cond_resched();
4778 return ret;
4779 }
4780
4781 static inline bool
check_retry_cpuset(int cpuset_mems_cookie,struct alloc_context * ac)4782 check_retry_cpuset(int cpuset_mems_cookie, struct alloc_context *ac)
4783 {
4784 /*
4785 * It's possible that cpuset's mems_allowed and the nodemask from
4786 * mempolicy don't intersect. This should be normally dealt with by
4787 * policy_nodemask(), but it's possible to race with cpuset update in
4788 * such a way the check therein was true, and then it became false
4789 * before we got our cpuset_mems_cookie here.
4790 * This assumes that for all allocations, ac->nodemask can come only
4791 * from MPOL_BIND mempolicy (whose documented semantics is to be ignored
4792 * when it does not intersect with the cpuset restrictions) or the
4793 * caller can deal with a violated nodemask.
4794 */
4795 if (cpusets_enabled() && ac->nodemask &&
4796 !cpuset_nodemask_valid_mems_allowed(ac->nodemask)) {
4797 ac->nodemask = NULL;
4798 return true;
4799 }
4800
4801 /*
4802 * When updating a task's mems_allowed or mempolicy nodemask, it is
4803 * possible to race with parallel threads in such a way that our
4804 * allocation can fail while the mask is being updated. If we are about
4805 * to fail, check if the cpuset changed during allocation and if so,
4806 * retry.
4807 */
4808 if (read_mems_allowed_retry(cpuset_mems_cookie))
4809 return true;
4810
4811 return false;
4812 }
4813
4814 static inline struct page *
__alloc_pages_slowpath(gfp_t gfp_mask,unsigned int order,struct alloc_context * ac)4815 __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order,
4816 struct alloc_context *ac)
4817 {
4818 bool can_direct_reclaim = gfp_mask & __GFP_DIRECT_RECLAIM;
4819 const bool costly_order = order > PAGE_ALLOC_COSTLY_ORDER;
4820 struct page *page = NULL;
4821 unsigned int alloc_flags;
4822 unsigned long did_some_progress;
4823 enum compact_priority compact_priority;
4824 enum compact_result compact_result;
4825 int compaction_retries;
4826 int no_progress_loops;
4827 unsigned int cpuset_mems_cookie;
4828 unsigned int zonelist_iter_cookie;
4829 int reserve_flags;
4830 unsigned long vh_record;
4831
4832 trace_android_vh_alloc_pages_slowpath_begin(gfp_mask, order, &vh_record);
4833 /*
4834 * We also sanity check to catch abuse of atomic reserves being used by
4835 * callers that are not in atomic context.
4836 */
4837 if (WARN_ON_ONCE((gfp_mask & (__GFP_ATOMIC|__GFP_DIRECT_RECLAIM)) ==
4838 (__GFP_ATOMIC|__GFP_DIRECT_RECLAIM)))
4839 gfp_mask &= ~__GFP_ATOMIC;
4840
4841 restart:
4842 compaction_retries = 0;
4843 no_progress_loops = 0;
4844 compact_priority = DEF_COMPACT_PRIORITY;
4845 cpuset_mems_cookie = read_mems_allowed_begin();
4846 zonelist_iter_cookie = zonelist_iter_begin();
4847
4848 /*
4849 * The fast path uses conservative alloc_flags to succeed only until
4850 * kswapd needs to be woken up, and to avoid the cost of setting up
4851 * alloc_flags precisely. So we do that now.
4852 */
4853 alloc_flags = gfp_to_alloc_flags(gfp_mask);
4854
4855 /*
4856 * We need to recalculate the starting point for the zonelist iterator
4857 * because we might have used different nodemask in the fast path, or
4858 * there was a cpuset modification and we are retrying - otherwise we
4859 * could end up iterating over non-eligible zones endlessly.
4860 */
4861 ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
4862 ac->highest_zoneidx, ac->nodemask);
4863 if (!ac->preferred_zoneref->zone)
4864 goto nopage;
4865
4866 if (alloc_flags & ALLOC_KSWAPD)
4867 wake_all_kswapds(order, gfp_mask, ac);
4868
4869 /*
4870 * The adjusted alloc_flags might result in immediate success, so try
4871 * that first
4872 */
4873 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4874 if (page)
4875 goto got_pg;
4876
4877 /*
4878 * For costly allocations, try direct compaction first, as it's likely
4879 * that we have enough base pages and don't need to reclaim. For non-
4880 * movable high-order allocations, do that as well, as compaction will
4881 * try prevent permanent fragmentation by migrating from blocks of the
4882 * same migratetype.
4883 * Don't try this for allocations that are allowed to ignore
4884 * watermarks, as the ALLOC_NO_WATERMARKS attempt didn't yet happen.
4885 */
4886 if (can_direct_reclaim &&
4887 (costly_order ||
4888 (order > 0 && ac->migratetype != MIGRATE_MOVABLE))
4889 && !gfp_pfmemalloc_allowed(gfp_mask)) {
4890 page = __alloc_pages_direct_compact(gfp_mask, order,
4891 alloc_flags, ac,
4892 INIT_COMPACT_PRIORITY,
4893 &compact_result);
4894 if (page)
4895 goto got_pg;
4896
4897 /*
4898 * Checks for costly allocations with __GFP_NORETRY, which
4899 * includes some THP page fault allocations
4900 */
4901 if (costly_order && (gfp_mask & __GFP_NORETRY)) {
4902 /*
4903 * If allocating entire pageblock(s) and compaction
4904 * failed because all zones are below low watermarks
4905 * or is prohibited because it recently failed at this
4906 * order, fail immediately unless the allocator has
4907 * requested compaction and reclaim retry.
4908 *
4909 * Reclaim is
4910 * - potentially very expensive because zones are far
4911 * below their low watermarks or this is part of very
4912 * bursty high order allocations,
4913 * - not guaranteed to help because isolate_freepages()
4914 * may not iterate over freed pages as part of its
4915 * linear scan, and
4916 * - unlikely to make entire pageblocks free on its
4917 * own.
4918 */
4919 if (compact_result == COMPACT_SKIPPED ||
4920 compact_result == COMPACT_DEFERRED)
4921 goto nopage;
4922
4923 /*
4924 * Looks like reclaim/compaction is worth trying, but
4925 * sync compaction could be very expensive, so keep
4926 * using async compaction.
4927 */
4928 compact_priority = INIT_COMPACT_PRIORITY;
4929 }
4930 }
4931
4932 retry:
4933 /* Ensure kswapd doesn't accidentally go to sleep as long as we loop */
4934 if (alloc_flags & ALLOC_KSWAPD)
4935 wake_all_kswapds(order, gfp_mask, ac);
4936
4937 reserve_flags = __gfp_pfmemalloc_flags(gfp_mask);
4938 if (reserve_flags)
4939 alloc_flags = current_alloc_flags(gfp_mask, reserve_flags);
4940
4941 /*
4942 * Reset the nodemask and zonelist iterators if memory policies can be
4943 * ignored. These allocations are high priority and system rather than
4944 * user oriented.
4945 */
4946 if (!(alloc_flags & ALLOC_CPUSET) || reserve_flags) {
4947 ac->nodemask = NULL;
4948 ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
4949 ac->highest_zoneidx, ac->nodemask);
4950 }
4951
4952 /* Attempt with potentially adjusted zonelist and alloc_flags */
4953 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4954 if (page)
4955 goto got_pg;
4956
4957 /* Caller is not willing to reclaim, we can't balance anything */
4958 if (!can_direct_reclaim)
4959 goto nopage;
4960
4961 /* Avoid recursion of direct reclaim */
4962 if (current->flags & PF_MEMALLOC)
4963 goto nopage;
4964
4965 trace_android_vh_alloc_pages_reclaim_bypass(gfp_mask, order,
4966 alloc_flags, ac->migratetype, &page);
4967
4968 if (page)
4969 goto got_pg;
4970
4971 /* Try direct reclaim and then allocating */
4972 page = __alloc_pages_direct_reclaim(gfp_mask, order, alloc_flags, ac,
4973 &did_some_progress);
4974 if (page)
4975 goto got_pg;
4976
4977 /* Try direct compaction and then allocating */
4978 page = __alloc_pages_direct_compact(gfp_mask, order, alloc_flags, ac,
4979 compact_priority, &compact_result);
4980 if (page)
4981 goto got_pg;
4982
4983 /* Do not loop if specifically requested */
4984 if (gfp_mask & __GFP_NORETRY)
4985 goto nopage;
4986
4987 /*
4988 * Do not retry costly high order allocations unless they are
4989 * __GFP_RETRY_MAYFAIL
4990 */
4991 if (costly_order && !(gfp_mask & __GFP_RETRY_MAYFAIL))
4992 goto nopage;
4993
4994 if (should_reclaim_retry(gfp_mask, order, ac, alloc_flags,
4995 did_some_progress > 0, &no_progress_loops))
4996 goto retry;
4997
4998 /*
4999 * It doesn't make any sense to retry for the compaction if the order-0
5000 * reclaim is not able to make any progress because the current
5001 * implementation of the compaction depends on the sufficient amount
5002 * of free memory (see __compaction_suitable)
5003 */
5004 if (did_some_progress > 0 &&
5005 should_compact_retry(ac, order, alloc_flags,
5006 compact_result, &compact_priority,
5007 &compaction_retries))
5008 goto retry;
5009
5010
5011 /*
5012 * Deal with possible cpuset update races or zonelist updates to avoid
5013 * a unnecessary OOM kill.
5014 */
5015 if (check_retry_cpuset(cpuset_mems_cookie, ac) ||
5016 check_retry_zonelist(zonelist_iter_cookie))
5017 goto restart;
5018
5019 /* Reclaim has failed us, start killing things */
5020 page = __alloc_pages_may_oom(gfp_mask, order, ac, &did_some_progress);
5021 if (page)
5022 goto got_pg;
5023
5024 /* Avoid allocations with no watermarks from looping endlessly */
5025 if (tsk_is_oom_victim(current) &&
5026 (alloc_flags & ALLOC_OOM ||
5027 (gfp_mask & __GFP_NOMEMALLOC)))
5028 goto nopage;
5029
5030 /* Retry as long as the OOM killer is making progress */
5031 if (did_some_progress) {
5032 no_progress_loops = 0;
5033 goto retry;
5034 }
5035
5036 nopage:
5037 /*
5038 * Deal with possible cpuset update races or zonelist updates to avoid
5039 * a unnecessary OOM kill.
5040 */
5041 if (check_retry_cpuset(cpuset_mems_cookie, ac) ||
5042 check_retry_zonelist(zonelist_iter_cookie))
5043 goto restart;
5044
5045 /*
5046 * Make sure that __GFP_NOFAIL request doesn't leak out and make sure
5047 * we always retry
5048 */
5049 if (gfp_mask & __GFP_NOFAIL) {
5050 /*
5051 * All existing users of the __GFP_NOFAIL are blockable, so warn
5052 * of any new users that actually require GFP_NOWAIT
5053 */
5054 if (WARN_ON_ONCE(!can_direct_reclaim))
5055 goto fail;
5056
5057 /*
5058 * PF_MEMALLOC request from this context is rather bizarre
5059 * because we cannot reclaim anything and only can loop waiting
5060 * for somebody to do a work for us
5061 */
5062 WARN_ON_ONCE(current->flags & PF_MEMALLOC);
5063
5064 /*
5065 * non failing costly orders are a hard requirement which we
5066 * are not prepared for much so let's warn about these users
5067 * so that we can identify them and convert them to something
5068 * else.
5069 */
5070 WARN_ON_ONCE(order > PAGE_ALLOC_COSTLY_ORDER);
5071
5072 /*
5073 * Help non-failing allocations by giving them access to memory
5074 * reserves but do not use ALLOC_NO_WATERMARKS because this
5075 * could deplete whole memory reserves which would just make
5076 * the situation worse
5077 */
5078 page = __alloc_pages_cpuset_fallback(gfp_mask, order, ALLOC_HARDER, ac);
5079 if (page)
5080 goto got_pg;
5081
5082 cond_resched();
5083 goto retry;
5084 }
5085 fail:
5086 trace_android_vh_alloc_pages_failure_bypass(gfp_mask, order,
5087 alloc_flags, ac->migratetype, &page);
5088 if (page)
5089 goto got_pg;
5090
5091 warn_alloc(gfp_mask, ac->nodemask,
5092 "page allocation failure: order:%u", order);
5093 got_pg:
5094 trace_android_vh_alloc_pages_slowpath_end(gfp_mask, order, vh_record);
5095 return page;
5096 }
5097
prepare_alloc_pages(gfp_t gfp_mask,unsigned int order,int preferred_nid,nodemask_t * nodemask,struct alloc_context * ac,gfp_t * alloc_mask,unsigned int * alloc_flags)5098 static inline bool prepare_alloc_pages(gfp_t gfp_mask, unsigned int order,
5099 int preferred_nid, nodemask_t *nodemask,
5100 struct alloc_context *ac, gfp_t *alloc_mask,
5101 unsigned int *alloc_flags)
5102 {
5103 ac->highest_zoneidx = gfp_zone(gfp_mask);
5104 ac->zonelist = node_zonelist(preferred_nid, gfp_mask);
5105 ac->nodemask = nodemask;
5106 ac->migratetype = gfp_migratetype(gfp_mask);
5107
5108 if (cpusets_enabled()) {
5109 *alloc_mask |= __GFP_HARDWALL;
5110 /*
5111 * When we are in the interrupt context, it is irrelevant
5112 * to the current task context. It means that any node ok.
5113 */
5114 if (!in_interrupt() && !ac->nodemask)
5115 ac->nodemask = &cpuset_current_mems_allowed;
5116 else
5117 *alloc_flags |= ALLOC_CPUSET;
5118 }
5119
5120 fs_reclaim_acquire(gfp_mask);
5121 fs_reclaim_release(gfp_mask);
5122
5123 might_sleep_if(gfp_mask & __GFP_DIRECT_RECLAIM);
5124
5125 if (should_fail_alloc_page(gfp_mask, order))
5126 return false;
5127
5128 *alloc_flags = current_alloc_flags(gfp_mask, *alloc_flags);
5129
5130 /* Dirty zone balancing only done in the fast path */
5131 ac->spread_dirty_pages = (gfp_mask & __GFP_WRITE);
5132
5133 /*
5134 * The preferred zone is used for statistics but crucially it is
5135 * also used as the starting point for the zonelist iterator. It
5136 * may get reset for allocations that ignore memory policies.
5137 */
5138 ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
5139 ac->highest_zoneidx, ac->nodemask);
5140
5141 return true;
5142 }
5143
5144 /*
5145 * This is the 'heart' of the zoned buddy allocator.
5146 */
5147 struct page *
__alloc_pages_nodemask(gfp_t gfp_mask,unsigned int order,int preferred_nid,nodemask_t * nodemask)5148 __alloc_pages_nodemask(gfp_t gfp_mask, unsigned int order, int preferred_nid,
5149 nodemask_t *nodemask)
5150 {
5151 struct page *page;
5152 unsigned int alloc_flags = ALLOC_WMARK_LOW;
5153 gfp_t alloc_mask; /* The gfp_t that was actually used for allocation */
5154 struct alloc_context ac = { };
5155
5156 /*
5157 * There are several places where we assume that the order value is sane
5158 * so bail out early if the request is out of bound.
5159 */
5160 if (unlikely(order >= MAX_ORDER)) {
5161 WARN_ON_ONCE(!(gfp_mask & __GFP_NOWARN));
5162 return NULL;
5163 }
5164
5165 gfp_mask &= gfp_allowed_mask;
5166 alloc_mask = gfp_mask;
5167 if (!prepare_alloc_pages(gfp_mask, order, preferred_nid, nodemask, &ac, &alloc_mask, &alloc_flags))
5168 return NULL;
5169
5170 /*
5171 * Forbid the first pass from falling back to types that fragment
5172 * memory until all local zones are considered.
5173 */
5174 alloc_flags |= alloc_flags_nofragment(ac.preferred_zoneref->zone, gfp_mask);
5175
5176 /* First allocation attempt */
5177 page = get_page_from_freelist(alloc_mask, order, alloc_flags, &ac);
5178 if (likely(page))
5179 goto out;
5180
5181 /*
5182 * Apply scoped allocation constraints. This is mainly about GFP_NOFS
5183 * resp. GFP_NOIO which has to be inherited for all allocation requests
5184 * from a particular context which has been marked by
5185 * memalloc_no{fs,io}_{save,restore}.
5186 */
5187 alloc_mask = current_gfp_context(gfp_mask);
5188 ac.spread_dirty_pages = false;
5189
5190 /*
5191 * Restore the original nodemask if it was potentially replaced with
5192 * &cpuset_current_mems_allowed to optimize the fast-path attempt.
5193 */
5194 ac.nodemask = nodemask;
5195
5196 page = __alloc_pages_slowpath(alloc_mask, order, &ac);
5197
5198 out:
5199 if (memcg_kmem_enabled() && (gfp_mask & __GFP_ACCOUNT) && page &&
5200 unlikely(__memcg_kmem_charge_page(page, gfp_mask, order) != 0)) {
5201 __free_pages(page, order);
5202 page = NULL;
5203 }
5204
5205 trace_mm_page_alloc(page, order, alloc_mask, ac.migratetype);
5206
5207 return page;
5208 }
5209 EXPORT_SYMBOL(__alloc_pages_nodemask);
5210
5211 /*
5212 * Common helper functions. Never use with __GFP_HIGHMEM because the returned
5213 * address cannot represent highmem pages. Use alloc_pages and then kmap if
5214 * you need to access high mem.
5215 */
__get_free_pages(gfp_t gfp_mask,unsigned int order)5216 unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order)
5217 {
5218 struct page *page;
5219
5220 page = alloc_pages(gfp_mask & ~__GFP_HIGHMEM, order);
5221 if (!page)
5222 return 0;
5223 return (unsigned long) page_address(page);
5224 }
5225 EXPORT_SYMBOL(__get_free_pages);
5226
get_zeroed_page(gfp_t gfp_mask)5227 unsigned long get_zeroed_page(gfp_t gfp_mask)
5228 {
5229 return __get_free_pages(gfp_mask | __GFP_ZERO, 0);
5230 }
5231 EXPORT_SYMBOL(get_zeroed_page);
5232
free_the_page(struct page * page,unsigned int order)5233 static inline void free_the_page(struct page *page, unsigned int order)
5234 {
5235 if (order == 0) /* Via pcp? */
5236 free_unref_page(page);
5237 else
5238 __free_pages_ok(page, order, FPI_NONE);
5239 }
5240
__free_pages(struct page * page,unsigned int order)5241 void __free_pages(struct page *page, unsigned int order)
5242 {
5243 trace_android_vh_free_pages(page, order);
5244 if (put_page_testzero(page))
5245 free_the_page(page, order);
5246 else if (!PageHead(page))
5247 while (order-- > 0)
5248 free_the_page(page + (1 << order), order);
5249 }
5250 EXPORT_SYMBOL(__free_pages);
5251
free_pages(unsigned long addr,unsigned int order)5252 void free_pages(unsigned long addr, unsigned int order)
5253 {
5254 if (addr != 0) {
5255 VM_BUG_ON(!virt_addr_valid((void *)addr));
5256 __free_pages(virt_to_page((void *)addr), order);
5257 }
5258 }
5259
5260 EXPORT_SYMBOL(free_pages);
5261
5262 /*
5263 * Page Fragment:
5264 * An arbitrary-length arbitrary-offset area of memory which resides
5265 * within a 0 or higher order page. Multiple fragments within that page
5266 * are individually refcounted, in the page's reference counter.
5267 *
5268 * The page_frag functions below provide a simple allocation framework for
5269 * page fragments. This is used by the network stack and network device
5270 * drivers to provide a backing region of memory for use as either an
5271 * sk_buff->head, or to be used in the "frags" portion of skb_shared_info.
5272 */
__page_frag_cache_refill(struct page_frag_cache * nc,gfp_t gfp_mask)5273 static struct page *__page_frag_cache_refill(struct page_frag_cache *nc,
5274 gfp_t gfp_mask)
5275 {
5276 struct page *page = NULL;
5277 gfp_t gfp = gfp_mask;
5278
5279 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
5280 gfp_mask |= __GFP_COMP | __GFP_NOWARN | __GFP_NORETRY |
5281 __GFP_NOMEMALLOC;
5282 page = alloc_pages_node(NUMA_NO_NODE, gfp_mask,
5283 PAGE_FRAG_CACHE_MAX_ORDER);
5284 nc->size = page ? PAGE_FRAG_CACHE_MAX_SIZE : PAGE_SIZE;
5285 #endif
5286 if (unlikely(!page))
5287 page = alloc_pages_node(NUMA_NO_NODE, gfp, 0);
5288
5289 nc->va = page ? page_address(page) : NULL;
5290
5291 return page;
5292 }
5293
__page_frag_cache_drain(struct page * page,unsigned int count)5294 void __page_frag_cache_drain(struct page *page, unsigned int count)
5295 {
5296 VM_BUG_ON_PAGE(page_ref_count(page) == 0, page);
5297
5298 if (page_ref_sub_and_test(page, count))
5299 free_the_page(page, compound_order(page));
5300 }
5301 EXPORT_SYMBOL(__page_frag_cache_drain);
5302
page_frag_alloc(struct page_frag_cache * nc,unsigned int fragsz,gfp_t gfp_mask)5303 void *page_frag_alloc(struct page_frag_cache *nc,
5304 unsigned int fragsz, gfp_t gfp_mask)
5305 {
5306 unsigned int size = PAGE_SIZE;
5307 struct page *page;
5308 int offset;
5309
5310 if (unlikely(!nc->va)) {
5311 refill:
5312 page = __page_frag_cache_refill(nc, gfp_mask);
5313 if (!page)
5314 return NULL;
5315
5316 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
5317 /* if size can vary use size else just use PAGE_SIZE */
5318 size = nc->size;
5319 #endif
5320 /* Even if we own the page, we do not use atomic_set().
5321 * This would break get_page_unless_zero() users.
5322 */
5323 page_ref_add(page, PAGE_FRAG_CACHE_MAX_SIZE);
5324
5325 /* reset page count bias and offset to start of new frag */
5326 nc->pfmemalloc = page_is_pfmemalloc(page);
5327 nc->pagecnt_bias = PAGE_FRAG_CACHE_MAX_SIZE + 1;
5328 nc->offset = size;
5329 }
5330
5331 offset = nc->offset - fragsz;
5332 if (unlikely(offset < 0)) {
5333 page = virt_to_page(nc->va);
5334
5335 if (!page_ref_sub_and_test(page, nc->pagecnt_bias))
5336 goto refill;
5337
5338 if (unlikely(nc->pfmemalloc)) {
5339 free_the_page(page, compound_order(page));
5340 goto refill;
5341 }
5342
5343 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
5344 /* if size can vary use size else just use PAGE_SIZE */
5345 size = nc->size;
5346 #endif
5347 /* OK, page count is 0, we can safely set it */
5348 set_page_count(page, PAGE_FRAG_CACHE_MAX_SIZE + 1);
5349
5350 /* reset page count bias and offset to start of new frag */
5351 nc->pagecnt_bias = PAGE_FRAG_CACHE_MAX_SIZE + 1;
5352 offset = size - fragsz;
5353 if (unlikely(offset < 0)) {
5354 /*
5355 * The caller is trying to allocate a fragment
5356 * with fragsz > PAGE_SIZE but the cache isn't big
5357 * enough to satisfy the request, this may
5358 * happen in low memory conditions.
5359 * We don't release the cache page because
5360 * it could make memory pressure worse
5361 * so we simply return NULL here.
5362 */
5363 return NULL;
5364 }
5365 }
5366
5367 nc->pagecnt_bias--;
5368 nc->offset = offset;
5369
5370 return nc->va + offset;
5371 }
5372 EXPORT_SYMBOL(page_frag_alloc);
5373
5374 /*
5375 * Frees a page fragment allocated out of either a compound or order 0 page.
5376 */
page_frag_free(void * addr)5377 void page_frag_free(void *addr)
5378 {
5379 struct page *page = virt_to_head_page(addr);
5380
5381 if (unlikely(put_page_testzero(page)))
5382 free_the_page(page, compound_order(page));
5383 }
5384 EXPORT_SYMBOL(page_frag_free);
5385
make_alloc_exact(unsigned long addr,unsigned int order,size_t size)5386 static void *make_alloc_exact(unsigned long addr, unsigned int order,
5387 size_t size)
5388 {
5389 if (addr) {
5390 unsigned long alloc_end = addr + (PAGE_SIZE << order);
5391 unsigned long used = addr + PAGE_ALIGN(size);
5392
5393 split_page(virt_to_page((void *)addr), order);
5394 while (used < alloc_end) {
5395 free_page(used);
5396 used += PAGE_SIZE;
5397 }
5398 }
5399 return (void *)addr;
5400 }
5401
5402 /**
5403 * alloc_pages_exact - allocate an exact number physically-contiguous pages.
5404 * @size: the number of bytes to allocate
5405 * @gfp_mask: GFP flags for the allocation, must not contain __GFP_COMP
5406 *
5407 * This function is similar to alloc_pages(), except that it allocates the
5408 * minimum number of pages to satisfy the request. alloc_pages() can only
5409 * allocate memory in power-of-two pages.
5410 *
5411 * This function is also limited by MAX_ORDER.
5412 *
5413 * Memory allocated by this function must be released by free_pages_exact().
5414 *
5415 * Return: pointer to the allocated area or %NULL in case of error.
5416 */
alloc_pages_exact(size_t size,gfp_t gfp_mask)5417 void *alloc_pages_exact(size_t size, gfp_t gfp_mask)
5418 {
5419 unsigned int order = get_order(size);
5420 unsigned long addr;
5421
5422 if (WARN_ON_ONCE(gfp_mask & __GFP_COMP))
5423 gfp_mask &= ~__GFP_COMP;
5424
5425 addr = __get_free_pages(gfp_mask, order);
5426 return make_alloc_exact(addr, order, size);
5427 }
5428 EXPORT_SYMBOL(alloc_pages_exact);
5429
5430 /**
5431 * alloc_pages_exact_nid - allocate an exact number of physically-contiguous
5432 * pages on a node.
5433 * @nid: the preferred node ID where memory should be allocated
5434 * @size: the number of bytes to allocate
5435 * @gfp_mask: GFP flags for the allocation, must not contain __GFP_COMP
5436 *
5437 * Like alloc_pages_exact(), but try to allocate on node nid first before falling
5438 * back.
5439 *
5440 * Return: pointer to the allocated area or %NULL in case of error.
5441 */
alloc_pages_exact_nid(int nid,size_t size,gfp_t gfp_mask)5442 void * __meminit alloc_pages_exact_nid(int nid, size_t size, gfp_t gfp_mask)
5443 {
5444 unsigned int order = get_order(size);
5445 struct page *p;
5446
5447 if (WARN_ON_ONCE(gfp_mask & __GFP_COMP))
5448 gfp_mask &= ~__GFP_COMP;
5449
5450 p = alloc_pages_node(nid, gfp_mask, order);
5451 if (!p)
5452 return NULL;
5453 return make_alloc_exact((unsigned long)page_address(p), order, size);
5454 }
5455
5456 /**
5457 * free_pages_exact - release memory allocated via alloc_pages_exact()
5458 * @virt: the value returned by alloc_pages_exact.
5459 * @size: size of allocation, same value as passed to alloc_pages_exact().
5460 *
5461 * Release the memory allocated by a previous call to alloc_pages_exact.
5462 */
free_pages_exact(void * virt,size_t size)5463 void free_pages_exact(void *virt, size_t size)
5464 {
5465 unsigned long addr = (unsigned long)virt;
5466 unsigned long end = addr + PAGE_ALIGN(size);
5467
5468 while (addr < end) {
5469 free_page(addr);
5470 addr += PAGE_SIZE;
5471 }
5472 }
5473 EXPORT_SYMBOL(free_pages_exact);
5474
5475 /**
5476 * nr_free_zone_pages - count number of pages beyond high watermark
5477 * @offset: The zone index of the highest zone
5478 *
5479 * nr_free_zone_pages() counts the number of pages which are beyond the
5480 * high watermark within all zones at or below a given zone index. For each
5481 * zone, the number of pages is calculated as:
5482 *
5483 * nr_free_zone_pages = managed_pages - high_pages
5484 *
5485 * Return: number of pages beyond high watermark.
5486 */
nr_free_zone_pages(int offset)5487 static unsigned long nr_free_zone_pages(int offset)
5488 {
5489 struct zoneref *z;
5490 struct zone *zone;
5491
5492 /* Just pick one node, since fallback list is circular */
5493 unsigned long sum = 0;
5494
5495 struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL);
5496
5497 for_each_zone_zonelist(zone, z, zonelist, offset) {
5498 unsigned long size = zone_managed_pages(zone);
5499 unsigned long high = high_wmark_pages(zone);
5500 if (size > high)
5501 sum += size - high;
5502 }
5503
5504 return sum;
5505 }
5506
5507 /**
5508 * nr_free_buffer_pages - count number of pages beyond high watermark
5509 *
5510 * nr_free_buffer_pages() counts the number of pages which are beyond the high
5511 * watermark within ZONE_DMA and ZONE_NORMAL.
5512 *
5513 * Return: number of pages beyond high watermark within ZONE_DMA and
5514 * ZONE_NORMAL.
5515 */
nr_free_buffer_pages(void)5516 unsigned long nr_free_buffer_pages(void)
5517 {
5518 return nr_free_zone_pages(gfp_zone(GFP_USER));
5519 }
5520 EXPORT_SYMBOL_GPL(nr_free_buffer_pages);
5521
show_node(struct zone * zone)5522 static inline void show_node(struct zone *zone)
5523 {
5524 if (IS_ENABLED(CONFIG_NUMA))
5525 printk("Node %d ", zone_to_nid(zone));
5526 }
5527
si_mem_available(void)5528 long si_mem_available(void)
5529 {
5530 long available;
5531 unsigned long pagecache;
5532 unsigned long wmark_low = 0;
5533 unsigned long pages[NR_LRU_LISTS];
5534 unsigned long reclaimable;
5535 struct zone *zone;
5536 int lru;
5537
5538 for (lru = LRU_BASE; lru < NR_LRU_LISTS; lru++)
5539 pages[lru] = global_node_page_state(NR_LRU_BASE + lru);
5540
5541 for_each_zone(zone)
5542 wmark_low += low_wmark_pages(zone);
5543
5544 /*
5545 * Estimate the amount of memory available for userspace allocations,
5546 * without causing swapping.
5547 */
5548 available = global_zone_page_state(NR_FREE_PAGES) - totalreserve_pages;
5549
5550 /*
5551 * Not all the page cache can be freed, otherwise the system will
5552 * start swapping. Assume at least half of the page cache, or the
5553 * low watermark worth of cache, needs to stay.
5554 */
5555 pagecache = pages[LRU_ACTIVE_FILE] + pages[LRU_INACTIVE_FILE];
5556 pagecache -= min(pagecache / 2, wmark_low);
5557 available += pagecache;
5558
5559 /*
5560 * Part of the reclaimable slab and other kernel memory consists of
5561 * items that are in use, and cannot be freed. Cap this estimate at the
5562 * low watermark.
5563 */
5564 reclaimable = global_node_page_state_pages(NR_SLAB_RECLAIMABLE_B) +
5565 global_node_page_state(NR_KERNEL_MISC_RECLAIMABLE);
5566 available += reclaimable - min(reclaimable / 2, wmark_low);
5567
5568 if (available < 0)
5569 available = 0;
5570 return available;
5571 }
5572 EXPORT_SYMBOL_GPL(si_mem_available);
5573
si_meminfo(struct sysinfo * val)5574 void si_meminfo(struct sysinfo *val)
5575 {
5576 val->totalram = totalram_pages();
5577 val->sharedram = global_node_page_state(NR_SHMEM);
5578 val->freeram = global_zone_page_state(NR_FREE_PAGES);
5579 val->bufferram = nr_blockdev_pages();
5580 val->totalhigh = totalhigh_pages();
5581 val->freehigh = nr_free_highpages();
5582 val->mem_unit = PAGE_SIZE;
5583 }
5584
5585 EXPORT_SYMBOL(si_meminfo);
5586
5587 #ifdef CONFIG_NUMA
si_meminfo_node(struct sysinfo * val,int nid)5588 void si_meminfo_node(struct sysinfo *val, int nid)
5589 {
5590 int zone_type; /* needs to be signed */
5591 unsigned long managed_pages = 0;
5592 unsigned long managed_highpages = 0;
5593 unsigned long free_highpages = 0;
5594 pg_data_t *pgdat = NODE_DATA(nid);
5595
5596 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++)
5597 managed_pages += zone_managed_pages(&pgdat->node_zones[zone_type]);
5598 val->totalram = managed_pages;
5599 val->sharedram = node_page_state(pgdat, NR_SHMEM);
5600 val->freeram = sum_zone_node_page_state(nid, NR_FREE_PAGES);
5601 #ifdef CONFIG_HIGHMEM
5602 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
5603 struct zone *zone = &pgdat->node_zones[zone_type];
5604
5605 if (is_highmem(zone)) {
5606 managed_highpages += zone_managed_pages(zone);
5607 free_highpages += zone_page_state(zone, NR_FREE_PAGES);
5608 }
5609 }
5610 val->totalhigh = managed_highpages;
5611 val->freehigh = free_highpages;
5612 #else
5613 val->totalhigh = managed_highpages;
5614 val->freehigh = free_highpages;
5615 #endif
5616 val->mem_unit = PAGE_SIZE;
5617 }
5618 #endif
5619
5620 /*
5621 * Determine whether the node should be displayed or not, depending on whether
5622 * SHOW_MEM_FILTER_NODES was passed to show_free_areas().
5623 */
show_mem_node_skip(unsigned int flags,int nid,nodemask_t * nodemask)5624 static bool show_mem_node_skip(unsigned int flags, int nid, nodemask_t *nodemask)
5625 {
5626 if (!(flags & SHOW_MEM_FILTER_NODES))
5627 return false;
5628
5629 /*
5630 * no node mask - aka implicit memory numa policy. Do not bother with
5631 * the synchronization - read_mems_allowed_begin - because we do not
5632 * have to be precise here.
5633 */
5634 if (!nodemask)
5635 nodemask = &cpuset_current_mems_allowed;
5636
5637 return !node_isset(nid, *nodemask);
5638 }
5639
5640 #define K(x) ((x) << (PAGE_SHIFT-10))
5641
show_migration_types(unsigned char type)5642 static void show_migration_types(unsigned char type)
5643 {
5644 static const char types[MIGRATE_TYPES] = {
5645 [MIGRATE_UNMOVABLE] = 'U',
5646 [MIGRATE_MOVABLE] = 'M',
5647 [MIGRATE_RECLAIMABLE] = 'E',
5648 [MIGRATE_HIGHATOMIC] = 'H',
5649 #ifdef CONFIG_CMA
5650 [MIGRATE_CMA] = 'C',
5651 #endif
5652 #ifdef CONFIG_MEMORY_ISOLATION
5653 [MIGRATE_ISOLATE] = 'I',
5654 #endif
5655 };
5656 char tmp[MIGRATE_TYPES + 1];
5657 char *p = tmp;
5658 int i;
5659
5660 for (i = 0; i < MIGRATE_TYPES; i++) {
5661 if (type & (1 << i))
5662 *p++ = types[i];
5663 }
5664
5665 *p = '\0';
5666 printk(KERN_CONT "(%s) ", tmp);
5667 }
5668
5669 /*
5670 * Show free area list (used inside shift_scroll-lock stuff)
5671 * We also calculate the percentage fragmentation. We do this by counting the
5672 * memory on each free list with the exception of the first item on the list.
5673 *
5674 * Bits in @filter:
5675 * SHOW_MEM_FILTER_NODES: suppress nodes that are not allowed by current's
5676 * cpuset.
5677 */
show_free_areas(unsigned int filter,nodemask_t * nodemask)5678 void show_free_areas(unsigned int filter, nodemask_t *nodemask)
5679 {
5680 unsigned long free_pcp = 0;
5681 int cpu;
5682 struct zone *zone;
5683 pg_data_t *pgdat;
5684
5685 for_each_populated_zone(zone) {
5686 if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask))
5687 continue;
5688
5689 for_each_online_cpu(cpu)
5690 free_pcp += per_cpu_ptr(zone->pageset, cpu)->pcp.count;
5691 }
5692
5693 printk("active_anon:%lu inactive_anon:%lu isolated_anon:%lu\n"
5694 " active_file:%lu inactive_file:%lu isolated_file:%lu\n"
5695 " unevictable:%lu dirty:%lu writeback:%lu\n"
5696 " slab_reclaimable:%lu slab_unreclaimable:%lu\n"
5697 " mapped:%lu shmem:%lu pagetables:%lu bounce:%lu\n"
5698 " free:%lu free_pcp:%lu free_cma:%lu\n",
5699 global_node_page_state(NR_ACTIVE_ANON),
5700 global_node_page_state(NR_INACTIVE_ANON),
5701 global_node_page_state(NR_ISOLATED_ANON),
5702 global_node_page_state(NR_ACTIVE_FILE),
5703 global_node_page_state(NR_INACTIVE_FILE),
5704 global_node_page_state(NR_ISOLATED_FILE),
5705 global_node_page_state(NR_UNEVICTABLE),
5706 global_node_page_state(NR_FILE_DIRTY),
5707 global_node_page_state(NR_WRITEBACK),
5708 global_node_page_state_pages(NR_SLAB_RECLAIMABLE_B),
5709 global_node_page_state_pages(NR_SLAB_UNRECLAIMABLE_B),
5710 global_node_page_state(NR_FILE_MAPPED),
5711 global_node_page_state(NR_SHMEM),
5712 global_zone_page_state(NR_PAGETABLE),
5713 global_zone_page_state(NR_BOUNCE),
5714 global_zone_page_state(NR_FREE_PAGES),
5715 free_pcp,
5716 global_zone_page_state(NR_FREE_CMA_PAGES));
5717
5718 trace_android_vh_show_mapcount_pages(NULL);
5719 for_each_online_pgdat(pgdat) {
5720 if (show_mem_node_skip(filter, pgdat->node_id, nodemask))
5721 continue;
5722
5723 printk("Node %d"
5724 " active_anon:%lukB"
5725 " inactive_anon:%lukB"
5726 " active_file:%lukB"
5727 " inactive_file:%lukB"
5728 " unevictable:%lukB"
5729 " isolated(anon):%lukB"
5730 " isolated(file):%lukB"
5731 " mapped:%lukB"
5732 " dirty:%lukB"
5733 " writeback:%lukB"
5734 " shmem:%lukB"
5735 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5736 " shmem_thp: %lukB"
5737 " shmem_pmdmapped: %lukB"
5738 " anon_thp: %lukB"
5739 #endif
5740 " writeback_tmp:%lukB"
5741 " kernel_stack:%lukB"
5742 #ifdef CONFIG_SHADOW_CALL_STACK
5743 " shadow_call_stack:%lukB"
5744 #endif
5745 " all_unreclaimable? %s"
5746 "\n",
5747 pgdat->node_id,
5748 K(node_page_state(pgdat, NR_ACTIVE_ANON)),
5749 K(node_page_state(pgdat, NR_INACTIVE_ANON)),
5750 K(node_page_state(pgdat, NR_ACTIVE_FILE)),
5751 K(node_page_state(pgdat, NR_INACTIVE_FILE)),
5752 K(node_page_state(pgdat, NR_UNEVICTABLE)),
5753 K(node_page_state(pgdat, NR_ISOLATED_ANON)),
5754 K(node_page_state(pgdat, NR_ISOLATED_FILE)),
5755 K(node_page_state(pgdat, NR_FILE_MAPPED)),
5756 K(node_page_state(pgdat, NR_FILE_DIRTY)),
5757 K(node_page_state(pgdat, NR_WRITEBACK)),
5758 K(node_page_state(pgdat, NR_SHMEM)),
5759 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5760 K(node_page_state(pgdat, NR_SHMEM_THPS) * HPAGE_PMD_NR),
5761 K(node_page_state(pgdat, NR_SHMEM_PMDMAPPED)
5762 * HPAGE_PMD_NR),
5763 K(node_page_state(pgdat, NR_ANON_THPS) * HPAGE_PMD_NR),
5764 #endif
5765 K(node_page_state(pgdat, NR_WRITEBACK_TEMP)),
5766 node_page_state(pgdat, NR_KERNEL_STACK_KB),
5767 #ifdef CONFIG_SHADOW_CALL_STACK
5768 node_page_state(pgdat, NR_KERNEL_SCS_KB),
5769 #endif
5770 pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ?
5771 "yes" : "no");
5772 }
5773
5774 for_each_populated_zone(zone) {
5775 int i;
5776
5777 if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask))
5778 continue;
5779
5780 free_pcp = 0;
5781 for_each_online_cpu(cpu)
5782 free_pcp += per_cpu_ptr(zone->pageset, cpu)->pcp.count;
5783
5784 show_node(zone);
5785 printk(KERN_CONT
5786 "%s"
5787 " free:%lukB"
5788 " min:%lukB"
5789 " low:%lukB"
5790 " high:%lukB"
5791 " reserved_highatomic:%luKB"
5792 " active_anon:%lukB"
5793 " inactive_anon:%lukB"
5794 " active_file:%lukB"
5795 " inactive_file:%lukB"
5796 " unevictable:%lukB"
5797 " writepending:%lukB"
5798 " present:%lukB"
5799 " managed:%lukB"
5800 " mlocked:%lukB"
5801 " pagetables:%lukB"
5802 " bounce:%lukB"
5803 " free_pcp:%lukB"
5804 " local_pcp:%ukB"
5805 " free_cma:%lukB"
5806 "\n",
5807 zone->name,
5808 K(zone_page_state(zone, NR_FREE_PAGES)),
5809 K(min_wmark_pages(zone)),
5810 K(low_wmark_pages(zone)),
5811 K(high_wmark_pages(zone)),
5812 K(zone->nr_reserved_highatomic),
5813 K(zone_page_state(zone, NR_ZONE_ACTIVE_ANON)),
5814 K(zone_page_state(zone, NR_ZONE_INACTIVE_ANON)),
5815 K(zone_page_state(zone, NR_ZONE_ACTIVE_FILE)),
5816 K(zone_page_state(zone, NR_ZONE_INACTIVE_FILE)),
5817 K(zone_page_state(zone, NR_ZONE_UNEVICTABLE)),
5818 K(zone_page_state(zone, NR_ZONE_WRITE_PENDING)),
5819 K(zone->present_pages),
5820 K(zone_managed_pages(zone)),
5821 K(zone_page_state(zone, NR_MLOCK)),
5822 K(zone_page_state(zone, NR_PAGETABLE)),
5823 K(zone_page_state(zone, NR_BOUNCE)),
5824 K(free_pcp),
5825 K(this_cpu_read(zone->pageset->pcp.count)),
5826 K(zone_page_state(zone, NR_FREE_CMA_PAGES)));
5827 printk("lowmem_reserve[]:");
5828 for (i = 0; i < MAX_NR_ZONES; i++)
5829 printk(KERN_CONT " %ld", zone->lowmem_reserve[i]);
5830 printk(KERN_CONT "\n");
5831 }
5832
5833 for_each_populated_zone(zone) {
5834 unsigned int order;
5835 unsigned long nr[MAX_ORDER], flags, total = 0;
5836 unsigned char types[MAX_ORDER];
5837
5838 if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask))
5839 continue;
5840 show_node(zone);
5841 printk(KERN_CONT "%s: ", zone->name);
5842
5843 spin_lock_irqsave(&zone->lock, flags);
5844 for (order = 0; order < MAX_ORDER; order++) {
5845 struct free_area *area = &zone->free_area[order];
5846 int type;
5847
5848 nr[order] = area->nr_free;
5849 total += nr[order] << order;
5850
5851 types[order] = 0;
5852 for (type = 0; type < MIGRATE_TYPES; type++) {
5853 if (!free_area_empty(area, type))
5854 types[order] |= 1 << type;
5855 }
5856 }
5857 spin_unlock_irqrestore(&zone->lock, flags);
5858 for (order = 0; order < MAX_ORDER; order++) {
5859 printk(KERN_CONT "%lu*%lukB ",
5860 nr[order], K(1UL) << order);
5861 if (nr[order])
5862 show_migration_types(types[order]);
5863 }
5864 printk(KERN_CONT "= %lukB\n", K(total));
5865 }
5866
5867 hugetlb_show_meminfo();
5868
5869 printk("%ld total pagecache pages\n", global_node_page_state(NR_FILE_PAGES));
5870
5871 show_swap_cache_info();
5872 }
5873
zoneref_set_zone(struct zone * zone,struct zoneref * zoneref)5874 static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref)
5875 {
5876 zoneref->zone = zone;
5877 zoneref->zone_idx = zone_idx(zone);
5878 }
5879
5880 /*
5881 * Builds allocation fallback zone lists.
5882 *
5883 * Add all populated zones of a node to the zonelist.
5884 */
build_zonerefs_node(pg_data_t * pgdat,struct zoneref * zonerefs)5885 static int build_zonerefs_node(pg_data_t *pgdat, struct zoneref *zonerefs)
5886 {
5887 struct zone *zone;
5888 enum zone_type zone_type = MAX_NR_ZONES;
5889 int nr_zones = 0;
5890
5891 do {
5892 zone_type--;
5893 zone = pgdat->node_zones + zone_type;
5894 if (populated_zone(zone)) {
5895 zoneref_set_zone(zone, &zonerefs[nr_zones++]);
5896 check_highest_zone(zone_type);
5897 }
5898 } while (zone_type);
5899
5900 return nr_zones;
5901 }
5902
5903 #ifdef CONFIG_NUMA
5904
__parse_numa_zonelist_order(char * s)5905 static int __parse_numa_zonelist_order(char *s)
5906 {
5907 /*
5908 * We used to support different zonlists modes but they turned
5909 * out to be just not useful. Let's keep the warning in place
5910 * if somebody still use the cmd line parameter so that we do
5911 * not fail it silently
5912 */
5913 if (!(*s == 'd' || *s == 'D' || *s == 'n' || *s == 'N')) {
5914 pr_warn("Ignoring unsupported numa_zonelist_order value: %s\n", s);
5915 return -EINVAL;
5916 }
5917 return 0;
5918 }
5919
5920 char numa_zonelist_order[] = "Node";
5921
5922 /*
5923 * sysctl handler for numa_zonelist_order
5924 */
numa_zonelist_order_handler(struct ctl_table * table,int write,void * buffer,size_t * length,loff_t * ppos)5925 int numa_zonelist_order_handler(struct ctl_table *table, int write,
5926 void *buffer, size_t *length, loff_t *ppos)
5927 {
5928 if (write)
5929 return __parse_numa_zonelist_order(buffer);
5930 return proc_dostring(table, write, buffer, length, ppos);
5931 }
5932
5933
5934 #define MAX_NODE_LOAD (nr_online_nodes)
5935 static int node_load[MAX_NUMNODES];
5936
5937 /**
5938 * find_next_best_node - find the next node that should appear in a given node's fallback list
5939 * @node: node whose fallback list we're appending
5940 * @used_node_mask: nodemask_t of already used nodes
5941 *
5942 * We use a number of factors to determine which is the next node that should
5943 * appear on a given node's fallback list. The node should not have appeared
5944 * already in @node's fallback list, and it should be the next closest node
5945 * according to the distance array (which contains arbitrary distance values
5946 * from each node to each node in the system), and should also prefer nodes
5947 * with no CPUs, since presumably they'll have very little allocation pressure
5948 * on them otherwise.
5949 *
5950 * Return: node id of the found node or %NUMA_NO_NODE if no node is found.
5951 */
find_next_best_node(int node,nodemask_t * used_node_mask)5952 static int find_next_best_node(int node, nodemask_t *used_node_mask)
5953 {
5954 int n, val;
5955 int min_val = INT_MAX;
5956 int best_node = NUMA_NO_NODE;
5957
5958 /* Use the local node if we haven't already */
5959 if (!node_isset(node, *used_node_mask)) {
5960 node_set(node, *used_node_mask);
5961 return node;
5962 }
5963
5964 for_each_node_state(n, N_MEMORY) {
5965
5966 /* Don't want a node to appear more than once */
5967 if (node_isset(n, *used_node_mask))
5968 continue;
5969
5970 /* Use the distance array to find the distance */
5971 val = node_distance(node, n);
5972
5973 /* Penalize nodes under us ("prefer the next node") */
5974 val += (n < node);
5975
5976 /* Give preference to headless and unused nodes */
5977 if (!cpumask_empty(cpumask_of_node(n)))
5978 val += PENALTY_FOR_NODE_WITH_CPUS;
5979
5980 /* Slight preference for less loaded node */
5981 val *= (MAX_NODE_LOAD*MAX_NUMNODES);
5982 val += node_load[n];
5983
5984 if (val < min_val) {
5985 min_val = val;
5986 best_node = n;
5987 }
5988 }
5989
5990 if (best_node >= 0)
5991 node_set(best_node, *used_node_mask);
5992
5993 return best_node;
5994 }
5995
5996
5997 /*
5998 * Build zonelists ordered by node and zones within node.
5999 * This results in maximum locality--normal zone overflows into local
6000 * DMA zone, if any--but risks exhausting DMA zone.
6001 */
build_zonelists_in_node_order(pg_data_t * pgdat,int * node_order,unsigned nr_nodes)6002 static void build_zonelists_in_node_order(pg_data_t *pgdat, int *node_order,
6003 unsigned nr_nodes)
6004 {
6005 struct zoneref *zonerefs;
6006 int i;
6007
6008 zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs;
6009
6010 for (i = 0; i < nr_nodes; i++) {
6011 int nr_zones;
6012
6013 pg_data_t *node = NODE_DATA(node_order[i]);
6014
6015 nr_zones = build_zonerefs_node(node, zonerefs);
6016 zonerefs += nr_zones;
6017 }
6018 zonerefs->zone = NULL;
6019 zonerefs->zone_idx = 0;
6020 }
6021
6022 /*
6023 * Build gfp_thisnode zonelists
6024 */
build_thisnode_zonelists(pg_data_t * pgdat)6025 static void build_thisnode_zonelists(pg_data_t *pgdat)
6026 {
6027 struct zoneref *zonerefs;
6028 int nr_zones;
6029
6030 zonerefs = pgdat->node_zonelists[ZONELIST_NOFALLBACK]._zonerefs;
6031 nr_zones = build_zonerefs_node(pgdat, zonerefs);
6032 zonerefs += nr_zones;
6033 zonerefs->zone = NULL;
6034 zonerefs->zone_idx = 0;
6035 }
6036
6037 /*
6038 * Build zonelists ordered by zone and nodes within zones.
6039 * This results in conserving DMA zone[s] until all Normal memory is
6040 * exhausted, but results in overflowing to remote node while memory
6041 * may still exist in local DMA zone.
6042 */
6043
build_zonelists(pg_data_t * pgdat)6044 static void build_zonelists(pg_data_t *pgdat)
6045 {
6046 static int node_order[MAX_NUMNODES];
6047 int node, load, nr_nodes = 0;
6048 nodemask_t used_mask = NODE_MASK_NONE;
6049 int local_node, prev_node;
6050
6051 /* NUMA-aware ordering of nodes */
6052 local_node = pgdat->node_id;
6053 load = nr_online_nodes;
6054 prev_node = local_node;
6055
6056 memset(node_order, 0, sizeof(node_order));
6057 while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
6058 /*
6059 * We don't want to pressure a particular node.
6060 * So adding penalty to the first node in same
6061 * distance group to make it round-robin.
6062 */
6063 if (node_distance(local_node, node) !=
6064 node_distance(local_node, prev_node))
6065 node_load[node] = load;
6066
6067 node_order[nr_nodes++] = node;
6068 prev_node = node;
6069 load--;
6070 }
6071
6072 build_zonelists_in_node_order(pgdat, node_order, nr_nodes);
6073 build_thisnode_zonelists(pgdat);
6074 }
6075
6076 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
6077 /*
6078 * Return node id of node used for "local" allocations.
6079 * I.e., first node id of first zone in arg node's generic zonelist.
6080 * Used for initializing percpu 'numa_mem', which is used primarily
6081 * for kernel allocations, so use GFP_KERNEL flags to locate zonelist.
6082 */
local_memory_node(int node)6083 int local_memory_node(int node)
6084 {
6085 struct zoneref *z;
6086
6087 z = first_zones_zonelist(node_zonelist(node, GFP_KERNEL),
6088 gfp_zone(GFP_KERNEL),
6089 NULL);
6090 return zone_to_nid(z->zone);
6091 }
6092 #endif
6093
6094 static void setup_min_unmapped_ratio(void);
6095 static void setup_min_slab_ratio(void);
6096 #else /* CONFIG_NUMA */
6097
build_zonelists(pg_data_t * pgdat)6098 static void build_zonelists(pg_data_t *pgdat)
6099 {
6100 int node, local_node;
6101 struct zoneref *zonerefs;
6102 int nr_zones;
6103
6104 local_node = pgdat->node_id;
6105
6106 zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs;
6107 nr_zones = build_zonerefs_node(pgdat, zonerefs);
6108 zonerefs += nr_zones;
6109
6110 /*
6111 * Now we build the zonelist so that it contains the zones
6112 * of all the other nodes.
6113 * We don't want to pressure a particular node, so when
6114 * building the zones for node N, we make sure that the
6115 * zones coming right after the local ones are those from
6116 * node N+1 (modulo N)
6117 */
6118 for (node = local_node + 1; node < MAX_NUMNODES; node++) {
6119 if (!node_online(node))
6120 continue;
6121 nr_zones = build_zonerefs_node(NODE_DATA(node), zonerefs);
6122 zonerefs += nr_zones;
6123 }
6124 for (node = 0; node < local_node; node++) {
6125 if (!node_online(node))
6126 continue;
6127 nr_zones = build_zonerefs_node(NODE_DATA(node), zonerefs);
6128 zonerefs += nr_zones;
6129 }
6130
6131 zonerefs->zone = NULL;
6132 zonerefs->zone_idx = 0;
6133 }
6134
6135 #endif /* CONFIG_NUMA */
6136
6137 /*
6138 * Boot pageset table. One per cpu which is going to be used for all
6139 * zones and all nodes. The parameters will be set in such a way
6140 * that an item put on a list will immediately be handed over to
6141 * the buddy list. This is safe since pageset manipulation is done
6142 * with interrupts disabled.
6143 *
6144 * The boot_pagesets must be kept even after bootup is complete for
6145 * unused processors and/or zones. They do play a role for bootstrapping
6146 * hotplugged processors.
6147 *
6148 * zoneinfo_show() and maybe other functions do
6149 * not check if the processor is online before following the pageset pointer.
6150 * Other parts of the kernel may not check if the zone is available.
6151 */
6152 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch);
6153 static DEFINE_PER_CPU(struct per_cpu_pageset, boot_pageset);
6154 static DEFINE_PER_CPU(struct per_cpu_nodestat, boot_nodestats);
6155
__build_all_zonelists(void * data)6156 static void __build_all_zonelists(void *data)
6157 {
6158 int nid;
6159 int __maybe_unused cpu;
6160 pg_data_t *self = data;
6161
6162 write_seqlock(&zonelist_update_seq);
6163
6164 #ifdef CONFIG_NUMA
6165 memset(node_load, 0, sizeof(node_load));
6166 #endif
6167
6168 /*
6169 * This node is hotadded and no memory is yet present. So just
6170 * building zonelists is fine - no need to touch other nodes.
6171 */
6172 if (self && !node_online(self->node_id)) {
6173 build_zonelists(self);
6174 } else {
6175 for_each_online_node(nid) {
6176 pg_data_t *pgdat = NODE_DATA(nid);
6177
6178 build_zonelists(pgdat);
6179 }
6180
6181 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
6182 /*
6183 * We now know the "local memory node" for each node--
6184 * i.e., the node of the first zone in the generic zonelist.
6185 * Set up numa_mem percpu variable for on-line cpus. During
6186 * boot, only the boot cpu should be on-line; we'll init the
6187 * secondary cpus' numa_mem as they come on-line. During
6188 * node/memory hotplug, we'll fixup all on-line cpus.
6189 */
6190 for_each_online_cpu(cpu)
6191 set_cpu_numa_mem(cpu, local_memory_node(cpu_to_node(cpu)));
6192 #endif
6193 }
6194
6195 write_sequnlock(&zonelist_update_seq);
6196 }
6197
6198 static noinline void __init
build_all_zonelists_init(void)6199 build_all_zonelists_init(void)
6200 {
6201 int cpu;
6202
6203 __build_all_zonelists(NULL);
6204
6205 /*
6206 * Initialize the boot_pagesets that are going to be used
6207 * for bootstrapping processors. The real pagesets for
6208 * each zone will be allocated later when the per cpu
6209 * allocator is available.
6210 *
6211 * boot_pagesets are used also for bootstrapping offline
6212 * cpus if the system is already booted because the pagesets
6213 * are needed to initialize allocators on a specific cpu too.
6214 * F.e. the percpu allocator needs the page allocator which
6215 * needs the percpu allocator in order to allocate its pagesets
6216 * (a chicken-egg dilemma).
6217 */
6218 for_each_possible_cpu(cpu)
6219 setup_pageset(&per_cpu(boot_pageset, cpu), 0);
6220
6221 mminit_verify_zonelist();
6222 cpuset_init_current_mems_allowed();
6223 }
6224
6225 /*
6226 * unless system_state == SYSTEM_BOOTING.
6227 *
6228 * __ref due to call of __init annotated helper build_all_zonelists_init
6229 * [protected by SYSTEM_BOOTING].
6230 */
build_all_zonelists(pg_data_t * pgdat)6231 void __ref build_all_zonelists(pg_data_t *pgdat)
6232 {
6233 unsigned long vm_total_pages;
6234
6235 if (system_state == SYSTEM_BOOTING) {
6236 build_all_zonelists_init();
6237 } else {
6238 __build_all_zonelists(pgdat);
6239 /* cpuset refresh routine should be here */
6240 }
6241 /* Get the number of free pages beyond high watermark in all zones. */
6242 vm_total_pages = nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE));
6243 /*
6244 * Disable grouping by mobility if the number of pages in the
6245 * system is too low to allow the mechanism to work. It would be
6246 * more accurate, but expensive to check per-zone. This check is
6247 * made on memory-hotadd so a system can start with mobility
6248 * disabled and enable it later
6249 */
6250 if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES))
6251 page_group_by_mobility_disabled = 1;
6252 else
6253 page_group_by_mobility_disabled = 0;
6254
6255 pr_info("Built %u zonelists, mobility grouping %s. Total pages: %ld\n",
6256 nr_online_nodes,
6257 page_group_by_mobility_disabled ? "off" : "on",
6258 vm_total_pages);
6259 #ifdef CONFIG_NUMA
6260 pr_info("Policy zone: %s\n", zone_names[policy_zone]);
6261 #endif
6262 }
6263
6264 /* If zone is ZONE_MOVABLE but memory is mirrored, it is an overlapped init */
6265 static bool __meminit
overlap_memmap_init(unsigned long zone,unsigned long * pfn)6266 overlap_memmap_init(unsigned long zone, unsigned long *pfn)
6267 {
6268 static struct memblock_region *r;
6269
6270 if (mirrored_kernelcore && zone == ZONE_MOVABLE) {
6271 if (!r || *pfn >= memblock_region_memory_end_pfn(r)) {
6272 for_each_mem_region(r) {
6273 if (*pfn < memblock_region_memory_end_pfn(r))
6274 break;
6275 }
6276 }
6277 if (*pfn >= memblock_region_memory_base_pfn(r) &&
6278 memblock_is_mirror(r)) {
6279 *pfn = memblock_region_memory_end_pfn(r);
6280 return true;
6281 }
6282 }
6283 return false;
6284 }
6285
6286 /*
6287 * Initially all pages are reserved - free ones are freed
6288 * up by memblock_free_all() once the early boot process is
6289 * done. Non-atomic initialization, single-pass.
6290 *
6291 * All aligned pageblocks are initialized to the specified migratetype
6292 * (usually MIGRATE_MOVABLE). Besides setting the migratetype, no related
6293 * zone stats (e.g., nr_isolate_pageblock) are touched.
6294 */
memmap_init_zone(unsigned long size,int nid,unsigned long zone,unsigned long start_pfn,unsigned long zone_end_pfn,enum meminit_context context,struct vmem_altmap * altmap,int migratetype)6295 void __meminit memmap_init_zone(unsigned long size, int nid, unsigned long zone,
6296 unsigned long start_pfn, unsigned long zone_end_pfn,
6297 enum meminit_context context,
6298 struct vmem_altmap *altmap, int migratetype)
6299 {
6300 unsigned long pfn, end_pfn = start_pfn + size;
6301 struct page *page;
6302
6303 if (highest_memmap_pfn < end_pfn - 1)
6304 highest_memmap_pfn = end_pfn - 1;
6305
6306 #ifdef CONFIG_ZONE_DEVICE
6307 /*
6308 * Honor reservation requested by the driver for this ZONE_DEVICE
6309 * memory. We limit the total number of pages to initialize to just
6310 * those that might contain the memory mapping. We will defer the
6311 * ZONE_DEVICE page initialization until after we have released
6312 * the hotplug lock.
6313 */
6314 if (zone == ZONE_DEVICE) {
6315 if (!altmap)
6316 return;
6317
6318 if (start_pfn == altmap->base_pfn)
6319 start_pfn += altmap->reserve;
6320 end_pfn = altmap->base_pfn + vmem_altmap_offset(altmap);
6321 }
6322 #endif
6323
6324 #ifdef CONFIG_ROCKCHIP_THUNDER_BOOT
6325 /* Zero all page struct in advance */
6326 memset(pfn_to_page(start_pfn), 0, sizeof(struct page) * size);
6327 #endif
6328
6329 for (pfn = start_pfn; pfn < end_pfn; ) {
6330 /*
6331 * There can be holes in boot-time mem_map[]s handed to this
6332 * function. They do not exist on hotplugged memory.
6333 */
6334 if (context == MEMINIT_EARLY) {
6335 if (overlap_memmap_init(zone, &pfn))
6336 continue;
6337 if (defer_init(nid, pfn, zone_end_pfn))
6338 break;
6339 }
6340
6341 page = pfn_to_page(pfn);
6342 __init_single_page(page, pfn, zone, nid, false);
6343 if (context == MEMINIT_HOTPLUG)
6344 __SetPageReserved(page);
6345
6346 /*
6347 * Usually, we want to mark the pageblock MIGRATE_MOVABLE,
6348 * such that unmovable allocations won't be scattered all
6349 * over the place during system boot.
6350 */
6351 if (IS_ALIGNED(pfn, pageblock_nr_pages)) {
6352 set_pageblock_migratetype(page, migratetype);
6353 cond_resched();
6354 }
6355 pfn++;
6356 }
6357 }
6358
6359 #ifdef CONFIG_ZONE_DEVICE
memmap_init_zone_device(struct zone * zone,unsigned long start_pfn,unsigned long nr_pages,struct dev_pagemap * pgmap)6360 void __ref memmap_init_zone_device(struct zone *zone,
6361 unsigned long start_pfn,
6362 unsigned long nr_pages,
6363 struct dev_pagemap *pgmap)
6364 {
6365 unsigned long pfn, end_pfn = start_pfn + nr_pages;
6366 struct pglist_data *pgdat = zone->zone_pgdat;
6367 struct vmem_altmap *altmap = pgmap_altmap(pgmap);
6368 unsigned long zone_idx = zone_idx(zone);
6369 unsigned long start = jiffies;
6370 int nid = pgdat->node_id;
6371
6372 if (WARN_ON_ONCE(!pgmap || zone_idx(zone) != ZONE_DEVICE))
6373 return;
6374
6375 /*
6376 * The call to memmap_init should have already taken care
6377 * of the pages reserved for the memmap, so we can just jump to
6378 * the end of that region and start processing the device pages.
6379 */
6380 if (altmap) {
6381 start_pfn = altmap->base_pfn + vmem_altmap_offset(altmap);
6382 nr_pages = end_pfn - start_pfn;
6383 }
6384
6385 for (pfn = start_pfn; pfn < end_pfn; pfn++) {
6386 struct page *page = pfn_to_page(pfn);
6387
6388 __init_single_page(page, pfn, zone_idx, nid, true);
6389
6390 /*
6391 * Mark page reserved as it will need to wait for onlining
6392 * phase for it to be fully associated with a zone.
6393 *
6394 * We can use the non-atomic __set_bit operation for setting
6395 * the flag as we are still initializing the pages.
6396 */
6397 __SetPageReserved(page);
6398
6399 /*
6400 * ZONE_DEVICE pages union ->lru with a ->pgmap back pointer
6401 * and zone_device_data. It is a bug if a ZONE_DEVICE page is
6402 * ever freed or placed on a driver-private list.
6403 */
6404 page->pgmap = pgmap;
6405 page->zone_device_data = NULL;
6406
6407 /*
6408 * Mark the block movable so that blocks are reserved for
6409 * movable at startup. This will force kernel allocations
6410 * to reserve their blocks rather than leaking throughout
6411 * the address space during boot when many long-lived
6412 * kernel allocations are made.
6413 *
6414 * Please note that MEMINIT_HOTPLUG path doesn't clear memmap
6415 * because this is done early in section_activate()
6416 */
6417 if (IS_ALIGNED(pfn, pageblock_nr_pages)) {
6418 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
6419 cond_resched();
6420 }
6421 }
6422
6423 pr_info("%s initialised %lu pages in %ums\n", __func__,
6424 nr_pages, jiffies_to_msecs(jiffies - start));
6425 }
6426
6427 #endif
zone_init_free_lists(struct zone * zone)6428 static void __meminit zone_init_free_lists(struct zone *zone)
6429 {
6430 unsigned int order, t;
6431 for_each_migratetype_order(order, t) {
6432 INIT_LIST_HEAD(&zone->free_area[order].free_list[t]);
6433 zone->free_area[order].nr_free = 0;
6434 }
6435 }
6436
6437 /*
6438 * Only struct pages that correspond to ranges defined by memblock.memory
6439 * are zeroed and initialized by going through __init_single_page() during
6440 * memmap_init_zone_range().
6441 *
6442 * But, there could be struct pages that correspond to holes in
6443 * memblock.memory. This can happen because of the following reasons:
6444 * - physical memory bank size is not necessarily the exact multiple of the
6445 * arbitrary section size
6446 * - early reserved memory may not be listed in memblock.memory
6447 * - memory layouts defined with memmap= kernel parameter may not align
6448 * nicely with memmap sections
6449 *
6450 * Explicitly initialize those struct pages so that:
6451 * - PG_Reserved is set
6452 * - zone and node links point to zone and node that span the page if the
6453 * hole is in the middle of a zone
6454 * - zone and node links point to adjacent zone/node if the hole falls on
6455 * the zone boundary; the pages in such holes will be prepended to the
6456 * zone/node above the hole except for the trailing pages in the last
6457 * section that will be appended to the zone/node below.
6458 */
init_unavailable_range(unsigned long spfn,unsigned long epfn,int zone,int node)6459 static void __init init_unavailable_range(unsigned long spfn,
6460 unsigned long epfn,
6461 int zone, int node)
6462 {
6463 unsigned long pfn;
6464 u64 pgcnt = 0;
6465
6466 for (pfn = spfn; pfn < epfn; pfn++) {
6467 if (!pfn_valid(ALIGN_DOWN(pfn, pageblock_nr_pages))) {
6468 pfn = ALIGN_DOWN(pfn, pageblock_nr_pages)
6469 + pageblock_nr_pages - 1;
6470 continue;
6471 }
6472 __init_single_page(pfn_to_page(pfn), pfn, zone, node, true);
6473 __SetPageReserved(pfn_to_page(pfn));
6474 pgcnt++;
6475 }
6476
6477 if (pgcnt)
6478 pr_info("On node %d, zone %s: %lld pages in unavailable ranges",
6479 node, zone_names[zone], pgcnt);
6480 }
6481
memmap_init_zone_range(struct zone * zone,unsigned long start_pfn,unsigned long end_pfn,unsigned long * hole_pfn)6482 static void __init memmap_init_zone_range(struct zone *zone,
6483 unsigned long start_pfn,
6484 unsigned long end_pfn,
6485 unsigned long *hole_pfn)
6486 {
6487 unsigned long zone_start_pfn = zone->zone_start_pfn;
6488 unsigned long zone_end_pfn = zone_start_pfn + zone->spanned_pages;
6489 int nid = zone_to_nid(zone), zone_id = zone_idx(zone);
6490
6491 start_pfn = clamp(start_pfn, zone_start_pfn, zone_end_pfn);
6492 end_pfn = clamp(end_pfn, zone_start_pfn, zone_end_pfn);
6493
6494 if (start_pfn >= end_pfn)
6495 return;
6496
6497 memmap_init_zone(end_pfn - start_pfn, nid, zone_id, start_pfn,
6498 zone_end_pfn, MEMINIT_EARLY, NULL, MIGRATE_MOVABLE);
6499
6500 if (*hole_pfn < start_pfn)
6501 init_unavailable_range(*hole_pfn, start_pfn, zone_id, nid);
6502
6503 *hole_pfn = end_pfn;
6504 }
6505
memmap_init(void)6506 void __init __weak memmap_init(void)
6507 {
6508 unsigned long start_pfn, end_pfn;
6509 unsigned long hole_pfn = 0;
6510 int i, j, zone_id, nid;
6511
6512 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
6513 struct pglist_data *node = NODE_DATA(nid);
6514
6515 for (j = 0; j < MAX_NR_ZONES; j++) {
6516 struct zone *zone = node->node_zones + j;
6517
6518 if (!populated_zone(zone))
6519 continue;
6520
6521 memmap_init_zone_range(zone, start_pfn, end_pfn,
6522 &hole_pfn);
6523 zone_id = j;
6524 }
6525 }
6526
6527 #ifdef CONFIG_SPARSEMEM
6528 /*
6529 * Initialize the memory map for hole in the range [memory_end,
6530 * section_end].
6531 * Append the pages in this hole to the highest zone in the last
6532 * node.
6533 * The call to init_unavailable_range() is outside the ifdef to
6534 * silence the compiler warining about zone_id set but not used;
6535 * for FLATMEM it is a nop anyway
6536 */
6537 end_pfn = round_up(end_pfn, PAGES_PER_SECTION);
6538 if (hole_pfn < end_pfn)
6539 #endif
6540 init_unavailable_range(hole_pfn, end_pfn, zone_id, nid);
6541 }
6542
6543 /* A stub for backwards compatibility with custom implementatin on IA-64 */
arch_memmap_init(unsigned long size,int nid,unsigned long zone,unsigned long range_start_pfn)6544 void __meminit __weak arch_memmap_init(unsigned long size, int nid,
6545 unsigned long zone,
6546 unsigned long range_start_pfn)
6547 {
6548 }
6549
zone_batchsize(struct zone * zone)6550 static int zone_batchsize(struct zone *zone)
6551 {
6552 #ifdef CONFIG_MMU
6553 int batch;
6554
6555 /*
6556 * The per-cpu-pages pools are set to around 1000th of the
6557 * size of the zone.
6558 */
6559 batch = zone_managed_pages(zone) / 1024;
6560 /* But no more than a meg. */
6561 if (batch * PAGE_SIZE > 1024 * 1024)
6562 batch = (1024 * 1024) / PAGE_SIZE;
6563 batch /= 4; /* We effectively *= 4 below */
6564 if (batch < 1)
6565 batch = 1;
6566
6567 /*
6568 * Clamp the batch to a 2^n - 1 value. Having a power
6569 * of 2 value was found to be more likely to have
6570 * suboptimal cache aliasing properties in some cases.
6571 *
6572 * For example if 2 tasks are alternately allocating
6573 * batches of pages, one task can end up with a lot
6574 * of pages of one half of the possible page colors
6575 * and the other with pages of the other colors.
6576 */
6577 batch = rounddown_pow_of_two(batch + batch/2) - 1;
6578
6579 return batch;
6580
6581 #else
6582 /* The deferral and batching of frees should be suppressed under NOMMU
6583 * conditions.
6584 *
6585 * The problem is that NOMMU needs to be able to allocate large chunks
6586 * of contiguous memory as there's no hardware page translation to
6587 * assemble apparent contiguous memory from discontiguous pages.
6588 *
6589 * Queueing large contiguous runs of pages for batching, however,
6590 * causes the pages to actually be freed in smaller chunks. As there
6591 * can be a significant delay between the individual batches being
6592 * recycled, this leads to the once large chunks of space being
6593 * fragmented and becoming unavailable for high-order allocations.
6594 */
6595 return 0;
6596 #endif
6597 }
6598
6599 /*
6600 * pcp->high and pcp->batch values are related and dependent on one another:
6601 * ->batch must never be higher then ->high.
6602 * The following function updates them in a safe manner without read side
6603 * locking.
6604 *
6605 * Any new users of pcp->batch and pcp->high should ensure they can cope with
6606 * those fields changing asynchronously (acording to the above rule).
6607 *
6608 * mutex_is_locked(&pcp_batch_high_lock) required when calling this function
6609 * outside of boot time (or some other assurance that no concurrent updaters
6610 * exist).
6611 */
pageset_update(struct per_cpu_pages * pcp,unsigned long high,unsigned long batch)6612 static void pageset_update(struct per_cpu_pages *pcp, unsigned long high,
6613 unsigned long batch)
6614 {
6615 /* start with a fail safe value for batch */
6616 pcp->batch = 1;
6617 smp_wmb();
6618
6619 /* Update high, then batch, in order */
6620 pcp->high = high;
6621 smp_wmb();
6622
6623 pcp->batch = batch;
6624 }
6625
6626 /* a companion to pageset_set_high() */
pageset_set_batch(struct per_cpu_pageset * p,unsigned long batch)6627 static void pageset_set_batch(struct per_cpu_pageset *p, unsigned long batch)
6628 {
6629 pageset_update(&p->pcp, 6 * batch, max(1UL, 1 * batch));
6630 }
6631
pageset_init(struct per_cpu_pageset * p)6632 static void pageset_init(struct per_cpu_pageset *p)
6633 {
6634 struct per_cpu_pages *pcp;
6635 int migratetype;
6636
6637 memset(p, 0, sizeof(*p));
6638
6639 pcp = &p->pcp;
6640 for (migratetype = 0; migratetype < MIGRATE_PCPTYPES; migratetype++)
6641 INIT_LIST_HEAD(&pcp->lists[migratetype]);
6642 }
6643
setup_pageset(struct per_cpu_pageset * p,unsigned long batch)6644 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch)
6645 {
6646 pageset_init(p);
6647 pageset_set_batch(p, batch);
6648 }
6649
6650 /*
6651 * pageset_set_high() sets the high water mark for hot per_cpu_pagelist
6652 * to the value high for the pageset p.
6653 */
pageset_set_high(struct per_cpu_pageset * p,unsigned long high)6654 static void pageset_set_high(struct per_cpu_pageset *p,
6655 unsigned long high)
6656 {
6657 unsigned long batch = max(1UL, high / 4);
6658 if ((high / 4) > (PAGE_SHIFT * 8))
6659 batch = PAGE_SHIFT * 8;
6660
6661 pageset_update(&p->pcp, high, batch);
6662 }
6663
pageset_set_high_and_batch(struct zone * zone,struct per_cpu_pageset * pcp)6664 static void pageset_set_high_and_batch(struct zone *zone,
6665 struct per_cpu_pageset *pcp)
6666 {
6667 if (percpu_pagelist_fraction)
6668 pageset_set_high(pcp,
6669 (zone_managed_pages(zone) /
6670 percpu_pagelist_fraction));
6671 else
6672 pageset_set_batch(pcp, zone_batchsize(zone));
6673 }
6674
zone_pageset_init(struct zone * zone,int cpu)6675 static void __meminit zone_pageset_init(struct zone *zone, int cpu)
6676 {
6677 struct per_cpu_pageset *pcp = per_cpu_ptr(zone->pageset, cpu);
6678
6679 pageset_init(pcp);
6680 pageset_set_high_and_batch(zone, pcp);
6681 }
6682
setup_zone_pageset(struct zone * zone)6683 void __meminit setup_zone_pageset(struct zone *zone)
6684 {
6685 int cpu;
6686 zone->pageset = alloc_percpu(struct per_cpu_pageset);
6687 for_each_possible_cpu(cpu)
6688 zone_pageset_init(zone, cpu);
6689 }
6690
6691 /*
6692 * Allocate per cpu pagesets and initialize them.
6693 * Before this call only boot pagesets were available.
6694 */
setup_per_cpu_pageset(void)6695 void __init setup_per_cpu_pageset(void)
6696 {
6697 struct pglist_data *pgdat;
6698 struct zone *zone;
6699 int __maybe_unused cpu;
6700
6701 for_each_populated_zone(zone)
6702 setup_zone_pageset(zone);
6703
6704 #ifdef CONFIG_NUMA
6705 /*
6706 * Unpopulated zones continue using the boot pagesets.
6707 * The numa stats for these pagesets need to be reset.
6708 * Otherwise, they will end up skewing the stats of
6709 * the nodes these zones are associated with.
6710 */
6711 for_each_possible_cpu(cpu) {
6712 struct per_cpu_pageset *pcp = &per_cpu(boot_pageset, cpu);
6713 memset(pcp->vm_numa_stat_diff, 0,
6714 sizeof(pcp->vm_numa_stat_diff));
6715 }
6716 #endif
6717
6718 for_each_online_pgdat(pgdat)
6719 pgdat->per_cpu_nodestats =
6720 alloc_percpu(struct per_cpu_nodestat);
6721 }
6722
zone_pcp_init(struct zone * zone)6723 static __meminit void zone_pcp_init(struct zone *zone)
6724 {
6725 /*
6726 * per cpu subsystem is not up at this point. The following code
6727 * relies on the ability of the linker to provide the
6728 * offset of a (static) per cpu variable into the per cpu area.
6729 */
6730 zone->pageset = &boot_pageset;
6731
6732 if (populated_zone(zone))
6733 printk(KERN_DEBUG " %s zone: %lu pages, LIFO batch:%u\n",
6734 zone->name, zone->present_pages,
6735 zone_batchsize(zone));
6736 }
6737
init_currently_empty_zone(struct zone * zone,unsigned long zone_start_pfn,unsigned long size)6738 void __meminit init_currently_empty_zone(struct zone *zone,
6739 unsigned long zone_start_pfn,
6740 unsigned long size)
6741 {
6742 struct pglist_data *pgdat = zone->zone_pgdat;
6743 int zone_idx = zone_idx(zone) + 1;
6744
6745 if (zone_idx > pgdat->nr_zones)
6746 pgdat->nr_zones = zone_idx;
6747
6748 zone->zone_start_pfn = zone_start_pfn;
6749
6750 mminit_dprintk(MMINIT_TRACE, "memmap_init",
6751 "Initialising map node %d zone %lu pfns %lu -> %lu\n",
6752 pgdat->node_id,
6753 (unsigned long)zone_idx(zone),
6754 zone_start_pfn, (zone_start_pfn + size));
6755
6756 zone_init_free_lists(zone);
6757 zone->initialized = 1;
6758 }
6759
6760 /**
6761 * get_pfn_range_for_nid - Return the start and end page frames for a node
6762 * @nid: The nid to return the range for. If MAX_NUMNODES, the min and max PFN are returned.
6763 * @start_pfn: Passed by reference. On return, it will have the node start_pfn.
6764 * @end_pfn: Passed by reference. On return, it will have the node end_pfn.
6765 *
6766 * It returns the start and end page frame of a node based on information
6767 * provided by memblock_set_node(). If called for a node
6768 * with no available memory, a warning is printed and the start and end
6769 * PFNs will be 0.
6770 */
get_pfn_range_for_nid(unsigned int nid,unsigned long * start_pfn,unsigned long * end_pfn)6771 void __init get_pfn_range_for_nid(unsigned int nid,
6772 unsigned long *start_pfn, unsigned long *end_pfn)
6773 {
6774 unsigned long this_start_pfn, this_end_pfn;
6775 int i;
6776
6777 *start_pfn = -1UL;
6778 *end_pfn = 0;
6779
6780 for_each_mem_pfn_range(i, nid, &this_start_pfn, &this_end_pfn, NULL) {
6781 *start_pfn = min(*start_pfn, this_start_pfn);
6782 *end_pfn = max(*end_pfn, this_end_pfn);
6783 }
6784
6785 if (*start_pfn == -1UL)
6786 *start_pfn = 0;
6787 }
6788
6789 /*
6790 * This finds a zone that can be used for ZONE_MOVABLE pages. The
6791 * assumption is made that zones within a node are ordered in monotonic
6792 * increasing memory addresses so that the "highest" populated zone is used
6793 */
find_usable_zone_for_movable(void)6794 static void __init find_usable_zone_for_movable(void)
6795 {
6796 int zone_index;
6797 for (zone_index = MAX_NR_ZONES - 1; zone_index >= 0; zone_index--) {
6798 if (zone_index == ZONE_MOVABLE)
6799 continue;
6800
6801 if (arch_zone_highest_possible_pfn[zone_index] >
6802 arch_zone_lowest_possible_pfn[zone_index])
6803 break;
6804 }
6805
6806 VM_BUG_ON(zone_index == -1);
6807 movable_zone = zone_index;
6808 }
6809
6810 /*
6811 * The zone ranges provided by the architecture do not include ZONE_MOVABLE
6812 * because it is sized independent of architecture. Unlike the other zones,
6813 * the starting point for ZONE_MOVABLE is not fixed. It may be different
6814 * in each node depending on the size of each node and how evenly kernelcore
6815 * is distributed. This helper function adjusts the zone ranges
6816 * provided by the architecture for a given node by using the end of the
6817 * highest usable zone for ZONE_MOVABLE. This preserves the assumption that
6818 * zones within a node are in order of monotonic increases memory addresses
6819 */
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)6820 static void __init adjust_zone_range_for_zone_movable(int nid,
6821 unsigned long zone_type,
6822 unsigned long node_start_pfn,
6823 unsigned long node_end_pfn,
6824 unsigned long *zone_start_pfn,
6825 unsigned long *zone_end_pfn)
6826 {
6827 /* Only adjust if ZONE_MOVABLE is on this node */
6828 if (zone_movable_pfn[nid]) {
6829 /* Size ZONE_MOVABLE */
6830 if (zone_type == ZONE_MOVABLE) {
6831 *zone_start_pfn = zone_movable_pfn[nid];
6832 *zone_end_pfn = min(node_end_pfn,
6833 arch_zone_highest_possible_pfn[movable_zone]);
6834
6835 /* Adjust for ZONE_MOVABLE starting within this range */
6836 } else if (!mirrored_kernelcore &&
6837 *zone_start_pfn < zone_movable_pfn[nid] &&
6838 *zone_end_pfn > zone_movable_pfn[nid]) {
6839 *zone_end_pfn = zone_movable_pfn[nid];
6840
6841 /* Check if this whole range is within ZONE_MOVABLE */
6842 } else if (*zone_start_pfn >= zone_movable_pfn[nid])
6843 *zone_start_pfn = *zone_end_pfn;
6844 }
6845 }
6846
6847 /*
6848 * Return the number of pages a zone spans in a node, including holes
6849 * present_pages = zone_spanned_pages_in_node() - zone_absent_pages_in_node()
6850 */
zone_spanned_pages_in_node(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)6851 static unsigned long __init zone_spanned_pages_in_node(int nid,
6852 unsigned long zone_type,
6853 unsigned long node_start_pfn,
6854 unsigned long node_end_pfn,
6855 unsigned long *zone_start_pfn,
6856 unsigned long *zone_end_pfn)
6857 {
6858 unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type];
6859 unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type];
6860 /* When hotadd a new node from cpu_up(), the node should be empty */
6861 if (!node_start_pfn && !node_end_pfn)
6862 return 0;
6863
6864 /* Get the start and end of the zone */
6865 *zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high);
6866 *zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high);
6867 adjust_zone_range_for_zone_movable(nid, zone_type,
6868 node_start_pfn, node_end_pfn,
6869 zone_start_pfn, zone_end_pfn);
6870
6871 /* Check that this node has pages within the zone's required range */
6872 if (*zone_end_pfn < node_start_pfn || *zone_start_pfn > node_end_pfn)
6873 return 0;
6874
6875 /* Move the zone boundaries inside the node if necessary */
6876 *zone_end_pfn = min(*zone_end_pfn, node_end_pfn);
6877 *zone_start_pfn = max(*zone_start_pfn, node_start_pfn);
6878
6879 /* Return the spanned pages */
6880 return *zone_end_pfn - *zone_start_pfn;
6881 }
6882
6883 /*
6884 * Return the number of holes in a range on a node. If nid is MAX_NUMNODES,
6885 * then all holes in the requested range will be accounted for.
6886 */
__absent_pages_in_range(int nid,unsigned long range_start_pfn,unsigned long range_end_pfn)6887 unsigned long __init __absent_pages_in_range(int nid,
6888 unsigned long range_start_pfn,
6889 unsigned long range_end_pfn)
6890 {
6891 unsigned long nr_absent = range_end_pfn - range_start_pfn;
6892 unsigned long start_pfn, end_pfn;
6893 int i;
6894
6895 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
6896 start_pfn = clamp(start_pfn, range_start_pfn, range_end_pfn);
6897 end_pfn = clamp(end_pfn, range_start_pfn, range_end_pfn);
6898 nr_absent -= end_pfn - start_pfn;
6899 }
6900 return nr_absent;
6901 }
6902
6903 /**
6904 * absent_pages_in_range - Return number of page frames in holes within a range
6905 * @start_pfn: The start PFN to start searching for holes
6906 * @end_pfn: The end PFN to stop searching for holes
6907 *
6908 * Return: the number of pages frames in memory holes within a range.
6909 */
absent_pages_in_range(unsigned long start_pfn,unsigned long end_pfn)6910 unsigned long __init absent_pages_in_range(unsigned long start_pfn,
6911 unsigned long end_pfn)
6912 {
6913 return __absent_pages_in_range(MAX_NUMNODES, start_pfn, end_pfn);
6914 }
6915
6916 /* 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)6917 static unsigned long __init zone_absent_pages_in_node(int nid,
6918 unsigned long zone_type,
6919 unsigned long node_start_pfn,
6920 unsigned long node_end_pfn)
6921 {
6922 unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type];
6923 unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type];
6924 unsigned long zone_start_pfn, zone_end_pfn;
6925 unsigned long nr_absent;
6926
6927 /* When hotadd a new node from cpu_up(), the node should be empty */
6928 if (!node_start_pfn && !node_end_pfn)
6929 return 0;
6930
6931 zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high);
6932 zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high);
6933
6934 adjust_zone_range_for_zone_movable(nid, zone_type,
6935 node_start_pfn, node_end_pfn,
6936 &zone_start_pfn, &zone_end_pfn);
6937 nr_absent = __absent_pages_in_range(nid, zone_start_pfn, zone_end_pfn);
6938
6939 /*
6940 * ZONE_MOVABLE handling.
6941 * Treat pages to be ZONE_MOVABLE in ZONE_NORMAL as absent pages
6942 * and vice versa.
6943 */
6944 if (mirrored_kernelcore && zone_movable_pfn[nid]) {
6945 unsigned long start_pfn, end_pfn;
6946 struct memblock_region *r;
6947
6948 for_each_mem_region(r) {
6949 start_pfn = clamp(memblock_region_memory_base_pfn(r),
6950 zone_start_pfn, zone_end_pfn);
6951 end_pfn = clamp(memblock_region_memory_end_pfn(r),
6952 zone_start_pfn, zone_end_pfn);
6953
6954 if (zone_type == ZONE_MOVABLE &&
6955 memblock_is_mirror(r))
6956 nr_absent += end_pfn - start_pfn;
6957
6958 if (zone_type == ZONE_NORMAL &&
6959 !memblock_is_mirror(r))
6960 nr_absent += end_pfn - start_pfn;
6961 }
6962 }
6963
6964 return nr_absent;
6965 }
6966
calculate_node_totalpages(struct pglist_data * pgdat,unsigned long node_start_pfn,unsigned long node_end_pfn)6967 static void __init calculate_node_totalpages(struct pglist_data *pgdat,
6968 unsigned long node_start_pfn,
6969 unsigned long node_end_pfn)
6970 {
6971 unsigned long realtotalpages = 0, totalpages = 0;
6972 enum zone_type i;
6973
6974 for (i = 0; i < MAX_NR_ZONES; i++) {
6975 struct zone *zone = pgdat->node_zones + i;
6976 unsigned long zone_start_pfn, zone_end_pfn;
6977 unsigned long spanned, absent;
6978 unsigned long size, real_size;
6979
6980 spanned = zone_spanned_pages_in_node(pgdat->node_id, i,
6981 node_start_pfn,
6982 node_end_pfn,
6983 &zone_start_pfn,
6984 &zone_end_pfn);
6985 absent = zone_absent_pages_in_node(pgdat->node_id, i,
6986 node_start_pfn,
6987 node_end_pfn);
6988
6989 size = spanned;
6990 real_size = size - absent;
6991
6992 if (size)
6993 zone->zone_start_pfn = zone_start_pfn;
6994 else
6995 zone->zone_start_pfn = 0;
6996 zone->spanned_pages = size;
6997 zone->present_pages = real_size;
6998
6999 totalpages += size;
7000 realtotalpages += real_size;
7001 }
7002
7003 pgdat->node_spanned_pages = totalpages;
7004 pgdat->node_present_pages = realtotalpages;
7005 printk(KERN_DEBUG "On node %d totalpages: %lu\n", pgdat->node_id,
7006 realtotalpages);
7007 }
7008
7009 #ifndef CONFIG_SPARSEMEM
7010 /*
7011 * Calculate the size of the zone->blockflags rounded to an unsigned long
7012 * Start by making sure zonesize is a multiple of pageblock_order by rounding
7013 * up. Then use 1 NR_PAGEBLOCK_BITS worth of bits per pageblock, finally
7014 * round what is now in bits to nearest long in bits, then return it in
7015 * bytes.
7016 */
usemap_size(unsigned long zone_start_pfn,unsigned long zonesize)7017 static unsigned long __init usemap_size(unsigned long zone_start_pfn, unsigned long zonesize)
7018 {
7019 unsigned long usemapsize;
7020
7021 zonesize += zone_start_pfn & (pageblock_nr_pages-1);
7022 usemapsize = roundup(zonesize, pageblock_nr_pages);
7023 usemapsize = usemapsize >> pageblock_order;
7024 usemapsize *= NR_PAGEBLOCK_BITS;
7025 usemapsize = roundup(usemapsize, 8 * sizeof(unsigned long));
7026
7027 return usemapsize / 8;
7028 }
7029
setup_usemap(struct pglist_data * pgdat,struct zone * zone,unsigned long zone_start_pfn,unsigned long zonesize)7030 static void __ref setup_usemap(struct pglist_data *pgdat,
7031 struct zone *zone,
7032 unsigned long zone_start_pfn,
7033 unsigned long zonesize)
7034 {
7035 unsigned long usemapsize = usemap_size(zone_start_pfn, zonesize);
7036 zone->pageblock_flags = NULL;
7037 if (usemapsize) {
7038 zone->pageblock_flags =
7039 memblock_alloc_node(usemapsize, SMP_CACHE_BYTES,
7040 pgdat->node_id);
7041 if (!zone->pageblock_flags)
7042 panic("Failed to allocate %ld bytes for zone %s pageblock flags on node %d\n",
7043 usemapsize, zone->name, pgdat->node_id);
7044 }
7045 }
7046 #else
setup_usemap(struct pglist_data * pgdat,struct zone * zone,unsigned long zone_start_pfn,unsigned long zonesize)7047 static inline void setup_usemap(struct pglist_data *pgdat, struct zone *zone,
7048 unsigned long zone_start_pfn, unsigned long zonesize) {}
7049 #endif /* CONFIG_SPARSEMEM */
7050
7051 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
7052
7053 /* Initialise the number of pages represented by NR_PAGEBLOCK_BITS */
set_pageblock_order(void)7054 void __init set_pageblock_order(void)
7055 {
7056 unsigned int order;
7057
7058 /* Check that pageblock_nr_pages has not already been setup */
7059 if (pageblock_order)
7060 return;
7061
7062 if (HPAGE_SHIFT > PAGE_SHIFT)
7063 order = HUGETLB_PAGE_ORDER;
7064 else
7065 order = MAX_ORDER - 1;
7066
7067 /*
7068 * Assume the largest contiguous order of interest is a huge page.
7069 * This value may be variable depending on boot parameters on IA64 and
7070 * powerpc.
7071 */
7072 pageblock_order = order;
7073 }
7074 #else /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
7075
7076 /*
7077 * When CONFIG_HUGETLB_PAGE_SIZE_VARIABLE is not set, set_pageblock_order()
7078 * is unused as pageblock_order is set at compile-time. See
7079 * include/linux/pageblock-flags.h for the values of pageblock_order based on
7080 * the kernel config
7081 */
set_pageblock_order(void)7082 void __init set_pageblock_order(void)
7083 {
7084 }
7085
7086 #endif /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
7087
calc_memmap_size(unsigned long spanned_pages,unsigned long present_pages)7088 static unsigned long __init calc_memmap_size(unsigned long spanned_pages,
7089 unsigned long present_pages)
7090 {
7091 unsigned long pages = spanned_pages;
7092
7093 /*
7094 * Provide a more accurate estimation if there are holes within
7095 * the zone and SPARSEMEM is in use. If there are holes within the
7096 * zone, each populated memory region may cost us one or two extra
7097 * memmap pages due to alignment because memmap pages for each
7098 * populated regions may not be naturally aligned on page boundary.
7099 * So the (present_pages >> 4) heuristic is a tradeoff for that.
7100 */
7101 if (spanned_pages > present_pages + (present_pages >> 4) &&
7102 IS_ENABLED(CONFIG_SPARSEMEM))
7103 pages = present_pages;
7104
7105 return PAGE_ALIGN(pages * sizeof(struct page)) >> PAGE_SHIFT;
7106 }
7107
7108 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
pgdat_init_split_queue(struct pglist_data * pgdat)7109 static void pgdat_init_split_queue(struct pglist_data *pgdat)
7110 {
7111 struct deferred_split *ds_queue = &pgdat->deferred_split_queue;
7112
7113 spin_lock_init(&ds_queue->split_queue_lock);
7114 INIT_LIST_HEAD(&ds_queue->split_queue);
7115 ds_queue->split_queue_len = 0;
7116 }
7117 #else
pgdat_init_split_queue(struct pglist_data * pgdat)7118 static void pgdat_init_split_queue(struct pglist_data *pgdat) {}
7119 #endif
7120
7121 #ifdef CONFIG_COMPACTION
pgdat_init_kcompactd(struct pglist_data * pgdat)7122 static void pgdat_init_kcompactd(struct pglist_data *pgdat)
7123 {
7124 init_waitqueue_head(&pgdat->kcompactd_wait);
7125 }
7126 #else
pgdat_init_kcompactd(struct pglist_data * pgdat)7127 static void pgdat_init_kcompactd(struct pglist_data *pgdat) {}
7128 #endif
7129
pgdat_init_internals(struct pglist_data * pgdat)7130 static void __meminit pgdat_init_internals(struct pglist_data *pgdat)
7131 {
7132 pgdat_resize_init(pgdat);
7133
7134 pgdat_init_split_queue(pgdat);
7135 pgdat_init_kcompactd(pgdat);
7136
7137 init_waitqueue_head(&pgdat->kswapd_wait);
7138 init_waitqueue_head(&pgdat->pfmemalloc_wait);
7139
7140 pgdat_page_ext_init(pgdat);
7141 spin_lock_init(&pgdat->lru_lock);
7142 lruvec_init(&pgdat->__lruvec);
7143 }
7144
zone_init_internals(struct zone * zone,enum zone_type idx,int nid,unsigned long remaining_pages)7145 static void __meminit zone_init_internals(struct zone *zone, enum zone_type idx, int nid,
7146 unsigned long remaining_pages)
7147 {
7148 atomic_long_set(&zone->managed_pages, remaining_pages);
7149 zone_set_nid(zone, nid);
7150 zone->name = zone_names[idx];
7151 zone->zone_pgdat = NODE_DATA(nid);
7152 spin_lock_init(&zone->lock);
7153 zone_seqlock_init(zone);
7154 zone_pcp_init(zone);
7155 }
7156
7157 /*
7158 * Set up the zone data structures
7159 * - init pgdat internals
7160 * - init all zones belonging to this node
7161 *
7162 * NOTE: this function is only called during memory hotplug
7163 */
7164 #ifdef CONFIG_MEMORY_HOTPLUG
free_area_init_core_hotplug(int nid)7165 void __ref free_area_init_core_hotplug(int nid)
7166 {
7167 enum zone_type z;
7168 pg_data_t *pgdat = NODE_DATA(nid);
7169
7170 pgdat_init_internals(pgdat);
7171 for (z = 0; z < MAX_NR_ZONES; z++)
7172 zone_init_internals(&pgdat->node_zones[z], z, nid, 0);
7173 }
7174 #endif
7175
7176 /*
7177 * Set up the zone data structures:
7178 * - mark all pages reserved
7179 * - mark all memory queues empty
7180 * - clear the memory bitmaps
7181 *
7182 * NOTE: pgdat should get zeroed by caller.
7183 * NOTE: this function is only called during early init.
7184 */
free_area_init_core(struct pglist_data * pgdat)7185 static void __init free_area_init_core(struct pglist_data *pgdat)
7186 {
7187 enum zone_type j;
7188 int nid = pgdat->node_id;
7189
7190 pgdat_init_internals(pgdat);
7191 pgdat->per_cpu_nodestats = &boot_nodestats;
7192
7193 for (j = 0; j < MAX_NR_ZONES; j++) {
7194 struct zone *zone = pgdat->node_zones + j;
7195 unsigned long size, freesize, memmap_pages;
7196 unsigned long zone_start_pfn = zone->zone_start_pfn;
7197
7198 size = zone->spanned_pages;
7199 freesize = zone->present_pages;
7200
7201 /*
7202 * Adjust freesize so that it accounts for how much memory
7203 * is used by this zone for memmap. This affects the watermark
7204 * and per-cpu initialisations
7205 */
7206 memmap_pages = calc_memmap_size(size, freesize);
7207 if (!is_highmem_idx(j)) {
7208 if (freesize >= memmap_pages) {
7209 freesize -= memmap_pages;
7210 if (memmap_pages)
7211 printk(KERN_DEBUG
7212 " %s zone: %lu pages used for memmap\n",
7213 zone_names[j], memmap_pages);
7214 } else
7215 pr_warn(" %s zone: %lu pages exceeds freesize %lu\n",
7216 zone_names[j], memmap_pages, freesize);
7217 }
7218
7219 /* Account for reserved pages */
7220 if (j == 0 && freesize > dma_reserve) {
7221 freesize -= dma_reserve;
7222 printk(KERN_DEBUG " %s zone: %lu pages reserved\n",
7223 zone_names[0], dma_reserve);
7224 }
7225
7226 if (!is_highmem_idx(j))
7227 nr_kernel_pages += freesize;
7228 /* Charge for highmem memmap if there are enough kernel pages */
7229 else if (nr_kernel_pages > memmap_pages * 2)
7230 nr_kernel_pages -= memmap_pages;
7231 nr_all_pages += freesize;
7232
7233 /*
7234 * Set an approximate value for lowmem here, it will be adjusted
7235 * when the bootmem allocator frees pages into the buddy system.
7236 * And all highmem pages will be managed by the buddy system.
7237 */
7238 zone_init_internals(zone, j, nid, freesize);
7239
7240 if (!size)
7241 continue;
7242
7243 set_pageblock_order();
7244 setup_usemap(pgdat, zone, zone_start_pfn, size);
7245 init_currently_empty_zone(zone, zone_start_pfn, size);
7246 arch_memmap_init(size, nid, j, zone_start_pfn);
7247 }
7248 }
7249
7250 #ifdef CONFIG_FLAT_NODE_MEM_MAP
alloc_node_mem_map(struct pglist_data * pgdat)7251 static void __ref alloc_node_mem_map(struct pglist_data *pgdat)
7252 {
7253 unsigned long __maybe_unused start = 0;
7254 unsigned long __maybe_unused offset = 0;
7255
7256 /* Skip empty nodes */
7257 if (!pgdat->node_spanned_pages)
7258 return;
7259
7260 start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1);
7261 offset = pgdat->node_start_pfn - start;
7262 /* ia64 gets its own node_mem_map, before this, without bootmem */
7263 if (!pgdat->node_mem_map) {
7264 unsigned long size, end;
7265 struct page *map;
7266
7267 /*
7268 * The zone's endpoints aren't required to be MAX_ORDER
7269 * aligned but the node_mem_map endpoints must be in order
7270 * for the buddy allocator to function correctly.
7271 */
7272 end = pgdat_end_pfn(pgdat);
7273 end = ALIGN(end, MAX_ORDER_NR_PAGES);
7274 size = (end - start) * sizeof(struct page);
7275 map = memblock_alloc_node(size, SMP_CACHE_BYTES,
7276 pgdat->node_id);
7277 if (!map)
7278 panic("Failed to allocate %ld bytes for node %d memory map\n",
7279 size, pgdat->node_id);
7280 pgdat->node_mem_map = map + offset;
7281 }
7282 pr_debug("%s: node %d, pgdat %08lx, node_mem_map %08lx\n",
7283 __func__, pgdat->node_id, (unsigned long)pgdat,
7284 (unsigned long)pgdat->node_mem_map);
7285 #ifndef CONFIG_NEED_MULTIPLE_NODES
7286 /*
7287 * With no DISCONTIG, the global mem_map is just set as node 0's
7288 */
7289 if (pgdat == NODE_DATA(0)) {
7290 mem_map = NODE_DATA(0)->node_mem_map;
7291 if (page_to_pfn(mem_map) != pgdat->node_start_pfn)
7292 mem_map -= offset;
7293 }
7294 #endif
7295 }
7296 #else
alloc_node_mem_map(struct pglist_data * pgdat)7297 static void __ref alloc_node_mem_map(struct pglist_data *pgdat) { }
7298 #endif /* CONFIG_FLAT_NODE_MEM_MAP */
7299
7300 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
pgdat_set_deferred_range(pg_data_t * pgdat)7301 static inline void pgdat_set_deferred_range(pg_data_t *pgdat)
7302 {
7303 pgdat->first_deferred_pfn = ULONG_MAX;
7304 }
7305 #else
pgdat_set_deferred_range(pg_data_t * pgdat)7306 static inline void pgdat_set_deferred_range(pg_data_t *pgdat) {}
7307 #endif
7308
free_area_init_node(int nid)7309 static void __init free_area_init_node(int nid)
7310 {
7311 pg_data_t *pgdat = NODE_DATA(nid);
7312 unsigned long start_pfn = 0;
7313 unsigned long end_pfn = 0;
7314
7315 /* pg_data_t should be reset to zero when it's allocated */
7316 WARN_ON(pgdat->nr_zones || pgdat->kswapd_highest_zoneidx);
7317
7318 get_pfn_range_for_nid(nid, &start_pfn, &end_pfn);
7319
7320 pgdat->node_id = nid;
7321 pgdat->node_start_pfn = start_pfn;
7322 pgdat->per_cpu_nodestats = NULL;
7323
7324 pr_info("Initmem setup node %d [mem %#018Lx-%#018Lx]\n", nid,
7325 (u64)start_pfn << PAGE_SHIFT,
7326 end_pfn ? ((u64)end_pfn << PAGE_SHIFT) - 1 : 0);
7327 calculate_node_totalpages(pgdat, start_pfn, end_pfn);
7328
7329 alloc_node_mem_map(pgdat);
7330 pgdat_set_deferred_range(pgdat);
7331
7332 free_area_init_core(pgdat);
7333 }
7334
free_area_init_memoryless_node(int nid)7335 void __init free_area_init_memoryless_node(int nid)
7336 {
7337 free_area_init_node(nid);
7338 }
7339
7340 #if MAX_NUMNODES > 1
7341 /*
7342 * Figure out the number of possible node ids.
7343 */
setup_nr_node_ids(void)7344 void __init setup_nr_node_ids(void)
7345 {
7346 unsigned int highest;
7347
7348 highest = find_last_bit(node_possible_map.bits, MAX_NUMNODES);
7349 nr_node_ids = highest + 1;
7350 }
7351 #endif
7352
7353 /**
7354 * node_map_pfn_alignment - determine the maximum internode alignment
7355 *
7356 * This function should be called after node map is populated and sorted.
7357 * It calculates the maximum power of two alignment which can distinguish
7358 * all the nodes.
7359 *
7360 * For example, if all nodes are 1GiB and aligned to 1GiB, the return value
7361 * would indicate 1GiB alignment with (1 << (30 - PAGE_SHIFT)). If the
7362 * nodes are shifted by 256MiB, 256MiB. Note that if only the last node is
7363 * shifted, 1GiB is enough and this function will indicate so.
7364 *
7365 * This is used to test whether pfn -> nid mapping of the chosen memory
7366 * model has fine enough granularity to avoid incorrect mapping for the
7367 * populated node map.
7368 *
7369 * Return: the determined alignment in pfn's. 0 if there is no alignment
7370 * requirement (single node).
7371 */
node_map_pfn_alignment(void)7372 unsigned long __init node_map_pfn_alignment(void)
7373 {
7374 unsigned long accl_mask = 0, last_end = 0;
7375 unsigned long start, end, mask;
7376 int last_nid = NUMA_NO_NODE;
7377 int i, nid;
7378
7379 for_each_mem_pfn_range(i, MAX_NUMNODES, &start, &end, &nid) {
7380 if (!start || last_nid < 0 || last_nid == nid) {
7381 last_nid = nid;
7382 last_end = end;
7383 continue;
7384 }
7385
7386 /*
7387 * Start with a mask granular enough to pin-point to the
7388 * start pfn and tick off bits one-by-one until it becomes
7389 * too coarse to separate the current node from the last.
7390 */
7391 mask = ~((1 << __ffs(start)) - 1);
7392 while (mask && last_end <= (start & (mask << 1)))
7393 mask <<= 1;
7394
7395 /* accumulate all internode masks */
7396 accl_mask |= mask;
7397 }
7398
7399 /* convert mask to number of pages */
7400 return ~accl_mask + 1;
7401 }
7402
7403 /**
7404 * find_min_pfn_with_active_regions - Find the minimum PFN registered
7405 *
7406 * Return: the minimum PFN based on information provided via
7407 * memblock_set_node().
7408 */
find_min_pfn_with_active_regions(void)7409 unsigned long __init find_min_pfn_with_active_regions(void)
7410 {
7411 return PHYS_PFN(memblock_start_of_DRAM());
7412 }
7413
7414 /*
7415 * early_calculate_totalpages()
7416 * Sum pages in active regions for movable zone.
7417 * Populate N_MEMORY for calculating usable_nodes.
7418 */
early_calculate_totalpages(void)7419 static unsigned long __init early_calculate_totalpages(void)
7420 {
7421 unsigned long totalpages = 0;
7422 unsigned long start_pfn, end_pfn;
7423 int i, nid;
7424
7425 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
7426 unsigned long pages = end_pfn - start_pfn;
7427
7428 totalpages += pages;
7429 if (pages)
7430 node_set_state(nid, N_MEMORY);
7431 }
7432 return totalpages;
7433 }
7434
7435 /*
7436 * Find the PFN the Movable zone begins in each node. Kernel memory
7437 * is spread evenly between nodes as long as the nodes have enough
7438 * memory. When they don't, some nodes will have more kernelcore than
7439 * others
7440 */
find_zone_movable_pfns_for_nodes(void)7441 static void __init find_zone_movable_pfns_for_nodes(void)
7442 {
7443 int i, nid;
7444 unsigned long usable_startpfn;
7445 unsigned long kernelcore_node, kernelcore_remaining;
7446 /* save the state before borrow the nodemask */
7447 nodemask_t saved_node_state = node_states[N_MEMORY];
7448 unsigned long totalpages = early_calculate_totalpages();
7449 int usable_nodes = nodes_weight(node_states[N_MEMORY]);
7450 struct memblock_region *r;
7451
7452 /* Need to find movable_zone earlier when movable_node is specified. */
7453 find_usable_zone_for_movable();
7454
7455 /*
7456 * If movable_node is specified, ignore kernelcore and movablecore
7457 * options.
7458 */
7459 if (movable_node_is_enabled()) {
7460 for_each_mem_region(r) {
7461 if (!memblock_is_hotpluggable(r))
7462 continue;
7463
7464 nid = memblock_get_region_node(r);
7465
7466 usable_startpfn = PFN_DOWN(r->base);
7467 zone_movable_pfn[nid] = zone_movable_pfn[nid] ?
7468 min(usable_startpfn, zone_movable_pfn[nid]) :
7469 usable_startpfn;
7470 }
7471
7472 goto out2;
7473 }
7474
7475 /*
7476 * If kernelcore=mirror is specified, ignore movablecore option
7477 */
7478 if (mirrored_kernelcore) {
7479 bool mem_below_4gb_not_mirrored = false;
7480
7481 for_each_mem_region(r) {
7482 if (memblock_is_mirror(r))
7483 continue;
7484
7485 nid = memblock_get_region_node(r);
7486
7487 usable_startpfn = memblock_region_memory_base_pfn(r);
7488
7489 if (usable_startpfn < 0x100000) {
7490 mem_below_4gb_not_mirrored = true;
7491 continue;
7492 }
7493
7494 zone_movable_pfn[nid] = zone_movable_pfn[nid] ?
7495 min(usable_startpfn, zone_movable_pfn[nid]) :
7496 usable_startpfn;
7497 }
7498
7499 if (mem_below_4gb_not_mirrored)
7500 pr_warn("This configuration results in unmirrored kernel memory.\n");
7501
7502 goto out2;
7503 }
7504
7505 /*
7506 * If kernelcore=nn% or movablecore=nn% was specified, calculate the
7507 * amount of necessary memory.
7508 */
7509 if (required_kernelcore_percent)
7510 required_kernelcore = (totalpages * 100 * required_kernelcore_percent) /
7511 10000UL;
7512 if (required_movablecore_percent)
7513 required_movablecore = (totalpages * 100 * required_movablecore_percent) /
7514 10000UL;
7515
7516 /*
7517 * If movablecore= was specified, calculate what size of
7518 * kernelcore that corresponds so that memory usable for
7519 * any allocation type is evenly spread. If both kernelcore
7520 * and movablecore are specified, then the value of kernelcore
7521 * will be used for required_kernelcore if it's greater than
7522 * what movablecore would have allowed.
7523 */
7524 if (required_movablecore) {
7525 unsigned long corepages;
7526
7527 /*
7528 * Round-up so that ZONE_MOVABLE is at least as large as what
7529 * was requested by the user
7530 */
7531 required_movablecore =
7532 roundup(required_movablecore, MAX_ORDER_NR_PAGES);
7533 required_movablecore = min(totalpages, required_movablecore);
7534 corepages = totalpages - required_movablecore;
7535
7536 required_kernelcore = max(required_kernelcore, corepages);
7537 }
7538
7539 /*
7540 * If kernelcore was not specified or kernelcore size is larger
7541 * than totalpages, there is no ZONE_MOVABLE.
7542 */
7543 if (!required_kernelcore || required_kernelcore >= totalpages)
7544 goto out;
7545
7546 /* usable_startpfn is the lowest possible pfn ZONE_MOVABLE can be at */
7547 usable_startpfn = arch_zone_lowest_possible_pfn[movable_zone];
7548
7549 restart:
7550 /* Spread kernelcore memory as evenly as possible throughout nodes */
7551 kernelcore_node = required_kernelcore / usable_nodes;
7552 for_each_node_state(nid, N_MEMORY) {
7553 unsigned long start_pfn, end_pfn;
7554
7555 /*
7556 * Recalculate kernelcore_node if the division per node
7557 * now exceeds what is necessary to satisfy the requested
7558 * amount of memory for the kernel
7559 */
7560 if (required_kernelcore < kernelcore_node)
7561 kernelcore_node = required_kernelcore / usable_nodes;
7562
7563 /*
7564 * As the map is walked, we track how much memory is usable
7565 * by the kernel using kernelcore_remaining. When it is
7566 * 0, the rest of the node is usable by ZONE_MOVABLE
7567 */
7568 kernelcore_remaining = kernelcore_node;
7569
7570 /* Go through each range of PFNs within this node */
7571 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
7572 unsigned long size_pages;
7573
7574 start_pfn = max(start_pfn, zone_movable_pfn[nid]);
7575 if (start_pfn >= end_pfn)
7576 continue;
7577
7578 /* Account for what is only usable for kernelcore */
7579 if (start_pfn < usable_startpfn) {
7580 unsigned long kernel_pages;
7581 kernel_pages = min(end_pfn, usable_startpfn)
7582 - start_pfn;
7583
7584 kernelcore_remaining -= min(kernel_pages,
7585 kernelcore_remaining);
7586 required_kernelcore -= min(kernel_pages,
7587 required_kernelcore);
7588
7589 /* Continue if range is now fully accounted */
7590 if (end_pfn <= usable_startpfn) {
7591
7592 /*
7593 * Push zone_movable_pfn to the end so
7594 * that if we have to rebalance
7595 * kernelcore across nodes, we will
7596 * not double account here
7597 */
7598 zone_movable_pfn[nid] = end_pfn;
7599 continue;
7600 }
7601 start_pfn = usable_startpfn;
7602 }
7603
7604 /*
7605 * The usable PFN range for ZONE_MOVABLE is from
7606 * start_pfn->end_pfn. Calculate size_pages as the
7607 * number of pages used as kernelcore
7608 */
7609 size_pages = end_pfn - start_pfn;
7610 if (size_pages > kernelcore_remaining)
7611 size_pages = kernelcore_remaining;
7612 zone_movable_pfn[nid] = start_pfn + size_pages;
7613
7614 /*
7615 * Some kernelcore has been met, update counts and
7616 * break if the kernelcore for this node has been
7617 * satisfied
7618 */
7619 required_kernelcore -= min(required_kernelcore,
7620 size_pages);
7621 kernelcore_remaining -= size_pages;
7622 if (!kernelcore_remaining)
7623 break;
7624 }
7625 }
7626
7627 /*
7628 * If there is still required_kernelcore, we do another pass with one
7629 * less node in the count. This will push zone_movable_pfn[nid] further
7630 * along on the nodes that still have memory until kernelcore is
7631 * satisfied
7632 */
7633 usable_nodes--;
7634 if (usable_nodes && required_kernelcore > usable_nodes)
7635 goto restart;
7636
7637 out2:
7638 /* Align start of ZONE_MOVABLE on all nids to MAX_ORDER_NR_PAGES */
7639 for (nid = 0; nid < MAX_NUMNODES; nid++) {
7640 unsigned long start_pfn, end_pfn;
7641
7642 zone_movable_pfn[nid] =
7643 roundup(zone_movable_pfn[nid], MAX_ORDER_NR_PAGES);
7644
7645 get_pfn_range_for_nid(nid, &start_pfn, &end_pfn);
7646 if (zone_movable_pfn[nid] >= end_pfn)
7647 zone_movable_pfn[nid] = 0;
7648 }
7649
7650 out:
7651 /* restore the node_state */
7652 node_states[N_MEMORY] = saved_node_state;
7653 }
7654
7655 /* Any regular or high memory on that node ? */
check_for_memory(pg_data_t * pgdat,int nid)7656 static void check_for_memory(pg_data_t *pgdat, int nid)
7657 {
7658 enum zone_type zone_type;
7659
7660 for (zone_type = 0; zone_type <= ZONE_MOVABLE - 1; zone_type++) {
7661 struct zone *zone = &pgdat->node_zones[zone_type];
7662 if (populated_zone(zone)) {
7663 if (IS_ENABLED(CONFIG_HIGHMEM))
7664 node_set_state(nid, N_HIGH_MEMORY);
7665 if (zone_type <= ZONE_NORMAL)
7666 node_set_state(nid, N_NORMAL_MEMORY);
7667 break;
7668 }
7669 }
7670 }
7671
7672 /*
7673 * Some architecturs, e.g. ARC may have ZONE_HIGHMEM below ZONE_NORMAL. For
7674 * such cases we allow max_zone_pfn sorted in the descending order
7675 */
arch_has_descending_max_zone_pfns(void)7676 bool __weak arch_has_descending_max_zone_pfns(void)
7677 {
7678 return false;
7679 }
7680
7681 /**
7682 * free_area_init - Initialise all pg_data_t and zone data
7683 * @max_zone_pfn: an array of max PFNs for each zone
7684 *
7685 * This will call free_area_init_node() for each active node in the system.
7686 * Using the page ranges provided by memblock_set_node(), the size of each
7687 * zone in each node and their holes is calculated. If the maximum PFN
7688 * between two adjacent zones match, it is assumed that the zone is empty.
7689 * For example, if arch_max_dma_pfn == arch_max_dma32_pfn, it is assumed
7690 * that arch_max_dma32_pfn has no pages. It is also assumed that a zone
7691 * starts where the previous one ended. For example, ZONE_DMA32 starts
7692 * at arch_max_dma_pfn.
7693 */
free_area_init(unsigned long * max_zone_pfn)7694 void __init free_area_init(unsigned long *max_zone_pfn)
7695 {
7696 unsigned long start_pfn, end_pfn;
7697 int i, nid, zone;
7698 bool descending;
7699
7700 /* Record where the zone boundaries are */
7701 memset(arch_zone_lowest_possible_pfn, 0,
7702 sizeof(arch_zone_lowest_possible_pfn));
7703 memset(arch_zone_highest_possible_pfn, 0,
7704 sizeof(arch_zone_highest_possible_pfn));
7705
7706 start_pfn = find_min_pfn_with_active_regions();
7707 descending = arch_has_descending_max_zone_pfns();
7708
7709 for (i = 0; i < MAX_NR_ZONES; i++) {
7710 if (descending)
7711 zone = MAX_NR_ZONES - i - 1;
7712 else
7713 zone = i;
7714
7715 if (zone == ZONE_MOVABLE)
7716 continue;
7717
7718 end_pfn = max(max_zone_pfn[zone], start_pfn);
7719 arch_zone_lowest_possible_pfn[zone] = start_pfn;
7720 arch_zone_highest_possible_pfn[zone] = end_pfn;
7721
7722 start_pfn = end_pfn;
7723 }
7724
7725 /* Find the PFNs that ZONE_MOVABLE begins at in each node */
7726 memset(zone_movable_pfn, 0, sizeof(zone_movable_pfn));
7727 find_zone_movable_pfns_for_nodes();
7728
7729 /* Print out the zone ranges */
7730 pr_info("Zone ranges:\n");
7731 for (i = 0; i < MAX_NR_ZONES; i++) {
7732 if (i == ZONE_MOVABLE)
7733 continue;
7734 pr_info(" %-8s ", zone_names[i]);
7735 if (arch_zone_lowest_possible_pfn[i] ==
7736 arch_zone_highest_possible_pfn[i])
7737 pr_cont("empty\n");
7738 else
7739 pr_cont("[mem %#018Lx-%#018Lx]\n",
7740 (u64)arch_zone_lowest_possible_pfn[i]
7741 << PAGE_SHIFT,
7742 ((u64)arch_zone_highest_possible_pfn[i]
7743 << PAGE_SHIFT) - 1);
7744 }
7745
7746 /* Print out the PFNs ZONE_MOVABLE begins at in each node */
7747 pr_info("Movable zone start for each node\n");
7748 for (i = 0; i < MAX_NUMNODES; i++) {
7749 if (zone_movable_pfn[i])
7750 pr_info(" Node %d: %#018Lx\n", i,
7751 (u64)zone_movable_pfn[i] << PAGE_SHIFT);
7752 }
7753
7754 /*
7755 * Print out the early node map, and initialize the
7756 * subsection-map relative to active online memory ranges to
7757 * enable future "sub-section" extensions of the memory map.
7758 */
7759 pr_info("Early memory node ranges\n");
7760 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
7761 pr_info(" node %3d: [mem %#018Lx-%#018Lx]\n", nid,
7762 (u64)start_pfn << PAGE_SHIFT,
7763 ((u64)end_pfn << PAGE_SHIFT) - 1);
7764 subsection_map_init(start_pfn, end_pfn - start_pfn);
7765 }
7766
7767 /* Initialise every node */
7768 mminit_verify_pageflags_layout();
7769 setup_nr_node_ids();
7770 for_each_online_node(nid) {
7771 pg_data_t *pgdat = NODE_DATA(nid);
7772 free_area_init_node(nid);
7773
7774 /* Any memory on that node */
7775 if (pgdat->node_present_pages)
7776 node_set_state(nid, N_MEMORY);
7777 check_for_memory(pgdat, nid);
7778 }
7779
7780 memmap_init();
7781 }
7782
cmdline_parse_core(char * p,unsigned long * core,unsigned long * percent)7783 static int __init cmdline_parse_core(char *p, unsigned long *core,
7784 unsigned long *percent)
7785 {
7786 unsigned long long coremem;
7787 char *endptr;
7788
7789 if (!p)
7790 return -EINVAL;
7791
7792 /* Value may be a percentage of total memory, otherwise bytes */
7793 coremem = simple_strtoull(p, &endptr, 0);
7794 if (*endptr == '%') {
7795 /* Paranoid check for percent values greater than 100 */
7796 WARN_ON(coremem > 100);
7797
7798 *percent = coremem;
7799 } else {
7800 coremem = memparse(p, &p);
7801 /* Paranoid check that UL is enough for the coremem value */
7802 WARN_ON((coremem >> PAGE_SHIFT) > ULONG_MAX);
7803
7804 *core = coremem >> PAGE_SHIFT;
7805 *percent = 0UL;
7806 }
7807 return 0;
7808 }
7809
7810 /*
7811 * kernelcore=size sets the amount of memory for use for allocations that
7812 * cannot be reclaimed or migrated.
7813 */
cmdline_parse_kernelcore(char * p)7814 static int __init cmdline_parse_kernelcore(char *p)
7815 {
7816 /* parse kernelcore=mirror */
7817 if (parse_option_str(p, "mirror")) {
7818 mirrored_kernelcore = true;
7819 return 0;
7820 }
7821
7822 return cmdline_parse_core(p, &required_kernelcore,
7823 &required_kernelcore_percent);
7824 }
7825
7826 /*
7827 * movablecore=size sets the amount of memory for use for allocations that
7828 * can be reclaimed or migrated.
7829 */
cmdline_parse_movablecore(char * p)7830 static int __init cmdline_parse_movablecore(char *p)
7831 {
7832 return cmdline_parse_core(p, &required_movablecore,
7833 &required_movablecore_percent);
7834 }
7835
7836 early_param("kernelcore", cmdline_parse_kernelcore);
7837 early_param("movablecore", cmdline_parse_movablecore);
7838
adjust_managed_page_count(struct page * page,long count)7839 void adjust_managed_page_count(struct page *page, long count)
7840 {
7841 atomic_long_add(count, &page_zone(page)->managed_pages);
7842 totalram_pages_add(count);
7843 #ifdef CONFIG_HIGHMEM
7844 if (PageHighMem(page))
7845 totalhigh_pages_add(count);
7846 #endif
7847 }
7848 EXPORT_SYMBOL(adjust_managed_page_count);
7849
free_reserved_area(void * start,void * end,int poison,const char * s)7850 unsigned long free_reserved_area(void *start, void *end, int poison, const char *s)
7851 {
7852 void *pos;
7853 unsigned long pages = 0;
7854
7855 start = (void *)PAGE_ALIGN((unsigned long)start);
7856 end = (void *)((unsigned long)end & PAGE_MASK);
7857 for (pos = start; pos < end; pos += PAGE_SIZE, pages++) {
7858 struct page *page = virt_to_page(pos);
7859 void *direct_map_addr;
7860
7861 /*
7862 * 'direct_map_addr' might be different from 'pos'
7863 * because some architectures' virt_to_page()
7864 * work with aliases. Getting the direct map
7865 * address ensures that we get a _writeable_
7866 * alias for the memset().
7867 */
7868 direct_map_addr = page_address(page);
7869 /*
7870 * Perform a kasan-unchecked memset() since this memory
7871 * has not been initialized.
7872 */
7873 direct_map_addr = kasan_reset_tag(direct_map_addr);
7874 if ((unsigned int)poison <= 0xFF)
7875 memset(direct_map_addr, poison, PAGE_SIZE);
7876
7877 free_reserved_page(page);
7878 }
7879
7880 if (pages && s)
7881 pr_info("Freeing %s memory: %ldK\n",
7882 s, pages << (PAGE_SHIFT - 10));
7883
7884 return pages;
7885 }
7886
7887 #ifdef CONFIG_HIGHMEM
free_highmem_page(struct page * page)7888 void free_highmem_page(struct page *page)
7889 {
7890 __free_reserved_page(page);
7891 totalram_pages_inc();
7892 atomic_long_inc(&page_zone(page)->managed_pages);
7893 totalhigh_pages_inc();
7894 }
7895 #endif
7896
7897
mem_init_print_info(const char * str)7898 void __init mem_init_print_info(const char *str)
7899 {
7900 unsigned long physpages, codesize, datasize, rosize, bss_size;
7901 unsigned long init_code_size, init_data_size;
7902
7903 physpages = get_num_physpages();
7904 codesize = _etext - _stext;
7905 datasize = _edata - _sdata;
7906 rosize = __end_rodata - __start_rodata;
7907 bss_size = __bss_stop - __bss_start;
7908 init_data_size = __init_end - __init_begin;
7909 init_code_size = _einittext - _sinittext;
7910
7911 /*
7912 * Detect special cases and adjust section sizes accordingly:
7913 * 1) .init.* may be embedded into .data sections
7914 * 2) .init.text.* may be out of [__init_begin, __init_end],
7915 * please refer to arch/tile/kernel/vmlinux.lds.S.
7916 * 3) .rodata.* may be embedded into .text or .data sections.
7917 */
7918 #define adj_init_size(start, end, size, pos, adj) \
7919 do { \
7920 if (&start[0] <= &pos[0] && &pos[0] < &end[0] && size > adj) \
7921 size -= adj; \
7922 } while (0)
7923
7924 adj_init_size(__init_begin, __init_end, init_data_size,
7925 _sinittext, init_code_size);
7926 adj_init_size(_stext, _etext, codesize, _sinittext, init_code_size);
7927 adj_init_size(_sdata, _edata, datasize, __init_begin, init_data_size);
7928 adj_init_size(_stext, _etext, codesize, __start_rodata, rosize);
7929 adj_init_size(_sdata, _edata, datasize, __start_rodata, rosize);
7930
7931 #undef adj_init_size
7932
7933 pr_info("Memory: %luK/%luK available (%luK kernel code, %luK rwdata, %luK rodata, %luK init, %luK bss, %luK reserved, %luK cma-reserved"
7934 #ifdef CONFIG_HIGHMEM
7935 ", %luK highmem"
7936 #endif
7937 "%s%s)\n",
7938 nr_free_pages() << (PAGE_SHIFT - 10),
7939 physpages << (PAGE_SHIFT - 10),
7940 codesize >> 10, datasize >> 10, rosize >> 10,
7941 (init_data_size + init_code_size) >> 10, bss_size >> 10,
7942 (physpages - totalram_pages() - totalcma_pages) << (PAGE_SHIFT - 10),
7943 totalcma_pages << (PAGE_SHIFT - 10),
7944 #ifdef CONFIG_HIGHMEM
7945 totalhigh_pages() << (PAGE_SHIFT - 10),
7946 #endif
7947 str ? ", " : "", str ? str : "");
7948 }
7949
7950 /**
7951 * set_dma_reserve - set the specified number of pages reserved in the first zone
7952 * @new_dma_reserve: The number of pages to mark reserved
7953 *
7954 * The per-cpu batchsize and zone watermarks are determined by managed_pages.
7955 * In the DMA zone, a significant percentage may be consumed by kernel image
7956 * and other unfreeable allocations which can skew the watermarks badly. This
7957 * function may optionally be used to account for unfreeable pages in the
7958 * first zone (e.g., ZONE_DMA). The effect will be lower watermarks and
7959 * smaller per-cpu batchsize.
7960 */
set_dma_reserve(unsigned long new_dma_reserve)7961 void __init set_dma_reserve(unsigned long new_dma_reserve)
7962 {
7963 dma_reserve = new_dma_reserve;
7964 }
7965
page_alloc_cpu_dead(unsigned int cpu)7966 static int page_alloc_cpu_dead(unsigned int cpu)
7967 {
7968
7969 lru_add_drain_cpu(cpu);
7970 drain_pages(cpu);
7971
7972 /*
7973 * Spill the event counters of the dead processor
7974 * into the current processors event counters.
7975 * This artificially elevates the count of the current
7976 * processor.
7977 */
7978 vm_events_fold_cpu(cpu);
7979
7980 /*
7981 * Zero the differential counters of the dead processor
7982 * so that the vm statistics are consistent.
7983 *
7984 * This is only okay since the processor is dead and cannot
7985 * race with what we are doing.
7986 */
7987 cpu_vm_stats_fold(cpu);
7988 return 0;
7989 }
7990
7991 #ifdef CONFIG_NUMA
7992 int hashdist = HASHDIST_DEFAULT;
7993
set_hashdist(char * str)7994 static int __init set_hashdist(char *str)
7995 {
7996 if (!str)
7997 return 0;
7998 hashdist = simple_strtoul(str, &str, 0);
7999 return 1;
8000 }
8001 __setup("hashdist=", set_hashdist);
8002 #endif
8003
page_alloc_init(void)8004 void __init page_alloc_init(void)
8005 {
8006 int ret;
8007
8008 #ifdef CONFIG_NUMA
8009 if (num_node_state(N_MEMORY) == 1)
8010 hashdist = 0;
8011 #endif
8012
8013 ret = cpuhp_setup_state_nocalls(CPUHP_PAGE_ALLOC_DEAD,
8014 "mm/page_alloc:dead", NULL,
8015 page_alloc_cpu_dead);
8016 WARN_ON(ret < 0);
8017 }
8018
8019 /*
8020 * calculate_totalreserve_pages - called when sysctl_lowmem_reserve_ratio
8021 * or min_free_kbytes changes.
8022 */
calculate_totalreserve_pages(void)8023 static void calculate_totalreserve_pages(void)
8024 {
8025 struct pglist_data *pgdat;
8026 unsigned long reserve_pages = 0;
8027 enum zone_type i, j;
8028
8029 for_each_online_pgdat(pgdat) {
8030
8031 pgdat->totalreserve_pages = 0;
8032
8033 for (i = 0; i < MAX_NR_ZONES; i++) {
8034 struct zone *zone = pgdat->node_zones + i;
8035 long max = 0;
8036 unsigned long managed_pages = zone_managed_pages(zone);
8037
8038 /* Find valid and maximum lowmem_reserve in the zone */
8039 for (j = i; j < MAX_NR_ZONES; j++) {
8040 if (zone->lowmem_reserve[j] > max)
8041 max = zone->lowmem_reserve[j];
8042 }
8043
8044 /* we treat the high watermark as reserved pages. */
8045 max += high_wmark_pages(zone);
8046
8047 if (max > managed_pages)
8048 max = managed_pages;
8049
8050 pgdat->totalreserve_pages += max;
8051
8052 reserve_pages += max;
8053 }
8054 }
8055 totalreserve_pages = reserve_pages;
8056 }
8057
8058 /*
8059 * setup_per_zone_lowmem_reserve - called whenever
8060 * sysctl_lowmem_reserve_ratio changes. Ensures that each zone
8061 * has a correct pages reserved value, so an adequate number of
8062 * pages are left in the zone after a successful __alloc_pages().
8063 */
setup_per_zone_lowmem_reserve(void)8064 static void setup_per_zone_lowmem_reserve(void)
8065 {
8066 struct pglist_data *pgdat;
8067 enum zone_type i, j;
8068
8069 for_each_online_pgdat(pgdat) {
8070 for (i = 0; i < MAX_NR_ZONES - 1; i++) {
8071 struct zone *zone = &pgdat->node_zones[i];
8072 int ratio = sysctl_lowmem_reserve_ratio[i];
8073 bool clear = !ratio || !zone_managed_pages(zone);
8074 unsigned long managed_pages = 0;
8075
8076 for (j = i + 1; j < MAX_NR_ZONES; j++) {
8077 struct zone *upper_zone = &pgdat->node_zones[j];
8078
8079 managed_pages += zone_managed_pages(upper_zone);
8080
8081 if (clear)
8082 zone->lowmem_reserve[j] = 0;
8083 else
8084 zone->lowmem_reserve[j] = managed_pages / ratio;
8085 }
8086 }
8087 }
8088
8089 /* update totalreserve_pages */
8090 calculate_totalreserve_pages();
8091 }
8092
__setup_per_zone_wmarks(void)8093 static void __setup_per_zone_wmarks(void)
8094 {
8095 unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
8096 unsigned long pages_low = extra_free_kbytes >> (PAGE_SHIFT - 10);
8097 unsigned long lowmem_pages = 0;
8098 struct zone *zone;
8099 unsigned long flags;
8100
8101 /* Calculate total number of !ZONE_HIGHMEM pages */
8102 for_each_zone(zone) {
8103 if (!is_highmem(zone))
8104 lowmem_pages += zone_managed_pages(zone);
8105 }
8106
8107 for_each_zone(zone) {
8108 u64 tmp, low;
8109
8110 spin_lock_irqsave(&zone->lock, flags);
8111 tmp = (u64)pages_min * zone_managed_pages(zone);
8112 do_div(tmp, lowmem_pages);
8113 low = (u64)pages_low * zone_managed_pages(zone);
8114 do_div(low, nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE)));
8115 if (is_highmem(zone)) {
8116 /*
8117 * __GFP_HIGH and PF_MEMALLOC allocations usually don't
8118 * need highmem pages, so cap pages_min to a small
8119 * value here.
8120 *
8121 * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN)
8122 * deltas control async page reclaim, and so should
8123 * not be capped for highmem.
8124 */
8125 unsigned long min_pages;
8126
8127 min_pages = zone_managed_pages(zone) / 1024;
8128 min_pages = clamp(min_pages, SWAP_CLUSTER_MAX, 128UL);
8129 zone->_watermark[WMARK_MIN] = min_pages;
8130 } else {
8131 /*
8132 * If it's a lowmem zone, reserve a number of pages
8133 * proportionate to the zone's size.
8134 */
8135 zone->_watermark[WMARK_MIN] = tmp;
8136 }
8137
8138 /*
8139 * Set the kswapd watermarks distance according to the
8140 * scale factor in proportion to available memory, but
8141 * ensure a minimum size on small systems.
8142 */
8143 tmp = max_t(u64, tmp >> 2,
8144 mult_frac(zone_managed_pages(zone),
8145 watermark_scale_factor, 10000));
8146
8147 zone->watermark_boost = 0;
8148 zone->_watermark[WMARK_LOW] = min_wmark_pages(zone) + low + tmp;
8149 zone->_watermark[WMARK_HIGH] = min_wmark_pages(zone) + low + tmp * 2;
8150
8151 spin_unlock_irqrestore(&zone->lock, flags);
8152 }
8153
8154 /* update totalreserve_pages */
8155 calculate_totalreserve_pages();
8156 }
8157
8158 /**
8159 * setup_per_zone_wmarks - called when min_free_kbytes changes
8160 * or when memory is hot-{added|removed}
8161 *
8162 * Ensures that the watermark[min,low,high] values for each zone are set
8163 * correctly with respect to min_free_kbytes.
8164 */
setup_per_zone_wmarks(void)8165 void setup_per_zone_wmarks(void)
8166 {
8167 static DEFINE_SPINLOCK(lock);
8168
8169 spin_lock(&lock);
8170 __setup_per_zone_wmarks();
8171 spin_unlock(&lock);
8172 }
8173
8174 /*
8175 * Initialise min_free_kbytes.
8176 *
8177 * For small machines we want it small (128k min). For large machines
8178 * we want it large (256MB max). But it is not linear, because network
8179 * bandwidth does not increase linearly with machine size. We use
8180 *
8181 * min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
8182 * min_free_kbytes = sqrt(lowmem_kbytes * 16)
8183 *
8184 * which yields
8185 *
8186 * 16MB: 512k
8187 * 32MB: 724k
8188 * 64MB: 1024k
8189 * 128MB: 1448k
8190 * 256MB: 2048k
8191 * 512MB: 2896k
8192 * 1024MB: 4096k
8193 * 2048MB: 5792k
8194 * 4096MB: 8192k
8195 * 8192MB: 11584k
8196 * 16384MB: 16384k
8197 */
init_per_zone_wmark_min(void)8198 int __meminit init_per_zone_wmark_min(void)
8199 {
8200 unsigned long lowmem_kbytes;
8201 int new_min_free_kbytes;
8202
8203 lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
8204 new_min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
8205
8206 if (new_min_free_kbytes > user_min_free_kbytes) {
8207 min_free_kbytes = new_min_free_kbytes;
8208 if (min_free_kbytes < 128)
8209 min_free_kbytes = 128;
8210 if (min_free_kbytes > 262144)
8211 min_free_kbytes = 262144;
8212 } else {
8213 pr_warn("min_free_kbytes is not updated to %d because user defined value %d is preferred\n",
8214 new_min_free_kbytes, user_min_free_kbytes);
8215 }
8216 setup_per_zone_wmarks();
8217 refresh_zone_stat_thresholds();
8218 setup_per_zone_lowmem_reserve();
8219
8220 #ifdef CONFIG_NUMA
8221 setup_min_unmapped_ratio();
8222 setup_min_slab_ratio();
8223 #endif
8224
8225 khugepaged_min_free_kbytes_update();
8226
8227 return 0;
8228 }
postcore_initcall(init_per_zone_wmark_min)8229 postcore_initcall(init_per_zone_wmark_min)
8230
8231 /*
8232 * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
8233 * that we can call two helper functions whenever min_free_kbytes
8234 * or extra_free_kbytes changes.
8235 */
8236 int min_free_kbytes_sysctl_handler(struct ctl_table *table, int write,
8237 void *buffer, size_t *length, loff_t *ppos)
8238 {
8239 int rc;
8240
8241 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
8242 if (rc)
8243 return rc;
8244
8245 if (write) {
8246 user_min_free_kbytes = min_free_kbytes;
8247 setup_per_zone_wmarks();
8248 }
8249 return 0;
8250 }
8251
watermark_scale_factor_sysctl_handler(struct ctl_table * table,int write,void * buffer,size_t * length,loff_t * ppos)8252 int watermark_scale_factor_sysctl_handler(struct ctl_table *table, int write,
8253 void *buffer, size_t *length, loff_t *ppos)
8254 {
8255 int rc;
8256
8257 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
8258 if (rc)
8259 return rc;
8260
8261 if (write)
8262 setup_per_zone_wmarks();
8263
8264 return 0;
8265 }
8266
8267 #ifdef CONFIG_NUMA
setup_min_unmapped_ratio(void)8268 static void setup_min_unmapped_ratio(void)
8269 {
8270 pg_data_t *pgdat;
8271 struct zone *zone;
8272
8273 for_each_online_pgdat(pgdat)
8274 pgdat->min_unmapped_pages = 0;
8275
8276 for_each_zone(zone)
8277 zone->zone_pgdat->min_unmapped_pages += (zone_managed_pages(zone) *
8278 sysctl_min_unmapped_ratio) / 100;
8279 }
8280
8281
sysctl_min_unmapped_ratio_sysctl_handler(struct ctl_table * table,int write,void * buffer,size_t * length,loff_t * ppos)8282 int sysctl_min_unmapped_ratio_sysctl_handler(struct ctl_table *table, int write,
8283 void *buffer, size_t *length, loff_t *ppos)
8284 {
8285 int rc;
8286
8287 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
8288 if (rc)
8289 return rc;
8290
8291 setup_min_unmapped_ratio();
8292
8293 return 0;
8294 }
8295
setup_min_slab_ratio(void)8296 static void setup_min_slab_ratio(void)
8297 {
8298 pg_data_t *pgdat;
8299 struct zone *zone;
8300
8301 for_each_online_pgdat(pgdat)
8302 pgdat->min_slab_pages = 0;
8303
8304 for_each_zone(zone)
8305 zone->zone_pgdat->min_slab_pages += (zone_managed_pages(zone) *
8306 sysctl_min_slab_ratio) / 100;
8307 }
8308
sysctl_min_slab_ratio_sysctl_handler(struct ctl_table * table,int write,void * buffer,size_t * length,loff_t * ppos)8309 int sysctl_min_slab_ratio_sysctl_handler(struct ctl_table *table, int write,
8310 void *buffer, size_t *length, loff_t *ppos)
8311 {
8312 int rc;
8313
8314 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
8315 if (rc)
8316 return rc;
8317
8318 setup_min_slab_ratio();
8319
8320 return 0;
8321 }
8322 #endif
8323
8324 /*
8325 * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
8326 * proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
8327 * whenever sysctl_lowmem_reserve_ratio changes.
8328 *
8329 * The reserve ratio obviously has absolutely no relation with the
8330 * minimum watermarks. The lowmem reserve ratio can only make sense
8331 * if in function of the boot time zone sizes.
8332 */
lowmem_reserve_ratio_sysctl_handler(struct ctl_table * table,int write,void * buffer,size_t * length,loff_t * ppos)8333 int lowmem_reserve_ratio_sysctl_handler(struct ctl_table *table, int write,
8334 void *buffer, size_t *length, loff_t *ppos)
8335 {
8336 int i;
8337
8338 proc_dointvec_minmax(table, write, buffer, length, ppos);
8339
8340 for (i = 0; i < MAX_NR_ZONES; i++) {
8341 if (sysctl_lowmem_reserve_ratio[i] < 1)
8342 sysctl_lowmem_reserve_ratio[i] = 0;
8343 }
8344
8345 setup_per_zone_lowmem_reserve();
8346 return 0;
8347 }
8348
__zone_pcp_update(struct zone * zone)8349 static void __zone_pcp_update(struct zone *zone)
8350 {
8351 unsigned int cpu;
8352
8353 for_each_possible_cpu(cpu)
8354 pageset_set_high_and_batch(zone,
8355 per_cpu_ptr(zone->pageset, cpu));
8356 }
8357
8358 /*
8359 * percpu_pagelist_fraction - changes the pcp->high for each zone on each
8360 * cpu. It is the fraction of total pages in each zone that a hot per cpu
8361 * pagelist can have before it gets flushed back to buddy allocator.
8362 */
percpu_pagelist_fraction_sysctl_handler(struct ctl_table * table,int write,void * buffer,size_t * length,loff_t * ppos)8363 int percpu_pagelist_fraction_sysctl_handler(struct ctl_table *table, int write,
8364 void *buffer, size_t *length, loff_t *ppos)
8365 {
8366 struct zone *zone;
8367 int old_percpu_pagelist_fraction;
8368 int ret;
8369
8370 mutex_lock(&pcp_batch_high_lock);
8371 old_percpu_pagelist_fraction = percpu_pagelist_fraction;
8372
8373 ret = proc_dointvec_minmax(table, write, buffer, length, ppos);
8374 if (!write || ret < 0)
8375 goto out;
8376
8377 /* Sanity checking to avoid pcp imbalance */
8378 if (percpu_pagelist_fraction &&
8379 percpu_pagelist_fraction < MIN_PERCPU_PAGELIST_FRACTION) {
8380 percpu_pagelist_fraction = old_percpu_pagelist_fraction;
8381 ret = -EINVAL;
8382 goto out;
8383 }
8384
8385 /* No change? */
8386 if (percpu_pagelist_fraction == old_percpu_pagelist_fraction)
8387 goto out;
8388
8389 for_each_populated_zone(zone)
8390 __zone_pcp_update(zone);
8391 out:
8392 mutex_unlock(&pcp_batch_high_lock);
8393 return ret;
8394 }
8395
8396 #ifndef __HAVE_ARCH_RESERVED_KERNEL_PAGES
8397 /*
8398 * Returns the number of pages that arch has reserved but
8399 * is not known to alloc_large_system_hash().
8400 */
arch_reserved_kernel_pages(void)8401 static unsigned long __init arch_reserved_kernel_pages(void)
8402 {
8403 return 0;
8404 }
8405 #endif
8406
8407 /*
8408 * Adaptive scale is meant to reduce sizes of hash tables on large memory
8409 * machines. As memory size is increased the scale is also increased but at
8410 * slower pace. Starting from ADAPT_SCALE_BASE (64G), every time memory
8411 * quadruples the scale is increased by one, which means the size of hash table
8412 * only doubles, instead of quadrupling as well.
8413 * Because 32-bit systems cannot have large physical memory, where this scaling
8414 * makes sense, it is disabled on such platforms.
8415 */
8416 #if __BITS_PER_LONG > 32
8417 #define ADAPT_SCALE_BASE (64ul << 30)
8418 #define ADAPT_SCALE_SHIFT 2
8419 #define ADAPT_SCALE_NPAGES (ADAPT_SCALE_BASE >> PAGE_SHIFT)
8420 #endif
8421
8422 /*
8423 * allocate a large system hash table from bootmem
8424 * - it is assumed that the hash table must contain an exact power-of-2
8425 * quantity of entries
8426 * - limit is the number of hash buckets, not the total allocation size
8427 */
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)8428 void *__init alloc_large_system_hash(const char *tablename,
8429 unsigned long bucketsize,
8430 unsigned long numentries,
8431 int scale,
8432 int flags,
8433 unsigned int *_hash_shift,
8434 unsigned int *_hash_mask,
8435 unsigned long low_limit,
8436 unsigned long high_limit)
8437 {
8438 unsigned long long max = high_limit;
8439 unsigned long log2qty, size;
8440 void *table = NULL;
8441 gfp_t gfp_flags;
8442 bool virt;
8443
8444 /* allow the kernel cmdline to have a say */
8445 if (!numentries) {
8446 /* round applicable memory size up to nearest megabyte */
8447 numentries = nr_kernel_pages;
8448 numentries -= arch_reserved_kernel_pages();
8449
8450 /* It isn't necessary when PAGE_SIZE >= 1MB */
8451 if (PAGE_SHIFT < 20)
8452 numentries = round_up(numentries, (1<<20)/PAGE_SIZE);
8453
8454 #if __BITS_PER_LONG > 32
8455 if (!high_limit) {
8456 unsigned long adapt;
8457
8458 for (adapt = ADAPT_SCALE_NPAGES; adapt < numentries;
8459 adapt <<= ADAPT_SCALE_SHIFT)
8460 scale++;
8461 }
8462 #endif
8463
8464 /* limit to 1 bucket per 2^scale bytes of low memory */
8465 if (scale > PAGE_SHIFT)
8466 numentries >>= (scale - PAGE_SHIFT);
8467 else
8468 numentries <<= (PAGE_SHIFT - scale);
8469
8470 /* Make sure we've got at least a 0-order allocation.. */
8471 if (unlikely(flags & HASH_SMALL)) {
8472 /* Makes no sense without HASH_EARLY */
8473 WARN_ON(!(flags & HASH_EARLY));
8474 if (!(numentries >> *_hash_shift)) {
8475 numentries = 1UL << *_hash_shift;
8476 BUG_ON(!numentries);
8477 }
8478 } else if (unlikely((numentries * bucketsize) < PAGE_SIZE))
8479 numentries = PAGE_SIZE / bucketsize;
8480 }
8481 numentries = roundup_pow_of_two(numentries);
8482
8483 /* limit allocation size to 1/16 total memory by default */
8484 if (max == 0) {
8485 max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
8486 do_div(max, bucketsize);
8487 }
8488 max = min(max, 0x80000000ULL);
8489
8490 if (numentries < low_limit)
8491 numentries = low_limit;
8492 if (numentries > max)
8493 numentries = max;
8494
8495 log2qty = ilog2(numentries);
8496
8497 gfp_flags = (flags & HASH_ZERO) ? GFP_ATOMIC | __GFP_ZERO : GFP_ATOMIC;
8498 do {
8499 virt = false;
8500 size = bucketsize << log2qty;
8501 if (flags & HASH_EARLY) {
8502 if (flags & HASH_ZERO)
8503 table = memblock_alloc(size, SMP_CACHE_BYTES);
8504 else
8505 table = memblock_alloc_raw(size,
8506 SMP_CACHE_BYTES);
8507 } else if (get_order(size) >= MAX_ORDER || hashdist) {
8508 table = __vmalloc(size, gfp_flags);
8509 virt = true;
8510 } else {
8511 /*
8512 * If bucketsize is not a power-of-two, we may free
8513 * some pages at the end of hash table which
8514 * alloc_pages_exact() automatically does
8515 */
8516 table = alloc_pages_exact(size, gfp_flags);
8517 kmemleak_alloc(table, size, 1, gfp_flags);
8518 }
8519 } while (!table && size > PAGE_SIZE && --log2qty);
8520
8521 if (!table)
8522 panic("Failed to allocate %s hash table\n", tablename);
8523
8524 pr_info("%s hash table entries: %ld (order: %d, %lu bytes, %s)\n",
8525 tablename, 1UL << log2qty, ilog2(size) - PAGE_SHIFT, size,
8526 virt ? "vmalloc" : "linear");
8527
8528 if (_hash_shift)
8529 *_hash_shift = log2qty;
8530 if (_hash_mask)
8531 *_hash_mask = (1 << log2qty) - 1;
8532
8533 return table;
8534 }
8535
8536 /*
8537 * This function checks whether pageblock includes unmovable pages or not.
8538 *
8539 * PageLRU check without isolation or lru_lock could race so that
8540 * MIGRATE_MOVABLE block might include unmovable pages. And __PageMovable
8541 * check without lock_page also may miss some movable non-lru pages at
8542 * race condition. So you can't expect this function should be exact.
8543 *
8544 * Returns a page without holding a reference. If the caller wants to
8545 * dereference that page (e.g., dumping), it has to make sure that it
8546 * cannot get removed (e.g., via memory unplug) concurrently.
8547 *
8548 */
has_unmovable_pages(struct zone * zone,struct page * page,int migratetype,int flags)8549 struct page *has_unmovable_pages(struct zone *zone, struct page *page,
8550 int migratetype, int flags)
8551 {
8552 unsigned long iter = 0;
8553 unsigned long pfn = page_to_pfn(page);
8554 unsigned long offset = pfn % pageblock_nr_pages;
8555
8556 if (is_migrate_cma_page(page)) {
8557 /*
8558 * CMA allocations (alloc_contig_range) really need to mark
8559 * isolate CMA pageblocks even when they are not movable in fact
8560 * so consider them movable here.
8561 */
8562 if (is_migrate_cma(migratetype))
8563 return NULL;
8564
8565 return page;
8566 }
8567
8568 for (; iter < pageblock_nr_pages - offset; iter++) {
8569 if (!pfn_valid_within(pfn + iter))
8570 continue;
8571
8572 page = pfn_to_page(pfn + iter);
8573
8574 /*
8575 * Both, bootmem allocations and memory holes are marked
8576 * PG_reserved and are unmovable. We can even have unmovable
8577 * allocations inside ZONE_MOVABLE, for example when
8578 * specifying "movablecore".
8579 */
8580 if (PageReserved(page))
8581 return page;
8582
8583 /*
8584 * If the zone is movable and we have ruled out all reserved
8585 * pages then it should be reasonably safe to assume the rest
8586 * is movable.
8587 */
8588 if (zone_idx(zone) == ZONE_MOVABLE)
8589 continue;
8590
8591 /*
8592 * Hugepages are not in LRU lists, but they're movable.
8593 * THPs are on the LRU, but need to be counted as #small pages.
8594 * We need not scan over tail pages because we don't
8595 * handle each tail page individually in migration.
8596 */
8597 if (PageHuge(page) || PageTransCompound(page)) {
8598 struct page *head = compound_head(page);
8599 unsigned int skip_pages;
8600
8601 if (PageHuge(page)) {
8602 if (!hugepage_migration_supported(page_hstate(head)))
8603 return page;
8604 } else if (!PageLRU(head) && !__PageMovable(head)) {
8605 return page;
8606 }
8607
8608 skip_pages = compound_nr(head) - (page - head);
8609 iter += skip_pages - 1;
8610 continue;
8611 }
8612
8613 /*
8614 * We can't use page_count without pin a page
8615 * because another CPU can free compound page.
8616 * This check already skips compound tails of THP
8617 * because their page->_refcount is zero at all time.
8618 */
8619 if (!page_ref_count(page)) {
8620 if (PageBuddy(page))
8621 iter += (1 << buddy_order(page)) - 1;
8622 continue;
8623 }
8624
8625 /*
8626 * The HWPoisoned page may be not in buddy system, and
8627 * page_count() is not 0.
8628 */
8629 if ((flags & MEMORY_OFFLINE) && PageHWPoison(page))
8630 continue;
8631
8632 /*
8633 * We treat all PageOffline() pages as movable when offlining
8634 * to give drivers a chance to decrement their reference count
8635 * in MEM_GOING_OFFLINE in order to indicate that these pages
8636 * can be offlined as there are no direct references anymore.
8637 * For actually unmovable PageOffline() where the driver does
8638 * not support this, we will fail later when trying to actually
8639 * move these pages that still have a reference count > 0.
8640 * (false negatives in this function only)
8641 */
8642 if ((flags & MEMORY_OFFLINE) && PageOffline(page))
8643 continue;
8644
8645 if (__PageMovable(page) || PageLRU(page))
8646 continue;
8647
8648 /*
8649 * If there are RECLAIMABLE pages, we need to check
8650 * it. But now, memory offline itself doesn't call
8651 * shrink_node_slabs() and it still to be fixed.
8652 */
8653 return page;
8654 }
8655 return NULL;
8656 }
8657
8658 #ifdef CONFIG_CONTIG_ALLOC
pfn_max_align_down(unsigned long pfn)8659 static unsigned long pfn_max_align_down(unsigned long pfn)
8660 {
8661 return pfn & ~(max_t(unsigned long, MAX_ORDER_NR_PAGES,
8662 pageblock_nr_pages) - 1);
8663 }
8664
pfn_max_align_up(unsigned long pfn)8665 unsigned long pfn_max_align_up(unsigned long pfn)
8666 {
8667 return ALIGN(pfn, max_t(unsigned long, MAX_ORDER_NR_PAGES,
8668 pageblock_nr_pages));
8669 }
8670
8671 #if defined(CONFIG_DYNAMIC_DEBUG) || \
8672 (defined(CONFIG_DYNAMIC_DEBUG_CORE) && defined(DYNAMIC_DEBUG_MODULE))
8673 /* Usage: See admin-guide/dynamic-debug-howto.rst */
alloc_contig_dump_pages(struct list_head * page_list)8674 static void alloc_contig_dump_pages(struct list_head *page_list)
8675 {
8676 DEFINE_DYNAMIC_DEBUG_METADATA(descriptor, "migrate failure");
8677
8678 if (DYNAMIC_DEBUG_BRANCH(descriptor)) {
8679 struct page *page;
8680 unsigned long nr_skip = 0;
8681 unsigned long nr_pages = 0;
8682
8683 dump_stack();
8684 list_for_each_entry(page, page_list, lru) {
8685 nr_pages++;
8686 /* The page will be freed by putback_movable_pages soon */
8687 if (page_count(page) == 1) {
8688 nr_skip++;
8689 continue;
8690 }
8691 dump_page(page, "migration failure");
8692 }
8693 pr_warn("total dump_pages %lu skipping %lu\n", nr_pages, nr_skip);
8694 }
8695 }
8696 #else
alloc_contig_dump_pages(struct list_head * page_list)8697 static inline void alloc_contig_dump_pages(struct list_head *page_list)
8698 {
8699 }
8700 #endif
8701
8702 /* [start, end) must belong to a single zone. */
__alloc_contig_migrate_range(struct compact_control * cc,unsigned long start,unsigned long end,struct acr_info * info)8703 static int __alloc_contig_migrate_range(struct compact_control *cc,
8704 unsigned long start, unsigned long end,
8705 struct acr_info *info)
8706 {
8707 /* This function is based on compact_zone() from compaction.c. */
8708 unsigned int nr_reclaimed;
8709 unsigned long pfn = start;
8710 unsigned int tries = 0;
8711 unsigned int max_tries = 5;
8712 int ret = 0;
8713 struct page *page;
8714 struct migration_target_control mtc = {
8715 .nid = zone_to_nid(cc->zone),
8716 .gfp_mask = GFP_USER | __GFP_MOVABLE | __GFP_RETRY_MAYFAIL,
8717 };
8718
8719 if (cc->alloc_contig && cc->mode == MIGRATE_ASYNC)
8720 max_tries = 1;
8721
8722 lru_cache_disable();
8723
8724 while (pfn < end || !list_empty(&cc->migratepages)) {
8725 if (fatal_signal_pending(current)) {
8726 ret = -EINTR;
8727 break;
8728 }
8729
8730 if (list_empty(&cc->migratepages)) {
8731 cc->nr_migratepages = 0;
8732 pfn = isolate_migratepages_range(cc, pfn, end);
8733 if (!pfn) {
8734 ret = -EINTR;
8735 break;
8736 }
8737 tries = 0;
8738 } else if (++tries == max_tries) {
8739 ret = ret < 0 ? ret : -EBUSY;
8740 break;
8741 }
8742
8743 nr_reclaimed = reclaim_clean_pages_from_list(cc->zone,
8744 &cc->migratepages);
8745 info->nr_reclaimed += nr_reclaimed;
8746 cc->nr_migratepages -= nr_reclaimed;
8747
8748 list_for_each_entry(page, &cc->migratepages, lru)
8749 info->nr_mapped += page_mapcount(page);
8750
8751 ret = migrate_pages(&cc->migratepages, alloc_migration_target,
8752 NULL, (unsigned long)&mtc, cc->mode, MR_CONTIG_RANGE);
8753 if (!ret)
8754 info->nr_migrated += cc->nr_migratepages;
8755 }
8756
8757 lru_cache_enable();
8758 if (ret < 0) {
8759 if (ret == -EBUSY) {
8760 alloc_contig_dump_pages(&cc->migratepages);
8761 page_pinner_mark_migration_failed_pages(&cc->migratepages);
8762 }
8763
8764 if (!list_empty(&cc->migratepages)) {
8765 page = list_first_entry(&cc->migratepages, struct page , lru);
8766 info->failed_pfn = page_to_pfn(page);
8767 }
8768
8769 putback_movable_pages(&cc->migratepages);
8770 info->err |= ACR_ERR_MIGRATE;
8771 return ret;
8772 }
8773 return 0;
8774 }
8775
8776 /**
8777 * alloc_contig_range() -- tries to allocate given range of pages
8778 * @start: start PFN to allocate
8779 * @end: one-past-the-last PFN to allocate
8780 * @migratetype: migratetype of the underlaying pageblocks (either
8781 * #MIGRATE_MOVABLE or #MIGRATE_CMA). All pageblocks
8782 * in range must have the same migratetype and it must
8783 * be either of the two.
8784 * @gfp_mask: GFP mask to use during compaction
8785 *
8786 * The PFN range does not have to be pageblock or MAX_ORDER_NR_PAGES
8787 * aligned. The PFN range must belong to a single zone.
8788 *
8789 * The first thing this routine does is attempt to MIGRATE_ISOLATE all
8790 * pageblocks in the range. Once isolated, the pageblocks should not
8791 * be modified by others.
8792 *
8793 * Return: zero on success or negative error code. On success all
8794 * pages which PFN is in [start, end) are allocated for the caller and
8795 * need to be freed with free_contig_range().
8796 */
alloc_contig_range(unsigned long start,unsigned long end,unsigned migratetype,gfp_t gfp_mask,struct acr_info * info)8797 int alloc_contig_range(unsigned long start, unsigned long end,
8798 unsigned migratetype, gfp_t gfp_mask,
8799 struct acr_info *info)
8800 {
8801 unsigned long outer_start, outer_end;
8802 unsigned int order;
8803 int ret = 0;
8804 bool skip_drain_all_pages = false;
8805
8806 struct compact_control cc = {
8807 .nr_migratepages = 0,
8808 .order = -1,
8809 .zone = page_zone(pfn_to_page(start)),
8810 .mode = gfp_mask & __GFP_NORETRY ? MIGRATE_ASYNC : MIGRATE_SYNC,
8811 .ignore_skip_hint = true,
8812 .no_set_skip_hint = true,
8813 .gfp_mask = current_gfp_context(gfp_mask),
8814 .alloc_contig = true,
8815 };
8816 INIT_LIST_HEAD(&cc.migratepages);
8817
8818 /*
8819 * What we do here is we mark all pageblocks in range as
8820 * MIGRATE_ISOLATE. Because pageblock and max order pages may
8821 * have different sizes, and due to the way page allocator
8822 * work, we align the range to biggest of the two pages so
8823 * that page allocator won't try to merge buddies from
8824 * different pageblocks and change MIGRATE_ISOLATE to some
8825 * other migration type.
8826 *
8827 * Once the pageblocks are marked as MIGRATE_ISOLATE, we
8828 * migrate the pages from an unaligned range (ie. pages that
8829 * we are interested in). This will put all the pages in
8830 * range back to page allocator as MIGRATE_ISOLATE.
8831 *
8832 * When this is done, we take the pages in range from page
8833 * allocator removing them from the buddy system. This way
8834 * page allocator will never consider using them.
8835 *
8836 * This lets us mark the pageblocks back as
8837 * MIGRATE_CMA/MIGRATE_MOVABLE so that free pages in the
8838 * aligned range but not in the unaligned, original range are
8839 * put back to page allocator so that buddy can use them.
8840 */
8841
8842 ret = start_isolate_page_range(pfn_max_align_down(start),
8843 pfn_max_align_up(end), migratetype, 0,
8844 &info->failed_pfn);
8845 if (ret) {
8846 info->err |= ACR_ERR_ISOLATE;
8847 return ret;
8848 }
8849
8850 trace_android_vh_cma_drain_all_pages_bypass(migratetype,
8851 &skip_drain_all_pages);
8852 if (!skip_drain_all_pages)
8853 drain_all_pages(cc.zone);
8854
8855 /*
8856 * In case of -EBUSY, we'd like to know which page causes problem.
8857 * So, just fall through. test_pages_isolated() has a tracepoint
8858 * which will report the busy page.
8859 *
8860 * It is possible that busy pages could become available before
8861 * the call to test_pages_isolated, and the range will actually be
8862 * allocated. So, if we fall through be sure to clear ret so that
8863 * -EBUSY is not accidentally used or returned to caller.
8864 */
8865 ret = __alloc_contig_migrate_range(&cc, start, end, info);
8866 if (ret && (ret != -EBUSY || (gfp_mask & __GFP_NORETRY)))
8867 goto done;
8868 ret =0;
8869
8870 /*
8871 * Pages from [start, end) are within a MAX_ORDER_NR_PAGES
8872 * aligned blocks that are marked as MIGRATE_ISOLATE. What's
8873 * more, all pages in [start, end) are free in page allocator.
8874 * What we are going to do is to allocate all pages from
8875 * [start, end) (that is remove them from page allocator).
8876 *
8877 * The only problem is that pages at the beginning and at the
8878 * end of interesting range may be not aligned with pages that
8879 * page allocator holds, ie. they can be part of higher order
8880 * pages. Because of this, we reserve the bigger range and
8881 * once this is done free the pages we are not interested in.
8882 *
8883 * We don't have to hold zone->lock here because the pages are
8884 * isolated thus they won't get removed from buddy.
8885 */
8886
8887 order = 0;
8888 outer_start = start;
8889 while (!PageBuddy(pfn_to_page(outer_start))) {
8890 if (++order >= MAX_ORDER) {
8891 outer_start = start;
8892 break;
8893 }
8894 outer_start &= ~0UL << order;
8895 }
8896
8897 if (outer_start != start) {
8898 order = buddy_order(pfn_to_page(outer_start));
8899
8900 /*
8901 * outer_start page could be small order buddy page and
8902 * it doesn't include start page. Adjust outer_start
8903 * in this case to report failed page properly
8904 * on tracepoint in test_pages_isolated()
8905 */
8906 if (outer_start + (1UL << order) <= start)
8907 outer_start = start;
8908 }
8909
8910 /* Make sure the range is really isolated. */
8911 if (test_pages_isolated(outer_start, end, 0, &info->failed_pfn)) {
8912 pr_info_ratelimited("%s: [%lx, %lx) PFNs busy\n",
8913 __func__, outer_start, end);
8914 ret = -EBUSY;
8915 info->err |= ACR_ERR_TEST;
8916 goto done;
8917 }
8918
8919 /* Grab isolated pages from freelists. */
8920 outer_end = isolate_freepages_range(&cc, outer_start, end);
8921 if (!outer_end) {
8922 ret = -EBUSY;
8923 goto done;
8924 }
8925
8926 /* Free head and tail (if any) */
8927 if (start != outer_start)
8928 free_contig_range(outer_start, start - outer_start);
8929 if (end != outer_end)
8930 free_contig_range(end, outer_end - end);
8931
8932 done:
8933 undo_isolate_page_range(pfn_max_align_down(start),
8934 pfn_max_align_up(end), migratetype);
8935 return ret;
8936 }
8937 EXPORT_SYMBOL(alloc_contig_range);
8938
__alloc_contig_pages(unsigned long start_pfn,unsigned long nr_pages,gfp_t gfp_mask)8939 static int __alloc_contig_pages(unsigned long start_pfn,
8940 unsigned long nr_pages, gfp_t gfp_mask)
8941 {
8942 struct acr_info dummy;
8943 unsigned long end_pfn = start_pfn + nr_pages;
8944
8945 return alloc_contig_range(start_pfn, end_pfn, MIGRATE_MOVABLE,
8946 gfp_mask, &dummy);
8947 }
8948
pfn_range_valid_contig(struct zone * z,unsigned long start_pfn,unsigned long nr_pages)8949 static bool pfn_range_valid_contig(struct zone *z, unsigned long start_pfn,
8950 unsigned long nr_pages)
8951 {
8952 unsigned long i, end_pfn = start_pfn + nr_pages;
8953 struct page *page;
8954
8955 for (i = start_pfn; i < end_pfn; i++) {
8956 page = pfn_to_online_page(i);
8957 if (!page)
8958 return false;
8959
8960 if (page_zone(page) != z)
8961 return false;
8962
8963 if (PageReserved(page))
8964 return false;
8965
8966 if (page_count(page) > 0)
8967 return false;
8968
8969 if (PageHuge(page))
8970 return false;
8971 }
8972 return true;
8973 }
8974
zone_spans_last_pfn(const struct zone * zone,unsigned long start_pfn,unsigned long nr_pages)8975 static bool zone_spans_last_pfn(const struct zone *zone,
8976 unsigned long start_pfn, unsigned long nr_pages)
8977 {
8978 unsigned long last_pfn = start_pfn + nr_pages - 1;
8979
8980 return zone_spans_pfn(zone, last_pfn);
8981 }
8982
8983 /**
8984 * alloc_contig_pages() -- tries to find and allocate contiguous range of pages
8985 * @nr_pages: Number of contiguous pages to allocate
8986 * @gfp_mask: GFP mask to limit search and used during compaction
8987 * @nid: Target node
8988 * @nodemask: Mask for other possible nodes
8989 *
8990 * This routine is a wrapper around alloc_contig_range(). It scans over zones
8991 * on an applicable zonelist to find a contiguous pfn range which can then be
8992 * tried for allocation with alloc_contig_range(). This routine is intended
8993 * for allocation requests which can not be fulfilled with the buddy allocator.
8994 *
8995 * The allocated memory is always aligned to a page boundary. If nr_pages is a
8996 * power of two then the alignment is guaranteed to be to the given nr_pages
8997 * (e.g. 1GB request would be aligned to 1GB).
8998 *
8999 * Allocated pages can be freed with free_contig_range() or by manually calling
9000 * __free_page() on each allocated page.
9001 *
9002 * Return: pointer to contiguous pages on success, or NULL if not successful.
9003 */
alloc_contig_pages(unsigned long nr_pages,gfp_t gfp_mask,int nid,nodemask_t * nodemask)9004 struct page *alloc_contig_pages(unsigned long nr_pages, gfp_t gfp_mask,
9005 int nid, nodemask_t *nodemask)
9006 {
9007 unsigned long ret, pfn, flags;
9008 struct zonelist *zonelist;
9009 struct zone *zone;
9010 struct zoneref *z;
9011
9012 zonelist = node_zonelist(nid, gfp_mask);
9013 for_each_zone_zonelist_nodemask(zone, z, zonelist,
9014 gfp_zone(gfp_mask), nodemask) {
9015 spin_lock_irqsave(&zone->lock, flags);
9016
9017 pfn = ALIGN(zone->zone_start_pfn, nr_pages);
9018 while (zone_spans_last_pfn(zone, pfn, nr_pages)) {
9019 if (pfn_range_valid_contig(zone, pfn, nr_pages)) {
9020 /*
9021 * We release the zone lock here because
9022 * alloc_contig_range() will also lock the zone
9023 * at some point. If there's an allocation
9024 * spinning on this lock, it may win the race
9025 * and cause alloc_contig_range() to fail...
9026 */
9027 spin_unlock_irqrestore(&zone->lock, flags);
9028 ret = __alloc_contig_pages(pfn, nr_pages,
9029 gfp_mask);
9030 if (!ret)
9031 return pfn_to_page(pfn);
9032 spin_lock_irqsave(&zone->lock, flags);
9033 }
9034 pfn += nr_pages;
9035 }
9036 spin_unlock_irqrestore(&zone->lock, flags);
9037 }
9038 return NULL;
9039 }
9040 #endif /* CONFIG_CONTIG_ALLOC */
9041
free_contig_range(unsigned long pfn,unsigned int nr_pages)9042 void free_contig_range(unsigned long pfn, unsigned int nr_pages)
9043 {
9044 unsigned int count = 0;
9045
9046 for (; nr_pages--; pfn++) {
9047 struct page *page = pfn_to_page(pfn);
9048
9049 count += page_count(page) != 1;
9050 __free_page(page);
9051 }
9052 WARN(count != 0, "%d pages are still in use!\n", count);
9053 }
9054 EXPORT_SYMBOL(free_contig_range);
9055
9056 /*
9057 * The zone indicated has a new number of managed_pages; batch sizes and percpu
9058 * page high values need to be recalulated.
9059 */
zone_pcp_update(struct zone * zone)9060 void __meminit zone_pcp_update(struct zone *zone)
9061 {
9062 mutex_lock(&pcp_batch_high_lock);
9063 __zone_pcp_update(zone);
9064 mutex_unlock(&pcp_batch_high_lock);
9065 }
9066
zone_pcp_reset(struct zone * zone)9067 void zone_pcp_reset(struct zone *zone)
9068 {
9069 unsigned long flags;
9070 int cpu;
9071 struct per_cpu_pageset *pset;
9072
9073 /* avoid races with drain_pages() */
9074 local_irq_save(flags);
9075 if (zone->pageset != &boot_pageset) {
9076 for_each_online_cpu(cpu) {
9077 pset = per_cpu_ptr(zone->pageset, cpu);
9078 drain_zonestat(zone, pset);
9079 }
9080 free_percpu(zone->pageset);
9081 zone->pageset = &boot_pageset;
9082 }
9083 local_irq_restore(flags);
9084 }
9085
9086 #ifdef CONFIG_MEMORY_HOTREMOVE
9087 /*
9088 * All pages in the range must be in a single zone, must not contain holes,
9089 * must span full sections, and must be isolated before calling this function.
9090 */
__offline_isolated_pages(unsigned long start_pfn,unsigned long end_pfn)9091 void __offline_isolated_pages(unsigned long start_pfn, unsigned long end_pfn)
9092 {
9093 unsigned long pfn = start_pfn;
9094 struct page *page;
9095 struct zone *zone;
9096 unsigned int order;
9097 unsigned long flags;
9098
9099 offline_mem_sections(pfn, end_pfn);
9100 zone = page_zone(pfn_to_page(pfn));
9101 spin_lock_irqsave(&zone->lock, flags);
9102 while (pfn < end_pfn) {
9103 page = pfn_to_page(pfn);
9104 /*
9105 * The HWPoisoned page may be not in buddy system, and
9106 * page_count() is not 0.
9107 */
9108 if (unlikely(!PageBuddy(page) && PageHWPoison(page))) {
9109 pfn++;
9110 continue;
9111 }
9112 /*
9113 * At this point all remaining PageOffline() pages have a
9114 * reference count of 0 and can simply be skipped.
9115 */
9116 if (PageOffline(page)) {
9117 BUG_ON(page_count(page));
9118 BUG_ON(PageBuddy(page));
9119 pfn++;
9120 continue;
9121 }
9122
9123 BUG_ON(page_count(page));
9124 BUG_ON(!PageBuddy(page));
9125 order = buddy_order(page);
9126 del_page_from_free_list(page, zone, order);
9127 pfn += (1 << order);
9128 }
9129 spin_unlock_irqrestore(&zone->lock, flags);
9130 }
9131 #endif
9132
is_free_buddy_page(struct page * page)9133 bool is_free_buddy_page(struct page *page)
9134 {
9135 struct zone *zone = page_zone(page);
9136 unsigned long pfn = page_to_pfn(page);
9137 unsigned long flags;
9138 unsigned int order;
9139
9140 spin_lock_irqsave(&zone->lock, flags);
9141 for (order = 0; order < MAX_ORDER; order++) {
9142 struct page *page_head = page - (pfn & ((1 << order) - 1));
9143
9144 if (PageBuddy(page_head) && buddy_order(page_head) >= order)
9145 break;
9146 }
9147 spin_unlock_irqrestore(&zone->lock, flags);
9148
9149 return order < MAX_ORDER;
9150 }
9151
9152 #ifdef CONFIG_MEMORY_FAILURE
9153 /*
9154 * Break down a higher-order page in sub-pages, and keep our target out of
9155 * buddy allocator.
9156 */
break_down_buddy_pages(struct zone * zone,struct page * page,struct page * target,int low,int high,int migratetype)9157 static void break_down_buddy_pages(struct zone *zone, struct page *page,
9158 struct page *target, int low, int high,
9159 int migratetype)
9160 {
9161 unsigned long size = 1 << high;
9162 struct page *current_buddy, *next_page;
9163
9164 while (high > low) {
9165 high--;
9166 size >>= 1;
9167
9168 if (target >= &page[size]) {
9169 next_page = page + size;
9170 current_buddy = page;
9171 } else {
9172 next_page = page;
9173 current_buddy = page + size;
9174 }
9175
9176 if (set_page_guard(zone, current_buddy, high, migratetype))
9177 continue;
9178
9179 if (current_buddy != target) {
9180 add_to_free_list(current_buddy, zone, high, migratetype);
9181 set_buddy_order(current_buddy, high);
9182 page = next_page;
9183 }
9184 }
9185 }
9186
9187 /*
9188 * Take a page that will be marked as poisoned off the buddy allocator.
9189 */
take_page_off_buddy(struct page * page)9190 bool take_page_off_buddy(struct page *page)
9191 {
9192 struct zone *zone = page_zone(page);
9193 unsigned long pfn = page_to_pfn(page);
9194 unsigned long flags;
9195 unsigned int order;
9196 bool ret = false;
9197
9198 spin_lock_irqsave(&zone->lock, flags);
9199 for (order = 0; order < MAX_ORDER; order++) {
9200 struct page *page_head = page - (pfn & ((1 << order) - 1));
9201 int page_order = buddy_order(page_head);
9202
9203 if (PageBuddy(page_head) && page_order >= order) {
9204 unsigned long pfn_head = page_to_pfn(page_head);
9205 int migratetype = get_pfnblock_migratetype(page_head,
9206 pfn_head);
9207
9208 del_page_from_free_list(page_head, zone, page_order);
9209 break_down_buddy_pages(zone, page_head, page, 0,
9210 page_order, migratetype);
9211 if (!is_migrate_isolate(migratetype))
9212 __mod_zone_freepage_state(zone, -1, migratetype);
9213 ret = true;
9214 break;
9215 }
9216 if (page_count(page_head) > 0)
9217 break;
9218 }
9219 spin_unlock_irqrestore(&zone->lock, flags);
9220 return ret;
9221 }
9222 #endif
9223
9224 #ifdef CONFIG_ZONE_DMA
has_managed_dma(void)9225 bool has_managed_dma(void)
9226 {
9227 struct pglist_data *pgdat;
9228
9229 for_each_online_pgdat(pgdat) {
9230 struct zone *zone = &pgdat->node_zones[ZONE_DMA];
9231
9232 if (managed_zone(zone))
9233 return true;
9234 }
9235 return false;
9236 }
9237 #endif /* CONFIG_ZONE_DMA */
9238