Asynchronous USB I/O With URBs and Completion Handlers
Queue several bulk URBs from a Linux 6.12 driver, limit how many are in flight, and handle completions in atomic context without leaking memory.

usb_bulk_msg() is easy to write and slow to use: one transfer, one blocked thread, an idle bus between calls. A driver that streams data, such as a capture device, a fast serial adapter or a firmware uploader, keeps several URBs (USB request blocks) queued at once so the host controller always has the next transfer ready. This post builds that pattern on Linux 6.12 for a bulk OUT write path and a bulk IN read stream. It covers the URB life cycle, how to bound the number in flight, what a completion handler may and may not do, and how to cancel everything on disconnect. It assumes the bulk transfer post and the driver skeleton.
The reference is the kernel's USB request block documentation and drivers/usb/usb-skeleton.c in the source tree.
The life cycle of a URB
A URB is a request you hand to the USB core. It moves through a fixed sequence, and each step has a call:
| Step | Call | Notes |
|---|---|---|
| Allocate | usb_alloc_urb(0, flags) | The zero is the number of isochronous packets |
| Fill | usb_fill_bulk_urb() | Sets device, pipe, buffer, length, completion and context |
| Submit | usb_submit_urb(urb, flags) | Returns at once; the transfer runs in the background |
| Complete | the completion handler | Called by the core, in atomic context |
| Reuse or free | usb_free_urb(urb) | Drops the last reference |
usb_submit_urb() returns zero when the request was queued and an errno when it was refused. A zero does not mean the transfer worked. The result arrives later in urb->status, inside the completion handler. A submitted URB belongs to the core until the handler runs, so you must not touch its buffer or fields in between.
The flags argument is a memory allocation flag, because the core may allocate while queuing. Use GFP_KERNEL from process context and GFP_ATOMIC from a completion handler, a tasklet or while holding a spinlock.
The completion handler's rules
The handler is called in interrupt context, from the host controller driver. That sets the constraints:
It must not sleep. No mutexes, no
GFP_KERNEL, nousb_kill_urb(), no synchronous USB calls.It should be short. Heavy work goes to a workqueue.
It always runs, once per submission, including after an error or a cancel. That is what lets you count completions and free resources exactly once.
It receives
urb->context, the pointer you set when filling the URB, and usually that is your device structure.
Check urb->status first and urb->actual_length second. The status values -ECONNRESET, -ENOENT and -ESHUTDOWN mean the URB was cancelled or the device is gone, and the handler must release resources and return without resubmitting.
A bounded write path
The danger in a write path is unbounded queuing. If user space writes faster than the device accepts, a naive driver allocates a URB per write forever and the machine runs out of memory. The usual remedy is a counting semaphore that limits the transfers in flight, taken before submit and released in the completion.
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/semaphore.h>
#include <linux/usb.h>
#define SAMPLE_MAX_WRITES 8
struct sample {
struct usb_device *udev;
struct usb_interface *intf;
unsigned int out_pipe;
struct semaphore limit;
struct usb_anchor submitted;
};
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->intf->dev, "write status %d\n", urb->status);
usb_free_coherent(urb->dev, urb->transfer_buffer_length,
urb->transfer_buffer, urb->transfer_dma);
up(&s->limit);
}
static int sample_write(struct sample *s, const void *data, size_t len)
{
struct urb *urb;
void *buf;
int ret;
if (down_interruptible(&s->limit))
return -ERESTARTSYS;
urb = usb_alloc_urb(0, GFP_KERNEL);
if (!urb) {
ret = -ENOMEM;
goto err_sem;
}
buf = usb_alloc_coherent(s->udev, len, GFP_KERNEL, &urb->transfer_dma);
if (!buf) {
ret = -ENOMEM;
goto err_urb;
}
memcpy(buf, data, len);
usb_fill_bulk_urb(urb, s->udev, s->out_pipe, buf, len,
sample_write_done, s);
urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
usb_anchor_urb(urb, &s->submitted);
ret = usb_submit_urb(urb, GFP_KERNEL);
if (ret) {
usb_unanchor_urb(urb);
usb_free_coherent(s->udev, len, buf, urb->transfer_dma);
goto err_urb;
}
usb_free_urb(urb); /* the core keeps its own reference until completion */
return 0;
err_urb:
usb_free_urb(urb);
err_sem:
up(&s->limit);
return ret;
}Initialization happens in probe:
sema_init(&s->limit, SAMPLE_MAX_WRITES);
init_usb_anchor(&s->submitted);Walk through the ownership, because this is where drivers leak. The semaphore is acquired before anything is allocated, so a flood of writers blocks in down_interruptible() and cannot pile up memory. If any later step fails, the error labels release exactly what was taken. After a successful submit the code calls usb_free_urb() immediately: the URB is reference counted, and the core holds its own reference until the completion handler returns, so dropping yours right away is the standard idiom and means no one tracks the URB afterward. The buffer is freed in the handler, because only then does the controller stop touching it. The semaphore is released there too, which is what lets the next writer proceed.
With eight writes outstanding, the ninth call to sample_write() sleeps until one completion releases a slot.
The anchor
struct usb_anchor is a list head for URBs. usb_anchor_urb() adds one when you submit it, and the core removes it automatically when it completes. Its payoff is shutdown: usb_kill_anchored_urbs() cancels every URB on the anchor and waits until their handlers have returned, with no list of your own to maintain.
static void sample_disconnect_writes(struct sample *s)
{
usb_kill_anchored_urbs(&s->submitted);
}Call it from disconnect, suspend and any close that must drain. It sleeps, so it is never legal from a handler. A related call, usb_poison_anchored_urbs(), also forbids further submissions, which closes the window where a writer submits a new URB after you killed the old ones. The disconnect post covers that race in detail.
A read stream with several URBs
For input, prefill the pipeline: allocate several URBs, submit them all, and resubmit each from its handler. The device then always has a buffer waiting, which is what keeps a high-rate stream from dropping data between completions.
static void sample_read_done(struct urb *urb)
{
struct sample_rx *rx = urb->context;
int ret;
if (urb->status == -ENOENT || urb->status == -ECONNRESET ||
urb->status == -ESHUTDOWN)
return;
if (!urb->status && urb->actual_length)
sample_deliver(rx, urb->transfer_buffer, urb->actual_length);
usb_anchor_urb(urb, &rx->anchor);
ret = usb_submit_urb(urb, GFP_ATOMIC);
if (ret)
usb_unanchor_urb(urb);
}The handler delivers the data first, using actual_length and not the buffer length, then reuses the same URB and buffer. Four to eight URBs of one wMaxPacketSize multiple each is a common starting point, and the right number depends on how long your delivery path can stall. sample_deliver() is a placeholder for your own function. It must also be atomic-safe, so a typical implementation copies into a kfifo and wakes a reader.
Short transfers and zero-length packets
For OUT transfers, a message whose length is an exact multiple of wMaxPacketSize is ambiguous to a device that treats a short packet as the end of a message. Set urb->transfer_flags |= URB_ZERO_PACKET and the core appends a zero-length packet to mark the end. Skip the flag when the protocol carries the length inside the data, since an extra empty packet can confuse a device that does not expect it.
Errors worth handling
-EPIPE on an asynchronous URB is a stall. Clearing it with usb_clear_halt() sleeps, so a handler cannot do it. Record the stall and queue work to a workqueue that clears it and resubmits. -EPROTO, -EILSEQ and -ETIME are bus errors on one transfer, and for streams the common reaction is to resubmit and count them, and to give up on the device after a threshold. -EOVERFLOW means the buffer was smaller than the data.


