Re: [PATCH v5 04/15] x86/mtrr: support setting MTRR state for software defined MTRRs

From: Huang, Kai
Date: Sun Apr 02 2023 - 22:25:48 EST


On Sat, 2023-04-01 at 08:36 +0200, Juergen Gross wrote:
> +/**
> + * mtrr_overwrite_state - set static MTRR state
> + *
> + * Used to set MTRR state via different means (e.g. with data obtained from
> + * a hypervisor).
> + * Is allowed only for special cases when running virtualized. Must be called
> + * from the x86_init.hyper.init_platform() hook.
> + */
> +void mtrr_overwrite_state(struct mtrr_var_range *var, unsigned int num_var,
> +   mtrr_type def_type)
> +{
> + unsigned int i;
> +
> + /* Only allowed to be called once before mtrr_bp_init(). */
> + if (WARN_ON(mtrr_state_set))
> + return;
> +
> + /* Only allowed when running virtualized. */
> + if (!cpu_feature_enabled(X86_FEATURE_HYPERVISOR))
> + return;
> +
> + /*
> + * Only allowed for special virtualization cases:
> + * - when running as SEV-SNP guest
> + * - when running as Hyper-V isolated guest
> + * - when running as Xen PV guest
> + * - when running as TSX guest
^
TDX guest

> + */
> + if (!cc_platform_has(CC_ATTR_GUEST_SEV_SNP) &&
> +     !hv_is_isolation_supported() &&
> +     !cpu_feature_enabled(X86_FEATURE_XENPV) &&
> +     !cpu_feature_enabled(X86_FEATURE_TDX_GUEST))
> + return;
> +
> + /* Disable MTRR in order to disable MTRR modifications. */
> + setup_clear_cpu_cap(X86_FEATURE_MTRR);
> +
> + if (var) {
> + if (num_var > MTRR_MAX_VAR_RANGES) {
> + pr_warn("Trying to overwrite MTRR state with %u variable entries\n",
> + num_var);
> + num_var = MTRR_MAX_VAR_RANGES;
> + }
> + for (i = 0; i < num_var; i++)
> + mtrr_state.var_ranges[i] = var[i];
> + num_var_ranges = num_var;
> + }
> +
> + mtrr_state.def_type = def_type;
> + mtrr_state.enabled |= MTRR_STATE_MTRR_ENABLED;
> +
> + mtrr_state_set = 1;
> +}
> +
>  /**
>   * mtrr_type_lookup - look up memory type in MTRR
>   *
> diff --git a/arch/x86/kernel/cpu/mtrr/mtrr.c b/arch/x86/kernel/cpu/mtrr/mtrr.c
> index 1beb38f7a7a3..1c19d67ddab3 100644
> --- a/arch/x86/kernel/cpu/mtrr/mtrr.c
> +++ b/arch/x86/kernel/cpu/mtrr/mtrr.c
> @@ -666,6 +666,15 @@ void __init mtrr_bp_init(void)
>   const char *why = "(not available)";
>   unsigned int phys_addr;
>  
> + if (!generic_mtrrs && mtrr_state.enabled) {
> + /* Software overwrite of MTRR state, only for generic case. */
^
!generic case?

> + mtrr_calc_physbits(true);
> + init_table();
> + pr_info("MTRRs set to read-only\n");
> +
> + return;
> + }
> +
>   phys_addr = mtrr_calc_physbits(generic_mtrrs);