File descriptors referencing the /dev/hidgN device created by the HID gadget can outlive the underlying gadget function, which creates easy to trigger use-after-frees in the kernel. A simple reproduction for this using the libusbgx example programs is: $ gadget-hid $ exec 3<> /dev/hidg0 $ gadget-vid-pid-remove $ exec 3<&- Closing the file descriptor on the last line triggers a use-after-free which can be seen immediately with slub_debug=P. This series fixes this by making the struct cdev associated with the module rather than dynamically allocated for the gadget and changing struct f_hidg to be refcounted instead of tied to the gadget lifetime. v2: - Fix compiling as a module John Keeping (6): USB: gadget: f_hid: move chardev setup to module init USB: gadget: f_hid: switch to IDR for tracking minors USB: gadget: f_hid: find f_hidg by IDR lookup on open USB: gadget: f_hid: decouple cdev from f_hidg lifetime USB: gadget: f_hid: refcount f_hidg structure USB: gadget: f_hid: return ENODEV from read/write after deletion drivers/usb/gadget/function/f_hid.c | 150 +++++++++++++++++++--------- drivers/usb/gadget/function/u_hid.h | 3 - 2 files changed, 103 insertions(+), 50 deletions(-) -- 2.23.0