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