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