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