Illustrated C/C++ source sheets, symbol index, API relationship graph, compiler console and debug trace

LIVE AI / FLEXIBLE SENSING / FLIGHT CONTEXT

Sensoraia API

Live AI and sensing, connected to the flight.
See, listen, inspect and return supported results while airborne.

Loading...
Searching...
No Matches
usbfs.h
Go to the documentation of this file.
1/*
2 * Copyright 2026 OpenUAS
3 * SPDX-License-Identifier: Apache-2.0
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18/**
19 * @file usbfs.h
20 * @brief Minimal header-only Linux usbfs access for one CHDKbridge camera.
21 * @details Discovers devices through sysfs, parses the active configuration,
22 * owns one interface and performs synchronous bulk transfers through
23 * /dev/bus/usb ioctls. The wrapper allocates no heap storage and creates
24 * no threads.
25 * @warning Serialize all access to a handle, including close. A bulk call
26 * owns its submitted URB until completion or descriptor teardown; another
27 * caller must not reap it or close and reuse the descriptor.
28 */
29#ifndef CHDKBRIDGE_USBFS_H
30#define CHDKBRIDGE_USBFS_H
31
32#include <dirent.h>
33#include <errno.h>
34#include <fcntl.h>
35#include <limits.h>
36#include <linux/usbdevice_fs.h>
37#include <poll.h>
38#include <signal.h>
39#include <stdbool.h>
40#include <stddef.h>
41#include <stdint.h>
42#include <stdio.h>
43#include <stdlib.h>
44#include <sys/ioctl.h>
45#include <sys/stat.h>
46#include <sys/sysmacros.h>
47#include <time.h>
48#include <unistd.h>
49
50#define USBFS_SYSFS_ROOT "/sys/bus/usb/devices"
51#define USBFS_DEVICE_ROOT "/dev/bus/usb"
52
53/** @brief Result codes; negative values are errors, as in libusb. */
54enum {
60};
61
62enum {
67 USBFS_LEGACY_TRANSFER = 16384, /**< Per-URB limit without NO_PACKET_SIZE_LIM. */
68 USBFS_DISCARD_MS = 1000, /**< Grace for a cancelled URB before the fd is dropped. */
70};
71
72/** @brief One enumerated USB device; a value copy, valid after enumeration ends. */
74 char name[32]; /**< sysfs name, e.g. "1-5.1". */
75 unsigned bus, address;
76 uint16_t vendor, product;
78 int depth; /**< Port count, or -1 when deeper than ports[]. */
79};
80
85
91
94};
95
96/** @brief Open usbfs file; fd is -1 when closed or dropped after a lost URB. */
98 int fd;
99 uint32_t capabilities;
100 const volatile sig_atomic_t *cancel; /**< Optional; nonzero discards a pending bulk URB early. */
101};
102
103/** @brief Get the diagnostic name of a usbfs result.
104 * @param error Result from this wrapper.
105 * @return Borrowed static name, with OTHER for unknown values.
106 * @details Keep the diagnostic vocabulary stable independently of errno. */
107static inline const char *usbfs_error_name(int error)
108{
109 switch (error) {
110 case USBFS_SUCCESS: return "USB_SUCCESS";
111 case USBFS_ERROR_IO: return "USB_ERROR_IO";
112 case USBFS_ERROR_INVALID_PARAM: return "USB_ERROR_INVALID_PARAM";
113 case USBFS_ERROR_ACCESS: return "USB_ERROR_ACCESS";
114 case USBFS_ERROR_NO_DEVICE: return "USB_ERROR_NO_DEVICE";
115 case USBFS_ERROR_NOT_FOUND: return "USB_ERROR_NOT_FOUND";
116 case USBFS_ERROR_BUSY: return "USB_ERROR_BUSY";
117 case USBFS_ERROR_TIMEOUT: return "USB_ERROR_TIMEOUT";
118 case USBFS_ERROR_OVERFLOW: return "USB_ERROR_OVERFLOW";
119 case USBFS_ERROR_PIPE: return "USB_ERROR_PIPE";
120 case USBFS_ERROR_INTERRUPTED: return "USB_ERROR_INTERRUPTED";
121 case USBFS_ERROR_NO_MEM: return "USB_ERROR_NO_MEM";
122 default: return "USB_ERROR_OTHER";
123 }
124}
125
126/** @brief True when sysfs device listing and usbfs nodes are reachable. */
127static inline bool usbfs_available(void)
128{
129 return access(USBFS_SYSFS_ROOT, R_OK | X_OK) == 0 && access(USBFS_DEVICE_ROOT, R_OK | X_OK) == 0;
130}
131
132/** @brief Read one bounded unsigned numeric sysfs attribute.
133 * @param device Sysfs device directory name.
134 * @param attribute Attribute basename.
135 * @param base Number base, 10 or 16 for supported callers.
136 * @param maximum Largest acceptable value.
137 * @param[out] value Result written only on success.
138 * @return True if the attribute could be read and parsed in range.
139 * @details Allow the newline used by sysfs, but reject signs and
140 * nonnumeric prefixes before conversion. */
141static inline bool usbfs_read_number(const char *device, const char *attribute, int base,
142 unsigned long maximum, unsigned long *value)
143{
144 char path[128], text[32];
145 int length = snprintf(path, sizeof(path), USBFS_SYSFS_ROOT "/%s/%s", device, attribute);
146 if (length < 0 || (size_t)length >= sizeof(path)) return false;
147 int fd = open(path, O_RDONLY | O_CLOEXEC);
148 if (fd < 0) return false;
149 ssize_t count;
150 do count = read(fd, text, sizeof(text) - 1); while (count < 0 && errno == EINTR);
151 close(fd);
152 if (count <= 0) return false;
153 text[count] = '\0';
154 bool digit = (text[0] >= '0' && text[0] <= '9') ||
155 (base == 16 && ((text[0] >= 'a' && text[0] <= 'f') || (text[0] >= 'A' && text[0] <= 'F')));
156 if (!digit) return false;
157 char *end;
158 errno = 0;
159 unsigned long parsed = strtoul(text, &end, base);
160 if (errno || (*end && *end != '\n') || parsed > maximum) return false;
161 *value = parsed;
162 return true;
163}
164
165/** @brief Parse "BUS-PORT[.PORT...]"; rejects root hubs and interface entries. */
166static inline bool usbfs_parse_name(const char *name, struct usbfs_device *device)
167{
168 int length = snprintf(device->name, sizeof(device->name), "%s", name);
169 if (length < 0 || (size_t)length >= sizeof(device->name) || name[0] < '1' || name[0] > '9') return false;
170 char *end;
171 unsigned long bus = strtoul(name, &end, 10);
172 if (*end != '-' || bus > 255) return false;
173 device->bus = (unsigned)bus;
174 unsigned depth = 0;
175 for (const char *cursor = end + 1;; cursor = end + 1) {
176 if (*cursor < '1' || *cursor > '9') return false;
177 unsigned long port = strtoul(cursor, &end, 10);
178 if (port > 255 || depth > 255) return false;
179 if (depth < USBFS_MAX_PORTS) device->ports[depth] = (uint8_t)port;
180 ++depth;
181 if (!*end) break;
182 if (*end != '.') return false;
183 }
184 device->depth = depth <= USBFS_MAX_PORTS ? (int)depth : -1;
185 return true;
186}
187
188/** @brief Start a streaming sysfs enumeration.
189 * @param[out] devices Iterator receiving the directory stream.
190 * @return USBFS_SUCCESS or a negative access/I/O error.
191 * @details Scan at iteration time rather than allocating a device list. */
192static inline int usbfs_devices_open(struct usbfs_devices *devices)
193{
194 devices->directory = opendir(USBFS_SYSFS_ROOT);
195 if (devices->directory) return USBFS_SUCCESS;
196 return errno == EACCES ? USBFS_ERROR_ACCESS : USBFS_ERROR_IO;
197}
198
199/** @return 1 with a device, 0 at the end, or a negative error. Vanishing devices are skipped. */
200static inline int usbfs_devices_next(struct usbfs_devices *devices, struct usbfs_device *device)
201{
202 for (;;) {
203 errno = 0;
204 struct dirent *entry = readdir(devices->directory);
205 if (!entry) return errno ? USBFS_ERROR_IO : 0;
206 struct usbfs_device candidate = {0};
207 unsigned long bus, address, vendor, product;
208 if (!usbfs_parse_name(entry->d_name, &candidate) ||
209 !usbfs_read_number(candidate.name, "busnum", 10, 255, &bus) ||
210 !usbfs_read_number(candidate.name, "devnum", 10, 127, &address) ||
211 !usbfs_read_number(candidate.name, "idVendor", 16, 0xffff, &vendor) ||
212 !usbfs_read_number(candidate.name, "idProduct", 16, 0xffff, &product) ||
213 bus != candidate.bus || !address) continue;
214 candidate.address = (unsigned)address;
215 candidate.vendor = (uint16_t)vendor;
216 candidate.product = (uint16_t)product;
217 *device = candidate;
218 return 1;
219 }
220}
221
222/** @brief Release the sysfs enumeration stream.
223 * @param[in,out] devices Initialized iterator.
224 * @details Clear the stream pointer so repeated cleanup is safe. */
225static inline void usbfs_devices_close(struct usbfs_devices *devices)
226{
227 if (devices->directory) closedir(devices->directory);
228 devices->directory = NULL;
229}
230
231/**
232 * @brief Locate configuration @p value in raw sysfs descriptors.
233 * @details sysfs stores the device descriptor followed by every configuration
234 * in bus (little-endian) order; a short final configuration is clamped.
235 */
236static inline int usbfs_select_config(const uint8_t *descriptors, size_t length, unsigned value,
237 const uint8_t **config, size_t *config_length)
238{
239 if (length < 18 || descriptors[0] != 18 || descriptors[1] != 1) return USBFS_ERROR_IO;
240 for (size_t offset = 18; length - offset >= 9;) {
241 const uint8_t *header = descriptors + offset;
242 size_t total = (size_t)header[2] | (size_t)header[3] << 8;
243 if (header[0] < 9 || header[1] != 2 || total < header[0]) return USBFS_ERROR_IO;
244 if (total > length - offset) total = length - offset;
245 if (header[5] == value) {
246 *config = header;
247 *config_length = total;
248 return USBFS_SUCCESS;
249 }
250 offset += total;
251 }
253}
254
255/** @brief Read the active configuration into @p buffer; @p config points inside it. */
256static inline int usbfs_active_config(const struct usbfs_device *device, uint8_t *buffer, size_t capacity,
257 const uint8_t **config, size_t *config_length)
258{
259 unsigned long value;
260 if (!usbfs_read_number(device->name, "bConfigurationValue", 10, 255, &value) || !value)
262 char path[128];
263 int written = snprintf(path, sizeof(path), USBFS_SYSFS_ROOT "/%s/descriptors", device->name);
264 if (written < 0 || (size_t)written >= sizeof(path)) return USBFS_ERROR_INVALID_PARAM;
265 int fd = open(path, O_RDONLY | O_CLOEXEC);
266 if (fd < 0) return errno == ENOENT ? USBFS_ERROR_NO_DEVICE : USBFS_ERROR_IO;
267 size_t used = 0;
268 int result = USBFS_SUCCESS;
269 for (;;) {
270 uint8_t probe;
271 uint8_t *target = used < capacity ? buffer + used : &probe;
272 ssize_t count = read(fd, target, used < capacity ? capacity - used : 1);
273 if (count < 0 && errno == EINTR) continue;
274 if (count < 0) result = USBFS_ERROR_IO;
275 else if (count > 0 && used >= capacity) result = USBFS_ERROR_OVERFLOW;
276 if (count <= 0 || result) break;
277 used += (size_t)count;
278 }
279 close(fd);
280 return result ? result : usbfs_select_config(buffer, used, (unsigned)value, config, config_length);
281}
282
283/**
284 * @brief Return the next complete interface/alternate setting in a configuration.
285 * @param config Borrowed descriptor block for the active configuration.
286 * @param length Readable bytes in @p config.
287 * @param offset Start with 0; advanced past the returned interface.
288 * @param[out] interface Parsed interface; use only when the function returns true.
289 * @return True when a complete interface was found.
290 * @details Interfaces whose endpoint descriptors disagree with bNumEndpoints
291 * are skipped. Parsing stops at the first malformed descriptor header.
292 */
293static inline bool usbfs_next_interface(const uint8_t *config, size_t length, size_t *offset,
294 struct usbfs_interface *interface)
295{
296 size_t cursor = *offset ? *offset : (length ? config[0] : 0);
297 bool open = false;
298 unsigned endpoints = 0;
299 while (cursor < length && length - cursor >= 2) {
300 const uint8_t *descriptor = config + cursor;
301 if (descriptor[0] < 2 || descriptor[0] > length - cursor) break;
302 if (descriptor[1] == 4 && descriptor[0] >= 9) {
303 if (open && endpoints == interface->bNumEndpoints) {
304 *offset = cursor;
305 return true;
306 }
307 *interface = (struct usbfs_interface){
308 .bInterfaceNumber = descriptor[2], .bAlternateSetting = descriptor[3],
309 .bNumEndpoints = descriptor[4], .bInterfaceClass = descriptor[5],
310 .bInterfaceSubClass = descriptor[6], .bInterfaceProtocol = descriptor[7]};
312 endpoints = 0;
313 } else if (descriptor[1] == 5 && descriptor[0] >= 7 && open) {
314 if (endpoints == interface->bNumEndpoints) {
315 open = false;
316 } else {
317 interface->endpoint[endpoints++] = (struct usbfs_endpoint){
318 .bEndpointAddress = descriptor[2], .bmAttributes = descriptor[3],
319 .wMaxPacketSize = (uint16_t)(descriptor[4] | descriptor[5] << 8)};
320 }
321 }
322 cursor += descriptor[0];
323 }
324 *offset = length ? length : 1;
325 return open && endpoints == interface->bNumEndpoints;
326}
327
328/** @brief Compare a previously discovered USB identity with current sysfs.
329 * @param device Device snapshot with sysfs name, bus, address and IDs.
330 * @return True if the checked attributes still match.
331 * @details Recheck after opening because disconnects and re-enumeration
332 * can invalidate a previously discovered bus address. */
333static inline bool usbfs_same_device(const struct usbfs_device *device)
334{
335 unsigned long bus, address, vendor, product;
336 return usbfs_read_number(device->name, "busnum", 10, 255, &bus) && bus == device->bus &&
337 usbfs_read_number(device->name, "devnum", 10, 127, &address) && address == device->address &&
338 usbfs_read_number(device->name, "idVendor", 16, 0xffff, &vendor) && vendor == device->vendor &&
339 usbfs_read_number(device->name, "idProduct", 16, 0xffff, &product) && product == device->product;
340}
341
342/** @brief Open the device node, rejecting a node now owned by a different device. */
343static inline int usbfs_open(const struct usbfs_device *device, struct usbfs_handle *handle)
344{
345 handle->fd = -1;
346 handle->capabilities = 0;
347 if (!device->bus || device->bus > 255 || !device->address || device->address > 127)
349 char path[64];
350 snprintf(path, sizeof(path), USBFS_DEVICE_ROOT "/%03u/%03u", device->bus, device->address);
351 int fd;
352 do fd = open(path, O_RDWR | O_CLOEXEC); while (fd < 0 && errno == EINTR);
353 if (fd < 0) {
354 if (errno == EACCES || errno == EPERM) return USBFS_ERROR_ACCESS;
355 return errno == ENOENT || errno == ENODEV || errno == ENXIO ? USBFS_ERROR_NO_DEVICE : USBFS_ERROR_IO;
356 }
357 struct stat status;
358 if (fstat(fd, &status) != 0 || !S_ISCHR(status.st_mode) || major(status.st_rdev) != USBFS_DEVICE_MAJOR ||
359 minor(status.st_rdev) != (device->bus - 1) * 128 + device->address - 1 || !usbfs_same_device(device)) {
360 close(fd);
362 }
363 uint32_t capabilities = 0;
364 if (ioctl(fd, USBDEVFS_GET_CAPABILITIES, &capabilities) != 0) capabilities = 0;
365 handle->fd = fd;
366 handle->capabilities = capabilities;
367 return USBFS_SUCCESS;
368}
369
370/** @brief Close the node; the kernel releases claimed interfaces and kills pending URBs. */
371static inline void usbfs_close(struct usbfs_handle *handle)
372{
373 if (handle->fd >= 0) close(handle->fd);
374 handle->fd = -1;
375}
376
377/** @brief Run a synchronous interface ioctl and translate its result.
378 * @param handle Serialized open device handle.
379 * @param request Linux usbfs ioctl number.
380 * @param argument Request-specific argument storage.
381 * @return USBFS_SUCCESS or a negative wrapper error.
382 * @details Retry interruptions, preserving the distinction between busy,
383 * disconnected and inaccessible devices for the calling policy. */
384static inline int usbfs_interface_ioctl(struct usbfs_handle *handle, unsigned long request, void *argument)
385{
386 if (handle->fd < 0) return USBFS_ERROR_NO_DEVICE;
387 int result;
388 do result = ioctl(handle->fd, request, argument); while (result < 0 && errno == EINTR);
389 if (result == 0) return USBFS_SUCCESS;
390 switch (errno) {
391 case EBUSY: return USBFS_ERROR_BUSY;
392 case ENOENT: case EINVAL: return USBFS_ERROR_NOT_FOUND;
393 case ENODEV: return USBFS_ERROR_NO_DEVICE;
394 case EACCES: case EPERM: return USBFS_ERROR_ACCESS;
395 default: return USBFS_ERROR_OTHER;
396 }
397}
398
399/** @brief Claim without detaching another owner; EBUSY is reported to the caller. */
400static inline int usbfs_claim_interface(struct usbfs_handle *handle, int interface)
401{
402 unsigned number = (unsigned)interface;
403 return interface < 0 ? USBFS_ERROR_INVALID_PARAM : usbfs_interface_ioctl(handle, USBDEVFS_CLAIMINTERFACE, &number);
404}
405
406/** @brief Release the numbered interface on an open device.
407 * @param handle Serialized device handle.
408 * @param interface Nonnegative USB interface number.
409 * @return USBFS_SUCCESS or a negative wrapper error.
410 * @details Release the claim without closing the device descriptor. */
411static inline int usbfs_release_interface(struct usbfs_handle *handle, int interface)
412{
413 unsigned number = (unsigned)interface;
414 return interface < 0 ? USBFS_ERROR_INVALID_PARAM : usbfs_interface_ioctl(handle, USBDEVFS_RELEASEINTERFACE, &number);
415}
416
417/** @brief Select an alternate setting for an interface.
418 * @param handle Serialized device handle.
419 * @param interface Nonnegative USB interface number.
420 * @param alternate Nonnegative alternate-setting number.
421 * @return USBFS_SUCCESS or a negative wrapper error.
422 * @details The caller must pair the setting with its matching endpoint descriptors. */
423static inline int usbfs_set_alternate(struct usbfs_handle *handle, int interface, int alternate)
424{
425 if (interface < 0 || alternate < 0) return USBFS_ERROR_INVALID_PARAM;
426 struct usbdevfs_setinterface setting = {.interface = (unsigned)interface, .altsetting = (unsigned)alternate};
427 return usbfs_interface_ioctl(handle, USBDEVFS_SETINTERFACE, &setting);
428}
429
430/**
431 * @brief Synchronous control transfer on endpoint zero.
432 * @param handle Serialized device handle.
433 * @param request_type USB bmRequestType, including direction.
434 * @param request USB bRequest.
435 * @param value USB wValue.
436 * @param index USB wIndex.
437 * @param[in,out] data Caller buffer; may be NULL only for a zero-length transfer.
438 * @param length Size of the data stage in bytes.
439 * @param timeout Nonzero kernel transfer timeout in milliseconds.
440 * @return Bytes transferred (>= 0) or a negative USBFS error.
441 * @details A short successful transfer can be meaningful; callers validate
442 * the returned length against the particular request's contract.
443 */
444static inline int usbfs_control_transfer(struct usbfs_handle *handle, uint8_t request_type, uint8_t request,
445 uint16_t value, uint16_t index, unsigned char *data,
446 uint16_t length, unsigned timeout)
447{
448 if (!handle || handle->fd < 0) return USBFS_ERROR_NO_DEVICE;
449 if ((!data && length) || !timeout) return USBFS_ERROR_INVALID_PARAM;
450 struct usbdevfs_ctrltransfer transfer = {.bRequestType = request_type, .bRequest = request,
451 .wValue = value, .wIndex = index, .wLength = length, .timeout = timeout, .data = data};
452 int result;
453 do result = ioctl(handle->fd, USBDEVFS_CONTROL, &transfer); while (result < 0 && errno == EINTR);
454 if (result >= 0) return result > length ? USBFS_ERROR_IO : result;
455 switch (errno) {
456 case ENODEV: case ESHUTDOWN: return USBFS_ERROR_NO_DEVICE;
457 case ETIMEDOUT: return USBFS_ERROR_TIMEOUT;
458 case EPIPE: return USBFS_ERROR_PIPE;
459 case EACCES: case EPERM: return USBFS_ERROR_ACCESS;
460 default: return USBFS_ERROR_IO;
461 }
462}
463
464/** @brief Clear a halted endpoint of a claimed interface; data toggles are reset by the kernel. */
465static inline int usbfs_clear_halt(struct usbfs_handle *handle, unsigned char endpoint)
466{
467 unsigned number = endpoint;
468 return usbfs_interface_ioctl(handle, USBDEVFS_CLEAR_HALT, &number);
469}
470
471/** @brief Read the clock used for bulk transfer deadlines.
472 * @return Monotonic milliseconds, or zero on failure.
473 * @details Keep a single time base across submit, wait and discard. */
474static inline uint64_t usbfs_now_ms(void)
475{
476 struct timespec now;
477 if (clock_gettime(CLOCK_MONOTONIC, &now) != 0) return 0;
478 return (uint64_t)now.tv_sec * 1000 + (uint64_t)now.tv_nsec / 1000000;
479}
480
481/** @brief Abandon the fd; closing it is the only way the kernel guarantees the URB is gone. */
482static inline int usbfs_drop(struct usbfs_handle *handle, int result)
483{
484 usbfs_close(handle);
485 return result;
486}
487
488/**
489 * @brief Submit one bulk URB and wait until it is reaped or @p deadline passes.
490 * @details On expiry the URB is discarded and reaped, preserving any bytes
491 * already received. Data reaches @p data only when the URB is reaped, so a URB
492 * that cannot be reaped within the discard grace is made harmless by closing.
493 */
494static inline int usbfs_bulk_urb(struct usbfs_handle *handle, unsigned char endpoint, unsigned char *data,
495 int length, int *actual, uint64_t deadline)
496{
497 struct usbdevfs_urb urb = {.type = USBDEVFS_URB_TYPE_BULK, .endpoint = endpoint,
498 .buffer = data, .buffer_length = length};
499 *actual = 0;
500 int result;
501 do result = ioctl(handle->fd, USBDEVFS_SUBMITURB, &urb); while (result < 0 && errno == EINTR);
502 if (result < 0) {
503 if (errno == ENODEV || errno == ESHUTDOWN) return USBFS_ERROR_NO_DEVICE;
504 if (errno == ENOMEM) return USBFS_ERROR_NO_MEM;
505 return errno == EPIPE ? USBFS_ERROR_PIPE : USBFS_ERROR_IO;
506 }
507 bool discarded = false, cancelled = false;
508 uint64_t limit = deadline;
509 for (;;) {
510 void *reaped = NULL;
511 if (ioctl(handle->fd, USBDEVFS_REAPURBNDELAY, &reaped) == 0) {
512 if (reaped != &urb) return usbfs_drop(handle, USBFS_ERROR_IO);
513 break;
514 }
515 int error = errno;
516 if (error == EINTR) continue;
517 if (error != EAGAIN) return usbfs_drop(handle, error == ENODEV ? USBFS_ERROR_NO_DEVICE : USBFS_ERROR_IO);
518 uint64_t now = usbfs_now_ms();
519 if (!now) return usbfs_drop(handle, USBFS_ERROR_IO);
520 if (!discarded && handle->cancel && *handle->cancel) {
521 (void)ioctl(handle->fd, USBDEVFS_DISCARDURB, &urb);
522 discarded = cancelled = true;
523 limit = now + USBFS_DISCARD_MS;
524 continue;
525 }
526 if (now >= limit) {
527 if (discarded) return usbfs_drop(handle, cancelled ? USBFS_ERROR_INTERRUPTED : USBFS_ERROR_TIMEOUT);
528 (void)ioctl(handle->fd, USBDEVFS_DISCARDURB, &urb);
529 discarded = true;
530 limit = now + USBFS_DISCARD_MS;
531 continue;
532 }
533 struct pollfd descriptor = {.fd = handle->fd, .events = POLLOUT};
534 uint64_t wait = limit - now;
535 if (poll(&descriptor, 1, wait > 1000 ? 1000 : (int)wait) < 0 && errno != EINTR)
536 return usbfs_drop(handle, USBFS_ERROR_IO);
537 }
538 if (urb.actual_length < 0 || urb.actual_length > length) return USBFS_ERROR_IO;
539 *actual = urb.actual_length;
540 switch (urb.status) {
541 case 0: case -EREMOTEIO: return USBFS_SUCCESS;
542 case -ENOENT: case -ECONNRESET:
544 case -ENODEV: case -ESHUTDOWN: return USBFS_ERROR_NO_DEVICE;
545 case -EPIPE: return USBFS_ERROR_PIPE;
546 case -EOVERFLOW: return USBFS_ERROR_OVERFLOW;
547 default: return USBFS_ERROR_IO;
548 }
549}
550
551/**
552 * @brief Synchronous bulk transfer with libusb_bulk_transfer() semantics.
553 * @param handle Serialized device handle holding the interface claim.
554 * @param endpoint Bulk endpoint address including the direction bit.
555 * @param[in,out] data Buffer for @p length bytes.
556 * @param length Requested bytes, nonnegative.
557 * @param[out] transferred Required byte count; may be nonzero on failure.
558 * @param timeout Nonzero total timeout in milliseconds.
559 * @return USBFS_SUCCESS or a negative wrapper error.
560 * @details IN transfers are capped at one URB; OUT transfers are split only on
561 * kernels without NO_PACKET_SIZE_LIM, sharing one deadline.
562 */
563static inline int usbfs_bulk_transfer(struct usbfs_handle *handle, unsigned char endpoint, unsigned char *data,
564 int length, int *transferred, unsigned timeout)
565{
566 *transferred = 0;
567 if (!handle || handle->fd < 0) return USBFS_ERROR_NO_DEVICE;
568 if (length < 0 || (!data && length) || !timeout) return USBFS_ERROR_INVALID_PARAM;
569 uint64_t now = usbfs_now_ms();
570 if (!now) return USBFS_ERROR_IO;
571 uint64_t deadline = now + timeout;
572 int limit = handle->capabilities & USBDEVFS_CAP_NO_PACKET_SIZE_LIM ? INT_MAX : USBFS_LEGACY_TRANSFER;
573 if (endpoint & USBFS_ENDPOINT_IN)
574 return usbfs_bulk_urb(handle, endpoint, data, length < limit ? length : limit, transferred, deadline);
575 do {
576 int chunk = length - *transferred < limit ? length - *transferred : limit;
577 int actual;
578 int result = usbfs_bulk_urb(handle, endpoint, data + *transferred, chunk, &actual, deadline);
579 *transferred += actual;
580 if (result || actual != chunk) return result;
581 } while (*transferred < length);
582 return USBFS_SUCCESS;
583}
584
585#endif
static unsigned capacity[COVERAGE_CAMERAS]
int descriptor
Definition chdk_pipe.c:142
void(* close)(struct usbfs_handle *)
Definition chdkbridge.c:57
int(* open)(const struct usbfs_device *, struct usbfs_handle *)
Definition chdkbridge.c:56
union dc_shot_union request
struct jpeg_error_mgr error
Definition lwir_image.c:60
static bool transfer(const struct lwir_state_io *io, uint64_t deadline, bool input, uint16_t address, uint8_t *data, unsigned length, struct lwir_state_value *value)
Perform one deadline-bounded mailbox transfer and classify failure.
Definition lwir_state.c:102
static const char header[]
Definition pose_log.c:87
static size_t count
Definition pose_log.c:79
int fd
Definition serial.c:39
One enumerated USB device; a value copy, valid after enumeration ends.
Definition usbfs.h:73
char name[32]
Definition usbfs.h:74
uint16_t vendor
Definition usbfs.h:76
uint16_t product
Definition usbfs.h:76
uint8_t ports[USBFS_MAX_PORTS]
Definition usbfs.h:77
unsigned bus
Definition usbfs.h:75
unsigned address
Definition usbfs.h:75
int depth
Definition usbfs.h:78
DIR * directory
Definition usbfs.h:93
uint16_t wMaxPacketSize
Definition usbfs.h:83
uint8_t bmAttributes
Definition usbfs.h:82
uint8_t bEndpointAddress
Definition usbfs.h:82
Open usbfs file; fd is -1 when closed or dropped after a lost URB.
Definition usbfs.h:97
const volatile sig_atomic_t * cancel
Definition usbfs.h:100
uint32_t capabilities
Definition usbfs.h:99
uint8_t bInterfaceProtocol
Definition usbfs.h:88
uint8_t bInterfaceNumber
Definition usbfs.h:87
uint8_t bInterfaceClass
Definition usbfs.h:87
uint8_t bInterfaceSubClass
Definition usbfs.h:88
uint8_t bNumEndpoints
Definition usbfs.h:88
struct usbfs_endpoint endpoint[USBFS_MAX_ENDPOINTS]
Definition usbfs.h:89
uint8_t bAlternateSetting
Definition usbfs.h:87
static bool usbfs_parse_name(const char *name, struct usbfs_device *device)
Parse "BUS-PORT[.PORT...]"; rejects root hubs and interface entries.
Definition usbfs.h:166
static int usbfs_bulk_urb(struct usbfs_handle *handle, unsigned char endpoint, unsigned char *data, int length, int *actual, uint64_t deadline)
Submit one bulk URB and wait until it is reaped or deadline passes.
Definition usbfs.h:494
static bool usbfs_next_interface(const uint8_t *config, size_t length, size_t *offset, struct usbfs_interface *interface)
Return the next complete interface/alternate setting in a configuration.
Definition usbfs.h:293
static int usbfs_select_config(const uint8_t *descriptors, size_t length, unsigned value, const uint8_t **config, size_t *config_length)
Locate configuration value in raw sysfs descriptors.
Definition usbfs.h:236
static int usbfs_clear_halt(struct usbfs_handle *handle, unsigned char endpoint)
Clear a halted endpoint of a claimed interface; data toggles are reset by the kernel.
Definition usbfs.h:465
static bool usbfs_available(void)
True when sysfs device listing and usbfs nodes are reachable.
Definition usbfs.h:127
static int usbfs_interface_ioctl(struct usbfs_handle *handle, unsigned long request, void *argument)
Run a synchronous interface ioctl and translate its result.
Definition usbfs.h:384
static const char * usbfs_error_name(int error)
Get the diagnostic name of a usbfs result.
Definition usbfs.h:107
@ USBFS_ERROR_PIPE
Definition usbfs.h:58
@ USBFS_ERROR_ACCESS
Definition usbfs.h:56
@ USBFS_SUCCESS
Definition usbfs.h:55
@ USBFS_ERROR_OVERFLOW
Definition usbfs.h:57
@ USBFS_ERROR_NO_MEM
Definition usbfs.h:58
@ USBFS_ERROR_BUSY
Definition usbfs.h:57
@ USBFS_ERROR_OTHER
Definition usbfs.h:59
@ USBFS_ERROR_INVALID_PARAM
Definition usbfs.h:55
@ USBFS_ERROR_NOT_FOUND
Definition usbfs.h:56
@ USBFS_ERROR_NO_DEVICE
Definition usbfs.h:56
@ USBFS_ERROR_TIMEOUT
Definition usbfs.h:57
@ USBFS_ERROR_INTERRUPTED
Definition usbfs.h:58
@ USBFS_ERROR_IO
Definition usbfs.h:55
static int usbfs_release_interface(struct usbfs_handle *handle, int interface)
Release the numbered interface on an open device.
Definition usbfs.h:411
static int usbfs_bulk_transfer(struct usbfs_handle *handle, unsigned char endpoint, unsigned char *data, int length, int *transferred, unsigned timeout)
Synchronous bulk transfer with libusb_bulk_transfer() semantics.
Definition usbfs.h:563
static int usbfs_drop(struct usbfs_handle *handle, int result)
Abandon the fd; closing it is the only way the kernel guarantees the URB is gone.
Definition usbfs.h:482
static int usbfs_active_config(const struct usbfs_device *device, uint8_t *buffer, size_t capacity, const uint8_t **config, size_t *config_length)
Read the active configuration into buffer; config points inside it.
Definition usbfs.h:256
static void usbfs_devices_close(struct usbfs_devices *devices)
Release the sysfs enumeration stream.
Definition usbfs.h:225
static int usbfs_devices_open(struct usbfs_devices *devices)
Start a streaming sysfs enumeration.
Definition usbfs.h:192
#define USBFS_DEVICE_ROOT
Definition usbfs.h:51
static int usbfs_control_transfer(struct usbfs_handle *handle, uint8_t request_type, uint8_t request, uint16_t value, uint16_t index, unsigned char *data, uint16_t length, unsigned timeout)
Synchronous control transfer on endpoint zero.
Definition usbfs.h:444
@ USBFS_TRANSFER_TYPE_MASK
Definition usbfs.h:63
@ USBFS_TRANSFER_TYPE_BULK
Definition usbfs.h:64
@ USBFS_DISCARD_MS
Definition usbfs.h:68
@ USBFS_DEVICE_MAJOR
Definition usbfs.h:69
@ USBFS_LEGACY_TRANSFER
Definition usbfs.h:67
@ USBFS_ENDPOINT_IN
Definition usbfs.h:63
@ USBFS_TRANSFER_TYPE_INTERRUPT
Definition usbfs.h:64
@ USBFS_MAX_ENDPOINTS
Definition usbfs.h:65
@ USBFS_MAX_PORTS
Definition usbfs.h:65
@ USBFS_DESCRIPTOR_CAPACITY
Definition usbfs.h:66
static int usbfs_open(const struct usbfs_device *device, struct usbfs_handle *handle)
Open the device node, rejecting a node now owned by a different device.
Definition usbfs.h:343
static bool usbfs_read_number(const char *device, const char *attribute, int base, unsigned long maximum, unsigned long *value)
Read one bounded unsigned numeric sysfs attribute.
Definition usbfs.h:141
static bool usbfs_same_device(const struct usbfs_device *device)
Compare a previously discovered USB identity with current sysfs.
Definition usbfs.h:333
static uint64_t usbfs_now_ms(void)
Read the clock used for bulk transfer deadlines.
Definition usbfs.h:474
#define USBFS_SYSFS_ROOT
Definition usbfs.h:50
static int usbfs_set_alternate(struct usbfs_handle *handle, int interface, int alternate)
Select an alternate setting for an interface.
Definition usbfs.h:423
static int usbfs_devices_next(struct usbfs_devices *devices, struct usbfs_device *device)
Definition usbfs.h:200
static int usbfs_claim_interface(struct usbfs_handle *handle, int interface)
Claim without detaching another owner; EBUSY is reported to the caller.
Definition usbfs.h:400
static void usbfs_close(struct usbfs_handle *handle)
Close the node; the kernel releases claimed interfaces and kills pending URBs.
Definition usbfs.h:371
struct usher_control_result result
Definition usher.c:377