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