summaryrefslogtreecommitdiffstats
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
parentafb8735176869db20219c35a341e89158651bffe (diff)
downloadlibirecovery-07391edbf2ca1feaf4357259fd9e477ec53e6d81.tar.gz
libirecovery-07391edbf2ca1feaf4357259fd9e477ec53e6d81.tar.bz2
Remove obsolete "in-tree" copy of libusb-1.0
-rw-r--r--include/libusb-1.0/config.h105
-rw-r--r--include/libusb-1.0/libusb.h1322
-rw-r--r--include/libusb-1.0/libusbi.h872
-rw-r--r--include/libusb-1.0/os/config.h105
-rw-r--r--include/libusb-1.0/os/darwin_usb.c1545
-rw-r--r--include/libusb-1.0/os/darwin_usb.h167
-rw-r--r--include/libusb-1.0/os/libusb.h1322
-rw-r--r--include/libusb-1.0/os/libusbi.h872
-rw-r--r--include/libusb-1.0/os/linux_usbfs.c2220
-rw-r--r--include/libusb-1.0/os/linux_usbfs.h138
-rw-r--r--include/libusb-1.0/os/poll_posix.h12
-rw-r--r--include/libusb-1.0/os/poll_windows.c860
-rw-r--r--include/libusb-1.0/os/poll_windows.h120
-rw-r--r--include/libusb-1.0/os/threads_posix.h46
-rw-r--r--include/libusb-1.0/os/threads_windows.c208
-rw-r--r--include/libusb-1.0/os/threads_windows.h84
-rw-r--r--include/libusb-1.0/os/windows_usb.c4185
-rw-r--r--include/libusb-1.0/os/windows_usb.h784
18 files changed, 0 insertions, 14967 deletions
diff --git a/include/libusb-1.0/config.h b/include/libusb-1.0/config.h
deleted file mode 100644
index 643d4af..0000000
--- a/include/libusb-1.0/config.h
+++ /dev/null
@@ -1,105 +0,0 @@
1/* config.h. Generated from config.h.in by configure. */
2/* config.h.in. Generated from configure.ac by autoheader. */
3
4/* Default visibility */
5#define DEFAULT_VISIBILITY __attribute__((visibility("default")))
6
7/* Debug message logging */
8/* #undef ENABLE_DEBUG_LOGGING */
9
10/* Message logging */
11#define ENABLE_LOGGING 1
12
13/* Define to 1 if you have the <dlfcn.h> header file. */
14#define HAVE_DLFCN_H 1
15
16/* Define to 1 if you have the <inttypes.h> header file. */
17#define HAVE_INTTYPES_H 1
18
19/* Define to 1 if you have the <memory.h> header file. */
20#define HAVE_MEMORY_H 1
21
22/* Define to 1 if you have the <stdint.h> header file. */
23#define HAVE_STDINT_H 1
24
25/* Define to 1 if you have the <stdlib.h> header file. */
26#define HAVE_STDLIB_H 1
27
28/* Define to 1 if you have the <strings.h> header file. */
29#define HAVE_STRINGS_H 1
30
31/* Define to 1 if you have the <string.h> header file. */
32#define HAVE_STRING_H 1
33
34/* Define to 1 if the system has the type `struct timespec'. */
35#define HAVE_STRUCT_TIMESPEC 1
36
37/* Define to 1 if you have the <sys/stat.h> header file. */
38#define HAVE_SYS_STAT_H 1
39
40/* Define to 1 if you have the <sys/time.h> header file. */
41#define HAVE_SYS_TIME_H 1
42
43/* Define to 1 if you have the <sys/types.h> header file. */
44#define HAVE_SYS_TYPES_H 1
45
46/* Define to 1 if you have the <unistd.h> header file. */
47#define HAVE_UNISTD_H 1
48
49/* Define to the sub-directory in which libtool stores uninstalled libraries.
50 */
51#define LT_OBJDIR ".libs/"
52
53/* Define to 1 if your C compiler doesn't accept -c and -o together. */
54/* #undef NO_MINUS_C_MINUS_O */
55
56/* Darwin backend */
57#define OS_DARWIN
58
59/* Linux backend */
60/* #undef OS_LINUX */
61
62/* Windows backend */
63/* #undef OS_WINDOWS */
64
65/* Name of package */
66#define PACKAGE "libusb"
67
68/* Define to the address where bug reports for this package should be sent. */
69#define PACKAGE_BUGREPORT "libusb-devel@lists.sourceforge.net"
70
71/* Define to the full name of this package. */
72#define PACKAGE_NAME "libusb"
73
74/* Define to the full name and version of this package. */
75#define PACKAGE_STRING "libusb 1.0.8"
76
77/* Define to the one symbol short name of this package. */
78#define PACKAGE_TARNAME "libusb"
79
80/* Define to the version of this package. */
81#define PACKAGE_VERSION "1.0.8"
82
83/* Define to 1 if you have the ANSI C header files. */
84#define STDC_HEADERS 1
85
86/* Use Posix Threads */
87#define THREADS_POSIX
88
89/* Backend handles timeout */
90#define USBI_OS_HANDLES_TIMEOUT
91
92/* timerfd headers available */
93/* #undef USBI_TIMERFD_AVAILABLE */
94
95/* Version number of package */
96#define VERSION "1.0.8"
97
98/* Use GNU extensions */
99#define _GNU_SOURCE
100
101/* Define to `__inline__' or `__inline' if that's what the C compiler
102 calls it, or to nothing if 'inline' is not supported under any name. */
103#ifndef __cplusplus
104/* #undef inline */
105#endif
diff --git a/include/libusb-1.0/libusb.h b/include/libusb-1.0/libusb.h
deleted file mode 100644
index 8dc3362..0000000
--- a/include/libusb-1.0/libusb.h
+++ /dev/null
@@ -1,1322 +0,0 @@
1/*
2 * Public libusb header file
3 * Copyright (C) 2007-2008 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#ifndef __LIBUSB_H__
22#define __LIBUSB_H__
23
24/* MSVC doesn't like inline, but does accept __inline ?? */
25#ifdef _MSC_VER
26#define inline __inline
27#endif
28
29#include <stdint.h>
30#include <sys/types.h>
31#include <time.h>
32#include <limits.h>
33
34#if defined(__linux) || defined(__APPLE__) || defined(__CYGWIN__)
35#include <sys/time.h>
36#endif
37
38/* 'interface' might be defined as a macro on Windows, so we need to
39 * undefine it so as not to break the current libusb API, because
40 * libusb_config_descriptor has an 'interface' member
41 * As this can be problematic if you include windows.h after libusb.h
42 * in your sources, we force windows.h to be included first. */
43#if defined(_WIN32) || defined(__CYGWIN__)
44#include <windows.h>
45#if defined(interface)
46#undef interface
47#endif
48#endif
49
50/** \def LIBUSB_CALL
51 * \ingroup misc
52 * libusb's Windows calling convention.
53 *
54 * Under Windows, the selection of available compilers and configurations
55 * means that, unlike other platforms, there is not <em>one true calling
56 * convention</em> (calling convention: the manner in which parameters are
57 * passed to funcions in the generated assembly code).
58 *
59 * Matching the Windows API itself, libusb uses the WINAPI convention (which
60 * translates to the <tt>stdcall</tt> convention) and guarantees that the
61 * library is compiled in this way. The public header file also includes
62 * appropriate annotations so that your own software will use the right
63 * convention, even if another convention is being used by default within
64 * your codebase.
65 *
66 * The one consideration that you must apply in your software is to mark
67 * all functions which you use as libusb callbacks with this LIBUSB_CALL
68 * annotation, so that they too get compiled for the correct calling
69 * convention.
70 *
71 * On non-Windows operating systems, this macro is defined as nothing. This
72 * means that you can apply it to your code without worrying about
73 * cross-platform compatibility.
74 */
75/* LIBUSB_CALL must be defined on both definition and declaration of libusb
76 * functions. You'd think that declaration would be enough, but cygwin will
77 * complain about conflicting types unless both are marked this way.
78 * The placement of this macro is important too; it must appear after the
79 * return type, before the function name. See internal documentation for
80 * API_EXPORTED.
81 */
82#if defined(_WIN32) || defined(__CYGWIN__)
83#define LIBUSB_CALL WINAPI
84#else
85#define LIBUSB_CALL
86#endif
87
88#ifdef __cplusplus
89extern "C" {
90#endif
91
92/** \def libusb_cpu_to_le16
93 * \ingroup misc
94 * Convert a 16-bit value from host-endian to little-endian format. On
95 * little endian systems, this function does nothing. On big endian systems,
96 * the bytes are swapped.
97 * \param x the host-endian value to convert
98 * \returns the value in little-endian byte order
99 */
100static inline uint16_t libusb_cpu_to_le16(const uint16_t x)
101{
102 union {
103 uint8_t b8[2];
104 uint16_t b16;
105 } _tmp;
106 _tmp.b8[1] = x >> 8;
107 _tmp.b8[0] = x & 0xff;
108 return _tmp.b16;
109}
110
111/** \def libusb_le16_to_cpu
112 * \ingroup misc
113 * Convert a 16-bit value from little-endian to host-endian format. On
114 * little endian systems, this function does nothing. On big endian systems,
115 * the bytes are swapped.
116 * \param x the little-endian value to convert
117 * \returns the value in host-endian byte order
118 */
119#define libusb_le16_to_cpu libusb_cpu_to_le16
120
121/* standard USB stuff */
122
123/** \ingroup desc
124 * Device and/or Interface Class codes */
125enum libusb_class_code {
126 /** In the context of a \ref libusb_device_descriptor "device descriptor",
127 * this bDeviceClass value indicates that each interface specifies its
128 * own class information and all interfaces operate independently.
129 */
130 LIBUSB_CLASS_PER_INTERFACE = 0,
131
132 /** Audio class */
133 LIBUSB_CLASS_AUDIO = 1,
134
135 /** Communications class */
136 LIBUSB_CLASS_COMM = 2,
137
138 /** Human Interface Device class */
139 LIBUSB_CLASS_HID = 3,
140
141 /** Printer dclass */
142 LIBUSB_CLASS_PRINTER = 7,
143
144 /** Picture transfer protocol class */
145 LIBUSB_CLASS_PTP = 6,
146
147 /** Mass storage class */
148 LIBUSB_CLASS_MASS_STORAGE = 8,
149
150 /** Hub class */
151 LIBUSB_CLASS_HUB = 9,
152
153 /** Data class */
154 LIBUSB_CLASS_DATA = 10,
155
156 /** Wireless class */
157 LIBUSB_CLASS_WIRELESS = 0xe0,
158
159 /** Application class */
160 LIBUSB_CLASS_APPLICATION = 0xfe,
161
162 /** Class is vendor-specific */
163 LIBUSB_CLASS_VENDOR_SPEC = 0xff
164};
165
166/** \ingroup desc
167 * Descriptor types as defined by the USB specification. */
168enum libusb_descriptor_type {
169 /** Device descriptor. See libusb_device_descriptor. */
170 LIBUSB_DT_DEVICE = 0x01,
171
172 /** Configuration descriptor. See libusb_config_descriptor. */
173 LIBUSB_DT_CONFIG = 0x02,
174
175 /** String descriptor */
176 LIBUSB_DT_STRING = 0x03,
177
178 /** Interface descriptor. See libusb_interface_descriptor. */
179 LIBUSB_DT_INTERFACE = 0x04,
180
181 /** Endpoint descriptor. See libusb_endpoint_descriptor. */
182 LIBUSB_DT_ENDPOINT = 0x05,
183
184 /** HID descriptor */
185 LIBUSB_DT_HID = 0x21,
186
187 /** HID report descriptor */
188 LIBUSB_DT_REPORT = 0x22,
189
190 /** Physical descriptor */
191 LIBUSB_DT_PHYSICAL = 0x23,
192
193 /** Hub descriptor */
194 LIBUSB_DT_HUB = 0x29
195};
196
197/* Descriptor sizes per descriptor type */
198#define LIBUSB_DT_DEVICE_SIZE 18
199#define LIBUSB_DT_CONFIG_SIZE 9
200#define LIBUSB_DT_INTERFACE_SIZE 9
201#define LIBUSB_DT_ENDPOINT_SIZE 7
202#define LIBUSB_DT_ENDPOINT_AUDIO_SIZE 9 /* Audio extension */
203#define LIBUSB_DT_HUB_NONVAR_SIZE 7
204
205#define LIBUSB_ENDPOINT_ADDRESS_MASK 0x0f /* in bEndpointAddress */
206#define LIBUSB_ENDPOINT_DIR_MASK 0x80
207
208/** \ingroup desc
209 * Endpoint direction. Values for bit 7 of the
210 * \ref libusb_endpoint_descriptor::bEndpointAddress "endpoint address" scheme.
211 */
212enum libusb_endpoint_direction {
213 /** In: device-to-host */
214 LIBUSB_ENDPOINT_IN = 0x80,
215
216 /** Out: host-to-device */
217 LIBUSB_ENDPOINT_OUT = 0x00
218};
219
220#define LIBUSB_TRANSFER_TYPE_MASK 0x03 /* in bmAttributes */
221
222/** \ingroup desc
223 * Endpoint transfer type. Values for bits 0:1 of the
224 * \ref libusb_endpoint_descriptor::bmAttributes "endpoint attributes" field.
225 */
226enum libusb_transfer_type {
227 /** Control endpoint */
228 LIBUSB_TRANSFER_TYPE_CONTROL = 0,
229
230 /** Isochronous endpoint */
231 LIBUSB_TRANSFER_TYPE_ISOCHRONOUS = 1,
232
233 /** Bulk endpoint */
234 LIBUSB_TRANSFER_TYPE_BULK = 2,
235
236 /** Interrupt endpoint */
237 LIBUSB_TRANSFER_TYPE_INTERRUPT = 3
238};
239
240/** \ingroup misc
241 * Standard requests, as defined in table 9-3 of the USB2 specifications */
242enum libusb_standard_request {
243 /** Request status of the specific recipient */
244 LIBUSB_REQUEST_GET_STATUS = 0x00,
245
246 /** Clear or disable a specific feature */
247 LIBUSB_REQUEST_CLEAR_FEATURE = 0x01,
248
249 /* 0x02 is reserved */
250
251 /** Set or enable a specific feature */
252 LIBUSB_REQUEST_SET_FEATURE = 0x03,
253
254 /* 0x04 is reserved */
255
256 /** Set device address for all future accesses */
257 LIBUSB_REQUEST_SET_ADDRESS = 0x05,
258
259 /** Get the specified descriptor */
260 LIBUSB_REQUEST_GET_DESCRIPTOR = 0x06,
261
262 /** Used to update existing descriptors or add new descriptors */
263 LIBUSB_REQUEST_SET_DESCRIPTOR = 0x07,
264
265 /** Get the current device configuration value */
266 LIBUSB_REQUEST_GET_CONFIGURATION = 0x08,
267
268 /** Set device configuration */
269 LIBUSB_REQUEST_SET_CONFIGURATION = 0x09,
270
271 /** Return the selected alternate setting for the specified interface */
272 LIBUSB_REQUEST_GET_INTERFACE = 0x0A,
273
274 /** Select an alternate interface for the specified interface */
275 LIBUSB_REQUEST_SET_INTERFACE = 0x0B,
276
277 /** Set then report an endpoint's synchronization frame */
278 LIBUSB_REQUEST_SYNCH_FRAME = 0x0C
279};
280
281/** \ingroup misc
282 * Request type bits of the
283 * \ref libusb_control_setup::bmRequestType "bmRequestType" field in control
284 * transfers. */
285enum libusb_request_type {
286 /** Standard */
287 LIBUSB_REQUEST_TYPE_STANDARD = (0x00 << 5),
288
289 /** Class */
290 LIBUSB_REQUEST_TYPE_CLASS = (0x01 << 5),
291
292 /** Vendor */
293 LIBUSB_REQUEST_TYPE_VENDOR = (0x02 << 5),
294
295 /** Reserved */
296 LIBUSB_REQUEST_TYPE_RESERVED = (0x03 << 5)
297};
298
299/** \ingroup misc
300 * Recipient bits of the
301 * \ref libusb_control_setup::bmRequestType "bmRequestType" field in control
302 * transfers. Values 4 through 31 are reserved. */
303enum libusb_request_recipient {
304 /** Device */
305 LIBUSB_RECIPIENT_DEVICE = 0x00,
306
307 /** Interface */
308 LIBUSB_RECIPIENT_INTERFACE = 0x01,
309
310 /** Endpoint */
311 LIBUSB_RECIPIENT_ENDPOINT = 0x02,
312
313 /** Other */
314 LIBUSB_RECIPIENT_OTHER = 0x03
315};
316
317#define LIBUSB_ISO_SYNC_TYPE_MASK 0x0C
318
319/** \ingroup desc
320 * Synchronization type for isochronous endpoints. Values for bits 2:3 of the
321 * \ref libusb_endpoint_descriptor::bmAttributes "bmAttributes" field in
322 * libusb_endpoint_descriptor.
323 */
324enum libusb_iso_sync_type {
325 /** No synchronization */
326 LIBUSB_ISO_SYNC_TYPE_NONE = 0,
327
328 /** Asynchronous */
329 LIBUSB_ISO_SYNC_TYPE_ASYNC = 1,
330
331 /** Adaptive */
332 LIBUSB_ISO_SYNC_TYPE_ADAPTIVE = 2,
333
334 /** Synchronous */
335 LIBUSB_ISO_SYNC_TYPE_SYNC = 3
336};
337
338#define LIBUSB_ISO_USAGE_TYPE_MASK 0x30
339
340/** \ingroup desc
341 * Usage type for isochronous endpoints. Values for bits 4:5 of the
342 * \ref libusb_endpoint_descriptor::bmAttributes "bmAttributes" field in
343 * libusb_endpoint_descriptor.
344 */
345enum libusb_iso_usage_type {
346 /** Data endpoint */
347 LIBUSB_ISO_USAGE_TYPE_DATA = 0,
348
349 /** Feedback endpoint */
350 LIBUSB_ISO_USAGE_TYPE_FEEDBACK = 1,
351
352 /** Implicit feedback Data endpoint */
353 LIBUSB_ISO_USAGE_TYPE_IMPLICIT = 2
354};
355
356/** \ingroup desc
357 * A structure representing the standard USB device descriptor. This
358 * descriptor is documented in section 9.6.1 of the USB 2.0 specification.
359 * All multiple-byte fields are represented in host-endian format.
360 */
361struct libusb_device_descriptor {
362 /** Size of this descriptor (in bytes) */
363 uint8_t bLength;
364
365 /** Descriptor type. Will have value
366 * \ref libusb_descriptor_type::LIBUSB_DT_DEVICE LIBUSB_DT_DEVICE in this
367 * context. */
368 uint8_t bDescriptorType;
369
370 /** USB specification release number in binary-coded decimal. A value of
371 * 0x0200 indicates USB 2.0, 0x0110 indicates USB 1.1, etc. */
372 uint16_t bcdUSB;
373
374 /** USB-IF class code for the device. See \ref libusb_class_code. */
375 uint8_t bDeviceClass;
376
377 /** USB-IF subclass code for the device, qualified by the bDeviceClass
378 * value */
379 uint8_t bDeviceSubClass;
380
381 /** USB-IF protocol code for the device, qualified by the bDeviceClass and
382 * bDeviceSubClass values */
383 uint8_t bDeviceProtocol;
384
385 /** Maximum packet size for endpoint 0 */
386 uint8_t bMaxPacketSize0;
387
388 /** USB-IF vendor ID */
389 uint16_t idVendor;
390
391 /** USB-IF product ID */
392 uint16_t idProduct;
393
394 /** Device release number in binary-coded decimal */
395 uint16_t bcdDevice;
396
397 /** Index of string descriptor describing manufacturer */
398 uint8_t iManufacturer;
399
400 /** Index of string descriptor describing product */
401 uint8_t iProduct;
402
403 /** Index of string descriptor containing device serial number */
404 uint8_t iSerialNumber;
405
406 /** Number of possible configurations */
407 uint8_t bNumConfigurations;
408};
409
410/** \ingroup desc
411 * A structure representing the standard USB endpoint descriptor. This
412 * descriptor is documented in section 9.6.3 of the USB 2.0 specification.
413 * All multiple-byte fields are represented in host-endian format.
414 */
415struct libusb_endpoint_descriptor {
416 /** Size of this descriptor (in bytes) */
417 uint8_t bLength;
418
419 /** Descriptor type. Will have value
420 * \ref libusb_descriptor_type::LIBUSB_DT_ENDPOINT LIBUSB_DT_ENDPOINT in
421 * this context. */
422 uint8_t bDescriptorType;
423
424 /** The address of the endpoint described by this descriptor. Bits 0:3 are
425 * the endpoint number. Bits 4:6 are reserved. Bit 7 indicates direction,
426 * see \ref libusb_endpoint_direction.
427 */
428 uint8_t bEndpointAddress;
429
430 /** Attributes which apply to the endpoint when it is configured using
431 * the bConfigurationValue. Bits 0:1 determine the transfer type and
432 * correspond to \ref libusb_transfer_type. Bits 2:3 are only used for
433 * isochronous endpoints and correspond to \ref libusb_iso_sync_type.
434 * Bits 4:5 are also only used for isochronous endpoints and correspond to
435 * \ref libusb_iso_usage_type. Bits 6:7 are reserved.
436 */
437 uint8_t bmAttributes;
438
439 /** Maximum packet size this endpoint is capable of sending/receiving. */
440 uint16_t wMaxPacketSize;
441
442 /** Interval for polling endpoint for data transfers. */
443 uint8_t bInterval;
444
445 /** For audio devices only: the rate at which synchronization feedback
446 * is provided. */
447 uint8_t bRefresh;
448
449 /** For audio devices only: the address if the synch endpoint */
450 uint8_t bSynchAddress;
451
452 /** Extra descriptors. If libusb encounters unknown endpoint descriptors,
453 * it will store them here, should you wish to parse them. */
454 const unsigned char *extra;
455
456 /** Length of the extra descriptors, in bytes. */
457 int extra_length;
458};
459
460/** \ingroup desc
461 * A structure representing the standard USB interface descriptor. This
462 * descriptor is documented in section 9.6.5 of the USB 2.0 specification.
463 * All multiple-byte fields are represented in host-endian format.
464 */
465struct libusb_interface_descriptor {
466 /** Size of this descriptor (in bytes) */
467 uint8_t bLength;
468
469 /** Descriptor type. Will have value
470 * \ref libusb_descriptor_type::LIBUSB_DT_INTERFACE LIBUSB_DT_INTERFACE
471 * in this context. */
472 uint8_t bDescriptorType;
473
474 /** Number of this interface */
475 uint8_t bInterfaceNumber;
476
477 /** Value used to select this alternate setting for this interface */
478 uint8_t bAlternateSetting;
479
480 /** Number of endpoints used by this interface (excluding the control
481 * endpoint). */
482 uint8_t bNumEndpoints;
483
484 /** USB-IF class code for this interface. See \ref libusb_class_code. */
485 uint8_t bInterfaceClass;
486
487 /** USB-IF subclass code for this interface, qualified by the
488 * bInterfaceClass value */
489 uint8_t bInterfaceSubClass;
490
491 /** USB-IF protocol code for this interface, qualified by the
492 * bInterfaceClass and bInterfaceSubClass values */
493 uint8_t bInterfaceProtocol;
494
495 /** Index of string descriptor describing this interface */
496 uint8_t iInterface;
497
498 /** Array of endpoint descriptors. This length of this array is determined
499 * by the bNumEndpoints field. */
500 const struct libusb_endpoint_descriptor *endpoint;
501
502 /** Extra descriptors. If libusb encounters unknown interface descriptors,
503 * it will store them here, should you wish to parse them. */
504 const unsigned char *extra;
505
506 /** Length of the extra descriptors, in bytes. */
507 int extra_length;
508};
509
510/** \ingroup desc
511 * A collection of alternate settings for a particular USB interface.
512 */
513struct libusb_interface {
514 /** Array of interface descriptors. The length of this array is determined
515 * by the num_altsetting field. */
516 const struct libusb_interface_descriptor *altsetting;
517
518 /** The number of alternate settings that belong to this interface */
519 int num_altsetting;
520};
521
522/** \ingroup desc
523 * A structure representing the standard USB configuration descriptor. This
524 * descriptor is documented in section 9.6.3 of the USB 2.0 specification.
525 * All multiple-byte fields are represented in host-endian format.
526 */
527struct libusb_config_descriptor {
528 /** Size of this descriptor (in bytes) */
529 uint8_t bLength;
530
531 /** Descriptor type. Will have value
532 * \ref libusb_descriptor_type::LIBUSB_DT_CONFIG LIBUSB_DT_CONFIG
533 * in this context. */
534 uint8_t bDescriptorType;
535
536 /** Total length of data returned for this configuration */
537 uint16_t wTotalLength;
538
539 /** Number of interfaces supported by this configuration */
540 uint8_t bNumInterfaces;
541
542 /** Identifier value for this configuration */
543 uint8_t bConfigurationValue;
544
545 /** Index of string descriptor describing this configuration */
546 uint8_t iConfiguration;
547
548 /** Configuration characteristics */
549 uint8_t bmAttributes;
550
551 /** Maximum power consumption of the USB device from this bus in this
552 * configuration when the device is fully opreation. Expressed in units
553 * of 2 mA. */
554 uint8_t MaxPower;
555
556 /** Array of interfaces supported by this configuration. The length of
557 * this array is determined by the bNumInterfaces field. */
558 const struct libusb_interface *interface;
559
560 /** Extra descriptors. If libusb encounters unknown configuration
561 * descriptors, it will store them here, should you wish to parse them. */
562 const unsigned char *extra;
563
564 /** Length of the extra descriptors, in bytes. */
565 int extra_length;
566};
567
568/** \ingroup asyncio
569 * Setup packet for control transfers. */
570struct libusb_control_setup {
571 /** Request type. Bits 0:4 determine recipient, see
572 * \ref libusb_request_recipient. Bits 5:6 determine type, see
573 * \ref libusb_request_type. Bit 7 determines data transfer direction, see
574 * \ref libusb_endpoint_direction.
575 */
576 uint8_t bmRequestType;
577
578 /** Request. If the type bits of bmRequestType are equal to
579 * \ref libusb_request_type::LIBUSB_REQUEST_TYPE_STANDARD
580 * "LIBUSB_REQUEST_TYPE_STANDARD" then this field refers to
581 * \ref libusb_standard_request. For other cases, use of this field is
582 * application-specific. */
583 uint8_t bRequest;
584
585 /** Value. Varies according to request */
586 uint16_t wValue;
587
588 /** Index. Varies according to request, typically used to pass an index
589 * or offset */
590 uint16_t wIndex;
591
592 /** Number of bytes to transfer */
593 uint16_t wLength;
594};
595
596#define LIBUSB_CONTROL_SETUP_SIZE (sizeof(struct libusb_control_setup))
597
598/* libusb */
599
600struct libusb_context;
601struct libusb_device;
602struct libusb_device_handle;
603
604/** \ingroup lib
605 * Structure representing a libusb session. The concept of individual libusb
606 * sessions allows for your program to use two libraries (or dynamically
607 * load two modules) which both independently use libusb. This will prevent
608 * interference between the individual libusb users - for example
609 * libusb_set_debug() will not affect the other user of the library, and
610 * libusb_exit() will not destroy resources that the other user is still
611 * using.
612 *
613 * Sessions are created by libusb_init() and destroyed through libusb_exit().
614 * If your application is guaranteed to only ever include a single libusb
615 * user (i.e. you), you do not have to worry about contexts: pass NULL in
616 * every function call where a context is required. The default context
617 * will be used.
618 *
619 * For more information, see \ref contexts.
620 */
621typedef struct libusb_context libusb_context;
622
623/** \ingroup dev
624 * Structure representing a USB device detected on the system. This is an
625 * opaque type for which you are only ever provided with a pointer, usually
626 * originating from libusb_get_device_list().
627 *
628 * Certain operations can be performed on a device, but in order to do any
629 * I/O you will have to first obtain a device handle using libusb_open().
630 *
631 * Devices are reference counted with libusb_device_ref() and
632 * libusb_device_unref(), and are freed when the reference count reaches 0.
633 * New devices presented by libusb_get_device_list() have a reference count of
634 * 1, and libusb_free_device_list() can optionally decrease the reference count
635 * on all devices in the list. libusb_open() adds another reference which is
636 * later destroyed by libusb_close().
637 */
638typedef struct libusb_device libusb_device;
639
640
641/** \ingroup dev
642 * Structure representing a handle on a USB device. This is an opaque type for
643 * which you are only ever provided with a pointer, usually originating from
644 * libusb_open().
645 *
646 * A device handle is used to perform I/O and other operations. When finished
647 * with a device handle, you should call libusb_close().
648 */
649typedef struct libusb_device_handle libusb_device_handle;
650
651/** \ingroup misc
652 * Error codes. Most libusb functions return 0 on success or one of these
653 * codes on failure.
654 * You can use libusb_strerror() to retrieve a short string description of
655 * a libusb_error enumeration value.
656 */
657enum libusb_error {
658 /** Success (no error) */
659 LIBUSB_SUCCESS = 0,
660
661 /** Input/output error */
662 LIBUSB_ERROR_IO = -1,
663
664 /** Invalid parameter */
665 LIBUSB_ERROR_INVALID_PARAM = -2,
666
667 /** Access denied (insufficient permissions) */
668 LIBUSB_ERROR_ACCESS = -3,
669
670 /** No such device (it may have been disconnected) */
671 LIBUSB_ERROR_NO_DEVICE = -4,
672
673 /** Entity not found */
674 LIBUSB_ERROR_NOT_FOUND = -5,
675
676 /** Resource busy */
677 LIBUSB_ERROR_BUSY = -6,
678
679 /** Operation timed out */
680 LIBUSB_ERROR_TIMEOUT = -7,
681
682 /** Overflow */
683 LIBUSB_ERROR_OVERFLOW = -8,
684
685 /** Pipe error */
686 LIBUSB_ERROR_PIPE = -9,
687
688 /** System call interrupted (perhaps due to signal) */
689 LIBUSB_ERROR_INTERRUPTED = -10,
690
691 /** Insufficient memory */
692 LIBUSB_ERROR_NO_MEM = -11,
693
694 /** Operation not supported or unimplemented on this platform */
695 LIBUSB_ERROR_NOT_SUPPORTED = -12,
696
697 /** Other error */
698 LIBUSB_ERROR_OTHER = -99
699
700 /* IMPORTANT: when adding new values to this enum, remember to
701 update the libusb_strerror() function implementation! */
702};
703
704/** \ingroup asyncio
705 * Transfer status codes */
706enum libusb_transfer_status {
707 /** Transfer completed without error. Note that this does not indicate
708 * that the entire amount of requested data was transferred. */
709 LIBUSB_TRANSFER_COMPLETED,
710
711 /** Transfer failed */
712 LIBUSB_TRANSFER_ERROR,
713
714 /** Transfer timed out */
715 LIBUSB_TRANSFER_TIMED_OUT,
716
717 /** Transfer was cancelled */
718 LIBUSB_TRANSFER_CANCELLED,
719
720 /** For bulk/interrupt endpoints: halt condition detected (endpoint
721 * stalled). For control endpoints: control request not supported. */
722 LIBUSB_TRANSFER_STALL,
723
724 /** Device was disconnected */
725 LIBUSB_TRANSFER_NO_DEVICE,
726
727 /** Device sent more data than requested */
728 LIBUSB_TRANSFER_OVERFLOW
729};
730
731/** \ingroup asyncio
732 * libusb_transfer.flags values */
733enum libusb_transfer_flags {
734 /** Report short frames as errors */
735 LIBUSB_TRANSFER_SHORT_NOT_OK = 1<<0,
736
737 /** Automatically free() transfer buffer during libusb_free_transfer() */
738 LIBUSB_TRANSFER_FREE_BUFFER = 1<<1,
739
740 /** Automatically call libusb_free_transfer() after callback returns.
741 * If this flag is set, it is illegal to call libusb_free_transfer()
742 * from your transfer callback, as this will result in a double-free
743 * when this flag is acted upon. */
744 LIBUSB_TRANSFER_FREE_TRANSFER = 1<<2
745};
746
747/** \ingroup asyncio
748 * Isochronous packet descriptor. */
749struct libusb_iso_packet_descriptor {
750 /** Length of data to request in this packet */
751 unsigned int length;
752
753 /** Amount of data that was actually transferred */
754 unsigned int actual_length;
755
756 /** Status code for this packet */
757 enum libusb_transfer_status status;
758};
759
760struct libusb_transfer;
761
762/** \ingroup asyncio
763 * Asynchronous transfer callback function type. When submitting asynchronous
764 * transfers, you pass a pointer to a callback function of this type via the
765 * \ref libusb_transfer::callback "callback" member of the libusb_transfer
766 * structure. libusb will call this function later, when the transfer has
767 * completed or failed. See \ref asyncio for more information.
768 * \param transfer The libusb_transfer struct the callback function is being
769 * notified about.
770 */
771typedef void (LIBUSB_CALL *libusb_transfer_cb_fn)(struct libusb_transfer *transfer);
772
773/** \ingroup asyncio
774 * The generic USB transfer structure. The user populates this structure and
775 * then submits it in order to request a transfer. After the transfer has
776 * completed, the library populates the transfer with the results and passes
777 * it back to the user.
778 */
779struct libusb_transfer {
780 /** Handle of the device that this transfer will be submitted to */
781 libusb_device_handle *dev_handle;
782
783 /** A bitwise OR combination of \ref libusb_transfer_flags. */
784 uint8_t flags;
785
786 /** Address of the endpoint where this transfer will be sent. */
787 unsigned char endpoint;
788
789 /** Type of the endpoint from \ref libusb_transfer_type */
790 unsigned char type;
791
792 /** Timeout for this transfer in millseconds. A value of 0 indicates no
793 * timeout. */
794 unsigned int timeout;
795
796 /** The status of the transfer. Read-only, and only for use within
797 * transfer callback function.
798 *
799 * If this is an isochronous transfer, this field may read COMPLETED even
800 * if there were errors in the frames. Use the
801 * \ref libusb_iso_packet_descriptor::status "status" field in each packet
802 * to determine if errors occurred. */
803 enum libusb_transfer_status status;
804
805 /** Length of the data buffer */
806 int length;
807
808 /** Actual length of data that was transferred. Read-only, and only for
809 * use within transfer callback function. Not valid for isochronous
810 * endpoint transfers. */
811 int actual_length;
812
813 /** Callback function. This will be invoked when the transfer completes,
814 * fails, or is cancelled. */
815 libusb_transfer_cb_fn callback;
816
817 /** User context data to pass to the callback function. */
818 void *user_data;
819
820 /** Data buffer */
821 unsigned char *buffer;
822
823 /** Number of isochronous packets. Only used for I/O with isochronous
824 * endpoints. */
825 int num_iso_packets;
826
827 /** Isochronous packet descriptors, for isochronous transfers only. */
828 struct libusb_iso_packet_descriptor iso_packet_desc
829#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
830 [] /* valid C99 code */
831#else
832 [0] /* non-standard, but usually working code */
833#endif
834 ;
835};
836
837int LIBUSB_CALL libusb_init(libusb_context **ctx);
838void LIBUSB_CALL libusb_exit(libusb_context *ctx);
839void LIBUSB_CALL libusb_set_debug(libusb_context *ctx, int level);
840const char * LIBUSB_CALL libusb_strerror(enum libusb_error errcode);
841
842ssize_t LIBUSB_CALL libusb_get_device_list(libusb_context *ctx,
843 libusb_device ***list);
844void LIBUSB_CALL libusb_free_device_list(libusb_device **list,
845 int unref_devices);
846libusb_device * LIBUSB_CALL libusb_ref_device(libusb_device *dev);
847void LIBUSB_CALL libusb_unref_device(libusb_device *dev);
848
849int LIBUSB_CALL libusb_get_configuration(libusb_device_handle *dev,
850 int *config);
851int LIBUSB_CALL libusb_get_device_descriptor(libusb_device *dev,
852 struct libusb_device_descriptor *desc);
853int LIBUSB_CALL libusb_get_active_config_descriptor(libusb_device *dev,
854 struct libusb_config_descriptor **config);
855int LIBUSB_CALL libusb_get_config_descriptor(libusb_device *dev,
856 uint8_t config_index, struct libusb_config_descriptor **config);
857int LIBUSB_CALL libusb_get_config_descriptor_by_value(libusb_device *dev,
858 uint8_t bConfigurationValue, struct libusb_config_descriptor **config);
859void LIBUSB_CALL libusb_free_config_descriptor(
860 struct libusb_config_descriptor *config);
861uint8_t LIBUSB_CALL libusb_get_bus_number(libusb_device *dev);
862uint8_t LIBUSB_CALL libusb_get_device_address(libusb_device *dev);
863int LIBUSB_CALL libusb_get_max_packet_size(libusb_device *dev,
864 unsigned char endpoint);
865int LIBUSB_CALL libusb_get_max_iso_packet_size(libusb_device *dev,
866 unsigned char endpoint);
867
868int LIBUSB_CALL libusb_open(libusb_device *dev, libusb_device_handle **handle);
869void LIBUSB_CALL libusb_close(libusb_device_handle *dev_handle);
870libusb_device * LIBUSB_CALL libusb_get_device(libusb_device_handle *dev_handle);
871
872int LIBUSB_CALL libusb_set_configuration(libusb_device_handle *dev,
873 int configuration);
874int LIBUSB_CALL libusb_claim_interface(libusb_device_handle *dev,
875 int interface_number);
876int LIBUSB_CALL libusb_release_interface(libusb_device_handle *dev,
877 int interface_number);
878
879libusb_device_handle * LIBUSB_CALL libusb_open_device_with_vid_pid(
880 libusb_context *ctx, uint16_t vendor_id, uint16_t product_id);
881
882int LIBUSB_CALL libusb_set_interface_alt_setting(libusb_device_handle *dev,
883 int interface_number, int alternate_setting);
884int LIBUSB_CALL libusb_clear_halt(libusb_device_handle *dev,
885 unsigned char endpoint);
886int LIBUSB_CALL libusb_reset_device(libusb_device_handle *dev);
887
888int LIBUSB_CALL libusb_kernel_driver_active(libusb_device_handle *dev,
889 int interface_number);
890int LIBUSB_CALL libusb_detach_kernel_driver(libusb_device_handle *dev,
891 int interface_number);
892int LIBUSB_CALL libusb_attach_kernel_driver(libusb_device_handle *dev,
893 int interface_number);
894
895/* async I/O */
896
897/** \ingroup asyncio
898 * Get the data section of a control transfer. This convenience function is here
899 * to remind you that the data does not start until 8 bytes into the actual
900 * buffer, as the setup packet comes first.
901 *
902 * Calling this function only makes sense from a transfer callback function,
903 * or situations where you have already allocated a suitably sized buffer at
904 * transfer->buffer.
905 *
906 * \param transfer a transfer
907 * \returns pointer to the first byte of the data section
908 */
909static inline unsigned char *libusb_control_transfer_get_data(
910 struct libusb_transfer *transfer)
911{
912 return transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
913}
914
915/** \ingroup asyncio
916 * Get the control setup packet of a control transfer. This convenience
917 * function is here to remind you that the control setup occupies the first
918 * 8 bytes of the transfer data buffer.
919 *
920 * Calling this function only makes sense from a transfer callback function,
921 * or situations where you have already allocated a suitably sized buffer at
922 * transfer->buffer.
923 *
924 * \param transfer a transfer
925 * \returns a casted pointer to the start of the transfer data buffer
926 */
927static inline struct libusb_control_setup *libusb_control_transfer_get_setup(
928 struct libusb_transfer *transfer)
929{
930 return (struct libusb_control_setup *) transfer->buffer;
931}
932
933/** \ingroup asyncio
934 * Helper function to populate the setup packet (first 8 bytes of the data
935 * buffer) for a control transfer. The wIndex, wValue and wLength values should
936 * be given in host-endian byte order.
937 *
938 * \param buffer buffer to output the setup packet into
939 * \param bmRequestType see the
940 * \ref libusb_control_setup::bmRequestType "bmRequestType" field of
941 * \ref libusb_control_setup
942 * \param bRequest see the
943 * \ref libusb_control_setup::bRequest "bRequest" field of
944 * \ref libusb_control_setup
945 * \param wValue see the
946 * \ref libusb_control_setup::wValue "wValue" field of
947 * \ref libusb_control_setup
948 * \param wIndex see the
949 * \ref libusb_control_setup::wIndex "wIndex" field of
950 * \ref libusb_control_setup
951 * \param wLength see the
952 * \ref libusb_control_setup::wLength "wLength" field of
953 * \ref libusb_control_setup
954 */
955static inline void libusb_fill_control_setup(unsigned char *buffer,
956 uint8_t bmRequestType, uint8_t bRequest, uint16_t wValue, uint16_t wIndex,
957 uint16_t wLength)
958{
959 struct libusb_control_setup *setup = (struct libusb_control_setup *) buffer;
960 setup->bmRequestType = bmRequestType;
961 setup->bRequest = bRequest;
962 setup->wValue = libusb_cpu_to_le16(wValue);
963 setup->wIndex = libusb_cpu_to_le16(wIndex);
964 setup->wLength = libusb_cpu_to_le16(wLength);
965}
966
967struct libusb_transfer * LIBUSB_CALL libusb_alloc_transfer(int iso_packets);
968int LIBUSB_CALL libusb_submit_transfer(struct libusb_transfer *transfer);
969int LIBUSB_CALL libusb_cancel_transfer(struct libusb_transfer *transfer);
970void LIBUSB_CALL libusb_free_transfer(struct libusb_transfer *transfer);
971
972/** \ingroup asyncio
973 * Helper function to populate the required \ref libusb_transfer fields
974 * for a control transfer.
975 *
976 * If you pass a transfer buffer to this function, the first 8 bytes will
977 * be interpreted as a control setup packet, and the wLength field will be
978 * used to automatically populate the \ref libusb_transfer::length "length"
979 * field of the transfer. Therefore the recommended approach is:
980 * -# Allocate a suitably sized data buffer (including space for control setup)
981 * -# Call libusb_fill_control_setup()
982 * -# If this is a host-to-device transfer with a data stage, put the data
983 * in place after the setup packet
984 * -# Call this function
985 * -# Call libusb_submit_transfer()
986 *
987 * It is also legal to pass a NULL buffer to this function, in which case this
988 * function will not attempt to populate the length field. Remember that you
989 * must then populate the buffer and length fields later.
990 *
991 * \param transfer the transfer to populate
992 * \param dev_handle handle of the device that will handle the transfer
993 * \param buffer data buffer. If provided, this function will interpret the
994 * first 8 bytes as a setup packet and infer the transfer length from that.
995 * \param callback callback function to be invoked on transfer completion
996 * \param user_data user data to pass to callback function
997 * \param timeout timeout for the transfer in milliseconds
998 */
999static inline void libusb_fill_control_transfer(
1000 struct libusb_transfer *transfer, libusb_device_handle *dev_handle,
1001 unsigned char *buffer, libusb_transfer_cb_fn callback, void *user_data,
1002 unsigned int timeout)
1003{
1004 struct libusb_control_setup *setup = (struct libusb_control_setup *) buffer;
1005 transfer->dev_handle = dev_handle;
1006 transfer->endpoint = 0;
1007 transfer->type = LIBUSB_TRANSFER_TYPE_CONTROL;
1008 transfer->timeout = timeout;
1009 transfer->buffer = buffer;
1010 if (setup)
1011 transfer->length = LIBUSB_CONTROL_SETUP_SIZE
1012 + libusb_le16_to_cpu(setup->wLength);
1013 transfer->user_data = user_data;
1014 transfer->callback = callback;
1015}
1016
1017/** \ingroup asyncio
1018 * Helper function to populate the required \ref libusb_transfer fields
1019 * for a bulk transfer.
1020 *
1021 * \param transfer the transfer to populate
1022 * \param dev_handle handle of the device that will handle the transfer
1023 * \param endpoint address of the endpoint where this transfer will be sent
1024 * \param buffer data buffer
1025 * \param length length of data buffer
1026 * \param callback callback function to be invoked on transfer completion
1027 * \param user_data user data to pass to callback function
1028 * \param timeout timeout for the transfer in milliseconds
1029 */
1030static inline void libusb_fill_bulk_transfer(struct libusb_transfer *transfer,
1031 libusb_device_handle *dev_handle, unsigned char endpoint,
1032 unsigned char *buffer, int length, libusb_transfer_cb_fn callback,
1033 void *user_data, unsigned int timeout)
1034{
1035 transfer->dev_handle = dev_handle;
1036 transfer->endpoint = endpoint;
1037 transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
1038 transfer->timeout = timeout;
1039 transfer->buffer = buffer;
1040 transfer->length = length;
1041 transfer->user_data = user_data;
1042 transfer->callback = callback;
1043}
1044
1045/** \ingroup asyncio
1046 * Helper function to populate the required \ref libusb_transfer fields
1047 * for an interrupt transfer.
1048 *
1049 * \param transfer the transfer to populate
1050 * \param dev_handle handle of the device that will handle the transfer
1051 * \param endpoint address of the endpoint where this transfer will be sent
1052 * \param buffer data buffer
1053 * \param length length of data buffer
1054 * \param callback callback function to be invoked on transfer completion
1055 * \param user_data user data to pass to callback function
1056 * \param timeout timeout for the transfer in milliseconds
1057 */
1058static inline void libusb_fill_interrupt_transfer(
1059 struct libusb_transfer *transfer, libusb_device_handle *dev_handle,
1060 unsigned char endpoint, unsigned char *buffer, int length,
1061 libusb_transfer_cb_fn callback, void *user_data, unsigned int timeout)
1062{
1063 transfer->dev_handle = dev_handle;
1064 transfer->endpoint = endpoint;
1065 transfer->type = LIBUSB_TRANSFER_TYPE_INTERRUPT;
1066 transfer->timeout = timeout;
1067 transfer->buffer = buffer;
1068 transfer->length = length;
1069 transfer->user_data = user_data;
1070 transfer->callback = callback;
1071}
1072
1073/** \ingroup asyncio
1074 * Helper function to populate the required \ref libusb_transfer fields
1075 * for an isochronous transfer.
1076 *
1077 * \param transfer the transfer to populate
1078 * \param dev_handle handle of the device that will handle the transfer
1079 * \param endpoint address of the endpoint where this transfer will be sent
1080 * \param buffer data buffer
1081 * \param length length of data buffer
1082 * \param num_iso_packets the number of isochronous packets
1083 * \param callback callback function to be invoked on transfer completion
1084 * \param user_data user data to pass to callback function
1085 * \param timeout timeout for the transfer in milliseconds
1086 */
1087static inline void libusb_fill_iso_transfer(struct libusb_transfer *transfer,
1088 libusb_device_handle *dev_handle, unsigned char endpoint,
1089 unsigned char *buffer, int length, int num_iso_packets,
1090 libusb_transfer_cb_fn callback, void *user_data, unsigned int timeout)
1091{
1092 transfer->dev_handle = dev_handle;
1093 transfer->endpoint = endpoint;
1094 transfer->type = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS;
1095 transfer->timeout = timeout;
1096 transfer->buffer = buffer;
1097 transfer->length = length;
1098 transfer->num_iso_packets = num_iso_packets;
1099 transfer->user_data = user_data;
1100 transfer->callback = callback;
1101}
1102
1103/** \ingroup asyncio
1104 * Convenience function to set the length of all packets in an isochronous
1105 * transfer, based on the num_iso_packets field in the transfer structure.
1106 *
1107 * \param transfer a transfer
1108 * \param length the length to set in each isochronous packet descriptor
1109 * \see libusb_get_max_packet_size()
1110 */
1111static inline void libusb_set_iso_packet_lengths(
1112 struct libusb_transfer *transfer, unsigned int length)
1113{
1114 int i;
1115 for (i = 0; i < transfer->num_iso_packets; i++)
1116 transfer->iso_packet_desc[i].length = length;
1117}
1118
1119/** \ingroup asyncio
1120 * Convenience function to locate the position of an isochronous packet
1121 * within the buffer of an isochronous transfer.
1122 *
1123 * This is a thorough function which loops through all preceding packets,
1124 * accumulating their lengths to find the position of the specified packet.
1125 * Typically you will assign equal lengths to each packet in the transfer,
1126 * and hence the above method is sub-optimal. You may wish to use
1127 * libusb_get_iso_packet_buffer_simple() instead.
1128 *
1129 * \param transfer a transfer
1130 * \param packet the packet to return the address of
1131 * \returns the base address of the packet buffer inside the transfer buffer,
1132 * or NULL if the packet does not exist.
1133 * \see libusb_get_iso_packet_buffer_simple()
1134 */
1135static inline unsigned char *libusb_get_iso_packet_buffer(
1136 struct libusb_transfer *transfer, unsigned int packet)
1137{
1138 int i;
1139 size_t offset = 0;
1140 int _packet;
1141
1142 /* oops..slight bug in the API. packet is an unsigned int, but we use
1143 * signed integers almost everywhere else. range-check and convert to
1144 * signed to avoid compiler warnings. FIXME for libusb-2. */
1145 if (packet > INT_MAX)
1146 return NULL;
1147 _packet = packet;
1148
1149 if (_packet >= transfer->num_iso_packets)
1150 return NULL;
1151
1152 for (i = 0; i < _packet; i++)
1153 offset += transfer->iso_packet_desc[i].length;
1154
1155 return transfer->buffer + offset;
1156}
1157
1158/** \ingroup asyncio
1159 * Convenience function to locate the position of an isochronous packet
1160 * within the buffer of an isochronous transfer, for transfers where each
1161 * packet is of identical size.
1162 *
1163 * This function relies on the assumption that every packet within the transfer
1164 * is of identical size to the first packet. Calculating the location of
1165 * the packet buffer is then just a simple calculation:
1166 * <tt>buffer + (packet_size * packet)</tt>
1167 *
1168 * Do not use this function on transfers other than those that have identical
1169 * packet lengths for each packet.
1170 *
1171 * \param transfer a transfer
1172 * \param packet the packet to return the address of
1173 * \returns the base address of the packet buffer inside the transfer buffer,
1174 * or NULL if the packet does not exist.
1175 * \see libusb_get_iso_packet_buffer()
1176 */
1177static inline unsigned char *libusb_get_iso_packet_buffer_simple(
1178 struct libusb_transfer *transfer, unsigned int packet)
1179{
1180 int _packet;
1181
1182 /* oops..slight bug in the API. packet is an unsigned int, but we use
1183 * signed integers almost everywhere else. range-check and convert to
1184 * signed to avoid compiler warnings. FIXME for libusb-2. */
1185 if (packet > INT_MAX)
1186 return NULL;
1187 _packet = packet;
1188
1189 if (_packet >= transfer->num_iso_packets)
1190 return NULL;
1191
1192 return transfer->buffer + (transfer->iso_packet_desc[0].length * _packet);
1193}
1194
1195/* sync I/O */
1196
1197int LIBUSB_CALL libusb_control_transfer(libusb_device_handle *dev_handle,
1198 uint8_t request_type, uint8_t bRequest, uint16_t wValue, uint16_t wIndex,
1199 unsigned char *data, uint16_t wLength, unsigned int timeout);
1200
1201int LIBUSB_CALL libusb_bulk_transfer(libusb_device_handle *dev_handle,
1202 unsigned char endpoint, unsigned char *data, int length,
1203 int *actual_length, unsigned int timeout);
1204
1205int LIBUSB_CALL libusb_interrupt_transfer(libusb_device_handle *dev_handle,
1206 unsigned char endpoint, unsigned char *data, int length,
1207 int *actual_length, unsigned int timeout);
1208
1209/** \ingroup desc
1210 * Retrieve a descriptor from the default control pipe.
1211 * This is a convenience function which formulates the appropriate control
1212 * message to retrieve the descriptor.
1213 *
1214 * \param dev a device handle
1215 * \param desc_type the descriptor type, see \ref libusb_descriptor_type
1216 * \param desc_index the index of the descriptor to retrieve
1217 * \param data output buffer for descriptor
1218 * \param length size of data buffer
1219 * \returns number of bytes returned in data, or LIBUSB_ERROR code on failure
1220 */
1221static inline int libusb_get_descriptor(libusb_device_handle *dev,
1222 uint8_t desc_type, uint8_t desc_index, unsigned char *data, int length)
1223{
1224 return libusb_control_transfer(dev, LIBUSB_ENDPOINT_IN,
1225 LIBUSB_REQUEST_GET_DESCRIPTOR, (desc_type << 8) | desc_index, 0, data,
1226 (uint16_t) length, 1000);
1227}
1228
1229/** \ingroup desc
1230 * Retrieve a descriptor from a device.
1231 * This is a convenience function which formulates the appropriate control
1232 * message to retrieve the descriptor. The string returned is Unicode, as
1233 * detailed in the USB specifications.
1234 *
1235 * \param dev a device handle
1236 * \param desc_index the index of the descriptor to retrieve
1237 * \param langid the language ID for the string descriptor
1238 * \param data output buffer for descriptor
1239 * \param length size of data buffer
1240 * \returns number of bytes returned in data, or LIBUSB_ERROR code on failure
1241 * \see libusb_get_string_descriptor_ascii()
1242 */
1243static inline int libusb_get_string_descriptor(libusb_device_handle *dev,
1244 uint8_t desc_index, uint16_t langid, unsigned char *data, int length)
1245{
1246 return libusb_control_transfer(dev, LIBUSB_ENDPOINT_IN,
1247 LIBUSB_REQUEST_GET_DESCRIPTOR, (LIBUSB_DT_STRING << 8) | desc_index,
1248 langid, data, (uint16_t) length, 1000);
1249}
1250
1251int LIBUSB_CALL libusb_get_string_descriptor_ascii(libusb_device_handle *dev,
1252 uint8_t desc_index, unsigned char *data, int length);
1253
1254/* polling and timeouts */
1255
1256int LIBUSB_CALL libusb_try_lock_events(libusb_context *ctx);
1257void LIBUSB_CALL libusb_lock_events(libusb_context *ctx);
1258void LIBUSB_CALL libusb_unlock_events(libusb_context *ctx);
1259int LIBUSB_CALL libusb_event_handling_ok(libusb_context *ctx);
1260int LIBUSB_CALL libusb_event_handler_active(libusb_context *ctx);
1261void LIBUSB_CALL libusb_lock_event_waiters(libusb_context *ctx);
1262void LIBUSB_CALL libusb_unlock_event_waiters(libusb_context *ctx);
1263int LIBUSB_CALL libusb_wait_for_event(libusb_context *ctx, struct timeval *tv);
1264
1265int LIBUSB_CALL libusb_handle_events_timeout(libusb_context *ctx,
1266 struct timeval *tv);
1267int LIBUSB_CALL libusb_handle_events(libusb_context *ctx);
1268int LIBUSB_CALL libusb_handle_events_locked(libusb_context *ctx,
1269 struct timeval *tv);
1270int LIBUSB_CALL libusb_pollfds_handle_timeouts(libusb_context *ctx);
1271int LIBUSB_CALL libusb_get_next_timeout(libusb_context *ctx,
1272 struct timeval *tv);
1273
1274/** \ingroup poll
1275 * File descriptor for polling
1276 */
1277struct libusb_pollfd {
1278 /** Numeric file descriptor */
1279 int fd;
1280
1281 /** Event flags to poll for from <poll.h>. POLLIN indicates that you
1282 * should monitor this file descriptor for becoming ready to read from,
1283 * and POLLOUT indicates that you should monitor this file descriptor for
1284 * nonblocking write readiness. */
1285 short events;
1286};
1287
1288/** \ingroup poll
1289 * Callback function, invoked when a new file descriptor should be added
1290 * to the set of file descriptors monitored for events.
1291 * \param fd the new file descriptor
1292 * \param events events to monitor for, see \ref libusb_pollfd for a
1293 * description
1294 * \param user_data User data pointer specified in
1295 * libusb_set_pollfd_notifiers() call
1296 * \see libusb_set_pollfd_notifiers()
1297 */
1298typedef void (LIBUSB_CALL *libusb_pollfd_added_cb)(int fd, short events,
1299 void *user_data);
1300
1301/** \ingroup poll
1302 * Callback function, invoked when a file descriptor should be removed from
1303 * the set of file descriptors being monitored for events. After returning
1304 * from this callback, do not use that file descriptor again.
1305 * \param fd the file descriptor to stop monitoring
1306 * \param user_data User data pointer specified in
1307 * libusb_set_pollfd_notifiers() call
1308 * \see libusb_set_pollfd_notifiers()
1309 */
1310typedef void (LIBUSB_CALL *libusb_pollfd_removed_cb)(int fd, void *user_data);
1311
1312const struct libusb_pollfd ** LIBUSB_CALL libusb_get_pollfds(
1313 libusb_context *ctx);
1314void LIBUSB_CALL libusb_set_pollfd_notifiers(libusb_context *ctx,
1315 libusb_pollfd_added_cb added_cb, libusb_pollfd_removed_cb removed_cb,
1316 void *user_data);
1317
1318#ifdef __cplusplus
1319}
1320#endif
1321
1322#endif
diff --git a/include/libusb-1.0/libusbi.h b/include/libusb-1.0/libusbi.h
deleted file mode 100644
index 9b2fa70..0000000
--- a/include/libusb-1.0/libusbi.h
+++ /dev/null
@@ -1,872 +0,0 @@
1/*
2 * Internal header 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#ifndef __LIBUSBI_H__
22#define __LIBUSBI_H__
23
24#include <config.h>
25
26#include <stddef.h>
27#include <stdint.h>
28#include <time.h>
29
30#include <libusb.h>
31
32/* Inside the libusb code, mark all public functions as follows:
33 * return_type API_EXPORTED function_name(params) { ... }
34 * But if the function returns a pointer, mark it as follows:
35 * DEFAULT_VISIBILITY return_type * LIBUSB_CALL function_name(params) { ... }
36 * In the libusb public header, mark all declarations as:
37 * return_type LIBUSB_CALL function_name(params);
38 */
39#define API_EXPORTED LIBUSB_CALL DEFAULT_VISIBILITY
40
41#define DEVICE_DESC_LENGTH 18
42
43#define USB_MAXENDPOINTS 32
44#define USB_MAXINTERFACES 32
45#define USB_MAXCONFIG 8
46
47struct list_head {
48 struct list_head *prev, *next;
49};
50
51/* Get an entry from the list
52 * ptr - the address of this list_head element in "type"
53 * type - the data type that contains "member"
54 * member - the list_head element in "type"
55 */
56#define list_entry(ptr, type, member) \
57 ((type *)((uintptr_t)(ptr) - (uintptr_t)(&((type *)0L)->member)))
58
59/* Get each entry from a list
60 * pos - A structure pointer has a "member" element
61 * head - list head
62 * member - the list_head element in "pos"
63 * type - the type of the first parameter
64 */
65#define list_for_each_entry(pos, head, member, type) \
66 for (pos = list_entry((head)->next, type, member); \
67 &pos->member != (head); \
68 pos = list_entry(pos->member.next, type, member))
69
70#define list_for_each_entry_safe(pos, n, head, member, type) \
71 for (pos = list_entry((head)->next, type, member), \
72 n = list_entry(pos->member.next, type, member); \
73 &pos->member != (head); \
74 pos = n, n = list_entry(n->member.next, type, member))
75
76#define list_empty(entry) ((entry)->next == (entry))
77
78static inline void list_init(struct list_head *entry)
79{
80 entry->prev = entry->next = entry;
81}
82
83static inline void list_add(struct list_head *entry, struct list_head *head)
84{
85 entry->next = head->next;
86 entry->prev = head;
87
88 head->next->prev = entry;
89 head->next = entry;
90}
91
92static inline void list_add_tail(struct list_head *entry,
93 struct list_head *head)
94{
95 entry->next = head;
96 entry->prev = head->prev;
97
98 head->prev->next = entry;
99 head->prev = entry;
100}
101
102static inline void list_del(struct list_head *entry)
103{
104 entry->next->prev = entry->prev;
105 entry->prev->next = entry->next;
106}
107
108#define container_of(ptr, type, member) ({ \
109 const typeof( ((type *)0)->member ) *__mptr = (ptr); \
110 (type *)( (char *)__mptr - offsetof(type,member) );})
111
112#define MIN(a, b) ((a) < (b) ? (a) : (b))
113#define MAX(a, b) ((a) > (b) ? (a) : (b))
114
115#define TIMESPEC_IS_SET(ts) ((ts)->tv_sec != 0 || (ts)->tv_nsec != 0)
116
117enum usbi_log_level {
118 LOG_LEVEL_DEBUG,
119 LOG_LEVEL_INFO,
120 LOG_LEVEL_WARNING,
121 LOG_LEVEL_ERROR,
122};
123
124void usbi_log(struct libusb_context *ctx, enum usbi_log_level level,
125 const char *function, const char *format, ...);
126
127#if !defined(_MSC_VER) || _MSC_VER > 1200
128
129#ifdef ENABLE_LOGGING
130#define _usbi_log(ctx, level, ...) usbi_log(ctx, level, __FUNCTION__, __VA_ARGS__)
131#else
132#define _usbi_log(ctx, level, ...)
133#endif
134
135#ifdef ENABLE_DEBUG_LOGGING
136#define usbi_dbg(...) _usbi_log(NULL, LOG_LEVEL_DEBUG, __VA_ARGS__)
137#else
138#define usbi_dbg(...)
139#endif
140
141#define usbi_info(ctx, ...) _usbi_log(ctx, LOG_LEVEL_INFO, __VA_ARGS__)
142#define usbi_warn(ctx, ...) _usbi_log(ctx, LOG_LEVEL_WARNING, __VA_ARGS__)
143#define usbi_err(ctx, ...) _usbi_log(ctx, LOG_LEVEL_ERROR, __VA_ARGS__)
144
145#else /* !defined(_MSC_VER) || _MSC_VER > 1200 */
146
147void usbi_log_v(struct libusb_context *ctx, enum usbi_log_level level,
148 const char *function, const char *format, va_list args);
149
150#ifdef ENABLE_LOGGING
151#define LOG_BODY(ctxt, level) \
152{ \
153 va_list args; \
154 va_start (args, format); \
155 usbi_log_v(ctxt, level, "", format, args); \
156 va_end(args); \
157}
158#else
159#define LOG_BODY(ctxt, level) { }
160#endif
161
162static inline void usbi_info(struct libusb_context *ctx, const char *format,
163 ...)
164 LOG_BODY(ctx,LOG_LEVEL_INFO)
165static inline void usbi_warn(struct libusb_context *ctx, const char *format,
166 ...)
167 LOG_BODY(ctx,LOG_LEVEL_WARNING)
168static inline void usbi_err( struct libusb_context *ctx, const char *format,
169 ...)
170 LOG_BODY(ctx,LOG_LEVEL_ERROR)
171
172static inline void usbi_dbg(const char *format, ...)
173#ifdef ENABLE_DEBUG_LOGGING
174 LOG_BODY(NULL,LOG_LEVEL_DEBUG)
175#else
176{ }
177#endif
178
179#endif /* !defined(_MSC_VER) || _MSC_VER > 1200 */
180
181#define USBI_GET_CONTEXT(ctx) if (!(ctx)) (ctx) = usbi_default_context
182#define DEVICE_CTX(dev) ((dev)->ctx)
183#define HANDLE_CTX(handle) (DEVICE_CTX((handle)->dev))
184#define TRANSFER_CTX(transfer) (HANDLE_CTX((transfer)->dev_handle))
185#define ITRANSFER_CTX(transfer) \
186 (TRANSFER_CTX(__USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer)))
187
188/* Internal abstractions for thread synchronization and poll */
189#if defined(THREADS_POSIX)
190#include <os/threads_posix.h>
191#elif defined(OS_WINDOWS)
192#include <os/threads_windows.h>
193#endif
194
195#if defined(OS_LINUX) || defined(OS_DARWIN)
196#include <os/poll_posix.h>
197#elif defined(OS_WINDOWS)
198#include <os/poll_windows.h>
199#endif
200
201extern struct libusb_context *usbi_default_context;
202
203struct libusb_context {
204 int debug;
205 int debug_fixed;
206
207 /* internal control pipe, used for interrupting event handling when
208 * something needs to modify poll fds. */
209 int ctrl_pipe[2];
210
211 struct list_head usb_devs;
212 usbi_mutex_t usb_devs_lock;
213
214 /* A list of open handles. Backends are free to traverse this if required.
215 */
216 struct list_head open_devs;
217 usbi_mutex_t open_devs_lock;
218
219 /* this is a list of in-flight transfer handles, sorted by timeout
220 * expiration. URBs to timeout the soonest are placed at the beginning of
221 * the list, URBs that will time out later are placed after, and urbs with
222 * infinite timeout are always placed at the very end. */
223 struct list_head flying_transfers;
224 usbi_mutex_t flying_transfers_lock;
225
226 /* list of poll fds */
227 struct list_head pollfds;
228 usbi_mutex_t pollfds_lock;
229
230 /* a counter that is set when we want to interrupt event handling, in order
231 * to modify the poll fd set. and a lock to protect it. */
232 unsigned int pollfd_modify;
233 usbi_mutex_t pollfd_modify_lock;
234
235 /* user callbacks for pollfd changes */
236 libusb_pollfd_added_cb fd_added_cb;
237 libusb_pollfd_removed_cb fd_removed_cb;
238 void *fd_cb_user_data;
239
240 /* ensures that only one thread is handling events at any one time */
241 usbi_mutex_t events_lock;
242
243 /* used to see if there is an active thread doing event handling */
244 int event_handler_active;
245
246 /* used to wait for event completion in threads other than the one that is
247 * event handling */
248 usbi_mutex_t event_waiters_lock;
249 usbi_cond_t event_waiters_cond;
250
251#ifdef USBI_TIMERFD_AVAILABLE
252 /* used for timeout handling, if supported by OS.
253 * this timerfd is maintained to trigger on the next pending timeout */
254 int timerfd;
255#endif
256};
257
258#ifdef USBI_TIMERFD_AVAILABLE
259#define usbi_using_timerfd(ctx) ((ctx)->timerfd >= 0)
260#else
261#define usbi_using_timerfd(ctx) (0)
262#endif
263
264struct libusb_device {
265 /* lock protects refcnt, everything else is finalized at initialization
266 * time */
267 usbi_mutex_t lock;
268 int refcnt;
269
270 struct libusb_context *ctx;
271
272 uint8_t bus_number;
273 uint8_t device_address;
274 uint8_t num_configurations;
275
276 struct list_head list;
277 unsigned long session_data;
278 unsigned char os_priv[0];
279};
280
281struct libusb_device_handle {
282 /* lock protects claimed_interfaces */
283 usbi_mutex_t lock;
284 unsigned long claimed_interfaces;
285
286 struct list_head list;
287 struct libusb_device *dev;
288 unsigned char os_priv[0];
289};
290
291#define USBI_TRANSFER_TIMED_OUT (1<<0)
292
293enum {
294 USBI_CLOCK_MONOTONIC,
295 USBI_CLOCK_REALTIME
296};
297
298/* in-memory transfer layout:
299 *
300 * 1. struct usbi_transfer
301 * 2. struct libusb_transfer (which includes iso packets) [variable size]
302 * 3. os private data [variable size]
303 *
304 * from a libusb_transfer, you can get the usbi_transfer by rewinding the
305 * appropriate number of bytes.
306 * the usbi_transfer includes the number of allocated packets, so you can
307 * determine the size of the transfer and hence the start and length of the
308 * OS-private data.
309 */
310
311struct usbi_transfer {
312 int num_iso_packets;
313 struct list_head list;
314 struct timeval timeout;
315 int transferred;
316 uint8_t flags;
317
318 /* this lock is held during libusb_submit_transfer() and
319 * libusb_cancel_transfer() (allowing the OS backend to prevent duplicate
320 * cancellation, submission-during-cancellation, etc). the OS backend
321 * should also take this lock in the handle_events path, to prevent the user
322 * cancelling the transfer from another thread while you are processing
323 * its completion (presumably there would be races within your OS backend
324 * if this were possible). */
325 usbi_mutex_t lock;
326};
327
328#define __USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer) \
329 ((struct libusb_transfer *)(((unsigned char *)(transfer)) \
330 + sizeof(struct usbi_transfer)))
331#define __LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer) \
332 ((struct usbi_transfer *)(((unsigned char *)(transfer)) \
333 - sizeof(struct usbi_transfer)))
334
335static inline void *usbi_transfer_get_os_priv(struct usbi_transfer *transfer)
336{
337 return ((unsigned char *)transfer) + sizeof(struct usbi_transfer)
338 + sizeof(struct libusb_transfer)
339 + (transfer->num_iso_packets
340 * sizeof(struct libusb_iso_packet_descriptor));
341}
342
343/* bus structures */
344
345/* All standard descriptors have these 2 fields in common */
346struct usb_descriptor_header {
347 uint8_t bLength;
348 uint8_t bDescriptorType;
349};
350
351/* shared data and functions */
352
353int usbi_io_init(struct libusb_context *ctx);
354void usbi_io_exit(struct libusb_context *ctx);
355
356struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
357 unsigned long session_id);
358struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
359 unsigned long session_id);
360int usbi_sanitize_device(struct libusb_device *dev);
361void usbi_handle_disconnect(struct libusb_device_handle *handle);
362
363int usbi_handle_transfer_completion(struct usbi_transfer *itransfer,
364 enum libusb_transfer_status status);
365int usbi_handle_transfer_cancellation(struct usbi_transfer *transfer);
366
367int usbi_parse_descriptor(unsigned char *source, char *descriptor, void *dest,
368 int host_endian);
369int usbi_get_config_index_by_value(struct libusb_device *dev,
370 uint8_t bConfigurationValue, int *idx);
371
372/* polling */
373
374struct usbi_pollfd {
375 /* must come first */
376 struct libusb_pollfd pollfd;
377
378 struct list_head list;
379};
380
381int usbi_add_pollfd(struct libusb_context *ctx, int fd, short events);
382void usbi_remove_pollfd(struct libusb_context *ctx, int fd);
383void usbi_fd_notification(struct libusb_context *ctx);
384
385/* device discovery */
386
387/* we traverse usbfs without knowing how many devices we are going to find.
388 * so we create this discovered_devs model which is similar to a linked-list
389 * which grows when required. it can be freed once discovery has completed,
390 * eliminating the need for a list node in the libusb_device structure
391 * itself. */
392struct discovered_devs {
393 size_t len;
394 size_t capacity;
395 struct libusb_device *devices[0];
396};
397
398struct discovered_devs *discovered_devs_append(
399 struct discovered_devs *discdevs, struct libusb_device *dev);
400
401/* OS abstraction */
402
403/* This is the interface that OS backends need to implement.
404 * All fields are mandatory, except ones explicitly noted as optional. */
405struct usbi_os_backend {
406 /* A human-readable name for your backend, e.g. "Linux usbfs" */
407 const char *name;
408
409 /* Perform initialization of your backend. You might use this function
410 * to determine specific capabilities of the system, allocate required
411 * data structures for later, etc.
412 *
413 * This function is called when a libusb user initializes the library
414 * prior to use.
415 *
416 * Return 0 on success, or a LIBUSB_ERROR code on failure.
417 */
418 int (*init)(struct libusb_context *ctx);
419
420 /* Deinitialization. Optional. This function should destroy anything
421 * that was set up by init.
422 *
423 * This function is called when the user deinitializes the library.
424 */
425 void (*exit)(void);
426
427 /* Enumerate all the USB devices on the system, returning them in a list
428 * of discovered devices.
429 *
430 * Your implementation should enumerate all devices on the system,
431 * regardless of whether they have been seen before or not.
432 *
433 * When you have found a device, compute a session ID for it. The session
434 * ID should uniquely represent that particular device for that particular
435 * connection session since boot (i.e. if you disconnect and reconnect a
436 * device immediately after, it should be assigned a different session ID).
437 * If your OS cannot provide a unique session ID as described above,
438 * presenting a session ID of (bus_number << 8 | device_address) should
439 * be sufficient. Bus numbers and device addresses wrap and get reused,
440 * but that is an unlikely case.
441 *
442 * After computing a session ID for a device, call
443 * usbi_get_device_by_session_id(). This function checks if libusb already
444 * knows about the device, and if so, it provides you with a libusb_device
445 * structure for it.
446 *
447 * If usbi_get_device_by_session_id() returns NULL, it is time to allocate
448 * a new device structure for the device. Call usbi_alloc_device() to
449 * obtain a new libusb_device structure with reference count 1. Populate
450 * the bus_number and device_address attributes of the new device, and
451 * perform any other internal backend initialization you need to do. At
452 * this point, you should be ready to provide device descriptors and so
453 * on through the get_*_descriptor functions. Finally, call
454 * usbi_sanitize_device() to perform some final sanity checks on the
455 * device. Assuming all of the above succeeded, we can now continue.
456 * If any of the above failed, remember to unreference the device that
457 * was returned by usbi_alloc_device().
458 *
459 * At this stage we have a populated libusb_device structure (either one
460 * that was found earlier, or one that we have just allocated and
461 * populated). This can now be added to the discovered devices list
462 * using discovered_devs_append(). Note that discovered_devs_append()
463 * may reallocate the list, returning a new location for it, and also
464 * note that reallocation can fail. Your backend should handle these
465 * error conditions appropriately.
466 *
467 * This function should not generate any bus I/O and should not block.
468 * If I/O is required (e.g. reading the active configuration value), it is
469 * OK to ignore these suggestions :)
470 *
471 * This function is executed when the user wishes to retrieve a list
472 * of USB devices connected to the system.
473 *
474 * Return 0 on success, or a LIBUSB_ERROR code on failure.
475 */
476 int (*get_device_list)(struct libusb_context *ctx,
477 struct discovered_devs **discdevs);
478
479 /* Open a device for I/O and other USB operations. The device handle
480 * is preallocated for you, you can retrieve the device in question
481 * through handle->dev.
482 *
483 * Your backend should allocate any internal resources required for I/O
484 * and other operations so that those operations can happen (hopefully)
485 * without hiccup. This is also a good place to inform libusb that it
486 * should monitor certain file descriptors related to this device -
487 * see the usbi_add_pollfd() function.
488 *
489 * This function should not generate any bus I/O and should not block.
490 *
491 * This function is called when the user attempts to obtain a device
492 * handle for a device.
493 *
494 * Return:
495 * - 0 on success
496 * - LIBUSB_ERROR_ACCESS if the user has insufficient permissions
497 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since
498 * discovery
499 * - another LIBUSB_ERROR code on other failure
500 *
501 * Do not worry about freeing the handle on failed open, the upper layers
502 * do this for you.
503 */
504 int (*open)(struct libusb_device_handle *handle);
505
506 /* Close a device such that the handle cannot be used again. Your backend
507 * should destroy any resources that were allocated in the open path.
508 * This may also be a good place to call usbi_remove_pollfd() to inform
509 * libusb of any file descriptors associated with this device that should
510 * no longer be monitored.
511 *
512 * This function is called when the user closes a device handle.
513 */
514 void (*close)(struct libusb_device_handle *handle);
515
516 /* Retrieve the device descriptor from a device.
517 *
518 * The descriptor should be retrieved from memory, NOT via bus I/O to the
519 * device. This means that you may have to cache it in a private structure
520 * during get_device_list enumeration. Alternatively, you may be able
521 * to retrieve it from a kernel interface (some Linux setups can do this)
522 * still without generating bus I/O.
523 *
524 * This function is expected to write DEVICE_DESC_LENGTH (18) bytes into
525 * buffer, which is guaranteed to be big enough.
526 *
527 * This function is called when sanity-checking a device before adding
528 * it to the list of discovered devices, and also when the user requests
529 * to read the device descriptor.
530 *
531 * This function is expected to return the descriptor in bus-endian format
532 * (LE). If it returns the multi-byte values in host-endian format,
533 * set the host_endian output parameter to "1".
534 *
535 * Return 0 on success or a LIBUSB_ERROR code on failure.
536 */
537 int (*get_device_descriptor)(struct libusb_device *device,
538 unsigned char *buffer, int *host_endian);
539
540 /* Get the ACTIVE configuration descriptor for a device.
541 *
542 * The descriptor should be retrieved from memory, NOT via bus I/O to the
543 * device. This means that you may have to cache it in a private structure
544 * during get_device_list enumeration. You may also have to keep track
545 * of which configuration is active when the user changes it.
546 *
547 * This function is expected to write len bytes of data into buffer, which
548 * is guaranteed to be big enough. If you can only do a partial write,
549 * return an error code.
550 *
551 * This function is expected to return the descriptor in bus-endian format
552 * (LE). If it returns the multi-byte values in host-endian format,
553 * set the host_endian output parameter to "1".
554 *
555 * Return:
556 * - 0 on success
557 * - LIBUSB_ERROR_NOT_FOUND if the device is in unconfigured state
558 * - another LIBUSB_ERROR code on other failure
559 */
560 int (*get_active_config_descriptor)(struct libusb_device *device,
561 unsigned char *buffer, size_t len, int *host_endian);
562
563 /* Get a specific configuration descriptor for a device.
564 *
565 * The descriptor should be retrieved from memory, NOT via bus I/O to the
566 * device. This means that you may have to cache it in a private structure
567 * during get_device_list enumeration.
568 *
569 * The requested descriptor is expressed as a zero-based index (i.e. 0
570 * indicates that we are requesting the first descriptor). The index does
571 * not (necessarily) equal the bConfigurationValue of the configuration
572 * being requested.
573 *
574 * This function is expected to write len bytes of data into buffer, which
575 * is guaranteed to be big enough. If you can only do a partial write,
576 * return an error code.
577 *
578 * This function is expected to return the descriptor in bus-endian format
579 * (LE). If it returns the multi-byte values in host-endian format,
580 * set the host_endian output parameter to "1".
581 *
582 * Return 0 on success or a LIBUSB_ERROR code on failure.
583 */
584 int (*get_config_descriptor)(struct libusb_device *device,
585 uint8_t config_index, unsigned char *buffer, size_t len,
586 int *host_endian);
587
588 /* Get the bConfigurationValue for the active configuration for a device.
589 * Optional. This should only be implemented if you can retrieve it from
590 * cache (don't generate I/O).
591 *
592 * If you cannot retrieve this from cache, either do not implement this
593 * function, or return LIBUSB_ERROR_NOT_SUPPORTED. This will cause
594 * libusb to retrieve the information through a standard control transfer.
595 *
596 * This function must be non-blocking.
597 * Return:
598 * - 0 on success
599 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
600 * was opened
601 * - LIBUSB_ERROR_NOT_SUPPORTED if the value cannot be retrieved without
602 * blocking
603 * - another LIBUSB_ERROR code on other failure.
604 */
605 int (*get_configuration)(struct libusb_device_handle *handle, int *config);
606
607 /* Set the active configuration for a device.
608 *
609 * A configuration value of -1 should put the device in unconfigured state.
610 *
611 * This function can block.
612 *
613 * Return:
614 * - 0 on success
615 * - LIBUSB_ERROR_NOT_FOUND if the configuration does not exist
616 * - LIBUSB_ERROR_BUSY if interfaces are currently claimed (and hence
617 * configuration cannot be changed)
618 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
619 * was opened
620 * - another LIBUSB_ERROR code on other failure.
621 */
622 int (*set_configuration)(struct libusb_device_handle *handle, int config);
623
624 /* Claim an interface. When claimed, the application can then perform
625 * I/O to an interface's endpoints.
626 *
627 * This function should not generate any bus I/O and should not block.
628 * Interface claiming is a logical operation that simply ensures that
629 * no other drivers/applications are using the interface, and after
630 * claiming, no other drivers/applicatiosn can use the interface because
631 * we now "own" it.
632 *
633 * Return:
634 * - 0 on success
635 * - LIBUSB_ERROR_NOT_FOUND if the interface does not exist
636 * - LIBUSB_ERROR_BUSY if the interface is in use by another driver/app
637 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
638 * was opened
639 * - another LIBUSB_ERROR code on other failure
640 */
641 int (*claim_interface)(struct libusb_device_handle *handle, int interface_number);
642
643 /* Release a previously claimed interface.
644 *
645 * This function should also generate a SET_INTERFACE control request,
646 * resetting the alternate setting of that interface to 0. It's OK for
647 * this function to block as a result.
648 *
649 * You will only ever be asked to release an interface which was
650 * successfully claimed earlier.
651 *
652 * Return:
653 * - 0 on success
654 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
655 * was opened
656 * - another LIBUSB_ERROR code on other failure
657 */
658 int (*release_interface)(struct libusb_device_handle *handle, int interface_number);
659
660 /* Set the alternate setting for an interface.
661 *
662 * You will only ever be asked to set the alternate setting for an
663 * interface which was successfully claimed earlier.
664 *
665 * It's OK for this function to block.
666 *
667 * Return:
668 * - 0 on success
669 * - LIBUSB_ERROR_NOT_FOUND if the alternate setting does not exist
670 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
671 * was opened
672 * - another LIBUSB_ERROR code on other failure
673 */
674 int (*set_interface_altsetting)(struct libusb_device_handle *handle,
675 int interface_number, int altsetting);
676
677 /* Clear a halt/stall condition on an endpoint.
678 *
679 * It's OK for this function to block.
680 *
681 * Return:
682 * - 0 on success
683 * - LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
684 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
685 * was opened
686 * - another LIBUSB_ERROR code on other failure
687 */
688 int (*clear_halt)(struct libusb_device_handle *handle,
689 unsigned char endpoint);
690
691 /* Perform a USB port reset to reinitialize a device.
692 *
693 * If possible, the handle should still be usable after the reset
694 * completes, assuming that the device descriptors did not change during
695 * reset and all previous interface state can be restored.
696 *
697 * If something changes, or you cannot easily locate/verify the resetted
698 * device, return LIBUSB_ERROR_NOT_FOUND. This prompts the application
699 * to close the old handle and re-enumerate the device.
700 *
701 * Return:
702 * - 0 on success
703 * - LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the device
704 * has been disconnected since it was opened
705 * - another LIBUSB_ERROR code on other failure
706 */
707 int (*reset_device)(struct libusb_device_handle *handle);
708
709 /* Determine if a kernel driver is active on an interface. Optional.
710 *
711 * The presence of a kernel driver on an interface indicates that any
712 * calls to claim_interface would fail with the LIBUSB_ERROR_BUSY code.
713 *
714 * Return:
715 * - 0 if no driver is active
716 * - 1 if a driver is active
717 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
718 * was opened
719 * - another LIBUSB_ERROR code on other failure
720 */
721 int (*kernel_driver_active)(struct libusb_device_handle *handle,
722 int interface_number);
723
724 /* Detach a kernel driver from an interface. Optional.
725 *
726 * After detaching a kernel driver, the interface should be available
727 * for claim.
728 *
729 * Return:
730 * - 0 on success
731 * - LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
732 * - LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
733 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
734 * was opened
735 * - another LIBUSB_ERROR code on other failure
736 */
737 int (*detach_kernel_driver)(struct libusb_device_handle *handle,
738 int interface_number);
739
740 /* Attach a kernel driver to an interface. Optional.
741 *
742 * Reattach a kernel driver to the device.
743 *
744 * Return:
745 * - 0 on success
746 * - LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
747 * - LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
748 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
749 * was opened
750 * - LIBUSB_ERROR_BUSY if a program or driver has claimed the interface,
751 * preventing reattachment
752 * - another LIBUSB_ERROR code on other failure
753 */
754 int (*attach_kernel_driver)(struct libusb_device_handle *handle,
755 int interface_number);
756
757 /* Destroy a device. Optional.
758 *
759 * This function is called when the last reference to a device is
760 * destroyed. It should free any resources allocated in the get_device_list
761 * path.
762 */
763 void (*destroy_device)(struct libusb_device *dev);
764
765 /* Submit a transfer. Your implementation should take the transfer,
766 * morph it into whatever form your platform requires, and submit it
767 * asynchronously.
768 *
769 * This function must not block.
770 *
771 * Return:
772 * - 0 on success
773 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
774 * - another LIBUSB_ERROR code on other failure
775 */
776 int (*submit_transfer)(struct usbi_transfer *itransfer);
777
778 /* Cancel a previously submitted transfer.
779 *
780 * This function must not block. The transfer cancellation must complete
781 * later, resulting in a call to usbi_handle_transfer_cancellation()
782 * from the context of handle_events.
783 */
784 int (*cancel_transfer)(struct usbi_transfer *itransfer);
785
786 /* Clear a transfer as if it has completed or cancelled, but do not
787 * report any completion/cancellation to the library. You should free
788 * all private data from the transfer as if you were just about to report
789 * completion or cancellation.
790 *
791 * This function might seem a bit out of place. It is used when libusb
792 * detects a disconnected device - it calls this function for all pending
793 * transfers before reporting completion (with the disconnect code) to
794 * the user. Maybe we can improve upon this internal interface in future.
795 */
796 void (*clear_transfer_priv)(struct usbi_transfer *itransfer);
797
798 /* Handle any pending events. This involves monitoring any active
799 * transfers and processing their completion or cancellation.
800 *
801 * The function is passed an array of pollfd structures (size nfds)
802 * as a result of the poll() system call. The num_ready parameter
803 * indicates the number of file descriptors that have reported events
804 * (i.e. the poll() return value). This should be enough information
805 * for you to determine which actions need to be taken on the currently
806 * active transfers.
807 *
808 * For any cancelled transfers, call usbi_handle_transfer_cancellation().
809 * For completed transfers, call usbi_handle_transfer_completion().
810 * For control/bulk/interrupt transfers, populate the "transferred"
811 * element of the appropriate usbi_transfer structure before calling the
812 * above functions. For isochronous transfers, populate the status and
813 * transferred fields of the iso packet descriptors of the transfer.
814 *
815 * This function should also be able to detect disconnection of the
816 * device, reporting that situation with usbi_handle_disconnect().
817 *
818 * When processing an event related to a transfer, you probably want to
819 * take usbi_transfer.lock to prevent races. See the documentation for
820 * the usbi_transfer structure.
821 *
822 * Return 0 on success, or a LIBUSB_ERROR code on failure.
823 */
824 int (*handle_events)(struct libusb_context *ctx,
825 struct pollfd *fds, nfds_t nfds, int num_ready);
826
827 /* Get time from specified clock. At least two clocks must be implemented
828 by the backend: USBI_CLOCK_REALTIME, and USBI_CLOCK_MONOTONIC.
829
830 Description of clocks:
831 USBI_CLOCK_REALTIME : clock returns time since system epoch.
832 USBI_CLOCK_MONOTONIC: clock returns time since unspecified start
833 time (usually boot).
834 */
835 int (*clock_gettime)(int clkid, struct timespec *tp);
836
837#ifdef USBI_TIMERFD_AVAILABLE
838 /* clock ID of the clock that should be used for timerfd */
839 clockid_t (*get_timerfd_clockid)(void);
840#endif
841
842 /* Number of bytes to reserve for per-device private backend data.
843 * This private data area is accessible through the "os_priv" field of
844 * struct libusb_device. */
845 size_t device_priv_size;
846
847 /* Number of bytes to reserve for per-handle private backend data.
848 * This private data area is accessible through the "os_priv" field of
849 * struct libusb_device. */
850 size_t device_handle_priv_size;
851
852 /* Number of bytes to reserve for per-transfer private backend data.
853 * This private data area is accessible by calling
854 * usbi_transfer_get_os_priv() on the appropriate usbi_transfer instance.
855 */
856 size_t transfer_priv_size;
857
858 /* Mumber of additional bytes for os_priv for each iso packet.
859 * Can your backend use this? */
860 /* FIXME: linux can't use this any more. if other OS's cannot either,
861 * then remove this */
862 size_t add_iso_packet_size;
863};
864
865extern const struct usbi_os_backend * const usbi_backend;
866
867extern const struct usbi_os_backend linux_usbfs_backend;
868extern const struct usbi_os_backend darwin_backend;
869extern const struct usbi_os_backend windows_backend;
870
871#endif
872
diff --git a/include/libusb-1.0/os/config.h b/include/libusb-1.0/os/config.h
deleted file mode 100644
index 643d4af..0000000
--- a/include/libusb-1.0/os/config.h
+++ /dev/null
@@ -1,105 +0,0 @@
1/* config.h. Generated from config.h.in by configure. */
2/* config.h.in. Generated from configure.ac by autoheader. */
3
4/* Default visibility */
5#define DEFAULT_VISIBILITY __attribute__((visibility("default")))
6
7/* Debug message logging */
8/* #undef ENABLE_DEBUG_LOGGING */
9
10/* Message logging */
11#define ENABLE_LOGGING 1
12
13/* Define to 1 if you have the <dlfcn.h> header file. */
14#define HAVE_DLFCN_H 1
15
16/* Define to 1 if you have the <inttypes.h> header file. */
17#define HAVE_INTTYPES_H 1
18
19/* Define to 1 if you have the <memory.h> header file. */
20#define HAVE_MEMORY_H 1
21
22/* Define to 1 if you have the <stdint.h> header file. */
23#define HAVE_STDINT_H 1
24
25/* Define to 1 if you have the <stdlib.h> header file. */
26#define HAVE_STDLIB_H 1
27
28/* Define to 1 if you have the <strings.h> header file. */
29#define HAVE_STRINGS_H 1
30
31/* Define to 1 if you have the <string.h> header file. */
32#define HAVE_STRING_H 1
33
34/* Define to 1 if the system has the type `struct timespec'. */
35#define HAVE_STRUCT_TIMESPEC 1
36
37/* Define to 1 if you have the <sys/stat.h> header file. */
38#define HAVE_SYS_STAT_H 1
39
40/* Define to 1 if you have the <sys/time.h> header file. */
41#define HAVE_SYS_TIME_H 1
42
43/* Define to 1 if you have the <sys/types.h> header file. */
44#define HAVE_SYS_TYPES_H 1
45
46/* Define to 1 if you have the <unistd.h> header file. */
47#define HAVE_UNISTD_H 1
48
49/* Define to the sub-directory in which libtool stores uninstalled libraries.
50 */
51#define LT_OBJDIR ".libs/"
52
53/* Define to 1 if your C compiler doesn't accept -c and -o together. */
54/* #undef NO_MINUS_C_MINUS_O */
55
56/* Darwin backend */
57#define OS_DARWIN
58
59/* Linux backend */
60/* #undef OS_LINUX */
61
62/* Windows backend */
63/* #undef OS_WINDOWS */
64
65/* Name of package */
66#define PACKAGE "libusb"
67
68/* Define to the address where bug reports for this package should be sent. */
69#define PACKAGE_BUGREPORT "libusb-devel@lists.sourceforge.net"
70
71/* Define to the full name of this package. */
72#define PACKAGE_NAME "libusb"
73
74/* Define to the full name and version of this package. */
75#define PACKAGE_STRING "libusb 1.0.8"
76
77/* Define to the one symbol short name of this package. */
78#define PACKAGE_TARNAME "libusb"
79
80/* Define to the version of this package. */
81#define PACKAGE_VERSION "1.0.8"
82
83/* Define to 1 if you have the ANSI C header files. */
84#define STDC_HEADERS 1
85
86/* Use Posix Threads */
87#define THREADS_POSIX
88
89/* Backend handles timeout */
90#define USBI_OS_HANDLES_TIMEOUT
91
92/* timerfd headers available */
93/* #undef USBI_TIMERFD_AVAILABLE */
94
95/* Version number of package */
96#define VERSION "1.0.8"
97
98/* Use GNU extensions */
99#define _GNU_SOURCE
100
101/* Define to `__inline__' or `__inline' if that's what the C compiler
102 calls it, or to nothing if 'inline' is not supported under any name. */
103#ifndef __cplusplus
104/* #undef inline */
105#endif
diff --git a/include/libusb-1.0/os/darwin_usb.c b/include/libusb-1.0/os/darwin_usb.c
deleted file mode 100644
index 646c938..0000000
--- a/include/libusb-1.0/os/darwin_usb.c
+++ /dev/null
@@ -1,1545 +0,0 @@
1/*
2 * darwin backend for libusb 1.0
3 * Copyright (C) 2008-2010 Nathan Hjelm <hjelmn@users.sourceforge.net>
4 *
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
9 *
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18 */
19
20#include <config.h>
21#include <ctype.h>
22#include <dirent.h>
23#include <errno.h>
24#include <fcntl.h>
25#include <pthread.h>
26#include <stdio.h>
27#include <stdlib.h>
28#include <string.h>
29#include <sys/ioctl.h>
30#include <sys/stat.h>
31#include <sys/types.h>
32#include <unistd.h>
33
34#include <mach/clock.h>
35#include <mach/clock_types.h>
36#include <mach/mach_host.h>
37
38#include <mach/mach_port.h>
39#include <IOKit/IOCFBundle.h>
40#include <IOKit/usb/IOUSBLib.h>
41#include <IOKit/IOCFPlugIn.h>
42
43#include "darwin_usb.h"
44
45static mach_port_t libusb_darwin_mp = 0; /* master port */
46static CFRunLoopRef libusb_darwin_acfl = NULL; /* async cf loop */
47static int initCount = 0;
48
49/* async event thread */
50static pthread_t libusb_darwin_at;
51
52static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
53static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
54static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
55static int darwin_reset_device(struct libusb_device_handle *dev_handle);
56static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
57
58static const char *darwin_error_str (int result) {
59 switch (result) {
60 case kIOReturnSuccess:
61 return "no error";
62 case kIOReturnNotOpen:
63 return "device not opened for exclusive access";
64 case kIOReturnNoDevice:
65 return "no connection to an IOService";
66 case kIOUSBNoAsyncPortErr:
67 return "no async port has been opened for interface";
68 case kIOReturnExclusiveAccess:
69 return "another process has device opened for exclusive access";
70 case kIOUSBPipeStalled:
71 return "pipe is stalled";
72 case kIOReturnError:
73 return "could not establish a connection to the Darwin kernel";
74 case kIOUSBTransactionTimeout:
75 return "transaction timed out";
76 case kIOReturnBadArgument:
77 return "invalid argument";
78 case kIOReturnAborted:
79 return "transaction aborted";
80 case kIOReturnNotResponding:
81 return "device not responding";
82 case kIOReturnOverrun:
83 return "data overrun";
84 case kIOReturnCannotWire:
85 return "physical memory can not be wired down";
86 default:
87 return "unknown error";
88 }
89}
90
91static int darwin_to_libusb (int result) {
92 switch (result) {
93 case kIOReturnUnderrun:
94 case kIOReturnSuccess:
95 return LIBUSB_SUCCESS;
96 case kIOReturnNotOpen:
97 case kIOReturnNoDevice:
98 return LIBUSB_ERROR_NO_DEVICE;
99 case kIOReturnExclusiveAccess:
100 return LIBUSB_ERROR_ACCESS;
101 case kIOUSBPipeStalled:
102 return LIBUSB_ERROR_PIPE;
103 case kIOReturnBadArgument:
104 return LIBUSB_ERROR_INVALID_PARAM;
105 case kIOUSBTransactionTimeout:
106 return LIBUSB_ERROR_TIMEOUT;
107 case kIOReturnNotResponding:
108 case kIOReturnAborted:
109 case kIOReturnError:
110 case kIOUSBNoAsyncPortErr:
111 default:
112 return LIBUSB_ERROR_OTHER;
113 }
114}
115
116
117static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp) {
118 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
119
120 /* current interface */
121 struct __darwin_interface *cInterface;
122
123 int8_t i, iface;
124
125 usbi_info (HANDLE_CTX(dev_handle), "converting ep address 0x%02x to pipeRef and interface", ep);
126
127 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
128 cInterface = &priv->interfaces[iface];
129
130 if (dev_handle->claimed_interfaces & (1 << iface)) {
131 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
132 if (cInterface->endpoint_addrs[i] == ep) {
133 *pipep = i + 1;
134 *ifcp = iface;
135 usbi_info (HANDLE_CTX(dev_handle), "pipe %d on interface %d matches", *pipep, *ifcp);
136 return 0;
137 }
138 }
139 }
140 }
141
142 /* No pipe found with the correct endpoint address */
143 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
144
145 return -1;
146}
147
148static int usb_setup_device_iterator (io_iterator_t *deviceIterator) {
149 return IOServiceGetMatchingServices(libusb_darwin_mp, IOServiceMatching(kIOUSBDeviceClassName), deviceIterator);
150}
151
152static usb_device_t **usb_get_next_device (io_iterator_t deviceIterator, UInt32 *locationp) {
153 io_cf_plugin_ref_t *plugInInterface = NULL;
154 usb_device_t **device;
155 io_service_t usbDevice;
156 long result;
157 SInt32 score;
158
159 if (!IOIteratorIsValid (deviceIterator))
160 return NULL;
161
162
163 while ((usbDevice = IOIteratorNext(deviceIterator))) {
164 result = IOCreatePlugInInterfaceForService(usbDevice, kIOUSBDeviceUserClientTypeID,
165 kIOCFPlugInInterfaceID, &plugInInterface,
166 &score);
167 if (kIOReturnSuccess == result && plugInInterface)
168 break;
169
170 usbi_dbg ("libusb/darwin.c usb_get_next_device: could not set up plugin for service: %s\n", darwin_error_str (result));
171 }
172
173 if (!usbDevice)
174 return NULL;
175
176 (void)IOObjectRelease(usbDevice);
177 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
178 (LPVOID)&device);
179
180 (*plugInInterface)->Stop(plugInInterface);
181 IODestroyPlugInInterface (plugInInterface);
182
183 /* get the location from the device */
184 if (locationp)
185 (*(device))->GetLocationID(device, locationp);
186
187 return device;
188}
189
190static kern_return_t darwin_get_device (uint32_t dev_location, usb_device_t ***darwin_device) {
191 kern_return_t kresult;
192 UInt32 location;
193 io_iterator_t deviceIterator;
194
195 kresult = usb_setup_device_iterator (&deviceIterator);
196 if (kresult)
197 return kresult;
198
199 /* This port of libusb uses locations to keep track of devices. */
200 while ((*darwin_device = usb_get_next_device (deviceIterator, &location)) != NULL) {
201 if (location == dev_location)
202 break;
203
204 (**darwin_device)->Release(*darwin_device);
205 }
206
207 IOObjectRelease (deviceIterator);
208
209 if (!(*darwin_device))
210 return kIOReturnNoDevice;
211
212 return kIOReturnSuccess;
213}
214
215
216
217static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
218 struct libusb_context *ctx = (struct libusb_context *)ptr;
219 struct libusb_device_handle *handle;
220 struct darwin_device_priv *dpriv;
221 struct darwin_device_handle_priv *priv;
222
223 io_service_t device;
224 long location;
225 CFTypeRef locationCF;
226 UInt32 message;
227
228 usbi_info (ctx, "a device has been detached");
229
230 while ((device = IOIteratorNext (rem_devices)) != 0) {
231 /* get the location from the i/o registry */
232 locationCF = IORegistryEntryCreateCFProperty (device, CFSTR(kUSBDevicePropertyLocationID), kCFAllocatorDefault, 0);
233
234 CFNumberGetValue(locationCF, kCFNumberLongType, &location);
235 CFRelease (locationCF);
236 IOObjectRelease (device);
237
238 usbi_mutex_lock(&ctx->open_devs_lock);
239 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
240 dpriv = (struct darwin_device_priv *)handle->dev->os_priv;
241
242 /* the device may have been opened several times. write to each handle's event descriptor */
243 if (dpriv->location == location && handle->os_priv) {
244 priv = (struct darwin_device_handle_priv *)handle->os_priv;
245
246 message = MESSAGE_DEVICE_GONE;
247 write (priv->fds[1], &message, sizeof (message));
248 }
249 }
250
251 usbi_mutex_unlock(&ctx->open_devs_lock);
252 }
253}
254
255static void darwin_clear_iterator (io_iterator_t iter) {
256 io_service_t device;
257
258 while ((device = IOIteratorNext (iter)) != 0)
259 IOObjectRelease (device);
260}
261
262static void *event_thread_main (void *arg0) {
263 IOReturn kresult;
264 struct libusb_context *ctx = (struct libusb_context *)arg0;
265
266 /* hotplug (device removal) source */
267 CFRunLoopSourceRef libusb_notification_cfsource;
268 io_notification_port_t libusb_notification_port;
269 io_iterator_t libusb_rem_device_iterator;
270
271 usbi_info (ctx, "creating hotplug event source");
272
273 CFRetain (CFRunLoopGetCurrent ());
274
275 /* add the notification port to the run loop */
276 libusb_notification_port = IONotificationPortCreate (libusb_darwin_mp);
277 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
278 CFRunLoopAddSource(CFRunLoopGetCurrent (), libusb_notification_cfsource, kCFRunLoopDefaultMode);
279
280 /* create notifications for removed devices */
281 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
282 IOServiceMatching(kIOUSBDeviceClassName),
283 (IOServiceMatchingCallback)darwin_devices_detached,
284 (void *)ctx, &libusb_rem_device_iterator);
285
286 if (kresult != kIOReturnSuccess) {
287 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
288
289 pthread_exit ((void *)kresult);
290 }
291
292 /* arm notifiers */
293 darwin_clear_iterator (libusb_rem_device_iterator);
294
295 /* let the main thread know about the async runloop */
296 libusb_darwin_acfl = CFRunLoopGetCurrent ();
297
298 usbi_info (ctx, "thread ready to receive events");
299
300 /* run the runloop */
301 CFRunLoopRun();
302
303 usbi_info (ctx, "thread exiting");
304
305 /* delete notification port */
306 CFRunLoopSourceInvalidate (libusb_notification_cfsource);
307 IONotificationPortDestroy (libusb_notification_port);
308
309 CFRelease (CFRunLoopGetCurrent ());
310
311 libusb_darwin_acfl = NULL;
312
313 pthread_exit (0);
314}
315
316static int darwin_init(struct libusb_context *ctx) {
317 IOReturn kresult;
318
319 if (!(initCount++)) {
320 /* Create the master port for talking to IOKit */
321 if (!libusb_darwin_mp) {
322 kresult = IOMasterPort (MACH_PORT_NULL, &libusb_darwin_mp);
323
324 if (kresult != kIOReturnSuccess || !libusb_darwin_mp)
325 return darwin_to_libusb (kresult);
326 }
327
328 pthread_create (&libusb_darwin_at, NULL, event_thread_main, (void *)ctx);
329
330 while (!libusb_darwin_acfl)
331 usleep (10);
332 }
333
334 return 0;
335}
336
337static void darwin_exit (void) {
338 if (!(--initCount)) {
339 void *ret;
340
341 /* stop the async runloop */
342 CFRunLoopStop (libusb_darwin_acfl);
343 pthread_join (libusb_darwin_at, &ret);
344
345 if (libusb_darwin_mp)
346 mach_port_deallocate(mach_task_self(), libusb_darwin_mp);
347
348 libusb_darwin_mp = 0;
349 }
350}
351
352static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
353 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
354
355 /* return cached copy */
356 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
357
358 *host_endian = 0;
359
360 return 0;
361}
362
363static int get_configuration_index (struct libusb_device *dev, int config_value) {
364 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
365 UInt8 i, numConfig;
366 IOUSBConfigurationDescriptorPtr desc;
367 IOReturn kresult;
368
369 /* is there a simpler way to determine the index? */
370 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
371 if (kresult != kIOReturnSuccess)
372 return darwin_to_libusb (kresult);
373
374 for (i = 0 ; i < numConfig ; i++) {
375 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
376
377 if (desc->bConfigurationValue == config_value)
378 return i;
379 }
380
381 /* configuration not found */
382 return LIBUSB_ERROR_OTHER;
383}
384
385static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
386 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
387 int config_index;
388
389 if (0 == priv->active_config)
390 return LIBUSB_ERROR_INVALID_PARAM;
391
392 config_index = get_configuration_index (dev, priv->active_config);
393 if (config_index < 0)
394 return config_index;
395
396 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
397}
398
399static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
400 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
401 IOUSBConfigurationDescriptorPtr desc;
402 IOReturn kresult;
403 usb_device_t **device = NULL;
404
405 if (!priv)
406 return LIBUSB_ERROR_OTHER;
407
408 if (!priv->device) {
409 kresult = darwin_get_device (priv->location, &device);
410 if (kresult || !device) {
411 usbi_err (DEVICE_CTX (dev), "could not find device: %s", darwin_error_str (kresult));
412
413 return darwin_to_libusb (kresult);
414 }
415
416 /* don't have to open the device to get a config descriptor */
417 } else
418 device = priv->device;
419
420 kresult = (*device)->GetConfigurationDescriptorPtr (device, config_index, &desc);
421 if (kresult == kIOReturnSuccess) {
422 /* copy descriptor */
423 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
424 len = libusb_le16_to_cpu(desc->wTotalLength);
425
426 memmove (buffer, desc, len);
427
428 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
429 *host_endian = 0;
430 }
431
432 if (!priv->device)
433 (*device)->Release (device);
434
435 return darwin_to_libusb (kresult);
436}
437
438/* check whether the os has configured the device */
439static int darwin_check_configuration (struct libusb_context *ctx, struct libusb_device *dev, usb_device_t **darwin_device) {
440 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
441
442 IOUSBConfigurationDescriptorPtr configDesc;
443 IOUSBFindInterfaceRequest request;
444 kern_return_t kresult;
445 io_iterator_t interface_iterator;
446 io_service_t firstInterface;
447
448 if (priv->dev_descriptor.bNumConfigurations < 1) {
449 usbi_err (ctx, "device has no configurations");
450 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
451 }
452
453 /* find the first configuration */
454 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
455 priv->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
456
457 /* check if the device is already configured. there is probably a better way than iterating over the
458 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
459 might lock up on the device request) */
460
461 /* Setup the Interface Request */
462 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
463 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
464 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
465 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
466
467 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
468 if (kresult)
469 return darwin_to_libusb (kresult);
470
471 /* iterate once */
472 firstInterface = IOIteratorNext(interface_iterator);
473
474 /* done with the interface iterator */
475 IOObjectRelease(interface_iterator);
476
477 if (firstInterface) {
478 IOObjectRelease (firstInterface);
479
480 /* device is configured */
481 if (priv->dev_descriptor.bNumConfigurations == 1)
482 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
483 priv->active_config = priv->first_config;
484 else
485 /* devices with more than one configuration should work with GetConfiguration */
486 (*darwin_device)->GetConfiguration (darwin_device, &priv->active_config);
487 } else
488 /* not configured */
489 priv->active_config = 0;
490
491 usbi_info (ctx, "active config: %u, first config: %u", priv->active_config, priv->first_config);
492
493 return 0;
494}
495
496static int process_new_device (struct libusb_context *ctx, usb_device_t **device, UInt32 locationID, struct discovered_devs **_discdevs) {
497 struct darwin_device_priv *priv;
498 struct libusb_device *dev;
499 struct discovered_devs *discdevs;
500 UInt16 address, idVendor, idProduct;
501 UInt8 bDeviceClass, bDeviceSubClass;
502 IOUSBDevRequest req;
503 int ret = 0, need_unref = 0;
504
505 do {
506 dev = usbi_get_device_by_session_id(ctx, locationID);
507 if (!dev) {
508 usbi_info (ctx, "allocating new device for location 0x%08x", locationID);
509 dev = usbi_alloc_device(ctx, locationID);
510 need_unref = 1;
511 } else
512 usbi_info (ctx, "using existing device for location 0x%08x", locationID);
513
514 if (!dev) {
515 ret = LIBUSB_ERROR_NO_MEM;
516 break;
517 }
518
519 priv = (struct darwin_device_priv *)dev->os_priv;
520
521 /* Set up request for device descriptor */
522 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
523 req.bRequest = kUSBRqGetDescriptor;
524 req.wValue = kUSBDeviceDesc << 8;
525 req.wIndex = 0;
526 req.wLength = sizeof(IOUSBDeviceDescriptor);
527 req.pData = &(priv->dev_descriptor);
528
529 (*(device))->GetDeviceAddress (device, (USBDeviceAddress *)&address);
530 (*(device))->GetDeviceProduct (device, &idProduct);
531 (*(device))->GetDeviceVendor (device, &idVendor);
532 (*(device))->GetDeviceClass (device, &bDeviceClass);
533 (*(device))->GetDeviceSubClass (device, &bDeviceSubClass);
534
535 /**** retrieve device descriptors ****/
536 /* according to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
537 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request */
538 ret = (*(device))->DeviceRequest (device, &req);
539 if (ret != kIOReturnSuccess) {
540 int try_unsuspend = 1;
541#if DeviceVersion >= 320
542 UInt32 info;
543
544 /* device may be suspended. unsuspend it and try again */
545 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
546 (void)(*device)->GetUSBDeviceInformation (device, &info);
547
548 try_unsuspend = info & (1 << kUSBInformationDeviceIsSuspendedBit);
549#endif
550
551 /* the device should be open before to device is unsuspended */
552 (void) (*device)->USBDeviceOpenSeize(device);
553
554 if (try_unsuspend) {
555 /* resume the device */
556 (void)(*device)->USBDeviceSuspend (device, 0);
557
558 ret = (*(device))->DeviceRequest (device, &req);
559
560 /* resuspend the device */
561 (void)(*device)->USBDeviceSuspend (device, 1);
562 }
563
564 (*device)->USBDeviceClose (device);
565 }
566
567 if (ret != kIOReturnSuccess) {
568 usbi_warn (ctx, "could not retrieve device descriptor: %s. skipping device", darwin_error_str (ret));
569 ret = -1;
570 break;
571 }
572
573 /**** end: retrieve device descriptors ****/
574
575 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
576 if (libusb_le16_to_cpu (priv->dev_descriptor.idProduct) != idProduct) {
577 /* not a valid device */
578 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
579 idProduct, libusb_le16_to_cpu (priv->dev_descriptor.idProduct));
580 ret = -1;
581 break;
582 }
583
584 dev->bus_number = locationID >> 24;
585 dev->device_address = address;
586
587 /* check current active configuration (and cache the first configuration value-- which may be used by claim_interface) */
588 ret = darwin_check_configuration (ctx, dev, device);
589 if (ret < 0)
590 break;
591
592 /* save our location, we'll need this later */
593 priv->location = locationID;
594 snprintf(priv->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", address, idVendor, idProduct, bDeviceClass, bDeviceSubClass);
595
596 ret = usbi_sanitize_device (dev);
597 if (ret < 0)
598 break;
599
600 /* append the device to the list of discovered devices */
601 discdevs = discovered_devs_append(*_discdevs, dev);
602 if (!discdevs) {
603 ret = LIBUSB_ERROR_NO_MEM;
604 break;
605 }
606
607 *_discdevs = discdevs;
608
609 usbi_info (ctx, "found device with address %d at %s", dev->device_address, priv->sys_path);
610 } while (0);
611
612 if (need_unref)
613 libusb_unref_device(dev);
614
615 return ret;
616}
617
618static int darwin_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs) {
619 io_iterator_t deviceIterator;
620 usb_device_t **device;
621 kern_return_t kresult;
622 UInt32 location;
623
624 if (!libusb_darwin_mp)
625 return LIBUSB_ERROR_INVALID_PARAM;
626
627 kresult = usb_setup_device_iterator (&deviceIterator);
628 if (kresult != kIOReturnSuccess)
629 return darwin_to_libusb (kresult);
630
631 while ((device = usb_get_next_device (deviceIterator, &location)) != NULL) {
632 (void) process_new_device (ctx, device, location, _discdevs);
633
634 (*(device))->Release(device);
635 }
636
637 IOObjectRelease(deviceIterator);
638
639 return 0;
640}
641
642static int darwin_open (struct libusb_device_handle *dev_handle) {
643 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
644 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
645 usb_device_t **darwin_device;
646 IOReturn kresult;
647
648 if (0 == dpriv->open_count) {
649 kresult = darwin_get_device (dpriv->location, &darwin_device);
650 if (kresult) {
651 usbi_err (HANDLE_CTX (dev_handle), "could not find device: %s", darwin_error_str (kresult));
652 return darwin_to_libusb (kresult);
653 }
654
655 dpriv->device = darwin_device;
656
657 /* try to open the device */
658 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
659
660 if (kresult != kIOReturnSuccess) {
661 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
662
663 switch (kresult) {
664 case kIOReturnExclusiveAccess:
665 /* it is possible to perform some actions on a device that is not open so do not return an error */
666 priv->is_open = 0;
667
668 break;
669 default:
670 (*(dpriv->device))->Release (dpriv->device);
671 dpriv->device = NULL;
672 return darwin_to_libusb (kresult);
673 }
674 } else {
675 priv->is_open = 1;
676
677 /* create async event source */
678 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
679
680 CFRetain (libusb_darwin_acfl);
681
682 /* add the cfSource to the aync run loop */
683 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
684 }
685 }
686
687 /* device opened successfully */
688 dpriv->open_count++;
689
690 /* create a file descriptor for notifications */
691 pipe (priv->fds);
692
693 /* set the pipe to be non-blocking */
694 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
695
696 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
697
698 usbi_info (HANDLE_CTX (dev_handle), "device open for access");
699
700 return 0;
701}
702
703static void darwin_close (struct libusb_device_handle *dev_handle) {
704 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
705 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
706 IOReturn kresult;
707 int i;
708
709 if (dpriv->open_count == 0) {
710 /* something is probably very wrong if this is the case */
711 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!\n");
712 return;
713 }
714
715 dpriv->open_count--;
716
717 /* make sure all interfaces are released */
718 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
719 if (dev_handle->claimed_interfaces & (1 << i))
720 libusb_release_interface (dev_handle, i);
721
722 if (0 == dpriv->open_count) {
723 if (priv->is_open) {
724 /* delete the device's async event source */
725 if (priv->cfSource) {
726 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
727 CFRelease (priv->cfSource);
728 }
729
730 /* close the device */
731 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
732 if (kresult) {
733 /* Log the fact that we had a problem closing the file, however failing a
734 * close isn't really an error, so return success anyway */
735 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
736 }
737 }
738
739 kresult = (*(dpriv->device))->Release(dpriv->device);
740 if (kresult) {
741 /* Log the fact that we had a problem closing the file, however failing a
742 * close isn't really an error, so return success anyway */
743 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
744 }
745
746 dpriv->device = NULL;
747 }
748
749 /* file descriptors are maintained per-instance */
750 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
751 close (priv->fds[1]);
752 close (priv->fds[0]);
753
754 priv->fds[0] = priv->fds[1] = -1;
755}
756
757static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
758 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
759
760 *config = (int) dpriv->active_config;
761
762 return 0;
763}
764
765static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
766 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
767 IOReturn kresult;
768 int i;
769
770 /* Setting configuration will invalidate the interface, so we need
771 to reclaim it. First, dispose of existing interfaces, if any. */
772 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
773 if (dev_handle->claimed_interfaces & (1 << i))
774 darwin_release_interface (dev_handle, i);
775
776 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
777 if (kresult != kIOReturnSuccess)
778 return darwin_to_libusb (kresult);
779
780 /* Reclaim any interfaces. */
781 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
782 if (dev_handle->claimed_interfaces & (1 << i))
783 darwin_claim_interface (dev_handle, i);
784
785 dpriv->active_config = config;
786
787 return 0;
788}
789
790static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
791 IOUSBFindInterfaceRequest request;
792 uint8_t current_interface;
793 kern_return_t kresult;
794 io_iterator_t interface_iterator;
795
796 *usbInterfacep = IO_OBJECT_NULL;
797
798 /* Setup the Interface Request */
799 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
800 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
801 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
802 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
803
804 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
805 if (kresult)
806 return kresult;
807
808 for ( current_interface = 0 ; current_interface <= ifc ; current_interface++ ) {
809 *usbInterfacep = IOIteratorNext(interface_iterator);
810 if (current_interface != ifc)
811 (void) IOObjectRelease (*usbInterfacep);
812 }
813
814 /* done with the interface iterator */
815 IOObjectRelease(interface_iterator);
816
817 return 0;
818}
819
820static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
821 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
822
823 /* current interface */
824 struct __darwin_interface *cInterface = &priv->interfaces[iface];
825
826 kern_return_t kresult;
827
828 u_int8_t numep, direction, number;
829 u_int8_t dont_care1, dont_care3;
830 u_int16_t dont_care2;
831 int i;
832
833 usbi_info (HANDLE_CTX (dev_handle), "building table of endpoints.");
834
835 /* retrieve the total number of endpoints on this interface */
836 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
837 if (kresult) {
838 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
839 return darwin_to_libusb (kresult);
840 }
841
842 /* iterate through pipe references */
843 for (i = 1 ; i <= numep ; i++) {
844 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
845 &dont_care2, &dont_care3);
846
847 if (kresult != kIOReturnSuccess) {
848 usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
849
850 return darwin_to_libusb (kresult);
851 }
852
853 usbi_info (HANDLE_CTX (dev_handle), "interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
854
855 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
856 }
857
858 cInterface->num_endpoints = numep;
859
860 return 0;
861}
862
863static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
864 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
865 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
866 io_service_t usbInterface = IO_OBJECT_NULL;
867 IOReturn kresult;
868 IOCFPlugInInterface **plugInInterface = NULL;
869 SInt32 score;
870
871 /* current interface */
872 struct __darwin_interface *cInterface = &priv->interfaces[iface];
873
874 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
875 if (kresult != kIOReturnSuccess)
876 return darwin_to_libusb (kresult);
877
878 /* make sure we have an interface */
879 if (!usbInterface && dpriv->first_config != 0) {
880 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
881
882 /* set the configuration */
883 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
884 if (kresult != LIBUSB_SUCCESS) {
885 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
886 return kresult;
887 }
888
889 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
890 if (kresult) {
891 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
892 return darwin_to_libusb (kresult);
893 }
894 }
895
896 if (!usbInterface) {
897 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
898 return LIBUSB_ERROR_NOT_FOUND;
899 }
900
901 /* get an interface to the device's interface */
902 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
903 kIOCFPlugInInterfaceID, &plugInInterface, &score);
904 if (kresult) {
905 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
906 return darwin_to_libusb (kresult);
907 }
908
909 if (!plugInInterface) {
910 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
911 return LIBUSB_ERROR_NOT_FOUND;
912 }
913
914 /* ignore release error */
915 (void)IOObjectRelease (usbInterface);
916
917 /* Do the actual claim */
918 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
919 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
920 (LPVOID)&cInterface->interface);
921 if (kresult || !cInterface->interface) {
922 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
923 return darwin_to_libusb (kresult);
924 }
925
926 /* We no longer need the intermediate plug-in */
927 (*plugInInterface)->Release(plugInInterface);
928
929 /* claim the interface */
930 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
931 if (kresult) {
932 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
933 return darwin_to_libusb (kresult);
934 }
935
936 /* update list of endpoints */
937 kresult = get_endpoints (dev_handle, iface);
938 if (kresult) {
939 /* this should not happen */
940 darwin_release_interface (dev_handle, iface);
941 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
942 return kresult;
943 }
944
945 cInterface->cfSource = NULL;
946
947 /* create async event source */
948 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
949 if (kresult != kIOReturnSuccess) {
950 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
951
952 /* can't continue without an async event source */
953 (void)darwin_release_interface (dev_handle, iface);
954
955 return darwin_to_libusb (kresult);
956 }
957
958 /* add the cfSource to the async thread's run loop */
959 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
960
961 usbi_info (HANDLE_CTX (dev_handle), "interface opened");
962
963 return 0;
964}
965
966static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
967 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
968 IOReturn kresult;
969
970 /* current interface */
971 struct __darwin_interface *cInterface = &priv->interfaces[iface];
972
973 /* Check to see if an interface is open */
974 if (!cInterface->interface)
975 return LIBUSB_SUCCESS;
976
977 /* clean up endpoint data */
978 cInterface->num_endpoints = 0;
979
980 /* delete the interface's async event source */
981 if (cInterface->cfSource) {
982 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
983 CFRelease (cInterface->cfSource);
984 }
985
986 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
987 if (kresult)
988 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
989
990 kresult = (*(cInterface->interface))->Release(cInterface->interface);
991 if (kresult != kIOReturnSuccess)
992 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
993
994 cInterface->interface = IO_OBJECT_NULL;
995
996 return darwin_to_libusb (kresult);
997}
998
999static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1000 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1001 IOReturn kresult;
1002
1003 /* current interface */
1004 struct __darwin_interface *cInterface = &priv->interfaces[iface];
1005
1006 if (!cInterface->interface)
1007 return LIBUSB_ERROR_NO_DEVICE;
1008
1009 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1010 if (kresult != kIOReturnSuccess)
1011 darwin_reset_device (dev_handle);
1012
1013 /* update list of endpoints */
1014 kresult = get_endpoints (dev_handle, iface);
1015 if (kresult) {
1016 /* this should not happen */
1017 darwin_release_interface (dev_handle, iface);
1018 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1019 return kresult;
1020 }
1021
1022 return darwin_to_libusb (kresult);
1023}
1024
1025static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1026 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1027
1028 /* current interface */
1029 struct __darwin_interface *cInterface;
1030 uint8_t pipeRef, iface;
1031 IOReturn kresult;
1032
1033 /* determine the interface/endpoint to use */
1034 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
1035 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1036
1037 return LIBUSB_ERROR_NOT_FOUND;
1038 }
1039
1040 cInterface = &priv->interfaces[iface];
1041
1042#if (InterfaceVersion < 190)
1043 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1044#else
1045 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1046 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1047#endif
1048 if (kresult)
1049 usbi_err (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1050
1051 return darwin_to_libusb (kresult);
1052}
1053
1054static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1055 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1056 IOReturn kresult;
1057
1058 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1059 if (kresult)
1060 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1061
1062 return darwin_to_libusb (kresult);
1063}
1064
1065static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1066 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1067 io_service_t usbInterface;
1068 CFTypeRef driver;
1069 IOReturn kresult;
1070
1071 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1072 if (kresult) {
1073 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1074
1075 return darwin_to_libusb (kresult);
1076 }
1077
1078 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1079 IOObjectRelease (usbInterface);
1080
1081 if (driver) {
1082 CFRelease (driver);
1083
1084 return 1;
1085 }
1086
1087 /* no driver */
1088 return 0;
1089}
1090
1091/* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1092static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1093 return LIBUSB_ERROR_NOT_SUPPORTED;
1094}
1095
1096static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1097 return LIBUSB_ERROR_NOT_SUPPORTED;
1098}
1099
1100static void darwin_destroy_device(struct libusb_device *dev) {
1101}
1102
1103static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1104 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1105 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1106
1107 IOReturn ret;
1108 uint8_t is_read; /* 0 = we're reading, 1 = we're writing */
1109 uint8_t transferType;
1110 /* None of the values below are used in libusb for bulk transfers */
1111 uint8_t direction, number, interval, pipeRef, iface;
1112 uint16_t maxPacketSize;
1113
1114 struct __darwin_interface *cInterface;
1115
1116 /* are we reading or writing? */
1117 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1118
1119 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1120 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1121
1122 return LIBUSB_ERROR_NOT_FOUND;
1123 }
1124
1125 cInterface = &priv->interfaces[iface];
1126
1127 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1128 &transferType, &maxPacketSize, &interval);
1129
1130 /* submit the request */
1131 /* timeouts are unavailable on interrupt endpoints */
1132 if (transferType == kUSBInterrupt) {
1133 if (is_read)
1134 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1135 transfer->length, darwin_async_io_callback, itransfer);
1136 else
1137 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1138 transfer->length, darwin_async_io_callback, itransfer);
1139 } else {
1140 if (is_read)
1141 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1142 transfer->length, transfer->timeout, transfer->timeout,
1143 darwin_async_io_callback, (void *)itransfer);
1144 else
1145 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1146 transfer->length, transfer->timeout, transfer->timeout,
1147 darwin_async_io_callback, (void *)itransfer);
1148 }
1149
1150 if (ret)
1151 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", is_read ? "In" : "Out",
1152 darwin_error_str(ret), ret);
1153
1154 return darwin_to_libusb (ret);
1155}
1156
1157static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1158 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1159 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1160 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1161
1162 IOReturn kresult;
1163 uint8_t is_read; /* 0 = we're writing, 1 = we're reading */
1164 uint8_t pipeRef, iface;
1165 UInt64 frame;
1166 AbsoluteTime atTime;
1167 int i;
1168
1169 struct __darwin_interface *cInterface;
1170
1171 /* are we reading or writing? */
1172 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1173
1174 /* construct an array of IOUSBIsocFrames */
1175 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1176 if (!tpriv->isoc_framelist)
1177 return LIBUSB_ERROR_NO_MEM;
1178
1179 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1180 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1181 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1182
1183 /* determine the interface/endpoint to use */
1184 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1185 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1186
1187 return LIBUSB_ERROR_NOT_FOUND;
1188 }
1189
1190 cInterface = &priv->interfaces[iface];
1191
1192 /* Last but not least we need the bus frame number */
1193 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1194 if (kresult) {
1195 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1196 free(tpriv->isoc_framelist);
1197 tpriv->isoc_framelist = NULL;
1198
1199 return darwin_to_libusb (kresult);
1200 }
1201
1202 /* schedule for a frame a little in the future */
1203 frame += 2;
1204
1205 /* submit the request */
1206 if (is_read)
1207 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1208 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1209 itransfer);
1210 else
1211 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1212 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1213 itransfer);
1214
1215 if (kresult != kIOReturnSuccess) {
1216 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", is_read ? "In" : "Out",
1217 darwin_error_str(kresult));
1218 free (tpriv->isoc_framelist);
1219 tpriv->isoc_framelist = NULL;
1220 }
1221
1222 return darwin_to_libusb (kresult);
1223}
1224
1225static int submit_control_transfer(struct usbi_transfer *itransfer) {
1226 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1227 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1228 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1229 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1230
1231 IOReturn kresult;
1232
1233 bzero(&tpriv->req, sizeof(tpriv->req));
1234
1235 /* IOUSBDeviceInterface expects the request in cpu endianess */
1236 tpriv->req.bmRequestType = setup->bmRequestType;
1237 tpriv->req.bRequest = setup->bRequest;
1238 /* these values should be in bus order from libusb_fill_control_setup */
1239 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1240 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1241 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1242 /* data is stored after the libusb control block */
1243 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1244 tpriv->req.completionTimeout = transfer->timeout;
1245 tpriv->req.noDataTimeout = transfer->timeout;
1246
1247 /* all transfers in libusb-1.0 are async */
1248 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1249
1250 if (kresult != kIOReturnSuccess)
1251 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1252
1253 return darwin_to_libusb (kresult);
1254}
1255
1256static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1257 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1258
1259 switch (transfer->type) {
1260 case LIBUSB_TRANSFER_TYPE_CONTROL:
1261 return submit_control_transfer(itransfer);
1262 case LIBUSB_TRANSFER_TYPE_BULK:
1263 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1264 return submit_bulk_transfer(itransfer);
1265 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1266 return submit_iso_transfer(itransfer);
1267 default:
1268 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1269 return LIBUSB_ERROR_INVALID_PARAM;
1270 }
1271}
1272
1273static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1274 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1275 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1276 IOReturn kresult;
1277
1278 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions control pipe");
1279
1280 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1281
1282 return darwin_to_libusb (kresult);
1283}
1284
1285static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1286 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1287 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1288 struct __darwin_interface *cInterface;
1289 uint8_t pipeRef, iface;
1290 IOReturn kresult;
1291
1292 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1293 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1294
1295 return LIBUSB_ERROR_NOT_FOUND;
1296 }
1297
1298 cInterface = &priv->interfaces[iface];
1299
1300 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions on interface %d pipe %d", iface, pipeRef);
1301
1302 /* abort transactions */
1303 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1304
1305 usbi_info (ITRANSFER_CTX (itransfer), "calling clear pipe stall to clear the data toggle bit");
1306
1307 /* clear the data toggle bit */
1308#if (InterfaceVersion < 190)
1309 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1310#else
1311 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1312 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1313#endif
1314
1315 return darwin_to_libusb (kresult);
1316}
1317
1318static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1319 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1320
1321 switch (transfer->type) {
1322 case LIBUSB_TRANSFER_TYPE_CONTROL:
1323 return cancel_control_transfer(itransfer);
1324 case LIBUSB_TRANSFER_TYPE_BULK:
1325 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1326 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1327 return darwin_abort_transfers (itransfer);
1328 default:
1329 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1330 return LIBUSB_ERROR_INVALID_PARAM;
1331 }
1332}
1333
1334static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1335 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1336 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1337
1338 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1339 free (tpriv->isoc_framelist);
1340 tpriv->isoc_framelist = NULL;
1341 }
1342}
1343
1344static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1345 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1346 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1347 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1348 UInt32 message;
1349
1350 usbi_info (ITRANSFER_CTX (itransfer), "an async io operation has completed");
1351
1352 /* send a completion message to the device's file descriptor */
1353 message = MESSAGE_ASYNC_IO_COMPLETE;
1354 write (priv->fds[1], &message, sizeof (message));
1355 write (priv->fds[1], &itransfer, sizeof (itransfer));
1356 write (priv->fds[1], &result, sizeof (IOReturn));
1357 write (priv->fds[1], &arg0, sizeof (UInt32));
1358}
1359
1360static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1361 switch (result) {
1362 case kIOReturnUnderrun:
1363 case kIOReturnSuccess:
1364 return LIBUSB_TRANSFER_COMPLETED;
1365 case kIOReturnAborted:
1366 return LIBUSB_TRANSFER_CANCELLED;
1367 case kIOUSBPipeStalled:
1368 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: pipe is stalled");
1369 return LIBUSB_TRANSFER_STALL;
1370 case kIOReturnOverrun:
1371 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1372 return LIBUSB_TRANSFER_OVERFLOW;
1373 case kIOUSBTransactionTimeout:
1374 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1375 return LIBUSB_TRANSFER_TIMED_OUT;
1376 default:
1377 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1378 return LIBUSB_TRANSFER_ERROR;
1379 }
1380}
1381
1382static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1383 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1384 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1385 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1386 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1387 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1388 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1389 int i;
1390
1391 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1392 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1393 return;
1394 }
1395
1396 usbi_info (ITRANSFER_CTX (itransfer), "handling %s completion with kernel status %d",
1397 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", result);
1398
1399 if (kIOReturnSuccess == result || kIOReturnUnderrun == result) {
1400 if (isIsoc && tpriv->isoc_framelist) {
1401 /* copy isochronous results back */
1402
1403 for (i = 0; i < transfer->num_iso_packets ; i++) {
1404 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1405 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1406 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1407 }
1408 } else if (!isIsoc)
1409 itransfer->transferred += io_size;
1410 }
1411
1412 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1413 usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, result));
1414}
1415
1416static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, nfds_t nfds, int num_ready) {
1417 struct usbi_transfer *itransfer;
1418 UInt32 io_size;
1419 IOReturn kresult;
1420 int i = 0, ret;
1421 UInt32 message;
1422
1423 usbi_mutex_lock(&ctx->open_devs_lock);
1424 for (i = 0; i < nfds && num_ready > 0; i++) {
1425 struct pollfd *pollfd = &fds[i];
1426 struct libusb_device_handle *handle;
1427 struct darwin_device_handle_priv *hpriv = NULL;
1428
1429 usbi_info (ctx, "checking fd %i with revents = %x", fds[i], pollfd->revents);
1430
1431 if (!pollfd->revents)
1432 continue;
1433
1434 num_ready--;
1435 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
1436 hpriv = (struct darwin_device_handle_priv *)handle->os_priv;
1437 if (hpriv->fds[0] == pollfd->fd)
1438 break;
1439 }
1440
1441 if (!(pollfd->revents & POLLERR)) {
1442 ret = read (hpriv->fds[0], &message, sizeof (message));
1443 if (ret < sizeof (message))
1444 continue;
1445 } else
1446 /* could not poll the device-- response is to delete the device (this seems a little heavy-handed) */
1447 message = MESSAGE_DEVICE_GONE;
1448
1449 switch (message) {
1450 case MESSAGE_DEVICE_GONE:
1451 /* remove the device's async port from the runloop */
1452 if (hpriv->cfSource) {
1453 if (libusb_darwin_acfl)
1454 CFRunLoopRemoveSource (libusb_darwin_acfl, hpriv->cfSource, kCFRunLoopDefaultMode);
1455 CFRelease (hpriv->cfSource);
1456 hpriv->cfSource = NULL;
1457 }
1458
1459 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
1460 usbi_handle_disconnect(handle);
1461
1462 /* done with this device */
1463 continue;
1464 case MESSAGE_ASYNC_IO_COMPLETE:
1465 read (hpriv->fds[0], &itransfer, sizeof (itransfer));
1466 read (hpriv->fds[0], &kresult, sizeof (IOReturn));
1467 read (hpriv->fds[0], &io_size, sizeof (UInt32));
1468
1469 darwin_handle_callback (itransfer, kresult, io_size);
1470 break;
1471 default:
1472 usbi_err (ctx, "unknown message received from device pipe");
1473 }
1474 }
1475
1476 usbi_mutex_unlock(&ctx->open_devs_lock);
1477
1478 return 0;
1479}
1480
1481static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1482 mach_timespec_t sys_time;
1483 clock_serv_t clock_ref;
1484
1485 switch (clk_id) {
1486 case USBI_CLOCK_REALTIME:
1487 /* CLOCK_REALTIME represents time since the epoch */
1488 host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &clock_ref);
1489 break;
1490 case USBI_CLOCK_MONOTONIC:
1491 /* use system boot time as reference for the monotonic clock */
1492 host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &clock_ref);
1493 break;
1494 default:
1495 return LIBUSB_ERROR_INVALID_PARAM;
1496 }
1497
1498 clock_get_time (clock_ref, &sys_time);
1499
1500 tp->tv_sec = sys_time.tv_sec;
1501 tp->tv_nsec = sys_time.tv_nsec;
1502
1503 return 0;
1504}
1505
1506const struct usbi_os_backend darwin_backend = {
1507 .name = "Darwin",
1508 .init = darwin_init,
1509 .exit = darwin_exit,
1510 .get_device_list = darwin_get_device_list,
1511 .get_device_descriptor = darwin_get_device_descriptor,
1512 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1513 .get_config_descriptor = darwin_get_config_descriptor,
1514
1515 .open = darwin_open,
1516 .close = darwin_close,
1517 .get_configuration = darwin_get_configuration,
1518 .set_configuration = darwin_set_configuration,
1519 .claim_interface = darwin_claim_interface,
1520 .release_interface = darwin_release_interface,
1521
1522 .set_interface_altsetting = darwin_set_interface_altsetting,
1523 .clear_halt = darwin_clear_halt,
1524 .reset_device = darwin_reset_device,
1525
1526 .kernel_driver_active = darwin_kernel_driver_active,
1527 .detach_kernel_driver = darwin_detach_kernel_driver,
1528 .attach_kernel_driver = darwin_attach_kernel_driver,
1529
1530 .destroy_device = darwin_destroy_device,
1531
1532 .submit_transfer = darwin_submit_transfer,
1533 .cancel_transfer = darwin_cancel_transfer,
1534 .clear_transfer_priv = darwin_clear_transfer_priv,
1535
1536 .handle_events = op_handle_events,
1537
1538 .clock_gettime = darwin_clock_gettime,
1539
1540 .device_priv_size = sizeof(struct darwin_device_priv),
1541 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1542 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1543 .add_iso_packet_size = 0,
1544};
1545
diff --git a/include/libusb-1.0/os/darwin_usb.h b/include/libusb-1.0/os/darwin_usb.h
deleted file mode 100644
index a71d464..0000000
--- a/include/libusb-1.0/os/darwin_usb.h
+++ /dev/null
@@ -1,167 +0,0 @@
1/*
2 * darwin backend for libusb 1.0
3 * Copyright (C) 2008-2009 Nathan Hjelm <hjelmn@users.sourceforge.net>
4 *
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
9 *
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18 */
19
20#if !defined(LIBUSB_DARWIN_H)
21#define LIBUSB_DARWIN_H
22
23#include "libusbi.h"
24
25#include <IOKit/IOTypes.h>
26#include <IOKit/IOCFBundle.h>
27#include <IOKit/usb/IOUSBLib.h>
28#include <IOKit/IOCFPlugIn.h>
29
30/* IOUSBInterfaceInferface */
31#if defined (kIOUSBInterfaceInterfaceID300)
32
33#define usb_interface_t IOUSBInterfaceInterface300
34#define InterfaceInterfaceID kIOUSBInterfaceInterfaceID300
35#define InterfaceVersion 300
36
37#elif defined (kIOUSBInterfaceInterfaceID245)
38
39#define usb_interface_t IOUSBInterfaceInterface245
40#define InterfaceInterfaceID kIOUSBInterfaceInterfaceID245
41#define InterfaceVersion 245
42
43#elif defined (kIOUSBInterfaceInterfaceID220)
44
45#define usb_interface_t IOUSBInterfaceInterface220
46#define InterfaceInterfaceID kIOUSBInterfaceInterfaceID220
47#define InterfaceVersion 220
48
49#elif defined (kIOUSBInterfaceInterfaceID197)
50
51#define usb_interface_t IOUSBInterfaceInterface197
52#define InterfaceInterfaceID kIOUSBInterfaceInterfaceID197
53#define InterfaceVersion 197
54
55#elif defined (kIOUSBInterfaceInterfaceID190)
56
57#define usb_interface_t IOUSBInterfaceInterface190
58#define InterfaceInterfaceID kIOUSBInterfaceInterfaceID190
59#define InterfaceVersion 190
60
61#elif defined (kIOUSBInterfaceInterfaceID182)
62
63#define usb_interface_t IOUSBInterfaceInterface182
64#define InterfaceInterfaceID kIOUSBInterfaceInterfaceID182
65#define InterfaceVersion 182
66
67#else
68
69#error "IOUSBFamily is too old. Please upgrade your OS"
70
71#endif
72
73/* IOUSBDeviceInterface */
74#if defined (kIOUSBDeviceInterfaceID320)
75
76#define usb_device_t IOUSBDeviceInterface320
77#define DeviceInterfaceID kIOUSBDeviceInterfaceID320
78#define DeviceVersion 320
79
80#elif defined (kIOUSBDeviceInterfaceID300)
81
82#define usb_device_t IOUSBDeviceInterface300
83#define DeviceInterfaceID kIOUSBDeviceInterfaceID300
84#define DeviceVersion 300
85
86#elif defined (kIOUSBDeviceInterfaceID245)
87
88#define usb_device_t IOUSBDeviceInterface245
89#define DeviceInterfaceID kIOUSBDeviceInterfaceID245
90#define DeviceVersion 245
91
92#elif defined (kIOUSBDeviceInterfaceID197)
93
94#define usb_device_t IOUSBDeviceInterface197
95#define DeviceInterfaceID kIOUSBDeviceInterfaceID197
96#define DeviceVersion 197
97
98#elif defined (kIOUSBDeviceInterfaceID187)
99
100#define usb_device_t IOUSBDeviceInterface187
101#define DeviceInterfaceID kIOUSBDeviceInterfaceID187
102#define DeviceVersion 187
103
104#elif defined (kIOUSBDeviceInterfaceID182)
105
106#define usb_device_t IOUSBDeviceInterface182
107#define DeviceInterfaceID kIOUSBDeviceInterfaceID182
108#define DeviceVersion 182
109
110#else
111
112#error "IOUSBFamily is too old. Please upgrade your OS"
113
114#endif
115
116#if !defined(IO_OBJECT_NULL)
117#define IO_OBJECT_NULL ((io_object_t) 0)
118#endif
119
120typedef IOCFPlugInInterface *io_cf_plugin_ref_t;
121typedef IONotificationPortRef io_notification_port_t;
122
123/* private structures */
124struct darwin_device_priv {
125 IOUSBDeviceDescriptor dev_descriptor;
126 UInt32 location;
127 char sys_path[21];
128 usb_device_t **device;
129 int open_count;
130 UInt8 first_config, active_config;
131};
132
133struct darwin_device_handle_priv {
134 int is_open;
135 CFRunLoopSourceRef cfSource;
136 int fds[2];
137
138 struct __darwin_interface {
139 usb_interface_t **interface;
140 uint8_t num_endpoints;
141 CFRunLoopSourceRef cfSource;
142 uint8_t endpoint_addrs[USB_MAXENDPOINTS];
143 } interfaces[USB_MAXINTERFACES];
144};
145
146struct darwin_transfer_priv {
147 /* Isoc */
148 IOUSBIsocFrame *isoc_framelist;
149
150 /* Control */
151#if !defined (LIBUSB_NO_TIMEOUT_DEVICE)
152 IOUSBDevRequestTO req;
153#else
154 IOUSBDevRequest req;
155#endif
156
157 /* Bulk */
158};
159
160enum {
161 MESSAGE_DEVICE_GONE,
162 MESSAGE_ASYNC_IO_COMPLETE
163};
164
165
166
167#endif
diff --git a/include/libusb-1.0/os/libusb.h b/include/libusb-1.0/os/libusb.h
deleted file mode 100644
index 8dc3362..0000000
--- a/include/libusb-1.0/os/libusb.h
+++ /dev/null
@@ -1,1322 +0,0 @@
1/*
2 * Public libusb header file
3 * Copyright (C) 2007-2008 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#ifndef __LIBUSB_H__
22#define __LIBUSB_H__
23
24/* MSVC doesn't like inline, but does accept __inline ?? */
25#ifdef _MSC_VER
26#define inline __inline
27#endif
28
29#include <stdint.h>
30#include <sys/types.h>
31#include <time.h>
32#include <limits.h>
33
34#if defined(__linux) || defined(__APPLE__) || defined(__CYGWIN__)
35#include <sys/time.h>
36#endif
37
38/* 'interface' might be defined as a macro on Windows, so we need to
39 * undefine it so as not to break the current libusb API, because
40 * libusb_config_descriptor has an 'interface' member
41 * As this can be problematic if you include windows.h after libusb.h
42 * in your sources, we force windows.h to be included first. */
43#if defined(_WIN32) || defined(__CYGWIN__)
44#include <windows.h>
45#if defined(interface)
46#undef interface
47#endif
48#endif
49
50/** \def LIBUSB_CALL
51 * \ingroup misc
52 * libusb's Windows calling convention.
53 *
54 * Under Windows, the selection of available compilers and configurations
55 * means that, unlike other platforms, there is not <em>one true calling
56 * convention</em> (calling convention: the manner in which parameters are
57 * passed to funcions in the generated assembly code).
58 *
59 * Matching the Windows API itself, libusb uses the WINAPI convention (which
60 * translates to the <tt>stdcall</tt> convention) and guarantees that the
61 * library is compiled in this way. The public header file also includes
62 * appropriate annotations so that your own software will use the right
63 * convention, even if another convention is being used by default within
64 * your codebase.
65 *
66 * The one consideration that you must apply in your software is to mark
67 * all functions which you use as libusb callbacks with this LIBUSB_CALL
68 * annotation, so that they too get compiled for the correct calling
69 * convention.
70 *
71 * On non-Windows operating systems, this macro is defined as nothing. This
72 * means that you can apply it to your code without worrying about
73 * cross-platform compatibility.
74 */
75/* LIBUSB_CALL must be defined on both definition and declaration of libusb
76 * functions. You'd think that declaration would be enough, but cygwin will
77 * complain about conflicting types unless both are marked this way.
78 * The placement of this macro is important too; it must appear after the
79 * return type, before the function name. See internal documentation for
80 * API_EXPORTED.
81 */
82#if defined(_WIN32) || defined(__CYGWIN__)
83#define LIBUSB_CALL WINAPI
84#else
85#define LIBUSB_CALL
86#endif
87
88#ifdef __cplusplus
89extern "C" {
90#endif
91
92/** \def libusb_cpu_to_le16
93 * \ingroup misc
94 * Convert a 16-bit value from host-endian to little-endian format. On
95 * little endian systems, this function does nothing. On big endian systems,
96 * the bytes are swapped.
97 * \param x the host-endian value to convert
98 * \returns the value in little-endian byte order
99 */
100static inline uint16_t libusb_cpu_to_le16(const uint16_t x)
101{
102 union {
103 uint8_t b8[2];
104 uint16_t b16;
105 } _tmp;
106 _tmp.b8[1] = x >> 8;
107 _tmp.b8[0] = x & 0xff;
108 return _tmp.b16;
109}
110
111/** \def libusb_le16_to_cpu
112 * \ingroup misc
113 * Convert a 16-bit value from little-endian to host-endian format. On
114 * little endian systems, this function does nothing. On big endian systems,
115 * the bytes are swapped.
116 * \param x the little-endian value to convert
117 * \returns the value in host-endian byte order
118 */
119#define libusb_le16_to_cpu libusb_cpu_to_le16
120
121/* standard USB stuff */
122
123/** \ingroup desc
124 * Device and/or Interface Class codes */
125enum libusb_class_code {
126 /** In the context of a \ref libusb_device_descriptor "device descriptor",
127 * this bDeviceClass value indicates that each interface specifies its
128 * own class information and all interfaces operate independently.
129 */
130 LIBUSB_CLASS_PER_INTERFACE = 0,
131
132 /** Audio class */
133 LIBUSB_CLASS_AUDIO = 1,
134
135 /** Communications class */
136 LIBUSB_CLASS_COMM = 2,
137
138 /** Human Interface Device class */
139 LIBUSB_CLASS_HID = 3,
140
141 /** Printer dclass */
142 LIBUSB_CLASS_PRINTER = 7,
143
144 /** Picture transfer protocol class */
145 LIBUSB_CLASS_PTP = 6,
146
147 /** Mass storage class */
148 LIBUSB_CLASS_MASS_STORAGE = 8,
149
150 /** Hub class */
151 LIBUSB_CLASS_HUB = 9,
152
153 /** Data class */
154 LIBUSB_CLASS_DATA = 10,
155
156 /** Wireless class */
157 LIBUSB_CLASS_WIRELESS = 0xe0,
158
159 /** Application class */
160 LIBUSB_CLASS_APPLICATION = 0xfe,
161
162 /** Class is vendor-specific */
163 LIBUSB_CLASS_VENDOR_SPEC = 0xff
164};
165
166/** \ingroup desc
167 * Descriptor types as defined by the USB specification. */
168enum libusb_descriptor_type {
169 /** Device descriptor. See libusb_device_descriptor. */
170 LIBUSB_DT_DEVICE = 0x01,
171
172 /** Configuration descriptor. See libusb_config_descriptor. */
173 LIBUSB_DT_CONFIG = 0x02,
174
175 /** String descriptor */
176 LIBUSB_DT_STRING = 0x03,
177
178 /** Interface descriptor. See libusb_interface_descriptor. */
179 LIBUSB_DT_INTERFACE = 0x04,
180
181 /** Endpoint descriptor. See libusb_endpoint_descriptor. */
182 LIBUSB_DT_ENDPOINT = 0x05,
183
184 /** HID descriptor */
185 LIBUSB_DT_HID = 0x21,
186
187 /** HID report descriptor */
188 LIBUSB_DT_REPORT = 0x22,
189
190 /** Physical descriptor */
191 LIBUSB_DT_PHYSICAL = 0x23,
192
193 /** Hub descriptor */
194 LIBUSB_DT_HUB = 0x29
195};
196
197/* Descriptor sizes per descriptor type */
198#define LIBUSB_DT_DEVICE_SIZE 18
199#define LIBUSB_DT_CONFIG_SIZE 9
200#define LIBUSB_DT_INTERFACE_SIZE 9
201#define LIBUSB_DT_ENDPOINT_SIZE 7
202#define LIBUSB_DT_ENDPOINT_AUDIO_SIZE 9 /* Audio extension */
203#define LIBUSB_DT_HUB_NONVAR_SIZE 7
204
205#define LIBUSB_ENDPOINT_ADDRESS_MASK 0x0f /* in bEndpointAddress */
206#define LIBUSB_ENDPOINT_DIR_MASK 0x80
207
208/** \ingroup desc
209 * Endpoint direction. Values for bit 7 of the
210 * \ref libusb_endpoint_descriptor::bEndpointAddress "endpoint address" scheme.
211 */
212enum libusb_endpoint_direction {
213 /** In: device-to-host */
214 LIBUSB_ENDPOINT_IN = 0x80,
215
216 /** Out: host-to-device */
217 LIBUSB_ENDPOINT_OUT = 0x00
218};
219
220#define LIBUSB_TRANSFER_TYPE_MASK 0x03 /* in bmAttributes */
221
222/** \ingroup desc
223 * Endpoint transfer type. Values for bits 0:1 of the
224 * \ref libusb_endpoint_descriptor::bmAttributes "endpoint attributes" field.
225 */
226enum libusb_transfer_type {
227 /** Control endpoint */
228 LIBUSB_TRANSFER_TYPE_CONTROL = 0,
229
230 /** Isochronous endpoint */
231 LIBUSB_TRANSFER_TYPE_ISOCHRONOUS = 1,
232
233 /** Bulk endpoint */
234 LIBUSB_TRANSFER_TYPE_BULK = 2,
235
236 /** Interrupt endpoint */
237 LIBUSB_TRANSFER_TYPE_INTERRUPT = 3
238};
239
240/** \ingroup misc
241 * Standard requests, as defined in table 9-3 of the USB2 specifications */
242enum libusb_standard_request {
243 /** Request status of the specific recipient */
244 LIBUSB_REQUEST_GET_STATUS = 0x00,
245
246 /** Clear or disable a specific feature */
247 LIBUSB_REQUEST_CLEAR_FEATURE = 0x01,
248
249 /* 0x02 is reserved */
250
251 /** Set or enable a specific feature */
252 LIBUSB_REQUEST_SET_FEATURE = 0x03,
253
254 /* 0x04 is reserved */
255
256 /** Set device address for all future accesses */
257 LIBUSB_REQUEST_SET_ADDRESS = 0x05,
258
259 /** Get the specified descriptor */
260 LIBUSB_REQUEST_GET_DESCRIPTOR = 0x06,
261
262 /** Used to update existing descriptors or add new descriptors */
263 LIBUSB_REQUEST_SET_DESCRIPTOR = 0x07,
264
265 /** Get the current device configuration value */
266 LIBUSB_REQUEST_GET_CONFIGURATION = 0x08,
267
268 /** Set device configuration */
269 LIBUSB_REQUEST_SET_CONFIGURATION = 0x09,
270
271 /** Return the selected alternate setting for the specified interface */
272 LIBUSB_REQUEST_GET_INTERFACE = 0x0A,
273
274 /** Select an alternate interface for the specified interface */
275 LIBUSB_REQUEST_SET_INTERFACE = 0x0B,
276
277 /** Set then report an endpoint's synchronization frame */
278 LIBUSB_REQUEST_SYNCH_FRAME = 0x0C
279};
280
281/** \ingroup misc
282 * Request type bits of the
283 * \ref libusb_control_setup::bmRequestType "bmRequestType" field in control
284 * transfers. */
285enum libusb_request_type {
286 /** Standard */
287 LIBUSB_REQUEST_TYPE_STANDARD = (0x00 << 5),
288
289 /** Class */
290 LIBUSB_REQUEST_TYPE_CLASS = (0x01 << 5),
291
292 /** Vendor */
293 LIBUSB_REQUEST_TYPE_VENDOR = (0x02 << 5),
294
295 /** Reserved */
296 LIBUSB_REQUEST_TYPE_RESERVED = (0x03 << 5)
297};
298
299/** \ingroup misc
300 * Recipient bits of the
301 * \ref libusb_control_setup::bmRequestType "bmRequestType" field in control
302 * transfers. Values 4 through 31 are reserved. */
303enum libusb_request_recipient {
304 /** Device */
305 LIBUSB_RECIPIENT_DEVICE = 0x00,
306
307 /** Interface */
308 LIBUSB_RECIPIENT_INTERFACE = 0x01,
309
310 /** Endpoint */
311 LIBUSB_RECIPIENT_ENDPOINT = 0x02,
312
313 /** Other */
314 LIBUSB_RECIPIENT_OTHER = 0x03
315};
316
317#define LIBUSB_ISO_SYNC_TYPE_MASK 0x0C
318
319/** \ingroup desc
320 * Synchronization type for isochronous endpoints. Values for bits 2:3 of the
321 * \ref libusb_endpoint_descriptor::bmAttributes "bmAttributes" field in
322 * libusb_endpoint_descriptor.
323 */
324enum libusb_iso_sync_type {
325 /** No synchronization */
326 LIBUSB_ISO_SYNC_TYPE_NONE = 0,
327
328 /** Asynchronous */
329 LIBUSB_ISO_SYNC_TYPE_ASYNC = 1,
330
331 /** Adaptive */
332 LIBUSB_ISO_SYNC_TYPE_ADAPTIVE = 2,
333
334 /** Synchronous */
335 LIBUSB_ISO_SYNC_TYPE_SYNC = 3
336};
337
338#define LIBUSB_ISO_USAGE_TYPE_MASK 0x30
339
340/** \ingroup desc
341 * Usage type for isochronous endpoints. Values for bits 4:5 of the
342 * \ref libusb_endpoint_descriptor::bmAttributes "bmAttributes" field in
343 * libusb_endpoint_descriptor.
344 */
345enum libusb_iso_usage_type {
346 /** Data endpoint */
347 LIBUSB_ISO_USAGE_TYPE_DATA = 0,
348
349 /** Feedback endpoint */
350 LIBUSB_ISO_USAGE_TYPE_FEEDBACK = 1,
351
352 /** Implicit feedback Data endpoint */
353 LIBUSB_ISO_USAGE_TYPE_IMPLICIT = 2
354};
355
356/** \ingroup desc
357 * A structure representing the standard USB device descriptor. This
358 * descriptor is documented in section 9.6.1 of the USB 2.0 specification.
359 * All multiple-byte fields are represented in host-endian format.
360 */
361struct libusb_device_descriptor {
362 /** Size of this descriptor (in bytes) */
363 uint8_t bLength;
364
365 /** Descriptor type. Will have value
366 * \ref libusb_descriptor_type::LIBUSB_DT_DEVICE LIBUSB_DT_DEVICE in this
367 * context. */
368 uint8_t bDescriptorType;
369
370 /** USB specification release number in binary-coded decimal. A value of
371 * 0x0200 indicates USB 2.0, 0x0110 indicates USB 1.1, etc. */
372 uint16_t bcdUSB;
373
374 /** USB-IF class code for the device. See \ref libusb_class_code. */
375 uint8_t bDeviceClass;
376
377 /** USB-IF subclass code for the device, qualified by the bDeviceClass
378 * value */
379 uint8_t bDeviceSubClass;
380
381 /** USB-IF protocol code for the device, qualified by the bDeviceClass and
382 * bDeviceSubClass values */
383 uint8_t bDeviceProtocol;
384
385 /** Maximum packet size for endpoint 0 */
386 uint8_t bMaxPacketSize0;
387
388 /** USB-IF vendor ID */
389 uint16_t idVendor;
390
391 /** USB-IF product ID */
392 uint16_t idProduct;
393
394 /** Device release number in binary-coded decimal */
395 uint16_t bcdDevice;
396
397 /** Index of string descriptor describing manufacturer */
398 uint8_t iManufacturer;
399
400 /** Index of string descriptor describing product */
401 uint8_t iProduct;
402
403 /** Index of string descriptor containing device serial number */
404 uint8_t iSerialNumber;
405
406 /** Number of possible configurations */
407 uint8_t bNumConfigurations;
408};
409
410/** \ingroup desc
411 * A structure representing the standard USB endpoint descriptor. This
412 * descriptor is documented in section 9.6.3 of the USB 2.0 specification.
413 * All multiple-byte fields are represented in host-endian format.
414 */
415struct libusb_endpoint_descriptor {
416 /** Size of this descriptor (in bytes) */
417 uint8_t bLength;
418
419 /** Descriptor type. Will have value
420 * \ref libusb_descriptor_type::LIBUSB_DT_ENDPOINT LIBUSB_DT_ENDPOINT in
421 * this context. */
422 uint8_t bDescriptorType;
423
424 /** The address of the endpoint described by this descriptor. Bits 0:3 are
425 * the endpoint number. Bits 4:6 are reserved. Bit 7 indicates direction,
426 * see \ref libusb_endpoint_direction.
427 */
428 uint8_t bEndpointAddress;
429
430 /** Attributes which apply to the endpoint when it is configured using
431 * the bConfigurationValue. Bits 0:1 determine the transfer type and
432 * correspond to \ref libusb_transfer_type. Bits 2:3 are only used for
433 * isochronous endpoints and correspond to \ref libusb_iso_sync_type.
434 * Bits 4:5 are also only used for isochronous endpoints and correspond to
435 * \ref libusb_iso_usage_type. Bits 6:7 are reserved.
436 */
437 uint8_t bmAttributes;
438
439 /** Maximum packet size this endpoint is capable of sending/receiving. */
440 uint16_t wMaxPacketSize;
441
442 /** Interval for polling endpoint for data transfers. */
443 uint8_t bInterval;
444
445 /** For audio devices only: the rate at which synchronization feedback
446 * is provided. */
447 uint8_t bRefresh;
448
449 /** For audio devices only: the address if the synch endpoint */
450 uint8_t bSynchAddress;
451
452 /** Extra descriptors. If libusb encounters unknown endpoint descriptors,
453 * it will store them here, should you wish to parse them. */
454 const unsigned char *extra;
455
456 /** Length of the extra descriptors, in bytes. */
457 int extra_length;
458};
459
460/** \ingroup desc
461 * A structure representing the standard USB interface descriptor. This
462 * descriptor is documented in section 9.6.5 of the USB 2.0 specification.
463 * All multiple-byte fields are represented in host-endian format.
464 */
465struct libusb_interface_descriptor {
466 /** Size of this descriptor (in bytes) */
467 uint8_t bLength;
468
469 /** Descriptor type. Will have value
470 * \ref libusb_descriptor_type::LIBUSB_DT_INTERFACE LIBUSB_DT_INTERFACE
471 * in this context. */
472 uint8_t bDescriptorType;
473
474 /** Number of this interface */
475 uint8_t bInterfaceNumber;
476
477 /** Value used to select this alternate setting for this interface */
478 uint8_t bAlternateSetting;
479
480 /** Number of endpoints used by this interface (excluding the control
481 * endpoint). */
482 uint8_t bNumEndpoints;
483
484 /** USB-IF class code for this interface. See \ref libusb_class_code. */
485 uint8_t bInterfaceClass;
486
487 /** USB-IF subclass code for this interface, qualified by the
488 * bInterfaceClass value */
489 uint8_t bInterfaceSubClass;
490
491 /** USB-IF protocol code for this interface, qualified by the
492 * bInterfaceClass and bInterfaceSubClass values */
493 uint8_t bInterfaceProtocol;
494
495 /** Index of string descriptor describing this interface */
496 uint8_t iInterface;
497
498 /** Array of endpoint descriptors. This length of this array is determined
499 * by the bNumEndpoints field. */
500 const struct libusb_endpoint_descriptor *endpoint;
501
502 /** Extra descriptors. If libusb encounters unknown interface descriptors,
503 * it will store them here, should you wish to parse them. */
504 const unsigned char *extra;
505
506 /** Length of the extra descriptors, in bytes. */
507 int extra_length;
508};
509
510/** \ingroup desc
511 * A collection of alternate settings for a particular USB interface.
512 */
513struct libusb_interface {
514 /** Array of interface descriptors. The length of this array is determined
515 * by the num_altsetting field. */
516 const struct libusb_interface_descriptor *altsetting;
517
518 /** The number of alternate settings that belong to this interface */
519 int num_altsetting;
520};
521
522/** \ingroup desc
523 * A structure representing the standard USB configuration descriptor. This
524 * descriptor is documented in section 9.6.3 of the USB 2.0 specification.
525 * All multiple-byte fields are represented in host-endian format.
526 */
527struct libusb_config_descriptor {
528 /** Size of this descriptor (in bytes) */
529 uint8_t bLength;
530
531 /** Descriptor type. Will have value
532 * \ref libusb_descriptor_type::LIBUSB_DT_CONFIG LIBUSB_DT_CONFIG
533 * in this context. */
534 uint8_t bDescriptorType;
535
536 /** Total length of data returned for this configuration */
537 uint16_t wTotalLength;
538
539 /** Number of interfaces supported by this configuration */
540 uint8_t bNumInterfaces;
541
542 /** Identifier value for this configuration */
543 uint8_t bConfigurationValue;
544
545 /** Index of string descriptor describing this configuration */
546 uint8_t iConfiguration;
547
548 /** Configuration characteristics */
549 uint8_t bmAttributes;
550
551 /** Maximum power consumption of the USB device from this bus in this
552 * configuration when the device is fully opreation. Expressed in units
553 * of 2 mA. */
554 uint8_t MaxPower;
555
556 /** Array of interfaces supported by this configuration. The length of
557 * this array is determined by the bNumInterfaces field. */
558 const struct libusb_interface *interface;
559
560 /** Extra descriptors. If libusb encounters unknown configuration
561 * descriptors, it will store them here, should you wish to parse them. */
562 const unsigned char *extra;
563
564 /** Length of the extra descriptors, in bytes. */
565 int extra_length;
566};
567
568/** \ingroup asyncio
569 * Setup packet for control transfers. */
570struct libusb_control_setup {
571 /** Request type. Bits 0:4 determine recipient, see
572 * \ref libusb_request_recipient. Bits 5:6 determine type, see
573 * \ref libusb_request_type. Bit 7 determines data transfer direction, see
574 * \ref libusb_endpoint_direction.
575 */
576 uint8_t bmRequestType;
577
578 /** Request. If the type bits of bmRequestType are equal to
579 * \ref libusb_request_type::LIBUSB_REQUEST_TYPE_STANDARD
580 * "LIBUSB_REQUEST_TYPE_STANDARD" then this field refers to
581 * \ref libusb_standard_request. For other cases, use of this field is
582 * application-specific. */
583 uint8_t bRequest;
584
585 /** Value. Varies according to request */
586 uint16_t wValue;
587
588 /** Index. Varies according to request, typically used to pass an index
589 * or offset */
590 uint16_t wIndex;
591
592 /** Number of bytes to transfer */
593 uint16_t wLength;
594};
595
596#define LIBUSB_CONTROL_SETUP_SIZE (sizeof(struct libusb_control_setup))
597
598/* libusb */
599
600struct libusb_context;
601struct libusb_device;
602struct libusb_device_handle;
603
604/** \ingroup lib
605 * Structure representing a libusb session. The concept of individual libusb
606 * sessions allows for your program to use two libraries (or dynamically
607 * load two modules) which both independently use libusb. This will prevent
608 * interference between the individual libusb users - for example
609 * libusb_set_debug() will not affect the other user of the library, and
610 * libusb_exit() will not destroy resources that the other user is still
611 * using.
612 *
613 * Sessions are created by libusb_init() and destroyed through libusb_exit().
614 * If your application is guaranteed to only ever include a single libusb
615 * user (i.e. you), you do not have to worry about contexts: pass NULL in
616 * every function call where a context is required. The default context
617 * will be used.
618 *
619 * For more information, see \ref contexts.
620 */
621typedef struct libusb_context libusb_context;
622
623/** \ingroup dev
624 * Structure representing a USB device detected on the system. This is an
625 * opaque type for which you are only ever provided with a pointer, usually
626 * originating from libusb_get_device_list().
627 *
628 * Certain operations can be performed on a device, but in order to do any
629 * I/O you will have to first obtain a device handle using libusb_open().
630 *
631 * Devices are reference counted with libusb_device_ref() and
632 * libusb_device_unref(), and are freed when the reference count reaches 0.
633 * New devices presented by libusb_get_device_list() have a reference count of
634 * 1, and libusb_free_device_list() can optionally decrease the reference count
635 * on all devices in the list. libusb_open() adds another reference which is
636 * later destroyed by libusb_close().
637 */
638typedef struct libusb_device libusb_device;
639
640
641/** \ingroup dev
642 * Structure representing a handle on a USB device. This is an opaque type for
643 * which you are only ever provided with a pointer, usually originating from
644 * libusb_open().
645 *
646 * A device handle is used to perform I/O and other operations. When finished
647 * with a device handle, you should call libusb_close().
648 */
649typedef struct libusb_device_handle libusb_device_handle;
650
651/** \ingroup misc
652 * Error codes. Most libusb functions return 0 on success or one of these
653 * codes on failure.
654 * You can use libusb_strerror() to retrieve a short string description of
655 * a libusb_error enumeration value.
656 */
657enum libusb_error {
658 /** Success (no error) */
659 LIBUSB_SUCCESS = 0,
660
661 /** Input/output error */
662 LIBUSB_ERROR_IO = -1,
663
664 /** Invalid parameter */
665 LIBUSB_ERROR_INVALID_PARAM = -2,
666
667 /** Access denied (insufficient permissions) */
668 LIBUSB_ERROR_ACCESS = -3,
669
670 /** No such device (it may have been disconnected) */
671 LIBUSB_ERROR_NO_DEVICE = -4,
672
673 /** Entity not found */
674 LIBUSB_ERROR_NOT_FOUND = -5,
675
676 /** Resource busy */
677 LIBUSB_ERROR_BUSY = -6,
678
679 /** Operation timed out */
680 LIBUSB_ERROR_TIMEOUT = -7,
681
682 /** Overflow */
683 LIBUSB_ERROR_OVERFLOW = -8,
684
685 /** Pipe error */
686 LIBUSB_ERROR_PIPE = -9,
687
688 /** System call interrupted (perhaps due to signal) */
689 LIBUSB_ERROR_INTERRUPTED = -10,
690
691 /** Insufficient memory */
692 LIBUSB_ERROR_NO_MEM = -11,
693
694 /** Operation not supported or unimplemented on this platform */
695 LIBUSB_ERROR_NOT_SUPPORTED = -12,
696
697 /** Other error */
698 LIBUSB_ERROR_OTHER = -99
699
700 /* IMPORTANT: when adding new values to this enum, remember to
701 update the libusb_strerror() function implementation! */
702};
703
704/** \ingroup asyncio
705 * Transfer status codes */
706enum libusb_transfer_status {
707 /** Transfer completed without error. Note that this does not indicate
708 * that the entire amount of requested data was transferred. */
709 LIBUSB_TRANSFER_COMPLETED,
710
711 /** Transfer failed */
712 LIBUSB_TRANSFER_ERROR,
713
714 /** Transfer timed out */
715 LIBUSB_TRANSFER_TIMED_OUT,
716
717 /** Transfer was cancelled */
718 LIBUSB_TRANSFER_CANCELLED,
719
720 /** For bulk/interrupt endpoints: halt condition detected (endpoint
721 * stalled). For control endpoints: control request not supported. */
722 LIBUSB_TRANSFER_STALL,
723
724 /** Device was disconnected */
725 LIBUSB_TRANSFER_NO_DEVICE,
726
727 /** Device sent more data than requested */
728 LIBUSB_TRANSFER_OVERFLOW
729};
730
731/** \ingroup asyncio
732 * libusb_transfer.flags values */
733enum libusb_transfer_flags {
734 /** Report short frames as errors */
735 LIBUSB_TRANSFER_SHORT_NOT_OK = 1<<0,
736
737 /** Automatically free() transfer buffer during libusb_free_transfer() */
738 LIBUSB_TRANSFER_FREE_BUFFER = 1<<1,
739
740 /** Automatically call libusb_free_transfer() after callback returns.
741 * If this flag is set, it is illegal to call libusb_free_transfer()
742 * from your transfer callback, as this will result in a double-free
743 * when this flag is acted upon. */
744 LIBUSB_TRANSFER_FREE_TRANSFER = 1<<2
745};
746
747/** \ingroup asyncio
748 * Isochronous packet descriptor. */
749struct libusb_iso_packet_descriptor {
750 /** Length of data to request in this packet */
751 unsigned int length;
752
753 /** Amount of data that was actually transferred */
754 unsigned int actual_length;
755
756 /** Status code for this packet */
757 enum libusb_transfer_status status;
758};
759
760struct libusb_transfer;
761
762/** \ingroup asyncio
763 * Asynchronous transfer callback function type. When submitting asynchronous
764 * transfers, you pass a pointer to a callback function of this type via the
765 * \ref libusb_transfer::callback "callback" member of the libusb_transfer
766 * structure. libusb will call this function later, when the transfer has
767 * completed or failed. See \ref asyncio for more information.
768 * \param transfer The libusb_transfer struct the callback function is being
769 * notified about.
770 */
771typedef void (LIBUSB_CALL *libusb_transfer_cb_fn)(struct libusb_transfer *transfer);
772
773/** \ingroup asyncio
774 * The generic USB transfer structure. The user populates this structure and
775 * then submits it in order to request a transfer. After the transfer has
776 * completed, the library populates the transfer with the results and passes
777 * it back to the user.
778 */
779struct libusb_transfer {
780 /** Handle of the device that this transfer will be submitted to */
781 libusb_device_handle *dev_handle;
782
783 /** A bitwise OR combination of \ref libusb_transfer_flags. */
784 uint8_t flags;
785
786 /** Address of the endpoint where this transfer will be sent. */
787 unsigned char endpoint;
788
789 /** Type of the endpoint from \ref libusb_transfer_type */
790 unsigned char type;
791
792 /** Timeout for this transfer in millseconds. A value of 0 indicates no
793 * timeout. */
794 unsigned int timeout;
795
796 /** The status of the transfer. Read-only, and only for use within
797 * transfer callback function.
798 *
799 * If this is an isochronous transfer, this field may read COMPLETED even
800 * if there were errors in the frames. Use the
801 * \ref libusb_iso_packet_descriptor::status "status" field in each packet
802 * to determine if errors occurred. */
803 enum libusb_transfer_status status;
804
805 /** Length of the data buffer */
806 int length;
807
808 /** Actual length of data that was transferred. Read-only, and only for
809 * use within transfer callback function. Not valid for isochronous
810 * endpoint transfers. */
811 int actual_length;
812
813 /** Callback function. This will be invoked when the transfer completes,
814 * fails, or is cancelled. */
815 libusb_transfer_cb_fn callback;
816
817 /** User context data to pass to the callback function. */
818 void *user_data;
819
820 /** Data buffer */
821 unsigned char *buffer;
822
823 /** Number of isochronous packets. Only used for I/O with isochronous
824 * endpoints. */
825 int num_iso_packets;
826
827 /** Isochronous packet descriptors, for isochronous transfers only. */
828 struct libusb_iso_packet_descriptor iso_packet_desc
829#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
830 [] /* valid C99 code */
831#else
832 [0] /* non-standard, but usually working code */
833#endif
834 ;
835};
836
837int LIBUSB_CALL libusb_init(libusb_context **ctx);
838void LIBUSB_CALL libusb_exit(libusb_context *ctx);
839void LIBUSB_CALL libusb_set_debug(libusb_context *ctx, int level);
840const char * LIBUSB_CALL libusb_strerror(enum libusb_error errcode);
841
842ssize_t LIBUSB_CALL libusb_get_device_list(libusb_context *ctx,
843 libusb_device ***list);
844void LIBUSB_CALL libusb_free_device_list(libusb_device **list,
845 int unref_devices);
846libusb_device * LIBUSB_CALL libusb_ref_device(libusb_device *dev);
847void LIBUSB_CALL libusb_unref_device(libusb_device *dev);
848
849int LIBUSB_CALL libusb_get_configuration(libusb_device_handle *dev,
850 int *config);
851int LIBUSB_CALL libusb_get_device_descriptor(libusb_device *dev,
852 struct libusb_device_descriptor *desc);
853int LIBUSB_CALL libusb_get_active_config_descriptor(libusb_device *dev,
854 struct libusb_config_descriptor **config);
855int LIBUSB_CALL libusb_get_config_descriptor(libusb_device *dev,
856 uint8_t config_index, struct libusb_config_descriptor **config);
857int LIBUSB_CALL libusb_get_config_descriptor_by_value(libusb_device *dev,
858 uint8_t bConfigurationValue, struct libusb_config_descriptor **config);
859void LIBUSB_CALL libusb_free_config_descriptor(
860 struct libusb_config_descriptor *config);
861uint8_t LIBUSB_CALL libusb_get_bus_number(libusb_device *dev);
862uint8_t LIBUSB_CALL libusb_get_device_address(libusb_device *dev);
863int LIBUSB_CALL libusb_get_max_packet_size(libusb_device *dev,
864 unsigned char endpoint);
865int LIBUSB_CALL libusb_get_max_iso_packet_size(libusb_device *dev,
866 unsigned char endpoint);
867
868int LIBUSB_CALL libusb_open(libusb_device *dev, libusb_device_handle **handle);
869void LIBUSB_CALL libusb_close(libusb_device_handle *dev_handle);
870libusb_device * LIBUSB_CALL libusb_get_device(libusb_device_handle *dev_handle);
871
872int LIBUSB_CALL libusb_set_configuration(libusb_device_handle *dev,
873 int configuration);
874int LIBUSB_CALL libusb_claim_interface(libusb_device_handle *dev,
875 int interface_number);
876int LIBUSB_CALL libusb_release_interface(libusb_device_handle *dev,
877 int interface_number);
878
879libusb_device_handle * LIBUSB_CALL libusb_open_device_with_vid_pid(
880 libusb_context *ctx, uint16_t vendor_id, uint16_t product_id);
881
882int LIBUSB_CALL libusb_set_interface_alt_setting(libusb_device_handle *dev,
883 int interface_number, int alternate_setting);
884int LIBUSB_CALL libusb_clear_halt(libusb_device_handle *dev,
885 unsigned char endpoint);
886int LIBUSB_CALL libusb_reset_device(libusb_device_handle *dev);
887
888int LIBUSB_CALL libusb_kernel_driver_active(libusb_device_handle *dev,
889 int interface_number);
890int LIBUSB_CALL libusb_detach_kernel_driver(libusb_device_handle *dev,
891 int interface_number);
892int LIBUSB_CALL libusb_attach_kernel_driver(libusb_device_handle *dev,
893 int interface_number);
894
895/* async I/O */
896
897/** \ingroup asyncio
898 * Get the data section of a control transfer. This convenience function is here
899 * to remind you that the data does not start until 8 bytes into the actual
900 * buffer, as the setup packet comes first.
901 *
902 * Calling this function only makes sense from a transfer callback function,
903 * or situations where you have already allocated a suitably sized buffer at
904 * transfer->buffer.
905 *
906 * \param transfer a transfer
907 * \returns pointer to the first byte of the data section
908 */
909static inline unsigned char *libusb_control_transfer_get_data(
910 struct libusb_transfer *transfer)
911{
912 return transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
913}
914
915/** \ingroup asyncio
916 * Get the control setup packet of a control transfer. This convenience
917 * function is here to remind you that the control setup occupies the first
918 * 8 bytes of the transfer data buffer.
919 *
920 * Calling this function only makes sense from a transfer callback function,
921 * or situations where you have already allocated a suitably sized buffer at
922 * transfer->buffer.
923 *
924 * \param transfer a transfer
925 * \returns a casted pointer to the start of the transfer data buffer
926 */
927static inline struct libusb_control_setup *libusb_control_transfer_get_setup(
928 struct libusb_transfer *transfer)
929{
930 return (struct libusb_control_setup *) transfer->buffer;
931}
932
933/** \ingroup asyncio
934 * Helper function to populate the setup packet (first 8 bytes of the data
935 * buffer) for a control transfer. The wIndex, wValue and wLength values should
936 * be given in host-endian byte order.
937 *
938 * \param buffer buffer to output the setup packet into
939 * \param bmRequestType see the
940 * \ref libusb_control_setup::bmRequestType "bmRequestType" field of
941 * \ref libusb_control_setup
942 * \param bRequest see the
943 * \ref libusb_control_setup::bRequest "bRequest" field of
944 * \ref libusb_control_setup
945 * \param wValue see the
946 * \ref libusb_control_setup::wValue "wValue" field of
947 * \ref libusb_control_setup
948 * \param wIndex see the
949 * \ref libusb_control_setup::wIndex "wIndex" field of
950 * \ref libusb_control_setup
951 * \param wLength see the
952 * \ref libusb_control_setup::wLength "wLength" field of
953 * \ref libusb_control_setup
954 */
955static inline void libusb_fill_control_setup(unsigned char *buffer,
956 uint8_t bmRequestType, uint8_t bRequest, uint16_t wValue, uint16_t wIndex,
957 uint16_t wLength)
958{
959 struct libusb_control_setup *setup = (struct libusb_control_setup *) buffer;
960 setup->bmRequestType = bmRequestType;
961 setup->bRequest = bRequest;
962 setup->wValue = libusb_cpu_to_le16(wValue);
963 setup->wIndex = libusb_cpu_to_le16(wIndex);
964 setup->wLength = libusb_cpu_to_le16(wLength);
965}
966
967struct libusb_transfer * LIBUSB_CALL libusb_alloc_transfer(int iso_packets);
968int LIBUSB_CALL libusb_submit_transfer(struct libusb_transfer *transfer);
969int LIBUSB_CALL libusb_cancel_transfer(struct libusb_transfer *transfer);
970void LIBUSB_CALL libusb_free_transfer(struct libusb_transfer *transfer);
971
972/** \ingroup asyncio
973 * Helper function to populate the required \ref libusb_transfer fields
974 * for a control transfer.
975 *
976 * If you pass a transfer buffer to this function, the first 8 bytes will
977 * be interpreted as a control setup packet, and the wLength field will be
978 * used to automatically populate the \ref libusb_transfer::length "length"
979 * field of the transfer. Therefore the recommended approach is:
980 * -# Allocate a suitably sized data buffer (including space for control setup)
981 * -# Call libusb_fill_control_setup()
982 * -# If this is a host-to-device transfer with a data stage, put the data
983 * in place after the setup packet
984 * -# Call this function
985 * -# Call libusb_submit_transfer()
986 *
987 * It is also legal to pass a NULL buffer to this function, in which case this
988 * function will not attempt to populate the length field. Remember that you
989 * must then populate the buffer and length fields later.
990 *
991 * \param transfer the transfer to populate
992 * \param dev_handle handle of the device that will handle the transfer
993 * \param buffer data buffer. If provided, this function will interpret the
994 * first 8 bytes as a setup packet and infer the transfer length from that.
995 * \param callback callback function to be invoked on transfer completion
996 * \param user_data user data to pass to callback function
997 * \param timeout timeout for the transfer in milliseconds
998 */
999static inline void libusb_fill_control_transfer(
1000 struct libusb_transfer *transfer, libusb_device_handle *dev_handle,
1001 unsigned char *buffer, libusb_transfer_cb_fn callback, void *user_data,
1002 unsigned int timeout)
1003{
1004 struct libusb_control_setup *setup = (struct libusb_control_setup *) buffer;
1005 transfer->dev_handle = dev_handle;
1006 transfer->endpoint = 0;
1007 transfer->type = LIBUSB_TRANSFER_TYPE_CONTROL;
1008 transfer->timeout = timeout;
1009 transfer->buffer = buffer;
1010 if (setup)
1011 transfer->length = LIBUSB_CONTROL_SETUP_SIZE
1012 + libusb_le16_to_cpu(setup->wLength);
1013 transfer->user_data = user_data;
1014 transfer->callback = callback;
1015}
1016
1017/** \ingroup asyncio
1018 * Helper function to populate the required \ref libusb_transfer fields
1019 * for a bulk transfer.
1020 *
1021 * \param transfer the transfer to populate
1022 * \param dev_handle handle of the device that will handle the transfer
1023 * \param endpoint address of the endpoint where this transfer will be sent
1024 * \param buffer data buffer
1025 * \param length length of data buffer
1026 * \param callback callback function to be invoked on transfer completion
1027 * \param user_data user data to pass to callback function
1028 * \param timeout timeout for the transfer in milliseconds
1029 */
1030static inline void libusb_fill_bulk_transfer(struct libusb_transfer *transfer,
1031 libusb_device_handle *dev_handle, unsigned char endpoint,
1032 unsigned char *buffer, int length, libusb_transfer_cb_fn callback,
1033 void *user_data, unsigned int timeout)
1034{
1035 transfer->dev_handle = dev_handle;
1036 transfer->endpoint = endpoint;
1037 transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
1038 transfer->timeout = timeout;
1039 transfer->buffer = buffer;
1040 transfer->length = length;
1041 transfer->user_data = user_data;
1042 transfer->callback = callback;
1043}
1044
1045/** \ingroup asyncio
1046 * Helper function to populate the required \ref libusb_transfer fields
1047 * for an interrupt transfer.
1048 *
1049 * \param transfer the transfer to populate
1050 * \param dev_handle handle of the device that will handle the transfer
1051 * \param endpoint address of the endpoint where this transfer will be sent
1052 * \param buffer data buffer
1053 * \param length length of data buffer
1054 * \param callback callback function to be invoked on transfer completion
1055 * \param user_data user data to pass to callback function
1056 * \param timeout timeout for the transfer in milliseconds
1057 */
1058static inline void libusb_fill_interrupt_transfer(
1059 struct libusb_transfer *transfer, libusb_device_handle *dev_handle,
1060 unsigned char endpoint, unsigned char *buffer, int length,
1061 libusb_transfer_cb_fn callback, void *user_data, unsigned int timeout)
1062{
1063 transfer->dev_handle = dev_handle;
1064 transfer->endpoint = endpoint;
1065 transfer->type = LIBUSB_TRANSFER_TYPE_INTERRUPT;
1066 transfer->timeout = timeout;
1067 transfer->buffer = buffer;
1068 transfer->length = length;
1069 transfer->user_data = user_data;
1070 transfer->callback = callback;
1071}
1072
1073/** \ingroup asyncio
1074 * Helper function to populate the required \ref libusb_transfer fields
1075 * for an isochronous transfer.
1076 *
1077 * \param transfer the transfer to populate
1078 * \param dev_handle handle of the device that will handle the transfer
1079 * \param endpoint address of the endpoint where this transfer will be sent
1080 * \param buffer data buffer
1081 * \param length length of data buffer
1082 * \param num_iso_packets the number of isochronous packets
1083 * \param callback callback function to be invoked on transfer completion
1084 * \param user_data user data to pass to callback function
1085 * \param timeout timeout for the transfer in milliseconds
1086 */
1087static inline void libusb_fill_iso_transfer(struct libusb_transfer *transfer,
1088 libusb_device_handle *dev_handle, unsigned char endpoint,
1089 unsigned char *buffer, int length, int num_iso_packets,
1090 libusb_transfer_cb_fn callback, void *user_data, unsigned int timeout)
1091{
1092 transfer->dev_handle = dev_handle;
1093 transfer->endpoint = endpoint;
1094 transfer->type = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS;
1095 transfer->timeout = timeout;
1096 transfer->buffer = buffer;
1097 transfer->length = length;
1098 transfer->num_iso_packets = num_iso_packets;
1099 transfer->user_data = user_data;
1100 transfer->callback = callback;
1101}
1102
1103/** \ingroup asyncio
1104 * Convenience function to set the length of all packets in an isochronous
1105 * transfer, based on the num_iso_packets field in the transfer structure.
1106 *
1107 * \param transfer a transfer
1108 * \param length the length to set in each isochronous packet descriptor
1109 * \see libusb_get_max_packet_size()
1110 */
1111static inline void libusb_set_iso_packet_lengths(
1112 struct libusb_transfer *transfer, unsigned int length)
1113{
1114 int i;
1115 for (i = 0; i < transfer->num_iso_packets; i++)
1116 transfer->iso_packet_desc[i].length = length;
1117}
1118
1119/** \ingroup asyncio
1120 * Convenience function to locate the position of an isochronous packet
1121 * within the buffer of an isochronous transfer.
1122 *
1123 * This is a thorough function which loops through all preceding packets,
1124 * accumulating their lengths to find the position of the specified packet.
1125 * Typically you will assign equal lengths to each packet in the transfer,
1126 * and hence the above method is sub-optimal. You may wish to use
1127 * libusb_get_iso_packet_buffer_simple() instead.
1128 *
1129 * \param transfer a transfer
1130 * \param packet the packet to return the address of
1131 * \returns the base address of the packet buffer inside the transfer buffer,
1132 * or NULL if the packet does not exist.
1133 * \see libusb_get_iso_packet_buffer_simple()
1134 */
1135static inline unsigned char *libusb_get_iso_packet_buffer(
1136 struct libusb_transfer *transfer, unsigned int packet)
1137{
1138 int i;
1139 size_t offset = 0;
1140 int _packet;
1141
1142 /* oops..slight bug in the API. packet is an unsigned int, but we use
1143 * signed integers almost everywhere else. range-check and convert to
1144 * signed to avoid compiler warnings. FIXME for libusb-2. */
1145 if (packet > INT_MAX)
1146 return NULL;
1147 _packet = packet;
1148
1149 if (_packet >= transfer->num_iso_packets)
1150 return NULL;
1151
1152 for (i = 0; i < _packet; i++)
1153 offset += transfer->iso_packet_desc[i].length;
1154
1155 return transfer->buffer + offset;
1156}
1157
1158/** \ingroup asyncio
1159 * Convenience function to locate the position of an isochronous packet
1160 * within the buffer of an isochronous transfer, for transfers where each
1161 * packet is of identical size.
1162 *
1163 * This function relies on the assumption that every packet within the transfer
1164 * is of identical size to the first packet. Calculating the location of
1165 * the packet buffer is then just a simple calculation:
1166 * <tt>buffer + (packet_size * packet)</tt>
1167 *
1168 * Do not use this function on transfers other than those that have identical
1169 * packet lengths for each packet.
1170 *
1171 * \param transfer a transfer
1172 * \param packet the packet to return the address of
1173 * \returns the base address of the packet buffer inside the transfer buffer,
1174 * or NULL if the packet does not exist.
1175 * \see libusb_get_iso_packet_buffer()
1176 */
1177static inline unsigned char *libusb_get_iso_packet_buffer_simple(
1178 struct libusb_transfer *transfer, unsigned int packet)
1179{
1180 int _packet;
1181
1182 /* oops..slight bug in the API. packet is an unsigned int, but we use
1183 * signed integers almost everywhere else. range-check and convert to
1184 * signed to avoid compiler warnings. FIXME for libusb-2. */
1185 if (packet > INT_MAX)
1186 return NULL;
1187 _packet = packet;
1188
1189 if (_packet >= transfer->num_iso_packets)
1190 return NULL;
1191
1192 return transfer->buffer + (transfer->iso_packet_desc[0].length * _packet);
1193}
1194
1195/* sync I/O */
1196
1197int LIBUSB_CALL libusb_control_transfer(libusb_device_handle *dev_handle,
1198 uint8_t request_type, uint8_t bRequest, uint16_t wValue, uint16_t wIndex,
1199 unsigned char *data, uint16_t wLength, unsigned int timeout);
1200
1201int LIBUSB_CALL libusb_bulk_transfer(libusb_device_handle *dev_handle,
1202 unsigned char endpoint, unsigned char *data, int length,
1203 int *actual_length, unsigned int timeout);
1204
1205int LIBUSB_CALL libusb_interrupt_transfer(libusb_device_handle *dev_handle,
1206 unsigned char endpoint, unsigned char *data, int length,
1207 int *actual_length, unsigned int timeout);
1208
1209/** \ingroup desc
1210 * Retrieve a descriptor from the default control pipe.
1211 * This is a convenience function which formulates the appropriate control
1212 * message to retrieve the descriptor.
1213 *
1214 * \param dev a device handle
1215 * \param desc_type the descriptor type, see \ref libusb_descriptor_type
1216 * \param desc_index the index of the descriptor to retrieve
1217 * \param data output buffer for descriptor
1218 * \param length size of data buffer
1219 * \returns number of bytes returned in data, or LIBUSB_ERROR code on failure
1220 */
1221static inline int libusb_get_descriptor(libusb_device_handle *dev,
1222 uint8_t desc_type, uint8_t desc_index, unsigned char *data, int length)
1223{
1224 return libusb_control_transfer(dev, LIBUSB_ENDPOINT_IN,
1225 LIBUSB_REQUEST_GET_DESCRIPTOR, (desc_type << 8) | desc_index, 0, data,
1226 (uint16_t) length, 1000);
1227}
1228
1229/** \ingroup desc
1230 * Retrieve a descriptor from a device.
1231 * This is a convenience function which formulates the appropriate control
1232 * message to retrieve the descriptor. The string returned is Unicode, as
1233 * detailed in the USB specifications.
1234 *
1235 * \param dev a device handle
1236 * \param desc_index the index of the descriptor to retrieve
1237 * \param langid the language ID for the string descriptor
1238 * \param data output buffer for descriptor
1239 * \param length size of data buffer
1240 * \returns number of bytes returned in data, or LIBUSB_ERROR code on failure
1241 * \see libusb_get_string_descriptor_ascii()
1242 */
1243static inline int libusb_get_string_descriptor(libusb_device_handle *dev,
1244 uint8_t desc_index, uint16_t langid, unsigned char *data, int length)
1245{
1246 return libusb_control_transfer(dev, LIBUSB_ENDPOINT_IN,
1247 LIBUSB_REQUEST_GET_DESCRIPTOR, (LIBUSB_DT_STRING << 8) | desc_index,
1248 langid, data, (uint16_t) length, 1000);
1249}
1250
1251int LIBUSB_CALL libusb_get_string_descriptor_ascii(libusb_device_handle *dev,
1252 uint8_t desc_index, unsigned char *data, int length);
1253
1254/* polling and timeouts */
1255
1256int LIBUSB_CALL libusb_try_lock_events(libusb_context *ctx);
1257void LIBUSB_CALL libusb_lock_events(libusb_context *ctx);
1258void LIBUSB_CALL libusb_unlock_events(libusb_context *ctx);
1259int LIBUSB_CALL libusb_event_handling_ok(libusb_context *ctx);
1260int LIBUSB_CALL libusb_event_handler_active(libusb_context *ctx);
1261void LIBUSB_CALL libusb_lock_event_waiters(libusb_context *ctx);
1262void LIBUSB_CALL libusb_unlock_event_waiters(libusb_context *ctx);
1263int LIBUSB_CALL libusb_wait_for_event(libusb_context *ctx, struct timeval *tv);
1264
1265int LIBUSB_CALL libusb_handle_events_timeout(libusb_context *ctx,
1266 struct timeval *tv);
1267int LIBUSB_CALL libusb_handle_events(libusb_context *ctx);
1268int LIBUSB_CALL libusb_handle_events_locked(libusb_context *ctx,
1269 struct timeval *tv);
1270int LIBUSB_CALL libusb_pollfds_handle_timeouts(libusb_context *ctx);
1271int LIBUSB_CALL libusb_get_next_timeout(libusb_context *ctx,
1272 struct timeval *tv);
1273
1274/** \ingroup poll
1275 * File descriptor for polling
1276 */
1277struct libusb_pollfd {
1278 /** Numeric file descriptor */
1279 int fd;
1280
1281 /** Event flags to poll for from <poll.h>. POLLIN indicates that you
1282 * should monitor this file descriptor for becoming ready to read from,
1283 * and POLLOUT indicates that you should monitor this file descriptor for
1284 * nonblocking write readiness. */
1285 short events;
1286};
1287
1288/** \ingroup poll
1289 * Callback function, invoked when a new file descriptor should be added
1290 * to the set of file descriptors monitored for events.
1291 * \param fd the new file descriptor
1292 * \param events events to monitor for, see \ref libusb_pollfd for a
1293 * description
1294 * \param user_data User data pointer specified in
1295 * libusb_set_pollfd_notifiers() call
1296 * \see libusb_set_pollfd_notifiers()
1297 */
1298typedef void (LIBUSB_CALL *libusb_pollfd_added_cb)(int fd, short events,
1299 void *user_data);
1300
1301/** \ingroup poll
1302 * Callback function, invoked when a file descriptor should be removed from
1303 * the set of file descriptors being monitored for events. After returning
1304 * from this callback, do not use that file descriptor again.
1305 * \param fd the file descriptor to stop monitoring
1306 * \param user_data User data pointer specified in
1307 * libusb_set_pollfd_notifiers() call
1308 * \see libusb_set_pollfd_notifiers()
1309 */
1310typedef void (LIBUSB_CALL *libusb_pollfd_removed_cb)(int fd, void *user_data);
1311
1312const struct libusb_pollfd ** LIBUSB_CALL libusb_get_pollfds(
1313 libusb_context *ctx);
1314void LIBUSB_CALL libusb_set_pollfd_notifiers(libusb_context *ctx,
1315 libusb_pollfd_added_cb added_cb, libusb_pollfd_removed_cb removed_cb,
1316 void *user_data);
1317
1318#ifdef __cplusplus
1319}
1320#endif
1321
1322#endif
diff --git a/include/libusb-1.0/os/libusbi.h b/include/libusb-1.0/os/libusbi.h
deleted file mode 100644
index 9b2fa70..0000000
--- a/include/libusb-1.0/os/libusbi.h
+++ /dev/null
@@ -1,872 +0,0 @@
1/*
2 * Internal header 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#ifndef __LIBUSBI_H__
22#define __LIBUSBI_H__
23
24#include <config.h>
25
26#include <stddef.h>
27#include <stdint.h>
28#include <time.h>
29
30#include <libusb.h>
31
32/* Inside the libusb code, mark all public functions as follows:
33 * return_type API_EXPORTED function_name(params) { ... }
34 * But if the function returns a pointer, mark it as follows:
35 * DEFAULT_VISIBILITY return_type * LIBUSB_CALL function_name(params) { ... }
36 * In the libusb public header, mark all declarations as:
37 * return_type LIBUSB_CALL function_name(params);
38 */
39#define API_EXPORTED LIBUSB_CALL DEFAULT_VISIBILITY
40
41#define DEVICE_DESC_LENGTH 18
42
43#define USB_MAXENDPOINTS 32
44#define USB_MAXINTERFACES 32
45#define USB_MAXCONFIG 8
46
47struct list_head {
48 struct list_head *prev, *next;
49};
50
51/* Get an entry from the list
52 * ptr - the address of this list_head element in "type"
53 * type - the data type that contains "member"
54 * member - the list_head element in "type"
55 */
56#define list_entry(ptr, type, member) \
57 ((type *)((uintptr_t)(ptr) - (uintptr_t)(&((type *)0L)->member)))
58
59/* Get each entry from a list
60 * pos - A structure pointer has a "member" element
61 * head - list head
62 * member - the list_head element in "pos"
63 * type - the type of the first parameter
64 */
65#define list_for_each_entry(pos, head, member, type) \
66 for (pos = list_entry((head)->next, type, member); \
67 &pos->member != (head); \
68 pos = list_entry(pos->member.next, type, member))
69
70#define list_for_each_entry_safe(pos, n, head, member, type) \
71 for (pos = list_entry((head)->next, type, member), \
72 n = list_entry(pos->member.next, type, member); \
73 &pos->member != (head); \
74 pos = n, n = list_entry(n->member.next, type, member))
75
76#define list_empty(entry) ((entry)->next == (entry))
77
78static inline void list_init(struct list_head *entry)
79{
80 entry->prev = entry->next = entry;
81}
82
83static inline void list_add(struct list_head *entry, struct list_head *head)
84{
85 entry->next = head->next;
86 entry->prev = head;
87
88 head->next->prev = entry;
89 head->next = entry;
90}
91
92static inline void list_add_tail(struct list_head *entry,
93 struct list_head *head)
94{
95 entry->next = head;
96 entry->prev = head->prev;
97
98 head->prev->next = entry;
99 head->prev = entry;
100}
101
102static inline void list_del(struct list_head *entry)
103{
104 entry->next->prev = entry->prev;
105 entry->prev->next = entry->next;
106}
107
108#define container_of(ptr, type, member) ({ \
109 const typeof( ((type *)0)->member ) *__mptr = (ptr); \
110 (type *)( (char *)__mptr - offsetof(type,member) );})
111
112#define MIN(a, b) ((a) < (b) ? (a) : (b))
113#define MAX(a, b) ((a) > (b) ? (a) : (b))
114
115#define TIMESPEC_IS_SET(ts) ((ts)->tv_sec != 0 || (ts)->tv_nsec != 0)
116
117enum usbi_log_level {
118 LOG_LEVEL_DEBUG,
119 LOG_LEVEL_INFO,
120 LOG_LEVEL_WARNING,
121 LOG_LEVEL_ERROR,
122};
123
124void usbi_log(struct libusb_context *ctx, enum usbi_log_level level,
125 const char *function, const char *format, ...);
126
127#if !defined(_MSC_VER) || _MSC_VER > 1200
128
129#ifdef ENABLE_LOGGING
130#define _usbi_log(ctx, level, ...) usbi_log(ctx, level, __FUNCTION__, __VA_ARGS__)
131#else
132#define _usbi_log(ctx, level, ...)
133#endif
134
135#ifdef ENABLE_DEBUG_LOGGING
136#define usbi_dbg(...) _usbi_log(NULL, LOG_LEVEL_DEBUG, __VA_ARGS__)
137#else
138#define usbi_dbg(...)
139#endif
140
141#define usbi_info(ctx, ...) _usbi_log(ctx, LOG_LEVEL_INFO, __VA_ARGS__)
142#define usbi_warn(ctx, ...) _usbi_log(ctx, LOG_LEVEL_WARNING, __VA_ARGS__)
143#define usbi_err(ctx, ...) _usbi_log(ctx, LOG_LEVEL_ERROR, __VA_ARGS__)
144
145#else /* !defined(_MSC_VER) || _MSC_VER > 1200 */
146
147void usbi_log_v(struct libusb_context *ctx, enum usbi_log_level level,
148 const char *function, const char *format, va_list args);
149
150#ifdef ENABLE_LOGGING
151#define LOG_BODY(ctxt, level) \
152{ \
153 va_list args; \
154 va_start (args, format); \
155 usbi_log_v(ctxt, level, "", format, args); \
156 va_end(args); \
157}
158#else
159#define LOG_BODY(ctxt, level) { }
160#endif
161
162static inline void usbi_info(struct libusb_context *ctx, const char *format,
163 ...)
164 LOG_BODY(ctx,LOG_LEVEL_INFO)
165static inline void usbi_warn(struct libusb_context *ctx, const char *format,
166 ...)
167 LOG_BODY(ctx,LOG_LEVEL_WARNING)
168static inline void usbi_err( struct libusb_context *ctx, const char *format,
169 ...)
170 LOG_BODY(ctx,LOG_LEVEL_ERROR)
171
172static inline void usbi_dbg(const char *format, ...)
173#ifdef ENABLE_DEBUG_LOGGING
174 LOG_BODY(NULL,LOG_LEVEL_DEBUG)
175#else
176{ }
177#endif
178
179#endif /* !defined(_MSC_VER) || _MSC_VER > 1200 */
180
181#define USBI_GET_CONTEXT(ctx) if (!(ctx)) (ctx) = usbi_default_context
182#define DEVICE_CTX(dev) ((dev)->ctx)
183#define HANDLE_CTX(handle) (DEVICE_CTX((handle)->dev))
184#define TRANSFER_CTX(transfer) (HANDLE_CTX((transfer)->dev_handle))
185#define ITRANSFER_CTX(transfer) \
186 (TRANSFER_CTX(__USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer)))
187
188/* Internal abstractions for thread synchronization and poll */
189#if defined(THREADS_POSIX)
190#include <os/threads_posix.h>
191#elif defined(OS_WINDOWS)
192#include <os/threads_windows.h>
193#endif
194
195#if defined(OS_LINUX) || defined(OS_DARWIN)
196#include <os/poll_posix.h>
197#elif defined(OS_WINDOWS)
198#include <os/poll_windows.h>
199#endif
200
201extern struct libusb_context *usbi_default_context;
202
203struct libusb_context {
204 int debug;
205 int debug_fixed;
206
207 /* internal control pipe, used for interrupting event handling when
208 * something needs to modify poll fds. */
209 int ctrl_pipe[2];
210
211 struct list_head usb_devs;
212 usbi_mutex_t usb_devs_lock;
213
214 /* A list of open handles. Backends are free to traverse this if required.
215 */
216 struct list_head open_devs;
217 usbi_mutex_t open_devs_lock;
218
219 /* this is a list of in-flight transfer handles, sorted by timeout
220 * expiration. URBs to timeout the soonest are placed at the beginning of
221 * the list, URBs that will time out later are placed after, and urbs with
222 * infinite timeout are always placed at the very end. */
223 struct list_head flying_transfers;
224 usbi_mutex_t flying_transfers_lock;
225
226 /* list of poll fds */
227 struct list_head pollfds;
228 usbi_mutex_t pollfds_lock;
229
230 /* a counter that is set when we want to interrupt event handling, in order
231 * to modify the poll fd set. and a lock to protect it. */
232 unsigned int pollfd_modify;
233 usbi_mutex_t pollfd_modify_lock;
234
235 /* user callbacks for pollfd changes */
236 libusb_pollfd_added_cb fd_added_cb;
237 libusb_pollfd_removed_cb fd_removed_cb;
238 void *fd_cb_user_data;
239
240 /* ensures that only one thread is handling events at any one time */
241 usbi_mutex_t events_lock;
242
243 /* used to see if there is an active thread doing event handling */
244 int event_handler_active;
245
246 /* used to wait for event completion in threads other than the one that is
247 * event handling */
248 usbi_mutex_t event_waiters_lock;
249 usbi_cond_t event_waiters_cond;
250
251#ifdef USBI_TIMERFD_AVAILABLE
252 /* used for timeout handling, if supported by OS.
253 * this timerfd is maintained to trigger on the next pending timeout */
254 int timerfd;
255#endif
256};
257
258#ifdef USBI_TIMERFD_AVAILABLE
259#define usbi_using_timerfd(ctx) ((ctx)->timerfd >= 0)
260#else
261#define usbi_using_timerfd(ctx) (0)
262#endif
263
264struct libusb_device {
265 /* lock protects refcnt, everything else is finalized at initialization
266 * time */
267 usbi_mutex_t lock;
268 int refcnt;
269
270 struct libusb_context *ctx;
271
272 uint8_t bus_number;
273 uint8_t device_address;
274 uint8_t num_configurations;
275
276 struct list_head list;
277 unsigned long session_data;
278 unsigned char os_priv[0];
279};
280
281struct libusb_device_handle {
282 /* lock protects claimed_interfaces */
283 usbi_mutex_t lock;
284 unsigned long claimed_interfaces;
285
286 struct list_head list;
287 struct libusb_device *dev;
288 unsigned char os_priv[0];
289};
290
291#define USBI_TRANSFER_TIMED_OUT (1<<0)
292
293enum {
294 USBI_CLOCK_MONOTONIC,
295 USBI_CLOCK_REALTIME
296};
297
298/* in-memory transfer layout:
299 *
300 * 1. struct usbi_transfer
301 * 2. struct libusb_transfer (which includes iso packets) [variable size]
302 * 3. os private data [variable size]
303 *
304 * from a libusb_transfer, you can get the usbi_transfer by rewinding the
305 * appropriate number of bytes.
306 * the usbi_transfer includes the number of allocated packets, so you can
307 * determine the size of the transfer and hence the start and length of the
308 * OS-private data.
309 */
310
311struct usbi_transfer {
312 int num_iso_packets;
313 struct list_head list;
314 struct timeval timeout;
315 int transferred;
316 uint8_t flags;
317
318 /* this lock is held during libusb_submit_transfer() and
319 * libusb_cancel_transfer() (allowing the OS backend to prevent duplicate
320 * cancellation, submission-during-cancellation, etc). the OS backend
321 * should also take this lock in the handle_events path, to prevent the user
322 * cancelling the transfer from another thread while you are processing
323 * its completion (presumably there would be races within your OS backend
324 * if this were possible). */
325 usbi_mutex_t lock;
326};
327
328#define __USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer) \
329 ((struct libusb_transfer *)(((unsigned char *)(transfer)) \
330 + sizeof(struct usbi_transfer)))
331#define __LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer) \
332 ((struct usbi_transfer *)(((unsigned char *)(transfer)) \
333 - sizeof(struct usbi_transfer)))
334
335static inline void *usbi_transfer_get_os_priv(struct usbi_transfer *transfer)
336{
337 return ((unsigned char *)transfer) + sizeof(struct usbi_transfer)
338 + sizeof(struct libusb_transfer)
339 + (transfer->num_iso_packets
340 * sizeof(struct libusb_iso_packet_descriptor));
341}
342
343/* bus structures */
344
345/* All standard descriptors have these 2 fields in common */
346struct usb_descriptor_header {
347 uint8_t bLength;
348 uint8_t bDescriptorType;
349};
350
351/* shared data and functions */
352
353int usbi_io_init(struct libusb_context *ctx);
354void usbi_io_exit(struct libusb_context *ctx);
355
356struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
357 unsigned long session_id);
358struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
359 unsigned long session_id);
360int usbi_sanitize_device(struct libusb_device *dev);
361void usbi_handle_disconnect(struct libusb_device_handle *handle);
362
363int usbi_handle_transfer_completion(struct usbi_transfer *itransfer,
364 enum libusb_transfer_status status);
365int usbi_handle_transfer_cancellation(struct usbi_transfer *transfer);
366
367int usbi_parse_descriptor(unsigned char *source, char *descriptor, void *dest,
368 int host_endian);
369int usbi_get_config_index_by_value(struct libusb_device *dev,
370 uint8_t bConfigurationValue, int *idx);
371
372/* polling */
373
374struct usbi_pollfd {
375 /* must come first */
376 struct libusb_pollfd pollfd;
377
378 struct list_head list;
379};
380
381int usbi_add_pollfd(struct libusb_context *ctx, int fd, short events);
382void usbi_remove_pollfd(struct libusb_context *ctx, int fd);
383void usbi_fd_notification(struct libusb_context *ctx);
384
385/* device discovery */
386
387/* we traverse usbfs without knowing how many devices we are going to find.
388 * so we create this discovered_devs model which is similar to a linked-list
389 * which grows when required. it can be freed once discovery has completed,
390 * eliminating the need for a list node in the libusb_device structure
391 * itself. */
392struct discovered_devs {
393 size_t len;
394 size_t capacity;
395 struct libusb_device *devices[0];
396};
397
398struct discovered_devs *discovered_devs_append(
399 struct discovered_devs *discdevs, struct libusb_device *dev);
400
401/* OS abstraction */
402
403/* This is the interface that OS backends need to implement.
404 * All fields are mandatory, except ones explicitly noted as optional. */
405struct usbi_os_backend {
406 /* A human-readable name for your backend, e.g. "Linux usbfs" */
407 const char *name;
408
409 /* Perform initialization of your backend. You might use this function
410 * to determine specific capabilities of the system, allocate required
411 * data structures for later, etc.
412 *
413 * This function is called when a libusb user initializes the library
414 * prior to use.
415 *
416 * Return 0 on success, or a LIBUSB_ERROR code on failure.
417 */
418 int (*init)(struct libusb_context *ctx);
419
420 /* Deinitialization. Optional. This function should destroy anything
421 * that was set up by init.
422 *
423 * This function is called when the user deinitializes the library.
424 */
425 void (*exit)(void);
426
427 /* Enumerate all the USB devices on the system, returning them in a list
428 * of discovered devices.
429 *
430 * Your implementation should enumerate all devices on the system,
431 * regardless of whether they have been seen before or not.
432 *
433 * When you have found a device, compute a session ID for it. The session
434 * ID should uniquely represent that particular device for that particular
435 * connection session since boot (i.e. if you disconnect and reconnect a
436 * device immediately after, it should be assigned a different session ID).
437 * If your OS cannot provide a unique session ID as described above,
438 * presenting a session ID of (bus_number << 8 | device_address) should
439 * be sufficient. Bus numbers and device addresses wrap and get reused,
440 * but that is an unlikely case.
441 *
442 * After computing a session ID for a device, call
443 * usbi_get_device_by_session_id(). This function checks if libusb already
444 * knows about the device, and if so, it provides you with a libusb_device
445 * structure for it.
446 *
447 * If usbi_get_device_by_session_id() returns NULL, it is time to allocate
448 * a new device structure for the device. Call usbi_alloc_device() to
449 * obtain a new libusb_device structure with reference count 1. Populate
450 * the bus_number and device_address attributes of the new device, and
451 * perform any other internal backend initialization you need to do. At
452 * this point, you should be ready to provide device descriptors and so
453 * on through the get_*_descriptor functions. Finally, call
454 * usbi_sanitize_device() to perform some final sanity checks on the
455 * device. Assuming all of the above succeeded, we can now continue.
456 * If any of the above failed, remember to unreference the device that
457 * was returned by usbi_alloc_device().
458 *
459 * At this stage we have a populated libusb_device structure (either one
460 * that was found earlier, or one that we have just allocated and
461 * populated). This can now be added to the discovered devices list
462 * using discovered_devs_append(). Note that discovered_devs_append()
463 * may reallocate the list, returning a new location for it, and also
464 * note that reallocation can fail. Your backend should handle these
465 * error conditions appropriately.
466 *
467 * This function should not generate any bus I/O and should not block.
468 * If I/O is required (e.g. reading the active configuration value), it is
469 * OK to ignore these suggestions :)
470 *
471 * This function is executed when the user wishes to retrieve a list
472 * of USB devices connected to the system.
473 *
474 * Return 0 on success, or a LIBUSB_ERROR code on failure.
475 */
476 int (*get_device_list)(struct libusb_context *ctx,
477 struct discovered_devs **discdevs);
478
479 /* Open a device for I/O and other USB operations. The device handle
480 * is preallocated for you, you can retrieve the device in question
481 * through handle->dev.
482 *
483 * Your backend should allocate any internal resources required for I/O
484 * and other operations so that those operations can happen (hopefully)
485 * without hiccup. This is also a good place to inform libusb that it
486 * should monitor certain file descriptors related to this device -
487 * see the usbi_add_pollfd() function.
488 *
489 * This function should not generate any bus I/O and should not block.
490 *
491 * This function is called when the user attempts to obtain a device
492 * handle for a device.
493 *
494 * Return:
495 * - 0 on success
496 * - LIBUSB_ERROR_ACCESS if the user has insufficient permissions
497 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since
498 * discovery
499 * - another LIBUSB_ERROR code on other failure
500 *
501 * Do not worry about freeing the handle on failed open, the upper layers
502 * do this for you.
503 */
504 int (*open)(struct libusb_device_handle *handle);
505
506 /* Close a device such that the handle cannot be used again. Your backend
507 * should destroy any resources that were allocated in the open path.
508 * This may also be a good place to call usbi_remove_pollfd() to inform
509 * libusb of any file descriptors associated with this device that should
510 * no longer be monitored.
511 *
512 * This function is called when the user closes a device handle.
513 */
514 void (*close)(struct libusb_device_handle *handle);
515
516 /* Retrieve the device descriptor from a device.
517 *
518 * The descriptor should be retrieved from memory, NOT via bus I/O to the
519 * device. This means that you may have to cache it in a private structure
520 * during get_device_list enumeration. Alternatively, you may be able
521 * to retrieve it from a kernel interface (some Linux setups can do this)
522 * still without generating bus I/O.
523 *
524 * This function is expected to write DEVICE_DESC_LENGTH (18) bytes into
525 * buffer, which is guaranteed to be big enough.
526 *
527 * This function is called when sanity-checking a device before adding
528 * it to the list of discovered devices, and also when the user requests
529 * to read the device descriptor.
530 *
531 * This function is expected to return the descriptor in bus-endian format
532 * (LE). If it returns the multi-byte values in host-endian format,
533 * set the host_endian output parameter to "1".
534 *
535 * Return 0 on success or a LIBUSB_ERROR code on failure.
536 */
537 int (*get_device_descriptor)(struct libusb_device *device,
538 unsigned char *buffer, int *host_endian);
539
540 /* Get the ACTIVE configuration descriptor for a device.
541 *
542 * The descriptor should be retrieved from memory, NOT via bus I/O to the
543 * device. This means that you may have to cache it in a private structure
544 * during get_device_list enumeration. You may also have to keep track
545 * of which configuration is active when the user changes it.
546 *
547 * This function is expected to write len bytes of data into buffer, which
548 * is guaranteed to be big enough. If you can only do a partial write,
549 * return an error code.
550 *
551 * This function is expected to return the descriptor in bus-endian format
552 * (LE). If it returns the multi-byte values in host-endian format,
553 * set the host_endian output parameter to "1".
554 *
555 * Return:
556 * - 0 on success
557 * - LIBUSB_ERROR_NOT_FOUND if the device is in unconfigured state
558 * - another LIBUSB_ERROR code on other failure
559 */
560 int (*get_active_config_descriptor)(struct libusb_device *device,
561 unsigned char *buffer, size_t len, int *host_endian);
562
563 /* Get a specific configuration descriptor for a device.
564 *
565 * The descriptor should be retrieved from memory, NOT via bus I/O to the
566 * device. This means that you may have to cache it in a private structure
567 * during get_device_list enumeration.
568 *
569 * The requested descriptor is expressed as a zero-based index (i.e. 0
570 * indicates that we are requesting the first descriptor). The index does
571 * not (necessarily) equal the bConfigurationValue of the configuration
572 * being requested.
573 *
574 * This function is expected to write len bytes of data into buffer, which
575 * is guaranteed to be big enough. If you can only do a partial write,
576 * return an error code.
577 *
578 * This function is expected to return the descriptor in bus-endian format
579 * (LE). If it returns the multi-byte values in host-endian format,
580 * set the host_endian output parameter to "1".
581 *
582 * Return 0 on success or a LIBUSB_ERROR code on failure.
583 */
584 int (*get_config_descriptor)(struct libusb_device *device,
585 uint8_t config_index, unsigned char *buffer, size_t len,
586 int *host_endian);
587
588 /* Get the bConfigurationValue for the active configuration for a device.
589 * Optional. This should only be implemented if you can retrieve it from
590 * cache (don't generate I/O).
591 *
592 * If you cannot retrieve this from cache, either do not implement this
593 * function, or return LIBUSB_ERROR_NOT_SUPPORTED. This will cause
594 * libusb to retrieve the information through a standard control transfer.
595 *
596 * This function must be non-blocking.
597 * Return:
598 * - 0 on success
599 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
600 * was opened
601 * - LIBUSB_ERROR_NOT_SUPPORTED if the value cannot be retrieved without
602 * blocking
603 * - another LIBUSB_ERROR code on other failure.
604 */
605 int (*get_configuration)(struct libusb_device_handle *handle, int *config);
606
607 /* Set the active configuration for a device.
608 *
609 * A configuration value of -1 should put the device in unconfigured state.
610 *
611 * This function can block.
612 *
613 * Return:
614 * - 0 on success
615 * - LIBUSB_ERROR_NOT_FOUND if the configuration does not exist
616 * - LIBUSB_ERROR_BUSY if interfaces are currently claimed (and hence
617 * configuration cannot be changed)
618 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
619 * was opened
620 * - another LIBUSB_ERROR code on other failure.
621 */
622 int (*set_configuration)(struct libusb_device_handle *handle, int config);
623
624 /* Claim an interface. When claimed, the application can then perform
625 * I/O to an interface's endpoints.
626 *
627 * This function should not generate any bus I/O and should not block.
628 * Interface claiming is a logical operation that simply ensures that
629 * no other drivers/applications are using the interface, and after
630 * claiming, no other drivers/applicatiosn can use the interface because
631 * we now "own" it.
632 *
633 * Return:
634 * - 0 on success
635 * - LIBUSB_ERROR_NOT_FOUND if the interface does not exist
636 * - LIBUSB_ERROR_BUSY if the interface is in use by another driver/app
637 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
638 * was opened
639 * - another LIBUSB_ERROR code on other failure
640 */
641 int (*claim_interface)(struct libusb_device_handle *handle, int interface_number);
642
643 /* Release a previously claimed interface.
644 *
645 * This function should also generate a SET_INTERFACE control request,
646 * resetting the alternate setting of that interface to 0. It's OK for
647 * this function to block as a result.
648 *
649 * You will only ever be asked to release an interface which was
650 * successfully claimed earlier.
651 *
652 * Return:
653 * - 0 on success
654 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
655 * was opened
656 * - another LIBUSB_ERROR code on other failure
657 */
658 int (*release_interface)(struct libusb_device_handle *handle, int interface_number);
659
660 /* Set the alternate setting for an interface.
661 *
662 * You will only ever be asked to set the alternate setting for an
663 * interface which was successfully claimed earlier.
664 *
665 * It's OK for this function to block.
666 *
667 * Return:
668 * - 0 on success
669 * - LIBUSB_ERROR_NOT_FOUND if the alternate setting does not exist
670 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
671 * was opened
672 * - another LIBUSB_ERROR code on other failure
673 */
674 int (*set_interface_altsetting)(struct libusb_device_handle *handle,
675 int interface_number, int altsetting);
676
677 /* Clear a halt/stall condition on an endpoint.
678 *
679 * It's OK for this function to block.
680 *
681 * Return:
682 * - 0 on success
683 * - LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
684 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
685 * was opened
686 * - another LIBUSB_ERROR code on other failure
687 */
688 int (*clear_halt)(struct libusb_device_handle *handle,
689 unsigned char endpoint);
690
691 /* Perform a USB port reset to reinitialize a device.
692 *
693 * If possible, the handle should still be usable after the reset
694 * completes, assuming that the device descriptors did not change during
695 * reset and all previous interface state can be restored.
696 *
697 * If something changes, or you cannot easily locate/verify the resetted
698 * device, return LIBUSB_ERROR_NOT_FOUND. This prompts the application
699 * to close the old handle and re-enumerate the device.
700 *
701 * Return:
702 * - 0 on success
703 * - LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the device
704 * has been disconnected since it was opened
705 * - another LIBUSB_ERROR code on other failure
706 */
707 int (*reset_device)(struct libusb_device_handle *handle);
708
709 /* Determine if a kernel driver is active on an interface. Optional.
710 *
711 * The presence of a kernel driver on an interface indicates that any
712 * calls to claim_interface would fail with the LIBUSB_ERROR_BUSY code.
713 *
714 * Return:
715 * - 0 if no driver is active
716 * - 1 if a driver is active
717 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
718 * was opened
719 * - another LIBUSB_ERROR code on other failure
720 */
721 int (*kernel_driver_active)(struct libusb_device_handle *handle,
722 int interface_number);
723
724 /* Detach a kernel driver from an interface. Optional.
725 *
726 * After detaching a kernel driver, the interface should be available
727 * for claim.
728 *
729 * Return:
730 * - 0 on success
731 * - LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
732 * - LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
733 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
734 * was opened
735 * - another LIBUSB_ERROR code on other failure
736 */
737 int (*detach_kernel_driver)(struct libusb_device_handle *handle,
738 int interface_number);
739
740 /* Attach a kernel driver to an interface. Optional.
741 *
742 * Reattach a kernel driver to the device.
743 *
744 * Return:
745 * - 0 on success
746 * - LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
747 * - LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
748 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it
749 * was opened
750 * - LIBUSB_ERROR_BUSY if a program or driver has claimed the interface,
751 * preventing reattachment
752 * - another LIBUSB_ERROR code on other failure
753 */
754 int (*attach_kernel_driver)(struct libusb_device_handle *handle,
755 int interface_number);
756
757 /* Destroy a device. Optional.
758 *
759 * This function is called when the last reference to a device is
760 * destroyed. It should free any resources allocated in the get_device_list
761 * path.
762 */
763 void (*destroy_device)(struct libusb_device *dev);
764
765 /* Submit a transfer. Your implementation should take the transfer,
766 * morph it into whatever form your platform requires, and submit it
767 * asynchronously.
768 *
769 * This function must not block.
770 *
771 * Return:
772 * - 0 on success
773 * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
774 * - another LIBUSB_ERROR code on other failure
775 */
776 int (*submit_transfer)(struct usbi_transfer *itransfer);
777
778 /* Cancel a previously submitted transfer.
779 *
780 * This function must not block. The transfer cancellation must complete
781 * later, resulting in a call to usbi_handle_transfer_cancellation()
782 * from the context of handle_events.
783 */
784 int (*cancel_transfer)(struct usbi_transfer *itransfer);
785
786 /* Clear a transfer as if it has completed or cancelled, but do not
787 * report any completion/cancellation to the library. You should free
788 * all private data from the transfer as if you were just about to report
789 * completion or cancellation.
790 *
791 * This function might seem a bit out of place. It is used when libusb
792 * detects a disconnected device - it calls this function for all pending
793 * transfers before reporting completion (with the disconnect code) to
794 * the user. Maybe we can improve upon this internal interface in future.
795 */
796 void (*clear_transfer_priv)(struct usbi_transfer *itransfer);
797
798 /* Handle any pending events. This involves monitoring any active
799 * transfers and processing their completion or cancellation.
800 *
801 * The function is passed an array of pollfd structures (size nfds)
802 * as a result of the poll() system call. The num_ready parameter
803 * indicates the number of file descriptors that have reported events
804 * (i.e. the poll() return value). This should be enough information
805 * for you to determine which actions need to be taken on the currently
806 * active transfers.
807 *
808 * For any cancelled transfers, call usbi_handle_transfer_cancellation().
809 * For completed transfers, call usbi_handle_transfer_completion().
810 * For control/bulk/interrupt transfers, populate the "transferred"
811 * element of the appropriate usbi_transfer structure before calling the
812 * above functions. For isochronous transfers, populate the status and
813 * transferred fields of the iso packet descriptors of the transfer.
814 *
815 * This function should also be able to detect disconnection of the
816 * device, reporting that situation with usbi_handle_disconnect().
817 *
818 * When processing an event related to a transfer, you probably want to
819 * take usbi_transfer.lock to prevent races. See the documentation for
820 * the usbi_transfer structure.
821 *
822 * Return 0 on success, or a LIBUSB_ERROR code on failure.
823 */
824 int (*handle_events)(struct libusb_context *ctx,
825 struct pollfd *fds, nfds_t nfds, int num_ready);
826
827 /* Get time from specified clock. At least two clocks must be implemented
828 by the backend: USBI_CLOCK_REALTIME, and USBI_CLOCK_MONOTONIC.
829
830 Description of clocks:
831 USBI_CLOCK_REALTIME : clock returns time since system epoch.
832 USBI_CLOCK_MONOTONIC: clock returns time since unspecified start
833 time (usually boot).
834 */
835 int (*clock_gettime)(int clkid, struct timespec *tp);
836
837#ifdef USBI_TIMERFD_AVAILABLE
838 /* clock ID of the clock that should be used for timerfd */
839 clockid_t (*get_timerfd_clockid)(void);
840#endif
841
842 /* Number of bytes to reserve for per-device private backend data.
843 * This private data area is accessible through the "os_priv" field of
844 * struct libusb_device. */
845 size_t device_priv_size;
846
847 /* Number of bytes to reserve for per-handle private backend data.
848 * This private data area is accessible through the "os_priv" field of
849 * struct libusb_device. */
850 size_t device_handle_priv_size;
851
852 /* Number of bytes to reserve for per-transfer private backend data.
853 * This private data area is accessible by calling
854 * usbi_transfer_get_os_priv() on the appropriate usbi_transfer instance.
855 */
856 size_t transfer_priv_size;
857
858 /* Mumber of additional bytes for os_priv for each iso packet.
859 * Can your backend use this? */
860 /* FIXME: linux can't use this any more. if other OS's cannot either,
861 * then remove this */
862 size_t add_iso_packet_size;
863};
864
865extern const struct usbi_os_backend * const usbi_backend;
866
867extern const struct usbi_os_backend linux_usbfs_backend;
868extern const struct usbi_os_backend darwin_backend;
869extern const struct usbi_os_backend windows_backend;
870
871#endif
872
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
diff --git a/include/libusb-1.0/os/linux_usbfs.h b/include/libusb-1.0/os/linux_usbfs.h
deleted file mode 100644
index bd02edc..0000000
--- a/include/libusb-1.0/os/linux_usbfs.h
+++ /dev/null
@@ -1,138 +0,0 @@
1/*
2 * usbfs header structures
3 * Copyright (C) 2007 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#ifndef __LIBUSB_USBFS_H__
22#define __LIBUSB_USBFS_H__
23
24#define SYSFS_DEVICE_PATH "/sys/bus/usb/devices"
25
26struct usbfs_ctrltransfer {
27 /* keep in sync with usbdevice_fs.h:usbdevfs_ctrltransfer */
28 uint8_t bmRequestType;
29 uint8_t bRequest;
30 uint16_t wValue;
31 uint16_t wIndex;
32 uint16_t wLength;
33
34 uint32_t timeout; /* in milliseconds */
35
36 /* pointer to data */
37 void *data;
38};
39
40struct usbfs_bulktransfer {
41 /* keep in sync with usbdevice_fs.h:usbdevfs_bulktransfer */
42 unsigned int ep;
43 unsigned int len;
44 unsigned int timeout; /* in milliseconds */
45
46 /* pointer to data */
47 void *data;
48};
49
50struct usbfs_setinterface {
51 /* keep in sync with usbdevice_fs.h:usbdevfs_setinterface */
52 unsigned int interface;
53 unsigned int altsetting;
54};
55
56#define USBFS_MAXDRIVERNAME 255
57
58struct usbfs_getdriver {
59 unsigned int interface;
60 char driver[USBFS_MAXDRIVERNAME + 1];
61};
62
63#define USBFS_URB_SHORT_NOT_OK 0x01
64#define USBFS_URB_ISO_ASAP 0x02
65#define USBFS_URB_BULK_CONTINUATION 0x04
66#define USBFS_URB_QUEUE_BULK 0x10
67
68enum usbfs_urb_type {
69 USBFS_URB_TYPE_ISO = 0,
70 USBFS_URB_TYPE_INTERRUPT = 1,
71 USBFS_URB_TYPE_CONTROL = 2,
72 USBFS_URB_TYPE_BULK = 3,
73};
74
75struct usbfs_iso_packet_desc {
76 unsigned int length;
77 unsigned int actual_length;
78 unsigned int status;
79};
80
81#define MAX_ISO_BUFFER_LENGTH 32768
82#define MAX_BULK_BUFFER_LENGTH 16384
83#define MAX_CTRL_BUFFER_LENGTH 4096
84
85struct usbfs_urb {
86 unsigned char type;
87 unsigned char endpoint;
88 int status;
89 unsigned int flags;
90 void *buffer;
91 int buffer_length;
92 int actual_length;
93 int start_frame;
94 int number_of_packets;
95 int error_count;
96 unsigned int signr;
97 void *usercontext;
98 struct usbfs_iso_packet_desc iso_frame_desc[0];
99};
100
101struct usbfs_connectinfo {
102 unsigned int devnum;
103 unsigned char slow;
104};
105
106struct usbfs_ioctl {
107 int ifno; /* interface 0..N ; negative numbers reserved */
108 int ioctl_code; /* MUST encode size + direction of data so the
109 * macros in <asm/ioctl.h> give correct values */
110 void *data; /* param buffer (in, or out) */
111};
112
113struct usbfs_hub_portinfo {
114 unsigned char numports;
115 unsigned char port[127]; /* port to device num mapping */
116};
117
118#define IOCTL_USBFS_CONTROL _IOWR('U', 0, struct usbfs_ctrltransfer)
119#define IOCTL_USBFS_BULK _IOWR('U', 2, struct usbfs_bulktransfer)
120#define IOCTL_USBFS_RESETEP _IOR('U', 3, unsigned int)
121#define IOCTL_USBFS_SETINTF _IOR('U', 4, struct usbfs_setinterface)
122#define IOCTL_USBFS_SETCONFIG _IOR('U', 5, unsigned int)
123#define IOCTL_USBFS_GETDRIVER _IOW('U', 8, struct usbfs_getdriver)
124#define IOCTL_USBFS_SUBMITURB _IOR('U', 10, struct usbfs_urb)
125#define IOCTL_USBFS_DISCARDURB _IO('U', 11)
126#define IOCTL_USBFS_REAPURB _IOW('U', 12, void *)
127#define IOCTL_USBFS_REAPURBNDELAY _IOW('U', 13, void *)
128#define IOCTL_USBFS_CLAIMINTF _IOR('U', 15, unsigned int)
129#define IOCTL_USBFS_RELEASEINTF _IOR('U', 16, unsigned int)
130#define IOCTL_USBFS_CONNECTINFO _IOW('U', 17, struct usbfs_connectinfo)
131#define IOCTL_USBFS_IOCTL _IOWR('U', 18, struct usbfs_ioctl)
132#define IOCTL_USBFS_HUB_PORTINFO _IOR('U', 19, struct usbfs_hub_portinfo)
133#define IOCTL_USBFS_RESET _IO('U', 20)
134#define IOCTL_USBFS_CLEAR_HALT _IOR('U', 21, unsigned int)
135#define IOCTL_USBFS_DISCONNECT _IO('U', 22)
136#define IOCTL_USBFS_CONNECT _IO('U', 23)
137
138#endif
diff --git a/include/libusb-1.0/os/poll_posix.h b/include/libusb-1.0/os/poll_posix.h
deleted file mode 100644
index 17298a5..0000000
--- a/include/libusb-1.0/os/poll_posix.h
+++ /dev/null
@@ -1,12 +0,0 @@
1#ifndef __LIBUSB_POLL_POSIX_H__
2#define __LIBUSB_POLL_POSIX_H__
3
4#include <unistd.h>
5#include <poll.h>
6#define usbi_write write
7#define usbi_read read
8#define usbi_close close
9#define usbi_pipe pipe
10#define usbi_poll poll
11
12#endif /* __LIBUSB_POLL_POSIX_H__ */
diff --git a/include/libusb-1.0/os/poll_windows.c b/include/libusb-1.0/os/poll_windows.c
deleted file mode 100644
index 9ae9895..0000000
--- a/include/libusb-1.0/os/poll_windows.c
+++ /dev/null
@@ -1,860 +0,0 @@
1/*
2 * poll_windows: poll compatibility wrapper for Windows
3 * Copyright (C) 2009-2010 Pete Batard <pbatard@gmail.com>
4 * With contributions from Michael Plante, Orin Eman et al.
5 * Parts of poll implementation from libusb-win32, by Stephan Meyer et al.
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 *
21 */
22
23/*
24 * poll() and pipe() Windows compatibility layer for libusb 1.0
25 *
26 * The way this layer works is by using OVERLAPPED with async I/O transfers, as
27 * OVERLAPPED have an associated event which is flagged for I/O completion.
28 *
29 * For USB pollable async I/O, you would typically:
30 * - obtain a Windows HANDLE to a file or device that has been opened in
31 * OVERLAPPED mode
32 * - call usbi_create_fd with this handle to obtain a custom fd.
33 * Note that if you need simultaneous R/W access, you need to call create_fd
34 * twice, once in _O_RDONLY and once in _O_WRONLY mode to obtain 2 separate
35 * pollable fds
36 * - leave the core functions call the poll routine and flag POLLIN/POLLOUT
37 *
38 * The pipe pollable synchronous I/O works using the overlapped event associated
39 * with a fake pipe. The read/write functions are only meant to be used in that
40 * context.
41 */
42#include <errno.h>
43#include <fcntl.h>
44#include <stdio.h>
45#include <stdlib.h>
46#include <io.h>
47
48#include <libusbi.h>
49
50// Uncomment to debug the polling layer
51//#define DEBUG_POLL_WINDOWS
52#if defined(DEBUG_POLL_WINDOWS)
53#define poll_dbg usbi_dbg
54#else
55// MSVC6 cannot use a variadic argument and non MSVC
56// compilers produce warnings if parenthesis are ommitted.
57#if defined(_MSC_VER)
58#define poll_dbg
59#else
60#define poll_dbg(...)
61#endif
62#endif
63
64#if defined(_PREFAST_)
65#pragma warning(disable:28719)
66#endif
67
68#if defined(__CYGWIN__)
69// cygwin produces a warning unless these prototypes are defined
70extern int _close(int fd);
71extern int _snprintf(char *buffer, size_t count, const char *format, ...);
72extern int cygwin_attach_handle_to_fd(char *name, int fd, HANDLE handle, int bin, int access_mode);
73// _open_osfhandle() is not available on cygwin, but we can emulate
74// it for our needs with cygwin_attach_handle_to_fd()
75static inline int _open_osfhandle(intptr_t osfhandle, int flags)
76{
77 int access_mode;
78 switch (flags) {
79 case _O_RDONLY:
80 access_mode = GENERIC_READ;
81 break;
82 case _O_WRONLY:
83 access_mode = GENERIC_WRITE;
84 break;
85 case _O_RDWR:
86 access_mode = GENERIC_READ|GENERIC_WRITE;
87 break;
88 default:
89 usbi_err(NULL, "unsupported access mode");
90 return -1;
91 }
92 return cygwin_attach_handle_to_fd("/dev/null", -1, (HANDLE)osfhandle, -1, access_mode);
93}
94#endif
95
96#define CHECK_INIT_POLLING do {if(!is_polling_set) init_polling();} while(0)
97
98// public fd data
99const struct winfd INVALID_WINFD = {-1, INVALID_HANDLE_VALUE, NULL, RW_NONE};
100struct winfd poll_fd[MAX_FDS];
101// internal fd data
102struct {
103 CRITICAL_SECTION mutex; // lock for fds
104 // Additional variables for XP CancelIoEx partial emulation
105 HANDLE original_handle;
106 DWORD thread_id;
107} _poll_fd[MAX_FDS];
108
109// globals
110BOOLEAN is_polling_set = FALSE;
111#if defined(DYNAMIC_FDS)
112HANDLE fd_update = INVALID_HANDLE_VALUE; // event to notify poll of fd update
113HANDLE new_fd[MAX_FDS]; // overlapped event handles for fds created since last poll
114unsigned nb_new_fds = 0; // nb new fds created since last poll
115usbi_mutex_t new_fd_mutex; // mutex required for the above
116#endif
117LONG pipe_number = 0;
118static volatile LONG compat_spinlock = 0;
119
120// CancelIoEx, available on Vista and later only, provides the ability to cancel
121// a single transfer (OVERLAPPED) when used. As it may not be part of any of the
122// platform headers, we hook into the Kernel32 system DLL directly to seek it.
123static BOOL (__stdcall *pCancelIoEx)(HANDLE, LPOVERLAPPED) = NULL;
124#define CancelIoEx_Available (pCancelIoEx != NULL)
125__inline BOOL cancel_io(int index)
126{
127 if ((index < 0) || (index >= MAX_FDS)) {
128 return FALSE;
129 }
130
131 if ( (poll_fd[index].fd < 0) || (poll_fd[index].handle == INVALID_HANDLE_VALUE)
132 || (poll_fd[index].handle == 0) || (poll_fd[index].overlapped == NULL) ) {
133 return TRUE;
134 }
135 if (CancelIoEx_Available) {
136 return (*pCancelIoEx)(poll_fd[index].handle, poll_fd[index].overlapped);
137 }
138 if (_poll_fd[index].thread_id == GetCurrentThreadId()) {
139 return CancelIo(poll_fd[index].handle);
140 }
141 usbi_warn(NULL, "Unable to cancel I/O that was started from another thread");
142 return FALSE;
143}
144
145// Init
146void init_polling(void)
147{
148 int i;
149
150 while (InterlockedExchange((LONG *)&compat_spinlock, 1) == 1) {
151 SleepEx(0, TRUE);
152 }
153 if (!is_polling_set) {
154 pCancelIoEx = (BOOL (__stdcall *)(HANDLE,LPOVERLAPPED))
155 GetProcAddress(GetModuleHandle("KERNEL32"), "CancelIoEx");
156 usbi_dbg("Will use CancelIo%s for I/O cancellation",
157 CancelIoEx_Available?"Ex":"");
158 for (i=0; i<MAX_FDS; i++) {
159 poll_fd[i] = INVALID_WINFD;
160 _poll_fd[i].original_handle = INVALID_HANDLE_VALUE;
161 _poll_fd[i].thread_id = 0;
162 InitializeCriticalSection(&_poll_fd[i].mutex);
163 }
164#if defined(DYNAMIC_FDS)
165 // We need to create an update event so that poll is warned when there
166 // are new/deleted fds during a timeout wait operation
167 fd_update = CreateEvent(NULL, TRUE, FALSE, NULL);
168 if (fd_update == NULL) {
169 usbi_err(NULL, "unable to create update event");
170 }
171 usbi_mutex_init(&new_fd_mutex, NULL);
172 nb_new_fds = 0;
173#endif
174 is_polling_set = TRUE;
175 }
176 compat_spinlock = 0;
177}
178
179// Internal function to retrieve the table index (and lock the fd mutex)
180int _fd_to_index_and_lock(int fd)
181{
182 int i;
183
184 if (fd <= 0)
185 return -1;
186
187 for (i=0; i<MAX_FDS; i++) {
188 if (poll_fd[i].fd == fd) {
189 EnterCriticalSection(&_poll_fd[i].mutex);
190 // fd might have changed before we got to critical
191 if (poll_fd[i].fd != fd) {
192 LeaveCriticalSection(&_poll_fd[i].mutex);
193 continue;
194 }
195 return i;
196 }
197 }
198 return -1;
199}
200
201OVERLAPPED *create_overlapped(void)
202{
203 OVERLAPPED *overlapped = calloc(1, sizeof(OVERLAPPED));
204 if (overlapped == NULL) {
205 return NULL;
206 }
207 overlapped->hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
208 if(overlapped->hEvent == NULL) {
209 free (overlapped);
210 return NULL;
211 }
212 return overlapped;
213}
214
215void free_overlapped(OVERLAPPED *overlapped)
216{
217 if (overlapped == NULL)
218 return;
219
220 if ( (overlapped->hEvent != 0)
221 && (overlapped->hEvent != INVALID_HANDLE_VALUE) ) {
222 CloseHandle(overlapped->hEvent);
223 }
224 free(overlapped);
225}
226
227void reset_overlapped(OVERLAPPED *overlapped)
228{
229 HANDLE event_handle;
230 if (overlapped == NULL)
231 return;
232
233 event_handle = overlapped->hEvent;
234 if (event_handle != NULL) {
235 ResetEvent(event_handle);
236 }
237 memset(overlapped, 0, sizeof(OVERLAPPED));
238 overlapped->hEvent = event_handle;
239}
240
241void exit_polling(void)
242{
243 int i;
244
245 while (InterlockedExchange((LONG *)&compat_spinlock, 1) == 1) {
246 SleepEx(0, TRUE);
247 }
248 if (is_polling_set) {
249 is_polling_set = FALSE;
250
251 for (i=0; i<MAX_FDS; i++) {
252 // Cancel any async I/O (handle can be invalid)
253 cancel_io(i);
254 // If anything was pending on that I/O, it should be
255 // terminating, and we should be able to access the fd
256 // mutex lock before too long
257 EnterCriticalSection(&_poll_fd[i].mutex);
258 if ( (poll_fd[i].fd > 0) && (poll_fd[i].handle != INVALID_HANDLE_VALUE) && (poll_fd[i].handle != 0)
259 && (GetFileType(poll_fd[i].handle) == FILE_TYPE_UNKNOWN) ) {
260 _close(poll_fd[i].fd);
261 }
262 free_overlapped(poll_fd[i].overlapped);
263 if (!CancelIoEx_Available) {
264 // Close duplicate handle
265 if (_poll_fd[i].original_handle != INVALID_HANDLE_VALUE) {
266 CloseHandle(poll_fd[i].handle);
267 }
268 }
269 poll_fd[i] = INVALID_WINFD;
270#if defined(DYNAMIC_FDS)
271 usbi_mutex_destroy(&new_fd_mutex);
272 CloseHandle(fd_update);
273 fd_update = INVALID_HANDLE_VALUE;
274#endif
275 LeaveCriticalSection(&_poll_fd[i].mutex);
276 DeleteCriticalSection(&_poll_fd[i].mutex);
277 }
278 }
279 compat_spinlock = 0;
280}
281
282/*
283 * Create a fake pipe.
284 * As libusb only uses pipes for signaling, all we need from a pipe is an
285 * event. To that extent, we create a single wfd and overlapped as a means
286 * to access that event.
287 */
288int usbi_pipe(int filedes[2])
289{
290 int i;
291 HANDLE handle;
292 OVERLAPPED* overlapped;
293
294 CHECK_INIT_POLLING;
295
296 overlapped = calloc(1, sizeof(OVERLAPPED));
297 if (overlapped == NULL) {
298 return -1;
299 }
300 // The overlapped must have status pending for signaling to work in poll
301 overlapped->Internal = STATUS_PENDING;
302 overlapped->InternalHigh = 0;
303
304 // Read end of the "pipe"
305 handle = CreateFileA("NUL", 0, 0, NULL, OPEN_EXISTING, 0, NULL);
306 if (handle == INVALID_HANDLE_VALUE) {
307 usbi_err(NULL, "could not create pipe: errcode %d", (int)GetLastError());
308 goto out1;
309 }
310 filedes[0] = _open_osfhandle((intptr_t)handle, _O_RDONLY);
311 // We can use the same handle for both ends
312 filedes[1] = filedes[0];
313 poll_dbg("pipe filedes = %d", filedes[0]);
314
315 // Note: manual reset must be true (second param) as the reset occurs in read
316 overlapped->hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
317 if(!overlapped->hEvent) {
318 goto out2;
319 }
320
321 for (i=0; i<MAX_FDS; i++) {
322 if (poll_fd[i].fd < 0) {
323 EnterCriticalSection(&_poll_fd[i].mutex);
324 // fd might have been allocated before we got to critical
325 if (poll_fd[i].fd >= 0) {
326 LeaveCriticalSection(&_poll_fd[i].mutex);
327 continue;
328 }
329
330 poll_fd[i].fd = filedes[0];
331 poll_fd[i].handle = handle;
332 poll_fd[i].overlapped = overlapped;
333 // There's no polling on the write end, so we just use READ for our needs
334 poll_fd[i].rw = RW_READ;
335 _poll_fd[i].original_handle = INVALID_HANDLE_VALUE;
336 LeaveCriticalSection(&_poll_fd[i].mutex);
337 return 0;
338 }
339 }
340
341 CloseHandle(overlapped->hEvent);
342out2:
343 CloseHandle(handle);
344out1:
345 free(overlapped);
346 return -1;
347}
348
349/*
350 * Create both an fd and an OVERLAPPED from an open Windows handle, so that
351 * it can be used with our polling function
352 * The handle MUST support overlapped transfers (usually requires CreateFile
353 * with FILE_FLAG_OVERLAPPED)
354 * Return a pollable file descriptor struct, or INVALID_WINFD on error
355 *
356 * Note that the fd returned by this function is a per-transfer fd, rather
357 * than a per-session fd and cannot be used for anything else but our
358 * custom functions (the fd itself points to the NUL: device)
359 * if you plan to do R/W on the same handle, you MUST create 2 fds: one for
360 * read and one for write. Using a single R/W fd is unsupported and will
361 * produce unexpected results
362 */
363struct winfd usbi_create_fd(HANDLE handle, int access_mode)
364{
365 int i, fd;
366 struct winfd wfd = INVALID_WINFD;
367 OVERLAPPED* overlapped = NULL;
368
369 CHECK_INIT_POLLING;
370
371 if ((handle == 0) || (handle == INVALID_HANDLE_VALUE)) {
372 return INVALID_WINFD;
373 }
374
375 if ((access_mode != _O_RDONLY) && (access_mode != _O_WRONLY)) {
376 usbi_warn(NULL, "only one of _O_RDONLY or _O_WRONLY are supported.\n"
377 "If you want to poll for R/W simultaneously, create multiple fds from the same handle.");
378 return INVALID_WINFD;
379 }
380 if (access_mode == _O_RDONLY) {
381 wfd.rw = RW_READ;
382 } else {
383 wfd.rw = RW_WRITE;
384 }
385
386 // Ensure that we get a non system conflicting unique fd
387 fd = _open_osfhandle((intptr_t)CreateFileA("NUL", 0, 0,
388 NULL, OPEN_EXISTING, 0, NULL), _O_RDWR);
389 if (fd < 0) {
390 return INVALID_WINFD;
391 }
392
393 overlapped = create_overlapped();
394 if(overlapped == NULL) {
395 _close(fd);
396 return INVALID_WINFD;
397 }
398
399 for (i=0; i<MAX_FDS; i++) {
400 if (poll_fd[i].fd < 0) {
401 EnterCriticalSection(&_poll_fd[i].mutex);
402 // fd might have been removed before we got to critical
403 if (poll_fd[i].fd >= 0) {
404 LeaveCriticalSection(&_poll_fd[i].mutex);
405 continue;
406 }
407 wfd.fd = fd;
408 // Attempt to emulate some of the CancelIoEx behaviour on platforms
409 // that don't have it
410 if (!CancelIoEx_Available) {
411 _poll_fd[i].thread_id = GetCurrentThreadId();
412 if (!DuplicateHandle(GetCurrentProcess(), handle, GetCurrentProcess(),
413 &wfd.handle, 0, TRUE, DUPLICATE_SAME_ACCESS)) {
414 usbi_dbg("could not duplicate handle for CancelIo - using original one");
415 wfd.handle = handle;
416 // Make sure we won't close the original handle on fd deletion then
417 _poll_fd[i].original_handle = INVALID_HANDLE_VALUE;
418 } else {
419 _poll_fd[i].original_handle = handle;
420 }
421 } else {
422 wfd.handle = handle;
423 }
424 wfd.overlapped = overlapped;
425 memcpy(&poll_fd[i], &wfd, sizeof(struct winfd));
426 LeaveCriticalSection(&_poll_fd[i].mutex);
427#if defined(DYNAMIC_FDS)
428 usbi_mutex_lock(&new_fd_mutex);
429 new_fd[nb_new_fds++] = overlapped->hEvent;
430 usbi_mutex_unlock(&new_fd_mutex);
431 // Notify poll that fds have been updated
432 SetEvent(fd_update);
433#endif
434 return wfd;
435 }
436 }
437 free_overlapped(overlapped);
438 _close(fd);
439 return INVALID_WINFD;
440}
441
442void _free_index(int index)
443{
444 // Cancel any async IO (Don't care about the validity of our handles for this)
445 cancel_io(index);
446 // close fake handle for devices
447 if ( (poll_fd[index].handle != INVALID_HANDLE_VALUE) && (poll_fd[index].handle != 0)
448 && (GetFileType(poll_fd[index].handle) == FILE_TYPE_UNKNOWN) ) {
449 _close(poll_fd[index].fd);
450 }
451 // close the duplicate handle (if we have an actual duplicate)
452 if (!CancelIoEx_Available) {
453 if (_poll_fd[index].original_handle != INVALID_HANDLE_VALUE) {
454 CloseHandle(poll_fd[index].handle);
455 }
456 _poll_fd[index].original_handle = INVALID_HANDLE_VALUE;
457 _poll_fd[index].thread_id = 0;
458 }
459 free_overlapped(poll_fd[index].overlapped);
460 poll_fd[index] = INVALID_WINFD;
461}
462
463/*
464 * Release a pollable file descriptor.
465 *
466 * Note that the associated Windows handle is not closed by this call
467 */
468void usbi_free_fd(int fd)
469{
470 int index;
471
472 CHECK_INIT_POLLING;
473
474 index = _fd_to_index_and_lock(fd);
475 if (index < 0) {
476 return;
477 }
478 _free_index(index);
479 LeaveCriticalSection(&_poll_fd[index].mutex);
480}
481
482/*
483 * The functions below perform various conversions between fd, handle and OVERLAPPED
484 */
485struct winfd fd_to_winfd(int fd)
486{
487 int i;
488 struct winfd wfd;
489
490 CHECK_INIT_POLLING;
491
492 if (fd <= 0)
493 return INVALID_WINFD;
494
495 for (i=0; i<MAX_FDS; i++) {
496 if (poll_fd[i].fd == fd) {
497 EnterCriticalSection(&_poll_fd[i].mutex);
498 // fd might have been deleted before we got to critical
499 if (poll_fd[i].fd != fd) {
500 LeaveCriticalSection(&_poll_fd[i].mutex);
501 continue;
502 }
503 memcpy(&wfd, &poll_fd[i], sizeof(struct winfd));
504 LeaveCriticalSection(&_poll_fd[i].mutex);
505 return wfd;
506 }
507 }
508 return INVALID_WINFD;
509}
510
511struct winfd handle_to_winfd(HANDLE handle)
512{
513 int i;
514 struct winfd wfd;
515
516 CHECK_INIT_POLLING;
517
518 if ((handle == 0) || (handle == INVALID_HANDLE_VALUE))
519 return INVALID_WINFD;
520
521 for (i=0; i<MAX_FDS; i++) {
522 if (poll_fd[i].handle == handle) {
523 EnterCriticalSection(&_poll_fd[i].mutex);
524 // fd might have been deleted before we got to critical
525 if (poll_fd[i].handle != handle) {
526 LeaveCriticalSection(&_poll_fd[i].mutex);
527 continue;
528 }
529 memcpy(&wfd, &poll_fd[i], sizeof(struct winfd));
530 LeaveCriticalSection(&_poll_fd[i].mutex);
531 return wfd;
532 }
533 }
534 return INVALID_WINFD;
535}
536
537struct winfd overlapped_to_winfd(OVERLAPPED* overlapped)
538{
539 int i;
540 struct winfd wfd;
541
542 CHECK_INIT_POLLING;
543
544 if (overlapped == NULL)
545 return INVALID_WINFD;
546
547 for (i=0; i<MAX_FDS; i++) {
548 if (poll_fd[i].overlapped == overlapped) {
549 EnterCriticalSection(&_poll_fd[i].mutex);
550 // fd might have been deleted before we got to critical
551 if (poll_fd[i].overlapped != overlapped) {
552 LeaveCriticalSection(&_poll_fd[i].mutex);
553 continue;
554 }
555 memcpy(&wfd, &poll_fd[i], sizeof(struct winfd));
556 LeaveCriticalSection(&_poll_fd[i].mutex);
557 return wfd;
558 }
559 }
560 return INVALID_WINFD;
561}
562
563/*
564 * POSIX poll equivalent, using Windows OVERLAPPED
565 * Currently, this function only accepts one of POLLIN or POLLOUT per fd
566 * (but you can create multiple fds from the same handle for read and write)
567 */
568int usbi_poll(struct pollfd *fds, unsigned int nfds, int timeout)
569{
570 unsigned i;
571 int index, object_index, triggered;
572 HANDLE *handles_to_wait_on;
573 int *handle_to_index;
574 DWORD nb_handles_to_wait_on = 0;
575 DWORD ret;
576
577#if defined(DYNAMIC_FDS)
578 DWORD nb_extra_handles = 0;
579 unsigned j;
580
581 // To address the possibility of missing new fds between the time the new
582 // pollable fd set is assembled, and the ResetEvent() call below, an
583 // additional new_fd[] HANDLE table is used for any new fd that was created
584 // since the last call to poll (see below)
585 ResetEvent(fd_update);
586
587 // At this stage, any new fd creation will be detected through the fd_update
588 // event notification, and any previous creation that we may have missed
589 // will be picked up through the existing new_fd[] table.
590#endif
591
592 CHECK_INIT_POLLING;
593
594 triggered = 0;
595 handles_to_wait_on = malloc((nfds+1)*sizeof(HANDLE)); // +1 for fd_update
596 handle_to_index = malloc(nfds*sizeof(int));
597 if ((handles_to_wait_on == NULL) || (handle_to_index == NULL)) {
598 errno = ENOMEM;
599 triggered = -1;
600 goto poll_exit;
601 }
602
603 for (i = 0; i < nfds; ++i) {
604 fds[i].revents = 0;
605
606 // Only one of POLLIN or POLLOUT can be selected with this version of poll (not both)
607 if ((fds[i].events & ~POLLIN) && (!(fds[i].events & POLLOUT))) {
608 fds[i].revents |= POLLERR;
609 errno = EACCES;
610 usbi_warn(NULL, "unsupported set of events");
611 triggered = -1;
612 goto poll_exit;
613 }
614
615 index = _fd_to_index_and_lock(fds[i].fd);
616 poll_dbg("fd[%d]=%d: (overlapped=%p) got events %04X", i, poll_fd[index].fd, poll_fd[index].overlapped, fds[i].events);
617
618 if ( (index < 0) || (poll_fd[index].handle == INVALID_HANDLE_VALUE)
619 || (poll_fd[index].handle == 0) || (poll_fd[index].overlapped == NULL)) {
620 fds[i].revents |= POLLNVAL | POLLERR;
621 errno = EBADF;
622 if (index >= 0) {
623 LeaveCriticalSection(&_poll_fd[index].mutex);
624 }
625 usbi_warn(NULL, "invalid fd");
626 triggered = -1;
627 goto poll_exit;
628 }
629
630 // IN or OUT must match our fd direction
631 if ((fds[i].events & POLLIN) && (poll_fd[index].rw != RW_READ)) {
632 fds[i].revents |= POLLNVAL | POLLERR;
633 errno = EBADF;
634 usbi_warn(NULL, "attempted POLLIN on fd without READ access");
635 LeaveCriticalSection(&_poll_fd[index].mutex);
636 triggered = -1;
637 goto poll_exit;
638 }
639
640 if ((fds[i].events & POLLOUT) && (poll_fd[index].rw != RW_WRITE)) {
641 fds[i].revents |= POLLNVAL | POLLERR;
642 errno = EBADF;
643 usbi_warn(NULL, "attempted POLLOUT on fd without WRITE access");
644 LeaveCriticalSection(&_poll_fd[index].mutex);
645 triggered = -1;
646 goto poll_exit;
647 }
648
649 // The following macro only works if overlapped I/O was reported pending
650 if ( (HasOverlappedIoCompleted(poll_fd[index].overlapped))
651 || (HasOverlappedIoCompletedSync(poll_fd[index].overlapped)) ) {
652 poll_dbg(" completed");
653 // checks above should ensure this works:
654 fds[i].revents = fds[i].events;
655 triggered++;
656 } else {
657 handles_to_wait_on[nb_handles_to_wait_on] = poll_fd[index].overlapped->hEvent;
658 handle_to_index[nb_handles_to_wait_on] = i;
659#if defined(DYNAMIC_FDS)
660 // If this fd from the poll set is also part of the new_fd event handle table, remove it
661 usbi_mutex_lock(&new_fd_mutex);
662 for (j=0; j<nb_new_fds; j++) {
663 if (handles_to_wait_on[nb_handles_to_wait_on] == new_fd[j]) {
664 new_fd[j] = INVALID_HANDLE_VALUE;
665 break;
666 }
667 }
668 usbi_mutex_unlock(&new_fd_mutex);
669#endif
670 nb_handles_to_wait_on++;
671 }
672 LeaveCriticalSection(&_poll_fd[index].mutex);
673 }
674#if defined(DYNAMIC_FDS)
675 // At this stage, new_fd[] should only contain events from fds that
676 // have been added since the last call to poll, but are not (yet) part
677 // of the pollable fd set. Typically, these would be from fds that have
678 // been created between the construction of the fd set and the calling
679 // of poll.
680 // Event if we won't be able to return usable poll data on these events,
681 // make sure we monitor them to return an EINTR code
682 usbi_mutex_lock(&new_fd_mutex); // We could probably do without
683 for (i=0; i<nb_new_fds; i++) {
684 if (new_fd[i] != INVALID_HANDLE_VALUE) {
685 handles_to_wait_on[nb_handles_to_wait_on++] = new_fd[i];
686 nb_extra_handles++;
687 }
688 }
689 usbi_mutex_unlock(&new_fd_mutex);
690 poll_dbg("dynamic_fds: added %d extra handles", nb_extra_handles);
691#endif
692
693 // If nothing was triggered, wait on all fds that require it
694 if ((timeout != 0) && (triggered == 0) && (nb_handles_to_wait_on != 0)) {
695#if defined(DYNAMIC_FDS)
696 // Register for fd update notifications
697 handles_to_wait_on[nb_handles_to_wait_on++] = fd_update;
698 nb_extra_handles++;
699#endif
700 if (timeout < 0) {
701 poll_dbg("starting infinite wait for %d handles...", (int)nb_handles_to_wait_on);
702 } else {
703 poll_dbg("starting %d ms wait for %d handles...", timeout, (int)nb_handles_to_wait_on);
704 }
705 ret = WaitForMultipleObjects(nb_handles_to_wait_on, handles_to_wait_on,
706 FALSE, (timeout<0)?INFINITE:(DWORD)timeout);
707 object_index = ret-WAIT_OBJECT_0;
708 if ((object_index >= 0) && ((DWORD)object_index < nb_handles_to_wait_on)) {
709#if defined(DYNAMIC_FDS)
710 if ((DWORD)object_index >= (nb_handles_to_wait_on-nb_extra_handles)) {
711 // Detected fd update => flag a poll interruption
712 if ((DWORD)object_index == (nb_handles_to_wait_on-1))
713 poll_dbg(" dynamic_fds: fd_update event");
714 else
715 poll_dbg(" dynamic_fds: new fd I/O event");
716 errno = EINTR;
717 triggered = -1;
718 goto poll_exit;
719 }
720#endif
721 poll_dbg(" completed after wait");
722 i = handle_to_index[object_index];
723 index = _fd_to_index_and_lock(fds[i].fd);
724 fds[i].revents = fds[i].events;
725 triggered++;
726 if (index >= 0) {
727 LeaveCriticalSection(&_poll_fd[index].mutex);
728 }
729 } else if (ret == WAIT_TIMEOUT) {
730 poll_dbg(" timed out");
731 triggered = 0; // 0 = timeout
732 } else {
733 errno = EIO;
734 triggered = -1; // error
735 }
736 }
737
738poll_exit:
739 if (handles_to_wait_on != NULL) {
740 free(handles_to_wait_on);
741 }
742 if (handle_to_index != NULL) {
743 free(handle_to_index);
744 }
745#if defined(DYNAMIC_FDS)
746 usbi_mutex_lock(&new_fd_mutex);
747 nb_new_fds = 0;
748 usbi_mutex_unlock(&new_fd_mutex);
749#endif
750 return triggered;
751}
752
753/*
754 * close a fake pipe fd
755 */
756int usbi_close(int fd)
757{
758 int index;
759 int r = -1;
760
761 CHECK_INIT_POLLING;
762
763 index = _fd_to_index_and_lock(fd);
764
765 if (index < 0) {
766 errno = EBADF;
767 } else {
768 if (poll_fd[index].overlapped != NULL) {
769 // Must be a different event for each end of the pipe
770 CloseHandle(poll_fd[index].overlapped->hEvent);
771 free(poll_fd[index].overlapped);
772 }
773 if (CloseHandle(poll_fd[index].handle) == 0) {
774 errno = EIO;
775 } else {
776 r = 0;
777 }
778 poll_fd[index] = INVALID_WINFD;
779 LeaveCriticalSection(&_poll_fd[index].mutex);
780 }
781 return r;
782}
783
784/*
785 * synchronous write for fake "pipe" signaling
786 */
787ssize_t usbi_write(int fd, const void *buf, size_t count)
788{
789 int index;
790
791 CHECK_INIT_POLLING;
792
793 if (count != sizeof(unsigned char)) {
794 usbi_err(NULL, "this function should only used for signaling");
795 return -1;
796 }
797
798 index = _fd_to_index_and_lock(fd);
799
800 if ( (index < 0) || (poll_fd[index].overlapped == NULL) ) {
801 errno = EBADF;
802 if (index >= 0) {
803 LeaveCriticalSection(&_poll_fd[index].mutex);
804 }
805 return -1;
806 }
807
808 poll_dbg("set pipe event (fd = %d, thread = %08X)", index, GetCurrentThreadId());
809 SetEvent(poll_fd[index].overlapped->hEvent);
810 poll_fd[index].overlapped->Internal = STATUS_WAIT_0;
811 // If two threads write on the pipe at the same time, we need to
812 // process two separate reads => use the overlapped as a counter
813 poll_fd[index].overlapped->InternalHigh++;
814
815 LeaveCriticalSection(&_poll_fd[index].mutex);
816 return sizeof(unsigned char);
817}
818
819/*
820 * synchronous read for fake "pipe" signaling
821 */
822ssize_t usbi_read(int fd, void *buf, size_t count)
823{
824 int index;
825 ssize_t r = -1;
826
827 CHECK_INIT_POLLING;
828
829 if (count != sizeof(unsigned char)) {
830 usbi_err(NULL, "this function should only used for signaling");
831 return -1;
832 }
833
834 index = _fd_to_index_and_lock(fd);
835
836 if (index < 0) {
837 errno = EBADF;
838 return -1;
839 }
840
841 if (WaitForSingleObject(poll_fd[index].overlapped->hEvent, INFINITE) != WAIT_OBJECT_0) {
842 usbi_warn(NULL, "waiting for event failed: %d", (int)GetLastError());
843 errno = EIO;
844 goto out;
845 }
846
847 poll_dbg("clr pipe event (fd = %d, thread = %08X)", index, GetCurrentThreadId());
848 poll_fd[index].overlapped->InternalHigh--;
849 // Don't reset unless we don't have any more events to process
850 if (poll_fd[index].overlapped->InternalHigh <= 0) {
851 ResetEvent(poll_fd[index].overlapped->hEvent);
852 poll_fd[index].overlapped->Internal = STATUS_PENDING;
853 }
854
855 r = sizeof(unsigned char);
856
857out:
858 LeaveCriticalSection(&_poll_fd[index].mutex);
859 return r;
860}
diff --git a/include/libusb-1.0/os/poll_windows.h b/include/libusb-1.0/os/poll_windows.h
deleted file mode 100644
index a9e3e90..0000000
--- a/include/libusb-1.0/os/poll_windows.h
+++ /dev/null
@@ -1,120 +0,0 @@
1/*
2 * Windows compat: POSIX compatibility wrapper
3 * Copyright (C) 2009-2010 Pete Batard <pbatard@gmail.com>
4 * With contributions from Michael Plante, Orin Eman et al.
5 * Parts of poll implementation from libusb-win32, by Stephan Meyer et al.
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 *
21 */
22#pragma once
23
24#if defined(_MSC_VER)
25// disable /W4 MSVC warnings that are benign
26#pragma warning(disable:4127) // conditional expression is constant
27#endif
28
29// Uncomment to have poll return with EINTR as soon as a new transfer (fd) is added
30// This should result in a LIBUSB_ERROR_INTERRUPTED being returned by libusb calls,
31// which should give the app an opportunity to resubmit a new fd set.
32//#define DYNAMIC_FDS
33
34// Handle synchronous completion through the overlapped structure
35#if !defined(STATUS_REPARSE) // reuse the REPARSE status code
36#define STATUS_REPARSE ((LONG)0x00000104L)
37#endif
38#define STATUS_COMPLETED_SYNCHRONOUSLY STATUS_REPARSE
39#define HasOverlappedIoCompletedSync(lpOverlapped) (((DWORD)(lpOverlapped)->Internal) == STATUS_COMPLETED_SYNCHRONOUSLY)
40
41enum windows_version {
42 WINDOWS_UNSUPPORTED,
43 WINDOWS_XP,
44 WINDOWS_2003, // also includes XP 64
45 WINDOWS_VISTA_AND_LATER,
46};
47extern enum windows_version windows_version;
48
49#define MAX_FDS 256
50
51#define POLLIN 0x0001 /* There is data to read */
52#define POLLPRI 0x0002 /* There is urgent data to read */
53#define POLLOUT 0x0004 /* Writing now will not block */
54#define POLLERR 0x0008 /* Error condition */
55#define POLLHUP 0x0010 /* Hung up */
56#define POLLNVAL 0x0020 /* Invalid request: fd not open */
57
58struct pollfd {
59 int fd; /* file descriptor */
60 short events; /* requested events */
61 short revents; /* returned events */
62};
63
64typedef unsigned int nfds_t;
65
66// access modes
67enum rw_type {
68 RW_NONE,
69 RW_READ,
70 RW_WRITE,
71};
72
73// fd struct that can be used for polling on Windows
74struct winfd {
75 int fd; // what's exposed to libusb core
76 HANDLE handle; // what we need to attach overlapped to the I/O op, so we can poll it
77 OVERLAPPED* overlapped; // what will report our I/O status
78 enum rw_type rw; // I/O transfer direction: read *XOR* write (NOT BOTH)
79};
80extern const struct winfd INVALID_WINFD;
81
82int usbi_pipe(int pipefd[2]);
83int usbi_poll(struct pollfd *fds, unsigned int nfds, int timeout);
84ssize_t usbi_write(int fd, const void *buf, size_t count);
85ssize_t usbi_read(int fd, void *buf, size_t count);
86int usbi_close(int fd);
87
88void init_polling(void);
89void exit_polling(void);
90struct winfd usbi_create_fd(HANDLE handle, int access_mode);
91void usbi_free_fd(int fd);
92struct winfd fd_to_winfd(int fd);
93struct winfd handle_to_winfd(HANDLE handle);
94struct winfd overlapped_to_winfd(OVERLAPPED* overlapped);
95
96/*
97 * Timeval operations
98 */
99#if defined(DDKBUILD)
100#include <winsock.h> // defines timeval functions on DDK
101#endif
102
103#if !defined(TIMESPEC_TO_TIMEVAL)
104#define TIMESPEC_TO_TIMEVAL(tv, ts) { \
105 (tv)->tv_sec = (long)(ts)->tv_sec; \
106 (tv)->tv_usec = (long)(ts)->tv_nsec / 1000; \
107}
108#endif
109#if !defined(timersub)
110#define timersub(a, b, result) \
111do { \
112 (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
113 (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \
114 if ((result)->tv_usec < 0) { \
115 --(result)->tv_sec; \
116 (result)->tv_usec += 1000000; \
117 } \
118} while (0)
119#endif
120
diff --git a/include/libusb-1.0/os/threads_posix.h b/include/libusb-1.0/os/threads_posix.h
deleted file mode 100644
index dc558d4..0000000
--- a/include/libusb-1.0/os/threads_posix.h
+++ /dev/null
@@ -1,46 +0,0 @@
1/*
2 * libusb synchronization using POSIX Threads
3 *
4 * Copyright (C) 2010 Peter Stuge <peter@stuge.se>
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#ifndef __LIBUSB_THREADS_POSIX_H__
22#define __LIBUSB_THREADS_POSIX_H__
23
24#include <pthread.h>
25
26#define usbi_mutex_static_t pthread_mutex_t
27#define USBI_MUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER
28#define usbi_mutex_static_lock pthread_mutex_lock
29#define usbi_mutex_static_unlock pthread_mutex_unlock
30
31#define usbi_mutex_t pthread_mutex_t
32#define usbi_mutex_init pthread_mutex_init
33#define usbi_mutex_lock pthread_mutex_lock
34#define usbi_mutex_unlock pthread_mutex_unlock
35#define usbi_mutex_trylock pthread_mutex_trylock
36#define usbi_mutex_destroy pthread_mutex_destroy
37
38#define usbi_cond_t pthread_cond_t
39#define usbi_cond_init pthread_cond_init
40#define usbi_cond_wait pthread_cond_wait
41#define usbi_cond_timedwait pthread_cond_timedwait
42#define usbi_cond_broadcast pthread_cond_broadcast
43#define usbi_cond_destroy pthread_cond_destroy
44#define usbi_cond_signal pthread_cond_signal
45
46#endif /* __LIBUSB_THREADS_POSIX_H__ */
diff --git a/include/libusb-1.0/os/threads_windows.c b/include/libusb-1.0/os/threads_windows.c
deleted file mode 100644
index 8a29920..0000000
--- a/include/libusb-1.0/os/threads_windows.c
+++ /dev/null
@@ -1,208 +0,0 @@
1/*
2 * libusb synchronization on Microsoft Windows
3 *
4 * Copyright (C) 2010 Michael Plante <michael.plante@gmail.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 <objbase.h>
23#include <errno.h>
24#include <stdarg.h>
25
26#include "libusbi.h"
27
28
29int usbi_mutex_init(usbi_mutex_t *mutex,
30 const usbi_mutexattr_t *attr) {
31 if(! mutex) return ((errno=EINVAL));
32 *mutex = CreateMutex(NULL, FALSE, NULL);
33 if(!*mutex) return ((errno=ENOMEM));
34 return 0;
35}
36int usbi_mutex_destroy(usbi_mutex_t *mutex) {
37 // It is not clear if CloseHandle failure is due to failure to unlock.
38 // If so, this should be errno=EBUSY.
39 if(!mutex || !CloseHandle(*mutex)) return ((errno=EINVAL));
40 *mutex = NULL;
41 return 0;
42}
43int usbi_mutex_trylock(usbi_mutex_t *mutex) {
44 DWORD result;
45 if(!mutex) return ((errno=EINVAL));
46 result = WaitForSingleObject(*mutex, 0);
47 if(result == WAIT_OBJECT_0 || result == WAIT_ABANDONED)
48 return 0; // acquired (ToDo: check that abandoned is ok)
49 if(result == WAIT_TIMEOUT)
50 return ((errno=EBUSY));
51 return ((errno=EINVAL)); // don't know how this would happen
52 // so don't know proper errno
53}
54int usbi_mutex_lock(usbi_mutex_t *mutex) {
55 DWORD result;
56 if(!mutex) return ((errno=EINVAL));
57 result = WaitForSingleObject(*mutex, INFINITE);
58 if(result == WAIT_OBJECT_0 || result == WAIT_ABANDONED)
59 return 0; // acquired (ToDo: check that abandoned is ok)
60 return ((errno=EINVAL)); // don't know how this would happen
61 // so don't know proper errno
62}
63int usbi_mutex_unlock(usbi_mutex_t *mutex) {
64 if(!mutex) return ((errno=EINVAL));
65 if(!ReleaseMutex(*mutex)) return ((errno=EPERM ));
66 return 0;
67}
68
69int usbi_mutex_static_lock(usbi_mutex_static_t *mutex) {
70 if(!mutex) return ((errno=EINVAL));
71 while (InterlockedExchange((LONG *)mutex, 1) == 1) {
72 SleepEx(0, TRUE);
73 }
74 return 0;
75}
76int usbi_mutex_static_unlock(usbi_mutex_static_t *mutex) {
77 if(!mutex) return ((errno=EINVAL));
78 *mutex = 0;
79 return 0;
80}
81
82
83
84int usbi_cond_init(usbi_cond_t *cond,
85 const usbi_condattr_t *attr) {
86 if(!cond) return ((errno=EINVAL));
87 list_init(&cond->waiters );
88 list_init(&cond->not_waiting);
89 return 0;
90}
91int usbi_cond_destroy(usbi_cond_t *cond) {
92 // This assumes no one is using this anymore. The check MAY NOT BE safe.
93 struct usbi_cond_perthread *pos, *prev_pos = NULL;
94 if(!cond) return ((errno=EINVAL));
95 if(!list_empty(&cond->waiters)) return ((errno=EBUSY )); // (!see above!)
96 list_for_each_entry(pos, &cond->not_waiting, list, struct usbi_cond_perthread) {
97 free(prev_pos);
98 list_del(&pos->list);
99 prev_pos = pos;
100 }
101 free(prev_pos);
102 prev_pos = pos = NULL;
103
104 return 0;
105}
106
107int usbi_cond_broadcast(usbi_cond_t *cond) {
108 // Assumes mutex is locked; this is not in keeping with POSIX spec, but
109 // libusb does this anyway, so we simplify by not adding more sync
110 // primitives to the CV definition!
111 int fail = 0;
112 struct usbi_cond_perthread *pos;
113 if(!cond) return ((errno=EINVAL));
114 list_for_each_entry(pos, &cond->waiters, list, struct usbi_cond_perthread) {
115 if(!SetEvent(pos->event))
116 fail = 1;
117 }
118 // The wait function will remove its respective item from the list.
119 return fail ? ((errno=EINVAL)) : 0;
120}
121int usbi_cond_signal(usbi_cond_t *cond) {
122 // Assumes mutex is locked; this is not in keeping with POSIX spec, but
123 // libusb does this anyway, so we simplify by not adding more sync
124 // primitives to the CV definition!
125 struct usbi_cond_perthread *pos;
126 if(!cond) return ((errno=EINVAL));
127 if(list_empty(&cond->waiters)) return 0; // no one to wakeup.
128 pos = list_entry(&cond->waiters.next, struct usbi_cond_perthread, list);
129 // The wait function will remove its respective item from the list.
130 return SetEvent(pos->event) ? 0 : ((errno=EINVAL));
131}
132static int __inline usbi_cond_intwait(usbi_cond_t *cond,
133 usbi_mutex_t *mutex,
134 DWORD timeout_ms) {
135 struct usbi_cond_perthread *pos;
136 int found = 0, r;
137 DWORD r2,tid = GetCurrentThreadId();
138 if(!cond || !mutex) return ((errno=EINVAL));
139 list_for_each_entry(pos, &cond->not_waiting, list, struct usbi_cond_perthread) {
140 if(tid == pos->tid) {
141 found = 1;
142 break;
143 }
144 }
145 if(!found) {
146 pos = malloc(sizeof(struct usbi_cond_perthread));
147 if(!pos) return ((errno=ENOMEM)); // This errno is not POSIX-allowed.
148 pos->tid = tid;
149 pos->event = CreateEvent(NULL, FALSE, FALSE, NULL); // auto-reset.
150 if(!pos->event) {
151 free(pos);
152 return ((errno=ENOMEM));
153 }
154 list_add(&pos->list, &cond->not_waiting);
155 }
156
157 list_del(&pos->list); // remove from not_waiting list.
158 list_add(&pos->list, &cond->waiters);
159
160 r = usbi_mutex_unlock(mutex);
161 if(r) return r;
162 r2 = WaitForSingleObject(pos->event, timeout_ms);
163 r = usbi_mutex_lock(mutex);
164 if(r) return r;
165
166 list_del(&pos->list);
167 list_add(&pos->list, &cond->not_waiting);
168
169 if(r2 == WAIT_TIMEOUT) return ((errno=ETIMEDOUT));
170
171 return 0;
172}
173// N.B.: usbi_cond_*wait() can also return ENOMEM, even though pthread_cond_*wait cannot!
174int usbi_cond_wait(usbi_cond_t *cond, usbi_mutex_t *mutex) {
175 return usbi_cond_intwait(cond, mutex, INFINITE);
176}
177int usbi_cond_timedwait(usbi_cond_t *cond,
178 usbi_mutex_t *mutex,
179 const struct timespec *abstime) {
180 FILETIME filetime;
181 ULARGE_INTEGER rtime;
182 struct timeval targ_time, cur_time, delta_time;
183 struct timespec cur_time_ns;
184 DWORD millis;
185 extern const uint64_t epoch_time;
186
187 GetSystemTimeAsFileTime(&filetime);
188 rtime.LowPart = filetime.dwLowDateTime;
189 rtime.HighPart = filetime.dwHighDateTime;
190 rtime.QuadPart -= epoch_time;
191 cur_time_ns.tv_sec = (long)(rtime.QuadPart / 10000000);
192 cur_time_ns.tv_nsec = (long)((rtime.QuadPart % 10000000)*100);
193 TIMESPEC_TO_TIMEVAL(&cur_time, &cur_time_ns);
194
195 TIMESPEC_TO_TIMEVAL(&targ_time, abstime);
196 timersub(&targ_time, &cur_time, &delta_time);
197 if(delta_time.tv_sec < 0) // abstime already passed?
198 millis = 0;
199 else {
200 millis = delta_time.tv_usec/1000;
201 millis += delta_time.tv_sec *1000;
202 if (delta_time.tv_usec % 1000) // round up to next millisecond
203 millis++;
204 }
205
206 return usbi_cond_intwait(cond, mutex, millis);
207}
208
diff --git a/include/libusb-1.0/os/threads_windows.h b/include/libusb-1.0/os/threads_windows.h
deleted file mode 100644
index 2cd1867..0000000
--- a/include/libusb-1.0/os/threads_windows.h
+++ /dev/null
@@ -1,84 +0,0 @@
1/*
2 * libusb synchronization on Microsoft Windows
3 *
4 * Copyright (C) 2010 Michael Plante <michael.plante@gmail.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#ifndef __LIBUSB_THREADS_WINDOWS_H__
22#define __LIBUSB_THREADS_WINDOWS_H__
23
24#define usbi_mutex_static_t volatile LONG
25#define USBI_MUTEX_INITIALIZER 0
26
27#define usbi_mutex_t HANDLE
28
29struct usbi_cond_perthread {
30 struct list_head list;
31 DWORD tid;
32 HANDLE event;
33};
34struct usbi_cond_t_ {
35 // Every time a thread touches the CV, it winds up in one of these lists.
36 // It stays there until the CV is destroyed, even if the thread
37 // terminates.
38 struct list_head waiters;
39 struct list_head not_waiting;
40};
41typedef struct usbi_cond_t_ usbi_cond_t;
42
43// We *were* getting timespec from pthread.h:
44#if (!defined(HAVE_STRUCT_TIMESPEC) && !defined(_TIMESPEC_DEFINED))
45#define HAVE_STRUCT_TIMESPEC 1
46#define _TIMESPEC_DEFINED 1
47struct timespec {
48 long tv_sec;
49 long tv_nsec;
50};
51#endif /* HAVE_STRUCT_TIMESPEC | _TIMESPEC_DEFINED */
52
53// We *were* getting ETIMEDOUT from pthread.h:
54#ifndef ETIMEDOUT
55# define ETIMEDOUT 10060 /* This is the value in winsock.h. */
56#endif
57
58#define usbi_mutexattr_t void
59#define usbi_condattr_t void
60
61
62int usbi_mutex_static_lock(usbi_mutex_static_t *mutex);
63int usbi_mutex_static_unlock(usbi_mutex_static_t *mutex);
64
65
66int usbi_mutex_init(usbi_mutex_t *mutex,
67 const usbi_mutexattr_t *attr);
68int usbi_mutex_lock(usbi_mutex_t *mutex);
69int usbi_mutex_unlock(usbi_mutex_t *mutex);
70int usbi_mutex_trylock(usbi_mutex_t *mutex);
71int usbi_mutex_destroy(usbi_mutex_t *mutex);
72
73int usbi_cond_init(usbi_cond_t *cond,
74 const usbi_condattr_t *attr);
75int usbi_cond_destroy(usbi_cond_t *cond);
76int usbi_cond_wait(usbi_cond_t *cond, usbi_mutex_t *mutex);
77int usbi_cond_timedwait(usbi_cond_t *cond,
78 usbi_mutex_t *mutex,
79 const struct timespec *abstime);
80int usbi_cond_broadcast(usbi_cond_t *cond);
81int usbi_cond_signal(usbi_cond_t *cond);
82
83#endif /* __LIBUSB_THREADS_WINDOWS_H__ */
84
diff --git a/include/libusb-1.0/os/windows_usb.c b/include/libusb-1.0/os/windows_usb.c
deleted file mode 100644
index e37932a..0000000
--- a/include/libusb-1.0/os/windows_usb.c
+++ /dev/null
@@ -1,4185 +0,0 @@
1/*
2 * windows backend for libusb 1.0
3 * Copyright (c) 2009-2010 Pete Batard <pbatard@gmail.com>
4 * With contributions from Michael Plante, Orin Eman et al.
5 * Parts of this code adapted from libusb-win32-v1 by Stephan Meyer
6 * HID Reports IOCTLs inspired from HIDAPI by Alan Ott, Signal 11 Software
7 * Major code testing contribution by Xiaofan Chen
8 *
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
13 *
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
18 *
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 */
23
24// COMPILATION OPTIONS:
25// - Should libusb automatically claim (and release) the interfaces it requires?
26#define AUTO_CLAIM
27// - Forces instant overlapped completion on timeouts: can prevents extensive
28// wait in poll, after a timeout, but might affect subsequent API calls.
29// ***USE AT YOUR OWN RISKS***
30//#define FORCE_INSTANT_TIMEOUTS
31
32#include <config.h>
33#include <windows.h>
34#include <setupapi.h>
35#include <ctype.h>
36#include <errno.h>
37#include <fcntl.h>
38#include <process.h>
39#include <stdio.h>
40#include <inttypes.h>
41#include <objbase.h> // for string to GUID conv. requires libole32.a
42#include <winioctl.h>
43
44#include <libusbi.h>
45#include "poll_windows.h"
46#include "windows_usb.h"
47
48// The following prevents "banned API" errors when using the MS's WDK OACR/Prefast
49#if defined(_PREFAST_)
50#pragma warning(disable:28719)
51#endif
52
53// The 2 macros below are used in conjunction with safe loops.
54#define LOOP_CHECK(fcall) { r=fcall; if (r != LIBUSB_SUCCESS) continue; }
55#define LOOP_BREAK(err) { r=err; continue; }
56
57extern void usbi_fd_notification(struct libusb_context *ctx);
58
59// Helper prototypes
60static int windows_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian);
61static int windows_clock_gettime(int clk_id, struct timespec *tp);
62unsigned __stdcall windows_clock_gettime_threaded(void* param);
63// WinUSB API prototypes
64static int winusb_init(struct libusb_context *ctx);
65static int winusb_exit(void);
66static int winusb_open(struct libusb_device_handle *dev_handle);
67static void winusb_close(struct libusb_device_handle *dev_handle);
68static int winusb_claim_interface(struct libusb_device_handle *dev_handle, int iface);
69static int winusb_release_interface(struct libusb_device_handle *dev_handle, int iface);
70static int winusb_submit_control_transfer(struct usbi_transfer *itransfer);
71static int winusb_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting);
72static int winusb_submit_bulk_transfer(struct usbi_transfer *itransfer);
73static int winusb_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint);
74static int winusb_abort_transfers(struct usbi_transfer *itransfer);
75static int winusb_abort_control(struct usbi_transfer *itransfer);
76static int winusb_reset_device(struct libusb_device_handle *dev_handle);
77static int winusb_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size);
78// HID API prototypes
79static int hid_init(struct libusb_context *ctx);
80static int hid_exit(void);
81static int hid_open(struct libusb_device_handle *dev_handle);
82static void hid_close(struct libusb_device_handle *dev_handle);
83static int hid_claim_interface(struct libusb_device_handle *dev_handle, int iface);
84static int hid_release_interface(struct libusb_device_handle *dev_handle, int iface);
85static int hid_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting);
86static int hid_submit_control_transfer(struct usbi_transfer *itransfer);
87static int hid_submit_bulk_transfer(struct usbi_transfer *itransfer);
88static int hid_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint);
89static int hid_abort_transfers(struct usbi_transfer *itransfer);
90static int hid_reset_device(struct libusb_device_handle *dev_handle);
91static int hid_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size);
92// Composite API prototypes
93static int composite_init(struct libusb_context *ctx);
94static int composite_exit(void);
95static int composite_open(struct libusb_device_handle *dev_handle);
96static void composite_close(struct libusb_device_handle *dev_handle);
97static int composite_claim_interface(struct libusb_device_handle *dev_handle, int iface);
98static int composite_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting);
99static int composite_release_interface(struct libusb_device_handle *dev_handle, int iface);
100static int composite_submit_control_transfer(struct usbi_transfer *itransfer);
101static int composite_submit_bulk_transfer(struct usbi_transfer *itransfer);
102static int composite_submit_iso_transfer(struct usbi_transfer *itransfer);
103static int composite_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint);
104static int composite_abort_transfers(struct usbi_transfer *itransfer);
105static int composite_abort_control(struct usbi_transfer *itransfer);
106static int composite_reset_device(struct libusb_device_handle *dev_handle);
107static int composite_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size);
108
109
110// Global variables
111struct windows_hcd_priv* hcd_root = NULL;
112uint64_t hires_frequency, hires_ticks_to_ps;
113const uint64_t epoch_time = UINT64_C(116444736000000000); // 1970.01.01 00:00:000 in MS Filetime
114enum windows_version windows_version = WINDOWS_UNSUPPORTED;
115// Concurrency
116static int concurrent_usage = -1;
117#if defined(AUTO_CLAIM)
118usbi_mutex_t autoclaim_lock;
119#endif
120// Timer thread
121// NB: index 0 is for monotonic and 1 is for the thread exit event
122HANDLE timer_thread = NULL;
123HANDLE timer_mutex = NULL;
124struct timespec timer_tp;
125volatile LONG request_count[2] = {0, 1}; // last one must be > 0
126HANDLE timer_request[2] = { NULL, NULL };
127HANDLE timer_response = NULL;
128// API globals
129bool api_winusb_available = false;
130#define CHECK_WINUSB_AVAILABLE do { if (!api_winusb_available) return LIBUSB_ERROR_ACCESS; } while (0)
131bool api_hid_available = false;
132#define CHECK_HID_AVAILABLE do { if (!api_hid_available) return LIBUSB_ERROR_ACCESS; } while (0)
133
134
135/*
136 * Converts a WCHAR string to UTF8 (allocate returned string)
137 * Returns NULL on error
138 */
139static char* wchar_to_utf8(LPCWSTR wstr)
140{
141 int size;
142 char* str;
143
144 // Find out the size we need to allocate for our converted string
145 size = wchar_to_utf8_ms(wstr, NULL, 0);
146 if (size <= 1) // An empty string would be size 1
147 return NULL;
148
149 if ((str = malloc(size)) == NULL)
150 return NULL;
151
152 if (wchar_to_utf8_ms(wstr, str, size) != size) {
153 safe_free(str);
154 return NULL;
155 }
156
157 return str;
158}
159
160static inline BOOLEAN guid_eq(const GUID *guid1, const GUID *guid2) {
161 if ((guid1 != NULL) && (guid2 != NULL)) {
162 return (memcmp(guid1, guid2, sizeof(GUID)) == 0);
163 }
164 return false;
165}
166
167#if 0
168static char* guid_to_string(const GUID guid)
169{
170 static char guid_string[MAX_GUID_STRING_LENGTH];
171
172 sprintf(guid_string, "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
173 (unsigned int)guid.Data1, guid.Data2, guid.Data3,
174 guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3],
175 guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]);
176 return guid_string;
177}
178#endif
179
180/*
181 * Converts a windows error to human readable string
182 * uses retval as errorcode, or, if 0, use GetLastError()
183 */
184static char *windows_error_str(uint32_t retval)
185{
186static char err_string[ERR_BUFFER_SIZE];
187
188 DWORD size;
189 size_t i;
190 uint32_t error_code, format_error;
191
192 error_code = retval?retval:GetLastError();
193
194 safe_sprintf(err_string, ERR_BUFFER_SIZE, "[%d] ", error_code);
195
196 size = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, error_code,
197 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &err_string[safe_strlen(err_string)],
198 ERR_BUFFER_SIZE - (DWORD)safe_strlen(err_string), NULL);
199 if (size == 0) {
200 format_error = GetLastError();
201 if (format_error)
202 safe_sprintf(err_string, ERR_BUFFER_SIZE,
203 "Windows error code %u (FormatMessage error code %u)", error_code, format_error);
204 else
205 safe_sprintf(err_string, ERR_BUFFER_SIZE, "Unknown error code %u", error_code);
206 } else {
207 // Remove CR/LF terminators
208 for (i=safe_strlen(err_string)-1; ((err_string[i]==0x0A) || (err_string[i]==0x0D)); i--) {
209 err_string[i] = 0;
210 }
211 }
212 return err_string;
213}
214
215/*
216 * Sanitize Microsoft's paths: convert to uppercase, add prefix and fix backslashes.
217 * Return an allocated sanitized string or NULL on error.
218 */
219static char* sanitize_path(const char* path)
220{
221 const char root_prefix[] = "\\\\.\\";
222 size_t j, size, root_size;
223 char* ret_path = NULL;
224 size_t add_root = 0;
225
226 if (path == NULL)
227 return NULL;
228
229 size = safe_strlen(path)+1;
230 root_size = sizeof(root_prefix)-1;
231
232 // Microsoft indiscriminatly uses '\\?\', '\\.\', '##?#" or "##.#" for root prefixes.
233 if (!((size > 3) && (((path[0] == '\\') && (path[1] == '\\') && (path[3] == '\\')) ||
234 ((path[0] == '#') && (path[1] == '#') && (path[3] == '#'))))) {
235 add_root = root_size;
236 size += add_root;
237 }
238
239 if ((ret_path = (char*)calloc(size, 1)) == NULL)
240 return NULL;
241
242 safe_strcpy(&ret_path[add_root], size-add_root, path);
243
244 // Ensure consistancy with root prefix
245 for (j=0; j<root_size; j++)
246 ret_path[j] = root_prefix[j];
247
248 // Same goes for '\' and '#' after the root prefix. Ensure '#' is used
249 for(j=root_size; j<size; j++) {
250 ret_path[j] = (char)toupper((int)ret_path[j]); // Fix case too
251 if (ret_path[j] == '\\')
252 ret_path[j] = '#';
253 }
254
255 return ret_path;
256}
257
258/*
259 * Cfgmgr32 API functions
260 */
261static int Cfgmgr32_init(void)
262{
263 DLL_LOAD(Cfgmgr32.dll, CM_Get_Parent, TRUE);
264 DLL_LOAD(Cfgmgr32.dll, CM_Get_Child, TRUE);
265 DLL_LOAD(Cfgmgr32.dll, CM_Get_Sibling, TRUE);
266 DLL_LOAD(Cfgmgr32.dll, CM_Get_Device_IDA, TRUE);
267 DLL_LOAD(Cfgmgr32.dll, CM_Get_Device_IDW, TRUE);
268
269 return LIBUSB_SUCCESS;
270}
271
272/*
273 * enumerate interfaces for a specific GUID
274 *
275 * Parameters:
276 * dev_info: a pointer to a dev_info list
277 * dev_info_data: a pointer to an SP_DEVINFO_DATA to be filled (or NULL if not needed)
278 * guid: the GUID for which to retrieve interface details
279 * index: zero based index of the interface in the device info list
280 *
281 * Note: it is the responsibility of the caller to free the DEVICE_INTERFACE_DETAIL_DATA
282 * structure returned and call this function repeatedly using the same guid (with an
283 * incremented index starting at zero) until all interfaces have been returned.
284 */
285SP_DEVICE_INTERFACE_DETAIL_DATA *get_interface_details(struct libusb_context *ctx,
286 HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, GUID guid, unsigned index)
287{
288 SP_DEVICE_INTERFACE_DATA dev_interface_data;
289 SP_DEVICE_INTERFACE_DETAIL_DATA *dev_interface_details = NULL;
290 DWORD size;
291
292 if (index <= 0) {
293 *dev_info = SetupDiGetClassDevs(&guid, NULL, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE);
294 }
295 if (*dev_info == INVALID_HANDLE_VALUE) {
296 return NULL;
297 }
298
299 if (dev_info_data != NULL) {
300 dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
301 if (!SetupDiEnumDeviceInfo(*dev_info, index, dev_info_data)) {
302 if (GetLastError() != ERROR_NO_MORE_ITEMS) {
303 usbi_err(ctx, "Could not obtain device info data for index %u: %s",
304 index, windows_error_str(0));
305 }
306 SetupDiDestroyDeviceInfoList(*dev_info);
307 *dev_info = INVALID_HANDLE_VALUE;
308 return NULL;
309 }
310 }
311
312 dev_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
313 if (!SetupDiEnumDeviceInterfaces(*dev_info, NULL, &guid, index, &dev_interface_data)) {
314 if (GetLastError() != ERROR_NO_MORE_ITEMS) {
315 usbi_err(ctx, "Could not obtain interface data for index %u: %s",
316 index, windows_error_str(0));
317 }
318 SetupDiDestroyDeviceInfoList(*dev_info);
319 *dev_info = INVALID_HANDLE_VALUE;
320 return NULL;
321 }
322
323 // Read interface data (dummy + actual) to access the device path
324 if (!SetupDiGetDeviceInterfaceDetail(*dev_info, &dev_interface_data, NULL, 0, &size, NULL)) {
325 // The dummy call should fail with ERROR_INSUFFICIENT_BUFFER
326 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
327 usbi_err(ctx, "could not access interface data (dummy) for index %u: %s",
328 index, windows_error_str(0));
329 goto err_exit;
330 }
331 }
332 else {
333 usbi_err(ctx, "program assertion failed - http://msdn.microsoft.com/en-us/library/ms792901.aspx is wrong.");
334 goto err_exit;
335 }
336
337 if ((dev_interface_details = malloc(size)) == NULL) {
338 usbi_err(ctx, "could not allocate interface data for index %u.", index);
339 goto err_exit;
340 }
341
342 dev_interface_details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
343 if (!SetupDiGetDeviceInterfaceDetail(*dev_info, &dev_interface_data,
344 dev_interface_details, size, &size, NULL)) {
345 usbi_err(ctx, "could not access interface data (actual) for index %u: %s",
346 index, windows_error_str(0));
347 }
348
349 return dev_interface_details;
350
351err_exit:
352 SetupDiDestroyDeviceInfoList(*dev_info);
353 *dev_info = INVALID_HANDLE_VALUE;
354 return NULL;
355}
356
357/*
358 * Populate the endpoints addresses of the device_priv interface helper structs
359 */
360static int windows_assign_endpoints(struct libusb_device *dev, int iface, int altsetting)
361{
362 int i, r;
363 struct windows_device_priv *priv = __device_priv(dev);
364 struct libusb_config_descriptor *conf_desc;
365 const struct libusb_interface_descriptor *if_desc;
366
367 r = libusb_get_config_descriptor(dev, 0, &conf_desc);
368 if (r != LIBUSB_SUCCESS) {
369 usbi_warn(NULL, "could not read config descriptor: error %d", r);
370 return r;
371 }
372
373 if_desc = &conf_desc->interface[iface].altsetting[altsetting];
374 safe_free(priv->usb_interface[iface].endpoint);
375
376 if (if_desc->bNumEndpoints == 0) {
377 usbi_dbg("no endpoints found for interface %d", iface);
378 return LIBUSB_SUCCESS;
379 }
380
381 priv->usb_interface[iface].endpoint = malloc(if_desc->bNumEndpoints);
382 if (priv->usb_interface[iface].endpoint == NULL) {
383 return LIBUSB_ERROR_NO_MEM;
384 }
385
386 priv->usb_interface[iface].nb_endpoints = if_desc->bNumEndpoints;
387 for (i=0; i<if_desc->bNumEndpoints; i++) {
388 priv->usb_interface[iface].endpoint[i] = if_desc->endpoint[i].bEndpointAddress;
389 usbi_dbg("(re)assigned endpoint %02X to interface %d", priv->usb_interface[iface].endpoint[i], iface);
390 }
391 libusb_free_config_descriptor(conf_desc);
392
393 return LIBUSB_SUCCESS;
394}
395
396// Lookup for a match in the list of API driver names
397bool is_api_driver(char* driver, uint8_t api)
398{
399 uint8_t i;
400 const char sep_str[2] = {LIST_SEPARATOR, 0};
401 char *tok, *tmp_str;
402 size_t len = safe_strlen(driver);
403
404 if (len == 0) return false;
405 tmp_str = calloc(len+1, 1);
406 if (tmp_str == NULL) return false;
407 memcpy(tmp_str, driver, len+1);
408 tok = strtok(tmp_str, sep_str);
409 while (tok != NULL) {
410 for (i=0; i<usb_api_backend[api].nb_driver_names; i++) {
411 if (safe_strcmp(tok, usb_api_backend[api].driver_name_list[i]) == 0) {
412 free(tmp_str);
413 return true;
414 }
415 }
416 tok = strtok(NULL, sep_str);
417 }
418 free (tmp_str);
419 return false;
420}
421
422/*
423 * auto-claiming and auto-release helper functions
424 */
425#if defined(AUTO_CLAIM)
426static int auto_claim(struct libusb_transfer *transfer, int *interface_number, int api_type)
427{
428 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
429 struct windows_device_handle_priv *handle_priv = __device_handle_priv(
430 transfer->dev_handle);
431 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
432 int current_interface = *interface_number;
433 int r = LIBUSB_SUCCESS;
434
435 switch(api_type) {
436 case USB_API_WINUSB:
437 case USB_API_HID:
438 break;
439 default:
440 return LIBUSB_ERROR_INVALID_PARAM;
441 }
442
443 usbi_mutex_lock(&autoclaim_lock);
444 if (current_interface < 0) // No serviceable interface was found
445 {
446 for (current_interface=0; current_interface<USB_MAXINTERFACES; current_interface++) {
447 // Must claim an interface of the same API type
448 if ( (priv->usb_interface[current_interface].apib == &usb_api_backend[api_type])
449 && (libusb_claim_interface(transfer->dev_handle, current_interface) == LIBUSB_SUCCESS) ) {
450 usbi_dbg("auto-claimed interface %d for control request", current_interface);
451 if (handle_priv->autoclaim_count[current_interface] != 0) {
452 usbi_warn(ctx, "program assertion failed - autoclaim_count was nonzero");
453 }
454 handle_priv->autoclaim_count[current_interface]++;
455 break;
456 }
457 }
458 if (current_interface == USB_MAXINTERFACES) {
459 usbi_err(ctx, "could not auto-claim any interface");
460 r = LIBUSB_ERROR_NOT_FOUND;
461 }
462 } else {
463 // If we have a valid interface that was autoclaimed, we must increment
464 // its autoclaim count so that we can prevent an early release.
465 if (handle_priv->autoclaim_count[current_interface] != 0) {
466 handle_priv->autoclaim_count[current_interface]++;
467 }
468 }
469 usbi_mutex_unlock(&autoclaim_lock);
470
471 *interface_number = current_interface;
472 return r;
473
474}
475
476static void auto_release(struct usbi_transfer *itransfer)
477{
478 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
479 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
480 libusb_device_handle *dev_handle = transfer->dev_handle;
481 struct windows_device_handle_priv* handle_priv = __device_handle_priv(dev_handle);
482 int r;
483
484 usbi_mutex_lock(&autoclaim_lock);
485 if (handle_priv->autoclaim_count[transfer_priv->interface_number] > 0) {
486 handle_priv->autoclaim_count[transfer_priv->interface_number]--;
487 if (handle_priv->autoclaim_count[transfer_priv->interface_number] == 0) {
488 r = libusb_release_interface(dev_handle, transfer_priv->interface_number);
489 if (r == LIBUSB_SUCCESS) {
490 usbi_dbg("auto-released interface %d", transfer_priv->interface_number);
491 } else {
492 usbi_dbg("failed to auto-release interface %d (%s)",
493 transfer_priv->interface_number, libusb_strerror(r));
494 }
495 }
496 }
497 usbi_mutex_unlock(&autoclaim_lock);
498}
499#endif
500
501
502/*
503 * init: libusb backend init function
504 *
505 * This function enumerates the HCDs (Host Controller Drivers) and populates our private HCD list
506 * In our implementation, we equate Windows' "HCD" to LibUSB's "bus". Note that bus is zero indexed.
507 * HCDs are not expected to change after init (might not hold true for hot pluggable USB PCI card?)
508 */
509static int windows_init(struct libusb_context *ctx)
510{
511 HDEVINFO dev_info;
512 SP_DEVICE_INTERFACE_DETAIL_DATA *dev_interface_details = NULL;
513 GUID guid;
514 libusb_bus_t bus;
515 int i, r = LIBUSB_ERROR_OTHER;
516 OSVERSIONINFO os_version;
517 HANDLE semaphore;
518 struct windows_hcd_priv** _hcd_cur;
519 TCHAR sem_name[11+1+8]; // strlen(libusb_init)+'\0'+(32-bit hex PID)
520
521 sprintf(sem_name, "libusb_init%08X", (unsigned int)GetCurrentProcessId()&0xFFFFFFFF);
522 semaphore = CreateSemaphore(NULL, 1, 1, sem_name);
523 if (semaphore == NULL) {
524 usbi_err(ctx, "could not create semaphore: %s", windows_error_str(0));
525 return LIBUSB_ERROR_NO_MEM;
526 }
527
528 // A successful wait brings our semaphore count to 0 (unsignaled)
529 // => any concurent wait stalls until the semaphore's release
530 if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
531 usbi_err(ctx, "failure to access semaphore: %s", windows_error_str(0));
532 CloseHandle(semaphore);
533 return LIBUSB_ERROR_NO_MEM;
534 }
535
536 // NB: concurrent usage supposes that init calls are equally balanced with
537 // exit calls. If init is called more than exit, we will not exit properly
538 if ( ++concurrent_usage == 0 ) { // First init?
539 _hcd_cur = &hcd_root;
540
541 // Detect OS version
542 memset(&os_version, 0, sizeof(OSVERSIONINFO));
543 os_version.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
544 windows_version = WINDOWS_UNSUPPORTED;
545 if ((GetVersionEx(&os_version) != 0) && (os_version.dwPlatformId == VER_PLATFORM_WIN32_NT)) {
546 if ((os_version.dwMajorVersion == 5) && (os_version.dwMinorVersion == 1)) {
547 windows_version = WINDOWS_XP;
548 } else if ((os_version.dwMajorVersion == 5) && (os_version.dwMinorVersion == 2)) {
549 windows_version = WINDOWS_2003; // also includes XP 64
550 } else if (os_version.dwMajorVersion >= 6) {
551 windows_version = WINDOWS_VISTA_AND_LATER;
552 }
553 }
554 if (windows_version == WINDOWS_UNSUPPORTED) {
555 usbi_err(ctx, "This version of Windows is NOT supported");
556 r = LIBUSB_ERROR_NOT_SUPPORTED;
557 goto init_exit;
558 }
559
560#if defined(AUTO_CLAIM)
561 // We need a lock for proper auto-release
562 usbi_mutex_init(&autoclaim_lock, NULL);
563#endif
564
565 // Initialize pollable file descriptors
566 init_polling();
567
568 // Load missing CFGMGR32.DLL imports
569 if (Cfgmgr32_init() != LIBUSB_SUCCESS) {
570 usbi_err(ctx, "could not resolve Cfgmgr32.dll functions");
571 return LIBUSB_ERROR_NOT_FOUND;
572 }
573
574 // Initialize the low level APIs (we don't care about errors at this stage)
575 for (i=0; i<USB_API_MAX; i++) {
576 usb_api_backend[i].init(ctx);
577 }
578
579 // Because QueryPerformanceCounter might report different values when
580 // running on different cores, we create a separate thread for the timer
581 // calls, which we glue to the first core always to prevent timing discrepancies.
582 r = LIBUSB_ERROR_NO_MEM;
583 for (i = 0; i < 2; i++) {
584 timer_request[i] = CreateEvent(NULL, TRUE, FALSE, NULL);
585 if (timer_request[i] == NULL) {
586 usbi_err(ctx, "could not create timer request event %d - aborting", i);
587 goto init_exit;
588 }
589 }
590 timer_response = CreateSemaphore(NULL, 0, MAX_TIMER_SEMAPHORES, NULL);
591 if (timer_response == NULL) {
592 usbi_err(ctx, "could not create timer response semaphore - aborting");
593 goto init_exit;
594 }
595 timer_mutex = CreateMutex(NULL, FALSE, NULL);
596 if (timer_mutex == NULL) {
597 usbi_err(ctx, "could not create timer mutex - aborting");
598 goto init_exit;
599 }
600 timer_thread = (HANDLE)_beginthreadex(NULL, 0, windows_clock_gettime_threaded, NULL, 0, NULL);
601 if (timer_thread == NULL) {
602 usbi_err(ctx, "Unable to create timer thread - aborting");
603 goto init_exit;
604 }
605 SetThreadAffinityMask(timer_thread, 0);
606
607 guid = GUID_DEVINTERFACE_USB_HOST_CONTROLLER;
608
609 r = LIBUSB_SUCCESS;
610 for (bus = 0; ; bus++)
611 {
612 // safe loop: free up any (unprotected) dynamic resource
613 // NB: this is always executed before breaking the loop
614 safe_free(dev_interface_details);
615 safe_free(*_hcd_cur);
616
617 dev_interface_details = get_interface_details(ctx, &dev_info, NULL, guid, bus);
618 // safe loop: end of loop condition
619 if ((dev_interface_details == NULL) || (r != LIBUSB_SUCCESS))
620 break;
621
622 // Will need to change storage and size of libusb_bus_t if this ever occurs
623 if (bus == LIBUSB_BUS_MAX) {
624 usbi_warn(ctx, "program assertion failed - found more than %d buses, skipping the rest.", LIBUSB_BUS_MAX);
625 continue;
626 }
627
628 // Allocate and init a new priv structure to hold our data
629 if ((*_hcd_cur = malloc(sizeof(struct windows_hcd_priv))) == NULL) {
630 usbi_err(ctx, "could not allocate private structure for bus %u. aborting.", bus);
631 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
632 }
633 windows_hcd_priv_init(*_hcd_cur);
634 (*_hcd_cur)->path = sanitize_path(dev_interface_details->DevicePath);
635
636 _hcd_cur = &((*_hcd_cur)->next);
637 }
638 // TODO (2nd official release): thread for hotplug (see darwin source)
639 }
640
641 if (hcd_root == NULL)
642 r = LIBUSB_ERROR_NO_DEVICE;
643 else
644 r = LIBUSB_SUCCESS;
645
646init_exit: // Holds semaphore here.
647 if(!concurrent_usage && r != LIBUSB_SUCCESS) { // First init failed?
648 if (timer_thread) {
649 SetEvent(timer_request[1]); // actually the signal to quit the thread.
650 if (WAIT_OBJECT_0 != WaitForSingleObject(timer_thread, INFINITE)) {
651 usbi_warn(ctx, "could not wait for timer thread to quit");
652 TerminateThread(timer_thread, 1); // shouldn't happen, but we're destroying
653 // all objects it might have held anyway.
654 }
655 CloseHandle(timer_thread);
656 timer_thread = NULL;
657 }
658 for (i = 0; i < 2; i++) {
659 if (timer_request[i]) {
660 CloseHandle(timer_request[i]);
661 timer_request[i] = NULL;
662 }
663 }
664 if (timer_response) {
665 CloseHandle(timer_response);
666 timer_response = NULL;
667 }
668 if (timer_mutex) {
669 CloseHandle(timer_mutex);
670 timer_mutex = NULL;
671 }
672 }
673
674 if (r != LIBUSB_SUCCESS)
675 --concurrent_usage; // Not expected to call libusb_exit if we failed.
676
677 ReleaseSemaphore(semaphore, 1, NULL); // increase count back to 1
678 CloseHandle(semaphore);
679 return r;
680}
681
682/*
683 * Initialize device structure, including active config
684 */
685static int initialize_device(struct libusb_device *dev, libusb_bus_t busnum,
686 libusb_devaddr_t devaddr, char *path, int connection_index, uint8_t active_config,
687 struct libusb_device *parent_dev)
688{
689 struct windows_device_priv *priv = __device_priv(dev);
690
691 windows_device_priv_init(priv);
692
693 dev->bus_number = busnum;
694 dev->device_address = devaddr;
695 priv->path = path;
696 priv->connection_index = connection_index;
697 priv->parent_dev = parent_dev;
698
699 priv->active_config = active_config;
700
701 if (priv->active_config != 0) {
702 usbi_dbg("active config: %d", priv->active_config);
703 } else {
704 // USB devices that don't have a config value are usually missing a driver
705 // TODO (after first official release): use this for automated driver installation
706 // NB: SetupDiGetDeviceRegistryProperty w/ SPDRP_INSTALL_STATE would tell us
707 // if the driver is properly installed, but driverless devices don't seem to
708 // be enumerable by SetupDi...
709 usbi_dbg("* This device has no driver => libusb will not be able to access it *");
710 }
711
712 return LIBUSB_SUCCESS;
713}
714
715/*
716 * HCD (root) hubs need to have their device descriptor manually populated
717 *
718 * Note that we follow the Linux convention and use the "Linux Foundation root hub"
719 * vendor ID as well as the product ID to indicate the hub speed
720 */
721static int force_hcd_device_descriptor(struct libusb_device *dev, HANDLE handle)
722{
723 DWORD size;
724 USB_HUB_CAPABILITIES hub_caps;
725 USB_HUB_CAPABILITIES_EX hub_caps_ex;
726 struct windows_device_priv *priv = __device_priv(dev);
727 struct libusb_context *ctx = DEVICE_CTX(dev);
728
729 priv->dev_descriptor.bLength = sizeof(USB_DEVICE_DESCRIPTOR);
730 priv->dev_descriptor.bDescriptorType = USB_DEVICE_DESCRIPTOR_TYPE;
731 dev->num_configurations = priv->dev_descriptor.bNumConfigurations = 1;
732
733 // The following is used to set the VIS:PID of root HUBs similarly to what
734 // Linux does: 1d6b:0001 is for 1x root hubs, 1d6b:0002 for 2x
735 priv->dev_descriptor.idVendor = 0x1d6b; // Linux Foundation root hub
736 if (windows_version >= WINDOWS_VISTA_AND_LATER) {
737 size = sizeof(USB_HUB_CAPABILITIES_EX);
738 if (DeviceIoControl(handle, IOCTL_USB_GET_HUB_CAPABILITIES_EX, &hub_caps_ex,
739 size, &hub_caps_ex, size, &size, NULL)) {
740 // Sanity check. HCD hub should always be root
741 if (!hub_caps_ex.CapabilityFlags.HubIsRoot) {
742 usbi_warn(ctx, "program assertion failed - HCD hub is not reported as root hub.");
743 }
744 priv->dev_descriptor.idProduct = hub_caps_ex.CapabilityFlags.HubIsHighSpeedCapable?2:1;
745 }
746 } else {
747 size = sizeof(USB_HUB_CAPABILITIES);
748 if (!DeviceIoControl(handle, IOCTL_USB_GET_HUB_CAPABILITIES, &hub_caps,
749 size, &hub_caps, size, &size, NULL)) {
750 usbi_warn(ctx, "could not read hub capabilities (std) for hub %s: %s",
751 priv->path, windows_error_str(0));
752 priv->dev_descriptor.idProduct = 1; // Indicate 1x speed
753 } else {
754 priv->dev_descriptor.idProduct = hub_caps.HubIs2xCapable?2:1;
755 }
756 }
757
758 return LIBUSB_SUCCESS;
759}
760
761/*
762 * fetch and cache all the config descriptors through I/O
763 */
764static int cache_config_descriptors(struct libusb_device *dev, HANDLE hub_handle)
765{
766 DWORD size, ret_size;
767 struct libusb_context *ctx = DEVICE_CTX(dev);
768 struct windows_device_priv *priv = __device_priv(dev);
769 int r;
770 uint8_t i;
771
772 USB_CONFIGURATION_DESCRIPTOR_SHORT cd_buf_short; // dummy request
773 PUSB_DESCRIPTOR_REQUEST cd_buf_actual = NULL; // actual request
774 PUSB_CONFIGURATION_DESCRIPTOR cd_data = NULL;
775
776 if (dev->num_configurations == 0)
777 return LIBUSB_ERROR_INVALID_PARAM;
778
779 priv->config_descriptor = malloc(dev->num_configurations * sizeof(PUSB_CONFIGURATION_DESCRIPTOR));
780 if (priv->config_descriptor == NULL)
781 return LIBUSB_ERROR_NO_MEM;
782 for (i=0; i<dev->num_configurations; i++)
783 priv->config_descriptor[i] = NULL;
784
785 for (i=0, r=LIBUSB_SUCCESS; ; i++)
786 {
787 // safe loop: release all dynamic resources
788 safe_free(cd_buf_actual);
789
790 // safe loop: end of loop condition
791 if ((i >= dev->num_configurations) || (r != LIBUSB_SUCCESS))
792 break;
793
794 size = sizeof(USB_CONFIGURATION_DESCRIPTOR_SHORT);
795 memset(&cd_buf_short, 0, size);
796
797 cd_buf_short.req.ConnectionIndex = priv->connection_index;
798 cd_buf_short.req.SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN;
799 cd_buf_short.req.SetupPacket.bRequest = USB_REQUEST_GET_DESCRIPTOR;
800 cd_buf_short.req.SetupPacket.wValue = (USB_CONFIGURATION_DESCRIPTOR_TYPE << 8) | i;
801 cd_buf_short.req.SetupPacket.wIndex = i;
802 cd_buf_short.req.SetupPacket.wLength = (USHORT)(size - sizeof(USB_DESCRIPTOR_REQUEST));
803
804 // Dummy call to get the required data size
805 if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, &cd_buf_short, size,
806 &cd_buf_short, size, &ret_size, NULL)) {
807 usbi_err(ctx, "could not access configuration descriptor (dummy): %s", windows_error_str(0));
808 LOOP_BREAK(LIBUSB_ERROR_IO);
809 }
810
811 if ((ret_size != size) || (cd_buf_short.data.wTotalLength < sizeof(USB_CONFIGURATION_DESCRIPTOR))) {
812 usbi_err(ctx, "unexpected configuration descriptor size (dummy).");
813 LOOP_BREAK(LIBUSB_ERROR_IO);
814 }
815
816 size = sizeof(USB_DESCRIPTOR_REQUEST) + cd_buf_short.data.wTotalLength;
817 if ((cd_buf_actual = (PUSB_DESCRIPTOR_REQUEST)malloc(size)) == NULL) {
818 usbi_err(ctx, "could not allocate configuration descriptor buffer. aborting.");
819 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
820 }
821 memset(cd_buf_actual, 0, size);
822
823 // Actual call
824 cd_buf_actual->ConnectionIndex = priv->connection_index;
825 cd_buf_actual->SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN;
826 cd_buf_actual->SetupPacket.bRequest = USB_REQUEST_GET_DESCRIPTOR;
827 cd_buf_actual->SetupPacket.wValue = (USB_CONFIGURATION_DESCRIPTOR_TYPE << 8) | i;
828 cd_buf_actual->SetupPacket.wIndex = i;
829 cd_buf_actual->SetupPacket.wLength = (USHORT)(size - sizeof(USB_DESCRIPTOR_REQUEST));
830
831 if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, cd_buf_actual, size,
832 cd_buf_actual, size, &ret_size, NULL)) {
833 usbi_err(ctx, "could not access configuration descriptor (actual): %s", windows_error_str(0));
834 LOOP_BREAK(LIBUSB_ERROR_IO);
835 }
836
837 cd_data = (PUSB_CONFIGURATION_DESCRIPTOR)((UCHAR*)cd_buf_actual+sizeof(USB_DESCRIPTOR_REQUEST));
838
839 if ((size != ret_size) || (cd_data->wTotalLength != cd_buf_short.data.wTotalLength)) {
840 usbi_err(ctx, "unexpected configuration descriptor size (actual).");
841 LOOP_BREAK(LIBUSB_ERROR_IO);
842 }
843
844 if (cd_data->bDescriptorType != USB_CONFIGURATION_DESCRIPTOR_TYPE) {
845 usbi_err(ctx, "not a configuration descriptor");
846 LOOP_BREAK(LIBUSB_ERROR_IO);
847 }
848
849 usbi_dbg("cached config descriptor #%d (%d bytes)", i+1, cd_data->wTotalLength);
850
851 // Sanity check. Ensures that indexes for our list of config desc is in the right order
852 if (i != (cd_data->bConfigurationValue-1)) {
853 usbi_warn(ctx, "program assertion failed - config descriptors are being read out of order");
854 continue;
855 }
856
857 // Cache the descriptor
858 priv->config_descriptor[i] = malloc(cd_data->wTotalLength);
859 if (priv->config_descriptor[i] == NULL)
860 return LIBUSB_ERROR_NO_MEM;
861
862 memcpy(priv->config_descriptor[i], cd_data, cd_data->wTotalLength);
863 }
864 return LIBUSB_SUCCESS;
865}
866
867/*
868 * Recursively enumerates and finds all hubs & devices
869 */
870static int usb_enumerate_hub(struct libusb_context *ctx, struct discovered_devs **_discdevs,
871 HANDLE hub_handle, libusb_bus_t busnum, struct libusb_device *parent_dev, uint8_t nb_ports)
872{
873 struct discovered_devs *discdevs = *_discdevs;
874 struct libusb_device *dev = NULL;
875 DWORD size, size_initial, size_fixed, getname_ioctl;
876 HANDLE handle = INVALID_HANDLE_VALUE;
877 USB_HUB_NAME_FIXED s_hubname;
878 USB_NODE_CONNECTION_INFORMATION conn_info;
879 USB_NODE_INFORMATION hub_node;
880 bool is_hcd, need_unref = false;
881 int i, r;
882 LPCWSTR wstr;
883 char *tmp_str = NULL, *path_str = NULL;
884 unsigned long session_id;
885 libusb_devaddr_t devaddr = 0;
886 struct windows_device_priv *priv, *parent_priv;
887
888 // obviously, root (HCD) hubs have no parent
889 is_hcd = (parent_dev == NULL);
890 if (is_hcd)
891 {
892 if (nb_ports != 1) {
893 usbi_warn(ctx, "program assertion failed - invalid number of ports for HCD.");
894 return LIBUSB_ERROR_INVALID_PARAM;
895 }
896 parent_priv = NULL;
897 size_initial = sizeof(USB_ROOT_HUB_NAME);
898 size_fixed = sizeof(USB_ROOT_HUB_NAME_FIXED);
899 getname_ioctl = IOCTL_USB_GET_ROOT_HUB_NAME;
900 }
901 else
902 {
903 parent_priv = __device_priv(parent_dev);
904 size_initial = sizeof(USB_NODE_CONNECTION_NAME);
905 size_fixed = sizeof(USB_NODE_CONNECTION_NAME_FIXED);
906 getname_ioctl = IOCTL_USB_GET_NODE_CONNECTION_NAME;
907 }
908
909 // Loop through all the ports on this hub
910 for (i = 1, r = LIBUSB_SUCCESS; ; i++)
911 {
912 // safe loop: release all dynamic resources
913 if (need_unref) {
914 safe_unref_device(dev);
915 need_unref = false;
916 }
917 safe_free(tmp_str);
918 safe_free(path_str);
919 safe_closehandle(handle);
920
921 // safe loop: end of loop condition
922 if ((i > nb_ports) || (r != LIBUSB_SUCCESS))
923 break;
924
925 memset(&conn_info, 0, sizeof(conn_info));
926 // For non HCDs, check if the node on this port is a hub or a regular device
927 if (!is_hcd) {
928 size = sizeof(USB_NODE_CONNECTION_INFORMATION);
929 conn_info.ConnectionIndex = i;
930 if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION, &conn_info, size,
931 &conn_info, size, &size, NULL)) {
932 usbi_warn(ctx, "could not get node connection information: %s", windows_error_str(0));
933 continue;
934 }
935
936 if (conn_info.ConnectionStatus == NoDeviceConnected) {
937 continue;
938 }
939
940 if (conn_info.DeviceAddress == LIBUSB_DEVADDR_MAX) {
941 usbi_warn(ctx, "program assertion failed - device address is %d "
942 "(conflicts with root hub), ignoring device", LIBUSB_DEVADDR_MAX);
943 continue;
944 }
945
946 s_hubname.u.node.ConnectionIndex = i; // Only used for non HCDs (s_hubname is an union)
947 }
948 else
949 {
950 // HCDs have only 1 node, and it's always a hub
951 conn_info.DeviceAddress = LIBUSB_DEVADDR_MAX; // using 0 can conflict with driverless devices
952 conn_info.DeviceIsHub = true;
953 conn_info.CurrentConfigurationValue = 1;
954 }
955
956 // If this node is a hub (HCD or not), open it
957 if (conn_info.DeviceIsHub) {
958 size = size_initial;
959 if (!DeviceIoControl(hub_handle, getname_ioctl, &s_hubname, size,
960 &s_hubname, size, &size, NULL)) {
961 usbi_warn(ctx, "could not get hub path (dummy): %s", windows_error_str(0));
962 continue;
963 }
964
965 size = is_hcd?s_hubname.u.root.ActualLength:s_hubname.u.node.ActualLength;
966 if (size > size_fixed) {
967 usbi_warn(ctx, "program assertion failed - hub path is too long");
968 continue;
969 }
970
971 if (!is_hcd) {
972 // previous call trashes some of the data
973 s_hubname.u.node.ConnectionIndex = i;
974 }
975 if (!DeviceIoControl(hub_handle, getname_ioctl, &s_hubname, size,
976 &s_hubname, size, &size, NULL)) {
977 usbi_warn(ctx, "could not get hub path (actual): %s", windows_error_str(0));
978 continue;
979 }
980
981 // Add prefix
982 wstr = is_hcd?s_hubname.u.root.RootHubName:s_hubname.u.node.NodeName;
983 tmp_str = wchar_to_utf8(wstr);
984 if (tmp_str == NULL) {
985 usbi_err(ctx, "could not convert hub path string.");
986 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
987 }
988
989 path_str = sanitize_path(tmp_str);
990 if (path_str == NULL) {
991 usbi_err(ctx, "could not sanitize hub path string.");
992 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
993 }
994
995 // Open Hub
996 handle = CreateFileA(path_str, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
997 FILE_FLAG_OVERLAPPED, NULL);
998 if(handle == INVALID_HANDLE_VALUE) {
999 usbi_warn(ctx, "could not open hub %s: %s", path_str, windows_error_str(0));
1000 continue;
1001 }
1002 }
1003
1004 // Generate a session ID
1005 // Will need to change the session_id computation if this assertion fails
1006 if (conn_info.DeviceAddress > LIBUSB_DEVADDR_MAX) {
1007 usbi_warn(ctx, "program assertion failed - device address is greater than %d, ignoring device",
1008 LIBUSB_DEVADDR_MAX);
1009 continue;
1010 } else {
1011 devaddr = (uint8_t)conn_info.DeviceAddress;
1012 }
1013 // Same trick as linux for session_id, with same caveat
1014 session_id = busnum << (sizeof(libusb_devaddr_t)*8) | devaddr;
1015 usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr, session_id);
1016
1017 // Allocate device if needed
1018 dev = usbi_get_device_by_session_id(ctx, session_id);
1019 if (dev) {
1020 usbi_dbg("using existing device for session %ld", session_id);
1021 priv = __device_priv(dev);
1022 // Because we are rebuilding the list, there's no guarantee
1023 // the parent device pointer is still the same.
1024 // Other device data should still be reusable
1025 priv->parent_dev = parent_dev;
1026 } else {
1027 usbi_dbg("allocating new device for session %ld", session_id);
1028 if ((dev = usbi_alloc_device(ctx, session_id)) == NULL) {
1029 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1030 }
1031 need_unref = true;
1032
1033 LOOP_CHECK(initialize_device(dev, busnum, devaddr, path_str, i,
1034 conn_info.CurrentConfigurationValue, parent_dev));
1035 priv = __device_priv(dev);
1036
1037 path_str = NULL; // protect our path from being freed
1038
1039 // Setup the cached descriptors. Note that only non HCDs can fetch descriptors
1040 if (!is_hcd) {
1041 // The device descriptor has been read with conn_info
1042 memcpy(&priv->dev_descriptor, &(conn_info.DeviceDescriptor), sizeof(USB_DEVICE_DESCRIPTOR));
1043 dev->num_configurations = priv->dev_descriptor.bNumConfigurations;
1044 // If we can't read the config descriptors, just set the number of confs to zero
1045 if (cache_config_descriptors(dev, hub_handle) != LIBUSB_SUCCESS) {
1046 dev->num_configurations = 0;
1047 priv->dev_descriptor.bNumConfigurations = 0;
1048 }
1049 } else {
1050 LOOP_CHECK(force_hcd_device_descriptor(dev, handle));
1051 }
1052 LOOP_CHECK(usbi_sanitize_device(dev));
1053 }
1054
1055 discdevs = discovered_devs_append(*_discdevs, dev);
1056 if (!discdevs) {
1057 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1058 }
1059
1060 *_discdevs = discdevs;
1061
1062 // Finally, if device is a hub, recurse
1063 if (conn_info.DeviceIsHub) {
1064 // Find number of ports for this hub
1065 size = sizeof(USB_NODE_INFORMATION);
1066 if (!DeviceIoControl(handle, IOCTL_USB_GET_NODE_INFORMATION, &hub_node, size,
1067 &hub_node, size, &size, NULL)) {
1068 usbi_warn(ctx, "could not retreive information for hub %s: %s",
1069 priv->path, windows_error_str(0));
1070 continue;
1071 }
1072
1073 if (hub_node.NodeType != UsbHub) {
1074 usbi_warn(ctx, "unexpected hub type (%d) for hub %s", hub_node.NodeType, priv->path);
1075 continue;
1076 }
1077
1078 usbi_dbg("%d ports Hub: %s", hub_node.u.HubInformation.HubDescriptor.bNumberOfPorts, priv->path);
1079
1080 usb_enumerate_hub(ctx, _discdevs, handle, busnum, dev,
1081 hub_node.u.HubInformation.HubDescriptor.bNumberOfPorts);
1082 }
1083 }
1084
1085 return r;
1086}
1087
1088/*
1089 * Composite device interfaces are not enumerated using GUID_DEVINTERFACE_USB_DEVICE,
1090 * but instead require a different lookup mechanism
1091 */
1092static int set_composite_device(struct libusb_context *ctx, DEVINST devinst, struct windows_device_priv *priv)
1093{
1094// indexes for additional interface GUIDs, not available from "USB"
1095// SetupDiGetClassDevs enumeration should go here. Typically, these are
1096// device interfaces that begin with something else than "\\?\usb\"
1097enum libusb_hid_report_type {
1098 HID_DEVICE_INTERFACE_GUID_INDEX = 0,
1099 MAX_DEVICE_INTERFACE_GUID_INDEX = 1
1100};
1101
1102 DEVINST child_devinst, parent_devinst;
1103 unsigned i, j, max_guids, nb_paths, interface_number;
1104 uint8_t api;
1105 bool found;
1106 DWORD type, size;
1107 CONFIGRET r;
1108 HDEVINFO dev_info;
1109 SP_DEVINFO_DATA dev_info_data;
1110 SP_DEVICE_INTERFACE_DETAIL_DATA *dev_interface_details = NULL;
1111 HKEY key;
1112 WCHAR guid_string_w[MAX_GUID_STRING_LENGTH];
1113 GUID guid, class_guid;
1114 GUID guid_table[MAX_USB_DEVICES];
1115 char* sanitized_path[MAX_USB_DEVICES];
1116 char* hid_path[MAX_USB_DEVICES]; // An extra path is needed for HID
1117 uint8_t api_type[MAX_USB_DEVICES];
1118 char* sanitized_short = NULL;
1119 char path[MAX_PATH_LENGTH];
1120 char driver[MAX_KEY_LENGTH];
1121
1122 dev_info = SetupDiGetClassDevs(NULL, "USB", NULL, DIGCF_PRESENT|DIGCF_ALLCLASSES);
1123 if (dev_info == INVALID_HANDLE_VALUE) {
1124 return LIBUSB_ERROR_NOT_FOUND;
1125 }
1126
1127 // Manually add the HID GUID as it cannot be read with DeviceInterfaceGUIDs reg key)
1128 // NB the value returned by HidD_GetHidGuid, which is for interface class is different
1129 // from GUID_HID, which is the device class GUID
1130 HidD_GetHidGuid(&guid_table[HID_DEVICE_INTERFACE_GUID_INDEX]);
1131 // NB: for other interface guids, SetupDiClassGuidsFromName can be used
1132 max_guids = MAX_DEVICE_INTERFACE_GUID_INDEX;
1133
1134 // First, retrieve all the device interface GUIDs
1135 for (i = 0; ; i++)
1136 {
1137 dev_info_data.cbSize = sizeof(dev_info_data);
1138 if (!SetupDiEnumDeviceInfo(dev_info, i, &dev_info_data)) {
1139 break;
1140 }
1141
1142 key = SetupDiOpenDevRegKey(dev_info, &dev_info_data, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ);
1143 if (key == INVALID_HANDLE_VALUE) {
1144 usbi_dbg("could not open registry key");
1145 continue;
1146 }
1147
1148 size = sizeof(guid_string_w);
1149 r = RegQueryValueExW(key, L"DeviceInterfaceGUIDs", NULL, &type,
1150 (BYTE*)guid_string_w, &size);
1151 RegCloseKey(key);
1152 if (r != ERROR_SUCCESS) {
1153 continue;
1154 }
1155 CLSIDFromString(guid_string_w, &guid);
1156
1157 // identical device interface GUIDs are not supposed to happen, but are a real possibility
1158 // => check and ignore duplicates
1159 found = false;
1160 for (j=0; j<max_guids; j++) {
1161 if (memcmp(&guid_table[j], &guid, sizeof(GUID)) == 0) {
1162 found = true;
1163 break;
1164 }
1165 }
1166 if (!found) {
1167 guid_table[max_guids++] = guid;
1168 if (max_guids > MAX_USB_DEVICES) {
1169 usbi_warn(ctx, "more than %d devices - ignoring the rest", MAX_USB_DEVICES);
1170 break;
1171 }
1172 }
1173 }
1174 SetupDiDestroyDeviceInfoList(dev_info);
1175
1176 // Now let's find the device interface paths for all these devices
1177 nb_paths = 0;
1178 for (j=0; j<max_guids; j++)
1179 {
1180 guid = guid_table[j];
1181
1182 for (i = 0; ; i++)
1183 {
1184 safe_free(dev_interface_details);
1185 dev_interface_details = get_interface_details(ctx, &dev_info, &dev_info_data, guid, i);
1186 if (dev_interface_details == NULL)
1187 break;
1188
1189 // HID devices (and possibly other classes) have an extra indirection
1190 // for an USB path we can recognize
1191 if (j == HID_DEVICE_INTERFACE_GUID_INDEX) {
1192 if (CM_Get_Parent(&parent_devinst, dev_info_data.DevInst, 0) != CR_SUCCESS) {
1193 usbi_warn(ctx, "could not retrieve HID parent info data for device %s, skipping: %s",
1194 dev_interface_details->DevicePath, windows_error_str(0));
1195 continue;
1196 }
1197
1198 if (CM_Get_Device_ID(parent_devinst, path, MAX_PATH_LENGTH, 0) != CR_SUCCESS) {
1199 usbi_warn(ctx, "could not retrieve HID parent's path for device %s, skipping: %s",
1200 dev_interface_details->DevicePath, windows_error_str(0));
1201 continue;
1202 }
1203 }
1204
1205 // In case we can't read the driver string through SPDRP_SERVICE (which is
1206 // the case for HID), we need the ClassGUID for comparison.
1207 if(!SetupDiGetDeviceRegistryPropertyW(dev_info, &dev_info_data, SPDRP_CLASSGUID,
1208 NULL, (BYTE*)guid_string_w, sizeof(guid_string_w), &size)) {
1209 usbi_warn(ctx, "could not read class GUID for device %s, skipping: %s",
1210 dev_interface_details->DevicePath, windows_error_str(0));
1211 continue;
1212 }
1213 CLSIDFromString(guid_string_w, &class_guid);
1214
1215 // Attempt to read the driver string
1216 if(!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data, SPDRP_SERVICE,
1217 NULL, (BYTE*)driver, MAX_KEY_LENGTH, &size)) {
1218 driver[0] = 0;
1219 }
1220
1221 for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
1222 if ( (is_api_driver(driver, api))
1223 || (guid_eq(&class_guid, usb_api_backend[api].class_guid)) ) {
1224 api_type[nb_paths] = api;
1225 if (j == HID_DEVICE_INTERFACE_GUID_INDEX) {
1226 hid_path[nb_paths] = sanitize_path(path);
1227 } else {
1228 hid_path[nb_paths] = NULL;
1229 }
1230 sanitized_path[nb_paths++] = sanitize_path(dev_interface_details->DevicePath);
1231 if (nb_paths > MAX_USB_DEVICES) {
1232 usbi_warn(ctx, "more than %d devices - ignoring the rest", MAX_USB_DEVICES);
1233 break;
1234 }
1235 }
1236 }
1237 }
1238 }
1239
1240 // Finally, match the interface paths with the interfaces. We do that
1241 // by looking at the children of the composite device
1242 // NB: if the interfaces are not found in their expected position,
1243 // claim_interface will issue a warning
1244 found = false;
1245 memset(&child_devinst, 0, sizeof(DEVINST)); // prevents /W4 warning
1246 for (i = 0; i<USB_MAXINTERFACES; i++)
1247 {
1248 if (i == 0) {
1249 r = CM_Get_Child(&child_devinst, devinst, 0);
1250 } else {
1251 r = CM_Get_Sibling(&child_devinst, child_devinst, 0);
1252 }
1253 if (r == CR_NO_SUCH_DEVNODE) { // end of the siblings
1254 break;
1255 } else if (r != CR_SUCCESS) {
1256 usbi_dbg("unable to find interface sibling #%d, error = %X", i, r);
1257 break;
1258 }
1259
1260 r = CM_Get_Device_ID(child_devinst, path, MAX_PATH_LENGTH, 0);
1261 if (r != CR_SUCCESS) {
1262 usbi_err(ctx, "could not retrieve simple path for interface %d: CR error %d",
1263 i, r);
1264 continue;
1265 }
1266 sanitized_short = sanitize_path(path);
1267 if (sanitized_short == NULL) {
1268 usbi_err(ctx, "could not sanitize path for interface %d", i);
1269 continue;
1270 }
1271
1272 // Because MI_## are not necessarily in sequential order (some composite HID
1273 // devices will have only MI_00 & MI_03 for instance), we retrieve the actual
1274 // interface number from the path's MI value
1275 interface_number = i;
1276 for (j=0; sanitized_short[j] != 0; ) {
1277 if ( (sanitized_short[j++] == 'M') && (sanitized_short[j++] == 'I')
1278 && (sanitized_short[j++] == '_') ) {
1279 interface_number = (sanitized_short[j++] - '0')*10;
1280 interface_number += sanitized_short[j] - '0';
1281 break;
1282 }
1283 }
1284 if (sanitized_short[j] == 0) {
1285 usbi_warn(ctx, "failure to read interface number for %s. Using default value %d",
1286 sanitized_short, interface_number);
1287 }
1288
1289 for (j=0; j<nb_paths; j++) {
1290 if ( (safe_strncmp(sanitized_path[j], sanitized_short, safe_strlen(sanitized_short)) == 0)
1291 || (safe_strcmp(hid_path[j], sanitized_short) == 0 ) ) {
1292 // HID devices can have multiple collections (COL##) for each MI_## interface
1293 if (priv->usb_interface[interface_number].path != NULL) {
1294 usbi_dbg("interface_path[%d] already set - ignoring HID collection: %s",
1295 interface_number, sanitized_path[j]);
1296 if (api_type[j] != USB_API_HID) {
1297 usbi_warn(ctx, "program assertion failed - not an HID collection");
1298 }
1299 } else {
1300 priv->usb_interface[interface_number].path = sanitized_path[j];
1301 priv->usb_interface[interface_number].apib = &usb_api_backend[api_type[j]];
1302 if ((api_type[j] == USB_API_HID) && (priv->hid == NULL)) {
1303 priv->hid = calloc(1, sizeof(struct hid_device_priv));
1304 }
1305 priv->composite_api_flags |= 1<<api_type[j];
1306 sanitized_path[j] = NULL;
1307 }
1308 }
1309 }
1310 safe_free(sanitized_short);
1311
1312 if (priv->usb_interface[interface_number].path == NULL) {
1313 usbi_warn(ctx, "interface_path[%d]: unhandled API - interface will be disabled",
1314 interface_number);
1315 continue;
1316 }
1317 usbi_dbg("interface_path[%d]: %s", interface_number, priv->usb_interface[interface_number].path);
1318 found = true;
1319 }
1320
1321 for (j=0; j<nb_paths; j++) {
1322 safe_free(sanitized_path[j]);
1323 safe_free(hid_path[j]);
1324 }
1325
1326 if (found == 0) {
1327 usbi_warn(ctx, "composite device: no interfaces were found");
1328 return LIBUSB_ERROR_NOT_FOUND;
1329 }
1330
1331 return LIBUSB_SUCCESS;
1332}
1333
1334/*
1335 * Likewise, HID device interfaces's path (\\.\HID\...) are not enumerated through the
1336 * generic USB devices GUID, but are actually children of one such device
1337 */
1338static int set_hid_device(struct libusb_context *ctx, struct windows_device_priv *priv)
1339 {
1340 char path[MAX_PATH_LENGTH];
1341 char *sanitized_path = NULL;
1342 HDEVINFO dev_info;
1343 SP_DEVICE_INTERFACE_DETAIL_DATA *dev_interface_details = NULL;
1344 SP_DEVINFO_DATA dev_info_data;
1345 DEVINST parent_devinst;
1346 GUID guid;
1347 int r = LIBUSB_SUCCESS;
1348 unsigned i, interface_number;
1349
1350 interface_number = 0;
1351 HidD_GetHidGuid(&guid);
1352 for (i = 0; ; i++)
1353 {
1354 // safe loop: free up any (unprotected) dynamic resource
1355 safe_free(dev_interface_details);
1356 safe_free(sanitized_path);
1357
1358 dev_interface_details = get_interface_details(ctx, &dev_info, &dev_info_data, guid, i);
1359 // safe loop: end of loop condition
1360 if ( (dev_interface_details == NULL)
1361 || (r != LIBUSB_SUCCESS) )
1362 break;
1363
1364 // Retrieve parent's path using PnP Configuration Manager (CM)
1365 if (CM_Get_Parent(&parent_devinst, dev_info_data.DevInst, 0) != CR_SUCCESS) {
1366 usbi_warn(ctx, "could not retrieve parent info data for device %s, skipping: %s",
1367 dev_interface_details->DevicePath, windows_error_str(0));
1368 continue;
1369 }
1370
1371 if (CM_Get_Device_ID(parent_devinst, path, MAX_PATH_LENGTH, 0) != CR_SUCCESS) {
1372 usbi_warn(ctx, "could not retrieve parent's path for device %s, skipping: %s",
1373 dev_interface_details->DevicePath, windows_error_str(0));
1374 continue;
1375 }
1376
1377 // Fix parent's path inconsistencies before attempting to compare
1378 sanitized_path = sanitize_path(path);
1379 if (sanitized_path == NULL) {
1380 usbi_warn(ctx, "could not sanitize parent's path for device %s, skipping.",
1381 dev_interface_details->DevicePath);
1382 continue;
1383 }
1384
1385 // NB: we compare strings of different lengths below => strncmp
1386 if (safe_strncmp(priv->path, sanitized_path, safe_strlen(sanitized_path)) == 0) {
1387 priv->usb_interface[interface_number].path = sanitize_path(dev_interface_details->DevicePath);
1388 priv->usb_interface[interface_number].apib = &usb_api_backend[USB_API_HID];
1389 usbi_dbg("interface_path[%d]: %s", interface_number, priv->usb_interface[interface_number].path);
1390 interface_number++;
1391 }
1392 }
1393
1394 return LIBUSB_SUCCESS;
1395}
1396
1397/*
1398 * This function retrieves and sets the paths of all non-hub devices
1399 * NB: No I/O with device is required during this call
1400 */
1401static int set_device_paths(struct libusb_context *ctx, struct discovered_devs *discdevs)
1402{
1403 // Precedence for filter drivers vs driver is in the order of this array
1404 struct driver_lookup lookup[3] = {
1405 {"\0\0", SPDRP_SERVICE, "driver"},
1406 {"\0\0", SPDRP_UPPERFILTERS, "upper filter driver"},
1407 {"\0\0", SPDRP_LOWERFILTERS, "lower filter driver"}
1408 };
1409 struct windows_device_priv *priv;
1410 struct windows_device_priv *parent_priv;
1411 char path[MAX_PATH_LENGTH];
1412 char *sanitized_path = NULL;
1413 HDEVINFO dev_info;
1414 SP_DEVICE_INTERFACE_DETAIL_DATA *dev_interface_details = NULL;
1415 SP_DEVINFO_DATA dev_info_data;
1416 DEVINST parent_devinst;
1417 GUID guid;
1418 DWORD size, reg_type, install_state, port_nr;
1419 int r = LIBUSB_SUCCESS;
1420 unsigned i, j, k, l;
1421 uint8_t api;
1422 bool found;
1423
1424 // TODO (after first official release): MI_## automated driver installation
1425 guid = GUID_DEVINTERFACE_USB_DEVICE;
1426 for (i = 0; ; i++)
1427 {
1428 // safe loop: free up any (unprotected) dynamic resource
1429 safe_free(dev_interface_details);
1430 safe_free(sanitized_path);
1431
1432 dev_interface_details = get_interface_details(ctx, &dev_info, &dev_info_data, guid, i);
1433 // safe loop: end of loop condition
1434 if ( (dev_interface_details == NULL)
1435 || (r != LIBUSB_SUCCESS) )
1436 break;
1437
1438 // Check that the driver installation is OK
1439 if ( (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data, SPDRP_INSTALL_STATE,
1440 &reg_type, (BYTE*)&install_state, 4, &size))
1441 && (size != 4) ){
1442 usbi_warn(ctx, "could not detect installation state of driver for %s: %s",
1443 dev_interface_details->DevicePath, windows_error_str(0));
1444 } else if (install_state != 0) {
1445 usbi_warn(ctx, "driver for device %s is reporting an issue (code: %d) - skipping",
1446 dev_interface_details->DevicePath, install_state);
1447 continue;
1448 }
1449
1450 // The SPDRP_ADDRESS for USB devices should be the device port number on the hub
1451 if ( (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data, SPDRP_ADDRESS,
1452 &reg_type, (BYTE*)&port_nr, 4, &size))
1453 && (size != 4) ){
1454 usbi_warn(ctx, "could not retrieve port number for device %s, skipping: %s",
1455 dev_interface_details->DevicePath, windows_error_str(0));
1456 continue;
1457 }
1458
1459 // Retrieve parent's path using PnP Configuration Manager (CM)
1460 if (CM_Get_Parent(&parent_devinst, dev_info_data.DevInst, 0) != CR_SUCCESS) {
1461 usbi_warn(ctx, "could not retrieve parent info data for device %s, skipping: %s",
1462 dev_interface_details->DevicePath, windows_error_str(0));
1463 continue;
1464 }
1465
1466 if (CM_Get_Device_ID(parent_devinst, path, MAX_PATH_LENGTH, 0) != CR_SUCCESS) {
1467 usbi_warn(ctx, "could not retrieve parent's path for device %s, skipping: %s",
1468 dev_interface_details->DevicePath, windows_error_str(0));
1469 continue;
1470 }
1471
1472 // Fix parent's path inconsistencies before attempting to compare
1473 sanitized_path = sanitize_path(path);
1474 if (sanitized_path == NULL) {
1475 usbi_warn(ctx, "could not sanitize parent's path for device %s, skipping.",
1476 dev_interface_details->DevicePath);
1477 continue;
1478 }
1479
1480 // With the parent path and port number, we should be able to locate our device
1481 // by comparing these values to the ones we got when enumerating hubs
1482 found = false;
1483 for (j=0; j<discdevs->len; j++) {
1484 priv = __device_priv(discdevs->devices[j]);
1485
1486 if (priv->parent_dev == NULL) {
1487 continue; // ignore HCDs
1488 }
1489
1490 parent_priv = __device_priv(priv->parent_dev);
1491
1492 // NB: we compare strings of different lengths below => strncmp
1493 if ( (safe_strncmp(parent_priv->path, sanitized_path, safe_strlen(sanitized_path)) == 0)
1494 && (port_nr == priv->connection_index) ) {
1495
1496 priv->path = sanitize_path(dev_interface_details->DevicePath);
1497
1498 usbi_dbg("path (%d:%d): %s", discdevs->devices[j]->bus_number,
1499 discdevs->devices[j]->device_address, priv->path);
1500
1501 // Check the service & filter names to know the API we should use
1502 for (k=0; k<3; k++) {
1503 if (SetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, lookup[k].reg_prop,
1504 &reg_type, (BYTE*)lookup[k].list, MAX_KEY_LENGTH, &size)) {
1505 // Turn the REG_SZ SPDRP_SERVICE into REG_MULTI_SZ
1506 if (lookup[k].reg_prop == SPDRP_SERVICE) {
1507 // our buffers are MAX_KEY_LENGTH+1 so we can overflow if needed
1508 lookup[k].list[safe_strlen(lookup[k].list)+1] = 0;
1509 }
1510 // MULTI_SZ is a pain to work with. Turn it into something much more manageable
1511 // NB: none of the driver names we check against contain LIST_SEPARATOR,
1512 // (currently ';'), so even if an unsuported one does, it's not an issue
1513 for (l=0; (lookup[k].list[l] != 0) || (lookup[k].list[l+1] != 0); l++) {
1514 if (lookup[k].list[l] == 0) {
1515 lookup[k].list[l] = LIST_SEPARATOR;
1516 }
1517 }
1518 upperize(lookup[k].list);
1519 usbi_dbg("%s(s): %s", lookup[k].designation, lookup[k].list);
1520 found = true;
1521 } else {
1522 if (GetLastError() != ERROR_INVALID_DATA) {
1523 usbi_dbg("could not access %s: %s", lookup[k].designation, windows_error_str(0));
1524 }
1525 lookup[k].list[0] = 0;
1526 }
1527 }
1528
1529 for (api=0; api<USB_API_MAX; api++) {
1530 for (k=0; k<3; k++) {
1531 if (is_api_driver(lookup[k].list, api)) {
1532 usbi_dbg("matched %s name against %s", lookup[k].designation, usb_api_backend[api].designation);
1533 break;
1534 }
1535 }
1536 if (k >= 3) continue;
1537 priv->apib = &usb_api_backend[api];
1538 switch(api) {
1539 case USB_API_COMPOSITE:
1540 set_composite_device(ctx, dev_info_data.DevInst, priv);
1541 break;
1542 case USB_API_HID:
1543 safe_free(priv->hid);
1544 priv->hid = calloc(1, sizeof(struct hid_device_priv));
1545 if (priv->hid == NULL) {
1546 usbi_err(ctx, "could not allocate HID data for %s, skipping",
1547 dev_interface_details->DevicePath);
1548 priv->apib = &usb_api_backend[USB_API_UNSUPPORTED];
1549 safe_free(priv->path);
1550 } else {
1551 set_hid_device(ctx, priv);
1552 }
1553 break;
1554 default:
1555 // For other devices, the first interface is the same as the device
1556 priv->usb_interface[0].path = malloc(safe_strlen(priv->path)+1);
1557 if (priv->usb_interface[0].path != NULL) {
1558 safe_strcpy(priv->usb_interface[0].path, safe_strlen(priv->path)+1, priv->path);
1559 }
1560 // The following is needed if we want to API calls to work for both simple
1561 // and composite devices, as
1562 for(k=0; k<USB_MAXINTERFACES; k++) {
1563 priv->usb_interface[k].apib = &usb_api_backend[api];
1564 }
1565 break;
1566 }
1567 }
1568 break;
1569 }
1570 }
1571 if (!found) {
1572 usbi_warn(ctx, "could not match %s with a libusb device.", dev_interface_details->DevicePath);
1573 continue;
1574 }
1575 }
1576
1577 return LIBUSB_SUCCESS;
1578}
1579
1580/*
1581 * get_device_list: libusb backend device enumeration function
1582 */
1583static int windows_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs)
1584{
1585 struct windows_hcd_priv* hcd;
1586 HANDLE handle = INVALID_HANDLE_VALUE;
1587 int r = LIBUSB_SUCCESS;
1588 libusb_bus_t bus;
1589
1590 // Use the index of the HCD in the chained list as bus #
1591 for (hcd = hcd_root, bus = 0; ; hcd = hcd->next, bus++)
1592 {
1593 safe_closehandle(handle);
1594
1595 if ( (hcd == NULL) || (r != LIBUSB_SUCCESS) )
1596 break;
1597
1598 if (bus == LIBUSB_BUS_MAX) {
1599 usbi_warn(ctx, "program assertion failed - got more than %d buses, skipping the rest.", LIBUSB_BUS_MAX);
1600 continue;
1601 }
1602
1603 handle = CreateFileA(hcd->path, GENERIC_WRITE, FILE_SHARE_WRITE,
1604 NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
1605 if (handle == INVALID_HANDLE_VALUE) {
1606 usbi_warn(ctx, "could not open bus %u, skipping: %s", bus, windows_error_str(0));
1607 continue;
1608 }
1609
1610 LOOP_CHECK(usb_enumerate_hub(ctx, _discdevs, handle, bus, NULL, 1));
1611 }
1612
1613 // Set the interface path for non-hubs
1614 r = set_device_paths(ctx, *_discdevs);
1615
1616 return r;
1617}
1618
1619/*
1620 * exit: libusb backend deinitialization function
1621 */
1622static void windows_exit(void)
1623{
1624 struct windows_hcd_priv* hcd_tmp;
1625 int i;
1626 HANDLE semaphore;
1627 TCHAR sem_name[11+1+8]; // strlen(libusb_init)+'\0'+(32-bit hex PID)
1628
1629 sprintf(sem_name, "libusb_init%08X", (unsigned int)GetCurrentProcessId()&0xFFFFFFFF);
1630 semaphore = CreateSemaphore(NULL, 1, 1, sem_name);
1631 if (semaphore == NULL) {
1632 return;
1633 }
1634
1635 // A successful wait brings our semaphore count to 0 (unsignaled)
1636 // => any concurent wait stalls until the semaphore release
1637 if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
1638 CloseHandle(semaphore);
1639 return;
1640 }
1641
1642 // Only works if exits and inits are balanced exactly
1643 if (--concurrent_usage < 0) { // Last exit
1644 while (hcd_root != NULL)
1645 {
1646 hcd_tmp = hcd_root; // Keep a copy for free
1647 hcd_root = hcd_root->next;
1648 windows_hcd_priv_release(hcd_tmp);
1649 safe_free(hcd_tmp);
1650 }
1651
1652 for (i=0; i<USB_API_MAX; i++) {
1653 usb_api_backend[i].exit();
1654 }
1655 exit_polling();
1656
1657 if (timer_thread) {
1658 SetEvent(timer_request[1]); // actually the signal to quit the thread.
1659 if (WAIT_OBJECT_0 != WaitForSingleObject(timer_thread, INFINITE)) {
1660 usbi_dbg("could not wait for timer thread to quit");
1661 TerminateThread(timer_thread, 1);
1662 }
1663 CloseHandle(timer_thread);
1664 timer_thread = NULL;
1665 }
1666 for (i = 0; i < 2; i++) {
1667 if (timer_request[i]) {
1668 CloseHandle(timer_request[i]);
1669 timer_request[i] = NULL;
1670 }
1671 }
1672 if (timer_response) {
1673 CloseHandle(timer_response);
1674 timer_response = NULL;
1675 }
1676 if (timer_mutex) {
1677 CloseHandle(timer_mutex);
1678 timer_mutex = NULL;
1679 }
1680 }
1681
1682 ReleaseSemaphore(semaphore, 1, NULL); // increase count back to 1
1683 CloseHandle(semaphore);
1684}
1685
1686static int windows_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian)
1687{
1688 struct windows_device_priv *priv = __device_priv(dev);
1689
1690 memcpy(buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
1691 *host_endian = 0;
1692
1693 return LIBUSB_SUCCESS;
1694}
1695
1696static int windows_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
1697{
1698 struct windows_device_priv *priv = __device_priv(dev);
1699 PUSB_CONFIGURATION_DESCRIPTOR config_header;
1700 size_t size;
1701
1702 // config index is zero based
1703 if (config_index >= dev->num_configurations)
1704 return LIBUSB_ERROR_INVALID_PARAM;
1705
1706 if ((priv->config_descriptor == NULL) || (priv->config_descriptor[config_index] == NULL))
1707 return LIBUSB_ERROR_NOT_FOUND;
1708
1709 config_header = (PUSB_CONFIGURATION_DESCRIPTOR)priv->config_descriptor[config_index];
1710
1711 size = min(config_header->wTotalLength, len);
1712 memcpy(buffer, priv->config_descriptor[config_index], size);
1713
1714 return LIBUSB_SUCCESS;
1715}
1716
1717/*
1718 * return the cached copy of the active config descriptor
1719 */
1720static int windows_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian)
1721{
1722 struct windows_device_priv *priv = __device_priv(dev);
1723
1724 if (priv->active_config == 0)
1725 return LIBUSB_ERROR_NOT_FOUND;
1726
1727 // config index is zero based
1728 return windows_get_config_descriptor(dev, (uint8_t)(priv->active_config-1), buffer, len, host_endian);
1729}
1730
1731static int windows_open(struct libusb_device_handle *dev_handle)
1732{
1733 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
1734 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
1735
1736 if (priv->apib == NULL) {
1737 usbi_err(ctx, "program assertion failed - device is not initialized");
1738 return LIBUSB_ERROR_NO_DEVICE;
1739 }
1740
1741 return priv->apib->open(dev_handle);
1742}
1743
1744static void windows_close(struct libusb_device_handle *dev_handle)
1745{
1746 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
1747
1748 priv->apib->close(dev_handle);
1749}
1750
1751static int windows_get_configuration(struct libusb_device_handle *dev_handle, int *config)
1752{
1753 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
1754
1755 if (priv->active_config == 0) {
1756 *config = 0;
1757 return LIBUSB_ERROR_NOT_FOUND;
1758 }
1759
1760 *config = priv->active_config;
1761 return LIBUSB_SUCCESS;
1762}
1763
1764/*
1765 * from http://msdn.microsoft.com/en-us/library/ms793522.aspx: "The port driver
1766 * does not currently expose a service that allows higher-level drivers to set
1767 * the configuration."
1768 */
1769static int windows_set_configuration(struct libusb_device_handle *dev_handle, int config)
1770{
1771 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
1772 int r = LIBUSB_SUCCESS;
1773
1774 if (config >= USB_MAXCONFIG)
1775 return LIBUSB_ERROR_INVALID_PARAM;
1776
1777 r = libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_OUT |
1778 LIBUSB_REQUEST_TYPE_STANDARD | LIBUSB_RECIPIENT_DEVICE,
1779 LIBUSB_REQUEST_SET_CONFIGURATION, (uint16_t)config,
1780 0, NULL, 0, 1000);
1781
1782 if (r == LIBUSB_SUCCESS) {
1783 priv->active_config = (uint8_t)config;
1784 }
1785 return r;
1786}
1787
1788static int windows_claim_interface(struct libusb_device_handle *dev_handle, int iface)
1789{
1790 int r = LIBUSB_SUCCESS;
1791 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
1792
1793 if (iface >= USB_MAXINTERFACES)
1794 return LIBUSB_ERROR_INVALID_PARAM;
1795
1796 safe_free(priv->usb_interface[iface].endpoint);
1797 priv->usb_interface[iface].nb_endpoints= 0;
1798
1799 r = priv->apib->claim_interface(dev_handle, iface);
1800
1801 if (r == LIBUSB_SUCCESS) {
1802 r = windows_assign_endpoints(dev_handle->dev, iface, 0);
1803 }
1804
1805 return r;
1806}
1807
1808static int windows_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
1809{
1810 int r = LIBUSB_SUCCESS;
1811 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
1812
1813 safe_free(priv->usb_interface[iface].endpoint);
1814 priv->usb_interface[iface].nb_endpoints= 0;
1815
1816 r = priv->apib->set_interface_altsetting(dev_handle, iface, altsetting);
1817
1818 if (r == LIBUSB_SUCCESS) {
1819 r = windows_assign_endpoints(dev_handle->dev, iface, altsetting);
1820 }
1821
1822 return r;
1823}
1824
1825static int windows_release_interface(struct libusb_device_handle *dev_handle, int iface)
1826{
1827 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
1828
1829 windows_set_interface_altsetting(dev_handle, iface, 0);
1830 return priv->apib->release_interface(dev_handle, iface);
1831}
1832
1833static int windows_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
1834{
1835 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
1836 return priv->apib->clear_halt(dev_handle, endpoint);
1837}
1838
1839static int windows_reset_device(struct libusb_device_handle *dev_handle)
1840{
1841 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
1842 return priv->apib->reset_device(dev_handle);
1843}
1844
1845// The 3 functions below are unlikely to ever get supported on Windows
1846static int windows_kernel_driver_active(struct libusb_device_handle *dev_handle, int iface)
1847{
1848 return LIBUSB_ERROR_NOT_SUPPORTED;
1849}
1850
1851static int windows_attach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
1852{
1853 return LIBUSB_ERROR_NOT_SUPPORTED;
1854}
1855
1856static int windows_detach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
1857{
1858 return LIBUSB_ERROR_NOT_SUPPORTED;
1859}
1860
1861static void windows_destroy_device(struct libusb_device *dev)
1862{
1863 struct windows_device_priv *priv = __device_priv(dev);
1864 windows_device_priv_release(priv, dev->num_configurations);
1865}
1866
1867static void windows_clear_transfer_priv(struct usbi_transfer *itransfer)
1868{
1869 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
1870
1871 usbi_free_fd(transfer_priv->pollable_fd.fd);
1872 safe_free(transfer_priv->hid_buffer);
1873#if defined(AUTO_CLAIM)
1874 // When auto claim is in use, attempt to release the auto-claimed interface
1875 auto_release(itransfer);
1876#endif
1877}
1878
1879static int submit_bulk_transfer(struct usbi_transfer *itransfer)
1880{
1881 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1882 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1883 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
1884 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
1885 int r;
1886
1887 r = priv->apib->submit_bulk_transfer(itransfer);
1888 if (r != LIBUSB_SUCCESS) {
1889 return r;
1890 }
1891
1892 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd,
1893 (short)((transfer->endpoint & LIBUSB_ENDPOINT_IN)?POLLIN:POLLOUT));
1894#if !defined(DYNAMIC_FDS)
1895 usbi_fd_notification(ctx);
1896#endif
1897
1898 return LIBUSB_SUCCESS;
1899}
1900
1901static int submit_iso_transfer(struct usbi_transfer *itransfer)
1902{
1903 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1904 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1905 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
1906 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
1907 int r;
1908
1909 r = priv->apib->submit_iso_transfer(itransfer);
1910 if (r != LIBUSB_SUCCESS) {
1911 return r;
1912 }
1913
1914 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd,
1915 (short)((transfer->endpoint & LIBUSB_ENDPOINT_IN)?POLLIN:POLLOUT));
1916#if !defined(DYNAMIC_FDS)
1917 usbi_fd_notification(ctx);
1918#endif
1919
1920 return LIBUSB_SUCCESS;
1921}
1922
1923static int submit_control_transfer(struct usbi_transfer *itransfer)
1924{
1925 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1926 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1927 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
1928 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
1929 int r;
1930
1931 r = priv->apib->submit_control_transfer(itransfer);
1932 if (r != LIBUSB_SUCCESS) {
1933 return r;
1934 }
1935
1936 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd, POLLIN);
1937#if !defined(DYNAMIC_FDS)
1938 usbi_fd_notification(ctx);
1939#endif
1940
1941 return LIBUSB_SUCCESS;
1942
1943}
1944
1945static int windows_submit_transfer(struct usbi_transfer *itransfer)
1946{
1947 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1948
1949 switch (transfer->type) {
1950 case LIBUSB_TRANSFER_TYPE_CONTROL:
1951 return submit_control_transfer(itransfer);
1952 case LIBUSB_TRANSFER_TYPE_BULK:
1953 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1954 return submit_bulk_transfer(itransfer);
1955 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1956 return submit_iso_transfer(itransfer);
1957 default:
1958 usbi_err(TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1959 return LIBUSB_ERROR_INVALID_PARAM;
1960 }
1961}
1962
1963static int windows_abort_control(struct usbi_transfer *itransfer)
1964{
1965 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1966 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
1967
1968 return priv->apib->abort_control(itransfer);
1969}
1970
1971static int windows_abort_transfers(struct usbi_transfer *itransfer)
1972{
1973 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1974 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
1975
1976 return priv->apib->abort_transfers(itransfer);
1977}
1978
1979static int windows_cancel_transfer(struct usbi_transfer *itransfer)
1980{
1981 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1982#if defined(FORCE_INSTANT_TIMEOUTS)
1983 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
1984
1985 // Forces instant overlapped completion on timeouts - use at your own risks
1986 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT) {
1987 transfer_priv->pollable_fd.overlapped->Internal &= ~STATUS_PENDING;
1988 }
1989#endif
1990 switch (transfer->type) {
1991 case LIBUSB_TRANSFER_TYPE_CONTROL:
1992 return windows_abort_control(itransfer);
1993 case LIBUSB_TRANSFER_TYPE_BULK:
1994 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1995 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1996 return windows_abort_transfers(itransfer);
1997 default:
1998 usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type);
1999 return LIBUSB_ERROR_INVALID_PARAM;
2000 }
2001}
2002
2003static void windows_transfer_callback(struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size)
2004{
2005 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2006 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
2007 int status;
2008
2009 usbi_dbg("handling I/O completion with errcode %d", io_result);
2010
2011 switch(io_result) {
2012 case NO_ERROR:
2013 status = priv->apib->copy_transfer_data(itransfer, io_size);
2014 break;
2015 case ERROR_GEN_FAILURE:
2016 usbi_dbg("detected endpoint stall");
2017 status = LIBUSB_TRANSFER_STALL;
2018 break;
2019 case ERROR_SEM_TIMEOUT:
2020 usbi_dbg("detected semaphore timeout");
2021 status = LIBUSB_TRANSFER_TIMED_OUT;
2022 break;
2023 case ERROR_OPERATION_ABORTED:
2024 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT) {
2025 usbi_dbg("detected timeout");
2026 status = LIBUSB_TRANSFER_TIMED_OUT;
2027 } else {
2028 usbi_dbg("detected operation aborted");
2029 status = LIBUSB_TRANSFER_CANCELLED;
2030 }
2031 break;
2032 default:
2033 usbi_err(ITRANSFER_CTX(itransfer), "detected I/O error: %s", windows_error_str(0));
2034 status = LIBUSB_TRANSFER_ERROR;
2035 break;
2036 }
2037 windows_clear_transfer_priv(itransfer); // Cancel polling
2038 usbi_handle_transfer_completion(itransfer, status);
2039}
2040
2041static void windows_handle_callback (struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size)
2042{
2043 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2044
2045 switch (transfer->type) {
2046 case LIBUSB_TRANSFER_TYPE_CONTROL:
2047 case LIBUSB_TRANSFER_TYPE_BULK:
2048 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2049 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2050 windows_transfer_callback (itransfer, io_result, io_size);
2051 break;
2052 default:
2053 usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type);
2054 }
2055}
2056
2057static int windows_handle_events(struct libusb_context *ctx, struct pollfd *fds, nfds_t nfds, int num_ready)
2058{
2059 struct windows_transfer_priv* transfer_priv = NULL;
2060 nfds_t i = 0;
2061 bool found = false;
2062 struct usbi_transfer *transfer;
2063 DWORD io_size, io_result;
2064
2065 usbi_mutex_lock(&ctx->open_devs_lock);
2066 for (i = 0; i < nfds && num_ready > 0; i++) {
2067
2068 usbi_dbg("checking fd %d with revents = %04x", fds[i].fd, fds[i].revents);
2069
2070 if (!fds[i].revents) {
2071 continue;
2072 }
2073
2074 num_ready--;
2075
2076 // Because a Windows OVERLAPPED is used for poll emulation,
2077 // a pollable fd is created and stored with each transfer
2078 usbi_mutex_lock(&ctx->flying_transfers_lock);
2079 list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) {
2080 transfer_priv = usbi_transfer_get_os_priv(transfer);
2081 if (transfer_priv->pollable_fd.fd == fds[i].fd) {
2082 found = true;
2083 break;
2084 }
2085 }
2086 usbi_mutex_unlock(&ctx->flying_transfers_lock);
2087
2088 if (found) {
2089 // Handle async requests that completed synchronously first
2090 if (HasOverlappedIoCompletedSync(transfer_priv->pollable_fd.overlapped)) {
2091 io_result = NO_ERROR;
2092 io_size = (DWORD)transfer_priv->pollable_fd.overlapped->InternalHigh;
2093 // Regular async overlapped
2094 } else if (GetOverlappedResult(transfer_priv->pollable_fd.handle,
2095 transfer_priv->pollable_fd.overlapped, &io_size, false)) {
2096 io_result = NO_ERROR;
2097 } else {
2098 io_result = GetLastError();
2099 }
2100 usbi_remove_pollfd(ctx, transfer_priv->pollable_fd.fd);
2101 // let handle_callback free the event using the transfer wfd
2102 // If you don't use the transfer wfd, you run a risk of trying to free a
2103 // newly allocated wfd that took the place of the one from the transfer.
2104 windows_handle_callback(transfer, io_result, io_size);
2105 } else {
2106 usbi_err(ctx, "could not find a matching transfer for fd %x", fds[i]);
2107 return LIBUSB_ERROR_NOT_FOUND;
2108 }
2109 }
2110
2111 usbi_mutex_unlock(&ctx->open_devs_lock);
2112 return LIBUSB_SUCCESS;
2113}
2114
2115/*
2116 * Monotonic and real time functions
2117 */
2118unsigned __stdcall windows_clock_gettime_threaded(void* param)
2119{
2120 LARGE_INTEGER hires_counter, li_frequency;
2121 LONG nb_responses;
2122 int timer_index;
2123
2124 // Init - find out if we have access to a monotonic (hires) timer
2125 if (!QueryPerformanceFrequency(&li_frequency)) {
2126 usbi_dbg("no hires timer available on this platform");
2127 hires_frequency = 0;
2128 hires_ticks_to_ps = UINT64_C(0);
2129 } else {
2130 hires_frequency = li_frequency.QuadPart;
2131 // The hires frequency can go as high as 4 GHz, so we'll use a conversion
2132 // to picoseconds to compute the tv_nsecs part in clock_gettime
2133 hires_ticks_to_ps = UINT64_C(1000000000000) / hires_frequency;
2134 usbi_dbg("hires timer available (Frequency: %"PRIu64" Hz)", hires_frequency);
2135 }
2136
2137 // Main loop - wait for requests
2138 while (1) {
2139 timer_index = WaitForMultipleObjects(2, timer_request, FALSE, INFINITE) - WAIT_OBJECT_0;
2140 if ( (timer_index != 0) && (timer_index != 1) ) {
2141 usbi_dbg("failure to wait on requests: %s", windows_error_str(0));
2142 continue;
2143 }
2144 if (request_count[timer_index] == 0) {
2145 // Request already handled
2146 ResetEvent(timer_request[timer_index]);
2147 // There's still a possiblity that a thread sends a request between the
2148 // time we test request_count[] == 0 and we reset the event, in which case
2149 // the request would be ignored. The simple solution to that is to test
2150 // request_count again and process requests if non zero.
2151 if (request_count[timer_index] == 0)
2152 continue;
2153 }
2154 switch (timer_index) {
2155 case 0:
2156 WaitForSingleObject(timer_mutex, INFINITE);
2157 // Requests to this thread are for hires always
2158 if (QueryPerformanceCounter(&hires_counter) != 0) {
2159 timer_tp.tv_sec = (long)(hires_counter.QuadPart / hires_frequency);
2160 timer_tp.tv_nsec = (long)(((hires_counter.QuadPart % hires_frequency)/1000) * hires_ticks_to_ps);
2161 } else {
2162 // Fallback to real-time if we can't get monotonic value
2163 // Note that real-time clock does not wait on the mutex or this thread.
2164 windows_clock_gettime(USBI_CLOCK_REALTIME, &timer_tp);
2165 }
2166 ReleaseMutex(timer_mutex);
2167
2168 nb_responses = InterlockedExchange((LONG*)&request_count[0], 0);
2169 if ( (nb_responses)
2170 && (ReleaseSemaphore(timer_response, nb_responses, NULL) == 0) ) {
2171 usbi_dbg("unable to release timer semaphore %d: %s", windows_error_str(0));
2172 }
2173 continue;
2174 case 1: // time to quit
2175 usbi_dbg("timer thread quitting");
2176 return 0;
2177 }
2178 }
2179 usbi_dbg("ERROR: broken timer thread");
2180 return 1;
2181}
2182
2183static int windows_clock_gettime(int clk_id, struct timespec *tp)
2184{
2185 FILETIME filetime;
2186 ULARGE_INTEGER rtime;
2187 DWORD r;
2188 switch(clk_id) {
2189 case USBI_CLOCK_MONOTONIC:
2190 if (hires_frequency != 0) {
2191 while (1) {
2192 InterlockedIncrement((LONG*)&request_count[0]);
2193 SetEvent(timer_request[0]);
2194 r = WaitForSingleObject(timer_response, TIMER_REQUEST_RETRY_MS);
2195 switch(r) {
2196 case WAIT_OBJECT_0:
2197 WaitForSingleObject(timer_mutex, INFINITE);
2198 *tp = timer_tp;
2199 ReleaseMutex(timer_mutex);
2200 return LIBUSB_SUCCESS;
2201 case WAIT_TIMEOUT:
2202 usbi_dbg("could not obtain a timer value within reasonable timeframe - too much load?");
2203 break; // Retry until successful
2204 default:
2205 usbi_dbg("WaitForSingleObject failed: %s", windows_error_str(0));
2206 return LIBUSB_ERROR_OTHER;
2207 }
2208 }
2209 }
2210 // Fall through and return real-time if monotonic was not detected @ timer init
2211 case USBI_CLOCK_REALTIME:
2212 // We follow http://msdn.microsoft.com/en-us/library/ms724928%28VS.85%29.aspx
2213 // with a predef epoch_time to have an epoch that starts at 1970.01.01 00:00
2214 // Note however that our resolution is bounded by the Windows system time
2215 // functions and is at best of the order of 1 ms (or, usually, worse)
2216 GetSystemTimeAsFileTime(&filetime);
2217 rtime.LowPart = filetime.dwLowDateTime;
2218 rtime.HighPart = filetime.dwHighDateTime;
2219 rtime.QuadPart -= epoch_time;
2220 tp->tv_sec = (long)(rtime.QuadPart / 10000000);
2221 tp->tv_nsec = (long)((rtime.QuadPart % 10000000)*100);
2222 return LIBUSB_SUCCESS;
2223 default:
2224 return LIBUSB_ERROR_INVALID_PARAM;
2225 }
2226}
2227
2228
2229// NB: MSVC6 does not support named initializers.
2230const struct usbi_os_backend windows_backend = {
2231 "Windows",
2232 windows_init,
2233 windows_exit,
2234
2235 windows_get_device_list,
2236 windows_open,
2237 windows_close,
2238
2239 windows_get_device_descriptor,
2240 windows_get_active_config_descriptor,
2241 windows_get_config_descriptor,
2242
2243 windows_get_configuration,
2244 windows_set_configuration,
2245 windows_claim_interface,
2246 windows_release_interface,
2247
2248 windows_set_interface_altsetting,
2249 windows_clear_halt,
2250 windows_reset_device,
2251
2252 windows_kernel_driver_active,
2253 windows_detach_kernel_driver,
2254 windows_attach_kernel_driver,
2255
2256 windows_destroy_device,
2257
2258 windows_submit_transfer,
2259 windows_cancel_transfer,
2260 windows_clear_transfer_priv,
2261
2262 windows_handle_events,
2263
2264 windows_clock_gettime,
2265#if defined(USBI_TIMERFD_AVAILABLE)
2266 NULL,
2267#endif
2268 sizeof(struct windows_device_priv),
2269 sizeof(struct windows_device_handle_priv),
2270 sizeof(struct windows_transfer_priv),
2271 0,
2272};
2273
2274
2275/*
2276 * USB API backends
2277 */
2278static int unsupported_init(struct libusb_context *ctx) {
2279 return LIBUSB_SUCCESS;
2280}
2281static int unsupported_exit(void) {
2282 return LIBUSB_SUCCESS;
2283}
2284static int unsupported_open(struct libusb_device_handle *dev_handle) {
2285 PRINT_UNSUPPORTED_API(open);
2286}
2287static void unsupported_close(struct libusb_device_handle *dev_handle) {
2288 usbi_dbg("unsupported API call for 'close'");
2289}
2290static int unsupported_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
2291 PRINT_UNSUPPORTED_API(claim_interface);
2292}
2293static int unsupported_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
2294 PRINT_UNSUPPORTED_API(set_interface_altsetting);
2295}
2296static int unsupported_release_interface(struct libusb_device_handle *dev_handle, int iface) {
2297 PRINT_UNSUPPORTED_API(release_interface);
2298}
2299static int unsupported_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
2300 PRINT_UNSUPPORTED_API(clear_halt);
2301}
2302static int unsupported_reset_device(struct libusb_device_handle *dev_handle) {
2303 PRINT_UNSUPPORTED_API(reset_device);
2304}
2305static int unsupported_submit_bulk_transfer(struct usbi_transfer *itransfer) {
2306 PRINT_UNSUPPORTED_API(submit_bulk_transfer);
2307}
2308static int unsupported_submit_iso_transfer(struct usbi_transfer *itransfer) {
2309 PRINT_UNSUPPORTED_API(submit_iso_transfer);
2310}
2311static int unsupported_submit_control_transfer(struct usbi_transfer *itransfer) {
2312 PRINT_UNSUPPORTED_API(submit_control_transfer);
2313}
2314static int unsupported_abort_control(struct usbi_transfer *itransfer) {
2315 PRINT_UNSUPPORTED_API(abort_control);
2316}
2317static int unsupported_abort_transfers(struct usbi_transfer *itransfer) {
2318 PRINT_UNSUPPORTED_API(abort_transfers);
2319}
2320static int unsupported_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size) {
2321 PRINT_UNSUPPORTED_API(copy_transfer_data);
2322}
2323
2324// These names must be uppercase
2325const char* composite_driver_names[] = {"USBCCGP"};
2326const char* winusb_driver_names[] = {"WINUSB"};
2327const char* hid_driver_names[] = {"HIDUSB", "MOUHID", "KBDHID"};
2328const struct windows_usb_api_backend usb_api_backend[USB_API_MAX] = {
2329 {
2330 USB_API_UNSUPPORTED,
2331 "Unsupported API",
2332 &CLASS_GUID_UNSUPPORTED,
2333 NULL,
2334 0,
2335 unsupported_init,
2336 unsupported_exit,
2337 unsupported_open,
2338 unsupported_close,
2339 unsupported_claim_interface,
2340 unsupported_set_interface_altsetting,
2341 unsupported_release_interface,
2342 unsupported_clear_halt,
2343 unsupported_reset_device,
2344 unsupported_submit_bulk_transfer,
2345 unsupported_submit_iso_transfer,
2346 unsupported_submit_control_transfer,
2347 unsupported_abort_control,
2348 unsupported_abort_transfers,
2349 unsupported_copy_transfer_data,
2350 }, {
2351 USB_API_COMPOSITE,
2352 "Composite API",
2353 &CLASS_GUID_COMPOSITE,
2354 composite_driver_names,
2355 sizeof(composite_driver_names)/sizeof(composite_driver_names[0]),
2356 composite_init,
2357 composite_exit,
2358 composite_open,
2359 composite_close,
2360 composite_claim_interface,
2361 composite_set_interface_altsetting,
2362 composite_release_interface,
2363 composite_clear_halt,
2364 composite_reset_device,
2365 composite_submit_bulk_transfer,
2366 composite_submit_iso_transfer,
2367 composite_submit_control_transfer,
2368 composite_abort_control,
2369 composite_abort_transfers,
2370 composite_copy_transfer_data,
2371 }, {
2372 USB_API_WINUSB,
2373 "WinUSB API",
2374 &CLASS_GUID_LIBUSB_WINUSB,
2375 winusb_driver_names,
2376 sizeof(winusb_driver_names)/sizeof(winusb_driver_names[0]),
2377 winusb_init,
2378 winusb_exit,
2379 winusb_open,
2380 winusb_close,
2381 winusb_claim_interface,
2382 winusb_set_interface_altsetting,
2383 winusb_release_interface,
2384 winusb_clear_halt,
2385 winusb_reset_device,
2386 winusb_submit_bulk_transfer,
2387 unsupported_submit_iso_transfer,
2388 winusb_submit_control_transfer,
2389 winusb_abort_control,
2390 winusb_abort_transfers,
2391 winusb_copy_transfer_data,
2392 }, {
2393 USB_API_HID,
2394 "HID API",
2395 &CLASS_GUID_HID,
2396 hid_driver_names,
2397 sizeof(hid_driver_names)/sizeof(hid_driver_names[0]),
2398 hid_init,
2399 hid_exit,
2400 hid_open,
2401 hid_close,
2402 hid_claim_interface,
2403 hid_set_interface_altsetting,
2404 hid_release_interface,
2405 hid_clear_halt,
2406 hid_reset_device,
2407 hid_submit_bulk_transfer,
2408 unsupported_submit_iso_transfer,
2409 hid_submit_control_transfer,
2410 hid_abort_transfers,
2411 hid_abort_transfers,
2412 hid_copy_transfer_data,
2413 },
2414};
2415
2416
2417/*
2418 * WinUSB API functions
2419 */
2420static int winusb_init(struct libusb_context *ctx)
2421{
2422 DLL_LOAD(winusb.dll, WinUsb_Initialize, TRUE);
2423 DLL_LOAD(winusb.dll, WinUsb_Free, TRUE);
2424 DLL_LOAD(winusb.dll, WinUsb_GetAssociatedInterface, TRUE);
2425 DLL_LOAD(winusb.dll, WinUsb_GetDescriptor, TRUE);
2426 DLL_LOAD(winusb.dll, WinUsb_QueryInterfaceSettings, TRUE);
2427 DLL_LOAD(winusb.dll, WinUsb_QueryDeviceInformation, TRUE);
2428 DLL_LOAD(winusb.dll, WinUsb_SetCurrentAlternateSetting, TRUE);
2429 DLL_LOAD(winusb.dll, WinUsb_GetCurrentAlternateSetting, TRUE);
2430 DLL_LOAD(winusb.dll, WinUsb_QueryPipe, TRUE);
2431 DLL_LOAD(winusb.dll, WinUsb_SetPipePolicy, TRUE);
2432 DLL_LOAD(winusb.dll, WinUsb_GetPipePolicy, TRUE);
2433 DLL_LOAD(winusb.dll, WinUsb_ReadPipe, TRUE);
2434 DLL_LOAD(winusb.dll, WinUsb_WritePipe, TRUE);
2435 DLL_LOAD(winusb.dll, WinUsb_ControlTransfer, TRUE);
2436 DLL_LOAD(winusb.dll, WinUsb_ResetPipe, TRUE);
2437 DLL_LOAD(winusb.dll, WinUsb_AbortPipe, TRUE);
2438 DLL_LOAD(winusb.dll, WinUsb_FlushPipe, TRUE);
2439
2440 api_winusb_available = true;
2441 return LIBUSB_SUCCESS;
2442}
2443
2444static int winusb_exit(void)
2445{
2446 return LIBUSB_SUCCESS;
2447}
2448
2449// NB: open and close must ensure that they only handle interface of
2450// the right API type, as these functions can be called wholesale from
2451// composite_open(), with interfaces belonging to different APIs
2452static int winusb_open(struct libusb_device_handle *dev_handle)
2453{
2454 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2455 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
2456 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
2457
2458 HANDLE file_handle;
2459 int i;
2460
2461 CHECK_WINUSB_AVAILABLE;
2462
2463 // WinUSB requires a seperate handle for each interface
2464 for (i = 0; i < USB_MAXINTERFACES; i++) {
2465 if ( (priv->usb_interface[i].path != NULL)
2466 && (priv->usb_interface[i].apib->id == USB_API_WINUSB) ) {
2467 file_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
2468 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
2469 if (file_handle == INVALID_HANDLE_VALUE) {
2470 usbi_err(ctx, "could not open device %s (interface %d): %s", priv->usb_interface[i].path, i, windows_error_str(0));
2471 switch(GetLastError()) {
2472 case ERROR_FILE_NOT_FOUND: // The device was disconnected
2473 return LIBUSB_ERROR_NO_DEVICE;
2474 case ERROR_ACCESS_DENIED:
2475 return LIBUSB_ERROR_ACCESS;
2476 default:
2477 return LIBUSB_ERROR_IO;
2478 }
2479 }
2480 handle_priv->interface_handle[i].dev_handle = file_handle;
2481 }
2482 }
2483
2484 return LIBUSB_SUCCESS;
2485}
2486
2487static void winusb_close(struct libusb_device_handle *dev_handle)
2488{
2489 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
2490 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
2491 HANDLE file_handle;
2492 int i;
2493
2494 if (!api_winusb_available)
2495 return;
2496
2497 for (i = 0; i < USB_MAXINTERFACES; i++) {
2498 if (priv->usb_interface[i].apib->id == USB_API_WINUSB) {
2499 file_handle = handle_priv->interface_handle[i].dev_handle;
2500 if ( (file_handle != 0) && (file_handle != INVALID_HANDLE_VALUE)) {
2501 CloseHandle(file_handle);
2502 }
2503 }
2504 }
2505}
2506
2507static int winusb_claim_interface(struct libusb_device_handle *dev_handle, int iface)
2508{
2509 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2510 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
2511 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
2512 bool is_composite = (priv->apib->id == USB_API_COMPOSITE);
2513 HANDLE file_handle, winusb_handle;
2514 USB_INTERFACE_DESCRIPTOR if_desc;
2515 UCHAR policy;
2516 uint8_t endpoint_address;
2517 int i;
2518
2519 CHECK_WINUSB_AVAILABLE;
2520
2521 // interfaces for composite devices are always independent, therefore
2522 // "alt" interfaces are only found on non-composite
2523 if ((!is_composite) && (iface != 0)) {
2524 winusb_handle = handle_priv->interface_handle[0].api_handle;
2525 // It is a requirement on Windows that to claim an interface >= 1
2526 // on a non-composite WinUSB device, you must first have claimed interface 0
2527 if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
2528#if defined(AUTO_CLAIM)
2529 file_handle = handle_priv->interface_handle[0].dev_handle;
2530 if (WinUsb_Initialize(file_handle, &winusb_handle)) {
2531 handle_priv->interface_handle[0].api_handle = winusb_handle;
2532 usbi_warn(ctx, "auto-claimed interface 0 (required to claim %d with WinUSB)", iface);
2533 } else {
2534 usbi_warn(ctx, "failed to auto-claim interface 0 (required to claim %d with WinUSB)", iface);
2535 return LIBUSB_ERROR_ACCESS;
2536 }
2537#else
2538 usbi_warn(ctx, "you must claim interface 0 before you can claim %d with WinUSB", iface);
2539 return LIBUSB_ERROR_ACCESS;
2540#endif
2541 }
2542 if (!WinUsb_GetAssociatedInterface(winusb_handle, (UCHAR)(iface-1),
2543 &handle_priv->interface_handle[iface].api_handle)) {
2544 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2545 switch(GetLastError()) {
2546 case ERROR_NO_MORE_ITEMS: // invalid iface
2547 return LIBUSB_ERROR_NOT_FOUND;
2548 case ERROR_BAD_COMMAND: // The device was disconnected
2549 return LIBUSB_ERROR_NO_DEVICE;
2550 case ERROR_ALREADY_EXISTS: // already claimed
2551 return LIBUSB_ERROR_BUSY;
2552 default:
2553 usbi_err(ctx, "could not claim interface %d: %s", iface, windows_error_str(0));
2554 return LIBUSB_ERROR_ACCESS;
2555 }
2556 }
2557 } else {
2558 // composite device (independent interfaces) or interface 0
2559 winusb_handle = handle_priv->interface_handle[iface].api_handle;
2560 file_handle = handle_priv->interface_handle[iface].dev_handle;
2561 if ((file_handle == 0) || (file_handle == INVALID_HANDLE_VALUE)) {
2562 return LIBUSB_ERROR_NOT_FOUND;
2563 }
2564
2565 if (!WinUsb_Initialize(file_handle, &winusb_handle)) {
2566 usbi_err(ctx, "could not access interface %d: %s", iface, windows_error_str(0));
2567 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2568
2569 switch(GetLastError()) {
2570 case ERROR_BAD_COMMAND: // The device was disconnected
2571 return LIBUSB_ERROR_NO_DEVICE;
2572 default:
2573 usbi_err(ctx, "could not claim interface %d: %s", iface, windows_error_str(0));
2574 return LIBUSB_ERROR_ACCESS;
2575 }
2576 }
2577 handle_priv->interface_handle[iface].api_handle = winusb_handle;
2578 }
2579 if (!WinUsb_QueryInterfaceSettings(winusb_handle, 0, &if_desc)) {
2580 usbi_err(ctx, "could not query interface settings for interface %d: %s", iface, windows_error_str(0));
2581 } else if (if_desc.bInterfaceNumber != iface) {
2582 usbi_warn(ctx, "program assertion failed - WinUSB interface %d found at position %d",
2583 if_desc.bInterfaceNumber, iface);
2584 }
2585
2586 usbi_dbg("claimed interface %d", iface);
2587 handle_priv->active_interface = iface;
2588
2589 // With handle and enpoints set (in parent), we can setup the default
2590 // pipe properties (copied from libusb-win32-v1)
2591 // see http://download.microsoft.com/download/D/1/D/D1DD7745-426B-4CC3-A269-ABBBE427C0EF/DVC-T705_DDC08.pptx
2592 for (i=0; i<priv->usb_interface[iface].nb_endpoints; i++) {
2593 endpoint_address = priv->usb_interface[iface].endpoint[i];
2594 policy = false;
2595 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2596 SHORT_PACKET_TERMINATE, sizeof(UCHAR), &policy)) {
2597 usbi_dbg("failed to disable SHORT_PACKET_TERMINATE for endpoint %02X", endpoint_address);
2598 }
2599 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2600 IGNORE_SHORT_PACKETS, sizeof(UCHAR), &policy)) {
2601 usbi_dbg("failed to disable IGNORE_SHORT_PACKETS for endpoint %02X", endpoint_address);
2602 }
2603 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2604 ALLOW_PARTIAL_READS, sizeof(UCHAR), &policy)) {
2605 usbi_dbg("failed to disable ALLOW_PARTIAL_READS for endpoint %02X", endpoint_address);
2606 }
2607 policy = true;
2608 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2609 AUTO_CLEAR_STALL, sizeof(UCHAR), &policy)) {
2610 usbi_dbg("failed to enable AUTO_CLEAR_STALL for endpoint %02X", endpoint_address);
2611 }
2612 }
2613
2614 return LIBUSB_SUCCESS;
2615}
2616
2617static int winusb_release_interface(struct libusb_device_handle *dev_handle, int iface)
2618{
2619 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
2620 HANDLE winusb_handle;
2621
2622 CHECK_WINUSB_AVAILABLE;
2623
2624 winusb_handle = handle_priv->interface_handle[iface].api_handle;
2625 if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
2626 return LIBUSB_ERROR_NOT_FOUND;
2627 }
2628
2629 WinUsb_Free(winusb_handle);
2630 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2631
2632 return LIBUSB_SUCCESS;
2633}
2634
2635/*
2636 * Return the first valid interface (of the same API type), for control transfers
2637 */
2638static int get_valid_interface(struct libusb_device_handle *dev_handle, int api_id)
2639{
2640 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
2641 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
2642 int i;
2643
2644 if ((api_id < USB_API_WINUSB) || (api_id > USB_API_HID)) {
2645 usbi_dbg("unsupported API ID");
2646 return -1;
2647 }
2648
2649 for (i=0; i<USB_MAXINTERFACES; i++) {
2650 if ( (handle_priv->interface_handle[i].dev_handle != 0)
2651 && (handle_priv->interface_handle[i].dev_handle != INVALID_HANDLE_VALUE)
2652 && (handle_priv->interface_handle[i].api_handle != 0)
2653 && (handle_priv->interface_handle[i].api_handle != INVALID_HANDLE_VALUE)
2654 && (priv->usb_interface[i].apib == &usb_api_backend[api_id]) ) {
2655 return i;
2656 }
2657 }
2658 return -1;
2659}
2660
2661/*
2662 * Lookup interface by endpoint address. -1 if not found
2663 */
2664static int interface_by_endpoint(struct windows_device_priv *priv,
2665 struct windows_device_handle_priv *handle_priv, uint8_t endpoint_address)
2666{
2667 int i, j;
2668 for (i=0; i<USB_MAXINTERFACES; i++) {
2669 if (handle_priv->interface_handle[i].api_handle == INVALID_HANDLE_VALUE)
2670 continue;
2671 if (handle_priv->interface_handle[i].api_handle == 0)
2672 continue;
2673 if (priv->usb_interface[i].endpoint == NULL)
2674 continue;
2675 for (j=0; j<priv->usb_interface[i].nb_endpoints; j++) {
2676 if (priv->usb_interface[i].endpoint[j] == endpoint_address) {
2677 return i;
2678 }
2679 }
2680 }
2681 return -1;
2682}
2683
2684static int winusb_submit_control_transfer(struct usbi_transfer *itransfer)
2685{
2686 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2687 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2688 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2689 struct windows_device_handle_priv *handle_priv = __device_handle_priv(
2690 transfer->dev_handle);
2691 WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *) transfer->buffer;
2692 ULONG size;
2693 HANDLE winusb_handle;
2694 int current_interface;
2695 struct winfd wfd;
2696
2697 CHECK_WINUSB_AVAILABLE;
2698
2699 transfer_priv->pollable_fd = INVALID_WINFD;
2700 size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
2701
2702 if (size > MAX_CTRL_BUFFER_LENGTH)
2703 return LIBUSB_ERROR_INVALID_PARAM;
2704
2705 current_interface = get_valid_interface(transfer->dev_handle, USB_API_WINUSB);
2706 if (current_interface < 0) {
2707#if defined(AUTO_CLAIM)
2708 if (auto_claim(transfer, &current_interface, USB_API_WINUSB) != LIBUSB_SUCCESS) {
2709 return LIBUSB_ERROR_NOT_FOUND;
2710 }
2711#else
2712 usbi_warn(ctx, "no interface available for control transfer");
2713 return LIBUSB_ERROR_NOT_FOUND;
2714#endif
2715 }
2716
2717 usbi_dbg("will use interface %d", current_interface);
2718 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2719
2720 wfd = usbi_create_fd(winusb_handle, _O_RDONLY);
2721 // Always use the handle returned from usbi_create_fd (wfd.handle)
2722 if (wfd.fd < 0) {
2723 return LIBUSB_ERROR_NO_MEM;
2724 }
2725
2726 if (!WinUsb_ControlTransfer(wfd.handle, *setup, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, size, NULL, wfd.overlapped)) {
2727 if(GetLastError() != ERROR_IO_PENDING) {
2728 usbi_err(ctx, "WinUsb_ControlTransfer failed: %s", windows_error_str(0));
2729 usbi_free_fd(wfd.fd);
2730 return LIBUSB_ERROR_IO;
2731 }
2732 } else {
2733 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2734 wfd.overlapped->InternalHigh = (DWORD)size;
2735 }
2736
2737 // Use priv_transfer to store data needed for async polling
2738 transfer_priv->pollable_fd = wfd;
2739 transfer_priv->interface_number = (uint8_t)current_interface;
2740
2741 return LIBUSB_SUCCESS;
2742}
2743
2744static int winusb_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
2745{
2746 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2747 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
2748 HANDLE winusb_handle;
2749
2750 CHECK_WINUSB_AVAILABLE;
2751
2752 if (altsetting > 255) {
2753 return LIBUSB_ERROR_INVALID_PARAM;
2754 }
2755
2756 winusb_handle = handle_priv->interface_handle[iface].api_handle;
2757 if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
2758 usbi_err(ctx, "interface must be claimed first");
2759 return LIBUSB_ERROR_NOT_FOUND;
2760 }
2761
2762 if (!WinUsb_SetCurrentAlternateSetting(winusb_handle, (UCHAR)altsetting)) {
2763 usbi_err(ctx, "WinUsb_SetCurrentAlternateSetting failed: %s", windows_error_str(0));
2764 return LIBUSB_ERROR_IO;
2765 }
2766
2767 return LIBUSB_SUCCESS;
2768}
2769
2770static int winusb_submit_bulk_transfer(struct usbi_transfer *itransfer)
2771{
2772 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2773 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2774 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2775 struct windows_device_handle_priv *handle_priv = __device_handle_priv(transfer->dev_handle);
2776 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
2777 HANDLE winusb_handle;
2778 bool direction_in, ret;
2779 int current_interface;
2780 struct winfd wfd;
2781
2782 CHECK_WINUSB_AVAILABLE;
2783
2784 transfer_priv->pollable_fd = INVALID_WINFD;
2785
2786 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
2787 if (current_interface < 0) {
2788 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
2789 return LIBUSB_ERROR_NOT_FOUND;
2790 }
2791
2792 usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
2793
2794 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2795 direction_in = transfer->endpoint & LIBUSB_ENDPOINT_IN;
2796
2797 wfd = usbi_create_fd(winusb_handle, direction_in?_O_RDONLY:_O_WRONLY);
2798 // Always use the handle returned from usbi_create_fd (wfd.handle)
2799 if (wfd.fd < 0) {
2800 return LIBUSB_ERROR_NO_MEM;
2801 }
2802
2803 if (direction_in) {
2804 usbi_dbg("reading %d bytes", transfer->length);
2805 ret = WinUsb_ReadPipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
2806 } else {
2807 usbi_dbg("writing %d bytes", transfer->length);
2808 ret = WinUsb_WritePipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
2809 }
2810 if (!ret) {
2811 if(GetLastError() != ERROR_IO_PENDING) {
2812 usbi_err(ctx, "WinUsb_Pipe Transfer failed: %s", windows_error_str(0));
2813 usbi_free_fd(wfd.fd);
2814 return LIBUSB_ERROR_IO;
2815 }
2816 } else {
2817 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2818 wfd.overlapped->InternalHigh = (DWORD)transfer->length;
2819 }
2820
2821 transfer_priv->pollable_fd = wfd;
2822 transfer_priv->interface_number = (uint8_t)current_interface;
2823
2824 return LIBUSB_SUCCESS;
2825}
2826
2827static int winusb_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
2828{
2829 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2830 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
2831 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
2832 HANDLE winusb_handle;
2833 int current_interface;
2834
2835 CHECK_WINUSB_AVAILABLE;
2836
2837 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
2838 if (current_interface < 0) {
2839 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
2840 return LIBUSB_ERROR_NOT_FOUND;
2841 }
2842
2843 usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface);
2844 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2845
2846 if (!WinUsb_ResetPipe(winusb_handle, endpoint)) {
2847 usbi_err(ctx, "WinUsb_ResetPipe failed: %s", windows_error_str(0));
2848 return LIBUSB_ERROR_NO_DEVICE;
2849 }
2850
2851 return LIBUSB_SUCCESS;
2852}
2853
2854/*
2855 * from http://www.winvistatips.com/winusb-bugchecks-t335323.html (confirmed
2856 * through testing as well):
2857 * "You can not call WinUsb_AbortPipe on control pipe. You can possibly cancel
2858 * the control transfer using CancelIo"
2859 */
2860static int winusb_abort_control(struct usbi_transfer *itransfer)
2861{
2862 // Cancelling of the I/O is done in the parent
2863 return LIBUSB_SUCCESS;
2864}
2865
2866static int winusb_abort_transfers(struct usbi_transfer *itransfer)
2867{
2868 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2869 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2870 struct windows_device_handle_priv *handle_priv = __device_handle_priv(transfer->dev_handle);
2871 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2872 HANDLE winusb_handle;
2873 int current_interface;
2874
2875 CHECK_WINUSB_AVAILABLE;
2876
2877 current_interface = transfer_priv->interface_number;
2878 if ((current_interface < 0) || (current_interface >= USB_MAXINTERFACES)) {
2879 usbi_err(ctx, "program assertion failed: invalid interface_number");
2880 return LIBUSB_ERROR_NOT_FOUND;
2881 }
2882 usbi_dbg("will use interface %d", current_interface);
2883
2884 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2885
2886 if (!WinUsb_AbortPipe(winusb_handle, transfer->endpoint)) {
2887 usbi_err(ctx, "WinUsb_AbortPipe failed: %s", windows_error_str(0));
2888 return LIBUSB_ERROR_NO_DEVICE;
2889 }
2890
2891 return LIBUSB_SUCCESS;
2892}
2893
2894/*
2895 * from the "How to Use WinUSB to Communicate with a USB Device" Microsoft white paper
2896 * (http://www.microsoft.com/whdc/connect/usb/winusb_howto.mspx):
2897 * "WinUSB does not support host-initiated reset port and cycle port operations" and
2898 * IOCTL_INTERNAL_USB_CYCLE_PORT is only available in kernel mode and the
2899 * IOCTL_USB_HUB_CYCLE_PORT ioctl was removed from Vista => the best we can do is
2900 * cycle the pipes (and even then, the control pipe can not be reset using WinUSB)
2901 */
2902// TODO (2nd official release): see if we can force eject the device and redetect it (reuse hotplug?)
2903static int winusb_reset_device(struct libusb_device_handle *dev_handle)
2904{
2905 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2906 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
2907 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
2908 struct winfd wfd;
2909 HANDLE winusb_handle;
2910 int i, j;
2911
2912 CHECK_WINUSB_AVAILABLE;
2913
2914 // Reset any available pipe (except control)
2915 for (i=0; i<USB_MAXINTERFACES; i++) {
2916 winusb_handle = handle_priv->interface_handle[i].api_handle;
2917 for (wfd = handle_to_winfd(winusb_handle); wfd.fd > 0;)
2918 {
2919 // Cancel any pollable I/O
2920 usbi_remove_pollfd(ctx, wfd.fd);
2921 usbi_free_fd(wfd.fd);
2922 wfd = handle_to_winfd(winusb_handle);
2923 }
2924
2925 if ( (winusb_handle != 0) && (winusb_handle != INVALID_HANDLE_VALUE)) {
2926 for (j=0; j<priv->usb_interface[i].nb_endpoints; j++) {
2927 usbi_dbg("resetting ep %02X", priv->usb_interface[i].endpoint[j]);
2928 if (!WinUsb_AbortPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) {
2929 usbi_err(ctx, "WinUsb_AbortPipe (pipe address %02X) failed: %s",
2930 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2931 }
2932 // FlushPipe seems to fail on OUT pipes
2933 if ( (priv->usb_interface[i].endpoint[j] & LIBUSB_ENDPOINT_IN)
2934 && (!WinUsb_FlushPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) ) {
2935 usbi_err(ctx, "WinUsb_FlushPipe (pipe address %02X) failed: %s",
2936 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2937 }
2938 if (!WinUsb_ResetPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) {
2939 usbi_err(ctx, "WinUsb_ResetPipe (pipe address %02X) failed: %s",
2940 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2941 }
2942 }
2943 }
2944 }
2945
2946 return LIBUSB_SUCCESS;
2947}
2948
2949static int winusb_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size)
2950{
2951 itransfer->transferred += io_size;
2952 return LIBUSB_TRANSFER_COMPLETED;
2953}
2954
2955/*
2956 * Internal HID Support functions (from libusb-win32)
2957 * Note that functions that complete data transfer synchronously must return
2958 * LIBUSB_COMPLETED instead of LIBUSB_SUCCESS
2959 */
2960static int _hid_get_hid_descriptor(struct hid_device_priv* dev, void *data, size_t *size);
2961static int _hid_get_report_descriptor(struct hid_device_priv* dev, void *data, size_t *size);
2962
2963static int _hid_wcslen(WCHAR *str)
2964{
2965 int i = 0;
2966 while (str[i] && (str[i] != 0x409)) {
2967 i++;
2968 }
2969 return i;
2970}
2971
2972static int _hid_get_device_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
2973{
2974 struct libusb_device_descriptor d;
2975
2976 d.bLength = LIBUSB_DT_DEVICE_SIZE;
2977 d.bDescriptorType = LIBUSB_DT_DEVICE;
2978 d.bcdUSB = 0x0200; /* 2.00 */
2979 d.bDeviceClass = 0;
2980 d.bDeviceSubClass = 0;
2981 d.bDeviceProtocol = 0;
2982 d.bMaxPacketSize0 = 64; /* fix this! */
2983 d.idVendor = (uint16_t)dev->vid;
2984 d.idProduct = (uint16_t)dev->pid;
2985 d.bcdDevice = 0x0100;
2986 d.iManufacturer = dev->string_index[0];
2987 d.iProduct = dev->string_index[1];
2988 d.iSerialNumber = dev->string_index[2];
2989 d.bNumConfigurations = 1;
2990
2991 if (*size > LIBUSB_DT_DEVICE_SIZE)
2992 *size = LIBUSB_DT_DEVICE_SIZE;
2993 memcpy(data, &d, *size);
2994 return LIBUSB_COMPLETED;
2995}
2996
2997static int _hid_get_config_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
2998{
2999 char num_endpoints = 0;
3000 size_t config_total_len = 0;
3001 char tmp[HID_MAX_CONFIG_DESC_SIZE];
3002 struct libusb_config_descriptor *cd;
3003 struct libusb_interface_descriptor *id;
3004 struct libusb_hid_descriptor *hd;
3005 struct libusb_endpoint_descriptor *ed;
3006 size_t tmp_size;
3007
3008 if (dev->input_report_size)
3009 num_endpoints++;
3010 if (dev->output_report_size)
3011 num_endpoints++;
3012
3013 config_total_len = LIBUSB_DT_CONFIG_SIZE + LIBUSB_DT_INTERFACE_SIZE
3014 + LIBUSB_DT_HID_SIZE + num_endpoints * LIBUSB_DT_ENDPOINT_SIZE;
3015
3016
3017 cd = (struct libusb_config_descriptor *)tmp;
3018 id = (struct libusb_interface_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE);
3019 hd = (struct libusb_hid_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE
3020 + LIBUSB_DT_INTERFACE_SIZE);
3021 ed = (struct libusb_endpoint_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE
3022 + LIBUSB_DT_INTERFACE_SIZE
3023 + LIBUSB_DT_HID_SIZE);
3024
3025 cd->bLength = LIBUSB_DT_CONFIG_SIZE;
3026 cd->bDescriptorType = LIBUSB_DT_CONFIG;
3027 cd->wTotalLength = (uint16_t) config_total_len;
3028 cd->bNumInterfaces = 1;
3029 cd->bConfigurationValue = 1;
3030 cd->iConfiguration = 0;
3031 cd->bmAttributes = 1 << 7; /* bus powered */
3032 cd->MaxPower = 50;
3033
3034 id->bLength = LIBUSB_DT_INTERFACE_SIZE;
3035 id->bDescriptorType = LIBUSB_DT_INTERFACE;
3036 id->bInterfaceNumber = 0;
3037 id->bAlternateSetting = 0;
3038 id->bNumEndpoints = num_endpoints;
3039 id->bInterfaceClass = 3;
3040 id->bInterfaceSubClass = 0;
3041 id->bInterfaceProtocol = 0;
3042 id->iInterface = 0;
3043
3044 tmp_size = LIBUSB_DT_HID_SIZE;
3045 _hid_get_hid_descriptor(dev, hd, &tmp_size);
3046
3047 if (dev->input_report_size) {
3048 ed->bLength = LIBUSB_DT_ENDPOINT_SIZE;
3049 ed->bDescriptorType = LIBUSB_DT_ENDPOINT;
3050 ed->bEndpointAddress = HID_IN_EP;
3051 ed->bmAttributes = 3;
3052 ed->wMaxPacketSize = dev->input_report_size - 1;
3053 ed->bInterval = 10;
3054
3055 ed++;
3056 }
3057
3058 if (dev->output_report_size) {
3059 ed->bLength = LIBUSB_DT_ENDPOINT_SIZE;
3060 ed->bDescriptorType = LIBUSB_DT_ENDPOINT;
3061 ed->bEndpointAddress = HID_OUT_EP;
3062 ed->bmAttributes = 3;
3063 ed->wMaxPacketSize = dev->output_report_size - 1;
3064 ed->bInterval = 10;
3065 }
3066
3067 if (*size > config_total_len)
3068 *size = config_total_len;
3069 memcpy(data, tmp, *size);
3070 return LIBUSB_COMPLETED;
3071}
3072
3073static int _hid_get_string_descriptor(struct hid_device_priv* dev, int index,
3074 void *data, size_t *size)
3075{
3076 void *tmp = NULL;
3077 size_t tmp_size = 0;
3078 int i;
3079
3080 /* language ID, EN-US */
3081 char string_langid[] = {
3082 0x09,
3083 0x04
3084 };
3085
3086 if ((*size < 2) || (*size > 255)) {
3087 return LIBUSB_ERROR_OVERFLOW;
3088 }
3089
3090 if (index == 0) {
3091 tmp = string_langid;
3092 tmp_size = sizeof(string_langid)+2;
3093 } else {
3094 for (i=0; i<3; i++) {
3095 if (index == (dev->string_index[i])) {
3096 tmp = dev->string[i];
3097 tmp_size = (_hid_wcslen(dev->string[i])+1) * sizeof(WCHAR);
3098 break;
3099 }
3100 }
3101 if (i == 3) { // not found
3102 return LIBUSB_ERROR_INVALID_PARAM;
3103 }
3104 }
3105
3106 if(!tmp_size) {
3107 return LIBUSB_ERROR_INVALID_PARAM;
3108 }
3109
3110 if (tmp_size < *size) {
3111 *size = tmp_size;
3112 }
3113 // 2 byte header
3114 ((uint8_t*)data)[0] = (uint8_t)*size;
3115 ((uint8_t*)data)[1] = LIBUSB_DT_STRING;
3116 memcpy((uint8_t*)data+2, tmp, *size-2);
3117 return LIBUSB_COMPLETED;
3118}
3119
3120static int _hid_get_hid_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
3121{
3122 struct libusb_hid_descriptor d;
3123 uint8_t tmp[MAX_HID_DESCRIPTOR_SIZE];
3124 size_t report_len = MAX_HID_DESCRIPTOR_SIZE;
3125
3126 _hid_get_report_descriptor(dev, tmp, &report_len);
3127
3128 d.bLength = LIBUSB_DT_HID_SIZE;
3129 d.bDescriptorType = LIBUSB_DT_HID;
3130 d.bcdHID = 0x0110; /* 1.10 */
3131 d.bCountryCode = 0;
3132 d.bNumDescriptors = 1;
3133 d.bClassDescriptorType = LIBUSB_DT_REPORT;
3134 d.wClassDescriptorLength = (uint16_t)report_len;
3135
3136 if (*size > LIBUSB_DT_HID_SIZE)
3137 *size = LIBUSB_DT_HID_SIZE;
3138 memcpy(data, &d, *size);
3139 return LIBUSB_COMPLETED;
3140}
3141
3142static int _hid_get_report_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
3143{
3144 uint8_t d[MAX_HID_DESCRIPTOR_SIZE];
3145 size_t i = 0;
3146
3147 /* usage page (0xFFA0 == vendor defined) */
3148 d[i++] = 0x06; d[i++] = 0xA0; d[i++] = 0xFF;
3149 /* usage (vendor defined) */
3150 d[i++] = 0x09; d[i++] = 0x01;
3151 /* start collection (application) */
3152 d[i++] = 0xA1; d[i++] = 0x01;
3153 /* input report */
3154 if (dev->input_report_size) {
3155 /* usage (vendor defined) */
3156 d[i++] = 0x09; d[i++] = 0x01;
3157 /* logical minimum (0) */
3158 d[i++] = 0x15; d[i++] = 0x00;
3159 /* logical maximum (255) */
3160 d[i++] = 0x25; d[i++] = 0xFF;
3161 /* report size (8 bits) */
3162 d[i++] = 0x75; d[i++] = 0x08;
3163 /* report count */
3164 d[i++] = 0x95; d[i++] = (uint8_t)dev->input_report_size - 1;
3165 /* input (data, variable, absolute) */
3166 d[i++] = 0x81; d[i++] = 0x00;
3167 }
3168 /* output report */
3169 if (dev->output_report_size) {
3170 /* usage (vendor defined) */
3171 d[i++] = 0x09; d[i++] = 0x02;
3172 /* logical minimum (0) */
3173 d[i++] = 0x15; d[i++] = 0x00;
3174 /* logical maximum (255) */
3175 d[i++] = 0x25; d[i++] = 0xFF;
3176 /* report size (8 bits) */
3177 d[i++] = 0x75; d[i++] = 0x08;
3178 /* report count */
3179 d[i++] = 0x95; d[i++] = (uint8_t)dev->output_report_size - 1;
3180 /* output (data, variable, absolute) */
3181 d[i++] = 0x91; d[i++] = 0x00;
3182 }
3183 /* feature report */
3184 if (dev->feature_report_size) {
3185 /* usage (vendor defined) */
3186 d[i++] = 0x09; d[i++] = 0x03;
3187 /* logical minimum (0) */
3188 d[i++] = 0x15; d[i++] = 0x00;
3189 /* logical maximum (255) */
3190 d[i++] = 0x25; d[i++] = 0xFF;
3191 /* report size (8 bits) */
3192 d[i++] = 0x75; d[i++] = 0x08;
3193 /* report count */
3194 d[i++] = 0x95; d[i++] = (uint8_t)dev->feature_report_size - 1;
3195 /* feature (data, variable, absolute) */
3196 d[i++] = 0xb2; d[i++] = 0x02; d[i++] = 0x01;
3197 }
3198
3199 /* end collection */
3200 d[i++] = 0xC0;
3201
3202 if (*size > i)
3203 *size = i;
3204 memcpy(data, d, *size);
3205 return LIBUSB_COMPLETED;
3206}
3207
3208static int _hid_get_descriptor(struct hid_device_priv* dev, HANDLE hid_handle, int recipient,
3209 int type, int index, void *data, size_t *size)
3210{
3211 switch(type) {
3212 case LIBUSB_DT_DEVICE:
3213 usbi_dbg("LIBUSB_DT_DEVICE");
3214 return _hid_get_device_descriptor(dev, data, size);
3215 case LIBUSB_DT_CONFIG:
3216 usbi_dbg("LIBUSB_DT_CONFIG");
3217 if (!index)
3218 return _hid_get_config_descriptor(dev, data, size);
3219 return LIBUSB_ERROR_INVALID_PARAM;
3220 case LIBUSB_DT_STRING:
3221 usbi_dbg("LIBUSB_DT_STRING");
3222 return _hid_get_string_descriptor(dev, index, data, size);
3223 case LIBUSB_DT_HID:
3224 usbi_dbg("LIBUSB_DT_HID");
3225 if (!index)
3226 return _hid_get_hid_descriptor(dev, data, size);
3227 return LIBUSB_ERROR_INVALID_PARAM;
3228 case LIBUSB_DT_REPORT:
3229 usbi_dbg("LIBUSB_DT_REPORT");
3230 if (!index)
3231 return _hid_get_report_descriptor(dev, data, size);
3232 return LIBUSB_ERROR_INVALID_PARAM;
3233 case LIBUSB_DT_PHYSICAL:
3234 usbi_dbg("LIBUSB_DT_PHYSICAL");
3235 if (HidD_GetPhysicalDescriptor(hid_handle, data, (ULONG)*size))
3236 return LIBUSB_COMPLETED;
3237 return LIBUSB_ERROR_OTHER;
3238 }
3239 usbi_dbg("unsupported");
3240 return LIBUSB_ERROR_INVALID_PARAM;
3241}
3242
3243static int _hid_get_report(struct hid_device_priv* dev, HANDLE hid_handle, int id, void *data,
3244 struct windows_transfer_priv *tp, size_t *size, OVERLAPPED* overlapped,
3245 int report_type)
3246{
3247 uint8_t *buf;
3248 DWORD ioctl_code, read_size, expected_size = (DWORD)*size;
3249 int r = LIBUSB_SUCCESS;
3250
3251 if (tp->hid_buffer != NULL) {
3252 usbi_dbg("program assertion failed: hid_buffer is not NULL");
3253 }
3254
3255 if ((*size == 0) || (*size > MAX_HID_REPORT_SIZE)) {
3256 usbi_dbg("invalid size (%d)", *size);
3257 return LIBUSB_ERROR_INVALID_PARAM;
3258 }
3259
3260 switch (report_type) {
3261 case HID_REPORT_TYPE_INPUT:
3262 ioctl_code = IOCTL_HID_GET_INPUT_REPORT;
3263 break;
3264 case HID_REPORT_TYPE_FEATURE:
3265 ioctl_code = IOCTL_HID_GET_FEATURE;
3266 break;
3267 default:
3268 usbi_dbg("unknown HID report type %d", report_type);
3269 return LIBUSB_ERROR_INVALID_PARAM;
3270 }
3271
3272 // When report IDs are not in use, add an extra byte for the report ID
3273 if (id==0) {
3274 expected_size++;
3275 }
3276
3277 // Add a trailing byte to detect overflows
3278 buf = (uint8_t*)calloc(expected_size+1, 1);
3279 if (buf == NULL) {
3280 return LIBUSB_ERROR_NO_MEM;
3281 }
3282 buf[0] = (uint8_t)id; // Must be set always
3283 usbi_dbg("report ID: 0x%02X", buf[0]);
3284
3285 tp->hid_expected_size = expected_size;
3286
3287 if (!DeviceIoControl(hid_handle, ioctl_code, buf, expected_size+1,
3288 buf, expected_size+1, &read_size, overlapped)) {
3289 if (GetLastError() != ERROR_IO_PENDING) {
3290 usbi_dbg("Failed to Read HID Report: %s", windows_error_str(0));
3291 safe_free(buf);
3292 return LIBUSB_ERROR_IO;
3293 }
3294 // Asynchronous wait
3295 tp->hid_buffer = buf;
3296 tp->hid_dest = data; // copy dest, as not necessarily the start of the transfer buffer
3297 return LIBUSB_SUCCESS;
3298 }
3299
3300 // Transfer completed synchronously => copy and discard extra buffer
3301 if (read_size == 0) {
3302 usbi_dbg("program assertion failed - read completed synchronously, but no data was read");
3303 *size = 0;
3304 } else {
3305 if (buf[0] != id) {
3306 usbi_warn(NULL, "mismatched report ID (data is %02X, parameter is %02X)", buf[0], id);
3307 }
3308 if ((size_t)read_size > expected_size) {
3309 r = LIBUSB_ERROR_OVERFLOW;
3310 usbi_dbg("OVERFLOW!");
3311 } else {
3312 r = LIBUSB_COMPLETED;
3313 }
3314
3315 if (id == 0) {
3316 // Discard report ID
3317 *size = MIN((size_t)read_size-1, *size);
3318 memcpy(data, buf+1, *size);
3319 } else {
3320 *size = MIN((size_t)read_size, *size);
3321 memcpy(data, buf, *size);
3322 }
3323 }
3324 safe_free(buf);
3325 return r;
3326}
3327
3328static int _hid_set_report(struct hid_device_priv* dev, HANDLE hid_handle, int id, void *data,
3329 struct windows_transfer_priv *tp, size_t *size, OVERLAPPED* overlapped,
3330 int report_type)
3331{
3332 uint8_t *buf = NULL;
3333 DWORD ioctl_code, write_size= (DWORD)*size;
3334
3335 if (tp->hid_buffer != NULL) {
3336 usbi_dbg("program assertion failed: hid_buffer is not NULL");
3337 }
3338
3339 if ((*size == 0) || (*size > MAX_HID_REPORT_SIZE)) {
3340 usbi_dbg("invalid size (%d)", *size);
3341 return LIBUSB_ERROR_INVALID_PARAM;
3342 }
3343
3344 switch (report_type) {
3345 case HID_REPORT_TYPE_OUTPUT:
3346 ioctl_code = IOCTL_HID_SET_OUTPUT_REPORT;
3347 break;
3348 case HID_REPORT_TYPE_FEATURE:
3349 ioctl_code = IOCTL_HID_SET_FEATURE;
3350 break;
3351 default:
3352 usbi_dbg("unknown HID report type %d", report_type);
3353 return LIBUSB_ERROR_INVALID_PARAM;
3354 }
3355
3356 usbi_dbg("report ID: 0x%02X", id);
3357 // When report IDs are not used (i.e. when id == 0), we must add
3358 // a null report ID. Otherwise, we just use original data buffer
3359 if (id == 0) {
3360 write_size++;
3361 }
3362 buf = malloc(write_size);
3363 if (buf == NULL) {
3364 return LIBUSB_ERROR_NO_MEM;
3365 }
3366 if (id == 0) {
3367 buf[0] = 0;
3368 memcpy(buf + 1, data, *size);
3369 } else {
3370 // This seems like a waste, but if we don't duplicate the
3371 // data, we'll get issues when freeing hid_buffer
3372 memcpy(buf, data, *size);
3373 if (buf[0] != id) {
3374 usbi_warn(NULL, "mismatched report ID (data is %02X, parameter is %02X)", buf[0], id);
3375 }
3376 }
3377
3378 if (!DeviceIoControl(hid_handle, ioctl_code, buf, write_size,
3379 buf, write_size, &write_size, overlapped)) {
3380 if (GetLastError() != ERROR_IO_PENDING) {
3381 usbi_dbg("Failed to Write HID Output Report: %s", windows_error_str(0));
3382 safe_free(buf);
3383 return LIBUSB_ERROR_IO;
3384 }
3385 tp->hid_buffer = buf;
3386 tp->hid_dest = NULL;
3387 return LIBUSB_SUCCESS;
3388 }
3389
3390 // Transfer completed synchronously
3391 if (write_size == 0) {
3392 usbi_dbg("program assertion failed - write completed synchronously, but no data was written");
3393 *size = 0;
3394 } else {
3395 *size = write_size - ((id == 0)?1:0);
3396 }
3397 safe_free(buf);
3398 return LIBUSB_COMPLETED;
3399}
3400
3401static int _hid_class_request(struct hid_device_priv* dev, HANDLE hid_handle, int request_type,
3402 int request, int value, int index, void *data, struct windows_transfer_priv *tp,
3403 size_t *size, OVERLAPPED* overlapped)
3404{
3405 int report_type = (value >> 8) & 0xFF;
3406 int report_id = value & 0xFF;
3407
3408 if ( (LIBUSB_REQ_RECIPIENT(request_type) != LIBUSB_RECIPIENT_INTERFACE)
3409 && (LIBUSB_REQ_RECIPIENT(request_type) != LIBUSB_RECIPIENT_DEVICE) )
3410 return LIBUSB_ERROR_INVALID_PARAM;
3411
3412 if (LIBUSB_REQ_OUT(request_type) && request == HID_REQ_SET_REPORT)
3413 return _hid_set_report(dev, hid_handle, report_id, data, tp, size, overlapped, report_type);
3414
3415 if (LIBUSB_REQ_IN(request_type) && request == HID_REQ_GET_REPORT)
3416 return _hid_get_report(dev, hid_handle, report_id, data, tp, size, overlapped, report_type);
3417
3418 return LIBUSB_ERROR_INVALID_PARAM;
3419}
3420
3421
3422/*
3423 * HID API functions
3424 */
3425static int hid_init(struct libusb_context *ctx)
3426{
3427 DLL_LOAD(hid.dll, HidD_GetAttributes, TRUE);
3428 DLL_LOAD(hid.dll, HidD_GetHidGuid, TRUE);
3429 DLL_LOAD(hid.dll, HidD_GetPreparsedData, TRUE);
3430 DLL_LOAD(hid.dll, HidD_FreePreparsedData, TRUE);
3431 DLL_LOAD(hid.dll, HidD_GetManufacturerString, TRUE);
3432 DLL_LOAD(hid.dll, HidD_GetProductString, TRUE);
3433 DLL_LOAD(hid.dll, HidD_GetSerialNumberString, TRUE);
3434 DLL_LOAD(hid.dll, HidP_GetCaps, TRUE);
3435 DLL_LOAD(hid.dll, HidD_SetNumInputBuffers, TRUE);
3436 DLL_LOAD(hid.dll, HidD_SetFeature, TRUE);
3437 DLL_LOAD(hid.dll, HidD_GetFeature, TRUE);
3438 DLL_LOAD(hid.dll, HidD_GetPhysicalDescriptor, TRUE);
3439 DLL_LOAD(hid.dll, HidD_GetInputReport, FALSE);
3440 DLL_LOAD(hid.dll, HidD_SetOutputReport, FALSE);
3441 DLL_LOAD(hid.dll, HidD_FlushQueue, TRUE);
3442 DLL_LOAD(hid.dll, HidP_GetValueCaps, TRUE);
3443
3444 api_hid_available = true;
3445 return LIBUSB_SUCCESS;
3446}
3447
3448static int hid_exit(void)
3449{
3450 return LIBUSB_SUCCESS;
3451}
3452
3453// NB: open and close must ensure that they only handle interface of
3454// the right API type, as these functions can be called wholesale from
3455// composite_open(), with interfaces belonging to different APIs
3456static int hid_open(struct libusb_device_handle *dev_handle)
3457{
3458 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3459 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
3460 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
3461
3462 HIDD_ATTRIBUTES hid_attributes;
3463 PHIDP_PREPARSED_DATA preparsed_data = NULL;
3464 HIDP_CAPS capabilities;
3465 HIDP_VALUE_CAPS *value_caps;
3466
3467 HANDLE hid_handle = INVALID_HANDLE_VALUE;
3468 int i, j;
3469 // report IDs handling
3470 ULONG size[3];
3471 char* type[3] = {"input", "output", "feature"};
3472 int nb_ids[2]; // zero and nonzero report IDs
3473
3474 CHECK_HID_AVAILABLE;
3475 if (priv->hid == NULL) {
3476 usbi_err(ctx, "program assertion failed - private HID structure is unitialized");
3477 return LIBUSB_ERROR_NOT_FOUND;
3478 }
3479
3480 for (i = 0; i < USB_MAXINTERFACES; i++) {
3481 if ( (priv->usb_interface[i].path != NULL)
3482 && (priv->usb_interface[i].apib->id == USB_API_HID) ) {
3483 hid_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
3484 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
3485 /*
3486 * http://www.lvr.com/hidfaq.htm: Why do I receive "Access denied" when attempting to access my HID?
3487 * "Windows 2000 and later have exclusive read/write access to HIDs that are configured as a system
3488 * keyboards or mice. An application can obtain a handle to a system keyboard or mouse by not
3489 * requesting READ or WRITE access with CreateFile. Applications can then use HidD_SetFeature and
3490 * HidD_GetFeature (if the device supports Feature reports)."
3491 */
3492 if (hid_handle == INVALID_HANDLE_VALUE) {
3493 usbi_warn(ctx, "could not open HID device in R/W mode (keyboard or mouse?) - trying without");
3494 hid_handle = CreateFileA(priv->usb_interface[i].path, 0, FILE_SHARE_WRITE | FILE_SHARE_READ,
3495 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
3496 if (hid_handle == INVALID_HANDLE_VALUE) {
3497 usbi_err(ctx, "could not open device %s (interface %d): %s", priv->path, i, windows_error_str(0));
3498 switch(GetLastError()) {
3499 case ERROR_FILE_NOT_FOUND: // The device was disconnected
3500 return LIBUSB_ERROR_NO_DEVICE;
3501 case ERROR_ACCESS_DENIED:
3502 return LIBUSB_ERROR_ACCESS;
3503 default:
3504 return LIBUSB_ERROR_IO;
3505 }
3506 }
3507 priv->usb_interface[i].restricted_functionality = true;
3508 }
3509 handle_priv->interface_handle[i].api_handle = hid_handle;
3510 }
3511 }
3512
3513 hid_attributes.Size = sizeof(hid_attributes);
3514 do {
3515 if (!HidD_GetAttributes(hid_handle, &hid_attributes)) {
3516 usbi_err(ctx, "could not gain access to HID top collection (HidD_GetAttributes)");
3517 break;
3518 }
3519
3520 priv->hid->vid = hid_attributes.VendorID;
3521 priv->hid->pid = hid_attributes.ProductID;
3522
3523 // Set the maximum available input buffer size
3524 for (i=32; HidD_SetNumInputBuffers(hid_handle, i); i*=2);
3525 usbi_dbg("set maximum input buffer size to %d", i/2);
3526
3527 // Get the maximum input and output report size
3528 if (!HidD_GetPreparsedData(hid_handle, &preparsed_data) || !preparsed_data) {
3529 usbi_err(ctx, "could not read HID preparsed data (HidD_GetPreparsedData)");
3530 break;
3531 }
3532 if (HidP_GetCaps(preparsed_data, &capabilities) != HIDP_STATUS_SUCCESS) {
3533 usbi_err(ctx, "could not parse HID capabilities (HidP_GetCaps)");
3534 break;
3535 }
3536
3537 // Find out if interrupt will need report IDs
3538 size[0] = capabilities.NumberInputValueCaps;
3539 size[1] = capabilities.NumberOutputValueCaps;
3540 size[2] = capabilities.NumberFeatureValueCaps;
3541 for (j=0; j<3; j++) {
3542 usbi_dbg("%d HID %s report value(s) found", size[j], type[j]);
3543 priv->hid->uses_report_ids[j] = false;
3544 if (size[j] > 0) {
3545 value_caps = malloc(size[j] * sizeof(HIDP_VALUE_CAPS));
3546 if ( (value_caps != NULL)
3547 && (HidP_GetValueCaps(j, value_caps, &size[j], preparsed_data) == HIDP_STATUS_SUCCESS)
3548 && (size[j] >= 1) ) {
3549 nb_ids[0] = 0;
3550 nb_ids[1] = 0;
3551 for (i=0; i<(int)size[j]; i++) {
3552 usbi_dbg(" Report ID: 0x%02X", value_caps[i].ReportID);
3553 if (value_caps[i].ReportID != 0) {
3554 nb_ids[1]++;
3555 } else {
3556 nb_ids[0]++;
3557 }
3558 }
3559 if (nb_ids[1] != 0) {
3560 if (nb_ids[0] != 0) {
3561 usbi_warn(ctx, "program assertion failed: zero and nonzero report IDs used for %s",
3562 type[j]);
3563 }
3564 priv->hid->uses_report_ids[j] = true;
3565 }
3566 } else {
3567 usbi_warn(ctx, " could not process %s report IDs", type[j]);
3568 }
3569 safe_free(value_caps);
3570 }
3571 }
3572
3573 // Set the report sizes
3574 priv->hid->input_report_size = capabilities.InputReportByteLength;
3575 priv->hid->output_report_size = capabilities.OutputReportByteLength;
3576 priv->hid->feature_report_size = capabilities.FeatureReportByteLength;
3577
3578 // Fetch string descriptors
3579 priv->hid->string_index[0] = priv->dev_descriptor.iManufacturer;
3580 if (priv->hid->string_index[0] != 0) {
3581 HidD_GetManufacturerString(hid_handle, priv->hid->string[0],
3582 sizeof(priv->hid->string[0]));
3583 } else {
3584 priv->hid->string[0][0] = 0;
3585 }
3586 priv->hid->string_index[1] = priv->dev_descriptor.iProduct;
3587 if (priv->hid->string_index[1] != 0) {
3588 HidD_GetProductString(hid_handle, priv->hid->string[1],
3589 sizeof(priv->hid->string[1]));
3590 } else {
3591 priv->hid->string[1][0] = 0;
3592 }
3593 priv->hid->string_index[2] = priv->dev_descriptor.iSerialNumber;
3594 if (priv->hid->string_index[2] != 0) {
3595 HidD_GetSerialNumberString(hid_handle, priv->hid->string[2],
3596 sizeof(priv->hid->string[2]));
3597 } else {
3598 priv->hid->string[2][0] = 0;
3599 }
3600 } while(0);
3601
3602 if (preparsed_data) {
3603 HidD_FreePreparsedData(preparsed_data);
3604 }
3605
3606 return LIBUSB_SUCCESS;
3607}
3608
3609static void hid_close(struct libusb_device_handle *dev_handle)
3610{
3611 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
3612 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
3613 HANDLE file_handle;
3614 int i;
3615
3616 if (!api_hid_available)
3617 return;
3618
3619 for (i = 0; i < USB_MAXINTERFACES; i++) {
3620 if (priv->usb_interface[i].apib->id == USB_API_HID) {
3621 file_handle = handle_priv->interface_handle[i].api_handle;
3622 if ( (file_handle != 0) && (file_handle != INVALID_HANDLE_VALUE)) {
3623 CloseHandle(file_handle);
3624 }
3625 }
3626 }
3627}
3628
3629static int hid_claim_interface(struct libusb_device_handle *dev_handle, int iface)
3630{
3631 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
3632 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
3633
3634 CHECK_HID_AVAILABLE;
3635
3636 // NB: Disconnection detection is not possible in this function
3637 if (priv->usb_interface[iface].path == NULL) {
3638 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3639 }
3640
3641 // We use dev_handle as a flag for interface claimed
3642 if (handle_priv->interface_handle[iface].dev_handle == INTERFACE_CLAIMED) {
3643 return LIBUSB_ERROR_BUSY; // already claimed
3644 }
3645
3646 handle_priv->interface_handle[iface].dev_handle = INTERFACE_CLAIMED;
3647
3648 usbi_dbg("claimed interface %d", iface);
3649 handle_priv->active_interface = iface;
3650
3651 return LIBUSB_SUCCESS;
3652}
3653
3654static int hid_release_interface(struct libusb_device_handle *dev_handle, int iface)
3655{
3656 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
3657 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
3658
3659 CHECK_HID_AVAILABLE;
3660
3661 if (priv->usb_interface[iface].path == NULL) {
3662 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3663 }
3664
3665 if (handle_priv->interface_handle[iface].dev_handle != INTERFACE_CLAIMED) {
3666 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3667 }
3668
3669 handle_priv->interface_handle[iface].dev_handle = INVALID_HANDLE_VALUE;
3670
3671 return LIBUSB_SUCCESS;
3672}
3673
3674static int hid_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
3675{
3676 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3677
3678 CHECK_HID_AVAILABLE;
3679
3680 if (altsetting > 255) {
3681 return LIBUSB_ERROR_INVALID_PARAM;
3682 }
3683
3684 if (altsetting != 0) {
3685 usbi_err(ctx, "set interface altsetting not supported for altsetting >0");
3686 return LIBUSB_ERROR_NOT_SUPPORTED;
3687 }
3688
3689 return LIBUSB_SUCCESS;
3690}
3691
3692static int hid_submit_control_transfer(struct usbi_transfer *itransfer)
3693{
3694 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3695 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3696 struct windows_device_handle_priv *handle_priv = __device_handle_priv(transfer->dev_handle);
3697 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
3698 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3699 WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *) transfer->buffer;
3700 HANDLE hid_handle;
3701 struct winfd wfd;
3702 int current_interface, config;
3703 size_t size;
3704 int r = LIBUSB_ERROR_INVALID_PARAM;
3705
3706 CHECK_HID_AVAILABLE;
3707
3708 transfer_priv->pollable_fd = INVALID_WINFD;
3709 safe_free(transfer_priv->hid_buffer);
3710 transfer_priv->hid_dest = NULL;
3711 size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
3712
3713 if (size > MAX_CTRL_BUFFER_LENGTH) {
3714 return LIBUSB_ERROR_INVALID_PARAM;
3715 }
3716
3717 current_interface = get_valid_interface(transfer->dev_handle, USB_API_HID);
3718 if (current_interface < 0) {
3719#if defined(AUTO_CLAIM)
3720 if (auto_claim(transfer, &current_interface, USB_API_HID) != LIBUSB_SUCCESS) {
3721 return LIBUSB_ERROR_NOT_FOUND;
3722 }
3723#else
3724 usbi_warn(ctx, "no interface available for control transfer");
3725 return LIBUSB_ERROR_NOT_FOUND;
3726#endif
3727 }
3728
3729 usbi_dbg("will use interface %d", current_interface);
3730 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3731 // Always use the handle returned from usbi_create_fd (wfd.handle)
3732 wfd = usbi_create_fd(hid_handle, _O_RDONLY);
3733 if (wfd.fd < 0) {
3734 return LIBUSB_ERROR_NO_MEM;
3735 }
3736
3737 switch(LIBUSB_REQ_TYPE(setup->request_type)) {
3738 case LIBUSB_REQUEST_TYPE_STANDARD:
3739 switch(setup->request) {
3740 case LIBUSB_REQUEST_GET_DESCRIPTOR:
3741 r = _hid_get_descriptor(priv->hid, wfd.handle, LIBUSB_REQ_RECIPIENT(setup->request_type),
3742 (setup->value >> 8) & 0xFF, setup->value & 0xFF, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, &size);
3743 break;
3744 case LIBUSB_REQUEST_GET_CONFIGURATION:
3745 r = windows_get_configuration(transfer->dev_handle, &config);
3746 if (r == LIBUSB_SUCCESS) {
3747 size = 1;
3748 ((uint8_t*)transfer->buffer)[LIBUSB_CONTROL_SETUP_SIZE] = (uint8_t)config;
3749 r = LIBUSB_COMPLETED;
3750 }
3751 break;
3752 case LIBUSB_REQUEST_SET_CONFIGURATION:
3753 if (setup->value == priv->active_config) {
3754 r = LIBUSB_COMPLETED;
3755 } else {
3756 usbi_warn(ctx, "cannot set configuration other than the default one");
3757 r = LIBUSB_ERROR_INVALID_PARAM;
3758 }
3759 break;
3760 case LIBUSB_REQUEST_GET_INTERFACE:
3761 size = 1;
3762 ((uint8_t*)transfer->buffer)[LIBUSB_CONTROL_SETUP_SIZE] = 0;
3763 r = LIBUSB_COMPLETED;
3764 break;
3765 case LIBUSB_REQUEST_SET_INTERFACE:
3766 r = hid_set_interface_altsetting(transfer->dev_handle, setup->index, setup->value);
3767 if (r == LIBUSB_SUCCESS) {
3768 r = LIBUSB_COMPLETED;
3769 }
3770 break;
3771 default:
3772 usbi_warn(ctx, "unsupported HID control request");
3773 r = LIBUSB_ERROR_INVALID_PARAM;
3774 break;
3775 }
3776 break;
3777 case LIBUSB_REQUEST_TYPE_CLASS:
3778 r =_hid_class_request(priv->hid, wfd.handle, setup->request_type, setup->request, setup->value,
3779 setup->index, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, transfer_priv,
3780 &size, wfd.overlapped);
3781 break;
3782 default:
3783 usbi_warn(ctx, "unsupported HID control request");
3784 r = LIBUSB_ERROR_INVALID_PARAM;
3785 break;
3786 }
3787
3788 if (r == LIBUSB_COMPLETED) {
3789 // Force request to be completed synchronously. Transferred size has been set by previous call
3790 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
3791 // http://msdn.microsoft.com/en-us/library/ms684342%28VS.85%29.aspx
3792 // set InternalHigh to the number of bytes transferred
3793 wfd.overlapped->InternalHigh = (DWORD)size;
3794 r = LIBUSB_SUCCESS;
3795 }
3796
3797 if (r == LIBUSB_SUCCESS) {
3798 // Use priv_transfer to store data needed for async polling
3799 transfer_priv->pollable_fd = wfd;
3800 transfer_priv->interface_number = (uint8_t)current_interface;
3801 } else {
3802 usbi_free_fd(wfd.fd);
3803 }
3804
3805 return r;
3806}
3807
3808static int hid_submit_bulk_transfer(struct usbi_transfer *itransfer) {
3809 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3810 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3811 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3812 struct windows_device_handle_priv *handle_priv = __device_handle_priv(transfer->dev_handle);
3813 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
3814 struct winfd wfd;
3815 HANDLE hid_handle;
3816 bool direction_in, ret;
3817 int current_interface, length;
3818 DWORD size;
3819 int r = LIBUSB_SUCCESS;
3820
3821 CHECK_HID_AVAILABLE;
3822
3823 transfer_priv->pollable_fd = INVALID_WINFD;
3824 transfer_priv->hid_dest = NULL;
3825 safe_free(transfer_priv->hid_buffer);
3826
3827 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
3828 if (current_interface < 0) {
3829 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
3830 return LIBUSB_ERROR_NOT_FOUND;
3831 }
3832
3833 usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
3834
3835 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3836 direction_in = transfer->endpoint & LIBUSB_ENDPOINT_IN;
3837
3838 wfd = usbi_create_fd(hid_handle, direction_in?_O_RDONLY:_O_WRONLY);
3839 // Always use the handle returned from usbi_create_fd (wfd.handle)
3840 if (wfd.fd < 0) {
3841 return LIBUSB_ERROR_NO_MEM;
3842 }
3843
3844 // If report IDs are not in use, an extra prefix byte must be added
3845 if ( ((direction_in) && (!priv->hid->uses_report_ids[0]))
3846 || ((!direction_in) && (!priv->hid->uses_report_ids[1])) ) {
3847 length = transfer->length+1;
3848 } else {
3849 length = transfer->length;
3850 }
3851 // Add a trailing byte to detect overflows on input
3852 transfer_priv->hid_buffer = (uint8_t*)calloc(length+1, 1);
3853 if (transfer_priv->hid_buffer == NULL) {
3854 return LIBUSB_ERROR_NO_MEM;
3855 }
3856 transfer_priv->hid_expected_size = length;
3857
3858 if (direction_in) {
3859 transfer_priv->hid_dest = transfer->buffer;
3860 usbi_dbg("reading %d bytes (report ID: 0x%02X)", length, transfer_priv->hid_buffer[0]);
3861 ret = ReadFile(wfd.handle, transfer_priv->hid_buffer, length+1, &size, wfd.overlapped);
3862 } else {
3863 if (!priv->hid->uses_report_ids[1]) {
3864 memcpy(transfer_priv->hid_buffer+1, transfer->buffer, transfer->length);
3865 } else {
3866 // We could actually do without the calloc and memcpy in this case
3867 memcpy(transfer_priv->hid_buffer, transfer->buffer, transfer->length);
3868 }
3869 usbi_dbg("writing %d bytes (report ID: 0x%02X)", length, transfer_priv->hid_buffer[0]);
3870 ret = WriteFile(wfd.handle, transfer_priv->hid_buffer, length, &size, wfd.overlapped);
3871 }
3872 if (!ret) {
3873 if (GetLastError() != ERROR_IO_PENDING) {
3874 usbi_err(ctx, "HID transfer failed: %s", windows_error_str(0));
3875 usbi_free_fd(wfd.fd);
3876 safe_free(transfer_priv->hid_buffer);
3877 return LIBUSB_ERROR_IO;
3878 }
3879 } else {
3880 // Only write operations that completed synchronously need to free up
3881 // hid_buffer. For reads, copy_transfer_data() handles that process.
3882 if (!direction_in) {
3883 safe_free(transfer_priv->hid_buffer);
3884 }
3885 if (size == 0) {
3886 usbi_err(ctx, "program assertion failed - no data was transferred");
3887 size = 1;
3888 }
3889 if (size > (size_t)length) {
3890 usbi_err(ctx, "OVERFLOW!");
3891 r = LIBUSB_ERROR_OVERFLOW;
3892 }
3893 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
3894 wfd.overlapped->InternalHigh = size;
3895 }
3896
3897 transfer_priv->pollable_fd = wfd;
3898 transfer_priv->interface_number = (uint8_t)current_interface;
3899
3900 return r;
3901}
3902
3903static int hid_abort_transfers(struct usbi_transfer *itransfer)
3904{
3905 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3906 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3907 struct windows_device_handle_priv *handle_priv = __device_handle_priv(transfer->dev_handle);
3908 HANDLE hid_handle;
3909 int current_interface;
3910
3911 CHECK_HID_AVAILABLE;
3912
3913 current_interface = transfer_priv->interface_number;
3914 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3915 CancelIo(hid_handle);
3916
3917 return LIBUSB_SUCCESS;
3918}
3919
3920static int hid_reset_device(struct libusb_device_handle *dev_handle)
3921{
3922 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
3923 HANDLE hid_handle;
3924 int current_interface;
3925
3926 CHECK_HID_AVAILABLE;
3927
3928 // Flushing the queues on all interfaces is the best we can achieve
3929 for (current_interface = 0; current_interface < USB_MAXINTERFACES; current_interface++) {
3930 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3931 if ((hid_handle != 0) && (hid_handle != INVALID_HANDLE_VALUE)) {
3932 HidD_FlushQueue(hid_handle);
3933 }
3934 }
3935 return LIBUSB_SUCCESS;
3936}
3937
3938static int hid_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
3939{
3940 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3941 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
3942 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
3943 HANDLE hid_handle;
3944 int current_interface;
3945
3946 CHECK_HID_AVAILABLE;
3947
3948 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
3949 if (current_interface < 0) {
3950 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
3951 return LIBUSB_ERROR_NOT_FOUND;
3952 }
3953
3954 usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface);
3955 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3956
3957 // No endpoint selection with Microsoft's implementation, so we try to flush the
3958 // whole interface. Should be OK for most case scenarios
3959 if (!HidD_FlushQueue(hid_handle)) {
3960 usbi_err(ctx, "Flushing of HID queue failed: %s", windows_error_str(0));
3961 // Device was probably disconnected
3962 return LIBUSB_ERROR_NO_DEVICE;
3963 }
3964
3965 return LIBUSB_SUCCESS;
3966}
3967
3968// This extra function is only needed for HID
3969static int hid_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size) {
3970 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3971 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3972 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3973 int r = LIBUSB_TRANSFER_COMPLETED;
3974 uint32_t corrected_size = io_size;
3975
3976 if (transfer_priv->hid_buffer != NULL) {
3977 // If we have a valid hid_buffer, it means the transfer was async
3978 if (transfer_priv->hid_dest != NULL) { // Data readout
3979 // First, check for overflow
3980 if (corrected_size > transfer_priv->hid_expected_size) {
3981 usbi_err(ctx, "OVERFLOW!");
3982 corrected_size = (uint32_t)transfer_priv->hid_expected_size;
3983 r = LIBUSB_TRANSFER_OVERFLOW;
3984 }
3985
3986 if (transfer_priv->hid_buffer[0] == 0) {
3987 // Discard the 1 byte report ID prefix
3988 corrected_size--;
3989 memcpy(transfer_priv->hid_dest, transfer_priv->hid_buffer+1, corrected_size);
3990 } else {
3991 memcpy(transfer_priv->hid_dest, transfer_priv->hid_buffer, corrected_size);
3992 }
3993 transfer_priv->hid_dest = NULL;
3994 }
3995 // For write, we just need to free the hid buffer
3996 safe_free(transfer_priv->hid_buffer);
3997 }
3998 itransfer->transferred += corrected_size;
3999 return r;
4000}
4001
4002
4003/*
4004 * Composite API functions
4005 */
4006static int composite_init(struct libusb_context *ctx)
4007{
4008 return LIBUSB_SUCCESS;
4009}
4010
4011static int composite_exit(void)
4012{
4013 return LIBUSB_SUCCESS;
4014}
4015
4016static int composite_open(struct libusb_device_handle *dev_handle)
4017{
4018 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
4019 unsigned api;
4020 int r;
4021 uint8_t flag = 1<<USB_API_WINUSB;
4022
4023 for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
4024 if (priv->composite_api_flags & flag) {
4025 r = usb_api_backend[api].open(dev_handle);
4026 if (r != LIBUSB_SUCCESS) {
4027 return r;
4028 }
4029 }
4030 flag <<= 1;
4031 }
4032 return LIBUSB_SUCCESS;
4033}
4034
4035static void composite_close(struct libusb_device_handle *dev_handle)
4036{
4037 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
4038 unsigned api;
4039 uint8_t flag = 1<<USB_API_WINUSB;
4040
4041 for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
4042 if (priv->composite_api_flags & flag) {
4043 usb_api_backend[api].close(dev_handle);
4044 }
4045 flag <<= 1;
4046 }
4047}
4048
4049static int composite_claim_interface(struct libusb_device_handle *dev_handle, int iface)
4050{
4051 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
4052 return priv->usb_interface[iface].apib->claim_interface(dev_handle, iface);
4053}
4054
4055static int composite_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
4056{
4057 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
4058 return priv->usb_interface[iface].apib->set_interface_altsetting(dev_handle, iface, altsetting);
4059}
4060
4061static int composite_release_interface(struct libusb_device_handle *dev_handle, int iface)
4062{
4063 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
4064 return priv->usb_interface[iface].apib->release_interface(dev_handle, iface);
4065}
4066
4067static int composite_submit_control_transfer(struct usbi_transfer *itransfer)
4068{
4069 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4070 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4071 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
4072 int i, pass;
4073
4074 // Interface shouldn't matter for control, but it does in practice, with Windows'
4075 // restrictions with regards to accessing HID keyboards and mice. Try a 2 pass approach
4076 for (pass = 0; pass < 2; pass++) {
4077 for (i=0; i<USB_MAXINTERFACES; i++) {
4078 if (priv->usb_interface[i].path != NULL) {
4079 if ((pass == 0) && (priv->usb_interface[i].restricted_functionality)) {
4080 usbi_dbg("trying to skip restricted interface #%d (HID keyboard or mouse?)", i);
4081 continue;
4082 }
4083 usbi_dbg("using interface %d", i);
4084 return priv->usb_interface[i].apib->submit_control_transfer(itransfer);
4085 }
4086 }
4087 }
4088
4089 usbi_err(ctx, "no libusb supported interfaces to complete request");
4090 return LIBUSB_ERROR_NOT_FOUND;
4091}
4092
4093static int composite_submit_bulk_transfer(struct usbi_transfer *itransfer) {
4094 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4095 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4096 struct windows_device_handle_priv *handle_priv = __device_handle_priv(transfer->dev_handle);
4097 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
4098 int current_interface;
4099
4100 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
4101 if (current_interface < 0) {
4102 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
4103 return LIBUSB_ERROR_NOT_FOUND;
4104 }
4105
4106 return priv->usb_interface[current_interface].apib->submit_bulk_transfer(itransfer);
4107}
4108
4109static int composite_submit_iso_transfer(struct usbi_transfer *itransfer) {
4110 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4111 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4112 struct windows_device_handle_priv *handle_priv = __device_handle_priv(transfer->dev_handle);
4113 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
4114 int current_interface;
4115
4116 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
4117 if (current_interface < 0) {
4118 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
4119 return LIBUSB_ERROR_NOT_FOUND;
4120 }
4121
4122 return priv->usb_interface[current_interface].apib->submit_iso_transfer(itransfer);
4123}
4124
4125static int composite_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
4126{
4127 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
4128 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
4129 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
4130 int current_interface;
4131
4132 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
4133 if (current_interface < 0) {
4134 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
4135 return LIBUSB_ERROR_NOT_FOUND;
4136 }
4137
4138 return priv->usb_interface[current_interface].apib->clear_halt(dev_handle, endpoint);
4139}
4140
4141static int composite_abort_control(struct usbi_transfer *itransfer)
4142{
4143 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4144 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4145 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
4146
4147 return priv->usb_interface[transfer_priv->interface_number].apib->abort_control(itransfer);
4148}
4149
4150static int composite_abort_transfers(struct usbi_transfer *itransfer)
4151{
4152 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4153 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4154 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
4155
4156 return priv->usb_interface[transfer_priv->interface_number].apib->abort_transfers(itransfer);
4157}
4158
4159static int composite_reset_device(struct libusb_device_handle *dev_handle)
4160{
4161 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
4162 unsigned api;
4163 int r;
4164 uint8_t flag = 1<<USB_API_WINUSB;
4165
4166 for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
4167 if (priv->composite_api_flags & flag) {
4168 r = usb_api_backend[api].reset_device(dev_handle);
4169 if (r != LIBUSB_SUCCESS) {
4170 return r;
4171 }
4172 }
4173 flag <<= 1;
4174 }
4175 return LIBUSB_SUCCESS;
4176}
4177
4178static int composite_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size)
4179{
4180 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4181 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4182 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
4183
4184 return priv->usb_interface[transfer_priv->interface_number].apib->copy_transfer_data(itransfer, io_size);
4185}
diff --git a/include/libusb-1.0/os/windows_usb.h b/include/libusb-1.0/os/windows_usb.h
deleted file mode 100644
index dc90a64..0000000
--- a/include/libusb-1.0/os/windows_usb.h
+++ /dev/null
@@ -1,784 +0,0 @@
1/*
2 * Windows backend for libusb 1.0
3 * Copyright (C) 2009-2010 Pete Batard <pbatard@gmail.com>
4 * With contributions from Michael Plante, Orin Eman et al.
5 * Parts of this code adapted from libusb-win32-v1 by Stephan Meyer
6 * Major code testing contribution by Xiaofan Chen
7 *
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23#pragma once
24
25#if defined(_MSC_VER)
26// disable /W4 MSVC warnings that are benign
27#pragma warning(disable:4127) // conditional expression is constant
28#pragma warning(disable:4100) // unreferenced formal parameter
29#pragma warning(disable:4214) // bit field types other than int
30#pragma warning(disable:4201) // nameless struct/union
31#endif
32
33// Windows API default is uppercase - ugh!
34#if !defined(bool)
35#define bool BOOL
36#endif
37#if !defined(true)
38#define true TRUE
39#endif
40#if !defined(false)
41#define false FALSE
42#endif
43
44#if !defined(libusb_bus_t)
45#define libusb_bus_t uint8_t
46#define LIBUSB_BUS_MAX UINT8_MAX
47#endif
48#if !defined(libusb_devaddr_t)
49#define libusb_devaddr_t uint8_t
50#define LIBUSB_DEVADDR_MAX UINT8_MAX
51#endif
52
53// Missing from MSVC6 setupapi.h
54#if !defined(SPDRP_ADDRESS)
55#define SPDRP_ADDRESS 28
56#endif
57#if !defined(SPDRP_INSTALL_STATE)
58#define SPDRP_INSTALL_STATE 34
59#endif
60
61#if defined(__CYGWIN__ )
62// cygwin produces a warning unless these prototypes are defined
63extern int _snprintf(char *buffer, size_t count, const char *format, ...);
64extern char *_strdup(const char *strSource);
65// _beginthreadex is MSVCRT => unavailable for cygwin. Fallback to using CreateThread
66#define _beginthreadex(a, b, c, d, e, f) CreateThread(a, b, (LPTHREAD_START_ROUTINE)c, d, e, f)
67#endif
68#define safe_free(p) do {if (p != NULL) {free((void*)p); p = NULL;}} while(0)
69#define safe_closehandle(h) do {if (h != INVALID_HANDLE_VALUE) {CloseHandle(h); h = INVALID_HANDLE_VALUE;}} while(0)
70#define safe_min(a, b) min((size_t)(a), (size_t)(b))
71#define safe_strcp(dst, dst_max, src, count) do {memcpy(dst, src, safe_min(count, dst_max)); \
72 ((char*)dst)[safe_min(count, dst_max)-1] = 0;} while(0)
73#define safe_strcpy(dst, dst_max, src) safe_strcp(dst, dst_max, src, safe_strlen(src)+1)
74#define safe_strncat(dst, dst_max, src, count) strncat(dst, src, safe_min(count, dst_max - safe_strlen(dst) - 1))
75#define safe_strcat(dst, dst_max, src) safe_strncat(dst, dst_max, src, safe_strlen(src)+1)
76#define safe_strcmp(str1, str2) strcmp(((str1==NULL)?"<NULL>":str1), ((str2==NULL)?"<NULL>":str2))
77#define safe_strncmp(str1, str2, count) strncmp(((str1==NULL)?"<NULL>":str1), ((str2==NULL)?"<NULL>":str2), count)
78#define safe_strlen(str) ((str==NULL)?0:strlen(str))
79#define safe_sprintf _snprintf
80#define safe_unref_device(dev) do {if (dev != NULL) {libusb_unref_device(dev); dev = NULL;}} while(0)
81#define wchar_to_utf8_ms(wstr, str, strlen) WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, strlen, NULL, NULL)
82inline void upperize(char* str) {
83 size_t i;
84 if (str == NULL) return;
85 for (i=0; i<safe_strlen(str); i++)
86 str[i] = (char)toupper((int)str[i]);
87}
88
89#define MAX_CTRL_BUFFER_LENGTH 4096
90#define MAX_USB_DEVICES 256
91#define MAX_USB_STRING_LENGTH 128
92#define MAX_HID_REPORT_SIZE 1024
93#define MAX_HID_DESCRIPTOR_SIZE 256
94#define MAX_GUID_STRING_LENGTH 40
95#define MAX_PATH_LENGTH 128
96#define MAX_KEY_LENGTH 256
97#define MAX_TIMER_SEMAPHORES 128
98#define TIMER_REQUEST_RETRY_MS 100
99#define ERR_BUFFER_SIZE 256
100#define LIST_SEPARATOR ';'
101
102// Handle code for HID interface that have been claimed ("dibs")
103#define INTERFACE_CLAIMED ((HANDLE)(intptr_t)0xD1B5)
104// Additional return code for HID operations that completed synchronously
105#define LIBUSB_COMPLETED (LIBUSB_SUCCESS + 1)
106
107// http://msdn.microsoft.com/en-us/library/bb663109.aspx
108// http://msdn.microsoft.com/en-us/library/bb663093.aspx
109#if !defined(GUID_DEVINTERFACE_USB_HOST_CONTROLLER)
110const GUID GUID_DEVINTERFACE_USB_HOST_CONTROLLER = { 0x3ABF6F2D, 0x71C4, 0x462A, {0x8A, 0x92, 0x1E, 0x68, 0x61, 0xE6, 0xAF, 0x27} };
111#endif
112#if !defined(GUID_DEVINTERFACE_USB_DEVICE)
113const GUID GUID_DEVINTERFACE_USB_DEVICE = { 0xA5DCBF10, 0x6530, 0x11D2, {0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED} };
114#endif
115
116
117/*
118 * Multiple USB API backend support
119 */
120#define USB_API_UNSUPPORTED 0
121#define USB_API_COMPOSITE 1
122#define USB_API_WINUSB 2
123#define USB_API_HID 3
124#define USB_API_MAX 4
125
126const GUID CLASS_GUID_UNSUPPORTED = { 0x00000000, 0x0000, 0x0000, {0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x57, 0xDA} };
127const GUID CLASS_GUID_HID = { 0x745A17A0, 0x74D3, 0x11D0, {0xB6, 0xFE, 0x00, 0xA0, 0xC9, 0x0F, 0x57, 0xDA} };
128const GUID CLASS_GUID_LIBUSB_WINUSB = { 0x78A1C341, 0x4539, 0x11D3, {0xB8, 0x8D, 0x00, 0xC0, 0x4F, 0xAD, 0x51, 0x71} };
129const GUID CLASS_GUID_COMPOSITE = { 0x36FC9E60, 0xC465, 0x11cF, {0x80, 0x56, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00} };
130
131struct windows_usb_api_backend {
132 const uint8_t id;
133 const char* designation;
134 const GUID *class_guid; // The Class GUID (for fallback in case the driver name cannot be read)
135 const char **driver_name_list; // Driver name, without .sys, e.g. "usbccgp"
136 const uint8_t nb_driver_names;
137 int (*init)(struct libusb_context *ctx);
138 int (*exit)(void);
139 int (*open)(struct libusb_device_handle *dev_handle);
140 void (*close)(struct libusb_device_handle *dev_handle);
141 int (*claim_interface)(struct libusb_device_handle *dev_handle, int iface);
142 int (*set_interface_altsetting)(struct libusb_device_handle *dev_handle, int iface, int altsetting);
143 int (*release_interface)(struct libusb_device_handle *dev_handle, int iface);
144 int (*clear_halt)(struct libusb_device_handle *dev_handle, unsigned char endpoint);
145 int (*reset_device)(struct libusb_device_handle *dev_handle);
146 int (*submit_bulk_transfer)(struct usbi_transfer *itransfer);
147 int (*submit_iso_transfer)(struct usbi_transfer *itransfer);
148 int (*submit_control_transfer)(struct usbi_transfer *itransfer);
149 int (*abort_control)(struct usbi_transfer *itransfer);
150 int (*abort_transfers)(struct usbi_transfer *itransfer);
151 int (*copy_transfer_data)(struct usbi_transfer *itransfer, uint32_t io_size);
152};
153
154extern const struct windows_usb_api_backend usb_api_backend[USB_API_MAX];
155
156#define PRINT_UNSUPPORTED_API(fname) \
157 usbi_dbg("unsupported API call for '" \
158 #fname "' (unrecognized device driver)"); \
159 return LIBUSB_ERROR_NOT_SUPPORTED;
160
161/*
162 * private structures definition
163 * with inline pseudo constructors/destructors
164 */
165
166// HCDs
167struct windows_hcd_priv {
168 char *path;
169 struct windows_hcd_priv *next;
170};
171
172static inline void windows_hcd_priv_init(struct windows_hcd_priv* p) {
173 p->path = NULL;
174 p->next = NULL;
175}
176
177static inline void windows_hcd_priv_release(struct windows_hcd_priv* p) {
178 safe_free(p->path);
179}
180
181// TODO (v2+): move hid desc to libusb.h?
182struct libusb_hid_descriptor {
183 uint8_t bLength;
184 uint8_t bDescriptorType;
185 uint16_t bcdHID;
186 uint8_t bCountryCode;
187 uint8_t bNumDescriptors;
188 uint8_t bClassDescriptorType;
189 uint16_t wClassDescriptorLength;
190};
191#define LIBUSB_DT_HID_SIZE 9
192#define HID_MAX_CONFIG_DESC_SIZE (LIBUSB_DT_CONFIG_SIZE + LIBUSB_DT_INTERFACE_SIZE \
193 + LIBUSB_DT_HID_SIZE + 2 * LIBUSB_DT_ENDPOINT_SIZE)
194#define HID_MAX_REPORT_SIZE 1024
195#define HID_IN_EP 0x81
196#define HID_OUT_EP 0x02
197#define LIBUSB_REQ_RECIPIENT(request_type) ((request_type) & 0x1F)
198#define LIBUSB_REQ_TYPE(request_type) ((request_type) & (0x03 << 5))
199#define LIBUSB_REQ_IN(request_type) ((request_type) & LIBUSB_ENDPOINT_IN)
200#define LIBUSB_REQ_OUT(request_type) (!LIBUSB_REQ_IN(request_type))
201
202// The following are used for HID reports IOCTLs
203#define HID_CTL_CODE(id) \
204 CTL_CODE (FILE_DEVICE_KEYBOARD, (id), METHOD_NEITHER, FILE_ANY_ACCESS)
205#define HID_BUFFER_CTL_CODE(id) \
206 CTL_CODE (FILE_DEVICE_KEYBOARD, (id), METHOD_BUFFERED, FILE_ANY_ACCESS)
207#define HID_IN_CTL_CODE(id) \
208 CTL_CODE (FILE_DEVICE_KEYBOARD, (id), METHOD_IN_DIRECT, FILE_ANY_ACCESS)
209#define HID_OUT_CTL_CODE(id) \
210 CTL_CODE (FILE_DEVICE_KEYBOARD, (id), METHOD_OUT_DIRECT, FILE_ANY_ACCESS)
211
212#define IOCTL_HID_GET_FEATURE HID_OUT_CTL_CODE(100)
213#define IOCTL_HID_GET_INPUT_REPORT HID_OUT_CTL_CODE(104)
214#define IOCTL_HID_SET_FEATURE HID_IN_CTL_CODE(100)
215#define IOCTL_HID_SET_OUTPUT_REPORT HID_IN_CTL_CODE(101)
216
217enum libusb_hid_request_type {
218 HID_REQ_GET_REPORT = 0x01,
219 HID_REQ_GET_IDLE = 0x02,
220 HID_REQ_GET_PROTOCOL = 0x03,
221 HID_REQ_SET_REPORT = 0x09,
222 HID_REQ_SET_IDLE = 0x0A,
223 HID_REQ_SET_PROTOCOL = 0x0B
224};
225
226enum libusb_hid_report_type {
227 HID_REPORT_TYPE_INPUT = 0x01,
228 HID_REPORT_TYPE_OUTPUT = 0x02,
229 HID_REPORT_TYPE_FEATURE = 0x03
230};
231
232struct hid_device_priv {
233 uint16_t vid;
234 uint16_t pid;
235 uint8_t config;
236 bool uses_report_ids[3]; // input, ouptput, feature
237 uint16_t input_report_size;
238 uint16_t output_report_size;
239 uint16_t feature_report_size;
240 WCHAR string[3][MAX_USB_STRING_LENGTH];
241 uint8_t string_index[3]; // man, prod, ser
242};
243
244typedef struct libusb_device_descriptor USB_DEVICE_DESCRIPTOR, *PUSB_DEVICE_DESCRIPTOR;
245struct windows_device_priv {
246 struct libusb_device *parent_dev; // access to parent is required for usermode ops
247 ULONG connection_index; // also required for some usermode ops
248 char *path; // path used by Windows to reference the USB node
249 struct windows_usb_api_backend const *apib;
250 struct {
251 char *path; // each interface needs a Windows device interface path,
252 struct windows_usb_api_backend const *apib; // an API backend (multiple drivers support),
253 int8_t nb_endpoints; // and a set of endpoint addresses (USB_MAXENDPOINTS)
254 uint8_t *endpoint;
255 bool restricted_functionality; // indicates if the interface functionality is restricted
256 // by Windows (eg. HID keyboards or mice cannot do R/W)
257 } usb_interface[USB_MAXINTERFACES];
258 uint8_t composite_api_flags; // HID and composite devices require additional data
259 struct hid_device_priv *hid;
260 uint8_t active_config;
261 USB_DEVICE_DESCRIPTOR dev_descriptor;
262 unsigned char **config_descriptor; // list of pointers to the cached config descriptors
263};
264
265static inline void windows_device_priv_init(struct windows_device_priv* p) {
266 int i;
267 p->parent_dev = NULL;
268 p->connection_index = 0;
269 p->path = NULL;
270 p->apib = &usb_api_backend[USB_API_UNSUPPORTED];
271 p->composite_api_flags = 0;
272 p->hid = NULL;
273 p->active_config = 0;
274 p->config_descriptor = NULL;
275 memset(&(p->dev_descriptor), 0, sizeof(USB_DEVICE_DESCRIPTOR));
276 for (i=0; i<USB_MAXINTERFACES; i++) {
277 p->usb_interface[i].path = NULL;
278 p->usb_interface[i].apib = &usb_api_backend[USB_API_UNSUPPORTED];
279 p->usb_interface[i].nb_endpoints = 0;
280 p->usb_interface[i].endpoint = NULL;
281 p->usb_interface[i].restricted_functionality = false;
282 }
283}
284
285static inline void windows_device_priv_release(struct windows_device_priv* p, int num_configurations) {
286 int i;
287 safe_free(p->path);
288 if ((num_configurations > 0) && (p->config_descriptor != NULL)) {
289 for (i=0; i < num_configurations; i++)
290 safe_free(p->config_descriptor[i]);
291 }
292 safe_free(p->config_descriptor);
293 safe_free(p->hid);
294 for (i=0; i<USB_MAXINTERFACES; i++) {
295 safe_free(p->usb_interface[i].path);
296 safe_free(p->usb_interface[i].endpoint);
297 }
298}
299
300static inline struct windows_device_priv *__device_priv(struct libusb_device *dev) {
301 return (struct windows_device_priv *)dev->os_priv;
302}
303
304struct interface_handle_t {
305 HANDLE dev_handle; // WinUSB needs an extra handle for the file
306 HANDLE api_handle; // used by the API to communicate with the device
307};
308
309struct windows_device_handle_priv {
310 int active_interface;
311 struct interface_handle_t interface_handle[USB_MAXINTERFACES];
312#if defined(AUTO_CLAIM)
313 int autoclaim_count[USB_MAXINTERFACES]; // For auto-release
314#endif
315};
316
317static inline struct windows_device_handle_priv *__device_handle_priv(
318 struct libusb_device_handle *handle)
319{
320 return (struct windows_device_handle_priv *) handle->os_priv;
321}
322
323// used for async polling functions
324struct windows_transfer_priv {
325 struct winfd pollable_fd;
326 uint8_t interface_number;
327 uint8_t *hid_buffer; // 1 byte extended data buffer, required for HID
328 uint8_t *hid_dest; // transfer buffer destination, required for HID
329 size_t hid_expected_size;
330};
331
332// used to match a device driver (including filter drivers) against a supported API
333struct driver_lookup {
334 char list[MAX_KEY_LENGTH+1];// REG_MULTI_SZ list of services (driver) names
335 const DWORD reg_prop; // SPDRP registry key to use to retreive list
336 const char* designation; // internal designation (for debug output)
337};
338
339/*
340 * API macros - from libusb-win32 1.x
341 */
342#define DLL_DECLARE(api, ret, name, args) \
343 typedef ret (api * __dll_##name##_t)args; __dll_##name##_t name = NULL
344
345#define DLL_LOAD(dll, name, ret_on_failure) \
346 do { \
347 HMODULE h = GetModuleHandle(#dll); \
348 if (!h) \
349 h = LoadLibrary(#dll); \
350 if (!h) { \
351 if (ret_on_failure) { return LIBUSB_ERROR_NOT_FOUND; }\
352 else { break; } \
353 } \
354 name = (__dll_##name##_t)GetProcAddress(h, #name); \
355 if (name) break; \
356 name = (__dll_##name##_t)GetProcAddress(h, #name "A"); \
357 if (name) break; \
358 name = (__dll_##name##_t)GetProcAddress(h, #name "W"); \
359 if (name) break; \
360 if(ret_on_failure) \
361 return LIBUSB_ERROR_NOT_FOUND; \
362 } while(0)
363
364
365/*
366 * Windows DDK API definitions. Most of it copied from MinGW's includes
367 */
368typedef DWORD DEVNODE, DEVINST;
369typedef DEVNODE *PDEVNODE, *PDEVINST;
370typedef DWORD RETURN_TYPE;
371typedef RETURN_TYPE CONFIGRET;
372
373#define CR_SUCCESS 0x00000000
374#define CR_NO_SUCH_DEVNODE 0x0000000D
375
376#define USB_DEVICE_DESCRIPTOR_TYPE LIBUSB_DT_DEVICE
377#define USB_CONFIGURATION_DESCRIPTOR_TYPE LIBUSB_DT_CONFIG
378#define USB_STRING_DESCRIPTOR_TYPE LIBUSB_DT_STRING
379#define USB_INTERFACE_DESCRIPTOR_TYPE LIBUSB_DT_INTERFACE
380#define USB_ENDPOINT_DESCRIPTOR_TYPE LIBUSB_DT_ENDPOINT
381
382#define USB_REQUEST_GET_STATUS LIBUSB_REQUEST_GET_STATUS
383#define USB_REQUEST_CLEAR_FEATURE LIBUSB_REQUEST_CLEAR_FEATURE
384#define USB_REQUEST_SET_FEATURE LIBUSB_REQUEST_SET_FEATURE
385#define USB_REQUEST_SET_ADDRESS LIBUSB_REQUEST_SET_ADDRESS
386#define USB_REQUEST_GET_DESCRIPTOR LIBUSB_REQUEST_GET_DESCRIPTOR
387#define USB_REQUEST_SET_DESCRIPTOR LIBUSB_REQUEST_SET_DESCRIPTOR
388#define USB_REQUEST_GET_CONFIGURATION LIBUSB_REQUEST_GET_CONFIGURATION
389#define USB_REQUEST_SET_CONFIGURATION LIBUSB_REQUEST_SET_CONFIGURATION
390#define USB_REQUEST_GET_INTERFACE LIBUSB_REQUEST_GET_INTERFACE
391#define USB_REQUEST_SET_INTERFACE LIBUSB_REQUEST_SET_INTERFACE
392#define USB_REQUEST_SYNC_FRAME LIBUSB_REQUEST_SYNCH_FRAME
393
394#define HCD_GET_ROOT_HUB_NAME 258
395#define USB_GET_NODE_INFORMATION 258
396#define USB_GET_NODE_CONNECTION_INFORMATION 259
397#define USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION 260
398#define USB_GET_NODE_CONNECTION_NAME 261
399#define USB_GET_HUB_CAPABILITIES 271
400#if !defined(USB_GET_HUB_CAPABILITIES_EX)
401#define USB_GET_HUB_CAPABILITIES_EX 276
402#endif
403
404#ifndef METHOD_BUFFERED
405#define METHOD_BUFFERED 0
406#endif
407#ifndef FILE_ANY_ACCESS
408#define FILE_ANY_ACCESS 0x00000000
409#endif
410#ifndef FILE_DEVICE_UNKNOWN
411#define FILE_DEVICE_UNKNOWN 0x00000022
412#endif
413#ifndef FILE_DEVICE_USB
414#define FILE_DEVICE_USB FILE_DEVICE_UNKNOWN
415#endif
416
417#ifndef CTL_CODE
418#define CTL_CODE(DeviceType, Function, Method, Access)( \
419 ((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method))
420#endif
421
422typedef enum _USB_CONNECTION_STATUS {
423 NoDeviceConnected,
424 DeviceConnected,
425 DeviceFailedEnumeration,
426 DeviceGeneralFailure,
427 DeviceCausedOvercurrent,
428 DeviceNotEnoughPower,
429 DeviceNotEnoughBandwidth,
430 DeviceHubNestedTooDeeply,
431 DeviceInLegacyHub
432} USB_CONNECTION_STATUS, *PUSB_CONNECTION_STATUS;
433
434typedef enum _USB_HUB_NODE {
435 UsbHub,
436 UsbMIParent
437} USB_HUB_NODE;
438
439/* Cfgmgr32.dll interface */
440DLL_DECLARE(WINAPI, CONFIGRET, CM_Get_Parent, (PDEVINST, DEVINST, ULONG));
441DLL_DECLARE(WINAPI, CONFIGRET, CM_Get_Child, (PDEVINST, DEVINST, ULONG));
442DLL_DECLARE(WINAPI, CONFIGRET, CM_Get_Sibling, (PDEVINST, DEVINST, ULONG));
443DLL_DECLARE(WINAPI, CONFIGRET, CM_Get_Device_IDA, (DEVINST, PCHAR, ULONG, ULONG));
444DLL_DECLARE(WINAPI, CONFIGRET, CM_Get_Device_IDW, (DEVINST, PWCHAR, ULONG, ULONG));
445
446#ifdef UNICODE
447#define CM_Get_Device_ID CM_Get_Device_IDW
448#else
449#define CM_Get_Device_ID CM_Get_Device_IDA
450#endif /* UNICODE */
451
452#define IOCTL_USB_GET_HUB_CAPABILITIES_EX \
453 CTL_CODE( FILE_DEVICE_USB, USB_GET_HUB_CAPABILITIES_EX, METHOD_BUFFERED, FILE_ANY_ACCESS)
454
455#define IOCTL_USB_GET_HUB_CAPABILITIES \
456 CTL_CODE(FILE_DEVICE_USB, USB_GET_HUB_CAPABILITIES, METHOD_BUFFERED, FILE_ANY_ACCESS)
457
458#define IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION \
459 CTL_CODE(FILE_DEVICE_USB, USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, METHOD_BUFFERED, FILE_ANY_ACCESS)
460
461#define IOCTL_USB_GET_ROOT_HUB_NAME \
462 CTL_CODE(FILE_DEVICE_USB, HCD_GET_ROOT_HUB_NAME, METHOD_BUFFERED, FILE_ANY_ACCESS)
463
464#define IOCTL_USB_GET_NODE_INFORMATION \
465 CTL_CODE(FILE_DEVICE_USB, USB_GET_NODE_INFORMATION, METHOD_BUFFERED, FILE_ANY_ACCESS)
466
467#define IOCTL_USB_GET_NODE_CONNECTION_INFORMATION \
468 CTL_CODE(FILE_DEVICE_USB, USB_GET_NODE_CONNECTION_INFORMATION, METHOD_BUFFERED, FILE_ANY_ACCESS)
469
470#define IOCTL_USB_GET_NODE_CONNECTION_ATTRIBUTES \
471 CTL_CODE(FILE_DEVICE_USB, USB_GET_NODE_CONNECTION_ATTRIBUTES, METHOD_BUFFERED, FILE_ANY_ACCESS)
472
473#define IOCTL_USB_GET_NODE_CONNECTION_NAME \
474 CTL_CODE(FILE_DEVICE_USB, USB_GET_NODE_CONNECTION_NAME, METHOD_BUFFERED, FILE_ANY_ACCESS)
475
476// Most of the structures below need to be packed
477#pragma pack(push, 1)
478
479typedef struct _USB_INTERFACE_DESCRIPTOR {
480 UCHAR bLength;
481 UCHAR bDescriptorType;
482 UCHAR bInterfaceNumber;
483 UCHAR bAlternateSetting;
484 UCHAR bNumEndpoints;
485 UCHAR bInterfaceClass;
486 UCHAR bInterfaceSubClass;
487 UCHAR bInterfaceProtocol;
488 UCHAR iInterface;
489} USB_INTERFACE_DESCRIPTOR, *PUSB_INTERFACE_DESCRIPTOR;
490
491typedef struct _USB_CONFIGURATION_DESCRIPTOR {
492 UCHAR bLength;
493 UCHAR bDescriptorType;
494 USHORT wTotalLength;
495 UCHAR bNumInterfaces;
496 UCHAR bConfigurationValue;
497 UCHAR iConfiguration;
498 UCHAR bmAttributes;
499 UCHAR MaxPower;
500} USB_CONFIGURATION_DESCRIPTOR, *PUSB_CONFIGURATION_DESCRIPTOR;
501
502typedef struct _USB_CONFIGURATION_DESCRIPTOR_SHORT {
503 struct {
504 ULONG ConnectionIndex;
505 struct {
506 UCHAR bmRequest;
507 UCHAR bRequest;
508 USHORT wValue;
509 USHORT wIndex;
510 USHORT wLength;
511 } SetupPacket;
512 } req;
513 USB_CONFIGURATION_DESCRIPTOR data;
514} USB_CONFIGURATION_DESCRIPTOR_SHORT;
515
516typedef struct _USB_ENDPOINT_DESCRIPTOR {
517 UCHAR bLength;
518 UCHAR bDescriptorType;
519 UCHAR bEndpointAddress;
520 UCHAR bmAttributes;
521 USHORT wMaxPacketSize;
522 UCHAR bInterval;
523} USB_ENDPOINT_DESCRIPTOR, *PUSB_ENDPOINT_DESCRIPTOR;
524
525typedef struct _USB_DESCRIPTOR_REQUEST {
526 ULONG ConnectionIndex;
527 struct {
528 UCHAR bmRequest;
529 UCHAR bRequest;
530 USHORT wValue;
531 USHORT wIndex;
532 USHORT wLength;
533 } SetupPacket;
534// UCHAR Data[0];
535} USB_DESCRIPTOR_REQUEST, *PUSB_DESCRIPTOR_REQUEST;
536
537typedef struct _USB_HUB_DESCRIPTOR {
538 UCHAR bDescriptorLength;
539 UCHAR bDescriptorType;
540 UCHAR bNumberOfPorts;
541 USHORT wHubCharacteristics;
542 UCHAR bPowerOnToPowerGood;
543 UCHAR bHubControlCurrent;
544 UCHAR bRemoveAndPowerMask[64];
545} USB_HUB_DESCRIPTOR, *PUSB_HUB_DESCRIPTOR;
546
547typedef struct _USB_ROOT_HUB_NAME {
548 ULONG ActualLength;
549 WCHAR RootHubName[1];
550} USB_ROOT_HUB_NAME, *PUSB_ROOT_HUB_NAME;
551
552typedef struct _USB_ROOT_HUB_NAME_FIXED {
553 ULONG ActualLength;
554 WCHAR RootHubName[MAX_PATH_LENGTH];
555} USB_ROOT_HUB_NAME_FIXED;
556
557typedef struct _USB_NODE_CONNECTION_NAME {
558 ULONG ConnectionIndex;
559 ULONG ActualLength;
560 WCHAR NodeName[1];
561} USB_NODE_CONNECTION_NAME, *PUSB_NODE_CONNECTION_NAME;
562
563typedef struct _USB_NODE_CONNECTION_NAME_FIXED {
564 ULONG ConnectionIndex;
565 ULONG ActualLength;
566 WCHAR NodeName[MAX_PATH_LENGTH];
567} USB_NODE_CONNECTION_NAME_FIXED;
568
569typedef struct _USB_HUB_NAME_FIXED {
570 union {
571 USB_ROOT_HUB_NAME_FIXED root;
572 USB_NODE_CONNECTION_NAME_FIXED node;
573 } u;
574} USB_HUB_NAME_FIXED;
575
576
577typedef struct _USB_HUB_INFORMATION {
578 USB_HUB_DESCRIPTOR HubDescriptor;
579 BOOLEAN HubIsBusPowered;
580} USB_HUB_INFORMATION, *PUSB_HUB_INFORMATION;
581
582typedef struct _USB_MI_PARENT_INFORMATION {
583 ULONG NumberOfInterfaces;
584} USB_MI_PARENT_INFORMATION, *PUSB_MI_PARENT_INFORMATION;
585
586typedef struct _USB_NODE_INFORMATION {
587 USB_HUB_NODE NodeType;
588 union {
589 USB_HUB_INFORMATION HubInformation;
590 USB_MI_PARENT_INFORMATION MiParentInformation;
591 } u;
592} USB_NODE_INFORMATION, *PUSB_NODE_INFORMATION;
593
594typedef struct _USB_PIPE_INFO {
595 USB_ENDPOINT_DESCRIPTOR EndpointDescriptor;
596 ULONG ScheduleOffset;
597} USB_PIPE_INFO, *PUSB_PIPE_INFO;
598
599typedef struct _USB_NODE_CONNECTION_INFORMATION {
600 ULONG ConnectionIndex;
601 USB_DEVICE_DESCRIPTOR DeviceDescriptor;
602 UCHAR CurrentConfigurationValue;
603 BOOLEAN LowSpeed;
604 BOOLEAN DeviceIsHub;
605 USHORT DeviceAddress;
606 ULONG NumberOfOpenPipes;
607 USB_CONNECTION_STATUS ConnectionStatus;
608// USB_PIPE_INFO PipeList[0];
609} USB_NODE_CONNECTION_INFORMATION, *PUSB_NODE_CONNECTION_INFORMATION;
610
611typedef struct _USB_HUB_CAP_FLAGS {
612 ULONG HubIsHighSpeedCapable:1;
613 ULONG HubIsHighSpeed:1;
614 ULONG HubIsMultiTtCapable:1;
615 ULONG HubIsMultiTt:1;
616 ULONG HubIsRoot:1;
617 ULONG HubIsArmedWakeOnConnect:1;
618 ULONG ReservedMBZ:26;
619} USB_HUB_CAP_FLAGS, *PUSB_HUB_CAP_FLAGS;
620
621typedef struct _USB_HUB_CAPABILITIES {
622 ULONG HubIs2xCapable : 1;
623} USB_HUB_CAPABILITIES, *PUSB_HUB_CAPABILITIES;
624
625typedef struct _USB_HUB_CAPABILITIES_EX {
626 USB_HUB_CAP_FLAGS CapabilityFlags;
627} USB_HUB_CAPABILITIES_EX, *PUSB_HUB_CAPABILITIES_EX;
628
629#pragma pack(pop)
630
631/* winusb.dll interface */
632
633#define SHORT_PACKET_TERMINATE 0x01
634#define AUTO_CLEAR_STALL 0x02
635#define PIPE_TRANSFER_TIMEOUT 0x03
636#define IGNORE_SHORT_PACKETS 0x04
637#define ALLOW_PARTIAL_READS 0x05
638#define AUTO_FLUSH 0x06
639#define RAW_IO 0x07
640#define MAXIMUM_TRANSFER_SIZE 0x08
641#define AUTO_SUSPEND 0x81
642#define SUSPEND_DELAY 0x83
643#define DEVICE_SPEED 0x01
644#define LowSpeed 0x01
645#define FullSpeed 0x02
646#define HighSpeed 0x03
647
648typedef enum _USBD_PIPE_TYPE {
649 UsbdPipeTypeControl,
650 UsbdPipeTypeIsochronous,
651 UsbdPipeTypeBulk,
652 UsbdPipeTypeInterrupt
653} USBD_PIPE_TYPE;
654
655typedef struct {
656 USBD_PIPE_TYPE PipeType;
657 UCHAR PipeId;
658 USHORT MaximumPacketSize;
659 UCHAR Interval;
660} WINUSB_PIPE_INFORMATION, *PWINUSB_PIPE_INFORMATION;
661
662#pragma pack(1)
663typedef struct {
664 UCHAR request_type;
665 UCHAR request;
666 USHORT value;
667 USHORT index;
668 USHORT length;
669} WINUSB_SETUP_PACKET, *PWINUSB_SETUP_PACKET;
670#pragma pack()
671
672typedef void *WINUSB_INTERFACE_HANDLE, *PWINUSB_INTERFACE_HANDLE;
673
674DLL_DECLARE(WINAPI, BOOL, WinUsb_Initialize, (HANDLE, PWINUSB_INTERFACE_HANDLE));
675DLL_DECLARE(WINAPI, BOOL, WinUsb_Free, (WINUSB_INTERFACE_HANDLE));
676DLL_DECLARE(WINAPI, BOOL, WinUsb_GetAssociatedInterface, (WINUSB_INTERFACE_HANDLE, UCHAR, PWINUSB_INTERFACE_HANDLE));
677DLL_DECLARE(WINAPI, BOOL, WinUsb_GetDescriptor, (WINUSB_INTERFACE_HANDLE, UCHAR, UCHAR, USHORT, PUCHAR, ULONG, PULONG));
678DLL_DECLARE(WINAPI, BOOL, WinUsb_QueryInterfaceSettings, (WINUSB_INTERFACE_HANDLE, UCHAR, PUSB_INTERFACE_DESCRIPTOR));
679DLL_DECLARE(WINAPI, BOOL, WinUsb_QueryDeviceInformation, (WINUSB_INTERFACE_HANDLE, ULONG, PULONG, PVOID));
680DLL_DECLARE(WINAPI, BOOL, WinUsb_SetCurrentAlternateSetting, (WINUSB_INTERFACE_HANDLE, UCHAR));
681DLL_DECLARE(WINAPI, BOOL, WinUsb_GetCurrentAlternateSetting, (WINUSB_INTERFACE_HANDLE, PUCHAR));
682DLL_DECLARE(WINAPI, BOOL, WinUsb_QueryPipe, (WINUSB_INTERFACE_HANDLE, UCHAR, UCHAR, PWINUSB_PIPE_INFORMATION));
683DLL_DECLARE(WINAPI, BOOL, WinUsb_SetPipePolicy, (WINUSB_INTERFACE_HANDLE, UCHAR, ULONG, ULONG, PVOID));
684DLL_DECLARE(WINAPI, BOOL, WinUsb_GetPipePolicy, (WINUSB_INTERFACE_HANDLE, UCHAR, ULONG, PULONG, PVOID));
685DLL_DECLARE(WINAPI, BOOL, WinUsb_ReadPipe, (WINUSB_INTERFACE_HANDLE, UCHAR, PUCHAR, ULONG, PULONG, LPOVERLAPPED));
686DLL_DECLARE(WINAPI, BOOL, WinUsb_WritePipe, (WINUSB_INTERFACE_HANDLE, UCHAR, PUCHAR, ULONG, PULONG, LPOVERLAPPED));
687DLL_DECLARE(WINAPI, BOOL, WinUsb_ControlTransfer, (WINUSB_INTERFACE_HANDLE, WINUSB_SETUP_PACKET, PUCHAR, ULONG, PULONG, LPOVERLAPPED));
688DLL_DECLARE(WINAPI, BOOL, WinUsb_ResetPipe, (WINUSB_INTERFACE_HANDLE, UCHAR));
689DLL_DECLARE(WINAPI, BOOL, WinUsb_AbortPipe, (WINUSB_INTERFACE_HANDLE, UCHAR));
690DLL_DECLARE(WINAPI, BOOL, WinUsb_FlushPipe, (WINUSB_INTERFACE_HANDLE, UCHAR));
691
692/* hid.dll interface */
693
694#define HIDP_STATUS_SUCCESS 0x110000
695typedef void* PHIDP_PREPARSED_DATA;
696
697#pragma pack(1)
698typedef struct {
699 ULONG Size;
700 USHORT VendorID;
701 USHORT ProductID;
702 USHORT VersionNumber;
703} HIDD_ATTRIBUTES, *PHIDD_ATTRIBUTES;
704#pragma pack()
705
706typedef USHORT USAGE;
707typedef struct {
708 USAGE Usage;
709 USAGE UsagePage;
710 USHORT InputReportByteLength;
711 USHORT OutputReportByteLength;
712 USHORT FeatureReportByteLength;
713 USHORT Reserved[17];
714 USHORT NumberLinkCollectionNodes;
715 USHORT NumberInputButtonCaps;
716 USHORT NumberInputValueCaps;
717 USHORT NumberInputDataIndices;
718 USHORT NumberOutputButtonCaps;
719 USHORT NumberOutputValueCaps;
720 USHORT NumberOutputDataIndices;
721 USHORT NumberFeatureButtonCaps;
722 USHORT NumberFeatureValueCaps;
723 USHORT NumberFeatureDataIndices;
724} HIDP_CAPS, *PHIDP_CAPS;
725
726typedef enum _HIDP_REPORT_TYPE {
727 HidP_Input,
728 HidP_Output,
729 HidP_Feature
730} HIDP_REPORT_TYPE;
731
732typedef struct _HIDP_VALUE_CAPS {
733 USAGE UsagePage;
734 UCHAR ReportID;
735 BOOLEAN IsAlias;
736 USHORT BitField;
737 USHORT LinkCollection;
738 USAGE LinkUsage;
739 USAGE LinkUsagePage;
740 BOOLEAN IsRange;
741 BOOLEAN IsStringRange;
742 BOOLEAN IsDesignatorRange;
743 BOOLEAN IsAbsolute;
744 BOOLEAN HasNull;
745 UCHAR Reserved;
746 USHORT BitSize;
747 USHORT ReportCount;
748 USHORT Reserved2[5];
749 ULONG UnitsExp;
750 ULONG Units;
751 LONG LogicalMin, LogicalMax;
752 LONG PhysicalMin, PhysicalMax;
753 union {
754 struct {
755 USAGE UsageMin, UsageMax;
756 USHORT StringMin, StringMax;
757 USHORT DesignatorMin, DesignatorMax;
758 USHORT DataIndexMin, DataIndexMax;
759 } Range;
760 struct {
761 USAGE Usage, Reserved1;
762 USHORT StringIndex, Reserved2;
763 USHORT DesignatorIndex, Reserved3;
764 USHORT DataIndex, Reserved4;
765 } NotRange;
766 } u;
767} HIDP_VALUE_CAPS, *PHIDP_VALUE_CAPS;
768
769DLL_DECLARE(WINAPI, BOOL, HidD_GetAttributes, (HANDLE, PHIDD_ATTRIBUTES));
770DLL_DECLARE(WINAPI, VOID, HidD_GetHidGuid, (LPGUID));
771DLL_DECLARE(WINAPI, BOOL, HidD_GetPreparsedData, (HANDLE, PHIDP_PREPARSED_DATA *));
772DLL_DECLARE(WINAPI, BOOL, HidD_FreePreparsedData, (PHIDP_PREPARSED_DATA));
773DLL_DECLARE(WINAPI, BOOL, HidD_GetManufacturerString, (HANDLE, PVOID, ULONG));
774DLL_DECLARE(WINAPI, BOOL, HidD_GetProductString, (HANDLE, PVOID, ULONG));
775DLL_DECLARE(WINAPI, BOOL, HidD_GetSerialNumberString, (HANDLE, PVOID, ULONG));
776DLL_DECLARE(WINAPI, LONG, HidP_GetCaps, (PHIDP_PREPARSED_DATA, PHIDP_CAPS));
777DLL_DECLARE(WINAPI, BOOL, HidD_SetNumInputBuffers, (HANDLE, ULONG));
778DLL_DECLARE(WINAPI, BOOL, HidD_SetFeature, (HANDLE, PVOID, ULONG));
779DLL_DECLARE(WINAPI, BOOL, HidD_GetFeature, (HANDLE, PVOID, ULONG));
780DLL_DECLARE(WINAPI, BOOL, HidD_GetPhysicalDescriptor, (HANDLE, PVOID, ULONG));
781DLL_DECLARE(WINAPI, BOOL, HidD_GetInputReport, (HANDLE, PVOID, ULONG));
782DLL_DECLARE(WINAPI, BOOL, HidD_SetOutputReport, (HANDLE, PVOID, ULONG));
783DLL_DECLARE(WINAPI, BOOL, HidD_FlushQueue, (HANDLE));
784DLL_DECLARE(WINAPI, BOOL, HidP_GetValueCaps, (HIDP_REPORT_TYPE, PHIDP_VALUE_CAPS, PULONG, PHIDP_PREPARSED_DATA));