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