xref: /openbmc/linux/include/linux/damon.h (revision 4c1f287f)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 /*
3  * DAMON api
4  *
5  * Author: SeongJae Park <sjpark@amazon.de>
6  */
7 
8 #ifndef _DAMON_H_
9 #define _DAMON_H_
10 
11 #include <linux/mutex.h>
12 #include <linux/time64.h>
13 #include <linux/types.h>
14 #include <linux/random.h>
15 
16 /* Minimal region size.  Every damon_region is aligned by this. */
17 #define DAMON_MIN_REGION	PAGE_SIZE
18 /* Max priority score for DAMON-based operation schemes */
19 #define DAMOS_MAX_SCORE		(99)
20 
21 /* Get a random number in [l, r) */
22 static inline unsigned long damon_rand(unsigned long l, unsigned long r)
23 {
24 	return l + prandom_u32_max(r - l);
25 }
26 
27 /**
28  * struct damon_addr_range - Represents an address region of [@start, @end).
29  * @start:	Start address of the region (inclusive).
30  * @end:	End address of the region (exclusive).
31  */
32 struct damon_addr_range {
33 	unsigned long start;
34 	unsigned long end;
35 };
36 
37 /**
38  * struct damon_region - Represents a monitoring target region.
39  * @ar:			The address range of the region.
40  * @sampling_addr:	Address of the sample for the next access check.
41  * @nr_accesses:	Access frequency of this region.
42  * @list:		List head for siblings.
43  * @age:		Age of this region.
44  *
45  * @age is initially zero, increased for each aggregation interval, and reset
46  * to zero again if the access frequency is significantly changed.  If two
47  * regions are merged into a new region, both @nr_accesses and @age of the new
48  * region are set as region size-weighted average of those of the two regions.
49  */
50 struct damon_region {
51 	struct damon_addr_range ar;
52 	unsigned long sampling_addr;
53 	unsigned int nr_accesses;
54 	struct list_head list;
55 
56 	unsigned int age;
57 /* private: Internal value for age calculation. */
58 	unsigned int last_nr_accesses;
59 };
60 
61 /**
62  * struct damon_target - Represents a monitoring target.
63  * @pid:		The PID of the virtual address space to monitor.
64  * @nr_regions:		Number of monitoring target regions of this target.
65  * @regions_list:	Head of the monitoring target regions of this target.
66  * @list:		List head for siblings.
67  *
68  * Each monitoring context could have multiple targets.  For example, a context
69  * for virtual memory address spaces could have multiple target processes.  The
70  * @pid should be set for appropriate &struct damon_operations including the
71  * virtual address spaces monitoring operations.
72  */
73 struct damon_target {
74 	struct pid *pid;
75 	unsigned int nr_regions;
76 	struct list_head regions_list;
77 	struct list_head list;
78 };
79 
80 /**
81  * enum damos_action - Represents an action of a Data Access Monitoring-based
82  * Operation Scheme.
83  *
84  * @DAMOS_WILLNEED:	Call ``madvise()`` for the region with MADV_WILLNEED.
85  * @DAMOS_COLD:		Call ``madvise()`` for the region with MADV_COLD.
86  * @DAMOS_PAGEOUT:	Call ``madvise()`` for the region with MADV_PAGEOUT.
87  * @DAMOS_HUGEPAGE:	Call ``madvise()`` for the region with MADV_HUGEPAGE.
88  * @DAMOS_NOHUGEPAGE:	Call ``madvise()`` for the region with MADV_NOHUGEPAGE.
89  * @DAMOS_STAT:		Do nothing but count the stat.
90  */
91 enum damos_action {
92 	DAMOS_WILLNEED,
93 	DAMOS_COLD,
94 	DAMOS_PAGEOUT,
95 	DAMOS_HUGEPAGE,
96 	DAMOS_NOHUGEPAGE,
97 	DAMOS_STAT,		/* Do nothing but only record the stat */
98 };
99 
100 /**
101  * struct damos_quota - Controls the aggressiveness of the given scheme.
102  * @ms:			Maximum milliseconds that the scheme can use.
103  * @sz:			Maximum bytes of memory that the action can be applied.
104  * @reset_interval:	Charge reset interval in milliseconds.
105  *
106  * @weight_sz:		Weight of the region's size for prioritization.
107  * @weight_nr_accesses:	Weight of the region's nr_accesses for prioritization.
108  * @weight_age:		Weight of the region's age for prioritization.
109  *
110  * To avoid consuming too much CPU time or IO resources for applying the
111  * &struct damos->action to large memory, DAMON allows users to set time and/or
112  * size quotas.  The quotas can be set by writing non-zero values to &ms and
113  * &sz, respectively.  If the time quota is set, DAMON tries to use only up to
114  * &ms milliseconds within &reset_interval for applying the action.  If the
115  * size quota is set, DAMON tries to apply the action only up to &sz bytes
116  * within &reset_interval.
117  *
118  * Internally, the time quota is transformed to a size quota using estimated
119  * throughput of the scheme's action.  DAMON then compares it against &sz and
120  * uses smaller one as the effective quota.
121  *
122  * For selecting regions within the quota, DAMON prioritizes current scheme's
123  * target memory regions using the &struct damon_operations->get_scheme_score.
124  * You could customize the prioritization logic by setting &weight_sz,
125  * &weight_nr_accesses, and &weight_age, because monitoring operations are
126  * encouraged to respect those.
127  */
128 struct damos_quota {
129 	unsigned long ms;
130 	unsigned long sz;
131 	unsigned long reset_interval;
132 
133 	unsigned int weight_sz;
134 	unsigned int weight_nr_accesses;
135 	unsigned int weight_age;
136 
137 /* private: */
138 	/* For throughput estimation */
139 	unsigned long total_charged_sz;
140 	unsigned long total_charged_ns;
141 
142 	unsigned long esz;	/* Effective size quota in bytes */
143 
144 	/* For charging the quota */
145 	unsigned long charged_sz;
146 	unsigned long charged_from;
147 	struct damon_target *charge_target_from;
148 	unsigned long charge_addr_from;
149 
150 	/* For prioritization */
151 	unsigned long histogram[DAMOS_MAX_SCORE + 1];
152 	unsigned int min_score;
153 };
154 
155 /**
156  * enum damos_wmark_metric - Represents the watermark metric.
157  *
158  * @DAMOS_WMARK_NONE:		Ignore the watermarks of the given scheme.
159  * @DAMOS_WMARK_FREE_MEM_RATE:	Free memory rate of the system in [0,1000].
160  */
161 enum damos_wmark_metric {
162 	DAMOS_WMARK_NONE,
163 	DAMOS_WMARK_FREE_MEM_RATE,
164 };
165 
166 /**
167  * struct damos_watermarks - Controls when a given scheme should be activated.
168  * @metric:	Metric for the watermarks.
169  * @interval:	Watermarks check time interval in microseconds.
170  * @high:	High watermark.
171  * @mid:	Middle watermark.
172  * @low:	Low watermark.
173  *
174  * If &metric is &DAMOS_WMARK_NONE, the scheme is always active.  Being active
175  * means DAMON does monitoring and applying the action of the scheme to
176  * appropriate memory regions.  Else, DAMON checks &metric of the system for at
177  * least every &interval microseconds and works as below.
178  *
179  * If &metric is higher than &high, the scheme is inactivated.  If &metric is
180  * between &mid and &low, the scheme is activated.  If &metric is lower than
181  * &low, the scheme is inactivated.
182  */
183 struct damos_watermarks {
184 	enum damos_wmark_metric metric;
185 	unsigned long interval;
186 	unsigned long high;
187 	unsigned long mid;
188 	unsigned long low;
189 
190 /* private: */
191 	bool activated;
192 };
193 
194 /**
195  * struct damos_stat - Statistics on a given scheme.
196  * @nr_tried:	Total number of regions that the scheme is tried to be applied.
197  * @sz_tried:	Total size of regions that the scheme is tried to be applied.
198  * @nr_applied:	Total number of regions that the scheme is applied.
199  * @sz_applied:	Total size of regions that the scheme is applied.
200  * @qt_exceeds: Total number of times the quota of the scheme has exceeded.
201  */
202 struct damos_stat {
203 	unsigned long nr_tried;
204 	unsigned long sz_tried;
205 	unsigned long nr_applied;
206 	unsigned long sz_applied;
207 	unsigned long qt_exceeds;
208 };
209 
210 /**
211  * struct damos - Represents a Data Access Monitoring-based Operation Scheme.
212  * @min_sz_region:	Minimum size of target regions.
213  * @max_sz_region:	Maximum size of target regions.
214  * @min_nr_accesses:	Minimum ``->nr_accesses`` of target regions.
215  * @max_nr_accesses:	Maximum ``->nr_accesses`` of target regions.
216  * @min_age_region:	Minimum age of target regions.
217  * @max_age_region:	Maximum age of target regions.
218  * @action:		&damo_action to be applied to the target regions.
219  * @quota:		Control the aggressiveness of this scheme.
220  * @wmarks:		Watermarks for automated (in)activation of this scheme.
221  * @stat:		Statistics of this scheme.
222  * @list:		List head for siblings.
223  *
224  * For each aggregation interval, DAMON finds regions which fit in the
225  * condition (&min_sz_region, &max_sz_region, &min_nr_accesses,
226  * &max_nr_accesses, &min_age_region, &max_age_region) and applies &action to
227  * those.  To avoid consuming too much CPU time or IO resources for the
228  * &action, &quota is used.
229  *
230  * To do the work only when needed, schemes can be activated for specific
231  * system situations using &wmarks.  If all schemes that registered to the
232  * monitoring context are inactive, DAMON stops monitoring either, and just
233  * repeatedly checks the watermarks.
234  *
235  * If all schemes that registered to a &struct damon_ctx are inactive, DAMON
236  * stops monitoring and just repeatedly checks the watermarks.
237  *
238  * After applying the &action to each region, &stat_count and &stat_sz is
239  * updated to reflect the number of regions and total size of regions that the
240  * &action is applied.
241  */
242 struct damos {
243 	unsigned long min_sz_region;
244 	unsigned long max_sz_region;
245 	unsigned int min_nr_accesses;
246 	unsigned int max_nr_accesses;
247 	unsigned int min_age_region;
248 	unsigned int max_age_region;
249 	enum damos_action action;
250 	struct damos_quota quota;
251 	struct damos_watermarks wmarks;
252 	struct damos_stat stat;
253 	struct list_head list;
254 };
255 
256 /**
257  * enum damon_ops_id - Identifier for each monitoring operations implementation
258  *
259  * @DAMON_OPS_VADDR:	Monitoring operations for virtual address spaces
260  * @DAMON_OPS_PADDR:	Monitoring operations for the physical address space
261  */
262 enum damon_ops_id {
263 	DAMON_OPS_VADDR,
264 	DAMON_OPS_PADDR,
265 	NR_DAMON_OPS,
266 };
267 
268 struct damon_ctx;
269 
270 /**
271  * struct damon_operations - Monitoring operations for given use cases.
272  *
273  * @id:				Identifier of this operations set.
274  * @init:			Initialize operations-related data structures.
275  * @update:			Update operations-related data structures.
276  * @prepare_access_checks:	Prepare next access check of target regions.
277  * @check_accesses:		Check the accesses to target regions.
278  * @reset_aggregated:		Reset aggregated accesses monitoring results.
279  * @get_scheme_score:		Get the score of a region for a scheme.
280  * @apply_scheme:		Apply a DAMON-based operation scheme.
281  * @target_valid:		Determine if the target is valid.
282  * @cleanup:			Clean up the context.
283  *
284  * DAMON can be extended for various address spaces and usages.  For this,
285  * users should register the low level operations for their target address
286  * space and usecase via the &damon_ctx.ops.  Then, the monitoring thread
287  * (&damon_ctx.kdamond) calls @init and @prepare_access_checks before starting
288  * the monitoring, @update after each &damon_ctx.ops_update_interval, and
289  * @check_accesses, @target_valid and @prepare_access_checks after each
290  * &damon_ctx.sample_interval.  Finally, @reset_aggregated is called after each
291  * &damon_ctx.aggr_interval.
292  *
293  * Each &struct damon_operations instance having valid @id can be registered
294  * via damon_register_ops() and selected by damon_select_ops() later.
295  * @init should initialize operations-related data structures.  For example,
296  * this could be used to construct proper monitoring target regions and link
297  * those to @damon_ctx.adaptive_targets.
298  * @update should update the operations-related data structures.  For example,
299  * this could be used to update monitoring target regions for current status.
300  * @prepare_access_checks should manipulate the monitoring regions to be
301  * prepared for the next access check.
302  * @check_accesses should check the accesses to each region that made after the
303  * last preparation and update the number of observed accesses of each region.
304  * It should also return max number of observed accesses that made as a result
305  * of its update.  The value will be used for regions adjustment threshold.
306  * @reset_aggregated should reset the access monitoring results that aggregated
307  * by @check_accesses.
308  * @get_scheme_score should return the priority score of a region for a scheme
309  * as an integer in [0, &DAMOS_MAX_SCORE].
310  * @apply_scheme is called from @kdamond when a region for user provided
311  * DAMON-based operation scheme is found.  It should apply the scheme's action
312  * to the region and return bytes of the region that the action is successfully
313  * applied.
314  * @target_valid should check whether the target is still valid for the
315  * monitoring.
316  * @cleanup is called from @kdamond just before its termination.
317  */
318 struct damon_operations {
319 	enum damon_ops_id id;
320 	void (*init)(struct damon_ctx *context);
321 	void (*update)(struct damon_ctx *context);
322 	void (*prepare_access_checks)(struct damon_ctx *context);
323 	unsigned int (*check_accesses)(struct damon_ctx *context);
324 	void (*reset_aggregated)(struct damon_ctx *context);
325 	int (*get_scheme_score)(struct damon_ctx *context,
326 			struct damon_target *t, struct damon_region *r,
327 			struct damos *scheme);
328 	unsigned long (*apply_scheme)(struct damon_ctx *context,
329 			struct damon_target *t, struct damon_region *r,
330 			struct damos *scheme);
331 	bool (*target_valid)(void *target);
332 	void (*cleanup)(struct damon_ctx *context);
333 };
334 
335 /**
336  * struct damon_callback - Monitoring events notification callbacks.
337  *
338  * @before_start:	Called before starting the monitoring.
339  * @after_sampling:	Called after each sampling.
340  * @after_aggregation:	Called after each aggregation.
341  * @before_terminate:	Called before terminating the monitoring.
342  * @private:		User private data.
343  *
344  * The monitoring thread (&damon_ctx.kdamond) calls @before_start and
345  * @before_terminate just before starting and finishing the monitoring,
346  * respectively.  Therefore, those are good places for installing and cleaning
347  * @private.
348  *
349  * The monitoring thread calls @after_sampling and @after_aggregation for each
350  * of the sampling intervals and aggregation intervals, respectively.
351  * Therefore, users can safely access the monitoring results without additional
352  * protection.  For the reason, users are recommended to use these callback for
353  * the accesses to the results.
354  *
355  * If any callback returns non-zero, monitoring stops.
356  */
357 struct damon_callback {
358 	void *private;
359 
360 	int (*before_start)(struct damon_ctx *context);
361 	int (*after_sampling)(struct damon_ctx *context);
362 	int (*after_aggregation)(struct damon_ctx *context);
363 	void (*before_terminate)(struct damon_ctx *context);
364 };
365 
366 /**
367  * struct damon_ctx - Represents a context for each monitoring.  This is the
368  * main interface that allows users to set the attributes and get the results
369  * of the monitoring.
370  *
371  * @sample_interval:		The time between access samplings.
372  * @aggr_interval:		The time between monitor results aggregations.
373  * @ops_update_interval:	The time between monitoring operations updates.
374  *
375  * For each @sample_interval, DAMON checks whether each region is accessed or
376  * not.  It aggregates and keeps the access information (number of accesses to
377  * each region) for @aggr_interval time.  DAMON also checks whether the target
378  * memory regions need update (e.g., by ``mmap()`` calls from the application,
379  * in case of virtual memory monitoring) and applies the changes for each
380  * @ops_update_interval.  All time intervals are in micro-seconds.
381  * Please refer to &struct damon_operations and &struct damon_callback for more
382  * detail.
383  *
384  * @kdamond:		Kernel thread who does the monitoring.
385  * @kdamond_stop:	Notifies whether kdamond should stop.
386  * @kdamond_lock:	Mutex for the synchronizations with @kdamond.
387  *
388  * For each monitoring context, one kernel thread for the monitoring is
389  * created.  The pointer to the thread is stored in @kdamond.
390  *
391  * Once started, the monitoring thread runs until explicitly required to be
392  * terminated or every monitoring target is invalid.  The validity of the
393  * targets is checked via the &damon_operations.target_valid of @ops.  The
394  * termination can also be explicitly requested by writing non-zero to
395  * @kdamond_stop.  The thread sets @kdamond to NULL when it terminates.
396  * Therefore, users can know whether the monitoring is ongoing or terminated by
397  * reading @kdamond.  Reads and writes to @kdamond and @kdamond_stop from
398  * outside of the monitoring thread must be protected by @kdamond_lock.
399  *
400  * Note that the monitoring thread protects only @kdamond and @kdamond_stop via
401  * @kdamond_lock.  Accesses to other fields must be protected by themselves.
402  *
403  * @ops:	Set of monitoring operations for given use cases.
404  * @callback:	Set of callbacks for monitoring events notifications.
405  *
406  * @min_nr_regions:	The minimum number of adaptive monitoring regions.
407  * @max_nr_regions:	The maximum number of adaptive monitoring regions.
408  * @adaptive_targets:	Head of monitoring targets (&damon_target) list.
409  * @schemes:		Head of schemes (&damos) list.
410  */
411 struct damon_ctx {
412 	unsigned long sample_interval;
413 	unsigned long aggr_interval;
414 	unsigned long ops_update_interval;
415 
416 /* private: internal use only */
417 	struct timespec64 last_aggregation;
418 	struct timespec64 last_ops_update;
419 
420 /* public: */
421 	struct task_struct *kdamond;
422 	struct mutex kdamond_lock;
423 
424 	struct damon_operations ops;
425 	struct damon_callback callback;
426 
427 	unsigned long min_nr_regions;
428 	unsigned long max_nr_regions;
429 	struct list_head adaptive_targets;
430 	struct list_head schemes;
431 };
432 
433 static inline struct damon_region *damon_next_region(struct damon_region *r)
434 {
435 	return container_of(r->list.next, struct damon_region, list);
436 }
437 
438 static inline struct damon_region *damon_prev_region(struct damon_region *r)
439 {
440 	return container_of(r->list.prev, struct damon_region, list);
441 }
442 
443 static inline struct damon_region *damon_last_region(struct damon_target *t)
444 {
445 	return list_last_entry(&t->regions_list, struct damon_region, list);
446 }
447 
448 #define damon_for_each_region(r, t) \
449 	list_for_each_entry(r, &t->regions_list, list)
450 
451 #define damon_for_each_region_safe(r, next, t) \
452 	list_for_each_entry_safe(r, next, &t->regions_list, list)
453 
454 #define damon_for_each_target(t, ctx) \
455 	list_for_each_entry(t, &(ctx)->adaptive_targets, list)
456 
457 #define damon_for_each_target_safe(t, next, ctx)	\
458 	list_for_each_entry_safe(t, next, &(ctx)->adaptive_targets, list)
459 
460 #define damon_for_each_scheme(s, ctx) \
461 	list_for_each_entry(s, &(ctx)->schemes, list)
462 
463 #define damon_for_each_scheme_safe(s, next, ctx) \
464 	list_for_each_entry_safe(s, next, &(ctx)->schemes, list)
465 
466 #ifdef CONFIG_DAMON
467 
468 struct damon_region *damon_new_region(unsigned long start, unsigned long end);
469 
470 /*
471  * Add a region between two other regions
472  */
473 static inline void damon_insert_region(struct damon_region *r,
474 		struct damon_region *prev, struct damon_region *next,
475 		struct damon_target *t)
476 {
477 	__list_add(&r->list, &prev->list, &next->list);
478 	t->nr_regions++;
479 }
480 
481 void damon_add_region(struct damon_region *r, struct damon_target *t);
482 void damon_destroy_region(struct damon_region *r, struct damon_target *t);
483 
484 struct damos *damon_new_scheme(
485 		unsigned long min_sz_region, unsigned long max_sz_region,
486 		unsigned int min_nr_accesses, unsigned int max_nr_accesses,
487 		unsigned int min_age_region, unsigned int max_age_region,
488 		enum damos_action action, struct damos_quota *quota,
489 		struct damos_watermarks *wmarks);
490 void damon_add_scheme(struct damon_ctx *ctx, struct damos *s);
491 void damon_destroy_scheme(struct damos *s);
492 
493 struct damon_target *damon_new_target(void);
494 void damon_add_target(struct damon_ctx *ctx, struct damon_target *t);
495 bool damon_targets_empty(struct damon_ctx *ctx);
496 void damon_free_target(struct damon_target *t);
497 void damon_destroy_target(struct damon_target *t);
498 unsigned int damon_nr_regions(struct damon_target *t);
499 
500 struct damon_ctx *damon_new_ctx(void);
501 void damon_destroy_ctx(struct damon_ctx *ctx);
502 int damon_set_attrs(struct damon_ctx *ctx, unsigned long sample_int,
503 		unsigned long aggr_int, unsigned long ops_upd_int,
504 		unsigned long min_nr_reg, unsigned long max_nr_reg);
505 int damon_set_schemes(struct damon_ctx *ctx,
506 			struct damos **schemes, ssize_t nr_schemes);
507 int damon_nr_running_ctxs(void);
508 int damon_register_ops(struct damon_operations *ops);
509 int damon_select_ops(struct damon_ctx *ctx, enum damon_ops_id id);
510 
511 int damon_start(struct damon_ctx **ctxs, int nr_ctxs);
512 int damon_stop(struct damon_ctx **ctxs, int nr_ctxs);
513 
514 #endif	/* CONFIG_DAMON */
515 
516 #endif	/* _DAMON_H */
517