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