Skip to content

Commit e3736c3

Browse files
ereshetovarkrcmar
authored andcommitted
kvm: convert kvm.users_count from atomic_t to refcount_t
refcount_t type and corresponding API should be used instead of atomic_t when the variable is used as a reference counter. This allows to avoid accidental refcounter overflows that might lead to use-after-free situations. Signed-off-by: Elena Reshetova <elena.reshetova@intel.com> Signed-off-by: Hans Liljestrand <ishkamiel@gmail.com> Signed-off-by: Kees Cook <keescook@chromium.org> Signed-off-by: David Windsor <dwindsor@gmail.com> Signed-off-by: Radim Krčmář <rkrcmar@redhat.com>
1 parent bba82fd commit e3736c3

File tree

2 files changed

+6
-5
lines changed

2 files changed

+6
-5
lines changed

include/linux/kvm_host.h

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
#include <linux/context_tracking.h>
2727
#include <linux/irqbypass.h>
2828
#include <linux/swait.h>
29+
#include <linux/refcount.h>
2930
#include <asm/signal.h>
3031

3132
#include <linux/kvm.h>
@@ -401,7 +402,7 @@ struct kvm {
401402
#endif
402403
struct kvm_vm_stat stat;
403404
struct kvm_arch arch;
404-
atomic_t users_count;
405+
refcount_t users_count;
405406
#ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
406407
struct kvm_coalesced_mmio_ring *coalesced_mmio_ring;
407408
spinlock_t ring_lock;

virt/kvm/kvm_main.c

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -617,7 +617,7 @@ static struct kvm *kvm_create_vm(unsigned long type)
617617
mutex_init(&kvm->lock);
618618
mutex_init(&kvm->irq_lock);
619619
mutex_init(&kvm->slots_lock);
620-
atomic_set(&kvm->users_count, 1);
620+
refcount_set(&kvm->users_count, 1);
621621
INIT_LIST_HEAD(&kvm->devices);
622622

623623
r = kvm_arch_init_vm(kvm, type);
@@ -747,13 +747,13 @@ static void kvm_destroy_vm(struct kvm *kvm)
747747

748748
void kvm_get_kvm(struct kvm *kvm)
749749
{
750-
atomic_inc(&kvm->users_count);
750+
refcount_inc(&kvm->users_count);
751751
}
752752
EXPORT_SYMBOL_GPL(kvm_get_kvm);
753753

754754
void kvm_put_kvm(struct kvm *kvm)
755755
{
756-
if (atomic_dec_and_test(&kvm->users_count))
756+
if (refcount_dec_and_test(&kvm->users_count))
757757
kvm_destroy_vm(kvm);
758758
}
759759
EXPORT_SYMBOL_GPL(kvm_put_kvm);
@@ -3639,7 +3639,7 @@ static int kvm_debugfs_open(struct inode *inode, struct file *file,
36393639
* To avoid the race between open and the removal of the debugfs
36403640
* directory we test against the users count.
36413641
*/
3642-
if (!atomic_add_unless(&stat_data->kvm->users_count, 1, 0))
3642+
if (!refcount_inc_not_zero(&stat_data->kvm->users_count))
36433643
return -ENOENT;
36443644

36453645
if (simple_attr_open(inode, file, get, set, fmt)) {

0 commit comments

Comments
 (0)