kvm.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /*
  3. * KVM paravirt_ops implementation
  4. *
  5. * Copyright (C) 2007, Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
  6. * Copyright IBM Corporation, 2007
  7. * Authors: Anthony Liguori <aliguori@us.ibm.com>
  8. */
  9. #define pr_fmt(fmt) "kvm-guest: " fmt
  10. #include <linux/context_tracking.h>
  11. #include <linux/init.h>
  12. #include <linux/irq.h>
  13. #include <linux/kernel.h>
  14. #include <linux/kvm_para.h>
  15. #include <linux/cpu.h>
  16. #include <linux/mm.h>
  17. #include <linux/highmem.h>
  18. #include <linux/hardirq.h>
  19. #include <linux/notifier.h>
  20. #include <linux/reboot.h>
  21. #include <linux/hash.h>
  22. #include <linux/sched.h>
  23. #include <linux/slab.h>
  24. #include <linux/kprobes.h>
  25. #include <linux/nmi.h>
  26. #include <linux/swait.h>
  27. #include <linux/syscore_ops.h>
  28. #include <linux/cc_platform.h>
  29. #include <linux/efi.h>
  30. #include <asm/timer.h>
  31. #include <asm/cpu.h>
  32. #include <asm/traps.h>
  33. #include <asm/desc.h>
  34. #include <asm/tlbflush.h>
  35. #include <asm/apic.h>
  36. #include <asm/apicdef.h>
  37. #include <asm/hypervisor.h>
  38. #include <asm/mtrr.h>
  39. #include <asm/tlb.h>
  40. #include <asm/cpuidle_haltpoll.h>
  41. #include <asm/ptrace.h>
  42. #include <asm/reboot.h>
  43. #include <asm/svm.h>
  44. #include <asm/e820/api.h>
  45. DEFINE_STATIC_KEY_FALSE_RO(kvm_async_pf_enabled);
  46. static int kvmapf = 1;
  47. static int __init parse_no_kvmapf(char *arg)
  48. {
  49. kvmapf = 0;
  50. return 0;
  51. }
  52. early_param("no-kvmapf", parse_no_kvmapf);
  53. static int steal_acc = 1;
  54. static int __init parse_no_stealacc(char *arg)
  55. {
  56. steal_acc = 0;
  57. return 0;
  58. }
  59. early_param("no-steal-acc", parse_no_stealacc);
  60. static DEFINE_PER_CPU_READ_MOSTLY(bool, async_pf_enabled);
  61. static DEFINE_PER_CPU_DECRYPTED(struct kvm_vcpu_pv_apf_data, apf_reason) __aligned(64);
  62. DEFINE_PER_CPU_DECRYPTED(struct kvm_steal_time, steal_time) __aligned(64) __visible;
  63. static int has_steal_clock = 0;
  64. static int has_guest_poll = 0;
  65. /*
  66. * No need for any "IO delay" on KVM
  67. */
  68. static void kvm_io_delay(void)
  69. {
  70. }
  71. #define KVM_TASK_SLEEP_HASHBITS 8
  72. #define KVM_TASK_SLEEP_HASHSIZE (1<<KVM_TASK_SLEEP_HASHBITS)
  73. struct kvm_task_sleep_node {
  74. struct hlist_node link;
  75. struct swait_queue_head wq;
  76. u32 token;
  77. int cpu;
  78. };
  79. static struct kvm_task_sleep_head {
  80. raw_spinlock_t lock;
  81. struct hlist_head list;
  82. } async_pf_sleepers[KVM_TASK_SLEEP_HASHSIZE];
  83. static struct kvm_task_sleep_node *_find_apf_task(struct kvm_task_sleep_head *b,
  84. u32 token)
  85. {
  86. struct hlist_node *p;
  87. hlist_for_each(p, &b->list) {
  88. struct kvm_task_sleep_node *n =
  89. hlist_entry(p, typeof(*n), link);
  90. if (n->token == token)
  91. return n;
  92. }
  93. return NULL;
  94. }
  95. static bool kvm_async_pf_queue_task(u32 token, struct kvm_task_sleep_node *n)
  96. {
  97. u32 key = hash_32(token, KVM_TASK_SLEEP_HASHBITS);
  98. struct kvm_task_sleep_head *b = &async_pf_sleepers[key];
  99. struct kvm_task_sleep_node *e;
  100. raw_spin_lock(&b->lock);
  101. e = _find_apf_task(b, token);
  102. if (e) {
  103. /* dummy entry exist -> wake up was delivered ahead of PF */
  104. hlist_del(&e->link);
  105. raw_spin_unlock(&b->lock);
  106. kfree(e);
  107. return false;
  108. }
  109. n->token = token;
  110. n->cpu = smp_processor_id();
  111. init_swait_queue_head(&n->wq);
  112. hlist_add_head(&n->link, &b->list);
  113. raw_spin_unlock(&b->lock);
  114. return true;
  115. }
  116. /*
  117. * kvm_async_pf_task_wait_schedule - Wait for pagefault to be handled
  118. * @token: Token to identify the sleep node entry
  119. *
  120. * Invoked from the async pagefault handling code or from the VM exit page
  121. * fault handler. In both cases RCU is watching.
  122. */
  123. void kvm_async_pf_task_wait_schedule(u32 token)
  124. {
  125. struct kvm_task_sleep_node n;
  126. DECLARE_SWAITQUEUE(wait);
  127. lockdep_assert_irqs_disabled();
  128. if (!kvm_async_pf_queue_task(token, &n))
  129. return;
  130. for (;;) {
  131. prepare_to_swait_exclusive(&n.wq, &wait, TASK_UNINTERRUPTIBLE);
  132. if (hlist_unhashed(&n.link))
  133. break;
  134. local_irq_enable();
  135. schedule();
  136. local_irq_disable();
  137. }
  138. finish_swait(&n.wq, &wait);
  139. }
  140. EXPORT_SYMBOL_GPL(kvm_async_pf_task_wait_schedule);
  141. static void apf_task_wake_one(struct kvm_task_sleep_node *n)
  142. {
  143. hlist_del_init(&n->link);
  144. if (swq_has_sleeper(&n->wq))
  145. swake_up_one(&n->wq);
  146. }
  147. static void apf_task_wake_all(void)
  148. {
  149. int i;
  150. for (i = 0; i < KVM_TASK_SLEEP_HASHSIZE; i++) {
  151. struct kvm_task_sleep_head *b = &async_pf_sleepers[i];
  152. struct kvm_task_sleep_node *n;
  153. struct hlist_node *p, *next;
  154. raw_spin_lock(&b->lock);
  155. hlist_for_each_safe(p, next, &b->list) {
  156. n = hlist_entry(p, typeof(*n), link);
  157. if (n->cpu == smp_processor_id())
  158. apf_task_wake_one(n);
  159. }
  160. raw_spin_unlock(&b->lock);
  161. }
  162. }
  163. void kvm_async_pf_task_wake(u32 token)
  164. {
  165. u32 key = hash_32(token, KVM_TASK_SLEEP_HASHBITS);
  166. struct kvm_task_sleep_head *b = &async_pf_sleepers[key];
  167. struct kvm_task_sleep_node *n, *dummy = NULL;
  168. if (token == ~0) {
  169. apf_task_wake_all();
  170. return;
  171. }
  172. again:
  173. raw_spin_lock(&b->lock);
  174. n = _find_apf_task(b, token);
  175. if (!n) {
  176. /*
  177. * Async #PF not yet handled, add a dummy entry for the token.
  178. * Allocating the token must be down outside of the raw lock
  179. * as the allocator is preemptible on PREEMPT_RT kernels.
  180. */
  181. if (!dummy) {
  182. raw_spin_unlock(&b->lock);
  183. dummy = kzalloc(sizeof(*dummy), GFP_ATOMIC);
  184. /*
  185. * Continue looping on allocation failure, eventually
  186. * the async #PF will be handled and allocating a new
  187. * node will be unnecessary.
  188. */
  189. if (!dummy)
  190. cpu_relax();
  191. /*
  192. * Recheck for async #PF completion before enqueueing
  193. * the dummy token to avoid duplicate list entries.
  194. */
  195. goto again;
  196. }
  197. dummy->token = token;
  198. dummy->cpu = smp_processor_id();
  199. init_swait_queue_head(&dummy->wq);
  200. hlist_add_head(&dummy->link, &b->list);
  201. dummy = NULL;
  202. } else {
  203. apf_task_wake_one(n);
  204. }
  205. raw_spin_unlock(&b->lock);
  206. /* A dummy token might be allocated and ultimately not used. */
  207. kfree(dummy);
  208. }
  209. EXPORT_SYMBOL_GPL(kvm_async_pf_task_wake);
  210. noinstr u32 kvm_read_and_reset_apf_flags(void)
  211. {
  212. u32 flags = 0;
  213. if (__this_cpu_read(async_pf_enabled)) {
  214. flags = __this_cpu_read(apf_reason.flags);
  215. __this_cpu_write(apf_reason.flags, 0);
  216. }
  217. return flags;
  218. }
  219. EXPORT_SYMBOL_GPL(kvm_read_and_reset_apf_flags);
  220. noinstr bool __kvm_handle_async_pf(struct pt_regs *regs, u32 token)
  221. {
  222. u32 flags = kvm_read_and_reset_apf_flags();
  223. irqentry_state_t state;
  224. if (!flags)
  225. return false;
  226. state = irqentry_enter(regs);
  227. instrumentation_begin();
  228. /*
  229. * If the host managed to inject an async #PF into an interrupt
  230. * disabled region, then die hard as this is not going to end well
  231. * and the host side is seriously broken.
  232. */
  233. if (unlikely(!(regs->flags & X86_EFLAGS_IF)))
  234. panic("Host injected async #PF in interrupt disabled region\n");
  235. if (flags & KVM_PV_REASON_PAGE_NOT_PRESENT) {
  236. if (unlikely(!(user_mode(regs))))
  237. panic("Host injected async #PF in kernel mode\n");
  238. /* Page is swapped out by the host. */
  239. kvm_async_pf_task_wait_schedule(token);
  240. } else {
  241. WARN_ONCE(1, "Unexpected async PF flags: %x\n", flags);
  242. }
  243. instrumentation_end();
  244. irqentry_exit(regs, state);
  245. return true;
  246. }
  247. DEFINE_IDTENTRY_SYSVEC(sysvec_kvm_asyncpf_interrupt)
  248. {
  249. struct pt_regs *old_regs = set_irq_regs(regs);
  250. u32 token;
  251. apic_eoi();
  252. inc_irq_stat(irq_hv_callback_count);
  253. if (__this_cpu_read(async_pf_enabled)) {
  254. token = __this_cpu_read(apf_reason.token);
  255. kvm_async_pf_task_wake(token);
  256. __this_cpu_write(apf_reason.token, 0);
  257. wrmsrl(MSR_KVM_ASYNC_PF_ACK, 1);
  258. }
  259. set_irq_regs(old_regs);
  260. }
  261. static void __init paravirt_ops_setup(void)
  262. {
  263. pv_info.name = "KVM";
  264. if (kvm_para_has_feature(KVM_FEATURE_NOP_IO_DELAY))
  265. pv_ops.cpu.io_delay = kvm_io_delay;
  266. #ifdef CONFIG_X86_IO_APIC
  267. no_timer_check = 1;
  268. #endif
  269. }
  270. static void kvm_register_steal_time(void)
  271. {
  272. int cpu = smp_processor_id();
  273. struct kvm_steal_time *st = &per_cpu(steal_time, cpu);
  274. if (!has_steal_clock)
  275. return;
  276. wrmsrl(MSR_KVM_STEAL_TIME, (slow_virt_to_phys(st) | KVM_MSR_ENABLED));
  277. pr_debug("stealtime: cpu %d, msr %llx\n", cpu,
  278. (unsigned long long) slow_virt_to_phys(st));
  279. }
  280. static DEFINE_PER_CPU_DECRYPTED(unsigned long, kvm_apic_eoi) = KVM_PV_EOI_DISABLED;
  281. static notrace __maybe_unused void kvm_guest_apic_eoi_write(void)
  282. {
  283. /**
  284. * This relies on __test_and_clear_bit to modify the memory
  285. * in a way that is atomic with respect to the local CPU.
  286. * The hypervisor only accesses this memory from the local CPU so
  287. * there's no need for lock or memory barriers.
  288. * An optimization barrier is implied in apic write.
  289. */
  290. if (__test_and_clear_bit(KVM_PV_EOI_BIT, this_cpu_ptr(&kvm_apic_eoi)))
  291. return;
  292. apic_native_eoi();
  293. }
  294. static void kvm_guest_cpu_init(void)
  295. {
  296. if (kvm_para_has_feature(KVM_FEATURE_ASYNC_PF_INT) && kvmapf) {
  297. u64 pa;
  298. WARN_ON_ONCE(!static_branch_likely(&kvm_async_pf_enabled));
  299. pa = slow_virt_to_phys(this_cpu_ptr(&apf_reason));
  300. pa |= KVM_ASYNC_PF_ENABLED | KVM_ASYNC_PF_DELIVERY_AS_INT;
  301. if (kvm_para_has_feature(KVM_FEATURE_ASYNC_PF_VMEXIT))
  302. pa |= KVM_ASYNC_PF_DELIVERY_AS_PF_VMEXIT;
  303. wrmsrl(MSR_KVM_ASYNC_PF_INT, HYPERVISOR_CALLBACK_VECTOR);
  304. wrmsrl(MSR_KVM_ASYNC_PF_EN, pa);
  305. __this_cpu_write(async_pf_enabled, true);
  306. pr_debug("setup async PF for cpu %d\n", smp_processor_id());
  307. }
  308. if (kvm_para_has_feature(KVM_FEATURE_PV_EOI)) {
  309. unsigned long pa;
  310. /* Size alignment is implied but just to make it explicit. */
  311. BUILD_BUG_ON(__alignof__(kvm_apic_eoi) < 4);
  312. __this_cpu_write(kvm_apic_eoi, 0);
  313. pa = slow_virt_to_phys(this_cpu_ptr(&kvm_apic_eoi))
  314. | KVM_MSR_ENABLED;
  315. wrmsrl(MSR_KVM_PV_EOI_EN, pa);
  316. }
  317. if (has_steal_clock)
  318. kvm_register_steal_time();
  319. }
  320. static void kvm_pv_disable_apf(void)
  321. {
  322. if (!__this_cpu_read(async_pf_enabled))
  323. return;
  324. wrmsrl(MSR_KVM_ASYNC_PF_EN, 0);
  325. __this_cpu_write(async_pf_enabled, false);
  326. pr_debug("disable async PF for cpu %d\n", smp_processor_id());
  327. }
  328. static void kvm_disable_steal_time(void)
  329. {
  330. if (!has_steal_clock)
  331. return;
  332. wrmsr(MSR_KVM_STEAL_TIME, 0, 0);
  333. }
  334. static u64 kvm_steal_clock(int cpu)
  335. {
  336. u64 steal;
  337. struct kvm_steal_time *src;
  338. int version;
  339. src = &per_cpu(steal_time, cpu);
  340. do {
  341. version = src->version;
  342. virt_rmb();
  343. steal = src->steal;
  344. virt_rmb();
  345. } while ((version & 1) || (version != src->version));
  346. return steal;
  347. }
  348. static inline void __set_percpu_decrypted(void *ptr, unsigned long size)
  349. {
  350. early_set_memory_decrypted((unsigned long) ptr, size);
  351. }
  352. /*
  353. * Iterate through all possible CPUs and map the memory region pointed
  354. * by apf_reason, steal_time and kvm_apic_eoi as decrypted at once.
  355. *
  356. * Note: we iterate through all possible CPUs to ensure that CPUs
  357. * hotplugged will have their per-cpu variable already mapped as
  358. * decrypted.
  359. */
  360. static void __init sev_map_percpu_data(void)
  361. {
  362. int cpu;
  363. if (cc_vendor != CC_VENDOR_AMD ||
  364. !cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT))
  365. return;
  366. for_each_possible_cpu(cpu) {
  367. __set_percpu_decrypted(&per_cpu(apf_reason, cpu), sizeof(apf_reason));
  368. __set_percpu_decrypted(&per_cpu(steal_time, cpu), sizeof(steal_time));
  369. __set_percpu_decrypted(&per_cpu(kvm_apic_eoi, cpu), sizeof(kvm_apic_eoi));
  370. }
  371. }
  372. static void kvm_guest_cpu_offline(bool shutdown)
  373. {
  374. kvm_disable_steal_time();
  375. if (kvm_para_has_feature(KVM_FEATURE_PV_EOI))
  376. wrmsrl(MSR_KVM_PV_EOI_EN, 0);
  377. if (kvm_para_has_feature(KVM_FEATURE_MIGRATION_CONTROL))
  378. wrmsrl(MSR_KVM_MIGRATION_CONTROL, 0);
  379. kvm_pv_disable_apf();
  380. if (!shutdown)
  381. apf_task_wake_all();
  382. kvmclock_disable();
  383. }
  384. static int kvm_cpu_online(unsigned int cpu)
  385. {
  386. unsigned long flags;
  387. local_irq_save(flags);
  388. kvm_guest_cpu_init();
  389. local_irq_restore(flags);
  390. return 0;
  391. }
  392. #ifdef CONFIG_SMP
  393. static DEFINE_PER_CPU(cpumask_var_t, __pv_cpu_mask);
  394. static bool pv_tlb_flush_supported(void)
  395. {
  396. return (kvm_para_has_feature(KVM_FEATURE_PV_TLB_FLUSH) &&
  397. !kvm_para_has_hint(KVM_HINTS_REALTIME) &&
  398. kvm_para_has_feature(KVM_FEATURE_STEAL_TIME) &&
  399. !boot_cpu_has(X86_FEATURE_MWAIT) &&
  400. (num_possible_cpus() != 1));
  401. }
  402. static bool pv_ipi_supported(void)
  403. {
  404. return (kvm_para_has_feature(KVM_FEATURE_PV_SEND_IPI) &&
  405. (num_possible_cpus() != 1));
  406. }
  407. static bool pv_sched_yield_supported(void)
  408. {
  409. return (kvm_para_has_feature(KVM_FEATURE_PV_SCHED_YIELD) &&
  410. !kvm_para_has_hint(KVM_HINTS_REALTIME) &&
  411. kvm_para_has_feature(KVM_FEATURE_STEAL_TIME) &&
  412. !boot_cpu_has(X86_FEATURE_MWAIT) &&
  413. (num_possible_cpus() != 1));
  414. }
  415. #define KVM_IPI_CLUSTER_SIZE (2 * BITS_PER_LONG)
  416. static void __send_ipi_mask(const struct cpumask *mask, int vector)
  417. {
  418. unsigned long flags;
  419. int cpu, min = 0, max = 0;
  420. #ifdef CONFIG_X86_64
  421. __uint128_t ipi_bitmap = 0;
  422. #else
  423. u64 ipi_bitmap = 0;
  424. #endif
  425. u32 apic_id, icr;
  426. long ret;
  427. if (cpumask_empty(mask))
  428. return;
  429. local_irq_save(flags);
  430. switch (vector) {
  431. default:
  432. icr = APIC_DM_FIXED | vector;
  433. break;
  434. case NMI_VECTOR:
  435. icr = APIC_DM_NMI;
  436. break;
  437. }
  438. for_each_cpu(cpu, mask) {
  439. apic_id = per_cpu(x86_cpu_to_apicid, cpu);
  440. if (!ipi_bitmap) {
  441. min = max = apic_id;
  442. } else if (apic_id < min && max - apic_id < KVM_IPI_CLUSTER_SIZE) {
  443. ipi_bitmap <<= min - apic_id;
  444. min = apic_id;
  445. } else if (apic_id > min && apic_id < min + KVM_IPI_CLUSTER_SIZE) {
  446. max = apic_id < max ? max : apic_id;
  447. } else {
  448. ret = kvm_hypercall4(KVM_HC_SEND_IPI, (unsigned long)ipi_bitmap,
  449. (unsigned long)(ipi_bitmap >> BITS_PER_LONG), min, icr);
  450. WARN_ONCE(ret < 0, "kvm-guest: failed to send PV IPI: %ld",
  451. ret);
  452. min = max = apic_id;
  453. ipi_bitmap = 0;
  454. }
  455. __set_bit(apic_id - min, (unsigned long *)&ipi_bitmap);
  456. }
  457. if (ipi_bitmap) {
  458. ret = kvm_hypercall4(KVM_HC_SEND_IPI, (unsigned long)ipi_bitmap,
  459. (unsigned long)(ipi_bitmap >> BITS_PER_LONG), min, icr);
  460. WARN_ONCE(ret < 0, "kvm-guest: failed to send PV IPI: %ld",
  461. ret);
  462. }
  463. local_irq_restore(flags);
  464. }
  465. static void kvm_send_ipi_mask(const struct cpumask *mask, int vector)
  466. {
  467. __send_ipi_mask(mask, vector);
  468. }
  469. static void kvm_send_ipi_mask_allbutself(const struct cpumask *mask, int vector)
  470. {
  471. unsigned int this_cpu = smp_processor_id();
  472. struct cpumask *new_mask = this_cpu_cpumask_var_ptr(__pv_cpu_mask);
  473. const struct cpumask *local_mask;
  474. cpumask_copy(new_mask, mask);
  475. cpumask_clear_cpu(this_cpu, new_mask);
  476. local_mask = new_mask;
  477. __send_ipi_mask(local_mask, vector);
  478. }
  479. static int __init setup_efi_kvm_sev_migration(void)
  480. {
  481. efi_char16_t efi_sev_live_migration_enabled[] = L"SevLiveMigrationEnabled";
  482. efi_guid_t efi_variable_guid = AMD_SEV_MEM_ENCRYPT_GUID;
  483. efi_status_t status;
  484. unsigned long size;
  485. bool enabled;
  486. if (!cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT) ||
  487. !kvm_para_has_feature(KVM_FEATURE_MIGRATION_CONTROL))
  488. return 0;
  489. if (!efi_enabled(EFI_BOOT))
  490. return 0;
  491. if (!efi_enabled(EFI_RUNTIME_SERVICES)) {
  492. pr_info("%s : EFI runtime services are not enabled\n", __func__);
  493. return 0;
  494. }
  495. size = sizeof(enabled);
  496. /* Get variable contents into buffer */
  497. status = efi.get_variable(efi_sev_live_migration_enabled,
  498. &efi_variable_guid, NULL, &size, &enabled);
  499. if (status == EFI_NOT_FOUND) {
  500. pr_info("%s : EFI live migration variable not found\n", __func__);
  501. return 0;
  502. }
  503. if (status != EFI_SUCCESS) {
  504. pr_info("%s : EFI variable retrieval failed\n", __func__);
  505. return 0;
  506. }
  507. if (enabled == 0) {
  508. pr_info("%s: live migration disabled in EFI\n", __func__);
  509. return 0;
  510. }
  511. pr_info("%s : live migration enabled in EFI\n", __func__);
  512. wrmsrl(MSR_KVM_MIGRATION_CONTROL, KVM_MIGRATION_READY);
  513. return 1;
  514. }
  515. late_initcall(setup_efi_kvm_sev_migration);
  516. /*
  517. * Set the IPI entry points
  518. */
  519. static __init void kvm_setup_pv_ipi(void)
  520. {
  521. apic_update_callback(send_IPI_mask, kvm_send_ipi_mask);
  522. apic_update_callback(send_IPI_mask_allbutself, kvm_send_ipi_mask_allbutself);
  523. pr_info("setup PV IPIs\n");
  524. }
  525. static void kvm_smp_send_call_func_ipi(const struct cpumask *mask)
  526. {
  527. int cpu;
  528. native_send_call_func_ipi(mask);
  529. /* Make sure other vCPUs get a chance to run if they need to. */
  530. for_each_cpu(cpu, mask) {
  531. if (!idle_cpu(cpu) && vcpu_is_preempted(cpu)) {
  532. kvm_hypercall1(KVM_HC_SCHED_YIELD, per_cpu(x86_cpu_to_apicid, cpu));
  533. break;
  534. }
  535. }
  536. }
  537. static void kvm_flush_tlb_multi(const struct cpumask *cpumask,
  538. const struct flush_tlb_info *info)
  539. {
  540. u8 state;
  541. int cpu;
  542. struct kvm_steal_time *src;
  543. struct cpumask *flushmask = this_cpu_cpumask_var_ptr(__pv_cpu_mask);
  544. cpumask_copy(flushmask, cpumask);
  545. /*
  546. * We have to call flush only on online vCPUs. And
  547. * queue flush_on_enter for pre-empted vCPUs
  548. */
  549. for_each_cpu(cpu, flushmask) {
  550. /*
  551. * The local vCPU is never preempted, so we do not explicitly
  552. * skip check for local vCPU - it will never be cleared from
  553. * flushmask.
  554. */
  555. src = &per_cpu(steal_time, cpu);
  556. state = READ_ONCE(src->preempted);
  557. if ((state & KVM_VCPU_PREEMPTED)) {
  558. if (try_cmpxchg(&src->preempted, &state,
  559. state | KVM_VCPU_FLUSH_TLB))
  560. __cpumask_clear_cpu(cpu, flushmask);
  561. }
  562. }
  563. native_flush_tlb_multi(flushmask, info);
  564. }
  565. static __init int kvm_alloc_cpumask(void)
  566. {
  567. int cpu;
  568. if (!kvm_para_available() || nopv)
  569. return 0;
  570. if (pv_tlb_flush_supported() || pv_ipi_supported())
  571. for_each_possible_cpu(cpu) {
  572. zalloc_cpumask_var_node(per_cpu_ptr(&__pv_cpu_mask, cpu),
  573. GFP_KERNEL, cpu_to_node(cpu));
  574. }
  575. return 0;
  576. }
  577. arch_initcall(kvm_alloc_cpumask);
  578. static void __init kvm_smp_prepare_boot_cpu(void)
  579. {
  580. /*
  581. * Map the per-cpu variables as decrypted before kvm_guest_cpu_init()
  582. * shares the guest physical address with the hypervisor.
  583. */
  584. sev_map_percpu_data();
  585. kvm_guest_cpu_init();
  586. native_smp_prepare_boot_cpu();
  587. kvm_spinlock_init();
  588. }
  589. static int kvm_cpu_down_prepare(unsigned int cpu)
  590. {
  591. unsigned long flags;
  592. local_irq_save(flags);
  593. kvm_guest_cpu_offline(false);
  594. local_irq_restore(flags);
  595. return 0;
  596. }
  597. #endif
  598. static int kvm_suspend(void)
  599. {
  600. u64 val = 0;
  601. kvm_guest_cpu_offline(false);
  602. #ifdef CONFIG_ARCH_CPUIDLE_HALTPOLL
  603. if (kvm_para_has_feature(KVM_FEATURE_POLL_CONTROL))
  604. rdmsrl(MSR_KVM_POLL_CONTROL, val);
  605. has_guest_poll = !(val & 1);
  606. #endif
  607. return 0;
  608. }
  609. static void kvm_resume(void)
  610. {
  611. kvm_cpu_online(raw_smp_processor_id());
  612. #ifdef CONFIG_ARCH_CPUIDLE_HALTPOLL
  613. if (kvm_para_has_feature(KVM_FEATURE_POLL_CONTROL) && has_guest_poll)
  614. wrmsrl(MSR_KVM_POLL_CONTROL, 0);
  615. #endif
  616. }
  617. static struct syscore_ops kvm_syscore_ops = {
  618. .suspend = kvm_suspend,
  619. .resume = kvm_resume,
  620. };
  621. static void kvm_pv_guest_cpu_reboot(void *unused)
  622. {
  623. kvm_guest_cpu_offline(true);
  624. }
  625. static int kvm_pv_reboot_notify(struct notifier_block *nb,
  626. unsigned long code, void *unused)
  627. {
  628. if (code == SYS_RESTART)
  629. on_each_cpu(kvm_pv_guest_cpu_reboot, NULL, 1);
  630. return NOTIFY_DONE;
  631. }
  632. static struct notifier_block kvm_pv_reboot_nb = {
  633. .notifier_call = kvm_pv_reboot_notify,
  634. };
  635. /*
  636. * After a PV feature is registered, the host will keep writing to the
  637. * registered memory location. If the guest happens to shutdown, this memory
  638. * won't be valid. In cases like kexec, in which you install a new kernel, this
  639. * means a random memory location will be kept being written.
  640. */
  641. #ifdef CONFIG_CRASH_DUMP
  642. static void kvm_crash_shutdown(struct pt_regs *regs)
  643. {
  644. kvm_guest_cpu_offline(true);
  645. native_machine_crash_shutdown(regs);
  646. }
  647. #endif
  648. #if defined(CONFIG_X86_32) || !defined(CONFIG_SMP)
  649. bool __kvm_vcpu_is_preempted(long cpu);
  650. __visible bool __kvm_vcpu_is_preempted(long cpu)
  651. {
  652. struct kvm_steal_time *src = &per_cpu(steal_time, cpu);
  653. return !!(src->preempted & KVM_VCPU_PREEMPTED);
  654. }
  655. PV_CALLEE_SAVE_REGS_THUNK(__kvm_vcpu_is_preempted);
  656. #else
  657. #include <asm/asm-offsets.h>
  658. extern bool __raw_callee_save___kvm_vcpu_is_preempted(long);
  659. /*
  660. * Hand-optimize version for x86-64 to avoid 8 64-bit register saving and
  661. * restoring to/from the stack.
  662. */
  663. #define PV_VCPU_PREEMPTED_ASM \
  664. "movq __per_cpu_offset(,%rdi,8), %rax\n\t" \
  665. "cmpb $0, " __stringify(KVM_STEAL_TIME_preempted) "+steal_time(%rax)\n\t" \
  666. "setne %al\n\t"
  667. DEFINE_ASM_FUNC(__raw_callee_save___kvm_vcpu_is_preempted,
  668. PV_VCPU_PREEMPTED_ASM, .text);
  669. #endif
  670. static void __init kvm_guest_init(void)
  671. {
  672. int i;
  673. paravirt_ops_setup();
  674. register_reboot_notifier(&kvm_pv_reboot_nb);
  675. for (i = 0; i < KVM_TASK_SLEEP_HASHSIZE; i++)
  676. raw_spin_lock_init(&async_pf_sleepers[i].lock);
  677. if (kvm_para_has_feature(KVM_FEATURE_STEAL_TIME)) {
  678. has_steal_clock = 1;
  679. static_call_update(pv_steal_clock, kvm_steal_clock);
  680. pv_ops.lock.vcpu_is_preempted =
  681. PV_CALLEE_SAVE(__kvm_vcpu_is_preempted);
  682. }
  683. if (kvm_para_has_feature(KVM_FEATURE_PV_EOI))
  684. apic_update_callback(eoi, kvm_guest_apic_eoi_write);
  685. if (kvm_para_has_feature(KVM_FEATURE_ASYNC_PF_INT) && kvmapf) {
  686. static_branch_enable(&kvm_async_pf_enabled);
  687. sysvec_install(HYPERVISOR_CALLBACK_VECTOR, sysvec_kvm_asyncpf_interrupt);
  688. }
  689. #ifdef CONFIG_SMP
  690. if (pv_tlb_flush_supported()) {
  691. pv_ops.mmu.flush_tlb_multi = kvm_flush_tlb_multi;
  692. pv_ops.mmu.tlb_remove_table = tlb_remove_table;
  693. pr_info("KVM setup pv remote TLB flush\n");
  694. }
  695. smp_ops.smp_prepare_boot_cpu = kvm_smp_prepare_boot_cpu;
  696. if (pv_sched_yield_supported()) {
  697. smp_ops.send_call_func_ipi = kvm_smp_send_call_func_ipi;
  698. pr_info("setup PV sched yield\n");
  699. }
  700. if (cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN, "x86/kvm:online",
  701. kvm_cpu_online, kvm_cpu_down_prepare) < 0)
  702. pr_err("failed to install cpu hotplug callbacks\n");
  703. #else
  704. sev_map_percpu_data();
  705. kvm_guest_cpu_init();
  706. #endif
  707. #ifdef CONFIG_CRASH_DUMP
  708. machine_ops.crash_shutdown = kvm_crash_shutdown;
  709. #endif
  710. register_syscore_ops(&kvm_syscore_ops);
  711. /*
  712. * Hard lockup detection is enabled by default. Disable it, as guests
  713. * can get false positives too easily, for example if the host is
  714. * overcommitted.
  715. */
  716. hardlockup_detector_disable();
  717. }
  718. static noinline uint32_t __kvm_cpuid_base(void)
  719. {
  720. if (boot_cpu_data.cpuid_level < 0)
  721. return 0; /* So we don't blow up on old processors */
  722. if (boot_cpu_has(X86_FEATURE_HYPERVISOR))
  723. return hypervisor_cpuid_base(KVM_SIGNATURE, 0);
  724. return 0;
  725. }
  726. static inline uint32_t kvm_cpuid_base(void)
  727. {
  728. static int kvm_cpuid_base = -1;
  729. if (kvm_cpuid_base == -1)
  730. kvm_cpuid_base = __kvm_cpuid_base();
  731. return kvm_cpuid_base;
  732. }
  733. bool kvm_para_available(void)
  734. {
  735. return kvm_cpuid_base() != 0;
  736. }
  737. EXPORT_SYMBOL_GPL(kvm_para_available);
  738. unsigned int kvm_arch_para_features(void)
  739. {
  740. return cpuid_eax(kvm_cpuid_base() | KVM_CPUID_FEATURES);
  741. }
  742. unsigned int kvm_arch_para_hints(void)
  743. {
  744. return cpuid_edx(kvm_cpuid_base() | KVM_CPUID_FEATURES);
  745. }
  746. EXPORT_SYMBOL_GPL(kvm_arch_para_hints);
  747. static uint32_t __init kvm_detect(void)
  748. {
  749. return kvm_cpuid_base();
  750. }
  751. static void __init kvm_apic_init(void)
  752. {
  753. #ifdef CONFIG_SMP
  754. if (pv_ipi_supported())
  755. kvm_setup_pv_ipi();
  756. #endif
  757. }
  758. static bool __init kvm_msi_ext_dest_id(void)
  759. {
  760. return kvm_para_has_feature(KVM_FEATURE_MSI_EXT_DEST_ID);
  761. }
  762. static void kvm_sev_hc_page_enc_status(unsigned long pfn, int npages, bool enc)
  763. {
  764. kvm_sev_hypercall3(KVM_HC_MAP_GPA_RANGE, pfn << PAGE_SHIFT, npages,
  765. KVM_MAP_GPA_RANGE_ENC_STAT(enc) | KVM_MAP_GPA_RANGE_PAGE_SZ_4K);
  766. }
  767. static void __init kvm_init_platform(void)
  768. {
  769. if (cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT) &&
  770. kvm_para_has_feature(KVM_FEATURE_MIGRATION_CONTROL)) {
  771. unsigned long nr_pages;
  772. int i;
  773. pv_ops.mmu.notify_page_enc_status_changed =
  774. kvm_sev_hc_page_enc_status;
  775. /*
  776. * Reset the host's shared pages list related to kernel
  777. * specific page encryption status settings before we load a
  778. * new kernel by kexec. Reset the page encryption status
  779. * during early boot instead of just before kexec to avoid SMP
  780. * races during kvm_pv_guest_cpu_reboot().
  781. * NOTE: We cannot reset the complete shared pages list
  782. * here as we need to retain the UEFI/OVMF firmware
  783. * specific settings.
  784. */
  785. for (i = 0; i < e820_table->nr_entries; i++) {
  786. struct e820_entry *entry = &e820_table->entries[i];
  787. if (entry->type != E820_TYPE_RAM)
  788. continue;
  789. nr_pages = DIV_ROUND_UP(entry->size, PAGE_SIZE);
  790. kvm_sev_hypercall3(KVM_HC_MAP_GPA_RANGE, entry->addr,
  791. nr_pages,
  792. KVM_MAP_GPA_RANGE_ENCRYPTED | KVM_MAP_GPA_RANGE_PAGE_SZ_4K);
  793. }
  794. /*
  795. * Ensure that _bss_decrypted section is marked as decrypted in the
  796. * shared pages list.
  797. */
  798. early_set_mem_enc_dec_hypercall((unsigned long)__start_bss_decrypted,
  799. __end_bss_decrypted - __start_bss_decrypted, 0);
  800. /*
  801. * If not booted using EFI, enable Live migration support.
  802. */
  803. if (!efi_enabled(EFI_BOOT))
  804. wrmsrl(MSR_KVM_MIGRATION_CONTROL,
  805. KVM_MIGRATION_READY);
  806. }
  807. kvmclock_init();
  808. x86_platform.apic_post_init = kvm_apic_init;
  809. /* Set WB as the default cache mode for SEV-SNP and TDX */
  810. mtrr_overwrite_state(NULL, 0, MTRR_TYPE_WRBACK);
  811. }
  812. #if defined(CONFIG_AMD_MEM_ENCRYPT)
  813. static void kvm_sev_es_hcall_prepare(struct ghcb *ghcb, struct pt_regs *regs)
  814. {
  815. /* RAX and CPL are already in the GHCB */
  816. ghcb_set_rbx(ghcb, regs->bx);
  817. ghcb_set_rcx(ghcb, regs->cx);
  818. ghcb_set_rdx(ghcb, regs->dx);
  819. ghcb_set_rsi(ghcb, regs->si);
  820. }
  821. static bool kvm_sev_es_hcall_finish(struct ghcb *ghcb, struct pt_regs *regs)
  822. {
  823. /* No checking of the return state needed */
  824. return true;
  825. }
  826. #endif
  827. const __initconst struct hypervisor_x86 x86_hyper_kvm = {
  828. .name = "KVM",
  829. .detect = kvm_detect,
  830. .type = X86_HYPER_KVM,
  831. .init.guest_late_init = kvm_guest_init,
  832. .init.x2apic_available = kvm_para_available,
  833. .init.msi_ext_dest_id = kvm_msi_ext_dest_id,
  834. .init.init_platform = kvm_init_platform,
  835. #if defined(CONFIG_AMD_MEM_ENCRYPT)
  836. .runtime.sev_es_hcall_prepare = kvm_sev_es_hcall_prepare,
  837. .runtime.sev_es_hcall_finish = kvm_sev_es_hcall_finish,
  838. #endif
  839. };
  840. static __init int activate_jump_labels(void)
  841. {
  842. if (has_steal_clock) {
  843. static_key_slow_inc(&paravirt_steal_enabled);
  844. if (steal_acc)
  845. static_key_slow_inc(&paravirt_steal_rq_enabled);
  846. }
  847. return 0;
  848. }
  849. arch_initcall(activate_jump_labels);
  850. #ifdef CONFIG_PARAVIRT_SPINLOCKS
  851. /* Kick a cpu by its apicid. Used to wake up a halted vcpu */
  852. static void kvm_kick_cpu(int cpu)
  853. {
  854. unsigned long flags = 0;
  855. u32 apicid;
  856. apicid = per_cpu(x86_cpu_to_apicid, cpu);
  857. kvm_hypercall2(KVM_HC_KICK_CPU, flags, apicid);
  858. }
  859. #include <asm/qspinlock.h>
  860. static void kvm_wait(u8 *ptr, u8 val)
  861. {
  862. if (in_nmi())
  863. return;
  864. /*
  865. * halt until it's our turn and kicked. Note that we do safe halt
  866. * for irq enabled case to avoid hang when lock info is overwritten
  867. * in irq spinlock slowpath and no spurious interrupt occur to save us.
  868. */
  869. if (irqs_disabled()) {
  870. if (READ_ONCE(*ptr) == val)
  871. halt();
  872. } else {
  873. local_irq_disable();
  874. /* safe_halt() will enable IRQ */
  875. if (READ_ONCE(*ptr) == val)
  876. safe_halt();
  877. else
  878. local_irq_enable();
  879. }
  880. }
  881. /*
  882. * Setup pv_lock_ops to exploit KVM_FEATURE_PV_UNHALT if present.
  883. */
  884. void __init kvm_spinlock_init(void)
  885. {
  886. /*
  887. * In case host doesn't support KVM_FEATURE_PV_UNHALT there is still an
  888. * advantage of keeping virt_spin_lock_key enabled: virt_spin_lock() is
  889. * preferred over native qspinlock when vCPU is preempted.
  890. */
  891. if (!kvm_para_has_feature(KVM_FEATURE_PV_UNHALT)) {
  892. pr_info("PV spinlocks disabled, no host support\n");
  893. return;
  894. }
  895. /*
  896. * Disable PV spinlocks and use native qspinlock when dedicated pCPUs
  897. * are available.
  898. */
  899. if (kvm_para_has_hint(KVM_HINTS_REALTIME)) {
  900. pr_info("PV spinlocks disabled with KVM_HINTS_REALTIME hints\n");
  901. goto out;
  902. }
  903. if (num_possible_cpus() == 1) {
  904. pr_info("PV spinlocks disabled, single CPU\n");
  905. goto out;
  906. }
  907. if (nopvspin) {
  908. pr_info("PV spinlocks disabled, forced by \"nopvspin\" parameter\n");
  909. goto out;
  910. }
  911. pr_info("PV spinlocks enabled\n");
  912. __pv_init_lock_hash();
  913. pv_ops.lock.queued_spin_lock_slowpath = __pv_queued_spin_lock_slowpath;
  914. pv_ops.lock.queued_spin_unlock =
  915. PV_CALLEE_SAVE(__pv_queued_spin_unlock);
  916. pv_ops.lock.wait = kvm_wait;
  917. pv_ops.lock.kick = kvm_kick_cpu;
  918. /*
  919. * When PV spinlock is enabled which is preferred over
  920. * virt_spin_lock(), virt_spin_lock_key's value is meaningless.
  921. * Just disable it anyway.
  922. */
  923. out:
  924. static_branch_disable(&virt_spin_lock_key);
  925. }
  926. #endif /* CONFIG_PARAVIRT_SPINLOCKS */
  927. #ifdef CONFIG_ARCH_CPUIDLE_HALTPOLL
  928. static void kvm_disable_host_haltpoll(void *i)
  929. {
  930. wrmsrl(MSR_KVM_POLL_CONTROL, 0);
  931. }
  932. static void kvm_enable_host_haltpoll(void *i)
  933. {
  934. wrmsrl(MSR_KVM_POLL_CONTROL, 1);
  935. }
  936. void arch_haltpoll_enable(unsigned int cpu)
  937. {
  938. if (!kvm_para_has_feature(KVM_FEATURE_POLL_CONTROL)) {
  939. pr_err_once("host does not support poll control\n");
  940. pr_err_once("host upgrade recommended\n");
  941. return;
  942. }
  943. /* Enable guest halt poll disables host halt poll */
  944. smp_call_function_single(cpu, kvm_disable_host_haltpoll, NULL, 1);
  945. }
  946. EXPORT_SYMBOL_GPL(arch_haltpoll_enable);
  947. void arch_haltpoll_disable(unsigned int cpu)
  948. {
  949. if (!kvm_para_has_feature(KVM_FEATURE_POLL_CONTROL))
  950. return;
  951. /* Disable guest halt poll enables host halt poll */
  952. smp_call_function_single(cpu, kvm_enable_host_haltpoll, NULL, 1);
  953. }
  954. EXPORT_SYMBOL_GPL(arch_haltpoll_disable);
  955. #endif