1 // SPDX-License-Identifier: GPL-2.0
3 * Hyper-V Isolation VM interface with paravisor and hypervisor
9 #include <linux/bitfield.h>
10 #include <linux/hyperv.h>
11 #include <linux/types.h>
12 #include <linux/slab.h>
17 #include <asm/mem_encrypt.h>
18 #include <asm/set_memory.h>
19 #include <asm/mshyperv.h>
20 #include <asm/hypervisor.h>
22 #include <asm/io_apic.h>
23 #include <asm/realmode.h>
24 #include <asm/e820/api.h>
26 #include <uapi/asm/vmx.h>
28 #ifdef CONFIG_AMD_MEM_ENCRYPT
30 #define GHCB_USAGE_HYPERV_CALL 1
35 u64 hypercalldata[509];
44 u32 countofelements : 12;
46 u32 repstartindex : 12;
55 u32 elementsprocessed : 12;
63 } __packed __aligned(HV_HYP_PAGE_SIZE);
65 /* Only used in an SNP VM with the paravisor */
66 static u16 hv_ghcb_version __ro_after_init;
68 /* Functions only used in an SNP VM with the paravisor go here. */
69 u64 hv_ghcb_hypercall(u64 control, void *input, void *output, u32 input_size)
71 union hv_ghcb *hv_ghcb;
81 local_irq_save(flags);
82 ghcb_base = (void **)this_cpu_ptr(hv_ghcb_pg);
83 hv_ghcb = (union hv_ghcb *)*ghcb_base;
85 local_irq_restore(flags);
89 hv_ghcb->ghcb.protocol_version = GHCB_PROTOCOL_MAX;
90 hv_ghcb->ghcb.ghcb_usage = GHCB_USAGE_HYPERV_CALL;
92 hv_ghcb->hypercall.outputgpa = (u64)output;
93 hv_ghcb->hypercall.hypercallinput.asuint64 = 0;
94 hv_ghcb->hypercall.hypercallinput.callcode = control;
97 memcpy(hv_ghcb->hypercall.hypercalldata, input, input_size);
101 hv_ghcb->ghcb.ghcb_usage = 0xffffffff;
102 memset(hv_ghcb->ghcb.save.valid_bitmap, 0,
103 sizeof(hv_ghcb->ghcb.save.valid_bitmap));
105 status = hv_ghcb->hypercall.hypercalloutput.callstatus;
107 local_irq_restore(flags);
112 static inline u64 rd_ghcb_msr(void)
114 return __rdmsr(MSR_AMD64_SEV_ES_GHCB);
117 static inline void wr_ghcb_msr(u64 val)
119 native_wrmsrl(MSR_AMD64_SEV_ES_GHCB, val);
122 static enum es_result hv_ghcb_hv_call(struct ghcb *ghcb, u64 exit_code,
123 u64 exit_info_1, u64 exit_info_2)
125 /* Fill in protocol and format specifiers */
126 ghcb->protocol_version = hv_ghcb_version;
127 ghcb->ghcb_usage = GHCB_DEFAULT_USAGE;
129 ghcb_set_sw_exit_code(ghcb, exit_code);
130 ghcb_set_sw_exit_info_1(ghcb, exit_info_1);
131 ghcb_set_sw_exit_info_2(ghcb, exit_info_2);
135 if (ghcb->save.sw_exit_info_1 & GENMASK_ULL(31, 0))
141 void __noreturn hv_ghcb_terminate(unsigned int set, unsigned int reason)
143 u64 val = GHCB_MSR_TERM_REQ;
145 /* Tell the hypervisor what went wrong. */
146 val |= GHCB_SEV_TERM_REASON(set, reason);
148 /* Request Guest Termination from Hypervisor */
153 asm volatile("hlt\n" : : : "memory");
156 bool hv_ghcb_negotiate_protocol(void)
161 /* Save ghcb page gpa. */
162 ghcb_gpa = rd_ghcb_msr();
164 /* Do the GHCB protocol version negotiation */
165 wr_ghcb_msr(GHCB_MSR_SEV_INFO_REQ);
169 if (GHCB_MSR_INFO(val) != GHCB_MSR_SEV_INFO_RESP)
172 if (GHCB_MSR_PROTO_MAX(val) < GHCB_PROTOCOL_MIN ||
173 GHCB_MSR_PROTO_MIN(val) > GHCB_PROTOCOL_MAX)
176 hv_ghcb_version = min_t(size_t, GHCB_MSR_PROTO_MAX(val),
179 /* Write ghcb page back after negotiating protocol. */
180 wr_ghcb_msr(ghcb_gpa);
186 static void hv_ghcb_msr_write(u64 msr, u64 value)
188 union hv_ghcb *hv_ghcb;
197 local_irq_save(flags);
198 ghcb_base = (void **)this_cpu_ptr(hv_ghcb_pg);
199 hv_ghcb = (union hv_ghcb *)*ghcb_base;
201 local_irq_restore(flags);
205 ghcb_set_rcx(&hv_ghcb->ghcb, msr);
206 ghcb_set_rax(&hv_ghcb->ghcb, lower_32_bits(value));
207 ghcb_set_rdx(&hv_ghcb->ghcb, upper_32_bits(value));
209 if (hv_ghcb_hv_call(&hv_ghcb->ghcb, SVM_EXIT_MSR, 1, 0))
210 pr_warn("Fail to write msr via ghcb %llx.\n", msr);
212 local_irq_restore(flags);
215 static void hv_ghcb_msr_read(u64 msr, u64 *value)
217 union hv_ghcb *hv_ghcb;
221 /* Check size of union hv_ghcb here. */
222 BUILD_BUG_ON(sizeof(union hv_ghcb) != HV_HYP_PAGE_SIZE);
229 local_irq_save(flags);
230 ghcb_base = (void **)this_cpu_ptr(hv_ghcb_pg);
231 hv_ghcb = (union hv_ghcb *)*ghcb_base;
233 local_irq_restore(flags);
237 ghcb_set_rcx(&hv_ghcb->ghcb, msr);
238 if (hv_ghcb_hv_call(&hv_ghcb->ghcb, SVM_EXIT_MSR, 0, 0))
239 pr_warn("Fail to read msr via ghcb %llx.\n", msr);
241 *value = (u64)lower_32_bits(hv_ghcb->ghcb.save.rax)
242 | ((u64)lower_32_bits(hv_ghcb->ghcb.save.rdx) << 32);
243 local_irq_restore(flags);
246 /* Only used in a fully enlightened SNP VM, i.e. without the paravisor */
247 static u8 ap_start_input_arg[PAGE_SIZE] __bss_decrypted __aligned(PAGE_SIZE);
248 static u8 ap_start_stack[PAGE_SIZE] __aligned(PAGE_SIZE);
249 static DEFINE_PER_CPU(struct sev_es_save_area *, hv_sev_vmsa);
251 /* Functions only used in an SNP VM without the paravisor go here. */
253 #define hv_populate_vmcb_seg(seg, gdtr_base) \
255 if (seg.selector) { \
257 seg.limit = HV_AP_SEGMENT_LIMIT; \
258 seg.attrib = *(u16 *)(gdtr_base + seg.selector + 5); \
259 seg.attrib = (seg.attrib & 0xFF) | ((seg.attrib >> 4) & 0xF00); \
263 static int snp_set_vmsa(void *va, bool vmsa)
268 * Running at VMPL0 allows the kernel to change the VMSA bit for a page
269 * using the RMPADJUST instruction. However, for the instruction to
270 * succeed it must target the permissions of a lesser privileged
271 * (higher numbered) VMPL level, so use VMPL1 (refer to the RMPADJUST
272 * instruction in the AMD64 APM Volume 3).
276 attrs |= RMPADJUST_VMSA_PAGE_BIT;
278 return rmpadjust((unsigned long)va, RMP_PG_SIZE_4K, attrs);
281 static void snp_cleanup_vmsa(struct sev_es_save_area *vmsa)
285 err = snp_set_vmsa(vmsa, false);
287 pr_err("clear VMSA page failed (%u), leaking page\n", err);
289 free_page((unsigned long)vmsa);
292 int hv_snp_boot_ap(u32 cpu, unsigned long start_ip)
294 struct sev_es_save_area *vmsa = (struct sev_es_save_area *)
295 __get_free_page(GFP_KERNEL | __GFP_ZERO);
296 struct sev_es_save_area *cur_vmsa;
297 struct desc_ptr gdtr;
299 struct hv_enable_vp_vtl *start_vp_input;
305 native_store_gdt(&gdtr);
307 vmsa->gdtr.base = gdtr.address;
308 vmsa->gdtr.limit = gdtr.size;
310 asm volatile("movl %%es, %%eax;" : "=a" (vmsa->es.selector));
311 hv_populate_vmcb_seg(vmsa->es, vmsa->gdtr.base);
313 asm volatile("movl %%cs, %%eax;" : "=a" (vmsa->cs.selector));
314 hv_populate_vmcb_seg(vmsa->cs, vmsa->gdtr.base);
316 asm volatile("movl %%ss, %%eax;" : "=a" (vmsa->ss.selector));
317 hv_populate_vmcb_seg(vmsa->ss, vmsa->gdtr.base);
319 asm volatile("movl %%ds, %%eax;" : "=a" (vmsa->ds.selector));
320 hv_populate_vmcb_seg(vmsa->ds, vmsa->gdtr.base);
322 vmsa->efer = native_read_msr(MSR_EFER);
324 vmsa->cr4 = native_read_cr4();
325 vmsa->cr3 = __native_read_cr3();
326 vmsa->cr0 = native_read_cr0();
329 vmsa->g_pat = HV_AP_INIT_GPAT_DEFAULT;
330 vmsa->rip = (u64)secondary_startup_64_no_verify;
331 vmsa->rsp = (u64)&ap_start_stack[PAGE_SIZE];
334 * Set the SNP-specific fields for this VMSA:
336 * SEV_FEATURES (matches the SEV STATUS MSR right shifted 2 bits)
339 vmsa->sev_features = sev_status >> 2;
341 ret = snp_set_vmsa(vmsa, true);
343 pr_err("RMPADJUST(%llx) failed: %llx\n", (u64)vmsa, ret);
344 free_page((u64)vmsa);
348 local_irq_save(flags);
349 start_vp_input = (struct hv_enable_vp_vtl *)ap_start_input_arg;
350 memset(start_vp_input, 0, sizeof(*start_vp_input));
351 start_vp_input->partition_id = -1;
352 start_vp_input->vp_index = cpu;
353 start_vp_input->target_vtl.target_vtl = ms_hyperv.vtl;
354 *(u64 *)&start_vp_input->vp_context = __pa(vmsa) | 1;
357 ret = hv_do_hypercall(HVCALL_START_VP,
358 start_vp_input, NULL);
359 } while (hv_result(ret) == HV_STATUS_TIME_OUT && retry--);
361 local_irq_restore(flags);
363 if (!hv_result_success(ret)) {
364 pr_err("HvCallStartVirtualProcessor failed: %llx\n", ret);
365 snp_cleanup_vmsa(vmsa);
369 cur_vmsa = per_cpu(hv_sev_vmsa, cpu);
370 /* Free up any previous VMSA page */
372 snp_cleanup_vmsa(cur_vmsa);
374 /* Record the current VMSA page */
375 per_cpu(hv_sev_vmsa, cpu) = vmsa;
381 static inline void hv_ghcb_msr_write(u64 msr, u64 value) {}
382 static inline void hv_ghcb_msr_read(u64 msr, u64 *value) {}
383 #endif /* CONFIG_AMD_MEM_ENCRYPT */
385 #ifdef CONFIG_INTEL_TDX_GUEST
386 static void hv_tdx_msr_write(u64 msr, u64 val)
388 struct tdx_module_args args = {
389 .r10 = TDX_HYPERCALL_STANDARD,
390 .r11 = EXIT_REASON_MSR_WRITE,
395 u64 ret = __tdx_hypercall(&args);
397 WARN_ONCE(ret, "Failed to emulate MSR write: %lld\n", ret);
400 static void hv_tdx_msr_read(u64 msr, u64 *val)
402 struct tdx_module_args args = {
403 .r10 = TDX_HYPERCALL_STANDARD,
404 .r11 = EXIT_REASON_MSR_READ,
408 u64 ret = __tdx_hypercall(&args);
410 if (WARN_ONCE(ret, "Failed to emulate MSR read: %lld\n", ret))
416 u64 hv_tdx_hypercall(u64 control, u64 param1, u64 param2)
418 struct tdx_module_args args = { };
424 (void)__tdx_hypercall(&args);
430 static inline void hv_tdx_msr_write(u64 msr, u64 value) {}
431 static inline void hv_tdx_msr_read(u64 msr, u64 *value) {}
432 #endif /* CONFIG_INTEL_TDX_GUEST */
434 #if defined(CONFIG_AMD_MEM_ENCRYPT) || defined(CONFIG_INTEL_TDX_GUEST)
435 void hv_ivm_msr_write(u64 msr, u64 value)
437 if (!ms_hyperv.paravisor_present)
440 if (hv_isolation_type_tdx())
441 hv_tdx_msr_write(msr, value);
442 else if (hv_isolation_type_snp())
443 hv_ghcb_msr_write(msr, value);
446 void hv_ivm_msr_read(u64 msr, u64 *value)
448 if (!ms_hyperv.paravisor_present)
451 if (hv_isolation_type_tdx())
452 hv_tdx_msr_read(msr, value);
453 else if (hv_isolation_type_snp())
454 hv_ghcb_msr_read(msr, value);
458 * hv_mark_gpa_visibility - Set pages visible to host via hvcall.
460 * In Isolation VM, all guest memory is encrypted from host and guest
461 * needs to set memory visible to host via hvcall before sharing memory
464 static int hv_mark_gpa_visibility(u16 count, const u64 pfn[],
465 enum hv_mem_host_visibility visibility)
467 struct hv_gpa_range_for_visibility *input;
472 /* no-op if partition isolation is not enabled */
473 if (!hv_is_isolation_supported())
476 if (count > HV_MAX_MODIFY_GPA_REP_COUNT) {
477 pr_err("Hyper-V: GPA count:%d exceeds supported:%lu\n", count,
478 HV_MAX_MODIFY_GPA_REP_COUNT);
482 local_irq_save(flags);
483 input = *this_cpu_ptr(hyperv_pcpu_input_arg);
485 if (unlikely(!input)) {
486 local_irq_restore(flags);
490 input->partition_id = HV_PARTITION_ID_SELF;
491 input->host_visibility = visibility;
492 input->reserved0 = 0;
493 input->reserved1 = 0;
494 memcpy((void *)input->gpa_page_list, pfn, count * sizeof(*pfn));
495 hv_status = hv_do_rep_hypercall(
496 HVCALL_MODIFY_SPARSE_GPA_PAGE_HOST_VISIBILITY, count,
497 0, input, &pages_processed);
498 local_irq_restore(flags);
500 if (hv_result_success(hv_status))
507 * When transitioning memory between encrypted and decrypted, the caller
508 * of set_memory_encrypted() or set_memory_decrypted() is responsible for
509 * ensuring that the memory isn't in use and isn't referenced while the
510 * transition is in progress. The transition has multiple steps, and the
511 * memory is in an inconsistent state until all steps are complete. A
512 * reference while the state is inconsistent could result in an exception
513 * that can't be cleanly fixed up.
515 * But the Linux kernel load_unaligned_zeropad() mechanism could cause a
516 * stray reference that can't be prevented by the caller, so Linux has
517 * specific code to handle this case. But when the #VC and #VE exceptions
518 * routed to a paravisor, the specific code doesn't work. To avoid this
519 * problem, mark the pages as "not present" while the transition is in
520 * progress. If load_unaligned_zeropad() causes a stray reference, a normal
521 * page fault is generated instead of #VC or #VE, and the page-fault-based
522 * handlers for load_unaligned_zeropad() resolve the reference. When the
523 * transition is complete, hv_vtom_set_host_visibility() marks the pages
524 * as "present" again.
526 static int hv_vtom_clear_present(unsigned long kbuffer, int pagecount, bool enc)
528 return set_memory_np(kbuffer, pagecount);
532 * hv_vtom_set_host_visibility - Set specified memory visible to host.
534 * In Isolation VM, all guest memory is encrypted from host and guest
535 * needs to set memory visible to host via hvcall before sharing memory
536 * with host. This function works as wrap of hv_mark_gpa_visibility()
537 * with memory base and size.
539 static int hv_vtom_set_host_visibility(unsigned long kbuffer, int pagecount, bool enc)
541 enum hv_mem_host_visibility visibility = enc ?
542 VMBUS_PAGE_NOT_VISIBLE : VMBUS_PAGE_VISIBLE_READ_WRITE;
549 pfn_array = kmalloc(HV_HYP_PAGE_SIZE, GFP_KERNEL);
552 goto err_set_memory_p;
555 for (i = 0, pfn = 0; i < pagecount; i++) {
557 * Use slow_virt_to_phys() because the PRESENT bit has been
558 * temporarily cleared in the PTEs. slow_virt_to_phys() works
559 * without the PRESENT bit while virt_to_hvpfn() or similar
562 vaddr = (void *)kbuffer + (i * HV_HYP_PAGE_SIZE);
563 paddr = slow_virt_to_phys(vaddr);
564 pfn_array[pfn] = paddr >> HV_HYP_PAGE_SHIFT;
567 if (pfn == HV_MAX_MODIFY_GPA_REP_COUNT || i == pagecount - 1) {
568 ret = hv_mark_gpa_visibility(pfn, pfn_array,
571 goto err_free_pfn_array;
581 * Set the PTE PRESENT bits again to revert what hv_vtom_clear_present()
582 * did. Do this even if there is an error earlier in this function in
583 * order to avoid leaving the memory range in a "broken" state. Setting
584 * the PRESENT bits shouldn't fail, but return an error if it does.
586 err = set_memory_p(kbuffer, pagecount);
593 static bool hv_vtom_tlb_flush_required(bool private)
596 * Since hv_vtom_clear_present() marks the PTEs as "not present"
597 * and flushes the TLB, they can't be in the TLB. That makes the
598 * flush controlled by this function redundant, so return "false".
603 static bool hv_vtom_cache_flush_required(void)
608 static bool hv_is_private_mmio(u64 addr)
611 * Hyper-V always provides a single IO-APIC in a guest VM.
612 * When a paravisor is used, it is emulated by the paravisor
613 * in the guest context and must be mapped private.
615 if (addr >= HV_IOAPIC_BASE_ADDRESS &&
616 addr < (HV_IOAPIC_BASE_ADDRESS + PAGE_SIZE))
619 /* Same with a vTPM */
620 if (addr >= VTPM_BASE_ADDRESS &&
621 addr < (VTPM_BASE_ADDRESS + PAGE_SIZE))
627 void __init hv_vtom_init(void)
629 enum hv_isolation_type type = hv_get_isolation_type();
632 case HV_ISOLATION_TYPE_VBS:
635 * By design, a VM using vTOM doesn't see the SEV setting,
636 * so SEV initialization is bypassed and sev_status isn't set.
637 * Set it here to indicate a vTOM VM.
639 * Note: if CONFIG_AMD_MEM_ENCRYPT is not set, sev_status is
640 * defined as 0ULL, to which we can't assigned a value.
642 #ifdef CONFIG_AMD_MEM_ENCRYPT
643 case HV_ISOLATION_TYPE_SNP:
644 sev_status = MSR_AMD64_SNP_VTOM;
645 cc_vendor = CC_VENDOR_AMD;
649 case HV_ISOLATION_TYPE_TDX:
650 cc_vendor = CC_VENDOR_INTEL;
654 panic("hv_vtom_init: unsupported isolation type %d\n", type);
657 cc_set_mask(ms_hyperv.shared_gpa_boundary);
658 physical_mask &= ms_hyperv.shared_gpa_boundary - 1;
660 x86_platform.hyper.is_private_mmio = hv_is_private_mmio;
661 x86_platform.guest.enc_cache_flush_required = hv_vtom_cache_flush_required;
662 x86_platform.guest.enc_tlb_flush_required = hv_vtom_tlb_flush_required;
663 x86_platform.guest.enc_status_change_prepare = hv_vtom_clear_present;
664 x86_platform.guest.enc_status_change_finish = hv_vtom_set_host_visibility;
666 /* Set WB as the default cache mode. */
667 guest_force_mtrr_state(NULL, 0, MTRR_TYPE_WRBACK);
670 #endif /* defined(CONFIG_AMD_MEM_ENCRYPT) || defined(CONFIG_INTEL_TDX_GUEST) */
672 enum hv_isolation_type hv_get_isolation_type(void)
674 if (!(ms_hyperv.priv_high & HV_ISOLATION))
675 return HV_ISOLATION_TYPE_NONE;
676 return FIELD_GET(HV_ISOLATION_TYPE, ms_hyperv.isolation_config_b);
678 EXPORT_SYMBOL_GPL(hv_get_isolation_type);
681 * hv_is_isolation_supported - Check system runs in the Hyper-V
684 bool hv_is_isolation_supported(void)
686 if (!cpu_feature_enabled(X86_FEATURE_HYPERVISOR))
689 if (!hypervisor_is_type(X86_HYPER_MS_HYPERV))
692 return hv_get_isolation_type() != HV_ISOLATION_TYPE_NONE;
695 DEFINE_STATIC_KEY_FALSE(isolation_type_snp);
698 * hv_isolation_type_snp - Check if the system runs in an AMD SEV-SNP based
701 bool hv_isolation_type_snp(void)
703 return static_branch_unlikely(&isolation_type_snp);
706 DEFINE_STATIC_KEY_FALSE(isolation_type_tdx);
708 * hv_isolation_type_tdx - Check if the system runs in an Intel TDX based
711 bool hv_isolation_type_tdx(void)
713 return static_branch_unlikely(&isolation_type_tdx);