xref: /linux/fs/resctrl/monitor.c (revision 333f7de560e1196034b67db16916b10a0c529e1d)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Resource Director Technology(RDT)
4  * - Monitoring code
5  *
6  * Copyright (C) 2017 Intel Corporation
7  *
8  * Author:
9  *    Vikas Shivappa <vikas.shivappa@intel.com>
10  *
11  * This replaces the cqm.c based on perf but we reuse a lot of
12  * code and datastructures originally from Peter Zijlstra and Matt Fleming.
13  *
14  * More information about RDT be found in the Intel (R) x86 Architecture
15  * Software Developer Manual June 2016, volume 3, section 17.17.
16  */
17 
18 #define pr_fmt(fmt)	"resctrl: " fmt
19 
20 #include <linux/cpu.h>
21 #include <linux/resctrl.h>
22 #include <linux/sizes.h>
23 #include <linux/slab.h>
24 
25 #include "internal.h"
26 
27 #define CREATE_TRACE_POINTS
28 
29 #include "monitor_trace.h"
30 
31 /**
32  * struct rmid_entry - dirty tracking for all RMID.
33  * @closid:	The CLOSID for this entry.
34  * @rmid:	The RMID for this entry.
35  * @busy:	The number of domains with cached data using this RMID.
36  * @list:	Member of the rmid_free_lru list when busy == 0.
37  *
38  * Depending on the architecture the correct monitor is accessed using
39  * both @closid and @rmid, or @rmid only.
40  *
41  * Take the rdtgroup_mutex when accessing.
42  */
43 struct rmid_entry {
44 	u32				closid;
45 	u32				rmid;
46 	int				busy;
47 	struct list_head		list;
48 };
49 
50 /*
51  * @rmid_free_lru - A least recently used list of free RMIDs
52  *     These RMIDs are guaranteed to have an occupancy less than the
53  *     threshold occupancy
54  */
55 static LIST_HEAD(rmid_free_lru);
56 
57 /*
58  * @closid_num_dirty_rmid    The number of dirty RMID each CLOSID has.
59  *     Only allocated when CONFIG_RESCTRL_RMID_DEPENDS_ON_CLOSID is defined.
60  *     Indexed by CLOSID. Protected by rdtgroup_mutex.
61  */
62 static u32 *closid_num_dirty_rmid;
63 
64 /*
65  * @rmid_limbo_count - count of currently unused but (potentially)
66  *     dirty RMIDs.
67  *     This counts RMIDs that no one is currently using but that
68  *     may have a occupancy value > resctrl_rmid_realloc_threshold. User can
69  *     change the threshold occupancy value.
70  */
71 static unsigned int rmid_limbo_count;
72 
73 /*
74  * @rmid_entry - The entry in the limbo and free lists.
75  */
76 static struct rmid_entry	*rmid_ptrs;
77 
78 /*
79  * This is the threshold cache occupancy in bytes at which we will consider an
80  * RMID available for re-allocation.
81  */
82 unsigned int resctrl_rmid_realloc_threshold;
83 
84 /*
85  * This is the maximum value for the reallocation threshold, in bytes.
86  */
87 unsigned int resctrl_rmid_realloc_limit;
88 
89 /*
90  * x86 and arm64 differ in their handling of monitoring.
91  * x86's RMID are independent numbers, there is only one source of traffic
92  * with an RMID value of '1'.
93  * arm64's PMG extends the PARTID/CLOSID space, there are multiple sources of
94  * traffic with a PMG value of '1', one for each CLOSID, meaning the RMID
95  * value is no longer unique.
96  * To account for this, resctrl uses an index. On x86 this is just the RMID,
97  * on arm64 it encodes the CLOSID and RMID. This gives a unique number.
98  *
99  * The domain's rmid_busy_llc and rmid_ptrs[] are sized by index. The arch code
100  * must accept an attempt to read every index.
101  */
102 static inline struct rmid_entry *__rmid_entry(u32 idx)
103 {
104 	struct rmid_entry *entry;
105 	u32 closid, rmid;
106 
107 	entry = &rmid_ptrs[idx];
108 	resctrl_arch_rmid_idx_decode(idx, &closid, &rmid);
109 
110 	WARN_ON_ONCE(entry->closid != closid);
111 	WARN_ON_ONCE(entry->rmid != rmid);
112 
113 	return entry;
114 }
115 
116 static void limbo_release_entry(struct rmid_entry *entry)
117 {
118 	lockdep_assert_held(&rdtgroup_mutex);
119 
120 	rmid_limbo_count--;
121 	list_add_tail(&entry->list, &rmid_free_lru);
122 
123 	if (IS_ENABLED(CONFIG_RESCTRL_RMID_DEPENDS_ON_CLOSID))
124 		closid_num_dirty_rmid[entry->closid]--;
125 }
126 
127 /*
128  * Check the RMIDs that are marked as busy for this domain. If the
129  * reported LLC occupancy is below the threshold clear the busy bit and
130  * decrement the count. If the busy count gets to zero on an RMID, we
131  * free the RMID
132  */
133 void __check_limbo(struct rdt_l3_mon_domain *d, bool force_free)
134 {
135 	struct rdt_resource *r = resctrl_arch_get_resource(RDT_RESOURCE_L3);
136 	u32 idx_limit = resctrl_arch_system_num_rmid_idx();
137 	struct rmid_entry *entry;
138 	bool rmid_dirty = true;
139 	u32 idx, cur_idx = 1;
140 	void *arch_mon_ctx;
141 	void *arch_priv;
142 	u64 val = 0;
143 
144 	arch_priv = mon_event_all[QOS_L3_OCCUP_EVENT_ID].arch_priv;
145 	arch_mon_ctx = resctrl_arch_mon_ctx_alloc(r, QOS_L3_OCCUP_EVENT_ID);
146 	if (IS_ERR(arch_mon_ctx)) {
147 		pr_warn_ratelimited("Failed to allocate monitor context: %ld",
148 				    PTR_ERR(arch_mon_ctx));
149 		return;
150 	}
151 
152 	/*
153 	 * Skip RMID 0 and start from RMID 1 and check all the RMIDs that
154 	 * are marked as busy for occupancy < threshold. If the occupancy
155 	 * is less than the threshold decrement the busy counter of the
156 	 * RMID and move it to the free list when the counter reaches 0.
157 	 */
158 	for (;;) {
159 		idx = find_next_bit(d->rmid_busy_llc, idx_limit, cur_idx);
160 		if (idx >= idx_limit)
161 			break;
162 
163 		entry = __rmid_entry(idx);
164 		if (!force_free) {
165 			if (resctrl_arch_rmid_read(r, &d->hdr, entry->closid,
166 						   entry->rmid, QOS_L3_OCCUP_EVENT_ID,
167 						   arch_priv, &val, arch_mon_ctx)) {
168 				rmid_dirty = true;
169 			} else {
170 				rmid_dirty = (val >= resctrl_rmid_realloc_threshold);
171 
172 				/*
173 				 * x86's CLOSID and RMID are independent numbers,
174 				 * so the entry's CLOSID is an empty CLOSID
175 				 * (X86_RESCTRL_EMPTY_CLOSID). On Arm the RMID
176 				 * (PMG) extends the CLOSID (PARTID) space with
177 				 * bits that aren't used to select the configuration.
178 				 * It is thus necessary to track both CLOSID and
179 				 * RMID because there may be dependencies between
180 				 * them on some architectures.
181 				 */
182 				trace_mon_llc_occupancy_limbo(entry->closid, entry->rmid,
183 							      d->hdr.id, val);
184 			}
185 		}
186 
187 		if (force_free || !rmid_dirty) {
188 			clear_bit(idx, d->rmid_busy_llc);
189 			if (!--entry->busy)
190 				limbo_release_entry(entry);
191 		}
192 		cur_idx = idx + 1;
193 	}
194 
195 	resctrl_arch_mon_ctx_free(r, QOS_L3_OCCUP_EVENT_ID, arch_mon_ctx);
196 }
197 
198 bool has_busy_rmid(struct rdt_l3_mon_domain *d)
199 {
200 	u32 idx_limit = resctrl_arch_system_num_rmid_idx();
201 
202 	return find_first_bit(d->rmid_busy_llc, idx_limit) != idx_limit;
203 }
204 
205 static struct rmid_entry *resctrl_find_free_rmid(u32 closid)
206 {
207 	struct rmid_entry *itr;
208 	u32 itr_idx, cmp_idx;
209 
210 	if (list_empty(&rmid_free_lru))
211 		return rmid_limbo_count ? ERR_PTR(-EBUSY) : ERR_PTR(-ENOSPC);
212 
213 	list_for_each_entry(itr, &rmid_free_lru, list) {
214 		/*
215 		 * Get the index of this free RMID, and the index it would need
216 		 * to be if it were used with this CLOSID.
217 		 * If the CLOSID is irrelevant on this architecture, the two
218 		 * index values are always the same on every entry and thus the
219 		 * very first entry will be returned.
220 		 */
221 		itr_idx = resctrl_arch_rmid_idx_encode(itr->closid, itr->rmid);
222 		cmp_idx = resctrl_arch_rmid_idx_encode(closid, itr->rmid);
223 
224 		if (itr_idx == cmp_idx)
225 			return itr;
226 	}
227 
228 	return ERR_PTR(-ENOSPC);
229 }
230 
231 /**
232  * resctrl_find_cleanest_closid() - Find a CLOSID where all the associated
233  *                                  RMID are clean, or the CLOSID that has
234  *                                  the most clean RMID.
235  *
236  * MPAM's equivalent of RMID are per-CLOSID, meaning a freshly allocated CLOSID
237  * may not be able to allocate clean RMID. To avoid this the allocator will
238  * choose the CLOSID with the most clean RMID.
239  *
240  * When the CLOSID and RMID are independent numbers, the first free CLOSID will
241  * be returned.
242  *
243  * Return: Free CLOSID on success, < 0 on failure.
244  */
245 int resctrl_find_cleanest_closid(void)
246 {
247 	u32 cleanest_closid = ~0;
248 	int i = 0;
249 
250 	lockdep_assert_held(&rdtgroup_mutex);
251 
252 	if (!IS_ENABLED(CONFIG_RESCTRL_RMID_DEPENDS_ON_CLOSID))
253 		return -EIO;
254 
255 	for (i = 0; i < closids_supported(); i++) {
256 		int num_dirty;
257 
258 		if (closid_allocated(i))
259 			continue;
260 
261 		num_dirty = closid_num_dirty_rmid[i];
262 		if (num_dirty == 0)
263 			return i;
264 
265 		if (cleanest_closid == ~0)
266 			cleanest_closid = i;
267 
268 		if (num_dirty < closid_num_dirty_rmid[cleanest_closid])
269 			cleanest_closid = i;
270 	}
271 
272 	if (cleanest_closid == ~0)
273 		return -ENOSPC;
274 
275 	return cleanest_closid;
276 }
277 
278 /*
279  * For MPAM the RMID value is not unique, and has to be considered with
280  * the CLOSID. The (CLOSID, RMID) pair is allocated on all domains, which
281  * allows all domains to be managed by a single free list.
282  * Each domain also has a rmid_busy_llc to reduce the work of the limbo handler.
283  */
284 int alloc_rmid(u32 closid)
285 {
286 	struct rmid_entry *entry;
287 
288 	lockdep_assert_held(&rdtgroup_mutex);
289 
290 	entry = resctrl_find_free_rmid(closid);
291 	if (IS_ERR(entry))
292 		return PTR_ERR(entry);
293 
294 	list_del(&entry->list);
295 	return entry->rmid;
296 }
297 
298 static void add_rmid_to_limbo(struct rmid_entry *entry)
299 {
300 	struct rdt_resource *r = resctrl_arch_get_resource(RDT_RESOURCE_L3);
301 	struct rdt_l3_mon_domain *d;
302 	u32 idx;
303 
304 	lockdep_assert_held(&rdtgroup_mutex);
305 
306 	/* Walking r->domains, ensure it can't race with cpuhp */
307 	lockdep_assert_cpus_held();
308 
309 	idx = resctrl_arch_rmid_idx_encode(entry->closid, entry->rmid);
310 
311 	entry->busy = 0;
312 	list_for_each_entry(d, &r->mon_domains, hdr.list) {
313 		/*
314 		 * For the first limbo RMID in the domain,
315 		 * setup up the limbo worker.
316 		 */
317 		if (!has_busy_rmid(d))
318 			cqm_setup_limbo_handler(d, CQM_LIMBOCHECK_INTERVAL,
319 						RESCTRL_PICK_ANY_CPU);
320 		set_bit(idx, d->rmid_busy_llc);
321 		entry->busy++;
322 	}
323 
324 	rmid_limbo_count++;
325 	if (IS_ENABLED(CONFIG_RESCTRL_RMID_DEPENDS_ON_CLOSID))
326 		closid_num_dirty_rmid[entry->closid]++;
327 }
328 
329 void free_rmid(u32 closid, u32 rmid)
330 {
331 	u32 idx = resctrl_arch_rmid_idx_encode(closid, rmid);
332 	struct rmid_entry *entry;
333 
334 	lockdep_assert_held(&rdtgroup_mutex);
335 
336 	/*
337 	 * Do not allow the default rmid to be free'd. Comparing by index
338 	 * allows architectures that ignore the closid parameter to avoid an
339 	 * unnecessary check.
340 	 */
341 	if (!resctrl_arch_mon_capable() ||
342 	    idx == resctrl_arch_rmid_idx_encode(RESCTRL_RESERVED_CLOSID,
343 						RESCTRL_RESERVED_RMID))
344 		return;
345 
346 	entry = __rmid_entry(idx);
347 
348 	if (resctrl_is_mon_event_enabled(QOS_L3_OCCUP_EVENT_ID))
349 		add_rmid_to_limbo(entry);
350 	else
351 		list_add_tail(&entry->list, &rmid_free_lru);
352 }
353 
354 static struct mbm_state *get_mbm_state(struct rdt_l3_mon_domain *d, u32 closid,
355 				       u32 rmid, enum resctrl_event_id evtid)
356 {
357 	u32 idx = resctrl_arch_rmid_idx_encode(closid, rmid);
358 	struct mbm_state *state;
359 
360 	if (!resctrl_is_mbm_event(evtid))
361 		return NULL;
362 
363 	state = d->mbm_states[MBM_STATE_IDX(evtid)];
364 
365 	return state ? &state[idx] : NULL;
366 }
367 
368 /*
369  * mbm_cntr_get() - Return the counter ID for the matching @evtid and @rdtgrp.
370  *
371  * Return:
372  * Valid counter ID on success, or -ENOENT on failure.
373  */
374 static int mbm_cntr_get(struct rdt_resource *r, struct rdt_l3_mon_domain *d,
375 			struct rdtgroup *rdtgrp, enum resctrl_event_id evtid)
376 {
377 	int cntr_id;
378 
379 	if (!r->mon.mbm_cntr_assignable)
380 		return -ENOENT;
381 
382 	if (!resctrl_is_mbm_event(evtid))
383 		return -ENOENT;
384 
385 	for (cntr_id = 0; cntr_id < r->mon.num_mbm_cntrs; cntr_id++) {
386 		if (d->cntr_cfg[cntr_id].rdtgrp == rdtgrp &&
387 		    d->cntr_cfg[cntr_id].evtid == evtid)
388 			return cntr_id;
389 	}
390 
391 	return -ENOENT;
392 }
393 
394 /*
395  * mbm_cntr_alloc() - Initialize and return a new counter ID in the domain @d.
396  * Caller must ensure that the specified event is not assigned already.
397  *
398  * Return:
399  * Valid counter ID on success, or -ENOSPC on failure.
400  */
401 static int mbm_cntr_alloc(struct rdt_resource *r, struct rdt_l3_mon_domain *d,
402 			  struct rdtgroup *rdtgrp, enum resctrl_event_id evtid)
403 {
404 	int cntr_id;
405 
406 	for (cntr_id = 0; cntr_id < r->mon.num_mbm_cntrs; cntr_id++) {
407 		if (!d->cntr_cfg[cntr_id].rdtgrp) {
408 			d->cntr_cfg[cntr_id].rdtgrp = rdtgrp;
409 			d->cntr_cfg[cntr_id].evtid = evtid;
410 			return cntr_id;
411 		}
412 	}
413 
414 	return -ENOSPC;
415 }
416 
417 /*
418  * mbm_cntr_free() - Clear the counter ID configuration details in the domain @d.
419  */
420 static void mbm_cntr_free(struct rdt_l3_mon_domain *d, int cntr_id)
421 {
422 	memset(&d->cntr_cfg[cntr_id], 0, sizeof(*d->cntr_cfg));
423 }
424 
425 static int __l3_mon_event_count(struct rdtgroup *rdtgrp, struct rmid_read *rr)
426 {
427 	int cpu = smp_processor_id();
428 	u32 closid = rdtgrp->closid;
429 	u32 rmid = rdtgrp->mon.rmid;
430 	struct rdt_l3_mon_domain *d;
431 	int cntr_id = -ENOENT;
432 	struct mbm_state *m;
433 	u64 tval = 0;
434 
435 	if (!domain_header_is_valid(rr->hdr, RESCTRL_MON_DOMAIN, RDT_RESOURCE_L3)) {
436 		rr->err = -EIO;
437 		return -EINVAL;
438 	}
439 	d = container_of(rr->hdr, struct rdt_l3_mon_domain, hdr);
440 
441 	if (rr->is_mbm_cntr) {
442 		cntr_id = mbm_cntr_get(rr->r, d, rdtgrp, rr->evt->evtid);
443 		if (cntr_id < 0) {
444 			rr->err = -ENOENT;
445 			return -EINVAL;
446 		}
447 	}
448 
449 	if (rr->first) {
450 		if (rr->is_mbm_cntr)
451 			resctrl_arch_reset_cntr(rr->r, d, closid, rmid, cntr_id, rr->evt->evtid);
452 		else
453 			resctrl_arch_reset_rmid(rr->r, d, closid, rmid, rr->evt->evtid);
454 		m = get_mbm_state(d, closid, rmid, rr->evt->evtid);
455 		if (m)
456 			memset(m, 0, sizeof(struct mbm_state));
457 		return 0;
458 	}
459 
460 	/* Reading a single domain, must be on a CPU in that domain. */
461 	if (!cpumask_test_cpu(cpu, &d->hdr.cpu_mask))
462 		return -EINVAL;
463 	if (rr->is_mbm_cntr)
464 		rr->err = resctrl_arch_cntr_read(rr->r, d, closid, rmid, cntr_id,
465 						 rr->evt->evtid, &tval);
466 	else
467 		rr->err = resctrl_arch_rmid_read(rr->r, rr->hdr, closid, rmid,
468 						 rr->evt->evtid, rr->evt->arch_priv,
469 						 &tval, rr->arch_mon_ctx);
470 	if (rr->err)
471 		return rr->err;
472 
473 	rr->val += tval;
474 
475 	return 0;
476 }
477 
478 static int __l3_mon_event_count_sum(struct rdtgroup *rdtgrp, struct rmid_read *rr)
479 {
480 	int cpu = smp_processor_id();
481 	u32 closid = rdtgrp->closid;
482 	u32 rmid = rdtgrp->mon.rmid;
483 	struct rdt_l3_mon_domain *d;
484 	u64 tval = 0;
485 	int err, ret;
486 
487 	/*
488 	 * Summing across domains is only done for systems that implement
489 	 * Sub-NUMA Cluster. There is no overlap with systems that support
490 	 * assignable counters.
491 	 */
492 	if (rr->is_mbm_cntr) {
493 		pr_warn_once("Summing domains using assignable counters is not supported\n");
494 		rr->err = -EINVAL;
495 		return -EINVAL;
496 	}
497 
498 	/* Summing domains that share a cache, must be on a CPU for that cache. */
499 	if (!cpumask_test_cpu(cpu, &rr->ci->shared_cpu_map))
500 		return -EINVAL;
501 
502 	/*
503 	 * Legacy files must report the sum of an event across all
504 	 * domains that share the same L3 cache instance.
505 	 * Report success if a read from any domain succeeds, -EINVAL
506 	 * (translated to "Unavailable" for user space) if reading from
507 	 * all domains fail for any reason.
508 	 */
509 	ret = -EINVAL;
510 	list_for_each_entry(d, &rr->r->mon_domains, hdr.list) {
511 		if (d->ci_id != rr->ci->id)
512 			continue;
513 		err = resctrl_arch_rmid_read(rr->r, &d->hdr, closid, rmid,
514 					     rr->evt->evtid, rr->evt->arch_priv,
515 					     &tval, rr->arch_mon_ctx);
516 		if (!err) {
517 			rr->val += tval;
518 			ret = 0;
519 		}
520 	}
521 
522 	if (ret)
523 		rr->err = ret;
524 
525 	return ret;
526 }
527 
528 static int __mon_event_count(struct rdtgroup *rdtgrp, struct rmid_read *rr)
529 {
530 	switch (rr->r->rid) {
531 	case RDT_RESOURCE_L3:
532 		WARN_ON_ONCE(rr->evt->any_cpu);
533 		if (rr->hdr)
534 			return __l3_mon_event_count(rdtgrp, rr);
535 		else
536 			return __l3_mon_event_count_sum(rdtgrp, rr);
537 	case RDT_RESOURCE_PERF_PKG: {
538 		u64 tval = 0;
539 
540 		rr->err = resctrl_arch_rmid_read(rr->r, rr->hdr, rdtgrp->closid,
541 						 rdtgrp->mon.rmid, rr->evt->evtid,
542 						 rr->evt->arch_priv,
543 						 &tval, rr->arch_mon_ctx);
544 		if (rr->err)
545 			return rr->err;
546 
547 		rr->val += tval;
548 
549 		return 0;
550 	}
551 	default:
552 		rr->err = -EINVAL;
553 		return -EINVAL;
554 	}
555 }
556 
557 /*
558  * mbm_bw_count() - Update bw count from values previously read by
559  *		    __mon_event_count().
560  * @rdtgrp:	resctrl group associated with the CLOSID and RMID to identify
561  *		the cached mbm_state.
562  * @rr:		The struct rmid_read populated by __mon_event_count().
563  *
564  * Supporting function to calculate the memory bandwidth
565  * and delta bandwidth in MBps. The chunks value previously read by
566  * __mon_event_count() is compared with the chunks value from the previous
567  * invocation. This must be called once per second to maintain values in MBps.
568  */
569 static void mbm_bw_count(struct rdtgroup *rdtgrp, struct rmid_read *rr)
570 {
571 	u64 cur_bw, bytes, cur_bytes;
572 	u32 closid = rdtgrp->closid;
573 	u32 rmid = rdtgrp->mon.rmid;
574 	struct rdt_l3_mon_domain *d;
575 	struct mbm_state *m;
576 
577 	if (!domain_header_is_valid(rr->hdr, RESCTRL_MON_DOMAIN, RDT_RESOURCE_L3))
578 		return;
579 	d = container_of(rr->hdr, struct rdt_l3_mon_domain, hdr);
580 	m = get_mbm_state(d, closid, rmid, rr->evt->evtid);
581 	if (WARN_ON_ONCE(!m))
582 		return;
583 
584 	cur_bytes = rr->val;
585 	bytes = cur_bytes - m->prev_bw_bytes;
586 	m->prev_bw_bytes = cur_bytes;
587 
588 	cur_bw = bytes / SZ_1M;
589 
590 	m->prev_bw = cur_bw;
591 }
592 
593 /*
594  * This is scheduled by mon_event_read() to read the CQM/MBM counters
595  * on a domain.
596  */
597 void mon_event_count(void *info)
598 {
599 	struct rdtgroup *rdtgrp, *entry;
600 	struct rmid_read *rr = info;
601 	struct list_head *head;
602 	int ret;
603 
604 	rdtgrp = rr->rgrp;
605 
606 	ret = __mon_event_count(rdtgrp, rr);
607 
608 	/*
609 	 * For Ctrl groups read data from child monitor groups and
610 	 * add them together. Count events which are read successfully.
611 	 * Discard the rmid_read's reporting errors.
612 	 */
613 	head = &rdtgrp->mon.crdtgrp_list;
614 
615 	if (rdtgrp->type == RDTCTRL_GROUP) {
616 		list_for_each_entry(entry, head, mon.crdtgrp_list) {
617 			if (__mon_event_count(entry, rr) == 0)
618 				ret = 0;
619 		}
620 	}
621 
622 	/*
623 	 * __mon_event_count() calls for newly created monitor groups may
624 	 * report -EINVAL/Unavailable if the monitor hasn't seen any traffic.
625 	 * Discard error if any of the monitor event reads succeeded.
626 	 */
627 	if (ret == 0)
628 		rr->err = 0;
629 }
630 
631 static struct rdt_ctrl_domain *get_ctrl_domain_from_cpu(int cpu,
632 							struct rdt_resource *r)
633 {
634 	struct rdt_ctrl_domain *d;
635 
636 	lockdep_assert_cpus_held();
637 
638 	list_for_each_entry(d, &r->ctrl_domains, hdr.list) {
639 		/* Find the domain that contains this CPU */
640 		if (cpumask_test_cpu(cpu, &d->hdr.cpu_mask))
641 			return d;
642 	}
643 
644 	return NULL;
645 }
646 
647 /*
648  * Feedback loop for MBA software controller (mba_sc)
649  *
650  * mba_sc is a feedback loop where we periodically read MBM counters and
651  * adjust the bandwidth percentage values via the IA32_MBA_THRTL_MSRs so
652  * that:
653  *
654  *   current bandwidth(cur_bw) < user specified bandwidth(user_bw)
655  *
656  * This uses the MBM counters to measure the bandwidth and MBA throttle
657  * MSRs to control the bandwidth for a particular rdtgrp. It builds on the
658  * fact that resctrl rdtgroups have both monitoring and control.
659  *
660  * The frequency of the checks is 1s and we just tag along the MBM overflow
661  * timer. Having 1s interval makes the calculation of bandwidth simpler.
662  *
663  * Although MBA's goal is to restrict the bandwidth to a maximum, there may
664  * be a need to increase the bandwidth to avoid unnecessarily restricting
665  * the L2 <-> L3 traffic.
666  *
667  * Since MBA controls the L2 external bandwidth where as MBM measures the
668  * L3 external bandwidth the following sequence could lead to such a
669  * situation.
670  *
671  * Consider an rdtgroup which had high L3 <-> memory traffic in initial
672  * phases -> mba_sc kicks in and reduced bandwidth percentage values -> but
673  * after some time rdtgroup has mostly L2 <-> L3 traffic.
674  *
675  * In this case we may restrict the rdtgroup's L2 <-> L3 traffic as its
676  * throttle MSRs already have low percentage values.  To avoid
677  * unnecessarily restricting such rdtgroups, we also increase the bandwidth.
678  */
679 static void update_mba_bw(struct rdtgroup *rgrp, struct rdt_l3_mon_domain *dom_mbm)
680 {
681 	u32 closid, rmid, cur_msr_val, new_msr_val;
682 	struct mbm_state *pmbm_data, *cmbm_data;
683 	struct rdt_ctrl_domain *dom_mba;
684 	enum resctrl_event_id evt_id;
685 	struct rdt_resource *r_mba;
686 	struct list_head *head;
687 	struct rdtgroup *entry;
688 	u32 cur_bw, user_bw;
689 
690 	r_mba = resctrl_arch_get_resource(RDT_RESOURCE_MBA);
691 	evt_id = rgrp->mba_mbps_event;
692 
693 	closid = rgrp->closid;
694 	rmid = rgrp->mon.rmid;
695 	pmbm_data = get_mbm_state(dom_mbm, closid, rmid, evt_id);
696 	if (WARN_ON_ONCE(!pmbm_data))
697 		return;
698 
699 	dom_mba = get_ctrl_domain_from_cpu(smp_processor_id(), r_mba);
700 	if (!dom_mba) {
701 		pr_warn_once("Failure to get domain for MBA update\n");
702 		return;
703 	}
704 
705 	cur_bw = pmbm_data->prev_bw;
706 	user_bw = dom_mba->mbps_val[closid];
707 
708 	/* MBA resource doesn't support CDP */
709 	cur_msr_val = resctrl_arch_get_config(r_mba, dom_mba, closid, CDP_NONE);
710 
711 	/*
712 	 * For Ctrl groups read data from child monitor groups.
713 	 */
714 	head = &rgrp->mon.crdtgrp_list;
715 	list_for_each_entry(entry, head, mon.crdtgrp_list) {
716 		cmbm_data = get_mbm_state(dom_mbm, entry->closid, entry->mon.rmid, evt_id);
717 		if (WARN_ON_ONCE(!cmbm_data))
718 			return;
719 		cur_bw += cmbm_data->prev_bw;
720 	}
721 
722 	/*
723 	 * Scale up/down the bandwidth linearly for the ctrl group.  The
724 	 * bandwidth step is the bandwidth granularity specified by the
725 	 * hardware.
726 	 * Always increase throttling if current bandwidth is above the
727 	 * target set by user.
728 	 * But avoid thrashing up and down on every poll by checking
729 	 * whether a decrease in throttling is likely to push the group
730 	 * back over target. E.g. if currently throttling to 30% of bandwidth
731 	 * on a system with 10% granularity steps, check whether moving to
732 	 * 40% would go past the limit by multiplying current bandwidth by
733 	 * "(30 + 10) / 30".
734 	 */
735 	if (cur_msr_val > r_mba->membw.min_bw && user_bw < cur_bw) {
736 		new_msr_val = cur_msr_val - r_mba->membw.bw_gran;
737 	} else if (cur_msr_val < MAX_MBA_BW &&
738 		   (user_bw > (cur_bw * (cur_msr_val + r_mba->membw.min_bw) / cur_msr_val))) {
739 		new_msr_val = cur_msr_val + r_mba->membw.bw_gran;
740 	} else {
741 		return;
742 	}
743 
744 	resctrl_arch_update_one(r_mba, dom_mba, closid, CDP_NONE, new_msr_val);
745 }
746 
747 static void mbm_update_one_event(struct rdt_resource *r, struct rdt_l3_mon_domain *d,
748 				 struct rdtgroup *rdtgrp, enum resctrl_event_id evtid)
749 {
750 	struct rmid_read rr = {0};
751 
752 	rr.r = r;
753 	rr.hdr = &d->hdr;
754 	rr.evt = &mon_event_all[evtid];
755 	if (resctrl_arch_mbm_cntr_assign_enabled(r)) {
756 		rr.is_mbm_cntr = true;
757 	} else {
758 		rr.arch_mon_ctx = resctrl_arch_mon_ctx_alloc(rr.r, evtid);
759 		if (IS_ERR(rr.arch_mon_ctx)) {
760 			pr_warn_ratelimited("Failed to allocate monitor context: %ld",
761 					    PTR_ERR(rr.arch_mon_ctx));
762 			return;
763 		}
764 	}
765 
766 	__mon_event_count(rdtgrp, &rr);
767 
768 	/*
769 	 * If the software controller is enabled, compute the
770 	 * bandwidth for this event id.
771 	 */
772 	if (is_mba_sc(NULL))
773 		mbm_bw_count(rdtgrp, &rr);
774 
775 	if (rr.arch_mon_ctx)
776 		resctrl_arch_mon_ctx_free(rr.r, evtid, rr.arch_mon_ctx);
777 }
778 
779 static void mbm_update(struct rdt_resource *r, struct rdt_l3_mon_domain *d,
780 		       struct rdtgroup *rdtgrp)
781 {
782 	/*
783 	 * This is protected from concurrent reads from user as both
784 	 * the user and overflow handler hold the global mutex.
785 	 */
786 	if (resctrl_is_mon_event_enabled(QOS_L3_MBM_TOTAL_EVENT_ID))
787 		mbm_update_one_event(r, d, rdtgrp, QOS_L3_MBM_TOTAL_EVENT_ID);
788 
789 	if (resctrl_is_mon_event_enabled(QOS_L3_MBM_LOCAL_EVENT_ID))
790 		mbm_update_one_event(r, d, rdtgrp, QOS_L3_MBM_LOCAL_EVENT_ID);
791 }
792 
793 /*
794  * Handler to scan the limbo list and move the RMIDs
795  * to free list whose occupancy < threshold_occupancy.
796  */
797 void cqm_handle_limbo(struct work_struct *work)
798 {
799 	unsigned long delay = msecs_to_jiffies(CQM_LIMBOCHECK_INTERVAL);
800 	struct rdt_l3_mon_domain *d;
801 
802 	cpus_read_lock();
803 	mutex_lock(&rdtgroup_mutex);
804 
805 	d = container_of(work, struct rdt_l3_mon_domain, cqm_limbo.work);
806 
807 	__check_limbo(d, false);
808 
809 	if (has_busy_rmid(d)) {
810 		d->cqm_work_cpu = cpumask_any_housekeeping(&d->hdr.cpu_mask,
811 							   RESCTRL_PICK_ANY_CPU);
812 		schedule_delayed_work_on(d->cqm_work_cpu, &d->cqm_limbo,
813 					 delay);
814 	}
815 
816 	mutex_unlock(&rdtgroup_mutex);
817 	cpus_read_unlock();
818 }
819 
820 /**
821  * cqm_setup_limbo_handler() - Schedule the limbo handler to run for this
822  *                             domain.
823  * @dom:           The domain the limbo handler should run for.
824  * @delay_ms:      How far in the future the handler should run.
825  * @exclude_cpu:   Which CPU the handler should not run on,
826  *		   RESCTRL_PICK_ANY_CPU to pick any CPU.
827  */
828 void cqm_setup_limbo_handler(struct rdt_l3_mon_domain *dom, unsigned long delay_ms,
829 			     int exclude_cpu)
830 {
831 	unsigned long delay = msecs_to_jiffies(delay_ms);
832 	int cpu;
833 
834 	cpu = cpumask_any_housekeeping(&dom->hdr.cpu_mask, exclude_cpu);
835 	dom->cqm_work_cpu = cpu;
836 
837 	if (cpu < nr_cpu_ids)
838 		schedule_delayed_work_on(cpu, &dom->cqm_limbo, delay);
839 }
840 
841 void mbm_handle_overflow(struct work_struct *work)
842 {
843 	unsigned long delay = msecs_to_jiffies(MBM_OVERFLOW_INTERVAL);
844 	struct rdtgroup *prgrp, *crgrp;
845 	struct rdt_l3_mon_domain *d;
846 	struct list_head *head;
847 	struct rdt_resource *r;
848 
849 	cpus_read_lock();
850 	mutex_lock(&rdtgroup_mutex);
851 
852 	/*
853 	 * If the filesystem has been unmounted this work no longer needs to
854 	 * run.
855 	 */
856 	if (!resctrl_mounted || !resctrl_arch_mon_capable())
857 		goto out_unlock;
858 
859 	r = resctrl_arch_get_resource(RDT_RESOURCE_L3);
860 	d = container_of(work, struct rdt_l3_mon_domain, mbm_over.work);
861 
862 	list_for_each_entry(prgrp, &rdt_all_groups, rdtgroup_list) {
863 		mbm_update(r, d, prgrp);
864 
865 		head = &prgrp->mon.crdtgrp_list;
866 		list_for_each_entry(crgrp, head, mon.crdtgrp_list)
867 			mbm_update(r, d, crgrp);
868 
869 		if (is_mba_sc(NULL))
870 			update_mba_bw(prgrp, d);
871 	}
872 
873 	/*
874 	 * Re-check for housekeeping CPUs. This allows the overflow handler to
875 	 * move off a nohz_full CPU quickly.
876 	 */
877 	d->mbm_work_cpu = cpumask_any_housekeeping(&d->hdr.cpu_mask,
878 						   RESCTRL_PICK_ANY_CPU);
879 	schedule_delayed_work_on(d->mbm_work_cpu, &d->mbm_over, delay);
880 
881 out_unlock:
882 	mutex_unlock(&rdtgroup_mutex);
883 	cpus_read_unlock();
884 }
885 
886 /**
887  * mbm_setup_overflow_handler() - Schedule the overflow handler to run for this
888  *                                domain.
889  * @dom:           The domain the overflow handler should run for.
890  * @delay_ms:      How far in the future the handler should run.
891  * @exclude_cpu:   Which CPU the handler should not run on,
892  *		   RESCTRL_PICK_ANY_CPU to pick any CPU.
893  */
894 void mbm_setup_overflow_handler(struct rdt_l3_mon_domain *dom, unsigned long delay_ms,
895 				int exclude_cpu)
896 {
897 	unsigned long delay = msecs_to_jiffies(delay_ms);
898 	int cpu;
899 
900 	/*
901 	 * When a domain comes online there is no guarantee the filesystem is
902 	 * mounted. If not, there is no need to catch counter overflow.
903 	 */
904 	if (!resctrl_mounted || !resctrl_arch_mon_capable())
905 		return;
906 	cpu = cpumask_any_housekeeping(&dom->hdr.cpu_mask, exclude_cpu);
907 	dom->mbm_work_cpu = cpu;
908 
909 	if (cpu < nr_cpu_ids)
910 		schedule_delayed_work_on(cpu, &dom->mbm_over, delay);
911 }
912 
913 int setup_rmid_lru_list(void)
914 {
915 	struct rmid_entry *entry = NULL;
916 	u32 idx_limit;
917 	u32 idx;
918 	int i;
919 
920 	if (!resctrl_arch_mon_capable())
921 		return 0;
922 
923 	/*
924 	 * Called on every mount, but the number of RMIDs cannot change
925 	 * after the first mount, so keep using the same set of rmid_ptrs[]
926 	 * until resctrl_exit(). Note that the limbo handler continues to
927 	 * access rmid_ptrs[] after resctrl is unmounted.
928 	 */
929 	if (rmid_ptrs)
930 		return 0;
931 
932 	idx_limit = resctrl_arch_system_num_rmid_idx();
933 	rmid_ptrs = kzalloc_objs(struct rmid_entry, idx_limit);
934 	if (!rmid_ptrs)
935 		return -ENOMEM;
936 
937 	for (i = 0; i < idx_limit; i++) {
938 		entry = &rmid_ptrs[i];
939 		INIT_LIST_HEAD(&entry->list);
940 
941 		resctrl_arch_rmid_idx_decode(i, &entry->closid, &entry->rmid);
942 		list_add_tail(&entry->list, &rmid_free_lru);
943 	}
944 
945 	/*
946 	 * RESCTRL_RESERVED_CLOSID and RESCTRL_RESERVED_RMID are special and
947 	 * are always allocated. These are used for the rdtgroup_default
948 	 * control group, which was setup earlier in rdtgroup_setup_default().
949 	 */
950 	idx = resctrl_arch_rmid_idx_encode(RESCTRL_RESERVED_CLOSID,
951 					   RESCTRL_RESERVED_RMID);
952 	entry = __rmid_entry(idx);
953 	list_del(&entry->list);
954 
955 	return 0;
956 }
957 
958 void free_rmid_lru_list(void)
959 {
960 	if (!resctrl_arch_mon_capable())
961 		return;
962 
963 	mutex_lock(&rdtgroup_mutex);
964 	kfree(rmid_ptrs);
965 	rmid_ptrs = NULL;
966 	mutex_unlock(&rdtgroup_mutex);
967 }
968 
969 #define MON_EVENT(_eventid, _name, _res, _fp)	\
970 	[_eventid] = {				\
971 	.name			= _name,	\
972 	.evtid			= _eventid,	\
973 	.rid			= _res,		\
974 	.is_floating_point	= _fp,		\
975 }
976 
977 /*
978  * All available events. Architecture code marks the ones that
979  * are supported by a system using resctrl_enable_mon_event()
980  * to set .enabled.
981  */
982 struct mon_evt mon_event_all[QOS_NUM_EVENTS] = {
983 	MON_EVENT(QOS_L3_OCCUP_EVENT_ID,		"llc_occupancy",	RDT_RESOURCE_L3,	false),
984 	MON_EVENT(QOS_L3_MBM_TOTAL_EVENT_ID,		"mbm_total_bytes",	RDT_RESOURCE_L3,	false),
985 	MON_EVENT(QOS_L3_MBM_LOCAL_EVENT_ID,		"mbm_local_bytes",	RDT_RESOURCE_L3,	false),
986 	MON_EVENT(PMT_EVENT_ENERGY,			"core_energy",		RDT_RESOURCE_PERF_PKG,	true),
987 	MON_EVENT(PMT_EVENT_ACTIVITY,			"activity",		RDT_RESOURCE_PERF_PKG,	true),
988 	MON_EVENT(PMT_EVENT_STALLS_LLC_HIT,		"stalls_llc_hit",	RDT_RESOURCE_PERF_PKG,	false),
989 	MON_EVENT(PMT_EVENT_C1_RES,			"c1_res",		RDT_RESOURCE_PERF_PKG,	false),
990 	MON_EVENT(PMT_EVENT_UNHALTED_CORE_CYCLES,	"unhalted_core_cycles",	RDT_RESOURCE_PERF_PKG,	false),
991 	MON_EVENT(PMT_EVENT_STALLS_LLC_MISS,		"stalls_llc_miss",	RDT_RESOURCE_PERF_PKG,	false),
992 	MON_EVENT(PMT_EVENT_AUTO_C6_RES,		"c6_res",		RDT_RESOURCE_PERF_PKG,	false),
993 	MON_EVENT(PMT_EVENT_UNHALTED_REF_CYCLES,	"unhalted_ref_cycles",	RDT_RESOURCE_PERF_PKG,	false),
994 	MON_EVENT(PMT_EVENT_UOPS_RETIRED,		"uops_retired",		RDT_RESOURCE_PERF_PKG,	false),
995 };
996 
997 bool resctrl_enable_mon_event(enum resctrl_event_id eventid, bool any_cpu,
998 			      unsigned int binary_bits, void *arch_priv)
999 {
1000 	if (WARN_ON_ONCE(eventid < QOS_FIRST_EVENT || eventid >= QOS_NUM_EVENTS ||
1001 			 binary_bits > MAX_BINARY_BITS))
1002 		return false;
1003 	if (mon_event_all[eventid].enabled) {
1004 		pr_warn("Duplicate enable for event %d\n", eventid);
1005 		return false;
1006 	}
1007 	if (binary_bits && !mon_event_all[eventid].is_floating_point) {
1008 		pr_warn("Event %d may not be floating point\n", eventid);
1009 		return false;
1010 	}
1011 
1012 	mon_event_all[eventid].any_cpu = any_cpu;
1013 	mon_event_all[eventid].binary_bits = binary_bits;
1014 	mon_event_all[eventid].arch_priv = arch_priv;
1015 	mon_event_all[eventid].enabled = true;
1016 
1017 	return true;
1018 }
1019 
1020 bool resctrl_is_mon_event_enabled(enum resctrl_event_id eventid)
1021 {
1022 	return eventid >= QOS_FIRST_EVENT && eventid < QOS_NUM_EVENTS &&
1023 	       mon_event_all[eventid].enabled;
1024 }
1025 
1026 u32 resctrl_get_mon_evt_cfg(enum resctrl_event_id evtid)
1027 {
1028 	return mon_event_all[evtid].evt_cfg;
1029 }
1030 
1031 /**
1032  * struct mbm_transaction - Memory transaction an MBM event can be configured with.
1033  * @name:	Name of memory transaction (read, write ...).
1034  * @val:	The bit (eg. READS_TO_LOCAL_MEM or READS_TO_REMOTE_MEM) used to
1035  *		represent the memory transaction within an event's configuration.
1036  */
1037 struct mbm_transaction {
1038 	char	name[32];
1039 	u32	val;
1040 };
1041 
1042 /* Decoded values for each type of memory transaction. */
1043 static struct mbm_transaction mbm_transactions[NUM_MBM_TRANSACTIONS] = {
1044 	{"local_reads", READS_TO_LOCAL_MEM},
1045 	{"remote_reads", READS_TO_REMOTE_MEM},
1046 	{"local_non_temporal_writes", NON_TEMP_WRITE_TO_LOCAL_MEM},
1047 	{"remote_non_temporal_writes", NON_TEMP_WRITE_TO_REMOTE_MEM},
1048 	{"local_reads_slow_memory", READS_TO_LOCAL_S_MEM},
1049 	{"remote_reads_slow_memory", READS_TO_REMOTE_S_MEM},
1050 	{"dirty_victim_writes_all", DIRTY_VICTIMS_TO_ALL_MEM},
1051 };
1052 
1053 int event_filter_show(struct kernfs_open_file *of, struct seq_file *seq, void *v)
1054 {
1055 	struct mon_evt *mevt = rdt_kn_parent_priv(of->kn);
1056 	struct rdt_resource *r;
1057 	bool sep = false;
1058 	int ret = 0, i;
1059 
1060 	mutex_lock(&rdtgroup_mutex);
1061 	rdt_last_cmd_clear();
1062 
1063 	r = resctrl_arch_get_resource(mevt->rid);
1064 	if (!resctrl_arch_mbm_cntr_assign_enabled(r)) {
1065 		rdt_last_cmd_puts("mbm_event counter assignment mode is not enabled\n");
1066 		ret = -EINVAL;
1067 		goto out_unlock;
1068 	}
1069 
1070 	for (i = 0; i < NUM_MBM_TRANSACTIONS; i++) {
1071 		if (mevt->evt_cfg & mbm_transactions[i].val) {
1072 			if (sep)
1073 				seq_putc(seq, ',');
1074 			seq_printf(seq, "%s", mbm_transactions[i].name);
1075 			sep = true;
1076 		}
1077 	}
1078 	seq_putc(seq, '\n');
1079 
1080 out_unlock:
1081 	mutex_unlock(&rdtgroup_mutex);
1082 
1083 	return ret;
1084 }
1085 
1086 int resctrl_mbm_assign_on_mkdir_show(struct kernfs_open_file *of, struct seq_file *s,
1087 				     void *v)
1088 {
1089 	struct rdt_resource *r = rdt_kn_parent_priv(of->kn);
1090 	int ret = 0;
1091 
1092 	mutex_lock(&rdtgroup_mutex);
1093 	rdt_last_cmd_clear();
1094 
1095 	if (!resctrl_arch_mbm_cntr_assign_enabled(r)) {
1096 		rdt_last_cmd_puts("mbm_event counter assignment mode is not enabled\n");
1097 		ret = -EINVAL;
1098 		goto out_unlock;
1099 	}
1100 
1101 	seq_printf(s, "%u\n", r->mon.mbm_assign_on_mkdir);
1102 
1103 out_unlock:
1104 	mutex_unlock(&rdtgroup_mutex);
1105 
1106 	return ret;
1107 }
1108 
1109 ssize_t resctrl_mbm_assign_on_mkdir_write(struct kernfs_open_file *of, char *buf,
1110 					  size_t nbytes, loff_t off)
1111 {
1112 	struct rdt_resource *r = rdt_kn_parent_priv(of->kn);
1113 	bool value;
1114 	int ret;
1115 
1116 	ret = kstrtobool(buf, &value);
1117 	if (ret)
1118 		return ret;
1119 
1120 	mutex_lock(&rdtgroup_mutex);
1121 	rdt_last_cmd_clear();
1122 
1123 	if (!resctrl_arch_mbm_cntr_assign_enabled(r)) {
1124 		rdt_last_cmd_puts("mbm_event counter assignment mode is not enabled\n");
1125 		ret = -EINVAL;
1126 		goto out_unlock;
1127 	}
1128 
1129 	r->mon.mbm_assign_on_mkdir = value;
1130 
1131 out_unlock:
1132 	mutex_unlock(&rdtgroup_mutex);
1133 
1134 	return ret ?: nbytes;
1135 }
1136 
1137 /*
1138  * mbm_cntr_free_all() - Clear all the counter ID configuration details in the
1139  *			 domain @d. Called when mbm_assign_mode is changed.
1140  */
1141 static void mbm_cntr_free_all(struct rdt_resource *r, struct rdt_l3_mon_domain *d)
1142 {
1143 	memset(d->cntr_cfg, 0, sizeof(*d->cntr_cfg) * r->mon.num_mbm_cntrs);
1144 }
1145 
1146 /*
1147  * resctrl_reset_rmid_all() - Reset all non-architecture states for all the
1148  *			      supported RMIDs.
1149  */
1150 static void resctrl_reset_rmid_all(struct rdt_resource *r, struct rdt_l3_mon_domain *d)
1151 {
1152 	u32 idx_limit = resctrl_arch_system_num_rmid_idx();
1153 	enum resctrl_event_id evt;
1154 	int idx;
1155 
1156 	for_each_mbm_event_id(evt) {
1157 		if (!resctrl_is_mon_event_enabled(evt))
1158 			continue;
1159 		idx = MBM_STATE_IDX(evt);
1160 		memset(d->mbm_states[idx], 0, sizeof(*d->mbm_states[0]) * idx_limit);
1161 	}
1162 }
1163 
1164 /*
1165  * rdtgroup_assign_cntr() - Assign/unassign the counter ID for the event, RMID
1166  * pair in the domain.
1167  *
1168  * Assign the counter if @assign is true else unassign the counter. Reset the
1169  * associated non-architectural state.
1170  */
1171 static void rdtgroup_assign_cntr(struct rdt_resource *r, struct rdt_l3_mon_domain *d,
1172 				 enum resctrl_event_id evtid, u32 rmid, u32 closid,
1173 				 u32 cntr_id, bool assign)
1174 {
1175 	struct mbm_state *m;
1176 
1177 	resctrl_arch_config_cntr(r, d, evtid, rmid, closid, cntr_id, assign);
1178 
1179 	m = get_mbm_state(d, closid, rmid, evtid);
1180 	if (m)
1181 		memset(m, 0, sizeof(*m));
1182 }
1183 
1184 /*
1185  * rdtgroup_alloc_assign_cntr() - Allocate a counter ID and assign it to the event
1186  * pointed to by @mevt and the resctrl group @rdtgrp within the domain @d.
1187  *
1188  * Return:
1189  * 0 on success, < 0 on failure.
1190  */
1191 static int rdtgroup_alloc_assign_cntr(struct rdt_resource *r, struct rdt_l3_mon_domain *d,
1192 				      struct rdtgroup *rdtgrp, struct mon_evt *mevt)
1193 {
1194 	int cntr_id;
1195 
1196 	/* No action required if the counter is assigned already. */
1197 	cntr_id = mbm_cntr_get(r, d, rdtgrp, mevt->evtid);
1198 	if (cntr_id >= 0)
1199 		return 0;
1200 
1201 	cntr_id = mbm_cntr_alloc(r, d, rdtgrp, mevt->evtid);
1202 	if (cntr_id < 0) {
1203 		rdt_last_cmd_printf("Failed to allocate counter for %s in domain %d\n",
1204 				    mevt->name, d->hdr.id);
1205 		return cntr_id;
1206 	}
1207 
1208 	rdtgroup_assign_cntr(r, d, mevt->evtid, rdtgrp->mon.rmid, rdtgrp->closid, cntr_id, true);
1209 
1210 	return 0;
1211 }
1212 
1213 /*
1214  * rdtgroup_assign_cntr_event() - Assign a hardware counter for the event in
1215  * @mevt to the resctrl group @rdtgrp. Assign counters to all domains if @d is
1216  * NULL; otherwise, assign the counter to the specified domain @d.
1217  *
1218  * If all counters in a domain are already in use, rdtgroup_alloc_assign_cntr()
1219  * will fail. When attempting to assign counters to all domains, carry on trying
1220  * to assign counters after a failure since only some domains may have counters
1221  * and the goal is to assign counters where possible. If any counter assignment
1222  * fails, return the error from the last failing assignment.
1223  *
1224  * Return:
1225  * 0 on success, < 0 on failure.
1226  */
1227 static int rdtgroup_assign_cntr_event(struct rdt_l3_mon_domain *d, struct rdtgroup *rdtgrp,
1228 				      struct mon_evt *mevt)
1229 {
1230 	struct rdt_resource *r = resctrl_arch_get_resource(mevt->rid);
1231 	int ret = 0;
1232 
1233 	if (!d) {
1234 		list_for_each_entry(d, &r->mon_domains, hdr.list) {
1235 			int err;
1236 
1237 			err = rdtgroup_alloc_assign_cntr(r, d, rdtgrp, mevt);
1238 			if (err)
1239 				ret = err;
1240 		}
1241 	} else {
1242 		ret = rdtgroup_alloc_assign_cntr(r, d, rdtgrp, mevt);
1243 	}
1244 
1245 	return ret;
1246 }
1247 
1248 /*
1249  * rdtgroup_assign_cntrs() - Assign counters to MBM events. Called when
1250  *			     a new group is created.
1251  *
1252  * Each group can accommodate two counters per domain: one for the total
1253  * event and one for the local event. Assignments may fail due to the limited
1254  * number of counters. However, it is not necessary to fail the group creation
1255  * and thus no failure is returned. Users have the option to modify the
1256  * counter assignments after the group has been created.
1257  */
1258 void rdtgroup_assign_cntrs(struct rdtgroup *rdtgrp)
1259 {
1260 	struct rdt_resource *r = resctrl_arch_get_resource(RDT_RESOURCE_L3);
1261 
1262 	if (!r->mon_capable || !resctrl_arch_mbm_cntr_assign_enabled(r) ||
1263 	    !r->mon.mbm_assign_on_mkdir)
1264 		return;
1265 
1266 	if (resctrl_is_mon_event_enabled(QOS_L3_MBM_TOTAL_EVENT_ID))
1267 		rdtgroup_assign_cntr_event(NULL, rdtgrp,
1268 					   &mon_event_all[QOS_L3_MBM_TOTAL_EVENT_ID]);
1269 
1270 	if (resctrl_is_mon_event_enabled(QOS_L3_MBM_LOCAL_EVENT_ID))
1271 		rdtgroup_assign_cntr_event(NULL, rdtgrp,
1272 					   &mon_event_all[QOS_L3_MBM_LOCAL_EVENT_ID]);
1273 }
1274 
1275 /*
1276  * rdtgroup_free_unassign_cntr() - Unassign and reset the counter ID configuration
1277  * for the event pointed to by @mevt within the domain @d and resctrl group @rdtgrp.
1278  */
1279 static void rdtgroup_free_unassign_cntr(struct rdt_resource *r, struct rdt_l3_mon_domain *d,
1280 					struct rdtgroup *rdtgrp, struct mon_evt *mevt)
1281 {
1282 	int cntr_id;
1283 
1284 	cntr_id = mbm_cntr_get(r, d, rdtgrp, mevt->evtid);
1285 
1286 	/* If there is no cntr_id assigned, nothing to do */
1287 	if (cntr_id < 0)
1288 		return;
1289 
1290 	rdtgroup_assign_cntr(r, d, mevt->evtid, rdtgrp->mon.rmid, rdtgrp->closid, cntr_id, false);
1291 
1292 	mbm_cntr_free(d, cntr_id);
1293 }
1294 
1295 /*
1296  * rdtgroup_unassign_cntr_event() - Unassign a hardware counter associated with
1297  * the event structure @mevt from the domain @d and the group @rdtgrp. Unassign
1298  * the counters from all the domains if @d is NULL else unassign from @d.
1299  */
1300 static void rdtgroup_unassign_cntr_event(struct rdt_l3_mon_domain *d, struct rdtgroup *rdtgrp,
1301 					 struct mon_evt *mevt)
1302 {
1303 	struct rdt_resource *r = resctrl_arch_get_resource(mevt->rid);
1304 
1305 	if (!d) {
1306 		list_for_each_entry(d, &r->mon_domains, hdr.list)
1307 			rdtgroup_free_unassign_cntr(r, d, rdtgrp, mevt);
1308 	} else {
1309 		rdtgroup_free_unassign_cntr(r, d, rdtgrp, mevt);
1310 	}
1311 }
1312 
1313 /*
1314  * rdtgroup_unassign_cntrs() - Unassign the counters associated with MBM events.
1315  *			       Called when a group is deleted.
1316  */
1317 void rdtgroup_unassign_cntrs(struct rdtgroup *rdtgrp)
1318 {
1319 	struct rdt_resource *r = resctrl_arch_get_resource(RDT_RESOURCE_L3);
1320 
1321 	if (!r->mon_capable || !resctrl_arch_mbm_cntr_assign_enabled(r))
1322 		return;
1323 
1324 	if (resctrl_is_mon_event_enabled(QOS_L3_MBM_TOTAL_EVENT_ID))
1325 		rdtgroup_unassign_cntr_event(NULL, rdtgrp,
1326 					     &mon_event_all[QOS_L3_MBM_TOTAL_EVENT_ID]);
1327 
1328 	if (resctrl_is_mon_event_enabled(QOS_L3_MBM_LOCAL_EVENT_ID))
1329 		rdtgroup_unassign_cntr_event(NULL, rdtgrp,
1330 					     &mon_event_all[QOS_L3_MBM_LOCAL_EVENT_ID]);
1331 }
1332 
1333 static int resctrl_parse_mem_transactions(char *tok, u32 *val)
1334 {
1335 	u32 temp_val = 0;
1336 	char *evt_str;
1337 	bool found;
1338 	int i;
1339 
1340 next_config:
1341 	if (!tok || tok[0] == '\0') {
1342 		*val = temp_val;
1343 		return 0;
1344 	}
1345 
1346 	/* Start processing the strings for each memory transaction type */
1347 	evt_str = strim(strsep(&tok, ","));
1348 	found = false;
1349 	for (i = 0; i < NUM_MBM_TRANSACTIONS; i++) {
1350 		if (!strcmp(mbm_transactions[i].name, evt_str)) {
1351 			temp_val |= mbm_transactions[i].val;
1352 			found = true;
1353 			break;
1354 		}
1355 	}
1356 
1357 	if (!found) {
1358 		rdt_last_cmd_printf("Invalid memory transaction type %s\n", evt_str);
1359 		return -EINVAL;
1360 	}
1361 
1362 	goto next_config;
1363 }
1364 
1365 /*
1366  * rdtgroup_update_cntr_event - Update the counter assignments for the event
1367  *				in a group.
1368  * @r:		Resource to which update needs to be done.
1369  * @rdtgrp:	Resctrl group.
1370  * @evtid:	MBM monitor event.
1371  */
1372 static void rdtgroup_update_cntr_event(struct rdt_resource *r, struct rdtgroup *rdtgrp,
1373 				       enum resctrl_event_id evtid)
1374 {
1375 	struct rdt_l3_mon_domain *d;
1376 	int cntr_id;
1377 
1378 	list_for_each_entry(d, &r->mon_domains, hdr.list) {
1379 		cntr_id = mbm_cntr_get(r, d, rdtgrp, evtid);
1380 		if (cntr_id >= 0)
1381 			rdtgroup_assign_cntr(r, d, evtid, rdtgrp->mon.rmid,
1382 					     rdtgrp->closid, cntr_id, true);
1383 	}
1384 }
1385 
1386 /*
1387  * resctrl_update_cntr_allrdtgrp - Update the counter assignments for the event
1388  *				   for all the groups.
1389  * @mevt	MBM Monitor event.
1390  */
1391 static void resctrl_update_cntr_allrdtgrp(struct mon_evt *mevt)
1392 {
1393 	struct rdt_resource *r = resctrl_arch_get_resource(mevt->rid);
1394 	struct rdtgroup *prgrp, *crgrp;
1395 
1396 	/*
1397 	 * Find all the groups where the event is assigned and update the
1398 	 * configuration of existing assignments.
1399 	 */
1400 	list_for_each_entry(prgrp, &rdt_all_groups, rdtgroup_list) {
1401 		rdtgroup_update_cntr_event(r, prgrp, mevt->evtid);
1402 
1403 		list_for_each_entry(crgrp, &prgrp->mon.crdtgrp_list, mon.crdtgrp_list)
1404 			rdtgroup_update_cntr_event(r, crgrp, mevt->evtid);
1405 	}
1406 }
1407 
1408 ssize_t event_filter_write(struct kernfs_open_file *of, char *buf, size_t nbytes,
1409 			   loff_t off)
1410 {
1411 	struct mon_evt *mevt = rdt_kn_parent_priv(of->kn);
1412 	struct rdt_resource *r;
1413 	u32 evt_cfg = 0;
1414 	int ret = 0;
1415 
1416 	/* Valid input requires a trailing newline */
1417 	if (nbytes == 0 || buf[nbytes - 1] != '\n')
1418 		return -EINVAL;
1419 
1420 	buf[nbytes - 1] = '\0';
1421 
1422 	cpus_read_lock();
1423 	mutex_lock(&rdtgroup_mutex);
1424 
1425 	rdt_last_cmd_clear();
1426 
1427 	r = resctrl_arch_get_resource(mevt->rid);
1428 	if (!resctrl_arch_mbm_cntr_assign_enabled(r)) {
1429 		rdt_last_cmd_puts("mbm_event counter assignment mode is not enabled\n");
1430 		ret = -EINVAL;
1431 		goto out_unlock;
1432 	}
1433 	if (!r->mon.mbm_cntr_configurable) {
1434 		rdt_last_cmd_puts("event_filter is not configurable\n");
1435 		ret = -EPERM;
1436 		goto out_unlock;
1437 	}
1438 
1439 	ret = resctrl_parse_mem_transactions(buf, &evt_cfg);
1440 	if (!ret && mevt->evt_cfg != evt_cfg) {
1441 		mevt->evt_cfg = evt_cfg;
1442 		resctrl_update_cntr_allrdtgrp(mevt);
1443 	}
1444 
1445 out_unlock:
1446 	mutex_unlock(&rdtgroup_mutex);
1447 	cpus_read_unlock();
1448 
1449 	return ret ?: nbytes;
1450 }
1451 
1452 int resctrl_mbm_assign_mode_show(struct kernfs_open_file *of,
1453 				 struct seq_file *s, void *v)
1454 {
1455 	struct rdt_resource *r = rdt_kn_parent_priv(of->kn);
1456 	bool enabled;
1457 
1458 	mutex_lock(&rdtgroup_mutex);
1459 	enabled = resctrl_arch_mbm_cntr_assign_enabled(r);
1460 
1461 	if (r->mon.mbm_cntr_assignable) {
1462 		if (enabled)
1463 			seq_puts(s, "[mbm_event]\n");
1464 		else
1465 			seq_puts(s, "[default]\n");
1466 
1467 		if (!r->mon.mbm_cntr_assign_fixed) {
1468 			if (enabled)
1469 				seq_puts(s, "default\n");
1470 			else
1471 				seq_puts(s, "mbm_event\n");
1472 		}
1473 	} else {
1474 		seq_puts(s, "[default]\n");
1475 	}
1476 
1477 	mutex_unlock(&rdtgroup_mutex);
1478 
1479 	return 0;
1480 }
1481 
1482 ssize_t resctrl_mbm_assign_mode_write(struct kernfs_open_file *of, char *buf,
1483 				      size_t nbytes, loff_t off)
1484 {
1485 	struct rdt_resource *r = rdt_kn_parent_priv(of->kn);
1486 	struct rdt_l3_mon_domain *d;
1487 	int ret = 0;
1488 	bool enable;
1489 
1490 	/* Valid input requires a trailing newline */
1491 	if (nbytes == 0 || buf[nbytes - 1] != '\n')
1492 		return -EINVAL;
1493 
1494 	buf[nbytes - 1] = '\0';
1495 
1496 	cpus_read_lock();
1497 	mutex_lock(&rdtgroup_mutex);
1498 
1499 	rdt_last_cmd_clear();
1500 
1501 	if (!strcmp(buf, "default")) {
1502 		enable = 0;
1503 	} else if (!strcmp(buf, "mbm_event")) {
1504 		if (r->mon.mbm_cntr_assignable) {
1505 			enable = 1;
1506 		} else {
1507 			ret = -EINVAL;
1508 			rdt_last_cmd_puts("mbm_event mode is not supported\n");
1509 			goto out_unlock;
1510 		}
1511 	} else {
1512 		ret = -EINVAL;
1513 		rdt_last_cmd_puts("Unsupported assign mode\n");
1514 		goto out_unlock;
1515 	}
1516 
1517 	if (enable != resctrl_arch_mbm_cntr_assign_enabled(r)) {
1518 		if (r->mon.mbm_cntr_assign_fixed) {
1519 			ret = -EINVAL;
1520 			rdt_last_cmd_puts("Counter assignment mode is not configurable\n");
1521 			goto out_unlock;
1522 		}
1523 
1524 		ret = resctrl_arch_mbm_cntr_assign_set(r, enable);
1525 		if (ret)
1526 			goto out_unlock;
1527 
1528 		/* Update the visibility of BMEC related files */
1529 		resctrl_bmec_files_show(r, NULL, !enable);
1530 
1531 		/*
1532 		 * Initialize the default memory transaction values for
1533 		 * total and local events.
1534 		 */
1535 		if (resctrl_is_mon_event_enabled(QOS_L3_MBM_TOTAL_EVENT_ID))
1536 			mon_event_all[QOS_L3_MBM_TOTAL_EVENT_ID].evt_cfg = r->mon.mbm_cfg_mask;
1537 		if (resctrl_is_mon_event_enabled(QOS_L3_MBM_LOCAL_EVENT_ID))
1538 			mon_event_all[QOS_L3_MBM_LOCAL_EVENT_ID].evt_cfg = r->mon.mbm_cfg_mask &
1539 									   (READS_TO_LOCAL_MEM |
1540 									    READS_TO_LOCAL_S_MEM |
1541 									    NON_TEMP_WRITE_TO_LOCAL_MEM);
1542 		/* Enable auto assignment when switching to "mbm_event" mode */
1543 		if (enable)
1544 			r->mon.mbm_assign_on_mkdir = true;
1545 		/*
1546 		 * Reset all the non-achitectural RMID state and assignable counters.
1547 		 */
1548 		list_for_each_entry(d, &r->mon_domains, hdr.list) {
1549 			mbm_cntr_free_all(r, d);
1550 			resctrl_reset_rmid_all(r, d);
1551 		}
1552 	}
1553 
1554 out_unlock:
1555 	mutex_unlock(&rdtgroup_mutex);
1556 	cpus_read_unlock();
1557 
1558 	return ret ?: nbytes;
1559 }
1560 
1561 int resctrl_num_mbm_cntrs_show(struct kernfs_open_file *of,
1562 			       struct seq_file *s, void *v)
1563 {
1564 	struct rdt_resource *r = rdt_kn_parent_priv(of->kn);
1565 	struct rdt_l3_mon_domain *dom;
1566 	bool sep = false;
1567 
1568 	cpus_read_lock();
1569 	mutex_lock(&rdtgroup_mutex);
1570 
1571 	list_for_each_entry(dom, &r->mon_domains, hdr.list) {
1572 		if (sep)
1573 			seq_putc(s, ';');
1574 
1575 		seq_printf(s, "%d=%d", dom->hdr.id, r->mon.num_mbm_cntrs);
1576 		sep = true;
1577 	}
1578 	seq_putc(s, '\n');
1579 
1580 	mutex_unlock(&rdtgroup_mutex);
1581 	cpus_read_unlock();
1582 	return 0;
1583 }
1584 
1585 int resctrl_available_mbm_cntrs_show(struct kernfs_open_file *of,
1586 				     struct seq_file *s, void *v)
1587 {
1588 	struct rdt_resource *r = rdt_kn_parent_priv(of->kn);
1589 	struct rdt_l3_mon_domain *dom;
1590 	bool sep = false;
1591 	u32 cntrs, i;
1592 	int ret = 0;
1593 
1594 	cpus_read_lock();
1595 	mutex_lock(&rdtgroup_mutex);
1596 
1597 	rdt_last_cmd_clear();
1598 
1599 	if (!resctrl_arch_mbm_cntr_assign_enabled(r)) {
1600 		rdt_last_cmd_puts("mbm_event counter assignment mode is not enabled\n");
1601 		ret = -EINVAL;
1602 		goto out_unlock;
1603 	}
1604 
1605 	list_for_each_entry(dom, &r->mon_domains, hdr.list) {
1606 		if (sep)
1607 			seq_putc(s, ';');
1608 
1609 		cntrs = 0;
1610 		for (i = 0; i < r->mon.num_mbm_cntrs; i++) {
1611 			if (!dom->cntr_cfg[i].rdtgrp)
1612 				cntrs++;
1613 		}
1614 
1615 		seq_printf(s, "%d=%u", dom->hdr.id, cntrs);
1616 		sep = true;
1617 	}
1618 	seq_putc(s, '\n');
1619 
1620 out_unlock:
1621 	mutex_unlock(&rdtgroup_mutex);
1622 	cpus_read_unlock();
1623 
1624 	return ret;
1625 }
1626 
1627 int mbm_L3_assignments_show(struct kernfs_open_file *of, struct seq_file *s, void *v)
1628 {
1629 	struct rdt_resource *r = resctrl_arch_get_resource(RDT_RESOURCE_L3);
1630 	struct rdt_l3_mon_domain *d;
1631 	struct rdtgroup *rdtgrp;
1632 	struct mon_evt *mevt;
1633 	int ret = 0;
1634 	bool sep;
1635 
1636 	rdtgrp = rdtgroup_kn_lock_live(of->kn);
1637 	if (!rdtgrp) {
1638 		ret = -ENOENT;
1639 		goto out_unlock;
1640 	}
1641 
1642 	rdt_last_cmd_clear();
1643 	if (!resctrl_arch_mbm_cntr_assign_enabled(r)) {
1644 		rdt_last_cmd_puts("mbm_event counter assignment mode is not enabled\n");
1645 		ret = -EINVAL;
1646 		goto out_unlock;
1647 	}
1648 
1649 	for_each_mon_event(mevt) {
1650 		if (mevt->rid != r->rid || !mevt->enabled || !resctrl_is_mbm_event(mevt->evtid))
1651 			continue;
1652 
1653 		sep = false;
1654 		seq_printf(s, "%s:", mevt->name);
1655 		list_for_each_entry(d, &r->mon_domains, hdr.list) {
1656 			if (sep)
1657 				seq_putc(s, ';');
1658 
1659 			if (mbm_cntr_get(r, d, rdtgrp, mevt->evtid) < 0)
1660 				seq_printf(s, "%d=_", d->hdr.id);
1661 			else
1662 				seq_printf(s, "%d=e", d->hdr.id);
1663 
1664 			sep = true;
1665 		}
1666 		seq_putc(s, '\n');
1667 	}
1668 
1669 out_unlock:
1670 	rdtgroup_kn_unlock(of->kn);
1671 
1672 	return ret;
1673 }
1674 
1675 /*
1676  * mbm_get_mon_event_by_name() - Return the mon_evt entry for the matching
1677  * event name.
1678  */
1679 static struct mon_evt *mbm_get_mon_event_by_name(struct rdt_resource *r, char *name)
1680 {
1681 	struct mon_evt *mevt;
1682 
1683 	for_each_mon_event(mevt) {
1684 		if (mevt->rid == r->rid && mevt->enabled &&
1685 		    resctrl_is_mbm_event(mevt->evtid) &&
1686 		    !strcmp(mevt->name, name))
1687 			return mevt;
1688 	}
1689 
1690 	return NULL;
1691 }
1692 
1693 static int rdtgroup_modify_assign_state(char *assign, struct rdt_l3_mon_domain *d,
1694 					struct rdtgroup *rdtgrp, struct mon_evt *mevt)
1695 {
1696 	int ret = 0;
1697 
1698 	if (!assign || strlen(assign) != 1)
1699 		return -EINVAL;
1700 
1701 	switch (*assign) {
1702 	case 'e':
1703 		ret = rdtgroup_assign_cntr_event(d, rdtgrp, mevt);
1704 		break;
1705 	case '_':
1706 		rdtgroup_unassign_cntr_event(d, rdtgrp, mevt);
1707 		break;
1708 	default:
1709 		ret = -EINVAL;
1710 		break;
1711 	}
1712 
1713 	return ret;
1714 }
1715 
1716 static int resctrl_parse_mbm_assignment(struct rdt_resource *r, struct rdtgroup *rdtgrp,
1717 					char *event, char *tok)
1718 {
1719 	struct rdt_l3_mon_domain *d;
1720 	unsigned long dom_id = 0;
1721 	char *dom_str, *id_str;
1722 	struct mon_evt *mevt;
1723 	int ret;
1724 
1725 	mevt = mbm_get_mon_event_by_name(r, event);
1726 	if (!mevt) {
1727 		rdt_last_cmd_printf("Invalid event %s\n", event);
1728 		return -ENOENT;
1729 	}
1730 
1731 next:
1732 	if (!tok || tok[0] == '\0')
1733 		return 0;
1734 
1735 	/* Start processing the strings for each domain */
1736 	dom_str = strim(strsep(&tok, ";"));
1737 
1738 	id_str = strsep(&dom_str, "=");
1739 
1740 	/* Check for domain id '*' which means all domains */
1741 	if (id_str && *id_str == '*') {
1742 		ret = rdtgroup_modify_assign_state(dom_str, NULL, rdtgrp, mevt);
1743 		if (ret)
1744 			rdt_last_cmd_printf("Assign operation '%s:*=%s' failed\n",
1745 					    event, dom_str);
1746 		return ret;
1747 	} else if (!id_str || kstrtoul(id_str, 10, &dom_id)) {
1748 		rdt_last_cmd_puts("Missing domain id\n");
1749 		return -EINVAL;
1750 	}
1751 
1752 	/* Verify if the dom_id is valid */
1753 	list_for_each_entry(d, &r->mon_domains, hdr.list) {
1754 		if (d->hdr.id == dom_id) {
1755 			ret = rdtgroup_modify_assign_state(dom_str, d, rdtgrp, mevt);
1756 			if (ret) {
1757 				rdt_last_cmd_printf("Assign operation '%s:%ld=%s' failed\n",
1758 						    event, dom_id, dom_str);
1759 				return ret;
1760 			}
1761 			goto next;
1762 		}
1763 	}
1764 
1765 	rdt_last_cmd_printf("Invalid domain id %ld\n", dom_id);
1766 	return -EINVAL;
1767 }
1768 
1769 ssize_t mbm_L3_assignments_write(struct kernfs_open_file *of, char *buf,
1770 				 size_t nbytes, loff_t off)
1771 {
1772 	struct rdt_resource *r = resctrl_arch_get_resource(RDT_RESOURCE_L3);
1773 	struct rdtgroup *rdtgrp;
1774 	char *token, *event;
1775 	int ret = 0;
1776 
1777 	/* Valid input requires a trailing newline */
1778 	if (nbytes == 0 || buf[nbytes - 1] != '\n')
1779 		return -EINVAL;
1780 
1781 	buf[nbytes - 1] = '\0';
1782 
1783 	rdtgrp = rdtgroup_kn_lock_live(of->kn);
1784 	if (!rdtgrp) {
1785 		rdtgroup_kn_unlock(of->kn);
1786 		return -ENOENT;
1787 	}
1788 	rdt_last_cmd_clear();
1789 
1790 	if (!resctrl_arch_mbm_cntr_assign_enabled(r)) {
1791 		rdt_last_cmd_puts("mbm_event mode is not enabled\n");
1792 		rdtgroup_kn_unlock(of->kn);
1793 		return -EINVAL;
1794 	}
1795 
1796 	while ((token = strsep(&buf, "\n")) != NULL) {
1797 		/*
1798 		 * The write command follows the following format:
1799 		 * "<Event>:<Domain ID>=<Assignment state>"
1800 		 * Extract the event name first.
1801 		 */
1802 		event = strsep(&token, ":");
1803 
1804 		ret = resctrl_parse_mbm_assignment(r, rdtgrp, event, token);
1805 		if (ret)
1806 			break;
1807 	}
1808 
1809 	rdtgroup_kn_unlock(of->kn);
1810 
1811 	return ret ?: nbytes;
1812 }
1813 
1814 static int closid_num_dirty_rmid_alloc(struct rdt_resource *r)
1815 {
1816 	if (IS_ENABLED(CONFIG_RESCTRL_RMID_DEPENDS_ON_CLOSID)) {
1817 		u32 num_closid = resctrl_arch_get_num_closid(r);
1818 		u32 *tmp;
1819 
1820 		/* For ARM memory ordering access to closid_num_dirty_rmid */
1821 		mutex_lock(&rdtgroup_mutex);
1822 
1823 		/*
1824 		 * If the architecture hasn't provided a sanitised value here,
1825 		 * this may result in larger arrays than necessary. Resctrl will
1826 		 * use a smaller system wide value based on the resources in
1827 		 * use.
1828 		 */
1829 		tmp = kcalloc(num_closid, sizeof(*tmp), GFP_KERNEL);
1830 		if (!tmp) {
1831 			mutex_unlock(&rdtgroup_mutex);
1832 			return -ENOMEM;
1833 		}
1834 
1835 		closid_num_dirty_rmid = tmp;
1836 
1837 		mutex_unlock(&rdtgroup_mutex);
1838 	}
1839 
1840 	return 0;
1841 }
1842 
1843 static void closid_num_dirty_rmid_free(void)
1844 {
1845 	if (IS_ENABLED(CONFIG_RESCTRL_RMID_DEPENDS_ON_CLOSID)) {
1846 		mutex_lock(&rdtgroup_mutex);
1847 		kfree(closid_num_dirty_rmid);
1848 		closid_num_dirty_rmid = NULL;
1849 		mutex_unlock(&rdtgroup_mutex);
1850 	}
1851 }
1852 
1853 /**
1854  * resctrl_l3_mon_resource_init() - Initialise global monitoring structures.
1855  *
1856  * Allocate and initialise global monitor resources that do not belong to a
1857  * specific domain. i.e. the closid_num_dirty_rmid[] used to find the CLOSID
1858  * with the cleanest set of RMIDs.
1859  * Called once during boot after the struct rdt_resource's have been configured
1860  * but before the filesystem is mounted.
1861  * Resctrl's cpuhp callbacks may be called before this point to bring a domain
1862  * online.
1863  *
1864  * Return: 0 for success, or -ENOMEM.
1865  */
1866 int resctrl_l3_mon_resource_init(void)
1867 {
1868 	struct rdt_resource *r = resctrl_arch_get_resource(RDT_RESOURCE_L3);
1869 	int ret;
1870 
1871 	if (!r->mon_capable)
1872 		return 0;
1873 
1874 	ret = closid_num_dirty_rmid_alloc(r);
1875 	if (ret)
1876 		return ret;
1877 
1878 	if (resctrl_arch_is_evt_configurable(QOS_L3_MBM_TOTAL_EVENT_ID)) {
1879 		mon_event_all[QOS_L3_MBM_TOTAL_EVENT_ID].configurable = true;
1880 		resctrl_file_fflags_init("mbm_total_bytes_config",
1881 					 RFTYPE_MON_INFO | RFTYPE_RES_CACHE);
1882 	}
1883 	if (resctrl_arch_is_evt_configurable(QOS_L3_MBM_LOCAL_EVENT_ID)) {
1884 		mon_event_all[QOS_L3_MBM_LOCAL_EVENT_ID].configurable = true;
1885 		resctrl_file_fflags_init("mbm_local_bytes_config",
1886 					 RFTYPE_MON_INFO | RFTYPE_RES_CACHE);
1887 	}
1888 
1889 	if (resctrl_is_mon_event_enabled(QOS_L3_MBM_LOCAL_EVENT_ID))
1890 		mba_mbps_default_event = QOS_L3_MBM_LOCAL_EVENT_ID;
1891 	else if (resctrl_is_mon_event_enabled(QOS_L3_MBM_TOTAL_EVENT_ID))
1892 		mba_mbps_default_event = QOS_L3_MBM_TOTAL_EVENT_ID;
1893 
1894 	if (r->mon.mbm_cntr_assignable) {
1895 		if (resctrl_is_mon_event_enabled(QOS_L3_MBM_TOTAL_EVENT_ID))
1896 			mon_event_all[QOS_L3_MBM_TOTAL_EVENT_ID].evt_cfg = r->mon.mbm_cfg_mask;
1897 		if (resctrl_is_mon_event_enabled(QOS_L3_MBM_LOCAL_EVENT_ID))
1898 			mon_event_all[QOS_L3_MBM_LOCAL_EVENT_ID].evt_cfg = r->mon.mbm_cfg_mask &
1899 									   (READS_TO_LOCAL_MEM |
1900 									    READS_TO_LOCAL_S_MEM |
1901 									    NON_TEMP_WRITE_TO_LOCAL_MEM);
1902 		r->mon.mbm_assign_on_mkdir = true;
1903 		resctrl_file_fflags_init("num_mbm_cntrs",
1904 					 RFTYPE_MON_INFO | RFTYPE_RES_CACHE);
1905 		resctrl_file_fflags_init("available_mbm_cntrs",
1906 					 RFTYPE_MON_INFO | RFTYPE_RES_CACHE);
1907 		resctrl_file_fflags_init("event_filter", RFTYPE_ASSIGN_CONFIG);
1908 		if (r->mon.mbm_cntr_configurable)
1909 			resctrl_file_mode_init("event_filter", 0644);
1910 		resctrl_file_fflags_init("mbm_assign_on_mkdir", RFTYPE_MON_INFO |
1911 					 RFTYPE_RES_CACHE);
1912 		resctrl_file_fflags_init("mbm_L3_assignments", RFTYPE_MON_BASE);
1913 	}
1914 
1915 	return 0;
1916 }
1917 
1918 void resctrl_l3_mon_resource_exit(void)
1919 {
1920 	struct rdt_resource *r = resctrl_arch_get_resource(RDT_RESOURCE_L3);
1921 
1922 	if (!r->mon_capable)
1923 		return;
1924 
1925 	closid_num_dirty_rmid_free();
1926 }
1927