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