xref: /linux/mm/damon/core.c (revision f4e98954234b104c23902ee5bb4e59be6f9904a7)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Data Access Monitor
4  *
5  * Author: SeongJae Park <sj@kernel.org>
6  */
7 
8 #define pr_fmt(fmt) "damon: " fmt
9 
10 #include <linux/damon.h>
11 #include <linux/delay.h>
12 #include <linux/kthread.h>
13 #include <linux/memcontrol.h>
14 #include <linux/mm.h>
15 #include <linux/psi.h>
16 #include <linux/sched.h>
17 #include <linux/slab.h>
18 #include <linux/string.h>
19 #include <linux/string_choices.h>
20 
21 /* for damon_get_folio() used by node eligible memory metrics */
22 #include "ops-common.h"
23 
24 #define CREATE_TRACE_POINTS
25 #include <trace/events/damon.h>
26 
27 static DEFINE_MUTEX(damon_lock);
28 static int nr_running_ctxs;
29 static bool running_exclusive_ctxs;
30 
31 static DEFINE_MUTEX(damon_ops_lock);
32 static struct damon_operations damon_registered_ops[NR_DAMON_OPS];
33 
34 static struct kmem_cache *damon_region_cache __ro_after_init;
35 
36 /* Should be called under damon_ops_lock with id smaller than NR_DAMON_OPS */
37 static bool __damon_is_registered_ops(enum damon_ops_id id)
38 {
39 	struct damon_operations empty_ops = {};
40 
41 	if (!memcmp(&empty_ops, &damon_registered_ops[id], sizeof(empty_ops)))
42 		return false;
43 	return true;
44 }
45 
46 /**
47  * damon_is_registered_ops() - Check if a given damon_operations is registered.
48  * @id:	Id of the damon_operations to check if registered.
49  *
50  * Return: true if the ops is set, false otherwise.
51  */
52 bool damon_is_registered_ops(enum damon_ops_id id)
53 {
54 	bool registered;
55 
56 	if (id >= NR_DAMON_OPS)
57 		return false;
58 	mutex_lock(&damon_ops_lock);
59 	registered = __damon_is_registered_ops(id);
60 	mutex_unlock(&damon_ops_lock);
61 	return registered;
62 }
63 
64 /**
65  * damon_register_ops() - Register a monitoring operations set to DAMON.
66  * @ops:	monitoring operations set to register.
67  *
68  * This function registers a monitoring operations set of valid &struct
69  * damon_operations->id so that others can find and use them later.
70  *
71  * Return: 0 on success, negative error code otherwise.
72  */
73 int damon_register_ops(struct damon_operations *ops)
74 {
75 	int err = 0;
76 
77 	if (ops->id >= NR_DAMON_OPS)
78 		return -EINVAL;
79 
80 	mutex_lock(&damon_ops_lock);
81 	/* Fail for already registered ops */
82 	if (__damon_is_registered_ops(ops->id))
83 		err = -EINVAL;
84 	else
85 		damon_registered_ops[ops->id] = *ops;
86 	mutex_unlock(&damon_ops_lock);
87 	return err;
88 }
89 
90 /**
91  * damon_select_ops() - Select a monitoring operations to use with the context.
92  * @ctx:	monitoring context to use the operations.
93  * @id:		id of the registered monitoring operations to select.
94  *
95  * This function finds registered monitoring operations set of @id and make
96  * @ctx to use it.
97  *
98  * Return: 0 on success, negative error code otherwise.
99  */
100 int damon_select_ops(struct damon_ctx *ctx, enum damon_ops_id id)
101 {
102 	int err = 0;
103 
104 	if (id >= NR_DAMON_OPS)
105 		return -EINVAL;
106 
107 	mutex_lock(&damon_ops_lock);
108 	if (!__damon_is_registered_ops(id))
109 		err = -EINVAL;
110 	else
111 		ctx->ops = damon_registered_ops[id];
112 	mutex_unlock(&damon_ops_lock);
113 	return err;
114 }
115 
116 struct damon_filter *damon_new_filter(enum damon_filter_type type,
117 		bool matching, bool allow)
118 {
119 	struct damon_filter *filter;
120 
121 	filter = kmalloc_obj(*filter);
122 	if (!filter)
123 		return NULL;
124 	filter->type = type;
125 	filter->matching = matching;
126 	filter->allow = allow;
127 	INIT_LIST_HEAD(&filter->list);
128 	return filter;
129 }
130 
131 void damon_add_filter(struct damon_probe *p, struct damon_filter *f)
132 {
133 	list_add_tail(&f->list, &p->filters);
134 }
135 
136 static void damon_del_filter(struct damon_filter *f)
137 {
138 	list_del(&f->list);
139 }
140 
141 static void damon_free_filter(struct damon_filter *f)
142 {
143 	kfree(f);
144 }
145 
146 static void damon_destroy_filter(struct damon_filter *f)
147 {
148 	damon_del_filter(f);
149 	damon_free_filter(f);
150 }
151 
152 static struct damon_filter *damon_nth_filter(int n, struct damon_probe *p)
153 {
154 	struct damon_filter *f;
155 	int i = 0;
156 
157 	damon_for_each_filter(f, p) {
158 		if (i++ == n)
159 			return f;
160 	}
161 	return NULL;
162 }
163 
164 struct damon_probe *damon_new_probe(void)
165 {
166 	struct damon_probe *p;
167 
168 	p = kmalloc_obj(*p);
169 	if (!p)
170 		return NULL;
171 	INIT_LIST_HEAD(&p->filters);
172 	INIT_LIST_HEAD(&p->list);
173 	return p;
174 }
175 
176 void damon_add_probe(struct damon_ctx *ctx, struct damon_probe *probe)
177 {
178 	list_add_tail(&probe->list, &ctx->probes);
179 }
180 
181 static void damon_del_probe(struct damon_probe *p)
182 {
183 	list_del(&p->list);
184 }
185 
186 static void damon_free_probe(struct damon_probe *p)
187 {
188 	struct damon_filter *f, *next;
189 
190 	damon_for_each_filter_safe(f, next, p)
191 		damon_free_filter(f);
192 	kfree(p);
193 }
194 
195 static void damon_destroy_probe(struct damon_probe *p)
196 {
197 	damon_del_probe(p);
198 	damon_free_probe(p);
199 }
200 
201 static struct damon_probe *damon_nth_probe(int n, struct damon_ctx *ctx)
202 {
203 	struct damon_probe *p;
204 	int i = 0;
205 
206 	damon_for_each_probe(p, ctx) {
207 		if (i++ == n)
208 			return p;
209 	}
210 	return NULL;
211 }
212 
213 #ifdef CONFIG_DAMON_DEBUG_SANITY
214 static void damon_verify_new_region(unsigned long start, unsigned long end)
215 {
216 	WARN_ONCE(start >= end, "start %lu >= end %lu\n", start, end);
217 }
218 #else
219 static void damon_verify_new_region(unsigned long start, unsigned long end)
220 {
221 }
222 #endif
223 
224 /*
225  * Construct a damon_region struct
226  *
227  * Returns the pointer to the new struct if success, or NULL otherwise
228  */
229 struct damon_region *damon_new_region(unsigned long start, unsigned long end)
230 {
231 	struct damon_region *region;
232 	int i;
233 
234 	damon_verify_new_region(start, end);
235 	region = kmem_cache_alloc(damon_region_cache, GFP_KERNEL);
236 	if (!region)
237 		return NULL;
238 
239 	region->ar.start = start;
240 	region->ar.end = end;
241 	region->nr_accesses = 0;
242 	region->nr_accesses_bp = 0;
243 	for (i = 0; i < DAMON_MAX_PROBES; i++)
244 		region->probe_hits[i] = 0;
245 	INIT_LIST_HEAD(&region->list);
246 
247 	region->age = 0;
248 	region->last_nr_accesses = 0;
249 
250 	return region;
251 }
252 
253 void damon_add_region(struct damon_region *r, struct damon_target *t)
254 {
255 	list_add_tail(&r->list, &t->regions_list);
256 	t->nr_regions++;
257 }
258 
259 #ifdef CONFIG_DAMON_DEBUG_SANITY
260 static void damon_verify_del_region(struct damon_target *t)
261 {
262 	WARN_ONCE(t->nr_regions == 0, "t->nr_regions == 0\n");
263 }
264 #else
265 static void damon_verify_del_region(struct damon_target *t)
266 {
267 }
268 #endif
269 
270 static void damon_del_region(struct damon_region *r, struct damon_target *t)
271 {
272 	damon_verify_del_region(t);
273 
274 	list_del(&r->list);
275 	t->nr_regions--;
276 }
277 
278 static void damon_free_region(struct damon_region *r)
279 {
280 	kmem_cache_free(damon_region_cache, r);
281 }
282 
283 void damon_destroy_region(struct damon_region *r, struct damon_target *t)
284 {
285 	damon_del_region(r, t);
286 	damon_free_region(r);
287 }
288 
289 static bool damon_is_last_region(struct damon_region *r,
290 		struct damon_target *t)
291 {
292 	return list_is_last(&r->list, &t->regions_list);
293 }
294 
295 /*
296  * Check whether a region is intersecting an address range
297  *
298  * Returns true if it is.
299  */
300 static bool damon_intersect(struct damon_region *r,
301 		struct damon_addr_range *re)
302 {
303 	return !(r->ar.end <= re->start || re->end <= r->ar.start);
304 }
305 
306 /*
307  * Fill holes in regions with new regions.
308  */
309 static int damon_fill_regions_holes(struct damon_region *first,
310 		struct damon_region *last, struct damon_target *t)
311 {
312 	struct damon_region *r = first;
313 
314 	damon_for_each_region_from(r, t) {
315 		struct damon_region *next, *newr;
316 
317 		if (r == last)
318 			break;
319 		next = damon_next_region(r);
320 		if (r->ar.end != next->ar.start) {
321 			newr = damon_new_region(r->ar.end, next->ar.start);
322 			if (!newr)
323 				return -ENOMEM;
324 			damon_insert_region(newr, r, next, t);
325 		}
326 	}
327 	return 0;
328 }
329 
330 /*
331  * damon_set_regions() - Set regions of a target for given address ranges.
332  * @t:		the given target.
333  * @ranges:	array of new monitoring target ranges.
334  * @nr_ranges:	length of @ranges.
335  * @min_region_sz:	minimum region size.
336  *
337  * This function adds new regions to, or modify existing regions of a
338  * monitoring target to fit in specific ranges.
339  *
340  * Return: 0 if success, or negative error code otherwise.
341  */
342 int damon_set_regions(struct damon_target *t, struct damon_addr_range *ranges,
343 		unsigned int nr_ranges, unsigned long min_region_sz)
344 {
345 	struct damon_region *r, *next;
346 	unsigned int i;
347 	int err;
348 
349 	/* Remove regions which are not in the new ranges */
350 	damon_for_each_region_safe(r, next, t) {
351 		for (i = 0; i < nr_ranges; i++) {
352 			if (damon_intersect(r, &ranges[i]))
353 				break;
354 		}
355 		if (i == nr_ranges)
356 			damon_destroy_region(r, t);
357 	}
358 
359 	r = damon_first_region(t);
360 	/* Add new regions or resize existing regions to fit in the ranges */
361 	for (i = 0; i < nr_ranges; i++) {
362 		struct damon_region *first = NULL, *last, *newr;
363 		struct damon_addr_range *range;
364 
365 		range = &ranges[i];
366 		/* Get the first/last regions intersecting with the range */
367 		damon_for_each_region_from(r, t) {
368 			if (damon_intersect(r, range)) {
369 				if (!first)
370 					first = r;
371 				last = r;
372 			}
373 			if (r->ar.start >= range->end)
374 				break;
375 		}
376 		if (!first) {
377 			/* no region intersects with this range */
378 			newr = damon_new_region(
379 					ALIGN_DOWN(range->start,
380 						min_region_sz),
381 					ALIGN(range->end, min_region_sz));
382 			if (!newr)
383 				return -ENOMEM;
384 			damon_insert_region(newr, damon_prev_region(r), r, t);
385 		} else {
386 			/* resize intersecting regions to fit in this range */
387 			first->ar.start = ALIGN_DOWN(range->start,
388 					min_region_sz);
389 			last->ar.end = ALIGN(range->end, min_region_sz);
390 
391 			/* fill possible holes in the range */
392 			err = damon_fill_regions_holes(first, last, t);
393 			if (err)
394 				return err;
395 		}
396 	}
397 	return 0;
398 }
399 
400 struct damos_filter *damos_new_filter(enum damos_filter_type type,
401 		bool matching, bool allow)
402 {
403 	struct damos_filter *filter;
404 
405 	filter = kmalloc_obj(*filter);
406 	if (!filter)
407 		return NULL;
408 	filter->type = type;
409 	filter->matching = matching;
410 	filter->allow = allow;
411 	INIT_LIST_HEAD(&filter->list);
412 	return filter;
413 }
414 
415 /**
416  * damos_filter_for_ops() - Return if the filter is ops-handled one.
417  * @type:	type of the filter.
418  *
419  * Return: true if the filter of @type needs to be handled by ops layer, false
420  * otherwise.
421  */
422 bool damos_filter_for_ops(enum damos_filter_type type)
423 {
424 	switch (type) {
425 	case DAMOS_FILTER_TYPE_ADDR:
426 	case DAMOS_FILTER_TYPE_TARGET:
427 		return false;
428 	default:
429 		break;
430 	}
431 	return true;
432 }
433 
434 void damos_add_filter(struct damos *s, struct damos_filter *f)
435 {
436 	if (damos_filter_for_ops(f->type))
437 		list_add_tail(&f->list, &s->ops_filters);
438 	else
439 		list_add_tail(&f->list, &s->core_filters);
440 }
441 
442 static void damos_del_filter(struct damos_filter *f)
443 {
444 	list_del(&f->list);
445 }
446 
447 static void damos_free_filter(struct damos_filter *f)
448 {
449 	kfree(f);
450 }
451 
452 void damos_destroy_filter(struct damos_filter *f)
453 {
454 	damos_del_filter(f);
455 	damos_free_filter(f);
456 }
457 
458 struct damos_quota_goal *damos_new_quota_goal(
459 		enum damos_quota_goal_metric metric,
460 		unsigned long target_value)
461 {
462 	struct damos_quota_goal *goal;
463 
464 	goal = kmalloc_obj(*goal);
465 	if (!goal)
466 		return NULL;
467 	goal->metric = metric;
468 	goal->target_value = target_value;
469 	INIT_LIST_HEAD(&goal->list);
470 	return goal;
471 }
472 
473 void damos_add_quota_goal(struct damos_quota *q, struct damos_quota_goal *g)
474 {
475 	list_add_tail(&g->list, &q->goals);
476 }
477 
478 static void damos_del_quota_goal(struct damos_quota_goal *g)
479 {
480 	list_del(&g->list);
481 }
482 
483 static void damos_free_quota_goal(struct damos_quota_goal *g)
484 {
485 	kfree(g);
486 }
487 
488 void damos_destroy_quota_goal(struct damos_quota_goal *g)
489 {
490 	damos_del_quota_goal(g);
491 	damos_free_quota_goal(g);
492 }
493 
494 static bool damos_quota_goals_empty(struct damos_quota *q)
495 {
496 	return list_empty(&q->goals);
497 }
498 
499 /* initialize fields of @quota that normally API users wouldn't set */
500 static struct damos_quota *damos_quota_init(struct damos_quota *quota)
501 {
502 	quota->esz = 0;
503 	quota->total_charged_sz = 0;
504 	quota->total_charged_ns = 0;
505 	quota->charged_sz = 0;
506 	quota->charged_from = 0;
507 	quota->charge_target_from = NULL;
508 	quota->charge_addr_from = 0;
509 	quota->esz_bp = 0;
510 	return quota;
511 }
512 
513 struct damos *damon_new_scheme(struct damos_access_pattern *pattern,
514 			enum damos_action action,
515 			unsigned long apply_interval_us,
516 			struct damos_quota *quota,
517 			struct damos_watermarks *wmarks,
518 			int target_nid)
519 {
520 	struct damos *scheme;
521 
522 	scheme = kmalloc_obj(*scheme);
523 	if (!scheme)
524 		return NULL;
525 	scheme->pattern = *pattern;
526 	scheme->action = action;
527 	scheme->apply_interval_us = apply_interval_us;
528 	/*
529 	 * next_apply_sis will be set when kdamond starts.  While kdamond is
530 	 * running, it will also updated when it is added to the DAMON context,
531 	 * or damon_attrs are updated.
532 	 */
533 	scheme->next_apply_sis = 0;
534 	scheme->walk_completed = false;
535 	INIT_LIST_HEAD(&scheme->core_filters);
536 	INIT_LIST_HEAD(&scheme->ops_filters);
537 	scheme->stat = (struct damos_stat){};
538 	scheme->max_nr_snapshots = 0;
539 	INIT_LIST_HEAD(&scheme->list);
540 
541 	scheme->quota = *(damos_quota_init(quota));
542 	/* quota.goals should be separately set by caller */
543 	INIT_LIST_HEAD(&scheme->quota.goals);
544 
545 	scheme->wmarks = *wmarks;
546 	scheme->wmarks.activated = true;
547 
548 	scheme->migrate_dests = (struct damos_migrate_dests){};
549 	scheme->target_nid = target_nid;
550 
551 	return scheme;
552 }
553 
554 static void damos_set_next_apply_sis(struct damos *s, struct damon_ctx *ctx)
555 {
556 	unsigned long sample_interval = ctx->attrs.sample_interval ?
557 		ctx->attrs.sample_interval : 1;
558 	unsigned long apply_interval = s->apply_interval_us ?
559 		s->apply_interval_us : ctx->attrs.aggr_interval;
560 
561 	s->next_apply_sis = ctx->passed_sample_intervals +
562 		apply_interval / sample_interval;
563 }
564 
565 void damon_add_scheme(struct damon_ctx *ctx, struct damos *s)
566 {
567 	list_add_tail(&s->list, &ctx->schemes);
568 	damos_set_next_apply_sis(s, ctx);
569 }
570 
571 static void damon_del_scheme(struct damos *s)
572 {
573 	list_del(&s->list);
574 }
575 
576 static void damon_free_scheme(struct damos *s)
577 {
578 	kfree(s);
579 }
580 
581 void damon_destroy_scheme(struct damos *s)
582 {
583 	struct damos_quota_goal *g, *g_next;
584 	struct damos_filter *f, *next;
585 
586 	damos_for_each_quota_goal_safe(g, g_next, &s->quota)
587 		damos_destroy_quota_goal(g);
588 
589 	damos_for_each_core_filter_safe(f, next, s)
590 		damos_destroy_filter(f);
591 
592 	damos_for_each_ops_filter_safe(f, next, s)
593 		damos_destroy_filter(f);
594 
595 	kfree(s->migrate_dests.node_id_arr);
596 	kfree(s->migrate_dests.weight_arr);
597 	damon_del_scheme(s);
598 	damon_free_scheme(s);
599 }
600 
601 /*
602  * Construct a damon_target struct
603  *
604  * Returns the pointer to the new struct if success, or NULL otherwise
605  */
606 struct damon_target *damon_new_target(void)
607 {
608 	struct damon_target *t;
609 
610 	t = kmalloc_obj(*t);
611 	if (!t)
612 		return NULL;
613 
614 	t->pid = NULL;
615 	t->nr_regions = 0;
616 	INIT_LIST_HEAD(&t->regions_list);
617 	INIT_LIST_HEAD(&t->list);
618 	t->obsolete = false;
619 
620 	return t;
621 }
622 
623 void damon_add_target(struct damon_ctx *ctx, struct damon_target *t)
624 {
625 	list_add_tail(&t->list, &ctx->adaptive_targets);
626 }
627 
628 bool damon_targets_empty(struct damon_ctx *ctx)
629 {
630 	return list_empty(&ctx->adaptive_targets);
631 }
632 
633 static void damon_del_target(struct damon_target *t)
634 {
635 	list_del(&t->list);
636 }
637 
638 void damon_free_target(struct damon_target *t)
639 {
640 	struct damon_region *r, *next;
641 
642 	damon_for_each_region_safe(r, next, t)
643 		damon_free_region(r);
644 	kfree(t);
645 }
646 
647 void damon_destroy_target(struct damon_target *t, struct damon_ctx *ctx)
648 {
649 
650 	if (ctx && ctx->ops.cleanup_target)
651 		ctx->ops.cleanup_target(t);
652 
653 	damon_del_target(t);
654 	damon_free_target(t);
655 }
656 
657 #ifdef CONFIG_DAMON_DEBUG_SANITY
658 static void damon_verify_nr_regions(struct damon_target *t)
659 {
660 	struct damon_region *r;
661 	unsigned int count = 0;
662 
663 	damon_for_each_region(r, t)
664 		count++;
665 	WARN_ONCE(count != t->nr_regions, "t->nr_regions (%u) != count (%u)\n",
666 			t->nr_regions, count);
667 }
668 #else
669 static void damon_verify_nr_regions(struct damon_target *t)
670 {
671 }
672 #endif
673 
674 unsigned int damon_nr_regions(struct damon_target *t)
675 {
676 	damon_verify_nr_regions(t);
677 
678 	return t->nr_regions;
679 }
680 
681 struct damon_ctx *damon_new_ctx(void)
682 {
683 	struct damon_ctx *ctx;
684 
685 	ctx = kzalloc_obj(*ctx);
686 	if (!ctx)
687 		return NULL;
688 
689 	init_completion(&ctx->kdamond_started);
690 
691 	ctx->attrs.sample_interval = 5 * 1000;
692 	ctx->attrs.aggr_interval = 100 * 1000;
693 	ctx->attrs.ops_update_interval = 60 * 1000 * 1000;
694 
695 	ctx->passed_sample_intervals = 0;
696 	/* These will be set from kdamond_init_ctx() */
697 	ctx->next_aggregation_sis = 0;
698 	ctx->next_ops_update_sis = 0;
699 
700 	mutex_init(&ctx->kdamond_lock);
701 	INIT_LIST_HEAD(&ctx->call_controls);
702 	mutex_init(&ctx->call_controls_lock);
703 	mutex_init(&ctx->walk_control_lock);
704 
705 	ctx->attrs.min_nr_regions = 10;
706 	ctx->attrs.max_nr_regions = 1000;
707 
708 	INIT_LIST_HEAD(&ctx->probes);
709 
710 	ctx->addr_unit = 1;
711 	ctx->min_region_sz = DAMON_MIN_REGION_SZ;
712 
713 	INIT_LIST_HEAD(&ctx->adaptive_targets);
714 	INIT_LIST_HEAD(&ctx->schemes);
715 
716 	prandom_seed_state(&ctx->rnd_state, get_random_u64());
717 
718 	return ctx;
719 }
720 
721 static void damon_destroy_targets(struct damon_ctx *ctx)
722 {
723 	struct damon_target *t, *next_t;
724 
725 	damon_for_each_target_safe(t, next_t, ctx)
726 		damon_destroy_target(t, ctx);
727 }
728 
729 void damon_destroy_ctx(struct damon_ctx *ctx)
730 {
731 	struct damos *s, *next_s;
732 	struct damon_probe *p, *next_p;
733 
734 	damon_destroy_targets(ctx);
735 
736 	damon_for_each_scheme_safe(s, next_s, ctx)
737 		damon_destroy_scheme(s);
738 
739 	damon_for_each_probe_safe(p, next_p, ctx)
740 		damon_destroy_probe(p);
741 
742 	kfree(ctx);
743 }
744 
745 static bool damon_attrs_equals(const struct damon_attrs *attrs1,
746 		const struct damon_attrs *attrs2)
747 {
748 	const struct damon_intervals_goal *ig1 = &attrs1->intervals_goal;
749 	const struct damon_intervals_goal *ig2 = &attrs2->intervals_goal;
750 
751 	return attrs1->sample_interval == attrs2->sample_interval &&
752 		attrs1->aggr_interval == attrs2->aggr_interval &&
753 		attrs1->ops_update_interval == attrs2->ops_update_interval &&
754 		attrs1->min_nr_regions == attrs2->min_nr_regions &&
755 		attrs1->max_nr_regions == attrs2->max_nr_regions &&
756 		ig1->access_bp == ig2->access_bp &&
757 		ig1->aggrs == ig2->aggrs &&
758 		ig1->min_sample_us == ig2->min_sample_us &&
759 		ig1->max_sample_us == ig2->max_sample_us;
760 }
761 
762 static unsigned int damon_age_for_new_attrs(unsigned int age,
763 		struct damon_attrs *old_attrs, struct damon_attrs *new_attrs)
764 {
765 	return age * old_attrs->aggr_interval / new_attrs->aggr_interval;
766 }
767 
768 /* convert access ratio in bp (per 10,000) to nr_accesses */
769 static unsigned int damon_accesses_bp_to_nr_accesses(
770 		unsigned int accesses_bp, struct damon_attrs *attrs)
771 {
772 	return accesses_bp * damon_max_nr_accesses(attrs) / 10000;
773 }
774 
775 /*
776  * Convert nr_accesses to access ratio in bp (per 10,000).
777  *
778  * Callers should ensure attrs.aggr_interval is not zero, like
779  * damon_update_monitoring_results() does .  Otherwise, divide-by-zero would
780  * happen.
781  */
782 static unsigned int damon_nr_accesses_to_accesses_bp(
783 		unsigned int nr_accesses, struct damon_attrs *attrs)
784 {
785 	return mult_frac(nr_accesses, 10000, damon_max_nr_accesses(attrs));
786 }
787 
788 static unsigned int damon_nr_accesses_for_new_attrs(unsigned int nr_accesses,
789 		struct damon_attrs *old_attrs, struct damon_attrs *new_attrs)
790 {
791 	return damon_accesses_bp_to_nr_accesses(
792 			damon_nr_accesses_to_accesses_bp(
793 				nr_accesses, old_attrs),
794 			new_attrs);
795 }
796 
797 static void damon_update_monitoring_result(struct damon_region *r,
798 		struct damon_attrs *old_attrs, struct damon_attrs *new_attrs,
799 		bool aggregating)
800 {
801 	if (!aggregating) {
802 		r->nr_accesses = damon_nr_accesses_for_new_attrs(
803 				r->nr_accesses, old_attrs, new_attrs);
804 		r->nr_accesses_bp = r->nr_accesses * 10000;
805 	} else {
806 		/*
807 		 * if this is called in the middle of the aggregation, reset
808 		 * the aggregations we made so far for this aggregation
809 		 * interval.  In other words, make the status like
810 		 * kdamond_reset_aggregated() is called.
811 		 */
812 		r->last_nr_accesses = damon_nr_accesses_for_new_attrs(
813 				r->last_nr_accesses, old_attrs, new_attrs);
814 		r->nr_accesses_bp = r->last_nr_accesses * 10000;
815 		r->nr_accesses = 0;
816 	}
817 	r->age = damon_age_for_new_attrs(r->age, old_attrs, new_attrs);
818 }
819 
820 /*
821  * region->nr_accesses is the number of sampling intervals in the last
822  * aggregation interval that access to the region has found, and region->age is
823  * the number of aggregation intervals that its access pattern has maintained.
824  * For the reason, the real meaning of the two fields depend on current
825  * sampling interval and aggregation interval.  This function updates
826  * ->nr_accesses and ->age of given damon_ctx's regions for new damon_attrs.
827  */
828 static void damon_update_monitoring_results(struct damon_ctx *ctx,
829 		struct damon_attrs *new_attrs, bool aggregating)
830 {
831 	struct damon_attrs *old_attrs = &ctx->attrs;
832 	struct damon_target *t;
833 	struct damon_region *r;
834 
835 	/* if any interval is zero, simply forgive conversion */
836 	if (!old_attrs->sample_interval || !old_attrs->aggr_interval ||
837 			!new_attrs->sample_interval ||
838 			!new_attrs->aggr_interval)
839 		return;
840 
841 	damon_for_each_target(t, ctx)
842 		damon_for_each_region(r, t)
843 			damon_update_monitoring_result(
844 					r, old_attrs, new_attrs, aggregating);
845 }
846 
847 /*
848  * damon_valid_intervals_goal() - return if the intervals goal of @attrs is
849  * valid.
850  */
851 static bool damon_valid_intervals_goal(struct damon_attrs *attrs)
852 {
853 	struct damon_intervals_goal *goal = &attrs->intervals_goal;
854 
855 	/* tuning is disabled */
856 	if (!goal->aggrs)
857 		return true;
858 	if (goal->min_sample_us > goal->max_sample_us)
859 		return false;
860 	if (attrs->sample_interval < goal->min_sample_us ||
861 			goal->max_sample_us < attrs->sample_interval)
862 		return false;
863 	return true;
864 }
865 
866 /**
867  * damon_set_attrs() - Set attributes for the monitoring.
868  * @ctx:		monitoring context
869  * @attrs:		monitoring attributes
870  *
871  * This function updates monitoring results and next monitoring/damos operation
872  * schedules.  Because those are periodically updated by kdamond, this should
873  * be called from a safe contexts.  Such contexts include damon_ctx setup time
874  * while the kdamond is not yet started, and inside of kdamond_fn().
875  *
876  * In detail, all DAMON API callers directly call this function for initial
877  * setup of damon_ctx before calling damon_start().  Some of the API callers
878  * also indirectly call this function via damon_call() -> damon_commit() for
879  * online parameters updates.  Finally, kdamond_fn() itself use this for
880  * applying auto-tuned monitoring intervals.
881  *
882  * Every time interval is in micro-seconds.
883  *
884  * Return: 0 on success, negative error code otherwise.
885  */
886 int damon_set_attrs(struct damon_ctx *ctx, struct damon_attrs *attrs)
887 {
888 	unsigned long sample_interval = attrs->sample_interval ?
889 		attrs->sample_interval : 1;
890 	struct damos *s;
891 	bool aggregating = ctx->passed_sample_intervals <
892 		ctx->next_aggregation_sis;
893 
894 	if (!damon_valid_intervals_goal(attrs))
895 		return -EINVAL;
896 
897 	if (attrs->min_nr_regions < 3)
898 		return -EINVAL;
899 	if (attrs->min_nr_regions > attrs->max_nr_regions)
900 		return -EINVAL;
901 	if (attrs->sample_interval > attrs->aggr_interval)
902 		return -EINVAL;
903 
904 	/* calls from core-external doesn't set this. */
905 	if (!attrs->aggr_samples)
906 		attrs->aggr_samples = attrs->aggr_interval / sample_interval;
907 
908 	ctx->next_aggregation_sis = ctx->passed_sample_intervals +
909 		attrs->aggr_interval / sample_interval;
910 	ctx->next_ops_update_sis = ctx->passed_sample_intervals +
911 		attrs->ops_update_interval / sample_interval;
912 
913 	damon_update_monitoring_results(ctx, attrs, aggregating);
914 	ctx->attrs = *attrs;
915 
916 	damon_for_each_scheme(s, ctx)
917 		damos_set_next_apply_sis(s, ctx);
918 
919 	return 0;
920 }
921 
922 /**
923  * damon_set_schemes() - Set data access monitoring based operation schemes.
924  * @ctx:	monitoring context
925  * @schemes:	array of the schemes
926  * @nr_schemes:	number of entries in @schemes
927  *
928  * This function should not be called while the kdamond of the context is
929  * running.
930  */
931 void damon_set_schemes(struct damon_ctx *ctx, struct damos **schemes,
932 			ssize_t nr_schemes)
933 {
934 	struct damos *s, *next;
935 	ssize_t i;
936 
937 	damon_for_each_scheme_safe(s, next, ctx)
938 		damon_destroy_scheme(s);
939 	for (i = 0; i < nr_schemes; i++)
940 		damon_add_scheme(ctx, schemes[i]);
941 }
942 
943 static struct damos_quota_goal *damos_nth_quota_goal(
944 		int n, struct damos_quota *q)
945 {
946 	struct damos_quota_goal *goal;
947 	int i = 0;
948 
949 	damos_for_each_quota_goal(goal, q) {
950 		if (i++ == n)
951 			return goal;
952 	}
953 	return NULL;
954 }
955 
956 static void damos_commit_quota_goal_union(
957 		struct damos_quota_goal *dst, struct damos_quota_goal *src)
958 {
959 	switch (dst->metric) {
960 	case DAMOS_QUOTA_NODE_MEM_USED_BP:
961 	case DAMOS_QUOTA_NODE_MEM_FREE_BP:
962 		dst->nid = src->nid;
963 		break;
964 	case DAMOS_QUOTA_NODE_MEMCG_USED_BP:
965 	case DAMOS_QUOTA_NODE_MEMCG_FREE_BP:
966 		dst->nid = src->nid;
967 		dst->memcg_id = src->memcg_id;
968 		break;
969 	default:
970 		break;
971 	}
972 }
973 
974 static void damos_commit_quota_goal(
975 		struct damos_quota_goal *dst, struct damos_quota_goal *src)
976 {
977 	dst->metric = src->metric;
978 	dst->target_value = src->target_value;
979 	if (dst->metric == DAMOS_QUOTA_USER_INPUT)
980 		dst->current_value = src->current_value;
981 	/* keep last_psi_total as is, since it will be updated in next cycle */
982 	damos_commit_quota_goal_union(dst, src);
983 }
984 
985 /**
986  * damos_commit_quota_goals() - Commit DAMOS quota goals to another quota.
987  * @dst:	The commit destination DAMOS quota.
988  * @src:	The commit source DAMOS quota.
989  *
990  * Copies user-specified parameters for quota goals from @src to @dst.  Users
991  * should use this function for quota goals-level parameters update of running
992  * DAMON contexts, instead of manual in-place updates.
993  *
994  * This function should be called from parameters-update safe context, like
995  * damon_call().
996  */
997 int damos_commit_quota_goals(struct damos_quota *dst, struct damos_quota *src)
998 {
999 	struct damos_quota_goal *dst_goal, *next, *src_goal, *new_goal;
1000 	int i = 0, j = 0;
1001 
1002 	damos_for_each_quota_goal_safe(dst_goal, next, dst) {
1003 		src_goal = damos_nth_quota_goal(i++, src);
1004 		if (src_goal)
1005 			damos_commit_quota_goal(dst_goal, src_goal);
1006 		else
1007 			damos_destroy_quota_goal(dst_goal);
1008 	}
1009 	damos_for_each_quota_goal_safe(src_goal, next, src) {
1010 		if (j++ < i)
1011 			continue;
1012 		new_goal = damos_new_quota_goal(
1013 				src_goal->metric, src_goal->target_value);
1014 		if (!new_goal)
1015 			return -ENOMEM;
1016 		damos_commit_quota_goal(new_goal, src_goal);
1017 		damos_add_quota_goal(dst, new_goal);
1018 	}
1019 	return 0;
1020 }
1021 
1022 static int damos_commit_quota(struct damos_quota *dst, struct damos_quota *src)
1023 {
1024 	int err;
1025 
1026 	dst->reset_interval = src->reset_interval;
1027 	dst->ms = src->ms;
1028 	dst->sz = src->sz;
1029 	err = damos_commit_quota_goals(dst, src);
1030 	if (err)
1031 		return err;
1032 	dst->goal_tuner = src->goal_tuner;
1033 	dst->fail_charge_num = src->fail_charge_num;
1034 	dst->fail_charge_denom = src->fail_charge_denom;
1035 	dst->weight_sz = src->weight_sz;
1036 	dst->weight_nr_accesses = src->weight_nr_accesses;
1037 	dst->weight_age = src->weight_age;
1038 	return 0;
1039 }
1040 
1041 static struct damos_filter *damos_nth_core_filter(int n, struct damos *s)
1042 {
1043 	struct damos_filter *filter;
1044 	int i = 0;
1045 
1046 	damos_for_each_core_filter(filter, s) {
1047 		if (i++ == n)
1048 			return filter;
1049 	}
1050 	return NULL;
1051 }
1052 
1053 static struct damos_filter *damos_nth_ops_filter(int n, struct damos *s)
1054 {
1055 	struct damos_filter *filter;
1056 	int i = 0;
1057 
1058 	damos_for_each_ops_filter(filter, s) {
1059 		if (i++ == n)
1060 			return filter;
1061 	}
1062 	return NULL;
1063 }
1064 
1065 static void damos_commit_filter_arg(
1066 		struct damos_filter *dst, struct damos_filter *src)
1067 {
1068 	switch (dst->type) {
1069 	case DAMOS_FILTER_TYPE_MEMCG:
1070 		dst->memcg_id = src->memcg_id;
1071 		break;
1072 	case DAMOS_FILTER_TYPE_ADDR:
1073 		dst->addr_range = src->addr_range;
1074 		break;
1075 	case DAMOS_FILTER_TYPE_TARGET:
1076 		dst->target_idx = src->target_idx;
1077 		break;
1078 	case DAMOS_FILTER_TYPE_HUGEPAGE_SIZE:
1079 		dst->sz_range = src->sz_range;
1080 		break;
1081 	default:
1082 		break;
1083 	}
1084 }
1085 
1086 static void damos_commit_filter(
1087 		struct damos_filter *dst, struct damos_filter *src)
1088 {
1089 	dst->type = src->type;
1090 	dst->matching = src->matching;
1091 	dst->allow = src->allow;
1092 	damos_commit_filter_arg(dst, src);
1093 }
1094 
1095 static int damos_commit_core_filters(struct damos *dst, struct damos *src)
1096 {
1097 	struct damos_filter *dst_filter, *next, *src_filter, *new_filter;
1098 	int i = 0, j = 0;
1099 
1100 	damos_for_each_core_filter_safe(dst_filter, next, dst) {
1101 		src_filter = damos_nth_core_filter(i++, src);
1102 		if (src_filter)
1103 			damos_commit_filter(dst_filter, src_filter);
1104 		else
1105 			damos_destroy_filter(dst_filter);
1106 	}
1107 
1108 	damos_for_each_core_filter_safe(src_filter, next, src) {
1109 		if (j++ < i)
1110 			continue;
1111 
1112 		new_filter = damos_new_filter(
1113 				src_filter->type, src_filter->matching,
1114 				src_filter->allow);
1115 		if (!new_filter)
1116 			return -ENOMEM;
1117 		damos_commit_filter_arg(new_filter, src_filter);
1118 		damos_add_filter(dst, new_filter);
1119 	}
1120 	return 0;
1121 }
1122 
1123 static int damos_commit_ops_filters(struct damos *dst, struct damos *src)
1124 {
1125 	struct damos_filter *dst_filter, *next, *src_filter, *new_filter;
1126 	int i = 0, j = 0;
1127 
1128 	damos_for_each_ops_filter_safe(dst_filter, next, dst) {
1129 		src_filter = damos_nth_ops_filter(i++, src);
1130 		if (src_filter)
1131 			damos_commit_filter(dst_filter, src_filter);
1132 		else
1133 			damos_destroy_filter(dst_filter);
1134 	}
1135 
1136 	damos_for_each_ops_filter_safe(src_filter, next, src) {
1137 		if (j++ < i)
1138 			continue;
1139 
1140 		new_filter = damos_new_filter(
1141 				src_filter->type, src_filter->matching,
1142 				src_filter->allow);
1143 		if (!new_filter)
1144 			return -ENOMEM;
1145 		damos_commit_filter_arg(new_filter, src_filter);
1146 		damos_add_filter(dst, new_filter);
1147 	}
1148 	return 0;
1149 }
1150 
1151 /**
1152  * damos_filters_default_reject() - decide whether to reject memory that didn't
1153  *				    match with any given filter.
1154  * @filters:	Given DAMOS filters of a group.
1155  */
1156 static bool damos_filters_default_reject(struct list_head *filters)
1157 {
1158 	struct damos_filter *last_filter;
1159 
1160 	if (list_empty(filters))
1161 		return false;
1162 	last_filter = list_last_entry(filters, struct damos_filter, list);
1163 	return last_filter->allow;
1164 }
1165 
1166 static void damos_set_filters_default_reject(struct damos *s)
1167 {
1168 	if (!list_empty(&s->ops_filters))
1169 		s->core_filters_default_reject = false;
1170 	else
1171 		s->core_filters_default_reject =
1172 			damos_filters_default_reject(&s->core_filters);
1173 	s->ops_filters_default_reject =
1174 		damos_filters_default_reject(&s->ops_filters);
1175 }
1176 
1177 /*
1178  * damos_commit_dests() - Copy migration destinations from @src to @dst.
1179  * @dst:	Destination structure to update.
1180  * @src:	Source structure to copy from.
1181  *
1182  * If the number of destinations has changed, the old arrays in @dst are freed
1183  * and new ones are allocated.  On success, @dst contains a full copy of
1184  * @src's arrays and count.
1185  *
1186  * On allocation failure, @dst is left in a partially torn-down state: its
1187  * arrays may be NULL and @nr_dests may not reflect the actual allocation
1188  * sizes.  The structure remains safe to deallocate via damon_destroy_scheme(),
1189  * but callers must not reuse @dst for further commits — it should be
1190  * discarded.
1191  *
1192  * Return: 0 on success, -ENOMEM on allocation failure.
1193  */
1194 static int damos_commit_dests(struct damos_migrate_dests *dst,
1195 		struct damos_migrate_dests *src)
1196 {
1197 	if (dst->nr_dests != src->nr_dests) {
1198 		kfree(dst->node_id_arr);
1199 		kfree(dst->weight_arr);
1200 
1201 		dst->node_id_arr = kmalloc_array(src->nr_dests,
1202 			sizeof(*dst->node_id_arr), GFP_KERNEL);
1203 		if (!dst->node_id_arr) {
1204 			dst->weight_arr = NULL;
1205 			return -ENOMEM;
1206 		}
1207 
1208 		dst->weight_arr = kmalloc_array(src->nr_dests,
1209 			sizeof(*dst->weight_arr), GFP_KERNEL);
1210 		if (!dst->weight_arr) {
1211 			/* ->node_id_arr will be freed by scheme destruction */
1212 			return -ENOMEM;
1213 		}
1214 	}
1215 
1216 	dst->nr_dests = src->nr_dests;
1217 	for (int i = 0; i < src->nr_dests; i++) {
1218 		dst->node_id_arr[i] = src->node_id_arr[i];
1219 		dst->weight_arr[i] = src->weight_arr[i];
1220 	}
1221 
1222 	return 0;
1223 }
1224 
1225 static int damos_commit_filters(struct damos *dst, struct damos *src)
1226 {
1227 	int err;
1228 
1229 	err = damos_commit_core_filters(dst, src);
1230 	if (err)
1231 		return err;
1232 	err = damos_commit_ops_filters(dst, src);
1233 	if (err)
1234 		return err;
1235 	damos_set_filters_default_reject(dst);
1236 	return 0;
1237 }
1238 
1239 static struct damos *damon_nth_scheme(int n, struct damon_ctx *ctx)
1240 {
1241 	struct damos *s;
1242 	int i = 0;
1243 
1244 	damon_for_each_scheme(s, ctx) {
1245 		if (i++ == n)
1246 			return s;
1247 	}
1248 	return NULL;
1249 }
1250 
1251 static int damos_commit(struct damos *dst, struct damos *src)
1252 {
1253 	int err;
1254 
1255 	dst->pattern = src->pattern;
1256 	dst->action = src->action;
1257 	dst->apply_interval_us = src->apply_interval_us;
1258 
1259 	err = damos_commit_quota(&dst->quota, &src->quota);
1260 	if (err)
1261 		return err;
1262 
1263 	dst->wmarks = src->wmarks;
1264 	dst->target_nid = src->target_nid;
1265 
1266 	err = damos_commit_dests(&dst->migrate_dests, &src->migrate_dests);
1267 	if (err)
1268 		return err;
1269 
1270 	err = damos_commit_filters(dst, src);
1271 	if (err)
1272 		return err;
1273 
1274 	dst->max_nr_snapshots = src->max_nr_snapshots;
1275 	return 0;
1276 }
1277 
1278 static int damon_commit_schemes(struct damon_ctx *dst, struct damon_ctx *src)
1279 {
1280 	struct damos *dst_scheme, *next, *src_scheme, *new_scheme;
1281 	int i = 0, j = 0, err;
1282 
1283 	damon_for_each_scheme_safe(dst_scheme, next, dst) {
1284 		src_scheme = damon_nth_scheme(i++, src);
1285 		if (src_scheme) {
1286 			err = damos_commit(dst_scheme, src_scheme);
1287 			if (err)
1288 				return err;
1289 		} else {
1290 			damon_destroy_scheme(dst_scheme);
1291 		}
1292 	}
1293 
1294 	damon_for_each_scheme_safe(src_scheme, next, src) {
1295 		if (j++ < i)
1296 			continue;
1297 		new_scheme = damon_new_scheme(&src_scheme->pattern,
1298 				src_scheme->action,
1299 				src_scheme->apply_interval_us,
1300 				&src_scheme->quota, &src_scheme->wmarks,
1301 				NUMA_NO_NODE);
1302 		if (!new_scheme)
1303 			return -ENOMEM;
1304 		err = damos_commit(new_scheme, src_scheme);
1305 		if (err) {
1306 			damon_destroy_scheme(new_scheme);
1307 			return err;
1308 		}
1309 		damon_add_scheme(dst, new_scheme);
1310 	}
1311 	return 0;
1312 }
1313 
1314 static struct damon_target *damon_nth_target(int n, struct damon_ctx *ctx)
1315 {
1316 	struct damon_target *t;
1317 	int i = 0;
1318 
1319 	damon_for_each_target(t, ctx) {
1320 		if (i++ == n)
1321 			return t;
1322 	}
1323 	return NULL;
1324 }
1325 
1326 /*
1327  * The caller should ensure the regions of @src are
1328  * 1. valid (end >= src) and
1329  * 2. sorted by starting address.
1330  *
1331  * If @src has no region, @dst keeps current regions.
1332  */
1333 static int damon_commit_target_regions(struct damon_target *dst,
1334 		struct damon_target *src, unsigned long src_min_region_sz)
1335 {
1336 	struct damon_region *src_region;
1337 	struct damon_addr_range *ranges;
1338 	int i = 0, err;
1339 
1340 	damon_for_each_region(src_region, src)
1341 		i++;
1342 	if (!i)
1343 		return 0;
1344 
1345 	ranges = kmalloc_objs(*ranges, i, GFP_KERNEL | __GFP_NOWARN);
1346 	if (!ranges)
1347 		return -ENOMEM;
1348 	i = 0;
1349 	damon_for_each_region(src_region, src)
1350 		ranges[i++] = src_region->ar;
1351 	err = damon_set_regions(dst, ranges, i, src_min_region_sz);
1352 	kfree(ranges);
1353 	return err;
1354 }
1355 
1356 static int damon_commit_target(
1357 		struct damon_target *dst, bool dst_has_pid,
1358 		struct damon_target *src, bool src_has_pid,
1359 		unsigned long src_min_region_sz)
1360 {
1361 	int err;
1362 
1363 	err = damon_commit_target_regions(dst, src, src_min_region_sz);
1364 	if (err)
1365 		return err;
1366 	if (dst_has_pid)
1367 		put_pid(dst->pid);
1368 	if (src_has_pid)
1369 		get_pid(src->pid);
1370 	dst->pid = src->pid;
1371 	return 0;
1372 }
1373 
1374 static int damon_commit_targets(
1375 		struct damon_ctx *dst, struct damon_ctx *src)
1376 {
1377 	struct damon_target *dst_target, *next, *src_target, *new_target;
1378 	int i = 0, j = 0, err;
1379 
1380 	damon_for_each_target_safe(dst_target, next, dst) {
1381 		src_target = damon_nth_target(i++, src);
1382 		/*
1383 		 * If src target is obsolete, do not commit the parameters to
1384 		 * the dst target, and further remove the dst target.
1385 		 */
1386 		if (src_target && !src_target->obsolete) {
1387 			err = damon_commit_target(
1388 					dst_target, damon_target_has_pid(dst),
1389 					src_target, damon_target_has_pid(src),
1390 					src->min_region_sz);
1391 			if (err)
1392 				return err;
1393 		} else {
1394 			struct damos *s;
1395 
1396 			damon_destroy_target(dst_target, dst);
1397 			damon_for_each_scheme(s, dst) {
1398 				if (s->quota.charge_target_from == dst_target) {
1399 					s->quota.charge_target_from = NULL;
1400 					s->quota.charge_addr_from = 0;
1401 				}
1402 			}
1403 		}
1404 	}
1405 
1406 	damon_for_each_target_safe(src_target, next, src) {
1407 		if (j++ < i)
1408 			continue;
1409 		/* target to remove has no matching dst */
1410 		if (src_target->obsolete)
1411 			return -EINVAL;
1412 		new_target = damon_new_target();
1413 		if (!new_target)
1414 			return -ENOMEM;
1415 		err = damon_commit_target(new_target, false,
1416 				src_target, damon_target_has_pid(src),
1417 				src->min_region_sz);
1418 		if (err) {
1419 			damon_destroy_target(new_target, NULL);
1420 			return err;
1421 		}
1422 		damon_add_target(dst, new_target);
1423 	}
1424 	return 0;
1425 }
1426 
1427 static void damon_commit_filter(struct damon_filter *dst,
1428 		struct damon_filter *src)
1429 {
1430 	dst->type = src->type;
1431 	dst->matching = src->matching;
1432 	dst->allow = src->allow;
1433 }
1434 
1435 static int damon_commit_filters(struct damon_probe *dst,
1436 		struct damon_probe *src)
1437 {
1438 	struct damon_filter *dst_filter, *next, *src_filter, *new_filter;
1439 	int i = 0, j = 0;
1440 
1441 	damon_for_each_filter_safe(dst_filter, next, dst) {
1442 		src_filter = damon_nth_filter(i++, src);
1443 		if (src_filter)
1444 			damon_commit_filter(dst_filter, src_filter);
1445 		else
1446 			damon_destroy_filter(dst_filter);
1447 	}
1448 
1449 	damon_for_each_filter_safe(src_filter, next, src) {
1450 		if (j++ < i)
1451 			continue;
1452 
1453 		new_filter = damon_new_filter(src_filter->type,
1454 				src_filter->matching, src_filter->allow);
1455 		if (!new_filter)
1456 			return -ENOMEM;
1457 		damon_add_filter(dst, new_filter);
1458 	}
1459 	return 0;
1460 }
1461 
1462 static int damon_commit_probes(struct damon_ctx *dst, struct damon_ctx *src)
1463 {
1464 	struct damon_probe *dst_probe, *next, *src_probe, *new_probe;
1465 	int i = 0, j = 0, err;
1466 
1467 	damon_for_each_probe_safe(dst_probe, next, dst) {
1468 		src_probe = damon_nth_probe(i++, src);
1469 		if (src_probe) {
1470 			err = damon_commit_filters(dst_probe, src_probe);
1471 			if (err)
1472 				return err;
1473 		} else {
1474 			damon_destroy_probe(dst_probe);
1475 		}
1476 	}
1477 
1478 	damon_for_each_probe_safe(src_probe, next, src) {
1479 		if (j++ < i)
1480 			continue;
1481 
1482 		new_probe = damon_new_probe();
1483 		if (!new_probe)
1484 			return -ENOMEM;
1485 		damon_add_probe(dst, new_probe);
1486 		err = damon_commit_filters(new_probe, src_probe);
1487 		if (err)
1488 			return err;
1489 	}
1490 	return 0;
1491 }
1492 
1493 /**
1494  * damon_commit_ctx() - Commit parameters of a DAMON context to another.
1495  * @dst:	The commit destination DAMON context.
1496  * @src:	The commit source DAMON context.
1497  *
1498  * This function copies user-specified parameters from @src to @dst and update
1499  * the internal status and results accordingly.  Users should use this function
1500  * for context-level parameters update of running context, instead of manual
1501  * in-place updates.
1502  *
1503  * This function should be called from parameters-update safe context, like
1504  * damon_call().
1505  */
1506 int damon_commit_ctx(struct damon_ctx *dst, struct damon_ctx *src)
1507 {
1508 	int err;
1509 	struct damos *scheme;
1510 	struct damos_quota_goal *goal;
1511 
1512 	dst->maybe_corrupted = true;
1513 	if (!is_power_of_2(src->min_region_sz))
1514 		return -EINVAL;
1515 
1516 	/* node_eligible_mem_bp metric requires PADDR ops */
1517 	if (src->ops.id != DAMON_OPS_PADDR) {
1518 		damon_for_each_scheme(scheme, src) {
1519 			struct damos_quota *quota = &scheme->quota;
1520 
1521 			damos_for_each_quota_goal(goal, quota) {
1522 				if (goal->metric ==
1523 						DAMOS_QUOTA_NODE_ELIGIBLE_MEM_BP)
1524 					return -EINVAL;
1525 			}
1526 		}
1527 	}
1528 
1529 	err = damon_commit_schemes(dst, src);
1530 	if (err)
1531 		return err;
1532 	err = damon_commit_targets(dst, src);
1533 	if (err)
1534 		return err;
1535 	/*
1536 	 * schemes and targets should be updated first, since
1537 	 * 1. damon_set_attrs() updates monitoring results of targets and
1538 	 * next_apply_sis of schemes, and
1539 	 * 2. ops update should be done after pid handling is done (target
1540 	 *    committing require putting pids).
1541 	 */
1542 	if (!damon_attrs_equals(&dst->attrs, &src->attrs)) {
1543 		err = damon_set_attrs(dst, &src->attrs);
1544 		if (err)
1545 			return err;
1546 	}
1547 	dst->pause = src->pause;
1548 	dst->ops = src->ops;
1549 	err = damon_commit_probes(dst, src);
1550 	if (err)
1551 		return err;
1552 	dst->addr_unit = src->addr_unit;
1553 	dst->min_region_sz = src->min_region_sz;
1554 
1555 	dst->maybe_corrupted = false;
1556 	return 0;
1557 }
1558 
1559 /**
1560  * damon_nr_running_ctxs() - Return number of currently running contexts.
1561  */
1562 int damon_nr_running_ctxs(void)
1563 {
1564 	int nr_ctxs;
1565 
1566 	mutex_lock(&damon_lock);
1567 	nr_ctxs = nr_running_ctxs;
1568 	mutex_unlock(&damon_lock);
1569 
1570 	return nr_ctxs;
1571 }
1572 
1573 /* Returns the size upper limit for each monitoring region */
1574 static unsigned long damon_region_sz_limit(struct damon_ctx *ctx)
1575 {
1576 	struct damon_target *t;
1577 	struct damon_region *r;
1578 	unsigned long sz = 0;
1579 
1580 	damon_for_each_target(t, ctx) {
1581 		damon_for_each_region(r, t)
1582 			sz += damon_sz_region(r);
1583 	}
1584 
1585 	if (ctx->attrs.min_nr_regions)
1586 		sz /= ctx->attrs.min_nr_regions;
1587 	if (sz < ctx->min_region_sz)
1588 		sz = ctx->min_region_sz;
1589 
1590 	return sz;
1591 }
1592 
1593 static void damon_split_region_at(struct damon_target *t,
1594 				  struct damon_region *r, unsigned long sz_r);
1595 
1596 /*
1597  * damon_apply_min_nr_regions() - Make effect of min_nr_regions parameter.
1598  * @ctx:	monitoring context.
1599  *
1600  * This function implement min_nr_regions (minimum number of damon_region
1601  * objects in the given monitoring context) behavior.  It first calculates
1602  * maximum size of each region for enforcing the min_nr_regions as total size
1603  * of the regions divided by the min_nr_regions.  After that, this function
1604  * splits regions to ensure all regions are equal to or smaller than the size
1605  * limit.  Finally, this function returns the maximum size limit.
1606  *
1607  * Returns: maximum size of each region for convincing min_nr_regions.
1608  */
1609 static unsigned long damon_apply_min_nr_regions(struct damon_ctx *ctx)
1610 {
1611 	unsigned long max_region_sz = damon_region_sz_limit(ctx);
1612 	struct damon_target *t;
1613 	struct damon_region *r, *next;
1614 
1615 	max_region_sz = ALIGN(max_region_sz, ctx->min_region_sz);
1616 	damon_for_each_target(t, ctx) {
1617 		damon_for_each_region_safe(r, next, t) {
1618 			while (damon_sz_region(r) > max_region_sz) {
1619 				damon_split_region_at(t, r, max_region_sz);
1620 				r = damon_next_region(r);
1621 			}
1622 		}
1623 	}
1624 	return max_region_sz;
1625 }
1626 
1627 static int kdamond_fn(void *data);
1628 
1629 /*
1630  * __damon_start() - Starts monitoring with given context.
1631  * @ctx:	monitoring context
1632  *
1633  * This function should be called while damon_lock is hold.
1634  *
1635  * Return: 0 on success, negative error code otherwise.
1636  */
1637 static int __damon_start(struct damon_ctx *ctx)
1638 {
1639 	int err = -EBUSY;
1640 
1641 	mutex_lock(&ctx->kdamond_lock);
1642 	if (!ctx->kdamond) {
1643 		err = 0;
1644 		reinit_completion(&ctx->kdamond_started);
1645 		ctx->kdamond = kthread_run(kdamond_fn, ctx, "kdamond.%d",
1646 				nr_running_ctxs);
1647 		if (IS_ERR(ctx->kdamond)) {
1648 			err = PTR_ERR(ctx->kdamond);
1649 			ctx->kdamond = NULL;
1650 		} else {
1651 			wait_for_completion(&ctx->kdamond_started);
1652 		}
1653 	}
1654 	mutex_unlock(&ctx->kdamond_lock);
1655 
1656 	return err;
1657 }
1658 
1659 /**
1660  * damon_start() - Starts the monitorings for a given group of contexts.
1661  * @ctxs:	an array of the pointers for contexts to start monitoring
1662  * @nr_ctxs:	size of @ctxs
1663  * @exclusive:	exclusiveness of this contexts group
1664  *
1665  * This function starts a group of monitoring threads for a group of monitoring
1666  * contexts.  One thread per each context is created and run in parallel.  The
1667  * caller should handle synchronization between the threads by itself.  If
1668  * @exclusive is true and a group of threads that created by other
1669  * 'damon_start()' call is currently running, this function does nothing but
1670  * returns -EBUSY.
1671  *
1672  * Return: 0 on success, negative error code otherwise.
1673  */
1674 int damon_start(struct damon_ctx **ctxs, int nr_ctxs, bool exclusive)
1675 {
1676 	int i;
1677 	int err = 0;
1678 
1679 	for (i = 0; i < nr_ctxs; i++) {
1680 		if (!is_power_of_2(ctxs[i]->min_region_sz))
1681 			return -EINVAL;
1682 	}
1683 
1684 	mutex_lock(&damon_lock);
1685 	if ((exclusive && nr_running_ctxs) ||
1686 			(!exclusive && running_exclusive_ctxs)) {
1687 		mutex_unlock(&damon_lock);
1688 		return -EBUSY;
1689 	}
1690 
1691 	for (i = 0; i < nr_ctxs; i++) {
1692 		err = __damon_start(ctxs[i]);
1693 		if (err)
1694 			break;
1695 		nr_running_ctxs++;
1696 	}
1697 	if (exclusive && nr_running_ctxs)
1698 		running_exclusive_ctxs = true;
1699 	mutex_unlock(&damon_lock);
1700 
1701 	return err;
1702 }
1703 
1704 /*
1705  * __damon_stop() - Stops monitoring of a given context.
1706  * @ctx:	monitoring context
1707  *
1708  * Return: 0 on success, negative error code otherwise.
1709  */
1710 static int __damon_stop(struct damon_ctx *ctx)
1711 {
1712 	struct task_struct *tsk;
1713 
1714 	mutex_lock(&ctx->kdamond_lock);
1715 	tsk = ctx->kdamond;
1716 	if (tsk) {
1717 		get_task_struct(tsk);
1718 		mutex_unlock(&ctx->kdamond_lock);
1719 		kthread_stop_put(tsk);
1720 		return 0;
1721 	}
1722 	mutex_unlock(&ctx->kdamond_lock);
1723 
1724 	return -EPERM;
1725 }
1726 
1727 /**
1728  * damon_stop() - Stops the monitorings for a given group of contexts.
1729  * @ctxs:	an array of the pointers for contexts to stop monitoring
1730  * @nr_ctxs:	size of @ctxs
1731  *
1732  * Return: 0 on success, negative error code otherwise.
1733  */
1734 int damon_stop(struct damon_ctx **ctxs, int nr_ctxs)
1735 {
1736 	int i, err = 0;
1737 
1738 	for (i = 0; i < nr_ctxs; i++) {
1739 		/* nr_running_ctxs is decremented in kdamond_fn */
1740 		err = __damon_stop(ctxs[i]);
1741 		if (err)
1742 			break;
1743 	}
1744 	return err;
1745 }
1746 
1747 /**
1748  * damon_is_running() - Returns if a given DAMON context is running.
1749  * @ctx:	The DAMON context to see if running.
1750  *
1751  * Return: true if @ctx is running, false otherwise.
1752  */
1753 bool damon_is_running(struct damon_ctx *ctx)
1754 {
1755 	bool running;
1756 
1757 	mutex_lock(&ctx->kdamond_lock);
1758 	running = ctx->kdamond != NULL;
1759 	mutex_unlock(&ctx->kdamond_lock);
1760 	return running;
1761 }
1762 
1763 /**
1764  * damon_kdamond_pid() - Return pid of a given DAMON context's worker thread.
1765  * @ctx:	The DAMON context of the question.
1766  *
1767  * Return: pid if @ctx is running, negative error code otherwise.
1768  */
1769 int damon_kdamond_pid(struct damon_ctx *ctx)
1770 {
1771 	int pid = -EINVAL;
1772 
1773 	mutex_lock(&ctx->kdamond_lock);
1774 	if (ctx->kdamond)
1775 		pid = ctx->kdamond->pid;
1776 	mutex_unlock(&ctx->kdamond_lock);
1777 	return pid;
1778 }
1779 
1780 /**
1781  * damon_call() - Invoke a given function on DAMON worker thread (kdamond).
1782  * @ctx:	DAMON context to call the function for.
1783  * @control:	Control variable of the call request.
1784  *
1785  * Ask DAMON worker thread (kdamond) of @ctx to call a function with an
1786  * argument data that respectively passed via &damon_call_control->fn and
1787  * &damon_call_control->data of @control.  If &damon_call_control->repeat of
1788  * @control is unset, further wait until the kdamond finishes handling of the
1789  * request.  Otherwise, return as soon as the request is made.
1790  *
1791  * The kdamond executes the function with the argument in the main loop, just
1792  * after a sampling of the iteration is finished.  The function can hence
1793  * safely access the internal data of the &struct damon_ctx without additional
1794  * synchronization.  The return value of the function will be saved in
1795  * &damon_call_control->return_code.
1796  *
1797  * Note that this function should be called only after damon_start() with the
1798  * @ctx has succeeded.  Otherwise, this function could fall into an indefinite
1799  * wait.
1800  *
1801  * Return: 0 on success, negative error code otherwise.
1802  */
1803 int damon_call(struct damon_ctx *ctx, struct damon_call_control *control)
1804 {
1805 	if (!control->repeat)
1806 		init_completion(&control->completion);
1807 	control->canceled = false;
1808 	INIT_LIST_HEAD(&control->list);
1809 
1810 	mutex_lock(&ctx->call_controls_lock);
1811 	if (ctx->call_controls_obsolete) {
1812 		mutex_unlock(&ctx->call_controls_lock);
1813 		return -ECANCELED;
1814 	}
1815 	list_add_tail(&control->list, &ctx->call_controls);
1816 	mutex_unlock(&ctx->call_controls_lock);
1817 	if (control->repeat)
1818 		return 0;
1819 	wait_for_completion(&control->completion);
1820 	if (control->canceled)
1821 		return -ECANCELED;
1822 	return 0;
1823 }
1824 
1825 /**
1826  * damos_walk() - Invoke a given functions while DAMOS walk regions.
1827  * @ctx:	DAMON context to call the functions for.
1828  * @control:	Control variable of the walk request.
1829  *
1830  * Ask DAMON worker thread (kdamond) of @ctx to call a function for each region
1831  * that the kdamond will apply DAMOS action to, and wait until the kdamond
1832  * finishes handling of the request.
1833  *
1834  * The kdamond executes the given function in the main loop, for each region
1835  * just after it applied any DAMOS actions of @ctx to it.  The invocation is
1836  * made only within one &damos->apply_interval_us since damos_walk()
1837  * invocation, for each scheme.  The given callback function can hence safely
1838  * access the internal data of &struct damon_ctx and &struct damon_region that
1839  * each of the scheme will apply the action for next interval, without
1840  * additional synchronizations against the kdamond.  If every scheme of @ctx
1841  * passed at least one &damos->apply_interval_us, kdamond marks the request as
1842  * completed so that damos_walk() can wakeup and return.
1843  *
1844  * Note that this function should be called only after damon_start() with the
1845  * @ctx has succeeded.  Otherwise, this function could fall into an indefinite
1846  * wait.
1847  *
1848  * Return: 0 on success, negative error code otherwise.
1849  */
1850 int damos_walk(struct damon_ctx *ctx, struct damos_walk_control *control)
1851 {
1852 	init_completion(&control->completion);
1853 	control->canceled = false;
1854 	mutex_lock(&ctx->walk_control_lock);
1855 	if (ctx->walk_control_obsolete) {
1856 		mutex_unlock(&ctx->walk_control_lock);
1857 		return -ECANCELED;
1858 	}
1859 	if (ctx->walk_control) {
1860 		mutex_unlock(&ctx->walk_control_lock);
1861 		return -EBUSY;
1862 	}
1863 	ctx->walk_control = control;
1864 	mutex_unlock(&ctx->walk_control_lock);
1865 	wait_for_completion(&control->completion);
1866 	if (control->canceled)
1867 		return -ECANCELED;
1868 	return 0;
1869 }
1870 
1871 /*
1872  * Warn and fix corrupted ->nr_accesses[_bp] for investigations and preventing
1873  * the problem being propagated.
1874  */
1875 static void damon_warn_fix_nr_accesses_corruption(struct damon_region *r)
1876 {
1877 	if (r->nr_accesses_bp == r->nr_accesses * 10000)
1878 		return;
1879 	WARN_ONCE(true, "invalid nr_accesses_bp at reset: %u %u\n",
1880 			r->nr_accesses_bp, r->nr_accesses);
1881 	r->nr_accesses_bp = r->nr_accesses * 10000;
1882 }
1883 
1884 #ifdef CONFIG_DAMON_DEBUG_SANITY
1885 static void damon_verify_reset_aggregated(struct damon_region *r,
1886 		struct damon_ctx *c)
1887 {
1888 	WARN_ONCE(r->nr_accesses_bp != r->last_nr_accesses * 10000,
1889 			"nr_accesses_bp %u last_nr_accesses %u sis %lu %lu\n",
1890 			r->nr_accesses_bp, r->last_nr_accesses,
1891 			c->passed_sample_intervals, c->next_aggregation_sis);
1892 }
1893 #else
1894 static void damon_verify_reset_aggregated(struct damon_region *r,
1895 		struct damon_ctx *c)
1896 {
1897 }
1898 #endif
1899 
1900 
1901 /*
1902  * Reset the aggregated monitoring results ('nr_accesses' of each region).
1903  */
1904 static void kdamond_reset_aggregated(struct damon_ctx *c)
1905 {
1906 	struct damon_target *t;
1907 	unsigned int ti = 0;	/* target's index */
1908 	unsigned int nr_probes = 0;
1909 	struct damon_probe *probe;
1910 
1911 	if (trace_damon_region_aggregated_enabled()) {
1912 		damon_for_each_probe(probe, c)
1913 			nr_probes++;
1914 	}
1915 
1916 	damon_for_each_target(t, c) {
1917 		struct damon_region *r;
1918 
1919 		damon_for_each_region(r, t) {
1920 			int i;
1921 
1922 			trace_damon_aggregated(ti, r, damon_nr_regions(t));
1923 			trace_damon_region_aggregated(ti, r,
1924 					damon_nr_regions(t), nr_probes);
1925 			damon_warn_fix_nr_accesses_corruption(r);
1926 			r->last_nr_accesses = r->nr_accesses;
1927 			r->nr_accesses = 0;
1928 			for (i = 0; i < DAMON_MAX_PROBES; i++)
1929 				r->probe_hits[i] = 0;
1930 			damon_verify_reset_aggregated(r, c);
1931 		}
1932 		ti++;
1933 	}
1934 }
1935 
1936 static unsigned long damon_get_intervals_score(struct damon_ctx *c)
1937 {
1938 	struct damon_target *t;
1939 	struct damon_region *r;
1940 	unsigned long sz_region, max_access_events = 0, access_events = 0;
1941 	unsigned long target_access_events;
1942 	unsigned long goal_bp = c->attrs.intervals_goal.access_bp;
1943 
1944 	damon_for_each_target(t, c) {
1945 		damon_for_each_region(r, t) {
1946 			sz_region = damon_sz_region(r);
1947 			max_access_events += sz_region * c->attrs.aggr_samples;
1948 			access_events += sz_region * r->nr_accesses;
1949 		}
1950 	}
1951 	target_access_events = max_access_events * goal_bp / 10000;
1952 	target_access_events = target_access_events ? : 1;
1953 	return mult_frac(access_events, 10000, target_access_events);
1954 }
1955 
1956 static unsigned long damon_feed_loop_next_input(unsigned long last_input,
1957 		unsigned long score);
1958 
1959 static unsigned long damon_get_intervals_adaptation_bp(struct damon_ctx *c)
1960 {
1961 	unsigned long score_bp, adaptation_bp;
1962 
1963 	score_bp = damon_get_intervals_score(c);
1964 	adaptation_bp = damon_feed_loop_next_input(100000000, score_bp) /
1965 		10000;
1966 	/*
1967 	 * adaptation_bp ranges from 1 to 20,000.  Avoid too rapid reduction of
1968 	 * the intervals by rescaling [1,10,000] to [5000, 10,000].
1969 	 */
1970 	if (adaptation_bp <= 10000)
1971 		adaptation_bp = 5000 + adaptation_bp / 2;
1972 	return adaptation_bp;
1973 }
1974 
1975 static void kdamond_tune_intervals(struct damon_ctx *c)
1976 {
1977 	unsigned long adaptation_bp;
1978 	struct damon_attrs new_attrs;
1979 	struct damon_intervals_goal *goal;
1980 
1981 	adaptation_bp = damon_get_intervals_adaptation_bp(c);
1982 	if (adaptation_bp == 10000)
1983 		return;
1984 
1985 	new_attrs = c->attrs;
1986 	goal = &c->attrs.intervals_goal;
1987 	new_attrs.sample_interval = min(goal->max_sample_us,
1988 			c->attrs.sample_interval * adaptation_bp / 10000);
1989 	new_attrs.sample_interval = max(goal->min_sample_us,
1990 			new_attrs.sample_interval);
1991 	new_attrs.aggr_interval = new_attrs.sample_interval *
1992 		c->attrs.aggr_samples;
1993 	trace_damon_monitor_intervals_tune(new_attrs.sample_interval);
1994 	damon_set_attrs(c, &new_attrs);
1995 }
1996 
1997 static bool __damos_valid_target(struct damon_region *r, struct damos *s)
1998 {
1999 	unsigned long sz;
2000 	unsigned int nr_accesses = r->nr_accesses_bp / 10000;
2001 
2002 	sz = damon_sz_region(r);
2003 	return s->pattern.min_sz_region <= sz &&
2004 		sz <= s->pattern.max_sz_region &&
2005 		s->pattern.min_nr_accesses <= nr_accesses &&
2006 		nr_accesses <= s->pattern.max_nr_accesses &&
2007 		s->pattern.min_age_region <= r->age &&
2008 		r->age <= s->pattern.max_age_region;
2009 }
2010 
2011 /*
2012  * damos_quota_is_set() - Return if the given quota is actually set.
2013  * @quota:	The quota to check.
2014  *
2015  * Returns true if the quota is set, false otherwise.
2016  */
2017 static bool damos_quota_is_set(struct damos_quota *quota)
2018 {
2019 	return quota->esz || quota->sz || quota->ms ||
2020 		!damos_quota_goals_empty(quota);
2021 }
2022 
2023 static bool damos_valid_target(struct damon_ctx *c, struct damon_region *r,
2024 		struct damos *s)
2025 {
2026 	bool ret = __damos_valid_target(r, s);
2027 
2028 	if (!ret || !damos_quota_is_set(&s->quota) || !c->ops.get_scheme_score)
2029 		return ret;
2030 
2031 	return c->ops.get_scheme_score(c, r, s) >= s->quota.min_score;
2032 }
2033 
2034 /*
2035  * damos_skip_charged_region() - Check if the given region or starting part of
2036  * it is already charged for the DAMOS quota.
2037  * @t:	The target of the region.
2038  * @rp:	The pointer to the region.
2039  * @s:	The scheme to be applied.
2040  * @min_region_sz:	minimum region size.
2041  *
2042  * If a quota of a scheme has exceeded in a quota charge window, the scheme's
2043  * action would applied to only a part of the target access pattern fulfilling
2044  * regions.  To avoid applying the scheme action to only already applied
2045  * regions, DAMON skips applying the scheme action to the regions that charged
2046  * in the previous charge window.
2047  *
2048  * This function checks if a given region should be skipped or not for the
2049  * reason.  If only the starting part of the region has previously charged,
2050  * this function splits the region into two so that the second one covers the
2051  * area that not charged in the previous charge widnow, and return true.  The
2052  * caller can see the second one on the next iteration of the region walk.
2053  * Note that this means the caller should use damon_for_each_region() instead
2054  * of damon_for_each_region_safe().  If damon_for_each_region_safe() is used,
2055  * the second region will just be ignored.
2056  *
2057  * Return: true if the region should be skipped, false otherwise.
2058  */
2059 static bool damos_skip_charged_region(struct damon_target *t,
2060 		struct damon_region *r, struct damos *s,
2061 		unsigned long min_region_sz)
2062 {
2063 	struct damos_quota *quota = &s->quota;
2064 	unsigned long sz_to_skip;
2065 
2066 	/* Skip previously charged regions */
2067 	if (quota->charge_target_from) {
2068 		if (t != quota->charge_target_from)
2069 			return true;
2070 		if (r == damon_last_region(t)) {
2071 			quota->charge_target_from = NULL;
2072 			quota->charge_addr_from = 0;
2073 			return true;
2074 		}
2075 		if (quota->charge_addr_from &&
2076 				r->ar.end <= quota->charge_addr_from)
2077 			return true;
2078 
2079 		if (quota->charge_addr_from && r->ar.start <
2080 				quota->charge_addr_from) {
2081 			sz_to_skip = ALIGN_DOWN(quota->charge_addr_from -
2082 					r->ar.start, min_region_sz);
2083 			if (!sz_to_skip) {
2084 				if (damon_sz_region(r) <= min_region_sz)
2085 					return true;
2086 				sz_to_skip = min_region_sz;
2087 			}
2088 			damon_split_region_at(t, r, sz_to_skip);
2089 			return true;
2090 		}
2091 		quota->charge_target_from = NULL;
2092 		quota->charge_addr_from = 0;
2093 	}
2094 	return false;
2095 }
2096 
2097 static void damos_update_stat(struct damos *s,
2098 		unsigned long sz_tried, unsigned long sz_applied,
2099 		unsigned long sz_ops_filter_passed)
2100 {
2101 	s->stat.nr_tried++;
2102 	s->stat.sz_tried += sz_tried;
2103 	if (sz_applied)
2104 		s->stat.nr_applied++;
2105 	s->stat.sz_applied += sz_applied;
2106 	s->stat.sz_ops_filter_passed += sz_ops_filter_passed;
2107 }
2108 
2109 static bool damos_filter_match(struct damon_ctx *ctx, struct damon_target *t,
2110 		struct damon_region *r, struct damos_filter *filter,
2111 		unsigned long min_region_sz)
2112 {
2113 	bool matched = false;
2114 	struct damon_target *ti;
2115 	int target_idx = 0;
2116 	unsigned long start, end;
2117 
2118 	switch (filter->type) {
2119 	case DAMOS_FILTER_TYPE_TARGET:
2120 		damon_for_each_target(ti, ctx) {
2121 			if (ti == t)
2122 				break;
2123 			target_idx++;
2124 		}
2125 		matched = target_idx == filter->target_idx;
2126 		break;
2127 	case DAMOS_FILTER_TYPE_ADDR:
2128 		start = ALIGN_DOWN(filter->addr_range.start, min_region_sz);
2129 		end = ALIGN_DOWN(filter->addr_range.end, min_region_sz);
2130 
2131 		/* inside the range */
2132 		if (start <= r->ar.start && r->ar.end <= end) {
2133 			matched = true;
2134 			break;
2135 		}
2136 		/* outside of the range */
2137 		if (r->ar.end <= start || end <= r->ar.start) {
2138 			matched = false;
2139 			break;
2140 		}
2141 		/* start before the range and overlap */
2142 		if (r->ar.start < start) {
2143 			damon_split_region_at(t, r, start - r->ar.start);
2144 			matched = false;
2145 			break;
2146 		}
2147 		/* start inside the range */
2148 		damon_split_region_at(t, r, end - r->ar.start);
2149 		matched = true;
2150 		break;
2151 	default:
2152 		return false;
2153 	}
2154 
2155 	return matched == filter->matching;
2156 }
2157 
2158 static bool damos_core_filter_out(struct damon_ctx *ctx, struct damon_target *t,
2159 		struct damon_region *r, struct damos *s)
2160 {
2161 	struct damos_filter *filter;
2162 
2163 	s->core_filters_allowed = false;
2164 	damos_for_each_core_filter(filter, s) {
2165 		if (damos_filter_match(ctx, t, r, filter, ctx->min_region_sz)) {
2166 			if (filter->allow)
2167 				s->core_filters_allowed = true;
2168 			return !filter->allow;
2169 		}
2170 	}
2171 	return s->core_filters_default_reject;
2172 }
2173 
2174 /*
2175  * damos_walk_call_walk() - Call &damos_walk_control->walk_fn.
2176  * @ctx:	The context of &damon_ctx->walk_control.
2177  * @t:		The monitoring target of @r that @s will be applied.
2178  * @r:		The region of @t that @s will be applied.
2179  * @s:		The scheme of @ctx that will be applied to @r.
2180  *
2181  * This function is called from kdamond whenever it asked the operation set to
2182  * apply a DAMOS scheme action to a region.  If a DAMOS walk request is
2183  * installed by damos_walk() and not yet uninstalled, invoke it.
2184  */
2185 static void damos_walk_call_walk(struct damon_ctx *ctx, struct damon_target *t,
2186 		struct damon_region *r, struct damos *s,
2187 		unsigned long sz_filter_passed)
2188 {
2189 	struct damos_walk_control *control;
2190 
2191 	if (s->walk_completed)
2192 		return;
2193 
2194 	control = ctx->walk_control;
2195 	if (!control)
2196 		return;
2197 
2198 	control->walk_fn(control->data, ctx, t, r, s, sz_filter_passed);
2199 }
2200 
2201 /*
2202  * damos_walk_complete() - Complete DAMOS walk request if all walks are done.
2203  * @ctx:	The context of &damon_ctx->walk_control.
2204  * @s:		A scheme of @ctx that all walks are now done.
2205  *
2206  * This function is called when kdamond finished applying the action of a DAMOS
2207  * scheme to all regions that eligible for the given &damos->apply_interval_us.
2208  * If every scheme of @ctx including @s now finished walking for at least one
2209  * &damos->apply_interval_us, this function makrs the handling of the given
2210  * DAMOS walk request is done, so that damos_walk() can wake up and return.
2211  */
2212 static void damos_walk_complete(struct damon_ctx *ctx, struct damos *s)
2213 {
2214 	struct damos *siter;
2215 	struct damos_walk_control *control;
2216 
2217 	control = ctx->walk_control;
2218 	if (!control)
2219 		return;
2220 
2221 	s->walk_completed = true;
2222 	/* if all schemes completed, signal completion to walker */
2223 	damon_for_each_scheme(siter, ctx) {
2224 		if (!siter->walk_completed)
2225 			return;
2226 	}
2227 	damon_for_each_scheme(siter, ctx)
2228 		siter->walk_completed = false;
2229 
2230 	complete(&control->completion);
2231 	ctx->walk_control = NULL;
2232 }
2233 
2234 /*
2235  * damos_walk_cancel() - Cancel the current DAMOS walk request.
2236  * @ctx:	The context of &damon_ctx->walk_control.
2237  *
2238  * This function is called when @ctx is deactivated by DAMOS watermarks, DAMOS
2239  * walk is requested but there is no DAMOS scheme to walk for, or the kdamond
2240  * is already out of the main loop and therefore gonna be terminated, and hence
2241  * cannot continue the walks.  This function therefore marks the walk request
2242  * as canceled, so that damos_walk() can wake up and return.
2243  */
2244 static void damos_walk_cancel(struct damon_ctx *ctx)
2245 {
2246 	struct damos_walk_control *control;
2247 
2248 	mutex_lock(&ctx->walk_control_lock);
2249 	control = ctx->walk_control;
2250 	mutex_unlock(&ctx->walk_control_lock);
2251 
2252 	if (!control)
2253 		return;
2254 	control->canceled = true;
2255 	complete(&control->completion);
2256 	mutex_lock(&ctx->walk_control_lock);
2257 	ctx->walk_control = NULL;
2258 	mutex_unlock(&ctx->walk_control_lock);
2259 }
2260 
2261 static void damos_charge_quota(struct damos_quota *quota,
2262 		unsigned long sz_region, unsigned long sz_applied)
2263 {
2264 	/*
2265 	 * sz_applied could be bigger than sz_region, depending on ops
2266 	 * implementation of the action, e.g., damos_pa_pageout().  Charge only
2267 	 * the region size in the case.
2268 	 */
2269 	if (!quota->fail_charge_denom || sz_applied > sz_region)
2270 		quota->charged_sz += sz_region;
2271 	else
2272 		quota->charged_sz += sz_applied + mult_frac(
2273 				(sz_region - sz_applied),
2274 				quota->fail_charge_num,
2275 				quota->fail_charge_denom);
2276 }
2277 
2278 static bool damos_quota_is_full(struct damos_quota *quota,
2279 		unsigned long min_region_sz)
2280 {
2281 	if (!damos_quota_is_set(quota))
2282 		return false;
2283 	if (quota->charged_sz >= quota->esz)
2284 		return true;
2285 	/*
2286 	 * DAMOS action is applied per region, so <min_region_sz remaining
2287 	 * quota means the quota is effectively full.
2288 	 */
2289 	return quota->esz - quota->charged_sz < min_region_sz;
2290 }
2291 
2292 static void damos_apply_scheme(struct damon_ctx *c, struct damon_target *t,
2293 		struct damon_region *r, struct damos *s)
2294 {
2295 	struct damos_quota *quota = &s->quota;
2296 	unsigned long sz = damon_sz_region(r);
2297 	struct timespec64 begin, end;
2298 	unsigned long sz_applied = 0;
2299 	unsigned long sz_ops_filter_passed = 0;
2300 	/*
2301 	 * We plan to support multiple context per kdamond, as DAMON sysfs
2302 	 * implies with 'nr_contexts' file.  Nevertheless, only single context
2303 	 * per kdamond is supported for now.  So, we can simply use '0' context
2304 	 * index here.
2305 	 */
2306 	unsigned int cidx = 0;
2307 	struct damos *siter;		/* schemes iterator */
2308 	unsigned int sidx = 0;
2309 	struct damon_target *titer;	/* targets iterator */
2310 	unsigned int tidx = 0;
2311 	bool do_trace = false;
2312 
2313 	/* get indices for trace_damos_before_apply() */
2314 	if (trace_damos_before_apply_enabled()) {
2315 		damon_for_each_scheme(siter, c) {
2316 			if (siter == s)
2317 				break;
2318 			sidx++;
2319 		}
2320 		damon_for_each_target(titer, c) {
2321 			if (titer == t)
2322 				break;
2323 			tidx++;
2324 		}
2325 		do_trace = true;
2326 	}
2327 
2328 	if (c->ops.apply_scheme) {
2329 		if (damos_quota_is_set(quota) &&
2330 				quota->charged_sz + sz > quota->esz) {
2331 			sz = ALIGN_DOWN(quota->esz - quota->charged_sz,
2332 					c->min_region_sz);
2333 			if (!sz)
2334 				goto update_stat;
2335 			damon_split_region_at(t, r, sz);
2336 		}
2337 		if (damos_core_filter_out(c, t, r, s))
2338 			return;
2339 		ktime_get_coarse_ts64(&begin);
2340 		trace_damos_before_apply(cidx, sidx, tidx, r,
2341 				damon_nr_regions(t), do_trace);
2342 		sz_applied = c->ops.apply_scheme(c, t, r, s,
2343 				&sz_ops_filter_passed);
2344 		damos_walk_call_walk(c, t, r, s, sz_ops_filter_passed);
2345 		ktime_get_coarse_ts64(&end);
2346 		quota->total_charged_ns += timespec64_to_ns(&end) -
2347 			timespec64_to_ns(&begin);
2348 		damos_charge_quota(quota, sz, sz_applied);
2349 		if (damos_quota_is_full(quota, c->min_region_sz)) {
2350 			quota->charge_target_from = t;
2351 			quota->charge_addr_from = r->ar.end;
2352 		}
2353 	}
2354 	if (s->action != DAMOS_STAT)
2355 		r->age = 0;
2356 
2357 update_stat:
2358 	damos_update_stat(s, sz, sz_applied, sz_ops_filter_passed);
2359 }
2360 
2361 static void damon_do_apply_schemes(struct damon_ctx *c,
2362 				   struct damon_target *t,
2363 				   struct damon_region *r)
2364 {
2365 	struct damos *s;
2366 
2367 	damon_for_each_scheme(s, c) {
2368 		struct damos_quota *quota = &s->quota;
2369 
2370 		if (time_before(c->passed_sample_intervals, s->next_apply_sis))
2371 			continue;
2372 
2373 		if (!s->wmarks.activated)
2374 			continue;
2375 
2376 		/* Check the quota */
2377 		if (damos_quota_is_full(quota, c->min_region_sz))
2378 			continue;
2379 
2380 		if (damos_skip_charged_region(t, r, s, c->min_region_sz))
2381 			continue;
2382 
2383 		if (s->max_nr_snapshots &&
2384 				s->max_nr_snapshots <= s->stat.nr_snapshots)
2385 			continue;
2386 
2387 		if (damos_valid_target(c, r, s))
2388 			damos_apply_scheme(c, t, r, s);
2389 
2390 		if (damon_is_last_region(r, t))
2391 			s->stat.nr_snapshots++;
2392 	}
2393 }
2394 
2395 /*
2396  * damos_apply_target() - Apply DAMOS schemes to a given target.
2397  * @c:			monitoring context to apply its DAMOS schemes to..
2398  * @t:			monitoring target to apply the schemes to.
2399  * @max_region_sz:	maximum region size for @c.
2400  *
2401  * This function could split regions for keeping the quota.  To minimize
2402  * overhead from the split operations increased number of regions, this
2403  * function will also merge regions after the schemes applying attempt is done,
2404  * for each region.  The merge operation is made only when it doesn't lose the
2405  * monitoring information and not violating @max_region_sz.
2406  *
2407  * Hence, after this function is called, the total number of regions could
2408  * be increased or reduced.  The increase could make max_nr_regions temporarily
2409  * be violated, until the next per-aggregation interval regions merge operation
2410  * is executed.  The decrease will not violate min_nr_regions though, since it
2411  * keeps @max_region_sz.
2412  */
2413 static void damos_apply_target(struct damon_ctx *c, struct damon_target *t,
2414 		unsigned long max_region_sz)
2415 {
2416 	struct damon_region *r;
2417 
2418 	damon_for_each_region(r, t) {
2419 		struct damon_region *prev_r;
2420 
2421 		damon_do_apply_schemes(c, t, r);
2422 		/*
2423 		 * damon_do_apply_scheems() could split the region for the
2424 		 * quota.  Keeping the new slices is an overhead.  Merge back
2425 		 * the slices into the previous region if it doesn't lose any
2426 		 * information and not violating the max_region_sz.
2427 		 */
2428 		if (damon_first_region(t) == r)
2429 			continue;
2430 		prev_r = damon_prev_region(r);
2431 		if (prev_r->ar.end != r->ar.start)
2432 			continue;
2433 		if (prev_r->age != r->age)
2434 			continue;
2435 		if (prev_r->last_nr_accesses != r->last_nr_accesses)
2436 			continue;
2437 		if (prev_r->nr_accesses != r->nr_accesses)
2438 			continue;
2439 		if (r->ar.end - prev_r->ar.start > max_region_sz)
2440 			continue;
2441 		prev_r->ar.end = r->ar.end;
2442 		damon_destroy_region(r, t);
2443 		r = prev_r;
2444 	}
2445 }
2446 
2447 /*
2448  * damon_feed_loop_next_input() - get next input to achieve a target score.
2449  * @last_input	The last input.
2450  * @score	Current score that made with @last_input.
2451  *
2452  * Calculate next input to achieve the target score, based on the last input
2453  * and current score.  Assuming the input and the score are positively
2454  * proportional, calculate how much compensation should be added to or
2455  * subtracted from the last input as a proportion of the last input.  Avoid
2456  * next input always being zero by setting it non-zero always.  In short form
2457  * (assuming support of float and signed calculations), the algorithm is as
2458  * below.
2459  *
2460  * next_input = max(last_input * ((goal - current) / goal + 1), 1)
2461  *
2462  * For simple implementation, we assume the target score is always 10,000.  The
2463  * caller should adjust @score for this.
2464  *
2465  * Returns next input that assumed to achieve the target score.
2466  */
2467 static unsigned long damon_feed_loop_next_input(unsigned long last_input,
2468 		unsigned long score)
2469 {
2470 	const unsigned long goal = 10000;
2471 	/* Set minimum input as 10000 to avoid compensation be zero */
2472 	const unsigned long min_input = 10000;
2473 	unsigned long score_goal_diff, compensation;
2474 	bool over_achieving = score > goal;
2475 
2476 	if (score == goal)
2477 		return last_input;
2478 	if (score >= goal * 2)
2479 		return min_input;
2480 
2481 	if (over_achieving)
2482 		score_goal_diff = score - goal;
2483 	else
2484 		score_goal_diff = goal - score;
2485 
2486 	if (last_input < ULONG_MAX / score_goal_diff)
2487 		compensation = last_input * score_goal_diff / goal;
2488 	else
2489 		compensation = last_input / goal * score_goal_diff;
2490 
2491 	if (over_achieving)
2492 		return max(last_input - compensation, min_input);
2493 	if (last_input < ULONG_MAX - compensation)
2494 		return last_input + compensation;
2495 	return ULONG_MAX;
2496 }
2497 
2498 #ifdef CONFIG_PSI
2499 
2500 static u64 damos_get_some_mem_psi_total(void)
2501 {
2502 	if (static_branch_likely(&psi_disabled))
2503 		return 0;
2504 	return div_u64(psi_system.total[PSI_AVGS][PSI_MEM * 2],
2505 			NSEC_PER_USEC);
2506 }
2507 
2508 #else	/* CONFIG_PSI */
2509 
2510 static inline u64 damos_get_some_mem_psi_total(void)
2511 {
2512 	return 0;
2513 };
2514 
2515 #endif	/* CONFIG_PSI */
2516 
2517 #ifdef CONFIG_NUMA
2518 static bool invalid_mem_node(int nid)
2519 {
2520 	return nid < 0 || nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY);
2521 }
2522 
2523 static __kernel_ulong_t damos_get_node_mem_bp(
2524 		struct damos_quota_goal *goal)
2525 {
2526 	struct sysinfo i;
2527 	__kernel_ulong_t numerator;
2528 
2529 	if (invalid_mem_node(goal->nid)) {
2530 		if (goal->metric == DAMOS_QUOTA_NODE_MEM_USED_BP)
2531 			return 0;
2532 		else	/* DAMOS_QUOTA_NODE_MEM_FREE_BP */
2533 			return 10000;
2534 	}
2535 
2536 	si_meminfo_node(&i, goal->nid);
2537 	if (goal->metric == DAMOS_QUOTA_NODE_MEM_USED_BP)
2538 		numerator = i.totalram - i.freeram;
2539 	else	/* DAMOS_QUOTA_NODE_MEM_FREE_BP */
2540 		numerator = i.freeram;
2541 	return mult_frac(numerator, 10000, i.totalram);
2542 }
2543 
2544 static unsigned long damos_get_node_memcg_used_bp(
2545 		struct damos_quota_goal *goal)
2546 {
2547 	struct mem_cgroup *memcg;
2548 	struct lruvec *lruvec;
2549 	unsigned long used_pages, numerator;
2550 	struct sysinfo i;
2551 
2552 	if (invalid_mem_node(goal->nid)) {
2553 		if (goal->metric == DAMOS_QUOTA_NODE_MEMCG_USED_BP)
2554 			return 0;
2555 		else	/* DAMOS_QUOTA_NODE_MEMCG_FREE_BP */
2556 			return 10000;
2557 	}
2558 
2559 	memcg = mem_cgroup_get_from_id(goal->memcg_id);
2560 	if (!memcg) {
2561 		if (goal->metric == DAMOS_QUOTA_NODE_MEMCG_USED_BP)
2562 			return 0;
2563 		else	/* DAMOS_QUOTA_NODE_MEMCG_FREE_BP */
2564 			return 10000;
2565 	}
2566 
2567 	mem_cgroup_flush_stats(memcg);
2568 	lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(goal->nid));
2569 	used_pages = lruvec_page_state(lruvec, NR_ACTIVE_ANON);
2570 	used_pages += lruvec_page_state(lruvec, NR_INACTIVE_ANON);
2571 	used_pages += lruvec_page_state(lruvec, NR_ACTIVE_FILE);
2572 	used_pages += lruvec_page_state(lruvec, NR_INACTIVE_FILE);
2573 
2574 	mem_cgroup_put(memcg);
2575 
2576 	si_meminfo_node(&i, goal->nid);
2577 	if (goal->metric == DAMOS_QUOTA_NODE_MEMCG_USED_BP)
2578 		numerator = used_pages;
2579 	else	/* DAMOS_QUOTA_NODE_MEMCG_FREE_BP */
2580 		numerator = i.totalram - used_pages;
2581 	return mult_frac(numerator, 10000, i.totalram);
2582 }
2583 
2584 #ifdef CONFIG_DAMON_PADDR
2585 /*
2586  * damos_calc_eligible_bytes() - Calculate raw eligible bytes per node.
2587  * @c:		The DAMON context.
2588  * @s:		The scheme.
2589  * @nid:	The target NUMA node id.
2590  * @total:	Output for total eligible bytes across all nodes.
2591  *
2592  * Iterates through each folio in eligible regions to accurately determine
2593  * which node the memory resides on. Returns eligible bytes on the specified
2594  * node and sets *total to the sum across all nodes.
2595  *
2596  * Note: This function requires damon_get_folio() from ops-common.c, which is
2597  * only available when CONFIG_DAMON_PADDR is enabled. It also requires the
2598  * context to be using PADDR operations for meaningful results.
2599  */
2600 static phys_addr_t damos_calc_eligible_bytes(struct damon_ctx *c,
2601 		struct damos *s, int nid, phys_addr_t *total)
2602 {
2603 	struct damon_target *t;
2604 	struct damon_region *r;
2605 	phys_addr_t total_eligible = 0;
2606 	phys_addr_t node_eligible = 0;
2607 
2608 	damon_for_each_target(t, c) {
2609 		damon_for_each_region(r, t) {
2610 			phys_addr_t addr, end_addr;
2611 
2612 			if (!__damos_valid_target(r, s))
2613 				continue;
2614 
2615 			/* Convert from core address units to physical bytes */
2616 			addr = (phys_addr_t)r->ar.start * c->addr_unit;
2617 			end_addr = (phys_addr_t)r->ar.end * c->addr_unit;
2618 			while (addr < end_addr) {
2619 				struct folio *folio;
2620 				phys_addr_t folio_start, folio_end;
2621 				phys_addr_t overlap_start, overlap_end;
2622 				phys_addr_t counted;
2623 
2624 				folio = damon_get_folio(PHYS_PFN(addr));
2625 				if (!folio) {
2626 					addr = PAGE_ALIGN_DOWN(addr +
2627 							PAGE_SIZE);
2628 					if (!addr)
2629 						break;
2630 					continue;
2631 				}
2632 
2633 				/*
2634 				 * Calculate exact overlap between the region
2635 				 * [addr, end_addr) and the folio range.
2636 				 * The folio may start before addr if addr is
2637 				 * in the middle of a large folio.
2638 				 */
2639 				folio_start = PFN_PHYS(folio_pfn(folio));
2640 				folio_end = folio_start + folio_size(folio);
2641 
2642 				overlap_start = max(addr, folio_start);
2643 				overlap_end = min(end_addr, folio_end);
2644 
2645 				if (overlap_end > overlap_start) {
2646 					counted = overlap_end - overlap_start;
2647 					total_eligible += counted;
2648 					if (folio_nid(folio) == nid)
2649 						node_eligible += counted;
2650 				}
2651 
2652 				/* Advance past the entire folio */
2653 				addr = folio_end;
2654 				folio_put(folio);
2655 			}
2656 			cond_resched();
2657 		}
2658 	}
2659 
2660 	*total = total_eligible;
2661 	return node_eligible;
2662 }
2663 
2664 static unsigned long damos_get_node_eligible_mem_bp(struct damon_ctx *c,
2665 		struct damos *s, int nid)
2666 {
2667 	phys_addr_t total_eligible = 0;
2668 	phys_addr_t node_eligible;
2669 
2670 	if (c->ops.id != DAMON_OPS_PADDR)
2671 		return 0;
2672 
2673 	if (nid < 0 || nid >= MAX_NUMNODES || !node_online(nid))
2674 		return 0;
2675 
2676 	node_eligible = damos_calc_eligible_bytes(c, s, nid, &total_eligible);
2677 
2678 	if (!(unsigned long)total_eligible)
2679 		return 0;
2680 
2681 	return mult_frac((unsigned long)node_eligible, 10000,
2682 			(unsigned long)total_eligible);
2683 }
2684 #else /* CONFIG_DAMON_PADDR */
2685 static unsigned long damos_get_node_eligible_mem_bp(struct damon_ctx *c,
2686 		struct damos *s, int nid)
2687 {
2688 	return 0;
2689 }
2690 #endif /* CONFIG_DAMON_PADDR */
2691 #else /* CONFIG_NUMA */
2692 static __kernel_ulong_t damos_get_node_mem_bp(
2693 		struct damos_quota_goal *goal)
2694 {
2695 	return 0;
2696 }
2697 
2698 static unsigned long damos_get_node_memcg_used_bp(
2699 		struct damos_quota_goal *goal)
2700 {
2701 	return 0;
2702 }
2703 
2704 static unsigned long damos_get_node_eligible_mem_bp(struct damon_ctx *c,
2705 		struct damos *s, int nid)
2706 {
2707 	return 0;
2708 }
2709 #endif /* CONFIG_NUMA */
2710 
2711 /*
2712  * Returns LRU-active or inactive memory to total LRU memory size ratio.
2713  */
2714 static unsigned int damos_get_in_active_mem_bp(bool active_ratio)
2715 {
2716 	unsigned long active, inactive, total;
2717 
2718 	/* This should align with /proc/meminfo output */
2719 	active = global_node_page_state(NR_LRU_BASE + LRU_ACTIVE_ANON) +
2720 		global_node_page_state(NR_LRU_BASE + LRU_ACTIVE_FILE);
2721 	inactive = global_node_page_state(NR_LRU_BASE + LRU_INACTIVE_ANON) +
2722 		global_node_page_state(NR_LRU_BASE + LRU_INACTIVE_FILE);
2723 	total = active + inactive;
2724 	if (active_ratio)
2725 		return mult_frac(active, 10000, total);
2726 	return mult_frac(inactive, 10000, total);
2727 }
2728 
2729 static void damos_set_quota_goal_current_value(struct damon_ctx *c,
2730 		struct damos *s, struct damos_quota_goal *goal)
2731 {
2732 	u64 now_psi_total;
2733 
2734 	switch (goal->metric) {
2735 	case DAMOS_QUOTA_USER_INPUT:
2736 		/* User should already set goal->current_value */
2737 		break;
2738 	case DAMOS_QUOTA_SOME_MEM_PSI_US:
2739 		now_psi_total = damos_get_some_mem_psi_total();
2740 		goal->current_value = now_psi_total - goal->last_psi_total;
2741 		goal->last_psi_total = now_psi_total;
2742 		break;
2743 	case DAMOS_QUOTA_NODE_MEM_USED_BP:
2744 	case DAMOS_QUOTA_NODE_MEM_FREE_BP:
2745 		goal->current_value = damos_get_node_mem_bp(goal);
2746 		break;
2747 	case DAMOS_QUOTA_NODE_MEMCG_USED_BP:
2748 	case DAMOS_QUOTA_NODE_MEMCG_FREE_BP:
2749 		goal->current_value = damos_get_node_memcg_used_bp(goal);
2750 		break;
2751 	case DAMOS_QUOTA_ACTIVE_MEM_BP:
2752 	case DAMOS_QUOTA_INACTIVE_MEM_BP:
2753 		goal->current_value = damos_get_in_active_mem_bp(
2754 				goal->metric == DAMOS_QUOTA_ACTIVE_MEM_BP);
2755 		break;
2756 	case DAMOS_QUOTA_NODE_ELIGIBLE_MEM_BP:
2757 		goal->current_value = damos_get_node_eligible_mem_bp(c, s,
2758 				goal->nid);
2759 		break;
2760 	default:
2761 		break;
2762 	}
2763 }
2764 
2765 /* Return the highest score since it makes schemes least aggressive */
2766 static unsigned long damos_quota_score(struct damon_ctx *c, struct damos *s)
2767 {
2768 	struct damos_quota_goal *goal;
2769 	struct damos_quota *quota = &s->quota;
2770 	unsigned long highest_score = 0;
2771 
2772 	damos_for_each_quota_goal(goal, quota) {
2773 		damos_set_quota_goal_current_value(c, s, goal);
2774 		highest_score = max(highest_score,
2775 				mult_frac(goal->current_value, 10000,
2776 					goal->target_value));
2777 	}
2778 
2779 	return highest_score;
2780 }
2781 
2782 static void damos_goal_tune_esz_bp_consist(struct damon_ctx *c, struct damos *s)
2783 {
2784 	struct damos_quota *quota = &s->quota;
2785 	unsigned long score = damos_quota_score(c, s);
2786 
2787 	quota->esz_bp = damon_feed_loop_next_input(
2788 			max(quota->esz_bp, 10000UL), score);
2789 }
2790 
2791 static void damos_goal_tune_esz_bp_temporal(struct damon_ctx *c,
2792 		struct damos *s)
2793 {
2794 	struct damos_quota *quota = &s->quota;
2795 	unsigned long score = damos_quota_score(c, s);
2796 
2797 	if (score >= 10000)
2798 		quota->esz_bp = 0;
2799 	else if (quota->sz)
2800 		quota->esz_bp = quota->sz * 10000;
2801 	else
2802 		quota->esz_bp = ULONG_MAX;
2803 }
2804 
2805 /*
2806  * Called only if quota->ms, or quota->sz are set, or quota->goals is not empty
2807  */
2808 static void damos_set_effective_quota(struct damon_ctx *ctx, struct damos *s)
2809 {
2810 	struct damos_quota *quota = &s->quota;
2811 	unsigned long throughput;
2812 	unsigned long esz = ULONG_MAX;
2813 
2814 	if (!quota->ms && list_empty(&quota->goals)) {
2815 		quota->esz = quota->sz;
2816 		return;
2817 	}
2818 
2819 	if (!list_empty(&quota->goals)) {
2820 		if (quota->goal_tuner == DAMOS_QUOTA_GOAL_TUNER_CONSIST)
2821 			damos_goal_tune_esz_bp_consist(ctx, s);
2822 		else if (quota->goal_tuner == DAMOS_QUOTA_GOAL_TUNER_TEMPORAL)
2823 			damos_goal_tune_esz_bp_temporal(ctx, s);
2824 		esz = quota->esz_bp / 10000;
2825 	}
2826 
2827 	if (quota->ms) {
2828 		if (quota->total_charged_ns)
2829 			throughput = mult_frac(quota->total_charged_sz,
2830 					1000000, quota->total_charged_ns);
2831 		else
2832 			throughput = PAGE_SIZE * 1024;
2833 		esz = min(throughput * quota->ms, esz);
2834 		esz = max(ctx->min_region_sz, esz);
2835 	}
2836 
2837 	if (quota->sz && quota->sz < esz)
2838 		esz = quota->sz;
2839 
2840 	quota->esz = esz;
2841 }
2842 
2843 static void damos_trace_esz(struct damon_ctx *c, struct damos *s,
2844 		struct damos_quota *quota)
2845 {
2846 	unsigned int cidx = 0, sidx = 0;
2847 	struct damos *siter;
2848 
2849 	damon_for_each_scheme(siter, c) {
2850 		if (siter == s)
2851 			break;
2852 		sidx++;
2853 	}
2854 	trace_damos_esz(cidx, sidx, quota->esz);
2855 }
2856 
2857 static void damos_adjust_quota(struct damon_ctx *c, struct damos *s)
2858 {
2859 	struct damos_quota *quota = &s->quota;
2860 	struct damon_target *t;
2861 	struct damon_region *r;
2862 	unsigned long cumulated_sz, cached_esz;
2863 	unsigned int score, max_score = 0;
2864 
2865 	if (!quota->ms && !quota->sz && list_empty(&quota->goals))
2866 		return;
2867 
2868 	/* First charge window */
2869 	if (!quota->total_charged_sz && !quota->charged_from) {
2870 		quota->charged_from = jiffies;
2871 		damos_set_effective_quota(c, s);
2872 	}
2873 
2874 	/* New charge window starts */
2875 	if (!time_in_range_open(jiffies, quota->charged_from,
2876 				quota->charged_from +
2877 				msecs_to_jiffies(quota->reset_interval))) {
2878 		if (damos_quota_is_full(quota, c->min_region_sz))
2879 			s->stat.qt_exceeds++;
2880 		quota->total_charged_sz += quota->charged_sz;
2881 		quota->charged_from = jiffies;
2882 		quota->charged_sz = 0;
2883 		if (trace_damos_esz_enabled())
2884 			cached_esz = quota->esz;
2885 		damos_set_effective_quota(c, s);
2886 		if (trace_damos_esz_enabled() && quota->esz != cached_esz)
2887 			damos_trace_esz(c, s, quota);
2888 	}
2889 
2890 	if (!c->ops.get_scheme_score)
2891 		return;
2892 
2893 	/* Fill up the score histogram */
2894 	memset(c->regions_score_histogram, 0,
2895 			sizeof(*c->regions_score_histogram) *
2896 			(DAMOS_MAX_SCORE + 1));
2897 	damon_for_each_target(t, c) {
2898 		damon_for_each_region(r, t) {
2899 			if (!__damos_valid_target(r, s))
2900 				continue;
2901 			if (damos_core_filter_out(c, t, r, s))
2902 				continue;
2903 			score = c->ops.get_scheme_score(c, r, s);
2904 			c->regions_score_histogram[score] +=
2905 				damon_sz_region(r);
2906 			if (score > max_score)
2907 				max_score = score;
2908 		}
2909 	}
2910 
2911 	/* Set the min score limit */
2912 	for (cumulated_sz = 0, score = max_score; ; score--) {
2913 		cumulated_sz += c->regions_score_histogram[score];
2914 		if (cumulated_sz >= quota->esz || !score)
2915 			break;
2916 	}
2917 	quota->min_score = score;
2918 }
2919 
2920 static void damos_trace_stat(struct damon_ctx *c, struct damos *s)
2921 {
2922 	unsigned int cidx = 0, sidx = 0;
2923 	struct damos *siter;
2924 
2925 	if (!trace_damos_stat_after_apply_interval_enabled())
2926 		return;
2927 
2928 	damon_for_each_scheme(siter, c) {
2929 		if (siter == s)
2930 			break;
2931 		sidx++;
2932 	}
2933 	trace_call__damos_stat_after_apply_interval(cidx, sidx, &s->stat);
2934 }
2935 
2936 static void kdamond_apply_schemes(struct damon_ctx *c)
2937 {
2938 	struct damon_target *t;
2939 	struct damos *s;
2940 	bool has_schemes_to_apply = false;
2941 	unsigned long max_region_sz;
2942 
2943 	damon_for_each_scheme(s, c) {
2944 		if (time_before(c->passed_sample_intervals, s->next_apply_sis))
2945 			continue;
2946 
2947 		if (!s->wmarks.activated)
2948 			continue;
2949 
2950 		has_schemes_to_apply = true;
2951 
2952 		damos_adjust_quota(c, s);
2953 	}
2954 
2955 	if (!has_schemes_to_apply)
2956 		return;
2957 
2958 	max_region_sz = damon_region_sz_limit(c);
2959 	mutex_lock(&c->walk_control_lock);
2960 	damon_for_each_target(t, c) {
2961 		if (c->ops.target_valid && c->ops.target_valid(t) == false)
2962 			continue;
2963 		damos_apply_target(c, t, max_region_sz);
2964 	}
2965 
2966 	damon_for_each_scheme(s, c) {
2967 		if (time_before(c->passed_sample_intervals, s->next_apply_sis))
2968 			continue;
2969 		damos_walk_complete(c, s);
2970 		damos_set_next_apply_sis(s, c);
2971 		s->last_applied = NULL;
2972 		damos_trace_stat(c, s);
2973 	}
2974 	mutex_unlock(&c->walk_control_lock);
2975 }
2976 
2977 #ifdef CONFIG_DAMON_DEBUG_SANITY
2978 static void damon_verify_merge_two_regions(
2979 		struct damon_region *l, struct damon_region *r)
2980 {
2981 	/* damon_merge_two_regions() may created incorrect left region */
2982 	WARN_ONCE(l->ar.start >= l->ar.end, "l: %lu-%lu, r: %lu-%lu\n",
2983 			l->ar.start, l->ar.end, r->ar.start, r->ar.end);
2984 }
2985 #else
2986 static void damon_verify_merge_two_regions(
2987 		struct damon_region *l, struct damon_region *r)
2988 {
2989 }
2990 #endif
2991 
2992 /*
2993  * Merge two adjacent regions into one region
2994  */
2995 static void damon_merge_two_regions(struct damon_target *t,
2996 		struct damon_region *l, struct damon_region *r)
2997 {
2998 	unsigned long sz_l = damon_sz_region(l), sz_r = damon_sz_region(r);
2999 	int i;
3000 
3001 	l->nr_accesses = (l->nr_accesses * sz_l + r->nr_accesses * sz_r) /
3002 			(sz_l + sz_r);
3003 	l->nr_accesses_bp = l->nr_accesses * 10000;
3004 	l->age = (l->age * sz_l + r->age * sz_r) / (sz_l + sz_r);
3005 	l->ar.end = r->ar.end;
3006 	/* todo: do this for only installed probes */
3007 	for (i = 0; i < DAMON_MAX_PROBES; i++)
3008 		l->probe_hits[i] = (l->probe_hits[i] * sz_l + r->probe_hits[i]
3009 				* sz_r) / (sz_l + sz_r);
3010 	damon_verify_merge_two_regions(l, r);
3011 	damon_destroy_region(r, t);
3012 }
3013 
3014 #ifdef CONFIG_DAMON_DEBUG_SANITY
3015 static void damon_verify_merge_regions_of(struct damon_region *r)
3016 {
3017 	WARN_ONCE(r->nr_accesses != r->nr_accesses_bp / 10000,
3018 			"nr_accesses (%u) != nr_accesses_bp (%u)\n",
3019 			r->nr_accesses, r->nr_accesses_bp);
3020 }
3021 #else
3022 static void damon_verify_merge_regions_of(struct damon_region *r)
3023 {
3024 }
3025 #endif
3026 
3027 
3028 /*
3029  * Merge adjacent regions having similar access frequencies
3030  *
3031  * t		target affected by this merge operation
3032  * thres	'->nr_accesses' diff threshold for the merge
3033  * sz_limit	size upper limit of each region
3034  */
3035 static void damon_merge_regions_of(struct damon_target *t, unsigned int thres,
3036 				   unsigned long sz_limit)
3037 {
3038 	struct damon_region *r, *prev = NULL, *next;
3039 
3040 	damon_for_each_region_safe(r, next, t) {
3041 		damon_verify_merge_regions_of(r);
3042 		if (abs(r->nr_accesses - r->last_nr_accesses) > thres)
3043 			r->age = 0;
3044 		else if ((r->nr_accesses == 0) != (r->last_nr_accesses == 0))
3045 			r->age = 0;
3046 		else
3047 			r->age++;
3048 
3049 		if (prev && prev->ar.end == r->ar.start &&
3050 		    abs(prev->nr_accesses - r->nr_accesses) <= thres &&
3051 		    damon_sz_region(prev) + damon_sz_region(r) <= sz_limit)
3052 			damon_merge_two_regions(t, prev, r);
3053 		else
3054 			prev = r;
3055 	}
3056 }
3057 
3058 /*
3059  * Merge adjacent regions having similar access frequencies
3060  *
3061  * threshold	'->nr_accesses' diff threshold for the merge
3062  * sz_limit	size upper limit of each region
3063  *
3064  * This function merges monitoring target regions which are adjacent and their
3065  * access frequencies are similar.  This is for minimizing the monitoring
3066  * overhead under the dynamically changeable access pattern.  If a merge was
3067  * unnecessarily made, later 'kdamond_split_regions()' will revert it.
3068  *
3069  * The total number of regions could be higher than the user-defined limit,
3070  * max_nr_regions for some cases.  For example, the user can update
3071  * max_nr_regions to a number that lower than the current number of regions
3072  * while DAMON is running.  For such a case, repeat merging until the limit is
3073  * met while increasing @threshold up to possible maximum level.
3074  */
3075 static void kdamond_merge_regions(struct damon_ctx *c, unsigned int threshold,
3076 				  unsigned long sz_limit)
3077 {
3078 	struct damon_target *t;
3079 	unsigned int nr_regions;
3080 	unsigned int max_thres;
3081 
3082 	max_thres = c->attrs.aggr_interval /
3083 		(c->attrs.sample_interval ?  c->attrs.sample_interval : 1);
3084 	do {
3085 		nr_regions = 0;
3086 		damon_for_each_target(t, c) {
3087 			damon_merge_regions_of(t, threshold, sz_limit);
3088 			nr_regions += damon_nr_regions(t);
3089 		}
3090 		threshold = max(1, threshold * 2);
3091 	} while (nr_regions > c->attrs.max_nr_regions &&
3092 			threshold / 2 < max_thres);
3093 }
3094 
3095 #ifdef CONFIG_DAMON_DEBUG_SANITY
3096 static void damon_verify_split_region_at(struct damon_region *r,
3097 		unsigned long sz_r)
3098 {
3099 	WARN_ONCE(sz_r == 0 || sz_r >= damon_sz_region(r),
3100 			"sz_r: %lu r: %lu-%lu (%lu)\n",
3101 			sz_r, r->ar.start, r->ar.end, damon_sz_region(r));
3102 }
3103 #else
3104 static void damon_verify_split_region_at(struct damon_region *r,
3105 		unsigned long sz_r)
3106 {
3107 }
3108 #endif
3109 
3110 /*
3111  * Split a region in two
3112  *
3113  * r		the region to be split
3114  * sz_r		size of the first sub-region that will be made
3115  */
3116 static void damon_split_region_at(struct damon_target *t,
3117 				  struct damon_region *r, unsigned long sz_r)
3118 {
3119 	struct damon_region *new;
3120 
3121 	damon_verify_split_region_at(r, sz_r);
3122 	new = damon_new_region(r->ar.start + sz_r, r->ar.end);
3123 	if (!new)
3124 		return;
3125 
3126 	r->ar.end = new->ar.start;
3127 
3128 	new->age = r->age;
3129 	new->last_nr_accesses = r->last_nr_accesses;
3130 	new->nr_accesses_bp = r->nr_accesses_bp;
3131 	new->nr_accesses = r->nr_accesses;
3132 	/* todo: do this for only installed probes */
3133 	memcpy(new->probe_hits, r->probe_hits, sizeof(r->probe_hits));
3134 
3135 	damon_insert_region(new, r, damon_next_region(r), t);
3136 }
3137 
3138 /* Split every region in the given target into 'nr_subs' regions */
3139 static void damon_split_regions_of(struct damon_ctx *ctx,
3140 				   struct damon_target *t, int nr_subs,
3141 				   unsigned long min_region_sz)
3142 {
3143 	struct damon_region *r, *next;
3144 	unsigned long sz_region, sz_sub = 0;
3145 	int i;
3146 
3147 	damon_for_each_region_safe(r, next, t) {
3148 		sz_region = damon_sz_region(r);
3149 
3150 		for (i = 0; i < nr_subs - 1 &&
3151 				sz_region > 2 * min_region_sz; i++) {
3152 			/*
3153 			 * Randomly select size of left sub-region to be at
3154 			 * least 10 percent and at most 90% of original region
3155 			 */
3156 			sz_sub = ALIGN_DOWN(damon_rand(ctx, 1, 10) *
3157 					sz_region / 10, min_region_sz);
3158 			/* Do not allow blank region */
3159 			if (sz_sub == 0 || sz_sub >= sz_region)
3160 				continue;
3161 
3162 			damon_split_region_at(t, r, sz_sub);
3163 			sz_region = sz_sub;
3164 		}
3165 	}
3166 }
3167 
3168 /*
3169  * Split every target region into randomly-sized small regions
3170  *
3171  * This function splits every target region into random-sized small regions if
3172  * current total number of the regions is equal or smaller than half of the
3173  * user-specified maximum number of regions.  This is for maximizing the
3174  * monitoring accuracy under the dynamically changeable access patterns.  If a
3175  * split was unnecessarily made, later 'kdamond_merge_regions()' will revert
3176  * it.
3177  */
3178 static void kdamond_split_regions(struct damon_ctx *ctx)
3179 {
3180 	struct damon_target *t;
3181 	unsigned int nr_regions = 0;
3182 	static unsigned int last_nr_regions;
3183 	int nr_subregions = 2;
3184 
3185 	damon_for_each_target(t, ctx)
3186 		nr_regions += damon_nr_regions(t);
3187 
3188 	if (nr_regions > ctx->attrs.max_nr_regions / 2)
3189 		return;
3190 
3191 	/* Maybe the middle of the region has different access frequency */
3192 	if (last_nr_regions == nr_regions &&
3193 			nr_regions < ctx->attrs.max_nr_regions / 3)
3194 		nr_subregions = 3;
3195 
3196 	damon_for_each_target(t, ctx)
3197 		damon_split_regions_of(ctx, t, nr_subregions,
3198 				       ctx->min_region_sz);
3199 
3200 	last_nr_regions = nr_regions;
3201 }
3202 
3203 /*
3204  * Check whether current monitoring should be stopped
3205  *
3206  * The monitoring is stopped when either the user requested to stop, or all
3207  * monitoring targets are invalid.
3208  *
3209  * Returns true if need to stop current monitoring.
3210  */
3211 static bool kdamond_need_stop(struct damon_ctx *ctx)
3212 {
3213 	struct damon_target *t;
3214 
3215 	if (kthread_should_stop())
3216 		return true;
3217 
3218 	if (!ctx->ops.target_valid)
3219 		return false;
3220 
3221 	damon_for_each_target(t, ctx) {
3222 		if (ctx->ops.target_valid(t))
3223 			return false;
3224 	}
3225 
3226 	return true;
3227 }
3228 
3229 static int damos_get_wmark_metric_value(enum damos_wmark_metric metric,
3230 					unsigned long *metric_value)
3231 {
3232 	switch (metric) {
3233 	case DAMOS_WMARK_FREE_MEM_RATE:
3234 		*metric_value = global_zone_page_state(NR_FREE_PAGES) * 1000 /
3235 		       totalram_pages();
3236 		return 0;
3237 	default:
3238 		break;
3239 	}
3240 	return -EINVAL;
3241 }
3242 
3243 /*
3244  * Returns zero if the scheme is active.  Else, returns time to wait for next
3245  * watermark check in micro-seconds.
3246  */
3247 static unsigned long damos_wmark_wait_us(struct damos *scheme)
3248 {
3249 	unsigned long metric;
3250 
3251 	if (damos_get_wmark_metric_value(scheme->wmarks.metric, &metric))
3252 		return 0;
3253 
3254 	/* higher than high watermark or lower than low watermark */
3255 	if (metric > scheme->wmarks.high || scheme->wmarks.low > metric) {
3256 		if (scheme->wmarks.activated)
3257 			pr_debug("deactivate a scheme (%d) for %s wmark\n",
3258 				 scheme->action,
3259 				 str_high_low(metric > scheme->wmarks.high));
3260 		scheme->wmarks.activated = false;
3261 		return scheme->wmarks.interval;
3262 	}
3263 
3264 	/* inactive and higher than middle watermark */
3265 	if ((scheme->wmarks.high >= metric && metric >= scheme->wmarks.mid) &&
3266 			!scheme->wmarks.activated)
3267 		return scheme->wmarks.interval;
3268 
3269 	if (!scheme->wmarks.activated)
3270 		pr_debug("activate a scheme (%d)\n", scheme->action);
3271 	scheme->wmarks.activated = true;
3272 	return 0;
3273 }
3274 
3275 static void kdamond_usleep(unsigned long usecs)
3276 {
3277 	if (usecs >= USLEEP_RANGE_UPPER_BOUND)
3278 		schedule_timeout_idle(usecs_to_jiffies(usecs));
3279 	else
3280 		usleep_range_idle(usecs, usecs + 1);
3281 }
3282 
3283 /*
3284  * kdamond_call() - handle damon_call_control objects.
3285  * @ctx:	The &struct damon_ctx of the kdamond.
3286  * @cancel:	Whether to cancel the invocation of the function.
3287  *
3288  * If there are &struct damon_call_control requests that registered via
3289  * &damon_call() on @ctx, do or cancel the invocation of the function depending
3290  * on @cancel.  @cancel is set when the kdamond is already out of the main loop
3291  * and therefore will be terminated.
3292  */
3293 static void kdamond_call(struct damon_ctx *ctx, bool cancel)
3294 {
3295 	struct damon_call_control *control, *next;
3296 	LIST_HEAD(controls);
3297 
3298 	mutex_lock(&ctx->call_controls_lock);
3299 	list_splice_tail_init(&ctx->call_controls, &controls);
3300 	mutex_unlock(&ctx->call_controls_lock);
3301 
3302 	list_for_each_entry_safe(control, next, &controls, list) {
3303 		if (!control->repeat || cancel)
3304 			list_del(&control->list);
3305 
3306 		if (cancel)
3307 			control->canceled = true;
3308 		else
3309 			control->return_code = control->fn(control->data);
3310 
3311 		if (!control->repeat)
3312 			complete(&control->completion);
3313 		else if (control->canceled && control->dealloc_on_cancel)
3314 			kfree(control);
3315 		if (!cancel && ctx->maybe_corrupted)
3316 			break;
3317 	}
3318 
3319 	mutex_lock(&ctx->call_controls_lock);
3320 	list_splice_tail(&controls, &ctx->call_controls);
3321 	mutex_unlock(&ctx->call_controls_lock);
3322 }
3323 
3324 /* Returns negative error code if it's not activated but should return */
3325 static int kdamond_wait_activation(struct damon_ctx *ctx)
3326 {
3327 	struct damos *s;
3328 	unsigned long wait_time;
3329 	unsigned long min_wait_time = 0;
3330 	bool init_wait_time = false;
3331 
3332 	while (!kdamond_need_stop(ctx)) {
3333 		damon_for_each_scheme(s, ctx) {
3334 			wait_time = damos_wmark_wait_us(s);
3335 			if (!init_wait_time || wait_time < min_wait_time) {
3336 				init_wait_time = true;
3337 				min_wait_time = wait_time;
3338 			}
3339 		}
3340 		if (!min_wait_time)
3341 			return 0;
3342 
3343 		kdamond_usleep(min_wait_time);
3344 
3345 		kdamond_call(ctx, false);
3346 		if (ctx->maybe_corrupted)
3347 			return -EINVAL;
3348 		damos_walk_cancel(ctx);
3349 	}
3350 	return -EBUSY;
3351 }
3352 
3353 static void kdamond_init_ctx(struct damon_ctx *ctx)
3354 {
3355 	unsigned long sample_interval = ctx->attrs.sample_interval ?
3356 		ctx->attrs.sample_interval : 1;
3357 	struct damos *scheme;
3358 
3359 	ctx->passed_sample_intervals = 0;
3360 	ctx->next_aggregation_sis = ctx->attrs.aggr_interval / sample_interval;
3361 	ctx->next_ops_update_sis = ctx->attrs.ops_update_interval /
3362 		sample_interval;
3363 	ctx->next_intervals_tune_sis = ctx->next_aggregation_sis *
3364 		ctx->attrs.intervals_goal.aggrs;
3365 
3366 	damon_for_each_scheme(scheme, ctx) {
3367 		damos_set_next_apply_sis(scheme, ctx);
3368 		damos_set_filters_default_reject(scheme);
3369 	}
3370 }
3371 
3372 /*
3373  * The monitoring daemon that runs as a kernel thread
3374  */
3375 static int kdamond_fn(void *data)
3376 {
3377 	struct damon_ctx *ctx = data;
3378 	unsigned int max_nr_accesses = 0;
3379 	unsigned long sz_limit = 0;
3380 
3381 	pr_debug("kdamond (%d) starts\n", current->pid);
3382 
3383 	mutex_lock(&ctx->call_controls_lock);
3384 	ctx->call_controls_obsolete = false;
3385 	mutex_unlock(&ctx->call_controls_lock);
3386 	mutex_lock(&ctx->walk_control_lock);
3387 	ctx->walk_control_obsolete = false;
3388 	mutex_unlock(&ctx->walk_control_lock);
3389 	complete(&ctx->kdamond_started);
3390 	kdamond_init_ctx(ctx);
3391 
3392 	if (ctx->ops.init)
3393 		ctx->ops.init(ctx);
3394 	ctx->regions_score_histogram = kmalloc_array(DAMOS_MAX_SCORE + 1,
3395 			sizeof(*ctx->regions_score_histogram), GFP_KERNEL);
3396 	if (!ctx->regions_score_histogram)
3397 		goto done;
3398 
3399 	sz_limit = damon_apply_min_nr_regions(ctx);
3400 
3401 	while (!kdamond_need_stop(ctx)) {
3402 		/*
3403 		 * ctx->attrs and ctx->next_{aggregation,ops_update}_sis could
3404 		 * be changed from kdamond_call().  Read the values here, and
3405 		 * use those for this iteration.  That is, damon_set_attrs()
3406 		 * updated new values are respected from next iteration.
3407 		 */
3408 		unsigned long next_aggregation_sis = ctx->next_aggregation_sis;
3409 		unsigned long next_ops_update_sis = ctx->next_ops_update_sis;
3410 		unsigned long sample_interval = ctx->attrs.sample_interval;
3411 
3412 		if (kdamond_wait_activation(ctx))
3413 			break;
3414 
3415 		if (ctx->ops.prepare_access_checks)
3416 			ctx->ops.prepare_access_checks(ctx);
3417 
3418 		kdamond_usleep(sample_interval);
3419 		ctx->passed_sample_intervals++;
3420 
3421 		if (ctx->ops.check_accesses)
3422 			max_nr_accesses = ctx->ops.check_accesses(ctx);
3423 		if (ctx->ops.apply_probes)
3424 			ctx->ops.apply_probes(ctx);
3425 
3426 		if (time_after_eq(ctx->passed_sample_intervals,
3427 					next_aggregation_sis)) {
3428 			kdamond_merge_regions(ctx,
3429 					max_nr_accesses / 10,
3430 					sz_limit);
3431 			/* online updates might be made */
3432 			sz_limit = damon_apply_min_nr_regions(ctx);
3433 		}
3434 
3435 		/*
3436 		 * do kdamond_call() and kdamond_apply_schemes() after
3437 		 * kdamond_merge_regions() if possible, to reduce overhead
3438 		 */
3439 		kdamond_call(ctx, false);
3440 		if (ctx->maybe_corrupted)
3441 			break;
3442 		while (ctx->pause) {
3443 			damos_walk_cancel(ctx);
3444 			kdamond_usleep(ctx->attrs.sample_interval);
3445 			/* allow caller unset pause via damon_call() */
3446 			kdamond_call(ctx, false);
3447 			if (kdamond_need_stop(ctx) || ctx->maybe_corrupted)
3448 				goto done;
3449 		}
3450 		if (!list_empty(&ctx->schemes))
3451 			kdamond_apply_schemes(ctx);
3452 		else
3453 			damos_walk_cancel(ctx);
3454 
3455 		sample_interval = ctx->attrs.sample_interval ?
3456 			ctx->attrs.sample_interval : 1;
3457 		if (time_after_eq(ctx->passed_sample_intervals,
3458 					next_aggregation_sis)) {
3459 			if (ctx->attrs.intervals_goal.aggrs &&
3460 					time_after_eq(
3461 						ctx->passed_sample_intervals,
3462 						ctx->next_intervals_tune_sis)) {
3463 				/*
3464 				 * ctx->next_aggregation_sis might be updated
3465 				 * from kdamond_call().  In the case,
3466 				 * damon_set_attrs() which will be called from
3467 				 * kdamond_tune_interval() may wrongly think
3468 				 * this is in the middle of the current
3469 				 * aggregation, and make aggregation
3470 				 * information reset for all regions.  Then,
3471 				 * following kdamond_reset_aggregated() call
3472 				 * will make the region information invalid,
3473 				 * particularly for ->nr_accesses_bp.
3474 				 *
3475 				 * Reset ->next_aggregation_sis to avoid that.
3476 				 * It will anyway correctly updated after this
3477 				 * if clause.
3478 				 */
3479 				ctx->next_aggregation_sis =
3480 					next_aggregation_sis;
3481 				ctx->next_intervals_tune_sis +=
3482 					ctx->attrs.aggr_samples *
3483 					ctx->attrs.intervals_goal.aggrs;
3484 				kdamond_tune_intervals(ctx);
3485 				sample_interval = ctx->attrs.sample_interval ?
3486 					ctx->attrs.sample_interval : 1;
3487 
3488 			}
3489 			ctx->next_aggregation_sis = next_aggregation_sis +
3490 				ctx->attrs.aggr_interval / sample_interval;
3491 
3492 			kdamond_reset_aggregated(ctx);
3493 			kdamond_split_regions(ctx);
3494 		}
3495 
3496 		if (time_after_eq(ctx->passed_sample_intervals,
3497 					next_ops_update_sis)) {
3498 			ctx->next_ops_update_sis = next_ops_update_sis +
3499 				ctx->attrs.ops_update_interval /
3500 				sample_interval;
3501 			if (ctx->ops.update)
3502 				ctx->ops.update(ctx);
3503 		}
3504 	}
3505 done:
3506 	damon_destroy_targets(ctx);
3507 
3508 	kfree(ctx->regions_score_histogram);
3509 	mutex_lock(&ctx->call_controls_lock);
3510 	ctx->call_controls_obsolete = true;
3511 	mutex_unlock(&ctx->call_controls_lock);
3512 	kdamond_call(ctx, true);
3513 	mutex_lock(&ctx->walk_control_lock);
3514 	ctx->walk_control_obsolete = true;
3515 	mutex_unlock(&ctx->walk_control_lock);
3516 	damos_walk_cancel(ctx);
3517 
3518 	pr_debug("kdamond (%d) finishes\n", current->pid);
3519 	mutex_lock(&ctx->kdamond_lock);
3520 	ctx->kdamond = NULL;
3521 	mutex_unlock(&ctx->kdamond_lock);
3522 
3523 	mutex_lock(&damon_lock);
3524 	nr_running_ctxs--;
3525 	if (!nr_running_ctxs && running_exclusive_ctxs)
3526 		running_exclusive_ctxs = false;
3527 	mutex_unlock(&damon_lock);
3528 
3529 	return 0;
3530 }
3531 
3532 struct damon_system_ram_range_walk_arg {
3533 	bool walked;
3534 	struct resource res;
3535 };
3536 
3537 static int damon_system_ram_walk_fn(struct resource *res, void *arg)
3538 {
3539 	struct damon_system_ram_range_walk_arg *a = arg;
3540 
3541 	if (!a->walked) {
3542 		a->walked = true;
3543 		a->res.start = res->start;
3544 	}
3545 	a->res.end = res->end;
3546 	return 0;
3547 }
3548 
3549 static unsigned long damon_res_to_core_addr(resource_size_t ra,
3550 		unsigned long addr_unit)
3551 {
3552 	/*
3553 	 * Use div_u64() for avoiding linking errors related with __udivdi3,
3554 	 * __aeabi_uldivmod, or similar problems.  This should also improve the
3555 	 * performance optimization (read div_u64() comment for the detail).
3556 	 */
3557 	if (sizeof(ra) == 8 && sizeof(addr_unit) == 4)
3558 		return div_u64(ra, addr_unit);
3559 	return ra / addr_unit;
3560 }
3561 
3562 static bool damon_find_system_rams_range(unsigned long *start,
3563 		unsigned long *end, unsigned long addr_unit)
3564 {
3565 	struct damon_system_ram_range_walk_arg arg = {};
3566 
3567 	walk_system_ram_res(0, -1, &arg, damon_system_ram_walk_fn);
3568 	if (!arg.walked)
3569 		return false;
3570 	*start = damon_res_to_core_addr(arg.res.start, addr_unit);
3571 	*end = damon_res_to_core_addr(arg.res.end + 1, addr_unit);
3572 	if (*end <= *start)
3573 		return false;
3574 	return true;
3575 }
3576 
3577 /**
3578  * damon_set_region_system_rams_default() - Set the region of the given
3579  * monitoring target as requested, or to cover all 'System RAM' resources.
3580  * @t:		The monitoring target to set the region.
3581  * @start:	The pointer to the start address of the region.
3582  * @end:	The pointer to the end address of the region.
3583  * @addr_unit:	The address unit for the damon_ctx of @t.
3584  * @min_region_sz:	Minimum region size.
3585  *
3586  * This function sets the region of @t as requested by @start and @end.  If the
3587  * values of @start and @end are zero, however, this function finds 'System
3588  * RAM' resources and sets the region to cover all the resource.  In the latter
3589  * case, this function saves the start and the end addresseses of the first and
3590  * the last resources in @start and @end, respectively.
3591  *
3592  * Return: 0 on success, negative error code otherwise.
3593  */
3594 int damon_set_region_system_rams_default(struct damon_target *t,
3595 			unsigned long *start, unsigned long *end,
3596 			unsigned long addr_unit, unsigned long min_region_sz)
3597 {
3598 	struct damon_addr_range addr_range;
3599 
3600 	if (*start > *end)
3601 		return -EINVAL;
3602 
3603 	if (!*start && !*end &&
3604 		!damon_find_system_rams_range(start, end, addr_unit))
3605 		return -EINVAL;
3606 
3607 	addr_range.start = *start;
3608 	addr_range.end = *end;
3609 	return damon_set_regions(t, &addr_range, 1, min_region_sz);
3610 }
3611 
3612 /*
3613  * damon_moving_sum() - Calculate an inferred moving sum value.
3614  * @mvsum:	Inferred sum of the last @len_window values.
3615  * @nomvsum:	Non-moving sum of the last discrete @len_window window values.
3616  * @len_window:	The number of last values to take care of.
3617  * @new_value:	New value that will be added to the pseudo moving sum.
3618  *
3619  * Moving sum (moving average * window size) is good for handling noise, but
3620  * the cost of keeping past values can be high for arbitrary window size.  This
3621  * function implements a lightweight pseudo moving sum function that doesn't
3622  * keep the past window values.
3623  *
3624  * It simply assumes there was no noise in the past, and get the no-noise
3625  * assumed past value to drop from @nomvsum and @len_window.  @nomvsum is a
3626  * non-moving sum of the last window.  For example, if @len_window is 10 and we
3627  * have 25 values, @nomvsum is the sum of the 11th to 20th values of the 25
3628  * values.  Hence, this function simply drops @nomvsum / @len_window from
3629  * given @mvsum and add @new_value.
3630  *
3631  * For example, if @len_window is 10 and @nomvsum is 50, the last 10 values for
3632  * the last window could be vary, e.g., 0, 10, 0, 10, 0, 10, 0, 0, 0, 20.  For
3633  * calculating next moving sum with a new value, we should drop 0 from 50 and
3634  * add the new value.  However, this function assumes it got value 5 for each
3635  * of the last ten times.  Based on the assumption, when the next value is
3636  * measured, it drops the assumed past value, 5 from the current sum, and add
3637  * the new value to get the updated pseduo-moving average.
3638  *
3639  * This means the value could have errors, but the errors will be disappeared
3640  * for every @len_window aligned calls.  For example, if @len_window is 10, the
3641  * pseudo moving sum with 11th value to 19th value would have an error.  But
3642  * the sum with 20th value will not have the error.
3643  *
3644  * Return: Pseudo-moving average after getting the @new_value.
3645  */
3646 static unsigned int damon_moving_sum(unsigned int mvsum, unsigned int nomvsum,
3647 		unsigned int len_window, unsigned int new_value)
3648 {
3649 	return mvsum - nomvsum / len_window + new_value;
3650 }
3651 
3652 /**
3653  * damon_update_region_access_rate() - Update the access rate of a region.
3654  * @r:		The DAMON region to update for its access check result.
3655  * @accessed:	Whether the region has accessed during last sampling interval.
3656  * @attrs:	The damon_attrs of the DAMON context.
3657  *
3658  * Update the access rate of a region with the region's last sampling interval
3659  * access check result.
3660  *
3661  * Usually this will be called by &damon_operations->check_accesses callback.
3662  */
3663 void damon_update_region_access_rate(struct damon_region *r, bool accessed,
3664 		struct damon_attrs *attrs)
3665 {
3666 	unsigned int len_window = 1;
3667 
3668 	/*
3669 	 * sample_interval can be zero, but cannot be larger than
3670 	 * aggr_interval, owing to validation of damon_set_attrs().
3671 	 */
3672 	if (attrs->sample_interval)
3673 		len_window = damon_max_nr_accesses(attrs);
3674 	r->nr_accesses_bp = damon_moving_sum(r->nr_accesses_bp,
3675 			r->last_nr_accesses * 10000, len_window,
3676 			accessed ? 10000 : 0);
3677 
3678 	if (accessed)
3679 		r->nr_accesses++;
3680 }
3681 
3682 /**
3683  * damon_initialized() - Return if DAMON is ready to be used.
3684  *
3685  * Return: true if DAMON is ready to be used, false otherwise.
3686  */
3687 bool damon_initialized(void)
3688 {
3689 	return damon_region_cache != NULL;
3690 }
3691 
3692 static int __init damon_init(void)
3693 {
3694 	damon_region_cache = KMEM_CACHE(damon_region, 0);
3695 	if (unlikely(!damon_region_cache)) {
3696 		pr_err("creating damon_region_cache fails\n");
3697 		return -ENOMEM;
3698 	}
3699 
3700 	return 0;
3701 }
3702 
3703 subsys_initcall(damon_init);
3704 
3705 #include "tests/core-kunit.h"
3706