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