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