xref: /linux/mm/damon/core.c (revision d866d5bafc5e1417032255002e95f8ec3121754b)
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_objs(*dst->node_id_arr,
1520 						src->nr_dests);
1521 		if (!dst->node_id_arr) {
1522 			dst->weight_arr = NULL;
1523 			return -ENOMEM;
1524 		}
1525 
1526 		dst->weight_arr = kmalloc_objs(*dst->weight_arr, src->nr_dests);
1527 		if (!dst->weight_arr) {
1528 			/* ->node_id_arr will be freed by scheme destruction */
1529 			return -ENOMEM;
1530 		}
1531 	}
1532 
1533 	dst->nr_dests = src->nr_dests;
1534 	for (int i = 0; i < src->nr_dests; i++) {
1535 		dst->node_id_arr[i] = src->node_id_arr[i];
1536 		dst->weight_arr[i] = src->weight_arr[i];
1537 	}
1538 
1539 	return 0;
1540 }
1541 
1542 static int damos_commit_filters(struct damos *dst, struct damos *src)
1543 {
1544 	int err;
1545 
1546 	err = damos_commit_core_filters(dst, src);
1547 	if (err)
1548 		return err;
1549 	err = damos_commit_ops_filters(dst, src);
1550 	if (err)
1551 		return err;
1552 	damos_set_filters_default_reject(dst);
1553 	return 0;
1554 }
1555 
1556 static struct damos *damon_nth_scheme(int n, struct damon_ctx *ctx)
1557 {
1558 	struct damos *s;
1559 	int i = 0;
1560 
1561 	damon_for_each_scheme(s, ctx) {
1562 		if (i++ == n)
1563 			return s;
1564 	}
1565 	return NULL;
1566 }
1567 
1568 static int damos_commit(struct damos *dst, struct damos *src)
1569 {
1570 	int err;
1571 
1572 	dst->pattern = src->pattern;
1573 	dst->action = src->action;
1574 	dst->apply_interval_us = src->apply_interval_us;
1575 
1576 	err = damos_commit_quota(&dst->quota, &src->quota);
1577 	if (err)
1578 		return err;
1579 
1580 	dst->wmarks = src->wmarks;
1581 	dst->target_nid = src->target_nid;
1582 
1583 	err = damos_commit_dests(&dst->migrate_dests, &src->migrate_dests);
1584 	if (err)
1585 		return err;
1586 
1587 	err = damos_commit_filters(dst, src);
1588 	if (err)
1589 		return err;
1590 
1591 	dst->max_nr_snapshots = src->max_nr_snapshots;
1592 	return 0;
1593 }
1594 
1595 static int damon_commit_schemes(struct damon_ctx *dst, struct damon_ctx *src)
1596 {
1597 	struct damos *dst_scheme, *next, *src_scheme, *new_scheme;
1598 	int i = 0, j = 0, err;
1599 
1600 	damon_for_each_scheme_safe(dst_scheme, next, dst) {
1601 		src_scheme = damon_nth_scheme(i++, src);
1602 		if (src_scheme) {
1603 			err = damos_commit(dst_scheme, src_scheme);
1604 			if (err)
1605 				return err;
1606 		} else {
1607 			damon_destroy_scheme(dst_scheme);
1608 		}
1609 	}
1610 
1611 	damon_for_each_scheme_safe(src_scheme, next, src) {
1612 		if (j++ < i)
1613 			continue;
1614 		new_scheme = damon_new_scheme(&src_scheme->pattern,
1615 				src_scheme->action,
1616 				src_scheme->apply_interval_us,
1617 				&src_scheme->quota, &src_scheme->wmarks,
1618 				NUMA_NO_NODE);
1619 		if (!new_scheme)
1620 			return -ENOMEM;
1621 		err = damos_commit(new_scheme, src_scheme);
1622 		if (err) {
1623 			damon_destroy_scheme(new_scheme);
1624 			return err;
1625 		}
1626 		damon_add_scheme(dst, new_scheme);
1627 	}
1628 	return 0;
1629 }
1630 
1631 static struct damon_target *damon_nth_target(int n, struct damon_ctx *ctx)
1632 {
1633 	struct damon_target *t;
1634 	int i = 0;
1635 
1636 	damon_for_each_target(t, ctx) {
1637 		if (i++ == n)
1638 			return t;
1639 	}
1640 	return NULL;
1641 }
1642 
1643 /*
1644  * The caller should ensure the regions of @src are
1645  * 1. valid (end >= src) and
1646  * 2. sorted by starting address.
1647  *
1648  * If @src has no region, @dst keeps current regions.
1649  */
1650 static int damon_commit_target_regions(struct damon_target *dst,
1651 		struct damon_target *src, unsigned long src_min_region_sz)
1652 {
1653 	struct damon_region *src_region, *prev = NULL;
1654 	struct damon_addr_range *ranges;
1655 	int i = 0, err;
1656 
1657 	damon_for_each_region(src_region, src) {
1658 		if (!prev || prev->ar.end != src_region->ar.start)
1659 			i++;
1660 		prev = src_region;
1661 	}
1662 	if (!i)
1663 		return 0;
1664 
1665 	ranges = kvmalloc_objs(*ranges, i, GFP_KERNEL | __GFP_NOWARN);
1666 	if (!ranges)
1667 		return -ENOMEM;
1668 	prev = NULL;
1669 	i = 0;
1670 	damon_for_each_region(src_region, src) {
1671 		if (!prev) {
1672 			ranges[i].start = src_region->ar.start;
1673 		} else if (prev->ar.end != src_region->ar.start) {
1674 			ranges[i++].end = prev->ar.end;
1675 			ranges[i].start = src_region->ar.start;
1676 		}
1677 		prev = src_region;
1678 	}
1679 	ranges[i++].end = damon_last_region(src)->ar.end;
1680 	err = damon_set_regions(dst, ranges, i, src_min_region_sz);
1681 	kvfree(ranges);
1682 	return err;
1683 }
1684 
1685 static int damon_commit_target(
1686 		struct damon_target *dst, bool dst_has_pid,
1687 		struct damon_target *src, bool src_has_pid,
1688 		unsigned long src_min_region_sz)
1689 {
1690 	int err;
1691 
1692 	err = damon_commit_target_regions(dst, src, src_min_region_sz);
1693 	if (err)
1694 		return err;
1695 	if (dst_has_pid)
1696 		put_pid(dst->pid);
1697 	if (src_has_pid)
1698 		get_pid(src->pid);
1699 	dst->pid = src->pid;
1700 	return 0;
1701 }
1702 
1703 /*
1704  * damon_revert_target_commits() - revert unsuccessful target commits.
1705  * @dst:	Commit destination context
1706  * @failed:	Commit failed destination target
1707  * @src:	Commit source context
1708  *
1709  * Revert target states that changed by damon_commit_target(), and cannot be
1710  * cleaned up by the destination context's ops.cleanup_target().
1711  */
1712 static void damon_revert_target_commits(struct damon_ctx *dst,
1713 		struct damon_target *failed, struct damon_ctx *src)
1714 {
1715 	struct damon_target *target;
1716 
1717 	if (!damon_target_has_pid(src))
1718 		return;
1719 	if (dst->ops.cleanup_target)
1720 		return;
1721 	damon_for_each_target(target, dst) {
1722 		if (target == failed)
1723 			return;
1724 		put_pid(target->pid);
1725 	}
1726 }
1727 
1728 static int damon_commit_targets(
1729 		struct damon_ctx *dst, struct damon_ctx *src)
1730 {
1731 	struct damon_target *dst_target, *next, *src_target, *new_target;
1732 	struct damon_target *failed;
1733 	int i = 0, j = 0, err;
1734 
1735 	damon_for_each_target_safe(dst_target, next, dst) {
1736 		src_target = damon_nth_target(i++, src);
1737 		/*
1738 		 * If src target is obsolete, do not commit the parameters to
1739 		 * the dst target, and further remove the dst target.
1740 		 */
1741 		if (src_target && !src_target->obsolete) {
1742 			err = damon_commit_target(
1743 					dst_target, damon_target_has_pid(dst),
1744 					src_target, damon_target_has_pid(src),
1745 					src->min_region_sz);
1746 			if (err) {
1747 				failed = dst_target;
1748 				goto out;
1749 			}
1750 		} else {
1751 			struct damos *s;
1752 
1753 			damon_destroy_target(dst_target, dst);
1754 			damon_for_each_scheme(s, dst) {
1755 				if (s->quota.charge_target_from == dst_target) {
1756 					s->quota.charge_target_from = NULL;
1757 					s->quota.charge_addr_from = 0;
1758 				}
1759 			}
1760 		}
1761 	}
1762 
1763 	failed = NULL;
1764 	damon_for_each_target_safe(src_target, next, src) {
1765 		if (j++ < i)
1766 			continue;
1767 		/* target to remove has no matching dst */
1768 		if (src_target->obsolete) {
1769 			err = -EINVAL;
1770 			goto out;
1771 		}
1772 		new_target = damon_new_target();
1773 		if (!new_target) {
1774 			err = -ENOMEM;
1775 			goto out;
1776 		}
1777 		err = damon_commit_target(new_target, false,
1778 				src_target, damon_target_has_pid(src),
1779 				src->min_region_sz);
1780 		if (err) {
1781 			damon_destroy_target(new_target, NULL);
1782 			goto out;
1783 		}
1784 		damon_add_target(dst, new_target);
1785 	}
1786 	return 0;
1787 
1788 out:
1789 	damon_revert_target_commits(dst, failed, src);
1790 	return err;
1791 }
1792 
1793 static void damon_commit_prep(struct damon_prep *dst, struct damon_prep *src)
1794 {
1795 	dst->action = src->action;
1796 }
1797 
1798 static int damon_commit_preps(struct damon_probe *dst, struct damon_probe *src)
1799 {
1800 	struct damon_prep *dst_prep, *next, *src_prep, *new_prep;
1801 	int i = 0, j = 0;
1802 
1803 	damon_for_each_prep_safe(dst_prep, next, dst) {
1804 		src_prep = damon_nth_prep(i++, src);
1805 		if (src_prep)
1806 			damon_commit_prep(dst_prep, src_prep);
1807 		else
1808 			damon_destroy_prep(dst_prep);
1809 	}
1810 
1811 	damon_for_each_prep_safe(src_prep, next, src) {
1812 		if (j++ < i)
1813 			continue;
1814 
1815 		new_prep = damon_new_prep(src_prep->action);
1816 		if (!new_prep)
1817 			return -ENOMEM;
1818 		damon_add_prep(dst, new_prep);
1819 	}
1820 	return 0;
1821 }
1822 
1823 static int damon_commit_filter(struct damon_filter *dst,
1824 		struct damon_filter *src)
1825 {
1826 	dst->type = src->type;
1827 	dst->matching = src->matching;
1828 	dst->allow = src->allow;
1829 	switch (dst->type) {
1830 	case DAMON_FILTER_TYPE_MEMCG:
1831 		dst->memcg_id = src->memcg_id;
1832 		break;
1833 	case DAMON_FILTER_TYPE_HUGEPAGE_SIZE:
1834 		if (src->range_max < src->range_min)
1835 			return -EINVAL;
1836 		dst->range_min = src->range_min;
1837 		dst->range_max = src->range_max;
1838 		break;
1839 	default:
1840 		break;
1841 	}
1842 	return 0;
1843 }
1844 
1845 static int damon_commit_filters(struct damon_probe *dst,
1846 		struct damon_probe *src)
1847 {
1848 	struct damon_filter *dst_filter, *next, *src_filter, *new_filter;
1849 	int i = 0, j = 0, err;
1850 
1851 	damon_for_each_filter_safe(dst_filter, next, dst) {
1852 		src_filter = damon_nth_filter(i++, src);
1853 		if (src_filter) {
1854 			err = damon_commit_filter(dst_filter, src_filter);
1855 			if (err)
1856 				return err;
1857 		} else {
1858 			damon_destroy_filter(dst_filter);
1859 		}
1860 	}
1861 
1862 	damon_for_each_filter_safe(src_filter, next, src) {
1863 		if (j++ < i)
1864 			continue;
1865 
1866 		new_filter = damon_new_filter(src_filter->type,
1867 				src_filter->matching, src_filter->allow);
1868 		if (!new_filter)
1869 			return -ENOMEM;
1870 		switch (src_filter->type) {
1871 		case DAMON_FILTER_TYPE_MEMCG:
1872 			new_filter->memcg_id = src_filter->memcg_id;
1873 			break;
1874 		case DAMON_FILTER_TYPE_HUGEPAGE_SIZE:
1875 			if (src_filter->range_max < src_filter->range_min) {
1876 				damon_destroy_filter(new_filter);
1877 				return -EINVAL;
1878 			}
1879 			new_filter->range_min = src_filter->range_min;
1880 			new_filter->range_max = src_filter->range_max;
1881 			break;
1882 		default:
1883 			break;
1884 		}
1885 		damon_add_filter(dst, new_filter);
1886 	}
1887 	return 0;
1888 }
1889 
1890 static int damon_commit_probes(struct damon_ctx *dst, struct damon_ctx *src)
1891 {
1892 	struct damon_probe *dst_probe, *next, *src_probe, *new_probe;
1893 	int i = 0, j = 0, err;
1894 
1895 	damon_for_each_probe_safe(dst_probe, next, dst) {
1896 		src_probe = damon_nth_probe(i++, src);
1897 		if (src_probe) {
1898 			dst_probe->weight = src_probe->weight;
1899 			err = damon_commit_preps(dst_probe, src_probe);
1900 			if (err)
1901 				return err;
1902 			err = damon_commit_filters(dst_probe, src_probe);
1903 			if (err)
1904 				return err;
1905 		} else {
1906 			damon_destroy_probe(dst_probe);
1907 		}
1908 	}
1909 
1910 	damon_for_each_probe_safe(src_probe, next, src) {
1911 		if (j++ < i)
1912 			continue;
1913 
1914 		new_probe = damon_new_probe();
1915 		if (!new_probe)
1916 			return -ENOMEM;
1917 		damon_add_probe(dst, new_probe);
1918 		new_probe->weight = src_probe->weight;
1919 		err = damon_commit_preps(new_probe, src_probe);
1920 		if (err)
1921 			return err;
1922 		err = damon_commit_filters(new_probe, src_probe);
1923 		if (err)
1924 			return err;
1925 	}
1926 	return 0;
1927 }
1928 
1929 static int __damon_commit_ctx(struct damon_ctx *dst, struct damon_ctx *src)
1930 {
1931 	int err;
1932 	struct damos *scheme;
1933 	struct damos_quota_goal *goal;
1934 
1935 	dst->maybe_corrupted = true;
1936 	if (!is_power_of_2(src->min_region_sz))
1937 		return -EINVAL;
1938 
1939 	/* node_eligible_mem_bp metric requires PADDR ops */
1940 	if (src->ops.id != DAMON_OPS_PADDR) {
1941 		damon_for_each_scheme(scheme, src) {
1942 			struct damos_quota *quota = &scheme->quota;
1943 
1944 			damos_for_each_quota_goal(goal, quota) {
1945 				if (goal->metric ==
1946 						DAMOS_QUOTA_NODE_ELIGIBLE_MEM_BP)
1947 					return -EINVAL;
1948 			}
1949 		}
1950 	}
1951 
1952 	if (!damon_valid_probe_params(src))
1953 		return -EINVAL;
1954 
1955 	err = damon_commit_schemes(dst, src);
1956 	if (err)
1957 		return err;
1958 	err = damon_commit_targets(dst, src);
1959 	if (err)
1960 		return err;
1961 	/*
1962 	 * schemes and targets should be updated first, since
1963 	 * 1. damon_set_attrs() updates monitoring results of targets and
1964 	 * next_apply_sis of schemes, and
1965 	 * 2. ops update should be done after pid handling is done (target
1966 	 *    committing require putting pids).
1967 	 */
1968 	if (!damon_attrs_equals(&dst->attrs, &src->attrs)) {
1969 		err = damon_set_attrs(dst, &src->attrs);
1970 		if (err) {
1971 			damon_revert_target_commits(dst, NULL, src);
1972 			return err;
1973 		}
1974 	}
1975 	dst->pause = src->pause;
1976 	dst->ops = src->ops;
1977 	err = damon_commit_probes(dst, src);
1978 	if (err)
1979 		return err;
1980 	dst->addr_unit = src->addr_unit;
1981 	dst->min_region_sz = src->min_region_sz;
1982 
1983 	dst->maybe_corrupted = false;
1984 	return 0;
1985 }
1986 
1987 static struct damon_ctx *damon_new_test_ctx(struct damon_ctx *dst)
1988 {
1989 	struct damon_ctx *test_ctx;
1990 	int err;
1991 
1992 	test_ctx = damon_new_ctx();
1993 	if (!test_ctx)
1994 		return NULL;
1995 	err = __damon_commit_ctx(test_ctx, dst);
1996 	if (err) {
1997 		damon_destroy_ctx(test_ctx);
1998 		return NULL;
1999 	}
2000 	return test_ctx;
2001 }
2002 
2003 /**
2004  * damon_commit_ctx() - Commit parameters of a DAMON context to another.
2005  * @dst:	The commit destination DAMON context.
2006  * @src:	The commit source DAMON context.
2007  *
2008  * This function copies user-specified parameters from @src to @dst and update
2009  * the internal status and results accordingly.  Users should use this function
2010  * for context-level parameters update of running context, instead of manual
2011  * in-place updates.
2012  *
2013  * This function should be called from parameters-update safe context, like
2014  * damon_call().
2015  */
2016 int damon_commit_ctx(struct damon_ctx *dst, struct damon_ctx *src)
2017 {
2018 	struct damon_ctx *test_ctx;
2019 	int err;
2020 
2021 	test_ctx = damon_new_test_ctx(dst);
2022 	if (!test_ctx)
2023 		return -ENOMEM;
2024 	err = __damon_commit_ctx(test_ctx, src);
2025 	if (err)
2026 		goto out;
2027 	err = __damon_commit_ctx(dst, src);
2028 out:
2029 	damon_destroy_ctx(test_ctx);
2030 	return err;
2031 }
2032 
2033 /* Returns the size upper limit for each monitoring region */
2034 static unsigned long damon_region_sz_limit(struct damon_ctx *ctx)
2035 {
2036 	struct damon_target *t;
2037 	struct damon_region *r;
2038 	unsigned long sz = 0;
2039 
2040 	damon_for_each_target(t, ctx) {
2041 		damon_for_each_region(r, t)
2042 			sz += damon_sz_region(r);
2043 	}
2044 
2045 	if (ctx->attrs.min_nr_regions)
2046 		sz /= ctx->attrs.min_nr_regions;
2047 	if (sz < ctx->min_region_sz)
2048 		sz = ctx->min_region_sz;
2049 
2050 	return sz;
2051 }
2052 
2053 static int damon_split_region_at(struct damon_target *t,
2054 				  struct damon_region *r, unsigned long sz_r);
2055 
2056 /*
2057  * damon_apply_min_nr_regions() - Make effect of min_nr_regions parameter.
2058  * @ctx:	monitoring context.
2059  *
2060  * This function implement min_nr_regions (minimum number of damon_region
2061  * objects in the given monitoring context) behavior.  It first calculates
2062  * maximum size of each region for enforcing the min_nr_regions as total size
2063  * of the regions divided by the min_nr_regions.  After that, this function
2064  * splits regions to ensure all regions are equal to or smaller than the size
2065  * limit.  Finally, this function returns the maximum size limit.
2066  *
2067  * Returns: maximum size of each region for convincing min_nr_regions.
2068  */
2069 static unsigned long damon_apply_min_nr_regions(struct damon_ctx *ctx)
2070 {
2071 	unsigned long max_region_sz = damon_region_sz_limit(ctx);
2072 	struct damon_target *t;
2073 	struct damon_region *r, *next;
2074 
2075 	max_region_sz = ALIGN(max_region_sz, ctx->min_region_sz);
2076 	damon_for_each_target(t, ctx) {
2077 		damon_for_each_region_safe(r, next, t) {
2078 			while (damon_sz_region(r) > max_region_sz) {
2079 				if (damon_split_region_at(t, r, max_region_sz))
2080 					goto out;
2081 				r = damon_next_region(r);
2082 			}
2083 		}
2084 	}
2085 out:
2086 	return max_region_sz;
2087 }
2088 
2089 static int kdamond_fn(void *data);
2090 
2091 /*
2092  * __damon_start() - Starts monitoring with given context.
2093  * @ctx:	monitoring context
2094  *
2095  * This function should be called while damon_lock is hold.
2096  *
2097  * Return: 0 on success, negative error code otherwise.
2098  */
2099 static int __damon_start(struct damon_ctx *ctx)
2100 {
2101 	int err = -EBUSY;
2102 
2103 	mutex_lock(&ctx->kdamond_lock);
2104 	if (!ctx->kdamond) {
2105 		err = 0;
2106 		reinit_completion(&ctx->kdamond_started);
2107 		ctx->kdamond = kthread_run(kdamond_fn, ctx, "kdamond.%d",
2108 				nr_running_ctxs);
2109 		if (IS_ERR(ctx->kdamond)) {
2110 			err = PTR_ERR(ctx->kdamond);
2111 			ctx->kdamond = NULL;
2112 		} else {
2113 			wait_for_completion(&ctx->kdamond_started);
2114 		}
2115 	}
2116 	mutex_unlock(&ctx->kdamond_lock);
2117 
2118 	return err;
2119 }
2120 
2121 /**
2122  * damon_start() - Starts the monitorings for a given group of contexts.
2123  * @ctxs:	an array of the pointers for contexts to start monitoring
2124  * @nr_ctxs:	size of @ctxs
2125  * @exclusive:	exclusiveness of this contexts group
2126  *
2127  * This function starts a group of monitoring threads for a group of monitoring
2128  * contexts.  One thread per each context is created and run in parallel.  The
2129  * caller should handle synchronization between the threads by itself.  If
2130  * @exclusive is true and a group of threads that created by other
2131  * 'damon_start()' call is currently running, this function does nothing but
2132  * returns -EBUSY.
2133  *
2134  * Return: 0 on success, negative error code otherwise.
2135  */
2136 int damon_start(struct damon_ctx **ctxs, int nr_ctxs, bool exclusive)
2137 {
2138 	int i;
2139 	int err = 0;
2140 
2141 	for (i = 0; i < nr_ctxs; i++) {
2142 		struct damon_ctx *test_ctx;
2143 
2144 		test_ctx = damon_new_ctx();
2145 		if (!test_ctx)
2146 			return -ENOMEM;
2147 
2148 		err = __damon_commit_ctx(test_ctx, ctxs[i]);
2149 		damon_destroy_ctx(test_ctx);
2150 		if (err)
2151 			return err;
2152 	}
2153 
2154 	mutex_lock(&damon_lock);
2155 	if ((exclusive && nr_running_ctxs) ||
2156 			(!exclusive && running_exclusive_ctxs)) {
2157 		mutex_unlock(&damon_lock);
2158 		return -EBUSY;
2159 	}
2160 
2161 	for (i = 0; i < nr_ctxs; i++) {
2162 		err = __damon_start(ctxs[i]);
2163 		if (err)
2164 			break;
2165 		nr_running_ctxs++;
2166 	}
2167 	if (exclusive && nr_running_ctxs)
2168 		running_exclusive_ctxs = true;
2169 	mutex_unlock(&damon_lock);
2170 
2171 	if (i != nr_ctxs)
2172 		damon_stop(ctxs, i);
2173 
2174 	return err;
2175 }
2176 
2177 /*
2178  * __damon_stop() - Stops monitoring of a given context.
2179  * @ctx:	monitoring context
2180  */
2181 static void __damon_stop(struct damon_ctx *ctx)
2182 {
2183 	struct task_struct *tsk;
2184 
2185 	mutex_lock(&ctx->kdamond_lock);
2186 	tsk = ctx->kdamond;
2187 	if (tsk) {
2188 		get_task_struct(tsk);
2189 		mutex_unlock(&ctx->kdamond_lock);
2190 		kthread_stop_put(tsk);
2191 		return;
2192 	}
2193 	mutex_unlock(&ctx->kdamond_lock);
2194 }
2195 
2196 /**
2197  * damon_stop() - Stops the monitorings for a given group of contexts.
2198  * @ctxs:	an array of the pointers for contexts to stop monitoring
2199  * @nr_ctxs:	size of @ctxs
2200  */
2201 void damon_stop(struct damon_ctx **ctxs, int nr_ctxs)
2202 {
2203 	int i;
2204 
2205 	for (i = 0; i < nr_ctxs; i++)
2206 		/* nr_running_ctxs is decremented in kdamond_fn */
2207 		__damon_stop(ctxs[i]);
2208 }
2209 
2210 /**
2211  * damon_is_running() - Returns if a given DAMON context is running.
2212  * @ctx:	The DAMON context to see if running.
2213  *
2214  * Return: true if @ctx is running, false otherwise.
2215  */
2216 bool damon_is_running(struct damon_ctx *ctx)
2217 {
2218 	bool running;
2219 
2220 	mutex_lock(&ctx->kdamond_lock);
2221 	running = ctx->kdamond != NULL;
2222 	mutex_unlock(&ctx->kdamond_lock);
2223 	return running;
2224 }
2225 
2226 /**
2227  * damon_kdamond_pid() - Return pid of a given DAMON context's worker thread.
2228  * @ctx:	The DAMON context of the question.
2229  *
2230  * Return: pid if @ctx is running, negative error code otherwise.
2231  */
2232 int damon_kdamond_pid(struct damon_ctx *ctx)
2233 {
2234 	int pid = -EINVAL;
2235 
2236 	mutex_lock(&ctx->kdamond_lock);
2237 	if (ctx->kdamond)
2238 		pid = ctx->kdamond->pid;
2239 	mutex_unlock(&ctx->kdamond_lock);
2240 	return pid;
2241 }
2242 
2243 /**
2244  * damon_call() - Invoke a given function on DAMON worker thread (kdamond).
2245  * @ctx:	DAMON context to call the function for.
2246  * @control:	Control variable of the call request.
2247  *
2248  * Ask DAMON worker thread (kdamond) of @ctx to call a function with an
2249  * argument data that respectively passed via &damon_call_control->fn and
2250  * &damon_call_control->data of @control.  If &damon_call_control->repeat of
2251  * @control is unset, further wait until the kdamond finishes handling of the
2252  * request.  Otherwise, return as soon as the request is made.
2253  *
2254  * The kdamond executes the function with the argument in the main loop, just
2255  * after a sampling of the iteration is finished.  The function can hence
2256  * safely access the internal data of the &struct damon_ctx without additional
2257  * synchronization.  The return value of the function will be saved in
2258  * &damon_call_control->return_code.
2259  *
2260  * When this function is failed, the @ctx is guaranteed to be stopped.
2261  *
2262  * This function should not be called in parallel to damon_start() for the
2263  * @ctx.  In the case, this function could indefinitely hang.
2264  *
2265  * Return: 0 on success, negative error code otherwise.
2266  */
2267 int damon_call(struct damon_ctx *ctx, struct damon_call_control *control)
2268 {
2269 	if (!ctx)
2270 		return -EINVAL;
2271 	if (!control->repeat)
2272 		init_completion(&control->completion);
2273 	control->canceled = false;
2274 	INIT_LIST_HEAD(&control->list);
2275 
2276 	mutex_lock(&ctx->call_controls_lock);
2277 	if (ctx->call_controls_obsolete) {
2278 		mutex_unlock(&ctx->call_controls_lock);
2279 		goto canceled;
2280 	}
2281 	list_add_tail(&control->list, &ctx->call_controls);
2282 	mutex_unlock(&ctx->call_controls_lock);
2283 	if (control->repeat)
2284 		return 0;
2285 	wait_for_completion(&control->completion);
2286 	if (control->canceled)
2287 		goto canceled;
2288 	return 0;
2289 
2290 canceled:
2291 	while (damon_is_running(ctx))
2292 		schedule_timeout_idle(msecs_to_jiffies(100));
2293 	return -ECANCELED;
2294 
2295 }
2296 
2297 /**
2298  * damos_walk() - Invoke a given functions while DAMOS walk regions.
2299  * @ctx:	DAMON context to call the functions for.
2300  * @control:	Control variable of the walk request.
2301  *
2302  * Ask DAMON worker thread (kdamond) of @ctx to call a function for each region
2303  * that the kdamond will apply DAMOS action to, and wait until the kdamond
2304  * finishes handling of the request.
2305  *
2306  * The kdamond executes the given function in the main loop, for each region
2307  * just after it applied any DAMOS actions of @ctx to it.  The invocation is
2308  * made only within one &damos->apply_interval_us since damos_walk()
2309  * invocation, for each scheme.  The given callback function can hence safely
2310  * access the internal data of &struct damon_ctx and &struct damon_region that
2311  * each of the scheme will apply the action for next interval, without
2312  * additional synchronizations against the kdamond.  If every scheme of @ctx
2313  * passed at least one &damos->apply_interval_us, kdamond marks the request as
2314  * completed so that damos_walk() can wakeup and return.
2315  *
2316  * Return: 0 on success, negative error code otherwise.
2317  */
2318 int damos_walk(struct damon_ctx *ctx, struct damos_walk_control *control)
2319 {
2320 	init_completion(&control->completion);
2321 	control->canceled = false;
2322 	mutex_lock(&ctx->walk_control_lock);
2323 	if (ctx->walk_control_obsolete) {
2324 		mutex_unlock(&ctx->walk_control_lock);
2325 		return -ECANCELED;
2326 	}
2327 	if (ctx->walk_control) {
2328 		mutex_unlock(&ctx->walk_control_lock);
2329 		return -EBUSY;
2330 	}
2331 	ctx->walk_control = control;
2332 	mutex_unlock(&ctx->walk_control_lock);
2333 	wait_for_completion(&control->completion);
2334 	if (control->canceled)
2335 		return -ECANCELED;
2336 	return 0;
2337 }
2338 
2339 /*
2340  * Reset the aggregated monitoring results ('nr_accesses' of each region).
2341  */
2342 static void kdamond_reset_aggregated(struct damon_ctx *c)
2343 {
2344 	struct damon_target *t;
2345 	unsigned int ti = 0;	/* target's index */
2346 	unsigned int nr_probes = 0;
2347 	struct damon_probe *probe;
2348 
2349 	if (trace_damon_region_aggregated_enabled()) {
2350 		damon_for_each_probe(probe, c)
2351 			nr_probes++;
2352 	}
2353 
2354 	damon_for_each_target(t, c) {
2355 		struct damon_region *r;
2356 
2357 		damon_for_each_region(r, t) {
2358 			int i;
2359 
2360 			trace_damon_aggregated(ti, r, damon_nr_regions(t));
2361 			trace_damon_region_aggregated(ti, r,
2362 					damon_nr_regions(t), nr_probes);
2363 			r->last_nr_accesses = r->nr_accesses;
2364 			r->nr_accesses = 0;
2365 			for (i = 0; i < DAMON_MAX_PROBES; i++) {
2366 				r->last_probe_hits[i] = r->probe_hits[i];
2367 				r->probe_hits[i] = 0;
2368 			}
2369 		}
2370 		ti++;
2371 	}
2372 }
2373 
2374 static unsigned long damon_get_intervals_score(struct damon_ctx *c)
2375 {
2376 	struct damon_target *t;
2377 	struct damon_region *r;
2378 	unsigned long sz_region, max_access_events = 0, access_events = 0;
2379 	unsigned long target_access_events;
2380 	unsigned long goal_bp = c->attrs.intervals_goal.access_bp;
2381 
2382 	damon_for_each_target(t, c) {
2383 		damon_for_each_region(r, t) {
2384 			sz_region = damon_sz_region(r);
2385 			max_access_events += sz_region * c->attrs.aggr_samples;
2386 			access_events += sz_region * r->nr_accesses;
2387 		}
2388 	}
2389 	target_access_events = max_access_events * goal_bp / 10000;
2390 	target_access_events = target_access_events ? : 1;
2391 	return mult_frac(access_events, 10000, target_access_events);
2392 }
2393 
2394 static unsigned long damon_feed_loop_next_input(unsigned long last_input,
2395 		unsigned long score);
2396 
2397 static unsigned long damon_get_intervals_adaptation_bp(struct damon_ctx *c)
2398 {
2399 	unsigned long score_bp, adaptation_bp;
2400 
2401 	score_bp = damon_get_intervals_score(c);
2402 	adaptation_bp = damon_feed_loop_next_input(100000000, score_bp) /
2403 		10000;
2404 	/*
2405 	 * adaptation_bp ranges from 1 to 20,000.  Avoid too rapid reduction of
2406 	 * the intervals by rescaling [1,10,000] to [5000, 10,000].
2407 	 */
2408 	if (adaptation_bp <= 10000)
2409 		adaptation_bp = 5000 + adaptation_bp / 2;
2410 	return adaptation_bp;
2411 }
2412 
2413 static noinline_for_stack void kdamond_tune_intervals(struct damon_ctx *c)
2414 {
2415 	unsigned long adaptation_bp;
2416 	struct damon_attrs new_attrs;
2417 	struct damon_intervals_goal *goal;
2418 
2419 	adaptation_bp = damon_get_intervals_adaptation_bp(c);
2420 	if (adaptation_bp == 10000)
2421 		return;
2422 
2423 	new_attrs = c->attrs;
2424 	goal = &c->attrs.intervals_goal;
2425 	new_attrs.sample_interval = min(goal->max_sample_us,
2426 			c->attrs.sample_interval * adaptation_bp / 10000);
2427 	new_attrs.sample_interval = max(goal->min_sample_us,
2428 			new_attrs.sample_interval);
2429 	new_attrs.aggr_interval = new_attrs.sample_interval *
2430 		c->attrs.aggr_samples;
2431 	trace_damon_monitor_intervals_tune(new_attrs.sample_interval);
2432 	damon_set_attrs(c, &new_attrs);
2433 }
2434 
2435 static bool __damos_valid_target(struct damon_region *r, struct damos *s,
2436 		struct damon_ctx *c)
2437 {
2438 	unsigned long sz;
2439 	unsigned int nr_accesses = damon_nr_accesses_mvsum(r, c);
2440 
2441 	sz = damon_sz_region(r);
2442 	return s->pattern.min_sz_region <= sz &&
2443 		sz <= s->pattern.max_sz_region &&
2444 		s->pattern.min_nr_accesses <= nr_accesses &&
2445 		nr_accesses <= s->pattern.max_nr_accesses &&
2446 		s->pattern.min_age_region <= r->age &&
2447 		r->age <= s->pattern.max_age_region;
2448 }
2449 
2450 /*
2451  * damos_quota_is_set() - Return if the given quota is actually set.
2452  * @quota:	The quota to check.
2453  *
2454  * Returns true if the quota is set, false otherwise.
2455  */
2456 static bool damos_quota_is_set(struct damos_quota *quota)
2457 {
2458 	return quota->esz || quota->sz || quota->ms ||
2459 		!damos_quota_goals_empty(quota);
2460 }
2461 
2462 static bool damos_valid_target(struct damon_ctx *c, struct damon_region *r,
2463 		struct damos *s)
2464 {
2465 	bool ret = __damos_valid_target(r, s, c);
2466 
2467 	if (!ret || !damos_quota_is_set(&s->quota) || !c->ops.get_scheme_score)
2468 		return ret;
2469 
2470 	return c->ops.get_scheme_score(c, r, s) >= s->quota.min_score;
2471 }
2472 
2473 /*
2474  * damos_skip_charged_region() - Check if the given region or starting part of
2475  * it is already charged for the DAMOS quota.
2476  * @t:	The target of the region.
2477  * @rp:	The pointer to the region.
2478  * @s:	The scheme to be applied.
2479  * @min_region_sz:	minimum region size.
2480  *
2481  * If a quota of a scheme has exceeded in a quota charge window, the scheme's
2482  * action would applied to only a part of the target access pattern fulfilling
2483  * regions.  To avoid applying the scheme action to only already applied
2484  * regions, DAMON skips applying the scheme action to the regions that charged
2485  * in the previous charge window.
2486  *
2487  * This function checks if a given region should be skipped or not for the
2488  * reason.  If only the starting part of the region has previously charged,
2489  * this function splits the region into two so that the second one covers the
2490  * area that not charged in the previous charge window, and return true.  The
2491  * caller can see the second one on the next iteration of the region walk.
2492  * Note that this means the caller should use damon_for_each_region() instead
2493  * of damon_for_each_region_safe().  If damon_for_each_region_safe() is used,
2494  * the second region will just be ignored.
2495  *
2496  * Return: true if the region should be skipped, false otherwise.
2497  */
2498 static bool damos_skip_charged_region(struct damon_target *t,
2499 		struct damon_region *r, struct damos *s,
2500 		unsigned long min_region_sz)
2501 {
2502 	struct damos_quota *quota = &s->quota;
2503 	unsigned long sz_to_skip;
2504 	bool skip = false;
2505 
2506 	/* Skip previously charged regions */
2507 	if (quota->charge_target_from) {
2508 		if (t != quota->charge_target_from)
2509 			return true;
2510 		if (quota->charge_addr_from &&
2511 				r->ar.end <= quota->charge_addr_from) {
2512 			skip = true;
2513 			goto out;
2514 		}
2515 
2516 		if (quota->charge_addr_from && r->ar.start <
2517 				quota->charge_addr_from) {
2518 			sz_to_skip = ALIGN_DOWN(quota->charge_addr_from -
2519 					r->ar.start, min_region_sz);
2520 			if (!sz_to_skip) {
2521 				if (damon_sz_region(r) <= min_region_sz) {
2522 					skip = true;
2523 					goto out;
2524 				}
2525 				sz_to_skip = min_region_sz;
2526 			}
2527 			damon_split_region_at(t, r, sz_to_skip);
2528 			skip = true;
2529 		}
2530 	}
2531 out:
2532 	if (r == damon_last_region(t)) {
2533 		quota->charge_target_from = NULL;
2534 		quota->charge_addr_from = 0;
2535 	}
2536 	return skip;
2537 }
2538 
2539 static void damos_update_stat(struct damos *s,
2540 		unsigned long sz_tried, unsigned long sz_applied,
2541 		unsigned long sz_ops_filter_passed)
2542 {
2543 	s->stat.nr_tried++;
2544 	s->stat.sz_tried += sz_tried;
2545 	if (sz_applied)
2546 		s->stat.nr_applied++;
2547 	s->stat.sz_applied += sz_applied;
2548 	s->stat.sz_ops_filter_passed += sz_ops_filter_passed;
2549 }
2550 
2551 static bool damos_filter_match(struct damon_ctx *ctx, struct damon_target *t,
2552 		struct damon_region *r, struct damos_filter *filter,
2553 		unsigned long min_region_sz, int *err)
2554 {
2555 	bool matched = false;
2556 	struct damon_target *ti;
2557 	int target_idx = 0;
2558 	unsigned long start, end, wsum;
2559 
2560 	*err = 0;
2561 	switch (filter->type) {
2562 	case DAMOS_FILTER_TYPE_TARGET:
2563 		damon_for_each_target(ti, ctx) {
2564 			if (ti == t)
2565 				break;
2566 			target_idx++;
2567 		}
2568 		matched = target_idx == filter->target_idx;
2569 		break;
2570 	case DAMOS_FILTER_TYPE_ADDR:
2571 		start = ALIGN_DOWN(filter->addr_range.start, min_region_sz);
2572 		end = ALIGN_DOWN(filter->addr_range.end, min_region_sz);
2573 
2574 		/* inside the range */
2575 		if (start <= r->ar.start && r->ar.end <= end) {
2576 			matched = true;
2577 			break;
2578 		}
2579 		/* outside of the range */
2580 		if (r->ar.end <= start || end <= r->ar.start) {
2581 			matched = false;
2582 			break;
2583 		}
2584 		/* start before the range and overlap */
2585 		if (r->ar.start < start) {
2586 			*err = damon_split_region_at(t, r,
2587 					start - r->ar.start);
2588 			matched = false;
2589 			break;
2590 		}
2591 		/* start inside the range */
2592 		*err = damon_split_region_at(t, r, end - r->ar.start);
2593 		matched = true;
2594 		break;
2595 	case DAMOS_FILTER_TYPE_PROBE_HITS_WSUM:
2596 		wsum = damon_probe_hits_wsum(r, false, true, ctx);
2597 		matched = filter->range_min <= wsum &&
2598 			wsum <= filter->range_max;
2599 		break;
2600 	default:
2601 		return false;
2602 	}
2603 
2604 	return matched == filter->matching;
2605 }
2606 
2607 static bool damos_core_filter_out(struct damon_ctx *ctx, struct damon_target *t,
2608 		struct damon_region *r, struct damos *s)
2609 {
2610 	struct damos_filter *filter;
2611 	bool matching;
2612 	int err;
2613 
2614 	s->core_filters_allowed = false;
2615 	damos_for_each_core_filter(filter, s) {
2616 		matching = damos_filter_match(ctx, t, r, filter,
2617 				ctx->min_region_sz, &err);
2618 		if (err)
2619 			return true;
2620 		if (matching) {
2621 			if (filter->allow)
2622 				s->core_filters_allowed = true;
2623 			return !filter->allow;
2624 		}
2625 	}
2626 	return s->core_filters_default_reject;
2627 }
2628 
2629 /*
2630  * damos_walk_call_walk() - Call &damos_walk_control->walk_fn.
2631  * @ctx:	The context of &damon_ctx->walk_control.
2632  * @t:		The monitoring target of @r that @s will be applied.
2633  * @r:		The region of @t that @s will be applied.
2634  * @s:		The scheme of @ctx that will be applied to @r.
2635  *
2636  * This function is called from kdamond whenever it asked the operation set to
2637  * apply a DAMOS scheme action to a region.  If a DAMOS walk request is
2638  * installed by damos_walk() and not yet uninstalled, invoke it.
2639  */
2640 static void damos_walk_call_walk(struct damon_ctx *ctx, struct damon_target *t,
2641 		struct damon_region *r, struct damos *s,
2642 		unsigned long sz_filter_passed)
2643 {
2644 	struct damos_walk_control *control;
2645 
2646 	if (s->walk_completed)
2647 		return;
2648 
2649 	control = ctx->walk_control;
2650 	if (!control)
2651 		return;
2652 
2653 	control->walk_fn(control->data, ctx, t, r, s, sz_filter_passed);
2654 }
2655 
2656 /*
2657  * damos_walk_complete() - Complete DAMOS walk request if all walks are done.
2658  * @ctx:	The context of &damon_ctx->walk_control.
2659  * @s:		A scheme of @ctx that all walks are now done.
2660  *
2661  * This function is called when kdamond finished applying the action of a DAMOS
2662  * scheme to all regions that eligible for the given &damos->apply_interval_us.
2663  * If every scheme of @ctx including @s now finished walking for at least one
2664  * &damos->apply_interval_us, this function marks the handling of the given
2665  * DAMOS walk request is done, so that damos_walk() can wake up and return.
2666  */
2667 static void damos_walk_complete(struct damon_ctx *ctx, struct damos *s)
2668 {
2669 	struct damos *siter;
2670 	struct damos_walk_control *control;
2671 
2672 	control = ctx->walk_control;
2673 	if (!control)
2674 		return;
2675 
2676 	s->walk_completed = true;
2677 	/* if all schemes completed, signal completion to walker */
2678 	damon_for_each_scheme(siter, ctx) {
2679 		if (!siter->walk_completed)
2680 			return;
2681 	}
2682 	damon_for_each_scheme(siter, ctx)
2683 		siter->walk_completed = false;
2684 
2685 	complete(&control->completion);
2686 	ctx->walk_control = NULL;
2687 }
2688 
2689 /*
2690  * damos_walk_cancel() - Cancel the current DAMOS walk request.
2691  * @ctx:	The context of &damon_ctx->walk_control.
2692  *
2693  * This function is called when @ctx is deactivated by DAMOS watermarks, DAMOS
2694  * walk is requested but there is no DAMOS scheme to walk for, or the kdamond
2695  * is already out of the main loop and therefore gonna be terminated, and hence
2696  * cannot continue the walks.  This function therefore marks the walk request
2697  * as canceled, so that damos_walk() can wake up and return.
2698  */
2699 static void damos_walk_cancel(struct damon_ctx *ctx)
2700 {
2701 	struct damos_walk_control *control;
2702 
2703 	mutex_lock(&ctx->walk_control_lock);
2704 	control = ctx->walk_control;
2705 	mutex_unlock(&ctx->walk_control_lock);
2706 
2707 	if (!control)
2708 		return;
2709 	control->canceled = true;
2710 	complete(&control->completion);
2711 	mutex_lock(&ctx->walk_control_lock);
2712 	ctx->walk_control = NULL;
2713 	mutex_unlock(&ctx->walk_control_lock);
2714 }
2715 
2716 static void damos_charge_quota(struct damos_quota *quota,
2717 		unsigned long sz_region, unsigned long sz_applied)
2718 {
2719 	/*
2720 	 * sz_applied could be bigger than sz_region, depending on ops
2721 	 * implementation of the action, e.g., damos_pa_pageout().  Charge only
2722 	 * the region size in the case.
2723 	 */
2724 	if (!quota->fail_charge_denom || sz_applied > sz_region)
2725 		quota->charged_sz += sz_region;
2726 	else
2727 		quota->charged_sz += sz_applied + mult_frac(
2728 				(sz_region - sz_applied),
2729 				quota->fail_charge_num,
2730 				quota->fail_charge_denom);
2731 }
2732 
2733 static bool damos_quota_is_full(struct damos_quota *quota,
2734 		unsigned long min_region_sz)
2735 {
2736 	if (!damos_quota_is_set(quota))
2737 		return false;
2738 	if (quota->charged_sz >= quota->esz)
2739 		return true;
2740 	/*
2741 	 * DAMOS action is applied per region, so <min_region_sz remaining
2742 	 * quota means the quota is effectively full.
2743 	 */
2744 	return quota->esz - quota->charged_sz < min_region_sz;
2745 }
2746 
2747 static void damos_apply_scheme(struct damon_ctx *c, struct damon_target *t,
2748 		struct damon_region *r, struct damos *s)
2749 {
2750 	struct damos_quota *quota = &s->quota;
2751 	unsigned long sz = damon_sz_region(r);
2752 	struct timespec64 begin, end;
2753 	unsigned long sz_applied = 0;
2754 	unsigned long sz_ops_filter_passed = 0;
2755 	/*
2756 	 * We plan to support multiple context per kdamond, as DAMON sysfs
2757 	 * implies with 'nr_contexts' file.  Nevertheless, only single context
2758 	 * per kdamond is supported for now.  So, we can simply use '0' context
2759 	 * index here.
2760 	 */
2761 	unsigned int cidx = 0;
2762 	struct damos *siter;		/* schemes iterator */
2763 	unsigned int sidx = 0;
2764 	struct damon_target *titer;	/* targets iterator */
2765 	unsigned int tidx = 0, nr_accesses = 0;
2766 	bool do_trace = false;
2767 
2768 	/* get indices for trace_damos_before_apply() */
2769 	if (trace_damos_before_apply_enabled()) {
2770 		damon_for_each_scheme(siter, c) {
2771 			if (siter == s)
2772 				break;
2773 			sidx++;
2774 		}
2775 		damon_for_each_target(titer, c) {
2776 			if (titer == t)
2777 				break;
2778 			tidx++;
2779 		}
2780 		nr_accesses = damon_nr_accesses_mvsum(r, c);
2781 		do_trace = true;
2782 	}
2783 
2784 	if (c->ops.apply_scheme) {
2785 		if (damos_quota_is_set(quota) &&
2786 				quota->charged_sz + sz > quota->esz) {
2787 			sz = ALIGN_DOWN(quota->esz - quota->charged_sz,
2788 					c->min_region_sz);
2789 			if (!sz)
2790 				goto update_stat;
2791 			if (damon_split_region_at(t, r, sz))
2792 				goto update_stat;
2793 		}
2794 		if (damos_core_filter_out(c, t, r, s))
2795 			return;
2796 		sz = damon_sz_region(r);
2797 		ktime_get_coarse_ts64(&begin);
2798 		trace_damos_before_apply(cidx, sidx, tidx, r, nr_accesses,
2799 				damon_nr_regions(t), do_trace);
2800 		sz_applied = c->ops.apply_scheme(c, t, r, s,
2801 				&sz_ops_filter_passed);
2802 		damos_walk_call_walk(c, t, r, s, sz_ops_filter_passed);
2803 		ktime_get_coarse_ts64(&end);
2804 		quota->total_charged_ns += timespec64_to_ns(&end) -
2805 			timespec64_to_ns(&begin);
2806 		damos_charge_quota(quota, sz, sz_applied);
2807 		if (damos_quota_is_full(quota, c->min_region_sz)) {
2808 			quota->charge_target_from = t;
2809 			quota->charge_addr_from = r->ar.end;
2810 		}
2811 	}
2812 	if (s->action != DAMOS_STAT)
2813 		r->age = 0;
2814 
2815 update_stat:
2816 	damos_update_stat(s, sz, sz_applied, sz_ops_filter_passed);
2817 }
2818 
2819 static void damon_do_apply_schemes(struct damon_ctx *c,
2820 				   struct damon_target *t,
2821 				   struct damon_region *r)
2822 {
2823 	struct damos *s;
2824 
2825 	damon_for_each_scheme(s, c) {
2826 		struct damos_quota *quota = &s->quota;
2827 
2828 		if (time_before(c->passed_sample_intervals, s->next_apply_sis))
2829 			continue;
2830 
2831 		if (!s->wmarks.activated)
2832 			continue;
2833 
2834 		/* Check the quota */
2835 		if (damos_quota_is_full(quota, c->min_region_sz))
2836 			continue;
2837 
2838 		if (damos_skip_charged_region(t, r, s, c->min_region_sz))
2839 			continue;
2840 
2841 		if (s->max_nr_snapshots &&
2842 				s->max_nr_snapshots <= s->stat.nr_snapshots)
2843 			continue;
2844 
2845 		if (damos_valid_target(c, r, s))
2846 			damos_apply_scheme(c, t, r, s);
2847 
2848 		if (damon_is_last_region(r, t))
2849 			s->stat.nr_snapshots++;
2850 	}
2851 }
2852 
2853 /*
2854  * damos_apply_target() - Apply DAMOS schemes to a given target.
2855  * @c:			monitoring context to apply its DAMOS schemes to..
2856  * @t:			monitoring target to apply the schemes to.
2857  * @max_region_sz:	maximum region size for @c.
2858  *
2859  * This function could split regions for keeping the quota.  To minimize
2860  * overhead from the split operations increased number of regions, this
2861  * function will also merge regions after the schemes applying attempt is done,
2862  * for each region.  The merge operation is made only when it doesn't lose the
2863  * monitoring information and not violating @max_region_sz.
2864  *
2865  * Hence, after this function is called, the total number of regions could
2866  * be increased or reduced.  The increase could make max_nr_regions temporarily
2867  * be violated, until the next per-aggregation interval regions merge operation
2868  * is executed.  The decrease will not violate min_nr_regions though, since it
2869  * keeps @max_region_sz.
2870  */
2871 static void damos_apply_target(struct damon_ctx *c, struct damon_target *t,
2872 		unsigned long max_region_sz)
2873 {
2874 	struct damon_region *r;
2875 
2876 	damon_for_each_region(r, t) {
2877 		struct damon_region *prev_r;
2878 
2879 		damon_do_apply_schemes(c, t, r);
2880 		/*
2881 		 * damon_do_apply_scheems() could split the region for the
2882 		 * quota.  Keeping the new slices is an overhead.  Merge back
2883 		 * the slices into the previous region if it doesn't lose any
2884 		 * information and not violating the max_region_sz.
2885 		 */
2886 		if (damon_first_region(t) == r)
2887 			continue;
2888 		prev_r = damon_prev_region(r);
2889 		if (prev_r->ar.end != r->ar.start)
2890 			continue;
2891 		if (prev_r->age != r->age)
2892 			continue;
2893 		if (prev_r->last_nr_accesses != r->last_nr_accesses)
2894 			continue;
2895 		if (prev_r->nr_accesses != r->nr_accesses)
2896 			continue;
2897 		if (r->ar.end - prev_r->ar.start > max_region_sz)
2898 			continue;
2899 		prev_r->ar.end = r->ar.end;
2900 		damon_destroy_region(r, t);
2901 		r = prev_r;
2902 	}
2903 }
2904 
2905 /*
2906  * damon_feed_loop_next_input() - get next input to achieve a target score.
2907  * @last_input	The last input.
2908  * @score	Current score that made with @last_input.
2909  *
2910  * Calculate next input to achieve the target score, based on the last input
2911  * and current score.  Assuming the input and the score are positively
2912  * proportional, calculate how much compensation should be added to or
2913  * subtracted from the last input as a proportion of the last input.  Avoid
2914  * next input always being zero by setting it non-zero always.  In short form
2915  * (assuming support of float and signed calculations), the algorithm is as
2916  * below.
2917  *
2918  * next_input = max(last_input * ((goal - current) / goal + 1), 1)
2919  *
2920  * For simple implementation, we assume the target score is always 10,000.  The
2921  * caller should adjust @score for this.
2922  *
2923  * Returns next input that assumed to achieve the target score.
2924  */
2925 static unsigned long damon_feed_loop_next_input(unsigned long last_input,
2926 		unsigned long score)
2927 {
2928 	const unsigned long goal = 10000;
2929 	/* Set minimum input as 10000 to avoid compensation be zero */
2930 	const unsigned long min_input = 10000;
2931 	unsigned long score_goal_diff, compensation;
2932 	bool over_achieving = score > goal;
2933 
2934 	if (score == goal)
2935 		return last_input;
2936 	if (score >= goal * 2)
2937 		return min_input;
2938 
2939 	score_goal_diff = abs_diff(score, goal);
2940 	compensation = mult_frac(last_input, score_goal_diff, goal);
2941 
2942 	if (over_achieving)
2943 		return max(last_input - compensation, min_input);
2944 	if (last_input < ULONG_MAX - compensation)
2945 		return last_input + compensation;
2946 	return ULONG_MAX;
2947 }
2948 
2949 #ifdef CONFIG_PSI
2950 
2951 static u64 damos_get_some_mem_psi_total(void)
2952 {
2953 	if (static_branch_likely(&psi_disabled))
2954 		return 0;
2955 	return div_u64(psi_system.total[PSI_AVGS][PSI_MEM * 2],
2956 			NSEC_PER_USEC);
2957 }
2958 
2959 #else	/* CONFIG_PSI */
2960 
2961 static inline u64 damos_get_some_mem_psi_total(void)
2962 {
2963 	return 0;
2964 }
2965 
2966 #endif	/* CONFIG_PSI */
2967 
2968 static void damos_set_psi_current_val(u64 now_psi_total,
2969 		struct damos_quota_goal *goal, struct damos *s)
2970 {
2971 	u64 last_psi_total = goal->last_psi_total;
2972 	unsigned long val;
2973 
2974 	goal->last_psi_total = now_psi_total;
2975 	if (last_psi_total != U64_MAX) {
2976 		val = now_psi_total - last_psi_total;
2977 		if (goal->complement) {
2978 			if (val < s->quota.reset_interval * 1000)
2979 				val = s->quota.reset_interval * 1000 - val;
2980 			else
2981 				val = 0;
2982 		}
2983 		goal->current_value = val;
2984 		return;
2985 	}
2986 	/* uninitialized last_psi_total; make no effect this round */
2987 	if (s->quota.goal_tuner == DAMOS_QUOTA_GOAL_TUNER_CONSIST) {
2988 		goal->current_value = goal->target_value;
2989 		return;
2990 	}
2991 	/* let temporal tuner show the same achievement as in the last round */
2992 	if (!s->quota.esz)
2993 		goal->current_value = goal->target_value;
2994 	else
2995 		goal->current_value = 0;
2996 }
2997 
2998 #ifdef CONFIG_NUMA
2999 static bool invalid_mem_node(int nid)
3000 {
3001 	return nid < 0 || nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY);
3002 }
3003 
3004 static __kernel_ulong_t damos_get_node_mem_bp(
3005 		struct damos_quota_goal *goal)
3006 {
3007 	struct sysinfo i;
3008 	__kernel_ulong_t numerator;
3009 
3010 	if (invalid_mem_node(goal->nid)) {
3011 		if (goal->metric == DAMOS_QUOTA_NODE_MEM_USED_BP)
3012 			return 0;
3013 		else	/* DAMOS_QUOTA_NODE_MEM_FREE_BP */
3014 			return 10000;
3015 	}
3016 
3017 	si_meminfo_node(&i, goal->nid);
3018 	if (!i.totalram || i.totalram < i.freeram) {
3019 		if (goal->metric == DAMOS_QUOTA_NODE_MEM_USED_BP)
3020 			return 10000;
3021 		else	/* DAMOS_QUOTA_NODE_MEM_FREE_BP */
3022 			return 0;
3023 	}
3024 
3025 	if (goal->metric == DAMOS_QUOTA_NODE_MEM_USED_BP)
3026 		numerator = i.totalram - i.freeram;
3027 	else	/* DAMOS_QUOTA_NODE_MEM_FREE_BP */
3028 		numerator = i.freeram;
3029 	return mult_frac(numerator, 10000, i.totalram);
3030 }
3031 
3032 static unsigned long damos_get_node_memcg_used_bp(
3033 		struct damos_quota_goal *goal)
3034 {
3035 	struct mem_cgroup *memcg;
3036 	struct lruvec *lruvec;
3037 	unsigned long used_pages, numerator;
3038 	struct sysinfo i;
3039 
3040 	if (invalid_mem_node(goal->nid)) {
3041 		if (goal->metric == DAMOS_QUOTA_NODE_MEMCG_USED_BP)
3042 			return 0;
3043 		else	/* DAMOS_QUOTA_NODE_MEMCG_FREE_BP */
3044 			return 10000;
3045 	}
3046 
3047 	memcg = mem_cgroup_get_from_id(goal->memcg_id);
3048 	if (!memcg) {
3049 		if (goal->metric == DAMOS_QUOTA_NODE_MEMCG_USED_BP)
3050 			return 0;
3051 		else	/* DAMOS_QUOTA_NODE_MEMCG_FREE_BP */
3052 			return 10000;
3053 	}
3054 
3055 	mem_cgroup_flush_stats(memcg);
3056 	lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(goal->nid));
3057 	used_pages = lruvec_page_state(lruvec, NR_ACTIVE_ANON);
3058 	used_pages += lruvec_page_state(lruvec, NR_INACTIVE_ANON);
3059 	used_pages += lruvec_page_state(lruvec, NR_ACTIVE_FILE);
3060 	used_pages += lruvec_page_state(lruvec, NR_INACTIVE_FILE);
3061 
3062 	mem_cgroup_put(memcg);
3063 
3064 	si_meminfo_node(&i, goal->nid);
3065 	if (!i.totalram || i.totalram < used_pages) {
3066 		if (goal->metric == DAMOS_QUOTA_NODE_MEMCG_USED_BP)
3067 			return 10000;
3068 		else	/* DAMOS_QUOTA_NODE_MEMCG_FREE_BP */
3069 			return 0;
3070 	}
3071 	if (goal->metric == DAMOS_QUOTA_NODE_MEMCG_USED_BP)
3072 		numerator = used_pages;
3073 	else	/* DAMOS_QUOTA_NODE_MEMCG_FREE_BP */
3074 		numerator = i.totalram - used_pages;
3075 	return mult_frac(numerator, 10000, i.totalram);
3076 }
3077 
3078 #ifdef CONFIG_DAMON_PADDR
3079 /*
3080  * damos_calc_eligible_bytes() - Calculate raw eligible bytes per node.
3081  * @c:		The DAMON context.
3082  * @s:		The scheme.
3083  * @nid:	The target NUMA node id.
3084  * @total:	Output for total eligible bytes across all nodes.
3085  *
3086  * Iterates through each folio in eligible regions to accurately determine
3087  * which node the memory resides on. Returns eligible bytes on the specified
3088  * node and sets *total to the sum across all nodes.
3089  *
3090  * Note: This function requires damon_get_folio() from ops-common.c, which is
3091  * only available when CONFIG_DAMON_PADDR is enabled. It also requires the
3092  * context to be using PADDR operations for meaningful results.
3093  */
3094 static phys_addr_t damos_calc_eligible_bytes(struct damon_ctx *c,
3095 		struct damos *s, int nid, phys_addr_t *total)
3096 {
3097 	struct damon_target *t;
3098 	struct damon_region *r;
3099 	phys_addr_t total_eligible = 0;
3100 	phys_addr_t node_eligible = 0;
3101 
3102 	damon_for_each_target(t, c) {
3103 		damon_for_each_region(r, t) {
3104 			phys_addr_t addr, end_addr;
3105 
3106 			if (!__damos_valid_target(r, s, c))
3107 				continue;
3108 
3109 			/* Convert from core address units to physical bytes */
3110 			addr = (phys_addr_t)r->ar.start * c->addr_unit;
3111 			end_addr = (phys_addr_t)r->ar.end * c->addr_unit;
3112 			while (addr < end_addr) {
3113 				struct folio *folio;
3114 				phys_addr_t folio_start, folio_end;
3115 				phys_addr_t overlap_start, overlap_end;
3116 				phys_addr_t counted;
3117 
3118 				folio = damon_get_folio(PHYS_PFN(addr));
3119 				if (!folio) {
3120 					addr = PAGE_ALIGN_DOWN(addr +
3121 							PAGE_SIZE);
3122 					if (!addr)
3123 						break;
3124 					continue;
3125 				}
3126 
3127 				/*
3128 				 * Calculate exact overlap between the region
3129 				 * [addr, end_addr) and the folio range.
3130 				 * The folio may start before addr if addr is
3131 				 * in the middle of a large folio.
3132 				 */
3133 				folio_start = PFN_PHYS(folio_pfn(folio));
3134 				folio_end = folio_start + folio_size(folio);
3135 
3136 				overlap_start = max(addr, folio_start);
3137 				overlap_end = min(end_addr, folio_end);
3138 
3139 				if (overlap_end > overlap_start) {
3140 					counted = overlap_end - overlap_start;
3141 					total_eligible += counted;
3142 					if (folio_nid(folio) == nid)
3143 						node_eligible += counted;
3144 				}
3145 
3146 				/* Advance past the entire folio */
3147 				addr = folio_end;
3148 				folio_put(folio);
3149 			}
3150 			cond_resched();
3151 		}
3152 	}
3153 
3154 	*total = total_eligible;
3155 	return node_eligible;
3156 }
3157 
3158 static unsigned long damos_get_node_eligible_mem_bp(struct damon_ctx *c,
3159 		struct damos *s, int nid)
3160 {
3161 	phys_addr_t total_eligible = 0;
3162 	phys_addr_t node_eligible;
3163 
3164 	if (c->ops.id != DAMON_OPS_PADDR)
3165 		return 0;
3166 
3167 	if (nid < 0 || nid >= MAX_NUMNODES || !node_online(nid))
3168 		return 0;
3169 
3170 	node_eligible = damos_calc_eligible_bytes(c, s, nid, &total_eligible);
3171 
3172 	if (!(unsigned long)total_eligible)
3173 		return 0;
3174 
3175 	return mult_frac((unsigned long)node_eligible, 10000,
3176 			(unsigned long)total_eligible);
3177 }
3178 #else /* CONFIG_DAMON_PADDR */
3179 static unsigned long damos_get_node_eligible_mem_bp(struct damon_ctx *c,
3180 		struct damos *s, int nid)
3181 {
3182 	return 0;
3183 }
3184 #endif /* CONFIG_DAMON_PADDR */
3185 #else /* CONFIG_NUMA */
3186 static __kernel_ulong_t damos_get_node_mem_bp(
3187 		struct damos_quota_goal *goal)
3188 {
3189 	return 0;
3190 }
3191 
3192 static unsigned long damos_get_node_memcg_used_bp(
3193 		struct damos_quota_goal *goal)
3194 {
3195 	return 0;
3196 }
3197 
3198 static unsigned long damos_get_node_eligible_mem_bp(struct damon_ctx *c,
3199 		struct damos *s, int nid)
3200 {
3201 	return 0;
3202 }
3203 #endif /* CONFIG_NUMA */
3204 
3205 /*
3206  * Returns LRU-active or inactive memory to total LRU memory size ratio.
3207  */
3208 static unsigned int damos_get_in_active_mem_bp(bool active_ratio)
3209 {
3210 	unsigned long active, inactive, total;
3211 
3212 	/* This should align with /proc/meminfo output */
3213 	active = global_node_page_state(NR_LRU_BASE + LRU_ACTIVE_ANON) +
3214 		global_node_page_state(NR_LRU_BASE + LRU_ACTIVE_FILE);
3215 	inactive = global_node_page_state(NR_LRU_BASE + LRU_INACTIVE_ANON) +
3216 		global_node_page_state(NR_LRU_BASE + LRU_INACTIVE_FILE);
3217 	total = max(active + inactive, 1);
3218 	if (active_ratio)
3219 		return mult_frac(active, 10000, total);
3220 	return mult_frac(inactive, 10000, total);
3221 }
3222 
3223 static unsigned int damos_hugepage_mem_bp(void)
3224 {
3225 	unsigned long thp, total_pages, free_pages;
3226 
3227 	total_pages = totalram_pages();
3228 	free_pages = global_zone_page_state(NR_FREE_PAGES);
3229 
3230 	if (total_pages <= free_pages)
3231 		return 10000;
3232 
3233 	thp = global_node_page_state(NR_ANON_THPS) +
3234 				global_node_page_state(NR_SHMEM_THPS) +
3235 				global_node_page_state(NR_FILE_THPS);
3236 	return mult_frac(thp, 10000, total_pages - free_pages);
3237 }
3238 
3239 static void damos_set_quota_goal_current_value(struct damon_ctx *c,
3240 		struct damos *s, struct damos_quota_goal *goal)
3241 {
3242 	u64 now_psi_total;
3243 
3244 	switch (goal->metric) {
3245 	case DAMOS_QUOTA_USER_INPUT:
3246 		/* User should already set goal->current_value */
3247 		break;
3248 	case DAMOS_QUOTA_SOME_MEM_PSI_US:
3249 		now_psi_total = damos_get_some_mem_psi_total();
3250 		damos_set_psi_current_val(now_psi_total, goal, s);
3251 		break;
3252 	case DAMOS_QUOTA_NODE_MEM_USED_BP:
3253 	case DAMOS_QUOTA_NODE_MEM_FREE_BP:
3254 		goal->current_value = damos_get_node_mem_bp(goal);
3255 		break;
3256 	case DAMOS_QUOTA_NODE_MEMCG_USED_BP:
3257 	case DAMOS_QUOTA_NODE_MEMCG_FREE_BP:
3258 		goal->current_value = damos_get_node_memcg_used_bp(goal);
3259 		break;
3260 	case DAMOS_QUOTA_ACTIVE_MEM_BP:
3261 	case DAMOS_QUOTA_INACTIVE_MEM_BP:
3262 		goal->current_value = damos_get_in_active_mem_bp(
3263 				goal->metric == DAMOS_QUOTA_ACTIVE_MEM_BP);
3264 		break;
3265 	case DAMOS_QUOTA_NODE_ELIGIBLE_MEM_BP:
3266 		goal->current_value = damos_get_node_eligible_mem_bp(c, s,
3267 				goal->nid);
3268 		break;
3269 	case DAMOS_QUOTA_HUGEPAGE_MEM_BP:
3270 		goal->current_value = damos_hugepage_mem_bp();
3271 		break;
3272 	default:
3273 		break;
3274 	}
3275 	if (!goal->complement)
3276 		return;
3277 
3278 	/* update current_value to complemented value */
3279 
3280 	/* for user_input, users set complemented value on their own */
3281 	if (goal->metric == DAMOS_QUOTA_USER_INPUT)
3282 		return;
3283 	/* damos_set_psi_current_val() handles complement flag itself */
3284 	if (goal->metric == DAMOS_QUOTA_SOME_MEM_PSI_US)
3285 		return;
3286 	if (goal->current_value < 10000)
3287 		goal->current_value = 10000 - goal->current_value;
3288 	else
3289 		goal->current_value = 0;
3290 }
3291 
3292 /* Return the highest score since it makes schemes least aggressive */
3293 static unsigned long damos_quota_score(struct damon_ctx *c, struct damos *s)
3294 {
3295 	struct damos_quota_goal *goal;
3296 	struct damos_quota *quota = &s->quota;
3297 	unsigned long highest_score = 0;
3298 
3299 	damos_for_each_quota_goal(goal, quota) {
3300 		damos_set_quota_goal_current_value(c, s, goal);
3301 		highest_score = max(highest_score,
3302 				mult_frac(goal->current_value, 10000,
3303 					goal->target_value));
3304 	}
3305 
3306 	return highest_score;
3307 }
3308 
3309 static void damos_goal_tune_esz_bp_consist(struct damon_ctx *c, struct damos *s)
3310 {
3311 	struct damos_quota *quota = &s->quota;
3312 	unsigned long score = damos_quota_score(c, s);
3313 
3314 	quota->esz_bp = damon_feed_loop_next_input(
3315 			max(quota->esz_bp, 10000UL), score);
3316 }
3317 
3318 static void damos_goal_tune_esz_bp_temporal(struct damon_ctx *c,
3319 		struct damos *s)
3320 {
3321 	struct damos_quota *quota = &s->quota;
3322 	unsigned long score = damos_quota_score(c, s);
3323 
3324 	if (score >= 10000)
3325 		quota->esz_bp = 0;
3326 	else if (quota->sz && quota->sz <= ULONG_MAX / 10000)
3327 		quota->esz_bp = quota->sz * 10000;
3328 	else
3329 		quota->esz_bp = ULONG_MAX;
3330 }
3331 
3332 /*
3333  * Called only if quota->ms, or quota->sz are set, or quota->goals is not empty
3334  */
3335 static void damos_set_effective_quota(struct damon_ctx *ctx, struct damos *s)
3336 {
3337 	struct damos_quota *quota = &s->quota;
3338 	unsigned long throughput;
3339 	unsigned long esz = ULONG_MAX;
3340 	unsigned long esz_time;
3341 
3342 	if (!quota->ms && list_empty(&quota->goals)) {
3343 		quota->esz = quota->sz;
3344 		return;
3345 	}
3346 
3347 	if (!list_empty(&quota->goals)) {
3348 		if (quota->goal_tuner == DAMOS_QUOTA_GOAL_TUNER_CONSIST)
3349 			damos_goal_tune_esz_bp_consist(ctx, s);
3350 		else if (quota->goal_tuner == DAMOS_QUOTA_GOAL_TUNER_TEMPORAL)
3351 			damos_goal_tune_esz_bp_temporal(ctx, s);
3352 		esz = quota->esz_bp / 10000;
3353 	}
3354 
3355 	if (quota->ms) {
3356 		if (quota->total_charged_ns)
3357 			throughput = mult_frac(quota->total_charged_sz,
3358 					1000000, quota->total_charged_ns);
3359 		else
3360 			throughput = PAGE_SIZE * 1024;
3361 		esz_time = max(throughput * quota->ms, ctx->min_region_sz);
3362 		esz = min(esz_time, esz);
3363 	}
3364 
3365 	if (quota->sz && quota->sz < esz)
3366 		esz = quota->sz;
3367 
3368 	quota->esz = esz;
3369 }
3370 
3371 static void damos_trace_esz(struct damon_ctx *c, struct damos *s,
3372 		struct damos_quota *quota)
3373 {
3374 	unsigned int cidx = 0, sidx = 0;
3375 	struct damos *siter;
3376 
3377 	damon_for_each_scheme(siter, c) {
3378 		if (siter == s)
3379 			break;
3380 		sidx++;
3381 	}
3382 	trace_damos_esz(cidx, sidx, quota->esz);
3383 }
3384 
3385 static void damos_fix_stale_charge_pointers(struct damon_ctx *c,
3386 		struct damos *s)
3387 {
3388 	struct damos_quota *quota;
3389 	struct damon_target *t;
3390 
3391 	quota = &s->quota;
3392 	if (!quota->charge_target_from)
3393 		return;
3394 	damon_for_each_target(t, c) {
3395 		if (t == quota->charge_target_from) {
3396 			if (damon_nr_regions(t) > 0)
3397 				return;
3398 			break;
3399 		}
3400 	}
3401 	quota->charge_target_from = NULL;
3402 	quota->charge_addr_from = 0;
3403 }
3404 
3405 static void damos_adjust_quota(struct damon_ctx *c, struct damos *s)
3406 {
3407 	struct damos_quota *quota = &s->quota;
3408 	struct damon_target *t;
3409 	struct damon_region *r;
3410 	unsigned long cumulated_sz, cached_esz;
3411 	unsigned int score, max_score = 0;
3412 
3413 	if (!damos_quota_is_set(quota))
3414 		return;
3415 
3416 	/* First charge window */
3417 	if (!quota->total_charged_sz && !quota->charged_from) {
3418 		quota->charged_from = jiffies;
3419 		damos_set_effective_quota(c, s);
3420 		if (trace_damos_esz_enabled())
3421 			damos_trace_esz(c, s, quota);
3422 	}
3423 
3424 	/* New charge window starts */
3425 	if (!time_in_range_open(jiffies, quota->charged_from,
3426 				quota->charged_from +
3427 				msecs_to_jiffies(quota->reset_interval))) {
3428 		if (damos_quota_is_full(quota, c->min_region_sz))
3429 			s->stat.qt_exceeds++;
3430 		quota->total_charged_sz += quota->charged_sz;
3431 		quota->charged_from = jiffies;
3432 		quota->charged_sz = 0;
3433 		if (trace_damos_esz_enabled())
3434 			cached_esz = quota->esz;
3435 		damos_set_effective_quota(c, s);
3436 		if (trace_damos_esz_enabled() && quota->esz != cached_esz)
3437 			damos_trace_esz(c, s, quota);
3438 	}
3439 
3440 	damos_fix_stale_charge_pointers(c, s);
3441 
3442 	if (damos_quota_is_full(quota, c->min_region_sz))
3443 		return;
3444 	if (!c->ops.get_scheme_score)
3445 		return;
3446 
3447 	/* Fill up the score histogram */
3448 	memset(c->regions_score_histogram, 0,
3449 			sizeof(*c->regions_score_histogram) *
3450 			(DAMOS_MAX_SCORE + 1));
3451 	damon_for_each_target(t, c) {
3452 		damon_for_each_region(r, t) {
3453 			if (!__damos_valid_target(r, s, c))
3454 				continue;
3455 			if (damos_core_filter_out(c, t, r, s))
3456 				continue;
3457 			score = c->ops.get_scheme_score(c, r, s);
3458 			c->regions_score_histogram[score] +=
3459 				damon_sz_region(r);
3460 			if (score > max_score)
3461 				max_score = score;
3462 		}
3463 	}
3464 
3465 	/* Set the min score limit */
3466 	for (cumulated_sz = 0, score = max_score; ; score--) {
3467 		cumulated_sz += c->regions_score_histogram[score];
3468 		if (cumulated_sz >= quota->esz || !score)
3469 			break;
3470 	}
3471 	quota->min_score = score;
3472 }
3473 
3474 static void damos_trace_stat(struct damon_ctx *c, struct damos *s)
3475 {
3476 	unsigned int cidx = 0, sidx = 0;
3477 	struct damos *siter;
3478 
3479 	if (!trace_damos_stat_after_apply_interval_enabled())
3480 		return;
3481 
3482 	damon_for_each_scheme(siter, c) {
3483 		if (siter == s)
3484 			break;
3485 		sidx++;
3486 	}
3487 	trace_call__damos_stat_after_apply_interval(cidx, sidx, &s->stat);
3488 }
3489 
3490 static noinline_for_stack void kdamond_apply_schemes(struct damon_ctx *c)
3491 {
3492 	struct damon_target *t;
3493 	struct damos *s;
3494 	bool has_schemes_to_apply = false;
3495 	unsigned long max_region_sz;
3496 
3497 	damon_for_each_scheme(s, c) {
3498 		if (time_before(c->passed_sample_intervals, s->next_apply_sis))
3499 			continue;
3500 
3501 		if (!s->wmarks.activated)
3502 			continue;
3503 
3504 		has_schemes_to_apply = true;
3505 
3506 		damos_adjust_quota(c, s);
3507 	}
3508 
3509 	if (!has_schemes_to_apply)
3510 		return;
3511 
3512 	max_region_sz = damon_region_sz_limit(c);
3513 	mutex_lock(&c->walk_control_lock);
3514 	damon_for_each_target(t, c) {
3515 		if (c->ops.target_valid && c->ops.target_valid(t) == false) {
3516 			damon_for_each_scheme(s, c) {
3517 				if (s->quota.charge_target_from != t)
3518 					continue;
3519 				s->quota.charge_target_from = NULL;
3520 				s->quota.charge_addr_from = 0;
3521 			}
3522 			continue;
3523 		}
3524 		damos_apply_target(c, t, max_region_sz);
3525 	}
3526 
3527 	damon_for_each_scheme(s, c) {
3528 		if (time_before(c->passed_sample_intervals, s->next_apply_sis))
3529 			continue;
3530 		damos_walk_complete(c, s);
3531 		damos_set_next_apply_sis(s, c);
3532 		s->last_applied = NULL;
3533 		damos_trace_stat(c, s);
3534 	}
3535 	mutex_unlock(&c->walk_control_lock);
3536 }
3537 
3538 #ifdef CONFIG_DAMON_DEBUG_SANITY
3539 static void damon_verify_merge_two_regions(
3540 		struct damon_region *l, struct damon_region *r)
3541 {
3542 	/* damon_merge_two_regions() may created incorrect left region */
3543 	WARN_ONCE(l->ar.start >= l->ar.end, "l: %lu-%lu, r: %lu-%lu\n",
3544 			l->ar.start, l->ar.end, r->ar.start, r->ar.end);
3545 }
3546 #else
3547 static void damon_verify_merge_two_regions(
3548 		struct damon_region *l, struct damon_region *r)
3549 {
3550 }
3551 #endif
3552 
3553 /*
3554  * Merge two adjacent regions into one region
3555  */
3556 static void damon_merge_two_regions(struct damon_target *t,
3557 		struct damon_region *l, struct damon_region *r)
3558 {
3559 	unsigned long sz_l = damon_sz_region(l), sz_r = damon_sz_region(r);
3560 	int i;
3561 
3562 	l->nr_accesses = (l->nr_accesses * sz_l + r->nr_accesses * sz_r) /
3563 			(sz_l + sz_r);
3564 	l->age = (l->age * sz_l + r->age * sz_r) / (sz_l + sz_r);
3565 	l->ar.end = r->ar.end;
3566 	/* todo: do this for only installed probes */
3567 	for (i = 0; i < DAMON_MAX_PROBES; i++)
3568 		l->probe_hits[i] = (l->probe_hits[i] * sz_l + r->probe_hits[i]
3569 				* sz_r) / (sz_l + sz_r);
3570 	damon_verify_merge_two_regions(l, r);
3571 	damon_destroy_region(r, t);
3572 }
3573 
3574 static unsigned int damon_merge_score(struct damon_region *r, bool last,
3575 		struct damon_ctx *ctx, bool use_probe_hits)
3576 {
3577 	if (use_probe_hits)
3578 		return damon_probe_hits_wsum(r, last, false, ctx);
3579 	if (last)
3580 		return r->last_nr_accesses;
3581 	return r->nr_accesses;
3582 }
3583 
3584 /*
3585  * Merge adjacent regions having similar access frequencies
3586  *
3587  * t		target affected by this merge operation
3588  * thres	'->nr_accesses' diff threshold for the merge
3589  * sz_limit	size upper limit of each region
3590  */
3591 static void damon_merge_regions_of(struct damon_target *t, unsigned int thres,
3592 		unsigned long sz_limit, struct damon_ctx *ctx, bool count_age)
3593 {
3594 	struct damon_region *r, *prev = NULL, *next;
3595 	bool use_probe_hits = damon_has_probe_weights(ctx);
3596 
3597 	damon_for_each_region_safe(r, next, t) {
3598 		unsigned int score, last_score, diff;
3599 
3600 		score = damon_merge_score(r, false, ctx, use_probe_hits);
3601 		last_score = damon_merge_score(r, true, ctx, use_probe_hits);
3602 
3603 		if (count_age) {
3604 			if (abs_diff(score, last_score) > thres)
3605 				r->age = 0;
3606 			else if ((score == 0) != (last_score == 0))
3607 				r->age = 0;
3608 			else
3609 				r->age++;
3610 		}
3611 
3612 		if (!prev)
3613 			goto set_prev_continue;
3614 		if (prev->ar.end != r->ar.start)
3615 			goto set_prev_continue;
3616 		diff = abs_diff(score, damon_merge_score(prev, false, ctx,
3617 					use_probe_hits));
3618 		if (diff > thres)
3619 			goto set_prev_continue;
3620 		if (damon_sz_region(prev) + damon_sz_region(r) > sz_limit)
3621 			goto set_prev_continue;
3622 		damon_merge_two_regions(t, prev, r);
3623 		continue;
3624 set_prev_continue:
3625 		prev = r;
3626 	}
3627 }
3628 
3629 /*
3630  * Merge adjacent regions having similar access frequencies
3631  *
3632  * threshold	'->nr_accesses' diff threshold for the merge
3633  * sz_limit	size upper limit of each region
3634  *
3635  * This function merges monitoring target regions which are adjacent and their
3636  * access frequencies are similar.  This is for minimizing the monitoring
3637  * overhead under the dynamically changeable access pattern.  If a merge was
3638  * unnecessarily made, later 'kdamond_split_regions()' will revert it.
3639  *
3640  * The total number of regions could be higher than the user-defined limit,
3641  * max_nr_regions for some cases.  For example, the user can update
3642  * max_nr_regions to a number that lower than the current number of regions
3643  * while DAMON is running.  For such a case, repeat merging until the limit is
3644  * met while increasing @threshold up to possible maximum level.
3645  */
3646 static noinline_for_stack void kdamond_merge_regions(struct damon_ctx *c,
3647 						     unsigned int threshold,
3648 						     unsigned long sz_limit)
3649 {
3650 	struct damon_target *t;
3651 	unsigned int nr_regions;
3652 	unsigned int max_thres;
3653 	bool count_age = true;
3654 
3655 	max_thres = damon_nr_samples_per_aggr(&c->attrs);
3656 	while (true) {
3657 		nr_regions = 0;
3658 		damon_for_each_target(t, c) {
3659 			damon_merge_regions_of(t, threshold, sz_limit, c,
3660 					count_age);
3661 			nr_regions += damon_nr_regions(t);
3662 		}
3663 		count_age = false;
3664 		if (nr_regions <= c->attrs.max_nr_regions ||
3665 				max_thres <= threshold)
3666 			break;
3667 		if (threshold < max_thres / 2)
3668 			threshold = max(1, threshold * 2);
3669 		else
3670 			threshold = max_thres;
3671 	}
3672 }
3673 
3674 #ifdef CONFIG_DAMON_DEBUG_SANITY
3675 static void damon_verify_split_region_at(struct damon_region *r,
3676 		unsigned long sz_r)
3677 {
3678 	WARN_ONCE(sz_r == 0 || sz_r >= damon_sz_region(r),
3679 			"sz_r: %lu r: %lu-%lu (%lu)\n",
3680 			sz_r, r->ar.start, r->ar.end, damon_sz_region(r));
3681 }
3682 #else
3683 static void damon_verify_split_region_at(struct damon_region *r,
3684 		unsigned long sz_r)
3685 {
3686 }
3687 #endif
3688 
3689 /*
3690  * Split a region in two
3691  *
3692  * r		the region to be split
3693  * sz_r		size of the first sub-region that will be made
3694  *
3695  * Return: 0 on success, negative error code otherwise.
3696  */
3697 static int damon_split_region_at(struct damon_target *t,
3698 				  struct damon_region *r, unsigned long sz_r)
3699 {
3700 	struct damon_region *new;
3701 
3702 	damon_verify_split_region_at(r, sz_r);
3703 	new = damon_new_region(r->ar.start + sz_r, r->ar.end);
3704 	if (!new)
3705 		return -ENOMEM;
3706 
3707 	r->ar.end = new->ar.start;
3708 
3709 	new->age = r->age;
3710 	new->last_nr_accesses = r->last_nr_accesses;
3711 	new->nr_accesses = r->nr_accesses;
3712 	/* todo: do this for only installed probes */
3713 	memcpy(new->probe_hits, r->probe_hits, sizeof(r->probe_hits));
3714 	memcpy(new->last_probe_hits, r->last_probe_hits,
3715 			sizeof(r->last_probe_hits));
3716 
3717 	damon_insert_region(new, r, damon_next_region(r), t);
3718 	return 0;
3719 }
3720 
3721 /* Split every region in the given target into 'nr_subs' regions */
3722 static void damon_split_regions_of(struct damon_ctx *ctx,
3723 				   struct damon_target *t, int nr_subs,
3724 				   unsigned long min_region_sz)
3725 {
3726 	struct damon_region *r, *next;
3727 	unsigned long sz_region, sz_sub = 0;
3728 	int i;
3729 
3730 	damon_for_each_region_safe(r, next, t) {
3731 		sz_region = damon_sz_region(r);
3732 
3733 		for (i = 0; i < nr_subs - 1 &&
3734 				sz_region > 2 * min_region_sz; i++) {
3735 			/*
3736 			 * Randomly select size of left sub-region to be at
3737 			 * least 10 percent and at most 90% of original region
3738 			 */
3739 			sz_sub = ALIGN_DOWN(damon_rand(ctx, 1, 10) *
3740 					sz_region / 10, min_region_sz);
3741 			/* Do not allow blank region */
3742 			if (sz_sub == 0 || sz_sub >= sz_region)
3743 				continue;
3744 
3745 			damon_split_region_at(t, r, sz_sub);
3746 			sz_region = sz_sub;
3747 		}
3748 	}
3749 }
3750 
3751 /* Split one in every @split_step regions into two, from a rotating offset */
3752 static void damon_split_some_regions(struct damon_ctx *ctx,
3753 				     unsigned long split_step)
3754 {
3755 	struct damon_target *t;
3756 	struct damon_region *r, *next;
3757 	unsigned long offset;
3758 	unsigned long idx = 0;
3759 
3760 	offset = ctx->region_split_rotation++ % split_step;
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 	int nr_subregions = 2;
3799 
3800 	damon_for_each_target(t, ctx)
3801 		nr_regions += damon_nr_regions(t);
3802 
3803 	if (nr_regions >= max_nr_regions)
3804 		goto done;
3805 
3806 	if (nr_regions > max_nr_regions / 2) {
3807 		damon_split_some_regions(ctx,
3808 			max_nr_regions / (max_nr_regions - nr_regions));
3809 		goto done;
3810 	}
3811 
3812 	/* Maybe the middle of the region has different access frequency */
3813 	if (ctx->last_nr_regions == nr_regions &&
3814 			nr_regions < max_nr_regions / 3)
3815 		nr_subregions = 3;
3816 
3817 	damon_for_each_target(t, ctx)
3818 		damon_split_regions_of(ctx, t, nr_subregions,
3819 				       ctx->min_region_sz);
3820 
3821 done:
3822 	ctx->last_nr_regions = nr_regions;
3823 }
3824 
3825 /*
3826  * Check whether current monitoring should be stopped
3827  *
3828  * The monitoring is stopped when either the user requested to stop, or all
3829  * monitoring targets are invalid.
3830  *
3831  * Returns true if need to stop current monitoring.
3832  */
3833 static bool kdamond_need_stop(struct damon_ctx *ctx)
3834 {
3835 	struct damon_target *t;
3836 
3837 	if (kthread_should_stop())
3838 		return true;
3839 
3840 	if (!ctx->ops.target_valid)
3841 		return false;
3842 
3843 	damon_for_each_target(t, ctx) {
3844 		if (ctx->ops.target_valid(t))
3845 			return false;
3846 	}
3847 
3848 	return true;
3849 }
3850 
3851 static int damos_get_wmark_metric_value(enum damos_wmark_metric metric,
3852 					unsigned long *metric_value)
3853 {
3854 	switch (metric) {
3855 	case DAMOS_WMARK_FREE_MEM_RATE:
3856 		*metric_value = global_zone_page_state(NR_FREE_PAGES) * 1000 /
3857 		       totalram_pages();
3858 		return 0;
3859 	default:
3860 		break;
3861 	}
3862 	return -EINVAL;
3863 }
3864 
3865 /*
3866  * Returns zero if the scheme is active.  Else, returns time to wait for next
3867  * watermark check in micro-seconds.
3868  */
3869 static unsigned long damos_wmark_wait_us(struct damos *scheme)
3870 {
3871 	unsigned long metric;
3872 
3873 	if (damos_get_wmark_metric_value(scheme->wmarks.metric, &metric))
3874 		return 0;
3875 
3876 	/* higher than high watermark or lower than low watermark */
3877 	if (metric > scheme->wmarks.high || scheme->wmarks.low > metric) {
3878 		scheme->wmarks.activated = false;
3879 		return scheme->wmarks.interval;
3880 	}
3881 
3882 	/* inactive and higher than middle watermark */
3883 	if ((scheme->wmarks.high >= metric && metric >= scheme->wmarks.mid) &&
3884 			!scheme->wmarks.activated)
3885 		return scheme->wmarks.interval;
3886 
3887 	scheme->wmarks.activated = true;
3888 	return 0;
3889 }
3890 
3891 static void kdamond_usleep(unsigned long usecs)
3892 {
3893 	if (usecs >= USLEEP_RANGE_UPPER_BOUND)
3894 		schedule_timeout_idle(usecs_to_jiffies(usecs));
3895 	else
3896 		usleep_range_idle(usecs, usecs + 1);
3897 }
3898 
3899 #ifdef CONFIG_DAMON_DEBUG_SANITY
3900 static void damon_verify_ctx(struct damon_ctx *c)
3901 {
3902 	struct damon_target *t;
3903 	struct damon_region *r;
3904 
3905 	damon_for_each_target(t, c) {
3906 		struct damon_region *prev_r = NULL;
3907 		unsigned int nr_regions = 0;
3908 
3909 		damon_for_each_region(r, t) {
3910 			WARN_ONCE(r->ar.start >= r->ar.end,
3911 					"region start (%lu) >= end (%lu)\n",
3912 					r->ar.start, r->ar.end);
3913 			WARN_ONCE(prev_r && prev_r->ar.end > r->ar.start,
3914 					"region overlap (%lu > %lu)\n",
3915 					prev_r->ar.end, r->ar.start);
3916 			prev_r = r;
3917 			nr_regions++;
3918 		}
3919 		WARN_ONCE(damon_nr_regions(t) != nr_regions,
3920 				"nr_regions mismatch: %u != %u\n",
3921 				damon_nr_regions(t), nr_regions);
3922 	}
3923 }
3924 #else
3925 static void damon_verify_ctx(struct damon_ctx *c)
3926 {
3927 }
3928 #endif
3929 
3930 /*
3931  * kdamond_call() - handle damon_call_control objects.
3932  * @ctx:	The &struct damon_ctx of the kdamond.
3933  * @cancel:	Whether to cancel the invocation of the function.
3934  *
3935  * If there are &struct damon_call_control requests that registered via
3936  * &damon_call() on @ctx, do or cancel the invocation of the function depending
3937  * on @cancel.  @cancel is set when the kdamond is already out of the main loop
3938  * and therefore will be terminated.
3939  */
3940 static void kdamond_call(struct damon_ctx *ctx, bool cancel)
3941 {
3942 	struct damon_call_control *control, *next;
3943 	LIST_HEAD(controls);
3944 
3945 	damon_verify_ctx(ctx);
3946 
3947 	mutex_lock(&ctx->call_controls_lock);
3948 	list_splice_tail_init(&ctx->call_controls, &controls);
3949 	mutex_unlock(&ctx->call_controls_lock);
3950 
3951 	list_for_each_entry_safe(control, next, &controls, list) {
3952 		if (!control->repeat || cancel)
3953 			list_del(&control->list);
3954 
3955 		if (cancel)
3956 			control->canceled = true;
3957 		else
3958 			control->return_code = control->fn(control->data);
3959 
3960 		if (!control->repeat)
3961 			complete(&control->completion);
3962 		else if (control->canceled && control->dealloc_on_cancel)
3963 			kfree(control);
3964 		if (!cancel && ctx->maybe_corrupted)
3965 			break;
3966 	}
3967 
3968 	mutex_lock(&ctx->call_controls_lock);
3969 	list_splice_tail(&controls, &ctx->call_controls);
3970 	mutex_unlock(&ctx->call_controls_lock);
3971 }
3972 
3973 /* Returns negative error code if it's not activated but should return */
3974 static int kdamond_wait_activation(struct damon_ctx *ctx)
3975 {
3976 	struct damos *s;
3977 	unsigned long wait_time;
3978 
3979 	while (!kdamond_need_stop(ctx)) {
3980 		unsigned long min_wait_time = 0;
3981 		bool init_wait_time = false;
3982 
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_objs(*ctx->regions_score_histogram,
4042 						    DAMOS_MAX_SCORE + 1);
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