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