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