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