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