summaryrefslogtreecommitdiffstats
path: root/include/libusb-1.0/os/linux_usbfs.c
diff options
context:
space:
mode:
authorGravatar Martin Szulecki2013-09-26 10:41:13 +0200
committerGravatar Martin Szulecki2013-09-26 10:41:13 +0200
commit07391edbf2ca1feaf4357259fd9e477ec53e6d81 (patch)
tree09bc0ab7de21b994dcb039a3e652ccfe173c310d /include/libusb-1.0/os/linux_usbfs.c
parentafb8735176869db20219c35a341e89158651bffe (diff)
downloadlibirecovery-07391edbf2ca1feaf4357259fd9e477ec53e6d81.tar.gz
libirecovery-07391edbf2ca1feaf4357259fd9e477ec53e6d81.tar.bz2
Remove obsolete "in-tree" copy of libusb-1.0
Diffstat (limited to 'include/libusb-1.0/os/linux_usbfs.c')
-rw-r--r--include/libusb-1.0/os/linux_usbfs.c2220
1 files changed, 0 insertions, 2220 deletions
diff --git a/include/libusb-1.0/os/linux_usbfs.c b/include/libusb-1.0/os/linux_usbfs.c
deleted file mode 100644
index a44688d..0000000
--- a/include/libusb-1.0/os/linux_usbfs.c
+++ /dev/null
@@ -1,2220 +0,0 @@
1/*
2 * Linux usbfs backend for libusb
3 * Copyright (C) 2007-2009 Daniel Drake <dsd@gentoo.org>
4 * Copyright (c) 2001 Johannes Erdfelt <johannes@erdfelt.com>
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20
21#include <config.h>
22#include <ctype.h>
23#include <dirent.h>
24#include <errno.h>
25#include <fcntl.h>
26#include <poll.h>
27#include <pthread.h>
28#include <stdio.h>
29#include <stdlib.h>
30#include <string.h>
31#include <sys/ioctl.h>
32#include <sys/stat.h>
33#include <sys/types.h>
34#include <sys/utsname.h>
35#include <unistd.h>
36
37#include "libusb.h"
38#include "libusbi.h"
39#include "linux_usbfs.h"
40
41/* sysfs vs usbfs:
42 * opening a usbfs node causes the device to be resumed, so we attempt to
43 * avoid this during enumeration.
44 *
45 * sysfs allows us to read the kernel's in-memory copies of device descriptors
46 * and so forth, avoiding the need to open the device:
47 * - The binary "descriptors" file was added in 2.6.23.
48 * - The "busnum" file was added in 2.6.22
49 * - The "devnum" file has been present since pre-2.6.18
50 * - the "bConfigurationValue" file has been present since pre-2.6.18
51 *
52 * If we have bConfigurationValue, busnum, and devnum, then we can determine
53 * the active configuration without having to open the usbfs node in RDWR mode.
54 * We assume this is the case if we see the busnum file (indicates 2.6.22+).
55 * The busnum file is important as that is the only way we can relate sysfs
56 * devices to usbfs nodes.
57 *
58 * If we also have descriptors, we can obtain the device descriptor and active
59 * configuration without touching usbfs at all.
60 *
61 * The descriptors file originally only contained the active configuration
62 * descriptor alongside the device descriptor, but all configurations are
63 * included as of Linux 2.6.26.
64 */
65
66/* endianness for multi-byte fields:
67 *
68 * Descriptors exposed by usbfs have the multi-byte fields in the device
69 * descriptor as host endian. Multi-byte fields in the other descriptors are
70 * bus-endian. The kernel documentation says otherwise, but it is wrong.
71 */
72
73static const char *usbfs_path = NULL;
74
75/* Linux 2.6.32 adds support for a bulk continuation URB flag. this basically
76 * allows us to mark URBs as being part of a specific logical transfer when
77 * we submit them to the kernel. then, on any error error except a
78 * cancellation, all URBs within that transfer will be cancelled with the
79 * endpoint is disabled, meaning that no more data can creep in during the
80 * time it takes to cancel the remaining URBs.
81 *
82 * The BULK_CONTINUATION flag must be set on all URBs within a bulk transfer
83 * (in either direction) except the first.
84 * For IN transfers, we must also set SHORT_NOT_OK on all the URBs.
85 * For OUT transfers, SHORT_NOT_OK must not be set. The effective behaviour
86 * (where an OUT transfer does not complete, the rest of the URBs in the
87 * transfer get cancelled) is already in effect, and setting this flag is
88 * disallowed (a kernel with USB debugging enabled will reject such URBs).
89 */
90static int supports_flag_bulk_continuation = -1;
91
92/* clock ID for monotonic clock, as not all clock sources are available on all
93 * systems. appropriate choice made at initialization time. */
94static clockid_t monotonic_clkid = -1;
95
96/* do we have a busnum to relate devices? this also implies that we can read
97 * the active configuration through bConfigurationValue */
98static int sysfs_can_relate_devices = -1;
99
100/* do we have a descriptors file? */
101static int sysfs_has_descriptors = -1;
102
103struct linux_device_priv {
104 char *sysfs_dir;
105 unsigned char *dev_descriptor;
106 unsigned char *config_descriptor;
107};
108
109struct linux_device_handle_priv {
110 int fd;
111};
112
113enum reap_action {
114 NORMAL = 0,
115 /* submission failed after the first URB, so await cancellation/completion
116 * of all the others */
117 SUBMIT_FAILED,
118
119 /* cancelled by user or timeout */
120 CANCELLED,
121
122 /* completed multi-URB transfer in non-final URB */
123 COMPLETED_EARLY,
124
125 /* one or more urbs encountered a low-level error */
126 ERROR,
127};
128
129struct linux_transfer_priv {
130 union {
131 struct usbfs_urb *urbs;
132 struct usbfs_urb **iso_urbs;
133 };
134
135 enum reap_action reap_action;
136 int num_urbs;
137 unsigned int num_retired;
138 enum libusb_transfer_status reap_status;
139
140 /* next iso packet in user-supplied transfer to be populated */
141 int iso_packet_offset;
142};
143
144static void __get_usbfs_path(struct libusb_device *dev, char *path)
145{
146 snprintf(path, PATH_MAX, "%s/%03d/%03d", usbfs_path, dev->bus_number,
147 dev->device_address);
148}
149
150static struct linux_device_priv *__device_priv(struct libusb_device *dev)
151{
152 return (struct linux_device_priv *) dev->os_priv;
153}
154
155static struct linux_device_handle_priv *__device_handle_priv(
156 struct libusb_device_handle *handle)
157{
158 return (struct linux_device_handle_priv *) handle->os_priv;
159}
160
161static int check_usb_vfs(const char *dirname)
162{
163 DIR *dir;
164 struct dirent *entry;
165 int found = 0;
166
167 dir = opendir(dirname);
168 if (!dir)
169 return 0;
170
171 while ((entry = readdir(dir)) != NULL) {
172 if (entry->d_name[0] == '.')
173 continue;
174
175 /* We assume if we find any files that it must be the right place */
176 found = 1;
177 break;
178 }
179
180 closedir(dir);
181 return found;
182}
183
184static const char *find_usbfs_path(void)
185{
186 const char *path = "/dev/bus/usb";
187 const char *ret = NULL;
188
189 if (check_usb_vfs(path)) {
190 ret = path;
191 } else {
192 path = "/proc/bus/usb";
193 if (check_usb_vfs(path))
194 ret = path;
195 }
196
197 usbi_dbg("found usbfs at %s", ret);
198 return ret;
199}
200
201/* the monotonic clock is not usable on all systems (e.g. embedded ones often
202 * seem to lack it). fall back to REALTIME if we have to. */
203static clockid_t find_monotonic_clock(void)
204{
205 struct timespec ts;
206 int r;
207
208#ifdef CLOCK_MONOTONIC
209 /* Linux 2.6.28 adds CLOCK_MONOTONIC_RAW but we don't use it
210 * because it's not available through timerfd */
211 r = clock_gettime(CLOCK_MONOTONIC, &ts);
212 if (r == 0)
213 return CLOCK_MONOTONIC;
214 usbi_dbg("monotonic clock doesn't work, errno %d", errno);
215#endif
216
217 return CLOCK_REALTIME;
218}
219
220/* bulk continuation URB flag available from Linux 2.6.32 */
221static int check_flag_bulk_continuation(void)
222{
223 struct utsname uts;
224 int sublevel;
225
226 if (uname(&uts) < 0)
227 return -1;
228 if (strlen(uts.release) < 4)
229 return 0;
230 if (strncmp(uts.release, "2.6.", 4) != 0)
231 return 0;
232
233 sublevel = atoi(uts.release + 4);
234 return sublevel >= 32;
235}
236
237static int op_init(struct libusb_context *ctx)
238{
239 struct stat statbuf;
240 int r;
241
242 usbfs_path = find_usbfs_path();
243 if (!usbfs_path) {
244 usbi_err(ctx, "could not find usbfs");
245 return LIBUSB_ERROR_OTHER;
246 }
247
248 if (monotonic_clkid == -1)
249 monotonic_clkid = find_monotonic_clock();
250
251 if (supports_flag_bulk_continuation == -1) {
252 supports_flag_bulk_continuation = check_flag_bulk_continuation();
253 if (supports_flag_bulk_continuation == -1) {
254 usbi_err(ctx, "error checking for bulk continuation support");
255 return LIBUSB_ERROR_OTHER;
256 }
257 }
258
259 if (supports_flag_bulk_continuation)
260 usbi_dbg("bulk continuation flag supported");
261
262 r = stat(SYSFS_DEVICE_PATH, &statbuf);
263 if (r == 0 && S_ISDIR(statbuf.st_mode)) {
264 usbi_dbg("found usb devices in sysfs");
265 } else {
266 usbi_dbg("sysfs usb info not available");
267 sysfs_has_descriptors = 0;
268 sysfs_can_relate_devices = 0;
269 }
270
271 return 0;
272}
273
274static int usbfs_get_device_descriptor(struct libusb_device *dev,
275 unsigned char *buffer)
276{
277 struct linux_device_priv *priv = __device_priv(dev);
278
279 /* return cached copy */
280 memcpy(buffer, priv->dev_descriptor, DEVICE_DESC_LENGTH);
281 return 0;
282}
283
284static int __open_sysfs_attr(struct libusb_device *dev, const char *attr)
285{
286 struct linux_device_priv *priv = __device_priv(dev);
287 char filename[PATH_MAX];
288 int fd;
289
290 snprintf(filename, PATH_MAX, "%s/%s/%s",
291 SYSFS_DEVICE_PATH, priv->sysfs_dir, attr);
292 fd = open(filename, O_RDONLY);
293 if (fd < 0) {
294 usbi_err(DEVICE_CTX(dev),
295 "open %s failed ret=%d errno=%d", filename, fd, errno);
296 return LIBUSB_ERROR_IO;
297 }
298
299 return fd;
300}
301
302static int sysfs_get_device_descriptor(struct libusb_device *dev,
303 unsigned char *buffer)
304{
305 int fd;
306 ssize_t r;
307
308 /* sysfs provides access to an in-memory copy of the device descriptor,
309 * so we use that rather than keeping our own copy */
310
311 fd = __open_sysfs_attr(dev, "descriptors");
312 if (fd < 0)
313 return fd;
314
315 r = read(fd, buffer, DEVICE_DESC_LENGTH);;
316 close(fd);
317 if (r < 0) {
318 usbi_err(DEVICE_CTX(dev), "read failed, ret=%d errno=%d", fd, errno);
319 return LIBUSB_ERROR_IO;
320 } else if (r < DEVICE_DESC_LENGTH) {
321 usbi_err(DEVICE_CTX(dev), "short read %d/%d", r, DEVICE_DESC_LENGTH);
322 return LIBUSB_ERROR_IO;
323 }
324
325 return 0;
326}
327
328static int op_get_device_descriptor(struct libusb_device *dev,
329 unsigned char *buffer, int *host_endian)
330{
331 if (sysfs_has_descriptors) {
332 return sysfs_get_device_descriptor(dev, buffer);
333 } else {
334 *host_endian = 1;
335 return usbfs_get_device_descriptor(dev, buffer);
336 }
337}
338
339static int usbfs_get_active_config_descriptor(struct libusb_device *dev,
340 unsigned char *buffer, size_t len)
341{
342 struct linux_device_priv *priv = __device_priv(dev);
343 if (!priv->config_descriptor)
344 return LIBUSB_ERROR_NOT_FOUND; /* device is unconfigured */
345
346 /* retrieve cached copy */
347 memcpy(buffer, priv->config_descriptor, len);
348 return 0;
349}
350
351/* read the bConfigurationValue for a device */
352static int sysfs_get_active_config(struct libusb_device *dev, int *config)
353{
354 char *endptr;
355 char tmp[4] = {0, 0, 0, 0};
356 long num;
357 int fd;
358 size_t r;
359
360 fd = __open_sysfs_attr(dev, "bConfigurationValue");
361 if (fd < 0)
362 return fd;
363
364 r = read(fd, tmp, sizeof(tmp));
365 close(fd);
366 if (r < 0) {
367 usbi_err(DEVICE_CTX(dev),
368 "read bConfigurationValue failed ret=%d errno=%d", r, errno);
369 return LIBUSB_ERROR_IO;
370 } else if (r == 0) {
371 usbi_err(DEVICE_CTX(dev), "device unconfigured");
372 *config = -1;
373 return 0;
374 }
375
376 if (tmp[sizeof(tmp) - 1] != 0) {
377 usbi_err(DEVICE_CTX(dev), "not null-terminated?");
378 return LIBUSB_ERROR_IO;
379 } else if (tmp[0] == 0) {
380 usbi_err(DEVICE_CTX(dev), "no configuration value?");
381 return LIBUSB_ERROR_IO;
382 }
383
384 num = strtol(tmp, &endptr, 10);
385 if (endptr == tmp) {
386 usbi_err(DEVICE_CTX(dev), "error converting '%s' to integer", tmp);
387 return LIBUSB_ERROR_IO;
388 }
389
390 *config = (int) num;
391 return 0;
392}
393
394/* takes a usbfs/descriptors fd seeked to the start of a configuration, and
395 * seeks to the next one. */
396static int seek_to_next_config(struct libusb_context *ctx, int fd,
397 int host_endian)
398{
399 struct libusb_config_descriptor config;
400 unsigned char tmp[6];
401 off_t off;
402 int r;
403
404 /* read first 6 bytes of descriptor */
405 r = read(fd, tmp, sizeof(tmp));
406 if (r < 0) {
407 usbi_err(ctx, "read failed ret=%d errno=%d", r, errno);
408 return LIBUSB_ERROR_IO;
409 } else if (r < sizeof(tmp)) {
410 usbi_err(ctx, "short descriptor read %d/%d", r, sizeof(tmp));
411 return LIBUSB_ERROR_IO;
412 }
413
414 /* seek forward to end of config */
415 usbi_parse_descriptor(tmp, "bbwbb", &config, host_endian);
416 off = lseek(fd, config.wTotalLength - sizeof(tmp), SEEK_CUR);
417 if (off < 0) {
418 usbi_err(ctx, "seek failed ret=%d errno=%d", off, errno);
419 return LIBUSB_ERROR_IO;
420 }
421
422 return 0;
423}
424
425static int sysfs_get_active_config_descriptor(struct libusb_device *dev,
426 unsigned char *buffer, size_t len)
427{
428 int fd;
429 ssize_t r;
430 off_t off;
431 int to_copy;
432 int config;
433 unsigned char tmp[6];
434
435 r = sysfs_get_active_config(dev, &config);
436 if (r < 0)
437 return r;
438 if (config == -1)
439 return LIBUSB_ERROR_NOT_FOUND;
440
441 usbi_dbg("active configuration %d", config);
442
443 /* sysfs provides access to an in-memory copy of the device descriptor,
444 * so we use that rather than keeping our own copy */
445
446 fd = __open_sysfs_attr(dev, "descriptors");
447 if (fd < 0)
448 return fd;
449
450 /* device might have been unconfigured since we read bConfigurationValue,
451 * so first check that there is any config descriptor data at all... */
452 off = lseek(fd, 0, SEEK_END);
453 if (off < 1) {
454 usbi_err(DEVICE_CTX(dev), "end seek failed, ret=%d errno=%d",
455 off, errno);
456 close(fd);
457 return LIBUSB_ERROR_IO;
458 } else if (off == DEVICE_DESC_LENGTH) {
459 close(fd);
460 return LIBUSB_ERROR_NOT_FOUND;
461 }
462
463 off = lseek(fd, DEVICE_DESC_LENGTH, SEEK_SET);
464 if (off < 0) {
465 usbi_err(DEVICE_CTX(dev), "seek failed, ret=%d errno=%d", off, errno);
466 close(fd);
467 return LIBUSB_ERROR_IO;
468 }
469
470 /* unbounded loop: we expect the descriptor to be present under all
471 * circumstances */
472 while (1) {
473 r = read(fd, tmp, sizeof(tmp));
474 if (r < 0) {
475 usbi_err(DEVICE_CTX(dev), "read failed, ret=%d errno=%d",
476 fd, errno);
477 return LIBUSB_ERROR_IO;
478 } else if (r < sizeof(tmp)) {
479 usbi_err(DEVICE_CTX(dev), "short read %d/%d", r, sizeof(tmp));
480 return LIBUSB_ERROR_IO;
481 }
482
483 /* check bConfigurationValue */
484 if (tmp[5] == config)
485 break;
486
487 /* try the next descriptor */
488 off = lseek(fd, 0 - sizeof(tmp), SEEK_CUR);
489 if (off < 0)
490 return LIBUSB_ERROR_IO;
491
492 r = seek_to_next_config(DEVICE_CTX(dev), fd, 1);
493 if (r < 0)
494 return r;
495 }
496
497 to_copy = (len < sizeof(tmp)) ? len : sizeof(tmp);
498 memcpy(buffer, tmp, to_copy);
499 if (len > sizeof(tmp)) {
500 r = read(fd, buffer + sizeof(tmp), len - sizeof(tmp));
501 if (r < 0) {
502 usbi_err(DEVICE_CTX(dev), "read failed, ret=%d errno=%d",
503 fd, errno);
504 r = LIBUSB_ERROR_IO;
505 } else if (r == 0) {
506 usbi_dbg("device is unconfigured");
507 r = LIBUSB_ERROR_NOT_FOUND;
508 } else if (r < len - sizeof(tmp)) {
509 usbi_err(DEVICE_CTX(dev), "short read %d/%d", r, len);
510 r = LIBUSB_ERROR_IO;
511 }
512 } else {
513 r = 0;
514 }
515
516 close(fd);
517 return r;
518}
519
520static int op_get_active_config_descriptor(struct libusb_device *dev,
521 unsigned char *buffer, size_t len, int *host_endian)
522{
523 if (sysfs_has_descriptors) {
524 return sysfs_get_active_config_descriptor(dev, buffer, len);
525 } else {
526 return usbfs_get_active_config_descriptor(dev, buffer, len);
527 }
528}
529
530/* takes a usbfs fd, attempts to find the requested config and copy a certain
531 * amount of it into an output buffer. */
532static int get_config_descriptor(struct libusb_context *ctx, int fd,
533 uint8_t config_index, unsigned char *buffer, size_t len)
534{
535 off_t off;
536 ssize_t r;
537
538 off = lseek(fd, DEVICE_DESC_LENGTH, SEEK_SET);
539 if (off < 0) {
540 usbi_err(ctx, "seek failed ret=%d errno=%d", off, errno);
541 return LIBUSB_ERROR_IO;
542 }
543
544 /* might need to skip some configuration descriptors to reach the
545 * requested configuration */
546 while (config_index > 0) {
547 r = seek_to_next_config(ctx, fd, 0);
548 if (r < 0)
549 return r;
550 config_index--;
551 }
552
553 /* read the rest of the descriptor */
554 r = read(fd, buffer, len);
555 if (r < 0) {
556 usbi_err(ctx, "read failed ret=%d errno=%d", r, errno);
557 return LIBUSB_ERROR_IO;
558 } else if (r < len) {
559 usbi_err(ctx, "short output read %d/%d", r, len);
560 return LIBUSB_ERROR_IO;
561 }
562
563 return 0;
564}
565
566static int op_get_config_descriptor(struct libusb_device *dev,
567 uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
568{
569 char filename[PATH_MAX];
570 int fd;
571 int r;
572
573 /* always read from usbfs: sysfs only has the active descriptor
574 * this will involve waking the device up, but oh well! */
575
576 /* FIXME: the above is no longer true, new kernels have all descriptors
577 * in the descriptors file. but its kinda hard to detect if the kernel
578 * is sufficiently new. */
579
580 __get_usbfs_path(dev, filename);
581 fd = open(filename, O_RDONLY);
582 if (fd < 0) {
583 usbi_err(DEVICE_CTX(dev),
584 "open '%s' failed, ret=%d errno=%d", filename, fd, errno);
585 return LIBUSB_ERROR_IO;
586 }
587
588 r = get_config_descriptor(DEVICE_CTX(dev), fd, config_index, buffer, len);
589 close(fd);
590 return r;
591}
592
593/* cache the active config descriptor in memory. a value of -1 means that
594 * we aren't sure which one is active, so just assume the first one.
595 * only for usbfs. */
596static int cache_active_config(struct libusb_device *dev, int fd,
597 int active_config)
598{
599 struct linux_device_priv *priv = __device_priv(dev);
600 struct libusb_config_descriptor config;
601 unsigned char tmp[8];
602 unsigned char *buf;
603 int idx;
604 int r;
605
606 if (active_config == -1) {
607 idx = 0;
608 } else {
609 r = usbi_get_config_index_by_value(dev, active_config, &idx);
610 if (r < 0)
611 return r;
612 if (idx == -1)
613 return LIBUSB_ERROR_NOT_FOUND;
614 }
615
616 r = get_config_descriptor(DEVICE_CTX(dev), fd, idx, tmp, sizeof(tmp));
617 if (r < 0) {
618 usbi_err(DEVICE_CTX(dev), "first read error %d", r);
619 return r;
620 }
621
622 usbi_parse_descriptor(tmp, "bbw", &config, 0);
623 buf = malloc(config.wTotalLength);
624 if (!buf)
625 return LIBUSB_ERROR_NO_MEM;
626
627 r = get_config_descriptor(DEVICE_CTX(dev), fd, idx, buf,
628 config.wTotalLength);
629 if (r < 0) {
630 free(buf);
631 return r;
632 }
633
634 if (priv->config_descriptor)
635 free(priv->config_descriptor);
636 priv->config_descriptor = buf;
637 return 0;
638}
639
640/* send a control message to retrieve active configuration */
641static int usbfs_get_active_config(struct libusb_device *dev, int fd)
642{
643 unsigned char active_config = 0;
644 int r;
645
646 struct usbfs_ctrltransfer ctrl = {
647 .bmRequestType = LIBUSB_ENDPOINT_IN,
648 .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
649 .wValue = 0,
650 .wIndex = 0,
651 .wLength = 1,
652 .timeout = 1000,
653 .data = &active_config
654 };
655
656 r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
657 if (r < 0) {
658 if (errno == ENODEV)
659 return LIBUSB_ERROR_NO_DEVICE;
660
661 /* we hit this error path frequently with buggy devices :( */
662 usbi_warn(DEVICE_CTX(dev),
663 "get_configuration failed ret=%d errno=%d", r, errno);
664 return LIBUSB_ERROR_IO;
665 }
666
667 return active_config;
668}
669
670static int initialize_device(struct libusb_device *dev, uint8_t busnum,
671 uint8_t devaddr, const char *sysfs_dir)
672{
673 struct linux_device_priv *priv = __device_priv(dev);
674 unsigned char *dev_buf;
675 char path[PATH_MAX];
676 int fd;
677 int active_config = 0;
678 int device_configured = 1;
679 ssize_t r;
680
681 dev->bus_number = busnum;
682 dev->device_address = devaddr;
683
684 if (sysfs_dir) {
685 priv->sysfs_dir = malloc(strlen(sysfs_dir) + 1);
686 if (!priv->sysfs_dir)
687 return LIBUSB_ERROR_NO_MEM;
688 strcpy(priv->sysfs_dir, sysfs_dir);
689 }
690
691 if (sysfs_has_descriptors)
692 return 0;
693
694 /* cache device descriptor in memory so that we can retrieve it later
695 * without waking the device up (op_get_device_descriptor) */
696
697 priv->dev_descriptor = NULL;
698 priv->config_descriptor = NULL;
699
700 if (sysfs_can_relate_devices) {
701 int tmp = sysfs_get_active_config(dev, &active_config);
702 if (tmp < 0)
703 return tmp;
704 if (active_config == -1)
705 device_configured = 0;
706 }
707
708 __get_usbfs_path(dev, path);
709 fd = open(path, O_RDWR);
710 if (fd < 0 && errno == EACCES) {
711 fd = open(path, O_RDONLY);
712 /* if we only have read-only access to the device, we cannot
713 * send a control message to determine the active config. just
714 * assume the first one is active. */
715 active_config = -1;
716 }
717
718 if (fd < 0) {
719 usbi_err(DEVICE_CTX(dev), "open failed, ret=%d errno=%d", fd, errno);
720 return LIBUSB_ERROR_IO;
721 }
722
723 if (!sysfs_can_relate_devices) {
724 if (active_config == -1) {
725 /* if we only have read-only access to the device, we cannot
726 * send a control message to determine the active config. just
727 * assume the first one is active. */
728 usbi_warn(DEVICE_CTX(dev), "access to %s is read-only; cannot "
729 "determine active configuration descriptor", path);
730 } else {
731 active_config = usbfs_get_active_config(dev, fd);
732 if (active_config == LIBUSB_ERROR_IO) {
733 /* buggy devices sometimes fail to report their active config.
734 * assume unconfigured and continue the probing */
735 usbi_warn(DEVICE_CTX(dev), "couldn't query active "
736 "configuration, assumung unconfigured");
737 device_configured = 0;
738 } else if (active_config < 0) {
739 close(fd);
740 return active_config;
741 } else if (active_config == 0) {
742 /* some buggy devices have a configuration 0, but we're
743 * reaching into the corner of a corner case here, so let's
744 * not support buggy devices in these circumstances.
745 * stick to the specs: a configuration value of 0 means
746 * unconfigured. */
747 usbi_dbg("active cfg 0? assuming unconfigured device");
748 device_configured = 0;
749 }
750 }
751 }
752
753 dev_buf = malloc(DEVICE_DESC_LENGTH);
754 if (!dev_buf) {
755 close(fd);
756 return LIBUSB_ERROR_NO_MEM;
757 }
758
759 r = read(fd, dev_buf, DEVICE_DESC_LENGTH);
760 if (r < 0) {
761 usbi_err(DEVICE_CTX(dev),
762 "read descriptor failed ret=%d errno=%d", fd, errno);
763 free(dev_buf);
764 close(fd);
765 return LIBUSB_ERROR_IO;
766 } else if (r < DEVICE_DESC_LENGTH) {
767 usbi_err(DEVICE_CTX(dev), "short descriptor read (%d)", r);
768 free(dev_buf);
769 close(fd);
770 return LIBUSB_ERROR_IO;
771 }
772
773 /* bit of a hack: set num_configurations now because cache_active_config()
774 * calls usbi_get_config_index_by_value() which uses it */
775 dev->num_configurations = dev_buf[DEVICE_DESC_LENGTH - 1];
776
777 if (device_configured) {
778 r = cache_active_config(dev, fd, active_config);
779 if (r < 0) {
780 close(fd);
781 free(dev_buf);
782 return r;
783 }
784 }
785
786 close(fd);
787 priv->dev_descriptor = dev_buf;
788 return 0;
789}
790
791static int enumerate_device(struct libusb_context *ctx,
792 struct discovered_devs **_discdevs, uint8_t busnum, uint8_t devaddr,
793 const char *sysfs_dir)
794{
795 struct discovered_devs *discdevs;
796 unsigned long session_id;
797 int need_unref = 0;
798 struct libusb_device *dev;
799 int r = 0;
800
801 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
802 * will be reused. instead we should add a simple sysfs attribute with
803 * a session ID. */
804 session_id = busnum << 8 | devaddr;
805 usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr,
806 session_id);
807
808 dev = usbi_get_device_by_session_id(ctx, session_id);
809 if (dev) {
810 usbi_dbg("using existing device for %d/%d (session %ld)",
811 busnum, devaddr, session_id);
812 } else {
813 usbi_dbg("allocating new device for %d/%d (session %ld)",
814 busnum, devaddr, session_id);
815 dev = usbi_alloc_device(ctx, session_id);
816 if (!dev)
817 return LIBUSB_ERROR_NO_MEM;
818 need_unref = 1;
819 r = initialize_device(dev, busnum, devaddr, sysfs_dir);
820 if (r < 0)
821 goto out;
822 r = usbi_sanitize_device(dev);
823 if (r < 0)
824 goto out;
825 }
826
827 discdevs = discovered_devs_append(*_discdevs, dev);
828 if (!discdevs)
829 r = LIBUSB_ERROR_NO_MEM;
830 else
831 *_discdevs = discdevs;
832
833out:
834 if (need_unref)
835 libusb_unref_device(dev);
836 return r;
837}
838
839/* open a bus directory and adds all discovered devices to discdevs. on
840 * failure (non-zero return) the pre-existing discdevs should be destroyed
841 * (and devices freed). on success, the new discdevs pointer should be used
842 * as it may have been moved. */
843static int usbfs_scan_busdir(struct libusb_context *ctx,
844 struct discovered_devs **_discdevs, uint8_t busnum)
845{
846 DIR *dir;
847 char dirpath[PATH_MAX];
848 struct dirent *entry;
849 struct discovered_devs *discdevs = *_discdevs;
850 int r = 0;
851
852 snprintf(dirpath, PATH_MAX, "%s/%03d", usbfs_path, busnum);
853 usbi_dbg("%s", dirpath);
854 dir = opendir(dirpath);
855 if (!dir) {
856 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
857 /* FIXME: should handle valid race conditions like hub unplugged
858 * during directory iteration - this is not an error */
859 return LIBUSB_ERROR_IO;
860 }
861
862 while ((entry = readdir(dir))) {
863 int devaddr;
864
865 if (entry->d_name[0] == '.')
866 continue;
867
868 devaddr = atoi(entry->d_name);
869 if (devaddr == 0) {
870 usbi_dbg("unknown dir entry %s", entry->d_name);
871 continue;
872 }
873
874 r = enumerate_device(ctx, &discdevs, busnum, (uint8_t) devaddr, NULL);
875 if (r < 0)
876 goto out;
877 }
878
879 *_discdevs = discdevs;
880out:
881 closedir(dir);
882 return r;
883}
884
885static int usbfs_get_device_list(struct libusb_context *ctx,
886 struct discovered_devs **_discdevs)
887{
888 struct dirent *entry;
889 DIR *buses = opendir(usbfs_path);
890 struct discovered_devs *discdevs = *_discdevs;
891 int r = 0;
892
893 if (!buses) {
894 usbi_err(ctx, "opendir buses failed errno=%d", errno);
895 return LIBUSB_ERROR_IO;
896 }
897
898 while ((entry = readdir(buses))) {
899 struct discovered_devs *discdevs_new = discdevs;
900 int busnum;
901
902 if (entry->d_name[0] == '.')
903 continue;
904
905 busnum = atoi(entry->d_name);
906 if (busnum == 0) {
907 usbi_dbg("unknown dir entry %s", entry->d_name);
908 continue;
909 }
910
911 r = usbfs_scan_busdir(ctx, &discdevs_new, busnum);
912 if (r < 0)
913 goto out;
914 discdevs = discdevs_new;
915 }
916
917out:
918 closedir(buses);
919 *_discdevs = discdevs;
920 return r;
921
922}
923
924static int sysfs_scan_device(struct libusb_context *ctx,
925 struct discovered_devs **_discdevs, const char *devname,
926 int *usbfs_fallback)
927{
928 int r;
929 FILE *fd;
930 char filename[PATH_MAX];
931 int busnum;
932 int devaddr;
933
934 usbi_dbg("scan %s", devname);
935
936 /* determine descriptors presence ahead of time, we need to know this
937 * when we reach initialize_device */
938 if (sysfs_has_descriptors == -1) {
939 struct stat statbuf;
940
941 snprintf(filename, PATH_MAX, "%s/%s/descriptors", SYSFS_DEVICE_PATH,
942 devname);
943 r = stat(filename, &statbuf);
944 if (r == 0 && S_ISREG(statbuf.st_mode)) {
945 usbi_dbg("sysfs descriptors available");
946 sysfs_has_descriptors = 1;
947 } else {
948 usbi_dbg("sysfs descriptors not available");
949 sysfs_has_descriptors = 0;
950 }
951 }
952
953 snprintf(filename, PATH_MAX, "%s/%s/busnum", SYSFS_DEVICE_PATH, devname);
954 fd = fopen(filename, "r");
955 if (!fd) {
956 if (errno == ENOENT) {
957 usbi_dbg("busnum not found, cannot relate sysfs to usbfs, "
958 "falling back on pure usbfs");
959 sysfs_can_relate_devices = 0;
960 *usbfs_fallback = 1;
961 return LIBUSB_ERROR_OTHER;
962 }
963 usbi_err(ctx, "open busnum failed, errno=%d", errno);
964 return LIBUSB_ERROR_IO;
965 }
966
967 sysfs_can_relate_devices = 1;
968
969 r = fscanf(fd, "%d", &busnum);
970 fclose(fd);
971 if (r != 1) {
972 usbi_err(ctx, "fscanf busnum returned %d, errno=%d", r, errno);
973 return LIBUSB_ERROR_IO;
974 }
975
976 snprintf(filename, PATH_MAX, "%s/%s/devnum", SYSFS_DEVICE_PATH, devname);
977 fd = fopen(filename, "r");
978 if (!fd) {
979 usbi_err(ctx, "open devnum failed, errno=%d", errno);
980 return LIBUSB_ERROR_IO;
981 }
982
983 r = fscanf(fd, "%d", &devaddr);
984 fclose(fd);
985 if (r != 1) {
986 usbi_err(ctx, "fscanf devnum returned %d, errno=%d", r, errno);
987 return LIBUSB_ERROR_IO;
988 }
989
990 usbi_dbg("bus=%d dev=%d", busnum, devaddr);
991 if (busnum > 255 || devaddr > 255)
992 return LIBUSB_ERROR_INVALID_PARAM;
993
994 return enumerate_device(ctx, _discdevs, busnum & 0xff, devaddr & 0xff,
995 devname);
996}
997
998static int sysfs_get_device_list(struct libusb_context *ctx,
999 struct discovered_devs **_discdevs, int *usbfs_fallback)
1000{
1001 struct discovered_devs *discdevs = *_discdevs;
1002 DIR *devices = opendir(SYSFS_DEVICE_PATH);
1003 struct dirent *entry;
1004 int r = 0;
1005
1006 if (!devices) {
1007 usbi_err(ctx, "opendir devices failed errno=%d", errno);
1008 return LIBUSB_ERROR_IO;
1009 }
1010
1011 while ((entry = readdir(devices))) {
1012 struct discovered_devs *discdevs_new = discdevs;
1013
1014 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1015 || strchr(entry->d_name, ':'))
1016 continue;
1017
1018 r = sysfs_scan_device(ctx, &discdevs_new, entry->d_name,
1019 usbfs_fallback);
1020 if (r < 0)
1021 goto out;
1022 discdevs = discdevs_new;
1023 }
1024
1025out:
1026 closedir(devices);
1027 *_discdevs = discdevs;
1028 return r;
1029}
1030
1031static int op_get_device_list(struct libusb_context *ctx,
1032 struct discovered_devs **_discdevs)
1033{
1034 /* we can retrieve device list and descriptors from sysfs or usbfs.
1035 * sysfs is preferable, because if we use usbfs we end up resuming
1036 * any autosuspended USB devices. however, sysfs is not available
1037 * everywhere, so we need a usbfs fallback too.
1038 *
1039 * as described in the "sysfs vs usbfs" comment, sometimes we have
1040 * sysfs but not enough information to relate sysfs devices to usbfs
1041 * nodes. the usbfs_fallback variable is used to indicate that we should
1042 * fall back on usbfs.
1043 */
1044 if (sysfs_can_relate_devices != 0) {
1045 int usbfs_fallback = 0;
1046 int r = sysfs_get_device_list(ctx, _discdevs, &usbfs_fallback);
1047 if (!usbfs_fallback)
1048 return r;
1049 }
1050
1051 return usbfs_get_device_list(ctx, _discdevs);
1052}
1053
1054static int op_open(struct libusb_device_handle *handle)
1055{
1056 struct linux_device_handle_priv *hpriv = __device_handle_priv(handle);
1057 char filename[PATH_MAX];
1058
1059 __get_usbfs_path(handle->dev, filename);
1060 hpriv->fd = open(filename, O_RDWR);
1061 if (hpriv->fd < 0) {
1062 if (errno == EACCES) {
1063 usbi_err(HANDLE_CTX(handle), "libusb couldn't open USB device %s: "
1064 "Permission denied.", filename);
1065 usbi_err(HANDLE_CTX(handle),
1066 "libusb requires write access to USB device nodes.");
1067 return LIBUSB_ERROR_ACCESS;
1068 } else if (errno == ENOENT) {
1069 return LIBUSB_ERROR_NO_DEVICE;
1070 } else {
1071 usbi_err(HANDLE_CTX(handle),
1072 "open failed, code %d errno %d", hpriv->fd, errno);
1073 return LIBUSB_ERROR_IO;
1074 }
1075 }
1076
1077 return usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1078}
1079
1080static void op_close(struct libusb_device_handle *dev_handle)
1081{
1082 int fd = __device_handle_priv(dev_handle)->fd;
1083 usbi_remove_pollfd(HANDLE_CTX(dev_handle), fd);
1084 close(fd);
1085}
1086
1087static int op_get_configuration(struct libusb_device_handle *handle,
1088 int *config)
1089{
1090 int r;
1091 if (sysfs_can_relate_devices != 1)
1092 return LIBUSB_ERROR_NOT_SUPPORTED;
1093
1094 r = sysfs_get_active_config(handle->dev, config);
1095 if (*config == -1)
1096 *config = 0;
1097
1098 return 0;
1099}
1100
1101static int op_set_configuration(struct libusb_device_handle *handle, int config)
1102{
1103 struct linux_device_priv *priv = __device_priv(handle->dev);
1104 int fd = __device_handle_priv(handle)->fd;
1105 int r = ioctl(fd, IOCTL_USBFS_SETCONFIG, &config);
1106 if (r) {
1107 if (errno == EINVAL)
1108 return LIBUSB_ERROR_NOT_FOUND;
1109 else if (errno == EBUSY)
1110 return LIBUSB_ERROR_BUSY;
1111 else if (errno == ENODEV)
1112 return LIBUSB_ERROR_NO_DEVICE;
1113
1114 usbi_err(HANDLE_CTX(handle), "failed, error %d errno %d", r, errno);
1115 return LIBUSB_ERROR_OTHER;
1116 }
1117
1118 if (!sysfs_has_descriptors) {
1119 /* update our cached active config descriptor */
1120 if (config == -1) {
1121 if (priv->config_descriptor) {
1122 free(priv->config_descriptor);
1123 priv->config_descriptor = NULL;
1124 }
1125 } else {
1126 r = cache_active_config(handle->dev, fd, config);
1127 if (r < 0)
1128 usbi_warn(HANDLE_CTX(handle),
1129 "failed to update cached config descriptor, error %d", r);
1130 }
1131 }
1132
1133 return 0;
1134}
1135
1136static int op_claim_interface(struct libusb_device_handle *handle, int iface)
1137{
1138 int fd = __device_handle_priv(handle)->fd;
1139 int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface);
1140 if (r) {
1141 if (errno == ENOENT)
1142 return LIBUSB_ERROR_NOT_FOUND;
1143 else if (errno == EBUSY)
1144 return LIBUSB_ERROR_BUSY;
1145 else if (errno == ENODEV)
1146 return LIBUSB_ERROR_NO_DEVICE;
1147
1148 usbi_err(HANDLE_CTX(handle),
1149 "claim interface failed, error %d errno %d", r, errno);
1150 return LIBUSB_ERROR_OTHER;
1151 }
1152 return 0;
1153}
1154
1155static int op_release_interface(struct libusb_device_handle *handle, int iface)
1156{
1157 int fd = __device_handle_priv(handle)->fd;
1158 int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface);
1159 if (r) {
1160 if (errno == ENODEV)
1161 return LIBUSB_ERROR_NO_DEVICE;
1162
1163 usbi_err(HANDLE_CTX(handle),
1164 "release interface failed, error %d errno %d", r, errno);
1165 return LIBUSB_ERROR_OTHER;
1166 }
1167 return 0;
1168}
1169
1170static int op_set_interface(struct libusb_device_handle *handle, int iface,
1171 int altsetting)
1172{
1173 int fd = __device_handle_priv(handle)->fd;
1174 struct usbfs_setinterface setintf;
1175 int r;
1176
1177 setintf.interface = iface;
1178 setintf.altsetting = altsetting;
1179 r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf);
1180 if (r) {
1181 if (errno == EINVAL)
1182 return LIBUSB_ERROR_NOT_FOUND;
1183 else if (errno == ENODEV)
1184 return LIBUSB_ERROR_NO_DEVICE;
1185
1186 usbi_err(HANDLE_CTX(handle),
1187 "setintf failed error %d errno %d", r, errno);
1188 return LIBUSB_ERROR_OTHER;
1189 }
1190
1191 return 0;
1192}
1193
1194static int op_clear_halt(struct libusb_device_handle *handle,
1195 unsigned char endpoint)
1196{
1197 int fd = __device_handle_priv(handle)->fd;
1198 unsigned int _endpoint = endpoint;
1199 int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1200 if (r) {
1201 if (errno == ENOENT)
1202 return LIBUSB_ERROR_NOT_FOUND;
1203 else if (errno == ENODEV)
1204 return LIBUSB_ERROR_NO_DEVICE;
1205
1206 usbi_err(HANDLE_CTX(handle),
1207 "clear_halt failed error %d errno %d", r, errno);
1208 return LIBUSB_ERROR_OTHER;
1209 }
1210
1211 return 0;
1212}
1213
1214static int op_reset_device(struct libusb_device_handle *handle)
1215{
1216 int fd = __device_handle_priv(handle)->fd;
1217 int r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1218 if (r) {
1219 if (errno == ENODEV)
1220 return LIBUSB_ERROR_NOT_FOUND;
1221
1222 usbi_err(HANDLE_CTX(handle),
1223 "reset failed error %d errno %d", r, errno);
1224 return LIBUSB_ERROR_OTHER;
1225 }
1226
1227 return 0;
1228}
1229
1230static int op_kernel_driver_active(struct libusb_device_handle *handle,
1231 int interface)
1232{
1233 int fd = __device_handle_priv(handle)->fd;
1234 struct usbfs_getdriver getdrv;
1235 int r;
1236
1237 getdrv.interface = interface;
1238 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1239 if (r) {
1240 if (errno == ENODATA)
1241 return 0;
1242 else if (errno == ENODEV)
1243 return LIBUSB_ERROR_NO_DEVICE;
1244
1245 usbi_err(HANDLE_CTX(handle),
1246 "get driver failed error %d errno %d", r, errno);
1247 return LIBUSB_ERROR_OTHER;
1248 }
1249
1250 return 1;
1251}
1252
1253static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1254 int interface)
1255{
1256 int fd = __device_handle_priv(handle)->fd;
1257 struct usbfs_ioctl command;
1258 int r;
1259
1260 command.ifno = interface;
1261 command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1262 command.data = NULL;
1263
1264 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1265 if (r) {
1266 if (errno == ENODATA)
1267 return LIBUSB_ERROR_NOT_FOUND;
1268 else if (errno == EINVAL)
1269 return LIBUSB_ERROR_INVALID_PARAM;
1270 else if (errno == ENODEV)
1271 return LIBUSB_ERROR_NO_DEVICE;
1272
1273 usbi_err(HANDLE_CTX(handle),
1274 "detach failed error %d errno %d", r, errno);
1275 return LIBUSB_ERROR_OTHER;
1276 }
1277
1278 return 0;
1279}
1280
1281static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1282 int interface)
1283{
1284 int fd = __device_handle_priv(handle)->fd;
1285 struct usbfs_ioctl command;
1286 int r;
1287
1288 command.ifno = interface;
1289 command.ioctl_code = IOCTL_USBFS_CONNECT;
1290 command.data = NULL;
1291
1292 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1293 if (r < 0) {
1294 if (errno == ENODATA)
1295 return LIBUSB_ERROR_NOT_FOUND;
1296 else if (errno == EINVAL)
1297 return LIBUSB_ERROR_INVALID_PARAM;
1298 else if (errno == ENODEV)
1299 return LIBUSB_ERROR_NO_DEVICE;
1300 else if (errno == EBUSY)
1301 return LIBUSB_ERROR_BUSY;
1302
1303 usbi_err(HANDLE_CTX(handle),
1304 "attach failed error %d errno %d", r, errno);
1305 return LIBUSB_ERROR_OTHER;
1306 } else if (r == 0) {
1307 return LIBUSB_ERROR_NOT_FOUND;
1308 }
1309
1310 return 0;
1311}
1312
1313static void op_destroy_device(struct libusb_device *dev)
1314{
1315 struct linux_device_priv *priv = __device_priv(dev);
1316 if (!sysfs_has_descriptors) {
1317 if (priv->dev_descriptor)
1318 free(priv->dev_descriptor);
1319 if (priv->config_descriptor)
1320 free(priv->config_descriptor);
1321 }
1322 if (priv->sysfs_dir)
1323 free(priv->sysfs_dir);
1324}
1325
1326static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1327{
1328 int i;
1329 for (i = 0; i < tpriv->num_urbs; i++) {
1330 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1331 if (!urb)
1332 break;
1333 free(urb);
1334 }
1335
1336 free(tpriv->iso_urbs);
1337 tpriv->iso_urbs = NULL;
1338}
1339
1340static int submit_bulk_transfer(struct usbi_transfer *itransfer,
1341 unsigned char urb_type)
1342{
1343 struct libusb_transfer *transfer =
1344 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1345 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1346 struct linux_device_handle_priv *dpriv =
1347 __device_handle_priv(transfer->dev_handle);
1348 struct usbfs_urb *urbs;
1349 int is_out = (transfer->endpoint & LIBUSB_ENDPOINT_DIR_MASK)
1350 == LIBUSB_ENDPOINT_OUT;
1351 int r;
1352 int i;
1353 size_t alloc_size;
1354
1355 if (tpriv->urbs)
1356 return LIBUSB_ERROR_BUSY;
1357
1358 /* usbfs places a 16kb limit on bulk URBs. we divide up larger requests
1359 * into smaller units to meet such restriction, then fire off all the
1360 * units at once. it would be simpler if we just fired one unit at a time,
1361 * but there is a big performance gain through doing it this way. */
1362 int num_urbs = transfer->length / MAX_BULK_BUFFER_LENGTH;
1363 int last_urb_partial = 0;
1364
1365 if (transfer->length == 0) {
1366 num_urbs = 1;
1367 } else if ((transfer->length % MAX_BULK_BUFFER_LENGTH) > 0) {
1368 last_urb_partial = 1;
1369 num_urbs++;
1370 }
1371 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
1372 transfer->length);
1373 alloc_size = num_urbs * sizeof(struct usbfs_urb);
1374 urbs = malloc(alloc_size);
1375 if (!urbs)
1376 return LIBUSB_ERROR_NO_MEM;
1377 memset(urbs, 0, alloc_size);
1378 tpriv->urbs = urbs;
1379 tpriv->num_urbs = num_urbs;
1380 tpriv->num_retired = 0;
1381 tpriv->reap_action = NORMAL;
1382 tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
1383
1384 for (i = 0; i < num_urbs; i++) {
1385 struct usbfs_urb *urb = &urbs[i];
1386 urb->usercontext = itransfer;
1387 urb->type = urb_type;
1388 urb->endpoint = transfer->endpoint;
1389 urb->buffer = transfer->buffer + (i * MAX_BULK_BUFFER_LENGTH);
1390 if (supports_flag_bulk_continuation && !is_out)
1391 urb->flags = USBFS_URB_SHORT_NOT_OK;
1392 if (i == num_urbs - 1 && last_urb_partial)
1393 urb->buffer_length = transfer->length % MAX_BULK_BUFFER_LENGTH;
1394 else if (transfer->length == 0)
1395 urb->buffer_length = 0;
1396 else
1397 urb->buffer_length = MAX_BULK_BUFFER_LENGTH;
1398
1399 if (i > 0 && supports_flag_bulk_continuation)
1400 urb->flags |= USBFS_URB_BULK_CONTINUATION;
1401
1402 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1403 if (r < 0) {
1404 int j;
1405
1406 if (errno == ENODEV) {
1407 r = LIBUSB_ERROR_NO_DEVICE;
1408 } else {
1409 usbi_err(TRANSFER_CTX(transfer),
1410 "submiturb failed error %d errno=%d", r, errno);
1411 r = LIBUSB_ERROR_IO;
1412 }
1413
1414 /* if the first URB submission fails, we can simply free up and
1415 * return failure immediately. */
1416 if (i == 0) {
1417 usbi_dbg("first URB failed, easy peasy");
1418 free(urbs);
1419 tpriv->urbs = NULL;
1420 return r;
1421 }
1422
1423 /* if it's not the first URB that failed, the situation is a bit
1424 * tricky. we may need to discard all previous URBs. there are
1425 * complications:
1426 * - discarding is asynchronous - discarded urbs will be reaped
1427 * later. the user must not have freed the transfer when the
1428 * discarded URBs are reaped, otherwise libusb will be using
1429 * freed memory.
1430 * - the earlier URBs may have completed successfully and we do
1431 * not want to throw away any data.
1432 * - this URB failing may be no error; EREMOTEIO means that
1433 * this transfer simply didn't need all the URBs we submitted
1434 * so, we report that the transfer was submitted successfully and
1435 * in case of error we discard all previous URBs. later when
1436 * the final reap completes we can report error to the user,
1437 * or success if an earlier URB was completed successfully.
1438 */
1439 tpriv->reap_action = EREMOTEIO == errno ? COMPLETED_EARLY : SUBMIT_FAILED;
1440
1441 /* The URBs we haven't submitted yet we count as already
1442 * retired. */
1443 tpriv->num_retired += num_urbs - i;
1444
1445 /* If we completed short then don't try to discard. */
1446 if (COMPLETED_EARLY == tpriv->reap_action)
1447 return 0;
1448
1449 for (j = 0; j < i; j++) {
1450 int tmp = ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, &urbs[j]);
1451 if (tmp && errno != EINVAL)
1452 usbi_warn(TRANSFER_CTX(transfer),
1453 "unrecognised discard errno %d", errno);
1454 }
1455
1456 usbi_dbg("reporting successful submission but waiting for %d "
1457 "discards before reporting error", i);
1458 return 0;
1459 }
1460 }
1461
1462 return 0;
1463}
1464
1465static int submit_iso_transfer(struct usbi_transfer *itransfer)
1466{
1467 struct libusb_transfer *transfer =
1468 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1469 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1470 struct linux_device_handle_priv *dpriv =
1471 __device_handle_priv(transfer->dev_handle);
1472 struct usbfs_urb **urbs;
1473 size_t alloc_size;
1474 int num_packets = transfer->num_iso_packets;
1475 int i;
1476 int this_urb_len = 0;
1477 int num_urbs = 1;
1478 int packet_offset = 0;
1479 unsigned int packet_len;
1480 unsigned char *urb_buffer = transfer->buffer;
1481
1482 if (tpriv->iso_urbs)
1483 return LIBUSB_ERROR_BUSY;
1484
1485 /* usbfs places a 32kb limit on iso URBs. we divide up larger requests
1486 * into smaller units to meet such restriction, then fire off all the
1487 * units at once. it would be simpler if we just fired one unit at a time,
1488 * but there is a big performance gain through doing it this way. */
1489
1490 /* calculate how many URBs we need */
1491 for (i = 0; i < num_packets; i++) {
1492 int space_remaining = MAX_ISO_BUFFER_LENGTH - this_urb_len;
1493 packet_len = transfer->iso_packet_desc[i].length;
1494
1495 if (packet_len > space_remaining) {
1496 num_urbs++;
1497 this_urb_len = packet_len;
1498 } else {
1499 this_urb_len += packet_len;
1500 }
1501 }
1502 usbi_dbg("need %d 32k URBs for transfer", num_urbs);
1503
1504 alloc_size = num_urbs * sizeof(*urbs);
1505 urbs = malloc(alloc_size);
1506 if (!urbs)
1507 return LIBUSB_ERROR_NO_MEM;
1508 memset(urbs, 0, alloc_size);
1509
1510 tpriv->iso_urbs = urbs;
1511 tpriv->num_urbs = num_urbs;
1512 tpriv->num_retired = 0;
1513 tpriv->reap_action = NORMAL;
1514 tpriv->iso_packet_offset = 0;
1515
1516 /* allocate + initialize each URB with the correct number of packets */
1517 for (i = 0; i < num_urbs; i++) {
1518 struct usbfs_urb *urb;
1519 int space_remaining_in_urb = MAX_ISO_BUFFER_LENGTH;
1520 int urb_packet_offset = 0;
1521 unsigned char *urb_buffer_orig = urb_buffer;
1522 int j;
1523 int k;
1524
1525 /* swallow up all the packets we can fit into this URB */
1526 while (packet_offset < transfer->num_iso_packets) {
1527 packet_len = transfer->iso_packet_desc[packet_offset].length;
1528 if (packet_len <= space_remaining_in_urb) {
1529 /* throw it in */
1530 urb_packet_offset++;
1531 packet_offset++;
1532 space_remaining_in_urb -= packet_len;
1533 urb_buffer += packet_len;
1534 } else {
1535 /* it can't fit, save it for the next URB */
1536 break;
1537 }
1538 }
1539
1540 alloc_size = sizeof(*urb)
1541 + (urb_packet_offset * sizeof(struct usbfs_iso_packet_desc));
1542 urb = malloc(alloc_size);
1543 if (!urb) {
1544 free_iso_urbs(tpriv);
1545 return LIBUSB_ERROR_NO_MEM;
1546 }
1547 memset(urb, 0, alloc_size);
1548 urbs[i] = urb;
1549
1550 /* populate packet lengths */
1551 for (j = 0, k = packet_offset - urb_packet_offset;
1552 k < packet_offset; k++, j++) {
1553 packet_len = transfer->iso_packet_desc[k].length;
1554 urb->iso_frame_desc[j].length = packet_len;
1555 }
1556
1557 urb->usercontext = itransfer;
1558 urb->type = USBFS_URB_TYPE_ISO;
1559 /* FIXME: interface for non-ASAP data? */
1560 urb->flags = USBFS_URB_ISO_ASAP;
1561 urb->endpoint = transfer->endpoint;
1562 urb->number_of_packets = urb_packet_offset;
1563 urb->buffer = urb_buffer_orig;
1564 }
1565
1566 /* submit URBs */
1567 for (i = 0; i < num_urbs; i++) {
1568 int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
1569 if (r < 0) {
1570 int j;
1571
1572 if (errno == ENODEV) {
1573 r = LIBUSB_ERROR_NO_DEVICE;
1574 } else {
1575 usbi_err(TRANSFER_CTX(transfer),
1576 "submiturb failed error %d errno=%d", r, errno);
1577 r = LIBUSB_ERROR_IO;
1578 }
1579
1580 /* if the first URB submission fails, we can simply free up and
1581 * return failure immediately. */
1582 if (i == 0) {
1583 usbi_dbg("first URB failed, easy peasy");
1584 free_iso_urbs(tpriv);
1585 return r;
1586 }
1587
1588 /* if it's not the first URB that failed, the situation is a bit
1589 * tricky. we must discard all previous URBs. there are
1590 * complications:
1591 * - discarding is asynchronous - discarded urbs will be reaped
1592 * later. the user must not have freed the transfer when the
1593 * discarded URBs are reaped, otherwise libusb will be using
1594 * freed memory.
1595 * - the earlier URBs may have completed successfully and we do
1596 * not want to throw away any data.
1597 * so, in this case we discard all the previous URBs BUT we report
1598 * that the transfer was submitted successfully. then later when
1599 * the final discard completes we can report error to the user.
1600 */
1601 tpriv->reap_action = SUBMIT_FAILED;
1602
1603 /* The URBs we haven't submitted yet we count as already
1604 * retired. */
1605 tpriv->num_retired = num_urbs - i;
1606 for (j = 0; j < i; j++) {
1607 int tmp = ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urbs[j]);
1608 if (tmp && errno != EINVAL)
1609 usbi_warn(TRANSFER_CTX(transfer),
1610 "unrecognised discard errno %d", errno);
1611 }
1612
1613 usbi_dbg("reporting successful submission but waiting for %d "
1614 "discards before reporting error", i);
1615 return 0;
1616 }
1617 }
1618
1619 return 0;
1620}
1621
1622static int submit_control_transfer(struct usbi_transfer *itransfer)
1623{
1624 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1625 struct libusb_transfer *transfer =
1626 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1627 struct linux_device_handle_priv *dpriv =
1628 __device_handle_priv(transfer->dev_handle);
1629 struct usbfs_urb *urb;
1630 int r;
1631
1632 if (tpriv->urbs)
1633 return LIBUSB_ERROR_BUSY;
1634
1635 if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
1636 return LIBUSB_ERROR_INVALID_PARAM;
1637
1638 urb = malloc(sizeof(struct usbfs_urb));
1639 if (!urb)
1640 return LIBUSB_ERROR_NO_MEM;
1641 memset(urb, 0, sizeof(struct usbfs_urb));
1642 tpriv->urbs = urb;
1643 tpriv->reap_action = NORMAL;
1644
1645 urb->usercontext = itransfer;
1646 urb->type = USBFS_URB_TYPE_CONTROL;
1647 urb->endpoint = transfer->endpoint;
1648 urb->buffer = transfer->buffer;
1649 urb->buffer_length = transfer->length;
1650
1651 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1652 if (r < 0) {
1653 free(urb);
1654 tpriv->urbs = NULL;
1655 if (errno == ENODEV)
1656 return LIBUSB_ERROR_NO_DEVICE;
1657
1658 usbi_err(TRANSFER_CTX(transfer),
1659 "submiturb failed error %d errno=%d", r, errno);
1660 return LIBUSB_ERROR_IO;
1661 }
1662 return 0;
1663}
1664
1665static int op_submit_transfer(struct usbi_transfer *itransfer)
1666{
1667 struct libusb_transfer *transfer =
1668 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1669
1670 switch (transfer->type) {
1671 case LIBUSB_TRANSFER_TYPE_CONTROL:
1672 return submit_control_transfer(itransfer);
1673 case LIBUSB_TRANSFER_TYPE_BULK:
1674 return submit_bulk_transfer(itransfer, USBFS_URB_TYPE_BULK);
1675 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1676 return submit_bulk_transfer(itransfer, USBFS_URB_TYPE_INTERRUPT);
1677 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1678 return submit_iso_transfer(itransfer);
1679 default:
1680 usbi_err(TRANSFER_CTX(transfer),
1681 "unknown endpoint type %d", transfer->type);
1682 return LIBUSB_ERROR_INVALID_PARAM;
1683 }
1684}
1685
1686static int cancel_control_transfer(struct usbi_transfer *itransfer)
1687{
1688 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1689 struct libusb_transfer *transfer =
1690 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1691 struct linux_device_handle_priv *dpriv =
1692 __device_handle_priv(transfer->dev_handle);
1693 int r;
1694
1695 if (!tpriv->urbs)
1696 return LIBUSB_ERROR_NOT_FOUND;
1697
1698 tpriv->reap_action = CANCELLED;
1699 r = ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, tpriv->urbs);
1700 if(r) {
1701 if (errno == EINVAL) {
1702 usbi_dbg("URB not found --> assuming ready to be reaped");
1703 return 0;
1704 } else {
1705 usbi_err(TRANSFER_CTX(transfer),
1706 "unrecognised DISCARD code %d", errno);
1707 return LIBUSB_ERROR_OTHER;
1708 }
1709 }
1710
1711 return 0;
1712}
1713
1714static int cancel_bulk_transfer(struct usbi_transfer *itransfer)
1715{
1716 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1717 struct libusb_transfer *transfer =
1718 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1719 struct linux_device_handle_priv *dpriv =
1720 __device_handle_priv(transfer->dev_handle);
1721 int i;
1722
1723 if (!tpriv->urbs)
1724 return LIBUSB_ERROR_NOT_FOUND;
1725
1726 if (tpriv->reap_action != ERROR)
1727 tpriv->reap_action = CANCELLED;
1728
1729 for (i = 0; i < tpriv->num_urbs; i++) {
1730 int tmp = ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, &tpriv->urbs[i]);
1731 if (tmp && errno != EINVAL)
1732 usbi_warn(TRANSFER_CTX(transfer),
1733 "unrecognised discard errno %d", errno);
1734 }
1735 return 0;
1736}
1737
1738static int cancel_iso_transfer(struct usbi_transfer *itransfer)
1739{
1740 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1741 struct libusb_transfer *transfer =
1742 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1743 struct linux_device_handle_priv *dpriv =
1744 __device_handle_priv(transfer->dev_handle);
1745 int i;
1746
1747 if (!tpriv->iso_urbs)
1748 return LIBUSB_ERROR_NOT_FOUND;
1749
1750 tpriv->reap_action = CANCELLED;
1751 for (i = 0; i < tpriv->num_urbs; i++) {
1752 int tmp = ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, tpriv->iso_urbs[i]);
1753 if (tmp && errno != EINVAL)
1754 usbi_warn(TRANSFER_CTX(transfer),
1755 "unrecognised discard errno %d", errno);
1756 }
1757 return 0;
1758}
1759
1760static int op_cancel_transfer(struct usbi_transfer *itransfer)
1761{
1762 struct libusb_transfer *transfer =
1763 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1764
1765 switch (transfer->type) {
1766 case LIBUSB_TRANSFER_TYPE_CONTROL:
1767 return cancel_control_transfer(itransfer);
1768 case LIBUSB_TRANSFER_TYPE_BULK:
1769 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1770 return cancel_bulk_transfer(itransfer);
1771 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1772 return cancel_iso_transfer(itransfer);
1773 default:
1774 usbi_err(TRANSFER_CTX(transfer),
1775 "unknown endpoint type %d", transfer->type);
1776 return LIBUSB_ERROR_INVALID_PARAM;
1777 }
1778}
1779
1780static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
1781{
1782 struct libusb_transfer *transfer =
1783 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1784 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1785
1786 switch (transfer->type) {
1787 case LIBUSB_TRANSFER_TYPE_CONTROL:
1788 case LIBUSB_TRANSFER_TYPE_BULK:
1789 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1790 free(tpriv->urbs);
1791 tpriv->urbs = NULL;
1792 break;
1793 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1794 free_iso_urbs(tpriv);
1795 break;
1796 default:
1797 usbi_err(TRANSFER_CTX(transfer),
1798 "unknown endpoint type %d", transfer->type);
1799 }
1800}
1801
1802static int handle_bulk_completion(struct usbi_transfer *itransfer,
1803 struct usbfs_urb *urb)
1804{
1805 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1806 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1807 struct linux_device_handle_priv *dpriv = __device_handle_priv(transfer->dev_handle);
1808 int urb_idx = urb - tpriv->urbs;
1809
1810 usbi_mutex_lock(&itransfer->lock);
1811 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
1812 urb_idx + 1, tpriv->num_urbs);
1813
1814 tpriv->num_retired++;
1815
1816 if (tpriv->reap_action != NORMAL) {
1817 /* cancelled, submit_fail, or completed early */
1818 usbi_dbg("abnormal reap: urb status %d", urb->status);
1819
1820 /* even though we're in the process of cancelling, it's possible that
1821 * we may receive some data in these URBs that we don't want to lose.
1822 * examples:
1823 * 1. while the kernel is cancelling all the packets that make up an
1824 * URB, a few of them might complete. so we get back a successful
1825 * cancellation *and* some data.
1826 * 2. we receive a short URB which marks the early completion condition,
1827 * so we start cancelling the remaining URBs. however, we're too
1828 * slow and another URB completes (or at least completes partially).
1829 *
1830 * When this happens, our objectives are not to lose any "surplus" data,
1831 * and also to stick it at the end of the previously-received data
1832 * (closing any holes), so that libusb reports the total amount of
1833 * transferred data and presents it in a contiguous chunk.
1834 */
1835 if (urb->actual_length > 0) {
1836 unsigned char *target = transfer->buffer + itransfer->transferred;
1837 usbi_dbg("received %d bytes of surplus data", urb->actual_length);
1838 if (urb->buffer != target) {
1839 usbi_dbg("moving surplus data from offset %d to offset %d",
1840 (unsigned char *) urb->buffer - transfer->buffer,
1841 target - transfer->buffer);
1842 memmove(target, urb->buffer, urb->actual_length);
1843 }
1844 itransfer->transferred += urb->actual_length;
1845 }
1846
1847 if (tpriv->num_retired == tpriv->num_urbs) {
1848 usbi_dbg("abnormal reap: last URB handled, reporting");
1849 if (tpriv->reap_action != COMPLETED_EARLY &&
1850 tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
1851 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
1852 goto completed;
1853 }
1854 goto out_unlock;
1855 }
1856
1857 if (urb->status == 0 || urb->status == -EREMOTEIO ||
1858 (urb->status == -EOVERFLOW && urb->actual_length > 0))
1859 itransfer->transferred += urb->actual_length;
1860
1861
1862 switch (urb->status) {
1863 case 0:
1864 break;
1865 case -EREMOTEIO: /* short transfer */
1866 break;
1867 case -EPIPE:
1868 usbi_dbg("detected endpoint stall");
1869 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
1870 tpriv->reap_status = LIBUSB_TRANSFER_STALL;
1871 goto cancel_remaining;
1872 case -EOVERFLOW:
1873 /* overflow can only ever occur in the last urb */
1874 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
1875 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
1876 tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
1877 goto completed;
1878 case -ETIME:
1879 case -EPROTO:
1880 case -EILSEQ:
1881 /* These can happen on *any* urb of a multi-urb transfer, so
1882 * save a status and tear down rest of the transfer */
1883 usbi_dbg("low level error %d", urb->status);
1884 tpriv->reap_action = ERROR;
1885 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
1886 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
1887 goto cancel_remaining;
1888 default:
1889 usbi_warn(ITRANSFER_CTX(itransfer),
1890 "unrecognised urb status %d", urb->status);
1891 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
1892 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
1893 goto cancel_remaining;
1894 }
1895
1896 /* if we're the last urb or we got less data than requested then we're
1897 * done */
1898 if (urb_idx == tpriv->num_urbs - 1) {
1899 usbi_dbg("last URB in transfer --> complete!");
1900 goto completed;
1901 } else if (urb->actual_length < urb->buffer_length) {
1902 usbi_dbg("short transfer %d/%d --> complete!",
1903 urb->actual_length, urb->buffer_length);
1904 if (tpriv->reap_action == NORMAL)
1905 tpriv->reap_action = COMPLETED_EARLY;
1906 } else
1907 goto out_unlock;
1908
1909cancel_remaining:
1910 if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
1911 goto completed;
1912
1913 /* cancel remaining urbs and wait for their completion before
1914 * reporting results */
1915 while (++urb_idx < tpriv->num_urbs) {
1916 /* remaining URBs with continuation flag are
1917 * automatically cancelled by the kernel */
1918 if (tpriv->urbs[urb_idx].flags & USBFS_URB_BULK_CONTINUATION)
1919 continue;
1920 int tmp = ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, &tpriv->urbs[urb_idx]);
1921 if (tmp && errno != EINVAL)
1922 usbi_warn(TRANSFER_CTX(transfer),
1923 "unrecognised discard errno %d", errno);
1924 }
1925
1926out_unlock:
1927 usbi_mutex_unlock(&itransfer->lock);
1928 return 0;
1929
1930completed:
1931 free(tpriv->urbs);
1932 tpriv->urbs = NULL;
1933 usbi_mutex_unlock(&itransfer->lock);
1934 return CANCELLED == tpriv->reap_action ?
1935 usbi_handle_transfer_cancellation(itransfer) :
1936 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
1937}
1938
1939static int handle_iso_completion(struct usbi_transfer *itransfer,
1940 struct usbfs_urb *urb)
1941{
1942 struct libusb_transfer *transfer =
1943 __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1944 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1945 int num_urbs = tpriv->num_urbs;
1946 int urb_idx = 0;
1947 int i;
1948
1949 usbi_mutex_lock(&itransfer->lock);
1950 for (i = 0; i < num_urbs; i++) {
1951 if (urb == tpriv->iso_urbs[i]) {
1952 urb_idx = i + 1;
1953 break;
1954 }
1955 }
1956 if (urb_idx == 0) {
1957 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
1958 usbi_mutex_unlock(&itransfer->lock);
1959 return LIBUSB_ERROR_NOT_FOUND;
1960 }
1961
1962 usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
1963 urb_idx, num_urbs);
1964
1965 if (urb->status == 0) {
1966 /* copy isochronous results back in */
1967
1968 for (i = 0; i < urb->number_of_packets; i++) {
1969 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
1970 struct libusb_iso_packet_descriptor *lib_desc =
1971 &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
1972 lib_desc->status = urb_desc->status;
1973 lib_desc->actual_length = urb_desc->actual_length;
1974 }
1975 }
1976
1977 tpriv->num_retired++;
1978
1979 if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
1980 usbi_dbg("CANCEL: urb status %d", urb->status);
1981
1982 if (tpriv->num_retired == num_urbs) {
1983 usbi_dbg("CANCEL: last URB handled, reporting");
1984 free_iso_urbs(tpriv);
1985 if (tpriv->reap_action == CANCELLED) {
1986 usbi_mutex_unlock(&itransfer->lock);
1987 return usbi_handle_transfer_cancellation(itransfer);
1988 } else {
1989 usbi_mutex_unlock(&itransfer->lock);
1990 return usbi_handle_transfer_completion(itransfer,
1991 LIBUSB_TRANSFER_ERROR);
1992 }
1993 }
1994 goto out;
1995 }
1996
1997 switch (urb->status) {
1998 case 0:
1999 break;
2000 case -ETIME:
2001 case -EPROTO:
2002 case -EILSEQ:
2003 usbi_dbg("low-level USB error %d", urb->status);
2004 break;
2005 default:
2006 usbi_warn(TRANSFER_CTX(transfer),
2007 "unrecognised urb status %d", urb->status);
2008 break;
2009 }
2010
2011 /* if we're the last urb or we got less data than requested then we're
2012 * done */
2013 if (urb_idx == num_urbs) {
2014 usbi_dbg("last URB in transfer --> complete!");
2015 free_iso_urbs(tpriv);
2016 usbi_mutex_unlock(&itransfer->lock);
2017 return usbi_handle_transfer_completion(itransfer, LIBUSB_TRANSFER_COMPLETED);
2018 }
2019
2020out:
2021 usbi_mutex_unlock(&itransfer->lock);
2022 return 0;
2023}
2024
2025static int handle_control_completion(struct usbi_transfer *itransfer,
2026 struct usbfs_urb *urb)
2027{
2028 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2029 int status;
2030
2031 usbi_mutex_lock(&itransfer->lock);
2032 usbi_dbg("handling completion status %d", urb->status);
2033
2034 if (urb->status == 0)
2035 itransfer->transferred += urb->actual_length;
2036
2037 if (tpriv->reap_action == CANCELLED) {
2038 if (urb->status != 0 && urb->status != -ENOENT)
2039 usbi_warn(ITRANSFER_CTX(itransfer),
2040 "cancel: unrecognised urb status %d", urb->status);
2041 free(tpriv->urbs);
2042 tpriv->urbs = NULL;
2043 usbi_mutex_unlock(&itransfer->lock);
2044 return usbi_handle_transfer_cancellation(itransfer);
2045 }
2046
2047 switch (urb->status) {
2048 case 0:
2049 itransfer->transferred = urb->actual_length;
2050 status = LIBUSB_TRANSFER_COMPLETED;
2051 break;
2052 case -EPIPE:
2053 usbi_dbg("unsupported control request");
2054 status = LIBUSB_TRANSFER_STALL;
2055 break;
2056 case -ETIME:
2057 case -EPROTO:
2058 case -EILSEQ:
2059 usbi_dbg("low-level bus error occurred");
2060 status = LIBUSB_TRANSFER_ERROR;
2061 break;
2062 default:
2063 usbi_warn(ITRANSFER_CTX(itransfer),
2064 "unrecognised urb status %d", urb->status);
2065 status = LIBUSB_TRANSFER_ERROR;
2066 break;
2067 }
2068
2069 free(tpriv->urbs);
2070 tpriv->urbs = NULL;
2071 usbi_mutex_unlock(&itransfer->lock);
2072 return usbi_handle_transfer_completion(itransfer, status);
2073}
2074
2075static int reap_for_handle(struct libusb_device_handle *handle)
2076{
2077 struct linux_device_handle_priv *hpriv = __device_handle_priv(handle);
2078 int r;
2079 struct usbfs_urb *urb;
2080 struct usbi_transfer *itransfer;
2081 struct libusb_transfer *transfer;
2082
2083 r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2084 if (r == -1 && errno == EAGAIN)
2085 return 1;
2086 if (r < 0) {
2087 if (errno == ENODEV)
2088 return LIBUSB_ERROR_NO_DEVICE;
2089
2090 usbi_err(HANDLE_CTX(handle), "reap failed error %d errno=%d",
2091 r, errno);
2092 return LIBUSB_ERROR_IO;
2093 }
2094
2095 itransfer = urb->usercontext;
2096 transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2097
2098 usbi_dbg("urb type=%d status=%d transferred=%d", urb->type, urb->status,
2099 urb->actual_length);
2100
2101 switch (transfer->type) {
2102 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2103 return handle_iso_completion(itransfer, urb);
2104 case LIBUSB_TRANSFER_TYPE_BULK:
2105 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2106 return handle_bulk_completion(itransfer, urb);
2107 case LIBUSB_TRANSFER_TYPE_CONTROL:
2108 return handle_control_completion(itransfer, urb);
2109 default:
2110 usbi_err(HANDLE_CTX(handle), "unrecognised endpoint type %x",
2111 transfer->type);
2112 return LIBUSB_ERROR_OTHER;
2113 }
2114}
2115
2116static int op_handle_events(struct libusb_context *ctx,
2117 struct pollfd *fds, nfds_t nfds, int num_ready)
2118{
2119 int r;
2120 int i = 0;
2121
2122 usbi_mutex_lock(&ctx->open_devs_lock);
2123 for (i = 0; i < nfds && num_ready > 0; i++) {
2124 struct pollfd *pollfd = &fds[i];
2125 struct libusb_device_handle *handle;
2126 struct linux_device_handle_priv *hpriv = NULL;
2127
2128 if (!pollfd->revents)
2129 continue;
2130
2131 num_ready--;
2132 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
2133 hpriv = __device_handle_priv(handle);
2134 if (hpriv->fd == pollfd->fd)
2135 break;
2136 }
2137
2138 if (pollfd->revents & POLLERR) {
2139 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2140 usbi_handle_disconnect(handle);
2141 continue;
2142 }
2143
2144 r = reap_for_handle(handle);
2145 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2146 continue;
2147 else if (r < 0)
2148 goto out;
2149 }
2150
2151 r = 0;
2152out:
2153 usbi_mutex_unlock(&ctx->open_devs_lock);
2154 return r;
2155}
2156
2157static int op_clock_gettime(int clk_id, struct timespec *tp)
2158{
2159 switch (clk_id) {
2160 case USBI_CLOCK_MONOTONIC:
2161 return clock_gettime(monotonic_clkid, tp);
2162 case USBI_CLOCK_REALTIME:
2163 return clock_gettime(CLOCK_REALTIME, tp);
2164 default:
2165 return LIBUSB_ERROR_INVALID_PARAM;
2166 }
2167}
2168
2169#ifdef USBI_TIMERFD_AVAILABLE
2170static clockid_t op_get_timerfd_clockid(void)
2171{
2172 return monotonic_clkid;
2173
2174}
2175#endif
2176
2177const struct usbi_os_backend linux_usbfs_backend = {
2178 .name = "Linux usbfs",
2179 .init = op_init,
2180 .exit = NULL,
2181 .get_device_list = op_get_device_list,
2182 .get_device_descriptor = op_get_device_descriptor,
2183 .get_active_config_descriptor = op_get_active_config_descriptor,
2184 .get_config_descriptor = op_get_config_descriptor,
2185
2186 .open = op_open,
2187 .close = op_close,
2188 .get_configuration = op_get_configuration,
2189 .set_configuration = op_set_configuration,
2190 .claim_interface = op_claim_interface,
2191 .release_interface = op_release_interface,
2192
2193 .set_interface_altsetting = op_set_interface,
2194 .clear_halt = op_clear_halt,
2195 .reset_device = op_reset_device,
2196
2197 .kernel_driver_active = op_kernel_driver_active,
2198 .detach_kernel_driver = op_detach_kernel_driver,
2199 .attach_kernel_driver = op_attach_kernel_driver,
2200
2201 .destroy_device = op_destroy_device,
2202
2203 .submit_transfer = op_submit_transfer,
2204 .cancel_transfer = op_cancel_transfer,
2205 .clear_transfer_priv = op_clear_transfer_priv,
2206
2207 .handle_events = op_handle_events,
2208
2209 .clock_gettime = op_clock_gettime,
2210
2211#ifdef USBI_TIMERFD_AVAILABLE
2212 .get_timerfd_clockid = op_get_timerfd_clockid,
2213#endif
2214
2215 .device_priv_size = sizeof(struct linux_device_priv),
2216 .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2217 .transfer_priv_size = sizeof(struct linux_transfer_priv),
2218 .add_iso_packet_size = 0,
2219};
2220