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