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