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