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