darwin: Untangle clock_* API tests from atomics tests
[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     default:
1041       usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
1042     }
1043
1044     ret = usbi_sanitize_device (dev);
1045     if (ret < 0)
1046       break;
1047
1048     usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address,
1049               dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path);
1050   } while (0);
1051
1052   if (0 == ret) {
1053     usbi_connect_device (dev);
1054   } else {
1055     libusb_unref_device (dev);
1056   }
1057
1058   return ret;
1059 }
1060
1061 static int darwin_scan_devices(struct libusb_context *ctx) {
1062   io_iterator_t deviceIterator;
1063   io_service_t service;
1064   kern_return_t kresult;
1065
1066   kresult = usb_setup_device_iterator (&deviceIterator, 0);
1067   if (kresult != kIOReturnSuccess)
1068     return darwin_to_libusb (kresult);
1069
1070   while ((service = IOIteratorNext (deviceIterator))) {
1071     (void) process_new_device (ctx, service);
1072
1073     IOObjectRelease(service);
1074   }
1075
1076   IOObjectRelease(deviceIterator);
1077
1078   return 0;
1079 }
1080
1081 static int darwin_open (struct libusb_device_handle *dev_handle) {
1082   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1083   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1084   IOReturn kresult;
1085
1086   if (0 == dpriv->open_count) {
1087     /* try to open the device */
1088     kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
1089     if (kresult != kIOReturnSuccess) {
1090       usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
1091
1092       if (kIOReturnExclusiveAccess != kresult) {
1093         return darwin_to_libusb (kresult);
1094       }
1095
1096       /* it is possible to perform some actions on a device that is not open so do not return an error */
1097       priv->is_open = 0;
1098     } else {
1099       priv->is_open = 1;
1100     }
1101
1102     /* create async event source */
1103     kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
1104     if (kresult != kIOReturnSuccess) {
1105       usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
1106
1107       if (priv->is_open) {
1108         (*(dpriv->device))->USBDeviceClose (dpriv->device);
1109       }
1110
1111       priv->is_open = 0;
1112
1113       return darwin_to_libusb (kresult);
1114     }
1115
1116     CFRetain (libusb_darwin_acfl);
1117
1118     /* add the cfSource to the aync run loop */
1119     CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
1120   }
1121
1122   /* device opened successfully */
1123   dpriv->open_count++;
1124
1125   usbi_dbg ("device open for access");
1126
1127   return 0;
1128 }
1129
1130 static void darwin_close (struct libusb_device_handle *dev_handle) {
1131   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1132   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1133   IOReturn kresult;
1134   int i;
1135
1136   if (dpriv->open_count == 0) {
1137     /* something is probably very wrong if this is the case */
1138     usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!");
1139     return;
1140   }
1141
1142   dpriv->open_count--;
1143
1144   /* make sure all interfaces are released */
1145   for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1146     if (dev_handle->claimed_interfaces & (1 << i))
1147       libusb_release_interface (dev_handle, i);
1148
1149   if (0 == dpriv->open_count) {
1150     /* delete the device's async event source */
1151     if (priv->cfSource) {
1152       CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
1153       CFRelease (priv->cfSource);
1154       priv->cfSource = NULL;
1155       CFRelease (libusb_darwin_acfl);
1156     }
1157
1158     if (priv->is_open) {
1159       /* close the device */
1160       kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
1161       if (kresult) {
1162         /* Log the fact that we had a problem closing the file, however failing a
1163          * close isn't really an error, so return success anyway */
1164         usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
1165       }
1166     }
1167   }
1168 }
1169
1170 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
1171   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1172
1173   *config = (int) dpriv->active_config;
1174
1175   return 0;
1176 }
1177
1178 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
1179   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1180   IOReturn kresult;
1181   int i;
1182
1183   /* Setting configuration will invalidate the interface, so we need
1184      to reclaim it. First, dispose of existing interfaces, if any. */
1185   for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1186     if (dev_handle->claimed_interfaces & (1 << i))
1187       darwin_release_interface (dev_handle, i);
1188
1189   kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
1190   if (kresult != kIOReturnSuccess)
1191     return darwin_to_libusb (kresult);
1192
1193   /* Reclaim any interfaces. */
1194   for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1195     if (dev_handle->claimed_interfaces & (1 << i))
1196       darwin_claim_interface (dev_handle, i);
1197
1198   dpriv->active_config = config;
1199
1200   return 0;
1201 }
1202
1203 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
1204   IOUSBFindInterfaceRequest request;
1205   kern_return_t             kresult;
1206   io_iterator_t             interface_iterator;
1207   UInt8                     bInterfaceNumber;
1208   int                       ret;
1209
1210   *usbInterfacep = IO_OBJECT_NULL;
1211
1212   /* Setup the Interface Request */
1213   request.bInterfaceClass    = kIOUSBFindInterfaceDontCare;
1214   request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1215   request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1216   request.bAlternateSetting  = kIOUSBFindInterfaceDontCare;
1217
1218   kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1219   if (kresult)
1220     return kresult;
1221
1222   while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
1223     /* find the interface number */
1224     ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
1225                                        &bInterfaceNumber);
1226
1227     if (ret && bInterfaceNumber == ifc) {
1228       break;
1229     }
1230
1231     (void) IOObjectRelease (*usbInterfacep);
1232   }
1233
1234   /* done with the interface iterator */
1235   IOObjectRelease(interface_iterator);
1236
1237   return 0;
1238 }
1239
1240 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
1241   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1242
1243   /* current interface */
1244   struct darwin_interface *cInterface = &priv->interfaces[iface];
1245
1246   kern_return_t kresult;
1247
1248   u_int8_t numep, direction, number;
1249   u_int8_t dont_care1, dont_care3;
1250   u_int16_t dont_care2;
1251   int rc;
1252
1253   usbi_dbg ("building table of endpoints.");
1254
1255   /* retrieve the total number of endpoints on this interface */
1256   kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
1257   if (kresult) {
1258     usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1259     return darwin_to_libusb (kresult);
1260   }
1261
1262   /* iterate through pipe references */
1263   for (int i = 1 ; i <= numep ; i++) {
1264     kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1265                                                             &dont_care2, &dont_care3);
1266
1267     if (kresult != kIOReturnSuccess) {
1268       /* probably a buggy device. try to get the endpoint address from the descriptors */
1269       struct libusb_config_descriptor *config;
1270       const struct libusb_endpoint_descriptor *endpoint_desc;
1271       UInt8 alt_setting;
1272
1273       kresult = (*(cInterface->interface))->GetAlternateSetting (cInterface->interface, &alt_setting);
1274       if (kresult) {
1275         usbi_err (HANDLE_CTX (dev_handle), "can't get alternate setting for interface");
1276         return darwin_to_libusb (kresult);
1277       }
1278
1279       rc = libusb_get_active_config_descriptor (dev_handle->dev, &config);
1280       if (LIBUSB_SUCCESS != rc) {
1281         return rc;
1282       }
1283
1284       endpoint_desc = config->interface[iface].altsetting[alt_setting].endpoint + i - 1;
1285
1286       cInterface->endpoint_addrs[i - 1] = endpoint_desc->bEndpointAddress;
1287     } else {
1288       cInterface->endpoint_addrs[i - 1] = (((kUSBIn == direction) << kUSBRqDirnShift) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1289     }
1290
1291     usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, cInterface->endpoint_addrs[i - 1] >> kUSBRqDirnShift,
1292               cInterface->endpoint_addrs[i - 1] & LIBUSB_ENDPOINT_ADDRESS_MASK);
1293   }
1294
1295   cInterface->num_endpoints = numep;
1296
1297   return 0;
1298 }
1299
1300 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1301   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1302   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1303   io_service_t          usbInterface = IO_OBJECT_NULL;
1304   IOReturn kresult;
1305   IOCFPlugInInterface **plugInInterface = NULL;
1306   SInt32                score;
1307
1308   /* current interface */
1309   struct darwin_interface *cInterface = &priv->interfaces[iface];
1310
1311   kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1312   if (kresult != kIOReturnSuccess)
1313     return darwin_to_libusb (kresult);
1314
1315   /* make sure we have an interface */
1316   if (!usbInterface && dpriv->first_config != 0) {
1317     usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1318
1319     /* set the configuration */
1320     kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1321     if (kresult != LIBUSB_SUCCESS) {
1322       usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1323       return kresult;
1324     }
1325
1326     kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1327     if (kresult) {
1328       usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1329       return darwin_to_libusb (kresult);
1330     }
1331   }
1332
1333   if (!usbInterface) {
1334     usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1335     return LIBUSB_ERROR_NOT_FOUND;
1336   }
1337
1338   /* get an interface to the device's interface */
1339   kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1340                                                kIOCFPlugInInterfaceID, &plugInInterface, &score);
1341
1342   /* ignore release error */
1343   (void)IOObjectRelease (usbInterface);
1344
1345   if (kresult) {
1346     usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1347     return darwin_to_libusb (kresult);
1348   }
1349
1350   if (!plugInInterface) {
1351     usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1352     return LIBUSB_ERROR_NOT_FOUND;
1353   }
1354
1355   /* Do the actual claim */
1356   kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1357                                                CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1358                                                (LPVOID)&cInterface->interface);
1359   /* We no longer need the intermediate plug-in */
1360   /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1361   (*plugInInterface)->Release (plugInInterface);
1362   if (kresult || !cInterface->interface) {
1363     usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1364     return darwin_to_libusb (kresult);
1365   }
1366
1367   /* claim the interface */
1368   kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1369   if (kresult) {
1370     usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1371     return darwin_to_libusb (kresult);
1372   }
1373
1374   /* update list of endpoints */
1375   kresult = get_endpoints (dev_handle, iface);
1376   if (kresult) {
1377     /* this should not happen */
1378     darwin_release_interface (dev_handle, iface);
1379     usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1380     return kresult;
1381   }
1382
1383   cInterface->cfSource = NULL;
1384
1385   /* create async event source */
1386   kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1387   if (kresult != kIOReturnSuccess) {
1388     usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1389
1390     /* can't continue without an async event source */
1391     (void)darwin_release_interface (dev_handle, iface);
1392
1393     return darwin_to_libusb (kresult);
1394   }
1395
1396   /* add the cfSource to the async thread's run loop */
1397   CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1398
1399   usbi_dbg ("interface opened");
1400
1401   return 0;
1402 }
1403
1404 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1405   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1406   IOReturn kresult;
1407
1408   /* current interface */
1409   struct darwin_interface *cInterface = &priv->interfaces[iface];
1410
1411   /* Check to see if an interface is open */
1412   if (!cInterface->interface)
1413     return LIBUSB_SUCCESS;
1414
1415   /* clean up endpoint data */
1416   cInterface->num_endpoints = 0;
1417
1418   /* delete the interface's async event source */
1419   if (cInterface->cfSource) {
1420     CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1421     CFRelease (cInterface->cfSource);
1422   }
1423
1424   kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1425   if (kresult)
1426     usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1427
1428   kresult = (*(cInterface->interface))->Release(cInterface->interface);
1429   if (kresult != kIOReturnSuccess)
1430     usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1431
1432   cInterface->interface = (usb_interface_t **) IO_OBJECT_NULL;
1433
1434   return darwin_to_libusb (kresult);
1435 }
1436
1437 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1438   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1439   IOReturn kresult;
1440
1441   /* current interface */
1442   struct darwin_interface *cInterface = &priv->interfaces[iface];
1443
1444   if (!cInterface->interface)
1445     return LIBUSB_ERROR_NO_DEVICE;
1446
1447   kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1448   if (kresult != kIOReturnSuccess)
1449     darwin_reset_device (dev_handle);
1450
1451   /* update list of endpoints */
1452   kresult = get_endpoints (dev_handle, iface);
1453   if (kresult) {
1454     /* this should not happen */
1455     darwin_release_interface (dev_handle, iface);
1456     usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1457     return kresult;
1458   }
1459
1460   return darwin_to_libusb (kresult);
1461 }
1462
1463 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1464   /* current interface */
1465   struct darwin_interface *cInterface;
1466   IOReturn kresult;
1467   uint8_t pipeRef;
1468
1469   /* determine the interface/endpoint to use */
1470   if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, NULL, &cInterface) != 0) {
1471     usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1472
1473     return LIBUSB_ERROR_NOT_FOUND;
1474   }
1475
1476   /* newer versions of darwin support clearing additional bits on the device's endpoint */
1477   kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1478   if (kresult)
1479     usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1480
1481   return darwin_to_libusb (kresult);
1482 }
1483
1484 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1485   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1486   IOUSBDeviceDescriptor descriptor;
1487   IOUSBConfigurationDescriptorPtr cached_configuration;
1488   IOUSBConfigurationDescriptor configuration;
1489   bool reenumerate = false;
1490   IOReturn kresult;
1491   int i;
1492
1493   kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1494   if (kresult) {
1495     usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1496     return darwin_to_libusb (kresult);
1497   }
1498
1499   do {
1500     usbi_dbg ("darwin/reset_device: checking if device descriptor changed");
1501
1502     /* ignore return code. if we can't get a descriptor it might be worthwhile re-enumerating anway */
1503     (void) darwin_request_descriptor (dpriv->device, kUSBDeviceDesc, 0, &descriptor, sizeof (descriptor));
1504
1505     /* check if the device descriptor has changed */
1506     if (0 != memcmp (&dpriv->dev_descriptor, &descriptor, sizeof (descriptor))) {
1507       reenumerate = true;
1508       break;
1509     }
1510
1511     /* check if any configuration descriptor has changed */
1512     for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1513       usbi_dbg ("darwin/reset_device: checking if configuration descriptor %d changed", i);
1514
1515       (void) darwin_request_descriptor (dpriv->device, kUSBConfDesc, i, &configuration, sizeof (configuration));
1516       (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1517
1518       if (!cached_configuration || 0 != memcmp (cached_configuration, &configuration, sizeof (configuration))) {
1519         reenumerate = true;
1520         break;
1521       }
1522     }
1523   } while (0);
1524
1525   if (reenumerate) {
1526     usbi_dbg ("darwin/reset_device: device requires reenumeration");
1527     (void) (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
1528     return LIBUSB_ERROR_NOT_FOUND;
1529   }
1530
1531   usbi_dbg ("darwin/reset_device: device reset complete");
1532
1533   return LIBUSB_SUCCESS;
1534 }
1535
1536 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1537   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1538   io_service_t usbInterface;
1539   CFTypeRef driver;
1540   IOReturn kresult;
1541
1542   kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1543   if (kresult) {
1544     usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1545
1546     return darwin_to_libusb (kresult);
1547   }
1548
1549   driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1550   IOObjectRelease (usbInterface);
1551
1552   if (driver) {
1553     CFRelease (driver);
1554
1555     return 1;
1556   }
1557
1558   /* no driver */
1559   return 0;
1560 }
1561
1562 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1563 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1564   UNUSED(dev_handle);
1565   UNUSED(interface);
1566   return LIBUSB_ERROR_NOT_SUPPORTED;
1567 }
1568
1569 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1570   UNUSED(dev_handle);
1571   UNUSED(interface);
1572   return LIBUSB_ERROR_NOT_SUPPORTED;
1573 }
1574
1575 static void darwin_destroy_device(struct libusb_device *dev) {
1576   struct darwin_device_priv *dpriv = (struct darwin_device_priv *) dev->os_priv;
1577
1578   if (dpriv->dev) {
1579     /* need to hold the lock in case this is the last reference to the device */
1580     usbi_mutex_lock(&darwin_cached_devices_lock);
1581     darwin_deref_cached_device (dpriv->dev);
1582     dpriv->dev = NULL;
1583     usbi_mutex_unlock(&darwin_cached_devices_lock);
1584   }
1585 }
1586
1587 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1588   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1589
1590   IOReturn               ret;
1591   uint8_t                transferType;
1592   /* None of the values below are used in libusbx for bulk transfers */
1593   uint8_t                direction, number, interval, pipeRef;
1594   uint16_t               maxPacketSize;
1595
1596   struct darwin_interface *cInterface;
1597
1598   if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1599     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1600
1601     return LIBUSB_ERROR_NOT_FOUND;
1602   }
1603
1604   ret = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1605                                                        &transferType, &maxPacketSize, &interval);
1606
1607   if (ret) {
1608     usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1609               darwin_error_str(ret), ret);
1610     return darwin_to_libusb (ret);
1611   }
1612
1613   if (0 != (transfer->length % maxPacketSize)) {
1614     /* do not need a zero packet */
1615     transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1616   }
1617
1618   /* submit the request */
1619   /* timeouts are unavailable on interrupt endpoints */
1620   if (transferType == kUSBInterrupt) {
1621     if (IS_XFERIN(transfer))
1622       ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1623                                                       transfer->length, darwin_async_io_callback, itransfer);
1624     else
1625       ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1626                                                        transfer->length, darwin_async_io_callback, itransfer);
1627   } else {
1628     itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1629
1630     if (IS_XFERIN(transfer))
1631       ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1632                                                         transfer->length, transfer->timeout, transfer->timeout,
1633                                                         darwin_async_io_callback, (void *)itransfer);
1634     else
1635       ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1636                                                          transfer->length, transfer->timeout, transfer->timeout,
1637                                                          darwin_async_io_callback, (void *)itransfer);
1638   }
1639
1640   if (ret)
1641     usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1642                darwin_error_str(ret), ret);
1643
1644   return darwin_to_libusb (ret);
1645 }
1646
1647 #if InterfaceVersion >= 550
1648 static int submit_stream_transfer(struct usbi_transfer *itransfer) {
1649   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1650   struct darwin_interface *cInterface;
1651   uint8_t pipeRef;
1652   IOReturn ret;
1653
1654   if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1655     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1656
1657     return LIBUSB_ERROR_NOT_FOUND;
1658   }
1659
1660   itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1661
1662   if (IS_XFERIN(transfer))
1663     ret = (*(cInterface->interface))->ReadStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1664                                                              transfer->buffer, transfer->length, transfer->timeout,
1665                                                              transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1666   else
1667     ret = (*(cInterface->interface))->WriteStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1668                                                               transfer->buffer, transfer->length, transfer->timeout,
1669                                                               transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1670
1671   if (ret)
1672     usbi_err (TRANSFER_CTX (transfer), "bulk stream transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1673                darwin_error_str(ret), ret);
1674
1675   return darwin_to_libusb (ret);
1676 }
1677 #endif
1678
1679 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1680   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1681   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1682
1683   IOReturn kresult;
1684   uint8_t direction, number, interval, pipeRef, transferType;
1685   uint16_t maxPacketSize;
1686   UInt64 frame;
1687   AbsoluteTime atTime;
1688   int i;
1689
1690   struct darwin_interface *cInterface;
1691
1692   /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1693   if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1694     free(tpriv->isoc_framelist);
1695     tpriv->isoc_framelist = NULL;
1696   }
1697
1698   if (!tpriv->isoc_framelist) {
1699     tpriv->num_iso_packets = transfer->num_iso_packets;
1700     tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1701     if (!tpriv->isoc_framelist)
1702       return LIBUSB_ERROR_NO_MEM;
1703   }
1704
1705   /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1706   for (i = 0 ; i < transfer->num_iso_packets ; i++)
1707     tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1708
1709   /* determine the interface/endpoint to use */
1710   if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1711     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1712
1713     return LIBUSB_ERROR_NOT_FOUND;
1714   }
1715
1716   /* determine the properties of this endpoint and the speed of the device */
1717   (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1718                                                  &transferType, &maxPacketSize, &interval);
1719
1720   /* Last but not least we need the bus frame number */
1721   kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1722   if (kresult) {
1723     usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1724     free(tpriv->isoc_framelist);
1725     tpriv->isoc_framelist = NULL;
1726
1727     return darwin_to_libusb (kresult);
1728   }
1729
1730   (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1731                                                  &transferType, &maxPacketSize, &interval);
1732
1733   /* schedule for a frame a little in the future */
1734   frame += 4;
1735
1736   if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1737     frame = cInterface->frames[transfer->endpoint];
1738
1739   /* submit the request */
1740   if (IS_XFERIN(transfer))
1741     kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1742                                                              transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1743                                                              itransfer);
1744   else
1745     kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1746                                                               transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1747                                                               itransfer);
1748
1749   if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
1750     /* Full speed */
1751     cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1));
1752   else
1753     /* High/super speed */
1754     cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1)) / 8;
1755
1756   if (kresult != kIOReturnSuccess) {
1757     usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1758                darwin_error_str(kresult));
1759     free (tpriv->isoc_framelist);
1760     tpriv->isoc_framelist = NULL;
1761   }
1762
1763   return darwin_to_libusb (kresult);
1764 }
1765
1766 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1767   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1768   struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1769   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1770   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1771
1772   IOReturn               kresult;
1773
1774   memset(&tpriv->req, 0, sizeof(tpriv->req));
1775
1776   /* IOUSBDeviceInterface expects the request in cpu endianness */
1777   tpriv->req.bmRequestType     = setup->bmRequestType;
1778   tpriv->req.bRequest          = setup->bRequest;
1779   /* these values should be in bus order from libusb_fill_control_setup */
1780   tpriv->req.wValue            = OSSwapLittleToHostInt16 (setup->wValue);
1781   tpriv->req.wIndex            = OSSwapLittleToHostInt16 (setup->wIndex);
1782   tpriv->req.wLength           = OSSwapLittleToHostInt16 (setup->wLength);
1783   /* data is stored after the libusb control block */
1784   tpriv->req.pData             = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1785   tpriv->req.completionTimeout = transfer->timeout;
1786   tpriv->req.noDataTimeout     = transfer->timeout;
1787
1788   itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1789
1790   /* all transfers in libusb-1.0 are async */
1791
1792   if (transfer->endpoint) {
1793     struct darwin_interface *cInterface;
1794     uint8_t                 pipeRef;
1795
1796     if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1797       usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1798
1799       return LIBUSB_ERROR_NOT_FOUND;
1800     }
1801
1802     kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1803   } else
1804     /* control request on endpoint 0 */
1805     kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1806
1807   if (kresult != kIOReturnSuccess)
1808     usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1809
1810   return darwin_to_libusb (kresult);
1811 }
1812
1813 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1814   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1815
1816   switch (transfer->type) {
1817   case LIBUSB_TRANSFER_TYPE_CONTROL:
1818     return submit_control_transfer(itransfer);
1819   case LIBUSB_TRANSFER_TYPE_BULK:
1820   case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1821     return submit_bulk_transfer(itransfer);
1822   case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1823     return submit_iso_transfer(itransfer);
1824   case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1825 #if InterfaceVersion >= 550
1826     return submit_stream_transfer(itransfer);
1827 #else
1828     usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version does not support bulk stream transfers");
1829     return LIBUSB_ERROR_NOT_SUPPORTED;
1830 #endif
1831   default:
1832     usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1833     return LIBUSB_ERROR_INVALID_PARAM;
1834   }
1835 }
1836
1837 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1838   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1839   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1840   IOReturn kresult;
1841
1842   usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
1843
1844   if (!dpriv->device)
1845     return LIBUSB_ERROR_NO_DEVICE;
1846
1847   kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1848
1849   return darwin_to_libusb (kresult);
1850 }
1851
1852 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1853   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1854   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1855   struct darwin_interface *cInterface;
1856   uint8_t pipeRef, iface;
1857   IOReturn kresult;
1858
1859   if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface, &cInterface) != 0) {
1860     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1861
1862     return LIBUSB_ERROR_NOT_FOUND;
1863   }
1864
1865   if (!dpriv->device)
1866     return LIBUSB_ERROR_NO_DEVICE;
1867
1868   usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
1869
1870   /* abort transactions */
1871 #if InterfaceVersion >= 550
1872   if (LIBUSB_TRANSFER_TYPE_BULK_STREAM == transfer->type)
1873     (*(cInterface->interface))->AbortStreamsPipe (cInterface->interface, pipeRef, itransfer->stream_id);
1874   else
1875 #endif
1876     (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1877
1878   usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
1879
1880   /* newer versions of darwin support clearing additional bits on the device's endpoint */
1881   kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1882
1883   return darwin_to_libusb (kresult);
1884 }
1885
1886 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1887   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1888
1889   switch (transfer->type) {
1890   case LIBUSB_TRANSFER_TYPE_CONTROL:
1891     return cancel_control_transfer(itransfer);
1892   case LIBUSB_TRANSFER_TYPE_BULK:
1893   case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1894   case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1895     return darwin_abort_transfers (itransfer);
1896   default:
1897     usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1898     return LIBUSB_ERROR_INVALID_PARAM;
1899   }
1900 }
1901
1902 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1903   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1904   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1905
1906   if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1907     free (tpriv->isoc_framelist);
1908     tpriv->isoc_framelist = NULL;
1909   }
1910 }
1911
1912 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1913   struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1914   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1915   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1916
1917   usbi_dbg ("an async io operation has completed");
1918
1919   /* if requested write a zero packet */
1920   if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
1921     struct darwin_interface *cInterface;
1922     uint8_t pipeRef;
1923
1924     (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface);
1925
1926     (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
1927   }
1928
1929   tpriv->result = result;
1930   tpriv->size = (UInt32) (uintptr_t) arg0;
1931
1932   /* signal the core that this transfer is complete */
1933   usbi_signal_transfer_completion(itransfer);
1934 }
1935
1936 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1937   if (itransfer->timeout_flags & USBI_TRANSFER_TIMED_OUT)
1938     result = kIOUSBTransactionTimeout;
1939
1940   switch (result) {
1941   case kIOReturnUnderrun:
1942   case kIOReturnSuccess:
1943     return LIBUSB_TRANSFER_COMPLETED;
1944   case kIOReturnAborted:
1945     return LIBUSB_TRANSFER_CANCELLED;
1946   case kIOUSBPipeStalled:
1947     usbi_dbg ("transfer error: pipe is stalled");
1948     return LIBUSB_TRANSFER_STALL;
1949   case kIOReturnOverrun:
1950     usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1951     return LIBUSB_TRANSFER_OVERFLOW;
1952   case kIOUSBTransactionTimeout:
1953     usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1954     itransfer->timeout_flags |= USBI_TRANSFER_TIMED_OUT;
1955     return LIBUSB_TRANSFER_TIMED_OUT;
1956   default:
1957     usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1958     return LIBUSB_TRANSFER_ERROR;
1959   }
1960 }
1961
1962 static int darwin_handle_transfer_completion (struct usbi_transfer *itransfer) {
1963   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1964   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1965   int isIsoc      = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1966   int isBulk      = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1967   int isControl   = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1968   int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1969   int i;
1970
1971   if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1972     usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1973     return LIBUSB_ERROR_INVALID_PARAM;
1974   }
1975
1976   usbi_dbg ("handling %s completion with kernel status %d",
1977              isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", tpriv->result);
1978
1979   if (kIOReturnSuccess == tpriv->result || kIOReturnUnderrun == tpriv->result) {
1980     if (isIsoc && tpriv->isoc_framelist) {
1981       /* copy isochronous results back */
1982
1983       for (i = 0; i < transfer->num_iso_packets ; i++) {
1984         struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1985         lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1986         lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1987       }
1988     } else if (!isIsoc)
1989       itransfer->transferred += tpriv->size;
1990   }
1991
1992   /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1993   return usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, tpriv->result));
1994 }
1995
1996 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1997 #if !OSX_USE_CLOCK_GETTIME
1998   mach_timespec_t sys_time;
1999   clock_serv_t clock_ref;
2000
2001   switch (clk_id) {
2002   case USBI_CLOCK_REALTIME:
2003     /* CLOCK_REALTIME represents time since the epoch */
2004     clock_ref = clock_realtime;
2005     break;
2006   case USBI_CLOCK_MONOTONIC:
2007     /* use system boot time as reference for the monotonic clock */
2008     clock_ref = clock_monotonic;
2009     break;
2010   default:
2011     return LIBUSB_ERROR_INVALID_PARAM;
2012   }
2013
2014   clock_get_time (clock_ref, &sys_time);
2015
2016   tp->tv_sec  = sys_time.tv_sec;
2017   tp->tv_nsec = sys_time.tv_nsec;
2018
2019   return 0;
2020 #else
2021   switch (clk_id) {
2022   case USBI_CLOCK_MONOTONIC:
2023     return clock_gettime(CLOCK_MONOTONIC, tp);
2024   case USBI_CLOCK_REALTIME:
2025     return clock_gettime(CLOCK_REALTIME, tp);
2026   default:
2027     return LIBUSB_ERROR_INVALID_PARAM;
2028   }
2029 #endif
2030 }
2031
2032 #if InterfaceVersion >= 550
2033 static int darwin_alloc_streams (struct libusb_device_handle *dev_handle, uint32_t num_streams, unsigned char *endpoints,
2034                                  int num_endpoints) {
2035   struct darwin_interface *cInterface;
2036   UInt32 supportsStreams;
2037   uint8_t pipeRef;
2038   int rc, i;
2039
2040   /* find the mimimum number of supported streams on the endpoint list */
2041   for (i = 0 ; i < num_endpoints ; ++i) {
2042     if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface))) {
2043       return rc;
2044     }
2045
2046     (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2047     if (num_streams > supportsStreams)
2048       num_streams = supportsStreams;
2049   }
2050
2051   /* it is an error if any endpoint in endpoints does not support streams */
2052   if (0 == num_streams)
2053     return LIBUSB_ERROR_INVALID_PARAM;
2054
2055   /* create the streams */
2056   for (i = 0 ; i < num_endpoints ; ++i) {
2057     (void) ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
2058
2059     rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, num_streams);
2060     if (kIOReturnSuccess != rc)
2061       return darwin_to_libusb(rc);
2062   }
2063
2064   return num_streams;
2065 }
2066
2067 static int darwin_free_streams (struct libusb_device_handle *dev_handle, unsigned char *endpoints, int num_endpoints) {
2068   struct darwin_interface *cInterface;
2069   UInt32 supportsStreams;
2070   uint8_t pipeRef;
2071   int rc;
2072
2073   for (int i = 0 ; i < num_endpoints ; ++i) {
2074     if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface)))
2075       return rc;
2076
2077     (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2078     if (0 == supportsStreams)
2079       return LIBUSB_ERROR_INVALID_PARAM;
2080
2081     rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, 0);
2082     if (kIOReturnSuccess != rc)
2083       return darwin_to_libusb(rc);
2084   }
2085
2086   return LIBUSB_SUCCESS;
2087 }
2088 #endif
2089
2090 const struct usbi_os_backend usbi_backend = {
2091         .name = "Darwin",
2092         .caps = 0,
2093         .init = darwin_init,
2094         .exit = darwin_exit,
2095         .get_device_list = NULL, /* not needed */
2096         .get_device_descriptor = darwin_get_device_descriptor,
2097         .get_active_config_descriptor = darwin_get_active_config_descriptor,
2098         .get_config_descriptor = darwin_get_config_descriptor,
2099         .hotplug_poll = darwin_hotplug_poll,
2100
2101         .open = darwin_open,
2102         .close = darwin_close,
2103         .get_configuration = darwin_get_configuration,
2104         .set_configuration = darwin_set_configuration,
2105         .claim_interface = darwin_claim_interface,
2106         .release_interface = darwin_release_interface,
2107
2108         .set_interface_altsetting = darwin_set_interface_altsetting,
2109         .clear_halt = darwin_clear_halt,
2110         .reset_device = darwin_reset_device,
2111
2112 #if InterfaceVersion >= 550
2113         .alloc_streams = darwin_alloc_streams,
2114         .free_streams = darwin_free_streams,
2115 #endif
2116
2117         .kernel_driver_active = darwin_kernel_driver_active,
2118         .detach_kernel_driver = darwin_detach_kernel_driver,
2119         .attach_kernel_driver = darwin_attach_kernel_driver,
2120
2121         .destroy_device = darwin_destroy_device,
2122
2123         .submit_transfer = darwin_submit_transfer,
2124         .cancel_transfer = darwin_cancel_transfer,
2125         .clear_transfer_priv = darwin_clear_transfer_priv,
2126
2127         .handle_transfer_completion = darwin_handle_transfer_completion,
2128
2129         .clock_gettime = darwin_clock_gettime,
2130
2131         .device_priv_size = sizeof(struct darwin_device_priv),
2132         .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
2133         .transfer_priv_size = sizeof(struct darwin_transfer_priv),
2134 };