pmu.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044
  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. #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  13. #include <linux/types.h>
  14. #include <linux/kvm_host.h>
  15. #include <linux/perf_event.h>
  16. #include <linux/bsearch.h>
  17. #include <linux/sort.h>
  18. #include <asm/perf_event.h>
  19. #include <asm/cpu_device_id.h>
  20. #include "x86.h"
  21. #include "cpuid.h"
  22. #include "lapic.h"
  23. #include "pmu.h"
  24. /* This is enough to filter the vast majority of currently defined events. */
  25. #define KVM_PMU_EVENT_FILTER_MAX_EVENTS 300
  26. struct x86_pmu_capability __read_mostly kvm_pmu_cap;
  27. EXPORT_SYMBOL_GPL(kvm_pmu_cap);
  28. struct kvm_pmu_emulated_event_selectors __read_mostly kvm_pmu_eventsel;
  29. EXPORT_SYMBOL_GPL(kvm_pmu_eventsel);
  30. /* Precise Distribution of Instructions Retired (PDIR) */
  31. static const struct x86_cpu_id vmx_pebs_pdir_cpu[] = {
  32. X86_MATCH_VFM(INTEL_ICELAKE_D, NULL),
  33. X86_MATCH_VFM(INTEL_ICELAKE_X, NULL),
  34. /* Instruction-Accurate PDIR (PDIR++) */
  35. X86_MATCH_VFM(INTEL_SAPPHIRERAPIDS_X, NULL),
  36. {}
  37. };
  38. /* Precise Distribution (PDist) */
  39. static const struct x86_cpu_id vmx_pebs_pdist_cpu[] = {
  40. X86_MATCH_VFM(INTEL_SAPPHIRERAPIDS_X, NULL),
  41. {}
  42. };
  43. /* NOTE:
  44. * - Each perf counter is defined as "struct kvm_pmc";
  45. * - There are two types of perf counters: general purpose (gp) and fixed.
  46. * gp counters are stored in gp_counters[] and fixed counters are stored
  47. * in fixed_counters[] respectively. Both of them are part of "struct
  48. * kvm_pmu";
  49. * - pmu.c understands the difference between gp counters and fixed counters.
  50. * However AMD doesn't support fixed-counters;
  51. * - There are three types of index to access perf counters (PMC):
  52. * 1. MSR (named msr): For example Intel has MSR_IA32_PERFCTRn and AMD
  53. * has MSR_K7_PERFCTRn and, for families 15H and later,
  54. * MSR_F15H_PERF_CTRn, where MSR_F15H_PERF_CTR[0-3] are
  55. * aliased to MSR_K7_PERFCTRn.
  56. * 2. MSR Index (named idx): This normally is used by RDPMC instruction.
  57. * For instance AMD RDPMC instruction uses 0000_0003h in ECX to access
  58. * C001_0007h (MSR_K7_PERCTR3). Intel has a similar mechanism, except
  59. * that it also supports fixed counters. idx can be used to as index to
  60. * gp and fixed counters.
  61. * 3. Global PMC Index (named pmc): pmc is an index specific to PMU
  62. * code. Each pmc, stored in kvm_pmc.idx field, is unique across
  63. * all perf counters (both gp and fixed). The mapping relationship
  64. * between pmc and perf counters is as the following:
  65. * * Intel: [0 .. KVM_MAX_NR_INTEL_GP_COUNTERS-1] <=> gp counters
  66. * [KVM_FIXED_PMC_BASE_IDX .. KVM_FIXED_PMC_BASE_IDX + 2] <=> fixed
  67. * * AMD: [0 .. AMD64_NUM_COUNTERS-1] and, for families 15H
  68. * and later, [0 .. AMD64_NUM_COUNTERS_CORE-1] <=> gp counters
  69. */
  70. static struct kvm_pmu_ops kvm_pmu_ops __read_mostly;
  71. #define KVM_X86_PMU_OP(func) \
  72. DEFINE_STATIC_CALL_NULL(kvm_x86_pmu_##func, \
  73. *(((struct kvm_pmu_ops *)0)->func));
  74. #define KVM_X86_PMU_OP_OPTIONAL KVM_X86_PMU_OP
  75. #include <asm/kvm-x86-pmu-ops.h>
  76. void kvm_pmu_ops_update(const struct kvm_pmu_ops *pmu_ops)
  77. {
  78. memcpy(&kvm_pmu_ops, pmu_ops, sizeof(kvm_pmu_ops));
  79. #define __KVM_X86_PMU_OP(func) \
  80. static_call_update(kvm_x86_pmu_##func, kvm_pmu_ops.func);
  81. #define KVM_X86_PMU_OP(func) \
  82. WARN_ON(!kvm_pmu_ops.func); __KVM_X86_PMU_OP(func)
  83. #define KVM_X86_PMU_OP_OPTIONAL __KVM_X86_PMU_OP
  84. #include <asm/kvm-x86-pmu-ops.h>
  85. #undef __KVM_X86_PMU_OP
  86. }
  87. static inline void __kvm_perf_overflow(struct kvm_pmc *pmc, bool in_pmi)
  88. {
  89. struct kvm_pmu *pmu = pmc_to_pmu(pmc);
  90. bool skip_pmi = false;
  91. if (pmc->perf_event && pmc->perf_event->attr.precise_ip) {
  92. if (!in_pmi) {
  93. /*
  94. * TODO: KVM is currently _choosing_ to not generate records
  95. * for emulated instructions, avoiding BUFFER_OVF PMI when
  96. * there are no records. Strictly speaking, it should be done
  97. * as well in the right context to improve sampling accuracy.
  98. */
  99. skip_pmi = true;
  100. } else {
  101. /* Indicate PEBS overflow PMI to guest. */
  102. skip_pmi = __test_and_set_bit(GLOBAL_STATUS_BUFFER_OVF_BIT,
  103. (unsigned long *)&pmu->global_status);
  104. }
  105. } else {
  106. __set_bit(pmc->idx, (unsigned long *)&pmu->global_status);
  107. }
  108. if (pmc->intr && !skip_pmi)
  109. kvm_make_request(KVM_REQ_PMI, pmc->vcpu);
  110. }
  111. static void kvm_perf_overflow(struct perf_event *perf_event,
  112. struct perf_sample_data *data,
  113. struct pt_regs *regs)
  114. {
  115. struct kvm_pmc *pmc = perf_event->overflow_handler_context;
  116. /*
  117. * Ignore asynchronous overflow events for counters that are scheduled
  118. * to be reprogrammed, e.g. if a PMI for the previous event races with
  119. * KVM's handling of a related guest WRMSR.
  120. */
  121. if (test_and_set_bit(pmc->idx, pmc_to_pmu(pmc)->reprogram_pmi))
  122. return;
  123. __kvm_perf_overflow(pmc, true);
  124. kvm_make_request(KVM_REQ_PMU, pmc->vcpu);
  125. }
  126. static u64 pmc_get_pebs_precise_level(struct kvm_pmc *pmc)
  127. {
  128. /*
  129. * For some model specific pebs counters with special capabilities
  130. * (PDIR, PDIR++, PDIST), KVM needs to raise the event precise
  131. * level to the maximum value (currently 3, backwards compatible)
  132. * so that the perf subsystem would assign specific hardware counter
  133. * with that capability for vPMC.
  134. */
  135. if ((pmc->idx == 0 && x86_match_cpu(vmx_pebs_pdist_cpu)) ||
  136. (pmc->idx == 32 && x86_match_cpu(vmx_pebs_pdir_cpu)))
  137. return 3;
  138. /*
  139. * The non-zero precision level of guest event makes the ordinary
  140. * guest event becomes a guest PEBS event and triggers the host
  141. * PEBS PMI handler to determine whether the PEBS overflow PMI
  142. * comes from the host counters or the guest.
  143. */
  144. return 1;
  145. }
  146. static u64 get_sample_period(struct kvm_pmc *pmc, u64 counter_value)
  147. {
  148. u64 sample_period = (-counter_value) & pmc_bitmask(pmc);
  149. if (!sample_period)
  150. sample_period = pmc_bitmask(pmc) + 1;
  151. return sample_period;
  152. }
  153. static int pmc_reprogram_counter(struct kvm_pmc *pmc, u32 type, u64 config,
  154. bool exclude_user, bool exclude_kernel,
  155. bool intr)
  156. {
  157. struct kvm_pmu *pmu = pmc_to_pmu(pmc);
  158. struct perf_event *event;
  159. struct perf_event_attr attr = {
  160. .type = type,
  161. .size = sizeof(attr),
  162. .pinned = true,
  163. .exclude_idle = true,
  164. .exclude_host = 1,
  165. .exclude_user = exclude_user,
  166. .exclude_kernel = exclude_kernel,
  167. .config = config,
  168. };
  169. bool pebs = test_bit(pmc->idx, (unsigned long *)&pmu->pebs_enable);
  170. attr.sample_period = get_sample_period(pmc, pmc->counter);
  171. if ((attr.config & HSW_IN_TX_CHECKPOINTED) &&
  172. (boot_cpu_has(X86_FEATURE_RTM) || boot_cpu_has(X86_FEATURE_HLE))) {
  173. /*
  174. * HSW_IN_TX_CHECKPOINTED is not supported with nonzero
  175. * period. Just clear the sample period so at least
  176. * allocating the counter doesn't fail.
  177. */
  178. attr.sample_period = 0;
  179. }
  180. if (pebs) {
  181. /*
  182. * For most PEBS hardware events, the difference in the software
  183. * precision levels of guest and host PEBS events will not affect
  184. * the accuracy of the PEBS profiling result, because the "event IP"
  185. * in the PEBS record is calibrated on the guest side.
  186. */
  187. attr.precise_ip = pmc_get_pebs_precise_level(pmc);
  188. }
  189. event = perf_event_create_kernel_counter(&attr, -1, current,
  190. kvm_perf_overflow, pmc);
  191. if (IS_ERR(event)) {
  192. pr_debug_ratelimited("kvm_pmu: event creation failed %ld for pmc->idx = %d\n",
  193. PTR_ERR(event), pmc->idx);
  194. return PTR_ERR(event);
  195. }
  196. pmc->perf_event = event;
  197. pmc_to_pmu(pmc)->event_count++;
  198. pmc->is_paused = false;
  199. pmc->intr = intr || pebs;
  200. return 0;
  201. }
  202. static bool pmc_pause_counter(struct kvm_pmc *pmc)
  203. {
  204. u64 counter = pmc->counter;
  205. u64 prev_counter;
  206. /* update counter, reset event value to avoid redundant accumulation */
  207. if (pmc->perf_event && !pmc->is_paused)
  208. counter += perf_event_pause(pmc->perf_event, true);
  209. /*
  210. * Snapshot the previous counter *after* accumulating state from perf.
  211. * If overflow already happened, hardware (via perf) is responsible for
  212. * generating a PMI. KVM just needs to detect overflow on emulated
  213. * counter events that haven't yet been processed.
  214. */
  215. prev_counter = counter & pmc_bitmask(pmc);
  216. counter += pmc->emulated_counter;
  217. pmc->counter = counter & pmc_bitmask(pmc);
  218. pmc->emulated_counter = 0;
  219. pmc->is_paused = true;
  220. return pmc->counter < prev_counter;
  221. }
  222. static bool pmc_resume_counter(struct kvm_pmc *pmc)
  223. {
  224. if (!pmc->perf_event)
  225. return false;
  226. /* recalibrate sample period and check if it's accepted by perf core */
  227. if (is_sampling_event(pmc->perf_event) &&
  228. perf_event_period(pmc->perf_event,
  229. get_sample_period(pmc, pmc->counter)))
  230. return false;
  231. if (test_bit(pmc->idx, (unsigned long *)&pmc_to_pmu(pmc)->pebs_enable) !=
  232. (!!pmc->perf_event->attr.precise_ip))
  233. return false;
  234. /* reuse perf_event to serve as pmc_reprogram_counter() does*/
  235. perf_event_enable(pmc->perf_event);
  236. pmc->is_paused = false;
  237. return true;
  238. }
  239. static void pmc_release_perf_event(struct kvm_pmc *pmc)
  240. {
  241. if (pmc->perf_event) {
  242. perf_event_release_kernel(pmc->perf_event);
  243. pmc->perf_event = NULL;
  244. pmc->current_config = 0;
  245. pmc_to_pmu(pmc)->event_count--;
  246. }
  247. }
  248. static void pmc_stop_counter(struct kvm_pmc *pmc)
  249. {
  250. if (pmc->perf_event) {
  251. pmc->counter = pmc_read_counter(pmc);
  252. pmc_release_perf_event(pmc);
  253. }
  254. }
  255. static void pmc_update_sample_period(struct kvm_pmc *pmc)
  256. {
  257. if (!pmc->perf_event || pmc->is_paused ||
  258. !is_sampling_event(pmc->perf_event))
  259. return;
  260. perf_event_period(pmc->perf_event,
  261. get_sample_period(pmc, pmc->counter));
  262. }
  263. void pmc_write_counter(struct kvm_pmc *pmc, u64 val)
  264. {
  265. /*
  266. * Drop any unconsumed accumulated counts, the WRMSR is a write, not a
  267. * read-modify-write. Adjust the counter value so that its value is
  268. * relative to the current count, as reading the current count from
  269. * perf is faster than pausing and repgrogramming the event in order to
  270. * reset it to '0'. Note, this very sneakily offsets the accumulated
  271. * emulated count too, by using pmc_read_counter()!
  272. */
  273. pmc->emulated_counter = 0;
  274. pmc->counter += val - pmc_read_counter(pmc);
  275. pmc->counter &= pmc_bitmask(pmc);
  276. pmc_update_sample_period(pmc);
  277. }
  278. EXPORT_SYMBOL_GPL(pmc_write_counter);
  279. static int filter_cmp(const void *pa, const void *pb, u64 mask)
  280. {
  281. u64 a = *(u64 *)pa & mask;
  282. u64 b = *(u64 *)pb & mask;
  283. return (a > b) - (a < b);
  284. }
  285. static int filter_sort_cmp(const void *pa, const void *pb)
  286. {
  287. return filter_cmp(pa, pb, (KVM_PMU_MASKED_ENTRY_EVENT_SELECT |
  288. KVM_PMU_MASKED_ENTRY_EXCLUDE));
  289. }
  290. /*
  291. * For the event filter, searching is done on the 'includes' list and
  292. * 'excludes' list separately rather than on the 'events' list (which
  293. * has both). As a result the exclude bit can be ignored.
  294. */
  295. static int filter_event_cmp(const void *pa, const void *pb)
  296. {
  297. return filter_cmp(pa, pb, (KVM_PMU_MASKED_ENTRY_EVENT_SELECT));
  298. }
  299. static int find_filter_index(u64 *events, u64 nevents, u64 key)
  300. {
  301. u64 *fe = bsearch(&key, events, nevents, sizeof(events[0]),
  302. filter_event_cmp);
  303. if (!fe)
  304. return -1;
  305. return fe - events;
  306. }
  307. static bool is_filter_entry_match(u64 filter_event, u64 umask)
  308. {
  309. u64 mask = filter_event >> (KVM_PMU_MASKED_ENTRY_UMASK_MASK_SHIFT - 8);
  310. u64 match = filter_event & KVM_PMU_MASKED_ENTRY_UMASK_MATCH;
  311. BUILD_BUG_ON((KVM_PMU_ENCODE_MASKED_ENTRY(0, 0xff, 0, false) >>
  312. (KVM_PMU_MASKED_ENTRY_UMASK_MASK_SHIFT - 8)) !=
  313. ARCH_PERFMON_EVENTSEL_UMASK);
  314. return (umask & mask) == match;
  315. }
  316. static bool filter_contains_match(u64 *events, u64 nevents, u64 eventsel)
  317. {
  318. u64 event_select = eventsel & kvm_pmu_ops.EVENTSEL_EVENT;
  319. u64 umask = eventsel & ARCH_PERFMON_EVENTSEL_UMASK;
  320. int i, index;
  321. index = find_filter_index(events, nevents, event_select);
  322. if (index < 0)
  323. return false;
  324. /*
  325. * Entries are sorted by the event select. Walk the list in both
  326. * directions to process all entries with the targeted event select.
  327. */
  328. for (i = index; i < nevents; i++) {
  329. if (filter_event_cmp(&events[i], &event_select))
  330. break;
  331. if (is_filter_entry_match(events[i], umask))
  332. return true;
  333. }
  334. for (i = index - 1; i >= 0; i--) {
  335. if (filter_event_cmp(&events[i], &event_select))
  336. break;
  337. if (is_filter_entry_match(events[i], umask))
  338. return true;
  339. }
  340. return false;
  341. }
  342. static bool is_gp_event_allowed(struct kvm_x86_pmu_event_filter *f,
  343. u64 eventsel)
  344. {
  345. if (filter_contains_match(f->includes, f->nr_includes, eventsel) &&
  346. !filter_contains_match(f->excludes, f->nr_excludes, eventsel))
  347. return f->action == KVM_PMU_EVENT_ALLOW;
  348. return f->action == KVM_PMU_EVENT_DENY;
  349. }
  350. static bool is_fixed_event_allowed(struct kvm_x86_pmu_event_filter *filter,
  351. int idx)
  352. {
  353. int fixed_idx = idx - KVM_FIXED_PMC_BASE_IDX;
  354. if (filter->action == KVM_PMU_EVENT_DENY &&
  355. test_bit(fixed_idx, (ulong *)&filter->fixed_counter_bitmap))
  356. return false;
  357. if (filter->action == KVM_PMU_EVENT_ALLOW &&
  358. !test_bit(fixed_idx, (ulong *)&filter->fixed_counter_bitmap))
  359. return false;
  360. return true;
  361. }
  362. static bool check_pmu_event_filter(struct kvm_pmc *pmc)
  363. {
  364. struct kvm_x86_pmu_event_filter *filter;
  365. struct kvm *kvm = pmc->vcpu->kvm;
  366. filter = srcu_dereference(kvm->arch.pmu_event_filter, &kvm->srcu);
  367. if (!filter)
  368. return true;
  369. if (pmc_is_gp(pmc))
  370. return is_gp_event_allowed(filter, pmc->eventsel);
  371. return is_fixed_event_allowed(filter, pmc->idx);
  372. }
  373. static bool pmc_event_is_allowed(struct kvm_pmc *pmc)
  374. {
  375. return pmc_is_globally_enabled(pmc) && pmc_speculative_in_use(pmc) &&
  376. check_pmu_event_filter(pmc);
  377. }
  378. static int reprogram_counter(struct kvm_pmc *pmc)
  379. {
  380. struct kvm_pmu *pmu = pmc_to_pmu(pmc);
  381. u64 eventsel = pmc->eventsel;
  382. u64 new_config = eventsel;
  383. bool emulate_overflow;
  384. u8 fixed_ctr_ctrl;
  385. emulate_overflow = pmc_pause_counter(pmc);
  386. if (!pmc_event_is_allowed(pmc))
  387. return 0;
  388. if (emulate_overflow)
  389. __kvm_perf_overflow(pmc, false);
  390. if (eventsel & ARCH_PERFMON_EVENTSEL_PIN_CONTROL)
  391. printk_once("kvm pmu: pin control bit is ignored\n");
  392. if (pmc_is_fixed(pmc)) {
  393. fixed_ctr_ctrl = fixed_ctrl_field(pmu->fixed_ctr_ctrl,
  394. pmc->idx - KVM_FIXED_PMC_BASE_IDX);
  395. if (fixed_ctr_ctrl & INTEL_FIXED_0_KERNEL)
  396. eventsel |= ARCH_PERFMON_EVENTSEL_OS;
  397. if (fixed_ctr_ctrl & INTEL_FIXED_0_USER)
  398. eventsel |= ARCH_PERFMON_EVENTSEL_USR;
  399. if (fixed_ctr_ctrl & INTEL_FIXED_0_ENABLE_PMI)
  400. eventsel |= ARCH_PERFMON_EVENTSEL_INT;
  401. new_config = (u64)fixed_ctr_ctrl;
  402. }
  403. if (pmc->current_config == new_config && pmc_resume_counter(pmc))
  404. return 0;
  405. pmc_release_perf_event(pmc);
  406. pmc->current_config = new_config;
  407. return pmc_reprogram_counter(pmc, PERF_TYPE_RAW,
  408. (eventsel & pmu->raw_event_mask),
  409. !(eventsel & ARCH_PERFMON_EVENTSEL_USR),
  410. !(eventsel & ARCH_PERFMON_EVENTSEL_OS),
  411. eventsel & ARCH_PERFMON_EVENTSEL_INT);
  412. }
  413. void kvm_pmu_handle_event(struct kvm_vcpu *vcpu)
  414. {
  415. DECLARE_BITMAP(bitmap, X86_PMC_IDX_MAX);
  416. struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
  417. struct kvm_pmc *pmc;
  418. int bit;
  419. bitmap_copy(bitmap, pmu->reprogram_pmi, X86_PMC_IDX_MAX);
  420. /*
  421. * The reprogramming bitmap can be written asynchronously by something
  422. * other than the task that holds vcpu->mutex, take care to clear only
  423. * the bits that will actually processed.
  424. */
  425. BUILD_BUG_ON(sizeof(bitmap) != sizeof(atomic64_t));
  426. atomic64_andnot(*(s64 *)bitmap, &pmu->__reprogram_pmi);
  427. kvm_for_each_pmc(pmu, pmc, bit, bitmap) {
  428. /*
  429. * If reprogramming fails, e.g. due to contention, re-set the
  430. * regprogram bit set, i.e. opportunistically try again on the
  431. * next PMU refresh. Don't make a new request as doing so can
  432. * stall the guest if reprogramming repeatedly fails.
  433. */
  434. if (reprogram_counter(pmc))
  435. set_bit(pmc->idx, pmu->reprogram_pmi);
  436. }
  437. /*
  438. * Release unused perf_events if the corresponding guest MSRs weren't
  439. * accessed during the last vCPU time slice (need_cleanup is set when
  440. * the vCPU is scheduled back in).
  441. */
  442. if (unlikely(pmu->need_cleanup))
  443. kvm_pmu_cleanup(vcpu);
  444. }
  445. int kvm_pmu_check_rdpmc_early(struct kvm_vcpu *vcpu, unsigned int idx)
  446. {
  447. /*
  448. * On Intel, VMX interception has priority over RDPMC exceptions that
  449. * aren't already handled by the emulator, i.e. there are no additional
  450. * check needed for Intel PMUs.
  451. *
  452. * On AMD, _all_ exceptions on RDPMC have priority over SVM intercepts,
  453. * i.e. an invalid PMC results in a #GP, not #VMEXIT.
  454. */
  455. if (!kvm_pmu_ops.check_rdpmc_early)
  456. return 0;
  457. return kvm_pmu_call(check_rdpmc_early)(vcpu, idx);
  458. }
  459. bool is_vmware_backdoor_pmc(u32 pmc_idx)
  460. {
  461. switch (pmc_idx) {
  462. case VMWARE_BACKDOOR_PMC_HOST_TSC:
  463. case VMWARE_BACKDOOR_PMC_REAL_TIME:
  464. case VMWARE_BACKDOOR_PMC_APPARENT_TIME:
  465. return true;
  466. }
  467. return false;
  468. }
  469. static int kvm_pmu_rdpmc_vmware(struct kvm_vcpu *vcpu, unsigned idx, u64 *data)
  470. {
  471. u64 ctr_val;
  472. switch (idx) {
  473. case VMWARE_BACKDOOR_PMC_HOST_TSC:
  474. ctr_val = rdtsc();
  475. break;
  476. case VMWARE_BACKDOOR_PMC_REAL_TIME:
  477. ctr_val = ktime_get_boottime_ns();
  478. break;
  479. case VMWARE_BACKDOOR_PMC_APPARENT_TIME:
  480. ctr_val = ktime_get_boottime_ns() +
  481. vcpu->kvm->arch.kvmclock_offset;
  482. break;
  483. default:
  484. return 1;
  485. }
  486. *data = ctr_val;
  487. return 0;
  488. }
  489. int kvm_pmu_rdpmc(struct kvm_vcpu *vcpu, unsigned idx, u64 *data)
  490. {
  491. struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
  492. struct kvm_pmc *pmc;
  493. u64 mask = ~0ull;
  494. if (!pmu->version)
  495. return 1;
  496. if (is_vmware_backdoor_pmc(idx))
  497. return kvm_pmu_rdpmc_vmware(vcpu, idx, data);
  498. pmc = kvm_pmu_call(rdpmc_ecx_to_pmc)(vcpu, idx, &mask);
  499. if (!pmc)
  500. return 1;
  501. if (!kvm_is_cr4_bit_set(vcpu, X86_CR4_PCE) &&
  502. (kvm_x86_call(get_cpl)(vcpu) != 0) &&
  503. kvm_is_cr0_bit_set(vcpu, X86_CR0_PE))
  504. return 1;
  505. *data = pmc_read_counter(pmc) & mask;
  506. return 0;
  507. }
  508. void kvm_pmu_deliver_pmi(struct kvm_vcpu *vcpu)
  509. {
  510. if (lapic_in_kernel(vcpu)) {
  511. kvm_pmu_call(deliver_pmi)(vcpu);
  512. kvm_apic_local_deliver(vcpu->arch.apic, APIC_LVTPC);
  513. }
  514. }
  515. bool kvm_pmu_is_valid_msr(struct kvm_vcpu *vcpu, u32 msr)
  516. {
  517. switch (msr) {
  518. case MSR_CORE_PERF_GLOBAL_STATUS:
  519. case MSR_CORE_PERF_GLOBAL_CTRL:
  520. case MSR_CORE_PERF_GLOBAL_OVF_CTRL:
  521. return kvm_pmu_has_perf_global_ctrl(vcpu_to_pmu(vcpu));
  522. default:
  523. break;
  524. }
  525. return kvm_pmu_call(msr_idx_to_pmc)(vcpu, msr) ||
  526. kvm_pmu_call(is_valid_msr)(vcpu, msr);
  527. }
  528. static void kvm_pmu_mark_pmc_in_use(struct kvm_vcpu *vcpu, u32 msr)
  529. {
  530. struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
  531. struct kvm_pmc *pmc = kvm_pmu_call(msr_idx_to_pmc)(vcpu, msr);
  532. if (pmc)
  533. __set_bit(pmc->idx, pmu->pmc_in_use);
  534. }
  535. int kvm_pmu_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
  536. {
  537. struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
  538. u32 msr = msr_info->index;
  539. switch (msr) {
  540. case MSR_CORE_PERF_GLOBAL_STATUS:
  541. case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS:
  542. msr_info->data = pmu->global_status;
  543. break;
  544. case MSR_AMD64_PERF_CNTR_GLOBAL_CTL:
  545. case MSR_CORE_PERF_GLOBAL_CTRL:
  546. msr_info->data = pmu->global_ctrl;
  547. break;
  548. case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_CLR:
  549. case MSR_CORE_PERF_GLOBAL_OVF_CTRL:
  550. msr_info->data = 0;
  551. break;
  552. default:
  553. return kvm_pmu_call(get_msr)(vcpu, msr_info);
  554. }
  555. return 0;
  556. }
  557. int kvm_pmu_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
  558. {
  559. struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
  560. u32 msr = msr_info->index;
  561. u64 data = msr_info->data;
  562. u64 diff;
  563. /*
  564. * Note, AMD ignores writes to reserved bits and read-only PMU MSRs,
  565. * whereas Intel generates #GP on attempts to write reserved/RO MSRs.
  566. */
  567. switch (msr) {
  568. case MSR_CORE_PERF_GLOBAL_STATUS:
  569. if (!msr_info->host_initiated)
  570. return 1; /* RO MSR */
  571. fallthrough;
  572. case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS:
  573. /* Per PPR, Read-only MSR. Writes are ignored. */
  574. if (!msr_info->host_initiated)
  575. break;
  576. if (data & pmu->global_status_rsvd)
  577. return 1;
  578. pmu->global_status = data;
  579. break;
  580. case MSR_AMD64_PERF_CNTR_GLOBAL_CTL:
  581. data &= ~pmu->global_ctrl_rsvd;
  582. fallthrough;
  583. case MSR_CORE_PERF_GLOBAL_CTRL:
  584. if (!kvm_valid_perf_global_ctrl(pmu, data))
  585. return 1;
  586. if (pmu->global_ctrl != data) {
  587. diff = pmu->global_ctrl ^ data;
  588. pmu->global_ctrl = data;
  589. reprogram_counters(pmu, diff);
  590. }
  591. break;
  592. case MSR_CORE_PERF_GLOBAL_OVF_CTRL:
  593. /*
  594. * GLOBAL_OVF_CTRL, a.k.a. GLOBAL STATUS_RESET, clears bits in
  595. * GLOBAL_STATUS, and so the set of reserved bits is the same.
  596. */
  597. if (data & pmu->global_status_rsvd)
  598. return 1;
  599. fallthrough;
  600. case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_CLR:
  601. if (!msr_info->host_initiated)
  602. pmu->global_status &= ~data;
  603. break;
  604. default:
  605. kvm_pmu_mark_pmc_in_use(vcpu, msr_info->index);
  606. return kvm_pmu_call(set_msr)(vcpu, msr_info);
  607. }
  608. return 0;
  609. }
  610. static void kvm_pmu_reset(struct kvm_vcpu *vcpu)
  611. {
  612. struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
  613. struct kvm_pmc *pmc;
  614. int i;
  615. pmu->need_cleanup = false;
  616. bitmap_zero(pmu->reprogram_pmi, X86_PMC_IDX_MAX);
  617. kvm_for_each_pmc(pmu, pmc, i, pmu->all_valid_pmc_idx) {
  618. pmc_stop_counter(pmc);
  619. pmc->counter = 0;
  620. pmc->emulated_counter = 0;
  621. if (pmc_is_gp(pmc))
  622. pmc->eventsel = 0;
  623. }
  624. pmu->fixed_ctr_ctrl = pmu->global_ctrl = pmu->global_status = 0;
  625. kvm_pmu_call(reset)(vcpu);
  626. }
  627. /*
  628. * Refresh the PMU configuration for the vCPU, e.g. if userspace changes CPUID
  629. * and/or PERF_CAPABILITIES.
  630. */
  631. void kvm_pmu_refresh(struct kvm_vcpu *vcpu)
  632. {
  633. struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
  634. if (KVM_BUG_ON(kvm_vcpu_has_run(vcpu), vcpu->kvm))
  635. return;
  636. /*
  637. * Stop/release all existing counters/events before realizing the new
  638. * vPMU model.
  639. */
  640. kvm_pmu_reset(vcpu);
  641. pmu->version = 0;
  642. pmu->nr_arch_gp_counters = 0;
  643. pmu->nr_arch_fixed_counters = 0;
  644. pmu->counter_bitmask[KVM_PMC_GP] = 0;
  645. pmu->counter_bitmask[KVM_PMC_FIXED] = 0;
  646. pmu->reserved_bits = 0xffffffff00200000ull;
  647. pmu->raw_event_mask = X86_RAW_EVENT_MASK;
  648. pmu->global_ctrl_rsvd = ~0ull;
  649. pmu->global_status_rsvd = ~0ull;
  650. pmu->fixed_ctr_ctrl_rsvd = ~0ull;
  651. pmu->pebs_enable_rsvd = ~0ull;
  652. pmu->pebs_data_cfg_rsvd = ~0ull;
  653. bitmap_zero(pmu->all_valid_pmc_idx, X86_PMC_IDX_MAX);
  654. if (!vcpu->kvm->arch.enable_pmu)
  655. return;
  656. kvm_pmu_call(refresh)(vcpu);
  657. /*
  658. * At RESET, both Intel and AMD CPUs set all enable bits for general
  659. * purpose counters in IA32_PERF_GLOBAL_CTRL (so that software that
  660. * was written for v1 PMUs don't unknowingly leave GP counters disabled
  661. * in the global controls). Emulate that behavior when refreshing the
  662. * PMU so that userspace doesn't need to manually set PERF_GLOBAL_CTRL.
  663. */
  664. if (kvm_pmu_has_perf_global_ctrl(pmu) && pmu->nr_arch_gp_counters)
  665. pmu->global_ctrl = GENMASK_ULL(pmu->nr_arch_gp_counters - 1, 0);
  666. }
  667. void kvm_pmu_init(struct kvm_vcpu *vcpu)
  668. {
  669. struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
  670. memset(pmu, 0, sizeof(*pmu));
  671. kvm_pmu_call(init)(vcpu);
  672. kvm_pmu_refresh(vcpu);
  673. }
  674. /* Release perf_events for vPMCs that have been unused for a full time slice. */
  675. void kvm_pmu_cleanup(struct kvm_vcpu *vcpu)
  676. {
  677. struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
  678. struct kvm_pmc *pmc = NULL;
  679. DECLARE_BITMAP(bitmask, X86_PMC_IDX_MAX);
  680. int i;
  681. pmu->need_cleanup = false;
  682. bitmap_andnot(bitmask, pmu->all_valid_pmc_idx,
  683. pmu->pmc_in_use, X86_PMC_IDX_MAX);
  684. kvm_for_each_pmc(pmu, pmc, i, bitmask) {
  685. if (pmc->perf_event && !pmc_speculative_in_use(pmc))
  686. pmc_stop_counter(pmc);
  687. }
  688. kvm_pmu_call(cleanup)(vcpu);
  689. bitmap_zero(pmu->pmc_in_use, X86_PMC_IDX_MAX);
  690. }
  691. void kvm_pmu_destroy(struct kvm_vcpu *vcpu)
  692. {
  693. kvm_pmu_reset(vcpu);
  694. }
  695. static void kvm_pmu_incr_counter(struct kvm_pmc *pmc)
  696. {
  697. pmc->emulated_counter++;
  698. kvm_pmu_request_counter_reprogram(pmc);
  699. }
  700. static inline bool cpl_is_matched(struct kvm_pmc *pmc)
  701. {
  702. bool select_os, select_user;
  703. u64 config;
  704. if (pmc_is_gp(pmc)) {
  705. config = pmc->eventsel;
  706. select_os = config & ARCH_PERFMON_EVENTSEL_OS;
  707. select_user = config & ARCH_PERFMON_EVENTSEL_USR;
  708. } else {
  709. config = fixed_ctrl_field(pmc_to_pmu(pmc)->fixed_ctr_ctrl,
  710. pmc->idx - KVM_FIXED_PMC_BASE_IDX);
  711. select_os = config & INTEL_FIXED_0_KERNEL;
  712. select_user = config & INTEL_FIXED_0_USER;
  713. }
  714. /*
  715. * Skip the CPL lookup, which isn't free on Intel, if the result will
  716. * be the same regardless of the CPL.
  717. */
  718. if (select_os == select_user)
  719. return select_os;
  720. return (kvm_x86_call(get_cpl)(pmc->vcpu) == 0) ? select_os :
  721. select_user;
  722. }
  723. void kvm_pmu_trigger_event(struct kvm_vcpu *vcpu, u64 eventsel)
  724. {
  725. DECLARE_BITMAP(bitmap, X86_PMC_IDX_MAX);
  726. struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
  727. struct kvm_pmc *pmc;
  728. int i;
  729. BUILD_BUG_ON(sizeof(pmu->global_ctrl) * BITS_PER_BYTE != X86_PMC_IDX_MAX);
  730. if (!kvm_pmu_has_perf_global_ctrl(pmu))
  731. bitmap_copy(bitmap, pmu->all_valid_pmc_idx, X86_PMC_IDX_MAX);
  732. else if (!bitmap_and(bitmap, pmu->all_valid_pmc_idx,
  733. (unsigned long *)&pmu->global_ctrl, X86_PMC_IDX_MAX))
  734. return;
  735. kvm_for_each_pmc(pmu, pmc, i, bitmap) {
  736. /*
  737. * Ignore checks for edge detect (all events currently emulated
  738. * but KVM are always rising edges), pin control (unsupported
  739. * by modern CPUs), and counter mask and its invert flag (KVM
  740. * doesn't emulate multiple events in a single clock cycle).
  741. *
  742. * Note, the uppermost nibble of AMD's mask overlaps Intel's
  743. * IN_TX (bit 32) and IN_TXCP (bit 33), as well as two reserved
  744. * bits (bits 35:34). Checking the "in HLE/RTM transaction"
  745. * flags is correct as the vCPU can't be in a transaction if
  746. * KVM is emulating an instruction. Checking the reserved bits
  747. * might be wrong if they are defined in the future, but so
  748. * could ignoring them, so do the simple thing for now.
  749. */
  750. if (((pmc->eventsel ^ eventsel) & AMD64_RAW_EVENT_MASK_NB) ||
  751. !pmc_event_is_allowed(pmc) || !cpl_is_matched(pmc))
  752. continue;
  753. kvm_pmu_incr_counter(pmc);
  754. }
  755. }
  756. EXPORT_SYMBOL_GPL(kvm_pmu_trigger_event);
  757. static bool is_masked_filter_valid(const struct kvm_x86_pmu_event_filter *filter)
  758. {
  759. u64 mask = kvm_pmu_ops.EVENTSEL_EVENT |
  760. KVM_PMU_MASKED_ENTRY_UMASK_MASK |
  761. KVM_PMU_MASKED_ENTRY_UMASK_MATCH |
  762. KVM_PMU_MASKED_ENTRY_EXCLUDE;
  763. int i;
  764. for (i = 0; i < filter->nevents; i++) {
  765. if (filter->events[i] & ~mask)
  766. return false;
  767. }
  768. return true;
  769. }
  770. static void convert_to_masked_filter(struct kvm_x86_pmu_event_filter *filter)
  771. {
  772. int i, j;
  773. for (i = 0, j = 0; i < filter->nevents; i++) {
  774. /*
  775. * Skip events that are impossible to match against a guest
  776. * event. When filtering, only the event select + unit mask
  777. * of the guest event is used. To maintain backwards
  778. * compatibility, impossible filters can't be rejected :-(
  779. */
  780. if (filter->events[i] & ~(kvm_pmu_ops.EVENTSEL_EVENT |
  781. ARCH_PERFMON_EVENTSEL_UMASK))
  782. continue;
  783. /*
  784. * Convert userspace events to a common in-kernel event so
  785. * only one code path is needed to support both events. For
  786. * the in-kernel events use masked events because they are
  787. * flexible enough to handle both cases. To convert to masked
  788. * events all that's needed is to add an "all ones" umask_mask,
  789. * (unmasked filter events don't support EXCLUDE).
  790. */
  791. filter->events[j++] = filter->events[i] |
  792. (0xFFULL << KVM_PMU_MASKED_ENTRY_UMASK_MASK_SHIFT);
  793. }
  794. filter->nevents = j;
  795. }
  796. static int prepare_filter_lists(struct kvm_x86_pmu_event_filter *filter)
  797. {
  798. int i;
  799. if (!(filter->flags & KVM_PMU_EVENT_FLAG_MASKED_EVENTS))
  800. convert_to_masked_filter(filter);
  801. else if (!is_masked_filter_valid(filter))
  802. return -EINVAL;
  803. /*
  804. * Sort entries by event select and includes vs. excludes so that all
  805. * entries for a given event select can be processed efficiently during
  806. * filtering. The EXCLUDE flag uses a more significant bit than the
  807. * event select, and so the sorted list is also effectively split into
  808. * includes and excludes sub-lists.
  809. */
  810. sort(&filter->events, filter->nevents, sizeof(filter->events[0]),
  811. filter_sort_cmp, NULL);
  812. i = filter->nevents;
  813. /* Find the first EXCLUDE event (only supported for masked events). */
  814. if (filter->flags & KVM_PMU_EVENT_FLAG_MASKED_EVENTS) {
  815. for (i = 0; i < filter->nevents; i++) {
  816. if (filter->events[i] & KVM_PMU_MASKED_ENTRY_EXCLUDE)
  817. break;
  818. }
  819. }
  820. filter->nr_includes = i;
  821. filter->nr_excludes = filter->nevents - filter->nr_includes;
  822. filter->includes = filter->events;
  823. filter->excludes = filter->events + filter->nr_includes;
  824. return 0;
  825. }
  826. int kvm_vm_ioctl_set_pmu_event_filter(struct kvm *kvm, void __user *argp)
  827. {
  828. struct kvm_pmu_event_filter __user *user_filter = argp;
  829. struct kvm_x86_pmu_event_filter *filter;
  830. struct kvm_pmu_event_filter tmp;
  831. struct kvm_vcpu *vcpu;
  832. unsigned long i;
  833. size_t size;
  834. int r;
  835. if (copy_from_user(&tmp, user_filter, sizeof(tmp)))
  836. return -EFAULT;
  837. if (tmp.action != KVM_PMU_EVENT_ALLOW &&
  838. tmp.action != KVM_PMU_EVENT_DENY)
  839. return -EINVAL;
  840. if (tmp.flags & ~KVM_PMU_EVENT_FLAGS_VALID_MASK)
  841. return -EINVAL;
  842. if (tmp.nevents > KVM_PMU_EVENT_FILTER_MAX_EVENTS)
  843. return -E2BIG;
  844. size = struct_size(filter, events, tmp.nevents);
  845. filter = kzalloc(size, GFP_KERNEL_ACCOUNT);
  846. if (!filter)
  847. return -ENOMEM;
  848. filter->action = tmp.action;
  849. filter->nevents = tmp.nevents;
  850. filter->fixed_counter_bitmap = tmp.fixed_counter_bitmap;
  851. filter->flags = tmp.flags;
  852. r = -EFAULT;
  853. if (copy_from_user(filter->events, user_filter->events,
  854. sizeof(filter->events[0]) * filter->nevents))
  855. goto cleanup;
  856. r = prepare_filter_lists(filter);
  857. if (r)
  858. goto cleanup;
  859. mutex_lock(&kvm->lock);
  860. filter = rcu_replace_pointer(kvm->arch.pmu_event_filter, filter,
  861. mutex_is_locked(&kvm->lock));
  862. mutex_unlock(&kvm->lock);
  863. synchronize_srcu_expedited(&kvm->srcu);
  864. BUILD_BUG_ON(sizeof(((struct kvm_pmu *)0)->reprogram_pmi) >
  865. sizeof(((struct kvm_pmu *)0)->__reprogram_pmi));
  866. kvm_for_each_vcpu(i, vcpu, kvm)
  867. atomic64_set(&vcpu_to_pmu(vcpu)->__reprogram_pmi, -1ull);
  868. kvm_make_all_cpus_request(kvm, KVM_REQ_PMU);
  869. r = 0;
  870. cleanup:
  871. kfree(filter);
  872. return r;
  873. }