xref: /linux/mm/damon/core.c (revision 2fd777ebdfaafaead833a04882cbe8b1cdc5bdf1)
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 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 	switch (dst->type) {
1434 	case DAMON_FILTER_TYPE_MEMCG:
1435 		dst->memcg_id = src->memcg_id;
1436 		break;
1437 	default:
1438 		break;
1439 	}
1440 }
1441 
1442 static int damon_commit_filters(struct damon_probe *dst,
1443 		struct damon_probe *src)
1444 {
1445 	struct damon_filter *dst_filter, *next, *src_filter, *new_filter;
1446 	int i = 0, j = 0;
1447 
1448 	damon_for_each_filter_safe(dst_filter, next, dst) {
1449 		src_filter = damon_nth_filter(i++, src);
1450 		if (src_filter)
1451 			damon_commit_filter(dst_filter, src_filter);
1452 		else
1453 			damon_destroy_filter(dst_filter);
1454 	}
1455 
1456 	damon_for_each_filter_safe(src_filter, next, src) {
1457 		if (j++ < i)
1458 			continue;
1459 
1460 		new_filter = damon_new_filter(src_filter->type,
1461 				src_filter->matching, src_filter->allow);
1462 		if (!new_filter)
1463 			return -ENOMEM;
1464 		switch (src_filter->type) {
1465 		case DAMON_FILTER_TYPE_MEMCG:
1466 			new_filter->memcg_id = src_filter->memcg_id;
1467 			break;
1468 		default:
1469 			break;
1470 		}
1471 		damon_add_filter(dst, new_filter);
1472 	}
1473 	return 0;
1474 }
1475 
1476 static int damon_commit_probes(struct damon_ctx *dst, struct damon_ctx *src)
1477 {
1478 	struct damon_probe *dst_probe, *next, *src_probe, *new_probe;
1479 	int i = 0, j = 0, err;
1480 
1481 	damon_for_each_probe_safe(dst_probe, next, dst) {
1482 		src_probe = damon_nth_probe(i++, src);
1483 		if (src_probe) {
1484 			err = damon_commit_filters(dst_probe, src_probe);
1485 			if (err)
1486 				return err;
1487 		} else {
1488 			damon_destroy_probe(dst_probe);
1489 		}
1490 	}
1491 
1492 	damon_for_each_probe_safe(src_probe, next, src) {
1493 		if (j++ < i)
1494 			continue;
1495 
1496 		new_probe = damon_new_probe();
1497 		if (!new_probe)
1498 			return -ENOMEM;
1499 		damon_add_probe(dst, new_probe);
1500 		err = damon_commit_filters(new_probe, src_probe);
1501 		if (err)
1502 			return err;
1503 	}
1504 	return 0;
1505 }
1506 
1507 /**
1508  * damon_commit_ctx() - Commit parameters of a DAMON context to another.
1509  * @dst:	The commit destination DAMON context.
1510  * @src:	The commit source DAMON context.
1511  *
1512  * This function copies user-specified parameters from @src to @dst and update
1513  * the internal status and results accordingly.  Users should use this function
1514  * for context-level parameters update of running context, instead of manual
1515  * in-place updates.
1516  *
1517  * This function should be called from parameters-update safe context, like
1518  * damon_call().
1519  */
1520 int damon_commit_ctx(struct damon_ctx *dst, struct damon_ctx *src)
1521 {
1522 	int err;
1523 	struct damos *scheme;
1524 	struct damos_quota_goal *goal;
1525 
1526 	dst->maybe_corrupted = true;
1527 	if (!is_power_of_2(src->min_region_sz))
1528 		return -EINVAL;
1529 
1530 	/* node_eligible_mem_bp metric requires PADDR ops */
1531 	if (src->ops.id != DAMON_OPS_PADDR) {
1532 		damon_for_each_scheme(scheme, src) {
1533 			struct damos_quota *quota = &scheme->quota;
1534 
1535 			damos_for_each_quota_goal(goal, quota) {
1536 				if (goal->metric ==
1537 						DAMOS_QUOTA_NODE_ELIGIBLE_MEM_BP)
1538 					return -EINVAL;
1539 			}
1540 		}
1541 	}
1542 
1543 	err = damon_commit_schemes(dst, src);
1544 	if (err)
1545 		return err;
1546 	err = damon_commit_targets(dst, src);
1547 	if (err)
1548 		return err;
1549 	/*
1550 	 * schemes and targets should be updated first, since
1551 	 * 1. damon_set_attrs() updates monitoring results of targets and
1552 	 * next_apply_sis of schemes, and
1553 	 * 2. ops update should be done after pid handling is done (target
1554 	 *    committing require putting pids).
1555 	 */
1556 	if (!damon_attrs_equals(&dst->attrs, &src->attrs)) {
1557 		err = damon_set_attrs(dst, &src->attrs);
1558 		if (err)
1559 			return err;
1560 	}
1561 	dst->pause = src->pause;
1562 	dst->ops = src->ops;
1563 	err = damon_commit_probes(dst, src);
1564 	if (err)
1565 		return err;
1566 	dst->addr_unit = src->addr_unit;
1567 	dst->min_region_sz = src->min_region_sz;
1568 
1569 	dst->maybe_corrupted = false;
1570 	return 0;
1571 }
1572 
1573 /**
1574  * damon_nr_running_ctxs() - Return number of currently running contexts.
1575  */
1576 int damon_nr_running_ctxs(void)
1577 {
1578 	int nr_ctxs;
1579 
1580 	mutex_lock(&damon_lock);
1581 	nr_ctxs = nr_running_ctxs;
1582 	mutex_unlock(&damon_lock);
1583 
1584 	return nr_ctxs;
1585 }
1586 
1587 /* Returns the size upper limit for each monitoring region */
1588 static unsigned long damon_region_sz_limit(struct damon_ctx *ctx)
1589 {
1590 	struct damon_target *t;
1591 	struct damon_region *r;
1592 	unsigned long sz = 0;
1593 
1594 	damon_for_each_target(t, ctx) {
1595 		damon_for_each_region(r, t)
1596 			sz += damon_sz_region(r);
1597 	}
1598 
1599 	if (ctx->attrs.min_nr_regions)
1600 		sz /= ctx->attrs.min_nr_regions;
1601 	if (sz < ctx->min_region_sz)
1602 		sz = ctx->min_region_sz;
1603 
1604 	return sz;
1605 }
1606 
1607 static void damon_split_region_at(struct damon_target *t,
1608 				  struct damon_region *r, unsigned long sz_r);
1609 
1610 /*
1611  * damon_apply_min_nr_regions() - Make effect of min_nr_regions parameter.
1612  * @ctx:	monitoring context.
1613  *
1614  * This function implement min_nr_regions (minimum number of damon_region
1615  * objects in the given monitoring context) behavior.  It first calculates
1616  * maximum size of each region for enforcing the min_nr_regions as total size
1617  * of the regions divided by the min_nr_regions.  After that, this function
1618  * splits regions to ensure all regions are equal to or smaller than the size
1619  * limit.  Finally, this function returns the maximum size limit.
1620  *
1621  * Returns: maximum size of each region for convincing min_nr_regions.
1622  */
1623 static unsigned long damon_apply_min_nr_regions(struct damon_ctx *ctx)
1624 {
1625 	unsigned long max_region_sz = damon_region_sz_limit(ctx);
1626 	struct damon_target *t;
1627 	struct damon_region *r, *next;
1628 
1629 	max_region_sz = ALIGN(max_region_sz, ctx->min_region_sz);
1630 	damon_for_each_target(t, ctx) {
1631 		damon_for_each_region_safe(r, next, t) {
1632 			while (damon_sz_region(r) > max_region_sz) {
1633 				damon_split_region_at(t, r, max_region_sz);
1634 				r = damon_next_region(r);
1635 			}
1636 		}
1637 	}
1638 	return max_region_sz;
1639 }
1640 
1641 static int kdamond_fn(void *data);
1642 
1643 /*
1644  * __damon_start() - Starts monitoring with given context.
1645  * @ctx:	monitoring context
1646  *
1647  * This function should be called while damon_lock is hold.
1648  *
1649  * Return: 0 on success, negative error code otherwise.
1650  */
1651 static int __damon_start(struct damon_ctx *ctx)
1652 {
1653 	int err = -EBUSY;
1654 
1655 	mutex_lock(&ctx->kdamond_lock);
1656 	if (!ctx->kdamond) {
1657 		err = 0;
1658 		reinit_completion(&ctx->kdamond_started);
1659 		ctx->kdamond = kthread_run(kdamond_fn, ctx, "kdamond.%d",
1660 				nr_running_ctxs);
1661 		if (IS_ERR(ctx->kdamond)) {
1662 			err = PTR_ERR(ctx->kdamond);
1663 			ctx->kdamond = NULL;
1664 		} else {
1665 			wait_for_completion(&ctx->kdamond_started);
1666 		}
1667 	}
1668 	mutex_unlock(&ctx->kdamond_lock);
1669 
1670 	return err;
1671 }
1672 
1673 /**
1674  * damon_start() - Starts the monitorings for a given group of contexts.
1675  * @ctxs:	an array of the pointers for contexts to start monitoring
1676  * @nr_ctxs:	size of @ctxs
1677  * @exclusive:	exclusiveness of this contexts group
1678  *
1679  * This function starts a group of monitoring threads for a group of monitoring
1680  * contexts.  One thread per each context is created and run in parallel.  The
1681  * caller should handle synchronization between the threads by itself.  If
1682  * @exclusive is true and a group of threads that created by other
1683  * 'damon_start()' call is currently running, this function does nothing but
1684  * returns -EBUSY.
1685  *
1686  * Return: 0 on success, negative error code otherwise.
1687  */
1688 int damon_start(struct damon_ctx **ctxs, int nr_ctxs, bool exclusive)
1689 {
1690 	int i;
1691 	int err = 0;
1692 
1693 	for (i = 0; i < nr_ctxs; i++) {
1694 		if (!is_power_of_2(ctxs[i]->min_region_sz))
1695 			return -EINVAL;
1696 	}
1697 
1698 	mutex_lock(&damon_lock);
1699 	if ((exclusive && nr_running_ctxs) ||
1700 			(!exclusive && running_exclusive_ctxs)) {
1701 		mutex_unlock(&damon_lock);
1702 		return -EBUSY;
1703 	}
1704 
1705 	for (i = 0; i < nr_ctxs; i++) {
1706 		err = __damon_start(ctxs[i]);
1707 		if (err)
1708 			break;
1709 		nr_running_ctxs++;
1710 	}
1711 	if (exclusive && nr_running_ctxs)
1712 		running_exclusive_ctxs = true;
1713 	mutex_unlock(&damon_lock);
1714 
1715 	return err;
1716 }
1717 
1718 /*
1719  * __damon_stop() - Stops monitoring of a given context.
1720  * @ctx:	monitoring context
1721  *
1722  * Return: 0 on success, negative error code otherwise.
1723  */
1724 static int __damon_stop(struct damon_ctx *ctx)
1725 {
1726 	struct task_struct *tsk;
1727 
1728 	mutex_lock(&ctx->kdamond_lock);
1729 	tsk = ctx->kdamond;
1730 	if (tsk) {
1731 		get_task_struct(tsk);
1732 		mutex_unlock(&ctx->kdamond_lock);
1733 		kthread_stop_put(tsk);
1734 		return 0;
1735 	}
1736 	mutex_unlock(&ctx->kdamond_lock);
1737 
1738 	return -EPERM;
1739 }
1740 
1741 /**
1742  * damon_stop() - Stops the monitorings for a given group of contexts.
1743  * @ctxs:	an array of the pointers for contexts to stop monitoring
1744  * @nr_ctxs:	size of @ctxs
1745  *
1746  * Return: 0 on success, negative error code otherwise.
1747  */
1748 int damon_stop(struct damon_ctx **ctxs, int nr_ctxs)
1749 {
1750 	int i, err = 0;
1751 
1752 	for (i = 0; i < nr_ctxs; i++) {
1753 		/* nr_running_ctxs is decremented in kdamond_fn */
1754 		err = __damon_stop(ctxs[i]);
1755 		if (err)
1756 			break;
1757 	}
1758 	return err;
1759 }
1760 
1761 /**
1762  * damon_is_running() - Returns if a given DAMON context is running.
1763  * @ctx:	The DAMON context to see if running.
1764  *
1765  * Return: true if @ctx is running, false otherwise.
1766  */
1767 bool damon_is_running(struct damon_ctx *ctx)
1768 {
1769 	bool running;
1770 
1771 	mutex_lock(&ctx->kdamond_lock);
1772 	running = ctx->kdamond != NULL;
1773 	mutex_unlock(&ctx->kdamond_lock);
1774 	return running;
1775 }
1776 
1777 /**
1778  * damon_kdamond_pid() - Return pid of a given DAMON context's worker thread.
1779  * @ctx:	The DAMON context of the question.
1780  *
1781  * Return: pid if @ctx is running, negative error code otherwise.
1782  */
1783 int damon_kdamond_pid(struct damon_ctx *ctx)
1784 {
1785 	int pid = -EINVAL;
1786 
1787 	mutex_lock(&ctx->kdamond_lock);
1788 	if (ctx->kdamond)
1789 		pid = ctx->kdamond->pid;
1790 	mutex_unlock(&ctx->kdamond_lock);
1791 	return pid;
1792 }
1793 
1794 /**
1795  * damon_call() - Invoke a given function on DAMON worker thread (kdamond).
1796  * @ctx:	DAMON context to call the function for.
1797  * @control:	Control variable of the call request.
1798  *
1799  * Ask DAMON worker thread (kdamond) of @ctx to call a function with an
1800  * argument data that respectively passed via &damon_call_control->fn and
1801  * &damon_call_control->data of @control.  If &damon_call_control->repeat of
1802  * @control is unset, further wait until the kdamond finishes handling of the
1803  * request.  Otherwise, return as soon as the request is made.
1804  *
1805  * The kdamond executes the function with the argument in the main loop, just
1806  * after a sampling of the iteration is finished.  The function can hence
1807  * safely access the internal data of the &struct damon_ctx without additional
1808  * synchronization.  The return value of the function will be saved in
1809  * &damon_call_control->return_code.
1810  *
1811  * Note that this function should be called only after damon_start() with the
1812  * @ctx has succeeded.  Otherwise, this function could fall into an indefinite
1813  * wait.
1814  *
1815  * Return: 0 on success, negative error code otherwise.
1816  */
1817 int damon_call(struct damon_ctx *ctx, struct damon_call_control *control)
1818 {
1819 	if (!control->repeat)
1820 		init_completion(&control->completion);
1821 	control->canceled = false;
1822 	INIT_LIST_HEAD(&control->list);
1823 
1824 	mutex_lock(&ctx->call_controls_lock);
1825 	if (ctx->call_controls_obsolete) {
1826 		mutex_unlock(&ctx->call_controls_lock);
1827 		return -ECANCELED;
1828 	}
1829 	list_add_tail(&control->list, &ctx->call_controls);
1830 	mutex_unlock(&ctx->call_controls_lock);
1831 	if (control->repeat)
1832 		return 0;
1833 	wait_for_completion(&control->completion);
1834 	if (control->canceled)
1835 		return -ECANCELED;
1836 	return 0;
1837 }
1838 
1839 /**
1840  * damos_walk() - Invoke a given functions while DAMOS walk regions.
1841  * @ctx:	DAMON context to call the functions for.
1842  * @control:	Control variable of the walk request.
1843  *
1844  * Ask DAMON worker thread (kdamond) of @ctx to call a function for each region
1845  * that the kdamond will apply DAMOS action to, and wait until the kdamond
1846  * finishes handling of the request.
1847  *
1848  * The kdamond executes the given function in the main loop, for each region
1849  * just after it applied any DAMOS actions of @ctx to it.  The invocation is
1850  * made only within one &damos->apply_interval_us since damos_walk()
1851  * invocation, for each scheme.  The given callback function can hence safely
1852  * access the internal data of &struct damon_ctx and &struct damon_region that
1853  * each of the scheme will apply the action for next interval, without
1854  * additional synchronizations against the kdamond.  If every scheme of @ctx
1855  * passed at least one &damos->apply_interval_us, kdamond marks the request as
1856  * completed so that damos_walk() can wakeup and return.
1857  *
1858  * Note that this function should be called only after damon_start() with the
1859  * @ctx has succeeded.  Otherwise, this function could fall into an indefinite
1860  * wait.
1861  *
1862  * Return: 0 on success, negative error code otherwise.
1863  */
1864 int damos_walk(struct damon_ctx *ctx, struct damos_walk_control *control)
1865 {
1866 	init_completion(&control->completion);
1867 	control->canceled = false;
1868 	mutex_lock(&ctx->walk_control_lock);
1869 	if (ctx->walk_control_obsolete) {
1870 		mutex_unlock(&ctx->walk_control_lock);
1871 		return -ECANCELED;
1872 	}
1873 	if (ctx->walk_control) {
1874 		mutex_unlock(&ctx->walk_control_lock);
1875 		return -EBUSY;
1876 	}
1877 	ctx->walk_control = control;
1878 	mutex_unlock(&ctx->walk_control_lock);
1879 	wait_for_completion(&control->completion);
1880 	if (control->canceled)
1881 		return -ECANCELED;
1882 	return 0;
1883 }
1884 
1885 /*
1886  * Warn and fix corrupted ->nr_accesses[_bp] for investigations and preventing
1887  * the problem being propagated.
1888  */
1889 static void damon_warn_fix_nr_accesses_corruption(struct damon_region *r)
1890 {
1891 	if (r->nr_accesses_bp == r->nr_accesses * 10000)
1892 		return;
1893 	WARN_ONCE(true, "invalid nr_accesses_bp at reset: %u %u\n",
1894 			r->nr_accesses_bp, r->nr_accesses);
1895 	r->nr_accesses_bp = r->nr_accesses * 10000;
1896 }
1897 
1898 #ifdef CONFIG_DAMON_DEBUG_SANITY
1899 static void damon_verify_reset_aggregated(struct damon_region *r,
1900 		struct damon_ctx *c)
1901 {
1902 	WARN_ONCE(r->nr_accesses_bp != r->last_nr_accesses * 10000,
1903 			"nr_accesses_bp %u last_nr_accesses %u sis %lu %lu\n",
1904 			r->nr_accesses_bp, r->last_nr_accesses,
1905 			c->passed_sample_intervals, c->next_aggregation_sis);
1906 }
1907 #else
1908 static void damon_verify_reset_aggregated(struct damon_region *r,
1909 		struct damon_ctx *c)
1910 {
1911 }
1912 #endif
1913 
1914 
1915 /*
1916  * Reset the aggregated monitoring results ('nr_accesses' of each region).
1917  */
1918 static void kdamond_reset_aggregated(struct damon_ctx *c)
1919 {
1920 	struct damon_target *t;
1921 	unsigned int ti = 0;	/* target's index */
1922 	unsigned int nr_probes = 0;
1923 	struct damon_probe *probe;
1924 
1925 	if (trace_damon_region_aggregated_enabled()) {
1926 		damon_for_each_probe(probe, c)
1927 			nr_probes++;
1928 	}
1929 
1930 	damon_for_each_target(t, c) {
1931 		struct damon_region *r;
1932 
1933 		damon_for_each_region(r, t) {
1934 			int i;
1935 
1936 			trace_damon_aggregated(ti, r, damon_nr_regions(t));
1937 			trace_damon_region_aggregated(ti, r,
1938 					damon_nr_regions(t), nr_probes);
1939 			damon_warn_fix_nr_accesses_corruption(r);
1940 			r->last_nr_accesses = r->nr_accesses;
1941 			r->nr_accesses = 0;
1942 			for (i = 0; i < DAMON_MAX_PROBES; i++)
1943 				r->probe_hits[i] = 0;
1944 			damon_verify_reset_aggregated(r, c);
1945 		}
1946 		ti++;
1947 	}
1948 }
1949 
1950 static unsigned long damon_get_intervals_score(struct damon_ctx *c)
1951 {
1952 	struct damon_target *t;
1953 	struct damon_region *r;
1954 	unsigned long sz_region, max_access_events = 0, access_events = 0;
1955 	unsigned long target_access_events;
1956 	unsigned long goal_bp = c->attrs.intervals_goal.access_bp;
1957 
1958 	damon_for_each_target(t, c) {
1959 		damon_for_each_region(r, t) {
1960 			sz_region = damon_sz_region(r);
1961 			max_access_events += sz_region * c->attrs.aggr_samples;
1962 			access_events += sz_region * r->nr_accesses;
1963 		}
1964 	}
1965 	target_access_events = max_access_events * goal_bp / 10000;
1966 	target_access_events = target_access_events ? : 1;
1967 	return mult_frac(access_events, 10000, target_access_events);
1968 }
1969 
1970 static unsigned long damon_feed_loop_next_input(unsigned long last_input,
1971 		unsigned long score);
1972 
1973 static unsigned long damon_get_intervals_adaptation_bp(struct damon_ctx *c)
1974 {
1975 	unsigned long score_bp, adaptation_bp;
1976 
1977 	score_bp = damon_get_intervals_score(c);
1978 	adaptation_bp = damon_feed_loop_next_input(100000000, score_bp) /
1979 		10000;
1980 	/*
1981 	 * adaptation_bp ranges from 1 to 20,000.  Avoid too rapid reduction of
1982 	 * the intervals by rescaling [1,10,000] to [5000, 10,000].
1983 	 */
1984 	if (adaptation_bp <= 10000)
1985 		adaptation_bp = 5000 + adaptation_bp / 2;
1986 	return adaptation_bp;
1987 }
1988 
1989 static void kdamond_tune_intervals(struct damon_ctx *c)
1990 {
1991 	unsigned long adaptation_bp;
1992 	struct damon_attrs new_attrs;
1993 	struct damon_intervals_goal *goal;
1994 
1995 	adaptation_bp = damon_get_intervals_adaptation_bp(c);
1996 	if (adaptation_bp == 10000)
1997 		return;
1998 
1999 	new_attrs = c->attrs;
2000 	goal = &c->attrs.intervals_goal;
2001 	new_attrs.sample_interval = min(goal->max_sample_us,
2002 			c->attrs.sample_interval * adaptation_bp / 10000);
2003 	new_attrs.sample_interval = max(goal->min_sample_us,
2004 			new_attrs.sample_interval);
2005 	new_attrs.aggr_interval = new_attrs.sample_interval *
2006 		c->attrs.aggr_samples;
2007 	trace_damon_monitor_intervals_tune(new_attrs.sample_interval);
2008 	damon_set_attrs(c, &new_attrs);
2009 }
2010 
2011 static bool __damos_valid_target(struct damon_region *r, struct damos *s)
2012 {
2013 	unsigned long sz;
2014 	unsigned int nr_accesses = r->nr_accesses_bp / 10000;
2015 
2016 	sz = damon_sz_region(r);
2017 	return s->pattern.min_sz_region <= sz &&
2018 		sz <= s->pattern.max_sz_region &&
2019 		s->pattern.min_nr_accesses <= nr_accesses &&
2020 		nr_accesses <= s->pattern.max_nr_accesses &&
2021 		s->pattern.min_age_region <= r->age &&
2022 		r->age <= s->pattern.max_age_region;
2023 }
2024 
2025 /*
2026  * damos_quota_is_set() - Return if the given quota is actually set.
2027  * @quota:	The quota to check.
2028  *
2029  * Returns true if the quota is set, false otherwise.
2030  */
2031 static bool damos_quota_is_set(struct damos_quota *quota)
2032 {
2033 	return quota->esz || quota->sz || quota->ms ||
2034 		!damos_quota_goals_empty(quota);
2035 }
2036 
2037 static bool damos_valid_target(struct damon_ctx *c, struct damon_region *r,
2038 		struct damos *s)
2039 {
2040 	bool ret = __damos_valid_target(r, s);
2041 
2042 	if (!ret || !damos_quota_is_set(&s->quota) || !c->ops.get_scheme_score)
2043 		return ret;
2044 
2045 	return c->ops.get_scheme_score(c, r, s) >= s->quota.min_score;
2046 }
2047 
2048 /*
2049  * damos_skip_charged_region() - Check if the given region or starting part of
2050  * it is already charged for the DAMOS quota.
2051  * @t:	The target of the region.
2052  * @rp:	The pointer to the region.
2053  * @s:	The scheme to be applied.
2054  * @min_region_sz:	minimum region size.
2055  *
2056  * If a quota of a scheme has exceeded in a quota charge window, the scheme's
2057  * action would applied to only a part of the target access pattern fulfilling
2058  * regions.  To avoid applying the scheme action to only already applied
2059  * regions, DAMON skips applying the scheme action to the regions that charged
2060  * in the previous charge window.
2061  *
2062  * This function checks if a given region should be skipped or not for the
2063  * reason.  If only the starting part of the region has previously charged,
2064  * this function splits the region into two so that the second one covers the
2065  * area that not charged in the previous charge widnow, and return true.  The
2066  * caller can see the second one on the next iteration of the region walk.
2067  * Note that this means the caller should use damon_for_each_region() instead
2068  * of damon_for_each_region_safe().  If damon_for_each_region_safe() is used,
2069  * the second region will just be ignored.
2070  *
2071  * Return: true if the region should be skipped, false otherwise.
2072  */
2073 static bool damos_skip_charged_region(struct damon_target *t,
2074 		struct damon_region *r, struct damos *s,
2075 		unsigned long min_region_sz)
2076 {
2077 	struct damos_quota *quota = &s->quota;
2078 	unsigned long sz_to_skip;
2079 
2080 	/* Skip previously charged regions */
2081 	if (quota->charge_target_from) {
2082 		if (t != quota->charge_target_from)
2083 			return true;
2084 		if (r == damon_last_region(t)) {
2085 			quota->charge_target_from = NULL;
2086 			quota->charge_addr_from = 0;
2087 			return true;
2088 		}
2089 		if (quota->charge_addr_from &&
2090 				r->ar.end <= quota->charge_addr_from)
2091 			return true;
2092 
2093 		if (quota->charge_addr_from && r->ar.start <
2094 				quota->charge_addr_from) {
2095 			sz_to_skip = ALIGN_DOWN(quota->charge_addr_from -
2096 					r->ar.start, min_region_sz);
2097 			if (!sz_to_skip) {
2098 				if (damon_sz_region(r) <= min_region_sz)
2099 					return true;
2100 				sz_to_skip = min_region_sz;
2101 			}
2102 			damon_split_region_at(t, r, sz_to_skip);
2103 			return true;
2104 		}
2105 		quota->charge_target_from = NULL;
2106 		quota->charge_addr_from = 0;
2107 	}
2108 	return false;
2109 }
2110 
2111 static void damos_update_stat(struct damos *s,
2112 		unsigned long sz_tried, unsigned long sz_applied,
2113 		unsigned long sz_ops_filter_passed)
2114 {
2115 	s->stat.nr_tried++;
2116 	s->stat.sz_tried += sz_tried;
2117 	if (sz_applied)
2118 		s->stat.nr_applied++;
2119 	s->stat.sz_applied += sz_applied;
2120 	s->stat.sz_ops_filter_passed += sz_ops_filter_passed;
2121 }
2122 
2123 static bool damos_filter_match(struct damon_ctx *ctx, struct damon_target *t,
2124 		struct damon_region *r, struct damos_filter *filter,
2125 		unsigned long min_region_sz)
2126 {
2127 	bool matched = false;
2128 	struct damon_target *ti;
2129 	int target_idx = 0;
2130 	unsigned long start, end;
2131 
2132 	switch (filter->type) {
2133 	case DAMOS_FILTER_TYPE_TARGET:
2134 		damon_for_each_target(ti, ctx) {
2135 			if (ti == t)
2136 				break;
2137 			target_idx++;
2138 		}
2139 		matched = target_idx == filter->target_idx;
2140 		break;
2141 	case DAMOS_FILTER_TYPE_ADDR:
2142 		start = ALIGN_DOWN(filter->addr_range.start, min_region_sz);
2143 		end = ALIGN_DOWN(filter->addr_range.end, min_region_sz);
2144 
2145 		/* inside the range */
2146 		if (start <= r->ar.start && r->ar.end <= end) {
2147 			matched = true;
2148 			break;
2149 		}
2150 		/* outside of the range */
2151 		if (r->ar.end <= start || end <= r->ar.start) {
2152 			matched = false;
2153 			break;
2154 		}
2155 		/* start before the range and overlap */
2156 		if (r->ar.start < start) {
2157 			damon_split_region_at(t, r, start - r->ar.start);
2158 			matched = false;
2159 			break;
2160 		}
2161 		/* start inside the range */
2162 		damon_split_region_at(t, r, end - r->ar.start);
2163 		matched = true;
2164 		break;
2165 	default:
2166 		return false;
2167 	}
2168 
2169 	return matched == filter->matching;
2170 }
2171 
2172 static bool damos_core_filter_out(struct damon_ctx *ctx, struct damon_target *t,
2173 		struct damon_region *r, struct damos *s)
2174 {
2175 	struct damos_filter *filter;
2176 
2177 	s->core_filters_allowed = false;
2178 	damos_for_each_core_filter(filter, s) {
2179 		if (damos_filter_match(ctx, t, r, filter, ctx->min_region_sz)) {
2180 			if (filter->allow)
2181 				s->core_filters_allowed = true;
2182 			return !filter->allow;
2183 		}
2184 	}
2185 	return s->core_filters_default_reject;
2186 }
2187 
2188 /*
2189  * damos_walk_call_walk() - Call &damos_walk_control->walk_fn.
2190  * @ctx:	The context of &damon_ctx->walk_control.
2191  * @t:		The monitoring target of @r that @s will be applied.
2192  * @r:		The region of @t that @s will be applied.
2193  * @s:		The scheme of @ctx that will be applied to @r.
2194  *
2195  * This function is called from kdamond whenever it asked the operation set to
2196  * apply a DAMOS scheme action to a region.  If a DAMOS walk request is
2197  * installed by damos_walk() and not yet uninstalled, invoke it.
2198  */
2199 static void damos_walk_call_walk(struct damon_ctx *ctx, struct damon_target *t,
2200 		struct damon_region *r, struct damos *s,
2201 		unsigned long sz_filter_passed)
2202 {
2203 	struct damos_walk_control *control;
2204 
2205 	if (s->walk_completed)
2206 		return;
2207 
2208 	control = ctx->walk_control;
2209 	if (!control)
2210 		return;
2211 
2212 	control->walk_fn(control->data, ctx, t, r, s, sz_filter_passed);
2213 }
2214 
2215 /*
2216  * damos_walk_complete() - Complete DAMOS walk request if all walks are done.
2217  * @ctx:	The context of &damon_ctx->walk_control.
2218  * @s:		A scheme of @ctx that all walks are now done.
2219  *
2220  * This function is called when kdamond finished applying the action of a DAMOS
2221  * scheme to all regions that eligible for the given &damos->apply_interval_us.
2222  * If every scheme of @ctx including @s now finished walking for at least one
2223  * &damos->apply_interval_us, this function makrs the handling of the given
2224  * DAMOS walk request is done, so that damos_walk() can wake up and return.
2225  */
2226 static void damos_walk_complete(struct damon_ctx *ctx, struct damos *s)
2227 {
2228 	struct damos *siter;
2229 	struct damos_walk_control *control;
2230 
2231 	control = ctx->walk_control;
2232 	if (!control)
2233 		return;
2234 
2235 	s->walk_completed = true;
2236 	/* if all schemes completed, signal completion to walker */
2237 	damon_for_each_scheme(siter, ctx) {
2238 		if (!siter->walk_completed)
2239 			return;
2240 	}
2241 	damon_for_each_scheme(siter, ctx)
2242 		siter->walk_completed = false;
2243 
2244 	complete(&control->completion);
2245 	ctx->walk_control = NULL;
2246 }
2247 
2248 /*
2249  * damos_walk_cancel() - Cancel the current DAMOS walk request.
2250  * @ctx:	The context of &damon_ctx->walk_control.
2251  *
2252  * This function is called when @ctx is deactivated by DAMOS watermarks, DAMOS
2253  * walk is requested but there is no DAMOS scheme to walk for, or the kdamond
2254  * is already out of the main loop and therefore gonna be terminated, and hence
2255  * cannot continue the walks.  This function therefore marks the walk request
2256  * as canceled, so that damos_walk() can wake up and return.
2257  */
2258 static void damos_walk_cancel(struct damon_ctx *ctx)
2259 {
2260 	struct damos_walk_control *control;
2261 
2262 	mutex_lock(&ctx->walk_control_lock);
2263 	control = ctx->walk_control;
2264 	mutex_unlock(&ctx->walk_control_lock);
2265 
2266 	if (!control)
2267 		return;
2268 	control->canceled = true;
2269 	complete(&control->completion);
2270 	mutex_lock(&ctx->walk_control_lock);
2271 	ctx->walk_control = NULL;
2272 	mutex_unlock(&ctx->walk_control_lock);
2273 }
2274 
2275 static void damos_charge_quota(struct damos_quota *quota,
2276 		unsigned long sz_region, unsigned long sz_applied)
2277 {
2278 	/*
2279 	 * sz_applied could be bigger than sz_region, depending on ops
2280 	 * implementation of the action, e.g., damos_pa_pageout().  Charge only
2281 	 * the region size in the case.
2282 	 */
2283 	if (!quota->fail_charge_denom || sz_applied > sz_region)
2284 		quota->charged_sz += sz_region;
2285 	else
2286 		quota->charged_sz += sz_applied + mult_frac(
2287 				(sz_region - sz_applied),
2288 				quota->fail_charge_num,
2289 				quota->fail_charge_denom);
2290 }
2291 
2292 static bool damos_quota_is_full(struct damos_quota *quota,
2293 		unsigned long min_region_sz)
2294 {
2295 	if (!damos_quota_is_set(quota))
2296 		return false;
2297 	if (quota->charged_sz >= quota->esz)
2298 		return true;
2299 	/*
2300 	 * DAMOS action is applied per region, so <min_region_sz remaining
2301 	 * quota means the quota is effectively full.
2302 	 */
2303 	return quota->esz - quota->charged_sz < min_region_sz;
2304 }
2305 
2306 static void damos_apply_scheme(struct damon_ctx *c, struct damon_target *t,
2307 		struct damon_region *r, struct damos *s)
2308 {
2309 	struct damos_quota *quota = &s->quota;
2310 	unsigned long sz = damon_sz_region(r);
2311 	struct timespec64 begin, end;
2312 	unsigned long sz_applied = 0;
2313 	unsigned long sz_ops_filter_passed = 0;
2314 	/*
2315 	 * We plan to support multiple context per kdamond, as DAMON sysfs
2316 	 * implies with 'nr_contexts' file.  Nevertheless, only single context
2317 	 * per kdamond is supported for now.  So, we can simply use '0' context
2318 	 * index here.
2319 	 */
2320 	unsigned int cidx = 0;
2321 	struct damos *siter;		/* schemes iterator */
2322 	unsigned int sidx = 0;
2323 	struct damon_target *titer;	/* targets iterator */
2324 	unsigned int tidx = 0;
2325 	bool do_trace = false;
2326 
2327 	/* get indices for trace_damos_before_apply() */
2328 	if (trace_damos_before_apply_enabled()) {
2329 		damon_for_each_scheme(siter, c) {
2330 			if (siter == s)
2331 				break;
2332 			sidx++;
2333 		}
2334 		damon_for_each_target(titer, c) {
2335 			if (titer == t)
2336 				break;
2337 			tidx++;
2338 		}
2339 		do_trace = true;
2340 	}
2341 
2342 	if (c->ops.apply_scheme) {
2343 		if (damos_quota_is_set(quota) &&
2344 				quota->charged_sz + sz > quota->esz) {
2345 			sz = ALIGN_DOWN(quota->esz - quota->charged_sz,
2346 					c->min_region_sz);
2347 			if (!sz)
2348 				goto update_stat;
2349 			damon_split_region_at(t, r, sz);
2350 		}
2351 		if (damos_core_filter_out(c, t, r, s))
2352 			return;
2353 		ktime_get_coarse_ts64(&begin);
2354 		trace_damos_before_apply(cidx, sidx, tidx, r,
2355 				damon_nr_regions(t), do_trace);
2356 		sz_applied = c->ops.apply_scheme(c, t, r, s,
2357 				&sz_ops_filter_passed);
2358 		damos_walk_call_walk(c, t, r, s, sz_ops_filter_passed);
2359 		ktime_get_coarse_ts64(&end);
2360 		quota->total_charged_ns += timespec64_to_ns(&end) -
2361 			timespec64_to_ns(&begin);
2362 		damos_charge_quota(quota, sz, sz_applied);
2363 		if (damos_quota_is_full(quota, c->min_region_sz)) {
2364 			quota->charge_target_from = t;
2365 			quota->charge_addr_from = r->ar.end;
2366 		}
2367 	}
2368 	if (s->action != DAMOS_STAT)
2369 		r->age = 0;
2370 
2371 update_stat:
2372 	damos_update_stat(s, sz, sz_applied, sz_ops_filter_passed);
2373 }
2374 
2375 static void damon_do_apply_schemes(struct damon_ctx *c,
2376 				   struct damon_target *t,
2377 				   struct damon_region *r)
2378 {
2379 	struct damos *s;
2380 
2381 	damon_for_each_scheme(s, c) {
2382 		struct damos_quota *quota = &s->quota;
2383 
2384 		if (time_before(c->passed_sample_intervals, s->next_apply_sis))
2385 			continue;
2386 
2387 		if (!s->wmarks.activated)
2388 			continue;
2389 
2390 		/* Check the quota */
2391 		if (damos_quota_is_full(quota, c->min_region_sz))
2392 			continue;
2393 
2394 		if (damos_skip_charged_region(t, r, s, c->min_region_sz))
2395 			continue;
2396 
2397 		if (s->max_nr_snapshots &&
2398 				s->max_nr_snapshots <= s->stat.nr_snapshots)
2399 			continue;
2400 
2401 		if (damos_valid_target(c, r, s))
2402 			damos_apply_scheme(c, t, r, s);
2403 
2404 		if (damon_is_last_region(r, t))
2405 			s->stat.nr_snapshots++;
2406 	}
2407 }
2408 
2409 /*
2410  * damos_apply_target() - Apply DAMOS schemes to a given target.
2411  * @c:			monitoring context to apply its DAMOS schemes to..
2412  * @t:			monitoring target to apply the schemes to.
2413  * @max_region_sz:	maximum region size for @c.
2414  *
2415  * This function could split regions for keeping the quota.  To minimize
2416  * overhead from the split operations increased number of regions, this
2417  * function will also merge regions after the schemes applying attempt is done,
2418  * for each region.  The merge operation is made only when it doesn't lose the
2419  * monitoring information and not violating @max_region_sz.
2420  *
2421  * Hence, after this function is called, the total number of regions could
2422  * be increased or reduced.  The increase could make max_nr_regions temporarily
2423  * be violated, until the next per-aggregation interval regions merge operation
2424  * is executed.  The decrease will not violate min_nr_regions though, since it
2425  * keeps @max_region_sz.
2426  */
2427 static void damos_apply_target(struct damon_ctx *c, struct damon_target *t,
2428 		unsigned long max_region_sz)
2429 {
2430 	struct damon_region *r;
2431 
2432 	damon_for_each_region(r, t) {
2433 		struct damon_region *prev_r;
2434 
2435 		damon_do_apply_schemes(c, t, r);
2436 		/*
2437 		 * damon_do_apply_scheems() could split the region for the
2438 		 * quota.  Keeping the new slices is an overhead.  Merge back
2439 		 * the slices into the previous region if it doesn't lose any
2440 		 * information and not violating the max_region_sz.
2441 		 */
2442 		if (damon_first_region(t) == r)
2443 			continue;
2444 		prev_r = damon_prev_region(r);
2445 		if (prev_r->ar.end != r->ar.start)
2446 			continue;
2447 		if (prev_r->age != r->age)
2448 			continue;
2449 		if (prev_r->last_nr_accesses != r->last_nr_accesses)
2450 			continue;
2451 		if (prev_r->nr_accesses != r->nr_accesses)
2452 			continue;
2453 		if (r->ar.end - prev_r->ar.start > max_region_sz)
2454 			continue;
2455 		prev_r->ar.end = r->ar.end;
2456 		damon_destroy_region(r, t);
2457 		r = prev_r;
2458 	}
2459 }
2460 
2461 /*
2462  * damon_feed_loop_next_input() - get next input to achieve a target score.
2463  * @last_input	The last input.
2464  * @score	Current score that made with @last_input.
2465  *
2466  * Calculate next input to achieve the target score, based on the last input
2467  * and current score.  Assuming the input and the score are positively
2468  * proportional, calculate how much compensation should be added to or
2469  * subtracted from the last input as a proportion of the last input.  Avoid
2470  * next input always being zero by setting it non-zero always.  In short form
2471  * (assuming support of float and signed calculations), the algorithm is as
2472  * below.
2473  *
2474  * next_input = max(last_input * ((goal - current) / goal + 1), 1)
2475  *
2476  * For simple implementation, we assume the target score is always 10,000.  The
2477  * caller should adjust @score for this.
2478  *
2479  * Returns next input that assumed to achieve the target score.
2480  */
2481 static unsigned long damon_feed_loop_next_input(unsigned long last_input,
2482 		unsigned long score)
2483 {
2484 	const unsigned long goal = 10000;
2485 	/* Set minimum input as 10000 to avoid compensation be zero */
2486 	const unsigned long min_input = 10000;
2487 	unsigned long score_goal_diff, compensation;
2488 	bool over_achieving = score > goal;
2489 
2490 	if (score == goal)
2491 		return last_input;
2492 	if (score >= goal * 2)
2493 		return min_input;
2494 
2495 	if (over_achieving)
2496 		score_goal_diff = score - goal;
2497 	else
2498 		score_goal_diff = goal - score;
2499 
2500 	if (last_input < ULONG_MAX / score_goal_diff)
2501 		compensation = last_input * score_goal_diff / goal;
2502 	else
2503 		compensation = last_input / goal * score_goal_diff;
2504 
2505 	if (over_achieving)
2506 		return max(last_input - compensation, min_input);
2507 	if (last_input < ULONG_MAX - compensation)
2508 		return last_input + compensation;
2509 	return ULONG_MAX;
2510 }
2511 
2512 #ifdef CONFIG_PSI
2513 
2514 static u64 damos_get_some_mem_psi_total(void)
2515 {
2516 	if (static_branch_likely(&psi_disabled))
2517 		return 0;
2518 	return div_u64(psi_system.total[PSI_AVGS][PSI_MEM * 2],
2519 			NSEC_PER_USEC);
2520 }
2521 
2522 #else	/* CONFIG_PSI */
2523 
2524 static inline u64 damos_get_some_mem_psi_total(void)
2525 {
2526 	return 0;
2527 };
2528 
2529 #endif	/* CONFIG_PSI */
2530 
2531 #ifdef CONFIG_NUMA
2532 static bool invalid_mem_node(int nid)
2533 {
2534 	return nid < 0 || nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY);
2535 }
2536 
2537 static __kernel_ulong_t damos_get_node_mem_bp(
2538 		struct damos_quota_goal *goal)
2539 {
2540 	struct sysinfo i;
2541 	__kernel_ulong_t numerator;
2542 
2543 	if (invalid_mem_node(goal->nid)) {
2544 		if (goal->metric == DAMOS_QUOTA_NODE_MEM_USED_BP)
2545 			return 0;
2546 		else	/* DAMOS_QUOTA_NODE_MEM_FREE_BP */
2547 			return 10000;
2548 	}
2549 
2550 	si_meminfo_node(&i, goal->nid);
2551 	if (goal->metric == DAMOS_QUOTA_NODE_MEM_USED_BP)
2552 		numerator = i.totalram - i.freeram;
2553 	else	/* DAMOS_QUOTA_NODE_MEM_FREE_BP */
2554 		numerator = i.freeram;
2555 	return mult_frac(numerator, 10000, i.totalram);
2556 }
2557 
2558 static unsigned long damos_get_node_memcg_used_bp(
2559 		struct damos_quota_goal *goal)
2560 {
2561 	struct mem_cgroup *memcg;
2562 	struct lruvec *lruvec;
2563 	unsigned long used_pages, numerator;
2564 	struct sysinfo i;
2565 
2566 	if (invalid_mem_node(goal->nid)) {
2567 		if (goal->metric == DAMOS_QUOTA_NODE_MEMCG_USED_BP)
2568 			return 0;
2569 		else	/* DAMOS_QUOTA_NODE_MEMCG_FREE_BP */
2570 			return 10000;
2571 	}
2572 
2573 	memcg = mem_cgroup_get_from_id(goal->memcg_id);
2574 	if (!memcg) {
2575 		if (goal->metric == DAMOS_QUOTA_NODE_MEMCG_USED_BP)
2576 			return 0;
2577 		else	/* DAMOS_QUOTA_NODE_MEMCG_FREE_BP */
2578 			return 10000;
2579 	}
2580 
2581 	mem_cgroup_flush_stats(memcg);
2582 	lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(goal->nid));
2583 	used_pages = lruvec_page_state(lruvec, NR_ACTIVE_ANON);
2584 	used_pages += lruvec_page_state(lruvec, NR_INACTIVE_ANON);
2585 	used_pages += lruvec_page_state(lruvec, NR_ACTIVE_FILE);
2586 	used_pages += lruvec_page_state(lruvec, NR_INACTIVE_FILE);
2587 
2588 	mem_cgroup_put(memcg);
2589 
2590 	si_meminfo_node(&i, goal->nid);
2591 	if (goal->metric == DAMOS_QUOTA_NODE_MEMCG_USED_BP)
2592 		numerator = used_pages;
2593 	else	/* DAMOS_QUOTA_NODE_MEMCG_FREE_BP */
2594 		numerator = i.totalram - used_pages;
2595 	return mult_frac(numerator, 10000, i.totalram);
2596 }
2597 
2598 #ifdef CONFIG_DAMON_PADDR
2599 /*
2600  * damos_calc_eligible_bytes() - Calculate raw eligible bytes per node.
2601  * @c:		The DAMON context.
2602  * @s:		The scheme.
2603  * @nid:	The target NUMA node id.
2604  * @total:	Output for total eligible bytes across all nodes.
2605  *
2606  * Iterates through each folio in eligible regions to accurately determine
2607  * which node the memory resides on. Returns eligible bytes on the specified
2608  * node and sets *total to the sum across all nodes.
2609  *
2610  * Note: This function requires damon_get_folio() from ops-common.c, which is
2611  * only available when CONFIG_DAMON_PADDR is enabled. It also requires the
2612  * context to be using PADDR operations for meaningful results.
2613  */
2614 static phys_addr_t damos_calc_eligible_bytes(struct damon_ctx *c,
2615 		struct damos *s, int nid, phys_addr_t *total)
2616 {
2617 	struct damon_target *t;
2618 	struct damon_region *r;
2619 	phys_addr_t total_eligible = 0;
2620 	phys_addr_t node_eligible = 0;
2621 
2622 	damon_for_each_target(t, c) {
2623 		damon_for_each_region(r, t) {
2624 			phys_addr_t addr, end_addr;
2625 
2626 			if (!__damos_valid_target(r, s))
2627 				continue;
2628 
2629 			/* Convert from core address units to physical bytes */
2630 			addr = (phys_addr_t)r->ar.start * c->addr_unit;
2631 			end_addr = (phys_addr_t)r->ar.end * c->addr_unit;
2632 			while (addr < end_addr) {
2633 				struct folio *folio;
2634 				phys_addr_t folio_start, folio_end;
2635 				phys_addr_t overlap_start, overlap_end;
2636 				phys_addr_t counted;
2637 
2638 				folio = damon_get_folio(PHYS_PFN(addr));
2639 				if (!folio) {
2640 					addr = PAGE_ALIGN_DOWN(addr +
2641 							PAGE_SIZE);
2642 					if (!addr)
2643 						break;
2644 					continue;
2645 				}
2646 
2647 				/*
2648 				 * Calculate exact overlap between the region
2649 				 * [addr, end_addr) and the folio range.
2650 				 * The folio may start before addr if addr is
2651 				 * in the middle of a large folio.
2652 				 */
2653 				folio_start = PFN_PHYS(folio_pfn(folio));
2654 				folio_end = folio_start + folio_size(folio);
2655 
2656 				overlap_start = max(addr, folio_start);
2657 				overlap_end = min(end_addr, folio_end);
2658 
2659 				if (overlap_end > overlap_start) {
2660 					counted = overlap_end - overlap_start;
2661 					total_eligible += counted;
2662 					if (folio_nid(folio) == nid)
2663 						node_eligible += counted;
2664 				}
2665 
2666 				/* Advance past the entire folio */
2667 				addr = folio_end;
2668 				folio_put(folio);
2669 			}
2670 			cond_resched();
2671 		}
2672 	}
2673 
2674 	*total = total_eligible;
2675 	return node_eligible;
2676 }
2677 
2678 static unsigned long damos_get_node_eligible_mem_bp(struct damon_ctx *c,
2679 		struct damos *s, int nid)
2680 {
2681 	phys_addr_t total_eligible = 0;
2682 	phys_addr_t node_eligible;
2683 
2684 	if (c->ops.id != DAMON_OPS_PADDR)
2685 		return 0;
2686 
2687 	if (nid < 0 || nid >= MAX_NUMNODES || !node_online(nid))
2688 		return 0;
2689 
2690 	node_eligible = damos_calc_eligible_bytes(c, s, nid, &total_eligible);
2691 
2692 	if (!(unsigned long)total_eligible)
2693 		return 0;
2694 
2695 	return mult_frac((unsigned long)node_eligible, 10000,
2696 			(unsigned long)total_eligible);
2697 }
2698 #else /* CONFIG_DAMON_PADDR */
2699 static unsigned long damos_get_node_eligible_mem_bp(struct damon_ctx *c,
2700 		struct damos *s, int nid)
2701 {
2702 	return 0;
2703 }
2704 #endif /* CONFIG_DAMON_PADDR */
2705 #else /* CONFIG_NUMA */
2706 static __kernel_ulong_t damos_get_node_mem_bp(
2707 		struct damos_quota_goal *goal)
2708 {
2709 	return 0;
2710 }
2711 
2712 static unsigned long damos_get_node_memcg_used_bp(
2713 		struct damos_quota_goal *goal)
2714 {
2715 	return 0;
2716 }
2717 
2718 static unsigned long damos_get_node_eligible_mem_bp(struct damon_ctx *c,
2719 		struct damos *s, int nid)
2720 {
2721 	return 0;
2722 }
2723 #endif /* CONFIG_NUMA */
2724 
2725 /*
2726  * Returns LRU-active or inactive memory to total LRU memory size ratio.
2727  */
2728 static unsigned int damos_get_in_active_mem_bp(bool active_ratio)
2729 {
2730 	unsigned long active, inactive, total;
2731 
2732 	/* This should align with /proc/meminfo output */
2733 	active = global_node_page_state(NR_LRU_BASE + LRU_ACTIVE_ANON) +
2734 		global_node_page_state(NR_LRU_BASE + LRU_ACTIVE_FILE);
2735 	inactive = global_node_page_state(NR_LRU_BASE + LRU_INACTIVE_ANON) +
2736 		global_node_page_state(NR_LRU_BASE + LRU_INACTIVE_FILE);
2737 	total = active + inactive;
2738 	if (active_ratio)
2739 		return mult_frac(active, 10000, total);
2740 	return mult_frac(inactive, 10000, total);
2741 }
2742 
2743 static void damos_set_quota_goal_current_value(struct damon_ctx *c,
2744 		struct damos *s, struct damos_quota_goal *goal)
2745 {
2746 	u64 now_psi_total;
2747 
2748 	switch (goal->metric) {
2749 	case DAMOS_QUOTA_USER_INPUT:
2750 		/* User should already set goal->current_value */
2751 		break;
2752 	case DAMOS_QUOTA_SOME_MEM_PSI_US:
2753 		now_psi_total = damos_get_some_mem_psi_total();
2754 		goal->current_value = now_psi_total - goal->last_psi_total;
2755 		goal->last_psi_total = now_psi_total;
2756 		break;
2757 	case DAMOS_QUOTA_NODE_MEM_USED_BP:
2758 	case DAMOS_QUOTA_NODE_MEM_FREE_BP:
2759 		goal->current_value = damos_get_node_mem_bp(goal);
2760 		break;
2761 	case DAMOS_QUOTA_NODE_MEMCG_USED_BP:
2762 	case DAMOS_QUOTA_NODE_MEMCG_FREE_BP:
2763 		goal->current_value = damos_get_node_memcg_used_bp(goal);
2764 		break;
2765 	case DAMOS_QUOTA_ACTIVE_MEM_BP:
2766 	case DAMOS_QUOTA_INACTIVE_MEM_BP:
2767 		goal->current_value = damos_get_in_active_mem_bp(
2768 				goal->metric == DAMOS_QUOTA_ACTIVE_MEM_BP);
2769 		break;
2770 	case DAMOS_QUOTA_NODE_ELIGIBLE_MEM_BP:
2771 		goal->current_value = damos_get_node_eligible_mem_bp(c, s,
2772 				goal->nid);
2773 		break;
2774 	default:
2775 		break;
2776 	}
2777 }
2778 
2779 /* Return the highest score since it makes schemes least aggressive */
2780 static unsigned long damos_quota_score(struct damon_ctx *c, struct damos *s)
2781 {
2782 	struct damos_quota_goal *goal;
2783 	struct damos_quota *quota = &s->quota;
2784 	unsigned long highest_score = 0;
2785 
2786 	damos_for_each_quota_goal(goal, quota) {
2787 		damos_set_quota_goal_current_value(c, s, goal);
2788 		highest_score = max(highest_score,
2789 				mult_frac(goal->current_value, 10000,
2790 					goal->target_value));
2791 	}
2792 
2793 	return highest_score;
2794 }
2795 
2796 static void damos_goal_tune_esz_bp_consist(struct damon_ctx *c, struct damos *s)
2797 {
2798 	struct damos_quota *quota = &s->quota;
2799 	unsigned long score = damos_quota_score(c, s);
2800 
2801 	quota->esz_bp = damon_feed_loop_next_input(
2802 			max(quota->esz_bp, 10000UL), score);
2803 }
2804 
2805 static void damos_goal_tune_esz_bp_temporal(struct damon_ctx *c,
2806 		struct damos *s)
2807 {
2808 	struct damos_quota *quota = &s->quota;
2809 	unsigned long score = damos_quota_score(c, s);
2810 
2811 	if (score >= 10000)
2812 		quota->esz_bp = 0;
2813 	else if (quota->sz)
2814 		quota->esz_bp = quota->sz * 10000;
2815 	else
2816 		quota->esz_bp = ULONG_MAX;
2817 }
2818 
2819 /*
2820  * Called only if quota->ms, or quota->sz are set, or quota->goals is not empty
2821  */
2822 static void damos_set_effective_quota(struct damon_ctx *ctx, struct damos *s)
2823 {
2824 	struct damos_quota *quota = &s->quota;
2825 	unsigned long throughput;
2826 	unsigned long esz = ULONG_MAX;
2827 
2828 	if (!quota->ms && list_empty(&quota->goals)) {
2829 		quota->esz = quota->sz;
2830 		return;
2831 	}
2832 
2833 	if (!list_empty(&quota->goals)) {
2834 		if (quota->goal_tuner == DAMOS_QUOTA_GOAL_TUNER_CONSIST)
2835 			damos_goal_tune_esz_bp_consist(ctx, s);
2836 		else if (quota->goal_tuner == DAMOS_QUOTA_GOAL_TUNER_TEMPORAL)
2837 			damos_goal_tune_esz_bp_temporal(ctx, s);
2838 		esz = quota->esz_bp / 10000;
2839 	}
2840 
2841 	if (quota->ms) {
2842 		if (quota->total_charged_ns)
2843 			throughput = mult_frac(quota->total_charged_sz,
2844 					1000000, quota->total_charged_ns);
2845 		else
2846 			throughput = PAGE_SIZE * 1024;
2847 		esz = min(throughput * quota->ms, esz);
2848 		esz = max(ctx->min_region_sz, esz);
2849 	}
2850 
2851 	if (quota->sz && quota->sz < esz)
2852 		esz = quota->sz;
2853 
2854 	quota->esz = esz;
2855 }
2856 
2857 static void damos_trace_esz(struct damon_ctx *c, struct damos *s,
2858 		struct damos_quota *quota)
2859 {
2860 	unsigned int cidx = 0, sidx = 0;
2861 	struct damos *siter;
2862 
2863 	damon_for_each_scheme(siter, c) {
2864 		if (siter == s)
2865 			break;
2866 		sidx++;
2867 	}
2868 	trace_damos_esz(cidx, sidx, quota->esz);
2869 }
2870 
2871 static void damos_adjust_quota(struct damon_ctx *c, struct damos *s)
2872 {
2873 	struct damos_quota *quota = &s->quota;
2874 	struct damon_target *t;
2875 	struct damon_region *r;
2876 	unsigned long cumulated_sz, cached_esz;
2877 	unsigned int score, max_score = 0;
2878 
2879 	if (!quota->ms && !quota->sz && list_empty(&quota->goals))
2880 		return;
2881 
2882 	/* First charge window */
2883 	if (!quota->total_charged_sz && !quota->charged_from) {
2884 		quota->charged_from = jiffies;
2885 		damos_set_effective_quota(c, s);
2886 	}
2887 
2888 	/* New charge window starts */
2889 	if (!time_in_range_open(jiffies, quota->charged_from,
2890 				quota->charged_from +
2891 				msecs_to_jiffies(quota->reset_interval))) {
2892 		if (damos_quota_is_full(quota, c->min_region_sz))
2893 			s->stat.qt_exceeds++;
2894 		quota->total_charged_sz += quota->charged_sz;
2895 		quota->charged_from = jiffies;
2896 		quota->charged_sz = 0;
2897 		if (trace_damos_esz_enabled())
2898 			cached_esz = quota->esz;
2899 		damos_set_effective_quota(c, s);
2900 		if (trace_damos_esz_enabled() && quota->esz != cached_esz)
2901 			damos_trace_esz(c, s, quota);
2902 	}
2903 
2904 	if (!c->ops.get_scheme_score)
2905 		return;
2906 
2907 	/* Fill up the score histogram */
2908 	memset(c->regions_score_histogram, 0,
2909 			sizeof(*c->regions_score_histogram) *
2910 			(DAMOS_MAX_SCORE + 1));
2911 	damon_for_each_target(t, c) {
2912 		damon_for_each_region(r, t) {
2913 			if (!__damos_valid_target(r, s))
2914 				continue;
2915 			if (damos_core_filter_out(c, t, r, s))
2916 				continue;
2917 			score = c->ops.get_scheme_score(c, r, s);
2918 			c->regions_score_histogram[score] +=
2919 				damon_sz_region(r);
2920 			if (score > max_score)
2921 				max_score = score;
2922 		}
2923 	}
2924 
2925 	/* Set the min score limit */
2926 	for (cumulated_sz = 0, score = max_score; ; score--) {
2927 		cumulated_sz += c->regions_score_histogram[score];
2928 		if (cumulated_sz >= quota->esz || !score)
2929 			break;
2930 	}
2931 	quota->min_score = score;
2932 }
2933 
2934 static void damos_trace_stat(struct damon_ctx *c, struct damos *s)
2935 {
2936 	unsigned int cidx = 0, sidx = 0;
2937 	struct damos *siter;
2938 
2939 	if (!trace_damos_stat_after_apply_interval_enabled())
2940 		return;
2941 
2942 	damon_for_each_scheme(siter, c) {
2943 		if (siter == s)
2944 			break;
2945 		sidx++;
2946 	}
2947 	trace_call__damos_stat_after_apply_interval(cidx, sidx, &s->stat);
2948 }
2949 
2950 static void kdamond_apply_schemes(struct damon_ctx *c)
2951 {
2952 	struct damon_target *t;
2953 	struct damos *s;
2954 	bool has_schemes_to_apply = false;
2955 	unsigned long max_region_sz;
2956 
2957 	damon_for_each_scheme(s, c) {
2958 		if (time_before(c->passed_sample_intervals, s->next_apply_sis))
2959 			continue;
2960 
2961 		if (!s->wmarks.activated)
2962 			continue;
2963 
2964 		has_schemes_to_apply = true;
2965 
2966 		damos_adjust_quota(c, s);
2967 	}
2968 
2969 	if (!has_schemes_to_apply)
2970 		return;
2971 
2972 	max_region_sz = damon_region_sz_limit(c);
2973 	mutex_lock(&c->walk_control_lock);
2974 	damon_for_each_target(t, c) {
2975 		if (c->ops.target_valid && c->ops.target_valid(t) == false)
2976 			continue;
2977 		damos_apply_target(c, t, max_region_sz);
2978 	}
2979 
2980 	damon_for_each_scheme(s, c) {
2981 		if (time_before(c->passed_sample_intervals, s->next_apply_sis))
2982 			continue;
2983 		damos_walk_complete(c, s);
2984 		damos_set_next_apply_sis(s, c);
2985 		s->last_applied = NULL;
2986 		damos_trace_stat(c, s);
2987 	}
2988 	mutex_unlock(&c->walk_control_lock);
2989 }
2990 
2991 #ifdef CONFIG_DAMON_DEBUG_SANITY
2992 static void damon_verify_merge_two_regions(
2993 		struct damon_region *l, struct damon_region *r)
2994 {
2995 	/* damon_merge_two_regions() may created incorrect left region */
2996 	WARN_ONCE(l->ar.start >= l->ar.end, "l: %lu-%lu, r: %lu-%lu\n",
2997 			l->ar.start, l->ar.end, r->ar.start, r->ar.end);
2998 }
2999 #else
3000 static void damon_verify_merge_two_regions(
3001 		struct damon_region *l, struct damon_region *r)
3002 {
3003 }
3004 #endif
3005 
3006 /*
3007  * Merge two adjacent regions into one region
3008  */
3009 static void damon_merge_two_regions(struct damon_target *t,
3010 		struct damon_region *l, struct damon_region *r)
3011 {
3012 	unsigned long sz_l = damon_sz_region(l), sz_r = damon_sz_region(r);
3013 	int i;
3014 
3015 	l->nr_accesses = (l->nr_accesses * sz_l + r->nr_accesses * sz_r) /
3016 			(sz_l + sz_r);
3017 	l->nr_accesses_bp = l->nr_accesses * 10000;
3018 	l->age = (l->age * sz_l + r->age * sz_r) / (sz_l + sz_r);
3019 	l->ar.end = r->ar.end;
3020 	/* todo: do this for only installed probes */
3021 	for (i = 0; i < DAMON_MAX_PROBES; i++)
3022 		l->probe_hits[i] = (l->probe_hits[i] * sz_l + r->probe_hits[i]
3023 				* sz_r) / (sz_l + sz_r);
3024 	damon_verify_merge_two_regions(l, r);
3025 	damon_destroy_region(r, t);
3026 }
3027 
3028 #ifdef CONFIG_DAMON_DEBUG_SANITY
3029 static void damon_verify_merge_regions_of(struct damon_region *r)
3030 {
3031 	WARN_ONCE(r->nr_accesses != r->nr_accesses_bp / 10000,
3032 			"nr_accesses (%u) != nr_accesses_bp (%u)\n",
3033 			r->nr_accesses, r->nr_accesses_bp);
3034 }
3035 #else
3036 static void damon_verify_merge_regions_of(struct damon_region *r)
3037 {
3038 }
3039 #endif
3040 
3041 
3042 /*
3043  * Merge adjacent regions having similar access frequencies
3044  *
3045  * t		target affected by this merge operation
3046  * thres	'->nr_accesses' diff threshold for the merge
3047  * sz_limit	size upper limit of each region
3048  */
3049 static void damon_merge_regions_of(struct damon_target *t, unsigned int thres,
3050 				   unsigned long sz_limit)
3051 {
3052 	struct damon_region *r, *prev = NULL, *next;
3053 
3054 	damon_for_each_region_safe(r, next, t) {
3055 		damon_verify_merge_regions_of(r);
3056 		if (abs(r->nr_accesses - r->last_nr_accesses) > thres)
3057 			r->age = 0;
3058 		else if ((r->nr_accesses == 0) != (r->last_nr_accesses == 0))
3059 			r->age = 0;
3060 		else
3061 			r->age++;
3062 
3063 		if (prev && prev->ar.end == r->ar.start &&
3064 		    abs(prev->nr_accesses - r->nr_accesses) <= thres &&
3065 		    damon_sz_region(prev) + damon_sz_region(r) <= sz_limit)
3066 			damon_merge_two_regions(t, prev, r);
3067 		else
3068 			prev = r;
3069 	}
3070 }
3071 
3072 /*
3073  * Merge adjacent regions having similar access frequencies
3074  *
3075  * threshold	'->nr_accesses' diff threshold for the merge
3076  * sz_limit	size upper limit of each region
3077  *
3078  * This function merges monitoring target regions which are adjacent and their
3079  * access frequencies are similar.  This is for minimizing the monitoring
3080  * overhead under the dynamically changeable access pattern.  If a merge was
3081  * unnecessarily made, later 'kdamond_split_regions()' will revert it.
3082  *
3083  * The total number of regions could be higher than the user-defined limit,
3084  * max_nr_regions for some cases.  For example, the user can update
3085  * max_nr_regions to a number that lower than the current number of regions
3086  * while DAMON is running.  For such a case, repeat merging until the limit is
3087  * met while increasing @threshold up to possible maximum level.
3088  */
3089 static void kdamond_merge_regions(struct damon_ctx *c, unsigned int threshold,
3090 				  unsigned long sz_limit)
3091 {
3092 	struct damon_target *t;
3093 	unsigned int nr_regions;
3094 	unsigned int max_thres;
3095 
3096 	max_thres = c->attrs.aggr_interval /
3097 		(c->attrs.sample_interval ?  c->attrs.sample_interval : 1);
3098 	do {
3099 		nr_regions = 0;
3100 		damon_for_each_target(t, c) {
3101 			damon_merge_regions_of(t, threshold, sz_limit);
3102 			nr_regions += damon_nr_regions(t);
3103 		}
3104 		threshold = max(1, threshold * 2);
3105 	} while (nr_regions > c->attrs.max_nr_regions &&
3106 			threshold / 2 < max_thres);
3107 }
3108 
3109 #ifdef CONFIG_DAMON_DEBUG_SANITY
3110 static void damon_verify_split_region_at(struct damon_region *r,
3111 		unsigned long sz_r)
3112 {
3113 	WARN_ONCE(sz_r == 0 || sz_r >= damon_sz_region(r),
3114 			"sz_r: %lu r: %lu-%lu (%lu)\n",
3115 			sz_r, r->ar.start, r->ar.end, damon_sz_region(r));
3116 }
3117 #else
3118 static void damon_verify_split_region_at(struct damon_region *r,
3119 		unsigned long sz_r)
3120 {
3121 }
3122 #endif
3123 
3124 /*
3125  * Split a region in two
3126  *
3127  * r		the region to be split
3128  * sz_r		size of the first sub-region that will be made
3129  */
3130 static void damon_split_region_at(struct damon_target *t,
3131 				  struct damon_region *r, unsigned long sz_r)
3132 {
3133 	struct damon_region *new;
3134 
3135 	damon_verify_split_region_at(r, sz_r);
3136 	new = damon_new_region(r->ar.start + sz_r, r->ar.end);
3137 	if (!new)
3138 		return;
3139 
3140 	r->ar.end = new->ar.start;
3141 
3142 	new->age = r->age;
3143 	new->last_nr_accesses = r->last_nr_accesses;
3144 	new->nr_accesses_bp = r->nr_accesses_bp;
3145 	new->nr_accesses = r->nr_accesses;
3146 	/* todo: do this for only installed probes */
3147 	memcpy(new->probe_hits, r->probe_hits, sizeof(r->probe_hits));
3148 
3149 	damon_insert_region(new, r, damon_next_region(r), t);
3150 }
3151 
3152 /* Split every region in the given target into 'nr_subs' regions */
3153 static void damon_split_regions_of(struct damon_ctx *ctx,
3154 				   struct damon_target *t, int nr_subs,
3155 				   unsigned long min_region_sz)
3156 {
3157 	struct damon_region *r, *next;
3158 	unsigned long sz_region, sz_sub = 0;
3159 	int i;
3160 
3161 	damon_for_each_region_safe(r, next, t) {
3162 		sz_region = damon_sz_region(r);
3163 
3164 		for (i = 0; i < nr_subs - 1 &&
3165 				sz_region > 2 * min_region_sz; i++) {
3166 			/*
3167 			 * Randomly select size of left sub-region to be at
3168 			 * least 10 percent and at most 90% of original region
3169 			 */
3170 			sz_sub = ALIGN_DOWN(damon_rand(ctx, 1, 10) *
3171 					sz_region / 10, min_region_sz);
3172 			/* Do not allow blank region */
3173 			if (sz_sub == 0 || sz_sub >= sz_region)
3174 				continue;
3175 
3176 			damon_split_region_at(t, r, sz_sub);
3177 			sz_region = sz_sub;
3178 		}
3179 	}
3180 }
3181 
3182 /*
3183  * Split every target region into randomly-sized small regions
3184  *
3185  * This function splits every target region into random-sized small regions if
3186  * current total number of the regions is equal or smaller than half of the
3187  * user-specified maximum number of regions.  This is for maximizing the
3188  * monitoring accuracy under the dynamically changeable access patterns.  If a
3189  * split was unnecessarily made, later 'kdamond_merge_regions()' will revert
3190  * it.
3191  */
3192 static void kdamond_split_regions(struct damon_ctx *ctx)
3193 {
3194 	struct damon_target *t;
3195 	unsigned int nr_regions = 0;
3196 	static unsigned int last_nr_regions;
3197 	int nr_subregions = 2;
3198 
3199 	damon_for_each_target(t, ctx)
3200 		nr_regions += damon_nr_regions(t);
3201 
3202 	if (nr_regions > ctx->attrs.max_nr_regions / 2)
3203 		return;
3204 
3205 	/* Maybe the middle of the region has different access frequency */
3206 	if (last_nr_regions == nr_regions &&
3207 			nr_regions < ctx->attrs.max_nr_regions / 3)
3208 		nr_subregions = 3;
3209 
3210 	damon_for_each_target(t, ctx)
3211 		damon_split_regions_of(ctx, t, nr_subregions,
3212 				       ctx->min_region_sz);
3213 
3214 	last_nr_regions = nr_regions;
3215 }
3216 
3217 /*
3218  * Check whether current monitoring should be stopped
3219  *
3220  * The monitoring is stopped when either the user requested to stop, or all
3221  * monitoring targets are invalid.
3222  *
3223  * Returns true if need to stop current monitoring.
3224  */
3225 static bool kdamond_need_stop(struct damon_ctx *ctx)
3226 {
3227 	struct damon_target *t;
3228 
3229 	if (kthread_should_stop())
3230 		return true;
3231 
3232 	if (!ctx->ops.target_valid)
3233 		return false;
3234 
3235 	damon_for_each_target(t, ctx) {
3236 		if (ctx->ops.target_valid(t))
3237 			return false;
3238 	}
3239 
3240 	return true;
3241 }
3242 
3243 static int damos_get_wmark_metric_value(enum damos_wmark_metric metric,
3244 					unsigned long *metric_value)
3245 {
3246 	switch (metric) {
3247 	case DAMOS_WMARK_FREE_MEM_RATE:
3248 		*metric_value = global_zone_page_state(NR_FREE_PAGES) * 1000 /
3249 		       totalram_pages();
3250 		return 0;
3251 	default:
3252 		break;
3253 	}
3254 	return -EINVAL;
3255 }
3256 
3257 /*
3258  * Returns zero if the scheme is active.  Else, returns time to wait for next
3259  * watermark check in micro-seconds.
3260  */
3261 static unsigned long damos_wmark_wait_us(struct damos *scheme)
3262 {
3263 	unsigned long metric;
3264 
3265 	if (damos_get_wmark_metric_value(scheme->wmarks.metric, &metric))
3266 		return 0;
3267 
3268 	/* higher than high watermark or lower than low watermark */
3269 	if (metric > scheme->wmarks.high || scheme->wmarks.low > metric) {
3270 		if (scheme->wmarks.activated)
3271 			pr_debug("deactivate a scheme (%d) for %s wmark\n",
3272 				 scheme->action,
3273 				 str_high_low(metric > scheme->wmarks.high));
3274 		scheme->wmarks.activated = false;
3275 		return scheme->wmarks.interval;
3276 	}
3277 
3278 	/* inactive and higher than middle watermark */
3279 	if ((scheme->wmarks.high >= metric && metric >= scheme->wmarks.mid) &&
3280 			!scheme->wmarks.activated)
3281 		return scheme->wmarks.interval;
3282 
3283 	if (!scheme->wmarks.activated)
3284 		pr_debug("activate a scheme (%d)\n", scheme->action);
3285 	scheme->wmarks.activated = true;
3286 	return 0;
3287 }
3288 
3289 static void kdamond_usleep(unsigned long usecs)
3290 {
3291 	if (usecs >= USLEEP_RANGE_UPPER_BOUND)
3292 		schedule_timeout_idle(usecs_to_jiffies(usecs));
3293 	else
3294 		usleep_range_idle(usecs, usecs + 1);
3295 }
3296 
3297 /*
3298  * kdamond_call() - handle damon_call_control objects.
3299  * @ctx:	The &struct damon_ctx of the kdamond.
3300  * @cancel:	Whether to cancel the invocation of the function.
3301  *
3302  * If there are &struct damon_call_control requests that registered via
3303  * &damon_call() on @ctx, do or cancel the invocation of the function depending
3304  * on @cancel.  @cancel is set when the kdamond is already out of the main loop
3305  * and therefore will be terminated.
3306  */
3307 static void kdamond_call(struct damon_ctx *ctx, bool cancel)
3308 {
3309 	struct damon_call_control *control, *next;
3310 	LIST_HEAD(controls);
3311 
3312 	mutex_lock(&ctx->call_controls_lock);
3313 	list_splice_tail_init(&ctx->call_controls, &controls);
3314 	mutex_unlock(&ctx->call_controls_lock);
3315 
3316 	list_for_each_entry_safe(control, next, &controls, list) {
3317 		if (!control->repeat || cancel)
3318 			list_del(&control->list);
3319 
3320 		if (cancel)
3321 			control->canceled = true;
3322 		else
3323 			control->return_code = control->fn(control->data);
3324 
3325 		if (!control->repeat)
3326 			complete(&control->completion);
3327 		else if (control->canceled && control->dealloc_on_cancel)
3328 			kfree(control);
3329 		if (!cancel && ctx->maybe_corrupted)
3330 			break;
3331 	}
3332 
3333 	mutex_lock(&ctx->call_controls_lock);
3334 	list_splice_tail(&controls, &ctx->call_controls);
3335 	mutex_unlock(&ctx->call_controls_lock);
3336 }
3337 
3338 /* Returns negative error code if it's not activated but should return */
3339 static int kdamond_wait_activation(struct damon_ctx *ctx)
3340 {
3341 	struct damos *s;
3342 	unsigned long wait_time;
3343 	unsigned long min_wait_time = 0;
3344 	bool init_wait_time = false;
3345 
3346 	while (!kdamond_need_stop(ctx)) {
3347 		damon_for_each_scheme(s, ctx) {
3348 			wait_time = damos_wmark_wait_us(s);
3349 			if (!init_wait_time || wait_time < min_wait_time) {
3350 				init_wait_time = true;
3351 				min_wait_time = wait_time;
3352 			}
3353 		}
3354 		if (!min_wait_time)
3355 			return 0;
3356 
3357 		kdamond_usleep(min_wait_time);
3358 
3359 		kdamond_call(ctx, false);
3360 		if (ctx->maybe_corrupted)
3361 			return -EINVAL;
3362 		damos_walk_cancel(ctx);
3363 	}
3364 	return -EBUSY;
3365 }
3366 
3367 static void kdamond_init_ctx(struct damon_ctx *ctx)
3368 {
3369 	unsigned long sample_interval = ctx->attrs.sample_interval ?
3370 		ctx->attrs.sample_interval : 1;
3371 	struct damos *scheme;
3372 
3373 	ctx->passed_sample_intervals = 0;
3374 	ctx->next_aggregation_sis = ctx->attrs.aggr_interval / sample_interval;
3375 	ctx->next_ops_update_sis = ctx->attrs.ops_update_interval /
3376 		sample_interval;
3377 	ctx->next_intervals_tune_sis = ctx->next_aggregation_sis *
3378 		ctx->attrs.intervals_goal.aggrs;
3379 
3380 	damon_for_each_scheme(scheme, ctx) {
3381 		damos_set_next_apply_sis(scheme, ctx);
3382 		damos_set_filters_default_reject(scheme);
3383 	}
3384 }
3385 
3386 /*
3387  * The monitoring daemon that runs as a kernel thread
3388  */
3389 static int kdamond_fn(void *data)
3390 {
3391 	struct damon_ctx *ctx = data;
3392 	unsigned int max_nr_accesses = 0;
3393 	unsigned long sz_limit = 0;
3394 
3395 	pr_debug("kdamond (%d) starts\n", current->pid);
3396 
3397 	mutex_lock(&ctx->call_controls_lock);
3398 	ctx->call_controls_obsolete = false;
3399 	mutex_unlock(&ctx->call_controls_lock);
3400 	mutex_lock(&ctx->walk_control_lock);
3401 	ctx->walk_control_obsolete = false;
3402 	mutex_unlock(&ctx->walk_control_lock);
3403 	complete(&ctx->kdamond_started);
3404 	kdamond_init_ctx(ctx);
3405 
3406 	if (ctx->ops.init)
3407 		ctx->ops.init(ctx);
3408 	ctx->regions_score_histogram = kmalloc_array(DAMOS_MAX_SCORE + 1,
3409 			sizeof(*ctx->regions_score_histogram), GFP_KERNEL);
3410 	if (!ctx->regions_score_histogram)
3411 		goto done;
3412 
3413 	sz_limit = damon_apply_min_nr_regions(ctx);
3414 
3415 	while (!kdamond_need_stop(ctx)) {
3416 		/*
3417 		 * ctx->attrs and ctx->next_{aggregation,ops_update}_sis could
3418 		 * be changed from kdamond_call().  Read the values here, and
3419 		 * use those for this iteration.  That is, damon_set_attrs()
3420 		 * updated new values are respected from next iteration.
3421 		 */
3422 		unsigned long next_aggregation_sis = ctx->next_aggregation_sis;
3423 		unsigned long next_ops_update_sis = ctx->next_ops_update_sis;
3424 		unsigned long sample_interval = ctx->attrs.sample_interval;
3425 
3426 		if (kdamond_wait_activation(ctx))
3427 			break;
3428 
3429 		if (ctx->ops.prepare_access_checks)
3430 			ctx->ops.prepare_access_checks(ctx);
3431 
3432 		kdamond_usleep(sample_interval);
3433 		ctx->passed_sample_intervals++;
3434 
3435 		if (ctx->ops.check_accesses)
3436 			max_nr_accesses = ctx->ops.check_accesses(ctx);
3437 		if (ctx->ops.apply_probes)
3438 			ctx->ops.apply_probes(ctx);
3439 
3440 		if (time_after_eq(ctx->passed_sample_intervals,
3441 					next_aggregation_sis)) {
3442 			kdamond_merge_regions(ctx,
3443 					max_nr_accesses / 10,
3444 					sz_limit);
3445 			/* online updates might be made */
3446 			sz_limit = damon_apply_min_nr_regions(ctx);
3447 		}
3448 
3449 		/*
3450 		 * do kdamond_call() and kdamond_apply_schemes() after
3451 		 * kdamond_merge_regions() if possible, to reduce overhead
3452 		 */
3453 		kdamond_call(ctx, false);
3454 		if (ctx->maybe_corrupted)
3455 			break;
3456 		while (ctx->pause) {
3457 			damos_walk_cancel(ctx);
3458 			kdamond_usleep(ctx->attrs.sample_interval);
3459 			/* allow caller unset pause via damon_call() */
3460 			kdamond_call(ctx, false);
3461 			if (kdamond_need_stop(ctx) || ctx->maybe_corrupted)
3462 				goto done;
3463 		}
3464 		if (!list_empty(&ctx->schemes))
3465 			kdamond_apply_schemes(ctx);
3466 		else
3467 			damos_walk_cancel(ctx);
3468 
3469 		sample_interval = ctx->attrs.sample_interval ?
3470 			ctx->attrs.sample_interval : 1;
3471 		if (time_after_eq(ctx->passed_sample_intervals,
3472 					next_aggregation_sis)) {
3473 			if (ctx->attrs.intervals_goal.aggrs &&
3474 					time_after_eq(
3475 						ctx->passed_sample_intervals,
3476 						ctx->next_intervals_tune_sis)) {
3477 				/*
3478 				 * ctx->next_aggregation_sis might be updated
3479 				 * from kdamond_call().  In the case,
3480 				 * damon_set_attrs() which will be called from
3481 				 * kdamond_tune_interval() may wrongly think
3482 				 * this is in the middle of the current
3483 				 * aggregation, and make aggregation
3484 				 * information reset for all regions.  Then,
3485 				 * following kdamond_reset_aggregated() call
3486 				 * will make the region information invalid,
3487 				 * particularly for ->nr_accesses_bp.
3488 				 *
3489 				 * Reset ->next_aggregation_sis to avoid that.
3490 				 * It will anyway correctly updated after this
3491 				 * if clause.
3492 				 */
3493 				ctx->next_aggregation_sis =
3494 					next_aggregation_sis;
3495 				ctx->next_intervals_tune_sis +=
3496 					ctx->attrs.aggr_samples *
3497 					ctx->attrs.intervals_goal.aggrs;
3498 				kdamond_tune_intervals(ctx);
3499 				sample_interval = ctx->attrs.sample_interval ?
3500 					ctx->attrs.sample_interval : 1;
3501 
3502 			}
3503 			ctx->next_aggregation_sis = next_aggregation_sis +
3504 				ctx->attrs.aggr_interval / sample_interval;
3505 
3506 			kdamond_reset_aggregated(ctx);
3507 			kdamond_split_regions(ctx);
3508 		}
3509 
3510 		if (time_after_eq(ctx->passed_sample_intervals,
3511 					next_ops_update_sis)) {
3512 			ctx->next_ops_update_sis = next_ops_update_sis +
3513 				ctx->attrs.ops_update_interval /
3514 				sample_interval;
3515 			if (ctx->ops.update)
3516 				ctx->ops.update(ctx);
3517 		}
3518 	}
3519 done:
3520 	damon_destroy_targets(ctx);
3521 
3522 	kfree(ctx->regions_score_histogram);
3523 	mutex_lock(&ctx->call_controls_lock);
3524 	ctx->call_controls_obsolete = true;
3525 	mutex_unlock(&ctx->call_controls_lock);
3526 	kdamond_call(ctx, true);
3527 	mutex_lock(&ctx->walk_control_lock);
3528 	ctx->walk_control_obsolete = true;
3529 	mutex_unlock(&ctx->walk_control_lock);
3530 	damos_walk_cancel(ctx);
3531 
3532 	pr_debug("kdamond (%d) finishes\n", current->pid);
3533 	mutex_lock(&ctx->kdamond_lock);
3534 	ctx->kdamond = NULL;
3535 	mutex_unlock(&ctx->kdamond_lock);
3536 
3537 	mutex_lock(&damon_lock);
3538 	nr_running_ctxs--;
3539 	if (!nr_running_ctxs && running_exclusive_ctxs)
3540 		running_exclusive_ctxs = false;
3541 	mutex_unlock(&damon_lock);
3542 
3543 	return 0;
3544 }
3545 
3546 struct damon_system_ram_range_walk_arg {
3547 	bool walked;
3548 	struct resource res;
3549 };
3550 
3551 static int damon_system_ram_walk_fn(struct resource *res, void *arg)
3552 {
3553 	struct damon_system_ram_range_walk_arg *a = arg;
3554 
3555 	if (!a->walked) {
3556 		a->walked = true;
3557 		a->res.start = res->start;
3558 	}
3559 	a->res.end = res->end;
3560 	return 0;
3561 }
3562 
3563 static unsigned long damon_res_to_core_addr(resource_size_t ra,
3564 		unsigned long addr_unit)
3565 {
3566 	/*
3567 	 * Use div_u64() for avoiding linking errors related with __udivdi3,
3568 	 * __aeabi_uldivmod, or similar problems.  This should also improve the
3569 	 * performance optimization (read div_u64() comment for the detail).
3570 	 */
3571 	if (sizeof(ra) == 8 && sizeof(addr_unit) == 4)
3572 		return div_u64(ra, addr_unit);
3573 	return ra / addr_unit;
3574 }
3575 
3576 static bool damon_find_system_rams_range(unsigned long *start,
3577 		unsigned long *end, unsigned long addr_unit)
3578 {
3579 	struct damon_system_ram_range_walk_arg arg = {};
3580 
3581 	walk_system_ram_res(0, -1, &arg, damon_system_ram_walk_fn);
3582 	if (!arg.walked)
3583 		return false;
3584 	*start = damon_res_to_core_addr(arg.res.start, addr_unit);
3585 	*end = damon_res_to_core_addr(arg.res.end + 1, addr_unit);
3586 	if (*end <= *start)
3587 		return false;
3588 	return true;
3589 }
3590 
3591 /**
3592  * damon_set_region_system_rams_default() - Set the region of the given
3593  * monitoring target as requested, or to cover all 'System RAM' resources.
3594  * @t:		The monitoring target to set the region.
3595  * @start:	The pointer to the start address of the region.
3596  * @end:	The pointer to the end address of the region.
3597  * @addr_unit:	The address unit for the damon_ctx of @t.
3598  * @min_region_sz:	Minimum region size.
3599  *
3600  * This function sets the region of @t as requested by @start and @end.  If the
3601  * values of @start and @end are zero, however, this function finds 'System
3602  * RAM' resources and sets the region to cover all the resource.  In the latter
3603  * case, this function saves the start and the end addresseses of the first and
3604  * the last resources in @start and @end, respectively.
3605  *
3606  * Return: 0 on success, negative error code otherwise.
3607  */
3608 int damon_set_region_system_rams_default(struct damon_target *t,
3609 			unsigned long *start, unsigned long *end,
3610 			unsigned long addr_unit, unsigned long min_region_sz)
3611 {
3612 	struct damon_addr_range addr_range;
3613 
3614 	if (*start > *end)
3615 		return -EINVAL;
3616 
3617 	if (!*start && !*end &&
3618 		!damon_find_system_rams_range(start, end, addr_unit))
3619 		return -EINVAL;
3620 
3621 	addr_range.start = *start;
3622 	addr_range.end = *end;
3623 	return damon_set_regions(t, &addr_range, 1, min_region_sz);
3624 }
3625 
3626 /*
3627  * damon_moving_sum() - Calculate an inferred moving sum value.
3628  * @mvsum:	Inferred sum of the last @len_window values.
3629  * @nomvsum:	Non-moving sum of the last discrete @len_window window values.
3630  * @len_window:	The number of last values to take care of.
3631  * @new_value:	New value that will be added to the pseudo moving sum.
3632  *
3633  * Moving sum (moving average * window size) is good for handling noise, but
3634  * the cost of keeping past values can be high for arbitrary window size.  This
3635  * function implements a lightweight pseudo moving sum function that doesn't
3636  * keep the past window values.
3637  *
3638  * It simply assumes there was no noise in the past, and get the no-noise
3639  * assumed past value to drop from @nomvsum and @len_window.  @nomvsum is a
3640  * non-moving sum of the last window.  For example, if @len_window is 10 and we
3641  * have 25 values, @nomvsum is the sum of the 11th to 20th values of the 25
3642  * values.  Hence, this function simply drops @nomvsum / @len_window from
3643  * given @mvsum and add @new_value.
3644  *
3645  * For example, if @len_window is 10 and @nomvsum is 50, the last 10 values for
3646  * the last window could be vary, e.g., 0, 10, 0, 10, 0, 10, 0, 0, 0, 20.  For
3647  * calculating next moving sum with a new value, we should drop 0 from 50 and
3648  * add the new value.  However, this function assumes it got value 5 for each
3649  * of the last ten times.  Based on the assumption, when the next value is
3650  * measured, it drops the assumed past value, 5 from the current sum, and add
3651  * the new value to get the updated pseduo-moving average.
3652  *
3653  * This means the value could have errors, but the errors will be disappeared
3654  * for every @len_window aligned calls.  For example, if @len_window is 10, the
3655  * pseudo moving sum with 11th value to 19th value would have an error.  But
3656  * the sum with 20th value will not have the error.
3657  *
3658  * Return: Pseudo-moving average after getting the @new_value.
3659  */
3660 static unsigned int damon_moving_sum(unsigned int mvsum, unsigned int nomvsum,
3661 		unsigned int len_window, unsigned int new_value)
3662 {
3663 	return mvsum - nomvsum / len_window + new_value;
3664 }
3665 
3666 /**
3667  * damon_update_region_access_rate() - Update the access rate of a region.
3668  * @r:		The DAMON region to update for its access check result.
3669  * @accessed:	Whether the region has accessed during last sampling interval.
3670  * @attrs:	The damon_attrs of the DAMON context.
3671  *
3672  * Update the access rate of a region with the region's last sampling interval
3673  * access check result.
3674  *
3675  * Usually this will be called by &damon_operations->check_accesses callback.
3676  */
3677 void damon_update_region_access_rate(struct damon_region *r, bool accessed,
3678 		struct damon_attrs *attrs)
3679 {
3680 	unsigned int len_window = 1;
3681 
3682 	/*
3683 	 * sample_interval can be zero, but cannot be larger than
3684 	 * aggr_interval, owing to validation of damon_set_attrs().
3685 	 */
3686 	if (attrs->sample_interval)
3687 		len_window = damon_max_nr_accesses(attrs);
3688 	r->nr_accesses_bp = damon_moving_sum(r->nr_accesses_bp,
3689 			r->last_nr_accesses * 10000, len_window,
3690 			accessed ? 10000 : 0);
3691 
3692 	if (accessed)
3693 		r->nr_accesses++;
3694 }
3695 
3696 /**
3697  * damon_initialized() - Return if DAMON is ready to be used.
3698  *
3699  * Return: true if DAMON is ready to be used, false otherwise.
3700  */
3701 bool damon_initialized(void)
3702 {
3703 	return damon_region_cache != NULL;
3704 }
3705 
3706 static int __init damon_init(void)
3707 {
3708 	damon_region_cache = KMEM_CACHE(damon_region, 0);
3709 	if (unlikely(!damon_region_cache)) {
3710 		pr_err("creating damon_region_cache fails\n");
3711 		return -ENOMEM;
3712 	}
3713 
3714 	return 0;
3715 }
3716 
3717 subsys_initcall(damon_init);
3718 
3719 #include "tests/core-kunit.h"
3720