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