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