1 // SPDX-License-Identifier: GPL-2.0 2 /* 3 * Data Access Monitor 4 * 5 * Author: SeongJae Park <sjpark@amazon.de> 6 */ 7 8 #define pr_fmt(fmt) "damon: " fmt 9 10 #include <linux/damon.h> 11 #include <linux/delay.h> 12 #include <linux/kthread.h> 13 #include <linux/mm.h> 14 #include <linux/slab.h> 15 #include <linux/string.h> 16 17 #define CREATE_TRACE_POINTS 18 #include <trace/events/damon.h> 19 20 #ifdef CONFIG_DAMON_KUNIT_TEST 21 #undef DAMON_MIN_REGION 22 #define DAMON_MIN_REGION 1 23 #endif 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 mutex_lock(&damon_ops_lock); 78 /* Fail for already registered ops */ 79 if (__damon_is_registered_ops(ops->id)) { 80 err = -EINVAL; 81 goto out; 82 } 83 damon_registered_ops[ops->id] = *ops; 84 out: 85 mutex_unlock(&damon_ops_lock); 86 return err; 87 } 88 89 /** 90 * damon_select_ops() - Select a monitoring operations to use with the context. 91 * @ctx: monitoring context to use the operations. 92 * @id: id of the registered monitoring operations to select. 93 * 94 * This function finds registered monitoring operations set of @id and make 95 * @ctx to use it. 96 * 97 * Return: 0 on success, negative error code otherwise. 98 */ 99 int damon_select_ops(struct damon_ctx *ctx, enum damon_ops_id id) 100 { 101 int err = 0; 102 103 if (id >= NR_DAMON_OPS) 104 return -EINVAL; 105 106 mutex_lock(&damon_ops_lock); 107 if (!__damon_is_registered_ops(id)) 108 err = -EINVAL; 109 else 110 ctx->ops = damon_registered_ops[id]; 111 mutex_unlock(&damon_ops_lock); 112 return err; 113 } 114 115 /* 116 * Construct a damon_region struct 117 * 118 * Returns the pointer to the new struct if success, or NULL otherwise 119 */ 120 struct damon_region *damon_new_region(unsigned long start, unsigned long end) 121 { 122 struct damon_region *region; 123 124 region = kmem_cache_alloc(damon_region_cache, GFP_KERNEL); 125 if (!region) 126 return NULL; 127 128 region->ar.start = start; 129 region->ar.end = end; 130 region->nr_accesses = 0; 131 INIT_LIST_HEAD(®ion->list); 132 133 region->age = 0; 134 region->last_nr_accesses = 0; 135 136 return region; 137 } 138 139 void damon_add_region(struct damon_region *r, struct damon_target *t) 140 { 141 list_add_tail(&r->list, &t->regions_list); 142 t->nr_regions++; 143 } 144 145 static void damon_del_region(struct damon_region *r, struct damon_target *t) 146 { 147 list_del(&r->list); 148 t->nr_regions--; 149 } 150 151 static void damon_free_region(struct damon_region *r) 152 { 153 kmem_cache_free(damon_region_cache, r); 154 } 155 156 void damon_destroy_region(struct damon_region *r, struct damon_target *t) 157 { 158 damon_del_region(r, t); 159 damon_free_region(r); 160 } 161 162 /* 163 * Check whether a region is intersecting an address range 164 * 165 * Returns true if it is. 166 */ 167 static bool damon_intersect(struct damon_region *r, 168 struct damon_addr_range *re) 169 { 170 return !(r->ar.end <= re->start || re->end <= r->ar.start); 171 } 172 173 /* 174 * Fill holes in regions with new regions. 175 */ 176 static int damon_fill_regions_holes(struct damon_region *first, 177 struct damon_region *last, struct damon_target *t) 178 { 179 struct damon_region *r = first; 180 181 damon_for_each_region_from(r, t) { 182 struct damon_region *next, *newr; 183 184 if (r == last) 185 break; 186 next = damon_next_region(r); 187 if (r->ar.end != next->ar.start) { 188 newr = damon_new_region(r->ar.end, next->ar.start); 189 if (!newr) 190 return -ENOMEM; 191 damon_insert_region(newr, r, next, t); 192 } 193 } 194 return 0; 195 } 196 197 /* 198 * damon_set_regions() - Set regions of a target for given address ranges. 199 * @t: the given target. 200 * @ranges: array of new monitoring target ranges. 201 * @nr_ranges: length of @ranges. 202 * 203 * This function adds new regions to, or modify existing regions of a 204 * monitoring target to fit in specific ranges. 205 * 206 * Return: 0 if success, or negative error code otherwise. 207 */ 208 int damon_set_regions(struct damon_target *t, struct damon_addr_range *ranges, 209 unsigned int nr_ranges) 210 { 211 struct damon_region *r, *next; 212 unsigned int i; 213 int err; 214 215 /* Remove regions which are not in the new ranges */ 216 damon_for_each_region_safe(r, next, t) { 217 for (i = 0; i < nr_ranges; i++) { 218 if (damon_intersect(r, &ranges[i])) 219 break; 220 } 221 if (i == nr_ranges) 222 damon_destroy_region(r, t); 223 } 224 225 r = damon_first_region(t); 226 /* Add new regions or resize existing regions to fit in the ranges */ 227 for (i = 0; i < nr_ranges; i++) { 228 struct damon_region *first = NULL, *last, *newr; 229 struct damon_addr_range *range; 230 231 range = &ranges[i]; 232 /* Get the first/last regions intersecting with the range */ 233 damon_for_each_region_from(r, t) { 234 if (damon_intersect(r, range)) { 235 if (!first) 236 first = r; 237 last = r; 238 } 239 if (r->ar.start >= range->end) 240 break; 241 } 242 if (!first) { 243 /* no region intersects with this range */ 244 newr = damon_new_region( 245 ALIGN_DOWN(range->start, 246 DAMON_MIN_REGION), 247 ALIGN(range->end, DAMON_MIN_REGION)); 248 if (!newr) 249 return -ENOMEM; 250 damon_insert_region(newr, damon_prev_region(r), r, t); 251 } else { 252 /* resize intersecting regions to fit in this range */ 253 first->ar.start = ALIGN_DOWN(range->start, 254 DAMON_MIN_REGION); 255 last->ar.end = ALIGN(range->end, DAMON_MIN_REGION); 256 257 /* fill possible holes in the range */ 258 err = damon_fill_regions_holes(first, last, t); 259 if (err) 260 return err; 261 } 262 } 263 return 0; 264 } 265 266 /* initialize private fields of damos_quota and return the pointer */ 267 static struct damos_quota *damos_quota_init_priv(struct damos_quota *quota) 268 { 269 quota->total_charged_sz = 0; 270 quota->total_charged_ns = 0; 271 quota->esz = 0; 272 quota->charged_sz = 0; 273 quota->charged_from = 0; 274 quota->charge_target_from = NULL; 275 quota->charge_addr_from = 0; 276 return quota; 277 } 278 279 struct damos *damon_new_scheme(struct damos_access_pattern *pattern, 280 enum damos_action action, struct damos_quota *quota, 281 struct damos_watermarks *wmarks) 282 { 283 struct damos *scheme; 284 285 scheme = kmalloc(sizeof(*scheme), GFP_KERNEL); 286 if (!scheme) 287 return NULL; 288 scheme->pattern = *pattern; 289 scheme->action = action; 290 scheme->stat = (struct damos_stat){}; 291 INIT_LIST_HEAD(&scheme->list); 292 293 scheme->quota = *(damos_quota_init_priv(quota)); 294 295 scheme->wmarks = *wmarks; 296 scheme->wmarks.activated = true; 297 298 return scheme; 299 } 300 301 void damon_add_scheme(struct damon_ctx *ctx, struct damos *s) 302 { 303 list_add_tail(&s->list, &ctx->schemes); 304 } 305 306 static void damon_del_scheme(struct damos *s) 307 { 308 list_del(&s->list); 309 } 310 311 static void damon_free_scheme(struct damos *s) 312 { 313 kfree(s); 314 } 315 316 void damon_destroy_scheme(struct damos *s) 317 { 318 damon_del_scheme(s); 319 damon_free_scheme(s); 320 } 321 322 /* 323 * Construct a damon_target struct 324 * 325 * Returns the pointer to the new struct if success, or NULL otherwise 326 */ 327 struct damon_target *damon_new_target(void) 328 { 329 struct damon_target *t; 330 331 t = kmalloc(sizeof(*t), GFP_KERNEL); 332 if (!t) 333 return NULL; 334 335 t->pid = NULL; 336 t->nr_regions = 0; 337 INIT_LIST_HEAD(&t->regions_list); 338 INIT_LIST_HEAD(&t->list); 339 340 return t; 341 } 342 343 void damon_add_target(struct damon_ctx *ctx, struct damon_target *t) 344 { 345 list_add_tail(&t->list, &ctx->adaptive_targets); 346 } 347 348 bool damon_targets_empty(struct damon_ctx *ctx) 349 { 350 return list_empty(&ctx->adaptive_targets); 351 } 352 353 static void damon_del_target(struct damon_target *t) 354 { 355 list_del(&t->list); 356 } 357 358 void damon_free_target(struct damon_target *t) 359 { 360 struct damon_region *r, *next; 361 362 damon_for_each_region_safe(r, next, t) 363 damon_free_region(r); 364 kfree(t); 365 } 366 367 void damon_destroy_target(struct damon_target *t) 368 { 369 damon_del_target(t); 370 damon_free_target(t); 371 } 372 373 unsigned int damon_nr_regions(struct damon_target *t) 374 { 375 return t->nr_regions; 376 } 377 378 struct damon_ctx *damon_new_ctx(void) 379 { 380 struct damon_ctx *ctx; 381 382 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL); 383 if (!ctx) 384 return NULL; 385 386 ctx->attrs.sample_interval = 5 * 1000; 387 ctx->attrs.aggr_interval = 100 * 1000; 388 ctx->attrs.ops_update_interval = 60 * 1000 * 1000; 389 390 ktime_get_coarse_ts64(&ctx->last_aggregation); 391 ctx->last_ops_update = ctx->last_aggregation; 392 393 mutex_init(&ctx->kdamond_lock); 394 395 ctx->attrs.min_nr_regions = 10; 396 ctx->attrs.max_nr_regions = 1000; 397 398 INIT_LIST_HEAD(&ctx->adaptive_targets); 399 INIT_LIST_HEAD(&ctx->schemes); 400 401 return ctx; 402 } 403 404 static void damon_destroy_targets(struct damon_ctx *ctx) 405 { 406 struct damon_target *t, *next_t; 407 408 if (ctx->ops.cleanup) { 409 ctx->ops.cleanup(ctx); 410 return; 411 } 412 413 damon_for_each_target_safe(t, next_t, ctx) 414 damon_destroy_target(t); 415 } 416 417 void damon_destroy_ctx(struct damon_ctx *ctx) 418 { 419 struct damos *s, *next_s; 420 421 damon_destroy_targets(ctx); 422 423 damon_for_each_scheme_safe(s, next_s, ctx) 424 damon_destroy_scheme(s); 425 426 kfree(ctx); 427 } 428 429 /** 430 * damon_set_attrs() - Set attributes for the monitoring. 431 * @ctx: monitoring context 432 * @attrs: monitoring attributes 433 * 434 * This function should not be called while the kdamond is running. 435 * Every time interval is in micro-seconds. 436 * 437 * Return: 0 on success, negative error code otherwise. 438 */ 439 int damon_set_attrs(struct damon_ctx *ctx, struct damon_attrs *attrs) 440 { 441 if (attrs->min_nr_regions < 3) 442 return -EINVAL; 443 if (attrs->min_nr_regions > attrs->max_nr_regions) 444 return -EINVAL; 445 446 ctx->attrs = *attrs; 447 return 0; 448 } 449 450 /** 451 * damon_set_schemes() - Set data access monitoring based operation schemes. 452 * @ctx: monitoring context 453 * @schemes: array of the schemes 454 * @nr_schemes: number of entries in @schemes 455 * 456 * This function should not be called while the kdamond of the context is 457 * running. 458 */ 459 void damon_set_schemes(struct damon_ctx *ctx, struct damos **schemes, 460 ssize_t nr_schemes) 461 { 462 struct damos *s, *next; 463 ssize_t i; 464 465 damon_for_each_scheme_safe(s, next, ctx) 466 damon_destroy_scheme(s); 467 for (i = 0; i < nr_schemes; i++) 468 damon_add_scheme(ctx, schemes[i]); 469 } 470 471 /** 472 * damon_nr_running_ctxs() - Return number of currently running contexts. 473 */ 474 int damon_nr_running_ctxs(void) 475 { 476 int nr_ctxs; 477 478 mutex_lock(&damon_lock); 479 nr_ctxs = nr_running_ctxs; 480 mutex_unlock(&damon_lock); 481 482 return nr_ctxs; 483 } 484 485 /* Returns the size upper limit for each monitoring region */ 486 static unsigned long damon_region_sz_limit(struct damon_ctx *ctx) 487 { 488 struct damon_target *t; 489 struct damon_region *r; 490 unsigned long sz = 0; 491 492 damon_for_each_target(t, ctx) { 493 damon_for_each_region(r, t) 494 sz += r->ar.end - r->ar.start; 495 } 496 497 if (ctx->attrs.min_nr_regions) 498 sz /= ctx->attrs.min_nr_regions; 499 if (sz < DAMON_MIN_REGION) 500 sz = DAMON_MIN_REGION; 501 502 return sz; 503 } 504 505 static int kdamond_fn(void *data); 506 507 /* 508 * __damon_start() - Starts monitoring with given context. 509 * @ctx: monitoring context 510 * 511 * This function should be called while damon_lock is hold. 512 * 513 * Return: 0 on success, negative error code otherwise. 514 */ 515 static int __damon_start(struct damon_ctx *ctx) 516 { 517 int err = -EBUSY; 518 519 mutex_lock(&ctx->kdamond_lock); 520 if (!ctx->kdamond) { 521 err = 0; 522 ctx->kdamond = kthread_run(kdamond_fn, ctx, "kdamond.%d", 523 nr_running_ctxs); 524 if (IS_ERR(ctx->kdamond)) { 525 err = PTR_ERR(ctx->kdamond); 526 ctx->kdamond = NULL; 527 } 528 } 529 mutex_unlock(&ctx->kdamond_lock); 530 531 return err; 532 } 533 534 /** 535 * damon_start() - Starts the monitorings for a given group of contexts. 536 * @ctxs: an array of the pointers for contexts to start monitoring 537 * @nr_ctxs: size of @ctxs 538 * @exclusive: exclusiveness of this contexts group 539 * 540 * This function starts a group of monitoring threads for a group of monitoring 541 * contexts. One thread per each context is created and run in parallel. The 542 * caller should handle synchronization between the threads by itself. If 543 * @exclusive is true and a group of threads that created by other 544 * 'damon_start()' call is currently running, this function does nothing but 545 * returns -EBUSY. 546 * 547 * Return: 0 on success, negative error code otherwise. 548 */ 549 int damon_start(struct damon_ctx **ctxs, int nr_ctxs, bool exclusive) 550 { 551 int i; 552 int err = 0; 553 554 mutex_lock(&damon_lock); 555 if ((exclusive && nr_running_ctxs) || 556 (!exclusive && running_exclusive_ctxs)) { 557 mutex_unlock(&damon_lock); 558 return -EBUSY; 559 } 560 561 for (i = 0; i < nr_ctxs; i++) { 562 err = __damon_start(ctxs[i]); 563 if (err) 564 break; 565 nr_running_ctxs++; 566 } 567 if (exclusive && nr_running_ctxs) 568 running_exclusive_ctxs = true; 569 mutex_unlock(&damon_lock); 570 571 return err; 572 } 573 574 /* 575 * __damon_stop() - Stops monitoring of a given context. 576 * @ctx: monitoring context 577 * 578 * Return: 0 on success, negative error code otherwise. 579 */ 580 static int __damon_stop(struct damon_ctx *ctx) 581 { 582 struct task_struct *tsk; 583 584 mutex_lock(&ctx->kdamond_lock); 585 tsk = ctx->kdamond; 586 if (tsk) { 587 get_task_struct(tsk); 588 mutex_unlock(&ctx->kdamond_lock); 589 kthread_stop(tsk); 590 put_task_struct(tsk); 591 return 0; 592 } 593 mutex_unlock(&ctx->kdamond_lock); 594 595 return -EPERM; 596 } 597 598 /** 599 * damon_stop() - Stops the monitorings for a given group of contexts. 600 * @ctxs: an array of the pointers for contexts to stop monitoring 601 * @nr_ctxs: size of @ctxs 602 * 603 * Return: 0 on success, negative error code otherwise. 604 */ 605 int damon_stop(struct damon_ctx **ctxs, int nr_ctxs) 606 { 607 int i, err = 0; 608 609 for (i = 0; i < nr_ctxs; i++) { 610 /* nr_running_ctxs is decremented in kdamond_fn */ 611 err = __damon_stop(ctxs[i]); 612 if (err) 613 break; 614 } 615 return err; 616 } 617 618 /* 619 * damon_check_reset_time_interval() - Check if a time interval is elapsed. 620 * @baseline: the time to check whether the interval has elapsed since 621 * @interval: the time interval (microseconds) 622 * 623 * See whether the given time interval has passed since the given baseline 624 * time. If so, it also updates the baseline to current time for next check. 625 * 626 * Return: true if the time interval has passed, or false otherwise. 627 */ 628 static bool damon_check_reset_time_interval(struct timespec64 *baseline, 629 unsigned long interval) 630 { 631 struct timespec64 now; 632 633 ktime_get_coarse_ts64(&now); 634 if ((timespec64_to_ns(&now) - timespec64_to_ns(baseline)) < 635 interval * 1000) 636 return false; 637 *baseline = now; 638 return true; 639 } 640 641 /* 642 * Check whether it is time to flush the aggregated information 643 */ 644 static bool kdamond_aggregate_interval_passed(struct damon_ctx *ctx) 645 { 646 return damon_check_reset_time_interval(&ctx->last_aggregation, 647 ctx->attrs.aggr_interval); 648 } 649 650 /* 651 * Reset the aggregated monitoring results ('nr_accesses' of each region). 652 */ 653 static void kdamond_reset_aggregated(struct damon_ctx *c) 654 { 655 struct damon_target *t; 656 unsigned int ti = 0; /* target's index */ 657 658 damon_for_each_target(t, c) { 659 struct damon_region *r; 660 661 damon_for_each_region(r, t) { 662 trace_damon_aggregated(t, ti, r, damon_nr_regions(t)); 663 r->last_nr_accesses = r->nr_accesses; 664 r->nr_accesses = 0; 665 } 666 ti++; 667 } 668 } 669 670 static void damon_split_region_at(struct damon_target *t, 671 struct damon_region *r, unsigned long sz_r); 672 673 static bool __damos_valid_target(struct damon_region *r, struct damos *s) 674 { 675 unsigned long sz; 676 677 sz = r->ar.end - r->ar.start; 678 return s->pattern.min_sz_region <= sz && 679 sz <= s->pattern.max_sz_region && 680 s->pattern.min_nr_accesses <= r->nr_accesses && 681 r->nr_accesses <= s->pattern.max_nr_accesses && 682 s->pattern.min_age_region <= r->age && 683 r->age <= s->pattern.max_age_region; 684 } 685 686 static bool damos_valid_target(struct damon_ctx *c, struct damon_target *t, 687 struct damon_region *r, struct damos *s) 688 { 689 bool ret = __damos_valid_target(r, s); 690 691 if (!ret || !s->quota.esz || !c->ops.get_scheme_score) 692 return ret; 693 694 return c->ops.get_scheme_score(c, t, r, s) >= s->quota.min_score; 695 } 696 697 static void damon_do_apply_schemes(struct damon_ctx *c, 698 struct damon_target *t, 699 struct damon_region *r) 700 { 701 struct damos *s; 702 703 damon_for_each_scheme(s, c) { 704 struct damos_quota *quota = &s->quota; 705 unsigned long sz = r->ar.end - r->ar.start; 706 struct timespec64 begin, end; 707 unsigned long sz_applied = 0; 708 709 if (!s->wmarks.activated) 710 continue; 711 712 /* Check the quota */ 713 if (quota->esz && quota->charged_sz >= quota->esz) 714 continue; 715 716 /* Skip previously charged regions */ 717 if (quota->charge_target_from) { 718 if (t != quota->charge_target_from) 719 continue; 720 if (r == damon_last_region(t)) { 721 quota->charge_target_from = NULL; 722 quota->charge_addr_from = 0; 723 continue; 724 } 725 if (quota->charge_addr_from && 726 r->ar.end <= quota->charge_addr_from) 727 continue; 728 729 if (quota->charge_addr_from && r->ar.start < 730 quota->charge_addr_from) { 731 sz = ALIGN_DOWN(quota->charge_addr_from - 732 r->ar.start, DAMON_MIN_REGION); 733 if (!sz) { 734 if (r->ar.end - r->ar.start <= 735 DAMON_MIN_REGION) 736 continue; 737 sz = DAMON_MIN_REGION; 738 } 739 damon_split_region_at(t, r, sz); 740 r = damon_next_region(r); 741 sz = r->ar.end - r->ar.start; 742 } 743 quota->charge_target_from = NULL; 744 quota->charge_addr_from = 0; 745 } 746 747 if (!damos_valid_target(c, t, r, s)) 748 continue; 749 750 /* Apply the scheme */ 751 if (c->ops.apply_scheme) { 752 if (quota->esz && 753 quota->charged_sz + sz > quota->esz) { 754 sz = ALIGN_DOWN(quota->esz - quota->charged_sz, 755 DAMON_MIN_REGION); 756 if (!sz) 757 goto update_stat; 758 damon_split_region_at(t, r, sz); 759 } 760 ktime_get_coarse_ts64(&begin); 761 sz_applied = c->ops.apply_scheme(c, t, r, s); 762 ktime_get_coarse_ts64(&end); 763 quota->total_charged_ns += timespec64_to_ns(&end) - 764 timespec64_to_ns(&begin); 765 quota->charged_sz += sz; 766 if (quota->esz && quota->charged_sz >= quota->esz) { 767 quota->charge_target_from = t; 768 quota->charge_addr_from = r->ar.end + 1; 769 } 770 } 771 if (s->action != DAMOS_STAT) 772 r->age = 0; 773 774 update_stat: 775 s->stat.nr_tried++; 776 s->stat.sz_tried += sz; 777 if (sz_applied) 778 s->stat.nr_applied++; 779 s->stat.sz_applied += sz_applied; 780 } 781 } 782 783 /* Shouldn't be called if quota->ms and quota->sz are zero */ 784 static void damos_set_effective_quota(struct damos_quota *quota) 785 { 786 unsigned long throughput; 787 unsigned long esz; 788 789 if (!quota->ms) { 790 quota->esz = quota->sz; 791 return; 792 } 793 794 if (quota->total_charged_ns) 795 throughput = quota->total_charged_sz * 1000000 / 796 quota->total_charged_ns; 797 else 798 throughput = PAGE_SIZE * 1024; 799 esz = throughput * quota->ms; 800 801 if (quota->sz && quota->sz < esz) 802 esz = quota->sz; 803 quota->esz = esz; 804 } 805 806 static void kdamond_apply_schemes(struct damon_ctx *c) 807 { 808 struct damon_target *t; 809 struct damon_region *r, *next_r; 810 struct damos *s; 811 812 damon_for_each_scheme(s, c) { 813 struct damos_quota *quota = &s->quota; 814 unsigned long cumulated_sz; 815 unsigned int score, max_score = 0; 816 817 if (!s->wmarks.activated) 818 continue; 819 820 if (!quota->ms && !quota->sz) 821 continue; 822 823 /* New charge window starts */ 824 if (time_after_eq(jiffies, quota->charged_from + 825 msecs_to_jiffies( 826 quota->reset_interval))) { 827 if (quota->esz && quota->charged_sz >= quota->esz) 828 s->stat.qt_exceeds++; 829 quota->total_charged_sz += quota->charged_sz; 830 quota->charged_from = jiffies; 831 quota->charged_sz = 0; 832 damos_set_effective_quota(quota); 833 } 834 835 if (!c->ops.get_scheme_score) 836 continue; 837 838 /* Fill up the score histogram */ 839 memset(quota->histogram, 0, sizeof(quota->histogram)); 840 damon_for_each_target(t, c) { 841 damon_for_each_region(r, t) { 842 if (!__damos_valid_target(r, s)) 843 continue; 844 score = c->ops.get_scheme_score( 845 c, t, r, s); 846 quota->histogram[score] += 847 r->ar.end - r->ar.start; 848 if (score > max_score) 849 max_score = score; 850 } 851 } 852 853 /* Set the min score limit */ 854 for (cumulated_sz = 0, score = max_score; ; score--) { 855 cumulated_sz += quota->histogram[score]; 856 if (cumulated_sz >= quota->esz || !score) 857 break; 858 } 859 quota->min_score = score; 860 } 861 862 damon_for_each_target(t, c) { 863 damon_for_each_region_safe(r, next_r, t) 864 damon_do_apply_schemes(c, t, r); 865 } 866 } 867 868 static inline unsigned long sz_damon_region(struct damon_region *r) 869 { 870 return r->ar.end - r->ar.start; 871 } 872 873 /* 874 * Merge two adjacent regions into one region 875 */ 876 static void damon_merge_two_regions(struct damon_target *t, 877 struct damon_region *l, struct damon_region *r) 878 { 879 unsigned long sz_l = sz_damon_region(l), sz_r = sz_damon_region(r); 880 881 l->nr_accesses = (l->nr_accesses * sz_l + r->nr_accesses * sz_r) / 882 (sz_l + sz_r); 883 l->age = (l->age * sz_l + r->age * sz_r) / (sz_l + sz_r); 884 l->ar.end = r->ar.end; 885 damon_destroy_region(r, t); 886 } 887 888 /* 889 * Merge adjacent regions having similar access frequencies 890 * 891 * t target affected by this merge operation 892 * thres '->nr_accesses' diff threshold for the merge 893 * sz_limit size upper limit of each region 894 */ 895 static void damon_merge_regions_of(struct damon_target *t, unsigned int thres, 896 unsigned long sz_limit) 897 { 898 struct damon_region *r, *prev = NULL, *next; 899 900 damon_for_each_region_safe(r, next, t) { 901 if (abs(r->nr_accesses - r->last_nr_accesses) > thres) 902 r->age = 0; 903 else 904 r->age++; 905 906 if (prev && prev->ar.end == r->ar.start && 907 abs(prev->nr_accesses - r->nr_accesses) <= thres && 908 sz_damon_region(prev) + sz_damon_region(r) <= sz_limit) 909 damon_merge_two_regions(t, prev, r); 910 else 911 prev = r; 912 } 913 } 914 915 /* 916 * Merge adjacent regions having similar access frequencies 917 * 918 * threshold '->nr_accesses' diff threshold for the merge 919 * sz_limit size upper limit of each region 920 * 921 * This function merges monitoring target regions which are adjacent and their 922 * access frequencies are similar. This is for minimizing the monitoring 923 * overhead under the dynamically changeable access pattern. If a merge was 924 * unnecessarily made, later 'kdamond_split_regions()' will revert it. 925 */ 926 static void kdamond_merge_regions(struct damon_ctx *c, unsigned int threshold, 927 unsigned long sz_limit) 928 { 929 struct damon_target *t; 930 931 damon_for_each_target(t, c) 932 damon_merge_regions_of(t, threshold, sz_limit); 933 } 934 935 /* 936 * Split a region in two 937 * 938 * r the region to be split 939 * sz_r size of the first sub-region that will be made 940 */ 941 static void damon_split_region_at(struct damon_target *t, 942 struct damon_region *r, unsigned long sz_r) 943 { 944 struct damon_region *new; 945 946 new = damon_new_region(r->ar.start + sz_r, r->ar.end); 947 if (!new) 948 return; 949 950 r->ar.end = new->ar.start; 951 952 new->age = r->age; 953 new->last_nr_accesses = r->last_nr_accesses; 954 955 damon_insert_region(new, r, damon_next_region(r), t); 956 } 957 958 /* Split every region in the given target into 'nr_subs' regions */ 959 static void damon_split_regions_of(struct damon_target *t, int nr_subs) 960 { 961 struct damon_region *r, *next; 962 unsigned long sz_region, sz_sub = 0; 963 int i; 964 965 damon_for_each_region_safe(r, next, t) { 966 sz_region = r->ar.end - r->ar.start; 967 968 for (i = 0; i < nr_subs - 1 && 969 sz_region > 2 * DAMON_MIN_REGION; i++) { 970 /* 971 * Randomly select size of left sub-region to be at 972 * least 10 percent and at most 90% of original region 973 */ 974 sz_sub = ALIGN_DOWN(damon_rand(1, 10) * 975 sz_region / 10, DAMON_MIN_REGION); 976 /* Do not allow blank region */ 977 if (sz_sub == 0 || sz_sub >= sz_region) 978 continue; 979 980 damon_split_region_at(t, r, sz_sub); 981 sz_region = sz_sub; 982 } 983 } 984 } 985 986 /* 987 * Split every target region into randomly-sized small regions 988 * 989 * This function splits every target region into random-sized small regions if 990 * current total number of the regions is equal or smaller than half of the 991 * user-specified maximum number of regions. This is for maximizing the 992 * monitoring accuracy under the dynamically changeable access patterns. If a 993 * split was unnecessarily made, later 'kdamond_merge_regions()' will revert 994 * it. 995 */ 996 static void kdamond_split_regions(struct damon_ctx *ctx) 997 { 998 struct damon_target *t; 999 unsigned int nr_regions = 0; 1000 static unsigned int last_nr_regions; 1001 int nr_subregions = 2; 1002 1003 damon_for_each_target(t, ctx) 1004 nr_regions += damon_nr_regions(t); 1005 1006 if (nr_regions > ctx->attrs.max_nr_regions / 2) 1007 return; 1008 1009 /* Maybe the middle of the region has different access frequency */ 1010 if (last_nr_regions == nr_regions && 1011 nr_regions < ctx->attrs.max_nr_regions / 3) 1012 nr_subregions = 3; 1013 1014 damon_for_each_target(t, ctx) 1015 damon_split_regions_of(t, nr_subregions); 1016 1017 last_nr_regions = nr_regions; 1018 } 1019 1020 /* 1021 * Check whether it is time to check and apply the operations-related data 1022 * structures. 1023 * 1024 * Returns true if it is. 1025 */ 1026 static bool kdamond_need_update_operations(struct damon_ctx *ctx) 1027 { 1028 return damon_check_reset_time_interval(&ctx->last_ops_update, 1029 ctx->attrs.ops_update_interval); 1030 } 1031 1032 /* 1033 * Check whether current monitoring should be stopped 1034 * 1035 * The monitoring is stopped when either the user requested to stop, or all 1036 * monitoring targets are invalid. 1037 * 1038 * Returns true if need to stop current monitoring. 1039 */ 1040 static bool kdamond_need_stop(struct damon_ctx *ctx) 1041 { 1042 struct damon_target *t; 1043 1044 if (kthread_should_stop()) 1045 return true; 1046 1047 if (!ctx->ops.target_valid) 1048 return false; 1049 1050 damon_for_each_target(t, ctx) { 1051 if (ctx->ops.target_valid(t)) 1052 return false; 1053 } 1054 1055 return true; 1056 } 1057 1058 static unsigned long damos_wmark_metric_value(enum damos_wmark_metric metric) 1059 { 1060 struct sysinfo i; 1061 1062 switch (metric) { 1063 case DAMOS_WMARK_FREE_MEM_RATE: 1064 si_meminfo(&i); 1065 return i.freeram * 1000 / i.totalram; 1066 default: 1067 break; 1068 } 1069 return -EINVAL; 1070 } 1071 1072 /* 1073 * Returns zero if the scheme is active. Else, returns time to wait for next 1074 * watermark check in micro-seconds. 1075 */ 1076 static unsigned long damos_wmark_wait_us(struct damos *scheme) 1077 { 1078 unsigned long metric; 1079 1080 if (scheme->wmarks.metric == DAMOS_WMARK_NONE) 1081 return 0; 1082 1083 metric = damos_wmark_metric_value(scheme->wmarks.metric); 1084 /* higher than high watermark or lower than low watermark */ 1085 if (metric > scheme->wmarks.high || scheme->wmarks.low > metric) { 1086 if (scheme->wmarks.activated) 1087 pr_debug("deactivate a scheme (%d) for %s wmark\n", 1088 scheme->action, 1089 metric > scheme->wmarks.high ? 1090 "high" : "low"); 1091 scheme->wmarks.activated = false; 1092 return scheme->wmarks.interval; 1093 } 1094 1095 /* inactive and higher than middle watermark */ 1096 if ((scheme->wmarks.high >= metric && metric >= scheme->wmarks.mid) && 1097 !scheme->wmarks.activated) 1098 return scheme->wmarks.interval; 1099 1100 if (!scheme->wmarks.activated) 1101 pr_debug("activate a scheme (%d)\n", scheme->action); 1102 scheme->wmarks.activated = true; 1103 return 0; 1104 } 1105 1106 static void kdamond_usleep(unsigned long usecs) 1107 { 1108 /* See Documentation/timers/timers-howto.rst for the thresholds */ 1109 if (usecs > 20 * USEC_PER_MSEC) 1110 schedule_timeout_idle(usecs_to_jiffies(usecs)); 1111 else 1112 usleep_idle_range(usecs, usecs + 1); 1113 } 1114 1115 /* Returns negative error code if it's not activated but should return */ 1116 static int kdamond_wait_activation(struct damon_ctx *ctx) 1117 { 1118 struct damos *s; 1119 unsigned long wait_time; 1120 unsigned long min_wait_time = 0; 1121 bool init_wait_time = false; 1122 1123 while (!kdamond_need_stop(ctx)) { 1124 damon_for_each_scheme(s, ctx) { 1125 wait_time = damos_wmark_wait_us(s); 1126 if (!init_wait_time || wait_time < min_wait_time) { 1127 init_wait_time = true; 1128 min_wait_time = wait_time; 1129 } 1130 } 1131 if (!min_wait_time) 1132 return 0; 1133 1134 kdamond_usleep(min_wait_time); 1135 1136 if (ctx->callback.after_wmarks_check && 1137 ctx->callback.after_wmarks_check(ctx)) 1138 break; 1139 } 1140 return -EBUSY; 1141 } 1142 1143 /* 1144 * The monitoring daemon that runs as a kernel thread 1145 */ 1146 static int kdamond_fn(void *data) 1147 { 1148 struct damon_ctx *ctx = data; 1149 struct damon_target *t; 1150 struct damon_region *r, *next; 1151 unsigned int max_nr_accesses = 0; 1152 unsigned long sz_limit = 0; 1153 1154 pr_debug("kdamond (%d) starts\n", current->pid); 1155 1156 if (ctx->ops.init) 1157 ctx->ops.init(ctx); 1158 if (ctx->callback.before_start && ctx->callback.before_start(ctx)) 1159 goto done; 1160 1161 sz_limit = damon_region_sz_limit(ctx); 1162 1163 while (!kdamond_need_stop(ctx)) { 1164 if (kdamond_wait_activation(ctx)) 1165 break; 1166 1167 if (ctx->ops.prepare_access_checks) 1168 ctx->ops.prepare_access_checks(ctx); 1169 if (ctx->callback.after_sampling && 1170 ctx->callback.after_sampling(ctx)) 1171 break; 1172 1173 kdamond_usleep(ctx->attrs.sample_interval); 1174 1175 if (ctx->ops.check_accesses) 1176 max_nr_accesses = ctx->ops.check_accesses(ctx); 1177 1178 if (kdamond_aggregate_interval_passed(ctx)) { 1179 kdamond_merge_regions(ctx, 1180 max_nr_accesses / 10, 1181 sz_limit); 1182 if (ctx->callback.after_aggregation && 1183 ctx->callback.after_aggregation(ctx)) 1184 break; 1185 kdamond_apply_schemes(ctx); 1186 kdamond_reset_aggregated(ctx); 1187 kdamond_split_regions(ctx); 1188 if (ctx->ops.reset_aggregated) 1189 ctx->ops.reset_aggregated(ctx); 1190 } 1191 1192 if (kdamond_need_update_operations(ctx)) { 1193 if (ctx->ops.update) 1194 ctx->ops.update(ctx); 1195 sz_limit = damon_region_sz_limit(ctx); 1196 } 1197 } 1198 done: 1199 damon_for_each_target(t, ctx) { 1200 damon_for_each_region_safe(r, next, t) 1201 damon_destroy_region(r, t); 1202 } 1203 1204 if (ctx->callback.before_terminate) 1205 ctx->callback.before_terminate(ctx); 1206 if (ctx->ops.cleanup) 1207 ctx->ops.cleanup(ctx); 1208 1209 pr_debug("kdamond (%d) finishes\n", current->pid); 1210 mutex_lock(&ctx->kdamond_lock); 1211 ctx->kdamond = NULL; 1212 mutex_unlock(&ctx->kdamond_lock); 1213 1214 mutex_lock(&damon_lock); 1215 nr_running_ctxs--; 1216 if (!nr_running_ctxs && running_exclusive_ctxs) 1217 running_exclusive_ctxs = false; 1218 mutex_unlock(&damon_lock); 1219 1220 return 0; 1221 } 1222 1223 /* 1224 * struct damon_system_ram_region - System RAM resource address region of 1225 * [@start, @end). 1226 * @start: Start address of the region (inclusive). 1227 * @end: End address of the region (exclusive). 1228 */ 1229 struct damon_system_ram_region { 1230 unsigned long start; 1231 unsigned long end; 1232 }; 1233 1234 static int walk_system_ram(struct resource *res, void *arg) 1235 { 1236 struct damon_system_ram_region *a = arg; 1237 1238 if (a->end - a->start < resource_size(res)) { 1239 a->start = res->start; 1240 a->end = res->end; 1241 } 1242 return 0; 1243 } 1244 1245 /* 1246 * Find biggest 'System RAM' resource and store its start and end address in 1247 * @start and @end, respectively. If no System RAM is found, returns false. 1248 */ 1249 static bool damon_find_biggest_system_ram(unsigned long *start, 1250 unsigned long *end) 1251 1252 { 1253 struct damon_system_ram_region arg = {}; 1254 1255 walk_system_ram_res(0, ULONG_MAX, &arg, walk_system_ram); 1256 if (arg.end <= arg.start) 1257 return false; 1258 1259 *start = arg.start; 1260 *end = arg.end; 1261 return true; 1262 } 1263 1264 /** 1265 * damon_set_region_biggest_system_ram_default() - Set the region of the given 1266 * monitoring target as requested, or biggest 'System RAM'. 1267 * @t: The monitoring target to set the region. 1268 * @start: The pointer to the start address of the region. 1269 * @end: The pointer to the end address of the region. 1270 * 1271 * This function sets the region of @t as requested by @start and @end. If the 1272 * values of @start and @end are zero, however, this function finds the biggest 1273 * 'System RAM' resource and sets the region to cover the resource. In the 1274 * latter case, this function saves the start and end addresses of the resource 1275 * in @start and @end, respectively. 1276 * 1277 * Return: 0 on success, negative error code otherwise. 1278 */ 1279 int damon_set_region_biggest_system_ram_default(struct damon_target *t, 1280 unsigned long *start, unsigned long *end) 1281 { 1282 struct damon_addr_range addr_range; 1283 1284 if (*start > *end) 1285 return -EINVAL; 1286 1287 if (!*start && !*end && 1288 !damon_find_biggest_system_ram(start, end)) 1289 return -EINVAL; 1290 1291 addr_range.start = *start; 1292 addr_range.end = *end; 1293 return damon_set_regions(t, &addr_range, 1); 1294 } 1295 1296 static int __init damon_init(void) 1297 { 1298 damon_region_cache = KMEM_CACHE(damon_region, 0); 1299 if (unlikely(!damon_region_cache)) { 1300 pr_err("creating damon_region_cache fails\n"); 1301 return -ENOMEM; 1302 } 1303 1304 return 0; 1305 } 1306 1307 subsys_initcall(damon_init); 1308 1309 #include "core-test.h" 1310