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