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