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