1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 *
4 * Manages the free list, the system allocates free pages here.
5 * Note that kmalloc() lives in slab.c
6 *
7 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
8 * Swap reorganised 29.12.95, Stephen Tweedie
9 * Support of BIGMEM added by Gerhard Wichert, Siemens AG, July 1999
10 * Reshaped it to be a zoned allocator, Ingo Molnar, Red Hat, 1999
11 * Discontiguous memory support, Kanoj Sarcar, SGI, Nov 1999
12 * Zone balancing, Kanoj Sarcar, SGI, Jan 2000
13 * Per cpu hot/cold page lists, bulk allocation, Martin J. Bligh, Sept 2002
14 * (lots of bits borrowed from Ingo Molnar & Andrew Morton)
15 */
16
17 #include <linux/stddef.h>
18 #include <linux/mm.h>
19 #include <linux/highmem.h>
20 #include <linux/interrupt.h>
21 #include <linux/jiffies.h>
22 #include <linux/compiler.h>
23 #include <linux/kernel.h>
24 #include <linux/kasan.h>
25 #include <linux/kmsan.h>
26 #include <linux/module.h>
27 #include <linux/suspend.h>
28 #include <linux/ratelimit.h>
29 #include <linux/oom.h>
30 #include <linux/topology.h>
31 #include <linux/sysctl.h>
32 #include <linux/cpu.h>
33 #include <linux/cpuset.h>
34 #include <linux/folio_batch.h>
35 #include <linux/memory_hotplug.h>
36 #include <linux/nodemask.h>
37 #include <linux/vmstat.h>
38 #include <linux/fault-inject.h>
39 #include <linux/compaction.h>
40 #include <trace/events/kmem.h>
41 #include <trace/events/oom.h>
42 #include <linux/prefetch.h>
43 #include <linux/mm_inline.h>
44 #include <linux/mmu_notifier.h>
45 #include <linux/migrate.h>
46 #include <linux/sched/mm.h>
47 #include <linux/page_owner.h>
48 #include <linux/page_table_check.h>
49 #include <linux/memcontrol.h>
50 #include <linux/ftrace.h>
51 #include <linux/lockdep.h>
52 #include <linux/psi.h>
53 #include <linux/khugepaged.h>
54 #include <linux/delayacct.h>
55 #include <linux/cacheinfo.h>
56 #include <linux/pgalloc_tag.h>
57 #include <asm/div64.h>
58 #include "internal.h"
59 #include "shuffle.h"
60 #include "page_reporting.h"
61
62 /* Free Page Internal flags: for internal, non-pcp variants of free_pages(). */
63 typedef int __bitwise fpi_t;
64
65 /* No special request */
66 #define FPI_NONE ((__force fpi_t)0)
67
68 /*
69 * Skip free page reporting notification for the (possibly merged) page.
70 * This does not hinder free page reporting from grabbing the page,
71 * reporting it and marking it "reported" - it only skips notifying
72 * the free page reporting infrastructure about a newly freed page. For
73 * example, used when temporarily pulling a page from a freelist and
74 * putting it back unmodified.
75 */
76 #define FPI_SKIP_REPORT_NOTIFY ((__force fpi_t)BIT(0))
77
78 /*
79 * Place the (possibly merged) page to the tail of the freelist. Will ignore
80 * page shuffling (relevant code - e.g., memory onlining - is expected to
81 * shuffle the whole zone).
82 *
83 * Note: No code should rely on this flag for correctness - it's purely
84 * to allow for optimizations when handing back either fresh pages
85 * (memory onlining) or untouched pages (page isolation, free page
86 * reporting).
87 */
88 #define FPI_TO_TAIL ((__force fpi_t)BIT(1))
89
90 /* Free the page without taking locks. Rely on trylock only. */
91 #define FPI_TRYLOCK ((__force fpi_t)BIT(2))
92
93 /* prevent >1 _updater_ of zone percpu pageset ->high and ->batch fields */
94 static DEFINE_MUTEX(pcp_batch_high_lock);
95 #define MIN_PERCPU_PAGELIST_HIGH_FRACTION (8)
96
97 /*
98 * Locking a pcp requires a PCP lookup followed by a spinlock. To avoid
99 * a migration causing the wrong PCP to be locked and remote memory being
100 * potentially allocated, pin the task to the CPU for the lookup+lock.
101 * preempt_disable is used on !RT because it is faster than migrate_disable.
102 * migrate_disable is used on RT because otherwise RT spinlock usage is
103 * interfered with and a high priority task cannot preempt the allocator.
104 */
105 #ifndef CONFIG_PREEMPT_RT
106 #define pcpu_task_pin() preempt_disable()
107 #define pcpu_task_unpin() preempt_enable()
108 #else
109 #define pcpu_task_pin() migrate_disable()
110 #define pcpu_task_unpin() migrate_enable()
111 #endif
112
113 /*
114 * A helper to lookup and trylock pcp with embedded spinlock.
115 * The return value should be used with the unlock helper.
116 * NULL return value means the trylock failed.
117 */
118 #ifdef CONFIG_SMP
119 #define pcp_spin_trylock(ptr) \
120 ({ \
121 struct per_cpu_pages *_ret; \
122 pcpu_task_pin(); \
123 _ret = this_cpu_ptr(ptr); \
124 if (!spin_trylock(&_ret->lock)) { \
125 pcpu_task_unpin(); \
126 _ret = NULL; \
127 } \
128 _ret; \
129 })
130
131 #define pcp_spin_unlock(ptr) \
132 ({ \
133 spin_unlock(&ptr->lock); \
134 pcpu_task_unpin(); \
135 })
136
137 /*
138 * On CONFIG_SMP=n the UP implementation of spin_trylock() never fails and thus
139 * is not compatible with our locking scheme. However we do not need pcp for
140 * scalability in the first place, so just make all the trylocks fail and take
141 * the slow path unconditionally.
142 */
143 #else
144 #define pcp_spin_trylock(ptr) \
145 NULL
146
147 #define pcp_spin_unlock(ptr) \
148 BUG_ON(1)
149 #endif
150
151 /*
152 * In some cases we do not need to pin the task to the CPU because we are
153 * already given a specific cpu's pcp pointer.
154 */
155 #define pcp_spin_lock_nopin(ptr) \
156 spin_lock(&(ptr)->lock)
157 #define pcp_spin_unlock_nopin(ptr) \
158 spin_unlock(&(ptr)->lock)
159
160 #ifdef CONFIG_USE_PERCPU_NUMA_NODE_ID
161 DEFINE_PER_CPU(int, numa_node);
162 EXPORT_PER_CPU_SYMBOL(numa_node);
163 #endif
164
165 DEFINE_STATIC_KEY_TRUE(vm_numa_stat_key);
166
167 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
168 /*
169 * N.B., Do NOT reference the '_numa_mem_' per cpu variable directly.
170 * It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined.
171 * Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem()
172 * defined in <linux/topology.h>.
173 */
174 DEFINE_PER_CPU(int, _numa_mem_); /* Kernel "local memory" node */
175 EXPORT_PER_CPU_SYMBOL(_numa_mem_);
176 #endif
177
178 static DEFINE_MUTEX(pcpu_drain_mutex);
179
180 #ifdef CONFIG_GCC_PLUGIN_LATENT_ENTROPY
181 volatile unsigned long latent_entropy __latent_entropy;
182 EXPORT_SYMBOL(latent_entropy);
183 #endif
184
185 /*
186 * Array of node states.
187 */
188 nodemask_t node_states[NR_NODE_STATES] __read_mostly = {
189 [N_POSSIBLE] = NODE_MASK_ALL,
190 [N_ONLINE] = { { [0] = 1UL } },
191 #ifndef CONFIG_NUMA
192 [N_NORMAL_MEMORY] = { { [0] = 1UL } },
193 #ifdef CONFIG_HIGHMEM
194 [N_HIGH_MEMORY] = { { [0] = 1UL } },
195 #endif
196 [N_MEMORY] = { { [0] = 1UL } },
197 [N_CPU] = { { [0] = 1UL } },
198 #endif /* NUMA */
199 };
200 EXPORT_SYMBOL(node_states);
201
202 gfp_t gfp_allowed_mask __read_mostly = GFP_BOOT_MASK;
203
204 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
205 unsigned int pageblock_order __read_mostly;
206 #endif
207
208 static void __free_pages_ok(struct page *page, unsigned int order,
209 fpi_t fpi_flags);
210 static void reserve_highatomic_pageblock(struct page *page, int order,
211 struct zone *zone);
212
213 /*
214 * results with 256, 32 in the lowmem_reserve sysctl:
215 * 1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
216 * 1G machine -> (16M dma, 784M normal, 224M high)
217 * NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
218 * HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
219 * HIGHMEM allocation will leave (224M+784M)/256 of ram reserved in ZONE_DMA
220 *
221 * TBD: should special case ZONE_DMA32 machines here - in those we normally
222 * don't need any ZONE_NORMAL reservation
223 */
224 static int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES] = {
225 #ifdef CONFIG_ZONE_DMA
226 [ZONE_DMA] = 256,
227 #endif
228 #ifdef CONFIG_ZONE_DMA32
229 [ZONE_DMA32] = 256,
230 #endif
231 [ZONE_NORMAL] = 32,
232 #ifdef CONFIG_HIGHMEM
233 [ZONE_HIGHMEM] = 0,
234 #endif
235 [ZONE_MOVABLE] = 0,
236 };
237
238 char * const zone_names[MAX_NR_ZONES] = {
239 #ifdef CONFIG_ZONE_DMA
240 "DMA",
241 #endif
242 #ifdef CONFIG_ZONE_DMA32
243 "DMA32",
244 #endif
245 "Normal",
246 #ifdef CONFIG_HIGHMEM
247 "HighMem",
248 #endif
249 "Movable",
250 #ifdef CONFIG_ZONE_DEVICE
251 "Device",
252 #endif
253 };
254
255 const char * const migratetype_names[MIGRATE_TYPES] = {
256 "Unmovable",
257 "Movable",
258 "Reclaimable",
259 "HighAtomic",
260 #ifdef CONFIG_CMA
261 "CMA",
262 #endif
263 #ifdef CONFIG_MEMORY_ISOLATION
264 "Isolate",
265 #endif
266 };
267
268 int min_free_kbytes = 1024;
269 int user_min_free_kbytes = -1;
270 static int watermark_boost_factor __read_mostly = 15000;
271 static int watermark_scale_factor = 10;
272 int defrag_mode;
273
274 /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
275 int movable_zone;
276 EXPORT_SYMBOL(movable_zone);
277
278 #if MAX_NUMNODES > 1
279 unsigned int nr_node_ids __read_mostly = MAX_NUMNODES;
280 unsigned int nr_online_nodes __read_mostly = 1;
281 EXPORT_SYMBOL(nr_node_ids);
282 EXPORT_SYMBOL(nr_online_nodes);
283 #endif
284
285 static bool page_contains_unaccepted(struct page *page, unsigned int order);
286 static bool cond_accept_memory(struct zone *zone, unsigned int order,
287 int alloc_flags);
288 static bool __free_unaccepted(struct page *page);
289
290 int page_group_by_mobility_disabled __read_mostly;
291
292 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
293 /*
294 * During boot we initialize deferred pages on-demand, as needed, but once
295 * page_alloc_init_late() has finished, the deferred pages are all initialized,
296 * and we can permanently disable that path.
297 */
298 DEFINE_STATIC_KEY_TRUE(deferred_pages);
299
300 /*
301 * deferred_grow_zone() is __init, but it is called from
302 * get_page_from_freelist() during early boot until deferred_pages permanently
303 * disables this call. This is why we have refdata wrapper to avoid warning,
304 * and to ensure that the function body gets unloaded.
305 */
306 static bool __ref
_deferred_grow_zone(struct zone * zone,unsigned int order)307 _deferred_grow_zone(struct zone *zone, unsigned int order)
308 {
309 return deferred_grow_zone(zone, order);
310 }
311 #else
_deferred_grow_zone(struct zone * zone,unsigned int order)312 static inline bool _deferred_grow_zone(struct zone *zone, unsigned int order)
313 {
314 return false;
315 }
316 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
317
318 /* Return a pointer to the bitmap storing bits affecting a block of pages */
get_pageblock_bitmap(const struct page * page,unsigned long pfn)319 static inline unsigned long *get_pageblock_bitmap(const struct page *page,
320 unsigned long pfn)
321 {
322 #ifdef CONFIG_SPARSEMEM
323 return section_to_usemap(__pfn_to_section(pfn));
324 #else
325 return page_zone(page)->pageblock_flags;
326 #endif /* CONFIG_SPARSEMEM */
327 }
328
pfn_to_bitidx(const struct page * page,unsigned long pfn)329 static inline int pfn_to_bitidx(const struct page *page, unsigned long pfn)
330 {
331 #ifdef CONFIG_SPARSEMEM
332 pfn &= (PAGES_PER_SECTION-1);
333 #else
334 pfn = pfn - pageblock_start_pfn(page_zone(page)->zone_start_pfn);
335 #endif /* CONFIG_SPARSEMEM */
336 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
337 }
338
is_standalone_pb_bit(enum pageblock_bits pb_bit)339 static __always_inline bool is_standalone_pb_bit(enum pageblock_bits pb_bit)
340 {
341 return pb_bit >= PB_compact_skip && pb_bit < __NR_PAGEBLOCK_BITS;
342 }
343
344 static __always_inline void
get_pfnblock_bitmap_bitidx(const struct page * page,unsigned long pfn,unsigned long ** bitmap_word,unsigned long * bitidx)345 get_pfnblock_bitmap_bitidx(const struct page *page, unsigned long pfn,
346 unsigned long **bitmap_word, unsigned long *bitidx)
347 {
348 unsigned long *bitmap;
349 unsigned long word_bitidx;
350
351 #ifdef CONFIG_MEMORY_ISOLATION
352 BUILD_BUG_ON(NR_PAGEBLOCK_BITS != 8);
353 #else
354 BUILD_BUG_ON(NR_PAGEBLOCK_BITS != 4);
355 #endif
356 BUILD_BUG_ON(__MIGRATE_TYPE_END > MIGRATETYPE_MASK);
357 VM_BUG_ON_PAGE(!zone_spans_pfn(page_zone(page), pfn), page);
358
359 bitmap = get_pageblock_bitmap(page, pfn);
360 *bitidx = pfn_to_bitidx(page, pfn);
361 word_bitidx = *bitidx / BITS_PER_LONG;
362 *bitidx &= (BITS_PER_LONG - 1);
363 *bitmap_word = &bitmap[word_bitidx];
364 }
365
366
367 /**
368 * __get_pfnblock_flags_mask - Return the requested group of flags for
369 * a pageblock_nr_pages block of pages
370 * @page: The page within the block of interest
371 * @pfn: The target page frame number
372 * @mask: mask of bits that the caller is interested in
373 *
374 * Return: pageblock_bits flags
375 */
__get_pfnblock_flags_mask(const struct page * page,unsigned long pfn,unsigned long mask)376 static unsigned long __get_pfnblock_flags_mask(const struct page *page,
377 unsigned long pfn,
378 unsigned long mask)
379 {
380 unsigned long *bitmap_word;
381 unsigned long bitidx;
382 unsigned long word;
383
384 get_pfnblock_bitmap_bitidx(page, pfn, &bitmap_word, &bitidx);
385 /*
386 * This races, without locks, with set_pfnblock_migratetype(). Ensure
387 * a consistent read of the memory array, so that results, even though
388 * racy, are not corrupted.
389 */
390 word = READ_ONCE(*bitmap_word);
391 return (word >> bitidx) & mask;
392 }
393
394 /**
395 * get_pfnblock_bit - Check if a standalone bit of a pageblock is set
396 * @page: The page within the block of interest
397 * @pfn: The target page frame number
398 * @pb_bit: pageblock bit to check
399 *
400 * Return: true if the bit is set, otherwise false
401 */
get_pfnblock_bit(const struct page * page,unsigned long pfn,enum pageblock_bits pb_bit)402 bool get_pfnblock_bit(const struct page *page, unsigned long pfn,
403 enum pageblock_bits pb_bit)
404 {
405 unsigned long *bitmap_word;
406 unsigned long bitidx;
407
408 if (WARN_ON_ONCE(!is_standalone_pb_bit(pb_bit)))
409 return false;
410
411 get_pfnblock_bitmap_bitidx(page, pfn, &bitmap_word, &bitidx);
412
413 return test_bit(bitidx + pb_bit, bitmap_word);
414 }
415
416 /**
417 * get_pfnblock_migratetype - Return the migratetype of a pageblock
418 * @page: The page within the block of interest
419 * @pfn: The target page frame number
420 *
421 * Return: The migratetype of the pageblock
422 *
423 * Use get_pfnblock_migratetype() if caller already has both @page and @pfn
424 * to save a call to page_to_pfn().
425 */
426 __always_inline enum migratetype
get_pfnblock_migratetype(const struct page * page,unsigned long pfn)427 get_pfnblock_migratetype(const struct page *page, unsigned long pfn)
428 {
429 unsigned long mask = MIGRATETYPE_AND_ISO_MASK;
430 unsigned long flags;
431
432 flags = __get_pfnblock_flags_mask(page, pfn, mask);
433
434 #ifdef CONFIG_MEMORY_ISOLATION
435 if (flags & BIT(PB_migrate_isolate))
436 return MIGRATE_ISOLATE;
437 #endif
438 return flags & MIGRATETYPE_MASK;
439 }
440
441 /**
442 * __set_pfnblock_flags_mask - Set the requested group of flags for
443 * a pageblock_nr_pages block of pages
444 * @page: The page within the block of interest
445 * @pfn: The target page frame number
446 * @flags: The flags to set
447 * @mask: mask of bits that the caller is interested in
448 */
__set_pfnblock_flags_mask(struct page * page,unsigned long pfn,unsigned long flags,unsigned long mask)449 static void __set_pfnblock_flags_mask(struct page *page, unsigned long pfn,
450 unsigned long flags, unsigned long mask)
451 {
452 unsigned long *bitmap_word;
453 unsigned long bitidx;
454 unsigned long word;
455
456 get_pfnblock_bitmap_bitidx(page, pfn, &bitmap_word, &bitidx);
457
458 mask <<= bitidx;
459 flags <<= bitidx;
460
461 word = READ_ONCE(*bitmap_word);
462 do {
463 } while (!try_cmpxchg(bitmap_word, &word, (word & ~mask) | flags));
464 }
465
466 /**
467 * set_pfnblock_bit - Set a standalone bit of a pageblock
468 * @page: The page within the block of interest
469 * @pfn: The target page frame number
470 * @pb_bit: pageblock bit to set
471 */
set_pfnblock_bit(const struct page * page,unsigned long pfn,enum pageblock_bits pb_bit)472 void set_pfnblock_bit(const struct page *page, unsigned long pfn,
473 enum pageblock_bits pb_bit)
474 {
475 unsigned long *bitmap_word;
476 unsigned long bitidx;
477
478 if (WARN_ON_ONCE(!is_standalone_pb_bit(pb_bit)))
479 return;
480
481 get_pfnblock_bitmap_bitidx(page, pfn, &bitmap_word, &bitidx);
482
483 set_bit(bitidx + pb_bit, bitmap_word);
484 }
485
486 /**
487 * clear_pfnblock_bit - Clear a standalone bit of a pageblock
488 * @page: The page within the block of interest
489 * @pfn: The target page frame number
490 * @pb_bit: pageblock bit to clear
491 */
clear_pfnblock_bit(const struct page * page,unsigned long pfn,enum pageblock_bits pb_bit)492 void clear_pfnblock_bit(const struct page *page, unsigned long pfn,
493 enum pageblock_bits pb_bit)
494 {
495 unsigned long *bitmap_word;
496 unsigned long bitidx;
497
498 if (WARN_ON_ONCE(!is_standalone_pb_bit(pb_bit)))
499 return;
500
501 get_pfnblock_bitmap_bitidx(page, pfn, &bitmap_word, &bitidx);
502
503 clear_bit(bitidx + pb_bit, bitmap_word);
504 }
505
506 /**
507 * set_pageblock_migratetype - Set the migratetype of a pageblock
508 * @page: The page within the block of interest
509 * @migratetype: migratetype to set
510 */
set_pageblock_migratetype(struct page * page,enum migratetype migratetype)511 static void set_pageblock_migratetype(struct page *page,
512 enum migratetype migratetype)
513 {
514 if (unlikely(page_group_by_mobility_disabled &&
515 migratetype < MIGRATE_PCPTYPES))
516 migratetype = MIGRATE_UNMOVABLE;
517
518 #ifdef CONFIG_MEMORY_ISOLATION
519 if (migratetype == MIGRATE_ISOLATE) {
520 VM_WARN_ONCE(1,
521 "Use set_pageblock_isolate() for pageblock isolation");
522 return;
523 }
524 VM_WARN_ONCE(get_pageblock_isolate(page),
525 "Use clear_pageblock_isolate() to unisolate pageblock");
526 /* MIGRATETYPE_AND_ISO_MASK clears PB_migrate_isolate if it is set */
527 #endif
528 __set_pfnblock_flags_mask(page, page_to_pfn(page),
529 (unsigned long)migratetype,
530 MIGRATETYPE_AND_ISO_MASK);
531 }
532
init_pageblock_migratetype(struct page * page,enum migratetype migratetype,bool isolate)533 void __meminit init_pageblock_migratetype(struct page *page,
534 enum migratetype migratetype,
535 bool isolate)
536 {
537 unsigned long flags;
538
539 if (unlikely(page_group_by_mobility_disabled &&
540 migratetype < MIGRATE_PCPTYPES))
541 migratetype = MIGRATE_UNMOVABLE;
542
543 flags = migratetype;
544
545 #ifdef CONFIG_MEMORY_ISOLATION
546 if (migratetype == MIGRATE_ISOLATE) {
547 VM_WARN_ONCE(
548 1,
549 "Set isolate=true to isolate pageblock with a migratetype");
550 return;
551 }
552 if (isolate)
553 flags |= BIT(PB_migrate_isolate);
554 #endif
555 __set_pfnblock_flags_mask(page, page_to_pfn(page), flags,
556 MIGRATETYPE_AND_ISO_MASK);
557 }
558
559 #ifdef CONFIG_DEBUG_VM
page_outside_zone_boundaries(struct zone * zone,struct page * page)560 static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
561 {
562 int ret;
563 unsigned seq;
564 unsigned long pfn = page_to_pfn(page);
565 unsigned long sp, start_pfn;
566
567 do {
568 seq = zone_span_seqbegin(zone);
569 start_pfn = zone->zone_start_pfn;
570 sp = zone->spanned_pages;
571 ret = !zone_spans_pfn(zone, pfn);
572 } while (zone_span_seqretry(zone, seq));
573
574 if (ret)
575 pr_err("page 0x%lx outside node %d zone %s [ 0x%lx - 0x%lx ]\n",
576 pfn, zone_to_nid(zone), zone->name,
577 start_pfn, start_pfn + sp);
578
579 return ret;
580 }
581
582 /*
583 * Temporary debugging check for pages not lying within a given zone.
584 */
bad_range(struct zone * zone,struct page * page)585 static bool __maybe_unused bad_range(struct zone *zone, struct page *page)
586 {
587 if (page_outside_zone_boundaries(zone, page))
588 return true;
589 if (zone != page_zone(page))
590 return true;
591
592 return false;
593 }
594 #else
bad_range(struct zone * zone,struct page * page)595 static inline bool __maybe_unused bad_range(struct zone *zone, struct page *page)
596 {
597 return false;
598 }
599 #endif
600
bad_page(struct page * page,const char * reason)601 static void bad_page(struct page *page, const char *reason)
602 {
603 static unsigned long resume;
604 static unsigned long nr_shown;
605 static unsigned long nr_unshown;
606
607 /*
608 * Allow a burst of 60 reports, then keep quiet for that minute;
609 * or allow a steady drip of one report per second.
610 */
611 if (nr_shown == 60) {
612 if (time_before(jiffies, resume)) {
613 nr_unshown++;
614 goto out;
615 }
616 if (nr_unshown) {
617 pr_alert(
618 "BUG: Bad page state: %lu messages suppressed\n",
619 nr_unshown);
620 nr_unshown = 0;
621 }
622 nr_shown = 0;
623 }
624 if (nr_shown++ == 0)
625 resume = jiffies + 60 * HZ;
626
627 pr_alert("BUG: Bad page state in process %s pfn:%05lx\n",
628 current->comm, page_to_pfn(page));
629 dump_page(page, reason);
630
631 print_modules();
632 dump_stack();
633 out:
634 /* Leave bad fields for debug, except PageBuddy could make trouble */
635 if (PageBuddy(page))
636 __ClearPageBuddy(page);
637 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
638 }
639
order_to_pindex(int migratetype,int order)640 static inline unsigned int order_to_pindex(int migratetype, int order)
641 {
642
643 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
644 bool movable;
645 if (order > PAGE_ALLOC_COSTLY_ORDER) {
646 VM_BUG_ON(!is_pmd_order(order));
647
648 movable = migratetype == MIGRATE_MOVABLE;
649
650 return NR_LOWORDER_PCP_LISTS + movable;
651 }
652 #else
653 VM_BUG_ON(order > PAGE_ALLOC_COSTLY_ORDER);
654 #endif
655
656 return (MIGRATE_PCPTYPES * order) + migratetype;
657 }
658
pindex_to_order(unsigned int pindex)659 static inline int pindex_to_order(unsigned int pindex)
660 {
661 int order = pindex / MIGRATE_PCPTYPES;
662
663 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
664 if (pindex >= NR_LOWORDER_PCP_LISTS)
665 order = HPAGE_PMD_ORDER;
666 #else
667 VM_BUG_ON(order > PAGE_ALLOC_COSTLY_ORDER);
668 #endif
669
670 return order;
671 }
672
pcp_allowed_order(unsigned int order)673 static inline bool pcp_allowed_order(unsigned int order)
674 {
675 if (order <= PAGE_ALLOC_COSTLY_ORDER)
676 return true;
677 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
678 if (is_pmd_order(order))
679 return true;
680 #endif
681 return false;
682 }
683
684 /*
685 * Higher-order pages are called "compound pages". They are structured thusly:
686 *
687 * The first PAGE_SIZE page is called the "head page" and have PG_head set.
688 *
689 * The remaining PAGE_SIZE pages are called "tail pages". PageTail() is encoded
690 * in bit 0 of page->compound_info. The rest of bits is pointer to head page.
691 *
692 * The first tail page's ->compound_order holds the order of allocation.
693 * This usage means that zero-order pages may not be compound.
694 */
695
prep_compound_page(struct page * page,unsigned int order)696 void prep_compound_page(struct page *page, unsigned int order)
697 {
698 int i;
699 int nr_pages = 1 << order;
700
701 __SetPageHead(page);
702 for (i = 1; i < nr_pages; i++)
703 prep_compound_tail(page + i, page, order);
704
705 prep_compound_head(page, order);
706 }
707
set_buddy_order(struct page * page,unsigned int order)708 static inline void set_buddy_order(struct page *page, unsigned int order)
709 {
710 set_page_private(page, order);
711 __SetPageBuddy(page);
712 }
713
714 #ifdef CONFIG_COMPACTION
task_capc(struct zone * zone)715 static inline struct capture_control *task_capc(struct zone *zone)
716 {
717 struct capture_control *capc = current->capture_control;
718
719 return unlikely(capc) &&
720 !(current->flags & PF_KTHREAD) &&
721 !capc->page &&
722 capc->cc->zone == zone ? capc : NULL;
723 }
724
725 static inline bool
compaction_capture(struct capture_control * capc,struct page * page,int order,int migratetype)726 compaction_capture(struct capture_control *capc, struct page *page,
727 int order, int migratetype)
728 {
729 if (!capc || order != capc->cc->order)
730 return false;
731
732 /* Do not accidentally pollute CMA or isolated regions*/
733 if (is_migrate_cma(migratetype) ||
734 is_migrate_isolate(migratetype))
735 return false;
736
737 /*
738 * Do not let lower order allocations pollute a movable pageblock
739 * unless compaction is also requesting movable pages.
740 * This might let an unmovable request use a reclaimable pageblock
741 * and vice-versa but no more than normal fallback logic which can
742 * have trouble finding a high-order free page.
743 */
744 if (order < pageblock_order && migratetype == MIGRATE_MOVABLE &&
745 capc->cc->migratetype != MIGRATE_MOVABLE)
746 return false;
747
748 if (migratetype != capc->cc->migratetype)
749 trace_mm_page_alloc_extfrag(page, capc->cc->order, order,
750 capc->cc->migratetype, migratetype);
751
752 capc->page = page;
753 return true;
754 }
755
756 #else
task_capc(struct zone * zone)757 static inline struct capture_control *task_capc(struct zone *zone)
758 {
759 return NULL;
760 }
761
762 static inline bool
compaction_capture(struct capture_control * capc,struct page * page,int order,int migratetype)763 compaction_capture(struct capture_control *capc, struct page *page,
764 int order, int migratetype)
765 {
766 return false;
767 }
768 #endif /* CONFIG_COMPACTION */
769
account_freepages(struct zone * zone,int nr_pages,int migratetype)770 static inline void account_freepages(struct zone *zone, int nr_pages,
771 int migratetype)
772 {
773 lockdep_assert_held(&zone->lock);
774
775 if (is_migrate_isolate(migratetype))
776 return;
777
778 __mod_zone_page_state(zone, NR_FREE_PAGES, nr_pages);
779
780 if (is_migrate_cma(migratetype))
781 __mod_zone_page_state(zone, NR_FREE_CMA_PAGES, nr_pages);
782 else if (migratetype == MIGRATE_HIGHATOMIC)
783 WRITE_ONCE(zone->nr_free_highatomic,
784 zone->nr_free_highatomic + nr_pages);
785 }
786
787 /* Used for pages not on another list */
__add_to_free_list(struct page * page,struct zone * zone,unsigned int order,int migratetype,bool tail)788 static inline void __add_to_free_list(struct page *page, struct zone *zone,
789 unsigned int order, int migratetype,
790 bool tail)
791 {
792 struct free_area *area = &zone->free_area[order];
793 int nr_pages = 1 << order;
794
795 VM_WARN_ONCE(get_pageblock_migratetype(page) != migratetype,
796 "page type is %d, passed migratetype is %d (nr=%d)\n",
797 get_pageblock_migratetype(page), migratetype, nr_pages);
798
799 if (tail)
800 list_add_tail(&page->buddy_list, &area->free_list[migratetype]);
801 else
802 list_add(&page->buddy_list, &area->free_list[migratetype]);
803 area->nr_free++;
804
805 if (order >= pageblock_order && !is_migrate_isolate(migratetype))
806 __mod_zone_page_state(zone, NR_FREE_PAGES_BLOCKS, nr_pages);
807 }
808
809 /*
810 * Used for pages which are on another list. Move the pages to the tail
811 * of the list - so the moved pages won't immediately be considered for
812 * allocation again (e.g., optimization for memory onlining).
813 */
move_to_free_list(struct page * page,struct zone * zone,unsigned int order,int old_mt,int new_mt)814 static inline void move_to_free_list(struct page *page, struct zone *zone,
815 unsigned int order, int old_mt, int new_mt)
816 {
817 struct free_area *area = &zone->free_area[order];
818 int nr_pages = 1 << order;
819
820 /* Free page moving can fail, so it happens before the type update */
821 VM_WARN_ONCE(get_pageblock_migratetype(page) != old_mt,
822 "page type is %d, passed migratetype is %d (nr=%d)\n",
823 get_pageblock_migratetype(page), old_mt, nr_pages);
824
825 list_move_tail(&page->buddy_list, &area->free_list[new_mt]);
826
827 account_freepages(zone, -nr_pages, old_mt);
828 account_freepages(zone, nr_pages, new_mt);
829
830 if (order >= pageblock_order &&
831 is_migrate_isolate(old_mt) != is_migrate_isolate(new_mt)) {
832 if (!is_migrate_isolate(old_mt))
833 nr_pages = -nr_pages;
834 __mod_zone_page_state(zone, NR_FREE_PAGES_BLOCKS, nr_pages);
835 }
836 }
837
__del_page_from_free_list(struct page * page,struct zone * zone,unsigned int order,int migratetype)838 static inline void __del_page_from_free_list(struct page *page, struct zone *zone,
839 unsigned int order, int migratetype)
840 {
841 int nr_pages = 1 << order;
842
843 VM_WARN_ONCE(get_pageblock_migratetype(page) != migratetype,
844 "page type is %d, passed migratetype is %d (nr=%d)\n",
845 get_pageblock_migratetype(page), migratetype, nr_pages);
846
847 /* clear reported state and update reported page count */
848 if (page_reported(page))
849 __ClearPageReported(page);
850
851 list_del(&page->buddy_list);
852 __ClearPageBuddy(page);
853 set_page_private(page, 0);
854 zone->free_area[order].nr_free--;
855
856 if (order >= pageblock_order && !is_migrate_isolate(migratetype))
857 __mod_zone_page_state(zone, NR_FREE_PAGES_BLOCKS, -nr_pages);
858 }
859
del_page_from_free_list(struct page * page,struct zone * zone,unsigned int order,int migratetype)860 static inline void del_page_from_free_list(struct page *page, struct zone *zone,
861 unsigned int order, int migratetype)
862 {
863 __del_page_from_free_list(page, zone, order, migratetype);
864 account_freepages(zone, -(1 << order), migratetype);
865 }
866
get_page_from_free_area(struct free_area * area,int migratetype)867 static inline struct page *get_page_from_free_area(struct free_area *area,
868 int migratetype)
869 {
870 return list_first_entry_or_null(&area->free_list[migratetype],
871 struct page, buddy_list);
872 }
873
874 /*
875 * If this is less than the 2nd largest possible page, check if the buddy
876 * of the next-higher order is free. If it is, it's possible
877 * that pages are being freed that will coalesce soon. In case,
878 * that is happening, add the free page to the tail of the list
879 * so it's less likely to be used soon and more likely to be merged
880 * as a 2-level higher order page
881 */
882 static inline bool
buddy_merge_likely(unsigned long pfn,unsigned long buddy_pfn,struct page * page,unsigned int order)883 buddy_merge_likely(unsigned long pfn, unsigned long buddy_pfn,
884 struct page *page, unsigned int order)
885 {
886 unsigned long higher_page_pfn;
887 struct page *higher_page;
888
889 if (order >= MAX_PAGE_ORDER - 1)
890 return false;
891
892 higher_page_pfn = buddy_pfn & pfn;
893 higher_page = page + (higher_page_pfn - pfn);
894
895 return find_buddy_page_pfn(higher_page, higher_page_pfn, order + 1,
896 NULL) != NULL;
897 }
898
change_pageblock_range(struct page * pageblock_page,int start_order,int migratetype)899 static void change_pageblock_range(struct page *pageblock_page,
900 int start_order, int migratetype)
901 {
902 int nr_pageblocks = 1 << (start_order - pageblock_order);
903
904 while (nr_pageblocks--) {
905 set_pageblock_migratetype(pageblock_page, migratetype);
906 pageblock_page += pageblock_nr_pages;
907 }
908 }
909
910 /*
911 * Freeing function for a buddy system allocator.
912 *
913 * The concept of a buddy system is to maintain direct-mapped table
914 * (containing bit values) for memory blocks of various "orders".
915 * The bottom level table contains the map for the smallest allocatable
916 * units of memory (here, pages), and each level above it describes
917 * pairs of units from the levels below, hence, "buddies".
918 * At a high level, all that happens here is marking the table entry
919 * at the bottom level available, and propagating the changes upward
920 * as necessary, plus some accounting needed to play nicely with other
921 * parts of the VM system.
922 * At each level, we keep a list of pages, which are heads of continuous
923 * free pages of length of (1 << order) and marked with PageBuddy.
924 * Page's order is recorded in page_private(page) field.
925 * So when we are allocating or freeing one, we can derive the state of the
926 * other. That is, if we allocate a small block, and both were
927 * free, the remainder of the region must be split into blocks.
928 * If a block is freed, and its buddy is also free, then this
929 * triggers coalescing into a block of larger size.
930 *
931 * -- nyc
932 */
933
__free_one_page(struct page * page,unsigned long pfn,struct zone * zone,unsigned int order,int migratetype,fpi_t fpi_flags)934 static inline void __free_one_page(struct page *page,
935 unsigned long pfn,
936 struct zone *zone, unsigned int order,
937 int migratetype, fpi_t fpi_flags)
938 {
939 struct capture_control *capc = task_capc(zone);
940 unsigned long buddy_pfn = 0;
941 unsigned long combined_pfn;
942 struct page *buddy;
943 bool to_tail;
944
945 VM_BUG_ON(!zone_is_initialized(zone));
946 VM_BUG_ON_PAGE(page->flags.f & PAGE_FLAGS_CHECK_AT_PREP, page);
947
948 VM_BUG_ON(migratetype == -1);
949 VM_BUG_ON_PAGE(pfn & ((1 << order) - 1), page);
950 VM_BUG_ON_PAGE(bad_range(zone, page), page);
951
952 account_freepages(zone, 1 << order, migratetype);
953
954 while (order < MAX_PAGE_ORDER) {
955 int buddy_mt = migratetype;
956
957 if (compaction_capture(capc, page, order, migratetype)) {
958 account_freepages(zone, -(1 << order), migratetype);
959 return;
960 }
961
962 buddy = find_buddy_page_pfn(page, pfn, order, &buddy_pfn);
963 if (!buddy)
964 goto done_merging;
965
966 if (unlikely(order >= pageblock_order)) {
967 /*
968 * We want to prevent merge between freepages on pageblock
969 * without fallbacks and normal pageblock. Without this,
970 * pageblock isolation could cause incorrect freepage or CMA
971 * accounting or HIGHATOMIC accounting.
972 */
973 buddy_mt = get_pfnblock_migratetype(buddy, buddy_pfn);
974
975 if (migratetype != buddy_mt &&
976 (!migratetype_is_mergeable(migratetype) ||
977 !migratetype_is_mergeable(buddy_mt)))
978 goto done_merging;
979 }
980
981 /*
982 * Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page,
983 * merge with it and move up one order.
984 */
985 if (page_is_guard(buddy))
986 clear_page_guard(zone, buddy, order);
987 else
988 __del_page_from_free_list(buddy, zone, order, buddy_mt);
989
990 if (unlikely(buddy_mt != migratetype)) {
991 /*
992 * Match buddy type. This ensures that an
993 * expand() down the line puts the sub-blocks
994 * on the right freelists.
995 */
996 change_pageblock_range(buddy, order, migratetype);
997 }
998
999 combined_pfn = buddy_pfn & pfn;
1000 page = page + (combined_pfn - pfn);
1001 pfn = combined_pfn;
1002 order++;
1003 }
1004
1005 done_merging:
1006 set_buddy_order(page, order);
1007
1008 if (fpi_flags & FPI_TO_TAIL)
1009 to_tail = true;
1010 else if (is_shuffle_order(order))
1011 to_tail = shuffle_pick_tail();
1012 else
1013 to_tail = buddy_merge_likely(pfn, buddy_pfn, page, order);
1014
1015 __add_to_free_list(page, zone, order, migratetype, to_tail);
1016
1017 /* Notify page reporting subsystem of freed page */
1018 if (!(fpi_flags & FPI_SKIP_REPORT_NOTIFY))
1019 page_reporting_notify_free(order);
1020 }
1021
1022 /*
1023 * A bad page could be due to a number of fields. Instead of multiple branches,
1024 * try and check multiple fields with one check. The caller must do a detailed
1025 * check if necessary.
1026 */
page_expected_state(struct page * page,unsigned long check_flags)1027 static inline bool page_expected_state(struct page *page,
1028 unsigned long check_flags)
1029 {
1030 if (unlikely(atomic_read(&page->_mapcount) != -1))
1031 return false;
1032
1033 if (unlikely((unsigned long)page->mapping |
1034 page_ref_count(page) |
1035 #ifdef CONFIG_MEMCG
1036 page->memcg_data |
1037 #endif
1038 page_pool_page_is_pp(page) |
1039 (page->flags.f & check_flags)))
1040 return false;
1041
1042 return true;
1043 }
1044
page_bad_reason(struct page * page,unsigned long flags)1045 static const char *page_bad_reason(struct page *page, unsigned long flags)
1046 {
1047 const char *bad_reason = NULL;
1048
1049 if (unlikely(atomic_read(&page->_mapcount) != -1))
1050 bad_reason = "nonzero mapcount";
1051 if (unlikely(page->mapping != NULL))
1052 bad_reason = "non-NULL mapping";
1053 if (unlikely(page_ref_count(page) != 0))
1054 bad_reason = "nonzero _refcount";
1055 if (unlikely(page->flags.f & flags)) {
1056 if (flags == PAGE_FLAGS_CHECK_AT_PREP)
1057 bad_reason = "PAGE_FLAGS_CHECK_AT_PREP flag(s) set";
1058 else
1059 bad_reason = "PAGE_FLAGS_CHECK_AT_FREE flag(s) set";
1060 }
1061 #ifdef CONFIG_MEMCG
1062 if (unlikely(page->memcg_data))
1063 bad_reason = "page still charged to cgroup";
1064 #endif
1065 if (unlikely(page_pool_page_is_pp(page)))
1066 bad_reason = "page_pool leak";
1067 return bad_reason;
1068 }
1069
free_page_is_bad(struct page * page)1070 static inline bool free_page_is_bad(struct page *page)
1071 {
1072 if (likely(page_expected_state(page, PAGE_FLAGS_CHECK_AT_FREE)))
1073 return false;
1074
1075 /* Something has gone sideways, find it */
1076 bad_page(page, page_bad_reason(page, PAGE_FLAGS_CHECK_AT_FREE));
1077 return true;
1078 }
1079
is_check_pages_enabled(void)1080 static inline bool is_check_pages_enabled(void)
1081 {
1082 return static_branch_unlikely(&check_pages_enabled);
1083 }
1084
free_tail_page_prepare(struct page * head_page,struct page * page)1085 static int free_tail_page_prepare(struct page *head_page, struct page *page)
1086 {
1087 struct folio *folio = (struct folio *)head_page;
1088 int ret = 1;
1089
1090 /*
1091 * We rely page->lru.next never has bit 0 set, unless the page
1092 * is PageTail(). Let's make sure that's true even for poisoned ->lru.
1093 */
1094 BUILD_BUG_ON((unsigned long)LIST_POISON1 & 1);
1095
1096 if (!is_check_pages_enabled()) {
1097 ret = 0;
1098 goto out;
1099 }
1100 switch (page - head_page) {
1101 case 1:
1102 /* the first tail page: these may be in place of ->mapping */
1103 if (unlikely(folio_large_mapcount(folio))) {
1104 bad_page(page, "nonzero large_mapcount");
1105 goto out;
1106 }
1107 if (IS_ENABLED(CONFIG_PAGE_MAPCOUNT) &&
1108 unlikely(atomic_read(&folio->_nr_pages_mapped))) {
1109 bad_page(page, "nonzero nr_pages_mapped");
1110 goto out;
1111 }
1112 if (IS_ENABLED(CONFIG_MM_ID)) {
1113 if (unlikely(folio->_mm_id_mapcount[0] != -1)) {
1114 bad_page(page, "nonzero mm mapcount 0");
1115 goto out;
1116 }
1117 if (unlikely(folio->_mm_id_mapcount[1] != -1)) {
1118 bad_page(page, "nonzero mm mapcount 1");
1119 goto out;
1120 }
1121 }
1122 if (IS_ENABLED(CONFIG_64BIT)) {
1123 if (unlikely(atomic_read(&folio->_entire_mapcount) + 1)) {
1124 bad_page(page, "nonzero entire_mapcount");
1125 goto out;
1126 }
1127 if (unlikely(atomic_read(&folio->_pincount))) {
1128 bad_page(page, "nonzero pincount");
1129 goto out;
1130 }
1131 }
1132 break;
1133 case 2:
1134 /* the second tail page: deferred_list overlaps ->mapping */
1135 if (unlikely(!list_empty(&folio->_deferred_list))) {
1136 bad_page(page, "on deferred list");
1137 goto out;
1138 }
1139 if (!IS_ENABLED(CONFIG_64BIT)) {
1140 if (unlikely(atomic_read(&folio->_entire_mapcount) + 1)) {
1141 bad_page(page, "nonzero entire_mapcount");
1142 goto out;
1143 }
1144 if (unlikely(atomic_read(&folio->_pincount))) {
1145 bad_page(page, "nonzero pincount");
1146 goto out;
1147 }
1148 }
1149 break;
1150 case 3:
1151 /* the third tail page: hugetlb specifics overlap ->mappings */
1152 if (IS_ENABLED(CONFIG_HUGETLB_PAGE))
1153 break;
1154 fallthrough;
1155 default:
1156 if (page->mapping != TAIL_MAPPING) {
1157 bad_page(page, "corrupted mapping in tail page");
1158 goto out;
1159 }
1160 break;
1161 }
1162 if (unlikely(!PageTail(page))) {
1163 bad_page(page, "PageTail not set");
1164 goto out;
1165 }
1166 if (unlikely(compound_head(page) != head_page)) {
1167 bad_page(page, "compound_head not consistent");
1168 goto out;
1169 }
1170 ret = 0;
1171 out:
1172 page->mapping = NULL;
1173 clear_compound_head(page);
1174 return ret;
1175 }
1176
1177 /*
1178 * Skip KASAN memory poisoning when either:
1179 *
1180 * 1. For generic KASAN: deferred memory initialization has not yet completed.
1181 * Tag-based KASAN modes skip pages freed via deferred memory initialization
1182 * using page tags instead (see below).
1183 * 2. For tag-based KASAN modes: the page has a match-all KASAN tag, indicating
1184 * that error detection is disabled for accesses via the page address.
1185 *
1186 * Pages will have match-all tags in the following circumstances:
1187 *
1188 * 1. Pages are being initialized for the first time, including during deferred
1189 * memory init; see the call to page_kasan_tag_reset in __init_single_page.
1190 * 2. The allocation was not unpoisoned due to __GFP_SKIP_KASAN, with the
1191 * exception of pages unpoisoned by kasan_unpoison_vmalloc.
1192 * 3. The allocation was excluded from being checked due to sampling,
1193 * see the call to kasan_unpoison_pages.
1194 *
1195 * Poisoning pages during deferred memory init will greatly lengthen the
1196 * process and cause problem in large memory systems as the deferred pages
1197 * initialization is done with interrupt disabled.
1198 *
1199 * Assuming that there will be no reference to those newly initialized
1200 * pages before they are ever allocated, this should have no effect on
1201 * KASAN memory tracking as the poison will be properly inserted at page
1202 * allocation time. The only corner case is when pages are allocated by
1203 * on-demand allocation and then freed again before the deferred pages
1204 * initialization is done, but this is not likely to happen.
1205 */
should_skip_kasan_poison(struct page * page)1206 static inline bool should_skip_kasan_poison(struct page *page)
1207 {
1208 if (IS_ENABLED(CONFIG_KASAN_GENERIC))
1209 return deferred_pages_enabled();
1210
1211 return page_kasan_tag(page) == KASAN_TAG_KERNEL;
1212 }
1213
kernel_init_pages(struct page * page,int numpages)1214 static void kernel_init_pages(struct page *page, int numpages)
1215 {
1216 int i;
1217
1218 /* s390's use of memset() could override KASAN redzones. */
1219 kasan_disable_current();
1220 for (i = 0; i < numpages; i++)
1221 clear_highpage_kasan_tagged(page + i);
1222 kasan_enable_current();
1223 }
1224
1225 #ifdef CONFIG_MEM_ALLOC_PROFILING
1226
1227 /* Should be called only if mem_alloc_profiling_enabled() */
__clear_page_tag_ref(struct page * page)1228 void __clear_page_tag_ref(struct page *page)
1229 {
1230 union pgtag_ref_handle handle;
1231 union codetag_ref ref;
1232
1233 if (get_page_tag_ref(page, &ref, &handle)) {
1234 set_codetag_empty(&ref);
1235 update_page_tag_ref(handle, &ref);
1236 put_page_tag_ref(handle);
1237 }
1238 }
1239
1240 /* Should be called only if mem_alloc_profiling_enabled() */
1241 static noinline
__pgalloc_tag_add(struct page * page,struct task_struct * task,unsigned int nr)1242 void __pgalloc_tag_add(struct page *page, struct task_struct *task,
1243 unsigned int nr)
1244 {
1245 union pgtag_ref_handle handle;
1246 union codetag_ref ref;
1247
1248 if (likely(get_page_tag_ref(page, &ref, &handle))) {
1249 alloc_tag_add(&ref, task->alloc_tag, PAGE_SIZE * nr);
1250 update_page_tag_ref(handle, &ref);
1251 put_page_tag_ref(handle);
1252 } else {
1253 /*
1254 * page_ext is not available yet, record the pfn so we can
1255 * clear the tag ref later when page_ext is initialized.
1256 */
1257 alloc_tag_add_early_pfn(page_to_pfn(page));
1258 if (task->alloc_tag)
1259 alloc_tag_set_inaccurate(task->alloc_tag);
1260 }
1261 }
1262
pgalloc_tag_add(struct page * page,struct task_struct * task,unsigned int nr)1263 static inline void pgalloc_tag_add(struct page *page, struct task_struct *task,
1264 unsigned int nr)
1265 {
1266 if (mem_alloc_profiling_enabled())
1267 __pgalloc_tag_add(page, task, nr);
1268 }
1269
1270 /* Should be called only if mem_alloc_profiling_enabled() */
1271 static noinline
__pgalloc_tag_sub(struct page * page,unsigned int nr)1272 void __pgalloc_tag_sub(struct page *page, unsigned int nr)
1273 {
1274 union pgtag_ref_handle handle;
1275 union codetag_ref ref;
1276
1277 if (get_page_tag_ref(page, &ref, &handle)) {
1278 alloc_tag_sub(&ref, PAGE_SIZE * nr);
1279 update_page_tag_ref(handle, &ref);
1280 put_page_tag_ref(handle);
1281 }
1282 }
1283
pgalloc_tag_sub(struct page * page,unsigned int nr)1284 static inline void pgalloc_tag_sub(struct page *page, unsigned int nr)
1285 {
1286 if (mem_alloc_profiling_enabled())
1287 __pgalloc_tag_sub(page, nr);
1288 }
1289
1290 /* When tag is not NULL, assuming mem_alloc_profiling_enabled */
pgalloc_tag_sub_pages(struct alloc_tag * tag,unsigned int nr)1291 static inline void pgalloc_tag_sub_pages(struct alloc_tag *tag, unsigned int nr)
1292 {
1293 if (tag)
1294 this_cpu_sub(tag->counters->bytes, PAGE_SIZE * nr);
1295 }
1296
1297 #else /* CONFIG_MEM_ALLOC_PROFILING */
1298
pgalloc_tag_add(struct page * page,struct task_struct * task,unsigned int nr)1299 static inline void pgalloc_tag_add(struct page *page, struct task_struct *task,
1300 unsigned int nr) {}
pgalloc_tag_sub(struct page * page,unsigned int nr)1301 static inline void pgalloc_tag_sub(struct page *page, unsigned int nr) {}
pgalloc_tag_sub_pages(struct alloc_tag * tag,unsigned int nr)1302 static inline void pgalloc_tag_sub_pages(struct alloc_tag *tag, unsigned int nr) {}
1303
1304 #endif /* CONFIG_MEM_ALLOC_PROFILING */
1305
__free_pages_prepare(struct page * page,unsigned int order,fpi_t fpi_flags)1306 __always_inline bool __free_pages_prepare(struct page *page,
1307 unsigned int order, fpi_t fpi_flags)
1308 {
1309 int bad = 0;
1310 bool skip_kasan_poison = should_skip_kasan_poison(page);
1311 bool init = want_init_on_free();
1312 bool compound = PageCompound(page);
1313 struct folio *folio = page_folio(page);
1314
1315 VM_BUG_ON_PAGE(PageTail(page), page);
1316
1317 trace_mm_page_free(page, order);
1318 kmsan_free_page(page, order);
1319
1320 if (memcg_kmem_online() && PageMemcgKmem(page))
1321 __memcg_kmem_uncharge_page(page, order);
1322
1323 /*
1324 * In rare cases, when truncation or holepunching raced with
1325 * munlock after VM_LOCKED was cleared, Mlocked may still be
1326 * found set here. This does not indicate a problem, unless
1327 * "unevictable_pgs_cleared" appears worryingly large.
1328 */
1329 if (unlikely(folio_test_mlocked(folio))) {
1330 long nr_pages = folio_nr_pages(folio);
1331
1332 __folio_clear_mlocked(folio);
1333 zone_stat_mod_folio(folio, NR_MLOCK, -nr_pages);
1334 count_vm_events(UNEVICTABLE_PGCLEARED, nr_pages);
1335 }
1336
1337 if (unlikely(PageHWPoison(page)) && !order) {
1338 /* Do not let hwpoison pages hit pcplists/buddy */
1339 reset_page_owner(page, order);
1340 page_table_check_free(page, order);
1341 pgalloc_tag_sub(page, 1 << order);
1342
1343 /*
1344 * The page is isolated and accounted for.
1345 * Mark the codetag as empty to avoid accounting error
1346 * when the page is freed by unpoison_memory().
1347 */
1348 clear_page_tag_ref(page);
1349 return false;
1350 }
1351
1352 VM_BUG_ON_PAGE(compound && compound_order(page) != order, page);
1353
1354 /*
1355 * Check tail pages before head page information is cleared to
1356 * avoid checking PageCompound for order-0 pages.
1357 */
1358 if (unlikely(order)) {
1359 int i;
1360
1361 if (compound) {
1362 page[1].flags.f &= ~PAGE_FLAGS_SECOND;
1363 #ifdef NR_PAGES_IN_LARGE_FOLIO
1364 folio->_nr_pages = 0;
1365 #endif
1366 }
1367 for (i = 1; i < (1 << order); i++) {
1368 if (compound)
1369 bad += free_tail_page_prepare(page, page + i);
1370 if (is_check_pages_enabled()) {
1371 if (free_page_is_bad(page + i)) {
1372 bad++;
1373 continue;
1374 }
1375 }
1376 (page + i)->flags.f &= ~PAGE_FLAGS_CHECK_AT_PREP;
1377 }
1378 }
1379 if (folio_test_anon(folio)) {
1380 mod_mthp_stat(order, MTHP_STAT_NR_ANON, -1);
1381 folio->mapping = NULL;
1382 }
1383 if (unlikely(page_has_type(page)))
1384 /* Reset the page_type (which overlays _mapcount) */
1385 page->page_type = UINT_MAX;
1386
1387 if (is_check_pages_enabled()) {
1388 if (free_page_is_bad(page))
1389 bad++;
1390 if (bad)
1391 return false;
1392 }
1393
1394 page_cpupid_reset_last(page);
1395 page->flags.f &= ~PAGE_FLAGS_CHECK_AT_PREP;
1396 page->private = 0;
1397 reset_page_owner(page, order);
1398 page_table_check_free(page, order);
1399 pgalloc_tag_sub(page, 1 << order);
1400
1401 if (!PageHighMem(page) && !(fpi_flags & FPI_TRYLOCK)) {
1402 debug_check_no_locks_freed(page_address(page),
1403 PAGE_SIZE << order);
1404 debug_check_no_obj_freed(page_address(page),
1405 PAGE_SIZE << order);
1406 }
1407
1408 kernel_poison_pages(page, 1 << order);
1409
1410 /*
1411 * As memory initialization might be integrated into KASAN,
1412 * KASAN poisoning and memory initialization code must be
1413 * kept together to avoid discrepancies in behavior.
1414 *
1415 * With hardware tag-based KASAN, memory tags must be set before the
1416 * page becomes unavailable via debug_pagealloc or arch_free_page.
1417 */
1418 if (!skip_kasan_poison) {
1419 kasan_poison_pages(page, order, init);
1420
1421 /* Memory is already initialized if KASAN did it internally. */
1422 if (kasan_has_integrated_init())
1423 init = false;
1424 }
1425 if (init)
1426 kernel_init_pages(page, 1 << order);
1427
1428 /*
1429 * arch_free_page() can make the page's contents inaccessible. s390
1430 * does this. So nothing which can access the page's contents should
1431 * happen after this.
1432 */
1433 arch_free_page(page, order);
1434
1435 debug_pagealloc_unmap_pages(page, 1 << order);
1436
1437 return true;
1438 }
1439
free_pages_prepare(struct page * page,unsigned int order)1440 bool free_pages_prepare(struct page *page, unsigned int order)
1441 {
1442 return __free_pages_prepare(page, order, FPI_NONE);
1443 }
1444
1445 /*
1446 * Frees a number of pages from the PCP lists
1447 * Assumes all pages on list are in same zone.
1448 * count is the number of pages to free.
1449 */
free_pcppages_bulk(struct zone * zone,int count,struct per_cpu_pages * pcp,int pindex)1450 static void free_pcppages_bulk(struct zone *zone, int count,
1451 struct per_cpu_pages *pcp,
1452 int pindex)
1453 {
1454 unsigned long flags;
1455 unsigned int order;
1456 struct page *page;
1457
1458 /*
1459 * Ensure proper count is passed which otherwise would stuck in the
1460 * below while (list_empty(list)) loop.
1461 */
1462 count = min(pcp->count, count);
1463
1464 /* Ensure requested pindex is drained first. */
1465 pindex = pindex - 1;
1466
1467 spin_lock_irqsave(&zone->lock, flags);
1468
1469 while (count > 0) {
1470 struct list_head *list;
1471 int nr_pages;
1472
1473 /* Remove pages from lists in a round-robin fashion. */
1474 do {
1475 if (++pindex > NR_PCP_LISTS - 1)
1476 pindex = 0;
1477 list = &pcp->lists[pindex];
1478 } while (list_empty(list));
1479
1480 order = pindex_to_order(pindex);
1481 nr_pages = 1 << order;
1482 do {
1483 unsigned long pfn;
1484 int mt;
1485
1486 page = list_last_entry(list, struct page, pcp_list);
1487 pfn = page_to_pfn(page);
1488 mt = get_pfnblock_migratetype(page, pfn);
1489
1490 /* must delete to avoid corrupting pcp list */
1491 list_del(&page->pcp_list);
1492 count -= nr_pages;
1493 pcp->count -= nr_pages;
1494
1495 __free_one_page(page, pfn, zone, order, mt, FPI_NONE);
1496 trace_mm_page_pcpu_drain(page, order, mt);
1497 } while (count > 0 && !list_empty(list));
1498 }
1499
1500 spin_unlock_irqrestore(&zone->lock, flags);
1501 }
1502
1503 /* Split a multi-block free page into its individual pageblocks. */
split_large_buddy(struct zone * zone,struct page * page,unsigned long pfn,int order,fpi_t fpi)1504 static void split_large_buddy(struct zone *zone, struct page *page,
1505 unsigned long pfn, int order, fpi_t fpi)
1506 {
1507 unsigned long end = pfn + (1 << order);
1508
1509 VM_WARN_ON_ONCE(!IS_ALIGNED(pfn, 1 << order));
1510 /* Caller removed page from freelist, buddy info cleared! */
1511 VM_WARN_ON_ONCE(PageBuddy(page));
1512
1513 if (order > pageblock_order)
1514 order = pageblock_order;
1515
1516 do {
1517 int mt = get_pfnblock_migratetype(page, pfn);
1518
1519 __free_one_page(page, pfn, zone, order, mt, fpi);
1520 pfn += 1 << order;
1521 if (pfn == end)
1522 break;
1523 page = pfn_to_page(pfn);
1524 } while (1);
1525 }
1526
add_page_to_zone_llist(struct zone * zone,struct page * page,unsigned int order)1527 static void add_page_to_zone_llist(struct zone *zone, struct page *page,
1528 unsigned int order)
1529 {
1530 /* Remember the order */
1531 page->private = order;
1532 /* Add the page to the free list */
1533 llist_add(&page->pcp_llist, &zone->trylock_free_pages);
1534 }
1535
free_one_page(struct zone * zone,struct page * page,unsigned long pfn,unsigned int order,fpi_t fpi_flags)1536 static void free_one_page(struct zone *zone, struct page *page,
1537 unsigned long pfn, unsigned int order,
1538 fpi_t fpi_flags)
1539 {
1540 struct llist_head *llhead;
1541 unsigned long flags;
1542
1543 if (unlikely(fpi_flags & FPI_TRYLOCK)) {
1544 if (!spin_trylock_irqsave(&zone->lock, flags)) {
1545 add_page_to_zone_llist(zone, page, order);
1546 return;
1547 }
1548 } else {
1549 spin_lock_irqsave(&zone->lock, flags);
1550 }
1551
1552 /* The lock succeeded. Process deferred pages. */
1553 llhead = &zone->trylock_free_pages;
1554 if (unlikely(!llist_empty(llhead) && !(fpi_flags & FPI_TRYLOCK))) {
1555 struct llist_node *llnode;
1556 struct page *p, *tmp;
1557
1558 llnode = llist_del_all(llhead);
1559 llist_for_each_entry_safe(p, tmp, llnode, pcp_llist) {
1560 unsigned int p_order = p->private;
1561
1562 split_large_buddy(zone, p, page_to_pfn(p), p_order, fpi_flags);
1563 __count_vm_events(PGFREE, 1 << p_order);
1564 }
1565 }
1566 split_large_buddy(zone, page, pfn, order, fpi_flags);
1567 spin_unlock_irqrestore(&zone->lock, flags);
1568
1569 __count_vm_events(PGFREE, 1 << order);
1570 }
1571
__free_pages_ok(struct page * page,unsigned int order,fpi_t fpi_flags)1572 static void __free_pages_ok(struct page *page, unsigned int order,
1573 fpi_t fpi_flags)
1574 {
1575 unsigned long pfn = page_to_pfn(page);
1576 struct zone *zone = page_zone(page);
1577
1578 if (__free_pages_prepare(page, order, fpi_flags))
1579 free_one_page(zone, page, pfn, order, fpi_flags);
1580 }
1581
__free_pages_core(struct page * page,unsigned int order,enum meminit_context context)1582 void __meminit __free_pages_core(struct page *page, unsigned int order,
1583 enum meminit_context context)
1584 {
1585 unsigned int nr_pages = 1 << order;
1586 struct page *p = page;
1587 unsigned int loop;
1588
1589 /*
1590 * When initializing the memmap, __init_single_page() sets the refcount
1591 * of all pages to 1 ("allocated"/"not free"). We have to set the
1592 * refcount of all involved pages to 0.
1593 *
1594 * Note that hotplugged memory pages are initialized to PageOffline().
1595 * Pages freed from memblock might be marked as reserved.
1596 */
1597 if (IS_ENABLED(CONFIG_MEMORY_HOTPLUG) &&
1598 unlikely(context == MEMINIT_HOTPLUG)) {
1599 for (loop = 0; loop < nr_pages; loop++, p++) {
1600 VM_WARN_ON_ONCE(PageReserved(p));
1601 __ClearPageOffline(p);
1602 set_page_count(p, 0);
1603 }
1604
1605 adjust_managed_page_count(page, nr_pages);
1606 } else {
1607 for (loop = 0; loop < nr_pages; loop++, p++) {
1608 __ClearPageReserved(p);
1609 set_page_count(p, 0);
1610 }
1611
1612 /* memblock adjusts totalram_pages() manually. */
1613 atomic_long_add(nr_pages, &page_zone(page)->managed_pages);
1614 }
1615
1616 if (page_contains_unaccepted(page, order)) {
1617 if (order == MAX_PAGE_ORDER && __free_unaccepted(page))
1618 return;
1619
1620 accept_memory(page_to_phys(page), PAGE_SIZE << order);
1621 }
1622
1623 /*
1624 * Bypass PCP and place fresh pages right to the tail, primarily
1625 * relevant for memory onlining.
1626 */
1627 __free_pages_ok(page, order, FPI_TO_TAIL);
1628 }
1629
1630 /*
1631 * Check that the whole (or subset of) a pageblock given by the interval of
1632 * [start_pfn, end_pfn) is valid and within the same zone, before scanning it
1633 * with the migration of free compaction scanner.
1634 *
1635 * Return struct page pointer of start_pfn, or NULL if checks were not passed.
1636 *
1637 * It's possible on some configurations to have a setup like node0 node1 node0
1638 * i.e. it's possible that all pages within a zones range of pages do not
1639 * belong to a single zone. We assume that a border between node0 and node1
1640 * can occur within a single pageblock, but not a node0 node1 node0
1641 * interleaving within a single pageblock. It is therefore sufficient to check
1642 * the first and last page of a pageblock and avoid checking each individual
1643 * page in a pageblock.
1644 *
1645 * Note: the function may return non-NULL struct page even for a page block
1646 * which contains a memory hole (i.e. there is no physical memory for a subset
1647 * of the pfn range). For example, if the pageblock order is MAX_PAGE_ORDER, which
1648 * will fall into 2 sub-sections, and the end pfn of the pageblock may be hole
1649 * even though the start pfn is online and valid. This should be safe most of
1650 * the time because struct pages are still initialized via init_unavailable_range()
1651 * and pfn walkers shouldn't touch any physical memory range for which they do
1652 * not recognize any specific metadata in struct pages.
1653 */
__pageblock_pfn_to_page(unsigned long start_pfn,unsigned long end_pfn,struct zone * zone)1654 struct page *__pageblock_pfn_to_page(unsigned long start_pfn,
1655 unsigned long end_pfn, struct zone *zone)
1656 {
1657 struct page *start_page;
1658 struct page *end_page;
1659
1660 /* end_pfn is one past the range we are checking */
1661 end_pfn--;
1662
1663 if (!pfn_valid(end_pfn))
1664 return NULL;
1665
1666 start_page = pfn_to_online_page(start_pfn);
1667 if (!start_page)
1668 return NULL;
1669
1670 if (page_zone(start_page) != zone)
1671 return NULL;
1672
1673 end_page = pfn_to_page(end_pfn);
1674
1675 /* This gives a shorter code than deriving page_zone(end_page) */
1676 if (page_zone_id(start_page) != page_zone_id(end_page))
1677 return NULL;
1678
1679 return start_page;
1680 }
1681
1682 /*
1683 * The order of subdivision here is critical for the IO subsystem.
1684 * Please do not alter this order without good reasons and regression
1685 * testing. Specifically, as large blocks of memory are subdivided,
1686 * the order in which smaller blocks are delivered depends on the order
1687 * they're subdivided in this function. This is the primary factor
1688 * influencing the order in which pages are delivered to the IO
1689 * subsystem according to empirical testing, and this is also justified
1690 * by considering the behavior of a buddy system containing a single
1691 * large block of memory acted on by a series of small allocations.
1692 * This behavior is a critical factor in sglist merging's success.
1693 *
1694 * -- nyc
1695 */
expand(struct zone * zone,struct page * page,int low,int high,int migratetype)1696 static inline unsigned int expand(struct zone *zone, struct page *page, int low,
1697 int high, int migratetype)
1698 {
1699 unsigned int size = 1 << high;
1700 unsigned int nr_added = 0;
1701
1702 while (high > low) {
1703 high--;
1704 size >>= 1;
1705 VM_BUG_ON_PAGE(bad_range(zone, &page[size]), &page[size]);
1706
1707 /*
1708 * Mark as guard pages (or page), that will allow to
1709 * merge back to allocator when buddy will be freed.
1710 * Corresponding page table entries will not be touched,
1711 * pages will stay not present in virtual address space
1712 */
1713 if (set_page_guard(zone, &page[size], high))
1714 continue;
1715
1716 __add_to_free_list(&page[size], zone, high, migratetype, false);
1717 set_buddy_order(&page[size], high);
1718 nr_added += size;
1719 }
1720
1721 return nr_added;
1722 }
1723
page_del_and_expand(struct zone * zone,struct page * page,int low,int high,int migratetype)1724 static __always_inline void page_del_and_expand(struct zone *zone,
1725 struct page *page, int low,
1726 int high, int migratetype)
1727 {
1728 int nr_pages = 1 << high;
1729
1730 __del_page_from_free_list(page, zone, high, migratetype);
1731 nr_pages -= expand(zone, page, low, high, migratetype);
1732 account_freepages(zone, -nr_pages, migratetype);
1733 }
1734
check_new_page_bad(struct page * page)1735 static void check_new_page_bad(struct page *page)
1736 {
1737 if (unlikely(PageHWPoison(page))) {
1738 /* Don't complain about hwpoisoned pages */
1739 if (PageBuddy(page))
1740 __ClearPageBuddy(page);
1741 return;
1742 }
1743
1744 bad_page(page,
1745 page_bad_reason(page, PAGE_FLAGS_CHECK_AT_PREP));
1746 }
1747
1748 /*
1749 * This page is about to be returned from the page allocator
1750 */
check_new_page(struct page * page)1751 static bool check_new_page(struct page *page)
1752 {
1753 if (likely(page_expected_state(page,
1754 PAGE_FLAGS_CHECK_AT_PREP|__PG_HWPOISON)))
1755 return false;
1756
1757 check_new_page_bad(page);
1758 return true;
1759 }
1760
check_new_pages(struct page * page,unsigned int order)1761 static inline bool check_new_pages(struct page *page, unsigned int order)
1762 {
1763 if (is_check_pages_enabled()) {
1764 for (int i = 0; i < (1 << order); i++) {
1765 struct page *p = page + i;
1766
1767 if (check_new_page(p))
1768 return true;
1769 }
1770 }
1771
1772 return false;
1773 }
1774
should_skip_kasan_unpoison(gfp_t flags)1775 static inline bool should_skip_kasan_unpoison(gfp_t flags)
1776 {
1777 /* Don't skip if a software KASAN mode is enabled. */
1778 if (IS_ENABLED(CONFIG_KASAN_GENERIC) ||
1779 IS_ENABLED(CONFIG_KASAN_SW_TAGS))
1780 return false;
1781
1782 /* Skip, if hardware tag-based KASAN is not enabled. */
1783 if (!kasan_hw_tags_enabled())
1784 return true;
1785
1786 /*
1787 * With hardware tag-based KASAN enabled, skip if this has been
1788 * requested via __GFP_SKIP_KASAN.
1789 */
1790 return flags & __GFP_SKIP_KASAN;
1791 }
1792
should_skip_init(gfp_t flags)1793 static inline bool should_skip_init(gfp_t flags)
1794 {
1795 /* Don't skip, if hardware tag-based KASAN is not enabled. */
1796 if (!kasan_hw_tags_enabled())
1797 return false;
1798
1799 /* For hardware tag-based KASAN, skip if requested. */
1800 return (flags & __GFP_SKIP_ZERO);
1801 }
1802
post_alloc_hook(struct page * page,unsigned int order,gfp_t gfp_flags)1803 inline void post_alloc_hook(struct page *page, unsigned int order,
1804 gfp_t gfp_flags)
1805 {
1806 const bool zero_tags = gfp_flags & __GFP_ZEROTAGS;
1807 bool init = !want_init_on_free() && want_init_on_alloc(gfp_flags) &&
1808 !should_skip_init(gfp_flags);
1809 int i;
1810
1811 set_page_private(page, 0);
1812
1813 arch_alloc_page(page, order);
1814 debug_pagealloc_map_pages(page, 1 << order);
1815
1816 /*
1817 * Page unpoisoning must happen before memory initialization.
1818 * Otherwise, the poison pattern will be overwritten for __GFP_ZERO
1819 * allocations and the page unpoisoning code will complain.
1820 */
1821 kernel_unpoison_pages(page, 1 << order);
1822
1823 /*
1824 * As memory initialization might be integrated into KASAN,
1825 * KASAN unpoisoning and memory initialization code must be
1826 * kept together to avoid discrepancies in behavior.
1827 */
1828
1829 /*
1830 * Clearing tags can efficiently clear the memory for us as well, if
1831 * required.
1832 */
1833 if (zero_tags)
1834 init = tag_clear_highpages(page, 1 << order, /* clear_pages= */init);
1835
1836 if (!should_skip_kasan_unpoison(gfp_flags) &&
1837 kasan_unpoison_pages(page, order, init)) {
1838 /* Take note that memory was initialized by KASAN. */
1839 if (kasan_has_integrated_init())
1840 init = false;
1841 } else {
1842 /*
1843 * If memory tags have not been set by KASAN, reset the page
1844 * tags to ensure page_address() dereferencing does not fault.
1845 */
1846 for (i = 0; i != 1 << order; ++i)
1847 page_kasan_tag_reset(page + i);
1848 }
1849 /* If memory is still not initialized, initialize it now. */
1850 if (init)
1851 kernel_init_pages(page, 1 << order);
1852
1853 set_page_owner(page, order, gfp_flags);
1854 page_table_check_alloc(page, order);
1855 pgalloc_tag_add(page, current, 1 << order);
1856 }
1857
prep_new_page(struct page * page,unsigned int order,gfp_t gfp_flags,unsigned int alloc_flags)1858 static void prep_new_page(struct page *page, unsigned int order, gfp_t gfp_flags,
1859 unsigned int alloc_flags)
1860 {
1861 post_alloc_hook(page, order, gfp_flags);
1862
1863 if (order && (gfp_flags & __GFP_COMP))
1864 prep_compound_page(page, order);
1865
1866 /*
1867 * page is set pfmemalloc when ALLOC_NO_WATERMARKS was necessary to
1868 * allocate the page. The expectation is that the caller is taking
1869 * steps that will free more memory. The caller should avoid the page
1870 * being used for !PFMEMALLOC purposes.
1871 */
1872 if (alloc_flags & ALLOC_NO_WATERMARKS)
1873 set_page_pfmemalloc(page);
1874 else
1875 clear_page_pfmemalloc(page);
1876 }
1877
1878 /*
1879 * Go through the free lists for the given migratetype and remove
1880 * the smallest available page from the freelists
1881 */
1882 static __always_inline
__rmqueue_smallest(struct zone * zone,unsigned int order,int migratetype)1883 struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
1884 int migratetype)
1885 {
1886 unsigned int current_order;
1887 struct free_area *area;
1888 struct page *page;
1889
1890 /* Find a page of the appropriate size in the preferred list */
1891 for (current_order = order; current_order < NR_PAGE_ORDERS; ++current_order) {
1892 area = &(zone->free_area[current_order]);
1893 page = get_page_from_free_area(area, migratetype);
1894 if (!page)
1895 continue;
1896
1897 page_del_and_expand(zone, page, order, current_order,
1898 migratetype);
1899 trace_mm_page_alloc_zone_locked(page, order, migratetype,
1900 pcp_allowed_order(order) &&
1901 migratetype < MIGRATE_PCPTYPES);
1902 return page;
1903 }
1904
1905 return NULL;
1906 }
1907
1908
1909 /*
1910 * This array describes the order lists are fallen back to when
1911 * the free lists for the desirable migrate type are depleted
1912 *
1913 * The other migratetypes do not have fallbacks.
1914 */
1915 static int fallbacks[MIGRATE_PCPTYPES][MIGRATE_PCPTYPES - 1] = {
1916 [MIGRATE_UNMOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE },
1917 [MIGRATE_MOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE },
1918 [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE, MIGRATE_MOVABLE },
1919 };
1920
1921 #ifdef CONFIG_CMA
__rmqueue_cma_fallback(struct zone * zone,unsigned int order)1922 static __always_inline struct page *__rmqueue_cma_fallback(struct zone *zone,
1923 unsigned int order)
1924 {
1925 return __rmqueue_smallest(zone, order, MIGRATE_CMA);
1926 }
1927 #else
__rmqueue_cma_fallback(struct zone * zone,unsigned int order)1928 static inline struct page *__rmqueue_cma_fallback(struct zone *zone,
1929 unsigned int order) { return NULL; }
1930 #endif
1931
1932 /*
1933 * Move all free pages of a block to new type's freelist. Caller needs to
1934 * change the block type.
1935 */
__move_freepages_block(struct zone * zone,unsigned long start_pfn,int old_mt,int new_mt)1936 static int __move_freepages_block(struct zone *zone, unsigned long start_pfn,
1937 int old_mt, int new_mt)
1938 {
1939 struct page *page;
1940 unsigned long pfn, end_pfn;
1941 unsigned int order;
1942 int pages_moved = 0;
1943
1944 VM_WARN_ON(start_pfn & (pageblock_nr_pages - 1));
1945 end_pfn = pageblock_end_pfn(start_pfn);
1946
1947 for (pfn = start_pfn; pfn < end_pfn;) {
1948 page = pfn_to_page(pfn);
1949 if (!PageBuddy(page)) {
1950 pfn++;
1951 continue;
1952 }
1953
1954 /* Make sure we are not inadvertently changing nodes */
1955 VM_BUG_ON_PAGE(page_to_nid(page) != zone_to_nid(zone), page);
1956 VM_BUG_ON_PAGE(page_zone(page) != zone, page);
1957
1958 order = buddy_order(page);
1959
1960 move_to_free_list(page, zone, order, old_mt, new_mt);
1961
1962 pfn += 1 << order;
1963 pages_moved += 1 << order;
1964 }
1965
1966 return pages_moved;
1967 }
1968
prep_move_freepages_block(struct zone * zone,struct page * page,unsigned long * start_pfn,int * num_free,int * num_movable)1969 static bool prep_move_freepages_block(struct zone *zone, struct page *page,
1970 unsigned long *start_pfn,
1971 int *num_free, int *num_movable)
1972 {
1973 unsigned long pfn, start, end;
1974
1975 pfn = page_to_pfn(page);
1976 start = pageblock_start_pfn(pfn);
1977 end = pageblock_end_pfn(pfn);
1978
1979 /*
1980 * The caller only has the lock for @zone, don't touch ranges
1981 * that straddle into other zones. While we could move part of
1982 * the range that's inside the zone, this call is usually
1983 * accompanied by other operations such as migratetype updates
1984 * which also should be locked.
1985 */
1986 if (!zone_spans_pfn(zone, start))
1987 return false;
1988 if (!zone_spans_pfn(zone, end - 1))
1989 return false;
1990
1991 *start_pfn = start;
1992
1993 if (num_free) {
1994 *num_free = 0;
1995 *num_movable = 0;
1996 for (pfn = start; pfn < end;) {
1997 page = pfn_to_page(pfn);
1998 if (PageBuddy(page)) {
1999 int nr = 1 << buddy_order(page);
2000
2001 *num_free += nr;
2002 pfn += nr;
2003 continue;
2004 }
2005 /*
2006 * We assume that pages that could be isolated for
2007 * migration are movable. But we don't actually try
2008 * isolating, as that would be expensive.
2009 */
2010 if (PageLRU(page) || page_has_movable_ops(page))
2011 (*num_movable)++;
2012 pfn++;
2013 }
2014 }
2015
2016 return true;
2017 }
2018
move_freepages_block(struct zone * zone,struct page * page,int old_mt,int new_mt)2019 static int move_freepages_block(struct zone *zone, struct page *page,
2020 int old_mt, int new_mt)
2021 {
2022 unsigned long start_pfn;
2023 int res;
2024
2025 if (!prep_move_freepages_block(zone, page, &start_pfn, NULL, NULL))
2026 return -1;
2027
2028 res = __move_freepages_block(zone, start_pfn, old_mt, new_mt);
2029 set_pageblock_migratetype(pfn_to_page(start_pfn), new_mt);
2030
2031 return res;
2032
2033 }
2034
2035 #ifdef CONFIG_MEMORY_ISOLATION
2036 /* Look for a buddy that straddles start_pfn */
find_large_buddy(unsigned long start_pfn)2037 static unsigned long find_large_buddy(unsigned long start_pfn)
2038 {
2039 /*
2040 * If start_pfn is not an order-0 PageBuddy, next PageBuddy containing
2041 * start_pfn has minimal order of __ffs(start_pfn) + 1. Start checking
2042 * the order with __ffs(start_pfn). If start_pfn is order-0 PageBuddy,
2043 * the starting order does not matter.
2044 */
2045 int order = start_pfn ? __ffs(start_pfn) : MAX_PAGE_ORDER;
2046 struct page *page;
2047 unsigned long pfn = start_pfn;
2048
2049 while (!PageBuddy(page = pfn_to_page(pfn))) {
2050 /* Nothing found */
2051 if (++order > MAX_PAGE_ORDER)
2052 return start_pfn;
2053 pfn &= ~0UL << order;
2054 }
2055
2056 /*
2057 * Found a preceding buddy, but does it straddle?
2058 */
2059 if (pfn + (1 << buddy_order(page)) > start_pfn)
2060 return pfn;
2061
2062 /* Nothing found */
2063 return start_pfn;
2064 }
2065
toggle_pageblock_isolate(struct page * page,bool isolate)2066 static inline void toggle_pageblock_isolate(struct page *page, bool isolate)
2067 {
2068 if (isolate)
2069 set_pageblock_isolate(page);
2070 else
2071 clear_pageblock_isolate(page);
2072 }
2073
2074 /**
2075 * __move_freepages_block_isolate - move free pages in block for page isolation
2076 * @zone: the zone
2077 * @page: the pageblock page
2078 * @isolate: to isolate the given pageblock or unisolate it
2079 *
2080 * This is similar to move_freepages_block(), but handles the special
2081 * case encountered in page isolation, where the block of interest
2082 * might be part of a larger buddy spanning multiple pageblocks.
2083 *
2084 * Unlike the regular page allocator path, which moves pages while
2085 * stealing buddies off the freelist, page isolation is interested in
2086 * arbitrary pfn ranges that may have overlapping buddies on both ends.
2087 *
2088 * This function handles that. Straddling buddies are split into
2089 * individual pageblocks. Only the block of interest is moved.
2090 *
2091 * Returns %true if pages could be moved, %false otherwise.
2092 */
__move_freepages_block_isolate(struct zone * zone,struct page * page,bool isolate)2093 static bool __move_freepages_block_isolate(struct zone *zone,
2094 struct page *page, bool isolate)
2095 {
2096 unsigned long start_pfn, buddy_pfn;
2097 int from_mt;
2098 int to_mt;
2099 struct page *buddy;
2100
2101 if (isolate == get_pageblock_isolate(page)) {
2102 VM_WARN_ONCE(1, "%s a pageblock that is already in that state",
2103 isolate ? "Isolate" : "Unisolate");
2104 return false;
2105 }
2106
2107 if (!prep_move_freepages_block(zone, page, &start_pfn, NULL, NULL))
2108 return false;
2109
2110 /* No splits needed if buddies can't span multiple blocks */
2111 if (pageblock_order == MAX_PAGE_ORDER)
2112 goto move;
2113
2114 buddy_pfn = find_large_buddy(start_pfn);
2115 buddy = pfn_to_page(buddy_pfn);
2116 /* We're a part of a larger buddy */
2117 if (PageBuddy(buddy) && buddy_order(buddy) > pageblock_order) {
2118 int order = buddy_order(buddy);
2119
2120 del_page_from_free_list(buddy, zone, order,
2121 get_pfnblock_migratetype(buddy, buddy_pfn));
2122 toggle_pageblock_isolate(page, isolate);
2123 split_large_buddy(zone, buddy, buddy_pfn, order, FPI_NONE);
2124 return true;
2125 }
2126
2127 move:
2128 /* Use MIGRATETYPE_MASK to get non-isolate migratetype */
2129 if (isolate) {
2130 from_mt = __get_pfnblock_flags_mask(page, page_to_pfn(page),
2131 MIGRATETYPE_MASK);
2132 to_mt = MIGRATE_ISOLATE;
2133 } else {
2134 from_mt = MIGRATE_ISOLATE;
2135 to_mt = __get_pfnblock_flags_mask(page, page_to_pfn(page),
2136 MIGRATETYPE_MASK);
2137 }
2138
2139 __move_freepages_block(zone, start_pfn, from_mt, to_mt);
2140 toggle_pageblock_isolate(pfn_to_page(start_pfn), isolate);
2141
2142 return true;
2143 }
2144
pageblock_isolate_and_move_free_pages(struct zone * zone,struct page * page)2145 bool pageblock_isolate_and_move_free_pages(struct zone *zone, struct page *page)
2146 {
2147 return __move_freepages_block_isolate(zone, page, true);
2148 }
2149
pageblock_unisolate_and_move_free_pages(struct zone * zone,struct page * page)2150 bool pageblock_unisolate_and_move_free_pages(struct zone *zone, struct page *page)
2151 {
2152 return __move_freepages_block_isolate(zone, page, false);
2153 }
2154
2155 #endif /* CONFIG_MEMORY_ISOLATION */
2156
boost_watermark(struct zone * zone)2157 static inline bool boost_watermark(struct zone *zone)
2158 {
2159 unsigned long max_boost;
2160
2161 if (!watermark_boost_factor)
2162 return false;
2163 /*
2164 * Don't bother in zones that are unlikely to produce results.
2165 * On small machines, including kdump capture kernels running
2166 * in a small area, boosting the watermark can cause an out of
2167 * memory situation immediately.
2168 */
2169 if ((pageblock_nr_pages * 4) > zone_managed_pages(zone))
2170 return false;
2171
2172 max_boost = mult_frac(zone->_watermark[WMARK_HIGH],
2173 watermark_boost_factor, 10000);
2174
2175 /*
2176 * high watermark may be uninitialised if fragmentation occurs
2177 * very early in boot so do not boost. We do not fall
2178 * through and boost by pageblock_nr_pages as failing
2179 * allocations that early means that reclaim is not going
2180 * to help and it may even be impossible to reclaim the
2181 * boosted watermark resulting in a hang.
2182 */
2183 if (!max_boost)
2184 return false;
2185
2186 max_boost = max(pageblock_nr_pages, max_boost);
2187
2188 zone->watermark_boost = min(zone->watermark_boost + pageblock_nr_pages,
2189 max_boost);
2190
2191 return true;
2192 }
2193
2194 /*
2195 * When we are falling back to another migratetype during allocation, should we
2196 * try to claim an entire block to satisfy further allocations, instead of
2197 * polluting multiple pageblocks?
2198 */
should_try_claim_block(unsigned int order,int start_mt)2199 static bool should_try_claim_block(unsigned int order, int start_mt)
2200 {
2201 /*
2202 * Leaving this order check is intended, although there is
2203 * relaxed order check in next check. The reason is that
2204 * we can actually claim the whole pageblock if this condition met,
2205 * but, below check doesn't guarantee it and that is just heuristic
2206 * so could be changed anytime.
2207 */
2208 if (order >= pageblock_order)
2209 return true;
2210
2211 /*
2212 * Above a certain threshold, always try to claim, as it's likely there
2213 * will be more free pages in the pageblock.
2214 */
2215 if (order >= pageblock_order / 2)
2216 return true;
2217
2218 /*
2219 * Unmovable/reclaimable allocations would cause permanent
2220 * fragmentations if they fell back to allocating from a movable block
2221 * (polluting it), so we try to claim the whole block regardless of the
2222 * allocation size. Later movable allocations can always steal from this
2223 * block, which is less problematic.
2224 */
2225 if (start_mt == MIGRATE_RECLAIMABLE || start_mt == MIGRATE_UNMOVABLE)
2226 return true;
2227
2228 if (page_group_by_mobility_disabled)
2229 return true;
2230
2231 /*
2232 * Movable pages won't cause permanent fragmentation, so when you alloc
2233 * small pages, we just need to temporarily steal unmovable or
2234 * reclaimable pages that are closest to the request size. After a
2235 * while, memory compaction may occur to form large contiguous pages,
2236 * and the next movable allocation may not need to steal.
2237 */
2238 return false;
2239 }
2240
2241 /*
2242 * Check whether there is a suitable fallback freepage with requested order.
2243 * If claimable is true, this function returns fallback_mt only if
2244 * we would do this whole-block claiming. This would help to reduce
2245 * fragmentation due to mixed migratetype pages in one pageblock.
2246 */
find_suitable_fallback(struct free_area * area,unsigned int order,int migratetype,bool claimable)2247 int find_suitable_fallback(struct free_area *area, unsigned int order,
2248 int migratetype, bool claimable)
2249 {
2250 int i;
2251
2252 if (claimable && !should_try_claim_block(order, migratetype))
2253 return -2;
2254
2255 if (area->nr_free == 0)
2256 return -1;
2257
2258 for (i = 0; i < MIGRATE_PCPTYPES - 1 ; i++) {
2259 int fallback_mt = fallbacks[migratetype][i];
2260
2261 if (!free_area_empty(area, fallback_mt))
2262 return fallback_mt;
2263 }
2264
2265 return -1;
2266 }
2267
2268 /*
2269 * This function implements actual block claiming behaviour. If order is large
2270 * enough, we can claim the whole pageblock for the requested migratetype. If
2271 * not, we check the pageblock for constituent pages; if at least half of the
2272 * pages are free or compatible, we can still claim the whole block, so pages
2273 * freed in the future will be put on the correct free list.
2274 */
2275 static struct page *
try_to_claim_block(struct zone * zone,struct page * page,int current_order,int order,int start_type,int block_type,unsigned int alloc_flags)2276 try_to_claim_block(struct zone *zone, struct page *page,
2277 int current_order, int order, int start_type,
2278 int block_type, unsigned int alloc_flags)
2279 {
2280 int free_pages, movable_pages, alike_pages;
2281 unsigned long start_pfn;
2282
2283 /* Take ownership for orders >= pageblock_order */
2284 if (current_order >= pageblock_order) {
2285 unsigned int nr_added;
2286
2287 del_page_from_free_list(page, zone, current_order, block_type);
2288 change_pageblock_range(page, current_order, start_type);
2289 nr_added = expand(zone, page, order, current_order, start_type);
2290 account_freepages(zone, nr_added, start_type);
2291 return page;
2292 }
2293
2294 /*
2295 * Boost watermarks to increase reclaim pressure to reduce the
2296 * likelihood of future fallbacks. Wake kswapd now as the node
2297 * may be balanced overall and kswapd will not wake naturally.
2298 */
2299 if (boost_watermark(zone) && (alloc_flags & ALLOC_KSWAPD))
2300 set_bit(ZONE_BOOSTED_WATERMARK, &zone->flags);
2301
2302 /* moving whole block can fail due to zone boundary conditions */
2303 if (!prep_move_freepages_block(zone, page, &start_pfn, &free_pages,
2304 &movable_pages))
2305 return NULL;
2306
2307 /*
2308 * Determine how many pages are compatible with our allocation.
2309 * For movable allocation, it's the number of movable pages which
2310 * we just obtained. For other types it's a bit more tricky.
2311 */
2312 if (start_type == MIGRATE_MOVABLE) {
2313 alike_pages = movable_pages;
2314 } else {
2315 /*
2316 * If we are falling back a RECLAIMABLE or UNMOVABLE allocation
2317 * to MOVABLE pageblock, consider all non-movable pages as
2318 * compatible. If it's UNMOVABLE falling back to RECLAIMABLE or
2319 * vice versa, be conservative since we can't distinguish the
2320 * exact migratetype of non-movable pages.
2321 */
2322 if (block_type == MIGRATE_MOVABLE)
2323 alike_pages = pageblock_nr_pages
2324 - (free_pages + movable_pages);
2325 else
2326 alike_pages = 0;
2327 }
2328 /*
2329 * If a sufficient number of pages in the block are either free or of
2330 * compatible migratability as our allocation, claim the whole block.
2331 */
2332 if (free_pages + alike_pages >= (1 << (pageblock_order-1)) ||
2333 page_group_by_mobility_disabled) {
2334 __move_freepages_block(zone, start_pfn, block_type, start_type);
2335 set_pageblock_migratetype(pfn_to_page(start_pfn), start_type);
2336 return __rmqueue_smallest(zone, order, start_type);
2337 }
2338
2339 return NULL;
2340 }
2341
2342 /*
2343 * Try to allocate from some fallback migratetype by claiming the entire block,
2344 * i.e. converting it to the allocation's start migratetype.
2345 *
2346 * The use of signed ints for order and current_order is a deliberate
2347 * deviation from the rest of this file, to make the for loop
2348 * condition simpler.
2349 */
2350 static __always_inline struct page *
__rmqueue_claim(struct zone * zone,int order,int start_migratetype,unsigned int alloc_flags)2351 __rmqueue_claim(struct zone *zone, int order, int start_migratetype,
2352 unsigned int alloc_flags)
2353 {
2354 struct free_area *area;
2355 int current_order;
2356 int min_order = order;
2357 struct page *page;
2358 int fallback_mt;
2359
2360 /*
2361 * Do not steal pages from freelists belonging to other pageblocks
2362 * i.e. orders < pageblock_order. If there are no local zones free,
2363 * the zonelists will be reiterated without ALLOC_NOFRAGMENT.
2364 */
2365 if (order < pageblock_order && alloc_flags & ALLOC_NOFRAGMENT)
2366 min_order = pageblock_order;
2367
2368 /*
2369 * Find the largest available free page in the other list. This roughly
2370 * approximates finding the pageblock with the most free pages, which
2371 * would be too costly to do exactly.
2372 */
2373 for (current_order = MAX_PAGE_ORDER; current_order >= min_order;
2374 --current_order) {
2375 area = &(zone->free_area[current_order]);
2376 fallback_mt = find_suitable_fallback(area, current_order,
2377 start_migratetype, true);
2378
2379 /* No block in that order */
2380 if (fallback_mt == -1)
2381 continue;
2382
2383 /* Advanced into orders too low to claim, abort */
2384 if (fallback_mt == -2)
2385 break;
2386
2387 page = get_page_from_free_area(area, fallback_mt);
2388 page = try_to_claim_block(zone, page, current_order, order,
2389 start_migratetype, fallback_mt,
2390 alloc_flags);
2391 if (page) {
2392 trace_mm_page_alloc_extfrag(page, order, current_order,
2393 start_migratetype, fallback_mt);
2394 return page;
2395 }
2396 }
2397
2398 return NULL;
2399 }
2400
2401 /*
2402 * Try to steal a single page from some fallback migratetype. Leave the rest of
2403 * the block as its current migratetype, potentially causing fragmentation.
2404 */
2405 static __always_inline struct page *
__rmqueue_steal(struct zone * zone,int order,int start_migratetype)2406 __rmqueue_steal(struct zone *zone, int order, int start_migratetype)
2407 {
2408 struct free_area *area;
2409 int current_order;
2410 struct page *page;
2411 int fallback_mt;
2412
2413 for (current_order = order; current_order < NR_PAGE_ORDERS; current_order++) {
2414 area = &(zone->free_area[current_order]);
2415 fallback_mt = find_suitable_fallback(area, current_order,
2416 start_migratetype, false);
2417 if (fallback_mt == -1)
2418 continue;
2419
2420 page = get_page_from_free_area(area, fallback_mt);
2421 page_del_and_expand(zone, page, order, current_order, fallback_mt);
2422 trace_mm_page_alloc_extfrag(page, order, current_order,
2423 start_migratetype, fallback_mt);
2424 return page;
2425 }
2426
2427 return NULL;
2428 }
2429
2430 enum rmqueue_mode {
2431 RMQUEUE_NORMAL,
2432 RMQUEUE_CMA,
2433 RMQUEUE_CLAIM,
2434 RMQUEUE_STEAL,
2435 };
2436
2437 /*
2438 * Do the hard work of removing an element from the buddy allocator.
2439 * Call me with the zone->lock already held.
2440 */
2441 static __always_inline struct page *
__rmqueue(struct zone * zone,unsigned int order,int migratetype,unsigned int alloc_flags,enum rmqueue_mode * mode)2442 __rmqueue(struct zone *zone, unsigned int order, int migratetype,
2443 unsigned int alloc_flags, enum rmqueue_mode *mode)
2444 {
2445 struct page *page;
2446
2447 if (IS_ENABLED(CONFIG_CMA)) {
2448 /*
2449 * Balance movable allocations between regular and CMA areas by
2450 * allocating from CMA when over half of the zone's free memory
2451 * is in the CMA area.
2452 */
2453 if (alloc_flags & ALLOC_CMA &&
2454 zone_page_state(zone, NR_FREE_CMA_PAGES) >
2455 zone_page_state(zone, NR_FREE_PAGES) / 2) {
2456 page = __rmqueue_cma_fallback(zone, order);
2457 if (page)
2458 return page;
2459 }
2460 }
2461
2462 /*
2463 * First try the freelists of the requested migratetype, then try
2464 * fallbacks modes with increasing levels of fragmentation risk.
2465 *
2466 * The fallback logic is expensive and rmqueue_bulk() calls in
2467 * a loop with the zone->lock held, meaning the freelists are
2468 * not subject to any outside changes. Remember in *mode where
2469 * we found pay dirt, to save us the search on the next call.
2470 */
2471 switch (*mode) {
2472 case RMQUEUE_NORMAL:
2473 page = __rmqueue_smallest(zone, order, migratetype);
2474 if (page)
2475 return page;
2476 fallthrough;
2477 case RMQUEUE_CMA:
2478 if (alloc_flags & ALLOC_CMA) {
2479 page = __rmqueue_cma_fallback(zone, order);
2480 if (page) {
2481 *mode = RMQUEUE_CMA;
2482 return page;
2483 }
2484 }
2485 fallthrough;
2486 case RMQUEUE_CLAIM:
2487 page = __rmqueue_claim(zone, order, migratetype, alloc_flags);
2488 if (page) {
2489 /* Replenished preferred freelist, back to normal mode. */
2490 *mode = RMQUEUE_NORMAL;
2491 return page;
2492 }
2493 fallthrough;
2494 case RMQUEUE_STEAL:
2495 if (!(alloc_flags & ALLOC_NOFRAGMENT)) {
2496 page = __rmqueue_steal(zone, order, migratetype);
2497 if (page) {
2498 *mode = RMQUEUE_STEAL;
2499 return page;
2500 }
2501 }
2502 }
2503 return NULL;
2504 }
2505
2506 /*
2507 * Obtain a specified number of elements from the buddy allocator, all under
2508 * a single hold of the lock, for efficiency. Add them to the supplied list.
2509 * Returns the number of new pages which were placed at *list.
2510 */
rmqueue_bulk(struct zone * zone,unsigned int order,unsigned long count,struct list_head * list,int migratetype,unsigned int alloc_flags)2511 static int rmqueue_bulk(struct zone *zone, unsigned int order,
2512 unsigned long count, struct list_head *list,
2513 int migratetype, unsigned int alloc_flags)
2514 {
2515 enum rmqueue_mode rmqm = RMQUEUE_NORMAL;
2516 unsigned long flags;
2517 int i;
2518
2519 if (unlikely(alloc_flags & ALLOC_TRYLOCK)) {
2520 if (!spin_trylock_irqsave(&zone->lock, flags))
2521 return 0;
2522 } else {
2523 spin_lock_irqsave(&zone->lock, flags);
2524 }
2525 for (i = 0; i < count; ++i) {
2526 struct page *page = __rmqueue(zone, order, migratetype,
2527 alloc_flags, &rmqm);
2528 if (unlikely(page == NULL))
2529 break;
2530
2531 /*
2532 * Split buddy pages returned by expand() are received here in
2533 * physical page order. The page is added to the tail of
2534 * caller's list. From the callers perspective, the linked list
2535 * is ordered by page number under some conditions. This is
2536 * useful for IO devices that can forward direction from the
2537 * head, thus also in the physical page order. This is useful
2538 * for IO devices that can merge IO requests if the physical
2539 * pages are ordered properly.
2540 */
2541 list_add_tail(&page->pcp_list, list);
2542 }
2543 spin_unlock_irqrestore(&zone->lock, flags);
2544
2545 return i;
2546 }
2547
2548 /*
2549 * Called from the vmstat counter updater to decay the PCP high.
2550 * Return whether there are addition works to do.
2551 */
decay_pcp_high(struct zone * zone,struct per_cpu_pages * pcp)2552 bool decay_pcp_high(struct zone *zone, struct per_cpu_pages *pcp)
2553 {
2554 int high_min, to_drain, to_drain_batched, batch;
2555 bool todo = false;
2556
2557 high_min = READ_ONCE(pcp->high_min);
2558 batch = READ_ONCE(pcp->batch);
2559 /*
2560 * Decrease pcp->high periodically to try to free possible
2561 * idle PCP pages. And, avoid to free too many pages to
2562 * control latency. This caps pcp->high decrement too.
2563 */
2564 if (pcp->high > high_min) {
2565 pcp->high = max3(pcp->count - (batch << CONFIG_PCP_BATCH_SCALE_MAX),
2566 pcp->high - (pcp->high >> 3), high_min);
2567 if (pcp->high > high_min)
2568 todo = true;
2569 }
2570
2571 to_drain = pcp->count - pcp->high;
2572 while (to_drain > 0) {
2573 to_drain_batched = min(to_drain, batch);
2574 pcp_spin_lock_nopin(pcp);
2575 free_pcppages_bulk(zone, to_drain_batched, pcp, 0);
2576 pcp_spin_unlock_nopin(pcp);
2577 todo = true;
2578
2579 to_drain -= to_drain_batched;
2580 }
2581
2582 return todo;
2583 }
2584
2585 #ifdef CONFIG_NUMA
2586 /*
2587 * Called from the vmstat counter updater to drain pagesets of this
2588 * currently executing processor on remote nodes after they have
2589 * expired.
2590 */
drain_zone_pages(struct zone * zone,struct per_cpu_pages * pcp)2591 void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp)
2592 {
2593 int to_drain, batch;
2594
2595 batch = READ_ONCE(pcp->batch);
2596 to_drain = min(pcp->count, batch);
2597 if (to_drain > 0) {
2598 pcp_spin_lock_nopin(pcp);
2599 free_pcppages_bulk(zone, to_drain, pcp, 0);
2600 pcp_spin_unlock_nopin(pcp);
2601 }
2602 }
2603 #endif
2604
2605 /*
2606 * Drain pcplists of the indicated processor and zone.
2607 */
drain_pages_zone(unsigned int cpu,struct zone * zone)2608 static void drain_pages_zone(unsigned int cpu, struct zone *zone)
2609 {
2610 struct per_cpu_pages *pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu);
2611 int count;
2612
2613 do {
2614 pcp_spin_lock_nopin(pcp);
2615 count = pcp->count;
2616 if (count) {
2617 int to_drain = min(count,
2618 pcp->batch << CONFIG_PCP_BATCH_SCALE_MAX);
2619
2620 free_pcppages_bulk(zone, to_drain, pcp, 0);
2621 count -= to_drain;
2622 }
2623 pcp_spin_unlock_nopin(pcp);
2624 } while (count);
2625 }
2626
2627 /*
2628 * Drain pcplists of all zones on the indicated processor.
2629 */
drain_pages(unsigned int cpu)2630 static void drain_pages(unsigned int cpu)
2631 {
2632 struct zone *zone;
2633
2634 for_each_populated_zone(zone) {
2635 drain_pages_zone(cpu, zone);
2636 }
2637 }
2638
2639 /*
2640 * Spill all of this CPU's per-cpu pages back into the buddy allocator.
2641 */
drain_local_pages(struct zone * zone)2642 void drain_local_pages(struct zone *zone)
2643 {
2644 int cpu = smp_processor_id();
2645
2646 if (zone)
2647 drain_pages_zone(cpu, zone);
2648 else
2649 drain_pages(cpu);
2650 }
2651
2652 /*
2653 * The implementation of drain_all_pages(), exposing an extra parameter to
2654 * drain on all cpus.
2655 *
2656 * drain_all_pages() is optimized to only execute on cpus where pcplists are
2657 * not empty. The check for non-emptiness can however race with a free to
2658 * pcplist that has not yet increased the pcp->count from 0 to 1. Callers
2659 * that need the guarantee that every CPU has drained can disable the
2660 * optimizing racy check.
2661 */
__drain_all_pages(struct zone * zone,bool force_all_cpus)2662 static void __drain_all_pages(struct zone *zone, bool force_all_cpus)
2663 {
2664 int cpu;
2665
2666 /*
2667 * Allocate in the BSS so we won't require allocation in
2668 * direct reclaim path for CONFIG_CPUMASK_OFFSTACK=y
2669 */
2670 static cpumask_t cpus_with_pcps;
2671
2672 /*
2673 * Do not drain if one is already in progress unless it's specific to
2674 * a zone. Such callers are primarily CMA and memory hotplug and need
2675 * the drain to be complete when the call returns.
2676 */
2677 if (unlikely(!mutex_trylock(&pcpu_drain_mutex))) {
2678 if (!zone)
2679 return;
2680 mutex_lock(&pcpu_drain_mutex);
2681 }
2682
2683 /*
2684 * We don't care about racing with CPU hotplug event
2685 * as offline notification will cause the notified
2686 * cpu to drain that CPU pcps and on_each_cpu_mask
2687 * disables preemption as part of its processing
2688 */
2689 for_each_online_cpu(cpu) {
2690 struct per_cpu_pages *pcp;
2691 struct zone *z;
2692 bool has_pcps = false;
2693
2694 if (force_all_cpus) {
2695 /*
2696 * The pcp.count check is racy, some callers need a
2697 * guarantee that no cpu is missed.
2698 */
2699 has_pcps = true;
2700 } else if (zone) {
2701 pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu);
2702 if (pcp->count)
2703 has_pcps = true;
2704 } else {
2705 for_each_populated_zone(z) {
2706 pcp = per_cpu_ptr(z->per_cpu_pageset, cpu);
2707 if (pcp->count) {
2708 has_pcps = true;
2709 break;
2710 }
2711 }
2712 }
2713
2714 if (has_pcps)
2715 cpumask_set_cpu(cpu, &cpus_with_pcps);
2716 else
2717 cpumask_clear_cpu(cpu, &cpus_with_pcps);
2718 }
2719
2720 for_each_cpu(cpu, &cpus_with_pcps) {
2721 if (zone)
2722 drain_pages_zone(cpu, zone);
2723 else
2724 drain_pages(cpu);
2725 }
2726
2727 mutex_unlock(&pcpu_drain_mutex);
2728 }
2729
2730 /*
2731 * Spill all the per-cpu pages from all CPUs back into the buddy allocator.
2732 *
2733 * When zone parameter is non-NULL, spill just the single zone's pages.
2734 */
drain_all_pages(struct zone * zone)2735 void drain_all_pages(struct zone *zone)
2736 {
2737 __drain_all_pages(zone, false);
2738 }
2739
nr_pcp_free(struct per_cpu_pages * pcp,int batch,int high,bool free_high)2740 static int nr_pcp_free(struct per_cpu_pages *pcp, int batch, int high, bool free_high)
2741 {
2742 int min_nr_free, max_nr_free;
2743
2744 /* Free as much as possible if batch freeing high-order pages. */
2745 if (unlikely(free_high))
2746 return min(pcp->count, batch << CONFIG_PCP_BATCH_SCALE_MAX);
2747
2748 /* Check for PCP disabled or boot pageset */
2749 if (unlikely(high < batch))
2750 return 1;
2751
2752 /* Leave at least pcp->batch pages on the list */
2753 min_nr_free = batch;
2754 max_nr_free = high - batch;
2755
2756 /*
2757 * Increase the batch number to the number of the consecutive
2758 * freed pages to reduce zone lock contention.
2759 */
2760 batch = clamp_t(int, pcp->free_count, min_nr_free, max_nr_free);
2761
2762 return batch;
2763 }
2764
nr_pcp_high(struct per_cpu_pages * pcp,struct zone * zone,int batch,bool free_high)2765 static int nr_pcp_high(struct per_cpu_pages *pcp, struct zone *zone,
2766 int batch, bool free_high)
2767 {
2768 int high, high_min, high_max;
2769
2770 high_min = READ_ONCE(pcp->high_min);
2771 high_max = READ_ONCE(pcp->high_max);
2772 high = pcp->high = clamp(pcp->high, high_min, high_max);
2773
2774 if (unlikely(!high))
2775 return 0;
2776
2777 if (unlikely(free_high)) {
2778 pcp->high = max(high - (batch << CONFIG_PCP_BATCH_SCALE_MAX),
2779 high_min);
2780 return 0;
2781 }
2782
2783 /*
2784 * If reclaim is active, limit the number of pages that can be
2785 * stored on pcp lists
2786 */
2787 if (test_bit(ZONE_RECLAIM_ACTIVE, &zone->flags)) {
2788 int free_count = max_t(int, pcp->free_count, batch);
2789
2790 pcp->high = max(high - free_count, high_min);
2791 return min(batch << 2, pcp->high);
2792 }
2793
2794 if (high_min == high_max)
2795 return high;
2796
2797 if (test_bit(ZONE_BELOW_HIGH, &zone->flags)) {
2798 int free_count = max_t(int, pcp->free_count, batch);
2799
2800 pcp->high = max(high - free_count, high_min);
2801 high = max(pcp->count, high_min);
2802 } else if (pcp->count >= high) {
2803 int need_high = pcp->free_count + batch;
2804
2805 /* pcp->high should be large enough to hold batch freed pages */
2806 if (pcp->high < need_high)
2807 pcp->high = clamp(need_high, high_min, high_max);
2808 }
2809
2810 return high;
2811 }
2812
2813 /*
2814 * Tune pcp alloc factor and adjust count & free_count. Free pages to bring the
2815 * pcp's watermarks below high.
2816 *
2817 * May return a freed pcp, if during page freeing the pcp spinlock cannot be
2818 * reacquired. Return true if pcp is locked, false otherwise.
2819 */
free_frozen_page_commit(struct zone * zone,struct per_cpu_pages * pcp,struct page * page,int migratetype,unsigned int order,fpi_t fpi_flags)2820 static bool free_frozen_page_commit(struct zone *zone,
2821 struct per_cpu_pages *pcp, struct page *page, int migratetype,
2822 unsigned int order, fpi_t fpi_flags)
2823 {
2824 int high, batch;
2825 int to_free, to_free_batched;
2826 int pindex;
2827 int cpu = smp_processor_id();
2828 int ret = true;
2829 bool free_high = false;
2830
2831 /*
2832 * On freeing, reduce the number of pages that are batch allocated.
2833 * See nr_pcp_alloc() where alloc_factor is increased for subsequent
2834 * allocations.
2835 */
2836 pcp->alloc_factor >>= 1;
2837 __count_vm_events(PGFREE, 1 << order);
2838 pindex = order_to_pindex(migratetype, order);
2839 list_add(&page->pcp_list, &pcp->lists[pindex]);
2840 pcp->count += 1 << order;
2841
2842 batch = READ_ONCE(pcp->batch);
2843 /*
2844 * As high-order pages other than THP's stored on PCP can contribute
2845 * to fragmentation, limit the number stored when PCP is heavily
2846 * freeing without allocation. The remainder after bulk freeing
2847 * stops will be drained from vmstat refresh context.
2848 */
2849 if (order && order <= PAGE_ALLOC_COSTLY_ORDER) {
2850 free_high = (pcp->free_count >= (batch + pcp->high_min / 2) &&
2851 (pcp->flags & PCPF_PREV_FREE_HIGH_ORDER) &&
2852 (!(pcp->flags & PCPF_FREE_HIGH_BATCH) ||
2853 pcp->count >= batch));
2854 pcp->flags |= PCPF_PREV_FREE_HIGH_ORDER;
2855 } else if (pcp->flags & PCPF_PREV_FREE_HIGH_ORDER) {
2856 pcp->flags &= ~PCPF_PREV_FREE_HIGH_ORDER;
2857 }
2858 if (pcp->free_count < (batch << CONFIG_PCP_BATCH_SCALE_MAX))
2859 pcp->free_count += (1 << order);
2860
2861 if (unlikely(fpi_flags & FPI_TRYLOCK)) {
2862 /*
2863 * Do not attempt to take a zone lock. Let pcp->count get
2864 * over high mark temporarily.
2865 */
2866 return true;
2867 }
2868
2869 high = nr_pcp_high(pcp, zone, batch, free_high);
2870 if (pcp->count < high)
2871 return true;
2872
2873 to_free = nr_pcp_free(pcp, batch, high, free_high);
2874 while (to_free > 0 && pcp->count > 0) {
2875 to_free_batched = min(to_free, batch);
2876 free_pcppages_bulk(zone, to_free_batched, pcp, pindex);
2877 to_free -= to_free_batched;
2878
2879 if (to_free == 0 || pcp->count == 0)
2880 break;
2881
2882 pcp_spin_unlock(pcp);
2883
2884 pcp = pcp_spin_trylock(zone->per_cpu_pageset);
2885 if (!pcp) {
2886 ret = false;
2887 break;
2888 }
2889
2890 /*
2891 * Check if this thread has been migrated to a different CPU.
2892 * If that is the case, give up and indicate that the pcp is
2893 * returned in an unlocked state.
2894 */
2895 if (smp_processor_id() != cpu) {
2896 pcp_spin_unlock(pcp);
2897 ret = false;
2898 break;
2899 }
2900 }
2901
2902 if (test_bit(ZONE_BELOW_HIGH, &zone->flags) &&
2903 zone_watermark_ok(zone, 0, high_wmark_pages(zone),
2904 ZONE_MOVABLE, 0)) {
2905 struct pglist_data *pgdat = zone->zone_pgdat;
2906 clear_bit(ZONE_BELOW_HIGH, &zone->flags);
2907
2908 /*
2909 * Assume that memory pressure on this node is gone and may be
2910 * in a reclaimable state. If a memory fallback node exists,
2911 * direct reclaim may not have been triggered, causing a
2912 * 'hopeless node' to stay in that state for a while. Let
2913 * kswapd work again by resetting kswapd_failures.
2914 */
2915 if (kswapd_test_hopeless(pgdat) &&
2916 next_memory_node(pgdat->node_id) < MAX_NUMNODES)
2917 kswapd_clear_hopeless(pgdat, KSWAPD_CLEAR_HOPELESS_PCP);
2918 }
2919 return ret;
2920 }
2921
2922 /*
2923 * Free a pcp page
2924 */
__free_frozen_pages(struct page * page,unsigned int order,fpi_t fpi_flags)2925 static void __free_frozen_pages(struct page *page, unsigned int order,
2926 fpi_t fpi_flags)
2927 {
2928 struct per_cpu_pages *pcp;
2929 struct zone *zone;
2930 unsigned long pfn = page_to_pfn(page);
2931 int migratetype;
2932
2933 if (!pcp_allowed_order(order)) {
2934 __free_pages_ok(page, order, fpi_flags);
2935 return;
2936 }
2937
2938 if (!__free_pages_prepare(page, order, fpi_flags))
2939 return;
2940
2941 /*
2942 * We only track unmovable, reclaimable and movable on pcp lists.
2943 * Place ISOLATE pages on the isolated list because they are being
2944 * offlined but treat HIGHATOMIC and CMA as movable pages so we can
2945 * get those areas back if necessary. Otherwise, we may have to free
2946 * excessively into the page allocator
2947 */
2948 zone = page_zone(page);
2949 migratetype = get_pfnblock_migratetype(page, pfn);
2950 if (unlikely(migratetype >= MIGRATE_PCPTYPES)) {
2951 if (unlikely(is_migrate_isolate(migratetype))) {
2952 free_one_page(zone, page, pfn, order, fpi_flags);
2953 return;
2954 }
2955 migratetype = MIGRATE_MOVABLE;
2956 }
2957
2958 if (unlikely((fpi_flags & FPI_TRYLOCK) && IS_ENABLED(CONFIG_PREEMPT_RT)
2959 && (in_nmi() || in_hardirq()))) {
2960 add_page_to_zone_llist(zone, page, order);
2961 return;
2962 }
2963 pcp = pcp_spin_trylock(zone->per_cpu_pageset);
2964 if (pcp) {
2965 if (!free_frozen_page_commit(zone, pcp, page, migratetype,
2966 order, fpi_flags))
2967 return;
2968 pcp_spin_unlock(pcp);
2969 } else {
2970 free_one_page(zone, page, pfn, order, fpi_flags);
2971 }
2972 }
2973
free_frozen_pages(struct page * page,unsigned int order)2974 void free_frozen_pages(struct page *page, unsigned int order)
2975 {
2976 __free_frozen_pages(page, order, FPI_NONE);
2977 }
2978
free_frozen_pages_nolock(struct page * page,unsigned int order)2979 void free_frozen_pages_nolock(struct page *page, unsigned int order)
2980 {
2981 __free_frozen_pages(page, order, FPI_TRYLOCK);
2982 }
2983
2984 /*
2985 * Free a batch of folios
2986 */
free_unref_folios(struct folio_batch * folios)2987 void free_unref_folios(struct folio_batch *folios)
2988 {
2989 struct per_cpu_pages *pcp = NULL;
2990 struct zone *locked_zone = NULL;
2991 int i, j;
2992
2993 /* Prepare folios for freeing */
2994 for (i = 0, j = 0; i < folios->nr; i++) {
2995 struct folio *folio = folios->folios[i];
2996 unsigned long pfn = folio_pfn(folio);
2997 unsigned int order = folio_order(folio);
2998
2999 if (!__free_pages_prepare(&folio->page, order, FPI_NONE))
3000 continue;
3001 /*
3002 * Free orders not handled on the PCP directly to the
3003 * allocator.
3004 */
3005 if (!pcp_allowed_order(order)) {
3006 free_one_page(folio_zone(folio), &folio->page,
3007 pfn, order, FPI_NONE);
3008 continue;
3009 }
3010 folio->private = (void *)(unsigned long)order;
3011 if (j != i)
3012 folios->folios[j] = folio;
3013 j++;
3014 }
3015 folios->nr = j;
3016
3017 for (i = 0; i < folios->nr; i++) {
3018 struct folio *folio = folios->folios[i];
3019 struct zone *zone = folio_zone(folio);
3020 unsigned long pfn = folio_pfn(folio);
3021 unsigned int order = (unsigned long)folio->private;
3022 int migratetype;
3023
3024 folio->private = NULL;
3025 migratetype = get_pfnblock_migratetype(&folio->page, pfn);
3026
3027 /* Different zone requires a different pcp lock */
3028 if (zone != locked_zone ||
3029 is_migrate_isolate(migratetype)) {
3030 if (pcp) {
3031 pcp_spin_unlock(pcp);
3032 locked_zone = NULL;
3033 pcp = NULL;
3034 }
3035
3036 /*
3037 * Free isolated pages directly to the
3038 * allocator, see comment in free_frozen_pages.
3039 */
3040 if (is_migrate_isolate(migratetype)) {
3041 free_one_page(zone, &folio->page, pfn,
3042 order, FPI_NONE);
3043 continue;
3044 }
3045
3046 /*
3047 * trylock is necessary as folios may be getting freed
3048 * from IRQ or SoftIRQ context after an IO completion.
3049 */
3050 pcp = pcp_spin_trylock(zone->per_cpu_pageset);
3051 if (unlikely(!pcp)) {
3052 free_one_page(zone, &folio->page, pfn,
3053 order, FPI_NONE);
3054 continue;
3055 }
3056 locked_zone = zone;
3057 }
3058
3059 /*
3060 * Non-isolated types over MIGRATE_PCPTYPES get added
3061 * to the MIGRATE_MOVABLE pcp list.
3062 */
3063 if (unlikely(migratetype >= MIGRATE_PCPTYPES))
3064 migratetype = MIGRATE_MOVABLE;
3065
3066 trace_mm_page_free_batched(&folio->page);
3067 if (!free_frozen_page_commit(zone, pcp, &folio->page,
3068 migratetype, order, FPI_NONE)) {
3069 pcp = NULL;
3070 locked_zone = NULL;
3071 }
3072 }
3073
3074 if (pcp)
3075 pcp_spin_unlock(pcp);
3076 folio_batch_reinit(folios);
3077 }
3078
__split_page(struct page * page,unsigned int order)3079 static void __split_page(struct page *page, unsigned int order)
3080 {
3081 VM_WARN_ON_PAGE(PageCompound(page), page);
3082
3083 split_page_owner(page, order, 0);
3084 pgalloc_tag_split(page_folio(page), order, 0);
3085 split_page_memcg(page, order);
3086 }
3087
3088 /*
3089 * split_page takes a non-compound higher-order page, and splits it into
3090 * n (1<<order) sub-pages: page[0..n]
3091 * Each sub-page must be freed individually.
3092 *
3093 * Note: this is probably too low level an operation for use in drivers.
3094 * Please consult with lkml before using this in your driver.
3095 */
split_page(struct page * page,unsigned int order)3096 void split_page(struct page *page, unsigned int order)
3097 {
3098 int i;
3099
3100 VM_WARN_ON_PAGE(!page_count(page), page);
3101
3102 for (i = 1; i < (1 << order); i++)
3103 set_page_refcounted(page + i);
3104
3105 __split_page(page, order);
3106 }
3107 EXPORT_SYMBOL_GPL(split_page);
3108
__isolate_free_page(struct page * page,unsigned int order)3109 int __isolate_free_page(struct page *page, unsigned int order)
3110 {
3111 struct zone *zone = page_zone(page);
3112 int mt = get_pageblock_migratetype(page);
3113
3114 if (!is_migrate_isolate(mt)) {
3115 unsigned long watermark;
3116 /*
3117 * Obey watermarks as if the page was being allocated. We can
3118 * emulate a high-order watermark check with a raised order-0
3119 * watermark, because we already know our high-order page
3120 * exists.
3121 */
3122 watermark = zone->_watermark[WMARK_MIN] + (1UL << order);
3123 if (!zone_watermark_ok(zone, 0, watermark, 0, ALLOC_CMA))
3124 return 0;
3125 }
3126
3127 del_page_from_free_list(page, zone, order, mt);
3128
3129 /*
3130 * Set the pageblock if the isolated page is at least half of a
3131 * pageblock
3132 */
3133 if (order >= pageblock_order - 1) {
3134 struct page *endpage = page + (1 << order) - 1;
3135 for (; page < endpage; page += pageblock_nr_pages) {
3136 int mt = get_pageblock_migratetype(page);
3137 /*
3138 * Only change normal pageblocks (i.e., they can merge
3139 * with others)
3140 */
3141 if (migratetype_is_mergeable(mt))
3142 move_freepages_block(zone, page, mt,
3143 MIGRATE_MOVABLE);
3144 }
3145 }
3146
3147 return 1UL << order;
3148 }
3149
3150 /**
3151 * __putback_isolated_page - Return a now-isolated page back where we got it
3152 * @page: Page that was isolated
3153 * @order: Order of the isolated page
3154 * @mt: The page's pageblock's migratetype
3155 *
3156 * This function is meant to return a page pulled from the free lists via
3157 * __isolate_free_page back to the free lists they were pulled from.
3158 */
__putback_isolated_page(struct page * page,unsigned int order,int mt)3159 void __putback_isolated_page(struct page *page, unsigned int order, int mt)
3160 {
3161 struct zone *zone = page_zone(page);
3162
3163 /* zone lock should be held when this function is called */
3164 lockdep_assert_held(&zone->lock);
3165
3166 /* Return isolated page to tail of freelist. */
3167 __free_one_page(page, page_to_pfn(page), zone, order, mt,
3168 FPI_SKIP_REPORT_NOTIFY | FPI_TO_TAIL);
3169 }
3170
3171 /*
3172 * Update NUMA hit/miss statistics
3173 */
zone_statistics(struct zone * preferred_zone,struct zone * z,long nr_account)3174 static inline void zone_statistics(struct zone *preferred_zone, struct zone *z,
3175 long nr_account)
3176 {
3177 #ifdef CONFIG_NUMA
3178 enum numa_stat_item local_stat = NUMA_LOCAL;
3179
3180 /* skip numa counters update if numa stats is disabled */
3181 if (!static_branch_likely(&vm_numa_stat_key))
3182 return;
3183
3184 if (zone_to_nid(z) != numa_node_id())
3185 local_stat = NUMA_OTHER;
3186
3187 if (zone_to_nid(z) == zone_to_nid(preferred_zone))
3188 __count_numa_events(z, NUMA_HIT, nr_account);
3189 else {
3190 __count_numa_events(z, NUMA_MISS, nr_account);
3191 __count_numa_events(preferred_zone, NUMA_FOREIGN, nr_account);
3192 }
3193 __count_numa_events(z, local_stat, nr_account);
3194 #endif
3195 }
3196
3197 static __always_inline
rmqueue_buddy(struct zone * preferred_zone,struct zone * zone,unsigned int order,unsigned int alloc_flags,int migratetype)3198 struct page *rmqueue_buddy(struct zone *preferred_zone, struct zone *zone,
3199 unsigned int order, unsigned int alloc_flags,
3200 int migratetype)
3201 {
3202 struct page *page;
3203 unsigned long flags;
3204
3205 do {
3206 page = NULL;
3207 if (unlikely(alloc_flags & ALLOC_TRYLOCK)) {
3208 if (!spin_trylock_irqsave(&zone->lock, flags))
3209 return NULL;
3210 } else {
3211 spin_lock_irqsave(&zone->lock, flags);
3212 }
3213 if (alloc_flags & ALLOC_HIGHATOMIC)
3214 page = __rmqueue_smallest(zone, order, MIGRATE_HIGHATOMIC);
3215 if (!page) {
3216 enum rmqueue_mode rmqm = RMQUEUE_NORMAL;
3217
3218 page = __rmqueue(zone, order, migratetype, alloc_flags, &rmqm);
3219
3220 /*
3221 * If the allocation fails, allow OOM handling and
3222 * order-0 (atomic) allocs access to HIGHATOMIC
3223 * reserves as failing now is worse than failing a
3224 * high-order atomic allocation in the future.
3225 */
3226 if (!page && (alloc_flags & (ALLOC_OOM|ALLOC_NON_BLOCK)))
3227 page = __rmqueue_smallest(zone, order, MIGRATE_HIGHATOMIC);
3228
3229 if (!page) {
3230 spin_unlock_irqrestore(&zone->lock, flags);
3231 return NULL;
3232 }
3233 }
3234 spin_unlock_irqrestore(&zone->lock, flags);
3235 } while (check_new_pages(page, order));
3236
3237 /*
3238 * If this is a high-order atomic allocation then check
3239 * if the pageblock should be reserved for the future
3240 */
3241 if (unlikely(alloc_flags & ALLOC_HIGHATOMIC))
3242 reserve_highatomic_pageblock(page, order, zone);
3243
3244 __count_zid_vm_events(PGALLOC, page_zonenum(page), 1 << order);
3245 zone_statistics(preferred_zone, zone, 1);
3246
3247 return page;
3248 }
3249
nr_pcp_alloc(struct per_cpu_pages * pcp,struct zone * zone,int order)3250 static int nr_pcp_alloc(struct per_cpu_pages *pcp, struct zone *zone, int order)
3251 {
3252 int high, base_batch, batch, max_nr_alloc;
3253 int high_max, high_min;
3254
3255 base_batch = READ_ONCE(pcp->batch);
3256 high_min = READ_ONCE(pcp->high_min);
3257 high_max = READ_ONCE(pcp->high_max);
3258 high = pcp->high = clamp(pcp->high, high_min, high_max);
3259
3260 /* Check for PCP disabled or boot pageset */
3261 if (unlikely(high < base_batch))
3262 return 1;
3263
3264 if (order)
3265 batch = base_batch;
3266 else
3267 batch = (base_batch << pcp->alloc_factor);
3268
3269 /*
3270 * If we had larger pcp->high, we could avoid to allocate from
3271 * zone.
3272 */
3273 if (high_min != high_max && !test_bit(ZONE_BELOW_HIGH, &zone->flags))
3274 high = pcp->high = min(high + batch, high_max);
3275
3276 if (!order) {
3277 max_nr_alloc = max(high - pcp->count - base_batch, base_batch);
3278 /*
3279 * Double the number of pages allocated each time there is
3280 * subsequent allocation of order-0 pages without any freeing.
3281 */
3282 if (batch <= max_nr_alloc &&
3283 pcp->alloc_factor < CONFIG_PCP_BATCH_SCALE_MAX)
3284 pcp->alloc_factor++;
3285 batch = min(batch, max_nr_alloc);
3286 }
3287
3288 /*
3289 * Scale batch relative to order if batch implies free pages
3290 * can be stored on the PCP. Batch can be 1 for small zones or
3291 * for boot pagesets which should never store free pages as
3292 * the pages may belong to arbitrary zones.
3293 */
3294 if (batch > 1)
3295 batch = max(batch >> order, 2);
3296
3297 return batch;
3298 }
3299
3300 /* Remove page from the per-cpu list, caller must protect the list */
3301 static inline
__rmqueue_pcplist(struct zone * zone,unsigned int order,int migratetype,unsigned int alloc_flags,struct per_cpu_pages * pcp,struct list_head * list)3302 struct page *__rmqueue_pcplist(struct zone *zone, unsigned int order,
3303 int migratetype,
3304 unsigned int alloc_flags,
3305 struct per_cpu_pages *pcp,
3306 struct list_head *list)
3307 {
3308 struct page *page;
3309
3310 do {
3311 if (list_empty(list)) {
3312 int batch = nr_pcp_alloc(pcp, zone, order);
3313 int alloced;
3314
3315 /*
3316 * Don't refill the list for a higher order atomic
3317 * allocation under memory pressure, as this would
3318 * not build up any HIGHATOMIC reserves, which
3319 * might be needed soon.
3320 *
3321 * Instead, direct it towards the reserves by
3322 * returning NULL, which will make the caller fall
3323 * back to rmqueue_buddy. This will try to use the
3324 * reserves first and grow them if needed.
3325 */
3326 if (alloc_flags & ALLOC_HIGHATOMIC)
3327 return NULL;
3328
3329 alloced = rmqueue_bulk(zone, order,
3330 batch, list,
3331 migratetype, alloc_flags);
3332
3333 pcp->count += alloced << order;
3334 if (unlikely(list_empty(list)))
3335 return NULL;
3336 }
3337
3338 page = list_first_entry(list, struct page, pcp_list);
3339 list_del(&page->pcp_list);
3340 pcp->count -= 1 << order;
3341 } while (check_new_pages(page, order));
3342
3343 return page;
3344 }
3345
3346 /* Lock and remove page from the per-cpu list */
rmqueue_pcplist(struct zone * preferred_zone,struct zone * zone,unsigned int order,int migratetype,unsigned int alloc_flags)3347 static struct page *rmqueue_pcplist(struct zone *preferred_zone,
3348 struct zone *zone, unsigned int order,
3349 int migratetype, unsigned int alloc_flags)
3350 {
3351 struct per_cpu_pages *pcp;
3352 struct list_head *list;
3353 struct page *page;
3354
3355 /* spin_trylock may fail due to a parallel drain or IRQ reentrancy. */
3356 pcp = pcp_spin_trylock(zone->per_cpu_pageset);
3357 if (!pcp)
3358 return NULL;
3359
3360 /*
3361 * On allocation, reduce the number of pages that are batch freed.
3362 * See nr_pcp_free() where free_factor is increased for subsequent
3363 * frees.
3364 */
3365 pcp->free_count >>= 1;
3366 list = &pcp->lists[order_to_pindex(migratetype, order)];
3367 page = __rmqueue_pcplist(zone, order, migratetype, alloc_flags, pcp, list);
3368 pcp_spin_unlock(pcp);
3369 if (page) {
3370 __count_zid_vm_events(PGALLOC, page_zonenum(page), 1 << order);
3371 zone_statistics(preferred_zone, zone, 1);
3372 }
3373 return page;
3374 }
3375
3376 /*
3377 * Allocate a page from the given zone.
3378 * Use pcplists for THP or "cheap" high-order allocations.
3379 */
3380
3381 /*
3382 * Do not instrument rmqueue() with KMSAN. This function may call
3383 * __msan_poison_alloca() through a call to set_pfnblock_migratetype().
3384 * If __msan_poison_alloca() attempts to allocate pages for the stack depot, it
3385 * may call rmqueue() again, which will result in a deadlock.
3386 */
3387 __no_sanitize_memory
3388 static inline
rmqueue(struct zone * preferred_zone,struct zone * zone,unsigned int order,gfp_t gfp_flags,unsigned int alloc_flags,int migratetype)3389 struct page *rmqueue(struct zone *preferred_zone,
3390 struct zone *zone, unsigned int order,
3391 gfp_t gfp_flags, unsigned int alloc_flags,
3392 int migratetype)
3393 {
3394 struct page *page;
3395
3396 if (likely(pcp_allowed_order(order))) {
3397 page = rmqueue_pcplist(preferred_zone, zone, order,
3398 migratetype, alloc_flags);
3399 if (likely(page))
3400 goto out;
3401 }
3402
3403 page = rmqueue_buddy(preferred_zone, zone, order, alloc_flags,
3404 migratetype);
3405
3406 out:
3407 /* Separate test+clear to avoid unnecessary atomics */
3408 if ((alloc_flags & ALLOC_KSWAPD) &&
3409 unlikely(test_bit(ZONE_BOOSTED_WATERMARK, &zone->flags))) {
3410 clear_bit(ZONE_BOOSTED_WATERMARK, &zone->flags);
3411 wakeup_kswapd(zone, 0, 0, zone_idx(zone));
3412 }
3413
3414 VM_BUG_ON_PAGE(page && bad_range(zone, page), page);
3415 return page;
3416 }
3417
3418 /*
3419 * Reserve the pageblock(s) surrounding an allocation request for
3420 * exclusive use of high-order atomic allocations if there are no
3421 * empty page blocks that contain a page with a suitable order
3422 */
reserve_highatomic_pageblock(struct page * page,int order,struct zone * zone)3423 static void reserve_highatomic_pageblock(struct page *page, int order,
3424 struct zone *zone)
3425 {
3426 int mt;
3427 unsigned long max_managed, flags;
3428
3429 /*
3430 * The number reserved as: minimum is 1 pageblock, maximum is
3431 * roughly 1% of a zone. But if 1% of a zone falls below a
3432 * pageblock size, then don't reserve any pageblocks.
3433 * Check is race-prone but harmless.
3434 */
3435 if ((zone_managed_pages(zone) / 100) < pageblock_nr_pages)
3436 return;
3437 max_managed = ALIGN((zone_managed_pages(zone) / 100), pageblock_nr_pages);
3438 if (zone->nr_reserved_highatomic >= max_managed)
3439 return;
3440
3441 spin_lock_irqsave(&zone->lock, flags);
3442
3443 /* Recheck the nr_reserved_highatomic limit under the lock */
3444 if (zone->nr_reserved_highatomic >= max_managed)
3445 goto out_unlock;
3446
3447 /* Yoink! */
3448 mt = get_pageblock_migratetype(page);
3449 /* Only reserve normal pageblocks (i.e., they can merge with others) */
3450 if (!migratetype_is_mergeable(mt))
3451 goto out_unlock;
3452
3453 if (order < pageblock_order) {
3454 if (move_freepages_block(zone, page, mt, MIGRATE_HIGHATOMIC) == -1)
3455 goto out_unlock;
3456 zone->nr_reserved_highatomic += pageblock_nr_pages;
3457 } else {
3458 change_pageblock_range(page, order, MIGRATE_HIGHATOMIC);
3459 zone->nr_reserved_highatomic += 1 << order;
3460 }
3461
3462 out_unlock:
3463 spin_unlock_irqrestore(&zone->lock, flags);
3464 }
3465
3466 /*
3467 * Used when an allocation is about to fail under memory pressure. This
3468 * potentially hurts the reliability of high-order allocations when under
3469 * intense memory pressure but failed atomic allocations should be easier
3470 * to recover from than an OOM.
3471 *
3472 * If @force is true, try to unreserve pageblocks even though highatomic
3473 * pageblock is exhausted.
3474 */
unreserve_highatomic_pageblock(const struct alloc_context * ac,bool force)3475 static bool unreserve_highatomic_pageblock(const struct alloc_context *ac,
3476 bool force)
3477 {
3478 struct zonelist *zonelist = ac->zonelist;
3479 unsigned long flags;
3480 struct zoneref *z;
3481 struct zone *zone;
3482 struct page *page;
3483 int order;
3484 int ret;
3485
3486 for_each_zone_zonelist_nodemask(zone, z, zonelist, ac->highest_zoneidx,
3487 ac->nodemask) {
3488 /*
3489 * Preserve at least one pageblock unless memory pressure
3490 * is really high.
3491 */
3492 if (!force && zone->nr_reserved_highatomic <=
3493 pageblock_nr_pages)
3494 continue;
3495
3496 spin_lock_irqsave(&zone->lock, flags);
3497 for (order = 0; order < NR_PAGE_ORDERS; order++) {
3498 struct free_area *area = &(zone->free_area[order]);
3499 unsigned long size;
3500
3501 page = get_page_from_free_area(area, MIGRATE_HIGHATOMIC);
3502 if (!page)
3503 continue;
3504
3505 size = max(pageblock_nr_pages, 1UL << order);
3506 /*
3507 * It should never happen but changes to
3508 * locking could inadvertently allow a per-cpu
3509 * drain to add pages to MIGRATE_HIGHATOMIC
3510 * while unreserving so be safe and watch for
3511 * underflows.
3512 */
3513 if (WARN_ON_ONCE(size > zone->nr_reserved_highatomic))
3514 size = zone->nr_reserved_highatomic;
3515 zone->nr_reserved_highatomic -= size;
3516
3517 /*
3518 * Convert to ac->migratetype and avoid the normal
3519 * pageblock stealing heuristics. Minimally, the caller
3520 * is doing the work and needs the pages. More
3521 * importantly, if the block was always converted to
3522 * MIGRATE_UNMOVABLE or another type then the number
3523 * of pageblocks that cannot be completely freed
3524 * may increase.
3525 */
3526 if (order < pageblock_order)
3527 ret = move_freepages_block(zone, page,
3528 MIGRATE_HIGHATOMIC,
3529 ac->migratetype);
3530 else {
3531 move_to_free_list(page, zone, order,
3532 MIGRATE_HIGHATOMIC,
3533 ac->migratetype);
3534 change_pageblock_range(page, order,
3535 ac->migratetype);
3536 ret = 1;
3537 }
3538 /*
3539 * Reserving the block(s) already succeeded,
3540 * so this should not fail on zone boundaries.
3541 */
3542 WARN_ON_ONCE(ret == -1);
3543 if (ret > 0) {
3544 spin_unlock_irqrestore(&zone->lock, flags);
3545 return ret;
3546 }
3547 }
3548 spin_unlock_irqrestore(&zone->lock, flags);
3549 }
3550
3551 return false;
3552 }
3553
__zone_watermark_unusable_free(struct zone * z,unsigned int order,unsigned int alloc_flags)3554 static inline long __zone_watermark_unusable_free(struct zone *z,
3555 unsigned int order, unsigned int alloc_flags)
3556 {
3557 long unusable_free = (1 << order) - 1;
3558
3559 /*
3560 * If the caller does not have rights to reserves below the min
3561 * watermark then subtract the free pages reserved for highatomic.
3562 */
3563 if (likely(!(alloc_flags & ALLOC_RESERVES)))
3564 unusable_free += READ_ONCE(z->nr_free_highatomic);
3565
3566 #ifdef CONFIG_CMA
3567 /* If allocation can't use CMA areas don't use free CMA pages */
3568 if (!(alloc_flags & ALLOC_CMA))
3569 unusable_free += zone_page_state(z, NR_FREE_CMA_PAGES);
3570 #endif
3571
3572 return unusable_free;
3573 }
3574
3575 /*
3576 * Return true if free base pages are above 'mark'. For high-order checks it
3577 * will return true of the order-0 watermark is reached and there is at least
3578 * one free page of a suitable size. Checking now avoids taking the zone lock
3579 * to check in the allocation paths if no pages are free.
3580 */
__zone_watermark_ok(struct zone * z,unsigned int order,unsigned long mark,int highest_zoneidx,unsigned int alloc_flags,long free_pages)3581 bool __zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
3582 int highest_zoneidx, unsigned int alloc_flags,
3583 long free_pages)
3584 {
3585 long min = mark;
3586 int o;
3587
3588 /* free_pages may go negative - that's OK */
3589 free_pages -= __zone_watermark_unusable_free(z, order, alloc_flags);
3590
3591 if (unlikely(alloc_flags & ALLOC_RESERVES)) {
3592 /*
3593 * __GFP_HIGH allows access to 50% of the min reserve as well
3594 * as OOM.
3595 */
3596 if (alloc_flags & ALLOC_MIN_RESERVE) {
3597 min -= min / 2;
3598
3599 /*
3600 * Non-blocking allocations (e.g. GFP_ATOMIC) can
3601 * access more reserves than just __GFP_HIGH. Other
3602 * non-blocking allocations requests such as GFP_NOWAIT
3603 * or (GFP_KERNEL & ~__GFP_DIRECT_RECLAIM) do not get
3604 * access to the min reserve.
3605 */
3606 if (alloc_flags & ALLOC_NON_BLOCK)
3607 min -= min / 4;
3608 }
3609
3610 /*
3611 * OOM victims can try even harder than the normal reserve
3612 * users on the grounds that it's definitely going to be in
3613 * the exit path shortly and free memory. Any allocation it
3614 * makes during the free path will be small and short-lived.
3615 */
3616 if (alloc_flags & ALLOC_OOM)
3617 min -= min / 2;
3618 }
3619
3620 /*
3621 * Check watermarks for an order-0 allocation request. If these
3622 * are not met, then a high-order request also cannot go ahead
3623 * even if a suitable page happened to be free.
3624 */
3625 if (free_pages <= min + z->lowmem_reserve[highest_zoneidx])
3626 return false;
3627
3628 /* If this is an order-0 request then the watermark is fine */
3629 if (!order)
3630 return true;
3631
3632 /* For a high-order request, check at least one suitable page is free */
3633 for (o = order; o < NR_PAGE_ORDERS; o++) {
3634 struct free_area *area = &z->free_area[o];
3635 int mt;
3636
3637 if (!area->nr_free)
3638 continue;
3639
3640 for (mt = 0; mt < MIGRATE_PCPTYPES; mt++) {
3641 if (!free_area_empty(area, mt))
3642 return true;
3643 }
3644
3645 #ifdef CONFIG_CMA
3646 if ((alloc_flags & ALLOC_CMA) &&
3647 !free_area_empty(area, MIGRATE_CMA)) {
3648 return true;
3649 }
3650 #endif
3651 if ((alloc_flags & (ALLOC_HIGHATOMIC|ALLOC_OOM)) &&
3652 !free_area_empty(area, MIGRATE_HIGHATOMIC)) {
3653 return true;
3654 }
3655 }
3656 return false;
3657 }
3658
zone_watermark_ok(struct zone * z,unsigned int order,unsigned long mark,int highest_zoneidx,unsigned int alloc_flags)3659 bool zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
3660 int highest_zoneidx, unsigned int alloc_flags)
3661 {
3662 return __zone_watermark_ok(z, order, mark, highest_zoneidx, alloc_flags,
3663 zone_page_state(z, NR_FREE_PAGES));
3664 }
3665
zone_watermark_fast(struct zone * z,unsigned int order,unsigned long mark,int highest_zoneidx,unsigned int alloc_flags,gfp_t gfp_mask)3666 static inline bool zone_watermark_fast(struct zone *z, unsigned int order,
3667 unsigned long mark, int highest_zoneidx,
3668 unsigned int alloc_flags, gfp_t gfp_mask)
3669 {
3670 long free_pages;
3671
3672 free_pages = zone_page_state(z, NR_FREE_PAGES);
3673
3674 /*
3675 * Fast check for order-0 only. If this fails then the reserves
3676 * need to be calculated.
3677 */
3678 if (!order) {
3679 long usable_free;
3680 long reserved;
3681
3682 usable_free = free_pages;
3683 reserved = __zone_watermark_unusable_free(z, 0, alloc_flags);
3684
3685 /* reserved may over estimate high-atomic reserves. */
3686 usable_free -= min(usable_free, reserved);
3687 if (usable_free > mark + z->lowmem_reserve[highest_zoneidx])
3688 return true;
3689 }
3690
3691 if (__zone_watermark_ok(z, order, mark, highest_zoneidx, alloc_flags,
3692 free_pages))
3693 return true;
3694
3695 /*
3696 * Ignore watermark boosting for __GFP_HIGH order-0 allocations
3697 * when checking the min watermark. The min watermark is the
3698 * point where boosting is ignored so that kswapd is woken up
3699 * when below the low watermark.
3700 */
3701 if (unlikely(!order && (alloc_flags & ALLOC_MIN_RESERVE) && z->watermark_boost
3702 && ((alloc_flags & ALLOC_WMARK_MASK) == WMARK_MIN))) {
3703 mark = z->_watermark[WMARK_MIN];
3704 return __zone_watermark_ok(z, order, mark, highest_zoneidx,
3705 alloc_flags, free_pages);
3706 }
3707
3708 return false;
3709 }
3710
3711 #ifdef CONFIG_NUMA
3712 int __read_mostly node_reclaim_distance = RECLAIM_DISTANCE;
3713
zone_allows_reclaim(struct zone * local_zone,struct zone * zone)3714 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
3715 {
3716 return node_distance(zone_to_nid(local_zone), zone_to_nid(zone)) <=
3717 node_reclaim_distance;
3718 }
3719 #else /* CONFIG_NUMA */
zone_allows_reclaim(struct zone * local_zone,struct zone * zone)3720 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
3721 {
3722 return true;
3723 }
3724 #endif /* CONFIG_NUMA */
3725
3726 /*
3727 * The restriction on ZONE_DMA32 as being a suitable zone to use to avoid
3728 * fragmentation is subtle. If the preferred zone was HIGHMEM then
3729 * premature use of a lower zone may cause lowmem pressure problems that
3730 * are worse than fragmentation. If the next zone is ZONE_DMA then it is
3731 * probably too small. It only makes sense to spread allocations to avoid
3732 * fragmentation between the Normal and DMA32 zones.
3733 */
3734 static inline unsigned int
alloc_flags_nofragment(struct zone * zone,gfp_t gfp_mask)3735 alloc_flags_nofragment(struct zone *zone, gfp_t gfp_mask)
3736 {
3737 unsigned int alloc_flags;
3738
3739 /*
3740 * __GFP_KSWAPD_RECLAIM is assumed to be the same as ALLOC_KSWAPD
3741 * to save a branch.
3742 */
3743 alloc_flags = (__force int) (gfp_mask & __GFP_KSWAPD_RECLAIM);
3744
3745 if (defrag_mode) {
3746 alloc_flags |= ALLOC_NOFRAGMENT;
3747 return alloc_flags;
3748 }
3749
3750 #ifdef CONFIG_ZONE_DMA32
3751 if (!zone)
3752 return alloc_flags;
3753
3754 if (zone_idx(zone) != ZONE_NORMAL)
3755 return alloc_flags;
3756
3757 /*
3758 * If ZONE_DMA32 exists, assume it is the one after ZONE_NORMAL and
3759 * the pointer is within zone->zone_pgdat->node_zones[]. Also assume
3760 * on UMA that if Normal is populated then so is DMA32.
3761 */
3762 BUILD_BUG_ON(ZONE_NORMAL - ZONE_DMA32 != 1);
3763 if (nr_online_nodes > 1 && !populated_zone(--zone))
3764 return alloc_flags;
3765
3766 alloc_flags |= ALLOC_NOFRAGMENT;
3767 #endif /* CONFIG_ZONE_DMA32 */
3768 return alloc_flags;
3769 }
3770
3771 /* Must be called after current_gfp_context() which can change gfp_mask */
gfp_to_alloc_flags_cma(gfp_t gfp_mask,unsigned int alloc_flags)3772 static inline unsigned int gfp_to_alloc_flags_cma(gfp_t gfp_mask,
3773 unsigned int alloc_flags)
3774 {
3775 #ifdef CONFIG_CMA
3776 if (gfp_migratetype(gfp_mask) == MIGRATE_MOVABLE)
3777 alloc_flags |= ALLOC_CMA;
3778 #endif
3779 return alloc_flags;
3780 }
3781
3782 /*
3783 * get_page_from_freelist goes through the zonelist trying to allocate
3784 * a page.
3785 */
3786 static struct page *
get_page_from_freelist(gfp_t gfp_mask,unsigned int order,int alloc_flags,const struct alloc_context * ac)3787 get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags,
3788 const struct alloc_context *ac)
3789 {
3790 struct zoneref *z;
3791 struct zone *zone;
3792 struct pglist_data *last_pgdat = NULL;
3793 bool last_pgdat_dirty_ok = false;
3794 bool no_fallback;
3795 bool skip_kswapd_nodes = nr_online_nodes > 1;
3796 bool skipped_kswapd_nodes = false;
3797
3798 retry:
3799 /*
3800 * Scan zonelist, looking for a zone with enough free.
3801 * See also cpuset_current_node_allowed() comment in kernel/cgroup/cpuset.c.
3802 */
3803 no_fallback = alloc_flags & ALLOC_NOFRAGMENT;
3804 z = ac->preferred_zoneref;
3805 for_next_zone_zonelist_nodemask(zone, z, ac->highest_zoneidx,
3806 ac->nodemask) {
3807 struct page *page;
3808 unsigned long mark;
3809
3810 if (cpusets_enabled() &&
3811 (alloc_flags & ALLOC_CPUSET) &&
3812 !__cpuset_zone_allowed(zone, gfp_mask))
3813 continue;
3814 /*
3815 * When allocating a page cache page for writing, we
3816 * want to get it from a node that is within its dirty
3817 * limit, such that no single node holds more than its
3818 * proportional share of globally allowed dirty pages.
3819 * The dirty limits take into account the node's
3820 * lowmem reserves and high watermark so that kswapd
3821 * should be able to balance it without having to
3822 * write pages from its LRU list.
3823 *
3824 * XXX: For now, allow allocations to potentially
3825 * exceed the per-node dirty limit in the slowpath
3826 * (spread_dirty_pages unset) before going into reclaim,
3827 * which is important when on a NUMA setup the allowed
3828 * nodes are together not big enough to reach the
3829 * global limit. The proper fix for these situations
3830 * will require awareness of nodes in the
3831 * dirty-throttling and the flusher threads.
3832 */
3833 if (ac->spread_dirty_pages) {
3834 if (last_pgdat != zone->zone_pgdat) {
3835 last_pgdat = zone->zone_pgdat;
3836 last_pgdat_dirty_ok = node_dirty_ok(zone->zone_pgdat);
3837 }
3838
3839 if (!last_pgdat_dirty_ok)
3840 continue;
3841 }
3842
3843 if (no_fallback && !defrag_mode && nr_online_nodes > 1 &&
3844 zone != zonelist_zone(ac->preferred_zoneref)) {
3845 int local_nid;
3846
3847 /*
3848 * If moving to a remote node, retry but allow
3849 * fragmenting fallbacks. Locality is more important
3850 * than fragmentation avoidance.
3851 */
3852 local_nid = zonelist_node_idx(ac->preferred_zoneref);
3853 if (zone_to_nid(zone) != local_nid) {
3854 alloc_flags &= ~ALLOC_NOFRAGMENT;
3855 goto retry;
3856 }
3857 }
3858
3859 /*
3860 * If kswapd is already active on a node, keep looking
3861 * for other nodes that might be idle. This can happen
3862 * if another process has NUMA bindings and is causing
3863 * kswapd wakeups on only some nodes. Avoid accidental
3864 * "node_reclaim_mode"-like behavior in this case.
3865 */
3866 if (skip_kswapd_nodes &&
3867 !waitqueue_active(&zone->zone_pgdat->kswapd_wait)) {
3868 skipped_kswapd_nodes = true;
3869 continue;
3870 }
3871
3872 cond_accept_memory(zone, order, alloc_flags);
3873
3874 /*
3875 * Detect whether the number of free pages is below high
3876 * watermark. If so, we will decrease pcp->high and free
3877 * PCP pages in free path to reduce the possibility of
3878 * premature page reclaiming. Detection is done here to
3879 * avoid to do that in hotter free path.
3880 */
3881 if (test_bit(ZONE_BELOW_HIGH, &zone->flags))
3882 goto check_alloc_wmark;
3883
3884 mark = high_wmark_pages(zone);
3885 if (zone_watermark_fast(zone, order, mark,
3886 ac->highest_zoneidx, alloc_flags,
3887 gfp_mask))
3888 goto try_this_zone;
3889 else
3890 set_bit(ZONE_BELOW_HIGH, &zone->flags);
3891
3892 check_alloc_wmark:
3893 mark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK);
3894 if (!zone_watermark_fast(zone, order, mark,
3895 ac->highest_zoneidx, alloc_flags,
3896 gfp_mask)) {
3897 int ret;
3898
3899 if (cond_accept_memory(zone, order, alloc_flags))
3900 goto try_this_zone;
3901
3902 /*
3903 * Watermark failed for this zone, but see if we can
3904 * grow this zone if it contains deferred pages.
3905 */
3906 if (deferred_pages_enabled()) {
3907 if (_deferred_grow_zone(zone, order))
3908 goto try_this_zone;
3909 }
3910 /* Checked here to keep the fast path fast */
3911 BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK);
3912 if (alloc_flags & ALLOC_NO_WATERMARKS)
3913 goto try_this_zone;
3914
3915 if (!node_reclaim_enabled() ||
3916 !zone_allows_reclaim(zonelist_zone(ac->preferred_zoneref), zone))
3917 continue;
3918
3919 ret = node_reclaim(zone->zone_pgdat, gfp_mask, order);
3920 switch (ret) {
3921 case NODE_RECLAIM_NOSCAN:
3922 /* did not scan */
3923 continue;
3924 case NODE_RECLAIM_FULL:
3925 /* scanned but unreclaimable */
3926 continue;
3927 default:
3928 /* did we reclaim enough */
3929 if (zone_watermark_ok(zone, order, mark,
3930 ac->highest_zoneidx, alloc_flags))
3931 goto try_this_zone;
3932
3933 continue;
3934 }
3935 }
3936
3937 try_this_zone:
3938 page = rmqueue(zonelist_zone(ac->preferred_zoneref), zone, order,
3939 gfp_mask, alloc_flags, ac->migratetype);
3940 if (page) {
3941 prep_new_page(page, order, gfp_mask, alloc_flags);
3942
3943 return page;
3944 } else {
3945 if (cond_accept_memory(zone, order, alloc_flags))
3946 goto try_this_zone;
3947
3948 /* Try again if zone has deferred pages */
3949 if (deferred_pages_enabled()) {
3950 if (_deferred_grow_zone(zone, order))
3951 goto try_this_zone;
3952 }
3953 }
3954 }
3955
3956 /*
3957 * If we skipped over nodes with active kswapds and found no
3958 * idle nodes, retry and place anywhere the watermarks permit.
3959 */
3960 if (skip_kswapd_nodes && skipped_kswapd_nodes) {
3961 skip_kswapd_nodes = false;
3962 goto retry;
3963 }
3964
3965 /*
3966 * It's possible on a UMA machine to get through all zones that are
3967 * fragmented. If avoiding fragmentation, reset and try again.
3968 */
3969 if (no_fallback && !defrag_mode) {
3970 alloc_flags &= ~ALLOC_NOFRAGMENT;
3971 goto retry;
3972 }
3973
3974 return NULL;
3975 }
3976
warn_alloc_show_mem(gfp_t gfp_mask,nodemask_t * nodemask)3977 static void warn_alloc_show_mem(gfp_t gfp_mask, nodemask_t *nodemask)
3978 {
3979 unsigned int filter = SHOW_MEM_FILTER_NODES;
3980
3981 /*
3982 * This documents exceptions given to allocations in certain
3983 * contexts that are allowed to allocate outside current's set
3984 * of allowed nodes.
3985 */
3986 if (!(gfp_mask & __GFP_NOMEMALLOC))
3987 if (tsk_is_oom_victim(current) ||
3988 (current->flags & (PF_MEMALLOC | PF_EXITING)))
3989 filter &= ~SHOW_MEM_FILTER_NODES;
3990 if (!in_task() || !(gfp_mask & __GFP_DIRECT_RECLAIM))
3991 filter &= ~SHOW_MEM_FILTER_NODES;
3992
3993 __show_mem(filter, nodemask, gfp_zone(gfp_mask));
3994 mem_cgroup_show_protected_memory(NULL);
3995 }
3996
warn_alloc(gfp_t gfp_mask,nodemask_t * nodemask,const char * fmt,...)3997 void warn_alloc(gfp_t gfp_mask, nodemask_t *nodemask, const char *fmt, ...)
3998 {
3999 struct va_format vaf;
4000 va_list args;
4001 static DEFINE_RATELIMIT_STATE(nopage_rs, 10*HZ, 1);
4002
4003 if ((gfp_mask & __GFP_NOWARN) ||
4004 !__ratelimit(&nopage_rs) ||
4005 ((gfp_mask & __GFP_DMA) && !has_managed_dma()))
4006 return;
4007
4008 va_start(args, fmt);
4009 vaf.fmt = fmt;
4010 vaf.va = &args;
4011 pr_warn("%s: %pV, mode:%#x(%pGg), nodemask=%*pbl",
4012 current->comm, &vaf, gfp_mask, &gfp_mask,
4013 nodemask_pr_args(nodemask));
4014 va_end(args);
4015
4016 cpuset_print_current_mems_allowed();
4017 pr_cont("\n");
4018 dump_stack();
4019 warn_alloc_show_mem(gfp_mask, nodemask);
4020 }
4021
4022 static inline struct page *
__alloc_pages_cpuset_fallback(gfp_t gfp_mask,unsigned int order,unsigned int alloc_flags,const struct alloc_context * ac)4023 __alloc_pages_cpuset_fallback(gfp_t gfp_mask, unsigned int order,
4024 unsigned int alloc_flags,
4025 const struct alloc_context *ac)
4026 {
4027 struct page *page;
4028
4029 page = get_page_from_freelist(gfp_mask, order,
4030 alloc_flags|ALLOC_CPUSET, ac);
4031 /*
4032 * fallback to ignore cpuset restriction if our nodes
4033 * are depleted
4034 */
4035 if (!page)
4036 page = get_page_from_freelist(gfp_mask, order,
4037 alloc_flags, ac);
4038 return page;
4039 }
4040
4041 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)4042 __alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order,
4043 const struct alloc_context *ac, unsigned long *did_some_progress)
4044 {
4045 struct oom_control oc = {
4046 .zonelist = ac->zonelist,
4047 .nodemask = ac->nodemask,
4048 .memcg = NULL,
4049 .gfp_mask = gfp_mask,
4050 .order = order,
4051 };
4052 struct page *page;
4053
4054 *did_some_progress = 0;
4055
4056 /*
4057 * Acquire the oom lock. If that fails, somebody else is
4058 * making progress for us.
4059 */
4060 if (!mutex_trylock(&oom_lock)) {
4061 *did_some_progress = 1;
4062 schedule_timeout_uninterruptible(1);
4063 return NULL;
4064 }
4065
4066 /*
4067 * Go through the zonelist yet one more time, keep very high watermark
4068 * here, this is only to catch a parallel oom killing, we must fail if
4069 * we're still under heavy pressure. But make sure that this reclaim
4070 * attempt shall not depend on __GFP_DIRECT_RECLAIM && !__GFP_NORETRY
4071 * allocation which will never fail due to oom_lock already held.
4072 */
4073 page = get_page_from_freelist((gfp_mask | __GFP_HARDWALL) &
4074 ~__GFP_DIRECT_RECLAIM, order,
4075 ALLOC_WMARK_HIGH|ALLOC_CPUSET, ac);
4076 if (page)
4077 goto out;
4078
4079 /* Coredumps can quickly deplete all memory reserves */
4080 if (current->flags & PF_DUMPCORE)
4081 goto out;
4082 /* The OOM killer will not help higher order allocs */
4083 if (order > PAGE_ALLOC_COSTLY_ORDER)
4084 goto out;
4085 /*
4086 * We have already exhausted all our reclaim opportunities without any
4087 * success so it is time to admit defeat. We will skip the OOM killer
4088 * because it is very likely that the caller has a more reasonable
4089 * fallback than shooting a random task.
4090 *
4091 * The OOM killer may not free memory on a specific node.
4092 */
4093 if (gfp_mask & (__GFP_RETRY_MAYFAIL | __GFP_THISNODE))
4094 goto out;
4095 /* The OOM killer does not needlessly kill tasks for lowmem */
4096 if (ac->highest_zoneidx < ZONE_NORMAL)
4097 goto out;
4098 if (pm_suspended_storage())
4099 goto out;
4100 /*
4101 * XXX: GFP_NOFS allocations should rather fail than rely on
4102 * other request to make a forward progress.
4103 * We are in an unfortunate situation where out_of_memory cannot
4104 * do much for this context but let's try it to at least get
4105 * access to memory reserved if the current task is killed (see
4106 * out_of_memory). Once filesystems are ready to handle allocation
4107 * failures more gracefully we should just bail out here.
4108 */
4109
4110 /* Exhausted what can be done so it's blame time */
4111 if (out_of_memory(&oc) ||
4112 WARN_ON_ONCE_GFP(gfp_mask & __GFP_NOFAIL, gfp_mask)) {
4113 *did_some_progress = 1;
4114
4115 /*
4116 * Help non-failing allocations by giving them access to memory
4117 * reserves
4118 */
4119 if (gfp_mask & __GFP_NOFAIL)
4120 page = __alloc_pages_cpuset_fallback(gfp_mask, order,
4121 ALLOC_NO_WATERMARKS, ac);
4122 }
4123 out:
4124 mutex_unlock(&oom_lock);
4125 return page;
4126 }
4127
4128 /*
4129 * Maximum number of compaction retries with a progress before OOM
4130 * killer is consider as the only way to move forward.
4131 */
4132 #define MAX_COMPACT_RETRIES 16
4133
4134 #ifdef CONFIG_COMPACTION
4135 /* Try memory compaction for high-order allocations before reclaim */
4136 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)4137 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
4138 unsigned int alloc_flags, const struct alloc_context *ac,
4139 enum compact_priority prio, enum compact_result *compact_result)
4140 {
4141 struct page *page = NULL;
4142 unsigned long pflags;
4143 unsigned int noreclaim_flag;
4144
4145 if (!order)
4146 return NULL;
4147
4148 psi_memstall_enter(&pflags);
4149 delayacct_compact_start();
4150 noreclaim_flag = memalloc_noreclaim_save();
4151
4152 *compact_result = try_to_compact_pages(gfp_mask, order, alloc_flags, ac,
4153 prio, &page);
4154
4155 memalloc_noreclaim_restore(noreclaim_flag);
4156 psi_memstall_leave(&pflags);
4157 delayacct_compact_end();
4158
4159 if (*compact_result == COMPACT_SKIPPED)
4160 return NULL;
4161 /*
4162 * At least in one zone compaction wasn't deferred or skipped, so let's
4163 * count a compaction stall
4164 */
4165 count_vm_event(COMPACTSTALL);
4166
4167 /* Prep a captured page if available */
4168 if (page)
4169 prep_new_page(page, order, gfp_mask, alloc_flags);
4170
4171 /* Try get a page from the freelist if available */
4172 if (!page)
4173 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4174
4175 if (page) {
4176 struct zone *zone = page_zone(page);
4177
4178 zone->compact_blockskip_flush = false;
4179 compaction_defer_reset(zone, order, true);
4180 count_vm_event(COMPACTSUCCESS);
4181 return page;
4182 }
4183
4184 /*
4185 * It's bad if compaction run occurs and fails. The most likely reason
4186 * is that pages exist, but not enough to satisfy watermarks.
4187 */
4188 count_vm_event(COMPACTFAIL);
4189
4190 cond_resched();
4191
4192 return NULL;
4193 }
4194
4195 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)4196 should_compact_retry(struct alloc_context *ac, int order, int alloc_flags,
4197 enum compact_result compact_result,
4198 enum compact_priority *compact_priority,
4199 int *compaction_retries)
4200 {
4201 int max_retries = MAX_COMPACT_RETRIES;
4202 int min_priority;
4203 bool ret = false;
4204 int retries = *compaction_retries;
4205 enum compact_priority priority = *compact_priority;
4206
4207 if (!order)
4208 return false;
4209
4210 if (fatal_signal_pending(current))
4211 return false;
4212
4213 /*
4214 * Compaction was skipped due to a lack of free order-0
4215 * migration targets. Continue if reclaim can help.
4216 */
4217 if (compact_result == COMPACT_SKIPPED) {
4218 ret = compaction_zonelist_suitable(ac, order, alloc_flags);
4219 goto out;
4220 }
4221
4222 /*
4223 * Compaction managed to coalesce some page blocks, but the
4224 * allocation failed presumably due to a race. Retry some.
4225 */
4226 if (compact_result == COMPACT_SUCCESS) {
4227 /*
4228 * !costly requests are much more important than
4229 * __GFP_RETRY_MAYFAIL costly ones because they are de
4230 * facto nofail and invoke OOM killer to move on while
4231 * costly can fail and users are ready to cope with
4232 * that. 1/4 retries is rather arbitrary but we would
4233 * need much more detailed feedback from compaction to
4234 * make a better decision.
4235 */
4236 if (order > PAGE_ALLOC_COSTLY_ORDER)
4237 max_retries /= 4;
4238
4239 if (++(*compaction_retries) <= max_retries) {
4240 ret = true;
4241 goto out;
4242 }
4243 }
4244
4245 /*
4246 * Compaction failed. Retry with increasing priority.
4247 */
4248 min_priority = (order > PAGE_ALLOC_COSTLY_ORDER) ?
4249 MIN_COMPACT_COSTLY_PRIORITY : MIN_COMPACT_PRIORITY;
4250
4251 if (*compact_priority > min_priority) {
4252 (*compact_priority)--;
4253 *compaction_retries = 0;
4254 ret = true;
4255 }
4256 out:
4257 trace_compact_retry(order, priority, compact_result, retries, max_retries, ret);
4258 return ret;
4259 }
4260 #else
4261 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)4262 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
4263 unsigned int alloc_flags, const struct alloc_context *ac,
4264 enum compact_priority prio, enum compact_result *compact_result)
4265 {
4266 *compact_result = COMPACT_SKIPPED;
4267 return NULL;
4268 }
4269
4270 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)4271 should_compact_retry(struct alloc_context *ac, int order, int alloc_flags,
4272 enum compact_result compact_result,
4273 enum compact_priority *compact_priority,
4274 int *compaction_retries)
4275 {
4276 struct zone *zone;
4277 struct zoneref *z;
4278
4279 if (!order || order > PAGE_ALLOC_COSTLY_ORDER)
4280 return false;
4281
4282 /*
4283 * There are setups with compaction disabled which would prefer to loop
4284 * inside the allocator rather than hit the oom killer prematurely.
4285 * Let's give them a good hope and keep retrying while the order-0
4286 * watermarks are OK.
4287 */
4288 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
4289 ac->highest_zoneidx, ac->nodemask) {
4290 if (zone_watermark_ok(zone, 0, min_wmark_pages(zone),
4291 ac->highest_zoneidx, alloc_flags))
4292 return true;
4293 }
4294 return false;
4295 }
4296 #endif /* CONFIG_COMPACTION */
4297
4298 #ifdef CONFIG_LOCKDEP
4299 static struct lockdep_map __fs_reclaim_map =
4300 STATIC_LOCKDEP_MAP_INIT("fs_reclaim", &__fs_reclaim_map);
4301
__need_reclaim(gfp_t gfp_mask)4302 static bool __need_reclaim(gfp_t gfp_mask)
4303 {
4304 /* no reclaim without waiting on it */
4305 if (!(gfp_mask & __GFP_DIRECT_RECLAIM))
4306 return false;
4307
4308 /* this guy won't enter reclaim */
4309 if (current->flags & PF_MEMALLOC)
4310 return false;
4311
4312 if (gfp_mask & __GFP_NOLOCKDEP)
4313 return false;
4314
4315 return true;
4316 }
4317
__fs_reclaim_acquire(unsigned long ip)4318 void __fs_reclaim_acquire(unsigned long ip)
4319 {
4320 lock_acquire_exclusive(&__fs_reclaim_map, 0, 0, NULL, ip);
4321 }
4322
__fs_reclaim_release(unsigned long ip)4323 void __fs_reclaim_release(unsigned long ip)
4324 {
4325 lock_release(&__fs_reclaim_map, ip);
4326 }
4327
fs_reclaim_acquire(gfp_t gfp_mask)4328 void fs_reclaim_acquire(gfp_t gfp_mask)
4329 {
4330 gfp_mask = current_gfp_context(gfp_mask);
4331
4332 if (__need_reclaim(gfp_mask)) {
4333 if (gfp_mask & __GFP_FS)
4334 __fs_reclaim_acquire(_RET_IP_);
4335
4336 #ifdef CONFIG_MMU_NOTIFIER
4337 lock_map_acquire(&__mmu_notifier_invalidate_range_start_map);
4338 lock_map_release(&__mmu_notifier_invalidate_range_start_map);
4339 #endif
4340
4341 }
4342 }
4343 EXPORT_SYMBOL_GPL(fs_reclaim_acquire);
4344
fs_reclaim_release(gfp_t gfp_mask)4345 void fs_reclaim_release(gfp_t gfp_mask)
4346 {
4347 gfp_mask = current_gfp_context(gfp_mask);
4348
4349 if (__need_reclaim(gfp_mask)) {
4350 if (gfp_mask & __GFP_FS)
4351 __fs_reclaim_release(_RET_IP_);
4352 }
4353 }
4354 EXPORT_SYMBOL_GPL(fs_reclaim_release);
4355 #endif
4356
4357 /*
4358 * Zonelists may change due to hotplug during allocation. Detect when zonelists
4359 * have been rebuilt so allocation retries. Reader side does not lock and
4360 * retries the allocation if zonelist changes. Writer side is protected by the
4361 * embedded spin_lock.
4362 */
4363 static DEFINE_SEQLOCK(zonelist_update_seq);
4364
zonelist_iter_begin(void)4365 static unsigned int zonelist_iter_begin(void)
4366 {
4367 if (IS_ENABLED(CONFIG_MEMORY_HOTREMOVE))
4368 return read_seqbegin(&zonelist_update_seq);
4369
4370 return 0;
4371 }
4372
check_retry_zonelist(unsigned int seq)4373 static unsigned int check_retry_zonelist(unsigned int seq)
4374 {
4375 if (IS_ENABLED(CONFIG_MEMORY_HOTREMOVE))
4376 return read_seqretry(&zonelist_update_seq, seq);
4377
4378 return seq;
4379 }
4380
4381 /* Perform direct synchronous page reclaim */
4382 static unsigned long
__perform_reclaim(gfp_t gfp_mask,unsigned int order,const struct alloc_context * ac)4383 __perform_reclaim(gfp_t gfp_mask, unsigned int order,
4384 const struct alloc_context *ac)
4385 {
4386 unsigned int noreclaim_flag;
4387 unsigned long progress;
4388
4389 cond_resched();
4390
4391 /* We now go into synchronous reclaim */
4392 cpuset_memory_pressure_bump();
4393 fs_reclaim_acquire(gfp_mask);
4394 noreclaim_flag = memalloc_noreclaim_save();
4395
4396 progress = try_to_free_pages(ac->zonelist, order, gfp_mask,
4397 ac->nodemask);
4398
4399 memalloc_noreclaim_restore(noreclaim_flag);
4400 fs_reclaim_release(gfp_mask);
4401
4402 cond_resched();
4403
4404 return progress;
4405 }
4406
4407 /* The really slow allocator path where we enter direct reclaim */
4408 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)4409 __alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order,
4410 unsigned int alloc_flags, const struct alloc_context *ac,
4411 unsigned long *did_some_progress)
4412 {
4413 struct page *page = NULL;
4414 unsigned long pflags;
4415 bool drained = false;
4416
4417 psi_memstall_enter(&pflags);
4418 *did_some_progress = __perform_reclaim(gfp_mask, order, ac);
4419 if (unlikely(!(*did_some_progress)))
4420 goto out;
4421
4422 retry:
4423 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4424
4425 /*
4426 * If an allocation failed after direct reclaim, it could be because
4427 * pages are pinned on the per-cpu lists or in high alloc reserves.
4428 * Shrink them and try again
4429 */
4430 if (!page && !drained) {
4431 unreserve_highatomic_pageblock(ac, false);
4432 drain_all_pages(NULL);
4433 drained = true;
4434 goto retry;
4435 }
4436 out:
4437 psi_memstall_leave(&pflags);
4438
4439 return page;
4440 }
4441
wake_all_kswapds(unsigned int order,gfp_t gfp_mask,const struct alloc_context * ac)4442 static void wake_all_kswapds(unsigned int order, gfp_t gfp_mask,
4443 const struct alloc_context *ac)
4444 {
4445 struct zoneref *z;
4446 struct zone *zone;
4447 pg_data_t *last_pgdat = NULL;
4448 enum zone_type highest_zoneidx = ac->highest_zoneidx;
4449 unsigned int reclaim_order;
4450
4451 if (defrag_mode)
4452 reclaim_order = max(order, pageblock_order);
4453 else
4454 reclaim_order = order;
4455
4456 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, highest_zoneidx,
4457 ac->nodemask) {
4458 if (!managed_zone(zone))
4459 continue;
4460 if (last_pgdat == zone->zone_pgdat)
4461 continue;
4462 wakeup_kswapd(zone, gfp_mask, reclaim_order, highest_zoneidx);
4463 last_pgdat = zone->zone_pgdat;
4464 }
4465 }
4466
4467 static inline unsigned int
gfp_to_alloc_flags(gfp_t gfp_mask,unsigned int order)4468 gfp_to_alloc_flags(gfp_t gfp_mask, unsigned int order)
4469 {
4470 unsigned int alloc_flags = ALLOC_WMARK_MIN | ALLOC_CPUSET;
4471
4472 /*
4473 * __GFP_HIGH is assumed to be the same as ALLOC_MIN_RESERVE
4474 * and __GFP_KSWAPD_RECLAIM is assumed to be the same as ALLOC_KSWAPD
4475 * to save two branches.
4476 */
4477 BUILD_BUG_ON(__GFP_HIGH != (__force gfp_t) ALLOC_MIN_RESERVE);
4478 BUILD_BUG_ON(__GFP_KSWAPD_RECLAIM != (__force gfp_t) ALLOC_KSWAPD);
4479
4480 /*
4481 * The caller may dip into page reserves a bit more if the caller
4482 * cannot run direct reclaim, or if the caller has realtime scheduling
4483 * policy or is asking for __GFP_HIGH memory. GFP_ATOMIC requests will
4484 * set both ALLOC_NON_BLOCK and ALLOC_MIN_RESERVE(__GFP_HIGH).
4485 */
4486 alloc_flags |= (__force int)
4487 (gfp_mask & (__GFP_HIGH | __GFP_KSWAPD_RECLAIM));
4488
4489 if (!(gfp_mask & __GFP_DIRECT_RECLAIM)) {
4490 /*
4491 * Not worth trying to allocate harder for __GFP_NOMEMALLOC even
4492 * if it can't schedule.
4493 */
4494 if (!(gfp_mask & __GFP_NOMEMALLOC)) {
4495 alloc_flags |= ALLOC_NON_BLOCK;
4496
4497 if (order > 0 && (alloc_flags & ALLOC_MIN_RESERVE))
4498 alloc_flags |= ALLOC_HIGHATOMIC;
4499 }
4500
4501 /*
4502 * Ignore cpuset mems for non-blocking __GFP_HIGH (probably
4503 * GFP_ATOMIC) rather than fail, see the comment for
4504 * cpuset_current_node_allowed().
4505 */
4506 if (alloc_flags & ALLOC_MIN_RESERVE)
4507 alloc_flags &= ~ALLOC_CPUSET;
4508 } else if (unlikely(rt_or_dl_task(current)) && in_task())
4509 alloc_flags |= ALLOC_MIN_RESERVE;
4510
4511 alloc_flags = gfp_to_alloc_flags_cma(gfp_mask, alloc_flags);
4512
4513 if (defrag_mode)
4514 alloc_flags |= ALLOC_NOFRAGMENT;
4515
4516 return alloc_flags;
4517 }
4518
oom_reserves_allowed(struct task_struct * tsk)4519 static bool oom_reserves_allowed(struct task_struct *tsk)
4520 {
4521 if (!tsk_is_oom_victim(tsk))
4522 return false;
4523
4524 /*
4525 * !MMU doesn't have oom reaper so give access to memory reserves
4526 * only to the thread with TIF_MEMDIE set
4527 */
4528 if (!IS_ENABLED(CONFIG_MMU) && !test_thread_flag(TIF_MEMDIE))
4529 return false;
4530
4531 return true;
4532 }
4533
4534 /*
4535 * Distinguish requests which really need access to full memory
4536 * reserves from oom victims which can live with a portion of it
4537 */
__gfp_pfmemalloc_flags(gfp_t gfp_mask)4538 static inline int __gfp_pfmemalloc_flags(gfp_t gfp_mask)
4539 {
4540 if (unlikely(gfp_mask & __GFP_NOMEMALLOC))
4541 return 0;
4542 if (gfp_mask & __GFP_MEMALLOC)
4543 return ALLOC_NO_WATERMARKS;
4544 if (in_serving_softirq() && (current->flags & PF_MEMALLOC))
4545 return ALLOC_NO_WATERMARKS;
4546 if (!in_interrupt()) {
4547 if (current->flags & PF_MEMALLOC)
4548 return ALLOC_NO_WATERMARKS;
4549 else if (oom_reserves_allowed(current))
4550 return ALLOC_OOM;
4551 }
4552
4553 return 0;
4554 }
4555
gfp_pfmemalloc_allowed(gfp_t gfp_mask)4556 bool gfp_pfmemalloc_allowed(gfp_t gfp_mask)
4557 {
4558 return !!__gfp_pfmemalloc_flags(gfp_mask);
4559 }
4560
4561 /*
4562 * Checks whether it makes sense to retry the reclaim to make a forward progress
4563 * for the given allocation request.
4564 *
4565 * We give up when we either have tried MAX_RECLAIM_RETRIES in a row
4566 * without success, or when we couldn't even meet the watermark if we
4567 * reclaimed all remaining pages on the LRU lists.
4568 *
4569 * Returns true if a retry is viable or false to enter the oom path.
4570 */
4571 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)4572 should_reclaim_retry(gfp_t gfp_mask, unsigned order,
4573 struct alloc_context *ac, int alloc_flags,
4574 bool did_some_progress, int *no_progress_loops)
4575 {
4576 struct zone *zone;
4577 struct zoneref *z;
4578 bool ret = false;
4579
4580 /*
4581 * Costly allocations might have made a progress but this doesn't mean
4582 * their order will become available due to high fragmentation so
4583 * always increment the no progress counter for them
4584 */
4585 if (did_some_progress && order <= PAGE_ALLOC_COSTLY_ORDER)
4586 *no_progress_loops = 0;
4587 else
4588 (*no_progress_loops)++;
4589
4590 if (*no_progress_loops > MAX_RECLAIM_RETRIES)
4591 goto out;
4592
4593
4594 /*
4595 * Keep reclaiming pages while there is a chance this will lead
4596 * somewhere. If none of the target zones can satisfy our allocation
4597 * request even if all reclaimable pages are considered then we are
4598 * screwed and have to go OOM.
4599 */
4600 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
4601 ac->highest_zoneidx, ac->nodemask) {
4602 unsigned long available;
4603 unsigned long reclaimable;
4604 unsigned long min_wmark = min_wmark_pages(zone);
4605 bool wmark;
4606
4607 if (cpusets_enabled() &&
4608 (alloc_flags & ALLOC_CPUSET) &&
4609 !__cpuset_zone_allowed(zone, gfp_mask))
4610 continue;
4611
4612 available = reclaimable = zone_reclaimable_pages(zone);
4613 available += zone_page_state_snapshot(zone, NR_FREE_PAGES);
4614
4615 /*
4616 * Would the allocation succeed if we reclaimed all
4617 * reclaimable pages?
4618 */
4619 wmark = __zone_watermark_ok(zone, order, min_wmark,
4620 ac->highest_zoneidx, alloc_flags, available);
4621 trace_reclaim_retry_zone(z, order, reclaimable,
4622 available, min_wmark, *no_progress_loops, wmark);
4623 if (wmark) {
4624 ret = true;
4625 break;
4626 }
4627 }
4628
4629 /*
4630 * Memory allocation/reclaim might be called from a WQ context and the
4631 * current implementation of the WQ concurrency control doesn't
4632 * recognize that a particular WQ is congested if the worker thread is
4633 * looping without ever sleeping. Therefore we have to do a short sleep
4634 * here rather than calling cond_resched().
4635 */
4636 if (current->flags & PF_WQ_WORKER)
4637 schedule_timeout_uninterruptible(1);
4638 else
4639 cond_resched();
4640 out:
4641 /* Before OOM, exhaust highatomic_reserve */
4642 if (!ret)
4643 return unreserve_highatomic_pageblock(ac, true);
4644
4645 return ret;
4646 }
4647
4648 static inline bool
check_retry_cpuset(int cpuset_mems_cookie,struct alloc_context * ac)4649 check_retry_cpuset(int cpuset_mems_cookie, struct alloc_context *ac)
4650 {
4651 /*
4652 * It's possible that cpuset's mems_allowed and the nodemask from
4653 * mempolicy don't intersect. This should be normally dealt with by
4654 * policy_nodemask(), but it's possible to race with cpuset update in
4655 * such a way the check therein was true, and then it became false
4656 * before we got our cpuset_mems_cookie here.
4657 * This assumes that for all allocations, ac->nodemask can come only
4658 * from MPOL_BIND mempolicy (whose documented semantics is to be ignored
4659 * when it does not intersect with the cpuset restrictions) or the
4660 * caller can deal with a violated nodemask.
4661 */
4662 if (cpusets_enabled() && ac->nodemask &&
4663 !cpuset_nodemask_valid_mems_allowed(ac->nodemask)) {
4664 ac->nodemask = NULL;
4665 return true;
4666 }
4667
4668 /*
4669 * When updating a task's mems_allowed or mempolicy nodemask, it is
4670 * possible to race with parallel threads in such a way that our
4671 * allocation can fail while the mask is being updated. If we are about
4672 * to fail, check if the cpuset changed during allocation and if so,
4673 * retry.
4674 */
4675 if (read_mems_allowed_retry(cpuset_mems_cookie))
4676 return true;
4677
4678 return false;
4679 }
4680
4681 static inline struct page *
__alloc_pages_slowpath(gfp_t gfp_mask,unsigned int order,struct alloc_context * ac)4682 __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order,
4683 struct alloc_context *ac)
4684 {
4685 bool can_direct_reclaim = gfp_mask & __GFP_DIRECT_RECLAIM;
4686 bool can_compact = can_direct_reclaim && gfp_compaction_allowed(gfp_mask);
4687 bool nofail = gfp_mask & __GFP_NOFAIL;
4688 const bool costly_order = order > PAGE_ALLOC_COSTLY_ORDER;
4689 struct page *page = NULL;
4690 unsigned int alloc_flags;
4691 unsigned long did_some_progress;
4692 enum compact_priority compact_priority;
4693 enum compact_result compact_result;
4694 int compaction_retries;
4695 int no_progress_loops;
4696 unsigned int cpuset_mems_cookie;
4697 unsigned int zonelist_iter_cookie;
4698 int reserve_flags;
4699 bool compact_first = false;
4700 bool can_retry_reserves = true;
4701
4702 if (unlikely(nofail)) {
4703 /*
4704 * Also we don't support __GFP_NOFAIL without __GFP_DIRECT_RECLAIM,
4705 * otherwise, we may result in lockup.
4706 */
4707 WARN_ON_ONCE(!can_direct_reclaim);
4708 /*
4709 * PF_MEMALLOC request from this context is rather bizarre
4710 * because we cannot reclaim anything and only can loop waiting
4711 * for somebody to do a work for us.
4712 */
4713 WARN_ON_ONCE(current->flags & PF_MEMALLOC);
4714 }
4715
4716 restart:
4717 compaction_retries = 0;
4718 no_progress_loops = 0;
4719 compact_result = COMPACT_SKIPPED;
4720 compact_priority = DEF_COMPACT_PRIORITY;
4721 cpuset_mems_cookie = read_mems_allowed_begin();
4722 zonelist_iter_cookie = zonelist_iter_begin();
4723
4724 /*
4725 * For costly allocations, try direct compaction first, as it's likely
4726 * that we have enough base pages and don't need to reclaim. For non-
4727 * movable high-order allocations, do that as well, as compaction will
4728 * try prevent permanent fragmentation by migrating from blocks of the
4729 * same migratetype.
4730 */
4731 if (can_compact && (costly_order || (order > 0 &&
4732 ac->migratetype != MIGRATE_MOVABLE))) {
4733 compact_first = true;
4734 compact_priority = INIT_COMPACT_PRIORITY;
4735 }
4736
4737 /*
4738 * The fast path uses conservative alloc_flags to succeed only until
4739 * kswapd needs to be woken up, and to avoid the cost of setting up
4740 * alloc_flags precisely. So we do that now.
4741 */
4742 alloc_flags = gfp_to_alloc_flags(gfp_mask, order);
4743
4744 /*
4745 * We need to recalculate the starting point for the zonelist iterator
4746 * because we might have used different nodemask in the fast path, or
4747 * there was a cpuset modification and we are retrying - otherwise we
4748 * could end up iterating over non-eligible zones endlessly.
4749 */
4750 ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
4751 ac->highest_zoneidx, ac->nodemask);
4752 if (!zonelist_zone(ac->preferred_zoneref))
4753 goto nopage;
4754
4755 /*
4756 * Check for insane configurations where the cpuset doesn't contain
4757 * any suitable zone to satisfy the request - e.g. non-movable
4758 * GFP_HIGHUSER allocations from MOVABLE nodes only.
4759 */
4760 if (cpusets_insane_config() && (gfp_mask & __GFP_HARDWALL)) {
4761 struct zoneref *z = first_zones_zonelist(ac->zonelist,
4762 ac->highest_zoneidx,
4763 &cpuset_current_mems_allowed);
4764 if (!zonelist_zone(z))
4765 goto nopage;
4766 }
4767
4768 retry:
4769 /* Ensure kswapd doesn't accidentally go to sleep as long as we loop */
4770 if (alloc_flags & ALLOC_KSWAPD)
4771 wake_all_kswapds(order, gfp_mask, ac);
4772
4773 /*
4774 * The adjusted alloc_flags might result in immediate success, so try
4775 * that first
4776 */
4777 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4778 if (page)
4779 goto got_pg;
4780
4781 reserve_flags = __gfp_pfmemalloc_flags(gfp_mask);
4782 if (reserve_flags)
4783 alloc_flags = gfp_to_alloc_flags_cma(gfp_mask, reserve_flags) |
4784 (alloc_flags & ALLOC_KSWAPD);
4785
4786 /*
4787 * Reset the nodemask and zonelist iterators if memory policies can be
4788 * ignored. These allocations are high priority and system rather than
4789 * user oriented.
4790 */
4791 if (!(alloc_flags & ALLOC_CPUSET) || reserve_flags) {
4792 ac->nodemask = NULL;
4793 ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
4794 ac->highest_zoneidx, ac->nodemask);
4795
4796 /*
4797 * The first time we adjust anything due to being allowed to
4798 * ignore memory policies or watermarks, retry immediately. This
4799 * allows us to keep the first allocation attempt optimistic so
4800 * it can succeed in a zone that is still above watermarks.
4801 */
4802 if (can_retry_reserves) {
4803 can_retry_reserves = false;
4804 goto retry;
4805 }
4806 }
4807
4808 /* Caller is not willing to reclaim, we can't balance anything */
4809 if (!can_direct_reclaim)
4810 goto nopage;
4811
4812 /* Avoid recursion of direct reclaim */
4813 if (current->flags & PF_MEMALLOC)
4814 goto nopage;
4815
4816 /* Try direct reclaim and then allocating */
4817 if (!compact_first) {
4818 page = __alloc_pages_direct_reclaim(gfp_mask, order, alloc_flags,
4819 ac, &did_some_progress);
4820 if (page)
4821 goto got_pg;
4822 }
4823
4824 /* Try direct compaction and then allocating */
4825 page = __alloc_pages_direct_compact(gfp_mask, order, alloc_flags, ac,
4826 compact_priority, &compact_result);
4827 if (page)
4828 goto got_pg;
4829
4830 if (compact_first) {
4831 /*
4832 * THP page faults may attempt local node only first, but are
4833 * then allowed to only compact, not reclaim, see
4834 * alloc_pages_mpol().
4835 *
4836 * Compaction has failed above and we don't want such THP
4837 * allocations to put reclaim pressure on a single node in a
4838 * situation where other nodes might have plenty of available
4839 * memory.
4840 */
4841 if (gfp_has_flags(gfp_mask, __GFP_NORETRY | __GFP_THISNODE))
4842 goto nopage;
4843
4844 /*
4845 * For the initial compaction attempt we have lowered its
4846 * priority. Restore it for further retries, if those are
4847 * allowed. With __GFP_NORETRY there will be a single round of
4848 * reclaim and compaction with the lowered priority.
4849 */
4850 if (!(gfp_mask & __GFP_NORETRY))
4851 compact_priority = DEF_COMPACT_PRIORITY;
4852
4853 compact_first = false;
4854 goto retry;
4855 }
4856
4857 /* Do not loop if specifically requested */
4858 if (gfp_mask & __GFP_NORETRY)
4859 goto nopage;
4860
4861 /*
4862 * Do not retry costly high order allocations unless they are
4863 * __GFP_RETRY_MAYFAIL and we can compact
4864 */
4865 if (costly_order && (!can_compact ||
4866 !(gfp_mask & __GFP_RETRY_MAYFAIL)))
4867 goto nopage;
4868
4869 /*
4870 * Deal with possible cpuset update races or zonelist updates to avoid
4871 * infinite retries. No "goto retry;" can be placed above this check
4872 * unless it can execute just once.
4873 */
4874 if (check_retry_cpuset(cpuset_mems_cookie, ac) ||
4875 check_retry_zonelist(zonelist_iter_cookie))
4876 goto restart;
4877
4878 if (should_reclaim_retry(gfp_mask, order, ac, alloc_flags,
4879 did_some_progress > 0, &no_progress_loops))
4880 goto retry;
4881
4882 /*
4883 * It doesn't make any sense to retry for the compaction if the order-0
4884 * reclaim is not able to make any progress because the current
4885 * implementation of the compaction depends on the sufficient amount
4886 * of free memory (see __compaction_suitable)
4887 */
4888 if (did_some_progress > 0 && can_compact &&
4889 should_compact_retry(ac, order, alloc_flags,
4890 compact_result, &compact_priority,
4891 &compaction_retries))
4892 goto retry;
4893
4894 /* Reclaim/compaction failed to prevent the fallback */
4895 if (defrag_mode && (alloc_flags & ALLOC_NOFRAGMENT)) {
4896 alloc_flags &= ~ALLOC_NOFRAGMENT;
4897 goto retry;
4898 }
4899
4900 /*
4901 * Deal with possible cpuset update races or zonelist updates to avoid
4902 * a unnecessary OOM kill.
4903 */
4904 if (check_retry_cpuset(cpuset_mems_cookie, ac) ||
4905 check_retry_zonelist(zonelist_iter_cookie))
4906 goto restart;
4907
4908 /* Reclaim has failed us, start killing things */
4909 page = __alloc_pages_may_oom(gfp_mask, order, ac, &did_some_progress);
4910 if (page)
4911 goto got_pg;
4912
4913 /* Avoid allocations with no watermarks from looping endlessly */
4914 if (tsk_is_oom_victim(current) &&
4915 (alloc_flags & ALLOC_OOM ||
4916 (gfp_mask & __GFP_NOMEMALLOC)))
4917 goto nopage;
4918
4919 /* Retry as long as the OOM killer is making progress */
4920 if (did_some_progress) {
4921 no_progress_loops = 0;
4922 goto retry;
4923 }
4924
4925 nopage:
4926 /*
4927 * Deal with possible cpuset update races or zonelist updates to avoid
4928 * a unnecessary OOM kill.
4929 */
4930 if (check_retry_cpuset(cpuset_mems_cookie, ac) ||
4931 check_retry_zonelist(zonelist_iter_cookie))
4932 goto restart;
4933
4934 /*
4935 * Make sure that __GFP_NOFAIL request doesn't leak out and make sure
4936 * we always retry
4937 */
4938 if (unlikely(nofail)) {
4939 /*
4940 * Lacking direct_reclaim we can't do anything to reclaim memory,
4941 * we disregard these unreasonable nofail requests and still
4942 * return NULL
4943 */
4944 if (!can_direct_reclaim)
4945 goto fail;
4946
4947 /*
4948 * Help non-failing allocations by giving some access to memory
4949 * reserves normally used for high priority non-blocking
4950 * allocations but do not use ALLOC_NO_WATERMARKS because this
4951 * could deplete whole memory reserves which would just make
4952 * the situation worse.
4953 */
4954 page = __alloc_pages_cpuset_fallback(gfp_mask, order, ALLOC_MIN_RESERVE, ac);
4955 if (page)
4956 goto got_pg;
4957
4958 cond_resched();
4959 goto retry;
4960 }
4961 fail:
4962 warn_alloc(gfp_mask, ac->nodemask,
4963 "page allocation failure: order:%u", order);
4964 got_pg:
4965 return page;
4966 }
4967
prepare_alloc_pages(gfp_t gfp_mask,unsigned int order,int preferred_nid,nodemask_t * nodemask,struct alloc_context * ac,gfp_t * alloc_gfp,unsigned int * alloc_flags)4968 static inline bool prepare_alloc_pages(gfp_t gfp_mask, unsigned int order,
4969 int preferred_nid, nodemask_t *nodemask,
4970 struct alloc_context *ac, gfp_t *alloc_gfp,
4971 unsigned int *alloc_flags)
4972 {
4973 ac->highest_zoneidx = gfp_zone(gfp_mask);
4974 ac->zonelist = node_zonelist(preferred_nid, gfp_mask);
4975 ac->nodemask = nodemask;
4976 ac->migratetype = gfp_migratetype(gfp_mask);
4977
4978 if (cpusets_enabled()) {
4979 *alloc_gfp |= __GFP_HARDWALL;
4980 /*
4981 * When we are in the interrupt context, it is irrelevant
4982 * to the current task context. It means that any node ok.
4983 */
4984 if (in_task() && !ac->nodemask)
4985 ac->nodemask = &cpuset_current_mems_allowed;
4986 else
4987 *alloc_flags |= ALLOC_CPUSET;
4988 }
4989
4990 might_alloc(gfp_mask);
4991
4992 /*
4993 * Don't invoke should_fail logic, since it may call
4994 * get_random_u32() and printk() which need to spin_lock.
4995 */
4996 if (!(*alloc_flags & ALLOC_TRYLOCK) &&
4997 should_fail_alloc_page(gfp_mask, order))
4998 return false;
4999
5000 *alloc_flags = gfp_to_alloc_flags_cma(gfp_mask, *alloc_flags);
5001
5002 /* Dirty zone balancing only done in the fast path */
5003 ac->spread_dirty_pages = (gfp_mask & __GFP_WRITE);
5004
5005 /*
5006 * The preferred zone is used for statistics but crucially it is
5007 * also used as the starting point for the zonelist iterator. It
5008 * may get reset for allocations that ignore memory policies.
5009 */
5010 ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
5011 ac->highest_zoneidx, ac->nodemask);
5012
5013 return true;
5014 }
5015
5016 /*
5017 * __alloc_pages_bulk - Allocate a number of order-0 pages to an array
5018 * @gfp: GFP flags for the allocation
5019 * @preferred_nid: The preferred NUMA node ID to allocate from
5020 * @nodemask: Set of nodes to allocate from, may be NULL
5021 * @nr_pages: The number of pages desired in the array
5022 * @page_array: Array to store the pages
5023 *
5024 * This is a batched version of the page allocator that attempts to allocate
5025 * @nr_pages quickly. Pages are added to @page_array.
5026 *
5027 * Note that only the elements in @page_array that were cleared to %NULL on
5028 * entry are populated with newly allocated pages. @nr_pages is the maximum
5029 * number of pages that will be stored in the array.
5030 *
5031 * Returns the number of pages in @page_array, including ones already
5032 * allocated on entry. This can be less than the number requested in @nr_pages,
5033 * but all empty slots are filled from the beginning. I.e., if all slots in
5034 * @page_array were set to %NULL on entry, the slots from 0 to the return value
5035 * - 1 will be filled.
5036 */
alloc_pages_bulk_noprof(gfp_t gfp,int preferred_nid,nodemask_t * nodemask,int nr_pages,struct page ** page_array)5037 unsigned long alloc_pages_bulk_noprof(gfp_t gfp, int preferred_nid,
5038 nodemask_t *nodemask, int nr_pages,
5039 struct page **page_array)
5040 {
5041 struct page *page;
5042 struct zone *zone;
5043 struct zoneref *z;
5044 struct per_cpu_pages *pcp;
5045 struct list_head *pcp_list;
5046 struct alloc_context ac;
5047 gfp_t alloc_gfp;
5048 unsigned int alloc_flags = ALLOC_WMARK_LOW;
5049 int nr_populated = 0, nr_account = 0;
5050
5051 /*
5052 * Skip populated array elements to determine if any pages need
5053 * to be allocated before disabling IRQs.
5054 */
5055 while (nr_populated < nr_pages && page_array[nr_populated])
5056 nr_populated++;
5057
5058 /* No pages requested? */
5059 if (unlikely(nr_pages <= 0))
5060 goto out;
5061
5062 /* Already populated array? */
5063 if (unlikely(nr_pages - nr_populated == 0))
5064 goto out;
5065
5066 /* Bulk allocator does not support memcg accounting. */
5067 if (memcg_kmem_online() && (gfp & __GFP_ACCOUNT))
5068 goto failed;
5069
5070 /* Use the single page allocator for one page. */
5071 if (nr_pages - nr_populated == 1)
5072 goto failed;
5073
5074 #ifdef CONFIG_PAGE_OWNER
5075 /*
5076 * PAGE_OWNER may recurse into the allocator to allocate space to
5077 * save the stack with pagesets.lock held. Releasing/reacquiring
5078 * removes much of the performance benefit of bulk allocation so
5079 * force the caller to allocate one page at a time as it'll have
5080 * similar performance to added complexity to the bulk allocator.
5081 */
5082 if (static_branch_unlikely(&page_owner_inited))
5083 goto failed;
5084 #endif
5085
5086 /* May set ALLOC_NOFRAGMENT, fragmentation will return 1 page. */
5087 gfp &= gfp_allowed_mask;
5088 alloc_gfp = gfp;
5089 if (!prepare_alloc_pages(gfp, 0, preferred_nid, nodemask, &ac, &alloc_gfp, &alloc_flags))
5090 goto out;
5091 gfp = alloc_gfp;
5092
5093 /* Find an allowed local zone that meets the low watermark. */
5094 z = ac.preferred_zoneref;
5095 for_next_zone_zonelist_nodemask(zone, z, ac.highest_zoneidx, ac.nodemask) {
5096 unsigned long mark;
5097
5098 if (cpusets_enabled() && (alloc_flags & ALLOC_CPUSET) &&
5099 !__cpuset_zone_allowed(zone, gfp)) {
5100 continue;
5101 }
5102
5103 if (nr_online_nodes > 1 && zone != zonelist_zone(ac.preferred_zoneref) &&
5104 zone_to_nid(zone) != zonelist_node_idx(ac.preferred_zoneref)) {
5105 goto failed;
5106 }
5107
5108 cond_accept_memory(zone, 0, alloc_flags);
5109 retry_this_zone:
5110 mark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK) + nr_pages - nr_populated;
5111 if (zone_watermark_fast(zone, 0, mark,
5112 zonelist_zone_idx(ac.preferred_zoneref),
5113 alloc_flags, gfp)) {
5114 break;
5115 }
5116
5117 if (cond_accept_memory(zone, 0, alloc_flags))
5118 goto retry_this_zone;
5119
5120 /* Try again if zone has deferred pages */
5121 if (deferred_pages_enabled()) {
5122 if (_deferred_grow_zone(zone, 0))
5123 goto retry_this_zone;
5124 }
5125 }
5126
5127 /*
5128 * If there are no allowed local zones that meets the watermarks then
5129 * try to allocate a single page and reclaim if necessary.
5130 */
5131 if (unlikely(!zone))
5132 goto failed;
5133
5134 /* spin_trylock may fail due to a parallel drain or IRQ reentrancy. */
5135 pcp = pcp_spin_trylock(zone->per_cpu_pageset);
5136 if (!pcp)
5137 goto failed;
5138
5139 /* Attempt the batch allocation */
5140 pcp_list = &pcp->lists[order_to_pindex(ac.migratetype, 0)];
5141 while (nr_populated < nr_pages) {
5142
5143 /* Skip existing pages */
5144 if (page_array[nr_populated]) {
5145 nr_populated++;
5146 continue;
5147 }
5148
5149 page = __rmqueue_pcplist(zone, 0, ac.migratetype, alloc_flags,
5150 pcp, pcp_list);
5151 if (unlikely(!page)) {
5152 /* Try and allocate at least one page */
5153 if (!nr_account) {
5154 pcp_spin_unlock(pcp);
5155 goto failed;
5156 }
5157 break;
5158 }
5159 nr_account++;
5160
5161 prep_new_page(page, 0, gfp, 0);
5162 set_page_refcounted(page);
5163 page_array[nr_populated++] = page;
5164 }
5165
5166 pcp_spin_unlock(pcp);
5167
5168 __count_zid_vm_events(PGALLOC, zone_idx(zone), nr_account);
5169 zone_statistics(zonelist_zone(ac.preferred_zoneref), zone, nr_account);
5170
5171 out:
5172 return nr_populated;
5173
5174 failed:
5175 page = __alloc_pages_noprof(gfp, 0, preferred_nid, nodemask);
5176 if (page)
5177 page_array[nr_populated++] = page;
5178 goto out;
5179 }
5180 EXPORT_SYMBOL_GPL(alloc_pages_bulk_noprof);
5181
5182 /*
5183 * This is the 'heart' of the zoned buddy allocator.
5184 */
__alloc_frozen_pages_noprof(gfp_t gfp,unsigned int order,int preferred_nid,nodemask_t * nodemask)5185 struct page *__alloc_frozen_pages_noprof(gfp_t gfp, unsigned int order,
5186 int preferred_nid, nodemask_t *nodemask)
5187 {
5188 struct page *page;
5189 unsigned int alloc_flags = ALLOC_WMARK_LOW;
5190 gfp_t alloc_gfp; /* The gfp_t that was actually used for allocation */
5191 struct alloc_context ac = { };
5192
5193 /*
5194 * There are several places where we assume that the order value is sane
5195 * so bail out early if the request is out of bound.
5196 */
5197 if (WARN_ON_ONCE_GFP(order > MAX_PAGE_ORDER, gfp))
5198 return NULL;
5199
5200 gfp &= gfp_allowed_mask;
5201 /*
5202 * Apply scoped allocation constraints. This is mainly about GFP_NOFS
5203 * resp. GFP_NOIO which has to be inherited for all allocation requests
5204 * from a particular context which has been marked by
5205 * memalloc_no{fs,io}_{save,restore}. And PF_MEMALLOC_PIN which ensures
5206 * movable zones are not used during allocation.
5207 */
5208 gfp = current_gfp_context(gfp);
5209 alloc_gfp = gfp;
5210 if (!prepare_alloc_pages(gfp, order, preferred_nid, nodemask, &ac,
5211 &alloc_gfp, &alloc_flags))
5212 return NULL;
5213
5214 /*
5215 * Forbid the first pass from falling back to types that fragment
5216 * memory until all local zones are considered.
5217 */
5218 alloc_flags |= alloc_flags_nofragment(zonelist_zone(ac.preferred_zoneref), gfp);
5219
5220 /* First allocation attempt */
5221 page = get_page_from_freelist(alloc_gfp, order, alloc_flags, &ac);
5222 if (likely(page))
5223 goto out;
5224
5225 alloc_gfp = gfp;
5226 ac.spread_dirty_pages = false;
5227
5228 /*
5229 * Restore the original nodemask if it was potentially replaced with
5230 * &cpuset_current_mems_allowed to optimize the fast-path attempt.
5231 */
5232 ac.nodemask = nodemask;
5233
5234 page = __alloc_pages_slowpath(alloc_gfp, order, &ac);
5235
5236 out:
5237 if (memcg_kmem_online() && (gfp & __GFP_ACCOUNT) && page &&
5238 unlikely(__memcg_kmem_charge_page(page, gfp, order) != 0)) {
5239 free_frozen_pages(page, order);
5240 page = NULL;
5241 }
5242
5243 trace_mm_page_alloc(page, order, alloc_gfp, ac.migratetype);
5244 kmsan_alloc_page(page, order, alloc_gfp);
5245
5246 return page;
5247 }
5248 EXPORT_SYMBOL(__alloc_frozen_pages_noprof);
5249
__alloc_pages_noprof(gfp_t gfp,unsigned int order,int preferred_nid,nodemask_t * nodemask)5250 struct page *__alloc_pages_noprof(gfp_t gfp, unsigned int order,
5251 int preferred_nid, nodemask_t *nodemask)
5252 {
5253 struct page *page;
5254
5255 page = __alloc_frozen_pages_noprof(gfp, order, preferred_nid, nodemask);
5256 if (page)
5257 set_page_refcounted(page);
5258 return page;
5259 }
5260 EXPORT_SYMBOL(__alloc_pages_noprof);
5261
__folio_alloc_noprof(gfp_t gfp,unsigned int order,int preferred_nid,nodemask_t * nodemask)5262 struct folio *__folio_alloc_noprof(gfp_t gfp, unsigned int order, int preferred_nid,
5263 nodemask_t *nodemask)
5264 {
5265 struct page *page = __alloc_pages_noprof(gfp | __GFP_COMP, order,
5266 preferred_nid, nodemask);
5267 return page_rmappable_folio(page);
5268 }
5269 EXPORT_SYMBOL(__folio_alloc_noprof);
5270
5271 /*
5272 * Common helper functions. Never use with __GFP_HIGHMEM because the returned
5273 * address cannot represent highmem pages. Use alloc_pages and then kmap if
5274 * you need to access high mem.
5275 */
get_free_pages_noprof(gfp_t gfp_mask,unsigned int order)5276 unsigned long get_free_pages_noprof(gfp_t gfp_mask, unsigned int order)
5277 {
5278 struct page *page;
5279
5280 page = alloc_pages_noprof(gfp_mask & ~__GFP_HIGHMEM, order);
5281 if (!page)
5282 return 0;
5283 return (unsigned long) page_address(page);
5284 }
5285 EXPORT_SYMBOL(get_free_pages_noprof);
5286
get_zeroed_page_noprof(gfp_t gfp_mask)5287 unsigned long get_zeroed_page_noprof(gfp_t gfp_mask)
5288 {
5289 return get_free_pages_noprof(gfp_mask | __GFP_ZERO, 0);
5290 }
5291 EXPORT_SYMBOL(get_zeroed_page_noprof);
5292
___free_pages(struct page * page,unsigned int order,fpi_t fpi_flags)5293 static void ___free_pages(struct page *page, unsigned int order,
5294 fpi_t fpi_flags)
5295 {
5296 /* get PageHead before we drop reference */
5297 int head = PageHead(page);
5298 /* get alloc tag in case the page is released by others */
5299 struct alloc_tag *tag = pgalloc_tag_get(page);
5300
5301 if (put_page_testzero(page))
5302 __free_frozen_pages(page, order, fpi_flags);
5303 else if (!head) {
5304 pgalloc_tag_sub_pages(tag, (1 << order) - 1);
5305 while (order-- > 0) {
5306 /*
5307 * The "tail" pages of this non-compound high-order
5308 * page will have no code tags, so to avoid warnings
5309 * mark them as empty.
5310 */
5311 clear_page_tag_ref(page + (1 << order));
5312 __free_frozen_pages(page + (1 << order), order,
5313 fpi_flags);
5314 }
5315 }
5316 }
5317
5318 /**
5319 * __free_pages - Free pages allocated with alloc_pages().
5320 * @page: The page pointer returned from alloc_pages().
5321 * @order: The order of the allocation.
5322 *
5323 * This function can free multi-page allocations that are not compound
5324 * pages. It does not check that the @order passed in matches that of
5325 * the allocation, so it is easy to leak memory. Freeing more memory
5326 * than was allocated will probably emit a warning.
5327 *
5328 * If the last reference to this page is speculative, it will be released
5329 * by put_page() which only frees the first page of a non-compound
5330 * allocation. To prevent the remaining pages from being leaked, we free
5331 * the subsequent pages here. If you want to use the page's reference
5332 * count to decide when to free the allocation, you should allocate a
5333 * compound page, and use put_page() instead of __free_pages().
5334 *
5335 * Context: May be called in interrupt context or while holding a normal
5336 * spinlock, but not in NMI context or while holding a raw spinlock.
5337 */
__free_pages(struct page * page,unsigned int order)5338 void __free_pages(struct page *page, unsigned int order)
5339 {
5340 ___free_pages(page, order, FPI_NONE);
5341 }
5342 EXPORT_SYMBOL(__free_pages);
5343
5344 /*
5345 * Can be called while holding raw_spin_lock or from IRQ and NMI for any
5346 * page type (not only those that came from alloc_pages_nolock)
5347 */
free_pages_nolock(struct page * page,unsigned int order)5348 void free_pages_nolock(struct page *page, unsigned int order)
5349 {
5350 ___free_pages(page, order, FPI_TRYLOCK);
5351 }
5352
5353 /**
5354 * free_pages - Free pages allocated with __get_free_pages().
5355 * @addr: The virtual address tied to a page returned from __get_free_pages().
5356 * @order: The order of the allocation.
5357 *
5358 * This function behaves the same as __free_pages(). Use this function
5359 * to free pages when you only have a valid virtual address. If you have
5360 * the page, call __free_pages() instead.
5361 */
free_pages(unsigned long addr,unsigned int order)5362 void free_pages(unsigned long addr, unsigned int order)
5363 {
5364 if (addr != 0) {
5365 VM_BUG_ON(!virt_addr_valid((void *)addr));
5366 __free_pages(virt_to_page((void *)addr), order);
5367 }
5368 }
5369
5370 EXPORT_SYMBOL(free_pages);
5371
make_alloc_exact(unsigned long addr,unsigned int order,size_t size)5372 static void *make_alloc_exact(unsigned long addr, unsigned int order,
5373 size_t size)
5374 {
5375 if (addr) {
5376 unsigned long nr = DIV_ROUND_UP(size, PAGE_SIZE);
5377 struct page *page = virt_to_page((void *)addr);
5378 struct page *last = page + nr;
5379
5380 __split_page(page, order);
5381 while (page < --last)
5382 set_page_refcounted(last);
5383
5384 last = page + (1UL << order);
5385 for (page += nr; page < last; page++)
5386 __free_pages_ok(page, 0, FPI_TO_TAIL);
5387 }
5388 return (void *)addr;
5389 }
5390
5391 /**
5392 * alloc_pages_exact - allocate an exact number physically-contiguous pages.
5393 * @size: the number of bytes to allocate
5394 * @gfp_mask: GFP flags for the allocation, must not contain __GFP_COMP
5395 *
5396 * This function is similar to alloc_pages(), except that it allocates the
5397 * minimum number of pages to satisfy the request. alloc_pages() can only
5398 * allocate memory in power-of-two pages.
5399 *
5400 * This function is also limited by MAX_PAGE_ORDER.
5401 *
5402 * Memory allocated by this function must be released by free_pages_exact().
5403 *
5404 * Return: pointer to the allocated area or %NULL in case of error.
5405 */
alloc_pages_exact_noprof(size_t size,gfp_t gfp_mask)5406 void *alloc_pages_exact_noprof(size_t size, gfp_t gfp_mask)
5407 {
5408 unsigned int order = get_order(size);
5409 unsigned long addr;
5410
5411 if (WARN_ON_ONCE(gfp_mask & (__GFP_COMP | __GFP_HIGHMEM)))
5412 gfp_mask &= ~(__GFP_COMP | __GFP_HIGHMEM);
5413
5414 addr = get_free_pages_noprof(gfp_mask, order);
5415 return make_alloc_exact(addr, order, size);
5416 }
5417 EXPORT_SYMBOL(alloc_pages_exact_noprof);
5418
5419 /**
5420 * alloc_pages_exact_nid - allocate an exact number of physically-contiguous
5421 * pages on a node.
5422 * @nid: the preferred node ID where memory should be allocated
5423 * @size: the number of bytes to allocate
5424 * @gfp_mask: GFP flags for the allocation, must not contain __GFP_COMP
5425 *
5426 * Like alloc_pages_exact(), but try to allocate on node nid first before falling
5427 * back.
5428 *
5429 * Return: pointer to the allocated area or %NULL in case of error.
5430 */
alloc_pages_exact_nid_noprof(int nid,size_t size,gfp_t gfp_mask)5431 void * __meminit alloc_pages_exact_nid_noprof(int nid, size_t size, gfp_t gfp_mask)
5432 {
5433 unsigned int order = get_order(size);
5434 struct page *p;
5435
5436 if (WARN_ON_ONCE(gfp_mask & (__GFP_COMP | __GFP_HIGHMEM)))
5437 gfp_mask &= ~(__GFP_COMP | __GFP_HIGHMEM);
5438
5439 p = alloc_pages_node_noprof(nid, gfp_mask, order);
5440 if (!p)
5441 return NULL;
5442 return make_alloc_exact((unsigned long)page_address(p), order, size);
5443 }
5444
5445 /**
5446 * free_pages_exact - release memory allocated via alloc_pages_exact()
5447 * @virt: the value returned by alloc_pages_exact.
5448 * @size: size of allocation, same value as passed to alloc_pages_exact().
5449 *
5450 * Release the memory allocated by a previous call to alloc_pages_exact.
5451 */
free_pages_exact(void * virt,size_t size)5452 void free_pages_exact(void *virt, size_t size)
5453 {
5454 unsigned long addr = (unsigned long)virt;
5455 unsigned long end = addr + PAGE_ALIGN(size);
5456
5457 while (addr < end) {
5458 free_page(addr);
5459 addr += PAGE_SIZE;
5460 }
5461 }
5462 EXPORT_SYMBOL(free_pages_exact);
5463
5464 /**
5465 * nr_free_zone_pages - count number of pages beyond high watermark
5466 * @offset: The zone index of the highest zone
5467 *
5468 * nr_free_zone_pages() counts the number of pages which are beyond the
5469 * high watermark within all zones at or below a given zone index. For each
5470 * zone, the number of pages is calculated as:
5471 *
5472 * nr_free_zone_pages = managed_pages - high_pages
5473 *
5474 * Return: number of pages beyond high watermark.
5475 */
nr_free_zone_pages(int offset)5476 static unsigned long nr_free_zone_pages(int offset)
5477 {
5478 struct zoneref *z;
5479 struct zone *zone;
5480
5481 /* Just pick one node, since fallback list is circular */
5482 unsigned long sum = 0;
5483
5484 struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL);
5485
5486 for_each_zone_zonelist(zone, z, zonelist, offset) {
5487 unsigned long size = zone_managed_pages(zone);
5488 unsigned long high = high_wmark_pages(zone);
5489 if (size > high)
5490 sum += size - high;
5491 }
5492
5493 return sum;
5494 }
5495
5496 /**
5497 * nr_free_buffer_pages - count number of pages beyond high watermark
5498 *
5499 * nr_free_buffer_pages() counts the number of pages which are beyond the high
5500 * watermark within ZONE_DMA and ZONE_NORMAL.
5501 *
5502 * Return: number of pages beyond high watermark within ZONE_DMA and
5503 * ZONE_NORMAL.
5504 */
nr_free_buffer_pages(void)5505 unsigned long nr_free_buffer_pages(void)
5506 {
5507 return nr_free_zone_pages(gfp_zone(GFP_USER));
5508 }
5509 EXPORT_SYMBOL_GPL(nr_free_buffer_pages);
5510
zoneref_set_zone(struct zone * zone,struct zoneref * zoneref)5511 static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref)
5512 {
5513 zoneref->zone = zone;
5514 zoneref->zone_idx = zone_idx(zone);
5515 }
5516
5517 /*
5518 * Builds allocation fallback zone lists.
5519 *
5520 * Add all populated zones of a node to the zonelist.
5521 */
build_zonerefs_node(pg_data_t * pgdat,struct zoneref * zonerefs)5522 static int build_zonerefs_node(pg_data_t *pgdat, struct zoneref *zonerefs)
5523 {
5524 struct zone *zone;
5525 enum zone_type zone_type = MAX_NR_ZONES;
5526 int nr_zones = 0;
5527
5528 do {
5529 zone_type--;
5530 zone = pgdat->node_zones + zone_type;
5531 if (populated_zone(zone)) {
5532 zoneref_set_zone(zone, &zonerefs[nr_zones++]);
5533 check_highest_zone(zone_type);
5534 }
5535 } while (zone_type);
5536
5537 return nr_zones;
5538 }
5539
5540 #ifdef CONFIG_NUMA
5541
__parse_numa_zonelist_order(char * s)5542 static int __parse_numa_zonelist_order(char *s)
5543 {
5544 /*
5545 * We used to support different zonelists modes but they turned
5546 * out to be just not useful. Let's keep the warning in place
5547 * if somebody still use the cmd line parameter so that we do
5548 * not fail it silently
5549 */
5550 if (!(*s == 'd' || *s == 'D' || *s == 'n' || *s == 'N')) {
5551 pr_warn("Ignoring unsupported numa_zonelist_order value: %s\n", s);
5552 return -EINVAL;
5553 }
5554 return 0;
5555 }
5556
5557 static char numa_zonelist_order[] = "Node";
5558 #define NUMA_ZONELIST_ORDER_LEN 16
5559 /*
5560 * sysctl handler for numa_zonelist_order
5561 */
numa_zonelist_order_handler(const struct ctl_table * table,int write,void * buffer,size_t * length,loff_t * ppos)5562 static int numa_zonelist_order_handler(const struct ctl_table *table, int write,
5563 void *buffer, size_t *length, loff_t *ppos)
5564 {
5565 if (write)
5566 return __parse_numa_zonelist_order(buffer);
5567 return proc_dostring(table, write, buffer, length, ppos);
5568 }
5569
5570 static int node_load[MAX_NUMNODES];
5571
5572 /**
5573 * find_next_best_node - find the next node that should appear in a given node's fallback list
5574 * @node: node whose fallback list we're appending
5575 * @used_node_mask: nodemask_t of already used nodes
5576 *
5577 * We use a number of factors to determine which is the next node that should
5578 * appear on a given node's fallback list. The node should not have appeared
5579 * already in @node's fallback list, and it should be the next closest node
5580 * according to the distance array (which contains arbitrary distance values
5581 * from each node to each node in the system), and should also prefer nodes
5582 * with no CPUs, since presumably they'll have very little allocation pressure
5583 * on them otherwise.
5584 *
5585 * Return: node id of the found node or %NUMA_NO_NODE if no node is found.
5586 */
find_next_best_node(int node,nodemask_t * used_node_mask)5587 int find_next_best_node(int node, nodemask_t *used_node_mask)
5588 {
5589 int n, val;
5590 int min_val = INT_MAX;
5591 int best_node = NUMA_NO_NODE;
5592
5593 /*
5594 * Use the local node if we haven't already, but for memoryless local
5595 * node, we should skip it and fall back to other nodes.
5596 */
5597 if (!node_isset(node, *used_node_mask) && node_state(node, N_MEMORY)) {
5598 node_set(node, *used_node_mask);
5599 return node;
5600 }
5601
5602 for_each_node_state(n, N_MEMORY) {
5603
5604 /* Don't want a node to appear more than once */
5605 if (node_isset(n, *used_node_mask))
5606 continue;
5607
5608 /* Use the distance array to find the distance */
5609 val = node_distance(node, n);
5610
5611 /* Penalize nodes under us ("prefer the next node") */
5612 val += (n < node);
5613
5614 /* Give preference to headless and unused nodes */
5615 if (!cpumask_empty(cpumask_of_node(n)))
5616 val += PENALTY_FOR_NODE_WITH_CPUS;
5617
5618 /* Slight preference for less loaded node */
5619 val *= MAX_NUMNODES;
5620 val += node_load[n];
5621
5622 if (val < min_val) {
5623 min_val = val;
5624 best_node = n;
5625 }
5626 }
5627
5628 if (best_node >= 0)
5629 node_set(best_node, *used_node_mask);
5630
5631 return best_node;
5632 }
5633
5634
5635 /*
5636 * Build zonelists ordered by node and zones within node.
5637 * This results in maximum locality--normal zone overflows into local
5638 * DMA zone, if any--but risks exhausting DMA zone.
5639 */
build_zonelists_in_node_order(pg_data_t * pgdat,int * node_order,unsigned nr_nodes)5640 static void build_zonelists_in_node_order(pg_data_t *pgdat, int *node_order,
5641 unsigned nr_nodes)
5642 {
5643 struct zoneref *zonerefs;
5644 int i;
5645
5646 zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs;
5647
5648 for (i = 0; i < nr_nodes; i++) {
5649 int nr_zones;
5650
5651 pg_data_t *node = NODE_DATA(node_order[i]);
5652
5653 nr_zones = build_zonerefs_node(node, zonerefs);
5654 zonerefs += nr_zones;
5655 }
5656 zonerefs->zone = NULL;
5657 zonerefs->zone_idx = 0;
5658 }
5659
5660 /*
5661 * Build __GFP_THISNODE zonelists
5662 */
build_thisnode_zonelists(pg_data_t * pgdat)5663 static void build_thisnode_zonelists(pg_data_t *pgdat)
5664 {
5665 struct zoneref *zonerefs;
5666 int nr_zones;
5667
5668 zonerefs = pgdat->node_zonelists[ZONELIST_NOFALLBACK]._zonerefs;
5669 nr_zones = build_zonerefs_node(pgdat, zonerefs);
5670 zonerefs += nr_zones;
5671 zonerefs->zone = NULL;
5672 zonerefs->zone_idx = 0;
5673 }
5674
build_zonelists(pg_data_t * pgdat)5675 static void build_zonelists(pg_data_t *pgdat)
5676 {
5677 static int node_order[MAX_NUMNODES];
5678 int node, nr_nodes = 0;
5679 nodemask_t used_mask = NODE_MASK_NONE;
5680 int local_node, prev_node;
5681
5682 /* NUMA-aware ordering of nodes */
5683 local_node = pgdat->node_id;
5684 prev_node = local_node;
5685
5686 memset(node_order, 0, sizeof(node_order));
5687 while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
5688 /*
5689 * We don't want to pressure a particular node.
5690 * So adding penalty to the first node in same
5691 * distance group to make it round-robin.
5692 */
5693 if (node_distance(local_node, node) !=
5694 node_distance(local_node, prev_node))
5695 node_load[node] += 1;
5696
5697 node_order[nr_nodes++] = node;
5698 prev_node = node;
5699 }
5700
5701 build_zonelists_in_node_order(pgdat, node_order, nr_nodes);
5702 build_thisnode_zonelists(pgdat);
5703 pr_info("Fallback order for Node %d: ", local_node);
5704 for (node = 0; node < nr_nodes; node++)
5705 pr_cont("%d ", node_order[node]);
5706 pr_cont("\n");
5707 }
5708
5709 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
5710 /*
5711 * Return node id of node used for "local" allocations.
5712 * I.e., first node id of first zone in arg node's generic zonelist.
5713 * Used for initializing percpu 'numa_mem', which is used primarily
5714 * for kernel allocations, so use GFP_KERNEL flags to locate zonelist.
5715 */
local_memory_node(int node)5716 int local_memory_node(int node)
5717 {
5718 struct zoneref *z;
5719
5720 z = first_zones_zonelist(node_zonelist(node, GFP_KERNEL),
5721 gfp_zone(GFP_KERNEL),
5722 NULL);
5723 return zonelist_node_idx(z);
5724 }
5725 #endif
5726
5727 static void setup_min_unmapped_ratio(void);
5728 static void setup_min_slab_ratio(void);
5729 #else /* CONFIG_NUMA */
5730
build_zonelists(pg_data_t * pgdat)5731 static void build_zonelists(pg_data_t *pgdat)
5732 {
5733 struct zoneref *zonerefs;
5734 int nr_zones;
5735
5736 zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs;
5737 nr_zones = build_zonerefs_node(pgdat, zonerefs);
5738 zonerefs += nr_zones;
5739
5740 zonerefs->zone = NULL;
5741 zonerefs->zone_idx = 0;
5742 }
5743
5744 #endif /* CONFIG_NUMA */
5745
5746 /*
5747 * Boot pageset table. One per cpu which is going to be used for all
5748 * zones and all nodes. The parameters will be set in such a way
5749 * that an item put on a list will immediately be handed over to
5750 * the buddy list. This is safe since pageset manipulation is done
5751 * with interrupts disabled.
5752 *
5753 * The boot_pagesets must be kept even after bootup is complete for
5754 * unused processors and/or zones. They do play a role for bootstrapping
5755 * hotplugged processors.
5756 *
5757 * zoneinfo_show() and maybe other functions do
5758 * not check if the processor is online before following the pageset pointer.
5759 * Other parts of the kernel may not check if the zone is available.
5760 */
5761 static void per_cpu_pages_init(struct per_cpu_pages *pcp, struct per_cpu_zonestat *pzstats);
5762 /* These effectively disable the pcplists in the boot pageset completely */
5763 #define BOOT_PAGESET_HIGH 0
5764 #define BOOT_PAGESET_BATCH 1
5765 static DEFINE_PER_CPU(struct per_cpu_pages, boot_pageset);
5766 static DEFINE_PER_CPU(struct per_cpu_zonestat, boot_zonestats);
5767
__build_all_zonelists(void * data)5768 static void __build_all_zonelists(void *data)
5769 {
5770 int nid;
5771 int __maybe_unused cpu;
5772 pg_data_t *self = data;
5773 unsigned long flags;
5774
5775 /*
5776 * The zonelist_update_seq must be acquired with irqsave because the
5777 * reader can be invoked from IRQ with GFP_ATOMIC.
5778 */
5779 write_seqlock_irqsave(&zonelist_update_seq, flags);
5780 /*
5781 * Also disable synchronous printk() to prevent any printk() from
5782 * trying to hold port->lock, for
5783 * tty_insert_flip_string_and_push_buffer() on other CPU might be
5784 * calling kmalloc(GFP_ATOMIC | __GFP_NOWARN) with port->lock held.
5785 */
5786 printk_deferred_enter();
5787
5788 #ifdef CONFIG_NUMA
5789 memset(node_load, 0, sizeof(node_load));
5790 #endif
5791
5792 /*
5793 * This node is hotadded and no memory is yet present. So just
5794 * building zonelists is fine - no need to touch other nodes.
5795 */
5796 if (self && !node_online(self->node_id)) {
5797 build_zonelists(self);
5798 } else {
5799 /*
5800 * All possible nodes have pgdat preallocated
5801 * in free_area_init
5802 */
5803 for_each_node(nid) {
5804 pg_data_t *pgdat = NODE_DATA(nid);
5805
5806 build_zonelists(pgdat);
5807 }
5808
5809 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
5810 /*
5811 * We now know the "local memory node" for each node--
5812 * i.e., the node of the first zone in the generic zonelist.
5813 * Set up numa_mem percpu variable for on-line cpus. During
5814 * boot, only the boot cpu should be on-line; we'll init the
5815 * secondary cpus' numa_mem as they come on-line. During
5816 * node/memory hotplug, we'll fixup all on-line cpus.
5817 */
5818 for_each_online_cpu(cpu)
5819 set_cpu_numa_mem(cpu, local_memory_node(cpu_to_node(cpu)));
5820 #endif
5821 }
5822
5823 printk_deferred_exit();
5824 write_sequnlock_irqrestore(&zonelist_update_seq, flags);
5825 }
5826
5827 static noinline void __init
build_all_zonelists_init(void)5828 build_all_zonelists_init(void)
5829 {
5830 int cpu;
5831
5832 __build_all_zonelists(NULL);
5833
5834 /*
5835 * Initialize the boot_pagesets that are going to be used
5836 * for bootstrapping processors. The real pagesets for
5837 * each zone will be allocated later when the per cpu
5838 * allocator is available.
5839 *
5840 * boot_pagesets are used also for bootstrapping offline
5841 * cpus if the system is already booted because the pagesets
5842 * are needed to initialize allocators on a specific cpu too.
5843 * F.e. the percpu allocator needs the page allocator which
5844 * needs the percpu allocator in order to allocate its pagesets
5845 * (a chicken-egg dilemma).
5846 */
5847 for_each_possible_cpu(cpu)
5848 per_cpu_pages_init(&per_cpu(boot_pageset, cpu), &per_cpu(boot_zonestats, cpu));
5849
5850 mminit_verify_zonelist();
5851 cpuset_init_current_mems_allowed();
5852 }
5853
5854 /*
5855 * unless system_state == SYSTEM_BOOTING.
5856 *
5857 * __ref due to call of __init annotated helper build_all_zonelists_init
5858 * [protected by SYSTEM_BOOTING].
5859 */
build_all_zonelists(pg_data_t * pgdat)5860 void __ref build_all_zonelists(pg_data_t *pgdat)
5861 {
5862 unsigned long vm_total_pages;
5863
5864 if (system_state == SYSTEM_BOOTING) {
5865 build_all_zonelists_init();
5866 } else {
5867 __build_all_zonelists(pgdat);
5868 /* cpuset refresh routine should be here */
5869 }
5870 /* Get the number of free pages beyond high watermark in all zones. */
5871 vm_total_pages = nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE));
5872 /*
5873 * Disable grouping by mobility if the number of pages in the
5874 * system is too low to allow the mechanism to work. It would be
5875 * more accurate, but expensive to check per-zone. This check is
5876 * made on memory-hotadd so a system can start with mobility
5877 * disabled and enable it later
5878 */
5879 if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES))
5880 page_group_by_mobility_disabled = 1;
5881 else
5882 page_group_by_mobility_disabled = 0;
5883
5884 pr_info("Built %u zonelists, mobility grouping %s. Total pages: %ld\n",
5885 nr_online_nodes,
5886 str_off_on(page_group_by_mobility_disabled),
5887 vm_total_pages);
5888 #ifdef CONFIG_NUMA
5889 pr_info("Policy zone: %s\n", zone_names[policy_zone]);
5890 #endif
5891 }
5892
zone_batchsize(struct zone * zone)5893 static int zone_batchsize(struct zone *zone)
5894 {
5895 #ifdef CONFIG_MMU
5896 int batch;
5897
5898 /*
5899 * The number of pages to batch allocate is either ~0.025%
5900 * of the zone or 256KB, whichever is smaller. The batch
5901 * size is striking a balance between allocation latency
5902 * and zone lock contention.
5903 */
5904 batch = min(zone_managed_pages(zone) >> 12, SZ_256K / PAGE_SIZE);
5905 if (batch <= 1)
5906 return 1;
5907
5908 /*
5909 * Clamp the batch to a 2^n - 1 value. Having a power
5910 * of 2 value was found to be more likely to have
5911 * suboptimal cache aliasing properties in some cases.
5912 *
5913 * For example if 2 tasks are alternately allocating
5914 * batches of pages, one task can end up with a lot
5915 * of pages of one half of the possible page colors
5916 * and the other with pages of the other colors.
5917 */
5918 batch = rounddown_pow_of_two(batch + batch/2) - 1;
5919
5920 return batch;
5921
5922 #else
5923 /* The deferral and batching of frees should be suppressed under NOMMU
5924 * conditions.
5925 *
5926 * The problem is that NOMMU needs to be able to allocate large chunks
5927 * of contiguous memory as there's no hardware page translation to
5928 * assemble apparent contiguous memory from discontiguous pages.
5929 *
5930 * Queueing large contiguous runs of pages for batching, however,
5931 * causes the pages to actually be freed in smaller chunks. As there
5932 * can be a significant delay between the individual batches being
5933 * recycled, this leads to the once large chunks of space being
5934 * fragmented and becoming unavailable for high-order allocations.
5935 */
5936 return 1;
5937 #endif
5938 }
5939
5940 static int percpu_pagelist_high_fraction;
zone_highsize(struct zone * zone,int batch,int cpu_online,int high_fraction)5941 static int zone_highsize(struct zone *zone, int batch, int cpu_online,
5942 int high_fraction)
5943 {
5944 #ifdef CONFIG_MMU
5945 int high;
5946 int nr_split_cpus;
5947 unsigned long total_pages;
5948
5949 if (!high_fraction) {
5950 /*
5951 * By default, the high value of the pcp is based on the zone
5952 * low watermark so that if they are full then background
5953 * reclaim will not be started prematurely.
5954 */
5955 total_pages = low_wmark_pages(zone);
5956 } else {
5957 /*
5958 * If percpu_pagelist_high_fraction is configured, the high
5959 * value is based on a fraction of the managed pages in the
5960 * zone.
5961 */
5962 total_pages = zone_managed_pages(zone) / high_fraction;
5963 }
5964
5965 /*
5966 * Split the high value across all online CPUs local to the zone. Note
5967 * that early in boot that CPUs may not be online yet and that during
5968 * CPU hotplug that the cpumask is not yet updated when a CPU is being
5969 * onlined. For memory nodes that have no CPUs, split the high value
5970 * across all online CPUs to mitigate the risk that reclaim is triggered
5971 * prematurely due to pages stored on pcp lists.
5972 */
5973 nr_split_cpus = cpumask_weight(cpumask_of_node(zone_to_nid(zone))) + cpu_online;
5974 if (!nr_split_cpus)
5975 nr_split_cpus = num_online_cpus();
5976 high = total_pages / nr_split_cpus;
5977
5978 /*
5979 * Ensure high is at least batch*4. The multiple is based on the
5980 * historical relationship between high and batch.
5981 */
5982 high = max(high, batch << 2);
5983
5984 return high;
5985 #else
5986 return 0;
5987 #endif
5988 }
5989
5990 /*
5991 * pcp->high and pcp->batch values are related and generally batch is lower
5992 * than high. They are also related to pcp->count such that count is lower
5993 * than high, and as soon as it reaches high, the pcplist is flushed.
5994 *
5995 * However, guaranteeing these relations at all times would require e.g. write
5996 * barriers here but also careful usage of read barriers at the read side, and
5997 * thus be prone to error and bad for performance. Thus the update only prevents
5998 * store tearing. Any new users of pcp->batch, pcp->high_min and pcp->high_max
5999 * should ensure they can cope with those fields changing asynchronously, and
6000 * fully trust only the pcp->count field on the local CPU with interrupts
6001 * disabled.
6002 *
6003 * mutex_is_locked(&pcp_batch_high_lock) required when calling this function
6004 * outside of boot time (or some other assurance that no concurrent updaters
6005 * exist).
6006 */
pageset_update(struct per_cpu_pages * pcp,unsigned long high_min,unsigned long high_max,unsigned long batch)6007 static void pageset_update(struct per_cpu_pages *pcp, unsigned long high_min,
6008 unsigned long high_max, unsigned long batch)
6009 {
6010 WRITE_ONCE(pcp->batch, batch);
6011 WRITE_ONCE(pcp->high_min, high_min);
6012 WRITE_ONCE(pcp->high_max, high_max);
6013 }
6014
per_cpu_pages_init(struct per_cpu_pages * pcp,struct per_cpu_zonestat * pzstats)6015 static void per_cpu_pages_init(struct per_cpu_pages *pcp, struct per_cpu_zonestat *pzstats)
6016 {
6017 int pindex;
6018
6019 memset(pcp, 0, sizeof(*pcp));
6020 memset(pzstats, 0, sizeof(*pzstats));
6021
6022 spin_lock_init(&pcp->lock);
6023 for (pindex = 0; pindex < NR_PCP_LISTS; pindex++)
6024 INIT_LIST_HEAD(&pcp->lists[pindex]);
6025
6026 /*
6027 * Set batch and high values safe for a boot pageset. A true percpu
6028 * pageset's initialization will update them subsequently. Here we don't
6029 * need to be as careful as pageset_update() as nobody can access the
6030 * pageset yet.
6031 */
6032 pcp->high_min = BOOT_PAGESET_HIGH;
6033 pcp->high_max = BOOT_PAGESET_HIGH;
6034 pcp->batch = BOOT_PAGESET_BATCH;
6035 }
6036
__zone_set_pageset_high_and_batch(struct zone * zone,unsigned long high_min,unsigned long high_max,unsigned long batch)6037 static void __zone_set_pageset_high_and_batch(struct zone *zone, unsigned long high_min,
6038 unsigned long high_max, unsigned long batch)
6039 {
6040 struct per_cpu_pages *pcp;
6041 int cpu;
6042
6043 for_each_possible_cpu(cpu) {
6044 pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu);
6045 pageset_update(pcp, high_min, high_max, batch);
6046 }
6047 }
6048
6049 /*
6050 * Calculate and set new high and batch values for all per-cpu pagesets of a
6051 * zone based on the zone's size.
6052 */
zone_set_pageset_high_and_batch(struct zone * zone,int cpu_online)6053 static void zone_set_pageset_high_and_batch(struct zone *zone, int cpu_online)
6054 {
6055 int new_high_min, new_high_max, new_batch;
6056
6057 new_batch = zone_batchsize(zone);
6058 if (percpu_pagelist_high_fraction) {
6059 new_high_min = zone_highsize(zone, new_batch, cpu_online,
6060 percpu_pagelist_high_fraction);
6061 /*
6062 * PCP high is tuned manually, disable auto-tuning via
6063 * setting high_min and high_max to the manual value.
6064 */
6065 new_high_max = new_high_min;
6066 } else {
6067 new_high_min = zone_highsize(zone, new_batch, cpu_online, 0);
6068 new_high_max = zone_highsize(zone, new_batch, cpu_online,
6069 MIN_PERCPU_PAGELIST_HIGH_FRACTION);
6070 }
6071
6072 if (zone->pageset_high_min == new_high_min &&
6073 zone->pageset_high_max == new_high_max &&
6074 zone->pageset_batch == new_batch)
6075 return;
6076
6077 zone->pageset_high_min = new_high_min;
6078 zone->pageset_high_max = new_high_max;
6079 zone->pageset_batch = new_batch;
6080
6081 __zone_set_pageset_high_and_batch(zone, new_high_min, new_high_max,
6082 new_batch);
6083 }
6084
setup_zone_pageset(struct zone * zone)6085 void __meminit setup_zone_pageset(struct zone *zone)
6086 {
6087 int cpu;
6088
6089 /* Size may be 0 on !SMP && !NUMA */
6090 if (sizeof(struct per_cpu_zonestat) > 0)
6091 zone->per_cpu_zonestats = alloc_percpu(struct per_cpu_zonestat);
6092
6093 zone->per_cpu_pageset = alloc_percpu(struct per_cpu_pages);
6094 for_each_possible_cpu(cpu) {
6095 struct per_cpu_pages *pcp;
6096 struct per_cpu_zonestat *pzstats;
6097
6098 pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu);
6099 pzstats = per_cpu_ptr(zone->per_cpu_zonestats, cpu);
6100 per_cpu_pages_init(pcp, pzstats);
6101 }
6102
6103 zone_set_pageset_high_and_batch(zone, 0);
6104 }
6105
6106 /*
6107 * The zone indicated has a new number of managed_pages; batch sizes and percpu
6108 * page high values need to be recalculated.
6109 */
zone_pcp_update(struct zone * zone,int cpu_online)6110 static void zone_pcp_update(struct zone *zone, int cpu_online)
6111 {
6112 mutex_lock(&pcp_batch_high_lock);
6113 zone_set_pageset_high_and_batch(zone, cpu_online);
6114 mutex_unlock(&pcp_batch_high_lock);
6115 }
6116
zone_pcp_update_cacheinfo(struct zone * zone,unsigned int cpu)6117 static void zone_pcp_update_cacheinfo(struct zone *zone, unsigned int cpu)
6118 {
6119 struct per_cpu_pages *pcp;
6120 struct cpu_cacheinfo *cci;
6121
6122 pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu);
6123 cci = get_cpu_cacheinfo(cpu);
6124 /*
6125 * If data cache slice of CPU is large enough, "pcp->batch"
6126 * pages can be preserved in PCP before draining PCP for
6127 * consecutive high-order pages freeing without allocation.
6128 * This can reduce zone lock contention without hurting
6129 * cache-hot pages sharing.
6130 */
6131 pcp_spin_lock_nopin(pcp);
6132 if ((cci->per_cpu_data_slice_size >> PAGE_SHIFT) > 3 * pcp->batch)
6133 pcp->flags |= PCPF_FREE_HIGH_BATCH;
6134 else
6135 pcp->flags &= ~PCPF_FREE_HIGH_BATCH;
6136 pcp_spin_unlock_nopin(pcp);
6137 }
6138
setup_pcp_cacheinfo(unsigned int cpu)6139 void setup_pcp_cacheinfo(unsigned int cpu)
6140 {
6141 struct zone *zone;
6142
6143 for_each_populated_zone(zone)
6144 zone_pcp_update_cacheinfo(zone, cpu);
6145 }
6146
6147 /*
6148 * Allocate per cpu pagesets and initialize them.
6149 * Before this call only boot pagesets were available.
6150 */
setup_per_cpu_pageset(void)6151 void __init setup_per_cpu_pageset(void)
6152 {
6153 struct pglist_data *pgdat;
6154 struct zone *zone;
6155 int __maybe_unused cpu;
6156
6157 for_each_populated_zone(zone)
6158 setup_zone_pageset(zone);
6159
6160 #ifdef CONFIG_NUMA
6161 /*
6162 * Unpopulated zones continue using the boot pagesets.
6163 * The numa stats for these pagesets need to be reset.
6164 * Otherwise, they will end up skewing the stats of
6165 * the nodes these zones are associated with.
6166 */
6167 for_each_possible_cpu(cpu) {
6168 struct per_cpu_zonestat *pzstats = &per_cpu(boot_zonestats, cpu);
6169 memset(pzstats->vm_numa_event, 0,
6170 sizeof(pzstats->vm_numa_event));
6171 }
6172 #endif
6173
6174 for_each_online_pgdat(pgdat)
6175 pgdat->per_cpu_nodestats =
6176 alloc_percpu(struct per_cpu_nodestat);
6177 }
6178
zone_pcp_init(struct zone * zone)6179 __meminit void zone_pcp_init(struct zone *zone)
6180 {
6181 /*
6182 * per cpu subsystem is not up at this point. The following code
6183 * relies on the ability of the linker to provide the
6184 * offset of a (static) per cpu variable into the per cpu area.
6185 */
6186 zone->per_cpu_pageset = &boot_pageset;
6187 zone->per_cpu_zonestats = &boot_zonestats;
6188 zone->pageset_high_min = BOOT_PAGESET_HIGH;
6189 zone->pageset_high_max = BOOT_PAGESET_HIGH;
6190 zone->pageset_batch = BOOT_PAGESET_BATCH;
6191
6192 if (populated_zone(zone))
6193 pr_debug(" %s zone: %lu pages, LIFO batch:%u\n", zone->name,
6194 zone->present_pages, zone_batchsize(zone));
6195 }
6196
6197 static void setup_per_zone_lowmem_reserve(void);
6198
adjust_managed_page_count(struct page * page,long count)6199 void adjust_managed_page_count(struct page *page, long count)
6200 {
6201 atomic_long_add(count, &page_zone(page)->managed_pages);
6202 totalram_pages_add(count);
6203 setup_per_zone_lowmem_reserve();
6204 }
6205 EXPORT_SYMBOL(adjust_managed_page_count);
6206
free_reserved_page(struct page * page)6207 void free_reserved_page(struct page *page)
6208 {
6209 clear_page_tag_ref(page);
6210 ClearPageReserved(page);
6211 init_page_count(page);
6212 __free_page(page);
6213 adjust_managed_page_count(page, 1);
6214 }
6215 EXPORT_SYMBOL(free_reserved_page);
6216
page_alloc_cpu_dead(unsigned int cpu)6217 static int page_alloc_cpu_dead(unsigned int cpu)
6218 {
6219 struct zone *zone;
6220
6221 lru_add_drain_cpu(cpu);
6222 mlock_drain_remote(cpu);
6223 drain_pages(cpu);
6224
6225 /*
6226 * Spill the event counters of the dead processor
6227 * into the current processors event counters.
6228 * This artificially elevates the count of the current
6229 * processor.
6230 */
6231 vm_events_fold_cpu(cpu);
6232
6233 /*
6234 * Zero the differential counters of the dead processor
6235 * so that the vm statistics are consistent.
6236 *
6237 * This is only okay since the processor is dead and cannot
6238 * race with what we are doing.
6239 */
6240 cpu_vm_stats_fold(cpu);
6241
6242 for_each_populated_zone(zone)
6243 zone_pcp_update(zone, 0);
6244
6245 return 0;
6246 }
6247
page_alloc_cpu_online(unsigned int cpu)6248 static int page_alloc_cpu_online(unsigned int cpu)
6249 {
6250 struct zone *zone;
6251
6252 for_each_populated_zone(zone)
6253 zone_pcp_update(zone, 1);
6254 return 0;
6255 }
6256
page_alloc_init_cpuhp(void)6257 void __init page_alloc_init_cpuhp(void)
6258 {
6259 int ret;
6260
6261 ret = cpuhp_setup_state_nocalls(CPUHP_PAGE_ALLOC,
6262 "mm/page_alloc:pcp",
6263 page_alloc_cpu_online,
6264 page_alloc_cpu_dead);
6265 WARN_ON(ret < 0);
6266 }
6267
6268 /*
6269 * calculate_totalreserve_pages - called when sysctl_lowmem_reserve_ratio
6270 * or min_free_kbytes changes.
6271 */
calculate_totalreserve_pages(void)6272 static void calculate_totalreserve_pages(void)
6273 {
6274 struct pglist_data *pgdat;
6275 unsigned long reserve_pages = 0;
6276 enum zone_type i, j;
6277
6278 for_each_online_pgdat(pgdat) {
6279
6280 pgdat->totalreserve_pages = 0;
6281
6282 for (i = 0; i < MAX_NR_ZONES; i++) {
6283 struct zone *zone = pgdat->node_zones + i;
6284 long max = 0;
6285 unsigned long managed_pages = zone_managed_pages(zone);
6286
6287 /*
6288 * lowmem_reserve[j] is monotonically non-decreasing
6289 * in j for a given zone (see
6290 * setup_per_zone_lowmem_reserve()). The maximum
6291 * valid reserve lives at the highest index with a
6292 * non-zero value, so scan backwards and stop at the
6293 * first hit.
6294 */
6295 for (j = MAX_NR_ZONES - 1; j > i; j--) {
6296 if (!zone->lowmem_reserve[j])
6297 continue;
6298
6299 max = zone->lowmem_reserve[j];
6300 break;
6301 }
6302 /* we treat the high watermark as reserved pages. */
6303 max += high_wmark_pages(zone);
6304
6305 max = min_t(unsigned long, max, managed_pages);
6306
6307 pgdat->totalreserve_pages += max;
6308
6309 reserve_pages += max;
6310 }
6311 }
6312 totalreserve_pages = reserve_pages;
6313 trace_mm_calculate_totalreserve_pages(totalreserve_pages);
6314 }
6315
6316 /*
6317 * setup_per_zone_lowmem_reserve - called whenever
6318 * sysctl_lowmem_reserve_ratio changes. Ensures that each zone
6319 * has a correct pages reserved value, so an adequate number of
6320 * pages are left in the zone after a successful __alloc_pages().
6321 */
setup_per_zone_lowmem_reserve(void)6322 static void setup_per_zone_lowmem_reserve(void)
6323 {
6324 struct pglist_data *pgdat;
6325 enum zone_type i, j;
6326 /*
6327 * For a given zone node_zones[i], lowmem_reserve[j] (j > i)
6328 * represents how many pages in zone i must effectively be kept
6329 * in reserve when deciding whether an allocation class that is
6330 * allowed to allocate from zones up to j may fall back into
6331 * zone i.
6332 *
6333 * As j increases, the allocation class can use a strictly larger
6334 * set of fallback zones and therefore must not be allowed to
6335 * deplete low zones more aggressively than a less flexible one.
6336 * As a result, lowmem_reserve[j] is required to be monotonically
6337 * non-decreasing in j for each zone i. Callers such as
6338 * calculate_totalreserve_pages() rely on this monotonicity when
6339 * selecting the maximum reserve entry.
6340 */
6341 for_each_online_pgdat(pgdat) {
6342 for (i = 0; i < MAX_NR_ZONES - 1; i++) {
6343 struct zone *zone = &pgdat->node_zones[i];
6344 int ratio = sysctl_lowmem_reserve_ratio[i];
6345 bool clear = !ratio || !zone_managed_pages(zone);
6346 unsigned long managed_pages = 0;
6347
6348 for (j = i + 1; j < MAX_NR_ZONES; j++) {
6349 struct zone *upper_zone = &pgdat->node_zones[j];
6350
6351 managed_pages += zone_managed_pages(upper_zone);
6352
6353 if (clear)
6354 zone->lowmem_reserve[j] = 0;
6355 else
6356 zone->lowmem_reserve[j] = managed_pages / ratio;
6357 trace_mm_setup_per_zone_lowmem_reserve(zone, upper_zone,
6358 zone->lowmem_reserve[j]);
6359 }
6360 }
6361 }
6362
6363 /* update totalreserve_pages */
6364 calculate_totalreserve_pages();
6365 }
6366
__setup_per_zone_wmarks(void)6367 static void __setup_per_zone_wmarks(void)
6368 {
6369 unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
6370 unsigned long lowmem_pages = 0;
6371 struct zone *zone;
6372 unsigned long flags;
6373
6374 /* Calculate total number of !ZONE_HIGHMEM and !ZONE_MOVABLE pages */
6375 for_each_zone(zone) {
6376 if (!is_highmem(zone) && zone_idx(zone) != ZONE_MOVABLE)
6377 lowmem_pages += zone_managed_pages(zone);
6378 }
6379
6380 for_each_zone(zone) {
6381 u64 tmp;
6382
6383 spin_lock_irqsave(&zone->lock, flags);
6384 tmp = (u64)pages_min * zone_managed_pages(zone);
6385 tmp = div64_ul(tmp, lowmem_pages);
6386 if (is_highmem(zone) || zone_idx(zone) == ZONE_MOVABLE) {
6387 /*
6388 * __GFP_HIGH and PF_MEMALLOC allocations usually don't
6389 * need highmem and movable zones pages, so cap pages_min
6390 * to a small value here.
6391 *
6392 * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN)
6393 * deltas control async page reclaim, and so should
6394 * not be capped for highmem and movable zones.
6395 */
6396 unsigned long min_pages;
6397
6398 min_pages = zone_managed_pages(zone) / 1024;
6399 min_pages = clamp(min_pages, SWAP_CLUSTER_MAX, 128UL);
6400 zone->_watermark[WMARK_MIN] = min_pages;
6401 } else {
6402 /*
6403 * If it's a lowmem zone, reserve a number of pages
6404 * proportionate to the zone's size.
6405 */
6406 zone->_watermark[WMARK_MIN] = tmp;
6407 }
6408
6409 /*
6410 * Set the kswapd watermarks distance according to the
6411 * scale factor in proportion to available memory, but
6412 * ensure a minimum size on small systems.
6413 */
6414 tmp = max_t(u64, tmp >> 2,
6415 mult_frac(zone_managed_pages(zone),
6416 watermark_scale_factor, 10000));
6417
6418 zone->watermark_boost = 0;
6419 zone->_watermark[WMARK_LOW] = min_wmark_pages(zone) + tmp;
6420 zone->_watermark[WMARK_HIGH] = low_wmark_pages(zone) + tmp;
6421 zone->_watermark[WMARK_PROMO] = high_wmark_pages(zone) + tmp;
6422 trace_mm_setup_per_zone_wmarks(zone);
6423
6424 spin_unlock_irqrestore(&zone->lock, flags);
6425 }
6426
6427 /* update totalreserve_pages */
6428 calculate_totalreserve_pages();
6429 }
6430
6431 /**
6432 * setup_per_zone_wmarks - called when min_free_kbytes changes
6433 * or when memory is hot-{added|removed}
6434 *
6435 * Ensures that the watermark[min,low,high] values for each zone are set
6436 * correctly with respect to min_free_kbytes.
6437 */
setup_per_zone_wmarks(void)6438 void setup_per_zone_wmarks(void)
6439 {
6440 struct zone *zone;
6441 static DEFINE_SPINLOCK(lock);
6442
6443 spin_lock(&lock);
6444 __setup_per_zone_wmarks();
6445 spin_unlock(&lock);
6446
6447 /*
6448 * The watermark size have changed so update the pcpu batch
6449 * and high limits or the limits may be inappropriate.
6450 */
6451 for_each_zone(zone)
6452 zone_pcp_update(zone, 0);
6453 }
6454
6455 /*
6456 * Initialise min_free_kbytes.
6457 *
6458 * For small machines we want it small (128k min). For large machines
6459 * we want it large (256MB max). But it is not linear, because network
6460 * bandwidth does not increase linearly with machine size. We use
6461 *
6462 * min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
6463 * min_free_kbytes = sqrt(lowmem_kbytes * 16)
6464 *
6465 * which yields
6466 *
6467 * 16MB: 512k
6468 * 32MB: 724k
6469 * 64MB: 1024k
6470 * 128MB: 1448k
6471 * 256MB: 2048k
6472 * 512MB: 2896k
6473 * 1024MB: 4096k
6474 * 2048MB: 5792k
6475 * 4096MB: 8192k
6476 * 8192MB: 11584k
6477 * 16384MB: 16384k
6478 */
calculate_min_free_kbytes(void)6479 void calculate_min_free_kbytes(void)
6480 {
6481 unsigned long lowmem_kbytes;
6482 int new_min_free_kbytes;
6483
6484 lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
6485 new_min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
6486
6487 if (new_min_free_kbytes > user_min_free_kbytes)
6488 min_free_kbytes = clamp(new_min_free_kbytes, 128, 262144);
6489 else
6490 pr_warn_ratelimited("min_free_kbytes is not updated to %d because user defined value %d is preferred\n",
6491 new_min_free_kbytes, user_min_free_kbytes);
6492
6493 }
6494
init_per_zone_wmark_min(void)6495 int __meminit init_per_zone_wmark_min(void)
6496 {
6497 calculate_min_free_kbytes();
6498 setup_per_zone_wmarks();
6499 refresh_zone_stat_thresholds();
6500 setup_per_zone_lowmem_reserve();
6501
6502 #ifdef CONFIG_NUMA
6503 setup_min_unmapped_ratio();
6504 setup_min_slab_ratio();
6505 #endif
6506
6507 khugepaged_min_free_kbytes_update();
6508
6509 return 0;
6510 }
postcore_initcall(init_per_zone_wmark_min)6511 postcore_initcall(init_per_zone_wmark_min)
6512
6513 /*
6514 * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
6515 * that we can call two helper functions whenever min_free_kbytes
6516 * changes.
6517 */
6518 static int min_free_kbytes_sysctl_handler(const struct ctl_table *table, int write,
6519 void *buffer, size_t *length, loff_t *ppos)
6520 {
6521 int rc;
6522
6523 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
6524 if (rc)
6525 return rc;
6526
6527 if (write) {
6528 user_min_free_kbytes = min_free_kbytes;
6529 setup_per_zone_wmarks();
6530 }
6531 return 0;
6532 }
6533
watermark_scale_factor_sysctl_handler(const struct ctl_table * table,int write,void * buffer,size_t * length,loff_t * ppos)6534 static int watermark_scale_factor_sysctl_handler(const struct ctl_table *table, int write,
6535 void *buffer, size_t *length, loff_t *ppos)
6536 {
6537 int rc;
6538
6539 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
6540 if (rc)
6541 return rc;
6542
6543 if (write)
6544 setup_per_zone_wmarks();
6545
6546 return 0;
6547 }
6548
6549 #ifdef CONFIG_NUMA
setup_min_unmapped_ratio(void)6550 static void setup_min_unmapped_ratio(void)
6551 {
6552 pg_data_t *pgdat;
6553 struct zone *zone;
6554
6555 for_each_online_pgdat(pgdat)
6556 pgdat->min_unmapped_pages = 0;
6557
6558 for_each_zone(zone)
6559 zone->zone_pgdat->min_unmapped_pages += (zone_managed_pages(zone) *
6560 sysctl_min_unmapped_ratio) / 100;
6561 }
6562
6563
sysctl_min_unmapped_ratio_sysctl_handler(const struct ctl_table * table,int write,void * buffer,size_t * length,loff_t * ppos)6564 static int sysctl_min_unmapped_ratio_sysctl_handler(const struct ctl_table *table, int write,
6565 void *buffer, size_t *length, loff_t *ppos)
6566 {
6567 int rc;
6568
6569 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
6570 if (rc)
6571 return rc;
6572
6573 setup_min_unmapped_ratio();
6574
6575 return 0;
6576 }
6577
setup_min_slab_ratio(void)6578 static void setup_min_slab_ratio(void)
6579 {
6580 pg_data_t *pgdat;
6581 struct zone *zone;
6582
6583 for_each_online_pgdat(pgdat)
6584 pgdat->min_slab_pages = 0;
6585
6586 for_each_zone(zone)
6587 zone->zone_pgdat->min_slab_pages += (zone_managed_pages(zone) *
6588 sysctl_min_slab_ratio) / 100;
6589 }
6590
sysctl_min_slab_ratio_sysctl_handler(const struct ctl_table * table,int write,void * buffer,size_t * length,loff_t * ppos)6591 static int sysctl_min_slab_ratio_sysctl_handler(const struct ctl_table *table, int write,
6592 void *buffer, size_t *length, loff_t *ppos)
6593 {
6594 int rc;
6595
6596 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
6597 if (rc)
6598 return rc;
6599
6600 setup_min_slab_ratio();
6601
6602 return 0;
6603 }
6604 #endif
6605
6606 /*
6607 * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
6608 * proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
6609 * whenever sysctl_lowmem_reserve_ratio changes.
6610 *
6611 * The reserve ratio obviously has absolutely no relation with the
6612 * minimum watermarks. The lowmem reserve ratio can only make sense
6613 * if in function of the boot time zone sizes.
6614 */
lowmem_reserve_ratio_sysctl_handler(const struct ctl_table * table,int write,void * buffer,size_t * length,loff_t * ppos)6615 static int lowmem_reserve_ratio_sysctl_handler(const struct ctl_table *table,
6616 int write, void *buffer, size_t *length, loff_t *ppos)
6617 {
6618 int i;
6619
6620 proc_dointvec_minmax(table, write, buffer, length, ppos);
6621
6622 for (i = 0; i < MAX_NR_ZONES; i++) {
6623 if (sysctl_lowmem_reserve_ratio[i] < 1)
6624 sysctl_lowmem_reserve_ratio[i] = 0;
6625 }
6626
6627 setup_per_zone_lowmem_reserve();
6628 return 0;
6629 }
6630
6631 /*
6632 * percpu_pagelist_high_fraction - changes the pcp->high for each zone on each
6633 * cpu. It is the fraction of total pages in each zone that a hot per cpu
6634 * pagelist can have before it gets flushed back to buddy allocator.
6635 */
percpu_pagelist_high_fraction_sysctl_handler(const struct ctl_table * table,int write,void * buffer,size_t * length,loff_t * ppos)6636 static int percpu_pagelist_high_fraction_sysctl_handler(const struct ctl_table *table,
6637 int write, void *buffer, size_t *length, loff_t *ppos)
6638 {
6639 struct zone *zone;
6640 int old_percpu_pagelist_high_fraction;
6641 int ret;
6642
6643 /*
6644 * Avoid using pcp_batch_high_lock for reads as the value is read
6645 * atomically and a race with offlining is harmless.
6646 */
6647
6648 if (!write)
6649 return proc_dointvec_minmax(table, write, buffer, length, ppos);
6650
6651 mutex_lock(&pcp_batch_high_lock);
6652 old_percpu_pagelist_high_fraction = percpu_pagelist_high_fraction;
6653
6654 ret = proc_dointvec_minmax(table, write, buffer, length, ppos);
6655 if (ret < 0)
6656 goto out;
6657
6658 /* Sanity checking to avoid pcp imbalance */
6659 if (percpu_pagelist_high_fraction &&
6660 percpu_pagelist_high_fraction < MIN_PERCPU_PAGELIST_HIGH_FRACTION) {
6661 percpu_pagelist_high_fraction = old_percpu_pagelist_high_fraction;
6662 ret = -EINVAL;
6663 goto out;
6664 }
6665
6666 /* No change? */
6667 if (percpu_pagelist_high_fraction == old_percpu_pagelist_high_fraction)
6668 goto out;
6669
6670 for_each_populated_zone(zone)
6671 zone_set_pageset_high_and_batch(zone, 0);
6672 out:
6673 mutex_unlock(&pcp_batch_high_lock);
6674 return ret;
6675 }
6676
6677 static const struct ctl_table page_alloc_sysctl_table[] = {
6678 {
6679 .procname = "min_free_kbytes",
6680 .data = &min_free_kbytes,
6681 .maxlen = sizeof(min_free_kbytes),
6682 .mode = 0644,
6683 .proc_handler = min_free_kbytes_sysctl_handler,
6684 .extra1 = SYSCTL_ZERO,
6685 },
6686 {
6687 .procname = "watermark_boost_factor",
6688 .data = &watermark_boost_factor,
6689 .maxlen = sizeof(watermark_boost_factor),
6690 .mode = 0644,
6691 .proc_handler = proc_dointvec_minmax,
6692 .extra1 = SYSCTL_ZERO,
6693 },
6694 {
6695 .procname = "watermark_scale_factor",
6696 .data = &watermark_scale_factor,
6697 .maxlen = sizeof(watermark_scale_factor),
6698 .mode = 0644,
6699 .proc_handler = watermark_scale_factor_sysctl_handler,
6700 .extra1 = SYSCTL_ONE,
6701 .extra2 = SYSCTL_THREE_THOUSAND,
6702 },
6703 {
6704 .procname = "defrag_mode",
6705 .data = &defrag_mode,
6706 .maxlen = sizeof(defrag_mode),
6707 .mode = 0644,
6708 .proc_handler = proc_dointvec_minmax,
6709 .extra1 = SYSCTL_ZERO,
6710 .extra2 = SYSCTL_ONE,
6711 },
6712 {
6713 .procname = "percpu_pagelist_high_fraction",
6714 .data = &percpu_pagelist_high_fraction,
6715 .maxlen = sizeof(percpu_pagelist_high_fraction),
6716 .mode = 0644,
6717 .proc_handler = percpu_pagelist_high_fraction_sysctl_handler,
6718 .extra1 = SYSCTL_ZERO,
6719 },
6720 {
6721 .procname = "lowmem_reserve_ratio",
6722 .data = &sysctl_lowmem_reserve_ratio,
6723 .maxlen = sizeof(sysctl_lowmem_reserve_ratio),
6724 .mode = 0644,
6725 .proc_handler = lowmem_reserve_ratio_sysctl_handler,
6726 },
6727 #ifdef CONFIG_NUMA
6728 {
6729 .procname = "numa_zonelist_order",
6730 .data = &numa_zonelist_order,
6731 .maxlen = NUMA_ZONELIST_ORDER_LEN,
6732 .mode = 0644,
6733 .proc_handler = numa_zonelist_order_handler,
6734 },
6735 {
6736 .procname = "min_unmapped_ratio",
6737 .data = &sysctl_min_unmapped_ratio,
6738 .maxlen = sizeof(sysctl_min_unmapped_ratio),
6739 .mode = 0644,
6740 .proc_handler = sysctl_min_unmapped_ratio_sysctl_handler,
6741 .extra1 = SYSCTL_ZERO,
6742 .extra2 = SYSCTL_ONE_HUNDRED,
6743 },
6744 {
6745 .procname = "min_slab_ratio",
6746 .data = &sysctl_min_slab_ratio,
6747 .maxlen = sizeof(sysctl_min_slab_ratio),
6748 .mode = 0644,
6749 .proc_handler = sysctl_min_slab_ratio_sysctl_handler,
6750 .extra1 = SYSCTL_ZERO,
6751 .extra2 = SYSCTL_ONE_HUNDRED,
6752 },
6753 #endif
6754 };
6755
page_alloc_sysctl_init(void)6756 void __init page_alloc_sysctl_init(void)
6757 {
6758 register_sysctl_init("vm", page_alloc_sysctl_table);
6759 }
6760
6761 #ifdef CONFIG_CONTIG_ALLOC
6762 /* Usage: See admin-guide/dynamic-debug-howto.rst */
alloc_contig_dump_pages(struct list_head * page_list)6763 static void alloc_contig_dump_pages(struct list_head *page_list)
6764 {
6765 DEFINE_DYNAMIC_DEBUG_METADATA(descriptor, "migrate failure");
6766
6767 if (DYNAMIC_DEBUG_BRANCH(descriptor)) {
6768 struct page *page;
6769
6770 dump_stack();
6771 list_for_each_entry(page, page_list, lru)
6772 dump_page(page, "migration failure");
6773 }
6774 }
6775
6776 /* [start, end) must belong to a single zone. */
__alloc_contig_migrate_range(struct compact_control * cc,unsigned long start,unsigned long end)6777 static int __alloc_contig_migrate_range(struct compact_control *cc,
6778 unsigned long start, unsigned long end)
6779 {
6780 /* This function is based on compact_zone() from compaction.c. */
6781 unsigned int nr_reclaimed;
6782 unsigned long pfn = start;
6783 unsigned int tries = 0;
6784 int ret = 0;
6785 struct migration_target_control mtc = {
6786 .nid = zone_to_nid(cc->zone),
6787 .gfp_mask = cc->gfp_mask,
6788 .reason = MR_CONTIG_RANGE,
6789 };
6790
6791 lru_cache_disable();
6792
6793 while (pfn < end || !list_empty(&cc->migratepages)) {
6794 if (fatal_signal_pending(current)) {
6795 ret = -EINTR;
6796 break;
6797 }
6798
6799 if (list_empty(&cc->migratepages)) {
6800 cc->nr_migratepages = 0;
6801 ret = isolate_migratepages_range(cc, pfn, end);
6802 if (ret && ret != -EAGAIN)
6803 break;
6804 pfn = cc->migrate_pfn;
6805 tries = 0;
6806 } else if (++tries == 5) {
6807 ret = -EBUSY;
6808 break;
6809 }
6810
6811 nr_reclaimed = reclaim_clean_pages_from_list(cc->zone,
6812 &cc->migratepages);
6813 cc->nr_migratepages -= nr_reclaimed;
6814
6815 ret = migrate_pages(&cc->migratepages, alloc_migration_target,
6816 NULL, (unsigned long)&mtc, cc->mode, MR_CONTIG_RANGE, NULL);
6817
6818 /*
6819 * On -ENOMEM, migrate_pages() bails out right away. It is pointless
6820 * to retry again over this error, so do the same here.
6821 */
6822 if (ret == -ENOMEM)
6823 break;
6824 }
6825
6826 lru_cache_enable();
6827 if (ret < 0) {
6828 if (!(cc->gfp_mask & __GFP_NOWARN) && ret == -EBUSY)
6829 alloc_contig_dump_pages(&cc->migratepages);
6830 putback_movable_pages(&cc->migratepages);
6831 }
6832
6833 return (ret < 0) ? ret : 0;
6834 }
6835
split_free_frozen_pages(struct list_head * list,gfp_t gfp_mask)6836 static void split_free_frozen_pages(struct list_head *list, gfp_t gfp_mask)
6837 {
6838 int order;
6839
6840 for (order = 0; order < NR_PAGE_ORDERS; order++) {
6841 struct page *page, *next;
6842 int nr_pages = 1 << order;
6843
6844 list_for_each_entry_safe(page, next, &list[order], lru) {
6845 int i;
6846
6847 post_alloc_hook(page, order, gfp_mask);
6848 if (!order)
6849 continue;
6850
6851 __split_page(page, order);
6852
6853 /* Add all subpages to the order-0 head, in sequence. */
6854 list_del(&page->lru);
6855 for (i = 0; i < nr_pages; i++)
6856 list_add_tail(&page[i].lru, &list[0]);
6857 }
6858 }
6859 }
6860
__alloc_contig_verify_gfp_mask(gfp_t gfp_mask,gfp_t * gfp_cc_mask)6861 static int __alloc_contig_verify_gfp_mask(gfp_t gfp_mask, gfp_t *gfp_cc_mask)
6862 {
6863 const gfp_t reclaim_mask = __GFP_IO | __GFP_FS | __GFP_RECLAIM;
6864 const gfp_t action_mask = __GFP_COMP | __GFP_RETRY_MAYFAIL | __GFP_NOWARN |
6865 __GFP_ZERO | __GFP_ZEROTAGS | __GFP_SKIP_ZERO |
6866 __GFP_SKIP_KASAN;
6867 const gfp_t cc_action_mask = __GFP_RETRY_MAYFAIL | __GFP_NOWARN;
6868
6869 /*
6870 * We are given the range to allocate; node, mobility and placement
6871 * hints are irrelevant at this point. We'll simply ignore them.
6872 */
6873 gfp_mask &= ~(GFP_ZONEMASK | __GFP_RECLAIMABLE | __GFP_WRITE |
6874 __GFP_HARDWALL | __GFP_THISNODE | __GFP_MOVABLE);
6875
6876 /*
6877 * We only support most reclaim flags (but not NOFAIL/NORETRY), and
6878 * selected action flags.
6879 */
6880 if (gfp_mask & ~(reclaim_mask | action_mask))
6881 return -EINVAL;
6882
6883 /*
6884 * Flags to control page compaction/migration/reclaim, to free up our
6885 * page range. Migratable pages are movable, __GFP_MOVABLE is implied
6886 * for them.
6887 *
6888 * Traditionally we always had __GFP_RETRY_MAYFAIL set, keep doing that
6889 * to not degrade callers.
6890 */
6891 *gfp_cc_mask = (gfp_mask & (reclaim_mask | cc_action_mask)) |
6892 __GFP_MOVABLE | __GFP_RETRY_MAYFAIL;
6893 return 0;
6894 }
6895
__free_contig_frozen_range(unsigned long pfn,unsigned long nr_pages)6896 static void __free_contig_frozen_range(unsigned long pfn, unsigned long nr_pages)
6897 {
6898 for (; nr_pages--; pfn++)
6899 free_frozen_pages(pfn_to_page(pfn), 0);
6900 }
6901
6902 /**
6903 * alloc_contig_frozen_range() -- tries to allocate given range of frozen pages
6904 * @start: start PFN to allocate
6905 * @end: one-past-the-last PFN to allocate
6906 * @alloc_flags: allocation information
6907 * @gfp_mask: GFP mask. Node/zone/placement hints are ignored; only some
6908 * action and reclaim modifiers are supported. Reclaim modifiers
6909 * control allocation behavior during compaction/migration/reclaim.
6910 *
6911 * The PFN range does not have to be pageblock aligned. The PFN range must
6912 * belong to a single zone.
6913 *
6914 * The first thing this routine does is attempt to MIGRATE_ISOLATE all
6915 * pageblocks in the range. Once isolated, the pageblocks should not
6916 * be modified by others.
6917 *
6918 * All frozen pages which PFN is in [start, end) are allocated for the
6919 * caller, and they could be freed with free_contig_frozen_range(),
6920 * free_frozen_pages() also could be used to free compound frozen pages
6921 * directly.
6922 *
6923 * Return: zero on success or negative error code.
6924 */
alloc_contig_frozen_range_noprof(unsigned long start,unsigned long end,acr_flags_t alloc_flags,gfp_t gfp_mask)6925 int alloc_contig_frozen_range_noprof(unsigned long start, unsigned long end,
6926 acr_flags_t alloc_flags, gfp_t gfp_mask)
6927 {
6928 const unsigned int order = ilog2(end - start);
6929 unsigned long outer_start, outer_end;
6930 int ret = 0;
6931
6932 struct compact_control cc = {
6933 .nr_migratepages = 0,
6934 .order = -1,
6935 .zone = page_zone(pfn_to_page(start)),
6936 .mode = MIGRATE_SYNC,
6937 .ignore_skip_hint = true,
6938 .no_set_skip_hint = true,
6939 .alloc_contig = true,
6940 };
6941 INIT_LIST_HEAD(&cc.migratepages);
6942 enum pb_isolate_mode mode = (alloc_flags & ACR_FLAGS_CMA) ?
6943 PB_ISOLATE_MODE_CMA_ALLOC :
6944 PB_ISOLATE_MODE_OTHER;
6945
6946 /*
6947 * In contrast to the buddy, we allow for orders here that exceed
6948 * MAX_PAGE_ORDER, so we must manually make sure that we are not
6949 * exceeding the maximum folio order.
6950 */
6951 if (WARN_ON_ONCE((gfp_mask & __GFP_COMP) && order > MAX_FOLIO_ORDER))
6952 return -EINVAL;
6953
6954 gfp_mask = current_gfp_context(gfp_mask);
6955 if (__alloc_contig_verify_gfp_mask(gfp_mask, (gfp_t *)&cc.gfp_mask))
6956 return -EINVAL;
6957
6958 /*
6959 * What we do here is we mark all pageblocks in range as
6960 * MIGRATE_ISOLATE. Because pageblock and max order pages may
6961 * have different sizes, and due to the way page allocator
6962 * work, start_isolate_page_range() has special handlings for this.
6963 *
6964 * Once the pageblocks are marked as MIGRATE_ISOLATE, we
6965 * migrate the pages from an unaligned range (ie. pages that
6966 * we are interested in). This will put all the pages in
6967 * range back to page allocator as MIGRATE_ISOLATE.
6968 *
6969 * When this is done, we take the pages in range from page
6970 * allocator removing them from the buddy system. This way
6971 * page allocator will never consider using them.
6972 *
6973 * This lets us mark the pageblocks back as
6974 * MIGRATE_CMA/MIGRATE_MOVABLE so that free pages in the
6975 * aligned range but not in the unaligned, original range are
6976 * put back to page allocator so that buddy can use them.
6977 */
6978
6979 ret = start_isolate_page_range(start, end, mode);
6980 if (ret)
6981 goto done;
6982
6983 drain_all_pages(cc.zone);
6984
6985 /*
6986 * In case of -EBUSY, we'd like to know which page causes problem.
6987 * So, just fall through. test_pages_isolated() has a tracepoint
6988 * which will report the busy page.
6989 *
6990 * It is possible that busy pages could become available before
6991 * the call to test_pages_isolated, and the range will actually be
6992 * allocated. So, if we fall through be sure to clear ret so that
6993 * -EBUSY is not accidentally used or returned to caller.
6994 */
6995 ret = __alloc_contig_migrate_range(&cc, start, end);
6996 if (ret && ret != -EBUSY)
6997 goto done;
6998
6999 /*
7000 * When in-use hugetlb pages are migrated, they may simply be released
7001 * back into the free hugepage pool instead of being returned to the
7002 * buddy system. After the migration of in-use huge pages is completed,
7003 * we will invoke replace_free_hugepage_folios() to ensure that these
7004 * hugepages are properly released to the buddy system.
7005 */
7006 ret = replace_free_hugepage_folios(start, end);
7007 if (ret)
7008 goto done;
7009
7010 /*
7011 * Pages from [start, end) are within a pageblock_nr_pages
7012 * aligned blocks that are marked as MIGRATE_ISOLATE. What's
7013 * more, all pages in [start, end) are free in page allocator.
7014 * What we are going to do is to allocate all pages from
7015 * [start, end) (that is remove them from page allocator).
7016 *
7017 * The only problem is that pages at the beginning and at the
7018 * end of interesting range may be not aligned with pages that
7019 * page allocator holds, ie. they can be part of higher order
7020 * pages. Because of this, we reserve the bigger range and
7021 * once this is done free the pages we are not interested in.
7022 *
7023 * We don't have to hold zone->lock here because the pages are
7024 * isolated thus they won't get removed from buddy.
7025 */
7026 outer_start = find_large_buddy(start);
7027
7028 /* Make sure the range is really isolated. */
7029 if (test_pages_isolated(outer_start, end, mode)) {
7030 ret = -EBUSY;
7031 goto done;
7032 }
7033
7034 /* Grab isolated pages from freelists. */
7035 outer_end = isolate_freepages_range(&cc, outer_start, end);
7036 if (!outer_end) {
7037 ret = -EBUSY;
7038 goto done;
7039 }
7040
7041 if (!(gfp_mask & __GFP_COMP)) {
7042 split_free_frozen_pages(cc.freepages, gfp_mask);
7043
7044 /* Free head and tail (if any) */
7045 if (start != outer_start)
7046 __free_contig_frozen_range(outer_start, start - outer_start);
7047 if (end != outer_end)
7048 __free_contig_frozen_range(end, outer_end - end);
7049 } else if (start == outer_start && end == outer_end && is_power_of_2(end - start)) {
7050 struct page *head = pfn_to_page(start);
7051
7052 check_new_pages(head, order);
7053 prep_new_page(head, order, gfp_mask, 0);
7054 } else {
7055 ret = -EINVAL;
7056 WARN(true, "PFN range: requested [%lu, %lu), allocated [%lu, %lu)\n",
7057 start, end, outer_start, outer_end);
7058 }
7059 done:
7060 undo_isolate_page_range(start, end);
7061 return ret;
7062 }
7063 EXPORT_SYMBOL(alloc_contig_frozen_range_noprof);
7064
7065 /**
7066 * alloc_contig_range() -- tries to allocate given range of pages
7067 * @start: start PFN to allocate
7068 * @end: one-past-the-last PFN to allocate
7069 * @alloc_flags: allocation information
7070 * @gfp_mask: GFP mask.
7071 *
7072 * This routine is a wrapper around alloc_contig_frozen_range(), it can't
7073 * be used to allocate compound pages, the refcount of each allocated page
7074 * will be set to one.
7075 *
7076 * All pages which PFN is in [start, end) are allocated for the caller,
7077 * and should be freed with free_contig_range() or by manually calling
7078 * __free_page() on each allocated page.
7079 *
7080 * Return: zero on success or negative error code.
7081 */
alloc_contig_range_noprof(unsigned long start,unsigned long end,acr_flags_t alloc_flags,gfp_t gfp_mask)7082 int alloc_contig_range_noprof(unsigned long start, unsigned long end,
7083 acr_flags_t alloc_flags, gfp_t gfp_mask)
7084 {
7085 int ret;
7086
7087 if (WARN_ON(gfp_mask & __GFP_COMP))
7088 return -EINVAL;
7089
7090 ret = alloc_contig_frozen_range_noprof(start, end, alloc_flags, gfp_mask);
7091 if (!ret)
7092 set_pages_refcounted(pfn_to_page(start), end - start);
7093
7094 return ret;
7095 }
7096 EXPORT_SYMBOL(alloc_contig_range_noprof);
7097
pfn_range_valid_contig(struct zone * z,unsigned long start_pfn,unsigned long nr_pages,bool skip_hugetlb,bool * skipped_hugetlb)7098 static bool pfn_range_valid_contig(struct zone *z, unsigned long start_pfn,
7099 unsigned long nr_pages, bool skip_hugetlb,
7100 bool *skipped_hugetlb)
7101 {
7102 unsigned long end_pfn = start_pfn + nr_pages;
7103 struct page *page;
7104
7105 while (start_pfn < end_pfn) {
7106 unsigned long step = 1;
7107
7108 page = pfn_to_online_page(start_pfn);
7109 if (!page)
7110 return false;
7111
7112 if (page_zone(page) != z)
7113 return false;
7114
7115 if (page_is_unmovable(z, page, PB_ISOLATE_MODE_OTHER, &step))
7116 return false;
7117
7118 /*
7119 * Only consider ranges containing hugepages if those pages are
7120 * smaller than the requested contiguous region. e.g.:
7121 * Move 2MB pages to free up a 1GB range.
7122 * Don't move 1GB pages to free up a 2MB range.
7123 *
7124 * This makes contiguous allocation more reliable if multiple
7125 * hugepage sizes are used without causing needless movement.
7126 */
7127 if (PageHuge(page)) {
7128 unsigned int order;
7129
7130 if (skip_hugetlb) {
7131 *skipped_hugetlb = true;
7132 return false;
7133 }
7134
7135 page = compound_head(page);
7136 order = compound_order(page);
7137 if ((order >= MAX_FOLIO_ORDER) ||
7138 (nr_pages <= (1 << order)))
7139 return false;
7140 }
7141
7142 start_pfn += step;
7143 }
7144 return true;
7145 }
7146
zone_spans_last_pfn(const struct zone * zone,unsigned long start_pfn,unsigned long nr_pages)7147 static bool zone_spans_last_pfn(const struct zone *zone,
7148 unsigned long start_pfn, unsigned long nr_pages)
7149 {
7150 unsigned long last_pfn = start_pfn + nr_pages - 1;
7151
7152 return zone_spans_pfn(zone, last_pfn);
7153 }
7154
7155 /**
7156 * alloc_contig_frozen_pages() -- tries to find and allocate contiguous range of frozen pages
7157 * @nr_pages: Number of contiguous pages to allocate
7158 * @gfp_mask: GFP mask. Node/zone/placement hints limit the search; only some
7159 * action and reclaim modifiers are supported. Reclaim modifiers
7160 * control allocation behavior during compaction/migration/reclaim.
7161 * @nid: Target node
7162 * @nodemask: Mask for other possible nodes
7163 *
7164 * This routine is a wrapper around alloc_contig_frozen_range(). It scans over
7165 * zones on an applicable zonelist to find a contiguous pfn range which can then
7166 * be tried for allocation with alloc_contig_frozen_range(). This routine is
7167 * intended for allocation requests which can not be fulfilled with the buddy
7168 * allocator.
7169 *
7170 * The allocated memory is always aligned to a page boundary. If nr_pages is a
7171 * power of two, then allocated range is also guaranteed to be aligned to same
7172 * nr_pages (e.g. 1GB request would be aligned to 1GB).
7173 *
7174 * Allocated frozen pages need be freed with free_contig_frozen_range(),
7175 * or by manually calling free_frozen_pages() on each allocated frozen
7176 * non-compound page, for compound frozen pages could be freed with
7177 * free_frozen_pages() directly.
7178 *
7179 * Return: pointer to contiguous frozen pages on success, or NULL if not successful.
7180 */
alloc_contig_frozen_pages_noprof(unsigned long nr_pages,gfp_t gfp_mask,int nid,nodemask_t * nodemask)7181 struct page *alloc_contig_frozen_pages_noprof(unsigned long nr_pages,
7182 gfp_t gfp_mask, int nid, nodemask_t *nodemask)
7183 {
7184 unsigned long ret, pfn, flags;
7185 struct zonelist *zonelist;
7186 struct zone *zone;
7187 struct zoneref *z;
7188 bool skip_hugetlb = true;
7189 bool skipped_hugetlb = false;
7190
7191 retry:
7192 zonelist = node_zonelist(nid, gfp_mask);
7193 for_each_zone_zonelist_nodemask(zone, z, zonelist,
7194 gfp_zone(gfp_mask), nodemask) {
7195 spin_lock_irqsave(&zone->lock, flags);
7196
7197 pfn = ALIGN(zone->zone_start_pfn, nr_pages);
7198 while (zone_spans_last_pfn(zone, pfn, nr_pages)) {
7199 if (pfn_range_valid_contig(zone, pfn, nr_pages,
7200 skip_hugetlb,
7201 &skipped_hugetlb)) {
7202 /*
7203 * We release the zone lock here because
7204 * alloc_contig_frozen_range() will also lock
7205 * the zone at some point. If there's an
7206 * allocation spinning on this lock, it may
7207 * win the race and cause allocation to fail.
7208 */
7209 spin_unlock_irqrestore(&zone->lock, flags);
7210 ret = alloc_contig_frozen_range_noprof(pfn,
7211 pfn + nr_pages,
7212 ACR_FLAGS_NONE,
7213 gfp_mask);
7214 if (!ret)
7215 return pfn_to_page(pfn);
7216 spin_lock_irqsave(&zone->lock, flags);
7217 }
7218 pfn += nr_pages;
7219 }
7220 spin_unlock_irqrestore(&zone->lock, flags);
7221 }
7222 /*
7223 * If we failed, retry the search, but treat regions with HugeTLB pages
7224 * as valid targets. This retains fast-allocations on first pass
7225 * without trying to migrate HugeTLB pages (which may fail). On the
7226 * second pass, we will try moving HugeTLB pages when those pages are
7227 * smaller than the requested contiguous region size.
7228 */
7229 if (skip_hugetlb && skipped_hugetlb) {
7230 skip_hugetlb = false;
7231 goto retry;
7232 }
7233 return NULL;
7234 }
7235 EXPORT_SYMBOL(alloc_contig_frozen_pages_noprof);
7236
7237 /**
7238 * alloc_contig_pages() -- tries to find and allocate contiguous range of pages
7239 * @nr_pages: Number of contiguous pages to allocate
7240 * @gfp_mask: GFP mask.
7241 * @nid: Target node
7242 * @nodemask: Mask for other possible nodes
7243 *
7244 * This routine is a wrapper around alloc_contig_frozen_pages(), it can't
7245 * be used to allocate compound pages, the refcount of each allocated page
7246 * will be set to one.
7247 *
7248 * Allocated pages can be freed with free_contig_range() or by manually
7249 * calling __free_page() on each allocated page.
7250 *
7251 * Return: pointer to contiguous pages on success, or NULL if not successful.
7252 */
alloc_contig_pages_noprof(unsigned long nr_pages,gfp_t gfp_mask,int nid,nodemask_t * nodemask)7253 struct page *alloc_contig_pages_noprof(unsigned long nr_pages, gfp_t gfp_mask,
7254 int nid, nodemask_t *nodemask)
7255 {
7256 struct page *page;
7257
7258 if (WARN_ON(gfp_mask & __GFP_COMP))
7259 return NULL;
7260
7261 page = alloc_contig_frozen_pages_noprof(nr_pages, gfp_mask, nid,
7262 nodemask);
7263 if (page)
7264 set_pages_refcounted(page, nr_pages);
7265
7266 return page;
7267 }
7268 EXPORT_SYMBOL(alloc_contig_pages_noprof);
7269
7270 /**
7271 * free_contig_frozen_range() -- free the contiguous range of frozen pages
7272 * @pfn: start PFN to free
7273 * @nr_pages: Number of contiguous frozen pages to free
7274 *
7275 * This can be used to free the allocated compound/non-compound frozen pages.
7276 */
free_contig_frozen_range(unsigned long pfn,unsigned long nr_pages)7277 void free_contig_frozen_range(unsigned long pfn, unsigned long nr_pages)
7278 {
7279 struct page *first_page = pfn_to_page(pfn);
7280 const unsigned int order = ilog2(nr_pages);
7281
7282 if (WARN_ON_ONCE(first_page != compound_head(first_page)))
7283 return;
7284
7285 if (PageHead(first_page)) {
7286 WARN_ON_ONCE(order != compound_order(first_page));
7287 free_frozen_pages(first_page, order);
7288 return;
7289 }
7290
7291 __free_contig_frozen_range(pfn, nr_pages);
7292 }
7293 EXPORT_SYMBOL(free_contig_frozen_range);
7294
7295 /**
7296 * free_contig_range() -- free the contiguous range of pages
7297 * @pfn: start PFN to free
7298 * @nr_pages: Number of contiguous pages to free
7299 *
7300 * This can be only used to free the allocated non-compound pages.
7301 */
free_contig_range(unsigned long pfn,unsigned long nr_pages)7302 void free_contig_range(unsigned long pfn, unsigned long nr_pages)
7303 {
7304 if (WARN_ON_ONCE(PageHead(pfn_to_page(pfn))))
7305 return;
7306
7307 for (; nr_pages--; pfn++)
7308 __free_page(pfn_to_page(pfn));
7309 }
7310 EXPORT_SYMBOL(free_contig_range);
7311 #endif /* CONFIG_CONTIG_ALLOC */
7312
7313 /*
7314 * Effectively disable pcplists for the zone by setting the high limit to 0
7315 * and draining all cpus. A concurrent page freeing on another CPU that's about
7316 * to put the page on pcplist will either finish before the drain and the page
7317 * will be drained, or observe the new high limit and skip the pcplist.
7318 *
7319 * Must be paired with a call to zone_pcp_enable().
7320 */
zone_pcp_disable(struct zone * zone)7321 void zone_pcp_disable(struct zone *zone)
7322 {
7323 mutex_lock(&pcp_batch_high_lock);
7324 __zone_set_pageset_high_and_batch(zone, 0, 0, 1);
7325 __drain_all_pages(zone, true);
7326 }
7327
zone_pcp_enable(struct zone * zone)7328 void zone_pcp_enable(struct zone *zone)
7329 {
7330 __zone_set_pageset_high_and_batch(zone, zone->pageset_high_min,
7331 zone->pageset_high_max, zone->pageset_batch);
7332 mutex_unlock(&pcp_batch_high_lock);
7333 }
7334
zone_pcp_reset(struct zone * zone)7335 void zone_pcp_reset(struct zone *zone)
7336 {
7337 int cpu;
7338 struct per_cpu_zonestat *pzstats;
7339
7340 if (zone->per_cpu_pageset != &boot_pageset) {
7341 for_each_online_cpu(cpu) {
7342 pzstats = per_cpu_ptr(zone->per_cpu_zonestats, cpu);
7343 drain_zonestat(zone, pzstats);
7344 }
7345 free_percpu(zone->per_cpu_pageset);
7346 zone->per_cpu_pageset = &boot_pageset;
7347 if (zone->per_cpu_zonestats != &boot_zonestats) {
7348 free_percpu(zone->per_cpu_zonestats);
7349 zone->per_cpu_zonestats = &boot_zonestats;
7350 }
7351 }
7352 }
7353
7354 #ifdef CONFIG_MEMORY_HOTREMOVE
7355 /*
7356 * All pages in the range must be in a single zone, must not contain holes,
7357 * must span full sections, and must be isolated before calling this function.
7358 *
7359 * Returns the number of managed (non-PageOffline()) pages in the range: the
7360 * number of pages for which memory offlining code must adjust managed page
7361 * counters using adjust_managed_page_count().
7362 */
__offline_isolated_pages(unsigned long start_pfn,unsigned long end_pfn)7363 unsigned long __offline_isolated_pages(unsigned long start_pfn,
7364 unsigned long end_pfn)
7365 {
7366 unsigned long already_offline = 0, flags;
7367 unsigned long pfn = start_pfn;
7368 struct page *page;
7369 struct zone *zone;
7370 unsigned int order;
7371
7372 offline_mem_sections(pfn, end_pfn);
7373 zone = page_zone(pfn_to_page(pfn));
7374 spin_lock_irqsave(&zone->lock, flags);
7375 while (pfn < end_pfn) {
7376 page = pfn_to_page(pfn);
7377 /*
7378 * The HWPoisoned page may be not in buddy system, and
7379 * page_count() is not 0.
7380 */
7381 if (unlikely(!PageBuddy(page) && PageHWPoison(page))) {
7382 pfn++;
7383 continue;
7384 }
7385 /*
7386 * At this point all remaining PageOffline() pages have a
7387 * reference count of 0 and can simply be skipped.
7388 */
7389 if (PageOffline(page)) {
7390 BUG_ON(page_count(page));
7391 BUG_ON(PageBuddy(page));
7392 already_offline++;
7393 pfn++;
7394 continue;
7395 }
7396
7397 BUG_ON(page_count(page));
7398 BUG_ON(!PageBuddy(page));
7399 VM_WARN_ON(get_pageblock_migratetype(page) != MIGRATE_ISOLATE);
7400 order = buddy_order(page);
7401 del_page_from_free_list(page, zone, order, MIGRATE_ISOLATE);
7402 pfn += (1 << order);
7403 }
7404 spin_unlock_irqrestore(&zone->lock, flags);
7405
7406 return end_pfn - start_pfn - already_offline;
7407 }
7408 #endif
7409
7410 /*
7411 * This function returns a stable result only if called under zone lock.
7412 */
is_free_buddy_page(const struct page * page)7413 bool is_free_buddy_page(const struct page *page)
7414 {
7415 unsigned long pfn = page_to_pfn(page);
7416 unsigned int order;
7417
7418 for (order = 0; order < NR_PAGE_ORDERS; order++) {
7419 const struct page *head = page - (pfn & ((1 << order) - 1));
7420
7421 if (PageBuddy(head) &&
7422 buddy_order_unsafe(head) >= order)
7423 break;
7424 }
7425
7426 return order <= MAX_PAGE_ORDER;
7427 }
7428 EXPORT_SYMBOL(is_free_buddy_page);
7429
7430 #ifdef CONFIG_MEMORY_FAILURE
add_to_free_list(struct page * page,struct zone * zone,unsigned int order,int migratetype,bool tail)7431 static inline void add_to_free_list(struct page *page, struct zone *zone,
7432 unsigned int order, int migratetype,
7433 bool tail)
7434 {
7435 __add_to_free_list(page, zone, order, migratetype, tail);
7436 account_freepages(zone, 1 << order, migratetype);
7437 }
7438
7439 /*
7440 * Break down a higher-order page in sub-pages, and keep our target out of
7441 * buddy allocator.
7442 */
break_down_buddy_pages(struct zone * zone,struct page * page,struct page * target,int low,int high,int migratetype)7443 static void break_down_buddy_pages(struct zone *zone, struct page *page,
7444 struct page *target, int low, int high,
7445 int migratetype)
7446 {
7447 unsigned long size = 1 << high;
7448 struct page *current_buddy;
7449
7450 while (high > low) {
7451 high--;
7452 size >>= 1;
7453
7454 if (target >= &page[size]) {
7455 current_buddy = page;
7456 page = page + size;
7457 } else {
7458 current_buddy = page + size;
7459 }
7460
7461 if (set_page_guard(zone, current_buddy, high))
7462 continue;
7463
7464 add_to_free_list(current_buddy, zone, high, migratetype, false);
7465 set_buddy_order(current_buddy, high);
7466 }
7467 }
7468
7469 /*
7470 * Take a page that will be marked as poisoned off the buddy allocator.
7471 */
take_page_off_buddy(struct page * page)7472 bool take_page_off_buddy(struct page *page)
7473 {
7474 struct zone *zone = page_zone(page);
7475 unsigned long pfn = page_to_pfn(page);
7476 unsigned long flags;
7477 unsigned int order;
7478 bool ret = false;
7479
7480 spin_lock_irqsave(&zone->lock, flags);
7481 for (order = 0; order < NR_PAGE_ORDERS; order++) {
7482 struct page *page_head = page - (pfn & ((1 << order) - 1));
7483 int page_order = buddy_order(page_head);
7484
7485 if (PageBuddy(page_head) && page_order >= order) {
7486 unsigned long pfn_head = page_to_pfn(page_head);
7487 int migratetype = get_pfnblock_migratetype(page_head,
7488 pfn_head);
7489
7490 del_page_from_free_list(page_head, zone, page_order,
7491 migratetype);
7492 break_down_buddy_pages(zone, page_head, page, 0,
7493 page_order, migratetype);
7494 SetPageHWPoisonTakenOff(page);
7495 ret = true;
7496 break;
7497 }
7498 if (page_count(page_head) > 0)
7499 break;
7500 }
7501 spin_unlock_irqrestore(&zone->lock, flags);
7502 return ret;
7503 }
7504
7505 /*
7506 * Cancel takeoff done by take_page_off_buddy().
7507 */
put_page_back_buddy(struct page * page)7508 bool put_page_back_buddy(struct page *page)
7509 {
7510 struct zone *zone = page_zone(page);
7511 unsigned long flags;
7512 bool ret = false;
7513
7514 spin_lock_irqsave(&zone->lock, flags);
7515 if (put_page_testzero(page)) {
7516 unsigned long pfn = page_to_pfn(page);
7517 int migratetype = get_pfnblock_migratetype(page, pfn);
7518
7519 ClearPageHWPoisonTakenOff(page);
7520 __free_one_page(page, pfn, zone, 0, migratetype, FPI_NONE);
7521 if (TestClearPageHWPoison(page)) {
7522 ret = true;
7523 }
7524 }
7525 spin_unlock_irqrestore(&zone->lock, flags);
7526
7527 return ret;
7528 }
7529 #endif
7530
has_managed_zone(enum zone_type zone)7531 bool has_managed_zone(enum zone_type zone)
7532 {
7533 struct pglist_data *pgdat;
7534
7535 for_each_online_pgdat(pgdat) {
7536 if (managed_zone(&pgdat->node_zones[zone]))
7537 return true;
7538 }
7539 return false;
7540 }
7541
7542 #ifdef CONFIG_UNACCEPTED_MEMORY
7543
7544 static bool lazy_accept = true;
7545
accept_memory_parse(char * p)7546 static int __init accept_memory_parse(char *p)
7547 {
7548 if (!strcmp(p, "lazy")) {
7549 lazy_accept = true;
7550 return 0;
7551 } else if (!strcmp(p, "eager")) {
7552 lazy_accept = false;
7553 return 0;
7554 } else {
7555 return -EINVAL;
7556 }
7557 }
7558 early_param("accept_memory", accept_memory_parse);
7559
page_contains_unaccepted(struct page * page,unsigned int order)7560 static bool page_contains_unaccepted(struct page *page, unsigned int order)
7561 {
7562 phys_addr_t start = page_to_phys(page);
7563
7564 return range_contains_unaccepted_memory(start, PAGE_SIZE << order);
7565 }
7566
__accept_page(struct zone * zone,unsigned long * flags,struct page * page)7567 static void __accept_page(struct zone *zone, unsigned long *flags,
7568 struct page *page)
7569 {
7570 list_del(&page->lru);
7571 account_freepages(zone, -MAX_ORDER_NR_PAGES, MIGRATE_MOVABLE);
7572 __mod_zone_page_state(zone, NR_UNACCEPTED, -MAX_ORDER_NR_PAGES);
7573 __ClearPageUnaccepted(page);
7574 spin_unlock_irqrestore(&zone->lock, *flags);
7575
7576 accept_memory(page_to_phys(page), PAGE_SIZE << MAX_PAGE_ORDER);
7577
7578 __free_pages_ok(page, MAX_PAGE_ORDER, FPI_TO_TAIL);
7579 }
7580
accept_page(struct page * page)7581 void accept_page(struct page *page)
7582 {
7583 struct zone *zone = page_zone(page);
7584 unsigned long flags;
7585
7586 spin_lock_irqsave(&zone->lock, flags);
7587 if (!PageUnaccepted(page)) {
7588 spin_unlock_irqrestore(&zone->lock, flags);
7589 return;
7590 }
7591
7592 /* Unlocks zone->lock */
7593 __accept_page(zone, &flags, page);
7594 }
7595
try_to_accept_memory_one(struct zone * zone)7596 static bool try_to_accept_memory_one(struct zone *zone)
7597 {
7598 unsigned long flags;
7599 struct page *page;
7600
7601 spin_lock_irqsave(&zone->lock, flags);
7602 page = list_first_entry_or_null(&zone->unaccepted_pages,
7603 struct page, lru);
7604 if (!page) {
7605 spin_unlock_irqrestore(&zone->lock, flags);
7606 return false;
7607 }
7608
7609 /* Unlocks zone->lock */
7610 __accept_page(zone, &flags, page);
7611
7612 return true;
7613 }
7614
cond_accept_memory(struct zone * zone,unsigned int order,int alloc_flags)7615 static bool cond_accept_memory(struct zone *zone, unsigned int order,
7616 int alloc_flags)
7617 {
7618 long to_accept, wmark;
7619 bool ret = false;
7620
7621 if (list_empty(&zone->unaccepted_pages))
7622 return false;
7623
7624 /* Bailout, since try_to_accept_memory_one() needs to take a lock */
7625 if (alloc_flags & ALLOC_TRYLOCK)
7626 return false;
7627
7628 wmark = promo_wmark_pages(zone);
7629
7630 /*
7631 * Watermarks have not been initialized yet.
7632 *
7633 * Accepting one MAX_ORDER page to ensure progress.
7634 */
7635 if (!wmark)
7636 return try_to_accept_memory_one(zone);
7637
7638 /* How much to accept to get to promo watermark? */
7639 to_accept = wmark -
7640 (zone_page_state(zone, NR_FREE_PAGES) -
7641 __zone_watermark_unusable_free(zone, order, 0) -
7642 zone_page_state(zone, NR_UNACCEPTED));
7643
7644 while (to_accept > 0) {
7645 if (!try_to_accept_memory_one(zone))
7646 break;
7647 ret = true;
7648 to_accept -= MAX_ORDER_NR_PAGES;
7649 }
7650
7651 return ret;
7652 }
7653
__free_unaccepted(struct page * page)7654 static bool __free_unaccepted(struct page *page)
7655 {
7656 struct zone *zone = page_zone(page);
7657 unsigned long flags;
7658
7659 if (!lazy_accept)
7660 return false;
7661
7662 spin_lock_irqsave(&zone->lock, flags);
7663 list_add_tail(&page->lru, &zone->unaccepted_pages);
7664 account_freepages(zone, MAX_ORDER_NR_PAGES, MIGRATE_MOVABLE);
7665 __mod_zone_page_state(zone, NR_UNACCEPTED, MAX_ORDER_NR_PAGES);
7666 __SetPageUnaccepted(page);
7667 spin_unlock_irqrestore(&zone->lock, flags);
7668
7669 return true;
7670 }
7671
7672 #else
7673
page_contains_unaccepted(struct page * page,unsigned int order)7674 static bool page_contains_unaccepted(struct page *page, unsigned int order)
7675 {
7676 return false;
7677 }
7678
cond_accept_memory(struct zone * zone,unsigned int order,int alloc_flags)7679 static bool cond_accept_memory(struct zone *zone, unsigned int order,
7680 int alloc_flags)
7681 {
7682 return false;
7683 }
7684
__free_unaccepted(struct page * page)7685 static bool __free_unaccepted(struct page *page)
7686 {
7687 BUILD_BUG();
7688 return false;
7689 }
7690
7691 #endif /* CONFIG_UNACCEPTED_MEMORY */
7692
alloc_frozen_pages_nolock_noprof(gfp_t gfp_flags,int nid,unsigned int order)7693 struct page *alloc_frozen_pages_nolock_noprof(gfp_t gfp_flags, int nid, unsigned int order)
7694 {
7695 /*
7696 * Do not specify __GFP_DIRECT_RECLAIM, since direct claim is not allowed.
7697 * Do not specify __GFP_KSWAPD_RECLAIM either, since wake up of kswapd
7698 * is not safe in arbitrary context.
7699 *
7700 * These two are the conditions for gfpflags_allow_spinning() being true.
7701 *
7702 * Specify __GFP_NOWARN since failing alloc_pages_nolock() is not a reason
7703 * to warn. Also warn would trigger printk() which is unsafe from
7704 * various contexts. We cannot use printk_deferred_enter() to mitigate,
7705 * since the running context is unknown.
7706 *
7707 * Specify __GFP_ZERO to make sure that call to kmsan_alloc_page() below
7708 * is safe in any context. Also zeroing the page is mandatory for
7709 * BPF use cases.
7710 *
7711 * Though __GFP_NOMEMALLOC is not checked in the code path below,
7712 * specify it here to highlight that alloc_pages_nolock()
7713 * doesn't want to deplete reserves.
7714 */
7715 gfp_t alloc_gfp = __GFP_NOWARN | __GFP_ZERO | __GFP_NOMEMALLOC | __GFP_COMP
7716 | gfp_flags;
7717 unsigned int alloc_flags = ALLOC_TRYLOCK;
7718 struct alloc_context ac = { };
7719 struct page *page;
7720
7721 VM_WARN_ON_ONCE(gfp_flags & ~__GFP_ACCOUNT);
7722 /*
7723 * In PREEMPT_RT spin_trylock() will call raw_spin_lock() which is
7724 * unsafe in NMI. If spin_trylock() is called from hard IRQ the current
7725 * task may be waiting for one rt_spin_lock, but rt_spin_trylock() will
7726 * mark the task as the owner of another rt_spin_lock which will
7727 * confuse PI logic, so return immediately if called from hard IRQ or
7728 * NMI.
7729 *
7730 * Note, irqs_disabled() case is ok. This function can be called
7731 * from raw_spin_lock_irqsave region.
7732 */
7733 if (IS_ENABLED(CONFIG_PREEMPT_RT) && (in_nmi() || in_hardirq()))
7734 return NULL;
7735
7736 /* On UP, spin_trylock() always succeeds even when it is locked */
7737 if (!IS_ENABLED(CONFIG_SMP) && in_nmi())
7738 return NULL;
7739
7740 if (!pcp_allowed_order(order))
7741 return NULL;
7742
7743 /* Bailout, since _deferred_grow_zone() needs to take a lock */
7744 if (deferred_pages_enabled())
7745 return NULL;
7746
7747 if (nid == NUMA_NO_NODE)
7748 nid = numa_node_id();
7749
7750 prepare_alloc_pages(alloc_gfp, order, nid, NULL, &ac,
7751 &alloc_gfp, &alloc_flags);
7752
7753 /*
7754 * Best effort allocation from percpu free list.
7755 * If it's empty attempt to spin_trylock zone->lock.
7756 */
7757 page = get_page_from_freelist(alloc_gfp, order, alloc_flags, &ac);
7758
7759 /* Unlike regular alloc_pages() there is no __alloc_pages_slowpath(). */
7760
7761 if (memcg_kmem_online() && page && (gfp_flags & __GFP_ACCOUNT) &&
7762 unlikely(__memcg_kmem_charge_page(page, alloc_gfp, order) != 0)) {
7763 __free_frozen_pages(page, order, FPI_TRYLOCK);
7764 page = NULL;
7765 }
7766 trace_mm_page_alloc(page, order, alloc_gfp, ac.migratetype);
7767 kmsan_alloc_page(page, order, alloc_gfp);
7768 return page;
7769 }
7770 /**
7771 * alloc_pages_nolock - opportunistic reentrant allocation from any context
7772 * @gfp_flags: GFP flags. Only __GFP_ACCOUNT allowed.
7773 * @nid: node to allocate from
7774 * @order: allocation order size
7775 *
7776 * Allocates pages of a given order from the given node. This is safe to
7777 * call from any context (from atomic, NMI, and also reentrant
7778 * allocator -> tracepoint -> alloc_pages_nolock_noprof).
7779 * Allocation is best effort and to be expected to fail easily so nobody should
7780 * rely on the success. Failures are not reported via warn_alloc().
7781 * See always fail conditions below.
7782 *
7783 * Return: allocated page or NULL on failure. NULL does not mean EBUSY or EAGAIN.
7784 * It means ENOMEM. There is no reason to call it again and expect !NULL.
7785 */
alloc_pages_nolock_noprof(gfp_t gfp_flags,int nid,unsigned int order)7786 struct page *alloc_pages_nolock_noprof(gfp_t gfp_flags, int nid, unsigned int order)
7787 {
7788 struct page *page;
7789
7790 page = alloc_frozen_pages_nolock_noprof(gfp_flags, nid, order);
7791 if (page)
7792 set_page_refcounted(page);
7793 return page;
7794 }
7795 EXPORT_SYMBOL_GPL(alloc_pages_nolock_noprof);
7796