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