GNU Linux-libre 5.4.274-gnu1
[releases.git] / arch / x86 / kvm / pmu.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Kernel-based Virtual Machine -- Performance Monitoring Unit support
4  *
5  * Copyright 2015 Red Hat, Inc. and/or its affiliates.
6  *
7  * Authors:
8  *   Avi Kivity   <avi@redhat.com>
9  *   Gleb Natapov <gleb@redhat.com>
10  *   Wei Huang    <wei@redhat.com>
11  */
12
13 #include <linux/types.h>
14 #include <linux/kvm_host.h>
15 #include <linux/perf_event.h>
16 #include <asm/perf_event.h>
17 #include "x86.h"
18 #include "cpuid.h"
19 #include "lapic.h"
20 #include "pmu.h"
21
22 /* This is enough to filter the vast majority of currently defined events. */
23 #define KVM_PMU_EVENT_FILTER_MAX_EVENTS 300
24
25 /* NOTE:
26  * - Each perf counter is defined as "struct kvm_pmc";
27  * - There are two types of perf counters: general purpose (gp) and fixed.
28  *   gp counters are stored in gp_counters[] and fixed counters are stored
29  *   in fixed_counters[] respectively. Both of them are part of "struct
30  *   kvm_pmu";
31  * - pmu.c understands the difference between gp counters and fixed counters.
32  *   However AMD doesn't support fixed-counters;
33  * - There are three types of index to access perf counters (PMC):
34  *     1. MSR (named msr): For example Intel has MSR_IA32_PERFCTRn and AMD
35  *        has MSR_K7_PERFCTRn.
36  *     2. MSR Index (named idx): This normally is used by RDPMC instruction.
37  *        For instance AMD RDPMC instruction uses 0000_0003h in ECX to access
38  *        C001_0007h (MSR_K7_PERCTR3). Intel has a similar mechanism, except
39  *        that it also supports fixed counters. idx can be used to as index to
40  *        gp and fixed counters.
41  *     3. Global PMC Index (named pmc): pmc is an index specific to PMU
42  *        code. Each pmc, stored in kvm_pmc.idx field, is unique across
43  *        all perf counters (both gp and fixed). The mapping relationship
44  *        between pmc and perf counters is as the following:
45  *        * Intel: [0 .. INTEL_PMC_MAX_GENERIC-1] <=> gp counters
46  *                 [INTEL_PMC_IDX_FIXED .. INTEL_PMC_IDX_FIXED + 2] <=> fixed
47  *        * AMD:   [0 .. AMD64_NUM_COUNTERS-1] <=> gp counters
48  */
49
50 static void kvm_pmi_trigger_fn(struct irq_work *irq_work)
51 {
52         struct kvm_pmu *pmu = container_of(irq_work, struct kvm_pmu, irq_work);
53         struct kvm_vcpu *vcpu = pmu_to_vcpu(pmu);
54
55         kvm_pmu_deliver_pmi(vcpu);
56 }
57
58 static void kvm_perf_overflow(struct perf_event *perf_event,
59                               struct perf_sample_data *data,
60                               struct pt_regs *regs)
61 {
62         struct kvm_pmc *pmc = perf_event->overflow_handler_context;
63         struct kvm_pmu *pmu = pmc_to_pmu(pmc);
64
65         if (!test_and_set_bit(pmc->idx,
66                               (unsigned long *)&pmu->reprogram_pmi)) {
67                 __set_bit(pmc->idx, (unsigned long *)&pmu->global_status);
68                 kvm_make_request(KVM_REQ_PMU, pmc->vcpu);
69         }
70 }
71
72 static void kvm_perf_overflow_intr(struct perf_event *perf_event,
73                                    struct perf_sample_data *data,
74                                    struct pt_regs *regs)
75 {
76         struct kvm_pmc *pmc = perf_event->overflow_handler_context;
77         struct kvm_pmu *pmu = pmc_to_pmu(pmc);
78
79         if (!test_and_set_bit(pmc->idx,
80                               (unsigned long *)&pmu->reprogram_pmi)) {
81                 __set_bit(pmc->idx, (unsigned long *)&pmu->global_status);
82                 kvm_make_request(KVM_REQ_PMU, pmc->vcpu);
83
84                 /*
85                  * Inject PMI. If vcpu was in a guest mode during NMI PMI
86                  * can be ejected on a guest mode re-entry. Otherwise we can't
87                  * be sure that vcpu wasn't executing hlt instruction at the
88                  * time of vmexit and is not going to re-enter guest mode until
89                  * woken up. So we should wake it, but this is impossible from
90                  * NMI context. Do it from irq work instead.
91                  */
92                 if (!kvm_is_in_guest())
93                         irq_work_queue(&pmc_to_pmu(pmc)->irq_work);
94                 else
95                         kvm_make_request(KVM_REQ_PMI, pmc->vcpu);
96         }
97 }
98
99 static void pmc_reprogram_counter(struct kvm_pmc *pmc, u32 type,
100                                   unsigned config, bool exclude_user,
101                                   bool exclude_kernel, bool intr,
102                                   bool in_tx, bool in_tx_cp)
103 {
104         struct perf_event *event;
105         struct perf_event_attr attr = {
106                 .type = type,
107                 .size = sizeof(attr),
108                 .pinned = true,
109                 .exclude_idle = true,
110                 .exclude_host = 1,
111                 .exclude_user = exclude_user,
112                 .exclude_kernel = exclude_kernel,
113                 .config = config,
114         };
115
116         attr.sample_period = (-pmc->counter) & pmc_bitmask(pmc);
117
118         if (in_tx)
119                 attr.config |= HSW_IN_TX;
120         if (in_tx_cp) {
121                 /*
122                  * HSW_IN_TX_CHECKPOINTED is not supported with nonzero
123                  * period. Just clear the sample period so at least
124                  * allocating the counter doesn't fail.
125                  */
126                 attr.sample_period = 0;
127                 attr.config |= HSW_IN_TX_CHECKPOINTED;
128         }
129
130         event = perf_event_create_kernel_counter(&attr, -1, current,
131                                                  intr ? kvm_perf_overflow_intr :
132                                                  kvm_perf_overflow, pmc);
133         if (IS_ERR(event)) {
134                 pr_debug_ratelimited("kvm_pmu: event creation failed %ld for pmc->idx = %d\n",
135                             PTR_ERR(event), pmc->idx);
136                 return;
137         }
138
139         pmc->perf_event = event;
140         clear_bit(pmc->idx, (unsigned long*)&pmc_to_pmu(pmc)->reprogram_pmi);
141 }
142
143 void reprogram_gp_counter(struct kvm_pmc *pmc, u64 eventsel)
144 {
145         unsigned config, type = PERF_TYPE_RAW;
146         struct kvm *kvm = pmc->vcpu->kvm;
147         struct kvm_pmu_event_filter *filter;
148         int i;
149         bool allow_event = true;
150
151         if (eventsel & ARCH_PERFMON_EVENTSEL_PIN_CONTROL)
152                 printk_once("kvm pmu: pin control bit is ignored\n");
153
154         pmc->eventsel = eventsel;
155
156         pmc_stop_counter(pmc);
157
158         if (!(eventsel & ARCH_PERFMON_EVENTSEL_ENABLE) || !pmc_is_enabled(pmc))
159                 return;
160
161         filter = srcu_dereference(kvm->arch.pmu_event_filter, &kvm->srcu);
162         if (filter) {
163                 for (i = 0; i < filter->nevents; i++)
164                         if (filter->events[i] ==
165                             (eventsel & AMD64_RAW_EVENT_MASK_NB))
166                                 break;
167                 if (filter->action == KVM_PMU_EVENT_ALLOW &&
168                     i == filter->nevents)
169                         allow_event = false;
170                 if (filter->action == KVM_PMU_EVENT_DENY &&
171                     i < filter->nevents)
172                         allow_event = false;
173         }
174         if (!allow_event)
175                 return;
176
177         if (!(eventsel & (ARCH_PERFMON_EVENTSEL_EDGE |
178                           ARCH_PERFMON_EVENTSEL_INV |
179                           ARCH_PERFMON_EVENTSEL_CMASK |
180                           HSW_IN_TX |
181                           HSW_IN_TX_CHECKPOINTED))) {
182                 config = kvm_x86_ops->pmu_ops->pmc_perf_hw_id(pmc);
183                 if (config != PERF_COUNT_HW_MAX)
184                         type = PERF_TYPE_HARDWARE;
185         }
186
187         if (type == PERF_TYPE_RAW)
188                 config = eventsel & AMD64_RAW_EVENT_MASK;
189
190         pmc_reprogram_counter(pmc, type, config,
191                               !(eventsel & ARCH_PERFMON_EVENTSEL_USR),
192                               !(eventsel & ARCH_PERFMON_EVENTSEL_OS),
193                               eventsel & ARCH_PERFMON_EVENTSEL_INT,
194                               (eventsel & HSW_IN_TX),
195                               (eventsel & HSW_IN_TX_CHECKPOINTED));
196 }
197 EXPORT_SYMBOL_GPL(reprogram_gp_counter);
198
199 void reprogram_fixed_counter(struct kvm_pmc *pmc, u8 ctrl, int idx)
200 {
201         unsigned en_field = ctrl & 0x3;
202         bool pmi = ctrl & 0x8;
203         struct kvm_pmu_event_filter *filter;
204         struct kvm *kvm = pmc->vcpu->kvm;
205
206         pmc_stop_counter(pmc);
207
208         if (!en_field || !pmc_is_enabled(pmc))
209                 return;
210
211         filter = srcu_dereference(kvm->arch.pmu_event_filter, &kvm->srcu);
212         if (filter) {
213                 if (filter->action == KVM_PMU_EVENT_DENY &&
214                     test_bit(idx, (ulong *)&filter->fixed_counter_bitmap))
215                         return;
216                 if (filter->action == KVM_PMU_EVENT_ALLOW &&
217                     !test_bit(idx, (ulong *)&filter->fixed_counter_bitmap))
218                         return;
219         }
220
221         pmc_reprogram_counter(pmc, PERF_TYPE_HARDWARE,
222                               kvm_x86_ops->pmu_ops->find_fixed_event(idx),
223                               !(en_field & 0x2), /* exclude user */
224                               !(en_field & 0x1), /* exclude kernel */
225                               pmi, false, false);
226 }
227 EXPORT_SYMBOL_GPL(reprogram_fixed_counter);
228
229 void reprogram_counter(struct kvm_pmu *pmu, int pmc_idx)
230 {
231         struct kvm_pmc *pmc = kvm_x86_ops->pmu_ops->pmc_idx_to_pmc(pmu, pmc_idx);
232
233         if (!pmc)
234                 return;
235
236         if (pmc_is_gp(pmc))
237                 reprogram_gp_counter(pmc, pmc->eventsel);
238         else {
239                 int idx = pmc_idx - INTEL_PMC_IDX_FIXED;
240                 u8 ctrl = fixed_ctrl_field(pmu->fixed_ctr_ctrl, idx);
241
242                 reprogram_fixed_counter(pmc, ctrl, idx);
243         }
244 }
245 EXPORT_SYMBOL_GPL(reprogram_counter);
246
247 void kvm_pmu_handle_event(struct kvm_vcpu *vcpu)
248 {
249         struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
250         u64 bitmask;
251         int bit;
252
253         bitmask = pmu->reprogram_pmi;
254
255         for_each_set_bit(bit, (unsigned long *)&bitmask, X86_PMC_IDX_MAX) {
256                 struct kvm_pmc *pmc = kvm_x86_ops->pmu_ops->pmc_idx_to_pmc(pmu, bit);
257
258                 if (unlikely(!pmc || !pmc->perf_event)) {
259                         clear_bit(bit, (unsigned long *)&pmu->reprogram_pmi);
260                         continue;
261                 }
262
263                 reprogram_counter(pmu, bit);
264         }
265 }
266
267 /* check if idx is a valid index to access PMU */
268 int kvm_pmu_is_valid_msr_idx(struct kvm_vcpu *vcpu, unsigned idx)
269 {
270         return kvm_x86_ops->pmu_ops->is_valid_msr_idx(vcpu, idx);
271 }
272
273 bool is_vmware_backdoor_pmc(u32 pmc_idx)
274 {
275         switch (pmc_idx) {
276         case VMWARE_BACKDOOR_PMC_HOST_TSC:
277         case VMWARE_BACKDOOR_PMC_REAL_TIME:
278         case VMWARE_BACKDOOR_PMC_APPARENT_TIME:
279                 return true;
280         }
281         return false;
282 }
283
284 static int kvm_pmu_rdpmc_vmware(struct kvm_vcpu *vcpu, unsigned idx, u64 *data)
285 {
286         u64 ctr_val;
287
288         switch (idx) {
289         case VMWARE_BACKDOOR_PMC_HOST_TSC:
290                 ctr_val = rdtsc();
291                 break;
292         case VMWARE_BACKDOOR_PMC_REAL_TIME:
293                 ctr_val = ktime_get_boottime_ns();
294                 break;
295         case VMWARE_BACKDOOR_PMC_APPARENT_TIME:
296                 ctr_val = ktime_get_boottime_ns() +
297                         vcpu->kvm->arch.kvmclock_offset;
298                 break;
299         default:
300                 return 1;
301         }
302
303         *data = ctr_val;
304         return 0;
305 }
306
307 int kvm_pmu_rdpmc(struct kvm_vcpu *vcpu, unsigned idx, u64 *data)
308 {
309         bool fast_mode = idx & (1u << 31);
310         struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
311         struct kvm_pmc *pmc;
312         u64 mask = fast_mode ? ~0u : ~0ull;
313
314         if (!pmu->version)
315                 return 1;
316
317         if (is_vmware_backdoor_pmc(idx))
318                 return kvm_pmu_rdpmc_vmware(vcpu, idx, data);
319
320         pmc = kvm_x86_ops->pmu_ops->msr_idx_to_pmc(vcpu, idx, &mask);
321         if (!pmc)
322                 return 1;
323
324         *data = pmc_read_counter(pmc) & mask;
325         return 0;
326 }
327
328 void kvm_pmu_deliver_pmi(struct kvm_vcpu *vcpu)
329 {
330         if (lapic_in_kernel(vcpu))
331                 kvm_apic_local_deliver(vcpu->arch.apic, APIC_LVTPC);
332 }
333
334 bool kvm_pmu_is_valid_msr(struct kvm_vcpu *vcpu, u32 msr)
335 {
336         return kvm_x86_ops->pmu_ops->is_valid_msr(vcpu, msr);
337 }
338
339 int kvm_pmu_get_msr(struct kvm_vcpu *vcpu, u32 msr, u64 *data)
340 {
341         return kvm_x86_ops->pmu_ops->get_msr(vcpu, msr, data);
342 }
343
344 int kvm_pmu_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
345 {
346         return kvm_x86_ops->pmu_ops->set_msr(vcpu, msr_info);
347 }
348
349 /* refresh PMU settings. This function generally is called when underlying
350  * settings are changed (such as changes of PMU CPUID by guest VMs), which
351  * should rarely happen.
352  */
353 void kvm_pmu_refresh(struct kvm_vcpu *vcpu)
354 {
355         kvm_x86_ops->pmu_ops->refresh(vcpu);
356 }
357
358 void kvm_pmu_reset(struct kvm_vcpu *vcpu)
359 {
360         struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
361
362         irq_work_sync(&pmu->irq_work);
363         kvm_x86_ops->pmu_ops->reset(vcpu);
364 }
365
366 void kvm_pmu_init(struct kvm_vcpu *vcpu)
367 {
368         struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
369
370         memset(pmu, 0, sizeof(*pmu));
371         kvm_x86_ops->pmu_ops->init(vcpu);
372         init_irq_work(&pmu->irq_work, kvm_pmi_trigger_fn);
373         kvm_pmu_refresh(vcpu);
374 }
375
376 void kvm_pmu_destroy(struct kvm_vcpu *vcpu)
377 {
378         kvm_pmu_reset(vcpu);
379 }
380
381 int kvm_vm_ioctl_set_pmu_event_filter(struct kvm *kvm, void __user *argp)
382 {
383         struct kvm_pmu_event_filter tmp, *filter;
384         size_t size;
385         int r;
386
387         if (copy_from_user(&tmp, argp, sizeof(tmp)))
388                 return -EFAULT;
389
390         if (tmp.action != KVM_PMU_EVENT_ALLOW &&
391             tmp.action != KVM_PMU_EVENT_DENY)
392                 return -EINVAL;
393
394         if (tmp.flags != 0)
395                 return -EINVAL;
396
397         if (tmp.nevents > KVM_PMU_EVENT_FILTER_MAX_EVENTS)
398                 return -E2BIG;
399
400         size = struct_size(filter, events, tmp.nevents);
401         filter = kmalloc(size, GFP_KERNEL_ACCOUNT);
402         if (!filter)
403                 return -ENOMEM;
404
405         r = -EFAULT;
406         if (copy_from_user(filter, argp, size))
407                 goto cleanup;
408
409         /* Ensure nevents can't be changed between the user copies. */
410         *filter = tmp;
411
412         mutex_lock(&kvm->lock);
413         rcu_swap_protected(kvm->arch.pmu_event_filter, filter,
414                            mutex_is_locked(&kvm->lock));
415         mutex_unlock(&kvm->lock);
416
417         synchronize_srcu_expedited(&kvm->srcu);
418         r = 0;
419 cleanup:
420         kfree(filter);
421         return r;
422 }