Handle the case of vCPU addition and/or APIC enabling during the APIC map recalculations. Check the sanity of x2APIC ID in !x2apic_format && apic_x2apic_mode() case. kvm_recalculate_apic_map() creates the APIC map iterating over the list of vCPUs twice. First to find the max APIC ID and allocate a max-sized buffer, then again, calling kvm_recalculate_phys_map() for each vCPU. This opens a race window: value of max APIC ID can increase _after_ the buffer was allocated. Signed-off-by: Michal Luczaj <mhal@xxxxxxx> --- arch/x86/kvm/lapic.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/arch/x86/kvm/lapic.c b/arch/x86/kvm/lapic.c index e542cf285b51..39b9a318d04c 100644 --- a/arch/x86/kvm/lapic.c +++ b/arch/x86/kvm/lapic.c @@ -265,10 +265,14 @@ static int kvm_recalculate_phys_map(struct kvm_apic_map *new, * mapped, i.e. is aliased to multiple vCPUs. The optimized * map requires a strict 1:1 mapping between IDs and vCPUs. */ - if (apic_x2apic_mode(apic)) + if (apic_x2apic_mode(apic)) { + if (x2apic_id > new->max_apic_id) + return -EINVAL; + physical_id = x2apic_id; - else + } else { physical_id = xapic_id; + } if (new->phys_map[physical_id]) return -EINVAL; -- 2.40.1