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