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