OS Lab 9 - USB drivers. USB transfers
In the last lab, we wrote a kernel module with a character device, whose read(), write() and ioctl() ran our functions. The device was a virtual one: it only kept data in memory. In this lab, the device behind the file is a real USB device, your project board, and the driver's functions talk to it.
The rule for the whole lab is simple: each file operation does its own USB transfers, waits for them, and returns. The driver never does anything in the background. Real drivers are often more complicated (see How real drivers do it), but for our boards, this is all that is needed, and it keeps the driver close to the character device of the last lab.
Learning objectives
By the end of this lab you should be able to:
- read the descriptors of a USB device, and find its interfaces and endpoints;
- write a USB driver which binds to a device, checks it in
probe(), and cleans up indisconnect(); - give each board its own file in
/dev; - send control requests, and read and write interrupt and bulk endpoints, with blocking calls;
- make a blocking call that can be interrupted with Ctrl+C, and that respects
O_NONBLOCK; - convert between the byte order of the device and of the machine;
- handle a device which is unplugged while a program uses it.
The project
There is no new template: you build your USB driver in the project of the last lab, which already has the three parts (the driver, a library which wraps it, and a program which uses the library) and the kernel tree in kbuild/. Work in a copy of it. kbuild/ is large, so move it rather than copy it:
rsync -a --exclude kbuild lab08/ lab09/
mv lab08/kbuild lab09/
cd lab09
Then turn the klog driver of the template into yours. The examples in this lab are from arhboard, a driver which works on every project board, because it only uses the requests and events which all of them have. For your own driver, use the name of your project instead:
- rename
driver/klog.ctodriver/arhboard.c, anddriver/uapi/klog_ioctl.htodriver/uapi/arhboard_ioctl.h; - in
driver/Kbuild, change the lineobj-mtoobj-m := arhboard.o; - in
driver/Makefile, changeMODULE := klogtoMODULE := arhboard; - rename the files in
lib/as well, when you write the library. CMake builds every.cfile inlib/andapp/, whatever its name. Until then, the library and the program of the template no longer build, because they includeklog_ioctl.h: build the driver alone, withmake -C driver.
A USB driver has one file in /dev for each board, /dev/arhboard0, /dev/arhboard1, ..., and they only appear when a board is plugged in (see One file per board). The rule load of the template already handles this: after insmod, it makes the file of every device of the module that it finds in /sys/class, which was /dev/klog in the last lab, and is one file per board now. make unload removes them again. On OrbStack, which does not make the files itself, run make -C driver nodes for a board you plug in after loading the driver.
ERROR: modpost: "usb_register_driver" [...] undefined!, your kbuild/ was made without USB support, by an older make_kbuild.sh. Download the template of the last lab again, take its make_kbuild.sh, delete kbuild/, and run the script again. Take its driver/Makefile too (and set MODULE in it again): an older one has no nodes rule, and only makes /dev/klog.The board
The board you will be working with is a Raspberry Pi Pico 2 (or Pico 2 W) which runs the firmware assigned to you for your project. It should be running the firmware as soon as you plug it in. You do not need to program the board yourself.
On a PC which runs Linux directly, there is nothing else to do: plug the board in. In a virtual machine, the board is plugged into the host (macOS or Windows), and you must give it to the Linux machine first.
OrbStack
orb usb list shows the USB devices of the Mac, with an ID for each:
$ orb usb list
...
00114000 cafe:4301 ARH ARH CC-1
$ orb usb attach 00114000
From then on, Linux sees the board as if it were plugged into it, and macOS does not see it anymore. orb usb detach 00114000 gives it back to the Mac, which, for Linux, is the same as unplugging it. This is useful later, to test what your driver does when the board goes away.
orb usb list again if you change ports.WSL
WSL gets USB devices from Windows through usbipd-win, which you install in Windows. In a PowerShell window opened as administrator, usbipd list shows the USB devices of the PC, with a bus ID for each. Share the board once with bind, and then give it to WSL with attach:
> usbipd list
BUSID VID:PID DEVICE STATE
2-3 cafe:4301 ARH CC-1 Not shared
> usbipd bind --busid 2-3
> usbipd attach --wsl --busid 2-3
From then on, lsusb in WSL shows the board. usbipd detach --busid 2-3 gives it back to Windows, which, for Linux, is the same as unplugging it. After you unplug the board and plug it back in, run usbipd attach again.
USB in brief
USB connects one host (the computer) to many devices. The most important rule is that the host always starts communication. A device never sends anything on its own: it only answers when the host asks. When the host asks a device for data, the device answers in one of three ways:
- with the data;
- with a NAK: nothing now, ask again later. This is normal, and the host should keep asking;
- with a STALL: no, the device refuses the request, or this part of the device is stopped.
Devices, interfaces and endpoints
A device describes itself to the host with descriptors, when it is plugged in. They form a tree:
- the device: its vendor and product IDs (VID and PID), its name, its serial number;
- a configuration: almost every device has exactly one;
- one or more interfaces: one function of the device. A webcam with a microphone has one interface for the video, and one for the sound. Each interface has a class (audio, keyboard, storage, ...). A class of 0xFF means that the interface is vendor-specific: its protocol is known only to its own driver;
- the endpoints of the interface: the places where data goes in or out of the device.
- one or more interfaces: one function of the device. A webcam with a microphone has one interface for the video, and one for the sound. Each interface has a class (audio, keyboard, storage, ...). A class of 0xFF means that the interface is vendor-specific: its protocol is known only to its own driver;
- a configuration: almost every device has exactly one;
A driver in Linux binds to an interface, not to a whole device. Our boards have exactly one interface, with three endpoints: a bulk endpoint in each direction for data, and an interrupt endpoint for events. So the driver of a board binds to that interface, and has the whole board to itself.
An endpoint has a number, from 1 to 15, and a direction, which is always seen from the host: IN means from the device to the host, OUT from the host to the device. The direction is the top bit of the endpoint address: 0x81 is endpoint 1 IN, 0x01 is endpoint 1 OUT. Every device also has endpoint 0, which works both ways, and is used for control requests: commands and settings. Each endpoint also has a maximum packet size (wMaxPacketSize), the most bytes that one packet on it can carry: on our boards, 64 bytes for endpoint 0 and the bulk endpoints, and 8 bytes for the event endpoint, which is exactly one event.
Each endpoint has a transfer type, which says how the host uses it:
| Type | Used for | On our boards |
|---|---|---|
| Control | Commands, settings, small replies. Only on endpoint 0 | Every request in the protocol of the board: GET_INFO, IDENTIFY, ...
|
| Bulk | Large amounts of data, as fast as the bus allows, with no promise about time | The data of a project: what a CC-1 hashes or encrypts, for example |
| Interrupt | Small, infrequent messages, which must arrive within a known time | Events: the button was pressed, an operation has finished |
| Isochronous | Sound and video: a fixed rate, and late data is dropped | Not used |
The name of interrupt endpoints is misleading: the device still cannot speak first. The host asks the endpoint again and again, every few milliseconds (the interval, set in the descriptor), and the device answers with NAK until it has something to say. Nothing reaches the host while nobody asks.
Our boards run at full speed (12 Mbit/s), where a bulk or interrupt packet carries at most 64 bytes. A larger transfer is cut into several packets.
Your board's descriptors
lsusb lists the devices, and lsusb -v prints all their descriptors. All our boards have the vendor ID 0xcafe, and a product ID for each project:
$ lsusb -d cafe:
Bus 001 Device 004: ID cafe:4301 ARH ARH CC-1
$ lsusb -v -d cafe:
...
idVendor 0xcafe
idProduct 0x4301
bcdDevice 1.00
iManufacturer 1 ARH
iProduct 2 ARH CC-1
iSerial 3 E6614103E7452D2F
...
Interface Descriptor:
bInterfaceNumber 0
bNumEndpoints 3
bInterfaceClass 255 Vendor Specific Class
bInterfaceSubClass 0
bInterfaceProtocol 0
Endpoint Descriptor:
bEndpointAddress 0x01 EP 1 OUT
bmAttributes 2
Transfer Type Bulk
wMaxPacketSize 0x0040 1x 64 bytes
Endpoint Descriptor:
bEndpointAddress 0x81 EP 1 IN
bmAttributes 2
Transfer Type Bulk
wMaxPacketSize 0x0040 1x 64 bytes
Endpoint Descriptor:
bEndpointAddress 0x82 EP 2 IN
bmAttributes 3
Transfer Type Interrupt
wMaxPacketSize 0x0008 1x 8 bytes
bInterval 10
This CC-1 has one vendor-specific interface, with a bulk endpoint in each direction for its data, and an interrupt IN endpoint of 8 bytes for its events, which the host asks every 10 ms. Look at the descriptors of your own board: it has the same three endpoints, and what travels on the two bulk endpoints depends on your project.
What every board answers
Every board for our lab, for all projects, answers a small common set of control requests, and sends events in the same format. They are described in full in section 4 of the specification of your project. The example driver of this lab uses only these:
| Request | Number | Direction | wValue | Data |
|---|---|---|---|---|
GET_INFO |
0x00 | IN | 0 | 16 bytes: what the board is (below) |
IDENTIFY |
0xE0 | OUT | How many times to flash the LED, 1 to 10 | None |
GET_BOARD_STATUS |
0xE1 | IN | 0 | 8 bytes: uptime, event counters, the button |
SET_LABEL |
0xE2 | OUT | 0 | 16 bytes: a name for the board, padded with zero bytes |
GET_LABEL |
0xE3 | IN | 0 | 16 bytes: the name set before |
GET_INFO starts with a magic number: the characters "ARH", which are the same on every board, followed by one character which names the project ("ARH1" for the CC-1). Then come the version of the project's protocol, the version of the firmware, and a few fields which the project defines.
Each event is one 8-byte packet on the first interrupt IN endpoint: a type, an argument, a sequence number, and the time in milliseconds since the board was powered up. Type 0x01 is a short press of the button which the board has no other use for. The other types belong to the project.
A USB driver
A USB driver is a struct usb_driver, with a table of the devices which it can handle, and two functions which the USB core calls:
// In: <linux/usb.h>
struct usb_driver {
const char *name;
int (*probe)(struct usb_interface *intf, const struct usb_device_id *id);
void (*disconnect)(struct usb_interface *intf);
const struct usb_device_id *id_table;
...
};
int usb_register(struct usb_driver *driver);
void usb_deregister(struct usb_driver *driver);
module_usb_driver(driver);
module_usb_driver() writes the module's init and exit functions for you: init registers the driver, exit deregisters it. A USB driver's module usually has nothing else to do when it is loaded. All the work happens per device, in probe() and disconnect().
Which devices: the ID table
When a device is plugged in, the USB core compares each of its interfaces with the ID table of every USB driver, and calls the probe() of the first driver which matches:
/* The seven lab boards: vendor 0xcafe, one product ID per project */
static const struct usb_device_id arhboard_ids[] = {
{ USB_DEVICE(0xcafe, 0x4301) }, /* CC-1 */
{ USB_DEVICE(0xcafe, 0x4302) }, /* EL-2 */
{ USB_DEVICE(0xcafe, 0x4303) }, /* FV-3 */
{ USB_DEVICE(0xcafe, 0x4304) }, /* MB-4 */
{ USB_DEVICE(0xcafe, 0x4305) }, /* TW-5 */
{ USB_DEVICE(0xcafe, 0x4306) }, /* WP-6 */
{ USB_DEVICE(0xcafe, 0x4307) }, /* BP-7 */
{}
};
MODULE_DEVICE_TABLE(usb, arhboard_ids);
The table ends with an empty entry. A few macros fill in an entry:
| Macro | Matches |
|---|---|
USB_DEVICE(vid, pid) |
One product. The example lists the seven boards this way; the driver of your project has a single entry, with the PID of your board |
USB_VENDOR_AND_INTERFACE_INFO(vid, class, subclass, protocol) |
Every interface of that class, on every product of that vendor |
USB_INTERFACE_INFO(class, subclass, protocol) |
Every interface of that class, from any vendor: how the drivers of standard classes (keyboards, storage, ...) bind |
MODULE_DEVICE_TABLE() copies the table into the module file. The system uses it to load the right module by itself when a device is plugged in. modinfo shows it, as alias lines.
arhboard is loaded, it takes your board, and the driver of your project never gets a probe(). Unload it first, with sudo rmmod arhboard, and the other way around.probe() and disconnect()
probe() is called once for each matching interface, when the device is plugged in, or when the driver is loaded with the device already there. It decides whether the driver takes the interface: it returns 0 to take it, or an error, usually -ENODEV, to leave it. If it takes it, it should:
- allocate a structure for this device, which keeps everything the driver knows about it. There may be several boards at once, so nothing about a board goes in a global variable;
- find the endpoints which it needs;
- check that the device is really what the driver expects;
- attach its structure to the interface, with
usb_set_intfdata(), so thatdisconnect()finds it again withusb_get_intfdata(); - make the device available to programs: here, a file in
/dev.
disconnect() is called when the device is unplugged, or when the driver is unloaded. It cannot fail, and cannot stop the unplugging: when it is called, the device may already be gone. It undoes what probe() did. See Unplugging for what happens to programs which still have the file open.
Print with dev_info(), dev_err() and so on, with &intf->dev. The messages then start with the name of the driver and the place of the device on the bus, so that two boards can be told apart in the log:
arhboard 1-1:1.0: project '1', protocol 1.0, firmware 1.0, /dev/arhboard0
Finding the endpoints
A driver should not assume the addresses of its endpoints: probe() finds them in the descriptors of the interface, in three steps.
Step 1: find the descriptor of the endpoint. The current descriptors of the interface are in intf->cur_altsetting. usb_find_common_endpoints() searches them, and returns the first endpoint of each kind. A few shorter functions return only one kind:
// In: <linux/usb.h>
int usb_find_common_endpoints(struct usb_host_interface *alt,
struct usb_endpoint_descriptor **bulk_in,
struct usb_endpoint_descriptor **bulk_out,
struct usb_endpoint_descriptor **int_in,
struct usb_endpoint_descriptor **int_out);
int usb_find_bulk_in_endpoint(struct usb_host_interface *alt, struct usb_endpoint_descriptor **bulk_in);
int usb_find_bulk_out_endpoint(struct usb_host_interface *alt, struct usb_endpoint_descriptor **bulk_out);
int usb_find_int_in_endpoint(struct usb_host_interface *alt, struct usb_endpoint_descriptor **int_in);
int usb_endpoint_maxp(const struct usb_endpoint_descriptor *epd);
alt is intf->cur_altsetting. Pass NULL for the kinds you don't need. They return 0, or -ENXIO if one of the endpoints you asked for is missing.
Step 2: check it. In an endpoint descriptor, bEndpointAddress is the address of the endpoint, and usb_endpoint_maxp() returns its largest packet. Refuse a device whose endpoint is not what the driver expects.
Step 3: make a pipe. A transfer does not take the address of an endpoint directly, but a pipe, a number which combines the device, the endpoint, its direction and its type. Make it once, and keep it in the structure of the device:
| Endpoint | IN | OUT |
|---|---|---|
| Control (endpoint 0) | usb_rcvctrlpipe(udev, 0) |
usb_sndctrlpipe(udev, 0)
|
| Bulk | usb_rcvbulkpipe(udev, addr) |
usb_sndbulkpipe(udev, addr)
|
| Interrupt | usb_rcvintpipe(udev, addr) |
usb_sndintpipe(udev, addr)
|
udev is the struct usb_device of the whole device, which interface_to_usbdev(intf) returns. The example does the three steps for its event endpoint:
/* The event endpoint: the first interrupt IN endpoint */
ret = usb_find_int_in_endpoint(intf->cur_altsetting, &ev_ep);
if (ret) {
dev_err(&intf->dev, "no interrupt IN endpoint\n");
goto err;
}
if (usb_endpoint_maxp(ev_ep) != sizeof(struct wire_event)) {
dev_err(&intf->dev, "event endpoint is not 8 bytes\n");
ret = -ENODEV;
goto err;
}
dev->ev_pipe = usb_rcvintpipe(dev->udev, ev_ep->bEndpointAddress);
One file per board
In the last lab, we got a device number, a struct cdev and a class in three steps. A USB driver does all three with one call:
// In: <linux/usb.h>
struct usb_class_driver {
char *name; /* "arhboard%d": %d becomes 0, 1, ... */
char *(*devnode)(const struct device *dev, umode_t *mode);
const struct file_operations *fops;
int minor_base;
};
int usb_register_dev(struct usb_interface *intf, struct usb_class_driver *class_driver);
void usb_deregister_dev(struct usb_interface *intf, struct usb_class_driver *class_driver);
usb_register_dev() takes the next free minor number from minor_base on, of major number 180, which the kernel keeps for USB devices. It sets intf->minor, and makes the device arhboard0 in the class usbmisc, so that the file /dev/arhboard0 appears. A second board gets /dev/arhboard1, and so on. The example uses minors from 192, and the driver of your project uses minors from 208, so that both can be loaded at once.
make -C driver load creates them with mknod, from /sys/class/usbmisc/arhboardN/dev. For a board which you attach after loading the driver, run make -C driver nodes.open() gets only the inode, and must find the board from its minor number. usb_find_interface() returns the interface of this driver which has that minor:
static int arhboard_open(struct inode *inode, struct file *file)
{
struct usb_interface *intf;
struct arhboard *dev;
intf = usb_find_interface(&arhboard_driver, iminor(inode));
if (!intf)
return -ENODEV;
dev = usb_get_intfdata(intf);
if (!dev)
return -ENODEV;
kref_get(&dev->kref);
file->private_data = dev;
return 0;
}
From then on, every file operation finds the board in file->private_data, as in the last lab. kref_get() is explained in Unplugging.
A device which is a stream, with no position to seek to (most project boards), should say so in its open(), by ending it with stream_open() (from <linux/fs.h>) instead of return 0:
file->private_data = dev;
return stream_open(inode, file); /* always returns 0 */
lseek() on the file then fails with ESPIPE, and so do pread() and pwrite(), which take a position. Your device is a stream unless its data has positions which a program can jump to. (The example has no llseek function, so lseek() already fails on it; it leaves stream_open() out to stay short.)
Talking to the device
Buffers
The USB controller moves the data of a transfer to and from memory by itself, with DMA, without the processor. It can only do that with memory from kmalloc(). A transfer buffer must never be on the stack, or a global variable: the transfer may fail, or corrupt memory next to the buffer, and on some machines it seems to work, until it doesn't.
The example allocates its buffers once, in probe(), and keeps them in its structure:
dev->ctrl_buf = kmalloc(CTRL_BUF_LEN, GFP_KERNEL);
dev->ev_buf = kmalloc(sizeof(struct wire_event), GFP_KERNEL);
A buffer which is used by one transfer at a time, like these, needs a lock: see Locking.
Byte order
All the numbers which our boards send and receive are little-endian: the lowest byte comes first. Most processors which run Linux are little-endian too, but not all of them, and a driver must work on any machine. The kernel has types which say the byte order of a value, and functions which convert it to and from the byte order of the machine:
// In: <asm/byteorder.h>, which most kernel headers include
u16 le16_to_cpu(__le16 x); __le16 cpu_to_le16(u16 x);
u32 le32_to_cpu(__le32 x); __le32 cpu_to_le32(u32 x);
On a little-endian machine, they do nothing, and cost nothing. Describe what the device sends with a structure of these types, and convert each field when you use it:
/* What the board sends, exactly as it is on the wire: little-endian */
struct wire_event {
u8 type;
u8 arg;
__le16 seq;
__le32 time_ms;
};
static_assert(sizeof(struct wire_event) == 8);
The structure must be exactly the 8 bytes that the board sends. If the compiler added padding between the fields, it would not be, and static_assert() catches that when you build. __le16 and __le32 mark the fields which are in the board's byte order: read them with le16_to_cpu() and le32_to_cpu(), never directly.
uapi/ are what the driver gives to programs, in the byte order of the machine, with the __u8 ... __u32 types of the last lab. The driver converts one into the other, field by field. Never copy the bytes from the device straight to user space.Blocking calls
The kernel has one function for each transfer type, which sends the transfer, waits until it ends, and returns:
// In: <linux/usb.h>
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);
int usb_interrupt_msg(struct usb_device *dev, unsigned int pipe,
void *data, int len, int *actual_length, int timeout);
int usb_bulk_msg(struct usb_device *dev, unsigned int pipe,
void *data, int len, int *actual_length, int timeout);
timeout is in milliseconds. They sleep, so they can only be called where sleeping is allowed: in file operations, in probe() and in disconnect(), but not while holding a spinlock. They return a negative error if the transfer failed, and -ETIMEDOUT in particular if the device did not respond in time. usb_control_msg() returns the number of bytes moved. The other two return 0, and store the number of bytes moved in *actual_length. It can be less than you asked for, and a driver should always check it. They store it when they fail, too: see A slice which times out may have moved data.
The errors which you will meet most often:
| Error | Meaning | What to do |
|---|---|---|
-EPIPE |
The device answered with STALL: it refused the request, or the endpoint is halted | For a control request, return it to the program: the request was refused. For a bulk endpoint, see Halted endpoints |
-ETIMEDOUT |
The device did not finish in time: for an IN endpoint, it had nothing to send | Wait again, or give up: see below |
-EOVERFLOW |
The device sent more than the buffer can hold | Use a buffer of whole packets: see Bulk transfers |
-EPROTO, -EILSEQ |
The packet was damaged on the cable | Return an error. It is rare, unless the cable is bad |
-ENODEV, -ESHUTDOWN |
The device is gone | Return -ENODEV to userspace
|
Waiting for a long time
Some calls must wait for as long as it takes: a program which reads an event waits until somebody presses the button, maybe forever. A transfer with a very long timeout would do that, but then nothing could stop it. The blocking calls cannot be interrupted: they return only when the transfer ends or its timeout runs out, and a signal does not wake them. So Ctrl+C would do nothing, the process could not even be killed while it waits, and every other call which needs the same lock would wait behind it.
So a long wait is a loop of short waits. Each transfer has a short timeout, 100 ms in the example. When it times out, the loop checks what may have happened meanwhile, and starts another one:
for (;;) {
if (mutex_lock_interruptible(&dev->ev_lock))
return -ERESTARTSYS;
if (dev->gone)
ret = -ENODEV;
else
ret = usb_interrupt_msg(dev->udev, dev->ev_pipe, dev->ev_buf,
sizeof(struct wire_event), &actual, SLICE_MS);
/* ... use the data while we still hold the lock ... */
mutex_unlock(&dev->ev_lock);
if (ret != -ETIMEDOUT)
break; /* the data, or a real error */
/* No event in this slice */
if (file->f_flags & O_NONBLOCK)
return -EAGAIN;
if (signal_pending(current))
return -ERESTARTSYS;
}
Between two slices:
- Signals.
signal_pending(current)is true when the process has a signal waiting, for example after Ctrl+C. Returning-ERESTARTSYSlets the kernel deliver it. The program seesEINTR, or, if it is stopped and continued, the call starts again by itself.mutex_lock_interruptible()does the same while it waits for the lock. O_NONBLOCK. A program which opened the file withO_NONBLOCKdoes not want to wait. It gets one slice, and thenEAGAIN.- The lock is free, so another call, or
disconnect(), can take it. Never wait for longer than one slice while holding a lock. - Unplugging.
disconnect()setsgone, and the loop notices it at the next slice.
None of this needs anything new in the kernel: only a loop, and the mutex of the last lab. Every call of your driver which may wait for long should use this pattern.
Control transfers
A control request starts with an 8-byte setup packet, which the host sends to endpoint 0. Its fields are the arguments of usb_control_msg():
| Field | Argument | Meaning |
|---|---|---|
bmRequestType |
requesttype |
The direction of the data, who defined the request, and who it is for: see below |
bRequest |
request |
The number of the request |
wValue |
value |
A 16-bit argument, defined by the request |
wIndex |
index |
Another 16-bit argument. For a request to an interface, the number of the interface |
wLength |
size |
The number of bytes in the data stage. May be 0 |
After the setup packet comes the data stage, wLength bytes in the direction which bmRequestType gives, and then the device confirms that it has finished. If it refuses the request, it answers with STALL instead, and usb_control_msg() returns -EPIPE. This is not a problem with the device: it is its way of saying no.
bmRequestType is made of three parts, with a macro for each:
| Part | Our boards | Other values |
|---|---|---|
| Direction | USB_DIR_IN or USB_DIR_OUT |
|
| Type | USB_TYPE_VENDOR: a request which the maker of the device defined |
USB_TYPE_STANDARD, which every device answers, and USB_TYPE_CLASS
|
| Recipient | USB_RECIP_INTERFACE: for interface 0 |
USB_RECIP_DEVICE, USB_RECIP_ENDPOINT
|
For the requests of our boards, bmRequestType is 0xC1 for IN, and 0x41 for OUT. The example wraps usb_control_msg() in two functions, one for each direction. The data is always in dev->ctrl_buf, which comes from kmalloc():
#define REQTYPE_IN (USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_INTERFACE) /* 0xC1 */
#define REQTYPE_OUT (USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_INTERFACE) /* 0x41 */
static int arhboard_ctrl_in(struct arhboard *dev, u8 request, u16 len)
{
int ret = usb_control_msg(dev->udev, usb_rcvctrlpipe(dev->udev, 0),
request, REQTYPE_IN, 0, 0, dev->ctrl_buf, len,
CTRL_TIMEOUT_MS);
if (ret < 0)
return ret; /* -EPIPE: the board refused (STALL) */
if (ret != len)
return -EPROTO; /* a short answer is an error too */
return 0;
}
static int arhboard_ctrl_out(struct arhboard *dev, u8 request, u16 value,
u16 len)
{
int ret = usb_control_msg(dev->udev, usb_sndctrlpipe(dev->udev, 0),
request, REQTYPE_OUT, value, 0,
len ? dev->ctrl_buf : NULL, len,
CTRL_TIMEOUT_MS);
if (ret < 0)
return ret;
if (ret != len)
return -EPROTO;
return 0;
}
A control request is short, so it doesn't need the loop of the last section: one transfer with a timeout of a second is enough.
Checking the device in probe()
The vendor ID 0xcafe is not registered, so another device could use it too, even with the same product ID. Before it takes the interface, probe() asks the board what it is, with GET_INFO, and refuses it if the magic does not start with "ARH":
ret = arhboard_ctrl_in(dev, REQ_GET_INFO, sizeof(struct wire_info));
if (ret) {
dev_err(&intf->dev, "GET_INFO failed: %pe\n", ERR_PTR(ret));
goto err;
}
info_from_wire(&info, (struct wire_info *)dev->ctrl_buf);
if ((info.magic & 0x00ffffff) != MAGIC_ARH) {
dev_err(&intf->dev, "not a lab board (magic 0x%08x)\n",
info.magic);
ret = -ENODEV;
goto err;
}
The driver of your project should check the whole magic, and the major version of its protocol, and refuse a board which runs other firmware.
Control requests as ioctls
A request which returns a structure, or takes a number, fits an ioctl(). The example has one for each common request, in its shared header:
#define ARHBOARD_IOC_MAGIC 0xB8
#define ARHBOARD_IOC_GET_INFO _IOR(ARHBOARD_IOC_MAGIC, 1, struct arhboard_info)
#define ARHBOARD_IOC_GET_STATUS _IOR(ARHBOARD_IOC_MAGIC, 2, struct arhboard_status)
#define ARHBOARD_IOC_GET_LABEL _IOR(ARHBOARD_IOC_MAGIC, 3, struct arhboard_label)
/* Flash the LED: 1 to 10 times. Anything else is refused by the board (EPIPE). */
#define ARHBOARD_IOC_IDENTIFY _IOW(ARHBOARD_IOC_MAGIC, 4, __u32)
They show the three kinds of control request:
- IN, with data:
GET_INFO,GET_BOARD_STATUS,GET_LABEL. The driver reads the reply intoctrl_buf, converts it into the structure of the shared header, and copies that to the program; - OUT, with no data:
IDENTIFY. The number of flashes travels inwValue, andwLengthis 0; - OUT, with data:
SET_LABEL, which the example does inwrite():echo bench-3 > /dev/arhboard0.
case ARHBOARD_IOC_GET_STATUS: {
struct wire_status *w = (struct wire_status *)dev->ctrl_buf;
ret = arhboard_ctrl_in(dev, REQ_GET_BOARD_STATUS, sizeof(*w));
if (ret)
break;
out.status.uptime_ms = le32_to_cpu(w->uptime_ms);
out.status.events_dropped = le16_to_cpu(w->events_dropped);
out.status.events_queued = w->events_queued;
out.status.button_down = w->button_down;
out_len = sizeof(out.status);
break;
}
case ARHBOARD_IOC_IDENTIFY:
/* No data stage: the number travels in wValue */
ret = arhboard_ctrl_out(dev, REQ_IDENTIFY, flashes, 0);
break;
The driver does not check the number of flashes: the board does, and refuses 0 or more than 10 with a STALL. The program then gets EPIPE. Try it: this is what a refused request looks like, and the requests of your project will be refused in the same way.
IDENTIFY tells you which file is which board: the LED of the board behind /dev/arhboard1 flashes when you send it to /dev/arhboard1.Interrupt transfers: events
The board keeps the events
The host gets an event only when it reads the interrupt endpoint. What happens to the events which come while nobody reads? Our boards keep them: each board has a queue of event_queue_len events (a field of GET_INFO), and sends the oldest one each time the host reads. So the driver only needs to read the endpoint when a program asks for an event, and nothing is lost meanwhile.
If nobody reads for a long time, the queue fills up. The board then drops an old event to make room (the oldest one which is not already on its way to the host), and counts it in events_dropped (in GET_BOARD_STATUS). Each event has a sequence number, which goes up by one for every event the board makes, so a program sees a gap where events were lost.
read() waits for the next event
In the example, read() waits for the next event, with the loop of Waiting for a long time, and returns it as one line of text. Any program which reads lines can then show the events:
$ cat /dev/arhboard0
seq=0 time=48213 type=0x01 arg=0
seq=1 time=51007 type=0x01 arg=0
^C
Each line is one short press of the button, and Ctrl+C stops cat at once, because the driver checks for signals between its slices. The line is made with scnprintf(), which works like snprintf(), but returns the number of characters it actually wrote. The fields are converted from little-endian first:
if (ret == 0 && actual != sizeof(*wev))
ret = -EPROTO;
if (ret == 0)
len = scnprintf(line, sizeof(line),
"seq=%u time=%u type=0x%02x arg=%u\n",
le16_to_cpu(wev->seq),
le32_to_cpu(wev->time_ms),
wev->type, wev->arg);
A real program would rather have the event as a structure, from an ioctl(): text is used here only so that cat works. The events of your project, and what their type and argument mean, are in the specification of your project. The example prints them as raw numbers: on a CC-1, a long press shows type 0x05.
A short press is type 0x01 only on a board which has no other use for the button: a CC-1, an EL-2 which is not logging, or an FV-3. On the other boards, the press does its job, and you see that event instead: a lap (type 0x05) on a TW-5; a scan which starts (0x02) and, a few seconds later, ends (0x03) on a WP-6 or a BP-7; and on an MB-4, a quick tap is keyed as the letter E (type 0x03, arg 69), followed 3 s later by the space which ends the word (type 0x03, arg 32).
Bulk transfers
The common requests have no bulk endpoint, so the example does not use one. The data of your project goes through its bulk endpoints, with usb_bulk_msg(), in the loop of Waiting for a long time whenever the device may take long to answer. A few rules come from the way bulk data travels.
Packets, short packets and ZLPs
A bulk transfer is cut into packets of at most 64 bytes. The receiver knows that a transfer has ended when a packet is short: less than 64 bytes. A transfer of 150 bytes is sent as 64 + 64 + 22 bytes, and the 22-byte packet ends it.
A transfer whose size is an exact multiple of 64 has no short packet at its end. Then the sender adds a zero-length packet (ZLP), which carries no data, only to say that the transfer is over. A usb_bulk_msg() on an IN endpoint which receives a ZLP returns 0 with *actual_length 0. Whether your device sends ZLPs, and when, is in the specification of your project. A driver usually skips them.
An IN transfer also ends when the buffer is full. So one usb_bulk_msg() may return less than the device has to send, and the rest comes with the next call.
Read whole packets
The host cannot ask the device for 10 bytes: it asks for a packet, and the device sends up to 64. If it sends more than the buffer can hold, the transfer fails with -EOVERFLOW, and the data is lost. So the buffer of an IN transfer should always hold whole packets: a multiple of usb_endpoint_maxp().
A read() of any size then needs a buffer of its own in the driver: read whole packets into it, give the program what it asked for, and keep the rest for the next read().
/* in_buf: kmalloc()ed, a multiple of 64 bytes */
ret = usb_bulk_msg(dev->udev, dev->in_pipe, dev->in_buf, IN_BUF_LEN,
&actual, SLICE_MS);
if (ret == 0 || ret == -ETIMEDOUT) {
/* actual bytes in in_buf: 0 for a ZLP, or less than the device has */
}
A slice which times out may have moved data
A transfer of several packets can stop halfway: the device sends or takes a few packets, then answers NAK until the slice runs out. usb_bulk_msg() then returns -ETIMEDOUT, but *actual_length still says how many bytes were moved, and those bytes are done: the device will not send them again, and it has already taken the ones you wrote. So after a timeout:
- on an IN endpoint, keep the
actualbytes which arrived; - on an OUT endpoint, go on from
buf + actualin the next slice, and never send the same bytes twice.
A driver which treats -ETIMEDOUT as "nothing happened" loses or repeats data. The simplest way to avoid the question is to move one packet (at most 64 bytes) in each transfer: a single packet either goes through, or does not.
Halted endpoints
A device can halt a bulk endpoint, for example after an error in the data. Every transfer on it then fails with -EPIPE, until the host clears the halt:
// In: <linux/usb.h>
int usb_clear_halt(struct usb_device *dev, int pipe);
The example driver has no bulk endpoints, so it never needs this, but most project boards refuse bulk data in some states, with a STALL. When to clear the halt, and what else the device expects before it works again, is in the specification of your project.
Locking
Several programs, or several threads, can use the same board at once, and each file operation uses the device and its buffers. As in the last lab, a mutex protects them. A transfer can take long, though, and while one file operation waits on an endpoint, the others should not wait behind it if they don't need that endpoint. So take one mutex for each thing which can be used on its own:
struct arhboard {
struct usb_device *udev;
struct usb_interface *intf;
struct kref kref; /* probe() holds one reference, each open file one */
struct mutex ctrl_lock; /* control transfers, ctrl_buf */
u8 *ctrl_buf; /* kmalloc()ed: the controller reads it by DMA */
struct mutex ev_lock; /* the event endpoint, ev_buf */
u8 *ev_buf;
unsigned int ev_pipe;
bool gone; /* unplugged: written under both locks */
};
While cat waits for an event, holding ev_lock for one slice at a time, an ioctl() takes ctrl_lock, and its control request goes through at once. A driver with bulk endpoints usually adds one mutex for each direction. Two calls which both read events take turns, one slice each, and each event goes to only one of them.
Unplugging
A board can be unplugged at any moment: while a program has its file open, or even while a call waits on one of its endpoints. disconnect() is then called, and must not wait for the programs to close their files, which may never happen. But the structure of the board cannot be freed while open files still point to it.
The solution has two parts.
The structure is reference counted, with a struct kref: a counter of how many users the structure has, kept as a member of the structure itself, like the struct list_head of the last lab.
// In: <linux/kref.h>
void kref_init(struct kref *kref); // The count starts at 1
void kref_get(struct kref *kref); // One more user
int kref_put(struct kref *kref, void (*release)(struct kref *kref)); // One user less
kref_put() calls release when the count reaches 0. release gets a pointer to the struct kref, goes back to the structure around it with container_of(), and frees it.
probe() holds one reference, from kref_init(), and each open file holds one: open() takes it with kref_get(), and release() drops it with kref_put(). Whoever drops the last reference frees the structure:
static void arhboard_delete(struct kref *kref)
{
struct arhboard *dev = container_of(kref, struct arhboard, kref);
kfree(dev->ev_buf);
kfree(dev->ctrl_buf);
usb_put_intf(dev->intf);
usb_put_dev(dev->udev);
kfree(dev);
}
static int arhboard_release(struct inode *inode, struct file *file)
{
struct arhboard *dev = file->private_data;
kref_put(&dev->kref, arhboard_delete);
return 0;
}
probe() also takes a reference to the struct usb_device and to the interface, with usb_get_dev() and usb_get_intf(), so that they stay valid for as long as the structure of the driver does.
disconnect() marks the board as gone, under both locks, and drops the reference of probe():
static void arhboard_disconnect(struct usb_interface *intf)
{
struct arhboard *dev = usb_get_intfdata(intf);
/* No new open() from now on */
usb_deregister_dev(intf, &arhboard_class);
usb_set_intfdata(intf, NULL);
/*
* Calls already running notice within one slice. Taking each lock
* waits for the transfer which holds it, if any.
*/
mutex_lock(&dev->ctrl_lock);
mutex_lock(&dev->ev_lock);
dev->gone = true;
mutex_unlock(&dev->ev_lock);
mutex_unlock(&dev->ctrl_lock);
dev_info(&intf->dev, "unplugged\n");
/* Freed now, or at the last close() */
kref_put(&dev->kref, arhboard_delete);
}
Every file operation checks gone, under its lock, before it touches the device, and returns -ENODEV. A call which is waiting notices it at its next slice. The program then gets ENODEV from every call, until it closes the file, and the last close() frees the structure.
Try it: start cat /dev/arhboard0, and unplug the board, or run orb usb detach. cat stops with No such device, and the kernel log shows unplugged, and nothing else.
disconnect() takes each lock, so it waits for the transfer which holds it: at most one slice for the events, and one control request. A call which held a lock for a long wait would make disconnect() wait for just as long.The library and the program
The library and the program follow the shape of the last lab: the library has one function for each operation of the driver, hides the ioctl numbers and structures, and turns errors into messages. The program should not need to include the shared header.
A program often has to do two things at once: wait for the commands of the user, and print the events of the board as they come. Both are blocking calls. The simplest way is two threads:
- one thread waits for events, in a loop, and prints each one as it comes;
- the main thread reads the commands of the user, with
readline(), and runs them.
The two threads can use the same open file: the driver has a separate lock for the events, so a command does not wait for the event thread. To stop the event thread, let it wait with a short timeout, for example 200 ms, and check a flag between two waits. When the user quits, the main thread sets the flag, waits for the event thread with pthread_join(), and only then closes the file. Never close a file which another thread is still using.
rl_forced_update_display().How real drivers do it
The drivers in the kernel rarely use the blocking calls of this lab. They send URBs (USB Request Blocks): a transfer which is started, and finishes later, while the driver does something else. When it finishes, the USB core calls a completion handler of the driver. A driver of a device with events keeps one URB always waiting on the interrupt endpoint, from probe() to disconnect(): its completion handler puts each event in a queue in the driver, wakes up the processes which wait for one, and sends the URB again. The driver then implements poll(), so that a program can wait for events on several files at once, in one thread.
This is needed when a device does not keep its events, or when it must be read without a pause, like a keyboard or a sound card. It also comes with new rules: a completion handler runs in interrupt context, where it cannot sleep, and so cannot take a mutex or call kmalloc() with GFP_KERNEL; it needs a spinlock instead. disconnect() must also stop every URB before it frees what they use. Our boards keep their events, so the blocking calls are enough, and none of this is needed.
Debugging
- The kernel log. Print what the driver does with
dev_dbg()anddev_info(), and every error withdev_err()and%pe:usb_control_msg failed: -EPIPEis much more useful than a program which getsEPIPEand says nothing. lsusb -v, to check the descriptors, andlsusb -t, to see which driver owns which interface.- The board on its own. The
arhboarddriver of this lab works on every board. Ifarhboardworks and your driver doesn't, the problem is in your driver. Only one of them can own the board: unload your driver first. usbmon, on a Linux machine which has it (not on OrbStack), shows every packet on the bus, with Wireshark: every request, every STALL, every ZLP.
A complete example: arhboard
The whole driver of this lab. It only uses the common part of the protocol, so it works on every project board. The driver of your project has the same shape, with the requests, endpoints and events of your project.
1// SPDX-License-Identifier: GPL-2.0
2/*
3 * arhboard: a driver for any lab board, which uses only the requests
4 * and events that every board has (section 4 of every board's spec).
5 *
6 * /dev/arhboardN
7 * read() waits for the next event, and returns it as one line of text
8 * write() sets the label of the board
9 * ioctl() GET_INFO, GET_STATUS, GET_LABEL, IDENTIFY
10 *
11 * Every transfer is synchronous: each file operation does its own USB
12 * transfers, and returns. The driver does nothing in the background.
13 */
14
15#include <linux/kref.h>
16#include <linux/module.h>
17#include <linux/mutex.h>
18#include <linux/slab.h>
19#include <linux/string.h>
20#include <linux/uaccess.h>
21#include <linux/usb.h>
22
23#include "arhboard_ioctl.h"
24
25#define ARHBOARD_MINOR_BASE 192
26
27/* Vendor requests, all to interface 0 */
28#define REQ_GET_INFO 0x00
29#define REQ_IDENTIFY 0xE0
30#define REQ_GET_BOARD_STATUS 0xE1
31#define REQ_SET_LABEL 0xE2
32#define REQ_GET_LABEL 0xE3
33
34#define REQTYPE_IN (USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_INTERFACE) /* 0xC1 */
35#define REQTYPE_OUT (USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_INTERFACE) /* 0x41 */
36
37#define CTRL_TIMEOUT_MS 1000
38/* A long wait is a loop of waits this long: see arhboard_read(). */
39#define SLICE_MS 100
40
41/* What the board sends, exactly as it is on the wire: little-endian */
42struct wire_info {
43 __le32 magic;
44 __le16 protocol_version;
45 __le16 firmware_version;
46 __le32 capabilities;
47 u8 device_specific[3];
48 u8 event_queue_len;
49};
50
51struct wire_status {
52 __le32 uptime_ms;
53 __le16 events_dropped;
54 u8 events_queued;
55 u8 button_down;
56};
57
58struct wire_event {
59 u8 type;
60 u8 arg;
61 __le16 seq;
62 __le32 time_ms;
63};
64
65static_assert(sizeof(struct wire_info) == 16);
66static_assert(sizeof(struct wire_status) == 8);
67static_assert(sizeof(struct wire_event) == 8);
68
69#define MAGIC_ARH 0x00485241 /* "ARH" in the low three bytes */
70#define CTRL_BUF_LEN 16
71
72/* Everything the driver knows about one board */
73struct arhboard {
74 struct usb_device *udev;
75 struct usb_interface *intf;
76 struct kref kref; /* probe() holds one reference, each open file one */
77
78 struct mutex ctrl_lock; /* control transfers, ctrl_buf */
79 u8 *ctrl_buf; /* kmalloc()ed: the controller reads it by DMA */
80
81 struct mutex ev_lock; /* the event endpoint, ev_buf */
82 u8 *ev_buf;
83 unsigned int ev_pipe;
84
85 bool gone; /* unplugged: written under both locks */
86};
87
88static struct usb_driver arhboard_driver;
89
90static void arhboard_delete(struct kref *kref)
91{
92 struct arhboard *dev = container_of(kref, struct arhboard, kref);
93
94 kfree(dev->ev_buf);
95 kfree(dev->ctrl_buf);
96 usb_put_intf(dev->intf);
97 usb_put_dev(dev->udev);
98 kfree(dev);
99}
100
101/*
102 * Control transfers. The caller holds ctrl_lock (or is probe(), before the
103 * device can be opened). The data is in dev->ctrl_buf.
104 */
105static int arhboard_ctrl_in(struct arhboard *dev, u8 request, u16 len)
106{
107 int ret = usb_control_msg(dev->udev, usb_rcvctrlpipe(dev->udev, 0),
108 request, REQTYPE_IN, 0, 0, dev->ctrl_buf, len,
109 CTRL_TIMEOUT_MS);
110 if (ret < 0)
111 return ret; /* -EPIPE: the board refused (STALL) */
112 if (ret != len)
113 return -EPROTO; /* a short answer is an error too */
114 return 0;
115}
116
117static int arhboard_ctrl_out(struct arhboard *dev, u8 request, u16 value,
118 u16 len)
119{
120 int ret = usb_control_msg(dev->udev, usb_sndctrlpipe(dev->udev, 0),
121 request, REQTYPE_OUT, value, 0,
122 len ? dev->ctrl_buf : NULL, len,
123 CTRL_TIMEOUT_MS);
124 if (ret < 0)
125 return ret;
126 if (ret != len)
127 return -EPROTO;
128 return 0;
129}
130
131static void info_from_wire(struct arhboard_info *info,
132 const struct wire_info *w)
133{
134 info->magic = le32_to_cpu(w->magic);
135 info->protocol_version = le16_to_cpu(w->protocol_version);
136 info->firmware_version = le16_to_cpu(w->firmware_version);
137 info->capabilities = le32_to_cpu(w->capabilities);
138 memcpy(info->device_specific, w->device_specific,
139 sizeof(info->device_specific));
140 info->event_queue_len = w->event_queue_len;
141}
142
143static int arhboard_open(struct inode *inode, struct file *file)
144{
145 struct usb_interface *intf;
146 struct arhboard *dev;
147
148 intf = usb_find_interface(&arhboard_driver, iminor(inode));
149 if (!intf)
150 return -ENODEV;
151 dev = usb_get_intfdata(intf);
152 if (!dev)
153 return -ENODEV;
154
155 kref_get(&dev->kref);
156 file->private_data = dev;
157 return 0;
158}
159
160static int arhboard_release(struct inode *inode, struct file *file)
161{
162 struct arhboard *dev = file->private_data;
163
164 kref_put(&dev->kref, arhboard_delete);
165 return 0;
166}
167
168/*
169 * Wait for the next event, and return it as one line of text. The board keeps
170 * the events until we read them, so nothing is lost while nobody reads.
171 *
172 * The wait is a loop of short transfers: between two of them, the lock is
173 * free (disconnect() can take it), and we look for Ctrl+C and O_NONBLOCK.
174 */
175static ssize_t arhboard_read(struct file *file, char __user *ubuf,
176 size_t count, loff_t *ppos)
177{
178 struct arhboard *dev = file->private_data;
179 struct wire_event *wev = (struct wire_event *)dev->ev_buf;
180 char line[64];
181 int len = 0;
182 int actual;
183 int ret;
184
185 for (;;) {
186 if (mutex_lock_interruptible(&dev->ev_lock))
187 return -ERESTARTSYS;
188 if (dev->gone) {
189 ret = -ENODEV;
190 } else {
191 ret = usb_interrupt_msg(dev->udev, dev->ev_pipe,
192 dev->ev_buf, sizeof(*wev),
193 &actual, SLICE_MS);
194 if (ret == 0 && actual != sizeof(*wev))
195 ret = -EPROTO;
196 if (ret == 0)
197 len = scnprintf(line, sizeof(line),
198 "seq=%u time=%u type=0x%02x arg=%u\n",
199 le16_to_cpu(wev->seq),
200 le32_to_cpu(wev->time_ms),
201 wev->type, wev->arg);
202 }
203 mutex_unlock(&dev->ev_lock);
204
205 if (ret != -ETIMEDOUT)
206 break;
207 /* No event in this slice */
208 if (file->f_flags & O_NONBLOCK)
209 return -EAGAIN;
210 if (signal_pending(current))
211 return -ERESTARTSYS;
212 }
213 if (ret)
214 return ret;
215
216 if (count < len)
217 return -EINVAL; /* one event per read(), and it must fit */
218 if (copy_to_user(ubuf, line, len))
219 return -EFAULT;
220 return len;
221}
222
223/* Set the label: up to 16 bytes, a final '\n' is dropped */
224static ssize_t arhboard_write(struct file *file, const char __user *ubuf,
225 size_t count, loff_t *ppos)
226{
227 struct arhboard *dev = file->private_data;
228 char label[ARHBOARD_LABEL_LEN + 1] = {};
229 size_t len = count;
230 int ret;
231
232 if (len > ARHBOARD_LABEL_LEN + 1)
233 return -EINVAL;
234 if (copy_from_user(label, ubuf, len))
235 return -EFAULT;
236 if (len > 0 && label[len - 1] == '\n')
237 len--;
238 if (len > ARHBOARD_LABEL_LEN)
239 return -EINVAL;
240
241 mutex_lock(&dev->ctrl_lock);
242 if (dev->gone) {
243 ret = -ENODEV;
244 } else {
245 memset(dev->ctrl_buf, 0, ARHBOARD_LABEL_LEN); /* padded with '\0' */
246 memcpy(dev->ctrl_buf, label, len);
247 ret = arhboard_ctrl_out(dev, REQ_SET_LABEL, 0, ARHBOARD_LABEL_LEN);
248 }
249 mutex_unlock(&dev->ctrl_lock);
250
251 return ret ? ret : count;
252}
253
254static long arhboard_ioctl(struct file *file, unsigned int cmd,
255 unsigned long arg)
256{
257 struct arhboard *dev = file->private_data;
258 void __user *uarg = (void __user *)arg;
259 union {
260 struct arhboard_info info;
261 struct arhboard_status status;
262 struct arhboard_label label;
263 } out = {}; /* zeroed: no kernel memory leaks to user space */
264 size_t out_len = 0;
265 u32 flashes;
266 int ret;
267
268 /* Read the argument before taking the lock */
269 if (cmd == ARHBOARD_IOC_IDENTIFY) {
270 if (copy_from_user(&flashes, uarg, sizeof(flashes)))
271 return -EFAULT;
272 if (flashes > U16_MAX) /* it travels in wValue, 16 bits */
273 return -EINVAL;
274 }
275
276 mutex_lock(&dev->ctrl_lock);
277 if (dev->gone) {
278 ret = -ENODEV;
279 goto out_unlock;
280 }
281
282 switch (cmd) {
283 case ARHBOARD_IOC_GET_INFO:
284 ret = arhboard_ctrl_in(dev, REQ_GET_INFO, sizeof(struct wire_info));
285 if (ret)
286 break;
287 info_from_wire(&out.info, (struct wire_info *)dev->ctrl_buf);
288 out_len = sizeof(out.info);
289 break;
290
291 case ARHBOARD_IOC_GET_STATUS: {
292 struct wire_status *w = (struct wire_status *)dev->ctrl_buf;
293
294 ret = arhboard_ctrl_in(dev, REQ_GET_BOARD_STATUS, sizeof(*w));
295 if (ret)
296 break;
297 out.status.uptime_ms = le32_to_cpu(w->uptime_ms);
298 out.status.events_dropped = le16_to_cpu(w->events_dropped);
299 out.status.events_queued = w->events_queued;
300 out.status.button_down = w->button_down;
301 out_len = sizeof(out.status);
302 break;
303 }
304
305 case ARHBOARD_IOC_GET_LABEL:
306 ret = arhboard_ctrl_in(dev, REQ_GET_LABEL, ARHBOARD_LABEL_LEN);
307 if (ret)
308 break;
309 /* out.label.label[16] stays '\0' */
310 memcpy(out.label.label, dev->ctrl_buf, ARHBOARD_LABEL_LEN);
311 out_len = sizeof(out.label);
312 break;
313
314 case ARHBOARD_IOC_IDENTIFY:
315 /* No data stage: the number travels in wValue */
316 ret = arhboard_ctrl_out(dev, REQ_IDENTIFY, flashes, 0);
317 break;
318
319 default:
320 ret = -ENOTTY;
321 break;
322 }
323
324out_unlock:
325 mutex_unlock(&dev->ctrl_lock);
326
327 if (ret == 0 && out_len && copy_to_user(uarg, &out, out_len))
328 ret = -EFAULT;
329 return ret;
330}
331
332static const struct file_operations arhboard_fops = {
333 .owner = THIS_MODULE,
334 .open = arhboard_open,
335 .release = arhboard_release,
336 .read = arhboard_read,
337 .write = arhboard_write,
338 .unlocked_ioctl = arhboard_ioctl,
339 .compat_ioctl = compat_ptr_ioctl,
340};
341
342static char *arhboard_devnode(const struct device *dev, umode_t *mode)
343{
344 if (mode)
345 *mode = 0666;
346 return NULL;
347}
348
349/* /dev/arhboard0, /dev/arhboard1, ...: major 180, minors from 192 */
350static struct usb_class_driver arhboard_class = {
351 .name = "arhboard%d",
352 .devnode = arhboard_devnode,
353 .fops = &arhboard_fops,
354 .minor_base = ARHBOARD_MINOR_BASE,
355};
356
357static int arhboard_probe(struct usb_interface *intf,
358 const struct usb_device_id *id)
359{
360 struct usb_endpoint_descriptor *ev_ep;
361 struct arhboard_info info;
362 struct arhboard *dev;
363 int ret;
364
365 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
366 if (!dev)
367 return -ENOMEM;
368 kref_init(&dev->kref);
369 mutex_init(&dev->ctrl_lock);
370 mutex_init(&dev->ev_lock);
371 dev->udev = usb_get_dev(interface_to_usbdev(intf));
372 dev->intf = usb_get_intf(intf);
373
374 dev->ctrl_buf = kmalloc(CTRL_BUF_LEN, GFP_KERNEL);
375 dev->ev_buf = kmalloc(sizeof(struct wire_event), GFP_KERNEL);
376 if (!dev->ctrl_buf || !dev->ev_buf) {
377 ret = -ENOMEM;
378 goto err;
379 }
380
381 /* The event endpoint: the first interrupt IN endpoint */
382 ret = usb_find_int_in_endpoint(intf->cur_altsetting, &ev_ep);
383 if (ret) {
384 dev_err(&intf->dev, "no interrupt IN endpoint\n");
385 goto err;
386 }
387 if (usb_endpoint_maxp(ev_ep) != sizeof(struct wire_event)) {
388 dev_err(&intf->dev, "event endpoint is not 8 bytes\n");
389 ret = -ENODEV;
390 goto err;
391 }
392 dev->ev_pipe = usb_rcvintpipe(dev->udev, ev_ep->bEndpointAddress);
393
394 /* Is it really a lab board? */
395 ret = arhboard_ctrl_in(dev, REQ_GET_INFO, sizeof(struct wire_info));
396 if (ret) {
397 dev_err(&intf->dev, "GET_INFO failed: %pe\n", ERR_PTR(ret));
398 goto err;
399 }
400 info_from_wire(&info, (struct wire_info *)dev->ctrl_buf);
401 if ((info.magic & 0x00ffffff) != MAGIC_ARH) {
402 dev_err(&intf->dev, "not a lab board (magic 0x%08x)\n",
403 info.magic);
404 ret = -ENODEV;
405 goto err;
406 }
407
408 usb_set_intfdata(intf, dev);
409 ret = usb_register_dev(intf, &arhboard_class);
410 if (ret) {
411 dev_err(&intf->dev, "no minor number: %pe\n", ERR_PTR(ret));
412 usb_set_intfdata(intf, NULL);
413 goto err;
414 }
415
416 dev_info(&intf->dev,
417 "project '%c', protocol %u.%u, firmware %u.%u, /dev/arhboard%d\n",
418 (char)(info.magic >> 24), info.protocol_version >> 8,
419 info.protocol_version & 0xff, info.firmware_version >> 8,
420 info.firmware_version & 0xff, intf->minor - ARHBOARD_MINOR_BASE);
421 return 0;
422
423err:
424 kref_put(&dev->kref, arhboard_delete);
425 return ret;
426}
427
428static void arhboard_disconnect(struct usb_interface *intf)
429{
430 struct arhboard *dev = usb_get_intfdata(intf);
431
432 /* No new open() from now on */
433 usb_deregister_dev(intf, &arhboard_class);
434 usb_set_intfdata(intf, NULL);
435
436 /*
437 * Calls already running notice within one slice. Taking each lock
438 * waits for the transfer which holds it, if any.
439 */
440 mutex_lock(&dev->ctrl_lock);
441 mutex_lock(&dev->ev_lock);
442 dev->gone = true;
443 mutex_unlock(&dev->ev_lock);
444 mutex_unlock(&dev->ctrl_lock);
445
446 dev_info(&intf->dev, "unplugged\n");
447 /* Freed now, or at the last close() */
448 kref_put(&dev->kref, arhboard_delete);
449}
450
451/* The seven lab boards: vendor 0xcafe, one product ID per project */
452static const struct usb_device_id arhboard_ids[] = {
453 { USB_DEVICE(0xcafe, 0x4301) }, /* CC-1 */
454 { USB_DEVICE(0xcafe, 0x4302) }, /* EL-2 */
455 { USB_DEVICE(0xcafe, 0x4303) }, /* FV-3 */
456 { USB_DEVICE(0xcafe, 0x4304) }, /* MB-4 */
457 { USB_DEVICE(0xcafe, 0x4305) }, /* TW-5 */
458 { USB_DEVICE(0xcafe, 0x4306) }, /* WP-6 */
459 { USB_DEVICE(0xcafe, 0x4307) }, /* BP-7 */
460 {}
461};
462MODULE_DEVICE_TABLE(usb, arhboard_ids);
463
464static struct usb_driver arhboard_driver = {
465 .name = "arhboard",
466 .probe = arhboard_probe,
467 .disconnect = arhboard_disconnect,
468 .id_table = arhboard_ids,
469};
470
471module_usb_driver(arhboard_driver);
472
473MODULE_LICENSE("GPL");
474MODULE_AUTHOR("OS Lab");
475MODULE_DESCRIPTION("Example USB driver for any lab board");
And its shared header, uapi/arhboard_ioctl.h:
1/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
2/*
3 * The interface between the arhboard driver and user space: ioctl numbers
4 * and their structures. Shared by the driver and by programs, so it only
5 * uses the __u8 ... __u32 types.
6 *
7 * The values here are in the byte order of the machine: the driver converts
8 * them from the device's little-endian structures.
9 */
10#ifndef ARHBOARD_IOCTL_H
11#define ARHBOARD_IOCTL_H
12
13#include <linux/ioctl.h>
14#include <linux/types.h>
15
16#define ARHBOARD_LABEL_LEN 16
17
18/* GET_INFO: what the board says about itself */
19struct arhboard_info {
20 __u32 magic; /* "ARH" + one character per project */
21 __u16 protocol_version; /* major in the high byte, minor in the low byte */
22 __u16 firmware_version;
23 __u32 capabilities; /* bits defined by the project */
24 __u8 device_specific[3];
25 __u8 event_queue_len; /* unread events the board keeps */
26};
27
28/* GET_BOARD_STATUS */
29struct arhboard_status {
30 __u32 uptime_ms; /* since power-up */
31 __u16 events_dropped; /* lost because the board's queue was full */
32 __u8 events_queued; /* waiting to be read, now */
33 __u8 button_down; /* 1 while the button is held */
34};
35
36/* GET_LABEL: always ends with '\0' */
37struct arhboard_label {
38 char label[ARHBOARD_LABEL_LEN + 1];
39};
40
41#define ARHBOARD_IOC_MAGIC 0xB8
42#define ARHBOARD_IOC_GET_INFO _IOR(ARHBOARD_IOC_MAGIC, 1, struct arhboard_info)
43#define ARHBOARD_IOC_GET_STATUS _IOR(ARHBOARD_IOC_MAGIC, 2, struct arhboard_status)
44#define ARHBOARD_IOC_GET_LABEL _IOR(ARHBOARD_IOC_MAGIC, 3, struct arhboard_label)
45/* Flash the LED: 1 to 10 times. Anything else is refused by the board (EPIPE). */
46#define ARHBOARD_IOC_IDENTIFY _IOW(ARHBOARD_IOC_MAGIC, 4, __u32)
47
48#endif
Try it on your board:
$ make -C driver load
$ sudo dmesg | tail -1
[ 9120.551021] arhboard 1-1:1.0: project '1', protocol 1.0, firmware 1.0, /dev/arhboard0
$ echo bench-3 > /dev/arhboard0 # SET_LABEL
$ cat /dev/arhboard0 # press the button; Ctrl+C to stop
seq=0 time=48213 type=0x01 arg=0
^C
$ make -C driver unload