GNU Linux-libre 5.15.137-gnu
[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, pmu->reprogram_pmi)) {
66                 __set_bit(pmc->idx, (unsigned long *)&pmu->global_status);
67                 kvm_make_request(KVM_REQ_PMU, pmc->vcpu);
68         }
69 }
70
71 static void kvm_perf_overflow_intr(struct perf_event *perf_event,
72                                    struct perf_sample_data *data,
73                                    struct pt_regs *regs)
74 {
75         struct kvm_pmc *pmc = perf_event->overflow_handler_context;
76         struct kvm_pmu *pmu = pmc_to_pmu(pmc);
77
78         if (!test_and_set_bit(pmc->idx, pmu->reprogram_pmi)) {
79                 __set_bit(pmc->idx, (unsigned long *)&pmu->global_status);
80                 kvm_make_request(KVM_REQ_PMU, pmc->vcpu);
81
82                 /*
83                  * Inject PMI. If vcpu was in a guest mode during NMI PMI
84                  * can be ejected on a guest mode re-entry. Otherwise we can't
85                  * be sure that vcpu wasn't executing hlt instruction at the
86                  * time of vmexit and is not going to re-enter guest mode until
87                  * woken up. So we should wake it, but this is impossible from
88                  * NMI context. Do it from irq work instead.
89                  */
90                 if (!kvm_is_in_guest())
91                         irq_work_queue(&pmc_to_pmu(pmc)->irq_work);
92                 else
93                         kvm_make_request(KVM_REQ_PMI, pmc->vcpu);
94         }
95 }
96
97 static void pmc_reprogram_counter(struct kvm_pmc *pmc, u32 type,
98                                   u64 config, bool exclude_user,
99                                   bool exclude_kernel, bool intr)
100 {
101         struct perf_event *event;
102         struct perf_event_attr attr = {
103                 .type = type,
104                 .size = sizeof(attr),
105                 .pinned = true,
106                 .exclude_idle = true,
107                 .exclude_host = 1,
108                 .exclude_user = exclude_user,
109                 .exclude_kernel = exclude_kernel,
110                 .config = config,
111         };
112
113         attr.sample_period = get_sample_period(pmc, pmc->counter);
114
115         if ((attr.config & HSW_IN_TX_CHECKPOINTED) &&
116             guest_cpuid_is_intel(pmc->vcpu)) {
117                 /*
118                  * HSW_IN_TX_CHECKPOINTED is not supported with nonzero
119                  * period. Just clear the sample period so at least
120                  * allocating the counter doesn't fail.
121                  */
122                 attr.sample_period = 0;
123         }
124
125         event = perf_event_create_kernel_counter(&attr, -1, current,
126                                                  intr ? kvm_perf_overflow_intr :
127                                                  kvm_perf_overflow, pmc);
128         if (IS_ERR(event)) {
129                 pr_debug_ratelimited("kvm_pmu: event creation failed %ld for pmc->idx = %d\n",
130                             PTR_ERR(event), pmc->idx);
131                 return;
132         }
133
134         pmc->perf_event = event;
135         pmc_to_pmu(pmc)->event_count++;
136         clear_bit(pmc->idx, pmc_to_pmu(pmc)->reprogram_pmi);
137         pmc->is_paused = false;
138 }
139
140 static void pmc_pause_counter(struct kvm_pmc *pmc)
141 {
142         u64 counter = pmc->counter;
143
144         if (!pmc->perf_event || pmc->is_paused)
145                 return;
146
147         /* update counter, reset event value to avoid redundant accumulation */
148         counter += perf_event_pause(pmc->perf_event, true);
149         pmc->counter = counter & pmc_bitmask(pmc);
150         pmc->is_paused = true;
151 }
152
153 static bool pmc_resume_counter(struct kvm_pmc *pmc)
154 {
155         if (!pmc->perf_event)
156                 return false;
157
158         /* recalibrate sample period and check if it's accepted by perf core */
159         if (perf_event_period(pmc->perf_event,
160                               get_sample_period(pmc, pmc->counter)))
161                 return false;
162
163         /* reuse perf_event to serve as pmc_reprogram_counter() does*/
164         perf_event_enable(pmc->perf_event);
165         pmc->is_paused = false;
166
167         clear_bit(pmc->idx, (unsigned long *)&pmc_to_pmu(pmc)->reprogram_pmi);
168         return true;
169 }
170
171 void reprogram_gp_counter(struct kvm_pmc *pmc, u64 eventsel)
172 {
173         u64 config;
174         u32 type = PERF_TYPE_RAW;
175         struct kvm *kvm = pmc->vcpu->kvm;
176         struct kvm_pmu_event_filter *filter;
177         int i;
178         struct kvm_pmu *pmu = vcpu_to_pmu(pmc->vcpu);
179         bool allow_event = true;
180
181         if (eventsel & ARCH_PERFMON_EVENTSEL_PIN_CONTROL)
182                 printk_once("kvm pmu: pin control bit is ignored\n");
183
184         pmc->eventsel = eventsel;
185
186         pmc_pause_counter(pmc);
187
188         if (!(eventsel & ARCH_PERFMON_EVENTSEL_ENABLE) || !pmc_is_enabled(pmc))
189                 return;
190
191         filter = srcu_dereference(kvm->arch.pmu_event_filter, &kvm->srcu);
192         if (filter) {
193                 for (i = 0; i < filter->nevents; i++)
194                         if (filter->events[i] ==
195                             (eventsel & AMD64_RAW_EVENT_MASK_NB))
196                                 break;
197                 if (filter->action == KVM_PMU_EVENT_ALLOW &&
198                     i == filter->nevents)
199                         allow_event = false;
200                 if (filter->action == KVM_PMU_EVENT_DENY &&
201                     i < filter->nevents)
202                         allow_event = false;
203         }
204         if (!allow_event)
205                 return;
206
207         if (!(eventsel & (ARCH_PERFMON_EVENTSEL_EDGE |
208                           ARCH_PERFMON_EVENTSEL_INV |
209                           ARCH_PERFMON_EVENTSEL_CMASK |
210                           HSW_IN_TX |
211                           HSW_IN_TX_CHECKPOINTED))) {
212                 config = kvm_x86_ops.pmu_ops->pmc_perf_hw_id(pmc);
213                 if (config != PERF_COUNT_HW_MAX)
214                         type = PERF_TYPE_HARDWARE;
215         }
216
217         if (type == PERF_TYPE_RAW)
218                 config = eventsel & pmu->raw_event_mask;
219
220         if (pmc->current_config == eventsel && pmc_resume_counter(pmc))
221                 return;
222
223         pmc_release_perf_event(pmc);
224
225         pmc->current_config = eventsel;
226         pmc_reprogram_counter(pmc, type, config,
227                               !(eventsel & ARCH_PERFMON_EVENTSEL_USR),
228                               !(eventsel & ARCH_PERFMON_EVENTSEL_OS),
229                               eventsel & ARCH_PERFMON_EVENTSEL_INT);
230 }
231 EXPORT_SYMBOL_GPL(reprogram_gp_counter);
232
233 void reprogram_fixed_counter(struct kvm_pmc *pmc, u8 ctrl, int idx)
234 {
235         unsigned en_field = ctrl & 0x3;
236         bool pmi = ctrl & 0x8;
237         struct kvm_pmu_event_filter *filter;
238         struct kvm *kvm = pmc->vcpu->kvm;
239
240         pmc_pause_counter(pmc);
241
242         if (!en_field || !pmc_is_enabled(pmc))
243                 return;
244
245         filter = srcu_dereference(kvm->arch.pmu_event_filter, &kvm->srcu);
246         if (filter) {
247                 if (filter->action == KVM_PMU_EVENT_DENY &&
248                     test_bit(idx, (ulong *)&filter->fixed_counter_bitmap))
249                         return;
250                 if (filter->action == KVM_PMU_EVENT_ALLOW &&
251                     !test_bit(idx, (ulong *)&filter->fixed_counter_bitmap))
252                         return;
253         }
254
255         if (pmc->current_config == (u64)ctrl && pmc_resume_counter(pmc))
256                 return;
257
258         pmc_release_perf_event(pmc);
259
260         pmc->current_config = (u64)ctrl;
261         pmc_reprogram_counter(pmc, PERF_TYPE_HARDWARE,
262                               kvm_x86_ops.pmu_ops->find_fixed_event(idx),
263                               !(en_field & 0x2), /* exclude user */
264                               !(en_field & 0x1), /* exclude kernel */
265                               pmi);
266 }
267 EXPORT_SYMBOL_GPL(reprogram_fixed_counter);
268
269 void reprogram_counter(struct kvm_pmu *pmu, int pmc_idx)
270 {
271         struct kvm_pmc *pmc = kvm_x86_ops.pmu_ops->pmc_idx_to_pmc(pmu, pmc_idx);
272
273         if (!pmc)
274                 return;
275
276         if (pmc_is_gp(pmc))
277                 reprogram_gp_counter(pmc, pmc->eventsel);
278         else {
279                 int idx = pmc_idx - INTEL_PMC_IDX_FIXED;
280                 u8 ctrl = fixed_ctrl_field(pmu->fixed_ctr_ctrl, idx);
281
282                 reprogram_fixed_counter(pmc, ctrl, idx);
283         }
284 }
285 EXPORT_SYMBOL_GPL(reprogram_counter);
286
287 void kvm_pmu_handle_event(struct kvm_vcpu *vcpu)
288 {
289         struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
290         int bit;
291
292         for_each_set_bit(bit, pmu->reprogram_pmi, X86_PMC_IDX_MAX) {
293                 struct kvm_pmc *pmc = kvm_x86_ops.pmu_ops->pmc_idx_to_pmc(pmu, bit);
294
295                 if (unlikely(!pmc || !pmc->perf_event)) {
296                         clear_bit(bit, pmu->reprogram_pmi);
297                         continue;
298                 }
299
300                 reprogram_counter(pmu, bit);
301         }
302
303         /*
304          * Unused perf_events are only released if the corresponding MSRs
305          * weren't accessed during the last vCPU time slice. kvm_arch_sched_in
306          * triggers KVM_REQ_PMU if cleanup is needed.
307          */
308         if (unlikely(pmu->need_cleanup))
309                 kvm_pmu_cleanup(vcpu);
310 }
311
312 /* check if idx is a valid index to access PMU */
313 int kvm_pmu_is_valid_rdpmc_ecx(struct kvm_vcpu *vcpu, unsigned int idx)
314 {
315         return kvm_x86_ops.pmu_ops->is_valid_rdpmc_ecx(vcpu, idx);
316 }
317
318 bool is_vmware_backdoor_pmc(u32 pmc_idx)
319 {
320         switch (pmc_idx) {
321         case VMWARE_BACKDOOR_PMC_HOST_TSC:
322         case VMWARE_BACKDOOR_PMC_REAL_TIME:
323         case VMWARE_BACKDOOR_PMC_APPARENT_TIME:
324                 return true;
325         }
326         return false;
327 }
328
329 static int kvm_pmu_rdpmc_vmware(struct kvm_vcpu *vcpu, unsigned idx, u64 *data)
330 {
331         u64 ctr_val;
332
333         switch (idx) {
334         case VMWARE_BACKDOOR_PMC_HOST_TSC:
335                 ctr_val = rdtsc();
336                 break;
337         case VMWARE_BACKDOOR_PMC_REAL_TIME:
338                 ctr_val = ktime_get_boottime_ns();
339                 break;
340         case VMWARE_BACKDOOR_PMC_APPARENT_TIME:
341                 ctr_val = ktime_get_boottime_ns() +
342                         vcpu->kvm->arch.kvmclock_offset;
343                 break;
344         default:
345                 return 1;
346         }
347
348         *data = ctr_val;
349         return 0;
350 }
351
352 int kvm_pmu_rdpmc(struct kvm_vcpu *vcpu, unsigned idx, u64 *data)
353 {
354         bool fast_mode = idx & (1u << 31);
355         struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
356         struct kvm_pmc *pmc;
357         u64 mask = fast_mode ? ~0u : ~0ull;
358
359         if (!pmu->version)
360                 return 1;
361
362         if (is_vmware_backdoor_pmc(idx))
363                 return kvm_pmu_rdpmc_vmware(vcpu, idx, data);
364
365         pmc = kvm_x86_ops.pmu_ops->rdpmc_ecx_to_pmc(vcpu, idx, &mask);
366         if (!pmc)
367                 return 1;
368
369         if (!(kvm_read_cr4(vcpu) & X86_CR4_PCE) &&
370             (static_call(kvm_x86_get_cpl)(vcpu) != 0) &&
371             (kvm_read_cr0(vcpu) & X86_CR0_PE))
372                 return 1;
373
374         *data = pmc_read_counter(pmc) & mask;
375         return 0;
376 }
377
378 void kvm_pmu_deliver_pmi(struct kvm_vcpu *vcpu)
379 {
380         if (lapic_in_kernel(vcpu)) {
381                 if (kvm_x86_ops.pmu_ops->deliver_pmi)
382                         kvm_x86_ops.pmu_ops->deliver_pmi(vcpu);
383                 kvm_apic_local_deliver(vcpu->arch.apic, APIC_LVTPC);
384         }
385 }
386
387 bool kvm_pmu_is_valid_msr(struct kvm_vcpu *vcpu, u32 msr)
388 {
389         return kvm_x86_ops.pmu_ops->msr_idx_to_pmc(vcpu, msr) ||
390                 kvm_x86_ops.pmu_ops->is_valid_msr(vcpu, msr);
391 }
392
393 static void kvm_pmu_mark_pmc_in_use(struct kvm_vcpu *vcpu, u32 msr)
394 {
395         struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
396         struct kvm_pmc *pmc = kvm_x86_ops.pmu_ops->msr_idx_to_pmc(vcpu, msr);
397
398         if (pmc)
399                 __set_bit(pmc->idx, pmu->pmc_in_use);
400 }
401
402 int kvm_pmu_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
403 {
404         return kvm_x86_ops.pmu_ops->get_msr(vcpu, msr_info);
405 }
406
407 int kvm_pmu_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
408 {
409         kvm_pmu_mark_pmc_in_use(vcpu, msr_info->index);
410         return kvm_x86_ops.pmu_ops->set_msr(vcpu, msr_info);
411 }
412
413 /* refresh PMU settings. This function generally is called when underlying
414  * settings are changed (such as changes of PMU CPUID by guest VMs), which
415  * should rarely happen.
416  */
417 void kvm_pmu_refresh(struct kvm_vcpu *vcpu)
418 {
419         kvm_x86_ops.pmu_ops->refresh(vcpu);
420 }
421
422 void kvm_pmu_reset(struct kvm_vcpu *vcpu)
423 {
424         struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
425
426         irq_work_sync(&pmu->irq_work);
427         kvm_x86_ops.pmu_ops->reset(vcpu);
428 }
429
430 void kvm_pmu_init(struct kvm_vcpu *vcpu)
431 {
432         struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
433
434         memset(pmu, 0, sizeof(*pmu));
435         kvm_x86_ops.pmu_ops->init(vcpu);
436         init_irq_work(&pmu->irq_work, kvm_pmi_trigger_fn);
437         pmu->event_count = 0;
438         pmu->need_cleanup = false;
439         kvm_pmu_refresh(vcpu);
440 }
441
442 static inline bool pmc_speculative_in_use(struct kvm_pmc *pmc)
443 {
444         struct kvm_pmu *pmu = pmc_to_pmu(pmc);
445
446         if (pmc_is_fixed(pmc))
447                 return fixed_ctrl_field(pmu->fixed_ctr_ctrl,
448                         pmc->idx - INTEL_PMC_IDX_FIXED) & 0x3;
449
450         return pmc->eventsel & ARCH_PERFMON_EVENTSEL_ENABLE;
451 }
452
453 /* Release perf_events for vPMCs that have been unused for a full time slice.  */
454 void kvm_pmu_cleanup(struct kvm_vcpu *vcpu)
455 {
456         struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
457         struct kvm_pmc *pmc = NULL;
458         DECLARE_BITMAP(bitmask, X86_PMC_IDX_MAX);
459         int i;
460
461         pmu->need_cleanup = false;
462
463         bitmap_andnot(bitmask, pmu->all_valid_pmc_idx,
464                       pmu->pmc_in_use, X86_PMC_IDX_MAX);
465
466         for_each_set_bit(i, bitmask, X86_PMC_IDX_MAX) {
467                 pmc = kvm_x86_ops.pmu_ops->pmc_idx_to_pmc(pmu, i);
468
469                 if (pmc && pmc->perf_event && !pmc_speculative_in_use(pmc))
470                         pmc_stop_counter(pmc);
471         }
472
473         if (kvm_x86_ops.pmu_ops->cleanup)
474                 kvm_x86_ops.pmu_ops->cleanup(vcpu);
475
476         bitmap_zero(pmu->pmc_in_use, X86_PMC_IDX_MAX);
477 }
478
479 void kvm_pmu_destroy(struct kvm_vcpu *vcpu)
480 {
481         kvm_pmu_reset(vcpu);
482 }
483
484 int kvm_vm_ioctl_set_pmu_event_filter(struct kvm *kvm, void __user *argp)
485 {
486         struct kvm_pmu_event_filter tmp, *filter;
487         size_t size;
488         int r;
489
490         if (copy_from_user(&tmp, argp, sizeof(tmp)))
491                 return -EFAULT;
492
493         if (tmp.action != KVM_PMU_EVENT_ALLOW &&
494             tmp.action != KVM_PMU_EVENT_DENY)
495                 return -EINVAL;
496
497         if (tmp.flags != 0)
498                 return -EINVAL;
499
500         if (tmp.nevents > KVM_PMU_EVENT_FILTER_MAX_EVENTS)
501                 return -E2BIG;
502
503         size = struct_size(filter, events, tmp.nevents);
504         filter = kmalloc(size, GFP_KERNEL_ACCOUNT);
505         if (!filter)
506                 return -ENOMEM;
507
508         r = -EFAULT;
509         if (copy_from_user(filter, argp, size))
510                 goto cleanup;
511
512         /* Ensure nevents can't be changed between the user copies. */
513         *filter = tmp;
514
515         mutex_lock(&kvm->lock);
516         filter = rcu_replace_pointer(kvm->arch.pmu_event_filter, filter,
517                                      mutex_is_locked(&kvm->lock));
518         mutex_unlock(&kvm->lock);
519
520         synchronize_srcu_expedited(&kvm->srcu);
521         r = 0;
522 cleanup:
523         kfree(filter);
524         return r;
525 }