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