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