xref: /linux/fs/resctrl/rdtgroup.c (revision 056e065a6b6e01ab54bb9770c0d5a15350e571e2)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * User interface for Resource Allocation in Resource Director Technology(RDT)
4  *
5  * Copyright (C) 2016 Intel Corporation
6  *
7  * Author: Fenghua Yu <fenghua.yu@intel.com>
8  *
9  * More information about RDT be found in the Intel (R) x86 Architecture
10  * Software Developer Manual.
11  */
12 
13 #define pr_fmt(fmt)	KBUILD_MODNAME ": " fmt
14 
15 #include <linux/cpu.h>
16 #include <linux/debugfs.h>
17 #include <linux/fs.h>
18 #include <linux/fs_parser.h>
19 #include <linux/sysfs.h>
20 #include <linux/kernfs.h>
21 #include <linux/once.h>
22 #include <linux/resctrl.h>
23 #include <linux/seq_buf.h>
24 #include <linux/seq_file.h>
25 #include <linux/sched/task.h>
26 #include <linux/slab.h>
27 #include <linux/user_namespace.h>
28 
29 #include <uapi/linux/magic.h>
30 
31 #include "internal.h"
32 
33 /* Mutex to protect rdtgroup access. */
34 DEFINE_MUTEX(rdtgroup_mutex);
35 
36 static struct kernfs_root *rdt_root;
37 
38 struct rdtgroup rdtgroup_default;
39 
40 LIST_HEAD(rdt_all_groups);
41 
42 /* list of entries for the schemata file */
43 LIST_HEAD(resctrl_schema_all);
44 
45 /*
46  * List of struct mon_data containing private data of event files for use by
47  * rdtgroup_mondata_show(). Protected by rdtgroup_mutex.
48  */
49 static LIST_HEAD(mon_data_kn_priv_list);
50 
51 /* The filesystem can only be mounted once. */
52 bool resctrl_mounted;
53 
54 /* Kernel fs node for "info" directory under root */
55 static struct kernfs_node *kn_info;
56 
57 /* Kernel fs node for "mon_groups" directory under root */
58 static struct kernfs_node *kn_mongrp;
59 
60 /* Kernel fs node for "mon_data" directory under root */
61 static struct kernfs_node *kn_mondata;
62 
63 /*
64  * Used to store the max resource name width to display the schemata names in
65  * a tabular format.
66  */
67 int max_name_width;
68 
69 static struct seq_buf last_cmd_status;
70 
71 static char last_cmd_status_buf[512];
72 
73 static int rdtgroup_setup_root(struct rdt_fs_context *ctx);
74 
75 static void rdtgroup_destroy_root(void);
76 
77 struct dentry *debugfs_resctrl;
78 
79 /*
80  * Memory bandwidth monitoring event to use for the default CTRL_MON group
81  * and each new CTRL_MON group created by the user.  Only relevant when
82  * the filesystem is mounted with the "mba_MBps" option so it does not
83  * matter that it remains uninitialized on systems that do not support
84  * the "mba_MBps" option.
85  */
86 enum resctrl_event_id mba_mbps_default_event;
87 
88 static bool resctrl_debug;
89 
90 void rdt_last_cmd_clear(void)
91 {
92 	lockdep_assert_held(&rdtgroup_mutex);
93 	seq_buf_clear(&last_cmd_status);
94 }
95 
96 void rdt_last_cmd_puts(const char *s)
97 {
98 	lockdep_assert_held(&rdtgroup_mutex);
99 	seq_buf_puts(&last_cmd_status, s);
100 }
101 
102 void rdt_last_cmd_printf(const char *fmt, ...)
103 {
104 	va_list ap;
105 
106 	va_start(ap, fmt);
107 	lockdep_assert_held(&rdtgroup_mutex);
108 	seq_buf_vprintf(&last_cmd_status, fmt, ap);
109 	va_end(ap);
110 }
111 
112 void rdt_staged_configs_clear(void)
113 {
114 	struct rdt_ctrl_domain *dom;
115 	struct rdt_resource *r;
116 
117 	lockdep_assert_held(&rdtgroup_mutex);
118 
119 	for_each_alloc_capable_rdt_resource(r) {
120 		list_for_each_entry(dom, &r->ctrl_domains, hdr.list)
121 			memset(dom->staged_config, 0, sizeof(dom->staged_config));
122 	}
123 }
124 
125 static bool resctrl_is_mbm_enabled(void)
126 {
127 	return (resctrl_is_mon_event_enabled(QOS_L3_MBM_TOTAL_EVENT_ID) ||
128 		resctrl_is_mon_event_enabled(QOS_L3_MBM_LOCAL_EVENT_ID));
129 }
130 
131 /*
132  * Trivial allocator for CLOSIDs. Use BITMAP APIs to manipulate a bitmap
133  * of free CLOSIDs.
134  *
135  * Using a global CLOSID across all resources has some advantages and
136  * some drawbacks:
137  * + We can simply set current's closid to assign a task to a resource
138  *   group.
139  * + Context switch code can avoid extra memory references deciding which
140  *   CLOSID to load into the PQR_ASSOC MSR
141  * - We give up some options in configuring resource groups across multi-socket
142  *   systems.
143  * - Our choices on how to configure each resource become progressively more
144  *   limited as the number of resources grows.
145  */
146 static unsigned long *closid_free_map;
147 
148 static int closid_free_map_len;
149 
150 int closids_supported(void)
151 {
152 	return closid_free_map_len;
153 }
154 
155 static int closid_init(void)
156 {
157 	struct resctrl_schema *s;
158 	u32 rdt_min_closid = ~0;
159 
160 	/* Monitor only platforms still call closid_init() */
161 	if (list_empty(&resctrl_schema_all))
162 		return 0;
163 
164 	/* Compute rdt_min_closid across all resources */
165 	list_for_each_entry(s, &resctrl_schema_all, list)
166 		rdt_min_closid = min(rdt_min_closid, s->num_closid);
167 
168 	closid_free_map = bitmap_alloc(rdt_min_closid, GFP_KERNEL);
169 	if (!closid_free_map)
170 		return -ENOMEM;
171 	bitmap_fill(closid_free_map, rdt_min_closid);
172 
173 	/* RESCTRL_RESERVED_CLOSID is always reserved for the default group */
174 	__clear_bit(RESCTRL_RESERVED_CLOSID, closid_free_map);
175 	closid_free_map_len = rdt_min_closid;
176 
177 	return 0;
178 }
179 
180 static void closid_exit(void)
181 {
182 	bitmap_free(closid_free_map);
183 	closid_free_map = NULL;
184 }
185 
186 static int closid_alloc(void)
187 {
188 	int cleanest_closid;
189 	u32 closid;
190 
191 	lockdep_assert_held(&rdtgroup_mutex);
192 
193 	if (IS_ENABLED(CONFIG_RESCTRL_RMID_DEPENDS_ON_CLOSID) &&
194 	    resctrl_is_mon_event_enabled(QOS_L3_OCCUP_EVENT_ID)) {
195 		cleanest_closid = resctrl_find_cleanest_closid();
196 		if (cleanest_closid < 0)
197 			return cleanest_closid;
198 		closid = cleanest_closid;
199 	} else {
200 		closid = find_first_bit(closid_free_map, closid_free_map_len);
201 		if (closid == closid_free_map_len)
202 			return -ENOSPC;
203 	}
204 	__clear_bit(closid, closid_free_map);
205 
206 	return closid;
207 }
208 
209 void closid_free(int closid)
210 {
211 	lockdep_assert_held(&rdtgroup_mutex);
212 
213 	__set_bit(closid, closid_free_map);
214 }
215 
216 /**
217  * closid_allocated - test if provided closid is in use
218  * @closid: closid to be tested
219  *
220  * Return: true if @closid is currently associated with a resource group,
221  * false if @closid is free
222  */
223 bool closid_allocated(unsigned int closid)
224 {
225 	lockdep_assert_held(&rdtgroup_mutex);
226 
227 	return !test_bit(closid, closid_free_map);
228 }
229 
230 bool closid_alloc_fixed(u32 closid)
231 {
232 	return __test_and_clear_bit(closid, closid_free_map);
233 }
234 
235 /**
236  * rdtgroup_mode_by_closid - Return mode of resource group with closid
237  * @closid: closid if the resource group
238  *
239  * Each resource group is associated with a @closid. Here the mode
240  * of a resource group can be queried by searching for it using its closid.
241  *
242  * Return: mode as &enum rdtgrp_mode of resource group with closid @closid
243  */
244 enum rdtgrp_mode rdtgroup_mode_by_closid(int closid)
245 {
246 	struct rdtgroup *rdtgrp;
247 
248 	list_for_each_entry(rdtgrp, &rdt_all_groups, rdtgroup_list) {
249 		if (rdtgrp->closid == closid)
250 			return rdtgrp->mode;
251 	}
252 
253 	return RDT_NUM_MODES;
254 }
255 
256 static const char * const rdt_mode_str[] = {
257 	[RDT_MODE_SHAREABLE]		= "shareable",
258 	[RDT_MODE_EXCLUSIVE]		= "exclusive",
259 	[RDT_MODE_PSEUDO_LOCKSETUP]	= "pseudo-locksetup",
260 	[RDT_MODE_PSEUDO_LOCKED]	= "pseudo-locked",
261 };
262 
263 /**
264  * rdtgroup_mode_str - Return the string representation of mode
265  * @mode: the resource group mode as &enum rdtgroup_mode
266  *
267  * Return: string representation of valid mode, "unknown" otherwise
268  */
269 static const char *rdtgroup_mode_str(enum rdtgrp_mode mode)
270 {
271 	if (mode < RDT_MODE_SHAREABLE || mode >= RDT_NUM_MODES)
272 		return "unknown";
273 
274 	return rdt_mode_str[mode];
275 }
276 
277 /* set uid and gid of rdtgroup dirs and files to that of the creator */
278 static int rdtgroup_kn_set_ugid(struct kernfs_node *kn)
279 {
280 	struct iattr iattr = { .ia_valid = ATTR_UID | ATTR_GID,
281 				.ia_uid = current_fsuid(),
282 				.ia_gid = current_fsgid(), };
283 
284 	if (uid_eq(iattr.ia_uid, GLOBAL_ROOT_UID) &&
285 	    gid_eq(iattr.ia_gid, GLOBAL_ROOT_GID))
286 		return 0;
287 
288 	return kernfs_setattr(kn, &iattr);
289 }
290 
291 static int rdtgroup_add_file(struct kernfs_node *parent_kn, struct rftype *rft)
292 {
293 	struct kernfs_node *kn;
294 	int ret;
295 
296 	kn = __kernfs_create_file(parent_kn, rft->name, rft->mode,
297 				  GLOBAL_ROOT_UID, GLOBAL_ROOT_GID,
298 				  0, rft->kf_ops, rft, NULL, NULL);
299 	if (IS_ERR(kn))
300 		return PTR_ERR(kn);
301 
302 	ret = rdtgroup_kn_set_ugid(kn);
303 	if (ret) {
304 		kernfs_remove(kn);
305 		return ret;
306 	}
307 
308 	return 0;
309 }
310 
311 static int rdtgroup_seqfile_show(struct seq_file *m, void *arg)
312 {
313 	struct kernfs_open_file *of = m->private;
314 	struct rftype *rft = of->kn->priv;
315 
316 	if (rft->seq_show)
317 		return rft->seq_show(of, m, arg);
318 	return 0;
319 }
320 
321 static ssize_t rdtgroup_file_write(struct kernfs_open_file *of, char *buf,
322 				   size_t nbytes, loff_t off)
323 {
324 	struct rftype *rft = of->kn->priv;
325 
326 	if (rft->write)
327 		return rft->write(of, buf, nbytes, off);
328 
329 	return -EINVAL;
330 }
331 
332 static const struct kernfs_ops rdtgroup_kf_single_ops = {
333 	.atomic_write_len	= PAGE_SIZE,
334 	.write			= rdtgroup_file_write,
335 	.seq_show		= rdtgroup_seqfile_show,
336 };
337 
338 static const struct kernfs_ops kf_mondata_ops = {
339 	.atomic_write_len	= PAGE_SIZE,
340 	.seq_show		= rdtgroup_mondata_show,
341 };
342 
343 static bool is_cpu_list(struct kernfs_open_file *of)
344 {
345 	struct rftype *rft = of->kn->priv;
346 
347 	return rft->flags & RFTYPE_FLAGS_CPUS_LIST;
348 }
349 
350 static int rdtgroup_cpus_show(struct kernfs_open_file *of,
351 			      struct seq_file *s, void *v)
352 {
353 	struct rdtgroup *rdtgrp;
354 	struct cpumask *mask;
355 	int ret = 0;
356 
357 	rdtgrp = rdtgroup_kn_lock_live(of->kn);
358 
359 	if (rdtgrp) {
360 		if (rdtgrp->mode == RDT_MODE_PSEUDO_LOCKED) {
361 			if (!rdtgrp->plr->d) {
362 				rdt_last_cmd_clear();
363 				rdt_last_cmd_puts("Cache domain offline\n");
364 				ret = -ENODEV;
365 			} else {
366 				mask = &rdtgrp->plr->d->hdr.cpu_mask;
367 				seq_printf(s, is_cpu_list(of) ?
368 					   "%*pbl\n" : "%*pb\n",
369 					   cpumask_pr_args(mask));
370 			}
371 		} else {
372 			seq_printf(s, is_cpu_list(of) ? "%*pbl\n" : "%*pb\n",
373 				   cpumask_pr_args(&rdtgrp->cpu_mask));
374 		}
375 	} else {
376 		ret = -ENOENT;
377 	}
378 	rdtgroup_kn_unlock(of->kn);
379 
380 	return ret;
381 }
382 
383 /*
384  * Update the PGR_ASSOC MSR on all cpus in @cpu_mask,
385  *
386  * Per task closids/rmids must have been set up before calling this function.
387  * @r may be NULL.
388  */
389 static void
390 update_closid_rmid(const struct cpumask *cpu_mask, struct rdtgroup *r)
391 {
392 	struct resctrl_cpu_defaults defaults, *p = NULL;
393 
394 	if (r) {
395 		defaults.closid = r->closid;
396 		defaults.rmid = r->mon.rmid;
397 		p = &defaults;
398 	}
399 
400 	on_each_cpu_mask(cpu_mask, resctrl_arch_sync_cpu_closid_rmid, p, 1);
401 }
402 
403 static int cpus_mon_write(struct rdtgroup *rdtgrp, cpumask_var_t newmask,
404 			  cpumask_var_t tmpmask)
405 {
406 	struct rdtgroup *prgrp = rdtgrp->mon.parent, *crgrp;
407 	struct list_head *head;
408 
409 	/* Check whether cpus belong to parent ctrl group */
410 	cpumask_andnot(tmpmask, newmask, &prgrp->cpu_mask);
411 	if (!cpumask_empty(tmpmask)) {
412 		rdt_last_cmd_puts("Can only add CPUs to mongroup that belong to parent\n");
413 		return -EINVAL;
414 	}
415 
416 	/* Check whether cpus are dropped from this group */
417 	cpumask_andnot(tmpmask, &rdtgrp->cpu_mask, newmask);
418 	if (!cpumask_empty(tmpmask)) {
419 		/* Give any dropped cpus to parent rdtgroup */
420 		cpumask_or(&prgrp->cpu_mask, &prgrp->cpu_mask, tmpmask);
421 		update_closid_rmid(tmpmask, prgrp);
422 	}
423 
424 	/*
425 	 * If we added cpus, remove them from previous group that owned them
426 	 * and update per-cpu rmid
427 	 */
428 	cpumask_andnot(tmpmask, newmask, &rdtgrp->cpu_mask);
429 	if (!cpumask_empty(tmpmask)) {
430 		head = &prgrp->mon.crdtgrp_list;
431 		list_for_each_entry(crgrp, head, mon.crdtgrp_list) {
432 			if (crgrp == rdtgrp)
433 				continue;
434 			cpumask_andnot(&crgrp->cpu_mask, &crgrp->cpu_mask,
435 				       tmpmask);
436 		}
437 		update_closid_rmid(tmpmask, rdtgrp);
438 	}
439 
440 	/* Done pushing/pulling - update this group with new mask */
441 	cpumask_copy(&rdtgrp->cpu_mask, newmask);
442 
443 	return 0;
444 }
445 
446 static void cpumask_rdtgrp_clear(struct rdtgroup *r, struct cpumask *m)
447 {
448 	struct rdtgroup *crgrp;
449 
450 	cpumask_andnot(&r->cpu_mask, &r->cpu_mask, m);
451 	/* update the child mon group masks as well*/
452 	list_for_each_entry(crgrp, &r->mon.crdtgrp_list, mon.crdtgrp_list)
453 		cpumask_and(&crgrp->cpu_mask, &r->cpu_mask, &crgrp->cpu_mask);
454 }
455 
456 static int cpus_ctrl_write(struct rdtgroup *rdtgrp, cpumask_var_t newmask,
457 			   cpumask_var_t tmpmask, cpumask_var_t tmpmask1)
458 {
459 	struct rdtgroup *r, *crgrp;
460 	struct list_head *head;
461 
462 	/* Check whether cpus are dropped from this group */
463 	cpumask_andnot(tmpmask, &rdtgrp->cpu_mask, newmask);
464 	if (!cpumask_empty(tmpmask)) {
465 		/* Can't drop from default group */
466 		if (rdtgrp == &rdtgroup_default) {
467 			rdt_last_cmd_puts("Can't drop CPUs from default group\n");
468 			return -EINVAL;
469 		}
470 
471 		/* Give any dropped cpus to rdtgroup_default */
472 		cpumask_or(&rdtgroup_default.cpu_mask,
473 			   &rdtgroup_default.cpu_mask, tmpmask);
474 		update_closid_rmid(tmpmask, &rdtgroup_default);
475 	}
476 
477 	/*
478 	 * If we added cpus, remove them from previous group and
479 	 * the prev group's child groups that owned them
480 	 * and update per-cpu closid/rmid.
481 	 */
482 	cpumask_andnot(tmpmask, newmask, &rdtgrp->cpu_mask);
483 	if (!cpumask_empty(tmpmask)) {
484 		list_for_each_entry(r, &rdt_all_groups, rdtgroup_list) {
485 			if (r == rdtgrp)
486 				continue;
487 			cpumask_and(tmpmask1, &r->cpu_mask, tmpmask);
488 			if (!cpumask_empty(tmpmask1))
489 				cpumask_rdtgrp_clear(r, tmpmask1);
490 		}
491 		update_closid_rmid(tmpmask, rdtgrp);
492 	}
493 
494 	/* Done pushing/pulling - update this group with new mask */
495 	cpumask_copy(&rdtgrp->cpu_mask, newmask);
496 
497 	/*
498 	 * Clear child mon group masks since there is a new parent mask
499 	 * now and update the rmid for the cpus the child lost.
500 	 */
501 	head = &rdtgrp->mon.crdtgrp_list;
502 	list_for_each_entry(crgrp, head, mon.crdtgrp_list) {
503 		cpumask_and(tmpmask, &rdtgrp->cpu_mask, &crgrp->cpu_mask);
504 		update_closid_rmid(tmpmask, rdtgrp);
505 		cpumask_clear(&crgrp->cpu_mask);
506 	}
507 
508 	return 0;
509 }
510 
511 static ssize_t rdtgroup_cpus_write(struct kernfs_open_file *of,
512 				   char *buf, size_t nbytes, loff_t off)
513 {
514 	cpumask_var_t tmpmask, newmask, tmpmask1;
515 	struct rdtgroup *rdtgrp;
516 	int ret;
517 
518 	if (!buf)
519 		return -EINVAL;
520 
521 	if (!zalloc_cpumask_var(&tmpmask, GFP_KERNEL))
522 		return -ENOMEM;
523 	if (!zalloc_cpumask_var(&newmask, GFP_KERNEL)) {
524 		free_cpumask_var(tmpmask);
525 		return -ENOMEM;
526 	}
527 	if (!zalloc_cpumask_var(&tmpmask1, GFP_KERNEL)) {
528 		free_cpumask_var(tmpmask);
529 		free_cpumask_var(newmask);
530 		return -ENOMEM;
531 	}
532 
533 	rdtgrp = rdtgroup_kn_lock_live(of->kn);
534 	if (!rdtgrp) {
535 		ret = -ENOENT;
536 		goto unlock;
537 	}
538 
539 	rdt_last_cmd_clear();
540 
541 	if (rdtgrp->mode == RDT_MODE_PSEUDO_LOCKED ||
542 	    rdtgrp->mode == RDT_MODE_PSEUDO_LOCKSETUP) {
543 		ret = -EINVAL;
544 		rdt_last_cmd_puts("Pseudo-locking in progress\n");
545 		goto unlock;
546 	}
547 
548 	if (is_cpu_list(of))
549 		ret = cpulist_parse(buf, newmask);
550 	else
551 		ret = cpumask_parse(buf, newmask);
552 
553 	if (ret) {
554 		rdt_last_cmd_puts("Bad CPU list/mask\n");
555 		goto unlock;
556 	}
557 
558 	/* check that user didn't specify any offline cpus */
559 	cpumask_andnot(tmpmask, newmask, cpu_online_mask);
560 	if (!cpumask_empty(tmpmask)) {
561 		ret = -EINVAL;
562 		rdt_last_cmd_puts("Can only assign online CPUs\n");
563 		goto unlock;
564 	}
565 
566 	if (rdtgrp->type == RDTCTRL_GROUP)
567 		ret = cpus_ctrl_write(rdtgrp, newmask, tmpmask, tmpmask1);
568 	else if (rdtgrp->type == RDTMON_GROUP)
569 		ret = cpus_mon_write(rdtgrp, newmask, tmpmask);
570 	else
571 		ret = -EINVAL;
572 
573 unlock:
574 	rdtgroup_kn_unlock(of->kn);
575 	free_cpumask_var(tmpmask);
576 	free_cpumask_var(newmask);
577 	free_cpumask_var(tmpmask1);
578 
579 	return ret ?: nbytes;
580 }
581 
582 /**
583  * rdtgroup_remove - the helper to remove resource group safely
584  * @rdtgrp: resource group to remove
585  *
586  * On resource group creation via a mkdir, an extra kernfs_node reference is
587  * taken to ensure that the rdtgroup structure remains accessible for the
588  * rdtgroup_kn_unlock() calls where it is removed.
589  *
590  * Drop the extra reference here, then free the rdtgroup structure.
591  *
592  * Return: void
593  */
594 static void rdtgroup_remove(struct rdtgroup *rdtgrp)
595 {
596 	kernfs_put(rdtgrp->kn);
597 	kfree(rdtgrp);
598 }
599 
600 static void _update_task_closid_rmid(void *task)
601 {
602 	/*
603 	 * If the task is still current on this CPU, update PQR_ASSOC MSR.
604 	 * Otherwise, the MSR is updated when the task is scheduled in.
605 	 */
606 	if (task == current)
607 		resctrl_arch_sched_in(task);
608 }
609 
610 static void update_task_closid_rmid(struct task_struct *t)
611 {
612 	if (IS_ENABLED(CONFIG_SMP) && task_curr(t))
613 		smp_call_function_single(task_cpu(t), _update_task_closid_rmid, t, 1);
614 	else
615 		_update_task_closid_rmid(t);
616 }
617 
618 static bool task_in_rdtgroup(struct task_struct *tsk, struct rdtgroup *rdtgrp)
619 {
620 	u32 closid, rmid = rdtgrp->mon.rmid;
621 
622 	if (rdtgrp->type == RDTCTRL_GROUP)
623 		closid = rdtgrp->closid;
624 	else if (rdtgrp->type == RDTMON_GROUP)
625 		closid = rdtgrp->mon.parent->closid;
626 	else
627 		return false;
628 
629 	return resctrl_arch_match_closid(tsk, closid) &&
630 	       resctrl_arch_match_rmid(tsk, closid, rmid);
631 }
632 
633 static int __rdtgroup_move_task(struct task_struct *tsk,
634 				struct rdtgroup *rdtgrp)
635 {
636 	/* If the task is already in rdtgrp, no need to move the task. */
637 	if (task_in_rdtgroup(tsk, rdtgrp))
638 		return 0;
639 
640 	/*
641 	 * Set the task's closid/rmid before the PQR_ASSOC MSR can be
642 	 * updated by them.
643 	 *
644 	 * For ctrl_mon groups, move both closid and rmid.
645 	 * For monitor groups, can move the tasks only from
646 	 * their parent CTRL group.
647 	 */
648 	if (rdtgrp->type == RDTMON_GROUP &&
649 	    !resctrl_arch_match_closid(tsk, rdtgrp->mon.parent->closid)) {
650 		rdt_last_cmd_puts("Can't move task to different control group\n");
651 		return -EINVAL;
652 	}
653 
654 	if (rdtgrp->type == RDTMON_GROUP)
655 		resctrl_arch_set_closid_rmid(tsk, rdtgrp->mon.parent->closid,
656 					     rdtgrp->mon.rmid);
657 	else
658 		resctrl_arch_set_closid_rmid(tsk, rdtgrp->closid,
659 					     rdtgrp->mon.rmid);
660 
661 	/*
662 	 * Ensure the task's closid and rmid are written before determining if
663 	 * the task is current that will decide if it will be interrupted.
664 	 * This pairs with the full barrier between the rq->curr update and
665 	 * resctrl_arch_sched_in() during context switch.
666 	 */
667 	smp_mb();
668 
669 	/*
670 	 * By now, the task's closid and rmid are set. If the task is current
671 	 * on a CPU, the PQR_ASSOC MSR needs to be updated to make the resource
672 	 * group go into effect. If the task is not current, the MSR will be
673 	 * updated when the task is scheduled in.
674 	 */
675 	update_task_closid_rmid(tsk);
676 
677 	return 0;
678 }
679 
680 static bool is_closid_match(struct task_struct *t, struct rdtgroup *r)
681 {
682 	return (resctrl_arch_alloc_capable() && (r->type == RDTCTRL_GROUP) &&
683 		resctrl_arch_match_closid(t, r->closid));
684 }
685 
686 static bool is_rmid_match(struct task_struct *t, struct rdtgroup *r)
687 {
688 	return (resctrl_arch_mon_capable() && (r->type == RDTMON_GROUP) &&
689 		resctrl_arch_match_rmid(t, r->mon.parent->closid,
690 					r->mon.rmid));
691 }
692 
693 /**
694  * rdtgroup_tasks_assigned - Test if tasks have been assigned to resource group
695  * @r: Resource group
696  *
697  * Return: 1 if tasks have been assigned to @r, 0 otherwise
698  */
699 int rdtgroup_tasks_assigned(struct rdtgroup *r)
700 {
701 	struct task_struct *p, *t;
702 	int ret = 0;
703 
704 	lockdep_assert_held(&rdtgroup_mutex);
705 
706 	rcu_read_lock();
707 	for_each_process_thread(p, t) {
708 		if (is_closid_match(t, r) || is_rmid_match(t, r)) {
709 			ret = 1;
710 			break;
711 		}
712 	}
713 	rcu_read_unlock();
714 
715 	return ret;
716 }
717 
718 static int rdtgroup_task_write_permission(struct task_struct *task,
719 					  struct kernfs_open_file *of)
720 {
721 	const struct cred *tcred = get_task_cred(task);
722 	const struct cred *cred = current_cred();
723 	int ret = 0;
724 
725 	/*
726 	 * Even if we're attaching all tasks in the thread group, we only
727 	 * need to check permissions on one of them.
728 	 */
729 	if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
730 	    !uid_eq(cred->euid, tcred->uid) &&
731 	    !uid_eq(cred->euid, tcred->suid)) {
732 		rdt_last_cmd_printf("No permission to move task %d\n", task->pid);
733 		ret = -EPERM;
734 	}
735 
736 	put_cred(tcred);
737 	return ret;
738 }
739 
740 static int rdtgroup_move_task(pid_t pid, struct rdtgroup *rdtgrp,
741 			      struct kernfs_open_file *of)
742 {
743 	struct task_struct *tsk;
744 	int ret;
745 
746 	rcu_read_lock();
747 	if (pid) {
748 		tsk = find_task_by_vpid(pid);
749 		if (!tsk) {
750 			rcu_read_unlock();
751 			rdt_last_cmd_printf("No task %d\n", pid);
752 			return -ESRCH;
753 		}
754 	} else {
755 		tsk = current;
756 	}
757 
758 	get_task_struct(tsk);
759 	rcu_read_unlock();
760 
761 	ret = rdtgroup_task_write_permission(tsk, of);
762 	if (!ret)
763 		ret = __rdtgroup_move_task(tsk, rdtgrp);
764 
765 	put_task_struct(tsk);
766 	return ret;
767 }
768 
769 static ssize_t rdtgroup_tasks_write(struct kernfs_open_file *of,
770 				    char *buf, size_t nbytes, loff_t off)
771 {
772 	struct rdtgroup *rdtgrp;
773 	char *pid_str;
774 	int ret = 0;
775 	pid_t pid;
776 
777 	rdtgrp = rdtgroup_kn_lock_live(of->kn);
778 	if (!rdtgrp) {
779 		rdtgroup_kn_unlock(of->kn);
780 		return -ENOENT;
781 	}
782 	rdt_last_cmd_clear();
783 
784 	if (rdtgrp->mode == RDT_MODE_PSEUDO_LOCKED ||
785 	    rdtgrp->mode == RDT_MODE_PSEUDO_LOCKSETUP) {
786 		ret = -EINVAL;
787 		rdt_last_cmd_puts("Pseudo-locking in progress\n");
788 		goto unlock;
789 	}
790 
791 	while (buf && buf[0] != '\0' && buf[0] != '\n') {
792 		pid_str = strim(strsep(&buf, ","));
793 
794 		if (kstrtoint(pid_str, 0, &pid)) {
795 			rdt_last_cmd_printf("Task list parsing error pid %s\n", pid_str);
796 			ret = -EINVAL;
797 			break;
798 		}
799 
800 		if (pid < 0) {
801 			rdt_last_cmd_printf("Invalid pid %d\n", pid);
802 			ret = -EINVAL;
803 			break;
804 		}
805 
806 		ret = rdtgroup_move_task(pid, rdtgrp, of);
807 		if (ret) {
808 			rdt_last_cmd_printf("Error while processing task %d\n", pid);
809 			break;
810 		}
811 	}
812 
813 unlock:
814 	rdtgroup_kn_unlock(of->kn);
815 
816 	return ret ?: nbytes;
817 }
818 
819 static void show_rdt_tasks(struct rdtgroup *r, struct seq_file *s)
820 {
821 	struct task_struct *p, *t;
822 	pid_t pid;
823 
824 	rcu_read_lock();
825 	for_each_process_thread(p, t) {
826 		if (is_closid_match(t, r) || is_rmid_match(t, r)) {
827 			pid = task_pid_vnr(t);
828 			if (pid)
829 				seq_printf(s, "%d\n", pid);
830 		}
831 	}
832 	rcu_read_unlock();
833 }
834 
835 static int rdtgroup_tasks_show(struct kernfs_open_file *of,
836 			       struct seq_file *s, void *v)
837 {
838 	struct rdtgroup *rdtgrp;
839 	int ret = 0;
840 
841 	rdtgrp = rdtgroup_kn_lock_live(of->kn);
842 	if (rdtgrp)
843 		show_rdt_tasks(rdtgrp, s);
844 	else
845 		ret = -ENOENT;
846 	rdtgroup_kn_unlock(of->kn);
847 
848 	return ret;
849 }
850 
851 static int rdtgroup_closid_show(struct kernfs_open_file *of,
852 				struct seq_file *s, void *v)
853 {
854 	struct rdtgroup *rdtgrp;
855 	int ret = 0;
856 
857 	rdtgrp = rdtgroup_kn_lock_live(of->kn);
858 	if (rdtgrp)
859 		seq_printf(s, "%u\n", rdtgrp->closid);
860 	else
861 		ret = -ENOENT;
862 	rdtgroup_kn_unlock(of->kn);
863 
864 	return ret;
865 }
866 
867 static int rdtgroup_rmid_show(struct kernfs_open_file *of,
868 			      struct seq_file *s, void *v)
869 {
870 	struct rdtgroup *rdtgrp;
871 	int ret = 0;
872 
873 	rdtgrp = rdtgroup_kn_lock_live(of->kn);
874 	if (rdtgrp)
875 		seq_printf(s, "%u\n", rdtgrp->mon.rmid);
876 	else
877 		ret = -ENOENT;
878 	rdtgroup_kn_unlock(of->kn);
879 
880 	return ret;
881 }
882 
883 #ifdef CONFIG_PROC_CPU_RESCTRL
884 /*
885  * A task can only be part of one resctrl control group and of one monitor
886  * group which is associated to that control group.
887  *
888  * 1)   res:
889  *      mon:
890  *
891  *    resctrl is not available.
892  *
893  * 2)   res:/
894  *      mon:
895  *
896  *    Task is part of the root resctrl control group, and it is not associated
897  *    to any monitor group.
898  *
899  * 3)  res:/
900  *     mon:mon0
901  *
902  *    Task is part of the root resctrl control group and monitor group mon0.
903  *
904  * 4)  res:group0
905  *     mon:
906  *
907  *    Task is part of resctrl control group group0, and it is not associated
908  *    to any monitor group.
909  *
910  * 5) res:group0
911  *    mon:mon1
912  *
913  *    Task is part of resctrl control group group0 and monitor group mon1.
914  */
915 int proc_resctrl_show(struct seq_file *s, struct pid_namespace *ns,
916 		      struct pid *pid, struct task_struct *tsk)
917 {
918 	struct rdtgroup *rdtg;
919 	int ret = 0;
920 
921 	mutex_lock(&rdtgroup_mutex);
922 
923 	/* Return empty if resctrl has not been mounted. */
924 	if (!resctrl_mounted) {
925 		seq_puts(s, "res:\nmon:\n");
926 		goto unlock;
927 	}
928 
929 	list_for_each_entry(rdtg, &rdt_all_groups, rdtgroup_list) {
930 		struct rdtgroup *crg;
931 
932 		/*
933 		 * Task information is only relevant for shareable
934 		 * and exclusive groups.
935 		 */
936 		if (rdtg->mode != RDT_MODE_SHAREABLE &&
937 		    rdtg->mode != RDT_MODE_EXCLUSIVE)
938 			continue;
939 
940 		if (!resctrl_arch_match_closid(tsk, rdtg->closid))
941 			continue;
942 
943 		seq_printf(s, "res:%s%s\n", (rdtg == &rdtgroup_default) ? "/" : "",
944 			   rdt_kn_name(rdtg->kn));
945 		seq_puts(s, "mon:");
946 		list_for_each_entry(crg, &rdtg->mon.crdtgrp_list,
947 				    mon.crdtgrp_list) {
948 			if (!resctrl_arch_match_rmid(tsk, crg->mon.parent->closid,
949 						     crg->mon.rmid))
950 				continue;
951 			seq_printf(s, "%s", rdt_kn_name(crg->kn));
952 			break;
953 		}
954 		seq_putc(s, '\n');
955 		goto unlock;
956 	}
957 	/*
958 	 * The above search should succeed. Otherwise return
959 	 * with an error.
960 	 */
961 	ret = -ENOENT;
962 unlock:
963 	mutex_unlock(&rdtgroup_mutex);
964 
965 	return ret;
966 }
967 #endif
968 
969 static int rdt_last_cmd_status_show(struct kernfs_open_file *of,
970 				    struct seq_file *seq, void *v)
971 {
972 	int len;
973 
974 	mutex_lock(&rdtgroup_mutex);
975 	len = seq_buf_used(&last_cmd_status);
976 	if (len)
977 		seq_printf(seq, "%.*s", len, last_cmd_status_buf);
978 	else
979 		seq_puts(seq, "ok\n");
980 	mutex_unlock(&rdtgroup_mutex);
981 	return 0;
982 }
983 
984 void *rdt_kn_parent_priv(struct kernfs_node *kn)
985 {
986 	/*
987 	 * The parent pointer is only valid within RCU section since it can be
988 	 * replaced.
989 	 */
990 	guard(rcu)();
991 	return rcu_dereference(kn->__parent)->priv;
992 }
993 
994 static int rdt_num_closids_show(struct kernfs_open_file *of,
995 				struct seq_file *seq, void *v)
996 {
997 	struct resctrl_schema *s = rdt_kn_parent_priv(of->kn);
998 
999 	seq_printf(seq, "%u\n", s->num_closid);
1000 	return 0;
1001 }
1002 
1003 static int rdt_default_ctrl_show(struct kernfs_open_file *of,
1004 				 struct seq_file *seq, void *v)
1005 {
1006 	struct resctrl_schema *s = rdt_kn_parent_priv(of->kn);
1007 	struct rdt_resource *r = s->res;
1008 
1009 	seq_printf(seq, "%x\n", resctrl_get_default_ctrl(r));
1010 	return 0;
1011 }
1012 
1013 static int rdt_min_cbm_bits_show(struct kernfs_open_file *of,
1014 				 struct seq_file *seq, void *v)
1015 {
1016 	struct resctrl_schema *s = rdt_kn_parent_priv(of->kn);
1017 	struct rdt_resource *r = s->res;
1018 
1019 	seq_printf(seq, "%u\n", r->cache.min_cbm_bits);
1020 	return 0;
1021 }
1022 
1023 static int rdt_shareable_bits_show(struct kernfs_open_file *of,
1024 				   struct seq_file *seq, void *v)
1025 {
1026 	struct resctrl_schema *s = rdt_kn_parent_priv(of->kn);
1027 	struct rdt_resource *r = s->res;
1028 
1029 	seq_printf(seq, "%x\n", r->cache.shareable_bits);
1030 	return 0;
1031 }
1032 
1033 /*
1034  * rdt_bit_usage_show - Display current usage of resources
1035  *
1036  * A domain is a shared resource that can now be allocated differently. Here
1037  * we display the current regions of the domain as an annotated bitmask.
1038  * For each domain of this resource its allocation bitmask
1039  * is annotated as below to indicate the current usage of the corresponding bit:
1040  *   0 - currently unused
1041  *   X - currently available for sharing and used by software and hardware
1042  *   H - currently used by hardware only but available for software use
1043  *   S - currently used and shareable by software only
1044  *   E - currently used exclusively by one resource group
1045  *   P - currently pseudo-locked by one resource group
1046  */
1047 static int rdt_bit_usage_show(struct kernfs_open_file *of,
1048 			      struct seq_file *seq, void *v)
1049 {
1050 	struct resctrl_schema *s = rdt_kn_parent_priv(of->kn);
1051 	/*
1052 	 * Use unsigned long even though only 32 bits are used to ensure
1053 	 * test_bit() is used safely.
1054 	 */
1055 	unsigned long sw_shareable = 0, hw_shareable = 0;
1056 	unsigned long exclusive = 0, pseudo_locked = 0;
1057 	struct rdt_resource *r = s->res;
1058 	struct rdt_ctrl_domain *dom;
1059 	int i, hwb, swb, excl, psl;
1060 	enum rdtgrp_mode mode;
1061 	bool sep = false;
1062 	u32 ctrl_val;
1063 
1064 	cpus_read_lock();
1065 	mutex_lock(&rdtgroup_mutex);
1066 	list_for_each_entry(dom, &r->ctrl_domains, hdr.list) {
1067 		if (sep)
1068 			seq_putc(seq, ';');
1069 		hw_shareable = r->cache.shareable_bits;
1070 		sw_shareable = 0;
1071 		exclusive = 0;
1072 		seq_printf(seq, "%d=", dom->hdr.id);
1073 		for (i = 0; i < closids_supported(); i++) {
1074 			if (!closid_allocated(i) ||
1075 			    (resctrl_arch_get_io_alloc_enabled(r) &&
1076 			     i == resctrl_io_alloc_closid(r)))
1077 				continue;
1078 			ctrl_val = resctrl_arch_get_config(r, dom, i,
1079 							   s->conf_type);
1080 			mode = rdtgroup_mode_by_closid(i);
1081 			switch (mode) {
1082 			case RDT_MODE_SHAREABLE:
1083 				sw_shareable |= ctrl_val;
1084 				break;
1085 			case RDT_MODE_EXCLUSIVE:
1086 				exclusive |= ctrl_val;
1087 				break;
1088 			case RDT_MODE_PSEUDO_LOCKSETUP:
1089 			/*
1090 			 * RDT_MODE_PSEUDO_LOCKSETUP is possible
1091 			 * here but not included since the CBM
1092 			 * associated with this CLOSID in this mode
1093 			 * is not initialized and no task or cpu can be
1094 			 * assigned this CLOSID.
1095 			 */
1096 				break;
1097 			case RDT_MODE_PSEUDO_LOCKED:
1098 			case RDT_NUM_MODES:
1099 				WARN(1,
1100 				     "invalid mode for closid %d\n", i);
1101 				break;
1102 			}
1103 		}
1104 
1105 		/*
1106 		 * When the "io_alloc" feature is enabled, a portion of the cache
1107 		 * is configured for shared use between hardware and software.
1108 		 * Also, when CDP is enabled the CBMs of CDP_CODE and CDP_DATA
1109 		 * resources are kept in sync. So, the CBMs for "io_alloc" can
1110 		 * be accessed through either resource.
1111 		 */
1112 		if (resctrl_arch_get_io_alloc_enabled(r)) {
1113 			ctrl_val = resctrl_arch_get_config(r, dom,
1114 							   resctrl_io_alloc_closid(r),
1115 							   s->conf_type);
1116 			hw_shareable |= ctrl_val;
1117 		}
1118 
1119 		for (i = r->cache.cbm_len - 1; i >= 0; i--) {
1120 			pseudo_locked = dom->plr ? dom->plr->cbm : 0;
1121 			hwb = test_bit(i, &hw_shareable);
1122 			swb = test_bit(i, &sw_shareable);
1123 			excl = test_bit(i, &exclusive);
1124 			psl = test_bit(i, &pseudo_locked);
1125 			if (hwb && swb)
1126 				seq_putc(seq, 'X');
1127 			else if (hwb && !swb)
1128 				seq_putc(seq, 'H');
1129 			else if (!hwb && swb)
1130 				seq_putc(seq, 'S');
1131 			else if (excl)
1132 				seq_putc(seq, 'E');
1133 			else if (psl)
1134 				seq_putc(seq, 'P');
1135 			else /* Unused bits remain */
1136 				seq_putc(seq, '0');
1137 		}
1138 		sep = true;
1139 	}
1140 	seq_putc(seq, '\n');
1141 	mutex_unlock(&rdtgroup_mutex);
1142 	cpus_read_unlock();
1143 	return 0;
1144 }
1145 
1146 static int rdt_min_bw_show(struct kernfs_open_file *of,
1147 			   struct seq_file *seq, void *v)
1148 {
1149 	struct resctrl_schema *s = rdt_kn_parent_priv(of->kn);
1150 	struct rdt_resource *r = s->res;
1151 
1152 	seq_printf(seq, "%u\n", r->membw.min_bw);
1153 	return 0;
1154 }
1155 
1156 static int rdt_num_rmids_show(struct kernfs_open_file *of,
1157 			      struct seq_file *seq, void *v)
1158 {
1159 	struct rdt_resource *r = rdt_kn_parent_priv(of->kn);
1160 
1161 	seq_printf(seq, "%u\n", r->mon.num_rmid);
1162 
1163 	return 0;
1164 }
1165 
1166 static int rdt_mon_features_show(struct kernfs_open_file *of,
1167 				 struct seq_file *seq, void *v)
1168 {
1169 	struct rdt_resource *r = rdt_kn_parent_priv(of->kn);
1170 	struct mon_evt *mevt;
1171 
1172 	for_each_mon_event(mevt) {
1173 		if (mevt->rid != r->rid || !mevt->enabled)
1174 			continue;
1175 		seq_printf(seq, "%s\n", mevt->name);
1176 		if (mevt->configurable &&
1177 		    !resctrl_arch_mbm_cntr_assign_enabled(r))
1178 			seq_printf(seq, "%s_config\n", mevt->name);
1179 	}
1180 
1181 	return 0;
1182 }
1183 
1184 static int rdt_bw_gran_show(struct kernfs_open_file *of,
1185 			    struct seq_file *seq, void *v)
1186 {
1187 	struct resctrl_schema *s = rdt_kn_parent_priv(of->kn);
1188 	struct rdt_resource *r = s->res;
1189 
1190 	seq_printf(seq, "%u\n", r->membw.bw_gran);
1191 	return 0;
1192 }
1193 
1194 static int rdt_delay_linear_show(struct kernfs_open_file *of,
1195 				 struct seq_file *seq, void *v)
1196 {
1197 	struct resctrl_schema *s = rdt_kn_parent_priv(of->kn);
1198 	struct rdt_resource *r = s->res;
1199 
1200 	seq_printf(seq, "%u\n", r->membw.delay_linear);
1201 	return 0;
1202 }
1203 
1204 static int max_threshold_occ_show(struct kernfs_open_file *of,
1205 				  struct seq_file *seq, void *v)
1206 {
1207 	seq_printf(seq, "%u\n", resctrl_rmid_realloc_threshold);
1208 
1209 	return 0;
1210 }
1211 
1212 static int rdt_thread_throttle_mode_show(struct kernfs_open_file *of,
1213 					 struct seq_file *seq, void *v)
1214 {
1215 	struct resctrl_schema *s = rdt_kn_parent_priv(of->kn);
1216 	struct rdt_resource *r = s->res;
1217 
1218 	switch (r->membw.throttle_mode) {
1219 	case THREAD_THROTTLE_PER_THREAD:
1220 		seq_puts(seq, "per-thread\n");
1221 		return 0;
1222 	case THREAD_THROTTLE_MAX:
1223 		seq_puts(seq, "max\n");
1224 		return 0;
1225 	case THREAD_THROTTLE_UNDEFINED:
1226 		seq_puts(seq, "undefined\n");
1227 		return 0;
1228 	}
1229 
1230 	WARN_ON_ONCE(1);
1231 
1232 	return 0;
1233 }
1234 
1235 static ssize_t max_threshold_occ_write(struct kernfs_open_file *of,
1236 				       char *buf, size_t nbytes, loff_t off)
1237 {
1238 	unsigned int bytes;
1239 	int ret;
1240 
1241 	ret = kstrtouint(buf, 0, &bytes);
1242 	if (ret)
1243 		return ret;
1244 
1245 	if (bytes > resctrl_rmid_realloc_limit)
1246 		return -EINVAL;
1247 
1248 	resctrl_rmid_realloc_threshold = resctrl_arch_round_mon_val(bytes);
1249 
1250 	return nbytes;
1251 }
1252 
1253 /*
1254  * rdtgroup_mode_show - Display mode of this resource group
1255  */
1256 static int rdtgroup_mode_show(struct kernfs_open_file *of,
1257 			      struct seq_file *s, void *v)
1258 {
1259 	struct rdtgroup *rdtgrp;
1260 
1261 	rdtgrp = rdtgroup_kn_lock_live(of->kn);
1262 	if (!rdtgrp) {
1263 		rdtgroup_kn_unlock(of->kn);
1264 		return -ENOENT;
1265 	}
1266 
1267 	seq_printf(s, "%s\n", rdtgroup_mode_str(rdtgrp->mode));
1268 
1269 	rdtgroup_kn_unlock(of->kn);
1270 	return 0;
1271 }
1272 
1273 enum resctrl_conf_type resctrl_peer_type(enum resctrl_conf_type my_type)
1274 {
1275 	switch (my_type) {
1276 	case CDP_CODE:
1277 		return CDP_DATA;
1278 	case CDP_DATA:
1279 		return CDP_CODE;
1280 	default:
1281 	case CDP_NONE:
1282 		return CDP_NONE;
1283 	}
1284 }
1285 
1286 static int rdt_has_sparse_bitmasks_show(struct kernfs_open_file *of,
1287 					struct seq_file *seq, void *v)
1288 {
1289 	struct resctrl_schema *s = rdt_kn_parent_priv(of->kn);
1290 	struct rdt_resource *r = s->res;
1291 
1292 	seq_printf(seq, "%u\n", r->cache.arch_has_sparse_bitmasks);
1293 
1294 	return 0;
1295 }
1296 
1297 /**
1298  * __rdtgroup_cbm_overlaps - Does CBM for intended closid overlap with other
1299  * @r: Resource to which domain instance @d belongs.
1300  * @d: The domain instance for which @closid is being tested.
1301  * @cbm: Capacity bitmask being tested.
1302  * @closid: Intended closid for @cbm.
1303  * @type: CDP type of @r.
1304  * @exclusive: Only check if overlaps with exclusive resource groups
1305  *
1306  * Checks if provided @cbm intended to be used for @closid on domain
1307  * @d overlaps with any other closids or other hardware usage associated
1308  * with this domain. If @exclusive is true then only overlaps with
1309  * resource groups in exclusive mode will be considered. If @exclusive
1310  * is false then overlaps with any resource group or hardware entities
1311  * will be considered.
1312  *
1313  * @cbm is unsigned long, even if only 32 bits are used, to make the
1314  * bitmap functions work correctly.
1315  *
1316  * Return: false if CBM does not overlap, true if it does.
1317  */
1318 static bool __rdtgroup_cbm_overlaps(struct rdt_resource *r, struct rdt_ctrl_domain *d,
1319 				    unsigned long cbm, int closid,
1320 				    enum resctrl_conf_type type, bool exclusive)
1321 {
1322 	enum rdtgrp_mode mode;
1323 	unsigned long ctrl_b;
1324 	int i;
1325 
1326 	/* Check for any overlap with regions used by hardware directly */
1327 	if (!exclusive) {
1328 		ctrl_b = r->cache.shareable_bits;
1329 		if (bitmap_intersects(&cbm, &ctrl_b, r->cache.cbm_len))
1330 			return true;
1331 	}
1332 
1333 	/* Check for overlap with other resource groups */
1334 	for (i = 0; i < closids_supported(); i++) {
1335 		ctrl_b = resctrl_arch_get_config(r, d, i, type);
1336 		mode = rdtgroup_mode_by_closid(i);
1337 		if (closid_allocated(i) && i != closid &&
1338 		    mode != RDT_MODE_PSEUDO_LOCKSETUP) {
1339 			if (bitmap_intersects(&cbm, &ctrl_b, r->cache.cbm_len)) {
1340 				if (exclusive) {
1341 					if (mode == RDT_MODE_EXCLUSIVE)
1342 						return true;
1343 					continue;
1344 				}
1345 				return true;
1346 			}
1347 		}
1348 	}
1349 
1350 	return false;
1351 }
1352 
1353 /**
1354  * rdtgroup_cbm_overlaps - Does CBM overlap with other use of hardware
1355  * @s: Schema for the resource to which domain instance @d belongs.
1356  * @d: The domain instance for which @closid is being tested.
1357  * @cbm: Capacity bitmask being tested.
1358  * @closid: Intended closid for @cbm.
1359  * @exclusive: Only check if overlaps with exclusive resource groups
1360  *
1361  * Resources that can be allocated using a CBM can use the CBM to control
1362  * the overlap of these allocations. rdtgroup_cmb_overlaps() is the test
1363  * for overlap. Overlap test is not limited to the specific resource for
1364  * which the CBM is intended though - when dealing with CDP resources that
1365  * share the underlying hardware the overlap check should be performed on
1366  * the CDP resource sharing the hardware also.
1367  *
1368  * Refer to description of __rdtgroup_cbm_overlaps() for the details of the
1369  * overlap test.
1370  *
1371  * Return: true if CBM overlap detected, false if there is no overlap
1372  */
1373 bool rdtgroup_cbm_overlaps(struct resctrl_schema *s, struct rdt_ctrl_domain *d,
1374 			   unsigned long cbm, int closid, bool exclusive)
1375 {
1376 	enum resctrl_conf_type peer_type = resctrl_peer_type(s->conf_type);
1377 	struct rdt_resource *r = s->res;
1378 
1379 	if (__rdtgroup_cbm_overlaps(r, d, cbm, closid, s->conf_type,
1380 				    exclusive))
1381 		return true;
1382 
1383 	if (!resctrl_arch_get_cdp_enabled(r->rid))
1384 		return false;
1385 	return  __rdtgroup_cbm_overlaps(r, d, cbm, closid, peer_type, exclusive);
1386 }
1387 
1388 /**
1389  * rdtgroup_mode_test_exclusive - Test if this resource group can be exclusive
1390  * @rdtgrp: Resource group identified through its closid.
1391  *
1392  * An exclusive resource group implies that there should be no sharing of
1393  * its allocated resources. At the time this group is considered to be
1394  * exclusive this test can determine if its current schemata supports this
1395  * setting by testing for overlap with all other resource groups.
1396  *
1397  * Return: true if resource group can be exclusive, false if there is overlap
1398  * with allocations of other resource groups and thus this resource group
1399  * cannot be exclusive.
1400  */
1401 static bool rdtgroup_mode_test_exclusive(struct rdtgroup *rdtgrp)
1402 {
1403 	int closid = rdtgrp->closid;
1404 	struct rdt_ctrl_domain *d;
1405 	struct resctrl_schema *s;
1406 	struct rdt_resource *r;
1407 	bool has_cache = false;
1408 	u32 ctrl;
1409 
1410 	/* Walking r->domains, ensure it can't race with cpuhp */
1411 	lockdep_assert_cpus_held();
1412 
1413 	list_for_each_entry(s, &resctrl_schema_all, list) {
1414 		r = s->res;
1415 		if (r->rid == RDT_RESOURCE_MBA || r->rid == RDT_RESOURCE_SMBA)
1416 			continue;
1417 		has_cache = true;
1418 		list_for_each_entry(d, &r->ctrl_domains, hdr.list) {
1419 			ctrl = resctrl_arch_get_config(r, d, closid,
1420 						       s->conf_type);
1421 			if (rdtgroup_cbm_overlaps(s, d, ctrl, closid, false)) {
1422 				rdt_last_cmd_puts("Schemata overlaps\n");
1423 				return false;
1424 			}
1425 		}
1426 	}
1427 
1428 	if (!has_cache) {
1429 		rdt_last_cmd_puts("Cannot be exclusive without CAT/CDP\n");
1430 		return false;
1431 	}
1432 
1433 	return true;
1434 }
1435 
1436 /*
1437  * rdtgroup_mode_write - Modify the resource group's mode
1438  */
1439 static ssize_t rdtgroup_mode_write(struct kernfs_open_file *of,
1440 				   char *buf, size_t nbytes, loff_t off)
1441 {
1442 	struct rdtgroup *rdtgrp;
1443 	enum rdtgrp_mode mode;
1444 	int ret = 0;
1445 
1446 	/* Valid input requires a trailing newline */
1447 	if (nbytes == 0 || buf[nbytes - 1] != '\n')
1448 		return -EINVAL;
1449 	buf[nbytes - 1] = '\0';
1450 
1451 	rdtgrp = rdtgroup_kn_lock_live(of->kn);
1452 	if (!rdtgrp) {
1453 		rdtgroup_kn_unlock(of->kn);
1454 		return -ENOENT;
1455 	}
1456 
1457 	rdt_last_cmd_clear();
1458 
1459 	mode = rdtgrp->mode;
1460 
1461 	if ((!strcmp(buf, "shareable") && mode == RDT_MODE_SHAREABLE) ||
1462 	    (!strcmp(buf, "exclusive") && mode == RDT_MODE_EXCLUSIVE) ||
1463 	    (!strcmp(buf, "pseudo-locksetup") &&
1464 	     mode == RDT_MODE_PSEUDO_LOCKSETUP) ||
1465 	    (!strcmp(buf, "pseudo-locked") && mode == RDT_MODE_PSEUDO_LOCKED))
1466 		goto out;
1467 
1468 	if (mode == RDT_MODE_PSEUDO_LOCKED) {
1469 		rdt_last_cmd_puts("Cannot change pseudo-locked group\n");
1470 		ret = -EINVAL;
1471 		goto out;
1472 	}
1473 
1474 	if (!strcmp(buf, "shareable")) {
1475 		if (rdtgrp->mode == RDT_MODE_PSEUDO_LOCKSETUP) {
1476 			ret = rdtgroup_locksetup_exit(rdtgrp);
1477 			if (ret)
1478 				goto out;
1479 		}
1480 		rdtgrp->mode = RDT_MODE_SHAREABLE;
1481 	} else if (!strcmp(buf, "exclusive")) {
1482 		if (!rdtgroup_mode_test_exclusive(rdtgrp)) {
1483 			ret = -EINVAL;
1484 			goto out;
1485 		}
1486 		if (rdtgrp->mode == RDT_MODE_PSEUDO_LOCKSETUP) {
1487 			ret = rdtgroup_locksetup_exit(rdtgrp);
1488 			if (ret)
1489 				goto out;
1490 		}
1491 		rdtgrp->mode = RDT_MODE_EXCLUSIVE;
1492 	} else if (IS_ENABLED(CONFIG_RESCTRL_FS_PSEUDO_LOCK) &&
1493 		   !strcmp(buf, "pseudo-locksetup")) {
1494 		ret = rdtgroup_locksetup_enter(rdtgrp);
1495 		if (ret)
1496 			goto out;
1497 		rdtgrp->mode = RDT_MODE_PSEUDO_LOCKSETUP;
1498 	} else {
1499 		rdt_last_cmd_puts("Unknown or unsupported mode\n");
1500 		ret = -EINVAL;
1501 	}
1502 
1503 out:
1504 	rdtgroup_kn_unlock(of->kn);
1505 	return ret ?: nbytes;
1506 }
1507 
1508 /**
1509  * rdtgroup_cbm_to_size - Translate CBM to size in bytes
1510  * @r: RDT resource to which @d belongs.
1511  * @d: RDT domain instance.
1512  * @cbm: bitmask for which the size should be computed.
1513  *
1514  * The bitmask provided associated with the RDT domain instance @d will be
1515  * translated into how many bytes it represents. The size in bytes is
1516  * computed by first dividing the total cache size by the CBM length to
1517  * determine how many bytes each bit in the bitmask represents. The result
1518  * is multiplied with the number of bits set in the bitmask.
1519  *
1520  * @cbm is unsigned long, even if only 32 bits are used to make the
1521  * bitmap functions work correctly.
1522  *
1523  * Return: Size (in bytes) of cache portion represented by CBM, 0 on failure.
1524  */
1525 unsigned int rdtgroup_cbm_to_size(struct rdt_resource *r,
1526 				  struct rdt_ctrl_domain *d, unsigned long cbm)
1527 {
1528 	unsigned int size = 0;
1529 	struct cacheinfo *ci;
1530 	int num_b;
1531 
1532 	if (WARN_ON_ONCE(r->ctrl_scope != RESCTRL_L2_CACHE && r->ctrl_scope != RESCTRL_L3_CACHE))
1533 		return size;
1534 
1535 	num_b = bitmap_weight(&cbm, r->cache.cbm_len);
1536 	ci = get_cpu_cacheinfo_level(cpumask_any(&d->hdr.cpu_mask), r->ctrl_scope);
1537 	if (ci)
1538 		size = ci->size / r->cache.cbm_len * num_b;
1539 
1540 	return size;
1541 }
1542 
1543 bool is_mba_sc(struct rdt_resource *r)
1544 {
1545 	if (!r)
1546 		r = resctrl_arch_get_resource(RDT_RESOURCE_MBA);
1547 
1548 	/*
1549 	 * The software controller support is only applicable to MBA resource.
1550 	 * Make sure to check for resource type.
1551 	 */
1552 	if (r->rid != RDT_RESOURCE_MBA)
1553 		return false;
1554 
1555 	return r->membw.mba_sc;
1556 }
1557 
1558 /*
1559  * rdtgroup_size_show - Display size in bytes of allocated regions
1560  *
1561  * The "size" file mirrors the layout of the "schemata" file, printing the
1562  * size in bytes of each region instead of the capacity bitmask.
1563  */
1564 static int rdtgroup_size_show(struct kernfs_open_file *of,
1565 			      struct seq_file *s, void *v)
1566 {
1567 	struct resctrl_schema *schema;
1568 	enum resctrl_conf_type type;
1569 	struct rdt_ctrl_domain *d;
1570 	struct rdtgroup *rdtgrp;
1571 	struct rdt_resource *r;
1572 	unsigned int size;
1573 	int ret = 0;
1574 	u32 closid;
1575 	bool sep;
1576 	u32 ctrl;
1577 
1578 	rdtgrp = rdtgroup_kn_lock_live(of->kn);
1579 	if (!rdtgrp) {
1580 		rdtgroup_kn_unlock(of->kn);
1581 		return -ENOENT;
1582 	}
1583 
1584 	if (rdtgrp->mode == RDT_MODE_PSEUDO_LOCKED) {
1585 		if (!rdtgrp->plr->d) {
1586 			rdt_last_cmd_clear();
1587 			rdt_last_cmd_puts("Cache domain offline\n");
1588 			ret = -ENODEV;
1589 		} else {
1590 			seq_printf(s, "%*s:", max_name_width,
1591 				   rdtgrp->plr->s->name);
1592 			size = rdtgroup_cbm_to_size(rdtgrp->plr->s->res,
1593 						    rdtgrp->plr->d,
1594 						    rdtgrp->plr->cbm);
1595 			seq_printf(s, "%d=%u\n", rdtgrp->plr->d->hdr.id, size);
1596 		}
1597 		goto out;
1598 	}
1599 
1600 	closid = rdtgrp->closid;
1601 
1602 	list_for_each_entry(schema, &resctrl_schema_all, list) {
1603 		r = schema->res;
1604 		type = schema->conf_type;
1605 		sep = false;
1606 		seq_printf(s, "%*s:", max_name_width, schema->name);
1607 		list_for_each_entry(d, &r->ctrl_domains, hdr.list) {
1608 			if (sep)
1609 				seq_putc(s, ';');
1610 			if (rdtgrp->mode == RDT_MODE_PSEUDO_LOCKSETUP) {
1611 				size = 0;
1612 			} else {
1613 				if (is_mba_sc(r))
1614 					ctrl = d->mbps_val[closid];
1615 				else
1616 					ctrl = resctrl_arch_get_config(r, d,
1617 								       closid,
1618 								       type);
1619 				if (r->rid == RDT_RESOURCE_MBA ||
1620 				    r->rid == RDT_RESOURCE_SMBA)
1621 					size = ctrl;
1622 				else
1623 					size = rdtgroup_cbm_to_size(r, d, ctrl);
1624 			}
1625 			seq_printf(s, "%d=%u", d->hdr.id, size);
1626 			sep = true;
1627 		}
1628 		seq_putc(s, '\n');
1629 	}
1630 
1631 out:
1632 	rdtgroup_kn_unlock(of->kn);
1633 
1634 	return ret;
1635 }
1636 
1637 static void mondata_config_read(struct resctrl_mon_config_info *mon_info)
1638 {
1639 	smp_call_function_any(&mon_info->d->hdr.cpu_mask,
1640 			      resctrl_arch_mon_event_config_read, mon_info, 1);
1641 }
1642 
1643 static int mbm_config_show(struct seq_file *s, struct rdt_resource *r, u32 evtid)
1644 {
1645 	struct resctrl_mon_config_info mon_info;
1646 	struct rdt_l3_mon_domain *dom;
1647 	bool sep = false;
1648 
1649 	cpus_read_lock();
1650 	mutex_lock(&rdtgroup_mutex);
1651 
1652 	list_for_each_entry(dom, &r->mon_domains, hdr.list) {
1653 		if (sep)
1654 			seq_puts(s, ";");
1655 
1656 		memset(&mon_info, 0, sizeof(struct resctrl_mon_config_info));
1657 		mon_info.r = r;
1658 		mon_info.d = dom;
1659 		mon_info.evtid = evtid;
1660 		mondata_config_read(&mon_info);
1661 
1662 		seq_printf(s, "%d=0x%02x", dom->hdr.id, mon_info.mon_config);
1663 		sep = true;
1664 	}
1665 	seq_puts(s, "\n");
1666 
1667 	mutex_unlock(&rdtgroup_mutex);
1668 	cpus_read_unlock();
1669 
1670 	return 0;
1671 }
1672 
1673 static int mbm_total_bytes_config_show(struct kernfs_open_file *of,
1674 				       struct seq_file *seq, void *v)
1675 {
1676 	struct rdt_resource *r = rdt_kn_parent_priv(of->kn);
1677 
1678 	mbm_config_show(seq, r, QOS_L3_MBM_TOTAL_EVENT_ID);
1679 
1680 	return 0;
1681 }
1682 
1683 static int mbm_local_bytes_config_show(struct kernfs_open_file *of,
1684 				       struct seq_file *seq, void *v)
1685 {
1686 	struct rdt_resource *r = rdt_kn_parent_priv(of->kn);
1687 
1688 	mbm_config_show(seq, r, QOS_L3_MBM_LOCAL_EVENT_ID);
1689 
1690 	return 0;
1691 }
1692 
1693 static void mbm_config_write_domain(struct rdt_resource *r,
1694 				    struct rdt_l3_mon_domain *d, u32 evtid, u32 val)
1695 {
1696 	struct resctrl_mon_config_info mon_info = {0};
1697 
1698 	/*
1699 	 * Read the current config value first. If both are the same then
1700 	 * no need to write it again.
1701 	 */
1702 	mon_info.r = r;
1703 	mon_info.d = d;
1704 	mon_info.evtid = evtid;
1705 	mondata_config_read(&mon_info);
1706 	if (mon_info.mon_config == val)
1707 		return;
1708 
1709 	mon_info.mon_config = val;
1710 
1711 	/*
1712 	 * Update MSR_IA32_EVT_CFG_BASE MSR on one of the CPUs in the
1713 	 * domain. The MSRs offset from MSR MSR_IA32_EVT_CFG_BASE
1714 	 * are scoped at the domain level. Writing any of these MSRs
1715 	 * on one CPU is observed by all the CPUs in the domain.
1716 	 */
1717 	smp_call_function_any(&d->hdr.cpu_mask, resctrl_arch_mon_event_config_write,
1718 			      &mon_info, 1);
1719 
1720 	/*
1721 	 * When an Event Configuration is changed, the bandwidth counters
1722 	 * for all RMIDs and Events will be cleared by the hardware. The
1723 	 * hardware also sets MSR_IA32_QM_CTR.Unavailable (bit 62) for
1724 	 * every RMID on the next read to any event for every RMID.
1725 	 * Subsequent reads will have MSR_IA32_QM_CTR.Unavailable (bit 62)
1726 	 * cleared while it is tracked by the hardware. Clear the
1727 	 * mbm_local and mbm_total counts for all the RMIDs.
1728 	 */
1729 	resctrl_arch_reset_rmid_all(r, d);
1730 }
1731 
1732 static int mon_config_write(struct rdt_resource *r, char *tok, u32 evtid)
1733 {
1734 	char *dom_str = NULL, *id_str;
1735 	struct rdt_l3_mon_domain *d;
1736 	unsigned long dom_id, val;
1737 
1738 	/* Walking r->domains, ensure it can't race with cpuhp */
1739 	lockdep_assert_cpus_held();
1740 
1741 next:
1742 	if (!tok || tok[0] == '\0')
1743 		return 0;
1744 
1745 	/* Start processing the strings for each domain */
1746 	dom_str = strim(strsep(&tok, ";"));
1747 	id_str = strsep(&dom_str, "=");
1748 
1749 	if (!id_str || kstrtoul(id_str, 10, &dom_id)) {
1750 		rdt_last_cmd_puts("Missing '=' or non-numeric domain id\n");
1751 		return -EINVAL;
1752 	}
1753 
1754 	if (!dom_str || kstrtoul(dom_str, 16, &val)) {
1755 		rdt_last_cmd_puts("Non-numeric event configuration value\n");
1756 		return -EINVAL;
1757 	}
1758 
1759 	/* Value from user cannot be more than the supported set of events */
1760 	if ((val & r->mon.mbm_cfg_mask) != val) {
1761 		rdt_last_cmd_printf("Invalid event configuration: max valid mask is 0x%02x\n",
1762 				    r->mon.mbm_cfg_mask);
1763 		return -EINVAL;
1764 	}
1765 
1766 	list_for_each_entry(d, &r->mon_domains, hdr.list) {
1767 		if (d->hdr.id == dom_id) {
1768 			mbm_config_write_domain(r, d, evtid, val);
1769 			goto next;
1770 		}
1771 	}
1772 
1773 	return -EINVAL;
1774 }
1775 
1776 static ssize_t mbm_total_bytes_config_write(struct kernfs_open_file *of,
1777 					    char *buf, size_t nbytes,
1778 					    loff_t off)
1779 {
1780 	struct rdt_resource *r = rdt_kn_parent_priv(of->kn);
1781 	int ret;
1782 
1783 	/* Valid input requires a trailing newline */
1784 	if (nbytes == 0 || buf[nbytes - 1] != '\n')
1785 		return -EINVAL;
1786 
1787 	cpus_read_lock();
1788 	mutex_lock(&rdtgroup_mutex);
1789 
1790 	rdt_last_cmd_clear();
1791 
1792 	buf[nbytes - 1] = '\0';
1793 
1794 	ret = mon_config_write(r, buf, QOS_L3_MBM_TOTAL_EVENT_ID);
1795 
1796 	mutex_unlock(&rdtgroup_mutex);
1797 	cpus_read_unlock();
1798 
1799 	return ret ?: nbytes;
1800 }
1801 
1802 static ssize_t mbm_local_bytes_config_write(struct kernfs_open_file *of,
1803 					    char *buf, size_t nbytes,
1804 					    loff_t off)
1805 {
1806 	struct rdt_resource *r = rdt_kn_parent_priv(of->kn);
1807 	int ret;
1808 
1809 	/* Valid input requires a trailing newline */
1810 	if (nbytes == 0 || buf[nbytes - 1] != '\n')
1811 		return -EINVAL;
1812 
1813 	cpus_read_lock();
1814 	mutex_lock(&rdtgroup_mutex);
1815 
1816 	rdt_last_cmd_clear();
1817 
1818 	buf[nbytes - 1] = '\0';
1819 
1820 	ret = mon_config_write(r, buf, QOS_L3_MBM_LOCAL_EVENT_ID);
1821 
1822 	mutex_unlock(&rdtgroup_mutex);
1823 	cpus_read_unlock();
1824 
1825 	return ret ?: nbytes;
1826 }
1827 
1828 /*
1829  * resctrl_bmec_files_show() — Controls the visibility of BMEC-related resctrl
1830  * files. When @show is true, the files are displayed; when false, the files
1831  * are hidden.
1832  * Don't treat kernfs_find_and_get failure as an error, since this function may
1833  * be called regardless of whether BMEC is supported or the event is enabled.
1834  */
1835 void resctrl_bmec_files_show(struct rdt_resource *r, struct kernfs_node *l3_mon_kn,
1836 			     bool show)
1837 {
1838 	struct kernfs_node *kn_config, *mon_kn = NULL;
1839 	char name[32];
1840 
1841 	if (!l3_mon_kn) {
1842 		sprintf(name, "%s_MON", r->name);
1843 		mon_kn = kernfs_find_and_get(kn_info, name);
1844 		if (!mon_kn)
1845 			return;
1846 		l3_mon_kn = mon_kn;
1847 	}
1848 
1849 	kn_config = kernfs_find_and_get(l3_mon_kn, "mbm_total_bytes_config");
1850 	if (kn_config) {
1851 		kernfs_show(kn_config, show);
1852 		kernfs_put(kn_config);
1853 	}
1854 
1855 	kn_config = kernfs_find_and_get(l3_mon_kn, "mbm_local_bytes_config");
1856 	if (kn_config) {
1857 		kernfs_show(kn_config, show);
1858 		kernfs_put(kn_config);
1859 	}
1860 
1861 	/* Release the reference only if it was acquired */
1862 	if (mon_kn)
1863 		kernfs_put(mon_kn);
1864 }
1865 
1866 const char *rdtgroup_name_by_closid(u32 closid)
1867 {
1868 	struct rdtgroup *rdtgrp;
1869 
1870 	list_for_each_entry(rdtgrp, &rdt_all_groups, rdtgroup_list) {
1871 		if (rdtgrp->closid == closid)
1872 			return rdt_kn_name(rdtgrp->kn);
1873 	}
1874 
1875 	return NULL;
1876 }
1877 
1878 /* rdtgroup information files for one cache resource. */
1879 static struct rftype res_common_files[] = {
1880 	{
1881 		.name		= "last_cmd_status",
1882 		.mode		= 0444,
1883 		.kf_ops		= &rdtgroup_kf_single_ops,
1884 		.seq_show	= rdt_last_cmd_status_show,
1885 		.fflags		= RFTYPE_TOP_INFO,
1886 	},
1887 	{
1888 		.name		= "mbm_assign_on_mkdir",
1889 		.mode		= 0644,
1890 		.kf_ops		= &rdtgroup_kf_single_ops,
1891 		.seq_show	= resctrl_mbm_assign_on_mkdir_show,
1892 		.write		= resctrl_mbm_assign_on_mkdir_write,
1893 	},
1894 	{
1895 		.name		= "num_closids",
1896 		.mode		= 0444,
1897 		.kf_ops		= &rdtgroup_kf_single_ops,
1898 		.seq_show	= rdt_num_closids_show,
1899 		.fflags		= RFTYPE_CTRL_INFO,
1900 	},
1901 	{
1902 		.name		= "mon_features",
1903 		.mode		= 0444,
1904 		.kf_ops		= &rdtgroup_kf_single_ops,
1905 		.seq_show	= rdt_mon_features_show,
1906 		.fflags		= RFTYPE_MON_INFO,
1907 	},
1908 	{
1909 		.name		= "available_mbm_cntrs",
1910 		.mode		= 0444,
1911 		.kf_ops		= &rdtgroup_kf_single_ops,
1912 		.seq_show	= resctrl_available_mbm_cntrs_show,
1913 	},
1914 	{
1915 		.name		= "num_rmids",
1916 		.mode		= 0444,
1917 		.kf_ops		= &rdtgroup_kf_single_ops,
1918 		.seq_show	= rdt_num_rmids_show,
1919 		.fflags		= RFTYPE_MON_INFO,
1920 	},
1921 	{
1922 		.name		= "cbm_mask",
1923 		.mode		= 0444,
1924 		.kf_ops		= &rdtgroup_kf_single_ops,
1925 		.seq_show	= rdt_default_ctrl_show,
1926 		.fflags		= RFTYPE_CTRL_INFO | RFTYPE_RES_CACHE,
1927 	},
1928 	{
1929 		.name		= "num_mbm_cntrs",
1930 		.mode		= 0444,
1931 		.kf_ops		= &rdtgroup_kf_single_ops,
1932 		.seq_show	= resctrl_num_mbm_cntrs_show,
1933 	},
1934 	{
1935 		.name		= "min_cbm_bits",
1936 		.mode		= 0444,
1937 		.kf_ops		= &rdtgroup_kf_single_ops,
1938 		.seq_show	= rdt_min_cbm_bits_show,
1939 		.fflags		= RFTYPE_CTRL_INFO | RFTYPE_RES_CACHE,
1940 	},
1941 	{
1942 		.name		= "shareable_bits",
1943 		.mode		= 0444,
1944 		.kf_ops		= &rdtgroup_kf_single_ops,
1945 		.seq_show	= rdt_shareable_bits_show,
1946 		.fflags		= RFTYPE_CTRL_INFO | RFTYPE_RES_CACHE,
1947 	},
1948 	{
1949 		.name		= "bit_usage",
1950 		.mode		= 0444,
1951 		.kf_ops		= &rdtgroup_kf_single_ops,
1952 		.seq_show	= rdt_bit_usage_show,
1953 		.fflags		= RFTYPE_CTRL_INFO | RFTYPE_RES_CACHE,
1954 	},
1955 	{
1956 		.name		= "min_bandwidth",
1957 		.mode		= 0444,
1958 		.kf_ops		= &rdtgroup_kf_single_ops,
1959 		.seq_show	= rdt_min_bw_show,
1960 		.fflags		= RFTYPE_CTRL_INFO | RFTYPE_RES_MB,
1961 	},
1962 	{
1963 		.name		= "bandwidth_gran",
1964 		.mode		= 0444,
1965 		.kf_ops		= &rdtgroup_kf_single_ops,
1966 		.seq_show	= rdt_bw_gran_show,
1967 		.fflags		= RFTYPE_CTRL_INFO | RFTYPE_RES_MB,
1968 	},
1969 	{
1970 		.name		= "delay_linear",
1971 		.mode		= 0444,
1972 		.kf_ops		= &rdtgroup_kf_single_ops,
1973 		.seq_show	= rdt_delay_linear_show,
1974 		.fflags		= RFTYPE_CTRL_INFO | RFTYPE_RES_MB,
1975 	},
1976 	/*
1977 	 * Platform specific which (if any) capabilities are provided by
1978 	 * thread_throttle_mode. Defer "fflags" initialization to platform
1979 	 * discovery.
1980 	 */
1981 	{
1982 		.name		= "thread_throttle_mode",
1983 		.mode		= 0444,
1984 		.kf_ops		= &rdtgroup_kf_single_ops,
1985 		.seq_show	= rdt_thread_throttle_mode_show,
1986 	},
1987 	{
1988 		.name		= "io_alloc",
1989 		.mode		= 0644,
1990 		.kf_ops		= &rdtgroup_kf_single_ops,
1991 		.seq_show	= resctrl_io_alloc_show,
1992 		.write          = resctrl_io_alloc_write,
1993 	},
1994 	{
1995 		.name		= "io_alloc_cbm",
1996 		.mode		= 0644,
1997 		.kf_ops		= &rdtgroup_kf_single_ops,
1998 		.seq_show	= resctrl_io_alloc_cbm_show,
1999 		.write		= resctrl_io_alloc_cbm_write,
2000 	},
2001 	{
2002 		.name		= "max_threshold_occupancy",
2003 		.mode		= 0644,
2004 		.kf_ops		= &rdtgroup_kf_single_ops,
2005 		.write		= max_threshold_occ_write,
2006 		.seq_show	= max_threshold_occ_show,
2007 		.fflags		= RFTYPE_MON_INFO | RFTYPE_RES_CACHE,
2008 	},
2009 	{
2010 		.name		= "mbm_total_bytes_config",
2011 		.mode		= 0644,
2012 		.kf_ops		= &rdtgroup_kf_single_ops,
2013 		.seq_show	= mbm_total_bytes_config_show,
2014 		.write		= mbm_total_bytes_config_write,
2015 	},
2016 	{
2017 		.name		= "mbm_local_bytes_config",
2018 		.mode		= 0644,
2019 		.kf_ops		= &rdtgroup_kf_single_ops,
2020 		.seq_show	= mbm_local_bytes_config_show,
2021 		.write		= mbm_local_bytes_config_write,
2022 	},
2023 	{
2024 		.name		= "event_filter",
2025 		.mode		= 0444,
2026 		.kf_ops		= &rdtgroup_kf_single_ops,
2027 		.seq_show	= event_filter_show,
2028 		.write		= event_filter_write,
2029 	},
2030 	{
2031 		.name		= "mbm_L3_assignments",
2032 		.mode		= 0644,
2033 		.kf_ops		= &rdtgroup_kf_single_ops,
2034 		.seq_show	= mbm_L3_assignments_show,
2035 		.write		= mbm_L3_assignments_write,
2036 	},
2037 	{
2038 		.name		= "mbm_assign_mode",
2039 		.mode		= 0644,
2040 		.kf_ops		= &rdtgroup_kf_single_ops,
2041 		.seq_show	= resctrl_mbm_assign_mode_show,
2042 		.write		= resctrl_mbm_assign_mode_write,
2043 		.fflags		= RFTYPE_MON_INFO | RFTYPE_RES_CACHE,
2044 	},
2045 	{
2046 		.name		= "cpus",
2047 		.mode		= 0644,
2048 		.kf_ops		= &rdtgroup_kf_single_ops,
2049 		.write		= rdtgroup_cpus_write,
2050 		.seq_show	= rdtgroup_cpus_show,
2051 		.fflags		= RFTYPE_BASE,
2052 	},
2053 	{
2054 		.name		= "cpus_list",
2055 		.mode		= 0644,
2056 		.kf_ops		= &rdtgroup_kf_single_ops,
2057 		.write		= rdtgroup_cpus_write,
2058 		.seq_show	= rdtgroup_cpus_show,
2059 		.flags		= RFTYPE_FLAGS_CPUS_LIST,
2060 		.fflags		= RFTYPE_BASE,
2061 	},
2062 	{
2063 		.name		= "tasks",
2064 		.mode		= 0644,
2065 		.kf_ops		= &rdtgroup_kf_single_ops,
2066 		.write		= rdtgroup_tasks_write,
2067 		.seq_show	= rdtgroup_tasks_show,
2068 		.fflags		= RFTYPE_BASE,
2069 	},
2070 	{
2071 		.name		= "mon_hw_id",
2072 		.mode		= 0444,
2073 		.kf_ops		= &rdtgroup_kf_single_ops,
2074 		.seq_show	= rdtgroup_rmid_show,
2075 		.fflags		= RFTYPE_MON_BASE | RFTYPE_DEBUG,
2076 	},
2077 	{
2078 		.name		= "schemata",
2079 		.mode		= 0644,
2080 		.kf_ops		= &rdtgroup_kf_single_ops,
2081 		.write		= rdtgroup_schemata_write,
2082 		.seq_show	= rdtgroup_schemata_show,
2083 		.fflags		= RFTYPE_CTRL_BASE,
2084 	},
2085 	{
2086 		.name		= "mba_MBps_event",
2087 		.mode		= 0644,
2088 		.kf_ops		= &rdtgroup_kf_single_ops,
2089 		.write		= rdtgroup_mba_mbps_event_write,
2090 		.seq_show	= rdtgroup_mba_mbps_event_show,
2091 	},
2092 	{
2093 		.name		= "mode",
2094 		.mode		= 0644,
2095 		.kf_ops		= &rdtgroup_kf_single_ops,
2096 		.write		= rdtgroup_mode_write,
2097 		.seq_show	= rdtgroup_mode_show,
2098 		.fflags		= RFTYPE_CTRL_BASE,
2099 	},
2100 	{
2101 		.name		= "size",
2102 		.mode		= 0444,
2103 		.kf_ops		= &rdtgroup_kf_single_ops,
2104 		.seq_show	= rdtgroup_size_show,
2105 		.fflags		= RFTYPE_CTRL_BASE,
2106 	},
2107 	{
2108 		.name		= "sparse_masks",
2109 		.mode		= 0444,
2110 		.kf_ops		= &rdtgroup_kf_single_ops,
2111 		.seq_show	= rdt_has_sparse_bitmasks_show,
2112 		.fflags		= RFTYPE_CTRL_INFO | RFTYPE_RES_CACHE,
2113 	},
2114 	{
2115 		.name		= "ctrl_hw_id",
2116 		.mode		= 0444,
2117 		.kf_ops		= &rdtgroup_kf_single_ops,
2118 		.seq_show	= rdtgroup_closid_show,
2119 		.fflags		= RFTYPE_CTRL_BASE | RFTYPE_DEBUG,
2120 	},
2121 };
2122 
2123 static int rdtgroup_add_files(struct kernfs_node *kn, unsigned long fflags)
2124 {
2125 	struct rftype *rfts, *rft;
2126 	int ret, len;
2127 
2128 	rfts = res_common_files;
2129 	len = ARRAY_SIZE(res_common_files);
2130 
2131 	lockdep_assert_held(&rdtgroup_mutex);
2132 
2133 	if (resctrl_debug)
2134 		fflags |= RFTYPE_DEBUG;
2135 
2136 	for (rft = rfts; rft < rfts + len; rft++) {
2137 		if (rft->fflags && ((fflags & rft->fflags) == rft->fflags)) {
2138 			ret = rdtgroup_add_file(kn, rft);
2139 			if (ret)
2140 				goto error;
2141 		}
2142 	}
2143 
2144 	return 0;
2145 error:
2146 	pr_warn("Failed to add %s, err=%d\n", rft->name, ret);
2147 	while (--rft >= rfts) {
2148 		if ((fflags & rft->fflags) == rft->fflags)
2149 			kernfs_remove_by_name(kn, rft->name);
2150 	}
2151 	return ret;
2152 }
2153 
2154 static struct rftype *rdtgroup_get_rftype_by_name(const char *name)
2155 {
2156 	struct rftype *rfts, *rft;
2157 	int len;
2158 
2159 	rfts = res_common_files;
2160 	len = ARRAY_SIZE(res_common_files);
2161 
2162 	for (rft = rfts; rft < rfts + len; rft++) {
2163 		if (!strcmp(rft->name, name))
2164 			return rft;
2165 	}
2166 
2167 	return NULL;
2168 }
2169 
2170 static void thread_throttle_mode_init(void)
2171 {
2172 	enum membw_throttle_mode throttle_mode = THREAD_THROTTLE_UNDEFINED;
2173 	struct rdt_resource *r_mba, *r_smba;
2174 
2175 	r_mba = resctrl_arch_get_resource(RDT_RESOURCE_MBA);
2176 	if (r_mba->alloc_capable &&
2177 	    r_mba->membw.throttle_mode != THREAD_THROTTLE_UNDEFINED)
2178 		throttle_mode = r_mba->membw.throttle_mode;
2179 
2180 	r_smba = resctrl_arch_get_resource(RDT_RESOURCE_SMBA);
2181 	if (r_smba->alloc_capable &&
2182 	    r_smba->membw.throttle_mode != THREAD_THROTTLE_UNDEFINED)
2183 		throttle_mode = r_smba->membw.throttle_mode;
2184 
2185 	if (throttle_mode == THREAD_THROTTLE_UNDEFINED)
2186 		return;
2187 
2188 	resctrl_file_fflags_init("thread_throttle_mode",
2189 				 RFTYPE_CTRL_INFO | RFTYPE_RES_MB);
2190 }
2191 
2192 /*
2193  * The resctrl file "io_alloc" is added using L3 resource. However, it results
2194  * in this file being visible for *all* cache resources (eg. L2 cache),
2195  * whether it supports "io_alloc" or not.
2196  */
2197 static void io_alloc_init(void)
2198 {
2199 	struct rdt_resource *r = resctrl_arch_get_resource(RDT_RESOURCE_L3);
2200 
2201 	if (r->cache.io_alloc_capable) {
2202 		resctrl_file_fflags_init("io_alloc", RFTYPE_CTRL_INFO |
2203 					 RFTYPE_RES_CACHE);
2204 		resctrl_file_fflags_init("io_alloc_cbm",
2205 					 RFTYPE_CTRL_INFO | RFTYPE_RES_CACHE);
2206 	}
2207 }
2208 
2209 void resctrl_file_fflags_init(const char *config, unsigned long fflags)
2210 {
2211 	struct rftype *rft;
2212 
2213 	rft = rdtgroup_get_rftype_by_name(config);
2214 	if (rft)
2215 		rft->fflags = fflags;
2216 }
2217 
2218 void resctrl_file_mode_init(const char *config, umode_t mode)
2219 {
2220 	struct rftype *rft;
2221 
2222 	rft = rdtgroup_get_rftype_by_name(config);
2223 	if (rft)
2224 		rft->mode = mode;
2225 }
2226 
2227 /**
2228  * rdtgroup_kn_mode_restrict - Restrict user access to named resctrl file
2229  * @r: The resource group with which the file is associated.
2230  * @name: Name of the file
2231  *
2232  * The permissions of named resctrl file, directory, or link are modified
2233  * to not allow read, write, or execute by any user.
2234  *
2235  * WARNING: This function is intended to communicate to the user that the
2236  * resctrl file has been locked down - that it is not relevant to the
2237  * particular state the system finds itself in. It should not be relied
2238  * on to protect from user access because after the file's permissions
2239  * are restricted the user can still change the permissions using chmod
2240  * from the command line.
2241  *
2242  * Return: 0 on success, <0 on failure.
2243  */
2244 int rdtgroup_kn_mode_restrict(struct rdtgroup *r, const char *name)
2245 {
2246 	struct iattr iattr = {.ia_valid = ATTR_MODE,};
2247 	struct kernfs_node *kn;
2248 	int ret = 0;
2249 
2250 	kn = kernfs_find_and_get_ns(r->kn, name, NULL);
2251 	if (!kn)
2252 		return -ENOENT;
2253 
2254 	switch (kernfs_type(kn)) {
2255 	case KERNFS_DIR:
2256 		iattr.ia_mode = S_IFDIR;
2257 		break;
2258 	case KERNFS_FILE:
2259 		iattr.ia_mode = S_IFREG;
2260 		break;
2261 	case KERNFS_LINK:
2262 		iattr.ia_mode = S_IFLNK;
2263 		break;
2264 	}
2265 
2266 	ret = kernfs_setattr(kn, &iattr);
2267 	kernfs_put(kn);
2268 	return ret;
2269 }
2270 
2271 /**
2272  * rdtgroup_kn_mode_restore - Restore user access to named resctrl file
2273  * @r: The resource group with which the file is associated.
2274  * @name: Name of the file
2275  * @mask: Mask of permissions that should be restored
2276  *
2277  * Restore the permissions of the named file. If @name is a directory the
2278  * permissions of its parent will be used.
2279  *
2280  * Return: 0 on success, <0 on failure.
2281  */
2282 int rdtgroup_kn_mode_restore(struct rdtgroup *r, const char *name,
2283 			     umode_t mask)
2284 {
2285 	struct iattr iattr = {.ia_valid = ATTR_MODE,};
2286 	struct kernfs_node *kn, *parent;
2287 	struct rftype *rfts, *rft;
2288 	int ret, len;
2289 
2290 	rfts = res_common_files;
2291 	len = ARRAY_SIZE(res_common_files);
2292 
2293 	for (rft = rfts; rft < rfts + len; rft++) {
2294 		if (!strcmp(rft->name, name))
2295 			iattr.ia_mode = rft->mode & mask;
2296 	}
2297 
2298 	kn = kernfs_find_and_get_ns(r->kn, name, NULL);
2299 	if (!kn)
2300 		return -ENOENT;
2301 
2302 	switch (kernfs_type(kn)) {
2303 	case KERNFS_DIR:
2304 		parent = kernfs_get_parent(kn);
2305 		if (parent) {
2306 			iattr.ia_mode |= parent->mode;
2307 			kernfs_put(parent);
2308 		}
2309 		iattr.ia_mode |= S_IFDIR;
2310 		break;
2311 	case KERNFS_FILE:
2312 		iattr.ia_mode |= S_IFREG;
2313 		break;
2314 	case KERNFS_LINK:
2315 		iattr.ia_mode |= S_IFLNK;
2316 		break;
2317 	}
2318 
2319 	ret = kernfs_setattr(kn, &iattr);
2320 	kernfs_put(kn);
2321 	return ret;
2322 }
2323 
2324 static int resctrl_mkdir_event_configs(struct rdt_resource *r, struct kernfs_node *l3_mon_kn)
2325 {
2326 	struct kernfs_node *kn_subdir, *kn_subdir2;
2327 	struct mon_evt *mevt;
2328 	int ret;
2329 
2330 	kn_subdir = kernfs_create_dir(l3_mon_kn, "event_configs", l3_mon_kn->mode, NULL);
2331 	if (IS_ERR(kn_subdir))
2332 		return PTR_ERR(kn_subdir);
2333 
2334 	ret = rdtgroup_kn_set_ugid(kn_subdir);
2335 	if (ret)
2336 		return ret;
2337 
2338 	for_each_mon_event(mevt) {
2339 		if (mevt->rid != r->rid || !mevt->enabled || !resctrl_is_mbm_event(mevt->evtid))
2340 			continue;
2341 
2342 		kn_subdir2 = kernfs_create_dir(kn_subdir, mevt->name, kn_subdir->mode, mevt);
2343 		if (IS_ERR(kn_subdir2))
2344 			return PTR_ERR(kn_subdir2);
2345 
2346 		ret = rdtgroup_kn_set_ugid(kn_subdir2);
2347 		if (ret)
2348 			return ret;
2349 
2350 		ret = rdtgroup_add_files(kn_subdir2, RFTYPE_ASSIGN_CONFIG);
2351 		if (ret)
2352 			return ret;
2353 	}
2354 
2355 	return 0;
2356 }
2357 
2358 static int rdtgroup_mkdir_info_resdir(void *priv, char *name,
2359 				      unsigned long fflags)
2360 {
2361 	struct kernfs_node *kn_subdir;
2362 	struct rdt_resource *r;
2363 	int ret;
2364 
2365 	kn_subdir = kernfs_create_dir(kn_info, name,
2366 				      kn_info->mode, priv);
2367 	if (IS_ERR(kn_subdir))
2368 		return PTR_ERR(kn_subdir);
2369 
2370 	ret = rdtgroup_kn_set_ugid(kn_subdir);
2371 	if (ret)
2372 		return ret;
2373 
2374 	ret = rdtgroup_add_files(kn_subdir, fflags);
2375 	if (ret)
2376 		return ret;
2377 
2378 	if ((fflags & RFTYPE_MON_INFO) == RFTYPE_MON_INFO) {
2379 		r = priv;
2380 		if (r->mon.mbm_cntr_assignable) {
2381 			ret = resctrl_mkdir_event_configs(r, kn_subdir);
2382 			if (ret)
2383 				return ret;
2384 			/*
2385 			 * Hide BMEC related files if mbm_event mode
2386 			 * is enabled.
2387 			 */
2388 			if (resctrl_arch_mbm_cntr_assign_enabled(r))
2389 				resctrl_bmec_files_show(r, kn_subdir, false);
2390 		}
2391 	}
2392 
2393 	kernfs_activate(kn_subdir);
2394 
2395 	return ret;
2396 }
2397 
2398 static unsigned long fflags_from_resource(struct rdt_resource *r)
2399 {
2400 	switch (r->rid) {
2401 	case RDT_RESOURCE_L3:
2402 	case RDT_RESOURCE_L2:
2403 		return RFTYPE_RES_CACHE;
2404 	case RDT_RESOURCE_MBA:
2405 	case RDT_RESOURCE_SMBA:
2406 		return RFTYPE_RES_MB;
2407 	case RDT_RESOURCE_PERF_PKG:
2408 		return RFTYPE_RES_PERF_PKG;
2409 	}
2410 
2411 	return WARN_ON_ONCE(1);
2412 }
2413 
2414 static int rdtgroup_create_info_dir(struct kernfs_node *parent_kn)
2415 {
2416 	struct resctrl_schema *s;
2417 	struct rdt_resource *r;
2418 	unsigned long fflags;
2419 	char name[32];
2420 	int ret;
2421 
2422 	/* create the directory */
2423 	kn_info = kernfs_create_dir(parent_kn, "info", parent_kn->mode, NULL);
2424 	if (IS_ERR(kn_info))
2425 		return PTR_ERR(kn_info);
2426 
2427 	ret = rdtgroup_add_files(kn_info, RFTYPE_TOP_INFO);
2428 	if (ret)
2429 		goto out_destroy;
2430 
2431 	/* loop over enabled controls, these are all alloc_capable */
2432 	list_for_each_entry(s, &resctrl_schema_all, list) {
2433 		r = s->res;
2434 		fflags = fflags_from_resource(r) | RFTYPE_CTRL_INFO;
2435 		ret = rdtgroup_mkdir_info_resdir(s, s->name, fflags);
2436 		if (ret)
2437 			goto out_destroy;
2438 	}
2439 
2440 	for_each_mon_capable_rdt_resource(r) {
2441 		fflags = fflags_from_resource(r) | RFTYPE_MON_INFO;
2442 		sprintf(name, "%s_MON", r->name);
2443 		ret = rdtgroup_mkdir_info_resdir(r, name, fflags);
2444 		if (ret)
2445 			goto out_destroy;
2446 	}
2447 
2448 	ret = rdtgroup_kn_set_ugid(kn_info);
2449 	if (ret)
2450 		goto out_destroy;
2451 
2452 	kernfs_activate(kn_info);
2453 
2454 	return 0;
2455 
2456 out_destroy:
2457 	kernfs_remove(kn_info);
2458 	return ret;
2459 }
2460 
2461 static int
2462 mongroup_create_dir(struct kernfs_node *parent_kn, struct rdtgroup *prgrp,
2463 		    char *name, struct kernfs_node **dest_kn)
2464 {
2465 	struct kernfs_node *kn;
2466 	int ret;
2467 
2468 	/* create the directory */
2469 	kn = kernfs_create_dir(parent_kn, name, parent_kn->mode, prgrp);
2470 	if (IS_ERR(kn))
2471 		return PTR_ERR(kn);
2472 
2473 	if (dest_kn)
2474 		*dest_kn = kn;
2475 
2476 	ret = rdtgroup_kn_set_ugid(kn);
2477 	if (ret)
2478 		goto out_destroy;
2479 
2480 	kernfs_activate(kn);
2481 
2482 	return 0;
2483 
2484 out_destroy:
2485 	kernfs_remove(kn);
2486 	return ret;
2487 }
2488 
2489 static inline bool is_mba_linear(void)
2490 {
2491 	return resctrl_arch_get_resource(RDT_RESOURCE_MBA)->membw.delay_linear;
2492 }
2493 
2494 static int mba_sc_domain_allocate(struct rdt_resource *r, struct rdt_ctrl_domain *d)
2495 {
2496 	u32 num_closid = resctrl_arch_get_num_closid(r);
2497 	int cpu = cpumask_any(&d->hdr.cpu_mask);
2498 	int i;
2499 
2500 	d->mbps_val = kcalloc_node(num_closid, sizeof(*d->mbps_val),
2501 				   GFP_KERNEL, cpu_to_node(cpu));
2502 	if (!d->mbps_val)
2503 		return -ENOMEM;
2504 
2505 	for (i = 0; i < num_closid; i++)
2506 		d->mbps_val[i] = MBA_MAX_MBPS;
2507 
2508 	return 0;
2509 }
2510 
2511 static void mba_sc_domain_destroy(struct rdt_resource *r,
2512 				  struct rdt_ctrl_domain *d)
2513 {
2514 	kfree(d->mbps_val);
2515 	d->mbps_val = NULL;
2516 }
2517 
2518 /*
2519  * The MBA software controller is supported only if MBM is supported and MBA is
2520  * in linear scale, and the MBM monitor scope is the same as MBA control scope.
2521  *
2522  * The software controller cannot be supported when the MBM counters are
2523  * assignable.  There is no guarantee that MBM counters are assigned to the
2524  * event backing the software controller in all monitoring domains of all
2525  * monitoring groups.
2526  */
2527 static bool supports_mba_mbps(void)
2528 {
2529 	struct rdt_resource *rmbm = resctrl_arch_get_resource(RDT_RESOURCE_L3);
2530 	struct rdt_resource *r = resctrl_arch_get_resource(RDT_RESOURCE_MBA);
2531 
2532 	return (resctrl_is_mbm_enabled() &&
2533 		r->alloc_capable && is_mba_linear() &&
2534 		r->ctrl_scope == rmbm->mon_scope &&
2535 		!rmbm->mon.mbm_cntr_assignable);
2536 }
2537 
2538 /*
2539  * Enable or disable the MBA software controller
2540  * which helps user specify bandwidth in MBps.
2541  */
2542 static int set_mba_sc(bool mba_sc)
2543 {
2544 	struct rdt_resource *r = resctrl_arch_get_resource(RDT_RESOURCE_MBA);
2545 	u32 num_closid = resctrl_arch_get_num_closid(r);
2546 	struct rdt_ctrl_domain *d;
2547 	unsigned long fflags;
2548 	int i;
2549 
2550 	if (!supports_mba_mbps() || mba_sc == is_mba_sc(r))
2551 		return -EINVAL;
2552 
2553 	r->membw.mba_sc = mba_sc;
2554 
2555 	rdtgroup_default.mba_mbps_event = mba_mbps_default_event;
2556 
2557 	list_for_each_entry(d, &r->ctrl_domains, hdr.list) {
2558 		for (i = 0; i < num_closid; i++)
2559 			d->mbps_val[i] = MBA_MAX_MBPS;
2560 	}
2561 
2562 	fflags = mba_sc ? RFTYPE_CTRL_BASE | RFTYPE_MON_BASE : 0;
2563 	resctrl_file_fflags_init("mba_MBps_event", fflags);
2564 
2565 	return 0;
2566 }
2567 
2568 /*
2569  * We don't allow rdtgroup directories to be created anywhere
2570  * except the root directory. Thus when looking for the rdtgroup
2571  * structure for a kernfs node we are either looking at a directory,
2572  * in which case the rdtgroup structure is pointed at by the "priv"
2573  * field, otherwise we have a file, and need only look to the parent
2574  * to find the rdtgroup.
2575  */
2576 static struct rdtgroup *kernfs_to_rdtgroup(struct kernfs_node *kn)
2577 {
2578 	if (kernfs_type(kn) == KERNFS_DIR) {
2579 		/*
2580 		 * All the resource directories use "kn->priv"
2581 		 * to point to the "struct rdtgroup" for the
2582 		 * resource. "info" and its subdirectories don't
2583 		 * have rdtgroup structures, so return NULL here.
2584 		 */
2585 		if (kn == kn_info ||
2586 		    rcu_access_pointer(kn->__parent) == kn_info)
2587 			return NULL;
2588 		else
2589 			return kn->priv;
2590 	} else {
2591 		return rdt_kn_parent_priv(kn);
2592 	}
2593 }
2594 
2595 static void rdtgroup_kn_get(struct rdtgroup *rdtgrp, struct kernfs_node *kn)
2596 {
2597 	atomic_inc(&rdtgrp->waitcount);
2598 	kernfs_break_active_protection(kn);
2599 }
2600 
2601 static void rdtgroup_kn_put(struct rdtgroup *rdtgrp, struct kernfs_node *kn)
2602 {
2603 	if (atomic_dec_and_test(&rdtgrp->waitcount) &&
2604 	    (rdtgrp->flags & RDT_DELETED)) {
2605 		if (rdtgrp->mode == RDT_MODE_PSEUDO_LOCKSETUP ||
2606 		    rdtgrp->mode == RDT_MODE_PSEUDO_LOCKED)
2607 			rdtgroup_pseudo_lock_remove(rdtgrp);
2608 		kernfs_unbreak_active_protection(kn);
2609 		rdtgroup_remove(rdtgrp);
2610 	} else {
2611 		kernfs_unbreak_active_protection(kn);
2612 	}
2613 }
2614 
2615 struct rdtgroup *rdtgroup_kn_lock_live(struct kernfs_node *kn)
2616 {
2617 	struct rdtgroup *rdtgrp = kernfs_to_rdtgroup(kn);
2618 
2619 	if (!rdtgrp)
2620 		return NULL;
2621 
2622 	rdtgroup_kn_get(rdtgrp, kn);
2623 
2624 	cpus_read_lock();
2625 	mutex_lock(&rdtgroup_mutex);
2626 
2627 	/* Was this group deleted while we waited? */
2628 	if (rdtgrp->flags & RDT_DELETED)
2629 		return NULL;
2630 
2631 	return rdtgrp;
2632 }
2633 
2634 void rdtgroup_kn_unlock(struct kernfs_node *kn)
2635 {
2636 	struct rdtgroup *rdtgrp = kernfs_to_rdtgroup(kn);
2637 
2638 	if (!rdtgrp)
2639 		return;
2640 
2641 	mutex_unlock(&rdtgroup_mutex);
2642 	cpus_read_unlock();
2643 
2644 	rdtgroup_kn_put(rdtgrp, kn);
2645 }
2646 
2647 static int mkdir_mondata_all(struct kernfs_node *parent_kn,
2648 			     struct rdtgroup *prgrp,
2649 			     struct kernfs_node **mon_data_kn);
2650 
2651 static void rdt_disable_ctx(void)
2652 {
2653 	resctrl_arch_set_cdp_enabled(RDT_RESOURCE_L3, false);
2654 	resctrl_arch_set_cdp_enabled(RDT_RESOURCE_L2, false);
2655 	set_mba_sc(false);
2656 
2657 	resctrl_debug = false;
2658 }
2659 
2660 static int rdt_enable_ctx(struct rdt_fs_context *ctx)
2661 {
2662 	int ret = 0;
2663 
2664 	if (ctx->enable_cdpl2) {
2665 		ret = resctrl_arch_set_cdp_enabled(RDT_RESOURCE_L2, true);
2666 		if (ret)
2667 			goto out_done;
2668 	}
2669 
2670 	if (ctx->enable_cdpl3) {
2671 		ret = resctrl_arch_set_cdp_enabled(RDT_RESOURCE_L3, true);
2672 		if (ret)
2673 			goto out_cdpl2;
2674 	}
2675 
2676 	if (ctx->enable_mba_mbps) {
2677 		ret = set_mba_sc(true);
2678 		if (ret)
2679 			goto out_cdpl3;
2680 	}
2681 
2682 	if (ctx->enable_debug)
2683 		resctrl_debug = true;
2684 
2685 	return 0;
2686 
2687 out_cdpl3:
2688 	resctrl_arch_set_cdp_enabled(RDT_RESOURCE_L3, false);
2689 out_cdpl2:
2690 	resctrl_arch_set_cdp_enabled(RDT_RESOURCE_L2, false);
2691 out_done:
2692 	return ret;
2693 }
2694 
2695 static int schemata_list_add(struct rdt_resource *r, enum resctrl_conf_type type)
2696 {
2697 	struct resctrl_schema *s;
2698 	const char *suffix = "";
2699 	int ret, cl;
2700 
2701 	s = kzalloc_obj(*s);
2702 	if (!s)
2703 		return -ENOMEM;
2704 
2705 	s->res = r;
2706 	s->num_closid = resctrl_arch_get_num_closid(r);
2707 	if (resctrl_arch_get_cdp_enabled(r->rid))
2708 		s->num_closid /= 2;
2709 
2710 	s->conf_type = type;
2711 	switch (type) {
2712 	case CDP_CODE:
2713 		suffix = "CODE";
2714 		break;
2715 	case CDP_DATA:
2716 		suffix = "DATA";
2717 		break;
2718 	case CDP_NONE:
2719 		suffix = "";
2720 		break;
2721 	}
2722 
2723 	ret = snprintf(s->name, sizeof(s->name), "%s%s", r->name, suffix);
2724 	if (ret >= sizeof(s->name)) {
2725 		kfree(s);
2726 		return -EINVAL;
2727 	}
2728 
2729 	cl = strlen(s->name);
2730 
2731 	/*
2732 	 * If CDP is supported by this resource, but not enabled,
2733 	 * include the suffix. This ensures the tabular format of the
2734 	 * schemata file does not change between mounts of the filesystem.
2735 	 */
2736 	if (r->cdp_capable && !resctrl_arch_get_cdp_enabled(r->rid))
2737 		cl += 4;
2738 
2739 	if (cl > max_name_width)
2740 		max_name_width = cl;
2741 
2742 	switch (r->schema_fmt) {
2743 	case RESCTRL_SCHEMA_BITMAP:
2744 		s->fmt_str = "%d=%x";
2745 		break;
2746 	case RESCTRL_SCHEMA_RANGE:
2747 		s->fmt_str = "%d=%u";
2748 		break;
2749 	}
2750 
2751 	if (WARN_ON_ONCE(!s->fmt_str)) {
2752 		kfree(s);
2753 		return -EINVAL;
2754 	}
2755 
2756 	INIT_LIST_HEAD(&s->list);
2757 	list_add(&s->list, &resctrl_schema_all);
2758 
2759 	return 0;
2760 }
2761 
2762 static int schemata_list_create(void)
2763 {
2764 	struct rdt_resource *r;
2765 	int ret = 0;
2766 
2767 	for_each_alloc_capable_rdt_resource(r) {
2768 		if (resctrl_arch_get_cdp_enabled(r->rid)) {
2769 			ret = schemata_list_add(r, CDP_CODE);
2770 			if (ret)
2771 				break;
2772 
2773 			ret = schemata_list_add(r, CDP_DATA);
2774 		} else {
2775 			ret = schemata_list_add(r, CDP_NONE);
2776 		}
2777 
2778 		if (ret)
2779 			break;
2780 	}
2781 
2782 	return ret;
2783 }
2784 
2785 static void schemata_list_destroy(void)
2786 {
2787 	struct resctrl_schema *s, *tmp;
2788 
2789 	list_for_each_entry_safe(s, tmp, &resctrl_schema_all, list) {
2790 		list_del(&s->list);
2791 		kfree(s);
2792 	}
2793 }
2794 
2795 static int rdt_get_tree(struct fs_context *fc)
2796 {
2797 	struct rdt_fs_context *ctx = rdt_fc2context(fc);
2798 	unsigned long flags = RFTYPE_CTRL_BASE;
2799 	struct rdt_l3_mon_domain *dom;
2800 	struct rdt_resource *r;
2801 	int ret;
2802 
2803 	DO_ONCE_SLEEPABLE(resctrl_arch_pre_mount);
2804 
2805 	cpus_read_lock();
2806 	mutex_lock(&rdtgroup_mutex);
2807 	/*
2808 	 * resctrl file system can only be mounted once.
2809 	 */
2810 	if (resctrl_mounted) {
2811 		ret = -EBUSY;
2812 		goto out;
2813 	}
2814 
2815 	ret = setup_rmid_lru_list();
2816 	if (ret)
2817 		goto out;
2818 
2819 	ret = rdtgroup_setup_root(ctx);
2820 	if (ret)
2821 		goto out;
2822 
2823 	ret = rdt_enable_ctx(ctx);
2824 	if (ret)
2825 		goto out_root;
2826 
2827 	ret = schemata_list_create();
2828 	if (ret)
2829 		goto out_schemata_free;
2830 
2831 	ret = closid_init();
2832 	if (ret)
2833 		goto out_schemata_free;
2834 
2835 	if (resctrl_arch_mon_capable())
2836 		flags |= RFTYPE_MON;
2837 
2838 	ret = rdtgroup_add_files(rdtgroup_default.kn, flags);
2839 	if (ret)
2840 		goto out_closid_exit;
2841 
2842 	kernfs_activate(rdtgroup_default.kn);
2843 
2844 	ret = rdtgroup_create_info_dir(rdtgroup_default.kn);
2845 	if (ret < 0)
2846 		goto out_closid_exit;
2847 
2848 	if (resctrl_arch_mon_capable()) {
2849 		ret = mongroup_create_dir(rdtgroup_default.kn,
2850 					  &rdtgroup_default, "mon_groups",
2851 					  &kn_mongrp);
2852 		if (ret < 0)
2853 			goto out_info;
2854 
2855 		rdtgroup_assign_cntrs(&rdtgroup_default);
2856 
2857 		ret = mkdir_mondata_all(rdtgroup_default.kn,
2858 					&rdtgroup_default, &kn_mondata);
2859 		if (ret < 0)
2860 			goto out_mongrp;
2861 		rdtgroup_default.mon.mon_data_kn = kn_mondata;
2862 	}
2863 
2864 	ret = rdt_pseudo_lock_init();
2865 	if (ret)
2866 		goto out_mondata;
2867 
2868 	ret = kernfs_get_tree(fc);
2869 	if (ret < 0)
2870 		goto out_psl;
2871 
2872 	if (resctrl_arch_alloc_capable())
2873 		resctrl_arch_enable_alloc();
2874 	if (resctrl_arch_mon_capable())
2875 		resctrl_arch_enable_mon();
2876 
2877 	if (resctrl_arch_alloc_capable() || resctrl_arch_mon_capable())
2878 		resctrl_mounted = true;
2879 
2880 	if (resctrl_is_mbm_enabled()) {
2881 		r = resctrl_arch_get_resource(RDT_RESOURCE_L3);
2882 		list_for_each_entry(dom, &r->mon_domains, hdr.list)
2883 			mbm_setup_overflow_handler(dom, MBM_OVERFLOW_INTERVAL,
2884 						   RESCTRL_PICK_ANY_CPU);
2885 	}
2886 
2887 	goto out;
2888 
2889 out_psl:
2890 	rdt_pseudo_lock_release();
2891 out_mondata:
2892 	if (resctrl_arch_mon_capable())
2893 		kernfs_remove(kn_mondata);
2894 out_mongrp:
2895 	if (resctrl_arch_mon_capable()) {
2896 		rdtgroup_unassign_cntrs(&rdtgroup_default);
2897 		kernfs_remove(kn_mongrp);
2898 	}
2899 out_info:
2900 	kernfs_remove(kn_info);
2901 out_closid_exit:
2902 	closid_exit();
2903 out_schemata_free:
2904 	schemata_list_destroy();
2905 	rdt_disable_ctx();
2906 out_root:
2907 	rdtgroup_destroy_root();
2908 out:
2909 	rdt_last_cmd_clear();
2910 	mutex_unlock(&rdtgroup_mutex);
2911 	cpus_read_unlock();
2912 	return ret;
2913 }
2914 
2915 enum rdt_param {
2916 	Opt_cdp,
2917 	Opt_cdpl2,
2918 	Opt_mba_mbps,
2919 	Opt_debug,
2920 	nr__rdt_params
2921 };
2922 
2923 static const struct fs_parameter_spec rdt_fs_parameters[] = {
2924 	fsparam_flag("cdp",		Opt_cdp),
2925 	fsparam_flag("cdpl2",		Opt_cdpl2),
2926 	fsparam_flag("mba_MBps",	Opt_mba_mbps),
2927 	fsparam_flag("debug",		Opt_debug),
2928 	{}
2929 };
2930 
2931 static int rdt_parse_param(struct fs_context *fc, struct fs_parameter *param)
2932 {
2933 	struct rdt_fs_context *ctx = rdt_fc2context(fc);
2934 	struct fs_parse_result result;
2935 	const char *msg;
2936 	int opt;
2937 
2938 	opt = fs_parse(fc, rdt_fs_parameters, param, &result);
2939 	if (opt < 0)
2940 		return opt;
2941 
2942 	switch (opt) {
2943 	case Opt_cdp:
2944 		ctx->enable_cdpl3 = true;
2945 		return 0;
2946 	case Opt_cdpl2:
2947 		ctx->enable_cdpl2 = true;
2948 		return 0;
2949 	case Opt_mba_mbps:
2950 		msg = "mba_MBps requires MBM (mbm_event mode not supported) and linear scale MBA at L3 scope";
2951 		if (!supports_mba_mbps())
2952 			return invalfc(fc, msg);
2953 		ctx->enable_mba_mbps = true;
2954 		return 0;
2955 	case Opt_debug:
2956 		ctx->enable_debug = true;
2957 		return 0;
2958 	}
2959 
2960 	return -EINVAL;
2961 }
2962 
2963 static void rdt_fs_context_free(struct fs_context *fc)
2964 {
2965 	struct rdt_fs_context *ctx = rdt_fc2context(fc);
2966 
2967 	kernfs_free_fs_context(fc);
2968 	kfree(ctx);
2969 }
2970 
2971 static const struct fs_context_operations rdt_fs_context_ops = {
2972 	.free		= rdt_fs_context_free,
2973 	.parse_param	= rdt_parse_param,
2974 	.get_tree	= rdt_get_tree,
2975 };
2976 
2977 static int rdt_init_fs_context(struct fs_context *fc)
2978 {
2979 	struct rdt_fs_context *ctx;
2980 
2981 	ctx = kzalloc_obj(*ctx);
2982 	if (!ctx)
2983 		return -ENOMEM;
2984 
2985 	ctx->kfc.magic = RDTGROUP_SUPER_MAGIC;
2986 	fc->fs_private = &ctx->kfc;
2987 	fc->ops = &rdt_fs_context_ops;
2988 	put_user_ns(fc->user_ns);
2989 	fc->user_ns = get_user_ns(&init_user_ns);
2990 	fc->global = true;
2991 	return 0;
2992 }
2993 
2994 /*
2995  * Move tasks from one to the other group. If @from is NULL, then all tasks
2996  * in the systems are moved unconditionally (used for teardown).
2997  *
2998  * If @mask is not NULL the cpus on which moved tasks are running are set
2999  * in that mask so the update smp function call is restricted to affected
3000  * cpus.
3001  */
3002 static void rdt_move_group_tasks(struct rdtgroup *from, struct rdtgroup *to,
3003 				 struct cpumask *mask)
3004 {
3005 	struct task_struct *p, *t;
3006 
3007 	read_lock(&tasklist_lock);
3008 	for_each_process_thread(p, t) {
3009 		if (!from || is_closid_match(t, from) ||
3010 		    is_rmid_match(t, from)) {
3011 			resctrl_arch_set_closid_rmid(t, to->closid,
3012 						     to->mon.rmid);
3013 
3014 			/*
3015 			 * Order the closid/rmid stores above before the loads
3016 			 * in task_curr(). This pairs with the full barrier
3017 			 * between the rq->curr update and
3018 			 * resctrl_arch_sched_in() during context switch.
3019 			 */
3020 			smp_mb();
3021 
3022 			/*
3023 			 * If the task is on a CPU, set the CPU in the mask.
3024 			 * The detection is inaccurate as tasks might move or
3025 			 * schedule before the smp function call takes place.
3026 			 * In such a case the function call is pointless, but
3027 			 * there is no other side effect.
3028 			 */
3029 			if (IS_ENABLED(CONFIG_SMP) && mask && task_curr(t))
3030 				cpumask_set_cpu(task_cpu(t), mask);
3031 		}
3032 	}
3033 	read_unlock(&tasklist_lock);
3034 }
3035 
3036 static void free_all_child_rdtgrp(struct rdtgroup *rdtgrp)
3037 {
3038 	struct rdtgroup *sentry, *stmp;
3039 	struct list_head *head;
3040 
3041 	head = &rdtgrp->mon.crdtgrp_list;
3042 	list_for_each_entry_safe(sentry, stmp, head, mon.crdtgrp_list) {
3043 		rdtgroup_unassign_cntrs(sentry);
3044 		free_rmid(sentry->closid, sentry->mon.rmid);
3045 		list_del(&sentry->mon.crdtgrp_list);
3046 
3047 		if (atomic_read(&sentry->waitcount) != 0)
3048 			sentry->flags = RDT_DELETED;
3049 		else
3050 			rdtgroup_remove(sentry);
3051 	}
3052 }
3053 
3054 /*
3055  * Forcibly remove all of subdirectories under root.
3056  */
3057 static void rmdir_all_sub(void)
3058 {
3059 	struct rdtgroup *rdtgrp, *tmp;
3060 
3061 	/* Move all tasks to the default resource group */
3062 	rdt_move_group_tasks(NULL, &rdtgroup_default, NULL);
3063 
3064 	list_for_each_entry_safe(rdtgrp, tmp, &rdt_all_groups, rdtgroup_list) {
3065 		/* Free any child rmids */
3066 		free_all_child_rdtgrp(rdtgrp);
3067 
3068 		/* Remove each rdtgroup other than root */
3069 		if (rdtgrp == &rdtgroup_default)
3070 			continue;
3071 
3072 		if (rdtgrp->mode == RDT_MODE_PSEUDO_LOCKSETUP ||
3073 		    rdtgrp->mode == RDT_MODE_PSEUDO_LOCKED)
3074 			rdtgroup_pseudo_lock_remove(rdtgrp);
3075 
3076 		/*
3077 		 * Give any CPUs back to the default group. We cannot copy
3078 		 * cpu_online_mask because a CPU might have executed the
3079 		 * offline callback already, but is still marked online.
3080 		 */
3081 		cpumask_or(&rdtgroup_default.cpu_mask,
3082 			   &rdtgroup_default.cpu_mask, &rdtgrp->cpu_mask);
3083 
3084 		rdtgroup_unassign_cntrs(rdtgrp);
3085 
3086 		free_rmid(rdtgrp->closid, rdtgrp->mon.rmid);
3087 
3088 		kernfs_remove(rdtgrp->kn);
3089 		list_del(&rdtgrp->rdtgroup_list);
3090 
3091 		if (atomic_read(&rdtgrp->waitcount) != 0)
3092 			rdtgrp->flags = RDT_DELETED;
3093 		else
3094 			rdtgroup_remove(rdtgrp);
3095 	}
3096 	/* Notify online CPUs to update per cpu storage and PQR_ASSOC MSR */
3097 	update_closid_rmid(cpu_online_mask, &rdtgroup_default);
3098 
3099 	kernfs_remove(kn_info);
3100 	kernfs_remove(kn_mongrp);
3101 	kernfs_remove(kn_mondata);
3102 }
3103 
3104 /**
3105  * mon_get_kn_priv() - Get the mon_data priv data for this event.
3106  *
3107  * The same values are used across the mon_data directories of all control and
3108  * monitor groups for the same event in the same domain. Keep a list of
3109  * allocated structures and re-use an existing one with the same values for
3110  * @rid, @domid, etc.
3111  *
3112  * @rid:    The resource id for the event file being created.
3113  * @domid:  The domain id for the event file being created.
3114  * @mevt:   The type of event file being created.
3115  * @do_sum: Whether SNC summing monitors are being created. Only set
3116  *	    when @rid == RDT_RESOURCE_L3.
3117  *
3118  * Return: Pointer to mon_data private data of the event, NULL on failure.
3119  */
3120 static struct mon_data *mon_get_kn_priv(enum resctrl_res_level rid, int domid,
3121 					struct mon_evt *mevt,
3122 					bool do_sum)
3123 {
3124 	struct mon_data *priv;
3125 
3126 	lockdep_assert_held(&rdtgroup_mutex);
3127 
3128 	list_for_each_entry(priv, &mon_data_kn_priv_list, list) {
3129 		if (priv->rid == rid && priv->domid == domid &&
3130 		    priv->sum == do_sum && priv->evt == mevt)
3131 			return priv;
3132 	}
3133 
3134 	priv = kzalloc_obj(*priv);
3135 	if (!priv)
3136 		return NULL;
3137 
3138 	priv->rid = rid;
3139 	priv->domid = domid;
3140 	priv->sum = do_sum;
3141 	priv->evt = mevt;
3142 	list_add_tail(&priv->list, &mon_data_kn_priv_list);
3143 
3144 	return priv;
3145 }
3146 
3147 /**
3148  * mon_put_kn_priv() - Free all allocated mon_data structures.
3149  *
3150  * Called when resctrl file system is unmounted.
3151  */
3152 static void mon_put_kn_priv(void)
3153 {
3154 	struct mon_data *priv, *tmp;
3155 
3156 	lockdep_assert_held(&rdtgroup_mutex);
3157 
3158 	list_for_each_entry_safe(priv, tmp, &mon_data_kn_priv_list, list) {
3159 		list_del(&priv->list);
3160 		kfree(priv);
3161 	}
3162 }
3163 
3164 static void resctrl_fs_teardown(void)
3165 {
3166 	lockdep_assert_held(&rdtgroup_mutex);
3167 
3168 	/* Cleared by rdtgroup_destroy_root() */
3169 	if (!rdtgroup_default.kn)
3170 		return;
3171 
3172 	rmdir_all_sub();
3173 	rdtgroup_unassign_cntrs(&rdtgroup_default);
3174 	mon_put_kn_priv();
3175 	rdt_pseudo_lock_release();
3176 	rdtgroup_default.mode = RDT_MODE_SHAREABLE;
3177 	closid_exit();
3178 	schemata_list_destroy();
3179 	rdtgroup_destroy_root();
3180 }
3181 
3182 static void rdt_kill_sb(struct super_block *sb)
3183 {
3184 	struct rdt_resource *r;
3185 
3186 	cpus_read_lock();
3187 	mutex_lock(&rdtgroup_mutex);
3188 
3189 	rdt_disable_ctx();
3190 
3191 	/* Put everything back to default values. */
3192 	for_each_alloc_capable_rdt_resource(r)
3193 		resctrl_arch_reset_all_ctrls(r);
3194 
3195 	resctrl_fs_teardown();
3196 	if (resctrl_arch_alloc_capable())
3197 		resctrl_arch_disable_alloc();
3198 	if (resctrl_arch_mon_capable())
3199 		resctrl_arch_disable_mon();
3200 	resctrl_mounted = false;
3201 	kernfs_kill_sb(sb);
3202 	mutex_unlock(&rdtgroup_mutex);
3203 	cpus_read_unlock();
3204 }
3205 
3206 static struct file_system_type rdt_fs_type = {
3207 	.name			= "resctrl",
3208 	.init_fs_context	= rdt_init_fs_context,
3209 	.parameters		= rdt_fs_parameters,
3210 	.kill_sb		= rdt_kill_sb,
3211 };
3212 
3213 static int mon_addfile(struct kernfs_node *parent_kn, const char *name,
3214 		       void *priv)
3215 {
3216 	struct kernfs_node *kn;
3217 	int ret = 0;
3218 
3219 	kn = __kernfs_create_file(parent_kn, name, 0444,
3220 				  GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, 0,
3221 				  &kf_mondata_ops, priv, NULL, NULL);
3222 	if (IS_ERR(kn))
3223 		return PTR_ERR(kn);
3224 
3225 	ret = rdtgroup_kn_set_ugid(kn);
3226 	if (ret) {
3227 		kernfs_remove(kn);
3228 		return ret;
3229 	}
3230 
3231 	return ret;
3232 }
3233 
3234 static void mon_rmdir_one_subdir(struct kernfs_node *pkn, char *name, char *subname)
3235 {
3236 	struct kernfs_node *kn;
3237 
3238 	kn = kernfs_find_and_get(pkn, name);
3239 	if (!kn)
3240 		return;
3241 	kernfs_put(kn);
3242 
3243 	if (kn->dir.subdirs <= 1)
3244 		kernfs_remove(kn);
3245 	else
3246 		kernfs_remove_by_name(kn, subname);
3247 }
3248 
3249 /*
3250  * Remove files and directories for one SNC node. If it is the last node
3251  * sharing an L3 cache, then remove the upper level directory containing
3252  * the "sum" files too.
3253  */
3254 static void rmdir_mondata_subdir_allrdtgrp_snc(struct rdt_resource *r,
3255 					       struct rdt_domain_hdr *hdr)
3256 {
3257 	struct rdtgroup *prgrp, *crgrp;
3258 	struct rdt_l3_mon_domain *d;
3259 	char subname[32];
3260 	char name[32];
3261 
3262 	if (!domain_header_is_valid(hdr, RESCTRL_MON_DOMAIN, RDT_RESOURCE_L3))
3263 		return;
3264 
3265 	d = container_of(hdr, struct rdt_l3_mon_domain, hdr);
3266 	sprintf(name, "mon_%s_%02d", r->name, d->ci_id);
3267 	sprintf(subname, "mon_sub_%s_%02d", r->name, hdr->id);
3268 
3269 	list_for_each_entry(prgrp, &rdt_all_groups, rdtgroup_list) {
3270 		mon_rmdir_one_subdir(prgrp->mon.mon_data_kn, name, subname);
3271 
3272 		list_for_each_entry(crgrp, &prgrp->mon.crdtgrp_list, mon.crdtgrp_list)
3273 			mon_rmdir_one_subdir(crgrp->mon.mon_data_kn, name, subname);
3274 	}
3275 }
3276 
3277 /*
3278  * Remove all subdirectories of mon_data of ctrl_mon groups
3279  * and monitor groups for the given domain.
3280  */
3281 static void rmdir_mondata_subdir_allrdtgrp(struct rdt_resource *r,
3282 					   struct rdt_domain_hdr *hdr)
3283 {
3284 	struct rdtgroup *prgrp, *crgrp;
3285 	char name[32];
3286 
3287 	if (r->rid == RDT_RESOURCE_L3 && r->mon_scope == RESCTRL_L3_NODE) {
3288 		rmdir_mondata_subdir_allrdtgrp_snc(r, hdr);
3289 		return;
3290 	}
3291 
3292 	sprintf(name, "mon_%s_%02d", r->name, hdr->id);
3293 	list_for_each_entry(prgrp, &rdt_all_groups, rdtgroup_list) {
3294 		kernfs_remove_by_name(prgrp->mon.mon_data_kn, name);
3295 
3296 		list_for_each_entry(crgrp, &prgrp->mon.crdtgrp_list, mon.crdtgrp_list)
3297 			kernfs_remove_by_name(crgrp->mon.mon_data_kn, name);
3298 	}
3299 }
3300 
3301 /*
3302  * Create a directory for a domain and populate it with monitor files. Create
3303  * summing monitors when @hdr is NULL. No need to initialize summing monitors.
3304  */
3305 static struct kernfs_node *_mkdir_mondata_subdir(struct kernfs_node *parent_kn, char *name,
3306 						 struct rdt_domain_hdr *hdr,
3307 						 struct rdt_resource *r,
3308 						 struct rdtgroup *prgrp, int domid)
3309 {
3310 	struct rmid_read rr = {0};
3311 	struct kernfs_node *kn;
3312 	struct mon_data *priv;
3313 	struct mon_evt *mevt;
3314 	int ret;
3315 
3316 	kn = kernfs_create_dir(parent_kn, name, parent_kn->mode, prgrp);
3317 	if (IS_ERR(kn))
3318 		return kn;
3319 
3320 	ret = rdtgroup_kn_set_ugid(kn);
3321 	if (ret)
3322 		goto out_destroy;
3323 
3324 	for_each_mon_event(mevt) {
3325 		if (mevt->rid != r->rid || !mevt->enabled)
3326 			continue;
3327 		priv = mon_get_kn_priv(r->rid, domid, mevt, !hdr);
3328 		if (WARN_ON_ONCE(!priv)) {
3329 			ret = -EINVAL;
3330 			goto out_destroy;
3331 		}
3332 
3333 		ret = mon_addfile(kn, mevt->name, priv);
3334 		if (ret)
3335 			goto out_destroy;
3336 
3337 		if (hdr && resctrl_is_mbm_event(mevt->evtid))
3338 			mon_event_read(&rr, r, hdr, prgrp, &hdr->cpu_mask, mevt, true);
3339 	}
3340 
3341 	return kn;
3342 out_destroy:
3343 	kernfs_remove(kn);
3344 	return ERR_PTR(ret);
3345 }
3346 
3347 static int mkdir_mondata_subdir_snc(struct kernfs_node *parent_kn,
3348 				    struct rdt_domain_hdr *hdr,
3349 				    struct rdt_resource *r, struct rdtgroup *prgrp)
3350 {
3351 	struct kernfs_node *ckn, *kn;
3352 	struct rdt_l3_mon_domain *d;
3353 	char name[32];
3354 
3355 	if (!domain_header_is_valid(hdr, RESCTRL_MON_DOMAIN, RDT_RESOURCE_L3))
3356 		return -EINVAL;
3357 
3358 	d = container_of(hdr, struct rdt_l3_mon_domain, hdr);
3359 	sprintf(name, "mon_%s_%02d", r->name, d->ci_id);
3360 	kn = kernfs_find_and_get(parent_kn, name);
3361 	if (kn) {
3362 		/*
3363 		 * rdtgroup_mutex will prevent this directory from being
3364 		 * removed. No need to keep this hold.
3365 		 */
3366 		kernfs_put(kn);
3367 	} else {
3368 		kn = _mkdir_mondata_subdir(parent_kn, name, NULL, r, prgrp, d->ci_id);
3369 		if (IS_ERR(kn))
3370 			return PTR_ERR(kn);
3371 	}
3372 
3373 	sprintf(name, "mon_sub_%s_%02d", r->name, hdr->id);
3374 	ckn = _mkdir_mondata_subdir(kn, name, hdr, r, prgrp, hdr->id);
3375 	if (IS_ERR(ckn)) {
3376 		kernfs_remove(kn);
3377 		return PTR_ERR(ckn);
3378 	}
3379 
3380 	kernfs_activate(kn);
3381 	return 0;
3382 }
3383 
3384 static int mkdir_mondata_subdir(struct kernfs_node *parent_kn,
3385 				struct rdt_domain_hdr *hdr,
3386 				struct rdt_resource *r, struct rdtgroup *prgrp)
3387 {
3388 	struct kernfs_node *kn;
3389 	char name[32];
3390 
3391 	lockdep_assert_held(&rdtgroup_mutex);
3392 
3393 	if (r->rid == RDT_RESOURCE_L3 && r->mon_scope == RESCTRL_L3_NODE)
3394 		return mkdir_mondata_subdir_snc(parent_kn, hdr, r, prgrp);
3395 
3396 	sprintf(name, "mon_%s_%02d", r->name, hdr->id);
3397 	kn = _mkdir_mondata_subdir(parent_kn, name, hdr, r, prgrp, hdr->id);
3398 	if (IS_ERR(kn))
3399 		return PTR_ERR(kn);
3400 
3401 	kernfs_activate(kn);
3402 	return 0;
3403 }
3404 
3405 /*
3406  * Add all subdirectories of mon_data for "ctrl_mon" groups
3407  * and "monitor" groups with given domain id.
3408  */
3409 static void mkdir_mondata_subdir_allrdtgrp(struct rdt_resource *r,
3410 					   struct rdt_domain_hdr *hdr)
3411 {
3412 	struct kernfs_node *parent_kn;
3413 	struct rdtgroup *prgrp, *crgrp;
3414 	struct list_head *head;
3415 
3416 	list_for_each_entry(prgrp, &rdt_all_groups, rdtgroup_list) {
3417 		parent_kn = prgrp->mon.mon_data_kn;
3418 		mkdir_mondata_subdir(parent_kn, hdr, r, prgrp);
3419 
3420 		head = &prgrp->mon.crdtgrp_list;
3421 		list_for_each_entry(crgrp, head, mon.crdtgrp_list) {
3422 			parent_kn = crgrp->mon.mon_data_kn;
3423 			mkdir_mondata_subdir(parent_kn, hdr, r, crgrp);
3424 		}
3425 	}
3426 }
3427 
3428 static int mkdir_mondata_subdir_alldom(struct kernfs_node *parent_kn,
3429 				       struct rdt_resource *r,
3430 				       struct rdtgroup *prgrp)
3431 {
3432 	struct rdt_domain_hdr *hdr;
3433 	int ret;
3434 
3435 	/* Walking r->domains, ensure it can't race with cpuhp */
3436 	lockdep_assert_cpus_held();
3437 
3438 	list_for_each_entry(hdr, &r->mon_domains, list) {
3439 		ret = mkdir_mondata_subdir(parent_kn, hdr, r, prgrp);
3440 		if (ret)
3441 			return ret;
3442 	}
3443 
3444 	return 0;
3445 }
3446 
3447 /*
3448  * This creates a directory mon_data which contains the monitored data.
3449  *
3450  * mon_data has one directory for each domain which are named
3451  * in the format mon_<domain_name>_<domain_id>. For ex: A mon_data
3452  * with L3 domain looks as below:
3453  * ./mon_data:
3454  * mon_L3_00
3455  * mon_L3_01
3456  * mon_L3_02
3457  * ...
3458  *
3459  * Each domain directory has one file per event:
3460  * ./mon_L3_00/:
3461  * llc_occupancy
3462  *
3463  */
3464 static int mkdir_mondata_all(struct kernfs_node *parent_kn,
3465 			     struct rdtgroup *prgrp,
3466 			     struct kernfs_node **dest_kn)
3467 {
3468 	struct rdt_resource *r;
3469 	struct kernfs_node *kn;
3470 	int ret;
3471 
3472 	/*
3473 	 * Create the mon_data directory first.
3474 	 */
3475 	ret = mongroup_create_dir(parent_kn, prgrp, "mon_data", &kn);
3476 	if (ret)
3477 		return ret;
3478 
3479 	if (dest_kn)
3480 		*dest_kn = kn;
3481 
3482 	/*
3483 	 * Create the subdirectories for each domain. Note that all events
3484 	 * in a domain like L3 are grouped into a resource whose domain is L3
3485 	 */
3486 	for_each_mon_capable_rdt_resource(r) {
3487 		ret = mkdir_mondata_subdir_alldom(kn, r, prgrp);
3488 		if (ret)
3489 			goto out_destroy;
3490 	}
3491 
3492 	return 0;
3493 
3494 out_destroy:
3495 	kernfs_remove(kn);
3496 	return ret;
3497 }
3498 
3499 /**
3500  * cbm_ensure_valid - Enforce validity on provided CBM
3501  * @_val:	Candidate CBM
3502  * @r:		RDT resource to which the CBM belongs
3503  *
3504  * The provided CBM represents all cache portions available for use. This
3505  * may be represented by a bitmap that does not consist of contiguous ones
3506  * and thus be an invalid CBM.
3507  * Here the provided CBM is forced to be a valid CBM by only considering
3508  * the first set of contiguous bits as valid and clearing all bits.
3509  * The intention here is to provide a valid default CBM with which a new
3510  * resource group is initialized. The user can follow this with a
3511  * modification to the CBM if the default does not satisfy the
3512  * requirements.
3513  *
3514  * Return: A CBM that is valid for resource @r.
3515  */
3516 static u32 cbm_ensure_valid(u32 _val, struct rdt_resource *r)
3517 {
3518 	unsigned int cbm_len = r->cache.cbm_len;
3519 	unsigned long first_bit, zero_bit;
3520 	unsigned long val;
3521 
3522 	if (!_val || r->cache.arch_has_sparse_bitmasks)
3523 		return _val;
3524 
3525 	val = _val;
3526 	first_bit = find_first_bit(&val, cbm_len);
3527 	zero_bit = find_next_zero_bit(&val, cbm_len, first_bit);
3528 
3529 	/* Clear any remaining bits to ensure contiguous region */
3530 	bitmap_clear(&val, zero_bit, cbm_len - zero_bit);
3531 	return (u32)val;
3532 }
3533 
3534 /*
3535  * Initialize cache resources per RDT domain
3536  *
3537  * Set the RDT domain up to start off with all usable allocations. That is,
3538  * all shareable and unused bits. All-zero CBM is invalid.
3539  */
3540 static int __init_one_rdt_domain(struct rdt_ctrl_domain *d, struct resctrl_schema *s,
3541 				 u32 closid)
3542 {
3543 	enum resctrl_conf_type peer_type = resctrl_peer_type(s->conf_type);
3544 	enum resctrl_conf_type t = s->conf_type;
3545 	struct resctrl_staged_config *cfg;
3546 	struct rdt_resource *r = s->res;
3547 	u32 used_b = 0, unused_b = 0;
3548 	unsigned long tmp_cbm;
3549 	enum rdtgrp_mode mode;
3550 	u32 peer_ctl, ctrl_val;
3551 	int i;
3552 
3553 	cfg = &d->staged_config[t];
3554 	cfg->have_new_ctrl = false;
3555 	cfg->new_ctrl = r->cache.shareable_bits;
3556 	used_b = r->cache.shareable_bits;
3557 	for (i = 0; i < closids_supported(); i++) {
3558 		if (closid_allocated(i) && i != closid) {
3559 			mode = rdtgroup_mode_by_closid(i);
3560 			if (mode == RDT_MODE_PSEUDO_LOCKSETUP)
3561 				/*
3562 				 * ctrl values for locksetup aren't relevant
3563 				 * until the schemata is written, and the mode
3564 				 * becomes RDT_MODE_PSEUDO_LOCKED.
3565 				 */
3566 				continue;
3567 			/*
3568 			 * If CDP is active include peer domain's
3569 			 * usage to ensure there is no overlap
3570 			 * with an exclusive group.
3571 			 */
3572 			if (resctrl_arch_get_cdp_enabled(r->rid))
3573 				peer_ctl = resctrl_arch_get_config(r, d, i,
3574 								   peer_type);
3575 			else
3576 				peer_ctl = 0;
3577 			ctrl_val = resctrl_arch_get_config(r, d, i,
3578 							   s->conf_type);
3579 			used_b |= ctrl_val | peer_ctl;
3580 			if (mode == RDT_MODE_SHAREABLE)
3581 				cfg->new_ctrl |= ctrl_val | peer_ctl;
3582 		}
3583 	}
3584 	if (d->plr && d->plr->cbm > 0)
3585 		used_b |= d->plr->cbm;
3586 	unused_b = used_b ^ (BIT_MASK(r->cache.cbm_len) - 1);
3587 	unused_b &= BIT_MASK(r->cache.cbm_len) - 1;
3588 	cfg->new_ctrl |= unused_b;
3589 	/*
3590 	 * Force the initial CBM to be valid, user can
3591 	 * modify the CBM based on system availability.
3592 	 */
3593 	cfg->new_ctrl = cbm_ensure_valid(cfg->new_ctrl, r);
3594 	/*
3595 	 * Assign the u32 CBM to an unsigned long to ensure that
3596 	 * bitmap_weight() does not access out-of-bound memory.
3597 	 */
3598 	tmp_cbm = cfg->new_ctrl;
3599 	if (bitmap_weight(&tmp_cbm, r->cache.cbm_len) < r->cache.min_cbm_bits) {
3600 		rdt_last_cmd_printf("No space on %s:%d\n", s->name, d->hdr.id);
3601 		return -ENOSPC;
3602 	}
3603 	cfg->have_new_ctrl = true;
3604 
3605 	return 0;
3606 }
3607 
3608 /*
3609  * Initialize cache resources with default values.
3610  *
3611  * A new RDT group is being created on an allocation capable (CAT)
3612  * supporting system. Set this group up to start off with all usable
3613  * allocations.
3614  *
3615  * If there are no more shareable bits available on any domain then
3616  * the entire allocation will fail.
3617  */
3618 int rdtgroup_init_cat(struct resctrl_schema *s, u32 closid)
3619 {
3620 	struct rdt_ctrl_domain *d;
3621 	int ret;
3622 
3623 	list_for_each_entry(d, &s->res->ctrl_domains, hdr.list) {
3624 		ret = __init_one_rdt_domain(d, s, closid);
3625 		if (ret < 0)
3626 			return ret;
3627 	}
3628 
3629 	return 0;
3630 }
3631 
3632 /* Initialize MBA resource with default values. */
3633 static void rdtgroup_init_mba(struct rdt_resource *r, u32 closid)
3634 {
3635 	struct resctrl_staged_config *cfg;
3636 	struct rdt_ctrl_domain *d;
3637 
3638 	list_for_each_entry(d, &r->ctrl_domains, hdr.list) {
3639 		if (is_mba_sc(r)) {
3640 			d->mbps_val[closid] = MBA_MAX_MBPS;
3641 			continue;
3642 		}
3643 
3644 		cfg = &d->staged_config[CDP_NONE];
3645 		cfg->new_ctrl = resctrl_get_default_ctrl(r);
3646 		cfg->have_new_ctrl = true;
3647 	}
3648 }
3649 
3650 /* Initialize the RDT group's allocations. */
3651 static int rdtgroup_init_alloc(struct rdtgroup *rdtgrp)
3652 {
3653 	struct resctrl_schema *s;
3654 	struct rdt_resource *r;
3655 	int ret = 0;
3656 
3657 	rdt_staged_configs_clear();
3658 
3659 	list_for_each_entry(s, &resctrl_schema_all, list) {
3660 		r = s->res;
3661 		if (r->rid == RDT_RESOURCE_MBA ||
3662 		    r->rid == RDT_RESOURCE_SMBA) {
3663 			rdtgroup_init_mba(r, rdtgrp->closid);
3664 			if (is_mba_sc(r))
3665 				continue;
3666 		} else {
3667 			ret = rdtgroup_init_cat(s, rdtgrp->closid);
3668 			if (ret < 0)
3669 				goto out;
3670 		}
3671 
3672 		ret = resctrl_arch_update_domains(r, rdtgrp->closid);
3673 		if (ret < 0) {
3674 			rdt_last_cmd_puts("Failed to initialize allocations\n");
3675 			goto out;
3676 		}
3677 	}
3678 
3679 	rdtgrp->mode = RDT_MODE_SHAREABLE;
3680 
3681 out:
3682 	rdt_staged_configs_clear();
3683 	return ret;
3684 }
3685 
3686 static int mkdir_rdt_prepare_rmid_alloc(struct rdtgroup *rdtgrp)
3687 {
3688 	int ret;
3689 
3690 	if (!resctrl_arch_mon_capable())
3691 		return 0;
3692 
3693 	ret = alloc_rmid(rdtgrp->closid);
3694 	if (ret < 0) {
3695 		rdt_last_cmd_puts("Out of RMIDs\n");
3696 		return ret;
3697 	}
3698 	rdtgrp->mon.rmid = ret;
3699 
3700 	rdtgroup_assign_cntrs(rdtgrp);
3701 
3702 	ret = mkdir_mondata_all(rdtgrp->kn, rdtgrp, &rdtgrp->mon.mon_data_kn);
3703 	if (ret) {
3704 		rdt_last_cmd_puts("kernfs subdir error\n");
3705 		rdtgroup_unassign_cntrs(rdtgrp);
3706 		free_rmid(rdtgrp->closid, rdtgrp->mon.rmid);
3707 		return ret;
3708 	}
3709 
3710 	return 0;
3711 }
3712 
3713 static void mkdir_rdt_prepare_rmid_free(struct rdtgroup *rgrp)
3714 {
3715 	if (resctrl_arch_mon_capable()) {
3716 		rdtgroup_unassign_cntrs(rgrp);
3717 		free_rmid(rgrp->closid, rgrp->mon.rmid);
3718 	}
3719 }
3720 
3721 /*
3722  * We allow creating mon groups only with in a directory called "mon_groups"
3723  * which is present in every ctrl_mon group. Check if this is a valid
3724  * "mon_groups" directory.
3725  *
3726  * 1. The directory should be named "mon_groups".
3727  * 2. The mon group itself should "not" be named "mon_groups".
3728  *   This makes sure "mon_groups" directory always has a ctrl_mon group
3729  *   as parent.
3730  */
3731 static bool is_mon_groups(struct kernfs_node *kn, const char *name)
3732 {
3733 	return (!strcmp(rdt_kn_name(kn), "mon_groups") &&
3734 		strcmp(name, "mon_groups"));
3735 }
3736 
3737 static int mkdir_rdt_prepare(struct kernfs_node *parent_kn,
3738 			     const char *name, umode_t mode,
3739 			     enum rdt_group_type rtype, struct rdtgroup **r)
3740 {
3741 	struct rdtgroup *prdtgrp, *rdtgrp;
3742 	unsigned long files = 0;
3743 	struct kernfs_node *kn;
3744 	int ret;
3745 
3746 	prdtgrp = rdtgroup_kn_lock_live(parent_kn);
3747 	if (!prdtgrp) {
3748 		ret = -ENODEV;
3749 		goto out_unlock;
3750 	}
3751 
3752 	rdt_last_cmd_clear();
3753 
3754 	/*
3755 	 * Check that the parent directory for a monitor group is a "mon_groups"
3756 	 * directory.
3757 	 */
3758 	if (rtype == RDTMON_GROUP && !is_mon_groups(parent_kn, name)) {
3759 		ret = -EPERM;
3760 		goto out_unlock;
3761 	}
3762 
3763 	if (rtype == RDTMON_GROUP &&
3764 	    (prdtgrp->mode == RDT_MODE_PSEUDO_LOCKSETUP ||
3765 	     prdtgrp->mode == RDT_MODE_PSEUDO_LOCKED)) {
3766 		ret = -EINVAL;
3767 		rdt_last_cmd_puts("Pseudo-locking in progress\n");
3768 		goto out_unlock;
3769 	}
3770 
3771 	/* allocate the rdtgroup. */
3772 	rdtgrp = kzalloc_obj(*rdtgrp);
3773 	if (!rdtgrp) {
3774 		ret = -ENOSPC;
3775 		rdt_last_cmd_puts("Kernel out of memory\n");
3776 		goto out_unlock;
3777 	}
3778 	*r = rdtgrp;
3779 	rdtgrp->mon.parent = prdtgrp;
3780 	rdtgrp->type = rtype;
3781 	INIT_LIST_HEAD(&rdtgrp->mon.crdtgrp_list);
3782 
3783 	/* kernfs creates the directory for rdtgrp */
3784 	kn = kernfs_create_dir(parent_kn, name, mode, rdtgrp);
3785 	if (IS_ERR(kn)) {
3786 		ret = PTR_ERR(kn);
3787 		rdt_last_cmd_puts("kernfs create error\n");
3788 		goto out_free_rgrp;
3789 	}
3790 	rdtgrp->kn = kn;
3791 
3792 	/*
3793 	 * kernfs_remove() will drop the reference count on "kn" which
3794 	 * will free it. But we still need it to stick around for the
3795 	 * rdtgroup_kn_unlock(kn) call. Take one extra reference here,
3796 	 * which will be dropped by kernfs_put() in rdtgroup_remove().
3797 	 */
3798 	kernfs_get(kn);
3799 
3800 	ret = rdtgroup_kn_set_ugid(kn);
3801 	if (ret) {
3802 		rdt_last_cmd_puts("kernfs perm error\n");
3803 		goto out_destroy;
3804 	}
3805 
3806 	if (rtype == RDTCTRL_GROUP) {
3807 		files = RFTYPE_BASE | RFTYPE_CTRL;
3808 		if (resctrl_arch_mon_capable())
3809 			files |= RFTYPE_MON;
3810 	} else {
3811 		files = RFTYPE_BASE | RFTYPE_MON;
3812 	}
3813 
3814 	ret = rdtgroup_add_files(kn, files);
3815 	if (ret) {
3816 		rdt_last_cmd_puts("kernfs fill error\n");
3817 		goto out_destroy;
3818 	}
3819 
3820 	/*
3821 	 * The caller unlocks the parent_kn upon success.
3822 	 */
3823 	return 0;
3824 
3825 out_destroy:
3826 	kernfs_put(rdtgrp->kn);
3827 	kernfs_remove(rdtgrp->kn);
3828 out_free_rgrp:
3829 	kfree(rdtgrp);
3830 out_unlock:
3831 	rdtgroup_kn_unlock(parent_kn);
3832 	return ret;
3833 }
3834 
3835 static void mkdir_rdt_prepare_clean(struct rdtgroup *rgrp)
3836 {
3837 	kernfs_remove(rgrp->kn);
3838 	rdtgroup_remove(rgrp);
3839 }
3840 
3841 /*
3842  * Create a monitor group under "mon_groups" directory of a control
3843  * and monitor group(ctrl_mon). This is a resource group
3844  * to monitor a subset of tasks and cpus in its parent ctrl_mon group.
3845  */
3846 static int rdtgroup_mkdir_mon(struct kernfs_node *parent_kn,
3847 			      const char *name, umode_t mode)
3848 {
3849 	struct rdtgroup *rdtgrp, *prgrp;
3850 	int ret;
3851 
3852 	ret = mkdir_rdt_prepare(parent_kn, name, mode, RDTMON_GROUP, &rdtgrp);
3853 	if (ret)
3854 		return ret;
3855 
3856 	prgrp = rdtgrp->mon.parent;
3857 	rdtgrp->closid = prgrp->closid;
3858 
3859 	ret = mkdir_rdt_prepare_rmid_alloc(rdtgrp);
3860 	if (ret) {
3861 		mkdir_rdt_prepare_clean(rdtgrp);
3862 		goto out_unlock;
3863 	}
3864 
3865 	kernfs_activate(rdtgrp->kn);
3866 
3867 	/*
3868 	 * Add the rdtgrp to the list of rdtgrps the parent
3869 	 * ctrl_mon group has to track.
3870 	 */
3871 	list_add_tail(&rdtgrp->mon.crdtgrp_list, &prgrp->mon.crdtgrp_list);
3872 
3873 out_unlock:
3874 	rdtgroup_kn_unlock(parent_kn);
3875 	return ret;
3876 }
3877 
3878 /*
3879  * These are rdtgroups created under the root directory. Can be used
3880  * to allocate and monitor resources.
3881  */
3882 static int rdtgroup_mkdir_ctrl_mon(struct kernfs_node *parent_kn,
3883 				   const char *name, umode_t mode)
3884 {
3885 	struct rdtgroup *rdtgrp;
3886 	struct kernfs_node *kn;
3887 	u32 closid;
3888 	int ret;
3889 
3890 	ret = mkdir_rdt_prepare(parent_kn, name, mode, RDTCTRL_GROUP, &rdtgrp);
3891 	if (ret)
3892 		return ret;
3893 
3894 	kn = rdtgrp->kn;
3895 	ret = closid_alloc();
3896 	if (ret < 0) {
3897 		rdt_last_cmd_puts("Out of CLOSIDs\n");
3898 		goto out_common_fail;
3899 	}
3900 	closid = ret;
3901 	ret = 0;
3902 
3903 	rdtgrp->closid = closid;
3904 
3905 	ret = mkdir_rdt_prepare_rmid_alloc(rdtgrp);
3906 	if (ret)
3907 		goto out_closid_free;
3908 
3909 	kernfs_activate(rdtgrp->kn);
3910 
3911 	ret = rdtgroup_init_alloc(rdtgrp);
3912 	if (ret < 0)
3913 		goto out_rmid_free;
3914 
3915 	list_add(&rdtgrp->rdtgroup_list, &rdt_all_groups);
3916 
3917 	if (resctrl_arch_mon_capable()) {
3918 		/*
3919 		 * Create an empty mon_groups directory to hold the subset
3920 		 * of tasks and cpus to monitor.
3921 		 */
3922 		ret = mongroup_create_dir(kn, rdtgrp, "mon_groups", NULL);
3923 		if (ret) {
3924 			rdt_last_cmd_puts("kernfs subdir error\n");
3925 			goto out_del_list;
3926 		}
3927 		if (is_mba_sc(NULL))
3928 			rdtgrp->mba_mbps_event = mba_mbps_default_event;
3929 	}
3930 
3931 	goto out_unlock;
3932 
3933 out_del_list:
3934 	list_del(&rdtgrp->rdtgroup_list);
3935 out_rmid_free:
3936 	mkdir_rdt_prepare_rmid_free(rdtgrp);
3937 out_closid_free:
3938 	closid_free(closid);
3939 out_common_fail:
3940 	mkdir_rdt_prepare_clean(rdtgrp);
3941 out_unlock:
3942 	rdtgroup_kn_unlock(parent_kn);
3943 	return ret;
3944 }
3945 
3946 static int rdtgroup_mkdir(struct kernfs_node *parent_kn, const char *name,
3947 			  umode_t mode)
3948 {
3949 	/* Do not accept '\n' to avoid unparsable situation. */
3950 	if (strchr(name, '\n'))
3951 		return -EINVAL;
3952 
3953 	/*
3954 	 * If the parent directory is the root directory and RDT
3955 	 * allocation is supported, add a control and monitoring
3956 	 * subdirectory
3957 	 */
3958 	if (resctrl_arch_alloc_capable() && parent_kn == rdtgroup_default.kn)
3959 		return rdtgroup_mkdir_ctrl_mon(parent_kn, name, mode);
3960 
3961 	/* Else, attempt to add a monitoring subdirectory. */
3962 	if (resctrl_arch_mon_capable())
3963 		return rdtgroup_mkdir_mon(parent_kn, name, mode);
3964 
3965 	return -EPERM;
3966 }
3967 
3968 static int rdtgroup_rmdir_mon(struct rdtgroup *rdtgrp, cpumask_var_t tmpmask)
3969 {
3970 	struct rdtgroup *prdtgrp = rdtgrp->mon.parent;
3971 	u32 closid, rmid;
3972 	int cpu;
3973 
3974 	/* Give any tasks back to the parent group */
3975 	rdt_move_group_tasks(rdtgrp, prdtgrp, tmpmask);
3976 
3977 	/*
3978 	 * Update per cpu closid/rmid of the moved CPUs first.
3979 	 * Note: the closid will not change, but the arch code still needs it.
3980 	 */
3981 	closid = prdtgrp->closid;
3982 	rmid = prdtgrp->mon.rmid;
3983 	for_each_cpu(cpu, &rdtgrp->cpu_mask)
3984 		resctrl_arch_set_cpu_default_closid_rmid(cpu, closid, rmid);
3985 
3986 	/*
3987 	 * Update the MSR on moved CPUs and CPUs which have moved
3988 	 * task running on them.
3989 	 */
3990 	cpumask_or(tmpmask, tmpmask, &rdtgrp->cpu_mask);
3991 	update_closid_rmid(tmpmask, NULL);
3992 
3993 	rdtgrp->flags = RDT_DELETED;
3994 
3995 	rdtgroup_unassign_cntrs(rdtgrp);
3996 
3997 	free_rmid(rdtgrp->closid, rdtgrp->mon.rmid);
3998 
3999 	/*
4000 	 * Remove the rdtgrp from the parent ctrl_mon group's list
4001 	 */
4002 	WARN_ON(list_empty(&prdtgrp->mon.crdtgrp_list));
4003 	list_del(&rdtgrp->mon.crdtgrp_list);
4004 
4005 	kernfs_remove(rdtgrp->kn);
4006 
4007 	return 0;
4008 }
4009 
4010 static int rdtgroup_ctrl_remove(struct rdtgroup *rdtgrp)
4011 {
4012 	rdtgrp->flags = RDT_DELETED;
4013 	list_del(&rdtgrp->rdtgroup_list);
4014 
4015 	kernfs_remove(rdtgrp->kn);
4016 	return 0;
4017 }
4018 
4019 static int rdtgroup_rmdir_ctrl(struct rdtgroup *rdtgrp, cpumask_var_t tmpmask)
4020 {
4021 	u32 closid, rmid;
4022 	int cpu;
4023 
4024 	/* Give any tasks back to the default group */
4025 	rdt_move_group_tasks(rdtgrp, &rdtgroup_default, tmpmask);
4026 
4027 	/* Give any CPUs back to the default group */
4028 	cpumask_or(&rdtgroup_default.cpu_mask,
4029 		   &rdtgroup_default.cpu_mask, &rdtgrp->cpu_mask);
4030 
4031 	/* Update per cpu closid and rmid of the moved CPUs first */
4032 	closid = rdtgroup_default.closid;
4033 	rmid = rdtgroup_default.mon.rmid;
4034 	for_each_cpu(cpu, &rdtgrp->cpu_mask)
4035 		resctrl_arch_set_cpu_default_closid_rmid(cpu, closid, rmid);
4036 
4037 	/*
4038 	 * Update the MSR on moved CPUs and CPUs which have moved
4039 	 * task running on them.
4040 	 */
4041 	cpumask_or(tmpmask, tmpmask, &rdtgrp->cpu_mask);
4042 	update_closid_rmid(tmpmask, NULL);
4043 
4044 	rdtgroup_unassign_cntrs(rdtgrp);
4045 
4046 	free_rmid(rdtgrp->closid, rdtgrp->mon.rmid);
4047 	closid_free(rdtgrp->closid);
4048 
4049 	rdtgroup_ctrl_remove(rdtgrp);
4050 
4051 	/*
4052 	 * Free all the child monitor group rmids.
4053 	 */
4054 	free_all_child_rdtgrp(rdtgrp);
4055 
4056 	return 0;
4057 }
4058 
4059 static struct kernfs_node *rdt_kn_parent(struct kernfs_node *kn)
4060 {
4061 	/*
4062 	 * Valid within the RCU section it was obtained or while rdtgroup_mutex
4063 	 * is held.
4064 	 */
4065 	return rcu_dereference_check(kn->__parent, lockdep_is_held(&rdtgroup_mutex));
4066 }
4067 
4068 static int rdtgroup_rmdir(struct kernfs_node *kn)
4069 {
4070 	struct kernfs_node *parent_kn;
4071 	struct rdtgroup *rdtgrp;
4072 	cpumask_var_t tmpmask;
4073 	int ret = 0;
4074 
4075 	if (!zalloc_cpumask_var(&tmpmask, GFP_KERNEL))
4076 		return -ENOMEM;
4077 
4078 	rdtgrp = rdtgroup_kn_lock_live(kn);
4079 	if (!rdtgrp) {
4080 		ret = -EPERM;
4081 		goto out;
4082 	}
4083 	parent_kn = rdt_kn_parent(kn);
4084 
4085 	/*
4086 	 * If the rdtgroup is a ctrl_mon group and parent directory
4087 	 * is the root directory, remove the ctrl_mon group.
4088 	 *
4089 	 * If the rdtgroup is a mon group and parent directory
4090 	 * is a valid "mon_groups" directory, remove the mon group.
4091 	 */
4092 	if (rdtgrp->type == RDTCTRL_GROUP && parent_kn == rdtgroup_default.kn &&
4093 	    rdtgrp != &rdtgroup_default) {
4094 		if (rdtgrp->mode == RDT_MODE_PSEUDO_LOCKSETUP ||
4095 		    rdtgrp->mode == RDT_MODE_PSEUDO_LOCKED) {
4096 			ret = rdtgroup_ctrl_remove(rdtgrp);
4097 		} else {
4098 			ret = rdtgroup_rmdir_ctrl(rdtgrp, tmpmask);
4099 		}
4100 	} else if (rdtgrp->type == RDTMON_GROUP &&
4101 		 is_mon_groups(parent_kn, rdt_kn_name(kn))) {
4102 		ret = rdtgroup_rmdir_mon(rdtgrp, tmpmask);
4103 	} else {
4104 		ret = -EPERM;
4105 	}
4106 
4107 out:
4108 	rdtgroup_kn_unlock(kn);
4109 	free_cpumask_var(tmpmask);
4110 	return ret;
4111 }
4112 
4113 /**
4114  * mongrp_reparent() - replace parent CTRL_MON group of a MON group
4115  * @rdtgrp:		the MON group whose parent should be replaced
4116  * @new_prdtgrp:	replacement parent CTRL_MON group for @rdtgrp
4117  * @cpus:		cpumask provided by the caller for use during this call
4118  *
4119  * Replaces the parent CTRL_MON group for a MON group, resulting in all member
4120  * tasks' CLOSID immediately changing to that of the new parent group.
4121  * Monitoring data for the group is unaffected by this operation.
4122  */
4123 static void mongrp_reparent(struct rdtgroup *rdtgrp,
4124 			    struct rdtgroup *new_prdtgrp,
4125 			    cpumask_var_t cpus)
4126 {
4127 	struct rdtgroup *prdtgrp = rdtgrp->mon.parent;
4128 
4129 	WARN_ON(rdtgrp->type != RDTMON_GROUP);
4130 	WARN_ON(new_prdtgrp->type != RDTCTRL_GROUP);
4131 
4132 	/* Nothing to do when simply renaming a MON group. */
4133 	if (prdtgrp == new_prdtgrp)
4134 		return;
4135 
4136 	WARN_ON(list_empty(&prdtgrp->mon.crdtgrp_list));
4137 	list_move_tail(&rdtgrp->mon.crdtgrp_list,
4138 		       &new_prdtgrp->mon.crdtgrp_list);
4139 
4140 	rdtgrp->mon.parent = new_prdtgrp;
4141 	rdtgrp->closid = new_prdtgrp->closid;
4142 
4143 	/* Propagate updated closid to all tasks in this group. */
4144 	rdt_move_group_tasks(rdtgrp, rdtgrp, cpus);
4145 
4146 	update_closid_rmid(cpus, NULL);
4147 }
4148 
4149 static int rdtgroup_rename(struct kernfs_node *kn,
4150 			   struct kernfs_node *new_parent, const char *new_name)
4151 {
4152 	struct kernfs_node *kn_parent;
4153 	struct rdtgroup *new_prdtgrp;
4154 	struct rdtgroup *rdtgrp;
4155 	cpumask_var_t tmpmask;
4156 	int ret;
4157 
4158 	rdtgrp = kernfs_to_rdtgroup(kn);
4159 	new_prdtgrp = kernfs_to_rdtgroup(new_parent);
4160 	if (!rdtgrp || !new_prdtgrp)
4161 		return -ENOENT;
4162 
4163 	/* Release both kernfs active_refs before obtaining rdtgroup mutex. */
4164 	rdtgroup_kn_get(rdtgrp, kn);
4165 	rdtgroup_kn_get(new_prdtgrp, new_parent);
4166 
4167 	mutex_lock(&rdtgroup_mutex);
4168 
4169 	rdt_last_cmd_clear();
4170 
4171 	/*
4172 	 * Don't allow kernfs_to_rdtgroup() to return a parent rdtgroup if
4173 	 * either kernfs_node is a file.
4174 	 */
4175 	if (kernfs_type(kn) != KERNFS_DIR ||
4176 	    kernfs_type(new_parent) != KERNFS_DIR) {
4177 		rdt_last_cmd_puts("Source and destination must be directories");
4178 		ret = -EPERM;
4179 		goto out;
4180 	}
4181 
4182 	if ((rdtgrp->flags & RDT_DELETED) || (new_prdtgrp->flags & RDT_DELETED)) {
4183 		ret = -ENOENT;
4184 		goto out;
4185 	}
4186 
4187 	kn_parent = rdt_kn_parent(kn);
4188 	if (rdtgrp->type != RDTMON_GROUP || !kn_parent ||
4189 	    !is_mon_groups(kn_parent, rdt_kn_name(kn))) {
4190 		rdt_last_cmd_puts("Source must be a MON group\n");
4191 		ret = -EPERM;
4192 		goto out;
4193 	}
4194 
4195 	if (!is_mon_groups(new_parent, new_name)) {
4196 		rdt_last_cmd_puts("Destination must be a mon_groups subdirectory\n");
4197 		ret = -EPERM;
4198 		goto out;
4199 	}
4200 
4201 	/*
4202 	 * If the MON group is monitoring CPUs, the CPUs must be assigned to the
4203 	 * current parent CTRL_MON group and therefore cannot be assigned to
4204 	 * the new parent, making the move illegal.
4205 	 */
4206 	if (!cpumask_empty(&rdtgrp->cpu_mask) &&
4207 	    rdtgrp->mon.parent != new_prdtgrp) {
4208 		rdt_last_cmd_puts("Cannot move a MON group that monitors CPUs\n");
4209 		ret = -EPERM;
4210 		goto out;
4211 	}
4212 
4213 	/*
4214 	 * Allocate the cpumask for use in mongrp_reparent() to avoid the
4215 	 * possibility of failing to allocate it after kernfs_rename() has
4216 	 * succeeded.
4217 	 */
4218 	if (!zalloc_cpumask_var(&tmpmask, GFP_KERNEL)) {
4219 		ret = -ENOMEM;
4220 		goto out;
4221 	}
4222 
4223 	/*
4224 	 * Perform all input validation and allocations needed to ensure
4225 	 * mongrp_reparent() will succeed before calling kernfs_rename(),
4226 	 * otherwise it would be necessary to revert this call if
4227 	 * mongrp_reparent() failed.
4228 	 */
4229 	ret = kernfs_rename(kn, new_parent, new_name);
4230 	if (!ret)
4231 		mongrp_reparent(rdtgrp, new_prdtgrp, tmpmask);
4232 
4233 	free_cpumask_var(tmpmask);
4234 
4235 out:
4236 	mutex_unlock(&rdtgroup_mutex);
4237 	rdtgroup_kn_put(rdtgrp, kn);
4238 	rdtgroup_kn_put(new_prdtgrp, new_parent);
4239 	return ret;
4240 }
4241 
4242 static int rdtgroup_show_options(struct seq_file *seq, struct kernfs_root *kf)
4243 {
4244 	if (resctrl_arch_get_cdp_enabled(RDT_RESOURCE_L3))
4245 		seq_puts(seq, ",cdp");
4246 
4247 	if (resctrl_arch_get_cdp_enabled(RDT_RESOURCE_L2))
4248 		seq_puts(seq, ",cdpl2");
4249 
4250 	if (is_mba_sc(resctrl_arch_get_resource(RDT_RESOURCE_MBA)))
4251 		seq_puts(seq, ",mba_MBps");
4252 
4253 	if (resctrl_debug)
4254 		seq_puts(seq, ",debug");
4255 
4256 	return 0;
4257 }
4258 
4259 static struct kernfs_syscall_ops rdtgroup_kf_syscall_ops = {
4260 	.mkdir		= rdtgroup_mkdir,
4261 	.rmdir		= rdtgroup_rmdir,
4262 	.rename		= rdtgroup_rename,
4263 	.show_options	= rdtgroup_show_options,
4264 };
4265 
4266 static int rdtgroup_setup_root(struct rdt_fs_context *ctx)
4267 {
4268 	rdt_root = kernfs_create_root(&rdtgroup_kf_syscall_ops,
4269 				      KERNFS_ROOT_CREATE_DEACTIVATED |
4270 				      KERNFS_ROOT_EXTRA_OPEN_PERM_CHECK,
4271 				      &rdtgroup_default);
4272 	if (IS_ERR(rdt_root))
4273 		return PTR_ERR(rdt_root);
4274 
4275 	ctx->kfc.root = rdt_root;
4276 	rdtgroup_default.kn = kernfs_root_to_node(rdt_root);
4277 
4278 	return 0;
4279 }
4280 
4281 static void rdtgroup_destroy_root(void)
4282 {
4283 	lockdep_assert_held(&rdtgroup_mutex);
4284 
4285 	kernfs_destroy_root(rdt_root);
4286 	rdtgroup_default.kn = NULL;
4287 }
4288 
4289 static void rdtgroup_setup_default(void)
4290 {
4291 	mutex_lock(&rdtgroup_mutex);
4292 
4293 	rdtgroup_default.closid = RESCTRL_RESERVED_CLOSID;
4294 	rdtgroup_default.mon.rmid = RESCTRL_RESERVED_RMID;
4295 	rdtgroup_default.type = RDTCTRL_GROUP;
4296 	INIT_LIST_HEAD(&rdtgroup_default.mon.crdtgrp_list);
4297 
4298 	list_add(&rdtgroup_default.rdtgroup_list, &rdt_all_groups);
4299 
4300 	mutex_unlock(&rdtgroup_mutex);
4301 }
4302 
4303 static void domain_destroy_l3_mon_state(struct rdt_l3_mon_domain *d)
4304 {
4305 	int idx;
4306 
4307 	kfree(d->cntr_cfg);
4308 	bitmap_free(d->rmid_busy_llc);
4309 	for_each_mbm_idx(idx) {
4310 		kfree(d->mbm_states[idx]);
4311 		d->mbm_states[idx] = NULL;
4312 	}
4313 }
4314 
4315 void resctrl_offline_ctrl_domain(struct rdt_resource *r, struct rdt_ctrl_domain *d)
4316 {
4317 	mutex_lock(&rdtgroup_mutex);
4318 
4319 	if (supports_mba_mbps() && r->rid == RDT_RESOURCE_MBA)
4320 		mba_sc_domain_destroy(r, d);
4321 
4322 	mutex_unlock(&rdtgroup_mutex);
4323 }
4324 
4325 void resctrl_offline_mon_domain(struct rdt_resource *r, struct rdt_domain_hdr *hdr)
4326 {
4327 	struct rdt_l3_mon_domain *d;
4328 
4329 	mutex_lock(&rdtgroup_mutex);
4330 
4331 	/*
4332 	 * If resctrl is mounted, remove all the
4333 	 * per domain monitor data directories.
4334 	 */
4335 	if (resctrl_mounted && resctrl_arch_mon_capable())
4336 		rmdir_mondata_subdir_allrdtgrp(r, hdr);
4337 
4338 	if (r->rid != RDT_RESOURCE_L3)
4339 		goto out_unlock;
4340 
4341 	if (!domain_header_is_valid(hdr, RESCTRL_MON_DOMAIN, RDT_RESOURCE_L3))
4342 		goto out_unlock;
4343 
4344 	d = container_of(hdr, struct rdt_l3_mon_domain, hdr);
4345 	if (resctrl_is_mbm_enabled())
4346 		cancel_delayed_work(&d->mbm_over);
4347 	if (resctrl_is_mon_event_enabled(QOS_L3_OCCUP_EVENT_ID) && has_busy_rmid(d)) {
4348 		/*
4349 		 * When a package is going down, forcefully
4350 		 * decrement rmid->ebusy. There is no way to know
4351 		 * that the L3 was flushed and hence may lead to
4352 		 * incorrect counts in rare scenarios, but leaving
4353 		 * the RMID as busy creates RMID leaks if the
4354 		 * package never comes back.
4355 		 */
4356 		__check_limbo(d, true);
4357 		cancel_delayed_work(&d->cqm_limbo);
4358 	}
4359 
4360 	domain_destroy_l3_mon_state(d);
4361 out_unlock:
4362 	mutex_unlock(&rdtgroup_mutex);
4363 }
4364 
4365 /**
4366  * domain_setup_l3_mon_state() -  Initialise domain monitoring structures.
4367  * @r:	The resource for the newly online domain.
4368  * @d:	The newly online domain.
4369  *
4370  * Allocate monitor resources that belong to this domain.
4371  * Called when the first CPU of a domain comes online, regardless of whether
4372  * the filesystem is mounted.
4373  * During boot this may be called before global allocations have been made by
4374  * resctrl_l3_mon_resource_init().
4375  *
4376  * Called during CPU online that may run as soon as CPU online callbacks
4377  * are set up during resctrl initialization. The number of supported RMIDs
4378  * may be reduced if additional mon_capable resources are enumerated
4379  * at mount time. This means the rdt_l3_mon_domain::mbm_states[] and
4380  * rdt_l3_mon_domain::rmid_busy_llc allocations may be larger than needed.
4381  *
4382  * Return: 0 for success, or -ENOMEM.
4383  */
4384 static int domain_setup_l3_mon_state(struct rdt_resource *r, struct rdt_l3_mon_domain *d)
4385 {
4386 	u32 idx_limit = resctrl_arch_system_num_rmid_idx();
4387 	size_t tsize = sizeof(*d->mbm_states[0]);
4388 	enum resctrl_event_id eventid;
4389 	int idx;
4390 
4391 	if (resctrl_is_mon_event_enabled(QOS_L3_OCCUP_EVENT_ID)) {
4392 		d->rmid_busy_llc = bitmap_zalloc(idx_limit, GFP_KERNEL);
4393 		if (!d->rmid_busy_llc)
4394 			return -ENOMEM;
4395 	}
4396 
4397 	for_each_mbm_event_id(eventid) {
4398 		if (!resctrl_is_mon_event_enabled(eventid))
4399 			continue;
4400 		idx = MBM_STATE_IDX(eventid);
4401 		d->mbm_states[idx] = kcalloc(idx_limit, tsize, GFP_KERNEL);
4402 		if (!d->mbm_states[idx])
4403 			goto cleanup;
4404 	}
4405 
4406 	if (resctrl_is_mbm_enabled() && r->mon.mbm_cntr_assignable) {
4407 		tsize = sizeof(*d->cntr_cfg);
4408 		d->cntr_cfg = kcalloc(r->mon.num_mbm_cntrs, tsize, GFP_KERNEL);
4409 		if (!d->cntr_cfg)
4410 			goto cleanup;
4411 	}
4412 
4413 	return 0;
4414 cleanup:
4415 	bitmap_free(d->rmid_busy_llc);
4416 	for_each_mbm_idx(idx) {
4417 		kfree(d->mbm_states[idx]);
4418 		d->mbm_states[idx] = NULL;
4419 	}
4420 
4421 	return -ENOMEM;
4422 }
4423 
4424 int resctrl_online_ctrl_domain(struct rdt_resource *r, struct rdt_ctrl_domain *d)
4425 {
4426 	int err = 0;
4427 
4428 	mutex_lock(&rdtgroup_mutex);
4429 
4430 	if (supports_mba_mbps() && r->rid == RDT_RESOURCE_MBA) {
4431 		/* RDT_RESOURCE_MBA is never mon_capable */
4432 		err = mba_sc_domain_allocate(r, d);
4433 	}
4434 
4435 	mutex_unlock(&rdtgroup_mutex);
4436 
4437 	return err;
4438 }
4439 
4440 int resctrl_online_mon_domain(struct rdt_resource *r, struct rdt_domain_hdr *hdr)
4441 {
4442 	struct rdt_l3_mon_domain *d;
4443 	int err = -EINVAL;
4444 
4445 	mutex_lock(&rdtgroup_mutex);
4446 
4447 	if (r->rid != RDT_RESOURCE_L3)
4448 		goto mkdir;
4449 
4450 	if (!domain_header_is_valid(hdr, RESCTRL_MON_DOMAIN, RDT_RESOURCE_L3))
4451 		goto out_unlock;
4452 
4453 	d = container_of(hdr, struct rdt_l3_mon_domain, hdr);
4454 	err = domain_setup_l3_mon_state(r, d);
4455 	if (err)
4456 		goto out_unlock;
4457 
4458 	if (resctrl_is_mbm_enabled()) {
4459 		INIT_DELAYED_WORK(&d->mbm_over, mbm_handle_overflow);
4460 		mbm_setup_overflow_handler(d, MBM_OVERFLOW_INTERVAL,
4461 					   RESCTRL_PICK_ANY_CPU);
4462 	}
4463 
4464 	if (resctrl_is_mon_event_enabled(QOS_L3_OCCUP_EVENT_ID))
4465 		INIT_DELAYED_WORK(&d->cqm_limbo, cqm_handle_limbo);
4466 
4467 mkdir:
4468 	err = 0;
4469 	/*
4470 	 * If the filesystem is not mounted then only the default resource group
4471 	 * exists. Creation of its directories is deferred until mount time
4472 	 * by rdt_get_tree() calling mkdir_mondata_all().
4473 	 * If resctrl is mounted, add per domain monitor data directories.
4474 	 */
4475 	if (resctrl_mounted && resctrl_arch_mon_capable())
4476 		mkdir_mondata_subdir_allrdtgrp(r, hdr);
4477 
4478 out_unlock:
4479 	mutex_unlock(&rdtgroup_mutex);
4480 
4481 	return err;
4482 }
4483 
4484 void resctrl_online_cpu(unsigned int cpu)
4485 {
4486 	mutex_lock(&rdtgroup_mutex);
4487 	/* The CPU is set in default rdtgroup after online. */
4488 	cpumask_set_cpu(cpu, &rdtgroup_default.cpu_mask);
4489 	mutex_unlock(&rdtgroup_mutex);
4490 }
4491 
4492 static void clear_childcpus(struct rdtgroup *r, unsigned int cpu)
4493 {
4494 	struct rdtgroup *cr;
4495 
4496 	list_for_each_entry(cr, &r->mon.crdtgrp_list, mon.crdtgrp_list) {
4497 		if (cpumask_test_and_clear_cpu(cpu, &cr->cpu_mask))
4498 			break;
4499 	}
4500 }
4501 
4502 static struct rdt_l3_mon_domain *get_mon_domain_from_cpu(int cpu,
4503 							 struct rdt_resource *r)
4504 {
4505 	struct rdt_l3_mon_domain *d;
4506 
4507 	lockdep_assert_cpus_held();
4508 
4509 	list_for_each_entry(d, &r->mon_domains, hdr.list) {
4510 		/* Find the domain that contains this CPU */
4511 		if (cpumask_test_cpu(cpu, &d->hdr.cpu_mask))
4512 			return d;
4513 	}
4514 
4515 	return NULL;
4516 }
4517 
4518 void resctrl_offline_cpu(unsigned int cpu)
4519 {
4520 	struct rdt_resource *l3 = resctrl_arch_get_resource(RDT_RESOURCE_L3);
4521 	struct rdt_l3_mon_domain *d;
4522 	struct rdtgroup *rdtgrp;
4523 
4524 	mutex_lock(&rdtgroup_mutex);
4525 	list_for_each_entry(rdtgrp, &rdt_all_groups, rdtgroup_list) {
4526 		if (cpumask_test_and_clear_cpu(cpu, &rdtgrp->cpu_mask)) {
4527 			clear_childcpus(rdtgrp, cpu);
4528 			break;
4529 		}
4530 	}
4531 
4532 	if (!l3->mon_capable)
4533 		goto out_unlock;
4534 
4535 	d = get_mon_domain_from_cpu(cpu, l3);
4536 	if (d) {
4537 		if (resctrl_is_mbm_enabled() && cpu == d->mbm_work_cpu) {
4538 			cancel_delayed_work(&d->mbm_over);
4539 			mbm_setup_overflow_handler(d, 0, cpu);
4540 		}
4541 		if (resctrl_is_mon_event_enabled(QOS_L3_OCCUP_EVENT_ID) &&
4542 		    cpu == d->cqm_work_cpu && has_busy_rmid(d)) {
4543 			cancel_delayed_work(&d->cqm_limbo);
4544 			cqm_setup_limbo_handler(d, 0, cpu);
4545 		}
4546 	}
4547 
4548 out_unlock:
4549 	mutex_unlock(&rdtgroup_mutex);
4550 }
4551 
4552 /*
4553  * resctrl_init - resctrl filesystem initialization
4554  *
4555  * Setup resctrl file system including set up root, create mount point,
4556  * register resctrl filesystem, and initialize files under root directory.
4557  *
4558  * Return: 0 on success or -errno
4559  */
4560 int resctrl_init(void)
4561 {
4562 	int ret = 0;
4563 
4564 	seq_buf_init(&last_cmd_status, last_cmd_status_buf,
4565 		     sizeof(last_cmd_status_buf));
4566 
4567 	rdtgroup_setup_default();
4568 
4569 	thread_throttle_mode_init();
4570 
4571 	io_alloc_init();
4572 
4573 	ret = resctrl_l3_mon_resource_init();
4574 	if (ret)
4575 		return ret;
4576 
4577 	ret = sysfs_create_mount_point(fs_kobj, "resctrl");
4578 	if (ret) {
4579 		resctrl_l3_mon_resource_exit();
4580 		return ret;
4581 	}
4582 
4583 	ret = register_filesystem(&rdt_fs_type);
4584 	if (ret)
4585 		goto cleanup_mountpoint;
4586 
4587 	/*
4588 	 * Adding the resctrl debugfs directory here may not be ideal since
4589 	 * it would let the resctrl debugfs directory appear on the debugfs
4590 	 * filesystem before the resctrl filesystem is mounted.
4591 	 * It may also be ok since that would enable debugging of RDT before
4592 	 * resctrl is mounted.
4593 	 * The reason why the debugfs directory is created here and not in
4594 	 * rdt_get_tree() is because rdt_get_tree() takes rdtgroup_mutex and
4595 	 * during the debugfs directory creation also &sb->s_type->i_mutex_key
4596 	 * (the lockdep class of inode->i_rwsem). Other filesystem
4597 	 * interactions (eg. SyS_getdents) have the lock ordering:
4598 	 * &sb->s_type->i_mutex_key --> &mm->mmap_lock
4599 	 * During mmap(), called with &mm->mmap_lock, the rdtgroup_mutex
4600 	 * is taken, thus creating dependency:
4601 	 * &mm->mmap_lock --> rdtgroup_mutex for the latter that can cause
4602 	 * issues considering the other two lock dependencies.
4603 	 * By creating the debugfs directory here we avoid a dependency
4604 	 * that may cause deadlock (even though file operations cannot
4605 	 * occur until the filesystem is mounted, but I do not know how to
4606 	 * tell lockdep that).
4607 	 */
4608 	debugfs_resctrl = debugfs_create_dir("resctrl", NULL);
4609 
4610 	return 0;
4611 
4612 cleanup_mountpoint:
4613 	sysfs_remove_mount_point(fs_kobj, "resctrl");
4614 	resctrl_l3_mon_resource_exit();
4615 
4616 	return ret;
4617 }
4618 
4619 static bool resctrl_online_domains_exist(void)
4620 {
4621 	struct rdt_resource *r;
4622 
4623 	/*
4624 	 * Only walk capable resources to allow resctrl_arch_get_resource()
4625 	 * to return dummy 'not capable' resources.
4626 	 */
4627 	for_each_alloc_capable_rdt_resource(r) {
4628 		if (!list_empty(&r->ctrl_domains))
4629 			return true;
4630 	}
4631 
4632 	for_each_mon_capable_rdt_resource(r) {
4633 		if (!list_empty(&r->mon_domains))
4634 			return true;
4635 	}
4636 
4637 	return false;
4638 }
4639 
4640 /**
4641  * resctrl_exit() - Remove the resctrl filesystem and free resources.
4642  *
4643  * Called by the architecture code in response to a fatal error.
4644  * Removes resctrl files and structures from kernfs to prevent further
4645  * configuration.
4646  *
4647  * When called by the architecture code, all CPUs and resctrl domains must be
4648  * offline. This ensures the limbo and overflow handlers are not scheduled to
4649  * run, meaning the data structures they access can be freed by
4650  * resctrl_l3_mon_resource_exit().
4651  *
4652  * After resctrl_exit() returns, the architecture code should return an
4653  * error from all resctrl_arch_ functions that can do this.
4654  * resctrl_arch_get_resource() must continue to return struct rdt_resources
4655  * with the correct rid field to ensure the filesystem can be unmounted.
4656  */
4657 void resctrl_exit(void)
4658 {
4659 	cpus_read_lock();
4660 	WARN_ON_ONCE(resctrl_online_domains_exist());
4661 
4662 	mutex_lock(&rdtgroup_mutex);
4663 	resctrl_fs_teardown();
4664 	mutex_unlock(&rdtgroup_mutex);
4665 
4666 	cpus_read_unlock();
4667 
4668 	debugfs_remove_recursive(debugfs_resctrl);
4669 	debugfs_resctrl = NULL;
4670 	unregister_filesystem(&rdt_fs_type);
4671 
4672 	/*
4673 	 * Do not remove the sysfs mount point added by resctrl_init() so that
4674 	 * it can be used to umount resctrl.
4675 	 */
4676 
4677 	resctrl_l3_mon_resource_exit();
4678 	free_rmid_lru_list();
4679 }
4680