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