Re: [PATCH v3 01/15] KVM: x86: Add a framework for enabling KVM-governed x86 features

From: Huang, Kai
Date: Tue Aug 15 2023 - 21:36:52 EST



>
> +enum kvm_governed_features {
> +#define KVM_GOVERNED_FEATURE(x) KVM_GOVERNED_##x,
> +#include "governed_features.h"
> + KVM_NR_GOVERNED_FEATURES
> +};
> +
> +static __always_inline int kvm_governed_feature_index(unsigned int x86_feature)
> +{
> + switch (x86_feature) {
> +#define KVM_GOVERNED_FEATURE(x) case x: return KVM_GOVERNED_##x;
> +#include "governed_features.h"
> + default:
> + return -1;
> + }
> +}
> +
> +static __always_inline bool kvm_is_governed_feature(unsigned int x86_feature)
> +{
> + return kvm_governed_feature_index(x86_feature) >= 0;
> +}
> +
> +static __always_inline void kvm_governed_feature_set(struct kvm_vcpu *vcpu,
> + unsigned int x86_feature)
> +{
> + BUILD_BUG_ON(!kvm_is_governed_feature(x86_feature));
> +
> + __set_bit(kvm_governed_feature_index(x86_feature),
> + vcpu->arch.governed_features.enabled);
> +}
> +
> +static __always_inline void kvm_governed_feature_check_and_set(struct kvm_vcpu *vcpu,
> + unsigned int x86_feature)
> +{
> + if (kvm_cpu_cap_has(x86_feature) && guest_cpuid_has(vcpu, x86_feature))
> + kvm_governed_feature_set(vcpu, x86_feature);
> +}
> +
> +static __always_inline bool guest_can_use(struct kvm_vcpu *vcpu,
> + unsigned int x86_feature)
> +{
> + BUILD_BUG_ON(!kvm_is_governed_feature(x86_feature));
> +
> + return test_bit(kvm_governed_feature_index(x86_feature),
> + vcpu->arch.governed_features.enabled);
> +}
> +
> #endif
> diff --git a/arch/x86/kvm/governed_features.h b/arch/x86/kvm/governed_features.h
> new file mode 100644
> index 000000000000..40ce8e6608cd
> --- /dev/null
> +++ b/arch/x86/kvm/governed_features.h
> @@ -0,0 +1,9 @@
> +/* SPDX-License-Identifier: GPL-2.0 */
> +#if !defined(KVM_GOVERNED_FEATURE) || defined(KVM_GOVERNED_X86_FEATURE)
> +BUILD_BUG()
> +#endif
> +
> +#define KVM_GOVERNED_X86_FEATURE(x) KVM_GOVERNED_FEATURE(X86_FEATURE_##x)
> +
> +#undef KVM_GOVERNED_X86_FEATURE
> +#undef KVM_GOVERNED_FEATURE

Nit:

Do you want to move the very last

#undef KVM_GOVERNED_FEATURE

out of "governed_features.h", but to the place(s) where the macro is defined?

Yes there will be multiple:

#define KVM_GOVERNED_FEATURE(x) ...
#include "governed_features.h"
#undef KVM_GOVERNED_FEATURE

But this looks clearer to me.