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/cacheinfo.h>
16 #include <linux/cpu.h>
17 #include <linux/debugfs.h>
18 #include <linux/fs.h>
19 #include <linux/fs_parser.h>
20 #include <linux/sysfs.h>
21 #include <linux/kernfs.h>
22 #include <linux/seq_buf.h>
23 #include <linux/seq_file.h>
24 #include <linux/sched/signal.h>
25 #include <linux/sched/task.h>
26 #include <linux/slab.h>
27 #include <linux/task_work.h>
28 #include <linux/user_namespace.h>
29 
30 #include <uapi/linux/magic.h>
31 
32 #include <asm/resctrl.h>
33 #include "internal.h"
34 
35 DEFINE_STATIC_KEY_FALSE(rdt_enable_key);
36 DEFINE_STATIC_KEY_FALSE(rdt_mon_enable_key);
37 DEFINE_STATIC_KEY_FALSE(rdt_alloc_enable_key);
38 static struct kernfs_root *rdt_root;
39 struct rdtgroup rdtgroup_default;
40 LIST_HEAD(rdt_all_groups);
41 
42 /* list of entries for the schemata file */
43 LIST_HEAD(resctrl_schema_all);
44 
45 /* Kernel fs node for "info" directory under root */
46 static struct kernfs_node *kn_info;
47 
48 /* Kernel fs node for "mon_groups" directory under root */
49 static struct kernfs_node *kn_mongrp;
50 
51 /* Kernel fs node for "mon_data" directory under root */
52 static struct kernfs_node *kn_mondata;
53 
54 static struct seq_buf last_cmd_status;
55 static char last_cmd_status_buf[512];
56 
57 struct dentry *debugfs_resctrl;
58 
59 void rdt_last_cmd_clear(void)
60 {
61 	lockdep_assert_held(&rdtgroup_mutex);
62 	seq_buf_clear(&last_cmd_status);
63 }
64 
65 void rdt_last_cmd_puts(const char *s)
66 {
67 	lockdep_assert_held(&rdtgroup_mutex);
68 	seq_buf_puts(&last_cmd_status, s);
69 }
70 
71 void rdt_last_cmd_printf(const char *fmt, ...)
72 {
73 	va_list ap;
74 
75 	va_start(ap, fmt);
76 	lockdep_assert_held(&rdtgroup_mutex);
77 	seq_buf_vprintf(&last_cmd_status, fmt, ap);
78 	va_end(ap);
79 }
80 
81 void rdt_staged_configs_clear(void)
82 {
83 	struct rdt_resource *r;
84 	struct rdt_domain *dom;
85 
86 	lockdep_assert_held(&rdtgroup_mutex);
87 
88 	for_each_alloc_capable_rdt_resource(r) {
89 		list_for_each_entry(dom, &r->domains, list)
90 			memset(dom->staged_config, 0, sizeof(dom->staged_config));
91 	}
92 }
93 
94 /*
95  * Trivial allocator for CLOSIDs. Since h/w only supports a small number,
96  * we can keep a bitmap of free CLOSIDs in a single integer.
97  *
98  * Using a global CLOSID across all resources has some advantages and
99  * some drawbacks:
100  * + We can simply set "current->closid" to assign a task to a resource
101  *   group.
102  * + Context switch code can avoid extra memory references deciding which
103  *   CLOSID to load into the PQR_ASSOC MSR
104  * - We give up some options in configuring resource groups across multi-socket
105  *   systems.
106  * - Our choices on how to configure each resource become progressively more
107  *   limited as the number of resources grows.
108  */
109 static int closid_free_map;
110 static int closid_free_map_len;
111 
112 int closids_supported(void)
113 {
114 	return closid_free_map_len;
115 }
116 
117 static void closid_init(void)
118 {
119 	struct resctrl_schema *s;
120 	u32 rdt_min_closid = 32;
121 
122 	/* Compute rdt_min_closid across all resources */
123 	list_for_each_entry(s, &resctrl_schema_all, list)
124 		rdt_min_closid = min(rdt_min_closid, s->num_closid);
125 
126 	closid_free_map = BIT_MASK(rdt_min_closid) - 1;
127 
128 	/* CLOSID 0 is always reserved for the default group */
129 	closid_free_map &= ~1;
130 	closid_free_map_len = rdt_min_closid;
131 }
132 
133 static int closid_alloc(void)
134 {
135 	u32 closid = ffs(closid_free_map);
136 
137 	if (closid == 0)
138 		return -ENOSPC;
139 	closid--;
140 	closid_free_map &= ~(1 << closid);
141 
142 	return closid;
143 }
144 
145 void closid_free(int closid)
146 {
147 	closid_free_map |= 1 << closid;
148 }
149 
150 /**
151  * closid_allocated - test if provided closid is in use
152  * @closid: closid to be tested
153  *
154  * Return: true if @closid is currently associated with a resource group,
155  * false if @closid is free
156  */
157 static bool closid_allocated(unsigned int closid)
158 {
159 	return (closid_free_map & (1 << closid)) == 0;
160 }
161 
162 /**
163  * rdtgroup_mode_by_closid - Return mode of resource group with closid
164  * @closid: closid if the resource group
165  *
166  * Each resource group is associated with a @closid. Here the mode
167  * of a resource group can be queried by searching for it using its closid.
168  *
169  * Return: mode as &enum rdtgrp_mode of resource group with closid @closid
170  */
171 enum rdtgrp_mode rdtgroup_mode_by_closid(int closid)
172 {
173 	struct rdtgroup *rdtgrp;
174 
175 	list_for_each_entry(rdtgrp, &rdt_all_groups, rdtgroup_list) {
176 		if (rdtgrp->closid == closid)
177 			return rdtgrp->mode;
178 	}
179 
180 	return RDT_NUM_MODES;
181 }
182 
183 static const char * const rdt_mode_str[] = {
184 	[RDT_MODE_SHAREABLE]		= "shareable",
185 	[RDT_MODE_EXCLUSIVE]		= "exclusive",
186 	[RDT_MODE_PSEUDO_LOCKSETUP]	= "pseudo-locksetup",
187 	[RDT_MODE_PSEUDO_LOCKED]	= "pseudo-locked",
188 };
189 
190 /**
191  * rdtgroup_mode_str - Return the string representation of mode
192  * @mode: the resource group mode as &enum rdtgroup_mode
193  *
194  * Return: string representation of valid mode, "unknown" otherwise
195  */
196 static const char *rdtgroup_mode_str(enum rdtgrp_mode mode)
197 {
198 	if (mode < RDT_MODE_SHAREABLE || mode >= RDT_NUM_MODES)
199 		return "unknown";
200 
201 	return rdt_mode_str[mode];
202 }
203 
204 /* set uid and gid of rdtgroup dirs and files to that of the creator */
205 static int rdtgroup_kn_set_ugid(struct kernfs_node *kn)
206 {
207 	struct iattr iattr = { .ia_valid = ATTR_UID | ATTR_GID,
208 				.ia_uid = current_fsuid(),
209 				.ia_gid = current_fsgid(), };
210 
211 	if (uid_eq(iattr.ia_uid, GLOBAL_ROOT_UID) &&
212 	    gid_eq(iattr.ia_gid, GLOBAL_ROOT_GID))
213 		return 0;
214 
215 	return kernfs_setattr(kn, &iattr);
216 }
217 
218 static int rdtgroup_add_file(struct kernfs_node *parent_kn, struct rftype *rft)
219 {
220 	struct kernfs_node *kn;
221 	int ret;
222 
223 	kn = __kernfs_create_file(parent_kn, rft->name, rft->mode,
224 				  GLOBAL_ROOT_UID, GLOBAL_ROOT_GID,
225 				  0, rft->kf_ops, rft, NULL, NULL);
226 	if (IS_ERR(kn))
227 		return PTR_ERR(kn);
228 
229 	ret = rdtgroup_kn_set_ugid(kn);
230 	if (ret) {
231 		kernfs_remove(kn);
232 		return ret;
233 	}
234 
235 	return 0;
236 }
237 
238 static int rdtgroup_seqfile_show(struct seq_file *m, void *arg)
239 {
240 	struct kernfs_open_file *of = m->private;
241 	struct rftype *rft = of->kn->priv;
242 
243 	if (rft->seq_show)
244 		return rft->seq_show(of, m, arg);
245 	return 0;
246 }
247 
248 static ssize_t rdtgroup_file_write(struct kernfs_open_file *of, char *buf,
249 				   size_t nbytes, loff_t off)
250 {
251 	struct rftype *rft = of->kn->priv;
252 
253 	if (rft->write)
254 		return rft->write(of, buf, nbytes, off);
255 
256 	return -EINVAL;
257 }
258 
259 static const struct kernfs_ops rdtgroup_kf_single_ops = {
260 	.atomic_write_len	= PAGE_SIZE,
261 	.write			= rdtgroup_file_write,
262 	.seq_show		= rdtgroup_seqfile_show,
263 };
264 
265 static const struct kernfs_ops kf_mondata_ops = {
266 	.atomic_write_len	= PAGE_SIZE,
267 	.seq_show		= rdtgroup_mondata_show,
268 };
269 
270 static bool is_cpu_list(struct kernfs_open_file *of)
271 {
272 	struct rftype *rft = of->kn->priv;
273 
274 	return rft->flags & RFTYPE_FLAGS_CPUS_LIST;
275 }
276 
277 static int rdtgroup_cpus_show(struct kernfs_open_file *of,
278 			      struct seq_file *s, void *v)
279 {
280 	struct rdtgroup *rdtgrp;
281 	struct cpumask *mask;
282 	int ret = 0;
283 
284 	rdtgrp = rdtgroup_kn_lock_live(of->kn);
285 
286 	if (rdtgrp) {
287 		if (rdtgrp->mode == RDT_MODE_PSEUDO_LOCKED) {
288 			if (!rdtgrp->plr->d) {
289 				rdt_last_cmd_clear();
290 				rdt_last_cmd_puts("Cache domain offline\n");
291 				ret = -ENODEV;
292 			} else {
293 				mask = &rdtgrp->plr->d->cpu_mask;
294 				seq_printf(s, is_cpu_list(of) ?
295 					   "%*pbl\n" : "%*pb\n",
296 					   cpumask_pr_args(mask));
297 			}
298 		} else {
299 			seq_printf(s, is_cpu_list(of) ? "%*pbl\n" : "%*pb\n",
300 				   cpumask_pr_args(&rdtgrp->cpu_mask));
301 		}
302 	} else {
303 		ret = -ENOENT;
304 	}
305 	rdtgroup_kn_unlock(of->kn);
306 
307 	return ret;
308 }
309 
310 /*
311  * This is safe against resctrl_sched_in() called from __switch_to()
312  * because __switch_to() is executed with interrupts disabled. A local call
313  * from update_closid_rmid() is protected against __switch_to() because
314  * preemption is disabled.
315  */
316 static void update_cpu_closid_rmid(void *info)
317 {
318 	struct rdtgroup *r = info;
319 
320 	if (r) {
321 		this_cpu_write(pqr_state.default_closid, r->closid);
322 		this_cpu_write(pqr_state.default_rmid, r->mon.rmid);
323 	}
324 
325 	/*
326 	 * We cannot unconditionally write the MSR because the current
327 	 * executing task might have its own closid selected. Just reuse
328 	 * the context switch code.
329 	 */
330 	resctrl_sched_in(current);
331 }
332 
333 /*
334  * Update the PGR_ASSOC MSR on all cpus in @cpu_mask,
335  *
336  * Per task closids/rmids must have been set up before calling this function.
337  */
338 static void
339 update_closid_rmid(const struct cpumask *cpu_mask, struct rdtgroup *r)
340 {
341 	on_each_cpu_mask(cpu_mask, update_cpu_closid_rmid, r, 1);
342 }
343 
344 static int cpus_mon_write(struct rdtgroup *rdtgrp, cpumask_var_t newmask,
345 			  cpumask_var_t tmpmask)
346 {
347 	struct rdtgroup *prgrp = rdtgrp->mon.parent, *crgrp;
348 	struct list_head *head;
349 
350 	/* Check whether cpus belong to parent ctrl group */
351 	cpumask_andnot(tmpmask, newmask, &prgrp->cpu_mask);
352 	if (!cpumask_empty(tmpmask)) {
353 		rdt_last_cmd_puts("Can only add CPUs to mongroup that belong to parent\n");
354 		return -EINVAL;
355 	}
356 
357 	/* Check whether cpus are dropped from this group */
358 	cpumask_andnot(tmpmask, &rdtgrp->cpu_mask, newmask);
359 	if (!cpumask_empty(tmpmask)) {
360 		/* Give any dropped cpus to parent rdtgroup */
361 		cpumask_or(&prgrp->cpu_mask, &prgrp->cpu_mask, tmpmask);
362 		update_closid_rmid(tmpmask, prgrp);
363 	}
364 
365 	/*
366 	 * If we added cpus, remove them from previous group that owned them
367 	 * and update per-cpu rmid
368 	 */
369 	cpumask_andnot(tmpmask, newmask, &rdtgrp->cpu_mask);
370 	if (!cpumask_empty(tmpmask)) {
371 		head = &prgrp->mon.crdtgrp_list;
372 		list_for_each_entry(crgrp, head, mon.crdtgrp_list) {
373 			if (crgrp == rdtgrp)
374 				continue;
375 			cpumask_andnot(&crgrp->cpu_mask, &crgrp->cpu_mask,
376 				       tmpmask);
377 		}
378 		update_closid_rmid(tmpmask, rdtgrp);
379 	}
380 
381 	/* Done pushing/pulling - update this group with new mask */
382 	cpumask_copy(&rdtgrp->cpu_mask, newmask);
383 
384 	return 0;
385 }
386 
387 static void cpumask_rdtgrp_clear(struct rdtgroup *r, struct cpumask *m)
388 {
389 	struct rdtgroup *crgrp;
390 
391 	cpumask_andnot(&r->cpu_mask, &r->cpu_mask, m);
392 	/* update the child mon group masks as well*/
393 	list_for_each_entry(crgrp, &r->mon.crdtgrp_list, mon.crdtgrp_list)
394 		cpumask_and(&crgrp->cpu_mask, &r->cpu_mask, &crgrp->cpu_mask);
395 }
396 
397 static int cpus_ctrl_write(struct rdtgroup *rdtgrp, cpumask_var_t newmask,
398 			   cpumask_var_t tmpmask, cpumask_var_t tmpmask1)
399 {
400 	struct rdtgroup *r, *crgrp;
401 	struct list_head *head;
402 
403 	/* Check whether cpus are dropped from this group */
404 	cpumask_andnot(tmpmask, &rdtgrp->cpu_mask, newmask);
405 	if (!cpumask_empty(tmpmask)) {
406 		/* Can't drop from default group */
407 		if (rdtgrp == &rdtgroup_default) {
408 			rdt_last_cmd_puts("Can't drop CPUs from default group\n");
409 			return -EINVAL;
410 		}
411 
412 		/* Give any dropped cpus to rdtgroup_default */
413 		cpumask_or(&rdtgroup_default.cpu_mask,
414 			   &rdtgroup_default.cpu_mask, tmpmask);
415 		update_closid_rmid(tmpmask, &rdtgroup_default);
416 	}
417 
418 	/*
419 	 * If we added cpus, remove them from previous group and
420 	 * the prev group's child groups that owned them
421 	 * and update per-cpu closid/rmid.
422 	 */
423 	cpumask_andnot(tmpmask, newmask, &rdtgrp->cpu_mask);
424 	if (!cpumask_empty(tmpmask)) {
425 		list_for_each_entry(r, &rdt_all_groups, rdtgroup_list) {
426 			if (r == rdtgrp)
427 				continue;
428 			cpumask_and(tmpmask1, &r->cpu_mask, tmpmask);
429 			if (!cpumask_empty(tmpmask1))
430 				cpumask_rdtgrp_clear(r, tmpmask1);
431 		}
432 		update_closid_rmid(tmpmask, rdtgrp);
433 	}
434 
435 	/* Done pushing/pulling - update this group with new mask */
436 	cpumask_copy(&rdtgrp->cpu_mask, newmask);
437 
438 	/*
439 	 * Clear child mon group masks since there is a new parent mask
440 	 * now and update the rmid for the cpus the child lost.
441 	 */
442 	head = &rdtgrp->mon.crdtgrp_list;
443 	list_for_each_entry(crgrp, head, mon.crdtgrp_list) {
444 		cpumask_and(tmpmask, &rdtgrp->cpu_mask, &crgrp->cpu_mask);
445 		update_closid_rmid(tmpmask, rdtgrp);
446 		cpumask_clear(&crgrp->cpu_mask);
447 	}
448 
449 	return 0;
450 }
451 
452 static ssize_t rdtgroup_cpus_write(struct kernfs_open_file *of,
453 				   char *buf, size_t nbytes, loff_t off)
454 {
455 	cpumask_var_t tmpmask, newmask, tmpmask1;
456 	struct rdtgroup *rdtgrp;
457 	int ret;
458 
459 	if (!buf)
460 		return -EINVAL;
461 
462 	if (!zalloc_cpumask_var(&tmpmask, GFP_KERNEL))
463 		return -ENOMEM;
464 	if (!zalloc_cpumask_var(&newmask, GFP_KERNEL)) {
465 		free_cpumask_var(tmpmask);
466 		return -ENOMEM;
467 	}
468 	if (!zalloc_cpumask_var(&tmpmask1, GFP_KERNEL)) {
469 		free_cpumask_var(tmpmask);
470 		free_cpumask_var(newmask);
471 		return -ENOMEM;
472 	}
473 
474 	rdtgrp = rdtgroup_kn_lock_live(of->kn);
475 	if (!rdtgrp) {
476 		ret = -ENOENT;
477 		goto unlock;
478 	}
479 
480 	if (rdtgrp->mode == RDT_MODE_PSEUDO_LOCKED ||
481 	    rdtgrp->mode == RDT_MODE_PSEUDO_LOCKSETUP) {
482 		ret = -EINVAL;
483 		rdt_last_cmd_puts("Pseudo-locking in progress\n");
484 		goto unlock;
485 	}
486 
487 	if (is_cpu_list(of))
488 		ret = cpulist_parse(buf, newmask);
489 	else
490 		ret = cpumask_parse(buf, newmask);
491 
492 	if (ret) {
493 		rdt_last_cmd_puts("Bad CPU list/mask\n");
494 		goto unlock;
495 	}
496 
497 	/* check that user didn't specify any offline cpus */
498 	cpumask_andnot(tmpmask, newmask, cpu_online_mask);
499 	if (!cpumask_empty(tmpmask)) {
500 		ret = -EINVAL;
501 		rdt_last_cmd_puts("Can only assign online CPUs\n");
502 		goto unlock;
503 	}
504 
505 	if (rdtgrp->type == RDTCTRL_GROUP)
506 		ret = cpus_ctrl_write(rdtgrp, newmask, tmpmask, tmpmask1);
507 	else if (rdtgrp->type == RDTMON_GROUP)
508 		ret = cpus_mon_write(rdtgrp, newmask, tmpmask);
509 	else
510 		ret = -EINVAL;
511 
512 unlock:
513 	rdtgroup_kn_unlock(of->kn);
514 	free_cpumask_var(tmpmask);
515 	free_cpumask_var(newmask);
516 	free_cpumask_var(tmpmask1);
517 
518 	return ret ?: nbytes;
519 }
520 
521 /**
522  * rdtgroup_remove - the helper to remove resource group safely
523  * @rdtgrp: resource group to remove
524  *
525  * On resource group creation via a mkdir, an extra kernfs_node reference is
526  * taken to ensure that the rdtgroup structure remains accessible for the
527  * rdtgroup_kn_unlock() calls where it is removed.
528  *
529  * Drop the extra reference here, then free the rdtgroup structure.
530  *
531  * Return: void
532  */
533 static void rdtgroup_remove(struct rdtgroup *rdtgrp)
534 {
535 	kernfs_put(rdtgrp->kn);
536 	kfree(rdtgrp);
537 }
538 
539 static void _update_task_closid_rmid(void *task)
540 {
541 	/*
542 	 * If the task is still current on this CPU, update PQR_ASSOC MSR.
543 	 * Otherwise, the MSR is updated when the task is scheduled in.
544 	 */
545 	if (task == current)
546 		resctrl_sched_in(task);
547 }
548 
549 static void update_task_closid_rmid(struct task_struct *t)
550 {
551 	if (IS_ENABLED(CONFIG_SMP) && task_curr(t))
552 		smp_call_function_single(task_cpu(t), _update_task_closid_rmid, t, 1);
553 	else
554 		_update_task_closid_rmid(t);
555 }
556 
557 static int __rdtgroup_move_task(struct task_struct *tsk,
558 				struct rdtgroup *rdtgrp)
559 {
560 	/* If the task is already in rdtgrp, no need to move the task. */
561 	if ((rdtgrp->type == RDTCTRL_GROUP && tsk->closid == rdtgrp->closid &&
562 	     tsk->rmid == rdtgrp->mon.rmid) ||
563 	    (rdtgrp->type == RDTMON_GROUP && tsk->rmid == rdtgrp->mon.rmid &&
564 	     tsk->closid == rdtgrp->mon.parent->closid))
565 		return 0;
566 
567 	/*
568 	 * Set the task's closid/rmid before the PQR_ASSOC MSR can be
569 	 * updated by them.
570 	 *
571 	 * For ctrl_mon groups, move both closid and rmid.
572 	 * For monitor groups, can move the tasks only from
573 	 * their parent CTRL group.
574 	 */
575 
576 	if (rdtgrp->type == RDTCTRL_GROUP) {
577 		WRITE_ONCE(tsk->closid, rdtgrp->closid);
578 		WRITE_ONCE(tsk->rmid, rdtgrp->mon.rmid);
579 	} else if (rdtgrp->type == RDTMON_GROUP) {
580 		if (rdtgrp->mon.parent->closid == tsk->closid) {
581 			WRITE_ONCE(tsk->rmid, rdtgrp->mon.rmid);
582 		} else {
583 			rdt_last_cmd_puts("Can't move task to different control group\n");
584 			return -EINVAL;
585 		}
586 	}
587 
588 	/*
589 	 * Ensure the task's closid and rmid are written before determining if
590 	 * the task is current that will decide if it will be interrupted.
591 	 * This pairs with the full barrier between the rq->curr update and
592 	 * resctrl_sched_in() during context switch.
593 	 */
594 	smp_mb();
595 
596 	/*
597 	 * By now, the task's closid and rmid are set. If the task is current
598 	 * on a CPU, the PQR_ASSOC MSR needs to be updated to make the resource
599 	 * group go into effect. If the task is not current, the MSR will be
600 	 * updated when the task is scheduled in.
601 	 */
602 	update_task_closid_rmid(tsk);
603 
604 	return 0;
605 }
606 
607 static bool is_closid_match(struct task_struct *t, struct rdtgroup *r)
608 {
609 	return (rdt_alloc_capable &&
610 	       (r->type == RDTCTRL_GROUP) && (t->closid == r->closid));
611 }
612 
613 static bool is_rmid_match(struct task_struct *t, struct rdtgroup *r)
614 {
615 	return (rdt_mon_capable &&
616 	       (r->type == RDTMON_GROUP) && (t->rmid == r->mon.rmid));
617 }
618 
619 /**
620  * rdtgroup_tasks_assigned - Test if tasks have been assigned to resource group
621  * @r: Resource group
622  *
623  * Return: 1 if tasks have been assigned to @r, 0 otherwise
624  */
625 int rdtgroup_tasks_assigned(struct rdtgroup *r)
626 {
627 	struct task_struct *p, *t;
628 	int ret = 0;
629 
630 	lockdep_assert_held(&rdtgroup_mutex);
631 
632 	rcu_read_lock();
633 	for_each_process_thread(p, t) {
634 		if (is_closid_match(t, r) || is_rmid_match(t, r)) {
635 			ret = 1;
636 			break;
637 		}
638 	}
639 	rcu_read_unlock();
640 
641 	return ret;
642 }
643 
644 static int rdtgroup_task_write_permission(struct task_struct *task,
645 					  struct kernfs_open_file *of)
646 {
647 	const struct cred *tcred = get_task_cred(task);
648 	const struct cred *cred = current_cred();
649 	int ret = 0;
650 
651 	/*
652 	 * Even if we're attaching all tasks in the thread group, we only
653 	 * need to check permissions on one of them.
654 	 */
655 	if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
656 	    !uid_eq(cred->euid, tcred->uid) &&
657 	    !uid_eq(cred->euid, tcred->suid)) {
658 		rdt_last_cmd_printf("No permission to move task %d\n", task->pid);
659 		ret = -EPERM;
660 	}
661 
662 	put_cred(tcred);
663 	return ret;
664 }
665 
666 static int rdtgroup_move_task(pid_t pid, struct rdtgroup *rdtgrp,
667 			      struct kernfs_open_file *of)
668 {
669 	struct task_struct *tsk;
670 	int ret;
671 
672 	rcu_read_lock();
673 	if (pid) {
674 		tsk = find_task_by_vpid(pid);
675 		if (!tsk) {
676 			rcu_read_unlock();
677 			rdt_last_cmd_printf("No task %d\n", pid);
678 			return -ESRCH;
679 		}
680 	} else {
681 		tsk = current;
682 	}
683 
684 	get_task_struct(tsk);
685 	rcu_read_unlock();
686 
687 	ret = rdtgroup_task_write_permission(tsk, of);
688 	if (!ret)
689 		ret = __rdtgroup_move_task(tsk, rdtgrp);
690 
691 	put_task_struct(tsk);
692 	return ret;
693 }
694 
695 static ssize_t rdtgroup_tasks_write(struct kernfs_open_file *of,
696 				    char *buf, size_t nbytes, loff_t off)
697 {
698 	struct rdtgroup *rdtgrp;
699 	int ret = 0;
700 	pid_t pid;
701 
702 	if (kstrtoint(strstrip(buf), 0, &pid) || pid < 0)
703 		return -EINVAL;
704 	rdtgrp = rdtgroup_kn_lock_live(of->kn);
705 	if (!rdtgrp) {
706 		rdtgroup_kn_unlock(of->kn);
707 		return -ENOENT;
708 	}
709 	rdt_last_cmd_clear();
710 
711 	if (rdtgrp->mode == RDT_MODE_PSEUDO_LOCKED ||
712 	    rdtgrp->mode == RDT_MODE_PSEUDO_LOCKSETUP) {
713 		ret = -EINVAL;
714 		rdt_last_cmd_puts("Pseudo-locking in progress\n");
715 		goto unlock;
716 	}
717 
718 	ret = rdtgroup_move_task(pid, rdtgrp, of);
719 
720 unlock:
721 	rdtgroup_kn_unlock(of->kn);
722 
723 	return ret ?: nbytes;
724 }
725 
726 static void show_rdt_tasks(struct rdtgroup *r, struct seq_file *s)
727 {
728 	struct task_struct *p, *t;
729 
730 	rcu_read_lock();
731 	for_each_process_thread(p, t) {
732 		if (is_closid_match(t, r) || is_rmid_match(t, r))
733 			seq_printf(s, "%d\n", t->pid);
734 	}
735 	rcu_read_unlock();
736 }
737 
738 static int rdtgroup_tasks_show(struct kernfs_open_file *of,
739 			       struct seq_file *s, void *v)
740 {
741 	struct rdtgroup *rdtgrp;
742 	int ret = 0;
743 
744 	rdtgrp = rdtgroup_kn_lock_live(of->kn);
745 	if (rdtgrp)
746 		show_rdt_tasks(rdtgrp, s);
747 	else
748 		ret = -ENOENT;
749 	rdtgroup_kn_unlock(of->kn);
750 
751 	return ret;
752 }
753 
754 #ifdef CONFIG_PROC_CPU_RESCTRL
755 
756 /*
757  * A task can only be part of one resctrl control group and of one monitor
758  * group which is associated to that control group.
759  *
760  * 1)   res:
761  *      mon:
762  *
763  *    resctrl is not available.
764  *
765  * 2)   res:/
766  *      mon:
767  *
768  *    Task is part of the root resctrl control group, and it is not associated
769  *    to any monitor group.
770  *
771  * 3)  res:/
772  *     mon:mon0
773  *
774  *    Task is part of the root resctrl control group and monitor group mon0.
775  *
776  * 4)  res:group0
777  *     mon:
778  *
779  *    Task is part of resctrl control group group0, and it is not associated
780  *    to any monitor group.
781  *
782  * 5) res:group0
783  *    mon:mon1
784  *
785  *    Task is part of resctrl control group group0 and monitor group mon1.
786  */
787 int proc_resctrl_show(struct seq_file *s, struct pid_namespace *ns,
788 		      struct pid *pid, struct task_struct *tsk)
789 {
790 	struct rdtgroup *rdtg;
791 	int ret = 0;
792 
793 	mutex_lock(&rdtgroup_mutex);
794 
795 	/* Return empty if resctrl has not been mounted. */
796 	if (!static_branch_unlikely(&rdt_enable_key)) {
797 		seq_puts(s, "res:\nmon:\n");
798 		goto unlock;
799 	}
800 
801 	list_for_each_entry(rdtg, &rdt_all_groups, rdtgroup_list) {
802 		struct rdtgroup *crg;
803 
804 		/*
805 		 * Task information is only relevant for shareable
806 		 * and exclusive groups.
807 		 */
808 		if (rdtg->mode != RDT_MODE_SHAREABLE &&
809 		    rdtg->mode != RDT_MODE_EXCLUSIVE)
810 			continue;
811 
812 		if (rdtg->closid != tsk->closid)
813 			continue;
814 
815 		seq_printf(s, "res:%s%s\n", (rdtg == &rdtgroup_default) ? "/" : "",
816 			   rdtg->kn->name);
817 		seq_puts(s, "mon:");
818 		list_for_each_entry(crg, &rdtg->mon.crdtgrp_list,
819 				    mon.crdtgrp_list) {
820 			if (tsk->rmid != crg->mon.rmid)
821 				continue;
822 			seq_printf(s, "%s", crg->kn->name);
823 			break;
824 		}
825 		seq_putc(s, '\n');
826 		goto unlock;
827 	}
828 	/*
829 	 * The above search should succeed. Otherwise return
830 	 * with an error.
831 	 */
832 	ret = -ENOENT;
833 unlock:
834 	mutex_unlock(&rdtgroup_mutex);
835 
836 	return ret;
837 }
838 #endif
839 
840 static int rdt_last_cmd_status_show(struct kernfs_open_file *of,
841 				    struct seq_file *seq, void *v)
842 {
843 	int len;
844 
845 	mutex_lock(&rdtgroup_mutex);
846 	len = seq_buf_used(&last_cmd_status);
847 	if (len)
848 		seq_printf(seq, "%.*s", len, last_cmd_status_buf);
849 	else
850 		seq_puts(seq, "ok\n");
851 	mutex_unlock(&rdtgroup_mutex);
852 	return 0;
853 }
854 
855 static int rdt_num_closids_show(struct kernfs_open_file *of,
856 				struct seq_file *seq, void *v)
857 {
858 	struct resctrl_schema *s = of->kn->parent->priv;
859 
860 	seq_printf(seq, "%u\n", s->num_closid);
861 	return 0;
862 }
863 
864 static int rdt_default_ctrl_show(struct kernfs_open_file *of,
865 			     struct seq_file *seq, void *v)
866 {
867 	struct resctrl_schema *s = of->kn->parent->priv;
868 	struct rdt_resource *r = s->res;
869 
870 	seq_printf(seq, "%x\n", r->default_ctrl);
871 	return 0;
872 }
873 
874 static int rdt_min_cbm_bits_show(struct kernfs_open_file *of,
875 			     struct seq_file *seq, void *v)
876 {
877 	struct resctrl_schema *s = of->kn->parent->priv;
878 	struct rdt_resource *r = s->res;
879 
880 	seq_printf(seq, "%u\n", r->cache.min_cbm_bits);
881 	return 0;
882 }
883 
884 static int rdt_shareable_bits_show(struct kernfs_open_file *of,
885 				   struct seq_file *seq, void *v)
886 {
887 	struct resctrl_schema *s = of->kn->parent->priv;
888 	struct rdt_resource *r = s->res;
889 
890 	seq_printf(seq, "%x\n", r->cache.shareable_bits);
891 	return 0;
892 }
893 
894 /**
895  * rdt_bit_usage_show - Display current usage of resources
896  *
897  * A domain is a shared resource that can now be allocated differently. Here
898  * we display the current regions of the domain as an annotated bitmask.
899  * For each domain of this resource its allocation bitmask
900  * is annotated as below to indicate the current usage of the corresponding bit:
901  *   0 - currently unused
902  *   X - currently available for sharing and used by software and hardware
903  *   H - currently used by hardware only but available for software use
904  *   S - currently used and shareable by software only
905  *   E - currently used exclusively by one resource group
906  *   P - currently pseudo-locked by one resource group
907  */
908 static int rdt_bit_usage_show(struct kernfs_open_file *of,
909 			      struct seq_file *seq, void *v)
910 {
911 	struct resctrl_schema *s = of->kn->parent->priv;
912 	/*
913 	 * Use unsigned long even though only 32 bits are used to ensure
914 	 * test_bit() is used safely.
915 	 */
916 	unsigned long sw_shareable = 0, hw_shareable = 0;
917 	unsigned long exclusive = 0, pseudo_locked = 0;
918 	struct rdt_resource *r = s->res;
919 	struct rdt_domain *dom;
920 	int i, hwb, swb, excl, psl;
921 	enum rdtgrp_mode mode;
922 	bool sep = false;
923 	u32 ctrl_val;
924 
925 	mutex_lock(&rdtgroup_mutex);
926 	hw_shareable = r->cache.shareable_bits;
927 	list_for_each_entry(dom, &r->domains, list) {
928 		if (sep)
929 			seq_putc(seq, ';');
930 		sw_shareable = 0;
931 		exclusive = 0;
932 		seq_printf(seq, "%d=", dom->id);
933 		for (i = 0; i < closids_supported(); i++) {
934 			if (!closid_allocated(i))
935 				continue;
936 			ctrl_val = resctrl_arch_get_config(r, dom, i,
937 							   s->conf_type);
938 			mode = rdtgroup_mode_by_closid(i);
939 			switch (mode) {
940 			case RDT_MODE_SHAREABLE:
941 				sw_shareable |= ctrl_val;
942 				break;
943 			case RDT_MODE_EXCLUSIVE:
944 				exclusive |= ctrl_val;
945 				break;
946 			case RDT_MODE_PSEUDO_LOCKSETUP:
947 			/*
948 			 * RDT_MODE_PSEUDO_LOCKSETUP is possible
949 			 * here but not included since the CBM
950 			 * associated with this CLOSID in this mode
951 			 * is not initialized and no task or cpu can be
952 			 * assigned this CLOSID.
953 			 */
954 				break;
955 			case RDT_MODE_PSEUDO_LOCKED:
956 			case RDT_NUM_MODES:
957 				WARN(1,
958 				     "invalid mode for closid %d\n", i);
959 				break;
960 			}
961 		}
962 		for (i = r->cache.cbm_len - 1; i >= 0; i--) {
963 			pseudo_locked = dom->plr ? dom->plr->cbm : 0;
964 			hwb = test_bit(i, &hw_shareable);
965 			swb = test_bit(i, &sw_shareable);
966 			excl = test_bit(i, &exclusive);
967 			psl = test_bit(i, &pseudo_locked);
968 			if (hwb && swb)
969 				seq_putc(seq, 'X');
970 			else if (hwb && !swb)
971 				seq_putc(seq, 'H');
972 			else if (!hwb && swb)
973 				seq_putc(seq, 'S');
974 			else if (excl)
975 				seq_putc(seq, 'E');
976 			else if (psl)
977 				seq_putc(seq, 'P');
978 			else /* Unused bits remain */
979 				seq_putc(seq, '0');
980 		}
981 		sep = true;
982 	}
983 	seq_putc(seq, '\n');
984 	mutex_unlock(&rdtgroup_mutex);
985 	return 0;
986 }
987 
988 static int rdt_min_bw_show(struct kernfs_open_file *of,
989 			     struct seq_file *seq, void *v)
990 {
991 	struct resctrl_schema *s = of->kn->parent->priv;
992 	struct rdt_resource *r = s->res;
993 
994 	seq_printf(seq, "%u\n", r->membw.min_bw);
995 	return 0;
996 }
997 
998 static int rdt_num_rmids_show(struct kernfs_open_file *of,
999 			      struct seq_file *seq, void *v)
1000 {
1001 	struct rdt_resource *r = of->kn->parent->priv;
1002 
1003 	seq_printf(seq, "%d\n", r->num_rmid);
1004 
1005 	return 0;
1006 }
1007 
1008 static int rdt_mon_features_show(struct kernfs_open_file *of,
1009 				 struct seq_file *seq, void *v)
1010 {
1011 	struct rdt_resource *r = of->kn->parent->priv;
1012 	struct mon_evt *mevt;
1013 
1014 	list_for_each_entry(mevt, &r->evt_list, list) {
1015 		seq_printf(seq, "%s\n", mevt->name);
1016 		if (mevt->configurable)
1017 			seq_printf(seq, "%s_config\n", mevt->name);
1018 	}
1019 
1020 	return 0;
1021 }
1022 
1023 static int rdt_bw_gran_show(struct kernfs_open_file *of,
1024 			     struct seq_file *seq, void *v)
1025 {
1026 	struct resctrl_schema *s = of->kn->parent->priv;
1027 	struct rdt_resource *r = s->res;
1028 
1029 	seq_printf(seq, "%u\n", r->membw.bw_gran);
1030 	return 0;
1031 }
1032 
1033 static int rdt_delay_linear_show(struct kernfs_open_file *of,
1034 			     struct seq_file *seq, void *v)
1035 {
1036 	struct resctrl_schema *s = of->kn->parent->priv;
1037 	struct rdt_resource *r = s->res;
1038 
1039 	seq_printf(seq, "%u\n", r->membw.delay_linear);
1040 	return 0;
1041 }
1042 
1043 static int max_threshold_occ_show(struct kernfs_open_file *of,
1044 				  struct seq_file *seq, void *v)
1045 {
1046 	seq_printf(seq, "%u\n", resctrl_rmid_realloc_threshold);
1047 
1048 	return 0;
1049 }
1050 
1051 static int rdt_thread_throttle_mode_show(struct kernfs_open_file *of,
1052 					 struct seq_file *seq, void *v)
1053 {
1054 	struct resctrl_schema *s = of->kn->parent->priv;
1055 	struct rdt_resource *r = s->res;
1056 
1057 	if (r->membw.throttle_mode == THREAD_THROTTLE_PER_THREAD)
1058 		seq_puts(seq, "per-thread\n");
1059 	else
1060 		seq_puts(seq, "max\n");
1061 
1062 	return 0;
1063 }
1064 
1065 static ssize_t max_threshold_occ_write(struct kernfs_open_file *of,
1066 				       char *buf, size_t nbytes, loff_t off)
1067 {
1068 	unsigned int bytes;
1069 	int ret;
1070 
1071 	ret = kstrtouint(buf, 0, &bytes);
1072 	if (ret)
1073 		return ret;
1074 
1075 	if (bytes > resctrl_rmid_realloc_limit)
1076 		return -EINVAL;
1077 
1078 	resctrl_rmid_realloc_threshold = resctrl_arch_round_mon_val(bytes);
1079 
1080 	return nbytes;
1081 }
1082 
1083 /*
1084  * rdtgroup_mode_show - Display mode of this resource group
1085  */
1086 static int rdtgroup_mode_show(struct kernfs_open_file *of,
1087 			      struct seq_file *s, void *v)
1088 {
1089 	struct rdtgroup *rdtgrp;
1090 
1091 	rdtgrp = rdtgroup_kn_lock_live(of->kn);
1092 	if (!rdtgrp) {
1093 		rdtgroup_kn_unlock(of->kn);
1094 		return -ENOENT;
1095 	}
1096 
1097 	seq_printf(s, "%s\n", rdtgroup_mode_str(rdtgrp->mode));
1098 
1099 	rdtgroup_kn_unlock(of->kn);
1100 	return 0;
1101 }
1102 
1103 static enum resctrl_conf_type resctrl_peer_type(enum resctrl_conf_type my_type)
1104 {
1105 	switch (my_type) {
1106 	case CDP_CODE:
1107 		return CDP_DATA;
1108 	case CDP_DATA:
1109 		return CDP_CODE;
1110 	default:
1111 	case CDP_NONE:
1112 		return CDP_NONE;
1113 	}
1114 }
1115 
1116 /**
1117  * __rdtgroup_cbm_overlaps - Does CBM for intended closid overlap with other
1118  * @r: Resource to which domain instance @d belongs.
1119  * @d: The domain instance for which @closid is being tested.
1120  * @cbm: Capacity bitmask being tested.
1121  * @closid: Intended closid for @cbm.
1122  * @exclusive: Only check if overlaps with exclusive resource groups
1123  *
1124  * Checks if provided @cbm intended to be used for @closid on domain
1125  * @d overlaps with any other closids or other hardware usage associated
1126  * with this domain. If @exclusive is true then only overlaps with
1127  * resource groups in exclusive mode will be considered. If @exclusive
1128  * is false then overlaps with any resource group or hardware entities
1129  * will be considered.
1130  *
1131  * @cbm is unsigned long, even if only 32 bits are used, to make the
1132  * bitmap functions work correctly.
1133  *
1134  * Return: false if CBM does not overlap, true if it does.
1135  */
1136 static bool __rdtgroup_cbm_overlaps(struct rdt_resource *r, struct rdt_domain *d,
1137 				    unsigned long cbm, int closid,
1138 				    enum resctrl_conf_type type, bool exclusive)
1139 {
1140 	enum rdtgrp_mode mode;
1141 	unsigned long ctrl_b;
1142 	int i;
1143 
1144 	/* Check for any overlap with regions used by hardware directly */
1145 	if (!exclusive) {
1146 		ctrl_b = r->cache.shareable_bits;
1147 		if (bitmap_intersects(&cbm, &ctrl_b, r->cache.cbm_len))
1148 			return true;
1149 	}
1150 
1151 	/* Check for overlap with other resource groups */
1152 	for (i = 0; i < closids_supported(); i++) {
1153 		ctrl_b = resctrl_arch_get_config(r, d, i, type);
1154 		mode = rdtgroup_mode_by_closid(i);
1155 		if (closid_allocated(i) && i != closid &&
1156 		    mode != RDT_MODE_PSEUDO_LOCKSETUP) {
1157 			if (bitmap_intersects(&cbm, &ctrl_b, r->cache.cbm_len)) {
1158 				if (exclusive) {
1159 					if (mode == RDT_MODE_EXCLUSIVE)
1160 						return true;
1161 					continue;
1162 				}
1163 				return true;
1164 			}
1165 		}
1166 	}
1167 
1168 	return false;
1169 }
1170 
1171 /**
1172  * rdtgroup_cbm_overlaps - Does CBM overlap with other use of hardware
1173  * @s: Schema for the resource to which domain instance @d belongs.
1174  * @d: The domain instance for which @closid is being tested.
1175  * @cbm: Capacity bitmask being tested.
1176  * @closid: Intended closid for @cbm.
1177  * @exclusive: Only check if overlaps with exclusive resource groups
1178  *
1179  * Resources that can be allocated using a CBM can use the CBM to control
1180  * the overlap of these allocations. rdtgroup_cmb_overlaps() is the test
1181  * for overlap. Overlap test is not limited to the specific resource for
1182  * which the CBM is intended though - when dealing with CDP resources that
1183  * share the underlying hardware the overlap check should be performed on
1184  * the CDP resource sharing the hardware also.
1185  *
1186  * Refer to description of __rdtgroup_cbm_overlaps() for the details of the
1187  * overlap test.
1188  *
1189  * Return: true if CBM overlap detected, false if there is no overlap
1190  */
1191 bool rdtgroup_cbm_overlaps(struct resctrl_schema *s, struct rdt_domain *d,
1192 			   unsigned long cbm, int closid, bool exclusive)
1193 {
1194 	enum resctrl_conf_type peer_type = resctrl_peer_type(s->conf_type);
1195 	struct rdt_resource *r = s->res;
1196 
1197 	if (__rdtgroup_cbm_overlaps(r, d, cbm, closid, s->conf_type,
1198 				    exclusive))
1199 		return true;
1200 
1201 	if (!resctrl_arch_get_cdp_enabled(r->rid))
1202 		return false;
1203 	return  __rdtgroup_cbm_overlaps(r, d, cbm, closid, peer_type, exclusive);
1204 }
1205 
1206 /**
1207  * rdtgroup_mode_test_exclusive - Test if this resource group can be exclusive
1208  *
1209  * An exclusive resource group implies that there should be no sharing of
1210  * its allocated resources. At the time this group is considered to be
1211  * exclusive this test can determine if its current schemata supports this
1212  * setting by testing for overlap with all other resource groups.
1213  *
1214  * Return: true if resource group can be exclusive, false if there is overlap
1215  * with allocations of other resource groups and thus this resource group
1216  * cannot be exclusive.
1217  */
1218 static bool rdtgroup_mode_test_exclusive(struct rdtgroup *rdtgrp)
1219 {
1220 	int closid = rdtgrp->closid;
1221 	struct resctrl_schema *s;
1222 	struct rdt_resource *r;
1223 	bool has_cache = false;
1224 	struct rdt_domain *d;
1225 	u32 ctrl;
1226 
1227 	list_for_each_entry(s, &resctrl_schema_all, list) {
1228 		r = s->res;
1229 		if (r->rid == RDT_RESOURCE_MBA || r->rid == RDT_RESOURCE_SMBA)
1230 			continue;
1231 		has_cache = true;
1232 		list_for_each_entry(d, &r->domains, list) {
1233 			ctrl = resctrl_arch_get_config(r, d, closid,
1234 						       s->conf_type);
1235 			if (rdtgroup_cbm_overlaps(s, d, ctrl, closid, false)) {
1236 				rdt_last_cmd_puts("Schemata overlaps\n");
1237 				return false;
1238 			}
1239 		}
1240 	}
1241 
1242 	if (!has_cache) {
1243 		rdt_last_cmd_puts("Cannot be exclusive without CAT/CDP\n");
1244 		return false;
1245 	}
1246 
1247 	return true;
1248 }
1249 
1250 /**
1251  * rdtgroup_mode_write - Modify the resource group's mode
1252  *
1253  */
1254 static ssize_t rdtgroup_mode_write(struct kernfs_open_file *of,
1255 				   char *buf, size_t nbytes, loff_t off)
1256 {
1257 	struct rdtgroup *rdtgrp;
1258 	enum rdtgrp_mode mode;
1259 	int ret = 0;
1260 
1261 	/* Valid input requires a trailing newline */
1262 	if (nbytes == 0 || buf[nbytes - 1] != '\n')
1263 		return -EINVAL;
1264 	buf[nbytes - 1] = '\0';
1265 
1266 	rdtgrp = rdtgroup_kn_lock_live(of->kn);
1267 	if (!rdtgrp) {
1268 		rdtgroup_kn_unlock(of->kn);
1269 		return -ENOENT;
1270 	}
1271 
1272 	rdt_last_cmd_clear();
1273 
1274 	mode = rdtgrp->mode;
1275 
1276 	if ((!strcmp(buf, "shareable") && mode == RDT_MODE_SHAREABLE) ||
1277 	    (!strcmp(buf, "exclusive") && mode == RDT_MODE_EXCLUSIVE) ||
1278 	    (!strcmp(buf, "pseudo-locksetup") &&
1279 	     mode == RDT_MODE_PSEUDO_LOCKSETUP) ||
1280 	    (!strcmp(buf, "pseudo-locked") && mode == RDT_MODE_PSEUDO_LOCKED))
1281 		goto out;
1282 
1283 	if (mode == RDT_MODE_PSEUDO_LOCKED) {
1284 		rdt_last_cmd_puts("Cannot change pseudo-locked group\n");
1285 		ret = -EINVAL;
1286 		goto out;
1287 	}
1288 
1289 	if (!strcmp(buf, "shareable")) {
1290 		if (rdtgrp->mode == RDT_MODE_PSEUDO_LOCKSETUP) {
1291 			ret = rdtgroup_locksetup_exit(rdtgrp);
1292 			if (ret)
1293 				goto out;
1294 		}
1295 		rdtgrp->mode = RDT_MODE_SHAREABLE;
1296 	} else if (!strcmp(buf, "exclusive")) {
1297 		if (!rdtgroup_mode_test_exclusive(rdtgrp)) {
1298 			ret = -EINVAL;
1299 			goto out;
1300 		}
1301 		if (rdtgrp->mode == RDT_MODE_PSEUDO_LOCKSETUP) {
1302 			ret = rdtgroup_locksetup_exit(rdtgrp);
1303 			if (ret)
1304 				goto out;
1305 		}
1306 		rdtgrp->mode = RDT_MODE_EXCLUSIVE;
1307 	} else if (!strcmp(buf, "pseudo-locksetup")) {
1308 		ret = rdtgroup_locksetup_enter(rdtgrp);
1309 		if (ret)
1310 			goto out;
1311 		rdtgrp->mode = RDT_MODE_PSEUDO_LOCKSETUP;
1312 	} else {
1313 		rdt_last_cmd_puts("Unknown or unsupported mode\n");
1314 		ret = -EINVAL;
1315 	}
1316 
1317 out:
1318 	rdtgroup_kn_unlock(of->kn);
1319 	return ret ?: nbytes;
1320 }
1321 
1322 /**
1323  * rdtgroup_cbm_to_size - Translate CBM to size in bytes
1324  * @r: RDT resource to which @d belongs.
1325  * @d: RDT domain instance.
1326  * @cbm: bitmask for which the size should be computed.
1327  *
1328  * The bitmask provided associated with the RDT domain instance @d will be
1329  * translated into how many bytes it represents. The size in bytes is
1330  * computed by first dividing the total cache size by the CBM length to
1331  * determine how many bytes each bit in the bitmask represents. The result
1332  * is multiplied with the number of bits set in the bitmask.
1333  *
1334  * @cbm is unsigned long, even if only 32 bits are used to make the
1335  * bitmap functions work correctly.
1336  */
1337 unsigned int rdtgroup_cbm_to_size(struct rdt_resource *r,
1338 				  struct rdt_domain *d, unsigned long cbm)
1339 {
1340 	struct cpu_cacheinfo *ci;
1341 	unsigned int size = 0;
1342 	int num_b, i;
1343 
1344 	num_b = bitmap_weight(&cbm, r->cache.cbm_len);
1345 	ci = get_cpu_cacheinfo(cpumask_any(&d->cpu_mask));
1346 	for (i = 0; i < ci->num_leaves; i++) {
1347 		if (ci->info_list[i].level == r->cache_level) {
1348 			size = ci->info_list[i].size / r->cache.cbm_len * num_b;
1349 			break;
1350 		}
1351 	}
1352 
1353 	return size;
1354 }
1355 
1356 /**
1357  * rdtgroup_size_show - Display size in bytes of allocated regions
1358  *
1359  * The "size" file mirrors the layout of the "schemata" file, printing the
1360  * size in bytes of each region instead of the capacity bitmask.
1361  *
1362  */
1363 static int rdtgroup_size_show(struct kernfs_open_file *of,
1364 			      struct seq_file *s, void *v)
1365 {
1366 	struct resctrl_schema *schema;
1367 	enum resctrl_conf_type type;
1368 	struct rdtgroup *rdtgrp;
1369 	struct rdt_resource *r;
1370 	struct rdt_domain *d;
1371 	unsigned int size;
1372 	int ret = 0;
1373 	u32 closid;
1374 	bool sep;
1375 	u32 ctrl;
1376 
1377 	rdtgrp = rdtgroup_kn_lock_live(of->kn);
1378 	if (!rdtgrp) {
1379 		rdtgroup_kn_unlock(of->kn);
1380 		return -ENOENT;
1381 	}
1382 
1383 	if (rdtgrp->mode == RDT_MODE_PSEUDO_LOCKED) {
1384 		if (!rdtgrp->plr->d) {
1385 			rdt_last_cmd_clear();
1386 			rdt_last_cmd_puts("Cache domain offline\n");
1387 			ret = -ENODEV;
1388 		} else {
1389 			seq_printf(s, "%*s:", max_name_width,
1390 				   rdtgrp->plr->s->name);
1391 			size = rdtgroup_cbm_to_size(rdtgrp->plr->s->res,
1392 						    rdtgrp->plr->d,
1393 						    rdtgrp->plr->cbm);
1394 			seq_printf(s, "%d=%u\n", rdtgrp->plr->d->id, size);
1395 		}
1396 		goto out;
1397 	}
1398 
1399 	closid = rdtgrp->closid;
1400 
1401 	list_for_each_entry(schema, &resctrl_schema_all, list) {
1402 		r = schema->res;
1403 		type = schema->conf_type;
1404 		sep = false;
1405 		seq_printf(s, "%*s:", max_name_width, schema->name);
1406 		list_for_each_entry(d, &r->domains, list) {
1407 			if (sep)
1408 				seq_putc(s, ';');
1409 			if (rdtgrp->mode == RDT_MODE_PSEUDO_LOCKSETUP) {
1410 				size = 0;
1411 			} else {
1412 				if (is_mba_sc(r))
1413 					ctrl = d->mbps_val[closid];
1414 				else
1415 					ctrl = resctrl_arch_get_config(r, d,
1416 								       closid,
1417 								       type);
1418 				if (r->rid == RDT_RESOURCE_MBA ||
1419 				    r->rid == RDT_RESOURCE_SMBA)
1420 					size = ctrl;
1421 				else
1422 					size = rdtgroup_cbm_to_size(r, d, ctrl);
1423 			}
1424 			seq_printf(s, "%d=%u", d->id, size);
1425 			sep = true;
1426 		}
1427 		seq_putc(s, '\n');
1428 	}
1429 
1430 out:
1431 	rdtgroup_kn_unlock(of->kn);
1432 
1433 	return ret;
1434 }
1435 
1436 struct mon_config_info {
1437 	u32 evtid;
1438 	u32 mon_config;
1439 };
1440 
1441 #define INVALID_CONFIG_INDEX   UINT_MAX
1442 
1443 /**
1444  * mon_event_config_index_get - get the hardware index for the
1445  *                              configurable event
1446  * @evtid: event id.
1447  *
1448  * Return: 0 for evtid == QOS_L3_MBM_TOTAL_EVENT_ID
1449  *         1 for evtid == QOS_L3_MBM_LOCAL_EVENT_ID
1450  *         INVALID_CONFIG_INDEX for invalid evtid
1451  */
1452 static inline unsigned int mon_event_config_index_get(u32 evtid)
1453 {
1454 	switch (evtid) {
1455 	case QOS_L3_MBM_TOTAL_EVENT_ID:
1456 		return 0;
1457 	case QOS_L3_MBM_LOCAL_EVENT_ID:
1458 		return 1;
1459 	default:
1460 		/* Should never reach here */
1461 		return INVALID_CONFIG_INDEX;
1462 	}
1463 }
1464 
1465 static void mon_event_config_read(void *info)
1466 {
1467 	struct mon_config_info *mon_info = info;
1468 	unsigned int index;
1469 	u64 msrval;
1470 
1471 	index = mon_event_config_index_get(mon_info->evtid);
1472 	if (index == INVALID_CONFIG_INDEX) {
1473 		pr_warn_once("Invalid event id %d\n", mon_info->evtid);
1474 		return;
1475 	}
1476 	rdmsrl(MSR_IA32_EVT_CFG_BASE + index, msrval);
1477 
1478 	/* Report only the valid event configuration bits */
1479 	mon_info->mon_config = msrval & MAX_EVT_CONFIG_BITS;
1480 }
1481 
1482 static void mondata_config_read(struct rdt_domain *d, struct mon_config_info *mon_info)
1483 {
1484 	smp_call_function_any(&d->cpu_mask, mon_event_config_read, mon_info, 1);
1485 }
1486 
1487 static int mbm_config_show(struct seq_file *s, struct rdt_resource *r, u32 evtid)
1488 {
1489 	struct mon_config_info mon_info = {0};
1490 	struct rdt_domain *dom;
1491 	bool sep = false;
1492 
1493 	mutex_lock(&rdtgroup_mutex);
1494 
1495 	list_for_each_entry(dom, &r->domains, list) {
1496 		if (sep)
1497 			seq_puts(s, ";");
1498 
1499 		memset(&mon_info, 0, sizeof(struct mon_config_info));
1500 		mon_info.evtid = evtid;
1501 		mondata_config_read(dom, &mon_info);
1502 
1503 		seq_printf(s, "%d=0x%02x", dom->id, mon_info.mon_config);
1504 		sep = true;
1505 	}
1506 	seq_puts(s, "\n");
1507 
1508 	mutex_unlock(&rdtgroup_mutex);
1509 
1510 	return 0;
1511 }
1512 
1513 static int mbm_total_bytes_config_show(struct kernfs_open_file *of,
1514 				       struct seq_file *seq, void *v)
1515 {
1516 	struct rdt_resource *r = of->kn->parent->priv;
1517 
1518 	mbm_config_show(seq, r, QOS_L3_MBM_TOTAL_EVENT_ID);
1519 
1520 	return 0;
1521 }
1522 
1523 static int mbm_local_bytes_config_show(struct kernfs_open_file *of,
1524 				       struct seq_file *seq, void *v)
1525 {
1526 	struct rdt_resource *r = of->kn->parent->priv;
1527 
1528 	mbm_config_show(seq, r, QOS_L3_MBM_LOCAL_EVENT_ID);
1529 
1530 	return 0;
1531 }
1532 
1533 static void mon_event_config_write(void *info)
1534 {
1535 	struct mon_config_info *mon_info = info;
1536 	unsigned int index;
1537 
1538 	index = mon_event_config_index_get(mon_info->evtid);
1539 	if (index == INVALID_CONFIG_INDEX) {
1540 		pr_warn_once("Invalid event id %d\n", mon_info->evtid);
1541 		return;
1542 	}
1543 	wrmsr(MSR_IA32_EVT_CFG_BASE + index, mon_info->mon_config, 0);
1544 }
1545 
1546 static int mbm_config_write_domain(struct rdt_resource *r,
1547 				   struct rdt_domain *d, u32 evtid, u32 val)
1548 {
1549 	struct mon_config_info mon_info = {0};
1550 	int ret = 0;
1551 
1552 	/* mon_config cannot be more than the supported set of events */
1553 	if (val > MAX_EVT_CONFIG_BITS) {
1554 		rdt_last_cmd_puts("Invalid event configuration\n");
1555 		return -EINVAL;
1556 	}
1557 
1558 	/*
1559 	 * Read the current config value first. If both are the same then
1560 	 * no need to write it again.
1561 	 */
1562 	mon_info.evtid = evtid;
1563 	mondata_config_read(d, &mon_info);
1564 	if (mon_info.mon_config == val)
1565 		goto out;
1566 
1567 	mon_info.mon_config = val;
1568 
1569 	/*
1570 	 * Update MSR_IA32_EVT_CFG_BASE MSR on one of the CPUs in the
1571 	 * domain. The MSRs offset from MSR MSR_IA32_EVT_CFG_BASE
1572 	 * are scoped at the domain level. Writing any of these MSRs
1573 	 * on one CPU is observed by all the CPUs in the domain.
1574 	 */
1575 	smp_call_function_any(&d->cpu_mask, mon_event_config_write,
1576 			      &mon_info, 1);
1577 
1578 	/*
1579 	 * When an Event Configuration is changed, the bandwidth counters
1580 	 * for all RMIDs and Events will be cleared by the hardware. The
1581 	 * hardware also sets MSR_IA32_QM_CTR.Unavailable (bit 62) for
1582 	 * every RMID on the next read to any event for every RMID.
1583 	 * Subsequent reads will have MSR_IA32_QM_CTR.Unavailable (bit 62)
1584 	 * cleared while it is tracked by the hardware. Clear the
1585 	 * mbm_local and mbm_total counts for all the RMIDs.
1586 	 */
1587 	resctrl_arch_reset_rmid_all(r, d);
1588 
1589 out:
1590 	return ret;
1591 }
1592 
1593 static int mon_config_write(struct rdt_resource *r, char *tok, u32 evtid)
1594 {
1595 	char *dom_str = NULL, *id_str;
1596 	unsigned long dom_id, val;
1597 	struct rdt_domain *d;
1598 	int ret = 0;
1599 
1600 next:
1601 	if (!tok || tok[0] == '\0')
1602 		return 0;
1603 
1604 	/* Start processing the strings for each domain */
1605 	dom_str = strim(strsep(&tok, ";"));
1606 	id_str = strsep(&dom_str, "=");
1607 
1608 	if (!id_str || kstrtoul(id_str, 10, &dom_id)) {
1609 		rdt_last_cmd_puts("Missing '=' or non-numeric domain id\n");
1610 		return -EINVAL;
1611 	}
1612 
1613 	if (!dom_str || kstrtoul(dom_str, 16, &val)) {
1614 		rdt_last_cmd_puts("Non-numeric event configuration value\n");
1615 		return -EINVAL;
1616 	}
1617 
1618 	list_for_each_entry(d, &r->domains, list) {
1619 		if (d->id == dom_id) {
1620 			ret = mbm_config_write_domain(r, d, evtid, val);
1621 			if (ret)
1622 				return -EINVAL;
1623 			goto next;
1624 		}
1625 	}
1626 
1627 	return -EINVAL;
1628 }
1629 
1630 static ssize_t mbm_total_bytes_config_write(struct kernfs_open_file *of,
1631 					    char *buf, size_t nbytes,
1632 					    loff_t off)
1633 {
1634 	struct rdt_resource *r = of->kn->parent->priv;
1635 	int ret;
1636 
1637 	/* Valid input requires a trailing newline */
1638 	if (nbytes == 0 || buf[nbytes - 1] != '\n')
1639 		return -EINVAL;
1640 
1641 	mutex_lock(&rdtgroup_mutex);
1642 
1643 	rdt_last_cmd_clear();
1644 
1645 	buf[nbytes - 1] = '\0';
1646 
1647 	ret = mon_config_write(r, buf, QOS_L3_MBM_TOTAL_EVENT_ID);
1648 
1649 	mutex_unlock(&rdtgroup_mutex);
1650 
1651 	return ret ?: nbytes;
1652 }
1653 
1654 static ssize_t mbm_local_bytes_config_write(struct kernfs_open_file *of,
1655 					    char *buf, size_t nbytes,
1656 					    loff_t off)
1657 {
1658 	struct rdt_resource *r = of->kn->parent->priv;
1659 	int ret;
1660 
1661 	/* Valid input requires a trailing newline */
1662 	if (nbytes == 0 || buf[nbytes - 1] != '\n')
1663 		return -EINVAL;
1664 
1665 	mutex_lock(&rdtgroup_mutex);
1666 
1667 	rdt_last_cmd_clear();
1668 
1669 	buf[nbytes - 1] = '\0';
1670 
1671 	ret = mon_config_write(r, buf, QOS_L3_MBM_LOCAL_EVENT_ID);
1672 
1673 	mutex_unlock(&rdtgroup_mutex);
1674 
1675 	return ret ?: nbytes;
1676 }
1677 
1678 /* rdtgroup information files for one cache resource. */
1679 static struct rftype res_common_files[] = {
1680 	{
1681 		.name		= "last_cmd_status",
1682 		.mode		= 0444,
1683 		.kf_ops		= &rdtgroup_kf_single_ops,
1684 		.seq_show	= rdt_last_cmd_status_show,
1685 		.fflags		= RF_TOP_INFO,
1686 	},
1687 	{
1688 		.name		= "num_closids",
1689 		.mode		= 0444,
1690 		.kf_ops		= &rdtgroup_kf_single_ops,
1691 		.seq_show	= rdt_num_closids_show,
1692 		.fflags		= RF_CTRL_INFO,
1693 	},
1694 	{
1695 		.name		= "mon_features",
1696 		.mode		= 0444,
1697 		.kf_ops		= &rdtgroup_kf_single_ops,
1698 		.seq_show	= rdt_mon_features_show,
1699 		.fflags		= RF_MON_INFO,
1700 	},
1701 	{
1702 		.name		= "num_rmids",
1703 		.mode		= 0444,
1704 		.kf_ops		= &rdtgroup_kf_single_ops,
1705 		.seq_show	= rdt_num_rmids_show,
1706 		.fflags		= RF_MON_INFO,
1707 	},
1708 	{
1709 		.name		= "cbm_mask",
1710 		.mode		= 0444,
1711 		.kf_ops		= &rdtgroup_kf_single_ops,
1712 		.seq_show	= rdt_default_ctrl_show,
1713 		.fflags		= RF_CTRL_INFO | RFTYPE_RES_CACHE,
1714 	},
1715 	{
1716 		.name		= "min_cbm_bits",
1717 		.mode		= 0444,
1718 		.kf_ops		= &rdtgroup_kf_single_ops,
1719 		.seq_show	= rdt_min_cbm_bits_show,
1720 		.fflags		= RF_CTRL_INFO | RFTYPE_RES_CACHE,
1721 	},
1722 	{
1723 		.name		= "shareable_bits",
1724 		.mode		= 0444,
1725 		.kf_ops		= &rdtgroup_kf_single_ops,
1726 		.seq_show	= rdt_shareable_bits_show,
1727 		.fflags		= RF_CTRL_INFO | RFTYPE_RES_CACHE,
1728 	},
1729 	{
1730 		.name		= "bit_usage",
1731 		.mode		= 0444,
1732 		.kf_ops		= &rdtgroup_kf_single_ops,
1733 		.seq_show	= rdt_bit_usage_show,
1734 		.fflags		= RF_CTRL_INFO | RFTYPE_RES_CACHE,
1735 	},
1736 	{
1737 		.name		= "min_bandwidth",
1738 		.mode		= 0444,
1739 		.kf_ops		= &rdtgroup_kf_single_ops,
1740 		.seq_show	= rdt_min_bw_show,
1741 		.fflags		= RF_CTRL_INFO | RFTYPE_RES_MB,
1742 	},
1743 	{
1744 		.name		= "bandwidth_gran",
1745 		.mode		= 0444,
1746 		.kf_ops		= &rdtgroup_kf_single_ops,
1747 		.seq_show	= rdt_bw_gran_show,
1748 		.fflags		= RF_CTRL_INFO | RFTYPE_RES_MB,
1749 	},
1750 	{
1751 		.name		= "delay_linear",
1752 		.mode		= 0444,
1753 		.kf_ops		= &rdtgroup_kf_single_ops,
1754 		.seq_show	= rdt_delay_linear_show,
1755 		.fflags		= RF_CTRL_INFO | RFTYPE_RES_MB,
1756 	},
1757 	/*
1758 	 * Platform specific which (if any) capabilities are provided by
1759 	 * thread_throttle_mode. Defer "fflags" initialization to platform
1760 	 * discovery.
1761 	 */
1762 	{
1763 		.name		= "thread_throttle_mode",
1764 		.mode		= 0444,
1765 		.kf_ops		= &rdtgroup_kf_single_ops,
1766 		.seq_show	= rdt_thread_throttle_mode_show,
1767 	},
1768 	{
1769 		.name		= "max_threshold_occupancy",
1770 		.mode		= 0644,
1771 		.kf_ops		= &rdtgroup_kf_single_ops,
1772 		.write		= max_threshold_occ_write,
1773 		.seq_show	= max_threshold_occ_show,
1774 		.fflags		= RF_MON_INFO | RFTYPE_RES_CACHE,
1775 	},
1776 	{
1777 		.name		= "mbm_total_bytes_config",
1778 		.mode		= 0644,
1779 		.kf_ops		= &rdtgroup_kf_single_ops,
1780 		.seq_show	= mbm_total_bytes_config_show,
1781 		.write		= mbm_total_bytes_config_write,
1782 	},
1783 	{
1784 		.name		= "mbm_local_bytes_config",
1785 		.mode		= 0644,
1786 		.kf_ops		= &rdtgroup_kf_single_ops,
1787 		.seq_show	= mbm_local_bytes_config_show,
1788 		.write		= mbm_local_bytes_config_write,
1789 	},
1790 	{
1791 		.name		= "cpus",
1792 		.mode		= 0644,
1793 		.kf_ops		= &rdtgroup_kf_single_ops,
1794 		.write		= rdtgroup_cpus_write,
1795 		.seq_show	= rdtgroup_cpus_show,
1796 		.fflags		= RFTYPE_BASE,
1797 	},
1798 	{
1799 		.name		= "cpus_list",
1800 		.mode		= 0644,
1801 		.kf_ops		= &rdtgroup_kf_single_ops,
1802 		.write		= rdtgroup_cpus_write,
1803 		.seq_show	= rdtgroup_cpus_show,
1804 		.flags		= RFTYPE_FLAGS_CPUS_LIST,
1805 		.fflags		= RFTYPE_BASE,
1806 	},
1807 	{
1808 		.name		= "tasks",
1809 		.mode		= 0644,
1810 		.kf_ops		= &rdtgroup_kf_single_ops,
1811 		.write		= rdtgroup_tasks_write,
1812 		.seq_show	= rdtgroup_tasks_show,
1813 		.fflags		= RFTYPE_BASE,
1814 	},
1815 	{
1816 		.name		= "schemata",
1817 		.mode		= 0644,
1818 		.kf_ops		= &rdtgroup_kf_single_ops,
1819 		.write		= rdtgroup_schemata_write,
1820 		.seq_show	= rdtgroup_schemata_show,
1821 		.fflags		= RF_CTRL_BASE,
1822 	},
1823 	{
1824 		.name		= "mode",
1825 		.mode		= 0644,
1826 		.kf_ops		= &rdtgroup_kf_single_ops,
1827 		.write		= rdtgroup_mode_write,
1828 		.seq_show	= rdtgroup_mode_show,
1829 		.fflags		= RF_CTRL_BASE,
1830 	},
1831 	{
1832 		.name		= "size",
1833 		.mode		= 0444,
1834 		.kf_ops		= &rdtgroup_kf_single_ops,
1835 		.seq_show	= rdtgroup_size_show,
1836 		.fflags		= RF_CTRL_BASE,
1837 	},
1838 
1839 };
1840 
1841 static int rdtgroup_add_files(struct kernfs_node *kn, unsigned long fflags)
1842 {
1843 	struct rftype *rfts, *rft;
1844 	int ret, len;
1845 
1846 	rfts = res_common_files;
1847 	len = ARRAY_SIZE(res_common_files);
1848 
1849 	lockdep_assert_held(&rdtgroup_mutex);
1850 
1851 	for (rft = rfts; rft < rfts + len; rft++) {
1852 		if (rft->fflags && ((fflags & rft->fflags) == rft->fflags)) {
1853 			ret = rdtgroup_add_file(kn, rft);
1854 			if (ret)
1855 				goto error;
1856 		}
1857 	}
1858 
1859 	return 0;
1860 error:
1861 	pr_warn("Failed to add %s, err=%d\n", rft->name, ret);
1862 	while (--rft >= rfts) {
1863 		if ((fflags & rft->fflags) == rft->fflags)
1864 			kernfs_remove_by_name(kn, rft->name);
1865 	}
1866 	return ret;
1867 }
1868 
1869 static struct rftype *rdtgroup_get_rftype_by_name(const char *name)
1870 {
1871 	struct rftype *rfts, *rft;
1872 	int len;
1873 
1874 	rfts = res_common_files;
1875 	len = ARRAY_SIZE(res_common_files);
1876 
1877 	for (rft = rfts; rft < rfts + len; rft++) {
1878 		if (!strcmp(rft->name, name))
1879 			return rft;
1880 	}
1881 
1882 	return NULL;
1883 }
1884 
1885 void __init thread_throttle_mode_init(void)
1886 {
1887 	struct rftype *rft;
1888 
1889 	rft = rdtgroup_get_rftype_by_name("thread_throttle_mode");
1890 	if (!rft)
1891 		return;
1892 
1893 	rft->fflags = RF_CTRL_INFO | RFTYPE_RES_MB;
1894 }
1895 
1896 void __init mbm_config_rftype_init(const char *config)
1897 {
1898 	struct rftype *rft;
1899 
1900 	rft = rdtgroup_get_rftype_by_name(config);
1901 	if (rft)
1902 		rft->fflags = RF_MON_INFO | RFTYPE_RES_CACHE;
1903 }
1904 
1905 /**
1906  * rdtgroup_kn_mode_restrict - Restrict user access to named resctrl file
1907  * @r: The resource group with which the file is associated.
1908  * @name: Name of the file
1909  *
1910  * The permissions of named resctrl file, directory, or link are modified
1911  * to not allow read, write, or execute by any user.
1912  *
1913  * WARNING: This function is intended to communicate to the user that the
1914  * resctrl file has been locked down - that it is not relevant to the
1915  * particular state the system finds itself in. It should not be relied
1916  * on to protect from user access because after the file's permissions
1917  * are restricted the user can still change the permissions using chmod
1918  * from the command line.
1919  *
1920  * Return: 0 on success, <0 on failure.
1921  */
1922 int rdtgroup_kn_mode_restrict(struct rdtgroup *r, const char *name)
1923 {
1924 	struct iattr iattr = {.ia_valid = ATTR_MODE,};
1925 	struct kernfs_node *kn;
1926 	int ret = 0;
1927 
1928 	kn = kernfs_find_and_get_ns(r->kn, name, NULL);
1929 	if (!kn)
1930 		return -ENOENT;
1931 
1932 	switch (kernfs_type(kn)) {
1933 	case KERNFS_DIR:
1934 		iattr.ia_mode = S_IFDIR;
1935 		break;
1936 	case KERNFS_FILE:
1937 		iattr.ia_mode = S_IFREG;
1938 		break;
1939 	case KERNFS_LINK:
1940 		iattr.ia_mode = S_IFLNK;
1941 		break;
1942 	}
1943 
1944 	ret = kernfs_setattr(kn, &iattr);
1945 	kernfs_put(kn);
1946 	return ret;
1947 }
1948 
1949 /**
1950  * rdtgroup_kn_mode_restore - Restore user access to named resctrl file
1951  * @r: The resource group with which the file is associated.
1952  * @name: Name of the file
1953  * @mask: Mask of permissions that should be restored
1954  *
1955  * Restore the permissions of the named file. If @name is a directory the
1956  * permissions of its parent will be used.
1957  *
1958  * Return: 0 on success, <0 on failure.
1959  */
1960 int rdtgroup_kn_mode_restore(struct rdtgroup *r, const char *name,
1961 			     umode_t mask)
1962 {
1963 	struct iattr iattr = {.ia_valid = ATTR_MODE,};
1964 	struct kernfs_node *kn, *parent;
1965 	struct rftype *rfts, *rft;
1966 	int ret, len;
1967 
1968 	rfts = res_common_files;
1969 	len = ARRAY_SIZE(res_common_files);
1970 
1971 	for (rft = rfts; rft < rfts + len; rft++) {
1972 		if (!strcmp(rft->name, name))
1973 			iattr.ia_mode = rft->mode & mask;
1974 	}
1975 
1976 	kn = kernfs_find_and_get_ns(r->kn, name, NULL);
1977 	if (!kn)
1978 		return -ENOENT;
1979 
1980 	switch (kernfs_type(kn)) {
1981 	case KERNFS_DIR:
1982 		parent = kernfs_get_parent(kn);
1983 		if (parent) {
1984 			iattr.ia_mode |= parent->mode;
1985 			kernfs_put(parent);
1986 		}
1987 		iattr.ia_mode |= S_IFDIR;
1988 		break;
1989 	case KERNFS_FILE:
1990 		iattr.ia_mode |= S_IFREG;
1991 		break;
1992 	case KERNFS_LINK:
1993 		iattr.ia_mode |= S_IFLNK;
1994 		break;
1995 	}
1996 
1997 	ret = kernfs_setattr(kn, &iattr);
1998 	kernfs_put(kn);
1999 	return ret;
2000 }
2001 
2002 static int rdtgroup_mkdir_info_resdir(void *priv, char *name,
2003 				      unsigned long fflags)
2004 {
2005 	struct kernfs_node *kn_subdir;
2006 	int ret;
2007 
2008 	kn_subdir = kernfs_create_dir(kn_info, name,
2009 				      kn_info->mode, priv);
2010 	if (IS_ERR(kn_subdir))
2011 		return PTR_ERR(kn_subdir);
2012 
2013 	ret = rdtgroup_kn_set_ugid(kn_subdir);
2014 	if (ret)
2015 		return ret;
2016 
2017 	ret = rdtgroup_add_files(kn_subdir, fflags);
2018 	if (!ret)
2019 		kernfs_activate(kn_subdir);
2020 
2021 	return ret;
2022 }
2023 
2024 static int rdtgroup_create_info_dir(struct kernfs_node *parent_kn)
2025 {
2026 	struct resctrl_schema *s;
2027 	struct rdt_resource *r;
2028 	unsigned long fflags;
2029 	char name[32];
2030 	int ret;
2031 
2032 	/* create the directory */
2033 	kn_info = kernfs_create_dir(parent_kn, "info", parent_kn->mode, NULL);
2034 	if (IS_ERR(kn_info))
2035 		return PTR_ERR(kn_info);
2036 
2037 	ret = rdtgroup_add_files(kn_info, RF_TOP_INFO);
2038 	if (ret)
2039 		goto out_destroy;
2040 
2041 	/* loop over enabled controls, these are all alloc_capable */
2042 	list_for_each_entry(s, &resctrl_schema_all, list) {
2043 		r = s->res;
2044 		fflags =  r->fflags | RF_CTRL_INFO;
2045 		ret = rdtgroup_mkdir_info_resdir(s, s->name, fflags);
2046 		if (ret)
2047 			goto out_destroy;
2048 	}
2049 
2050 	for_each_mon_capable_rdt_resource(r) {
2051 		fflags =  r->fflags | RF_MON_INFO;
2052 		sprintf(name, "%s_MON", r->name);
2053 		ret = rdtgroup_mkdir_info_resdir(r, name, fflags);
2054 		if (ret)
2055 			goto out_destroy;
2056 	}
2057 
2058 	ret = rdtgroup_kn_set_ugid(kn_info);
2059 	if (ret)
2060 		goto out_destroy;
2061 
2062 	kernfs_activate(kn_info);
2063 
2064 	return 0;
2065 
2066 out_destroy:
2067 	kernfs_remove(kn_info);
2068 	return ret;
2069 }
2070 
2071 static int
2072 mongroup_create_dir(struct kernfs_node *parent_kn, struct rdtgroup *prgrp,
2073 		    char *name, struct kernfs_node **dest_kn)
2074 {
2075 	struct kernfs_node *kn;
2076 	int ret;
2077 
2078 	/* create the directory */
2079 	kn = kernfs_create_dir(parent_kn, name, parent_kn->mode, prgrp);
2080 	if (IS_ERR(kn))
2081 		return PTR_ERR(kn);
2082 
2083 	if (dest_kn)
2084 		*dest_kn = kn;
2085 
2086 	ret = rdtgroup_kn_set_ugid(kn);
2087 	if (ret)
2088 		goto out_destroy;
2089 
2090 	kernfs_activate(kn);
2091 
2092 	return 0;
2093 
2094 out_destroy:
2095 	kernfs_remove(kn);
2096 	return ret;
2097 }
2098 
2099 static void l3_qos_cfg_update(void *arg)
2100 {
2101 	bool *enable = arg;
2102 
2103 	wrmsrl(MSR_IA32_L3_QOS_CFG, *enable ? L3_QOS_CDP_ENABLE : 0ULL);
2104 }
2105 
2106 static void l2_qos_cfg_update(void *arg)
2107 {
2108 	bool *enable = arg;
2109 
2110 	wrmsrl(MSR_IA32_L2_QOS_CFG, *enable ? L2_QOS_CDP_ENABLE : 0ULL);
2111 }
2112 
2113 static inline bool is_mba_linear(void)
2114 {
2115 	return rdt_resources_all[RDT_RESOURCE_MBA].r_resctrl.membw.delay_linear;
2116 }
2117 
2118 static int set_cache_qos_cfg(int level, bool enable)
2119 {
2120 	void (*update)(void *arg);
2121 	struct rdt_resource *r_l;
2122 	cpumask_var_t cpu_mask;
2123 	struct rdt_domain *d;
2124 	int cpu;
2125 
2126 	if (level == RDT_RESOURCE_L3)
2127 		update = l3_qos_cfg_update;
2128 	else if (level == RDT_RESOURCE_L2)
2129 		update = l2_qos_cfg_update;
2130 	else
2131 		return -EINVAL;
2132 
2133 	if (!zalloc_cpumask_var(&cpu_mask, GFP_KERNEL))
2134 		return -ENOMEM;
2135 
2136 	r_l = &rdt_resources_all[level].r_resctrl;
2137 	list_for_each_entry(d, &r_l->domains, list) {
2138 		if (r_l->cache.arch_has_per_cpu_cfg)
2139 			/* Pick all the CPUs in the domain instance */
2140 			for_each_cpu(cpu, &d->cpu_mask)
2141 				cpumask_set_cpu(cpu, cpu_mask);
2142 		else
2143 			/* Pick one CPU from each domain instance to update MSR */
2144 			cpumask_set_cpu(cpumask_any(&d->cpu_mask), cpu_mask);
2145 	}
2146 
2147 	/* Update QOS_CFG MSR on all the CPUs in cpu_mask */
2148 	on_each_cpu_mask(cpu_mask, update, &enable, 1);
2149 
2150 	free_cpumask_var(cpu_mask);
2151 
2152 	return 0;
2153 }
2154 
2155 /* Restore the qos cfg state when a domain comes online */
2156 void rdt_domain_reconfigure_cdp(struct rdt_resource *r)
2157 {
2158 	struct rdt_hw_resource *hw_res = resctrl_to_arch_res(r);
2159 
2160 	if (!r->cdp_capable)
2161 		return;
2162 
2163 	if (r->rid == RDT_RESOURCE_L2)
2164 		l2_qos_cfg_update(&hw_res->cdp_enabled);
2165 
2166 	if (r->rid == RDT_RESOURCE_L3)
2167 		l3_qos_cfg_update(&hw_res->cdp_enabled);
2168 }
2169 
2170 static int mba_sc_domain_allocate(struct rdt_resource *r, struct rdt_domain *d)
2171 {
2172 	u32 num_closid = resctrl_arch_get_num_closid(r);
2173 	int cpu = cpumask_any(&d->cpu_mask);
2174 	int i;
2175 
2176 	d->mbps_val = kcalloc_node(num_closid, sizeof(*d->mbps_val),
2177 				   GFP_KERNEL, cpu_to_node(cpu));
2178 	if (!d->mbps_val)
2179 		return -ENOMEM;
2180 
2181 	for (i = 0; i < num_closid; i++)
2182 		d->mbps_val[i] = MBA_MAX_MBPS;
2183 
2184 	return 0;
2185 }
2186 
2187 static void mba_sc_domain_destroy(struct rdt_resource *r,
2188 				  struct rdt_domain *d)
2189 {
2190 	kfree(d->mbps_val);
2191 	d->mbps_val = NULL;
2192 }
2193 
2194 /*
2195  * MBA software controller is supported only if
2196  * MBM is supported and MBA is in linear scale.
2197  */
2198 static bool supports_mba_mbps(void)
2199 {
2200 	struct rdt_resource *r = &rdt_resources_all[RDT_RESOURCE_MBA].r_resctrl;
2201 
2202 	return (is_mbm_local_enabled() &&
2203 		r->alloc_capable && is_mba_linear());
2204 }
2205 
2206 /*
2207  * Enable or disable the MBA software controller
2208  * which helps user specify bandwidth in MBps.
2209  */
2210 static int set_mba_sc(bool mba_sc)
2211 {
2212 	struct rdt_resource *r = &rdt_resources_all[RDT_RESOURCE_MBA].r_resctrl;
2213 	u32 num_closid = resctrl_arch_get_num_closid(r);
2214 	struct rdt_domain *d;
2215 	int i;
2216 
2217 	if (!supports_mba_mbps() || mba_sc == is_mba_sc(r))
2218 		return -EINVAL;
2219 
2220 	r->membw.mba_sc = mba_sc;
2221 
2222 	list_for_each_entry(d, &r->domains, list) {
2223 		for (i = 0; i < num_closid; i++)
2224 			d->mbps_val[i] = MBA_MAX_MBPS;
2225 	}
2226 
2227 	return 0;
2228 }
2229 
2230 static int cdp_enable(int level)
2231 {
2232 	struct rdt_resource *r_l = &rdt_resources_all[level].r_resctrl;
2233 	int ret;
2234 
2235 	if (!r_l->alloc_capable)
2236 		return -EINVAL;
2237 
2238 	ret = set_cache_qos_cfg(level, true);
2239 	if (!ret)
2240 		rdt_resources_all[level].cdp_enabled = true;
2241 
2242 	return ret;
2243 }
2244 
2245 static void cdp_disable(int level)
2246 {
2247 	struct rdt_hw_resource *r_hw = &rdt_resources_all[level];
2248 
2249 	if (r_hw->cdp_enabled) {
2250 		set_cache_qos_cfg(level, false);
2251 		r_hw->cdp_enabled = false;
2252 	}
2253 }
2254 
2255 int resctrl_arch_set_cdp_enabled(enum resctrl_res_level l, bool enable)
2256 {
2257 	struct rdt_hw_resource *hw_res = &rdt_resources_all[l];
2258 
2259 	if (!hw_res->r_resctrl.cdp_capable)
2260 		return -EINVAL;
2261 
2262 	if (enable)
2263 		return cdp_enable(l);
2264 
2265 	cdp_disable(l);
2266 
2267 	return 0;
2268 }
2269 
2270 static void cdp_disable_all(void)
2271 {
2272 	if (resctrl_arch_get_cdp_enabled(RDT_RESOURCE_L3))
2273 		resctrl_arch_set_cdp_enabled(RDT_RESOURCE_L3, false);
2274 	if (resctrl_arch_get_cdp_enabled(RDT_RESOURCE_L2))
2275 		resctrl_arch_set_cdp_enabled(RDT_RESOURCE_L2, false);
2276 }
2277 
2278 /*
2279  * We don't allow rdtgroup directories to be created anywhere
2280  * except the root directory. Thus when looking for the rdtgroup
2281  * structure for a kernfs node we are either looking at a directory,
2282  * in which case the rdtgroup structure is pointed at by the "priv"
2283  * field, otherwise we have a file, and need only look to the parent
2284  * to find the rdtgroup.
2285  */
2286 static struct rdtgroup *kernfs_to_rdtgroup(struct kernfs_node *kn)
2287 {
2288 	if (kernfs_type(kn) == KERNFS_DIR) {
2289 		/*
2290 		 * All the resource directories use "kn->priv"
2291 		 * to point to the "struct rdtgroup" for the
2292 		 * resource. "info" and its subdirectories don't
2293 		 * have rdtgroup structures, so return NULL here.
2294 		 */
2295 		if (kn == kn_info || kn->parent == kn_info)
2296 			return NULL;
2297 		else
2298 			return kn->priv;
2299 	} else {
2300 		return kn->parent->priv;
2301 	}
2302 }
2303 
2304 struct rdtgroup *rdtgroup_kn_lock_live(struct kernfs_node *kn)
2305 {
2306 	struct rdtgroup *rdtgrp = kernfs_to_rdtgroup(kn);
2307 
2308 	if (!rdtgrp)
2309 		return NULL;
2310 
2311 	atomic_inc(&rdtgrp->waitcount);
2312 	kernfs_break_active_protection(kn);
2313 
2314 	mutex_lock(&rdtgroup_mutex);
2315 
2316 	/* Was this group deleted while we waited? */
2317 	if (rdtgrp->flags & RDT_DELETED)
2318 		return NULL;
2319 
2320 	return rdtgrp;
2321 }
2322 
2323 void rdtgroup_kn_unlock(struct kernfs_node *kn)
2324 {
2325 	struct rdtgroup *rdtgrp = kernfs_to_rdtgroup(kn);
2326 
2327 	if (!rdtgrp)
2328 		return;
2329 
2330 	mutex_unlock(&rdtgroup_mutex);
2331 
2332 	if (atomic_dec_and_test(&rdtgrp->waitcount) &&
2333 	    (rdtgrp->flags & RDT_DELETED)) {
2334 		if (rdtgrp->mode == RDT_MODE_PSEUDO_LOCKSETUP ||
2335 		    rdtgrp->mode == RDT_MODE_PSEUDO_LOCKED)
2336 			rdtgroup_pseudo_lock_remove(rdtgrp);
2337 		kernfs_unbreak_active_protection(kn);
2338 		rdtgroup_remove(rdtgrp);
2339 	} else {
2340 		kernfs_unbreak_active_protection(kn);
2341 	}
2342 }
2343 
2344 static int mkdir_mondata_all(struct kernfs_node *parent_kn,
2345 			     struct rdtgroup *prgrp,
2346 			     struct kernfs_node **mon_data_kn);
2347 
2348 static int rdt_enable_ctx(struct rdt_fs_context *ctx)
2349 {
2350 	int ret = 0;
2351 
2352 	if (ctx->enable_cdpl2)
2353 		ret = resctrl_arch_set_cdp_enabled(RDT_RESOURCE_L2, true);
2354 
2355 	if (!ret && ctx->enable_cdpl3)
2356 		ret = resctrl_arch_set_cdp_enabled(RDT_RESOURCE_L3, true);
2357 
2358 	if (!ret && ctx->enable_mba_mbps)
2359 		ret = set_mba_sc(true);
2360 
2361 	return ret;
2362 }
2363 
2364 static int schemata_list_add(struct rdt_resource *r, enum resctrl_conf_type type)
2365 {
2366 	struct resctrl_schema *s;
2367 	const char *suffix = "";
2368 	int ret, cl;
2369 
2370 	s = kzalloc(sizeof(*s), GFP_KERNEL);
2371 	if (!s)
2372 		return -ENOMEM;
2373 
2374 	s->res = r;
2375 	s->num_closid = resctrl_arch_get_num_closid(r);
2376 	if (resctrl_arch_get_cdp_enabled(r->rid))
2377 		s->num_closid /= 2;
2378 
2379 	s->conf_type = type;
2380 	switch (type) {
2381 	case CDP_CODE:
2382 		suffix = "CODE";
2383 		break;
2384 	case CDP_DATA:
2385 		suffix = "DATA";
2386 		break;
2387 	case CDP_NONE:
2388 		suffix = "";
2389 		break;
2390 	}
2391 
2392 	ret = snprintf(s->name, sizeof(s->name), "%s%s", r->name, suffix);
2393 	if (ret >= sizeof(s->name)) {
2394 		kfree(s);
2395 		return -EINVAL;
2396 	}
2397 
2398 	cl = strlen(s->name);
2399 
2400 	/*
2401 	 * If CDP is supported by this resource, but not enabled,
2402 	 * include the suffix. This ensures the tabular format of the
2403 	 * schemata file does not change between mounts of the filesystem.
2404 	 */
2405 	if (r->cdp_capable && !resctrl_arch_get_cdp_enabled(r->rid))
2406 		cl += 4;
2407 
2408 	if (cl > max_name_width)
2409 		max_name_width = cl;
2410 
2411 	INIT_LIST_HEAD(&s->list);
2412 	list_add(&s->list, &resctrl_schema_all);
2413 
2414 	return 0;
2415 }
2416 
2417 static int schemata_list_create(void)
2418 {
2419 	struct rdt_resource *r;
2420 	int ret = 0;
2421 
2422 	for_each_alloc_capable_rdt_resource(r) {
2423 		if (resctrl_arch_get_cdp_enabled(r->rid)) {
2424 			ret = schemata_list_add(r, CDP_CODE);
2425 			if (ret)
2426 				break;
2427 
2428 			ret = schemata_list_add(r, CDP_DATA);
2429 		} else {
2430 			ret = schemata_list_add(r, CDP_NONE);
2431 		}
2432 
2433 		if (ret)
2434 			break;
2435 	}
2436 
2437 	return ret;
2438 }
2439 
2440 static void schemata_list_destroy(void)
2441 {
2442 	struct resctrl_schema *s, *tmp;
2443 
2444 	list_for_each_entry_safe(s, tmp, &resctrl_schema_all, list) {
2445 		list_del(&s->list);
2446 		kfree(s);
2447 	}
2448 }
2449 
2450 static int rdt_get_tree(struct fs_context *fc)
2451 {
2452 	struct rdt_fs_context *ctx = rdt_fc2context(fc);
2453 	struct rdt_domain *dom;
2454 	struct rdt_resource *r;
2455 	int ret;
2456 
2457 	cpus_read_lock();
2458 	mutex_lock(&rdtgroup_mutex);
2459 	/*
2460 	 * resctrl file system can only be mounted once.
2461 	 */
2462 	if (static_branch_unlikely(&rdt_enable_key)) {
2463 		ret = -EBUSY;
2464 		goto out;
2465 	}
2466 
2467 	ret = rdt_enable_ctx(ctx);
2468 	if (ret < 0)
2469 		goto out_cdp;
2470 
2471 	ret = schemata_list_create();
2472 	if (ret) {
2473 		schemata_list_destroy();
2474 		goto out_mba;
2475 	}
2476 
2477 	closid_init();
2478 
2479 	ret = rdtgroup_create_info_dir(rdtgroup_default.kn);
2480 	if (ret < 0)
2481 		goto out_schemata_free;
2482 
2483 	if (rdt_mon_capable) {
2484 		ret = mongroup_create_dir(rdtgroup_default.kn,
2485 					  &rdtgroup_default, "mon_groups",
2486 					  &kn_mongrp);
2487 		if (ret < 0)
2488 			goto out_info;
2489 
2490 		ret = mkdir_mondata_all(rdtgroup_default.kn,
2491 					&rdtgroup_default, &kn_mondata);
2492 		if (ret < 0)
2493 			goto out_mongrp;
2494 		rdtgroup_default.mon.mon_data_kn = kn_mondata;
2495 	}
2496 
2497 	ret = rdt_pseudo_lock_init();
2498 	if (ret)
2499 		goto out_mondata;
2500 
2501 	ret = kernfs_get_tree(fc);
2502 	if (ret < 0)
2503 		goto out_psl;
2504 
2505 	if (rdt_alloc_capable)
2506 		static_branch_enable_cpuslocked(&rdt_alloc_enable_key);
2507 	if (rdt_mon_capable)
2508 		static_branch_enable_cpuslocked(&rdt_mon_enable_key);
2509 
2510 	if (rdt_alloc_capable || rdt_mon_capable)
2511 		static_branch_enable_cpuslocked(&rdt_enable_key);
2512 
2513 	if (is_mbm_enabled()) {
2514 		r = &rdt_resources_all[RDT_RESOURCE_L3].r_resctrl;
2515 		list_for_each_entry(dom, &r->domains, list)
2516 			mbm_setup_overflow_handler(dom, MBM_OVERFLOW_INTERVAL);
2517 	}
2518 
2519 	goto out;
2520 
2521 out_psl:
2522 	rdt_pseudo_lock_release();
2523 out_mondata:
2524 	if (rdt_mon_capable)
2525 		kernfs_remove(kn_mondata);
2526 out_mongrp:
2527 	if (rdt_mon_capable)
2528 		kernfs_remove(kn_mongrp);
2529 out_info:
2530 	kernfs_remove(kn_info);
2531 out_schemata_free:
2532 	schemata_list_destroy();
2533 out_mba:
2534 	if (ctx->enable_mba_mbps)
2535 		set_mba_sc(false);
2536 out_cdp:
2537 	cdp_disable_all();
2538 out:
2539 	rdt_last_cmd_clear();
2540 	mutex_unlock(&rdtgroup_mutex);
2541 	cpus_read_unlock();
2542 	return ret;
2543 }
2544 
2545 enum rdt_param {
2546 	Opt_cdp,
2547 	Opt_cdpl2,
2548 	Opt_mba_mbps,
2549 	nr__rdt_params
2550 };
2551 
2552 static const struct fs_parameter_spec rdt_fs_parameters[] = {
2553 	fsparam_flag("cdp",		Opt_cdp),
2554 	fsparam_flag("cdpl2",		Opt_cdpl2),
2555 	fsparam_flag("mba_MBps",	Opt_mba_mbps),
2556 	{}
2557 };
2558 
2559 static int rdt_parse_param(struct fs_context *fc, struct fs_parameter *param)
2560 {
2561 	struct rdt_fs_context *ctx = rdt_fc2context(fc);
2562 	struct fs_parse_result result;
2563 	int opt;
2564 
2565 	opt = fs_parse(fc, rdt_fs_parameters, param, &result);
2566 	if (opt < 0)
2567 		return opt;
2568 
2569 	switch (opt) {
2570 	case Opt_cdp:
2571 		ctx->enable_cdpl3 = true;
2572 		return 0;
2573 	case Opt_cdpl2:
2574 		ctx->enable_cdpl2 = true;
2575 		return 0;
2576 	case Opt_mba_mbps:
2577 		if (!supports_mba_mbps())
2578 			return -EINVAL;
2579 		ctx->enable_mba_mbps = true;
2580 		return 0;
2581 	}
2582 
2583 	return -EINVAL;
2584 }
2585 
2586 static void rdt_fs_context_free(struct fs_context *fc)
2587 {
2588 	struct rdt_fs_context *ctx = rdt_fc2context(fc);
2589 
2590 	kernfs_free_fs_context(fc);
2591 	kfree(ctx);
2592 }
2593 
2594 static const struct fs_context_operations rdt_fs_context_ops = {
2595 	.free		= rdt_fs_context_free,
2596 	.parse_param	= rdt_parse_param,
2597 	.get_tree	= rdt_get_tree,
2598 };
2599 
2600 static int rdt_init_fs_context(struct fs_context *fc)
2601 {
2602 	struct rdt_fs_context *ctx;
2603 
2604 	ctx = kzalloc(sizeof(struct rdt_fs_context), GFP_KERNEL);
2605 	if (!ctx)
2606 		return -ENOMEM;
2607 
2608 	ctx->kfc.root = rdt_root;
2609 	ctx->kfc.magic = RDTGROUP_SUPER_MAGIC;
2610 	fc->fs_private = &ctx->kfc;
2611 	fc->ops = &rdt_fs_context_ops;
2612 	put_user_ns(fc->user_ns);
2613 	fc->user_ns = get_user_ns(&init_user_ns);
2614 	fc->global = true;
2615 	return 0;
2616 }
2617 
2618 static int reset_all_ctrls(struct rdt_resource *r)
2619 {
2620 	struct rdt_hw_resource *hw_res = resctrl_to_arch_res(r);
2621 	struct rdt_hw_domain *hw_dom;
2622 	struct msr_param msr_param;
2623 	cpumask_var_t cpu_mask;
2624 	struct rdt_domain *d;
2625 	int i;
2626 
2627 	if (!zalloc_cpumask_var(&cpu_mask, GFP_KERNEL))
2628 		return -ENOMEM;
2629 
2630 	msr_param.res = r;
2631 	msr_param.low = 0;
2632 	msr_param.high = hw_res->num_closid;
2633 
2634 	/*
2635 	 * Disable resource control for this resource by setting all
2636 	 * CBMs in all domains to the maximum mask value. Pick one CPU
2637 	 * from each domain to update the MSRs below.
2638 	 */
2639 	list_for_each_entry(d, &r->domains, list) {
2640 		hw_dom = resctrl_to_arch_dom(d);
2641 		cpumask_set_cpu(cpumask_any(&d->cpu_mask), cpu_mask);
2642 
2643 		for (i = 0; i < hw_res->num_closid; i++)
2644 			hw_dom->ctrl_val[i] = r->default_ctrl;
2645 	}
2646 
2647 	/* Update CBM on all the CPUs in cpu_mask */
2648 	on_each_cpu_mask(cpu_mask, rdt_ctrl_update, &msr_param, 1);
2649 
2650 	free_cpumask_var(cpu_mask);
2651 
2652 	return 0;
2653 }
2654 
2655 /*
2656  * Move tasks from one to the other group. If @from is NULL, then all tasks
2657  * in the systems are moved unconditionally (used for teardown).
2658  *
2659  * If @mask is not NULL the cpus on which moved tasks are running are set
2660  * in that mask so the update smp function call is restricted to affected
2661  * cpus.
2662  */
2663 static void rdt_move_group_tasks(struct rdtgroup *from, struct rdtgroup *to,
2664 				 struct cpumask *mask)
2665 {
2666 	struct task_struct *p, *t;
2667 
2668 	read_lock(&tasklist_lock);
2669 	for_each_process_thread(p, t) {
2670 		if (!from || is_closid_match(t, from) ||
2671 		    is_rmid_match(t, from)) {
2672 			WRITE_ONCE(t->closid, to->closid);
2673 			WRITE_ONCE(t->rmid, to->mon.rmid);
2674 
2675 			/*
2676 			 * Order the closid/rmid stores above before the loads
2677 			 * in task_curr(). This pairs with the full barrier
2678 			 * between the rq->curr update and resctrl_sched_in()
2679 			 * during context switch.
2680 			 */
2681 			smp_mb();
2682 
2683 			/*
2684 			 * If the task is on a CPU, set the CPU in the mask.
2685 			 * The detection is inaccurate as tasks might move or
2686 			 * schedule before the smp function call takes place.
2687 			 * In such a case the function call is pointless, but
2688 			 * there is no other side effect.
2689 			 */
2690 			if (IS_ENABLED(CONFIG_SMP) && mask && task_curr(t))
2691 				cpumask_set_cpu(task_cpu(t), mask);
2692 		}
2693 	}
2694 	read_unlock(&tasklist_lock);
2695 }
2696 
2697 static void free_all_child_rdtgrp(struct rdtgroup *rdtgrp)
2698 {
2699 	struct rdtgroup *sentry, *stmp;
2700 	struct list_head *head;
2701 
2702 	head = &rdtgrp->mon.crdtgrp_list;
2703 	list_for_each_entry_safe(sentry, stmp, head, mon.crdtgrp_list) {
2704 		free_rmid(sentry->mon.rmid);
2705 		list_del(&sentry->mon.crdtgrp_list);
2706 
2707 		if (atomic_read(&sentry->waitcount) != 0)
2708 			sentry->flags = RDT_DELETED;
2709 		else
2710 			rdtgroup_remove(sentry);
2711 	}
2712 }
2713 
2714 /*
2715  * Forcibly remove all of subdirectories under root.
2716  */
2717 static void rmdir_all_sub(void)
2718 {
2719 	struct rdtgroup *rdtgrp, *tmp;
2720 
2721 	/* Move all tasks to the default resource group */
2722 	rdt_move_group_tasks(NULL, &rdtgroup_default, NULL);
2723 
2724 	list_for_each_entry_safe(rdtgrp, tmp, &rdt_all_groups, rdtgroup_list) {
2725 		/* Free any child rmids */
2726 		free_all_child_rdtgrp(rdtgrp);
2727 
2728 		/* Remove each rdtgroup other than root */
2729 		if (rdtgrp == &rdtgroup_default)
2730 			continue;
2731 
2732 		if (rdtgrp->mode == RDT_MODE_PSEUDO_LOCKSETUP ||
2733 		    rdtgrp->mode == RDT_MODE_PSEUDO_LOCKED)
2734 			rdtgroup_pseudo_lock_remove(rdtgrp);
2735 
2736 		/*
2737 		 * Give any CPUs back to the default group. We cannot copy
2738 		 * cpu_online_mask because a CPU might have executed the
2739 		 * offline callback already, but is still marked online.
2740 		 */
2741 		cpumask_or(&rdtgroup_default.cpu_mask,
2742 			   &rdtgroup_default.cpu_mask, &rdtgrp->cpu_mask);
2743 
2744 		free_rmid(rdtgrp->mon.rmid);
2745 
2746 		kernfs_remove(rdtgrp->kn);
2747 		list_del(&rdtgrp->rdtgroup_list);
2748 
2749 		if (atomic_read(&rdtgrp->waitcount) != 0)
2750 			rdtgrp->flags = RDT_DELETED;
2751 		else
2752 			rdtgroup_remove(rdtgrp);
2753 	}
2754 	/* Notify online CPUs to update per cpu storage and PQR_ASSOC MSR */
2755 	update_closid_rmid(cpu_online_mask, &rdtgroup_default);
2756 
2757 	kernfs_remove(kn_info);
2758 	kernfs_remove(kn_mongrp);
2759 	kernfs_remove(kn_mondata);
2760 }
2761 
2762 static void rdt_kill_sb(struct super_block *sb)
2763 {
2764 	struct rdt_resource *r;
2765 
2766 	cpus_read_lock();
2767 	mutex_lock(&rdtgroup_mutex);
2768 
2769 	set_mba_sc(false);
2770 
2771 	/*Put everything back to default values. */
2772 	for_each_alloc_capable_rdt_resource(r)
2773 		reset_all_ctrls(r);
2774 	cdp_disable_all();
2775 	rmdir_all_sub();
2776 	rdt_pseudo_lock_release();
2777 	rdtgroup_default.mode = RDT_MODE_SHAREABLE;
2778 	schemata_list_destroy();
2779 	static_branch_disable_cpuslocked(&rdt_alloc_enable_key);
2780 	static_branch_disable_cpuslocked(&rdt_mon_enable_key);
2781 	static_branch_disable_cpuslocked(&rdt_enable_key);
2782 	kernfs_kill_sb(sb);
2783 	mutex_unlock(&rdtgroup_mutex);
2784 	cpus_read_unlock();
2785 }
2786 
2787 static struct file_system_type rdt_fs_type = {
2788 	.name			= "resctrl",
2789 	.init_fs_context	= rdt_init_fs_context,
2790 	.parameters		= rdt_fs_parameters,
2791 	.kill_sb		= rdt_kill_sb,
2792 };
2793 
2794 static int mon_addfile(struct kernfs_node *parent_kn, const char *name,
2795 		       void *priv)
2796 {
2797 	struct kernfs_node *kn;
2798 	int ret = 0;
2799 
2800 	kn = __kernfs_create_file(parent_kn, name, 0444,
2801 				  GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, 0,
2802 				  &kf_mondata_ops, priv, NULL, NULL);
2803 	if (IS_ERR(kn))
2804 		return PTR_ERR(kn);
2805 
2806 	ret = rdtgroup_kn_set_ugid(kn);
2807 	if (ret) {
2808 		kernfs_remove(kn);
2809 		return ret;
2810 	}
2811 
2812 	return ret;
2813 }
2814 
2815 /*
2816  * Remove all subdirectories of mon_data of ctrl_mon groups
2817  * and monitor groups with given domain id.
2818  */
2819 static void rmdir_mondata_subdir_allrdtgrp(struct rdt_resource *r,
2820 					   unsigned int dom_id)
2821 {
2822 	struct rdtgroup *prgrp, *crgrp;
2823 	char name[32];
2824 
2825 	list_for_each_entry(prgrp, &rdt_all_groups, rdtgroup_list) {
2826 		sprintf(name, "mon_%s_%02d", r->name, dom_id);
2827 		kernfs_remove_by_name(prgrp->mon.mon_data_kn, name);
2828 
2829 		list_for_each_entry(crgrp, &prgrp->mon.crdtgrp_list, mon.crdtgrp_list)
2830 			kernfs_remove_by_name(crgrp->mon.mon_data_kn, name);
2831 	}
2832 }
2833 
2834 static int mkdir_mondata_subdir(struct kernfs_node *parent_kn,
2835 				struct rdt_domain *d,
2836 				struct rdt_resource *r, struct rdtgroup *prgrp)
2837 {
2838 	union mon_data_bits priv;
2839 	struct kernfs_node *kn;
2840 	struct mon_evt *mevt;
2841 	struct rmid_read rr;
2842 	char name[32];
2843 	int ret;
2844 
2845 	sprintf(name, "mon_%s_%02d", r->name, d->id);
2846 	/* create the directory */
2847 	kn = kernfs_create_dir(parent_kn, name, parent_kn->mode, prgrp);
2848 	if (IS_ERR(kn))
2849 		return PTR_ERR(kn);
2850 
2851 	ret = rdtgroup_kn_set_ugid(kn);
2852 	if (ret)
2853 		goto out_destroy;
2854 
2855 	if (WARN_ON(list_empty(&r->evt_list))) {
2856 		ret = -EPERM;
2857 		goto out_destroy;
2858 	}
2859 
2860 	priv.u.rid = r->rid;
2861 	priv.u.domid = d->id;
2862 	list_for_each_entry(mevt, &r->evt_list, list) {
2863 		priv.u.evtid = mevt->evtid;
2864 		ret = mon_addfile(kn, mevt->name, priv.priv);
2865 		if (ret)
2866 			goto out_destroy;
2867 
2868 		if (is_mbm_event(mevt->evtid))
2869 			mon_event_read(&rr, r, d, prgrp, mevt->evtid, true);
2870 	}
2871 	kernfs_activate(kn);
2872 	return 0;
2873 
2874 out_destroy:
2875 	kernfs_remove(kn);
2876 	return ret;
2877 }
2878 
2879 /*
2880  * Add all subdirectories of mon_data for "ctrl_mon" groups
2881  * and "monitor" groups with given domain id.
2882  */
2883 static void mkdir_mondata_subdir_allrdtgrp(struct rdt_resource *r,
2884 					   struct rdt_domain *d)
2885 {
2886 	struct kernfs_node *parent_kn;
2887 	struct rdtgroup *prgrp, *crgrp;
2888 	struct list_head *head;
2889 
2890 	list_for_each_entry(prgrp, &rdt_all_groups, rdtgroup_list) {
2891 		parent_kn = prgrp->mon.mon_data_kn;
2892 		mkdir_mondata_subdir(parent_kn, d, r, prgrp);
2893 
2894 		head = &prgrp->mon.crdtgrp_list;
2895 		list_for_each_entry(crgrp, head, mon.crdtgrp_list) {
2896 			parent_kn = crgrp->mon.mon_data_kn;
2897 			mkdir_mondata_subdir(parent_kn, d, r, crgrp);
2898 		}
2899 	}
2900 }
2901 
2902 static int mkdir_mondata_subdir_alldom(struct kernfs_node *parent_kn,
2903 				       struct rdt_resource *r,
2904 				       struct rdtgroup *prgrp)
2905 {
2906 	struct rdt_domain *dom;
2907 	int ret;
2908 
2909 	list_for_each_entry(dom, &r->domains, list) {
2910 		ret = mkdir_mondata_subdir(parent_kn, dom, r, prgrp);
2911 		if (ret)
2912 			return ret;
2913 	}
2914 
2915 	return 0;
2916 }
2917 
2918 /*
2919  * This creates a directory mon_data which contains the monitored data.
2920  *
2921  * mon_data has one directory for each domain which are named
2922  * in the format mon_<domain_name>_<domain_id>. For ex: A mon_data
2923  * with L3 domain looks as below:
2924  * ./mon_data:
2925  * mon_L3_00
2926  * mon_L3_01
2927  * mon_L3_02
2928  * ...
2929  *
2930  * Each domain directory has one file per event:
2931  * ./mon_L3_00/:
2932  * llc_occupancy
2933  *
2934  */
2935 static int mkdir_mondata_all(struct kernfs_node *parent_kn,
2936 			     struct rdtgroup *prgrp,
2937 			     struct kernfs_node **dest_kn)
2938 {
2939 	struct rdt_resource *r;
2940 	struct kernfs_node *kn;
2941 	int ret;
2942 
2943 	/*
2944 	 * Create the mon_data directory first.
2945 	 */
2946 	ret = mongroup_create_dir(parent_kn, prgrp, "mon_data", &kn);
2947 	if (ret)
2948 		return ret;
2949 
2950 	if (dest_kn)
2951 		*dest_kn = kn;
2952 
2953 	/*
2954 	 * Create the subdirectories for each domain. Note that all events
2955 	 * in a domain like L3 are grouped into a resource whose domain is L3
2956 	 */
2957 	for_each_mon_capable_rdt_resource(r) {
2958 		ret = mkdir_mondata_subdir_alldom(kn, r, prgrp);
2959 		if (ret)
2960 			goto out_destroy;
2961 	}
2962 
2963 	return 0;
2964 
2965 out_destroy:
2966 	kernfs_remove(kn);
2967 	return ret;
2968 }
2969 
2970 /**
2971  * cbm_ensure_valid - Enforce validity on provided CBM
2972  * @_val:	Candidate CBM
2973  * @r:		RDT resource to which the CBM belongs
2974  *
2975  * The provided CBM represents all cache portions available for use. This
2976  * may be represented by a bitmap that does not consist of contiguous ones
2977  * and thus be an invalid CBM.
2978  * Here the provided CBM is forced to be a valid CBM by only considering
2979  * the first set of contiguous bits as valid and clearing all bits.
2980  * The intention here is to provide a valid default CBM with which a new
2981  * resource group is initialized. The user can follow this with a
2982  * modification to the CBM if the default does not satisfy the
2983  * requirements.
2984  */
2985 static u32 cbm_ensure_valid(u32 _val, struct rdt_resource *r)
2986 {
2987 	unsigned int cbm_len = r->cache.cbm_len;
2988 	unsigned long first_bit, zero_bit;
2989 	unsigned long val = _val;
2990 
2991 	if (!val)
2992 		return 0;
2993 
2994 	first_bit = find_first_bit(&val, cbm_len);
2995 	zero_bit = find_next_zero_bit(&val, cbm_len, first_bit);
2996 
2997 	/* Clear any remaining bits to ensure contiguous region */
2998 	bitmap_clear(&val, zero_bit, cbm_len - zero_bit);
2999 	return (u32)val;
3000 }
3001 
3002 /*
3003  * Initialize cache resources per RDT domain
3004  *
3005  * Set the RDT domain up to start off with all usable allocations. That is,
3006  * all shareable and unused bits. All-zero CBM is invalid.
3007  */
3008 static int __init_one_rdt_domain(struct rdt_domain *d, struct resctrl_schema *s,
3009 				 u32 closid)
3010 {
3011 	enum resctrl_conf_type peer_type = resctrl_peer_type(s->conf_type);
3012 	enum resctrl_conf_type t = s->conf_type;
3013 	struct resctrl_staged_config *cfg;
3014 	struct rdt_resource *r = s->res;
3015 	u32 used_b = 0, unused_b = 0;
3016 	unsigned long tmp_cbm;
3017 	enum rdtgrp_mode mode;
3018 	u32 peer_ctl, ctrl_val;
3019 	int i;
3020 
3021 	cfg = &d->staged_config[t];
3022 	cfg->have_new_ctrl = false;
3023 	cfg->new_ctrl = r->cache.shareable_bits;
3024 	used_b = r->cache.shareable_bits;
3025 	for (i = 0; i < closids_supported(); i++) {
3026 		if (closid_allocated(i) && i != closid) {
3027 			mode = rdtgroup_mode_by_closid(i);
3028 			if (mode == RDT_MODE_PSEUDO_LOCKSETUP)
3029 				/*
3030 				 * ctrl values for locksetup aren't relevant
3031 				 * until the schemata is written, and the mode
3032 				 * becomes RDT_MODE_PSEUDO_LOCKED.
3033 				 */
3034 				continue;
3035 			/*
3036 			 * If CDP is active include peer domain's
3037 			 * usage to ensure there is no overlap
3038 			 * with an exclusive group.
3039 			 */
3040 			if (resctrl_arch_get_cdp_enabled(r->rid))
3041 				peer_ctl = resctrl_arch_get_config(r, d, i,
3042 								   peer_type);
3043 			else
3044 				peer_ctl = 0;
3045 			ctrl_val = resctrl_arch_get_config(r, d, i,
3046 							   s->conf_type);
3047 			used_b |= ctrl_val | peer_ctl;
3048 			if (mode == RDT_MODE_SHAREABLE)
3049 				cfg->new_ctrl |= ctrl_val | peer_ctl;
3050 		}
3051 	}
3052 	if (d->plr && d->plr->cbm > 0)
3053 		used_b |= d->plr->cbm;
3054 	unused_b = used_b ^ (BIT_MASK(r->cache.cbm_len) - 1);
3055 	unused_b &= BIT_MASK(r->cache.cbm_len) - 1;
3056 	cfg->new_ctrl |= unused_b;
3057 	/*
3058 	 * Force the initial CBM to be valid, user can
3059 	 * modify the CBM based on system availability.
3060 	 */
3061 	cfg->new_ctrl = cbm_ensure_valid(cfg->new_ctrl, r);
3062 	/*
3063 	 * Assign the u32 CBM to an unsigned long to ensure that
3064 	 * bitmap_weight() does not access out-of-bound memory.
3065 	 */
3066 	tmp_cbm = cfg->new_ctrl;
3067 	if (bitmap_weight(&tmp_cbm, r->cache.cbm_len) < r->cache.min_cbm_bits) {
3068 		rdt_last_cmd_printf("No space on %s:%d\n", s->name, d->id);
3069 		return -ENOSPC;
3070 	}
3071 	cfg->have_new_ctrl = true;
3072 
3073 	return 0;
3074 }
3075 
3076 /*
3077  * Initialize cache resources with default values.
3078  *
3079  * A new RDT group is being created on an allocation capable (CAT)
3080  * supporting system. Set this group up to start off with all usable
3081  * allocations.
3082  *
3083  * If there are no more shareable bits available on any domain then
3084  * the entire allocation will fail.
3085  */
3086 static int rdtgroup_init_cat(struct resctrl_schema *s, u32 closid)
3087 {
3088 	struct rdt_domain *d;
3089 	int ret;
3090 
3091 	list_for_each_entry(d, &s->res->domains, list) {
3092 		ret = __init_one_rdt_domain(d, s, closid);
3093 		if (ret < 0)
3094 			return ret;
3095 	}
3096 
3097 	return 0;
3098 }
3099 
3100 /* Initialize MBA resource with default values. */
3101 static void rdtgroup_init_mba(struct rdt_resource *r, u32 closid)
3102 {
3103 	struct resctrl_staged_config *cfg;
3104 	struct rdt_domain *d;
3105 
3106 	list_for_each_entry(d, &r->domains, list) {
3107 		if (is_mba_sc(r)) {
3108 			d->mbps_val[closid] = MBA_MAX_MBPS;
3109 			continue;
3110 		}
3111 
3112 		cfg = &d->staged_config[CDP_NONE];
3113 		cfg->new_ctrl = r->default_ctrl;
3114 		cfg->have_new_ctrl = true;
3115 	}
3116 }
3117 
3118 /* Initialize the RDT group's allocations. */
3119 static int rdtgroup_init_alloc(struct rdtgroup *rdtgrp)
3120 {
3121 	struct resctrl_schema *s;
3122 	struct rdt_resource *r;
3123 	int ret = 0;
3124 
3125 	rdt_staged_configs_clear();
3126 
3127 	list_for_each_entry(s, &resctrl_schema_all, list) {
3128 		r = s->res;
3129 		if (r->rid == RDT_RESOURCE_MBA ||
3130 		    r->rid == RDT_RESOURCE_SMBA) {
3131 			rdtgroup_init_mba(r, rdtgrp->closid);
3132 			if (is_mba_sc(r))
3133 				continue;
3134 		} else {
3135 			ret = rdtgroup_init_cat(s, rdtgrp->closid);
3136 			if (ret < 0)
3137 				goto out;
3138 		}
3139 
3140 		ret = resctrl_arch_update_domains(r, rdtgrp->closid);
3141 		if (ret < 0) {
3142 			rdt_last_cmd_puts("Failed to initialize allocations\n");
3143 			goto out;
3144 		}
3145 
3146 	}
3147 
3148 	rdtgrp->mode = RDT_MODE_SHAREABLE;
3149 
3150 out:
3151 	rdt_staged_configs_clear();
3152 	return ret;
3153 }
3154 
3155 static int mkdir_rdt_prepare(struct kernfs_node *parent_kn,
3156 			     const char *name, umode_t mode,
3157 			     enum rdt_group_type rtype, struct rdtgroup **r)
3158 {
3159 	struct rdtgroup *prdtgrp, *rdtgrp;
3160 	struct kernfs_node *kn;
3161 	uint files = 0;
3162 	int ret;
3163 
3164 	prdtgrp = rdtgroup_kn_lock_live(parent_kn);
3165 	if (!prdtgrp) {
3166 		ret = -ENODEV;
3167 		goto out_unlock;
3168 	}
3169 
3170 	if (rtype == RDTMON_GROUP &&
3171 	    (prdtgrp->mode == RDT_MODE_PSEUDO_LOCKSETUP ||
3172 	     prdtgrp->mode == RDT_MODE_PSEUDO_LOCKED)) {
3173 		ret = -EINVAL;
3174 		rdt_last_cmd_puts("Pseudo-locking in progress\n");
3175 		goto out_unlock;
3176 	}
3177 
3178 	/* allocate the rdtgroup. */
3179 	rdtgrp = kzalloc(sizeof(*rdtgrp), GFP_KERNEL);
3180 	if (!rdtgrp) {
3181 		ret = -ENOSPC;
3182 		rdt_last_cmd_puts("Kernel out of memory\n");
3183 		goto out_unlock;
3184 	}
3185 	*r = rdtgrp;
3186 	rdtgrp->mon.parent = prdtgrp;
3187 	rdtgrp->type = rtype;
3188 	INIT_LIST_HEAD(&rdtgrp->mon.crdtgrp_list);
3189 
3190 	/* kernfs creates the directory for rdtgrp */
3191 	kn = kernfs_create_dir(parent_kn, name, mode, rdtgrp);
3192 	if (IS_ERR(kn)) {
3193 		ret = PTR_ERR(kn);
3194 		rdt_last_cmd_puts("kernfs create error\n");
3195 		goto out_free_rgrp;
3196 	}
3197 	rdtgrp->kn = kn;
3198 
3199 	/*
3200 	 * kernfs_remove() will drop the reference count on "kn" which
3201 	 * will free it. But we still need it to stick around for the
3202 	 * rdtgroup_kn_unlock(kn) call. Take one extra reference here,
3203 	 * which will be dropped by kernfs_put() in rdtgroup_remove().
3204 	 */
3205 	kernfs_get(kn);
3206 
3207 	ret = rdtgroup_kn_set_ugid(kn);
3208 	if (ret) {
3209 		rdt_last_cmd_puts("kernfs perm error\n");
3210 		goto out_destroy;
3211 	}
3212 
3213 	files = RFTYPE_BASE | BIT(RF_CTRLSHIFT + rtype);
3214 	ret = rdtgroup_add_files(kn, files);
3215 	if (ret) {
3216 		rdt_last_cmd_puts("kernfs fill error\n");
3217 		goto out_destroy;
3218 	}
3219 
3220 	if (rdt_mon_capable) {
3221 		ret = alloc_rmid();
3222 		if (ret < 0) {
3223 			rdt_last_cmd_puts("Out of RMIDs\n");
3224 			goto out_destroy;
3225 		}
3226 		rdtgrp->mon.rmid = ret;
3227 
3228 		ret = mkdir_mondata_all(kn, rdtgrp, &rdtgrp->mon.mon_data_kn);
3229 		if (ret) {
3230 			rdt_last_cmd_puts("kernfs subdir error\n");
3231 			goto out_idfree;
3232 		}
3233 	}
3234 	kernfs_activate(kn);
3235 
3236 	/*
3237 	 * The caller unlocks the parent_kn upon success.
3238 	 */
3239 	return 0;
3240 
3241 out_idfree:
3242 	free_rmid(rdtgrp->mon.rmid);
3243 out_destroy:
3244 	kernfs_put(rdtgrp->kn);
3245 	kernfs_remove(rdtgrp->kn);
3246 out_free_rgrp:
3247 	kfree(rdtgrp);
3248 out_unlock:
3249 	rdtgroup_kn_unlock(parent_kn);
3250 	return ret;
3251 }
3252 
3253 static void mkdir_rdt_prepare_clean(struct rdtgroup *rgrp)
3254 {
3255 	kernfs_remove(rgrp->kn);
3256 	free_rmid(rgrp->mon.rmid);
3257 	rdtgroup_remove(rgrp);
3258 }
3259 
3260 /*
3261  * Create a monitor group under "mon_groups" directory of a control
3262  * and monitor group(ctrl_mon). This is a resource group
3263  * to monitor a subset of tasks and cpus in its parent ctrl_mon group.
3264  */
3265 static int rdtgroup_mkdir_mon(struct kernfs_node *parent_kn,
3266 			      const char *name, umode_t mode)
3267 {
3268 	struct rdtgroup *rdtgrp, *prgrp;
3269 	int ret;
3270 
3271 	ret = mkdir_rdt_prepare(parent_kn, name, mode, RDTMON_GROUP, &rdtgrp);
3272 	if (ret)
3273 		return ret;
3274 
3275 	prgrp = rdtgrp->mon.parent;
3276 	rdtgrp->closid = prgrp->closid;
3277 
3278 	/*
3279 	 * Add the rdtgrp to the list of rdtgrps the parent
3280 	 * ctrl_mon group has to track.
3281 	 */
3282 	list_add_tail(&rdtgrp->mon.crdtgrp_list, &prgrp->mon.crdtgrp_list);
3283 
3284 	rdtgroup_kn_unlock(parent_kn);
3285 	return ret;
3286 }
3287 
3288 /*
3289  * These are rdtgroups created under the root directory. Can be used
3290  * to allocate and monitor resources.
3291  */
3292 static int rdtgroup_mkdir_ctrl_mon(struct kernfs_node *parent_kn,
3293 				   const char *name, umode_t mode)
3294 {
3295 	struct rdtgroup *rdtgrp;
3296 	struct kernfs_node *kn;
3297 	u32 closid;
3298 	int ret;
3299 
3300 	ret = mkdir_rdt_prepare(parent_kn, name, mode, RDTCTRL_GROUP, &rdtgrp);
3301 	if (ret)
3302 		return ret;
3303 
3304 	kn = rdtgrp->kn;
3305 	ret = closid_alloc();
3306 	if (ret < 0) {
3307 		rdt_last_cmd_puts("Out of CLOSIDs\n");
3308 		goto out_common_fail;
3309 	}
3310 	closid = ret;
3311 	ret = 0;
3312 
3313 	rdtgrp->closid = closid;
3314 	ret = rdtgroup_init_alloc(rdtgrp);
3315 	if (ret < 0)
3316 		goto out_id_free;
3317 
3318 	list_add(&rdtgrp->rdtgroup_list, &rdt_all_groups);
3319 
3320 	if (rdt_mon_capable) {
3321 		/*
3322 		 * Create an empty mon_groups directory to hold the subset
3323 		 * of tasks and cpus to monitor.
3324 		 */
3325 		ret = mongroup_create_dir(kn, rdtgrp, "mon_groups", NULL);
3326 		if (ret) {
3327 			rdt_last_cmd_puts("kernfs subdir error\n");
3328 			goto out_del_list;
3329 		}
3330 	}
3331 
3332 	goto out_unlock;
3333 
3334 out_del_list:
3335 	list_del(&rdtgrp->rdtgroup_list);
3336 out_id_free:
3337 	closid_free(closid);
3338 out_common_fail:
3339 	mkdir_rdt_prepare_clean(rdtgrp);
3340 out_unlock:
3341 	rdtgroup_kn_unlock(parent_kn);
3342 	return ret;
3343 }
3344 
3345 /*
3346  * We allow creating mon groups only with in a directory called "mon_groups"
3347  * which is present in every ctrl_mon group. Check if this is a valid
3348  * "mon_groups" directory.
3349  *
3350  * 1. The directory should be named "mon_groups".
3351  * 2. The mon group itself should "not" be named "mon_groups".
3352  *   This makes sure "mon_groups" directory always has a ctrl_mon group
3353  *   as parent.
3354  */
3355 static bool is_mon_groups(struct kernfs_node *kn, const char *name)
3356 {
3357 	return (!strcmp(kn->name, "mon_groups") &&
3358 		strcmp(name, "mon_groups"));
3359 }
3360 
3361 static int rdtgroup_mkdir(struct kernfs_node *parent_kn, const char *name,
3362 			  umode_t mode)
3363 {
3364 	/* Do not accept '\n' to avoid unparsable situation. */
3365 	if (strchr(name, '\n'))
3366 		return -EINVAL;
3367 
3368 	/*
3369 	 * If the parent directory is the root directory and RDT
3370 	 * allocation is supported, add a control and monitoring
3371 	 * subdirectory
3372 	 */
3373 	if (rdt_alloc_capable && parent_kn == rdtgroup_default.kn)
3374 		return rdtgroup_mkdir_ctrl_mon(parent_kn, name, mode);
3375 
3376 	/*
3377 	 * If RDT monitoring is supported and the parent directory is a valid
3378 	 * "mon_groups" directory, add a monitoring subdirectory.
3379 	 */
3380 	if (rdt_mon_capable && is_mon_groups(parent_kn, name))
3381 		return rdtgroup_mkdir_mon(parent_kn, name, mode);
3382 
3383 	return -EPERM;
3384 }
3385 
3386 static int rdtgroup_rmdir_mon(struct rdtgroup *rdtgrp, cpumask_var_t tmpmask)
3387 {
3388 	struct rdtgroup *prdtgrp = rdtgrp->mon.parent;
3389 	int cpu;
3390 
3391 	/* Give any tasks back to the parent group */
3392 	rdt_move_group_tasks(rdtgrp, prdtgrp, tmpmask);
3393 
3394 	/* Update per cpu rmid of the moved CPUs first */
3395 	for_each_cpu(cpu, &rdtgrp->cpu_mask)
3396 		per_cpu(pqr_state.default_rmid, cpu) = prdtgrp->mon.rmid;
3397 	/*
3398 	 * Update the MSR on moved CPUs and CPUs which have moved
3399 	 * task running on them.
3400 	 */
3401 	cpumask_or(tmpmask, tmpmask, &rdtgrp->cpu_mask);
3402 	update_closid_rmid(tmpmask, NULL);
3403 
3404 	rdtgrp->flags = RDT_DELETED;
3405 	free_rmid(rdtgrp->mon.rmid);
3406 
3407 	/*
3408 	 * Remove the rdtgrp from the parent ctrl_mon group's list
3409 	 */
3410 	WARN_ON(list_empty(&prdtgrp->mon.crdtgrp_list));
3411 	list_del(&rdtgrp->mon.crdtgrp_list);
3412 
3413 	kernfs_remove(rdtgrp->kn);
3414 
3415 	return 0;
3416 }
3417 
3418 static int rdtgroup_ctrl_remove(struct rdtgroup *rdtgrp)
3419 {
3420 	rdtgrp->flags = RDT_DELETED;
3421 	list_del(&rdtgrp->rdtgroup_list);
3422 
3423 	kernfs_remove(rdtgrp->kn);
3424 	return 0;
3425 }
3426 
3427 static int rdtgroup_rmdir_ctrl(struct rdtgroup *rdtgrp, cpumask_var_t tmpmask)
3428 {
3429 	int cpu;
3430 
3431 	/* Give any tasks back to the default group */
3432 	rdt_move_group_tasks(rdtgrp, &rdtgroup_default, tmpmask);
3433 
3434 	/* Give any CPUs back to the default group */
3435 	cpumask_or(&rdtgroup_default.cpu_mask,
3436 		   &rdtgroup_default.cpu_mask, &rdtgrp->cpu_mask);
3437 
3438 	/* Update per cpu closid and rmid of the moved CPUs first */
3439 	for_each_cpu(cpu, &rdtgrp->cpu_mask) {
3440 		per_cpu(pqr_state.default_closid, cpu) = rdtgroup_default.closid;
3441 		per_cpu(pqr_state.default_rmid, cpu) = rdtgroup_default.mon.rmid;
3442 	}
3443 
3444 	/*
3445 	 * Update the MSR on moved CPUs and CPUs which have moved
3446 	 * task running on them.
3447 	 */
3448 	cpumask_or(tmpmask, tmpmask, &rdtgrp->cpu_mask);
3449 	update_closid_rmid(tmpmask, NULL);
3450 
3451 	closid_free(rdtgrp->closid);
3452 	free_rmid(rdtgrp->mon.rmid);
3453 
3454 	rdtgroup_ctrl_remove(rdtgrp);
3455 
3456 	/*
3457 	 * Free all the child monitor group rmids.
3458 	 */
3459 	free_all_child_rdtgrp(rdtgrp);
3460 
3461 	return 0;
3462 }
3463 
3464 static int rdtgroup_rmdir(struct kernfs_node *kn)
3465 {
3466 	struct kernfs_node *parent_kn = kn->parent;
3467 	struct rdtgroup *rdtgrp;
3468 	cpumask_var_t tmpmask;
3469 	int ret = 0;
3470 
3471 	if (!zalloc_cpumask_var(&tmpmask, GFP_KERNEL))
3472 		return -ENOMEM;
3473 
3474 	rdtgrp = rdtgroup_kn_lock_live(kn);
3475 	if (!rdtgrp) {
3476 		ret = -EPERM;
3477 		goto out;
3478 	}
3479 
3480 	/*
3481 	 * If the rdtgroup is a ctrl_mon group and parent directory
3482 	 * is the root directory, remove the ctrl_mon group.
3483 	 *
3484 	 * If the rdtgroup is a mon group and parent directory
3485 	 * is a valid "mon_groups" directory, remove the mon group.
3486 	 */
3487 	if (rdtgrp->type == RDTCTRL_GROUP && parent_kn == rdtgroup_default.kn &&
3488 	    rdtgrp != &rdtgroup_default) {
3489 		if (rdtgrp->mode == RDT_MODE_PSEUDO_LOCKSETUP ||
3490 		    rdtgrp->mode == RDT_MODE_PSEUDO_LOCKED) {
3491 			ret = rdtgroup_ctrl_remove(rdtgrp);
3492 		} else {
3493 			ret = rdtgroup_rmdir_ctrl(rdtgrp, tmpmask);
3494 		}
3495 	} else if (rdtgrp->type == RDTMON_GROUP &&
3496 		 is_mon_groups(parent_kn, kn->name)) {
3497 		ret = rdtgroup_rmdir_mon(rdtgrp, tmpmask);
3498 	} else {
3499 		ret = -EPERM;
3500 	}
3501 
3502 out:
3503 	rdtgroup_kn_unlock(kn);
3504 	free_cpumask_var(tmpmask);
3505 	return ret;
3506 }
3507 
3508 static int rdtgroup_show_options(struct seq_file *seq, struct kernfs_root *kf)
3509 {
3510 	if (resctrl_arch_get_cdp_enabled(RDT_RESOURCE_L3))
3511 		seq_puts(seq, ",cdp");
3512 
3513 	if (resctrl_arch_get_cdp_enabled(RDT_RESOURCE_L2))
3514 		seq_puts(seq, ",cdpl2");
3515 
3516 	if (is_mba_sc(&rdt_resources_all[RDT_RESOURCE_MBA].r_resctrl))
3517 		seq_puts(seq, ",mba_MBps");
3518 
3519 	return 0;
3520 }
3521 
3522 static struct kernfs_syscall_ops rdtgroup_kf_syscall_ops = {
3523 	.mkdir		= rdtgroup_mkdir,
3524 	.rmdir		= rdtgroup_rmdir,
3525 	.show_options	= rdtgroup_show_options,
3526 };
3527 
3528 static int __init rdtgroup_setup_root(void)
3529 {
3530 	int ret;
3531 
3532 	rdt_root = kernfs_create_root(&rdtgroup_kf_syscall_ops,
3533 				      KERNFS_ROOT_CREATE_DEACTIVATED |
3534 				      KERNFS_ROOT_EXTRA_OPEN_PERM_CHECK,
3535 				      &rdtgroup_default);
3536 	if (IS_ERR(rdt_root))
3537 		return PTR_ERR(rdt_root);
3538 
3539 	mutex_lock(&rdtgroup_mutex);
3540 
3541 	rdtgroup_default.closid = 0;
3542 	rdtgroup_default.mon.rmid = 0;
3543 	rdtgroup_default.type = RDTCTRL_GROUP;
3544 	INIT_LIST_HEAD(&rdtgroup_default.mon.crdtgrp_list);
3545 
3546 	list_add(&rdtgroup_default.rdtgroup_list, &rdt_all_groups);
3547 
3548 	ret = rdtgroup_add_files(kernfs_root_to_node(rdt_root), RF_CTRL_BASE);
3549 	if (ret) {
3550 		kernfs_destroy_root(rdt_root);
3551 		goto out;
3552 	}
3553 
3554 	rdtgroup_default.kn = kernfs_root_to_node(rdt_root);
3555 	kernfs_activate(rdtgroup_default.kn);
3556 
3557 out:
3558 	mutex_unlock(&rdtgroup_mutex);
3559 
3560 	return ret;
3561 }
3562 
3563 static void domain_destroy_mon_state(struct rdt_domain *d)
3564 {
3565 	bitmap_free(d->rmid_busy_llc);
3566 	kfree(d->mbm_total);
3567 	kfree(d->mbm_local);
3568 }
3569 
3570 void resctrl_offline_domain(struct rdt_resource *r, struct rdt_domain *d)
3571 {
3572 	lockdep_assert_held(&rdtgroup_mutex);
3573 
3574 	if (supports_mba_mbps() && r->rid == RDT_RESOURCE_MBA)
3575 		mba_sc_domain_destroy(r, d);
3576 
3577 	if (!r->mon_capable)
3578 		return;
3579 
3580 	/*
3581 	 * If resctrl is mounted, remove all the
3582 	 * per domain monitor data directories.
3583 	 */
3584 	if (static_branch_unlikely(&rdt_mon_enable_key))
3585 		rmdir_mondata_subdir_allrdtgrp(r, d->id);
3586 
3587 	if (is_mbm_enabled())
3588 		cancel_delayed_work(&d->mbm_over);
3589 	if (is_llc_occupancy_enabled() && has_busy_rmid(r, d)) {
3590 		/*
3591 		 * When a package is going down, forcefully
3592 		 * decrement rmid->ebusy. There is no way to know
3593 		 * that the L3 was flushed and hence may lead to
3594 		 * incorrect counts in rare scenarios, but leaving
3595 		 * the RMID as busy creates RMID leaks if the
3596 		 * package never comes back.
3597 		 */
3598 		__check_limbo(d, true);
3599 		cancel_delayed_work(&d->cqm_limbo);
3600 	}
3601 
3602 	domain_destroy_mon_state(d);
3603 }
3604 
3605 static int domain_setup_mon_state(struct rdt_resource *r, struct rdt_domain *d)
3606 {
3607 	size_t tsize;
3608 
3609 	if (is_llc_occupancy_enabled()) {
3610 		d->rmid_busy_llc = bitmap_zalloc(r->num_rmid, GFP_KERNEL);
3611 		if (!d->rmid_busy_llc)
3612 			return -ENOMEM;
3613 	}
3614 	if (is_mbm_total_enabled()) {
3615 		tsize = sizeof(*d->mbm_total);
3616 		d->mbm_total = kcalloc(r->num_rmid, tsize, GFP_KERNEL);
3617 		if (!d->mbm_total) {
3618 			bitmap_free(d->rmid_busy_llc);
3619 			return -ENOMEM;
3620 		}
3621 	}
3622 	if (is_mbm_local_enabled()) {
3623 		tsize = sizeof(*d->mbm_local);
3624 		d->mbm_local = kcalloc(r->num_rmid, tsize, GFP_KERNEL);
3625 		if (!d->mbm_local) {
3626 			bitmap_free(d->rmid_busy_llc);
3627 			kfree(d->mbm_total);
3628 			return -ENOMEM;
3629 		}
3630 	}
3631 
3632 	return 0;
3633 }
3634 
3635 int resctrl_online_domain(struct rdt_resource *r, struct rdt_domain *d)
3636 {
3637 	int err;
3638 
3639 	lockdep_assert_held(&rdtgroup_mutex);
3640 
3641 	if (supports_mba_mbps() && r->rid == RDT_RESOURCE_MBA)
3642 		/* RDT_RESOURCE_MBA is never mon_capable */
3643 		return mba_sc_domain_allocate(r, d);
3644 
3645 	if (!r->mon_capable)
3646 		return 0;
3647 
3648 	err = domain_setup_mon_state(r, d);
3649 	if (err)
3650 		return err;
3651 
3652 	if (is_mbm_enabled()) {
3653 		INIT_DELAYED_WORK(&d->mbm_over, mbm_handle_overflow);
3654 		mbm_setup_overflow_handler(d, MBM_OVERFLOW_INTERVAL);
3655 	}
3656 
3657 	if (is_llc_occupancy_enabled())
3658 		INIT_DELAYED_WORK(&d->cqm_limbo, cqm_handle_limbo);
3659 
3660 	/* If resctrl is mounted, add per domain monitor data directories. */
3661 	if (static_branch_unlikely(&rdt_mon_enable_key))
3662 		mkdir_mondata_subdir_allrdtgrp(r, d);
3663 
3664 	return 0;
3665 }
3666 
3667 /*
3668  * rdtgroup_init - rdtgroup initialization
3669  *
3670  * Setup resctrl file system including set up root, create mount point,
3671  * register rdtgroup filesystem, and initialize files under root directory.
3672  *
3673  * Return: 0 on success or -errno
3674  */
3675 int __init rdtgroup_init(void)
3676 {
3677 	int ret = 0;
3678 
3679 	seq_buf_init(&last_cmd_status, last_cmd_status_buf,
3680 		     sizeof(last_cmd_status_buf));
3681 
3682 	ret = rdtgroup_setup_root();
3683 	if (ret)
3684 		return ret;
3685 
3686 	ret = sysfs_create_mount_point(fs_kobj, "resctrl");
3687 	if (ret)
3688 		goto cleanup_root;
3689 
3690 	ret = register_filesystem(&rdt_fs_type);
3691 	if (ret)
3692 		goto cleanup_mountpoint;
3693 
3694 	/*
3695 	 * Adding the resctrl debugfs directory here may not be ideal since
3696 	 * it would let the resctrl debugfs directory appear on the debugfs
3697 	 * filesystem before the resctrl filesystem is mounted.
3698 	 * It may also be ok since that would enable debugging of RDT before
3699 	 * resctrl is mounted.
3700 	 * The reason why the debugfs directory is created here and not in
3701 	 * rdt_get_tree() is because rdt_get_tree() takes rdtgroup_mutex and
3702 	 * during the debugfs directory creation also &sb->s_type->i_mutex_key
3703 	 * (the lockdep class of inode->i_rwsem). Other filesystem
3704 	 * interactions (eg. SyS_getdents) have the lock ordering:
3705 	 * &sb->s_type->i_mutex_key --> &mm->mmap_lock
3706 	 * During mmap(), called with &mm->mmap_lock, the rdtgroup_mutex
3707 	 * is taken, thus creating dependency:
3708 	 * &mm->mmap_lock --> rdtgroup_mutex for the latter that can cause
3709 	 * issues considering the other two lock dependencies.
3710 	 * By creating the debugfs directory here we avoid a dependency
3711 	 * that may cause deadlock (even though file operations cannot
3712 	 * occur until the filesystem is mounted, but I do not know how to
3713 	 * tell lockdep that).
3714 	 */
3715 	debugfs_resctrl = debugfs_create_dir("resctrl", NULL);
3716 
3717 	return 0;
3718 
3719 cleanup_mountpoint:
3720 	sysfs_remove_mount_point(fs_kobj, "resctrl");
3721 cleanup_root:
3722 	kernfs_destroy_root(rdt_root);
3723 
3724 	return ret;
3725 }
3726 
3727 void __exit rdtgroup_exit(void)
3728 {
3729 	debugfs_remove_recursive(debugfs_resctrl);
3730 	unregister_filesystem(&rdt_fs_type);
3731 	sysfs_remove_mount_point(fs_kobj, "resctrl");
3732 	kernfs_destroy_root(rdt_root);
3733 }
3734