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