xref: /linux/mm/damon/vaddr.c (revision 7db28abbea0f7dc1ec4fdfdc149db5fbd9e4c994)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * DAMON Code for Virtual Address Spaces
4  */
5 
6 #define pr_fmt(fmt) "damon-va: " fmt
7 
8 #include <linux/highmem.h>
9 #include <linux/hugetlb.h>
10 #include <linux/mman.h>
11 #include <linux/mmu_notifier.h>
12 #include <linux/page_idle.h>
13 #include <linux/pagemap.h>
14 #include <linux/pagewalk.h>
15 #include <linux/sched/mm.h>
16 
17 #include "../internal.h"
18 #include "ops-common.h"
19 
20 #ifdef CONFIG_DAMON_VADDR_KUNIT_TEST
21 #undef DAMON_MIN_REGION_SZ
22 #define DAMON_MIN_REGION_SZ 1
23 #endif
24 
25 /*
26  * 't->pid' should be the pointer to the relevant 'struct pid' having reference
27  * count.  Caller must put the returned task, unless it is NULL.
28  */
29 static inline struct task_struct *damon_get_task_struct(struct damon_target *t)
30 {
31 	return get_pid_task(t->pid, PIDTYPE_PID);
32 }
33 
34 /*
35  * Get the mm_struct of the given target
36  *
37  * Caller _must_ put the mm_struct after use, unless it is NULL.
38  *
39  * Returns the mm_struct of the target on success, NULL on failure
40  */
41 static struct mm_struct *damon_get_mm(struct damon_target *t)
42 {
43 	struct task_struct *task;
44 	struct mm_struct *mm;
45 
46 	task = damon_get_task_struct(t);
47 	if (!task)
48 		return NULL;
49 
50 	mm = get_task_mm(task);
51 	put_task_struct(task);
52 	return mm;
53 }
54 
55 static unsigned long sz_range(struct damon_addr_range *r)
56 {
57 	return r->end - r->start;
58 }
59 
60 /*
61  * Find three regions separated by two biggest unmapped regions
62  *
63  * vma		the head vma of the target address space
64  * regions	an array of three address ranges that results will be saved
65  *
66  * This function receives an address space and finds three regions in it which
67  * separated by the two biggest unmapped regions in the space.  Please refer to
68  * below comments of '__damon_va_init_regions()' function to know why this is
69  * necessary.
70  *
71  * Returns 0 if success, or negative error code otherwise.
72  */
73 static int __damon_va_three_regions(struct mm_struct *mm,
74 				       struct damon_addr_range regions[3])
75 {
76 	struct damon_addr_range first_gap = {0}, second_gap = {0};
77 	VMA_ITERATOR(vmi, mm, 0);
78 	struct vm_area_struct *vma, *prev = NULL;
79 	unsigned long start;
80 
81 	/*
82 	 * Find the two biggest gaps so that first_gap > second_gap > others.
83 	 * If this is too slow, it can be optimised to examine the maple
84 	 * tree gaps.
85 	 */
86 	rcu_read_lock();
87 	for_each_vma(vmi, vma) {
88 		unsigned long gap;
89 
90 		if (!prev) {
91 			start = vma->vm_start;
92 			goto next;
93 		}
94 		gap = vma->vm_start - prev->vm_end;
95 
96 		if (gap > sz_range(&first_gap)) {
97 			second_gap = first_gap;
98 			first_gap.start = prev->vm_end;
99 			first_gap.end = vma->vm_start;
100 		} else if (gap > sz_range(&second_gap)) {
101 			second_gap.start = prev->vm_end;
102 			second_gap.end = vma->vm_start;
103 		}
104 next:
105 		prev = vma;
106 	}
107 	rcu_read_unlock();
108 
109 	if (!sz_range(&second_gap) || !sz_range(&first_gap))
110 		return -EINVAL;
111 
112 	/* Sort the two biggest gaps by address */
113 	if (first_gap.start > second_gap.start)
114 		swap(first_gap, second_gap);
115 
116 	/* Store the result */
117 	regions[0].start = ALIGN(start, DAMON_MIN_REGION_SZ);
118 	regions[0].end = ALIGN(first_gap.start, DAMON_MIN_REGION_SZ);
119 	regions[1].start = ALIGN(first_gap.end, DAMON_MIN_REGION_SZ);
120 	regions[1].end = ALIGN(second_gap.start, DAMON_MIN_REGION_SZ);
121 	regions[2].start = ALIGN(second_gap.end, DAMON_MIN_REGION_SZ);
122 	regions[2].end = ALIGN(prev->vm_end, DAMON_MIN_REGION_SZ);
123 
124 	return 0;
125 }
126 
127 /*
128  * Get the three regions in the given target (task)
129  *
130  * Returns 0 on success, negative error code otherwise.
131  */
132 static int damon_va_three_regions(struct damon_target *t,
133 				struct damon_addr_range regions[3])
134 {
135 	struct mm_struct *mm;
136 	int rc;
137 
138 	mm = damon_get_mm(t);
139 	if (!mm)
140 		return -EINVAL;
141 
142 	mmap_read_lock(mm);
143 	rc = __damon_va_three_regions(mm, regions);
144 	mmap_read_unlock(mm);
145 
146 	mmput(mm);
147 	return rc;
148 }
149 
150 /*
151  * Initialize the monitoring target regions for the given target (task)
152  *
153  * t	the given target
154  *
155  * Because only a number of small portions of the entire address space
156  * is actually mapped to the memory and accessed, monitoring the unmapped
157  * regions is wasteful.  That said, because we can deal with small noises,
158  * tracking every mapping is not strictly required but could even incur a high
159  * overhead if the mapping frequently changes or the number of mappings is
160  * high.  The adaptive regions adjustment mechanism will further help to deal
161  * with the noise by simply identifying the unmapped areas as a region that
162  * has no access.  Moreover, applying the real mappings that would have many
163  * unmapped areas inside will make the adaptive mechanism quite complex.  That
164  * said, too huge unmapped areas inside the monitoring target should be removed
165  * to not take the time for the adaptive mechanism.
166  *
167  * For the reason, we convert the complex mappings to three distinct regions
168  * that cover every mapped area of the address space.  Also the two gaps
169  * between the three regions are the two biggest unmapped areas in the given
170  * address space.  In detail, this function first identifies the start and the
171  * end of the mappings and the two biggest unmapped areas of the address space.
172  * Then, it constructs the three regions as below:
173  *
174  *     [mappings[0]->start, big_two_unmapped_areas[0]->start)
175  *     [big_two_unmapped_areas[0]->end, big_two_unmapped_areas[1]->start)
176  *     [big_two_unmapped_areas[1]->end, mappings[nr_mappings - 1]->end)
177  *
178  * As usual memory map of processes is as below, the gap between the heap and
179  * the uppermost mmap()-ed region, and the gap between the lowermost mmap()-ed
180  * region and the stack will be two biggest unmapped regions.  Because these
181  * gaps are exceptionally huge areas in usual address space, excluding these
182  * two biggest unmapped regions will be sufficient to make a trade-off.
183  *
184  *   <heap>
185  *   <BIG UNMAPPED REGION 1>
186  *   <uppermost mmap()-ed region>
187  *   (other mmap()-ed regions and small unmapped regions)
188  *   <lowermost mmap()-ed region>
189  *   <BIG UNMAPPED REGION 2>
190  *   <stack>
191  */
192 static void __damon_va_init_regions(struct damon_ctx *ctx,
193 				     struct damon_target *t)
194 {
195 	struct damon_target *ti;
196 	struct damon_addr_range regions[3];
197 	int tidx = 0;
198 
199 	if (damon_va_three_regions(t, regions)) {
200 		damon_for_each_target(ti, ctx) {
201 			if (ti == t)
202 				break;
203 			tidx++;
204 		}
205 		pr_debug("Failed to get three regions of %dth target\n", tidx);
206 		return;
207 	}
208 
209 	damon_set_regions(t, regions, 3, DAMON_MIN_REGION_SZ);
210 }
211 
212 /* Initialize '->regions_list' of every target (task) */
213 static void damon_va_init(struct damon_ctx *ctx)
214 {
215 	struct damon_target *t;
216 
217 	damon_for_each_target(t, ctx) {
218 		/* the user may set the target regions as they want */
219 		if (!damon_nr_regions(t))
220 			__damon_va_init_regions(ctx, t);
221 	}
222 }
223 
224 /*
225  * Update regions for current memory mappings
226  */
227 static void damon_va_update(struct damon_ctx *ctx)
228 {
229 	struct damon_addr_range three_regions[3];
230 	struct damon_target *t;
231 
232 	damon_for_each_target(t, ctx) {
233 		if (damon_va_three_regions(t, three_regions))
234 			continue;
235 		damon_set_regions(t, three_regions, 3, DAMON_MIN_REGION_SZ);
236 	}
237 }
238 
239 static void damon_va_walk_page_range(struct mm_struct *mm, unsigned long start,
240 		unsigned long end, struct mm_walk_ops *ops, void *private)
241 {
242 	struct vm_area_struct *vma;
243 
244 	vma = lock_vma_under_rcu(mm, start);
245 	if (!vma)
246 		goto lock_mmap;
247 
248 	if (end > vma->vm_end) {
249 		vma_end_read(vma);
250 		goto lock_mmap;
251 	}
252 
253 	if (!(vma->vm_flags & VM_PFNMAP)) {
254 		ops->walk_lock = PGWALK_VMA_RDLOCK_VERIFY;
255 		walk_page_range_vma(vma, start, end, ops, private);
256 	}
257 
258 	vma_end_read(vma);
259 	return;
260 
261 lock_mmap:
262 	mmap_read_lock(mm);
263 	ops->walk_lock = PGWALK_RDLOCK;
264 	walk_page_range(mm, start, end, ops, private);
265 	mmap_read_unlock(mm);
266 }
267 
268 static int damon_mkold_pmd_entry(pmd_t *pmd, unsigned long addr,
269 		unsigned long next, struct mm_walk *walk)
270 {
271 	pte_t *pte;
272 	spinlock_t *ptl;
273 
274 	ptl = pmd_trans_huge_lock(pmd, walk->vma);
275 	if (ptl) {
276 		pmd_t pmde = pmdp_get(pmd);
277 
278 		if (pmd_present(pmde))
279 			damon_pmdp_mkold(pmd, walk->vma, addr);
280 		spin_unlock(ptl);
281 		return 0;
282 	}
283 
284 	pte = pte_offset_map_lock(walk->mm, pmd, addr, &ptl);
285 	if (!pte)
286 		return 0;
287 	if (!pte_present(ptep_get(pte)))
288 		goto out;
289 	damon_ptep_mkold(pte, walk->vma, addr);
290 out:
291 	pte_unmap_unlock(pte, ptl);
292 	return 0;
293 }
294 
295 #ifdef CONFIG_HUGETLB_PAGE
296 static void damon_hugetlb_mkold(pte_t *pte, struct mm_struct *mm,
297 				struct vm_area_struct *vma, unsigned long addr)
298 {
299 	bool referenced = false;
300 	pte_t entry = huge_ptep_get(mm, addr, pte);
301 	struct folio *folio = pfn_folio(pte_pfn(entry));
302 	unsigned long psize = huge_page_size(hstate_vma(vma));
303 
304 	folio_get(folio);
305 
306 	if (pte_young(entry)) {
307 		referenced = true;
308 		entry = pte_mkold(entry);
309 		set_huge_pte_at(mm, addr, pte, entry, psize);
310 	}
311 
312 	if (mmu_notifier_clear_young(mm, addr,
313 				     addr + huge_page_size(hstate_vma(vma))))
314 		referenced = true;
315 
316 	if (referenced)
317 		folio_set_young(folio);
318 
319 	folio_set_idle(folio);
320 	folio_put(folio);
321 }
322 
323 static int damon_mkold_hugetlb_entry(pte_t *pte, unsigned long hmask,
324 				     unsigned long addr, unsigned long end,
325 				     struct mm_walk *walk)
326 {
327 	struct hstate *h = hstate_vma(walk->vma);
328 	spinlock_t *ptl;
329 	pte_t entry;
330 
331 	ptl = huge_pte_lock(h, walk->mm, pte);
332 	entry = huge_ptep_get(walk->mm, addr, pte);
333 	if (!pte_present(entry))
334 		goto out;
335 
336 	damon_hugetlb_mkold(pte, walk->mm, walk->vma, addr);
337 
338 out:
339 	spin_unlock(ptl);
340 	return 0;
341 }
342 #else
343 #define damon_mkold_hugetlb_entry NULL
344 #endif /* CONFIG_HUGETLB_PAGE */
345 
346 static void damon_va_mkold(struct mm_struct *mm, unsigned long addr)
347 {
348 	struct mm_walk_ops damon_mkold_ops = {
349 		.pmd_entry = damon_mkold_pmd_entry,
350 		.hugetlb_entry = damon_mkold_hugetlb_entry,
351 	};
352 
353 	damon_va_walk_page_range(mm, addr, addr + 1, &damon_mkold_ops, NULL);
354 }
355 
356 /*
357  * Functions for the access checking of the regions
358  */
359 
360 static void __damon_va_prepare_access_check(struct mm_struct *mm,
361 					struct damon_region *r,
362 					struct damon_ctx *ctx)
363 {
364 	r->sampling_addr = damon_rand(ctx, r->ar.start, r->ar.end);
365 
366 	damon_va_mkold(mm, r->sampling_addr);
367 }
368 
369 static void damon_va_prepare_access_checks(struct damon_ctx *ctx)
370 {
371 	struct damon_target *t;
372 	struct mm_struct *mm;
373 	struct damon_region *r;
374 
375 	damon_for_each_target(t, ctx) {
376 		mm = damon_get_mm(t);
377 		if (!mm)
378 			continue;
379 		damon_for_each_region(r, t)
380 			__damon_va_prepare_access_check(mm, r, ctx);
381 		mmput(mm);
382 	}
383 }
384 
385 struct damon_young_walk_private {
386 	bool young;
387 };
388 
389 static int damon_young_pmd_entry(pmd_t *pmd, unsigned long addr,
390 		unsigned long next, struct mm_walk *walk)
391 {
392 	pte_t *pte;
393 	pte_t ptent;
394 	spinlock_t *ptl;
395 	struct folio *folio;
396 	struct damon_young_walk_private *priv = walk->private;
397 
398 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
399 	ptl = pmd_trans_huge_lock(pmd, walk->vma);
400 	if (ptl) {
401 		pmd_t pmde = pmdp_get(pmd);
402 
403 		if (!pmd_present(pmde))
404 			goto huge_out;
405 		folio = vm_normal_folio_pmd(walk->vma, addr, pmde);
406 		if (!folio)
407 			goto huge_out;
408 		if (pmd_young(pmde) || !folio_test_idle(folio) ||
409 					mmu_notifier_test_young(walk->mm,
410 						addr))
411 			priv->young = true;
412 huge_out:
413 		spin_unlock(ptl);
414 		return 0;
415 	}
416 #endif	/* CONFIG_TRANSPARENT_HUGEPAGE */
417 
418 	pte = pte_offset_map_lock(walk->mm, pmd, addr, &ptl);
419 	if (!pte)
420 		return 0;
421 	ptent = ptep_get(pte);
422 	if (!pte_present(ptent))
423 		goto out;
424 	folio = vm_normal_folio(walk->vma, addr, ptent);
425 	if (!folio)
426 		goto out;
427 	if (pte_young(ptent) || !folio_test_idle(folio) ||
428 			mmu_notifier_test_young(walk->mm, addr))
429 		priv->young = true;
430 out:
431 	pte_unmap_unlock(pte, ptl);
432 	return 0;
433 }
434 
435 #ifdef CONFIG_HUGETLB_PAGE
436 static int damon_young_hugetlb_entry(pte_t *pte, unsigned long hmask,
437 				     unsigned long addr, unsigned long end,
438 				     struct mm_walk *walk)
439 {
440 	struct damon_young_walk_private *priv = walk->private;
441 	struct hstate *h = hstate_vma(walk->vma);
442 	struct folio *folio;
443 	spinlock_t *ptl;
444 	pte_t entry;
445 
446 	ptl = huge_pte_lock(h, walk->mm, pte);
447 	entry = huge_ptep_get(walk->mm, addr, pte);
448 	if (!pte_present(entry))
449 		goto out;
450 
451 	folio = pfn_folio(pte_pfn(entry));
452 	folio_get(folio);
453 
454 	if (pte_young(entry) || !folio_test_idle(folio) ||
455 	    mmu_notifier_test_young(walk->mm, addr))
456 		priv->young = true;
457 
458 	folio_put(folio);
459 
460 out:
461 	spin_unlock(ptl);
462 	return 0;
463 }
464 #else
465 #define damon_young_hugetlb_entry NULL
466 #endif /* CONFIG_HUGETLB_PAGE */
467 
468 static bool damon_va_young(struct mm_struct *mm, unsigned long addr)
469 {
470 	struct damon_young_walk_private arg = {
471 		.young = false,
472 	};
473 
474 	struct mm_walk_ops damon_young_ops = {
475 		.pmd_entry = damon_young_pmd_entry,
476 		.hugetlb_entry = damon_young_hugetlb_entry,
477 	};
478 
479 	damon_va_walk_page_range(mm, addr, addr + 1, &damon_young_ops, &arg);
480 	return arg.young;
481 }
482 
483 /*
484  * Check whether the region was accessed after the last preparation
485  *
486  * mm	'mm_struct' for the given virtual address space
487  * r	the region to be checked
488  */
489 static void __damon_va_check_access(struct mm_struct *mm,
490 				struct damon_region *r)
491 {
492 	bool accessed;
493 
494 	if (!mm) {
495 		damon_update_region_access_rate(r, false);
496 		return;
497 	}
498 
499 	accessed = damon_va_young(mm, r->sampling_addr);
500 	damon_update_region_access_rate(r, accessed);
501 }
502 
503 static unsigned int damon_va_check_accesses(struct damon_ctx *ctx)
504 {
505 	struct damon_target *t;
506 	struct mm_struct *mm;
507 	struct damon_region *r;
508 	unsigned int max_nr_accesses = 0;
509 
510 	damon_for_each_target(t, ctx) {
511 		mm = damon_get_mm(t);
512 		damon_for_each_region(r, t) {
513 			__damon_va_check_access(mm, r);
514 			max_nr_accesses = max(r->nr_accesses, max_nr_accesses);
515 		}
516 		if (mm)
517 			mmput(mm);
518 	}
519 
520 	return max_nr_accesses;
521 }
522 
523 static bool damos_va_filter_young_match(struct damos_filter *filter,
524 		struct folio *folio, struct vm_area_struct *vma,
525 		unsigned long addr, pte_t *ptep, pmd_t *pmdp)
526 {
527 	bool young = false;
528 
529 	if (ptep)
530 		young = pte_young(ptep_get(ptep));
531 	else if (pmdp)
532 		young = pmd_young(pmdp_get(pmdp));
533 
534 	young = young || !folio_test_idle(folio) ||
535 		mmu_notifier_test_young(vma->vm_mm, addr);
536 
537 	if (young && ptep)
538 		damon_ptep_mkold(ptep, vma, addr);
539 	else if (young && pmdp)
540 		damon_pmdp_mkold(pmdp, vma, addr);
541 
542 	return young == filter->matching;
543 }
544 
545 static bool damos_va_filter_out(struct damos *scheme, struct folio *folio,
546 		struct vm_area_struct *vma, unsigned long addr,
547 		pte_t *ptep, pmd_t *pmdp)
548 {
549 	struct damos_filter *filter;
550 	bool matched;
551 
552 	if (scheme->core_filters_allowed)
553 		return false;
554 
555 	damos_for_each_ops_filter(filter, scheme) {
556 		/*
557 		 * damos_folio_filter_match checks the young filter by doing an
558 		 * rmap on the folio to find its page table. However, being the
559 		 * vaddr scheme, we have direct access to the page tables, so
560 		 * use that instead.
561 		 */
562 		if (filter->type == DAMOS_FILTER_TYPE_YOUNG)
563 			matched = damos_va_filter_young_match(filter, folio,
564 				vma, addr, ptep, pmdp);
565 		else
566 			matched = damos_folio_filter_match(filter, folio);
567 
568 		if (matched)
569 			return !filter->allow;
570 	}
571 	return scheme->ops_filters_default_reject;
572 }
573 
574 struct damos_va_migrate_private {
575 	struct list_head *migration_lists;
576 	struct damos *scheme;
577 };
578 
579 /*
580  * Place the given folio in the migration_list corresponding to where the folio
581  * should be migrated.
582  *
583  * The algorithm used here is similar to weighted_interleave_nid()
584  */
585 static void damos_va_migrate_dests_add(struct folio *folio,
586 		struct vm_area_struct *vma, unsigned long addr,
587 		struct damos_migrate_dests *dests,
588 		struct list_head *migration_lists)
589 {
590 	pgoff_t ilx;
591 	int order;
592 	unsigned int target;
593 	unsigned int weight_total = 0;
594 	int i;
595 
596 	/*
597 	 * If dests is empty, there is only one migration list corresponding
598 	 * to s->target_nid.
599 	 */
600 	if (!dests->nr_dests) {
601 		i = 0;
602 		goto isolate;
603 	}
604 
605 	order = folio_order(folio);
606 	ilx = vma_start_pgoff(vma) >> order;
607 	ilx += linear_page_delta(vma, addr) >> order;
608 
609 	for (i = 0; i < dests->nr_dests; i++)
610 		weight_total += dests->weight_arr[i];
611 
612 	/* If the total weights are somehow 0, don't migrate at all */
613 	if (!weight_total)
614 		return;
615 
616 	target = ilx % weight_total;
617 	for (i = 0; i < dests->nr_dests; i++) {
618 		if (target < dests->weight_arr[i])
619 			break;
620 		target -= dests->weight_arr[i];
621 	}
622 
623 	/* If the folio is already in the right node, don't do anything */
624 	if (folio_nid(folio) == dests->node_id_arr[i])
625 		return;
626 
627 isolate:
628 	if (!folio_isolate_lru(folio))
629 		return;
630 	node_stat_add_folio(folio, NR_ISOLATED_ANON +
631 			folio_is_file_lru(folio));
632 	list_add(&folio->lru, &migration_lists[i]);
633 }
634 
635 static int damos_va_migrate_pmd_entry(pmd_t *pmd, unsigned long addr,
636 		unsigned long next, struct mm_walk *walk)
637 {
638 	struct damos_va_migrate_private *priv = walk->private;
639 	struct list_head *migration_lists = priv->migration_lists;
640 	struct damos *s = priv->scheme;
641 	struct damos_migrate_dests *dests = &s->migrate_dests;
642 	struct folio *folio;
643 	spinlock_t *ptl;
644 	pte_t *start_pte, *pte, ptent;
645 	int nr;
646 
647 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
648 	ptl = pmd_trans_huge_lock(pmd, walk->vma);
649 	if (ptl) {
650 		pmd_t pmde = pmdp_get(pmd);
651 
652 		if (!pmd_present(pmde))
653 			goto huge_out;
654 		folio = vm_normal_folio_pmd(walk->vma, addr, pmde);
655 		if (!folio)
656 			goto huge_out;
657 		if (damos_va_filter_out(s, folio, walk->vma, addr, NULL, pmd))
658 			goto huge_out;
659 		damos_va_migrate_dests_add(folio, walk->vma, addr, dests,
660 				migration_lists);
661 huge_out:
662 		spin_unlock(ptl);
663 		return 0;
664 	}
665 #endif	/* CONFIG_TRANSPARENT_HUGEPAGE */
666 
667 	start_pte = pte = pte_offset_map_lock(walk->mm, pmd, addr, &ptl);
668 	if (!pte)
669 		return 0;
670 
671 	for (; addr < next; pte += nr, addr += nr * PAGE_SIZE) {
672 		nr = 1;
673 		ptent = ptep_get(pte);
674 
675 		if (pte_none(ptent) || !pte_present(ptent))
676 			continue;
677 		folio = vm_normal_folio(walk->vma, addr, ptent);
678 		if (!folio)
679 			continue;
680 		if (damos_va_filter_out(s, folio, walk->vma, addr, pte, NULL))
681 			continue;
682 		damos_va_migrate_dests_add(folio, walk->vma, addr, dests,
683 				migration_lists);
684 		nr = folio_nr_pages(folio);
685 	}
686 	pte_unmap_unlock(start_pte, ptl);
687 	return 0;
688 }
689 
690 /*
691  * Functions for the target validity check and cleanup
692  */
693 
694 static bool damon_va_target_valid(struct damon_target *t)
695 {
696 	struct task_struct *task;
697 
698 	task = damon_get_task_struct(t);
699 	if (task) {
700 		put_task_struct(task);
701 		return true;
702 	}
703 
704 	return false;
705 }
706 
707 static void damon_va_cleanup_target(struct damon_target *t)
708 {
709 	put_pid(t->pid);
710 }
711 
712 #ifndef CONFIG_ADVISE_SYSCALLS
713 static unsigned long damos_madvise(struct damon_target *target,
714 		struct damon_region *r, int behavior)
715 {
716 	return 0;
717 }
718 #else
719 static unsigned long damos_madvise(struct damon_target *target,
720 		struct damon_region *r, int behavior)
721 {
722 	struct mm_struct *mm;
723 	unsigned long start = PAGE_ALIGN(r->ar.start);
724 	unsigned long len = PAGE_ALIGN(damon_sz_region(r));
725 	unsigned long applied;
726 
727 	mm = damon_get_mm(target);
728 	if (!mm)
729 		return 0;
730 
731 	applied = do_madvise(mm, start, len, behavior) ? 0 : len;
732 	mmput(mm);
733 
734 	return applied;
735 }
736 #endif	/* CONFIG_ADVISE_SYSCALLS */
737 
738 static unsigned long damos_va_migrate(struct damon_target *target,
739 		struct damon_region *r, struct damos *s,
740 		unsigned long *sz_filter_passed)
741 {
742 	LIST_HEAD(folio_list);
743 	struct damos_va_migrate_private priv;
744 	struct mm_struct *mm;
745 	int nr_dests;
746 	int nid;
747 	bool use_target_nid;
748 	unsigned long applied = 0;
749 	struct damos_migrate_dests *dests = &s->migrate_dests;
750 	struct mm_walk_ops walk_ops = {
751 		.pmd_entry = damos_va_migrate_pmd_entry,
752 		.pte_entry = NULL,
753 	};
754 
755 	use_target_nid = dests->nr_dests == 0;
756 	nr_dests = use_target_nid ? 1 : dests->nr_dests;
757 	priv.scheme = s;
758 	priv.migration_lists = kmalloc_objs(*priv.migration_lists, nr_dests);
759 	if (!priv.migration_lists)
760 		return 0;
761 
762 	for (int i = 0; i < nr_dests; i++)
763 		INIT_LIST_HEAD(&priv.migration_lists[i]);
764 
765 
766 	mm = damon_get_mm(target);
767 	if (!mm)
768 		goto free_lists;
769 
770 	damon_va_walk_page_range(mm, r->ar.start, r->ar.end, &walk_ops, &priv);
771 	mmput(mm);
772 
773 	for (int i = 0; i < nr_dests; i++) {
774 		nid = use_target_nid ? s->target_nid : dests->node_id_arr[i];
775 		applied += damon_migrate_pages(&priv.migration_lists[i], nid);
776 		cond_resched();
777 	}
778 
779 free_lists:
780 	kfree(priv.migration_lists);
781 	return applied * PAGE_SIZE;
782 }
783 
784 struct damos_va_stat_private {
785 	struct damos *scheme;
786 	unsigned long *sz_filter_passed;
787 };
788 
789 static inline bool damos_va_invalid_folio(struct folio *folio,
790 		struct damos *s)
791 {
792 	return !folio || folio == s->last_applied;
793 }
794 
795 static int damos_va_stat_pmd_entry(pmd_t *pmd, unsigned long addr,
796 		unsigned long next, struct mm_walk *walk)
797 {
798 	struct damos_va_stat_private *priv = walk->private;
799 	struct damos *s = priv->scheme;
800 	unsigned long *sz_filter_passed = priv->sz_filter_passed;
801 	struct vm_area_struct *vma = walk->vma;
802 	struct folio *folio;
803 	spinlock_t *ptl;
804 	pte_t *start_pte, *pte, ptent;
805 	int nr;
806 
807 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
808 	ptl = pmd_trans_huge_lock(pmd, vma);
809 	if (ptl) {
810 		pmd_t pmde = pmdp_get(pmd);
811 
812 		if (!pmd_present(pmde))
813 			goto huge_unlock;
814 
815 		folio = vm_normal_folio_pmd(vma, addr, pmde);
816 
817 		if (damos_va_invalid_folio(folio, s))
818 			goto huge_unlock;
819 
820 		if (!damos_va_filter_out(s, folio, vma, addr, NULL, pmd))
821 			*sz_filter_passed += folio_size(folio);
822 		s->last_applied = folio;
823 
824 huge_unlock:
825 		spin_unlock(ptl);
826 		return 0;
827 	}
828 #endif
829 	start_pte = pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
830 	if (!start_pte)
831 		return 0;
832 
833 	for (; addr < next; pte += nr, addr += nr * PAGE_SIZE) {
834 		nr = 1;
835 		ptent = ptep_get(pte);
836 
837 		if (pte_none(ptent) || !pte_present(ptent))
838 			continue;
839 
840 		folio = vm_normal_folio(vma, addr, ptent);
841 
842 		if (damos_va_invalid_folio(folio, s))
843 			continue;
844 
845 		if (!damos_va_filter_out(s, folio, vma, addr, pte, NULL))
846 			*sz_filter_passed += folio_size(folio);
847 		nr = folio_nr_pages(folio);
848 		s->last_applied = folio;
849 	}
850 	pte_unmap_unlock(start_pte, ptl);
851 	return 0;
852 }
853 
854 static unsigned long damos_va_stat(struct damon_target *target,
855 		struct damon_region *r, struct damos *s,
856 		unsigned long *sz_filter_passed)
857 {
858 	struct damos_va_stat_private priv;
859 	struct mm_struct *mm;
860 	struct mm_walk_ops walk_ops = {
861 		.pmd_entry = damos_va_stat_pmd_entry,
862 	};
863 
864 	priv.scheme = s;
865 	priv.sz_filter_passed = sz_filter_passed;
866 
867 	if (!damos_ops_has_filter(s))
868 		return 0;
869 
870 	mm = damon_get_mm(target);
871 	if (!mm)
872 		return 0;
873 
874 	damon_va_walk_page_range(mm, r->ar.start, r->ar.end, &walk_ops, &priv);
875 	mmput(mm);
876 	return 0;
877 }
878 
879 static unsigned long damon_va_apply_scheme(struct damon_ctx *ctx,
880 		struct damon_target *t, struct damon_region *r,
881 		struct damos *scheme, unsigned long *sz_filter_passed)
882 {
883 	int madv_action;
884 
885 	switch (scheme->action) {
886 	case DAMOS_WILLNEED:
887 		madv_action = MADV_WILLNEED;
888 		break;
889 	case DAMOS_COLD:
890 		madv_action = MADV_COLD;
891 		break;
892 	case DAMOS_PAGEOUT:
893 		madv_action = MADV_PAGEOUT;
894 		break;
895 	case DAMOS_HUGEPAGE:
896 		madv_action = MADV_HUGEPAGE;
897 		break;
898 	case DAMOS_NOHUGEPAGE:
899 		madv_action = MADV_NOHUGEPAGE;
900 		break;
901 	case DAMOS_COLLAPSE:
902 		madv_action = MADV_COLLAPSE;
903 		break;
904 	case DAMOS_MIGRATE_HOT:
905 	case DAMOS_MIGRATE_COLD:
906 		return damos_va_migrate(t, r, scheme, sz_filter_passed);
907 	case DAMOS_STAT:
908 		return damos_va_stat(t, r, scheme, sz_filter_passed);
909 	default:
910 		/*
911 		 * DAMOS actions that are not yet supported by 'vaddr'.
912 		 */
913 		return 0;
914 	}
915 
916 	return damos_madvise(t, r, madv_action);
917 }
918 
919 static int damon_va_scheme_score(struct damon_ctx *context,
920 		struct damon_region *r, struct damos *scheme)
921 {
922 
923 	switch (scheme->action) {
924 	case DAMOS_PAGEOUT:
925 		return damon_cold_score(context, r, scheme);
926 	case DAMOS_MIGRATE_HOT:
927 		return damon_hot_score(context, r, scheme);
928 	case DAMOS_MIGRATE_COLD:
929 		return damon_cold_score(context, r, scheme);
930 	default:
931 		break;
932 	}
933 
934 	return DAMOS_MAX_SCORE;
935 }
936 
937 static int __init damon_va_initcall(void)
938 {
939 	struct damon_operations ops = {
940 		.id = DAMON_OPS_VADDR,
941 		.init = damon_va_init,
942 		.update = damon_va_update,
943 		.prepare_access_checks = damon_va_prepare_access_checks,
944 		.check_accesses = damon_va_check_accesses,
945 		.target_valid = damon_va_target_valid,
946 		.cleanup_target = damon_va_cleanup_target,
947 		.apply_scheme = damon_va_apply_scheme,
948 		.get_scheme_score = damon_va_scheme_score,
949 	};
950 	/* ops for fixed virtual address ranges */
951 	struct damon_operations ops_fvaddr = ops;
952 	int err;
953 
954 	/* Don't set the monitoring target regions for the entire mapping */
955 	ops_fvaddr.id = DAMON_OPS_FVADDR;
956 	ops_fvaddr.init = NULL;
957 	ops_fvaddr.update = NULL;
958 
959 	err = damon_register_ops(&ops);
960 	if (err)
961 		return err;
962 	return damon_register_ops(&ops_fvaddr);
963 }
964 
965 subsys_initcall(damon_va_initcall);
966 
967 #include "tests/vaddr-kunit.h"
968