Handle USB Disconnect Safely While I/O Is in Flight
Make a Linux 6.12 USB driver survive unplug during reads and writes with kref, an io_mutex, a disconnect flag, usb_poison_urb and anchored URB cancellation.

Users unplug USB devices whenever they like, and the driver finds out only when the core calls disconnect. At that moment a thread may be blocked in read(), another may be inside a usb_bulk_msg() call, and URBs may be queued in the controller. A driver that frees its structure in disconnect while any of those is alive crashes, and the crash is rare and hard to reproduce. This post shows the pattern the kernel's own usb-skeleton.c uses on Linux 6.12: a reference count on the device structure, a mutex that serializes I/O against disconnect, a state flag, and URB cancellation that also blocks new submissions. It builds on asynchronous URBs.
The skeleton is in drivers/usb/usb-skeleton.c of the kernel tree, and the cancellation calls are documented in the URB guide.
The three races
Disconnect races with I/O in three distinct ways, and each needs its own defense.
The first is a use after free of the driver structure. A user process holds an open file descriptor to the device node. The device is unplugged, disconnect runs and frees the structure, and the process then calls read() on a descriptor whose private data now points at freed memory. The file lives longer than the device. The defense is a reference count: the open file holds a reference, and the structure is freed only when the last one goes.
The second is a submission after disconnect. Thread A is about to call usb_submit_urb() while thread B runs disconnect and cancels the URBs. If A submits after the cancel, a URB is in flight against a dead device, and its completion arrives after the structure is freed. The defense is to make the cancel a poison, so later submissions fail by themselves.
The third is a synchronous call that never returns. A thread waits inside usb_bulk_msg(). The device vanishes, but the core completes the URB with -ESHUTDOWN, so the call returns an error. That race is harmless on its own. It matters because the thread then continues into your code, and if your code uses the interface pointer it must know it is gone.
The structure
Keep the lifetime state in one place:
#include <linux/module.h>
#include <linux/kref.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include <linux/usb.h>
struct sample {
struct usb_device *udev;
struct usb_interface *interface; /* NULL after disconnect */
struct usb_anchor submitted;
struct mutex io_mutex; /* serializes I/O and disconnect */
struct kref kref;
unsigned int out_pipe;
};
#define to_sample(d) container_of(d, struct sample, kref)
static void sample_delete(struct kref *kref)
{
struct sample *s = to_sample(kref);
usb_put_dev(s->udev);
kfree(s);
}interface doubles as the "is the device still there" flag. It is set in probe and cleared to NULL in disconnect while holding io_mutex, so any code that holds the mutex can test it and know the answer will not change underneath.
The reference count starts at one in probe, which is the reference owned by the interface itself. Each open() adds one with kref_get(), each release() drops one with kref_put(), and disconnect drops the interface's own reference. Whoever drops the last one runs sample_delete().
Guarding every I/O path
Every function that talks to the device takes io_mutex and checks the flag first:
static int sample_send(struct sample *s, const void *data, int len)
{
void *buf;
int actual, ret;
buf = kmemdup(data, len, GFP_KERNEL);
if (!buf)
return -ENOMEM;
mutex_lock(&s->io_mutex);
if (!s->interface) {
ret = -ENODEV;
goto out;
}
ret = usb_bulk_msg(s->udev, s->out_pipe, buf, len, &actual, 1000);
if (!ret)
ret = actual;
out:
mutex_unlock(&s->io_mutex);
kfree(buf);
return ret;
}A caller that arrives after the unplug gets -ENODEV and no USB call is made. A caller already inside usb_bulk_msg() holds the mutex, so disconnect waits for it. The synchronous call returns promptly, because the core fails the URB with -ESHUTDOWN when the device is removed, so disconnect is not delayed for long.
This is the reason a blocking function must have a finite timeout. A call with a timeout of zero on a device that merely stopped answering, without being unplugged, would hold the mutex indefinitely and stall disconnect for as long as it lasts.
The disconnect function
static void sample_disconnect(struct usb_interface *interface)
{
struct sample *s = usb_get_intfdata(interface);
usb_set_intfdata(interface, NULL);
mutex_lock(&s->io_mutex);
s->interface = NULL;
mutex_unlock(&s->io_mutex);
usb_kill_anchored_urbs(&s->submitted);
kref_put(&s->kref, sample_delete);
dev_info(&interface->dev, "disconnected\n");
}The order is deliberate. Clearing interface under the mutex first means no new I/O starts, and any I/O already in progress has finished by the time the mutex is acquired. Then the asynchronous URBs are killed, with the guarantee that their handlers have returned afterwards. Only then is the interface's reference dropped.
For drivers that submit URBs from several places, replace the kill with a poison:
usb_poison_anchored_urbs(&s->submitted);A poisoned anchor makes every later usb_submit_urb() on a URB attached to it fail with -EPERM, so a thread that raced past the flag check cannot sneak a new request in. If the device may be reset or reconnected, call usb_unpoison_anchored_urbs() when the driver starts using it again, as the skeleton does in resume.
The asynchronous side
A completion handler runs in interrupt context and cannot take the mutex. It must treat a cancel or shutdown status as the signal to stop, with no touch of the interface pointer:
static void sample_write_done(struct urb *urb)
{
struct sample *s = urb->context;
if (urb->status && urb->status != -ENOENT &&
urb->status != -ECONNRESET && urb->status != -ESHUTDOWN)
dev_dbg(&s->udev->dev, "write error %d\n", urb->status);
usb_free_coherent(urb->dev, urb->transfer_buffer_length,
urb->transfer_buffer, urb->transfer_dma);
}It uses s->udev, which is valid because the driver structure's reference on the device is held until the last kref_put(). It does not use s->interface, because that pointer may already be NULL. This distinction, "the device structure outlives disconnect, the interface pointer does not", is the single most useful rule in hotplug code.
What the user sees
With the pattern in place, a process writing to the device when the cable is pulled gets a clean error, and the log is orderly:
usb 1-2: USB disconnect, device number 7
sample_hotplug 1-2:1.0: disconnectedThe write call in user space returns -1 with errno set to ENODEV, and the next call on the same descriptor returns the same, which is the contract programs expect. A close() afterwards releases the last reference and the memory is freed then, which can be well after the disconnected line if a process keeps the file open.
Suspend, reset and the same rules
The same dangers appear on suspend and on usb_reset_device(), where the core calls your pre_reset and post_reset callbacks. In those, take io_mutex in pre_reset and release it in post_reset, so no I/O overlaps a reset. For suspend, kill the anchored URBs but do not poison them, since the device will return. Treat the three events as one class of problem: "the device stops accepting requests for a while, or forever, and nothing in flight may touch freed state".
Testing the unplug path
A driver that has never been tested with an unplug during I/O has a bug in it. Two ways to provoke it without hardware to yank: write to the interface's unbind file while a dd loop is writing to the node, or load the driver on a gadget you control and remove the gadget with the configfs teardown from the gadget post. Kernel debugging options such as CONFIG_KASAN and CONFIG_DEBUG_ATOMIC_SLEEP make the failures loud: a use after free is reported at the access, and a sleeping call in a handler is reported where it happens.


