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