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