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