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 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";
85 return "unknown error";
89 static int darwin_to_libusb (int result) {
91 case kIOReturnSuccess:
92 return LIBUSB_SUCCESS;
93 case kIOReturnNotOpen:
94 case kIOReturnNoDevice:
95 return LIBUSB_ERROR_NO_DEVICE;
96 case kIOReturnExclusiveAccess:
97 return LIBUSB_ERROR_ACCESS;
98 case kIOUSBPipeStalled:
99 return LIBUSB_ERROR_PIPE;
100 case kIOReturnBadArgument:
101 return LIBUSB_ERROR_INVALID_PARAM;
102 case kIOUSBTransactionTimeout:
103 return LIBUSB_ERROR_TIMEOUT;
104 case kIOReturnNotResponding:
105 case kIOReturnAborted:
107 case kIOUSBNoAsyncPortErr:
109 return LIBUSB_ERROR_OTHER;
114 static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp) {
115 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
117 /* current interface */
118 struct __darwin_interface *cInterface;
122 _usbi_log (HANDLE_CTX(dev_handle), LOG_LEVEL_INFO, "converting ep address 0x%02x to pipeRef and interface", ep);
124 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
125 cInterface = &priv->interfaces[iface];
127 if (dev_handle->claimed_interfaces & (1 << iface)) {
128 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
129 if (cInterface->endpoint_addrs[i] == ep) {
132 _usbi_log (HANDLE_CTX(dev_handle), LOG_LEVEL_INFO, "pipe %d on interface %d matches", *pipep, *ifcp);
139 /* No pipe found with the correct endpoint address */
140 _usbi_log (HANDLE_CTX(dev_handle), LOG_LEVEL_WARNING, "no pipeRef found with endpoint address 0x%02x.", ep);
145 static int usb_setup_device_iterator (io_iterator_t *deviceIterator) {
146 return IOServiceGetMatchingServices(libusb_darwin_mp, IOServiceMatching(kIOUSBDeviceClassName), deviceIterator);
149 static usb_device_t **usb_get_next_device (io_iterator_t deviceIterator, UInt32 *locationp) {
150 io_cf_plugin_ref_t *plugInInterface = NULL;
151 usb_device_t **device;
152 io_service_t usbDevice;
156 if (!IOIteratorIsValid (deviceIterator) || !(usbDevice = IOIteratorNext(deviceIterator)))
159 result = IOCreatePlugInInterfaceForService(usbDevice, kIOUSBDeviceUserClientTypeID,
160 kIOCFPlugInInterfaceID, &plugInInterface,
163 if (result || !plugInInterface) {
164 usbi_dbg ("libusb/darwin.c usb_get_next_device: could not set up plugin for service: %s\n", darwin_error_str (result));
169 (void)IOObjectRelease(usbDevice);
170 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
173 (*plugInInterface)->Stop(plugInInterface);
174 IODestroyPlugInInterface (plugInInterface);
176 (*(device))->GetLocationID(device, locationp);
181 static kern_return_t darwin_get_device (uint32_t dev_location, usb_device_t ***darwin_device) {
182 kern_return_t kresult;
184 io_iterator_t deviceIterator;
186 kresult = usb_setup_device_iterator (&deviceIterator);
190 /* This port of libusb uses locations to keep track of devices. */
191 while ((*darwin_device = usb_get_next_device (deviceIterator, &location)) != NULL) {
192 if (location == dev_location)
195 (**darwin_device)->Release(*darwin_device);
198 IOObjectRelease (deviceIterator);
200 if (!(*darwin_device))
201 return kIOReturnNoDevice;
203 return kIOReturnSuccess;
208 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
209 struct libusb_context *ctx = (struct libusb_context *)ptr;
210 struct libusb_device_handle *handle;
211 struct darwin_device_priv *dpriv;
212 struct darwin_device_handle_priv *priv;
216 CFTypeRef locationCF;
219 _usbi_log (ctx, LOG_LEVEL_INFO, "a device has been detached");
221 while ((device = IOIteratorNext (rem_devices)) != 0) {
222 /* get the location from the i/o registry */
223 locationCF = IORegistryEntryCreateCFProperty (device, CFSTR(kUSBDevicePropertyLocationID), kCFAllocatorDefault, 0);
225 CFNumberGetValue(locationCF, kCFNumberLongType, &location);
226 CFRelease (locationCF);
227 IOObjectRelease (device);
229 pthread_mutex_lock(&ctx->open_devs_lock);
230 list_for_each_entry(handle, &ctx->open_devs, list) {
231 dpriv = (struct darwin_device_priv *)handle->dev->os_priv;
232 if (dpriv->location == location)
236 if (handle && 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));
243 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 kresult = darwin_get_device (dpriv->location, &darwin_device);
571 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "could not find device: %s", darwin_error_str (kresult));
572 return darwin_to_libusb (kresult);
575 dpriv->device = darwin_device;
577 /* try to open the device */
578 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
580 if (kresult != kIOReturnSuccess) {
581 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "USBDeviceOpen: %s", darwin_error_str(kresult));
584 case kIOReturnExclusiveAccess:
585 /* it is possible to perform some actions on a device that is not open so do not return an error */
590 (*(dpriv->device))->Release (dpriv->device);
591 dpriv->device = NULL;
592 return darwin_to_libusb (kresult);
597 /* create async event source */
598 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
600 CFRetain (libusb_darwin_acfl);
602 /* add the cfSource to the aync run loop */
603 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
606 /* create a file descriptor for notifications */
609 /* set the pipe to be non-blocking */
610 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
612 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
614 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "device open for access");
619 static void darwin_close (struct libusb_device_handle *dev_handle) {
620 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
621 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
625 /* make sure all interfaces are released */
626 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
627 if (dev_handle->claimed_interfaces & (1 << i))
628 libusb_release_interface (dev_handle, i);
631 /* delete the device's async event source */
632 if (priv->cfSource) {
633 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
634 CFRelease (priv->cfSource);
637 /* close the device */
638 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
640 /* Log the fact that we had a problem closing the file, however failing a
641 * close isn't really an error, so return success anyway */
642 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "USBDeviceClose: %s", darwin_error_str(kresult));
646 kresult = (*(dpriv->device))->Release(dpriv->device);
648 /* Log the fact that we had a problem closing the file, however failing a
649 * close isn't really an error, so return success anyway */
650 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "Release: %s", darwin_error_str(kresult));
653 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
654 close (priv->fds[1]);
655 close (priv->fds[0]);
657 dpriv->device = NULL;
658 priv->fds[0] = priv->fds[1] = -1;
661 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
662 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
666 kresult = (*(dpriv->device))->GetConfiguration (dpriv->device, &configNum);
667 if (kresult != kIOReturnSuccess)
668 return darwin_to_libusb (kresult);
670 *config = (int) configNum;
675 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
676 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
680 /* Setting configuration will invalidate the interface, so we need
681 to reclaim it. First, dispose of existing interfaces, if any. */
682 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
683 if (dev_handle->claimed_interfaces & (1 << i))
684 darwin_release_interface (dev_handle, i);
686 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
687 if (kresult != kIOReturnSuccess)
688 return darwin_to_libusb (kresult);
690 /* Reclaim any interfaces. */
691 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
692 if (dev_handle->claimed_interfaces & (1 << i))
693 darwin_claim_interface (dev_handle, i);
698 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
699 IOUSBFindInterfaceRequest request;
700 uint8_t current_interface;
701 kern_return_t kresult;
702 io_iterator_t interface_iterator;
704 *usbInterfacep = IO_OBJECT_NULL;
706 /* Setup the Interface Request */
707 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
708 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
709 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
710 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
712 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
716 for ( current_interface = 0 ; current_interface <= ifc ; current_interface++ )
717 *usbInterfacep = IOIteratorNext(interface_iterator);
719 /* done with the interface iterator */
720 IOObjectRelease(interface_iterator);
725 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
726 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
728 /* current interface */
729 struct __darwin_interface *cInterface = &priv->interfaces[iface];
731 kern_return_t kresult;
733 u_int8_t numep, direction, number;
734 u_int8_t dont_care1, dont_care3;
735 u_int16_t dont_care2;
738 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "building table of endpoints.");
740 /* retrieve the total number of endpoints on this interface */
741 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
743 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
744 return darwin_to_libusb (kresult);
747 /* iterate through pipe references */
748 for (i = 1 ; i <= numep ; i++) {
749 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
750 &dont_care2, &dont_care3);
752 if (kresult != kIOReturnSuccess) {
753 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
755 return darwin_to_libusb (kresult);
758 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
760 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
763 cInterface->num_endpoints = numep;
768 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
769 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
770 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
771 io_service_t usbInterface = IO_OBJECT_NULL;
773 IOCFPlugInInterface **plugInInterface = NULL;
777 /* current interface */
778 struct __darwin_interface *cInterface = &priv->interfaces[iface];
780 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
781 if (kresult != kIOReturnSuccess)
782 return darwin_to_libusb (kresult);
784 /* make sure we have an interface */
786 u_int8_t nConfig; /* Index of configuration to use */
787 IOUSBConfigurationDescriptorPtr configDesc; /* to describe which configuration to select */
788 /* Only a composite class device with no vendor-specific driver will
789 be configured. Otherwise, we need to do it ourselves, or there
790 will be no interfaces for the device. */
792 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "no interface found; selecting configuration" );
794 kresult = (*(dpriv->device))->GetNumberOfConfigurations (dpriv->device, &nConfig);
795 if (kresult != kIOReturnSuccess) {
796 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "GetNumberOfConfigurations: %s", darwin_error_str(kresult));
797 return darwin_to_libusb(kresult);
801 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "GetNumberOfConfigurations: no configurations");
802 return LIBUSB_ERROR_OTHER;
805 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "device has %d configuration%s. using the first",
806 (int)nConfig, (nConfig > 1 ? "s" : "") );
808 /* Always use the first configuration */
809 kresult = (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, 0, &configDesc);
810 if (kresult != kIOReturnSuccess) {
811 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "GetConfigurationDescriptorPtr: %s",
812 darwin_error_str(kresult));
816 new_config = configDesc->bConfigurationValue;
818 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "new configuration value is %d", new_config);
820 /* set the configuration */
821 kresult = darwin_set_configuration (dev_handle, new_config);
822 if (kresult != LIBUSB_SUCCESS) {
823 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "could not set configuration");
827 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
829 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "darwin_get_interface: %s", darwin_error_str(kresult));
830 return darwin_to_libusb (kresult);
835 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "interface not found");
836 return LIBUSB_ERROR_NOT_FOUND;
839 /* get an interface to the device's interface */
840 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
841 kIOCFPlugInInterfaceID, &plugInInterface, &score);
843 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
844 return darwin_to_libusb (kresult);
847 if (!plugInInterface) {
848 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "plugin interface not found");
849 return LIBUSB_ERROR_NOT_FOUND;
852 /* ignore release error */
853 (void)IOObjectRelease (usbInterface);
855 /* Do the actual claim */
856 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
857 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
858 (LPVOID)&cInterface->interface);
859 if (kresult || !cInterface->interface) {
860 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "QueryInterface: %s", darwin_error_str(kresult));
861 return darwin_to_libusb (kresult);
864 /* We no longer need the intermediate plug-in */
865 (*plugInInterface)->Release(plugInInterface);
867 /* claim the interface */
868 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
870 _usbi_log(HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "USBInterfaceOpen: %s", darwin_error_str(kresult));
871 return darwin_to_libusb (kresult);
874 /* update list of endpoints */
875 kresult = get_endpoints (dev_handle, iface);
877 /* this should not happen */
878 darwin_release_interface (dev_handle, iface);
879 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "could not build endpoint table");
883 cInterface->cfSource = NULL;
885 /* create async event source */
886 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
887 if (kresult != kIOReturnSuccess) {
888 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "could not create async event source");
890 /* can't continue without an async event source */
891 (void)darwin_release_interface (dev_handle, iface);
893 return darwin_to_libusb (kresult);
896 /* add the cfSource to the async thread's run loop */
897 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
899 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "interface opened");
904 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
905 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
908 /* current interface */
909 struct __darwin_interface *cInterface = &priv->interfaces[iface];
911 /* Check to see if an interface is open */
912 if (!cInterface->interface)
913 return LIBUSB_SUCCESS;
915 /* clean up endpoint data */
916 cInterface->num_endpoints = 0;
918 /* delete the interface's async event source */
919 if (cInterface->cfSource) {
920 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
921 CFRelease (cInterface->cfSource);
924 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
926 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "USBInterfaceClose: %s", darwin_error_str(kresult));
928 kresult = (*(cInterface->interface))->Release(cInterface->interface);
929 if (kresult != kIOReturnSuccess)
930 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "Release: %s", darwin_error_str(kresult));
932 cInterface->interface = IO_OBJECT_NULL;
934 return darwin_to_libusb (kresult);
937 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
938 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
941 /* current interface */
942 struct __darwin_interface *cInterface = &priv->interfaces[iface];
944 if (!cInterface->interface)
945 return LIBUSB_ERROR_NO_DEVICE;
947 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
948 if (kresult != kIOReturnSuccess)
949 darwin_reset_device (dev_handle);
951 return darwin_to_libusb (kresult);
954 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
955 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
957 /* current interface */
958 struct __darwin_interface *cInterface;
959 uint8_t pipeRef, iface;
962 /* determine the interface/endpoint to use */
963 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
964 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
966 return LIBUSB_ERROR_NOT_FOUND;
969 cInterface = &priv->interfaces[iface];
971 #if (InterfaceVersion < 190)
972 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
974 /* newer versions of darwin support clearing additional bits on the device's endpoint */
975 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
978 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "ClearPipeStall: %s", darwin_error_str (kresult));
980 return darwin_to_libusb (kresult);
983 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
984 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
987 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
989 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "ResetDevice: %s", darwin_error_str (kresult));
991 return darwin_to_libusb (kresult);
994 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
995 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
996 io_service_t usbInterface;
1000 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1002 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "darwin_get_interface: %s", darwin_error_str(kresult));
1004 return darwin_to_libusb (kresult);
1007 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1008 IOObjectRelease (usbInterface);
1020 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1021 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1022 return LIBUSB_ERROR_NOT_SUPPORTED;
1025 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1026 return LIBUSB_ERROR_NOT_SUPPORTED;
1029 static void darwin_destroy_device(struct libusb_device *dev) {
1032 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1033 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1034 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1037 uint8_t is_read; /* 0 = we're reading, 1 = we're writing */
1038 uint8_t transferType;
1039 /* None of the values below are used in libusb for bulk transfers */
1040 uint8_t direction, number, interval, pipeRef, iface;
1041 uint16_t maxPacketSize;
1043 struct __darwin_interface *cInterface;
1045 /* are we reading or writing? */
1046 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1048 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1049 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
1051 return LIBUSB_ERROR_NOT_FOUND;
1054 cInterface = &priv->interfaces[iface];
1056 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1057 &transferType, &maxPacketSize, &interval);
1059 /* submit the request */
1060 /* timeouts are unavailable on interrupt endpoints */
1061 if (transferType == kUSBInterrupt) {
1063 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1064 transfer->length, darwin_async_io_callback, itransfer);
1066 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1067 transfer->length, darwin_async_io_callback, itransfer);
1070 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1071 transfer->length, transfer->timeout, transfer->timeout,
1072 darwin_async_io_callback, (void *)itransfer);
1074 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1075 transfer->length, transfer->timeout, transfer->timeout,
1076 darwin_async_io_callback, (void *)itransfer);
1080 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "bulk transfer failed (dir = %s): %s", is_read ? "In" : "Out",
1081 darwin_error_str(ret));
1083 return darwin_to_libusb (ret);
1086 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1087 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1088 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1089 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1092 uint8_t is_read; /* 0 = we're writing, 1 = we're reading */
1093 uint8_t pipeRef, iface;
1095 AbsoluteTime atTime;
1098 struct __darwin_interface *cInterface;
1100 /* are we reading or writing? */
1101 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1103 /* construct an array of IOUSBIsocFrames */
1104 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1105 if (!tpriv->isoc_framelist)
1106 return LIBUSB_ERROR_NO_MEM;
1108 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1109 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1110 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1112 /* determine the interface/endpoint to use */
1113 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1114 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
1116 return LIBUSB_ERROR_NOT_FOUND;
1119 cInterface = &priv->interfaces[iface];
1121 /* Last but not least we need the bus frame number */
1122 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1124 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "failed to get bus frame number: %d", kresult);
1125 free(tpriv->isoc_framelist);
1126 tpriv->isoc_framelist = NULL;
1128 return darwin_to_libusb (kresult);
1131 /* schedule for a frame a little in the future */
1134 /* submit the request */
1136 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1137 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1140 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1141 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1144 if (kresult != kIOReturnSuccess) {
1145 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "isochronous transfer failed (dir: %s): %s", is_read ? "In" : "Out",
1146 darwin_error_str(kresult));
1147 free (tpriv->isoc_framelist);
1148 tpriv->isoc_framelist = NULL;
1151 return darwin_to_libusb (kresult);
1154 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1155 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1156 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1157 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1158 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1162 bzero(&tpriv->req, sizeof(tpriv->req));
1164 /* IOUSBDeviceInterface expects the request in cpu endianess */
1165 tpriv->req.bmRequestType = setup->bmRequestType;
1166 tpriv->req.bRequest = setup->bRequest;
1167 /* these values should already be in bus order */
1168 tpriv->req.wValue = setup->wValue;
1169 tpriv->req.wIndex = setup->wIndex;
1170 tpriv->req.wLength = setup->wLength;
1171 /* data is stored after the libusb control block */
1172 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1173 tpriv->req.completionTimeout = transfer->timeout;
1174 tpriv->req.noDataTimeout = transfer->timeout;
1176 /* all transfers in libusb-1.0 are async */
1177 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1179 if (kresult != kIOReturnSuccess)
1180 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "control request failed: %s", darwin_error_str(kresult));
1182 return darwin_to_libusb (kresult);
1185 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1186 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1188 switch (transfer->type) {
1189 case LIBUSB_TRANSFER_TYPE_CONTROL:
1190 return submit_control_transfer(itransfer);
1191 case LIBUSB_TRANSFER_TYPE_BULK:
1192 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1193 return submit_bulk_transfer(itransfer);
1194 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1195 return submit_iso_transfer(itransfer);
1197 _usbi_log (TRANSFER_CTX(transfer), LOG_LEVEL_ERROR, "unknown endpoint type %d", transfer->type);
1198 return LIBUSB_ERROR_INVALID_PARAM;
1202 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1203 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1204 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1207 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "WARNING: aborting all transactions control pipe");
1209 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1211 return darwin_to_libusb (kresult);
1214 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1215 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1216 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1217 struct __darwin_interface *cInterface;
1218 uint8_t pipeRef, iface;
1221 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1222 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
1224 return LIBUSB_ERROR_NOT_FOUND;
1227 cInterface = &priv->interfaces[iface];
1229 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "WARNING: aborting all transactions on interface %d pipe %d", iface, pipeRef);
1231 /* abort transactions */
1232 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1234 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "calling clear pipe stall to clear the data toggle bit");
1236 /* clear the data toggle bit */
1237 #if (InterfaceVersion < 190)
1238 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1240 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1241 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1244 return darwin_to_libusb (kresult);
1247 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1248 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1250 switch (transfer->type) {
1251 case LIBUSB_TRANSFER_TYPE_CONTROL:
1252 return cancel_control_transfer(itransfer);
1253 case LIBUSB_TRANSFER_TYPE_BULK:
1254 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1255 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1256 return darwin_abort_transfers (itransfer);
1258 _usbi_log (TRANSFER_CTX(transfer), LOG_LEVEL_ERROR, "unknown endpoint type %d", transfer->type);
1259 return LIBUSB_ERROR_INVALID_PARAM;
1263 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1264 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1265 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1267 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1268 free (tpriv->isoc_framelist);
1269 tpriv->isoc_framelist = NULL;
1273 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1274 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1275 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1276 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1279 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "an async io operation has completed");
1281 /* send a completion message to the device's file descriptor */
1282 message = MESSAGE_ASYNC_IO_COMPLETE;
1283 write (priv->fds[1], &message, sizeof (message));
1284 write (priv->fds[1], &itransfer, sizeof (itransfer));
1285 write (priv->fds[1], &result, sizeof (IOReturn));
1286 write (priv->fds[1], &arg0, sizeof (UInt32));
1289 static void darwin_bulk_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1290 enum libusb_transfer_status status;
1292 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "handling bulk completion with status %d", result);
1295 case kIOReturnSuccess:
1296 status = LIBUSB_TRANSFER_COMPLETED;
1297 itransfer->transferred += io_size;
1299 case kIOReturnAborted:
1300 usbi_handle_transfer_cancellation(itransfer);
1302 case kIOUSBPipeStalled:
1303 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_WARNING, "unsupported control request");
1304 status = LIBUSB_TRANSFER_STALL;
1308 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_ERROR, "control error = %s", darwin_error_str (result));
1309 status = LIBUSB_TRANSFER_ERROR;
1312 usbi_handle_transfer_completion(itransfer, status);
1315 static void darwin_isoc_callback (struct usbi_transfer *itransfer, kern_return_t result) {
1316 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1317 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1320 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "handling isoc completion with status %d", result);
1322 if (result == kIOReturnSuccess && tpriv->isoc_framelist) {
1323 /* copy isochronous results back */
1325 for (i = 0; i < transfer->num_iso_packets ; i++) {
1326 struct libusb_iso_packet_descriptor *lib_desc = transfer->iso_packet_desc;
1327 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1328 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1333 case kIOReturnSuccess:
1334 status = LIBUSB_TRANSFER_COMPLETED;
1336 case kIOReturnAborted:
1337 usbi_handle_transfer_cancellation(itransfer);
1339 case kIOUSBPipeStalled:
1340 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_WARNING, "unsupported control request");
1341 status = LIBUSB_TRANSFER_STALL;
1345 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_ERROR, "control error = %s", darwin_error_str (result));
1346 status = LIBUSB_TRANSFER_ERROR;
1349 usbi_handle_transfer_completion(itransfer, status);
1352 static void darwin_control_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1355 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "handling control completion with status %d", result);
1358 case kIOReturnSuccess:
1359 status = LIBUSB_TRANSFER_COMPLETED;
1360 itransfer->transferred += io_size;
1362 case kIOReturnAborted:
1363 usbi_handle_transfer_cancellation(itransfer);
1365 case kIOUSBPipeStalled:
1366 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_WARNING, "unsupported control request");
1367 status = LIBUSB_TRANSFER_STALL;
1371 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_ERROR, "control error = %s", darwin_error_str (result));
1372 status = LIBUSB_TRANSFER_ERROR;
1375 usbi_handle_transfer_completion(itransfer, status);
1378 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1379 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1381 switch (transfer->type) {
1382 case LIBUSB_TRANSFER_TYPE_CONTROL:
1383 darwin_control_callback (itransfer, result, io_size);
1385 case LIBUSB_TRANSFER_TYPE_BULK:
1386 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1387 darwin_bulk_callback (itransfer, result, io_size);
1389 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1390 darwin_isoc_callback (itransfer, result);
1393 _usbi_log (TRANSFER_CTX(transfer), LOG_LEVEL_ERROR, "unknown endpoint type %d", transfer->type);
1397 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, nfds_t nfds, int num_ready) {
1398 struct usbi_transfer *itransfer;
1404 pthread_mutex_lock(&ctx->open_devs_lock);
1405 for (i = 0; i < nfds && num_ready > 0; i++) {
1406 struct pollfd *pollfd = &fds[i];
1407 struct libusb_device_handle *handle;
1408 struct darwin_device_handle_priv *hpriv = NULL;
1410 _usbi_log (ctx, LOG_LEVEL_INFO, "checking fd %i with revents = %x", fds[i], pollfd->revents);
1412 if (!pollfd->revents)
1416 list_for_each_entry(handle, &ctx->open_devs, list) {
1417 hpriv = (struct darwin_device_handle_priv *)handle->os_priv;
1418 if (hpriv->fds[0] == pollfd->fd)
1422 if (!(pollfd->revents & POLLERR)) {
1423 ret = read (hpriv->fds[0], &message, sizeof (message));
1424 if (ret < sizeof (message))
1427 /* could not poll the device-- response is to delete the device (this seems a little heavy-handed) */
1428 message = MESSAGE_DEVICE_GONE;
1431 case MESSAGE_DEVICE_GONE:
1432 /* remove the device's async port from the runloop */
1433 if (hpriv->cfSource) {
1434 if (libusb_darwin_acfl)
1435 CFRunLoopRemoveSource (libusb_darwin_acfl, hpriv->cfSource, kCFRunLoopDefaultMode);
1436 CFRelease (hpriv->cfSource);
1437 hpriv->cfSource = NULL;
1440 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
1441 usbi_handle_disconnect(handle);
1443 /* done with this device */
1445 case MESSAGE_ASYNC_IO_COMPLETE:
1446 read (hpriv->fds[0], &itransfer, sizeof (itransfer));
1447 read (hpriv->fds[0], &kresult, sizeof (IOReturn));
1448 read (hpriv->fds[0], &io_size, sizeof (UInt32));
1450 darwin_handle_callback (itransfer, kresult, io_size);
1453 _usbi_log (ctx, LOG_LEVEL_ERROR, "unknown message received from device pipe");
1457 pthread_mutex_unlock(&ctx->open_devs_lock);
1462 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1463 mach_timespec_t sys_time;
1464 clock_serv_t clock_ref;
1467 case USBI_CLOCK_REALTIME:
1468 /* CLOCK_REALTIME represents time since the epoch */
1469 host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &clock_ref);
1471 case USBI_CLOCK_MONOTONIC:
1472 /* use system boot time as reference for the monotonic clock */
1473 host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &clock_ref);
1476 return LIBUSB_ERROR_INVALID_PARAM;
1479 clock_get_time (clock_ref, &sys_time);
1481 tp->tv_sec = sys_time.tv_sec;
1482 tp->tv_nsec = sys_time.tv_nsec;
1487 const struct usbi_os_backend darwin_backend = {
1489 .init = darwin_init,
1490 .exit = darwin_exit,
1491 .get_device_list = darwin_get_device_list,
1492 .get_device_descriptor = darwin_get_device_descriptor,
1493 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1494 .get_config_descriptor = darwin_get_config_descriptor,
1496 .open = darwin_open,
1497 .close = darwin_close,
1498 .get_configuration = darwin_get_configuration,
1499 .set_configuration = darwin_set_configuration,
1500 .claim_interface = darwin_claim_interface,
1501 .release_interface = darwin_release_interface,
1503 .set_interface_altsetting = darwin_set_interface_altsetting,
1504 .clear_halt = darwin_clear_halt,
1505 .reset_device = darwin_reset_device,
1507 .kernel_driver_active = darwin_kernel_driver_active,
1508 .detach_kernel_driver = darwin_detach_kernel_driver,
1509 .attach_kernel_driver = darwin_attach_kernel_driver,
1511 .destroy_device = darwin_destroy_device,
1513 .submit_transfer = darwin_submit_transfer,
1514 .cancel_transfer = darwin_cancel_transfer,
1515 .clear_transfer_priv = darwin_clear_transfer_priv,
1517 .handle_events = op_handle_events,
1519 .clock_gettime = darwin_clock_gettime,
1521 .device_priv_size = sizeof(struct darwin_device_priv),
1522 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1523 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1524 .add_iso_packet_size = 0,