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