kvm.c 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175
  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. u64 tolud = PFN_PHYS(e820__end_of_low_ram_pfn());
  770. /*
  771. * Note, hardware requires variable MTRR ranges to be power-of-2 sized
  772. * and naturally aligned. But when forcing guest MTRR state, Linux
  773. * doesn't program the forced ranges into hardware. Don't bother doing
  774. * the math to generate a technically-legal range.
  775. */
  776. struct mtrr_var_range pci_hole = {
  777. .base_lo = tolud | X86_MEMTYPE_UC,
  778. .mask_lo = (u32)(~(SZ_4G - tolud - 1)) | MTRR_PHYSMASK_V,
  779. .mask_hi = (BIT_ULL(boot_cpu_data.x86_phys_bits) - 1) >> 32,
  780. };
  781. if (cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT) &&
  782. kvm_para_has_feature(KVM_FEATURE_MIGRATION_CONTROL)) {
  783. unsigned long nr_pages;
  784. int i;
  785. pv_ops.mmu.notify_page_enc_status_changed =
  786. kvm_sev_hc_page_enc_status;
  787. /*
  788. * Reset the host's shared pages list related to kernel
  789. * specific page encryption status settings before we load a
  790. * new kernel by kexec. Reset the page encryption status
  791. * during early boot instead of just before kexec to avoid SMP
  792. * races during kvm_pv_guest_cpu_reboot().
  793. * NOTE: We cannot reset the complete shared pages list
  794. * here as we need to retain the UEFI/OVMF firmware
  795. * specific settings.
  796. */
  797. for (i = 0; i < e820_table->nr_entries; i++) {
  798. struct e820_entry *entry = &e820_table->entries[i];
  799. if (entry->type != E820_TYPE_RAM)
  800. continue;
  801. nr_pages = DIV_ROUND_UP(entry->size, PAGE_SIZE);
  802. kvm_sev_hypercall3(KVM_HC_MAP_GPA_RANGE, entry->addr,
  803. nr_pages,
  804. KVM_MAP_GPA_RANGE_ENCRYPTED | KVM_MAP_GPA_RANGE_PAGE_SZ_4K);
  805. }
  806. /*
  807. * Ensure that _bss_decrypted section is marked as decrypted in the
  808. * shared pages list.
  809. */
  810. early_set_mem_enc_dec_hypercall((unsigned long)__start_bss_decrypted,
  811. __end_bss_decrypted - __start_bss_decrypted, 0);
  812. /*
  813. * If not booted using EFI, enable Live migration support.
  814. */
  815. if (!efi_enabled(EFI_BOOT))
  816. wrmsrl(MSR_KVM_MIGRATION_CONTROL,
  817. KVM_MIGRATION_READY);
  818. }
  819. kvmclock_init();
  820. x86_platform.apic_post_init = kvm_apic_init;
  821. /*
  822. * Set WB as the default cache mode for SEV-SNP and TDX, with a single
  823. * UC range for the legacy PCI hole, e.g. so that devices that expect
  824. * to get UC/WC mappings don't get surprised with WB.
  825. */
  826. guest_force_mtrr_state(&pci_hole, 1, MTRR_TYPE_WRBACK);
  827. }
  828. #if defined(CONFIG_AMD_MEM_ENCRYPT)
  829. static void kvm_sev_es_hcall_prepare(struct ghcb *ghcb, struct pt_regs *regs)
  830. {
  831. /* RAX and CPL are already in the GHCB */
  832. ghcb_set_rbx(ghcb, regs->bx);
  833. ghcb_set_rcx(ghcb, regs->cx);
  834. ghcb_set_rdx(ghcb, regs->dx);
  835. ghcb_set_rsi(ghcb, regs->si);
  836. }
  837. static bool kvm_sev_es_hcall_finish(struct ghcb *ghcb, struct pt_regs *regs)
  838. {
  839. /* No checking of the return state needed */
  840. return true;
  841. }
  842. #endif
  843. const __initconst struct hypervisor_x86 x86_hyper_kvm = {
  844. .name = "KVM",
  845. .detect = kvm_detect,
  846. .type = X86_HYPER_KVM,
  847. .init.guest_late_init = kvm_guest_init,
  848. .init.x2apic_available = kvm_para_available,
  849. .init.msi_ext_dest_id = kvm_msi_ext_dest_id,
  850. .init.init_platform = kvm_init_platform,
  851. #if defined(CONFIG_AMD_MEM_ENCRYPT)
  852. .runtime.sev_es_hcall_prepare = kvm_sev_es_hcall_prepare,
  853. .runtime.sev_es_hcall_finish = kvm_sev_es_hcall_finish,
  854. #endif
  855. };
  856. static __init int activate_jump_labels(void)
  857. {
  858. if (has_steal_clock) {
  859. static_key_slow_inc(&paravirt_steal_enabled);
  860. if (steal_acc)
  861. static_key_slow_inc(&paravirt_steal_rq_enabled);
  862. }
  863. return 0;
  864. }
  865. arch_initcall(activate_jump_labels);
  866. #ifdef CONFIG_PARAVIRT_SPINLOCKS
  867. /* Kick a cpu by its apicid. Used to wake up a halted vcpu */
  868. static void kvm_kick_cpu(int cpu)
  869. {
  870. unsigned long flags = 0;
  871. u32 apicid;
  872. apicid = per_cpu(x86_cpu_to_apicid, cpu);
  873. kvm_hypercall2(KVM_HC_KICK_CPU, flags, apicid);
  874. }
  875. #include <asm/qspinlock.h>
  876. static void kvm_wait(u8 *ptr, u8 val)
  877. {
  878. if (in_nmi())
  879. return;
  880. /*
  881. * halt until it's our turn and kicked. Note that we do safe halt
  882. * for irq enabled case to avoid hang when lock info is overwritten
  883. * in irq spinlock slowpath and no spurious interrupt occur to save us.
  884. */
  885. if (irqs_disabled()) {
  886. if (READ_ONCE(*ptr) == val)
  887. halt();
  888. } else {
  889. local_irq_disable();
  890. /* safe_halt() will enable IRQ */
  891. if (READ_ONCE(*ptr) == val)
  892. safe_halt();
  893. else
  894. local_irq_enable();
  895. }
  896. }
  897. /*
  898. * Setup pv_lock_ops to exploit KVM_FEATURE_PV_UNHALT if present.
  899. */
  900. void __init kvm_spinlock_init(void)
  901. {
  902. /*
  903. * In case host doesn't support KVM_FEATURE_PV_UNHALT there is still an
  904. * advantage of keeping virt_spin_lock_key enabled: virt_spin_lock() is
  905. * preferred over native qspinlock when vCPU is preempted.
  906. */
  907. if (!kvm_para_has_feature(KVM_FEATURE_PV_UNHALT)) {
  908. pr_info("PV spinlocks disabled, no host support\n");
  909. return;
  910. }
  911. /*
  912. * Disable PV spinlocks and use native qspinlock when dedicated pCPUs
  913. * are available.
  914. */
  915. if (kvm_para_has_hint(KVM_HINTS_REALTIME)) {
  916. pr_info("PV spinlocks disabled with KVM_HINTS_REALTIME hints\n");
  917. goto out;
  918. }
  919. if (num_possible_cpus() == 1) {
  920. pr_info("PV spinlocks disabled, single CPU\n");
  921. goto out;
  922. }
  923. if (nopvspin) {
  924. pr_info("PV spinlocks disabled, forced by \"nopvspin\" parameter\n");
  925. goto out;
  926. }
  927. pr_info("PV spinlocks enabled\n");
  928. __pv_init_lock_hash();
  929. pv_ops.lock.queued_spin_lock_slowpath = __pv_queued_spin_lock_slowpath;
  930. pv_ops.lock.queued_spin_unlock =
  931. PV_CALLEE_SAVE(__pv_queued_spin_unlock);
  932. pv_ops.lock.wait = kvm_wait;
  933. pv_ops.lock.kick = kvm_kick_cpu;
  934. /*
  935. * When PV spinlock is enabled which is preferred over
  936. * virt_spin_lock(), virt_spin_lock_key's value is meaningless.
  937. * Just disable it anyway.
  938. */
  939. out:
  940. static_branch_disable(&virt_spin_lock_key);
  941. }
  942. #endif /* CONFIG_PARAVIRT_SPINLOCKS */
  943. #ifdef CONFIG_ARCH_CPUIDLE_HALTPOLL
  944. static void kvm_disable_host_haltpoll(void *i)
  945. {
  946. wrmsrl(MSR_KVM_POLL_CONTROL, 0);
  947. }
  948. static void kvm_enable_host_haltpoll(void *i)
  949. {
  950. wrmsrl(MSR_KVM_POLL_CONTROL, 1);
  951. }
  952. void arch_haltpoll_enable(unsigned int cpu)
  953. {
  954. if (!kvm_para_has_feature(KVM_FEATURE_POLL_CONTROL)) {
  955. pr_err_once("host does not support poll control\n");
  956. pr_err_once("host upgrade recommended\n");
  957. return;
  958. }
  959. /* Enable guest halt poll disables host halt poll */
  960. smp_call_function_single(cpu, kvm_disable_host_haltpoll, NULL, 1);
  961. }
  962. EXPORT_SYMBOL_GPL(arch_haltpoll_enable);
  963. void arch_haltpoll_disable(unsigned int cpu)
  964. {
  965. if (!kvm_para_has_feature(KVM_FEATURE_POLL_CONTROL))
  966. return;
  967. /* Disable guest halt poll enables host halt poll */
  968. smp_call_function_single(cpu, kvm_enable_host_haltpoll, NULL, 1);
  969. }
  970. EXPORT_SYMBOL_GPL(arch_haltpoll_disable);
  971. #endif