1 // SPDX-License-Identifier: GPL-2.0
8 #define pr_fmt(fmt) "damon: " fmt
10 #include <linux/damon.h>
11 #include <linux/delay.h>
12 #include <linux/kthread.h>
14 #include <linux/slab.h>
15 #include <linux/string.h>
17 #define CREATE_TRACE_POINTS
18 #include <trace/events/damon.h>
20 #ifdef CONFIG_DAMON_KUNIT_TEST
21 #undef DAMON_MIN_REGION
22 #define DAMON_MIN_REGION 1
25 static DEFINE_MUTEX(damon_lock);
26 static int nr_running_ctxs;
27 static bool running_exclusive_ctxs;
29 static DEFINE_MUTEX(damon_ops_lock);
30 static struct damon_operations damon_registered_ops[NR_DAMON_OPS];
32 static struct kmem_cache *damon_region_cache __ro_after_init;
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)
37 struct damon_operations empty_ops = {};
39 if (!memcmp(&empty_ops, &damon_registered_ops[id], sizeof(empty_ops)))
45 * damon_is_registered_ops() - Check if a given damon_operations is registered.
46 * @id: Id of the damon_operations to check if registered.
48 * Return: true if the ops is set, false otherwise.
50 bool damon_is_registered_ops(enum damon_ops_id id)
54 if (id >= NR_DAMON_OPS)
56 mutex_lock(&damon_ops_lock);
57 registered = __damon_is_registered_ops(id);
58 mutex_unlock(&damon_ops_lock);
63 * damon_register_ops() - Register a monitoring operations set to DAMON.
64 * @ops: monitoring operations set to register.
66 * This function registers a monitoring operations set of valid &struct
67 * damon_operations->id so that others can find and use them later.
69 * Return: 0 on success, negative error code otherwise.
71 int damon_register_ops(struct damon_operations *ops)
75 if (ops->id >= NR_DAMON_OPS)
77 mutex_lock(&damon_ops_lock);
78 /* Fail for already registered ops */
79 if (__damon_is_registered_ops(ops->id)) {
83 damon_registered_ops[ops->id] = *ops;
85 mutex_unlock(&damon_ops_lock);
90 * damon_select_ops() - Select a monitoring operations to use with the context.
91 * @ctx: monitoring context to use the operations.
92 * @id: id of the registered monitoring operations to select.
94 * This function finds registered monitoring operations set of @id and make
97 * Return: 0 on success, negative error code otherwise.
99 int damon_select_ops(struct damon_ctx *ctx, enum damon_ops_id id)
103 if (id >= NR_DAMON_OPS)
106 mutex_lock(&damon_ops_lock);
107 if (!__damon_is_registered_ops(id))
110 ctx->ops = damon_registered_ops[id];
111 mutex_unlock(&damon_ops_lock);
116 * Construct a damon_region struct
118 * Returns the pointer to the new struct if success, or NULL otherwise
120 struct damon_region *damon_new_region(unsigned long start, unsigned long end)
122 struct damon_region *region;
124 region = kmem_cache_alloc(damon_region_cache, GFP_KERNEL);
128 region->ar.start = start;
129 region->ar.end = end;
130 region->nr_accesses = 0;
131 INIT_LIST_HEAD(®ion->list);
134 region->last_nr_accesses = 0;
139 void damon_add_region(struct damon_region *r, struct damon_target *t)
141 list_add_tail(&r->list, &t->regions_list);
145 static void damon_del_region(struct damon_region *r, struct damon_target *t)
151 static void damon_free_region(struct damon_region *r)
153 kmem_cache_free(damon_region_cache, r);
156 void damon_destroy_region(struct damon_region *r, struct damon_target *t)
158 damon_del_region(r, t);
159 damon_free_region(r);
163 * Check whether a region is intersecting an address range
165 * Returns true if it is.
167 static bool damon_intersect(struct damon_region *r,
168 struct damon_addr_range *re)
170 return !(r->ar.end <= re->start || re->end <= r->ar.start);
174 * Fill holes in regions with new regions.
176 static int damon_fill_regions_holes(struct damon_region *first,
177 struct damon_region *last, struct damon_target *t)
179 struct damon_region *r = first;
181 damon_for_each_region_from(r, t) {
182 struct damon_region *next, *newr;
186 next = damon_next_region(r);
187 if (r->ar.end != next->ar.start) {
188 newr = damon_new_region(r->ar.end, next->ar.start);
191 damon_insert_region(newr, r, next, t);
198 * damon_set_regions() - Set regions of a target for given address ranges.
199 * @t: the given target.
200 * @ranges: array of new monitoring target ranges.
201 * @nr_ranges: length of @ranges.
203 * This function adds new regions to, or modify existing regions of a
204 * monitoring target to fit in specific ranges.
206 * Return: 0 if success, or negative error code otherwise.
208 int damon_set_regions(struct damon_target *t, struct damon_addr_range *ranges,
209 unsigned int nr_ranges)
211 struct damon_region *r, *next;
215 /* Remove regions which are not in the new ranges */
216 damon_for_each_region_safe(r, next, t) {
217 for (i = 0; i < nr_ranges; i++) {
218 if (damon_intersect(r, &ranges[i]))
222 damon_destroy_region(r, t);
225 r = damon_first_region(t);
226 /* Add new regions or resize existing regions to fit in the ranges */
227 for (i = 0; i < nr_ranges; i++) {
228 struct damon_region *first = NULL, *last, *newr;
229 struct damon_addr_range *range;
232 /* Get the first/last regions intersecting with the range */
233 damon_for_each_region_from(r, t) {
234 if (damon_intersect(r, range)) {
239 if (r->ar.start >= range->end)
243 /* no region intersects with this range */
244 newr = damon_new_region(
245 ALIGN_DOWN(range->start,
247 ALIGN(range->end, DAMON_MIN_REGION));
250 damon_insert_region(newr, damon_prev_region(r), r, t);
252 /* resize intersecting regions to fit in this range */
253 first->ar.start = ALIGN_DOWN(range->start,
255 last->ar.end = ALIGN(range->end, DAMON_MIN_REGION);
257 /* fill possible holes in the range */
258 err = damon_fill_regions_holes(first, last, t);
266 struct damos_filter *damos_new_filter(enum damos_filter_type type,
269 struct damos_filter *filter;
271 filter = kmalloc(sizeof(*filter), GFP_KERNEL);
275 filter->matching = matching;
279 void damos_add_filter(struct damos *s, struct damos_filter *f)
281 list_add_tail(&f->list, &s->filters);
284 static void damos_del_filter(struct damos_filter *f)
289 static void damos_free_filter(struct damos_filter *f)
294 void damos_destroy_filter(struct damos_filter *f)
297 damos_free_filter(f);
300 /* initialize private fields of damos_quota and return the pointer */
301 static struct damos_quota *damos_quota_init_priv(struct damos_quota *quota)
303 quota->total_charged_sz = 0;
304 quota->total_charged_ns = 0;
306 quota->charged_sz = 0;
307 quota->charged_from = 0;
308 quota->charge_target_from = NULL;
309 quota->charge_addr_from = 0;
313 struct damos *damon_new_scheme(struct damos_access_pattern *pattern,
314 enum damos_action action, struct damos_quota *quota,
315 struct damos_watermarks *wmarks)
317 struct damos *scheme;
319 scheme = kmalloc(sizeof(*scheme), GFP_KERNEL);
322 scheme->pattern = *pattern;
323 scheme->action = action;
324 INIT_LIST_HEAD(&scheme->filters);
325 scheme->stat = (struct damos_stat){};
326 INIT_LIST_HEAD(&scheme->list);
328 scheme->quota = *(damos_quota_init_priv(quota));
330 scheme->wmarks = *wmarks;
331 scheme->wmarks.activated = true;
336 void damon_add_scheme(struct damon_ctx *ctx, struct damos *s)
338 list_add_tail(&s->list, &ctx->schemes);
341 static void damon_del_scheme(struct damos *s)
346 static void damon_free_scheme(struct damos *s)
351 void damon_destroy_scheme(struct damos *s)
353 struct damos_filter *f, *next;
355 damos_for_each_filter_safe(f, next, s)
356 damos_destroy_filter(f);
358 damon_free_scheme(s);
362 * Construct a damon_target struct
364 * Returns the pointer to the new struct if success, or NULL otherwise
366 struct damon_target *damon_new_target(void)
368 struct damon_target *t;
370 t = kmalloc(sizeof(*t), GFP_KERNEL);
376 INIT_LIST_HEAD(&t->regions_list);
377 INIT_LIST_HEAD(&t->list);
382 void damon_add_target(struct damon_ctx *ctx, struct damon_target *t)
384 list_add_tail(&t->list, &ctx->adaptive_targets);
387 bool damon_targets_empty(struct damon_ctx *ctx)
389 return list_empty(&ctx->adaptive_targets);
392 static void damon_del_target(struct damon_target *t)
397 void damon_free_target(struct damon_target *t)
399 struct damon_region *r, *next;
401 damon_for_each_region_safe(r, next, t)
402 damon_free_region(r);
406 void damon_destroy_target(struct damon_target *t)
409 damon_free_target(t);
412 unsigned int damon_nr_regions(struct damon_target *t)
414 return t->nr_regions;
417 struct damon_ctx *damon_new_ctx(void)
419 struct damon_ctx *ctx;
421 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
425 ctx->attrs.sample_interval = 5 * 1000;
426 ctx->attrs.aggr_interval = 100 * 1000;
427 ctx->attrs.ops_update_interval = 60 * 1000 * 1000;
429 ktime_get_coarse_ts64(&ctx->last_aggregation);
430 ctx->last_ops_update = ctx->last_aggregation;
432 mutex_init(&ctx->kdamond_lock);
434 ctx->attrs.min_nr_regions = 10;
435 ctx->attrs.max_nr_regions = 1000;
437 INIT_LIST_HEAD(&ctx->adaptive_targets);
438 INIT_LIST_HEAD(&ctx->schemes);
443 static void damon_destroy_targets(struct damon_ctx *ctx)
445 struct damon_target *t, *next_t;
447 if (ctx->ops.cleanup) {
448 ctx->ops.cleanup(ctx);
452 damon_for_each_target_safe(t, next_t, ctx)
453 damon_destroy_target(t);
456 void damon_destroy_ctx(struct damon_ctx *ctx)
458 struct damos *s, *next_s;
460 damon_destroy_targets(ctx);
462 damon_for_each_scheme_safe(s, next_s, ctx)
463 damon_destroy_scheme(s);
468 static unsigned int damon_age_for_new_attrs(unsigned int age,
469 struct damon_attrs *old_attrs, struct damon_attrs *new_attrs)
471 return age * old_attrs->aggr_interval / new_attrs->aggr_interval;
474 /* convert access ratio in bp (per 10,000) to nr_accesses */
475 static unsigned int damon_accesses_bp_to_nr_accesses(
476 unsigned int accesses_bp, struct damon_attrs *attrs)
478 unsigned int max_nr_accesses =
479 attrs->aggr_interval / attrs->sample_interval;
481 return accesses_bp * max_nr_accesses / 10000;
484 /* convert nr_accesses to access ratio in bp (per 10,000) */
485 static unsigned int damon_nr_accesses_to_accesses_bp(
486 unsigned int nr_accesses, struct damon_attrs *attrs)
488 unsigned int max_nr_accesses =
489 attrs->aggr_interval / attrs->sample_interval;
491 return nr_accesses * 10000 / max_nr_accesses;
494 static unsigned int damon_nr_accesses_for_new_attrs(unsigned int nr_accesses,
495 struct damon_attrs *old_attrs, struct damon_attrs *new_attrs)
497 return damon_accesses_bp_to_nr_accesses(
498 damon_nr_accesses_to_accesses_bp(
499 nr_accesses, old_attrs),
503 static void damon_update_monitoring_result(struct damon_region *r,
504 struct damon_attrs *old_attrs, struct damon_attrs *new_attrs)
506 r->nr_accesses = damon_nr_accesses_for_new_attrs(r->nr_accesses,
507 old_attrs, new_attrs);
508 r->age = damon_age_for_new_attrs(r->age, old_attrs, new_attrs);
512 * region->nr_accesses is the number of sampling intervals in the last
513 * aggregation interval that access to the region has found, and region->age is
514 * the number of aggregation intervals that its access pattern has maintained.
515 * For the reason, the real meaning of the two fields depend on current
516 * sampling interval and aggregation interval. This function updates
517 * ->nr_accesses and ->age of given damon_ctx's regions for new damon_attrs.
519 static void damon_update_monitoring_results(struct damon_ctx *ctx,
520 struct damon_attrs *new_attrs)
522 struct damon_attrs *old_attrs = &ctx->attrs;
523 struct damon_target *t;
524 struct damon_region *r;
526 /* if any interval is zero, simply forgive conversion */
527 if (!old_attrs->sample_interval || !old_attrs->aggr_interval ||
528 !new_attrs->sample_interval ||
529 !new_attrs->aggr_interval)
532 damon_for_each_target(t, ctx)
533 damon_for_each_region(r, t)
534 damon_update_monitoring_result(
535 r, old_attrs, new_attrs);
539 * damon_set_attrs() - Set attributes for the monitoring.
540 * @ctx: monitoring context
541 * @attrs: monitoring attributes
543 * This function should not be called while the kdamond is running.
544 * Every time interval is in micro-seconds.
546 * Return: 0 on success, negative error code otherwise.
548 int damon_set_attrs(struct damon_ctx *ctx, struct damon_attrs *attrs)
550 if (attrs->min_nr_regions < 3)
552 if (attrs->min_nr_regions > attrs->max_nr_regions)
554 if (attrs->sample_interval > attrs->aggr_interval)
557 damon_update_monitoring_results(ctx, attrs);
563 * damon_set_schemes() - Set data access monitoring based operation schemes.
564 * @ctx: monitoring context
565 * @schemes: array of the schemes
566 * @nr_schemes: number of entries in @schemes
568 * This function should not be called while the kdamond of the context is
571 void damon_set_schemes(struct damon_ctx *ctx, struct damos **schemes,
574 struct damos *s, *next;
577 damon_for_each_scheme_safe(s, next, ctx)
578 damon_destroy_scheme(s);
579 for (i = 0; i < nr_schemes; i++)
580 damon_add_scheme(ctx, schemes[i]);
584 * damon_nr_running_ctxs() - Return number of currently running contexts.
586 int damon_nr_running_ctxs(void)
590 mutex_lock(&damon_lock);
591 nr_ctxs = nr_running_ctxs;
592 mutex_unlock(&damon_lock);
597 /* Returns the size upper limit for each monitoring region */
598 static unsigned long damon_region_sz_limit(struct damon_ctx *ctx)
600 struct damon_target *t;
601 struct damon_region *r;
602 unsigned long sz = 0;
604 damon_for_each_target(t, ctx) {
605 damon_for_each_region(r, t)
606 sz += damon_sz_region(r);
609 if (ctx->attrs.min_nr_regions)
610 sz /= ctx->attrs.min_nr_regions;
611 if (sz < DAMON_MIN_REGION)
612 sz = DAMON_MIN_REGION;
617 static int kdamond_fn(void *data);
620 * __damon_start() - Starts monitoring with given context.
621 * @ctx: monitoring context
623 * This function should be called while damon_lock is hold.
625 * Return: 0 on success, negative error code otherwise.
627 static int __damon_start(struct damon_ctx *ctx)
631 mutex_lock(&ctx->kdamond_lock);
634 ctx->kdamond = kthread_run(kdamond_fn, ctx, "kdamond.%d",
636 if (IS_ERR(ctx->kdamond)) {
637 err = PTR_ERR(ctx->kdamond);
641 mutex_unlock(&ctx->kdamond_lock);
647 * damon_start() - Starts the monitorings for a given group of contexts.
648 * @ctxs: an array of the pointers for contexts to start monitoring
649 * @nr_ctxs: size of @ctxs
650 * @exclusive: exclusiveness of this contexts group
652 * This function starts a group of monitoring threads for a group of monitoring
653 * contexts. One thread per each context is created and run in parallel. The
654 * caller should handle synchronization between the threads by itself. If
655 * @exclusive is true and a group of threads that created by other
656 * 'damon_start()' call is currently running, this function does nothing but
659 * Return: 0 on success, negative error code otherwise.
661 int damon_start(struct damon_ctx **ctxs, int nr_ctxs, bool exclusive)
666 mutex_lock(&damon_lock);
667 if ((exclusive && nr_running_ctxs) ||
668 (!exclusive && running_exclusive_ctxs)) {
669 mutex_unlock(&damon_lock);
673 for (i = 0; i < nr_ctxs; i++) {
674 err = __damon_start(ctxs[i]);
679 if (exclusive && nr_running_ctxs)
680 running_exclusive_ctxs = true;
681 mutex_unlock(&damon_lock);
687 * __damon_stop() - Stops monitoring of a given context.
688 * @ctx: monitoring context
690 * Return: 0 on success, negative error code otherwise.
692 static int __damon_stop(struct damon_ctx *ctx)
694 struct task_struct *tsk;
696 mutex_lock(&ctx->kdamond_lock);
699 get_task_struct(tsk);
700 mutex_unlock(&ctx->kdamond_lock);
702 put_task_struct(tsk);
705 mutex_unlock(&ctx->kdamond_lock);
711 * damon_stop() - Stops the monitorings for a given group of contexts.
712 * @ctxs: an array of the pointers for contexts to stop monitoring
713 * @nr_ctxs: size of @ctxs
715 * Return: 0 on success, negative error code otherwise.
717 int damon_stop(struct damon_ctx **ctxs, int nr_ctxs)
721 for (i = 0; i < nr_ctxs; i++) {
722 /* nr_running_ctxs is decremented in kdamond_fn */
723 err = __damon_stop(ctxs[i]);
731 * damon_check_reset_time_interval() - Check if a time interval is elapsed.
732 * @baseline: the time to check whether the interval has elapsed since
733 * @interval: the time interval (microseconds)
735 * See whether the given time interval has passed since the given baseline
736 * time. If so, it also updates the baseline to current time for next check.
738 * Return: true if the time interval has passed, or false otherwise.
740 static bool damon_check_reset_time_interval(struct timespec64 *baseline,
741 unsigned long interval)
743 struct timespec64 now;
745 ktime_get_coarse_ts64(&now);
746 if ((timespec64_to_ns(&now) - timespec64_to_ns(baseline)) <
754 * Check whether it is time to flush the aggregated information
756 static bool kdamond_aggregate_interval_passed(struct damon_ctx *ctx)
758 return damon_check_reset_time_interval(&ctx->last_aggregation,
759 ctx->attrs.aggr_interval);
763 * Reset the aggregated monitoring results ('nr_accesses' of each region).
765 static void kdamond_reset_aggregated(struct damon_ctx *c)
767 struct damon_target *t;
768 unsigned int ti = 0; /* target's index */
770 damon_for_each_target(t, c) {
771 struct damon_region *r;
773 damon_for_each_region(r, t) {
774 trace_damon_aggregated(t, ti, r, damon_nr_regions(t));
775 r->last_nr_accesses = r->nr_accesses;
782 static void damon_split_region_at(struct damon_target *t,
783 struct damon_region *r, unsigned long sz_r);
785 static bool __damos_valid_target(struct damon_region *r, struct damos *s)
789 sz = damon_sz_region(r);
790 return s->pattern.min_sz_region <= sz &&
791 sz <= s->pattern.max_sz_region &&
792 s->pattern.min_nr_accesses <= r->nr_accesses &&
793 r->nr_accesses <= s->pattern.max_nr_accesses &&
794 s->pattern.min_age_region <= r->age &&
795 r->age <= s->pattern.max_age_region;
798 static bool damos_valid_target(struct damon_ctx *c, struct damon_target *t,
799 struct damon_region *r, struct damos *s)
801 bool ret = __damos_valid_target(r, s);
803 if (!ret || !s->quota.esz || !c->ops.get_scheme_score)
806 return c->ops.get_scheme_score(c, t, r, s) >= s->quota.min_score;
810 * damos_skip_charged_region() - Check if the given region or starting part of
811 * it is already charged for the DAMOS quota.
812 * @t: The target of the region.
813 * @rp: The pointer to the region.
814 * @s: The scheme to be applied.
816 * If a quota of a scheme has exceeded in a quota charge window, the scheme's
817 * action would applied to only a part of the target access pattern fulfilling
818 * regions. To avoid applying the scheme action to only already applied
819 * regions, DAMON skips applying the scheme action to the regions that charged
820 * in the previous charge window.
822 * This function checks if a given region should be skipped or not for the
823 * reason. If only the starting part of the region has previously charged,
824 * this function splits the region into two so that the second one covers the
825 * area that not charged in the previous charge widnow and saves the second
826 * region in *rp and returns false, so that the caller can apply DAMON action
829 * Return: true if the region should be entirely skipped, false otherwise.
831 static bool damos_skip_charged_region(struct damon_target *t,
832 struct damon_region **rp, struct damos *s)
834 struct damon_region *r = *rp;
835 struct damos_quota *quota = &s->quota;
836 unsigned long sz_to_skip;
838 /* Skip previously charged regions */
839 if (quota->charge_target_from) {
840 if (t != quota->charge_target_from)
842 if (r == damon_last_region(t)) {
843 quota->charge_target_from = NULL;
844 quota->charge_addr_from = 0;
847 if (quota->charge_addr_from &&
848 r->ar.end <= quota->charge_addr_from)
851 if (quota->charge_addr_from && r->ar.start <
852 quota->charge_addr_from) {
853 sz_to_skip = ALIGN_DOWN(quota->charge_addr_from -
854 r->ar.start, DAMON_MIN_REGION);
856 if (damon_sz_region(r) <= DAMON_MIN_REGION)
858 sz_to_skip = DAMON_MIN_REGION;
860 damon_split_region_at(t, r, sz_to_skip);
861 r = damon_next_region(r);
864 quota->charge_target_from = NULL;
865 quota->charge_addr_from = 0;
870 static void damos_update_stat(struct damos *s,
871 unsigned long sz_tried, unsigned long sz_applied)
874 s->stat.sz_tried += sz_tried;
876 s->stat.nr_applied++;
877 s->stat.sz_applied += sz_applied;
880 static void damos_apply_scheme(struct damon_ctx *c, struct damon_target *t,
881 struct damon_region *r, struct damos *s)
883 struct damos_quota *quota = &s->quota;
884 unsigned long sz = damon_sz_region(r);
885 struct timespec64 begin, end;
886 unsigned long sz_applied = 0;
889 if (c->ops.apply_scheme) {
890 if (quota->esz && quota->charged_sz + sz > quota->esz) {
891 sz = ALIGN_DOWN(quota->esz - quota->charged_sz,
895 damon_split_region_at(t, r, sz);
897 ktime_get_coarse_ts64(&begin);
898 if (c->callback.before_damos_apply)
899 err = c->callback.before_damos_apply(c, t, r, s);
901 sz_applied = c->ops.apply_scheme(c, t, r, s);
902 ktime_get_coarse_ts64(&end);
903 quota->total_charged_ns += timespec64_to_ns(&end) -
904 timespec64_to_ns(&begin);
905 quota->charged_sz += sz;
906 if (quota->esz && quota->charged_sz >= quota->esz) {
907 quota->charge_target_from = t;
908 quota->charge_addr_from = r->ar.end + 1;
911 if (s->action != DAMOS_STAT)
915 damos_update_stat(s, sz, sz_applied);
918 static void damon_do_apply_schemes(struct damon_ctx *c,
919 struct damon_target *t,
920 struct damon_region *r)
924 damon_for_each_scheme(s, c) {
925 struct damos_quota *quota = &s->quota;
927 if (!s->wmarks.activated)
930 /* Check the quota */
931 if (quota->esz && quota->charged_sz >= quota->esz)
934 if (damos_skip_charged_region(t, &r, s))
937 if (!damos_valid_target(c, t, r, s))
940 damos_apply_scheme(c, t, r, s);
944 /* Shouldn't be called if quota->ms and quota->sz are zero */
945 static void damos_set_effective_quota(struct damos_quota *quota)
947 unsigned long throughput;
951 quota->esz = quota->sz;
955 if (quota->total_charged_ns)
956 throughput = quota->total_charged_sz * 1000000 /
957 quota->total_charged_ns;
959 throughput = PAGE_SIZE * 1024;
960 esz = throughput * quota->ms;
962 if (quota->sz && quota->sz < esz)
967 static void damos_adjust_quota(struct damon_ctx *c, struct damos *s)
969 struct damos_quota *quota = &s->quota;
970 struct damon_target *t;
971 struct damon_region *r;
972 unsigned long cumulated_sz;
973 unsigned int score, max_score = 0;
975 if (!quota->ms && !quota->sz)
978 /* New charge window starts */
979 if (time_after_eq(jiffies, quota->charged_from +
980 msecs_to_jiffies(quota->reset_interval))) {
981 if (quota->esz && quota->charged_sz >= quota->esz)
982 s->stat.qt_exceeds++;
983 quota->total_charged_sz += quota->charged_sz;
984 quota->charged_from = jiffies;
985 quota->charged_sz = 0;
986 damos_set_effective_quota(quota);
989 if (!c->ops.get_scheme_score)
992 /* Fill up the score histogram */
993 memset(quota->histogram, 0, sizeof(quota->histogram));
994 damon_for_each_target(t, c) {
995 damon_for_each_region(r, t) {
996 if (!__damos_valid_target(r, s))
998 score = c->ops.get_scheme_score(c, t, r, s);
999 quota->histogram[score] += damon_sz_region(r);
1000 if (score > max_score)
1005 /* Set the min score limit */
1006 for (cumulated_sz = 0, score = max_score; ; score--) {
1007 cumulated_sz += quota->histogram[score];
1008 if (cumulated_sz >= quota->esz || !score)
1011 quota->min_score = score;
1014 static void kdamond_apply_schemes(struct damon_ctx *c)
1016 struct damon_target *t;
1017 struct damon_region *r, *next_r;
1020 damon_for_each_scheme(s, c) {
1021 if (!s->wmarks.activated)
1024 damos_adjust_quota(c, s);
1027 damon_for_each_target(t, c) {
1028 damon_for_each_region_safe(r, next_r, t)
1029 damon_do_apply_schemes(c, t, r);
1034 * Merge two adjacent regions into one region
1036 static void damon_merge_two_regions(struct damon_target *t,
1037 struct damon_region *l, struct damon_region *r)
1039 unsigned long sz_l = damon_sz_region(l), sz_r = damon_sz_region(r);
1041 l->nr_accesses = (l->nr_accesses * sz_l + r->nr_accesses * sz_r) /
1043 l->age = (l->age * sz_l + r->age * sz_r) / (sz_l + sz_r);
1044 l->ar.end = r->ar.end;
1045 damon_destroy_region(r, t);
1049 * Merge adjacent regions having similar access frequencies
1051 * t target affected by this merge operation
1052 * thres '->nr_accesses' diff threshold for the merge
1053 * sz_limit size upper limit of each region
1055 static void damon_merge_regions_of(struct damon_target *t, unsigned int thres,
1056 unsigned long sz_limit)
1058 struct damon_region *r, *prev = NULL, *next;
1060 damon_for_each_region_safe(r, next, t) {
1061 if (abs(r->nr_accesses - r->last_nr_accesses) > thres)
1066 if (prev && prev->ar.end == r->ar.start &&
1067 abs(prev->nr_accesses - r->nr_accesses) <= thres &&
1068 damon_sz_region(prev) + damon_sz_region(r) <= sz_limit)
1069 damon_merge_two_regions(t, prev, r);
1076 * Merge adjacent regions having similar access frequencies
1078 * threshold '->nr_accesses' diff threshold for the merge
1079 * sz_limit size upper limit of each region
1081 * This function merges monitoring target regions which are adjacent and their
1082 * access frequencies are similar. This is for minimizing the monitoring
1083 * overhead under the dynamically changeable access pattern. If a merge was
1084 * unnecessarily made, later 'kdamond_split_regions()' will revert it.
1086 static void kdamond_merge_regions(struct damon_ctx *c, unsigned int threshold,
1087 unsigned long sz_limit)
1089 struct damon_target *t;
1091 damon_for_each_target(t, c)
1092 damon_merge_regions_of(t, threshold, sz_limit);
1096 * Split a region in two
1098 * r the region to be split
1099 * sz_r size of the first sub-region that will be made
1101 static void damon_split_region_at(struct damon_target *t,
1102 struct damon_region *r, unsigned long sz_r)
1104 struct damon_region *new;
1106 new = damon_new_region(r->ar.start + sz_r, r->ar.end);
1110 r->ar.end = new->ar.start;
1113 new->last_nr_accesses = r->last_nr_accesses;
1115 damon_insert_region(new, r, damon_next_region(r), t);
1118 /* Split every region in the given target into 'nr_subs' regions */
1119 static void damon_split_regions_of(struct damon_target *t, int nr_subs)
1121 struct damon_region *r, *next;
1122 unsigned long sz_region, sz_sub = 0;
1125 damon_for_each_region_safe(r, next, t) {
1126 sz_region = damon_sz_region(r);
1128 for (i = 0; i < nr_subs - 1 &&
1129 sz_region > 2 * DAMON_MIN_REGION; i++) {
1131 * Randomly select size of left sub-region to be at
1132 * least 10 percent and at most 90% of original region
1134 sz_sub = ALIGN_DOWN(damon_rand(1, 10) *
1135 sz_region / 10, DAMON_MIN_REGION);
1136 /* Do not allow blank region */
1137 if (sz_sub == 0 || sz_sub >= sz_region)
1140 damon_split_region_at(t, r, sz_sub);
1147 * Split every target region into randomly-sized small regions
1149 * This function splits every target region into random-sized small regions if
1150 * current total number of the regions is equal or smaller than half of the
1151 * user-specified maximum number of regions. This is for maximizing the
1152 * monitoring accuracy under the dynamically changeable access patterns. If a
1153 * split was unnecessarily made, later 'kdamond_merge_regions()' will revert
1156 static void kdamond_split_regions(struct damon_ctx *ctx)
1158 struct damon_target *t;
1159 unsigned int nr_regions = 0;
1160 static unsigned int last_nr_regions;
1161 int nr_subregions = 2;
1163 damon_for_each_target(t, ctx)
1164 nr_regions += damon_nr_regions(t);
1166 if (nr_regions > ctx->attrs.max_nr_regions / 2)
1169 /* Maybe the middle of the region has different access frequency */
1170 if (last_nr_regions == nr_regions &&
1171 nr_regions < ctx->attrs.max_nr_regions / 3)
1174 damon_for_each_target(t, ctx)
1175 damon_split_regions_of(t, nr_subregions);
1177 last_nr_regions = nr_regions;
1181 * Check whether it is time to check and apply the operations-related data
1184 * Returns true if it is.
1186 static bool kdamond_need_update_operations(struct damon_ctx *ctx)
1188 return damon_check_reset_time_interval(&ctx->last_ops_update,
1189 ctx->attrs.ops_update_interval);
1193 * Check whether current monitoring should be stopped
1195 * The monitoring is stopped when either the user requested to stop, or all
1196 * monitoring targets are invalid.
1198 * Returns true if need to stop current monitoring.
1200 static bool kdamond_need_stop(struct damon_ctx *ctx)
1202 struct damon_target *t;
1204 if (kthread_should_stop())
1207 if (!ctx->ops.target_valid)
1210 damon_for_each_target(t, ctx) {
1211 if (ctx->ops.target_valid(t))
1218 static unsigned long damos_wmark_metric_value(enum damos_wmark_metric metric)
1223 case DAMOS_WMARK_FREE_MEM_RATE:
1225 return i.freeram * 1000 / i.totalram;
1233 * Returns zero if the scheme is active. Else, returns time to wait for next
1234 * watermark check in micro-seconds.
1236 static unsigned long damos_wmark_wait_us(struct damos *scheme)
1238 unsigned long metric;
1240 if (scheme->wmarks.metric == DAMOS_WMARK_NONE)
1243 metric = damos_wmark_metric_value(scheme->wmarks.metric);
1244 /* higher than high watermark or lower than low watermark */
1245 if (metric > scheme->wmarks.high || scheme->wmarks.low > metric) {
1246 if (scheme->wmarks.activated)
1247 pr_debug("deactivate a scheme (%d) for %s wmark\n",
1249 metric > scheme->wmarks.high ?
1251 scheme->wmarks.activated = false;
1252 return scheme->wmarks.interval;
1255 /* inactive and higher than middle watermark */
1256 if ((scheme->wmarks.high >= metric && metric >= scheme->wmarks.mid) &&
1257 !scheme->wmarks.activated)
1258 return scheme->wmarks.interval;
1260 if (!scheme->wmarks.activated)
1261 pr_debug("activate a scheme (%d)\n", scheme->action);
1262 scheme->wmarks.activated = true;
1266 static void kdamond_usleep(unsigned long usecs)
1268 /* See Documentation/timers/timers-howto.rst for the thresholds */
1269 if (usecs > 20 * USEC_PER_MSEC)
1270 schedule_timeout_idle(usecs_to_jiffies(usecs));
1272 usleep_idle_range(usecs, usecs + 1);
1275 /* Returns negative error code if it's not activated but should return */
1276 static int kdamond_wait_activation(struct damon_ctx *ctx)
1279 unsigned long wait_time;
1280 unsigned long min_wait_time = 0;
1281 bool init_wait_time = false;
1283 while (!kdamond_need_stop(ctx)) {
1284 damon_for_each_scheme(s, ctx) {
1285 wait_time = damos_wmark_wait_us(s);
1286 if (!init_wait_time || wait_time < min_wait_time) {
1287 init_wait_time = true;
1288 min_wait_time = wait_time;
1294 kdamond_usleep(min_wait_time);
1296 if (ctx->callback.after_wmarks_check &&
1297 ctx->callback.after_wmarks_check(ctx))
1304 * The monitoring daemon that runs as a kernel thread
1306 static int kdamond_fn(void *data)
1308 struct damon_ctx *ctx = data;
1309 struct damon_target *t;
1310 struct damon_region *r, *next;
1311 unsigned int max_nr_accesses = 0;
1312 unsigned long sz_limit = 0;
1314 pr_debug("kdamond (%d) starts\n", current->pid);
1318 if (ctx->callback.before_start && ctx->callback.before_start(ctx))
1321 sz_limit = damon_region_sz_limit(ctx);
1323 while (!kdamond_need_stop(ctx)) {
1324 if (kdamond_wait_activation(ctx))
1327 if (ctx->ops.prepare_access_checks)
1328 ctx->ops.prepare_access_checks(ctx);
1329 if (ctx->callback.after_sampling &&
1330 ctx->callback.after_sampling(ctx))
1333 kdamond_usleep(ctx->attrs.sample_interval);
1335 if (ctx->ops.check_accesses)
1336 max_nr_accesses = ctx->ops.check_accesses(ctx);
1338 if (kdamond_aggregate_interval_passed(ctx)) {
1339 kdamond_merge_regions(ctx,
1340 max_nr_accesses / 10,
1342 if (ctx->callback.after_aggregation &&
1343 ctx->callback.after_aggregation(ctx))
1345 if (!list_empty(&ctx->schemes))
1346 kdamond_apply_schemes(ctx);
1347 kdamond_reset_aggregated(ctx);
1348 kdamond_split_regions(ctx);
1349 if (ctx->ops.reset_aggregated)
1350 ctx->ops.reset_aggregated(ctx);
1353 if (kdamond_need_update_operations(ctx)) {
1354 if (ctx->ops.update)
1355 ctx->ops.update(ctx);
1356 sz_limit = damon_region_sz_limit(ctx);
1360 damon_for_each_target(t, ctx) {
1361 damon_for_each_region_safe(r, next, t)
1362 damon_destroy_region(r, t);
1365 if (ctx->callback.before_terminate)
1366 ctx->callback.before_terminate(ctx);
1367 if (ctx->ops.cleanup)
1368 ctx->ops.cleanup(ctx);
1370 pr_debug("kdamond (%d) finishes\n", current->pid);
1371 mutex_lock(&ctx->kdamond_lock);
1372 ctx->kdamond = NULL;
1373 mutex_unlock(&ctx->kdamond_lock);
1375 mutex_lock(&damon_lock);
1377 if (!nr_running_ctxs && running_exclusive_ctxs)
1378 running_exclusive_ctxs = false;
1379 mutex_unlock(&damon_lock);
1385 * struct damon_system_ram_region - System RAM resource address region of
1387 * @start: Start address of the region (inclusive).
1388 * @end: End address of the region (exclusive).
1390 struct damon_system_ram_region {
1391 unsigned long start;
1395 static int walk_system_ram(struct resource *res, void *arg)
1397 struct damon_system_ram_region *a = arg;
1399 if (a->end - a->start < resource_size(res)) {
1400 a->start = res->start;
1407 * Find biggest 'System RAM' resource and store its start and end address in
1408 * @start and @end, respectively. If no System RAM is found, returns false.
1410 static bool damon_find_biggest_system_ram(unsigned long *start,
1414 struct damon_system_ram_region arg = {};
1416 walk_system_ram_res(0, ULONG_MAX, &arg, walk_system_ram);
1417 if (arg.end <= arg.start)
1426 * damon_set_region_biggest_system_ram_default() - Set the region of the given
1427 * monitoring target as requested, or biggest 'System RAM'.
1428 * @t: The monitoring target to set the region.
1429 * @start: The pointer to the start address of the region.
1430 * @end: The pointer to the end address of the region.
1432 * This function sets the region of @t as requested by @start and @end. If the
1433 * values of @start and @end are zero, however, this function finds the biggest
1434 * 'System RAM' resource and sets the region to cover the resource. In the
1435 * latter case, this function saves the start and end addresses of the resource
1436 * in @start and @end, respectively.
1438 * Return: 0 on success, negative error code otherwise.
1440 int damon_set_region_biggest_system_ram_default(struct damon_target *t,
1441 unsigned long *start, unsigned long *end)
1443 struct damon_addr_range addr_range;
1448 if (!*start && !*end &&
1449 !damon_find_biggest_system_ram(start, end))
1452 addr_range.start = *start;
1453 addr_range.end = *end;
1454 return damon_set_regions(t, &addr_range, 1);
1457 static int __init damon_init(void)
1459 damon_region_cache = KMEM_CACHE(damon_region, 0);
1460 if (unlikely(!damon_region_cache)) {
1461 pr_err("creating damon_region_cache fails\n");
1468 subsys_initcall(damon_init);
1470 #include "core-test.h"