xref: /linux/mm/damon/core.c (revision d8a142058f39a32ae6c7cd5a786c656133c717fb)
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/mm.h>
14 #include <linux/psi.h>
15 #include <linux/slab.h>
16 #include <linux/string.h>
17 
18 #define CREATE_TRACE_POINTS
19 #include <trace/events/damon.h>
20 
21 #ifdef CONFIG_DAMON_KUNIT_TEST
22 #undef DAMON_MIN_REGION
23 #define DAMON_MIN_REGION 1
24 #endif
25 
26 static DEFINE_MUTEX(damon_lock);
27 static int nr_running_ctxs;
28 static bool running_exclusive_ctxs;
29 
30 static DEFINE_MUTEX(damon_ops_lock);
31 static struct damon_operations damon_registered_ops[NR_DAMON_OPS];
32 
33 static struct kmem_cache *damon_region_cache __ro_after_init;
34 
35 /* Should be called under damon_ops_lock with id smaller than NR_DAMON_OPS */
36 static bool __damon_is_registered_ops(enum damon_ops_id id)
37 {
38 	struct damon_operations empty_ops = {};
39 
40 	if (!memcmp(&empty_ops, &damon_registered_ops[id], sizeof(empty_ops)))
41 		return false;
42 	return true;
43 }
44 
45 /**
46  * damon_is_registered_ops() - Check if a given damon_operations is registered.
47  * @id:	Id of the damon_operations to check if registered.
48  *
49  * Return: true if the ops is set, false otherwise.
50  */
51 bool damon_is_registered_ops(enum damon_ops_id id)
52 {
53 	bool registered;
54 
55 	if (id >= NR_DAMON_OPS)
56 		return false;
57 	mutex_lock(&damon_ops_lock);
58 	registered = __damon_is_registered_ops(id);
59 	mutex_unlock(&damon_ops_lock);
60 	return registered;
61 }
62 
63 /**
64  * damon_register_ops() - Register a monitoring operations set to DAMON.
65  * @ops:	monitoring operations set to register.
66  *
67  * This function registers a monitoring operations set of valid &struct
68  * damon_operations->id so that others can find and use them later.
69  *
70  * Return: 0 on success, negative error code otherwise.
71  */
72 int damon_register_ops(struct damon_operations *ops)
73 {
74 	int err = 0;
75 
76 	if (ops->id >= NR_DAMON_OPS)
77 		return -EINVAL;
78 	mutex_lock(&damon_ops_lock);
79 	/* Fail for already registered ops */
80 	if (__damon_is_registered_ops(ops->id)) {
81 		err = -EINVAL;
82 		goto out;
83 	}
84 	damon_registered_ops[ops->id] = *ops;
85 out:
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 /*
117  * Construct a damon_region struct
118  *
119  * Returns the pointer to the new struct if success, or NULL otherwise
120  */
121 struct damon_region *damon_new_region(unsigned long start, unsigned long end)
122 {
123 	struct damon_region *region;
124 
125 	region = kmem_cache_alloc(damon_region_cache, GFP_KERNEL);
126 	if (!region)
127 		return NULL;
128 
129 	region->ar.start = start;
130 	region->ar.end = end;
131 	region->nr_accesses = 0;
132 	region->nr_accesses_bp = 0;
133 	INIT_LIST_HEAD(&region->list);
134 
135 	region->age = 0;
136 	region->last_nr_accesses = 0;
137 
138 	return region;
139 }
140 
141 void damon_add_region(struct damon_region *r, struct damon_target *t)
142 {
143 	list_add_tail(&r->list, &t->regions_list);
144 	t->nr_regions++;
145 }
146 
147 static void damon_del_region(struct damon_region *r, struct damon_target *t)
148 {
149 	list_del(&r->list);
150 	t->nr_regions--;
151 }
152 
153 static void damon_free_region(struct damon_region *r)
154 {
155 	kmem_cache_free(damon_region_cache, r);
156 }
157 
158 void damon_destroy_region(struct damon_region *r, struct damon_target *t)
159 {
160 	damon_del_region(r, t);
161 	damon_free_region(r);
162 }
163 
164 /*
165  * Check whether a region is intersecting an address range
166  *
167  * Returns true if it is.
168  */
169 static bool damon_intersect(struct damon_region *r,
170 		struct damon_addr_range *re)
171 {
172 	return !(r->ar.end <= re->start || re->end <= r->ar.start);
173 }
174 
175 /*
176  * Fill holes in regions with new regions.
177  */
178 static int damon_fill_regions_holes(struct damon_region *first,
179 		struct damon_region *last, struct damon_target *t)
180 {
181 	struct damon_region *r = first;
182 
183 	damon_for_each_region_from(r, t) {
184 		struct damon_region *next, *newr;
185 
186 		if (r == last)
187 			break;
188 		next = damon_next_region(r);
189 		if (r->ar.end != next->ar.start) {
190 			newr = damon_new_region(r->ar.end, next->ar.start);
191 			if (!newr)
192 				return -ENOMEM;
193 			damon_insert_region(newr, r, next, t);
194 		}
195 	}
196 	return 0;
197 }
198 
199 /*
200  * damon_set_regions() - Set regions of a target for given address ranges.
201  * @t:		the given target.
202  * @ranges:	array of new monitoring target ranges.
203  * @nr_ranges:	length of @ranges.
204  *
205  * This function adds new regions to, or modify existing regions of a
206  * monitoring target to fit in specific ranges.
207  *
208  * Return: 0 if success, or negative error code otherwise.
209  */
210 int damon_set_regions(struct damon_target *t, struct damon_addr_range *ranges,
211 		unsigned int nr_ranges)
212 {
213 	struct damon_region *r, *next;
214 	unsigned int i;
215 	int err;
216 
217 	/* Remove regions which are not in the new ranges */
218 	damon_for_each_region_safe(r, next, t) {
219 		for (i = 0; i < nr_ranges; i++) {
220 			if (damon_intersect(r, &ranges[i]))
221 				break;
222 		}
223 		if (i == nr_ranges)
224 			damon_destroy_region(r, t);
225 	}
226 
227 	r = damon_first_region(t);
228 	/* Add new regions or resize existing regions to fit in the ranges */
229 	for (i = 0; i < nr_ranges; i++) {
230 		struct damon_region *first = NULL, *last, *newr;
231 		struct damon_addr_range *range;
232 
233 		range = &ranges[i];
234 		/* Get the first/last regions intersecting with the range */
235 		damon_for_each_region_from(r, t) {
236 			if (damon_intersect(r, range)) {
237 				if (!first)
238 					first = r;
239 				last = r;
240 			}
241 			if (r->ar.start >= range->end)
242 				break;
243 		}
244 		if (!first) {
245 			/* no region intersects with this range */
246 			newr = damon_new_region(
247 					ALIGN_DOWN(range->start,
248 						DAMON_MIN_REGION),
249 					ALIGN(range->end, DAMON_MIN_REGION));
250 			if (!newr)
251 				return -ENOMEM;
252 			damon_insert_region(newr, damon_prev_region(r), r, t);
253 		} else {
254 			/* resize intersecting regions to fit in this range */
255 			first->ar.start = ALIGN_DOWN(range->start,
256 					DAMON_MIN_REGION);
257 			last->ar.end = ALIGN(range->end, DAMON_MIN_REGION);
258 
259 			/* fill possible holes in the range */
260 			err = damon_fill_regions_holes(first, last, t);
261 			if (err)
262 				return err;
263 		}
264 	}
265 	return 0;
266 }
267 
268 struct damos_filter *damos_new_filter(enum damos_filter_type type,
269 		bool matching)
270 {
271 	struct damos_filter *filter;
272 
273 	filter = kmalloc(sizeof(*filter), GFP_KERNEL);
274 	if (!filter)
275 		return NULL;
276 	filter->type = type;
277 	filter->matching = matching;
278 	INIT_LIST_HEAD(&filter->list);
279 	return filter;
280 }
281 
282 void damos_add_filter(struct damos *s, struct damos_filter *f)
283 {
284 	list_add_tail(&f->list, &s->filters);
285 }
286 
287 static void damos_del_filter(struct damos_filter *f)
288 {
289 	list_del(&f->list);
290 }
291 
292 static void damos_free_filter(struct damos_filter *f)
293 {
294 	kfree(f);
295 }
296 
297 void damos_destroy_filter(struct damos_filter *f)
298 {
299 	damos_del_filter(f);
300 	damos_free_filter(f);
301 }
302 
303 struct damos_quota_goal *damos_new_quota_goal(
304 		enum damos_quota_goal_metric metric,
305 		unsigned long target_value)
306 {
307 	struct damos_quota_goal *goal;
308 
309 	goal = kmalloc(sizeof(*goal), GFP_KERNEL);
310 	if (!goal)
311 		return NULL;
312 	goal->metric = metric;
313 	goal->target_value = target_value;
314 	INIT_LIST_HEAD(&goal->list);
315 	return goal;
316 }
317 
318 void damos_add_quota_goal(struct damos_quota *q, struct damos_quota_goal *g)
319 {
320 	list_add_tail(&g->list, &q->goals);
321 }
322 
323 static void damos_del_quota_goal(struct damos_quota_goal *g)
324 {
325 	list_del(&g->list);
326 }
327 
328 static void damos_free_quota_goal(struct damos_quota_goal *g)
329 {
330 	kfree(g);
331 }
332 
333 void damos_destroy_quota_goal(struct damos_quota_goal *g)
334 {
335 	damos_del_quota_goal(g);
336 	damos_free_quota_goal(g);
337 }
338 
339 /* initialize fields of @quota that normally API users wouldn't set */
340 static struct damos_quota *damos_quota_init(struct damos_quota *quota)
341 {
342 	quota->esz = 0;
343 	quota->total_charged_sz = 0;
344 	quota->total_charged_ns = 0;
345 	quota->charged_sz = 0;
346 	quota->charged_from = 0;
347 	quota->charge_target_from = NULL;
348 	quota->charge_addr_from = 0;
349 	quota->esz_bp = 0;
350 	return quota;
351 }
352 
353 struct damos *damon_new_scheme(struct damos_access_pattern *pattern,
354 			enum damos_action action,
355 			unsigned long apply_interval_us,
356 			struct damos_quota *quota,
357 			struct damos_watermarks *wmarks,
358 			int target_nid)
359 {
360 	struct damos *scheme;
361 
362 	scheme = kmalloc(sizeof(*scheme), GFP_KERNEL);
363 	if (!scheme)
364 		return NULL;
365 	scheme->pattern = *pattern;
366 	scheme->action = action;
367 	scheme->apply_interval_us = apply_interval_us;
368 	/*
369 	 * next_apply_sis will be set when kdamond starts.  While kdamond is
370 	 * running, it will also updated when it is added to the DAMON context,
371 	 * or damon_attrs are updated.
372 	 */
373 	scheme->next_apply_sis = 0;
374 	INIT_LIST_HEAD(&scheme->filters);
375 	scheme->stat = (struct damos_stat){};
376 	INIT_LIST_HEAD(&scheme->list);
377 
378 	scheme->quota = *(damos_quota_init(quota));
379 	/* quota.goals should be separately set by caller */
380 	INIT_LIST_HEAD(&scheme->quota.goals);
381 
382 	scheme->wmarks = *wmarks;
383 	scheme->wmarks.activated = true;
384 
385 	scheme->target_nid = target_nid;
386 
387 	return scheme;
388 }
389 
390 static void damos_set_next_apply_sis(struct damos *s, struct damon_ctx *ctx)
391 {
392 	unsigned long sample_interval = ctx->attrs.sample_interval ?
393 		ctx->attrs.sample_interval : 1;
394 	unsigned long apply_interval = s->apply_interval_us ?
395 		s->apply_interval_us : ctx->attrs.aggr_interval;
396 
397 	s->next_apply_sis = ctx->passed_sample_intervals +
398 		apply_interval / sample_interval;
399 }
400 
401 void damon_add_scheme(struct damon_ctx *ctx, struct damos *s)
402 {
403 	list_add_tail(&s->list, &ctx->schemes);
404 	damos_set_next_apply_sis(s, ctx);
405 }
406 
407 static void damon_del_scheme(struct damos *s)
408 {
409 	list_del(&s->list);
410 }
411 
412 static void damon_free_scheme(struct damos *s)
413 {
414 	kfree(s);
415 }
416 
417 void damon_destroy_scheme(struct damos *s)
418 {
419 	struct damos_quota_goal *g, *g_next;
420 	struct damos_filter *f, *next;
421 
422 	damos_for_each_quota_goal_safe(g, g_next, &s->quota)
423 		damos_destroy_quota_goal(g);
424 
425 	damos_for_each_filter_safe(f, next, s)
426 		damos_destroy_filter(f);
427 	damon_del_scheme(s);
428 	damon_free_scheme(s);
429 }
430 
431 /*
432  * Construct a damon_target struct
433  *
434  * Returns the pointer to the new struct if success, or NULL otherwise
435  */
436 struct damon_target *damon_new_target(void)
437 {
438 	struct damon_target *t;
439 
440 	t = kmalloc(sizeof(*t), GFP_KERNEL);
441 	if (!t)
442 		return NULL;
443 
444 	t->pid = NULL;
445 	t->nr_regions = 0;
446 	INIT_LIST_HEAD(&t->regions_list);
447 	INIT_LIST_HEAD(&t->list);
448 
449 	return t;
450 }
451 
452 void damon_add_target(struct damon_ctx *ctx, struct damon_target *t)
453 {
454 	list_add_tail(&t->list, &ctx->adaptive_targets);
455 }
456 
457 bool damon_targets_empty(struct damon_ctx *ctx)
458 {
459 	return list_empty(&ctx->adaptive_targets);
460 }
461 
462 static void damon_del_target(struct damon_target *t)
463 {
464 	list_del(&t->list);
465 }
466 
467 void damon_free_target(struct damon_target *t)
468 {
469 	struct damon_region *r, *next;
470 
471 	damon_for_each_region_safe(r, next, t)
472 		damon_free_region(r);
473 	kfree(t);
474 }
475 
476 void damon_destroy_target(struct damon_target *t)
477 {
478 	damon_del_target(t);
479 	damon_free_target(t);
480 }
481 
482 unsigned int damon_nr_regions(struct damon_target *t)
483 {
484 	return t->nr_regions;
485 }
486 
487 struct damon_ctx *damon_new_ctx(void)
488 {
489 	struct damon_ctx *ctx;
490 
491 	ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
492 	if (!ctx)
493 		return NULL;
494 
495 	init_completion(&ctx->kdamond_started);
496 
497 	ctx->attrs.sample_interval = 5 * 1000;
498 	ctx->attrs.aggr_interval = 100 * 1000;
499 	ctx->attrs.ops_update_interval = 60 * 1000 * 1000;
500 
501 	ctx->passed_sample_intervals = 0;
502 	/* These will be set from kdamond_init_intervals_sis() */
503 	ctx->next_aggregation_sis = 0;
504 	ctx->next_ops_update_sis = 0;
505 
506 	mutex_init(&ctx->kdamond_lock);
507 	mutex_init(&ctx->call_control_lock);
508 	mutex_init(&ctx->walk_control_lock);
509 
510 	ctx->attrs.min_nr_regions = 10;
511 	ctx->attrs.max_nr_regions = 1000;
512 
513 	INIT_LIST_HEAD(&ctx->adaptive_targets);
514 	INIT_LIST_HEAD(&ctx->schemes);
515 
516 	return ctx;
517 }
518 
519 static void damon_destroy_targets(struct damon_ctx *ctx)
520 {
521 	struct damon_target *t, *next_t;
522 
523 	if (ctx->ops.cleanup) {
524 		ctx->ops.cleanup(ctx);
525 		return;
526 	}
527 
528 	damon_for_each_target_safe(t, next_t, ctx)
529 		damon_destroy_target(t);
530 }
531 
532 void damon_destroy_ctx(struct damon_ctx *ctx)
533 {
534 	struct damos *s, *next_s;
535 
536 	damon_destroy_targets(ctx);
537 
538 	damon_for_each_scheme_safe(s, next_s, ctx)
539 		damon_destroy_scheme(s);
540 
541 	kfree(ctx);
542 }
543 
544 static unsigned int damon_age_for_new_attrs(unsigned int age,
545 		struct damon_attrs *old_attrs, struct damon_attrs *new_attrs)
546 {
547 	return age * old_attrs->aggr_interval / new_attrs->aggr_interval;
548 }
549 
550 /* convert access ratio in bp (per 10,000) to nr_accesses */
551 static unsigned int damon_accesses_bp_to_nr_accesses(
552 		unsigned int accesses_bp, struct damon_attrs *attrs)
553 {
554 	return accesses_bp * damon_max_nr_accesses(attrs) / 10000;
555 }
556 
557 /*
558  * Convert nr_accesses to access ratio in bp (per 10,000).
559  *
560  * Callers should ensure attrs.aggr_interval is not zero, like
561  * damon_update_monitoring_results() does .  Otherwise, divide-by-zero would
562  * happen.
563  */
564 static unsigned int damon_nr_accesses_to_accesses_bp(
565 		unsigned int nr_accesses, struct damon_attrs *attrs)
566 {
567 	return nr_accesses * 10000 / damon_max_nr_accesses(attrs);
568 }
569 
570 static unsigned int damon_nr_accesses_for_new_attrs(unsigned int nr_accesses,
571 		struct damon_attrs *old_attrs, struct damon_attrs *new_attrs)
572 {
573 	return damon_accesses_bp_to_nr_accesses(
574 			damon_nr_accesses_to_accesses_bp(
575 				nr_accesses, old_attrs),
576 			new_attrs);
577 }
578 
579 static void damon_update_monitoring_result(struct damon_region *r,
580 		struct damon_attrs *old_attrs, struct damon_attrs *new_attrs)
581 {
582 	r->nr_accesses = damon_nr_accesses_for_new_attrs(r->nr_accesses,
583 			old_attrs, new_attrs);
584 	r->nr_accesses_bp = r->nr_accesses * 10000;
585 	r->age = damon_age_for_new_attrs(r->age, old_attrs, new_attrs);
586 }
587 
588 /*
589  * region->nr_accesses is the number of sampling intervals in the last
590  * aggregation interval that access to the region has found, and region->age is
591  * the number of aggregation intervals that its access pattern has maintained.
592  * For the reason, the real meaning of the two fields depend on current
593  * sampling interval and aggregation interval.  This function updates
594  * ->nr_accesses and ->age of given damon_ctx's regions for new damon_attrs.
595  */
596 static void damon_update_monitoring_results(struct damon_ctx *ctx,
597 		struct damon_attrs *new_attrs)
598 {
599 	struct damon_attrs *old_attrs = &ctx->attrs;
600 	struct damon_target *t;
601 	struct damon_region *r;
602 
603 	/* if any interval is zero, simply forgive conversion */
604 	if (!old_attrs->sample_interval || !old_attrs->aggr_interval ||
605 			!new_attrs->sample_interval ||
606 			!new_attrs->aggr_interval)
607 		return;
608 
609 	damon_for_each_target(t, ctx)
610 		damon_for_each_region(r, t)
611 			damon_update_monitoring_result(
612 					r, old_attrs, new_attrs);
613 }
614 
615 /**
616  * damon_set_attrs() - Set attributes for the monitoring.
617  * @ctx:		monitoring context
618  * @attrs:		monitoring attributes
619  *
620  * This function should be called while the kdamond is not running, or an
621  * access check results aggregation is not ongoing (e.g., from
622  * &struct damon_callback->after_aggregation or
623  * &struct damon_callback->after_wmarks_check callbacks).
624  *
625  * Every time interval is in micro-seconds.
626  *
627  * Return: 0 on success, negative error code otherwise.
628  */
629 int damon_set_attrs(struct damon_ctx *ctx, struct damon_attrs *attrs)
630 {
631 	unsigned long sample_interval = attrs->sample_interval ?
632 		attrs->sample_interval : 1;
633 	struct damos *s;
634 
635 	if (attrs->min_nr_regions < 3)
636 		return -EINVAL;
637 	if (attrs->min_nr_regions > attrs->max_nr_regions)
638 		return -EINVAL;
639 	if (attrs->sample_interval > attrs->aggr_interval)
640 		return -EINVAL;
641 
642 	ctx->next_aggregation_sis = ctx->passed_sample_intervals +
643 		attrs->aggr_interval / sample_interval;
644 	ctx->next_ops_update_sis = ctx->passed_sample_intervals +
645 		attrs->ops_update_interval / sample_interval;
646 
647 	damon_update_monitoring_results(ctx, attrs);
648 	ctx->attrs = *attrs;
649 
650 	damon_for_each_scheme(s, ctx)
651 		damos_set_next_apply_sis(s, ctx);
652 
653 	return 0;
654 }
655 
656 /**
657  * damon_set_schemes() - Set data access monitoring based operation schemes.
658  * @ctx:	monitoring context
659  * @schemes:	array of the schemes
660  * @nr_schemes:	number of entries in @schemes
661  *
662  * This function should not be called while the kdamond of the context is
663  * running.
664  */
665 void damon_set_schemes(struct damon_ctx *ctx, struct damos **schemes,
666 			ssize_t nr_schemes)
667 {
668 	struct damos *s, *next;
669 	ssize_t i;
670 
671 	damon_for_each_scheme_safe(s, next, ctx)
672 		damon_destroy_scheme(s);
673 	for (i = 0; i < nr_schemes; i++)
674 		damon_add_scheme(ctx, schemes[i]);
675 }
676 
677 static struct damos_quota_goal *damos_nth_quota_goal(
678 		int n, struct damos_quota *q)
679 {
680 	struct damos_quota_goal *goal;
681 	int i = 0;
682 
683 	damos_for_each_quota_goal(goal, q) {
684 		if (i++ == n)
685 			return goal;
686 	}
687 	return NULL;
688 }
689 
690 static void damos_commit_quota_goal(
691 		struct damos_quota_goal *dst, struct damos_quota_goal *src)
692 {
693 	dst->metric = src->metric;
694 	dst->target_value = src->target_value;
695 	if (dst->metric == DAMOS_QUOTA_USER_INPUT)
696 		dst->current_value = src->current_value;
697 	/* keep last_psi_total as is, since it will be updated in next cycle */
698 }
699 
700 /**
701  * damos_commit_quota_goals() - Commit DAMOS quota goals to another quota.
702  * @dst:	The commit destination DAMOS quota.
703  * @src:	The commit source DAMOS quota.
704  *
705  * Copies user-specified parameters for quota goals from @src to @dst.  Users
706  * should use this function for quota goals-level parameters update of running
707  * DAMON contexts, instead of manual in-place updates.
708  *
709  * This function should be called from parameters-update safe context, like
710  * DAMON callbacks.
711  */
712 int damos_commit_quota_goals(struct damos_quota *dst, struct damos_quota *src)
713 {
714 	struct damos_quota_goal *dst_goal, *next, *src_goal, *new_goal;
715 	int i = 0, j = 0;
716 
717 	damos_for_each_quota_goal_safe(dst_goal, next, dst) {
718 		src_goal = damos_nth_quota_goal(i++, src);
719 		if (src_goal)
720 			damos_commit_quota_goal(dst_goal, src_goal);
721 		else
722 			damos_destroy_quota_goal(dst_goal);
723 	}
724 	damos_for_each_quota_goal_safe(src_goal, next, src) {
725 		if (j++ < i)
726 			continue;
727 		new_goal = damos_new_quota_goal(
728 				src_goal->metric, src_goal->target_value);
729 		if (!new_goal)
730 			return -ENOMEM;
731 		damos_add_quota_goal(dst, new_goal);
732 	}
733 	return 0;
734 }
735 
736 static int damos_commit_quota(struct damos_quota *dst, struct damos_quota *src)
737 {
738 	int err;
739 
740 	dst->reset_interval = src->reset_interval;
741 	dst->ms = src->ms;
742 	dst->sz = src->sz;
743 	err = damos_commit_quota_goals(dst, src);
744 	if (err)
745 		return err;
746 	dst->weight_sz = src->weight_sz;
747 	dst->weight_nr_accesses = src->weight_nr_accesses;
748 	dst->weight_age = src->weight_age;
749 	return 0;
750 }
751 
752 static struct damos_filter *damos_nth_filter(int n, struct damos *s)
753 {
754 	struct damos_filter *filter;
755 	int i = 0;
756 
757 	damos_for_each_filter(filter, s) {
758 		if (i++ == n)
759 			return filter;
760 	}
761 	return NULL;
762 }
763 
764 static void damos_commit_filter_arg(
765 		struct damos_filter *dst, struct damos_filter *src)
766 {
767 	switch (dst->type) {
768 	case DAMOS_FILTER_TYPE_MEMCG:
769 		dst->memcg_id = src->memcg_id;
770 		break;
771 	case DAMOS_FILTER_TYPE_ADDR:
772 		dst->addr_range = src->addr_range;
773 		break;
774 	case DAMOS_FILTER_TYPE_TARGET:
775 		dst->target_idx = src->target_idx;
776 		break;
777 	default:
778 		break;
779 	}
780 }
781 
782 static void damos_commit_filter(
783 		struct damos_filter *dst, struct damos_filter *src)
784 {
785 	dst->type = src->type;
786 	dst->matching = src->matching;
787 	damos_commit_filter_arg(dst, src);
788 }
789 
790 static int damos_commit_filters(struct damos *dst, struct damos *src)
791 {
792 	struct damos_filter *dst_filter, *next, *src_filter, *new_filter;
793 	int i = 0, j = 0;
794 
795 	damos_for_each_filter_safe(dst_filter, next, dst) {
796 		src_filter = damos_nth_filter(i++, src);
797 		if (src_filter)
798 			damos_commit_filter(dst_filter, src_filter);
799 		else
800 			damos_destroy_filter(dst_filter);
801 	}
802 
803 	damos_for_each_filter_safe(src_filter, next, src) {
804 		if (j++ < i)
805 			continue;
806 
807 		new_filter = damos_new_filter(
808 				src_filter->type, src_filter->matching);
809 		if (!new_filter)
810 			return -ENOMEM;
811 		damos_commit_filter_arg(new_filter, src_filter);
812 		damos_add_filter(dst, new_filter);
813 	}
814 	return 0;
815 }
816 
817 static struct damos *damon_nth_scheme(int n, struct damon_ctx *ctx)
818 {
819 	struct damos *s;
820 	int i = 0;
821 
822 	damon_for_each_scheme(s, ctx) {
823 		if (i++ == n)
824 			return s;
825 	}
826 	return NULL;
827 }
828 
829 static int damos_commit(struct damos *dst, struct damos *src)
830 {
831 	int err;
832 
833 	dst->pattern = src->pattern;
834 	dst->action = src->action;
835 	dst->apply_interval_us = src->apply_interval_us;
836 
837 	err = damos_commit_quota(&dst->quota, &src->quota);
838 	if (err)
839 		return err;
840 
841 	dst->wmarks = src->wmarks;
842 
843 	err = damos_commit_filters(dst, src);
844 	return err;
845 }
846 
847 static int damon_commit_schemes(struct damon_ctx *dst, struct damon_ctx *src)
848 {
849 	struct damos *dst_scheme, *next, *src_scheme, *new_scheme;
850 	int i = 0, j = 0, err;
851 
852 	damon_for_each_scheme_safe(dst_scheme, next, dst) {
853 		src_scheme = damon_nth_scheme(i++, src);
854 		if (src_scheme) {
855 			err = damos_commit(dst_scheme, src_scheme);
856 			if (err)
857 				return err;
858 		} else {
859 			damon_destroy_scheme(dst_scheme);
860 		}
861 	}
862 
863 	damon_for_each_scheme_safe(src_scheme, next, src) {
864 		if (j++ < i)
865 			continue;
866 		new_scheme = damon_new_scheme(&src_scheme->pattern,
867 				src_scheme->action,
868 				src_scheme->apply_interval_us,
869 				&src_scheme->quota, &src_scheme->wmarks,
870 				NUMA_NO_NODE);
871 		if (!new_scheme)
872 			return -ENOMEM;
873 		err = damos_commit(new_scheme, src_scheme);
874 		if (err) {
875 			damon_destroy_scheme(new_scheme);
876 			return err;
877 		}
878 		damon_add_scheme(dst, new_scheme);
879 	}
880 	return 0;
881 }
882 
883 static struct damon_target *damon_nth_target(int n, struct damon_ctx *ctx)
884 {
885 	struct damon_target *t;
886 	int i = 0;
887 
888 	damon_for_each_target(t, ctx) {
889 		if (i++ == n)
890 			return t;
891 	}
892 	return NULL;
893 }
894 
895 /*
896  * The caller should ensure the regions of @src are
897  * 1. valid (end >= src) and
898  * 2. sorted by starting address.
899  *
900  * If @src has no region, @dst keeps current regions.
901  */
902 static int damon_commit_target_regions(
903 		struct damon_target *dst, struct damon_target *src)
904 {
905 	struct damon_region *src_region;
906 	struct damon_addr_range *ranges;
907 	int i = 0, err;
908 
909 	damon_for_each_region(src_region, src)
910 		i++;
911 	if (!i)
912 		return 0;
913 
914 	ranges = kmalloc_array(i, sizeof(*ranges), GFP_KERNEL | __GFP_NOWARN);
915 	if (!ranges)
916 		return -ENOMEM;
917 	i = 0;
918 	damon_for_each_region(src_region, src)
919 		ranges[i++] = src_region->ar;
920 	err = damon_set_regions(dst, ranges, i);
921 	kfree(ranges);
922 	return err;
923 }
924 
925 static int damon_commit_target(
926 		struct damon_target *dst, bool dst_has_pid,
927 		struct damon_target *src, bool src_has_pid)
928 {
929 	int err;
930 
931 	err = damon_commit_target_regions(dst, src);
932 	if (err)
933 		return err;
934 	if (dst_has_pid)
935 		put_pid(dst->pid);
936 	if (src_has_pid)
937 		get_pid(src->pid);
938 	dst->pid = src->pid;
939 	return 0;
940 }
941 
942 static int damon_commit_targets(
943 		struct damon_ctx *dst, struct damon_ctx *src)
944 {
945 	struct damon_target *dst_target, *next, *src_target, *new_target;
946 	int i = 0, j = 0, err;
947 
948 	damon_for_each_target_safe(dst_target, next, dst) {
949 		src_target = damon_nth_target(i++, src);
950 		if (src_target) {
951 			err = damon_commit_target(
952 					dst_target, damon_target_has_pid(dst),
953 					src_target, damon_target_has_pid(src));
954 			if (err)
955 				return err;
956 		} else {
957 			if (damon_target_has_pid(dst))
958 				put_pid(dst_target->pid);
959 			damon_destroy_target(dst_target);
960 		}
961 	}
962 
963 	damon_for_each_target_safe(src_target, next, src) {
964 		if (j++ < i)
965 			continue;
966 		new_target = damon_new_target();
967 		if (!new_target)
968 			return -ENOMEM;
969 		err = damon_commit_target(new_target, false,
970 				src_target, damon_target_has_pid(src));
971 		if (err) {
972 			damon_destroy_target(new_target);
973 			return err;
974 		}
975 		damon_add_target(dst, new_target);
976 	}
977 	return 0;
978 }
979 
980 /**
981  * damon_commit_ctx() - Commit parameters of a DAMON context to another.
982  * @dst:	The commit destination DAMON context.
983  * @src:	The commit source DAMON context.
984  *
985  * This function copies user-specified parameters from @src to @dst and update
986  * the internal status and results accordingly.  Users should use this function
987  * for context-level parameters update of running context, instead of manual
988  * in-place updates.
989  *
990  * This function should be called from parameters-update safe context, like
991  * DAMON callbacks.
992  */
993 int damon_commit_ctx(struct damon_ctx *dst, struct damon_ctx *src)
994 {
995 	int err;
996 
997 	err = damon_commit_schemes(dst, src);
998 	if (err)
999 		return err;
1000 	err = damon_commit_targets(dst, src);
1001 	if (err)
1002 		return err;
1003 	/*
1004 	 * schemes and targets should be updated first, since
1005 	 * 1. damon_set_attrs() updates monitoring results of targets and
1006 	 * next_apply_sis of schemes, and
1007 	 * 2. ops update should be done after pid handling is done (target
1008 	 *    committing require putting pids).
1009 	 */
1010 	err = damon_set_attrs(dst, &src->attrs);
1011 	if (err)
1012 		return err;
1013 	dst->ops = src->ops;
1014 
1015 	return 0;
1016 }
1017 
1018 /**
1019  * damon_nr_running_ctxs() - Return number of currently running contexts.
1020  */
1021 int damon_nr_running_ctxs(void)
1022 {
1023 	int nr_ctxs;
1024 
1025 	mutex_lock(&damon_lock);
1026 	nr_ctxs = nr_running_ctxs;
1027 	mutex_unlock(&damon_lock);
1028 
1029 	return nr_ctxs;
1030 }
1031 
1032 /* Returns the size upper limit for each monitoring region */
1033 static unsigned long damon_region_sz_limit(struct damon_ctx *ctx)
1034 {
1035 	struct damon_target *t;
1036 	struct damon_region *r;
1037 	unsigned long sz = 0;
1038 
1039 	damon_for_each_target(t, ctx) {
1040 		damon_for_each_region(r, t)
1041 			sz += damon_sz_region(r);
1042 	}
1043 
1044 	if (ctx->attrs.min_nr_regions)
1045 		sz /= ctx->attrs.min_nr_regions;
1046 	if (sz < DAMON_MIN_REGION)
1047 		sz = DAMON_MIN_REGION;
1048 
1049 	return sz;
1050 }
1051 
1052 static int kdamond_fn(void *data);
1053 
1054 /*
1055  * __damon_start() - Starts monitoring with given context.
1056  * @ctx:	monitoring context
1057  *
1058  * This function should be called while damon_lock is hold.
1059  *
1060  * Return: 0 on success, negative error code otherwise.
1061  */
1062 static int __damon_start(struct damon_ctx *ctx)
1063 {
1064 	int err = -EBUSY;
1065 
1066 	mutex_lock(&ctx->kdamond_lock);
1067 	if (!ctx->kdamond) {
1068 		err = 0;
1069 		reinit_completion(&ctx->kdamond_started);
1070 		ctx->kdamond = kthread_run(kdamond_fn, ctx, "kdamond.%d",
1071 				nr_running_ctxs);
1072 		if (IS_ERR(ctx->kdamond)) {
1073 			err = PTR_ERR(ctx->kdamond);
1074 			ctx->kdamond = NULL;
1075 		} else {
1076 			wait_for_completion(&ctx->kdamond_started);
1077 		}
1078 	}
1079 	mutex_unlock(&ctx->kdamond_lock);
1080 
1081 	return err;
1082 }
1083 
1084 /**
1085  * damon_start() - Starts the monitorings for a given group of contexts.
1086  * @ctxs:	an array of the pointers for contexts to start monitoring
1087  * @nr_ctxs:	size of @ctxs
1088  * @exclusive:	exclusiveness of this contexts group
1089  *
1090  * This function starts a group of monitoring threads for a group of monitoring
1091  * contexts.  One thread per each context is created and run in parallel.  The
1092  * caller should handle synchronization between the threads by itself.  If
1093  * @exclusive is true and a group of threads that created by other
1094  * 'damon_start()' call is currently running, this function does nothing but
1095  * returns -EBUSY.
1096  *
1097  * Return: 0 on success, negative error code otherwise.
1098  */
1099 int damon_start(struct damon_ctx **ctxs, int nr_ctxs, bool exclusive)
1100 {
1101 	int i;
1102 	int err = 0;
1103 
1104 	mutex_lock(&damon_lock);
1105 	if ((exclusive && nr_running_ctxs) ||
1106 			(!exclusive && running_exclusive_ctxs)) {
1107 		mutex_unlock(&damon_lock);
1108 		return -EBUSY;
1109 	}
1110 
1111 	for (i = 0; i < nr_ctxs; i++) {
1112 		err = __damon_start(ctxs[i]);
1113 		if (err)
1114 			break;
1115 		nr_running_ctxs++;
1116 	}
1117 	if (exclusive && nr_running_ctxs)
1118 		running_exclusive_ctxs = true;
1119 	mutex_unlock(&damon_lock);
1120 
1121 	return err;
1122 }
1123 
1124 /*
1125  * __damon_stop() - Stops monitoring of a given context.
1126  * @ctx:	monitoring context
1127  *
1128  * Return: 0 on success, negative error code otherwise.
1129  */
1130 static int __damon_stop(struct damon_ctx *ctx)
1131 {
1132 	struct task_struct *tsk;
1133 
1134 	mutex_lock(&ctx->kdamond_lock);
1135 	tsk = ctx->kdamond;
1136 	if (tsk) {
1137 		get_task_struct(tsk);
1138 		mutex_unlock(&ctx->kdamond_lock);
1139 		kthread_stop_put(tsk);
1140 		return 0;
1141 	}
1142 	mutex_unlock(&ctx->kdamond_lock);
1143 
1144 	return -EPERM;
1145 }
1146 
1147 /**
1148  * damon_stop() - Stops the monitorings for a given group of contexts.
1149  * @ctxs:	an array of the pointers for contexts to stop monitoring
1150  * @nr_ctxs:	size of @ctxs
1151  *
1152  * Return: 0 on success, negative error code otherwise.
1153  */
1154 int damon_stop(struct damon_ctx **ctxs, int nr_ctxs)
1155 {
1156 	int i, err = 0;
1157 
1158 	for (i = 0; i < nr_ctxs; i++) {
1159 		/* nr_running_ctxs is decremented in kdamond_fn */
1160 		err = __damon_stop(ctxs[i]);
1161 		if (err)
1162 			break;
1163 	}
1164 	return err;
1165 }
1166 
1167 static bool damon_is_running(struct damon_ctx *ctx)
1168 {
1169 	bool running;
1170 
1171 	mutex_lock(&ctx->kdamond_lock);
1172 	running = ctx->kdamond != NULL;
1173 	mutex_unlock(&ctx->kdamond_lock);
1174 	return running;
1175 }
1176 
1177 /**
1178  * damon_call() - Invoke a given function on DAMON worker thread (kdamond).
1179  * @ctx:	DAMON context to call the function for.
1180  * @control:	Control variable of the call request.
1181  *
1182  * Ask DAMON worker thread (kdamond) of @ctx to call a function with an
1183  * argument data that respectively passed via &damon_call_control->fn and
1184  * &damon_call_control->data of @control, and wait until the kdamond finishes
1185  * handling of the request.
1186  *
1187  * The kdamond executes the function with the argument in the main loop, just
1188  * after a sampling of the iteration is finished.  The function can hence
1189  * safely access the internal data of the &struct damon_ctx without additional
1190  * synchronization.  The return value of the function will be saved in
1191  * &damon_call_control->return_code.
1192  *
1193  * Return: 0 on success, negative error code otherwise.
1194  */
1195 int damon_call(struct damon_ctx *ctx, struct damon_call_control *control)
1196 {
1197 	init_completion(&control->completion);
1198 	control->canceled = false;
1199 
1200 	mutex_lock(&ctx->call_control_lock);
1201 	if (ctx->call_control) {
1202 		mutex_unlock(&ctx->call_control_lock);
1203 		return -EBUSY;
1204 	}
1205 	ctx->call_control = control;
1206 	mutex_unlock(&ctx->call_control_lock);
1207 	if (!damon_is_running(ctx))
1208 		return -EINVAL;
1209 	wait_for_completion(&control->completion);
1210 	if (control->canceled)
1211 		return -ECANCELED;
1212 	return 0;
1213 }
1214 
1215 /**
1216  * damos_walk() - Invoke a given functions while DAMOS walk regions.
1217  * @ctx:	DAMON context to call the functions for.
1218  * @control:	Control variable of the walk request.
1219  *
1220  * Ask DAMON worker thread (kdamond) of @ctx to call a function for each region
1221  * that the kdamond will apply DAMOS action to, and wait until the kdamond
1222  * finishes handling of the request.
1223  *
1224  * The kdamond executes the given function in the main loop, for each region
1225  * just after it applied any DAMOS actions of @ctx to it.  The invocation is
1226  * made only within one &damos->apply_interval_us since damos_walk()
1227  * invocation, for each scheme.  The given callback function can hence safely
1228  * access the internal data of &struct damon_ctx and &struct damon_region that
1229  * each of the scheme will apply the action for next interval, without
1230  * additional synchronizations against the kdamond.  If every scheme of @ctx
1231  * passed at least one &damos->apply_interval_us, kdamond marks the request as
1232  * completed so that damos_walk() can wakeup and return.
1233  *
1234  * Return: 0 on success, negative error code otherwise.
1235  */
1236 int damos_walk(struct damon_ctx *ctx, struct damos_walk_control *control)
1237 {
1238 	init_completion(&control->completion);
1239 	control->canceled = false;
1240 	mutex_lock(&ctx->walk_control_lock);
1241 	if (ctx->walk_control) {
1242 		mutex_unlock(&ctx->walk_control_lock);
1243 		return -EBUSY;
1244 	}
1245 	ctx->walk_control = control;
1246 	mutex_unlock(&ctx->walk_control_lock);
1247 	if (!damon_is_running(ctx))
1248 		return -EINVAL;
1249 	wait_for_completion(&control->completion);
1250 	if (control->canceled)
1251 		return -ECANCELED;
1252 	return 0;
1253 }
1254 
1255 /*
1256  * Reset the aggregated monitoring results ('nr_accesses' of each region).
1257  */
1258 static void kdamond_reset_aggregated(struct damon_ctx *c)
1259 {
1260 	struct damon_target *t;
1261 	unsigned int ti = 0;	/* target's index */
1262 
1263 	damon_for_each_target(t, c) {
1264 		struct damon_region *r;
1265 
1266 		damon_for_each_region(r, t) {
1267 			trace_damon_aggregated(ti, r, damon_nr_regions(t));
1268 			r->last_nr_accesses = r->nr_accesses;
1269 			r->nr_accesses = 0;
1270 		}
1271 		ti++;
1272 	}
1273 }
1274 
1275 static void damon_split_region_at(struct damon_target *t,
1276 				  struct damon_region *r, unsigned long sz_r);
1277 
1278 static bool __damos_valid_target(struct damon_region *r, struct damos *s)
1279 {
1280 	unsigned long sz;
1281 	unsigned int nr_accesses = r->nr_accesses_bp / 10000;
1282 
1283 	sz = damon_sz_region(r);
1284 	return s->pattern.min_sz_region <= sz &&
1285 		sz <= s->pattern.max_sz_region &&
1286 		s->pattern.min_nr_accesses <= nr_accesses &&
1287 		nr_accesses <= s->pattern.max_nr_accesses &&
1288 		s->pattern.min_age_region <= r->age &&
1289 		r->age <= s->pattern.max_age_region;
1290 }
1291 
1292 static bool damos_valid_target(struct damon_ctx *c, struct damon_target *t,
1293 		struct damon_region *r, struct damos *s)
1294 {
1295 	bool ret = __damos_valid_target(r, s);
1296 
1297 	if (!ret || !s->quota.esz || !c->ops.get_scheme_score)
1298 		return ret;
1299 
1300 	return c->ops.get_scheme_score(c, t, r, s) >= s->quota.min_score;
1301 }
1302 
1303 /*
1304  * damos_skip_charged_region() - Check if the given region or starting part of
1305  * it is already charged for the DAMOS quota.
1306  * @t:	The target of the region.
1307  * @rp:	The pointer to the region.
1308  * @s:	The scheme to be applied.
1309  *
1310  * If a quota of a scheme has exceeded in a quota charge window, the scheme's
1311  * action would applied to only a part of the target access pattern fulfilling
1312  * regions.  To avoid applying the scheme action to only already applied
1313  * regions, DAMON skips applying the scheme action to the regions that charged
1314  * in the previous charge window.
1315  *
1316  * This function checks if a given region should be skipped or not for the
1317  * reason.  If only the starting part of the region has previously charged,
1318  * this function splits the region into two so that the second one covers the
1319  * area that not charged in the previous charge widnow and saves the second
1320  * region in *rp and returns false, so that the caller can apply DAMON action
1321  * to the second one.
1322  *
1323  * Return: true if the region should be entirely skipped, false otherwise.
1324  */
1325 static bool damos_skip_charged_region(struct damon_target *t,
1326 		struct damon_region **rp, struct damos *s)
1327 {
1328 	struct damon_region *r = *rp;
1329 	struct damos_quota *quota = &s->quota;
1330 	unsigned long sz_to_skip;
1331 
1332 	/* Skip previously charged regions */
1333 	if (quota->charge_target_from) {
1334 		if (t != quota->charge_target_from)
1335 			return true;
1336 		if (r == damon_last_region(t)) {
1337 			quota->charge_target_from = NULL;
1338 			quota->charge_addr_from = 0;
1339 			return true;
1340 		}
1341 		if (quota->charge_addr_from &&
1342 				r->ar.end <= quota->charge_addr_from)
1343 			return true;
1344 
1345 		if (quota->charge_addr_from && r->ar.start <
1346 				quota->charge_addr_from) {
1347 			sz_to_skip = ALIGN_DOWN(quota->charge_addr_from -
1348 					r->ar.start, DAMON_MIN_REGION);
1349 			if (!sz_to_skip) {
1350 				if (damon_sz_region(r) <= DAMON_MIN_REGION)
1351 					return true;
1352 				sz_to_skip = DAMON_MIN_REGION;
1353 			}
1354 			damon_split_region_at(t, r, sz_to_skip);
1355 			r = damon_next_region(r);
1356 			*rp = r;
1357 		}
1358 		quota->charge_target_from = NULL;
1359 		quota->charge_addr_from = 0;
1360 	}
1361 	return false;
1362 }
1363 
1364 static void damos_update_stat(struct damos *s,
1365 		unsigned long sz_tried, unsigned long sz_applied,
1366 		unsigned long sz_ops_filter_passed)
1367 {
1368 	s->stat.nr_tried++;
1369 	s->stat.sz_tried += sz_tried;
1370 	if (sz_applied)
1371 		s->stat.nr_applied++;
1372 	s->stat.sz_applied += sz_applied;
1373 	s->stat.sz_ops_filter_passed += sz_ops_filter_passed;
1374 }
1375 
1376 static bool __damos_filter_out(struct damon_ctx *ctx, struct damon_target *t,
1377 		struct damon_region *r, struct damos_filter *filter)
1378 {
1379 	bool matched = false;
1380 	struct damon_target *ti;
1381 	int target_idx = 0;
1382 	unsigned long start, end;
1383 
1384 	switch (filter->type) {
1385 	case DAMOS_FILTER_TYPE_TARGET:
1386 		damon_for_each_target(ti, ctx) {
1387 			if (ti == t)
1388 				break;
1389 			target_idx++;
1390 		}
1391 		matched = target_idx == filter->target_idx;
1392 		break;
1393 	case DAMOS_FILTER_TYPE_ADDR:
1394 		start = ALIGN_DOWN(filter->addr_range.start, DAMON_MIN_REGION);
1395 		end = ALIGN_DOWN(filter->addr_range.end, DAMON_MIN_REGION);
1396 
1397 		/* inside the range */
1398 		if (start <= r->ar.start && r->ar.end <= end) {
1399 			matched = true;
1400 			break;
1401 		}
1402 		/* outside of the range */
1403 		if (r->ar.end <= start || end <= r->ar.start) {
1404 			matched = false;
1405 			break;
1406 		}
1407 		/* start before the range and overlap */
1408 		if (r->ar.start < start) {
1409 			damon_split_region_at(t, r, start - r->ar.start);
1410 			matched = false;
1411 			break;
1412 		}
1413 		/* start inside the range */
1414 		damon_split_region_at(t, r, end - r->ar.start);
1415 		matched = true;
1416 		break;
1417 	default:
1418 		return false;
1419 	}
1420 
1421 	return matched == filter->matching;
1422 }
1423 
1424 static bool damos_filter_out(struct damon_ctx *ctx, struct damon_target *t,
1425 		struct damon_region *r, struct damos *s)
1426 {
1427 	struct damos_filter *filter;
1428 
1429 	damos_for_each_filter(filter, s) {
1430 		if (__damos_filter_out(ctx, t, r, filter))
1431 			return true;
1432 	}
1433 	return false;
1434 }
1435 
1436 /*
1437  * damos_walk_call_walk() - Call &damos_walk_control->walk_fn.
1438  * @ctx:	The context of &damon_ctx->walk_control.
1439  * @t:		The monitoring target of @r that @s will be applied.
1440  * @r:		The region of @t that @s will be applied.
1441  * @s:		The scheme of @ctx that will be applied to @r.
1442  *
1443  * This function is called from kdamond whenever it asked the operation set to
1444  * apply a DAMOS scheme action to a region.  If a DAMOS walk request is
1445  * installed by damos_walk() and not yet uninstalled, invoke it.
1446  */
1447 static void damos_walk_call_walk(struct damon_ctx *ctx, struct damon_target *t,
1448 		struct damon_region *r, struct damos *s,
1449 		unsigned long sz_filter_passed)
1450 {
1451 	struct damos_walk_control *control;
1452 
1453 	mutex_lock(&ctx->walk_control_lock);
1454 	control = ctx->walk_control;
1455 	mutex_unlock(&ctx->walk_control_lock);
1456 	if (!control)
1457 		return;
1458 	control->walk_fn(control->data, ctx, t, r, s, sz_filter_passed);
1459 }
1460 
1461 /*
1462  * damos_walk_complete() - Complete DAMOS walk request if all walks are done.
1463  * @ctx:	The context of &damon_ctx->walk_control.
1464  * @s:		A scheme of @ctx that all walks are now done.
1465  *
1466  * This function is called when kdamond finished applying the action of a DAMOS
1467  * scheme to all regions that eligible for the given &damos->apply_interval_us.
1468  * If every scheme of @ctx including @s now finished walking for at least one
1469  * &damos->apply_interval_us, this function makrs the handling of the given
1470  * DAMOS walk request is done, so that damos_walk() can wake up and return.
1471  */
1472 static void damos_walk_complete(struct damon_ctx *ctx, struct damos *s)
1473 {
1474 	struct damos *siter;
1475 	struct damos_walk_control *control;
1476 
1477 	mutex_lock(&ctx->walk_control_lock);
1478 	control = ctx->walk_control;
1479 	mutex_unlock(&ctx->walk_control_lock);
1480 	if (!control)
1481 		return;
1482 
1483 	s->walk_completed = true;
1484 	/* if all schemes completed, signal completion to walker */
1485 	damon_for_each_scheme(siter, ctx) {
1486 		if (!siter->walk_completed)
1487 			return;
1488 	}
1489 	complete(&control->completion);
1490 	mutex_lock(&ctx->walk_control_lock);
1491 	ctx->walk_control = NULL;
1492 	mutex_unlock(&ctx->walk_control_lock);
1493 }
1494 
1495 /*
1496  * damos_walk_cancel() - Cancel the current DAMOS walk request.
1497  * @ctx:	The context of &damon_ctx->walk_control.
1498  *
1499  * This function is called when @ctx is deactivated by DAMOS watermarks, DAMOS
1500  * walk is requested but there is no DAMOS scheme to walk for, or the kdamond
1501  * is already out of the main loop and therefore gonna be terminated, and hence
1502  * cannot continue the walks.  This function therefore marks the walk request
1503  * as canceled, so that damos_walk() can wake up and return.
1504  */
1505 static void damos_walk_cancel(struct damon_ctx *ctx)
1506 {
1507 	struct damos_walk_control *control;
1508 
1509 	mutex_lock(&ctx->walk_control_lock);
1510 	control = ctx->walk_control;
1511 	mutex_unlock(&ctx->walk_control_lock);
1512 
1513 	if (!control)
1514 		return;
1515 	control->canceled = true;
1516 	complete(&control->completion);
1517 	mutex_lock(&ctx->walk_control_lock);
1518 	ctx->walk_control = NULL;
1519 	mutex_unlock(&ctx->walk_control_lock);
1520 }
1521 
1522 static void damos_apply_scheme(struct damon_ctx *c, struct damon_target *t,
1523 		struct damon_region *r, struct damos *s)
1524 {
1525 	struct damos_quota *quota = &s->quota;
1526 	unsigned long sz = damon_sz_region(r);
1527 	struct timespec64 begin, end;
1528 	unsigned long sz_applied = 0;
1529 	unsigned long sz_ops_filter_passed = 0;
1530 	int err = 0;
1531 	/*
1532 	 * We plan to support multiple context per kdamond, as DAMON sysfs
1533 	 * implies with 'nr_contexts' file.  Nevertheless, only single context
1534 	 * per kdamond is supported for now.  So, we can simply use '0' context
1535 	 * index here.
1536 	 */
1537 	unsigned int cidx = 0;
1538 	struct damos *siter;		/* schemes iterator */
1539 	unsigned int sidx = 0;
1540 	struct damon_target *titer;	/* targets iterator */
1541 	unsigned int tidx = 0;
1542 	bool do_trace = false;
1543 
1544 	/* get indices for trace_damos_before_apply() */
1545 	if (trace_damos_before_apply_enabled()) {
1546 		damon_for_each_scheme(siter, c) {
1547 			if (siter == s)
1548 				break;
1549 			sidx++;
1550 		}
1551 		damon_for_each_target(titer, c) {
1552 			if (titer == t)
1553 				break;
1554 			tidx++;
1555 		}
1556 		do_trace = true;
1557 	}
1558 
1559 	if (c->ops.apply_scheme) {
1560 		if (quota->esz && quota->charged_sz + sz > quota->esz) {
1561 			sz = ALIGN_DOWN(quota->esz - quota->charged_sz,
1562 					DAMON_MIN_REGION);
1563 			if (!sz)
1564 				goto update_stat;
1565 			damon_split_region_at(t, r, sz);
1566 		}
1567 		if (damos_filter_out(c, t, r, s))
1568 			return;
1569 		ktime_get_coarse_ts64(&begin);
1570 		if (c->callback.before_damos_apply)
1571 			err = c->callback.before_damos_apply(c, t, r, s);
1572 		if (!err) {
1573 			trace_damos_before_apply(cidx, sidx, tidx, r,
1574 					damon_nr_regions(t), do_trace);
1575 			sz_applied = c->ops.apply_scheme(c, t, r, s,
1576 					&sz_ops_filter_passed);
1577 		}
1578 		damos_walk_call_walk(c, t, r, s, sz_ops_filter_passed);
1579 		ktime_get_coarse_ts64(&end);
1580 		quota->total_charged_ns += timespec64_to_ns(&end) -
1581 			timespec64_to_ns(&begin);
1582 		quota->charged_sz += sz;
1583 		if (quota->esz && quota->charged_sz >= quota->esz) {
1584 			quota->charge_target_from = t;
1585 			quota->charge_addr_from = r->ar.end + 1;
1586 		}
1587 	}
1588 	if (s->action != DAMOS_STAT)
1589 		r->age = 0;
1590 
1591 update_stat:
1592 	damos_update_stat(s, sz, sz_applied, sz_ops_filter_passed);
1593 }
1594 
1595 static void damon_do_apply_schemes(struct damon_ctx *c,
1596 				   struct damon_target *t,
1597 				   struct damon_region *r)
1598 {
1599 	struct damos *s;
1600 
1601 	damon_for_each_scheme(s, c) {
1602 		struct damos_quota *quota = &s->quota;
1603 
1604 		if (c->passed_sample_intervals < s->next_apply_sis)
1605 			continue;
1606 
1607 		if (!s->wmarks.activated)
1608 			continue;
1609 
1610 		/* Check the quota */
1611 		if (quota->esz && quota->charged_sz >= quota->esz)
1612 			continue;
1613 
1614 		if (damos_skip_charged_region(t, &r, s))
1615 			continue;
1616 
1617 		if (!damos_valid_target(c, t, r, s))
1618 			continue;
1619 
1620 		damos_apply_scheme(c, t, r, s);
1621 	}
1622 }
1623 
1624 /*
1625  * damon_feed_loop_next_input() - get next input to achieve a target score.
1626  * @last_input	The last input.
1627  * @score	Current score that made with @last_input.
1628  *
1629  * Calculate next input to achieve the target score, based on the last input
1630  * and current score.  Assuming the input and the score are positively
1631  * proportional, calculate how much compensation should be added to or
1632  * subtracted from the last input as a proportion of the last input.  Avoid
1633  * next input always being zero by setting it non-zero always.  In short form
1634  * (assuming support of float and signed calculations), the algorithm is as
1635  * below.
1636  *
1637  * next_input = max(last_input * ((goal - current) / goal + 1), 1)
1638  *
1639  * For simple implementation, we assume the target score is always 10,000.  The
1640  * caller should adjust @score for this.
1641  *
1642  * Returns next input that assumed to achieve the target score.
1643  */
1644 static unsigned long damon_feed_loop_next_input(unsigned long last_input,
1645 		unsigned long score)
1646 {
1647 	const unsigned long goal = 10000;
1648 	/* Set minimum input as 10000 to avoid compensation be zero */
1649 	const unsigned long min_input = 10000;
1650 	unsigned long score_goal_diff, compensation;
1651 	bool over_achieving = score > goal;
1652 
1653 	if (score == goal)
1654 		return last_input;
1655 	if (score >= goal * 2)
1656 		return min_input;
1657 
1658 	if (over_achieving)
1659 		score_goal_diff = score - goal;
1660 	else
1661 		score_goal_diff = goal - score;
1662 
1663 	if (last_input < ULONG_MAX / score_goal_diff)
1664 		compensation = last_input * score_goal_diff / goal;
1665 	else
1666 		compensation = last_input / goal * score_goal_diff;
1667 
1668 	if (over_achieving)
1669 		return max(last_input - compensation, min_input);
1670 	if (last_input < ULONG_MAX - compensation)
1671 		return last_input + compensation;
1672 	return ULONG_MAX;
1673 }
1674 
1675 #ifdef CONFIG_PSI
1676 
1677 static u64 damos_get_some_mem_psi_total(void)
1678 {
1679 	if (static_branch_likely(&psi_disabled))
1680 		return 0;
1681 	return div_u64(psi_system.total[PSI_AVGS][PSI_MEM * 2],
1682 			NSEC_PER_USEC);
1683 }
1684 
1685 #else	/* CONFIG_PSI */
1686 
1687 static inline u64 damos_get_some_mem_psi_total(void)
1688 {
1689 	return 0;
1690 };
1691 
1692 #endif	/* CONFIG_PSI */
1693 
1694 static void damos_set_quota_goal_current_value(struct damos_quota_goal *goal)
1695 {
1696 	u64 now_psi_total;
1697 
1698 	switch (goal->metric) {
1699 	case DAMOS_QUOTA_USER_INPUT:
1700 		/* User should already set goal->current_value */
1701 		break;
1702 	case DAMOS_QUOTA_SOME_MEM_PSI_US:
1703 		now_psi_total = damos_get_some_mem_psi_total();
1704 		goal->current_value = now_psi_total - goal->last_psi_total;
1705 		goal->last_psi_total = now_psi_total;
1706 		break;
1707 	default:
1708 		break;
1709 	}
1710 }
1711 
1712 /* Return the highest score since it makes schemes least aggressive */
1713 static unsigned long damos_quota_score(struct damos_quota *quota)
1714 {
1715 	struct damos_quota_goal *goal;
1716 	unsigned long highest_score = 0;
1717 
1718 	damos_for_each_quota_goal(goal, quota) {
1719 		damos_set_quota_goal_current_value(goal);
1720 		highest_score = max(highest_score,
1721 				goal->current_value * 10000 /
1722 				goal->target_value);
1723 	}
1724 
1725 	return highest_score;
1726 }
1727 
1728 /*
1729  * Called only if quota->ms, or quota->sz are set, or quota->goals is not empty
1730  */
1731 static void damos_set_effective_quota(struct damos_quota *quota)
1732 {
1733 	unsigned long throughput;
1734 	unsigned long esz = ULONG_MAX;
1735 
1736 	if (!quota->ms && list_empty(&quota->goals)) {
1737 		quota->esz = quota->sz;
1738 		return;
1739 	}
1740 
1741 	if (!list_empty(&quota->goals)) {
1742 		unsigned long score = damos_quota_score(quota);
1743 
1744 		quota->esz_bp = damon_feed_loop_next_input(
1745 				max(quota->esz_bp, 10000UL),
1746 				score);
1747 		esz = quota->esz_bp / 10000;
1748 	}
1749 
1750 	if (quota->ms) {
1751 		if (quota->total_charged_ns)
1752 			throughput = quota->total_charged_sz * 1000000 /
1753 				quota->total_charged_ns;
1754 		else
1755 			throughput = PAGE_SIZE * 1024;
1756 		esz = min(throughput * quota->ms, esz);
1757 	}
1758 
1759 	if (quota->sz && quota->sz < esz)
1760 		esz = quota->sz;
1761 
1762 	quota->esz = esz;
1763 }
1764 
1765 static void damos_adjust_quota(struct damon_ctx *c, struct damos *s)
1766 {
1767 	struct damos_quota *quota = &s->quota;
1768 	struct damon_target *t;
1769 	struct damon_region *r;
1770 	unsigned long cumulated_sz;
1771 	unsigned int score, max_score = 0;
1772 
1773 	if (!quota->ms && !quota->sz && list_empty(&quota->goals))
1774 		return;
1775 
1776 	/* New charge window starts */
1777 	if (time_after_eq(jiffies, quota->charged_from +
1778 				msecs_to_jiffies(quota->reset_interval))) {
1779 		if (quota->esz && quota->charged_sz >= quota->esz)
1780 			s->stat.qt_exceeds++;
1781 		quota->total_charged_sz += quota->charged_sz;
1782 		quota->charged_from = jiffies;
1783 		quota->charged_sz = 0;
1784 		damos_set_effective_quota(quota);
1785 	}
1786 
1787 	if (!c->ops.get_scheme_score)
1788 		return;
1789 
1790 	/* Fill up the score histogram */
1791 	memset(c->regions_score_histogram, 0,
1792 			sizeof(*c->regions_score_histogram) *
1793 			(DAMOS_MAX_SCORE + 1));
1794 	damon_for_each_target(t, c) {
1795 		damon_for_each_region(r, t) {
1796 			if (!__damos_valid_target(r, s))
1797 				continue;
1798 			score = c->ops.get_scheme_score(c, t, r, s);
1799 			c->regions_score_histogram[score] +=
1800 				damon_sz_region(r);
1801 			if (score > max_score)
1802 				max_score = score;
1803 		}
1804 	}
1805 
1806 	/* Set the min score limit */
1807 	for (cumulated_sz = 0, score = max_score; ; score--) {
1808 		cumulated_sz += c->regions_score_histogram[score];
1809 		if (cumulated_sz >= quota->esz || !score)
1810 			break;
1811 	}
1812 	quota->min_score = score;
1813 }
1814 
1815 static void kdamond_apply_schemes(struct damon_ctx *c)
1816 {
1817 	struct damon_target *t;
1818 	struct damon_region *r, *next_r;
1819 	struct damos *s;
1820 	unsigned long sample_interval = c->attrs.sample_interval ?
1821 		c->attrs.sample_interval : 1;
1822 	bool has_schemes_to_apply = false;
1823 
1824 	damon_for_each_scheme(s, c) {
1825 		if (c->passed_sample_intervals < s->next_apply_sis)
1826 			continue;
1827 
1828 		if (!s->wmarks.activated)
1829 			continue;
1830 
1831 		has_schemes_to_apply = true;
1832 
1833 		damos_adjust_quota(c, s);
1834 	}
1835 
1836 	if (!has_schemes_to_apply)
1837 		return;
1838 
1839 	damon_for_each_target(t, c) {
1840 		damon_for_each_region_safe(r, next_r, t)
1841 			damon_do_apply_schemes(c, t, r);
1842 	}
1843 
1844 	damon_for_each_scheme(s, c) {
1845 		if (c->passed_sample_intervals < s->next_apply_sis)
1846 			continue;
1847 		damos_walk_complete(c, s);
1848 		s->next_apply_sis = c->passed_sample_intervals +
1849 			(s->apply_interval_us ? s->apply_interval_us :
1850 			 c->attrs.aggr_interval) / sample_interval;
1851 	}
1852 }
1853 
1854 /*
1855  * Merge two adjacent regions into one region
1856  */
1857 static void damon_merge_two_regions(struct damon_target *t,
1858 		struct damon_region *l, struct damon_region *r)
1859 {
1860 	unsigned long sz_l = damon_sz_region(l), sz_r = damon_sz_region(r);
1861 
1862 	l->nr_accesses = (l->nr_accesses * sz_l + r->nr_accesses * sz_r) /
1863 			(sz_l + sz_r);
1864 	l->nr_accesses_bp = l->nr_accesses * 10000;
1865 	l->age = (l->age * sz_l + r->age * sz_r) / (sz_l + sz_r);
1866 	l->ar.end = r->ar.end;
1867 	damon_destroy_region(r, t);
1868 }
1869 
1870 /*
1871  * Merge adjacent regions having similar access frequencies
1872  *
1873  * t		target affected by this merge operation
1874  * thres	'->nr_accesses' diff threshold for the merge
1875  * sz_limit	size upper limit of each region
1876  */
1877 static void damon_merge_regions_of(struct damon_target *t, unsigned int thres,
1878 				   unsigned long sz_limit)
1879 {
1880 	struct damon_region *r, *prev = NULL, *next;
1881 
1882 	damon_for_each_region_safe(r, next, t) {
1883 		if (abs(r->nr_accesses - r->last_nr_accesses) > thres)
1884 			r->age = 0;
1885 		else
1886 			r->age++;
1887 
1888 		if (prev && prev->ar.end == r->ar.start &&
1889 		    abs(prev->nr_accesses - r->nr_accesses) <= thres &&
1890 		    damon_sz_region(prev) + damon_sz_region(r) <= sz_limit)
1891 			damon_merge_two_regions(t, prev, r);
1892 		else
1893 			prev = r;
1894 	}
1895 }
1896 
1897 /*
1898  * Merge adjacent regions having similar access frequencies
1899  *
1900  * threshold	'->nr_accesses' diff threshold for the merge
1901  * sz_limit	size upper limit of each region
1902  *
1903  * This function merges monitoring target regions which are adjacent and their
1904  * access frequencies are similar.  This is for minimizing the monitoring
1905  * overhead under the dynamically changeable access pattern.  If a merge was
1906  * unnecessarily made, later 'kdamond_split_regions()' will revert it.
1907  *
1908  * The total number of regions could be higher than the user-defined limit,
1909  * max_nr_regions for some cases.  For example, the user can update
1910  * max_nr_regions to a number that lower than the current number of regions
1911  * while DAMON is running.  For such a case, repeat merging until the limit is
1912  * met while increasing @threshold up to possible maximum level.
1913  */
1914 static void kdamond_merge_regions(struct damon_ctx *c, unsigned int threshold,
1915 				  unsigned long sz_limit)
1916 {
1917 	struct damon_target *t;
1918 	unsigned int nr_regions;
1919 	unsigned int max_thres;
1920 
1921 	max_thres = c->attrs.aggr_interval /
1922 		(c->attrs.sample_interval ?  c->attrs.sample_interval : 1);
1923 	do {
1924 		nr_regions = 0;
1925 		damon_for_each_target(t, c) {
1926 			damon_merge_regions_of(t, threshold, sz_limit);
1927 			nr_regions += damon_nr_regions(t);
1928 		}
1929 		threshold = max(1, threshold * 2);
1930 	} while (nr_regions > c->attrs.max_nr_regions &&
1931 			threshold / 2 < max_thres);
1932 }
1933 
1934 /*
1935  * Split a region in two
1936  *
1937  * r		the region to be split
1938  * sz_r		size of the first sub-region that will be made
1939  */
1940 static void damon_split_region_at(struct damon_target *t,
1941 				  struct damon_region *r, unsigned long sz_r)
1942 {
1943 	struct damon_region *new;
1944 
1945 	new = damon_new_region(r->ar.start + sz_r, r->ar.end);
1946 	if (!new)
1947 		return;
1948 
1949 	r->ar.end = new->ar.start;
1950 
1951 	new->age = r->age;
1952 	new->last_nr_accesses = r->last_nr_accesses;
1953 	new->nr_accesses_bp = r->nr_accesses_bp;
1954 	new->nr_accesses = r->nr_accesses;
1955 
1956 	damon_insert_region(new, r, damon_next_region(r), t);
1957 }
1958 
1959 /* Split every region in the given target into 'nr_subs' regions */
1960 static void damon_split_regions_of(struct damon_target *t, int nr_subs)
1961 {
1962 	struct damon_region *r, *next;
1963 	unsigned long sz_region, sz_sub = 0;
1964 	int i;
1965 
1966 	damon_for_each_region_safe(r, next, t) {
1967 		sz_region = damon_sz_region(r);
1968 
1969 		for (i = 0; i < nr_subs - 1 &&
1970 				sz_region > 2 * DAMON_MIN_REGION; i++) {
1971 			/*
1972 			 * Randomly select size of left sub-region to be at
1973 			 * least 10 percent and at most 90% of original region
1974 			 */
1975 			sz_sub = ALIGN_DOWN(damon_rand(1, 10) *
1976 					sz_region / 10, DAMON_MIN_REGION);
1977 			/* Do not allow blank region */
1978 			if (sz_sub == 0 || sz_sub >= sz_region)
1979 				continue;
1980 
1981 			damon_split_region_at(t, r, sz_sub);
1982 			sz_region = sz_sub;
1983 		}
1984 	}
1985 }
1986 
1987 /*
1988  * Split every target region into randomly-sized small regions
1989  *
1990  * This function splits every target region into random-sized small regions if
1991  * current total number of the regions is equal or smaller than half of the
1992  * user-specified maximum number of regions.  This is for maximizing the
1993  * monitoring accuracy under the dynamically changeable access patterns.  If a
1994  * split was unnecessarily made, later 'kdamond_merge_regions()' will revert
1995  * it.
1996  */
1997 static void kdamond_split_regions(struct damon_ctx *ctx)
1998 {
1999 	struct damon_target *t;
2000 	unsigned int nr_regions = 0;
2001 	static unsigned int last_nr_regions;
2002 	int nr_subregions = 2;
2003 
2004 	damon_for_each_target(t, ctx)
2005 		nr_regions += damon_nr_regions(t);
2006 
2007 	if (nr_regions > ctx->attrs.max_nr_regions / 2)
2008 		return;
2009 
2010 	/* Maybe the middle of the region has different access frequency */
2011 	if (last_nr_regions == nr_regions &&
2012 			nr_regions < ctx->attrs.max_nr_regions / 3)
2013 		nr_subregions = 3;
2014 
2015 	damon_for_each_target(t, ctx)
2016 		damon_split_regions_of(t, nr_subregions);
2017 
2018 	last_nr_regions = nr_regions;
2019 }
2020 
2021 /*
2022  * Check whether current monitoring should be stopped
2023  *
2024  * The monitoring is stopped when either the user requested to stop, or all
2025  * monitoring targets are invalid.
2026  *
2027  * Returns true if need to stop current monitoring.
2028  */
2029 static bool kdamond_need_stop(struct damon_ctx *ctx)
2030 {
2031 	struct damon_target *t;
2032 
2033 	if (kthread_should_stop())
2034 		return true;
2035 
2036 	if (!ctx->ops.target_valid)
2037 		return false;
2038 
2039 	damon_for_each_target(t, ctx) {
2040 		if (ctx->ops.target_valid(t))
2041 			return false;
2042 	}
2043 
2044 	return true;
2045 }
2046 
2047 static int damos_get_wmark_metric_value(enum damos_wmark_metric metric,
2048 					unsigned long *metric_value)
2049 {
2050 	switch (metric) {
2051 	case DAMOS_WMARK_FREE_MEM_RATE:
2052 		*metric_value = global_zone_page_state(NR_FREE_PAGES) * 1000 /
2053 		       totalram_pages();
2054 		return 0;
2055 	default:
2056 		break;
2057 	}
2058 	return -EINVAL;
2059 }
2060 
2061 /*
2062  * Returns zero if the scheme is active.  Else, returns time to wait for next
2063  * watermark check in micro-seconds.
2064  */
2065 static unsigned long damos_wmark_wait_us(struct damos *scheme)
2066 {
2067 	unsigned long metric;
2068 
2069 	if (damos_get_wmark_metric_value(scheme->wmarks.metric, &metric))
2070 		return 0;
2071 
2072 	/* higher than high watermark or lower than low watermark */
2073 	if (metric > scheme->wmarks.high || scheme->wmarks.low > metric) {
2074 		if (scheme->wmarks.activated)
2075 			pr_debug("deactivate a scheme (%d) for %s wmark\n",
2076 					scheme->action,
2077 					metric > scheme->wmarks.high ?
2078 					"high" : "low");
2079 		scheme->wmarks.activated = false;
2080 		return scheme->wmarks.interval;
2081 	}
2082 
2083 	/* inactive and higher than middle watermark */
2084 	if ((scheme->wmarks.high >= metric && metric >= scheme->wmarks.mid) &&
2085 			!scheme->wmarks.activated)
2086 		return scheme->wmarks.interval;
2087 
2088 	if (!scheme->wmarks.activated)
2089 		pr_debug("activate a scheme (%d)\n", scheme->action);
2090 	scheme->wmarks.activated = true;
2091 	return 0;
2092 }
2093 
2094 static void kdamond_usleep(unsigned long usecs)
2095 {
2096 	if (usecs >= USLEEP_RANGE_UPPER_BOUND)
2097 		schedule_timeout_idle(usecs_to_jiffies(usecs));
2098 	else
2099 		usleep_range_idle(usecs, usecs + 1);
2100 }
2101 
2102 /*
2103  * kdamond_call() - handle damon_call_control.
2104  * @ctx:	The &struct damon_ctx of the kdamond.
2105  * @cancel:	Whether to cancel the invocation of the function.
2106  *
2107  * If there is a &struct damon_call_control request that registered via
2108  * &damon_call() on @ctx, do or cancel the invocation of the function depending
2109  * on @cancel.  @cancel is set when the kdamond is deactivated by DAMOS
2110  * watermarks, or the kdamond is already out of the main loop and therefore
2111  * will be terminated.
2112  */
2113 static void kdamond_call(struct damon_ctx *ctx, bool cancel)
2114 {
2115 	struct damon_call_control *control;
2116 	int ret = 0;
2117 
2118 	mutex_lock(&ctx->call_control_lock);
2119 	control = ctx->call_control;
2120 	mutex_unlock(&ctx->call_control_lock);
2121 	if (!control)
2122 		return;
2123 	if (cancel) {
2124 		control->canceled = true;
2125 	} else {
2126 		ret = control->fn(control->data);
2127 		control->return_code = ret;
2128 	}
2129 	complete(&control->completion);
2130 	mutex_lock(&ctx->call_control_lock);
2131 	ctx->call_control = NULL;
2132 	mutex_unlock(&ctx->call_control_lock);
2133 }
2134 
2135 /* Returns negative error code if it's not activated but should return */
2136 static int kdamond_wait_activation(struct damon_ctx *ctx)
2137 {
2138 	struct damos *s;
2139 	unsigned long wait_time;
2140 	unsigned long min_wait_time = 0;
2141 	bool init_wait_time = false;
2142 
2143 	while (!kdamond_need_stop(ctx)) {
2144 		damon_for_each_scheme(s, ctx) {
2145 			wait_time = damos_wmark_wait_us(s);
2146 			if (!init_wait_time || wait_time < min_wait_time) {
2147 				init_wait_time = true;
2148 				min_wait_time = wait_time;
2149 			}
2150 		}
2151 		if (!min_wait_time)
2152 			return 0;
2153 
2154 		kdamond_usleep(min_wait_time);
2155 
2156 		if (ctx->callback.after_wmarks_check &&
2157 				ctx->callback.after_wmarks_check(ctx))
2158 			break;
2159 		kdamond_call(ctx, true);
2160 		damos_walk_cancel(ctx);
2161 	}
2162 	return -EBUSY;
2163 }
2164 
2165 static void kdamond_init_intervals_sis(struct damon_ctx *ctx)
2166 {
2167 	unsigned long sample_interval = ctx->attrs.sample_interval ?
2168 		ctx->attrs.sample_interval : 1;
2169 	unsigned long apply_interval;
2170 	struct damos *scheme;
2171 
2172 	ctx->passed_sample_intervals = 0;
2173 	ctx->next_aggregation_sis = ctx->attrs.aggr_interval / sample_interval;
2174 	ctx->next_ops_update_sis = ctx->attrs.ops_update_interval /
2175 		sample_interval;
2176 
2177 	damon_for_each_scheme(scheme, ctx) {
2178 		apply_interval = scheme->apply_interval_us ?
2179 			scheme->apply_interval_us : ctx->attrs.aggr_interval;
2180 		scheme->next_apply_sis = apply_interval / sample_interval;
2181 	}
2182 }
2183 
2184 /*
2185  * The monitoring daemon that runs as a kernel thread
2186  */
2187 static int kdamond_fn(void *data)
2188 {
2189 	struct damon_ctx *ctx = data;
2190 	struct damon_target *t;
2191 	struct damon_region *r, *next;
2192 	unsigned int max_nr_accesses = 0;
2193 	unsigned long sz_limit = 0;
2194 
2195 	pr_debug("kdamond (%d) starts\n", current->pid);
2196 
2197 	complete(&ctx->kdamond_started);
2198 	kdamond_init_intervals_sis(ctx);
2199 
2200 	if (ctx->ops.init)
2201 		ctx->ops.init(ctx);
2202 	if (ctx->callback.before_start && ctx->callback.before_start(ctx))
2203 		goto done;
2204 	ctx->regions_score_histogram = kmalloc_array(DAMOS_MAX_SCORE + 1,
2205 			sizeof(*ctx->regions_score_histogram), GFP_KERNEL);
2206 	if (!ctx->regions_score_histogram)
2207 		goto done;
2208 
2209 	sz_limit = damon_region_sz_limit(ctx);
2210 
2211 	while (!kdamond_need_stop(ctx)) {
2212 		/*
2213 		 * ctx->attrs and ctx->next_{aggregation,ops_update}_sis could
2214 		 * be changed from after_wmarks_check() or after_aggregation()
2215 		 * callbacks.  Read the values here, and use those for this
2216 		 * iteration.  That is, damon_set_attrs() updated new values
2217 		 * are respected from next iteration.
2218 		 */
2219 		unsigned long next_aggregation_sis = ctx->next_aggregation_sis;
2220 		unsigned long next_ops_update_sis = ctx->next_ops_update_sis;
2221 		unsigned long sample_interval = ctx->attrs.sample_interval;
2222 
2223 		if (kdamond_wait_activation(ctx))
2224 			break;
2225 
2226 		if (ctx->ops.prepare_access_checks)
2227 			ctx->ops.prepare_access_checks(ctx);
2228 		if (ctx->callback.after_sampling &&
2229 				ctx->callback.after_sampling(ctx))
2230 			break;
2231 		kdamond_call(ctx, false);
2232 
2233 		kdamond_usleep(sample_interval);
2234 		ctx->passed_sample_intervals++;
2235 
2236 		if (ctx->ops.check_accesses)
2237 			max_nr_accesses = ctx->ops.check_accesses(ctx);
2238 
2239 		if (ctx->passed_sample_intervals >= next_aggregation_sis) {
2240 			kdamond_merge_regions(ctx,
2241 					max_nr_accesses / 10,
2242 					sz_limit);
2243 			if (ctx->callback.after_aggregation &&
2244 					ctx->callback.after_aggregation(ctx))
2245 				break;
2246 		}
2247 
2248 		/*
2249 		 * do kdamond_apply_schemes() after kdamond_merge_regions() if
2250 		 * possible, to reduce overhead
2251 		 */
2252 		if (!list_empty(&ctx->schemes))
2253 			kdamond_apply_schemes(ctx);
2254 		else
2255 			damos_walk_cancel(ctx);
2256 
2257 		sample_interval = ctx->attrs.sample_interval ?
2258 			ctx->attrs.sample_interval : 1;
2259 		if (ctx->passed_sample_intervals >= next_aggregation_sis) {
2260 			ctx->next_aggregation_sis = next_aggregation_sis +
2261 				ctx->attrs.aggr_interval / sample_interval;
2262 
2263 			kdamond_reset_aggregated(ctx);
2264 			kdamond_split_regions(ctx);
2265 			if (ctx->ops.reset_aggregated)
2266 				ctx->ops.reset_aggregated(ctx);
2267 		}
2268 
2269 		if (ctx->passed_sample_intervals >= next_ops_update_sis) {
2270 			ctx->next_ops_update_sis = next_ops_update_sis +
2271 				ctx->attrs.ops_update_interval /
2272 				sample_interval;
2273 			if (ctx->ops.update)
2274 				ctx->ops.update(ctx);
2275 			sz_limit = damon_region_sz_limit(ctx);
2276 		}
2277 	}
2278 done:
2279 	damon_for_each_target(t, ctx) {
2280 		damon_for_each_region_safe(r, next, t)
2281 			damon_destroy_region(r, t);
2282 	}
2283 
2284 	if (ctx->callback.before_terminate)
2285 		ctx->callback.before_terminate(ctx);
2286 	if (ctx->ops.cleanup)
2287 		ctx->ops.cleanup(ctx);
2288 	kfree(ctx->regions_score_histogram);
2289 
2290 	pr_debug("kdamond (%d) finishes\n", current->pid);
2291 	mutex_lock(&ctx->kdamond_lock);
2292 	ctx->kdamond = NULL;
2293 	mutex_unlock(&ctx->kdamond_lock);
2294 
2295 	kdamond_call(ctx, true);
2296 	damos_walk_cancel(ctx);
2297 
2298 	mutex_lock(&damon_lock);
2299 	nr_running_ctxs--;
2300 	if (!nr_running_ctxs && running_exclusive_ctxs)
2301 		running_exclusive_ctxs = false;
2302 	mutex_unlock(&damon_lock);
2303 
2304 	return 0;
2305 }
2306 
2307 /*
2308  * struct damon_system_ram_region - System RAM resource address region of
2309  *				    [@start, @end).
2310  * @start:	Start address of the region (inclusive).
2311  * @end:	End address of the region (exclusive).
2312  */
2313 struct damon_system_ram_region {
2314 	unsigned long start;
2315 	unsigned long end;
2316 };
2317 
2318 static int walk_system_ram(struct resource *res, void *arg)
2319 {
2320 	struct damon_system_ram_region *a = arg;
2321 
2322 	if (a->end - a->start < resource_size(res)) {
2323 		a->start = res->start;
2324 		a->end = res->end;
2325 	}
2326 	return 0;
2327 }
2328 
2329 /*
2330  * Find biggest 'System RAM' resource and store its start and end address in
2331  * @start and @end, respectively.  If no System RAM is found, returns false.
2332  */
2333 static bool damon_find_biggest_system_ram(unsigned long *start,
2334 						unsigned long *end)
2335 
2336 {
2337 	struct damon_system_ram_region arg = {};
2338 
2339 	walk_system_ram_res(0, ULONG_MAX, &arg, walk_system_ram);
2340 	if (arg.end <= arg.start)
2341 		return false;
2342 
2343 	*start = arg.start;
2344 	*end = arg.end;
2345 	return true;
2346 }
2347 
2348 /**
2349  * damon_set_region_biggest_system_ram_default() - Set the region of the given
2350  * monitoring target as requested, or biggest 'System RAM'.
2351  * @t:		The monitoring target to set the region.
2352  * @start:	The pointer to the start address of the region.
2353  * @end:	The pointer to the end address of the region.
2354  *
2355  * This function sets the region of @t as requested by @start and @end.  If the
2356  * values of @start and @end are zero, however, this function finds the biggest
2357  * 'System RAM' resource and sets the region to cover the resource.  In the
2358  * latter case, this function saves the start and end addresses of the resource
2359  * in @start and @end, respectively.
2360  *
2361  * Return: 0 on success, negative error code otherwise.
2362  */
2363 int damon_set_region_biggest_system_ram_default(struct damon_target *t,
2364 			unsigned long *start, unsigned long *end)
2365 {
2366 	struct damon_addr_range addr_range;
2367 
2368 	if (*start > *end)
2369 		return -EINVAL;
2370 
2371 	if (!*start && !*end &&
2372 		!damon_find_biggest_system_ram(start, end))
2373 		return -EINVAL;
2374 
2375 	addr_range.start = *start;
2376 	addr_range.end = *end;
2377 	return damon_set_regions(t, &addr_range, 1);
2378 }
2379 
2380 /*
2381  * damon_moving_sum() - Calculate an inferred moving sum value.
2382  * @mvsum:	Inferred sum of the last @len_window values.
2383  * @nomvsum:	Non-moving sum of the last discrete @len_window window values.
2384  * @len_window:	The number of last values to take care of.
2385  * @new_value:	New value that will be added to the pseudo moving sum.
2386  *
2387  * Moving sum (moving average * window size) is good for handling noise, but
2388  * the cost of keeping past values can be high for arbitrary window size.  This
2389  * function implements a lightweight pseudo moving sum function that doesn't
2390  * keep the past window values.
2391  *
2392  * It simply assumes there was no noise in the past, and get the no-noise
2393  * assumed past value to drop from @nomvsum and @len_window.  @nomvsum is a
2394  * non-moving sum of the last window.  For example, if @len_window is 10 and we
2395  * have 25 values, @nomvsum is the sum of the 11th to 20th values of the 25
2396  * values.  Hence, this function simply drops @nomvsum / @len_window from
2397  * given @mvsum and add @new_value.
2398  *
2399  * For example, if @len_window is 10 and @nomvsum is 50, the last 10 values for
2400  * the last window could be vary, e.g., 0, 10, 0, 10, 0, 10, 0, 0, 0, 20.  For
2401  * calculating next moving sum with a new value, we should drop 0 from 50 and
2402  * add the new value.  However, this function assumes it got value 5 for each
2403  * of the last ten times.  Based on the assumption, when the next value is
2404  * measured, it drops the assumed past value, 5 from the current sum, and add
2405  * the new value to get the updated pseduo-moving average.
2406  *
2407  * This means the value could have errors, but the errors will be disappeared
2408  * for every @len_window aligned calls.  For example, if @len_window is 10, the
2409  * pseudo moving sum with 11th value to 19th value would have an error.  But
2410  * the sum with 20th value will not have the error.
2411  *
2412  * Return: Pseudo-moving average after getting the @new_value.
2413  */
2414 static unsigned int damon_moving_sum(unsigned int mvsum, unsigned int nomvsum,
2415 		unsigned int len_window, unsigned int new_value)
2416 {
2417 	return mvsum - nomvsum / len_window + new_value;
2418 }
2419 
2420 /**
2421  * damon_update_region_access_rate() - Update the access rate of a region.
2422  * @r:		The DAMON region to update for its access check result.
2423  * @accessed:	Whether the region has accessed during last sampling interval.
2424  * @attrs:	The damon_attrs of the DAMON context.
2425  *
2426  * Update the access rate of a region with the region's last sampling interval
2427  * access check result.
2428  *
2429  * Usually this will be called by &damon_operations->check_accesses callback.
2430  */
2431 void damon_update_region_access_rate(struct damon_region *r, bool accessed,
2432 		struct damon_attrs *attrs)
2433 {
2434 	unsigned int len_window = 1;
2435 
2436 	/*
2437 	 * sample_interval can be zero, but cannot be larger than
2438 	 * aggr_interval, owing to validation of damon_set_attrs().
2439 	 */
2440 	if (attrs->sample_interval)
2441 		len_window = damon_max_nr_accesses(attrs);
2442 	r->nr_accesses_bp = damon_moving_sum(r->nr_accesses_bp,
2443 			r->last_nr_accesses * 10000, len_window,
2444 			accessed ? 10000 : 0);
2445 
2446 	if (accessed)
2447 		r->nr_accesses++;
2448 }
2449 
2450 static int __init damon_init(void)
2451 {
2452 	damon_region_cache = KMEM_CACHE(damon_region, 0);
2453 	if (unlikely(!damon_region_cache)) {
2454 		pr_err("creating damon_region_cache fails\n");
2455 		return -ENOMEM;
2456 	}
2457 
2458 	return 0;
2459 }
2460 
2461 subsys_initcall(damon_init);
2462 
2463 #include "tests/core-kunit.h"
2464