diff --git a/sys/amd64/amd64/machdep.c b/sys/amd64/amd64/machdep.c --- a/sys/amd64/amd64/machdep.c +++ b/sys/amd64/amd64/machdep.c @@ -1836,6 +1836,39 @@ : "cc", "memory"); } +extern const char wrmsr_early_safe_gp_handler[]; +static struct region_descriptor wrmsr_early_safe_orig_efi_idt; + +void +wrmsr_early_safe_start(void) +{ + struct region_descriptor efi_idt; + struct gate_descriptor *gpf_descr; + + sidt(&wrmsr_early_safe_orig_efi_idt); + efi_idt.rd_limit = 32 * sizeof(idt0[0]); + efi_idt.rd_base = (uintptr_t)idt0; + lidt(&efi_idt); + + gpf_descr = &idt0[IDT_GP]; + gpf_descr->gd_looffset = (uintptr_t)wrmsr_early_safe_gp_handler; + gpf_descr->gd_hioffset = (uintptr_t)wrmsr_early_safe_gp_handler >> 16; + gpf_descr->gd_selector = rcs(); + gpf_descr->gd_type = SDT_SYSTGT; + gpf_descr->gd_p = 1; +} + +void +wrmsr_early_safe_end(void) +{ + struct gate_descriptor *gpf_descr; + + lidt(&wrmsr_early_safe_orig_efi_idt); + + gpf_descr = &idt0[IDT_GP]; + memset(gpf_descr, 0, sizeof(*gpf_descr)); +} + #ifdef KDB /* diff --git a/sys/amd64/amd64/support.S b/sys/amd64/amd64/support.S --- a/sys/amd64/amd64/support.S +++ b/sys/amd64/amd64/support.S @@ -1565,6 +1565,22 @@ POP_FRAME_POINTER ret +ENTRY(wrmsr_early_safe) + movl %edi,%ecx + movl %esi,%eax + sarq $32,%rsi + movl %esi,%edx + wrmsr + xorl %eax,%eax +wrmsr_early_faulted: + ret + +ENTRY(wrmsr_early_safe_gp_handler) + addq $8,%rsp + movl $EFAULT,%eax + movq $wrmsr_early_faulted,(%rsp) + iretq + /* * void pmap_pti_pcid_invalidate(uint64_t ucr3, uint64_t kcr3); * Invalidates address space addressed by ucr3, then returns to kcr3. diff --git a/sys/amd64/include/cpufunc.h b/sys/amd64/include/cpufunc.h --- a/sys/amd64/include/cpufunc.h +++ b/sys/amd64/include/cpufunc.h @@ -572,6 +572,15 @@ return (sel); } +static __inline u_short +rcs(void) +{ + u_short sel; + + __asm __volatile("movw %%cs,%0" : "=rm" (sel)); + return (sel); +} + static __inline void load_ds(u_short sel) { diff --git a/sys/amd64/include/md_var.h b/sys/amd64/include/md_var.h --- a/sys/amd64/include/md_var.h +++ b/sys/amd64/include/md_var.h @@ -100,6 +100,10 @@ int set_fpcontext(struct thread *td, struct __mcontext *mcp, char *xfpustate, size_t xfpustate_len); +void wrmsr_early_safe_start(void); +void wrmsr_early_safe_end(void); +int wrmsr_early_safe(u_int msr, uint64_t data); + #endif /* !_MACHINE_MD_VAR_H_ */ #endif /* __i386__ */