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