Skip to content
systemcoding.dev
Kernels

Bulk Transfers in a USB Driver With usb_bulk_msg

Send and receive bulk data from a Linux 6.12 USB driver with usb_bulk_msg: pipes, DMA-safe buffers, timeouts, short transfers and how to recover from a stall.

6 min read
Summarize in AI
Flat illustration of user space above the system call boundary, the kernel and the hardware, with the Linux, C and Rust logos.

usb_bulk_msg() is the shortest path from a USB driver to data on the wire. It builds a URB, submits it, sleeps until it completes or times out, and hands back the result, all in one call. That simplicity has rules, and breaking them gives you crashes that appear only on some machines. This post uses Linux 6.12 to send a command and read a reply over a bulk pair, explains why the buffer must come from kmalloc, and shows how to handle the two failures a bulk endpoint produces in practice, a timeout and a stall. It builds on the driver skeleton.

The function is declared in include/linux/usb.h and documented in the kernel's USB core API.

The signature

c
int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe,
		 void *data, int len, int *actual_length, int timeout);

It returns zero on success and a negative errno otherwise. actual_length receives the number of bytes that really moved, which can be smaller than len, and timeout is in milliseconds. A timeout of zero means wait forever, which is almost never what you want, because a vanished device then blocks your thread until the disconnect cancels the URB.

The pipe argument packs the device, endpoint number, direction and type into one integer. You never build it by hand. Use the macros, which take the endpoint address from the descriptor:

MacroDirection
usb_sndbulkpipe(udev, epnum)Host to device (OUT)
usb_rcvbulkpipe(udev, epnum)Device to host (IN)

The epnum is the endpoint number without the direction bit, so for address 0x81 you pass 1. Passing the full address 0x81 builds a pipe for the wrong endpoint and the transfer fails with -EPIPE or a warning in the kernel log, which is a very common first bug. The helper usb_endpoint_num() extracts the number from a descriptor safely.

The buffer must be DMA-capable

The host controller reads and writes the buffer with DMA, so the memory has to be addressable that way. That rules out the stack, which can be virtually mapped, and it rules out static or global data that sits in the wrong section on some architectures. Allocate with kmalloc() or kzalloc(), and free it afterwards. With CONFIG_VMAP_STACK enabled, which is the default on most systems, a stack buffer triggers a warning at best and corrupts memory at worst.

c
buf = kmalloc(len, GFP_KERNEL);

The rule applies to every USB transfer function, including control transfers. The kernel does contain code that bounces a bad buffer, but a driver should never depend on it.

A command and a reply

This driver sends a four-byte command to a device and reads up to 64 bytes back. The endpoints are discovered once in probe, with the helper from the post on how USB works:

sample_bulk.cc
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/usb.h>

#define SAMPLE_TIMEOUT_MS	1000
#define SAMPLE_REPLY_MAX	64

struct sample {
	struct usb_device	*udev;
	unsigned int		out_pipe;
	unsigned int		in_pipe;
};

static int sample_ping(struct sample *s)
{
	static const u8 cmd[4] = { 'P', 'I', 'N', 'G' };
	u8 *buf;
	int sent, got, ret;

	buf = kmalloc(SAMPLE_REPLY_MAX, GFP_KERNEL);
	if (!buf)
		return -ENOMEM;

	memcpy(buf, cmd, sizeof(cmd));
	ret = usb_bulk_msg(s->udev, s->out_pipe, buf, sizeof(cmd),
			   &sent, SAMPLE_TIMEOUT_MS);
	if (ret) {
		dev_err(&s->udev->dev, "bulk out failed: %d\n", ret);
		goto out;
	}

	ret = usb_bulk_msg(s->udev, s->in_pipe, buf, SAMPLE_REPLY_MAX,
			   &got, SAMPLE_TIMEOUT_MS);
	if (ret) {
		dev_err(&s->udev->dev, "bulk in failed: %d\n", ret);
		goto out;
	}

	dev_info(&s->udev->dev, "sent %d bytes, got %d: %.*s\n",
		 sent, got, got, buf);
out:
	kfree(buf);
	return ret;
}

static int sample_setup(struct sample *s, struct usb_interface *intf)
{
	struct usb_endpoint_descriptor *in, *out;
	int ret;

	ret = usb_find_common_endpoints(intf->cur_altsetting,
					&in, &out, NULL, NULL);
	if (ret)
		return ret;

	s->udev = interface_to_usbdev(intf);
	s->in_pipe = usb_rcvbulkpipe(s->udev, usb_endpoint_num(in));
	s->out_pipe = usb_sndbulkpipe(s->udev, usb_endpoint_num(out));
	return 0;
}

If the device answers PONG to the four-byte PING, the log shows:

Text
usb 1-2: sent 4 bytes, got 4: PONG

Two details deserve attention. The same buffer carries the command out and the reply in, which is safe because the first call completes before the second starts. And the %.*s format prints exactly got bytes, since the buffer from the device is not guaranteed to be NUL terminated.

Context and locking

usb_bulk_msg() sleeps, so it works only in process context. Never call it from an interrupt handler, a tasklet, a timer or while holding a spinlock. A driver that needs to start a transfer from one of those contexts uses an asynchronous URB instead, which is the subject of the post on URBs and completion handlers.

Calls from several threads need your own mutex. The USB core does not serialize bulk transfers to one endpoint for you, and two threads interleaving command and reply would read each other's data.

Timeouts and short transfers

A bulk IN request for 64 bytes ends when the device sends a short packet or when 64 bytes have arrived. So got can be anything from 0 to 64, and your code must use it. Ignoring actual_length and parsing the full 64 bytes reads stale data from a previous call.

A timeout returns -ETIMEDOUT. Importantly, on a timeout the URB is cancelled, but actual_length may still report bytes that arrived before the cancel. A driver that treats the data as valid after a timeout will occasionally act on half a message. Discard it.

Bulk transfers at a given maximum packet size have a subtle length rule on IN. If you request a length that is not a multiple of wMaxPacketSize and the device sends more than you asked for, the controller reports -EOVERFLOW. For a device that returns variable-length replies, request a multiple of the packet size (512 at high speed), and let the short packet end the transfer.

Recover from a stall

A device can answer a bulk request with a STALL handshake, meaning "I cannot do this now". The kernel reports it as -EPIPE. The endpoint stays halted until the host clears the condition, and every later transfer fails the same way. Clear it with:

c
ret = usb_bulk_msg(s->udev, s->in_pipe, buf, len, &got, SAMPLE_TIMEOUT_MS);
if (ret == -EPIPE) {
	usb_clear_halt(s->udev, s->in_pipe);
	ret = usb_bulk_msg(s->udev, s->in_pipe, buf, len, &got,
			   SAMPLE_TIMEOUT_MS);
}

usb_clear_halt() sends the standard CLEAR_FEATURE(ENDPOINT_HALT) request and resets the host-side data toggle. It sleeps too. Retry once, not in a loop: a device that stalls again after a clear is telling you the command is invalid, and spinning on it hides the real bug.

The errors you will see, in order of frequency:

ErrorMeaningReaction
-ETIMEDOUTNo reply within the timeoutDiscard data, maybe retry
-EPIPEEndpoint stalledusb_clear_halt(), retry once
-EOVERFLOWThe device sent more than requestedRequest a multiple of the packet size
-ENODEV, -ESHUTDOWNDevice unpluggedStop, clean up, return
-EPROTO, -EILSEQBus-level errorTreat as a failing device or cable

When usb_bulk_msg is the wrong tool

It is a blocking call with one transfer in flight. For a stream of data, such as a capture device or a fast serial adapter, one blocked thread cannot keep the endpoint busy, and throughput drops because the bus idles between calls. Those drivers keep several URBs queued. For a few transfers per second, such as configuration or a firmware update, usb_bulk_msg() is the right choice and the simplest correct one.

Also inHardware
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.