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 */
48 /* async event thread */
49 static pthread_t libusb_darwin_at;
51 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
52 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
53 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
54 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
55 static void darwin_bulk_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size);
56 static void darwin_isoc_callback (struct usbi_transfer *itransfer, kern_return_t result);
57 static void darwin_control_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size);
58 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
60 static const char *darwin_error_str (int result) {
62 case kIOReturnSuccess:
64 case kIOReturnNotOpen:
65 return "device not opened for exclusive access";
66 case kIOReturnNoDevice:
67 return "no connection to an IOService";
68 case kIOUSBNoAsyncPortErr:
69 return "no async port has been opened for interface";
70 case kIOReturnExclusiveAccess:
71 return "another process has device opened for exclusive access";
72 case kIOUSBPipeStalled:
73 return "pipe is stalled";
75 return "could not establish a connection to the Darwin kernel";
76 case kIOUSBTransactionTimeout:
77 return "transaction timed out";
78 case kIOReturnBadArgument:
79 return "invalid argument";
80 case kIOReturnAborted:
81 return "transaction aborted";
82 case kIOReturnNotResponding:
83 return "device not responding";
84 case kIOReturnOverrun:
85 return "data overrun";
87 return "unknown error";
91 static int darwin_to_libusb (int result) {
93 case kIOReturnSuccess:
94 return LIBUSB_SUCCESS;
95 case kIOReturnNotOpen:
96 case kIOReturnNoDevice:
97 return LIBUSB_ERROR_NO_DEVICE;
98 case kIOReturnExclusiveAccess:
99 return LIBUSB_ERROR_ACCESS;
100 case kIOUSBPipeStalled:
101 return LIBUSB_ERROR_PIPE;
102 case kIOReturnBadArgument:
103 return LIBUSB_ERROR_INVALID_PARAM;
104 case kIOUSBTransactionTimeout:
105 return LIBUSB_ERROR_TIMEOUT;
106 case kIOReturnNotResponding:
107 case kIOReturnAborted:
109 case kIOUSBNoAsyncPortErr:
111 return LIBUSB_ERROR_OTHER;
116 static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp) {
117 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
119 /* current interface */
120 struct __darwin_interface *cInterface;
124 _usbi_log (HANDLE_CTX(dev_handle), LOG_LEVEL_INFO, "converting ep address 0x%02x to pipeRef and interface", ep);
126 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
127 cInterface = &priv->interfaces[iface];
129 if (dev_handle->claimed_interfaces & (1 << iface)) {
130 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
131 if (cInterface->endpoint_addrs[i] == ep) {
134 _usbi_log (HANDLE_CTX(dev_handle), LOG_LEVEL_INFO, "pipe %d on interface %d matches", *pipep, *ifcp);
141 /* No pipe found with the correct endpoint address */
142 _usbi_log (HANDLE_CTX(dev_handle), LOG_LEVEL_WARNING, "no pipeRef found with endpoint address 0x%02x.", ep);
147 static int usb_setup_device_iterator (io_iterator_t *deviceIterator) {
148 return IOServiceGetMatchingServices(libusb_darwin_mp, IOServiceMatching(kIOUSBDeviceClassName), deviceIterator);
151 static usb_device_t **usb_get_next_device (io_iterator_t deviceIterator, UInt32 *locationp) {
152 io_cf_plugin_ref_t *plugInInterface = NULL;
153 usb_device_t **device;
154 io_service_t usbDevice;
158 if (!IOIteratorIsValid (deviceIterator) || !(usbDevice = IOIteratorNext(deviceIterator)))
161 result = IOCreatePlugInInterfaceForService(usbDevice, kIOUSBDeviceUserClientTypeID,
162 kIOCFPlugInInterfaceID, &plugInInterface,
165 if (result || !plugInInterface) {
166 usbi_dbg ("libusb/darwin.c usb_get_next_device: could not set up plugin for service: %s\n", darwin_error_str (result));
171 (void)IOObjectRelease(usbDevice);
172 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
175 (*plugInInterface)->Stop(plugInInterface);
176 IODestroyPlugInInterface (plugInInterface);
178 (*(device))->GetLocationID(device, locationp);
183 static kern_return_t darwin_get_device (uint32_t dev_location, usb_device_t ***darwin_device) {
184 kern_return_t kresult;
186 io_iterator_t deviceIterator;
188 kresult = usb_setup_device_iterator (&deviceIterator);
192 /* This port of libusb uses locations to keep track of devices. */
193 while ((*darwin_device = usb_get_next_device (deviceIterator, &location)) != NULL) {
194 if (location == dev_location)
197 (**darwin_device)->Release(*darwin_device);
200 IOObjectRelease (deviceIterator);
202 if (!(*darwin_device))
203 return kIOReturnNoDevice;
205 return kIOReturnSuccess;
210 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
211 struct libusb_context *ctx = (struct libusb_context *)ptr;
212 struct libusb_device_handle *handle;
213 struct darwin_device_priv *dpriv;
214 struct darwin_device_handle_priv *priv;
218 CFTypeRef locationCF;
221 _usbi_log (ctx, LOG_LEVEL_INFO, "a device has been detached");
223 while ((device = IOIteratorNext (rem_devices)) != 0) {
224 /* get the location from the i/o registry */
225 locationCF = IORegistryEntryCreateCFProperty (device, CFSTR(kUSBDevicePropertyLocationID), kCFAllocatorDefault, 0);
227 CFNumberGetValue(locationCF, kCFNumberLongType, &location);
228 CFRelease (locationCF);
229 IOObjectRelease (device);
231 pthread_mutex_lock(&ctx->open_devs_lock);
232 list_for_each_entry(handle, &ctx->open_devs, list) {
233 dpriv = (struct darwin_device_priv *)handle->dev->os_priv;
235 /* the device may have been opened several times. write to each handle's event descriptor */
236 if (dpriv->location == location && handle->os_priv) {
237 priv = (struct darwin_device_handle_priv *)handle->os_priv;
239 message = MESSAGE_DEVICE_GONE;
240 write (priv->fds[1], &message, sizeof (message));
244 pthread_mutex_unlock(&ctx->open_devs_lock);
248 static void darwin_clear_iterator (io_iterator_t iter) {
251 while ((device = IOIteratorNext (iter)) != 0)
252 IOObjectRelease (device);
255 static void *event_thread_main (void *arg0) {
257 struct libusb_context *ctx = (struct libusb_context *)arg0;
259 /* hotplug (device removal) source */
260 CFRunLoopSourceRef libusb_notification_cfsource;
261 io_notification_port_t libusb_notification_port;
262 io_iterator_t libusb_rem_device_iterator;
264 _usbi_log (ctx, LOG_LEVEL_INFO, "creating hotplug event source");
266 CFRetain (CFRunLoopGetCurrent ());
268 /* add the notification port to the run loop */
269 libusb_notification_port = IONotificationPortCreate (libusb_darwin_mp);
270 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
271 CFRunLoopAddSource(CFRunLoopGetCurrent (), libusb_notification_cfsource, kCFRunLoopDefaultMode);
273 /* create notifications for removed devices */
274 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
275 IOServiceMatching(kIOUSBDeviceClassName),
276 (IOServiceMatchingCallback)darwin_devices_detached,
277 (void *)ctx, &libusb_rem_device_iterator);
279 if (kresult != kIOReturnSuccess) {
280 _usbi_log (ctx, LOG_LEVEL_ERROR, "could not add hotplug event source: %s", darwin_error_str (kresult));
282 pthread_exit ((void *)kresult);
286 darwin_clear_iterator (libusb_rem_device_iterator);
288 /* let the main thread know about the async runloop */
289 libusb_darwin_acfl = CFRunLoopGetCurrent ();
291 _usbi_log (ctx, LOG_LEVEL_INFO, "libopenusb/darwin.c event_thread_main: thread ready to receive events");
293 /* run the runloop */
296 _usbi_log (ctx, LOG_LEVEL_INFO, "libopenusb/darwin.c event_thread_main: thread exiting");
298 /* delete notification port */
299 CFRunLoopSourceInvalidate (libusb_notification_cfsource);
300 IONotificationPortDestroy (libusb_notification_port);
302 CFRelease (CFRunLoopGetCurrent ());
304 libusb_darwin_acfl = NULL;
309 static int darwin_init(struct libusb_context *ctx) {
312 /* Create the master port for talking to IOKit */
313 if (!libusb_darwin_mp) {
314 kresult = IOMasterPort (MACH_PORT_NULL, &libusb_darwin_mp);
316 if (kresult != kIOReturnSuccess || !libusb_darwin_mp)
317 return darwin_to_libusb (kresult);
320 pthread_create (&libusb_darwin_at, NULL, event_thread_main, (void *)ctx);
322 while (!libusb_darwin_acfl)
328 static void darwin_exit (void) {
331 /* stop the async runloop */
332 CFRunLoopStop (libusb_darwin_acfl);
333 pthread_join (libusb_darwin_at, &ret);
335 if (libusb_darwin_mp)
336 mach_port_deallocate(mach_task_self(), libusb_darwin_mp);
338 libusb_darwin_mp = 0;
341 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
342 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
344 /* return cached copy */
345 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
352 static int get_configuration_index (struct libusb_device *dev, int config_value) {
353 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
355 IOUSBConfigurationDescriptorPtr desc;
358 /* is there a simpler way to determine the index? */
359 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
360 if (kresult != kIOReturnSuccess)
361 return darwin_to_libusb (kresult);
363 for (i = 0 ; i < numConfig ; i++) {
364 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
366 if (libusb_le16_to_cpu (desc->bConfigurationValue) == config_value)
370 /* configuration not found */
371 return LIBUSB_ERROR_OTHER;
374 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
375 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
380 kresult = (*(priv->device))->GetConfiguration (priv->device, &config_value);
381 if (kresult != kIOReturnSuccess)
382 return darwin_to_libusb (kresult);
384 config_index = get_configuration_index (dev, config_value);
385 if (config_index < 0)
388 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
391 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
392 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
393 IOUSBConfigurationDescriptorPtr desc;
395 usb_device_t **device = NULL;
398 return LIBUSB_ERROR_OTHER;
401 kresult = darwin_get_device (priv->location, &device);
402 if (kresult || !device) {
403 _usbi_log (DEVICE_CTX (dev), LOG_LEVEL_ERROR, "could not find device: %s", darwin_error_str (kresult));
405 return darwin_to_libusb (kresult);
408 /* don't have to open the device to get a config descriptor */
410 device = priv->device;
412 kresult = (*device)->GetConfigurationDescriptorPtr (device, config_index, &desc);
413 if (kresult == kIOReturnSuccess) {
414 /* copy descriptor */
415 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
416 len = libusb_le16_to_cpu(desc->wTotalLength);
418 memmove (buffer, desc, len);
420 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
425 (*device)->Release (device);
427 return darwin_to_libusb (kresult);
430 static int process_new_device (struct libusb_context *ctx, usb_device_t **device, UInt32 locationID, struct discovered_devs **_discdevs) {
431 struct darwin_device_priv *priv;
432 struct libusb_device *dev;
433 struct discovered_devs *discdevs;
434 UInt16 address, idVendor, idProduct;
435 UInt8 bDeviceClass, bDeviceSubClass;
439 dev = usbi_get_device_by_session_id(ctx, locationID);
441 _usbi_log (ctx, LOG_LEVEL_INFO, "allocating new device for location 0x%08x", locationID);
442 dev = usbi_alloc_device(ctx, locationID);
444 return LIBUSB_ERROR_NO_MEM;
446 priv = (struct darwin_device_priv *)dev->os_priv;
448 /* Set up request for device descriptor */
449 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
450 req.bRequest = kUSBRqGetDescriptor;
451 req.wValue = kUSBDeviceDesc << 8;
453 req.wLength = sizeof(IOUSBDeviceDescriptor);
454 req.pData = &(priv->dev_descriptor);
456 (*(device))->GetDeviceAddress (device, (USBDeviceAddress *)&address);
457 (*(device))->GetDeviceProduct (device, &idProduct);
458 (*(device))->GetDeviceVendor (device, &idVendor);
459 (*(device))->GetDeviceClass (device, &bDeviceClass);
460 (*(device))->GetDeviceSubClass (device, &bDeviceSubClass);
462 /**** retrieve device descriptors ****/
463 /* device must be open for DeviceRequest */
464 (*device)->USBDeviceOpen(device);
466 ret = (*(device))->DeviceRequest (device, &req);
467 if (ret != kIOReturnSuccess) {
468 int try_unsuspend = 1;
469 #if DeviceVersion >= 320
472 /* device may be suspended. unsuspend it and try again */
473 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
474 (void)(*device)->GetUSBDeviceInformation (device, &info);
476 try_unsuspend = info & (1 << kUSBInformationDeviceIsSuspendedBit);
480 /* resume the device */
481 (void)(*device)->USBDeviceSuspend (device, 0);
483 ret = (*(device))->DeviceRequest (device, &req);
485 /* resuspend the device */
486 (void)(*device)->USBDeviceSuspend (device, 1);
490 (*device)->USBDeviceClose (device);
492 if (ret != kIOReturnSuccess) {
493 _usbi_log (ctx, LOG_LEVEL_WARNING, "could not retrieve device descriptor: %s. skipping device", darwin_error_str (ret));
494 libusb_unref_device(dev);
497 /**** end: retrieve device descriptors ****/
499 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
500 if (libusb_le16_to_cpu (priv->dev_descriptor.idProduct) != idProduct) {
501 /* not a valid device */
502 _usbi_log (ctx, LOG_LEVEL_WARNING, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
503 idProduct, libusb_le16_to_cpu (priv->dev_descriptor.idProduct));
504 libusb_unref_device(dev);
508 dev->bus_number = locationID >> 24;
509 dev->device_address = address;
511 /* save our location, we'll need this later */
512 priv->location = locationID;
513 snprintf(priv->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", address, idVendor, idProduct, bDeviceClass, bDeviceSubClass);
515 ret = usbi_sanitize_device(dev);
518 libusb_unref_device(dev);
522 priv = (struct darwin_device_priv *)dev->os_priv;
524 _usbi_log (ctx, LOG_LEVEL_INFO, "using existing device for location 0x%08x", locationID);
527 /* append the device to the list of discovered devices */
528 discdevs = discovered_devs_append(*_discdevs, dev);
530 return LIBUSB_ERROR_NO_MEM;
532 *_discdevs = discdevs;
534 _usbi_log (ctx, LOG_LEVEL_INFO, "found device with address %d at %s", dev->device_address, priv->sys_path);
539 static int darwin_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs) {
540 io_iterator_t deviceIterator;
541 usb_device_t **device;
542 kern_return_t kresult;
545 if (!libusb_darwin_mp)
546 return LIBUSB_ERROR_INVALID_PARAM;
548 kresult = usb_setup_device_iterator (&deviceIterator);
549 if (kresult != kIOReturnSuccess)
550 return darwin_to_libusb (kresult);
552 while ((device = usb_get_next_device (deviceIterator, &location)) != NULL) {
553 (void) process_new_device (ctx, device, location, _discdevs);
555 (*(device))->Release(device);
558 IOObjectRelease(deviceIterator);
563 static int darwin_open (struct libusb_device_handle *dev_handle) {
564 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
565 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
566 usb_device_t **darwin_device;
569 if (0 == dpriv->open_count) {
570 kresult = darwin_get_device (dpriv->location, &darwin_device);
572 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "could not find device: %s", darwin_error_str (kresult));
573 return darwin_to_libusb (kresult);
576 dpriv->device = darwin_device;
578 /* try to open the device */
579 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
581 if (kresult != kIOReturnSuccess) {
582 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "USBDeviceOpen: %s", darwin_error_str(kresult));
585 case kIOReturnExclusiveAccess:
586 /* it is possible to perform some actions on a device that is not open so do not return an error */
591 (*(dpriv->device))->Release (dpriv->device);
592 dpriv->device = NULL;
593 return darwin_to_libusb (kresult);
598 /* create async event source */
599 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
601 CFRetain (libusb_darwin_acfl);
603 /* add the cfSource to the aync run loop */
604 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
608 /* device opened successfully */
611 /* create a file descriptor for notifications */
614 /* set the pipe to be non-blocking */
615 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
617 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
619 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "device open for access");
624 static void darwin_close (struct libusb_device_handle *dev_handle) {
625 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
626 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
630 if (dpriv->open_count == 0) {
631 /* something is probably very wrong if this is the case */
632 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "Close called on a device that was not open!\n");
638 /* make sure all interfaces are released */
639 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
640 if (dev_handle->claimed_interfaces & (1 << i))
641 libusb_release_interface (dev_handle, i);
643 if (0 == dpriv->open_count) {
645 /* delete the device's async event source */
646 if (priv->cfSource) {
647 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
648 CFRelease (priv->cfSource);
651 /* close the device */
652 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
654 /* Log the fact that we had a problem closing the file, however failing a
655 * close isn't really an error, so return success anyway */
656 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "USBDeviceClose: %s", darwin_error_str(kresult));
660 kresult = (*(dpriv->device))->Release(dpriv->device);
662 /* Log the fact that we had a problem closing the file, however failing a
663 * close isn't really an error, so return success anyway */
664 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "Release: %s", darwin_error_str(kresult));
667 dpriv->device = NULL;
670 /* file descriptors are maintained per-instance */
671 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
672 close (priv->fds[1]);
673 close (priv->fds[0]);
675 priv->fds[0] = priv->fds[1] = -1;
678 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
679 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
683 kresult = (*(dpriv->device))->GetConfiguration (dpriv->device, &configNum);
684 if (kresult != kIOReturnSuccess)
685 return darwin_to_libusb (kresult);
687 *config = (int) configNum;
692 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
693 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
697 /* Setting configuration will invalidate the interface, so we need
698 to reclaim it. First, dispose of existing interfaces, if any. */
699 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
700 if (dev_handle->claimed_interfaces & (1 << i))
701 darwin_release_interface (dev_handle, i);
703 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
704 if (kresult != kIOReturnSuccess)
705 return darwin_to_libusb (kresult);
707 /* Reclaim any interfaces. */
708 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
709 if (dev_handle->claimed_interfaces & (1 << i))
710 darwin_claim_interface (dev_handle, i);
715 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
716 IOUSBFindInterfaceRequest request;
717 uint8_t current_interface;
718 kern_return_t kresult;
719 io_iterator_t interface_iterator;
721 *usbInterfacep = IO_OBJECT_NULL;
723 /* Setup the Interface Request */
724 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
725 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
726 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
727 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
729 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
733 for ( current_interface = 0 ; current_interface <= ifc ; current_interface++ )
734 *usbInterfacep = IOIteratorNext(interface_iterator);
736 /* done with the interface iterator */
737 IOObjectRelease(interface_iterator);
742 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
743 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
745 /* current interface */
746 struct __darwin_interface *cInterface = &priv->interfaces[iface];
748 kern_return_t kresult;
750 u_int8_t numep, direction, number;
751 u_int8_t dont_care1, dont_care3;
752 u_int16_t dont_care2;
755 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "building table of endpoints.");
757 /* retrieve the total number of endpoints on this interface */
758 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
760 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
761 return darwin_to_libusb (kresult);
764 /* iterate through pipe references */
765 for (i = 1 ; i <= numep ; i++) {
766 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
767 &dont_care2, &dont_care3);
769 if (kresult != kIOReturnSuccess) {
770 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
772 return darwin_to_libusb (kresult);
775 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
777 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
780 cInterface->num_endpoints = numep;
785 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
786 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
787 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
788 io_service_t usbInterface = IO_OBJECT_NULL;
790 IOCFPlugInInterface **plugInInterface = NULL;
794 /* current interface */
795 struct __darwin_interface *cInterface = &priv->interfaces[iface];
797 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
798 if (kresult != kIOReturnSuccess)
799 return darwin_to_libusb (kresult);
801 /* make sure we have an interface */
803 u_int8_t nConfig; /* Index of configuration to use */
804 IOUSBConfigurationDescriptorPtr configDesc; /* to describe which configuration to select */
805 /* Only a composite class device with no vendor-specific driver will
806 be configured. Otherwise, we need to do it ourselves, or there
807 will be no interfaces for the device. */
809 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "no interface found; selecting configuration" );
811 kresult = (*(dpriv->device))->GetNumberOfConfigurations (dpriv->device, &nConfig);
812 if (kresult != kIOReturnSuccess) {
813 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "GetNumberOfConfigurations: %s", darwin_error_str(kresult));
814 return darwin_to_libusb(kresult);
818 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "GetNumberOfConfigurations: no configurations");
819 return LIBUSB_ERROR_OTHER;
822 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "device has %d configuration%s. using the first",
823 (int)nConfig, (nConfig > 1 ? "s" : "") );
825 /* Always use the first configuration */
826 kresult = (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, 0, &configDesc);
827 if (kresult != kIOReturnSuccess) {
828 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "GetConfigurationDescriptorPtr: %s",
829 darwin_error_str(kresult));
833 new_config = configDesc->bConfigurationValue;
835 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "new configuration value is %d", new_config);
837 /* set the configuration */
838 kresult = darwin_set_configuration (dev_handle, new_config);
839 if (kresult != LIBUSB_SUCCESS) {
840 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "could not set configuration");
844 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
846 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "darwin_get_interface: %s", darwin_error_str(kresult));
847 return darwin_to_libusb (kresult);
852 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "interface not found");
853 return LIBUSB_ERROR_NOT_FOUND;
856 /* get an interface to the device's interface */
857 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
858 kIOCFPlugInInterfaceID, &plugInInterface, &score);
860 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
861 return darwin_to_libusb (kresult);
864 if (!plugInInterface) {
865 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "plugin interface not found");
866 return LIBUSB_ERROR_NOT_FOUND;
869 /* ignore release error */
870 (void)IOObjectRelease (usbInterface);
872 /* Do the actual claim */
873 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
874 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
875 (LPVOID)&cInterface->interface);
876 if (kresult || !cInterface->interface) {
877 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "QueryInterface: %s", darwin_error_str(kresult));
878 return darwin_to_libusb (kresult);
881 /* We no longer need the intermediate plug-in */
882 (*plugInInterface)->Release(plugInInterface);
884 /* claim the interface */
885 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
887 _usbi_log(HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "USBInterfaceOpen: %s", darwin_error_str(kresult));
888 return darwin_to_libusb (kresult);
891 /* update list of endpoints */
892 kresult = get_endpoints (dev_handle, iface);
894 /* this should not happen */
895 darwin_release_interface (dev_handle, iface);
896 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "could not build endpoint table");
900 cInterface->cfSource = NULL;
902 /* create async event source */
903 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
904 if (kresult != kIOReturnSuccess) {
905 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "could not create async event source");
907 /* can't continue without an async event source */
908 (void)darwin_release_interface (dev_handle, iface);
910 return darwin_to_libusb (kresult);
913 /* add the cfSource to the async thread's run loop */
914 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
916 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "interface opened");
921 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
922 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
925 /* current interface */
926 struct __darwin_interface *cInterface = &priv->interfaces[iface];
928 /* Check to see if an interface is open */
929 if (!cInterface->interface)
930 return LIBUSB_SUCCESS;
932 /* clean up endpoint data */
933 cInterface->num_endpoints = 0;
935 /* delete the interface's async event source */
936 if (cInterface->cfSource) {
937 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
938 CFRelease (cInterface->cfSource);
941 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
943 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "USBInterfaceClose: %s", darwin_error_str(kresult));
945 kresult = (*(cInterface->interface))->Release(cInterface->interface);
946 if (kresult != kIOReturnSuccess)
947 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "Release: %s", darwin_error_str(kresult));
949 cInterface->interface = IO_OBJECT_NULL;
951 return darwin_to_libusb (kresult);
954 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
955 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
958 /* current interface */
959 struct __darwin_interface *cInterface = &priv->interfaces[iface];
961 if (!cInterface->interface)
962 return LIBUSB_ERROR_NO_DEVICE;
964 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
965 if (kresult != kIOReturnSuccess)
966 darwin_reset_device (dev_handle);
968 /* update list of endpoints */
969 kresult = get_endpoints (dev_handle, iface);
971 /* this should not happen */
972 darwin_release_interface (dev_handle, iface);
973 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "could not build endpoint table");
977 return darwin_to_libusb (kresult);
980 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
981 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
983 /* current interface */
984 struct __darwin_interface *cInterface;
985 uint8_t pipeRef, iface;
988 /* determine the interface/endpoint to use */
989 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
990 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
992 return LIBUSB_ERROR_NOT_FOUND;
995 cInterface = &priv->interfaces[iface];
997 #if (InterfaceVersion < 190)
998 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1000 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1001 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1004 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "ClearPipeStall: %s", darwin_error_str (kresult));
1006 return darwin_to_libusb (kresult);
1009 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1010 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1013 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1015 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "ResetDevice: %s", darwin_error_str (kresult));
1017 return darwin_to_libusb (kresult);
1020 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1021 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1022 io_service_t usbInterface;
1026 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1028 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "darwin_get_interface: %s", darwin_error_str(kresult));
1030 return darwin_to_libusb (kresult);
1033 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1034 IOObjectRelease (usbInterface);
1046 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1047 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1048 return LIBUSB_ERROR_NOT_SUPPORTED;
1051 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1052 return LIBUSB_ERROR_NOT_SUPPORTED;
1055 static void darwin_destroy_device(struct libusb_device *dev) {
1058 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1059 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1060 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1063 uint8_t is_read; /* 0 = we're reading, 1 = we're writing */
1064 uint8_t transferType;
1065 /* None of the values below are used in libusb for bulk transfers */
1066 uint8_t direction, number, interval, pipeRef, iface;
1067 uint16_t maxPacketSize;
1069 struct __darwin_interface *cInterface;
1071 /* are we reading or writing? */
1072 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1074 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1075 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
1077 return LIBUSB_ERROR_NOT_FOUND;
1080 cInterface = &priv->interfaces[iface];
1082 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1083 &transferType, &maxPacketSize, &interval);
1085 /* submit the request */
1086 /* timeouts are unavailable on interrupt endpoints */
1087 if (transferType == kUSBInterrupt) {
1089 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1090 transfer->length, darwin_async_io_callback, itransfer);
1092 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1093 transfer->length, darwin_async_io_callback, itransfer);
1096 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1097 transfer->length, transfer->timeout, transfer->timeout,
1098 darwin_async_io_callback, (void *)itransfer);
1100 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1101 transfer->length, transfer->timeout, transfer->timeout,
1102 darwin_async_io_callback, (void *)itransfer);
1106 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "bulk transfer failed (dir = %s): %s", is_read ? "In" : "Out",
1107 darwin_error_str(ret));
1109 return darwin_to_libusb (ret);
1112 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1113 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1114 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1115 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1118 uint8_t is_read; /* 0 = we're writing, 1 = we're reading */
1119 uint8_t pipeRef, iface;
1121 AbsoluteTime atTime;
1124 struct __darwin_interface *cInterface;
1126 /* are we reading or writing? */
1127 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1129 /* construct an array of IOUSBIsocFrames */
1130 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1131 if (!tpriv->isoc_framelist)
1132 return LIBUSB_ERROR_NO_MEM;
1134 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1135 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1136 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1138 /* determine the interface/endpoint to use */
1139 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1140 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
1142 return LIBUSB_ERROR_NOT_FOUND;
1145 cInterface = &priv->interfaces[iface];
1147 /* Last but not least we need the bus frame number */
1148 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1150 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "failed to get bus frame number: %d", kresult);
1151 free(tpriv->isoc_framelist);
1152 tpriv->isoc_framelist = NULL;
1154 return darwin_to_libusb (kresult);
1157 /* schedule for a frame a little in the future */
1160 /* submit the request */
1162 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1163 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1166 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1167 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1170 if (kresult != kIOReturnSuccess) {
1171 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "isochronous transfer failed (dir: %s): %s", is_read ? "In" : "Out",
1172 darwin_error_str(kresult));
1173 free (tpriv->isoc_framelist);
1174 tpriv->isoc_framelist = NULL;
1177 return darwin_to_libusb (kresult);
1180 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1181 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1182 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1183 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1184 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1188 bzero(&tpriv->req, sizeof(tpriv->req));
1190 /* IOUSBDeviceInterface expects the request in cpu endianess */
1191 tpriv->req.bmRequestType = setup->bmRequestType;
1192 tpriv->req.bRequest = setup->bRequest;
1193 /* these values should already be in bus order */
1194 tpriv->req.wValue = setup->wValue;
1195 tpriv->req.wIndex = setup->wIndex;
1196 tpriv->req.wLength = setup->wLength;
1197 /* data is stored after the libusb control block */
1198 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1199 tpriv->req.completionTimeout = transfer->timeout;
1200 tpriv->req.noDataTimeout = transfer->timeout;
1202 /* all transfers in libusb-1.0 are async */
1203 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1205 if (kresult != kIOReturnSuccess)
1206 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "control request failed: %s", darwin_error_str(kresult));
1208 return darwin_to_libusb (kresult);
1211 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1212 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1214 switch (transfer->type) {
1215 case LIBUSB_TRANSFER_TYPE_CONTROL:
1216 return submit_control_transfer(itransfer);
1217 case LIBUSB_TRANSFER_TYPE_BULK:
1218 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1219 return submit_bulk_transfer(itransfer);
1220 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1221 return submit_iso_transfer(itransfer);
1223 _usbi_log (TRANSFER_CTX(transfer), LOG_LEVEL_ERROR, "unknown endpoint type %d", transfer->type);
1224 return LIBUSB_ERROR_INVALID_PARAM;
1228 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1229 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1230 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1233 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "WARNING: aborting all transactions control pipe");
1235 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1237 return darwin_to_libusb (kresult);
1240 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1241 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1242 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1243 struct __darwin_interface *cInterface;
1244 uint8_t pipeRef, iface;
1247 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1248 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
1250 return LIBUSB_ERROR_NOT_FOUND;
1253 cInterface = &priv->interfaces[iface];
1255 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "WARNING: aborting all transactions on interface %d pipe %d", iface, pipeRef);
1257 /* abort transactions */
1258 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1260 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "calling clear pipe stall to clear the data toggle bit");
1262 /* clear the data toggle bit */
1263 #if (InterfaceVersion < 190)
1264 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1266 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1267 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1270 return darwin_to_libusb (kresult);
1273 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1274 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1276 switch (transfer->type) {
1277 case LIBUSB_TRANSFER_TYPE_CONTROL:
1278 return cancel_control_transfer(itransfer);
1279 case LIBUSB_TRANSFER_TYPE_BULK:
1280 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1281 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1282 return darwin_abort_transfers (itransfer);
1284 _usbi_log (TRANSFER_CTX(transfer), LOG_LEVEL_ERROR, "unknown endpoint type %d", transfer->type);
1285 return LIBUSB_ERROR_INVALID_PARAM;
1289 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1290 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1291 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1293 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1294 free (tpriv->isoc_framelist);
1295 tpriv->isoc_framelist = NULL;
1299 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1300 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1301 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1302 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1305 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "an async io operation has completed");
1307 /* send a completion message to the device's file descriptor */
1308 message = MESSAGE_ASYNC_IO_COMPLETE;
1309 write (priv->fds[1], &message, sizeof (message));
1310 write (priv->fds[1], &itransfer, sizeof (itransfer));
1311 write (priv->fds[1], &result, sizeof (IOReturn));
1312 write (priv->fds[1], &arg0, sizeof (UInt32));
1315 static void darwin_bulk_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1316 enum libusb_transfer_status status;
1318 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "handling bulk completion with status %d", result);
1321 case kIOReturnSuccess:
1322 status = LIBUSB_TRANSFER_COMPLETED;
1323 itransfer->transferred += io_size;
1325 case kIOReturnAborted:
1326 usbi_handle_transfer_cancellation(itransfer);
1328 case kIOUSBPipeStalled:
1329 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_WARNING, "bulk error. pipe is stalled");
1330 status = LIBUSB_TRANSFER_STALL;
1333 case kIOReturnOverrun:
1334 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_ERROR, "bulk error. data overrun", darwin_error_str (result));
1335 status = LIBUSB_TRANSFER_OVERFLOW;
1339 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_ERROR, "bulk error = %s (value = 0x%08x)", darwin_error_str (result), result);
1340 status = LIBUSB_TRANSFER_ERROR;
1343 usbi_handle_transfer_completion(itransfer, status);
1346 static void darwin_isoc_callback (struct usbi_transfer *itransfer, kern_return_t result) {
1347 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1348 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1351 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "handling isoc completion with status %d", result);
1353 if (result == kIOReturnSuccess && tpriv->isoc_framelist) {
1354 /* copy isochronous results back */
1356 for (i = 0; i < transfer->num_iso_packets ; i++) {
1357 struct libusb_iso_packet_descriptor *lib_desc = transfer->iso_packet_desc;
1358 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1359 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1364 case kIOReturnSuccess:
1365 status = LIBUSB_TRANSFER_COMPLETED;
1367 case kIOReturnAborted:
1368 usbi_handle_transfer_cancellation(itransfer);
1370 case kIOUSBPipeStalled:
1371 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_WARNING, "unsupported control request");
1372 status = LIBUSB_TRANSFER_STALL;
1375 case kIOReturnOverrun:
1376 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_ERROR, "bulk error. data overrun", darwin_error_str (result));
1377 status = LIBUSB_TRANSFER_OVERFLOW;
1381 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_ERROR, "control error = %s", darwin_error_str (result));
1382 status = LIBUSB_TRANSFER_ERROR;
1385 usbi_handle_transfer_completion(itransfer, status);
1388 static void darwin_control_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1391 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "handling control completion with status %d", result);
1394 case kIOReturnSuccess:
1395 status = LIBUSB_TRANSFER_COMPLETED;
1396 itransfer->transferred += io_size;
1398 case kIOReturnAborted:
1399 usbi_handle_transfer_cancellation(itransfer);
1401 case kIOUSBPipeStalled:
1402 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_WARNING, "unsupported control request");
1403 status = LIBUSB_TRANSFER_STALL;
1407 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_ERROR, "control error = %s", darwin_error_str (result));
1408 status = LIBUSB_TRANSFER_ERROR;
1411 usbi_handle_transfer_completion(itransfer, status);
1414 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1415 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1417 switch (transfer->type) {
1418 case LIBUSB_TRANSFER_TYPE_CONTROL:
1419 darwin_control_callback (itransfer, result, io_size);
1421 case LIBUSB_TRANSFER_TYPE_BULK:
1422 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1423 darwin_bulk_callback (itransfer, result, io_size);
1425 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1426 darwin_isoc_callback (itransfer, result);
1429 _usbi_log (TRANSFER_CTX(transfer), LOG_LEVEL_ERROR, "unknown endpoint type %d", transfer->type);
1433 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, nfds_t nfds, int num_ready) {
1434 struct usbi_transfer *itransfer;
1440 pthread_mutex_lock(&ctx->open_devs_lock);
1441 for (i = 0; i < nfds && num_ready > 0; i++) {
1442 struct pollfd *pollfd = &fds[i];
1443 struct libusb_device_handle *handle;
1444 struct darwin_device_handle_priv *hpriv = NULL;
1446 _usbi_log (ctx, LOG_LEVEL_INFO, "checking fd %i with revents = %x", fds[i], pollfd->revents);
1448 if (!pollfd->revents)
1452 list_for_each_entry(handle, &ctx->open_devs, list) {
1453 hpriv = (struct darwin_device_handle_priv *)handle->os_priv;
1454 if (hpriv->fds[0] == pollfd->fd)
1458 if (!(pollfd->revents & POLLERR)) {
1459 ret = read (hpriv->fds[0], &message, sizeof (message));
1460 if (ret < sizeof (message))
1463 /* could not poll the device-- response is to delete the device (this seems a little heavy-handed) */
1464 message = MESSAGE_DEVICE_GONE;
1467 case MESSAGE_DEVICE_GONE:
1468 /* remove the device's async port from the runloop */
1469 if (hpriv->cfSource) {
1470 if (libusb_darwin_acfl)
1471 CFRunLoopRemoveSource (libusb_darwin_acfl, hpriv->cfSource, kCFRunLoopDefaultMode);
1472 CFRelease (hpriv->cfSource);
1473 hpriv->cfSource = NULL;
1476 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
1477 usbi_handle_disconnect(handle);
1479 /* done with this device */
1481 case MESSAGE_ASYNC_IO_COMPLETE:
1482 read (hpriv->fds[0], &itransfer, sizeof (itransfer));
1483 read (hpriv->fds[0], &kresult, sizeof (IOReturn));
1484 read (hpriv->fds[0], &io_size, sizeof (UInt32));
1486 darwin_handle_callback (itransfer, kresult, io_size);
1489 _usbi_log (ctx, LOG_LEVEL_ERROR, "unknown message received from device pipe");
1493 pthread_mutex_unlock(&ctx->open_devs_lock);
1498 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1499 mach_timespec_t sys_time;
1500 clock_serv_t clock_ref;
1503 case USBI_CLOCK_REALTIME:
1504 /* CLOCK_REALTIME represents time since the epoch */
1505 host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &clock_ref);
1507 case USBI_CLOCK_MONOTONIC:
1508 /* use system boot time as reference for the monotonic clock */
1509 host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &clock_ref);
1512 return LIBUSB_ERROR_INVALID_PARAM;
1515 clock_get_time (clock_ref, &sys_time);
1517 tp->tv_sec = sys_time.tv_sec;
1518 tp->tv_nsec = sys_time.tv_nsec;
1523 const struct usbi_os_backend darwin_backend = {
1525 .init = darwin_init,
1526 .exit = darwin_exit,
1527 .get_device_list = darwin_get_device_list,
1528 .get_device_descriptor = darwin_get_device_descriptor,
1529 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1530 .get_config_descriptor = darwin_get_config_descriptor,
1532 .open = darwin_open,
1533 .close = darwin_close,
1534 .get_configuration = darwin_get_configuration,
1535 .set_configuration = darwin_set_configuration,
1536 .claim_interface = darwin_claim_interface,
1537 .release_interface = darwin_release_interface,
1539 .set_interface_altsetting = darwin_set_interface_altsetting,
1540 .clear_halt = darwin_clear_halt,
1541 .reset_device = darwin_reset_device,
1543 .kernel_driver_active = darwin_kernel_driver_active,
1544 .detach_kernel_driver = darwin_detach_kernel_driver,
1545 .attach_kernel_driver = darwin_attach_kernel_driver,
1547 .destroy_device = darwin_destroy_device,
1549 .submit_transfer = darwin_submit_transfer,
1550 .cancel_transfer = darwin_cancel_transfer,
1551 .clear_transfer_priv = darwin_clear_transfer_priv,
1553 .handle_events = op_handle_events,
1555 .clock_gettime = darwin_clock_gettime,
1557 .device_priv_size = sizeof(struct darwin_device_priv),
1558 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1559 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1560 .add_iso_packet_size = 0,