darwin: update the list of endpoints after successfull SetAlternateInterface()
[platform/upstream/libusb.git] / libusb / os / darwin_usb.c
1 /* -*- Mode: C; indent-tabs-mode:nil -*- */
2 /*
3  * darwin backend for libusb 1.0
4  * Copyright © 2008-2020 Nathan Hjelm <hjelmn@cs.unm.edu>
5  * Copyright © 2019-2020 Google LLC. All rights reserved.
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include <config.h>
23 #include <assert.h>
24 #include <time.h>
25 #include <ctype.h>
26 #include <pthread.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <sys/types.h>
31 #include <unistd.h>
32 #include <fcntl.h>
33 #include <sys/sysctl.h>
34
35 #include <mach/clock.h>
36 #include <mach/clock_types.h>
37 #include <mach/mach_host.h>
38 #include <mach/mach_port.h>
39
40 /* Suppress warnings about the use of the deprecated objc_registerThreadWithCollector
41  * function. Its use is also conditionalized to only older deployment targets. */
42 #define OBJC_SILENCE_GC_DEPRECATIONS 1
43
44 /* Default timeout to 10s for reenumerate. This is needed because USBDeviceReEnumerate
45  * does not return error status on macOS. */
46 #define DARWIN_REENUMERATE_TIMEOUT_US 10000000
47
48 #include <AvailabilityMacros.h>
49 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
50   #include <objc/objc-auto.h>
51 #endif
52
53 #include "darwin_usb.h"
54
55 static int init_count = 0;
56
57 /* async event thread */
58 static pthread_mutex_t libusb_darwin_at_mutex = PTHREAD_MUTEX_INITIALIZER;
59 static pthread_cond_t  libusb_darwin_at_cond = PTHREAD_COND_INITIALIZER;
60
61 #if !defined(HAVE_CLOCK_GETTIME)
62 static clock_serv_t clock_realtime;
63 static clock_serv_t clock_monotonic;
64 #endif
65
66 #define LIBUSB_DARWIN_STARTUP_FAILURE ((CFRunLoopRef) -1)
67
68 static CFRunLoopRef libusb_darwin_acfl = NULL; /* event cf loop */
69 static CFRunLoopSourceRef libusb_darwin_acfls = NULL; /* shutdown signal for event cf loop */
70
71 static usbi_mutex_t darwin_cached_devices_lock = PTHREAD_MUTEX_INITIALIZER;
72 static struct list_head darwin_cached_devices;
73 static const char *darwin_device_class = "IOUSBDevice";
74
75 #define DARWIN_CACHED_DEVICE(a) (((struct darwin_device_priv *)usbi_get_device_priv((a)))->dev)
76
77 /* async event thread */
78 static pthread_t libusb_darwin_at;
79
80 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, void *buffer, size_t len);
81 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, uint8_t iface);
82 static int darwin_release_interface(struct libusb_device_handle *dev_handle, uint8_t iface);
83 static int darwin_reenumerate_device(struct libusb_device_handle *dev_handle, bool capture);
84 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint);
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, locationID;
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     (void) get_ioregistry_value_number (device, CFSTR("locationID"), kCFNumberSInt32Type, &locationID);
378     IOObjectRelease (device);
379     if (!ret)
380       continue;
381
382     /* we need to match darwin_ref_cached_device call made in darwin_get_cached_device function
383        otherwise no cached device will ever get freed */
384     usbi_mutex_lock(&darwin_cached_devices_lock);
385     list_for_each_entry(old_device, &darwin_cached_devices, list, struct darwin_cached_device) {
386       if (old_device->session == session) {
387         if (old_device->in_reenumerate) {
388           /* device is re-enumerating. do not dereference the device at this time. libusb_reset_device()
389            * will deref if needed. */
390           usbi_dbg ("detected device detached due to re-enumeration. sessionID: 0x%" PRIx64 ", locationID: 0x%" PRIx64,
391                     session, locationID);
392
393           /* the device object is no longer usable so go ahead and release it */
394           if (old_device->device) {
395             (*(old_device->device))->Release(old_device->device);
396             old_device->device = NULL;
397           }
398
399           is_reenumerating = true;
400         } else {
401           darwin_deref_cached_device (old_device);
402         }
403
404         break;
405       }
406     }
407
408     usbi_mutex_unlock(&darwin_cached_devices_lock);
409     if (is_reenumerating) {
410       continue;
411     }
412
413     for_each_context(ctx) {
414       usbi_dbg ("notifying context %p of device disconnect", ctx);
415
416       dev = usbi_get_device_by_session_id(ctx, (unsigned long) session);
417       if (dev) {
418         /* signal the core that this device has been disconnected. the core will tear down this device
419            when the reference count reaches 0 */
420         usbi_disconnect_device(dev);
421         libusb_unref_device(dev);
422       }
423     }
424   }
425
426   usbi_mutex_unlock(&active_contexts_lock);
427 }
428
429 static void darwin_hotplug_poll (void)
430 {
431   /* not sure if 1 ms will be too long/short but it should work ok */
432   mach_timespec_t timeout = {.tv_sec = 0, .tv_nsec = 1000000ul};
433
434   /* since a kernel thread may notify the IOIterators used for
435    * hotplug notification we can't just clear the iterators.
436    * instead just wait until all IOService providers are quiet */
437   (void) IOKitWaitQuiet (kIOMasterPortDefault, &timeout);
438 }
439
440 static void darwin_clear_iterator (io_iterator_t iter) {
441   io_service_t device;
442
443   while ((device = IOIteratorNext (iter)) != 0)
444     IOObjectRelease (device);
445 }
446
447 static void darwin_fail_startup(void) {
448   pthread_mutex_lock (&libusb_darwin_at_mutex);
449   libusb_darwin_acfl = LIBUSB_DARWIN_STARTUP_FAILURE;
450   pthread_cond_signal (&libusb_darwin_at_cond);
451   pthread_mutex_unlock (&libusb_darwin_at_mutex);
452   pthread_exit (NULL);
453 }
454
455 static void *darwin_event_thread_main (void *arg0) {
456   IOReturn kresult;
457   struct libusb_context *ctx = (struct libusb_context *)arg0;
458   CFRunLoopRef runloop;
459   CFRunLoopSourceRef libusb_shutdown_cfsource;
460   CFRunLoopSourceContext libusb_shutdown_cfsourcectx;
461
462 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
463   /* Set this thread's name, so it can be seen in the debugger
464      and crash reports. */
465   pthread_setname_np ("org.libusb.device-hotplug");
466 #endif
467
468 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
469   /* Tell the Objective-C garbage collector about this thread.
470      This is required because, unlike NSThreads, pthreads are
471      not automatically registered. Although we don't use
472      Objective-C, we use CoreFoundation, which does.
473      Garbage collection support was entirely removed in 10.12,
474      so don't bother there. */
475   objc_registerThreadWithCollector();
476 #endif
477
478   /* hotplug (device arrival/removal) sources */
479   CFRunLoopSourceRef     libusb_notification_cfsource;
480   io_notification_port_t libusb_notification_port;
481   io_iterator_t          libusb_rem_device_iterator;
482   io_iterator_t          libusb_add_device_iterator;
483
484   usbi_dbg ("creating hotplug event source");
485
486   runloop = CFRunLoopGetCurrent ();
487   CFRetain (runloop);
488
489   /* add the shutdown cfsource to the run loop */
490   memset(&libusb_shutdown_cfsourcectx, 0, sizeof(libusb_shutdown_cfsourcectx));
491   libusb_shutdown_cfsourcectx.info = runloop;
492   libusb_shutdown_cfsourcectx.perform = (void (*)(void *))CFRunLoopStop;
493   libusb_shutdown_cfsource = CFRunLoopSourceCreate(NULL, 0, &libusb_shutdown_cfsourcectx);
494   CFRunLoopAddSource(runloop, libusb_shutdown_cfsource, kCFRunLoopDefaultMode);
495
496   /* add the notification port to the run loop */
497   libusb_notification_port     = IONotificationPortCreate (kIOMasterPortDefault);
498   libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
499   CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
500
501   /* create notifications for removed devices */
502   kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
503                                               IOServiceMatching(darwin_device_class),
504                                               darwin_devices_detached,
505                                               ctx, &libusb_rem_device_iterator);
506
507   if (kresult != kIOReturnSuccess) {
508     usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
509     CFRelease (libusb_shutdown_cfsource);
510     CFRelease (runloop);
511     darwin_fail_startup ();
512   }
513
514   /* create notifications for attached devices */
515   kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification,
516                                               IOServiceMatching(darwin_device_class),
517                                               darwin_devices_attached,
518                                               ctx, &libusb_add_device_iterator);
519
520   if (kresult != kIOReturnSuccess) {
521     usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
522     CFRelease (libusb_shutdown_cfsource);
523     CFRelease (runloop);
524     darwin_fail_startup ();
525   }
526
527   /* arm notifiers */
528   darwin_clear_iterator (libusb_rem_device_iterator);
529   darwin_clear_iterator (libusb_add_device_iterator);
530
531   usbi_dbg ("darwin event thread ready to receive events");
532
533   /* signal the main thread that the hotplug runloop has been created. */
534   pthread_mutex_lock (&libusb_darwin_at_mutex);
535   libusb_darwin_acfl = runloop;
536   libusb_darwin_acfls = libusb_shutdown_cfsource;
537   pthread_cond_signal (&libusb_darwin_at_cond);
538   pthread_mutex_unlock (&libusb_darwin_at_mutex);
539
540   /* run the runloop */
541   CFRunLoopRun();
542
543   usbi_dbg ("darwin event thread exiting");
544
545   /* signal the main thread that the hotplug runloop has finished. */
546   pthread_mutex_lock (&libusb_darwin_at_mutex);
547   libusb_darwin_acfls = NULL;
548   libusb_darwin_acfl = NULL;
549   pthread_cond_signal (&libusb_darwin_at_cond);
550   pthread_mutex_unlock (&libusb_darwin_at_mutex);
551
552   /* remove the notification cfsource */
553   CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
554
555   /* remove the shutdown cfsource */
556   CFRunLoopRemoveSource(runloop, libusb_shutdown_cfsource, kCFRunLoopDefaultMode);
557
558   /* delete notification port */
559   IONotificationPortDestroy (libusb_notification_port);
560
561   /* delete iterators */
562   IOObjectRelease (libusb_rem_device_iterator);
563   IOObjectRelease (libusb_add_device_iterator);
564
565   CFRelease (libusb_shutdown_cfsource);
566   CFRelease (runloop);
567
568   pthread_exit (NULL);
569 }
570
571 /* cleanup function to destroy cached devices */
572 static void darwin_cleanup_devices(void) {
573   struct darwin_cached_device *dev, *next;
574
575   list_for_each_entry_safe(dev, next, &darwin_cached_devices, list, struct darwin_cached_device) {
576     darwin_deref_cached_device(dev);
577   }
578 }
579
580 static int darwin_init(struct libusb_context *ctx) {
581   bool first_init;
582   int rc;
583
584   first_init = (1 == ++init_count);
585
586   do {
587     if (first_init) {
588       if (NULL == darwin_cached_devices.next) {
589         list_init (&darwin_cached_devices);
590       }
591       assert(list_empty(&darwin_cached_devices));
592 #if !defined(HAVE_CLOCK_GETTIME)
593       /* create the clocks that will be used if clock_gettime() is not available */
594       host_name_port_t host_self;
595
596       host_self = mach_host_self();
597       host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
598       host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
599       mach_port_deallocate(mach_task_self(), host_self);
600 #endif
601     }
602
603     rc = darwin_scan_devices (ctx);
604     if (LIBUSB_SUCCESS != rc)
605       break;
606
607     if (first_init) {
608       rc = pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, ctx);
609       if (0 != rc) {
610         usbi_err (ctx, "could not create event thread, error %d", rc);
611         rc = LIBUSB_ERROR_OTHER;
612         break;
613       }
614
615       pthread_mutex_lock (&libusb_darwin_at_mutex);
616       while (!libusb_darwin_acfl)
617         pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
618       if (libusb_darwin_acfl == LIBUSB_DARWIN_STARTUP_FAILURE) {
619         libusb_darwin_acfl = NULL;
620         rc = LIBUSB_ERROR_OTHER;
621       }
622       pthread_mutex_unlock (&libusb_darwin_at_mutex);
623
624       if (0 != rc)
625         pthread_join (libusb_darwin_at, NULL);
626     }
627   } while (0);
628
629   if (LIBUSB_SUCCESS != rc) {
630     if (first_init) {
631       darwin_cleanup_devices ();
632 #if !defined(HAVE_CLOCK_GETTIME)
633       mach_port_deallocate(mach_task_self(), clock_realtime);
634       mach_port_deallocate(mach_task_self(), clock_monotonic);
635 #endif
636     }
637     --init_count;
638   }
639
640   return rc;
641 }
642
643 static void darwin_exit (struct libusb_context *ctx) {
644   UNUSED(ctx);
645
646   if (0 == --init_count) {
647     /* stop the event runloop and wait for the thread to terminate. */
648     pthread_mutex_lock (&libusb_darwin_at_mutex);
649     CFRunLoopSourceSignal (libusb_darwin_acfls);
650     CFRunLoopWakeUp (libusb_darwin_acfl);
651     while (libusb_darwin_acfl)
652       pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
653     pthread_mutex_unlock (&libusb_darwin_at_mutex);
654     pthread_join (libusb_darwin_at, NULL);
655
656     darwin_cleanup_devices ();
657
658 #if !defined(HAVE_CLOCK_GETTIME)
659     mach_port_deallocate(mach_task_self(), clock_realtime);
660     mach_port_deallocate(mach_task_self(), clock_monotonic);
661 #endif
662   }
663 }
664
665 static int get_configuration_index (struct libusb_device *dev, UInt8 config_value) {
666   struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
667   UInt8 i, numConfig;
668   IOUSBConfigurationDescriptorPtr desc;
669   IOReturn kresult;
670
671   /* is there a simpler way to determine the index? */
672   kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
673   if (kresult != kIOReturnSuccess)
674     return darwin_to_libusb (kresult);
675
676   for (i = 0 ; i < numConfig ; i++) {
677     (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
678
679     if (desc->bConfigurationValue == config_value)
680       return i;
681   }
682
683   /* configuration not found */
684   return LIBUSB_ERROR_NOT_FOUND;
685 }
686
687 static int darwin_get_active_config_descriptor(struct libusb_device *dev, void *buffer, size_t len) {
688   struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
689   int config_index;
690
691   if (0 == priv->active_config)
692     return LIBUSB_ERROR_NOT_FOUND;
693
694   config_index = get_configuration_index (dev, priv->active_config);
695   if (config_index < 0)
696     return config_index;
697
698   assert(config_index >= 0 && config_index <= UINT8_MAX);
699   return darwin_get_config_descriptor (dev, (UInt8)config_index, buffer, len);
700 }
701
702 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, void *buffer, size_t len) {
703   struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
704   IOUSBConfigurationDescriptorPtr desc;
705   IOReturn kresult;
706   int ret;
707
708   if (!priv || !priv->device)
709     return LIBUSB_ERROR_OTHER;
710
711   kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
712   if (kresult == kIOReturnSuccess) {
713     /* copy descriptor */
714     if (libusb_le16_to_cpu(desc->wTotalLength) < len)
715       len = libusb_le16_to_cpu(desc->wTotalLength);
716
717     memmove (buffer, desc, len);
718   }
719
720   ret = darwin_to_libusb (kresult);
721   if (ret != LIBUSB_SUCCESS)
722     return ret;
723
724   return (int) len;
725 }
726
727 /* check whether the os has configured the device */
728 static enum libusb_error darwin_check_configuration (struct libusb_context *ctx, struct darwin_cached_device *dev) {
729   usb_device_t **darwin_device = dev->device;
730
731   IOUSBConfigurationDescriptorPtr configDesc;
732   IOUSBFindInterfaceRequest request;
733   IOReturn                  kresult;
734   io_iterator_t             interface_iterator;
735   io_service_t              firstInterface;
736
737   if (dev->dev_descriptor.bNumConfigurations < 1) {
738     usbi_err (ctx, "device has no configurations");
739     return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
740   }
741
742   /* checking the configuration of a root hub simulation takes ~1 s in 10.11. the device is
743      not usable anyway */
744   if (0x05ac == libusb_le16_to_cpu (dev->dev_descriptor.idVendor) &&
745       0x8005 == libusb_le16_to_cpu (dev->dev_descriptor.idProduct)) {
746     usbi_dbg ("ignoring configuration on root hub simulation");
747     dev->active_config = 0;
748     return LIBUSB_SUCCESS;
749   }
750
751   /* find the first configuration */
752   kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
753   dev->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
754
755   /* check if the device is already configured. there is probably a better way than iterating over the
756      to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
757      might lock up on the device request) */
758
759   /* Setup the Interface Request */
760   request.bInterfaceClass    = kIOUSBFindInterfaceDontCare;
761   request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
762   request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
763   request.bAlternateSetting  = kIOUSBFindInterfaceDontCare;
764
765   kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
766   if (kresult != kIOReturnSuccess)
767     return darwin_to_libusb (kresult);
768
769   /* iterate once */
770   firstInterface = IOIteratorNext(interface_iterator);
771
772   /* done with the interface iterator */
773   IOObjectRelease(interface_iterator);
774
775   if (firstInterface) {
776     IOObjectRelease (firstInterface);
777
778     /* device is configured */
779     if (dev->dev_descriptor.bNumConfigurations == 1)
780       /* to avoid problems with some devices get the configurations value from the configuration descriptor */
781       dev->active_config = dev->first_config;
782     else
783       /* devices with more than one configuration should work with GetConfiguration */
784       (*darwin_device)->GetConfiguration (darwin_device, &dev->active_config);
785   } else
786     /* not configured */
787     dev->active_config = 0;
788
789   usbi_dbg ("active config: %u, first config: %u", dev->active_config, dev->first_config);
790
791   return LIBUSB_SUCCESS;
792 }
793
794 static IOReturn darwin_request_descriptor (usb_device_t **device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
795   IOUSBDevRequestTO req;
796
797   assert(buffer_size <= UINT16_MAX);
798
799   memset (buffer, 0, buffer_size);
800
801   /* Set up request for descriptor/ */
802   req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
803   req.bRequest      = kUSBRqGetDescriptor;
804   req.wValue        = (UInt16)(desc << 8);
805   req.wIndex        = desc_index;
806   req.wLength       = (UInt16)buffer_size;
807   req.pData         = buffer;
808   req.noDataTimeout = 20;
809   req.completionTimeout = 100;
810
811   return (*device)->DeviceRequestTO (device, &req);
812 }
813
814 static enum libusb_error darwin_cache_device_descriptor (struct darwin_cached_device *dev) {
815   usb_device_t **device = dev->device;
816   int retries = 1;
817   long delay = 30000; // microseconds
818   int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
819   int is_open = 0;
820   IOReturn ret = 0, ret2;
821   UInt8 bDeviceClass;
822   UInt16 idProduct, idVendor;
823
824   dev->can_enumerate = 0;
825
826   (*device)->GetDeviceClass (device, &bDeviceClass);
827   (*device)->GetDeviceProduct (device, &idProduct);
828   (*device)->GetDeviceVendor (device, &idVendor);
829
830   /* According to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
831    * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request.  Still,
832    * to follow the spec as closely as possible, try opening the device */
833   is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
834
835   do {
836     /**** retrieve device descriptor ****/
837     ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &dev->dev_descriptor, sizeof(dev->dev_descriptor));
838
839     if (kIOReturnOverrun == ret && kUSBDeviceDesc == dev->dev_descriptor.bDescriptorType)
840       /* received an overrun error but we still received a device descriptor */
841       ret = kIOReturnSuccess;
842
843     if (kIOUSBVendorIDAppleComputer == idVendor) {
844       /* NTH: don't bother retrying or unsuspending Apple devices */
845       break;
846     }
847
848     if (kIOReturnSuccess == ret && (0 == dev->dev_descriptor.bNumConfigurations ||
849                                     0 == dev->dev_descriptor.bcdUSB)) {
850       /* work around for incorrectly configured devices */
851       if (try_reconfigure && is_open) {
852         usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
853
854         /* set the first configuration */
855         (*device)->SetConfiguration(device, 1);
856
857         /* don't try to reconfigure again */
858         try_reconfigure = 0;
859       }
860
861       ret = kIOUSBPipeStalled;
862     }
863
864     if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
865       /* device may be suspended. unsuspend it and try again */
866 #if DeviceVersion >= 320
867       UInt32 info = 0;
868
869       /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
870       (void)(*device)->GetUSBDeviceInformation (device, &info);
871
872       /* note that the device was suspended */
873       if (info & (1U << kUSBInformationDeviceIsSuspendedBit) || 0 == info)
874         try_unsuspend = 1;
875 #endif
876
877       if (try_unsuspend) {
878         /* try to unsuspend the device */
879         ret2 = (*device)->USBDeviceSuspend (device, 0);
880         if (kIOReturnSuccess != ret2) {
881           /* prevent log spew from poorly behaving devices.  this indicates the
882              os actually had trouble communicating with the device */
883           usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
884         } else
885           unsuspended = 1;
886
887         try_unsuspend = 0;
888       }
889     }
890
891     if (kIOReturnSuccess != ret) {
892       usbi_dbg("kernel responded with code: 0x%08x. sleeping for %ld ms before trying again", ret, delay/1000);
893       /* sleep for a little while before trying again */
894       nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000}, NULL);
895     }
896   } while (kIOReturnSuccess != ret && retries--);
897
898   if (unsuspended)
899     /* resuspend the device */
900     (void)(*device)->USBDeviceSuspend (device, 1);
901
902   if (is_open)
903     (void) (*device)->USBDeviceClose (device);
904
905   if (ret != kIOReturnSuccess) {
906     /* a debug message was already printed out for this error */
907     if (LIBUSB_CLASS_HUB == bDeviceClass)
908       usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
909                 idVendor, idProduct, darwin_error_str (ret), ret);
910     else
911       usbi_warn (NULL, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
912                  idVendor, idProduct, darwin_error_str (ret), ret);
913     return darwin_to_libusb (ret);
914   }
915
916   /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
917   if (libusb_le16_to_cpu (dev->dev_descriptor.idProduct) != idProduct) {
918     /* not a valid device */
919     usbi_warn (NULL, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
920                idProduct, libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
921     return LIBUSB_ERROR_NO_DEVICE;
922   }
923
924   usbi_dbg ("cached device descriptor:");
925   usbi_dbg ("  bDescriptorType:    0x%02x", dev->dev_descriptor.bDescriptorType);
926   usbi_dbg ("  bcdUSB:             0x%04x", libusb_le16_to_cpu (dev->dev_descriptor.bcdUSB));
927   usbi_dbg ("  bDeviceClass:       0x%02x", dev->dev_descriptor.bDeviceClass);
928   usbi_dbg ("  bDeviceSubClass:    0x%02x", dev->dev_descriptor.bDeviceSubClass);
929   usbi_dbg ("  bDeviceProtocol:    0x%02x", dev->dev_descriptor.bDeviceProtocol);
930   usbi_dbg ("  bMaxPacketSize0:    0x%02x", dev->dev_descriptor.bMaxPacketSize0);
931   usbi_dbg ("  idVendor:           0x%04x", libusb_le16_to_cpu (dev->dev_descriptor.idVendor));
932   usbi_dbg ("  idProduct:          0x%04x", libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
933   usbi_dbg ("  bcdDevice:          0x%04x", libusb_le16_to_cpu (dev->dev_descriptor.bcdDevice));
934   usbi_dbg ("  iManufacturer:      0x%02x", dev->dev_descriptor.iManufacturer);
935   usbi_dbg ("  iProduct:           0x%02x", dev->dev_descriptor.iProduct);
936   usbi_dbg ("  iSerialNumber:      0x%02x", dev->dev_descriptor.iSerialNumber);
937   usbi_dbg ("  bNumConfigurations: 0x%02x", dev->dev_descriptor.bNumConfigurations);
938
939   dev->can_enumerate = 1;
940
941   return LIBUSB_SUCCESS;
942 }
943
944 /* Returns 1 on success, 0 on failure. */
945 static bool get_device_port (io_service_t service, UInt8 *port) {
946   IOReturn kresult;
947   io_service_t parent;
948   bool ret = false;
949
950   if (get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, port)) {
951     return true;
952   }
953
954   kresult = IORegistryEntryGetParentEntry (service, kIOServicePlane, &parent);
955   if (kIOReturnSuccess == kresult) {
956     ret = get_ioregistry_value_data (parent, CFSTR("port"), 1, port);
957     IOObjectRelease (parent);
958   }
959
960   return ret;
961 }
962
963 /* Returns 1 on success, 0 on failure. */
964 static bool get_device_parent_sessionID(io_service_t service, UInt64 *parent_sessionID) {
965   IOReturn kresult;
966   io_service_t parent;
967
968   /* Walk up the tree in the IOService plane until we find a parent that has a sessionID */
969   parent = service;
970   while((kresult = IORegistryEntryGetParentEntry (parent, kIOUSBPlane, &parent)) == kIOReturnSuccess) {
971     if (get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, parent_sessionID)) {
972         /* Success */
973         return true;
974     }
975   }
976
977   /* We ran out of parents */
978   return false;
979 }
980
981 static enum libusb_error darwin_get_cached_device(io_service_t service, struct darwin_cached_device **cached_out,
982                                                   UInt64 *old_session_id) {
983   struct darwin_cached_device *new_device;
984   UInt64 sessionID = 0, parent_sessionID = 0;
985   UInt32 locationID = 0;
986   enum libusb_error ret = LIBUSB_SUCCESS;
987   usb_device_t **device;
988   UInt8 port = 0;
989
990   /* assuming sessionID != 0 normally (never seen it be 0) */
991   *old_session_id = 0;
992   *cached_out = NULL;
993
994   /* get some info from the io registry */
995   (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
996   (void) get_ioregistry_value_number (service, CFSTR("locationID"), kCFNumberSInt32Type, &locationID);
997   if (!get_device_port (service, &port)) {
998     usbi_dbg("could not get connected port number");
999   }
1000
1001   usbi_dbg("finding cached device for sessionID 0x%" PRIx64, sessionID);
1002
1003   if (get_device_parent_sessionID(service, &parent_sessionID)) {
1004     usbi_dbg("parent sessionID: 0x%" PRIx64, parent_sessionID);
1005   }
1006
1007   usbi_mutex_lock(&darwin_cached_devices_lock);
1008   do {
1009     list_for_each_entry(new_device, &darwin_cached_devices, list, struct darwin_cached_device) {
1010       usbi_dbg("matching sessionID/locationID 0x%" PRIx64 "/0x%x against cached device with sessionID/locationID 0x%" PRIx64 "/0x%x",
1011                sessionID, locationID, new_device->session, new_device->location);
1012       if (new_device->location == locationID && new_device->in_reenumerate) {
1013         usbi_dbg ("found cached device with matching location that is being re-enumerated");
1014         *old_session_id = new_device->session;
1015         break;
1016       }
1017
1018       if (new_device->session == sessionID) {
1019         usbi_dbg("using cached device for device");
1020         *cached_out = new_device;
1021         break;
1022       }
1023     }
1024
1025     if (*cached_out)
1026       break;
1027
1028     usbi_dbg("caching new device with sessionID 0x%" PRIx64, sessionID);
1029
1030     device = darwin_device_from_service (service);
1031     if (!device) {
1032       ret = LIBUSB_ERROR_NO_DEVICE;
1033       break;
1034     }
1035
1036     if (!(*old_session_id)) {
1037       new_device = calloc (1, sizeof (*new_device));
1038       if (!new_device) {
1039         ret = LIBUSB_ERROR_NO_MEM;
1040         break;
1041       }
1042
1043       /* add this device to the cached device list */
1044       list_add(&new_device->list, &darwin_cached_devices);
1045
1046       (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
1047
1048       /* keep a reference to this device */
1049       darwin_ref_cached_device(new_device);
1050
1051       (*device)->GetLocationID (device, &new_device->location);
1052       new_device->port = port;
1053       new_device->parent_session = parent_sessionID;
1054     } else {
1055       /* release the ref to old device's service */
1056       IOObjectRelease (new_device->service);
1057     }
1058
1059     /* keep track of devices regardless of if we successfully enumerate them to
1060        prevent them from being enumerated multiple times */
1061     *cached_out = new_device;
1062
1063     new_device->session = sessionID;
1064     new_device->device = device;
1065     new_device->service = service;
1066
1067     /* retain the service */
1068     IOObjectRetain (service);
1069
1070     /* cache the device descriptor */
1071     ret = darwin_cache_device_descriptor(new_device);
1072     if (ret)
1073       break;
1074
1075     if (new_device->can_enumerate) {
1076       snprintf(new_device->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", new_device->address,
1077                libusb_le16_to_cpu (new_device->dev_descriptor.idVendor),
1078                libusb_le16_to_cpu (new_device->dev_descriptor.idProduct),
1079                new_device->dev_descriptor.bDeviceClass, new_device->dev_descriptor.bDeviceSubClass);
1080     }
1081   } while (0);
1082
1083   usbi_mutex_unlock(&darwin_cached_devices_lock);
1084
1085   return ret;
1086 }
1087
1088 static enum libusb_error process_new_device (struct libusb_context *ctx, struct darwin_cached_device *cached_device,
1089                                              UInt64 old_session_id) {
1090   struct darwin_device_priv *priv;
1091   struct libusb_device *dev = NULL;
1092   UInt8 devSpeed;
1093   enum libusb_error ret = LIBUSB_SUCCESS;
1094
1095   do {
1096     /* check current active configuration (and cache the first configuration value--
1097        which may be used by claim_interface) */
1098     ret = darwin_check_configuration (ctx, cached_device);
1099     if (ret)
1100       break;
1101
1102     if (0 != old_session_id) {
1103       usbi_dbg ("re-using existing device from context %p for with session 0x%" PRIx64 " new session 0x%" PRIx64,
1104                 ctx, old_session_id, cached_device->session);
1105       /* save the libusb device before the session id is updated */
1106       dev = usbi_get_device_by_session_id (ctx, (unsigned long) old_session_id);
1107     }
1108
1109     if (!dev) {
1110       usbi_dbg ("allocating new device in context %p for with session 0x%" PRIx64,
1111                 ctx, cached_device->session);
1112
1113       dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
1114       if (!dev) {
1115         return LIBUSB_ERROR_NO_MEM;
1116       }
1117
1118       priv = usbi_get_device_priv(dev);
1119
1120       priv->dev = cached_device;
1121       darwin_ref_cached_device (priv->dev);
1122       dev->port_number    = cached_device->port;
1123       dev->bus_number     = cached_device->location >> 24;
1124       assert(cached_device->address <= UINT8_MAX);
1125       dev->device_address = (uint8_t)cached_device->address;
1126     } else {
1127       priv = usbi_get_device_priv(dev);
1128     }
1129
1130     static_assert(sizeof(dev->device_descriptor) == sizeof(cached_device->dev_descriptor),
1131                   "mismatch between libusb and IOKit device descriptor sizes");
1132     memcpy(&dev->device_descriptor, &cached_device->dev_descriptor, LIBUSB_DT_DEVICE_SIZE);
1133     usbi_localize_device_descriptor(&dev->device_descriptor);
1134     dev->session_data = cached_device->session;
1135
1136     if (NULL != dev->parent_dev) {
1137       libusb_unref_device(dev->parent_dev);
1138       dev->parent_dev = NULL;
1139     }
1140
1141     if (cached_device->parent_session > 0) {
1142       dev->parent_dev = usbi_get_device_by_session_id (ctx, (unsigned long) cached_device->parent_session);
1143     }
1144
1145     (*(priv->dev->device))->GetDeviceSpeed (priv->dev->device, &devSpeed);
1146
1147     switch (devSpeed) {
1148     case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
1149     case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
1150     case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
1151 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1080
1152     case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
1153 #endif
1154 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101200
1155     case kUSBDeviceSpeedSuperPlus: dev->speed = LIBUSB_SPEED_SUPER_PLUS; break;
1156 #endif
1157     default:
1158       usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
1159     }
1160
1161     ret = usbi_sanitize_device (dev);
1162     if (ret < 0)
1163       break;
1164
1165     usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address,
1166               dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path);
1167
1168   } while (0);
1169
1170   if (!cached_device->in_reenumerate && 0 == ret) {
1171     usbi_connect_device (dev);
1172   } else {
1173     libusb_unref_device (dev);
1174   }
1175
1176   return ret;
1177 }
1178
1179 static enum libusb_error darwin_scan_devices(struct libusb_context *ctx) {
1180   struct darwin_cached_device *cached_device;
1181   UInt64 old_session_id;
1182   io_iterator_t deviceIterator;
1183   io_service_t service;
1184   IOReturn kresult;
1185   int ret;
1186
1187   kresult = usb_setup_device_iterator (&deviceIterator, 0);
1188   if (kresult != kIOReturnSuccess)
1189     return darwin_to_libusb (kresult);
1190
1191   while ((service = IOIteratorNext (deviceIterator))) {
1192     ret = darwin_get_cached_device (service, &cached_device, &old_session_id);
1193     if (ret < 0 || !cached_device->can_enumerate) {
1194       continue;
1195     }
1196
1197     (void) process_new_device (ctx, cached_device, old_session_id);
1198
1199     IOObjectRelease(service);
1200   }
1201
1202   IOObjectRelease(deviceIterator);
1203
1204   return LIBUSB_SUCCESS;
1205 }
1206
1207 static int darwin_open (struct libusb_device_handle *dev_handle) {
1208   struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1209   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1210   IOReturn kresult;
1211
1212   if (0 == dpriv->open_count) {
1213     /* try to open the device */
1214     kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
1215     if (kresult != kIOReturnSuccess) {
1216       usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
1217
1218       if (kIOReturnExclusiveAccess != kresult) {
1219         return darwin_to_libusb (kresult);
1220       }
1221
1222       /* it is possible to perform some actions on a device that is not open so do not return an error */
1223       priv->is_open = false;
1224     } else {
1225       priv->is_open = true;
1226     }
1227
1228     /* create async event source */
1229     kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
1230     if (kresult != kIOReturnSuccess) {
1231       usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
1232
1233       if (priv->is_open) {
1234         (*(dpriv->device))->USBDeviceClose (dpriv->device);
1235       }
1236
1237       priv->is_open = false;
1238
1239       return darwin_to_libusb (kresult);
1240     }
1241
1242     CFRetain (libusb_darwin_acfl);
1243
1244     /* add the cfSource to the aync run loop */
1245     CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
1246   }
1247
1248   /* device opened successfully */
1249   dpriv->open_count++;
1250
1251   usbi_dbg ("device open for access");
1252
1253   return 0;
1254 }
1255
1256 static void darwin_close (struct libusb_device_handle *dev_handle) {
1257   struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1258   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1259   IOReturn kresult;
1260   int i;
1261
1262   if (dpriv->open_count == 0) {
1263     /* something is probably very wrong if this is the case */
1264     usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!");
1265     return;
1266   }
1267
1268   dpriv->open_count--;
1269   if (NULL == dpriv->device) {
1270     usbi_warn (HANDLE_CTX (dev_handle), "darwin_close device missing IOService");
1271     return;
1272   }
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   int i;
1576   uint8_t old_alt_setting;
1577
1578   /* current interface */
1579   struct darwin_interface *cInterface = &priv->interfaces[iface];
1580
1581   if (!cInterface->interface)
1582     return LIBUSB_ERROR_NO_DEVICE;
1583
1584   kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1585   if (kresult == kIOReturnSuccess) {
1586     /* update the list of endpoints */
1587     ret = get_endpoints (dev_handle, iface);
1588     if (ret) {
1589       /* this should not happen */
1590       darwin_release_interface (dev_handle, iface);
1591       usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1592     }
1593     return ret;
1594   }
1595   else
1596     usbi_warn (HANDLE_CTX (dev_handle), "SetAlternateInterface: %s", darwin_error_str(kresult));
1597
1598   if (kresult != kIOUSBPipeStalled)
1599     return darwin_to_libusb (kresult);
1600
1601   /* If a device only supports a default setting for the specified interface, then a STALL
1602      (kIOUSBPipeStalled) may be returned. Ref: USB 2.0 specs 9.4.10.
1603      Mimick the behaviour in e.g. the Linux kernel: in such case, reset all endpoints
1604      of the interface (as would have been done per 9.1.1.5) and return success. */
1605
1606   /* For some reason we need to reclaim the interface after the pipe error */
1607   ret = darwin_claim_interface (dev_handle, iface);
1608
1609   if (ret) {
1610     darwin_release_interface (dev_handle, iface);
1611     usbi_err (HANDLE_CTX (dev_handle), "could not reclaim interface");
1612   }
1613
1614   /* Return error if a change to another value was attempted */
1615   kresult = (*(cInterface->interface))->GetAlternateSetting (cInterface->interface, &old_alt_setting);
1616   if (kresult == kIOReturnSuccess && altsetting != old_alt_setting)
1617     return LIBUSB_ERROR_PIPE;
1618
1619   for (i = 0 ; i < cInterface->num_endpoints ; i++)
1620     darwin_clear_halt(dev_handle, cInterface->endpoint_addrs[i]);
1621
1622   return LIBUSB_SUCCESS;
1623 }
1624
1625 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1626   /* current interface */
1627   struct darwin_interface *cInterface;
1628   IOReturn kresult;
1629   uint8_t pipeRef;
1630
1631   /* determine the interface/endpoint to use */
1632   if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, NULL, &cInterface) != 0) {
1633     usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1634
1635     return LIBUSB_ERROR_NOT_FOUND;
1636   }
1637
1638   /* newer versions of darwin support clearing additional bits on the device's endpoint */
1639   kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1640   if (kresult != kIOReturnSuccess)
1641     usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1642
1643   return darwin_to_libusb (kresult);
1644 }
1645
1646 static int darwin_restore_state (struct libusb_device_handle *dev_handle, int8_t active_config,
1647                                  unsigned long claimed_interfaces) {
1648   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1649   struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1650   int open_count = dpriv->open_count;
1651   int ret;
1652
1653   /* clear claimed interfaces temporarily */
1654   dev_handle->claimed_interfaces = 0;
1655
1656   /* close and re-open the device */
1657   priv->is_open = false;
1658   dpriv->open_count = 1;
1659
1660   /* clean up open interfaces */
1661   (void) darwin_close (dev_handle);
1662
1663   /* re-open the device */
1664   ret = darwin_open (dev_handle);
1665   dpriv->open_count = open_count;
1666   if (LIBUSB_SUCCESS != ret) {
1667     /* could not restore configuration */
1668     return LIBUSB_ERROR_NOT_FOUND;
1669   }
1670
1671   if (dpriv->active_config != active_config) {
1672     usbi_dbg ("darwin/restore_state: restoring configuration %d...", active_config);
1673
1674     ret = darwin_set_configuration (dev_handle, active_config);
1675     if (LIBUSB_SUCCESS != ret) {
1676       usbi_dbg ("darwin/restore_state: could not restore configuration");
1677       return LIBUSB_ERROR_NOT_FOUND;
1678     }
1679   }
1680
1681   usbi_dbg ("darwin/restore_state: reclaiming interfaces");
1682
1683   if (claimed_interfaces) {
1684     for (uint8_t iface = 0 ; iface < USB_MAXINTERFACES ; ++iface) {
1685       if (!(claimed_interfaces & (1U << iface))) {
1686         continue;
1687       }
1688
1689       usbi_dbg ("darwin/restore_state: re-claiming interface %u", iface);
1690
1691       ret = darwin_claim_interface (dev_handle, iface);
1692       if (LIBUSB_SUCCESS != ret) {
1693         usbi_dbg ("darwin/restore_state: could not claim interface %u", iface);
1694         return LIBUSB_ERROR_NOT_FOUND;
1695       }
1696
1697       dev_handle->claimed_interfaces |= 1U << iface;
1698     }
1699   }
1700
1701   usbi_dbg ("darwin/restore_state: device state restored");
1702
1703   return LIBUSB_SUCCESS;
1704 }
1705
1706 static int darwin_reenumerate_device (struct libusb_device_handle *dev_handle, bool capture) {
1707   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1708   unsigned long claimed_interfaces = dev_handle->claimed_interfaces;
1709   int8_t active_config = dpriv->active_config;
1710   UInt32 options = 0;
1711   IOUSBDeviceDescriptor descriptor;
1712   IOUSBConfigurationDescriptorPtr cached_configuration;
1713   IOUSBConfigurationDescriptor *cached_configurations;
1714   IOReturn kresult;
1715   UInt8 i;
1716   UInt32 time;
1717
1718   if (dpriv->in_reenumerate) {
1719     /* ack, two (or more) threads are trying to reset the device! abort! */
1720     return LIBUSB_ERROR_NOT_FOUND;
1721   }
1722
1723   dpriv->in_reenumerate = true;
1724
1725   /* store copies of descriptors so they can be compared after the reset */
1726   memcpy (&descriptor, &dpriv->dev_descriptor, sizeof (descriptor));
1727   cached_configurations = alloca (sizeof (*cached_configurations) * descriptor.bNumConfigurations);
1728
1729   for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1730     (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1731     memcpy (cached_configurations + i, cached_configuration, sizeof (cached_configurations[i]));
1732   }
1733
1734   /* if we need to release capture */
1735   if (HAS_CAPTURE_DEVICE()) {
1736     if (capture) {
1737       options |= kUSBReEnumerateCaptureDeviceMask;
1738     }
1739   } else {
1740     capture = false;
1741   }
1742
1743   /* from macOS 10.11 ResetDevice no longer does anything so just use USBDeviceReEnumerate */
1744   kresult = (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, options);
1745   if (kresult != kIOReturnSuccess) {
1746     usbi_err (HANDLE_CTX (dev_handle), "USBDeviceReEnumerate: %s", darwin_error_str (kresult));
1747     dpriv->in_reenumerate = false;
1748     return darwin_to_libusb (kresult);
1749   }
1750
1751   /* capture mode does not re-enumerate but it does require re-open */
1752   if (capture) {
1753     usbi_dbg ("darwin/reenumerate_device: restoring state...");
1754     dpriv->in_reenumerate = false;
1755     return darwin_restore_state (dev_handle, active_config, claimed_interfaces);
1756   }
1757
1758   usbi_dbg ("darwin/reenumerate_device: waiting for re-enumeration to complete...");
1759
1760   time = 0;
1761   while (dpriv->in_reenumerate) {
1762     struct timespec delay = {.tv_sec = 0, .tv_nsec = 1000};
1763     nanosleep (&delay, NULL);
1764     if (time++ >= DARWIN_REENUMERATE_TIMEOUT_US) {
1765       usbi_err (HANDLE_CTX (dev_handle), "darwin/reenumerate_device: timeout waiting for reenumerate");
1766       dpriv->in_reenumerate = false;
1767       return LIBUSB_ERROR_TIMEOUT;
1768     }
1769   }
1770
1771   /* compare descriptors */
1772   usbi_dbg ("darwin/reenumerate_device: checking whether descriptors changed");
1773
1774   if (memcmp (&descriptor, &dpriv->dev_descriptor, sizeof (descriptor))) {
1775     /* device descriptor changed. need to return not found. */
1776     usbi_dbg ("darwin/reenumerate_device: device descriptor changed");
1777     return LIBUSB_ERROR_NOT_FOUND;
1778   }
1779
1780   for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1781     (void) (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1782     if (memcmp (cached_configuration, cached_configurations + i, sizeof (cached_configurations[i]))) {
1783       usbi_dbg ("darwin/reenumerate_device: configuration descriptor %d changed", i);
1784       return LIBUSB_ERROR_NOT_FOUND;
1785     }
1786   }
1787
1788   usbi_dbg ("darwin/reenumerate_device: device reset complete. restoring state...");
1789
1790   return darwin_restore_state (dev_handle, active_config, claimed_interfaces);
1791 }
1792
1793 static int darwin_reset_device (struct libusb_device_handle *dev_handle) {
1794   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1795   IOReturn kresult;
1796
1797   if (dpriv->capture_count > 0) {
1798     /* we have to use ResetDevice as USBDeviceReEnumerate() loses the authorization for capture */
1799     kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1800     return darwin_to_libusb (kresult);
1801   } else {
1802     return darwin_reenumerate_device (dev_handle, false);
1803   }
1804 }
1805
1806 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, uint8_t interface) {
1807   enum libusb_error ret = darwin_claim_interface (dev_handle, interface);
1808   if (ret == LIBUSB_SUCCESS) {
1809     darwin_release_interface (dev_handle, interface);
1810   }
1811   return (ret == LIBUSB_ERROR_ACCESS);
1812 }
1813
1814 static void darwin_destroy_device(struct libusb_device *dev) {
1815   struct darwin_device_priv *dpriv = usbi_get_device_priv(dev);
1816
1817   if (dpriv->dev) {
1818     /* need to hold the lock in case this is the last reference to the device */
1819     usbi_mutex_lock(&darwin_cached_devices_lock);
1820     darwin_deref_cached_device (dpriv->dev);
1821     dpriv->dev = NULL;
1822     usbi_mutex_unlock(&darwin_cached_devices_lock);
1823   }
1824 }
1825
1826 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1827   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1828
1829   IOReturn               ret;
1830   uint8_t                transferType;
1831   uint8_t                pipeRef;
1832   uint16_t               maxPacketSize;
1833
1834   struct darwin_interface *cInterface;
1835 #if InterfaceVersion >= 550
1836   IOUSBEndpointProperties pipeProperties = {.bVersion = kUSBEndpointPropertiesVersion3};
1837 #else
1838   /* None of the values below are used in libusb for bulk transfers */
1839   uint8_t                 direction, number, interval;
1840 #endif
1841
1842   if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1843     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1844
1845     return LIBUSB_ERROR_NOT_FOUND;
1846   }
1847
1848 #if InterfaceVersion >= 550
1849   ret = (*(cInterface->interface))->GetPipePropertiesV3 (cInterface->interface, pipeRef, &pipeProperties);
1850
1851   transferType = pipeProperties.bTransferType;
1852   maxPacketSize = pipeProperties.wMaxPacketSize;
1853 #else
1854   ret = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1855                                                        &transferType, &maxPacketSize, &interval);
1856 #endif
1857
1858   if (ret) {
1859     usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1860               darwin_error_str(ret), ret);
1861     return darwin_to_libusb (ret);
1862   }
1863
1864   if (0 != (transfer->length % maxPacketSize)) {
1865     /* do not need a zero packet */
1866     transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1867   }
1868
1869   /* submit the request */
1870   /* timeouts are unavailable on interrupt endpoints */
1871   if (transferType == kUSBInterrupt) {
1872     if (IS_XFERIN(transfer))
1873       ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1874                                                       (UInt32)transfer->length, darwin_async_io_callback, itransfer);
1875     else
1876       ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1877                                                        (UInt32)transfer->length, darwin_async_io_callback, itransfer);
1878   } else {
1879     itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1880
1881     if (IS_XFERIN(transfer))
1882       ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1883                                                         (UInt32)transfer->length, transfer->timeout, transfer->timeout,
1884                                                         darwin_async_io_callback, itransfer);
1885     else
1886       ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1887                                                          (UInt32)transfer->length, transfer->timeout, transfer->timeout,
1888                                                          darwin_async_io_callback, itransfer);
1889   }
1890
1891   if (ret)
1892     usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1893                darwin_error_str(ret), ret);
1894
1895   return darwin_to_libusb (ret);
1896 }
1897
1898 #if InterfaceVersion >= 550
1899 static int submit_stream_transfer(struct usbi_transfer *itransfer) {
1900   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1901   struct darwin_interface *cInterface;
1902   uint8_t pipeRef;
1903   IOReturn ret;
1904
1905   if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1906     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1907
1908     return LIBUSB_ERROR_NOT_FOUND;
1909   }
1910
1911   itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1912
1913   if (IS_XFERIN(transfer))
1914     ret = (*(cInterface->interface))->ReadStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1915                                                              transfer->buffer, (UInt32)transfer->length, transfer->timeout,
1916                                                              transfer->timeout, darwin_async_io_callback, itransfer);
1917   else
1918     ret = (*(cInterface->interface))->WriteStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1919                                                               transfer->buffer, (UInt32)transfer->length, transfer->timeout,
1920                                                               transfer->timeout, darwin_async_io_callback, itransfer);
1921
1922   if (ret)
1923     usbi_err (TRANSFER_CTX (transfer), "bulk stream transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1924                darwin_error_str(ret), ret);
1925
1926   return darwin_to_libusb (ret);
1927 }
1928 #endif
1929
1930 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1931   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1932   struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
1933
1934   IOReturn kresult;
1935   uint8_t direction, number, interval, pipeRef, transferType;
1936   uint16_t maxPacketSize;
1937   UInt64 frame;
1938   AbsoluteTime atTime;
1939   int i;
1940
1941   struct darwin_interface *cInterface;
1942
1943   /* construct an array of IOUSBIsocFrames, reuse the old one if the sizes are the same */
1944   if (tpriv->num_iso_packets != transfer->num_iso_packets) {
1945     free(tpriv->isoc_framelist);
1946     tpriv->isoc_framelist = NULL;
1947   }
1948
1949   if (!tpriv->isoc_framelist) {
1950     tpriv->num_iso_packets = transfer->num_iso_packets;
1951     tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc ((size_t)transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1952     if (!tpriv->isoc_framelist)
1953       return LIBUSB_ERROR_NO_MEM;
1954   }
1955
1956   /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1957   for (i = 0 ; i < transfer->num_iso_packets ; i++) {
1958     unsigned int length = transfer->iso_packet_desc[i].length;
1959     assert(length <= UINT16_MAX);
1960     tpriv->isoc_framelist[i].frReqCount = (UInt16)length;
1961   }
1962
1963   /* determine the interface/endpoint to use */
1964   if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1965     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1966
1967     return LIBUSB_ERROR_NOT_FOUND;
1968   }
1969
1970   /* determine the properties of this endpoint and the speed of the device */
1971   (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1972                                                  &transferType, &maxPacketSize, &interval);
1973
1974   /* Last but not least we need the bus frame number */
1975   kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1976   if (kresult != kIOReturnSuccess) {
1977     usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1978     free(tpriv->isoc_framelist);
1979     tpriv->isoc_framelist = NULL;
1980
1981     return darwin_to_libusb (kresult);
1982   }
1983
1984   (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1985                                                  &transferType, &maxPacketSize, &interval);
1986
1987   /* schedule for a frame a little in the future */
1988   frame += 4;
1989
1990   if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1991     frame = cInterface->frames[transfer->endpoint];
1992
1993   /* submit the request */
1994   if (IS_XFERIN(transfer))
1995     kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1996                                                              (UInt32)transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1997                                                              itransfer);
1998   else
1999     kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
2000                                                               (UInt32)transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
2001                                                               itransfer);
2002
2003   if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
2004     /* Full speed */
2005     cInterface->frames[transfer->endpoint] = frame + (UInt32)transfer->num_iso_packets * (1U << (interval - 1));
2006   else
2007     /* High/super speed */
2008     cInterface->frames[transfer->endpoint] = frame + (UInt32)transfer->num_iso_packets * (1U << (interval - 1)) / 8;
2009
2010   if (kresult != kIOReturnSuccess) {
2011     usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
2012                darwin_error_str(kresult));
2013     free (tpriv->isoc_framelist);
2014     tpriv->isoc_framelist = NULL;
2015   }
2016
2017   return darwin_to_libusb (kresult);
2018 }
2019
2020 static int submit_control_transfer(struct usbi_transfer *itransfer) {
2021   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2022   struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
2023   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
2024   struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2025
2026   IOReturn               kresult;
2027
2028   memset(&tpriv->req, 0, sizeof(tpriv->req));
2029
2030   /* IOUSBDeviceInterface expects the request in cpu endianness */
2031   tpriv->req.bmRequestType     = setup->bmRequestType;
2032   tpriv->req.bRequest          = setup->bRequest;
2033   /* these values should be in bus order from libusb_fill_control_setup */
2034   tpriv->req.wValue            = OSSwapLittleToHostInt16 (setup->wValue);
2035   tpriv->req.wIndex            = OSSwapLittleToHostInt16 (setup->wIndex);
2036   tpriv->req.wLength           = OSSwapLittleToHostInt16 (setup->wLength);
2037   /* data is stored after the libusb control block */
2038   tpriv->req.pData             = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
2039   tpriv->req.completionTimeout = transfer->timeout;
2040   tpriv->req.noDataTimeout     = transfer->timeout;
2041
2042   itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
2043
2044   /* all transfers in libusb-1.0 are async */
2045
2046   if (transfer->endpoint) {
2047     struct darwin_interface *cInterface;
2048     uint8_t                 pipeRef;
2049
2050     if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
2051       usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
2052
2053       return LIBUSB_ERROR_NOT_FOUND;
2054     }
2055
2056     kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
2057   } else
2058     /* control request on endpoint 0 */
2059     kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
2060
2061   if (kresult != kIOReturnSuccess)
2062     usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
2063
2064   return darwin_to_libusb (kresult);
2065 }
2066
2067 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
2068   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2069
2070   switch (transfer->type) {
2071   case LIBUSB_TRANSFER_TYPE_CONTROL:
2072     return submit_control_transfer(itransfer);
2073   case LIBUSB_TRANSFER_TYPE_BULK:
2074   case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2075     return submit_bulk_transfer(itransfer);
2076   case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2077     return submit_iso_transfer(itransfer);
2078   case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2079 #if InterfaceVersion >= 550
2080     return submit_stream_transfer(itransfer);
2081 #else
2082     usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version does not support bulk stream transfers");
2083     return LIBUSB_ERROR_NOT_SUPPORTED;
2084 #endif
2085   default:
2086     usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
2087     return LIBUSB_ERROR_INVALID_PARAM;
2088   }
2089 }
2090
2091 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
2092   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2093   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
2094   IOReturn kresult;
2095
2096   usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
2097
2098   if (!dpriv->device)
2099     return LIBUSB_ERROR_NO_DEVICE;
2100
2101   kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
2102
2103   return darwin_to_libusb (kresult);
2104 }
2105
2106 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
2107   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2108   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
2109   struct darwin_interface *cInterface;
2110   uint8_t pipeRef, iface;
2111   IOReturn kresult;
2112
2113   if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface, &cInterface) != 0) {
2114     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
2115
2116     return LIBUSB_ERROR_NOT_FOUND;
2117   }
2118
2119   if (!dpriv->device)
2120     return LIBUSB_ERROR_NO_DEVICE;
2121
2122   usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
2123
2124   /* abort transactions */
2125 #if InterfaceVersion >= 550
2126   if (LIBUSB_TRANSFER_TYPE_BULK_STREAM == transfer->type)
2127     (*(cInterface->interface))->AbortStreamsPipe (cInterface->interface, pipeRef, itransfer->stream_id);
2128   else
2129 #endif
2130     (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
2131
2132   usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
2133
2134   /* newer versions of darwin support clearing additional bits on the device's endpoint */
2135   kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
2136
2137   return darwin_to_libusb (kresult);
2138 }
2139
2140 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
2141   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2142
2143   switch (transfer->type) {
2144   case LIBUSB_TRANSFER_TYPE_CONTROL:
2145     return cancel_control_transfer(itransfer);
2146   case LIBUSB_TRANSFER_TYPE_BULK:
2147   case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2148   case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2149     return darwin_abort_transfers (itransfer);
2150   default:
2151     usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
2152     return LIBUSB_ERROR_INVALID_PARAM;
2153   }
2154 }
2155
2156 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
2157   struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
2158   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2159   struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2160
2161   usbi_dbg ("an async io operation has completed");
2162
2163   /* if requested write a zero packet */
2164   if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
2165     struct darwin_interface *cInterface;
2166     uint8_t pipeRef;
2167
2168     (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface);
2169
2170     (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
2171   }
2172
2173   tpriv->result = result;
2174   tpriv->size = (UInt32) (uintptr_t) arg0;
2175
2176   /* signal the core that this transfer is complete */
2177   usbi_signal_transfer_completion(itransfer);
2178 }
2179
2180 static enum libusb_transfer_status darwin_transfer_status (struct usbi_transfer *itransfer, IOReturn result) {
2181   if (itransfer->timeout_flags & USBI_TRANSFER_TIMED_OUT)
2182     result = kIOUSBTransactionTimeout;
2183
2184   switch (result) {
2185   case kIOReturnUnderrun:
2186   case kIOReturnSuccess:
2187     return LIBUSB_TRANSFER_COMPLETED;
2188   case kIOReturnAborted:
2189     return LIBUSB_TRANSFER_CANCELLED;
2190   case kIOUSBPipeStalled:
2191     usbi_dbg ("transfer error: pipe is stalled");
2192     return LIBUSB_TRANSFER_STALL;
2193   case kIOReturnOverrun:
2194     usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
2195     return LIBUSB_TRANSFER_OVERFLOW;
2196   case kIOUSBTransactionTimeout:
2197     usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
2198     itransfer->timeout_flags |= USBI_TRANSFER_TIMED_OUT;
2199     return LIBUSB_TRANSFER_TIMED_OUT;
2200   default:
2201     usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
2202     return LIBUSB_TRANSFER_ERROR;
2203   }
2204 }
2205
2206 static int darwin_handle_transfer_completion (struct usbi_transfer *itransfer) {
2207   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2208   struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2209   const unsigned char max_transfer_type = LIBUSB_TRANSFER_TYPE_BULK_STREAM;
2210   const char *transfer_types[] = {"control", "isoc", "bulk", "interrupt", "bulk-stream", NULL};
2211   bool is_isoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
2212
2213   if (transfer->type > max_transfer_type) {
2214     usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
2215     return LIBUSB_ERROR_INVALID_PARAM;
2216   }
2217
2218   if (NULL == tpriv) {
2219     usbi_err (TRANSFER_CTX(transfer), "malformed request is missing transfer priv");
2220     return LIBUSB_ERROR_INVALID_PARAM;
2221   }
2222
2223   usbi_dbg ("handling transfer completion type %s with kernel status %d", transfer_types[transfer->type], tpriv->result);
2224
2225   if (kIOReturnSuccess == tpriv->result || kIOReturnUnderrun == tpriv->result || kIOUSBTransactionTimeout == tpriv->result) {
2226     if (is_isoc && tpriv->isoc_framelist) {
2227       /* copy isochronous results back */
2228
2229       for (int i = 0; i < transfer->num_iso_packets ; i++) {
2230         struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
2231         lib_desc->status = darwin_transfer_status (itransfer, tpriv->isoc_framelist[i].frStatus);
2232         lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
2233       }
2234     } else if (!is_isoc) {
2235       itransfer->transferred += tpriv->size;
2236     }
2237   }
2238
2239   /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
2240   return usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, tpriv->result));
2241 }
2242
2243 #if !defined(HAVE_CLOCK_GETTIME)
2244 void usbi_get_monotonic_time(struct timespec *tp) {
2245   mach_timespec_t sys_time;
2246
2247   /* use system boot time as reference for the monotonic clock */
2248   clock_get_time (clock_monotonic, &sys_time);
2249
2250   tp->tv_sec  = sys_time.tv_sec;
2251   tp->tv_nsec = sys_time.tv_nsec;
2252 }
2253
2254 void usbi_get_real_time(struct timespec *tp) {
2255   mach_timespec_t sys_time;
2256
2257   /* CLOCK_REALTIME represents time since the epoch */
2258   clock_get_time (clock_realtime, &sys_time);
2259
2260   tp->tv_sec  = sys_time.tv_sec;
2261   tp->tv_nsec = sys_time.tv_nsec;
2262 }
2263 #endif
2264
2265 #if InterfaceVersion >= 550
2266 static int darwin_alloc_streams (struct libusb_device_handle *dev_handle, uint32_t num_streams, unsigned char *endpoints,
2267                                  int num_endpoints) {
2268   struct darwin_interface *cInterface;
2269   UInt32 supportsStreams;
2270   uint8_t pipeRef;
2271   int rc, i;
2272
2273   /* find the minimum number of supported streams on the endpoint list */
2274   for (i = 0 ; i < num_endpoints ; ++i) {
2275     if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface))) {
2276       return rc;
2277     }
2278
2279     (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2280     if (num_streams > supportsStreams)
2281       num_streams = supportsStreams;
2282   }
2283
2284   /* it is an error if any endpoint in endpoints does not support streams */
2285   if (0 == num_streams)
2286     return LIBUSB_ERROR_INVALID_PARAM;
2287
2288   /* create the streams */
2289   for (i = 0 ; i < num_endpoints ; ++i) {
2290     (void) ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
2291
2292     rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, num_streams);
2293     if (kIOReturnSuccess != rc)
2294       return darwin_to_libusb(rc);
2295   }
2296
2297   assert(num_streams <= INT_MAX);
2298   return (int)num_streams;
2299 }
2300
2301 static int darwin_free_streams (struct libusb_device_handle *dev_handle, unsigned char *endpoints, int num_endpoints) {
2302   struct darwin_interface *cInterface;
2303   UInt32 supportsStreams;
2304   uint8_t pipeRef;
2305   int rc;
2306
2307   for (int i = 0 ; i < num_endpoints ; ++i) {
2308     if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface)))
2309       return rc;
2310
2311     (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2312     if (0 == supportsStreams)
2313       return LIBUSB_ERROR_INVALID_PARAM;
2314
2315     rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, 0);
2316     if (kIOReturnSuccess != rc)
2317       return darwin_to_libusb(rc);
2318   }
2319
2320   return LIBUSB_SUCCESS;
2321 }
2322 #endif
2323
2324 #if InterfaceVersion >= 700
2325
2326 /* macOS APIs for getting entitlement values */
2327
2328 #if TARGET_OS_OSX
2329 #include <Security/Security.h>
2330 #else
2331 typedef struct __SecTask *SecTaskRef;
2332 extern SecTaskRef SecTaskCreateFromSelf(CFAllocatorRef allocator);
2333 extern CFTypeRef SecTaskCopyValueForEntitlement(SecTaskRef task, CFStringRef entitlement, CFErrorRef *error);
2334 #endif
2335
2336 static bool darwin_has_capture_entitlements (void) {
2337   SecTaskRef task;
2338   CFTypeRef value;
2339   bool entitled;
2340
2341   task = SecTaskCreateFromSelf (kCFAllocatorDefault);
2342   if (task == NULL) {
2343     return false;
2344   }
2345   value = SecTaskCopyValueForEntitlement(task, CFSTR("com.apple.vm.device-access"), NULL);
2346   CFRelease (task);
2347   entitled = value && (CFGetTypeID (value) == CFBooleanGetTypeID ()) && CFBooleanGetValue (value);
2348   if (value) {
2349     CFRelease (value);
2350   }
2351   return entitled;
2352 }
2353
2354 static int darwin_reload_device (struct libusb_device_handle *dev_handle) {
2355   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
2356   enum libusb_error err;
2357
2358   usbi_mutex_lock(&darwin_cached_devices_lock);
2359   (*(dpriv->device))->Release(dpriv->device);
2360   dpriv->device = darwin_device_from_service (dpriv->service);
2361   if (!dpriv->device) {
2362     err = LIBUSB_ERROR_NO_DEVICE;
2363   } else {
2364     err = LIBUSB_SUCCESS;
2365   }
2366   usbi_mutex_unlock(&darwin_cached_devices_lock);
2367
2368   return err;
2369 }
2370
2371 /* On macOS, we capture an entire device at once, not individual interfaces. */
2372
2373 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, uint8_t interface) {
2374   UNUSED(interface);
2375   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
2376   IOReturn kresult;
2377   enum libusb_error err;
2378
2379   if (HAS_CAPTURE_DEVICE()) {
2380   } else {
2381     return LIBUSB_ERROR_NOT_SUPPORTED;
2382   }
2383
2384   if (dpriv->capture_count == 0) {
2385     usbi_dbg ("attempting to detach kernel driver from device");
2386
2387     if (!darwin_has_capture_entitlements ()) {
2388       usbi_warn (HANDLE_CTX (dev_handle), "no capture entitlements. can not detach the kernel driver for this device");
2389       return LIBUSB_ERROR_NOT_SUPPORTED;
2390     }
2391
2392     /* request authorization */
2393     kresult = IOServiceAuthorize (dpriv->service, kIOServiceInteractionAllowed);
2394     if (kresult != kIOReturnSuccess) {
2395       usbi_err (HANDLE_CTX (dev_handle), "IOServiceAuthorize: %s", darwin_error_str(kresult));
2396       return darwin_to_libusb (kresult);
2397     }
2398
2399     /* we need start() to be called again for authorization status to refresh */
2400     err = darwin_reload_device (dev_handle);
2401     if (err != LIBUSB_SUCCESS) {
2402       return err;
2403     }
2404
2405     /* reset device to release existing drivers */
2406     err = darwin_reenumerate_device (dev_handle, true);
2407     if (err != LIBUSB_SUCCESS) {
2408       return err;
2409     }
2410   }
2411   dpriv->capture_count++;
2412   return LIBUSB_SUCCESS;
2413 }
2414
2415
2416 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, uint8_t interface) {
2417   UNUSED(interface);
2418   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
2419
2420   if (HAS_CAPTURE_DEVICE()) {
2421   } else {
2422     return LIBUSB_ERROR_NOT_SUPPORTED;
2423   }
2424
2425   dpriv->capture_count--;
2426   if (dpriv->capture_count > 0) {
2427     return LIBUSB_SUCCESS;
2428   }
2429
2430   usbi_dbg ("reenumerating device for kernel driver attach");
2431
2432   /* reset device to attach kernel drivers */
2433   return darwin_reenumerate_device (dev_handle, false);
2434 }
2435
2436 static int darwin_capture_claim_interface(struct libusb_device_handle *dev_handle, uint8_t iface) {
2437   enum libusb_error ret;
2438   if (dev_handle->auto_detach_kernel_driver) {
2439     ret = darwin_detach_kernel_driver (dev_handle, iface);
2440     if (ret != LIBUSB_SUCCESS) {
2441       usbi_warn (HANDLE_CTX (dev_handle), "failed to auto-detach the kernel driver for this device, ret=%d", ret);
2442     }
2443   }
2444
2445   return darwin_claim_interface (dev_handle, iface);
2446 }
2447
2448 static int darwin_capture_release_interface(struct libusb_device_handle *dev_handle, uint8_t iface) {
2449   enum libusb_error ret;
2450   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
2451
2452   ret = darwin_release_interface (dev_handle, iface);
2453   if (ret != LIBUSB_SUCCESS) {
2454     return ret;
2455   }
2456
2457   if (dev_handle->auto_detach_kernel_driver && dpriv->capture_count > 0) {
2458     ret = darwin_attach_kernel_driver (dev_handle, iface);
2459     if (LIBUSB_SUCCESS != ret) {
2460       usbi_warn (HANDLE_CTX (dev_handle), "on attempt to reattach the kernel driver got ret=%d", ret);
2461     }
2462     /* ignore the error as the interface was successfully released */
2463   }
2464
2465   return LIBUSB_SUCCESS;
2466 }
2467
2468 #endif
2469
2470 const struct usbi_os_backend usbi_backend = {
2471         .name = "Darwin",
2472         .caps = USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2473         .init = darwin_init,
2474         .exit = darwin_exit,
2475         .get_active_config_descriptor = darwin_get_active_config_descriptor,
2476         .get_config_descriptor = darwin_get_config_descriptor,
2477         .hotplug_poll = darwin_hotplug_poll,
2478
2479         .open = darwin_open,
2480         .close = darwin_close,
2481         .get_configuration = darwin_get_configuration,
2482         .set_configuration = darwin_set_configuration,
2483
2484         .set_interface_altsetting = darwin_set_interface_altsetting,
2485         .clear_halt = darwin_clear_halt,
2486         .reset_device = darwin_reset_device,
2487
2488 #if InterfaceVersion >= 550
2489         .alloc_streams = darwin_alloc_streams,
2490         .free_streams = darwin_free_streams,
2491 #endif
2492
2493         .kernel_driver_active = darwin_kernel_driver_active,
2494
2495 #if InterfaceVersion >= 700
2496         .detach_kernel_driver = darwin_detach_kernel_driver,
2497         .attach_kernel_driver = darwin_attach_kernel_driver,
2498         .claim_interface = darwin_capture_claim_interface,
2499         .release_interface = darwin_capture_release_interface,
2500 #else
2501         .claim_interface = darwin_claim_interface,
2502         .release_interface = darwin_release_interface,
2503 #endif
2504
2505         .destroy_device = darwin_destroy_device,
2506
2507         .submit_transfer = darwin_submit_transfer,
2508         .cancel_transfer = darwin_cancel_transfer,
2509
2510         .handle_transfer_completion = darwin_handle_transfer_completion,
2511
2512         .device_priv_size = sizeof(struct darwin_device_priv),
2513         .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
2514         .transfer_priv_size = sizeof(struct darwin_transfer_priv),
2515 };