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