Files
unkernel/test/usb/usbtest.c

553 lines
17 KiB
C

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
// Guest side of test/usb.test.ts: drives the SDK's test device
// (js/core/usb-fake.ts FakeUsbBackend, 1209:0001) through usbfs
// (/dev/bus/usb/BBB/DDD) on kwusb, without libusb. Static aarch64 musl,
// built by the test:
//
// zig cc -target aarch64-linux-musl -mcpu=generic -static -O2 -s -o usbtest test/usb/usbtest.c
//
// usbtest run [CPU] the whole sequence below, on CPU if given
// usbtest quick SPEED enumeration and a loopback; the device's sysfs speed must be SPEED
// usbtest bench MIB bulk loopback of MIB MiB, 4 URBs of 256 KiB each way in flight
// usbtest park OUT claim, submit a bulk IN, say "ready", wait in REAPURB; then write
// the URB's status and what the next ioctl gave to OUT
//
// `run` prints one line per check, "ok NAME ..." or "FAIL NAME: ...", and at
// each "step NAME" line waits for a line on stdin while the host acts or
// checks its side. The last line is "done N failure(s)", exit 0 without one.
// The steps: the descriptors usbfs gives (the HID interface hidden),
// GET_CAPABILITIES (scatter-gather), vendor control requests both ways, a
// bulk loopback of 4 MiB at once (scatter-gather) and of 8 MiB with URBs
// in flight, a zero-length packet (URB_ZERO_PACKET), a short read, an
// interrupt IN, an unlinked IN whose data reaches the next URB, a stall
// and CLEAR_HALT, isochronous IN in alternate setting 1, USBDEVFS_RESET (the
// device is reset and configured again), URBs pending when the device is
// unplugged (ESHUTDOWN, then ENODEV), and a new device in the port.
#define _GNU_SOURCE
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/usb/ch9.h>
#include <linux/usbdevice_fs.h>
#include <sched.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <time.h>
#include <unistd.h>
#define VID 0x1209
#define PID 0x0001
static int failures;
static void out(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vprintf(fmt, ap);
va_end(ap);
putchar('\n');
fflush(stdout);
}
#define CHECK(name, cond, ...) do { \
if (cond) out("ok %s", name); \
else { failures++; printf("FAIL %s: ", name); printf(__VA_ARGS__); putchar('\n'); fflush(stdout); } \
} while (0)
static void step(const char *name)
{
char line[64];
out("step %s", name);
if (!fgets(line, sizeof(line), stdin))
exit(3);
}
static double now(void)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ts.tv_sec + ts.tv_nsec / 1e9;
}
static int read_attr(const char *dir, const char *name, char *buf, size_t n)
{
char path[512];
int fd, r;
snprintf(path, sizeof(path), "/sys/bus/usb/devices/%s/%s", dir, name);
fd = open(path, O_RDONLY);
if (fd < 0)
return -1;
r = read(fd, buf, n - 1);
close(fd);
if (r < 0)
return -1;
buf[r] = 0;
if (r && buf[r - 1] == '\n')
buf[r - 1] = 0;
return 0;
}
/* The test device's node and sysfs name, waiting up to `secs` for it (and for a devnum other than `not`). */
static int find(int secs, int not, char *node, size_t n, char *sysname, int *devnum)
{
double end = now() + secs;
do {
DIR *d = opendir("/sys/bus/usb/devices");
struct dirent *e;
while (d && (e = readdir(d))) {
char v[16], p[16], b[16], dn[16];
if (e->d_name[0] == '.' || strchr(e->d_name, ':'))
continue;
if (read_attr(e->d_name, "idVendor", v, sizeof(v)) || read_attr(e->d_name, "idProduct", p, sizeof(p)))
continue;
if (strtol(v, 0, 16) != VID || strtol(p, 0, 16) != PID)
continue;
if (read_attr(e->d_name, "busnum", b, sizeof(b)) || read_attr(e->d_name, "devnum", dn, sizeof(dn)))
continue;
if (atoi(dn) == not)
continue;
snprintf(node, n, "/dev/bus/usb/%03d/%03d", atoi(b), atoi(dn));
if (access(node, R_OK | W_OK))
continue;
if (sysname)
snprintf(sysname, 64, "%s", e->d_name);
if (devnum)
*devnum = atoi(dn);
closedir(d);
return 0;
}
if (d)
closedir(d);
usleep(50000);
} while (now() < end);
return -1;
}
static int ctrl(int fd, uint8_t type, uint8_t req, uint16_t value, uint16_t index, void *data, uint16_t len)
{
struct usbdevfs_ctrltransfer c = {
.bRequestType = type, .bRequest = req, .wValue = value, .wIndex = index, .wLength = len, .timeout = 5000, .data = data,
};
return ioctl(fd, USBDEVFS_CONTROL, &c);
}
static int bulk(int fd, unsigned int ep, void *data, unsigned int len, unsigned int timeout)
{
struct usbdevfs_bulktransfer b = { .ep = ep, .len = len, .timeout = timeout, .data = data };
return ioctl(fd, USBDEVFS_BULK, &b);
}
static int submit(int fd, struct usbdevfs_urb *u, unsigned char type, unsigned char ep, void *buf, int len, unsigned int flags)
{
memset(u, 0, sizeof(*u));
u->type = type;
u->endpoint = ep;
u->buffer = buf;
u->buffer_length = len;
u->flags = flags;
return ioctl(fd, USBDEVFS_SUBMITURB, u);
}
/* The next finished URB; a wait a signal ends (a snapshot parks every task so) is taken up again, as libusb does. */
static struct usbdevfs_urb *reap(int fd)
{
struct usbdevfs_urb *u = NULL;
int r;
while ((r = ioctl(fd, USBDEVFS_REAPURB, &u)) < 0 && errno == EINTR)
;
return r < 0 ? NULL : u;
}
static void fill(uint8_t *b, size_t n, uint32_t seed)
{
for (size_t i = 0; i < n; i++) {
seed = seed * 1103515245 + 12345;
b[i] = seed >> 24;
}
}
static int claim(int fd)
{
unsigned int i = 0;
return ioctl(fd, USBDEVFS_CLAIMINTERFACE, &i);
}
static int open_dev(int secs, int not, char *sysname, int *devnum)
{
char node[64];
if (find(secs, not, node, sizeof(node), sysname, devnum))
return -1;
return open(node, O_RDWR);
}
/* Bulk loopback of `total` bytes, `depth` URBs of `chunk` bytes in flight each way: MB/s, or -1. */
static double loopback(int fd, size_t total, size_t chunk, int depth)
{
struct usbdevfs_urb *outs = calloc(depth, sizeof(*outs)), *ins = calloc(depth, sizeof(*ins));
uint8_t *src = malloc(total), *dst = malloc(total);
size_t sent = 0, recvd = 0, outq = 0, inq = 0; /* outq: OUT URBs in flight */
int bad = 0, i;
double t0;
fill(src, total, 7);
memset(dst, 0, total);
t0 = now();
for (i = 0; i < depth; i++) {
if (sent < total) {
size_t n = total - sent < chunk ? total - sent : chunk;
if (submit(fd, &outs[i], USBDEVFS_URB_TYPE_BULK, 0x01, src + sent, n, 0))
return -1;
sent += n;
outq++;
}
if (inq * chunk < total) {
if (submit(fd, &ins[i], USBDEVFS_URB_TYPE_BULK, 0x81, dst + inq * chunk, chunk, 0))
return -1;
inq++;
}
}
while (recvd < total) {
struct usbdevfs_urb *u = reap(fd);
if (!u || u->status) {
bad = 1;
break;
}
if (u->endpoint == 0x01) {
outq--;
if (sent < total) {
size_t n = total - sent < chunk ? total - sent : chunk;
if (submit(fd, u, USBDEVFS_URB_TYPE_BULK, 0x01, src + sent, n, 0))
return -1;
sent += n;
outq++;
}
} else {
recvd += u->actual_length;
if (inq * chunk < total) {
if (submit(fd, u, USBDEVFS_URB_TYPE_BULK, 0x81, dst + inq * chunk, chunk, 0))
return -1;
inq++;
}
}
}
/* The OUT URBs not reaped yet (their bytes all came back). */
while (!bad && outq) {
struct usbdevfs_urb *u = reap(fd);
if (!u || u->status)
bad = 1;
outq--;
}
t0 = now() - t0;
if (bad || memcmp(src, dst, total))
t0 = -1;
free(src);
free(dst);
free(outs);
free(ins);
return t0 < 0 ? -1 : total / t0 / 1e6;
}
static int run(void)
{
char sysname[64], speed[16];
uint8_t desc[512], buf[4096], big_check;
int fd, r, devnum = 0;
unsigned int caps = 0;
struct usbdevfs_urb u1, u2, *u;
fd = open_dev(30, 0, sysname, &devnum);
CHECK("open", fd >= 0, "no %04x:%04x in /dev/bus/usb (%s)", VID, PID, strerror(errno));
if (fd < 0)
return 1;
read_attr(sysname, "speed", speed, sizeof(speed));
CHECK("speed", !strcmp(speed, "480"), "sysfs speed %s, want 480", speed);
/* usbfs reads give the device descriptor, then the configuration as the guest sees it. */
r = read(fd, desc, sizeof(desc));
CHECK("descriptors", r > 18 + 9 && desc[18 + 1] == USB_DT_CONFIG && desc[18 + 4] == 1,
"read %d, bNumInterfaces %d", r, r > 22 ? desc[18 + 4] : -1);
{
int hid = 0;
for (int i = 18; i + 2 <= r && desc[i] >= 2; i += desc[i])
if (desc[i + 1] == USB_DT_INTERFACE && desc[i + 5] == USB_CLASS_HID)
hid = 1;
CHECK("hid hidden", !hid, "the configuration has a HID interface");
}
r = ioctl(fd, USBDEVFS_GET_CAPABILITIES, &caps);
CHECK("capabilities", !r && (caps & USBDEVFS_CAP_BULK_SCATTER_GATHER) && (caps & USBDEVFS_CAP_ZERO_PACKET),
"r %d caps 0x%x", r, caps);
CHECK("claim", !claim(fd), "%s", strerror(errno));
{
unsigned int one = 1;
errno = 0;
r = ioctl(fd, USBDEVFS_CLAIMINTERFACE, &one);
CHECK("no interface 1", r < 0 && errno == ENOENT, "claim of the hidden interface: %d %s", r, strerror(errno));
}
/* Vendor control requests. */
r = ctrl(fd, USB_DIR_OUT | USB_TYPE_VENDOR, 0x02, 0, 0, "hello, device", 13);
memset(buf, 0, sizeof(buf));
r = r == 13 ? ctrl(fd, USB_DIR_IN | USB_TYPE_VENDOR, 0x01, 0, 0, buf, 64) : -1;
CHECK("control", r == 13 && !memcmp(buf, "hello, device", 13), "r %d %s", r, strerror(errno));
r = ctrl(fd, USB_DIR_IN | USB_TYPE_STANDARD, USB_REQ_GET_CONFIGURATION, 0, 0, buf, 1);
CHECK("get configuration", r == 1 && buf[0] == 1, "r %d [%d]", r, buf[0]);
/* One 4 MiB transfer each way at once (scatter-gather: 256 segments). */
{
size_t n = 4 << 20;
uint8_t *src = malloc(n), *dst = malloc(n);
fill(src, n, 3);
memset(dst, 0, n);
r = submit(fd, &u1, USBDEVFS_URB_TYPE_BULK, 0x01, src, n, 0);
r = r ? r : submit(fd, &u2, USBDEVFS_URB_TYPE_BULK, 0x81, dst, n, 0);
int got = 0, st = 0;
for (int i = 0; !r && i < 2; i++) {
u = reap(fd);
if (!u)
break;
st |= u->status;
if (u == &u2)
got = u->actual_length;
}
big_check = !r && !st && got == (int)n && !memcmp(src, dst, n);
CHECK("bulk 4 MiB", big_check, "r %d status %d got %d", r, st, got);
free(src);
free(dst);
}
{
double mbs = loopback(fd, 8 << 20, 256 << 10, 4);
CHECK("bulk 8 MiB in flight", mbs > 0, "the loopback failed");
out("rate %.1f MB/s", mbs);
}
/* A zero-length packet after a full packet; then a short read. */
memset(buf, 0x5a, 512);
r = submit(fd, &u1, USBDEVFS_URB_TYPE_BULK, 0x01, buf, 512, USBDEVFS_URB_ZERO_PACKET);
u = r ? NULL : reap(fd);
r = u && !u->status ? bulk(fd, 0x81, buf, 4096, 5000) : -2;
int r2 = r == 512 ? bulk(fd, 0x81, buf, 4096, 5000) : -2;
CHECK("zero-length packet", r == 512 && r2 == 0, "reads %d, then %d", r, r2);
r = bulk(fd, 0x01, "short", 5, 5000);
r2 = r == 5 ? bulk(fd, 0x81, buf, 4096, 5000) : -2;
CHECK("short read", r2 == 5 && !memcmp(buf, "short", 5), "read %d", r2);
/* Interrupt IN: pending until the device has data (vendor request 0x05). */
r = submit(fd, &u1, USBDEVFS_URB_TYPE_INTERRUPT, 0x82, buf, 64, 0);
usleep(50000);
u = NULL;
r2 = ioctl(fd, USBDEVFS_REAPURBNDELAY, &u);
CHECK("interrupt pending", !r && r2 < 0 && errno == EAGAIN, "submit %d, reap %d %s", r, r2, strerror(errno));
ctrl(fd, USB_DIR_OUT | USB_TYPE_VENDOR, 0x05, 0, 0, "tick", 4);
u = reap(fd);
CHECK("interrupt", u == &u1 && !u->status && u->actual_length == 4 && !memcmp(buf, "tick", 4),
"%s status %d len %d", u ? "reaped" : strerror(errno), u ? u->status : 0, u ? u->actual_length : 0);
/* An IN unlinked while its transfer is pending: the data it would have taken reaches the next URB. */
r = submit(fd, &u1, USBDEVFS_URB_TYPE_BULK, 0x81, buf, 4096, 0);
usleep(50000);
r2 = ioctl(fd, USBDEVFS_DISCARDURB, &u1);
u = reap(fd);
CHECK("unlink", !r && !r2 && u == &u1 && (u->status == -ECONNRESET || u->status == -ENOENT) && !u->actual_length,
"submit %d discard %d status %d", r, r2, u ? u->status : 0);
r = bulk(fd, 0x01, "after the unlink", 16, 5000);
memset(buf, 0, 64);
r2 = bulk(fd, 0x81, buf, 4096, 5000);
CHECK("unlinked data kept", r == 16 && r2 == 16 && !memcmp(buf, "after the unlink", 16), "write %d read %d '%.16s'", r, r2, buf);
/* A stall: vendor request 0x03 halts 0x81; CLEAR_HALT ends it. */
ctrl(fd, USB_DIR_OUT | USB_TYPE_VENDOR, 0x03, 0x81, 0, NULL, 0);
errno = 0;
r = bulk(fd, 0x81, buf, 64, 5000);
CHECK("stall", r < 0 && errno == EPIPE, "read %d %s", r, strerror(errno));
{
unsigned int ep = 0x81;
r = ioctl(fd, USBDEVFS_CLEAR_HALT, &ep);
}
r2 = r ? -2 : bulk(fd, 0x01, "go on", 5, 5000);
r2 = r2 == 5 ? bulk(fd, 0x81, buf, 64, 5000) : -2;
CHECK("clear halt", !r && r2 == 5 && !memcmp(buf, "go on", 5), "clear %d %s, read %d", r, strerror(errno), r2);
/* Isochronous IN, in alternate setting 1. */
{
struct usbdevfs_setinterface si = { .interface = 0, .altsetting = 1 };
struct usbdevfs_urb *iu = calloc(1, sizeof(*iu) + 8 * sizeof(struct usbdevfs_iso_packet_desc));
uint8_t ib[8 * 64];
int okp = 1;
r = ioctl(fd, USBDEVFS_SETINTERFACE, &si);
iu->type = USBDEVFS_URB_TYPE_ISO;
iu->endpoint = 0x83;
iu->flags = USBDEVFS_URB_ISO_ASAP;
iu->buffer = ib;
iu->buffer_length = sizeof(ib);
iu->number_of_packets = 8;
for (int i = 0; i < 8; i++)
iu->iso_frame_desc[i].length = 64;
r2 = r ? -2 : ioctl(fd, USBDEVFS_SUBMITURB, iu);
u = r2 ? NULL : reap(fd);
for (int i = 0; u && i < 8; i++) {
uint8_t *p = ib + i * 64;
if (iu->iso_frame_desc[i].actual_length != 16 || iu->iso_frame_desc[i].status || p[1] != (uint8_t)(p[0] + 1))
okp = 0;
}
CHECK("isochronous", !r && !r2 && u == iu && !u->status && !u->error_count && okp,
"setinterface %d submit %d %s status %d errors %d", r, r2, strerror(errno), u ? u->status : 0, u ? u->error_count : 0);
si.altsetting = 0;
ioctl(fd, USBDEVFS_SETINTERFACE, &si);
free(iu);
}
/* USBDEVFS_RESET: the host resets the device; usbcore configures it again. */
r = ioctl(fd, USBDEVFS_RESET, 0);
r2 = r ? -2 : claim(fd);
r2 = r2 ? -3 : bulk(fd, 0x01, "reset", 5, 5000);
r2 = r2 == 5 ? bulk(fd, 0x81, buf, 64, 5000) : r2;
CHECK("reset", !r && r2 == 5 && !memcmp(buf, "reset", 5), "reset %d %s, then %d", r, strerror(errno), r2);
step("reset-done");
/* Unplugged with URBs pending: they end with ESHUTDOWN, then everything is ENODEV. */
r = submit(fd, &u1, USBDEVFS_URB_TYPE_BULK, 0x81, buf, 4096, 0);
r2 = submit(fd, &u2, USBDEVFS_URB_TYPE_INTERRUPT, 0x82, buf + 2048, 64, 0);
usleep(50000);
step("unplug");
{
int st[2] = { 1, 1 }, n = 0;
while (n < 2 && (u = reap(fd)))
st[n++] = u->status;
CHECK("pending at unplug", !r && !r2 && n == 2 && st[0] == -ESHUTDOWN && st[1] == -ESHUTDOWN,
"submit %d %d, reaped %d: %d %d", r, r2, n, st[0], st[1]);
}
errno = 0;
r = bulk(fd, 0x81, buf, 64, 1000);
CHECK("gone", r < 0 && errno == ENODEV, "read %d %s", r, strerror(errno));
close(fd);
step("reattach");
fd = open_dev(30, devnum, sysname, NULL);
CHECK("reattached", fd >= 0, "no device again (%s)", strerror(errno));
if (fd >= 0) {
r = claim(fd);
r2 = r ? -2 : bulk(fd, 0x01, "again", 5, 5000);
r2 = r2 == 5 ? bulk(fd, 0x81, buf, 64, 5000) : r2;
CHECK("loopback again", r2 == 5 && !memcmp(buf, "again", 5), "claim %d read %d", r, r2);
close(fd);
}
return 0;
}
static int quick(const char *want)
{
char sysname[64], speed[16];
uint8_t buf[2048];
int fd = open_dev(30, 0, sysname, NULL), r;
CHECK("open", fd >= 0, "no %04x:%04x (%s)", VID, PID, strerror(errno));
if (fd < 0)
return 1;
read_attr(sysname, "speed", speed, sizeof(speed));
CHECK("speed", !strcmp(speed, want), "sysfs speed %s, want %s", speed, want);
r = claim(fd);
r = r ? -2 : bulk(fd, 0x01, "quick", 5, 5000);
r = r == 5 ? bulk(fd, 0x81, buf, sizeof(buf), 5000) : r;
CHECK("loopback", r == 5 && !memcmp(buf, "quick", 5), "read %d %s", r, strerror(errno));
{
double mbs = loopback(fd, 4 << 20, 64 << 10, 4);
CHECK("bulk 4 MiB in flight", mbs > 0, "the loopback failed");
}
close(fd);
return 0;
}
static int bench(int mib)
{
int fd = open_dev(30, 0, NULL, NULL);
double mbs;
if (fd < 0 || claim(fd)) {
out("FAIL bench: no device");
return 1;
}
mbs = loopback(fd, (size_t)mib << 20, 256 << 10, 4);
out("rate %.1f MB/s", mbs);
close(fd);
return mbs > 0 ? 0 : 1;
}
static int park(const char *outfile)
{
static uint8_t buf[4096];
struct usbdevfs_urb u1, *u;
int fd = open_dev(30, 0, NULL, NULL), st, r;
FILE *f;
if (fd < 0 || claim(fd) || submit(fd, &u1, USBDEVFS_URB_TYPE_BULK, 0x81, buf, sizeof(buf), 0))
return 1;
out("ready");
u = reap(fd);
st = u ? u->status : -errno;
errno = 0;
r = bulk(fd, 0x81, buf, 64, 1000);
f = fopen(outfile, "w");
fprintf(f, "urb %d\nnext %d %s\n", st, r, r < 0 ? strerror(errno) : "-");
fclose(f);
return 0;
}
int main(int argc, char **argv)
{
if (argc >= 2 && !strcmp(argv[1], "run")) {
if (argc >= 3) {
cpu_set_t set;
CPU_ZERO(&set);
CPU_SET(atoi(argv[2]), &set);
if (sched_setaffinity(0, sizeof(set), &set))
out("FAIL affinity: %s", strerror(errno));
}
run();
out("done %d failure(s)", failures);
return failures ? 1 : 0;
}
if (argc >= 3 && !strcmp(argv[1], "quick")) {
quick(argv[2]);
out("done %d failure(s)", failures);
return failures ? 1 : 0;
}
if (argc >= 3 && !strcmp(argv[1], "bench"))
return bench(atoi(argv[2]));
if (argc >= 3 && !strcmp(argv[1], "park"))
return park(argv[2]);
fprintf(stderr, "usage: usbtest run [CPU] | quick SPEED | bench MIB | park OUT\n");
return 2;
}