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