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