cqm.c 43.3 KB
Newer Older
1 2 3 4 5 6 7 8 9
/*
 * Intel Cache Quality-of-Service Monitoring (CQM) support.
 *
 * Based very, very heavily on work by Peter Zijlstra.
 */

#include <linux/perf_event.h>
#include <linux/slab.h>
#include <asm/cpu_device_id.h>
10
#include "../perf_event.h"
11 12 13 14 15

#define MSR_IA32_PQR_ASSOC	0x0c8f
#define MSR_IA32_QM_CTR		0x0c8e
#define MSR_IA32_QM_EVTSEL	0x0c8d

16
#define MBM_CNTR_WIDTH		24
17 18 19 20
/*
 * Guaranteed time in ms as per SDM where MBM counters will not overflow.
 */
#define MBM_CTR_OVERFLOW_TIME	1000
21

22
static u32 cqm_max_rmid = -1;
23
static unsigned int cqm_l3_scale; /* supposedly cacheline size */
24
static bool cqm_enabled, mbm_enabled;
25
unsigned int mbm_socket_max;
26

27 28 29 30 31 32 33 34 35 36 37 38 39 40
/**
 * struct intel_pqr_state - State cache for the PQR MSR
 * @rmid:		The cached Resource Monitoring ID
 * @closid:		The cached Class Of Service ID
 * @rmid_usecnt:	The usage counter for rmid
 *
 * The upper 32 bits of MSR_IA32_PQR_ASSOC contain closid and the
 * lower 10 bits rmid. The update to MSR_IA32_PQR_ASSOC always
 * contains both parts, so we need to cache them.
 *
 * The cache also helps to avoid pointless updates if the value does
 * not change.
 */
struct intel_pqr_state {
41
	u32			rmid;
42 43
	u32			closid;
	int			rmid_usecnt;
44 45
};

46
/*
47
 * The cached intel_pqr_state is strictly per CPU and can never be
48 49 50 51
 * updated from a remote CPU. Both functions which modify the state
 * (intel_cqm_event_start and intel_cqm_event_stop) are called with
 * interrupts disabled, which is sufficient for the protection.
 */
52
static DEFINE_PER_CPU(struct intel_pqr_state, pqr_state);
53
static struct hrtimer *mbm_timers;
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
/**
 * struct sample - mbm event's (local or total) data
 * @total_bytes    #bytes since we began monitoring
 * @prev_msr       previous value of MSR
 */
struct sample {
	u64	total_bytes;
	u64	prev_msr;
};

/*
 * samples profiled for total memory bandwidth type events
 */
static struct sample *mbm_total;
/*
 * samples profiled for local memory bandwidth type events
 */
static struct sample *mbm_local;
72

73 74 75 76 77 78 79 80 81 82
#define pkg_id	topology_physical_package_id(smp_processor_id())
/*
 * rmid_2_index returns the index for the rmid in mbm_local/mbm_total array.
 * mbm_total[] and mbm_local[] are linearly indexed by socket# * max number of
 * rmids per socket, an example is given below
 * RMID1 of Socket0:  vrmid =  1
 * RMID1 of Socket1:  vrmid =  1 * (cqm_max_rmid + 1) + 1
 * RMID1 of Socket2:  vrmid =  2 * (cqm_max_rmid + 1) + 1
 */
#define rmid_2_index(rmid)  ((pkg_id * (cqm_max_rmid + 1)) + rmid)
83
/*
84 85 86 87
 * Protects cache_cgroups and cqm_rmid_free_lru and cqm_rmid_limbo_lru.
 * Also protects event->hw.cqm_rmid
 *
 * Hold either for stability, both for modification of ->hw.cqm_rmid.
88 89
 */
static DEFINE_MUTEX(cache_mutex);
90
static DEFINE_RAW_SPINLOCK(cache_lock);
91 92 93 94 95 96 97 98 99 100 101 102 103 104

/*
 * Groups of events that have the same target(s), one RMID per group.
 */
static LIST_HEAD(cache_groups);

/*
 * Mask of CPUs for reading CQM values. We only need one per-socket.
 */
static cpumask_t cqm_cpumask;

#define RMID_VAL_ERROR		(1ULL << 63)
#define RMID_VAL_UNAVAIL	(1ULL << 62)

105 106 107 108 109 110 111
/*
 * Event IDs are used to program IA32_QM_EVTSEL before reading event
 * counter from IA32_QM_CTR
 */
#define QOS_L3_OCCUP_EVENT_ID	0x01
#define QOS_MBM_TOTAL_EVENT_ID	0x02
#define QOS_MBM_LOCAL_EVENT_ID	0x03
112

113 114 115 116 117 118 119
/*
 * This is central to the rotation algorithm in __intel_cqm_rmid_rotate().
 *
 * This rmid is always free and is guaranteed to have an associated
 * near-zero occupancy value, i.e. no cachelines are tagged with this
 * RMID, once __intel_cqm_rmid_rotate() returns.
 */
120
static u32 intel_cqm_rotation_rmid;
121 122 123 124 125 126 127 128 129 130 131

#define INVALID_RMID		(-1)

/*
 * Is @rmid valid for programming the hardware?
 *
 * rmid 0 is reserved by the hardware for all non-monitored tasks, which
 * means that we should never come across an rmid with that value.
 * Likewise, an rmid value of -1 is used to indicate "no rmid currently
 * assigned" and is used as part of the rotation code.
 */
132
static inline bool __rmid_valid(u32 rmid)
133 134 135 136 137 138 139
{
	if (!rmid || rmid == INVALID_RMID)
		return false;

	return true;
}

140
static u64 __rmid_read(u32 rmid)
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
{
	u64 val;

	/*
	 * Ignore the SDM, this thing is _NOTHING_ like a regular perfcnt,
	 * it just says that to increase confusion.
	 */
	wrmsr(MSR_IA32_QM_EVTSEL, QOS_L3_OCCUP_EVENT_ID, rmid);
	rdmsrl(MSR_IA32_QM_CTR, val);

	/*
	 * Aside from the ERROR and UNAVAIL bits, assume this thing returns
	 * the number of cachelines tagged with @rmid.
	 */
	return val;
}

158 159 160 161 162 163
enum rmid_recycle_state {
	RMID_YOUNG = 0,
	RMID_AVAILABLE,
	RMID_DIRTY,
};

164
struct cqm_rmid_entry {
165
	u32 rmid;
166
	enum rmid_recycle_state state;
167
	struct list_head list;
168
	unsigned long queue_time;
169 170 171
};

/*
172
 * cqm_rmid_free_lru - A least recently used list of RMIDs.
173 174 175 176 177 178 179 180 181 182
 *
 * Oldest entry at the head, newest (most recently used) entry at the
 * tail. This list is never traversed, it's only used to keep track of
 * the lru order. That is, we only pick entries of the head or insert
 * them on the tail.
 *
 * All entries on the list are 'free', and their RMIDs are not currently
 * in use. To mark an RMID as in use, remove its entry from the lru
 * list.
 *
183 184 185 186 187 188 189 190 191
 *
 * cqm_rmid_limbo_lru - list of currently unused but (potentially) dirty RMIDs.
 *
 * This list is contains RMIDs that no one is currently using but that
 * may have a non-zero occupancy value associated with them. The
 * rotation worker moves RMIDs from the limbo list to the free list once
 * the occupancy value drops below __intel_cqm_threshold.
 *
 * Both lists are protected by cache_mutex.
192
 */
193 194
static LIST_HEAD(cqm_rmid_free_lru);
static LIST_HEAD(cqm_rmid_limbo_lru);
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209

/*
 * We use a simple array of pointers so that we can lookup a struct
 * cqm_rmid_entry in O(1). This alleviates the callers of __get_rmid()
 * and __put_rmid() from having to worry about dealing with struct
 * cqm_rmid_entry - they just deal with rmids, i.e. integers.
 *
 * Once this array is initialized it is read-only. No locks are required
 * to access it.
 *
 * All entries for all RMIDs can be looked up in the this array at all
 * times.
 */
static struct cqm_rmid_entry **cqm_rmid_ptrs;

210
static inline struct cqm_rmid_entry *__rmid_entry(u32 rmid)
211 212 213 214 215 216 217 218
{
	struct cqm_rmid_entry *entry;

	entry = cqm_rmid_ptrs[rmid];
	WARN_ON(entry->rmid != rmid);

	return entry;
}
219 220 221

/*
 * Returns < 0 on fail.
222 223
 *
 * We expect to be called with cache_mutex held.
224
 */
225
static u32 __get_rmid(void)
226
{
227 228 229 230
	struct cqm_rmid_entry *entry;

	lockdep_assert_held(&cache_mutex);

231 232
	if (list_empty(&cqm_rmid_free_lru))
		return INVALID_RMID;
233

234
	entry = list_first_entry(&cqm_rmid_free_lru, struct cqm_rmid_entry, list);
235 236 237
	list_del(&entry->list);

	return entry->rmid;
238 239
}

240
static void __put_rmid(u32 rmid)
241
{
242 243 244 245
	struct cqm_rmid_entry *entry;

	lockdep_assert_held(&cache_mutex);

246
	WARN_ON(!__rmid_valid(rmid));
247 248
	entry = __rmid_entry(rmid);

249 250 251 252
	entry->queue_time = jiffies;
	entry->state = RMID_YOUNG;

	list_add_tail(&entry->list, &cqm_rmid_limbo_lru);
253 254
}

255 256 257 258 259 260 261 262 263 264 265 266
static void cqm_cleanup(void)
{
	int i;

	if (!cqm_rmid_ptrs)
		return;

	for (i = 0; i < cqm_max_rmid; i++)
		kfree(cqm_rmid_ptrs[i]);

	kfree(cqm_rmid_ptrs);
	cqm_rmid_ptrs = NULL;
267
	cqm_enabled = false;
268 269
}

270 271
static int intel_cqm_setup_rmid_cache(void)
{
272
	struct cqm_rmid_entry *entry;
273 274
	unsigned int nr_rmids;
	int r = 0;
275

276
	nr_rmids = cqm_max_rmid + 1;
277
	cqm_rmid_ptrs = kzalloc(sizeof(struct cqm_rmid_entry *) *
278
				nr_rmids, GFP_KERNEL);
279
	if (!cqm_rmid_ptrs)
280 281
		return -ENOMEM;

282
	for (; r <= cqm_max_rmid; r++) {
283 284 285 286 287 288 289 290 291 292
		struct cqm_rmid_entry *entry;

		entry = kmalloc(sizeof(*entry), GFP_KERNEL);
		if (!entry)
			goto fail;

		INIT_LIST_HEAD(&entry->list);
		entry->rmid = r;
		cqm_rmid_ptrs[r] = entry;

293
		list_add_tail(&entry->list, &cqm_rmid_free_lru);
294
	}
295 296 297 298 299

	/*
	 * RMID 0 is special and is always allocated. It's used for all
	 * tasks that are not monitored.
	 */
300 301
	entry = __rmid_entry(0);
	list_del(&entry->list);
302

303 304 305 306
	mutex_lock(&cache_mutex);
	intel_cqm_rotation_rmid = __get_rmid();
	mutex_unlock(&cache_mutex);

307
	return 0;
308

309 310
fail:
	cqm_cleanup();
311
	return -ENOMEM;
312 313 314 315
}

/*
 * Determine if @a and @b measure the same set of tasks.
316 317 318
 *
 * If @a and @b measure the same set of tasks then we want to share a
 * single RMID.
319 320 321
 */
static bool __match_event(struct perf_event *a, struct perf_event *b)
{
322
	/* Per-cpu and task events don't mix */
323 324 325 326
	if ((a->attach_state & PERF_ATTACH_TASK) !=
	    (b->attach_state & PERF_ATTACH_TASK))
		return false;

327 328 329 330 331 332 333 334 335 336 337
#ifdef CONFIG_CGROUP_PERF
	if (a->cgrp != b->cgrp)
		return false;
#endif

	/* If not task event, we're machine wide */
	if (!(b->attach_state & PERF_ATTACH_TASK))
		return true;

	/*
	 * Events that target same task are placed into the same cache group.
338 339
	 * Mark it as a multi event group, so that we update ->count
	 * for every event rather than just the group leader later.
340
	 */
341 342
	if (a->hw.target == b->hw.target) {
		b->hw.is_group_event = true;
343
		return true;
344
	}
345 346 347 348 349 350 351 352 353 354 355 356 357 358

	/*
	 * Are we an inherited event?
	 */
	if (b->parent == a)
		return true;

	return false;
}

#ifdef CONFIG_CGROUP_PERF
static inline struct perf_cgroup *event_to_cgroup(struct perf_event *event)
{
	if (event->attach_state & PERF_ATTACH_TASK)
359
		return perf_cgroup_from_task(event->hw.target, event->ctx);
360

361
	return event->cgrp;
362
}
363
#endif
364 365 366

/*
 * Determine if @a's tasks intersect with @b's tasks
367 368 369 370 371 372 373 374 375 376 377
 *
 * There are combinations of events that we explicitly prohibit,
 *
 *		   PROHIBITS
 *     system-wide    -> 	cgroup and task
 *     cgroup 	      ->	system-wide
 *     		      ->	task in cgroup
 *     task 	      -> 	system-wide
 *     		      ->	task in cgroup
 *
 * Call this function before allocating an RMID.
378 379 380
 */
static bool __conflict_event(struct perf_event *a, struct perf_event *b)
{
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
#ifdef CONFIG_CGROUP_PERF
	/*
	 * We can have any number of cgroups but only one system-wide
	 * event at a time.
	 */
	if (a->cgrp && b->cgrp) {
		struct perf_cgroup *ac = a->cgrp;
		struct perf_cgroup *bc = b->cgrp;

		/*
		 * This condition should have been caught in
		 * __match_event() and we should be sharing an RMID.
		 */
		WARN_ON_ONCE(ac == bc);

		if (cgroup_is_descendant(ac->css.cgroup, bc->css.cgroup) ||
		    cgroup_is_descendant(bc->css.cgroup, ac->css.cgroup))
			return true;

		return false;
	}

	if (a->cgrp || b->cgrp) {
		struct perf_cgroup *ac, *bc;

		/*
		 * cgroup and system-wide events are mutually exclusive
		 */
		if ((a->cgrp && !(b->attach_state & PERF_ATTACH_TASK)) ||
		    (b->cgrp && !(a->attach_state & PERF_ATTACH_TASK)))
			return true;

		/*
		 * Ensure neither event is part of the other's cgroup
		 */
		ac = event_to_cgroup(a);
		bc = event_to_cgroup(b);
		if (ac == bc)
			return true;

		/*
		 * Must have cgroup and non-intersecting task events.
		 */
		if (!ac || !bc)
			return false;

		/*
		 * We have cgroup and task events, and the task belongs
		 * to a cgroup. Check for for overlap.
		 */
		if (cgroup_is_descendant(ac->css.cgroup, bc->css.cgroup) ||
		    cgroup_is_descendant(bc->css.cgroup, ac->css.cgroup))
			return true;

		return false;
	}
#endif
438 439 440 441 442 443 444 445 446 447 448 449 450
	/*
	 * If one of them is not a task, same story as above with cgroups.
	 */
	if (!(a->attach_state & PERF_ATTACH_TASK) ||
	    !(b->attach_state & PERF_ATTACH_TASK))
		return true;

	/*
	 * Must be non-overlapping.
	 */
	return false;
}

451
struct rmid_read {
452
	u32 rmid;
453
	u32 evt_type;
454 455 456 457
	atomic64_t value;
};

static void __intel_cqm_event_count(void *info);
458
static void init_mbm_sample(u32 rmid, u32 evt_type);
459
static void __intel_mbm_event_count(void *info);
460 461 462 463 464

static bool is_mbm_event(int e)
{
	return (e >= QOS_MBM_TOTAL_EVENT_ID && e <= QOS_MBM_LOCAL_EVENT_ID);
}
465

466 467 468 469 470 471 472 473
static void cqm_mask_call(struct rmid_read *rr)
{
	if (is_mbm_event(rr->evt_type))
		on_each_cpu_mask(&cqm_cpumask, __intel_mbm_event_count, rr, 1);
	else
		on_each_cpu_mask(&cqm_cpumask, __intel_cqm_event_count, rr, 1);
}

474 475 476
/*
 * Exchange the RMID of a group of events.
 */
477
static u32 intel_cqm_xchg_rmid(struct perf_event *group, u32 rmid)
478 479 480
{
	struct perf_event *event;
	struct list_head *head = &group->hw.cqm_group_entry;
481
	u32 old_rmid = group->hw.cqm_rmid;
482 483 484 485 486 487 488 489 490

	lockdep_assert_held(&cache_mutex);

	/*
	 * If our RMID is being deallocated, perform a read now.
	 */
	if (__rmid_valid(old_rmid) && !__rmid_valid(rmid)) {
		struct rmid_read rr = {
			.rmid = old_rmid,
491 492
			.evt_type = group->attr.config,
			.value = ATOMIC64_INIT(0),
493 494
		};

495
		cqm_mask_call(&rr);
496 497 498 499 500 501 502 503 504 505 506
		local64_set(&group->count, atomic64_read(&rr.value));
	}

	raw_spin_lock_irq(&cache_lock);

	group->hw.cqm_rmid = rmid;
	list_for_each_entry(event, head, hw.cqm_group_entry)
		event->hw.cqm_rmid = rmid;

	raw_spin_unlock_irq(&cache_lock);

507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
	/*
	 * If the allocation is for mbm, init the mbm stats.
	 * Need to check if each event in the group is mbm event
	 * because there could be multiple type of events in the same group.
	 */
	if (__rmid_valid(rmid)) {
		event = group;
		if (is_mbm_event(event->attr.config))
			init_mbm_sample(rmid, event->attr.config);

		list_for_each_entry(event, head, hw.cqm_group_entry) {
			if (is_mbm_event(event->attr.config))
				init_mbm_sample(rmid, event->attr.config);
		}
	}

523 524 525 526 527 528 529 530 531 532 533 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
	return old_rmid;
}

/*
 * If we fail to assign a new RMID for intel_cqm_rotation_rmid because
 * cachelines are still tagged with RMIDs in limbo, we progressively
 * increment the threshold until we find an RMID in limbo with <=
 * __intel_cqm_threshold lines tagged. This is designed to mitigate the
 * problem where cachelines tagged with an RMID are not steadily being
 * evicted.
 *
 * On successful rotations we decrease the threshold back towards zero.
 *
 * __intel_cqm_max_threshold provides an upper bound on the threshold,
 * and is measured in bytes because it's exposed to userland.
 */
static unsigned int __intel_cqm_threshold;
static unsigned int __intel_cqm_max_threshold;

/*
 * Test whether an RMID has a zero occupancy value on this cpu.
 */
static void intel_cqm_stable(void *arg)
{
	struct cqm_rmid_entry *entry;

	list_for_each_entry(entry, &cqm_rmid_limbo_lru, list) {
		if (entry->state != RMID_AVAILABLE)
			break;

		if (__rmid_read(entry->rmid) > __intel_cqm_threshold)
			entry->state = RMID_DIRTY;
	}
}

/*
 * If we have group events waiting for an RMID that don't conflict with
 * events already running, assign @rmid.
 */
562
static bool intel_cqm_sched_in_event(u32 rmid)
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
{
	struct perf_event *leader, *event;

	lockdep_assert_held(&cache_mutex);

	leader = list_first_entry(&cache_groups, struct perf_event,
				  hw.cqm_groups_entry);
	event = leader;

	list_for_each_entry_continue(event, &cache_groups,
				     hw.cqm_groups_entry) {
		if (__rmid_valid(event->hw.cqm_rmid))
			continue;

		if (__conflict_event(event, leader))
			continue;

		intel_cqm_xchg_rmid(event, rmid);
		return true;
	}

	return false;
}

/*
 * Initially use this constant for both the limbo queue time and the
 * rotation timer interval, pmu::hrtimer_interval_ms.
 *
 * They don't need to be the same, but the two are related since if you
 * rotate faster than you recycle RMIDs, you may run out of available
 * RMIDs.
 */
#define RMID_DEFAULT_QUEUE_TIME 250	/* ms */

static unsigned int __rmid_queue_time_ms = RMID_DEFAULT_QUEUE_TIME;

/*
 * intel_cqm_rmid_stabilize - move RMIDs from limbo to free list
 * @nr_available: number of freeable RMIDs on the limbo list
 *
 * Quiescent state; wait for all 'freed' RMIDs to become unused, i.e. no
 * cachelines are tagged with those RMIDs. After this we can reuse them
 * and know that the current set of active RMIDs is stable.
 *
 * Return %true or %false depending on whether stabilization needs to be
 * reattempted.
 *
 * If we return %true then @nr_available is updated to indicate the
 * number of RMIDs on the limbo list that have been queued for the
 * minimum queue time (RMID_AVAILABLE), but whose data occupancy values
 * are above __intel_cqm_threshold.
 */
static bool intel_cqm_rmid_stabilize(unsigned int *available)
{
	struct cqm_rmid_entry *entry, *tmp;

	lockdep_assert_held(&cache_mutex);

	*available = 0;
	list_for_each_entry(entry, &cqm_rmid_limbo_lru, list) {
		unsigned long min_queue_time;
		unsigned long now = jiffies;

		/*
		 * We hold RMIDs placed into limbo for a minimum queue
		 * time. Before the minimum queue time has elapsed we do
		 * not recycle RMIDs.
		 *
		 * The reasoning is that until a sufficient time has
		 * passed since we stopped using an RMID, any RMID
		 * placed onto the limbo list will likely still have
		 * data tagged in the cache, which means we'll probably
		 * fail to recycle it anyway.
		 *
		 * We can save ourselves an expensive IPI by skipping
		 * any RMIDs that have not been queued for the minimum
		 * time.
		 */
		min_queue_time = entry->queue_time +
			msecs_to_jiffies(__rmid_queue_time_ms);

		if (time_after(min_queue_time, now))
			break;

		entry->state = RMID_AVAILABLE;
		(*available)++;
	}

	/*
	 * Fast return if none of the RMIDs on the limbo list have been
	 * sitting on the queue for the minimum queue time.
	 */
	if (!*available)
		return false;

	/*
	 * Test whether an RMID is free for each package.
	 */
	on_each_cpu_mask(&cqm_cpumask, intel_cqm_stable, NULL, true);

	list_for_each_entry_safe(entry, tmp, &cqm_rmid_limbo_lru, list) {
		/*
		 * Exhausted all RMIDs that have waited min queue time.
		 */
		if (entry->state == RMID_YOUNG)
			break;

		if (entry->state == RMID_DIRTY)
			continue;

		list_del(&entry->list);	/* remove from limbo */

		/*
		 * The rotation RMID gets priority if it's
		 * currently invalid. In which case, skip adding
		 * the RMID to the the free lru.
		 */
		if (!__rmid_valid(intel_cqm_rotation_rmid)) {
			intel_cqm_rotation_rmid = entry->rmid;
			continue;
		}

		/*
		 * If we have groups waiting for RMIDs, hand
687
		 * them one now provided they don't conflict.
688
		 */
689
		if (intel_cqm_sched_in_event(entry->rmid))
690 691 692 693 694 695 696 697 698 699 700 701 702 703
			continue;

		/*
		 * Otherwise place it onto the free list.
		 */
		list_add_tail(&entry->list, &cqm_rmid_free_lru);
	}


	return __rmid_valid(intel_cqm_rotation_rmid);
}

/*
 * Pick a victim group and move it to the tail of the group list.
704
 * @next: The first group without an RMID
705
 */
706
static void __intel_cqm_pick_and_rotate(struct perf_event *next)
707 708
{
	struct perf_event *rotor;
709
	u32 rmid;
710 711 712 713 714

	lockdep_assert_held(&cache_mutex);

	rotor = list_first_entry(&cache_groups, struct perf_event,
				 hw.cqm_groups_entry);
715 716 717 718 719 720 721 722 723 724 725 726

	/*
	 * The group at the front of the list should always have a valid
	 * RMID. If it doesn't then no groups have RMIDs assigned and we
	 * don't need to rotate the list.
	 */
	if (next == rotor)
		return;

	rmid = intel_cqm_xchg_rmid(rotor, INVALID_RMID);
	__put_rmid(rmid);

727
	list_rotate_left(&cache_groups);
728 729 730 731 732 733 734 735 736
}

/*
 * Deallocate the RMIDs from any events that conflict with @event, and
 * place them on the back of the group list.
 */
static void intel_cqm_sched_out_conflicting_events(struct perf_event *event)
{
	struct perf_event *group, *g;
737
	u32 rmid;
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757

	lockdep_assert_held(&cache_mutex);

	list_for_each_entry_safe(group, g, &cache_groups, hw.cqm_groups_entry) {
		if (group == event)
			continue;

		rmid = group->hw.cqm_rmid;

		/*
		 * Skip events that don't have a valid RMID.
		 */
		if (!__rmid_valid(rmid))
			continue;

		/*
		 * No conflict? No problem! Leave the event alone.
		 */
		if (!__conflict_event(group, event))
			continue;
758

759 760 761
		intel_cqm_xchg_rmid(group, INVALID_RMID);
		__put_rmid(rmid);
	}
762 763 764 765 766
}

/*
 * Attempt to rotate the groups and assign new RMIDs.
 *
767 768 769 770
 * We rotate for two reasons,
 *   1. To handle the scheduling of conflicting events
 *   2. To recycle RMIDs
 *
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
 * Rotating RMIDs is complicated because the hardware doesn't give us
 * any clues.
 *
 * There's problems with the hardware interface; when you change the
 * task:RMID map cachelines retain their 'old' tags, giving a skewed
 * picture. In order to work around this, we must always keep one free
 * RMID - intel_cqm_rotation_rmid.
 *
 * Rotation works by taking away an RMID from a group (the old RMID),
 * and assigning the free RMID to another group (the new RMID). We must
 * then wait for the old RMID to not be used (no cachelines tagged).
 * This ensure that all cachelines are tagged with 'active' RMIDs. At
 * this point we can start reading values for the new RMID and treat the
 * old RMID as the free RMID for the next rotation.
 *
 * Return %true or %false depending on whether we did any rotating.
 */
static bool __intel_cqm_rmid_rotate(void)
{
790
	struct perf_event *group, *start = NULL;
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
	unsigned int threshold_limit;
	unsigned int nr_needed = 0;
	unsigned int nr_available;
	bool rotated = false;

	mutex_lock(&cache_mutex);

again:
	/*
	 * Fast path through this function if there are no groups and no
	 * RMIDs that need cleaning.
	 */
	if (list_empty(&cache_groups) && list_empty(&cqm_rmid_limbo_lru))
		goto out;

	list_for_each_entry(group, &cache_groups, hw.cqm_groups_entry) {
		if (!__rmid_valid(group->hw.cqm_rmid)) {
			if (!start)
				start = group;
			nr_needed++;
		}
	}

	/*
	 * We have some event groups, but they all have RMIDs assigned
	 * and no RMIDs need cleaning.
	 */
	if (!nr_needed && list_empty(&cqm_rmid_limbo_lru))
		goto out;

	if (!nr_needed)
		goto stabilize;

	/*
825 826 827
	 * We have more event groups without RMIDs than available RMIDs,
	 * or we have event groups that conflict with the ones currently
	 * scheduled.
828 829 830 831 832 833 834 835 836
	 *
	 * We force deallocate the rmid of the group at the head of
	 * cache_groups. The first event group without an RMID then gets
	 * assigned intel_cqm_rotation_rmid. This ensures we always make
	 * forward progress.
	 *
	 * Rotate the cache_groups list so the previous head is now the
	 * tail.
	 */
837
	__intel_cqm_pick_and_rotate(start);
838 839 840 841 842 843 844

	/*
	 * If the rotation is going to succeed, reduce the threshold so
	 * that we don't needlessly reuse dirty RMIDs.
	 */
	if (__rmid_valid(intel_cqm_rotation_rmid)) {
		intel_cqm_xchg_rmid(start, intel_cqm_rotation_rmid);
845 846 847
		intel_cqm_rotation_rmid = __get_rmid();

		intel_cqm_sched_out_conflicting_events(start);
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 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929

		if (__intel_cqm_threshold)
			__intel_cqm_threshold--;
	}

	rotated = true;

stabilize:
	/*
	 * We now need to stablize the RMID we freed above (if any) to
	 * ensure that the next time we rotate we have an RMID with zero
	 * occupancy value.
	 *
	 * Alternatively, if we didn't need to perform any rotation,
	 * we'll have a bunch of RMIDs in limbo that need stabilizing.
	 */
	threshold_limit = __intel_cqm_max_threshold / cqm_l3_scale;

	while (intel_cqm_rmid_stabilize(&nr_available) &&
	       __intel_cqm_threshold < threshold_limit) {
		unsigned int steal_limit;

		/*
		 * Don't spin if nobody is actively waiting for an RMID,
		 * the rotation worker will be kicked as soon as an
		 * event needs an RMID anyway.
		 */
		if (!nr_needed)
			break;

		/* Allow max 25% of RMIDs to be in limbo. */
		steal_limit = (cqm_max_rmid + 1) / 4;

		/*
		 * We failed to stabilize any RMIDs so our rotation
		 * logic is now stuck. In order to make forward progress
		 * we have a few options:
		 *
		 *   1. rotate ("steal") another RMID
		 *   2. increase the threshold
		 *   3. do nothing
		 *
		 * We do both of 1. and 2. until we hit the steal limit.
		 *
		 * The steal limit prevents all RMIDs ending up on the
		 * limbo list. This can happen if every RMID has a
		 * non-zero occupancy above threshold_limit, and the
		 * occupancy values aren't dropping fast enough.
		 *
		 * Note that there is prioritisation at work here - we'd
		 * rather increase the number of RMIDs on the limbo list
		 * than increase the threshold, because increasing the
		 * threshold skews the event data (because we reuse
		 * dirty RMIDs) - threshold bumps are a last resort.
		 */
		if (nr_available < steal_limit)
			goto again;

		__intel_cqm_threshold++;
	}

out:
	mutex_unlock(&cache_mutex);
	return rotated;
}

static void intel_cqm_rmid_rotate(struct work_struct *work);

static DECLARE_DELAYED_WORK(intel_cqm_rmid_work, intel_cqm_rmid_rotate);

static struct pmu intel_cqm_pmu;

static void intel_cqm_rmid_rotate(struct work_struct *work)
{
	unsigned long delay;

	__intel_cqm_rmid_rotate();

	delay = msecs_to_jiffies(intel_cqm_pmu.hrtimer_interval_ms);
	schedule_delayed_work(&intel_cqm_rmid_work, delay);
}

930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
static u64 update_sample(unsigned int rmid, u32 evt_type, int first)
{
	struct sample *mbm_current;
	u32 vrmid = rmid_2_index(rmid);
	u64 val, bytes, shift;
	u32 eventid;

	if (evt_type == QOS_MBM_LOCAL_EVENT_ID) {
		mbm_current = &mbm_local[vrmid];
		eventid     = QOS_MBM_LOCAL_EVENT_ID;
	} else {
		mbm_current = &mbm_total[vrmid];
		eventid     = QOS_MBM_TOTAL_EVENT_ID;
	}

	wrmsr(MSR_IA32_QM_EVTSEL, eventid, rmid);
	rdmsrl(MSR_IA32_QM_CTR, val);
	if (val & (RMID_VAL_ERROR | RMID_VAL_UNAVAIL))
		return mbm_current->total_bytes;

	if (first) {
		mbm_current->prev_msr = val;
		mbm_current->total_bytes = 0;
		return mbm_current->total_bytes;
	}

956 957 958 959
	/*
	 * The h/w guarantees that counters will not overflow
	 * so long as we poll them at least once per second.
	 */
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 987 988 989 990 991 992 993 994 995
	shift = 64 - MBM_CNTR_WIDTH;
	bytes = (val << shift) - (mbm_current->prev_msr << shift);
	bytes >>= shift;

	bytes *= cqm_l3_scale;

	mbm_current->total_bytes += bytes;
	mbm_current->prev_msr = val;

	return mbm_current->total_bytes;
}

static u64 rmid_read_mbm(unsigned int rmid, u32 evt_type)
{
	return update_sample(rmid, evt_type, 0);
}

static void __intel_mbm_event_init(void *info)
{
	struct rmid_read *rr = info;

	update_sample(rr->rmid, rr->evt_type, 1);
}

static void init_mbm_sample(u32 rmid, u32 evt_type)
{
	struct rmid_read rr = {
		.rmid = rmid,
		.evt_type = evt_type,
		.value = ATOMIC64_INIT(0),
	};

	/* on each socket, init sample */
	on_each_cpu_mask(&cqm_cpumask, __intel_mbm_event_init, &rr, 1);
}

996 997 998 999 1000
/*
 * Find a group and setup RMID.
 *
 * If we're part of a group, we use the group's RMID.
 */
1001 1002
static void intel_cqm_setup_event(struct perf_event *event,
				  struct perf_event **group)
1003 1004
{
	struct perf_event *iter;
1005
	bool conflict = false;
1006
	u32 rmid;
1007

1008
	event->hw.is_group_event = false;
1009
	list_for_each_entry(iter, &cache_groups, hw.cqm_groups_entry) {
1010 1011
		rmid = iter->hw.cqm_rmid;

1012 1013
		if (__match_event(iter, event)) {
			/* All tasks in a group share an RMID */
1014
			event->hw.cqm_rmid = rmid;
1015
			*group = iter;
1016
			if (is_mbm_event(event->attr.config) && __rmid_valid(rmid))
1017
				init_mbm_sample(rmid, event->attr.config);
1018
			return;
1019 1020
		}

1021 1022 1023 1024 1025 1026
		/*
		 * We only care about conflicts for events that are
		 * actually scheduled in (and hence have a valid RMID).
		 */
		if (__conflict_event(iter, event) && __rmid_valid(rmid))
			conflict = true;
1027 1028
	}

1029 1030 1031 1032 1033
	if (conflict)
		rmid = INVALID_RMID;
	else
		rmid = __get_rmid();

1034
	if (is_mbm_event(event->attr.config) && __rmid_valid(rmid))
1035 1036
		init_mbm_sample(rmid, event->attr.config);

1037
	event->hw.cqm_rmid = rmid;
1038 1039 1040 1041
}

static void intel_cqm_event_read(struct perf_event *event)
{
1042
	unsigned long flags;
1043
	u32 rmid;
1044 1045
	u64 val;

1046 1047 1048 1049 1050 1051
	/*
	 * Task events are handled by intel_cqm_event_count().
	 */
	if (event->cpu == -1)
		return;

1052
	raw_spin_lock_irqsave(&cache_lock, flags);
1053
	rmid = event->hw.cqm_rmid;
1054 1055 1056 1057

	if (!__rmid_valid(rmid))
		goto out;

1058 1059 1060 1061
	if (is_mbm_event(event->attr.config))
		val = rmid_read_mbm(rmid, event->attr.config);
	else
		val = __rmid_read(rmid);
1062 1063 1064 1065 1066

	/*
	 * Ignore this reading on error states and do not update the value.
	 */
	if (val & (RMID_VAL_ERROR | RMID_VAL_UNAVAIL))
1067
		goto out;
1068 1069

	local64_set(&event->count, val);
1070 1071
out:
	raw_spin_unlock_irqrestore(&cache_lock, flags);
1072 1073
}

1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
static void __intel_cqm_event_count(void *info)
{
	struct rmid_read *rr = info;
	u64 val;

	val = __rmid_read(rr->rmid);

	if (val & (RMID_VAL_ERROR | RMID_VAL_UNAVAIL))
		return;

	atomic64_add(val, &rr->value);
}

static inline bool cqm_group_leader(struct perf_event *event)
{
	return !list_empty(&event->hw.cqm_groups_entry);
}

1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
static void __intel_mbm_event_count(void *info)
{
	struct rmid_read *rr = info;
	u64 val;

	val = rmid_read_mbm(rr->rmid, rr->evt_type);
	if (val & (RMID_VAL_ERROR | RMID_VAL_UNAVAIL))
		return;
	atomic64_add(val, &rr->value);
}

1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
static enum hrtimer_restart mbm_hrtimer_handle(struct hrtimer *hrtimer)
{
	struct perf_event *iter, *iter1;
	int ret = HRTIMER_RESTART;
	struct list_head *head;
	unsigned long flags;
	u32 grp_rmid;

	/*
	 * Need to cache_lock as the timer Event Select MSR reads
	 * can race with the mbm/cqm count() and mbm_init() reads.
	 */
	raw_spin_lock_irqsave(&cache_lock, flags);

	if (list_empty(&cache_groups)) {
		ret = HRTIMER_NORESTART;
		goto out;
	}

	list_for_each_entry(iter, &cache_groups, hw.cqm_groups_entry) {
		grp_rmid = iter->hw.cqm_rmid;
		if (!__rmid_valid(grp_rmid))
			continue;
		if (is_mbm_event(iter->attr.config))
			update_sample(grp_rmid, iter->attr.config, 0);

		head = &iter->hw.cqm_group_entry;
		if (list_empty(head))
			continue;
		list_for_each_entry(iter1, head, hw.cqm_group_entry) {
			if (!iter1->hw.is_group_event)
				break;
			if (is_mbm_event(iter1->attr.config))
				update_sample(iter1->hw.cqm_rmid,
					      iter1->attr.config, 0);
		}
	}

	hrtimer_forward_now(hrtimer, ms_to_ktime(MBM_CTR_OVERFLOW_TIME));
out:
	raw_spin_unlock_irqrestore(&cache_lock, flags);

	return ret;
}

static void __mbm_start_timer(void *info)
{
	hrtimer_start(&mbm_timers[pkg_id], ms_to_ktime(MBM_CTR_OVERFLOW_TIME),
			     HRTIMER_MODE_REL_PINNED);
}

static void __mbm_stop_timer(void *info)
{
	hrtimer_cancel(&mbm_timers[pkg_id]);
}

static void mbm_start_timers(void)
{
	on_each_cpu_mask(&cqm_cpumask, __mbm_start_timer, NULL, 1);
}

static void mbm_stop_timers(void)
{
	on_each_cpu_mask(&cqm_cpumask, __mbm_stop_timer, NULL, 1);
}

static void mbm_hrtimer_init(void)
{
	struct hrtimer *hr;
	int i;

	for (i = 0; i < mbm_socket_max; i++) {
		hr = &mbm_timers[i];
		hrtimer_init(hr, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
		hr->function = mbm_hrtimer_handle;
	}
}

1181 1182
static u64 intel_cqm_event_count(struct perf_event *event)
{
1183
	unsigned long flags;
1184
	struct rmid_read rr = {
1185
		.evt_type = event->attr.config,
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
		.value = ATOMIC64_INIT(0),
	};

	/*
	 * We only need to worry about task events. System-wide events
	 * are handled like usual, i.e. entirely with
	 * intel_cqm_event_read().
	 */
	if (event->cpu != -1)
		return __perf_event_count(event);

	/*
1198 1199 1200
	 * Only the group leader gets to report values except in case of
	 * multiple events in the same group, we still need to read the
	 * other events.This stops us
1201 1202 1203 1204 1205 1206 1207
	 * reporting duplicate values to userspace, and gives us a clear
	 * rule for which task gets to report the values.
	 *
	 * Note that it is impossible to attribute these values to
	 * specific packages - we forfeit that ability when we create
	 * task events.
	 */
1208
	if (!cqm_group_leader(event) && !event->hw.is_group_event)
1209 1210
		return 0;

1211 1212 1213 1214 1215 1216 1217 1218
	/*
	 * Getting up-to-date values requires an SMP IPI which is not
	 * possible if we're being called in interrupt context. Return
	 * the cached values instead.
	 */
	if (unlikely(in_interrupt()))
		goto out;

1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
	/*
	 * Notice that we don't perform the reading of an RMID
	 * atomically, because we can't hold a spin lock across the
	 * IPIs.
	 *
	 * Speculatively perform the read, since @event might be
	 * assigned a different (possibly invalid) RMID while we're
	 * busying performing the IPI calls. It's therefore necessary to
	 * check @event's RMID afterwards, and if it has changed,
	 * discard the result of the read.
	 */
	rr.rmid = ACCESS_ONCE(event->hw.cqm_rmid);
1231

1232 1233 1234
	if (!__rmid_valid(rr.rmid))
		goto out;

1235
	cqm_mask_call(&rr);
1236

1237 1238 1239 1240 1241
	raw_spin_lock_irqsave(&cache_lock, flags);
	if (event->hw.cqm_rmid == rr.rmid)
		local64_set(&event->count, atomic64_read(&rr.value));
	raw_spin_unlock_irqrestore(&cache_lock, flags);
out:
1242 1243 1244
	return __perf_event_count(event);
}

1245 1246
static void intel_cqm_event_start(struct perf_event *event, int mode)
{
1247
	struct intel_pqr_state *state = this_cpu_ptr(&pqr_state);
1248
	u32 rmid = event->hw.cqm_rmid;
1249 1250 1251 1252 1253 1254

	if (!(event->hw.cqm_state & PERF_HES_STOPPED))
		return;

	event->hw.cqm_state &= ~PERF_HES_STOPPED;

1255
	if (state->rmid_usecnt++) {
1256 1257 1258
		if (!WARN_ON_ONCE(state->rmid != rmid))
			return;
	} else {
1259
		WARN_ON_ONCE(state->rmid);
1260
	}
1261 1262

	state->rmid = rmid;
1263
	wrmsr(MSR_IA32_PQR_ASSOC, rmid, state->closid);
1264 1265 1266 1267
}

static void intel_cqm_event_stop(struct perf_event *event, int mode)
{
1268
	struct intel_pqr_state *state = this_cpu_ptr(&pqr_state);
1269 1270 1271 1272 1273 1274 1275 1276

	if (event->hw.cqm_state & PERF_HES_STOPPED)
		return;

	event->hw.cqm_state |= PERF_HES_STOPPED;

	intel_cqm_event_read(event);

1277
	if (!--state->rmid_usecnt) {
1278
		state->rmid = 0;
1279
		wrmsr(MSR_IA32_PQR_ASSOC, 0, state->closid);
1280 1281 1282 1283 1284 1285 1286
	} else {
		WARN_ON_ONCE(!state->rmid);
	}
}

static int intel_cqm_event_add(struct perf_event *event, int mode)
{
1287
	unsigned long flags;
1288
	u32 rmid;
1289 1290

	raw_spin_lock_irqsave(&cache_lock, flags);
1291 1292 1293 1294

	event->hw.cqm_state = PERF_HES_STOPPED;
	rmid = event->hw.cqm_rmid;

1295
	if (__rmid_valid(rmid) && (mode & PERF_EF_START))
1296 1297
		intel_cqm_event_start(event, mode);

1298 1299
	raw_spin_unlock_irqrestore(&cache_lock, flags);

1300 1301 1302 1303 1304 1305
	return 0;
}

static void intel_cqm_event_destroy(struct perf_event *event)
{
	struct perf_event *group_other = NULL;
1306
	unsigned long flags;
1307 1308

	mutex_lock(&cache_mutex);
1309 1310 1311 1312 1313
	/*
	* Hold the cache_lock as mbm timer handlers could be
	* scanning the list of events.
	*/
	raw_spin_lock_irqsave(&cache_lock, flags);
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327

	/*
	 * If there's another event in this group...
	 */
	if (!list_empty(&event->hw.cqm_group_entry)) {
		group_other = list_first_entry(&event->hw.cqm_group_entry,
					       struct perf_event,
					       hw.cqm_group_entry);
		list_del(&event->hw.cqm_group_entry);
	}

	/*
	 * And we're the group leader..
	 */
1328
	if (cqm_group_leader(event)) {
1329 1330 1331 1332 1333 1334 1335 1336
		/*
		 * If there was a group_other, make that leader, otherwise
		 * destroy the group and return the RMID.
		 */
		if (group_other) {
			list_replace(&event->hw.cqm_groups_entry,
				     &group_other->hw.cqm_groups_entry);
		} else {
1337
			u32 rmid = event->hw.cqm_rmid;
1338

1339 1340
			if (__rmid_valid(rmid))
				__put_rmid(rmid);
1341 1342 1343 1344
			list_del(&event->hw.cqm_groups_entry);
		}
	}

1345 1346 1347 1348 1349 1350 1351 1352
	raw_spin_unlock_irqrestore(&cache_lock, flags);

	/*
	 * Stop the mbm overflow timers when the last event is destroyed.
	*/
	if (mbm_enabled && list_empty(&cache_groups))
		mbm_stop_timers();

1353 1354 1355 1356 1357 1358
	mutex_unlock(&cache_mutex);
}

static int intel_cqm_event_init(struct perf_event *event)
{
	struct perf_event *group = NULL;
1359
	bool rotate = false;
1360
	unsigned long flags;
1361 1362 1363 1364

	if (event->attr.type != intel_cqm_pmu.type)
		return -ENOENT;

1365 1366
	if ((event->attr.config < QOS_L3_OCCUP_EVENT_ID) ||
	     (event->attr.config > QOS_MBM_LOCAL_EVENT_ID))
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
		return -EINVAL;

	/* unsupported modes and filters */
	if (event->attr.exclude_user   ||
	    event->attr.exclude_kernel ||
	    event->attr.exclude_hv     ||
	    event->attr.exclude_idle   ||
	    event->attr.exclude_host   ||
	    event->attr.exclude_guest  ||
	    event->attr.sample_period) /* no sampling */
		return -EINVAL;

	INIT_LIST_HEAD(&event->hw.cqm_group_entry);
	INIT_LIST_HEAD(&event->hw.cqm_groups_entry);

	event->destroy = intel_cqm_event_destroy;

	mutex_lock(&cache_mutex);

1386 1387 1388 1389 1390 1391
	/*
	 * Start the mbm overflow timers when the first event is created.
	*/
	if (mbm_enabled && list_empty(&cache_groups))
		mbm_start_timers();

1392
	/* Will also set rmid */
1393
	intel_cqm_setup_event(event, &group);
1394

1395 1396 1397 1398 1399 1400
	/*
	* Hold the cache_lock as mbm timer handlers be
	* scanning the list of events.
	*/
	raw_spin_lock_irqsave(&cache_lock, flags);

1401 1402 1403 1404 1405 1406
	if (group) {
		list_add_tail(&event->hw.cqm_group_entry,
			      &group->hw.cqm_group_entry);
	} else {
		list_add_tail(&event->hw.cqm_groups_entry,
			      &cache_groups);
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416

		/*
		 * All RMIDs are either in use or have recently been
		 * used. Kick the rotation worker to clean/free some.
		 *
		 * We only do this for the group leader, rather than for
		 * every event in a group to save on needless work.
		 */
		if (!__rmid_valid(event->hw.cqm_rmid))
			rotate = true;
1417 1418
	}

1419
	raw_spin_unlock_irqrestore(&cache_lock, flags);
1420
	mutex_unlock(&cache_mutex);
1421 1422 1423 1424

	if (rotate)
		schedule_delayed_work(&intel_cqm_rmid_work, 0);

1425
	return 0;
1426 1427 1428 1429 1430 1431 1432 1433
}

EVENT_ATTR_STR(llc_occupancy, intel_cqm_llc, "event=0x01");
EVENT_ATTR_STR(llc_occupancy.per-pkg, intel_cqm_llc_pkg, "1");
EVENT_ATTR_STR(llc_occupancy.unit, intel_cqm_llc_unit, "Bytes");
EVENT_ATTR_STR(llc_occupancy.scale, intel_cqm_llc_scale, NULL);
EVENT_ATTR_STR(llc_occupancy.snapshot, intel_cqm_llc_snapshot, "1");

1434 1435 1436 1437 1438 1439 1440 1441 1442 1443
EVENT_ATTR_STR(total_bytes, intel_cqm_total_bytes, "event=0x02");
EVENT_ATTR_STR(total_bytes.per-pkg, intel_cqm_total_bytes_pkg, "1");
EVENT_ATTR_STR(total_bytes.unit, intel_cqm_total_bytes_unit, "MB");
EVENT_ATTR_STR(total_bytes.scale, intel_cqm_total_bytes_scale, "1e-6");

EVENT_ATTR_STR(local_bytes, intel_cqm_local_bytes, "event=0x03");
EVENT_ATTR_STR(local_bytes.per-pkg, intel_cqm_local_bytes_pkg, "1");
EVENT_ATTR_STR(local_bytes.unit, intel_cqm_local_bytes_unit, "MB");
EVENT_ATTR_STR(local_bytes.scale, intel_cqm_local_bytes_scale, "1e-6");

1444 1445 1446 1447 1448 1449 1450 1451 1452
static struct attribute *intel_cqm_events_attr[] = {
	EVENT_PTR(intel_cqm_llc),
	EVENT_PTR(intel_cqm_llc_pkg),
	EVENT_PTR(intel_cqm_llc_unit),
	EVENT_PTR(intel_cqm_llc_scale),
	EVENT_PTR(intel_cqm_llc_snapshot),
	NULL,
};

1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
static struct attribute *intel_mbm_events_attr[] = {
	EVENT_PTR(intel_cqm_total_bytes),
	EVENT_PTR(intel_cqm_local_bytes),
	EVENT_PTR(intel_cqm_total_bytes_pkg),
	EVENT_PTR(intel_cqm_local_bytes_pkg),
	EVENT_PTR(intel_cqm_total_bytes_unit),
	EVENT_PTR(intel_cqm_local_bytes_unit),
	EVENT_PTR(intel_cqm_total_bytes_scale),
	EVENT_PTR(intel_cqm_local_bytes_scale),
	NULL,
};

static struct attribute *intel_cmt_mbm_events_attr[] = {
	EVENT_PTR(intel_cqm_llc),
	EVENT_PTR(intel_cqm_total_bytes),
	EVENT_PTR(intel_cqm_local_bytes),
	EVENT_PTR(intel_cqm_llc_pkg),
	EVENT_PTR(intel_cqm_total_bytes_pkg),
	EVENT_PTR(intel_cqm_local_bytes_pkg),
	EVENT_PTR(intel_cqm_llc_unit),
	EVENT_PTR(intel_cqm_total_bytes_unit),
	EVENT_PTR(intel_cqm_local_bytes_unit),
	EVENT_PTR(intel_cqm_llc_scale),
	EVENT_PTR(intel_cqm_total_bytes_scale),
	EVENT_PTR(intel_cqm_local_bytes_scale),
	EVENT_PTR(intel_cqm_llc_snapshot),
	NULL,
};

1482 1483
static struct attribute_group intel_cqm_events_group = {
	.name = "events",
1484
	.attrs = NULL,
1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497
};

PMU_FORMAT_ATTR(event, "config:0-7");
static struct attribute *intel_cqm_formats_attr[] = {
	&format_attr_event.attr,
	NULL,
};

static struct attribute_group intel_cqm_format_group = {
	.name = "format",
	.attrs = intel_cqm_formats_attr,
};

1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549
static ssize_t
max_recycle_threshold_show(struct device *dev, struct device_attribute *attr,
			   char *page)
{
	ssize_t rv;

	mutex_lock(&cache_mutex);
	rv = snprintf(page, PAGE_SIZE-1, "%u\n", __intel_cqm_max_threshold);
	mutex_unlock(&cache_mutex);

	return rv;
}

static ssize_t
max_recycle_threshold_store(struct device *dev,
			    struct device_attribute *attr,
			    const char *buf, size_t count)
{
	unsigned int bytes, cachelines;
	int ret;

	ret = kstrtouint(buf, 0, &bytes);
	if (ret)
		return ret;

	mutex_lock(&cache_mutex);

	__intel_cqm_max_threshold = bytes;
	cachelines = bytes / cqm_l3_scale;

	/*
	 * The new maximum takes effect immediately.
	 */
	if (__intel_cqm_threshold > cachelines)
		__intel_cqm_threshold = cachelines;

	mutex_unlock(&cache_mutex);

	return count;
}

static DEVICE_ATTR_RW(max_recycle_threshold);

static struct attribute *intel_cqm_attrs[] = {
	&dev_attr_max_recycle_threshold.attr,
	NULL,
};

static const struct attribute_group intel_cqm_group = {
	.attrs = intel_cqm_attrs,
};

1550 1551 1552
static const struct attribute_group *intel_cqm_attr_groups[] = {
	&intel_cqm_events_group,
	&intel_cqm_format_group,
1553
	&intel_cqm_group,
1554 1555 1556 1557
	NULL,
};

static struct pmu intel_cqm_pmu = {
1558 1559 1560 1561 1562
	.hrtimer_interval_ms = RMID_DEFAULT_QUEUE_TIME,
	.attr_groups	     = intel_cqm_attr_groups,
	.task_ctx_nr	     = perf_sw_context,
	.event_init	     = intel_cqm_event_init,
	.add		     = intel_cqm_event_add,
1563
	.del		     = intel_cqm_event_stop,
1564 1565 1566 1567
	.start		     = intel_cqm_event_start,
	.stop		     = intel_cqm_event_stop,
	.read		     = intel_cqm_event_read,
	.count		     = intel_cqm_event_count,
1568 1569 1570 1571
};

static inline void cqm_pick_event_reader(int cpu)
{
1572
	int reader;
1573

1574 1575 1576 1577
	/* First online cpu in package becomes the reader */
	reader = cpumask_any_and(&cqm_cpumask, topology_core_cpumask(cpu));
	if (reader >= nr_cpu_ids)
		cpumask_set_cpu(cpu, &cqm_cpumask);
1578 1579
}

1580
static int intel_cqm_cpu_starting(unsigned int cpu)
1581
{
1582
	struct intel_pqr_state *state = &per_cpu(pqr_state, cpu);
1583 1584 1585
	struct cpuinfo_x86 *c = &cpu_data(cpu);

	state->rmid = 0;
1586 1587
	state->closid = 0;
	state->rmid_usecnt = 0;
1588 1589 1590

	WARN_ON(c->x86_cache_max_rmid != cqm_max_rmid);
	WARN_ON(c->x86_cache_occ_scale != cqm_l3_scale);
1591 1592 1593

	cqm_pick_event_reader(cpu);
	return 0;
1594 1595
}

1596
static int intel_cqm_cpu_exit(unsigned int cpu)
1597
{
1598
	int target;
1599

1600
	/* Is @cpu the current cqm reader for this package ? */
1601
	if (!cpumask_test_and_clear_cpu(cpu, &cqm_cpumask))
1602
		return 0;
1603

1604 1605
	/* Find another online reader in this package */
	target = cpumask_any_but(topology_core_cpumask(cpu), cpu);
1606

1607 1608
	if (target < nr_cpu_ids)
		cpumask_set_cpu(target, &cqm_cpumask);
1609

1610
	return 0;
1611 1612 1613 1614 1615 1616 1617
}

static const struct x86_cpu_id intel_cqm_match[] = {
	{ .vendor = X86_VENDOR_INTEL, .feature = X86_FEATURE_CQM_OCCUP_LLC },
	{}
};

1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
static void mbm_cleanup(void)
{
	if (!mbm_enabled)
		return;

	kfree(mbm_local);
	kfree(mbm_total);
	mbm_enabled = false;
}

static const struct x86_cpu_id intel_mbm_local_match[] = {
	{ .vendor = X86_VENDOR_INTEL, .feature = X86_FEATURE_CQM_MBM_LOCAL },
	{}
};

static const struct x86_cpu_id intel_mbm_total_match[] = {
	{ .vendor = X86_VENDOR_INTEL, .feature = X86_FEATURE_CQM_MBM_TOTAL },
	{}
};

static int intel_mbm_init(void)
{
1640
	int ret = 0, array_size, maxid = cqm_max_rmid + 1;
1641

1642 1643
	mbm_socket_max = topology_max_packages();
	array_size = sizeof(struct sample) * maxid * mbm_socket_max;
1644 1645 1646 1647 1648 1649
	mbm_local = kmalloc(array_size, GFP_KERNEL);
	if (!mbm_local)
		return -ENOMEM;

	mbm_total = kmalloc(array_size, GFP_KERNEL);
	if (!mbm_total) {
1650 1651
		ret = -ENOMEM;
		goto out;
1652 1653
	}

1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666
	array_size = sizeof(struct hrtimer) * mbm_socket_max;
	mbm_timers = kmalloc(array_size, GFP_KERNEL);
	if (!mbm_timers) {
		ret = -ENOMEM;
		goto out;
	}
	mbm_hrtimer_init();

out:
	if (ret)
		mbm_cleanup();

	return ret;
1667 1668
}

1669 1670
static int __init intel_cqm_init(void)
{
1671
	char *str = NULL, scale[20];
1672
	int cpu, ret;
1673

1674 1675 1676 1677 1678 1679 1680 1681
	if (x86_match_cpu(intel_cqm_match))
		cqm_enabled = true;

	if (x86_match_cpu(intel_mbm_local_match) &&
	     x86_match_cpu(intel_mbm_total_match))
		mbm_enabled = true;

	if (!cqm_enabled && !mbm_enabled)
1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694
		return -ENODEV;

	cqm_l3_scale = boot_cpu_data.x86_cache_occ_scale;

	/*
	 * It's possible that not all resources support the same number
	 * of RMIDs. Instead of making scheduling much more complicated
	 * (where we have to match a task's RMID to a cpu that supports
	 * that many RMIDs) just find the minimum RMIDs supported across
	 * all cpus.
	 *
	 * Also, check that the scales match on all cpus.
	 */
1695
	get_online_cpus();
1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708
	for_each_online_cpu(cpu) {
		struct cpuinfo_x86 *c = &cpu_data(cpu);

		if (c->x86_cache_max_rmid < cqm_max_rmid)
			cqm_max_rmid = c->x86_cache_max_rmid;

		if (c->x86_cache_occ_scale != cqm_l3_scale) {
			pr_err("Multiple LLC scale values, disabling\n");
			ret = -EINVAL;
			goto out;
		}
	}

1709 1710 1711 1712 1713 1714 1715 1716 1717 1718
	/*
	 * A reasonable upper limit on the max threshold is the number
	 * of lines tagged per RMID if all RMIDs have the same number of
	 * lines tagged in the LLC.
	 *
	 * For a 35MB LLC and 56 RMIDs, this is ~1.8% of the LLC.
	 */
	__intel_cqm_max_threshold =
		boot_cpu_data.x86_cache_size * 1024 / (cqm_max_rmid + 1);

1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731
	snprintf(scale, sizeof(scale), "%u", cqm_l3_scale);
	str = kstrdup(scale, GFP_KERNEL);
	if (!str) {
		ret = -ENOMEM;
		goto out;
	}

	event_attr_intel_cqm_llc_scale.event_str = str;

	ret = intel_cqm_setup_rmid_cache();
	if (ret)
		goto out;

1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743
	if (mbm_enabled)
		ret = intel_mbm_init();
	if (ret && !cqm_enabled)
		goto out;

	if (cqm_enabled && mbm_enabled)
		intel_cqm_events_group.attrs = intel_cmt_mbm_events_attr;
	else if (!cqm_enabled && mbm_enabled)
		intel_cqm_events_group.attrs = intel_mbm_events_attr;
	else if (cqm_enabled && !mbm_enabled)
		intel_cqm_events_group.attrs = intel_cqm_events_attr;

1744
	ret = perf_pmu_register(&intel_cqm_pmu, "intel_cqm", -1);
1745
	if (ret) {
1746
		pr_err("Intel CQM perf registration failed: %d\n", ret);
1747 1748
		goto out;
	}
1749

1750 1751 1752 1753
	if (cqm_enabled)
		pr_info("Intel CQM monitoring enabled\n");
	if (mbm_enabled)
		pr_info("Intel MBM enabled\n");
1754 1755

	/*
1756
	 * Setup the hot cpu notifier once we are sure cqm
1757 1758
	 * is enabled to avoid notifier leak.
	 */
1759 1760 1761 1762 1763 1764
	cpuhp_setup_state(CPUHP_AP_PERF_X86_CQM_STARTING,
			  "AP_PERF_X86_CQM_STARTING",
			  intel_cqm_cpu_starting, NULL);
	cpuhp_setup_state(CPUHP_AP_PERF_X86_CQM_ONLINE, "AP_PERF_X86_CQM_ONLINE",
			  NULL, intel_cqm_cpu_exit);

1765
out:
1766 1767
	put_online_cpus();

1768 1769 1770
	if (ret) {
		kfree(str);
		cqm_cleanup();
1771
		mbm_cleanup();
1772
	}
1773 1774 1775 1776

	return ret;
}
device_initcall(intel_cqm_init);