1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef _LINUX_MMZONE_H
3 #define _LINUX_MMZONE_H
4
5 #ifndef __ASSEMBLY__
6 #ifndef __GENERATING_BOUNDS_H
7
8 #include <linux/spinlock.h>
9 #include <linux/list.h>
10 #include <linux/list_nulls.h>
11 #include <linux/wait.h>
12 #include <linux/bitops.h>
13 #include <linux/cache.h>
14 #include <linux/threads.h>
15 #include <linux/numa.h>
16 #include <linux/init.h>
17 #include <linux/seqlock.h>
18 #include <linux/nodemask.h>
19 #include <linux/pageblock-flags.h>
20 #include <linux/page-flags-layout.h>
21 #include <linux/atomic.h>
22 #include <linux/mm_types.h>
23 #include <linux/page-flags.h>
24 #include <linux/local_lock.h>
25 #include <linux/android_kabi.h>
26 #include <asm/page.h>
27
28 /* Free memory management - zoned buddy allocator. */
29 #ifndef CONFIG_ARCH_FORCE_MAX_ORDER
30 #define MAX_ORDER 11
31 #else
32 #define MAX_ORDER CONFIG_ARCH_FORCE_MAX_ORDER
33 #endif
34 #define MAX_ORDER_NR_PAGES (1 << (MAX_ORDER - 1))
35
36 /*
37 * PAGE_ALLOC_COSTLY_ORDER is the order at which allocations are deemed
38 * costly to service. That is between allocation orders which should
39 * coalesce naturally under reasonable reclaim pressure and those which
40 * will not.
41 */
42 #define PAGE_ALLOC_COSTLY_ORDER 3
43
44 #define MAX_KSWAPD_THREADS 16
45
46 enum migratetype {
47 MIGRATE_UNMOVABLE,
48 MIGRATE_MOVABLE,
49 MIGRATE_RECLAIMABLE,
50 #ifdef CONFIG_CMA
51 /*
52 * MIGRATE_CMA migration type is designed to mimic the way
53 * ZONE_MOVABLE works. Only movable pages can be allocated
54 * from MIGRATE_CMA pageblocks and page allocator never
55 * implicitly change migration type of MIGRATE_CMA pageblock.
56 *
57 * The way to use it is to change migratetype of a range of
58 * pageblocks to MIGRATE_CMA which can be done by
59 * __free_pageblock_cma() function.
60 */
61 MIGRATE_CMA,
62 #endif
63 MIGRATE_PCPTYPES, /* the number of types on the pcp lists */
64 MIGRATE_HIGHATOMIC = MIGRATE_PCPTYPES,
65 #ifdef CONFIG_MEMORY_ISOLATION
66 MIGRATE_ISOLATE, /* can't allocate from here */
67 #endif
68 MIGRATE_TYPES
69 };
70
71 /* In mm/page_alloc.c; keep in sync also with show_migration_types() there */
72 extern const char * const migratetype_names[MIGRATE_TYPES];
73
74 #ifdef CONFIG_CMA
75 # define is_migrate_cma(migratetype) unlikely((migratetype) == MIGRATE_CMA)
76 # define is_migrate_cma_page(_page) (get_pageblock_migratetype(_page) == MIGRATE_CMA)
77 # define get_cma_migrate_type() MIGRATE_CMA
78 #else
79 # define is_migrate_cma(migratetype) false
80 # define is_migrate_cma_page(_page) false
81 # define get_cma_migrate_type() MIGRATE_MOVABLE
82 #endif
83
is_migrate_movable(int mt)84 static inline bool is_migrate_movable(int mt)
85 {
86 return is_migrate_cma(mt) || mt == MIGRATE_MOVABLE;
87 }
88
89 /*
90 * Check whether a migratetype can be merged with another migratetype.
91 *
92 * It is only mergeable when it can fall back to other migratetypes for
93 * allocation. See fallbacks[MIGRATE_TYPES][3] in page_alloc.c.
94 */
migratetype_is_mergeable(int mt)95 static inline bool migratetype_is_mergeable(int mt)
96 {
97 return mt <= MIGRATE_RECLAIMABLE;
98 }
99
100 #define for_each_migratetype_order(order, type) \
101 for (order = 0; order < MAX_ORDER; order++) \
102 for (type = 0; type < MIGRATE_TYPES; type++)
103
104 extern int page_group_by_mobility_disabled;
105
106 #define MIGRATETYPE_MASK ((1UL << PB_migratetype_bits) - 1)
107
108 #define get_pageblock_migratetype(page) \
109 get_pfnblock_flags_mask(page, page_to_pfn(page), MIGRATETYPE_MASK)
110
111 struct free_area {
112 struct list_head free_list[MIGRATE_TYPES];
113 unsigned long nr_free;
114 };
115
get_page_from_free_area(struct free_area * area,int migratetype)116 static inline struct page *get_page_from_free_area(struct free_area *area,
117 int migratetype)
118 {
119 return list_first_entry_or_null(&area->free_list[migratetype],
120 struct page, lru);
121 }
122
free_area_empty(struct free_area * area,int migratetype)123 static inline bool free_area_empty(struct free_area *area, int migratetype)
124 {
125 return list_empty(&area->free_list[migratetype]);
126 }
127
128 struct pglist_data;
129
130 #ifdef CONFIG_NUMA
131 enum numa_stat_item {
132 NUMA_HIT, /* allocated in intended node */
133 NUMA_MISS, /* allocated in non intended node */
134 NUMA_FOREIGN, /* was intended here, hit elsewhere */
135 NUMA_INTERLEAVE_HIT, /* interleaver preferred this zone */
136 NUMA_LOCAL, /* allocation from local node */
137 NUMA_OTHER, /* allocation from other node */
138 NR_VM_NUMA_EVENT_ITEMS
139 };
140 #else
141 #define NR_VM_NUMA_EVENT_ITEMS 0
142 #endif
143
144 enum zone_stat_item {
145 /* First 128 byte cacheline (assuming 64 bit words) */
146 NR_FREE_PAGES,
147 NR_ZONE_LRU_BASE, /* Used only for compaction and reclaim retry */
148 NR_ZONE_INACTIVE_ANON = NR_ZONE_LRU_BASE,
149 NR_ZONE_ACTIVE_ANON,
150 NR_ZONE_INACTIVE_FILE,
151 NR_ZONE_ACTIVE_FILE,
152 NR_ZONE_UNEVICTABLE,
153 NR_ZONE_WRITE_PENDING, /* Count of dirty, writeback and unstable pages */
154 NR_MLOCK, /* mlock()ed pages found and moved off LRU */
155 /* Second 128 byte cacheline */
156 NR_BOUNCE,
157 NR_ZSPAGES, /* allocated in zsmalloc */
158 NR_FREE_CMA_PAGES,
159 NR_VM_ZONE_STAT_ITEMS };
160
161 enum node_stat_item {
162 NR_LRU_BASE,
163 NR_INACTIVE_ANON = NR_LRU_BASE, /* must match order of LRU_[IN]ACTIVE */
164 NR_ACTIVE_ANON, /* " " " " " */
165 NR_INACTIVE_FILE, /* " " " " " */
166 NR_ACTIVE_FILE, /* " " " " " */
167 NR_UNEVICTABLE, /* " " " " " */
168 NR_SLAB_RECLAIMABLE_B,
169 NR_SLAB_UNRECLAIMABLE_B,
170 NR_ISOLATED_ANON, /* Temporary isolated pages from anon lru */
171 NR_ISOLATED_FILE, /* Temporary isolated pages from file lru */
172 WORKINGSET_NODES,
173 WORKINGSET_REFAULT_BASE,
174 WORKINGSET_REFAULT_ANON = WORKINGSET_REFAULT_BASE,
175 WORKINGSET_REFAULT_FILE,
176 WORKINGSET_ACTIVATE_BASE,
177 WORKINGSET_ACTIVATE_ANON = WORKINGSET_ACTIVATE_BASE,
178 WORKINGSET_ACTIVATE_FILE,
179 WORKINGSET_RESTORE_BASE,
180 WORKINGSET_RESTORE_ANON = WORKINGSET_RESTORE_BASE,
181 WORKINGSET_RESTORE_FILE,
182 WORKINGSET_NODERECLAIM,
183 NR_ANON_MAPPED, /* Mapped anonymous pages */
184 NR_FILE_MAPPED, /* pagecache pages mapped into pagetables.
185 only modified from process context */
186 NR_FILE_PAGES,
187 NR_FILE_DIRTY,
188 NR_WRITEBACK,
189 NR_WRITEBACK_TEMP, /* Writeback using temporary buffers */
190 NR_SHMEM, /* shmem pages (included tmpfs/GEM pages) */
191 NR_SHMEM_THPS,
192 NR_SHMEM_PMDMAPPED,
193 NR_FILE_THPS,
194 NR_FILE_PMDMAPPED,
195 NR_ANON_THPS,
196 NR_VMSCAN_WRITE,
197 NR_VMSCAN_IMMEDIATE, /* Prioritise for reclaim when writeback ends */
198 NR_DIRTIED, /* page dirtyings since bootup */
199 NR_WRITTEN, /* page writings since bootup */
200 NR_THROTTLED_WRITTEN, /* NR_WRITTEN while reclaim throttled */
201 NR_KERNEL_MISC_RECLAIMABLE, /* reclaimable non-slab kernel pages */
202 NR_FOLL_PIN_ACQUIRED, /* via: pin_user_page(), gup flag: FOLL_PIN */
203 NR_FOLL_PIN_RELEASED, /* pages returned via unpin_user_page() */
204 NR_KERNEL_STACK_KB, /* measured in KiB */
205 #if IS_ENABLED(CONFIG_SHADOW_CALL_STACK)
206 NR_KERNEL_SCS_KB, /* measured in KiB */
207 #endif
208 NR_PAGETABLE, /* used for pagetables */
209 NR_SECONDARY_PAGETABLE, /* secondary pagetables, e.g. KVM pagetables */
210 #ifdef CONFIG_SWAP
211 NR_SWAPCACHE,
212 #endif
213 #ifdef CONFIG_NUMA_BALANCING
214 PGPROMOTE_SUCCESS, /* promote successfully */
215 PGPROMOTE_CANDIDATE, /* candidate pages to promote */
216 #endif
217 NR_VM_NODE_STAT_ITEMS
218 };
219
220 /*
221 * Returns true if the item should be printed in THPs (/proc/vmstat
222 * currently prints number of anon, file and shmem THPs. But the item
223 * is charged in pages).
224 */
vmstat_item_print_in_thp(enum node_stat_item item)225 static __always_inline bool vmstat_item_print_in_thp(enum node_stat_item item)
226 {
227 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE))
228 return false;
229
230 return item == NR_ANON_THPS ||
231 item == NR_FILE_THPS ||
232 item == NR_SHMEM_THPS ||
233 item == NR_SHMEM_PMDMAPPED ||
234 item == NR_FILE_PMDMAPPED;
235 }
236
237 /*
238 * Returns true if the value is measured in bytes (most vmstat values are
239 * measured in pages). This defines the API part, the internal representation
240 * might be different.
241 */
vmstat_item_in_bytes(int idx)242 static __always_inline bool vmstat_item_in_bytes(int idx)
243 {
244 /*
245 * Global and per-node slab counters track slab pages.
246 * It's expected that changes are multiples of PAGE_SIZE.
247 * Internally values are stored in pages.
248 *
249 * Per-memcg and per-lruvec counters track memory, consumed
250 * by individual slab objects. These counters are actually
251 * byte-precise.
252 */
253 return (idx == NR_SLAB_RECLAIMABLE_B ||
254 idx == NR_SLAB_UNRECLAIMABLE_B);
255 }
256
257 /*
258 * We do arithmetic on the LRU lists in various places in the code,
259 * so it is important to keep the active lists LRU_ACTIVE higher in
260 * the array than the corresponding inactive lists, and to keep
261 * the *_FILE lists LRU_FILE higher than the corresponding _ANON lists.
262 *
263 * This has to be kept in sync with the statistics in zone_stat_item
264 * above and the descriptions in vmstat_text in mm/vmstat.c
265 */
266 #define LRU_BASE 0
267 #define LRU_ACTIVE 1
268 #define LRU_FILE 2
269
270 enum lru_list {
271 LRU_INACTIVE_ANON = LRU_BASE,
272 LRU_ACTIVE_ANON = LRU_BASE + LRU_ACTIVE,
273 LRU_INACTIVE_FILE = LRU_BASE + LRU_FILE,
274 LRU_ACTIVE_FILE = LRU_BASE + LRU_FILE + LRU_ACTIVE,
275 LRU_UNEVICTABLE,
276 NR_LRU_LISTS
277 };
278
279 enum vmscan_throttle_state {
280 VMSCAN_THROTTLE_WRITEBACK,
281 VMSCAN_THROTTLE_ISOLATED,
282 VMSCAN_THROTTLE_NOPROGRESS,
283 VMSCAN_THROTTLE_CONGESTED,
284 NR_VMSCAN_THROTTLE,
285 };
286
287 #define for_each_lru(lru) for (lru = 0; lru < NR_LRU_LISTS; lru++)
288
289 #define for_each_evictable_lru(lru) for (lru = 0; lru <= LRU_ACTIVE_FILE; lru++)
290
is_file_lru(enum lru_list lru)291 static inline bool is_file_lru(enum lru_list lru)
292 {
293 return (lru == LRU_INACTIVE_FILE || lru == LRU_ACTIVE_FILE);
294 }
295
is_active_lru(enum lru_list lru)296 static inline bool is_active_lru(enum lru_list lru)
297 {
298 return (lru == LRU_ACTIVE_ANON || lru == LRU_ACTIVE_FILE);
299 }
300
301 #define WORKINGSET_ANON 0
302 #define WORKINGSET_FILE 1
303 #define ANON_AND_FILE 2
304
305 enum lruvec_flags {
306 LRUVEC_CONGESTED, /* lruvec has many dirty pages
307 * backed by a congested BDI
308 */
309 };
310
311 #endif /* !__GENERATING_BOUNDS_H */
312
313 /*
314 * Evictable pages are divided into multiple generations. The youngest and the
315 * oldest generation numbers, max_seq and min_seq, are monotonically increasing.
316 * They form a sliding window of a variable size [MIN_NR_GENS, MAX_NR_GENS]. An
317 * offset within MAX_NR_GENS, i.e., gen, indexes the LRU list of the
318 * corresponding generation. The gen counter in folio->flags stores gen+1 while
319 * a page is on one of lrugen->folios[]. Otherwise it stores 0.
320 *
321 * A page is added to the youngest generation on faulting. The aging needs to
322 * check the accessed bit at least twice before handing this page over to the
323 * eviction. The first check takes care of the accessed bit set on the initial
324 * fault; the second check makes sure this page hasn't been used since then.
325 * This process, AKA second chance, requires a minimum of two generations,
326 * hence MIN_NR_GENS. And to maintain ABI compatibility with the active/inactive
327 * LRU, e.g., /proc/vmstat, these two generations are considered active; the
328 * rest of generations, if they exist, are considered inactive. See
329 * lru_gen_is_active().
330 *
331 * PG_active is always cleared while a page is on one of lrugen->folios[] so
332 * that the aging needs not to worry about it. And it's set again when a page
333 * considered active is isolated for non-reclaiming purposes, e.g., migration.
334 * See lru_gen_add_folio() and lru_gen_del_folio().
335 *
336 * MAX_NR_GENS is set to 4 so that the multi-gen LRU can support twice the
337 * number of categories of the active/inactive LRU when keeping track of
338 * accesses through page tables. This requires order_base_2(MAX_NR_GENS+1) bits
339 * in folio->flags.
340 */
341 #define MIN_NR_GENS 2U
342 #define MAX_NR_GENS 4U
343
344 /*
345 * Each generation is divided into multiple tiers. A page accessed N times
346 * through file descriptors is in tier order_base_2(N). A page in the first tier
347 * (N=0,1) is marked by PG_referenced unless it was faulted in through page
348 * tables or read ahead. A page in any other tier (N>1) is marked by
349 * PG_referenced and PG_workingset. This implies a minimum of two tiers is
350 * supported without using additional bits in folio->flags.
351 *
352 * In contrast to moving across generations which requires the LRU lock, moving
353 * across tiers only involves atomic operations on folio->flags and therefore
354 * has a negligible cost in the buffered access path. In the eviction path,
355 * comparisons of refaulted/(evicted+protected) from the first tier and the
356 * rest infer whether pages accessed multiple times through file descriptors
357 * are statistically hot and thus worth protecting.
358 *
359 * MAX_NR_TIERS is set to 4 so that the multi-gen LRU can support twice the
360 * number of categories of the active/inactive LRU when keeping track of
361 * accesses through file descriptors. This uses MAX_NR_TIERS-2 spare bits in
362 * folio->flags.
363 */
364 #define MAX_NR_TIERS 4U
365
366 #ifndef __GENERATING_BOUNDS_H
367
368 struct lruvec;
369 struct page_vma_mapped_walk;
370
371 #define LRU_GEN_MASK ((BIT(LRU_GEN_WIDTH) - 1) << LRU_GEN_PGOFF)
372 #define LRU_REFS_MASK ((BIT(LRU_REFS_WIDTH) - 1) << LRU_REFS_PGOFF)
373
374 #ifdef CONFIG_LRU_GEN
375
376 enum {
377 LRU_GEN_ANON,
378 LRU_GEN_FILE,
379 };
380
381 enum {
382 LRU_GEN_CORE,
383 LRU_GEN_MM_WALK,
384 LRU_GEN_NONLEAF_YOUNG,
385 NR_LRU_GEN_CAPS
386 };
387
388 #define MIN_LRU_BATCH BITS_PER_LONG
389 #define MAX_LRU_BATCH (MIN_LRU_BATCH * 64)
390
391 /* whether to keep historical stats from evicted generations */
392 #ifdef CONFIG_LRU_GEN_STATS
393 #define NR_HIST_GENS MAX_NR_GENS
394 #else
395 #define NR_HIST_GENS 1U
396 #endif
397
398 /*
399 * The youngest generation number is stored in max_seq for both anon and file
400 * types as they are aged on an equal footing. The oldest generation numbers are
401 * stored in min_seq[] separately for anon and file types as clean file pages
402 * can be evicted regardless of swap constraints.
403 *
404 * Normally anon and file min_seq are in sync. But if swapping is constrained,
405 * e.g., out of swap space, file min_seq is allowed to advance and leave anon
406 * min_seq behind.
407 *
408 * The number of pages in each generation is eventually consistent and therefore
409 * can be transiently negative when reset_batch_size() is pending.
410 */
411 struct lru_gen_folio {
412 /* the aging increments the youngest generation number */
413 unsigned long max_seq;
414 /* the eviction increments the oldest generation numbers */
415 unsigned long min_seq[ANON_AND_FILE];
416 /* the birth time of each generation in jiffies */
417 unsigned long timestamps[MAX_NR_GENS];
418 /* the multi-gen LRU lists, lazily sorted on eviction */
419 struct list_head folios[MAX_NR_GENS][ANON_AND_FILE][MAX_NR_ZONES];
420 /* the multi-gen LRU sizes, eventually consistent */
421 long nr_pages[MAX_NR_GENS][ANON_AND_FILE][MAX_NR_ZONES];
422 /* the exponential moving average of refaulted */
423 unsigned long avg_refaulted[ANON_AND_FILE][MAX_NR_TIERS];
424 /* the exponential moving average of evicted+protected */
425 unsigned long avg_total[ANON_AND_FILE][MAX_NR_TIERS];
426 /* the first tier doesn't need protection, hence the minus one */
427 unsigned long protected[NR_HIST_GENS][ANON_AND_FILE][MAX_NR_TIERS - 1];
428 /* can be modified without holding the LRU lock */
429 atomic_long_t evicted[NR_HIST_GENS][ANON_AND_FILE][MAX_NR_TIERS];
430 atomic_long_t refaulted[NR_HIST_GENS][ANON_AND_FILE][MAX_NR_TIERS];
431 /* whether the multi-gen LRU is enabled */
432 bool enabled;
433 #ifdef CONFIG_MEMCG
434 /* the memcg generation this lru_gen_folio belongs to */
435 u8 gen;
436 /* the list segment this lru_gen_folio belongs to */
437 u8 seg;
438 /* per-node lru_gen_folio list for global reclaim */
439 struct hlist_nulls_node list;
440 #endif
441
442 ANDROID_KABI_RESERVE(1);
443 ANDROID_KABI_RESERVE(2);
444 };
445
446 enum {
447 MM_LEAF_TOTAL, /* total leaf entries */
448 MM_LEAF_OLD, /* old leaf entries */
449 MM_LEAF_YOUNG, /* young leaf entries */
450 MM_NONLEAF_TOTAL, /* total non-leaf entries */
451 MM_NONLEAF_FOUND, /* non-leaf entries found in Bloom filters */
452 MM_NONLEAF_ADDED, /* non-leaf entries added to Bloom filters */
453 NR_MM_STATS
454 };
455
456 /* double-buffering Bloom filters */
457 #define NR_BLOOM_FILTERS 2
458
459 struct lru_gen_mm_state {
460 /* set to max_seq after each iteration */
461 unsigned long seq;
462 /* where the current iteration continues after */
463 struct list_head *head;
464 /* where the last iteration ended before */
465 struct list_head *tail;
466 /* Bloom filters flip after each iteration */
467 unsigned long *filters[NR_BLOOM_FILTERS];
468 /* the mm stats for debugging */
469 unsigned long stats[NR_HIST_GENS][NR_MM_STATS];
470
471 ANDROID_KABI_RESERVE(1);
472 };
473
474 struct lru_gen_mm_walk {
475 /* the lruvec under reclaim */
476 struct lruvec *lruvec;
477 /* unstable max_seq from lru_gen_folio */
478 unsigned long max_seq;
479 /* the next address within an mm to scan */
480 unsigned long next_addr;
481 /* to batch promoted pages */
482 int nr_pages[MAX_NR_GENS][ANON_AND_FILE][MAX_NR_ZONES];
483 /* to batch the mm stats */
484 int mm_stats[NR_MM_STATS];
485 /* total batched items */
486 int batched;
487 bool can_swap;
488 bool force_scan;
489
490 ANDROID_KABI_RESERVE(1);
491 ANDROID_KABI_RESERVE(2);
492 };
493
494 void lru_gen_init_lruvec(struct lruvec *lruvec);
495 void lru_gen_look_around(struct page_vma_mapped_walk *pvmw);
496
497 #ifdef CONFIG_MEMCG
498
499 /*
500 * For each node, memcgs are divided into two generations: the old and the
501 * young. For each generation, memcgs are randomly sharded into multiple bins
502 * to improve scalability. For each bin, the hlist_nulls is virtually divided
503 * into three segments: the head, the tail and the default.
504 *
505 * An onlining memcg is added to the tail of a random bin in the old generation.
506 * The eviction starts at the head of a random bin in the old generation. The
507 * per-node memcg generation counter, whose reminder (mod MEMCG_NR_GENS) indexes
508 * the old generation, is incremented when all its bins become empty.
509 *
510 * There are four operations:
511 * 1. MEMCG_LRU_HEAD, which moves an memcg to the head of a random bin in its
512 * current generation (old or young) and updates its "seg" to "head";
513 * 2. MEMCG_LRU_TAIL, which moves an memcg to the tail of a random bin in its
514 * current generation (old or young) and updates its "seg" to "tail";
515 * 3. MEMCG_LRU_OLD, which moves an memcg to the head of a random bin in the old
516 * generation, updates its "gen" to "old" and resets its "seg" to "default";
517 * 4. MEMCG_LRU_YOUNG, which moves an memcg to the tail of a random bin in the
518 * young generation, updates its "gen" to "young" and resets its "seg" to
519 * "default".
520 *
521 * The events that trigger the above operations are:
522 * 1. Exceeding the soft limit, which triggers MEMCG_LRU_HEAD;
523 * 2. The first attempt to reclaim an memcg below low, which triggers
524 * MEMCG_LRU_TAIL;
525 * 3. The first attempt to reclaim an memcg below reclaimable size threshold,
526 * which triggers MEMCG_LRU_TAIL;
527 * 4. The second attempt to reclaim an memcg below reclaimable size threshold,
528 * which triggers MEMCG_LRU_YOUNG;
529 * 5. Attempting to reclaim an memcg below min, which triggers MEMCG_LRU_YOUNG;
530 * 6. Finishing the aging on the eviction path, which triggers MEMCG_LRU_YOUNG;
531 * 7. Offlining an memcg, which triggers MEMCG_LRU_OLD.
532 *
533 * Note that memcg LRU only applies to global reclaim, and the round-robin
534 * incrementing of their max_seq counters ensures the eventual fairness to all
535 * eligible memcgs. For memcg reclaim, it still relies on mem_cgroup_iter().
536 */
537 #define MEMCG_NR_GENS 2
538 #define MEMCG_NR_BINS 8
539
540 struct lru_gen_memcg {
541 /* the per-node memcg generation counter */
542 unsigned long seq;
543 /* each memcg has one lru_gen_folio per node */
544 unsigned long nr_memcgs[MEMCG_NR_GENS];
545 /* per-node lru_gen_folio list for global reclaim */
546 struct hlist_nulls_head fifo[MEMCG_NR_GENS][MEMCG_NR_BINS];
547 /* protects the above */
548 spinlock_t lock;
549
550 ANDROID_KABI_RESERVE(1);
551 ANDROID_KABI_RESERVE(2);
552 };
553
554 void lru_gen_init_pgdat(struct pglist_data *pgdat);
555
556 void lru_gen_init_memcg(struct mem_cgroup *memcg);
557 void lru_gen_exit_memcg(struct mem_cgroup *memcg);
558 void lru_gen_online_memcg(struct mem_cgroup *memcg);
559 void lru_gen_offline_memcg(struct mem_cgroup *memcg);
560 void lru_gen_release_memcg(struct mem_cgroup *memcg);
561 void lru_gen_soft_reclaim(struct lruvec *lruvec);
562
563 #else /* !CONFIG_MEMCG */
564
565 #define MEMCG_NR_GENS 1
566
567 struct lru_gen_memcg {
568 };
569
lru_gen_init_pgdat(struct pglist_data * pgdat)570 static inline void lru_gen_init_pgdat(struct pglist_data *pgdat)
571 {
572 }
573
574 #endif /* CONFIG_MEMCG */
575
576 #else /* !CONFIG_LRU_GEN */
577
lru_gen_init_pgdat(struct pglist_data * pgdat)578 static inline void lru_gen_init_pgdat(struct pglist_data *pgdat)
579 {
580 }
581
lru_gen_init_lruvec(struct lruvec * lruvec)582 static inline void lru_gen_init_lruvec(struct lruvec *lruvec)
583 {
584 }
585
lru_gen_look_around(struct page_vma_mapped_walk * pvmw)586 static inline void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
587 {
588 }
589
590 #ifdef CONFIG_MEMCG
591
lru_gen_init_memcg(struct mem_cgroup * memcg)592 static inline void lru_gen_init_memcg(struct mem_cgroup *memcg)
593 {
594 }
595
lru_gen_exit_memcg(struct mem_cgroup * memcg)596 static inline void lru_gen_exit_memcg(struct mem_cgroup *memcg)
597 {
598 }
599
lru_gen_online_memcg(struct mem_cgroup * memcg)600 static inline void lru_gen_online_memcg(struct mem_cgroup *memcg)
601 {
602 }
603
lru_gen_offline_memcg(struct mem_cgroup * memcg)604 static inline void lru_gen_offline_memcg(struct mem_cgroup *memcg)
605 {
606 }
607
lru_gen_release_memcg(struct mem_cgroup * memcg)608 static inline void lru_gen_release_memcg(struct mem_cgroup *memcg)
609 {
610 }
611
lru_gen_soft_reclaim(struct lruvec * lruvec)612 static inline void lru_gen_soft_reclaim(struct lruvec *lruvec)
613 {
614 }
615
616 #endif /* CONFIG_MEMCG */
617
618 #endif /* CONFIG_LRU_GEN */
619
620 struct lruvec {
621 struct list_head lists[NR_LRU_LISTS];
622 /* per lruvec lru_lock for memcg */
623 spinlock_t lru_lock;
624 /*
625 * These track the cost of reclaiming one LRU - file or anon -
626 * over the other. As the observed cost of reclaiming one LRU
627 * increases, the reclaim scan balance tips toward the other.
628 */
629 unsigned long anon_cost;
630 unsigned long file_cost;
631 /* Non-resident age, driven by LRU movement */
632 atomic_long_t nonresident_age;
633 /* Refaults at the time of last reclaim cycle */
634 unsigned long refaults[ANON_AND_FILE];
635 /* Various lruvec state flags (enum lruvec_flags) */
636 unsigned long flags;
637 #ifdef CONFIG_LRU_GEN
638 /* evictable pages divided into generations */
639 struct lru_gen_folio lrugen;
640 /* to concurrently iterate lru_gen_mm_list */
641 struct lru_gen_mm_state mm_state;
642 #endif
643 #ifdef CONFIG_MEMCG
644 struct pglist_data *pgdat;
645 #endif
646 ANDROID_VENDOR_DATA(1);
647 ANDROID_KABI_RESERVE(1);
648 ANDROID_KABI_RESERVE(2);
649 };
650
651 /* Isolate unmapped pages */
652 #define ISOLATE_UNMAPPED ((__force isolate_mode_t)0x2)
653 /* Isolate for asynchronous migration */
654 #define ISOLATE_ASYNC_MIGRATE ((__force isolate_mode_t)0x4)
655 /* Isolate unevictable pages */
656 #define ISOLATE_UNEVICTABLE ((__force isolate_mode_t)0x8)
657
658 /* LRU Isolation modes. */
659 typedef unsigned __bitwise isolate_mode_t;
660
661 enum zone_watermarks {
662 WMARK_MIN,
663 WMARK_LOW,
664 WMARK_HIGH,
665 WMARK_PROMO,
666 NR_WMARK
667 };
668
669 /*
670 * One per migratetype for each PAGE_ALLOC_COSTLY_ORDER. One additional list
671 * for THP which will usually be GFP_MOVABLE. Even if it is another type,
672 * it should not contribute to serious fragmentation causing THP allocation
673 * failures.
674 */
675 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
676 #define NR_PCP_THP 1
677 #else
678 #define NR_PCP_THP 0
679 #endif
680 #define NR_LOWORDER_PCP_LISTS (MIGRATE_PCPTYPES * (PAGE_ALLOC_COSTLY_ORDER + 1))
681 #define NR_PCP_LISTS (NR_LOWORDER_PCP_LISTS + NR_PCP_THP)
682
683 #define min_wmark_pages(z) (z->_watermark[WMARK_MIN] + z->watermark_boost)
684 #define low_wmark_pages(z) (z->_watermark[WMARK_LOW] + z->watermark_boost)
685 #define high_wmark_pages(z) (z->_watermark[WMARK_HIGH] + z->watermark_boost)
686 #define wmark_pages(z, i) (z->_watermark[i] + z->watermark_boost)
687
688 /* Fields and list protected by pagesets local_lock in page_alloc.c */
689 struct per_cpu_pages {
690 spinlock_t lock; /* Protects lists field */
691 int count; /* number of pages in the list */
692 int high; /* high watermark, emptying needed */
693 int batch; /* chunk size for buddy add/remove */
694 short free_factor; /* batch scaling factor during free */
695 #ifdef CONFIG_NUMA
696 short expire; /* When 0, remote pagesets are drained */
697 #endif
698
699 /* Lists of pages, one per migrate type stored on the pcp-lists */
700 struct list_head lists[NR_PCP_LISTS];
701 } ____cacheline_aligned_in_smp;
702
703 struct per_cpu_zonestat {
704 #ifdef CONFIG_SMP
705 s8 vm_stat_diff[NR_VM_ZONE_STAT_ITEMS];
706 s8 stat_threshold;
707 #endif
708 #ifdef CONFIG_NUMA
709 /*
710 * Low priority inaccurate counters that are only folded
711 * on demand. Use a large type to avoid the overhead of
712 * folding during refresh_cpu_vm_stats.
713 */
714 unsigned long vm_numa_event[NR_VM_NUMA_EVENT_ITEMS];
715 #endif
716 };
717
718 struct per_cpu_nodestat {
719 s8 stat_threshold;
720 s8 vm_node_stat_diff[NR_VM_NODE_STAT_ITEMS];
721 };
722
723 #endif /* !__GENERATING_BOUNDS.H */
724
725 enum zone_type {
726 /*
727 * ZONE_DMA and ZONE_DMA32 are used when there are peripherals not able
728 * to DMA to all of the addressable memory (ZONE_NORMAL).
729 * On architectures where this area covers the whole 32 bit address
730 * space ZONE_DMA32 is used. ZONE_DMA is left for the ones with smaller
731 * DMA addressing constraints. This distinction is important as a 32bit
732 * DMA mask is assumed when ZONE_DMA32 is defined. Some 64-bit
733 * platforms may need both zones as they support peripherals with
734 * different DMA addressing limitations.
735 */
736 #ifdef CONFIG_ZONE_DMA
737 ZONE_DMA,
738 #endif
739 #ifdef CONFIG_ZONE_DMA32
740 ZONE_DMA32,
741 #endif
742 /*
743 * Normal addressable memory is in ZONE_NORMAL. DMA operations can be
744 * performed on pages in ZONE_NORMAL if the DMA devices support
745 * transfers to all addressable memory.
746 */
747 ZONE_NORMAL,
748 #ifdef CONFIG_HIGHMEM
749 /*
750 * A memory area that is only addressable by the kernel through
751 * mapping portions into its own address space. This is for example
752 * used by i386 to allow the kernel to address the memory beyond
753 * 900MB. The kernel will set up special mappings (page
754 * table entries on i386) for each page that the kernel needs to
755 * access.
756 */
757 ZONE_HIGHMEM,
758 #endif
759 /*
760 * ZONE_MOVABLE is similar to ZONE_NORMAL, except that it contains
761 * movable pages with few exceptional cases described below. Main use
762 * cases for ZONE_MOVABLE are to make memory offlining/unplug more
763 * likely to succeed, and to locally limit unmovable allocations - e.g.,
764 * to increase the number of THP/huge pages. Notable special cases are:
765 *
766 * 1. Pinned pages: (long-term) pinning of movable pages might
767 * essentially turn such pages unmovable. Therefore, we do not allow
768 * pinning long-term pages in ZONE_MOVABLE. When pages are pinned and
769 * faulted, they come from the right zone right away. However, it is
770 * still possible that address space already has pages in
771 * ZONE_MOVABLE at the time when pages are pinned (i.e. user has
772 * touches that memory before pinning). In such case we migrate them
773 * to a different zone. When migration fails - pinning fails.
774 * 2. memblock allocations: kernelcore/movablecore setups might create
775 * situations where ZONE_MOVABLE contains unmovable allocations
776 * after boot. Memory offlining and allocations fail early.
777 * 3. Memory holes: kernelcore/movablecore setups might create very rare
778 * situations where ZONE_MOVABLE contains memory holes after boot,
779 * for example, if we have sections that are only partially
780 * populated. Memory offlining and allocations fail early.
781 * 4. PG_hwpoison pages: while poisoned pages can be skipped during
782 * memory offlining, such pages cannot be allocated.
783 * 5. Unmovable PG_offline pages: in paravirtualized environments,
784 * hotplugged memory blocks might only partially be managed by the
785 * buddy (e.g., via XEN-balloon, Hyper-V balloon, virtio-mem). The
786 * parts not manged by the buddy are unmovable PG_offline pages. In
787 * some cases (virtio-mem), such pages can be skipped during
788 * memory offlining, however, cannot be moved/allocated. These
789 * techniques might use alloc_contig_range() to hide previously
790 * exposed pages from the buddy again (e.g., to implement some sort
791 * of memory unplug in virtio-mem).
792 * 6. ZERO_PAGE(0), kernelcore/movablecore setups might create
793 * situations where ZERO_PAGE(0) which is allocated differently
794 * on different platforms may end up in a movable zone. ZERO_PAGE(0)
795 * cannot be migrated.
796 * 7. Memory-hotplug: when using memmap_on_memory and onlining the
797 * memory to the MOVABLE zone, the vmemmap pages are also placed in
798 * such zone. Such pages cannot be really moved around as they are
799 * self-stored in the range, but they are treated as movable when
800 * the range they describe is about to be offlined.
801 *
802 * In general, no unmovable allocations that degrade memory offlining
803 * should end up in ZONE_MOVABLE. Allocators (like alloc_contig_range())
804 * have to expect that migrating pages in ZONE_MOVABLE can fail (even
805 * if has_unmovable_pages() states that there are no unmovable pages,
806 * there can be false negatives).
807 */
808 ZONE_MOVABLE,
809 #ifdef CONFIG_ZONE_DEVICE
810 ZONE_DEVICE,
811 #endif
812 __MAX_NR_ZONES
813
814 };
815
816 #ifndef __GENERATING_BOUNDS_H
817
818 #define ASYNC_AND_SYNC 2
819
820 struct zone {
821 /* Read-mostly fields */
822
823 /* zone watermarks, access with *_wmark_pages(zone) macros */
824 unsigned long _watermark[NR_WMARK];
825 unsigned long watermark_boost;
826
827 unsigned long nr_reserved_highatomic;
828
829 /*
830 * We don't know if the memory that we're going to allocate will be
831 * freeable or/and it will be released eventually, so to avoid totally
832 * wasting several GB of ram we must reserve some of the lower zone
833 * memory (otherwise we risk to run OOM on the lower zones despite
834 * there being tons of freeable ram on the higher zones). This array is
835 * recalculated at runtime if the sysctl_lowmem_reserve_ratio sysctl
836 * changes.
837 */
838 long lowmem_reserve[MAX_NR_ZONES];
839
840 #ifdef CONFIG_NUMA
841 int node;
842 #endif
843 struct pglist_data *zone_pgdat;
844 struct per_cpu_pages __percpu *per_cpu_pageset;
845 struct per_cpu_zonestat __percpu *per_cpu_zonestats;
846 /*
847 * the high and batch values are copied to individual pagesets for
848 * faster access
849 */
850 int pageset_high;
851 int pageset_batch;
852
853 #ifndef CONFIG_SPARSEMEM
854 /*
855 * Flags for a pageblock_nr_pages block. See pageblock-flags.h.
856 * In SPARSEMEM, this map is stored in struct mem_section
857 */
858 unsigned long *pageblock_flags;
859 #endif /* CONFIG_SPARSEMEM */
860
861 /* zone_start_pfn == zone_start_paddr >> PAGE_SHIFT */
862 unsigned long zone_start_pfn;
863
864 /*
865 * spanned_pages is the total pages spanned by the zone, including
866 * holes, which is calculated as:
867 * spanned_pages = zone_end_pfn - zone_start_pfn;
868 *
869 * present_pages is physical pages existing within the zone, which
870 * is calculated as:
871 * present_pages = spanned_pages - absent_pages(pages in holes);
872 *
873 * present_early_pages is present pages existing within the zone
874 * located on memory available since early boot, excluding hotplugged
875 * memory.
876 *
877 * managed_pages is present pages managed by the buddy system, which
878 * is calculated as (reserved_pages includes pages allocated by the
879 * bootmem allocator):
880 * managed_pages = present_pages - reserved_pages;
881 *
882 * cma pages is present pages that are assigned for CMA use
883 * (MIGRATE_CMA).
884 *
885 * So present_pages may be used by memory hotplug or memory power
886 * management logic to figure out unmanaged pages by checking
887 * (present_pages - managed_pages). And managed_pages should be used
888 * by page allocator and vm scanner to calculate all kinds of watermarks
889 * and thresholds.
890 *
891 * Locking rules:
892 *
893 * zone_start_pfn and spanned_pages are protected by span_seqlock.
894 * It is a seqlock because it has to be read outside of zone->lock,
895 * and it is done in the main allocator path. But, it is written
896 * quite infrequently.
897 *
898 * The span_seq lock is declared along with zone->lock because it is
899 * frequently read in proximity to zone->lock. It's good to
900 * give them a chance of being in the same cacheline.
901 *
902 * Write access to present_pages at runtime should be protected by
903 * mem_hotplug_begin/done(). Any reader who can't tolerant drift of
904 * present_pages should use get_online_mems() to get a stable value.
905 */
906 atomic_long_t managed_pages;
907 unsigned long spanned_pages;
908 unsigned long present_pages;
909 #if defined(CONFIG_MEMORY_HOTPLUG)
910 unsigned long present_early_pages;
911 #endif
912 #ifdef CONFIG_CMA
913 unsigned long cma_pages;
914 #endif
915
916 const char *name;
917
918 #ifdef CONFIG_MEMORY_ISOLATION
919 /*
920 * Number of isolated pageblock. It is used to solve incorrect
921 * freepage counting problem due to racy retrieving migratetype
922 * of pageblock. Protected by zone->lock.
923 */
924 unsigned long nr_isolate_pageblock;
925 #endif
926
927 #ifdef CONFIG_MEMORY_HOTPLUG
928 /* see spanned/present_pages for more description */
929 seqlock_t span_seqlock;
930 #endif
931
932 int initialized;
933
934 /* Write-intensive fields used from the page allocator */
935 CACHELINE_PADDING(_pad1_);
936
937 /* free areas of different sizes */
938 struct free_area free_area[MAX_ORDER];
939
940 /* zone flags, see below */
941 unsigned long flags;
942
943 /* Primarily protects free_area */
944 spinlock_t lock;
945
946 /* Write-intensive fields used by compaction and vmstats. */
947 CACHELINE_PADDING(_pad2_);
948
949 /*
950 * When free pages are below this point, additional steps are taken
951 * when reading the number of free pages to avoid per-cpu counter
952 * drift allowing watermarks to be breached
953 */
954 unsigned long percpu_drift_mark;
955
956 #if defined CONFIG_COMPACTION || defined CONFIG_CMA
957 /* pfn where compaction free scanner should start */
958 unsigned long compact_cached_free_pfn;
959 /* pfn where compaction migration scanner should start */
960 unsigned long compact_cached_migrate_pfn[ASYNC_AND_SYNC];
961 unsigned long compact_init_migrate_pfn;
962 unsigned long compact_init_free_pfn;
963 #endif
964
965 #ifdef CONFIG_COMPACTION
966 /*
967 * On compaction failure, 1<<compact_defer_shift compactions
968 * are skipped before trying again. The number attempted since
969 * last failure is tracked with compact_considered.
970 * compact_order_failed is the minimum compaction failed order.
971 */
972 unsigned int compact_considered;
973 unsigned int compact_defer_shift;
974 int compact_order_failed;
975 #endif
976
977 #if defined CONFIG_COMPACTION || defined CONFIG_CMA
978 /* Set to true when the PG_migrate_skip bits should be cleared */
979 bool compact_blockskip_flush;
980 #endif
981
982 bool contiguous;
983
984 CACHELINE_PADDING(_pad3_);
985 /* Zone statistics */
986 atomic_long_t vm_stat[NR_VM_ZONE_STAT_ITEMS];
987 atomic_long_t vm_numa_event[NR_VM_NUMA_EVENT_ITEMS];
988
989 ANDROID_KABI_RESERVE(1);
990 ANDROID_KABI_RESERVE(2);
991 ANDROID_KABI_RESERVE(3);
992 ANDROID_KABI_RESERVE(4);
993 } ____cacheline_internodealigned_in_smp;
994
995 enum pgdat_flags {
996 PGDAT_DIRTY, /* reclaim scanning has recently found
997 * many dirty file pages at the tail
998 * of the LRU.
999 */
1000 PGDAT_WRITEBACK, /* reclaim scanning has recently found
1001 * many pages under writeback
1002 */
1003 PGDAT_RECLAIM_LOCKED, /* prevents concurrent reclaim */
1004 };
1005
1006 enum zone_flags {
1007 ZONE_BOOSTED_WATERMARK, /* zone recently boosted watermarks.
1008 * Cleared when kswapd is woken.
1009 */
1010 ZONE_RECLAIM_ACTIVE, /* kswapd may be scanning the zone. */
1011 };
1012
zone_managed_pages(struct zone * zone)1013 static inline unsigned long zone_managed_pages(struct zone *zone)
1014 {
1015 return (unsigned long)atomic_long_read(&zone->managed_pages);
1016 }
1017
zone_cma_pages(struct zone * zone)1018 static inline unsigned long zone_cma_pages(struct zone *zone)
1019 {
1020 #ifdef CONFIG_CMA
1021 return zone->cma_pages;
1022 #else
1023 return 0;
1024 #endif
1025 }
1026
zone_end_pfn(const struct zone * zone)1027 static inline unsigned long zone_end_pfn(const struct zone *zone)
1028 {
1029 return zone->zone_start_pfn + zone->spanned_pages;
1030 }
1031
zone_spans_pfn(const struct zone * zone,unsigned long pfn)1032 static inline bool zone_spans_pfn(const struct zone *zone, unsigned long pfn)
1033 {
1034 return zone->zone_start_pfn <= pfn && pfn < zone_end_pfn(zone);
1035 }
1036
zone_is_initialized(struct zone * zone)1037 static inline bool zone_is_initialized(struct zone *zone)
1038 {
1039 return zone->initialized;
1040 }
1041
zone_is_empty(struct zone * zone)1042 static inline bool zone_is_empty(struct zone *zone)
1043 {
1044 return zone->spanned_pages == 0;
1045 }
1046
1047 #ifndef BUILD_VDSO32_64
1048 /*
1049 * The zone field is never updated after free_area_init_core()
1050 * sets it, so none of the operations on it need to be atomic.
1051 */
1052
1053 /* Page flags: | [SECTION] | [NODE] | ZONE | [LAST_CPUPID] | ... | FLAGS | */
1054 #define SECTIONS_PGOFF ((sizeof(unsigned long)*8) - SECTIONS_WIDTH)
1055 #define NODES_PGOFF (SECTIONS_PGOFF - NODES_WIDTH)
1056 #define ZONES_PGOFF (NODES_PGOFF - ZONES_WIDTH)
1057 #define LAST_CPUPID_PGOFF (ZONES_PGOFF - LAST_CPUPID_WIDTH)
1058 #define KASAN_TAG_PGOFF (LAST_CPUPID_PGOFF - KASAN_TAG_WIDTH)
1059 #define LRU_GEN_PGOFF (KASAN_TAG_PGOFF - LRU_GEN_WIDTH)
1060 #define LRU_REFS_PGOFF (LRU_GEN_PGOFF - LRU_REFS_WIDTH)
1061
1062 /*
1063 * Define the bit shifts to access each section. For non-existent
1064 * sections we define the shift as 0; that plus a 0 mask ensures
1065 * the compiler will optimise away reference to them.
1066 */
1067 #define SECTIONS_PGSHIFT (SECTIONS_PGOFF * (SECTIONS_WIDTH != 0))
1068 #define NODES_PGSHIFT (NODES_PGOFF * (NODES_WIDTH != 0))
1069 #define ZONES_PGSHIFT (ZONES_PGOFF * (ZONES_WIDTH != 0))
1070 #define LAST_CPUPID_PGSHIFT (LAST_CPUPID_PGOFF * (LAST_CPUPID_WIDTH != 0))
1071 #define KASAN_TAG_PGSHIFT (KASAN_TAG_PGOFF * (KASAN_TAG_WIDTH != 0))
1072
1073 /* NODE:ZONE or SECTION:ZONE is used to ID a zone for the buddy allocator */
1074 #ifdef NODE_NOT_IN_PAGE_FLAGS
1075 #define ZONEID_SHIFT (SECTIONS_SHIFT + ZONES_SHIFT)
1076 #define ZONEID_PGOFF ((SECTIONS_PGOFF < ZONES_PGOFF) ? \
1077 SECTIONS_PGOFF : ZONES_PGOFF)
1078 #else
1079 #define ZONEID_SHIFT (NODES_SHIFT + ZONES_SHIFT)
1080 #define ZONEID_PGOFF ((NODES_PGOFF < ZONES_PGOFF) ? \
1081 NODES_PGOFF : ZONES_PGOFF)
1082 #endif
1083
1084 #define ZONEID_PGSHIFT (ZONEID_PGOFF * (ZONEID_SHIFT != 0))
1085
1086 #define ZONES_MASK ((1UL << ZONES_WIDTH) - 1)
1087 #define NODES_MASK ((1UL << NODES_WIDTH) - 1)
1088 #define SECTIONS_MASK ((1UL << SECTIONS_WIDTH) - 1)
1089 #define LAST_CPUPID_MASK ((1UL << LAST_CPUPID_SHIFT) - 1)
1090 #define KASAN_TAG_MASK ((1UL << KASAN_TAG_WIDTH) - 1)
1091 #define ZONEID_MASK ((1UL << ZONEID_SHIFT) - 1)
1092
page_zonenum(const struct page * page)1093 static inline enum zone_type page_zonenum(const struct page *page)
1094 {
1095 ASSERT_EXCLUSIVE_BITS(page->flags, ZONES_MASK << ZONES_PGSHIFT);
1096 return (page->flags >> ZONES_PGSHIFT) & ZONES_MASK;
1097 }
1098
folio_zonenum(const struct folio * folio)1099 static inline enum zone_type folio_zonenum(const struct folio *folio)
1100 {
1101 return page_zonenum(&folio->page);
1102 }
1103
1104 #ifdef CONFIG_ZONE_DEVICE
is_zone_device_page(const struct page * page)1105 static inline bool is_zone_device_page(const struct page *page)
1106 {
1107 return page_zonenum(page) == ZONE_DEVICE;
1108 }
1109 extern void memmap_init_zone_device(struct zone *, unsigned long,
1110 unsigned long, struct dev_pagemap *);
1111 #else
is_zone_device_page(const struct page * page)1112 static inline bool is_zone_device_page(const struct page *page)
1113 {
1114 return false;
1115 }
1116 #endif
1117
folio_is_zone_device(const struct folio * folio)1118 static inline bool folio_is_zone_device(const struct folio *folio)
1119 {
1120 return is_zone_device_page(&folio->page);
1121 }
1122
is_zone_movable_page(const struct page * page)1123 static inline bool is_zone_movable_page(const struct page *page)
1124 {
1125 return page_zonenum(page) == ZONE_MOVABLE;
1126 }
1127 #endif
1128
1129 /*
1130 * Return true if [start_pfn, start_pfn + nr_pages) range has a non-empty
1131 * intersection with the given zone
1132 */
zone_intersects(struct zone * zone,unsigned long start_pfn,unsigned long nr_pages)1133 static inline bool zone_intersects(struct zone *zone,
1134 unsigned long start_pfn, unsigned long nr_pages)
1135 {
1136 if (zone_is_empty(zone))
1137 return false;
1138 if (start_pfn >= zone_end_pfn(zone) ||
1139 start_pfn + nr_pages <= zone->zone_start_pfn)
1140 return false;
1141
1142 return true;
1143 }
1144
1145 /*
1146 * The "priority" of VM scanning is how much of the queues we will scan in one
1147 * go. A value of 12 for DEF_PRIORITY implies that we will scan 1/4096th of the
1148 * queues ("queue_length >> 12") during an aging round.
1149 */
1150 #define DEF_PRIORITY 12
1151
1152 /* Maximum number of zones on a zonelist */
1153 #define MAX_ZONES_PER_ZONELIST (MAX_NUMNODES * MAX_NR_ZONES)
1154
1155 enum {
1156 ZONELIST_FALLBACK, /* zonelist with fallback */
1157 #ifdef CONFIG_NUMA
1158 /*
1159 * The NUMA zonelists are doubled because we need zonelists that
1160 * restrict the allocations to a single node for __GFP_THISNODE.
1161 */
1162 ZONELIST_NOFALLBACK, /* zonelist without fallback (__GFP_THISNODE) */
1163 #endif
1164 MAX_ZONELISTS
1165 };
1166
1167 /*
1168 * This struct contains information about a zone in a zonelist. It is stored
1169 * here to avoid dereferences into large structures and lookups of tables
1170 */
1171 struct zoneref {
1172 struct zone *zone; /* Pointer to actual zone */
1173 int zone_idx; /* zone_idx(zoneref->zone) */
1174 };
1175
1176 /*
1177 * One allocation request operates on a zonelist. A zonelist
1178 * is a list of zones, the first one is the 'goal' of the
1179 * allocation, the other zones are fallback zones, in decreasing
1180 * priority.
1181 *
1182 * To speed the reading of the zonelist, the zonerefs contain the zone index
1183 * of the entry being read. Helper functions to access information given
1184 * a struct zoneref are
1185 *
1186 * zonelist_zone() - Return the struct zone * for an entry in _zonerefs
1187 * zonelist_zone_idx() - Return the index of the zone for an entry
1188 * zonelist_node_idx() - Return the index of the node for an entry
1189 */
1190 struct zonelist {
1191 struct zoneref _zonerefs[MAX_ZONES_PER_ZONELIST + 1];
1192 };
1193
1194 /*
1195 * The array of struct pages for flatmem.
1196 * It must be declared for SPARSEMEM as well because there are configurations
1197 * that rely on that.
1198 */
1199 extern struct page *mem_map;
1200
1201 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1202 struct deferred_split {
1203 spinlock_t split_queue_lock;
1204 struct list_head split_queue;
1205 unsigned long split_queue_len;
1206 };
1207 #endif
1208
1209 /*
1210 * On NUMA machines, each NUMA node would have a pg_data_t to describe
1211 * it's memory layout. On UMA machines there is a single pglist_data which
1212 * describes the whole memory.
1213 *
1214 * Memory statistics and page replacement data structures are maintained on a
1215 * per-zone basis.
1216 */
1217 typedef struct pglist_data {
1218 /*
1219 * node_zones contains just the zones for THIS node. Not all of the
1220 * zones may be populated, but it is the full list. It is referenced by
1221 * this node's node_zonelists as well as other node's node_zonelists.
1222 */
1223 struct zone node_zones[MAX_NR_ZONES];
1224
1225 /*
1226 * node_zonelists contains references to all zones in all nodes.
1227 * Generally the first zones will be references to this node's
1228 * node_zones.
1229 */
1230 struct zonelist node_zonelists[MAX_ZONELISTS];
1231
1232 int nr_zones; /* number of populated zones in this node */
1233 #ifdef CONFIG_FLATMEM /* means !SPARSEMEM */
1234 struct page *node_mem_map;
1235 #ifdef CONFIG_PAGE_EXTENSION
1236 struct page_ext *node_page_ext;
1237 #endif
1238 #endif
1239 #if defined(CONFIG_MEMORY_HOTPLUG) || defined(CONFIG_DEFERRED_STRUCT_PAGE_INIT)
1240 /*
1241 * Must be held any time you expect node_start_pfn,
1242 * node_present_pages, node_spanned_pages or nr_zones to stay constant.
1243 * Also synchronizes pgdat->first_deferred_pfn during deferred page
1244 * init.
1245 *
1246 * pgdat_resize_lock() and pgdat_resize_unlock() are provided to
1247 * manipulate node_size_lock without checking for CONFIG_MEMORY_HOTPLUG
1248 * or CONFIG_DEFERRED_STRUCT_PAGE_INIT.
1249 *
1250 * Nests above zone->lock and zone->span_seqlock
1251 */
1252 spinlock_t node_size_lock;
1253 #endif
1254 unsigned long node_start_pfn;
1255 unsigned long node_present_pages; /* total number of physical pages */
1256 unsigned long node_spanned_pages; /* total size of physical page
1257 range, including holes */
1258 int node_id;
1259 wait_queue_head_t kswapd_wait;
1260 wait_queue_head_t pfmemalloc_wait;
1261
1262 /* workqueues for throttling reclaim for different reasons. */
1263 wait_queue_head_t reclaim_wait[NR_VMSCAN_THROTTLE];
1264
1265 atomic_t nr_writeback_throttled;/* nr of writeback-throttled tasks */
1266 unsigned long nr_reclaim_start; /* nr pages written while throttled
1267 * when throttling started. */
1268 #ifdef CONFIG_MEMORY_HOTPLUG
1269 struct mutex kswapd_lock;
1270 #endif
1271 struct task_struct *kswapd; /* Protected by kswapd_lock */
1272 struct task_struct *mkswapd[MAX_KSWAPD_THREADS];
1273 int kswapd_order;
1274 enum zone_type kswapd_highest_zoneidx;
1275
1276 int kswapd_failures; /* Number of 'reclaimed == 0' runs */
1277
1278 ANDROID_OEM_DATA(1);
1279 #ifdef CONFIG_COMPACTION
1280 int kcompactd_max_order;
1281 enum zone_type kcompactd_highest_zoneidx;
1282 wait_queue_head_t kcompactd_wait;
1283 struct task_struct *kcompactd;
1284 bool proactive_compact_trigger;
1285 #endif
1286 /*
1287 * This is a per-node reserve of pages that are not available
1288 * to userspace allocations.
1289 */
1290 unsigned long totalreserve_pages;
1291
1292 #ifdef CONFIG_NUMA
1293 /*
1294 * node reclaim becomes active if more unmapped pages exist.
1295 */
1296 unsigned long min_unmapped_pages;
1297 unsigned long min_slab_pages;
1298 #endif /* CONFIG_NUMA */
1299
1300 /* Write-intensive fields used by page reclaim */
1301 CACHELINE_PADDING(_pad1_);
1302
1303 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1304 /*
1305 * If memory initialisation on large machines is deferred then this
1306 * is the first PFN that needs to be initialised.
1307 */
1308 unsigned long first_deferred_pfn;
1309 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
1310
1311 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1312 struct deferred_split deferred_split_queue;
1313 #endif
1314
1315 #ifdef CONFIG_NUMA_BALANCING
1316 /* start time in ms of current promote rate limit period */
1317 unsigned int nbp_rl_start;
1318 /* number of promote candidate pages at start time of current rate limit period */
1319 unsigned long nbp_rl_nr_cand;
1320 /* promote threshold in ms */
1321 unsigned int nbp_threshold;
1322 /* start time in ms of current promote threshold adjustment period */
1323 unsigned int nbp_th_start;
1324 /*
1325 * number of promote candidate pages at stat time of current promote
1326 * threshold adjustment period
1327 */
1328 unsigned long nbp_th_nr_cand;
1329 #endif
1330 /* Fields commonly accessed by the page reclaim scanner */
1331
1332 /*
1333 * NOTE: THIS IS UNUSED IF MEMCG IS ENABLED.
1334 *
1335 * Use mem_cgroup_lruvec() to look up lruvecs.
1336 */
1337 struct lruvec __lruvec;
1338
1339 unsigned long flags;
1340
1341 #ifdef CONFIG_LRU_GEN
1342 /* kswap mm walk data */
1343 struct lru_gen_mm_walk mm_walk;
1344 /* lru_gen_folio list */
1345 struct lru_gen_memcg memcg_lru;
1346 #endif
1347
1348 CACHELINE_PADDING(_pad2_);
1349
1350 /* Per-node vmstats */
1351 struct per_cpu_nodestat __percpu *per_cpu_nodestats;
1352 atomic_long_t vm_stat[NR_VM_NODE_STAT_ITEMS];
1353 #ifdef CONFIG_NUMA
1354 struct memory_tier __rcu *memtier;
1355 #endif
1356 } pg_data_t;
1357
1358 #define node_present_pages(nid) (NODE_DATA(nid)->node_present_pages)
1359 #define node_spanned_pages(nid) (NODE_DATA(nid)->node_spanned_pages)
1360
1361 #define node_start_pfn(nid) (NODE_DATA(nid)->node_start_pfn)
1362 #define node_end_pfn(nid) pgdat_end_pfn(NODE_DATA(nid))
1363
pgdat_end_pfn(pg_data_t * pgdat)1364 static inline unsigned long pgdat_end_pfn(pg_data_t *pgdat)
1365 {
1366 return pgdat->node_start_pfn + pgdat->node_spanned_pages;
1367 }
1368
1369 #include <linux/memory_hotplug.h>
1370
1371 void build_all_zonelists(pg_data_t *pgdat);
1372 void wakeup_kswapd(struct zone *zone, gfp_t gfp_mask, int order,
1373 enum zone_type highest_zoneidx);
1374 bool __zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
1375 int highest_zoneidx, unsigned int alloc_flags,
1376 long free_pages);
1377 bool zone_watermark_ok(struct zone *z, unsigned int order,
1378 unsigned long mark, int highest_zoneidx,
1379 unsigned int alloc_flags);
1380 bool zone_watermark_ok_safe(struct zone *z, unsigned int order,
1381 unsigned long mark, int highest_zoneidx);
1382 /*
1383 * Memory initialization context, use to differentiate memory added by
1384 * the platform statically or via memory hotplug interface.
1385 */
1386 enum meminit_context {
1387 MEMINIT_EARLY,
1388 MEMINIT_HOTPLUG,
1389 };
1390
1391 extern void init_currently_empty_zone(struct zone *zone, unsigned long start_pfn,
1392 unsigned long size);
1393
1394 extern void lruvec_init(struct lruvec *lruvec);
1395
lruvec_pgdat(struct lruvec * lruvec)1396 static inline struct pglist_data *lruvec_pgdat(struct lruvec *lruvec)
1397 {
1398 #ifdef CONFIG_MEMCG
1399 return lruvec->pgdat;
1400 #else
1401 return container_of(lruvec, struct pglist_data, __lruvec);
1402 #endif
1403 }
1404
1405 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
1406 int local_memory_node(int node_id);
1407 #else
local_memory_node(int node_id)1408 static inline int local_memory_node(int node_id) { return node_id; };
1409 #endif
1410
1411 /*
1412 * zone_idx() returns 0 for the ZONE_DMA zone, 1 for the ZONE_NORMAL zone, etc.
1413 */
1414 #define zone_idx(zone) ((zone) - (zone)->zone_pgdat->node_zones)
1415
1416 #ifdef CONFIG_ZONE_DEVICE
zone_is_zone_device(struct zone * zone)1417 static inline bool zone_is_zone_device(struct zone *zone)
1418 {
1419 return zone_idx(zone) == ZONE_DEVICE;
1420 }
1421 #else
zone_is_zone_device(struct zone * zone)1422 static inline bool zone_is_zone_device(struct zone *zone)
1423 {
1424 return false;
1425 }
1426 #endif
1427
1428 /*
1429 * Returns true if a zone has pages managed by the buddy allocator.
1430 * All the reclaim decisions have to use this function rather than
1431 * populated_zone(). If the whole zone is reserved then we can easily
1432 * end up with populated_zone() && !managed_zone().
1433 */
managed_zone(struct zone * zone)1434 static inline bool managed_zone(struct zone *zone)
1435 {
1436 return zone_managed_pages(zone);
1437 }
1438
1439 /* Returns true if a zone has memory */
populated_zone(struct zone * zone)1440 static inline bool populated_zone(struct zone *zone)
1441 {
1442 return zone->present_pages;
1443 }
1444
1445 #ifdef CONFIG_NUMA
zone_to_nid(struct zone * zone)1446 static inline int zone_to_nid(struct zone *zone)
1447 {
1448 return zone->node;
1449 }
1450
zone_set_nid(struct zone * zone,int nid)1451 static inline void zone_set_nid(struct zone *zone, int nid)
1452 {
1453 zone->node = nid;
1454 }
1455 #else
zone_to_nid(struct zone * zone)1456 static inline int zone_to_nid(struct zone *zone)
1457 {
1458 return 0;
1459 }
1460
zone_set_nid(struct zone * zone,int nid)1461 static inline void zone_set_nid(struct zone *zone, int nid) {}
1462 #endif
1463
1464 extern int movable_zone;
1465
is_highmem_idx(enum zone_type idx)1466 static inline int is_highmem_idx(enum zone_type idx)
1467 {
1468 #ifdef CONFIG_HIGHMEM
1469 return (idx == ZONE_HIGHMEM ||
1470 (idx == ZONE_MOVABLE && movable_zone == ZONE_HIGHMEM));
1471 #else
1472 return 0;
1473 #endif
1474 }
1475
1476 /**
1477 * is_highmem - helper function to quickly check if a struct zone is a
1478 * highmem zone or not. This is an attempt to keep references
1479 * to ZONE_{DMA/NORMAL/HIGHMEM/etc} in general code to a minimum.
1480 * @zone: pointer to struct zone variable
1481 * Return: 1 for a highmem zone, 0 otherwise
1482 */
is_highmem(struct zone * zone)1483 static inline int is_highmem(struct zone *zone)
1484 {
1485 return is_highmem_idx(zone_idx(zone));
1486 }
1487
1488 #ifdef CONFIG_ZONE_DMA
1489 bool has_managed_dma(void);
1490 #else
has_managed_dma(void)1491 static inline bool has_managed_dma(void)
1492 {
1493 return false;
1494 }
1495 #endif
1496
1497 /* These two functions are used to setup the per zone pages min values */
1498 struct ctl_table;
1499
1500 int min_free_kbytes_sysctl_handler(struct ctl_table *, int, void *, size_t *,
1501 loff_t *);
1502 int watermark_scale_factor_sysctl_handler(struct ctl_table *, int, void *,
1503 size_t *, loff_t *);
1504 extern int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES];
1505 int lowmem_reserve_ratio_sysctl_handler(struct ctl_table *, int, void *,
1506 size_t *, loff_t *);
1507 int percpu_pagelist_high_fraction_sysctl_handler(struct ctl_table *, int,
1508 void *, size_t *, loff_t *);
1509 int sysctl_min_unmapped_ratio_sysctl_handler(struct ctl_table *, int,
1510 void *, size_t *, loff_t *);
1511 int sysctl_min_slab_ratio_sysctl_handler(struct ctl_table *, int,
1512 void *, size_t *, loff_t *);
1513 int numa_zonelist_order_handler(struct ctl_table *, int,
1514 void *, size_t *, loff_t *);
1515 extern int percpu_pagelist_high_fraction;
1516 extern char numa_zonelist_order[];
1517 #define NUMA_ZONELIST_ORDER_LEN 16
1518
1519 #ifndef CONFIG_NUMA
1520
1521 extern struct pglist_data contig_page_data;
NODE_DATA(int nid)1522 static inline struct pglist_data *NODE_DATA(int nid)
1523 {
1524 return &contig_page_data;
1525 }
1526
1527 #else /* CONFIG_NUMA */
1528
1529 #include <asm/mmzone.h>
1530
1531 #endif /* !CONFIG_NUMA */
1532
1533 extern struct pglist_data *first_online_pgdat(void);
1534 extern struct pglist_data *next_online_pgdat(struct pglist_data *pgdat);
1535 extern struct zone *next_zone(struct zone *zone);
1536 extern int isolate_anon_lru_page(struct page *page);
1537
1538 /**
1539 * for_each_online_pgdat - helper macro to iterate over all online nodes
1540 * @pgdat: pointer to a pg_data_t variable
1541 */
1542 #define for_each_online_pgdat(pgdat) \
1543 for (pgdat = first_online_pgdat(); \
1544 pgdat; \
1545 pgdat = next_online_pgdat(pgdat))
1546 /**
1547 * for_each_zone - helper macro to iterate over all memory zones
1548 * @zone: pointer to struct zone variable
1549 *
1550 * The user only needs to declare the zone variable, for_each_zone
1551 * fills it in.
1552 */
1553 #define for_each_zone(zone) \
1554 for (zone = (first_online_pgdat())->node_zones; \
1555 zone; \
1556 zone = next_zone(zone))
1557
1558 #define for_each_populated_zone(zone) \
1559 for (zone = (first_online_pgdat())->node_zones; \
1560 zone; \
1561 zone = next_zone(zone)) \
1562 if (!populated_zone(zone)) \
1563 ; /* do nothing */ \
1564 else
1565
zonelist_zone(struct zoneref * zoneref)1566 static inline struct zone *zonelist_zone(struct zoneref *zoneref)
1567 {
1568 return zoneref->zone;
1569 }
1570
zonelist_zone_idx(struct zoneref * zoneref)1571 static inline int zonelist_zone_idx(struct zoneref *zoneref)
1572 {
1573 return zoneref->zone_idx;
1574 }
1575
zonelist_node_idx(struct zoneref * zoneref)1576 static inline int zonelist_node_idx(struct zoneref *zoneref)
1577 {
1578 return zone_to_nid(zoneref->zone);
1579 }
1580
1581 struct zoneref *__next_zones_zonelist(struct zoneref *z,
1582 enum zone_type highest_zoneidx,
1583 nodemask_t *nodes);
1584
1585 /**
1586 * next_zones_zonelist - Returns the next zone at or below highest_zoneidx within the allowed nodemask using a cursor within a zonelist as a starting point
1587 * @z: The cursor used as a starting point for the search
1588 * @highest_zoneidx: The zone index of the highest zone to return
1589 * @nodes: An optional nodemask to filter the zonelist with
1590 *
1591 * This function returns the next zone at or below a given zone index that is
1592 * within the allowed nodemask using a cursor as the starting point for the
1593 * search. The zoneref returned is a cursor that represents the current zone
1594 * being examined. It should be advanced by one before calling
1595 * next_zones_zonelist again.
1596 *
1597 * Return: the next zone at or below highest_zoneidx within the allowed
1598 * nodemask using a cursor within a zonelist as a starting point
1599 */
next_zones_zonelist(struct zoneref * z,enum zone_type highest_zoneidx,nodemask_t * nodes)1600 static __always_inline struct zoneref *next_zones_zonelist(struct zoneref *z,
1601 enum zone_type highest_zoneidx,
1602 nodemask_t *nodes)
1603 {
1604 if (likely(!nodes && zonelist_zone_idx(z) <= highest_zoneidx))
1605 return z;
1606 return __next_zones_zonelist(z, highest_zoneidx, nodes);
1607 }
1608
1609 /**
1610 * first_zones_zonelist - Returns the first zone at or below highest_zoneidx within the allowed nodemask in a zonelist
1611 * @zonelist: The zonelist to search for a suitable zone
1612 * @highest_zoneidx: The zone index of the highest zone to return
1613 * @nodes: An optional nodemask to filter the zonelist with
1614 *
1615 * This function returns the first zone at or below a given zone index that is
1616 * within the allowed nodemask. The zoneref returned is a cursor that can be
1617 * used to iterate the zonelist with next_zones_zonelist by advancing it by
1618 * one before calling.
1619 *
1620 * When no eligible zone is found, zoneref->zone is NULL (zoneref itself is
1621 * never NULL). This may happen either genuinely, or due to concurrent nodemask
1622 * update due to cpuset modification.
1623 *
1624 * Return: Zoneref pointer for the first suitable zone found
1625 */
first_zones_zonelist(struct zonelist * zonelist,enum zone_type highest_zoneidx,nodemask_t * nodes)1626 static inline struct zoneref *first_zones_zonelist(struct zonelist *zonelist,
1627 enum zone_type highest_zoneidx,
1628 nodemask_t *nodes)
1629 {
1630 return next_zones_zonelist(zonelist->_zonerefs,
1631 highest_zoneidx, nodes);
1632 }
1633
1634 /**
1635 * for_each_zone_zonelist_nodemask - helper macro to iterate over valid zones in a zonelist at or below a given zone index and within a nodemask
1636 * @zone: The current zone in the iterator
1637 * @z: The current pointer within zonelist->_zonerefs being iterated
1638 * @zlist: The zonelist being iterated
1639 * @highidx: The zone index of the highest zone to return
1640 * @nodemask: Nodemask allowed by the allocator
1641 *
1642 * This iterator iterates though all zones at or below a given zone index and
1643 * within a given nodemask
1644 */
1645 #define for_each_zone_zonelist_nodemask(zone, z, zlist, highidx, nodemask) \
1646 for (z = first_zones_zonelist(zlist, highidx, nodemask), zone = zonelist_zone(z); \
1647 zone; \
1648 z = next_zones_zonelist(++z, highidx, nodemask), \
1649 zone = zonelist_zone(z))
1650
1651 #define for_next_zone_zonelist_nodemask(zone, z, highidx, nodemask) \
1652 for (zone = z->zone; \
1653 zone; \
1654 z = next_zones_zonelist(++z, highidx, nodemask), \
1655 zone = zonelist_zone(z))
1656
1657
1658 /**
1659 * for_each_zone_zonelist - helper macro to iterate over valid zones in a zonelist at or below a given zone index
1660 * @zone: The current zone in the iterator
1661 * @z: The current pointer within zonelist->zones being iterated
1662 * @zlist: The zonelist being iterated
1663 * @highidx: The zone index of the highest zone to return
1664 *
1665 * This iterator iterates though all zones at or below a given zone index.
1666 */
1667 #define for_each_zone_zonelist(zone, z, zlist, highidx) \
1668 for_each_zone_zonelist_nodemask(zone, z, zlist, highidx, NULL)
1669
1670 /* Whether the 'nodes' are all movable nodes */
movable_only_nodes(nodemask_t * nodes)1671 static inline bool movable_only_nodes(nodemask_t *nodes)
1672 {
1673 struct zonelist *zonelist;
1674 struct zoneref *z;
1675 int nid;
1676
1677 if (nodes_empty(*nodes))
1678 return false;
1679
1680 /*
1681 * We can chose arbitrary node from the nodemask to get a
1682 * zonelist as they are interlinked. We just need to find
1683 * at least one zone that can satisfy kernel allocations.
1684 */
1685 nid = first_node(*nodes);
1686 zonelist = &NODE_DATA(nid)->node_zonelists[ZONELIST_FALLBACK];
1687 z = first_zones_zonelist(zonelist, ZONE_NORMAL, nodes);
1688 return (!z->zone) ? true : false;
1689 }
1690
1691
1692 #ifdef CONFIG_SPARSEMEM
1693 #include <asm/sparsemem.h>
1694 #endif
1695
1696 #ifdef CONFIG_FLATMEM
1697 #define pfn_to_nid(pfn) (0)
1698 #endif
1699
1700 #ifdef CONFIG_SPARSEMEM
1701
1702 /*
1703 * PA_SECTION_SHIFT physical address to/from section number
1704 * PFN_SECTION_SHIFT pfn to/from section number
1705 */
1706 #define PA_SECTION_SHIFT (SECTION_SIZE_BITS)
1707 #define PFN_SECTION_SHIFT (SECTION_SIZE_BITS - PAGE_SHIFT)
1708
1709 #define NR_MEM_SECTIONS (1UL << SECTIONS_SHIFT)
1710
1711 #define PAGES_PER_SECTION (1UL << PFN_SECTION_SHIFT)
1712 #define PAGE_SECTION_MASK (~(PAGES_PER_SECTION-1))
1713
1714 #define SECTION_BLOCKFLAGS_BITS \
1715 ((1UL << (PFN_SECTION_SHIFT - pageblock_order)) * NR_PAGEBLOCK_BITS)
1716
1717 #if (MAX_ORDER - 1 + PAGE_SHIFT) > SECTION_SIZE_BITS
1718 #error Allocator MAX_ORDER exceeds SECTION_SIZE
1719 #endif
1720
pfn_to_section_nr(unsigned long pfn)1721 static inline unsigned long pfn_to_section_nr(unsigned long pfn)
1722 {
1723 return pfn >> PFN_SECTION_SHIFT;
1724 }
section_nr_to_pfn(unsigned long sec)1725 static inline unsigned long section_nr_to_pfn(unsigned long sec)
1726 {
1727 return sec << PFN_SECTION_SHIFT;
1728 }
1729
1730 #define SECTION_ALIGN_UP(pfn) (((pfn) + PAGES_PER_SECTION - 1) & PAGE_SECTION_MASK)
1731 #define SECTION_ALIGN_DOWN(pfn) ((pfn) & PAGE_SECTION_MASK)
1732
1733 #define SUBSECTION_SHIFT 21
1734 #define SUBSECTION_SIZE (1UL << SUBSECTION_SHIFT)
1735
1736 #define PFN_SUBSECTION_SHIFT (SUBSECTION_SHIFT - PAGE_SHIFT)
1737 #define PAGES_PER_SUBSECTION (1UL << PFN_SUBSECTION_SHIFT)
1738 #define PAGE_SUBSECTION_MASK (~(PAGES_PER_SUBSECTION-1))
1739
1740 #if SUBSECTION_SHIFT > SECTION_SIZE_BITS
1741 #error Subsection size exceeds section size
1742 #else
1743 #define SUBSECTIONS_PER_SECTION (1UL << (SECTION_SIZE_BITS - SUBSECTION_SHIFT))
1744 #endif
1745
1746 #define SUBSECTION_ALIGN_UP(pfn) ALIGN((pfn), PAGES_PER_SUBSECTION)
1747 #define SUBSECTION_ALIGN_DOWN(pfn) ((pfn) & PAGE_SUBSECTION_MASK)
1748
1749 struct mem_section_usage {
1750 #ifdef CONFIG_SPARSEMEM_VMEMMAP
1751 DECLARE_BITMAP(subsection_map, SUBSECTIONS_PER_SECTION);
1752 #endif
1753 /* See declaration of similar field in struct zone */
1754 unsigned long pageblock_flags[0];
1755 };
1756
1757 void subsection_map_init(unsigned long pfn, unsigned long nr_pages);
1758
1759 struct page;
1760 struct page_ext;
1761 struct mem_section {
1762 /*
1763 * This is, logically, a pointer to an array of struct
1764 * pages. However, it is stored with some other magic.
1765 * (see sparse.c::sparse_init_one_section())
1766 *
1767 * Additionally during early boot we encode node id of
1768 * the location of the section here to guide allocation.
1769 * (see sparse.c::memory_present())
1770 *
1771 * Making it a UL at least makes someone do a cast
1772 * before using it wrong.
1773 */
1774 unsigned long section_mem_map;
1775
1776 struct mem_section_usage *usage;
1777 #ifdef CONFIG_PAGE_EXTENSION
1778 /*
1779 * If SPARSEMEM, pgdat doesn't have page_ext pointer. We use
1780 * section. (see page_ext.h about this.)
1781 */
1782 struct page_ext *page_ext;
1783 unsigned long pad;
1784 #endif
1785 /*
1786 * WARNING: mem_section must be a power-of-2 in size for the
1787 * calculation and use of SECTION_ROOT_MASK to make sense.
1788 */
1789 };
1790
1791 #ifdef CONFIG_SPARSEMEM_EXTREME
1792 #define SECTIONS_PER_ROOT (PAGE_SIZE / sizeof (struct mem_section))
1793 #else
1794 #define SECTIONS_PER_ROOT 1
1795 #endif
1796
1797 #define SECTION_NR_TO_ROOT(sec) ((sec) / SECTIONS_PER_ROOT)
1798 #define NR_SECTION_ROOTS DIV_ROUND_UP(NR_MEM_SECTIONS, SECTIONS_PER_ROOT)
1799 #define SECTION_ROOT_MASK (SECTIONS_PER_ROOT - 1)
1800
1801 #ifdef CONFIG_SPARSEMEM_EXTREME
1802 extern struct mem_section **mem_section;
1803 #else
1804 extern struct mem_section mem_section[NR_SECTION_ROOTS][SECTIONS_PER_ROOT];
1805 #endif
1806
section_to_usemap(struct mem_section * ms)1807 static inline unsigned long *section_to_usemap(struct mem_section *ms)
1808 {
1809 return ms->usage->pageblock_flags;
1810 }
1811
__nr_to_section(unsigned long nr)1812 static inline struct mem_section *__nr_to_section(unsigned long nr)
1813 {
1814 unsigned long root = SECTION_NR_TO_ROOT(nr);
1815
1816 if (unlikely(root >= NR_SECTION_ROOTS))
1817 return NULL;
1818
1819 #ifdef CONFIG_SPARSEMEM_EXTREME
1820 if (!mem_section || !mem_section[root])
1821 return NULL;
1822 #endif
1823 return &mem_section[root][nr & SECTION_ROOT_MASK];
1824 }
1825 extern size_t mem_section_usage_size(void);
1826
1827 /*
1828 * We use the lower bits of the mem_map pointer to store
1829 * a little bit of information. The pointer is calculated
1830 * as mem_map - section_nr_to_pfn(pnum). The result is
1831 * aligned to the minimum alignment of the two values:
1832 * 1. All mem_map arrays are page-aligned.
1833 * 2. section_nr_to_pfn() always clears PFN_SECTION_SHIFT
1834 * lowest bits. PFN_SECTION_SHIFT is arch-specific
1835 * (equal SECTION_SIZE_BITS - PAGE_SHIFT), and the
1836 * worst combination is powerpc with 256k pages,
1837 * which results in PFN_SECTION_SHIFT equal 6.
1838 * To sum it up, at least 6 bits are available on all architectures.
1839 * However, we can exceed 6 bits on some other architectures except
1840 * powerpc (e.g. 15 bits are available on x86_64, 13 bits are available
1841 * with the worst case of 64K pages on arm64) if we make sure the
1842 * exceeded bit is not applicable to powerpc.
1843 */
1844 enum {
1845 SECTION_MARKED_PRESENT_BIT,
1846 SECTION_HAS_MEM_MAP_BIT,
1847 SECTION_IS_ONLINE_BIT,
1848 SECTION_IS_EARLY_BIT,
1849 #ifdef CONFIG_ZONE_DEVICE
1850 SECTION_TAINT_ZONE_DEVICE_BIT,
1851 #endif
1852 SECTION_MAP_LAST_BIT,
1853 };
1854
1855 #define SECTION_MARKED_PRESENT BIT(SECTION_MARKED_PRESENT_BIT)
1856 #define SECTION_HAS_MEM_MAP BIT(SECTION_HAS_MEM_MAP_BIT)
1857 #define SECTION_IS_ONLINE BIT(SECTION_IS_ONLINE_BIT)
1858 #define SECTION_IS_EARLY BIT(SECTION_IS_EARLY_BIT)
1859 #ifdef CONFIG_ZONE_DEVICE
1860 #define SECTION_TAINT_ZONE_DEVICE BIT(SECTION_TAINT_ZONE_DEVICE_BIT)
1861 #endif
1862 #define SECTION_MAP_MASK (~(BIT(SECTION_MAP_LAST_BIT) - 1))
1863 #define SECTION_NID_SHIFT SECTION_MAP_LAST_BIT
1864
__section_mem_map_addr(struct mem_section * section)1865 static inline struct page *__section_mem_map_addr(struct mem_section *section)
1866 {
1867 unsigned long map = section->section_mem_map;
1868 map &= SECTION_MAP_MASK;
1869 return (struct page *)map;
1870 }
1871
present_section(struct mem_section * section)1872 static inline int present_section(struct mem_section *section)
1873 {
1874 return (section && (section->section_mem_map & SECTION_MARKED_PRESENT));
1875 }
1876
present_section_nr(unsigned long nr)1877 static inline int present_section_nr(unsigned long nr)
1878 {
1879 return present_section(__nr_to_section(nr));
1880 }
1881
valid_section(struct mem_section * section)1882 static inline int valid_section(struct mem_section *section)
1883 {
1884 return (section && (section->section_mem_map & SECTION_HAS_MEM_MAP));
1885 }
1886
early_section(struct mem_section * section)1887 static inline int early_section(struct mem_section *section)
1888 {
1889 return (section && (section->section_mem_map & SECTION_IS_EARLY));
1890 }
1891
valid_section_nr(unsigned long nr)1892 static inline int valid_section_nr(unsigned long nr)
1893 {
1894 return valid_section(__nr_to_section(nr));
1895 }
1896
online_section(struct mem_section * section)1897 static inline int online_section(struct mem_section *section)
1898 {
1899 return (section && (section->section_mem_map & SECTION_IS_ONLINE));
1900 }
1901
1902 #ifdef CONFIG_ZONE_DEVICE
online_device_section(struct mem_section * section)1903 static inline int online_device_section(struct mem_section *section)
1904 {
1905 unsigned long flags = SECTION_IS_ONLINE | SECTION_TAINT_ZONE_DEVICE;
1906
1907 return section && ((section->section_mem_map & flags) == flags);
1908 }
1909 #else
online_device_section(struct mem_section * section)1910 static inline int online_device_section(struct mem_section *section)
1911 {
1912 return 0;
1913 }
1914 #endif
1915
online_section_nr(unsigned long nr)1916 static inline int online_section_nr(unsigned long nr)
1917 {
1918 return online_section(__nr_to_section(nr));
1919 }
1920
1921 #ifdef CONFIG_MEMORY_HOTPLUG
1922 void online_mem_sections(unsigned long start_pfn, unsigned long end_pfn);
1923 void offline_mem_sections(unsigned long start_pfn, unsigned long end_pfn);
1924 #endif
1925
__pfn_to_section(unsigned long pfn)1926 static inline struct mem_section *__pfn_to_section(unsigned long pfn)
1927 {
1928 return __nr_to_section(pfn_to_section_nr(pfn));
1929 }
1930
1931 extern unsigned long __highest_present_section_nr;
1932
subsection_map_index(unsigned long pfn)1933 static inline int subsection_map_index(unsigned long pfn)
1934 {
1935 return (pfn & ~(PAGE_SECTION_MASK)) / PAGES_PER_SUBSECTION;
1936 }
1937
1938 #ifdef CONFIG_SPARSEMEM_VMEMMAP
pfn_section_valid(struct mem_section * ms,unsigned long pfn)1939 static inline int pfn_section_valid(struct mem_section *ms, unsigned long pfn)
1940 {
1941 int idx = subsection_map_index(pfn);
1942
1943 return test_bit(idx, ms->usage->subsection_map);
1944 }
1945 #else
pfn_section_valid(struct mem_section * ms,unsigned long pfn)1946 static inline int pfn_section_valid(struct mem_section *ms, unsigned long pfn)
1947 {
1948 return 1;
1949 }
1950 #endif
1951
1952 #ifndef CONFIG_HAVE_ARCH_PFN_VALID
1953 /**
1954 * pfn_valid - check if there is a valid memory map entry for a PFN
1955 * @pfn: the page frame number to check
1956 *
1957 * Check if there is a valid memory map entry aka struct page for the @pfn.
1958 * Note, that availability of the memory map entry does not imply that
1959 * there is actual usable memory at that @pfn. The struct page may
1960 * represent a hole or an unusable page frame.
1961 *
1962 * Return: 1 for PFNs that have memory map entries and 0 otherwise
1963 */
pfn_valid(unsigned long pfn)1964 static inline int pfn_valid(unsigned long pfn)
1965 {
1966 struct mem_section *ms;
1967
1968 /*
1969 * Ensure the upper PAGE_SHIFT bits are clear in the
1970 * pfn. Else it might lead to false positives when
1971 * some of the upper bits are set, but the lower bits
1972 * match a valid pfn.
1973 */
1974 if (PHYS_PFN(PFN_PHYS(pfn)) != pfn)
1975 return 0;
1976
1977 if (pfn_to_section_nr(pfn) >= NR_MEM_SECTIONS)
1978 return 0;
1979 ms = __pfn_to_section(pfn);
1980 if (!valid_section(ms))
1981 return 0;
1982 /*
1983 * Traditionally early sections always returned pfn_valid() for
1984 * the entire section-sized span.
1985 */
1986 return early_section(ms) || pfn_section_valid(ms, pfn);
1987 }
1988 #endif
1989
pfn_in_present_section(unsigned long pfn)1990 static inline int pfn_in_present_section(unsigned long pfn)
1991 {
1992 if (pfn_to_section_nr(pfn) >= NR_MEM_SECTIONS)
1993 return 0;
1994 return present_section(__pfn_to_section(pfn));
1995 }
1996
next_present_section_nr(unsigned long section_nr)1997 static inline unsigned long next_present_section_nr(unsigned long section_nr)
1998 {
1999 while (++section_nr <= __highest_present_section_nr) {
2000 if (present_section_nr(section_nr))
2001 return section_nr;
2002 }
2003
2004 return -1;
2005 }
2006
2007 /*
2008 * These are _only_ used during initialisation, therefore they
2009 * can use __initdata ... They could have names to indicate
2010 * this restriction.
2011 */
2012 #ifdef CONFIG_NUMA
2013 #define pfn_to_nid(pfn) \
2014 ({ \
2015 unsigned long __pfn_to_nid_pfn = (pfn); \
2016 page_to_nid(pfn_to_page(__pfn_to_nid_pfn)); \
2017 })
2018 #else
2019 #define pfn_to_nid(pfn) (0)
2020 #endif
2021
2022 void sparse_init(void);
2023 #else
2024 #define sparse_init() do {} while (0)
2025 #define sparse_index_init(_sec, _nid) do {} while (0)
2026 #define pfn_in_present_section pfn_valid
2027 #define subsection_map_init(_pfn, _nr_pages) do {} while (0)
2028 #endif /* CONFIG_SPARSEMEM */
2029
2030 #endif /* !__GENERATING_BOUNDS.H */
2031 #endif /* !__ASSEMBLY__ */
2032 #endif /* _LINUX_MMZONE_H */
2033