darwin: fix clang warnings about explicit conversion
[platform/upstream/libusb.git] / libusb / os / darwin_usb.c
1 /* -*- Mode: C; indent-tabs-mode:nil -*- */
2 /*
3  * darwin backend for libusbx 1.0
4  * Copyright © 2008-2013 Nathan Hjelm <hjelmn@users.sourceforge.net>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 #include "config.h"
22 #include <ctype.h>
23 #include <errno.h>
24 #include <pthread.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sys/types.h>
29 #include <unistd.h>
30 #include <fcntl.h>
31 #include <libkern/OSAtomic.h>
32
33 #include <mach/clock.h>
34 #include <mach/clock_types.h>
35 #include <mach/mach_host.h>
36 #include <mach/mach_port.h>
37
38 #include <AvailabilityMacros.h>
39 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
40   #include <objc/objc-auto.h>
41 #endif
42
43 #include "darwin_usb.h"
44
45 /* async event thread */
46 static pthread_mutex_t libusb_darwin_at_mutex = PTHREAD_MUTEX_INITIALIZER;
47 static pthread_cond_t  libusb_darwin_at_cond = PTHREAD_COND_INITIALIZER;
48
49 static clock_serv_t clock_realtime;
50 static clock_serv_t clock_monotonic;
51
52 static CFRunLoopRef libusb_darwin_acfl = NULL; /* event cf loop */
53 static volatile int32_t initCount = 0;
54
55 static usbi_mutex_t darwin_cached_devices_lock = PTHREAD_MUTEX_INITIALIZER;
56 static struct list_head darwin_cached_devices = {&darwin_cached_devices, &darwin_cached_devices};
57
58 #define DARWIN_CACHED_DEVICE(a) ((struct darwin_cached_device *) (((struct darwin_device_priv *)((a)->os_priv))->dev))
59
60 /* async event thread */
61 static pthread_t libusb_darwin_at;
62
63 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
64 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
65 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
66 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
67 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
68
69 static int darwin_scan_devices(struct libusb_context *ctx);
70 static int process_new_device (struct libusb_context *ctx, io_service_t service);
71
72 #if defined(ENABLE_LOGGING)
73 static const char *darwin_error_str (int result) {
74   switch (result) {
75   case kIOReturnSuccess:
76     return "no error";
77   case kIOReturnNotOpen:
78     return "device not opened for exclusive access";
79   case kIOReturnNoDevice:
80     return "no connection to an IOService";
81   case kIOUSBNoAsyncPortErr:
82     return "no async port has been opened for interface";
83   case kIOReturnExclusiveAccess:
84     return "another process has device opened for exclusive access";
85   case kIOUSBPipeStalled:
86     return "pipe is stalled";
87   case kIOReturnError:
88     return "could not establish a connection to the Darwin kernel";
89   case kIOUSBTransactionTimeout:
90     return "transaction timed out";
91   case kIOReturnBadArgument:
92     return "invalid argument";
93   case kIOReturnAborted:
94     return "transaction aborted";
95   case kIOReturnNotResponding:
96     return "device not responding";
97   case kIOReturnOverrun:
98     return "data overrun";
99   case kIOReturnCannotWire:
100     return "physical memory can not be wired down";
101   case kIOReturnNoResources:
102     return "out of resources";
103   case kIOUSBHighSpeedSplitError:
104     return "high speed split error";
105   default:
106     return "unknown error";
107   }
108 }
109 #endif
110
111 static int darwin_to_libusb (int result) {
112   switch (result) {
113   case kIOReturnUnderrun:
114   case kIOReturnSuccess:
115     return LIBUSB_SUCCESS;
116   case kIOReturnNotOpen:
117   case kIOReturnNoDevice:
118     return LIBUSB_ERROR_NO_DEVICE;
119   case kIOReturnExclusiveAccess:
120     return LIBUSB_ERROR_ACCESS;
121   case kIOUSBPipeStalled:
122     return LIBUSB_ERROR_PIPE;
123   case kIOReturnBadArgument:
124     return LIBUSB_ERROR_INVALID_PARAM;
125   case kIOUSBTransactionTimeout:
126     return LIBUSB_ERROR_TIMEOUT;
127   case kIOReturnNotResponding:
128   case kIOReturnAborted:
129   case kIOReturnError:
130   case kIOUSBNoAsyncPortErr:
131   default:
132     return LIBUSB_ERROR_OTHER;
133   }
134 }
135
136 /* this function must be called with the darwin_cached_devices_lock held */
137 static void darwin_deref_cached_device(struct darwin_cached_device *cached_dev) {
138   cached_dev->refcount--;
139   /* free the device and remove it from the cache */
140   if (0 == cached_dev->refcount) {
141     list_del(&cached_dev->list);
142
143     (*(cached_dev->device))->Release(cached_dev->device);
144     free (cached_dev);
145   }
146 }
147
148 static void darwin_ref_cached_device(struct darwin_cached_device *cached_dev) {
149   cached_dev->refcount++;
150 }
151
152 static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp) {
153   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
154
155   /* current interface */
156   struct darwin_interface *cInterface;
157
158   int8_t i, iface;
159
160   usbi_dbg ("converting ep address 0x%02x to pipeRef and interface", ep);
161
162   for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
163     cInterface = &priv->interfaces[iface];
164
165     if (dev_handle->claimed_interfaces & (1 << iface)) {
166       for (i = 0 ; i < cInterface->num_endpoints ; i++) {
167         if (cInterface->endpoint_addrs[i] == ep) {
168           *pipep = i + 1;
169           *ifcp = iface;
170           usbi_dbg ("pipe %d on interface %d matches", *pipep, *ifcp);
171           return 0;
172         }
173       }
174     }
175   }
176
177   /* No pipe found with the correct endpoint address */
178   usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
179
180   return -1;
181 }
182
183 static int usb_setup_device_iterator (io_iterator_t *deviceIterator, UInt32 location) {
184   CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBDeviceClassName);
185
186   if (!matchingDict)
187     return kIOReturnError;
188
189   if (location) {
190     CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
191                                                                          &kCFTypeDictionaryKeyCallBacks,
192                                                                          &kCFTypeDictionaryValueCallBacks);
193
194     if (propertyMatchDict) {
195       /* there are no unsigned CFNumber types so treat the value as signed. the os seems to do this
196          internally (CFNumberType of locationID is 3) */
197       CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberSInt32Type, &location);
198
199       CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
200       /* release our reference to the CFNumber (CFDictionarySetValue retains it) */
201       CFRelease (locationCF);
202
203       CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
204       /* release out reference to the CFMutableDictionaryRef (CFDictionarySetValue retains it) */
205       CFRelease (propertyMatchDict);
206     }
207     /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
208   }
209
210   return IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, deviceIterator);
211 }
212
213 /* 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 -1;
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 -1;
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 0;
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   *cached_out = NULL;
747
748   /* get some info from the io registry */
749   (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
750   (void) get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, &port);
751
752   usbi_dbg("finding cached device for sessionID 0x\n" PRIx64, sessionID);
753
754   result = IORegistryEntryGetParentEntry (service, kIOUSBPlane, &parent);
755
756   if (kIOReturnSuccess == result) {
757     (void) get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, &parent_sessionID);
758     IOObjectRelease(parent);
759   }
760
761   usbi_mutex_lock(&darwin_cached_devices_lock);
762   do {
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     new_device = calloc (1, sizeof (*new_device));
778     if (!new_device) {
779       ret = LIBUSB_ERROR_NO_MEM;
780       break;
781     }
782
783     device = darwin_device_from_service (service);
784     if (!device) {
785       ret = LIBUSB_ERROR_NO_DEVICE;
786       free (new_device);
787       new_device = NULL;
788       break;
789     }
790
791     /* add this device to the cached device list */
792     list_add(&new_device->list, &darwin_cached_devices);
793
794     (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
795
796     /* keep a reference to this device */
797     darwin_ref_cached_device(new_device);
798
799     new_device->device = device;
800     new_device->session = sessionID;
801     (*device)->GetLocationID (device, &new_device->location);
802     new_device->port = port;
803     new_device->parent_session = parent_sessionID;
804
805     /* cache the device descriptor */
806     ret = darwin_cache_device_descriptor(ctx, new_device);
807     if (ret)
808       break;
809
810     if (new_device->can_enumerate) {
811       snprintf(new_device->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", new_device->address,
812                new_device->dev_descriptor.idVendor, new_device->dev_descriptor.idProduct,
813                new_device->dev_descriptor.bDeviceClass, new_device->dev_descriptor.bDeviceSubClass);
814     }
815   } while (0);
816
817   usbi_mutex_unlock(&darwin_cached_devices_lock);
818
819   /* keep track of devices regardless of if we successfully enumerate them to
820      prevent them from being enumerated multiple times */
821
822   *cached_out = new_device;
823
824   return ret;
825 }
826
827 static int process_new_device (struct libusb_context *ctx, io_service_t service) {
828   struct darwin_device_priv *priv;
829   struct libusb_device *dev = NULL;
830   struct darwin_cached_device *cached_device;
831   UInt8 devSpeed;
832   int ret = 0;
833
834   do {
835     ret = darwin_get_cached_device (ctx, service, &cached_device);
836
837     if (ret < 0 || (cached_device && !cached_device->can_enumerate)) {
838       return ret;
839     }
840
841     /* check current active configuration (and cache the first configuration value--
842        which may be used by claim_interface) */
843     ret = darwin_check_configuration (ctx, cached_device);
844     if (ret)
845       break;
846
847     usbi_dbg ("allocating new device in context %p for with session 0x%08x",
848               ctx, cached_device->session);
849
850     dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
851     if (!dev) {
852       return LIBUSB_ERROR_NO_MEM;
853     }
854
855     priv = (struct darwin_device_priv *)dev->os_priv;
856
857     priv->dev = cached_device;
858     darwin_ref_cached_device (priv->dev);
859
860     if (cached_device->parent_session > 0) {
861       dev->parent_dev = usbi_get_device_by_session_id (ctx, (unsigned long) cached_device->parent_session);
862     } else {
863       dev->parent_dev = NULL;
864     }
865     dev->port_number    = cached_device->port;
866     dev->bus_number     = cached_device->location >> 24;
867     dev->device_address = cached_device->address;
868
869     /* need to add a reference to the parent device */
870     if (dev->parent_dev) {
871       libusb_ref_device(dev->parent_dev);
872     }
873
874     (*(priv->dev->device))->GetDeviceSpeed (priv->dev->device, &devSpeed);
875
876     switch (devSpeed) {
877     case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
878     case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
879     case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
880 #if DeviceVersion >= 500
881     case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
882 #endif
883     default:
884       usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
885     }
886
887     ret = usbi_sanitize_device (dev);
888     if (ret < 0)
889       break;
890
891     usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address,
892               dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path);
893   } while (0);
894
895   if (0 == ret) {
896     usbi_connect_device (dev);
897   } else {
898     libusb_unref_device (dev);
899   }
900
901   return ret;
902 }
903
904 static int darwin_scan_devices(struct libusb_context *ctx) {
905   io_iterator_t deviceIterator;
906   io_service_t service;
907   kern_return_t kresult;
908
909   kresult = usb_setup_device_iterator (&deviceIterator, 0);
910   if (kresult != kIOReturnSuccess)
911     return darwin_to_libusb (kresult);
912
913   while ((service = IOIteratorNext (deviceIterator))) {
914     (void) process_new_device (ctx, service);
915
916     IOObjectRelease(service);
917   }
918
919   IOObjectRelease(deviceIterator);
920
921   return 0;
922 }
923
924 static int darwin_open (struct libusb_device_handle *dev_handle) {
925   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
926   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
927   IOReturn kresult;
928
929   if (0 == dpriv->open_count) {
930     /* try to open the device */
931     kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
932     if (kresult != kIOReturnSuccess) {
933       usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
934
935       if (kIOReturnExclusiveAccess != kresult) {
936         return darwin_to_libusb (kresult);
937       }
938
939       /* it is possible to perform some actions on a device that is not open so do not return an error */
940       priv->is_open = 0;
941     } else {
942       priv->is_open = 1;
943     }
944
945     /* create async event source */
946     kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
947     if (kresult != kIOReturnSuccess) {
948       usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
949
950       if (priv->is_open) {
951         (*(dpriv->device))->USBDeviceClose (dpriv->device);
952       }
953
954       priv->is_open = 0;
955
956       return darwin_to_libusb (kresult);
957     }
958
959     CFRetain (libusb_darwin_acfl);
960
961     /* add the cfSource to the aync run loop */
962     CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
963   }
964
965   /* device opened successfully */
966   dpriv->open_count++;
967
968   /* create a file descriptor for notifications */
969   pipe (priv->fds);
970
971   /* set the pipe to be non-blocking */
972   fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
973
974   usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
975
976   usbi_dbg ("device open for access");
977
978   return 0;
979 }
980
981 static void darwin_close (struct libusb_device_handle *dev_handle) {
982   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
983   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
984   IOReturn kresult;
985   int i;
986
987   if (dpriv->open_count == 0) {
988     /* something is probably very wrong if this is the case */
989     usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!\n");
990     return;
991   }
992
993   dpriv->open_count--;
994
995   /* make sure all interfaces are released */
996   for (i = 0 ; i < USB_MAXINTERFACES ; i++)
997     if (dev_handle->claimed_interfaces & (1 << i))
998       libusb_release_interface (dev_handle, i);
999
1000   if (0 == dpriv->open_count) {
1001     /* delete the device's async event source */
1002     if (priv->cfSource) {
1003       CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
1004       CFRelease (priv->cfSource);
1005       priv->cfSource = NULL;
1006       CFRelease (libusb_darwin_acfl);
1007     }
1008
1009     if (priv->is_open) {
1010       /* close the device */
1011       kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
1012       if (kresult) {
1013         /* Log the fact that we had a problem closing the file, however failing a
1014          * close isn't really an error, so return success anyway */
1015         usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
1016       }
1017     }
1018   }
1019
1020   /* file descriptors are maintained per-instance */
1021   usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
1022   close (priv->fds[1]);
1023   close (priv->fds[0]);
1024
1025   priv->fds[0] = priv->fds[1] = -1;
1026 }
1027
1028 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
1029   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1030
1031   *config = (int) dpriv->active_config;
1032
1033   return 0;
1034 }
1035
1036 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
1037   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1038   IOReturn kresult;
1039   int i;
1040
1041   /* Setting configuration will invalidate the interface, so we need
1042      to reclaim it. First, dispose of existing interfaces, if any. */
1043   for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1044     if (dev_handle->claimed_interfaces & (1 << i))
1045       darwin_release_interface (dev_handle, i);
1046
1047   kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
1048   if (kresult != kIOReturnSuccess)
1049     return darwin_to_libusb (kresult);
1050
1051   /* Reclaim any interfaces. */
1052   for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1053     if (dev_handle->claimed_interfaces & (1 << i))
1054       darwin_claim_interface (dev_handle, i);
1055
1056   dpriv->active_config = config;
1057
1058   return 0;
1059 }
1060
1061 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
1062   IOUSBFindInterfaceRequest request;
1063   kern_return_t             kresult;
1064   io_iterator_t             interface_iterator;
1065   UInt8                     bInterfaceNumber;
1066   int                       ret;
1067
1068   *usbInterfacep = IO_OBJECT_NULL;
1069
1070   /* Setup the Interface Request */
1071   request.bInterfaceClass    = kIOUSBFindInterfaceDontCare;
1072   request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1073   request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1074   request.bAlternateSetting  = kIOUSBFindInterfaceDontCare;
1075
1076   kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1077   if (kresult)
1078     return kresult;
1079
1080   while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
1081     /* find the interface number */
1082     ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
1083                                        &bInterfaceNumber);
1084
1085     if (ret && bInterfaceNumber == ifc) {
1086       break;
1087     }
1088
1089     (void) IOObjectRelease (*usbInterfacep);
1090   }
1091
1092   /* done with the interface iterator */
1093   IOObjectRelease(interface_iterator);
1094
1095   return 0;
1096 }
1097
1098 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
1099   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1100
1101   /* current interface */
1102   struct darwin_interface *cInterface = &priv->interfaces[iface];
1103
1104   kern_return_t kresult;
1105
1106   u_int8_t numep, direction, number;
1107   u_int8_t dont_care1, dont_care3;
1108   u_int16_t dont_care2;
1109   int i;
1110
1111   usbi_dbg ("building table of endpoints.");
1112
1113   /* retrieve the total number of endpoints on this interface */
1114   kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
1115   if (kresult) {
1116     usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1117     return darwin_to_libusb (kresult);
1118   }
1119
1120   /* iterate through pipe references */
1121   for (i = 1 ; i <= numep ; i++) {
1122     kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1123                                                             &dont_care2, &dont_care3);
1124
1125     if (kresult != kIOReturnSuccess) {
1126       usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
1127
1128       return darwin_to_libusb (kresult);
1129     }
1130
1131     usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
1132
1133     cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1134   }
1135
1136   cInterface->num_endpoints = numep;
1137
1138   return 0;
1139 }
1140
1141 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1142   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1143   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1144   io_service_t          usbInterface = IO_OBJECT_NULL;
1145   IOReturn kresult;
1146   IOCFPlugInInterface **plugInInterface = NULL;
1147   SInt32                score;
1148
1149   /* current interface */
1150   struct darwin_interface *cInterface = &priv->interfaces[iface];
1151
1152   kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1153   if (kresult != kIOReturnSuccess)
1154     return darwin_to_libusb (kresult);
1155
1156   /* make sure we have an interface */
1157   if (!usbInterface && dpriv->first_config != 0) {
1158     usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1159
1160     /* set the configuration */
1161     kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1162     if (kresult != LIBUSB_SUCCESS) {
1163       usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1164       return kresult;
1165     }
1166
1167     kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1168     if (kresult) {
1169       usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1170       return darwin_to_libusb (kresult);
1171     }
1172   }
1173
1174   if (!usbInterface) {
1175     usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1176     return LIBUSB_ERROR_NOT_FOUND;
1177   }
1178
1179   /* get an interface to the device's interface */
1180   kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1181                                                kIOCFPlugInInterfaceID, &plugInInterface, &score);
1182
1183   /* ignore release error */
1184   (void)IOObjectRelease (usbInterface);
1185
1186   if (kresult) {
1187     usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1188     return darwin_to_libusb (kresult);
1189   }
1190
1191   if (!plugInInterface) {
1192     usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1193     return LIBUSB_ERROR_NOT_FOUND;
1194   }
1195
1196   /* Do the actual claim */
1197   kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1198                                                CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1199                                                (LPVOID)&cInterface->interface);
1200   /* We no longer need the intermediate plug-in */
1201   /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1202   (*plugInInterface)->Release (plugInInterface);
1203   if (kresult || !cInterface->interface) {
1204     usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1205     return darwin_to_libusb (kresult);
1206   }
1207
1208   /* claim the interface */
1209   kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1210   if (kresult) {
1211     usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1212     return darwin_to_libusb (kresult);
1213   }
1214
1215   /* update list of endpoints */
1216   kresult = get_endpoints (dev_handle, iface);
1217   if (kresult) {
1218     /* this should not happen */
1219     darwin_release_interface (dev_handle, iface);
1220     usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1221     return kresult;
1222   }
1223
1224   cInterface->cfSource = NULL;
1225
1226   /* create async event source */
1227   kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1228   if (kresult != kIOReturnSuccess) {
1229     usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1230
1231     /* can't continue without an async event source */
1232     (void)darwin_release_interface (dev_handle, iface);
1233
1234     return darwin_to_libusb (kresult);
1235   }
1236
1237   /* add the cfSource to the async thread's run loop */
1238   CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1239
1240   usbi_dbg ("interface opened");
1241
1242   return 0;
1243 }
1244
1245 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1246   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1247   IOReturn kresult;
1248
1249   /* current interface */
1250   struct darwin_interface *cInterface = &priv->interfaces[iface];
1251
1252   /* Check to see if an interface is open */
1253   if (!cInterface->interface)
1254     return LIBUSB_SUCCESS;
1255
1256   /* clean up endpoint data */
1257   cInterface->num_endpoints = 0;
1258
1259   /* delete the interface's async event source */
1260   if (cInterface->cfSource) {
1261     CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1262     CFRelease (cInterface->cfSource);
1263   }
1264
1265   kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1266   if (kresult)
1267     usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1268
1269   kresult = (*(cInterface->interface))->Release(cInterface->interface);
1270   if (kresult != kIOReturnSuccess)
1271     usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1272
1273   cInterface->interface = IO_OBJECT_NULL;
1274
1275   return darwin_to_libusb (kresult);
1276 }
1277
1278 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1279   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1280   IOReturn kresult;
1281
1282   /* current interface */
1283   struct darwin_interface *cInterface = &priv->interfaces[iface];
1284
1285   if (!cInterface->interface)
1286     return LIBUSB_ERROR_NO_DEVICE;
1287
1288   kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1289   if (kresult != kIOReturnSuccess)
1290     darwin_reset_device (dev_handle);
1291
1292   /* update list of endpoints */
1293   kresult = get_endpoints (dev_handle, iface);
1294   if (kresult) {
1295     /* this should not happen */
1296     darwin_release_interface (dev_handle, iface);
1297     usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1298     return kresult;
1299   }
1300
1301   return darwin_to_libusb (kresult);
1302 }
1303
1304 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1305   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1306
1307   /* current interface */
1308   struct darwin_interface *cInterface;
1309   uint8_t pipeRef, iface;
1310   IOReturn kresult;
1311
1312   /* determine the interface/endpoint to use */
1313   if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
1314     usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1315
1316     return LIBUSB_ERROR_NOT_FOUND;
1317   }
1318
1319   cInterface = &priv->interfaces[iface];
1320
1321   /* newer versions of darwin support clearing additional bits on the device's endpoint */
1322   kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1323   if (kresult)
1324     usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1325
1326   return darwin_to_libusb (kresult);
1327 }
1328
1329 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1330   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1331   IOUSBDeviceDescriptor descriptor;
1332   IOUSBConfigurationDescriptorPtr cached_configuration;
1333   IOUSBConfigurationDescriptor configuration;
1334   bool reenumerate = false;
1335   IOReturn kresult;
1336   int i;
1337
1338   kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1339   if (kresult) {
1340     usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1341     return darwin_to_libusb (kresult);
1342   }
1343
1344   do {
1345     usbi_dbg ("darwin/reset_device: checking if device descriptor changed");
1346
1347     /* ignore return code. if we can't get a descriptor it might be worthwhile re-enumerating anway */
1348     (void) darwin_request_descriptor (dpriv->device, kUSBDeviceDesc, 0, &descriptor, sizeof (descriptor));
1349
1350     /* check if the device descriptor has changed */
1351     if (0 != memcmp (&dpriv->dev_descriptor, &descriptor, sizeof (descriptor))) {
1352       reenumerate = true;
1353       break;
1354     }
1355
1356     /* check if any configuration descriptor has changed */
1357     for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1358       usbi_dbg ("darwin/reset_device: checking if configuration descriptor %d changed", i);
1359
1360       (void) darwin_request_descriptor (dpriv->device, kUSBConfDesc, i, &configuration, sizeof (configuration));
1361       (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1362
1363       if (!cached_configuration || 0 != memcmp (cached_configuration, &configuration, sizeof (configuration))) {
1364         reenumerate = true;
1365         break;
1366       }
1367     }
1368   } while (0);
1369
1370   if (reenumerate) {
1371     usbi_dbg ("darwin/reset_device: device requires reenumeration");
1372     (void) (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
1373     return LIBUSB_ERROR_NOT_FOUND;
1374   }
1375
1376   usbi_dbg ("darwin/reset_device: device reset complete");
1377
1378   return LIBUSB_SUCCESS;
1379 }
1380
1381 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1382   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1383   io_service_t usbInterface;
1384   CFTypeRef driver;
1385   IOReturn kresult;
1386
1387   kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1388   if (kresult) {
1389     usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1390
1391     return darwin_to_libusb (kresult);
1392   }
1393
1394   driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1395   IOObjectRelease (usbInterface);
1396
1397   if (driver) {
1398     CFRelease (driver);
1399
1400     return 1;
1401   }
1402
1403   /* no driver */
1404   return 0;
1405 }
1406
1407 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1408 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1409   (void)dev_handle;
1410   (void)interface;
1411   return LIBUSB_ERROR_NOT_SUPPORTED;
1412 }
1413
1414 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1415   (void)dev_handle;
1416   (void)interface;
1417   return LIBUSB_ERROR_NOT_SUPPORTED;
1418 }
1419
1420 static void darwin_destroy_device(struct libusb_device *dev) {
1421   struct darwin_device_priv *dpriv = (struct darwin_device_priv *) dev->os_priv;
1422
1423   if (dpriv->dev) {
1424     /* need to hold the lock in case this is the last reference to the device */
1425     usbi_mutex_lock(&darwin_cached_devices_lock);
1426     darwin_deref_cached_device (dpriv->dev);
1427     dpriv->dev = NULL;
1428     usbi_mutex_unlock(&darwin_cached_devices_lock);
1429   }
1430 }
1431
1432 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1433   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1434   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1435
1436   IOReturn               ret;
1437   uint8_t                transferType;
1438   /* None of the values below are used in libusbx for bulk transfers */
1439   uint8_t                direction, number, interval, pipeRef, iface;
1440   uint16_t               maxPacketSize;
1441
1442   struct darwin_interface *cInterface;
1443
1444   if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1445     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1446
1447     return LIBUSB_ERROR_NOT_FOUND;
1448   }
1449
1450   cInterface = &priv->interfaces[iface];
1451
1452   (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1453                                                  &transferType, &maxPacketSize, &interval);
1454
1455   if (0 != (transfer->length % maxPacketSize)) {
1456     /* do not need a zero packet */
1457     transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1458   }
1459
1460   /* submit the request */
1461   /* timeouts are unavailable on interrupt endpoints */
1462   if (transferType == kUSBInterrupt) {
1463     if (IS_XFERIN(transfer))
1464       ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1465                                                       transfer->length, darwin_async_io_callback, itransfer);
1466     else
1467       ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1468                                                        transfer->length, darwin_async_io_callback, itransfer);
1469   } else {
1470     itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1471
1472     if (IS_XFERIN(transfer))
1473       ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1474                                                         transfer->length, transfer->timeout, transfer->timeout,
1475                                                         darwin_async_io_callback, (void *)itransfer);
1476     else
1477       ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1478                                                          transfer->length, transfer->timeout, transfer->timeout,
1479                                                          darwin_async_io_callback, (void *)itransfer);
1480   }
1481
1482   if (ret)
1483     usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1484                darwin_error_str(ret), ret);
1485
1486   return darwin_to_libusb (ret);
1487 }
1488
1489 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1490   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1491   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1492   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1493
1494   IOReturn kresult;
1495   uint8_t direction, number, interval, pipeRef, iface, transferType;
1496   uint16_t maxPacketSize;
1497   UInt64 frame;
1498   AbsoluteTime atTime;
1499   int i;
1500
1501   struct darwin_interface *cInterface;
1502
1503   /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1504   if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1505     free(tpriv->isoc_framelist);
1506     tpriv->isoc_framelist = NULL;
1507   }
1508
1509   if (!tpriv->isoc_framelist) {
1510     tpriv->num_iso_packets = transfer->num_iso_packets;
1511     tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1512     if (!tpriv->isoc_framelist)
1513       return LIBUSB_ERROR_NO_MEM;
1514   }
1515
1516   /* copy the frame list from the libusbx descriptor (the structures differ only is member order) */
1517   for (i = 0 ; i < transfer->num_iso_packets ; i++)
1518     tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1519
1520   /* determine the interface/endpoint to use */
1521   if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1522     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1523
1524     return LIBUSB_ERROR_NOT_FOUND;
1525   }
1526
1527   cInterface = &priv->interfaces[iface];
1528
1529   /* determine the properties of this endpoint and the speed of the device */
1530   (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1531                                                  &transferType, &maxPacketSize, &interval);
1532
1533   /* Last but not least we need the bus frame number */
1534   kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1535   if (kresult) {
1536     usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1537     free(tpriv->isoc_framelist);
1538     tpriv->isoc_framelist = NULL;
1539
1540     return darwin_to_libusb (kresult);
1541   }
1542
1543   (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1544                                                  &transferType, &maxPacketSize, &interval);
1545
1546   /* schedule for a frame a little in the future */
1547   frame += 4;
1548
1549   if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1550     frame = cInterface->frames[transfer->endpoint];
1551
1552   /* submit the request */
1553   if (IS_XFERIN(transfer))
1554     kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1555                                                              transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1556                                                              itransfer);
1557   else
1558     kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1559                                                               transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1560                                                               itransfer);
1561
1562   if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
1563     /* Full speed */
1564     cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1));
1565   else
1566     /* High/super speed */
1567     cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1)) / 8;
1568
1569   if (kresult != kIOReturnSuccess) {
1570     usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1571                darwin_error_str(kresult));
1572     free (tpriv->isoc_framelist);
1573     tpriv->isoc_framelist = NULL;
1574   }
1575
1576   return darwin_to_libusb (kresult);
1577 }
1578
1579 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1580   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1581   struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1582   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1583   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1584   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1585
1586   IOReturn               kresult;
1587
1588   bzero(&tpriv->req, sizeof(tpriv->req));
1589
1590   /* IOUSBDeviceInterface expects the request in cpu endianess */
1591   tpriv->req.bmRequestType     = setup->bmRequestType;
1592   tpriv->req.bRequest          = setup->bRequest;
1593   /* these values should be in bus order from libusb_fill_control_setup */
1594   tpriv->req.wValue            = OSSwapLittleToHostInt16 (setup->wValue);
1595   tpriv->req.wIndex            = OSSwapLittleToHostInt16 (setup->wIndex);
1596   tpriv->req.wLength           = OSSwapLittleToHostInt16 (setup->wLength);
1597   /* data is stored after the libusbx control block */
1598   tpriv->req.pData             = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1599   tpriv->req.completionTimeout = transfer->timeout;
1600   tpriv->req.noDataTimeout     = transfer->timeout;
1601
1602   itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1603
1604   /* all transfers in libusb-1.0 are async */
1605
1606   if (transfer->endpoint) {
1607     struct darwin_interface *cInterface;
1608     uint8_t                 pipeRef, iface;
1609
1610     if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1611       usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1612
1613       return LIBUSB_ERROR_NOT_FOUND;
1614     }
1615
1616     cInterface = &priv->interfaces[iface];
1617
1618     kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1619   } else
1620     /* control request on endpoint 0 */
1621     kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1622
1623   if (kresult != kIOReturnSuccess)
1624     usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1625
1626   return darwin_to_libusb (kresult);
1627 }
1628
1629 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1630   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1631
1632   switch (transfer->type) {
1633   case LIBUSB_TRANSFER_TYPE_CONTROL:
1634     return submit_control_transfer(itransfer);
1635   case LIBUSB_TRANSFER_TYPE_BULK:
1636   case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1637     return submit_bulk_transfer(itransfer);
1638   case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1639     return submit_iso_transfer(itransfer);
1640   default:
1641     usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1642     return LIBUSB_ERROR_INVALID_PARAM;
1643   }
1644 }
1645
1646 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1647   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1648   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1649   IOReturn kresult;
1650
1651   usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
1652
1653   if (!dpriv->device)
1654     return LIBUSB_ERROR_NO_DEVICE;
1655
1656   kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1657
1658   return darwin_to_libusb (kresult);
1659 }
1660
1661 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1662   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1663   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1664   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1665   struct darwin_interface *cInterface;
1666   uint8_t pipeRef, iface;
1667   IOReturn kresult;
1668
1669   if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1670     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1671
1672     return LIBUSB_ERROR_NOT_FOUND;
1673   }
1674
1675   cInterface = &priv->interfaces[iface];
1676
1677   if (!dpriv->device)
1678     return LIBUSB_ERROR_NO_DEVICE;
1679
1680   usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
1681
1682   /* abort transactions */
1683   (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1684
1685   usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
1686
1687   /* newer versions of darwin support clearing additional bits on the device's endpoint */
1688   kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1689
1690   return darwin_to_libusb (kresult);
1691 }
1692
1693 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1694   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1695
1696   switch (transfer->type) {
1697   case LIBUSB_TRANSFER_TYPE_CONTROL:
1698     return cancel_control_transfer(itransfer);
1699   case LIBUSB_TRANSFER_TYPE_BULK:
1700   case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1701   case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1702     return darwin_abort_transfers (itransfer);
1703   default:
1704     usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1705     return LIBUSB_ERROR_INVALID_PARAM;
1706   }
1707 }
1708
1709 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1710   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1711   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1712
1713   if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1714     free (tpriv->isoc_framelist);
1715     tpriv->isoc_framelist = NULL;
1716   }
1717 }
1718
1719 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1720   struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1721   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1722   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1723   struct darwin_msg_async_io_complete message = {.itransfer = itransfer, .result = result,
1724                                                  .size = (UInt32) (uintptr_t) arg0};
1725
1726   usbi_dbg ("an async io operation has completed");
1727
1728   /* if requested write a zero packet */
1729   if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
1730     struct darwin_interface *cInterface;
1731     uint8_t iface, pipeRef;
1732
1733     (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface);
1734     cInterface = &priv->interfaces[iface];
1735
1736     (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
1737   }
1738
1739   /* send a completion message to the device's file descriptor */
1740   write (priv->fds[1], &message, sizeof (message));
1741 }
1742
1743 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1744   if (itransfer->flags & USBI_TRANSFER_TIMED_OUT)
1745     result = kIOUSBTransactionTimeout;
1746
1747   switch (result) {
1748   case kIOReturnUnderrun:
1749   case kIOReturnSuccess:
1750     return LIBUSB_TRANSFER_COMPLETED;
1751   case kIOReturnAborted:
1752     return LIBUSB_TRANSFER_CANCELLED;
1753   case kIOUSBPipeStalled:
1754     usbi_dbg ("transfer error: pipe is stalled");
1755     return LIBUSB_TRANSFER_STALL;
1756   case kIOReturnOverrun:
1757     usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1758     return LIBUSB_TRANSFER_OVERFLOW;
1759   case kIOUSBTransactionTimeout:
1760     usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1761     itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
1762     return LIBUSB_TRANSFER_TIMED_OUT;
1763   default:
1764     usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1765     return LIBUSB_TRANSFER_ERROR;
1766   }
1767 }
1768
1769 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1770   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1771   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1772   int isIsoc      = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1773   int isBulk      = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1774   int isControl   = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1775   int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1776   int i;
1777
1778   if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1779     usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1780     return;
1781   }
1782
1783   usbi_dbg ("handling %s completion with kernel status %d",
1784              isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", result);
1785
1786   if (kIOReturnSuccess == result || kIOReturnUnderrun == result) {
1787     if (isIsoc && tpriv->isoc_framelist) {
1788       /* copy isochronous results back */
1789
1790       for (i = 0; i < transfer->num_iso_packets ; i++) {
1791         struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1792         lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1793         lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1794       }
1795     } else if (!isIsoc)
1796       itransfer->transferred += io_size;
1797   }
1798
1799   /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1800   usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, result));
1801 }
1802
1803 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready) {
1804   struct darwin_msg_async_io_complete message;
1805   POLL_NFDS_TYPE i = 0;
1806   ssize_t ret;
1807
1808   usbi_mutex_lock(&ctx->open_devs_lock);
1809
1810   for (i = 0; i < nfds && num_ready > 0; i++) {
1811     struct pollfd *pollfd = &fds[i];
1812
1813     usbi_dbg ("checking fd %i with revents = %x", pollfd->fd, pollfd->revents);
1814
1815     if (!pollfd->revents)
1816       continue;
1817
1818     num_ready--;
1819
1820     if (pollfd->revents & POLLERR) {
1821       /* this probably will never happen so ignore the error an move on. */
1822       continue;
1823     }
1824
1825     /* there is only one type of message */
1826     ret = read (pollfd->fd, &message, sizeof (message));
1827     if (ret < (ssize_t) sizeof (message)) {
1828       usbi_dbg ("WARNING: short read on async io completion pipe\n");
1829       continue;
1830     }
1831
1832     darwin_handle_callback (message.itransfer, message.result, message.size);
1833   }
1834
1835   usbi_mutex_unlock(&ctx->open_devs_lock);
1836
1837   return 0;
1838 }
1839
1840 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1841   mach_timespec_t sys_time;
1842   clock_serv_t clock_ref;
1843
1844   switch (clk_id) {
1845   case USBI_CLOCK_REALTIME:
1846     /* CLOCK_REALTIME represents time since the epoch */
1847     clock_ref = clock_realtime;
1848     break;
1849   case USBI_CLOCK_MONOTONIC:
1850     /* use system boot time as reference for the monotonic clock */
1851     clock_ref = clock_monotonic;
1852     break;
1853   default:
1854     return LIBUSB_ERROR_INVALID_PARAM;
1855   }
1856
1857   clock_get_time (clock_ref, &sys_time);
1858
1859   tp->tv_sec  = sys_time.tv_sec;
1860   tp->tv_nsec = sys_time.tv_nsec;
1861
1862   return 0;
1863 }
1864
1865 const struct usbi_os_backend darwin_backend = {
1866         .name = "Darwin",
1867         .caps = 0,
1868         .init = darwin_init,
1869         .exit = darwin_exit,
1870         .get_device_list = NULL, /* not needed */
1871         .get_device_descriptor = darwin_get_device_descriptor,
1872         .get_active_config_descriptor = darwin_get_active_config_descriptor,
1873         .get_config_descriptor = darwin_get_config_descriptor,
1874
1875         .open = darwin_open,
1876         .close = darwin_close,
1877         .get_configuration = darwin_get_configuration,
1878         .set_configuration = darwin_set_configuration,
1879         .claim_interface = darwin_claim_interface,
1880         .release_interface = darwin_release_interface,
1881
1882         .set_interface_altsetting = darwin_set_interface_altsetting,
1883         .clear_halt = darwin_clear_halt,
1884         .reset_device = darwin_reset_device,
1885
1886         .kernel_driver_active = darwin_kernel_driver_active,
1887         .detach_kernel_driver = darwin_detach_kernel_driver,
1888         .attach_kernel_driver = darwin_attach_kernel_driver,
1889
1890         .destroy_device = darwin_destroy_device,
1891
1892         .submit_transfer = darwin_submit_transfer,
1893         .cancel_transfer = darwin_cancel_transfer,
1894         .clear_transfer_priv = darwin_clear_transfer_priv,
1895
1896         .handle_events = op_handle_events,
1897
1898         .clock_gettime = darwin_clock_gettime,
1899
1900         .device_priv_size = sizeof(struct darwin_device_priv),
1901         .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1902         .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1903         .add_iso_packet_size = 0,
1904 };