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