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