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