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