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