2 * darwin backend for libusb 1.0
3 * Copyright (C) 2008-2009 Nathan Hjelm <hjelmn@users.sourceforge.net>
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.
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.
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
29 #include <sys/ioctl.h>
31 #include <sys/types.h>
34 #include <mach/clock.h>
35 #include <mach/clock_types.h>
36 #include <mach/mach_host.h>
38 #include <mach/mach_port.h>
39 #include <IOKit/IOCFBundle.h>
40 #include <IOKit/usb/IOUSBLib.h>
41 #include <IOKit/IOCFPlugIn.h>
43 #include "darwin_usb.h"
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;
49 /* async event thread */
50 static pthread_t libusb_darwin_at;
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_bulk_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size);
57 static void darwin_isoc_callback (struct usbi_transfer *itransfer, kern_return_t result);
58 static void darwin_control_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size);
59 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
61 static const char *darwin_error_str (int result) {
63 case kIOReturnSuccess:
65 case kIOReturnNotOpen:
66 return "device not opened for exclusive access";
67 case kIOReturnNoDevice:
68 return "no connection to an IOService";
69 case kIOUSBNoAsyncPortErr:
70 return "no async port has been opened for interface";
71 case kIOReturnExclusiveAccess:
72 return "another process has device opened for exclusive access";
73 case kIOUSBPipeStalled:
74 return "pipe is stalled";
76 return "could not establish a connection to the Darwin kernel";
77 case kIOUSBTransactionTimeout:
78 return "transaction timed out";
79 case kIOReturnBadArgument:
80 return "invalid argument";
81 case kIOReturnAborted:
82 return "transaction aborted";
83 case kIOReturnNotResponding:
84 return "device not responding";
85 case kIOReturnOverrun:
86 return "data overrun";
88 return "unknown error";
92 static int darwin_to_libusb (int result) {
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:
110 case kIOUSBNoAsyncPortErr:
112 return LIBUSB_ERROR_OTHER;
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;
120 /* current interface */
121 struct __darwin_interface *cInterface;
125 _usbi_log (HANDLE_CTX(dev_handle), LOG_LEVEL_INFO, "converting ep address 0x%02x to pipeRef and interface", ep);
127 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
128 cInterface = &priv->interfaces[iface];
130 if (dev_handle->claimed_interfaces & (1 << iface)) {
131 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
132 if (cInterface->endpoint_addrs[i] == ep) {
135 _usbi_log (HANDLE_CTX(dev_handle), LOG_LEVEL_INFO, "pipe %d on interface %d matches", *pipep, *ifcp);
142 /* No pipe found with the correct endpoint address */
143 _usbi_log (HANDLE_CTX(dev_handle), LOG_LEVEL_WARNING, "no pipeRef found with endpoint address 0x%02x.", ep);
148 static int usb_setup_device_iterator (io_iterator_t *deviceIterator) {
149 return IOServiceGetMatchingServices(libusb_darwin_mp, IOServiceMatching(kIOUSBDeviceClassName), deviceIterator);
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;
159 if (!IOIteratorIsValid (deviceIterator) || !(usbDevice = IOIteratorNext(deviceIterator)))
162 result = IOCreatePlugInInterfaceForService(usbDevice, kIOUSBDeviceUserClientTypeID,
163 kIOCFPlugInInterfaceID, &plugInInterface,
166 if (result || !plugInInterface) {
167 usbi_dbg ("libusb/darwin.c usb_get_next_device: could not set up plugin for service: %s\n", darwin_error_str (result));
172 (void)IOObjectRelease(usbDevice);
173 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
176 (*plugInInterface)->Stop(plugInInterface);
177 IODestroyPlugInInterface (plugInInterface);
179 (*(device))->GetLocationID(device, locationp);
184 static kern_return_t darwin_get_device (uint32_t dev_location, usb_device_t ***darwin_device) {
185 kern_return_t kresult;
187 io_iterator_t deviceIterator;
189 kresult = usb_setup_device_iterator (&deviceIterator);
193 /* This port of libusb uses locations to keep track of devices. */
194 while ((*darwin_device = usb_get_next_device (deviceIterator, &location)) != NULL) {
195 if (location == dev_location)
198 (**darwin_device)->Release(*darwin_device);
201 IOObjectRelease (deviceIterator);
203 if (!(*darwin_device))
204 return kIOReturnNoDevice;
206 return kIOReturnSuccess;
211 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
212 struct libusb_context *ctx = (struct libusb_context *)ptr;
213 struct libusb_device_handle *handle;
214 struct darwin_device_priv *dpriv;
215 struct darwin_device_handle_priv *priv;
219 CFTypeRef locationCF;
222 _usbi_log (ctx, LOG_LEVEL_INFO, "a device has been detached");
224 while ((device = IOIteratorNext (rem_devices)) != 0) {
225 /* get the location from the i/o registry */
226 locationCF = IORegistryEntryCreateCFProperty (device, CFSTR(kUSBDevicePropertyLocationID), kCFAllocatorDefault, 0);
228 CFNumberGetValue(locationCF, kCFNumberLongType, &location);
229 CFRelease (locationCF);
230 IOObjectRelease (device);
232 pthread_mutex_lock(&ctx->open_devs_lock);
233 list_for_each_entry(handle, &ctx->open_devs, list) {
234 dpriv = (struct darwin_device_priv *)handle->dev->os_priv;
236 /* the device may have been opened several times. write to each handle's event descriptor */
237 if (dpriv->location == location && handle->os_priv) {
238 priv = (struct darwin_device_handle_priv *)handle->os_priv;
240 message = MESSAGE_DEVICE_GONE;
241 write (priv->fds[1], &message, sizeof (message));
245 pthread_mutex_unlock(&ctx->open_devs_lock);
249 static void darwin_clear_iterator (io_iterator_t iter) {
252 while ((device = IOIteratorNext (iter)) != 0)
253 IOObjectRelease (device);
256 static void *event_thread_main (void *arg0) {
258 struct libusb_context *ctx = (struct libusb_context *)arg0;
260 /* hotplug (device removal) source */
261 CFRunLoopSourceRef libusb_notification_cfsource;
262 io_notification_port_t libusb_notification_port;
263 io_iterator_t libusb_rem_device_iterator;
265 _usbi_log (ctx, LOG_LEVEL_INFO, "creating hotplug event source");
267 CFRetain (CFRunLoopGetCurrent ());
269 /* add the notification port to the run loop */
270 libusb_notification_port = IONotificationPortCreate (libusb_darwin_mp);
271 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
272 CFRunLoopAddSource(CFRunLoopGetCurrent (), libusb_notification_cfsource, kCFRunLoopDefaultMode);
274 /* create notifications for removed devices */
275 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
276 IOServiceMatching(kIOUSBDeviceClassName),
277 (IOServiceMatchingCallback)darwin_devices_detached,
278 (void *)ctx, &libusb_rem_device_iterator);
280 if (kresult != kIOReturnSuccess) {
281 _usbi_log (ctx, LOG_LEVEL_ERROR, "could not add hotplug event source: %s", darwin_error_str (kresult));
283 pthread_exit ((void *)kresult);
287 darwin_clear_iterator (libusb_rem_device_iterator);
289 /* let the main thread know about the async runloop */
290 libusb_darwin_acfl = CFRunLoopGetCurrent ();
292 _usbi_log (ctx, LOG_LEVEL_INFO, "libopenusb/darwin.c event_thread_main: thread ready to receive events");
294 /* run the runloop */
297 _usbi_log (ctx, LOG_LEVEL_INFO, "libopenusb/darwin.c event_thread_main: thread exiting");
299 /* delete notification port */
300 CFRunLoopSourceInvalidate (libusb_notification_cfsource);
301 IONotificationPortDestroy (libusb_notification_port);
303 CFRelease (CFRunLoopGetCurrent ());
305 libusb_darwin_acfl = NULL;
310 static int darwin_init(struct libusb_context *ctx) {
313 if (!(initCount++)) {
314 /* Create the master port for talking to IOKit */
315 if (!libusb_darwin_mp) {
316 kresult = IOMasterPort (MACH_PORT_NULL, &libusb_darwin_mp);
318 if (kresult != kIOReturnSuccess || !libusb_darwin_mp)
319 return darwin_to_libusb (kresult);
322 pthread_create (&libusb_darwin_at, NULL, event_thread_main, (void *)ctx);
324 while (!libusb_darwin_acfl)
331 static void darwin_exit (void) {
332 if (!(--initCount)) {
335 /* stop the async runloop */
336 CFRunLoopStop (libusb_darwin_acfl);
337 pthread_join (libusb_darwin_at, &ret);
339 if (libusb_darwin_mp)
340 mach_port_deallocate(mach_task_self(), libusb_darwin_mp);
342 libusb_darwin_mp = 0;
346 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
347 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
349 /* return cached copy */
350 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
357 static int get_configuration_index (struct libusb_device *dev, int config_value) {
358 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
360 IOUSBConfigurationDescriptorPtr desc;
363 /* is there a simpler way to determine the index? */
364 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
365 if (kresult != kIOReturnSuccess)
366 return darwin_to_libusb (kresult);
368 for (i = 0 ; i < numConfig ; i++) {
369 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
371 if (libusb_le16_to_cpu (desc->bConfigurationValue) == config_value)
375 /* configuration not found */
376 return LIBUSB_ERROR_OTHER;
379 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
380 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
385 kresult = (*(priv->device))->GetConfiguration (priv->device, &config_value);
386 if (kresult != kIOReturnSuccess)
387 return darwin_to_libusb (kresult);
389 config_index = get_configuration_index (dev, config_value);
390 if (config_index < 0)
393 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
396 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
397 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
398 IOUSBConfigurationDescriptorPtr desc;
400 usb_device_t **device = NULL;
403 return LIBUSB_ERROR_OTHER;
406 kresult = darwin_get_device (priv->location, &device);
407 if (kresult || !device) {
408 _usbi_log (DEVICE_CTX (dev), LOG_LEVEL_ERROR, "could not find device: %s", darwin_error_str (kresult));
410 return darwin_to_libusb (kresult);
413 /* don't have to open the device to get a config descriptor */
415 device = priv->device;
417 kresult = (*device)->GetConfigurationDescriptorPtr (device, config_index, &desc);
418 if (kresult == kIOReturnSuccess) {
419 /* copy descriptor */
420 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
421 len = libusb_le16_to_cpu(desc->wTotalLength);
423 memmove (buffer, desc, len);
425 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
430 (*device)->Release (device);
432 return darwin_to_libusb (kresult);
435 static int process_new_device (struct libusb_context *ctx, usb_device_t **device, UInt32 locationID, struct discovered_devs **_discdevs) {
436 struct darwin_device_priv *priv;
437 struct libusb_device *dev;
438 struct discovered_devs *discdevs;
439 UInt16 address, idVendor, idProduct;
440 UInt8 bDeviceClass, bDeviceSubClass;
444 dev = usbi_get_device_by_session_id(ctx, locationID);
446 _usbi_log (ctx, LOG_LEVEL_INFO, "allocating new device for location 0x%08x", locationID);
447 dev = usbi_alloc_device(ctx, locationID);
449 return LIBUSB_ERROR_NO_MEM;
451 priv = (struct darwin_device_priv *)dev->os_priv;
453 /* Set up request for device descriptor */
454 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
455 req.bRequest = kUSBRqGetDescriptor;
456 req.wValue = kUSBDeviceDesc << 8;
458 req.wLength = sizeof(IOUSBDeviceDescriptor);
459 req.pData = &(priv->dev_descriptor);
461 (*(device))->GetDeviceAddress (device, (USBDeviceAddress *)&address);
462 (*(device))->GetDeviceProduct (device, &idProduct);
463 (*(device))->GetDeviceVendor (device, &idVendor);
464 (*(device))->GetDeviceClass (device, &bDeviceClass);
465 (*(device))->GetDeviceSubClass (device, &bDeviceSubClass);
467 /**** retrieve device descriptors ****/
468 /* device must be open for DeviceRequest */
469 (*device)->USBDeviceOpen(device);
471 ret = (*(device))->DeviceRequest (device, &req);
472 if (ret != kIOReturnSuccess) {
473 int try_unsuspend = 1;
474 #if DeviceVersion >= 320
477 /* device may be suspended. unsuspend it and try again */
478 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
479 (void)(*device)->GetUSBDeviceInformation (device, &info);
481 try_unsuspend = info & (1 << kUSBInformationDeviceIsSuspendedBit);
485 /* resume the device */
486 (void)(*device)->USBDeviceSuspend (device, 0);
488 ret = (*(device))->DeviceRequest (device, &req);
490 /* resuspend the device */
491 (void)(*device)->USBDeviceSuspend (device, 1);
495 (*device)->USBDeviceClose (device);
497 if (ret != kIOReturnSuccess) {
498 _usbi_log (ctx, LOG_LEVEL_WARNING, "could not retrieve device descriptor: %s. skipping device", darwin_error_str (ret));
499 libusb_unref_device(dev);
502 /**** end: retrieve device descriptors ****/
504 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
505 if (libusb_le16_to_cpu (priv->dev_descriptor.idProduct) != idProduct) {
506 /* not a valid device */
507 _usbi_log (ctx, LOG_LEVEL_WARNING, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
508 idProduct, libusb_le16_to_cpu (priv->dev_descriptor.idProduct));
509 libusb_unref_device(dev);
513 dev->bus_number = locationID >> 24;
514 dev->device_address = address;
516 /* save our location, we'll need this later */
517 priv->location = locationID;
518 snprintf(priv->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", address, idVendor, idProduct, bDeviceClass, bDeviceSubClass);
520 ret = usbi_sanitize_device(dev);
523 libusb_unref_device(dev);
527 priv = (struct darwin_device_priv *)dev->os_priv;
529 _usbi_log (ctx, LOG_LEVEL_INFO, "using existing device for location 0x%08x", locationID);
532 /* append the device to the list of discovered devices */
533 discdevs = discovered_devs_append(*_discdevs, dev);
535 return LIBUSB_ERROR_NO_MEM;
537 *_discdevs = discdevs;
539 _usbi_log (ctx, LOG_LEVEL_INFO, "found device with address %d at %s", dev->device_address, priv->sys_path);
544 static int darwin_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs) {
545 io_iterator_t deviceIterator;
546 usb_device_t **device;
547 kern_return_t kresult;
550 if (!libusb_darwin_mp)
551 return LIBUSB_ERROR_INVALID_PARAM;
553 kresult = usb_setup_device_iterator (&deviceIterator);
554 if (kresult != kIOReturnSuccess)
555 return darwin_to_libusb (kresult);
557 while ((device = usb_get_next_device (deviceIterator, &location)) != NULL) {
558 (void) process_new_device (ctx, device, location, _discdevs);
560 (*(device))->Release(device);
563 IOObjectRelease(deviceIterator);
568 static int darwin_open (struct libusb_device_handle *dev_handle) {
569 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
570 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
571 usb_device_t **darwin_device;
574 if (0 == dpriv->open_count) {
575 kresult = darwin_get_device (dpriv->location, &darwin_device);
577 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "could not find device: %s", darwin_error_str (kresult));
578 return darwin_to_libusb (kresult);
581 dpriv->device = darwin_device;
583 /* try to open the device */
584 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
586 if (kresult != kIOReturnSuccess) {
587 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "USBDeviceOpen: %s", darwin_error_str(kresult));
590 case kIOReturnExclusiveAccess:
591 /* it is possible to perform some actions on a device that is not open so do not return an error */
596 (*(dpriv->device))->Release (dpriv->device);
597 dpriv->device = NULL;
598 return darwin_to_libusb (kresult);
603 /* create async event source */
604 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
606 CFRetain (libusb_darwin_acfl);
608 /* add the cfSource to the aync run loop */
609 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
613 /* device opened successfully */
616 /* create a file descriptor for notifications */
619 /* set the pipe to be non-blocking */
620 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
622 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
624 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "device open for access");
629 static void darwin_close (struct libusb_device_handle *dev_handle) {
630 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
631 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
635 if (dpriv->open_count == 0) {
636 /* something is probably very wrong if this is the case */
637 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "Close called on a device that was not open!\n");
643 /* make sure all interfaces are released */
644 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
645 if (dev_handle->claimed_interfaces & (1 << i))
646 libusb_release_interface (dev_handle, i);
648 if (0 == dpriv->open_count) {
650 /* delete the device's async event source */
651 if (priv->cfSource) {
652 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
653 CFRelease (priv->cfSource);
656 /* close the device */
657 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
659 /* Log the fact that we had a problem closing the file, however failing a
660 * close isn't really an error, so return success anyway */
661 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "USBDeviceClose: %s", darwin_error_str(kresult));
665 kresult = (*(dpriv->device))->Release(dpriv->device);
667 /* Log the fact that we had a problem closing the file, however failing a
668 * close isn't really an error, so return success anyway */
669 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "Release: %s", darwin_error_str(kresult));
672 dpriv->device = NULL;
675 /* file descriptors are maintained per-instance */
676 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
677 close (priv->fds[1]);
678 close (priv->fds[0]);
680 priv->fds[0] = priv->fds[1] = -1;
683 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
684 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
688 kresult = (*(dpriv->device))->GetConfiguration (dpriv->device, &configNum);
689 if (kresult != kIOReturnSuccess)
690 return darwin_to_libusb (kresult);
692 *config = (int) configNum;
697 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
698 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
702 /* Setting configuration will invalidate the interface, so we need
703 to reclaim it. First, dispose of existing interfaces, if any. */
704 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
705 if (dev_handle->claimed_interfaces & (1 << i))
706 darwin_release_interface (dev_handle, i);
708 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
709 if (kresult != kIOReturnSuccess)
710 return darwin_to_libusb (kresult);
712 /* Reclaim any interfaces. */
713 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
714 if (dev_handle->claimed_interfaces & (1 << i))
715 darwin_claim_interface (dev_handle, i);
720 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
721 IOUSBFindInterfaceRequest request;
722 uint8_t current_interface;
723 kern_return_t kresult;
724 io_iterator_t interface_iterator;
726 *usbInterfacep = IO_OBJECT_NULL;
728 /* Setup the Interface Request */
729 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
730 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
731 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
732 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
734 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
738 for ( current_interface = 0 ; current_interface <= ifc ; current_interface++ )
739 *usbInterfacep = IOIteratorNext(interface_iterator);
741 /* done with the interface iterator */
742 IOObjectRelease(interface_iterator);
747 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
748 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
750 /* current interface */
751 struct __darwin_interface *cInterface = &priv->interfaces[iface];
753 kern_return_t kresult;
755 u_int8_t numep, direction, number;
756 u_int8_t dont_care1, dont_care3;
757 u_int16_t dont_care2;
760 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "building table of endpoints.");
762 /* retrieve the total number of endpoints on this interface */
763 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
765 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
766 return darwin_to_libusb (kresult);
769 /* iterate through pipe references */
770 for (i = 1 ; i <= numep ; i++) {
771 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
772 &dont_care2, &dont_care3);
774 if (kresult != kIOReturnSuccess) {
775 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
777 return darwin_to_libusb (kresult);
780 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
782 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
785 cInterface->num_endpoints = numep;
790 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
791 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
792 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
793 io_service_t usbInterface = IO_OBJECT_NULL;
795 IOCFPlugInInterface **plugInInterface = NULL;
799 /* current interface */
800 struct __darwin_interface *cInterface = &priv->interfaces[iface];
802 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
803 if (kresult != kIOReturnSuccess)
804 return darwin_to_libusb (kresult);
806 /* make sure we have an interface */
808 u_int8_t nConfig; /* Index of configuration to use */
809 IOUSBConfigurationDescriptorPtr configDesc; /* to describe which configuration to select */
810 /* Only a composite class device with no vendor-specific driver will
811 be configured. Otherwise, we need to do it ourselves, or there
812 will be no interfaces for the device. */
814 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "no interface found; selecting configuration" );
816 kresult = (*(dpriv->device))->GetNumberOfConfigurations (dpriv->device, &nConfig);
817 if (kresult != kIOReturnSuccess) {
818 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "GetNumberOfConfigurations: %s", darwin_error_str(kresult));
819 return darwin_to_libusb(kresult);
823 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "GetNumberOfConfigurations: no configurations");
824 return LIBUSB_ERROR_OTHER;
827 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "device has %d configuration%s. using the first",
828 (int)nConfig, (nConfig > 1 ? "s" : "") );
830 /* Always use the first configuration */
831 kresult = (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, 0, &configDesc);
832 if (kresult != kIOReturnSuccess) {
833 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "GetConfigurationDescriptorPtr: %s",
834 darwin_error_str(kresult));
838 new_config = configDesc->bConfigurationValue;
840 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "new configuration value is %d", new_config);
842 /* set the configuration */
843 kresult = darwin_set_configuration (dev_handle, new_config);
844 if (kresult != LIBUSB_SUCCESS) {
845 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "could not set configuration");
849 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
851 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "darwin_get_interface: %s", darwin_error_str(kresult));
852 return darwin_to_libusb (kresult);
857 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "interface not found");
858 return LIBUSB_ERROR_NOT_FOUND;
861 /* get an interface to the device's interface */
862 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
863 kIOCFPlugInInterfaceID, &plugInInterface, &score);
865 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
866 return darwin_to_libusb (kresult);
869 if (!plugInInterface) {
870 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "plugin interface not found");
871 return LIBUSB_ERROR_NOT_FOUND;
874 /* ignore release error */
875 (void)IOObjectRelease (usbInterface);
877 /* Do the actual claim */
878 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
879 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
880 (LPVOID)&cInterface->interface);
881 if (kresult || !cInterface->interface) {
882 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "QueryInterface: %s", darwin_error_str(kresult));
883 return darwin_to_libusb (kresult);
886 /* We no longer need the intermediate plug-in */
887 (*plugInInterface)->Release(plugInInterface);
889 /* claim the interface */
890 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
892 _usbi_log(HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "USBInterfaceOpen: %s", darwin_error_str(kresult));
893 return darwin_to_libusb (kresult);
896 /* update list of endpoints */
897 kresult = get_endpoints (dev_handle, iface);
899 /* this should not happen */
900 darwin_release_interface (dev_handle, iface);
901 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "could not build endpoint table");
905 cInterface->cfSource = NULL;
907 /* create async event source */
908 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
909 if (kresult != kIOReturnSuccess) {
910 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "could not create async event source");
912 /* can't continue without an async event source */
913 (void)darwin_release_interface (dev_handle, iface);
915 return darwin_to_libusb (kresult);
918 /* add the cfSource to the async thread's run loop */
919 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
921 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "interface opened");
926 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
927 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
930 /* current interface */
931 struct __darwin_interface *cInterface = &priv->interfaces[iface];
933 /* Check to see if an interface is open */
934 if (!cInterface->interface)
935 return LIBUSB_SUCCESS;
937 /* clean up endpoint data */
938 cInterface->num_endpoints = 0;
940 /* delete the interface's async event source */
941 if (cInterface->cfSource) {
942 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
943 CFRelease (cInterface->cfSource);
946 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
948 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "USBInterfaceClose: %s", darwin_error_str(kresult));
950 kresult = (*(cInterface->interface))->Release(cInterface->interface);
951 if (kresult != kIOReturnSuccess)
952 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "Release: %s", darwin_error_str(kresult));
954 cInterface->interface = IO_OBJECT_NULL;
956 return darwin_to_libusb (kresult);
959 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
960 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
963 /* current interface */
964 struct __darwin_interface *cInterface = &priv->interfaces[iface];
966 if (!cInterface->interface)
967 return LIBUSB_ERROR_NO_DEVICE;
969 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
970 if (kresult != kIOReturnSuccess)
971 darwin_reset_device (dev_handle);
973 /* update list of endpoints */
974 kresult = get_endpoints (dev_handle, iface);
976 /* this should not happen */
977 darwin_release_interface (dev_handle, iface);
978 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "could not build endpoint table");
982 return darwin_to_libusb (kresult);
985 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
986 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
988 /* current interface */
989 struct __darwin_interface *cInterface;
990 uint8_t pipeRef, iface;
993 /* determine the interface/endpoint to use */
994 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
995 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
997 return LIBUSB_ERROR_NOT_FOUND;
1000 cInterface = &priv->interfaces[iface];
1002 #if (InterfaceVersion < 190)
1003 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1005 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1006 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1009 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "ClearPipeStall: %s", darwin_error_str (kresult));
1011 return darwin_to_libusb (kresult);
1014 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1015 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1018 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1020 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "ResetDevice: %s", darwin_error_str (kresult));
1022 return darwin_to_libusb (kresult);
1025 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1026 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1027 io_service_t usbInterface;
1031 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1033 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "darwin_get_interface: %s", darwin_error_str(kresult));
1035 return darwin_to_libusb (kresult);
1038 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1039 IOObjectRelease (usbInterface);
1051 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1052 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1053 return LIBUSB_ERROR_NOT_SUPPORTED;
1056 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1057 return LIBUSB_ERROR_NOT_SUPPORTED;
1060 static void darwin_destroy_device(struct libusb_device *dev) {
1063 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1064 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1065 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1068 uint8_t is_read; /* 0 = we're reading, 1 = we're writing */
1069 uint8_t transferType;
1070 /* None of the values below are used in libusb for bulk transfers */
1071 uint8_t direction, number, interval, pipeRef, iface;
1072 uint16_t maxPacketSize;
1074 struct __darwin_interface *cInterface;
1076 /* are we reading or writing? */
1077 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1079 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1080 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
1082 return LIBUSB_ERROR_NOT_FOUND;
1085 cInterface = &priv->interfaces[iface];
1087 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1088 &transferType, &maxPacketSize, &interval);
1090 /* submit the request */
1091 /* timeouts are unavailable on interrupt endpoints */
1092 if (transferType == kUSBInterrupt) {
1094 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1095 transfer->length, darwin_async_io_callback, itransfer);
1097 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1098 transfer->length, darwin_async_io_callback, itransfer);
1101 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1102 transfer->length, transfer->timeout, transfer->timeout,
1103 darwin_async_io_callback, (void *)itransfer);
1105 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1106 transfer->length, transfer->timeout, transfer->timeout,
1107 darwin_async_io_callback, (void *)itransfer);
1111 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "bulk transfer failed (dir = %s): %s", is_read ? "In" : "Out",
1112 darwin_error_str(ret));
1114 return darwin_to_libusb (ret);
1117 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1118 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1119 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1120 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1123 uint8_t is_read; /* 0 = we're writing, 1 = we're reading */
1124 uint8_t pipeRef, iface;
1126 AbsoluteTime atTime;
1129 struct __darwin_interface *cInterface;
1131 /* are we reading or writing? */
1132 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1134 /* construct an array of IOUSBIsocFrames */
1135 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1136 if (!tpriv->isoc_framelist)
1137 return LIBUSB_ERROR_NO_MEM;
1139 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1140 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1141 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1143 /* determine the interface/endpoint to use */
1144 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1145 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
1147 return LIBUSB_ERROR_NOT_FOUND;
1150 cInterface = &priv->interfaces[iface];
1152 /* Last but not least we need the bus frame number */
1153 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1155 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "failed to get bus frame number: %d", kresult);
1156 free(tpriv->isoc_framelist);
1157 tpriv->isoc_framelist = NULL;
1159 return darwin_to_libusb (kresult);
1162 /* schedule for a frame a little in the future */
1165 /* submit the request */
1167 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1168 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1171 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1172 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1175 if (kresult != kIOReturnSuccess) {
1176 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "isochronous transfer failed (dir: %s): %s", is_read ? "In" : "Out",
1177 darwin_error_str(kresult));
1178 free (tpriv->isoc_framelist);
1179 tpriv->isoc_framelist = NULL;
1182 return darwin_to_libusb (kresult);
1185 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1186 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1187 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1188 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1189 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1193 bzero(&tpriv->req, sizeof(tpriv->req));
1195 /* IOUSBDeviceInterface expects the request in cpu endianess */
1196 tpriv->req.bmRequestType = setup->bmRequestType;
1197 tpriv->req.bRequest = setup->bRequest;
1198 /* these values should already be in bus order */
1199 tpriv->req.wValue = setup->wValue;
1200 tpriv->req.wIndex = setup->wIndex;
1201 tpriv->req.wLength = setup->wLength;
1202 /* data is stored after the libusb control block */
1203 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1204 tpriv->req.completionTimeout = transfer->timeout;
1205 tpriv->req.noDataTimeout = transfer->timeout;
1207 /* all transfers in libusb-1.0 are async */
1208 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1210 if (kresult != kIOReturnSuccess)
1211 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "control request failed: %s", darwin_error_str(kresult));
1213 return darwin_to_libusb (kresult);
1216 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1217 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1219 switch (transfer->type) {
1220 case LIBUSB_TRANSFER_TYPE_CONTROL:
1221 return submit_control_transfer(itransfer);
1222 case LIBUSB_TRANSFER_TYPE_BULK:
1223 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1224 return submit_bulk_transfer(itransfer);
1225 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1226 return submit_iso_transfer(itransfer);
1228 _usbi_log (TRANSFER_CTX(transfer), LOG_LEVEL_ERROR, "unknown endpoint type %d", transfer->type);
1229 return LIBUSB_ERROR_INVALID_PARAM;
1233 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1234 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1235 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1238 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "WARNING: aborting all transactions control pipe");
1240 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1242 return darwin_to_libusb (kresult);
1245 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1246 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1247 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1248 struct __darwin_interface *cInterface;
1249 uint8_t pipeRef, iface;
1252 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1253 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
1255 return LIBUSB_ERROR_NOT_FOUND;
1258 cInterface = &priv->interfaces[iface];
1260 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "WARNING: aborting all transactions on interface %d pipe %d", iface, pipeRef);
1262 /* abort transactions */
1263 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1265 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "calling clear pipe stall to clear the data toggle bit");
1267 /* clear the data toggle bit */
1268 #if (InterfaceVersion < 190)
1269 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1271 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1272 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1275 return darwin_to_libusb (kresult);
1278 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1279 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1281 switch (transfer->type) {
1282 case LIBUSB_TRANSFER_TYPE_CONTROL:
1283 return cancel_control_transfer(itransfer);
1284 case LIBUSB_TRANSFER_TYPE_BULK:
1285 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1286 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1287 return darwin_abort_transfers (itransfer);
1289 _usbi_log (TRANSFER_CTX(transfer), LOG_LEVEL_ERROR, "unknown endpoint type %d", transfer->type);
1290 return LIBUSB_ERROR_INVALID_PARAM;
1294 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1295 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1296 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1298 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1299 free (tpriv->isoc_framelist);
1300 tpriv->isoc_framelist = NULL;
1304 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1305 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1306 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1307 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1310 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "an async io operation has completed");
1312 /* send a completion message to the device's file descriptor */
1313 message = MESSAGE_ASYNC_IO_COMPLETE;
1314 write (priv->fds[1], &message, sizeof (message));
1315 write (priv->fds[1], &itransfer, sizeof (itransfer));
1316 write (priv->fds[1], &result, sizeof (IOReturn));
1317 write (priv->fds[1], &arg0, sizeof (UInt32));
1320 static void darwin_bulk_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1321 enum libusb_transfer_status status;
1323 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "handling bulk completion with status %d", result);
1326 case kIOReturnSuccess:
1327 status = LIBUSB_TRANSFER_COMPLETED;
1328 itransfer->transferred += io_size;
1330 case kIOReturnAborted:
1331 usbi_handle_transfer_cancellation(itransfer);
1333 case kIOUSBPipeStalled:
1334 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_WARNING, "bulk error. pipe is stalled");
1335 status = LIBUSB_TRANSFER_STALL;
1338 case kIOReturnOverrun:
1339 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_ERROR, "bulk error. data overrun", darwin_error_str (result));
1340 status = LIBUSB_TRANSFER_OVERFLOW;
1344 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_ERROR, "bulk error = %s (value = 0x%08x)", darwin_error_str (result), result);
1345 status = LIBUSB_TRANSFER_ERROR;
1348 usbi_handle_transfer_completion(itransfer, status);
1351 static void darwin_isoc_callback (struct usbi_transfer *itransfer, kern_return_t result) {
1352 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1353 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1356 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "handling isoc completion with status %d", result);
1358 if (result == kIOReturnSuccess && tpriv->isoc_framelist) {
1359 /* copy isochronous results back */
1361 for (i = 0; i < transfer->num_iso_packets ; i++) {
1362 struct libusb_iso_packet_descriptor *lib_desc = transfer->iso_packet_desc;
1363 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1364 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1369 case kIOReturnSuccess:
1370 status = LIBUSB_TRANSFER_COMPLETED;
1372 case kIOReturnAborted:
1373 usbi_handle_transfer_cancellation(itransfer);
1375 case kIOUSBPipeStalled:
1376 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_WARNING, "unsupported control request");
1377 status = LIBUSB_TRANSFER_STALL;
1380 case kIOReturnOverrun:
1381 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_ERROR, "bulk error. data overrun", darwin_error_str (result));
1382 status = LIBUSB_TRANSFER_OVERFLOW;
1386 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_ERROR, "control error = %s", darwin_error_str (result));
1387 status = LIBUSB_TRANSFER_ERROR;
1390 usbi_handle_transfer_completion(itransfer, status);
1393 static void darwin_control_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1396 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "handling control completion with status %d", result);
1399 case kIOReturnSuccess:
1400 status = LIBUSB_TRANSFER_COMPLETED;
1401 itransfer->transferred += io_size;
1403 case kIOReturnAborted:
1404 usbi_handle_transfer_cancellation(itransfer);
1406 case kIOUSBPipeStalled:
1407 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_WARNING, "unsupported control request");
1408 status = LIBUSB_TRANSFER_STALL;
1412 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_ERROR, "control error = %s", darwin_error_str (result));
1413 status = LIBUSB_TRANSFER_ERROR;
1416 usbi_handle_transfer_completion(itransfer, status);
1419 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1420 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1422 switch (transfer->type) {
1423 case LIBUSB_TRANSFER_TYPE_CONTROL:
1424 darwin_control_callback (itransfer, result, io_size);
1426 case LIBUSB_TRANSFER_TYPE_BULK:
1427 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1428 darwin_bulk_callback (itransfer, result, io_size);
1430 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1431 darwin_isoc_callback (itransfer, result);
1434 _usbi_log (TRANSFER_CTX(transfer), LOG_LEVEL_ERROR, "unknown endpoint type %d", transfer->type);
1438 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, nfds_t nfds, int num_ready) {
1439 struct usbi_transfer *itransfer;
1445 pthread_mutex_lock(&ctx->open_devs_lock);
1446 for (i = 0; i < nfds && num_ready > 0; i++) {
1447 struct pollfd *pollfd = &fds[i];
1448 struct libusb_device_handle *handle;
1449 struct darwin_device_handle_priv *hpriv = NULL;
1451 _usbi_log (ctx, LOG_LEVEL_INFO, "checking fd %i with revents = %x", fds[i], pollfd->revents);
1453 if (!pollfd->revents)
1457 list_for_each_entry(handle, &ctx->open_devs, list) {
1458 hpriv = (struct darwin_device_handle_priv *)handle->os_priv;
1459 if (hpriv->fds[0] == pollfd->fd)
1463 if (!(pollfd->revents & POLLERR)) {
1464 ret = read (hpriv->fds[0], &message, sizeof (message));
1465 if (ret < sizeof (message))
1468 /* could not poll the device-- response is to delete the device (this seems a little heavy-handed) */
1469 message = MESSAGE_DEVICE_GONE;
1472 case MESSAGE_DEVICE_GONE:
1473 /* remove the device's async port from the runloop */
1474 if (hpriv->cfSource) {
1475 if (libusb_darwin_acfl)
1476 CFRunLoopRemoveSource (libusb_darwin_acfl, hpriv->cfSource, kCFRunLoopDefaultMode);
1477 CFRelease (hpriv->cfSource);
1478 hpriv->cfSource = NULL;
1481 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
1482 usbi_handle_disconnect(handle);
1484 /* done with this device */
1486 case MESSAGE_ASYNC_IO_COMPLETE:
1487 read (hpriv->fds[0], &itransfer, sizeof (itransfer));
1488 read (hpriv->fds[0], &kresult, sizeof (IOReturn));
1489 read (hpriv->fds[0], &io_size, sizeof (UInt32));
1491 darwin_handle_callback (itransfer, kresult, io_size);
1494 _usbi_log (ctx, LOG_LEVEL_ERROR, "unknown message received from device pipe");
1498 pthread_mutex_unlock(&ctx->open_devs_lock);
1503 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1504 mach_timespec_t sys_time;
1505 clock_serv_t clock_ref;
1508 case USBI_CLOCK_REALTIME:
1509 /* CLOCK_REALTIME represents time since the epoch */
1510 host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &clock_ref);
1512 case USBI_CLOCK_MONOTONIC:
1513 /* use system boot time as reference for the monotonic clock */
1514 host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &clock_ref);
1517 return LIBUSB_ERROR_INVALID_PARAM;
1520 clock_get_time (clock_ref, &sys_time);
1522 tp->tv_sec = sys_time.tv_sec;
1523 tp->tv_nsec = sys_time.tv_nsec;
1528 const struct usbi_os_backend darwin_backend = {
1530 .init = darwin_init,
1531 .exit = darwin_exit,
1532 .get_device_list = darwin_get_device_list,
1533 .get_device_descriptor = darwin_get_device_descriptor,
1534 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1535 .get_config_descriptor = darwin_get_config_descriptor,
1537 .open = darwin_open,
1538 .close = darwin_close,
1539 .get_configuration = darwin_get_configuration,
1540 .set_configuration = darwin_set_configuration,
1541 .claim_interface = darwin_claim_interface,
1542 .release_interface = darwin_release_interface,
1544 .set_interface_altsetting = darwin_set_interface_altsetting,
1545 .clear_halt = darwin_clear_halt,
1546 .reset_device = darwin_reset_device,
1548 .kernel_driver_active = darwin_kernel_driver_active,
1549 .detach_kernel_driver = darwin_detach_kernel_driver,
1550 .attach_kernel_driver = darwin_attach_kernel_driver,
1552 .destroy_device = darwin_destroy_device,
1554 .submit_transfer = darwin_submit_transfer,
1555 .cancel_transfer = darwin_cancel_transfer,
1556 .clear_transfer_priv = darwin_clear_transfer_priv,
1558 .handle_events = op_handle_events,
1560 .clock_gettime = darwin_clock_gettime,
1562 .device_priv_size = sizeof(struct darwin_device_priv),
1563 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1564 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1565 .add_iso_packet_size = 0,