You need to sign in or sign up before continuing.
core.c 43.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
// SPDX-License-Identifier: GPL-2.0
/*
 * Data Access Monitor
 *
 * Author: SeongJae Park <sjpark@amazon.de>
 */

#define pr_fmt(fmt) "damon: " fmt

#include <linux/damon.h>
#include <linux/delay.h>
#include <linux/kthread.h>
13
#include <linux/mm.h>
14
#include <linux/slab.h>
15
#include <linux/string.h>
16

SeongJae Park's avatar
SeongJae Park committed
17 18 19
#define CREATE_TRACE_POINTS
#include <trace/events/damon.h>

SeongJae Park's avatar
SeongJae Park committed
20 21 22 23 24
#ifdef CONFIG_DAMON_KUNIT_TEST
#undef DAMON_MIN_REGION
#define DAMON_MIN_REGION 1
#endif

25 26
static DEFINE_MUTEX(damon_lock);
static int nr_running_ctxs;
27
static bool running_exclusive_ctxs;
28

29 30 31
static DEFINE_MUTEX(damon_ops_lock);
static struct damon_operations damon_registered_ops[NR_DAMON_OPS];

32 33
static struct kmem_cache *damon_region_cache __ro_after_init;

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 38 39 40 41 42 43
{
	struct damon_operations empty_ops = {};

	if (!memcmp(&empty_ops, &damon_registered_ops[id], sizeof(empty_ops)))
		return false;
	return true;
}

44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
/**
 * damon_is_registered_ops() - Check if a given damon_operations is registered.
 * @id:	Id of the damon_operations to check if registered.
 *
 * Return: true if the ops is set, false otherwise.
 */
bool damon_is_registered_ops(enum damon_ops_id id)
{
	bool registered;

	if (id >= NR_DAMON_OPS)
		return false;
	mutex_lock(&damon_ops_lock);
	registered = __damon_is_registered_ops(id);
	mutex_unlock(&damon_ops_lock);
	return registered;
}

62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
/**
 * damon_register_ops() - Register a monitoring operations set to DAMON.
 * @ops:	monitoring operations set to register.
 *
 * This function registers a monitoring operations set of valid &struct
 * damon_operations->id so that others can find and use them later.
 *
 * Return: 0 on success, negative error code otherwise.
 */
int damon_register_ops(struct damon_operations *ops)
{
	int err = 0;

	if (ops->id >= NR_DAMON_OPS)
		return -EINVAL;
	mutex_lock(&damon_ops_lock);
	/* Fail for already registered ops */
79
	if (__damon_is_registered_ops(ops->id)) {
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
		err = -EINVAL;
		goto out;
	}
	damon_registered_ops[ops->id] = *ops;
out:
	mutex_unlock(&damon_ops_lock);
	return err;
}

/**
 * damon_select_ops() - Select a monitoring operations to use with the context.
 * @ctx:	monitoring context to use the operations.
 * @id:		id of the registered monitoring operations to select.
 *
 * This function finds registered monitoring operations set of @id and make
 * @ctx to use it.
 *
 * Return: 0 on success, negative error code otherwise.
 */
int damon_select_ops(struct damon_ctx *ctx, enum damon_ops_id id)
{
	int err = 0;

	if (id >= NR_DAMON_OPS)
		return -EINVAL;

	mutex_lock(&damon_ops_lock);
107
	if (!__damon_is_registered_ops(id))
108 109 110 111 112 113 114
		err = -EINVAL;
	else
		ctx->ops = damon_registered_ops[id];
	mutex_unlock(&damon_ops_lock);
	return err;
}

115 116 117 118 119 120 121 122 123
/*
 * Construct a damon_region struct
 *
 * Returns the pointer to the new struct if success, or NULL otherwise
 */
struct damon_region *damon_new_region(unsigned long start, unsigned long end)
{
	struct damon_region *region;

124
	region = kmem_cache_alloc(damon_region_cache, GFP_KERNEL);
125 126 127 128 129 130
	if (!region)
		return NULL;

	region->ar.start = start;
	region->ar.end = end;
	region->nr_accesses = 0;
131
	region->nr_accesses_bp = 0;
132 133
	INIT_LIST_HEAD(&region->list);

134 135 136
	region->age = 0;
	region->last_nr_accesses = 0;

137 138 139 140 141 142
	return region;
}

void damon_add_region(struct damon_region *r, struct damon_target *t)
{
	list_add_tail(&r->list, &t->regions_list);
143
	t->nr_regions++;
144 145
}

146
static void damon_del_region(struct damon_region *r, struct damon_target *t)
147 148
{
	list_del(&r->list);
149
	t->nr_regions--;
150 151 152 153
}

static void damon_free_region(struct damon_region *r)
{
154
	kmem_cache_free(damon_region_cache, r);
155 156
}

157
void damon_destroy_region(struct damon_region *r, struct damon_target *t)
158
{
159
	damon_del_region(r, t);
160 161 162
	damon_free_region(r);
}

163 164 165 166 167 168 169 170 171 172 173
/*
 * Check whether a region is intersecting an address range
 *
 * Returns true if it is.
 */
static bool damon_intersect(struct damon_region *r,
		struct damon_addr_range *re)
{
	return !(r->ar.end <= re->start || re->end <= r->ar.start);
}

174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
/*
 * Fill holes in regions with new regions.
 */
static int damon_fill_regions_holes(struct damon_region *first,
		struct damon_region *last, struct damon_target *t)
{
	struct damon_region *r = first;

	damon_for_each_region_from(r, t) {
		struct damon_region *next, *newr;

		if (r == last)
			break;
		next = damon_next_region(r);
		if (r->ar.end != next->ar.start) {
			newr = damon_new_region(r->ar.end, next->ar.start);
			if (!newr)
				return -ENOMEM;
			damon_insert_region(newr, r, next, t);
		}
	}
	return 0;
}

198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
/*
 * damon_set_regions() - Set regions of a target for given address ranges.
 * @t:		the given target.
 * @ranges:	array of new monitoring target ranges.
 * @nr_ranges:	length of @ranges.
 *
 * This function adds new regions to, or modify existing regions of a
 * monitoring target to fit in specific ranges.
 *
 * Return: 0 if success, or negative error code otherwise.
 */
int damon_set_regions(struct damon_target *t, struct damon_addr_range *ranges,
		unsigned int nr_ranges)
{
	struct damon_region *r, *next;
	unsigned int i;
214
	int err;
215 216 217 218 219 220 221 222 223 224 225

	/* Remove regions which are not in the new ranges */
	damon_for_each_region_safe(r, next, t) {
		for (i = 0; i < nr_ranges; i++) {
			if (damon_intersect(r, &ranges[i]))
				break;
		}
		if (i == nr_ranges)
			damon_destroy_region(r, t);
	}

226
	r = damon_first_region(t);
227 228 229 230 231 232 233
	/* Add new regions or resize existing regions to fit in the ranges */
	for (i = 0; i < nr_ranges; i++) {
		struct damon_region *first = NULL, *last, *newr;
		struct damon_addr_range *range;

		range = &ranges[i];
		/* Get the first/last regions intersecting with the range */
234
		damon_for_each_region_from(r, t) {
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
			if (damon_intersect(r, range)) {
				if (!first)
					first = r;
				last = r;
			}
			if (r->ar.start >= range->end)
				break;
		}
		if (!first) {
			/* no region intersects with this range */
			newr = damon_new_region(
					ALIGN_DOWN(range->start,
						DAMON_MIN_REGION),
					ALIGN(range->end, DAMON_MIN_REGION));
			if (!newr)
				return -ENOMEM;
			damon_insert_region(newr, damon_prev_region(r), r, t);
		} else {
			/* resize intersecting regions to fit in this range */
			first->ar.start = ALIGN_DOWN(range->start,
					DAMON_MIN_REGION);
			last->ar.end = ALIGN(range->end, DAMON_MIN_REGION);
257 258 259 260 261

			/* fill possible holes in the range */
			err = damon_fill_regions_holes(first, last, t);
			if (err)
				return err;
262 263 264 265 266
		}
	}
	return 0;
}

267 268 269 270 271 272 273 274 275 276
struct damos_filter *damos_new_filter(enum damos_filter_type type,
		bool matching)
{
	struct damos_filter *filter;

	filter = kmalloc(sizeof(*filter), GFP_KERNEL);
	if (!filter)
		return NULL;
	filter->type = type;
	filter->matching = matching;
277
	INIT_LIST_HEAD(&filter->list);
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
	return filter;
}

void damos_add_filter(struct damos *s, struct damos_filter *f)
{
	list_add_tail(&f->list, &s->filters);
}

static void damos_del_filter(struct damos_filter *f)
{
	list_del(&f->list);
}

static void damos_free_filter(struct damos_filter *f)
{
	kfree(f);
}

void damos_destroy_filter(struct damos_filter *f)
{
	damos_del_filter(f);
	damos_free_filter(f);
}

302 303 304 305 306 307 308 309 310 311 312 313 314
/* initialize private fields of damos_quota and return the pointer */
static struct damos_quota *damos_quota_init_priv(struct damos_quota *quota)
{
	quota->total_charged_sz = 0;
	quota->total_charged_ns = 0;
	quota->esz = 0;
	quota->charged_sz = 0;
	quota->charged_from = 0;
	quota->charge_target_from = NULL;
	quota->charge_addr_from = 0;
	return quota;
}

315
struct damos *damon_new_scheme(struct damos_access_pattern *pattern,
316 317 318
			enum damos_action action,
			unsigned long apply_interval_us,
			struct damos_quota *quota,
319
			struct damos_watermarks *wmarks)
320 321 322 323 324 325
{
	struct damos *scheme;

	scheme = kmalloc(sizeof(*scheme), GFP_KERNEL);
	if (!scheme)
		return NULL;
326
	scheme->pattern = *pattern;
327
	scheme->action = action;
328 329 330 331 332 333 334
	scheme->apply_interval_us = apply_interval_us;
	/*
	 * next_apply_sis will be set when kdamond starts.  While kdamond is
	 * running, it will also updated when it is added to the DAMON context,
	 * or damon_attrs are updated.
	 */
	scheme->next_apply_sis = 0;
335
	INIT_LIST_HEAD(&scheme->filters);
336
	scheme->stat = (struct damos_stat){};
337 338
	INIT_LIST_HEAD(&scheme->list);

339
	scheme->quota = *(damos_quota_init_priv(quota));
340

341
	scheme->wmarks = *wmarks;
342 343
	scheme->wmarks.activated = true;

344 345 346
	return scheme;
}

347 348 349 350 351 352 353 354 355 356 357
static void damos_set_next_apply_sis(struct damos *s, struct damon_ctx *ctx)
{
	unsigned long sample_interval = ctx->attrs.sample_interval ?
		ctx->attrs.sample_interval : 1;
	unsigned long apply_interval = s->apply_interval_us ?
		s->apply_interval_us : ctx->attrs.aggr_interval;

	s->next_apply_sis = ctx->passed_sample_intervals +
		apply_interval / sample_interval;
}

358 359 360
void damon_add_scheme(struct damon_ctx *ctx, struct damos *s)
{
	list_add_tail(&s->list, &ctx->schemes);
361
	damos_set_next_apply_sis(s, ctx);
362 363 364 365 366 367 368 369 370 371 372 373 374 375
}

static void damon_del_scheme(struct damos *s)
{
	list_del(&s->list);
}

static void damon_free_scheme(struct damos *s)
{
	kfree(s);
}

void damon_destroy_scheme(struct damos *s)
{
376 377 378 379
	struct damos_filter *f, *next;

	damos_for_each_filter_safe(f, next, s)
		damos_destroy_filter(f);
380 381 382 383
	damon_del_scheme(s);
	damon_free_scheme(s);
}

384 385 386 387 388
/*
 * Construct a damon_target struct
 *
 * Returns the pointer to the new struct if success, or NULL otherwise
 */
389
struct damon_target *damon_new_target(void)
390 391 392 393 394 395 396
{
	struct damon_target *t;

	t = kmalloc(sizeof(*t), GFP_KERNEL);
	if (!t)
		return NULL;

397
	t->pid = NULL;
398
	t->nr_regions = 0;
399
	INIT_LIST_HEAD(&t->regions_list);
400
	INIT_LIST_HEAD(&t->list);
401 402 403 404 405 406

	return t;
}

void damon_add_target(struct damon_ctx *ctx, struct damon_target *t)
{
407
	list_add_tail(&t->list, &ctx->adaptive_targets);
408 409
}

410 411 412 413 414
bool damon_targets_empty(struct damon_ctx *ctx)
{
	return list_empty(&ctx->adaptive_targets);
}

415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
static void damon_del_target(struct damon_target *t)
{
	list_del(&t->list);
}

void damon_free_target(struct damon_target *t)
{
	struct damon_region *r, *next;

	damon_for_each_region_safe(r, next, t)
		damon_free_region(r);
	kfree(t);
}

void damon_destroy_target(struct damon_target *t)
{
	damon_del_target(t);
	damon_free_target(t);
}

435 436 437 438 439
unsigned int damon_nr_regions(struct damon_target *t)
{
	return t->nr_regions;
}

440 441 442 443 444 445 446 447
struct damon_ctx *damon_new_ctx(void)
{
	struct damon_ctx *ctx;

	ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
	if (!ctx)
		return NULL;

448 449 450
	ctx->attrs.sample_interval = 5 * 1000;
	ctx->attrs.aggr_interval = 100 * 1000;
	ctx->attrs.ops_update_interval = 60 * 1000 * 1000;
451

452 453 454 455
	ctx->passed_sample_intervals = 0;
	/* These will be set from kdamond_init_intervals_sis() */
	ctx->next_aggregation_sis = 0;
	ctx->next_ops_update_sis = 0;
456 457 458

	mutex_init(&ctx->kdamond_lock);

459 460
	ctx->attrs.min_nr_regions = 10;
	ctx->attrs.max_nr_regions = 1000;
461 462

	INIT_LIST_HEAD(&ctx->adaptive_targets);
463
	INIT_LIST_HEAD(&ctx->schemes);
464 465 466 467

	return ctx;
}

468
static void damon_destroy_targets(struct damon_ctx *ctx)
469
{
470 471
	struct damon_target *t, *next_t;

472 473
	if (ctx->ops.cleanup) {
		ctx->ops.cleanup(ctx);
474 475 476 477 478 479 480 481 482
		return;
	}

	damon_for_each_target_safe(t, next_t, ctx)
		damon_destroy_target(t);
}

void damon_destroy_ctx(struct damon_ctx *ctx)
{
483 484
	struct damos *s, *next_s;

485
	damon_destroy_targets(ctx);
486 487 488 489

	damon_for_each_scheme_safe(s, next_s, ctx)
		damon_destroy_scheme(s);

490 491 492
	kfree(ctx);
}

493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
static unsigned int damon_age_for_new_attrs(unsigned int age,
		struct damon_attrs *old_attrs, struct damon_attrs *new_attrs)
{
	return age * old_attrs->aggr_interval / new_attrs->aggr_interval;
}

/* convert access ratio in bp (per 10,000) to nr_accesses */
static unsigned int damon_accesses_bp_to_nr_accesses(
		unsigned int accesses_bp, struct damon_attrs *attrs)
{
	unsigned int max_nr_accesses =
		attrs->aggr_interval / attrs->sample_interval;

	return accesses_bp * max_nr_accesses / 10000;
}

/* convert nr_accesses to access ratio in bp (per 10,000) */
static unsigned int damon_nr_accesses_to_accesses_bp(
		unsigned int nr_accesses, struct damon_attrs *attrs)
{
	unsigned int max_nr_accesses =
		attrs->aggr_interval / attrs->sample_interval;

	return nr_accesses * 10000 / max_nr_accesses;
}

static unsigned int damon_nr_accesses_for_new_attrs(unsigned int nr_accesses,
		struct damon_attrs *old_attrs, struct damon_attrs *new_attrs)
{
	return damon_accesses_bp_to_nr_accesses(
			damon_nr_accesses_to_accesses_bp(
				nr_accesses, old_attrs),
			new_attrs);
}

static void damon_update_monitoring_result(struct damon_region *r,
		struct damon_attrs *old_attrs, struct damon_attrs *new_attrs)
{
	r->nr_accesses = damon_nr_accesses_for_new_attrs(r->nr_accesses,
			old_attrs, new_attrs);
533
	r->nr_accesses_bp = r->nr_accesses * 10000;
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
	r->age = damon_age_for_new_attrs(r->age, old_attrs, new_attrs);
}

/*
 * region->nr_accesses is the number of sampling intervals in the last
 * aggregation interval that access to the region has found, and region->age is
 * the number of aggregation intervals that its access pattern has maintained.
 * For the reason, the real meaning of the two fields depend on current
 * sampling interval and aggregation interval.  This function updates
 * ->nr_accesses and ->age of given damon_ctx's regions for new damon_attrs.
 */
static void damon_update_monitoring_results(struct damon_ctx *ctx,
		struct damon_attrs *new_attrs)
{
	struct damon_attrs *old_attrs = &ctx->attrs;
	struct damon_target *t;
	struct damon_region *r;

	/* if any interval is zero, simply forgive conversion */
	if (!old_attrs->sample_interval || !old_attrs->aggr_interval ||
			!new_attrs->sample_interval ||
			!new_attrs->aggr_interval)
		return;

	damon_for_each_target(t, ctx)
		damon_for_each_region(r, t)
			damon_update_monitoring_result(
					r, old_attrs, new_attrs);
}

564 565 566
/**
 * damon_set_attrs() - Set attributes for the monitoring.
 * @ctx:		monitoring context
567
 * @attrs:		monitoring attributes
568
 *
569 570 571 572 573
 * This function should be called while the kdamond is not running, or an
 * access check results aggregation is not ongoing (e.g., from
 * &struct damon_callback->after_aggregation or
 * &struct damon_callback->after_wmarks_check callbacks).
 *
574 575 576 577
 * Every time interval is in micro-seconds.
 *
 * Return: 0 on success, negative error code otherwise.
 */
578
int damon_set_attrs(struct damon_ctx *ctx, struct damon_attrs *attrs)
579
{
580 581
	unsigned long sample_interval = attrs->sample_interval ?
		attrs->sample_interval : 1;
582
	struct damos *s;
583

584
	if (attrs->min_nr_regions < 3)
585
		return -EINVAL;
586
	if (attrs->min_nr_regions > attrs->max_nr_regions)
587
		return -EINVAL;
588 589
	if (attrs->sample_interval > attrs->aggr_interval)
		return -EINVAL;
590

591 592 593 594 595
	ctx->next_aggregation_sis = ctx->passed_sample_intervals +
		attrs->aggr_interval / sample_interval;
	ctx->next_ops_update_sis = ctx->passed_sample_intervals +
		attrs->ops_update_interval / sample_interval;

596
	damon_update_monitoring_results(ctx, attrs);
597
	ctx->attrs = *attrs;
598 599 600 601

	damon_for_each_scheme(s, ctx)
		damos_set_next_apply_sis(s, ctx);

602 603 604
	return 0;
}

605 606 607 608 609 610 611 612 613
/**
 * damon_set_schemes() - Set data access monitoring based operation schemes.
 * @ctx:	monitoring context
 * @schemes:	array of the schemes
 * @nr_schemes:	number of entries in @schemes
 *
 * This function should not be called while the kdamond of the context is
 * running.
 */
614
void damon_set_schemes(struct damon_ctx *ctx, struct damos **schemes,
615 616 617 618 619 620 621 622 623 624 625
			ssize_t nr_schemes)
{
	struct damos *s, *next;
	ssize_t i;

	damon_for_each_scheme_safe(s, next, ctx)
		damon_destroy_scheme(s);
	for (i = 0; i < nr_schemes; i++)
		damon_add_scheme(ctx, schemes[i]);
}

626 627 628 629 630 631 632 633 634 635 636 637 638 639
/**
 * damon_nr_running_ctxs() - Return number of currently running contexts.
 */
int damon_nr_running_ctxs(void)
{
	int nr_ctxs;

	mutex_lock(&damon_lock);
	nr_ctxs = nr_running_ctxs;
	mutex_unlock(&damon_lock);

	return nr_ctxs;
}

640 641 642 643 644 645 646 647 648
/* Returns the size upper limit for each monitoring region */
static unsigned long damon_region_sz_limit(struct damon_ctx *ctx)
{
	struct damon_target *t;
	struct damon_region *r;
	unsigned long sz = 0;

	damon_for_each_target(t, ctx) {
		damon_for_each_region(r, t)
649
			sz += damon_sz_region(r);
650 651
	}

652 653
	if (ctx->attrs.min_nr_regions)
		sz /= ctx->attrs.min_nr_regions;
654 655 656 657 658 659
	if (sz < DAMON_MIN_REGION)
		sz = DAMON_MIN_REGION;

	return sz;
}

660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
static int kdamond_fn(void *data);

/*
 * __damon_start() - Starts monitoring with given context.
 * @ctx:	monitoring context
 *
 * This function should be called while damon_lock is hold.
 *
 * Return: 0 on success, negative error code otherwise.
 */
static int __damon_start(struct damon_ctx *ctx)
{
	int err = -EBUSY;

	mutex_lock(&ctx->kdamond_lock);
	if (!ctx->kdamond) {
		err = 0;
		ctx->kdamond = kthread_run(kdamond_fn, ctx, "kdamond.%d",
				nr_running_ctxs);
		if (IS_ERR(ctx->kdamond)) {
			err = PTR_ERR(ctx->kdamond);
681
			ctx->kdamond = NULL;
682 683 684 685 686 687 688 689 690 691 692
		}
	}
	mutex_unlock(&ctx->kdamond_lock);

	return err;
}

/**
 * damon_start() - Starts the monitorings for a given group of contexts.
 * @ctxs:	an array of the pointers for contexts to start monitoring
 * @nr_ctxs:	size of @ctxs
693
 * @exclusive:	exclusiveness of this contexts group
694 695 696
 *
 * This function starts a group of monitoring threads for a group of monitoring
 * contexts.  One thread per each context is created and run in parallel.  The
697 698 699 700
 * caller should handle synchronization between the threads by itself.  If
 * @exclusive is true and a group of threads that created by other
 * 'damon_start()' call is currently running, this function does nothing but
 * returns -EBUSY.
701 702 703
 *
 * Return: 0 on success, negative error code otherwise.
 */
704
int damon_start(struct damon_ctx **ctxs, int nr_ctxs, bool exclusive)
705 706 707 708 709
{
	int i;
	int err = 0;

	mutex_lock(&damon_lock);
710 711
	if ((exclusive && nr_running_ctxs) ||
			(!exclusive && running_exclusive_ctxs)) {
712 713 714 715 716 717 718 719 720 721
		mutex_unlock(&damon_lock);
		return -EBUSY;
	}

	for (i = 0; i < nr_ctxs; i++) {
		err = __damon_start(ctxs[i]);
		if (err)
			break;
		nr_running_ctxs++;
	}
722 723
	if (exclusive && nr_running_ctxs)
		running_exclusive_ctxs = true;
724 725 726 727 728 729
	mutex_unlock(&damon_lock);

	return err;
}

/*
730
 * __damon_stop() - Stops monitoring of a given context.
731 732 733 734 735 736
 * @ctx:	monitoring context
 *
 * Return: 0 on success, negative error code otherwise.
 */
static int __damon_stop(struct damon_ctx *ctx)
{
737 738
	struct task_struct *tsk;

739
	mutex_lock(&ctx->kdamond_lock);
740 741 742
	tsk = ctx->kdamond;
	if (tsk) {
		get_task_struct(tsk);
743
		mutex_unlock(&ctx->kdamond_lock);
744 745
		kthread_stop(tsk);
		put_task_struct(tsk);
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
		return 0;
	}
	mutex_unlock(&ctx->kdamond_lock);

	return -EPERM;
}

/**
 * damon_stop() - Stops the monitorings for a given group of contexts.
 * @ctxs:	an array of the pointers for contexts to stop monitoring
 * @nr_ctxs:	size of @ctxs
 *
 * Return: 0 on success, negative error code otherwise.
 */
int damon_stop(struct damon_ctx **ctxs, int nr_ctxs)
{
	int i, err = 0;

	for (i = 0; i < nr_ctxs; i++) {
		/* nr_running_ctxs is decremented in kdamond_fn */
		err = __damon_stop(ctxs[i]);
		if (err)
768
			break;
769 770 771 772
	}
	return err;
}

773 774 775 776 777 778
/*
 * Reset the aggregated monitoring results ('nr_accesses' of each region).
 */
static void kdamond_reset_aggregated(struct damon_ctx *c)
{
	struct damon_target *t;
779
	unsigned int ti = 0;	/* target's index */
780 781 782 783

	damon_for_each_target(t, c) {
		struct damon_region *r;

SeongJae Park's avatar
SeongJae Park committed
784
		damon_for_each_region(r, t) {
785
			trace_damon_aggregated(ti, r, damon_nr_regions(t));
786
			r->last_nr_accesses = r->nr_accesses;
787
			r->nr_accesses = 0;
SeongJae Park's avatar
SeongJae Park committed
788
		}
789
		ti++;
790 791 792
	}
}

793 794
static void damon_split_region_at(struct damon_target *t,
				  struct damon_region *r, unsigned long sz_r);
795

796 797 798
static bool __damos_valid_target(struct damon_region *r, struct damos *s)
{
	unsigned long sz;
799
	unsigned int nr_accesses = r->nr_accesses_bp / 10000;
800

801
	sz = damon_sz_region(r);
802 803
	return s->pattern.min_sz_region <= sz &&
		sz <= s->pattern.max_sz_region &&
804 805
		s->pattern.min_nr_accesses <= nr_accesses &&
		nr_accesses <= s->pattern.max_nr_accesses &&
806 807
		s->pattern.min_age_region <= r->age &&
		r->age <= s->pattern.max_age_region;
808 809 810 811 812 813 814
}

static bool damos_valid_target(struct damon_ctx *c, struct damon_target *t,
		struct damon_region *r, struct damos *s)
{
	bool ret = __damos_valid_target(r, s);

815
	if (!ret || !s->quota.esz || !c->ops.get_scheme_score)
816 817
		return ret;

818
	return c->ops.get_scheme_score(c, t, r, s) >= s->quota.min_score;
819 820
}

821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
/*
 * damos_skip_charged_region() - Check if the given region or starting part of
 * it is already charged for the DAMOS quota.
 * @t:	The target of the region.
 * @rp:	The pointer to the region.
 * @s:	The scheme to be applied.
 *
 * If a quota of a scheme has exceeded in a quota charge window, the scheme's
 * action would applied to only a part of the target access pattern fulfilling
 * regions.  To avoid applying the scheme action to only already applied
 * regions, DAMON skips applying the scheme action to the regions that charged
 * in the previous charge window.
 *
 * This function checks if a given region should be skipped or not for the
 * reason.  If only the starting part of the region has previously charged,
 * this function splits the region into two so that the second one covers the
 * area that not charged in the previous charge widnow and saves the second
 * region in *rp and returns false, so that the caller can apply DAMON action
 * to the second one.
 *
 * Return: true if the region should be entirely skipped, false otherwise.
 */
static bool damos_skip_charged_region(struct damon_target *t,
		struct damon_region **rp, struct damos *s)
{
	struct damon_region *r = *rp;
	struct damos_quota *quota = &s->quota;
	unsigned long sz_to_skip;

	/* Skip previously charged regions */
	if (quota->charge_target_from) {
		if (t != quota->charge_target_from)
			return true;
		if (r == damon_last_region(t)) {
			quota->charge_target_from = NULL;
			quota->charge_addr_from = 0;
			return true;
		}
		if (quota->charge_addr_from &&
				r->ar.end <= quota->charge_addr_from)
			return true;

		if (quota->charge_addr_from && r->ar.start <
				quota->charge_addr_from) {
			sz_to_skip = ALIGN_DOWN(quota->charge_addr_from -
					r->ar.start, DAMON_MIN_REGION);
			if (!sz_to_skip) {
				if (damon_sz_region(r) <= DAMON_MIN_REGION)
					return true;
				sz_to_skip = DAMON_MIN_REGION;
			}
			damon_split_region_at(t, r, sz_to_skip);
			r = damon_next_region(r);
			*rp = r;
		}
		quota->charge_target_from = NULL;
		quota->charge_addr_from = 0;
	}
	return false;
}

882 883 884 885 886 887 888 889 890 891
static void damos_update_stat(struct damos *s,
		unsigned long sz_tried, unsigned long sz_applied)
{
	s->stat.nr_tried++;
	s->stat.sz_tried += sz_tried;
	if (sz_applied)
		s->stat.nr_applied++;
	s->stat.sz_applied += sz_applied;
}

892 893
static bool __damos_filter_out(struct damon_ctx *ctx, struct damon_target *t,
		struct damon_region *r, struct damos_filter *filter)
894 895
{
	bool matched = false;
896 897
	struct damon_target *ti;
	int target_idx = 0;
898 899 900
	unsigned long start, end;

	switch (filter->type) {
901 902 903 904 905 906 907 908
	case DAMOS_FILTER_TYPE_TARGET:
		damon_for_each_target(ti, ctx) {
			if (ti == t)
				break;
			target_idx++;
		}
		matched = target_idx == filter->target_idx;
		break;
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939
	case DAMOS_FILTER_TYPE_ADDR:
		start = ALIGN_DOWN(filter->addr_range.start, DAMON_MIN_REGION);
		end = ALIGN_DOWN(filter->addr_range.end, DAMON_MIN_REGION);

		/* inside the range */
		if (start <= r->ar.start && r->ar.end <= end) {
			matched = true;
			break;
		}
		/* outside of the range */
		if (r->ar.end <= start || end <= r->ar.start) {
			matched = false;
			break;
		}
		/* start before the range and overlap */
		if (r->ar.start < start) {
			damon_split_region_at(t, r, start - r->ar.start);
			matched = false;
			break;
		}
		/* start inside the range */
		damon_split_region_at(t, r, end - r->ar.start);
		matched = true;
		break;
	default:
		break;
	}

	return matched == filter->matching;
}

940 941
static bool damos_filter_out(struct damon_ctx *ctx, struct damon_target *t,
		struct damon_region *r, struct damos *s)
942 943 944 945
{
	struct damos_filter *filter;

	damos_for_each_filter(filter, s) {
946
		if (__damos_filter_out(ctx, t, r, filter))
947 948 949 950 951
			return true;
	}
	return false;
}

952 953 954 955 956 957 958
static void damos_apply_scheme(struct damon_ctx *c, struct damon_target *t,
		struct damon_region *r, struct damos *s)
{
	struct damos_quota *quota = &s->quota;
	unsigned long sz = damon_sz_region(r);
	struct timespec64 begin, end;
	unsigned long sz_applied = 0;
959
	int err = 0;
960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
	/*
	 * We plan to support multiple context per kdamond, as DAMON sysfs
	 * implies with 'nr_contexts' file.  Nevertheless, only single context
	 * per kdamond is supported for now.  So, we can simply use '0' context
	 * index here.
	 */
	unsigned int cidx = 0;
	struct damos *siter;		/* schemes iterator */
	unsigned int sidx = 0;
	struct damon_target *titer;	/* targets iterator */
	unsigned int tidx = 0;
	bool do_trace = false;

	/* get indices for trace_damos_before_apply() */
	if (trace_damos_before_apply_enabled()) {
		damon_for_each_scheme(siter, c) {
			if (siter == s)
				break;
			sidx++;
		}
		damon_for_each_target(titer, c) {
			if (titer == t)
				break;
			tidx++;
		}
		do_trace = true;
	}
987 988 989 990 991 992 993 994 995

	if (c->ops.apply_scheme) {
		if (quota->esz && quota->charged_sz + sz > quota->esz) {
			sz = ALIGN_DOWN(quota->esz - quota->charged_sz,
					DAMON_MIN_REGION);
			if (!sz)
				goto update_stat;
			damon_split_region_at(t, r, sz);
		}
996
		if (damos_filter_out(c, t, r, s))
997
			return;
998
		ktime_get_coarse_ts64(&begin);
999 1000
		if (c->callback.before_damos_apply)
			err = c->callback.before_damos_apply(c, t, r, s);
1001 1002 1003
		if (!err) {
			trace_damos_before_apply(cidx, sidx, tidx, r,
					damon_nr_regions(t), do_trace);
1004
			sz_applied = c->ops.apply_scheme(c, t, r, s);
1005
		}
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
		ktime_get_coarse_ts64(&end);
		quota->total_charged_ns += timespec64_to_ns(&end) -
			timespec64_to_ns(&begin);
		quota->charged_sz += sz;
		if (quota->esz && quota->charged_sz >= quota->esz) {
			quota->charge_target_from = t;
			quota->charge_addr_from = r->ar.end + 1;
		}
	}
	if (s->action != DAMOS_STAT)
		r->age = 0;

update_stat:
1019
	damos_update_stat(s, sz, sz_applied);
1020 1021
}

1022 1023 1024 1025 1026 1027 1028
static void damon_do_apply_schemes(struct damon_ctx *c,
				   struct damon_target *t,
				   struct damon_region *r)
{
	struct damos *s;

	damon_for_each_scheme(s, c) {
1029 1030
		struct damos_quota *quota = &s->quota;

1031 1032 1033
		if (!s->wmarks.activated)
			continue;

1034
		/* Check the quota */
1035
		if (quota->esz && quota->charged_sz >= quota->esz)
1036 1037
			continue;

1038 1039
		if (damos_skip_charged_region(t, &r, s))
			continue;
1040

1041
		if (!damos_valid_target(c, t, r, s))
1042
			continue;
1043

1044
		damos_apply_scheme(c, t, r, s);
1045 1046 1047
	}
}

1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
/* Shouldn't be called if quota->ms and quota->sz are zero */
static void damos_set_effective_quota(struct damos_quota *quota)
{
	unsigned long throughput;
	unsigned long esz;

	if (!quota->ms) {
		quota->esz = quota->sz;
		return;
	}

	if (quota->total_charged_ns)
		throughput = quota->total_charged_sz * 1000000 /
			quota->total_charged_ns;
	else
		throughput = PAGE_SIZE * 1024;
	esz = throughput * quota->ms;

	if (quota->sz && quota->sz < esz)
		esz = quota->sz;
	quota->esz = esz;
}

1071
static void damos_adjust_quota(struct damon_ctx *c, struct damos *s)
1072
{
1073
	struct damos_quota *quota = &s->quota;
1074
	struct damon_target *t;
1075 1076 1077
	struct damon_region *r;
	unsigned long cumulated_sz;
	unsigned int score, max_score = 0;
1078

1079 1080
	if (!quota->ms && !quota->sz)
		return;
1081

1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
	/* New charge window starts */
	if (time_after_eq(jiffies, quota->charged_from +
				msecs_to_jiffies(quota->reset_interval))) {
		if (quota->esz && quota->charged_sz >= quota->esz)
			s->stat.qt_exceeds++;
		quota->total_charged_sz += quota->charged_sz;
		quota->charged_from = jiffies;
		quota->charged_sz = 0;
		damos_set_effective_quota(quota);
	}
1092

1093 1094
	if (!c->ops.get_scheme_score)
		return;
1095

1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
	/* Fill up the score histogram */
	memset(quota->histogram, 0, sizeof(quota->histogram));
	damon_for_each_target(t, c) {
		damon_for_each_region(r, t) {
			if (!__damos_valid_target(r, s))
				continue;
			score = c->ops.get_scheme_score(c, t, r, s);
			quota->histogram[score] += damon_sz_region(r);
			if (score > max_score)
				max_score = score;
1106
		}
1107
	}
1108

1109 1110 1111 1112 1113 1114 1115 1116
	/* Set the min score limit */
	for (cumulated_sz = 0, score = max_score; ; score--) {
		cumulated_sz += quota->histogram[score];
		if (cumulated_sz >= quota->esz || !score)
			break;
	}
	quota->min_score = score;
}
1117

1118 1119 1120 1121 1122
static void kdamond_apply_schemes(struct damon_ctx *c)
{
	struct damon_target *t;
	struct damon_region *r, *next_r;
	struct damos *s;
1123 1124 1125
	unsigned long sample_interval = c->attrs.sample_interval ?
		c->attrs.sample_interval : 1;
	bool has_schemes_to_apply = false;
1126

1127
	damon_for_each_scheme(s, c) {
1128 1129 1130 1131 1132 1133 1134
		if (c->passed_sample_intervals != s->next_apply_sis)
			continue;

		s->next_apply_sis +=
			(s->apply_interval_us ? s->apply_interval_us :
			 c->attrs.aggr_interval) / sample_interval;

1135 1136 1137
		if (!s->wmarks.activated)
			continue;

1138 1139
		has_schemes_to_apply = true;

1140
		damos_adjust_quota(c, s);
1141
	}
1142

1143 1144 1145
	if (!has_schemes_to_apply)
		return;

1146
	damon_for_each_target(t, c) {
1147
		damon_for_each_region_safe(r, next_r, t)
1148 1149 1150 1151
			damon_do_apply_schemes(c, t, r);
	}
}

1152 1153 1154 1155 1156 1157
/*
 * Merge two adjacent regions into one region
 */
static void damon_merge_two_regions(struct damon_target *t,
		struct damon_region *l, struct damon_region *r)
{
1158
	unsigned long sz_l = damon_sz_region(l), sz_r = damon_sz_region(r);
1159 1160 1161

	l->nr_accesses = (l->nr_accesses * sz_l + r->nr_accesses * sz_r) /
			(sz_l + sz_r);
1162
	l->nr_accesses_bp = l->nr_accesses * 10000;
1163
	l->age = (l->age * sz_l + r->age * sz_r) / (sz_l + sz_r);
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
	l->ar.end = r->ar.end;
	damon_destroy_region(r, t);
}

/*
 * Merge adjacent regions having similar access frequencies
 *
 * t		target affected by this merge operation
 * thres	'->nr_accesses' diff threshold for the merge
 * sz_limit	size upper limit of each region
 */
static void damon_merge_regions_of(struct damon_target *t, unsigned int thres,
				   unsigned long sz_limit)
{
	struct damon_region *r, *prev = NULL, *next;

	damon_for_each_region_safe(r, next, t) {
1181
		if (abs(r->nr_accesses - r->last_nr_accesses) > thres)
1182 1183 1184 1185
			r->age = 0;
		else
			r->age++;

1186
		if (prev && prev->ar.end == r->ar.start &&
1187
		    abs(prev->nr_accesses - r->nr_accesses) <= thres &&
1188
		    damon_sz_region(prev) + damon_sz_region(r) <= sz_limit)
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
			damon_merge_two_regions(t, prev, r);
		else
			prev = r;
	}
}

/*
 * Merge adjacent regions having similar access frequencies
 *
 * threshold	'->nr_accesses' diff threshold for the merge
 * sz_limit	size upper limit of each region
 *
 * This function merges monitoring target regions which are adjacent and their
 * access frequencies are similar.  This is for minimizing the monitoring
 * overhead under the dynamically changeable access pattern.  If a merge was
 * unnecessarily made, later 'kdamond_split_regions()' will revert it.
 */
static void kdamond_merge_regions(struct damon_ctx *c, unsigned int threshold,
				  unsigned long sz_limit)
{
	struct damon_target *t;

	damon_for_each_target(t, c)
		damon_merge_regions_of(t, threshold, sz_limit);
}

/*
 * Split a region in two
 *
 * r		the region to be split
 * sz_r		size of the first sub-region that will be made
 */
1221 1222
static void damon_split_region_at(struct damon_target *t,
				  struct damon_region *r, unsigned long sz_r)
1223 1224 1225 1226 1227 1228 1229 1230 1231
{
	struct damon_region *new;

	new = damon_new_region(r->ar.start + sz_r, r->ar.end);
	if (!new)
		return;

	r->ar.end = new->ar.start;

1232 1233
	new->age = r->age;
	new->last_nr_accesses = r->last_nr_accesses;
1234
	new->nr_accesses_bp = r->nr_accesses_bp;
1235

1236 1237 1238 1239
	damon_insert_region(new, r, damon_next_region(r), t);
}

/* Split every region in the given target into 'nr_subs' regions */
1240
static void damon_split_regions_of(struct damon_target *t, int nr_subs)
1241 1242 1243 1244 1245 1246
{
	struct damon_region *r, *next;
	unsigned long sz_region, sz_sub = 0;
	int i;

	damon_for_each_region_safe(r, next, t) {
1247
		sz_region = damon_sz_region(r);
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260

		for (i = 0; i < nr_subs - 1 &&
				sz_region > 2 * DAMON_MIN_REGION; i++) {
			/*
			 * Randomly select size of left sub-region to be at
			 * least 10 percent and at most 90% of original region
			 */
			sz_sub = ALIGN_DOWN(damon_rand(1, 10) *
					sz_region / 10, DAMON_MIN_REGION);
			/* Do not allow blank region */
			if (sz_sub == 0 || sz_sub >= sz_region)
				continue;

1261
			damon_split_region_at(t, r, sz_sub);
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
			sz_region = sz_sub;
		}
	}
}

/*
 * Split every target region into randomly-sized small regions
 *
 * This function splits every target region into random-sized small regions if
 * current total number of the regions is equal or smaller than half of the
 * user-specified maximum number of regions.  This is for maximizing the
 * monitoring accuracy under the dynamically changeable access patterns.  If a
 * split was unnecessarily made, later 'kdamond_merge_regions()' will revert
 * it.
 */
static void kdamond_split_regions(struct damon_ctx *ctx)
{
	struct damon_target *t;
	unsigned int nr_regions = 0;
	static unsigned int last_nr_regions;
	int nr_subregions = 2;

	damon_for_each_target(t, ctx)
		nr_regions += damon_nr_regions(t);

1287
	if (nr_regions > ctx->attrs.max_nr_regions / 2)
1288 1289 1290 1291
		return;

	/* Maybe the middle of the region has different access frequency */
	if (last_nr_regions == nr_regions &&
1292
			nr_regions < ctx->attrs.max_nr_regions / 3)
1293 1294 1295
		nr_subregions = 3;

	damon_for_each_target(t, ctx)
1296
		damon_split_regions_of(t, nr_subregions);
1297 1298 1299 1300

	last_nr_regions = nr_regions;
}

1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
/*
 * Check whether current monitoring should be stopped
 *
 * The monitoring is stopped when either the user requested to stop, or all
 * monitoring targets are invalid.
 *
 * Returns true if need to stop current monitoring.
 */
static bool kdamond_need_stop(struct damon_ctx *ctx)
{
1311
	struct damon_target *t;
1312

1313
	if (kthread_should_stop())
1314 1315
		return true;

1316
	if (!ctx->ops.target_valid)
1317 1318
		return false;

1319
	damon_for_each_target(t, ctx) {
1320
		if (ctx->ops.target_valid(t))
1321 1322 1323 1324
			return false;
	}

	return true;
1325 1326
}

1327 1328 1329 1330
static unsigned long damos_wmark_metric_value(enum damos_wmark_metric metric)
{
	switch (metric) {
	case DAMOS_WMARK_FREE_MEM_RATE:
1331 1332
		return global_zone_page_state(NR_FREE_PAGES) * 1000 /
		       totalram_pages();
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
	default:
		break;
	}
	return -EINVAL;
}

/*
 * Returns zero if the scheme is active.  Else, returns time to wait for next
 * watermark check in micro-seconds.
 */
static unsigned long damos_wmark_wait_us(struct damos *scheme)
{
	unsigned long metric;

	if (scheme->wmarks.metric == DAMOS_WMARK_NONE)
		return 0;

	metric = damos_wmark_metric_value(scheme->wmarks.metric);
	/* higher than high watermark or lower than low watermark */
	if (metric > scheme->wmarks.high || scheme->wmarks.low > metric) {
		if (scheme->wmarks.activated)
1354
			pr_debug("deactivate a scheme (%d) for %s wmark\n",
1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
					scheme->action,
					metric > scheme->wmarks.high ?
					"high" : "low");
		scheme->wmarks.activated = false;
		return scheme->wmarks.interval;
	}

	/* inactive and higher than middle watermark */
	if ((scheme->wmarks.high >= metric && metric >= scheme->wmarks.mid) &&
			!scheme->wmarks.activated)
		return scheme->wmarks.interval;

	if (!scheme->wmarks.activated)
		pr_debug("activate a scheme (%d)\n", scheme->action);
	scheme->wmarks.activated = true;
	return 0;
}

static void kdamond_usleep(unsigned long usecs)
{
1375 1376
	/* See Documentation/timers/timers-howto.rst for the thresholds */
	if (usecs > 20 * USEC_PER_MSEC)
1377
		schedule_timeout_idle(usecs_to_jiffies(usecs));
1378
	else
1379
		usleep_idle_range(usecs, usecs + 1);
1380 1381 1382 1383 1384 1385 1386 1387
}

/* Returns negative error code if it's not activated but should return */
static int kdamond_wait_activation(struct damon_ctx *ctx)
{
	struct damos *s;
	unsigned long wait_time;
	unsigned long min_wait_time = 0;
1388
	bool init_wait_time = false;
1389 1390 1391 1392

	while (!kdamond_need_stop(ctx)) {
		damon_for_each_scheme(s, ctx) {
			wait_time = damos_wmark_wait_us(s);
1393 1394
			if (!init_wait_time || wait_time < min_wait_time) {
				init_wait_time = true;
1395
				min_wait_time = wait_time;
1396
			}
1397 1398 1399 1400 1401
		}
		if (!min_wait_time)
			return 0;

		kdamond_usleep(min_wait_time);
1402 1403 1404 1405

		if (ctx->callback.after_wmarks_check &&
				ctx->callback.after_wmarks_check(ctx))
			break;
1406 1407 1408 1409
	}
	return -EBUSY;
}

1410 1411 1412 1413
static void kdamond_init_intervals_sis(struct damon_ctx *ctx)
{
	unsigned long sample_interval = ctx->attrs.sample_interval ?
		ctx->attrs.sample_interval : 1;
1414 1415
	unsigned long apply_interval;
	struct damos *scheme;
1416 1417 1418 1419 1420

	ctx->passed_sample_intervals = 0;
	ctx->next_aggregation_sis = ctx->attrs.aggr_interval / sample_interval;
	ctx->next_ops_update_sis = ctx->attrs.ops_update_interval /
		sample_interval;
1421 1422 1423 1424 1425 1426

	damon_for_each_scheme(scheme, ctx) {
		apply_interval = scheme->apply_interval_us ?
			scheme->apply_interval_us : ctx->attrs.aggr_interval;
		scheme->next_apply_sis = apply_interval / sample_interval;
	}
1427 1428
}

1429 1430 1431 1432 1433
/*
 * The monitoring daemon that runs as a kernel thread
 */
static int kdamond_fn(void *data)
{
1434
	struct damon_ctx *ctx = data;
1435 1436
	struct damon_target *t;
	struct damon_region *r, *next;
1437 1438
	unsigned int max_nr_accesses = 0;
	unsigned long sz_limit = 0;
1439

1440
	pr_debug("kdamond (%d) starts\n", current->pid);
1441

1442 1443
	kdamond_init_intervals_sis(ctx);

1444 1445
	if (ctx->ops.init)
		ctx->ops.init(ctx);
1446
	if (ctx->callback.before_start && ctx->callback.before_start(ctx))
1447
		goto done;
1448

1449 1450
	sz_limit = damon_region_sz_limit(ctx);

1451
	while (!kdamond_need_stop(ctx)) {
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
		/*
		 * ctx->attrs and ctx->next_{aggregation,ops_update}_sis could
		 * be changed from after_wmarks_check() or after_aggregation()
		 * callbacks.  Read the values here, and use those for this
		 * iteration.  That is, damon_set_attrs() updated new values
		 * are respected from next iteration.
		 */
		unsigned long next_aggregation_sis = ctx->next_aggregation_sis;
		unsigned long next_ops_update_sis = ctx->next_ops_update_sis;
		unsigned long sample_interval = ctx->attrs.sample_interval;

1463 1464
		if (kdamond_wait_activation(ctx))
			break;
1465

1466 1467
		if (ctx->ops.prepare_access_checks)
			ctx->ops.prepare_access_checks(ctx);
1468
		if (ctx->callback.after_sampling &&
1469 1470
				ctx->callback.after_sampling(ctx))
			break;
1471

1472 1473
		kdamond_usleep(sample_interval);
		ctx->passed_sample_intervals++;
1474

1475 1476
		if (ctx->ops.check_accesses)
			max_nr_accesses = ctx->ops.check_accesses(ctx);
1477

1478
		if (ctx->passed_sample_intervals == next_aggregation_sis) {
1479 1480 1481
			kdamond_merge_regions(ctx,
					max_nr_accesses / 10,
					sz_limit);
1482
			if (ctx->callback.after_aggregation &&
1483 1484
					ctx->callback.after_aggregation(ctx))
				break;
1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
		}

		/*
		 * do kdamond_apply_schemes() after kdamond_merge_regions() if
		 * possible, to reduce overhead
		 */
		if (!list_empty(&ctx->schemes))
			kdamond_apply_schemes(ctx);

		sample_interval = ctx->attrs.sample_interval ?
			ctx->attrs.sample_interval : 1;
		if (ctx->passed_sample_intervals == next_aggregation_sis) {
			ctx->next_aggregation_sis = next_aggregation_sis +
				ctx->attrs.aggr_interval / sample_interval;

1500
			kdamond_reset_aggregated(ctx);
1501
			kdamond_split_regions(ctx);
1502 1503
			if (ctx->ops.reset_aggregated)
				ctx->ops.reset_aggregated(ctx);
1504 1505
		}

1506 1507 1508 1509
		if (ctx->passed_sample_intervals == next_ops_update_sis) {
			ctx->next_ops_update_sis = next_ops_update_sis +
				ctx->attrs.ops_update_interval /
				sample_interval;
1510 1511
			if (ctx->ops.update)
				ctx->ops.update(ctx);
1512
			sz_limit = damon_region_sz_limit(ctx);
1513 1514
		}
	}
1515
done:
1516 1517
	damon_for_each_target(t, ctx) {
		damon_for_each_region_safe(r, next, t)
1518
			damon_destroy_region(r, t);
1519
	}
1520

1521 1522
	if (ctx->callback.before_terminate)
		ctx->callback.before_terminate(ctx);
1523 1524
	if (ctx->ops.cleanup)
		ctx->ops.cleanup(ctx);
1525

1526
	pr_debug("kdamond (%d) finishes\n", current->pid);
1527 1528 1529 1530 1531 1532
	mutex_lock(&ctx->kdamond_lock);
	ctx->kdamond = NULL;
	mutex_unlock(&ctx->kdamond_lock);

	mutex_lock(&damon_lock);
	nr_running_ctxs--;
1533 1534
	if (!nr_running_ctxs && running_exclusive_ctxs)
		running_exclusive_ctxs = false;
1535 1536
	mutex_unlock(&damon_lock);

1537
	return 0;
1538
}
SeongJae Park's avatar
SeongJae Park committed
1539

1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
/*
 * struct damon_system_ram_region - System RAM resource address region of
 *				    [@start, @end).
 * @start:	Start address of the region (inclusive).
 * @end:	End address of the region (exclusive).
 */
struct damon_system_ram_region {
	unsigned long start;
	unsigned long end;
};

static int walk_system_ram(struct resource *res, void *arg)
{
	struct damon_system_ram_region *a = arg;

	if (a->end - a->start < resource_size(res)) {
		a->start = res->start;
		a->end = res->end;
	}
	return 0;
}

/*
 * Find biggest 'System RAM' resource and store its start and end address in
 * @start and @end, respectively.  If no System RAM is found, returns false.
 */
1566 1567
static bool damon_find_biggest_system_ram(unsigned long *start,
						unsigned long *end)
1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580

{
	struct damon_system_ram_region arg = {};

	walk_system_ram_res(0, ULONG_MAX, &arg, walk_system_ram);
	if (arg.end <= arg.start)
		return false;

	*start = arg.start;
	*end = arg.end;
	return true;
}

1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612
/**
 * damon_set_region_biggest_system_ram_default() - Set the region of the given
 * monitoring target as requested, or biggest 'System RAM'.
 * @t:		The monitoring target to set the region.
 * @start:	The pointer to the start address of the region.
 * @end:	The pointer to the end address of the region.
 *
 * This function sets the region of @t as requested by @start and @end.  If the
 * values of @start and @end are zero, however, this function finds the biggest
 * 'System RAM' resource and sets the region to cover the resource.  In the
 * latter case, this function saves the start and end addresses of the resource
 * in @start and @end, respectively.
 *
 * Return: 0 on success, negative error code otherwise.
 */
int damon_set_region_biggest_system_ram_default(struct damon_target *t,
			unsigned long *start, unsigned long *end)
{
	struct damon_addr_range addr_range;

	if (*start > *end)
		return -EINVAL;

	if (!*start && !*end &&
		!damon_find_biggest_system_ram(start, end))
		return -EINVAL;

	addr_range.start = *start;
	addr_range.end = *end;
	return damon_set_regions(t, &addr_range, 1);
}

1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646
/*
 * damon_moving_sum() - Calculate an inferred moving sum value.
 * @mvsum:	Inferred sum of the last @len_window values.
 * @nomvsum:	Non-moving sum of the last discrete @len_window window values.
 * @len_window:	The number of last values to take care of.
 * @new_value:	New value that will be added to the pseudo moving sum.
 *
 * Moving sum (moving average * window size) is good for handling noise, but
 * the cost of keeping past values can be high for arbitrary window size.  This
 * function implements a lightweight pseudo moving sum function that doesn't
 * keep the past window values.
 *
 * It simply assumes there was no noise in the past, and get the no-noise
 * assumed past value to drop from @nomvsum and @len_window.  @nomvsum is a
 * non-moving sum of the last window.  For example, if @len_window is 10 and we
 * have 25 values, @nomvsum is the sum of the 11th to 20th values of the 25
 * values.  Hence, this function simply drops @nomvsum / @len_window from
 * given @mvsum and add @new_value.
 *
 * For example, if @len_window is 10 and @nomvsum is 50, the last 10 values for
 * the last window could be vary, e.g., 0, 10, 0, 10, 0, 10, 0, 0, 0, 20.  For
 * calculating next moving sum with a new value, we should drop 0 from 50 and
 * add the new value.  However, this function assumes it got value 5 for each
 * of the last ten times.  Based on the assumption, when the next value is
 * measured, it drops the assumed past value, 5 from the current sum, and add
 * the new value to get the updated pseduo-moving average.
 *
 * This means the value could have errors, but the errors will be disappeared
 * for every @len_window aligned calls.  For example, if @len_window is 10, the
 * pseudo moving sum with 11th value to 19th value would have an error.  But
 * the sum with 20th value will not have the error.
 *
 * Return: Pseudo-moving average after getting the @new_value.
 */
1647
static unsigned int damon_moving_sum(unsigned int mvsum, unsigned int nomvsum,
1648 1649 1650 1651 1652
		unsigned int len_window, unsigned int new_value)
{
	return mvsum - nomvsum / len_window + new_value;
}

1653 1654 1655 1656
/**
 * damon_update_region_access_rate() - Update the access rate of a region.
 * @r:		The DAMON region to update for its access check result.
 * @accessed:	Whether the region has accessed during last sampling interval.
1657
 * @attrs:	The damon_attrs of the DAMON context.
1658 1659 1660 1661 1662 1663
 *
 * Update the access rate of a region with the region's last sampling interval
 * access check result.
 *
 * Usually this will be called by &damon_operations->check_accesses callback.
 */
1664 1665
void damon_update_region_access_rate(struct damon_region *r, bool accessed,
		struct damon_attrs *attrs)
1666
{
1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678
	unsigned int len_window = 1;

	/*
	 * sample_interval can be zero, but cannot be larger than
	 * aggr_interval, owing to validation of damon_set_attrs().
	 */
	if (attrs->sample_interval)
		len_window = attrs->aggr_interval / attrs->sample_interval;
	r->nr_accesses_bp = damon_moving_sum(r->nr_accesses_bp,
			r->last_nr_accesses * 10000, len_window,
			accessed ? 10000 : 0);

1679 1680 1681 1682
	if (accessed)
		r->nr_accesses++;
}

1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695
static int __init damon_init(void)
{
	damon_region_cache = KMEM_CACHE(damon_region, 0);
	if (unlikely(!damon_region_cache)) {
		pr_err("creating damon_region_cache fails\n");
		return -ENOMEM;
	}

	return 0;
}

subsys_initcall(damon_init);

SeongJae Park's avatar
SeongJae Park committed
1696
#include "core-test.h"