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