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