xref: /linux/arch/x86/kernel/cpu/resctrl/rdtgroup.c (revision 3a38ef2b3cb6b63c105247b5ea4a9cf600e673f0)
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();
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 	int cpu = get_cpu();
329 
330 	if (cpumask_test_cpu(cpu, cpu_mask))
331 		update_cpu_closid_rmid(r);
332 	smp_call_function_many(cpu_mask, update_cpu_closid_rmid, r, 1);
333 	put_cpu();
334 }
335 
336 static int cpus_mon_write(struct rdtgroup *rdtgrp, cpumask_var_t newmask,
337 			  cpumask_var_t tmpmask)
338 {
339 	struct rdtgroup *prgrp = rdtgrp->mon.parent, *crgrp;
340 	struct list_head *head;
341 
342 	/* Check whether cpus belong to parent ctrl group */
343 	cpumask_andnot(tmpmask, newmask, &prgrp->cpu_mask);
344 	if (!cpumask_empty(tmpmask)) {
345 		rdt_last_cmd_puts("Can only add CPUs to mongroup that belong to parent\n");
346 		return -EINVAL;
347 	}
348 
349 	/* Check whether cpus are dropped from this group */
350 	cpumask_andnot(tmpmask, &rdtgrp->cpu_mask, newmask);
351 	if (!cpumask_empty(tmpmask)) {
352 		/* Give any dropped cpus to parent rdtgroup */
353 		cpumask_or(&prgrp->cpu_mask, &prgrp->cpu_mask, tmpmask);
354 		update_closid_rmid(tmpmask, prgrp);
355 	}
356 
357 	/*
358 	 * If we added cpus, remove them from previous group that owned them
359 	 * and update per-cpu rmid
360 	 */
361 	cpumask_andnot(tmpmask, newmask, &rdtgrp->cpu_mask);
362 	if (!cpumask_empty(tmpmask)) {
363 		head = &prgrp->mon.crdtgrp_list;
364 		list_for_each_entry(crgrp, head, mon.crdtgrp_list) {
365 			if (crgrp == rdtgrp)
366 				continue;
367 			cpumask_andnot(&crgrp->cpu_mask, &crgrp->cpu_mask,
368 				       tmpmask);
369 		}
370 		update_closid_rmid(tmpmask, rdtgrp);
371 	}
372 
373 	/* Done pushing/pulling - update this group with new mask */
374 	cpumask_copy(&rdtgrp->cpu_mask, newmask);
375 
376 	return 0;
377 }
378 
379 static void cpumask_rdtgrp_clear(struct rdtgroup *r, struct cpumask *m)
380 {
381 	struct rdtgroup *crgrp;
382 
383 	cpumask_andnot(&r->cpu_mask, &r->cpu_mask, m);
384 	/* update the child mon group masks as well*/
385 	list_for_each_entry(crgrp, &r->mon.crdtgrp_list, mon.crdtgrp_list)
386 		cpumask_and(&crgrp->cpu_mask, &r->cpu_mask, &crgrp->cpu_mask);
387 }
388 
389 static int cpus_ctrl_write(struct rdtgroup *rdtgrp, cpumask_var_t newmask,
390 			   cpumask_var_t tmpmask, cpumask_var_t tmpmask1)
391 {
392 	struct rdtgroup *r, *crgrp;
393 	struct list_head *head;
394 
395 	/* Check whether cpus are dropped from this group */
396 	cpumask_andnot(tmpmask, &rdtgrp->cpu_mask, newmask);
397 	if (!cpumask_empty(tmpmask)) {
398 		/* Can't drop from default group */
399 		if (rdtgrp == &rdtgroup_default) {
400 			rdt_last_cmd_puts("Can't drop CPUs from default group\n");
401 			return -EINVAL;
402 		}
403 
404 		/* Give any dropped cpus to rdtgroup_default */
405 		cpumask_or(&rdtgroup_default.cpu_mask,
406 			   &rdtgroup_default.cpu_mask, tmpmask);
407 		update_closid_rmid(tmpmask, &rdtgroup_default);
408 	}
409 
410 	/*
411 	 * If we added cpus, remove them from previous group and
412 	 * the prev group's child groups that owned them
413 	 * and update per-cpu closid/rmid.
414 	 */
415 	cpumask_andnot(tmpmask, newmask, &rdtgrp->cpu_mask);
416 	if (!cpumask_empty(tmpmask)) {
417 		list_for_each_entry(r, &rdt_all_groups, rdtgroup_list) {
418 			if (r == rdtgrp)
419 				continue;
420 			cpumask_and(tmpmask1, &r->cpu_mask, tmpmask);
421 			if (!cpumask_empty(tmpmask1))
422 				cpumask_rdtgrp_clear(r, tmpmask1);
423 		}
424 		update_closid_rmid(tmpmask, rdtgrp);
425 	}
426 
427 	/* Done pushing/pulling - update this group with new mask */
428 	cpumask_copy(&rdtgrp->cpu_mask, newmask);
429 
430 	/*
431 	 * Clear child mon group masks since there is a new parent mask
432 	 * now and update the rmid for the cpus the child lost.
433 	 */
434 	head = &rdtgrp->mon.crdtgrp_list;
435 	list_for_each_entry(crgrp, head, mon.crdtgrp_list) {
436 		cpumask_and(tmpmask, &rdtgrp->cpu_mask, &crgrp->cpu_mask);
437 		update_closid_rmid(tmpmask, rdtgrp);
438 		cpumask_clear(&crgrp->cpu_mask);
439 	}
440 
441 	return 0;
442 }
443 
444 static ssize_t rdtgroup_cpus_write(struct kernfs_open_file *of,
445 				   char *buf, size_t nbytes, loff_t off)
446 {
447 	cpumask_var_t tmpmask, newmask, tmpmask1;
448 	struct rdtgroup *rdtgrp;
449 	int ret;
450 
451 	if (!buf)
452 		return -EINVAL;
453 
454 	if (!zalloc_cpumask_var(&tmpmask, GFP_KERNEL))
455 		return -ENOMEM;
456 	if (!zalloc_cpumask_var(&newmask, GFP_KERNEL)) {
457 		free_cpumask_var(tmpmask);
458 		return -ENOMEM;
459 	}
460 	if (!zalloc_cpumask_var(&tmpmask1, GFP_KERNEL)) {
461 		free_cpumask_var(tmpmask);
462 		free_cpumask_var(newmask);
463 		return -ENOMEM;
464 	}
465 
466 	rdtgrp = rdtgroup_kn_lock_live(of->kn);
467 	if (!rdtgrp) {
468 		ret = -ENOENT;
469 		goto unlock;
470 	}
471 
472 	if (rdtgrp->mode == RDT_MODE_PSEUDO_LOCKED ||
473 	    rdtgrp->mode == RDT_MODE_PSEUDO_LOCKSETUP) {
474 		ret = -EINVAL;
475 		rdt_last_cmd_puts("Pseudo-locking in progress\n");
476 		goto unlock;
477 	}
478 
479 	if (is_cpu_list(of))
480 		ret = cpulist_parse(buf, newmask);
481 	else
482 		ret = cpumask_parse(buf, newmask);
483 
484 	if (ret) {
485 		rdt_last_cmd_puts("Bad CPU list/mask\n");
486 		goto unlock;
487 	}
488 
489 	/* check that user didn't specify any offline cpus */
490 	cpumask_andnot(tmpmask, newmask, cpu_online_mask);
491 	if (!cpumask_empty(tmpmask)) {
492 		ret = -EINVAL;
493 		rdt_last_cmd_puts("Can only assign online CPUs\n");
494 		goto unlock;
495 	}
496 
497 	if (rdtgrp->type == RDTCTRL_GROUP)
498 		ret = cpus_ctrl_write(rdtgrp, newmask, tmpmask, tmpmask1);
499 	else if (rdtgrp->type == RDTMON_GROUP)
500 		ret = cpus_mon_write(rdtgrp, newmask, tmpmask);
501 	else
502 		ret = -EINVAL;
503 
504 unlock:
505 	rdtgroup_kn_unlock(of->kn);
506 	free_cpumask_var(tmpmask);
507 	free_cpumask_var(newmask);
508 	free_cpumask_var(tmpmask1);
509 
510 	return ret ?: nbytes;
511 }
512 
513 /**
514  * rdtgroup_remove - the helper to remove resource group safely
515  * @rdtgrp: resource group to remove
516  *
517  * On resource group creation via a mkdir, an extra kernfs_node reference is
518  * taken to ensure that the rdtgroup structure remains accessible for the
519  * rdtgroup_kn_unlock() calls where it is removed.
520  *
521  * Drop the extra reference here, then free the rdtgroup structure.
522  *
523  * Return: void
524  */
525 static void rdtgroup_remove(struct rdtgroup *rdtgrp)
526 {
527 	kernfs_put(rdtgrp->kn);
528 	kfree(rdtgrp);
529 }
530 
531 static void _update_task_closid_rmid(void *task)
532 {
533 	/*
534 	 * If the task is still current on this CPU, update PQR_ASSOC MSR.
535 	 * Otherwise, the MSR is updated when the task is scheduled in.
536 	 */
537 	if (task == current)
538 		resctrl_sched_in();
539 }
540 
541 static void update_task_closid_rmid(struct task_struct *t)
542 {
543 	if (IS_ENABLED(CONFIG_SMP) && task_curr(t))
544 		smp_call_function_single(task_cpu(t), _update_task_closid_rmid, t, 1);
545 	else
546 		_update_task_closid_rmid(t);
547 }
548 
549 static int __rdtgroup_move_task(struct task_struct *tsk,
550 				struct rdtgroup *rdtgrp)
551 {
552 	/* If the task is already in rdtgrp, no need to move the task. */
553 	if ((rdtgrp->type == RDTCTRL_GROUP && tsk->closid == rdtgrp->closid &&
554 	     tsk->rmid == rdtgrp->mon.rmid) ||
555 	    (rdtgrp->type == RDTMON_GROUP && tsk->rmid == rdtgrp->mon.rmid &&
556 	     tsk->closid == rdtgrp->mon.parent->closid))
557 		return 0;
558 
559 	/*
560 	 * Set the task's closid/rmid before the PQR_ASSOC MSR can be
561 	 * updated by them.
562 	 *
563 	 * For ctrl_mon groups, move both closid and rmid.
564 	 * For monitor groups, can move the tasks only from
565 	 * their parent CTRL group.
566 	 */
567 
568 	if (rdtgrp->type == RDTCTRL_GROUP) {
569 		WRITE_ONCE(tsk->closid, rdtgrp->closid);
570 		WRITE_ONCE(tsk->rmid, rdtgrp->mon.rmid);
571 	} else if (rdtgrp->type == RDTMON_GROUP) {
572 		if (rdtgrp->mon.parent->closid == tsk->closid) {
573 			WRITE_ONCE(tsk->rmid, rdtgrp->mon.rmid);
574 		} else {
575 			rdt_last_cmd_puts("Can't move task to different control group\n");
576 			return -EINVAL;
577 		}
578 	}
579 
580 	/*
581 	 * Ensure the task's closid and rmid are written before determining if
582 	 * the task is current that will decide if it will be interrupted.
583 	 */
584 	barrier();
585 
586 	/*
587 	 * By now, the task's closid and rmid are set. If the task is current
588 	 * on a CPU, the PQR_ASSOC MSR needs to be updated to make the resource
589 	 * group go into effect. If the task is not current, the MSR will be
590 	 * updated when the task is scheduled in.
591 	 */
592 	update_task_closid_rmid(tsk);
593 
594 	return 0;
595 }
596 
597 static bool is_closid_match(struct task_struct *t, struct rdtgroup *r)
598 {
599 	return (rdt_alloc_capable &&
600 	       (r->type == RDTCTRL_GROUP) && (t->closid == r->closid));
601 }
602 
603 static bool is_rmid_match(struct task_struct *t, struct rdtgroup *r)
604 {
605 	return (rdt_mon_capable &&
606 	       (r->type == RDTMON_GROUP) && (t->rmid == r->mon.rmid));
607 }
608 
609 /**
610  * rdtgroup_tasks_assigned - Test if tasks have been assigned to resource group
611  * @r: Resource group
612  *
613  * Return: 1 if tasks have been assigned to @r, 0 otherwise
614  */
615 int rdtgroup_tasks_assigned(struct rdtgroup *r)
616 {
617 	struct task_struct *p, *t;
618 	int ret = 0;
619 
620 	lockdep_assert_held(&rdtgroup_mutex);
621 
622 	rcu_read_lock();
623 	for_each_process_thread(p, t) {
624 		if (is_closid_match(t, r) || is_rmid_match(t, r)) {
625 			ret = 1;
626 			break;
627 		}
628 	}
629 	rcu_read_unlock();
630 
631 	return ret;
632 }
633 
634 static int rdtgroup_task_write_permission(struct task_struct *task,
635 					  struct kernfs_open_file *of)
636 {
637 	const struct cred *tcred = get_task_cred(task);
638 	const struct cred *cred = current_cred();
639 	int ret = 0;
640 
641 	/*
642 	 * Even if we're attaching all tasks in the thread group, we only
643 	 * need to check permissions on one of them.
644 	 */
645 	if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
646 	    !uid_eq(cred->euid, tcred->uid) &&
647 	    !uid_eq(cred->euid, tcred->suid)) {
648 		rdt_last_cmd_printf("No permission to move task %d\n", task->pid);
649 		ret = -EPERM;
650 	}
651 
652 	put_cred(tcred);
653 	return ret;
654 }
655 
656 static int rdtgroup_move_task(pid_t pid, struct rdtgroup *rdtgrp,
657 			      struct kernfs_open_file *of)
658 {
659 	struct task_struct *tsk;
660 	int ret;
661 
662 	rcu_read_lock();
663 	if (pid) {
664 		tsk = find_task_by_vpid(pid);
665 		if (!tsk) {
666 			rcu_read_unlock();
667 			rdt_last_cmd_printf("No task %d\n", pid);
668 			return -ESRCH;
669 		}
670 	} else {
671 		tsk = current;
672 	}
673 
674 	get_task_struct(tsk);
675 	rcu_read_unlock();
676 
677 	ret = rdtgroup_task_write_permission(tsk, of);
678 	if (!ret)
679 		ret = __rdtgroup_move_task(tsk, rdtgrp);
680 
681 	put_task_struct(tsk);
682 	return ret;
683 }
684 
685 static ssize_t rdtgroup_tasks_write(struct kernfs_open_file *of,
686 				    char *buf, size_t nbytes, loff_t off)
687 {
688 	struct rdtgroup *rdtgrp;
689 	int ret = 0;
690 	pid_t pid;
691 
692 	if (kstrtoint(strstrip(buf), 0, &pid) || pid < 0)
693 		return -EINVAL;
694 	rdtgrp = rdtgroup_kn_lock_live(of->kn);
695 	if (!rdtgrp) {
696 		rdtgroup_kn_unlock(of->kn);
697 		return -ENOENT;
698 	}
699 	rdt_last_cmd_clear();
700 
701 	if (rdtgrp->mode == RDT_MODE_PSEUDO_LOCKED ||
702 	    rdtgrp->mode == RDT_MODE_PSEUDO_LOCKSETUP) {
703 		ret = -EINVAL;
704 		rdt_last_cmd_puts("Pseudo-locking in progress\n");
705 		goto unlock;
706 	}
707 
708 	ret = rdtgroup_move_task(pid, rdtgrp, of);
709 
710 unlock:
711 	rdtgroup_kn_unlock(of->kn);
712 
713 	return ret ?: nbytes;
714 }
715 
716 static void show_rdt_tasks(struct rdtgroup *r, struct seq_file *s)
717 {
718 	struct task_struct *p, *t;
719 
720 	rcu_read_lock();
721 	for_each_process_thread(p, t) {
722 		if (is_closid_match(t, r) || is_rmid_match(t, r))
723 			seq_printf(s, "%d\n", t->pid);
724 	}
725 	rcu_read_unlock();
726 }
727 
728 static int rdtgroup_tasks_show(struct kernfs_open_file *of,
729 			       struct seq_file *s, void *v)
730 {
731 	struct rdtgroup *rdtgrp;
732 	int ret = 0;
733 
734 	rdtgrp = rdtgroup_kn_lock_live(of->kn);
735 	if (rdtgrp)
736 		show_rdt_tasks(rdtgrp, s);
737 	else
738 		ret = -ENOENT;
739 	rdtgroup_kn_unlock(of->kn);
740 
741 	return ret;
742 }
743 
744 #ifdef CONFIG_PROC_CPU_RESCTRL
745 
746 /*
747  * A task can only be part of one resctrl control group and of one monitor
748  * group which is associated to that control group.
749  *
750  * 1)   res:
751  *      mon:
752  *
753  *    resctrl is not available.
754  *
755  * 2)   res:/
756  *      mon:
757  *
758  *    Task is part of the root resctrl control group, and it is not associated
759  *    to any monitor group.
760  *
761  * 3)  res:/
762  *     mon:mon0
763  *
764  *    Task is part of the root resctrl control group and monitor group mon0.
765  *
766  * 4)  res:group0
767  *     mon:
768  *
769  *    Task is part of resctrl control group group0, and it is not associated
770  *    to any monitor group.
771  *
772  * 5) res:group0
773  *    mon:mon1
774  *
775  *    Task is part of resctrl control group group0 and monitor group mon1.
776  */
777 int proc_resctrl_show(struct seq_file *s, struct pid_namespace *ns,
778 		      struct pid *pid, struct task_struct *tsk)
779 {
780 	struct rdtgroup *rdtg;
781 	int ret = 0;
782 
783 	mutex_lock(&rdtgroup_mutex);
784 
785 	/* Return empty if resctrl has not been mounted. */
786 	if (!static_branch_unlikely(&rdt_enable_key)) {
787 		seq_puts(s, "res:\nmon:\n");
788 		goto unlock;
789 	}
790 
791 	list_for_each_entry(rdtg, &rdt_all_groups, rdtgroup_list) {
792 		struct rdtgroup *crg;
793 
794 		/*
795 		 * Task information is only relevant for shareable
796 		 * and exclusive groups.
797 		 */
798 		if (rdtg->mode != RDT_MODE_SHAREABLE &&
799 		    rdtg->mode != RDT_MODE_EXCLUSIVE)
800 			continue;
801 
802 		if (rdtg->closid != tsk->closid)
803 			continue;
804 
805 		seq_printf(s, "res:%s%s\n", (rdtg == &rdtgroup_default) ? "/" : "",
806 			   rdtg->kn->name);
807 		seq_puts(s, "mon:");
808 		list_for_each_entry(crg, &rdtg->mon.crdtgrp_list,
809 				    mon.crdtgrp_list) {
810 			if (tsk->rmid != crg->mon.rmid)
811 				continue;
812 			seq_printf(s, "%s", crg->kn->name);
813 			break;
814 		}
815 		seq_putc(s, '\n');
816 		goto unlock;
817 	}
818 	/*
819 	 * The above search should succeed. Otherwise return
820 	 * with an error.
821 	 */
822 	ret = -ENOENT;
823 unlock:
824 	mutex_unlock(&rdtgroup_mutex);
825 
826 	return ret;
827 }
828 #endif
829 
830 static int rdt_last_cmd_status_show(struct kernfs_open_file *of,
831 				    struct seq_file *seq, void *v)
832 {
833 	int len;
834 
835 	mutex_lock(&rdtgroup_mutex);
836 	len = seq_buf_used(&last_cmd_status);
837 	if (len)
838 		seq_printf(seq, "%.*s", len, last_cmd_status_buf);
839 	else
840 		seq_puts(seq, "ok\n");
841 	mutex_unlock(&rdtgroup_mutex);
842 	return 0;
843 }
844 
845 static int rdt_num_closids_show(struct kernfs_open_file *of,
846 				struct seq_file *seq, void *v)
847 {
848 	struct resctrl_schema *s = of->kn->parent->priv;
849 
850 	seq_printf(seq, "%u\n", s->num_closid);
851 	return 0;
852 }
853 
854 static int rdt_default_ctrl_show(struct kernfs_open_file *of,
855 			     struct seq_file *seq, void *v)
856 {
857 	struct resctrl_schema *s = of->kn->parent->priv;
858 	struct rdt_resource *r = s->res;
859 
860 	seq_printf(seq, "%x\n", r->default_ctrl);
861 	return 0;
862 }
863 
864 static int rdt_min_cbm_bits_show(struct kernfs_open_file *of,
865 			     struct seq_file *seq, void *v)
866 {
867 	struct resctrl_schema *s = of->kn->parent->priv;
868 	struct rdt_resource *r = s->res;
869 
870 	seq_printf(seq, "%u\n", r->cache.min_cbm_bits);
871 	return 0;
872 }
873 
874 static int rdt_shareable_bits_show(struct kernfs_open_file *of,
875 				   struct seq_file *seq, void *v)
876 {
877 	struct resctrl_schema *s = of->kn->parent->priv;
878 	struct rdt_resource *r = s->res;
879 
880 	seq_printf(seq, "%x\n", r->cache.shareable_bits);
881 	return 0;
882 }
883 
884 /**
885  * rdt_bit_usage_show - Display current usage of resources
886  *
887  * A domain is a shared resource that can now be allocated differently. Here
888  * we display the current regions of the domain as an annotated bitmask.
889  * For each domain of this resource its allocation bitmask
890  * is annotated as below to indicate the current usage of the corresponding bit:
891  *   0 - currently unused
892  *   X - currently available for sharing and used by software and hardware
893  *   H - currently used by hardware only but available for software use
894  *   S - currently used and shareable by software only
895  *   E - currently used exclusively by one resource group
896  *   P - currently pseudo-locked by one resource group
897  */
898 static int rdt_bit_usage_show(struct kernfs_open_file *of,
899 			      struct seq_file *seq, void *v)
900 {
901 	struct resctrl_schema *s = of->kn->parent->priv;
902 	/*
903 	 * Use unsigned long even though only 32 bits are used to ensure
904 	 * test_bit() is used safely.
905 	 */
906 	unsigned long sw_shareable = 0, hw_shareable = 0;
907 	unsigned long exclusive = 0, pseudo_locked = 0;
908 	struct rdt_resource *r = s->res;
909 	struct rdt_domain *dom;
910 	int i, hwb, swb, excl, psl;
911 	enum rdtgrp_mode mode;
912 	bool sep = false;
913 	u32 ctrl_val;
914 
915 	mutex_lock(&rdtgroup_mutex);
916 	hw_shareable = r->cache.shareable_bits;
917 	list_for_each_entry(dom, &r->domains, list) {
918 		if (sep)
919 			seq_putc(seq, ';');
920 		sw_shareable = 0;
921 		exclusive = 0;
922 		seq_printf(seq, "%d=", dom->id);
923 		for (i = 0; i < closids_supported(); i++) {
924 			if (!closid_allocated(i))
925 				continue;
926 			ctrl_val = resctrl_arch_get_config(r, dom, i,
927 							   s->conf_type);
928 			mode = rdtgroup_mode_by_closid(i);
929 			switch (mode) {
930 			case RDT_MODE_SHAREABLE:
931 				sw_shareable |= ctrl_val;
932 				break;
933 			case RDT_MODE_EXCLUSIVE:
934 				exclusive |= ctrl_val;
935 				break;
936 			case RDT_MODE_PSEUDO_LOCKSETUP:
937 			/*
938 			 * RDT_MODE_PSEUDO_LOCKSETUP is possible
939 			 * here but not included since the CBM
940 			 * associated with this CLOSID in this mode
941 			 * is not initialized and no task or cpu can be
942 			 * assigned this CLOSID.
943 			 */
944 				break;
945 			case RDT_MODE_PSEUDO_LOCKED:
946 			case RDT_NUM_MODES:
947 				WARN(1,
948 				     "invalid mode for closid %d\n", i);
949 				break;
950 			}
951 		}
952 		for (i = r->cache.cbm_len - 1; i >= 0; i--) {
953 			pseudo_locked = dom->plr ? dom->plr->cbm : 0;
954 			hwb = test_bit(i, &hw_shareable);
955 			swb = test_bit(i, &sw_shareable);
956 			excl = test_bit(i, &exclusive);
957 			psl = test_bit(i, &pseudo_locked);
958 			if (hwb && swb)
959 				seq_putc(seq, 'X');
960 			else if (hwb && !swb)
961 				seq_putc(seq, 'H');
962 			else if (!hwb && swb)
963 				seq_putc(seq, 'S');
964 			else if (excl)
965 				seq_putc(seq, 'E');
966 			else if (psl)
967 				seq_putc(seq, 'P');
968 			else /* Unused bits remain */
969 				seq_putc(seq, '0');
970 		}
971 		sep = true;
972 	}
973 	seq_putc(seq, '\n');
974 	mutex_unlock(&rdtgroup_mutex);
975 	return 0;
976 }
977 
978 static int rdt_min_bw_show(struct kernfs_open_file *of,
979 			     struct seq_file *seq, void *v)
980 {
981 	struct resctrl_schema *s = of->kn->parent->priv;
982 	struct rdt_resource *r = s->res;
983 
984 	seq_printf(seq, "%u\n", r->membw.min_bw);
985 	return 0;
986 }
987 
988 static int rdt_num_rmids_show(struct kernfs_open_file *of,
989 			      struct seq_file *seq, void *v)
990 {
991 	struct rdt_resource *r = of->kn->parent->priv;
992 
993 	seq_printf(seq, "%d\n", r->num_rmid);
994 
995 	return 0;
996 }
997 
998 static int rdt_mon_features_show(struct kernfs_open_file *of,
999 				 struct seq_file *seq, void *v)
1000 {
1001 	struct rdt_resource *r = of->kn->parent->priv;
1002 	struct mon_evt *mevt;
1003 
1004 	list_for_each_entry(mevt, &r->evt_list, list)
1005 		seq_printf(seq, "%s\n", mevt->name);
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)
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 					size = ctrl;
1407 				else
1408 					size = rdtgroup_cbm_to_size(r, d, ctrl);
1409 			}
1410 			seq_printf(s, "%d=%u", d->id, size);
1411 			sep = true;
1412 		}
1413 		seq_putc(s, '\n');
1414 	}
1415 
1416 out:
1417 	rdtgroup_kn_unlock(of->kn);
1418 
1419 	return ret;
1420 }
1421 
1422 /* rdtgroup information files for one cache resource. */
1423 static struct rftype res_common_files[] = {
1424 	{
1425 		.name		= "last_cmd_status",
1426 		.mode		= 0444,
1427 		.kf_ops		= &rdtgroup_kf_single_ops,
1428 		.seq_show	= rdt_last_cmd_status_show,
1429 		.fflags		= RF_TOP_INFO,
1430 	},
1431 	{
1432 		.name		= "num_closids",
1433 		.mode		= 0444,
1434 		.kf_ops		= &rdtgroup_kf_single_ops,
1435 		.seq_show	= rdt_num_closids_show,
1436 		.fflags		= RF_CTRL_INFO,
1437 	},
1438 	{
1439 		.name		= "mon_features",
1440 		.mode		= 0444,
1441 		.kf_ops		= &rdtgroup_kf_single_ops,
1442 		.seq_show	= rdt_mon_features_show,
1443 		.fflags		= RF_MON_INFO,
1444 	},
1445 	{
1446 		.name		= "num_rmids",
1447 		.mode		= 0444,
1448 		.kf_ops		= &rdtgroup_kf_single_ops,
1449 		.seq_show	= rdt_num_rmids_show,
1450 		.fflags		= RF_MON_INFO,
1451 	},
1452 	{
1453 		.name		= "cbm_mask",
1454 		.mode		= 0444,
1455 		.kf_ops		= &rdtgroup_kf_single_ops,
1456 		.seq_show	= rdt_default_ctrl_show,
1457 		.fflags		= RF_CTRL_INFO | RFTYPE_RES_CACHE,
1458 	},
1459 	{
1460 		.name		= "min_cbm_bits",
1461 		.mode		= 0444,
1462 		.kf_ops		= &rdtgroup_kf_single_ops,
1463 		.seq_show	= rdt_min_cbm_bits_show,
1464 		.fflags		= RF_CTRL_INFO | RFTYPE_RES_CACHE,
1465 	},
1466 	{
1467 		.name		= "shareable_bits",
1468 		.mode		= 0444,
1469 		.kf_ops		= &rdtgroup_kf_single_ops,
1470 		.seq_show	= rdt_shareable_bits_show,
1471 		.fflags		= RF_CTRL_INFO | RFTYPE_RES_CACHE,
1472 	},
1473 	{
1474 		.name		= "bit_usage",
1475 		.mode		= 0444,
1476 		.kf_ops		= &rdtgroup_kf_single_ops,
1477 		.seq_show	= rdt_bit_usage_show,
1478 		.fflags		= RF_CTRL_INFO | RFTYPE_RES_CACHE,
1479 	},
1480 	{
1481 		.name		= "min_bandwidth",
1482 		.mode		= 0444,
1483 		.kf_ops		= &rdtgroup_kf_single_ops,
1484 		.seq_show	= rdt_min_bw_show,
1485 		.fflags		= RF_CTRL_INFO | RFTYPE_RES_MB,
1486 	},
1487 	{
1488 		.name		= "bandwidth_gran",
1489 		.mode		= 0444,
1490 		.kf_ops		= &rdtgroup_kf_single_ops,
1491 		.seq_show	= rdt_bw_gran_show,
1492 		.fflags		= RF_CTRL_INFO | RFTYPE_RES_MB,
1493 	},
1494 	{
1495 		.name		= "delay_linear",
1496 		.mode		= 0444,
1497 		.kf_ops		= &rdtgroup_kf_single_ops,
1498 		.seq_show	= rdt_delay_linear_show,
1499 		.fflags		= RF_CTRL_INFO | RFTYPE_RES_MB,
1500 	},
1501 	/*
1502 	 * Platform specific which (if any) capabilities are provided by
1503 	 * thread_throttle_mode. Defer "fflags" initialization to platform
1504 	 * discovery.
1505 	 */
1506 	{
1507 		.name		= "thread_throttle_mode",
1508 		.mode		= 0444,
1509 		.kf_ops		= &rdtgroup_kf_single_ops,
1510 		.seq_show	= rdt_thread_throttle_mode_show,
1511 	},
1512 	{
1513 		.name		= "max_threshold_occupancy",
1514 		.mode		= 0644,
1515 		.kf_ops		= &rdtgroup_kf_single_ops,
1516 		.write		= max_threshold_occ_write,
1517 		.seq_show	= max_threshold_occ_show,
1518 		.fflags		= RF_MON_INFO | RFTYPE_RES_CACHE,
1519 	},
1520 	{
1521 		.name		= "cpus",
1522 		.mode		= 0644,
1523 		.kf_ops		= &rdtgroup_kf_single_ops,
1524 		.write		= rdtgroup_cpus_write,
1525 		.seq_show	= rdtgroup_cpus_show,
1526 		.fflags		= RFTYPE_BASE,
1527 	},
1528 	{
1529 		.name		= "cpus_list",
1530 		.mode		= 0644,
1531 		.kf_ops		= &rdtgroup_kf_single_ops,
1532 		.write		= rdtgroup_cpus_write,
1533 		.seq_show	= rdtgroup_cpus_show,
1534 		.flags		= RFTYPE_FLAGS_CPUS_LIST,
1535 		.fflags		= RFTYPE_BASE,
1536 	},
1537 	{
1538 		.name		= "tasks",
1539 		.mode		= 0644,
1540 		.kf_ops		= &rdtgroup_kf_single_ops,
1541 		.write		= rdtgroup_tasks_write,
1542 		.seq_show	= rdtgroup_tasks_show,
1543 		.fflags		= RFTYPE_BASE,
1544 	},
1545 	{
1546 		.name		= "schemata",
1547 		.mode		= 0644,
1548 		.kf_ops		= &rdtgroup_kf_single_ops,
1549 		.write		= rdtgroup_schemata_write,
1550 		.seq_show	= rdtgroup_schemata_show,
1551 		.fflags		= RF_CTRL_BASE,
1552 	},
1553 	{
1554 		.name		= "mode",
1555 		.mode		= 0644,
1556 		.kf_ops		= &rdtgroup_kf_single_ops,
1557 		.write		= rdtgroup_mode_write,
1558 		.seq_show	= rdtgroup_mode_show,
1559 		.fflags		= RF_CTRL_BASE,
1560 	},
1561 	{
1562 		.name		= "size",
1563 		.mode		= 0444,
1564 		.kf_ops		= &rdtgroup_kf_single_ops,
1565 		.seq_show	= rdtgroup_size_show,
1566 		.fflags		= RF_CTRL_BASE,
1567 	},
1568 
1569 };
1570 
1571 static int rdtgroup_add_files(struct kernfs_node *kn, unsigned long fflags)
1572 {
1573 	struct rftype *rfts, *rft;
1574 	int ret, len;
1575 
1576 	rfts = res_common_files;
1577 	len = ARRAY_SIZE(res_common_files);
1578 
1579 	lockdep_assert_held(&rdtgroup_mutex);
1580 
1581 	for (rft = rfts; rft < rfts + len; rft++) {
1582 		if (rft->fflags && ((fflags & rft->fflags) == rft->fflags)) {
1583 			ret = rdtgroup_add_file(kn, rft);
1584 			if (ret)
1585 				goto error;
1586 		}
1587 	}
1588 
1589 	return 0;
1590 error:
1591 	pr_warn("Failed to add %s, err=%d\n", rft->name, ret);
1592 	while (--rft >= rfts) {
1593 		if ((fflags & rft->fflags) == rft->fflags)
1594 			kernfs_remove_by_name(kn, rft->name);
1595 	}
1596 	return ret;
1597 }
1598 
1599 static struct rftype *rdtgroup_get_rftype_by_name(const char *name)
1600 {
1601 	struct rftype *rfts, *rft;
1602 	int len;
1603 
1604 	rfts = res_common_files;
1605 	len = ARRAY_SIZE(res_common_files);
1606 
1607 	for (rft = rfts; rft < rfts + len; rft++) {
1608 		if (!strcmp(rft->name, name))
1609 			return rft;
1610 	}
1611 
1612 	return NULL;
1613 }
1614 
1615 void __init thread_throttle_mode_init(void)
1616 {
1617 	struct rftype *rft;
1618 
1619 	rft = rdtgroup_get_rftype_by_name("thread_throttle_mode");
1620 	if (!rft)
1621 		return;
1622 
1623 	rft->fflags = RF_CTRL_INFO | RFTYPE_RES_MB;
1624 }
1625 
1626 /**
1627  * rdtgroup_kn_mode_restrict - Restrict user access to named resctrl file
1628  * @r: The resource group with which the file is associated.
1629  * @name: Name of the file
1630  *
1631  * The permissions of named resctrl file, directory, or link are modified
1632  * to not allow read, write, or execute by any user.
1633  *
1634  * WARNING: This function is intended to communicate to the user that the
1635  * resctrl file has been locked down - that it is not relevant to the
1636  * particular state the system finds itself in. It should not be relied
1637  * on to protect from user access because after the file's permissions
1638  * are restricted the user can still change the permissions using chmod
1639  * from the command line.
1640  *
1641  * Return: 0 on success, <0 on failure.
1642  */
1643 int rdtgroup_kn_mode_restrict(struct rdtgroup *r, const char *name)
1644 {
1645 	struct iattr iattr = {.ia_valid = ATTR_MODE,};
1646 	struct kernfs_node *kn;
1647 	int ret = 0;
1648 
1649 	kn = kernfs_find_and_get_ns(r->kn, name, NULL);
1650 	if (!kn)
1651 		return -ENOENT;
1652 
1653 	switch (kernfs_type(kn)) {
1654 	case KERNFS_DIR:
1655 		iattr.ia_mode = S_IFDIR;
1656 		break;
1657 	case KERNFS_FILE:
1658 		iattr.ia_mode = S_IFREG;
1659 		break;
1660 	case KERNFS_LINK:
1661 		iattr.ia_mode = S_IFLNK;
1662 		break;
1663 	}
1664 
1665 	ret = kernfs_setattr(kn, &iattr);
1666 	kernfs_put(kn);
1667 	return ret;
1668 }
1669 
1670 /**
1671  * rdtgroup_kn_mode_restore - Restore user access to named resctrl file
1672  * @r: The resource group with which the file is associated.
1673  * @name: Name of the file
1674  * @mask: Mask of permissions that should be restored
1675  *
1676  * Restore the permissions of the named file. If @name is a directory the
1677  * permissions of its parent will be used.
1678  *
1679  * Return: 0 on success, <0 on failure.
1680  */
1681 int rdtgroup_kn_mode_restore(struct rdtgroup *r, const char *name,
1682 			     umode_t mask)
1683 {
1684 	struct iattr iattr = {.ia_valid = ATTR_MODE,};
1685 	struct kernfs_node *kn, *parent;
1686 	struct rftype *rfts, *rft;
1687 	int ret, len;
1688 
1689 	rfts = res_common_files;
1690 	len = ARRAY_SIZE(res_common_files);
1691 
1692 	for (rft = rfts; rft < rfts + len; rft++) {
1693 		if (!strcmp(rft->name, name))
1694 			iattr.ia_mode = rft->mode & mask;
1695 	}
1696 
1697 	kn = kernfs_find_and_get_ns(r->kn, name, NULL);
1698 	if (!kn)
1699 		return -ENOENT;
1700 
1701 	switch (kernfs_type(kn)) {
1702 	case KERNFS_DIR:
1703 		parent = kernfs_get_parent(kn);
1704 		if (parent) {
1705 			iattr.ia_mode |= parent->mode;
1706 			kernfs_put(parent);
1707 		}
1708 		iattr.ia_mode |= S_IFDIR;
1709 		break;
1710 	case KERNFS_FILE:
1711 		iattr.ia_mode |= S_IFREG;
1712 		break;
1713 	case KERNFS_LINK:
1714 		iattr.ia_mode |= S_IFLNK;
1715 		break;
1716 	}
1717 
1718 	ret = kernfs_setattr(kn, &iattr);
1719 	kernfs_put(kn);
1720 	return ret;
1721 }
1722 
1723 static int rdtgroup_mkdir_info_resdir(void *priv, char *name,
1724 				      unsigned long fflags)
1725 {
1726 	struct kernfs_node *kn_subdir;
1727 	int ret;
1728 
1729 	kn_subdir = kernfs_create_dir(kn_info, name,
1730 				      kn_info->mode, priv);
1731 	if (IS_ERR(kn_subdir))
1732 		return PTR_ERR(kn_subdir);
1733 
1734 	ret = rdtgroup_kn_set_ugid(kn_subdir);
1735 	if (ret)
1736 		return ret;
1737 
1738 	ret = rdtgroup_add_files(kn_subdir, fflags);
1739 	if (!ret)
1740 		kernfs_activate(kn_subdir);
1741 
1742 	return ret;
1743 }
1744 
1745 static int rdtgroup_create_info_dir(struct kernfs_node *parent_kn)
1746 {
1747 	struct resctrl_schema *s;
1748 	struct rdt_resource *r;
1749 	unsigned long fflags;
1750 	char name[32];
1751 	int ret;
1752 
1753 	/* create the directory */
1754 	kn_info = kernfs_create_dir(parent_kn, "info", parent_kn->mode, NULL);
1755 	if (IS_ERR(kn_info))
1756 		return PTR_ERR(kn_info);
1757 
1758 	ret = rdtgroup_add_files(kn_info, RF_TOP_INFO);
1759 	if (ret)
1760 		goto out_destroy;
1761 
1762 	/* loop over enabled controls, these are all alloc_capable */
1763 	list_for_each_entry(s, &resctrl_schema_all, list) {
1764 		r = s->res;
1765 		fflags =  r->fflags | RF_CTRL_INFO;
1766 		ret = rdtgroup_mkdir_info_resdir(s, s->name, fflags);
1767 		if (ret)
1768 			goto out_destroy;
1769 	}
1770 
1771 	for_each_mon_capable_rdt_resource(r) {
1772 		fflags =  r->fflags | RF_MON_INFO;
1773 		sprintf(name, "%s_MON", r->name);
1774 		ret = rdtgroup_mkdir_info_resdir(r, name, fflags);
1775 		if (ret)
1776 			goto out_destroy;
1777 	}
1778 
1779 	ret = rdtgroup_kn_set_ugid(kn_info);
1780 	if (ret)
1781 		goto out_destroy;
1782 
1783 	kernfs_activate(kn_info);
1784 
1785 	return 0;
1786 
1787 out_destroy:
1788 	kernfs_remove(kn_info);
1789 	return ret;
1790 }
1791 
1792 static int
1793 mongroup_create_dir(struct kernfs_node *parent_kn, struct rdtgroup *prgrp,
1794 		    char *name, struct kernfs_node **dest_kn)
1795 {
1796 	struct kernfs_node *kn;
1797 	int ret;
1798 
1799 	/* create the directory */
1800 	kn = kernfs_create_dir(parent_kn, name, parent_kn->mode, prgrp);
1801 	if (IS_ERR(kn))
1802 		return PTR_ERR(kn);
1803 
1804 	if (dest_kn)
1805 		*dest_kn = kn;
1806 
1807 	ret = rdtgroup_kn_set_ugid(kn);
1808 	if (ret)
1809 		goto out_destroy;
1810 
1811 	kernfs_activate(kn);
1812 
1813 	return 0;
1814 
1815 out_destroy:
1816 	kernfs_remove(kn);
1817 	return ret;
1818 }
1819 
1820 static void l3_qos_cfg_update(void *arg)
1821 {
1822 	bool *enable = arg;
1823 
1824 	wrmsrl(MSR_IA32_L3_QOS_CFG, *enable ? L3_QOS_CDP_ENABLE : 0ULL);
1825 }
1826 
1827 static void l2_qos_cfg_update(void *arg)
1828 {
1829 	bool *enable = arg;
1830 
1831 	wrmsrl(MSR_IA32_L2_QOS_CFG, *enable ? L2_QOS_CDP_ENABLE : 0ULL);
1832 }
1833 
1834 static inline bool is_mba_linear(void)
1835 {
1836 	return rdt_resources_all[RDT_RESOURCE_MBA].r_resctrl.membw.delay_linear;
1837 }
1838 
1839 static int set_cache_qos_cfg(int level, bool enable)
1840 {
1841 	void (*update)(void *arg);
1842 	struct rdt_resource *r_l;
1843 	cpumask_var_t cpu_mask;
1844 	struct rdt_domain *d;
1845 	int cpu;
1846 
1847 	if (level == RDT_RESOURCE_L3)
1848 		update = l3_qos_cfg_update;
1849 	else if (level == RDT_RESOURCE_L2)
1850 		update = l2_qos_cfg_update;
1851 	else
1852 		return -EINVAL;
1853 
1854 	if (!zalloc_cpumask_var(&cpu_mask, GFP_KERNEL))
1855 		return -ENOMEM;
1856 
1857 	r_l = &rdt_resources_all[level].r_resctrl;
1858 	list_for_each_entry(d, &r_l->domains, list) {
1859 		if (r_l->cache.arch_has_per_cpu_cfg)
1860 			/* Pick all the CPUs in the domain instance */
1861 			for_each_cpu(cpu, &d->cpu_mask)
1862 				cpumask_set_cpu(cpu, cpu_mask);
1863 		else
1864 			/* Pick one CPU from each domain instance to update MSR */
1865 			cpumask_set_cpu(cpumask_any(&d->cpu_mask), cpu_mask);
1866 	}
1867 	cpu = get_cpu();
1868 	/* Update QOS_CFG MSR on this cpu if it's in cpu_mask. */
1869 	if (cpumask_test_cpu(cpu, cpu_mask))
1870 		update(&enable);
1871 	/* Update QOS_CFG MSR on all other cpus in cpu_mask. */
1872 	smp_call_function_many(cpu_mask, update, &enable, 1);
1873 	put_cpu();
1874 
1875 	free_cpumask_var(cpu_mask);
1876 
1877 	return 0;
1878 }
1879 
1880 /* Restore the qos cfg state when a domain comes online */
1881 void rdt_domain_reconfigure_cdp(struct rdt_resource *r)
1882 {
1883 	struct rdt_hw_resource *hw_res = resctrl_to_arch_res(r);
1884 
1885 	if (!r->cdp_capable)
1886 		return;
1887 
1888 	if (r->rid == RDT_RESOURCE_L2)
1889 		l2_qos_cfg_update(&hw_res->cdp_enabled);
1890 
1891 	if (r->rid == RDT_RESOURCE_L3)
1892 		l3_qos_cfg_update(&hw_res->cdp_enabled);
1893 }
1894 
1895 static int mba_sc_domain_allocate(struct rdt_resource *r, struct rdt_domain *d)
1896 {
1897 	u32 num_closid = resctrl_arch_get_num_closid(r);
1898 	int cpu = cpumask_any(&d->cpu_mask);
1899 	int i;
1900 
1901 	d->mbps_val = kcalloc_node(num_closid, sizeof(*d->mbps_val),
1902 				   GFP_KERNEL, cpu_to_node(cpu));
1903 	if (!d->mbps_val)
1904 		return -ENOMEM;
1905 
1906 	for (i = 0; i < num_closid; i++)
1907 		d->mbps_val[i] = MBA_MAX_MBPS;
1908 
1909 	return 0;
1910 }
1911 
1912 static void mba_sc_domain_destroy(struct rdt_resource *r,
1913 				  struct rdt_domain *d)
1914 {
1915 	kfree(d->mbps_val);
1916 	d->mbps_val = NULL;
1917 }
1918 
1919 /*
1920  * MBA software controller is supported only if
1921  * MBM is supported and MBA is in linear scale.
1922  */
1923 static bool supports_mba_mbps(void)
1924 {
1925 	struct rdt_resource *r = &rdt_resources_all[RDT_RESOURCE_MBA].r_resctrl;
1926 
1927 	return (is_mbm_local_enabled() &&
1928 		r->alloc_capable && is_mba_linear());
1929 }
1930 
1931 /*
1932  * Enable or disable the MBA software controller
1933  * which helps user specify bandwidth in MBps.
1934  */
1935 static int set_mba_sc(bool mba_sc)
1936 {
1937 	struct rdt_resource *r = &rdt_resources_all[RDT_RESOURCE_MBA].r_resctrl;
1938 	u32 num_closid = resctrl_arch_get_num_closid(r);
1939 	struct rdt_domain *d;
1940 	int i;
1941 
1942 	if (!supports_mba_mbps() || mba_sc == is_mba_sc(r))
1943 		return -EINVAL;
1944 
1945 	r->membw.mba_sc = mba_sc;
1946 
1947 	list_for_each_entry(d, &r->domains, list) {
1948 		for (i = 0; i < num_closid; i++)
1949 			d->mbps_val[i] = MBA_MAX_MBPS;
1950 	}
1951 
1952 	return 0;
1953 }
1954 
1955 static int cdp_enable(int level)
1956 {
1957 	struct rdt_resource *r_l = &rdt_resources_all[level].r_resctrl;
1958 	int ret;
1959 
1960 	if (!r_l->alloc_capable)
1961 		return -EINVAL;
1962 
1963 	ret = set_cache_qos_cfg(level, true);
1964 	if (!ret)
1965 		rdt_resources_all[level].cdp_enabled = true;
1966 
1967 	return ret;
1968 }
1969 
1970 static void cdp_disable(int level)
1971 {
1972 	struct rdt_hw_resource *r_hw = &rdt_resources_all[level];
1973 
1974 	if (r_hw->cdp_enabled) {
1975 		set_cache_qos_cfg(level, false);
1976 		r_hw->cdp_enabled = false;
1977 	}
1978 }
1979 
1980 int resctrl_arch_set_cdp_enabled(enum resctrl_res_level l, bool enable)
1981 {
1982 	struct rdt_hw_resource *hw_res = &rdt_resources_all[l];
1983 
1984 	if (!hw_res->r_resctrl.cdp_capable)
1985 		return -EINVAL;
1986 
1987 	if (enable)
1988 		return cdp_enable(l);
1989 
1990 	cdp_disable(l);
1991 
1992 	return 0;
1993 }
1994 
1995 static void cdp_disable_all(void)
1996 {
1997 	if (resctrl_arch_get_cdp_enabled(RDT_RESOURCE_L3))
1998 		resctrl_arch_set_cdp_enabled(RDT_RESOURCE_L3, false);
1999 	if (resctrl_arch_get_cdp_enabled(RDT_RESOURCE_L2))
2000 		resctrl_arch_set_cdp_enabled(RDT_RESOURCE_L2, false);
2001 }
2002 
2003 /*
2004  * We don't allow rdtgroup directories to be created anywhere
2005  * except the root directory. Thus when looking for the rdtgroup
2006  * structure for a kernfs node we are either looking at a directory,
2007  * in which case the rdtgroup structure is pointed at by the "priv"
2008  * field, otherwise we have a file, and need only look to the parent
2009  * to find the rdtgroup.
2010  */
2011 static struct rdtgroup *kernfs_to_rdtgroup(struct kernfs_node *kn)
2012 {
2013 	if (kernfs_type(kn) == KERNFS_DIR) {
2014 		/*
2015 		 * All the resource directories use "kn->priv"
2016 		 * to point to the "struct rdtgroup" for the
2017 		 * resource. "info" and its subdirectories don't
2018 		 * have rdtgroup structures, so return NULL here.
2019 		 */
2020 		if (kn == kn_info || kn->parent == kn_info)
2021 			return NULL;
2022 		else
2023 			return kn->priv;
2024 	} else {
2025 		return kn->parent->priv;
2026 	}
2027 }
2028 
2029 struct rdtgroup *rdtgroup_kn_lock_live(struct kernfs_node *kn)
2030 {
2031 	struct rdtgroup *rdtgrp = kernfs_to_rdtgroup(kn);
2032 
2033 	if (!rdtgrp)
2034 		return NULL;
2035 
2036 	atomic_inc(&rdtgrp->waitcount);
2037 	kernfs_break_active_protection(kn);
2038 
2039 	mutex_lock(&rdtgroup_mutex);
2040 
2041 	/* Was this group deleted while we waited? */
2042 	if (rdtgrp->flags & RDT_DELETED)
2043 		return NULL;
2044 
2045 	return rdtgrp;
2046 }
2047 
2048 void rdtgroup_kn_unlock(struct kernfs_node *kn)
2049 {
2050 	struct rdtgroup *rdtgrp = kernfs_to_rdtgroup(kn);
2051 
2052 	if (!rdtgrp)
2053 		return;
2054 
2055 	mutex_unlock(&rdtgroup_mutex);
2056 
2057 	if (atomic_dec_and_test(&rdtgrp->waitcount) &&
2058 	    (rdtgrp->flags & RDT_DELETED)) {
2059 		if (rdtgrp->mode == RDT_MODE_PSEUDO_LOCKSETUP ||
2060 		    rdtgrp->mode == RDT_MODE_PSEUDO_LOCKED)
2061 			rdtgroup_pseudo_lock_remove(rdtgrp);
2062 		kernfs_unbreak_active_protection(kn);
2063 		rdtgroup_remove(rdtgrp);
2064 	} else {
2065 		kernfs_unbreak_active_protection(kn);
2066 	}
2067 }
2068 
2069 static int mkdir_mondata_all(struct kernfs_node *parent_kn,
2070 			     struct rdtgroup *prgrp,
2071 			     struct kernfs_node **mon_data_kn);
2072 
2073 static int rdt_enable_ctx(struct rdt_fs_context *ctx)
2074 {
2075 	int ret = 0;
2076 
2077 	if (ctx->enable_cdpl2)
2078 		ret = resctrl_arch_set_cdp_enabled(RDT_RESOURCE_L2, true);
2079 
2080 	if (!ret && ctx->enable_cdpl3)
2081 		ret = resctrl_arch_set_cdp_enabled(RDT_RESOURCE_L3, true);
2082 
2083 	if (!ret && ctx->enable_mba_mbps)
2084 		ret = set_mba_sc(true);
2085 
2086 	return ret;
2087 }
2088 
2089 static int schemata_list_add(struct rdt_resource *r, enum resctrl_conf_type type)
2090 {
2091 	struct resctrl_schema *s;
2092 	const char *suffix = "";
2093 	int ret, cl;
2094 
2095 	s = kzalloc(sizeof(*s), GFP_KERNEL);
2096 	if (!s)
2097 		return -ENOMEM;
2098 
2099 	s->res = r;
2100 	s->num_closid = resctrl_arch_get_num_closid(r);
2101 	if (resctrl_arch_get_cdp_enabled(r->rid))
2102 		s->num_closid /= 2;
2103 
2104 	s->conf_type = type;
2105 	switch (type) {
2106 	case CDP_CODE:
2107 		suffix = "CODE";
2108 		break;
2109 	case CDP_DATA:
2110 		suffix = "DATA";
2111 		break;
2112 	case CDP_NONE:
2113 		suffix = "";
2114 		break;
2115 	}
2116 
2117 	ret = snprintf(s->name, sizeof(s->name), "%s%s", r->name, suffix);
2118 	if (ret >= sizeof(s->name)) {
2119 		kfree(s);
2120 		return -EINVAL;
2121 	}
2122 
2123 	cl = strlen(s->name);
2124 
2125 	/*
2126 	 * If CDP is supported by this resource, but not enabled,
2127 	 * include the suffix. This ensures the tabular format of the
2128 	 * schemata file does not change between mounts of the filesystem.
2129 	 */
2130 	if (r->cdp_capable && !resctrl_arch_get_cdp_enabled(r->rid))
2131 		cl += 4;
2132 
2133 	if (cl > max_name_width)
2134 		max_name_width = cl;
2135 
2136 	INIT_LIST_HEAD(&s->list);
2137 	list_add(&s->list, &resctrl_schema_all);
2138 
2139 	return 0;
2140 }
2141 
2142 static int schemata_list_create(void)
2143 {
2144 	struct rdt_resource *r;
2145 	int ret = 0;
2146 
2147 	for_each_alloc_capable_rdt_resource(r) {
2148 		if (resctrl_arch_get_cdp_enabled(r->rid)) {
2149 			ret = schemata_list_add(r, CDP_CODE);
2150 			if (ret)
2151 				break;
2152 
2153 			ret = schemata_list_add(r, CDP_DATA);
2154 		} else {
2155 			ret = schemata_list_add(r, CDP_NONE);
2156 		}
2157 
2158 		if (ret)
2159 			break;
2160 	}
2161 
2162 	return ret;
2163 }
2164 
2165 static void schemata_list_destroy(void)
2166 {
2167 	struct resctrl_schema *s, *tmp;
2168 
2169 	list_for_each_entry_safe(s, tmp, &resctrl_schema_all, list) {
2170 		list_del(&s->list);
2171 		kfree(s);
2172 	}
2173 }
2174 
2175 static int rdt_get_tree(struct fs_context *fc)
2176 {
2177 	struct rdt_fs_context *ctx = rdt_fc2context(fc);
2178 	struct rdt_domain *dom;
2179 	struct rdt_resource *r;
2180 	int ret;
2181 
2182 	cpus_read_lock();
2183 	mutex_lock(&rdtgroup_mutex);
2184 	/*
2185 	 * resctrl file system can only be mounted once.
2186 	 */
2187 	if (static_branch_unlikely(&rdt_enable_key)) {
2188 		ret = -EBUSY;
2189 		goto out;
2190 	}
2191 
2192 	ret = rdt_enable_ctx(ctx);
2193 	if (ret < 0)
2194 		goto out_cdp;
2195 
2196 	ret = schemata_list_create();
2197 	if (ret) {
2198 		schemata_list_destroy();
2199 		goto out_mba;
2200 	}
2201 
2202 	closid_init();
2203 
2204 	ret = rdtgroup_create_info_dir(rdtgroup_default.kn);
2205 	if (ret < 0)
2206 		goto out_schemata_free;
2207 
2208 	if (rdt_mon_capable) {
2209 		ret = mongroup_create_dir(rdtgroup_default.kn,
2210 					  &rdtgroup_default, "mon_groups",
2211 					  &kn_mongrp);
2212 		if (ret < 0)
2213 			goto out_info;
2214 
2215 		ret = mkdir_mondata_all(rdtgroup_default.kn,
2216 					&rdtgroup_default, &kn_mondata);
2217 		if (ret < 0)
2218 			goto out_mongrp;
2219 		rdtgroup_default.mon.mon_data_kn = kn_mondata;
2220 	}
2221 
2222 	ret = rdt_pseudo_lock_init();
2223 	if (ret)
2224 		goto out_mondata;
2225 
2226 	ret = kernfs_get_tree(fc);
2227 	if (ret < 0)
2228 		goto out_psl;
2229 
2230 	if (rdt_alloc_capable)
2231 		static_branch_enable_cpuslocked(&rdt_alloc_enable_key);
2232 	if (rdt_mon_capable)
2233 		static_branch_enable_cpuslocked(&rdt_mon_enable_key);
2234 
2235 	if (rdt_alloc_capable || rdt_mon_capable)
2236 		static_branch_enable_cpuslocked(&rdt_enable_key);
2237 
2238 	if (is_mbm_enabled()) {
2239 		r = &rdt_resources_all[RDT_RESOURCE_L3].r_resctrl;
2240 		list_for_each_entry(dom, &r->domains, list)
2241 			mbm_setup_overflow_handler(dom, MBM_OVERFLOW_INTERVAL);
2242 	}
2243 
2244 	goto out;
2245 
2246 out_psl:
2247 	rdt_pseudo_lock_release();
2248 out_mondata:
2249 	if (rdt_mon_capable)
2250 		kernfs_remove(kn_mondata);
2251 out_mongrp:
2252 	if (rdt_mon_capable)
2253 		kernfs_remove(kn_mongrp);
2254 out_info:
2255 	kernfs_remove(kn_info);
2256 out_schemata_free:
2257 	schemata_list_destroy();
2258 out_mba:
2259 	if (ctx->enable_mba_mbps)
2260 		set_mba_sc(false);
2261 out_cdp:
2262 	cdp_disable_all();
2263 out:
2264 	rdt_last_cmd_clear();
2265 	mutex_unlock(&rdtgroup_mutex);
2266 	cpus_read_unlock();
2267 	return ret;
2268 }
2269 
2270 enum rdt_param {
2271 	Opt_cdp,
2272 	Opt_cdpl2,
2273 	Opt_mba_mbps,
2274 	nr__rdt_params
2275 };
2276 
2277 static const struct fs_parameter_spec rdt_fs_parameters[] = {
2278 	fsparam_flag("cdp",		Opt_cdp),
2279 	fsparam_flag("cdpl2",		Opt_cdpl2),
2280 	fsparam_flag("mba_MBps",	Opt_mba_mbps),
2281 	{}
2282 };
2283 
2284 static int rdt_parse_param(struct fs_context *fc, struct fs_parameter *param)
2285 {
2286 	struct rdt_fs_context *ctx = rdt_fc2context(fc);
2287 	struct fs_parse_result result;
2288 	int opt;
2289 
2290 	opt = fs_parse(fc, rdt_fs_parameters, param, &result);
2291 	if (opt < 0)
2292 		return opt;
2293 
2294 	switch (opt) {
2295 	case Opt_cdp:
2296 		ctx->enable_cdpl3 = true;
2297 		return 0;
2298 	case Opt_cdpl2:
2299 		ctx->enable_cdpl2 = true;
2300 		return 0;
2301 	case Opt_mba_mbps:
2302 		if (!supports_mba_mbps())
2303 			return -EINVAL;
2304 		ctx->enable_mba_mbps = true;
2305 		return 0;
2306 	}
2307 
2308 	return -EINVAL;
2309 }
2310 
2311 static void rdt_fs_context_free(struct fs_context *fc)
2312 {
2313 	struct rdt_fs_context *ctx = rdt_fc2context(fc);
2314 
2315 	kernfs_free_fs_context(fc);
2316 	kfree(ctx);
2317 }
2318 
2319 static const struct fs_context_operations rdt_fs_context_ops = {
2320 	.free		= rdt_fs_context_free,
2321 	.parse_param	= rdt_parse_param,
2322 	.get_tree	= rdt_get_tree,
2323 };
2324 
2325 static int rdt_init_fs_context(struct fs_context *fc)
2326 {
2327 	struct rdt_fs_context *ctx;
2328 
2329 	ctx = kzalloc(sizeof(struct rdt_fs_context), GFP_KERNEL);
2330 	if (!ctx)
2331 		return -ENOMEM;
2332 
2333 	ctx->kfc.root = rdt_root;
2334 	ctx->kfc.magic = RDTGROUP_SUPER_MAGIC;
2335 	fc->fs_private = &ctx->kfc;
2336 	fc->ops = &rdt_fs_context_ops;
2337 	put_user_ns(fc->user_ns);
2338 	fc->user_ns = get_user_ns(&init_user_ns);
2339 	fc->global = true;
2340 	return 0;
2341 }
2342 
2343 static int reset_all_ctrls(struct rdt_resource *r)
2344 {
2345 	struct rdt_hw_resource *hw_res = resctrl_to_arch_res(r);
2346 	struct rdt_hw_domain *hw_dom;
2347 	struct msr_param msr_param;
2348 	cpumask_var_t cpu_mask;
2349 	struct rdt_domain *d;
2350 	int i, cpu;
2351 
2352 	if (!zalloc_cpumask_var(&cpu_mask, GFP_KERNEL))
2353 		return -ENOMEM;
2354 
2355 	msr_param.res = r;
2356 	msr_param.low = 0;
2357 	msr_param.high = hw_res->num_closid;
2358 
2359 	/*
2360 	 * Disable resource control for this resource by setting all
2361 	 * CBMs in all domains to the maximum mask value. Pick one CPU
2362 	 * from each domain to update the MSRs below.
2363 	 */
2364 	list_for_each_entry(d, &r->domains, list) {
2365 		hw_dom = resctrl_to_arch_dom(d);
2366 		cpumask_set_cpu(cpumask_any(&d->cpu_mask), cpu_mask);
2367 
2368 		for (i = 0; i < hw_res->num_closid; i++)
2369 			hw_dom->ctrl_val[i] = r->default_ctrl;
2370 	}
2371 	cpu = get_cpu();
2372 	/* Update CBM on this cpu if it's in cpu_mask. */
2373 	if (cpumask_test_cpu(cpu, cpu_mask))
2374 		rdt_ctrl_update(&msr_param);
2375 	/* Update CBM on all other cpus in cpu_mask. */
2376 	smp_call_function_many(cpu_mask, rdt_ctrl_update, &msr_param, 1);
2377 	put_cpu();
2378 
2379 	free_cpumask_var(cpu_mask);
2380 
2381 	return 0;
2382 }
2383 
2384 /*
2385  * Move tasks from one to the other group. If @from is NULL, then all tasks
2386  * in the systems are moved unconditionally (used for teardown).
2387  *
2388  * If @mask is not NULL the cpus on which moved tasks are running are set
2389  * in that mask so the update smp function call is restricted to affected
2390  * cpus.
2391  */
2392 static void rdt_move_group_tasks(struct rdtgroup *from, struct rdtgroup *to,
2393 				 struct cpumask *mask)
2394 {
2395 	struct task_struct *p, *t;
2396 
2397 	read_lock(&tasklist_lock);
2398 	for_each_process_thread(p, t) {
2399 		if (!from || is_closid_match(t, from) ||
2400 		    is_rmid_match(t, from)) {
2401 			WRITE_ONCE(t->closid, to->closid);
2402 			WRITE_ONCE(t->rmid, to->mon.rmid);
2403 
2404 			/*
2405 			 * If the task is on a CPU, set the CPU in the mask.
2406 			 * The detection is inaccurate as tasks might move or
2407 			 * schedule before the smp function call takes place.
2408 			 * In such a case the function call is pointless, but
2409 			 * there is no other side effect.
2410 			 */
2411 			if (IS_ENABLED(CONFIG_SMP) && mask && task_curr(t))
2412 				cpumask_set_cpu(task_cpu(t), mask);
2413 		}
2414 	}
2415 	read_unlock(&tasklist_lock);
2416 }
2417 
2418 static void free_all_child_rdtgrp(struct rdtgroup *rdtgrp)
2419 {
2420 	struct rdtgroup *sentry, *stmp;
2421 	struct list_head *head;
2422 
2423 	head = &rdtgrp->mon.crdtgrp_list;
2424 	list_for_each_entry_safe(sentry, stmp, head, mon.crdtgrp_list) {
2425 		free_rmid(sentry->mon.rmid);
2426 		list_del(&sentry->mon.crdtgrp_list);
2427 
2428 		if (atomic_read(&sentry->waitcount) != 0)
2429 			sentry->flags = RDT_DELETED;
2430 		else
2431 			rdtgroup_remove(sentry);
2432 	}
2433 }
2434 
2435 /*
2436  * Forcibly remove all of subdirectories under root.
2437  */
2438 static void rmdir_all_sub(void)
2439 {
2440 	struct rdtgroup *rdtgrp, *tmp;
2441 
2442 	/* Move all tasks to the default resource group */
2443 	rdt_move_group_tasks(NULL, &rdtgroup_default, NULL);
2444 
2445 	list_for_each_entry_safe(rdtgrp, tmp, &rdt_all_groups, rdtgroup_list) {
2446 		/* Free any child rmids */
2447 		free_all_child_rdtgrp(rdtgrp);
2448 
2449 		/* Remove each rdtgroup other than root */
2450 		if (rdtgrp == &rdtgroup_default)
2451 			continue;
2452 
2453 		if (rdtgrp->mode == RDT_MODE_PSEUDO_LOCKSETUP ||
2454 		    rdtgrp->mode == RDT_MODE_PSEUDO_LOCKED)
2455 			rdtgroup_pseudo_lock_remove(rdtgrp);
2456 
2457 		/*
2458 		 * Give any CPUs back to the default group. We cannot copy
2459 		 * cpu_online_mask because a CPU might have executed the
2460 		 * offline callback already, but is still marked online.
2461 		 */
2462 		cpumask_or(&rdtgroup_default.cpu_mask,
2463 			   &rdtgroup_default.cpu_mask, &rdtgrp->cpu_mask);
2464 
2465 		free_rmid(rdtgrp->mon.rmid);
2466 
2467 		kernfs_remove(rdtgrp->kn);
2468 		list_del(&rdtgrp->rdtgroup_list);
2469 
2470 		if (atomic_read(&rdtgrp->waitcount) != 0)
2471 			rdtgrp->flags = RDT_DELETED;
2472 		else
2473 			rdtgroup_remove(rdtgrp);
2474 	}
2475 	/* Notify online CPUs to update per cpu storage and PQR_ASSOC MSR */
2476 	update_closid_rmid(cpu_online_mask, &rdtgroup_default);
2477 
2478 	kernfs_remove(kn_info);
2479 	kernfs_remove(kn_mongrp);
2480 	kernfs_remove(kn_mondata);
2481 }
2482 
2483 static void rdt_kill_sb(struct super_block *sb)
2484 {
2485 	struct rdt_resource *r;
2486 
2487 	cpus_read_lock();
2488 	mutex_lock(&rdtgroup_mutex);
2489 
2490 	set_mba_sc(false);
2491 
2492 	/*Put everything back to default values. */
2493 	for_each_alloc_capable_rdt_resource(r)
2494 		reset_all_ctrls(r);
2495 	cdp_disable_all();
2496 	rmdir_all_sub();
2497 	rdt_pseudo_lock_release();
2498 	rdtgroup_default.mode = RDT_MODE_SHAREABLE;
2499 	schemata_list_destroy();
2500 	static_branch_disable_cpuslocked(&rdt_alloc_enable_key);
2501 	static_branch_disable_cpuslocked(&rdt_mon_enable_key);
2502 	static_branch_disable_cpuslocked(&rdt_enable_key);
2503 	kernfs_kill_sb(sb);
2504 	mutex_unlock(&rdtgroup_mutex);
2505 	cpus_read_unlock();
2506 }
2507 
2508 static struct file_system_type rdt_fs_type = {
2509 	.name			= "resctrl",
2510 	.init_fs_context	= rdt_init_fs_context,
2511 	.parameters		= rdt_fs_parameters,
2512 	.kill_sb		= rdt_kill_sb,
2513 };
2514 
2515 static int mon_addfile(struct kernfs_node *parent_kn, const char *name,
2516 		       void *priv)
2517 {
2518 	struct kernfs_node *kn;
2519 	int ret = 0;
2520 
2521 	kn = __kernfs_create_file(parent_kn, name, 0444,
2522 				  GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, 0,
2523 				  &kf_mondata_ops, priv, NULL, NULL);
2524 	if (IS_ERR(kn))
2525 		return PTR_ERR(kn);
2526 
2527 	ret = rdtgroup_kn_set_ugid(kn);
2528 	if (ret) {
2529 		kernfs_remove(kn);
2530 		return ret;
2531 	}
2532 
2533 	return ret;
2534 }
2535 
2536 /*
2537  * Remove all subdirectories of mon_data of ctrl_mon groups
2538  * and monitor groups with given domain id.
2539  */
2540 static void rmdir_mondata_subdir_allrdtgrp(struct rdt_resource *r,
2541 					   unsigned int dom_id)
2542 {
2543 	struct rdtgroup *prgrp, *crgrp;
2544 	char name[32];
2545 
2546 	list_for_each_entry(prgrp, &rdt_all_groups, rdtgroup_list) {
2547 		sprintf(name, "mon_%s_%02d", r->name, dom_id);
2548 		kernfs_remove_by_name(prgrp->mon.mon_data_kn, name);
2549 
2550 		list_for_each_entry(crgrp, &prgrp->mon.crdtgrp_list, mon.crdtgrp_list)
2551 			kernfs_remove_by_name(crgrp->mon.mon_data_kn, name);
2552 	}
2553 }
2554 
2555 static int mkdir_mondata_subdir(struct kernfs_node *parent_kn,
2556 				struct rdt_domain *d,
2557 				struct rdt_resource *r, struct rdtgroup *prgrp)
2558 {
2559 	union mon_data_bits priv;
2560 	struct kernfs_node *kn;
2561 	struct mon_evt *mevt;
2562 	struct rmid_read rr;
2563 	char name[32];
2564 	int ret;
2565 
2566 	sprintf(name, "mon_%s_%02d", r->name, d->id);
2567 	/* create the directory */
2568 	kn = kernfs_create_dir(parent_kn, name, parent_kn->mode, prgrp);
2569 	if (IS_ERR(kn))
2570 		return PTR_ERR(kn);
2571 
2572 	ret = rdtgroup_kn_set_ugid(kn);
2573 	if (ret)
2574 		goto out_destroy;
2575 
2576 	if (WARN_ON(list_empty(&r->evt_list))) {
2577 		ret = -EPERM;
2578 		goto out_destroy;
2579 	}
2580 
2581 	priv.u.rid = r->rid;
2582 	priv.u.domid = d->id;
2583 	list_for_each_entry(mevt, &r->evt_list, list) {
2584 		priv.u.evtid = mevt->evtid;
2585 		ret = mon_addfile(kn, mevt->name, priv.priv);
2586 		if (ret)
2587 			goto out_destroy;
2588 
2589 		if (is_mbm_event(mevt->evtid))
2590 			mon_event_read(&rr, r, d, prgrp, mevt->evtid, true);
2591 	}
2592 	kernfs_activate(kn);
2593 	return 0;
2594 
2595 out_destroy:
2596 	kernfs_remove(kn);
2597 	return ret;
2598 }
2599 
2600 /*
2601  * Add all subdirectories of mon_data for "ctrl_mon" groups
2602  * and "monitor" groups with given domain id.
2603  */
2604 static void mkdir_mondata_subdir_allrdtgrp(struct rdt_resource *r,
2605 					   struct rdt_domain *d)
2606 {
2607 	struct kernfs_node *parent_kn;
2608 	struct rdtgroup *prgrp, *crgrp;
2609 	struct list_head *head;
2610 
2611 	list_for_each_entry(prgrp, &rdt_all_groups, rdtgroup_list) {
2612 		parent_kn = prgrp->mon.mon_data_kn;
2613 		mkdir_mondata_subdir(parent_kn, d, r, prgrp);
2614 
2615 		head = &prgrp->mon.crdtgrp_list;
2616 		list_for_each_entry(crgrp, head, mon.crdtgrp_list) {
2617 			parent_kn = crgrp->mon.mon_data_kn;
2618 			mkdir_mondata_subdir(parent_kn, d, r, crgrp);
2619 		}
2620 	}
2621 }
2622 
2623 static int mkdir_mondata_subdir_alldom(struct kernfs_node *parent_kn,
2624 				       struct rdt_resource *r,
2625 				       struct rdtgroup *prgrp)
2626 {
2627 	struct rdt_domain *dom;
2628 	int ret;
2629 
2630 	list_for_each_entry(dom, &r->domains, list) {
2631 		ret = mkdir_mondata_subdir(parent_kn, dom, r, prgrp);
2632 		if (ret)
2633 			return ret;
2634 	}
2635 
2636 	return 0;
2637 }
2638 
2639 /*
2640  * This creates a directory mon_data which contains the monitored data.
2641  *
2642  * mon_data has one directory for each domain which are named
2643  * in the format mon_<domain_name>_<domain_id>. For ex: A mon_data
2644  * with L3 domain looks as below:
2645  * ./mon_data:
2646  * mon_L3_00
2647  * mon_L3_01
2648  * mon_L3_02
2649  * ...
2650  *
2651  * Each domain directory has one file per event:
2652  * ./mon_L3_00/:
2653  * llc_occupancy
2654  *
2655  */
2656 static int mkdir_mondata_all(struct kernfs_node *parent_kn,
2657 			     struct rdtgroup *prgrp,
2658 			     struct kernfs_node **dest_kn)
2659 {
2660 	struct rdt_resource *r;
2661 	struct kernfs_node *kn;
2662 	int ret;
2663 
2664 	/*
2665 	 * Create the mon_data directory first.
2666 	 */
2667 	ret = mongroup_create_dir(parent_kn, prgrp, "mon_data", &kn);
2668 	if (ret)
2669 		return ret;
2670 
2671 	if (dest_kn)
2672 		*dest_kn = kn;
2673 
2674 	/*
2675 	 * Create the subdirectories for each domain. Note that all events
2676 	 * in a domain like L3 are grouped into a resource whose domain is L3
2677 	 */
2678 	for_each_mon_capable_rdt_resource(r) {
2679 		ret = mkdir_mondata_subdir_alldom(kn, r, prgrp);
2680 		if (ret)
2681 			goto out_destroy;
2682 	}
2683 
2684 	return 0;
2685 
2686 out_destroy:
2687 	kernfs_remove(kn);
2688 	return ret;
2689 }
2690 
2691 /**
2692  * cbm_ensure_valid - Enforce validity on provided CBM
2693  * @_val:	Candidate CBM
2694  * @r:		RDT resource to which the CBM belongs
2695  *
2696  * The provided CBM represents all cache portions available for use. This
2697  * may be represented by a bitmap that does not consist of contiguous ones
2698  * and thus be an invalid CBM.
2699  * Here the provided CBM is forced to be a valid CBM by only considering
2700  * the first set of contiguous bits as valid and clearing all bits.
2701  * The intention here is to provide a valid default CBM with which a new
2702  * resource group is initialized. The user can follow this with a
2703  * modification to the CBM if the default does not satisfy the
2704  * requirements.
2705  */
2706 static u32 cbm_ensure_valid(u32 _val, struct rdt_resource *r)
2707 {
2708 	unsigned int cbm_len = r->cache.cbm_len;
2709 	unsigned long first_bit, zero_bit;
2710 	unsigned long val = _val;
2711 
2712 	if (!val)
2713 		return 0;
2714 
2715 	first_bit = find_first_bit(&val, cbm_len);
2716 	zero_bit = find_next_zero_bit(&val, cbm_len, first_bit);
2717 
2718 	/* Clear any remaining bits to ensure contiguous region */
2719 	bitmap_clear(&val, zero_bit, cbm_len - zero_bit);
2720 	return (u32)val;
2721 }
2722 
2723 /*
2724  * Initialize cache resources per RDT domain
2725  *
2726  * Set the RDT domain up to start off with all usable allocations. That is,
2727  * all shareable and unused bits. All-zero CBM is invalid.
2728  */
2729 static int __init_one_rdt_domain(struct rdt_domain *d, struct resctrl_schema *s,
2730 				 u32 closid)
2731 {
2732 	enum resctrl_conf_type peer_type = resctrl_peer_type(s->conf_type);
2733 	enum resctrl_conf_type t = s->conf_type;
2734 	struct resctrl_staged_config *cfg;
2735 	struct rdt_resource *r = s->res;
2736 	u32 used_b = 0, unused_b = 0;
2737 	unsigned long tmp_cbm;
2738 	enum rdtgrp_mode mode;
2739 	u32 peer_ctl, ctrl_val;
2740 	int i;
2741 
2742 	cfg = &d->staged_config[t];
2743 	cfg->have_new_ctrl = false;
2744 	cfg->new_ctrl = r->cache.shareable_bits;
2745 	used_b = r->cache.shareable_bits;
2746 	for (i = 0; i < closids_supported(); i++) {
2747 		if (closid_allocated(i) && i != closid) {
2748 			mode = rdtgroup_mode_by_closid(i);
2749 			if (mode == RDT_MODE_PSEUDO_LOCKSETUP)
2750 				/*
2751 				 * ctrl values for locksetup aren't relevant
2752 				 * until the schemata is written, and the mode
2753 				 * becomes RDT_MODE_PSEUDO_LOCKED.
2754 				 */
2755 				continue;
2756 			/*
2757 			 * If CDP is active include peer domain's
2758 			 * usage to ensure there is no overlap
2759 			 * with an exclusive group.
2760 			 */
2761 			if (resctrl_arch_get_cdp_enabled(r->rid))
2762 				peer_ctl = resctrl_arch_get_config(r, d, i,
2763 								   peer_type);
2764 			else
2765 				peer_ctl = 0;
2766 			ctrl_val = resctrl_arch_get_config(r, d, i,
2767 							   s->conf_type);
2768 			used_b |= ctrl_val | peer_ctl;
2769 			if (mode == RDT_MODE_SHAREABLE)
2770 				cfg->new_ctrl |= ctrl_val | peer_ctl;
2771 		}
2772 	}
2773 	if (d->plr && d->plr->cbm > 0)
2774 		used_b |= d->plr->cbm;
2775 	unused_b = used_b ^ (BIT_MASK(r->cache.cbm_len) - 1);
2776 	unused_b &= BIT_MASK(r->cache.cbm_len) - 1;
2777 	cfg->new_ctrl |= unused_b;
2778 	/*
2779 	 * Force the initial CBM to be valid, user can
2780 	 * modify the CBM based on system availability.
2781 	 */
2782 	cfg->new_ctrl = cbm_ensure_valid(cfg->new_ctrl, r);
2783 	/*
2784 	 * Assign the u32 CBM to an unsigned long to ensure that
2785 	 * bitmap_weight() does not access out-of-bound memory.
2786 	 */
2787 	tmp_cbm = cfg->new_ctrl;
2788 	if (bitmap_weight(&tmp_cbm, r->cache.cbm_len) < r->cache.min_cbm_bits) {
2789 		rdt_last_cmd_printf("No space on %s:%d\n", s->name, d->id);
2790 		return -ENOSPC;
2791 	}
2792 	cfg->have_new_ctrl = true;
2793 
2794 	return 0;
2795 }
2796 
2797 /*
2798  * Initialize cache resources with default values.
2799  *
2800  * A new RDT group is being created on an allocation capable (CAT)
2801  * supporting system. Set this group up to start off with all usable
2802  * allocations.
2803  *
2804  * If there are no more shareable bits available on any domain then
2805  * the entire allocation will fail.
2806  */
2807 static int rdtgroup_init_cat(struct resctrl_schema *s, u32 closid)
2808 {
2809 	struct rdt_domain *d;
2810 	int ret;
2811 
2812 	list_for_each_entry(d, &s->res->domains, list) {
2813 		ret = __init_one_rdt_domain(d, s, closid);
2814 		if (ret < 0)
2815 			return ret;
2816 	}
2817 
2818 	return 0;
2819 }
2820 
2821 /* Initialize MBA resource with default values. */
2822 static void rdtgroup_init_mba(struct rdt_resource *r, u32 closid)
2823 {
2824 	struct resctrl_staged_config *cfg;
2825 	struct rdt_domain *d;
2826 
2827 	list_for_each_entry(d, &r->domains, list) {
2828 		if (is_mba_sc(r)) {
2829 			d->mbps_val[closid] = MBA_MAX_MBPS;
2830 			continue;
2831 		}
2832 
2833 		cfg = &d->staged_config[CDP_NONE];
2834 		cfg->new_ctrl = r->default_ctrl;
2835 		cfg->have_new_ctrl = true;
2836 	}
2837 }
2838 
2839 /* Initialize the RDT group's allocations. */
2840 static int rdtgroup_init_alloc(struct rdtgroup *rdtgrp)
2841 {
2842 	struct resctrl_schema *s;
2843 	struct rdt_resource *r;
2844 	int ret;
2845 
2846 	list_for_each_entry(s, &resctrl_schema_all, list) {
2847 		r = s->res;
2848 		if (r->rid == RDT_RESOURCE_MBA) {
2849 			rdtgroup_init_mba(r, rdtgrp->closid);
2850 			if (is_mba_sc(r))
2851 				continue;
2852 		} else {
2853 			ret = rdtgroup_init_cat(s, rdtgrp->closid);
2854 			if (ret < 0)
2855 				return ret;
2856 		}
2857 
2858 		ret = resctrl_arch_update_domains(r, rdtgrp->closid);
2859 		if (ret < 0) {
2860 			rdt_last_cmd_puts("Failed to initialize allocations\n");
2861 			return ret;
2862 		}
2863 
2864 	}
2865 
2866 	rdtgrp->mode = RDT_MODE_SHAREABLE;
2867 
2868 	return 0;
2869 }
2870 
2871 static int mkdir_rdt_prepare(struct kernfs_node *parent_kn,
2872 			     const char *name, umode_t mode,
2873 			     enum rdt_group_type rtype, struct rdtgroup **r)
2874 {
2875 	struct rdtgroup *prdtgrp, *rdtgrp;
2876 	struct kernfs_node *kn;
2877 	uint files = 0;
2878 	int ret;
2879 
2880 	prdtgrp = rdtgroup_kn_lock_live(parent_kn);
2881 	if (!prdtgrp) {
2882 		ret = -ENODEV;
2883 		goto out_unlock;
2884 	}
2885 
2886 	if (rtype == RDTMON_GROUP &&
2887 	    (prdtgrp->mode == RDT_MODE_PSEUDO_LOCKSETUP ||
2888 	     prdtgrp->mode == RDT_MODE_PSEUDO_LOCKED)) {
2889 		ret = -EINVAL;
2890 		rdt_last_cmd_puts("Pseudo-locking in progress\n");
2891 		goto out_unlock;
2892 	}
2893 
2894 	/* allocate the rdtgroup. */
2895 	rdtgrp = kzalloc(sizeof(*rdtgrp), GFP_KERNEL);
2896 	if (!rdtgrp) {
2897 		ret = -ENOSPC;
2898 		rdt_last_cmd_puts("Kernel out of memory\n");
2899 		goto out_unlock;
2900 	}
2901 	*r = rdtgrp;
2902 	rdtgrp->mon.parent = prdtgrp;
2903 	rdtgrp->type = rtype;
2904 	INIT_LIST_HEAD(&rdtgrp->mon.crdtgrp_list);
2905 
2906 	/* kernfs creates the directory for rdtgrp */
2907 	kn = kernfs_create_dir(parent_kn, name, mode, rdtgrp);
2908 	if (IS_ERR(kn)) {
2909 		ret = PTR_ERR(kn);
2910 		rdt_last_cmd_puts("kernfs create error\n");
2911 		goto out_free_rgrp;
2912 	}
2913 	rdtgrp->kn = kn;
2914 
2915 	/*
2916 	 * kernfs_remove() will drop the reference count on "kn" which
2917 	 * will free it. But we still need it to stick around for the
2918 	 * rdtgroup_kn_unlock(kn) call. Take one extra reference here,
2919 	 * which will be dropped by kernfs_put() in rdtgroup_remove().
2920 	 */
2921 	kernfs_get(kn);
2922 
2923 	ret = rdtgroup_kn_set_ugid(kn);
2924 	if (ret) {
2925 		rdt_last_cmd_puts("kernfs perm error\n");
2926 		goto out_destroy;
2927 	}
2928 
2929 	files = RFTYPE_BASE | BIT(RF_CTRLSHIFT + rtype);
2930 	ret = rdtgroup_add_files(kn, files);
2931 	if (ret) {
2932 		rdt_last_cmd_puts("kernfs fill error\n");
2933 		goto out_destroy;
2934 	}
2935 
2936 	if (rdt_mon_capable) {
2937 		ret = alloc_rmid();
2938 		if (ret < 0) {
2939 			rdt_last_cmd_puts("Out of RMIDs\n");
2940 			goto out_destroy;
2941 		}
2942 		rdtgrp->mon.rmid = ret;
2943 
2944 		ret = mkdir_mondata_all(kn, rdtgrp, &rdtgrp->mon.mon_data_kn);
2945 		if (ret) {
2946 			rdt_last_cmd_puts("kernfs subdir error\n");
2947 			goto out_idfree;
2948 		}
2949 	}
2950 	kernfs_activate(kn);
2951 
2952 	/*
2953 	 * The caller unlocks the parent_kn upon success.
2954 	 */
2955 	return 0;
2956 
2957 out_idfree:
2958 	free_rmid(rdtgrp->mon.rmid);
2959 out_destroy:
2960 	kernfs_put(rdtgrp->kn);
2961 	kernfs_remove(rdtgrp->kn);
2962 out_free_rgrp:
2963 	kfree(rdtgrp);
2964 out_unlock:
2965 	rdtgroup_kn_unlock(parent_kn);
2966 	return ret;
2967 }
2968 
2969 static void mkdir_rdt_prepare_clean(struct rdtgroup *rgrp)
2970 {
2971 	kernfs_remove(rgrp->kn);
2972 	free_rmid(rgrp->mon.rmid);
2973 	rdtgroup_remove(rgrp);
2974 }
2975 
2976 /*
2977  * Create a monitor group under "mon_groups" directory of a control
2978  * and monitor group(ctrl_mon). This is a resource group
2979  * to monitor a subset of tasks and cpus in its parent ctrl_mon group.
2980  */
2981 static int rdtgroup_mkdir_mon(struct kernfs_node *parent_kn,
2982 			      const char *name, umode_t mode)
2983 {
2984 	struct rdtgroup *rdtgrp, *prgrp;
2985 	int ret;
2986 
2987 	ret = mkdir_rdt_prepare(parent_kn, name, mode, RDTMON_GROUP, &rdtgrp);
2988 	if (ret)
2989 		return ret;
2990 
2991 	prgrp = rdtgrp->mon.parent;
2992 	rdtgrp->closid = prgrp->closid;
2993 
2994 	/*
2995 	 * Add the rdtgrp to the list of rdtgrps the parent
2996 	 * ctrl_mon group has to track.
2997 	 */
2998 	list_add_tail(&rdtgrp->mon.crdtgrp_list, &prgrp->mon.crdtgrp_list);
2999 
3000 	rdtgroup_kn_unlock(parent_kn);
3001 	return ret;
3002 }
3003 
3004 /*
3005  * These are rdtgroups created under the root directory. Can be used
3006  * to allocate and monitor resources.
3007  */
3008 static int rdtgroup_mkdir_ctrl_mon(struct kernfs_node *parent_kn,
3009 				   const char *name, umode_t mode)
3010 {
3011 	struct rdtgroup *rdtgrp;
3012 	struct kernfs_node *kn;
3013 	u32 closid;
3014 	int ret;
3015 
3016 	ret = mkdir_rdt_prepare(parent_kn, name, mode, RDTCTRL_GROUP, &rdtgrp);
3017 	if (ret)
3018 		return ret;
3019 
3020 	kn = rdtgrp->kn;
3021 	ret = closid_alloc();
3022 	if (ret < 0) {
3023 		rdt_last_cmd_puts("Out of CLOSIDs\n");
3024 		goto out_common_fail;
3025 	}
3026 	closid = ret;
3027 	ret = 0;
3028 
3029 	rdtgrp->closid = closid;
3030 	ret = rdtgroup_init_alloc(rdtgrp);
3031 	if (ret < 0)
3032 		goto out_id_free;
3033 
3034 	list_add(&rdtgrp->rdtgroup_list, &rdt_all_groups);
3035 
3036 	if (rdt_mon_capable) {
3037 		/*
3038 		 * Create an empty mon_groups directory to hold the subset
3039 		 * of tasks and cpus to monitor.
3040 		 */
3041 		ret = mongroup_create_dir(kn, rdtgrp, "mon_groups", NULL);
3042 		if (ret) {
3043 			rdt_last_cmd_puts("kernfs subdir error\n");
3044 			goto out_del_list;
3045 		}
3046 	}
3047 
3048 	goto out_unlock;
3049 
3050 out_del_list:
3051 	list_del(&rdtgrp->rdtgroup_list);
3052 out_id_free:
3053 	closid_free(closid);
3054 out_common_fail:
3055 	mkdir_rdt_prepare_clean(rdtgrp);
3056 out_unlock:
3057 	rdtgroup_kn_unlock(parent_kn);
3058 	return ret;
3059 }
3060 
3061 /*
3062  * We allow creating mon groups only with in a directory called "mon_groups"
3063  * which is present in every ctrl_mon group. Check if this is a valid
3064  * "mon_groups" directory.
3065  *
3066  * 1. The directory should be named "mon_groups".
3067  * 2. The mon group itself should "not" be named "mon_groups".
3068  *   This makes sure "mon_groups" directory always has a ctrl_mon group
3069  *   as parent.
3070  */
3071 static bool is_mon_groups(struct kernfs_node *kn, const char *name)
3072 {
3073 	return (!strcmp(kn->name, "mon_groups") &&
3074 		strcmp(name, "mon_groups"));
3075 }
3076 
3077 static int rdtgroup_mkdir(struct kernfs_node *parent_kn, const char *name,
3078 			  umode_t mode)
3079 {
3080 	/* Do not accept '\n' to avoid unparsable situation. */
3081 	if (strchr(name, '\n'))
3082 		return -EINVAL;
3083 
3084 	/*
3085 	 * If the parent directory is the root directory and RDT
3086 	 * allocation is supported, add a control and monitoring
3087 	 * subdirectory
3088 	 */
3089 	if (rdt_alloc_capable && parent_kn == rdtgroup_default.kn)
3090 		return rdtgroup_mkdir_ctrl_mon(parent_kn, name, mode);
3091 
3092 	/*
3093 	 * If RDT monitoring is supported and the parent directory is a valid
3094 	 * "mon_groups" directory, add a monitoring subdirectory.
3095 	 */
3096 	if (rdt_mon_capable && is_mon_groups(parent_kn, name))
3097 		return rdtgroup_mkdir_mon(parent_kn, name, mode);
3098 
3099 	return -EPERM;
3100 }
3101 
3102 static int rdtgroup_rmdir_mon(struct rdtgroup *rdtgrp, cpumask_var_t tmpmask)
3103 {
3104 	struct rdtgroup *prdtgrp = rdtgrp->mon.parent;
3105 	int cpu;
3106 
3107 	/* Give any tasks back to the parent group */
3108 	rdt_move_group_tasks(rdtgrp, prdtgrp, tmpmask);
3109 
3110 	/* Update per cpu rmid of the moved CPUs first */
3111 	for_each_cpu(cpu, &rdtgrp->cpu_mask)
3112 		per_cpu(pqr_state.default_rmid, cpu) = prdtgrp->mon.rmid;
3113 	/*
3114 	 * Update the MSR on moved CPUs and CPUs which have moved
3115 	 * task running on them.
3116 	 */
3117 	cpumask_or(tmpmask, tmpmask, &rdtgrp->cpu_mask);
3118 	update_closid_rmid(tmpmask, NULL);
3119 
3120 	rdtgrp->flags = RDT_DELETED;
3121 	free_rmid(rdtgrp->mon.rmid);
3122 
3123 	/*
3124 	 * Remove the rdtgrp from the parent ctrl_mon group's list
3125 	 */
3126 	WARN_ON(list_empty(&prdtgrp->mon.crdtgrp_list));
3127 	list_del(&rdtgrp->mon.crdtgrp_list);
3128 
3129 	kernfs_remove(rdtgrp->kn);
3130 
3131 	return 0;
3132 }
3133 
3134 static int rdtgroup_ctrl_remove(struct rdtgroup *rdtgrp)
3135 {
3136 	rdtgrp->flags = RDT_DELETED;
3137 	list_del(&rdtgrp->rdtgroup_list);
3138 
3139 	kernfs_remove(rdtgrp->kn);
3140 	return 0;
3141 }
3142 
3143 static int rdtgroup_rmdir_ctrl(struct rdtgroup *rdtgrp, cpumask_var_t tmpmask)
3144 {
3145 	int cpu;
3146 
3147 	/* Give any tasks back to the default group */
3148 	rdt_move_group_tasks(rdtgrp, &rdtgroup_default, tmpmask);
3149 
3150 	/* Give any CPUs back to the default group */
3151 	cpumask_or(&rdtgroup_default.cpu_mask,
3152 		   &rdtgroup_default.cpu_mask, &rdtgrp->cpu_mask);
3153 
3154 	/* Update per cpu closid and rmid of the moved CPUs first */
3155 	for_each_cpu(cpu, &rdtgrp->cpu_mask) {
3156 		per_cpu(pqr_state.default_closid, cpu) = rdtgroup_default.closid;
3157 		per_cpu(pqr_state.default_rmid, cpu) = rdtgroup_default.mon.rmid;
3158 	}
3159 
3160 	/*
3161 	 * Update the MSR on moved CPUs and CPUs which have moved
3162 	 * task running on them.
3163 	 */
3164 	cpumask_or(tmpmask, tmpmask, &rdtgrp->cpu_mask);
3165 	update_closid_rmid(tmpmask, NULL);
3166 
3167 	closid_free(rdtgrp->closid);
3168 	free_rmid(rdtgrp->mon.rmid);
3169 
3170 	rdtgroup_ctrl_remove(rdtgrp);
3171 
3172 	/*
3173 	 * Free all the child monitor group rmids.
3174 	 */
3175 	free_all_child_rdtgrp(rdtgrp);
3176 
3177 	return 0;
3178 }
3179 
3180 static int rdtgroup_rmdir(struct kernfs_node *kn)
3181 {
3182 	struct kernfs_node *parent_kn = kn->parent;
3183 	struct rdtgroup *rdtgrp;
3184 	cpumask_var_t tmpmask;
3185 	int ret = 0;
3186 
3187 	if (!zalloc_cpumask_var(&tmpmask, GFP_KERNEL))
3188 		return -ENOMEM;
3189 
3190 	rdtgrp = rdtgroup_kn_lock_live(kn);
3191 	if (!rdtgrp) {
3192 		ret = -EPERM;
3193 		goto out;
3194 	}
3195 
3196 	/*
3197 	 * If the rdtgroup is a ctrl_mon group and parent directory
3198 	 * is the root directory, remove the ctrl_mon group.
3199 	 *
3200 	 * If the rdtgroup is a mon group and parent directory
3201 	 * is a valid "mon_groups" directory, remove the mon group.
3202 	 */
3203 	if (rdtgrp->type == RDTCTRL_GROUP && parent_kn == rdtgroup_default.kn &&
3204 	    rdtgrp != &rdtgroup_default) {
3205 		if (rdtgrp->mode == RDT_MODE_PSEUDO_LOCKSETUP ||
3206 		    rdtgrp->mode == RDT_MODE_PSEUDO_LOCKED) {
3207 			ret = rdtgroup_ctrl_remove(rdtgrp);
3208 		} else {
3209 			ret = rdtgroup_rmdir_ctrl(rdtgrp, tmpmask);
3210 		}
3211 	} else if (rdtgrp->type == RDTMON_GROUP &&
3212 		 is_mon_groups(parent_kn, kn->name)) {
3213 		ret = rdtgroup_rmdir_mon(rdtgrp, tmpmask);
3214 	} else {
3215 		ret = -EPERM;
3216 	}
3217 
3218 out:
3219 	rdtgroup_kn_unlock(kn);
3220 	free_cpumask_var(tmpmask);
3221 	return ret;
3222 }
3223 
3224 static int rdtgroup_show_options(struct seq_file *seq, struct kernfs_root *kf)
3225 {
3226 	if (resctrl_arch_get_cdp_enabled(RDT_RESOURCE_L3))
3227 		seq_puts(seq, ",cdp");
3228 
3229 	if (resctrl_arch_get_cdp_enabled(RDT_RESOURCE_L2))
3230 		seq_puts(seq, ",cdpl2");
3231 
3232 	if (is_mba_sc(&rdt_resources_all[RDT_RESOURCE_MBA].r_resctrl))
3233 		seq_puts(seq, ",mba_MBps");
3234 
3235 	return 0;
3236 }
3237 
3238 static struct kernfs_syscall_ops rdtgroup_kf_syscall_ops = {
3239 	.mkdir		= rdtgroup_mkdir,
3240 	.rmdir		= rdtgroup_rmdir,
3241 	.show_options	= rdtgroup_show_options,
3242 };
3243 
3244 static int __init rdtgroup_setup_root(void)
3245 {
3246 	int ret;
3247 
3248 	rdt_root = kernfs_create_root(&rdtgroup_kf_syscall_ops,
3249 				      KERNFS_ROOT_CREATE_DEACTIVATED |
3250 				      KERNFS_ROOT_EXTRA_OPEN_PERM_CHECK,
3251 				      &rdtgroup_default);
3252 	if (IS_ERR(rdt_root))
3253 		return PTR_ERR(rdt_root);
3254 
3255 	mutex_lock(&rdtgroup_mutex);
3256 
3257 	rdtgroup_default.closid = 0;
3258 	rdtgroup_default.mon.rmid = 0;
3259 	rdtgroup_default.type = RDTCTRL_GROUP;
3260 	INIT_LIST_HEAD(&rdtgroup_default.mon.crdtgrp_list);
3261 
3262 	list_add(&rdtgroup_default.rdtgroup_list, &rdt_all_groups);
3263 
3264 	ret = rdtgroup_add_files(kernfs_root_to_node(rdt_root), RF_CTRL_BASE);
3265 	if (ret) {
3266 		kernfs_destroy_root(rdt_root);
3267 		goto out;
3268 	}
3269 
3270 	rdtgroup_default.kn = kernfs_root_to_node(rdt_root);
3271 	kernfs_activate(rdtgroup_default.kn);
3272 
3273 out:
3274 	mutex_unlock(&rdtgroup_mutex);
3275 
3276 	return ret;
3277 }
3278 
3279 static void domain_destroy_mon_state(struct rdt_domain *d)
3280 {
3281 	bitmap_free(d->rmid_busy_llc);
3282 	kfree(d->mbm_total);
3283 	kfree(d->mbm_local);
3284 }
3285 
3286 void resctrl_offline_domain(struct rdt_resource *r, struct rdt_domain *d)
3287 {
3288 	lockdep_assert_held(&rdtgroup_mutex);
3289 
3290 	if (supports_mba_mbps() && r->rid == RDT_RESOURCE_MBA)
3291 		mba_sc_domain_destroy(r, d);
3292 
3293 	if (!r->mon_capable)
3294 		return;
3295 
3296 	/*
3297 	 * If resctrl is mounted, remove all the
3298 	 * per domain monitor data directories.
3299 	 */
3300 	if (static_branch_unlikely(&rdt_mon_enable_key))
3301 		rmdir_mondata_subdir_allrdtgrp(r, d->id);
3302 
3303 	if (is_mbm_enabled())
3304 		cancel_delayed_work(&d->mbm_over);
3305 	if (is_llc_occupancy_enabled() && has_busy_rmid(r, d)) {
3306 		/*
3307 		 * When a package is going down, forcefully
3308 		 * decrement rmid->ebusy. There is no way to know
3309 		 * that the L3 was flushed and hence may lead to
3310 		 * incorrect counts in rare scenarios, but leaving
3311 		 * the RMID as busy creates RMID leaks if the
3312 		 * package never comes back.
3313 		 */
3314 		__check_limbo(d, true);
3315 		cancel_delayed_work(&d->cqm_limbo);
3316 	}
3317 
3318 	domain_destroy_mon_state(d);
3319 }
3320 
3321 static int domain_setup_mon_state(struct rdt_resource *r, struct rdt_domain *d)
3322 {
3323 	size_t tsize;
3324 
3325 	if (is_llc_occupancy_enabled()) {
3326 		d->rmid_busy_llc = bitmap_zalloc(r->num_rmid, GFP_KERNEL);
3327 		if (!d->rmid_busy_llc)
3328 			return -ENOMEM;
3329 	}
3330 	if (is_mbm_total_enabled()) {
3331 		tsize = sizeof(*d->mbm_total);
3332 		d->mbm_total = kcalloc(r->num_rmid, tsize, GFP_KERNEL);
3333 		if (!d->mbm_total) {
3334 			bitmap_free(d->rmid_busy_llc);
3335 			return -ENOMEM;
3336 		}
3337 	}
3338 	if (is_mbm_local_enabled()) {
3339 		tsize = sizeof(*d->mbm_local);
3340 		d->mbm_local = kcalloc(r->num_rmid, tsize, GFP_KERNEL);
3341 		if (!d->mbm_local) {
3342 			bitmap_free(d->rmid_busy_llc);
3343 			kfree(d->mbm_total);
3344 			return -ENOMEM;
3345 		}
3346 	}
3347 
3348 	return 0;
3349 }
3350 
3351 int resctrl_online_domain(struct rdt_resource *r, struct rdt_domain *d)
3352 {
3353 	int err;
3354 
3355 	lockdep_assert_held(&rdtgroup_mutex);
3356 
3357 	if (supports_mba_mbps() && r->rid == RDT_RESOURCE_MBA)
3358 		/* RDT_RESOURCE_MBA is never mon_capable */
3359 		return mba_sc_domain_allocate(r, d);
3360 
3361 	if (!r->mon_capable)
3362 		return 0;
3363 
3364 	err = domain_setup_mon_state(r, d);
3365 	if (err)
3366 		return err;
3367 
3368 	if (is_mbm_enabled()) {
3369 		INIT_DELAYED_WORK(&d->mbm_over, mbm_handle_overflow);
3370 		mbm_setup_overflow_handler(d, MBM_OVERFLOW_INTERVAL);
3371 	}
3372 
3373 	if (is_llc_occupancy_enabled())
3374 		INIT_DELAYED_WORK(&d->cqm_limbo, cqm_handle_limbo);
3375 
3376 	/* If resctrl is mounted, add per domain monitor data directories. */
3377 	if (static_branch_unlikely(&rdt_mon_enable_key))
3378 		mkdir_mondata_subdir_allrdtgrp(r, d);
3379 
3380 	return 0;
3381 }
3382 
3383 /*
3384  * rdtgroup_init - rdtgroup initialization
3385  *
3386  * Setup resctrl file system including set up root, create mount point,
3387  * register rdtgroup filesystem, and initialize files under root directory.
3388  *
3389  * Return: 0 on success or -errno
3390  */
3391 int __init rdtgroup_init(void)
3392 {
3393 	int ret = 0;
3394 
3395 	seq_buf_init(&last_cmd_status, last_cmd_status_buf,
3396 		     sizeof(last_cmd_status_buf));
3397 
3398 	ret = rdtgroup_setup_root();
3399 	if (ret)
3400 		return ret;
3401 
3402 	ret = sysfs_create_mount_point(fs_kobj, "resctrl");
3403 	if (ret)
3404 		goto cleanup_root;
3405 
3406 	ret = register_filesystem(&rdt_fs_type);
3407 	if (ret)
3408 		goto cleanup_mountpoint;
3409 
3410 	/*
3411 	 * Adding the resctrl debugfs directory here may not be ideal since
3412 	 * it would let the resctrl debugfs directory appear on the debugfs
3413 	 * filesystem before the resctrl filesystem is mounted.
3414 	 * It may also be ok since that would enable debugging of RDT before
3415 	 * resctrl is mounted.
3416 	 * The reason why the debugfs directory is created here and not in
3417 	 * rdt_get_tree() is because rdt_get_tree() takes rdtgroup_mutex and
3418 	 * during the debugfs directory creation also &sb->s_type->i_mutex_key
3419 	 * (the lockdep class of inode->i_rwsem). Other filesystem
3420 	 * interactions (eg. SyS_getdents) have the lock ordering:
3421 	 * &sb->s_type->i_mutex_key --> &mm->mmap_lock
3422 	 * During mmap(), called with &mm->mmap_lock, the rdtgroup_mutex
3423 	 * is taken, thus creating dependency:
3424 	 * &mm->mmap_lock --> rdtgroup_mutex for the latter that can cause
3425 	 * issues considering the other two lock dependencies.
3426 	 * By creating the debugfs directory here we avoid a dependency
3427 	 * that may cause deadlock (even though file operations cannot
3428 	 * occur until the filesystem is mounted, but I do not know how to
3429 	 * tell lockdep that).
3430 	 */
3431 	debugfs_resctrl = debugfs_create_dir("resctrl", NULL);
3432 
3433 	return 0;
3434 
3435 cleanup_mountpoint:
3436 	sysfs_remove_mount_point(fs_kobj, "resctrl");
3437 cleanup_root:
3438 	kernfs_destroy_root(rdt_root);
3439 
3440 	return ret;
3441 }
3442 
3443 void __exit rdtgroup_exit(void)
3444 {
3445 	debugfs_remove_recursive(debugfs_resctrl);
3446 	unregister_filesystem(&rdt_fs_type);
3447 	sysfs_remove_mount_point(fs_kobj, "resctrl");
3448 	kernfs_destroy_root(rdt_root);
3449 }
3450