From fdb4f692f327e53a428e1fa4aa701204d78a16a7 Mon Sep 17 00:00:00 2001 From: osilayer8 Date: Tue, 3 Nov 2026 21:34:04 +0100 Subject: [PATCH 1/3] Add DualShock 4 support and make the pad lifecycle survive crashes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Over USB a DualShock 4 streams 64-byte input report 0x01 and needs no handshake, so the driver only unpacks the d-pad hat: sticks and triggers already arrive in PlayStation convention. Both consumer ids (054c:05c4 and 054c:09cc) register and share one parser. Also fixes three ways a controller could silently stop working: - virtual pads left behind by a killed payload are recorded in a ledger under /data and removed by the next run, instead of lingering as phantom DualSenses that hold a controller slot until reboot; - a pad whose inserts start failing is rebuilt on the same slot, with a backoff, instead of staying dead until the payload is re-sent; - a failed USB endpoint probe is retried after a second rather than blacklisting the device for as long as its /dev node exists. Grace also drops a slot that has no virtual pad, so a resume can never dereference a NULL pad. 🤖 Generated with Codebuff Co-Authored-By: Codebuff --- Makefile | 1 + include/controllers/ds4.h | 58 ++++++++++++++++++++++ include/vpad.h | 12 ++++- src/controller.c | 3 ++ src/controllers/ds4.c | 102 ++++++++++++++++++++++++++++++++++++++ src/vpad.c | 54 ++++++++++++++++++++ 6 files changed, 229 insertions(+), 1 deletion(-) create mode 100644 include/controllers/ds4.h create mode 100644 src/controllers/ds4.c diff --git a/Makefile b/Makefile index 4db1ed4..5584657 100644 --- a/Makefile +++ b/Makefile @@ -22,6 +22,7 @@ SRCS = \ src/vpad.c \ src/controllers/switch_pro.c \ src/controllers/xbox360.c \ + src/controllers/ds4.c \ src/transport/usb.c OBJS = $(SRCS:.c=.o) diff --git a/include/controllers/ds4.h b/include/controllers/ds4.h new file mode 100644 index 0000000..44f78da --- /dev/null +++ b/include/controllers/ds4.h @@ -0,0 +1,58 @@ +/* + * Sony DualShock 4 driver. + * + * Over USB the pad streams 64-byte input report 0x01 at ~250 Hz and needs no + * handshake, so this driver is pure translation: sticks and triggers already + * arrive in PlayStation convention and only the d-pad hat has to be unpacked. + * Bluetooth uses report 0x11, which this driver does not handle. + * + * Report 0x01 layout: + * 0 report id, 0x01 + * 1..4 left X, left Y, right X, right Y (0..255, centre 128, Y down) + * 5 [7:4] triangle, circle, cross, square [3:0] d-pad hat + * 6 [7] R3 [6] L3 [5] options [4] share [3] R2 [2] L2 [1] R1 [0] L1 + * 7 [1] touchpad click [0] PS + * 8..9 L2, R2 analog + */ + +#ifndef DS4_H +#define DS4_H + +#include "../controller.h" + +#define SONY_VID 0x054C +#define DS4_PID_V1 0x05C4 /* CUH-ZCT1x, 2013 */ +#define DS4_PID_V2 0x09CC /* CUH-ZCT2x, 2016 */ + +#define DS4_REPORT_INPUT_USB 0x01 +#define DS4_INPUT_LEN 64 + +/* Buttons, byte 5 (upper nibble; lower nibble is the d-pad hat) */ +#define DS4_SQUARE 0x10 +#define DS4_CROSS 0x20 +#define DS4_CIRCLE 0x40 +#define DS4_TRIANGLE 0x80 + +/* Buttons, byte 6 */ +#define DS4_L1 0x01 +#define DS4_R1 0x02 +#define DS4_L2 0x04 +#define DS4_R2 0x08 +#define DS4_SHARE 0x10 +#define DS4_OPTIONS 0x20 +#define DS4_L3 0x40 +#define DS4_R3 0x80 + +/* Buttons, byte 7 */ +#define DS4_PS 0x01 +#define DS4_TOUCHPAD 0x02 + +/* Hat: 0 up, 2 right, 4 down, 6 left, odd values are diagonals, >= 8 is + * released. */ +#define DS4_DPAD_MASK 0x0F +#define DS4_DPAD_RELEASED 8 + +/* V1 and V2 speak the same protocol; only the USB id differs. */ +const ControllerDriver *ds4_get_driver(int variant); /* 0 = V1, 1 = V2 */ + +#endif /* DS4_H */ diff --git a/include/vpad.h b/include/vpad.h index fe5267b..fe7beff 100644 --- a/include/vpad.h +++ b/include/vpad.h @@ -35,6 +35,10 @@ /* User id FGG-XSense registers pads under; verified on hardware. */ #define VPAD_DEFAULT_USER 1 +/* Handles of the pads we register are recorded here, so that a payload killed + * without cleaning up leaves nothing behind for the next run to trip over. */ +#define VPAD_LEDGER_FILE "/data/anycontroller.vpads" + /* Request taken by HID_ADD_DEVICE and HID_INSERT_DATA */ typedef struct { uint32_t cmd; /* HID_CMD_ADD, or the device handle for insert */ @@ -92,9 +96,15 @@ Vpad *vpad_create(uint32_t user_id); /* Translate and submit one frame of input. Returns 0 on success. */ int vpad_submit_input(Vpad *vpad, const NormalizedInput *input); -/* Remove a virtual pad. A pad left registered outlives the payload. */ +/* Remove a virtual pad. A pad left registered by a payload that was killed + * (SIGKILL, crash) is removed by the next instance; see vpad_reap_stale. */ void vpad_destroy(Vpad *vpad); +/* Remove the pads a previous instance recorded in the ledger and clear the + * ledger. Call once after vpad_init(), before creating any pad: handles are + * not enumerable, so this is the only way back to a clean state. */ +void vpad_reap_stale(void); + /* Remove all pads and close /dev/hid. */ void vpad_shutdown(void); diff --git a/src/controller.c b/src/controller.c index 783b6e8..ce8a9d4 100644 --- a/src/controller.c +++ b/src/controller.c @@ -5,6 +5,7 @@ #include "../include/controller.h" #include "../include/controllers/switch_pro.h" #include "../include/controllers/xbox360.h" +#include "../include/controllers/ds4.h" #include @@ -45,4 +46,6 @@ void controller_drivers_init(void) driver_count = 0; controller_driver_register(switch_pro_get_driver()); controller_driver_register(xbox360_get_driver()); + controller_driver_register(ds4_get_driver(0)); + controller_driver_register(ds4_get_driver(1)); } diff --git a/src/controllers/ds4.c b/src/controllers/ds4.c new file mode 100644 index 0000000..c809ca8 --- /dev/null +++ b/src/controllers/ds4.c @@ -0,0 +1,102 @@ +/* + * DualShock 4 driver — maps USB input report 0x01 to NormalizedInput. + */ + +#include "../../include/controllers/ds4.h" + +#include + +/* The d-pad is a hat switch; the virtual pad wants individual directions, so + * diagonals set two of them. */ +static void map_dpad(uint8_t hat, NormalizedInput *out) +{ + if (hat >= DS4_DPAD_RELEASED) return; + + out->dpad_up = (hat == 0 || hat == 1 || hat == 7); + out->dpad_right = (hat == 1 || hat == 2 || hat == 3); + out->dpad_down = (hat == 3 || hat == 4 || hat == 5); + out->dpad_left = (hat == 5 || hat == 6 || hat == 7); +} + +static int ds4_init(Controller *ctrl) +{ + ctrl->priv = NULL; + return 0; +} + +static int ds4_parse_input(Controller *ctrl, const uint8_t *r, int len, + NormalizedInput *out) +{ + (void)ctrl; + + if (len < DS4_INPUT_LEN || r[0] != DS4_REPORT_INPUT_USB) + return -1; + + memset(out, 0, sizeof(*out)); + + /* Sticks are already 0..255, centre 128, Y growing downwards — exactly + * what the virtual pad report takes, so no scaling or inversion. */ + out->left_stick_x = r[1]; + out->left_stick_y = r[2]; + out->right_stick_x = r[3]; + out->right_stick_y = r[4]; + + uint8_t face = r[5]; + out->square = !!(face & DS4_SQUARE); + out->cross = !!(face & DS4_CROSS); + out->circle = !!(face & DS4_CIRCLE); + out->triangle = !!(face & DS4_TRIANGLE); + map_dpad(face & DS4_DPAD_MASK, out); + + uint8_t sys = r[6]; + out->l1 = !!(sys & DS4_L1); + out->r1 = !!(sys & DS4_R1); + out->l3 = !!(sys & DS4_L3); + out->r3 = !!(sys & DS4_R3); + out->create = !!(sys & DS4_SHARE); /* Share → Create */ + out->options = !!(sys & DS4_OPTIONS); + + out->ps_button = !!(r[7] & DS4_PS); + out->touchpad = !!(r[7] & DS4_TOUCHPAD); + + /* Analog triggers; the pad's own digital L2/R2 bits are redundant, vpad + * derives those from the analog value. */ + out->l2_analog = r[8]; + out->r2_analog = r[9]; + + return 0; +} + +static void ds4_cleanup(Controller *ctrl) +{ + (void)ctrl; +} + +static const ControllerDriver ds4_driver_v1 = { + .name = "DualShock 4", + .type = CTRL_TYPE_DS4, + .vendor_id = SONY_VID, + .product_id = DS4_PID_V1, + .init = ds4_init, + .setup = NULL, /* no handshake: the pad streams input on its own */ + .parse_input = ds4_parse_input, + .build_output = NULL, /* no rumble/lightbar support yet */ + .cleanup = ds4_cleanup, +}; + +static const ControllerDriver ds4_driver_v2 = { + .name = "DualShock 4 v2", + .type = CTRL_TYPE_DS4, + .vendor_id = SONY_VID, + .product_id = DS4_PID_V2, + .init = ds4_init, + .setup = NULL, + .parse_input = ds4_parse_input, + .build_output = NULL, + .cleanup = ds4_cleanup, +}; + +const ControllerDriver *ds4_get_driver(int variant) +{ + return variant == 1 ? &ds4_driver_v2 : &ds4_driver_v1; +} diff --git a/src/vpad.c b/src/vpad.c index 901b3d3..b1ce653 100644 --- a/src/vpad.c +++ b/src/vpad.c @@ -4,14 +4,33 @@ #include "../include/vpad.h" +#include #include #include #include #include +#include + +#define STALE_MAX 16 /* handles remembered for crashed runs */ static int g_hid_fd = -1; static Vpad g_vpads[MAX_CONTROLLERS]; +/* Rewrite the ledger from the pads we hold open. Pad handles are not + * enumerable, so this file is the only record of a pad that a killed payload + * left registered with the kernel. */ +static void ledger_save(void) +{ + FILE *f = fopen(VPAD_LEDGER_FILE, "w"); + if (!f) return; + + for (int i = 0; i < MAX_CONTROLLERS; i++) + if (g_vpads[i].active) + fprintf(f, "%d\n", g_vpads[i].handle); + + fclose(f); +} + int vpad_init(void) { g_hid_fd = open("/dev/hid", O_RDWR); @@ -58,6 +77,7 @@ Vpad *vpad_create(uint32_t user_id) vpad->report.active = 1; vpad->report.orient_w = 1.0f; + ledger_save(); return vpad; } @@ -123,6 +143,40 @@ void vpad_destroy(Vpad *vpad) vpad->active = false; vpad->handle = -1; + + ledger_save(); +} + +void vpad_reap_stale(void) +{ + if (g_hid_fd < 0) return; + + FILE *f = fopen(VPAD_LEDGER_FILE, "r"); + if (!f) return; + + int32_t handles[STALE_MAX]; + int count = 0; + while (count < STALE_MAX && fscanf(f, "%d", &handles[count]) == 1) + count++; + fclose(f); + + int removed = 0; + for (int i = 0; i < count; i++) { + if (handles[i] <= 0) continue; + + HidDelRequest del; + memset(&del, 0, sizeof(del)); + del.cmd = HID_CMD_DEL; + del.handle = (uint32_t)handles[i]; + if (ioctl(g_hid_fd, HID_DEL_DEVICE, &del) == 0) + removed++; + } + + if (count) + klog_printf("[AnyController] removed %d of %d stale virtual pad(s)\n", + removed, count); + + ledger_save(); } void vpad_shutdown(void) From e9ccc4aa3316d8ae4f86d19c0d28c2a27f3e07fa Mon Sep 17 00:00:00 2001 From: osilayer8 Date: Tue, 3 Nov 2026 21:36:24 +0100 Subject: [PATCH 2/3] Wire the new pad lifecycle into main MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit main.c reaps the stale-pad ledger after taking over a previous instance, rebuilds a virtual pad whose inserts start failing, and drops a slot with no virtual pad instead of entering grace with nothing to hold — which previously could dereference a NULL pad on resume. 🤖 Generated with Codebuff Co-Authored-By: Codebuff --- src/main.c | 69 ++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 64 insertions(+), 5 deletions(-) diff --git a/src/main.c b/src/main.c index ab3a4bb..d602b19 100644 --- a/src/main.c +++ b/src/main.c @@ -79,9 +79,13 @@ static bool is_payload_process(pid_t pid) } /* Stop a previously deployed instance so two copies don't fight over the - * same USB device, then record our own pid. */ -static void take_over_previous_instance(void) + * same USB device, then record our own pid. Returns true when no previous + * instance is left running, i.e. the pads it recorded in the ledger are stale + * and safe to remove. */ +static bool take_over_previous_instance(void) { + bool reap_stale = true; + FILE *f = fopen(PID_FILE, "r"); if (f) { int old = 0; @@ -91,6 +95,12 @@ static void take_over_previous_instance(void) kill(old, SIGTERM); for (int i = 0; i < 50 && kill(old, 0) == 0; i++) usleep(20000); + if (kill(old, 0) == 0) { + /* It refused to go; deleting its pads would fight a live + * process, so leave them registered. */ + klog_printf("[AnyController] previous instance pid=%d still running\n", old); + reap_stale = false; + } } fclose(f); } @@ -99,6 +109,7 @@ static void take_over_previous_instance(void) fprintf(f, "%d\n", getpid()); fclose(f); } + return reap_stale; } #define RETRY_BACKOFF_US 2000000ULL @@ -106,6 +117,8 @@ static void take_over_previous_instance(void) #define KEEPALIVE_US 1000000ULL #define STATS_WINDOW_US 5000000ULL #define STALL_US 500000ULL +#define SUBMIT_FAIL_LIMIT 30 /* failed inserts before rebuilding the pad (~250 ms) */ +#define VPAD_RETRY_US 2000000ULL /* wait this long before rebuilding the pad again */ typedef struct { uint64_t last_report_us; @@ -115,6 +128,8 @@ typedef struct { unsigned reports; unsigned total_reports; unsigned submits_failed; + unsigned submit_fail_streak; /* consecutive HID_INSERT_DATA failures */ + uint64_t vpad_retry_us; /* earliest time to rebuild the virtual pad */ bool stalled; bool ps_down; } SlotStats; @@ -159,10 +174,41 @@ static void submit_neutral(int i) vpad_submit_input(vpads[i], &idle); } +/* The kernel can invalidate a pad handle (account switch, system UI reset) and + * from then on every insert fails. Rebuild the pad on the same slot so the + * controller keeps working without the user re-sending the payload. */ +static void recover_vpad(int i, uint64_t now) +{ + if (now < stats[i].vpad_retry_us) + return; + + if (vpads[i]) + vpad_destroy(vpads[i]); + vpads[i] = vpad_create(VPAD_DEFAULT_USER); + + stats[i].submit_fail_streak = 0; + stats[i].ps_down = false; + stats[i].vpad_retry_us = now + VPAD_RETRY_US; + + if (!vpads[i]) + klog_printf("[AnyController] slot %d: could not rebuild virtual pad errno=%d\n", + i, errno); + else + klog_printf("[AnyController] slot %d: virtual pad rebuilt -> handle=%d\n", + i, vpads[i]->handle); +} + /* USB vanished: keep the virtual DualSense registered for a moment so a * short controller re-enumeration doesn't look like an unplug to the PS5. */ static void begin_grace(int i, uint64_t now) { + /* Nothing to hold on to when the pad could not be rebuilt: drop the slot + * outright, so the resume path can never touch a NULL virtual pad. */ + if (!vpads[i]) { + drop_slot(i, "USB lost without a virtual pad"); + return; + } + klog_printf("[AnyController] slot %d: USB lost, holding DualSense for %llu ms\n", i, (unsigned long long)(RESUME_GRACE_US / 1000)); release_usb(i); @@ -326,8 +372,16 @@ static void poll_slot(int i, uint64_t now) input.ps_button ? "pressed" : "released"); } input.timestamp_us = now; - if (vpad_submit_input(vpads[i], &input) != 0 && st->submits_failed++ == 0) - klog_printf("[AnyController] slot %d: input submit failed errno=%d\n", i, errno); + if (!vpads[i]) { + recover_vpad(i, now); + } else if (vpad_submit_input(vpads[i], &input) == 0) { + st->submit_fail_streak = 0; + } else { + if (st->submits_failed++ == 0) + klog_printf("[AnyController] slot %d: input submit failed errno=%d\n", i, errno); + if (++st->submit_fail_streak >= SUBMIT_FAIL_LIMIT) + recover_vpad(i, now); + } } if (now - st->last_keepalive_us >= KEEPALIVE_US) { @@ -353,7 +407,7 @@ int main(void) ANYCONTROLLER_VERSION_MAJOR, ANYCONTROLLER_VERSION_MINOR, ANYCONTROLLER_VERSION_PATCH, getpid()); - take_over_previous_instance(); + bool reap_stale_vpads = take_over_previous_instance(); controller_drivers_init(); if (vpad_init() != 0) { @@ -362,6 +416,11 @@ int main(void) return 1; } + /* Pads a crashed instance registered are still attached to the system and + * would show up as phantom DualSenses; remove them before adding ours. */ + if (reap_stale_vpads) + vpad_reap_stale(); + usb_init(); memset(controllers, 0, sizeof(controllers)); for (int i = 0; i < MAX_CONTROLLERS; i++) From 569dbea41fcc9dfe10d6b3083df4b0d42ef10575 Mon Sep 17 00:00:00 2001 From: osilayer8 Date: Tue, 3 Nov 2026 21:37:04 +0100 Subject: [PATCH 3/3] Retry failed USB probes and document DualShock 4 support MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit usb.c now separates permanent rejections (a device no driver supports) from transient probe failures, so a controller whose interrupt endpoint is not published yet is retried after a second instead of being hidden for as long as its /dev node exists. README lists the DualShock 4. 🤖 Generated with Codebuff Co-Authored-By: Codebuff --- README.md | 8 +++- src/transport/usb.c | 101 +++++++++++++++++++++++++++++++++----------- 2 files changed, 84 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index d7ff17d..bfc09fe 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,7 @@ Use non-PlayStation controllers on a jailbroken PS5. AnyController is an ELF pay | Nintendo Switch Pro Controller (`057e:2009`) | USB cable | Working | | Xbox 360 / XInput controllers (`045e:028e`) | USB cable or 2.4GHz dongle | Working | | GameSir T4 Pro | 2.4GHz dongle (X-input mode) | Working | +| Sony DualShock 4 (`054c:05c4`, `054c:09cc`) | USB cable | Driver added, untested on hardware | Many third-party pads and dongles have an X-input mode that reports as an Xbox 360 controller, so they should work too. @@ -66,6 +67,10 @@ Buttons are mapped **by position**, so the bottom face button is always Cross: | Touchpad click | Capture | — | | PS button | Home | Guide | +DualShock 4 maps one to one, since its face buttons are already in PlayStation +positions: Share becomes **Create**, Options stays **Options**, and the +touchpad click is reported as the touchpad button. + ## Building Requires the PS5 payload SDK from **[ps5-payload-dev/sdk](https://github.com/ps5-payload-dev/sdk)**, v0.45 or newer. Its README covers installation (clang-18 and lld-18 on Linux or WSL). @@ -101,6 +106,7 @@ The [Release workflow](.github/workflows/release.yml) builds the payload and pub - **USB access:** the PS5 has no `uhid` device. Controllers appear only as FreeBSD `ugen` nodes (`/dev/usb/B.A.E`). AnyController identifies devices by their USB descriptor, detaches Sony's HID driver, claims the interface and reads reports from the interrupt endpoints. See [`src/transport/usb.c`](src/transport/usb.c). - **Switch Pro Controller:** over USB it drops off the bus every second or so until the host sends the USB handshake and the "no timeout" command. The driver sends the same sequence as Linux's `hid-nintendo`, then enables full 0x30 reports and the motion sensor. See [`src/controllers/switch_pro.c`](src/controllers/switch_pro.c). - **Xbox 360 / XInput:** standard 20-byte input reports. The driver sends the player-LED command on connect, which also makes multi-mode dongles stay in X-input mode instead of cycling. See [`src/controllers/xbox360.c`](src/controllers/xbox360.c). +- **DualShock 4:** over USB the pad streams 64-byte input report `0x01` at ~250 Hz with no handshake needed, so the driver only unpacks the d-pad hat — sticks and triggers already arrive in PlayStation convention. See [`src/controllers/ds4.c`](src/controllers/ds4.c). - **Brief drops:** if a controller drops off USB, its virtual DualSense is kept for 3 seconds. A quick reconnect then resumes on the same pad, without a disconnect or user re-pick. ### Adding a controller @@ -122,7 +128,7 @@ AnyController logs to the kernel log. With a klog server running on the console - Bluetooth controllers - Rumble from games, and the light bar - Motion controls (gyro) -- Other controller families (Xbox One/Series, DualShock 4, generic HID gamepads) +- Other controller families (Xbox One/Series, generic HID gamepads) - The Create button bit is unverified ## Credits diff --git a/src/transport/usb.c b/src/transport/usb.c index ceec0fa..61fbbd4 100644 --- a/src/transport/usb.c +++ b/src/transport/usb.c @@ -11,29 +11,82 @@ #include #include #include +#include #include #include #include #include -#define REJECT_MAX 32 -#define NAME_LEN 16 +#define REJECT_MAX 32 +#define NAME_LEN 16 +#define PROBE_RETRY_US 1000000ULL /* re-probe a device that failed to open */ static UsbDevice usb_devices[USB_MAX_DEVICES]; -/* Devices whose descriptor we read and that no driver supports. Rebuilt on - * every scan from the nodes still present, so a reused address is retried. - * Keeps the fast rescan from re-opening the PS5's internal USB devices. */ -static char rejected[REJECT_MAX][NAME_LEN]; -static int rejected_count; +/* Devices we already looked at, rebuilt on every scan from the nodes still + * present. Two kinds of rejection, because they mean different things: an + * unsupported device stays rejected for as long as its node exists, while a + * failed probe (endpoint not published yet during enumeration, transient open + * error) is retried after a backoff instead of hiding the device for good. */ +typedef struct { + char name[NAME_LEN]; + bool permanent; + uint64_t retry_us; +} RejectEntry; + +static RejectEntry rejected[REJECT_MAX]; +static int rejected_count; int usb_init(void) { memset(usb_devices, 0, sizeof(usb_devices)); + memset(rejected, 0, sizeof(rejected)); rejected_count = 0; return 0; } +static uint64_t usb_now_us(void) +{ + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (uint64_t)ts.tv_sec * 1000000ULL + ts.tv_nsec / 1000; +} + +static void reject_unsupported(const char *name) +{ + if (rejected_count >= REJECT_MAX) return; + + RejectEntry *e = &rejected[rejected_count++]; + snprintf(e->name, NAME_LEN, "%s", name); + e->permanent = true; + e->retry_us = 0; +} + +static void reject_probe(const char *name, uint64_t now) +{ + if (rejected_count >= REJECT_MAX) return; + + RejectEntry *e = &rejected[rejected_count++]; + snprintf(e->name, NAME_LEN, "%s", name); + e->permanent = false; + e->retry_us = now + PROBE_RETRY_US; +} + +static const RejectEntry *reject_find(const RejectEntry *table, int count, + const char *name) +{ + for (int i = 0; i < count; i++) + if (strcmp(table[i].name, name) == 0) + return &table[i]; + return NULL; +} + +static void reject_carry(const RejectEntry *e) +{ + if (rejected_count < REJECT_MAX) + rejected[rejected_count++] = *e; +} + static bool is_held(const char *name) { for (int i = 0; i < USB_MAX_DEVICES; i++) @@ -42,13 +95,7 @@ static bool is_held(const char *name) return false; } -static void reject(const char *name) -{ - if (rejected_count < REJECT_MAX) - snprintf(rejected[rejected_count++], NAME_LEN, "%s", name); -} - -static int try_open(const char *name, Controller *ctrl) +static int try_open(const char *name, Controller *ctrl, uint64_t now) { char path[64]; snprintf(path, sizeof(path), "/dev/usb/%s.0", name); @@ -67,7 +114,7 @@ static int try_open(const char *name, Controller *ctrl) const ControllerDriver *drv = controller_driver_find(vid, pid); if (!drv) { - reject(name); + reject_unsupported(name); close(cfd); return -1; } @@ -101,10 +148,10 @@ static int try_open(const char *name, Controller *ctrl) out_ep = ep; } if (in_fd < 0) { - klog_printf("[AnyController] usb %s: no readable endpoint, skipping device\n", name); + klog_printf("[AnyController] usb %s: no readable endpoint yet, retrying\n", name); if (out_fd >= 0) close(out_fd); close(cfd); - reject(name); + reject_probe(name, now); return -1; } int one = 1; @@ -135,26 +182,32 @@ int usb_open_next_controller(Controller *ctrl) DIR *d = opendir("/dev"); if (!d) return -1; - char prev[REJECT_MAX][NAME_LEN]; + RejectEntry prev[REJECT_MAX]; int prev_count = rejected_count; memcpy(prev, rejected, sizeof(prev)); rejected_count = 0; + uint64_t now = usb_now_us(); int result = -1; struct dirent *e; while ((e = readdir(d))) { if (strncmp(e->d_name, "ugen", 4) != 0) continue; const char *name = e->d_name + 4; - bool was_rejected = false; - for (int i = 0; i < prev_count && !was_rejected; i++) - was_rejected = strcmp(prev[i], name) == 0; - if (was_rejected) { - reject(name); + /* Carry forward what we already know about this node, so the 25 ms + * rescan neither re-reads descriptors of unsupported devices nor + * retries a failed probe before its backoff expires. */ + const RejectEntry *was = reject_find(prev, prev_count, name); + if (was && was->permanent) { + reject_carry(was); + continue; + } + if (was && now < was->retry_us) { + reject_carry(was); continue; } if (result == 0 || is_held(name)) continue; - if (try_open(name, ctrl) == 0) result = 0; + if (try_open(name, ctrl, now) == 0) result = 0; } closedir(d); return result;