xref: /linux-6.15/include/linux/damon.h (revision b243d666)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 /*
3  * DAMON api
4  *
5  * Author: SeongJae Park <[email protected]>
6  */
7 
8 #ifndef _DAMON_H_
9 #define _DAMON_H_
10 
11 #include <linux/memcontrol.h>
12 #include <linux/mutex.h>
13 #include <linux/time64.h>
14 #include <linux/types.h>
15 #include <linux/random.h>
16 
17 /* Minimal region size.  Every damon_region is aligned by this. */
18 #define DAMON_MIN_REGION	PAGE_SIZE
19 /* Max priority score for DAMON-based operation schemes */
20 #define DAMOS_MAX_SCORE		(99)
21 
22 /* Get a random number in [l, r) */
23 static inline unsigned long damon_rand(unsigned long l, unsigned long r)
24 {
25 	return l + get_random_u32_below(r - l);
26 }
27 
28 /**
29  * struct damon_addr_range - Represents an address region of [@start, @end).
30  * @start:	Start address of the region (inclusive).
31  * @end:	End address of the region (exclusive).
32  */
33 struct damon_addr_range {
34 	unsigned long start;
35 	unsigned long end;
36 };
37 
38 /**
39  * struct damon_size_range - Represents size for filter to operate on [@min, @max].
40  * @min:	Min size (inclusive).
41  * @max:	Max size (inclusive).
42  */
43 struct damon_size_range {
44 	unsigned long min;
45 	unsigned long max;
46 };
47 
48 /**
49  * struct damon_region - Represents a monitoring target region.
50  * @ar:			The address range of the region.
51  * @sampling_addr:	Address of the sample for the next access check.
52  * @nr_accesses:	Access frequency of this region.
53  * @nr_accesses_bp:	@nr_accesses in basis point (0.01%) that updated for
54  *			each sampling interval.
55  * @list:		List head for siblings.
56  * @age:		Age of this region.
57  *
58  * @nr_accesses is reset to zero for every &damon_attrs->aggr_interval and be
59  * increased for every &damon_attrs->sample_interval if an access to the region
60  * during the last sampling interval is found.  The update of this field should
61  * not be done with direct access but with the helper function,
62  * damon_update_region_access_rate().
63  *
64  * @nr_accesses_bp is another representation of @nr_accesses in basis point
65  * (1 in 10,000) that updated for every &damon_attrs->sample_interval in a
66  * manner similar to moving sum.  By the algorithm, this value becomes
67  * @nr_accesses * 10000 for every &struct damon_attrs->aggr_interval.  This can
68  * be used when the aggregation interval is too huge and therefore cannot wait
69  * for it before getting the access monitoring results.
70  *
71  * @age is initially zero, increased for each aggregation interval, and reset
72  * to zero again if the access frequency is significantly changed.  If two
73  * regions are merged into a new region, both @nr_accesses and @age of the new
74  * region are set as region size-weighted average of those of the two regions.
75  */
76 struct damon_region {
77 	struct damon_addr_range ar;
78 	unsigned long sampling_addr;
79 	unsigned int nr_accesses;
80 	unsigned int nr_accesses_bp;
81 	struct list_head list;
82 
83 	unsigned int age;
84 /* private: Internal value for age calculation. */
85 	unsigned int last_nr_accesses;
86 };
87 
88 /**
89  * struct damon_target - Represents a monitoring target.
90  * @pid:		The PID of the virtual address space to monitor.
91  * @nr_regions:		Number of monitoring target regions of this target.
92  * @regions_list:	Head of the monitoring target regions of this target.
93  * @list:		List head for siblings.
94  *
95  * Each monitoring context could have multiple targets.  For example, a context
96  * for virtual memory address spaces could have multiple target processes.  The
97  * @pid should be set for appropriate &struct damon_operations including the
98  * virtual address spaces monitoring operations.
99  */
100 struct damon_target {
101 	struct pid *pid;
102 	unsigned int nr_regions;
103 	struct list_head regions_list;
104 	struct list_head list;
105 };
106 
107 /**
108  * enum damos_action - Represents an action of a Data Access Monitoring-based
109  * Operation Scheme.
110  *
111  * @DAMOS_WILLNEED:	Call ``madvise()`` for the region with MADV_WILLNEED.
112  * @DAMOS_COLD:		Call ``madvise()`` for the region with MADV_COLD.
113  * @DAMOS_PAGEOUT:	Call ``madvise()`` for the region with MADV_PAGEOUT.
114  * @DAMOS_HUGEPAGE:	Call ``madvise()`` for the region with MADV_HUGEPAGE.
115  * @DAMOS_NOHUGEPAGE:	Call ``madvise()`` for the region with MADV_NOHUGEPAGE.
116  * @DAMOS_LRU_PRIO:	Prioritize the region on its LRU lists.
117  * @DAMOS_LRU_DEPRIO:	Deprioritize the region on its LRU lists.
118  * @DAMOS_MIGRATE_HOT:  Migrate the regions prioritizing warmer regions.
119  * @DAMOS_MIGRATE_COLD:	Migrate the regions prioritizing colder regions.
120  * @DAMOS_STAT:		Do nothing but count the stat.
121  * @NR_DAMOS_ACTIONS:	Total number of DAMOS actions
122  *
123  * The support of each action is up to running &struct damon_operations.
124  * &enum DAMON_OPS_VADDR and &enum DAMON_OPS_FVADDR supports all actions except
125  * &enum DAMOS_LRU_PRIO and &enum DAMOS_LRU_DEPRIO.  &enum DAMON_OPS_PADDR
126  * supports only &enum DAMOS_PAGEOUT, &enum DAMOS_LRU_PRIO, &enum
127  * DAMOS_LRU_DEPRIO, and &DAMOS_STAT.
128  */
129 enum damos_action {
130 	DAMOS_WILLNEED,
131 	DAMOS_COLD,
132 	DAMOS_PAGEOUT,
133 	DAMOS_HUGEPAGE,
134 	DAMOS_NOHUGEPAGE,
135 	DAMOS_LRU_PRIO,
136 	DAMOS_LRU_DEPRIO,
137 	DAMOS_MIGRATE_HOT,
138 	DAMOS_MIGRATE_COLD,
139 	DAMOS_STAT,		/* Do nothing but only record the stat */
140 	NR_DAMOS_ACTIONS,
141 };
142 
143 /**
144  * enum damos_quota_goal_metric - Represents the metric to be used as the goal
145  *
146  * @DAMOS_QUOTA_USER_INPUT:	User-input value.
147  * @DAMOS_QUOTA_SOME_MEM_PSI_US:	System level some memory PSI in us.
148  * @NR_DAMOS_QUOTA_GOAL_METRICS:	Number of DAMOS quota goal metrics.
149  *
150  * Metrics equal to larger than @NR_DAMOS_QUOTA_GOAL_METRICS are unsupported.
151  */
152 enum damos_quota_goal_metric {
153 	DAMOS_QUOTA_USER_INPUT,
154 	DAMOS_QUOTA_SOME_MEM_PSI_US,
155 	NR_DAMOS_QUOTA_GOAL_METRICS,
156 };
157 
158 /**
159  * struct damos_quota_goal - DAMOS scheme quota auto-tuning goal.
160  * @metric:		Metric to be used for representing the goal.
161  * @target_value:	Target value of @metric to achieve with the tuning.
162  * @current_value:	Current value of @metric.
163  * @last_psi_total:	Last measured total PSI
164  * @list:		List head for siblings.
165  *
166  * Data structure for getting the current score of the quota tuning goal.  The
167  * score is calculated by how close @current_value and @target_value are.  Then
168  * the score is entered to DAMON's internal feedback loop mechanism to get the
169  * auto-tuned quota.
170  *
171  * If @metric is DAMOS_QUOTA_USER_INPUT, @current_value should be manually
172  * entered by the user, probably inside the kdamond callbacks.  Otherwise,
173  * DAMON sets @current_value with self-measured value of @metric.
174  */
175 struct damos_quota_goal {
176 	enum damos_quota_goal_metric metric;
177 	unsigned long target_value;
178 	unsigned long current_value;
179 	/* metric-dependent fields */
180 	union {
181 		u64 last_psi_total;
182 	};
183 	struct list_head list;
184 };
185 
186 /**
187  * struct damos_quota - Controls the aggressiveness of the given scheme.
188  * @reset_interval:	Charge reset interval in milliseconds.
189  * @ms:			Maximum milliseconds that the scheme can use.
190  * @sz:			Maximum bytes of memory that the action can be applied.
191  * @goals:		Head of quota tuning goals (&damos_quota_goal) list.
192  * @esz:		Effective size quota in bytes.
193  *
194  * @weight_sz:		Weight of the region's size for prioritization.
195  * @weight_nr_accesses:	Weight of the region's nr_accesses for prioritization.
196  * @weight_age:		Weight of the region's age for prioritization.
197  *
198  * To avoid consuming too much CPU time or IO resources for applying the
199  * &struct damos->action to large memory, DAMON allows users to set time and/or
200  * size quotas.  The quotas can be set by writing non-zero values to &ms and
201  * &sz, respectively.  If the time quota is set, DAMON tries to use only up to
202  * &ms milliseconds within &reset_interval for applying the action.  If the
203  * size quota is set, DAMON tries to apply the action only up to &sz bytes
204  * within &reset_interval.
205  *
206  * To convince the different types of quotas and goals, DAMON internally
207  * converts those into one single size quota called "effective quota".  DAMON
208  * internally uses it as the only one real quota.  The conversion is made as
209  * follows.
210  *
211  * The time quota is transformed to a size quota using estimated throughput of
212  * the scheme's action.  DAMON then compares it against &sz and uses smaller
213  * one as the effective quota.
214  *
215  * If @goals is not empty, DAMON calculates yet another size quota based on the
216  * goals using its internal feedback loop algorithm, for every @reset_interval.
217  * Then, if the new size quota is smaller than the effective quota, it uses the
218  * new size quota as the effective quota.
219  *
220  * The resulting effective size quota in bytes is set to @esz.
221  *
222  * For selecting regions within the quota, DAMON prioritizes current scheme's
223  * target memory regions using the &struct damon_operations->get_scheme_score.
224  * You could customize the prioritization logic by setting &weight_sz,
225  * &weight_nr_accesses, and &weight_age, because monitoring operations are
226  * encouraged to respect those.
227  */
228 struct damos_quota {
229 	unsigned long reset_interval;
230 	unsigned long ms;
231 	unsigned long sz;
232 	struct list_head goals;
233 	unsigned long esz;
234 
235 	unsigned int weight_sz;
236 	unsigned int weight_nr_accesses;
237 	unsigned int weight_age;
238 
239 /* private: */
240 	/* For throughput estimation */
241 	unsigned long total_charged_sz;
242 	unsigned long total_charged_ns;
243 
244 	/* For charging the quota */
245 	unsigned long charged_sz;
246 	unsigned long charged_from;
247 	struct damon_target *charge_target_from;
248 	unsigned long charge_addr_from;
249 
250 	/* For prioritization */
251 	unsigned int min_score;
252 
253 	/* For feedback loop */
254 	unsigned long esz_bp;
255 };
256 
257 /**
258  * enum damos_wmark_metric - Represents the watermark metric.
259  *
260  * @DAMOS_WMARK_NONE:		Ignore the watermarks of the given scheme.
261  * @DAMOS_WMARK_FREE_MEM_RATE:	Free memory rate of the system in [0,1000].
262  * @NR_DAMOS_WMARK_METRICS:	Total number of DAMOS watermark metrics
263  */
264 enum damos_wmark_metric {
265 	DAMOS_WMARK_NONE,
266 	DAMOS_WMARK_FREE_MEM_RATE,
267 	NR_DAMOS_WMARK_METRICS,
268 };
269 
270 /**
271  * struct damos_watermarks - Controls when a given scheme should be activated.
272  * @metric:	Metric for the watermarks.
273  * @interval:	Watermarks check time interval in microseconds.
274  * @high:	High watermark.
275  * @mid:	Middle watermark.
276  * @low:	Low watermark.
277  *
278  * If &metric is &DAMOS_WMARK_NONE, the scheme is always active.  Being active
279  * means DAMON does monitoring and applying the action of the scheme to
280  * appropriate memory regions.  Else, DAMON checks &metric of the system for at
281  * least every &interval microseconds and works as below.
282  *
283  * If &metric is higher than &high, the scheme is inactivated.  If &metric is
284  * between &mid and &low, the scheme is activated.  If &metric is lower than
285  * &low, the scheme is inactivated.
286  */
287 struct damos_watermarks {
288 	enum damos_wmark_metric metric;
289 	unsigned long interval;
290 	unsigned long high;
291 	unsigned long mid;
292 	unsigned long low;
293 
294 /* private: */
295 	bool activated;
296 };
297 
298 /**
299  * struct damos_stat - Statistics on a given scheme.
300  * @nr_tried:	Total number of regions that the scheme is tried to be applied.
301  * @sz_tried:	Total size of regions that the scheme is tried to be applied.
302  * @nr_applied:	Total number of regions that the scheme is applied.
303  * @sz_applied:	Total size of regions that the scheme is applied.
304  * @sz_ops_filter_passed:
305  *		Total bytes that passed ops layer-handled DAMOS filters.
306  * @qt_exceeds: Total number of times the quota of the scheme has exceeded.
307  *
308  * "Tried an action to a region" in this context means the DAMOS core logic
309  * determined the region as eligible to apply the action.  The access pattern
310  * (&struct damos_access_pattern), quotas (&struct damos_quota), watermarks
311  * (&struct damos_watermarks) and filters (&struct damos_filter) that handled
312  * on core logic can affect this.  The core logic asks the operation set
313  * (&struct damon_operations) to apply the action to the region.
314  *
315  * "Applied an action to a region" in this context means the operation set
316  * (&struct damon_operations) successfully applied the action to the region, at
317  * least to a part of the region.  The filters (&struct damos_filter) that
318  * handled on operation set layer and type of the action and pages of the
319  * region can affect this.  For example, if a filter is set to exclude
320  * anonymous pages and the region has only anonymous pages, the region will be
321  * failed at applying the action.  If the action is &DAMOS_PAGEOUT and all
322  * pages of the region are already paged out, the region will be failed at
323  * applying the action.
324  */
325 struct damos_stat {
326 	unsigned long nr_tried;
327 	unsigned long sz_tried;
328 	unsigned long nr_applied;
329 	unsigned long sz_applied;
330 	unsigned long sz_ops_filter_passed;
331 	unsigned long qt_exceeds;
332 };
333 
334 /**
335  * enum damos_filter_type - Type of memory for &struct damos_filter
336  * @DAMOS_FILTER_TYPE_ANON:	Anonymous pages.
337  * @DAMOS_FILTER_TYPE_MEMCG:	Specific memcg's pages.
338  * @DAMOS_FILTER_TYPE_YOUNG:	Recently accessed pages.
339  * @DAMOS_FILTER_TYPE_HUGEPAGE_SIZE:	Page is part of a hugepage.
340  * @DAMOS_FILTER_TYPE_UNMAPPED:	Unmapped pages.
341  * @DAMOS_FILTER_TYPE_ADDR:	Address range.
342  * @DAMOS_FILTER_TYPE_TARGET:	Data Access Monitoring target.
343  * @NR_DAMOS_FILTER_TYPES:	Number of filter types.
344  *
345  * The anon pages type and memcg type filters are handled by underlying
346  * &struct damon_operations as a part of scheme action trying, and therefore
347  * accounted as 'tried'.  In contrast, other types are handled by core layer
348  * before trying of the action and therefore not accounted as 'tried'.
349  *
350  * The support of the filters that handled by &struct damon_operations depend
351  * on the running &struct damon_operations.
352  * &enum DAMON_OPS_PADDR supports both anon pages type and memcg type filters,
353  * while &enum DAMON_OPS_VADDR and &enum DAMON_OPS_FVADDR don't support any of
354  * the two types.
355  */
356 enum damos_filter_type {
357 	DAMOS_FILTER_TYPE_ANON,
358 	DAMOS_FILTER_TYPE_MEMCG,
359 	DAMOS_FILTER_TYPE_YOUNG,
360 	DAMOS_FILTER_TYPE_HUGEPAGE_SIZE,
361 	DAMOS_FILTER_TYPE_UNMAPPED,
362 	DAMOS_FILTER_TYPE_ADDR,
363 	DAMOS_FILTER_TYPE_TARGET,
364 	NR_DAMOS_FILTER_TYPES,
365 };
366 
367 /**
368  * struct damos_filter - DAMOS action target memory filter.
369  * @type:	Type of the target memory.
370  * @matching:	Whether this is for @type-matching memory.
371  * @allow:	Whether to include or exclude the @matching memory.
372  * @memcg_id:	Memcg id of the question if @type is DAMOS_FILTER_MEMCG.
373  * @addr_range:	Address range if @type is DAMOS_FILTER_TYPE_ADDR.
374  * @target_idx:	Index of the &struct damon_target of
375  *		&damon_ctx->adaptive_targets if @type is
376  *		DAMOS_FILTER_TYPE_TARGET.
377  * @sz_range:	Size range if @type is DAMOS_FILTER_TYPE_HUGEPAGE_SIZE.
378  * @list:	List head for siblings.
379  *
380  * Before applying the &damos->action to a memory region, DAMOS checks if each
381  * byte of the region matches to this given condition and avoid applying the
382  * action if so.  Support of each filter type depends on the running &struct
383  * damon_operations and the type.  Refer to &enum damos_filter_type for more
384  * details.
385  */
386 struct damos_filter {
387 	enum damos_filter_type type;
388 	bool matching;
389 	bool allow;
390 	union {
391 		unsigned short memcg_id;
392 		struct damon_addr_range addr_range;
393 		int target_idx;
394 		struct damon_size_range sz_range;
395 	};
396 	struct list_head list;
397 };
398 
399 struct damon_ctx;
400 struct damos;
401 
402 /**
403  * struct damos_walk_control - Control damos_walk().
404  *
405  * @walk_fn:	Function to be called back for each region.
406  * @data:	Data that will be passed to walk functions.
407  *
408  * Control damos_walk(), which requests specific kdamond to invoke the given
409  * function to each region that eligible to apply actions of the kdamond's
410  * schemes.  Refer to damos_walk() for more details.
411  */
412 struct damos_walk_control {
413 	void (*walk_fn)(void *data, struct damon_ctx *ctx,
414 			struct damon_target *t, struct damon_region *r,
415 			struct damos *s, unsigned long sz_filter_passed);
416 	void *data;
417 /* private: internal use only */
418 	/* informs if the kdamond finished handling of the walk request */
419 	struct completion completion;
420 	/* informs if the walk is canceled. */
421 	bool canceled;
422 };
423 
424 /**
425  * struct damos_access_pattern - Target access pattern of the given scheme.
426  * @min_sz_region:	Minimum size of target regions.
427  * @max_sz_region:	Maximum size of target regions.
428  * @min_nr_accesses:	Minimum ``->nr_accesses`` of target regions.
429  * @max_nr_accesses:	Maximum ``->nr_accesses`` of target regions.
430  * @min_age_region:	Minimum age of target regions.
431  * @max_age_region:	Maximum age of target regions.
432  */
433 struct damos_access_pattern {
434 	unsigned long min_sz_region;
435 	unsigned long max_sz_region;
436 	unsigned int min_nr_accesses;
437 	unsigned int max_nr_accesses;
438 	unsigned int min_age_region;
439 	unsigned int max_age_region;
440 };
441 
442 /**
443  * struct damos - Represents a Data Access Monitoring-based Operation Scheme.
444  * @pattern:		Access pattern of target regions.
445  * @action:		&damo_action to be applied to the target regions.
446  * @apply_interval_us:	The time between applying the @action.
447  * @quota:		Control the aggressiveness of this scheme.
448  * @wmarks:		Watermarks for automated (in)activation of this scheme.
449  * @target_nid:		Destination node if @action is "migrate_{hot,cold}".
450  * @filters:		Additional set of &struct damos_filter for &action.
451  * @last_applied:	Last @action applied ops-managing entity.
452  * @stat:		Statistics of this scheme.
453  * @list:		List head for siblings.
454  *
455  * For each @apply_interval_us, DAMON finds regions which fit in the
456  * &pattern and applies &action to those. To avoid consuming too much
457  * CPU time or IO resources for the &action, &quota is used.
458  *
459  * If @apply_interval_us is zero, &damon_attrs->aggr_interval is used instead.
460  *
461  * To do the work only when needed, schemes can be activated for specific
462  * system situations using &wmarks.  If all schemes that registered to the
463  * monitoring context are inactive, DAMON stops monitoring either, and just
464  * repeatedly checks the watermarks.
465  *
466  * @target_nid is used to set the migration target node for migrate_hot or
467  * migrate_cold actions, which means it's only meaningful when @action is either
468  * "migrate_hot" or "migrate_cold".
469  *
470  * Before applying the &action to a memory region, &struct damon_operations
471  * implementation could check pages of the region and skip &action to respect
472  * &filters
473  *
474  * The minimum entity that @action can be applied depends on the underlying
475  * &struct damon_operations.  Since it may not be aligned with the core layer
476  * abstract, namely &struct damon_region, &struct damon_operations could apply
477  * @action to same entity multiple times.  Large folios that underlying on
478  * multiple &struct damon region objects could be such examples.  The &struct
479  * damon_operations can use @last_applied to avoid that.  DAMOS core logic
480  * unsets @last_applied when each regions walking for applying the scheme is
481  * finished.
482  *
483  * After applying the &action to each region, &stat_count and &stat_sz is
484  * updated to reflect the number of regions and total size of regions that the
485  * &action is applied.
486  */
487 struct damos {
488 	struct damos_access_pattern pattern;
489 	enum damos_action action;
490 	unsigned long apply_interval_us;
491 /* private: internal use only */
492 	/*
493 	 * number of sample intervals that should be passed before applying
494 	 * @action
495 	 */
496 	unsigned long next_apply_sis;
497 	/* informs if ongoing DAMOS walk for this scheme is finished */
498 	bool walk_completed;
499 	/*
500 	 * If the current region in the filtering stage is allowed by core
501 	 * layer-handled filters.  If true, operations layer allows it, too.
502 	 */
503 	bool core_filters_allowed;
504 /* public: */
505 	struct damos_quota quota;
506 	struct damos_watermarks wmarks;
507 	union {
508 		int target_nid;
509 	};
510 	struct list_head filters;
511 	void *last_applied;
512 	struct damos_stat stat;
513 	struct list_head list;
514 };
515 
516 /**
517  * enum damon_ops_id - Identifier for each monitoring operations implementation
518  *
519  * @DAMON_OPS_VADDR:	Monitoring operations for virtual address spaces
520  * @DAMON_OPS_FVADDR:	Monitoring operations for only fixed ranges of virtual
521  *			address spaces
522  * @DAMON_OPS_PADDR:	Monitoring operations for the physical address space
523  * @NR_DAMON_OPS:	Number of monitoring operations implementations
524  */
525 enum damon_ops_id {
526 	DAMON_OPS_VADDR,
527 	DAMON_OPS_FVADDR,
528 	DAMON_OPS_PADDR,
529 	NR_DAMON_OPS,
530 };
531 
532 /**
533  * struct damon_operations - Monitoring operations for given use cases.
534  *
535  * @id:				Identifier of this operations set.
536  * @init:			Initialize operations-related data structures.
537  * @update:			Update operations-related data structures.
538  * @prepare_access_checks:	Prepare next access check of target regions.
539  * @check_accesses:		Check the accesses to target regions.
540  * @reset_aggregated:		Reset aggregated accesses monitoring results.
541  * @get_scheme_score:		Get the score of a region for a scheme.
542  * @apply_scheme:		Apply a DAMON-based operation scheme.
543  * @target_valid:		Determine if the target is valid.
544  * @cleanup:			Clean up the context.
545  *
546  * DAMON can be extended for various address spaces and usages.  For this,
547  * users should register the low level operations for their target address
548  * space and usecase via the &damon_ctx.ops.  Then, the monitoring thread
549  * (&damon_ctx.kdamond) calls @init and @prepare_access_checks before starting
550  * the monitoring, @update after each &damon_attrs.ops_update_interval, and
551  * @check_accesses, @target_valid and @prepare_access_checks after each
552  * &damon_attrs.sample_interval.  Finally, @reset_aggregated is called after
553  * each &damon_attrs.aggr_interval.
554  *
555  * Each &struct damon_operations instance having valid @id can be registered
556  * via damon_register_ops() and selected by damon_select_ops() later.
557  * @init should initialize operations-related data structures.  For example,
558  * this could be used to construct proper monitoring target regions and link
559  * those to @damon_ctx.adaptive_targets.
560  * @update should update the operations-related data structures.  For example,
561  * this could be used to update monitoring target regions for current status.
562  * @prepare_access_checks should manipulate the monitoring regions to be
563  * prepared for the next access check.
564  * @check_accesses should check the accesses to each region that made after the
565  * last preparation and update the number of observed accesses of each region.
566  * It should also return max number of observed accesses that made as a result
567  * of its update.  The value will be used for regions adjustment threshold.
568  * @reset_aggregated should reset the access monitoring results that aggregated
569  * by @check_accesses.
570  * @get_scheme_score should return the priority score of a region for a scheme
571  * as an integer in [0, &DAMOS_MAX_SCORE].
572  * @apply_scheme is called from @kdamond when a region for user provided
573  * DAMON-based operation scheme is found.  It should apply the scheme's action
574  * to the region and return bytes of the region that the action is successfully
575  * applied.  It should also report how many bytes of the region has passed
576  * filters (&struct damos_filter) that handled by itself.
577  * @target_valid should check whether the target is still valid for the
578  * monitoring.
579  * @cleanup is called from @kdamond just before its termination.
580  */
581 struct damon_operations {
582 	enum damon_ops_id id;
583 	void (*init)(struct damon_ctx *context);
584 	void (*update)(struct damon_ctx *context);
585 	void (*prepare_access_checks)(struct damon_ctx *context);
586 	unsigned int (*check_accesses)(struct damon_ctx *context);
587 	void (*reset_aggregated)(struct damon_ctx *context);
588 	int (*get_scheme_score)(struct damon_ctx *context,
589 			struct damon_target *t, struct damon_region *r,
590 			struct damos *scheme);
591 	unsigned long (*apply_scheme)(struct damon_ctx *context,
592 			struct damon_target *t, struct damon_region *r,
593 			struct damos *scheme, unsigned long *sz_filter_passed);
594 	bool (*target_valid)(struct damon_target *t);
595 	void (*cleanup)(struct damon_ctx *context);
596 };
597 
598 /**
599  * struct damon_callback - Monitoring events notification callbacks.
600  *
601  * @before_start:	Called before starting the monitoring.
602  * @after_wmarks_check:	Called after each schemes' watermarks check.
603  * @after_sampling:	Called after each sampling.
604  * @after_aggregation:	Called after each aggregation.
605  * @before_damos_apply:	Called before applying DAMOS action.
606  * @before_terminate:	Called before terminating the monitoring.
607  * @private:		User private data.
608  *
609  * The monitoring thread (&damon_ctx.kdamond) calls @before_start and
610  * @before_terminate just before starting and finishing the monitoring,
611  * respectively.  Therefore, those are good places for installing and cleaning
612  * @private.
613  *
614  * The monitoring thread calls @after_wmarks_check after each DAMON-based
615  * operation schemes' watermarks check.  If users need to make changes to the
616  * attributes of the monitoring context while it's deactivated due to the
617  * watermarks, this is the good place to do.
618  *
619  * The monitoring thread calls @after_sampling and @after_aggregation for each
620  * of the sampling intervals and aggregation intervals, respectively.
621  * Therefore, users can safely access the monitoring results without additional
622  * protection.  For the reason, users are recommended to use these callback for
623  * the accesses to the results.
624  *
625  * If any callback returns non-zero, monitoring stops.
626  */
627 struct damon_callback {
628 	void *private;
629 
630 	int (*before_start)(struct damon_ctx *context);
631 	int (*after_wmarks_check)(struct damon_ctx *context);
632 	int (*after_sampling)(struct damon_ctx *context);
633 	int (*after_aggregation)(struct damon_ctx *context);
634 	int (*before_damos_apply)(struct damon_ctx *context,
635 			struct damon_target *target,
636 			struct damon_region *region,
637 			struct damos *scheme);
638 	void (*before_terminate)(struct damon_ctx *context);
639 };
640 
641 /*
642  * struct damon_call_control - Control damon_call().
643  *
644  * @fn:			Function to be called back.
645  * @data:		Data that will be passed to @fn.
646  * @return_code:	Return code from @fn invocation.
647  *
648  * Control damon_call(), which requests specific kdamond to invoke a given
649  * function.  Refer to damon_call() for more details.
650  */
651 struct damon_call_control {
652 	int (*fn)(void *data);
653 	void *data;
654 	int return_code;
655 /* private: internal use only */
656 	/* informs if the kdamond finished handling of the request */
657 	struct completion completion;
658 	/* informs if the kdamond canceled @fn infocation */
659 	bool canceled;
660 };
661 
662 /**
663  * struct damon_intervals_goal - Monitoring intervals auto-tuning goal.
664  *
665  * @access_bp:		Access events observation ratio to achieve in bp.
666  * @aggrs:		Number of aggregations to acheive @access_bp within.
667  * @min_sample_us:	Minimum resulting sampling interval in microseconds.
668  * @max_sample_us:	Maximum resulting sampling interval in microseconds.
669  *
670  * DAMON automatically tunes &damon_attrs->sample_interval and
671  * &damon_attrs->aggr_interval aiming the ratio in bp (1/10,000) of
672  * DAMON-observed access events to theoretical maximum amount within @aggrs
673  * aggregations be same to @access_bp.  The logic increases
674  * &damon_attrs->aggr_interval and &damon_attrs->sampling_interval in same
675  * ratio if the current access events observation ratio is lower than the
676  * target for each @aggrs aggregations, and vice versa.
677  *
678  * If @aggrs is zero, the tuning is disabled and hence this struct is ignored.
679  */
680 struct damon_intervals_goal {
681 	unsigned long access_bp;
682 	unsigned long aggrs;
683 	unsigned long min_sample_us;
684 	unsigned long max_sample_us;
685 };
686 
687 /**
688  * struct damon_attrs - Monitoring attributes for accuracy/overhead control.
689  *
690  * @sample_interval:		The time between access samplings.
691  * @aggr_interval:		The time between monitor results aggregations.
692  * @ops_update_interval:	The time between monitoring operations updates.
693  * @intervals_goal:		Intervals auto-tuning goal.
694  * @min_nr_regions:		The minimum number of adaptive monitoring
695  *				regions.
696  * @max_nr_regions:		The maximum number of adaptive monitoring
697  *				regions.
698  *
699  * For each @sample_interval, DAMON checks whether each region is accessed or
700  * not during the last @sample_interval.  If such access is found, DAMON
701  * aggregates the information by increasing &damon_region->nr_accesses for
702  * @aggr_interval time.  For each @aggr_interval, the count is reset.  DAMON
703  * also checks whether the target memory regions need update (e.g., by
704  * ``mmap()`` calls from the application, in case of virtual memory monitoring)
705  * and applies the changes for each @ops_update_interval.  All time intervals
706  * are in micro-seconds.  Please refer to &struct damon_operations and &struct
707  * damon_callback for more detail.
708  */
709 struct damon_attrs {
710 	unsigned long sample_interval;
711 	unsigned long aggr_interval;
712 	unsigned long ops_update_interval;
713 	struct damon_intervals_goal intervals_goal;
714 	unsigned long min_nr_regions;
715 	unsigned long max_nr_regions;
716 /* private: internal use only */
717 	/*
718 	 * @aggr_interval to @sample_interval ratio.
719 	 * Core-external components call damon_set_attrs() with &damon_attrs
720 	 * that this field is unset.  In the case, damon_set_attrs() sets this
721 	 * field of resulting &damon_attrs.  Core-internal components such as
722 	 * kdamond_tune_intervals() calls damon_set_attrs() with &damon_attrs
723 	 * that this field is set.  In the case, damon_set_attrs() just keep
724 	 * it.
725 	 */
726 	unsigned long aggr_samples;
727 };
728 
729 /**
730  * struct damon_ctx - Represents a context for each monitoring.  This is the
731  * main interface that allows users to set the attributes and get the results
732  * of the monitoring.
733  *
734  * @attrs:		Monitoring attributes for accuracy/overhead control.
735  * @kdamond:		Kernel thread who does the monitoring.
736  * @kdamond_lock:	Mutex for the synchronizations with @kdamond.
737  *
738  * For each monitoring context, one kernel thread for the monitoring is
739  * created.  The pointer to the thread is stored in @kdamond.
740  *
741  * Once started, the monitoring thread runs until explicitly required to be
742  * terminated or every monitoring target is invalid.  The validity of the
743  * targets is checked via the &damon_operations.target_valid of @ops.  The
744  * termination can also be explicitly requested by calling damon_stop().
745  * The thread sets @kdamond to NULL when it terminates. Therefore, users can
746  * know whether the monitoring is ongoing or terminated by reading @kdamond.
747  * Reads and writes to @kdamond from outside of the monitoring thread must
748  * be protected by @kdamond_lock.
749  *
750  * Note that the monitoring thread protects only @kdamond via @kdamond_lock.
751  * Accesses to other fields must be protected by themselves.
752  *
753  * @ops:	Set of monitoring operations for given use cases.
754  * @callback:	Set of callbacks for monitoring events notifications.
755  *
756  * @adaptive_targets:	Head of monitoring targets (&damon_target) list.
757  * @schemes:		Head of schemes (&damos) list.
758  */
759 struct damon_ctx {
760 	struct damon_attrs attrs;
761 
762 /* private: internal use only */
763 	/* number of sample intervals that passed since this context started */
764 	unsigned long passed_sample_intervals;
765 	/*
766 	 * number of sample intervals that should be passed before next
767 	 * aggregation
768 	 */
769 	unsigned long next_aggregation_sis;
770 	/*
771 	 * number of sample intervals that should be passed before next ops
772 	 * update
773 	 */
774 	unsigned long next_ops_update_sis;
775 	/*
776 	 * number of sample intervals that should be passed before next
777 	 * intervals tuning
778 	 */
779 	unsigned long next_intervals_tune_sis;
780 	/* for waiting until the execution of the kdamond_fn is started */
781 	struct completion kdamond_started;
782 	/* for scheme quotas prioritization */
783 	unsigned long *regions_score_histogram;
784 
785 	struct damon_call_control *call_control;
786 	struct mutex call_control_lock;
787 
788 	struct damos_walk_control *walk_control;
789 	struct mutex walk_control_lock;
790 
791 /* public: */
792 	struct task_struct *kdamond;
793 	struct mutex kdamond_lock;
794 
795 	struct damon_operations ops;
796 	struct damon_callback callback;
797 
798 	struct list_head adaptive_targets;
799 	struct list_head schemes;
800 };
801 
802 static inline struct damon_region *damon_next_region(struct damon_region *r)
803 {
804 	return container_of(r->list.next, struct damon_region, list);
805 }
806 
807 static inline struct damon_region *damon_prev_region(struct damon_region *r)
808 {
809 	return container_of(r->list.prev, struct damon_region, list);
810 }
811 
812 static inline struct damon_region *damon_last_region(struct damon_target *t)
813 {
814 	return list_last_entry(&t->regions_list, struct damon_region, list);
815 }
816 
817 static inline struct damon_region *damon_first_region(struct damon_target *t)
818 {
819 	return list_first_entry(&t->regions_list, struct damon_region, list);
820 }
821 
822 static inline unsigned long damon_sz_region(struct damon_region *r)
823 {
824 	return r->ar.end - r->ar.start;
825 }
826 
827 
828 #define damon_for_each_region(r, t) \
829 	list_for_each_entry(r, &t->regions_list, list)
830 
831 #define damon_for_each_region_from(r, t) \
832 	list_for_each_entry_from(r, &t->regions_list, list)
833 
834 #define damon_for_each_region_safe(r, next, t) \
835 	list_for_each_entry_safe(r, next, &t->regions_list, list)
836 
837 #define damon_for_each_target(t, ctx) \
838 	list_for_each_entry(t, &(ctx)->adaptive_targets, list)
839 
840 #define damon_for_each_target_safe(t, next, ctx)	\
841 	list_for_each_entry_safe(t, next, &(ctx)->adaptive_targets, list)
842 
843 #define damon_for_each_scheme(s, ctx) \
844 	list_for_each_entry(s, &(ctx)->schemes, list)
845 
846 #define damon_for_each_scheme_safe(s, next, ctx) \
847 	list_for_each_entry_safe(s, next, &(ctx)->schemes, list)
848 
849 #define damos_for_each_quota_goal(goal, quota) \
850 	list_for_each_entry(goal, &quota->goals, list)
851 
852 #define damos_for_each_quota_goal_safe(goal, next, quota) \
853 	list_for_each_entry_safe(goal, next, &(quota)->goals, list)
854 
855 #define damos_for_each_filter(f, scheme) \
856 	list_for_each_entry(f, &(scheme)->filters, list)
857 
858 #define damos_for_each_filter_safe(f, next, scheme) \
859 	list_for_each_entry_safe(f, next, &(scheme)->filters, list)
860 
861 #ifdef CONFIG_DAMON
862 
863 struct damon_region *damon_new_region(unsigned long start, unsigned long end);
864 
865 /*
866  * Add a region between two other regions
867  */
868 static inline void damon_insert_region(struct damon_region *r,
869 		struct damon_region *prev, struct damon_region *next,
870 		struct damon_target *t)
871 {
872 	__list_add(&r->list, &prev->list, &next->list);
873 	t->nr_regions++;
874 }
875 
876 void damon_add_region(struct damon_region *r, struct damon_target *t);
877 void damon_destroy_region(struct damon_region *r, struct damon_target *t);
878 int damon_set_regions(struct damon_target *t, struct damon_addr_range *ranges,
879 		unsigned int nr_ranges);
880 void damon_update_region_access_rate(struct damon_region *r, bool accessed,
881 		struct damon_attrs *attrs);
882 
883 struct damos_filter *damos_new_filter(enum damos_filter_type type,
884 		bool matching, bool allow);
885 void damos_add_filter(struct damos *s, struct damos_filter *f);
886 void damos_destroy_filter(struct damos_filter *f);
887 
888 struct damos_quota_goal *damos_new_quota_goal(
889 		enum damos_quota_goal_metric metric,
890 		unsigned long target_value);
891 void damos_add_quota_goal(struct damos_quota *q, struct damos_quota_goal *g);
892 void damos_destroy_quota_goal(struct damos_quota_goal *goal);
893 
894 struct damos *damon_new_scheme(struct damos_access_pattern *pattern,
895 			enum damos_action action,
896 			unsigned long apply_interval_us,
897 			struct damos_quota *quota,
898 			struct damos_watermarks *wmarks,
899 			int target_nid);
900 void damon_add_scheme(struct damon_ctx *ctx, struct damos *s);
901 void damon_destroy_scheme(struct damos *s);
902 int damos_commit_quota_goals(struct damos_quota *dst, struct damos_quota *src);
903 
904 struct damon_target *damon_new_target(void);
905 void damon_add_target(struct damon_ctx *ctx, struct damon_target *t);
906 bool damon_targets_empty(struct damon_ctx *ctx);
907 void damon_free_target(struct damon_target *t);
908 void damon_destroy_target(struct damon_target *t);
909 unsigned int damon_nr_regions(struct damon_target *t);
910 
911 struct damon_ctx *damon_new_ctx(void);
912 void damon_destroy_ctx(struct damon_ctx *ctx);
913 int damon_set_attrs(struct damon_ctx *ctx, struct damon_attrs *attrs);
914 void damon_set_schemes(struct damon_ctx *ctx,
915 			struct damos **schemes, ssize_t nr_schemes);
916 int damon_commit_ctx(struct damon_ctx *old_ctx, struct damon_ctx *new_ctx);
917 int damon_nr_running_ctxs(void);
918 bool damon_is_registered_ops(enum damon_ops_id id);
919 int damon_register_ops(struct damon_operations *ops);
920 int damon_select_ops(struct damon_ctx *ctx, enum damon_ops_id id);
921 
922 static inline bool damon_target_has_pid(const struct damon_ctx *ctx)
923 {
924 	return ctx->ops.id == DAMON_OPS_VADDR || ctx->ops.id == DAMON_OPS_FVADDR;
925 }
926 
927 static inline unsigned int damon_max_nr_accesses(const struct damon_attrs *attrs)
928 {
929 	/* {aggr,sample}_interval are unsigned long, hence could overflow */
930 	return min(attrs->aggr_interval / attrs->sample_interval,
931 			(unsigned long)UINT_MAX);
932 }
933 
934 
935 int damon_start(struct damon_ctx **ctxs, int nr_ctxs, bool exclusive);
936 int damon_stop(struct damon_ctx **ctxs, int nr_ctxs);
937 
938 int damon_call(struct damon_ctx *ctx, struct damon_call_control *control);
939 int damos_walk(struct damon_ctx *ctx, struct damos_walk_control *control);
940 
941 int damon_set_region_biggest_system_ram_default(struct damon_target *t,
942 				unsigned long *start, unsigned long *end);
943 
944 #endif	/* CONFIG_DAMON */
945 
946 #endif	/* _DAMON_H */
947