Skip to content

Commit

Permalink
KVM: fix memory leak in kvm_io_bus_unregister_dev()
Browse files Browse the repository at this point in the history
when kmalloc() fails in kvm_io_bus_unregister_dev(), before removing
the bus, we should iterate over all other devices linked to it and call
kvm_iodevice_destructor() for them

Fixes: 90db104 ("KVM: kvm_io_bus_unregister_dev() should never fail")
Cc: [email protected]
Reported-and-tested-by: [email protected]
Link: https://syzkaller.appspot.com/bug?extid=f196caa45793d6374707
Signed-off-by: Rustam Kovhaev <[email protected]>
Reviewed-by: Vitaly Kuznetsov <[email protected]>
Message-Id: <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
  • Loading branch information
rustylife authored and bonzini committed Sep 11, 2020
1 parent 0f99022 commit f658866
Showing 1 changed file with 12 additions and 9 deletions.
21 changes: 12 additions & 9 deletions virt/kvm/kvm_main.c
Original file line number Diff line number Diff line change
Expand Up @@ -4332,7 +4332,7 @@ int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
void kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
struct kvm_io_device *dev)
{
int i;
int i, j;
struct kvm_io_bus *new_bus, *bus;

bus = kvm_get_bus(kvm, bus_idx);
Expand All @@ -4349,17 +4349,20 @@ void kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,

new_bus = kmalloc(struct_size(bus, range, bus->dev_count - 1),
GFP_KERNEL_ACCOUNT);
if (!new_bus) {
if (new_bus) {
memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
new_bus->dev_count--;
memcpy(new_bus->range + i, bus->range + i + 1,
(new_bus->dev_count - i) * sizeof(struct kvm_io_range));
} else {
pr_err("kvm: failed to shrink bus, removing it completely\n");
goto broken;
for (j = 0; j < bus->dev_count; j++) {
if (j == i)
continue;
kvm_iodevice_destructor(bus->range[j].dev);
}
}

memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
new_bus->dev_count--;
memcpy(new_bus->range + i, bus->range + i + 1,
(new_bus->dev_count - i) * sizeof(struct kvm_io_range));

broken:
rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
synchronize_srcu_expedited(&kvm->srcu);
kfree(bus);
Expand Down

0 comments on commit f658866

Please sign in to comment.