[PATCH] net/9p/usbg: Fix use-after-free in usb9pfs_free_func
From: Yizhou Zhao
Date: Fri May 29 2026 - 04:23:12 EST
In usb9pfs_free_func, kfree(usb9pfs) frees the entire f_usb9pfs
structure which contains the embedded usb_function member that the
parameter 'f' points to. After the kfree, the code accesses f->fi
via container_of(f->fi, struct f_usb9pfs_opts, func_inst) and later
calls usb_free_all_descriptors(f), both of which dereference the
freed memory. Since f is &usb9pfs->function, all post-kfree accesses
through f constitute use-after-free on the already-freed usb9pfs
allocation.
Move kfree(usb9pfs) to the end of the function so that all accesses
through f complete before the memory is freed.
Fixes: a3be076dc174 ("net/9p/usbg: Add new usb gadget function transport")
Reported-by: Yizhou Zhao <zhaoyz24@xxxxxxxxxxxxxxxxxxxxx>
Reported-by: Yuxiang Yang <yangyx22@xxxxxxxxxxxxxxxxxxxxx>
Reported-by: Ao Wang <wangao@xxxxxxxxxx>
Reported-by: Xuewei Feng <fengxw06@xxxxxxx>
Reported-by: Qi Li <qli01@xxxxxxxxxxxxxxx>
Reported-by: Ke Xu <xuke@xxxxxxxxxxxxxxx>
Assisted-by: GLM:GLM-5.1
Signed-off-by: Yizhou Zhao <zhaoyz24@xxxxxxxxxxxxxxxxxxxxx>
---
diff --git a/net/9p/trans_usbg.c b/net/9p/trans_usbg.c
index 1ce7033..c30ef5f 100644
--- a/net/9p/trans_usbg.c
+++ b/net/9p/trans_usbg.c
@@ -725,8 +725,6 @@ static void usb9pfs_free_func(struct usb_function *f)
struct f_usb9pfs *usb9pfs = func_to_usb9pfs(f);
struct f_usb9pfs_opts *opts;
- kfree(usb9pfs);
-
opts = container_of(f->fi, struct f_usb9pfs_opts, func_inst);
mutex_lock(&opts->lock);
@@ -734,6 +732,8 @@ static void usb9pfs_free_func(struct usb_function *f)
mutex_unlock(&opts->lock);
usb_free_all_descriptors(f);
+
+ kfree(usb9pfs);
}
static int usb9pfs_set_alt(struct usb_function *f,
--
2.43.0