core: Refactor initialization and how the default context is handled
[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 int init_count = 0;
56
57 /* async event thread */
58 static pthread_mutex_t libusb_darwin_at_mutex = PTHREAD_MUTEX_INITIALIZER;
59 static pthread_cond_t  libusb_darwin_at_cond = PTHREAD_COND_INITIALIZER;
60
61 #if !defined(HAVE_CLOCK_GETTIME)
62 static clock_serv_t clock_realtime;
63 static clock_serv_t clock_monotonic;
64 #endif
65
66 #define LIBUSB_DARWIN_STARTUP_FAILURE ((CFRunLoopRef) -1)
67
68 static CFRunLoopRef libusb_darwin_acfl = NULL; /* event cf loop */
69 static CFRunLoopSourceRef libusb_darwin_acfls = NULL; /* shutdown signal for event cf loop */
70
71 static usbi_mutex_t darwin_cached_devices_lock = PTHREAD_MUTEX_INITIALIZER;
72 static struct list_head darwin_cached_devices;
73 static const char *darwin_device_class = "IOUSBDevice";
74
75 #define DARWIN_CACHED_DEVICE(a) (((struct darwin_device_priv *)usbi_get_device_priv((a)))->dev)
76
77 /* async event thread */
78 static pthread_t libusb_darwin_at;
79
80 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, void *buffer, size_t len);
81 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, uint8_t iface);
82 static int darwin_release_interface(struct libusb_device_handle *dev_handle, uint8_t iface);
83 static int darwin_reenumerate_device(struct libusb_device_handle *dev_handle, bool capture);
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     IOObjectRelease (cached_dev->service);
175     free (cached_dev);
176   }
177 }
178
179 static void darwin_ref_cached_device(struct darwin_cached_device *cached_dev) {
180   cached_dev->refcount++;
181 }
182
183 static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp, struct darwin_interface **interface_out) {
184   struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
185
186   /* current interface */
187   struct darwin_interface *cInterface;
188
189   uint8_t i, iface;
190
191   usbi_dbg ("converting ep address 0x%02x to pipeRef and interface", ep);
192
193   for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
194     cInterface = &priv->interfaces[iface];
195
196     if (dev_handle->claimed_interfaces & (1U << iface)) {
197       for (i = 0 ; i < cInterface->num_endpoints ; i++) {
198         if (cInterface->endpoint_addrs[i] == ep) {
199           *pipep = i + 1;
200
201           if (ifcp)
202             *ifcp = iface;
203
204           if (interface_out)
205             *interface_out = cInterface;
206
207           usbi_dbg ("pipe %d on interface %d matches", *pipep, iface);
208           return LIBUSB_SUCCESS;
209         }
210       }
211     }
212   }
213
214   /* No pipe found with the correct endpoint address */
215   usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
216
217   return LIBUSB_ERROR_NOT_FOUND;
218 }
219
220 static IOReturn usb_setup_device_iterator (io_iterator_t *deviceIterator, UInt32 location) {
221   CFMutableDictionaryRef matchingDict = IOServiceMatching(darwin_device_class);
222
223   if (!matchingDict)
224     return kIOReturnError;
225
226   if (location) {
227     CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
228                                                                          &kCFTypeDictionaryKeyCallBacks,
229                                                                          &kCFTypeDictionaryValueCallBacks);
230
231     /* there are no unsigned CFNumber types so treat the value as signed. the OS seems to do this
232          internally (CFNumberType of locationID is kCFNumberSInt32Type) */
233     CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberSInt32Type, &location);
234
235     if (propertyMatchDict && locationCF) {
236       CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
237       CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
238     }
239     /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
240
241     /* release our references as per the Create Rule */
242     if (propertyMatchDict)
243       CFRelease (propertyMatchDict);
244     if (locationCF)
245       CFRelease (locationCF);
246   }
247
248   return IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, deviceIterator);
249 }
250
251 /* Returns 1 on success, 0 on failure. */
252 static bool get_ioregistry_value_number (io_service_t service, CFStringRef property, CFNumberType type, void *p) {
253   CFTypeRef cfNumber = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
254   Boolean success = 0;
255
256   if (cfNumber) {
257     if (CFGetTypeID(cfNumber) == CFNumberGetTypeID()) {
258       success = CFNumberGetValue(cfNumber, type, p);
259     }
260
261     CFRelease (cfNumber);
262   }
263
264   return (success != 0);
265 }
266
267 /* Returns 1 on success, 0 on failure. */
268 static bool get_ioregistry_value_data (io_service_t service, CFStringRef property, ssize_t size, void *p) {
269   CFTypeRef cfData = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
270   bool success = false;
271
272   if (cfData) {
273     if (CFGetTypeID (cfData) == CFDataGetTypeID ()) {
274       CFIndex length = CFDataGetLength (cfData);
275       if (length < size) {
276         size = length;
277       }
278
279       CFDataGetBytes (cfData, CFRangeMake(0, size), p);
280       success = true;
281     }
282
283     CFRelease (cfData);
284   }
285
286   return success;
287 }
288
289 static usb_device_t **darwin_device_from_service (io_service_t service)
290 {
291   io_cf_plugin_ref_t *plugInInterface = NULL;
292   usb_device_t **device;
293   IOReturn kresult;
294   SInt32 score;
295   const int max_retries = 5;
296
297   /* The IOCreatePlugInInterfaceForService function might consistently return
298      an "out of resources" error with certain USB devices the first time we run 
299      it. The reason is still unclear, but retrying fixes the problem */
300   for (int count = 0; count < max_retries; count++) {
301     kresult = IOCreatePlugInInterfaceForService(service, kIOUSBDeviceUserClientTypeID,
302                                                 kIOCFPlugInInterfaceID, &plugInInterface,
303                                                 &score);
304     if (kIOReturnSuccess == kresult && plugInInterface) {
305       break;
306     }
307
308     usbi_dbg ("set up plugin for service retry: %s", darwin_error_str (kresult));
309
310     /* sleep for a little while before trying again */
311     nanosleep(&(struct timespec){.tv_sec = 0, .tv_nsec = 1000}, NULL);
312   }
313
314   if (kIOReturnSuccess != kresult || !plugInInterface) {
315     usbi_dbg ("could not set up plugin for service: %s", darwin_error_str (kresult));
316     return NULL;
317   }
318
319   (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
320                                            (LPVOID)&device);
321   /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
322   (*plugInInterface)->Release (plugInInterface);
323
324   return device;
325 }
326
327 static void darwin_devices_attached (void *ptr, io_iterator_t add_devices) {
328   UNUSED(ptr);
329   struct darwin_cached_device *cached_device;
330   UInt64 old_session_id;
331   struct libusb_context *ctx;
332   io_service_t service;
333   int ret;
334
335   usbi_mutex_lock(&active_contexts_lock);
336
337   while ((service = IOIteratorNext(add_devices))) {
338     ret = darwin_get_cached_device (service, &cached_device, &old_session_id);
339     if (ret < 0 || !cached_device->can_enumerate) {
340       continue;
341     }
342
343     /* add this device to each active context's device list */
344     for_each_context(ctx) {
345       process_new_device (ctx, cached_device, old_session_id);
346     }
347
348     if (cached_device->in_reenumerate) {
349       usbi_dbg ("cached device in reset state. reset complete...");
350       cached_device->in_reenumerate = false;
351     }
352
353     IOObjectRelease(service);
354   }
355
356   usbi_mutex_unlock(&active_contexts_lock);
357 }
358
359 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
360   UNUSED(ptr);
361   struct libusb_device *dev = NULL;
362   struct libusb_context *ctx;
363   struct darwin_cached_device *old_device;
364
365   io_service_t device;
366   UInt64 session;
367   int ret;
368
369   usbi_mutex_lock(&active_contexts_lock);
370
371   while ((device = IOIteratorNext (rem_devices)) != 0) {
372     bool is_reenumerating = false;
373
374     /* get the location from the i/o registry */
375     ret = get_ioregistry_value_number (device, CFSTR("sessionID"), kCFNumberSInt64Type, &session);
376     IOObjectRelease (device);
377     if (!ret)
378       continue;
379
380     /* we need to match darwin_ref_cached_device call made in darwin_get_cached_device function
381        otherwise no cached device will ever get freed */
382     usbi_mutex_lock(&darwin_cached_devices_lock);
383     list_for_each_entry(old_device, &darwin_cached_devices, list, struct darwin_cached_device) {
384       if (old_device->session == session) {
385         if (old_device->in_reenumerate) {
386           /* device is re-enumerating. do not dereference the device at this time. libusb_reset_device()
387            * will deref if needed. */
388           usbi_dbg ("detected device detached due to re-enumeration");
389
390           /* the device object is no longer usable so go ahead and release it */
391           if (old_device->device) {
392             (*(old_device->device))->Release(old_device->device);
393             old_device->device = NULL;
394           }
395
396           is_reenumerating = true;
397         } else {
398           darwin_deref_cached_device (old_device);
399         }
400
401         break;
402       }
403     }
404
405     usbi_mutex_unlock(&darwin_cached_devices_lock);
406     if (is_reenumerating) {
407       continue;
408     }
409
410     for_each_context(ctx) {
411       usbi_dbg ("notifying context %p of device disconnect", ctx);
412
413       dev = usbi_get_device_by_session_id(ctx, (unsigned long) session);
414       if (dev) {
415         /* signal the core that this device has been disconnected. the core will tear down this device
416            when the reference count reaches 0 */
417         usbi_disconnect_device(dev);
418         libusb_unref_device(dev);
419       }
420     }
421   }
422
423   usbi_mutex_unlock(&active_contexts_lock);
424 }
425
426 static void darwin_hotplug_poll (void)
427 {
428   /* not sure if 1 ms will be too long/short but it should work ok */
429   mach_timespec_t timeout = {.tv_sec = 0, .tv_nsec = 1000000ul};
430
431   /* since a kernel thread may notify the IOIterators used for
432    * hotplug notification we can't just clear the iterators.
433    * instead just wait until all IOService providers are quiet */
434   (void) IOKitWaitQuiet (kIOMasterPortDefault, &timeout);
435 }
436
437 static void darwin_clear_iterator (io_iterator_t iter) {
438   io_service_t device;
439
440   while ((device = IOIteratorNext (iter)) != 0)
441     IOObjectRelease (device);
442 }
443
444 static void darwin_fail_startup(void) {
445   pthread_mutex_lock (&libusb_darwin_at_mutex);
446   libusb_darwin_acfl = LIBUSB_DARWIN_STARTUP_FAILURE;
447   pthread_cond_signal (&libusb_darwin_at_cond);
448   pthread_mutex_unlock (&libusb_darwin_at_mutex);
449   pthread_exit (NULL);
450 }
451
452 static void *darwin_event_thread_main (void *arg0) {
453   IOReturn kresult;
454   struct libusb_context *ctx = (struct libusb_context *)arg0;
455   CFRunLoopRef runloop;
456   CFRunLoopSourceRef libusb_shutdown_cfsource;
457   CFRunLoopSourceContext libusb_shutdown_cfsourcectx;
458
459 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
460   /* Set this thread's name, so it can be seen in the debugger
461      and crash reports. */
462   pthread_setname_np ("org.libusb.device-hotplug");
463 #endif
464
465 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
466   /* Tell the Objective-C garbage collector about this thread.
467      This is required because, unlike NSThreads, pthreads are
468      not automatically registered. Although we don't use
469      Objective-C, we use CoreFoundation, which does.
470      Garbage collection support was entirely removed in 10.12,
471      so don't bother there. */
472   objc_registerThreadWithCollector();
473 #endif
474
475   /* hotplug (device arrival/removal) sources */
476   CFRunLoopSourceRef     libusb_notification_cfsource;
477   io_notification_port_t libusb_notification_port;
478   io_iterator_t          libusb_rem_device_iterator;
479   io_iterator_t          libusb_add_device_iterator;
480
481   usbi_dbg ("creating hotplug event source");
482
483   runloop = CFRunLoopGetCurrent ();
484   CFRetain (runloop);
485
486   /* add the shutdown cfsource to the run loop */
487   memset(&libusb_shutdown_cfsourcectx, 0, sizeof(libusb_shutdown_cfsourcectx));
488   libusb_shutdown_cfsourcectx.info = runloop;
489   libusb_shutdown_cfsourcectx.perform = (void (*)(void *))CFRunLoopStop;
490   libusb_shutdown_cfsource = CFRunLoopSourceCreate(NULL, 0, &libusb_shutdown_cfsourcectx);
491   CFRunLoopAddSource(runloop, libusb_shutdown_cfsource, kCFRunLoopDefaultMode);
492
493   /* add the notification port to the run loop */
494   libusb_notification_port     = IONotificationPortCreate (kIOMasterPortDefault);
495   libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
496   CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
497
498   /* create notifications for removed devices */
499   kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
500                                               IOServiceMatching(darwin_device_class),
501                                               darwin_devices_detached,
502                                               ctx, &libusb_rem_device_iterator);
503
504   if (kresult != kIOReturnSuccess) {
505     usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
506     CFRelease (libusb_shutdown_cfsource);
507     CFRelease (runloop);
508     darwin_fail_startup ();
509   }
510
511   /* create notifications for attached devices */
512   kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification,
513                                               IOServiceMatching(darwin_device_class),
514                                               darwin_devices_attached,
515                                               ctx, &libusb_add_device_iterator);
516
517   if (kresult != kIOReturnSuccess) {
518     usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
519     CFRelease (libusb_shutdown_cfsource);
520     CFRelease (runloop);
521     darwin_fail_startup ();
522   }
523
524   /* arm notifiers */
525   darwin_clear_iterator (libusb_rem_device_iterator);
526   darwin_clear_iterator (libusb_add_device_iterator);
527
528   usbi_dbg ("darwin event thread ready to receive events");
529
530   /* signal the main thread that the hotplug runloop has been created. */
531   pthread_mutex_lock (&libusb_darwin_at_mutex);
532   libusb_darwin_acfl = runloop;
533   libusb_darwin_acfls = libusb_shutdown_cfsource;
534   pthread_cond_signal (&libusb_darwin_at_cond);
535   pthread_mutex_unlock (&libusb_darwin_at_mutex);
536
537   /* run the runloop */
538   CFRunLoopRun();
539
540   usbi_dbg ("darwin event thread exiting");
541
542   /* signal the main thread that the hotplug runloop has finished. */
543   pthread_mutex_lock (&libusb_darwin_at_mutex);
544   libusb_darwin_acfls = NULL;
545   libusb_darwin_acfl = NULL;
546   pthread_cond_signal (&libusb_darwin_at_cond);
547   pthread_mutex_unlock (&libusb_darwin_at_mutex);
548
549   /* remove the notification cfsource */
550   CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
551
552   /* remove the shutdown cfsource */
553   CFRunLoopRemoveSource(runloop, libusb_shutdown_cfsource, kCFRunLoopDefaultMode);
554
555   /* delete notification port */
556   IONotificationPortDestroy (libusb_notification_port);
557
558   /* delete iterators */
559   IOObjectRelease (libusb_rem_device_iterator);
560   IOObjectRelease (libusb_add_device_iterator);
561
562   CFRelease (libusb_shutdown_cfsource);
563   CFRelease (runloop);
564
565   pthread_exit (NULL);
566 }
567
568 /* cleanup function to destroy cached devices */
569 static void darwin_cleanup_devices(void) {
570   struct darwin_cached_device *dev, *next;
571
572   list_for_each_entry_safe(dev, next, &darwin_cached_devices, list, struct darwin_cached_device) {
573     darwin_deref_cached_device(dev);
574   }
575
576   darwin_cached_devices.prev = darwin_cached_devices.next = NULL;
577 }
578
579 static int darwin_init(struct libusb_context *ctx) {
580   bool first_init;
581   int rc;
582
583   first_init = (1 == ++init_count);
584
585   do {
586     if (first_init) {
587       assert (NULL == darwin_cached_devices.next);
588       list_init (&darwin_cached_devices);
589
590 #if !defined(HAVE_CLOCK_GETTIME)
591       /* create the clocks that will be used if clock_gettime() is not available */
592       host_name_port_t host_self;
593
594       host_self = mach_host_self();
595       host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
596       host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
597       mach_port_deallocate(mach_task_self(), host_self);
598 #endif
599     }
600
601     rc = darwin_scan_devices (ctx);
602     if (LIBUSB_SUCCESS != rc)
603       break;
604
605     if (first_init) {
606       rc = pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, ctx);
607       if (0 != rc) {
608         usbi_err (ctx, "could not create event thread, error %d", rc);
609         rc = LIBUSB_ERROR_OTHER;
610         break;
611       }
612
613       pthread_mutex_lock (&libusb_darwin_at_mutex);
614       while (!libusb_darwin_acfl)
615         pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
616       if (libusb_darwin_acfl == LIBUSB_DARWIN_STARTUP_FAILURE) {
617         libusb_darwin_acfl = NULL;
618         rc = LIBUSB_ERROR_OTHER;
619       }
620       pthread_mutex_unlock (&libusb_darwin_at_mutex);
621
622       if (0 != rc)
623         pthread_join (libusb_darwin_at, NULL);
624     }
625   } while (0);
626
627   if (LIBUSB_SUCCESS != rc) {
628     if (first_init) {
629       darwin_cleanup_devices ();
630 #if !defined(HAVE_CLOCK_GETTIME)
631       mach_port_deallocate(mach_task_self(), clock_realtime);
632       mach_port_deallocate(mach_task_self(), clock_monotonic);
633 #endif
634     }
635     --init_count;
636   }
637
638   return rc;
639 }
640
641 static void darwin_exit (struct libusb_context *ctx) {
642   UNUSED(ctx);
643
644   if (0 == --init_count) {
645     /* stop the event runloop and wait for the thread to terminate. */
646     pthread_mutex_lock (&libusb_darwin_at_mutex);
647     CFRunLoopSourceSignal (libusb_darwin_acfls);
648     CFRunLoopWakeUp (libusb_darwin_acfl);
649     while (libusb_darwin_acfl)
650       pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
651     pthread_mutex_unlock (&libusb_darwin_at_mutex);
652     pthread_join (libusb_darwin_at, NULL);
653
654     darwin_cleanup_devices ();
655
656 #if !defined(HAVE_CLOCK_GETTIME)
657     mach_port_deallocate(mach_task_self(), clock_realtime);
658     mach_port_deallocate(mach_task_self(), clock_monotonic);
659 #endif
660   }
661 }
662
663 static int get_configuration_index (struct libusb_device *dev, UInt8 config_value) {
664   struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
665   UInt8 i, numConfig;
666   IOUSBConfigurationDescriptorPtr desc;
667   IOReturn kresult;
668
669   /* is there a simpler way to determine the index? */
670   kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
671   if (kresult != kIOReturnSuccess)
672     return darwin_to_libusb (kresult);
673
674   for (i = 0 ; i < numConfig ; i++) {
675     (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
676
677     if (desc->bConfigurationValue == config_value)
678       return i;
679   }
680
681   /* configuration not found */
682   return LIBUSB_ERROR_NOT_FOUND;
683 }
684
685 static int darwin_get_active_config_descriptor(struct libusb_device *dev, void *buffer, size_t len) {
686   struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
687   int config_index;
688
689   if (0 == priv->active_config)
690     return LIBUSB_ERROR_NOT_FOUND;
691
692   config_index = get_configuration_index (dev, priv->active_config);
693   if (config_index < 0)
694     return config_index;
695
696   assert(config_index >= 0 && config_index <= UINT8_MAX);
697   return darwin_get_config_descriptor (dev, (UInt8)config_index, buffer, len);
698 }
699
700 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, void *buffer, size_t len) {
701   struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
702   IOUSBConfigurationDescriptorPtr desc;
703   IOReturn kresult;
704   int ret;
705
706   if (!priv || !priv->device)
707     return LIBUSB_ERROR_OTHER;
708
709   kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
710   if (kresult == kIOReturnSuccess) {
711     /* copy descriptor */
712     if (libusb_le16_to_cpu(desc->wTotalLength) < len)
713       len = libusb_le16_to_cpu(desc->wTotalLength);
714
715     memmove (buffer, desc, len);
716   }
717
718   ret = darwin_to_libusb (kresult);
719   if (ret != LIBUSB_SUCCESS)
720     return ret;
721
722   return (int) len;
723 }
724
725 /* check whether the os has configured the device */
726 static enum libusb_error darwin_check_configuration (struct libusb_context *ctx, struct darwin_cached_device *dev) {
727   usb_device_t **darwin_device = dev->device;
728
729   IOUSBConfigurationDescriptorPtr configDesc;
730   IOUSBFindInterfaceRequest request;
731   IOReturn                  kresult;
732   io_iterator_t             interface_iterator;
733   io_service_t              firstInterface;
734
735   if (dev->dev_descriptor.bNumConfigurations < 1) {
736     usbi_err (ctx, "device has no configurations");
737     return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
738   }
739
740   /* checking the configuration of a root hub simulation takes ~1 s in 10.11. the device is
741      not usable anyway */
742   if (0x05ac == libusb_le16_to_cpu (dev->dev_descriptor.idVendor) &&
743       0x8005 == libusb_le16_to_cpu (dev->dev_descriptor.idProduct)) {
744     usbi_dbg ("ignoring configuration on root hub simulation");
745     dev->active_config = 0;
746     return LIBUSB_SUCCESS;
747   }
748
749   /* find the first configuration */
750   kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
751   dev->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
752
753   /* check if the device is already configured. there is probably a better way than iterating over the
754      to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
755      might lock up on the device request) */
756
757   /* Setup the Interface Request */
758   request.bInterfaceClass    = kIOUSBFindInterfaceDontCare;
759   request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
760   request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
761   request.bAlternateSetting  = kIOUSBFindInterfaceDontCare;
762
763   kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
764   if (kresult != kIOReturnSuccess)
765     return darwin_to_libusb (kresult);
766
767   /* iterate once */
768   firstInterface = IOIteratorNext(interface_iterator);
769
770   /* done with the interface iterator */
771   IOObjectRelease(interface_iterator);
772
773   if (firstInterface) {
774     IOObjectRelease (firstInterface);
775
776     /* device is configured */
777     if (dev->dev_descriptor.bNumConfigurations == 1)
778       /* to avoid problems with some devices get the configurations value from the configuration descriptor */
779       dev->active_config = dev->first_config;
780     else
781       /* devices with more than one configuration should work with GetConfiguration */
782       (*darwin_device)->GetConfiguration (darwin_device, &dev->active_config);
783   } else
784     /* not configured */
785     dev->active_config = 0;
786
787   usbi_dbg ("active config: %u, first config: %u", dev->active_config, dev->first_config);
788
789   return LIBUSB_SUCCESS;
790 }
791
792 static IOReturn darwin_request_descriptor (usb_device_t **device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
793   IOUSBDevRequestTO req;
794
795   assert(buffer_size <= UINT16_MAX);
796
797   memset (buffer, 0, buffer_size);
798
799   /* Set up request for descriptor/ */
800   req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
801   req.bRequest      = kUSBRqGetDescriptor;
802   req.wValue        = (UInt16)(desc << 8);
803   req.wIndex        = desc_index;
804   req.wLength       = (UInt16)buffer_size;
805   req.pData         = buffer;
806   req.noDataTimeout = 20;
807   req.completionTimeout = 100;
808
809   return (*device)->DeviceRequestTO (device, &req);
810 }
811
812 static enum libusb_error darwin_cache_device_descriptor (struct darwin_cached_device *dev) {
813   usb_device_t **device = dev->device;
814   int retries = 1;
815   long delay = 30000; // microseconds
816   int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
817   int is_open = 0;
818   IOReturn ret = 0, ret2;
819   UInt8 bDeviceClass;
820   UInt16 idProduct, idVendor;
821
822   dev->can_enumerate = 0;
823
824   (*device)->GetDeviceClass (device, &bDeviceClass);
825   (*device)->GetDeviceProduct (device, &idProduct);
826   (*device)->GetDeviceVendor (device, &idVendor);
827
828   /* According to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
829    * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request.  Still,
830    * to follow the spec as closely as possible, try opening the device */
831   is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
832
833   do {
834     /**** retrieve device descriptor ****/
835     ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &dev->dev_descriptor, sizeof(dev->dev_descriptor));
836
837     if (kIOReturnOverrun == ret && kUSBDeviceDesc == dev->dev_descriptor.bDescriptorType)
838       /* received an overrun error but we still received a device descriptor */
839       ret = kIOReturnSuccess;
840
841     if (kIOUSBVendorIDAppleComputer == idVendor) {
842       /* NTH: don't bother retrying or unsuspending Apple devices */
843       break;
844     }
845
846     if (kIOReturnSuccess == ret && (0 == dev->dev_descriptor.bNumConfigurations ||
847                                     0 == dev->dev_descriptor.bcdUSB)) {
848       /* work around for incorrectly configured devices */
849       if (try_reconfigure && is_open) {
850         usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
851
852         /* set the first configuration */
853         (*device)->SetConfiguration(device, 1);
854
855         /* don't try to reconfigure again */
856         try_reconfigure = 0;
857       }
858
859       ret = kIOUSBPipeStalled;
860     }
861
862     if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
863       /* device may be suspended. unsuspend it and try again */
864 #if DeviceVersion >= 320
865       UInt32 info = 0;
866
867       /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
868       (void)(*device)->GetUSBDeviceInformation (device, &info);
869
870       /* note that the device was suspended */
871       if (info & (1U << kUSBInformationDeviceIsSuspendedBit) || 0 == info)
872         try_unsuspend = 1;
873 #endif
874
875       if (try_unsuspend) {
876         /* try to unsuspend the device */
877         ret2 = (*device)->USBDeviceSuspend (device, 0);
878         if (kIOReturnSuccess != ret2) {
879           /* prevent log spew from poorly behaving devices.  this indicates the
880              os actually had trouble communicating with the device */
881           usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
882         } else
883           unsuspended = 1;
884
885         try_unsuspend = 0;
886       }
887     }
888
889     if (kIOReturnSuccess != ret) {
890       usbi_dbg("kernel responded with code: 0x%08x. sleeping for %ld ms before trying again", ret, delay/1000);
891       /* sleep for a little while before trying again */
892       nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000}, NULL);
893     }
894   } while (kIOReturnSuccess != ret && retries--);
895
896   if (unsuspended)
897     /* resuspend the device */
898     (void)(*device)->USBDeviceSuspend (device, 1);
899
900   if (is_open)
901     (void) (*device)->USBDeviceClose (device);
902
903   if (ret != kIOReturnSuccess) {
904     /* a debug message was already printed out for this error */
905     if (LIBUSB_CLASS_HUB == bDeviceClass)
906       usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
907                 idVendor, idProduct, darwin_error_str (ret), ret);
908     else
909       usbi_warn (NULL, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
910                  idVendor, idProduct, darwin_error_str (ret), ret);
911     return darwin_to_libusb (ret);
912   }
913
914   /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
915   if (libusb_le16_to_cpu (dev->dev_descriptor.idProduct) != idProduct) {
916     /* not a valid device */
917     usbi_warn (NULL, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
918                idProduct, libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
919     return LIBUSB_ERROR_NO_DEVICE;
920   }
921
922   usbi_dbg ("cached device descriptor:");
923   usbi_dbg ("  bDescriptorType:    0x%02x", dev->dev_descriptor.bDescriptorType);
924   usbi_dbg ("  bcdUSB:             0x%04x", libusb_le16_to_cpu (dev->dev_descriptor.bcdUSB));
925   usbi_dbg ("  bDeviceClass:       0x%02x", dev->dev_descriptor.bDeviceClass);
926   usbi_dbg ("  bDeviceSubClass:    0x%02x", dev->dev_descriptor.bDeviceSubClass);
927   usbi_dbg ("  bDeviceProtocol:    0x%02x", dev->dev_descriptor.bDeviceProtocol);
928   usbi_dbg ("  bMaxPacketSize0:    0x%02x", dev->dev_descriptor.bMaxPacketSize0);
929   usbi_dbg ("  idVendor:           0x%04x", libusb_le16_to_cpu (dev->dev_descriptor.idVendor));
930   usbi_dbg ("  idProduct:          0x%04x", libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
931   usbi_dbg ("  bcdDevice:          0x%04x", libusb_le16_to_cpu (dev->dev_descriptor.bcdDevice));
932   usbi_dbg ("  iManufacturer:      0x%02x", dev->dev_descriptor.iManufacturer);
933   usbi_dbg ("  iProduct:           0x%02x", dev->dev_descriptor.iProduct);
934   usbi_dbg ("  iSerialNumber:      0x%02x", dev->dev_descriptor.iSerialNumber);
935   usbi_dbg ("  bNumConfigurations: 0x%02x", dev->dev_descriptor.bNumConfigurations);
936
937   dev->can_enumerate = 1;
938
939   return LIBUSB_SUCCESS;
940 }
941
942 /* Returns 1 on success, 0 on failure. */
943 static bool get_device_port (io_service_t service, UInt8 *port) {
944   IOReturn kresult;
945   io_service_t parent;
946   bool ret = false;
947
948   if (get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, port)) {
949     return true;
950   }
951
952   kresult = IORegistryEntryGetParentEntry (service, kIOServicePlane, &parent);
953   if (kIOReturnSuccess == kresult) {
954     ret = get_ioregistry_value_data (parent, CFSTR("port"), 1, port);
955     IOObjectRelease (parent);
956   }
957
958   return ret;
959 }
960
961 /* Returns 1 on success, 0 on failure. */
962 static bool get_device_parent_sessionID(io_service_t service, UInt64 *parent_sessionID) {
963   IOReturn kresult;
964   io_service_t parent;
965
966   /* Walk up the tree in the IOService plane until we find a parent that has a sessionID */
967   parent = service;
968   while((kresult = IORegistryEntryGetParentEntry (parent, kIOUSBPlane, &parent)) == kIOReturnSuccess) {
969     if (get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, parent_sessionID)) {
970         /* Success */
971         return true;
972     }
973   }
974
975   /* We ran out of parents */
976   return false;
977 }
978
979 static enum libusb_error darwin_get_cached_device(io_service_t service, struct darwin_cached_device **cached_out,
980                                                   UInt64 *old_session_id) {
981   struct darwin_cached_device *new_device;
982   UInt64 sessionID = 0, parent_sessionID = 0;
983   UInt32 locationID = 0;
984   enum libusb_error ret = LIBUSB_SUCCESS;
985   usb_device_t **device;
986   UInt8 port = 0;
987
988   /* assuming sessionID != 0 normally (never seen it be 0) */
989   *old_session_id = 0;
990   *cached_out = NULL;
991
992   /* get some info from the io registry */
993   (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
994   (void) get_ioregistry_value_number (service, CFSTR("locationID"), kCFNumberSInt32Type, &locationID);
995   if (!get_device_port (service, &port)) {
996     usbi_dbg("could not get connected port number");
997   }
998
999   usbi_dbg("finding cached device for sessionID 0x%" PRIx64, sessionID);
1000
1001   if (get_device_parent_sessionID(service, &parent_sessionID)) {
1002     usbi_dbg("parent sessionID: 0x%" PRIx64, parent_sessionID);
1003   }
1004
1005   usbi_mutex_lock(&darwin_cached_devices_lock);
1006   do {
1007     list_for_each_entry(new_device, &darwin_cached_devices, list, struct darwin_cached_device) {
1008       usbi_dbg("matching sessionID/locationID 0x%" PRIx64 "/0x%x against cached device with sessionID/locationID 0x%" PRIx64 "/0x%x",
1009                sessionID, locationID, new_device->session, new_device->location);
1010       if (new_device->location == locationID && new_device->in_reenumerate) {
1011         usbi_dbg ("found cached device with matching location that is being re-enumerated");
1012         *old_session_id = new_device->session;
1013         break;
1014       }
1015
1016       if (new_device->session == sessionID) {
1017         usbi_dbg("using cached device for device");
1018         *cached_out = new_device;
1019         break;
1020       }
1021     }
1022
1023     if (*cached_out)
1024       break;
1025
1026     usbi_dbg("caching new device with sessionID 0x%" PRIx64, sessionID);
1027
1028     device = darwin_device_from_service (service);
1029     if (!device) {
1030       ret = LIBUSB_ERROR_NO_DEVICE;
1031       break;
1032     }
1033
1034     if (!(*old_session_id)) {
1035       new_device = calloc (1, sizeof (*new_device));
1036       if (!new_device) {
1037         ret = LIBUSB_ERROR_NO_MEM;
1038         break;
1039       }
1040
1041       /* add this device to the cached device list */
1042       list_add(&new_device->list, &darwin_cached_devices);
1043
1044       (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
1045
1046       /* keep a reference to this device */
1047       darwin_ref_cached_device(new_device);
1048
1049       (*device)->GetLocationID (device, &new_device->location);
1050       new_device->port = port;
1051       new_device->parent_session = parent_sessionID;
1052     } else {
1053       /* release the ref to old device's service */
1054       IOObjectRelease (new_device->service);
1055     }
1056
1057     /* keep track of devices regardless of if we successfully enumerate them to
1058        prevent them from being enumerated multiple times */
1059     *cached_out = new_device;
1060
1061     new_device->session = sessionID;
1062     new_device->device = device;
1063     new_device->service = service;
1064
1065     /* retain the service */
1066     IOObjectRetain (service);
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_reenumerate_device (struct libusb_device_handle *dev_handle, bool capture) {
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   UInt32 options = 0;
1681   IOUSBDeviceDescriptor descriptor;
1682   IOUSBConfigurationDescriptorPtr cached_configuration;
1683   IOUSBConfigurationDescriptor *cached_configurations;
1684   IOReturn kresult;
1685   UInt8 i;
1686   UInt32 time;
1687
1688   if (dpriv->in_reenumerate) {
1689     /* ack, two (or more) threads are trying to reset the device! abort! */
1690     return LIBUSB_ERROR_NOT_FOUND;
1691   }
1692
1693   dpriv->in_reenumerate = true;
1694
1695   /* store copies of descriptors so they can be compared after the reset */
1696   memcpy (&descriptor, &dpriv->dev_descriptor, sizeof (descriptor));
1697   cached_configurations = alloca (sizeof (*cached_configurations) * descriptor.bNumConfigurations);
1698
1699   for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1700     (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1701     memcpy (cached_configurations + i, cached_configuration, sizeof (cached_configurations[i]));
1702   }
1703
1704   /* if we need to release capture */
1705   if (HAS_CAPTURE_DEVICE()) {
1706     if (capture) {
1707       options |= kUSBReEnumerateCaptureDeviceMask;
1708     }
1709   } else {
1710     capture = false;
1711   }
1712
1713   /* from macOS 10.11 ResetDevice no longer does anything so just use USBDeviceReEnumerate */
1714   kresult = (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, options);
1715   if (kresult != kIOReturnSuccess) {
1716     usbi_err (HANDLE_CTX (dev_handle), "USBDeviceReEnumerate: %s", darwin_error_str (kresult));
1717     dpriv->in_reenumerate = false;
1718     return darwin_to_libusb (kresult);
1719   }
1720
1721   /* capture mode does not re-enumerate but it does require re-open */
1722   if (capture) {
1723     usbi_dbg ("darwin/reenumerate_device: restoring state...");
1724     dpriv->in_reenumerate = false;
1725     return darwin_restore_state (dev_handle, active_config, claimed_interfaces);
1726   }
1727
1728   usbi_dbg ("darwin/reenumerate_device: waiting for re-enumeration to complete...");
1729
1730   time = 0;
1731   while (dpriv->in_reenumerate) {
1732     struct timespec delay = {.tv_sec = 0, .tv_nsec = 1000};
1733     nanosleep (&delay, NULL);
1734     if (time++ >= DARWIN_REENUMERATE_TIMEOUT_US) {
1735       usbi_err (HANDLE_CTX (dev_handle), "darwin/reenumerate_device: timeout waiting for reenumerate");
1736       dpriv->in_reenumerate = false;
1737       return LIBUSB_ERROR_TIMEOUT;
1738     }
1739   }
1740
1741   /* compare descriptors */
1742   usbi_dbg ("darwin/reenumerate_device: checking whether descriptors changed");
1743
1744   if (memcmp (&descriptor, &dpriv->dev_descriptor, sizeof (descriptor))) {
1745     /* device descriptor changed. need to return not found. */
1746     usbi_dbg ("darwin/reenumerate_device: device descriptor changed");
1747     return LIBUSB_ERROR_NOT_FOUND;
1748   }
1749
1750   for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1751     (void) (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1752     if (memcmp (cached_configuration, cached_configurations + i, sizeof (cached_configurations[i]))) {
1753       usbi_dbg ("darwin/reenumerate_device: configuration descriptor %d changed", i);
1754       return LIBUSB_ERROR_NOT_FOUND;
1755     }
1756   }
1757
1758   usbi_dbg ("darwin/reenumerate_device: device reset complete. restoring state...");
1759
1760   return darwin_restore_state (dev_handle, active_config, claimed_interfaces);
1761 }
1762
1763 static int darwin_reset_device (struct libusb_device_handle *dev_handle) {
1764   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1765   IOReturn kresult;
1766
1767   if (dpriv->capture_count > 0) {
1768     /* we have to use ResetDevice as USBDeviceReEnumerate() loses the authorization for capture */
1769     kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1770     return darwin_to_libusb (kresult);
1771   } else {
1772     return darwin_reenumerate_device (dev_handle, false);
1773   }
1774 }
1775
1776 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, uint8_t interface) {
1777   enum libusb_error ret = darwin_claim_interface (dev_handle, interface);
1778   if (ret == LIBUSB_SUCCESS) {
1779     darwin_release_interface (dev_handle, interface);
1780   }
1781   return (ret == LIBUSB_ERROR_ACCESS);
1782 }
1783
1784 static void darwin_destroy_device(struct libusb_device *dev) {
1785   struct darwin_device_priv *dpriv = usbi_get_device_priv(dev);
1786
1787   if (dpriv->dev) {
1788     /* need to hold the lock in case this is the last reference to the device */
1789     usbi_mutex_lock(&darwin_cached_devices_lock);
1790     darwin_deref_cached_device (dpriv->dev);
1791     dpriv->dev = NULL;
1792     usbi_mutex_unlock(&darwin_cached_devices_lock);
1793   }
1794 }
1795
1796 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1797   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1798
1799   IOReturn               ret;
1800   uint8_t                transferType;
1801   uint8_t                pipeRef;
1802   uint16_t               maxPacketSize;
1803
1804   struct darwin_interface *cInterface;
1805 #if InterfaceVersion >= 550
1806   IOUSBEndpointProperties pipeProperties = {.bVersion = kUSBEndpointPropertiesVersion3};
1807 #else
1808   /* None of the values below are used in libusb for bulk transfers */
1809   uint8_t                 direction, number, interval;
1810 #endif
1811
1812   if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1813     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1814
1815     return LIBUSB_ERROR_NOT_FOUND;
1816   }
1817
1818 #if InterfaceVersion >= 550
1819   ret = (*(cInterface->interface))->GetPipePropertiesV3 (cInterface->interface, pipeRef, &pipeProperties);
1820
1821   transferType = pipeProperties.bTransferType;
1822   maxPacketSize = pipeProperties.wMaxPacketSize;
1823 #else
1824   ret = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1825                                                        &transferType, &maxPacketSize, &interval);
1826 #endif
1827
1828   if (ret) {
1829     usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1830               darwin_error_str(ret), ret);
1831     return darwin_to_libusb (ret);
1832   }
1833
1834   if (0 != (transfer->length % maxPacketSize)) {
1835     /* do not need a zero packet */
1836     transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1837   }
1838
1839   /* submit the request */
1840   /* timeouts are unavailable on interrupt endpoints */
1841   if (transferType == kUSBInterrupt) {
1842     if (IS_XFERIN(transfer))
1843       ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1844                                                       (UInt32)transfer->length, darwin_async_io_callback, itransfer);
1845     else
1846       ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1847                                                        (UInt32)transfer->length, darwin_async_io_callback, itransfer);
1848   } else {
1849     itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1850
1851     if (IS_XFERIN(transfer))
1852       ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1853                                                         (UInt32)transfer->length, transfer->timeout, transfer->timeout,
1854                                                         darwin_async_io_callback, itransfer);
1855     else
1856       ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1857                                                          (UInt32)transfer->length, transfer->timeout, transfer->timeout,
1858                                                          darwin_async_io_callback, itransfer);
1859   }
1860
1861   if (ret)
1862     usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1863                darwin_error_str(ret), ret);
1864
1865   return darwin_to_libusb (ret);
1866 }
1867
1868 #if InterfaceVersion >= 550
1869 static int submit_stream_transfer(struct usbi_transfer *itransfer) {
1870   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1871   struct darwin_interface *cInterface;
1872   uint8_t pipeRef;
1873   IOReturn ret;
1874
1875   if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1876     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1877
1878     return LIBUSB_ERROR_NOT_FOUND;
1879   }
1880
1881   itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1882
1883   if (IS_XFERIN(transfer))
1884     ret = (*(cInterface->interface))->ReadStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1885                                                              transfer->buffer, (UInt32)transfer->length, transfer->timeout,
1886                                                              transfer->timeout, darwin_async_io_callback, itransfer);
1887   else
1888     ret = (*(cInterface->interface))->WriteStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1889                                                               transfer->buffer, (UInt32)transfer->length, transfer->timeout,
1890                                                               transfer->timeout, darwin_async_io_callback, itransfer);
1891
1892   if (ret)
1893     usbi_err (TRANSFER_CTX (transfer), "bulk stream transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1894                darwin_error_str(ret), ret);
1895
1896   return darwin_to_libusb (ret);
1897 }
1898 #endif
1899
1900 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1901   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1902   struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
1903
1904   IOReturn kresult;
1905   uint8_t direction, number, interval, pipeRef, transferType;
1906   uint16_t maxPacketSize;
1907   UInt64 frame;
1908   AbsoluteTime atTime;
1909   int i;
1910
1911   struct darwin_interface *cInterface;
1912
1913   /* construct an array of IOUSBIsocFrames, reuse the old one if the sizes are the same */
1914   if (tpriv->num_iso_packets != transfer->num_iso_packets) {
1915     free(tpriv->isoc_framelist);
1916     tpriv->isoc_framelist = NULL;
1917   }
1918
1919   if (!tpriv->isoc_framelist) {
1920     tpriv->num_iso_packets = transfer->num_iso_packets;
1921     tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc ((size_t)transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1922     if (!tpriv->isoc_framelist)
1923       return LIBUSB_ERROR_NO_MEM;
1924   }
1925
1926   /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1927   for (i = 0 ; i < transfer->num_iso_packets ; i++) {
1928     unsigned int length = transfer->iso_packet_desc[i].length;
1929     assert(length <= UINT16_MAX);
1930     tpriv->isoc_framelist[i].frReqCount = (UInt16)length;
1931   }
1932
1933   /* determine the interface/endpoint to use */
1934   if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1935     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1936
1937     return LIBUSB_ERROR_NOT_FOUND;
1938   }
1939
1940   /* determine the properties of this endpoint and the speed of the device */
1941   (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1942                                                  &transferType, &maxPacketSize, &interval);
1943
1944   /* Last but not least we need the bus frame number */
1945   kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1946   if (kresult != kIOReturnSuccess) {
1947     usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1948     free(tpriv->isoc_framelist);
1949     tpriv->isoc_framelist = NULL;
1950
1951     return darwin_to_libusb (kresult);
1952   }
1953
1954   (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1955                                                  &transferType, &maxPacketSize, &interval);
1956
1957   /* schedule for a frame a little in the future */
1958   frame += 4;
1959
1960   if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1961     frame = cInterface->frames[transfer->endpoint];
1962
1963   /* submit the request */
1964   if (IS_XFERIN(transfer))
1965     kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1966                                                              (UInt32)transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1967                                                              itransfer);
1968   else
1969     kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1970                                                               (UInt32)transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1971                                                               itransfer);
1972
1973   if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
1974     /* Full speed */
1975     cInterface->frames[transfer->endpoint] = frame + (UInt32)transfer->num_iso_packets * (1U << (interval - 1));
1976   else
1977     /* High/super speed */
1978     cInterface->frames[transfer->endpoint] = frame + (UInt32)transfer->num_iso_packets * (1U << (interval - 1)) / 8;
1979
1980   if (kresult != kIOReturnSuccess) {
1981     usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1982                darwin_error_str(kresult));
1983     free (tpriv->isoc_framelist);
1984     tpriv->isoc_framelist = NULL;
1985   }
1986
1987   return darwin_to_libusb (kresult);
1988 }
1989
1990 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1991   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1992   struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1993   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1994   struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
1995
1996   IOReturn               kresult;
1997
1998   memset(&tpriv->req, 0, sizeof(tpriv->req));
1999
2000   /* IOUSBDeviceInterface expects the request in cpu endianness */
2001   tpriv->req.bmRequestType     = setup->bmRequestType;
2002   tpriv->req.bRequest          = setup->bRequest;
2003   /* these values should be in bus order from libusb_fill_control_setup */
2004   tpriv->req.wValue            = OSSwapLittleToHostInt16 (setup->wValue);
2005   tpriv->req.wIndex            = OSSwapLittleToHostInt16 (setup->wIndex);
2006   tpriv->req.wLength           = OSSwapLittleToHostInt16 (setup->wLength);
2007   /* data is stored after the libusb control block */
2008   tpriv->req.pData             = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
2009   tpriv->req.completionTimeout = transfer->timeout;
2010   tpriv->req.noDataTimeout     = transfer->timeout;
2011
2012   itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
2013
2014   /* all transfers in libusb-1.0 are async */
2015
2016   if (transfer->endpoint) {
2017     struct darwin_interface *cInterface;
2018     uint8_t                 pipeRef;
2019
2020     if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
2021       usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
2022
2023       return LIBUSB_ERROR_NOT_FOUND;
2024     }
2025
2026     kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
2027   } else
2028     /* control request on endpoint 0 */
2029     kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
2030
2031   if (kresult != kIOReturnSuccess)
2032     usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
2033
2034   return darwin_to_libusb (kresult);
2035 }
2036
2037 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
2038   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2039
2040   switch (transfer->type) {
2041   case LIBUSB_TRANSFER_TYPE_CONTROL:
2042     return submit_control_transfer(itransfer);
2043   case LIBUSB_TRANSFER_TYPE_BULK:
2044   case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2045     return submit_bulk_transfer(itransfer);
2046   case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2047     return submit_iso_transfer(itransfer);
2048   case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2049 #if InterfaceVersion >= 550
2050     return submit_stream_transfer(itransfer);
2051 #else
2052     usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version does not support bulk stream transfers");
2053     return LIBUSB_ERROR_NOT_SUPPORTED;
2054 #endif
2055   default:
2056     usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
2057     return LIBUSB_ERROR_INVALID_PARAM;
2058   }
2059 }
2060
2061 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
2062   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2063   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
2064   IOReturn kresult;
2065
2066   usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
2067
2068   if (!dpriv->device)
2069     return LIBUSB_ERROR_NO_DEVICE;
2070
2071   kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
2072
2073   return darwin_to_libusb (kresult);
2074 }
2075
2076 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
2077   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2078   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
2079   struct darwin_interface *cInterface;
2080   uint8_t pipeRef, iface;
2081   IOReturn kresult;
2082
2083   if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface, &cInterface) != 0) {
2084     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
2085
2086     return LIBUSB_ERROR_NOT_FOUND;
2087   }
2088
2089   if (!dpriv->device)
2090     return LIBUSB_ERROR_NO_DEVICE;
2091
2092   usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
2093
2094   /* abort transactions */
2095 #if InterfaceVersion >= 550
2096   if (LIBUSB_TRANSFER_TYPE_BULK_STREAM == transfer->type)
2097     (*(cInterface->interface))->AbortStreamsPipe (cInterface->interface, pipeRef, itransfer->stream_id);
2098   else
2099 #endif
2100     (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
2101
2102   usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
2103
2104   /* newer versions of darwin support clearing additional bits on the device's endpoint */
2105   kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
2106
2107   return darwin_to_libusb (kresult);
2108 }
2109
2110 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
2111   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2112
2113   switch (transfer->type) {
2114   case LIBUSB_TRANSFER_TYPE_CONTROL:
2115     return cancel_control_transfer(itransfer);
2116   case LIBUSB_TRANSFER_TYPE_BULK:
2117   case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2118   case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2119     return darwin_abort_transfers (itransfer);
2120   default:
2121     usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
2122     return LIBUSB_ERROR_INVALID_PARAM;
2123   }
2124 }
2125
2126 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
2127   struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
2128   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2129   struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2130
2131   usbi_dbg ("an async io operation has completed");
2132
2133   /* if requested write a zero packet */
2134   if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
2135     struct darwin_interface *cInterface;
2136     uint8_t pipeRef;
2137
2138     (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface);
2139
2140     (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
2141   }
2142
2143   tpriv->result = result;
2144   tpriv->size = (UInt32) (uintptr_t) arg0;
2145
2146   /* signal the core that this transfer is complete */
2147   usbi_signal_transfer_completion(itransfer);
2148 }
2149
2150 static enum libusb_transfer_status darwin_transfer_status (struct usbi_transfer *itransfer, IOReturn result) {
2151   if (itransfer->timeout_flags & USBI_TRANSFER_TIMED_OUT)
2152     result = kIOUSBTransactionTimeout;
2153
2154   switch (result) {
2155   case kIOReturnUnderrun:
2156   case kIOReturnSuccess:
2157     return LIBUSB_TRANSFER_COMPLETED;
2158   case kIOReturnAborted:
2159     return LIBUSB_TRANSFER_CANCELLED;
2160   case kIOUSBPipeStalled:
2161     usbi_dbg ("transfer error: pipe is stalled");
2162     return LIBUSB_TRANSFER_STALL;
2163   case kIOReturnOverrun:
2164     usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
2165     return LIBUSB_TRANSFER_OVERFLOW;
2166   case kIOUSBTransactionTimeout:
2167     usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
2168     itransfer->timeout_flags |= USBI_TRANSFER_TIMED_OUT;
2169     return LIBUSB_TRANSFER_TIMED_OUT;
2170   default:
2171     usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
2172     return LIBUSB_TRANSFER_ERROR;
2173   }
2174 }
2175
2176 static int darwin_handle_transfer_completion (struct usbi_transfer *itransfer) {
2177   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2178   struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2179   const unsigned char max_transfer_type = LIBUSB_TRANSFER_TYPE_BULK_STREAM;
2180   const char *transfer_types[] = {"control", "isoc", "bulk", "interrupt", "bulk-stream", NULL};
2181   bool is_isoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
2182
2183   if (transfer->type > max_transfer_type) {
2184     usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
2185     return LIBUSB_ERROR_INVALID_PARAM;
2186   }
2187
2188   if (NULL == tpriv) {
2189     usbi_err (TRANSFER_CTX(transfer), "malformed request is missing transfer priv");
2190     return LIBUSB_ERROR_INVALID_PARAM;
2191   }
2192
2193   usbi_dbg ("handling transfer completion type %s with kernel status %d", transfer_types[transfer->type], tpriv->result);
2194
2195   if (kIOReturnSuccess == tpriv->result || kIOReturnUnderrun == tpriv->result || kIOUSBTransactionTimeout == tpriv->result) {
2196     if (is_isoc && tpriv->isoc_framelist) {
2197       /* copy isochronous results back */
2198
2199       for (int i = 0; i < transfer->num_iso_packets ; i++) {
2200         struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
2201         lib_desc->status = darwin_transfer_status (itransfer, tpriv->isoc_framelist[i].frStatus);
2202         lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
2203       }
2204     } else if (!is_isoc) {
2205       itransfer->transferred += tpriv->size;
2206     }
2207   }
2208
2209   /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
2210   return usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, tpriv->result));
2211 }
2212
2213 #if !defined(HAVE_CLOCK_GETTIME)
2214 void usbi_get_monotonic_time(struct timespec *tp) {
2215   mach_timespec_t sys_time;
2216
2217   /* use system boot time as reference for the monotonic clock */
2218   clock_get_time (clock_monotonic, &sys_time);
2219
2220   tp->tv_sec  = sys_time.tv_sec;
2221   tp->tv_nsec = sys_time.tv_nsec;
2222 }
2223
2224 void usbi_get_real_time(struct timespec *tp) {
2225   mach_timespec_t sys_time;
2226
2227   /* CLOCK_REALTIME represents time since the epoch */
2228   clock_get_time (clock_realtime, &sys_time);
2229
2230   tp->tv_sec  = sys_time.tv_sec;
2231   tp->tv_nsec = sys_time.tv_nsec;
2232 }
2233 #endif
2234
2235 #if InterfaceVersion >= 550
2236 static int darwin_alloc_streams (struct libusb_device_handle *dev_handle, uint32_t num_streams, unsigned char *endpoints,
2237                                  int num_endpoints) {
2238   struct darwin_interface *cInterface;
2239   UInt32 supportsStreams;
2240   uint8_t pipeRef;
2241   int rc, i;
2242
2243   /* find the minimum number of supported streams on the endpoint list */
2244   for (i = 0 ; i < num_endpoints ; ++i) {
2245     if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface))) {
2246       return rc;
2247     }
2248
2249     (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2250     if (num_streams > supportsStreams)
2251       num_streams = supportsStreams;
2252   }
2253
2254   /* it is an error if any endpoint in endpoints does not support streams */
2255   if (0 == num_streams)
2256     return LIBUSB_ERROR_INVALID_PARAM;
2257
2258   /* create the streams */
2259   for (i = 0 ; i < num_endpoints ; ++i) {
2260     (void) ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
2261
2262     rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, num_streams);
2263     if (kIOReturnSuccess != rc)
2264       return darwin_to_libusb(rc);
2265   }
2266
2267   assert(num_streams <= INT_MAX);
2268   return (int)num_streams;
2269 }
2270
2271 static int darwin_free_streams (struct libusb_device_handle *dev_handle, unsigned char *endpoints, int num_endpoints) {
2272   struct darwin_interface *cInterface;
2273   UInt32 supportsStreams;
2274   uint8_t pipeRef;
2275   int rc;
2276
2277   for (int i = 0 ; i < num_endpoints ; ++i) {
2278     if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface)))
2279       return rc;
2280
2281     (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2282     if (0 == supportsStreams)
2283       return LIBUSB_ERROR_INVALID_PARAM;
2284
2285     rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, 0);
2286     if (kIOReturnSuccess != rc)
2287       return darwin_to_libusb(rc);
2288   }
2289
2290   return LIBUSB_SUCCESS;
2291 }
2292 #endif
2293
2294 #if InterfaceVersion >= 700
2295
2296 /* macOS APIs for getting entitlement values */
2297
2298 #if TARGET_OS_OSX
2299 #include <Security/Security.h>
2300 #else
2301 typedef struct __SecTask *SecTaskRef;
2302 extern SecTaskRef SecTaskCreateFromSelf(CFAllocatorRef allocator);
2303 extern CFTypeRef SecTaskCopyValueForEntitlement(SecTaskRef task, CFStringRef entitlement, CFErrorRef *error);
2304 #endif
2305
2306 static bool darwin_has_capture_entitlements (void) {
2307   SecTaskRef task;
2308   CFTypeRef value;
2309   bool entitled;
2310
2311   task = SecTaskCreateFromSelf (kCFAllocatorDefault);
2312   if (task == NULL) {
2313     return false;
2314   }
2315   value = SecTaskCopyValueForEntitlement(task, CFSTR("com.apple.vm.device-access"), NULL);
2316   CFRelease (task);
2317   entitled = value && (CFGetTypeID (value) == CFBooleanGetTypeID ()) && CFBooleanGetValue (value);
2318   if (value) {
2319     CFRelease (value);
2320   }
2321   return entitled;
2322 }
2323
2324 static int darwin_reload_device (struct libusb_device_handle *dev_handle) {
2325   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
2326   enum libusb_error err;
2327
2328   usbi_mutex_lock(&darwin_cached_devices_lock);
2329   (*(dpriv->device))->Release(dpriv->device);
2330   dpriv->device = darwin_device_from_service (dpriv->service);
2331   if (!dpriv->device) {
2332     err = LIBUSB_ERROR_NO_DEVICE;
2333   } else {
2334     err = LIBUSB_SUCCESS;
2335   }
2336   usbi_mutex_unlock(&darwin_cached_devices_lock);
2337
2338   return err;
2339 }
2340
2341 /* On macOS, we capture an entire device at once, not individual interfaces. */
2342
2343 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, uint8_t interface) {
2344   UNUSED(interface);
2345   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
2346   IOReturn kresult;
2347   enum libusb_error err;
2348
2349   if (HAS_CAPTURE_DEVICE()) {
2350   } else {
2351     return LIBUSB_ERROR_NOT_SUPPORTED;
2352   }
2353
2354   if (dpriv->capture_count == 0) {
2355     /* request authorization */
2356     if (darwin_has_capture_entitlements ()) {
2357       kresult = IOServiceAuthorize (dpriv->service, kIOServiceInteractionAllowed);
2358       if (kresult != kIOReturnSuccess) {
2359         usbi_err (HANDLE_CTX (dev_handle), "IOServiceAuthorize: %s", darwin_error_str(kresult));
2360         return darwin_to_libusb (kresult);
2361       }
2362       /* we need start() to be called again for authorization status to refresh */
2363       err = darwin_reload_device (dev_handle);
2364       if (err != LIBUSB_SUCCESS) {
2365         return err;
2366       }
2367     }
2368     /* reset device to release existing drivers */
2369     err = darwin_reenumerate_device (dev_handle, true);
2370     if (err != LIBUSB_SUCCESS) {
2371       return err;
2372     }
2373   }
2374   dpriv->capture_count++;
2375   return LIBUSB_SUCCESS;
2376 }
2377
2378
2379 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, uint8_t interface) {
2380   UNUSED(interface);
2381   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
2382
2383   if (HAS_CAPTURE_DEVICE()) {
2384   } else {
2385     return LIBUSB_ERROR_NOT_SUPPORTED;
2386   }
2387
2388   dpriv->capture_count--;
2389   if (dpriv->capture_count > 0) {
2390     return LIBUSB_SUCCESS;
2391   } else {
2392     dpriv->capture_count = 0;
2393   }
2394   /* reset device to attach kernel drivers */
2395   return darwin_reenumerate_device (dev_handle, false);
2396 }
2397
2398 static int darwin_capture_claim_interface(struct libusb_device_handle *dev_handle, uint8_t iface) {
2399   enum libusb_error ret;
2400   if (dev_handle->auto_detach_kernel_driver) {
2401     ret = darwin_detach_kernel_driver (dev_handle, iface);
2402     if (ret != LIBUSB_SUCCESS) {
2403       return ret;
2404     }
2405   }
2406   return darwin_claim_interface (dev_handle, iface);
2407 }
2408
2409 static int darwin_capture_release_interface(struct libusb_device_handle *dev_handle, uint8_t iface) {
2410   enum libusb_error ret;
2411
2412   ret = darwin_release_interface (dev_handle, iface);
2413   if (ret != LIBUSB_SUCCESS) {
2414     return ret;
2415   }
2416   if (dev_handle->auto_detach_kernel_driver) {
2417     ret = darwin_attach_kernel_driver (dev_handle, iface);
2418   }
2419   return ret;
2420 }
2421
2422 #endif
2423
2424 const struct usbi_os_backend usbi_backend = {
2425         .name = "Darwin",
2426         .caps = USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2427         .init = darwin_init,
2428         .exit = darwin_exit,
2429         .get_active_config_descriptor = darwin_get_active_config_descriptor,
2430         .get_config_descriptor = darwin_get_config_descriptor,
2431         .hotplug_poll = darwin_hotplug_poll,
2432
2433         .open = darwin_open,
2434         .close = darwin_close,
2435         .get_configuration = darwin_get_configuration,
2436         .set_configuration = darwin_set_configuration,
2437
2438         .set_interface_altsetting = darwin_set_interface_altsetting,
2439         .clear_halt = darwin_clear_halt,
2440         .reset_device = darwin_reset_device,
2441
2442 #if InterfaceVersion >= 550
2443         .alloc_streams = darwin_alloc_streams,
2444         .free_streams = darwin_free_streams,
2445 #endif
2446
2447         .kernel_driver_active = darwin_kernel_driver_active,
2448
2449 #if InterfaceVersion >= 700
2450         .detach_kernel_driver = darwin_detach_kernel_driver,
2451         .attach_kernel_driver = darwin_attach_kernel_driver,
2452         .claim_interface = darwin_capture_claim_interface,
2453         .release_interface = darwin_capture_release_interface,
2454 #else
2455         .claim_interface = darwin_claim_interface,
2456         .release_interface = darwin_release_interface,
2457 #endif
2458
2459         .destroy_device = darwin_destroy_device,
2460
2461         .submit_transfer = darwin_submit_transfer,
2462         .cancel_transfer = darwin_cancel_transfer,
2463
2464         .handle_transfer_completion = darwin_handle_transfer_completion,
2465
2466         .device_priv_size = sizeof(struct darwin_device_priv),
2467         .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
2468         .transfer_priv_size = sizeof(struct darwin_transfer_priv),
2469 };