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