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