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