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:
- check that the interface has the endpoints which the driver expects;
- 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;
- 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
Checking the endpoints
The endpoints of our boards are fixed: every board has the three endpoints which lsusb -v showed above, at the same addresses. So the driver does not search for them. It has their addresses as constants:
/* The endpoints of every board: the addresses which lsusb -v shows */
#define EP_DATA_OUT 0x01 /* bulk OUT */
#define EP_DATA_IN 0x81 /* bulk IN */
#define EP_EVENT 0x82 /* interrupt IN: one event of 8 bytes */
A device with the right VID and PID may still be something else, for example a board which runs other firmware, with other endpoints. Transfers to an endpoint which the device does not have would only fail later, in the middle of a file operation. So probe() first checks that the interface really has these endpoints, and refuses the device if it doesn't. Two functions do the check:
// In: <linux/usb.h>
bool usb_check_bulk_endpoints(const struct usb_interface *intf, const u8 *ep_addrs);
bool usb_check_int_endpoints(const struct usb_interface *intf, const u8 *ep_addrs);
ep_addrs is an array of endpoint addresses, which ends with 0. They return true if the interface has an endpoint at every address in the array, and each of them is a bulk endpoint (or an interrupt endpoint, for the second function). The direction is part of the address, so it is checked too. The example checks its three endpoints at the start of probe(), before it allocates anything:
/* For usb_check_*_endpoints(): lists of addresses, which end with 0 */
static const u8 arhboard_bulk_eps[] = { EP_DATA_OUT, EP_DATA_IN, 0 };
static const u8 arhboard_int_eps[] = { EP_EVENT, 0 };
static int arhboard_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
...
/* Does the interface have the endpoints which we expect? */
if (!usb_check_bulk_endpoints(intf, arhboard_bulk_eps) ||
!usb_check_int_endpoints(intf, arhboard_int_eps)) {
dev_err(&intf->dev, "unexpected endpoints\n");
return -ENODEV;
}
...
The example does not use the bulk endpoints, but every board has them, so it checks them as well. The driver of your project starts with the same check.
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);
dev is the struct usb_device of the whole device, which interface_to_usbdev(intf) returns. The example keeps it in its structure, as dev->udev.
pipe says where the transfer goes. It is not the address of the endpoint alone, but a number which combines the device, the endpoint, its direction and its type. A macro for each kind of endpoint makes it, and we write it directly in the call:
| Endpoint | IN | OUT |
|---|---|---|
| Control (endpoint 0) | usb_rcvctrlpipe(udev, 0) |
usb_sndctrlpipe(udev, 0)
|
| Bulk | usb_rcvbulkpipe(udev, EP_DATA_IN) |
usb_sndbulkpipe(udev, EP_DATA_OUT)
|
| Interrupt | usb_rcvintpipe(udev, EP_EVENT) |
usb_sndintpipe(udev, addr): our boards have none
|
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,
usb_rcvintpipe(dev->udev, EP_EVENT),
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 do not use the bulk endpoints, so neither does the example. 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 64 bytes, the maximum packet size of our bulk endpoints.
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, usb_rcvbulkpipe(dev->udev, EP_DATA_IN),
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);
pipe is made as for a transfer: usb_clear_halt(dev->udev, usb_rcvbulkpipe(dev->udev, EP_DATA_IN)). The example driver does not use the 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;
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/* The endpoints of every board: the addresses which lsusb -v shows */
28#define EP_DATA_OUT 0x01 /* bulk OUT */
29#define EP_DATA_IN 0x81 /* bulk IN */
30#define EP_EVENT 0x82 /* interrupt IN: one event of 8 bytes */
31
32/* For usb_check_*_endpoints(): lists of addresses, which end with 0 */
33static const u8 arhboard_bulk_eps[] = { EP_DATA_OUT, EP_DATA_IN, 0 };
34static const u8 arhboard_int_eps[] = { EP_EVENT, 0 };
35
36/* Vendor requests, all to interface 0 */
37#define REQ_GET_INFO 0x00
38#define REQ_IDENTIFY 0xE0
39#define REQ_GET_BOARD_STATUS 0xE1
40#define REQ_SET_LABEL 0xE2
41#define REQ_GET_LABEL 0xE3
42
43#define REQTYPE_IN (USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_INTERFACE) /* 0xC1 */
44#define REQTYPE_OUT (USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_INTERFACE) /* 0x41 */
45
46#define CTRL_TIMEOUT_MS 1000
47/* A long wait is a loop of waits this long: see arhboard_read(). */
48#define SLICE_MS 100
49
50/* What the board sends, exactly as it is on the wire: little-endian */
51struct wire_info {
52 __le32 magic;
53 __le16 protocol_version;
54 __le16 firmware_version;
55 __le32 capabilities;
56 u8 device_specific[3];
57 u8 event_queue_len;
58};
59
60struct wire_status {
61 __le32 uptime_ms;
62 __le16 events_dropped;
63 u8 events_queued;
64 u8 button_down;
65};
66
67struct wire_event {
68 u8 type;
69 u8 arg;
70 __le16 seq;
71 __le32 time_ms;
72};
73
74static_assert(sizeof(struct wire_info) == 16);
75static_assert(sizeof(struct wire_status) == 8);
76static_assert(sizeof(struct wire_event) == 8);
77
78#define MAGIC_ARH 0x00485241 /* "ARH" in the low three bytes */
79#define CTRL_BUF_LEN 16
80
81/* Everything the driver knows about one board */
82struct arhboard {
83 struct usb_device *udev;
84 struct usb_interface *intf;
85 struct kref kref; /* probe() holds one reference, each open file one */
86
87 struct mutex ctrl_lock; /* control transfers, ctrl_buf */
88 u8 *ctrl_buf; /* kmalloc()ed: the controller reads it by DMA */
89
90 struct mutex ev_lock; /* the event endpoint, ev_buf */
91 u8 *ev_buf;
92
93 bool gone; /* unplugged: written under both locks */
94};
95
96static struct usb_driver arhboard_driver;
97
98static void arhboard_delete(struct kref *kref)
99{
100 struct arhboard *dev = container_of(kref, struct arhboard, kref);
101
102 kfree(dev->ev_buf);
103 kfree(dev->ctrl_buf);
104 usb_put_intf(dev->intf);
105 usb_put_dev(dev->udev);
106 kfree(dev);
107}
108
109/*
110 * Control transfers. The caller holds ctrl_lock (or is probe(), before the
111 * device can be opened). The data is in dev->ctrl_buf.
112 */
113static int arhboard_ctrl_in(struct arhboard *dev, u8 request, u16 len)
114{
115 int ret = usb_control_msg(dev->udev, usb_rcvctrlpipe(dev->udev, 0),
116 request, REQTYPE_IN, 0, 0, dev->ctrl_buf, len,
117 CTRL_TIMEOUT_MS);
118 if (ret < 0)
119 return ret; /* -EPIPE: the board refused (STALL) */
120 if (ret != len)
121 return -EPROTO; /* a short answer is an error too */
122 return 0;
123}
124
125static int arhboard_ctrl_out(struct arhboard *dev, u8 request, u16 value,
126 u16 len)
127{
128 int ret = usb_control_msg(dev->udev, usb_sndctrlpipe(dev->udev, 0),
129 request, REQTYPE_OUT, value, 0,
130 len ? dev->ctrl_buf : NULL, len,
131 CTRL_TIMEOUT_MS);
132 if (ret < 0)
133 return ret;
134 if (ret != len)
135 return -EPROTO;
136 return 0;
137}
138
139static void info_from_wire(struct arhboard_info *info,
140 const struct wire_info *w)
141{
142 info->magic = le32_to_cpu(w->magic);
143 info->protocol_version = le16_to_cpu(w->protocol_version);
144 info->firmware_version = le16_to_cpu(w->firmware_version);
145 info->capabilities = le32_to_cpu(w->capabilities);
146 memcpy(info->device_specific, w->device_specific,
147 sizeof(info->device_specific));
148 info->event_queue_len = w->event_queue_len;
149}
150
151static int arhboard_open(struct inode *inode, struct file *file)
152{
153 struct usb_interface *intf;
154 struct arhboard *dev;
155
156 intf = usb_find_interface(&arhboard_driver, iminor(inode));
157 if (!intf)
158 return -ENODEV;
159 dev = usb_get_intfdata(intf);
160 if (!dev)
161 return -ENODEV;
162
163 kref_get(&dev->kref);
164 file->private_data = dev;
165 return 0;
166}
167
168static int arhboard_release(struct inode *inode, struct file *file)
169{
170 struct arhboard *dev = file->private_data;
171
172 kref_put(&dev->kref, arhboard_delete);
173 return 0;
174}
175
176/*
177 * Wait for the next event, and return it as one line of text. The board keeps
178 * the events until we read them, so nothing is lost while nobody reads.
179 *
180 * The wait is a loop of short transfers: between two of them, the lock is
181 * free (disconnect() can take it), and we look for Ctrl+C and O_NONBLOCK.
182 */
183static ssize_t arhboard_read(struct file *file, char __user *ubuf,
184 size_t count, loff_t *ppos)
185{
186 struct arhboard *dev = file->private_data;
187 struct wire_event *wev = (struct wire_event *)dev->ev_buf;
188 char line[64];
189 int len = 0;
190 int actual;
191 int ret;
192
193 for (;;) {
194 if (mutex_lock_interruptible(&dev->ev_lock))
195 return -ERESTARTSYS;
196 if (dev->gone) {
197 ret = -ENODEV;
198 } else {
199 ret = usb_interrupt_msg(dev->udev,
200 usb_rcvintpipe(dev->udev, EP_EVENT),
201 dev->ev_buf, sizeof(*wev),
202 &actual, SLICE_MS);
203 if (ret == 0 && actual != sizeof(*wev))
204 ret = -EPROTO;
205 if (ret == 0)
206 len = scnprintf(line, sizeof(line),
207 "seq=%u time=%u type=0x%02x arg=%u\n",
208 le16_to_cpu(wev->seq),
209 le32_to_cpu(wev->time_ms),
210 wev->type, wev->arg);
211 }
212 mutex_unlock(&dev->ev_lock);
213
214 if (ret != -ETIMEDOUT)
215 break;
216 /* No event in this slice */
217 if (file->f_flags & O_NONBLOCK)
218 return -EAGAIN;
219 if (signal_pending(current))
220 return -ERESTARTSYS;
221 }
222 if (ret)
223 return ret;
224
225 if (count < len)
226 return -EINVAL; /* one event per read(), and it must fit */
227 if (copy_to_user(ubuf, line, len))
228 return -EFAULT;
229 return len;
230}
231
232/* Set the label: up to 16 bytes, a final '\n' is dropped */
233static ssize_t arhboard_write(struct file *file, const char __user *ubuf,
234 size_t count, loff_t *ppos)
235{
236 struct arhboard *dev = file->private_data;
237 char label[ARHBOARD_LABEL_LEN + 1] = {};
238 size_t len = count;
239 int ret;
240
241 if (len > ARHBOARD_LABEL_LEN + 1)
242 return -EINVAL;
243 if (copy_from_user(label, ubuf, len))
244 return -EFAULT;
245 if (len > 0 && label[len - 1] == '\n')
246 len--;
247 if (len > ARHBOARD_LABEL_LEN)
248 return -EINVAL;
249
250 mutex_lock(&dev->ctrl_lock);
251 if (dev->gone) {
252 ret = -ENODEV;
253 } else {
254 memset(dev->ctrl_buf, 0, ARHBOARD_LABEL_LEN); /* padded with '\0' */
255 memcpy(dev->ctrl_buf, label, len);
256 ret = arhboard_ctrl_out(dev, REQ_SET_LABEL, 0, ARHBOARD_LABEL_LEN);
257 }
258 mutex_unlock(&dev->ctrl_lock);
259
260 return ret ? ret : count;
261}
262
263static long arhboard_ioctl(struct file *file, unsigned int cmd,
264 unsigned long arg)
265{
266 struct arhboard *dev = file->private_data;
267 void __user *uarg = (void __user *)arg;
268 union {
269 struct arhboard_info info;
270 struct arhboard_status status;
271 struct arhboard_label label;
272 } out = {}; /* zeroed: no kernel memory leaks to user space */
273 size_t out_len = 0;
274 u32 flashes;
275 int ret;
276
277 /* Read the argument before taking the lock */
278 if (cmd == ARHBOARD_IOC_IDENTIFY) {
279 if (copy_from_user(&flashes, uarg, sizeof(flashes)))
280 return -EFAULT;
281 if (flashes > U16_MAX) /* it travels in wValue, 16 bits */
282 return -EINVAL;
283 }
284
285 mutex_lock(&dev->ctrl_lock);
286 if (dev->gone) {
287 ret = -ENODEV;
288 goto out_unlock;
289 }
290
291 switch (cmd) {
292 case ARHBOARD_IOC_GET_INFO:
293 ret = arhboard_ctrl_in(dev, REQ_GET_INFO, sizeof(struct wire_info));
294 if (ret)
295 break;
296 info_from_wire(&out.info, (struct wire_info *)dev->ctrl_buf);
297 out_len = sizeof(out.info);
298 break;
299
300 case ARHBOARD_IOC_GET_STATUS: {
301 struct wire_status *w = (struct wire_status *)dev->ctrl_buf;
302
303 ret = arhboard_ctrl_in(dev, REQ_GET_BOARD_STATUS, sizeof(*w));
304 if (ret)
305 break;
306 out.status.uptime_ms = le32_to_cpu(w->uptime_ms);
307 out.status.events_dropped = le16_to_cpu(w->events_dropped);
308 out.status.events_queued = w->events_queued;
309 out.status.button_down = w->button_down;
310 out_len = sizeof(out.status);
311 break;
312 }
313
314 case ARHBOARD_IOC_GET_LABEL:
315 ret = arhboard_ctrl_in(dev, REQ_GET_LABEL, ARHBOARD_LABEL_LEN);
316 if (ret)
317 break;
318 /* out.label.label[16] stays '\0' */
319 memcpy(out.label.label, dev->ctrl_buf, ARHBOARD_LABEL_LEN);
320 out_len = sizeof(out.label);
321 break;
322
323 case ARHBOARD_IOC_IDENTIFY:
324 /* No data stage: the number travels in wValue */
325 ret = arhboard_ctrl_out(dev, REQ_IDENTIFY, flashes, 0);
326 break;
327
328 default:
329 ret = -ENOTTY;
330 break;
331 }
332
333out_unlock:
334 mutex_unlock(&dev->ctrl_lock);
335
336 if (ret == 0 && out_len && copy_to_user(uarg, &out, out_len))
337 ret = -EFAULT;
338 return ret;
339}
340
341static const struct file_operations arhboard_fops = {
342 .owner = THIS_MODULE,
343 .open = arhboard_open,
344 .release = arhboard_release,
345 .read = arhboard_read,
346 .write = arhboard_write,
347 .unlocked_ioctl = arhboard_ioctl,
348 .compat_ioctl = compat_ptr_ioctl,
349};
350
351static char *arhboard_devnode(const struct device *dev, umode_t *mode)
352{
353 if (mode)
354 *mode = 0666;
355 return NULL;
356}
357
358/* /dev/arhboard0, /dev/arhboard1, ...: major 180, minors from 192 */
359static struct usb_class_driver arhboard_class = {
360 .name = "arhboard%d",
361 .devnode = arhboard_devnode,
362 .fops = &arhboard_fops,
363 .minor_base = ARHBOARD_MINOR_BASE,
364};
365
366static int arhboard_probe(struct usb_interface *intf,
367 const struct usb_device_id *id)
368{
369 struct arhboard_info info;
370 struct arhboard *dev;
371 int ret;
372
373 /* Does the interface have the endpoints which we expect? */
374 if (!usb_check_bulk_endpoints(intf, arhboard_bulk_eps) ||
375 !usb_check_int_endpoints(intf, arhboard_int_eps)) {
376 dev_err(&intf->dev, "unexpected endpoints\n");
377 return -ENODEV;
378 }
379
380 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
381 if (!dev)
382 return -ENOMEM;
383 kref_init(&dev->kref);
384 mutex_init(&dev->ctrl_lock);
385 mutex_init(&dev->ev_lock);
386 dev->udev = usb_get_dev(interface_to_usbdev(intf));
387 dev->intf = usb_get_intf(intf);
388
389 dev->ctrl_buf = kmalloc(CTRL_BUF_LEN, GFP_KERNEL);
390 dev->ev_buf = kmalloc(sizeof(struct wire_event), GFP_KERNEL);
391 if (!dev->ctrl_buf || !dev->ev_buf) {
392 ret = -ENOMEM;
393 goto err;
394 }
395
396 /* Is it really a lab board? */
397 ret = arhboard_ctrl_in(dev, REQ_GET_INFO, sizeof(struct wire_info));
398 if (ret) {
399 dev_err(&intf->dev, "GET_INFO failed: %pe\n", ERR_PTR(ret));
400 goto err;
401 }
402 info_from_wire(&info, (struct wire_info *)dev->ctrl_buf);
403 if ((info.magic & 0x00ffffff) != MAGIC_ARH) {
404 dev_err(&intf->dev, "not a lab board (magic 0x%08x)\n",
405 info.magic);
406 ret = -ENODEV;
407 goto err;
408 }
409
410 usb_set_intfdata(intf, dev);
411 ret = usb_register_dev(intf, &arhboard_class);
412 if (ret) {
413 dev_err(&intf->dev, "no minor number: %pe\n", ERR_PTR(ret));
414 usb_set_intfdata(intf, NULL);
415 goto err;
416 }
417
418 dev_info(&intf->dev,
419 "project '%c', protocol %u.%u, firmware %u.%u, /dev/arhboard%d\n",
420 (char)(info.magic >> 24), info.protocol_version >> 8,
421 info.protocol_version & 0xff, info.firmware_version >> 8,
422 info.firmware_version & 0xff, intf->minor - ARHBOARD_MINOR_BASE);
423 return 0;
424
425err:
426 kref_put(&dev->kref, arhboard_delete);
427 return ret;
428}
429
430static void arhboard_disconnect(struct usb_interface *intf)
431{
432 struct arhboard *dev = usb_get_intfdata(intf);
433
434 /* No new open() from now on */
435 usb_deregister_dev(intf, &arhboard_class);
436 usb_set_intfdata(intf, NULL);
437
438 /*
439 * Calls already running notice within one slice. Taking each lock
440 * waits for the transfer which holds it, if any.
441 */
442 mutex_lock(&dev->ctrl_lock);
443 mutex_lock(&dev->ev_lock);
444 dev->gone = true;
445 mutex_unlock(&dev->ev_lock);
446 mutex_unlock(&dev->ctrl_lock);
447
448 dev_info(&intf->dev, "unplugged\n");
449 /* Freed now, or at the last close() */
450 kref_put(&dev->kref, arhboard_delete);
451}
452
453/* The seven lab boards: vendor 0xcafe, one product ID per project */
454static const struct usb_device_id arhboard_ids[] = {
455 { USB_DEVICE(0xcafe, 0x4301) }, /* CC-1 */
456 { USB_DEVICE(0xcafe, 0x4302) }, /* EL-2 */
457 { USB_DEVICE(0xcafe, 0x4303) }, /* FV-3 */
458 { USB_DEVICE(0xcafe, 0x4304) }, /* MB-4 */
459 { USB_DEVICE(0xcafe, 0x4305) }, /* TW-5 */
460 { USB_DEVICE(0xcafe, 0x4306) }, /* WP-6 */
461 { USB_DEVICE(0xcafe, 0x4307) }, /* BP-7 */
462 {}
463};
464MODULE_DEVICE_TABLE(usb, arhboard_ids);
465
466static struct usb_driver arhboard_driver = {
467 .name = "arhboard",
468 .probe = arhboard_probe,
469 .disconnect = arhboard_disconnect,
470 .id_table = arhboard_ids,
471};
472
473module_usb_driver(arhboard_driver);
474
475MODULE_LICENSE("GPL");
476MODULE_AUTHOR("OS Lab");
477MODULE_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