summaryrefslogtreecommitdiff
path: root/mm/damon/vaddr.c
blob: 9a38dc89a156efd44b5d4e5a9bb1110f324e5dec (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
// SPDX-License-Identifier: GPL-2.0
/*
 * DAMON Code for Virtual Address Spaces
 */

#define pr_fmt(fmt) "damon-va: " fmt

#include <linux/highmem.h>
#include <linux/hugetlb.h>
#include <linux/mman.h>
#include <linux/mmu_notifier.h>
#include <linux/page_idle.h>
#include <linux/pagemap.h>
#include <linux/pagewalk.h>
#include <linux/sched/mm.h>

#include "../internal.h"
#include "ops-common.h"

#ifdef CONFIG_DAMON_VADDR_KUNIT_TEST
#undef DAMON_MIN_REGION_SZ
#define DAMON_MIN_REGION_SZ 1
#endif

/*
 * 't->pid' should be the pointer to the relevant 'struct pid' having reference
 * count.  Caller must put the returned task, unless it is NULL.
 */
static inline struct task_struct *damon_get_task_struct(struct damon_target *t)
{
	return get_pid_task(t->pid, PIDTYPE_PID);
}

/*
 * Get the mm_struct of the given target
 *
 * Caller _must_ put the mm_struct after use, unless it is NULL.
 *
 * Returns the mm_struct of the target on success, NULL on failure
 */
static struct mm_struct *damon_get_mm(struct damon_target *t)
{
	struct task_struct *task;
	struct mm_struct *mm;

	task = damon_get_task_struct(t);
	if (!task)
		return NULL;

	mm = get_task_mm(task);
	put_task_struct(task);
	return mm;
}

static unsigned long sz_range(struct damon_addr_range *r)
{
	return r->end - r->start;
}

/*
 * Find three regions separated by two biggest unmapped regions
 *
 * vma		the head vma of the target address space
 * regions	an array of three address ranges that results will be saved
 *
 * This function receives an address space and finds three regions in it which
 * separated by the two biggest unmapped regions in the space.  Please refer to
 * below comments of '__damon_va_init_regions()' function to know why this is
 * necessary.
 *
 * Returns 0 if success, or negative error code otherwise.
 */
static int __damon_va_three_regions(struct mm_struct *mm,
				       struct damon_addr_range regions[3])
{
	struct damon_addr_range first_gap = {0}, second_gap = {0};
	VMA_ITERATOR(vmi, mm, 0);
	struct vm_area_struct *vma, *prev = NULL;
	unsigned long start;

	/*
	 * Find the two biggest gaps so that first_gap > second_gap > others.
	 * If this is too slow, it can be optimised to examine the maple
	 * tree gaps.
	 */
	rcu_read_lock();
	for_each_vma(vmi, vma) {
		unsigned long gap;

		if (!prev) {
			start = vma->vm_start;
			goto next;
		}
		gap = vma->vm_start - prev->vm_end;

		if (gap > sz_range(&first_gap)) {
			second_gap = first_gap;
			first_gap.start = prev->vm_end;
			first_gap.end = vma->vm_start;
		} else if (gap > sz_range(&second_gap)) {
			second_gap.start = prev->vm_end;
			second_gap.end = vma->vm_start;
		}
next:
		prev = vma;
	}
	rcu_read_unlock();

	if (!sz_range(&second_gap) || !sz_range(&first_gap))
		return -EINVAL;

	/* Sort the two biggest gaps by address */
	if (first_gap.start > second_gap.start)
		swap(first_gap, second_gap);

	/* Store the result */
	regions[0].start = ALIGN(start, DAMON_MIN_REGION_SZ);
	regions[0].end = ALIGN(first_gap.start, DAMON_MIN_REGION_SZ);
	regions[1].start = ALIGN(first_gap.end, DAMON_MIN_REGION_SZ);
	regions[1].end = ALIGN(second_gap.start, DAMON_MIN_REGION_SZ);
	regions[2].start = ALIGN(second_gap.end, DAMON_MIN_REGION_SZ);
	regions[2].end = ALIGN(prev->vm_end, DAMON_MIN_REGION_SZ);

	return 0;
}

/*
 * Get the three regions in the given target (task)
 *
 * Returns 0 on success, negative error code otherwise.
 */
static int damon_va_three_regions(struct damon_target *t,
				struct damon_addr_range regions[3])
{
	struct mm_struct *mm;
	int rc;

	mm = damon_get_mm(t);
	if (!mm)
		return -EINVAL;

	mmap_read_lock(mm);
	rc = __damon_va_three_regions(mm, regions);
	mmap_read_unlock(mm);

	mmput(mm);
	return rc;
}

/*
 * Initialize the monitoring target regions for the given target (task)
 *
 * t	the given target
 *
 * Because only a number of small portions of the entire address space
 * is actually mapped to the memory and accessed, monitoring the unmapped
 * regions is wasteful.  That said, because we can deal with small noises,
 * tracking every mapping is not strictly required but could even incur a high
 * overhead if the mapping frequently changes or the number of mappings is
 * high.  The adaptive regions adjustment mechanism will further help to deal
 * with the noise by simply identifying the unmapped areas as a region that
 * has no access.  Moreover, applying the real mappings that would have many
 * unmapped areas inside will make the adaptive mechanism quite complex.  That
 * said, too huge unmapped areas inside the monitoring target should be removed
 * to not take the time for the adaptive mechanism.
 *
 * For the reason, we convert the complex mappings to three distinct regions
 * that cover every mapped area of the address space.  Also the two gaps
 * between the three regions are the two biggest unmapped areas in the given
 * address space.  In detail, this function first identifies the start and the
 * end of the mappings and the two biggest unmapped areas of the address space.
 * Then, it constructs the three regions as below:
 *
 *     [mappings[0]->start, big_two_unmapped_areas[0]->start)
 *     [big_two_unmapped_areas[0]->end, big_two_unmapped_areas[1]->start)
 *     [big_two_unmapped_areas[1]->end, mappings[nr_mappings - 1]->end)
 *
 * As usual memory map of processes is as below, the gap between the heap and
 * the uppermost mmap()-ed region, and the gap between the lowermost mmap()-ed
 * region and the stack will be two biggest unmapped regions.  Because these
 * gaps are exceptionally huge areas in usual address space, excluding these
 * two biggest unmapped regions will be sufficient to make a trade-off.
 *
 *   <heap>
 *   <BIG UNMAPPED REGION 1>
 *   <uppermost mmap()-ed region>
 *   (other mmap()-ed regions and small unmapped regions)
 *   <lowermost mmap()-ed region>
 *   <BIG UNMAPPED REGION 2>
 *   <stack>
 */
static void __damon_va_init_regions(struct damon_target *t)
{
	struct damon_addr_range regions[3];

	if (damon_va_three_regions(t, regions))
		return;

	damon_set_regions(t, regions, 3, DAMON_MIN_REGION_SZ);
}

/* Initialize '->regions_list' of every target (task) */
static void damon_va_init(struct damon_ctx *ctx)
{
	struct damon_target *t;

	damon_for_each_target(t, ctx) {
		/* the user may set the target regions as they want */
		if (!damon_nr_regions(t))
			__damon_va_init_regions(t);
	}
}

/*
 * Update regions for current memory mappings
 */
static void damon_va_update(struct damon_ctx *ctx)
{
	struct damon_addr_range three_regions[3];
	struct damon_target *t;

	damon_for_each_target(t, ctx) {
		if (damon_va_three_regions(t, three_regions))
			continue;
		damon_set_regions(t, three_regions, 3, DAMON_MIN_REGION_SZ);
	}
}

static void damon_va_walk_page_range(struct mm_struct *mm, unsigned long start,
		unsigned long end, struct mm_walk_ops *ops, void *private)
{
	struct vm_area_struct *vma;

	vma = lock_vma_under_rcu(mm, start);
	if (!vma)
		goto lock_mmap;

	if (end > vma->vm_end) {
		vma_end_read(vma);
		goto lock_mmap;
	}

	if (!(vma->vm_flags & VM_PFNMAP)) {
		ops->walk_lock = PGWALK_VMA_RDLOCK_VERIFY;
		walk_page_range_vma(vma, start, end, ops, private);
	}

	vma_end_read(vma);
	return;

lock_mmap:
	mmap_read_lock(mm);
	ops->walk_lock = PGWALK_RDLOCK;
	walk_page_range(mm, start, end, ops, private);
	mmap_read_unlock(mm);
}

static int damon_mkold_pmd_entry(pmd_t *pmd, unsigned long addr,
		unsigned long next, struct mm_walk *walk)
{
	pte_t *pte;
	spinlock_t *ptl;

	ptl = pmd_trans_huge_lock(pmd, walk->vma);
	if (ptl) {
		pmd_t pmde = pmdp_get(pmd);

		if (pmd_present(pmde))
			damon_pmdp_mkold(pmd, walk->vma, addr);
		spin_unlock(ptl);
		return 0;
	}

	pte = pte_offset_map_lock(walk->mm, pmd, addr, &ptl);
	if (!pte)
		return 0;
	if (!pte_present(ptep_get(pte)))
		goto out;
	damon_ptep_mkold(pte, walk->vma, addr);
out:
	pte_unmap_unlock(pte, ptl);
	return 0;
}

#ifdef CONFIG_HUGETLB_PAGE
static int damon_mkold_hugetlb_entry(pte_t *pte, unsigned long hmask,
				     unsigned long addr, unsigned long end,
				     struct mm_walk *walk)
{
	struct hstate *h = hstate_vma(walk->vma);
	spinlock_t *ptl;
	pte_t entry;

	ptl = huge_pte_lock(h, walk->mm, pte);
	entry = huge_ptep_get(walk->mm, addr, pte);
	if (!pte_present(entry))
		goto out;

	damon_hugetlb_mkold(pte, walk->mm, walk->vma, addr);

out:
	spin_unlock(ptl);
	return 0;
}
#else
#define damon_mkold_hugetlb_entry NULL
#endif /* CONFIG_HUGETLB_PAGE */

static void damon_va_mkold(struct mm_struct *mm, unsigned long addr)
{
	struct mm_walk_ops damon_mkold_ops = {
		.pmd_entry = damon_mkold_pmd_entry,
		.hugetlb_entry = damon_mkold_hugetlb_entry,
	};

	damon_va_walk_page_range(mm, addr, addr + 1, &damon_mkold_ops, NULL);
}

/*
 * Functions for the access checking of the regions
 */

static void __damon_va_prepare_access_check(struct mm_struct *mm,
					struct damon_region *r,
					struct damon_ctx *ctx)
{
	r->sampling_addr = damon_rand(ctx, r->ar.start, r->ar.end);

	damon_va_mkold(mm, r->sampling_addr);
}

static void damon_va_prepare_access_checks(struct damon_ctx *ctx)
{
	struct damon_target *t;
	struct mm_struct *mm;
	struct damon_region *r;

	damon_for_each_target(t, ctx) {
		mm = damon_get_mm(t);
		if (!mm)
			continue;
		damon_for_each_region(r, t)
			__damon_va_prepare_access_check(mm, r, ctx);
		mmput(mm);
	}
}

struct damon_young_walk_private {
	bool young;
};

static int damon_young_pmd_entry(pmd_t *pmd, unsigned long addr,
		unsigned long next, struct mm_walk *walk)
{
	pte_t *pte;
	pte_t ptent;
	spinlock_t *ptl;
	struct folio *folio;
	struct damon_young_walk_private *priv = walk->private;

#ifdef CONFIG_TRANSPARENT_HUGEPAGE
	ptl = pmd_trans_huge_lock(pmd, walk->vma);
	if (ptl) {
		pmd_t pmde = pmdp_get(pmd);

		if (!pmd_present(pmde))
			goto huge_out;
		folio = vm_normal_folio_pmd(walk->vma, addr, pmde);
		if (!folio)
			goto huge_out;
		if (pmd_young(pmde) || !folio_test_idle(folio) ||
					mmu_notifier_test_young(walk->mm,
						addr))
			priv->young = true;
huge_out:
		spin_unlock(ptl);
		return 0;
	}
#endif	/* CONFIG_TRANSPARENT_HUGEPAGE */

	pte = pte_offset_map_lock(walk->mm, pmd, addr, &ptl);
	if (!pte)
		return 0;
	ptent = ptep_get(pte);
	if (!pte_present(ptent))
		goto out;
	folio = vm_normal_folio(walk->vma, addr, ptent);
	if (!folio)
		goto out;
	if (pte_young(ptent) || !folio_test_idle(folio) ||
			mmu_notifier_test_young(walk->mm, addr))
		priv->young = true;
out:
	pte_unmap_unlock(pte, ptl);
	return 0;
}

#ifdef CONFIG_HUGETLB_PAGE
static int damon_young_hugetlb_entry(pte_t *pte, unsigned long hmask,
				     unsigned long addr, unsigned long end,
				     struct mm_walk *walk)
{
	struct damon_young_walk_private *priv = walk->private;
	struct hstate *h = hstate_vma(walk->vma);
	struct folio *folio;
	spinlock_t *ptl;
	pte_t entry;

	ptl = huge_pte_lock(h, walk->mm, pte);
	entry = huge_ptep_get(walk->mm, addr, pte);
	if (!pte_present(entry))
		goto out;

	folio = pfn_folio(pte_pfn(entry));
	folio_get(folio);

	if (pte_young(entry) || !folio_test_idle(folio) ||
	    mmu_notifier_test_young(walk->mm, addr))
		priv->young = true;

	folio_put(folio);

out:
	spin_unlock(ptl);
	return 0;
}
#else
#define damon_young_hugetlb_entry NULL
#endif /* CONFIG_HUGETLB_PAGE */

static bool damon_va_young(struct mm_struct *mm, unsigned long addr)
{
	struct damon_young_walk_private arg = {
		.young = false,
	};

	struct mm_walk_ops damon_young_ops = {
		.pmd_entry = damon_young_pmd_entry,
		.hugetlb_entry = damon_young_hugetlb_entry,
	};

	damon_va_walk_page_range(mm, addr, addr + 1, &damon_young_ops, &arg);
	return arg.young;
}

/*
 * Check whether the region was accessed after the last preparation
 *
 * mm	'mm_struct' for the given virtual address space
 * r	the region to be checked
 */
static void __damon_va_check_access(struct mm_struct *mm,
				struct damon_region *r)
{
	bool accessed;

	if (!mm) {
		damon_update_region_access_rate(r, false);
		return;
	}

	accessed = damon_va_young(mm, r->sampling_addr);
	damon_update_region_access_rate(r, accessed);
}

static unsigned int damon_va_check_accesses(struct damon_ctx *ctx)
{
	struct damon_target *t;
	struct mm_struct *mm;
	struct damon_region *r;
	unsigned int max_nr_accesses = 0;

	damon_for_each_target(t, ctx) {
		mm = damon_get_mm(t);
		damon_for_each_region(r, t) {
			__damon_va_check_access(mm, r);
			max_nr_accesses = max(r->nr_accesses, max_nr_accesses);
		}
		if (mm)
			mmput(mm);
	}

	return max_nr_accesses;
}

static void damon_va_prep_probe_region(struct damon_ctx *ctx,
		struct mm_struct *mm, struct damon_region *r,
		struct damon_probe *probe)
{
	struct damon_prep *p;

	damon_for_each_prep(p, probe) {
		switch (p->action) {
		case DAMON_PREP_SET_PGIDLE:
			damon_va_mkold(mm, r->sampling_addr);
			break;
		default:
			break;
		}
	}
}

static void damon_va_prep_probes(struct damon_ctx *ctx, bool set_samples)
{
	struct damon_target *t;
	struct mm_struct *mm;
	struct damon_region *r;
	struct damon_probe *p;

	damon_for_each_target(t, ctx) {
		mm = damon_get_mm(t);
		if (!mm)
			continue;
		damon_for_each_region(r, t) {
			if (set_samples)
				r->sampling_addr = damon_rand(ctx, r->ar.start,
						r->ar.end);
			damon_for_each_probe(p, ctx)
				damon_va_prep_probe_region(ctx, mm, r, p);
		}
		mmput(mm);
	}
}

static bool damon_va_young_addr(struct folio *folio, pte_t *pte, pmd_t *pmd,
		struct mm_struct *mm, unsigned long addr)
{
	bool young = false;

	if (pte)
		young = pte_young(*pte);
	else if (pmd)
		young = pmd_young(*pmd);
	young = young || !folio_test_idle(folio) ||
		mmu_notifier_test_young(mm, addr);
	return young;
}

static bool damon_va_filter_match(struct damon_filter *filter,
		struct folio *folio, pte_t *pte, pmd_t *pmd,
		struct mm_struct *mm, unsigned long addr)
{
	bool matched = false;

	switch (filter->type) {
	case DAMON_FILTER_TYPE_PGIDLE_UNSET:
		if (!folio)
			matched = false;
		else
			matched = damon_va_young_addr(folio, pte, pmd, mm,
					addr);
		break;
	default:
		return damon_ops_filter_match(filter, folio);
	}
	return matched == filter->matching;
}

static bool damon_va_filter_pass(struct folio *folio, struct damon_probe *p,
		pte_t *pte, pmd_t *pmd, struct mm_struct *mm,
		unsigned long addr)
{
	struct damon_filter *f;
	bool pass = true;

	damon_for_each_filter(f, p) {
		if (damon_va_filter_match(f, folio, pte, pmd, mm, addr)) {
			pass = f->allow;
			break;
		}
		pass = !f->allow;
	}
	return pass;
}

struct damon_va_probe_walk_private {
	struct damon_ctx *ctx;
	struct damon_region *r;
};

static void damon_va_probe_folio(struct damon_ctx *ctx,
		struct damon_region *r, struct folio *folio,
		pte_t *pte, pmd_t *pmd, struct mm_struct *mm)
{
	struct damon_probe *probe;
	int i = 0;

	damon_for_each_probe(probe, ctx) {
		if (damon_va_filter_pass(folio, probe, pte, pmd, mm,
					r->sampling_addr))
			r->probe_hits[i]++;
		i++;
	}
}

static int damon_va_probe_pmd_entry(pmd_t *pmd, unsigned long addr,
		unsigned long next, struct mm_walk *walk)
{
	pte_t *pte;
	pte_t ptent;
	spinlock_t *ptl;
	struct folio *folio;
	struct damon_va_probe_walk_private *priv = walk->private;

#ifdef CONFIG_TRANSPARENT_HUGEPAGE
	ptl = pmd_trans_huge_lock(pmd, walk->vma);
	if (ptl) {
		pmd_t pmde = pmdp_get(pmd);

		if (!pmd_present(pmde))
			goto huge_out;
		folio = vm_normal_folio_pmd(walk->vma, addr, pmde);
		if (!folio)
			goto huge_out;
		damon_va_probe_folio(priv->ctx, priv->r, folio, NULL, &pmde,
				walk->vma->vm_mm);

huge_out:
		spin_unlock(ptl);
		return 0;
	}
#endif	/* CONFIG_TRANSPARENT_HUGEPAGE */

	pte = pte_offset_map_lock(walk->mm, pmd, addr, &ptl);
	if (!pte)
		return 0;
	ptent = ptep_get(pte);
	if (!pte_present(ptent))
		goto out;
	folio = vm_normal_folio(walk->vma, addr, ptent);
	if (!folio)
		goto out;
	damon_va_probe_folio(priv->ctx, priv->r, folio, &ptent, NULL,
			walk->vma->vm_mm);

out:
	pte_unmap_unlock(pte, ptl);
	return 0;
}

#ifdef CONFIG_HUGETLB_PAGE
static int damon_va_probe_hugetlb_entry(pte_t *pte, unsigned long hmask,
		unsigned long addr, unsigned long end, struct mm_walk *walk)
{
	struct damon_va_probe_walk_private *priv = walk->private;
	struct hstate *h = hstate_vma(walk->vma);
	struct folio *folio;
	spinlock_t *ptl;
	pte_t entry;

	ptl = huge_pte_lock(h, walk->mm, pte);
	entry = huge_ptep_get(walk->mm, addr, pte);
	if (!pte_present(entry))
		goto out;

	folio = pfn_folio(pte_pfn(entry));
	folio_get(folio);
	damon_va_probe_folio(priv->ctx, priv->r, folio, &entry, NULL,
			walk->vma->vm_mm);
	folio_put(folio);

out:
	spin_unlock(ptl);
	return 0;
}
#else
#define damon_va_probe_hugetlb_entry NULL
#endif /* CONFIG_HUGETLB_PAGE */

static void __damon_va_apply_probes(struct damon_ctx *ctx,
		struct mm_struct *mm,  struct damon_region *r)
{
	struct damon_va_probe_walk_private arg = {
		.ctx = ctx,
		.r = r,
	};
	struct mm_walk_ops damon_probe_walk_ops = {
		.pmd_entry = damon_va_probe_pmd_entry,
		.hugetlb_entry = damon_va_probe_hugetlb_entry,
	};
	unsigned long addr = r->sampling_addr;

	if (!mm)
		return;

	damon_va_walk_page_range(mm, addr, addr + 1, &damon_probe_walk_ops,
			&arg);
}

static unsigned int damon_va_apply_probes(struct damon_ctx *ctx,
		bool set_samples, bool return_max_wsum)
{
	struct damon_target *t;
	struct mm_struct *mm;
	struct damon_region *r;
	unsigned int max_wsum = 0;

	damon_for_each_target(t, ctx) {
		mm = damon_get_mm(t);
		damon_for_each_region(r, t) {
			if (set_samples)
				r->sampling_addr = damon_rand(ctx, r->ar.start,
						r->ar.end);
			__damon_va_apply_probes(ctx, mm, r);
			if (return_max_wsum)
				max_wsum = max(damon_probe_hits_wsum(r, false,
							ctx), max_wsum);
		}
		if (mm)
			mmput(mm);
	}

	return max_wsum;
}

static bool damos_va_filter_young_match(struct damos_filter *filter,
		struct folio *folio, struct vm_area_struct *vma,
		unsigned long addr, pte_t *ptep, pmd_t *pmdp)
{
	bool young = false;

	if (ptep)
		young = pte_young(ptep_get(ptep));
	else if (pmdp)
		young = pmd_young(pmdp_get(pmdp));

	young = young || !folio_test_idle(folio) ||
		mmu_notifier_test_young(vma->vm_mm, addr);

	if (young && ptep)
		damon_ptep_mkold(ptep, vma, addr);
	else if (young && pmdp)
		damon_pmdp_mkold(pmdp, vma, addr);

	return young == filter->matching;
}

static bool damos_va_filter_out(struct damos *scheme, struct folio *folio,
		struct vm_area_struct *vma, unsigned long addr,
		pte_t *ptep, pmd_t *pmdp)
{
	struct damos_filter *filter;
	bool matched;

	if (scheme->core_filters_allowed)
		return false;

	damos_for_each_ops_filter(filter, scheme) {
		/*
		 * damos_folio_filter_match checks the young filter by doing an
		 * rmap on the folio to find its page table. However, being the
		 * vaddr scheme, we have direct access to the page tables, so
		 * use that instead.
		 */
		if (filter->type == DAMOS_FILTER_TYPE_YOUNG)
			matched = damos_va_filter_young_match(filter, folio,
				vma, addr, ptep, pmdp);
		else
			matched = damos_folio_filter_match(filter, folio);

		if (matched)
			return !filter->allow;
	}
	return scheme->ops_filters_default_reject;
}

struct damos_va_migrate_private {
	struct list_head *migration_lists;
	struct damos *scheme;
};

/*
 * Place the given folio in the migration_list corresponding to where the folio
 * should be migrated.
 *
 * The algorithm used here is similar to weighted_interleave_nid()
 */
static void damos_va_migrate_dests_add(struct folio *folio,
		struct vm_area_struct *vma, unsigned long addr,
		struct damos_migrate_dests *dests,
		struct list_head *migration_lists)
{
	pgoff_t ilx;
	int order;
	unsigned int target;
	unsigned int weight_total = 0;
	int i;

	/*
	 * If dests is empty, there is only one migration list corresponding
	 * to s->target_nid.
	 */
	if (!dests->nr_dests) {
		i = 0;
		goto isolate;
	}

	order = folio_order(folio);
	ilx = vma_start_pgoff(vma) >> order;
	ilx += linear_page_delta(vma, addr) >> order;

	for (i = 0; i < dests->nr_dests; i++)
		weight_total += dests->weight_arr[i];

	/* If the total weights are somehow 0, don't migrate at all */
	if (!weight_total)
		return;

	target = ilx % weight_total;
	for (i = 0; i < dests->nr_dests; i++) {
		if (target < dests->weight_arr[i])
			break;
		target -= dests->weight_arr[i];
	}

	/* If the folio is already in the right node, don't do anything */
	if (folio_nid(folio) == dests->node_id_arr[i])
		return;

isolate:
	if (!folio_isolate_lru(folio))
		return;
	node_stat_add_folio(folio, NR_ISOLATED_ANON +
			folio_is_file_lru(folio));
	list_add(&folio->lru, &migration_lists[i]);
}

static int damos_va_migrate_pmd_entry(pmd_t *pmd, unsigned long addr,
		unsigned long next, struct mm_walk *walk)
{
	struct damos_va_migrate_private *priv = walk->private;
	struct list_head *migration_lists = priv->migration_lists;
	struct damos *s = priv->scheme;
	struct damos_migrate_dests *dests = &s->migrate_dests;
	struct folio *folio;
	spinlock_t *ptl;
	pte_t *start_pte, *pte, ptent;
	int nr;

#ifdef CONFIG_TRANSPARENT_HUGEPAGE
	ptl = pmd_trans_huge_lock(pmd, walk->vma);
	if (ptl) {
		pmd_t pmde = pmdp_get(pmd);

		if (!pmd_present(pmde))
			goto huge_out;
		folio = vm_normal_folio_pmd(walk->vma, addr, pmde);
		if (!folio)
			goto huge_out;
		if (damos_va_filter_out(s, folio, walk->vma, addr, NULL, pmd))
			goto huge_out;
		damos_va_migrate_dests_add(folio, walk->vma, addr, dests,
				migration_lists);
huge_out:
		spin_unlock(ptl);
		return 0;
	}
#endif	/* CONFIG_TRANSPARENT_HUGEPAGE */

	start_pte = pte = pte_offset_map_lock(walk->mm, pmd, addr, &ptl);
	if (!pte)
		return 0;

	for (; addr < next; pte += nr, addr += nr * PAGE_SIZE) {
		unsigned long page_idx;

		nr = 1;
		ptent = ptep_get(pte);

		if (pte_none(ptent) || !pte_present(ptent))
			continue;
		folio = vm_normal_folio(walk->vma, addr, ptent);
		if (!folio)
			continue;
		if (damos_va_filter_out(s, folio, walk->vma, addr, pte, NULL))
			continue;
		damos_va_migrate_dests_add(folio, walk->vma, addr, dests,
				migration_lists);
		page_idx = folio_page_idx(folio, pte_page(ptent));
		nr = folio_nr_pages(folio) - page_idx;
	}
	pte_unmap_unlock(start_pte, ptl);
	return 0;
}

/*
 * Functions for the target validity check and cleanup
 */

static bool damon_va_target_valid(struct damon_target *t)
{
	struct task_struct *task;

	task = damon_get_task_struct(t);
	if (task) {
		put_task_struct(task);
		return true;
	}

	return false;
}

static void damon_va_cleanup_target(struct damon_target *t)
{
	put_pid(t->pid);
}

#ifndef CONFIG_ADVISE_SYSCALLS
static unsigned long damos_madvise(struct damon_target *target,
		struct damon_region *r, int behavior)
{
	return 0;
}
#else
static unsigned long damos_madvise(struct damon_target *target,
		struct damon_region *r, int behavior)
{
	struct mm_struct *mm;
	unsigned long start = PAGE_ALIGN(r->ar.start);
	unsigned long len = PAGE_ALIGN(damon_sz_region(r));
	unsigned long applied;

	mm = damon_get_mm(target);
	if (!mm)
		return 0;

	applied = do_madvise(mm, start, len, behavior) ? 0 : len;
	mmput(mm);

	return applied;
}
#endif	/* CONFIG_ADVISE_SYSCALLS */

static unsigned long damos_va_migrate(struct damon_target *target,
		struct damon_region *r, struct damos *s,
		unsigned long *sz_filter_passed)
{
	LIST_HEAD(folio_list);
	struct damos_va_migrate_private priv;
	struct mm_struct *mm;
	int nr_dests;
	int nid;
	bool use_target_nid;
	unsigned long applied = 0;
	struct damos_migrate_dests *dests = &s->migrate_dests;
	struct mm_walk_ops walk_ops = {
		.pmd_entry = damos_va_migrate_pmd_entry,
		.pte_entry = NULL,
	};

	use_target_nid = dests->nr_dests == 0;
	nr_dests = use_target_nid ? 1 : dests->nr_dests;
	priv.scheme = s;
	priv.migration_lists = kmalloc_objs(*priv.migration_lists, nr_dests);
	if (!priv.migration_lists)
		return 0;

	for (int i = 0; i < nr_dests; i++)
		INIT_LIST_HEAD(&priv.migration_lists[i]);


	mm = damon_get_mm(target);
	if (!mm)
		goto free_lists;

	damon_va_walk_page_range(mm, r->ar.start, r->ar.end, &walk_ops, &priv);
	mmput(mm);

	for (int i = 0; i < nr_dests; i++) {
		nid = use_target_nid ? s->target_nid : dests->node_id_arr[i];
		applied += damon_migrate_pages(&priv.migration_lists[i], nid);
		cond_resched();
	}

free_lists:
	kfree(priv.migration_lists);
	return applied * PAGE_SIZE;
}

struct damos_va_stat_private {
	struct damos *scheme;
	unsigned long *sz_filter_passed;
};

static inline bool damos_va_invalid_folio(struct folio *folio,
		struct damos *s)
{
	return !folio || folio == s->last_applied;
}

static int damos_va_stat_pmd_entry(pmd_t *pmd, unsigned long addr,
		unsigned long next, struct mm_walk *walk)
{
	struct damos_va_stat_private *priv = walk->private;
	struct damos *s = priv->scheme;
	unsigned long *sz_filter_passed = priv->sz_filter_passed;
	struct vm_area_struct *vma = walk->vma;
	struct folio *folio;
	spinlock_t *ptl;
	pte_t *start_pte, *pte, ptent;
	int nr;

#ifdef CONFIG_TRANSPARENT_HUGEPAGE
	ptl = pmd_trans_huge_lock(pmd, vma);
	if (ptl) {
		pmd_t pmde = pmdp_get(pmd);

		if (!pmd_present(pmde))
			goto huge_unlock;

		folio = vm_normal_folio_pmd(vma, addr, pmde);

		if (damos_va_invalid_folio(folio, s))
			goto huge_unlock;

		if (!damos_va_filter_out(s, folio, vma, addr, NULL, pmd))
			*sz_filter_passed += folio_size(folio);
		s->last_applied = folio;

huge_unlock:
		spin_unlock(ptl);
		return 0;
	}
#endif
	start_pte = pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
	if (!start_pte)
		return 0;

	for (; addr < next; pte += nr, addr += nr * PAGE_SIZE) {
		unsigned long page_idx;

		nr = 1;
		ptent = ptep_get(pte);

		if (pte_none(ptent) || !pte_present(ptent))
			continue;

		folio = vm_normal_folio(vma, addr, ptent);

		if (damos_va_invalid_folio(folio, s))
			continue;

		if (!damos_va_filter_out(s, folio, vma, addr, pte, NULL))
			*sz_filter_passed += folio_size(folio);
		page_idx = folio_page_idx(folio, pte_page(ptent));
		nr = folio_nr_pages(folio) - page_idx;
		s->last_applied = folio;
	}
	pte_unmap_unlock(start_pte, ptl);
	return 0;
}

static unsigned long damos_va_stat(struct damon_target *target,
		struct damon_region *r, struct damos *s,
		unsigned long *sz_filter_passed)
{
	struct damos_va_stat_private priv;
	struct mm_struct *mm;
	struct mm_walk_ops walk_ops = {
		.pmd_entry = damos_va_stat_pmd_entry,
	};

	priv.scheme = s;
	priv.sz_filter_passed = sz_filter_passed;

	if (!damos_ops_has_filter(s))
		return 0;

	mm = damon_get_mm(target);
	if (!mm)
		return 0;

	damon_va_walk_page_range(mm, r->ar.start, r->ar.end, &walk_ops, &priv);
	mmput(mm);
	return 0;
}

static unsigned long damon_va_apply_scheme(struct damon_ctx *ctx,
		struct damon_target *t, struct damon_region *r,
		struct damos *scheme, unsigned long *sz_filter_passed)
{
	int madv_action;

	switch (scheme->action) {
	case DAMOS_WILLNEED:
		madv_action = MADV_WILLNEED;
		break;
	case DAMOS_COLD:
		madv_action = MADV_COLD;
		break;
	case DAMOS_PAGEOUT:
		madv_action = MADV_PAGEOUT;
		break;
	case DAMOS_HUGEPAGE:
		madv_action = MADV_HUGEPAGE;
		break;
	case DAMOS_NOHUGEPAGE:
		madv_action = MADV_NOHUGEPAGE;
		break;
	case DAMOS_COLLAPSE:
		madv_action = MADV_COLLAPSE;
		break;
	case DAMOS_MIGRATE_HOT:
	case DAMOS_MIGRATE_COLD:
		return damos_va_migrate(t, r, scheme, sz_filter_passed);
	case DAMOS_STAT:
		return damos_va_stat(t, r, scheme, sz_filter_passed);
	default:
		/*
		 * DAMOS actions that are not yet supported by 'vaddr'.
		 */
		return 0;
	}

	return damos_madvise(t, r, madv_action);
}

static int damon_va_scheme_score(struct damon_ctx *context,
		struct damon_region *r, struct damos *scheme)
{

	switch (scheme->action) {
	case DAMOS_PAGEOUT:
		return damon_cold_score(context, r, scheme);
	case DAMOS_MIGRATE_HOT:
		return damon_hot_score(context, r, scheme);
	case DAMOS_MIGRATE_COLD:
		return damon_cold_score(context, r, scheme);
	default:
		break;
	}

	return DAMOS_MAX_SCORE;
}

static int __init damon_va_initcall(void)
{
	struct damon_operations ops = {
		.id = DAMON_OPS_VADDR,
		.init = damon_va_init,
		.update = damon_va_update,
		.prepare_access_checks = damon_va_prepare_access_checks,
		.check_accesses = damon_va_check_accesses,
		.prep_probes = damon_va_prep_probes,
		.apply_probes = damon_va_apply_probes,
		.target_valid = damon_va_target_valid,
		.cleanup_target = damon_va_cleanup_target,
		.apply_scheme = damon_va_apply_scheme,
		.get_scheme_score = damon_va_scheme_score,
	};
	/* ops for fixed virtual address ranges */
	struct damon_operations ops_fvaddr = ops;
	int err;

	/* Don't set the monitoring target regions for the entire mapping */
	ops_fvaddr.id = DAMON_OPS_FVADDR;
	ops_fvaddr.init = NULL;
	ops_fvaddr.update = NULL;

	err = damon_register_ops(&ops);
	if (err)
		return err;
	return damon_register_ops(&ops_fvaddr);
}

subsys_initcall(damon_va_initcall);

#include "tests/vaddr-kunit.h"