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