darwin: fix reset device
[platform/upstream/libusb.git] / libusb / os / darwin_usb.c
1 /* -*- Mode: C; indent-tabs-mode:nil -*- */
2 /*
3  * darwin backend for libusb 1.0
4  * Copyright © 2008-2019 Nathan Hjelm <hjelmn@users.sourceforge.net>
5  * Copyright © 2019      Google LLC. All rights reserved.
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 #include "config.h"
23 #include <assert.h>
24 #include <time.h>
25 #include <ctype.h>
26 #include <errno.h>
27 #include <pthread.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <sys/types.h>
32 #include <unistd.h>
33 #include <fcntl.h>
34 #include <sys/sysctl.h>
35
36 #include <mach/clock.h>
37 #include <mach/clock_types.h>
38 #include <mach/mach_host.h>
39 #include <mach/mach_port.h>
40
41 /* Suppress warnings about the use of the deprecated objc_registerThreadWithCollector
42  * function. Its use is also conditionalized to only older deployment targets. */
43 #define OBJC_SILENCE_GC_DEPRECATIONS 1
44
45 #include <AvailabilityMacros.h>
46 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
47   #include <objc/objc-auto.h>
48 #endif
49
50 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 101200
51 /* Apple deprecated the darwin atomics in 10.12 in favor of C11 atomics */
52 #include <stdatomic.h>
53 #define libusb_darwin_atomic_fetch_add(x, y) atomic_fetch_add(x, y)
54
55 _Atomic int32_t initCount = ATOMIC_VAR_INIT(0);
56 #else
57 /* use darwin atomics if the target is older than 10.12 */
58 #include <libkern/OSAtomic.h>
59
60 /* OSAtomicAdd32Barrier returns the new value */
61 #define libusb_darwin_atomic_fetch_add(x, y) (OSAtomicAdd32Barrier(y, x) - y)
62
63 static volatile int32_t initCount = 0;
64
65 #endif
66
67 /* On 10.12 and later, use newly available clock_*() functions */
68 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 101200
69 #define OSX_USE_CLOCK_GETTIME 1
70 #else
71 #define OSX_USE_CLOCK_GETTIME 0
72 #endif
73
74 #include "darwin_usb.h"
75
76 /* async event thread */
77 static pthread_mutex_t libusb_darwin_at_mutex = PTHREAD_MUTEX_INITIALIZER;
78 static pthread_cond_t  libusb_darwin_at_cond = PTHREAD_COND_INITIALIZER;
79
80 #if !OSX_USE_CLOCK_GETTIME
81 static clock_serv_t clock_realtime;
82 static clock_serv_t clock_monotonic;
83 #endif
84
85 static CFRunLoopRef libusb_darwin_acfl = NULL; /* event cf loop */
86 static CFRunLoopSourceRef libusb_darwin_acfls = NULL; /* shutdown signal for event cf loop */
87
88 static usbi_mutex_t darwin_cached_devices_lock = PTHREAD_MUTEX_INITIALIZER;
89 static struct list_head darwin_cached_devices = {&darwin_cached_devices, &darwin_cached_devices};
90 static const char *darwin_device_class = kIOUSBDeviceClassName;
91
92 #define DARWIN_CACHED_DEVICE(a) ((struct darwin_cached_device *) (((struct darwin_device_priv *)((a)->os_priv))->dev))
93
94 /* async event thread */
95 static pthread_t libusb_darwin_at;
96
97 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
98 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
99 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
100 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
101 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
102
103 static enum libusb_error darwin_scan_devices(struct libusb_context *ctx);
104 static enum libusb_error process_new_device (struct libusb_context *ctx, io_service_t service);
105
106 #if defined(ENABLE_LOGGING)
107 static const char *darwin_error_str (IOReturn result) {
108   static char string_buffer[50];
109   switch (result) {
110   case kIOReturnSuccess:
111     return "no error";
112   case kIOReturnNotOpen:
113     return "device not opened for exclusive access";
114   case kIOReturnNoDevice:
115     return "no connection to an IOService";
116   case kIOUSBNoAsyncPortErr:
117     return "no async port has been opened for interface";
118   case kIOReturnExclusiveAccess:
119     return "another process has device opened for exclusive access";
120   case kIOUSBPipeStalled:
121     return "pipe is stalled";
122   case kIOReturnError:
123     return "could not establish a connection to the Darwin kernel";
124   case kIOUSBTransactionTimeout:
125     return "transaction timed out";
126   case kIOReturnBadArgument:
127     return "invalid argument";
128   case kIOReturnAborted:
129     return "transaction aborted";
130   case kIOReturnNotResponding:
131     return "device not responding";
132   case kIOReturnOverrun:
133     return "data overrun";
134   case kIOReturnCannotWire:
135     return "physical memory can not be wired down";
136   case kIOReturnNoResources:
137     return "out of resources";
138   case kIOUSBHighSpeedSplitError:
139     return "high speed split error";
140   default:
141     snprintf(string_buffer, sizeof(string_buffer), "unknown error (0x%x)", result);
142     return string_buffer;
143   }
144 }
145 #endif
146
147 static enum libusb_error darwin_to_libusb (IOReturn result) {
148   switch (result) {
149   case kIOReturnUnderrun:
150   case kIOReturnSuccess:
151     return LIBUSB_SUCCESS;
152   case kIOReturnNotOpen:
153   case kIOReturnNoDevice:
154     return LIBUSB_ERROR_NO_DEVICE;
155   case kIOReturnExclusiveAccess:
156     return LIBUSB_ERROR_ACCESS;
157   case kIOUSBPipeStalled:
158     return LIBUSB_ERROR_PIPE;
159   case kIOReturnBadArgument:
160     return LIBUSB_ERROR_INVALID_PARAM;
161   case kIOUSBTransactionTimeout:
162     return LIBUSB_ERROR_TIMEOUT;
163   case kIOReturnNotResponding:
164   case kIOReturnAborted:
165   case kIOReturnError:
166   case kIOUSBNoAsyncPortErr:
167   default:
168     return LIBUSB_ERROR_OTHER;
169   }
170 }
171
172 /* this function must be called with the darwin_cached_devices_lock held */
173 static void darwin_deref_cached_device(struct darwin_cached_device *cached_dev) {
174   cached_dev->refcount--;
175   /* free the device and remove it from the cache */
176   if (0 == cached_dev->refcount) {
177     list_del(&cached_dev->list);
178
179     (*(cached_dev->device))->Release(cached_dev->device);
180     free (cached_dev);
181   }
182 }
183
184 static void darwin_ref_cached_device(struct darwin_cached_device *cached_dev) {
185   cached_dev->refcount++;
186 }
187
188 static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp, struct darwin_interface **interface_out) {
189   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
190
191   /* current interface */
192   struct darwin_interface *cInterface;
193
194   uint8_t i, iface;
195
196   usbi_dbg ("converting ep address 0x%02x to pipeRef and interface", ep);
197
198   for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
199     cInterface = &priv->interfaces[iface];
200
201     if (dev_handle->claimed_interfaces & (1U << iface)) {
202       for (i = 0 ; i < cInterface->num_endpoints ; i++) {
203         if (cInterface->endpoint_addrs[i] == ep) {
204           *pipep = i + 1;
205
206           if (ifcp)
207             *ifcp = iface;
208
209           if (interface_out)
210             *interface_out = cInterface;
211
212           usbi_dbg ("pipe %d on interface %d matches", *pipep, iface);
213           return LIBUSB_SUCCESS;
214         }
215       }
216     }
217   }
218
219   /* No pipe found with the correct endpoint address */
220   usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
221
222   return LIBUSB_ERROR_NOT_FOUND;
223 }
224
225 static IOReturn usb_setup_device_iterator (io_iterator_t *deviceIterator, UInt32 location) {
226   CFMutableDictionaryRef matchingDict = IOServiceMatching(darwin_device_class);
227
228   if (!matchingDict)
229     return kIOReturnError;
230
231   if (location) {
232     CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
233                                                                          &kCFTypeDictionaryKeyCallBacks,
234                                                                          &kCFTypeDictionaryValueCallBacks);
235
236     /* there are no unsigned CFNumber types so treat the value as signed. the OS seems to do this
237          internally (CFNumberType of locationID is kCFNumberSInt32Type) */
238     CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberSInt32Type, &location);
239
240     if (propertyMatchDict && locationCF) {
241       CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
242       CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
243     }
244     /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
245
246     /* release our references as per the Create Rule */
247     if (propertyMatchDict)
248       CFRelease (propertyMatchDict);
249     if (locationCF)
250       CFRelease (locationCF);
251   }
252
253   return IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, deviceIterator);
254 }
255
256 /* Returns 1 on success, 0 on failure. */
257 static bool get_ioregistry_value_number (io_service_t service, CFStringRef property, CFNumberType type, void *p) {
258   CFTypeRef cfNumber = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
259   Boolean success = 0;
260
261   if (cfNumber) {
262     if (CFGetTypeID(cfNumber) == CFNumberGetTypeID()) {
263       success = CFNumberGetValue(cfNumber, type, p);
264     }
265
266     CFRelease (cfNumber);
267   }
268
269   return (success != 0);
270 }
271
272 /* Returns 1 on success, 0 on failure. */
273 static bool get_ioregistry_value_data (io_service_t service, CFStringRef property, ssize_t size, void *p) {
274   CFTypeRef cfData = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
275   bool success = false;
276
277   if (cfData) {
278     if (CFGetTypeID (cfData) == CFDataGetTypeID ()) {
279       CFIndex length = CFDataGetLength (cfData);
280       if (length < size) {
281         size = length;
282       }
283
284       CFDataGetBytes (cfData, CFRangeMake(0, size), p);
285       success = true;
286     }
287
288     CFRelease (cfData);
289   }
290
291   return success;
292 }
293
294 static usb_device_t **darwin_device_from_service (io_service_t service)
295 {
296   io_cf_plugin_ref_t *plugInInterface = NULL;
297   usb_device_t **device;
298   IOReturn kresult;
299   SInt32 score;
300
301   kresult = IOCreatePlugInInterfaceForService(service, kIOUSBDeviceUserClientTypeID,
302                                               kIOCFPlugInInterfaceID, &plugInInterface,
303                                               &score);
304
305   if (kIOReturnSuccess != kresult || !plugInInterface) {
306     usbi_dbg ("could not set up plugin for service: %s", darwin_error_str (kresult));
307     return NULL;
308   }
309
310   (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
311                                            (LPVOID)&device);
312   /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
313   (*plugInInterface)->Release (plugInInterface);
314
315   return device;
316 }
317
318 static void darwin_devices_attached (void *ptr, io_iterator_t add_devices) {
319   UNUSED(ptr);
320   struct libusb_context *ctx;
321   io_service_t service;
322
323   usbi_mutex_lock(&active_contexts_lock);
324
325   while ((service = IOIteratorNext(add_devices))) {
326     /* add this device to each active context's device list */
327     list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
328       process_new_device (ctx, service);
329     }
330
331     IOObjectRelease(service);
332   }
333
334   usbi_mutex_unlock(&active_contexts_lock);
335 }
336
337 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
338   UNUSED(ptr);
339   struct libusb_device *dev = NULL;
340   struct libusb_context *ctx;
341   struct darwin_cached_device *old_device;
342
343   io_service_t device;
344   UInt64 session;
345   int ret;
346
347   usbi_mutex_lock(&active_contexts_lock);
348
349   while ((device = IOIteratorNext (rem_devices)) != 0) {
350     /* get the location from the i/o registry */
351     ret = get_ioregistry_value_number (device, CFSTR("sessionID"), kCFNumberSInt64Type, &session);
352     IOObjectRelease (device);
353     if (!ret)
354       continue;
355
356     /* we need to match darwin_ref_cached_device call made in darwin_get_cached_device function
357        otherwise no cached device will ever get freed */
358     usbi_mutex_lock(&darwin_cached_devices_lock);
359     list_for_each_entry(old_device, &darwin_cached_devices, list, struct darwin_cached_device) {
360       if (old_device->session == session) {
361         if (old_device->in_reenumerate) {
362           /* device is re-enumerating. do not dereference the device at this time. libusb_reset_device()
363            * will deref if needed. */
364           usbi_dbg ("detected device detatched due to re-enumeration");
365         } else {
366           darwin_deref_cached_device (old_device);
367         }
368         break;
369       }
370     }
371     usbi_mutex_unlock(&darwin_cached_devices_lock);
372     if (old_device->in_reenumerate) {
373       continue;
374     }
375
376     list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
377       usbi_dbg ("notifying context %p of device disconnect", ctx);
378
379       dev = usbi_get_device_by_session_id(ctx, (unsigned long) session);
380       if (dev) {
381         /* signal the core that this device has been disconnected. the core will tear down this device
382            when the reference count reaches 0 */
383         usbi_disconnect_device(dev);
384         libusb_unref_device(dev);
385       }
386     }
387   }
388
389   usbi_mutex_unlock(&active_contexts_lock);
390 }
391
392 static void darwin_hotplug_poll (void)
393 {
394   /* not sure if 1 ms will be too long/short but it should work ok */
395   mach_timespec_t timeout = {.tv_sec = 0, .tv_nsec = 1000000ul};
396
397   /* since a kernel thread may nodify the IOInterators used for
398    * hotplug notidication we can't just clear the iterators.
399    * instead just wait until all IOService providers are quiet */
400   (void) IOKitWaitQuiet (kIOMasterPortDefault, &timeout);
401 }
402
403 static void darwin_clear_iterator (io_iterator_t iter) {
404   io_service_t device;
405
406   while ((device = IOIteratorNext (iter)) != 0)
407     IOObjectRelease (device);
408 }
409
410 static void *darwin_event_thread_main (void *arg0) {
411   IOReturn kresult;
412   struct libusb_context *ctx = (struct libusb_context *)arg0;
413   CFRunLoopRef runloop;
414
415 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
416   /* Set this thread's name, so it can be seen in the debugger
417      and crash reports. */
418   pthread_setname_np ("org.libusb.device-hotplug");
419 #endif
420
421 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
422   /* Tell the Objective-C garbage collector about this thread.
423      This is required because, unlike NSThreads, pthreads are
424      not automatically registered. Although we don't use
425      Objective-C, we use CoreFoundation, which does.
426      Garbage collection support was entirely removed in 10.12,
427      so don't bother there. */
428   objc_registerThreadWithCollector();
429 #endif
430
431   /* hotplug (device arrival/removal) sources */
432   CFRunLoopSourceContext libusb_shutdown_cfsourcectx;
433   CFRunLoopSourceRef     libusb_notification_cfsource;
434   io_notification_port_t libusb_notification_port;
435   io_iterator_t          libusb_rem_device_iterator;
436   io_iterator_t          libusb_add_device_iterator;
437
438   usbi_dbg ("creating hotplug event source");
439
440   runloop = CFRunLoopGetCurrent ();
441   CFRetain (runloop);
442
443   /* add the shutdown cfsource to the run loop */
444   memset(&libusb_shutdown_cfsourcectx, 0, sizeof(libusb_shutdown_cfsourcectx));
445   libusb_shutdown_cfsourcectx.info = runloop;
446   libusb_shutdown_cfsourcectx.perform = (void (*)(void *))CFRunLoopStop;
447   libusb_darwin_acfls = CFRunLoopSourceCreate(NULL, 0, &libusb_shutdown_cfsourcectx);
448   CFRunLoopAddSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode);
449
450   /* add the notification port to the run loop */
451   libusb_notification_port     = IONotificationPortCreate (kIOMasterPortDefault);
452   libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
453   CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
454
455   /* create notifications for removed devices */
456   kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
457                                               IOServiceMatching(darwin_device_class),
458                                               darwin_devices_detached,
459                                               ctx, &libusb_rem_device_iterator);
460
461   if (kresult != kIOReturnSuccess) {
462     usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
463
464     pthread_exit (NULL);
465   }
466
467   /* create notifications for attached devices */
468   kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification,
469                                               IOServiceMatching(darwin_device_class),
470                                               darwin_devices_attached,
471                                               ctx, &libusb_add_device_iterator);
472
473   if (kresult != kIOReturnSuccess) {
474     usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
475
476     pthread_exit (NULL);
477   }
478
479   /* arm notifiers */
480   darwin_clear_iterator (libusb_rem_device_iterator);
481   darwin_clear_iterator (libusb_add_device_iterator);
482
483   usbi_dbg ("darwin event thread ready to receive events");
484
485   /* signal the main thread that the hotplug runloop has been created. */
486   pthread_mutex_lock (&libusb_darwin_at_mutex);
487   libusb_darwin_acfl = runloop;
488   pthread_cond_signal (&libusb_darwin_at_cond);
489   pthread_mutex_unlock (&libusb_darwin_at_mutex);
490
491   /* run the runloop */
492   CFRunLoopRun();
493
494   usbi_dbg ("darwin event thread exiting");
495
496   /* remove the notification cfsource */
497   CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
498
499   /* remove the shutdown cfsource */
500   CFRunLoopRemoveSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode);
501
502   /* delete notification port */
503   IONotificationPortDestroy (libusb_notification_port);
504
505   /* delete iterators */
506   IOObjectRelease (libusb_rem_device_iterator);
507   IOObjectRelease (libusb_add_device_iterator);
508
509   CFRelease (libusb_darwin_acfls);
510   CFRelease (runloop);
511
512   libusb_darwin_acfls = NULL;
513   libusb_darwin_acfl = NULL;
514
515   pthread_exit (NULL);
516 }
517
518 /* cleanup function to destroy cached devices */
519 static void __attribute__((destructor)) _darwin_finalize(void) {
520   struct darwin_cached_device *dev, *next;
521
522   usbi_mutex_lock(&darwin_cached_devices_lock);
523   list_for_each_entry_safe(dev, next, &darwin_cached_devices, list, struct darwin_cached_device) {
524     darwin_deref_cached_device(dev);
525   }
526   usbi_mutex_unlock(&darwin_cached_devices_lock);
527 }
528
529 static int darwin_init(struct libusb_context *ctx) {
530   int rc;
531
532   rc = darwin_scan_devices (ctx);
533   if (LIBUSB_SUCCESS != rc) {
534     return rc;
535   }
536
537   if (libusb_darwin_atomic_fetch_add (&initCount, 1) == 0) {
538 #if !OSX_USE_CLOCK_GETTIME
539     /* create the clocks that will be used if clock_gettime() is not available */
540     host_name_port_t host_self;
541
542     host_self = mach_host_self();
543     host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
544     host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
545     mach_port_deallocate(mach_task_self(), host_self);
546 #endif
547
548     pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, ctx);
549
550     pthread_mutex_lock (&libusb_darwin_at_mutex);
551     while (!libusb_darwin_acfl)
552       pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
553     pthread_mutex_unlock (&libusb_darwin_at_mutex);
554   }
555
556   return rc;
557 }
558
559 static void darwin_exit (struct libusb_context *ctx) {
560   UNUSED(ctx);
561   if (libusb_darwin_atomic_fetch_add (&initCount, -1) == 1) {
562 #if !OSX_USE_CLOCK_GETTIME
563     mach_port_deallocate(mach_task_self(), clock_realtime);
564     mach_port_deallocate(mach_task_self(), clock_monotonic);
565 #endif
566
567     /* stop the event runloop and wait for the thread to terminate. */
568     CFRunLoopSourceSignal(libusb_darwin_acfls);
569     CFRunLoopWakeUp (libusb_darwin_acfl);
570     pthread_join (libusb_darwin_at, NULL);
571   }
572 }
573
574 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
575   struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
576
577   /* return cached copy */
578   memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
579
580   *host_endian = 0;
581
582   return LIBUSB_SUCCESS;
583 }
584
585 static int get_configuration_index (struct libusb_device *dev, int config_value) {
586   struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
587   UInt8 i, numConfig;
588   IOUSBConfigurationDescriptorPtr desc;
589   IOReturn kresult;
590
591   /* is there a simpler way to determine the index? */
592   kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
593   if (kresult != kIOReturnSuccess)
594     return darwin_to_libusb (kresult);
595
596   for (i = 0 ; i < numConfig ; i++) {
597     (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
598
599     if (desc->bConfigurationValue == config_value)
600       return i;
601   }
602
603   /* configuration not found */
604   return LIBUSB_ERROR_NOT_FOUND;
605 }
606
607 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
608   struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
609   int config_index;
610
611   if (0 == priv->active_config)
612     return LIBUSB_ERROR_NOT_FOUND;
613
614   config_index = get_configuration_index (dev, priv->active_config);
615   if (config_index < 0)
616     return config_index;
617
618   assert(config_index >= 0 && config_index <= UINT8_MAX);
619   return darwin_get_config_descriptor (dev, (UInt8)config_index, buffer, len, host_endian);
620 }
621
622 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
623   struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
624   IOUSBConfigurationDescriptorPtr desc;
625   IOReturn kresult;
626   int ret;
627
628   if (!priv || !priv->device)
629     return LIBUSB_ERROR_OTHER;
630
631   kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
632   if (kresult == kIOReturnSuccess) {
633     /* copy descriptor */
634     if (libusb_le16_to_cpu(desc->wTotalLength) < len)
635       len = libusb_le16_to_cpu(desc->wTotalLength);
636
637     memmove (buffer, desc, len);
638
639     /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
640     *host_endian = 0;
641   }
642
643   ret = darwin_to_libusb (kresult);
644   if (ret != LIBUSB_SUCCESS)
645     return ret;
646
647   return (int) len;
648 }
649
650 /* check whether the os has configured the device */
651 static enum libusb_error darwin_check_configuration (struct libusb_context *ctx, struct darwin_cached_device *dev) {
652   usb_device_t **darwin_device = dev->device;
653
654   IOUSBConfigurationDescriptorPtr configDesc;
655   IOUSBFindInterfaceRequest request;
656   IOReturn                  kresult;
657   io_iterator_t             interface_iterator;
658   io_service_t              firstInterface;
659
660   if (dev->dev_descriptor.bNumConfigurations < 1) {
661     usbi_err (ctx, "device has no configurations");
662     return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
663   }
664
665   /* checking the configuration of a root hub simulation takes ~1 s in 10.11. the device is
666      not usable anyway */
667   if (0x05ac == dev->dev_descriptor.idVendor && 0x8005 == dev->dev_descriptor.idProduct) {
668     usbi_dbg ("ignoring configuration on root hub simulation");
669     dev->active_config = 0;
670     return LIBUSB_SUCCESS;
671   }
672
673   /* find the first configuration */
674   kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
675   dev->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
676
677   /* check if the device is already configured. there is probably a better way than iterating over the
678      to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
679      might lock up on the device request) */
680
681   /* Setup the Interface Request */
682   request.bInterfaceClass    = kIOUSBFindInterfaceDontCare;
683   request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
684   request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
685   request.bAlternateSetting  = kIOUSBFindInterfaceDontCare;
686
687   kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
688   if (kresult != kIOReturnSuccess)
689     return darwin_to_libusb (kresult);
690
691   /* iterate once */
692   firstInterface = IOIteratorNext(interface_iterator);
693
694   /* done with the interface iterator */
695   IOObjectRelease(interface_iterator);
696
697   if (firstInterface) {
698     IOObjectRelease (firstInterface);
699
700     /* device is configured */
701     if (dev->dev_descriptor.bNumConfigurations == 1)
702       /* to avoid problems with some devices get the configurations value from the configuration descriptor */
703       dev->active_config = dev->first_config;
704     else
705       /* devices with more than one configuration should work with GetConfiguration */
706       (*darwin_device)->GetConfiguration (darwin_device, &dev->active_config);
707   } else
708     /* not configured */
709     dev->active_config = 0;
710   
711   usbi_dbg ("active config: %u, first config: %u", dev->active_config, dev->first_config);
712
713   return LIBUSB_SUCCESS;
714 }
715
716 static IOReturn darwin_request_descriptor (usb_device_t **device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
717   IOUSBDevRequestTO req;
718
719   assert(buffer_size <= UINT16_MAX);
720
721   memset (buffer, 0, buffer_size);
722
723   /* Set up request for descriptor/ */
724   req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
725   req.bRequest      = kUSBRqGetDescriptor;
726   req.wValue        = (UInt16)(desc << 8);
727   req.wIndex        = desc_index;
728   req.wLength       = (UInt16)buffer_size;
729   req.pData         = buffer;
730   req.noDataTimeout = 20;
731   req.completionTimeout = 100;
732
733   return (*device)->DeviceRequestTO (device, &req);
734 }
735
736 static enum libusb_error darwin_cache_device_descriptor (struct libusb_context *ctx, struct darwin_cached_device *dev) {
737   usb_device_t **device = dev->device;
738   int retries = 1;
739   long delay = 30000; // microseconds
740   int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
741   int is_open = 0;
742   IOReturn ret = 0, ret2;
743   UInt8 bDeviceClass;
744   UInt16 idProduct, idVendor;
745
746   dev->can_enumerate = 0;
747
748   (*device)->GetDeviceClass (device, &bDeviceClass);
749   (*device)->GetDeviceProduct (device, &idProduct);
750   (*device)->GetDeviceVendor (device, &idVendor);
751
752   /* According to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
753    * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request.  Still,
754    * to follow the spec as closely as possible, try opening the device */
755   is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
756
757   do {
758     /**** retrieve device descriptor ****/
759     ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &dev->dev_descriptor, sizeof(dev->dev_descriptor));
760
761     if (kIOReturnOverrun == ret && kUSBDeviceDesc == dev->dev_descriptor.bDescriptorType)
762       /* received an overrun error but we still received a device descriptor */
763       ret = kIOReturnSuccess;
764
765     if (kIOUSBVendorIDAppleComputer == idVendor) {
766       /* NTH: don't bother retrying or unsuspending Apple devices */
767       break;
768     }
769
770     if (kIOReturnSuccess == ret && (0 == dev->dev_descriptor.bNumConfigurations ||
771                                     0 == dev->dev_descriptor.bcdUSB)) {
772       /* work around for incorrectly configured devices */
773       if (try_reconfigure && is_open) {
774         usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
775
776         /* set the first configuration */
777         (*device)->SetConfiguration(device, 1);
778
779         /* don't try to reconfigure again */
780         try_reconfigure = 0;
781       }
782
783       ret = kIOUSBPipeStalled;
784     }
785
786     if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
787       /* device may be suspended. unsuspend it and try again */
788 #if DeviceVersion >= 320
789       UInt32 info = 0;
790
791       /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
792       (void)(*device)->GetUSBDeviceInformation (device, &info);
793
794       /* note that the device was suspended */
795       if (info & (1U << kUSBInformationDeviceIsSuspendedBit) || 0 == info)
796         try_unsuspend = 1;
797 #endif
798
799       if (try_unsuspend) {
800         /* try to unsuspend the device */
801         ret2 = (*device)->USBDeviceSuspend (device, 0);
802         if (kIOReturnSuccess != ret2) {
803           /* prevent log spew from poorly behaving devices.  this indicates the
804              os actually had trouble communicating with the device */
805           usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
806         } else
807           unsuspended = 1;
808
809         try_unsuspend = 0;
810       }
811     }
812
813     if (kIOReturnSuccess != ret) {
814       usbi_dbg("kernel responded with code: 0x%08x. sleeping for %ld ms before trying again", ret, delay/1000);
815       /* sleep for a little while before trying again */
816       nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000}, NULL);
817     }
818   } while (kIOReturnSuccess != ret && retries--);
819
820   if (unsuspended)
821     /* resuspend the device */
822     (void)(*device)->USBDeviceSuspend (device, 1);
823
824   if (is_open)
825     (void) (*device)->USBDeviceClose (device);
826
827   if (ret != kIOReturnSuccess) {
828     /* a debug message was already printed out for this error */
829     if (LIBUSB_CLASS_HUB == bDeviceClass)
830       usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
831                 idVendor, idProduct, darwin_error_str (ret), ret);
832     else
833       usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
834                  idVendor, idProduct, darwin_error_str (ret), ret);
835     return darwin_to_libusb (ret);
836   }
837
838   /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
839   if (libusb_le16_to_cpu (dev->dev_descriptor.idProduct) != idProduct) {
840     /* not a valid device */
841     usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
842                idProduct, libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
843     return LIBUSB_ERROR_NO_DEVICE;
844   }
845
846   usbi_dbg ("cached device descriptor:");
847   usbi_dbg ("  bDescriptorType:    0x%02x", dev->dev_descriptor.bDescriptorType);
848   usbi_dbg ("  bcdUSB:             0x%04x", dev->dev_descriptor.bcdUSB);
849   usbi_dbg ("  bDeviceClass:       0x%02x", dev->dev_descriptor.bDeviceClass);
850   usbi_dbg ("  bDeviceSubClass:    0x%02x", dev->dev_descriptor.bDeviceSubClass);
851   usbi_dbg ("  bDeviceProtocol:    0x%02x", dev->dev_descriptor.bDeviceProtocol);
852   usbi_dbg ("  bMaxPacketSize0:    0x%02x", dev->dev_descriptor.bMaxPacketSize0);
853   usbi_dbg ("  idVendor:           0x%04x", dev->dev_descriptor.idVendor);
854   usbi_dbg ("  idProduct:          0x%04x", dev->dev_descriptor.idProduct);
855   usbi_dbg ("  bcdDevice:          0x%04x", dev->dev_descriptor.bcdDevice);
856   usbi_dbg ("  iManufacturer:      0x%02x", dev->dev_descriptor.iManufacturer);
857   usbi_dbg ("  iProduct:           0x%02x", dev->dev_descriptor.iProduct);
858   usbi_dbg ("  iSerialNumber:      0x%02x", dev->dev_descriptor.iSerialNumber);
859   usbi_dbg ("  bNumConfigurations: 0x%02x", dev->dev_descriptor.bNumConfigurations);
860
861   dev->can_enumerate = 1;
862
863   return LIBUSB_SUCCESS;
864 }
865
866 /* Returns 1 on success, 0 on failure. */
867 static bool get_device_port (io_service_t service, UInt8 *port) {
868   IOReturn kresult;
869   io_service_t parent;
870   bool ret = false;
871
872   if (get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, port)) {
873     return true;
874   }
875
876   kresult = IORegistryEntryGetParentEntry (service, kIOServicePlane, &parent);
877   if (kIOReturnSuccess == kresult) {
878     ret = get_ioregistry_value_data (parent, CFSTR("port"), 1, port);
879     IOObjectRelease (parent);
880   }
881
882   return ret;
883 }
884
885 /* Returns 1 on success, 0 on failure. */
886 static bool get_device_parent_sessionID(io_service_t service, UInt64 *parent_sessionID) {
887   IOReturn kresult;
888   io_service_t parent;
889
890   /* Walk up the tree in the IOService plane until we find a parent that has a sessionID */
891   parent = service;
892   while((kresult = IORegistryEntryGetParentEntry (parent, kIOUSBPlane, &parent)) == kIOReturnSuccess) {
893     if (get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, parent_sessionID)) {
894         /* Success */
895         return true;
896     }
897   }
898
899   /* We ran out of parents */
900   return false;
901 }
902
903 static enum libusb_error darwin_get_cached_device(struct libusb_context *ctx, io_service_t service,
904                                                   struct darwin_cached_device **cached_out) {
905   struct darwin_cached_device *new_device;
906   UInt64 sessionID = 0, parent_sessionID = 0;
907   UInt32 locationID = 0;
908   enum libusb_error ret = LIBUSB_SUCCESS;
909   usb_device_t **device;
910   UInt8 port = 0;
911   bool reuse_device = false;
912
913   /* get some info from the io registry */
914   (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
915   (void) get_ioregistry_value_number (service, CFSTR("locationID"), kCFNumberSInt32Type, &locationID);
916   if (!get_device_port (service, &port)) {
917     usbi_dbg("could not get connected port number");
918   }
919
920   usbi_dbg("finding cached device for sessionID 0x%" PRIx64, sessionID);
921
922   if (get_device_parent_sessionID(service, &parent_sessionID)) {
923     usbi_dbg("parent sessionID: 0x%" PRIx64, parent_sessionID);
924   }
925
926   usbi_mutex_lock(&darwin_cached_devices_lock);
927   do {
928     *cached_out = NULL;
929
930     list_for_each_entry(new_device, &darwin_cached_devices, list, struct darwin_cached_device) {
931       usbi_dbg("matching sessionID/locationID 0x%" PRIx64 "/0x%x against cached device with sessionID/locationID 0x%" PRIx64 "/0x%x",
932                sessionID, locationID, new_device->session, new_device->location);
933       if (new_device->location == locationID && new_device->in_reenumerate) {
934         usbi_dbg ("found cached device with matching location that is being re-enumerated");
935         new_device->session = sessionID;
936         reuse_device = true;
937         break;
938       }
939
940       if (new_device->session == sessionID) {
941         usbi_dbg("using cached device for device");
942         *cached_out = new_device;
943         break;
944       }
945     }
946
947     if (*cached_out)
948       break;
949
950     usbi_dbg("caching new device with sessionID 0x%" PRIx64, sessionID);
951
952     device = darwin_device_from_service (service);
953     if (!device) {
954       ret = LIBUSB_ERROR_NO_DEVICE;
955       break;
956     }
957
958     if (!reuse_device) {
959       new_device = calloc (1, sizeof (*new_device));
960       if (!new_device) {
961         ret = LIBUSB_ERROR_NO_MEM;
962         break;
963       }
964
965       /* add this device to the cached device list */
966       list_add(&new_device->list, &darwin_cached_devices);
967
968       (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
969
970       /* keep a reference to this device */
971       darwin_ref_cached_device(new_device);
972
973       new_device->session = sessionID;
974       (*device)->GetLocationID (device, &new_device->location);
975       new_device->port = port;
976       new_device->parent_session = parent_sessionID;
977     }
978
979     new_device->device = device;
980
981     /* cache the device descriptor */
982     ret = darwin_cache_device_descriptor(ctx, new_device);
983     if (ret)
984       break;
985
986     if (new_device->can_enumerate) {
987       snprintf(new_device->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", new_device->address,
988                new_device->dev_descriptor.idVendor, new_device->dev_descriptor.idProduct,
989                new_device->dev_descriptor.bDeviceClass, new_device->dev_descriptor.bDeviceSubClass);
990     }
991   } while (0);
992
993   usbi_mutex_unlock(&darwin_cached_devices_lock);
994
995   /* keep track of devices regardless of if we successfully enumerate them to
996      prevent them from being enumerated multiple times */
997
998   *cached_out = new_device;
999
1000   return ret;
1001 }
1002
1003 static enum libusb_error process_new_device (struct libusb_context *ctx, io_service_t service) {
1004   struct darwin_device_priv *priv;
1005   struct libusb_device *dev = NULL;
1006   struct darwin_cached_device *cached_device;
1007   UInt8 devSpeed;
1008   enum libusb_error ret = LIBUSB_SUCCESS;
1009
1010   do {
1011     ret = darwin_get_cached_device (ctx, service, &cached_device);
1012     if (ret < 0 || !cached_device->can_enumerate) {
1013       return ret;
1014     }
1015
1016     /* check current active configuration (and cache the first configuration value--
1017        which may be used by claim_interface) */
1018     ret = darwin_check_configuration (ctx, cached_device);
1019     if (ret)
1020       break;
1021
1022     usbi_dbg ("allocating new device in context %p for with session 0x%" PRIx64,
1023               ctx, cached_device->session);
1024
1025     dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
1026     if (!dev) {
1027       return LIBUSB_ERROR_NO_MEM;
1028     }
1029
1030     priv = (struct darwin_device_priv *)dev->os_priv;
1031
1032     priv->dev = cached_device;
1033     darwin_ref_cached_device (priv->dev);
1034
1035     if (cached_device->parent_session > 0) {
1036       dev->parent_dev = usbi_get_device_by_session_id (ctx, (unsigned long) cached_device->parent_session);
1037     } else {
1038       dev->parent_dev = NULL;
1039     }
1040     dev->port_number    = cached_device->port;
1041     dev->bus_number     = cached_device->location >> 24;
1042     assert(cached_device->address <= UINT8_MAX);
1043     dev->device_address = (uint8_t)cached_device->address;
1044
1045     (*(priv->dev->device))->GetDeviceSpeed (priv->dev->device, &devSpeed);
1046
1047     switch (devSpeed) {
1048     case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
1049     case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
1050     case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
1051 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
1052     case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
1053 #endif
1054 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101200
1055     case kUSBDeviceSpeedSuperPlus: dev->speed = LIBUSB_SPEED_SUPER_PLUS; break;
1056 #endif
1057     default:
1058       usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
1059     }
1060
1061     ret = usbi_sanitize_device (dev);
1062     if (ret < 0)
1063       break;
1064
1065     usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address,
1066               dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path);
1067
1068   } while (0);
1069
1070   if (cached_device->in_reenumerate) {
1071     usbi_dbg ("cached device in reset state. reset complete...");
1072     cached_device->in_reenumerate = false;
1073   } else if (0 == ret) {
1074     usbi_connect_device (dev);
1075   } else {
1076     libusb_unref_device (dev);
1077   }
1078
1079   return ret;
1080 }
1081
1082 static enum libusb_error darwin_scan_devices(struct libusb_context *ctx) {
1083   io_iterator_t deviceIterator;
1084   io_service_t service;
1085   IOReturn kresult;
1086
1087   kresult = usb_setup_device_iterator (&deviceIterator, 0);
1088   if (kresult != kIOReturnSuccess)
1089     return darwin_to_libusb (kresult);
1090
1091   while ((service = IOIteratorNext (deviceIterator))) {
1092     (void) process_new_device (ctx, service);
1093
1094     IOObjectRelease(service);
1095   }
1096
1097   IOObjectRelease(deviceIterator);
1098
1099   return LIBUSB_SUCCESS;
1100 }
1101
1102 static int darwin_open (struct libusb_device_handle *dev_handle) {
1103   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1104   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1105   IOReturn kresult;
1106
1107   if (0 == dpriv->open_count) {
1108     /* try to open the device */
1109     kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
1110     if (kresult != kIOReturnSuccess) {
1111       usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
1112
1113       if (kIOReturnExclusiveAccess != kresult) {
1114         return darwin_to_libusb (kresult);
1115       }
1116
1117       /* it is possible to perform some actions on a device that is not open so do not return an error */
1118       priv->is_open = false;
1119     } else {
1120       priv->is_open = true;
1121     }
1122
1123     /* create async event source */
1124     kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
1125     if (kresult != kIOReturnSuccess) {
1126       usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
1127
1128       if (priv->is_open) {
1129         (*(dpriv->device))->USBDeviceClose (dpriv->device);
1130       }
1131
1132       priv->is_open = false;
1133
1134       return darwin_to_libusb (kresult);
1135     }
1136
1137     CFRetain (libusb_darwin_acfl);
1138
1139     /* add the cfSource to the aync run loop */
1140     CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
1141   }
1142
1143   /* device opened successfully */
1144   dpriv->open_count++;
1145
1146   usbi_dbg ("device open for access");
1147
1148   return 0;
1149 }
1150
1151 static void darwin_close (struct libusb_device_handle *dev_handle) {
1152   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1153   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1154   IOReturn kresult;
1155   int i;
1156
1157   if (dpriv->open_count == 0) {
1158     /* something is probably very wrong if this is the case */
1159     usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!");
1160     return;
1161   }
1162
1163   dpriv->open_count--;
1164
1165   /* make sure all interfaces are released */
1166   for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1167     if (dev_handle->claimed_interfaces & (1U << i))
1168       libusb_release_interface (dev_handle, i);
1169
1170   if (0 == dpriv->open_count) {
1171     /* delete the device's async event source */
1172     if (priv->cfSource) {
1173       CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
1174       CFRelease (priv->cfSource);
1175       priv->cfSource = NULL;
1176       CFRelease (libusb_darwin_acfl);
1177     }
1178
1179     if (priv->is_open) {
1180       /* close the device */
1181       kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
1182       if (kresult != kIOReturnSuccess) {
1183         /* Log the fact that we had a problem closing the file, however failing a
1184          * close isn't really an error, so return success anyway */
1185         usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
1186       }
1187     }
1188   }
1189 }
1190
1191 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
1192   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1193
1194   *config = (int) dpriv->active_config;
1195
1196   return LIBUSB_SUCCESS;
1197 }
1198
1199 static enum libusb_error darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
1200   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1201   IOReturn kresult;
1202   int i;
1203
1204   assert(config >= 0 && config <= UINT8_MAX);
1205
1206   /* Setting configuration will invalidate the interface, so we need
1207      to reclaim it. First, dispose of existing interfaces, if any. */
1208   for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1209     if (dev_handle->claimed_interfaces & (1U << i))
1210       darwin_release_interface (dev_handle, i);
1211
1212   kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, (UInt8)config);
1213   if (kresult != kIOReturnSuccess)
1214     return darwin_to_libusb (kresult);
1215
1216   /* Reclaim any interfaces. */
1217   for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1218     if (dev_handle->claimed_interfaces & (1U << i))
1219       darwin_claim_interface (dev_handle, i);
1220
1221   dpriv->active_config = (UInt8)config;
1222
1223   return LIBUSB_SUCCESS;
1224 }
1225
1226 static IOReturn darwin_get_interface (usb_device_t **darwin_device, int ifc, io_service_t *usbInterfacep) {
1227   IOUSBFindInterfaceRequest request;
1228   IOReturn                  kresult;
1229   io_iterator_t             interface_iterator;
1230   UInt8                     bInterfaceNumber;
1231   bool                      ret;
1232
1233   *usbInterfacep = IO_OBJECT_NULL;
1234
1235   /* Setup the Interface Request */
1236   request.bInterfaceClass    = kIOUSBFindInterfaceDontCare;
1237   request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1238   request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1239   request.bAlternateSetting  = kIOUSBFindInterfaceDontCare;
1240
1241   kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1242   if (kresult != kIOReturnSuccess)
1243     return kresult;
1244
1245   while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
1246     /* find the interface number */
1247     ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
1248                                        &bInterfaceNumber);
1249
1250     if (ret && bInterfaceNumber == ifc) {
1251       break;
1252     }
1253
1254     (void) IOObjectRelease (*usbInterfacep);
1255   }
1256
1257   /* done with the interface iterator */
1258   IOObjectRelease(interface_iterator);
1259
1260   return kIOReturnSuccess;
1261 }
1262
1263 static enum libusb_error get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
1264   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1265
1266   /* current interface */
1267   struct darwin_interface *cInterface = &priv->interfaces[iface];
1268
1269   IOReturn kresult;
1270
1271   UInt8 numep, direction, number;
1272   UInt8 dont_care1, dont_care3;
1273   UInt16 dont_care2;
1274   int rc;
1275
1276   usbi_dbg ("building table of endpoints.");
1277
1278   /* retrieve the total number of endpoints on this interface */
1279   kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
1280   if (kresult != kIOReturnSuccess) {
1281     usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1282     return darwin_to_libusb (kresult);
1283   }
1284
1285   /* iterate through pipe references */
1286   for (UInt8 i = 1 ; i <= numep ; i++) {
1287     kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1288                                                             &dont_care2, &dont_care3);
1289
1290     if (kresult != kIOReturnSuccess) {
1291       /* probably a buggy device. try to get the endpoint address from the descriptors */
1292       struct libusb_config_descriptor *config;
1293       const struct libusb_endpoint_descriptor *endpoint_desc;
1294       UInt8 alt_setting;
1295
1296       kresult = (*(cInterface->interface))->GetAlternateSetting (cInterface->interface, &alt_setting);
1297       if (kresult != kIOReturnSuccess) {
1298         usbi_err (HANDLE_CTX (dev_handle), "can't get alternate setting for interface");
1299         return darwin_to_libusb (kresult);
1300       }
1301
1302       rc = libusb_get_active_config_descriptor (dev_handle->dev, &config);
1303       if (LIBUSB_SUCCESS != rc) {
1304         return rc;
1305       }
1306
1307       endpoint_desc = config->interface[iface].altsetting[alt_setting].endpoint + i - 1;
1308
1309       cInterface->endpoint_addrs[i - 1] = endpoint_desc->bEndpointAddress;
1310     } else {
1311       cInterface->endpoint_addrs[i - 1] = (UInt8)(((kUSBIn == direction) << kUSBRqDirnShift) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1312     }
1313
1314     usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, cInterface->endpoint_addrs[i - 1] >> kUSBRqDirnShift,
1315               cInterface->endpoint_addrs[i - 1] & LIBUSB_ENDPOINT_ADDRESS_MASK);
1316   }
1317
1318   cInterface->num_endpoints = numep;
1319
1320   return LIBUSB_SUCCESS;
1321 }
1322
1323 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1324   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1325   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1326   io_service_t          usbInterface = IO_OBJECT_NULL;
1327   IOReturn              kresult;
1328   enum libusb_error     ret;
1329   IOCFPlugInInterface **plugInInterface = NULL;
1330   SInt32                score;
1331
1332   assert(iface >= 0 && iface <= UINT8_MAX);
1333
1334   /* current interface */
1335   struct darwin_interface *cInterface = &priv->interfaces[iface];
1336
1337   kresult = darwin_get_interface (dpriv->device, (uint8_t)iface, &usbInterface);
1338   if (kresult != kIOReturnSuccess)
1339     return darwin_to_libusb (kresult);
1340
1341   /* make sure we have an interface */
1342   if (!usbInterface && dpriv->first_config != 0) {
1343     usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1344
1345     /* set the configuration */
1346     ret = darwin_set_configuration (dev_handle, dpriv->first_config);
1347     if (ret != LIBUSB_SUCCESS) {
1348       usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1349       return ret;
1350     }
1351
1352     kresult = darwin_get_interface (dpriv->device, (uint8_t)iface, &usbInterface);
1353     if (kresult != kIOReturnSuccess) {
1354       usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1355       return darwin_to_libusb (kresult);
1356     }
1357   }
1358
1359   if (!usbInterface) {
1360     usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1361     return LIBUSB_ERROR_NOT_FOUND;
1362   }
1363
1364   /* get an interface to the device's interface */
1365   kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1366                                                kIOCFPlugInInterfaceID, &plugInInterface, &score);
1367
1368   /* ignore release error */
1369   (void)IOObjectRelease (usbInterface);
1370
1371   if (kresult != kIOReturnSuccess) {
1372     usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1373     return darwin_to_libusb (kresult);
1374   }
1375
1376   if (!plugInInterface) {
1377     usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1378     return LIBUSB_ERROR_NOT_FOUND;
1379   }
1380
1381   /* Do the actual claim */
1382   kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1383                                                CFUUIDGetUUIDBytes(InterfaceInterfaceID),
1384                                                (LPVOID)&cInterface->interface);
1385   /* We no longer need the intermediate plug-in */
1386   /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1387   (*plugInInterface)->Release (plugInInterface);
1388   if (kresult != kIOReturnSuccess || !cInterface->interface) {
1389     usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1390     return darwin_to_libusb (kresult);
1391   }
1392
1393   /* claim the interface */
1394   kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1395   if (kresult != kIOReturnSuccess) {
1396     usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1397     return darwin_to_libusb (kresult);
1398   }
1399
1400   /* update list of endpoints */
1401   ret = get_endpoints (dev_handle, iface);
1402   if (ret) {
1403     /* this should not happen */
1404     darwin_release_interface (dev_handle, iface);
1405     usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1406     return ret;
1407   }
1408
1409   cInterface->cfSource = NULL;
1410
1411   /* create async event source */
1412   kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1413   if (kresult != kIOReturnSuccess) {
1414     usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1415
1416     /* can't continue without an async event source */
1417     (void)darwin_release_interface (dev_handle, iface);
1418
1419     return darwin_to_libusb (kresult);
1420   }
1421
1422   /* add the cfSource to the async thread's run loop */
1423   CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1424
1425   usbi_dbg ("interface opened");
1426
1427   return LIBUSB_SUCCESS;
1428 }
1429
1430 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1431   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1432   IOReturn kresult;
1433
1434   /* current interface */
1435   struct darwin_interface *cInterface = &priv->interfaces[iface];
1436
1437   /* Check to see if an interface is open */
1438   if (!cInterface->interface)
1439     return LIBUSB_SUCCESS;
1440
1441   /* clean up endpoint data */
1442   cInterface->num_endpoints = 0;
1443
1444   /* delete the interface's async event source */
1445   if (cInterface->cfSource) {
1446     CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1447     CFRelease (cInterface->cfSource);
1448   }
1449
1450   kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1451   if (kresult != kIOReturnSuccess)
1452     usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1453
1454   kresult = (*(cInterface->interface))->Release(cInterface->interface);
1455   if (kresult != kIOReturnSuccess)
1456     usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1457
1458   cInterface->interface = (usb_interface_t **) IO_OBJECT_NULL;
1459
1460   return darwin_to_libusb (kresult);
1461 }
1462
1463 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1464   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1465   IOReturn kresult;
1466   enum libusb_error ret;
1467
1468   /* current interface */
1469   struct darwin_interface *cInterface = &priv->interfaces[iface];
1470
1471   if (!cInterface->interface)
1472     return LIBUSB_ERROR_NO_DEVICE;
1473
1474   assert(altsetting >= 0 && altsetting <= UINT8_MAX);
1475   kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, (UInt8)altsetting);
1476   if (kresult != kIOReturnSuccess)
1477     darwin_reset_device (dev_handle);
1478
1479   /* update list of endpoints */
1480   ret = get_endpoints (dev_handle, iface);
1481   if (ret) {
1482     /* this should not happen */
1483     darwin_release_interface (dev_handle, iface);
1484     usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1485     return ret;
1486   }
1487
1488   return darwin_to_libusb (kresult);
1489 }
1490
1491 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1492   /* current interface */
1493   struct darwin_interface *cInterface;
1494   IOReturn kresult;
1495   uint8_t pipeRef;
1496
1497   /* determine the interface/endpoint to use */
1498   if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, NULL, &cInterface) != 0) {
1499     usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1500
1501     return LIBUSB_ERROR_NOT_FOUND;
1502   }
1503
1504   /* newer versions of darwin support clearing additional bits on the device's endpoint */
1505   kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1506   if (kresult != kIOReturnSuccess)
1507     usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1508
1509   return darwin_to_libusb (kresult);
1510 }
1511
1512 static int darwin_restore_state (struct libusb_device_handle *dev_handle, int8_t active_config,
1513                                  unsigned long claimed_interfaces) {
1514   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1515   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1516   int open_count = dpriv->open_count;
1517   int ret;
1518
1519   /* clear claimed interfaces temporarily */
1520   dev_handle->claimed_interfaces = 0;
1521
1522   /* close and re-open the device */
1523   priv->is_open = false;
1524   dpriv->open_count = 1;
1525
1526   /* clean up open interfaces */
1527   (void) darwin_close (dev_handle);
1528
1529   /* re-open the device */
1530   ret = darwin_open (dev_handle);
1531   dpriv->open_count = open_count;
1532   if (LIBUSB_SUCCESS != ret) {
1533     /* could not restore configuration */
1534     return LIBUSB_ERROR_NOT_FOUND;
1535   }
1536
1537   if (dpriv->active_config != active_config) {
1538     usbi_dbg ("darwin/restore_state: restoring configuration %d...", active_config);
1539
1540     ret = darwin_set_configuration (dev_handle, active_config);
1541     if (LIBUSB_SUCCESS != ret) {
1542       usbi_dbg ("darwin/restore_state: could not restore configuration");
1543       return LIBUSB_ERROR_NOT_FOUND;
1544     }
1545   }
1546
1547   usbi_dbg ("darwin/restore_state: reclaiming interfaces");
1548
1549   if (claimed_interfaces) {
1550     for (int iface = 0 ; iface < USB_MAXINTERFACES ; ++iface) {
1551       if (!(claimed_interfaces & (1U << iface))) {
1552         continue;
1553       }
1554
1555       usbi_dbg ("darwin/restore_state: re-claiming interface %d", iface);
1556
1557       ret = darwin_claim_interface (dev_handle, iface);
1558       if (LIBUSB_SUCCESS != ret) {
1559         usbi_dbg ("darwin/restore_state: could not claim interface %d", iface);
1560         return LIBUSB_ERROR_NOT_FOUND;
1561       }
1562
1563       dev_handle->claimed_interfaces |= 1U << iface;
1564     }
1565   }
1566
1567   usbi_dbg ("darwin/restore_state: device state restored");
1568
1569   return LIBUSB_SUCCESS;
1570 }
1571
1572 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1573   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1574   unsigned long claimed_interfaces = dev_handle->claimed_interfaces;
1575   int8_t active_config = dpriv->active_config;
1576   IOUSBDeviceDescriptor descriptor;
1577   IOUSBConfigurationDescriptorPtr cached_configuration;
1578   IOUSBConfigurationDescriptor *cached_configurations;
1579   IOReturn kresult;
1580   UInt8 i;
1581
1582   if (dpriv->in_reenumerate) {
1583     /* ack, two (or more) threads are trying to reset the device! abort! */
1584     return LIBUSB_ERROR_NOT_FOUND;
1585   }
1586
1587   dpriv->in_reenumerate = true;
1588
1589   /* store copies of descriptors so they can be compared after the reset */
1590   memcpy (&descriptor, &dpriv->dev_descriptor, sizeof (descriptor));
1591   cached_configurations = alloca (sizeof (*cached_configurations) * descriptor.bNumConfigurations);
1592
1593   for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1594     (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1595     memcpy (cached_configurations + i, cached_configuration, sizeof (cached_configurations[i]));
1596   }
1597
1598   /* from macOS 10.11 ResetDevice no longer does anything so just use USBDeviceReEnumerate */
1599   kresult = (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
1600   if (kresult != kIOReturnSuccess) {
1601     usbi_err (HANDLE_CTX (dev_handle), "USBDeviceReEnumerate: %s", darwin_error_str (kresult));
1602     dpriv->in_reenumerate = false;
1603     return darwin_to_libusb (kresult);
1604   }
1605
1606   usbi_dbg ("darwin/reset_device: waiting for re-enumeration to complete...");
1607
1608   while (dpriv->in_reenumerate) {
1609     struct timespec delay = {.tv_sec = 0, .tv_nsec = 1000};
1610     nanosleep (&delay, NULL);
1611   }
1612
1613   /* compare descriptors */
1614   usbi_dbg ("darwin/reset_device: checking whether descriptors changed");
1615
1616   if (memcmp (&descriptor, &dpriv->dev_descriptor, sizeof (descriptor))) {
1617     /* device descriptor changed. need to return not found. */
1618     usbi_dbg ("darwin/reset_device: device descriptor changed");
1619     return LIBUSB_ERROR_NOT_FOUND;
1620   }
1621
1622   for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1623     (void) (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1624     if (memcmp (cached_configuration, cached_configurations + i, sizeof (cached_configurations[i]))) {
1625       usbi_dbg ("darwin/reset_device: configuration descriptor %d changed", i);
1626       return LIBUSB_ERROR_NOT_FOUND;
1627     }
1628   }
1629
1630   usbi_dbg ("darwin/reset_device: device reset complete. restoring state...");
1631
1632   return darwin_restore_state (dev_handle, active_config, claimed_interfaces);
1633 }
1634
1635 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1636   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1637   io_service_t usbInterface;
1638   CFTypeRef driver;
1639   IOReturn kresult;
1640
1641   assert(interface >= 0 && interface <= UINT8_MAX);
1642   kresult = darwin_get_interface (dpriv->device, (uint8_t)interface, &usbInterface);
1643   if (kresult != kIOReturnSuccess) {
1644     usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1645
1646     return darwin_to_libusb (kresult);
1647   }
1648
1649   driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1650   IOObjectRelease (usbInterface);
1651
1652   if (driver) {
1653     CFRelease (driver);
1654
1655     return 1;
1656   }
1657
1658   /* no driver */
1659   return 0;
1660 }
1661
1662 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1663 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1664   UNUSED(dev_handle);
1665   UNUSED(interface);
1666   return LIBUSB_ERROR_NOT_SUPPORTED;
1667 }
1668
1669 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1670   UNUSED(dev_handle);
1671   UNUSED(interface);
1672   return LIBUSB_ERROR_NOT_SUPPORTED;
1673 }
1674
1675 static void darwin_destroy_device(struct libusb_device *dev) {
1676   struct darwin_device_priv *dpriv = (struct darwin_device_priv *) dev->os_priv;
1677
1678   if (dpriv->dev) {
1679     /* need to hold the lock in case this is the last reference to the device */
1680     usbi_mutex_lock(&darwin_cached_devices_lock);
1681     darwin_deref_cached_device (dpriv->dev);
1682     dpriv->dev = NULL;
1683     usbi_mutex_unlock(&darwin_cached_devices_lock);
1684   }
1685 }
1686
1687 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1688   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1689
1690   IOReturn               ret;
1691   uint8_t                transferType;
1692   /* None of the values below are used in libusbx for bulk transfers */
1693   uint8_t                direction, number, interval, pipeRef;
1694   uint16_t               maxPacketSize;
1695
1696   struct darwin_interface *cInterface;
1697
1698   if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1699     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1700
1701     return LIBUSB_ERROR_NOT_FOUND;
1702   }
1703
1704   ret = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1705                                                        &transferType, &maxPacketSize, &interval);
1706
1707   if (ret) {
1708     usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1709               darwin_error_str(ret), ret);
1710     return darwin_to_libusb (ret);
1711   }
1712
1713   if (0 != (transfer->length % maxPacketSize)) {
1714     /* do not need a zero packet */
1715     transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1716   }
1717
1718   /* submit the request */
1719   /* timeouts are unavailable on interrupt endpoints */
1720   if (transferType == kUSBInterrupt) {
1721     if (IS_XFERIN(transfer))
1722       ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1723                                                       (UInt32)transfer->length, darwin_async_io_callback, itransfer);
1724     else
1725       ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1726                                                        (UInt32)transfer->length, darwin_async_io_callback, itransfer);
1727   } else {
1728     itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1729
1730     if (IS_XFERIN(transfer))
1731       ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1732                                                         (UInt32)transfer->length, transfer->timeout, transfer->timeout,
1733                                                         darwin_async_io_callback, itransfer);
1734     else
1735       ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1736                                                          (UInt32)transfer->length, transfer->timeout, transfer->timeout,
1737                                                          darwin_async_io_callback, itransfer);
1738   }
1739
1740   if (ret)
1741     usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1742                darwin_error_str(ret), ret);
1743
1744   return darwin_to_libusb (ret);
1745 }
1746
1747 #if InterfaceVersion >= 550
1748 static int submit_stream_transfer(struct usbi_transfer *itransfer) {
1749   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1750   struct darwin_interface *cInterface;
1751   uint8_t pipeRef;
1752   IOReturn ret;
1753
1754   if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1755     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1756
1757     return LIBUSB_ERROR_NOT_FOUND;
1758   }
1759
1760   itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1761
1762   if (IS_XFERIN(transfer))
1763     ret = (*(cInterface->interface))->ReadStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1764                                                              transfer->buffer, (UInt32)transfer->length, transfer->timeout,
1765                                                              transfer->timeout, darwin_async_io_callback, itransfer);
1766   else
1767     ret = (*(cInterface->interface))->WriteStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1768                                                               transfer->buffer, (UInt32)transfer->length, transfer->timeout,
1769                                                               transfer->timeout, darwin_async_io_callback, itransfer);
1770
1771   if (ret)
1772     usbi_err (TRANSFER_CTX (transfer), "bulk stream transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1773                darwin_error_str(ret), ret);
1774
1775   return darwin_to_libusb (ret);
1776 }
1777 #endif
1778
1779 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1780   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1781   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1782
1783   IOReturn kresult;
1784   uint8_t direction, number, interval, pipeRef, transferType;
1785   uint16_t maxPacketSize;
1786   UInt64 frame;
1787   AbsoluteTime atTime;
1788   int i;
1789
1790   struct darwin_interface *cInterface;
1791
1792   /* construct an array of IOUSBIsocFrames, reuse the old one if the sizes are the same */
1793   if (tpriv->num_iso_packets != transfer->num_iso_packets) {
1794     free(tpriv->isoc_framelist);
1795     tpriv->isoc_framelist = NULL;
1796   }
1797
1798   if (!tpriv->isoc_framelist) {
1799     tpriv->num_iso_packets = transfer->num_iso_packets;
1800     tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc ((size_t)transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1801     if (!tpriv->isoc_framelist)
1802       return LIBUSB_ERROR_NO_MEM;
1803   }
1804
1805   /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1806   for (i = 0 ; i < transfer->num_iso_packets ; i++) {
1807     unsigned int length = transfer->iso_packet_desc[i].length;
1808     assert(length <= UINT16_MAX);
1809     tpriv->isoc_framelist[i].frReqCount = (UInt16)length;
1810   }
1811
1812   /* determine the interface/endpoint to use */
1813   if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1814     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1815
1816     return LIBUSB_ERROR_NOT_FOUND;
1817   }
1818
1819   /* determine the properties of this endpoint and the speed of the device */
1820   (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1821                                                  &transferType, &maxPacketSize, &interval);
1822
1823   /* Last but not least we need the bus frame number */
1824   kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1825   if (kresult != kIOReturnSuccess) {
1826     usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1827     free(tpriv->isoc_framelist);
1828     tpriv->isoc_framelist = NULL;
1829
1830     return darwin_to_libusb (kresult);
1831   }
1832
1833   (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1834                                                  &transferType, &maxPacketSize, &interval);
1835
1836   /* schedule for a frame a little in the future */
1837   frame += 4;
1838
1839   if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1840     frame = cInterface->frames[transfer->endpoint];
1841
1842   /* submit the request */
1843   if (IS_XFERIN(transfer))
1844     kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1845                                                              (UInt32)transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1846                                                              itransfer);
1847   else
1848     kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1849                                                               (UInt32)transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1850                                                               itransfer);
1851
1852   if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
1853     /* Full speed */
1854     cInterface->frames[transfer->endpoint] = frame + (UInt32)transfer->num_iso_packets * (1U << (interval - 1));
1855   else
1856     /* High/super speed */
1857     cInterface->frames[transfer->endpoint] = frame + (UInt32)transfer->num_iso_packets * (1U << (interval - 1)) / 8;
1858
1859   if (kresult != kIOReturnSuccess) {
1860     usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1861                darwin_error_str(kresult));
1862     free (tpriv->isoc_framelist);
1863     tpriv->isoc_framelist = NULL;
1864   }
1865
1866   return darwin_to_libusb (kresult);
1867 }
1868
1869 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1870   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1871   struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1872   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1873   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1874
1875   IOReturn               kresult;
1876
1877   memset(&tpriv->req, 0, sizeof(tpriv->req));
1878
1879   /* IOUSBDeviceInterface expects the request in cpu endianness */
1880   tpriv->req.bmRequestType     = setup->bmRequestType;
1881   tpriv->req.bRequest          = setup->bRequest;
1882   /* these values should be in bus order from libusb_fill_control_setup */
1883   tpriv->req.wValue            = OSSwapLittleToHostInt16 (setup->wValue);
1884   tpriv->req.wIndex            = OSSwapLittleToHostInt16 (setup->wIndex);
1885   tpriv->req.wLength           = OSSwapLittleToHostInt16 (setup->wLength);
1886   /* data is stored after the libusb control block */
1887   tpriv->req.pData             = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1888   tpriv->req.completionTimeout = transfer->timeout;
1889   tpriv->req.noDataTimeout     = transfer->timeout;
1890
1891   itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1892
1893   /* all transfers in libusb-1.0 are async */
1894
1895   if (transfer->endpoint) {
1896     struct darwin_interface *cInterface;
1897     uint8_t                 pipeRef;
1898
1899     if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1900       usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1901
1902       return LIBUSB_ERROR_NOT_FOUND;
1903     }
1904
1905     kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1906   } else
1907     /* control request on endpoint 0 */
1908     kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1909
1910   if (kresult != kIOReturnSuccess)
1911     usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1912
1913   return darwin_to_libusb (kresult);
1914 }
1915
1916 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1917   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1918
1919   switch (transfer->type) {
1920   case LIBUSB_TRANSFER_TYPE_CONTROL:
1921     return submit_control_transfer(itransfer);
1922   case LIBUSB_TRANSFER_TYPE_BULK:
1923   case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1924     return submit_bulk_transfer(itransfer);
1925   case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1926     return submit_iso_transfer(itransfer);
1927   case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1928 #if InterfaceVersion >= 550
1929     return submit_stream_transfer(itransfer);
1930 #else
1931     usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version does not support bulk stream transfers");
1932     return LIBUSB_ERROR_NOT_SUPPORTED;
1933 #endif
1934   default:
1935     usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1936     return LIBUSB_ERROR_INVALID_PARAM;
1937   }
1938 }
1939
1940 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1941   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1942   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1943   IOReturn kresult;
1944
1945   usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
1946
1947   if (!dpriv->device)
1948     return LIBUSB_ERROR_NO_DEVICE;
1949
1950   kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1951
1952   return darwin_to_libusb (kresult);
1953 }
1954
1955 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1956   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1957   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1958   struct darwin_interface *cInterface;
1959   uint8_t pipeRef, iface;
1960   IOReturn kresult;
1961
1962   if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface, &cInterface) != 0) {
1963     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1964
1965     return LIBUSB_ERROR_NOT_FOUND;
1966   }
1967
1968   if (!dpriv->device)
1969     return LIBUSB_ERROR_NO_DEVICE;
1970
1971   usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
1972
1973   /* abort transactions */
1974 #if InterfaceVersion >= 550
1975   if (LIBUSB_TRANSFER_TYPE_BULK_STREAM == transfer->type)
1976     (*(cInterface->interface))->AbortStreamsPipe (cInterface->interface, pipeRef, itransfer->stream_id);
1977   else
1978 #endif
1979     (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1980
1981   usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
1982
1983   /* newer versions of darwin support clearing additional bits on the device's endpoint */
1984   kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1985
1986   return darwin_to_libusb (kresult);
1987 }
1988
1989 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1990   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1991
1992   switch (transfer->type) {
1993   case LIBUSB_TRANSFER_TYPE_CONTROL:
1994     return cancel_control_transfer(itransfer);
1995   case LIBUSB_TRANSFER_TYPE_BULK:
1996   case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1997   case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1998     return darwin_abort_transfers (itransfer);
1999   default:
2000     usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
2001     return LIBUSB_ERROR_INVALID_PARAM;
2002   }
2003 }
2004
2005 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
2006   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2007   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2008
2009   if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
2010     free (tpriv->isoc_framelist);
2011     tpriv->isoc_framelist = NULL;
2012   }
2013 }
2014
2015 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
2016   struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
2017   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2018   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2019
2020   usbi_dbg ("an async io operation has completed");
2021
2022   /* if requested write a zero packet */
2023   if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
2024     struct darwin_interface *cInterface;
2025     uint8_t pipeRef;
2026
2027     (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface);
2028
2029     (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
2030   }
2031
2032   tpriv->result = result;
2033   tpriv->size = (UInt32) (uintptr_t) arg0;
2034
2035   /* signal the core that this transfer is complete */
2036   usbi_signal_transfer_completion(itransfer);
2037 }
2038
2039 static enum libusb_transfer_status darwin_transfer_status (struct usbi_transfer *itransfer, IOReturn result) {
2040   if (itransfer->timeout_flags & USBI_TRANSFER_TIMED_OUT)
2041     result = kIOUSBTransactionTimeout;
2042
2043   switch (result) {
2044   case kIOReturnUnderrun:
2045   case kIOReturnSuccess:
2046     return LIBUSB_TRANSFER_COMPLETED;
2047   case kIOReturnAborted:
2048     return LIBUSB_TRANSFER_CANCELLED;
2049   case kIOUSBPipeStalled:
2050     usbi_dbg ("transfer error: pipe is stalled");
2051     return LIBUSB_TRANSFER_STALL;
2052   case kIOReturnOverrun:
2053     usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
2054     return LIBUSB_TRANSFER_OVERFLOW;
2055   case kIOUSBTransactionTimeout:
2056     usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
2057     itransfer->timeout_flags |= USBI_TRANSFER_TIMED_OUT;
2058     return LIBUSB_TRANSFER_TIMED_OUT;
2059   default:
2060     usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
2061     return LIBUSB_TRANSFER_ERROR;
2062   }
2063 }
2064
2065 static int darwin_handle_transfer_completion (struct usbi_transfer *itransfer) {
2066   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2067   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2068   bool isIsoc      = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
2069   bool isBulk      = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
2070   bool isControl   = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
2071   bool isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
2072   int i;
2073
2074   if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
2075     usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
2076     return LIBUSB_ERROR_INVALID_PARAM;
2077   }
2078
2079   usbi_dbg ("handling %s completion with kernel status %d",
2080              isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", tpriv->result);
2081
2082   if (kIOReturnSuccess == tpriv->result || kIOReturnUnderrun == tpriv->result) {
2083     if (isIsoc && tpriv->isoc_framelist) {
2084       /* copy isochronous results back */
2085
2086       for (i = 0; i < transfer->num_iso_packets ; i++) {
2087         struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
2088         lib_desc->status = darwin_transfer_status (itransfer, tpriv->isoc_framelist[i].frStatus);
2089         lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
2090       }
2091     } else if (!isIsoc)
2092       itransfer->transferred += tpriv->size;
2093   }
2094
2095   /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
2096   return usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, tpriv->result));
2097 }
2098
2099 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
2100 #if !OSX_USE_CLOCK_GETTIME
2101   mach_timespec_t sys_time;
2102   clock_serv_t clock_ref;
2103
2104   switch (clk_id) {
2105   case USBI_CLOCK_REALTIME:
2106     /* CLOCK_REALTIME represents time since the epoch */
2107     clock_ref = clock_realtime;
2108     break;
2109   case USBI_CLOCK_MONOTONIC:
2110     /* use system boot time as reference for the monotonic clock */
2111     clock_ref = clock_monotonic;
2112     break;
2113   default:
2114     return LIBUSB_ERROR_INVALID_PARAM;
2115   }
2116
2117   clock_get_time (clock_ref, &sys_time);
2118
2119   tp->tv_sec  = sys_time.tv_sec;
2120   tp->tv_nsec = sys_time.tv_nsec;
2121
2122   return LIBUSB_SUCCESS;
2123 #else
2124   switch (clk_id) {
2125   case USBI_CLOCK_MONOTONIC:
2126     return clock_gettime(CLOCK_MONOTONIC, tp);
2127   case USBI_CLOCK_REALTIME:
2128     return clock_gettime(CLOCK_REALTIME, tp);
2129   default:
2130     return LIBUSB_ERROR_INVALID_PARAM;
2131   }
2132 #endif
2133 }
2134
2135 #if InterfaceVersion >= 550
2136 static int darwin_alloc_streams (struct libusb_device_handle *dev_handle, uint32_t num_streams, unsigned char *endpoints,
2137                                  int num_endpoints) {
2138   struct darwin_interface *cInterface;
2139   UInt32 supportsStreams;
2140   uint8_t pipeRef;
2141   int rc, i;
2142
2143   /* find the mimimum number of supported streams on the endpoint list */
2144   for (i = 0 ; i < num_endpoints ; ++i) {
2145     if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface))) {
2146       return rc;
2147     }
2148
2149     (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2150     if (num_streams > supportsStreams)
2151       num_streams = supportsStreams;
2152   }
2153
2154   /* it is an error if any endpoint in endpoints does not support streams */
2155   if (0 == num_streams)
2156     return LIBUSB_ERROR_INVALID_PARAM;
2157
2158   /* create the streams */
2159   for (i = 0 ; i < num_endpoints ; ++i) {
2160     (void) ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
2161
2162     rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, num_streams);
2163     if (kIOReturnSuccess != rc)
2164       return darwin_to_libusb(rc);
2165   }
2166
2167   assert(num_streams <= INT_MAX);
2168   return (int)num_streams;
2169 }
2170
2171 static int darwin_free_streams (struct libusb_device_handle *dev_handle, unsigned char *endpoints, int num_endpoints) {
2172   struct darwin_interface *cInterface;
2173   UInt32 supportsStreams;
2174   uint8_t pipeRef;
2175   int rc;
2176
2177   for (int i = 0 ; i < num_endpoints ; ++i) {
2178     if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface)))
2179       return rc;
2180
2181     (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2182     if (0 == supportsStreams)
2183       return LIBUSB_ERROR_INVALID_PARAM;
2184
2185     rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, 0);
2186     if (kIOReturnSuccess != rc)
2187       return darwin_to_libusb(rc);
2188   }
2189
2190   return LIBUSB_SUCCESS;
2191 }
2192 #endif
2193
2194 const struct usbi_os_backend usbi_backend = {
2195         .name = "Darwin",
2196         .caps = 0,
2197         .init = darwin_init,
2198         .exit = darwin_exit,
2199         .get_device_list = NULL, /* not needed */
2200         .get_device_descriptor = darwin_get_device_descriptor,
2201         .get_active_config_descriptor = darwin_get_active_config_descriptor,
2202         .get_config_descriptor = darwin_get_config_descriptor,
2203         .hotplug_poll = darwin_hotplug_poll,
2204
2205         .open = darwin_open,
2206         .close = darwin_close,
2207         .get_configuration = darwin_get_configuration,
2208         .set_configuration = darwin_set_configuration,
2209         .claim_interface = darwin_claim_interface,
2210         .release_interface = darwin_release_interface,
2211
2212         .set_interface_altsetting = darwin_set_interface_altsetting,
2213         .clear_halt = darwin_clear_halt,
2214         .reset_device = darwin_reset_device,
2215
2216 #if InterfaceVersion >= 550
2217         .alloc_streams = darwin_alloc_streams,
2218         .free_streams = darwin_free_streams,
2219 #endif
2220
2221         .kernel_driver_active = darwin_kernel_driver_active,
2222         .detach_kernel_driver = darwin_detach_kernel_driver,
2223         .attach_kernel_driver = darwin_attach_kernel_driver,
2224
2225         .destroy_device = darwin_destroy_device,
2226
2227         .submit_transfer = darwin_submit_transfer,
2228         .cancel_transfer = darwin_cancel_transfer,
2229         .clear_transfer_priv = darwin_clear_transfer_priv,
2230
2231         .handle_transfer_completion = darwin_handle_transfer_completion,
2232
2233         .clock_gettime = darwin_clock_gettime,
2234
2235         .device_priv_size = sizeof(struct darwin_device_priv),
2236         .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
2237         .transfer_priv_size = sizeof(struct darwin_transfer_priv),
2238 };