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