xref: /openbmc/linux/mm/damon/vaddr.c (revision 06ba8020)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * DAMON Primitives for Virtual Address Spaces
4  *
5  * Author: SeongJae Park <sjpark@amazon.de>
6  */
7 
8 #define pr_fmt(fmt) "damon-va: " fmt
9 
10 #include <asm-generic/mman-common.h>
11 #include <linux/highmem.h>
12 #include <linux/hugetlb.h>
13 #include <linux/mmu_notifier.h>
14 #include <linux/page_idle.h>
15 #include <linux/pagewalk.h>
16 #include <linux/sched/mm.h>
17 
18 #include "ops-common.h"
19 
20 #ifdef CONFIG_DAMON_VADDR_KUNIT_TEST
21 #undef DAMON_MIN_REGION
22 #define DAMON_MIN_REGION 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 /*
56  * Functions for the initial monitoring target regions construction
57  */
58 
59 /*
60  * Size-evenly split a region into 'nr_pieces' small regions
61  *
62  * Returns 0 on success, or negative error code otherwise.
63  */
64 static int damon_va_evenly_split_region(struct damon_target *t,
65 		struct damon_region *r, unsigned int nr_pieces)
66 {
67 	unsigned long sz_orig, sz_piece, orig_end;
68 	struct damon_region *n = NULL, *next;
69 	unsigned long start;
70 
71 	if (!r || !nr_pieces)
72 		return -EINVAL;
73 
74 	orig_end = r->ar.end;
75 	sz_orig = damon_sz_region(r);
76 	sz_piece = ALIGN_DOWN(sz_orig / nr_pieces, DAMON_MIN_REGION);
77 
78 	if (!sz_piece)
79 		return -EINVAL;
80 
81 	r->ar.end = r->ar.start + sz_piece;
82 	next = damon_next_region(r);
83 	for (start = r->ar.end; start + sz_piece <= orig_end;
84 			start += sz_piece) {
85 		n = damon_new_region(start, start + sz_piece);
86 		if (!n)
87 			return -ENOMEM;
88 		damon_insert_region(n, r, next, t);
89 		r = n;
90 	}
91 	/* complement last region for possible rounding error */
92 	if (n)
93 		n->ar.end = orig_end;
94 
95 	return 0;
96 }
97 
98 static unsigned long sz_range(struct damon_addr_range *r)
99 {
100 	return r->end - r->start;
101 }
102 
103 /*
104  * Find three regions separated by two biggest unmapped regions
105  *
106  * vma		the head vma of the target address space
107  * regions	an array of three address ranges that results will be saved
108  *
109  * This function receives an address space and finds three regions in it which
110  * separated by the two biggest unmapped regions in the space.  Please refer to
111  * below comments of '__damon_va_init_regions()' function to know why this is
112  * necessary.
113  *
114  * Returns 0 if success, or negative error code otherwise.
115  */
116 static int __damon_va_three_regions(struct mm_struct *mm,
117 				       struct damon_addr_range regions[3])
118 {
119 	struct damon_addr_range first_gap = {0}, second_gap = {0};
120 	VMA_ITERATOR(vmi, mm, 0);
121 	struct vm_area_struct *vma, *prev = NULL;
122 	unsigned long start;
123 
124 	/*
125 	 * Find the two biggest gaps so that first_gap > second_gap > others.
126 	 * If this is too slow, it can be optimised to examine the maple
127 	 * tree gaps.
128 	 */
129 	for_each_vma(vmi, vma) {
130 		unsigned long gap;
131 
132 		if (!prev) {
133 			start = vma->vm_start;
134 			goto next;
135 		}
136 		gap = vma->vm_start - prev->vm_end;
137 
138 		if (gap > sz_range(&first_gap)) {
139 			second_gap = first_gap;
140 			first_gap.start = prev->vm_end;
141 			first_gap.end = vma->vm_start;
142 		} else if (gap > sz_range(&second_gap)) {
143 			second_gap.start = prev->vm_end;
144 			second_gap.end = vma->vm_start;
145 		}
146 next:
147 		prev = vma;
148 	}
149 
150 	if (!sz_range(&second_gap) || !sz_range(&first_gap))
151 		return -EINVAL;
152 
153 	/* Sort the two biggest gaps by address */
154 	if (first_gap.start > second_gap.start)
155 		swap(first_gap, second_gap);
156 
157 	/* Store the result */
158 	regions[0].start = ALIGN(start, DAMON_MIN_REGION);
159 	regions[0].end = ALIGN(first_gap.start, DAMON_MIN_REGION);
160 	regions[1].start = ALIGN(first_gap.end, DAMON_MIN_REGION);
161 	regions[1].end = ALIGN(second_gap.start, DAMON_MIN_REGION);
162 	regions[2].start = ALIGN(second_gap.end, DAMON_MIN_REGION);
163 	regions[2].end = ALIGN(prev->vm_end, DAMON_MIN_REGION);
164 
165 	return 0;
166 }
167 
168 /*
169  * Get the three regions in the given target (task)
170  *
171  * Returns 0 on success, negative error code otherwise.
172  */
173 static int damon_va_three_regions(struct damon_target *t,
174 				struct damon_addr_range regions[3])
175 {
176 	struct mm_struct *mm;
177 	int rc;
178 
179 	mm = damon_get_mm(t);
180 	if (!mm)
181 		return -EINVAL;
182 
183 	mmap_read_lock(mm);
184 	rc = __damon_va_three_regions(mm, regions);
185 	mmap_read_unlock(mm);
186 
187 	mmput(mm);
188 	return rc;
189 }
190 
191 /*
192  * Initialize the monitoring target regions for the given target (task)
193  *
194  * t	the given target
195  *
196  * Because only a number of small portions of the entire address space
197  * is actually mapped to the memory and accessed, monitoring the unmapped
198  * regions is wasteful.  That said, because we can deal with small noises,
199  * tracking every mapping is not strictly required but could even incur a high
200  * overhead if the mapping frequently changes or the number of mappings is
201  * high.  The adaptive regions adjustment mechanism will further help to deal
202  * with the noise by simply identifying the unmapped areas as a region that
203  * has no access.  Moreover, applying the real mappings that would have many
204  * unmapped areas inside will make the adaptive mechanism quite complex.  That
205  * said, too huge unmapped areas inside the monitoring target should be removed
206  * to not take the time for the adaptive mechanism.
207  *
208  * For the reason, we convert the complex mappings to three distinct regions
209  * that cover every mapped area of the address space.  Also the two gaps
210  * between the three regions are the two biggest unmapped areas in the given
211  * address space.  In detail, this function first identifies the start and the
212  * end of the mappings and the two biggest unmapped areas of the address space.
213  * Then, it constructs the three regions as below:
214  *
215  *     [mappings[0]->start, big_two_unmapped_areas[0]->start)
216  *     [big_two_unmapped_areas[0]->end, big_two_unmapped_areas[1]->start)
217  *     [big_two_unmapped_areas[1]->end, mappings[nr_mappings - 1]->end)
218  *
219  * As usual memory map of processes is as below, the gap between the heap and
220  * the uppermost mmap()-ed region, and the gap between the lowermost mmap()-ed
221  * region and the stack will be two biggest unmapped regions.  Because these
222  * gaps are exceptionally huge areas in usual address space, excluding these
223  * two biggest unmapped regions will be sufficient to make a trade-off.
224  *
225  *   <heap>
226  *   <BIG UNMAPPED REGION 1>
227  *   <uppermost mmap()-ed region>
228  *   (other mmap()-ed regions and small unmapped regions)
229  *   <lowermost mmap()-ed region>
230  *   <BIG UNMAPPED REGION 2>
231  *   <stack>
232  */
233 static void __damon_va_init_regions(struct damon_ctx *ctx,
234 				     struct damon_target *t)
235 {
236 	struct damon_target *ti;
237 	struct damon_region *r;
238 	struct damon_addr_range regions[3];
239 	unsigned long sz = 0, nr_pieces;
240 	int i, tidx = 0;
241 
242 	if (damon_va_three_regions(t, regions)) {
243 		damon_for_each_target(ti, ctx) {
244 			if (ti == t)
245 				break;
246 			tidx++;
247 		}
248 		pr_debug("Failed to get three regions of %dth target\n", tidx);
249 		return;
250 	}
251 
252 	for (i = 0; i < 3; i++)
253 		sz += regions[i].end - regions[i].start;
254 	if (ctx->attrs.min_nr_regions)
255 		sz /= ctx->attrs.min_nr_regions;
256 	if (sz < DAMON_MIN_REGION)
257 		sz = DAMON_MIN_REGION;
258 
259 	/* Set the initial three regions of the target */
260 	for (i = 0; i < 3; i++) {
261 		r = damon_new_region(regions[i].start, regions[i].end);
262 		if (!r) {
263 			pr_err("%d'th init region creation failed\n", i);
264 			return;
265 		}
266 		damon_add_region(r, t);
267 
268 		nr_pieces = (regions[i].end - regions[i].start) / sz;
269 		damon_va_evenly_split_region(t, r, nr_pieces);
270 	}
271 }
272 
273 /* Initialize '->regions_list' of every target (task) */
274 static void damon_va_init(struct damon_ctx *ctx)
275 {
276 	struct damon_target *t;
277 
278 	damon_for_each_target(t, ctx) {
279 		/* the user may set the target regions as they want */
280 		if (!damon_nr_regions(t))
281 			__damon_va_init_regions(ctx, t);
282 	}
283 }
284 
285 /*
286  * Update regions for current memory mappings
287  */
288 static void damon_va_update(struct damon_ctx *ctx)
289 {
290 	struct damon_addr_range three_regions[3];
291 	struct damon_target *t;
292 
293 	damon_for_each_target(t, ctx) {
294 		if (damon_va_three_regions(t, three_regions))
295 			continue;
296 		damon_set_regions(t, three_regions, 3);
297 	}
298 }
299 
300 static int damon_mkold_pmd_entry(pmd_t *pmd, unsigned long addr,
301 		unsigned long next, struct mm_walk *walk)
302 {
303 	pte_t *pte;
304 	spinlock_t *ptl;
305 
306 	if (pmd_trans_huge(*pmd)) {
307 		ptl = pmd_lock(walk->mm, pmd);
308 		if (!pmd_present(*pmd)) {
309 			spin_unlock(ptl);
310 			return 0;
311 		}
312 
313 		if (pmd_trans_huge(*pmd)) {
314 			damon_pmdp_mkold(pmd, walk->mm, addr);
315 			spin_unlock(ptl);
316 			return 0;
317 		}
318 		spin_unlock(ptl);
319 	}
320 
321 	if (pmd_none(*pmd) || unlikely(pmd_bad(*pmd)))
322 		return 0;
323 	pte = pte_offset_map_lock(walk->mm, pmd, addr, &ptl);
324 	if (!pte_present(*pte))
325 		goto out;
326 	damon_ptep_mkold(pte, walk->mm, addr);
327 out:
328 	pte_unmap_unlock(pte, ptl);
329 	return 0;
330 }
331 
332 #ifdef CONFIG_HUGETLB_PAGE
333 static void damon_hugetlb_mkold(pte_t *pte, struct mm_struct *mm,
334 				struct vm_area_struct *vma, unsigned long addr)
335 {
336 	bool referenced = false;
337 	pte_t entry = huge_ptep_get(pte);
338 	struct folio *folio = pfn_folio(pte_pfn(entry));
339 
340 	folio_get(folio);
341 
342 	if (pte_young(entry)) {
343 		referenced = true;
344 		entry = pte_mkold(entry);
345 		set_huge_pte_at(mm, addr, pte, entry);
346 	}
347 
348 #ifdef CONFIG_MMU_NOTIFIER
349 	if (mmu_notifier_clear_young(mm, addr,
350 				     addr + huge_page_size(hstate_vma(vma))))
351 		referenced = true;
352 #endif /* CONFIG_MMU_NOTIFIER */
353 
354 	if (referenced)
355 		folio_set_young(folio);
356 
357 	folio_set_idle(folio);
358 	folio_put(folio);
359 }
360 
361 static int damon_mkold_hugetlb_entry(pte_t *pte, unsigned long hmask,
362 				     unsigned long addr, unsigned long end,
363 				     struct mm_walk *walk)
364 {
365 	struct hstate *h = hstate_vma(walk->vma);
366 	spinlock_t *ptl;
367 	pte_t entry;
368 
369 	ptl = huge_pte_lock(h, walk->mm, pte);
370 	entry = huge_ptep_get(pte);
371 	if (!pte_present(entry))
372 		goto out;
373 
374 	damon_hugetlb_mkold(pte, walk->mm, walk->vma, addr);
375 
376 out:
377 	spin_unlock(ptl);
378 	return 0;
379 }
380 #else
381 #define damon_mkold_hugetlb_entry NULL
382 #endif /* CONFIG_HUGETLB_PAGE */
383 
384 static const struct mm_walk_ops damon_mkold_ops = {
385 	.pmd_entry = damon_mkold_pmd_entry,
386 	.hugetlb_entry = damon_mkold_hugetlb_entry,
387 };
388 
389 static void damon_va_mkold(struct mm_struct *mm, unsigned long addr)
390 {
391 	mmap_read_lock(mm);
392 	walk_page_range(mm, addr, addr + 1, &damon_mkold_ops, NULL);
393 	mmap_read_unlock(mm);
394 }
395 
396 /*
397  * Functions for the access checking of the regions
398  */
399 
400 static void __damon_va_prepare_access_check(struct mm_struct *mm,
401 					struct damon_region *r)
402 {
403 	r->sampling_addr = damon_rand(r->ar.start, r->ar.end);
404 
405 	damon_va_mkold(mm, r->sampling_addr);
406 }
407 
408 static void damon_va_prepare_access_checks(struct damon_ctx *ctx)
409 {
410 	struct damon_target *t;
411 	struct mm_struct *mm;
412 	struct damon_region *r;
413 
414 	damon_for_each_target(t, ctx) {
415 		mm = damon_get_mm(t);
416 		if (!mm)
417 			continue;
418 		damon_for_each_region(r, t)
419 			__damon_va_prepare_access_check(mm, r);
420 		mmput(mm);
421 	}
422 }
423 
424 struct damon_young_walk_private {
425 	/* size of the folio for the access checked virtual memory address */
426 	unsigned long *folio_sz;
427 	bool young;
428 };
429 
430 static int damon_young_pmd_entry(pmd_t *pmd, unsigned long addr,
431 		unsigned long next, struct mm_walk *walk)
432 {
433 	pte_t *pte;
434 	spinlock_t *ptl;
435 	struct folio *folio;
436 	struct damon_young_walk_private *priv = walk->private;
437 
438 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
439 	if (pmd_trans_huge(*pmd)) {
440 		ptl = pmd_lock(walk->mm, pmd);
441 		if (!pmd_present(*pmd)) {
442 			spin_unlock(ptl);
443 			return 0;
444 		}
445 
446 		if (!pmd_trans_huge(*pmd)) {
447 			spin_unlock(ptl);
448 			goto regular_page;
449 		}
450 		folio = damon_get_folio(pmd_pfn(*pmd));
451 		if (!folio)
452 			goto huge_out;
453 		if (pmd_young(*pmd) || !folio_test_idle(folio) ||
454 					mmu_notifier_test_young(walk->mm,
455 						addr))
456 			priv->young = true;
457 		*priv->folio_sz = HPAGE_PMD_SIZE;
458 		folio_put(folio);
459 huge_out:
460 		spin_unlock(ptl);
461 		return 0;
462 	}
463 
464 regular_page:
465 #endif	/* CONFIG_TRANSPARENT_HUGEPAGE */
466 
467 	if (pmd_none(*pmd) || unlikely(pmd_bad(*pmd)))
468 		return -EINVAL;
469 	pte = pte_offset_map_lock(walk->mm, pmd, addr, &ptl);
470 	if (!pte_present(*pte))
471 		goto out;
472 	folio = damon_get_folio(pte_pfn(*pte));
473 	if (!folio)
474 		goto out;
475 	if (pte_young(*pte) || !folio_test_idle(folio) ||
476 			mmu_notifier_test_young(walk->mm, addr))
477 		priv->young = true;
478 	*priv->folio_sz = folio_size(folio);
479 	folio_put(folio);
480 out:
481 	pte_unmap_unlock(pte, ptl);
482 	return 0;
483 }
484 
485 #ifdef CONFIG_HUGETLB_PAGE
486 static int damon_young_hugetlb_entry(pte_t *pte, unsigned long hmask,
487 				     unsigned long addr, unsigned long end,
488 				     struct mm_walk *walk)
489 {
490 	struct damon_young_walk_private *priv = walk->private;
491 	struct hstate *h = hstate_vma(walk->vma);
492 	struct folio *folio;
493 	spinlock_t *ptl;
494 	pte_t entry;
495 
496 	ptl = huge_pte_lock(h, walk->mm, pte);
497 	entry = huge_ptep_get(pte);
498 	if (!pte_present(entry))
499 		goto out;
500 
501 	folio = pfn_folio(pte_pfn(entry));
502 	folio_get(folio);
503 
504 	if (pte_young(entry) || !folio_test_idle(folio) ||
505 	    mmu_notifier_test_young(walk->mm, addr))
506 		priv->young = true;
507 	*priv->folio_sz = huge_page_size(h);
508 
509 	folio_put(folio);
510 
511 out:
512 	spin_unlock(ptl);
513 	return 0;
514 }
515 #else
516 #define damon_young_hugetlb_entry NULL
517 #endif /* CONFIG_HUGETLB_PAGE */
518 
519 static const struct mm_walk_ops damon_young_ops = {
520 	.pmd_entry = damon_young_pmd_entry,
521 	.hugetlb_entry = damon_young_hugetlb_entry,
522 };
523 
524 static bool damon_va_young(struct mm_struct *mm, unsigned long addr,
525 		unsigned long *folio_sz)
526 {
527 	struct damon_young_walk_private arg = {
528 		.folio_sz = folio_sz,
529 		.young = false,
530 	};
531 
532 	mmap_read_lock(mm);
533 	walk_page_range(mm, addr, addr + 1, &damon_young_ops, &arg);
534 	mmap_read_unlock(mm);
535 	return arg.young;
536 }
537 
538 /*
539  * Check whether the region was accessed after the last preparation
540  *
541  * mm	'mm_struct' for the given virtual address space
542  * r	the region to be checked
543  */
544 static void __damon_va_check_access(struct mm_struct *mm,
545 				struct damon_region *r, bool same_target)
546 {
547 	static unsigned long last_addr;
548 	static unsigned long last_folio_sz = PAGE_SIZE;
549 	static bool last_accessed;
550 
551 	/* If the region is in the last checked page, reuse the result */
552 	if (same_target && (ALIGN_DOWN(last_addr, last_folio_sz) ==
553 				ALIGN_DOWN(r->sampling_addr, last_folio_sz))) {
554 		if (last_accessed)
555 			r->nr_accesses++;
556 		return;
557 	}
558 
559 	last_accessed = damon_va_young(mm, r->sampling_addr, &last_folio_sz);
560 	if (last_accessed)
561 		r->nr_accesses++;
562 
563 	last_addr = r->sampling_addr;
564 }
565 
566 static unsigned int damon_va_check_accesses(struct damon_ctx *ctx)
567 {
568 	struct damon_target *t;
569 	struct mm_struct *mm;
570 	struct damon_region *r;
571 	unsigned int max_nr_accesses = 0;
572 	bool same_target;
573 
574 	damon_for_each_target(t, ctx) {
575 		mm = damon_get_mm(t);
576 		if (!mm)
577 			continue;
578 		same_target = false;
579 		damon_for_each_region(r, t) {
580 			__damon_va_check_access(mm, r, same_target);
581 			max_nr_accesses = max(r->nr_accesses, max_nr_accesses);
582 			same_target = true;
583 		}
584 		mmput(mm);
585 	}
586 
587 	return max_nr_accesses;
588 }
589 
590 /*
591  * Functions for the target validity check and cleanup
592  */
593 
594 static bool damon_va_target_valid(struct damon_target *t)
595 {
596 	struct task_struct *task;
597 
598 	task = damon_get_task_struct(t);
599 	if (task) {
600 		put_task_struct(task);
601 		return true;
602 	}
603 
604 	return false;
605 }
606 
607 #ifndef CONFIG_ADVISE_SYSCALLS
608 static unsigned long damos_madvise(struct damon_target *target,
609 		struct damon_region *r, int behavior)
610 {
611 	return 0;
612 }
613 #else
614 static unsigned long damos_madvise(struct damon_target *target,
615 		struct damon_region *r, int behavior)
616 {
617 	struct mm_struct *mm;
618 	unsigned long start = PAGE_ALIGN(r->ar.start);
619 	unsigned long len = PAGE_ALIGN(damon_sz_region(r));
620 	unsigned long applied;
621 
622 	mm = damon_get_mm(target);
623 	if (!mm)
624 		return 0;
625 
626 	applied = do_madvise(mm, start, len, behavior) ? 0 : len;
627 	mmput(mm);
628 
629 	return applied;
630 }
631 #endif	/* CONFIG_ADVISE_SYSCALLS */
632 
633 static unsigned long damon_va_apply_scheme(struct damon_ctx *ctx,
634 		struct damon_target *t, struct damon_region *r,
635 		struct damos *scheme)
636 {
637 	int madv_action;
638 
639 	switch (scheme->action) {
640 	case DAMOS_WILLNEED:
641 		madv_action = MADV_WILLNEED;
642 		break;
643 	case DAMOS_COLD:
644 		madv_action = MADV_COLD;
645 		break;
646 	case DAMOS_PAGEOUT:
647 		madv_action = MADV_PAGEOUT;
648 		break;
649 	case DAMOS_HUGEPAGE:
650 		madv_action = MADV_HUGEPAGE;
651 		break;
652 	case DAMOS_NOHUGEPAGE:
653 		madv_action = MADV_NOHUGEPAGE;
654 		break;
655 	case DAMOS_STAT:
656 		return 0;
657 	default:
658 		/*
659 		 * DAMOS actions that are not yet supported by 'vaddr'.
660 		 */
661 		return 0;
662 	}
663 
664 	return damos_madvise(t, r, madv_action);
665 }
666 
667 static int damon_va_scheme_score(struct damon_ctx *context,
668 		struct damon_target *t, struct damon_region *r,
669 		struct damos *scheme)
670 {
671 
672 	switch (scheme->action) {
673 	case DAMOS_PAGEOUT:
674 		return damon_cold_score(context, r, scheme);
675 	default:
676 		break;
677 	}
678 
679 	return DAMOS_MAX_SCORE;
680 }
681 
682 static int __init damon_va_initcall(void)
683 {
684 	struct damon_operations ops = {
685 		.id = DAMON_OPS_VADDR,
686 		.init = damon_va_init,
687 		.update = damon_va_update,
688 		.prepare_access_checks = damon_va_prepare_access_checks,
689 		.check_accesses = damon_va_check_accesses,
690 		.reset_aggregated = NULL,
691 		.target_valid = damon_va_target_valid,
692 		.cleanup = NULL,
693 		.apply_scheme = damon_va_apply_scheme,
694 		.get_scheme_score = damon_va_scheme_score,
695 	};
696 	/* ops for fixed virtual address ranges */
697 	struct damon_operations ops_fvaddr = ops;
698 	int err;
699 
700 	/* Don't set the monitoring target regions for the entire mapping */
701 	ops_fvaddr.id = DAMON_OPS_FVADDR;
702 	ops_fvaddr.init = NULL;
703 	ops_fvaddr.update = NULL;
704 
705 	err = damon_register_ops(&ops);
706 	if (err)
707 		return err;
708 	return damon_register_ops(&ops_fvaddr);
709 };
710 
711 subsys_initcall(damon_va_initcall);
712 
713 #include "vaddr-test.h"
714