From 7493fc3bb233bd7a475608921f6cb8f130b689c2 Mon Sep 17 00:00:00 2001 From: Udipto Goswami Date: Mon, 14 Oct 2024 21:28:06 +0530 Subject: [PATCH] ANDROID: usb: gadget: android_f_accessory: Assign NULL on misc_register failure Currently, misc_register fails in acc_init, leading to an error condition that calls kfree for acc_dev. However, the composite driver calls android_acc_disconnect regardless of whether acc_init was successful or not. Since the accessory driver uses acc_dev_instance as a global pointer, android_acc_disconnect proceeds with a stale dev variable if acc_dev_instance is not NULL. This results in an after-free error when accessing the kref of dev. To fix this, assign acc_dev_instance to NULL. This ensures that when get_acc_dev is called, the NULL check prevents the extraction of the kref from a stale dev variable. Also protect the failure path with acc_dev_instance_lock since multiple threads could try to access the acc_dev_instance. Bug: 373331241 Change-Id: Ib8512bd8855f40c99c844b56c58f69d8d3c9ee94 Signed-off-by: Udipto Goswami --- drivers/usb/gadget/function/android_f_accessory.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/drivers/usb/gadget/function/android_f_accessory.c b/drivers/usb/gadget/function/android_f_accessory.c index 44653667a6ca..e87984222608 100644 --- a/drivers/usb/gadget/function/android_f_accessory.c +++ b/drivers/usb/gadget/function/android_f_accessory.c @@ -1290,6 +1290,14 @@ static int acc_init(void) return 0; err_free_dev: + /* + * Multiple threads might try to access the acc_dev_instance + * therefore protect the failure path with spinlock to avoid race + * conditions. + */ + spin_lock_irqsave(&acc_dev_instance_lock, flags); + acc_dev_instance = NULL; + spin_unlock_irqrestore(&acc_dev_instance_lock, flags); kfree(dev); pr_err("USB accessory gadget driver failed to initialize\n"); return ret;