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