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