Skip to content
systemcoding.dev
Kernels

Send USB Control Transfers With usb_control_msg

Send vendor and standard USB control requests from a Linux 6.12 driver with usb_control_msg and the safer usb_control_msg_recv and usb_control_msg_send helpers.

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 FreeBSD logos.

Control transfers are how a host configures a USB device. Enumeration uses them, class drivers use them, and almost every vendor-specific chip exposes registers or commands through them. The kernel offers usb_control_msg() for the job, and since Linux 5.10 two wrappers, usb_control_msg_recv() and usb_control_msg_send(), that remove the sharpest edges. This post uses Linux 6.12 to read a firmware version and write a configuration value through a vendor request, and explains each argument of the setup packet so you can map a datasheet table to code on the first try. The driver structure comes from the skeleton post.

The setup packet is defined in chapter 9 of the USB 2.0 specification, and the kernel functions are declared in include/linux/usb.h.

What a control transfer contains

Every control transfer starts with an eight-byte setup packet on endpoint 0, then an optional data stage, then a status stage. The setup packet has five fields, and usb_control_msg() takes each of them as an argument:

FieldSizeMeaning
bmRequestType1 byteDirection (bit 7), type (bits 6:5), recipient (bits 4:0)
bRequest1 byteThe request code
wValue2 bytesA request-specific parameter
wIndex2 bytesAnother parameter, often an interface or register index
wLength2 bytesThe number of bytes in the data stage

The bmRequestType byte is built from three kernel constants OR-ed together. Direction is USB_DIR_IN or USB_DIR_OUT. Type is USB_TYPE_STANDARD, USB_TYPE_CLASS or USB_TYPE_VENDOR. Recipient is USB_RECIP_DEVICE, USB_RECIP_INTERFACE, USB_RECIP_ENDPOINT or USB_RECIP_OTHER. A vendor request read from the device itself is therefore USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE, which is the byte 0xc0.

Datasheets quote the bytes directly, as in "request type 0xC0, request 0x01, value 0, index 0, length 2". Translate by building the same byte from the constants, which keeps the code readable and lets the compiler check it.

The classic function

c
int usb_control_msg(struct usb_device *dev, unsigned int pipe,
		    __u8 request, __u8 requesttype,
		    __u16 value, __u16 index,
		    void *data, __u16 size, int timeout);

The pipe comes from usb_rcvctrlpipe(udev, 0) for a read or usb_sndctrlpipe(udev, 0) for a write, always with endpoint 0. The return value is the number of bytes transferred on success, which is different from the bulk function. A negative value is an errno. That difference between "bytes" and "zero" trips people up, because code like if (ret) treats a successful two-byte read as an error.

A read of a two-byte firmware version looks like this:

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

#define SAMPLE_REQ_GET_VERSION	0x01
#define SAMPLE_REQ_SET_LEVEL	0x02
#define SAMPLE_TIMEOUT_MS	500

static int sample_get_version(struct usb_device *udev, u16 *version)
{
	__le16 *buf;
	int ret;

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

	ret = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0),
			      SAMPLE_REQ_GET_VERSION,
			      USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
			      0, 0, buf, sizeof(*buf), SAMPLE_TIMEOUT_MS);
	if (ret < 0)
		goto out;
	if (ret != sizeof(*buf)) {
		ret = -EREMOTEIO;
		goto out;
	}

	*version = le16_to_cpu(*buf);
	dev_info(&udev->dev, "firmware version %u.%u\n",
		 *version >> 8, *version & 0xff);
	ret = 0;
out:
	kfree(buf);
	return ret;
}

Three things in it are required, not stylistic. The buffer is kmalloced, because the data stage uses DMA like any transfer. The length check handles a short reply, which the function reports as success with a smaller count. And the value is converted with le16_to_cpu(), because USB is little-endian on the wire and a big-endian host would otherwise read the bytes swapped.

If the device returns bytes 0x03 0x01, the value is 0x0103, and the dev_info call prints the high byte as the major number and the low byte as the minor number. The kernel log shows the device name, because the message is tied to the device and not to an interface:

Text
usb 1-2: firmware version 1.3

The safer wrappers

The two helpers added in Linux 5.10 handle exactly the three mistakes above. They allocate the bounce buffer for you, check the length, and return zero on success:

c
int usb_control_msg_recv(struct usb_device *dev, __u8 endpoint, __u8 request,
			 __u8 requesttype, __u16 value, __u16 index,
			 void *driver_data, __u16 size, int timeout,
			 gfp_t memflags);

int usb_control_msg_send(struct usb_device *dev, __u8 endpoint, __u8 request,
			 __u8 requesttype, __u16 value, __u16 index,
			 const void *driver_data, __u16 size, int timeout,
			 gfp_t memflags);

Notice what changed. You pass the endpoint number (0) instead of a pipe, and the direction bit of requesttype is set for you from the function you called. driver_data can be any memory, even the stack, because the helper copies through a buffer it allocates with memflags. A short read is converted into -EREMOTEIO.

The same read becomes shorter, and the write is symmetric:

c
static int sample_get_version_v2(struct usb_device *udev, u16 *version)
{
	__le16 raw;
	int ret;

	ret = usb_control_msg_recv(udev, 0, SAMPLE_REQ_GET_VERSION,
				   USB_TYPE_VENDOR | USB_RECIP_DEVICE,
				   0, 0, &raw, sizeof(raw),
				   SAMPLE_TIMEOUT_MS, GFP_KERNEL);
	if (ret)
		return ret;

	*version = le16_to_cpu(raw);
	return 0;
}

static int sample_set_level(struct usb_device *udev, u16 level)
{
	return usb_control_msg_send(udev, 0, SAMPLE_REQ_SET_LEVEL,
				    USB_TYPE_VENDOR | USB_RECIP_DEVICE,
				    level, 0, NULL, 0,
				    SAMPLE_TIMEOUT_MS, GFP_KERNEL);
}

sample_set_level() has no data stage. The parameter travels in wValue, so driver_data is NULL and size is zero, and the transfer is only the setup and status stages. Many vendor writes are shaped like this, with a register number in wIndex and a value in wValue. Prefer the wrappers in new code for that reason: a bug class disappears.

Errors and the stall

A device that does not support a request answers the data or status stage with a STALL, and the call returns -EPIPE. Unlike a bulk endpoint, a control stall is cleared automatically by the next setup packet, so you do not call usb_clear_halt(). -EPIPE on endpoint 0 means "unsupported request", and a driver can use it to detect an older firmware: try the new request, and fall back on -EPIPE.

-ETIMEDOUT means the device was too slow, and the standard allows up to five seconds for the data stage, so a short timeout can break a slow device. -ENODEV means the device is gone. Treat -EPROTO as a cable or hardware problem.

Control requests to a device whose driver is probing run on the USB core's own timing, and they take a mutex on the device. Do not issue them from interrupt context, and do not hold a lock that your disconnect also takes while you wait for one, or you can deadlock against the unplug.

Standard requests you may need

The core already wraps the common standard ones, and you should call those rather than rebuild them:

NeedCall
Read a string descriptorusb_string()
Select an alternate settingusb_set_interface()
Clear a haltusb_clear_halt()
Reset the deviceusb_reset_device()

A vendor request is for what the standard does not cover, and for a class request on an interface, use USB_TYPE_CLASS | USB_RECIP_INTERFACE with wIndex set to the interface number.

Reading a datasheet table

Vendor documents often list requests as a table with columns for type, request, value, index and length. Map each column to one argument in order, and write the type column as a symbolic expression rather than a raw byte. For example, a row that reads "0x40, 0x03, 0x0010, 0x0001, 0" becomes USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE with request 3, value 16, index 1 and no data stage. Keeping the symbolic form means a reviewer can see at a glance that the request is a vendor write to the device, and a mistaken direction bit shows up as an obvious mismatch instead of a magic number.

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.