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