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