Home | History | Annotate | Download | only in os
      1 /*
      2  * darwin backend for libusb 1.0
      3  * Copyright (C) 2008-2010 Nathan Hjelm <hjelmn (at) users.sourceforge.net>
      4  *
      5  * This library is free software; you can redistribute it and/or
      6  * modify it under the terms of the GNU Lesser General Public
      7  * License as published by the Free Software Foundation; either
      8  * version 2.1 of the License, or (at your option) any later version.
      9  *
     10  * This library is distributed in the hope that it will be useful,
     11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
     12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     13  * Lesser General Public License for more details.
     14  *
     15  * You should have received a copy of the GNU Lesser General Public
     16  * License along with this library; if not, write to the Free Software
     17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
     18  */
     19 
     20 #include <config.h>
     21 #include <ctype.h>
     22 #include <dirent.h>
     23 #include <errno.h>
     24 #include <fcntl.h>
     25 #include <pthread.h>
     26 #include <stdio.h>
     27 #include <stdlib.h>
     28 #include <string.h>
     29 #include <sys/ioctl.h>
     30 #include <sys/stat.h>
     31 #include <sys/types.h>
     32 #include <unistd.h>
     33 
     34 #include <mach/clock.h>
     35 #include <mach/clock_types.h>
     36 #include <mach/mach_host.h>
     37 
     38 #include <mach/mach_port.h>
     39 #include <IOKit/IOCFBundle.h>
     40 #include <IOKit/usb/IOUSBLib.h>
     41 #include <IOKit/IOCFPlugIn.h>
     42 
     43 #include "darwin_usb.h"
     44 
     45 static mach_port_t  libusb_darwin_mp = 0; /* master port */
     46 static CFRunLoopRef libusb_darwin_acfl = NULL; /* async cf loop */
     47 static int initCount = 0;
     48 
     49 /* async event thread */
     50 static pthread_t libusb_darwin_at;
     51 
     52 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
     53 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
     54 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
     55 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
     56 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
     57 
     58 static const char *darwin_error_str (int result) {
     59   switch (result) {
     60   case kIOReturnSuccess:
     61     return "no error";
     62   case kIOReturnNotOpen:
     63     return "device not opened for exclusive access";
     64   case kIOReturnNoDevice:
     65     return "no connection to an IOService";
     66   case kIOUSBNoAsyncPortErr:
     67     return "no async port has been opened for interface";
     68   case kIOReturnExclusiveAccess:
     69     return "another process has device opened for exclusive access";
     70   case kIOUSBPipeStalled:
     71     return "pipe is stalled";
     72   case kIOReturnError:
     73     return "could not establish a connection to the Darwin kernel";
     74   case kIOUSBTransactionTimeout:
     75     return "transaction timed out";
     76   case kIOReturnBadArgument:
     77     return "invalid argument";
     78   case kIOReturnAborted:
     79     return "transaction aborted";
     80   case kIOReturnNotResponding:
     81     return "device not responding";
     82   case kIOReturnOverrun:
     83     return "data overrun";
     84   case kIOReturnCannotWire:
     85     return "physical memory can not be wired down";
     86   default:
     87     return "unknown error";
     88   }
     89 }
     90 
     91 static int darwin_to_libusb (int result) {
     92   switch (result) {
     93   case kIOReturnSuccess:
     94     return LIBUSB_SUCCESS;
     95   case kIOReturnNotOpen:
     96   case kIOReturnNoDevice:
     97     return LIBUSB_ERROR_NO_DEVICE;
     98   case kIOReturnExclusiveAccess:
     99     return LIBUSB_ERROR_ACCESS;
    100   case kIOUSBPipeStalled:
    101     return LIBUSB_ERROR_PIPE;
    102   case kIOReturnBadArgument:
    103     return LIBUSB_ERROR_INVALID_PARAM;
    104   case kIOUSBTransactionTimeout:
    105     return LIBUSB_ERROR_TIMEOUT;
    106   case kIOReturnNotResponding:
    107   case kIOReturnAborted:
    108   case kIOReturnError:
    109   case kIOUSBNoAsyncPortErr:
    110   default:
    111     return LIBUSB_ERROR_OTHER;
    112   }
    113 }
    114 
    115 
    116 static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp) {
    117   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
    118 
    119   /* current interface */
    120   struct __darwin_interface *cInterface;
    121 
    122   int8_t i, iface;
    123 
    124   usbi_info (HANDLE_CTX(dev_handle), "converting ep address 0x%02x to pipeRef and interface", ep);
    125 
    126   for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
    127     cInterface = &priv->interfaces[iface];
    128 
    129     if (dev_handle->claimed_interfaces & (1 << iface)) {
    130       for (i = 0 ; i < cInterface->num_endpoints ; i++) {
    131 	if (cInterface->endpoint_addrs[i] == ep) {
    132 	  *pipep = i + 1;
    133 	  *ifcp = iface;
    134 	  usbi_info (HANDLE_CTX(dev_handle), "pipe %d on interface %d matches", *pipep, *ifcp);
    135 	  return 0;
    136 	}
    137       }
    138     }
    139   }
    140 
    141   /* No pipe found with the correct endpoint address */
    142   usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
    143 
    144   return -1;
    145 }
    146 
    147 static int usb_setup_device_iterator (io_iterator_t *deviceIterator) {
    148   return IOServiceGetMatchingServices(libusb_darwin_mp, IOServiceMatching(kIOUSBDeviceClassName), deviceIterator);
    149 }
    150 
    151 static usb_device_t **usb_get_next_device (io_iterator_t deviceIterator, UInt32 *locationp) {
    152   io_cf_plugin_ref_t *plugInInterface = NULL;
    153   usb_device_t **device;
    154   io_service_t usbDevice;
    155   long result;
    156   SInt32 score;
    157 
    158   if (!IOIteratorIsValid (deviceIterator))
    159     return NULL;
    160 
    161 
    162   while ((usbDevice = IOIteratorNext(deviceIterator))) {
    163     result = IOCreatePlugInInterfaceForService(usbDevice, kIOUSBDeviceUserClientTypeID,
    164 					       kIOCFPlugInInterfaceID, &plugInInterface,
    165 					       &score);
    166     if (kIOReturnSuccess == result && plugInInterface)
    167       break;
    168 
    169     usbi_dbg ("libusb/darwin.c usb_get_next_device: could not set up plugin for service: %s\n", darwin_error_str (result));
    170   }
    171 
    172   if (!usbDevice)
    173     return NULL;
    174 
    175   (void)IOObjectRelease(usbDevice);
    176   (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
    177 					   (LPVOID)&device);
    178 
    179   (*plugInInterface)->Stop(plugInInterface);
    180   IODestroyPlugInInterface (plugInInterface);
    181 
    182   (*(device))->GetLocationID(device, locationp);
    183 
    184   return device;
    185 }
    186 
    187 static kern_return_t darwin_get_device (uint32_t dev_location, usb_device_t ***darwin_device) {
    188   kern_return_t kresult;
    189   UInt32        location;
    190   io_iterator_t deviceIterator;
    191 
    192   kresult = usb_setup_device_iterator (&deviceIterator);
    193   if (kresult)
    194     return kresult;
    195 
    196   /* This port of libusb uses locations to keep track of devices. */
    197   while ((*darwin_device = usb_get_next_device (deviceIterator, &location)) != NULL) {
    198     if (location == dev_location)
    199       break;
    200 
    201     (**darwin_device)->Release(*darwin_device);
    202   }
    203 
    204   IOObjectRelease (deviceIterator);
    205 
    206   if (!(*darwin_device))
    207     return kIOReturnNoDevice;
    208 
    209   return kIOReturnSuccess;
    210 }
    211 
    212 
    213 
    214 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
    215   struct libusb_context *ctx = (struct libusb_context *)ptr;
    216   struct libusb_device_handle *handle;
    217   struct darwin_device_priv *dpriv;
    218   struct darwin_device_handle_priv *priv;
    219 
    220   io_service_t device;
    221   long location;
    222   CFTypeRef locationCF;
    223   UInt32 message;
    224 
    225   usbi_info (ctx, "a device has been detached");
    226 
    227   while ((device = IOIteratorNext (rem_devices)) != 0) {
    228     /* get the location from the i/o registry */
    229     locationCF = IORegistryEntryCreateCFProperty (device, CFSTR(kUSBDevicePropertyLocationID), kCFAllocatorDefault, 0);
    230 
    231     CFNumberGetValue(locationCF, kCFNumberLongType, &location);
    232     CFRelease (locationCF);
    233     IOObjectRelease (device);
    234 
    235     pthread_mutex_lock(&ctx->open_devs_lock);
    236     list_for_each_entry(handle, &ctx->open_devs, list) {
    237       dpriv = (struct darwin_device_priv *)handle->dev->os_priv;
    238 
    239       /* the device may have been opened several times. write to each handle's event descriptor */
    240       if (dpriv->location == location  && handle->os_priv) {
    241 	priv  = (struct darwin_device_handle_priv *)handle->os_priv;
    242 
    243 	message = MESSAGE_DEVICE_GONE;
    244 	write (priv->fds[1], &message, sizeof (message));
    245       }
    246     }
    247 
    248     pthread_mutex_unlock(&ctx->open_devs_lock);
    249   }
    250 }
    251 
    252 static void darwin_clear_iterator (io_iterator_t iter) {
    253   io_service_t device;
    254 
    255   while ((device = IOIteratorNext (iter)) != 0)
    256     IOObjectRelease (device);
    257 }
    258 
    259 static void *event_thread_main (void *arg0) {
    260   IOReturn kresult;
    261   struct libusb_context *ctx = (struct libusb_context *)arg0;
    262 
    263   /* hotplug (device removal) source */
    264   CFRunLoopSourceRef     libusb_notification_cfsource;
    265   io_notification_port_t libusb_notification_port;
    266   io_iterator_t          libusb_rem_device_iterator;
    267 
    268   usbi_info (ctx, "creating hotplug event source");
    269 
    270   CFRetain (CFRunLoopGetCurrent ());
    271 
    272   /* add the notification port to the run loop */
    273   libusb_notification_port     = IONotificationPortCreate (libusb_darwin_mp);
    274   libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
    275   CFRunLoopAddSource(CFRunLoopGetCurrent (), libusb_notification_cfsource, kCFRunLoopDefaultMode);
    276 
    277   /* create notifications for removed devices */
    278   kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
    279 					      IOServiceMatching(kIOUSBDeviceClassName),
    280 					      (IOServiceMatchingCallback)darwin_devices_detached,
    281 					      (void *)ctx, &libusb_rem_device_iterator);
    282 
    283   if (kresult != kIOReturnSuccess) {
    284     usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
    285 
    286     pthread_exit ((void *)kresult);
    287   }
    288 
    289   /* arm notifiers */
    290   darwin_clear_iterator (libusb_rem_device_iterator);
    291 
    292   /* let the main thread know about the async runloop */
    293   libusb_darwin_acfl = CFRunLoopGetCurrent ();
    294 
    295   usbi_info (ctx, "libopenusb/darwin.c event_thread_main: thread ready to receive events");
    296 
    297   /* run the runloop */
    298   CFRunLoopRun();
    299 
    300   usbi_info (ctx, "libopenusb/darwin.c event_thread_main: thread exiting");
    301 
    302   /* delete notification port */
    303   CFRunLoopSourceInvalidate (libusb_notification_cfsource);
    304   IONotificationPortDestroy (libusb_notification_port);
    305 
    306   CFRelease (CFRunLoopGetCurrent ());
    307 
    308   libusb_darwin_acfl = NULL;
    309 
    310   pthread_exit (0);
    311 }
    312 
    313 static int darwin_init(struct libusb_context *ctx) {
    314   IOReturn kresult;
    315 
    316   if (!(initCount++)) {
    317     /* Create the master port for talking to IOKit */
    318     if (!libusb_darwin_mp) {
    319       kresult = IOMasterPort (MACH_PORT_NULL, &libusb_darwin_mp);
    320 
    321       if (kresult != kIOReturnSuccess || !libusb_darwin_mp)
    322 	return darwin_to_libusb (kresult);
    323     }
    324 
    325     pthread_create (&libusb_darwin_at, NULL, event_thread_main, (void *)ctx);
    326 
    327     while (!libusb_darwin_acfl)
    328       usleep (10);
    329   }
    330 
    331   return 0;
    332 }
    333 
    334 static void darwin_exit (void) {
    335   if (!(--initCount)) {
    336     void *ret;
    337 
    338     /* stop the async runloop */
    339     CFRunLoopStop (libusb_darwin_acfl);
    340     pthread_join (libusb_darwin_at, &ret);
    341 
    342     if (libusb_darwin_mp)
    343       mach_port_deallocate(mach_task_self(), libusb_darwin_mp);
    344 
    345     libusb_darwin_mp = 0;
    346   }
    347 }
    348 
    349 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
    350   struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
    351 
    352   /* return cached copy */
    353   memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
    354 
    355   *host_endian = 0;
    356 
    357   return 0;
    358 }
    359 
    360 static int get_configuration_index (struct libusb_device *dev, int config_value) {
    361   struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
    362   UInt8 i, numConfig;
    363   IOUSBConfigurationDescriptorPtr desc;
    364   IOReturn kresult;
    365 
    366   /* is there a simpler way to determine the index? */
    367   kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
    368   if (kresult != kIOReturnSuccess)
    369     return darwin_to_libusb (kresult);
    370 
    371   for (i = 0 ; i < numConfig ; i++) {
    372     (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
    373 
    374     if (libusb_le16_to_cpu (desc->bConfigurationValue) == config_value)
    375       return i;
    376   }
    377 
    378   /* configuration not found */
    379   return LIBUSB_ERROR_OTHER;
    380 }
    381 
    382 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
    383   struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
    384   UInt8 config_value;
    385   int config_index;
    386   IOReturn kresult;
    387 
    388   kresult = (*(priv->device))->GetConfiguration (priv->device, &config_value);
    389   if (kresult != kIOReturnSuccess)
    390     return darwin_to_libusb (kresult);
    391 
    392   config_index = get_configuration_index (dev, config_value);
    393   if (config_index < 0)
    394     return config_index;
    395 
    396   return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
    397 }
    398 
    399 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
    400   struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
    401   IOUSBConfigurationDescriptorPtr desc;
    402   IOReturn kresult;
    403   usb_device_t **device = NULL;
    404 
    405   if (!priv)
    406     return LIBUSB_ERROR_OTHER;
    407 
    408   if (!priv->device) {
    409     kresult = darwin_get_device (priv->location, &device);
    410     if (kresult || !device) {
    411       usbi_err (DEVICE_CTX (dev), "could not find device: %s", darwin_error_str (kresult));
    412 
    413       return darwin_to_libusb (kresult);
    414     }
    415 
    416     /* don't have to open the device to get a config descriptor */
    417   } else
    418     device = priv->device;
    419 
    420   kresult = (*device)->GetConfigurationDescriptorPtr (device, config_index, &desc);
    421   if (kresult == kIOReturnSuccess) {
    422     /* copy descriptor */
    423     if (libusb_le16_to_cpu(desc->wTotalLength) < len)
    424       len = libusb_le16_to_cpu(desc->wTotalLength);
    425 
    426     memmove (buffer, desc, len);
    427 
    428     /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
    429     *host_endian = 0;
    430   }
    431 
    432   if (!priv->device)
    433     (*device)->Release (device);
    434 
    435   return darwin_to_libusb (kresult);
    436 }
    437 
    438 static int process_new_device (struct libusb_context *ctx, usb_device_t **device, UInt32 locationID, struct discovered_devs **_discdevs) {
    439   struct darwin_device_priv *priv;
    440   struct libusb_device *dev;
    441   struct discovered_devs *discdevs;
    442   UInt16                address, idVendor, idProduct;
    443   UInt8                 bDeviceClass, bDeviceSubClass;
    444   IOUSBDevRequest      req;
    445   int ret = 0, need_unref = 0;
    446 
    447   do {
    448     dev = usbi_get_device_by_session_id(ctx, locationID);
    449     if (!dev) {
    450       usbi_info (ctx, "allocating new device for location 0x%08x", locationID);
    451       dev = usbi_alloc_device(ctx, locationID);
    452       need_unref = 1;
    453     } else
    454       usbi_info (ctx, "using existing device for location 0x%08x", locationID);
    455 
    456     if (!dev) {
    457       ret = LIBUSB_ERROR_NO_MEM;
    458       break;
    459     }
    460 
    461     priv = (struct darwin_device_priv *)dev->os_priv;
    462 
    463     /* Set up request for device descriptor */
    464     req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
    465     req.bRequest      = kUSBRqGetDescriptor;
    466     req.wValue        = kUSBDeviceDesc << 8;
    467     req.wIndex        = 0;
    468     req.wLength       = sizeof(IOUSBDeviceDescriptor);
    469     req.pData         = &(priv->dev_descriptor);
    470 
    471     (*(device))->GetDeviceAddress (device, (USBDeviceAddress *)&address);
    472     (*(device))->GetDeviceProduct (device, &idProduct);
    473     (*(device))->GetDeviceVendor (device, &idVendor);
    474     (*(device))->GetDeviceClass (device, &bDeviceClass);
    475     (*(device))->GetDeviceSubClass (device, &bDeviceSubClass);
    476 
    477     /**** retrieve device descriptors ****/
    478     /* device must be open for DeviceRequest */
    479     (*device)->USBDeviceOpen(device);
    480 
    481     ret = (*(device))->DeviceRequest (device, &req);
    482     if (ret != kIOReturnSuccess) {
    483       int try_unsuspend = 1;
    484 #if DeviceVersion >= 320
    485       UInt32 info;
    486 
    487       /* device may be suspended. unsuspend it and try again */
    488       /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
    489       (void)(*device)->GetUSBDeviceInformation (device, &info);
    490 
    491       try_unsuspend = info & (1 << kUSBInformationDeviceIsSuspendedBit);
    492 #endif
    493 
    494       if (try_unsuspend) {
    495 	/* resume the device */
    496 	(void)(*device)->USBDeviceSuspend (device, 0);
    497 
    498 	ret = (*(device))->DeviceRequest (device, &req);
    499 
    500 	/* resuspend the device */
    501 	(void)(*device)->USBDeviceSuspend (device, 1);
    502       }
    503     }
    504 
    505     (*device)->USBDeviceClose (device);
    506 
    507     if (ret != kIOReturnSuccess) {
    508       usbi_warn (ctx, "could not retrieve device descriptor: %s. skipping device", darwin_error_str (ret));
    509       ret = -1;
    510       break;
    511     }
    512 
    513     /**** end: retrieve device descriptors ****/
    514 
    515     /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
    516     if (libusb_le16_to_cpu (priv->dev_descriptor.idProduct) != idProduct) {
    517       /* not a valid device */
    518       usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
    519 		 idProduct, libusb_le16_to_cpu (priv->dev_descriptor.idProduct));
    520       ret = -1;
    521       break;
    522     }
    523 
    524     dev->bus_number     = locationID >> 24;
    525     dev->device_address = address;
    526 
    527     /* save our location, we'll need this later */
    528     priv->location = locationID;
    529     snprintf(priv->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", address, idVendor, idProduct, bDeviceClass, bDeviceSubClass);
    530 
    531     ret = usbi_sanitize_device (dev);
    532     if (ret < 0)
    533       break;
    534 
    535     /* append the device to the list of discovered devices */
    536     discdevs = discovered_devs_append(*_discdevs, dev);
    537     if (!discdevs) {
    538       ret = LIBUSB_ERROR_NO_MEM;
    539       break;
    540     }
    541 
    542     *_discdevs = discdevs;
    543 
    544     usbi_info (ctx, "found device with address %d at %s", dev->device_address, priv->sys_path);
    545   } while (0);
    546 
    547   if (need_unref)
    548     libusb_unref_device(dev);
    549 
    550   return ret;
    551 }
    552 
    553 static int darwin_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs) {
    554   io_iterator_t        deviceIterator;
    555   usb_device_t         **device;
    556   kern_return_t        kresult;
    557   UInt32               location;
    558 
    559   if (!libusb_darwin_mp)
    560     return LIBUSB_ERROR_INVALID_PARAM;
    561 
    562   kresult = usb_setup_device_iterator (&deviceIterator);
    563   if (kresult != kIOReturnSuccess)
    564     return darwin_to_libusb (kresult);
    565 
    566   while ((device = usb_get_next_device (deviceIterator, &location)) != NULL) {
    567     (void) process_new_device (ctx, device, location, _discdevs);
    568 
    569     (*(device))->Release(device);
    570   }
    571 
    572   IOObjectRelease(deviceIterator);
    573 
    574   return 0;
    575 }
    576 
    577 static int darwin_open (struct libusb_device_handle *dev_handle) {
    578   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
    579   struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
    580   usb_device_t  **darwin_device;
    581   IOReturn kresult;
    582 
    583   if (0 == dpriv->open_count) {
    584     kresult = darwin_get_device (dpriv->location, &darwin_device);
    585     if (kresult) {
    586       usbi_err (HANDLE_CTX (dev_handle), "could not find device: %s", darwin_error_str (kresult));
    587       return darwin_to_libusb (kresult);
    588     }
    589 
    590     dpriv->device = darwin_device;
    591 
    592     /* try to open the device */
    593     kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
    594 
    595     if (kresult != kIOReturnSuccess) {
    596       usbi_err (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
    597 
    598       switch (kresult) {
    599       case kIOReturnExclusiveAccess:
    600 	/* it is possible to perform some actions on a device that is not open so do not return an error */
    601 	priv->is_open = 0;
    602 
    603 	break;
    604       default:
    605 	(*(dpriv->device))->Release (dpriv->device);
    606 	dpriv->device = NULL;
    607 	return darwin_to_libusb (kresult);
    608       }
    609     } else {
    610       priv->is_open = 1;
    611 
    612       /* create async event source */
    613       kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
    614 
    615       CFRetain (libusb_darwin_acfl);
    616 
    617       /* add the cfSource to the aync run loop */
    618       CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
    619     }
    620   }
    621 
    622   /* device opened successfully */
    623   dpriv->open_count++;
    624 
    625   /* create a file descriptor for notifications */
    626   pipe (priv->fds);
    627 
    628   /* set the pipe to be non-blocking */
    629   fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
    630 
    631   usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
    632 
    633   usbi_info (HANDLE_CTX (dev_handle), "device open for access");
    634 
    635   return 0;
    636 }
    637 
    638 static void darwin_close (struct libusb_device_handle *dev_handle) {
    639   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
    640   struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
    641   IOReturn kresult;
    642   int i;
    643 
    644   if (dpriv->open_count == 0) {
    645     /* something is probably very wrong if this is the case */
    646     usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!\n");
    647     return;
    648   }
    649 
    650   dpriv->open_count--;
    651 
    652   /* make sure all interfaces are released */
    653   for (i = 0 ; i < USB_MAXINTERFACES ; i++)
    654     if (dev_handle->claimed_interfaces & (1 << i))
    655       libusb_release_interface (dev_handle, i);
    656 
    657   if (0 == dpriv->open_count) {
    658     if (priv->is_open) {
    659       /* delete the device's async event source */
    660       if (priv->cfSource) {
    661 	CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
    662 	CFRelease (priv->cfSource);
    663       }
    664 
    665       /* close the device */
    666       kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
    667       if (kresult) {
    668 	/* Log the fact that we had a problem closing the file, however failing a
    669 	 * close isn't really an error, so return success anyway */
    670 	usbi_err (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
    671       }
    672     }
    673 
    674     kresult = (*(dpriv->device))->Release(dpriv->device);
    675     if (kresult) {
    676       /* Log the fact that we had a problem closing the file, however failing a
    677        * close isn't really an error, so return success anyway */
    678       usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
    679     }
    680 
    681     dpriv->device = NULL;
    682   }
    683 
    684   /* file descriptors are maintained per-instance */
    685   usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
    686   close (priv->fds[1]);
    687   close (priv->fds[0]);
    688 
    689   priv->fds[0] = priv->fds[1] = -1;
    690 }
    691 
    692 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
    693   struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
    694   UInt8 configNum;
    695   IOReturn kresult;
    696 
    697   kresult = (*(dpriv->device))->GetConfiguration (dpriv->device, &configNum);
    698   if (kresult != kIOReturnSuccess)
    699     return darwin_to_libusb (kresult);
    700 
    701   *config = (int) configNum;
    702 
    703   return 0;
    704 }
    705 
    706 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
    707   struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
    708   IOReturn kresult;
    709   int i;
    710 
    711   /* Setting configuration will invalidate the interface, so we need
    712      to reclaim it. First, dispose of existing interfaces, if any. */
    713   for (i = 0 ; i < USB_MAXINTERFACES ; i++)
    714     if (dev_handle->claimed_interfaces & (1 << i))
    715       darwin_release_interface (dev_handle, i);
    716 
    717   kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
    718   if (kresult != kIOReturnSuccess)
    719     return darwin_to_libusb (kresult);
    720 
    721   /* Reclaim any interfaces. */
    722   for (i = 0 ; i < USB_MAXINTERFACES ; i++)
    723     if (dev_handle->claimed_interfaces & (1 << i))
    724       darwin_claim_interface (dev_handle, i);
    725 
    726   return 0;
    727 }
    728 
    729 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
    730   IOUSBFindInterfaceRequest request;
    731   uint8_t                   current_interface;
    732   kern_return_t             kresult;
    733   io_iterator_t             interface_iterator;
    734 
    735   *usbInterfacep = IO_OBJECT_NULL;
    736 
    737   /* Setup the Interface Request */
    738   request.bInterfaceClass    = kIOUSBFindInterfaceDontCare;
    739   request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
    740   request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
    741   request.bAlternateSetting  = kIOUSBFindInterfaceDontCare;
    742 
    743   kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
    744   if (kresult)
    745     return kresult;
    746 
    747   for ( current_interface = 0 ; current_interface <= ifc ; current_interface++ )
    748     *usbInterfacep = IOIteratorNext(interface_iterator);
    749 
    750   /* done with the interface iterator */
    751   IOObjectRelease(interface_iterator);
    752 
    753   return 0;
    754 }
    755 
    756 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
    757   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
    758 
    759   /* current interface */
    760   struct __darwin_interface *cInterface = &priv->interfaces[iface];
    761 
    762   kern_return_t kresult;
    763 
    764   u_int8_t numep, direction, number;
    765   u_int8_t dont_care1, dont_care3;
    766   u_int16_t dont_care2;
    767   int i;
    768 
    769   usbi_info (HANDLE_CTX (dev_handle), "building table of endpoints.");
    770 
    771   /* retrieve the total number of endpoints on this interface */
    772   kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
    773   if (kresult) {
    774     usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
    775     return darwin_to_libusb (kresult);
    776   }
    777 
    778   /* iterate through pipe references */
    779   for (i = 1 ; i <= numep ; i++) {
    780     kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
    781 							    &dont_care2, &dont_care3);
    782 
    783     if (kresult != kIOReturnSuccess) {
    784       usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
    785 
    786       return darwin_to_libusb (kresult);
    787     }
    788 
    789     usbi_info (HANDLE_CTX (dev_handle), "interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
    790 
    791     cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
    792   }
    793 
    794   cInterface->num_endpoints = numep;
    795 
    796   return 0;
    797 }
    798 
    799 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
    800   struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
    801   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
    802   io_service_t          usbInterface = IO_OBJECT_NULL;
    803   IOReturn kresult;
    804   IOCFPlugInInterface **plugInInterface = NULL;
    805   SInt32                score;
    806   uint8_t               new_config;
    807 
    808   /* current interface */
    809   struct __darwin_interface *cInterface = &priv->interfaces[iface];
    810 
    811   kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
    812   if (kresult != kIOReturnSuccess)
    813     return darwin_to_libusb (kresult);
    814 
    815   /* make sure we have an interface */
    816   if (!usbInterface) {
    817     u_int8_t nConfig;     /* Index of configuration to use */
    818     IOUSBConfigurationDescriptorPtr configDesc; /* to describe which configuration to select */
    819     /* Only a composite class device with no vendor-specific driver will
    820        be configured. Otherwise, we need to do it ourselves, or there
    821        will be no interfaces for the device. */
    822 
    823     usbi_info (HANDLE_CTX (dev_handle), "no interface found; selecting configuration" );
    824 
    825     kresult = (*(dpriv->device))->GetNumberOfConfigurations (dpriv->device, &nConfig);
    826     if (kresult != kIOReturnSuccess) {
    827       usbi_err (HANDLE_CTX (dev_handle), "GetNumberOfConfigurations: %s", darwin_error_str(kresult));
    828       return darwin_to_libusb(kresult);
    829     }
    830 
    831     if (nConfig < 1) {
    832       usbi_err (HANDLE_CTX (dev_handle), "GetNumberOfConfigurations: no configurations");
    833       return LIBUSB_ERROR_OTHER;
    834     }
    835 
    836     usbi_info (HANDLE_CTX (dev_handle), "device has %d configuration%s. using the first",
    837 	      (int)nConfig, (nConfig > 1 ? "s" : "") );
    838 
    839     /* Always use the first configuration */
    840     kresult = (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, 0, &configDesc);
    841     if (kresult != kIOReturnSuccess) {
    842       usbi_err (HANDLE_CTX (dev_handle), "GetConfigurationDescriptorPtr: %s",
    843 		darwin_error_str(kresult));
    844 
    845       new_config = 1;
    846     } else
    847       new_config = configDesc->bConfigurationValue;
    848 
    849     usbi_info (HANDLE_CTX (dev_handle), "new configuration value is %d", new_config);
    850 
    851     /* set the configuration */
    852     kresult = darwin_set_configuration (dev_handle, new_config);
    853     if (kresult != LIBUSB_SUCCESS) {
    854       usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
    855       return kresult;
    856     }
    857 
    858     kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
    859     if (kresult) {
    860       usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
    861       return darwin_to_libusb (kresult);
    862     }
    863   }
    864 
    865   if (!usbInterface) {
    866     usbi_err (HANDLE_CTX (dev_handle), "interface not found");
    867     return LIBUSB_ERROR_NOT_FOUND;
    868   }
    869 
    870   /* get an interface to the device's interface */
    871   kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
    872 					       kIOCFPlugInInterfaceID, &plugInInterface, &score);
    873   if (kresult) {
    874     usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
    875     return darwin_to_libusb (kresult);
    876   }
    877 
    878   if (!plugInInterface) {
    879     usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
    880     return LIBUSB_ERROR_NOT_FOUND;
    881   }
    882 
    883   /* ignore release error */
    884   (void)IOObjectRelease (usbInterface);
    885 
    886   /* Do the actual claim */
    887   kresult = (*plugInInterface)->QueryInterface(plugInInterface,
    888 					       CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
    889 					       (LPVOID)&cInterface->interface);
    890   if (kresult || !cInterface->interface) {
    891     usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
    892     return darwin_to_libusb (kresult);
    893   }
    894 
    895   /* We no longer need the intermediate plug-in */
    896   (*plugInInterface)->Release(plugInInterface);
    897 
    898   /* claim the interface */
    899   kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
    900   if (kresult) {
    901     usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
    902     return darwin_to_libusb (kresult);
    903   }
    904 
    905   /* update list of endpoints */
    906   kresult = get_endpoints (dev_handle, iface);
    907   if (kresult) {
    908     /* this should not happen */
    909     darwin_release_interface (dev_handle, iface);
    910     usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
    911     return kresult;
    912   }
    913 
    914   cInterface->cfSource = NULL;
    915 
    916   /* create async event source */
    917   kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
    918   if (kresult != kIOReturnSuccess) {
    919     usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
    920 
    921     /* can't continue without an async event source */
    922     (void)darwin_release_interface (dev_handle, iface);
    923 
    924     return darwin_to_libusb (kresult);
    925   }
    926 
    927   /* add the cfSource to the async thread's run loop */
    928   CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
    929 
    930   usbi_info (HANDLE_CTX (dev_handle), "interface opened");
    931 
    932   return 0;
    933 }
    934 
    935 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
    936   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
    937   IOReturn kresult;
    938 
    939   /* current interface */
    940   struct __darwin_interface *cInterface = &priv->interfaces[iface];
    941 
    942   /* Check to see if an interface is open */
    943   if (!cInterface->interface)
    944     return LIBUSB_SUCCESS;
    945 
    946   /* clean up endpoint data */
    947   cInterface->num_endpoints = 0;
    948 
    949   /* delete the interface's async event source */
    950   if (cInterface->cfSource) {
    951     CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
    952     CFRelease (cInterface->cfSource);
    953   }
    954 
    955   kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
    956   if (kresult)
    957     usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
    958 
    959   kresult = (*(cInterface->interface))->Release(cInterface->interface);
    960   if (kresult != kIOReturnSuccess)
    961     usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
    962 
    963   cInterface->interface = IO_OBJECT_NULL;
    964 
    965   return darwin_to_libusb (kresult);
    966 }
    967 
    968 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
    969   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
    970   IOReturn kresult;
    971 
    972   /* current interface */
    973   struct __darwin_interface *cInterface = &priv->interfaces[iface];
    974 
    975   if (!cInterface->interface)
    976     return LIBUSB_ERROR_NO_DEVICE;
    977 
    978   kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
    979   if (kresult != kIOReturnSuccess)
    980     darwin_reset_device (dev_handle);
    981 
    982   /* update list of endpoints */
    983   kresult = get_endpoints (dev_handle, iface);
    984   if (kresult) {
    985     /* this should not happen */
    986     darwin_release_interface (dev_handle, iface);
    987     usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
    988     return kresult;
    989   }
    990 
    991   return darwin_to_libusb (kresult);
    992 }
    993 
    994 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
    995   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
    996 
    997   /* current interface */
    998   struct __darwin_interface *cInterface;
    999   uint8_t pipeRef, iface;
   1000   IOReturn kresult;
   1001 
   1002   /* determine the interface/endpoint to use */
   1003   if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
   1004     usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
   1005 
   1006     return LIBUSB_ERROR_NOT_FOUND;
   1007   }
   1008 
   1009   cInterface = &priv->interfaces[iface];
   1010 
   1011 #if (InterfaceVersion < 190)
   1012   kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
   1013 #else
   1014   /* newer versions of darwin support clearing additional bits on the device's endpoint */
   1015   kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
   1016 #endif
   1017   if (kresult)
   1018     usbi_err (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
   1019 
   1020   return darwin_to_libusb (kresult);
   1021 }
   1022 
   1023 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
   1024   struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
   1025   IOReturn kresult;
   1026 
   1027   kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
   1028   if (kresult)
   1029     usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
   1030 
   1031   return darwin_to_libusb (kresult);
   1032 }
   1033 
   1034 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
   1035   struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
   1036   io_service_t usbInterface;
   1037   CFTypeRef driver;
   1038   IOReturn kresult;
   1039 
   1040   kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
   1041   if (kresult) {
   1042     usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
   1043 
   1044     return darwin_to_libusb (kresult);
   1045   }
   1046 
   1047   driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
   1048   IOObjectRelease (usbInterface);
   1049 
   1050   if (driver) {
   1051     CFRelease (driver);
   1052 
   1053     return 1;
   1054   }
   1055 
   1056   /* no driver */
   1057   return 0;
   1058 }
   1059 
   1060 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
   1061 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
   1062   return LIBUSB_ERROR_NOT_SUPPORTED;
   1063 }
   1064 
   1065 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
   1066   return LIBUSB_ERROR_NOT_SUPPORTED;
   1067 }
   1068 
   1069 static void darwin_destroy_device(struct libusb_device *dev) {
   1070 }
   1071 
   1072 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
   1073   struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   1074   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
   1075 
   1076   IOReturn               ret;
   1077   uint8_t                is_read; /* 0 = we're reading, 1 = we're writing */
   1078   uint8_t                transferType;
   1079   /* None of the values below are used in libusb for bulk transfers */
   1080   uint8_t                direction, number, interval, pipeRef, iface;
   1081   uint16_t               maxPacketSize;
   1082 
   1083   struct __darwin_interface *cInterface;
   1084 
   1085   /* are we reading or writing? */
   1086   is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
   1087 
   1088   if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
   1089     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
   1090 
   1091     return LIBUSB_ERROR_NOT_FOUND;
   1092   }
   1093 
   1094   cInterface = &priv->interfaces[iface];
   1095 
   1096   (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
   1097 						 &transferType, &maxPacketSize, &interval);
   1098 
   1099   /* submit the request */
   1100   /* timeouts are unavailable on interrupt endpoints */
   1101   if (transferType == kUSBInterrupt) {
   1102     if (is_read)
   1103       ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
   1104 						      transfer->length, darwin_async_io_callback, itransfer);
   1105     else
   1106       ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
   1107 						       transfer->length, darwin_async_io_callback, itransfer);
   1108   } else {
   1109     if (is_read)
   1110       ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
   1111 							transfer->length, transfer->timeout, transfer->timeout,
   1112 							darwin_async_io_callback, (void *)itransfer);
   1113     else
   1114       ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
   1115 							 transfer->length, transfer->timeout, transfer->timeout,
   1116 							 darwin_async_io_callback, (void *)itransfer);
   1117   }
   1118 
   1119   if (ret)
   1120     usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", is_read ? "In" : "Out",
   1121 	       darwin_error_str(ret), ret);
   1122 
   1123   return darwin_to_libusb (ret);
   1124 }
   1125 
   1126 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
   1127   struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   1128   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
   1129   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
   1130 
   1131   IOReturn                kresult;
   1132   uint8_t                 is_read; /* 0 = we're writing, 1 = we're reading */
   1133   uint8_t                 pipeRef, iface;
   1134   UInt64                  frame;
   1135   AbsoluteTime            atTime;
   1136   int                     i;
   1137 
   1138   struct __darwin_interface *cInterface;
   1139 
   1140   /* are we reading or writing? */
   1141   is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
   1142 
   1143   /* construct an array of IOUSBIsocFrames */
   1144   tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
   1145   if (!tpriv->isoc_framelist)
   1146     return LIBUSB_ERROR_NO_MEM;
   1147 
   1148   /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
   1149   for (i = 0 ; i < transfer->num_iso_packets ; i++)
   1150     tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
   1151 
   1152   /* determine the interface/endpoint to use */
   1153   if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
   1154     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
   1155 
   1156     return LIBUSB_ERROR_NOT_FOUND;
   1157   }
   1158 
   1159   cInterface = &priv->interfaces[iface];
   1160 
   1161   /* Last but not least we need the bus frame number */
   1162   kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
   1163   if (kresult) {
   1164     usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
   1165     free(tpriv->isoc_framelist);
   1166     tpriv->isoc_framelist = NULL;
   1167 
   1168     return darwin_to_libusb (kresult);
   1169   }
   1170 
   1171   /* schedule for a frame a little in the future */
   1172   frame += 2;
   1173 
   1174   /* submit the request */
   1175   if (is_read)
   1176     kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
   1177 							     transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
   1178 							     itransfer);
   1179   else
   1180     kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
   1181 							      transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
   1182 							      itransfer);
   1183 
   1184   if (kresult != kIOReturnSuccess) {
   1185     usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", is_read ? "In" : "Out",
   1186 	       darwin_error_str(kresult));
   1187     free (tpriv->isoc_framelist);
   1188     tpriv->isoc_framelist = NULL;
   1189   }
   1190 
   1191   return darwin_to_libusb (kresult);
   1192 }
   1193 
   1194 static int submit_control_transfer(struct usbi_transfer *itransfer) {
   1195   struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   1196   struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
   1197   struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
   1198   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
   1199 
   1200   IOReturn               kresult;
   1201 
   1202   bzero(&tpriv->req, sizeof(tpriv->req));
   1203 
   1204   /* IOUSBDeviceInterface expects the request in cpu endianess */
   1205   tpriv->req.bmRequestType     = setup->bmRequestType;
   1206   tpriv->req.bRequest          = setup->bRequest;
   1207   /* these values should be in bus order from libusb_fill_control_setup */
   1208   tpriv->req.wValue            = OSSwapLittleToHostInt16 (setup->wValue);
   1209   tpriv->req.wIndex            = OSSwapLittleToHostInt16 (setup->wIndex);
   1210   tpriv->req.wLength           = OSSwapLittleToHostInt16 (setup->wLength);
   1211   /* data is stored after the libusb control block */
   1212   tpriv->req.pData             = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
   1213   tpriv->req.completionTimeout = transfer->timeout;
   1214   tpriv->req.noDataTimeout     = transfer->timeout;
   1215 
   1216   /* all transfers in libusb-1.0 are async */
   1217   kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
   1218 
   1219   if (kresult != kIOReturnSuccess)
   1220     usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
   1221 
   1222   return darwin_to_libusb (kresult);
   1223 }
   1224 
   1225 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
   1226   struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   1227 
   1228   switch (transfer->type) {
   1229   case LIBUSB_TRANSFER_TYPE_CONTROL:
   1230     return submit_control_transfer(itransfer);
   1231   case LIBUSB_TRANSFER_TYPE_BULK:
   1232   case LIBUSB_TRANSFER_TYPE_INTERRUPT:
   1233     return submit_bulk_transfer(itransfer);
   1234   case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
   1235     return submit_iso_transfer(itransfer);
   1236   default:
   1237     usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
   1238     return LIBUSB_ERROR_INVALID_PARAM;
   1239   }
   1240 }
   1241 
   1242 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
   1243   struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   1244   struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
   1245   IOReturn kresult;
   1246 
   1247   usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions control pipe");
   1248 
   1249   kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
   1250 
   1251   return darwin_to_libusb (kresult);
   1252 }
   1253 
   1254 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
   1255   struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   1256   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
   1257   struct __darwin_interface *cInterface;
   1258   uint8_t pipeRef, iface;
   1259   IOReturn kresult;
   1260 
   1261   if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
   1262     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
   1263 
   1264     return LIBUSB_ERROR_NOT_FOUND;
   1265   }
   1266 
   1267   cInterface = &priv->interfaces[iface];
   1268 
   1269   usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions on interface %d pipe %d", iface, pipeRef);
   1270 
   1271   /* abort transactions */
   1272   (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
   1273 
   1274   usbi_info (ITRANSFER_CTX (itransfer), "calling clear pipe stall to clear the data toggle bit");
   1275 
   1276   /* clear the data toggle bit */
   1277 #if (InterfaceVersion < 190)
   1278   kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
   1279 #else
   1280   /* newer versions of darwin support clearing additional bits on the device's endpoint */
   1281   kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
   1282 #endif
   1283 
   1284   return darwin_to_libusb (kresult);
   1285 }
   1286 
   1287 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
   1288   struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   1289 
   1290   switch (transfer->type) {
   1291   case LIBUSB_TRANSFER_TYPE_CONTROL:
   1292     return cancel_control_transfer(itransfer);
   1293   case LIBUSB_TRANSFER_TYPE_BULK:
   1294   case LIBUSB_TRANSFER_TYPE_INTERRUPT:
   1295   case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
   1296     return darwin_abort_transfers (itransfer);
   1297   default:
   1298     usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
   1299     return LIBUSB_ERROR_INVALID_PARAM;
   1300   }
   1301 }
   1302 
   1303 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
   1304   struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   1305   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
   1306 
   1307   if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
   1308     free (tpriv->isoc_framelist);
   1309     tpriv->isoc_framelist = NULL;
   1310   }
   1311 }
   1312 
   1313 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
   1314   struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
   1315   struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   1316   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
   1317   UInt32 message;
   1318 
   1319   usbi_info (ITRANSFER_CTX (itransfer), "an async io operation has completed");
   1320 
   1321   /* send a completion message to the device's file descriptor */
   1322   message = MESSAGE_ASYNC_IO_COMPLETE;
   1323   write (priv->fds[1], &message, sizeof (message));
   1324   write (priv->fds[1], &itransfer, sizeof (itransfer));
   1325   write (priv->fds[1], &result, sizeof (IOReturn));
   1326   write (priv->fds[1], &arg0, sizeof (UInt32));
   1327 }
   1328 
   1329 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
   1330   switch (result) {
   1331   case kIOReturnSuccess:
   1332     return LIBUSB_TRANSFER_COMPLETED;
   1333   case kIOReturnAborted:
   1334     return LIBUSB_TRANSFER_CANCELLED;
   1335   case kIOUSBPipeStalled:
   1336     usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: pipe is stalled");
   1337     return LIBUSB_TRANSFER_STALL;
   1338   case kIOReturnOverrun:
   1339     usbi_err (ITRANSFER_CTX (itransfer), "transfer error: data overrun", darwin_error_str (result));
   1340     return LIBUSB_TRANSFER_OVERFLOW;
   1341   case kIOUSBTransactionTimeout:
   1342     usbi_err (ITRANSFER_CTX (itransfer), "transfer error: timed out");
   1343     return LIBUSB_TRANSFER_TIMED_OUT;
   1344   default:
   1345     usbi_err (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
   1346     return LIBUSB_TRANSFER_ERROR;
   1347   }
   1348 }
   1349 
   1350 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
   1351   struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   1352   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
   1353   int isIsoc      = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
   1354   int isBulk      = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
   1355   int isControl   = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
   1356   int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
   1357   int i;
   1358 
   1359   if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
   1360     usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
   1361     return;
   1362   }
   1363 
   1364   usbi_info (ITRANSFER_CTX (itransfer), "handling %s completion with kernel status %d",
   1365 	     isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", result);
   1366 
   1367   if (kIOReturnSuccess == result) {
   1368     if (isIsoc && tpriv->isoc_framelist) {
   1369       /* copy isochronous results back */
   1370 
   1371       for (i = 0; i < transfer->num_iso_packets ; i++) {
   1372 	struct libusb_iso_packet_descriptor *lib_desc = transfer->iso_packet_desc;
   1373 	lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
   1374 	lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
   1375       }
   1376     } else if (!isIsoc)
   1377       itransfer->transferred += io_size;
   1378   }
   1379 
   1380   /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
   1381   usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, result));
   1382 }
   1383 
   1384 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, nfds_t nfds, int num_ready) {
   1385   struct usbi_transfer *itransfer;
   1386   UInt32 io_size;
   1387   IOReturn kresult;
   1388   int i = 0, ret;
   1389   UInt32 message;
   1390 
   1391   pthread_mutex_lock(&ctx->open_devs_lock);
   1392   for (i = 0; i < nfds && num_ready > 0; i++) {
   1393     struct pollfd *pollfd = &fds[i];
   1394     struct libusb_device_handle *handle;
   1395     struct darwin_device_handle_priv *hpriv = NULL;
   1396 
   1397     usbi_info (ctx, "checking fd %i with revents = %x", fds[i], pollfd->revents);
   1398 
   1399     if (!pollfd->revents)
   1400       continue;
   1401 
   1402     num_ready--;
   1403     list_for_each_entry(handle, &ctx->open_devs, list) {
   1404       hpriv =  (struct darwin_device_handle_priv *)handle->os_priv;
   1405       if (hpriv->fds[0] == pollfd->fd)
   1406 	break;
   1407     }
   1408 
   1409     if (!(pollfd->revents & POLLERR)) {
   1410       ret = read (hpriv->fds[0], &message, sizeof (message));
   1411       if (ret < sizeof (message))
   1412 	continue;
   1413     } else
   1414       /* could not poll the device-- response is to delete the device (this seems a little heavy-handed) */
   1415       message = MESSAGE_DEVICE_GONE;
   1416 
   1417     switch (message) {
   1418     case MESSAGE_DEVICE_GONE:
   1419       /* remove the device's async port from the runloop */
   1420       if (hpriv->cfSource) {
   1421 	if (libusb_darwin_acfl)
   1422 	  CFRunLoopRemoveSource (libusb_darwin_acfl, hpriv->cfSource, kCFRunLoopDefaultMode);
   1423 	CFRelease (hpriv->cfSource);
   1424 	hpriv->cfSource = NULL;
   1425       }
   1426 
   1427       usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
   1428       usbi_handle_disconnect(handle);
   1429 
   1430       /* done with this device */
   1431       continue;
   1432     case MESSAGE_ASYNC_IO_COMPLETE:
   1433       read (hpriv->fds[0], &itransfer, sizeof (itransfer));
   1434       read (hpriv->fds[0], &kresult, sizeof (IOReturn));
   1435       read (hpriv->fds[0], &io_size, sizeof (UInt32));
   1436 
   1437       darwin_handle_callback (itransfer, kresult, io_size);
   1438       break;
   1439     default:
   1440       usbi_err (ctx, "unknown message received from device pipe");
   1441     }
   1442   }
   1443 
   1444   pthread_mutex_unlock(&ctx->open_devs_lock);
   1445 
   1446   return 0;
   1447 }
   1448 
   1449 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
   1450   mach_timespec_t sys_time;
   1451   clock_serv_t clock_ref;
   1452 
   1453   switch (clk_id) {
   1454   case USBI_CLOCK_REALTIME:
   1455     /* CLOCK_REALTIME represents time since the epoch */
   1456     host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &clock_ref);
   1457     break;
   1458   case USBI_CLOCK_MONOTONIC:
   1459     /* use system boot time as reference for the monotonic clock */
   1460     host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &clock_ref);
   1461     break;
   1462   default:
   1463     return LIBUSB_ERROR_INVALID_PARAM;
   1464   }
   1465 
   1466   clock_get_time (clock_ref, &sys_time);
   1467 
   1468   tp->tv_sec  = sys_time.tv_sec;
   1469   tp->tv_nsec = sys_time.tv_nsec;
   1470 
   1471   return 0;
   1472 }
   1473 
   1474 const struct usbi_os_backend darwin_backend = {
   1475 	.name = "Darwin",
   1476 	.init = darwin_init,
   1477 	.exit = darwin_exit,
   1478 	.get_device_list = darwin_get_device_list,
   1479 	.get_device_descriptor = darwin_get_device_descriptor,
   1480 	.get_active_config_descriptor = darwin_get_active_config_descriptor,
   1481 	.get_config_descriptor = darwin_get_config_descriptor,
   1482 
   1483 	.open = darwin_open,
   1484 	.close = darwin_close,
   1485 	.get_configuration = darwin_get_configuration,
   1486 	.set_configuration = darwin_set_configuration,
   1487 	.claim_interface = darwin_claim_interface,
   1488 	.release_interface = darwin_release_interface,
   1489 
   1490 	.set_interface_altsetting = darwin_set_interface_altsetting,
   1491 	.clear_halt = darwin_clear_halt,
   1492 	.reset_device = darwin_reset_device,
   1493 
   1494 	.kernel_driver_active = darwin_kernel_driver_active,
   1495 	.detach_kernel_driver = darwin_detach_kernel_driver,
   1496 	.attach_kernel_driver = darwin_attach_kernel_driver,
   1497 
   1498 	.destroy_device = darwin_destroy_device,
   1499 
   1500 	.submit_transfer = darwin_submit_transfer,
   1501 	.cancel_transfer = darwin_cancel_transfer,
   1502 	.clear_transfer_priv = darwin_clear_transfer_priv,
   1503 
   1504 	.handle_events = op_handle_events,
   1505 
   1506 	.clock_gettime = darwin_clock_gettime,
   1507 
   1508 	.device_priv_size = sizeof(struct darwin_device_priv),
   1509 	.device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
   1510 	.transfer_priv_size = sizeof(struct darwin_transfer_priv),
   1511 	.add_iso_packet_size = 0,
   1512 };
   1513 
   1514