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