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