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