1 // SPDX-License-Identifier: GPL-2.0 2 /* 3 * Data Access Monitor 4 */ 5 6 #define pr_fmt(fmt) "damon: " fmt 7 8 #include <linux/damon.h> 9 #include <linux/delay.h> 10 #include <linux/kthread.h> 11 #include <linux/memcontrol.h> 12 #include <linux/mm.h> 13 #include <linux/psi.h> 14 #include <linux/sched.h> 15 #include <linux/slab.h> 16 #include <linux/string.h> 17 #include <linux/string_choices.h> 18 19 /* for damon_get_folio() used by node eligible memory metrics */ 20 #include "ops-common.h" 21 22 #define CREATE_TRACE_POINTS 23 #include <trace/events/damon.h> 24 25 static DEFINE_MUTEX(damon_lock); 26 static int nr_running_ctxs; 27 static bool running_exclusive_ctxs; 28 29 static DEFINE_MUTEX(damon_ops_lock); 30 static struct damon_operations damon_registered_ops[NR_DAMON_OPS]; 31 32 static struct kmem_cache *damon_region_cache __ro_after_init; 33 34 /* Should be called under damon_ops_lock with id smaller than NR_DAMON_OPS */ 35 static bool __damon_is_registered_ops(enum damon_ops_id id) 36 { 37 struct damon_operations empty_ops = {}; 38 39 if (!memcmp(&empty_ops, &damon_registered_ops[id], sizeof(empty_ops))) 40 return false; 41 return true; 42 } 43 44 /** 45 * damon_is_registered_ops() - Check if a given damon_operations is registered. 46 * @id: Id of the damon_operations to check if registered. 47 * 48 * Return: true if the ops is set, false otherwise. 49 */ 50 bool damon_is_registered_ops(enum damon_ops_id id) 51 { 52 bool registered; 53 54 if (id >= NR_DAMON_OPS) 55 return false; 56 mutex_lock(&damon_ops_lock); 57 registered = __damon_is_registered_ops(id); 58 mutex_unlock(&damon_ops_lock); 59 return registered; 60 } 61 62 /** 63 * damon_register_ops() - Register a monitoring operations set to DAMON. 64 * @ops: monitoring operations set to register. 65 * 66 * This function registers a monitoring operations set of valid &struct 67 * damon_operations->id so that others can find and use them later. 68 * 69 * Return: 0 on success, negative error code otherwise. 70 */ 71 int damon_register_ops(struct damon_operations *ops) 72 { 73 int err = 0; 74 75 if (ops->id >= NR_DAMON_OPS) 76 return -EINVAL; 77 78 mutex_lock(&damon_ops_lock); 79 /* Fail for already registered ops */ 80 if (__damon_is_registered_ops(ops->id)) 81 err = -EINVAL; 82 else 83 damon_registered_ops[ops->id] = *ops; 84 mutex_unlock(&damon_ops_lock); 85 return err; 86 } 87 88 /** 89 * damon_select_ops() - Select a monitoring operations to use with the context. 90 * @ctx: monitoring context to use the operations. 91 * @id: id of the registered monitoring operations to select. 92 * 93 * This function finds registered monitoring operations set of @id and make 94 * @ctx to use it. 95 * 96 * Return: 0 on success, negative error code otherwise. 97 */ 98 int damon_select_ops(struct damon_ctx *ctx, enum damon_ops_id id) 99 { 100 int err = 0; 101 102 if (id >= NR_DAMON_OPS) 103 return -EINVAL; 104 105 mutex_lock(&damon_ops_lock); 106 if (!__damon_is_registered_ops(id)) 107 err = -EINVAL; 108 else 109 ctx->ops = damon_registered_ops[id]; 110 mutex_unlock(&damon_ops_lock); 111 return err; 112 } 113 114 struct damon_filter *damon_new_filter(enum damon_filter_type type, 115 bool matching, bool allow) 116 { 117 struct damon_filter *filter; 118 119 filter = kmalloc_obj(*filter); 120 if (!filter) 121 return NULL; 122 filter->type = type; 123 filter->matching = matching; 124 filter->allow = allow; 125 INIT_LIST_HEAD(&filter->list); 126 return filter; 127 } 128 129 void damon_add_filter(struct damon_probe *p, struct damon_filter *f) 130 { 131 list_add_tail(&f->list, &p->filters); 132 } 133 134 static void damon_del_filter(struct damon_filter *f) 135 { 136 list_del(&f->list); 137 } 138 139 static void damon_free_filter(struct damon_filter *f) 140 { 141 kfree(f); 142 } 143 144 void damon_destroy_filter(struct damon_filter *f) 145 { 146 damon_del_filter(f); 147 damon_free_filter(f); 148 } 149 150 static struct damon_filter *damon_nth_filter(int n, struct damon_probe *p) 151 { 152 struct damon_filter *f; 153 int i = 0; 154 155 damon_for_each_filter(f, p) { 156 if (i++ == n) 157 return f; 158 } 159 return NULL; 160 } 161 162 struct damon_probe *damon_new_probe(void) 163 { 164 struct damon_probe *p; 165 166 p = kmalloc_obj(*p); 167 if (!p) 168 return NULL; 169 INIT_LIST_HEAD(&p->filters); 170 INIT_LIST_HEAD(&p->list); 171 return p; 172 } 173 174 void damon_add_probe(struct damon_ctx *ctx, struct damon_probe *probe) 175 { 176 list_add_tail(&probe->list, &ctx->probes); 177 } 178 179 static void damon_del_probe(struct damon_probe *p) 180 { 181 list_del(&p->list); 182 } 183 184 static void damon_free_probe(struct damon_probe *p) 185 { 186 struct damon_filter *f, *next; 187 188 damon_for_each_filter_safe(f, next, p) 189 damon_free_filter(f); 190 kfree(p); 191 } 192 193 static void damon_destroy_probe(struct damon_probe *p) 194 { 195 damon_del_probe(p); 196 damon_free_probe(p); 197 } 198 199 static struct damon_probe *damon_nth_probe(int n, struct damon_ctx *ctx) 200 { 201 struct damon_probe *p; 202 int i = 0; 203 204 damon_for_each_probe(p, ctx) { 205 if (i++ == n) 206 return p; 207 } 208 return NULL; 209 } 210 211 #ifdef CONFIG_DAMON_DEBUG_SANITY 212 static void damon_verify_new_region(unsigned long start, unsigned long end) 213 { 214 WARN_ONCE(start >= end, "start %lu >= end %lu\n", start, end); 215 } 216 #else 217 static void damon_verify_new_region(unsigned long start, unsigned long end) 218 { 219 } 220 #endif 221 222 /* 223 * Construct a damon_region struct 224 * 225 * Returns the pointer to the new struct if success, or NULL otherwise 226 */ 227 struct damon_region *damon_new_region(unsigned long start, unsigned long end) 228 { 229 struct damon_region *region; 230 int i; 231 232 damon_verify_new_region(start, end); 233 region = kmem_cache_alloc(damon_region_cache, GFP_KERNEL); 234 if (!region) 235 return NULL; 236 237 region->ar.start = start; 238 region->ar.end = end; 239 region->nr_accesses = 0; 240 region->nr_accesses_bp = 0; 241 for (i = 0; i < DAMON_MAX_PROBES; i++) 242 region->probe_hits[i] = 0; 243 INIT_LIST_HEAD(®ion->list); 244 245 region->age = 0; 246 region->last_nr_accesses = 0; 247 248 return region; 249 } 250 251 static void damon_add_region(struct damon_region *r, struct damon_target *t) 252 { 253 list_add_tail(&r->list, &t->regions_list); 254 t->nr_regions++; 255 } 256 257 /* 258 * Add a region between two other regions 259 */ 260 static inline void damon_insert_region(struct damon_region *r, 261 struct damon_region *prev, struct damon_region *next, 262 struct damon_target *t) 263 { 264 __list_add(&r->list, &prev->list, &next->list); 265 t->nr_regions++; 266 } 267 268 #ifdef CONFIG_DAMON_DEBUG_SANITY 269 static void damon_verify_del_region(struct damon_target *t) 270 { 271 WARN_ONCE(t->nr_regions == 0, "t->nr_regions == 0\n"); 272 } 273 #else 274 static void damon_verify_del_region(struct damon_target *t) 275 { 276 } 277 #endif 278 279 static void damon_del_region(struct damon_region *r, struct damon_target *t) 280 { 281 damon_verify_del_region(t); 282 283 list_del(&r->list); 284 t->nr_regions--; 285 } 286 287 static void damon_free_region(struct damon_region *r) 288 { 289 kmem_cache_free(damon_region_cache, r); 290 } 291 292 static void damon_destroy_region(struct damon_region *r, 293 struct damon_target *t) 294 { 295 damon_del_region(r, t); 296 damon_free_region(r); 297 } 298 299 static bool damon_is_last_region(struct damon_region *r, 300 struct damon_target *t) 301 { 302 return list_is_last(&r->list, &t->regions_list); 303 } 304 305 /* 306 * Check whether a region is intersecting an address range 307 * 308 * Returns true if it is. 309 */ 310 static bool damon_intersect(struct damon_region *r, 311 struct damon_addr_range *re) 312 { 313 return !(r->ar.end <= re->start || re->end <= r->ar.start); 314 } 315 316 /* 317 * Fill holes in regions with new regions. 318 */ 319 static int damon_fill_regions_holes(struct damon_region *first, 320 struct damon_region *last, struct damon_target *t) 321 { 322 struct damon_region *r = first; 323 324 damon_for_each_region_from(r, t) { 325 struct damon_region *next, *newr; 326 327 if (r == last) 328 break; 329 next = damon_next_region(r); 330 if (r->ar.end != next->ar.start) { 331 newr = damon_new_region(r->ar.end, next->ar.start); 332 if (!newr) 333 return -ENOMEM; 334 damon_insert_region(newr, r, next, t); 335 } 336 } 337 return 0; 338 } 339 340 /* 341 * damon_set_regions() - Set regions of a target for given address ranges. 342 * @t: the given target. 343 * @ranges: array of new monitoring target ranges. 344 * @nr_ranges: length of @ranges. 345 * @min_region_sz: minimum region size. 346 * 347 * This function adds new regions to, or modify existing regions of a 348 * monitoring target to fit in specific ranges. 349 * 350 * Return: 0 if success, or negative error code otherwise. 351 */ 352 int damon_set_regions(struct damon_target *t, struct damon_addr_range *ranges, 353 unsigned int nr_ranges, unsigned long min_region_sz) 354 { 355 struct damon_region *r, *next; 356 unsigned int i; 357 unsigned long last_end; 358 int err; 359 360 for (i = 0; i < nr_ranges; i++) { 361 unsigned long start, end; 362 363 start = ALIGN_DOWN(ranges[i].start, min_region_sz); 364 end = ALIGN(ranges[i].end, min_region_sz); 365 if (start >= end) 366 return -EINVAL; 367 if (i > 0 && last_end > start) 368 return -EINVAL; 369 last_end = end; 370 } 371 372 /* Remove regions which are not in the new ranges */ 373 damon_for_each_region_safe(r, next, t) { 374 for (i = 0; i < nr_ranges; i++) { 375 if (damon_intersect(r, &ranges[i])) 376 break; 377 } 378 if (i == nr_ranges) 379 damon_destroy_region(r, t); 380 } 381 382 if (!damon_nr_regions(t)) { 383 for (i = 0; i < nr_ranges; i++) { 384 r = damon_new_region( 385 ALIGN_DOWN(ranges[i].start, 386 min_region_sz), 387 ALIGN(ranges[i].end, min_region_sz)); 388 if (!r) 389 return -ENOMEM; 390 damon_add_region(r, t); 391 } 392 return 0; 393 } 394 395 r = damon_first_region(t); 396 /* Add new regions or resize existing regions to fit in the ranges */ 397 for (i = 0; i < nr_ranges; i++) { 398 struct damon_region *first = NULL, *last, *newr; 399 struct damon_addr_range *range; 400 bool insert_before_r = false; 401 402 range = &ranges[i]; 403 /* Get the first/last regions intersecting with the range */ 404 damon_for_each_region_from(r, t) { 405 if (damon_intersect(r, range)) { 406 if (!first) 407 first = r; 408 last = r; 409 } 410 if (r->ar.start >= range->end) { 411 insert_before_r = true; 412 break; 413 } 414 } 415 if (!first) { 416 /* no region intersects with this range */ 417 newr = damon_new_region( 418 ALIGN_DOWN(range->start, 419 min_region_sz), 420 ALIGN(range->end, min_region_sz)); 421 if (!newr) 422 return -ENOMEM; 423 if (insert_before_r) 424 damon_insert_region(newr, damon_prev_region(r), 425 r, t); 426 else 427 damon_add_region(newr, t); 428 } else { 429 /* resize intersecting regions to fit in this range */ 430 first->ar.start = ALIGN_DOWN(range->start, 431 min_region_sz); 432 last->ar.end = ALIGN(range->end, min_region_sz); 433 434 /* fill possible holes in the range */ 435 err = damon_fill_regions_holes(first, last, t); 436 if (err) 437 return err; 438 } 439 } 440 return 0; 441 } 442 443 struct damos_filter *damos_new_filter(enum damos_filter_type type, 444 bool matching, bool allow) 445 { 446 struct damos_filter *filter; 447 448 filter = kmalloc_obj(*filter); 449 if (!filter) 450 return NULL; 451 filter->type = type; 452 filter->matching = matching; 453 filter->allow = allow; 454 INIT_LIST_HEAD(&filter->list); 455 return filter; 456 } 457 458 /** 459 * damos_filter_for_ops() - Return if the filter is ops-handled one. 460 * @type: type of the filter. 461 * 462 * Return: true if the filter of @type needs to be handled by ops layer, false 463 * otherwise. 464 */ 465 bool damos_filter_for_ops(enum damos_filter_type type) 466 { 467 switch (type) { 468 case DAMOS_FILTER_TYPE_ADDR: 469 case DAMOS_FILTER_TYPE_TARGET: 470 return false; 471 default: 472 break; 473 } 474 return true; 475 } 476 477 void damos_add_filter(struct damos *s, struct damos_filter *f) 478 { 479 if (damos_filter_for_ops(f->type)) 480 list_add_tail(&f->list, &s->ops_filters); 481 else 482 list_add_tail(&f->list, &s->core_filters); 483 } 484 485 static void damos_del_filter(struct damos_filter *f) 486 { 487 list_del(&f->list); 488 } 489 490 static void damos_free_filter(struct damos_filter *f) 491 { 492 kfree(f); 493 } 494 495 void damos_destroy_filter(struct damos_filter *f) 496 { 497 damos_del_filter(f); 498 damos_free_filter(f); 499 } 500 501 struct damos_quota_goal *damos_new_quota_goal( 502 enum damos_quota_goal_metric metric, 503 unsigned long target_value) 504 { 505 struct damos_quota_goal *goal; 506 507 goal = kmalloc_obj(*goal); 508 if (!goal) 509 return NULL; 510 goal->metric = metric; 511 goal->target_value = target_value; 512 INIT_LIST_HEAD(&goal->list); 513 return goal; 514 } 515 516 void damos_add_quota_goal(struct damos_quota *q, struct damos_quota_goal *g) 517 { 518 list_add_tail(&g->list, &q->goals); 519 } 520 521 static void damos_del_quota_goal(struct damos_quota_goal *g) 522 { 523 list_del(&g->list); 524 } 525 526 static void damos_free_quota_goal(struct damos_quota_goal *g) 527 { 528 kfree(g); 529 } 530 531 void damos_destroy_quota_goal(struct damos_quota_goal *g) 532 { 533 damos_del_quota_goal(g); 534 damos_free_quota_goal(g); 535 } 536 537 static bool damos_quota_goals_empty(struct damos_quota *q) 538 { 539 return list_empty(&q->goals); 540 } 541 542 /* initialize fields of @quota that normally API users wouldn't set */ 543 static struct damos_quota *damos_quota_init(struct damos_quota *quota) 544 { 545 quota->esz = 0; 546 quota->total_charged_sz = 0; 547 quota->total_charged_ns = 0; 548 quota->charged_sz = 0; 549 quota->charged_from = 0; 550 quota->charge_target_from = NULL; 551 quota->charge_addr_from = 0; 552 quota->esz_bp = 0; 553 return quota; 554 } 555 556 struct damos *damon_new_scheme(struct damos_access_pattern *pattern, 557 enum damos_action action, 558 unsigned long apply_interval_us, 559 struct damos_quota *quota, 560 struct damos_watermarks *wmarks, 561 int target_nid) 562 { 563 struct damos *scheme; 564 565 scheme = kmalloc_obj(*scheme); 566 if (!scheme) 567 return NULL; 568 scheme->pattern = *pattern; 569 scheme->action = action; 570 scheme->apply_interval_us = apply_interval_us; 571 /* 572 * next_apply_sis will be set when kdamond starts. While kdamond is 573 * running, it will also updated when it is added to the DAMON context, 574 * or damon_attrs are updated. 575 */ 576 scheme->next_apply_sis = 0; 577 scheme->walk_completed = false; 578 INIT_LIST_HEAD(&scheme->core_filters); 579 INIT_LIST_HEAD(&scheme->ops_filters); 580 scheme->stat = (struct damos_stat){}; 581 scheme->max_nr_snapshots = 0; 582 INIT_LIST_HEAD(&scheme->list); 583 584 scheme->quota = *(damos_quota_init(quota)); 585 /* quota.goals should be separately set by caller */ 586 INIT_LIST_HEAD(&scheme->quota.goals); 587 588 scheme->wmarks = *wmarks; 589 scheme->wmarks.activated = true; 590 591 scheme->migrate_dests = (struct damos_migrate_dests){}; 592 scheme->target_nid = target_nid; 593 594 return scheme; 595 } 596 597 static void damos_set_next_apply_sis(struct damos *s, struct damon_ctx *ctx) 598 { 599 unsigned long sample_interval = ctx->attrs.sample_interval ? 600 ctx->attrs.sample_interval : 1; 601 unsigned long apply_interval = s->apply_interval_us ? 602 s->apply_interval_us : ctx->attrs.aggr_interval; 603 604 s->next_apply_sis = ctx->passed_sample_intervals + 605 apply_interval / sample_interval; 606 } 607 608 void damon_add_scheme(struct damon_ctx *ctx, struct damos *s) 609 { 610 list_add_tail(&s->list, &ctx->schemes); 611 damos_set_next_apply_sis(s, ctx); 612 } 613 614 static void damon_del_scheme(struct damos *s) 615 { 616 list_del(&s->list); 617 } 618 619 static void damon_free_scheme(struct damos *s) 620 { 621 kfree(s); 622 } 623 624 void damon_destroy_scheme(struct damos *s) 625 { 626 struct damos_quota_goal *g, *g_next; 627 struct damos_filter *f, *next; 628 629 damos_for_each_quota_goal_safe(g, g_next, &s->quota) 630 damos_destroy_quota_goal(g); 631 632 damos_for_each_core_filter_safe(f, next, s) 633 damos_destroy_filter(f); 634 635 damos_for_each_ops_filter_safe(f, next, s) 636 damos_destroy_filter(f); 637 638 kfree(s->migrate_dests.node_id_arr); 639 kfree(s->migrate_dests.weight_arr); 640 damon_del_scheme(s); 641 damon_free_scheme(s); 642 } 643 644 /* 645 * Construct a damon_target struct 646 * 647 * Returns the pointer to the new struct if success, or NULL otherwise 648 */ 649 struct damon_target *damon_new_target(void) 650 { 651 struct damon_target *t; 652 653 t = kmalloc_obj(*t); 654 if (!t) 655 return NULL; 656 657 t->pid = NULL; 658 t->nr_regions = 0; 659 INIT_LIST_HEAD(&t->regions_list); 660 INIT_LIST_HEAD(&t->list); 661 t->obsolete = false; 662 663 return t; 664 } 665 666 void damon_add_target(struct damon_ctx *ctx, struct damon_target *t) 667 { 668 list_add_tail(&t->list, &ctx->adaptive_targets); 669 } 670 671 bool damon_targets_empty(struct damon_ctx *ctx) 672 { 673 return list_empty(&ctx->adaptive_targets); 674 } 675 676 static void damon_del_target(struct damon_target *t) 677 { 678 list_del(&t->list); 679 } 680 681 void damon_free_target(struct damon_target *t) 682 { 683 struct damon_region *r, *next; 684 685 damon_for_each_region_safe(r, next, t) 686 damon_free_region(r); 687 kfree(t); 688 } 689 690 void damon_destroy_target(struct damon_target *t, struct damon_ctx *ctx) 691 { 692 693 if (ctx && ctx->ops.cleanup_target) 694 ctx->ops.cleanup_target(t); 695 696 damon_del_target(t); 697 damon_free_target(t); 698 } 699 700 unsigned int damon_nr_regions(struct damon_target *t) 701 { 702 return t->nr_regions; 703 } 704 705 struct damon_ctx *damon_new_ctx(void) 706 { 707 struct damon_ctx *ctx; 708 709 ctx = kzalloc_obj(*ctx); 710 if (!ctx) 711 return NULL; 712 713 init_completion(&ctx->kdamond_started); 714 715 ctx->attrs.sample_interval = 5 * 1000; 716 ctx->attrs.aggr_interval = 100 * 1000; 717 ctx->attrs.ops_update_interval = 60 * 1000 * 1000; 718 719 ctx->passed_sample_intervals = 0; 720 /* These will be set from kdamond_init_ctx() */ 721 ctx->next_aggregation_sis = 0; 722 ctx->next_ops_update_sis = 0; 723 724 mutex_init(&ctx->kdamond_lock); 725 INIT_LIST_HEAD(&ctx->call_controls); 726 mutex_init(&ctx->call_controls_lock); 727 mutex_init(&ctx->walk_control_lock); 728 729 ctx->attrs.min_nr_regions = 10; 730 ctx->attrs.max_nr_regions = 1000; 731 732 INIT_LIST_HEAD(&ctx->probes); 733 734 ctx->addr_unit = 1; 735 ctx->min_region_sz = DAMON_MIN_REGION_SZ; 736 737 INIT_LIST_HEAD(&ctx->adaptive_targets); 738 INIT_LIST_HEAD(&ctx->schemes); 739 740 prandom_seed_state(&ctx->rnd_state, get_random_u64()); 741 742 return ctx; 743 } 744 745 static void damon_destroy_targets(struct damon_ctx *ctx) 746 { 747 struct damon_target *t, *next_t; 748 749 damon_for_each_target_safe(t, next_t, ctx) 750 damon_destroy_target(t, ctx); 751 } 752 753 void damon_destroy_ctx(struct damon_ctx *ctx) 754 { 755 struct damos *s, *next_s; 756 struct damon_probe *p, *next_p; 757 758 damon_destroy_targets(ctx); 759 760 damon_for_each_scheme_safe(s, next_s, ctx) 761 damon_destroy_scheme(s); 762 763 damon_for_each_probe_safe(p, next_p, ctx) 764 damon_destroy_probe(p); 765 766 kfree(ctx); 767 } 768 769 static bool damon_attrs_equals(const struct damon_attrs *attrs1, 770 const struct damon_attrs *attrs2) 771 { 772 const struct damon_intervals_goal *ig1 = &attrs1->intervals_goal; 773 const struct damon_intervals_goal *ig2 = &attrs2->intervals_goal; 774 775 return attrs1->sample_interval == attrs2->sample_interval && 776 attrs1->aggr_interval == attrs2->aggr_interval && 777 attrs1->ops_update_interval == attrs2->ops_update_interval && 778 attrs1->min_nr_regions == attrs2->min_nr_regions && 779 attrs1->max_nr_regions == attrs2->max_nr_regions && 780 ig1->access_bp == ig2->access_bp && 781 ig1->aggrs == ig2->aggrs && 782 ig1->min_sample_us == ig2->min_sample_us && 783 ig1->max_sample_us == ig2->max_sample_us; 784 } 785 786 static unsigned int damon_age_for_new_attrs(unsigned int age, 787 struct damon_attrs *old_attrs, struct damon_attrs *new_attrs) 788 { 789 return age * old_attrs->aggr_interval / new_attrs->aggr_interval; 790 } 791 792 /* convert access ratio in bp (per 10,000) to nr_accesses */ 793 static unsigned int damon_accesses_bp_to_nr_accesses( 794 unsigned int accesses_bp, struct damon_attrs *attrs) 795 { 796 return accesses_bp * damon_max_nr_accesses(attrs) / 10000; 797 } 798 799 /* 800 * Convert nr_accesses to access ratio in bp (per 10,000). 801 * 802 * Callers should ensure attrs.aggr_interval is not zero, like 803 * damon_update_monitoring_results() does . Otherwise, divide-by-zero would 804 * happen. 805 */ 806 static unsigned int damon_nr_accesses_to_accesses_bp( 807 unsigned int nr_accesses, struct damon_attrs *attrs) 808 { 809 return mult_frac(nr_accesses, 10000, damon_max_nr_accesses(attrs)); 810 } 811 812 static unsigned int damon_nr_accesses_for_new_attrs(unsigned int nr_accesses, 813 struct damon_attrs *old_attrs, struct damon_attrs *new_attrs) 814 { 815 return damon_accesses_bp_to_nr_accesses( 816 damon_nr_accesses_to_accesses_bp( 817 nr_accesses, old_attrs), 818 new_attrs); 819 } 820 821 static void damon_update_monitoring_result(struct damon_region *r, 822 struct damon_attrs *old_attrs, struct damon_attrs *new_attrs, 823 bool aggregating) 824 { 825 if (!aggregating) { 826 r->nr_accesses = damon_nr_accesses_for_new_attrs( 827 r->nr_accesses, old_attrs, new_attrs); 828 r->nr_accesses_bp = r->nr_accesses * 10000; 829 } else { 830 /* 831 * if this is called in the middle of the aggregation, reset 832 * the aggregations we made so far for this aggregation 833 * interval. In other words, make the status like 834 * kdamond_reset_aggregated() is called. 835 */ 836 r->last_nr_accesses = damon_nr_accesses_for_new_attrs( 837 r->last_nr_accesses, old_attrs, new_attrs); 838 r->nr_accesses_bp = r->last_nr_accesses * 10000; 839 r->nr_accesses = 0; 840 } 841 r->age = damon_age_for_new_attrs(r->age, old_attrs, new_attrs); 842 } 843 844 /* 845 * region->nr_accesses is the number of sampling intervals in the last 846 * aggregation interval that access to the region has found, and region->age is 847 * the number of aggregation intervals that its access pattern has maintained. 848 * For the reason, the real meaning of the two fields depend on current 849 * sampling interval and aggregation interval. This function updates 850 * ->nr_accesses and ->age of given damon_ctx's regions for new damon_attrs. 851 */ 852 static void damon_update_monitoring_results(struct damon_ctx *ctx, 853 struct damon_attrs *new_attrs, bool aggregating) 854 { 855 struct damon_attrs *old_attrs = &ctx->attrs; 856 struct damon_target *t; 857 struct damon_region *r; 858 859 /* if any interval is zero, simply forgive conversion */ 860 if (!old_attrs->sample_interval || !old_attrs->aggr_interval || 861 !new_attrs->sample_interval || 862 !new_attrs->aggr_interval) 863 return; 864 865 damon_for_each_target(t, ctx) 866 damon_for_each_region(r, t) 867 damon_update_monitoring_result( 868 r, old_attrs, new_attrs, aggregating); 869 } 870 871 /* 872 * damon_valid_intervals_goal() - return if the intervals goal of @attrs is 873 * valid. 874 */ 875 static bool damon_valid_intervals_goal(struct damon_attrs *attrs) 876 { 877 struct damon_intervals_goal *goal = &attrs->intervals_goal; 878 879 /* tuning is disabled */ 880 if (!goal->aggrs) 881 return true; 882 if (goal->min_sample_us > goal->max_sample_us) 883 return false; 884 if (attrs->sample_interval < goal->min_sample_us || 885 goal->max_sample_us < attrs->sample_interval) 886 return false; 887 return true; 888 } 889 890 /** 891 * damon_set_attrs() - Set attributes for the monitoring. 892 * @ctx: monitoring context 893 * @attrs: monitoring attributes 894 * 895 * This function updates monitoring results and next monitoring/damos operation 896 * schedules. Because those are periodically updated by kdamond, this should 897 * be called from a safe contexts. Such contexts include damon_ctx setup time 898 * while the kdamond is not yet started, and inside of kdamond_fn(). 899 * 900 * In detail, all DAMON API callers directly call this function for initial 901 * setup of damon_ctx before calling damon_start(). Some of the API callers 902 * also indirectly call this function via damon_call() -> damon_commit() for 903 * online parameters updates. Finally, kdamond_fn() itself use this for 904 * applying auto-tuned monitoring intervals. 905 * 906 * Every time interval is in micro-seconds. 907 * 908 * Return: 0 on success, negative error code otherwise. 909 */ 910 int damon_set_attrs(struct damon_ctx *ctx, struct damon_attrs *attrs) 911 { 912 unsigned long sample_interval = attrs->sample_interval ? 913 attrs->sample_interval : 1; 914 struct damos *s; 915 bool aggregating = ctx->passed_sample_intervals < 916 ctx->next_aggregation_sis; 917 918 if (!damon_valid_intervals_goal(attrs)) 919 return -EINVAL; 920 921 if (attrs->min_nr_regions < 3) 922 return -EINVAL; 923 if (attrs->min_nr_regions > attrs->max_nr_regions) 924 return -EINVAL; 925 if (attrs->sample_interval > attrs->aggr_interval) 926 return -EINVAL; 927 928 /* calls from core-external doesn't set this. */ 929 if (!attrs->aggr_samples) 930 attrs->aggr_samples = attrs->aggr_interval / sample_interval; 931 932 ctx->next_aggregation_sis = ctx->passed_sample_intervals + 933 attrs->aggr_interval / sample_interval; 934 ctx->next_ops_update_sis = ctx->passed_sample_intervals + 935 attrs->ops_update_interval / sample_interval; 936 /* 937 * next_intervals_tune_sis will be updated inside kdamond_fn(). 938 */ 939 940 damon_update_monitoring_results(ctx, attrs, aggregating); 941 ctx->attrs = *attrs; 942 943 damon_for_each_scheme(s, ctx) 944 damos_set_next_apply_sis(s, ctx); 945 946 return 0; 947 } 948 949 /** 950 * damon_set_schemes() - Set data access monitoring based operation schemes. 951 * @ctx: monitoring context 952 * @schemes: array of the schemes 953 * @nr_schemes: number of entries in @schemes 954 * 955 * This function should not be called while the kdamond of the context is 956 * running. 957 */ 958 void damon_set_schemes(struct damon_ctx *ctx, struct damos **schemes, 959 ssize_t nr_schemes) 960 { 961 struct damos *s, *next; 962 ssize_t i; 963 964 damon_for_each_scheme_safe(s, next, ctx) 965 damon_destroy_scheme(s); 966 for (i = 0; i < nr_schemes; i++) 967 damon_add_scheme(ctx, schemes[i]); 968 } 969 970 static struct damos_quota_goal *damos_nth_quota_goal( 971 int n, struct damos_quota *q) 972 { 973 struct damos_quota_goal *goal; 974 int i = 0; 975 976 damos_for_each_quota_goal(goal, q) { 977 if (i++ == n) 978 return goal; 979 } 980 return NULL; 981 } 982 983 static void damos_commit_quota_goal_union( 984 struct damos_quota_goal *dst, struct damos_quota_goal *src) 985 { 986 switch (dst->metric) { 987 case DAMOS_QUOTA_NODE_MEM_USED_BP: 988 case DAMOS_QUOTA_NODE_MEM_FREE_BP: 989 dst->nid = src->nid; 990 break; 991 case DAMOS_QUOTA_NODE_MEMCG_USED_BP: 992 case DAMOS_QUOTA_NODE_MEMCG_FREE_BP: 993 dst->nid = src->nid; 994 dst->memcg_id = src->memcg_id; 995 break; 996 default: 997 break; 998 } 999 } 1000 1001 static void damos_commit_quota_goal( 1002 struct damos_quota_goal *dst, struct damos_quota_goal *src) 1003 { 1004 dst->metric = src->metric; 1005 dst->target_value = src->target_value; 1006 if (dst->metric == DAMOS_QUOTA_USER_INPUT) 1007 dst->current_value = src->current_value; 1008 /* keep last_psi_total as is, since it will be updated in next cycle */ 1009 damos_commit_quota_goal_union(dst, src); 1010 } 1011 1012 /** 1013 * damos_commit_quota_goals() - Commit DAMOS quota goals to another quota. 1014 * @dst: The commit destination DAMOS quota. 1015 * @src: The commit source DAMOS quota. 1016 * 1017 * Copies user-specified parameters for quota goals from @src to @dst. Users 1018 * should use this function for quota goals-level parameters update of running 1019 * DAMON contexts, instead of manual in-place updates. 1020 * 1021 * This function should be called from parameters-update safe context, like 1022 * damon_call(). 1023 */ 1024 int damos_commit_quota_goals(struct damos_quota *dst, struct damos_quota *src) 1025 { 1026 struct damos_quota_goal *dst_goal, *next, *src_goal, *new_goal; 1027 int i = 0, j = 0; 1028 1029 damos_for_each_quota_goal_safe(dst_goal, next, dst) { 1030 src_goal = damos_nth_quota_goal(i++, src); 1031 if (src_goal) 1032 damos_commit_quota_goal(dst_goal, src_goal); 1033 else 1034 damos_destroy_quota_goal(dst_goal); 1035 } 1036 damos_for_each_quota_goal_safe(src_goal, next, src) { 1037 if (j++ < i) 1038 continue; 1039 new_goal = damos_new_quota_goal( 1040 src_goal->metric, src_goal->target_value); 1041 if (!new_goal) 1042 return -ENOMEM; 1043 damos_commit_quota_goal(new_goal, src_goal); 1044 damos_add_quota_goal(dst, new_goal); 1045 } 1046 return 0; 1047 } 1048 1049 static int damos_commit_quota(struct damos_quota *dst, struct damos_quota *src) 1050 { 1051 int err; 1052 1053 dst->reset_interval = src->reset_interval; 1054 dst->ms = src->ms; 1055 dst->sz = src->sz; 1056 err = damos_commit_quota_goals(dst, src); 1057 if (err) 1058 return err; 1059 dst->goal_tuner = src->goal_tuner; 1060 dst->fail_charge_num = src->fail_charge_num; 1061 dst->fail_charge_denom = src->fail_charge_denom; 1062 dst->weight_sz = src->weight_sz; 1063 dst->weight_nr_accesses = src->weight_nr_accesses; 1064 dst->weight_age = src->weight_age; 1065 return 0; 1066 } 1067 1068 static struct damos_filter *damos_nth_core_filter(int n, struct damos *s) 1069 { 1070 struct damos_filter *filter; 1071 int i = 0; 1072 1073 damos_for_each_core_filter(filter, s) { 1074 if (i++ == n) 1075 return filter; 1076 } 1077 return NULL; 1078 } 1079 1080 static struct damos_filter *damos_nth_ops_filter(int n, struct damos *s) 1081 { 1082 struct damos_filter *filter; 1083 int i = 0; 1084 1085 damos_for_each_ops_filter(filter, s) { 1086 if (i++ == n) 1087 return filter; 1088 } 1089 return NULL; 1090 } 1091 1092 static void damos_commit_filter_arg( 1093 struct damos_filter *dst, struct damos_filter *src) 1094 { 1095 switch (dst->type) { 1096 case DAMOS_FILTER_TYPE_MEMCG: 1097 dst->memcg_id = src->memcg_id; 1098 break; 1099 case DAMOS_FILTER_TYPE_ADDR: 1100 dst->addr_range = src->addr_range; 1101 break; 1102 case DAMOS_FILTER_TYPE_TARGET: 1103 dst->target_idx = src->target_idx; 1104 break; 1105 case DAMOS_FILTER_TYPE_HUGEPAGE_SIZE: 1106 dst->sz_range = src->sz_range; 1107 break; 1108 default: 1109 break; 1110 } 1111 } 1112 1113 static void damos_commit_filter( 1114 struct damos_filter *dst, struct damos_filter *src) 1115 { 1116 dst->type = src->type; 1117 dst->matching = src->matching; 1118 dst->allow = src->allow; 1119 damos_commit_filter_arg(dst, src); 1120 } 1121 1122 static int damos_commit_core_filters(struct damos *dst, struct damos *src) 1123 { 1124 struct damos_filter *dst_filter, *next, *src_filter, *new_filter; 1125 int i = 0, j = 0; 1126 1127 damos_for_each_core_filter_safe(dst_filter, next, dst) { 1128 src_filter = damos_nth_core_filter(i++, src); 1129 if (src_filter) 1130 damos_commit_filter(dst_filter, src_filter); 1131 else 1132 damos_destroy_filter(dst_filter); 1133 } 1134 1135 damos_for_each_core_filter_safe(src_filter, next, src) { 1136 if (j++ < i) 1137 continue; 1138 1139 new_filter = damos_new_filter( 1140 src_filter->type, src_filter->matching, 1141 src_filter->allow); 1142 if (!new_filter) 1143 return -ENOMEM; 1144 damos_commit_filter_arg(new_filter, src_filter); 1145 damos_add_filter(dst, new_filter); 1146 } 1147 return 0; 1148 } 1149 1150 static int damos_commit_ops_filters(struct damos *dst, struct damos *src) 1151 { 1152 struct damos_filter *dst_filter, *next, *src_filter, *new_filter; 1153 int i = 0, j = 0; 1154 1155 damos_for_each_ops_filter_safe(dst_filter, next, dst) { 1156 src_filter = damos_nth_ops_filter(i++, src); 1157 if (src_filter) 1158 damos_commit_filter(dst_filter, src_filter); 1159 else 1160 damos_destroy_filter(dst_filter); 1161 } 1162 1163 damos_for_each_ops_filter_safe(src_filter, next, src) { 1164 if (j++ < i) 1165 continue; 1166 1167 new_filter = damos_new_filter( 1168 src_filter->type, src_filter->matching, 1169 src_filter->allow); 1170 if (!new_filter) 1171 return -ENOMEM; 1172 damos_commit_filter_arg(new_filter, src_filter); 1173 damos_add_filter(dst, new_filter); 1174 } 1175 return 0; 1176 } 1177 1178 /** 1179 * damos_filters_default_reject() - decide whether to reject memory that didn't 1180 * match with any given filter. 1181 * @filters: Given DAMOS filters of a group. 1182 */ 1183 static bool damos_filters_default_reject(struct list_head *filters) 1184 { 1185 struct damos_filter *last_filter; 1186 1187 if (list_empty(filters)) 1188 return false; 1189 last_filter = list_last_entry(filters, struct damos_filter, list); 1190 return last_filter->allow; 1191 } 1192 1193 static void damos_set_filters_default_reject(struct damos *s) 1194 { 1195 if (!list_empty(&s->ops_filters)) 1196 s->core_filters_default_reject = false; 1197 else 1198 s->core_filters_default_reject = 1199 damos_filters_default_reject(&s->core_filters); 1200 s->ops_filters_default_reject = 1201 damos_filters_default_reject(&s->ops_filters); 1202 } 1203 1204 /* 1205 * damos_commit_dests() - Copy migration destinations from @src to @dst. 1206 * @dst: Destination structure to update. 1207 * @src: Source structure to copy from. 1208 * 1209 * If the number of destinations has changed, the old arrays in @dst are freed 1210 * and new ones are allocated. On success, @dst contains a full copy of 1211 * @src's arrays and count. 1212 * 1213 * On allocation failure, @dst is left in a partially torn-down state: its 1214 * arrays may be NULL and @nr_dests may not reflect the actual allocation 1215 * sizes. The structure remains safe to deallocate via damon_destroy_scheme(), 1216 * but callers must not reuse @dst for further commits — it should be 1217 * discarded. 1218 * 1219 * Return: 0 on success, -ENOMEM on allocation failure. 1220 */ 1221 static int damos_commit_dests(struct damos_migrate_dests *dst, 1222 struct damos_migrate_dests *src) 1223 { 1224 if (dst->nr_dests != src->nr_dests) { 1225 kfree(dst->node_id_arr); 1226 kfree(dst->weight_arr); 1227 1228 dst->node_id_arr = kmalloc_array(src->nr_dests, 1229 sizeof(*dst->node_id_arr), GFP_KERNEL); 1230 if (!dst->node_id_arr) { 1231 dst->weight_arr = NULL; 1232 return -ENOMEM; 1233 } 1234 1235 dst->weight_arr = kmalloc_array(src->nr_dests, 1236 sizeof(*dst->weight_arr), GFP_KERNEL); 1237 if (!dst->weight_arr) { 1238 /* ->node_id_arr will be freed by scheme destruction */ 1239 return -ENOMEM; 1240 } 1241 } 1242 1243 dst->nr_dests = src->nr_dests; 1244 for (int i = 0; i < src->nr_dests; i++) { 1245 dst->node_id_arr[i] = src->node_id_arr[i]; 1246 dst->weight_arr[i] = src->weight_arr[i]; 1247 } 1248 1249 return 0; 1250 } 1251 1252 static int damos_commit_filters(struct damos *dst, struct damos *src) 1253 { 1254 int err; 1255 1256 err = damos_commit_core_filters(dst, src); 1257 if (err) 1258 return err; 1259 err = damos_commit_ops_filters(dst, src); 1260 if (err) 1261 return err; 1262 damos_set_filters_default_reject(dst); 1263 return 0; 1264 } 1265 1266 static struct damos *damon_nth_scheme(int n, struct damon_ctx *ctx) 1267 { 1268 struct damos *s; 1269 int i = 0; 1270 1271 damon_for_each_scheme(s, ctx) { 1272 if (i++ == n) 1273 return s; 1274 } 1275 return NULL; 1276 } 1277 1278 static int damos_commit(struct damos *dst, struct damos *src) 1279 { 1280 int err; 1281 1282 dst->pattern = src->pattern; 1283 dst->action = src->action; 1284 dst->apply_interval_us = src->apply_interval_us; 1285 1286 err = damos_commit_quota(&dst->quota, &src->quota); 1287 if (err) 1288 return err; 1289 1290 dst->wmarks = src->wmarks; 1291 dst->target_nid = src->target_nid; 1292 1293 err = damos_commit_dests(&dst->migrate_dests, &src->migrate_dests); 1294 if (err) 1295 return err; 1296 1297 err = damos_commit_filters(dst, src); 1298 if (err) 1299 return err; 1300 1301 dst->max_nr_snapshots = src->max_nr_snapshots; 1302 return 0; 1303 } 1304 1305 static int damon_commit_schemes(struct damon_ctx *dst, struct damon_ctx *src) 1306 { 1307 struct damos *dst_scheme, *next, *src_scheme, *new_scheme; 1308 int i = 0, j = 0, err; 1309 1310 damon_for_each_scheme_safe(dst_scheme, next, dst) { 1311 src_scheme = damon_nth_scheme(i++, src); 1312 if (src_scheme) { 1313 err = damos_commit(dst_scheme, src_scheme); 1314 if (err) 1315 return err; 1316 } else { 1317 damon_destroy_scheme(dst_scheme); 1318 } 1319 } 1320 1321 damon_for_each_scheme_safe(src_scheme, next, src) { 1322 if (j++ < i) 1323 continue; 1324 new_scheme = damon_new_scheme(&src_scheme->pattern, 1325 src_scheme->action, 1326 src_scheme->apply_interval_us, 1327 &src_scheme->quota, &src_scheme->wmarks, 1328 NUMA_NO_NODE); 1329 if (!new_scheme) 1330 return -ENOMEM; 1331 err = damos_commit(new_scheme, src_scheme); 1332 if (err) { 1333 damon_destroy_scheme(new_scheme); 1334 return err; 1335 } 1336 damon_add_scheme(dst, new_scheme); 1337 } 1338 return 0; 1339 } 1340 1341 static struct damon_target *damon_nth_target(int n, struct damon_ctx *ctx) 1342 { 1343 struct damon_target *t; 1344 int i = 0; 1345 1346 damon_for_each_target(t, ctx) { 1347 if (i++ == n) 1348 return t; 1349 } 1350 return NULL; 1351 } 1352 1353 /* 1354 * The caller should ensure the regions of @src are 1355 * 1. valid (end >= src) and 1356 * 2. sorted by starting address. 1357 * 1358 * If @src has no region, @dst keeps current regions. 1359 */ 1360 static int damon_commit_target_regions(struct damon_target *dst, 1361 struct damon_target *src, unsigned long src_min_region_sz) 1362 { 1363 struct damon_region *src_region; 1364 struct damon_addr_range *ranges; 1365 int i = 0, err; 1366 1367 damon_for_each_region(src_region, src) 1368 i++; 1369 if (!i) 1370 return 0; 1371 1372 ranges = kmalloc_objs(*ranges, i, GFP_KERNEL | __GFP_NOWARN); 1373 if (!ranges) 1374 return -ENOMEM; 1375 i = 0; 1376 damon_for_each_region(src_region, src) 1377 ranges[i++] = src_region->ar; 1378 err = damon_set_regions(dst, ranges, i, src_min_region_sz); 1379 kfree(ranges); 1380 return err; 1381 } 1382 1383 static int damon_commit_target( 1384 struct damon_target *dst, bool dst_has_pid, 1385 struct damon_target *src, bool src_has_pid, 1386 unsigned long src_min_region_sz) 1387 { 1388 int err; 1389 1390 err = damon_commit_target_regions(dst, src, src_min_region_sz); 1391 if (err) 1392 return err; 1393 if (dst_has_pid) 1394 put_pid(dst->pid); 1395 if (src_has_pid) 1396 get_pid(src->pid); 1397 dst->pid = src->pid; 1398 return 0; 1399 } 1400 1401 /* 1402 * damon_revert_target_commits() - revert unsuccessful target commits. 1403 * @dst: Commit destination context 1404 * @failed: Commit failed destination target 1405 * @src: Commit source context 1406 * 1407 * Revert target states that changed by damon_commit_target(), and cannot be 1408 * cleaned up by the destination context's ops.cleanup_target(). 1409 */ 1410 static void damon_revert_target_commits(struct damon_ctx *dst, 1411 struct damon_target *failed, struct damon_ctx *src) 1412 { 1413 struct damon_target *target; 1414 1415 if (!damon_target_has_pid(src)) 1416 return; 1417 if (dst->ops.cleanup_target) 1418 return; 1419 damon_for_each_target(target, dst) { 1420 if (target == failed) 1421 return; 1422 put_pid(target->pid); 1423 } 1424 } 1425 1426 static int damon_commit_targets( 1427 struct damon_ctx *dst, struct damon_ctx *src) 1428 { 1429 struct damon_target *dst_target, *next, *src_target, *new_target; 1430 struct damon_target *failed; 1431 int i = 0, j = 0, err; 1432 1433 damon_for_each_target_safe(dst_target, next, dst) { 1434 src_target = damon_nth_target(i++, src); 1435 /* 1436 * If src target is obsolete, do not commit the parameters to 1437 * the dst target, and further remove the dst target. 1438 */ 1439 if (src_target && !src_target->obsolete) { 1440 err = damon_commit_target( 1441 dst_target, damon_target_has_pid(dst), 1442 src_target, damon_target_has_pid(src), 1443 src->min_region_sz); 1444 if (err) { 1445 failed = dst_target; 1446 goto out; 1447 } 1448 } else { 1449 struct damos *s; 1450 1451 damon_destroy_target(dst_target, dst); 1452 damon_for_each_scheme(s, dst) { 1453 if (s->quota.charge_target_from == dst_target) { 1454 s->quota.charge_target_from = NULL; 1455 s->quota.charge_addr_from = 0; 1456 } 1457 } 1458 } 1459 } 1460 1461 failed = NULL; 1462 damon_for_each_target_safe(src_target, next, src) { 1463 if (j++ < i) 1464 continue; 1465 /* target to remove has no matching dst */ 1466 if (src_target->obsolete) { 1467 err = -EINVAL; 1468 goto out; 1469 } 1470 new_target = damon_new_target(); 1471 if (!new_target) { 1472 err = -ENOMEM; 1473 goto out; 1474 } 1475 err = damon_commit_target(new_target, false, 1476 src_target, damon_target_has_pid(src), 1477 src->min_region_sz); 1478 if (err) { 1479 damon_destroy_target(new_target, NULL); 1480 goto out; 1481 } 1482 damon_add_target(dst, new_target); 1483 } 1484 return 0; 1485 1486 out: 1487 damon_revert_target_commits(dst, failed, src); 1488 return err; 1489 } 1490 1491 static void damon_commit_filter(struct damon_filter *dst, 1492 struct damon_filter *src) 1493 { 1494 dst->type = src->type; 1495 dst->matching = src->matching; 1496 dst->allow = src->allow; 1497 switch (dst->type) { 1498 case DAMON_FILTER_TYPE_MEMCG: 1499 dst->memcg_id = src->memcg_id; 1500 break; 1501 default: 1502 break; 1503 } 1504 } 1505 1506 static int damon_commit_filters(struct damon_probe *dst, 1507 struct damon_probe *src) 1508 { 1509 struct damon_filter *dst_filter, *next, *src_filter, *new_filter; 1510 int i = 0, j = 0; 1511 1512 damon_for_each_filter_safe(dst_filter, next, dst) { 1513 src_filter = damon_nth_filter(i++, src); 1514 if (src_filter) 1515 damon_commit_filter(dst_filter, src_filter); 1516 else 1517 damon_destroy_filter(dst_filter); 1518 } 1519 1520 damon_for_each_filter_safe(src_filter, next, src) { 1521 if (j++ < i) 1522 continue; 1523 1524 new_filter = damon_new_filter(src_filter->type, 1525 src_filter->matching, src_filter->allow); 1526 if (!new_filter) 1527 return -ENOMEM; 1528 switch (src_filter->type) { 1529 case DAMON_FILTER_TYPE_MEMCG: 1530 new_filter->memcg_id = src_filter->memcg_id; 1531 break; 1532 default: 1533 break; 1534 } 1535 damon_add_filter(dst, new_filter); 1536 } 1537 return 0; 1538 } 1539 1540 static int damon_commit_probes(struct damon_ctx *dst, struct damon_ctx *src) 1541 { 1542 struct damon_probe *dst_probe, *next, *src_probe, *new_probe; 1543 int i = 0, j = 0, err; 1544 1545 damon_for_each_probe_safe(dst_probe, next, dst) { 1546 src_probe = damon_nth_probe(i++, src); 1547 if (src_probe) { 1548 err = damon_commit_filters(dst_probe, src_probe); 1549 if (err) 1550 return err; 1551 } else { 1552 damon_destroy_probe(dst_probe); 1553 } 1554 } 1555 1556 damon_for_each_probe_safe(src_probe, next, src) { 1557 if (j++ < i) 1558 continue; 1559 1560 new_probe = damon_new_probe(); 1561 if (!new_probe) 1562 return -ENOMEM; 1563 damon_add_probe(dst, new_probe); 1564 err = damon_commit_filters(new_probe, src_probe); 1565 if (err) 1566 return err; 1567 } 1568 return 0; 1569 } 1570 1571 /** 1572 * damon_commit_ctx() - Commit parameters of a DAMON context to another. 1573 * @dst: The commit destination DAMON context. 1574 * @src: The commit source DAMON context. 1575 * 1576 * This function copies user-specified parameters from @src to @dst and update 1577 * the internal status and results accordingly. Users should use this function 1578 * for context-level parameters update of running context, instead of manual 1579 * in-place updates. 1580 * 1581 * This function should be called from parameters-update safe context, like 1582 * damon_call(). 1583 */ 1584 int damon_commit_ctx(struct damon_ctx *dst, struct damon_ctx *src) 1585 { 1586 int err; 1587 struct damos *scheme; 1588 struct damos_quota_goal *goal; 1589 1590 dst->maybe_corrupted = true; 1591 if (!is_power_of_2(src->min_region_sz)) 1592 return -EINVAL; 1593 1594 /* node_eligible_mem_bp metric requires PADDR ops */ 1595 if (src->ops.id != DAMON_OPS_PADDR) { 1596 damon_for_each_scheme(scheme, src) { 1597 struct damos_quota *quota = &scheme->quota; 1598 1599 damos_for_each_quota_goal(goal, quota) { 1600 if (goal->metric == 1601 DAMOS_QUOTA_NODE_ELIGIBLE_MEM_BP) 1602 return -EINVAL; 1603 } 1604 } 1605 } 1606 1607 err = damon_commit_schemes(dst, src); 1608 if (err) 1609 return err; 1610 err = damon_commit_targets(dst, src); 1611 if (err) 1612 return err; 1613 /* 1614 * schemes and targets should be updated first, since 1615 * 1. damon_set_attrs() updates monitoring results of targets and 1616 * next_apply_sis of schemes, and 1617 * 2. ops update should be done after pid handling is done (target 1618 * committing require putting pids). 1619 */ 1620 if (!damon_attrs_equals(&dst->attrs, &src->attrs)) { 1621 err = damon_set_attrs(dst, &src->attrs); 1622 if (err) { 1623 damon_revert_target_commits(dst, NULL, src); 1624 return err; 1625 } 1626 } 1627 dst->pause = src->pause; 1628 dst->ops = src->ops; 1629 err = damon_commit_probes(dst, src); 1630 if (err) 1631 return err; 1632 dst->addr_unit = src->addr_unit; 1633 dst->min_region_sz = src->min_region_sz; 1634 1635 dst->maybe_corrupted = false; 1636 return 0; 1637 } 1638 1639 /** 1640 * damon_nr_running_ctxs() - Return number of currently running contexts. 1641 */ 1642 int damon_nr_running_ctxs(void) 1643 { 1644 int nr_ctxs; 1645 1646 mutex_lock(&damon_lock); 1647 nr_ctxs = nr_running_ctxs; 1648 mutex_unlock(&damon_lock); 1649 1650 return nr_ctxs; 1651 } 1652 1653 /* Returns the size upper limit for each monitoring region */ 1654 static unsigned long damon_region_sz_limit(struct damon_ctx *ctx) 1655 { 1656 struct damon_target *t; 1657 struct damon_region *r; 1658 unsigned long sz = 0; 1659 1660 damon_for_each_target(t, ctx) { 1661 damon_for_each_region(r, t) 1662 sz += damon_sz_region(r); 1663 } 1664 1665 if (ctx->attrs.min_nr_regions) 1666 sz /= ctx->attrs.min_nr_regions; 1667 if (sz < ctx->min_region_sz) 1668 sz = ctx->min_region_sz; 1669 1670 return sz; 1671 } 1672 1673 static void damon_split_region_at(struct damon_target *t, 1674 struct damon_region *r, unsigned long sz_r); 1675 1676 /* 1677 * damon_apply_min_nr_regions() - Make effect of min_nr_regions parameter. 1678 * @ctx: monitoring context. 1679 * 1680 * This function implement min_nr_regions (minimum number of damon_region 1681 * objects in the given monitoring context) behavior. It first calculates 1682 * maximum size of each region for enforcing the min_nr_regions as total size 1683 * of the regions divided by the min_nr_regions. After that, this function 1684 * splits regions to ensure all regions are equal to or smaller than the size 1685 * limit. Finally, this function returns the maximum size limit. 1686 * 1687 * Returns: maximum size of each region for convincing min_nr_regions. 1688 */ 1689 static unsigned long damon_apply_min_nr_regions(struct damon_ctx *ctx) 1690 { 1691 unsigned long max_region_sz = damon_region_sz_limit(ctx); 1692 struct damon_target *t; 1693 struct damon_region *r, *next; 1694 1695 max_region_sz = ALIGN(max_region_sz, ctx->min_region_sz); 1696 damon_for_each_target(t, ctx) { 1697 damon_for_each_region_safe(r, next, t) { 1698 while (damon_sz_region(r) > max_region_sz) { 1699 damon_split_region_at(t, r, max_region_sz); 1700 r = damon_next_region(r); 1701 } 1702 } 1703 } 1704 return max_region_sz; 1705 } 1706 1707 static int kdamond_fn(void *data); 1708 1709 /* 1710 * __damon_start() - Starts monitoring with given context. 1711 * @ctx: monitoring context 1712 * 1713 * This function should be called while damon_lock is hold. 1714 * 1715 * Return: 0 on success, negative error code otherwise. 1716 */ 1717 static int __damon_start(struct damon_ctx *ctx) 1718 { 1719 int err = -EBUSY; 1720 1721 mutex_lock(&ctx->kdamond_lock); 1722 if (!ctx->kdamond) { 1723 err = 0; 1724 reinit_completion(&ctx->kdamond_started); 1725 ctx->kdamond = kthread_run(kdamond_fn, ctx, "kdamond.%d", 1726 nr_running_ctxs); 1727 if (IS_ERR(ctx->kdamond)) { 1728 err = PTR_ERR(ctx->kdamond); 1729 ctx->kdamond = NULL; 1730 } else { 1731 wait_for_completion(&ctx->kdamond_started); 1732 } 1733 } 1734 mutex_unlock(&ctx->kdamond_lock); 1735 1736 return err; 1737 } 1738 1739 /** 1740 * damon_start() - Starts the monitorings for a given group of contexts. 1741 * @ctxs: an array of the pointers for contexts to start monitoring 1742 * @nr_ctxs: size of @ctxs 1743 * @exclusive: exclusiveness of this contexts group 1744 * 1745 * This function starts a group of monitoring threads for a group of monitoring 1746 * contexts. One thread per each context is created and run in parallel. The 1747 * caller should handle synchronization between the threads by itself. If 1748 * @exclusive is true and a group of threads that created by other 1749 * 'damon_start()' call is currently running, this function does nothing but 1750 * returns -EBUSY. 1751 * 1752 * Return: 0 on success, negative error code otherwise. 1753 */ 1754 int damon_start(struct damon_ctx **ctxs, int nr_ctxs, bool exclusive) 1755 { 1756 int i; 1757 int err = 0; 1758 1759 for (i = 0; i < nr_ctxs; i++) { 1760 if (!is_power_of_2(ctxs[i]->min_region_sz)) 1761 return -EINVAL; 1762 } 1763 1764 mutex_lock(&damon_lock); 1765 if ((exclusive && nr_running_ctxs) || 1766 (!exclusive && running_exclusive_ctxs)) { 1767 mutex_unlock(&damon_lock); 1768 return -EBUSY; 1769 } 1770 1771 for (i = 0; i < nr_ctxs; i++) { 1772 err = __damon_start(ctxs[i]); 1773 if (err) 1774 break; 1775 nr_running_ctxs++; 1776 } 1777 if (exclusive && nr_running_ctxs) 1778 running_exclusive_ctxs = true; 1779 mutex_unlock(&damon_lock); 1780 1781 return err; 1782 } 1783 1784 /* 1785 * __damon_stop() - Stops monitoring of a given context. 1786 * @ctx: monitoring context 1787 * 1788 * Return: 0 on success, negative error code otherwise. 1789 */ 1790 static int __damon_stop(struct damon_ctx *ctx) 1791 { 1792 struct task_struct *tsk; 1793 1794 mutex_lock(&ctx->kdamond_lock); 1795 tsk = ctx->kdamond; 1796 if (tsk) { 1797 get_task_struct(tsk); 1798 mutex_unlock(&ctx->kdamond_lock); 1799 kthread_stop_put(tsk); 1800 return 0; 1801 } 1802 mutex_unlock(&ctx->kdamond_lock); 1803 1804 return -EPERM; 1805 } 1806 1807 /** 1808 * damon_stop() - Stops the monitorings for a given group of contexts. 1809 * @ctxs: an array of the pointers for contexts to stop monitoring 1810 * @nr_ctxs: size of @ctxs 1811 * 1812 * Return: 0 on success, negative error code otherwise. 1813 */ 1814 int damon_stop(struct damon_ctx **ctxs, int nr_ctxs) 1815 { 1816 int i, err = 0; 1817 1818 for (i = 0; i < nr_ctxs; i++) { 1819 /* nr_running_ctxs is decremented in kdamond_fn */ 1820 err = __damon_stop(ctxs[i]); 1821 if (err) 1822 break; 1823 } 1824 return err; 1825 } 1826 1827 /** 1828 * damon_is_running() - Returns if a given DAMON context is running. 1829 * @ctx: The DAMON context to see if running. 1830 * 1831 * Return: true if @ctx is running, false otherwise. 1832 */ 1833 bool damon_is_running(struct damon_ctx *ctx) 1834 { 1835 bool running; 1836 1837 mutex_lock(&ctx->kdamond_lock); 1838 running = ctx->kdamond != NULL; 1839 mutex_unlock(&ctx->kdamond_lock); 1840 return running; 1841 } 1842 1843 /** 1844 * damon_kdamond_pid() - Return pid of a given DAMON context's worker thread. 1845 * @ctx: The DAMON context of the question. 1846 * 1847 * Return: pid if @ctx is running, negative error code otherwise. 1848 */ 1849 int damon_kdamond_pid(struct damon_ctx *ctx) 1850 { 1851 int pid = -EINVAL; 1852 1853 mutex_lock(&ctx->kdamond_lock); 1854 if (ctx->kdamond) 1855 pid = ctx->kdamond->pid; 1856 mutex_unlock(&ctx->kdamond_lock); 1857 return pid; 1858 } 1859 1860 /** 1861 * damon_call() - Invoke a given function on DAMON worker thread (kdamond). 1862 * @ctx: DAMON context to call the function for. 1863 * @control: Control variable of the call request. 1864 * 1865 * Ask DAMON worker thread (kdamond) of @ctx to call a function with an 1866 * argument data that respectively passed via &damon_call_control->fn and 1867 * &damon_call_control->data of @control. If &damon_call_control->repeat of 1868 * @control is unset, further wait until the kdamond finishes handling of the 1869 * request. Otherwise, return as soon as the request is made. 1870 * 1871 * The kdamond executes the function with the argument in the main loop, just 1872 * after a sampling of the iteration is finished. The function can hence 1873 * safely access the internal data of the &struct damon_ctx without additional 1874 * synchronization. The return value of the function will be saved in 1875 * &damon_call_control->return_code. 1876 * 1877 * Note that this function should be called only after damon_start() with the 1878 * @ctx has succeeded. Otherwise, this function could fall into an indefinite 1879 * wait. 1880 * 1881 * Return: 0 on success, negative error code otherwise. 1882 */ 1883 int damon_call(struct damon_ctx *ctx, struct damon_call_control *control) 1884 { 1885 if (!control->repeat) 1886 init_completion(&control->completion); 1887 control->canceled = false; 1888 INIT_LIST_HEAD(&control->list); 1889 1890 mutex_lock(&ctx->call_controls_lock); 1891 if (ctx->call_controls_obsolete) { 1892 mutex_unlock(&ctx->call_controls_lock); 1893 return -ECANCELED; 1894 } 1895 list_add_tail(&control->list, &ctx->call_controls); 1896 mutex_unlock(&ctx->call_controls_lock); 1897 if (control->repeat) 1898 return 0; 1899 wait_for_completion(&control->completion); 1900 if (control->canceled) 1901 return -ECANCELED; 1902 return 0; 1903 } 1904 1905 /** 1906 * damos_walk() - Invoke a given functions while DAMOS walk regions. 1907 * @ctx: DAMON context to call the functions for. 1908 * @control: Control variable of the walk request. 1909 * 1910 * Ask DAMON worker thread (kdamond) of @ctx to call a function for each region 1911 * that the kdamond will apply DAMOS action to, and wait until the kdamond 1912 * finishes handling of the request. 1913 * 1914 * The kdamond executes the given function in the main loop, for each region 1915 * just after it applied any DAMOS actions of @ctx to it. The invocation is 1916 * made only within one &damos->apply_interval_us since damos_walk() 1917 * invocation, for each scheme. The given callback function can hence safely 1918 * access the internal data of &struct damon_ctx and &struct damon_region that 1919 * each of the scheme will apply the action for next interval, without 1920 * additional synchronizations against the kdamond. If every scheme of @ctx 1921 * passed at least one &damos->apply_interval_us, kdamond marks the request as 1922 * completed so that damos_walk() can wakeup and return. 1923 * 1924 * Note that this function should be called only after damon_start() with the 1925 * @ctx has succeeded. Otherwise, this function could fall into an indefinite 1926 * wait. 1927 * 1928 * Return: 0 on success, negative error code otherwise. 1929 */ 1930 int damos_walk(struct damon_ctx *ctx, struct damos_walk_control *control) 1931 { 1932 init_completion(&control->completion); 1933 control->canceled = false; 1934 mutex_lock(&ctx->walk_control_lock); 1935 if (ctx->walk_control_obsolete) { 1936 mutex_unlock(&ctx->walk_control_lock); 1937 return -ECANCELED; 1938 } 1939 if (ctx->walk_control) { 1940 mutex_unlock(&ctx->walk_control_lock); 1941 return -EBUSY; 1942 } 1943 ctx->walk_control = control; 1944 mutex_unlock(&ctx->walk_control_lock); 1945 wait_for_completion(&control->completion); 1946 if (control->canceled) 1947 return -ECANCELED; 1948 return 0; 1949 } 1950 1951 /* 1952 * Warn and fix corrupted ->nr_accesses[_bp] for investigations and preventing 1953 * the problem being propagated. 1954 */ 1955 static void damon_warn_fix_nr_accesses_corruption(struct damon_region *r) 1956 { 1957 if (r->nr_accesses_bp == r->nr_accesses * 10000) 1958 return; 1959 WARN_ONCE(true, "invalid nr_accesses_bp at reset: %u %u\n", 1960 r->nr_accesses_bp, r->nr_accesses); 1961 r->nr_accesses_bp = r->nr_accesses * 10000; 1962 } 1963 1964 #ifdef CONFIG_DAMON_DEBUG_SANITY 1965 static void damon_verify_reset_aggregated(struct damon_region *r, 1966 struct damon_ctx *c) 1967 { 1968 WARN_ONCE(r->nr_accesses_bp != r->last_nr_accesses * 10000, 1969 "nr_accesses_bp %u last_nr_accesses %u sis %lu %lu\n", 1970 r->nr_accesses_bp, r->last_nr_accesses, 1971 c->passed_sample_intervals, c->next_aggregation_sis); 1972 } 1973 #else 1974 static void damon_verify_reset_aggregated(struct damon_region *r, 1975 struct damon_ctx *c) 1976 { 1977 } 1978 #endif 1979 1980 1981 /* 1982 * Reset the aggregated monitoring results ('nr_accesses' of each region). 1983 */ 1984 static void kdamond_reset_aggregated(struct damon_ctx *c) 1985 { 1986 struct damon_target *t; 1987 unsigned int ti = 0; /* target's index */ 1988 unsigned int nr_probes = 0; 1989 struct damon_probe *probe; 1990 1991 if (trace_damon_region_aggregated_enabled()) { 1992 damon_for_each_probe(probe, c) 1993 nr_probes++; 1994 } 1995 1996 damon_for_each_target(t, c) { 1997 struct damon_region *r; 1998 1999 damon_for_each_region(r, t) { 2000 int i; 2001 2002 trace_damon_aggregated(ti, r, damon_nr_regions(t)); 2003 trace_damon_region_aggregated(ti, r, 2004 damon_nr_regions(t), nr_probes); 2005 damon_warn_fix_nr_accesses_corruption(r); 2006 r->last_nr_accesses = r->nr_accesses; 2007 r->nr_accesses = 0; 2008 for (i = 0; i < DAMON_MAX_PROBES; i++) 2009 r->probe_hits[i] = 0; 2010 damon_verify_reset_aggregated(r, c); 2011 } 2012 ti++; 2013 } 2014 } 2015 2016 static unsigned long damon_get_intervals_score(struct damon_ctx *c) 2017 { 2018 struct damon_target *t; 2019 struct damon_region *r; 2020 unsigned long sz_region, max_access_events = 0, access_events = 0; 2021 unsigned long target_access_events; 2022 unsigned long goal_bp = c->attrs.intervals_goal.access_bp; 2023 2024 damon_for_each_target(t, c) { 2025 damon_for_each_region(r, t) { 2026 sz_region = damon_sz_region(r); 2027 max_access_events += sz_region * c->attrs.aggr_samples; 2028 access_events += sz_region * r->nr_accesses; 2029 } 2030 } 2031 target_access_events = max_access_events * goal_bp / 10000; 2032 target_access_events = target_access_events ? : 1; 2033 return mult_frac(access_events, 10000, target_access_events); 2034 } 2035 2036 static unsigned long damon_feed_loop_next_input(unsigned long last_input, 2037 unsigned long score); 2038 2039 static unsigned long damon_get_intervals_adaptation_bp(struct damon_ctx *c) 2040 { 2041 unsigned long score_bp, adaptation_bp; 2042 2043 score_bp = damon_get_intervals_score(c); 2044 adaptation_bp = damon_feed_loop_next_input(100000000, score_bp) / 2045 10000; 2046 /* 2047 * adaptation_bp ranges from 1 to 20,000. Avoid too rapid reduction of 2048 * the intervals by rescaling [1,10,000] to [5000, 10,000]. 2049 */ 2050 if (adaptation_bp <= 10000) 2051 adaptation_bp = 5000 + adaptation_bp / 2; 2052 return adaptation_bp; 2053 } 2054 2055 static void kdamond_tune_intervals(struct damon_ctx *c) 2056 { 2057 unsigned long adaptation_bp; 2058 struct damon_attrs new_attrs; 2059 struct damon_intervals_goal *goal; 2060 2061 adaptation_bp = damon_get_intervals_adaptation_bp(c); 2062 if (adaptation_bp == 10000) 2063 return; 2064 2065 new_attrs = c->attrs; 2066 goal = &c->attrs.intervals_goal; 2067 new_attrs.sample_interval = min(goal->max_sample_us, 2068 c->attrs.sample_interval * adaptation_bp / 10000); 2069 new_attrs.sample_interval = max(goal->min_sample_us, 2070 new_attrs.sample_interval); 2071 new_attrs.aggr_interval = new_attrs.sample_interval * 2072 c->attrs.aggr_samples; 2073 trace_damon_monitor_intervals_tune(new_attrs.sample_interval); 2074 damon_set_attrs(c, &new_attrs); 2075 } 2076 2077 static bool __damos_valid_target(struct damon_region *r, struct damos *s) 2078 { 2079 unsigned long sz; 2080 unsigned int nr_accesses = r->nr_accesses_bp / 10000; 2081 2082 sz = damon_sz_region(r); 2083 return s->pattern.min_sz_region <= sz && 2084 sz <= s->pattern.max_sz_region && 2085 s->pattern.min_nr_accesses <= nr_accesses && 2086 nr_accesses <= s->pattern.max_nr_accesses && 2087 s->pattern.min_age_region <= r->age && 2088 r->age <= s->pattern.max_age_region; 2089 } 2090 2091 /* 2092 * damos_quota_is_set() - Return if the given quota is actually set. 2093 * @quota: The quota to check. 2094 * 2095 * Returns true if the quota is set, false otherwise. 2096 */ 2097 static bool damos_quota_is_set(struct damos_quota *quota) 2098 { 2099 return quota->esz || quota->sz || quota->ms || 2100 !damos_quota_goals_empty(quota); 2101 } 2102 2103 static bool damos_valid_target(struct damon_ctx *c, struct damon_region *r, 2104 struct damos *s) 2105 { 2106 bool ret = __damos_valid_target(r, s); 2107 2108 if (!ret || !damos_quota_is_set(&s->quota) || !c->ops.get_scheme_score) 2109 return ret; 2110 2111 return c->ops.get_scheme_score(c, r, s) >= s->quota.min_score; 2112 } 2113 2114 /* 2115 * damos_skip_charged_region() - Check if the given region or starting part of 2116 * it is already charged for the DAMOS quota. 2117 * @t: The target of the region. 2118 * @rp: The pointer to the region. 2119 * @s: The scheme to be applied. 2120 * @min_region_sz: minimum region size. 2121 * 2122 * If a quota of a scheme has exceeded in a quota charge window, the scheme's 2123 * action would applied to only a part of the target access pattern fulfilling 2124 * regions. To avoid applying the scheme action to only already applied 2125 * regions, DAMON skips applying the scheme action to the regions that charged 2126 * in the previous charge window. 2127 * 2128 * This function checks if a given region should be skipped or not for the 2129 * reason. If only the starting part of the region has previously charged, 2130 * this function splits the region into two so that the second one covers the 2131 * area that not charged in the previous charge widnow, and return true. The 2132 * caller can see the second one on the next iteration of the region walk. 2133 * Note that this means the caller should use damon_for_each_region() instead 2134 * of damon_for_each_region_safe(). If damon_for_each_region_safe() is used, 2135 * the second region will just be ignored. 2136 * 2137 * Return: true if the region should be skipped, false otherwise. 2138 */ 2139 static bool damos_skip_charged_region(struct damon_target *t, 2140 struct damon_region *r, struct damos *s, 2141 unsigned long min_region_sz) 2142 { 2143 struct damos_quota *quota = &s->quota; 2144 unsigned long sz_to_skip; 2145 2146 /* Skip previously charged regions */ 2147 if (quota->charge_target_from) { 2148 if (t != quota->charge_target_from) 2149 return true; 2150 if (r == damon_last_region(t)) { 2151 quota->charge_target_from = NULL; 2152 quota->charge_addr_from = 0; 2153 return true; 2154 } 2155 if (quota->charge_addr_from && 2156 r->ar.end <= quota->charge_addr_from) 2157 return true; 2158 2159 if (quota->charge_addr_from && r->ar.start < 2160 quota->charge_addr_from) { 2161 sz_to_skip = ALIGN_DOWN(quota->charge_addr_from - 2162 r->ar.start, min_region_sz); 2163 if (!sz_to_skip) { 2164 if (damon_sz_region(r) <= min_region_sz) 2165 return true; 2166 sz_to_skip = min_region_sz; 2167 } 2168 damon_split_region_at(t, r, sz_to_skip); 2169 return true; 2170 } 2171 quota->charge_target_from = NULL; 2172 quota->charge_addr_from = 0; 2173 } 2174 return false; 2175 } 2176 2177 static void damos_update_stat(struct damos *s, 2178 unsigned long sz_tried, unsigned long sz_applied, 2179 unsigned long sz_ops_filter_passed) 2180 { 2181 s->stat.nr_tried++; 2182 s->stat.sz_tried += sz_tried; 2183 if (sz_applied) 2184 s->stat.nr_applied++; 2185 s->stat.sz_applied += sz_applied; 2186 s->stat.sz_ops_filter_passed += sz_ops_filter_passed; 2187 } 2188 2189 static bool damos_filter_match(struct damon_ctx *ctx, struct damon_target *t, 2190 struct damon_region *r, struct damos_filter *filter, 2191 unsigned long min_region_sz) 2192 { 2193 bool matched = false; 2194 struct damon_target *ti; 2195 int target_idx = 0; 2196 unsigned long start, end; 2197 2198 switch (filter->type) { 2199 case DAMOS_FILTER_TYPE_TARGET: 2200 damon_for_each_target(ti, ctx) { 2201 if (ti == t) 2202 break; 2203 target_idx++; 2204 } 2205 matched = target_idx == filter->target_idx; 2206 break; 2207 case DAMOS_FILTER_TYPE_ADDR: 2208 start = ALIGN_DOWN(filter->addr_range.start, min_region_sz); 2209 end = ALIGN_DOWN(filter->addr_range.end, min_region_sz); 2210 2211 /* inside the range */ 2212 if (start <= r->ar.start && r->ar.end <= end) { 2213 matched = true; 2214 break; 2215 } 2216 /* outside of the range */ 2217 if (r->ar.end <= start || end <= r->ar.start) { 2218 matched = false; 2219 break; 2220 } 2221 /* start before the range and overlap */ 2222 if (r->ar.start < start) { 2223 damon_split_region_at(t, r, start - r->ar.start); 2224 matched = false; 2225 break; 2226 } 2227 /* start inside the range */ 2228 damon_split_region_at(t, r, end - r->ar.start); 2229 matched = true; 2230 break; 2231 default: 2232 return false; 2233 } 2234 2235 return matched == filter->matching; 2236 } 2237 2238 static bool damos_core_filter_out(struct damon_ctx *ctx, struct damon_target *t, 2239 struct damon_region *r, struct damos *s) 2240 { 2241 struct damos_filter *filter; 2242 2243 s->core_filters_allowed = false; 2244 damos_for_each_core_filter(filter, s) { 2245 if (damos_filter_match(ctx, t, r, filter, ctx->min_region_sz)) { 2246 if (filter->allow) 2247 s->core_filters_allowed = true; 2248 return !filter->allow; 2249 } 2250 } 2251 return s->core_filters_default_reject; 2252 } 2253 2254 /* 2255 * damos_walk_call_walk() - Call &damos_walk_control->walk_fn. 2256 * @ctx: The context of &damon_ctx->walk_control. 2257 * @t: The monitoring target of @r that @s will be applied. 2258 * @r: The region of @t that @s will be applied. 2259 * @s: The scheme of @ctx that will be applied to @r. 2260 * 2261 * This function is called from kdamond whenever it asked the operation set to 2262 * apply a DAMOS scheme action to a region. If a DAMOS walk request is 2263 * installed by damos_walk() and not yet uninstalled, invoke it. 2264 */ 2265 static void damos_walk_call_walk(struct damon_ctx *ctx, struct damon_target *t, 2266 struct damon_region *r, struct damos *s, 2267 unsigned long sz_filter_passed) 2268 { 2269 struct damos_walk_control *control; 2270 2271 if (s->walk_completed) 2272 return; 2273 2274 control = ctx->walk_control; 2275 if (!control) 2276 return; 2277 2278 control->walk_fn(control->data, ctx, t, r, s, sz_filter_passed); 2279 } 2280 2281 /* 2282 * damos_walk_complete() - Complete DAMOS walk request if all walks are done. 2283 * @ctx: The context of &damon_ctx->walk_control. 2284 * @s: A scheme of @ctx that all walks are now done. 2285 * 2286 * This function is called when kdamond finished applying the action of a DAMOS 2287 * scheme to all regions that eligible for the given &damos->apply_interval_us. 2288 * If every scheme of @ctx including @s now finished walking for at least one 2289 * &damos->apply_interval_us, this function makrs the handling of the given 2290 * DAMOS walk request is done, so that damos_walk() can wake up and return. 2291 */ 2292 static void damos_walk_complete(struct damon_ctx *ctx, struct damos *s) 2293 { 2294 struct damos *siter; 2295 struct damos_walk_control *control; 2296 2297 control = ctx->walk_control; 2298 if (!control) 2299 return; 2300 2301 s->walk_completed = true; 2302 /* if all schemes completed, signal completion to walker */ 2303 damon_for_each_scheme(siter, ctx) { 2304 if (!siter->walk_completed) 2305 return; 2306 } 2307 damon_for_each_scheme(siter, ctx) 2308 siter->walk_completed = false; 2309 2310 complete(&control->completion); 2311 ctx->walk_control = NULL; 2312 } 2313 2314 /* 2315 * damos_walk_cancel() - Cancel the current DAMOS walk request. 2316 * @ctx: The context of &damon_ctx->walk_control. 2317 * 2318 * This function is called when @ctx is deactivated by DAMOS watermarks, DAMOS 2319 * walk is requested but there is no DAMOS scheme to walk for, or the kdamond 2320 * is already out of the main loop and therefore gonna be terminated, and hence 2321 * cannot continue the walks. This function therefore marks the walk request 2322 * as canceled, so that damos_walk() can wake up and return. 2323 */ 2324 static void damos_walk_cancel(struct damon_ctx *ctx) 2325 { 2326 struct damos_walk_control *control; 2327 2328 mutex_lock(&ctx->walk_control_lock); 2329 control = ctx->walk_control; 2330 mutex_unlock(&ctx->walk_control_lock); 2331 2332 if (!control) 2333 return; 2334 control->canceled = true; 2335 complete(&control->completion); 2336 mutex_lock(&ctx->walk_control_lock); 2337 ctx->walk_control = NULL; 2338 mutex_unlock(&ctx->walk_control_lock); 2339 } 2340 2341 static void damos_charge_quota(struct damos_quota *quota, 2342 unsigned long sz_region, unsigned long sz_applied) 2343 { 2344 /* 2345 * sz_applied could be bigger than sz_region, depending on ops 2346 * implementation of the action, e.g., damos_pa_pageout(). Charge only 2347 * the region size in the case. 2348 */ 2349 if (!quota->fail_charge_denom || sz_applied > sz_region) 2350 quota->charged_sz += sz_region; 2351 else 2352 quota->charged_sz += sz_applied + mult_frac( 2353 (sz_region - sz_applied), 2354 quota->fail_charge_num, 2355 quota->fail_charge_denom); 2356 } 2357 2358 static bool damos_quota_is_full(struct damos_quota *quota, 2359 unsigned long min_region_sz) 2360 { 2361 if (!damos_quota_is_set(quota)) 2362 return false; 2363 if (quota->charged_sz >= quota->esz) 2364 return true; 2365 /* 2366 * DAMOS action is applied per region, so <min_region_sz remaining 2367 * quota means the quota is effectively full. 2368 */ 2369 return quota->esz - quota->charged_sz < min_region_sz; 2370 } 2371 2372 static void damos_apply_scheme(struct damon_ctx *c, struct damon_target *t, 2373 struct damon_region *r, struct damos *s) 2374 { 2375 struct damos_quota *quota = &s->quota; 2376 unsigned long sz = damon_sz_region(r); 2377 struct timespec64 begin, end; 2378 unsigned long sz_applied = 0; 2379 unsigned long sz_ops_filter_passed = 0; 2380 /* 2381 * We plan to support multiple context per kdamond, as DAMON sysfs 2382 * implies with 'nr_contexts' file. Nevertheless, only single context 2383 * per kdamond is supported for now. So, we can simply use '0' context 2384 * index here. 2385 */ 2386 unsigned int cidx = 0; 2387 struct damos *siter; /* schemes iterator */ 2388 unsigned int sidx = 0; 2389 struct damon_target *titer; /* targets iterator */ 2390 unsigned int tidx = 0; 2391 bool do_trace = false; 2392 2393 /* get indices for trace_damos_before_apply() */ 2394 if (trace_damos_before_apply_enabled()) { 2395 damon_for_each_scheme(siter, c) { 2396 if (siter == s) 2397 break; 2398 sidx++; 2399 } 2400 damon_for_each_target(titer, c) { 2401 if (titer == t) 2402 break; 2403 tidx++; 2404 } 2405 do_trace = true; 2406 } 2407 2408 if (c->ops.apply_scheme) { 2409 if (damos_quota_is_set(quota) && 2410 quota->charged_sz + sz > quota->esz) { 2411 sz = ALIGN_DOWN(quota->esz - quota->charged_sz, 2412 c->min_region_sz); 2413 if (!sz) 2414 goto update_stat; 2415 damon_split_region_at(t, r, sz); 2416 } 2417 if (damos_core_filter_out(c, t, r, s)) 2418 return; 2419 ktime_get_coarse_ts64(&begin); 2420 trace_damos_before_apply(cidx, sidx, tidx, r, 2421 damon_nr_regions(t), do_trace); 2422 sz_applied = c->ops.apply_scheme(c, t, r, s, 2423 &sz_ops_filter_passed); 2424 damos_walk_call_walk(c, t, r, s, sz_ops_filter_passed); 2425 ktime_get_coarse_ts64(&end); 2426 quota->total_charged_ns += timespec64_to_ns(&end) - 2427 timespec64_to_ns(&begin); 2428 damos_charge_quota(quota, sz, sz_applied); 2429 if (damos_quota_is_full(quota, c->min_region_sz)) { 2430 quota->charge_target_from = t; 2431 quota->charge_addr_from = r->ar.end; 2432 } 2433 } 2434 if (s->action != DAMOS_STAT) 2435 r->age = 0; 2436 2437 update_stat: 2438 damos_update_stat(s, sz, sz_applied, sz_ops_filter_passed); 2439 } 2440 2441 static void damon_do_apply_schemes(struct damon_ctx *c, 2442 struct damon_target *t, 2443 struct damon_region *r) 2444 { 2445 struct damos *s; 2446 2447 damon_for_each_scheme(s, c) { 2448 struct damos_quota *quota = &s->quota; 2449 2450 if (time_before(c->passed_sample_intervals, s->next_apply_sis)) 2451 continue; 2452 2453 if (!s->wmarks.activated) 2454 continue; 2455 2456 /* Check the quota */ 2457 if (damos_quota_is_full(quota, c->min_region_sz)) 2458 continue; 2459 2460 if (damos_skip_charged_region(t, r, s, c->min_region_sz)) 2461 continue; 2462 2463 if (s->max_nr_snapshots && 2464 s->max_nr_snapshots <= s->stat.nr_snapshots) 2465 continue; 2466 2467 if (damos_valid_target(c, r, s)) 2468 damos_apply_scheme(c, t, r, s); 2469 2470 if (damon_is_last_region(r, t)) 2471 s->stat.nr_snapshots++; 2472 } 2473 } 2474 2475 /* 2476 * damos_apply_target() - Apply DAMOS schemes to a given target. 2477 * @c: monitoring context to apply its DAMOS schemes to.. 2478 * @t: monitoring target to apply the schemes to. 2479 * @max_region_sz: maximum region size for @c. 2480 * 2481 * This function could split regions for keeping the quota. To minimize 2482 * overhead from the split operations increased number of regions, this 2483 * function will also merge regions after the schemes applying attempt is done, 2484 * for each region. The merge operation is made only when it doesn't lose the 2485 * monitoring information and not violating @max_region_sz. 2486 * 2487 * Hence, after this function is called, the total number of regions could 2488 * be increased or reduced. The increase could make max_nr_regions temporarily 2489 * be violated, until the next per-aggregation interval regions merge operation 2490 * is executed. The decrease will not violate min_nr_regions though, since it 2491 * keeps @max_region_sz. 2492 */ 2493 static void damos_apply_target(struct damon_ctx *c, struct damon_target *t, 2494 unsigned long max_region_sz) 2495 { 2496 struct damon_region *r; 2497 2498 damon_for_each_region(r, t) { 2499 struct damon_region *prev_r; 2500 2501 damon_do_apply_schemes(c, t, r); 2502 /* 2503 * damon_do_apply_scheems() could split the region for the 2504 * quota. Keeping the new slices is an overhead. Merge back 2505 * the slices into the previous region if it doesn't lose any 2506 * information and not violating the max_region_sz. 2507 */ 2508 if (damon_first_region(t) == r) 2509 continue; 2510 prev_r = damon_prev_region(r); 2511 if (prev_r->ar.end != r->ar.start) 2512 continue; 2513 if (prev_r->age != r->age) 2514 continue; 2515 if (prev_r->last_nr_accesses != r->last_nr_accesses) 2516 continue; 2517 if (prev_r->nr_accesses != r->nr_accesses) 2518 continue; 2519 if (r->ar.end - prev_r->ar.start > max_region_sz) 2520 continue; 2521 prev_r->ar.end = r->ar.end; 2522 damon_destroy_region(r, t); 2523 r = prev_r; 2524 } 2525 } 2526 2527 /* 2528 * damon_feed_loop_next_input() - get next input to achieve a target score. 2529 * @last_input The last input. 2530 * @score Current score that made with @last_input. 2531 * 2532 * Calculate next input to achieve the target score, based on the last input 2533 * and current score. Assuming the input and the score are positively 2534 * proportional, calculate how much compensation should be added to or 2535 * subtracted from the last input as a proportion of the last input. Avoid 2536 * next input always being zero by setting it non-zero always. In short form 2537 * (assuming support of float and signed calculations), the algorithm is as 2538 * below. 2539 * 2540 * next_input = max(last_input * ((goal - current) / goal + 1), 1) 2541 * 2542 * For simple implementation, we assume the target score is always 10,000. The 2543 * caller should adjust @score for this. 2544 * 2545 * Returns next input that assumed to achieve the target score. 2546 */ 2547 static unsigned long damon_feed_loop_next_input(unsigned long last_input, 2548 unsigned long score) 2549 { 2550 const unsigned long goal = 10000; 2551 /* Set minimum input as 10000 to avoid compensation be zero */ 2552 const unsigned long min_input = 10000; 2553 unsigned long score_goal_diff, compensation; 2554 bool over_achieving = score > goal; 2555 2556 if (score == goal) 2557 return last_input; 2558 if (score >= goal * 2) 2559 return min_input; 2560 2561 if (over_achieving) 2562 score_goal_diff = score - goal; 2563 else 2564 score_goal_diff = goal - score; 2565 2566 if (last_input < ULONG_MAX / score_goal_diff) 2567 compensation = last_input * score_goal_diff / goal; 2568 else 2569 compensation = last_input / goal * score_goal_diff; 2570 2571 if (over_achieving) 2572 return max(last_input - compensation, min_input); 2573 if (last_input < ULONG_MAX - compensation) 2574 return last_input + compensation; 2575 return ULONG_MAX; 2576 } 2577 2578 #ifdef CONFIG_PSI 2579 2580 static u64 damos_get_some_mem_psi_total(void) 2581 { 2582 if (static_branch_likely(&psi_disabled)) 2583 return 0; 2584 return div_u64(psi_system.total[PSI_AVGS][PSI_MEM * 2], 2585 NSEC_PER_USEC); 2586 } 2587 2588 #else /* CONFIG_PSI */ 2589 2590 static inline u64 damos_get_some_mem_psi_total(void) 2591 { 2592 return 0; 2593 }; 2594 2595 #endif /* CONFIG_PSI */ 2596 2597 #ifdef CONFIG_NUMA 2598 static bool invalid_mem_node(int nid) 2599 { 2600 return nid < 0 || nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY); 2601 } 2602 2603 static __kernel_ulong_t damos_get_node_mem_bp( 2604 struct damos_quota_goal *goal) 2605 { 2606 struct sysinfo i; 2607 __kernel_ulong_t numerator; 2608 2609 if (invalid_mem_node(goal->nid)) { 2610 if (goal->metric == DAMOS_QUOTA_NODE_MEM_USED_BP) 2611 return 0; 2612 else /* DAMOS_QUOTA_NODE_MEM_FREE_BP */ 2613 return 10000; 2614 } 2615 2616 si_meminfo_node(&i, goal->nid); 2617 if (goal->metric == DAMOS_QUOTA_NODE_MEM_USED_BP) 2618 numerator = i.totalram - i.freeram; 2619 else /* DAMOS_QUOTA_NODE_MEM_FREE_BP */ 2620 numerator = i.freeram; 2621 return mult_frac(numerator, 10000, i.totalram); 2622 } 2623 2624 static unsigned long damos_get_node_memcg_used_bp( 2625 struct damos_quota_goal *goal) 2626 { 2627 struct mem_cgroup *memcg; 2628 struct lruvec *lruvec; 2629 unsigned long used_pages, numerator; 2630 struct sysinfo i; 2631 2632 if (invalid_mem_node(goal->nid)) { 2633 if (goal->metric == DAMOS_QUOTA_NODE_MEMCG_USED_BP) 2634 return 0; 2635 else /* DAMOS_QUOTA_NODE_MEMCG_FREE_BP */ 2636 return 10000; 2637 } 2638 2639 memcg = mem_cgroup_get_from_id(goal->memcg_id); 2640 if (!memcg) { 2641 if (goal->metric == DAMOS_QUOTA_NODE_MEMCG_USED_BP) 2642 return 0; 2643 else /* DAMOS_QUOTA_NODE_MEMCG_FREE_BP */ 2644 return 10000; 2645 } 2646 2647 mem_cgroup_flush_stats(memcg); 2648 lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(goal->nid)); 2649 used_pages = lruvec_page_state(lruvec, NR_ACTIVE_ANON); 2650 used_pages += lruvec_page_state(lruvec, NR_INACTIVE_ANON); 2651 used_pages += lruvec_page_state(lruvec, NR_ACTIVE_FILE); 2652 used_pages += lruvec_page_state(lruvec, NR_INACTIVE_FILE); 2653 2654 mem_cgroup_put(memcg); 2655 2656 si_meminfo_node(&i, goal->nid); 2657 if (goal->metric == DAMOS_QUOTA_NODE_MEMCG_USED_BP) 2658 numerator = used_pages; 2659 else /* DAMOS_QUOTA_NODE_MEMCG_FREE_BP */ 2660 numerator = i.totalram - used_pages; 2661 return mult_frac(numerator, 10000, i.totalram); 2662 } 2663 2664 #ifdef CONFIG_DAMON_PADDR 2665 /* 2666 * damos_calc_eligible_bytes() - Calculate raw eligible bytes per node. 2667 * @c: The DAMON context. 2668 * @s: The scheme. 2669 * @nid: The target NUMA node id. 2670 * @total: Output for total eligible bytes across all nodes. 2671 * 2672 * Iterates through each folio in eligible regions to accurately determine 2673 * which node the memory resides on. Returns eligible bytes on the specified 2674 * node and sets *total to the sum across all nodes. 2675 * 2676 * Note: This function requires damon_get_folio() from ops-common.c, which is 2677 * only available when CONFIG_DAMON_PADDR is enabled. It also requires the 2678 * context to be using PADDR operations for meaningful results. 2679 */ 2680 static phys_addr_t damos_calc_eligible_bytes(struct damon_ctx *c, 2681 struct damos *s, int nid, phys_addr_t *total) 2682 { 2683 struct damon_target *t; 2684 struct damon_region *r; 2685 phys_addr_t total_eligible = 0; 2686 phys_addr_t node_eligible = 0; 2687 2688 damon_for_each_target(t, c) { 2689 damon_for_each_region(r, t) { 2690 phys_addr_t addr, end_addr; 2691 2692 if (!__damos_valid_target(r, s)) 2693 continue; 2694 2695 /* Convert from core address units to physical bytes */ 2696 addr = (phys_addr_t)r->ar.start * c->addr_unit; 2697 end_addr = (phys_addr_t)r->ar.end * c->addr_unit; 2698 while (addr < end_addr) { 2699 struct folio *folio; 2700 phys_addr_t folio_start, folio_end; 2701 phys_addr_t overlap_start, overlap_end; 2702 phys_addr_t counted; 2703 2704 folio = damon_get_folio(PHYS_PFN(addr)); 2705 if (!folio) { 2706 addr = PAGE_ALIGN_DOWN(addr + 2707 PAGE_SIZE); 2708 if (!addr) 2709 break; 2710 continue; 2711 } 2712 2713 /* 2714 * Calculate exact overlap between the region 2715 * [addr, end_addr) and the folio range. 2716 * The folio may start before addr if addr is 2717 * in the middle of a large folio. 2718 */ 2719 folio_start = PFN_PHYS(folio_pfn(folio)); 2720 folio_end = folio_start + folio_size(folio); 2721 2722 overlap_start = max(addr, folio_start); 2723 overlap_end = min(end_addr, folio_end); 2724 2725 if (overlap_end > overlap_start) { 2726 counted = overlap_end - overlap_start; 2727 total_eligible += counted; 2728 if (folio_nid(folio) == nid) 2729 node_eligible += counted; 2730 } 2731 2732 /* Advance past the entire folio */ 2733 addr = folio_end; 2734 folio_put(folio); 2735 } 2736 cond_resched(); 2737 } 2738 } 2739 2740 *total = total_eligible; 2741 return node_eligible; 2742 } 2743 2744 static unsigned long damos_get_node_eligible_mem_bp(struct damon_ctx *c, 2745 struct damos *s, int nid) 2746 { 2747 phys_addr_t total_eligible = 0; 2748 phys_addr_t node_eligible; 2749 2750 if (c->ops.id != DAMON_OPS_PADDR) 2751 return 0; 2752 2753 if (nid < 0 || nid >= MAX_NUMNODES || !node_online(nid)) 2754 return 0; 2755 2756 node_eligible = damos_calc_eligible_bytes(c, s, nid, &total_eligible); 2757 2758 if (!(unsigned long)total_eligible) 2759 return 0; 2760 2761 return mult_frac((unsigned long)node_eligible, 10000, 2762 (unsigned long)total_eligible); 2763 } 2764 #else /* CONFIG_DAMON_PADDR */ 2765 static unsigned long damos_get_node_eligible_mem_bp(struct damon_ctx *c, 2766 struct damos *s, int nid) 2767 { 2768 return 0; 2769 } 2770 #endif /* CONFIG_DAMON_PADDR */ 2771 #else /* CONFIG_NUMA */ 2772 static __kernel_ulong_t damos_get_node_mem_bp( 2773 struct damos_quota_goal *goal) 2774 { 2775 return 0; 2776 } 2777 2778 static unsigned long damos_get_node_memcg_used_bp( 2779 struct damos_quota_goal *goal) 2780 { 2781 return 0; 2782 } 2783 2784 static unsigned long damos_get_node_eligible_mem_bp(struct damon_ctx *c, 2785 struct damos *s, int nid) 2786 { 2787 return 0; 2788 } 2789 #endif /* CONFIG_NUMA */ 2790 2791 /* 2792 * Returns LRU-active or inactive memory to total LRU memory size ratio. 2793 */ 2794 static unsigned int damos_get_in_active_mem_bp(bool active_ratio) 2795 { 2796 unsigned long active, inactive, total; 2797 2798 /* This should align with /proc/meminfo output */ 2799 active = global_node_page_state(NR_LRU_BASE + LRU_ACTIVE_ANON) + 2800 global_node_page_state(NR_LRU_BASE + LRU_ACTIVE_FILE); 2801 inactive = global_node_page_state(NR_LRU_BASE + LRU_INACTIVE_ANON) + 2802 global_node_page_state(NR_LRU_BASE + LRU_INACTIVE_FILE); 2803 total = active + inactive; 2804 if (active_ratio) 2805 return mult_frac(active, 10000, total); 2806 return mult_frac(inactive, 10000, total); 2807 } 2808 2809 static void damos_set_quota_goal_current_value(struct damon_ctx *c, 2810 struct damos *s, struct damos_quota_goal *goal) 2811 { 2812 u64 now_psi_total; 2813 2814 switch (goal->metric) { 2815 case DAMOS_QUOTA_USER_INPUT: 2816 /* User should already set goal->current_value */ 2817 break; 2818 case DAMOS_QUOTA_SOME_MEM_PSI_US: 2819 now_psi_total = damos_get_some_mem_psi_total(); 2820 goal->current_value = now_psi_total - goal->last_psi_total; 2821 goal->last_psi_total = now_psi_total; 2822 break; 2823 case DAMOS_QUOTA_NODE_MEM_USED_BP: 2824 case DAMOS_QUOTA_NODE_MEM_FREE_BP: 2825 goal->current_value = damos_get_node_mem_bp(goal); 2826 break; 2827 case DAMOS_QUOTA_NODE_MEMCG_USED_BP: 2828 case DAMOS_QUOTA_NODE_MEMCG_FREE_BP: 2829 goal->current_value = damos_get_node_memcg_used_bp(goal); 2830 break; 2831 case DAMOS_QUOTA_ACTIVE_MEM_BP: 2832 case DAMOS_QUOTA_INACTIVE_MEM_BP: 2833 goal->current_value = damos_get_in_active_mem_bp( 2834 goal->metric == DAMOS_QUOTA_ACTIVE_MEM_BP); 2835 break; 2836 case DAMOS_QUOTA_NODE_ELIGIBLE_MEM_BP: 2837 goal->current_value = damos_get_node_eligible_mem_bp(c, s, 2838 goal->nid); 2839 break; 2840 default: 2841 break; 2842 } 2843 } 2844 2845 /* Return the highest score since it makes schemes least aggressive */ 2846 static unsigned long damos_quota_score(struct damon_ctx *c, struct damos *s) 2847 { 2848 struct damos_quota_goal *goal; 2849 struct damos_quota *quota = &s->quota; 2850 unsigned long highest_score = 0; 2851 2852 damos_for_each_quota_goal(goal, quota) { 2853 damos_set_quota_goal_current_value(c, s, goal); 2854 highest_score = max(highest_score, 2855 mult_frac(goal->current_value, 10000, 2856 goal->target_value)); 2857 } 2858 2859 return highest_score; 2860 } 2861 2862 static void damos_goal_tune_esz_bp_consist(struct damon_ctx *c, struct damos *s) 2863 { 2864 struct damos_quota *quota = &s->quota; 2865 unsigned long score = damos_quota_score(c, s); 2866 2867 quota->esz_bp = damon_feed_loop_next_input( 2868 max(quota->esz_bp, 10000UL), score); 2869 } 2870 2871 static void damos_goal_tune_esz_bp_temporal(struct damon_ctx *c, 2872 struct damos *s) 2873 { 2874 struct damos_quota *quota = &s->quota; 2875 unsigned long score = damos_quota_score(c, s); 2876 2877 if (score >= 10000) 2878 quota->esz_bp = 0; 2879 else if (quota->sz) 2880 quota->esz_bp = quota->sz * 10000; 2881 else 2882 quota->esz_bp = ULONG_MAX; 2883 } 2884 2885 /* 2886 * Called only if quota->ms, or quota->sz are set, or quota->goals is not empty 2887 */ 2888 static void damos_set_effective_quota(struct damon_ctx *ctx, struct damos *s) 2889 { 2890 struct damos_quota *quota = &s->quota; 2891 unsigned long throughput; 2892 unsigned long esz = ULONG_MAX; 2893 2894 if (!quota->ms && list_empty("a->goals)) { 2895 quota->esz = quota->sz; 2896 return; 2897 } 2898 2899 if (!list_empty("a->goals)) { 2900 if (quota->goal_tuner == DAMOS_QUOTA_GOAL_TUNER_CONSIST) 2901 damos_goal_tune_esz_bp_consist(ctx, s); 2902 else if (quota->goal_tuner == DAMOS_QUOTA_GOAL_TUNER_TEMPORAL) 2903 damos_goal_tune_esz_bp_temporal(ctx, s); 2904 esz = quota->esz_bp / 10000; 2905 } 2906 2907 if (quota->ms) { 2908 if (quota->total_charged_ns) 2909 throughput = mult_frac(quota->total_charged_sz, 2910 1000000, quota->total_charged_ns); 2911 else 2912 throughput = PAGE_SIZE * 1024; 2913 esz = min(throughput * quota->ms, esz); 2914 esz = max(ctx->min_region_sz, esz); 2915 } 2916 2917 if (quota->sz && quota->sz < esz) 2918 esz = quota->sz; 2919 2920 quota->esz = esz; 2921 } 2922 2923 static void damos_trace_esz(struct damon_ctx *c, struct damos *s, 2924 struct damos_quota *quota) 2925 { 2926 unsigned int cidx = 0, sidx = 0; 2927 struct damos *siter; 2928 2929 damon_for_each_scheme(siter, c) { 2930 if (siter == s) 2931 break; 2932 sidx++; 2933 } 2934 trace_damos_esz(cidx, sidx, quota->esz); 2935 } 2936 2937 static void damos_adjust_quota(struct damon_ctx *c, struct damos *s) 2938 { 2939 struct damos_quota *quota = &s->quota; 2940 struct damon_target *t; 2941 struct damon_region *r; 2942 unsigned long cumulated_sz, cached_esz; 2943 unsigned int score, max_score = 0; 2944 2945 if (!quota->ms && !quota->sz && list_empty("a->goals)) 2946 return; 2947 2948 /* First charge window */ 2949 if (!quota->total_charged_sz && !quota->charged_from) { 2950 quota->charged_from = jiffies; 2951 damos_set_effective_quota(c, s); 2952 if (trace_damos_esz_enabled()) 2953 damos_trace_esz(c, s, quota); 2954 } 2955 2956 /* New charge window starts */ 2957 if (!time_in_range_open(jiffies, quota->charged_from, 2958 quota->charged_from + 2959 msecs_to_jiffies(quota->reset_interval))) { 2960 if (damos_quota_is_full(quota, c->min_region_sz)) 2961 s->stat.qt_exceeds++; 2962 quota->total_charged_sz += quota->charged_sz; 2963 quota->charged_from = jiffies; 2964 quota->charged_sz = 0; 2965 if (trace_damos_esz_enabled()) 2966 cached_esz = quota->esz; 2967 damos_set_effective_quota(c, s); 2968 if (trace_damos_esz_enabled() && quota->esz != cached_esz) 2969 damos_trace_esz(c, s, quota); 2970 } 2971 2972 if (!c->ops.get_scheme_score) 2973 return; 2974 2975 /* Fill up the score histogram */ 2976 memset(c->regions_score_histogram, 0, 2977 sizeof(*c->regions_score_histogram) * 2978 (DAMOS_MAX_SCORE + 1)); 2979 damon_for_each_target(t, c) { 2980 damon_for_each_region(r, t) { 2981 if (!__damos_valid_target(r, s)) 2982 continue; 2983 if (damos_core_filter_out(c, t, r, s)) 2984 continue; 2985 score = c->ops.get_scheme_score(c, r, s); 2986 c->regions_score_histogram[score] += 2987 damon_sz_region(r); 2988 if (score > max_score) 2989 max_score = score; 2990 } 2991 } 2992 2993 /* Set the min score limit */ 2994 for (cumulated_sz = 0, score = max_score; ; score--) { 2995 cumulated_sz += c->regions_score_histogram[score]; 2996 if (cumulated_sz >= quota->esz || !score) 2997 break; 2998 } 2999 quota->min_score = score; 3000 } 3001 3002 static void damos_trace_stat(struct damon_ctx *c, struct damos *s) 3003 { 3004 unsigned int cidx = 0, sidx = 0; 3005 struct damos *siter; 3006 3007 if (!trace_damos_stat_after_apply_interval_enabled()) 3008 return; 3009 3010 damon_for_each_scheme(siter, c) { 3011 if (siter == s) 3012 break; 3013 sidx++; 3014 } 3015 trace_call__damos_stat_after_apply_interval(cidx, sidx, &s->stat); 3016 } 3017 3018 static void kdamond_apply_schemes(struct damon_ctx *c) 3019 { 3020 struct damon_target *t; 3021 struct damos *s; 3022 bool has_schemes_to_apply = false; 3023 unsigned long max_region_sz; 3024 3025 damon_for_each_scheme(s, c) { 3026 if (time_before(c->passed_sample_intervals, s->next_apply_sis)) 3027 continue; 3028 3029 if (!s->wmarks.activated) 3030 continue; 3031 3032 has_schemes_to_apply = true; 3033 3034 damos_adjust_quota(c, s); 3035 } 3036 3037 if (!has_schemes_to_apply) 3038 return; 3039 3040 max_region_sz = damon_region_sz_limit(c); 3041 mutex_lock(&c->walk_control_lock); 3042 damon_for_each_target(t, c) { 3043 if (c->ops.target_valid && c->ops.target_valid(t) == false) 3044 continue; 3045 damos_apply_target(c, t, max_region_sz); 3046 } 3047 3048 damon_for_each_scheme(s, c) { 3049 if (time_before(c->passed_sample_intervals, s->next_apply_sis)) 3050 continue; 3051 damos_walk_complete(c, s); 3052 damos_set_next_apply_sis(s, c); 3053 s->last_applied = NULL; 3054 damos_trace_stat(c, s); 3055 } 3056 mutex_unlock(&c->walk_control_lock); 3057 } 3058 3059 #ifdef CONFIG_DAMON_DEBUG_SANITY 3060 static void damon_verify_merge_two_regions( 3061 struct damon_region *l, struct damon_region *r) 3062 { 3063 /* damon_merge_two_regions() may created incorrect left region */ 3064 WARN_ONCE(l->ar.start >= l->ar.end, "l: %lu-%lu, r: %lu-%lu\n", 3065 l->ar.start, l->ar.end, r->ar.start, r->ar.end); 3066 } 3067 #else 3068 static void damon_verify_merge_two_regions( 3069 struct damon_region *l, struct damon_region *r) 3070 { 3071 } 3072 #endif 3073 3074 /* 3075 * Merge two adjacent regions into one region 3076 */ 3077 static void damon_merge_two_regions(struct damon_target *t, 3078 struct damon_region *l, struct damon_region *r) 3079 { 3080 unsigned long sz_l = damon_sz_region(l), sz_r = damon_sz_region(r); 3081 int i; 3082 3083 l->nr_accesses = (l->nr_accesses * sz_l + r->nr_accesses * sz_r) / 3084 (sz_l + sz_r); 3085 l->nr_accesses_bp = l->nr_accesses * 10000; 3086 l->age = (l->age * sz_l + r->age * sz_r) / (sz_l + sz_r); 3087 l->ar.end = r->ar.end; 3088 /* todo: do this for only installed probes */ 3089 for (i = 0; i < DAMON_MAX_PROBES; i++) 3090 l->probe_hits[i] = (l->probe_hits[i] * sz_l + r->probe_hits[i] 3091 * sz_r) / (sz_l + sz_r); 3092 damon_verify_merge_two_regions(l, r); 3093 damon_destroy_region(r, t); 3094 } 3095 3096 #ifdef CONFIG_DAMON_DEBUG_SANITY 3097 static void damon_verify_merge_regions_of(struct damon_region *r) 3098 { 3099 WARN_ONCE(r->nr_accesses != r->nr_accesses_bp / 10000, 3100 "nr_accesses (%u) != nr_accesses_bp (%u)\n", 3101 r->nr_accesses, r->nr_accesses_bp); 3102 } 3103 #else 3104 static void damon_verify_merge_regions_of(struct damon_region *r) 3105 { 3106 } 3107 #endif 3108 3109 3110 /* 3111 * Merge adjacent regions having similar access frequencies 3112 * 3113 * t target affected by this merge operation 3114 * thres '->nr_accesses' diff threshold for the merge 3115 * sz_limit size upper limit of each region 3116 */ 3117 static void damon_merge_regions_of(struct damon_target *t, unsigned int thres, 3118 unsigned long sz_limit) 3119 { 3120 struct damon_region *r, *prev = NULL, *next; 3121 3122 damon_for_each_region_safe(r, next, t) { 3123 damon_verify_merge_regions_of(r); 3124 if (abs(r->nr_accesses - r->last_nr_accesses) > thres) 3125 r->age = 0; 3126 else if ((r->nr_accesses == 0) != (r->last_nr_accesses == 0)) 3127 r->age = 0; 3128 else 3129 r->age++; 3130 3131 if (prev && prev->ar.end == r->ar.start && 3132 abs(prev->nr_accesses - r->nr_accesses) <= thres && 3133 damon_sz_region(prev) + damon_sz_region(r) <= sz_limit) 3134 damon_merge_two_regions(t, prev, r); 3135 else 3136 prev = r; 3137 } 3138 } 3139 3140 /* 3141 * Merge adjacent regions having similar access frequencies 3142 * 3143 * threshold '->nr_accesses' diff threshold for the merge 3144 * sz_limit size upper limit of each region 3145 * 3146 * This function merges monitoring target regions which are adjacent and their 3147 * access frequencies are similar. This is for minimizing the monitoring 3148 * overhead under the dynamically changeable access pattern. If a merge was 3149 * unnecessarily made, later 'kdamond_split_regions()' will revert it. 3150 * 3151 * The total number of regions could be higher than the user-defined limit, 3152 * max_nr_regions for some cases. For example, the user can update 3153 * max_nr_regions to a number that lower than the current number of regions 3154 * while DAMON is running. For such a case, repeat merging until the limit is 3155 * met while increasing @threshold up to possible maximum level. 3156 */ 3157 static void kdamond_merge_regions(struct damon_ctx *c, unsigned int threshold, 3158 unsigned long sz_limit) 3159 { 3160 struct damon_target *t; 3161 unsigned int nr_regions; 3162 unsigned int max_thres; 3163 3164 max_thres = c->attrs.aggr_interval / 3165 (c->attrs.sample_interval ? c->attrs.sample_interval : 1); 3166 do { 3167 nr_regions = 0; 3168 damon_for_each_target(t, c) { 3169 damon_merge_regions_of(t, threshold, sz_limit); 3170 nr_regions += damon_nr_regions(t); 3171 } 3172 threshold = max(1, threshold * 2); 3173 } while (nr_regions > c->attrs.max_nr_regions && 3174 threshold / 2 < max_thres); 3175 } 3176 3177 #ifdef CONFIG_DAMON_DEBUG_SANITY 3178 static void damon_verify_split_region_at(struct damon_region *r, 3179 unsigned long sz_r) 3180 { 3181 WARN_ONCE(sz_r == 0 || sz_r >= damon_sz_region(r), 3182 "sz_r: %lu r: %lu-%lu (%lu)\n", 3183 sz_r, r->ar.start, r->ar.end, damon_sz_region(r)); 3184 } 3185 #else 3186 static void damon_verify_split_region_at(struct damon_region *r, 3187 unsigned long sz_r) 3188 { 3189 } 3190 #endif 3191 3192 /* 3193 * Split a region in two 3194 * 3195 * r the region to be split 3196 * sz_r size of the first sub-region that will be made 3197 */ 3198 static void damon_split_region_at(struct damon_target *t, 3199 struct damon_region *r, unsigned long sz_r) 3200 { 3201 struct damon_region *new; 3202 3203 damon_verify_split_region_at(r, sz_r); 3204 new = damon_new_region(r->ar.start + sz_r, r->ar.end); 3205 if (!new) 3206 return; 3207 3208 r->ar.end = new->ar.start; 3209 3210 new->age = r->age; 3211 new->last_nr_accesses = r->last_nr_accesses; 3212 new->nr_accesses_bp = r->nr_accesses_bp; 3213 new->nr_accesses = r->nr_accesses; 3214 /* todo: do this for only installed probes */ 3215 memcpy(new->probe_hits, r->probe_hits, sizeof(r->probe_hits)); 3216 3217 damon_insert_region(new, r, damon_next_region(r), t); 3218 } 3219 3220 /* Split every region in the given target into 'nr_subs' regions */ 3221 static void damon_split_regions_of(struct damon_ctx *ctx, 3222 struct damon_target *t, int nr_subs, 3223 unsigned long min_region_sz) 3224 { 3225 struct damon_region *r, *next; 3226 unsigned long sz_region, sz_sub = 0; 3227 int i; 3228 3229 damon_for_each_region_safe(r, next, t) { 3230 sz_region = damon_sz_region(r); 3231 3232 for (i = 0; i < nr_subs - 1 && 3233 sz_region > 2 * min_region_sz; i++) { 3234 /* 3235 * Randomly select size of left sub-region to be at 3236 * least 10 percent and at most 90% of original region 3237 */ 3238 sz_sub = ALIGN_DOWN(damon_rand(ctx, 1, 10) * 3239 sz_region / 10, min_region_sz); 3240 /* Do not allow blank region */ 3241 if (sz_sub == 0 || sz_sub >= sz_region) 3242 continue; 3243 3244 damon_split_region_at(t, r, sz_sub); 3245 sz_region = sz_sub; 3246 } 3247 } 3248 } 3249 3250 /* 3251 * Split every target region into randomly-sized small regions 3252 * 3253 * This function splits every target region into random-sized small regions if 3254 * current total number of the regions is equal or smaller than half of the 3255 * user-specified maximum number of regions. This is for maximizing the 3256 * monitoring accuracy under the dynamically changeable access patterns. If a 3257 * split was unnecessarily made, later 'kdamond_merge_regions()' will revert 3258 * it. 3259 */ 3260 static void kdamond_split_regions(struct damon_ctx *ctx) 3261 { 3262 struct damon_target *t; 3263 unsigned int nr_regions = 0; 3264 static unsigned int last_nr_regions; 3265 int nr_subregions = 2; 3266 3267 damon_for_each_target(t, ctx) 3268 nr_regions += damon_nr_regions(t); 3269 3270 if (nr_regions > ctx->attrs.max_nr_regions / 2) 3271 return; 3272 3273 /* Maybe the middle of the region has different access frequency */ 3274 if (last_nr_regions == nr_regions && 3275 nr_regions < ctx->attrs.max_nr_regions / 3) 3276 nr_subregions = 3; 3277 3278 damon_for_each_target(t, ctx) 3279 damon_split_regions_of(ctx, t, nr_subregions, 3280 ctx->min_region_sz); 3281 3282 last_nr_regions = nr_regions; 3283 } 3284 3285 /* 3286 * Check whether current monitoring should be stopped 3287 * 3288 * The monitoring is stopped when either the user requested to stop, or all 3289 * monitoring targets are invalid. 3290 * 3291 * Returns true if need to stop current monitoring. 3292 */ 3293 static bool kdamond_need_stop(struct damon_ctx *ctx) 3294 { 3295 struct damon_target *t; 3296 3297 if (kthread_should_stop()) 3298 return true; 3299 3300 if (!ctx->ops.target_valid) 3301 return false; 3302 3303 damon_for_each_target(t, ctx) { 3304 if (ctx->ops.target_valid(t)) 3305 return false; 3306 } 3307 3308 return true; 3309 } 3310 3311 static int damos_get_wmark_metric_value(enum damos_wmark_metric metric, 3312 unsigned long *metric_value) 3313 { 3314 switch (metric) { 3315 case DAMOS_WMARK_FREE_MEM_RATE: 3316 *metric_value = global_zone_page_state(NR_FREE_PAGES) * 1000 / 3317 totalram_pages(); 3318 return 0; 3319 default: 3320 break; 3321 } 3322 return -EINVAL; 3323 } 3324 3325 /* 3326 * Returns zero if the scheme is active. Else, returns time to wait for next 3327 * watermark check in micro-seconds. 3328 */ 3329 static unsigned long damos_wmark_wait_us(struct damos *scheme) 3330 { 3331 unsigned long metric; 3332 3333 if (damos_get_wmark_metric_value(scheme->wmarks.metric, &metric)) 3334 return 0; 3335 3336 /* higher than high watermark or lower than low watermark */ 3337 if (metric > scheme->wmarks.high || scheme->wmarks.low > metric) { 3338 if (scheme->wmarks.activated) 3339 pr_debug("deactivate a scheme (%d) for %s wmark\n", 3340 scheme->action, 3341 str_high_low(metric > scheme->wmarks.high)); 3342 scheme->wmarks.activated = false; 3343 return scheme->wmarks.interval; 3344 } 3345 3346 /* inactive and higher than middle watermark */ 3347 if ((scheme->wmarks.high >= metric && metric >= scheme->wmarks.mid) && 3348 !scheme->wmarks.activated) 3349 return scheme->wmarks.interval; 3350 3351 if (!scheme->wmarks.activated) 3352 pr_debug("activate a scheme (%d)\n", scheme->action); 3353 scheme->wmarks.activated = true; 3354 return 0; 3355 } 3356 3357 static void kdamond_usleep(unsigned long usecs) 3358 { 3359 if (usecs >= USLEEP_RANGE_UPPER_BOUND) 3360 schedule_timeout_idle(usecs_to_jiffies(usecs)); 3361 else 3362 usleep_range_idle(usecs, usecs + 1); 3363 } 3364 3365 #ifdef CONFIG_DAMON_DEBUG_SANITY 3366 static void damon_verify_ctx(struct damon_ctx *c) 3367 { 3368 struct damon_target *t; 3369 struct damon_region *r; 3370 3371 damon_for_each_target(t, c) { 3372 struct damon_region *prev_r = NULL; 3373 unsigned int nr_regions = 0; 3374 3375 damon_for_each_region(r, t) { 3376 WARN_ONCE(r->ar.start >= r->ar.end, 3377 "region start (%lu) >= end (%lu)\n", 3378 r->ar.start, r->ar.end); 3379 WARN_ONCE(prev_r && prev_r->ar.end > r->ar.start, 3380 "region overlap (%lu > %lu)\n", 3381 prev_r->ar.end, r->ar.start); 3382 prev_r = r; 3383 nr_regions++; 3384 } 3385 WARN_ONCE(damon_nr_regions(t) != nr_regions, 3386 "nr_regions mismatch: %u != %u\n", 3387 damon_nr_regions(t), nr_regions); 3388 } 3389 } 3390 #else 3391 static void damon_verify_ctx(struct damon_ctx *c) 3392 { 3393 } 3394 #endif 3395 3396 /* 3397 * kdamond_call() - handle damon_call_control objects. 3398 * @ctx: The &struct damon_ctx of the kdamond. 3399 * @cancel: Whether to cancel the invocation of the function. 3400 * 3401 * If there are &struct damon_call_control requests that registered via 3402 * &damon_call() on @ctx, do or cancel the invocation of the function depending 3403 * on @cancel. @cancel is set when the kdamond is already out of the main loop 3404 * and therefore will be terminated. 3405 */ 3406 static void kdamond_call(struct damon_ctx *ctx, bool cancel) 3407 { 3408 struct damon_call_control *control, *next; 3409 LIST_HEAD(controls); 3410 3411 damon_verify_ctx(ctx); 3412 3413 mutex_lock(&ctx->call_controls_lock); 3414 list_splice_tail_init(&ctx->call_controls, &controls); 3415 mutex_unlock(&ctx->call_controls_lock); 3416 3417 list_for_each_entry_safe(control, next, &controls, list) { 3418 if (!control->repeat || cancel) 3419 list_del(&control->list); 3420 3421 if (cancel) 3422 control->canceled = true; 3423 else 3424 control->return_code = control->fn(control->data); 3425 3426 if (!control->repeat) 3427 complete(&control->completion); 3428 else if (control->canceled && control->dealloc_on_cancel) 3429 kfree(control); 3430 if (!cancel && ctx->maybe_corrupted) 3431 break; 3432 } 3433 3434 mutex_lock(&ctx->call_controls_lock); 3435 list_splice_tail(&controls, &ctx->call_controls); 3436 mutex_unlock(&ctx->call_controls_lock); 3437 } 3438 3439 /* Returns negative error code if it's not activated but should return */ 3440 static int kdamond_wait_activation(struct damon_ctx *ctx) 3441 { 3442 struct damos *s; 3443 unsigned long wait_time; 3444 unsigned long min_wait_time = 0; 3445 bool init_wait_time = false; 3446 3447 while (!kdamond_need_stop(ctx)) { 3448 damon_for_each_scheme(s, ctx) { 3449 wait_time = damos_wmark_wait_us(s); 3450 if (!init_wait_time || wait_time < min_wait_time) { 3451 init_wait_time = true; 3452 min_wait_time = wait_time; 3453 } 3454 } 3455 if (!min_wait_time) 3456 return 0; 3457 3458 kdamond_usleep(min_wait_time); 3459 3460 kdamond_call(ctx, false); 3461 if (ctx->maybe_corrupted) 3462 return -EINVAL; 3463 damos_walk_cancel(ctx); 3464 } 3465 return -EBUSY; 3466 } 3467 3468 static void kdamond_init_ctx(struct damon_ctx *ctx) 3469 { 3470 unsigned long sample_interval = ctx->attrs.sample_interval ? 3471 ctx->attrs.sample_interval : 1; 3472 struct damos *scheme; 3473 3474 ctx->passed_sample_intervals = 0; 3475 ctx->next_aggregation_sis = ctx->attrs.aggr_interval / sample_interval; 3476 ctx->next_ops_update_sis = ctx->attrs.ops_update_interval / 3477 sample_interval; 3478 ctx->next_intervals_tune_sis = ctx->next_aggregation_sis * 3479 ctx->attrs.intervals_goal.aggrs; 3480 3481 damon_for_each_scheme(scheme, ctx) { 3482 damos_set_next_apply_sis(scheme, ctx); 3483 damos_set_filters_default_reject(scheme); 3484 } 3485 } 3486 3487 /* 3488 * The monitoring daemon that runs as a kernel thread 3489 */ 3490 static int kdamond_fn(void *data) 3491 { 3492 struct damon_ctx *ctx = data; 3493 unsigned int max_nr_accesses = 0; 3494 unsigned long sz_limit = 0; 3495 3496 pr_debug("kdamond (%d) starts\n", current->pid); 3497 3498 mutex_lock(&ctx->call_controls_lock); 3499 ctx->call_controls_obsolete = false; 3500 mutex_unlock(&ctx->call_controls_lock); 3501 mutex_lock(&ctx->walk_control_lock); 3502 ctx->walk_control_obsolete = false; 3503 mutex_unlock(&ctx->walk_control_lock); 3504 complete(&ctx->kdamond_started); 3505 kdamond_init_ctx(ctx); 3506 3507 if (ctx->ops.init) 3508 ctx->ops.init(ctx); 3509 ctx->regions_score_histogram = kmalloc_array(DAMOS_MAX_SCORE + 1, 3510 sizeof(*ctx->regions_score_histogram), GFP_KERNEL); 3511 if (!ctx->regions_score_histogram) 3512 goto done; 3513 3514 sz_limit = damon_apply_min_nr_regions(ctx); 3515 3516 while (!kdamond_need_stop(ctx)) { 3517 /* 3518 * ctx->attrs and ctx->next_{aggregation,ops_update}_sis could 3519 * be changed from kdamond_call(). Read the values here, and 3520 * use those for this iteration. That is, damon_set_attrs() 3521 * updated new values are respected from next iteration. 3522 */ 3523 unsigned long next_aggregation_sis = ctx->next_aggregation_sis; 3524 unsigned long next_ops_update_sis = ctx->next_ops_update_sis; 3525 unsigned long sample_interval = ctx->attrs.sample_interval; 3526 3527 if (kdamond_wait_activation(ctx)) 3528 break; 3529 3530 if (ctx->ops.prepare_access_checks) 3531 ctx->ops.prepare_access_checks(ctx); 3532 3533 kdamond_usleep(sample_interval); 3534 ctx->passed_sample_intervals++; 3535 3536 if (ctx->ops.check_accesses) 3537 max_nr_accesses = ctx->ops.check_accesses(ctx); 3538 if (ctx->ops.apply_probes) 3539 ctx->ops.apply_probes(ctx); 3540 3541 if (time_after_eq(ctx->passed_sample_intervals, 3542 next_aggregation_sis)) { 3543 kdamond_merge_regions(ctx, 3544 max_nr_accesses / 10, 3545 sz_limit); 3546 /* online updates might be made */ 3547 sz_limit = damon_apply_min_nr_regions(ctx); 3548 } 3549 3550 /* 3551 * do kdamond_call() and kdamond_apply_schemes() after 3552 * kdamond_merge_regions() if possible, to reduce overhead 3553 */ 3554 kdamond_call(ctx, false); 3555 if (ctx->maybe_corrupted) 3556 break; 3557 while (ctx->pause) { 3558 damos_walk_cancel(ctx); 3559 kdamond_usleep(ctx->attrs.sample_interval); 3560 /* allow caller unset pause via damon_call() */ 3561 kdamond_call(ctx, false); 3562 if (kdamond_need_stop(ctx) || ctx->maybe_corrupted) 3563 goto done; 3564 } 3565 if (!list_empty(&ctx->schemes)) 3566 kdamond_apply_schemes(ctx); 3567 else 3568 damos_walk_cancel(ctx); 3569 3570 sample_interval = ctx->attrs.sample_interval ? 3571 ctx->attrs.sample_interval : 1; 3572 if (time_after_eq(ctx->passed_sample_intervals, 3573 next_aggregation_sis)) { 3574 if (ctx->attrs.intervals_goal.aggrs && 3575 time_after_eq( 3576 ctx->passed_sample_intervals, 3577 ctx->next_intervals_tune_sis)) { 3578 /* 3579 * ctx->next_aggregation_sis might be updated 3580 * from kdamond_call(). In the case, 3581 * damon_set_attrs() which will be called from 3582 * kdamond_tune_interval() may wrongly think 3583 * this is in the middle of the current 3584 * aggregation, and make aggregation 3585 * information reset for all regions. Then, 3586 * following kdamond_reset_aggregated() call 3587 * will make the region information invalid, 3588 * particularly for ->nr_accesses_bp. 3589 * 3590 * Reset ->next_aggregation_sis to avoid that. 3591 * It will anyway correctly updated after this 3592 * if clause. 3593 */ 3594 ctx->next_aggregation_sis = 3595 next_aggregation_sis; 3596 ctx->next_intervals_tune_sis += 3597 ctx->attrs.aggr_samples * 3598 ctx->attrs.intervals_goal.aggrs; 3599 kdamond_tune_intervals(ctx); 3600 sample_interval = ctx->attrs.sample_interval ? 3601 ctx->attrs.sample_interval : 1; 3602 3603 } 3604 ctx->next_aggregation_sis = next_aggregation_sis + 3605 ctx->attrs.aggr_interval / sample_interval; 3606 3607 kdamond_reset_aggregated(ctx); 3608 kdamond_split_regions(ctx); 3609 } 3610 3611 if (time_after_eq(ctx->passed_sample_intervals, 3612 next_ops_update_sis)) { 3613 ctx->next_ops_update_sis = next_ops_update_sis + 3614 ctx->attrs.ops_update_interval / 3615 sample_interval; 3616 if (ctx->ops.update) 3617 ctx->ops.update(ctx); 3618 } 3619 } 3620 done: 3621 damon_destroy_targets(ctx); 3622 3623 kfree(ctx->regions_score_histogram); 3624 mutex_lock(&ctx->call_controls_lock); 3625 ctx->call_controls_obsolete = true; 3626 mutex_unlock(&ctx->call_controls_lock); 3627 kdamond_call(ctx, true); 3628 mutex_lock(&ctx->walk_control_lock); 3629 ctx->walk_control_obsolete = true; 3630 mutex_unlock(&ctx->walk_control_lock); 3631 damos_walk_cancel(ctx); 3632 3633 pr_debug("kdamond (%d) finishes\n", current->pid); 3634 mutex_lock(&ctx->kdamond_lock); 3635 ctx->kdamond = NULL; 3636 mutex_unlock(&ctx->kdamond_lock); 3637 3638 mutex_lock(&damon_lock); 3639 nr_running_ctxs--; 3640 if (!nr_running_ctxs && running_exclusive_ctxs) 3641 running_exclusive_ctxs = false; 3642 mutex_unlock(&damon_lock); 3643 3644 return 0; 3645 } 3646 3647 struct damon_system_ram_range_walk_arg { 3648 bool walked; 3649 struct resource res; 3650 }; 3651 3652 static int damon_system_ram_walk_fn(struct resource *res, void *arg) 3653 { 3654 struct damon_system_ram_range_walk_arg *a = arg; 3655 3656 if (!a->walked) { 3657 a->walked = true; 3658 a->res.start = res->start; 3659 } 3660 a->res.end = res->end; 3661 return 0; 3662 } 3663 3664 static unsigned long damon_res_to_core_addr(resource_size_t ra, 3665 unsigned long addr_unit) 3666 { 3667 /* 3668 * Use div_u64() for avoiding linking errors related with __udivdi3, 3669 * __aeabi_uldivmod, or similar problems. This should also improve the 3670 * performance optimization (read div_u64() comment for the detail). 3671 */ 3672 if (sizeof(ra) == 8 && sizeof(addr_unit) == 4) 3673 return div_u64(ra, addr_unit); 3674 return ra / addr_unit; 3675 } 3676 3677 static bool damon_find_system_rams_range(unsigned long *start, 3678 unsigned long *end, unsigned long addr_unit) 3679 { 3680 struct damon_system_ram_range_walk_arg arg = {}; 3681 3682 walk_system_ram_res(0, -1, &arg, damon_system_ram_walk_fn); 3683 if (!arg.walked) 3684 return false; 3685 *start = damon_res_to_core_addr(arg.res.start, addr_unit); 3686 *end = damon_res_to_core_addr(arg.res.end + 1, addr_unit); 3687 if (*end <= *start) 3688 return false; 3689 return true; 3690 } 3691 3692 /** 3693 * damon_set_region_system_rams_default() - Set the region of the given 3694 * monitoring target as requested, or to cover all 'System RAM' resources. 3695 * @t: The monitoring target to set the region. 3696 * @start: The pointer to the start address of the region. 3697 * @end: The pointer to the end address of the region. 3698 * @addr_unit: The address unit for the damon_ctx of @t. 3699 * @min_region_sz: Minimum region size. 3700 * 3701 * This function sets the region of @t as requested by @start and @end. If the 3702 * values of @start and @end are zero, however, this function finds 'System 3703 * RAM' resources and sets the region to cover all the resource. In the latter 3704 * case, this function saves the start and the end addresseses of the first and 3705 * the last resources in @start and @end, respectively. 3706 * 3707 * Return: 0 on success, negative error code otherwise. 3708 */ 3709 int damon_set_region_system_rams_default(struct damon_target *t, 3710 unsigned long *start, unsigned long *end, 3711 unsigned long addr_unit, unsigned long min_region_sz) 3712 { 3713 struct damon_addr_range addr_range; 3714 3715 if (*start > *end) 3716 return -EINVAL; 3717 3718 if (!*start && !*end && 3719 !damon_find_system_rams_range(start, end, addr_unit)) 3720 return -EINVAL; 3721 3722 addr_range.start = *start; 3723 addr_range.end = *end; 3724 return damon_set_regions(t, &addr_range, 1, min_region_sz); 3725 } 3726 3727 /* 3728 * damon_moving_sum() - Calculate an inferred moving sum value. 3729 * @mvsum: Inferred sum of the last @len_window values. 3730 * @nomvsum: Non-moving sum of the last discrete @len_window window values. 3731 * @len_window: The number of last values to take care of. 3732 * @new_value: New value that will be added to the pseudo moving sum. 3733 * 3734 * Moving sum (moving average * window size) is good for handling noise, but 3735 * the cost of keeping past values can be high for arbitrary window size. This 3736 * function implements a lightweight pseudo moving sum function that doesn't 3737 * keep the past window values. 3738 * 3739 * It simply assumes there was no noise in the past, and get the no-noise 3740 * assumed past value to drop from @nomvsum and @len_window. @nomvsum is a 3741 * non-moving sum of the last window. For example, if @len_window is 10 and we 3742 * have 25 values, @nomvsum is the sum of the 11th to 20th values of the 25 3743 * values. Hence, this function simply drops @nomvsum / @len_window from 3744 * given @mvsum and add @new_value. 3745 * 3746 * For example, if @len_window is 10 and @nomvsum is 50, the last 10 values for 3747 * the last window could be vary, e.g., 0, 10, 0, 10, 0, 10, 0, 0, 0, 20. For 3748 * calculating next moving sum with a new value, we should drop 0 from 50 and 3749 * add the new value. However, this function assumes it got value 5 for each 3750 * of the last ten times. Based on the assumption, when the next value is 3751 * measured, it drops the assumed past value, 5 from the current sum, and add 3752 * the new value to get the updated pseduo-moving average. 3753 * 3754 * This means the value could have errors, but the errors will be disappeared 3755 * for every @len_window aligned calls. For example, if @len_window is 10, the 3756 * pseudo moving sum with 11th value to 19th value would have an error. But 3757 * the sum with 20th value will not have the error. 3758 * 3759 * Return: Pseudo-moving average after getting the @new_value. 3760 */ 3761 static unsigned int damon_moving_sum(unsigned int mvsum, unsigned int nomvsum, 3762 unsigned int len_window, unsigned int new_value) 3763 { 3764 return mvsum - nomvsum / len_window + new_value; 3765 } 3766 3767 /** 3768 * damon_update_region_access_rate() - Update the access rate of a region. 3769 * @r: The DAMON region to update for its access check result. 3770 * @accessed: Whether the region has accessed during last sampling interval. 3771 * @attrs: The damon_attrs of the DAMON context. 3772 * 3773 * Update the access rate of a region with the region's last sampling interval 3774 * access check result. 3775 * 3776 * Usually this will be called by &damon_operations->check_accesses callback. 3777 */ 3778 void damon_update_region_access_rate(struct damon_region *r, bool accessed, 3779 struct damon_attrs *attrs) 3780 { 3781 unsigned int len_window = 1; 3782 3783 /* 3784 * sample_interval can be zero, but cannot be larger than 3785 * aggr_interval, owing to validation of damon_set_attrs(). 3786 */ 3787 if (attrs->sample_interval) 3788 len_window = damon_max_nr_accesses(attrs); 3789 r->nr_accesses_bp = damon_moving_sum(r->nr_accesses_bp, 3790 r->last_nr_accesses * 10000, len_window, 3791 accessed ? 10000 : 0); 3792 3793 if (accessed) 3794 r->nr_accesses++; 3795 } 3796 3797 /** 3798 * damon_initialized() - Return if DAMON is ready to be used. 3799 * 3800 * Return: true if DAMON is ready to be used, false otherwise. 3801 */ 3802 bool damon_initialized(void) 3803 { 3804 return damon_region_cache != NULL; 3805 } 3806 3807 static int __init damon_init(void) 3808 { 3809 damon_region_cache = KMEM_CACHE(damon_region, 0); 3810 if (unlikely(!damon_region_cache)) { 3811 pr_err("creating damon_region_cache fails\n"); 3812 return -ENOMEM; 3813 } 3814 3815 return 0; 3816 } 3817 3818 subsys_initcall(damon_init); 3819 3820 #include "tests/core-kunit.h" 3821