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