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