xref: /linux/fs/resctrl/rdtgroup.c (revision 79727019ce3da234d877ec0cb6a3985f001e2b2d)
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		= 0644,
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 /**
2219  * rdtgroup_kn_mode_restrict - Restrict user access to named resctrl file
2220  * @r: The resource group with which the file is associated.
2221  * @name: Name of the file
2222  *
2223  * The permissions of named resctrl file, directory, or link are modified
2224  * to not allow read, write, or execute by any user.
2225  *
2226  * WARNING: This function is intended to communicate to the user that the
2227  * resctrl file has been locked down - that it is not relevant to the
2228  * particular state the system finds itself in. It should not be relied
2229  * on to protect from user access because after the file's permissions
2230  * are restricted the user can still change the permissions using chmod
2231  * from the command line.
2232  *
2233  * Return: 0 on success, <0 on failure.
2234  */
2235 int rdtgroup_kn_mode_restrict(struct rdtgroup *r, const char *name)
2236 {
2237 	struct iattr iattr = {.ia_valid = ATTR_MODE,};
2238 	struct kernfs_node *kn;
2239 	int ret = 0;
2240 
2241 	kn = kernfs_find_and_get_ns(r->kn, name, NULL);
2242 	if (!kn)
2243 		return -ENOENT;
2244 
2245 	switch (kernfs_type(kn)) {
2246 	case KERNFS_DIR:
2247 		iattr.ia_mode = S_IFDIR;
2248 		break;
2249 	case KERNFS_FILE:
2250 		iattr.ia_mode = S_IFREG;
2251 		break;
2252 	case KERNFS_LINK:
2253 		iattr.ia_mode = S_IFLNK;
2254 		break;
2255 	}
2256 
2257 	ret = kernfs_setattr(kn, &iattr);
2258 	kernfs_put(kn);
2259 	return ret;
2260 }
2261 
2262 /**
2263  * rdtgroup_kn_mode_restore - Restore user access to named resctrl file
2264  * @r: The resource group with which the file is associated.
2265  * @name: Name of the file
2266  * @mask: Mask of permissions that should be restored
2267  *
2268  * Restore the permissions of the named file. If @name is a directory the
2269  * permissions of its parent will be used.
2270  *
2271  * Return: 0 on success, <0 on failure.
2272  */
2273 int rdtgroup_kn_mode_restore(struct rdtgroup *r, const char *name,
2274 			     umode_t mask)
2275 {
2276 	struct iattr iattr = {.ia_valid = ATTR_MODE,};
2277 	struct kernfs_node *kn, *parent;
2278 	struct rftype *rfts, *rft;
2279 	int ret, len;
2280 
2281 	rfts = res_common_files;
2282 	len = ARRAY_SIZE(res_common_files);
2283 
2284 	for (rft = rfts; rft < rfts + len; rft++) {
2285 		if (!strcmp(rft->name, name))
2286 			iattr.ia_mode = rft->mode & mask;
2287 	}
2288 
2289 	kn = kernfs_find_and_get_ns(r->kn, name, NULL);
2290 	if (!kn)
2291 		return -ENOENT;
2292 
2293 	switch (kernfs_type(kn)) {
2294 	case KERNFS_DIR:
2295 		parent = kernfs_get_parent(kn);
2296 		if (parent) {
2297 			iattr.ia_mode |= parent->mode;
2298 			kernfs_put(parent);
2299 		}
2300 		iattr.ia_mode |= S_IFDIR;
2301 		break;
2302 	case KERNFS_FILE:
2303 		iattr.ia_mode |= S_IFREG;
2304 		break;
2305 	case KERNFS_LINK:
2306 		iattr.ia_mode |= S_IFLNK;
2307 		break;
2308 	}
2309 
2310 	ret = kernfs_setattr(kn, &iattr);
2311 	kernfs_put(kn);
2312 	return ret;
2313 }
2314 
2315 static int resctrl_mkdir_event_configs(struct rdt_resource *r, struct kernfs_node *l3_mon_kn)
2316 {
2317 	struct kernfs_node *kn_subdir, *kn_subdir2;
2318 	struct mon_evt *mevt;
2319 	int ret;
2320 
2321 	kn_subdir = kernfs_create_dir(l3_mon_kn, "event_configs", l3_mon_kn->mode, NULL);
2322 	if (IS_ERR(kn_subdir))
2323 		return PTR_ERR(kn_subdir);
2324 
2325 	ret = rdtgroup_kn_set_ugid(kn_subdir);
2326 	if (ret)
2327 		return ret;
2328 
2329 	for_each_mon_event(mevt) {
2330 		if (mevt->rid != r->rid || !mevt->enabled || !resctrl_is_mbm_event(mevt->evtid))
2331 			continue;
2332 
2333 		kn_subdir2 = kernfs_create_dir(kn_subdir, mevt->name, kn_subdir->mode, mevt);
2334 		if (IS_ERR(kn_subdir2)) {
2335 			ret = PTR_ERR(kn_subdir2);
2336 			goto out;
2337 		}
2338 
2339 		ret = rdtgroup_kn_set_ugid(kn_subdir2);
2340 		if (ret)
2341 			goto out;
2342 
2343 		ret = rdtgroup_add_files(kn_subdir2, RFTYPE_ASSIGN_CONFIG);
2344 		if (ret)
2345 			break;
2346 	}
2347 
2348 out:
2349 	return ret;
2350 }
2351 
2352 static int rdtgroup_mkdir_info_resdir(void *priv, char *name,
2353 				      unsigned long fflags)
2354 {
2355 	struct kernfs_node *kn_subdir;
2356 	struct rdt_resource *r;
2357 	int ret;
2358 
2359 	kn_subdir = kernfs_create_dir(kn_info, name,
2360 				      kn_info->mode, priv);
2361 	if (IS_ERR(kn_subdir))
2362 		return PTR_ERR(kn_subdir);
2363 
2364 	ret = rdtgroup_kn_set_ugid(kn_subdir);
2365 	if (ret)
2366 		return ret;
2367 
2368 	ret = rdtgroup_add_files(kn_subdir, fflags);
2369 	if (ret)
2370 		return ret;
2371 
2372 	if ((fflags & RFTYPE_MON_INFO) == RFTYPE_MON_INFO) {
2373 		r = priv;
2374 		if (r->mon.mbm_cntr_assignable) {
2375 			ret = resctrl_mkdir_event_configs(r, kn_subdir);
2376 			if (ret)
2377 				return ret;
2378 			/*
2379 			 * Hide BMEC related files if mbm_event mode
2380 			 * is enabled.
2381 			 */
2382 			if (resctrl_arch_mbm_cntr_assign_enabled(r))
2383 				resctrl_bmec_files_show(r, kn_subdir, false);
2384 		}
2385 	}
2386 
2387 	kernfs_activate(kn_subdir);
2388 
2389 	return ret;
2390 }
2391 
2392 static unsigned long fflags_from_resource(struct rdt_resource *r)
2393 {
2394 	switch (r->rid) {
2395 	case RDT_RESOURCE_L3:
2396 	case RDT_RESOURCE_L2:
2397 		return RFTYPE_RES_CACHE;
2398 	case RDT_RESOURCE_MBA:
2399 	case RDT_RESOURCE_SMBA:
2400 		return RFTYPE_RES_MB;
2401 	case RDT_RESOURCE_PERF_PKG:
2402 		return RFTYPE_RES_PERF_PKG;
2403 	}
2404 
2405 	return WARN_ON_ONCE(1);
2406 }
2407 
2408 static int rdtgroup_create_info_dir(struct kernfs_node *parent_kn)
2409 {
2410 	struct resctrl_schema *s;
2411 	struct rdt_resource *r;
2412 	unsigned long fflags;
2413 	char name[32];
2414 	int ret;
2415 
2416 	/* create the directory */
2417 	kn_info = kernfs_create_dir(parent_kn, "info", parent_kn->mode, NULL);
2418 	if (IS_ERR(kn_info))
2419 		return PTR_ERR(kn_info);
2420 
2421 	ret = rdtgroup_add_files(kn_info, RFTYPE_TOP_INFO);
2422 	if (ret)
2423 		goto out_destroy;
2424 
2425 	/* loop over enabled controls, these are all alloc_capable */
2426 	list_for_each_entry(s, &resctrl_schema_all, list) {
2427 		r = s->res;
2428 		fflags = fflags_from_resource(r) | RFTYPE_CTRL_INFO;
2429 		ret = rdtgroup_mkdir_info_resdir(s, s->name, fflags);
2430 		if (ret)
2431 			goto out_destroy;
2432 	}
2433 
2434 	for_each_mon_capable_rdt_resource(r) {
2435 		fflags = fflags_from_resource(r) | RFTYPE_MON_INFO;
2436 		sprintf(name, "%s_MON", r->name);
2437 		ret = rdtgroup_mkdir_info_resdir(r, name, fflags);
2438 		if (ret)
2439 			goto out_destroy;
2440 	}
2441 
2442 	ret = rdtgroup_kn_set_ugid(kn_info);
2443 	if (ret)
2444 		goto out_destroy;
2445 
2446 	kernfs_activate(kn_info);
2447 
2448 	return 0;
2449 
2450 out_destroy:
2451 	kernfs_remove(kn_info);
2452 	return ret;
2453 }
2454 
2455 static int
2456 mongroup_create_dir(struct kernfs_node *parent_kn, struct rdtgroup *prgrp,
2457 		    char *name, struct kernfs_node **dest_kn)
2458 {
2459 	struct kernfs_node *kn;
2460 	int ret;
2461 
2462 	/* create the directory */
2463 	kn = kernfs_create_dir(parent_kn, name, parent_kn->mode, prgrp);
2464 	if (IS_ERR(kn))
2465 		return PTR_ERR(kn);
2466 
2467 	if (dest_kn)
2468 		*dest_kn = kn;
2469 
2470 	ret = rdtgroup_kn_set_ugid(kn);
2471 	if (ret)
2472 		goto out_destroy;
2473 
2474 	kernfs_activate(kn);
2475 
2476 	return 0;
2477 
2478 out_destroy:
2479 	kernfs_remove(kn);
2480 	return ret;
2481 }
2482 
2483 static inline bool is_mba_linear(void)
2484 {
2485 	return resctrl_arch_get_resource(RDT_RESOURCE_MBA)->membw.delay_linear;
2486 }
2487 
2488 static int mba_sc_domain_allocate(struct rdt_resource *r, struct rdt_ctrl_domain *d)
2489 {
2490 	u32 num_closid = resctrl_arch_get_num_closid(r);
2491 	int cpu = cpumask_any(&d->hdr.cpu_mask);
2492 	int i;
2493 
2494 	d->mbps_val = kcalloc_node(num_closid, sizeof(*d->mbps_val),
2495 				   GFP_KERNEL, cpu_to_node(cpu));
2496 	if (!d->mbps_val)
2497 		return -ENOMEM;
2498 
2499 	for (i = 0; i < num_closid; i++)
2500 		d->mbps_val[i] = MBA_MAX_MBPS;
2501 
2502 	return 0;
2503 }
2504 
2505 static void mba_sc_domain_destroy(struct rdt_resource *r,
2506 				  struct rdt_ctrl_domain *d)
2507 {
2508 	kfree(d->mbps_val);
2509 	d->mbps_val = NULL;
2510 }
2511 
2512 /*
2513  * MBA software controller is supported only if
2514  * MBM is supported and MBA is in linear scale,
2515  * and the MBM monitor scope is the same as MBA
2516  * control scope.
2517  */
2518 static bool supports_mba_mbps(void)
2519 {
2520 	struct rdt_resource *rmbm = resctrl_arch_get_resource(RDT_RESOURCE_L3);
2521 	struct rdt_resource *r = resctrl_arch_get_resource(RDT_RESOURCE_MBA);
2522 
2523 	return (resctrl_is_mbm_enabled() &&
2524 		r->alloc_capable && is_mba_linear() &&
2525 		r->ctrl_scope == rmbm->mon_scope);
2526 }
2527 
2528 /*
2529  * Enable or disable the MBA software controller
2530  * which helps user specify bandwidth in MBps.
2531  */
2532 static int set_mba_sc(bool mba_sc)
2533 {
2534 	struct rdt_resource *r = resctrl_arch_get_resource(RDT_RESOURCE_MBA);
2535 	u32 num_closid = resctrl_arch_get_num_closid(r);
2536 	struct rdt_ctrl_domain *d;
2537 	unsigned long fflags;
2538 	int i;
2539 
2540 	if (!supports_mba_mbps() || mba_sc == is_mba_sc(r))
2541 		return -EINVAL;
2542 
2543 	r->membw.mba_sc = mba_sc;
2544 
2545 	rdtgroup_default.mba_mbps_event = mba_mbps_default_event;
2546 
2547 	list_for_each_entry(d, &r->ctrl_domains, hdr.list) {
2548 		for (i = 0; i < num_closid; i++)
2549 			d->mbps_val[i] = MBA_MAX_MBPS;
2550 	}
2551 
2552 	fflags = mba_sc ? RFTYPE_CTRL_BASE | RFTYPE_MON_BASE : 0;
2553 	resctrl_file_fflags_init("mba_MBps_event", fflags);
2554 
2555 	return 0;
2556 }
2557 
2558 /*
2559  * We don't allow rdtgroup directories to be created anywhere
2560  * except the root directory. Thus when looking for the rdtgroup
2561  * structure for a kernfs node we are either looking at a directory,
2562  * in which case the rdtgroup structure is pointed at by the "priv"
2563  * field, otherwise we have a file, and need only look to the parent
2564  * to find the rdtgroup.
2565  */
2566 static struct rdtgroup *kernfs_to_rdtgroup(struct kernfs_node *kn)
2567 {
2568 	if (kernfs_type(kn) == KERNFS_DIR) {
2569 		/*
2570 		 * All the resource directories use "kn->priv"
2571 		 * to point to the "struct rdtgroup" for the
2572 		 * resource. "info" and its subdirectories don't
2573 		 * have rdtgroup structures, so return NULL here.
2574 		 */
2575 		if (kn == kn_info ||
2576 		    rcu_access_pointer(kn->__parent) == kn_info)
2577 			return NULL;
2578 		else
2579 			return kn->priv;
2580 	} else {
2581 		return rdt_kn_parent_priv(kn);
2582 	}
2583 }
2584 
2585 static void rdtgroup_kn_get(struct rdtgroup *rdtgrp, struct kernfs_node *kn)
2586 {
2587 	atomic_inc(&rdtgrp->waitcount);
2588 	kernfs_break_active_protection(kn);
2589 }
2590 
2591 static void rdtgroup_kn_put(struct rdtgroup *rdtgrp, struct kernfs_node *kn)
2592 {
2593 	if (atomic_dec_and_test(&rdtgrp->waitcount) &&
2594 	    (rdtgrp->flags & RDT_DELETED)) {
2595 		if (rdtgrp->mode == RDT_MODE_PSEUDO_LOCKSETUP ||
2596 		    rdtgrp->mode == RDT_MODE_PSEUDO_LOCKED)
2597 			rdtgroup_pseudo_lock_remove(rdtgrp);
2598 		kernfs_unbreak_active_protection(kn);
2599 		rdtgroup_remove(rdtgrp);
2600 	} else {
2601 		kernfs_unbreak_active_protection(kn);
2602 	}
2603 }
2604 
2605 struct rdtgroup *rdtgroup_kn_lock_live(struct kernfs_node *kn)
2606 {
2607 	struct rdtgroup *rdtgrp = kernfs_to_rdtgroup(kn);
2608 
2609 	if (!rdtgrp)
2610 		return NULL;
2611 
2612 	rdtgroup_kn_get(rdtgrp, kn);
2613 
2614 	cpus_read_lock();
2615 	mutex_lock(&rdtgroup_mutex);
2616 
2617 	/* Was this group deleted while we waited? */
2618 	if (rdtgrp->flags & RDT_DELETED)
2619 		return NULL;
2620 
2621 	return rdtgrp;
2622 }
2623 
2624 void rdtgroup_kn_unlock(struct kernfs_node *kn)
2625 {
2626 	struct rdtgroup *rdtgrp = kernfs_to_rdtgroup(kn);
2627 
2628 	if (!rdtgrp)
2629 		return;
2630 
2631 	mutex_unlock(&rdtgroup_mutex);
2632 	cpus_read_unlock();
2633 
2634 	rdtgroup_kn_put(rdtgrp, kn);
2635 }
2636 
2637 static int mkdir_mondata_all(struct kernfs_node *parent_kn,
2638 			     struct rdtgroup *prgrp,
2639 			     struct kernfs_node **mon_data_kn);
2640 
2641 static void rdt_disable_ctx(void)
2642 {
2643 	resctrl_arch_set_cdp_enabled(RDT_RESOURCE_L3, false);
2644 	resctrl_arch_set_cdp_enabled(RDT_RESOURCE_L2, false);
2645 	set_mba_sc(false);
2646 
2647 	resctrl_debug = false;
2648 }
2649 
2650 static int rdt_enable_ctx(struct rdt_fs_context *ctx)
2651 {
2652 	int ret = 0;
2653 
2654 	if (ctx->enable_cdpl2) {
2655 		ret = resctrl_arch_set_cdp_enabled(RDT_RESOURCE_L2, true);
2656 		if (ret)
2657 			goto out_done;
2658 	}
2659 
2660 	if (ctx->enable_cdpl3) {
2661 		ret = resctrl_arch_set_cdp_enabled(RDT_RESOURCE_L3, true);
2662 		if (ret)
2663 			goto out_cdpl2;
2664 	}
2665 
2666 	if (ctx->enable_mba_mbps) {
2667 		ret = set_mba_sc(true);
2668 		if (ret)
2669 			goto out_cdpl3;
2670 	}
2671 
2672 	if (ctx->enable_debug)
2673 		resctrl_debug = true;
2674 
2675 	return 0;
2676 
2677 out_cdpl3:
2678 	resctrl_arch_set_cdp_enabled(RDT_RESOURCE_L3, false);
2679 out_cdpl2:
2680 	resctrl_arch_set_cdp_enabled(RDT_RESOURCE_L2, false);
2681 out_done:
2682 	return ret;
2683 }
2684 
2685 static int schemata_list_add(struct rdt_resource *r, enum resctrl_conf_type type)
2686 {
2687 	struct resctrl_schema *s;
2688 	const char *suffix = "";
2689 	int ret, cl;
2690 
2691 	s = kzalloc_obj(*s);
2692 	if (!s)
2693 		return -ENOMEM;
2694 
2695 	s->res = r;
2696 	s->num_closid = resctrl_arch_get_num_closid(r);
2697 	if (resctrl_arch_get_cdp_enabled(r->rid))
2698 		s->num_closid /= 2;
2699 
2700 	s->conf_type = type;
2701 	switch (type) {
2702 	case CDP_CODE:
2703 		suffix = "CODE";
2704 		break;
2705 	case CDP_DATA:
2706 		suffix = "DATA";
2707 		break;
2708 	case CDP_NONE:
2709 		suffix = "";
2710 		break;
2711 	}
2712 
2713 	ret = snprintf(s->name, sizeof(s->name), "%s%s", r->name, suffix);
2714 	if (ret >= sizeof(s->name)) {
2715 		kfree(s);
2716 		return -EINVAL;
2717 	}
2718 
2719 	cl = strlen(s->name);
2720 
2721 	/*
2722 	 * If CDP is supported by this resource, but not enabled,
2723 	 * include the suffix. This ensures the tabular format of the
2724 	 * schemata file does not change between mounts of the filesystem.
2725 	 */
2726 	if (r->cdp_capable && !resctrl_arch_get_cdp_enabled(r->rid))
2727 		cl += 4;
2728 
2729 	if (cl > max_name_width)
2730 		max_name_width = cl;
2731 
2732 	switch (r->schema_fmt) {
2733 	case RESCTRL_SCHEMA_BITMAP:
2734 		s->fmt_str = "%d=%x";
2735 		break;
2736 	case RESCTRL_SCHEMA_RANGE:
2737 		s->fmt_str = "%d=%u";
2738 		break;
2739 	}
2740 
2741 	if (WARN_ON_ONCE(!s->fmt_str)) {
2742 		kfree(s);
2743 		return -EINVAL;
2744 	}
2745 
2746 	INIT_LIST_HEAD(&s->list);
2747 	list_add(&s->list, &resctrl_schema_all);
2748 
2749 	return 0;
2750 }
2751 
2752 static int schemata_list_create(void)
2753 {
2754 	struct rdt_resource *r;
2755 	int ret = 0;
2756 
2757 	for_each_alloc_capable_rdt_resource(r) {
2758 		if (resctrl_arch_get_cdp_enabled(r->rid)) {
2759 			ret = schemata_list_add(r, CDP_CODE);
2760 			if (ret)
2761 				break;
2762 
2763 			ret = schemata_list_add(r, CDP_DATA);
2764 		} else {
2765 			ret = schemata_list_add(r, CDP_NONE);
2766 		}
2767 
2768 		if (ret)
2769 			break;
2770 	}
2771 
2772 	return ret;
2773 }
2774 
2775 static void schemata_list_destroy(void)
2776 {
2777 	struct resctrl_schema *s, *tmp;
2778 
2779 	list_for_each_entry_safe(s, tmp, &resctrl_schema_all, list) {
2780 		list_del(&s->list);
2781 		kfree(s);
2782 	}
2783 }
2784 
2785 static int rdt_get_tree(struct fs_context *fc)
2786 {
2787 	struct rdt_fs_context *ctx = rdt_fc2context(fc);
2788 	unsigned long flags = RFTYPE_CTRL_BASE;
2789 	struct rdt_l3_mon_domain *dom;
2790 	struct rdt_resource *r;
2791 	int ret;
2792 
2793 	DO_ONCE_SLEEPABLE(resctrl_arch_pre_mount);
2794 
2795 	cpus_read_lock();
2796 	mutex_lock(&rdtgroup_mutex);
2797 	/*
2798 	 * resctrl file system can only be mounted once.
2799 	 */
2800 	if (resctrl_mounted) {
2801 		ret = -EBUSY;
2802 		goto out;
2803 	}
2804 
2805 	ret = setup_rmid_lru_list();
2806 	if (ret)
2807 		goto out;
2808 
2809 	ret = rdtgroup_setup_root(ctx);
2810 	if (ret)
2811 		goto out;
2812 
2813 	ret = rdt_enable_ctx(ctx);
2814 	if (ret)
2815 		goto out_root;
2816 
2817 	ret = schemata_list_create();
2818 	if (ret)
2819 		goto out_schemata_free;
2820 
2821 	ret = closid_init();
2822 	if (ret)
2823 		goto out_schemata_free;
2824 
2825 	if (resctrl_arch_mon_capable())
2826 		flags |= RFTYPE_MON;
2827 
2828 	ret = rdtgroup_add_files(rdtgroup_default.kn, flags);
2829 	if (ret)
2830 		goto out_closid_exit;
2831 
2832 	kernfs_activate(rdtgroup_default.kn);
2833 
2834 	ret = rdtgroup_create_info_dir(rdtgroup_default.kn);
2835 	if (ret < 0)
2836 		goto out_closid_exit;
2837 
2838 	if (resctrl_arch_mon_capable()) {
2839 		ret = mongroup_create_dir(rdtgroup_default.kn,
2840 					  &rdtgroup_default, "mon_groups",
2841 					  &kn_mongrp);
2842 		if (ret < 0)
2843 			goto out_info;
2844 
2845 		rdtgroup_assign_cntrs(&rdtgroup_default);
2846 
2847 		ret = mkdir_mondata_all(rdtgroup_default.kn,
2848 					&rdtgroup_default, &kn_mondata);
2849 		if (ret < 0)
2850 			goto out_mongrp;
2851 		rdtgroup_default.mon.mon_data_kn = kn_mondata;
2852 	}
2853 
2854 	ret = rdt_pseudo_lock_init();
2855 	if (ret)
2856 		goto out_mondata;
2857 
2858 	ret = kernfs_get_tree(fc);
2859 	if (ret < 0)
2860 		goto out_psl;
2861 
2862 	if (resctrl_arch_alloc_capable())
2863 		resctrl_arch_enable_alloc();
2864 	if (resctrl_arch_mon_capable())
2865 		resctrl_arch_enable_mon();
2866 
2867 	if (resctrl_arch_alloc_capable() || resctrl_arch_mon_capable())
2868 		resctrl_mounted = true;
2869 
2870 	if (resctrl_is_mbm_enabled()) {
2871 		r = resctrl_arch_get_resource(RDT_RESOURCE_L3);
2872 		list_for_each_entry(dom, &r->mon_domains, hdr.list)
2873 			mbm_setup_overflow_handler(dom, MBM_OVERFLOW_INTERVAL,
2874 						   RESCTRL_PICK_ANY_CPU);
2875 	}
2876 
2877 	goto out;
2878 
2879 out_psl:
2880 	rdt_pseudo_lock_release();
2881 out_mondata:
2882 	if (resctrl_arch_mon_capable())
2883 		kernfs_remove(kn_mondata);
2884 out_mongrp:
2885 	if (resctrl_arch_mon_capable()) {
2886 		rdtgroup_unassign_cntrs(&rdtgroup_default);
2887 		kernfs_remove(kn_mongrp);
2888 	}
2889 out_info:
2890 	kernfs_remove(kn_info);
2891 out_closid_exit:
2892 	closid_exit();
2893 out_schemata_free:
2894 	schemata_list_destroy();
2895 	rdt_disable_ctx();
2896 out_root:
2897 	rdtgroup_destroy_root();
2898 out:
2899 	rdt_last_cmd_clear();
2900 	mutex_unlock(&rdtgroup_mutex);
2901 	cpus_read_unlock();
2902 	return ret;
2903 }
2904 
2905 enum rdt_param {
2906 	Opt_cdp,
2907 	Opt_cdpl2,
2908 	Opt_mba_mbps,
2909 	Opt_debug,
2910 	nr__rdt_params
2911 };
2912 
2913 static const struct fs_parameter_spec rdt_fs_parameters[] = {
2914 	fsparam_flag("cdp",		Opt_cdp),
2915 	fsparam_flag("cdpl2",		Opt_cdpl2),
2916 	fsparam_flag("mba_MBps",	Opt_mba_mbps),
2917 	fsparam_flag("debug",		Opt_debug),
2918 	{}
2919 };
2920 
2921 static int rdt_parse_param(struct fs_context *fc, struct fs_parameter *param)
2922 {
2923 	struct rdt_fs_context *ctx = rdt_fc2context(fc);
2924 	struct fs_parse_result result;
2925 	const char *msg;
2926 	int opt;
2927 
2928 	opt = fs_parse(fc, rdt_fs_parameters, param, &result);
2929 	if (opt < 0)
2930 		return opt;
2931 
2932 	switch (opt) {
2933 	case Opt_cdp:
2934 		ctx->enable_cdpl3 = true;
2935 		return 0;
2936 	case Opt_cdpl2:
2937 		ctx->enable_cdpl2 = true;
2938 		return 0;
2939 	case Opt_mba_mbps:
2940 		msg = "mba_MBps requires MBM and linear scale MBA at L3 scope";
2941 		if (!supports_mba_mbps())
2942 			return invalfc(fc, msg);
2943 		ctx->enable_mba_mbps = true;
2944 		return 0;
2945 	case Opt_debug:
2946 		ctx->enable_debug = true;
2947 		return 0;
2948 	}
2949 
2950 	return -EINVAL;
2951 }
2952 
2953 static void rdt_fs_context_free(struct fs_context *fc)
2954 {
2955 	struct rdt_fs_context *ctx = rdt_fc2context(fc);
2956 
2957 	kernfs_free_fs_context(fc);
2958 	kfree(ctx);
2959 }
2960 
2961 static const struct fs_context_operations rdt_fs_context_ops = {
2962 	.free		= rdt_fs_context_free,
2963 	.parse_param	= rdt_parse_param,
2964 	.get_tree	= rdt_get_tree,
2965 };
2966 
2967 static int rdt_init_fs_context(struct fs_context *fc)
2968 {
2969 	struct rdt_fs_context *ctx;
2970 
2971 	ctx = kzalloc_obj(*ctx);
2972 	if (!ctx)
2973 		return -ENOMEM;
2974 
2975 	ctx->kfc.magic = RDTGROUP_SUPER_MAGIC;
2976 	fc->fs_private = &ctx->kfc;
2977 	fc->ops = &rdt_fs_context_ops;
2978 	put_user_ns(fc->user_ns);
2979 	fc->user_ns = get_user_ns(&init_user_ns);
2980 	fc->global = true;
2981 	return 0;
2982 }
2983 
2984 /*
2985  * Move tasks from one to the other group. If @from is NULL, then all tasks
2986  * in the systems are moved unconditionally (used for teardown).
2987  *
2988  * If @mask is not NULL the cpus on which moved tasks are running are set
2989  * in that mask so the update smp function call is restricted to affected
2990  * cpus.
2991  */
2992 static void rdt_move_group_tasks(struct rdtgroup *from, struct rdtgroup *to,
2993 				 struct cpumask *mask)
2994 {
2995 	struct task_struct *p, *t;
2996 
2997 	read_lock(&tasklist_lock);
2998 	for_each_process_thread(p, t) {
2999 		if (!from || is_closid_match(t, from) ||
3000 		    is_rmid_match(t, from)) {
3001 			resctrl_arch_set_closid_rmid(t, to->closid,
3002 						     to->mon.rmid);
3003 
3004 			/*
3005 			 * Order the closid/rmid stores above before the loads
3006 			 * in task_curr(). This pairs with the full barrier
3007 			 * between the rq->curr update and
3008 			 * resctrl_arch_sched_in() during context switch.
3009 			 */
3010 			smp_mb();
3011 
3012 			/*
3013 			 * If the task is on a CPU, set the CPU in the mask.
3014 			 * The detection is inaccurate as tasks might move or
3015 			 * schedule before the smp function call takes place.
3016 			 * In such a case the function call is pointless, but
3017 			 * there is no other side effect.
3018 			 */
3019 			if (IS_ENABLED(CONFIG_SMP) && mask && task_curr(t))
3020 				cpumask_set_cpu(task_cpu(t), mask);
3021 		}
3022 	}
3023 	read_unlock(&tasklist_lock);
3024 }
3025 
3026 static void free_all_child_rdtgrp(struct rdtgroup *rdtgrp)
3027 {
3028 	struct rdtgroup *sentry, *stmp;
3029 	struct list_head *head;
3030 
3031 	head = &rdtgrp->mon.crdtgrp_list;
3032 	list_for_each_entry_safe(sentry, stmp, head, mon.crdtgrp_list) {
3033 		rdtgroup_unassign_cntrs(sentry);
3034 		free_rmid(sentry->closid, sentry->mon.rmid);
3035 		list_del(&sentry->mon.crdtgrp_list);
3036 
3037 		if (atomic_read(&sentry->waitcount) != 0)
3038 			sentry->flags = RDT_DELETED;
3039 		else
3040 			rdtgroup_remove(sentry);
3041 	}
3042 }
3043 
3044 /*
3045  * Forcibly remove all of subdirectories under root.
3046  */
3047 static void rmdir_all_sub(void)
3048 {
3049 	struct rdtgroup *rdtgrp, *tmp;
3050 
3051 	/* Move all tasks to the default resource group */
3052 	rdt_move_group_tasks(NULL, &rdtgroup_default, NULL);
3053 
3054 	list_for_each_entry_safe(rdtgrp, tmp, &rdt_all_groups, rdtgroup_list) {
3055 		/* Free any child rmids */
3056 		free_all_child_rdtgrp(rdtgrp);
3057 
3058 		/* Remove each rdtgroup other than root */
3059 		if (rdtgrp == &rdtgroup_default)
3060 			continue;
3061 
3062 		if (rdtgrp->mode == RDT_MODE_PSEUDO_LOCKSETUP ||
3063 		    rdtgrp->mode == RDT_MODE_PSEUDO_LOCKED)
3064 			rdtgroup_pseudo_lock_remove(rdtgrp);
3065 
3066 		/*
3067 		 * Give any CPUs back to the default group. We cannot copy
3068 		 * cpu_online_mask because a CPU might have executed the
3069 		 * offline callback already, but is still marked online.
3070 		 */
3071 		cpumask_or(&rdtgroup_default.cpu_mask,
3072 			   &rdtgroup_default.cpu_mask, &rdtgrp->cpu_mask);
3073 
3074 		rdtgroup_unassign_cntrs(rdtgrp);
3075 
3076 		free_rmid(rdtgrp->closid, rdtgrp->mon.rmid);
3077 
3078 		kernfs_remove(rdtgrp->kn);
3079 		list_del(&rdtgrp->rdtgroup_list);
3080 
3081 		if (atomic_read(&rdtgrp->waitcount) != 0)
3082 			rdtgrp->flags = RDT_DELETED;
3083 		else
3084 			rdtgroup_remove(rdtgrp);
3085 	}
3086 	/* Notify online CPUs to update per cpu storage and PQR_ASSOC MSR */
3087 	update_closid_rmid(cpu_online_mask, &rdtgroup_default);
3088 
3089 	kernfs_remove(kn_info);
3090 	kernfs_remove(kn_mongrp);
3091 	kernfs_remove(kn_mondata);
3092 }
3093 
3094 /**
3095  * mon_get_kn_priv() - Get the mon_data priv data for this event.
3096  *
3097  * The same values are used across the mon_data directories of all control and
3098  * monitor groups for the same event in the same domain. Keep a list of
3099  * allocated structures and re-use an existing one with the same values for
3100  * @rid, @domid, etc.
3101  *
3102  * @rid:    The resource id for the event file being created.
3103  * @domid:  The domain id for the event file being created.
3104  * @mevt:   The type of event file being created.
3105  * @do_sum: Whether SNC summing monitors are being created. Only set
3106  *	    when @rid == RDT_RESOURCE_L3.
3107  *
3108  * Return: Pointer to mon_data private data of the event, NULL on failure.
3109  */
3110 static struct mon_data *mon_get_kn_priv(enum resctrl_res_level rid, int domid,
3111 					struct mon_evt *mevt,
3112 					bool do_sum)
3113 {
3114 	struct mon_data *priv;
3115 
3116 	lockdep_assert_held(&rdtgroup_mutex);
3117 
3118 	list_for_each_entry(priv, &mon_data_kn_priv_list, list) {
3119 		if (priv->rid == rid && priv->domid == domid &&
3120 		    priv->sum == do_sum && priv->evt == mevt)
3121 			return priv;
3122 	}
3123 
3124 	priv = kzalloc_obj(*priv);
3125 	if (!priv)
3126 		return NULL;
3127 
3128 	priv->rid = rid;
3129 	priv->domid = domid;
3130 	priv->sum = do_sum;
3131 	priv->evt = mevt;
3132 	list_add_tail(&priv->list, &mon_data_kn_priv_list);
3133 
3134 	return priv;
3135 }
3136 
3137 /**
3138  * mon_put_kn_priv() - Free all allocated mon_data structures.
3139  *
3140  * Called when resctrl file system is unmounted.
3141  */
3142 static void mon_put_kn_priv(void)
3143 {
3144 	struct mon_data *priv, *tmp;
3145 
3146 	lockdep_assert_held(&rdtgroup_mutex);
3147 
3148 	list_for_each_entry_safe(priv, tmp, &mon_data_kn_priv_list, list) {
3149 		list_del(&priv->list);
3150 		kfree(priv);
3151 	}
3152 }
3153 
3154 static void resctrl_fs_teardown(void)
3155 {
3156 	lockdep_assert_held(&rdtgroup_mutex);
3157 
3158 	/* Cleared by rdtgroup_destroy_root() */
3159 	if (!rdtgroup_default.kn)
3160 		return;
3161 
3162 	rmdir_all_sub();
3163 	rdtgroup_unassign_cntrs(&rdtgroup_default);
3164 	mon_put_kn_priv();
3165 	rdt_pseudo_lock_release();
3166 	rdtgroup_default.mode = RDT_MODE_SHAREABLE;
3167 	closid_exit();
3168 	schemata_list_destroy();
3169 	rdtgroup_destroy_root();
3170 }
3171 
3172 static void rdt_kill_sb(struct super_block *sb)
3173 {
3174 	struct rdt_resource *r;
3175 
3176 	cpus_read_lock();
3177 	mutex_lock(&rdtgroup_mutex);
3178 
3179 	rdt_disable_ctx();
3180 
3181 	/* Put everything back to default values. */
3182 	for_each_alloc_capable_rdt_resource(r)
3183 		resctrl_arch_reset_all_ctrls(r);
3184 
3185 	resctrl_fs_teardown();
3186 	if (resctrl_arch_alloc_capable())
3187 		resctrl_arch_disable_alloc();
3188 	if (resctrl_arch_mon_capable())
3189 		resctrl_arch_disable_mon();
3190 	resctrl_mounted = false;
3191 	kernfs_kill_sb(sb);
3192 	mutex_unlock(&rdtgroup_mutex);
3193 	cpus_read_unlock();
3194 }
3195 
3196 static struct file_system_type rdt_fs_type = {
3197 	.name			= "resctrl",
3198 	.init_fs_context	= rdt_init_fs_context,
3199 	.parameters		= rdt_fs_parameters,
3200 	.kill_sb		= rdt_kill_sb,
3201 };
3202 
3203 static int mon_addfile(struct kernfs_node *parent_kn, const char *name,
3204 		       void *priv)
3205 {
3206 	struct kernfs_node *kn;
3207 	int ret = 0;
3208 
3209 	kn = __kernfs_create_file(parent_kn, name, 0444,
3210 				  GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, 0,
3211 				  &kf_mondata_ops, priv, NULL, NULL);
3212 	if (IS_ERR(kn))
3213 		return PTR_ERR(kn);
3214 
3215 	ret = rdtgroup_kn_set_ugid(kn);
3216 	if (ret) {
3217 		kernfs_remove(kn);
3218 		return ret;
3219 	}
3220 
3221 	return ret;
3222 }
3223 
3224 static void mon_rmdir_one_subdir(struct kernfs_node *pkn, char *name, char *subname)
3225 {
3226 	struct kernfs_node *kn;
3227 
3228 	kn = kernfs_find_and_get(pkn, name);
3229 	if (!kn)
3230 		return;
3231 	kernfs_put(kn);
3232 
3233 	if (kn->dir.subdirs <= 1)
3234 		kernfs_remove(kn);
3235 	else
3236 		kernfs_remove_by_name(kn, subname);
3237 }
3238 
3239 /*
3240  * Remove files and directories for one SNC node. If it is the last node
3241  * sharing an L3 cache, then remove the upper level directory containing
3242  * the "sum" files too.
3243  */
3244 static void rmdir_mondata_subdir_allrdtgrp_snc(struct rdt_resource *r,
3245 					       struct rdt_domain_hdr *hdr)
3246 {
3247 	struct rdtgroup *prgrp, *crgrp;
3248 	struct rdt_l3_mon_domain *d;
3249 	char subname[32];
3250 	char name[32];
3251 
3252 	if (!domain_header_is_valid(hdr, RESCTRL_MON_DOMAIN, RDT_RESOURCE_L3))
3253 		return;
3254 
3255 	d = container_of(hdr, struct rdt_l3_mon_domain, hdr);
3256 	sprintf(name, "mon_%s_%02d", r->name, d->ci_id);
3257 	sprintf(subname, "mon_sub_%s_%02d", r->name, hdr->id);
3258 
3259 	list_for_each_entry(prgrp, &rdt_all_groups, rdtgroup_list) {
3260 		mon_rmdir_one_subdir(prgrp->mon.mon_data_kn, name, subname);
3261 
3262 		list_for_each_entry(crgrp, &prgrp->mon.crdtgrp_list, mon.crdtgrp_list)
3263 			mon_rmdir_one_subdir(crgrp->mon.mon_data_kn, name, subname);
3264 	}
3265 }
3266 
3267 /*
3268  * Remove all subdirectories of mon_data of ctrl_mon groups
3269  * and monitor groups for the given domain.
3270  */
3271 static void rmdir_mondata_subdir_allrdtgrp(struct rdt_resource *r,
3272 					   struct rdt_domain_hdr *hdr)
3273 {
3274 	struct rdtgroup *prgrp, *crgrp;
3275 	char name[32];
3276 
3277 	if (r->rid == RDT_RESOURCE_L3 && r->mon_scope == RESCTRL_L3_NODE) {
3278 		rmdir_mondata_subdir_allrdtgrp_snc(r, hdr);
3279 		return;
3280 	}
3281 
3282 	sprintf(name, "mon_%s_%02d", r->name, hdr->id);
3283 	list_for_each_entry(prgrp, &rdt_all_groups, rdtgroup_list) {
3284 		kernfs_remove_by_name(prgrp->mon.mon_data_kn, name);
3285 
3286 		list_for_each_entry(crgrp, &prgrp->mon.crdtgrp_list, mon.crdtgrp_list)
3287 			kernfs_remove_by_name(crgrp->mon.mon_data_kn, name);
3288 	}
3289 }
3290 
3291 /*
3292  * Create a directory for a domain and populate it with monitor files. Create
3293  * summing monitors when @hdr is NULL. No need to initialize summing monitors.
3294  */
3295 static struct kernfs_node *_mkdir_mondata_subdir(struct kernfs_node *parent_kn, char *name,
3296 						 struct rdt_domain_hdr *hdr,
3297 						 struct rdt_resource *r,
3298 						 struct rdtgroup *prgrp, int domid)
3299 {
3300 	struct rmid_read rr = {0};
3301 	struct kernfs_node *kn;
3302 	struct mon_data *priv;
3303 	struct mon_evt *mevt;
3304 	int ret;
3305 
3306 	kn = kernfs_create_dir(parent_kn, name, parent_kn->mode, prgrp);
3307 	if (IS_ERR(kn))
3308 		return kn;
3309 
3310 	ret = rdtgroup_kn_set_ugid(kn);
3311 	if (ret)
3312 		goto out_destroy;
3313 
3314 	for_each_mon_event(mevt) {
3315 		if (mevt->rid != r->rid || !mevt->enabled)
3316 			continue;
3317 		priv = mon_get_kn_priv(r->rid, domid, mevt, !hdr);
3318 		if (WARN_ON_ONCE(!priv)) {
3319 			ret = -EINVAL;
3320 			goto out_destroy;
3321 		}
3322 
3323 		ret = mon_addfile(kn, mevt->name, priv);
3324 		if (ret)
3325 			goto out_destroy;
3326 
3327 		if (hdr && resctrl_is_mbm_event(mevt->evtid))
3328 			mon_event_read(&rr, r, hdr, prgrp, &hdr->cpu_mask, mevt, true);
3329 	}
3330 
3331 	return kn;
3332 out_destroy:
3333 	kernfs_remove(kn);
3334 	return ERR_PTR(ret);
3335 }
3336 
3337 static int mkdir_mondata_subdir_snc(struct kernfs_node *parent_kn,
3338 				    struct rdt_domain_hdr *hdr,
3339 				    struct rdt_resource *r, struct rdtgroup *prgrp)
3340 {
3341 	struct kernfs_node *ckn, *kn;
3342 	struct rdt_l3_mon_domain *d;
3343 	char name[32];
3344 
3345 	if (!domain_header_is_valid(hdr, RESCTRL_MON_DOMAIN, RDT_RESOURCE_L3))
3346 		return -EINVAL;
3347 
3348 	d = container_of(hdr, struct rdt_l3_mon_domain, hdr);
3349 	sprintf(name, "mon_%s_%02d", r->name, d->ci_id);
3350 	kn = kernfs_find_and_get(parent_kn, name);
3351 	if (kn) {
3352 		/*
3353 		 * rdtgroup_mutex will prevent this directory from being
3354 		 * removed. No need to keep this hold.
3355 		 */
3356 		kernfs_put(kn);
3357 	} else {
3358 		kn = _mkdir_mondata_subdir(parent_kn, name, NULL, r, prgrp, d->ci_id);
3359 		if (IS_ERR(kn))
3360 			return PTR_ERR(kn);
3361 	}
3362 
3363 	sprintf(name, "mon_sub_%s_%02d", r->name, hdr->id);
3364 	ckn = _mkdir_mondata_subdir(kn, name, hdr, r, prgrp, hdr->id);
3365 	if (IS_ERR(ckn)) {
3366 		kernfs_remove(kn);
3367 		return PTR_ERR(ckn);
3368 	}
3369 
3370 	kernfs_activate(kn);
3371 	return 0;
3372 }
3373 
3374 static int mkdir_mondata_subdir(struct kernfs_node *parent_kn,
3375 				struct rdt_domain_hdr *hdr,
3376 				struct rdt_resource *r, struct rdtgroup *prgrp)
3377 {
3378 	struct kernfs_node *kn;
3379 	char name[32];
3380 
3381 	lockdep_assert_held(&rdtgroup_mutex);
3382 
3383 	if (r->rid == RDT_RESOURCE_L3 && r->mon_scope == RESCTRL_L3_NODE)
3384 		return mkdir_mondata_subdir_snc(parent_kn, hdr, r, prgrp);
3385 
3386 	sprintf(name, "mon_%s_%02d", r->name, hdr->id);
3387 	kn = _mkdir_mondata_subdir(parent_kn, name, hdr, r, prgrp, hdr->id);
3388 	if (IS_ERR(kn))
3389 		return PTR_ERR(kn);
3390 
3391 	kernfs_activate(kn);
3392 	return 0;
3393 }
3394 
3395 /*
3396  * Add all subdirectories of mon_data for "ctrl_mon" groups
3397  * and "monitor" groups with given domain id.
3398  */
3399 static void mkdir_mondata_subdir_allrdtgrp(struct rdt_resource *r,
3400 					   struct rdt_domain_hdr *hdr)
3401 {
3402 	struct kernfs_node *parent_kn;
3403 	struct rdtgroup *prgrp, *crgrp;
3404 	struct list_head *head;
3405 
3406 	list_for_each_entry(prgrp, &rdt_all_groups, rdtgroup_list) {
3407 		parent_kn = prgrp->mon.mon_data_kn;
3408 		mkdir_mondata_subdir(parent_kn, hdr, r, prgrp);
3409 
3410 		head = &prgrp->mon.crdtgrp_list;
3411 		list_for_each_entry(crgrp, head, mon.crdtgrp_list) {
3412 			parent_kn = crgrp->mon.mon_data_kn;
3413 			mkdir_mondata_subdir(parent_kn, hdr, r, crgrp);
3414 		}
3415 	}
3416 }
3417 
3418 static int mkdir_mondata_subdir_alldom(struct kernfs_node *parent_kn,
3419 				       struct rdt_resource *r,
3420 				       struct rdtgroup *prgrp)
3421 {
3422 	struct rdt_domain_hdr *hdr;
3423 	int ret;
3424 
3425 	/* Walking r->domains, ensure it can't race with cpuhp */
3426 	lockdep_assert_cpus_held();
3427 
3428 	list_for_each_entry(hdr, &r->mon_domains, list) {
3429 		ret = mkdir_mondata_subdir(parent_kn, hdr, r, prgrp);
3430 		if (ret)
3431 			return ret;
3432 	}
3433 
3434 	return 0;
3435 }
3436 
3437 /*
3438  * This creates a directory mon_data which contains the monitored data.
3439  *
3440  * mon_data has one directory for each domain which are named
3441  * in the format mon_<domain_name>_<domain_id>. For ex: A mon_data
3442  * with L3 domain looks as below:
3443  * ./mon_data:
3444  * mon_L3_00
3445  * mon_L3_01
3446  * mon_L3_02
3447  * ...
3448  *
3449  * Each domain directory has one file per event:
3450  * ./mon_L3_00/:
3451  * llc_occupancy
3452  *
3453  */
3454 static int mkdir_mondata_all(struct kernfs_node *parent_kn,
3455 			     struct rdtgroup *prgrp,
3456 			     struct kernfs_node **dest_kn)
3457 {
3458 	struct rdt_resource *r;
3459 	struct kernfs_node *kn;
3460 	int ret;
3461 
3462 	/*
3463 	 * Create the mon_data directory first.
3464 	 */
3465 	ret = mongroup_create_dir(parent_kn, prgrp, "mon_data", &kn);
3466 	if (ret)
3467 		return ret;
3468 
3469 	if (dest_kn)
3470 		*dest_kn = kn;
3471 
3472 	/*
3473 	 * Create the subdirectories for each domain. Note that all events
3474 	 * in a domain like L3 are grouped into a resource whose domain is L3
3475 	 */
3476 	for_each_mon_capable_rdt_resource(r) {
3477 		ret = mkdir_mondata_subdir_alldom(kn, r, prgrp);
3478 		if (ret)
3479 			goto out_destroy;
3480 	}
3481 
3482 	return 0;
3483 
3484 out_destroy:
3485 	kernfs_remove(kn);
3486 	return ret;
3487 }
3488 
3489 /**
3490  * cbm_ensure_valid - Enforce validity on provided CBM
3491  * @_val:	Candidate CBM
3492  * @r:		RDT resource to which the CBM belongs
3493  *
3494  * The provided CBM represents all cache portions available for use. This
3495  * may be represented by a bitmap that does not consist of contiguous ones
3496  * and thus be an invalid CBM.
3497  * Here the provided CBM is forced to be a valid CBM by only considering
3498  * the first set of contiguous bits as valid and clearing all bits.
3499  * The intention here is to provide a valid default CBM with which a new
3500  * resource group is initialized. The user can follow this with a
3501  * modification to the CBM if the default does not satisfy the
3502  * requirements.
3503  *
3504  * Return: A CBM that is valid for resource @r.
3505  */
3506 static u32 cbm_ensure_valid(u32 _val, struct rdt_resource *r)
3507 {
3508 	unsigned int cbm_len = r->cache.cbm_len;
3509 	unsigned long first_bit, zero_bit;
3510 	unsigned long val;
3511 
3512 	if (!_val || r->cache.arch_has_sparse_bitmasks)
3513 		return _val;
3514 
3515 	val = _val;
3516 	first_bit = find_first_bit(&val, cbm_len);
3517 	zero_bit = find_next_zero_bit(&val, cbm_len, first_bit);
3518 
3519 	/* Clear any remaining bits to ensure contiguous region */
3520 	bitmap_clear(&val, zero_bit, cbm_len - zero_bit);
3521 	return (u32)val;
3522 }
3523 
3524 /*
3525  * Initialize cache resources per RDT domain
3526  *
3527  * Set the RDT domain up to start off with all usable allocations. That is,
3528  * all shareable and unused bits. All-zero CBM is invalid.
3529  */
3530 static int __init_one_rdt_domain(struct rdt_ctrl_domain *d, struct resctrl_schema *s,
3531 				 u32 closid)
3532 {
3533 	enum resctrl_conf_type peer_type = resctrl_peer_type(s->conf_type);
3534 	enum resctrl_conf_type t = s->conf_type;
3535 	struct resctrl_staged_config *cfg;
3536 	struct rdt_resource *r = s->res;
3537 	u32 used_b = 0, unused_b = 0;
3538 	unsigned long tmp_cbm;
3539 	enum rdtgrp_mode mode;
3540 	u32 peer_ctl, ctrl_val;
3541 	int i;
3542 
3543 	cfg = &d->staged_config[t];
3544 	cfg->have_new_ctrl = false;
3545 	cfg->new_ctrl = r->cache.shareable_bits;
3546 	used_b = r->cache.shareable_bits;
3547 	for (i = 0; i < closids_supported(); i++) {
3548 		if (closid_allocated(i) && i != closid) {
3549 			mode = rdtgroup_mode_by_closid(i);
3550 			if (mode == RDT_MODE_PSEUDO_LOCKSETUP)
3551 				/*
3552 				 * ctrl values for locksetup aren't relevant
3553 				 * until the schemata is written, and the mode
3554 				 * becomes RDT_MODE_PSEUDO_LOCKED.
3555 				 */
3556 				continue;
3557 			/*
3558 			 * If CDP is active include peer domain's
3559 			 * usage to ensure there is no overlap
3560 			 * with an exclusive group.
3561 			 */
3562 			if (resctrl_arch_get_cdp_enabled(r->rid))
3563 				peer_ctl = resctrl_arch_get_config(r, d, i,
3564 								   peer_type);
3565 			else
3566 				peer_ctl = 0;
3567 			ctrl_val = resctrl_arch_get_config(r, d, i,
3568 							   s->conf_type);
3569 			used_b |= ctrl_val | peer_ctl;
3570 			if (mode == RDT_MODE_SHAREABLE)
3571 				cfg->new_ctrl |= ctrl_val | peer_ctl;
3572 		}
3573 	}
3574 	if (d->plr && d->plr->cbm > 0)
3575 		used_b |= d->plr->cbm;
3576 	unused_b = used_b ^ (BIT_MASK(r->cache.cbm_len) - 1);
3577 	unused_b &= BIT_MASK(r->cache.cbm_len) - 1;
3578 	cfg->new_ctrl |= unused_b;
3579 	/*
3580 	 * Force the initial CBM to be valid, user can
3581 	 * modify the CBM based on system availability.
3582 	 */
3583 	cfg->new_ctrl = cbm_ensure_valid(cfg->new_ctrl, r);
3584 	/*
3585 	 * Assign the u32 CBM to an unsigned long to ensure that
3586 	 * bitmap_weight() does not access out-of-bound memory.
3587 	 */
3588 	tmp_cbm = cfg->new_ctrl;
3589 	if (bitmap_weight(&tmp_cbm, r->cache.cbm_len) < r->cache.min_cbm_bits) {
3590 		rdt_last_cmd_printf("No space on %s:%d\n", s->name, d->hdr.id);
3591 		return -ENOSPC;
3592 	}
3593 	cfg->have_new_ctrl = true;
3594 
3595 	return 0;
3596 }
3597 
3598 /*
3599  * Initialize cache resources with default values.
3600  *
3601  * A new RDT group is being created on an allocation capable (CAT)
3602  * supporting system. Set this group up to start off with all usable
3603  * allocations.
3604  *
3605  * If there are no more shareable bits available on any domain then
3606  * the entire allocation will fail.
3607  */
3608 int rdtgroup_init_cat(struct resctrl_schema *s, u32 closid)
3609 {
3610 	struct rdt_ctrl_domain *d;
3611 	int ret;
3612 
3613 	list_for_each_entry(d, &s->res->ctrl_domains, hdr.list) {
3614 		ret = __init_one_rdt_domain(d, s, closid);
3615 		if (ret < 0)
3616 			return ret;
3617 	}
3618 
3619 	return 0;
3620 }
3621 
3622 /* Initialize MBA resource with default values. */
3623 static void rdtgroup_init_mba(struct rdt_resource *r, u32 closid)
3624 {
3625 	struct resctrl_staged_config *cfg;
3626 	struct rdt_ctrl_domain *d;
3627 
3628 	list_for_each_entry(d, &r->ctrl_domains, hdr.list) {
3629 		if (is_mba_sc(r)) {
3630 			d->mbps_val[closid] = MBA_MAX_MBPS;
3631 			continue;
3632 		}
3633 
3634 		cfg = &d->staged_config[CDP_NONE];
3635 		cfg->new_ctrl = resctrl_get_default_ctrl(r);
3636 		cfg->have_new_ctrl = true;
3637 	}
3638 }
3639 
3640 /* Initialize the RDT group's allocations. */
3641 static int rdtgroup_init_alloc(struct rdtgroup *rdtgrp)
3642 {
3643 	struct resctrl_schema *s;
3644 	struct rdt_resource *r;
3645 	int ret = 0;
3646 
3647 	rdt_staged_configs_clear();
3648 
3649 	list_for_each_entry(s, &resctrl_schema_all, list) {
3650 		r = s->res;
3651 		if (r->rid == RDT_RESOURCE_MBA ||
3652 		    r->rid == RDT_RESOURCE_SMBA) {
3653 			rdtgroup_init_mba(r, rdtgrp->closid);
3654 			if (is_mba_sc(r))
3655 				continue;
3656 		} else {
3657 			ret = rdtgroup_init_cat(s, rdtgrp->closid);
3658 			if (ret < 0)
3659 				goto out;
3660 		}
3661 
3662 		ret = resctrl_arch_update_domains(r, rdtgrp->closid);
3663 		if (ret < 0) {
3664 			rdt_last_cmd_puts("Failed to initialize allocations\n");
3665 			goto out;
3666 		}
3667 	}
3668 
3669 	rdtgrp->mode = RDT_MODE_SHAREABLE;
3670 
3671 out:
3672 	rdt_staged_configs_clear();
3673 	return ret;
3674 }
3675 
3676 static int mkdir_rdt_prepare_rmid_alloc(struct rdtgroup *rdtgrp)
3677 {
3678 	int ret;
3679 
3680 	if (!resctrl_arch_mon_capable())
3681 		return 0;
3682 
3683 	ret = alloc_rmid(rdtgrp->closid);
3684 	if (ret < 0) {
3685 		rdt_last_cmd_puts("Out of RMIDs\n");
3686 		return ret;
3687 	}
3688 	rdtgrp->mon.rmid = ret;
3689 
3690 	rdtgroup_assign_cntrs(rdtgrp);
3691 
3692 	ret = mkdir_mondata_all(rdtgrp->kn, rdtgrp, &rdtgrp->mon.mon_data_kn);
3693 	if (ret) {
3694 		rdt_last_cmd_puts("kernfs subdir error\n");
3695 		rdtgroup_unassign_cntrs(rdtgrp);
3696 		free_rmid(rdtgrp->closid, rdtgrp->mon.rmid);
3697 		return ret;
3698 	}
3699 
3700 	return 0;
3701 }
3702 
3703 static void mkdir_rdt_prepare_rmid_free(struct rdtgroup *rgrp)
3704 {
3705 	if (resctrl_arch_mon_capable()) {
3706 		rdtgroup_unassign_cntrs(rgrp);
3707 		free_rmid(rgrp->closid, rgrp->mon.rmid);
3708 	}
3709 }
3710 
3711 /*
3712  * We allow creating mon groups only with in a directory called "mon_groups"
3713  * which is present in every ctrl_mon group. Check if this is a valid
3714  * "mon_groups" directory.
3715  *
3716  * 1. The directory should be named "mon_groups".
3717  * 2. The mon group itself should "not" be named "mon_groups".
3718  *   This makes sure "mon_groups" directory always has a ctrl_mon group
3719  *   as parent.
3720  */
3721 static bool is_mon_groups(struct kernfs_node *kn, const char *name)
3722 {
3723 	return (!strcmp(rdt_kn_name(kn), "mon_groups") &&
3724 		strcmp(name, "mon_groups"));
3725 }
3726 
3727 static int mkdir_rdt_prepare(struct kernfs_node *parent_kn,
3728 			     const char *name, umode_t mode,
3729 			     enum rdt_group_type rtype, struct rdtgroup **r)
3730 {
3731 	struct rdtgroup *prdtgrp, *rdtgrp;
3732 	unsigned long files = 0;
3733 	struct kernfs_node *kn;
3734 	int ret;
3735 
3736 	prdtgrp = rdtgroup_kn_lock_live(parent_kn);
3737 	if (!prdtgrp) {
3738 		ret = -ENODEV;
3739 		goto out_unlock;
3740 	}
3741 
3742 	rdt_last_cmd_clear();
3743 
3744 	/*
3745 	 * Check that the parent directory for a monitor group is a "mon_groups"
3746 	 * directory.
3747 	 */
3748 	if (rtype == RDTMON_GROUP && !is_mon_groups(parent_kn, name)) {
3749 		ret = -EPERM;
3750 		goto out_unlock;
3751 	}
3752 
3753 	if (rtype == RDTMON_GROUP &&
3754 	    (prdtgrp->mode == RDT_MODE_PSEUDO_LOCKSETUP ||
3755 	     prdtgrp->mode == RDT_MODE_PSEUDO_LOCKED)) {
3756 		ret = -EINVAL;
3757 		rdt_last_cmd_puts("Pseudo-locking in progress\n");
3758 		goto out_unlock;
3759 	}
3760 
3761 	/* allocate the rdtgroup. */
3762 	rdtgrp = kzalloc_obj(*rdtgrp);
3763 	if (!rdtgrp) {
3764 		ret = -ENOSPC;
3765 		rdt_last_cmd_puts("Kernel out of memory\n");
3766 		goto out_unlock;
3767 	}
3768 	*r = rdtgrp;
3769 	rdtgrp->mon.parent = prdtgrp;
3770 	rdtgrp->type = rtype;
3771 	INIT_LIST_HEAD(&rdtgrp->mon.crdtgrp_list);
3772 
3773 	/* kernfs creates the directory for rdtgrp */
3774 	kn = kernfs_create_dir(parent_kn, name, mode, rdtgrp);
3775 	if (IS_ERR(kn)) {
3776 		ret = PTR_ERR(kn);
3777 		rdt_last_cmd_puts("kernfs create error\n");
3778 		goto out_free_rgrp;
3779 	}
3780 	rdtgrp->kn = kn;
3781 
3782 	/*
3783 	 * kernfs_remove() will drop the reference count on "kn" which
3784 	 * will free it. But we still need it to stick around for the
3785 	 * rdtgroup_kn_unlock(kn) call. Take one extra reference here,
3786 	 * which will be dropped by kernfs_put() in rdtgroup_remove().
3787 	 */
3788 	kernfs_get(kn);
3789 
3790 	ret = rdtgroup_kn_set_ugid(kn);
3791 	if (ret) {
3792 		rdt_last_cmd_puts("kernfs perm error\n");
3793 		goto out_destroy;
3794 	}
3795 
3796 	if (rtype == RDTCTRL_GROUP) {
3797 		files = RFTYPE_BASE | RFTYPE_CTRL;
3798 		if (resctrl_arch_mon_capable())
3799 			files |= RFTYPE_MON;
3800 	} else {
3801 		files = RFTYPE_BASE | RFTYPE_MON;
3802 	}
3803 
3804 	ret = rdtgroup_add_files(kn, files);
3805 	if (ret) {
3806 		rdt_last_cmd_puts("kernfs fill error\n");
3807 		goto out_destroy;
3808 	}
3809 
3810 	/*
3811 	 * The caller unlocks the parent_kn upon success.
3812 	 */
3813 	return 0;
3814 
3815 out_destroy:
3816 	kernfs_put(rdtgrp->kn);
3817 	kernfs_remove(rdtgrp->kn);
3818 out_free_rgrp:
3819 	kfree(rdtgrp);
3820 out_unlock:
3821 	rdtgroup_kn_unlock(parent_kn);
3822 	return ret;
3823 }
3824 
3825 static void mkdir_rdt_prepare_clean(struct rdtgroup *rgrp)
3826 {
3827 	kernfs_remove(rgrp->kn);
3828 	rdtgroup_remove(rgrp);
3829 }
3830 
3831 /*
3832  * Create a monitor group under "mon_groups" directory of a control
3833  * and monitor group(ctrl_mon). This is a resource group
3834  * to monitor a subset of tasks and cpus in its parent ctrl_mon group.
3835  */
3836 static int rdtgroup_mkdir_mon(struct kernfs_node *parent_kn,
3837 			      const char *name, umode_t mode)
3838 {
3839 	struct rdtgroup *rdtgrp, *prgrp;
3840 	int ret;
3841 
3842 	ret = mkdir_rdt_prepare(parent_kn, name, mode, RDTMON_GROUP, &rdtgrp);
3843 	if (ret)
3844 		return ret;
3845 
3846 	prgrp = rdtgrp->mon.parent;
3847 	rdtgrp->closid = prgrp->closid;
3848 
3849 	ret = mkdir_rdt_prepare_rmid_alloc(rdtgrp);
3850 	if (ret) {
3851 		mkdir_rdt_prepare_clean(rdtgrp);
3852 		goto out_unlock;
3853 	}
3854 
3855 	kernfs_activate(rdtgrp->kn);
3856 
3857 	/*
3858 	 * Add the rdtgrp to the list of rdtgrps the parent
3859 	 * ctrl_mon group has to track.
3860 	 */
3861 	list_add_tail(&rdtgrp->mon.crdtgrp_list, &prgrp->mon.crdtgrp_list);
3862 
3863 out_unlock:
3864 	rdtgroup_kn_unlock(parent_kn);
3865 	return ret;
3866 }
3867 
3868 /*
3869  * These are rdtgroups created under the root directory. Can be used
3870  * to allocate and monitor resources.
3871  */
3872 static int rdtgroup_mkdir_ctrl_mon(struct kernfs_node *parent_kn,
3873 				   const char *name, umode_t mode)
3874 {
3875 	struct rdtgroup *rdtgrp;
3876 	struct kernfs_node *kn;
3877 	u32 closid;
3878 	int ret;
3879 
3880 	ret = mkdir_rdt_prepare(parent_kn, name, mode, RDTCTRL_GROUP, &rdtgrp);
3881 	if (ret)
3882 		return ret;
3883 
3884 	kn = rdtgrp->kn;
3885 	ret = closid_alloc();
3886 	if (ret < 0) {
3887 		rdt_last_cmd_puts("Out of CLOSIDs\n");
3888 		goto out_common_fail;
3889 	}
3890 	closid = ret;
3891 	ret = 0;
3892 
3893 	rdtgrp->closid = closid;
3894 
3895 	ret = mkdir_rdt_prepare_rmid_alloc(rdtgrp);
3896 	if (ret)
3897 		goto out_closid_free;
3898 
3899 	kernfs_activate(rdtgrp->kn);
3900 
3901 	ret = rdtgroup_init_alloc(rdtgrp);
3902 	if (ret < 0)
3903 		goto out_rmid_free;
3904 
3905 	list_add(&rdtgrp->rdtgroup_list, &rdt_all_groups);
3906 
3907 	if (resctrl_arch_mon_capable()) {
3908 		/*
3909 		 * Create an empty mon_groups directory to hold the subset
3910 		 * of tasks and cpus to monitor.
3911 		 */
3912 		ret = mongroup_create_dir(kn, rdtgrp, "mon_groups", NULL);
3913 		if (ret) {
3914 			rdt_last_cmd_puts("kernfs subdir error\n");
3915 			goto out_del_list;
3916 		}
3917 		if (is_mba_sc(NULL))
3918 			rdtgrp->mba_mbps_event = mba_mbps_default_event;
3919 	}
3920 
3921 	goto out_unlock;
3922 
3923 out_del_list:
3924 	list_del(&rdtgrp->rdtgroup_list);
3925 out_rmid_free:
3926 	mkdir_rdt_prepare_rmid_free(rdtgrp);
3927 out_closid_free:
3928 	closid_free(closid);
3929 out_common_fail:
3930 	mkdir_rdt_prepare_clean(rdtgrp);
3931 out_unlock:
3932 	rdtgroup_kn_unlock(parent_kn);
3933 	return ret;
3934 }
3935 
3936 static int rdtgroup_mkdir(struct kernfs_node *parent_kn, const char *name,
3937 			  umode_t mode)
3938 {
3939 	/* Do not accept '\n' to avoid unparsable situation. */
3940 	if (strchr(name, '\n'))
3941 		return -EINVAL;
3942 
3943 	/*
3944 	 * If the parent directory is the root directory and RDT
3945 	 * allocation is supported, add a control and monitoring
3946 	 * subdirectory
3947 	 */
3948 	if (resctrl_arch_alloc_capable() && parent_kn == rdtgroup_default.kn)
3949 		return rdtgroup_mkdir_ctrl_mon(parent_kn, name, mode);
3950 
3951 	/* Else, attempt to add a monitoring subdirectory. */
3952 	if (resctrl_arch_mon_capable())
3953 		return rdtgroup_mkdir_mon(parent_kn, name, mode);
3954 
3955 	return -EPERM;
3956 }
3957 
3958 static int rdtgroup_rmdir_mon(struct rdtgroup *rdtgrp, cpumask_var_t tmpmask)
3959 {
3960 	struct rdtgroup *prdtgrp = rdtgrp->mon.parent;
3961 	u32 closid, rmid;
3962 	int cpu;
3963 
3964 	/* Give any tasks back to the parent group */
3965 	rdt_move_group_tasks(rdtgrp, prdtgrp, tmpmask);
3966 
3967 	/*
3968 	 * Update per cpu closid/rmid of the moved CPUs first.
3969 	 * Note: the closid will not change, but the arch code still needs it.
3970 	 */
3971 	closid = prdtgrp->closid;
3972 	rmid = prdtgrp->mon.rmid;
3973 	for_each_cpu(cpu, &rdtgrp->cpu_mask)
3974 		resctrl_arch_set_cpu_default_closid_rmid(cpu, closid, rmid);
3975 
3976 	/*
3977 	 * Update the MSR on moved CPUs and CPUs which have moved
3978 	 * task running on them.
3979 	 */
3980 	cpumask_or(tmpmask, tmpmask, &rdtgrp->cpu_mask);
3981 	update_closid_rmid(tmpmask, NULL);
3982 
3983 	rdtgrp->flags = RDT_DELETED;
3984 
3985 	rdtgroup_unassign_cntrs(rdtgrp);
3986 
3987 	free_rmid(rdtgrp->closid, rdtgrp->mon.rmid);
3988 
3989 	/*
3990 	 * Remove the rdtgrp from the parent ctrl_mon group's list
3991 	 */
3992 	WARN_ON(list_empty(&prdtgrp->mon.crdtgrp_list));
3993 	list_del(&rdtgrp->mon.crdtgrp_list);
3994 
3995 	kernfs_remove(rdtgrp->kn);
3996 
3997 	return 0;
3998 }
3999 
4000 static int rdtgroup_ctrl_remove(struct rdtgroup *rdtgrp)
4001 {
4002 	rdtgrp->flags = RDT_DELETED;
4003 	list_del(&rdtgrp->rdtgroup_list);
4004 
4005 	kernfs_remove(rdtgrp->kn);
4006 	return 0;
4007 }
4008 
4009 static int rdtgroup_rmdir_ctrl(struct rdtgroup *rdtgrp, cpumask_var_t tmpmask)
4010 {
4011 	u32 closid, rmid;
4012 	int cpu;
4013 
4014 	/* Give any tasks back to the default group */
4015 	rdt_move_group_tasks(rdtgrp, &rdtgroup_default, tmpmask);
4016 
4017 	/* Give any CPUs back to the default group */
4018 	cpumask_or(&rdtgroup_default.cpu_mask,
4019 		   &rdtgroup_default.cpu_mask, &rdtgrp->cpu_mask);
4020 
4021 	/* Update per cpu closid and rmid of the moved CPUs first */
4022 	closid = rdtgroup_default.closid;
4023 	rmid = rdtgroup_default.mon.rmid;
4024 	for_each_cpu(cpu, &rdtgrp->cpu_mask)
4025 		resctrl_arch_set_cpu_default_closid_rmid(cpu, closid, rmid);
4026 
4027 	/*
4028 	 * Update the MSR on moved CPUs and CPUs which have moved
4029 	 * task running on them.
4030 	 */
4031 	cpumask_or(tmpmask, tmpmask, &rdtgrp->cpu_mask);
4032 	update_closid_rmid(tmpmask, NULL);
4033 
4034 	rdtgroup_unassign_cntrs(rdtgrp);
4035 
4036 	free_rmid(rdtgrp->closid, rdtgrp->mon.rmid);
4037 	closid_free(rdtgrp->closid);
4038 
4039 	rdtgroup_ctrl_remove(rdtgrp);
4040 
4041 	/*
4042 	 * Free all the child monitor group rmids.
4043 	 */
4044 	free_all_child_rdtgrp(rdtgrp);
4045 
4046 	return 0;
4047 }
4048 
4049 static struct kernfs_node *rdt_kn_parent(struct kernfs_node *kn)
4050 {
4051 	/*
4052 	 * Valid within the RCU section it was obtained or while rdtgroup_mutex
4053 	 * is held.
4054 	 */
4055 	return rcu_dereference_check(kn->__parent, lockdep_is_held(&rdtgroup_mutex));
4056 }
4057 
4058 static int rdtgroup_rmdir(struct kernfs_node *kn)
4059 {
4060 	struct kernfs_node *parent_kn;
4061 	struct rdtgroup *rdtgrp;
4062 	cpumask_var_t tmpmask;
4063 	int ret = 0;
4064 
4065 	if (!zalloc_cpumask_var(&tmpmask, GFP_KERNEL))
4066 		return -ENOMEM;
4067 
4068 	rdtgrp = rdtgroup_kn_lock_live(kn);
4069 	if (!rdtgrp) {
4070 		ret = -EPERM;
4071 		goto out;
4072 	}
4073 	parent_kn = rdt_kn_parent(kn);
4074 
4075 	/*
4076 	 * If the rdtgroup is a ctrl_mon group and parent directory
4077 	 * is the root directory, remove the ctrl_mon group.
4078 	 *
4079 	 * If the rdtgroup is a mon group and parent directory
4080 	 * is a valid "mon_groups" directory, remove the mon group.
4081 	 */
4082 	if (rdtgrp->type == RDTCTRL_GROUP && parent_kn == rdtgroup_default.kn &&
4083 	    rdtgrp != &rdtgroup_default) {
4084 		if (rdtgrp->mode == RDT_MODE_PSEUDO_LOCKSETUP ||
4085 		    rdtgrp->mode == RDT_MODE_PSEUDO_LOCKED) {
4086 			ret = rdtgroup_ctrl_remove(rdtgrp);
4087 		} else {
4088 			ret = rdtgroup_rmdir_ctrl(rdtgrp, tmpmask);
4089 		}
4090 	} else if (rdtgrp->type == RDTMON_GROUP &&
4091 		 is_mon_groups(parent_kn, rdt_kn_name(kn))) {
4092 		ret = rdtgroup_rmdir_mon(rdtgrp, tmpmask);
4093 	} else {
4094 		ret = -EPERM;
4095 	}
4096 
4097 out:
4098 	rdtgroup_kn_unlock(kn);
4099 	free_cpumask_var(tmpmask);
4100 	return ret;
4101 }
4102 
4103 /**
4104  * mongrp_reparent() - replace parent CTRL_MON group of a MON group
4105  * @rdtgrp:		the MON group whose parent should be replaced
4106  * @new_prdtgrp:	replacement parent CTRL_MON group for @rdtgrp
4107  * @cpus:		cpumask provided by the caller for use during this call
4108  *
4109  * Replaces the parent CTRL_MON group for a MON group, resulting in all member
4110  * tasks' CLOSID immediately changing to that of the new parent group.
4111  * Monitoring data for the group is unaffected by this operation.
4112  */
4113 static void mongrp_reparent(struct rdtgroup *rdtgrp,
4114 			    struct rdtgroup *new_prdtgrp,
4115 			    cpumask_var_t cpus)
4116 {
4117 	struct rdtgroup *prdtgrp = rdtgrp->mon.parent;
4118 
4119 	WARN_ON(rdtgrp->type != RDTMON_GROUP);
4120 	WARN_ON(new_prdtgrp->type != RDTCTRL_GROUP);
4121 
4122 	/* Nothing to do when simply renaming a MON group. */
4123 	if (prdtgrp == new_prdtgrp)
4124 		return;
4125 
4126 	WARN_ON(list_empty(&prdtgrp->mon.crdtgrp_list));
4127 	list_move_tail(&rdtgrp->mon.crdtgrp_list,
4128 		       &new_prdtgrp->mon.crdtgrp_list);
4129 
4130 	rdtgrp->mon.parent = new_prdtgrp;
4131 	rdtgrp->closid = new_prdtgrp->closid;
4132 
4133 	/* Propagate updated closid to all tasks in this group. */
4134 	rdt_move_group_tasks(rdtgrp, rdtgrp, cpus);
4135 
4136 	update_closid_rmid(cpus, NULL);
4137 }
4138 
4139 static int rdtgroup_rename(struct kernfs_node *kn,
4140 			   struct kernfs_node *new_parent, const char *new_name)
4141 {
4142 	struct kernfs_node *kn_parent;
4143 	struct rdtgroup *new_prdtgrp;
4144 	struct rdtgroup *rdtgrp;
4145 	cpumask_var_t tmpmask;
4146 	int ret;
4147 
4148 	rdtgrp = kernfs_to_rdtgroup(kn);
4149 	new_prdtgrp = kernfs_to_rdtgroup(new_parent);
4150 	if (!rdtgrp || !new_prdtgrp)
4151 		return -ENOENT;
4152 
4153 	/* Release both kernfs active_refs before obtaining rdtgroup mutex. */
4154 	rdtgroup_kn_get(rdtgrp, kn);
4155 	rdtgroup_kn_get(new_prdtgrp, new_parent);
4156 
4157 	mutex_lock(&rdtgroup_mutex);
4158 
4159 	rdt_last_cmd_clear();
4160 
4161 	/*
4162 	 * Don't allow kernfs_to_rdtgroup() to return a parent rdtgroup if
4163 	 * either kernfs_node is a file.
4164 	 */
4165 	if (kernfs_type(kn) != KERNFS_DIR ||
4166 	    kernfs_type(new_parent) != KERNFS_DIR) {
4167 		rdt_last_cmd_puts("Source and destination must be directories");
4168 		ret = -EPERM;
4169 		goto out;
4170 	}
4171 
4172 	if ((rdtgrp->flags & RDT_DELETED) || (new_prdtgrp->flags & RDT_DELETED)) {
4173 		ret = -ENOENT;
4174 		goto out;
4175 	}
4176 
4177 	kn_parent = rdt_kn_parent(kn);
4178 	if (rdtgrp->type != RDTMON_GROUP || !kn_parent ||
4179 	    !is_mon_groups(kn_parent, rdt_kn_name(kn))) {
4180 		rdt_last_cmd_puts("Source must be a MON group\n");
4181 		ret = -EPERM;
4182 		goto out;
4183 	}
4184 
4185 	if (!is_mon_groups(new_parent, new_name)) {
4186 		rdt_last_cmd_puts("Destination must be a mon_groups subdirectory\n");
4187 		ret = -EPERM;
4188 		goto out;
4189 	}
4190 
4191 	/*
4192 	 * If the MON group is monitoring CPUs, the CPUs must be assigned to the
4193 	 * current parent CTRL_MON group and therefore cannot be assigned to
4194 	 * the new parent, making the move illegal.
4195 	 */
4196 	if (!cpumask_empty(&rdtgrp->cpu_mask) &&
4197 	    rdtgrp->mon.parent != new_prdtgrp) {
4198 		rdt_last_cmd_puts("Cannot move a MON group that monitors CPUs\n");
4199 		ret = -EPERM;
4200 		goto out;
4201 	}
4202 
4203 	/*
4204 	 * Allocate the cpumask for use in mongrp_reparent() to avoid the
4205 	 * possibility of failing to allocate it after kernfs_rename() has
4206 	 * succeeded.
4207 	 */
4208 	if (!zalloc_cpumask_var(&tmpmask, GFP_KERNEL)) {
4209 		ret = -ENOMEM;
4210 		goto out;
4211 	}
4212 
4213 	/*
4214 	 * Perform all input validation and allocations needed to ensure
4215 	 * mongrp_reparent() will succeed before calling kernfs_rename(),
4216 	 * otherwise it would be necessary to revert this call if
4217 	 * mongrp_reparent() failed.
4218 	 */
4219 	ret = kernfs_rename(kn, new_parent, new_name);
4220 	if (!ret)
4221 		mongrp_reparent(rdtgrp, new_prdtgrp, tmpmask);
4222 
4223 	free_cpumask_var(tmpmask);
4224 
4225 out:
4226 	mutex_unlock(&rdtgroup_mutex);
4227 	rdtgroup_kn_put(rdtgrp, kn);
4228 	rdtgroup_kn_put(new_prdtgrp, new_parent);
4229 	return ret;
4230 }
4231 
4232 static int rdtgroup_show_options(struct seq_file *seq, struct kernfs_root *kf)
4233 {
4234 	if (resctrl_arch_get_cdp_enabled(RDT_RESOURCE_L3))
4235 		seq_puts(seq, ",cdp");
4236 
4237 	if (resctrl_arch_get_cdp_enabled(RDT_RESOURCE_L2))
4238 		seq_puts(seq, ",cdpl2");
4239 
4240 	if (is_mba_sc(resctrl_arch_get_resource(RDT_RESOURCE_MBA)))
4241 		seq_puts(seq, ",mba_MBps");
4242 
4243 	if (resctrl_debug)
4244 		seq_puts(seq, ",debug");
4245 
4246 	return 0;
4247 }
4248 
4249 static struct kernfs_syscall_ops rdtgroup_kf_syscall_ops = {
4250 	.mkdir		= rdtgroup_mkdir,
4251 	.rmdir		= rdtgroup_rmdir,
4252 	.rename		= rdtgroup_rename,
4253 	.show_options	= rdtgroup_show_options,
4254 };
4255 
4256 static int rdtgroup_setup_root(struct rdt_fs_context *ctx)
4257 {
4258 	rdt_root = kernfs_create_root(&rdtgroup_kf_syscall_ops,
4259 				      KERNFS_ROOT_CREATE_DEACTIVATED |
4260 				      KERNFS_ROOT_EXTRA_OPEN_PERM_CHECK,
4261 				      &rdtgroup_default);
4262 	if (IS_ERR(rdt_root))
4263 		return PTR_ERR(rdt_root);
4264 
4265 	ctx->kfc.root = rdt_root;
4266 	rdtgroup_default.kn = kernfs_root_to_node(rdt_root);
4267 
4268 	return 0;
4269 }
4270 
4271 static void rdtgroup_destroy_root(void)
4272 {
4273 	lockdep_assert_held(&rdtgroup_mutex);
4274 
4275 	kernfs_destroy_root(rdt_root);
4276 	rdtgroup_default.kn = NULL;
4277 }
4278 
4279 static void rdtgroup_setup_default(void)
4280 {
4281 	mutex_lock(&rdtgroup_mutex);
4282 
4283 	rdtgroup_default.closid = RESCTRL_RESERVED_CLOSID;
4284 	rdtgroup_default.mon.rmid = RESCTRL_RESERVED_RMID;
4285 	rdtgroup_default.type = RDTCTRL_GROUP;
4286 	INIT_LIST_HEAD(&rdtgroup_default.mon.crdtgrp_list);
4287 
4288 	list_add(&rdtgroup_default.rdtgroup_list, &rdt_all_groups);
4289 
4290 	mutex_unlock(&rdtgroup_mutex);
4291 }
4292 
4293 static void domain_destroy_l3_mon_state(struct rdt_l3_mon_domain *d)
4294 {
4295 	int idx;
4296 
4297 	kfree(d->cntr_cfg);
4298 	bitmap_free(d->rmid_busy_llc);
4299 	for_each_mbm_idx(idx) {
4300 		kfree(d->mbm_states[idx]);
4301 		d->mbm_states[idx] = NULL;
4302 	}
4303 }
4304 
4305 void resctrl_offline_ctrl_domain(struct rdt_resource *r, struct rdt_ctrl_domain *d)
4306 {
4307 	mutex_lock(&rdtgroup_mutex);
4308 
4309 	if (supports_mba_mbps() && r->rid == RDT_RESOURCE_MBA)
4310 		mba_sc_domain_destroy(r, d);
4311 
4312 	mutex_unlock(&rdtgroup_mutex);
4313 }
4314 
4315 void resctrl_offline_mon_domain(struct rdt_resource *r, struct rdt_domain_hdr *hdr)
4316 {
4317 	struct rdt_l3_mon_domain *d;
4318 
4319 	mutex_lock(&rdtgroup_mutex);
4320 
4321 	/*
4322 	 * If resctrl is mounted, remove all the
4323 	 * per domain monitor data directories.
4324 	 */
4325 	if (resctrl_mounted && resctrl_arch_mon_capable())
4326 		rmdir_mondata_subdir_allrdtgrp(r, hdr);
4327 
4328 	if (r->rid != RDT_RESOURCE_L3)
4329 		goto out_unlock;
4330 
4331 	if (!domain_header_is_valid(hdr, RESCTRL_MON_DOMAIN, RDT_RESOURCE_L3))
4332 		goto out_unlock;
4333 
4334 	d = container_of(hdr, struct rdt_l3_mon_domain, hdr);
4335 	if (resctrl_is_mbm_enabled())
4336 		cancel_delayed_work(&d->mbm_over);
4337 	if (resctrl_is_mon_event_enabled(QOS_L3_OCCUP_EVENT_ID) && has_busy_rmid(d)) {
4338 		/*
4339 		 * When a package is going down, forcefully
4340 		 * decrement rmid->ebusy. There is no way to know
4341 		 * that the L3 was flushed and hence may lead to
4342 		 * incorrect counts in rare scenarios, but leaving
4343 		 * the RMID as busy creates RMID leaks if the
4344 		 * package never comes back.
4345 		 */
4346 		__check_limbo(d, true);
4347 		cancel_delayed_work(&d->cqm_limbo);
4348 	}
4349 
4350 	domain_destroy_l3_mon_state(d);
4351 out_unlock:
4352 	mutex_unlock(&rdtgroup_mutex);
4353 }
4354 
4355 /**
4356  * domain_setup_l3_mon_state() -  Initialise domain monitoring structures.
4357  * @r:	The resource for the newly online domain.
4358  * @d:	The newly online domain.
4359  *
4360  * Allocate monitor resources that belong to this domain.
4361  * Called when the first CPU of a domain comes online, regardless of whether
4362  * the filesystem is mounted.
4363  * During boot this may be called before global allocations have been made by
4364  * resctrl_l3_mon_resource_init().
4365  *
4366  * Called during CPU online that may run as soon as CPU online callbacks
4367  * are set up during resctrl initialization. The number of supported RMIDs
4368  * may be reduced if additional mon_capable resources are enumerated
4369  * at mount time. This means the rdt_l3_mon_domain::mbm_states[] and
4370  * rdt_l3_mon_domain::rmid_busy_llc allocations may be larger than needed.
4371  *
4372  * Return: 0 for success, or -ENOMEM.
4373  */
4374 static int domain_setup_l3_mon_state(struct rdt_resource *r, struct rdt_l3_mon_domain *d)
4375 {
4376 	u32 idx_limit = resctrl_arch_system_num_rmid_idx();
4377 	size_t tsize = sizeof(*d->mbm_states[0]);
4378 	enum resctrl_event_id eventid;
4379 	int idx;
4380 
4381 	if (resctrl_is_mon_event_enabled(QOS_L3_OCCUP_EVENT_ID)) {
4382 		d->rmid_busy_llc = bitmap_zalloc(idx_limit, GFP_KERNEL);
4383 		if (!d->rmid_busy_llc)
4384 			return -ENOMEM;
4385 	}
4386 
4387 	for_each_mbm_event_id(eventid) {
4388 		if (!resctrl_is_mon_event_enabled(eventid))
4389 			continue;
4390 		idx = MBM_STATE_IDX(eventid);
4391 		d->mbm_states[idx] = kcalloc(idx_limit, tsize, GFP_KERNEL);
4392 		if (!d->mbm_states[idx])
4393 			goto cleanup;
4394 	}
4395 
4396 	if (resctrl_is_mbm_enabled() && r->mon.mbm_cntr_assignable) {
4397 		tsize = sizeof(*d->cntr_cfg);
4398 		d->cntr_cfg = kcalloc(r->mon.num_mbm_cntrs, tsize, GFP_KERNEL);
4399 		if (!d->cntr_cfg)
4400 			goto cleanup;
4401 	}
4402 
4403 	return 0;
4404 cleanup:
4405 	bitmap_free(d->rmid_busy_llc);
4406 	for_each_mbm_idx(idx) {
4407 		kfree(d->mbm_states[idx]);
4408 		d->mbm_states[idx] = NULL;
4409 	}
4410 
4411 	return -ENOMEM;
4412 }
4413 
4414 int resctrl_online_ctrl_domain(struct rdt_resource *r, struct rdt_ctrl_domain *d)
4415 {
4416 	int err = 0;
4417 
4418 	mutex_lock(&rdtgroup_mutex);
4419 
4420 	if (supports_mba_mbps() && r->rid == RDT_RESOURCE_MBA) {
4421 		/* RDT_RESOURCE_MBA is never mon_capable */
4422 		err = mba_sc_domain_allocate(r, d);
4423 	}
4424 
4425 	mutex_unlock(&rdtgroup_mutex);
4426 
4427 	return err;
4428 }
4429 
4430 int resctrl_online_mon_domain(struct rdt_resource *r, struct rdt_domain_hdr *hdr)
4431 {
4432 	struct rdt_l3_mon_domain *d;
4433 	int err = -EINVAL;
4434 
4435 	mutex_lock(&rdtgroup_mutex);
4436 
4437 	if (r->rid != RDT_RESOURCE_L3)
4438 		goto mkdir;
4439 
4440 	if (!domain_header_is_valid(hdr, RESCTRL_MON_DOMAIN, RDT_RESOURCE_L3))
4441 		goto out_unlock;
4442 
4443 	d = container_of(hdr, struct rdt_l3_mon_domain, hdr);
4444 	err = domain_setup_l3_mon_state(r, d);
4445 	if (err)
4446 		goto out_unlock;
4447 
4448 	if (resctrl_is_mbm_enabled()) {
4449 		INIT_DELAYED_WORK(&d->mbm_over, mbm_handle_overflow);
4450 		mbm_setup_overflow_handler(d, MBM_OVERFLOW_INTERVAL,
4451 					   RESCTRL_PICK_ANY_CPU);
4452 	}
4453 
4454 	if (resctrl_is_mon_event_enabled(QOS_L3_OCCUP_EVENT_ID))
4455 		INIT_DELAYED_WORK(&d->cqm_limbo, cqm_handle_limbo);
4456 
4457 mkdir:
4458 	err = 0;
4459 	/*
4460 	 * If the filesystem is not mounted then only the default resource group
4461 	 * exists. Creation of its directories is deferred until mount time
4462 	 * by rdt_get_tree() calling mkdir_mondata_all().
4463 	 * If resctrl is mounted, add per domain monitor data directories.
4464 	 */
4465 	if (resctrl_mounted && resctrl_arch_mon_capable())
4466 		mkdir_mondata_subdir_allrdtgrp(r, hdr);
4467 
4468 out_unlock:
4469 	mutex_unlock(&rdtgroup_mutex);
4470 
4471 	return err;
4472 }
4473 
4474 void resctrl_online_cpu(unsigned int cpu)
4475 {
4476 	mutex_lock(&rdtgroup_mutex);
4477 	/* The CPU is set in default rdtgroup after online. */
4478 	cpumask_set_cpu(cpu, &rdtgroup_default.cpu_mask);
4479 	mutex_unlock(&rdtgroup_mutex);
4480 }
4481 
4482 static void clear_childcpus(struct rdtgroup *r, unsigned int cpu)
4483 {
4484 	struct rdtgroup *cr;
4485 
4486 	list_for_each_entry(cr, &r->mon.crdtgrp_list, mon.crdtgrp_list) {
4487 		if (cpumask_test_and_clear_cpu(cpu, &cr->cpu_mask))
4488 			break;
4489 	}
4490 }
4491 
4492 static struct rdt_l3_mon_domain *get_mon_domain_from_cpu(int cpu,
4493 							 struct rdt_resource *r)
4494 {
4495 	struct rdt_l3_mon_domain *d;
4496 
4497 	lockdep_assert_cpus_held();
4498 
4499 	list_for_each_entry(d, &r->mon_domains, hdr.list) {
4500 		/* Find the domain that contains this CPU */
4501 		if (cpumask_test_cpu(cpu, &d->hdr.cpu_mask))
4502 			return d;
4503 	}
4504 
4505 	return NULL;
4506 }
4507 
4508 void resctrl_offline_cpu(unsigned int cpu)
4509 {
4510 	struct rdt_resource *l3 = resctrl_arch_get_resource(RDT_RESOURCE_L3);
4511 	struct rdt_l3_mon_domain *d;
4512 	struct rdtgroup *rdtgrp;
4513 
4514 	mutex_lock(&rdtgroup_mutex);
4515 	list_for_each_entry(rdtgrp, &rdt_all_groups, rdtgroup_list) {
4516 		if (cpumask_test_and_clear_cpu(cpu, &rdtgrp->cpu_mask)) {
4517 			clear_childcpus(rdtgrp, cpu);
4518 			break;
4519 		}
4520 	}
4521 
4522 	if (!l3->mon_capable)
4523 		goto out_unlock;
4524 
4525 	d = get_mon_domain_from_cpu(cpu, l3);
4526 	if (d) {
4527 		if (resctrl_is_mbm_enabled() && cpu == d->mbm_work_cpu) {
4528 			cancel_delayed_work(&d->mbm_over);
4529 			mbm_setup_overflow_handler(d, 0, cpu);
4530 		}
4531 		if (resctrl_is_mon_event_enabled(QOS_L3_OCCUP_EVENT_ID) &&
4532 		    cpu == d->cqm_work_cpu && has_busy_rmid(d)) {
4533 			cancel_delayed_work(&d->cqm_limbo);
4534 			cqm_setup_limbo_handler(d, 0, cpu);
4535 		}
4536 	}
4537 
4538 out_unlock:
4539 	mutex_unlock(&rdtgroup_mutex);
4540 }
4541 
4542 /*
4543  * resctrl_init - resctrl filesystem initialization
4544  *
4545  * Setup resctrl file system including set up root, create mount point,
4546  * register resctrl filesystem, and initialize files under root directory.
4547  *
4548  * Return: 0 on success or -errno
4549  */
4550 int resctrl_init(void)
4551 {
4552 	int ret = 0;
4553 
4554 	seq_buf_init(&last_cmd_status, last_cmd_status_buf,
4555 		     sizeof(last_cmd_status_buf));
4556 
4557 	rdtgroup_setup_default();
4558 
4559 	thread_throttle_mode_init();
4560 
4561 	io_alloc_init();
4562 
4563 	ret = resctrl_l3_mon_resource_init();
4564 	if (ret)
4565 		return ret;
4566 
4567 	ret = sysfs_create_mount_point(fs_kobj, "resctrl");
4568 	if (ret) {
4569 		resctrl_l3_mon_resource_exit();
4570 		return ret;
4571 	}
4572 
4573 	ret = register_filesystem(&rdt_fs_type);
4574 	if (ret)
4575 		goto cleanup_mountpoint;
4576 
4577 	/*
4578 	 * Adding the resctrl debugfs directory here may not be ideal since
4579 	 * it would let the resctrl debugfs directory appear on the debugfs
4580 	 * filesystem before the resctrl filesystem is mounted.
4581 	 * It may also be ok since that would enable debugging of RDT before
4582 	 * resctrl is mounted.
4583 	 * The reason why the debugfs directory is created here and not in
4584 	 * rdt_get_tree() is because rdt_get_tree() takes rdtgroup_mutex and
4585 	 * during the debugfs directory creation also &sb->s_type->i_mutex_key
4586 	 * (the lockdep class of inode->i_rwsem). Other filesystem
4587 	 * interactions (eg. SyS_getdents) have the lock ordering:
4588 	 * &sb->s_type->i_mutex_key --> &mm->mmap_lock
4589 	 * During mmap(), called with &mm->mmap_lock, the rdtgroup_mutex
4590 	 * is taken, thus creating dependency:
4591 	 * &mm->mmap_lock --> rdtgroup_mutex for the latter that can cause
4592 	 * issues considering the other two lock dependencies.
4593 	 * By creating the debugfs directory here we avoid a dependency
4594 	 * that may cause deadlock (even though file operations cannot
4595 	 * occur until the filesystem is mounted, but I do not know how to
4596 	 * tell lockdep that).
4597 	 */
4598 	debugfs_resctrl = debugfs_create_dir("resctrl", NULL);
4599 
4600 	return 0;
4601 
4602 cleanup_mountpoint:
4603 	sysfs_remove_mount_point(fs_kobj, "resctrl");
4604 	resctrl_l3_mon_resource_exit();
4605 
4606 	return ret;
4607 }
4608 
4609 static bool resctrl_online_domains_exist(void)
4610 {
4611 	struct rdt_resource *r;
4612 
4613 	/*
4614 	 * Only walk capable resources to allow resctrl_arch_get_resource()
4615 	 * to return dummy 'not capable' resources.
4616 	 */
4617 	for_each_alloc_capable_rdt_resource(r) {
4618 		if (!list_empty(&r->ctrl_domains))
4619 			return true;
4620 	}
4621 
4622 	for_each_mon_capable_rdt_resource(r) {
4623 		if (!list_empty(&r->mon_domains))
4624 			return true;
4625 	}
4626 
4627 	return false;
4628 }
4629 
4630 /**
4631  * resctrl_exit() - Remove the resctrl filesystem and free resources.
4632  *
4633  * Called by the architecture code in response to a fatal error.
4634  * Removes resctrl files and structures from kernfs to prevent further
4635  * configuration.
4636  *
4637  * When called by the architecture code, all CPUs and resctrl domains must be
4638  * offline. This ensures the limbo and overflow handlers are not scheduled to
4639  * run, meaning the data structures they access can be freed by
4640  * resctrl_l3_mon_resource_exit().
4641  *
4642  * After resctrl_exit() returns, the architecture code should return an
4643  * error from all resctrl_arch_ functions that can do this.
4644  * resctrl_arch_get_resource() must continue to return struct rdt_resources
4645  * with the correct rid field to ensure the filesystem can be unmounted.
4646  */
4647 void resctrl_exit(void)
4648 {
4649 	cpus_read_lock();
4650 	WARN_ON_ONCE(resctrl_online_domains_exist());
4651 
4652 	mutex_lock(&rdtgroup_mutex);
4653 	resctrl_fs_teardown();
4654 	mutex_unlock(&rdtgroup_mutex);
4655 
4656 	cpus_read_unlock();
4657 
4658 	debugfs_remove_recursive(debugfs_resctrl);
4659 	debugfs_resctrl = NULL;
4660 	unregister_filesystem(&rdt_fs_type);
4661 
4662 	/*
4663 	 * Do not remove the sysfs mount point added by resctrl_init() so that
4664 	 * it can be used to umount resctrl.
4665 	 */
4666 
4667 	resctrl_l3_mon_resource_exit();
4668 	free_rmid_lru_list();
4669 }
4670