core: Only interrupt event handlers as necessary during libusb_open()
[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   /* create a file descriptor for notifications */
977   pipe (priv->fds);
978
979   /* set the pipe to be non-blocking */
980   fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
981
982   usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
983
984   usbi_dbg ("device open for access");
985
986   return 0;
987 }
988
989 static void darwin_close (struct libusb_device_handle *dev_handle) {
990   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
991   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
992   IOReturn kresult;
993   int i;
994
995   if (dpriv->open_count == 0) {
996     /* something is probably very wrong if this is the case */
997     usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!\n");
998     return;
999   }
1000
1001   dpriv->open_count--;
1002
1003   /* make sure all interfaces are released */
1004   for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1005     if (dev_handle->claimed_interfaces & (1 << i))
1006       libusb_release_interface (dev_handle, i);
1007
1008   if (0 == dpriv->open_count) {
1009     /* delete the device's async event source */
1010     if (priv->cfSource) {
1011       CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
1012       CFRelease (priv->cfSource);
1013       priv->cfSource = NULL;
1014       CFRelease (libusb_darwin_acfl);
1015     }
1016
1017     if (priv->is_open) {
1018       /* close the device */
1019       kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
1020       if (kresult) {
1021         /* Log the fact that we had a problem closing the file, however failing a
1022          * close isn't really an error, so return success anyway */
1023         usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
1024       }
1025     }
1026   }
1027
1028   /* file descriptors are maintained per-instance */
1029   usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
1030   close (priv->fds[1]);
1031   close (priv->fds[0]);
1032
1033   priv->fds[0] = priv->fds[1] = -1;
1034 }
1035
1036 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
1037   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1038
1039   *config = (int) dpriv->active_config;
1040
1041   return 0;
1042 }
1043
1044 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
1045   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1046   IOReturn kresult;
1047   int i;
1048
1049   /* Setting configuration will invalidate the interface, so we need
1050      to reclaim it. First, dispose of existing interfaces, if any. */
1051   for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1052     if (dev_handle->claimed_interfaces & (1 << i))
1053       darwin_release_interface (dev_handle, i);
1054
1055   kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
1056   if (kresult != kIOReturnSuccess)
1057     return darwin_to_libusb (kresult);
1058
1059   /* Reclaim any interfaces. */
1060   for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1061     if (dev_handle->claimed_interfaces & (1 << i))
1062       darwin_claim_interface (dev_handle, i);
1063
1064   dpriv->active_config = config;
1065
1066   return 0;
1067 }
1068
1069 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
1070   IOUSBFindInterfaceRequest request;
1071   kern_return_t             kresult;
1072   io_iterator_t             interface_iterator;
1073   UInt8                     bInterfaceNumber;
1074   int                       ret;
1075
1076   *usbInterfacep = IO_OBJECT_NULL;
1077
1078   /* Setup the Interface Request */
1079   request.bInterfaceClass    = kIOUSBFindInterfaceDontCare;
1080   request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1081   request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1082   request.bAlternateSetting  = kIOUSBFindInterfaceDontCare;
1083
1084   kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1085   if (kresult)
1086     return kresult;
1087
1088   while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
1089     /* find the interface number */
1090     ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
1091                                        &bInterfaceNumber);
1092
1093     if (ret && bInterfaceNumber == ifc) {
1094       break;
1095     }
1096
1097     (void) IOObjectRelease (*usbInterfacep);
1098   }
1099
1100   /* done with the interface iterator */
1101   IOObjectRelease(interface_iterator);
1102
1103   return 0;
1104 }
1105
1106 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
1107   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1108
1109   /* current interface */
1110   struct darwin_interface *cInterface = &priv->interfaces[iface];
1111
1112   kern_return_t kresult;
1113
1114   u_int8_t numep, direction, number;
1115   u_int8_t dont_care1, dont_care3;
1116   u_int16_t dont_care2;
1117   int i;
1118
1119   usbi_dbg ("building table of endpoints.");
1120
1121   /* retrieve the total number of endpoints on this interface */
1122   kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
1123   if (kresult) {
1124     usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1125     return darwin_to_libusb (kresult);
1126   }
1127
1128   /* iterate through pipe references */
1129   for (i = 1 ; i <= numep ; i++) {
1130     kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1131                                                             &dont_care2, &dont_care3);
1132
1133     if (kresult != kIOReturnSuccess) {
1134       usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
1135
1136       return darwin_to_libusb (kresult);
1137     }
1138
1139     usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
1140
1141     cInterface->endpoint_addrs[i - 1] = (((kUSBIn == direction) << kUSBRqDirnShift) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1142   }
1143
1144   cInterface->num_endpoints = numep;
1145
1146   return 0;
1147 }
1148
1149 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1150   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1151   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1152   io_service_t          usbInterface = IO_OBJECT_NULL;
1153   IOReturn kresult;
1154   IOCFPlugInInterface **plugInInterface = NULL;
1155   SInt32                score;
1156
1157   /* current interface */
1158   struct darwin_interface *cInterface = &priv->interfaces[iface];
1159
1160   kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1161   if (kresult != kIOReturnSuccess)
1162     return darwin_to_libusb (kresult);
1163
1164   /* make sure we have an interface */
1165   if (!usbInterface && dpriv->first_config != 0) {
1166     usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1167
1168     /* set the configuration */
1169     kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1170     if (kresult != LIBUSB_SUCCESS) {
1171       usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1172       return kresult;
1173     }
1174
1175     kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1176     if (kresult) {
1177       usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1178       return darwin_to_libusb (kresult);
1179     }
1180   }
1181
1182   if (!usbInterface) {
1183     usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1184     return LIBUSB_ERROR_NOT_FOUND;
1185   }
1186
1187   /* get an interface to the device's interface */
1188   kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1189                                                kIOCFPlugInInterfaceID, &plugInInterface, &score);
1190
1191   /* ignore release error */
1192   (void)IOObjectRelease (usbInterface);
1193
1194   if (kresult) {
1195     usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1196     return darwin_to_libusb (kresult);
1197   }
1198
1199   if (!plugInInterface) {
1200     usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1201     return LIBUSB_ERROR_NOT_FOUND;
1202   }
1203
1204   /* Do the actual claim */
1205   kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1206                                                CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1207                                                (LPVOID)&cInterface->interface);
1208   /* We no longer need the intermediate plug-in */
1209   /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1210   (*plugInInterface)->Release (plugInInterface);
1211   if (kresult || !cInterface->interface) {
1212     usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1213     return darwin_to_libusb (kresult);
1214   }
1215
1216   /* claim the interface */
1217   kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1218   if (kresult) {
1219     usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1220     return darwin_to_libusb (kresult);
1221   }
1222
1223   /* update list of endpoints */
1224   kresult = get_endpoints (dev_handle, iface);
1225   if (kresult) {
1226     /* this should not happen */
1227     darwin_release_interface (dev_handle, iface);
1228     usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1229     return kresult;
1230   }
1231
1232   cInterface->cfSource = NULL;
1233
1234   /* create async event source */
1235   kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1236   if (kresult != kIOReturnSuccess) {
1237     usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1238
1239     /* can't continue without an async event source */
1240     (void)darwin_release_interface (dev_handle, iface);
1241
1242     return darwin_to_libusb (kresult);
1243   }
1244
1245   /* add the cfSource to the async thread's run loop */
1246   CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1247
1248   usbi_dbg ("interface opened");
1249
1250   return 0;
1251 }
1252
1253 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1254   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1255   IOReturn kresult;
1256
1257   /* current interface */
1258   struct darwin_interface *cInterface = &priv->interfaces[iface];
1259
1260   /* Check to see if an interface is open */
1261   if (!cInterface->interface)
1262     return LIBUSB_SUCCESS;
1263
1264   /* clean up endpoint data */
1265   cInterface->num_endpoints = 0;
1266
1267   /* delete the interface's async event source */
1268   if (cInterface->cfSource) {
1269     CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1270     CFRelease (cInterface->cfSource);
1271   }
1272
1273   kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1274   if (kresult)
1275     usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1276
1277   kresult = (*(cInterface->interface))->Release(cInterface->interface);
1278   if (kresult != kIOReturnSuccess)
1279     usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1280
1281   cInterface->interface = IO_OBJECT_NULL;
1282
1283   return darwin_to_libusb (kresult);
1284 }
1285
1286 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1287   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1288   IOReturn kresult;
1289
1290   /* current interface */
1291   struct darwin_interface *cInterface = &priv->interfaces[iface];
1292
1293   if (!cInterface->interface)
1294     return LIBUSB_ERROR_NO_DEVICE;
1295
1296   kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1297   if (kresult != kIOReturnSuccess)
1298     darwin_reset_device (dev_handle);
1299
1300   /* update list of endpoints */
1301   kresult = get_endpoints (dev_handle, iface);
1302   if (kresult) {
1303     /* this should not happen */
1304     darwin_release_interface (dev_handle, iface);
1305     usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1306     return kresult;
1307   }
1308
1309   return darwin_to_libusb (kresult);
1310 }
1311
1312 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1313   /* current interface */
1314   struct darwin_interface *cInterface;
1315   IOReturn kresult;
1316   uint8_t pipeRef;
1317
1318   /* determine the interface/endpoint to use */
1319   if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, NULL, &cInterface) != 0) {
1320     usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1321
1322     return LIBUSB_ERROR_NOT_FOUND;
1323   }
1324
1325   /* newer versions of darwin support clearing additional bits on the device's endpoint */
1326   kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1327   if (kresult)
1328     usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1329
1330   return darwin_to_libusb (kresult);
1331 }
1332
1333 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1334   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1335   IOUSBDeviceDescriptor descriptor;
1336   IOUSBConfigurationDescriptorPtr cached_configuration;
1337   IOUSBConfigurationDescriptor configuration;
1338   bool reenumerate = false;
1339   IOReturn kresult;
1340   int i;
1341
1342   kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1343   if (kresult) {
1344     usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1345     return darwin_to_libusb (kresult);
1346   }
1347
1348   do {
1349     usbi_dbg ("darwin/reset_device: checking if device descriptor changed");
1350
1351     /* ignore return code. if we can't get a descriptor it might be worthwhile re-enumerating anway */
1352     (void) darwin_request_descriptor (dpriv->device, kUSBDeviceDesc, 0, &descriptor, sizeof (descriptor));
1353
1354     /* check if the device descriptor has changed */
1355     if (0 != memcmp (&dpriv->dev_descriptor, &descriptor, sizeof (descriptor))) {
1356       reenumerate = true;
1357       break;
1358     }
1359
1360     /* check if any configuration descriptor has changed */
1361     for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1362       usbi_dbg ("darwin/reset_device: checking if configuration descriptor %d changed", i);
1363
1364       (void) darwin_request_descriptor (dpriv->device, kUSBConfDesc, i, &configuration, sizeof (configuration));
1365       (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1366
1367       if (!cached_configuration || 0 != memcmp (cached_configuration, &configuration, sizeof (configuration))) {
1368         reenumerate = true;
1369         break;
1370       }
1371     }
1372   } while (0);
1373
1374   if (reenumerate) {
1375     usbi_dbg ("darwin/reset_device: device requires reenumeration");
1376     (void) (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
1377     return LIBUSB_ERROR_NOT_FOUND;
1378   }
1379
1380   usbi_dbg ("darwin/reset_device: device reset complete");
1381
1382   return LIBUSB_SUCCESS;
1383 }
1384
1385 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1386   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1387   io_service_t usbInterface;
1388   CFTypeRef driver;
1389   IOReturn kresult;
1390
1391   kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1392   if (kresult) {
1393     usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1394
1395     return darwin_to_libusb (kresult);
1396   }
1397
1398   driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1399   IOObjectRelease (usbInterface);
1400
1401   if (driver) {
1402     CFRelease (driver);
1403
1404     return 1;
1405   }
1406
1407   /* no driver */
1408   return 0;
1409 }
1410
1411 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1412 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1413   (void)dev_handle;
1414   (void)interface;
1415   return LIBUSB_ERROR_NOT_SUPPORTED;
1416 }
1417
1418 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1419   (void)dev_handle;
1420   (void)interface;
1421   return LIBUSB_ERROR_NOT_SUPPORTED;
1422 }
1423
1424 static void darwin_destroy_device(struct libusb_device *dev) {
1425   struct darwin_device_priv *dpriv = (struct darwin_device_priv *) dev->os_priv;
1426
1427   if (dpriv->dev) {
1428     /* need to hold the lock in case this is the last reference to the device */
1429     usbi_mutex_lock(&darwin_cached_devices_lock);
1430     darwin_deref_cached_device (dpriv->dev);
1431     dpriv->dev = NULL;
1432     usbi_mutex_unlock(&darwin_cached_devices_lock);
1433   }
1434 }
1435
1436 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1437   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1438
1439   IOReturn               ret;
1440   uint8_t                transferType;
1441   /* None of the values below are used in libusbx for bulk transfers */
1442   uint8_t                direction, number, interval, pipeRef;
1443   uint16_t               maxPacketSize;
1444
1445   struct darwin_interface *cInterface;
1446
1447   if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1448     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1449
1450     return LIBUSB_ERROR_NOT_FOUND;
1451   }
1452
1453   ret = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1454                                                        &transferType, &maxPacketSize, &interval);
1455
1456   if (ret) {
1457     usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1458               darwin_error_str(ret), ret);
1459     return darwin_to_libusb (ret);
1460   }
1461
1462   if (0 != (transfer->length % maxPacketSize)) {
1463     /* do not need a zero packet */
1464     transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1465   }
1466
1467   /* submit the request */
1468   /* timeouts are unavailable on interrupt endpoints */
1469   if (transferType == kUSBInterrupt) {
1470     if (IS_XFERIN(transfer))
1471       ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1472                                                       transfer->length, darwin_async_io_callback, itransfer);
1473     else
1474       ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1475                                                        transfer->length, darwin_async_io_callback, itransfer);
1476   } else {
1477     itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1478
1479     if (IS_XFERIN(transfer))
1480       ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1481                                                         transfer->length, transfer->timeout, transfer->timeout,
1482                                                         darwin_async_io_callback, (void *)itransfer);
1483     else
1484       ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1485                                                          transfer->length, transfer->timeout, transfer->timeout,
1486                                                          darwin_async_io_callback, (void *)itransfer);
1487   }
1488
1489   if (ret)
1490     usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1491                darwin_error_str(ret), ret);
1492
1493   return darwin_to_libusb (ret);
1494 }
1495
1496 #if InterfaceVersion >= 550
1497 static int submit_stream_transfer(struct usbi_transfer *itransfer) {
1498   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1499   struct darwin_interface *cInterface;
1500   uint8_t pipeRef;
1501   IOReturn ret;
1502
1503   if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1504     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1505
1506     return LIBUSB_ERROR_NOT_FOUND;
1507   }
1508
1509   itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1510
1511   if (IS_XFERIN(transfer))
1512     ret = (*(cInterface->interface))->ReadStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1513                                                              transfer->buffer, transfer->length, transfer->timeout,
1514                                                              transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1515   else
1516     ret = (*(cInterface->interface))->WriteStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1517                                                               transfer->buffer, transfer->length, transfer->timeout,
1518                                                               transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1519
1520   if (ret)
1521     usbi_err (TRANSFER_CTX (transfer), "bulk stream transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1522                darwin_error_str(ret), ret);
1523
1524   return darwin_to_libusb (ret);
1525 }
1526 #endif
1527
1528 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1529   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1530   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1531
1532   IOReturn kresult;
1533   uint8_t direction, number, interval, pipeRef, transferType;
1534   uint16_t maxPacketSize;
1535   UInt64 frame;
1536   AbsoluteTime atTime;
1537   int i;
1538
1539   struct darwin_interface *cInterface;
1540
1541   /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1542   if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1543     free(tpriv->isoc_framelist);
1544     tpriv->isoc_framelist = NULL;
1545   }
1546
1547   if (!tpriv->isoc_framelist) {
1548     tpriv->num_iso_packets = transfer->num_iso_packets;
1549     tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1550     if (!tpriv->isoc_framelist)
1551       return LIBUSB_ERROR_NO_MEM;
1552   }
1553
1554   /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1555   for (i = 0 ; i < transfer->num_iso_packets ; i++)
1556     tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1557
1558   /* determine the interface/endpoint to use */
1559   if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1560     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1561
1562     return LIBUSB_ERROR_NOT_FOUND;
1563   }
1564
1565   /* determine the properties of this endpoint and the speed of the device */
1566   (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1567                                                  &transferType, &maxPacketSize, &interval);
1568
1569   /* Last but not least we need the bus frame number */
1570   kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1571   if (kresult) {
1572     usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1573     free(tpriv->isoc_framelist);
1574     tpriv->isoc_framelist = NULL;
1575
1576     return darwin_to_libusb (kresult);
1577   }
1578
1579   (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1580                                                  &transferType, &maxPacketSize, &interval);
1581
1582   /* schedule for a frame a little in the future */
1583   frame += 4;
1584
1585   if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1586     frame = cInterface->frames[transfer->endpoint];
1587
1588   /* submit the request */
1589   if (IS_XFERIN(transfer))
1590     kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1591                                                              transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1592                                                              itransfer);
1593   else
1594     kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1595                                                               transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1596                                                               itransfer);
1597
1598   if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
1599     /* Full speed */
1600     cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1));
1601   else
1602     /* High/super speed */
1603     cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1)) / 8;
1604
1605   if (kresult != kIOReturnSuccess) {
1606     usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1607                darwin_error_str(kresult));
1608     free (tpriv->isoc_framelist);
1609     tpriv->isoc_framelist = NULL;
1610   }
1611
1612   return darwin_to_libusb (kresult);
1613 }
1614
1615 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1616   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1617   struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1618   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1619   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1620
1621   IOReturn               kresult;
1622
1623   bzero(&tpriv->req, sizeof(tpriv->req));
1624
1625   /* IOUSBDeviceInterface expects the request in cpu endianess */
1626   tpriv->req.bmRequestType     = setup->bmRequestType;
1627   tpriv->req.bRequest          = setup->bRequest;
1628   /* these values should be in bus order from libusb_fill_control_setup */
1629   tpriv->req.wValue            = OSSwapLittleToHostInt16 (setup->wValue);
1630   tpriv->req.wIndex            = OSSwapLittleToHostInt16 (setup->wIndex);
1631   tpriv->req.wLength           = OSSwapLittleToHostInt16 (setup->wLength);
1632   /* data is stored after the libusb control block */
1633   tpriv->req.pData             = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1634   tpriv->req.completionTimeout = transfer->timeout;
1635   tpriv->req.noDataTimeout     = transfer->timeout;
1636
1637   itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1638
1639   /* all transfers in libusb-1.0 are async */
1640
1641   if (transfer->endpoint) {
1642     struct darwin_interface *cInterface;
1643     uint8_t                 pipeRef;
1644
1645     if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1646       usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1647
1648       return LIBUSB_ERROR_NOT_FOUND;
1649     }
1650
1651     kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1652   } else
1653     /* control request on endpoint 0 */
1654     kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1655
1656   if (kresult != kIOReturnSuccess)
1657     usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1658
1659   return darwin_to_libusb (kresult);
1660 }
1661
1662 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1663   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1664
1665   switch (transfer->type) {
1666   case LIBUSB_TRANSFER_TYPE_CONTROL:
1667     return submit_control_transfer(itransfer);
1668   case LIBUSB_TRANSFER_TYPE_BULK:
1669   case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1670     return submit_bulk_transfer(itransfer);
1671   case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1672     return submit_iso_transfer(itransfer);
1673   case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1674 #if InterfaceVersion >= 550
1675     return submit_stream_transfer(itransfer);
1676 #else
1677     usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version does not support bulk stream transfers");
1678     return LIBUSB_ERROR_NOT_SUPPORTED;
1679 #endif
1680   default:
1681     usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1682     return LIBUSB_ERROR_INVALID_PARAM;
1683   }
1684 }
1685
1686 static int cancel_control_transfer(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   IOReturn kresult;
1690
1691   usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
1692
1693   if (!dpriv->device)
1694     return LIBUSB_ERROR_NO_DEVICE;
1695
1696   kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1697
1698   return darwin_to_libusb (kresult);
1699 }
1700
1701 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1702   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1703   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1704   struct darwin_interface *cInterface;
1705   uint8_t pipeRef, iface;
1706   IOReturn kresult;
1707
1708   if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface, &cInterface) != 0) {
1709     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1710
1711     return LIBUSB_ERROR_NOT_FOUND;
1712   }
1713
1714   if (!dpriv->device)
1715     return LIBUSB_ERROR_NO_DEVICE;
1716
1717   usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
1718
1719   /* abort transactions */
1720 #if InterfaceVersion >= 550
1721   if (LIBUSB_TRANSFER_TYPE_BULK_STREAM == transfer->type)
1722     (*(cInterface->interface))->AbortStreamsPipe (cInterface->interface, pipeRef, itransfer->stream_id);
1723   else
1724 #endif
1725     (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1726
1727   usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
1728
1729   /* newer versions of darwin support clearing additional bits on the device's endpoint */
1730   kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1731
1732   return darwin_to_libusb (kresult);
1733 }
1734
1735 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1736   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1737
1738   switch (transfer->type) {
1739   case LIBUSB_TRANSFER_TYPE_CONTROL:
1740     return cancel_control_transfer(itransfer);
1741   case LIBUSB_TRANSFER_TYPE_BULK:
1742   case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1743   case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1744     return darwin_abort_transfers (itransfer);
1745   default:
1746     usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1747     return LIBUSB_ERROR_INVALID_PARAM;
1748   }
1749 }
1750
1751 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1752   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1753   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1754
1755   if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1756     free (tpriv->isoc_framelist);
1757     tpriv->isoc_framelist = NULL;
1758   }
1759 }
1760
1761 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1762   struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1763   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1764   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1765   struct darwin_msg_async_io_complete message = {.itransfer = itransfer, .result = result,
1766                                                  .size = (UInt32) (uintptr_t) arg0};
1767
1768   usbi_dbg ("an async io operation has completed");
1769
1770   /* if requested write a zero packet */
1771   if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
1772     struct darwin_interface *cInterface;
1773     uint8_t pipeRef;
1774
1775     (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface);
1776
1777     (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
1778   }
1779
1780   /* send a completion message to the device's file descriptor */
1781   write (priv->fds[1], &message, sizeof (message));
1782 }
1783
1784 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1785   if (itransfer->flags & USBI_TRANSFER_TIMED_OUT)
1786     result = kIOUSBTransactionTimeout;
1787
1788   switch (result) {
1789   case kIOReturnUnderrun:
1790   case kIOReturnSuccess:
1791     return LIBUSB_TRANSFER_COMPLETED;
1792   case kIOReturnAborted:
1793     return LIBUSB_TRANSFER_CANCELLED;
1794   case kIOUSBPipeStalled:
1795     usbi_dbg ("transfer error: pipe is stalled");
1796     return LIBUSB_TRANSFER_STALL;
1797   case kIOReturnOverrun:
1798     usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1799     return LIBUSB_TRANSFER_OVERFLOW;
1800   case kIOUSBTransactionTimeout:
1801     usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1802     itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
1803     return LIBUSB_TRANSFER_TIMED_OUT;
1804   default:
1805     usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1806     return LIBUSB_TRANSFER_ERROR;
1807   }
1808 }
1809
1810 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1811   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1812   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1813   int isIsoc      = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1814   int isBulk      = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1815   int isControl   = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1816   int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1817   int i;
1818
1819   if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1820     usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1821     return;
1822   }
1823
1824   usbi_dbg ("handling %s completion with kernel status %d",
1825              isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", result);
1826
1827   if (kIOReturnSuccess == result || kIOReturnUnderrun == result) {
1828     if (isIsoc && tpriv->isoc_framelist) {
1829       /* copy isochronous results back */
1830
1831       for (i = 0; i < transfer->num_iso_packets ; i++) {
1832         struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1833         lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1834         lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1835       }
1836     } else if (!isIsoc)
1837       itransfer->transferred += io_size;
1838   }
1839
1840   /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1841   usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, result));
1842 }
1843
1844 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready) {
1845   struct darwin_msg_async_io_complete message;
1846   POLL_NFDS_TYPE i = 0;
1847   ssize_t ret;
1848
1849   usbi_mutex_lock(&ctx->open_devs_lock);
1850
1851   for (i = 0; i < nfds && num_ready > 0; i++) {
1852     struct pollfd *pollfd = &fds[i];
1853
1854     usbi_dbg ("checking fd %i with revents = %x", pollfd->fd, pollfd->revents);
1855
1856     if (!pollfd->revents)
1857       continue;
1858
1859     num_ready--;
1860
1861     if (pollfd->revents & POLLERR) {
1862       /* this probably will never happen so ignore the error an move on. */
1863       continue;
1864     }
1865
1866     /* there is only one type of message */
1867     ret = read (pollfd->fd, &message, sizeof (message));
1868     if (ret < (ssize_t) sizeof (message)) {
1869       usbi_dbg ("WARNING: short read on async io completion pipe\n");
1870       continue;
1871     }
1872
1873     darwin_handle_callback (message.itransfer, message.result, message.size);
1874   }
1875
1876   usbi_mutex_unlock(&ctx->open_devs_lock);
1877
1878   return 0;
1879 }
1880
1881 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1882   mach_timespec_t sys_time;
1883   clock_serv_t clock_ref;
1884
1885   switch (clk_id) {
1886   case USBI_CLOCK_REALTIME:
1887     /* CLOCK_REALTIME represents time since the epoch */
1888     clock_ref = clock_realtime;
1889     break;
1890   case USBI_CLOCK_MONOTONIC:
1891     /* use system boot time as reference for the monotonic clock */
1892     clock_ref = clock_monotonic;
1893     break;
1894   default:
1895     return LIBUSB_ERROR_INVALID_PARAM;
1896   }
1897
1898   clock_get_time (clock_ref, &sys_time);
1899
1900   tp->tv_sec  = sys_time.tv_sec;
1901   tp->tv_nsec = sys_time.tv_nsec;
1902
1903   return 0;
1904 }
1905
1906 #if InterfaceVersion >= 550
1907 static int darwin_alloc_streams (struct libusb_device_handle *dev_handle, uint32_t num_streams, unsigned char *endpoints,
1908                                  int num_endpoints) {
1909   struct darwin_interface *cInterface;
1910   UInt32 supportsStreams;
1911   uint8_t pipeRef;
1912   int rc, i;
1913
1914   /* find the mimimum number of supported streams on the endpoint list */
1915   for (i = 0 ; i < num_endpoints ; ++i) {
1916     if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface))) {
1917       return rc;
1918     }
1919
1920     (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
1921     if (num_streams > supportsStreams)
1922       num_streams = supportsStreams;
1923   }
1924
1925   /* it is an error if any endpoint in endpoints does not support streams */
1926   if (0 == num_streams)
1927     return LIBUSB_ERROR_INVALID_PARAM;
1928
1929   /* create the streams */
1930   for (i = 0 ; i < num_endpoints ; ++i) {
1931     (void) ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
1932
1933     rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, num_streams);
1934     if (kIOReturnSuccess != rc)
1935       return darwin_to_libusb(rc);
1936   }
1937
1938   return num_streams;
1939 }
1940
1941 static int darwin_free_streams (struct libusb_device_handle *dev_handle, unsigned char *endpoints, int num_endpoints) {
1942   struct darwin_interface *cInterface;
1943   UInt32 supportsStreams;
1944   uint8_t pipeRef;
1945   int rc;
1946
1947   for (int i = 0 ; i < num_endpoints ; ++i) {
1948     if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface)))
1949       return rc;
1950
1951     (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
1952     if (0 == supportsStreams)
1953       return LIBUSB_ERROR_INVALID_PARAM;
1954
1955     rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, 0);
1956     if (kIOReturnSuccess != rc)
1957       return darwin_to_libusb(rc);
1958   }
1959
1960   return LIBUSB_SUCCESS;
1961 }
1962 #endif
1963
1964 const struct usbi_os_backend darwin_backend = {
1965         .name = "Darwin",
1966         .caps = USBI_CAP_HAS_POLLABLE_DEVICE_FD,
1967         .init = darwin_init,
1968         .exit = darwin_exit,
1969         .get_device_list = NULL, /* not needed */
1970         .get_device_descriptor = darwin_get_device_descriptor,
1971         .get_active_config_descriptor = darwin_get_active_config_descriptor,
1972         .get_config_descriptor = darwin_get_config_descriptor,
1973         .hotplug_poll = darwin_hotplug_poll,
1974
1975         .open = darwin_open,
1976         .close = darwin_close,
1977         .get_configuration = darwin_get_configuration,
1978         .set_configuration = darwin_set_configuration,
1979         .claim_interface = darwin_claim_interface,
1980         .release_interface = darwin_release_interface,
1981
1982         .set_interface_altsetting = darwin_set_interface_altsetting,
1983         .clear_halt = darwin_clear_halt,
1984         .reset_device = darwin_reset_device,
1985
1986 #if InterfaceVersion >= 550
1987         .alloc_streams = darwin_alloc_streams,
1988         .free_streams = darwin_free_streams,
1989 #endif
1990
1991         .kernel_driver_active = darwin_kernel_driver_active,
1992         .detach_kernel_driver = darwin_detach_kernel_driver,
1993         .attach_kernel_driver = darwin_attach_kernel_driver,
1994
1995         .destroy_device = darwin_destroy_device,
1996
1997         .submit_transfer = darwin_submit_transfer,
1998         .cancel_transfer = darwin_cancel_transfer,
1999         .clear_transfer_priv = darwin_clear_transfer_priv,
2000
2001         .handle_events = op_handle_events,
2002
2003         .clock_gettime = darwin_clock_gettime,
2004
2005         .device_priv_size = sizeof(struct darwin_device_priv),
2006         .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
2007         .transfer_priv_size = sizeof(struct darwin_transfer_priv),
2008         .add_iso_packet_size = 0,
2009 };