mm/damon/core: use number of passed access sampling as a timer
[platform/kernel/linux-rpi.git] / mm / damon / core.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Data Access Monitor
4  *
5  * Author: SeongJae Park <sjpark@amazon.de>
6  */
7
8 #define pr_fmt(fmt) "damon: " fmt
9
10 #include <linux/damon.h>
11 #include <linux/delay.h>
12 #include <linux/kthread.h>
13 #include <linux/mm.h>
14 #include <linux/slab.h>
15 #include <linux/string.h>
16
17 #define CREATE_TRACE_POINTS
18 #include <trace/events/damon.h>
19
20 #ifdef CONFIG_DAMON_KUNIT_TEST
21 #undef DAMON_MIN_REGION
22 #define DAMON_MIN_REGION 1
23 #endif
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         mutex_lock(&damon_ops_lock);
78         /* Fail for already registered ops */
79         if (__damon_is_registered_ops(ops->id)) {
80                 err = -EINVAL;
81                 goto out;
82         }
83         damon_registered_ops[ops->id] = *ops;
84 out:
85         mutex_unlock(&damon_ops_lock);
86         return err;
87 }
88
89 /**
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.
93  *
94  * This function finds registered monitoring operations set of @id and make
95  * @ctx to use it.
96  *
97  * Return: 0 on success, negative error code otherwise.
98  */
99 int damon_select_ops(struct damon_ctx *ctx, enum damon_ops_id id)
100 {
101         int err = 0;
102
103         if (id >= NR_DAMON_OPS)
104                 return -EINVAL;
105
106         mutex_lock(&damon_ops_lock);
107         if (!__damon_is_registered_ops(id))
108                 err = -EINVAL;
109         else
110                 ctx->ops = damon_registered_ops[id];
111         mutex_unlock(&damon_ops_lock);
112         return err;
113 }
114
115 /*
116  * Construct a damon_region struct
117  *
118  * Returns the pointer to the new struct if success, or NULL otherwise
119  */
120 struct damon_region *damon_new_region(unsigned long start, unsigned long end)
121 {
122         struct damon_region *region;
123
124         region = kmem_cache_alloc(damon_region_cache, GFP_KERNEL);
125         if (!region)
126                 return NULL;
127
128         region->ar.start = start;
129         region->ar.end = end;
130         region->nr_accesses = 0;
131         INIT_LIST_HEAD(&region->list);
132
133         region->age = 0;
134         region->last_nr_accesses = 0;
135
136         return region;
137 }
138
139 void damon_add_region(struct damon_region *r, struct damon_target *t)
140 {
141         list_add_tail(&r->list, &t->regions_list);
142         t->nr_regions++;
143 }
144
145 static void damon_del_region(struct damon_region *r, struct damon_target *t)
146 {
147         list_del(&r->list);
148         t->nr_regions--;
149 }
150
151 static void damon_free_region(struct damon_region *r)
152 {
153         kmem_cache_free(damon_region_cache, r);
154 }
155
156 void damon_destroy_region(struct damon_region *r, struct damon_target *t)
157 {
158         damon_del_region(r, t);
159         damon_free_region(r);
160 }
161
162 /*
163  * Check whether a region is intersecting an address range
164  *
165  * Returns true if it is.
166  */
167 static bool damon_intersect(struct damon_region *r,
168                 struct damon_addr_range *re)
169 {
170         return !(r->ar.end <= re->start || re->end <= r->ar.start);
171 }
172
173 /*
174  * Fill holes in regions with new regions.
175  */
176 static int damon_fill_regions_holes(struct damon_region *first,
177                 struct damon_region *last, struct damon_target *t)
178 {
179         struct damon_region *r = first;
180
181         damon_for_each_region_from(r, t) {
182                 struct damon_region *next, *newr;
183
184                 if (r == last)
185                         break;
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);
189                         if (!newr)
190                                 return -ENOMEM;
191                         damon_insert_region(newr, r, next, t);
192                 }
193         }
194         return 0;
195 }
196
197 /*
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.
202  *
203  * This function adds new regions to, or modify existing regions of a
204  * monitoring target to fit in specific ranges.
205  *
206  * Return: 0 if success, or negative error code otherwise.
207  */
208 int damon_set_regions(struct damon_target *t, struct damon_addr_range *ranges,
209                 unsigned int nr_ranges)
210 {
211         struct damon_region *r, *next;
212         unsigned int i;
213         int err;
214
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]))
219                                 break;
220                 }
221                 if (i == nr_ranges)
222                         damon_destroy_region(r, t);
223         }
224
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;
230
231                 range = &ranges[i];
232                 /* Get the first/last regions intersecting with the range */
233                 damon_for_each_region_from(r, t) {
234                         if (damon_intersect(r, range)) {
235                                 if (!first)
236                                         first = r;
237                                 last = r;
238                         }
239                         if (r->ar.start >= range->end)
240                                 break;
241                 }
242                 if (!first) {
243                         /* no region intersects with this range */
244                         newr = damon_new_region(
245                                         ALIGN_DOWN(range->start,
246                                                 DAMON_MIN_REGION),
247                                         ALIGN(range->end, DAMON_MIN_REGION));
248                         if (!newr)
249                                 return -ENOMEM;
250                         damon_insert_region(newr, damon_prev_region(r), r, t);
251                 } else {
252                         /* resize intersecting regions to fit in this range */
253                         first->ar.start = ALIGN_DOWN(range->start,
254                                         DAMON_MIN_REGION);
255                         last->ar.end = ALIGN(range->end, DAMON_MIN_REGION);
256
257                         /* fill possible holes in the range */
258                         err = damon_fill_regions_holes(first, last, t);
259                         if (err)
260                                 return err;
261                 }
262         }
263         return 0;
264 }
265
266 struct damos_filter *damos_new_filter(enum damos_filter_type type,
267                 bool matching)
268 {
269         struct damos_filter *filter;
270
271         filter = kmalloc(sizeof(*filter), GFP_KERNEL);
272         if (!filter)
273                 return NULL;
274         filter->type = type;
275         filter->matching = matching;
276         INIT_LIST_HEAD(&filter->list);
277         return filter;
278 }
279
280 void damos_add_filter(struct damos *s, struct damos_filter *f)
281 {
282         list_add_tail(&f->list, &s->filters);
283 }
284
285 static void damos_del_filter(struct damos_filter *f)
286 {
287         list_del(&f->list);
288 }
289
290 static void damos_free_filter(struct damos_filter *f)
291 {
292         kfree(f);
293 }
294
295 void damos_destroy_filter(struct damos_filter *f)
296 {
297         damos_del_filter(f);
298         damos_free_filter(f);
299 }
300
301 /* initialize private fields of damos_quota and return the pointer */
302 static struct damos_quota *damos_quota_init_priv(struct damos_quota *quota)
303 {
304         quota->total_charged_sz = 0;
305         quota->total_charged_ns = 0;
306         quota->esz = 0;
307         quota->charged_sz = 0;
308         quota->charged_from = 0;
309         quota->charge_target_from = NULL;
310         quota->charge_addr_from = 0;
311         return quota;
312 }
313
314 struct damos *damon_new_scheme(struct damos_access_pattern *pattern,
315                         enum damos_action action, struct damos_quota *quota,
316                         struct damos_watermarks *wmarks)
317 {
318         struct damos *scheme;
319
320         scheme = kmalloc(sizeof(*scheme), GFP_KERNEL);
321         if (!scheme)
322                 return NULL;
323         scheme->pattern = *pattern;
324         scheme->action = action;
325         INIT_LIST_HEAD(&scheme->filters);
326         scheme->stat = (struct damos_stat){};
327         INIT_LIST_HEAD(&scheme->list);
328
329         scheme->quota = *(damos_quota_init_priv(quota));
330
331         scheme->wmarks = *wmarks;
332         scheme->wmarks.activated = true;
333
334         return scheme;
335 }
336
337 void damon_add_scheme(struct damon_ctx *ctx, struct damos *s)
338 {
339         list_add_tail(&s->list, &ctx->schemes);
340 }
341
342 static void damon_del_scheme(struct damos *s)
343 {
344         list_del(&s->list);
345 }
346
347 static void damon_free_scheme(struct damos *s)
348 {
349         kfree(s);
350 }
351
352 void damon_destroy_scheme(struct damos *s)
353 {
354         struct damos_filter *f, *next;
355
356         damos_for_each_filter_safe(f, next, s)
357                 damos_destroy_filter(f);
358         damon_del_scheme(s);
359         damon_free_scheme(s);
360 }
361
362 /*
363  * Construct a damon_target struct
364  *
365  * Returns the pointer to the new struct if success, or NULL otherwise
366  */
367 struct damon_target *damon_new_target(void)
368 {
369         struct damon_target *t;
370
371         t = kmalloc(sizeof(*t), GFP_KERNEL);
372         if (!t)
373                 return NULL;
374
375         t->pid = NULL;
376         t->nr_regions = 0;
377         INIT_LIST_HEAD(&t->regions_list);
378         INIT_LIST_HEAD(&t->list);
379
380         return t;
381 }
382
383 void damon_add_target(struct damon_ctx *ctx, struct damon_target *t)
384 {
385         list_add_tail(&t->list, &ctx->adaptive_targets);
386 }
387
388 bool damon_targets_empty(struct damon_ctx *ctx)
389 {
390         return list_empty(&ctx->adaptive_targets);
391 }
392
393 static void damon_del_target(struct damon_target *t)
394 {
395         list_del(&t->list);
396 }
397
398 void damon_free_target(struct damon_target *t)
399 {
400         struct damon_region *r, *next;
401
402         damon_for_each_region_safe(r, next, t)
403                 damon_free_region(r);
404         kfree(t);
405 }
406
407 void damon_destroy_target(struct damon_target *t)
408 {
409         damon_del_target(t);
410         damon_free_target(t);
411 }
412
413 unsigned int damon_nr_regions(struct damon_target *t)
414 {
415         return t->nr_regions;
416 }
417
418 struct damon_ctx *damon_new_ctx(void)
419 {
420         struct damon_ctx *ctx;
421
422         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
423         if (!ctx)
424                 return NULL;
425
426         ctx->attrs.sample_interval = 5 * 1000;
427         ctx->attrs.aggr_interval = 100 * 1000;
428         ctx->attrs.ops_update_interval = 60 * 1000 * 1000;
429
430         ctx->passed_sample_intervals = 0;
431         /* These will be set from kdamond_init_intervals_sis() */
432         ctx->next_aggregation_sis = 0;
433         ctx->next_ops_update_sis = 0;
434
435         mutex_init(&ctx->kdamond_lock);
436
437         ctx->attrs.min_nr_regions = 10;
438         ctx->attrs.max_nr_regions = 1000;
439
440         INIT_LIST_HEAD(&ctx->adaptive_targets);
441         INIT_LIST_HEAD(&ctx->schemes);
442
443         return ctx;
444 }
445
446 static void damon_destroy_targets(struct damon_ctx *ctx)
447 {
448         struct damon_target *t, *next_t;
449
450         if (ctx->ops.cleanup) {
451                 ctx->ops.cleanup(ctx);
452                 return;
453         }
454
455         damon_for_each_target_safe(t, next_t, ctx)
456                 damon_destroy_target(t);
457 }
458
459 void damon_destroy_ctx(struct damon_ctx *ctx)
460 {
461         struct damos *s, *next_s;
462
463         damon_destroy_targets(ctx);
464
465         damon_for_each_scheme_safe(s, next_s, ctx)
466                 damon_destroy_scheme(s);
467
468         kfree(ctx);
469 }
470
471 static unsigned int damon_age_for_new_attrs(unsigned int age,
472                 struct damon_attrs *old_attrs, struct damon_attrs *new_attrs)
473 {
474         return age * old_attrs->aggr_interval / new_attrs->aggr_interval;
475 }
476
477 /* convert access ratio in bp (per 10,000) to nr_accesses */
478 static unsigned int damon_accesses_bp_to_nr_accesses(
479                 unsigned int accesses_bp, struct damon_attrs *attrs)
480 {
481         return accesses_bp * damon_max_nr_accesses(attrs) / 10000;
482 }
483
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)
487 {
488         return nr_accesses * 10000 / damon_max_nr_accesses(attrs);
489 }
490
491 static unsigned int damon_nr_accesses_for_new_attrs(unsigned int nr_accesses,
492                 struct damon_attrs *old_attrs, struct damon_attrs *new_attrs)
493 {
494         return damon_accesses_bp_to_nr_accesses(
495                         damon_nr_accesses_to_accesses_bp(
496                                 nr_accesses, old_attrs),
497                         new_attrs);
498 }
499
500 static void damon_update_monitoring_result(struct damon_region *r,
501                 struct damon_attrs *old_attrs, struct damon_attrs *new_attrs)
502 {
503         r->nr_accesses = damon_nr_accesses_for_new_attrs(r->nr_accesses,
504                         old_attrs, new_attrs);
505         r->age = damon_age_for_new_attrs(r->age, old_attrs, new_attrs);
506 }
507
508 /*
509  * region->nr_accesses is the number of sampling intervals in the last
510  * aggregation interval that access to the region has found, and region->age is
511  * the number of aggregation intervals that its access pattern has maintained.
512  * For the reason, the real meaning of the two fields depend on current
513  * sampling interval and aggregation interval.  This function updates
514  * ->nr_accesses and ->age of given damon_ctx's regions for new damon_attrs.
515  */
516 static void damon_update_monitoring_results(struct damon_ctx *ctx,
517                 struct damon_attrs *new_attrs)
518 {
519         struct damon_attrs *old_attrs = &ctx->attrs;
520         struct damon_target *t;
521         struct damon_region *r;
522
523         /* if any interval is zero, simply forgive conversion */
524         if (!old_attrs->sample_interval || !old_attrs->aggr_interval ||
525                         !new_attrs->sample_interval ||
526                         !new_attrs->aggr_interval)
527                 return;
528
529         damon_for_each_target(t, ctx)
530                 damon_for_each_region(r, t)
531                         damon_update_monitoring_result(
532                                         r, old_attrs, new_attrs);
533 }
534
535 /**
536  * damon_set_attrs() - Set attributes for the monitoring.
537  * @ctx:                monitoring context
538  * @attrs:              monitoring attributes
539  *
540  * This function should not be called while the kdamond is running.
541  * Every time interval is in micro-seconds.
542  *
543  * Return: 0 on success, negative error code otherwise.
544  */
545 int damon_set_attrs(struct damon_ctx *ctx, struct damon_attrs *attrs)
546 {
547         unsigned long sample_interval = attrs->sample_interval ?
548                 attrs->sample_interval : 1;
549
550         if (attrs->min_nr_regions < 3)
551                 return -EINVAL;
552         if (attrs->min_nr_regions > attrs->max_nr_regions)
553                 return -EINVAL;
554         if (attrs->sample_interval > attrs->aggr_interval)
555                 return -EINVAL;
556
557         ctx->next_aggregation_sis = ctx->passed_sample_intervals +
558                 attrs->aggr_interval / sample_interval;
559         ctx->next_ops_update_sis = ctx->passed_sample_intervals +
560                 attrs->ops_update_interval / sample_interval;
561
562         damon_update_monitoring_results(ctx, attrs);
563         ctx->attrs = *attrs;
564         return 0;
565 }
566
567 /**
568  * damon_set_schemes() - Set data access monitoring based operation schemes.
569  * @ctx:        monitoring context
570  * @schemes:    array of the schemes
571  * @nr_schemes: number of entries in @schemes
572  *
573  * This function should not be called while the kdamond of the context is
574  * running.
575  */
576 void damon_set_schemes(struct damon_ctx *ctx, struct damos **schemes,
577                         ssize_t nr_schemes)
578 {
579         struct damos *s, *next;
580         ssize_t i;
581
582         damon_for_each_scheme_safe(s, next, ctx)
583                 damon_destroy_scheme(s);
584         for (i = 0; i < nr_schemes; i++)
585                 damon_add_scheme(ctx, schemes[i]);
586 }
587
588 /**
589  * damon_nr_running_ctxs() - Return number of currently running contexts.
590  */
591 int damon_nr_running_ctxs(void)
592 {
593         int nr_ctxs;
594
595         mutex_lock(&damon_lock);
596         nr_ctxs = nr_running_ctxs;
597         mutex_unlock(&damon_lock);
598
599         return nr_ctxs;
600 }
601
602 /* Returns the size upper limit for each monitoring region */
603 static unsigned long damon_region_sz_limit(struct damon_ctx *ctx)
604 {
605         struct damon_target *t;
606         struct damon_region *r;
607         unsigned long sz = 0;
608
609         damon_for_each_target(t, ctx) {
610                 damon_for_each_region(r, t)
611                         sz += damon_sz_region(r);
612         }
613
614         if (ctx->attrs.min_nr_regions)
615                 sz /= ctx->attrs.min_nr_regions;
616         if (sz < DAMON_MIN_REGION)
617                 sz = DAMON_MIN_REGION;
618
619         return sz;
620 }
621
622 static int kdamond_fn(void *data);
623
624 /*
625  * __damon_start() - Starts monitoring with given context.
626  * @ctx:        monitoring context
627  *
628  * This function should be called while damon_lock is hold.
629  *
630  * Return: 0 on success, negative error code otherwise.
631  */
632 static int __damon_start(struct damon_ctx *ctx)
633 {
634         int err = -EBUSY;
635
636         mutex_lock(&ctx->kdamond_lock);
637         if (!ctx->kdamond) {
638                 err = 0;
639                 ctx->kdamond = kthread_run(kdamond_fn, ctx, "kdamond.%d",
640                                 nr_running_ctxs);
641                 if (IS_ERR(ctx->kdamond)) {
642                         err = PTR_ERR(ctx->kdamond);
643                         ctx->kdamond = NULL;
644                 }
645         }
646         mutex_unlock(&ctx->kdamond_lock);
647
648         return err;
649 }
650
651 /**
652  * damon_start() - Starts the monitorings for a given group of contexts.
653  * @ctxs:       an array of the pointers for contexts to start monitoring
654  * @nr_ctxs:    size of @ctxs
655  * @exclusive:  exclusiveness of this contexts group
656  *
657  * This function starts a group of monitoring threads for a group of monitoring
658  * contexts.  One thread per each context is created and run in parallel.  The
659  * caller should handle synchronization between the threads by itself.  If
660  * @exclusive is true and a group of threads that created by other
661  * 'damon_start()' call is currently running, this function does nothing but
662  * returns -EBUSY.
663  *
664  * Return: 0 on success, negative error code otherwise.
665  */
666 int damon_start(struct damon_ctx **ctxs, int nr_ctxs, bool exclusive)
667 {
668         int i;
669         int err = 0;
670
671         mutex_lock(&damon_lock);
672         if ((exclusive && nr_running_ctxs) ||
673                         (!exclusive && running_exclusive_ctxs)) {
674                 mutex_unlock(&damon_lock);
675                 return -EBUSY;
676         }
677
678         for (i = 0; i < nr_ctxs; i++) {
679                 err = __damon_start(ctxs[i]);
680                 if (err)
681                         break;
682                 nr_running_ctxs++;
683         }
684         if (exclusive && nr_running_ctxs)
685                 running_exclusive_ctxs = true;
686         mutex_unlock(&damon_lock);
687
688         return err;
689 }
690
691 /*
692  * __damon_stop() - Stops monitoring of a given context.
693  * @ctx:        monitoring context
694  *
695  * Return: 0 on success, negative error code otherwise.
696  */
697 static int __damon_stop(struct damon_ctx *ctx)
698 {
699         struct task_struct *tsk;
700
701         mutex_lock(&ctx->kdamond_lock);
702         tsk = ctx->kdamond;
703         if (tsk) {
704                 get_task_struct(tsk);
705                 mutex_unlock(&ctx->kdamond_lock);
706                 kthread_stop(tsk);
707                 put_task_struct(tsk);
708                 return 0;
709         }
710         mutex_unlock(&ctx->kdamond_lock);
711
712         return -EPERM;
713 }
714
715 /**
716  * damon_stop() - Stops the monitorings for a given group of contexts.
717  * @ctxs:       an array of the pointers for contexts to stop monitoring
718  * @nr_ctxs:    size of @ctxs
719  *
720  * Return: 0 on success, negative error code otherwise.
721  */
722 int damon_stop(struct damon_ctx **ctxs, int nr_ctxs)
723 {
724         int i, err = 0;
725
726         for (i = 0; i < nr_ctxs; i++) {
727                 /* nr_running_ctxs is decremented in kdamond_fn */
728                 err = __damon_stop(ctxs[i]);
729                 if (err)
730                         break;
731         }
732         return err;
733 }
734
735 /*
736  * Reset the aggregated monitoring results ('nr_accesses' of each region).
737  */
738 static void kdamond_reset_aggregated(struct damon_ctx *c)
739 {
740         struct damon_target *t;
741         unsigned int ti = 0;    /* target's index */
742
743         damon_for_each_target(t, c) {
744                 struct damon_region *r;
745
746                 damon_for_each_region(r, t) {
747                         trace_damon_aggregated(t, ti, r, damon_nr_regions(t));
748                         r->last_nr_accesses = r->nr_accesses;
749                         r->nr_accesses = 0;
750                 }
751                 ti++;
752         }
753 }
754
755 static void damon_split_region_at(struct damon_target *t,
756                                   struct damon_region *r, unsigned long sz_r);
757
758 static bool __damos_valid_target(struct damon_region *r, struct damos *s)
759 {
760         unsigned long sz;
761
762         sz = damon_sz_region(r);
763         return s->pattern.min_sz_region <= sz &&
764                 sz <= s->pattern.max_sz_region &&
765                 s->pattern.min_nr_accesses <= r->nr_accesses &&
766                 r->nr_accesses <= s->pattern.max_nr_accesses &&
767                 s->pattern.min_age_region <= r->age &&
768                 r->age <= s->pattern.max_age_region;
769 }
770
771 static bool damos_valid_target(struct damon_ctx *c, struct damon_target *t,
772                 struct damon_region *r, struct damos *s)
773 {
774         bool ret = __damos_valid_target(r, s);
775
776         if (!ret || !s->quota.esz || !c->ops.get_scheme_score)
777                 return ret;
778
779         return c->ops.get_scheme_score(c, t, r, s) >= s->quota.min_score;
780 }
781
782 /*
783  * damos_skip_charged_region() - Check if the given region or starting part of
784  * it is already charged for the DAMOS quota.
785  * @t:  The target of the region.
786  * @rp: The pointer to the region.
787  * @s:  The scheme to be applied.
788  *
789  * If a quota of a scheme has exceeded in a quota charge window, the scheme's
790  * action would applied to only a part of the target access pattern fulfilling
791  * regions.  To avoid applying the scheme action to only already applied
792  * regions, DAMON skips applying the scheme action to the regions that charged
793  * in the previous charge window.
794  *
795  * This function checks if a given region should be skipped or not for the
796  * reason.  If only the starting part of the region has previously charged,
797  * this function splits the region into two so that the second one covers the
798  * area that not charged in the previous charge widnow and saves the second
799  * region in *rp and returns false, so that the caller can apply DAMON action
800  * to the second one.
801  *
802  * Return: true if the region should be entirely skipped, false otherwise.
803  */
804 static bool damos_skip_charged_region(struct damon_target *t,
805                 struct damon_region **rp, struct damos *s)
806 {
807         struct damon_region *r = *rp;
808         struct damos_quota *quota = &s->quota;
809         unsigned long sz_to_skip;
810
811         /* Skip previously charged regions */
812         if (quota->charge_target_from) {
813                 if (t != quota->charge_target_from)
814                         return true;
815                 if (r == damon_last_region(t)) {
816                         quota->charge_target_from = NULL;
817                         quota->charge_addr_from = 0;
818                         return true;
819                 }
820                 if (quota->charge_addr_from &&
821                                 r->ar.end <= quota->charge_addr_from)
822                         return true;
823
824                 if (quota->charge_addr_from && r->ar.start <
825                                 quota->charge_addr_from) {
826                         sz_to_skip = ALIGN_DOWN(quota->charge_addr_from -
827                                         r->ar.start, DAMON_MIN_REGION);
828                         if (!sz_to_skip) {
829                                 if (damon_sz_region(r) <= DAMON_MIN_REGION)
830                                         return true;
831                                 sz_to_skip = DAMON_MIN_REGION;
832                         }
833                         damon_split_region_at(t, r, sz_to_skip);
834                         r = damon_next_region(r);
835                         *rp = r;
836                 }
837                 quota->charge_target_from = NULL;
838                 quota->charge_addr_from = 0;
839         }
840         return false;
841 }
842
843 static void damos_update_stat(struct damos *s,
844                 unsigned long sz_tried, unsigned long sz_applied)
845 {
846         s->stat.nr_tried++;
847         s->stat.sz_tried += sz_tried;
848         if (sz_applied)
849                 s->stat.nr_applied++;
850         s->stat.sz_applied += sz_applied;
851 }
852
853 static bool __damos_filter_out(struct damon_ctx *ctx, struct damon_target *t,
854                 struct damon_region *r, struct damos_filter *filter)
855 {
856         bool matched = false;
857         struct damon_target *ti;
858         int target_idx = 0;
859         unsigned long start, end;
860
861         switch (filter->type) {
862         case DAMOS_FILTER_TYPE_TARGET:
863                 damon_for_each_target(ti, ctx) {
864                         if (ti == t)
865                                 break;
866                         target_idx++;
867                 }
868                 matched = target_idx == filter->target_idx;
869                 break;
870         case DAMOS_FILTER_TYPE_ADDR:
871                 start = ALIGN_DOWN(filter->addr_range.start, DAMON_MIN_REGION);
872                 end = ALIGN_DOWN(filter->addr_range.end, DAMON_MIN_REGION);
873
874                 /* inside the range */
875                 if (start <= r->ar.start && r->ar.end <= end) {
876                         matched = true;
877                         break;
878                 }
879                 /* outside of the range */
880                 if (r->ar.end <= start || end <= r->ar.start) {
881                         matched = false;
882                         break;
883                 }
884                 /* start before the range and overlap */
885                 if (r->ar.start < start) {
886                         damon_split_region_at(t, r, start - r->ar.start);
887                         matched = false;
888                         break;
889                 }
890                 /* start inside the range */
891                 damon_split_region_at(t, r, end - r->ar.start);
892                 matched = true;
893                 break;
894         default:
895                 return false;
896         }
897
898         return matched == filter->matching;
899 }
900
901 static bool damos_filter_out(struct damon_ctx *ctx, struct damon_target *t,
902                 struct damon_region *r, struct damos *s)
903 {
904         struct damos_filter *filter;
905
906         damos_for_each_filter(filter, s) {
907                 if (__damos_filter_out(ctx, t, r, filter))
908                         return true;
909         }
910         return false;
911 }
912
913 static void damos_apply_scheme(struct damon_ctx *c, struct damon_target *t,
914                 struct damon_region *r, struct damos *s)
915 {
916         struct damos_quota *quota = &s->quota;
917         unsigned long sz = damon_sz_region(r);
918         struct timespec64 begin, end;
919         unsigned long sz_applied = 0;
920         int err = 0;
921
922         if (c->ops.apply_scheme) {
923                 if (quota->esz && quota->charged_sz + sz > quota->esz) {
924                         sz = ALIGN_DOWN(quota->esz - quota->charged_sz,
925                                         DAMON_MIN_REGION);
926                         if (!sz)
927                                 goto update_stat;
928                         damon_split_region_at(t, r, sz);
929                 }
930                 if (damos_filter_out(c, t, r, s))
931                         return;
932                 ktime_get_coarse_ts64(&begin);
933                 if (c->callback.before_damos_apply)
934                         err = c->callback.before_damos_apply(c, t, r, s);
935                 if (!err)
936                         sz_applied = c->ops.apply_scheme(c, t, r, s);
937                 ktime_get_coarse_ts64(&end);
938                 quota->total_charged_ns += timespec64_to_ns(&end) -
939                         timespec64_to_ns(&begin);
940                 quota->charged_sz += sz;
941                 if (quota->esz && quota->charged_sz >= quota->esz) {
942                         quota->charge_target_from = t;
943                         quota->charge_addr_from = r->ar.end + 1;
944                 }
945         }
946         if (s->action != DAMOS_STAT)
947                 r->age = 0;
948
949 update_stat:
950         damos_update_stat(s, sz, sz_applied);
951 }
952
953 static void damon_do_apply_schemes(struct damon_ctx *c,
954                                    struct damon_target *t,
955                                    struct damon_region *r)
956 {
957         struct damos *s;
958
959         damon_for_each_scheme(s, c) {
960                 struct damos_quota *quota = &s->quota;
961
962                 if (!s->wmarks.activated)
963                         continue;
964
965                 /* Check the quota */
966                 if (quota->esz && quota->charged_sz >= quota->esz)
967                         continue;
968
969                 if (damos_skip_charged_region(t, &r, s))
970                         continue;
971
972                 if (!damos_valid_target(c, t, r, s))
973                         continue;
974
975                 damos_apply_scheme(c, t, r, s);
976         }
977 }
978
979 /* Shouldn't be called if quota->ms and quota->sz are zero */
980 static void damos_set_effective_quota(struct damos_quota *quota)
981 {
982         unsigned long throughput;
983         unsigned long esz;
984
985         if (!quota->ms) {
986                 quota->esz = quota->sz;
987                 return;
988         }
989
990         if (quota->total_charged_ns)
991                 throughput = quota->total_charged_sz * 1000000 /
992                         quota->total_charged_ns;
993         else
994                 throughput = PAGE_SIZE * 1024;
995         esz = throughput * quota->ms;
996
997         if (quota->sz && quota->sz < esz)
998                 esz = quota->sz;
999         quota->esz = esz;
1000 }
1001
1002 static void damos_adjust_quota(struct damon_ctx *c, struct damos *s)
1003 {
1004         struct damos_quota *quota = &s->quota;
1005         struct damon_target *t;
1006         struct damon_region *r;
1007         unsigned long cumulated_sz;
1008         unsigned int score, max_score = 0;
1009
1010         if (!quota->ms && !quota->sz)
1011                 return;
1012
1013         /* New charge window starts */
1014         if (time_after_eq(jiffies, quota->charged_from +
1015                                 msecs_to_jiffies(quota->reset_interval))) {
1016                 if (quota->esz && quota->charged_sz >= quota->esz)
1017                         s->stat.qt_exceeds++;
1018                 quota->total_charged_sz += quota->charged_sz;
1019                 quota->charged_from = jiffies;
1020                 quota->charged_sz = 0;
1021                 damos_set_effective_quota(quota);
1022         }
1023
1024         if (!c->ops.get_scheme_score)
1025                 return;
1026
1027         /* Fill up the score histogram */
1028         memset(quota->histogram, 0, sizeof(quota->histogram));
1029         damon_for_each_target(t, c) {
1030                 damon_for_each_region(r, t) {
1031                         if (!__damos_valid_target(r, s))
1032                                 continue;
1033                         score = c->ops.get_scheme_score(c, t, r, s);
1034                         quota->histogram[score] += damon_sz_region(r);
1035                         if (score > max_score)
1036                                 max_score = score;
1037                 }
1038         }
1039
1040         /* Set the min score limit */
1041         for (cumulated_sz = 0, score = max_score; ; score--) {
1042                 cumulated_sz += quota->histogram[score];
1043                 if (cumulated_sz >= quota->esz || !score)
1044                         break;
1045         }
1046         quota->min_score = score;
1047 }
1048
1049 static void kdamond_apply_schemes(struct damon_ctx *c)
1050 {
1051         struct damon_target *t;
1052         struct damon_region *r, *next_r;
1053         struct damos *s;
1054
1055         damon_for_each_scheme(s, c) {
1056                 if (!s->wmarks.activated)
1057                         continue;
1058
1059                 damos_adjust_quota(c, s);
1060         }
1061
1062         damon_for_each_target(t, c) {
1063                 damon_for_each_region_safe(r, next_r, t)
1064                         damon_do_apply_schemes(c, t, r);
1065         }
1066 }
1067
1068 /*
1069  * Merge two adjacent regions into one region
1070  */
1071 static void damon_merge_two_regions(struct damon_target *t,
1072                 struct damon_region *l, struct damon_region *r)
1073 {
1074         unsigned long sz_l = damon_sz_region(l), sz_r = damon_sz_region(r);
1075
1076         l->nr_accesses = (l->nr_accesses * sz_l + r->nr_accesses * sz_r) /
1077                         (sz_l + sz_r);
1078         l->age = (l->age * sz_l + r->age * sz_r) / (sz_l + sz_r);
1079         l->ar.end = r->ar.end;
1080         damon_destroy_region(r, t);
1081 }
1082
1083 /*
1084  * Merge adjacent regions having similar access frequencies
1085  *
1086  * t            target affected by this merge operation
1087  * thres        '->nr_accesses' diff threshold for the merge
1088  * sz_limit     size upper limit of each region
1089  */
1090 static void damon_merge_regions_of(struct damon_target *t, unsigned int thres,
1091                                    unsigned long sz_limit)
1092 {
1093         struct damon_region *r, *prev = NULL, *next;
1094
1095         damon_for_each_region_safe(r, next, t) {
1096                 if (abs(r->nr_accesses - r->last_nr_accesses) > thres)
1097                         r->age = 0;
1098                 else
1099                         r->age++;
1100
1101                 if (prev && prev->ar.end == r->ar.start &&
1102                     abs(prev->nr_accesses - r->nr_accesses) <= thres &&
1103                     damon_sz_region(prev) + damon_sz_region(r) <= sz_limit)
1104                         damon_merge_two_regions(t, prev, r);
1105                 else
1106                         prev = r;
1107         }
1108 }
1109
1110 /*
1111  * Merge adjacent regions having similar access frequencies
1112  *
1113  * threshold    '->nr_accesses' diff threshold for the merge
1114  * sz_limit     size upper limit of each region
1115  *
1116  * This function merges monitoring target regions which are adjacent and their
1117  * access frequencies are similar.  This is for minimizing the monitoring
1118  * overhead under the dynamically changeable access pattern.  If a merge was
1119  * unnecessarily made, later 'kdamond_split_regions()' will revert it.
1120  */
1121 static void kdamond_merge_regions(struct damon_ctx *c, unsigned int threshold,
1122                                   unsigned long sz_limit)
1123 {
1124         struct damon_target *t;
1125
1126         damon_for_each_target(t, c)
1127                 damon_merge_regions_of(t, threshold, sz_limit);
1128 }
1129
1130 /*
1131  * Split a region in two
1132  *
1133  * r            the region to be split
1134  * sz_r         size of the first sub-region that will be made
1135  */
1136 static void damon_split_region_at(struct damon_target *t,
1137                                   struct damon_region *r, unsigned long sz_r)
1138 {
1139         struct damon_region *new;
1140
1141         new = damon_new_region(r->ar.start + sz_r, r->ar.end);
1142         if (!new)
1143                 return;
1144
1145         r->ar.end = new->ar.start;
1146
1147         new->age = r->age;
1148         new->last_nr_accesses = r->last_nr_accesses;
1149
1150         damon_insert_region(new, r, damon_next_region(r), t);
1151 }
1152
1153 /* Split every region in the given target into 'nr_subs' regions */
1154 static void damon_split_regions_of(struct damon_target *t, int nr_subs)
1155 {
1156         struct damon_region *r, *next;
1157         unsigned long sz_region, sz_sub = 0;
1158         int i;
1159
1160         damon_for_each_region_safe(r, next, t) {
1161                 sz_region = damon_sz_region(r);
1162
1163                 for (i = 0; i < nr_subs - 1 &&
1164                                 sz_region > 2 * DAMON_MIN_REGION; i++) {
1165                         /*
1166                          * Randomly select size of left sub-region to be at
1167                          * least 10 percent and at most 90% of original region
1168                          */
1169                         sz_sub = ALIGN_DOWN(damon_rand(1, 10) *
1170                                         sz_region / 10, DAMON_MIN_REGION);
1171                         /* Do not allow blank region */
1172                         if (sz_sub == 0 || sz_sub >= sz_region)
1173                                 continue;
1174
1175                         damon_split_region_at(t, r, sz_sub);
1176                         sz_region = sz_sub;
1177                 }
1178         }
1179 }
1180
1181 /*
1182  * Split every target region into randomly-sized small regions
1183  *
1184  * This function splits every target region into random-sized small regions if
1185  * current total number of the regions is equal or smaller than half of the
1186  * user-specified maximum number of regions.  This is for maximizing the
1187  * monitoring accuracy under the dynamically changeable access patterns.  If a
1188  * split was unnecessarily made, later 'kdamond_merge_regions()' will revert
1189  * it.
1190  */
1191 static void kdamond_split_regions(struct damon_ctx *ctx)
1192 {
1193         struct damon_target *t;
1194         unsigned int nr_regions = 0;
1195         static unsigned int last_nr_regions;
1196         int nr_subregions = 2;
1197
1198         damon_for_each_target(t, ctx)
1199                 nr_regions += damon_nr_regions(t);
1200
1201         if (nr_regions > ctx->attrs.max_nr_regions / 2)
1202                 return;
1203
1204         /* Maybe the middle of the region has different access frequency */
1205         if (last_nr_regions == nr_regions &&
1206                         nr_regions < ctx->attrs.max_nr_regions / 3)
1207                 nr_subregions = 3;
1208
1209         damon_for_each_target(t, ctx)
1210                 damon_split_regions_of(t, nr_subregions);
1211
1212         last_nr_regions = nr_regions;
1213 }
1214
1215 /*
1216  * Check whether current monitoring should be stopped
1217  *
1218  * The monitoring is stopped when either the user requested to stop, or all
1219  * monitoring targets are invalid.
1220  *
1221  * Returns true if need to stop current monitoring.
1222  */
1223 static bool kdamond_need_stop(struct damon_ctx *ctx)
1224 {
1225         struct damon_target *t;
1226
1227         if (kthread_should_stop())
1228                 return true;
1229
1230         if (!ctx->ops.target_valid)
1231                 return false;
1232
1233         damon_for_each_target(t, ctx) {
1234                 if (ctx->ops.target_valid(t))
1235                         return false;
1236         }
1237
1238         return true;
1239 }
1240
1241 static unsigned long damos_wmark_metric_value(enum damos_wmark_metric metric)
1242 {
1243         struct sysinfo i;
1244
1245         switch (metric) {
1246         case DAMOS_WMARK_FREE_MEM_RATE:
1247                 si_meminfo(&i);
1248                 return i.freeram * 1000 / i.totalram;
1249         default:
1250                 break;
1251         }
1252         return -EINVAL;
1253 }
1254
1255 /*
1256  * Returns zero if the scheme is active.  Else, returns time to wait for next
1257  * watermark check in micro-seconds.
1258  */
1259 static unsigned long damos_wmark_wait_us(struct damos *scheme)
1260 {
1261         unsigned long metric;
1262
1263         if (scheme->wmarks.metric == DAMOS_WMARK_NONE)
1264                 return 0;
1265
1266         metric = damos_wmark_metric_value(scheme->wmarks.metric);
1267         /* higher than high watermark or lower than low watermark */
1268         if (metric > scheme->wmarks.high || scheme->wmarks.low > metric) {
1269                 if (scheme->wmarks.activated)
1270                         pr_debug("deactivate a scheme (%d) for %s wmark\n",
1271                                         scheme->action,
1272                                         metric > scheme->wmarks.high ?
1273                                         "high" : "low");
1274                 scheme->wmarks.activated = false;
1275                 return scheme->wmarks.interval;
1276         }
1277
1278         /* inactive and higher than middle watermark */
1279         if ((scheme->wmarks.high >= metric && metric >= scheme->wmarks.mid) &&
1280                         !scheme->wmarks.activated)
1281                 return scheme->wmarks.interval;
1282
1283         if (!scheme->wmarks.activated)
1284                 pr_debug("activate a scheme (%d)\n", scheme->action);
1285         scheme->wmarks.activated = true;
1286         return 0;
1287 }
1288
1289 static void kdamond_usleep(unsigned long usecs)
1290 {
1291         /* See Documentation/timers/timers-howto.rst for the thresholds */
1292         if (usecs > 20 * USEC_PER_MSEC)
1293                 schedule_timeout_idle(usecs_to_jiffies(usecs));
1294         else
1295                 usleep_idle_range(usecs, usecs + 1);
1296 }
1297
1298 /* Returns negative error code if it's not activated but should return */
1299 static int kdamond_wait_activation(struct damon_ctx *ctx)
1300 {
1301         struct damos *s;
1302         unsigned long wait_time;
1303         unsigned long min_wait_time = 0;
1304         bool init_wait_time = false;
1305
1306         while (!kdamond_need_stop(ctx)) {
1307                 damon_for_each_scheme(s, ctx) {
1308                         wait_time = damos_wmark_wait_us(s);
1309                         if (!init_wait_time || wait_time < min_wait_time) {
1310                                 init_wait_time = true;
1311                                 min_wait_time = wait_time;
1312                         }
1313                 }
1314                 if (!min_wait_time)
1315                         return 0;
1316
1317                 kdamond_usleep(min_wait_time);
1318
1319                 if (ctx->callback.after_wmarks_check &&
1320                                 ctx->callback.after_wmarks_check(ctx))
1321                         break;
1322         }
1323         return -EBUSY;
1324 }
1325
1326 static void kdamond_init_intervals_sis(struct damon_ctx *ctx)
1327 {
1328         unsigned long sample_interval = ctx->attrs.sample_interval ?
1329                 ctx->attrs.sample_interval : 1;
1330
1331         ctx->passed_sample_intervals = 0;
1332         ctx->next_aggregation_sis = ctx->attrs.aggr_interval / sample_interval;
1333         ctx->next_ops_update_sis = ctx->attrs.ops_update_interval /
1334                 sample_interval;
1335 }
1336
1337 /*
1338  * The monitoring daemon that runs as a kernel thread
1339  */
1340 static int kdamond_fn(void *data)
1341 {
1342         struct damon_ctx *ctx = data;
1343         struct damon_target *t;
1344         struct damon_region *r, *next;
1345         unsigned int max_nr_accesses = 0;
1346         unsigned long sz_limit = 0;
1347
1348         pr_debug("kdamond (%d) starts\n", current->pid);
1349
1350         kdamond_init_intervals_sis(ctx);
1351
1352         if (ctx->ops.init)
1353                 ctx->ops.init(ctx);
1354         if (ctx->callback.before_start && ctx->callback.before_start(ctx))
1355                 goto done;
1356
1357         sz_limit = damon_region_sz_limit(ctx);
1358
1359         while (!kdamond_need_stop(ctx)) {
1360                 /*
1361                  * ctx->attrs and ctx->next_{aggregation,ops_update}_sis could
1362                  * be changed from after_wmarks_check() or after_aggregation()
1363                  * callbacks.  Read the values here, and use those for this
1364                  * iteration.  That is, damon_set_attrs() updated new values
1365                  * are respected from next iteration.
1366                  */
1367                 unsigned long next_aggregation_sis = ctx->next_aggregation_sis;
1368                 unsigned long next_ops_update_sis = ctx->next_ops_update_sis;
1369                 unsigned long sample_interval = ctx->attrs.sample_interval;
1370
1371                 if (kdamond_wait_activation(ctx))
1372                         break;
1373
1374                 if (ctx->ops.prepare_access_checks)
1375                         ctx->ops.prepare_access_checks(ctx);
1376                 if (ctx->callback.after_sampling &&
1377                                 ctx->callback.after_sampling(ctx))
1378                         break;
1379
1380                 kdamond_usleep(sample_interval);
1381                 ctx->passed_sample_intervals++;
1382
1383                 if (ctx->ops.check_accesses)
1384                         max_nr_accesses = ctx->ops.check_accesses(ctx);
1385
1386                 sample_interval = ctx->attrs.sample_interval ?
1387                         ctx->attrs.sample_interval : 1;
1388                 if (ctx->passed_sample_intervals == next_aggregation_sis) {
1389                         ctx->next_aggregation_sis = next_aggregation_sis +
1390                                 ctx->attrs.aggr_interval / sample_interval;
1391                         kdamond_merge_regions(ctx,
1392                                         max_nr_accesses / 10,
1393                                         sz_limit);
1394                         if (ctx->callback.after_aggregation &&
1395                                         ctx->callback.after_aggregation(ctx))
1396                                 break;
1397                         if (!list_empty(&ctx->schemes))
1398                                 kdamond_apply_schemes(ctx);
1399                         kdamond_reset_aggregated(ctx);
1400                         kdamond_split_regions(ctx);
1401                         if (ctx->ops.reset_aggregated)
1402                                 ctx->ops.reset_aggregated(ctx);
1403                 }
1404
1405                 if (ctx->passed_sample_intervals == next_ops_update_sis) {
1406                         ctx->next_ops_update_sis = next_ops_update_sis +
1407                                 ctx->attrs.ops_update_interval /
1408                                 sample_interval;
1409                         if (ctx->ops.update)
1410                                 ctx->ops.update(ctx);
1411                         sz_limit = damon_region_sz_limit(ctx);
1412                 }
1413         }
1414 done:
1415         damon_for_each_target(t, ctx) {
1416                 damon_for_each_region_safe(r, next, t)
1417                         damon_destroy_region(r, t);
1418         }
1419
1420         if (ctx->callback.before_terminate)
1421                 ctx->callback.before_terminate(ctx);
1422         if (ctx->ops.cleanup)
1423                 ctx->ops.cleanup(ctx);
1424
1425         pr_debug("kdamond (%d) finishes\n", current->pid);
1426         mutex_lock(&ctx->kdamond_lock);
1427         ctx->kdamond = NULL;
1428         mutex_unlock(&ctx->kdamond_lock);
1429
1430         mutex_lock(&damon_lock);
1431         nr_running_ctxs--;
1432         if (!nr_running_ctxs && running_exclusive_ctxs)
1433                 running_exclusive_ctxs = false;
1434         mutex_unlock(&damon_lock);
1435
1436         return 0;
1437 }
1438
1439 /*
1440  * struct damon_system_ram_region - System RAM resource address region of
1441  *                                  [@start, @end).
1442  * @start:      Start address of the region (inclusive).
1443  * @end:        End address of the region (exclusive).
1444  */
1445 struct damon_system_ram_region {
1446         unsigned long start;
1447         unsigned long end;
1448 };
1449
1450 static int walk_system_ram(struct resource *res, void *arg)
1451 {
1452         struct damon_system_ram_region *a = arg;
1453
1454         if (a->end - a->start < resource_size(res)) {
1455                 a->start = res->start;
1456                 a->end = res->end;
1457         }
1458         return 0;
1459 }
1460
1461 /*
1462  * Find biggest 'System RAM' resource and store its start and end address in
1463  * @start and @end, respectively.  If no System RAM is found, returns false.
1464  */
1465 static bool damon_find_biggest_system_ram(unsigned long *start,
1466                                                 unsigned long *end)
1467
1468 {
1469         struct damon_system_ram_region arg = {};
1470
1471         walk_system_ram_res(0, ULONG_MAX, &arg, walk_system_ram);
1472         if (arg.end <= arg.start)
1473                 return false;
1474
1475         *start = arg.start;
1476         *end = arg.end;
1477         return true;
1478 }
1479
1480 /**
1481  * damon_set_region_biggest_system_ram_default() - Set the region of the given
1482  * monitoring target as requested, or biggest 'System RAM'.
1483  * @t:          The monitoring target to set the region.
1484  * @start:      The pointer to the start address of the region.
1485  * @end:        The pointer to the end address of the region.
1486  *
1487  * This function sets the region of @t as requested by @start and @end.  If the
1488  * values of @start and @end are zero, however, this function finds the biggest
1489  * 'System RAM' resource and sets the region to cover the resource.  In the
1490  * latter case, this function saves the start and end addresses of the resource
1491  * in @start and @end, respectively.
1492  *
1493  * Return: 0 on success, negative error code otherwise.
1494  */
1495 int damon_set_region_biggest_system_ram_default(struct damon_target *t,
1496                         unsigned long *start, unsigned long *end)
1497 {
1498         struct damon_addr_range addr_range;
1499
1500         if (*start > *end)
1501                 return -EINVAL;
1502
1503         if (!*start && !*end &&
1504                 !damon_find_biggest_system_ram(start, end))
1505                 return -EINVAL;
1506
1507         addr_range.start = *start;
1508         addr_range.end = *end;
1509         return damon_set_regions(t, &addr_range, 1);
1510 }
1511
1512 static int __init damon_init(void)
1513 {
1514         damon_region_cache = KMEM_CACHE(damon_region, 0);
1515         if (unlikely(!damon_region_cache)) {
1516                 pr_err("creating damon_region_cache fails\n");
1517                 return -ENOMEM;
1518         }
1519
1520         return 0;
1521 }
1522
1523 subsys_initcall(damon_init);
1524
1525 #include "core-test.h"