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