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