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