macOS Sierra: Fix detection of parent devices.
[platform/upstream/libusb.git] / libusb / os / darwin_usb.c
index 146218b..739644e 100644 (file)
@@ -1,7 +1,7 @@
 /* -*- Mode: C; indent-tabs-mode:nil -*- */
 /*
- * darwin backend for libusbx 1.0
- * Copyright © 2008-2013 Nathan Hjelm <hjelmn@users.sourceforge.net>
+ * darwin backend for libusb 1.0
+ * Copyright © 2008-2017 Nathan Hjelm <hjelmn@users.sourceforge.net>
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
@@ -19,6 +19,7 @@
  */
 
 #include "config.h"
+#include <time.h>
 #include <ctype.h>
 #include <errno.h>
 #include <pthread.h>
@@ -28,7 +29,7 @@
 #include <sys/types.h>
 #include <unistd.h>
 #include <fcntl.h>
-#include <libkern/OSAtomic.h>
+#include <sys/sysctl.h>
 
 #include <mach/clock.h>
 #include <mach/clock_types.h>
 #include <mach/mach_port.h>
 
 #include <AvailabilityMacros.h>
-#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
+#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
   #include <objc/objc-auto.h>
 #endif
 
+#if MAC_OS_X_VERSION_MIN_REQUIRED >= 101200
+/* Apple deprecated the darwin atomics in 10.12 in favor of C11 atomics */
+#include <stdatomic.h>
+#define libusb_darwin_atomic_fetch_add(x, y) atomic_fetch_add(x, y)
+#define OSX_USE_CLOCK_GETTIME 1
+
+_Atomic int32_t initCount = ATOMIC_VAR_INIT(0);
+#else
+/* use darwin atomics if the target is older than 10.12 */
+#include <libkern/OSAtomic.h>
+
+/* OSAtomicAdd32Barrier returns the new value */
+#define libusb_darwin_atomic_fetch_add(x, y) (OSAtomicAdd32Barrier(y, x) - y)
+
+static volatile int32_t initCount = 0;
+
+#define OSX_USE_CLOCK_GETTIME 0
+#endif
+
 #include "darwin_usb.h"
 
 /* async event thread */
 static pthread_mutex_t libusb_darwin_at_mutex = PTHREAD_MUTEX_INITIALIZER;
 static pthread_cond_t  libusb_darwin_at_cond = PTHREAD_COND_INITIALIZER;
 
+static pthread_once_t darwin_init_once = PTHREAD_ONCE_INIT;
+
+#if !OSX_USE_CLOCK_GETTIME
 static clock_serv_t clock_realtime;
 static clock_serv_t clock_monotonic;
+#endif
 
 static CFRunLoopRef libusb_darwin_acfl = NULL; /* event cf loop */
-static volatile int32_t initCount = 0;
+static CFRunLoopSourceRef libusb_darwin_acfls = NULL; /* shutdown signal for event cf loop */
 
 static usbi_mutex_t darwin_cached_devices_lock = PTHREAD_MUTEX_INITIALIZER;
 static struct list_head darwin_cached_devices = {&darwin_cached_devices, &darwin_cached_devices};
+static char *darwin_device_class = kIOUSBDeviceClassName;
 
 #define DARWIN_CACHED_DEVICE(a) ((struct darwin_cached_device *) (((struct darwin_device_priv *)((a)->os_priv))->dev))
 
@@ -151,7 +176,7 @@ static void darwin_ref_cached_device(struct darwin_cached_device *cached_dev) {
   cached_dev->refcount++;
 }
 
-static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp) {
+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) {
   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
 
   /* current interface */
@@ -168,8 +193,14 @@ static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, ui
       for (i = 0 ; i < cInterface->num_endpoints ; i++) {
         if (cInterface->endpoint_addrs[i] == ep) {
           *pipep = i + 1;
-          *ifcp = iface;
-          usbi_dbg ("pipe %d on interface %d matches", *pipep, *ifcp);
+
+          if (ifcp)
+            *ifcp = iface;
+
+          if (interface_out)
+            *interface_out = cInterface;
+
+          usbi_dbg ("pipe %d on interface %d matches", *pipep, iface);
           return 0;
         }
       }
@@ -179,11 +210,11 @@ static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, ui
   /* No pipe found with the correct endpoint address */
   usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
 
-  return -1;
+  return LIBUSB_ERROR_NOT_FOUND;
 }
 
 static int usb_setup_device_iterator (io_iterator_t *deviceIterator, UInt32 location) {
-  CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBDeviceClassName);
+  CFMutableDictionaryRef matchingDict = IOServiceMatching(darwin_device_class);
 
   if (!matchingDict)
     return kIOReturnError;
@@ -228,6 +259,27 @@ static int get_ioregistry_value_number (io_service_t service, CFStringRef proper
   return ret;
 }
 
+static int get_ioregistry_value_data (io_service_t service, CFStringRef property, ssize_t size, void *p) {
+  CFTypeRef cfData = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
+  int ret = 0;
+
+  if (cfData) {
+    if (CFGetTypeID (cfData) == CFDataGetTypeID ()) {
+      CFIndex length = CFDataGetLength (cfData);
+      if (length < size) {
+        size = length;
+      }
+
+      CFDataGetBytes (cfData, CFRangeMake(0, size), p);
+      ret = 1;
+    }
+
+    CFRelease (cfData);
+  }
+
+  return ret;
+}
+
 static usb_device_t **darwin_device_from_service (io_service_t service)
 {
   io_cf_plugin_ref_t *plugInInterface = NULL;
@@ -240,7 +292,7 @@ static usb_device_t **darwin_device_from_service (io_service_t service)
                                              &score);
 
   if (kIOReturnSuccess != result || !plugInInterface) {
-    usbi_dbg ("could not set up plugin for service: %s\n", darwin_error_str (result));
+    usbi_dbg ("could not set up plugin for service: %s", darwin_error_str (result));
     return NULL;
   }
 
@@ -273,11 +325,14 @@ static void darwin_devices_attached (void *ptr, io_iterator_t add_devices) {
 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
   struct libusb_device *dev = NULL;
   struct libusb_context *ctx;
+  struct darwin_cached_device *old_device;
 
   io_service_t device;
   UInt64 session;
   int ret;
 
+  usbi_mutex_lock(&active_contexts_lock);
+
   while ((device = IOIteratorNext (rem_devices)) != 0) {
     /* get the location from the i/o registry */
     ret = get_ioregistry_value_number (device, CFSTR("sessionID"), kCFNumberSInt64Type, &session);
@@ -285,7 +340,16 @@ static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
     if (!ret)
       continue;
 
-    usbi_mutex_lock(&active_contexts_lock);
+    /* we need to match darwin_ref_cached_device call made in darwin_get_cached_device function
+       otherwise no cached device will ever get freed */
+    usbi_mutex_lock(&darwin_cached_devices_lock);
+    list_for_each_entry(old_device, &darwin_cached_devices, list, struct darwin_cached_device) {
+      if (old_device->session == session) {
+        darwin_deref_cached_device (old_device);
+        break;
+      }
+    }
+    usbi_mutex_unlock(&darwin_cached_devices_lock);
 
     list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
       usbi_dbg ("notifying context %p of device disconnect", ctx);
@@ -298,9 +362,20 @@ static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
         libusb_unref_device(dev);
       }
     }
-
-    usbi_mutex_unlock(&active_contexts_lock);
   }
+
+  usbi_mutex_unlock(&active_contexts_lock);
+}
+
+static void darwin_hotplug_poll (void)
+{
+  /* not sure if 5 seconds will be too long/short but it should work ok */
+  mach_timespec_t timeout = {.tv_sec = 5, .tv_nsec = 0};
+
+  /* since a kernel thread may nodify the IOInterators used for
+   * hotplug notidication we can't just clear the iterators.
+   * instead just wait until all IOService providers are quiet */
+  (void) IOKitWaitQuiet (kIOMasterPortDefault, &timeout);
 }
 
 static void darwin_clear_iterator (io_iterator_t iter) {
@@ -315,19 +390,24 @@ static void *darwin_event_thread_main (void *arg0) {
   struct libusb_context *ctx = (struct libusb_context *)arg0;
   CFRunLoopRef runloop;
 
+#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
   /* Set this thread's name, so it can be seen in the debugger
      and crash reports. */
-#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
   pthread_setname_np ("org.libusb.device-hotplug");
+#endif
 
+#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
   /* Tell the Objective-C garbage collector about this thread.
      This is required because, unlike NSThreads, pthreads are
      not automatically registered. Although we don't use
-     Objective-C, we use CoreFoundation, which does. */
+     Objective-C, we use CoreFoundation, which does.
+     Garbage collection support was entirely removed in 10.12,
+     so don't bother there. */
   objc_registerThreadWithCollector();
 #endif
 
   /* hotplug (device arrival/removal) sources */
+  CFRunLoopSourceContext libusb_shutdown_cfsourcectx;
   CFRunLoopSourceRef     libusb_notification_cfsource;
   io_notification_port_t libusb_notification_port;
   io_iterator_t          libusb_rem_device_iterator;
@@ -338,6 +418,13 @@ static void *darwin_event_thread_main (void *arg0) {
   runloop = CFRunLoopGetCurrent ();
   CFRetain (runloop);
 
+  /* add the shutdown cfsource to the run loop */
+  memset(&libusb_shutdown_cfsourcectx, 0, sizeof(libusb_shutdown_cfsourcectx));
+  libusb_shutdown_cfsourcectx.info = runloop;
+  libusb_shutdown_cfsourcectx.perform = (void (*)(void *))CFRunLoopStop;
+  libusb_darwin_acfls = CFRunLoopSourceCreate(NULL, 0, &libusb_shutdown_cfsourcectx);
+  CFRunLoopAddSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode);
+
   /* add the notification port to the run loop */
   libusb_notification_port     = IONotificationPortCreate (kIOMasterPortDefault);
   libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
@@ -345,9 +432,9 @@ static void *darwin_event_thread_main (void *arg0) {
 
   /* create notifications for removed devices */
   kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
-                                              IOServiceMatching(kIOUSBDeviceClassName),
-                                              (IOServiceMatchingCallback)darwin_devices_detached,
-                                              (void *)ctx, &libusb_rem_device_iterator);
+                                              IOServiceMatching(darwin_device_class),
+                                              darwin_devices_detached,
+                                              ctx, &libusb_rem_device_iterator);
 
   if (kresult != kIOReturnSuccess) {
     usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
@@ -357,9 +444,9 @@ static void *darwin_event_thread_main (void *arg0) {
 
   /* create notifications for attached devices */
   kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification,
-                                              IOServiceMatching(kIOUSBDeviceClassName),
-                                              (IOServiceMatchingCallback)darwin_devices_attached,
-                                              (void *)ctx, &libusb_add_device_iterator);
+                                              IOServiceMatching(darwin_device_class),
+                                              darwin_devices_attached,
+                                              ctx, &libusb_add_device_iterator);
 
   if (kresult != kIOReturnSuccess) {
     usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
@@ -387,6 +474,9 @@ static void *darwin_event_thread_main (void *arg0) {
   /* remove the notification cfsource */
   CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
 
+  /* remove the shutdown cfsource */
+  CFRunLoopRemoveSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode);
+
   /* delete notification port */
   IONotificationPortDestroy (libusb_notification_port);
 
@@ -394,14 +484,17 @@ static void *darwin_event_thread_main (void *arg0) {
   IOObjectRelease (libusb_rem_device_iterator);
   IOObjectRelease (libusb_add_device_iterator);
 
+  CFRelease (libusb_darwin_acfls);
   CFRelease (runloop);
 
+  libusb_darwin_acfls = NULL;
   libusb_darwin_acfl = NULL;
 
   pthread_exit (NULL);
 }
 
-static void _darwin_finalize(void) {
+/* cleanup function to destroy cached devices */
+static void __attribute__((destructor)) _darwin_finalize(void) {
   struct darwin_cached_device *dev, *next;
 
   usbi_mutex_lock(&darwin_cached_devices_lock);
@@ -411,30 +504,47 @@ static void _darwin_finalize(void) {
   usbi_mutex_unlock(&darwin_cached_devices_lock);
 }
 
+static void darwin_check_version (void) {
+  /* adjust for changes in the USB stack in xnu 15 */
+  int sysctl_args[] = {CTL_KERN, KERN_OSRELEASE};
+  long version;
+  char version_string[256] = {'\0',};
+  size_t length = 256;
+
+  sysctl(sysctl_args, 2, version_string, &length, NULL, 0);
+
+  errno = 0;
+  version = strtol (version_string, NULL, 10);
+  if (0 == errno && version >= 15) {
+    darwin_device_class = "IOUSBHostDevice";
+  }
+}
+
 static int darwin_init(struct libusb_context *ctx) {
-  host_name_port_t host_self;
-  static int initted = 0;
   int rc;
 
+  rc = pthread_once (&darwin_init_once, darwin_check_version);
+  if (rc) {
+    return LIBUSB_ERROR_OTHER;
+  }
+
   rc = darwin_scan_devices (ctx);
   if (LIBUSB_SUCCESS != rc) {
     return rc;
   }
 
-  if (OSAtomicIncrement32Barrier(&initCount) == 1) {
-    /* create the clocks that will be used */
-
-    if (!initted) {
-      initted = 1;
-      atexit(_darwin_finalize);
-    }
+  if (libusb_darwin_atomic_fetch_add (&initCount, 1) == 0) {
+#if !OSX_USE_CLOCK_GETTIME
+    /* create the clocks that will be used if clock_gettime() is not available */
+    host_name_port_t host_self;
 
     host_self = mach_host_self();
     host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
     host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
     mach_port_deallocate(mach_task_self(), host_self);
+#endif
 
-    pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, (void *)ctx);
+    pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, ctx);
 
     pthread_mutex_lock (&libusb_darwin_at_mutex);
     while (!libusb_darwin_acfl)
@@ -446,12 +556,15 @@ static int darwin_init(struct libusb_context *ctx) {
 }
 
 static void darwin_exit (void) {
-  if (OSAtomicDecrement32Barrier(&initCount) == 0) {
+  if (libusb_darwin_atomic_fetch_add (&initCount, -1) == 1) {
+#if !OSX_USE_CLOCK_GETTIME
     mach_port_deallocate(mach_task_self(), clock_realtime);
     mach_port_deallocate(mach_task_self(), clock_monotonic);
+#endif
 
     /* stop the event runloop and wait for the thread to terminate. */
-    CFRunLoopStop (libusb_darwin_acfl);
+    CFRunLoopSourceSignal(libusb_darwin_acfls);
+    CFRunLoopWakeUp (libusb_darwin_acfl);
     pthread_join (libusb_darwin_at, NULL);
   }
 }
@@ -528,7 +641,7 @@ static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t confi
   if (ret != LIBUSB_SUCCESS)
     return ret;
 
-  return len;
+  return (int) len;
 }
 
 /* check whether the os has configured the device */
@@ -546,6 +659,14 @@ static int darwin_check_configuration (struct libusb_context *ctx, struct darwin
     return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
   }
 
+  /* checking the configuration of a root hub simulation takes ~1 s in 10.11. the device is
+     not usable anyway */
+  if (0x05ac == dev->dev_descriptor.idVendor && 0x8005 == dev->dev_descriptor.idProduct) {
+    usbi_dbg ("ignoring configuration on root hub simulation");
+    dev->active_config = 0;
+    return 0;
+  }
+
   /* find the first configuration */
   kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
   dev->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
@@ -686,7 +807,7 @@ static int darwin_cache_device_descriptor (struct libusb_context *ctx, struct da
     if (kIOReturnSuccess != ret) {
       usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000);
       /* sleep for a little while before trying again */
-      usleep (delay);
+      nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000UL}, NULL);
     }
   } while (kIOReturnSuccess != ret && retries--);
 
@@ -736,27 +857,59 @@ static int darwin_cache_device_descriptor (struct libusb_context *ctx, struct da
   return LIBUSB_SUCCESS;
 }
 
+static int get_device_port (io_service_t service, UInt8 *port) {
+  kern_return_t result;
+  io_service_t parent;
+  int ret = 0;
+
+  if (get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, port)) {
+    return 1;
+  }
+
+  result = IORegistryEntryGetParentEntry (service, kIOServicePlane, &parent);
+  if (kIOReturnSuccess == result) {
+    ret = get_ioregistry_value_data (parent, CFSTR("port"), 1, port);
+    IOObjectRelease (parent);
+  }
+
+  return ret;
+}
+
+static int get_device_parent_sessionID(io_service_t service, UInt64 *parent_sessionID) {
+  kern_return_t result;
+  io_service_t parent;
+
+  /* Walk up the tree in the IOService plane until we find a parent that has a sessionID */
+  parent = service;
+  while((result = IORegistryEntryGetParentEntry (parent, kIOServicePlane, &parent)) == kIOReturnSuccess) {
+    if (get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, parent_sessionID)) {
+        /* Success */
+        return 1;
+    }
+  }
+
+  /* We ran out of parents */
+  return 0;
+}
+
 static int darwin_get_cached_device(struct libusb_context *ctx, io_service_t service,
                                     struct darwin_cached_device **cached_out) {
   struct darwin_cached_device *new_device;
   UInt64 sessionID = 0, parent_sessionID = 0;
   int ret = LIBUSB_SUCCESS;
   usb_device_t **device;
-  io_service_t parent;
-  kern_return_t result;
   UInt8 port = 0;
 
   /* get some info from the io registry */
   (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
-  (void) get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, &port);
-
-  usbi_dbg("finding cached device for sessionID 0x\n" PRIx64, sessionID);
+  if (!get_device_port (service, &port)) {
+    usbi_dbg("could not get connected port number");
+  }
 
-  result = IORegistryEntryGetParentEntry (service, kIOUSBPlane, &parent);
+  usbi_dbg("finding cached device for sessionID 0x%" PRIx64, sessionID);
 
-  if (kIOReturnSuccess == result) {
-    (void) get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, &parent_sessionID);
-    IOObjectRelease(parent);
+  if (get_device_parent_sessionID(service, &parent_sessionID)) {
+    usbi_dbg("parent sessionID: 0x%" PRIx64, parent_sessionID);
   }
 
   usbi_mutex_lock(&darwin_cached_devices_lock);
@@ -764,7 +917,7 @@ static int darwin_get_cached_device(struct libusb_context *ctx, io_service_t ser
     *cached_out = NULL;
 
     list_for_each_entry(new_device, &darwin_cached_devices, list, struct darwin_cached_device) {
-      usbi_dbg("matching sessionID 0x%x against cached device with sessionID 0x%x", sessionID, new_device->session);
+      usbi_dbg("matching sessionID 0x%" PRIx64 " against cached device with sessionID 0x%" PRIx64, sessionID, new_device->session);
       if (new_device->session == sessionID) {
         usbi_dbg("using cached device for device");
         *cached_out = new_device;
@@ -775,7 +928,7 @@ static int darwin_get_cached_device(struct libusb_context *ctx, io_service_t ser
     if (*cached_out)
       break;
 
-    usbi_dbg("caching new device with sessionID 0x%x\n", sessionID);
+    usbi_dbg("caching new device with sessionID 0x%" PRIx64, sessionID);
 
     device = darwin_device_from_service (service);
     if (!device) {
@@ -845,7 +998,7 @@ static int process_new_device (struct libusb_context *ctx, io_service_t service)
     if (ret)
       break;
 
-    usbi_dbg ("allocating new device in context %p for with session 0x%08x",
+    usbi_dbg ("allocating new device in context %p for with session 0x%" PRIx64,
               ctx, cached_device->session);
 
     dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
@@ -961,14 +1114,6 @@ static int darwin_open (struct libusb_device_handle *dev_handle) {
   /* device opened successfully */
   dpriv->open_count++;
 
-  /* create a file descriptor for notifications */
-  pipe (priv->fds);
-
-  /* set the pipe to be non-blocking */
-  fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
-
-  usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
-
   usbi_dbg ("device open for access");
 
   return 0;
@@ -982,7 +1127,7 @@ static void darwin_close (struct libusb_device_handle *dev_handle) {
 
   if (dpriv->open_count == 0) {
     /* something is probably very wrong if this is the case */
-    usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!\n");
+    usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!");
     return;
   }
 
@@ -1012,13 +1157,6 @@ static void darwin_close (struct libusb_device_handle *dev_handle) {
       }
     }
   }
-
-  /* file descriptors are maintained per-instance */
-  usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
-  close (priv->fds[1]);
-  close (priv->fds[0]);
-
-  priv->fds[0] = priv->fds[1] = -1;
 }
 
 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
@@ -1102,7 +1240,7 @@ static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
   u_int8_t numep, direction, number;
   u_int8_t dont_care1, dont_care3;
   u_int16_t dont_care2;
-  int i;
+  int rc;
 
   usbi_dbg ("building table of endpoints.");
 
@@ -1114,19 +1252,36 @@ static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
   }
 
   /* iterate through pipe references */
-  for (i = 1 ; i <= numep ; i++) {
+  for (int i = 1 ; i <= numep ; i++) {
     kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
                                                             &dont_care2, &dont_care3);
 
     if (kresult != kIOReturnSuccess) {
-      usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
+      /* probably a buggy device. try to get the endpoint address from the descriptors */
+      struct libusb_config_descriptor *config;
+      const struct libusb_endpoint_descriptor *endpoint_desc;
+      UInt8 alt_setting;
 
-      return darwin_to_libusb (kresult);
-    }
+      kresult = (*(cInterface->interface))->GetAlternateSetting (cInterface->interface, &alt_setting);
+      if (kresult) {
+        usbi_err (HANDLE_CTX (dev_handle), "can't get alternate setting for interface");
+        return darwin_to_libusb (kresult);
+      }
+
+      rc = libusb_get_active_config_descriptor (dev_handle->dev, &config);
+      if (LIBUSB_SUCCESS != rc) {
+        return rc;
+      }
 
-    usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
+      endpoint_desc = config->interface[iface].altsetting[alt_setting].endpoint + i - 1;
 
-    cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
+      cInterface->endpoint_addrs[i - 1] = endpoint_desc->bEndpointAddress;
+    } else {
+      cInterface->endpoint_addrs[i - 1] = (((kUSBIn == direction) << kUSBRqDirnShift) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
+    }
+
+    usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, cInterface->endpoint_addrs[i - 1] >> kUSBRqDirnShift,
+              cInterface->endpoint_addrs[i - 1] & LIBUSB_ENDPOINT_ADDRESS_MASK);
   }
 
   cInterface->num_endpoints = numep;
@@ -1266,7 +1421,7 @@ static int darwin_release_interface(struct libusb_device_handle *dev_handle, int
   if (kresult != kIOReturnSuccess)
     usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
 
-  cInterface->interface = IO_OBJECT_NULL;
+  cInterface->interface = (usb_interface_t **) IO_OBJECT_NULL;
 
   return darwin_to_libusb (kresult);
 }
@@ -1298,22 +1453,18 @@ static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_hand
 }
 
 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
-  struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
-
   /* current interface */
   struct darwin_interface *cInterface;
-  uint8_t pipeRef, iface;
   IOReturn kresult;
+  uint8_t pipeRef;
 
   /* determine the interface/endpoint to use */
-  if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
+  if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, NULL, &cInterface) != 0) {
     usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
 
     return LIBUSB_ERROR_NOT_FOUND;
   }
 
-  cInterface = &priv->interfaces[iface];
-
   /* newer versions of darwin support clearing additional bits on the device's endpoint */
   kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
   if (kresult)
@@ -1402,14 +1553,14 @@ static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle,
 
 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
-  (void)dev_handle;
-  (void)interface;
+  UNUSED(dev_handle);
+  UNUSED(interface);
   return LIBUSB_ERROR_NOT_SUPPORTED;
 }
 
 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
-  (void)dev_handle;
-  (void)interface;
+  UNUSED(dev_handle);
+  UNUSED(interface);
   return LIBUSB_ERROR_NOT_SUPPORTED;
 }
 
@@ -1427,24 +1578,21 @@ static void darwin_destroy_device(struct libusb_device *dev) {
 
 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
-  struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
 
   IOReturn               ret;
   uint8_t                transferType;
   /* None of the values below are used in libusbx for bulk transfers */
-  uint8_t                direction, number, interval, pipeRef, iface;
+  uint8_t                direction, number, interval, pipeRef;
   uint16_t               maxPacketSize;
 
   struct darwin_interface *cInterface;
 
-  if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
+  if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
 
     return LIBUSB_ERROR_NOT_FOUND;
   }
 
-  cInterface = &priv->interfaces[iface];
-
   ret = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
                                                        &transferType, &maxPacketSize, &interval);
 
@@ -1469,7 +1617,7 @@ static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
       ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
                                                        transfer->length, darwin_async_io_callback, itransfer);
   } else {
-    itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
+    itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
 
     if (IS_XFERIN(transfer))
       ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
@@ -1488,13 +1636,44 @@ static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
   return darwin_to_libusb (ret);
 }
 
+#if InterfaceVersion >= 550
+static int submit_stream_transfer(struct usbi_transfer *itransfer) {
+  struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
+  struct darwin_interface *cInterface;
+  uint8_t pipeRef;
+  IOReturn ret;
+
+  if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
+    usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
+
+    return LIBUSB_ERROR_NOT_FOUND;
+  }
+
+  itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
+
+  if (IS_XFERIN(transfer))
+    ret = (*(cInterface->interface))->ReadStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
+                                                             transfer->buffer, transfer->length, transfer->timeout,
+                                                             transfer->timeout, darwin_async_io_callback, (void *)itransfer);
+  else
+    ret = (*(cInterface->interface))->WriteStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
+                                                              transfer->buffer, transfer->length, transfer->timeout,
+                                                              transfer->timeout, darwin_async_io_callback, (void *)itransfer);
+
+  if (ret)
+    usbi_err (TRANSFER_CTX (transfer), "bulk stream transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
+               darwin_error_str(ret), ret);
+
+  return darwin_to_libusb (ret);
+}
+#endif
+
 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
-  struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
 
   IOReturn kresult;
-  uint8_t direction, number, interval, pipeRef, iface, transferType;
+  uint8_t direction, number, interval, pipeRef, transferType;
   uint16_t maxPacketSize;
   UInt64 frame;
   AbsoluteTime atTime;
@@ -1515,19 +1694,17 @@ static int submit_iso_transfer(struct usbi_transfer *itransfer) {
       return LIBUSB_ERROR_NO_MEM;
   }
 
-  /* copy the frame list from the libusbx descriptor (the structures differ only is member order) */
+  /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
   for (i = 0 ; i < transfer->num_iso_packets ; i++)
     tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
 
   /* determine the interface/endpoint to use */
-  if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
+  if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
 
     return LIBUSB_ERROR_NOT_FOUND;
   }
 
-  cInterface = &priv->interfaces[iface];
-
   /* determine the properties of this endpoint and the speed of the device */
   (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
                                                  &transferType, &maxPacketSize, &interval);
@@ -1582,41 +1759,38 @@ static int submit_control_transfer(struct usbi_transfer *itransfer) {
   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
-  struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
 
   IOReturn               kresult;
 
-  bzero(&tpriv->req, sizeof(tpriv->req));
+  memset(&tpriv->req, 0, sizeof(tpriv->req));
 
-  /* IOUSBDeviceInterface expects the request in cpu endianess */
+  /* IOUSBDeviceInterface expects the request in cpu endianness */
   tpriv->req.bmRequestType     = setup->bmRequestType;
   tpriv->req.bRequest          = setup->bRequest;
   /* these values should be in bus order from libusb_fill_control_setup */
   tpriv->req.wValue            = OSSwapLittleToHostInt16 (setup->wValue);
   tpriv->req.wIndex            = OSSwapLittleToHostInt16 (setup->wIndex);
   tpriv->req.wLength           = OSSwapLittleToHostInt16 (setup->wLength);
-  /* data is stored after the libusbx control block */
+  /* data is stored after the libusb control block */
   tpriv->req.pData             = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
   tpriv->req.completionTimeout = transfer->timeout;
   tpriv->req.noDataTimeout     = transfer->timeout;
 
-  itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
+  itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
 
   /* all transfers in libusb-1.0 are async */
 
   if (transfer->endpoint) {
     struct darwin_interface *cInterface;
-    uint8_t                 pipeRef, iface;
+    uint8_t                 pipeRef;
 
-    if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
+    if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
       usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
 
       return LIBUSB_ERROR_NOT_FOUND;
     }
 
-    cInterface = &priv->interfaces[iface];
-
     kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
   } else
     /* control request on endpoint 0 */
@@ -1639,6 +1813,13 @@ static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
     return submit_bulk_transfer(itransfer);
   case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
     return submit_iso_transfer(itransfer);
+  case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
+#if InterfaceVersion >= 550
+    return submit_stream_transfer(itransfer);
+#else
+    usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version does not support bulk stream transfers");
+    return LIBUSB_ERROR_NOT_SUPPORTED;
+#endif
   default:
     usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
     return LIBUSB_ERROR_INVALID_PARAM;
@@ -1663,26 +1844,28 @@ static int cancel_control_transfer(struct usbi_transfer *itransfer) {
 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
-  struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
   struct darwin_interface *cInterface;
   uint8_t pipeRef, iface;
   IOReturn kresult;
 
-  if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
+  if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface, &cInterface) != 0) {
     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
 
     return LIBUSB_ERROR_NOT_FOUND;
   }
 
-  cInterface = &priv->interfaces[iface];
-
   if (!dpriv->device)
     return LIBUSB_ERROR_NO_DEVICE;
 
   usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
 
   /* abort transactions */
-  (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
+#if InterfaceVersion >= 550
+  if (LIBUSB_TRANSFER_TYPE_BULK_STREAM == transfer->type)
+    (*(cInterface->interface))->AbortStreamsPipe (cInterface->interface, pipeRef, itransfer->stream_id);
+  else
+#endif
+    (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
 
   usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
 
@@ -1721,29 +1904,29 @@ static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
   struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
-  struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
-  struct darwin_msg_async_io_complete message = {.itransfer = itransfer, .result = result,
-                                                 .size = (UInt32) (uintptr_t) arg0};
+  struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
 
   usbi_dbg ("an async io operation has completed");
 
   /* if requested write a zero packet */
   if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
     struct darwin_interface *cInterface;
-    uint8_t iface, pipeRef;
+    uint8_t pipeRef;
 
-    (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface);
-    cInterface = &priv->interfaces[iface];
+    (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface);
 
     (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
   }
 
-  /* send a completion message to the device's file descriptor */
-  write (priv->fds[1], &message, sizeof (message));
+  tpriv->result = result;
+  tpriv->size = (UInt32) (uintptr_t) arg0;
+
+  /* signal the core that this transfer is complete */
+  usbi_signal_transfer_completion(itransfer);
 }
 
 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
-  if (itransfer->flags & USBI_TRANSFER_TIMED_OUT)
+  if (itransfer->timeout_flags & USBI_TRANSFER_TIMED_OUT)
     result = kIOUSBTransactionTimeout;
 
   switch (result) {
@@ -1760,7 +1943,7 @@ static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_
     return LIBUSB_TRANSFER_OVERFLOW;
   case kIOUSBTransactionTimeout:
     usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
-    itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
+    itransfer->timeout_flags |= USBI_TRANSFER_TIMED_OUT;
     return LIBUSB_TRANSFER_TIMED_OUT;
   default:
     usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
@@ -1768,7 +1951,7 @@ static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_
   }
 }
 
-static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
+static int darwin_handle_transfer_completion (struct usbi_transfer *itransfer) {
   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
   int isIsoc      = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
@@ -1779,13 +1962,13 @@ static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return
 
   if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
     usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
-    return;
+    return LIBUSB_ERROR_INVALID_PARAM;
   }
 
   usbi_dbg ("handling %s completion with kernel status %d",
-             isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", result);
+             isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", tpriv->result);
 
-  if (kIOReturnSuccess == result || kIOReturnUnderrun == result) {
+  if (kIOReturnSuccess == tpriv->result || kIOReturnUnderrun == tpriv->result) {
     if (isIsoc && tpriv->isoc_framelist) {
       /* copy isochronous results back */
 
@@ -1795,51 +1978,15 @@ static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return
         lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
       }
     } else if (!isIsoc)
-      itransfer->transferred += io_size;
+      itransfer->transferred += tpriv->size;
   }
 
   /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
-  usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, result));
-}
-
-static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready) {
-  struct darwin_msg_async_io_complete message;
-  POLL_NFDS_TYPE i = 0;
-  ssize_t ret;
-
-  usbi_mutex_lock(&ctx->open_devs_lock);
-
-  for (i = 0; i < nfds && num_ready > 0; i++) {
-    struct pollfd *pollfd = &fds[i];
-
-    usbi_dbg ("checking fd %i with revents = %x", pollfd->fd, pollfd->revents);
-
-    if (!pollfd->revents)
-      continue;
-
-    num_ready--;
-
-    if (pollfd->revents & POLLERR) {
-      /* this probably will never happen so ignore the error an move on. */
-      continue;
-    }
-
-    /* there is only one type of message */
-    ret = read (pollfd->fd, &message, sizeof (message));
-    if (ret < (ssize_t) sizeof (message)) {
-      usbi_dbg ("WARNING: short read on async io completion pipe\n");
-      continue;
-    }
-
-    darwin_handle_callback (message.itransfer, message.result, message.size);
-  }
-
-  usbi_mutex_unlock(&ctx->open_devs_lock);
-
-  return 0;
+  return usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, tpriv->result));
 }
 
 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
+#if !OSX_USE_CLOCK_GETTIME
   mach_timespec_t sys_time;
   clock_serv_t clock_ref;
 
@@ -1862,7 +2009,75 @@ static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
   tp->tv_nsec = sys_time.tv_nsec;
 
   return 0;
+#else
+  switch (clk_id) {
+  case USBI_CLOCK_MONOTONIC:
+    return clock_gettime(CLOCK_MONOTONIC, tp);
+  case USBI_CLOCK_REALTIME:
+    return clock_gettime(CLOCK_REALTIME, tp);
+  default:
+    return LIBUSB_ERROR_INVALID_PARAM;
+  }
+#endif
+}
+
+#if InterfaceVersion >= 550
+static int darwin_alloc_streams (struct libusb_device_handle *dev_handle, uint32_t num_streams, unsigned char *endpoints,
+                                 int num_endpoints) {
+  struct darwin_interface *cInterface;
+  UInt32 supportsStreams;
+  uint8_t pipeRef;
+  int rc, i;
+
+  /* find the mimimum number of supported streams on the endpoint list */
+  for (i = 0 ; i < num_endpoints ; ++i) {
+    if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface))) {
+      return rc;
+    }
+
+    (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
+    if (num_streams > supportsStreams)
+      num_streams = supportsStreams;
+  }
+
+  /* it is an error if any endpoint in endpoints does not support streams */
+  if (0 == num_streams)
+    return LIBUSB_ERROR_INVALID_PARAM;
+
+  /* create the streams */
+  for (i = 0 ; i < num_endpoints ; ++i) {
+    (void) ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
+
+    rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, num_streams);
+    if (kIOReturnSuccess != rc)
+      return darwin_to_libusb(rc);
+  }
+
+  return num_streams;
+}
+
+static int darwin_free_streams (struct libusb_device_handle *dev_handle, unsigned char *endpoints, int num_endpoints) {
+  struct darwin_interface *cInterface;
+  UInt32 supportsStreams;
+  uint8_t pipeRef;
+  int rc;
+
+  for (int i = 0 ; i < num_endpoints ; ++i) {
+    if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface)))
+      return rc;
+
+    (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
+    if (0 == supportsStreams)
+      return LIBUSB_ERROR_INVALID_PARAM;
+
+    rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, 0);
+    if (kIOReturnSuccess != rc)
+      return darwin_to_libusb(rc);
+  }
+
+  return LIBUSB_SUCCESS;
 }
+#endif
 
 const struct usbi_os_backend darwin_backend = {
         .name = "Darwin",
@@ -1873,6 +2088,7 @@ const struct usbi_os_backend darwin_backend = {
         .get_device_descriptor = darwin_get_device_descriptor,
         .get_active_config_descriptor = darwin_get_active_config_descriptor,
         .get_config_descriptor = darwin_get_config_descriptor,
+        .hotplug_poll = darwin_hotplug_poll,
 
         .open = darwin_open,
         .close = darwin_close,
@@ -1885,6 +2101,11 @@ const struct usbi_os_backend darwin_backend = {
         .clear_halt = darwin_clear_halt,
         .reset_device = darwin_reset_device,
 
+#if InterfaceVersion >= 550
+        .alloc_streams = darwin_alloc_streams,
+        .free_streams = darwin_free_streams,
+#endif
+
         .kernel_driver_active = darwin_kernel_driver_active,
         .detach_kernel_driver = darwin_detach_kernel_driver,
         .attach_kernel_driver = darwin_attach_kernel_driver,
@@ -1895,12 +2116,11 @@ const struct usbi_os_backend darwin_backend = {
         .cancel_transfer = darwin_cancel_transfer,
         .clear_transfer_priv = darwin_clear_transfer_priv,
 
-        .handle_events = op_handle_events,
+        .handle_transfer_completion = darwin_handle_transfer_completion,
 
         .clock_gettime = darwin_clock_gettime,
 
         .device_priv_size = sizeof(struct darwin_device_priv),
         .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
         .transfer_priv_size = sizeof(struct darwin_transfer_priv),
-        .add_iso_packet_size = 0,
 };