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