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