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