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