2 * darwin backend for libusb 1.0
3 * Copyright (C) 2008-2010 Nathan Hjelm <hjelmn@users.sourceforge.net>
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
29 #include <sys/ioctl.h>
31 #include <sys/types.h>
34 #include <mach/clock.h>
35 #include <mach/clock_types.h>
36 #include <mach/mach_host.h>
38 #include <mach/mach_port.h>
39 #include <IOKit/IOCFBundle.h>
40 #include <IOKit/usb/IOUSBLib.h>
41 #include <IOKit/IOCFPlugIn.h>
43 #include "darwin_usb.h"
45 static mach_port_t libusb_darwin_mp = 0; /* master port */
46 static CFRunLoopRef libusb_darwin_acfl = NULL; /* async cf loop */
47 static int initCount = 0;
49 /* async event thread */
50 static pthread_t libusb_darwin_at;
52 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
53 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
54 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
55 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
56 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
58 static const char *darwin_error_str (int result) {
60 case kIOReturnSuccess:
62 case kIOReturnNotOpen:
63 return "device not opened for exclusive access";
64 case kIOReturnNoDevice:
65 return "no connection to an IOService";
66 case kIOUSBNoAsyncPortErr:
67 return "no async port has been opened for interface";
68 case kIOReturnExclusiveAccess:
69 return "another process has device opened for exclusive access";
70 case kIOUSBPipeStalled:
71 return "pipe is stalled";
73 return "could not establish a connection to the Darwin kernel";
74 case kIOUSBTransactionTimeout:
75 return "transaction timed out";
76 case kIOReturnBadArgument:
77 return "invalid argument";
78 case kIOReturnAborted:
79 return "transaction aborted";
80 case kIOReturnNotResponding:
81 return "device not responding";
82 case kIOReturnOverrun:
83 return "data overrun";
84 case kIOReturnCannotWire:
85 return "physical memory can not be wired down";
87 return "unknown error";
91 static int darwin_to_libusb (int result) {
93 case kIOReturnUnderrun:
94 case kIOReturnSuccess:
95 return LIBUSB_SUCCESS;
96 case kIOReturnNotOpen:
97 case kIOReturnNoDevice:
98 return LIBUSB_ERROR_NO_DEVICE;
99 case kIOReturnExclusiveAccess:
100 return LIBUSB_ERROR_ACCESS;
101 case kIOUSBPipeStalled:
102 return LIBUSB_ERROR_PIPE;
103 case kIOReturnBadArgument:
104 return LIBUSB_ERROR_INVALID_PARAM;
105 case kIOUSBTransactionTimeout:
106 return LIBUSB_ERROR_TIMEOUT;
107 case kIOReturnNotResponding:
108 case kIOReturnAborted:
110 case kIOUSBNoAsyncPortErr:
112 return LIBUSB_ERROR_OTHER;
117 static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp) {
118 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
120 /* current interface */
121 struct __darwin_interface *cInterface;
125 usbi_info (HANDLE_CTX(dev_handle), "converting ep address 0x%02x to pipeRef and interface", ep);
127 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
128 cInterface = &priv->interfaces[iface];
130 if (dev_handle->claimed_interfaces & (1 << iface)) {
131 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
132 if (cInterface->endpoint_addrs[i] == ep) {
135 usbi_info (HANDLE_CTX(dev_handle), "pipe %d on interface %d matches", *pipep, *ifcp);
142 /* No pipe found with the correct endpoint address */
143 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
148 static int usb_setup_device_iterator (io_iterator_t *deviceIterator) {
149 return IOServiceGetMatchingServices(libusb_darwin_mp, IOServiceMatching(kIOUSBDeviceClassName), deviceIterator);
152 static usb_device_t **usb_get_next_device (io_iterator_t deviceIterator, UInt32 *locationp) {
153 io_cf_plugin_ref_t *plugInInterface = NULL;
154 usb_device_t **device;
155 io_service_t usbDevice;
159 if (!IOIteratorIsValid (deviceIterator))
163 while ((usbDevice = IOIteratorNext(deviceIterator))) {
164 result = IOCreatePlugInInterfaceForService(usbDevice, kIOUSBDeviceUserClientTypeID,
165 kIOCFPlugInInterfaceID, &plugInInterface,
167 if (kIOReturnSuccess == result && plugInInterface)
170 usbi_dbg ("libusb/darwin.c usb_get_next_device: could not set up plugin for service: %s\n", darwin_error_str (result));
176 (void)IOObjectRelease(usbDevice);
177 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
180 (*plugInInterface)->Stop(plugInInterface);
181 IODestroyPlugInInterface (plugInInterface);
183 /* get the location from the device */
185 (*(device))->GetLocationID(device, locationp);
190 static kern_return_t darwin_get_device (uint32_t dev_location, usb_device_t ***darwin_device) {
191 kern_return_t kresult;
193 io_iterator_t deviceIterator;
195 kresult = usb_setup_device_iterator (&deviceIterator);
199 /* This port of libusb uses locations to keep track of devices. */
200 while ((*darwin_device = usb_get_next_device (deviceIterator, &location)) != NULL) {
201 if (location == dev_location)
204 (**darwin_device)->Release(*darwin_device);
207 IOObjectRelease (deviceIterator);
209 if (!(*darwin_device))
210 return kIOReturnNoDevice;
212 return kIOReturnSuccess;
217 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
218 struct libusb_context *ctx = (struct libusb_context *)ptr;
219 struct libusb_device_handle *handle;
220 struct darwin_device_priv *dpriv;
221 struct darwin_device_handle_priv *priv;
225 CFTypeRef locationCF;
228 usbi_info (ctx, "a device has been detached");
230 while ((device = IOIteratorNext (rem_devices)) != 0) {
231 /* get the location from the i/o registry */
232 locationCF = IORegistryEntryCreateCFProperty (device, CFSTR(kUSBDevicePropertyLocationID), kCFAllocatorDefault, 0);
234 CFNumberGetValue(locationCF, kCFNumberLongType, &location);
235 CFRelease (locationCF);
236 IOObjectRelease (device);
238 usbi_mutex_lock(&ctx->open_devs_lock);
239 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
240 dpriv = (struct darwin_device_priv *)handle->dev->os_priv;
242 /* the device may have been opened several times. write to each handle's event descriptor */
243 if (dpriv->location == location && handle->os_priv) {
244 priv = (struct darwin_device_handle_priv *)handle->os_priv;
246 message = MESSAGE_DEVICE_GONE;
247 write (priv->fds[1], &message, sizeof (message));
251 usbi_mutex_unlock(&ctx->open_devs_lock);
255 static void darwin_clear_iterator (io_iterator_t iter) {
258 while ((device = IOIteratorNext (iter)) != 0)
259 IOObjectRelease (device);
262 static void *event_thread_main (void *arg0) {
264 struct libusb_context *ctx = (struct libusb_context *)arg0;
266 /* hotplug (device removal) source */
267 CFRunLoopSourceRef libusb_notification_cfsource;
268 io_notification_port_t libusb_notification_port;
269 io_iterator_t libusb_rem_device_iterator;
271 usbi_info (ctx, "creating hotplug event source");
273 CFRetain (CFRunLoopGetCurrent ());
275 /* add the notification port to the run loop */
276 libusb_notification_port = IONotificationPortCreate (libusb_darwin_mp);
277 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
278 CFRunLoopAddSource(CFRunLoopGetCurrent (), libusb_notification_cfsource, kCFRunLoopDefaultMode);
280 /* create notifications for removed devices */
281 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
282 IOServiceMatching(kIOUSBDeviceClassName),
283 (IOServiceMatchingCallback)darwin_devices_detached,
284 (void *)ctx, &libusb_rem_device_iterator);
286 if (kresult != kIOReturnSuccess) {
287 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
289 pthread_exit ((void *)kresult);
293 darwin_clear_iterator (libusb_rem_device_iterator);
295 /* let the main thread know about the async runloop */
296 libusb_darwin_acfl = CFRunLoopGetCurrent ();
298 usbi_info (ctx, "thread ready to receive events");
300 /* run the runloop */
303 usbi_info (ctx, "thread exiting");
305 /* delete notification port */
306 CFRunLoopSourceInvalidate (libusb_notification_cfsource);
307 IONotificationPortDestroy (libusb_notification_port);
309 CFRelease (CFRunLoopGetCurrent ());
311 libusb_darwin_acfl = NULL;
316 static int darwin_init(struct libusb_context *ctx) {
319 if (!(initCount++)) {
320 /* Create the master port for talking to IOKit */
321 if (!libusb_darwin_mp) {
322 kresult = IOMasterPort (MACH_PORT_NULL, &libusb_darwin_mp);
324 if (kresult != kIOReturnSuccess || !libusb_darwin_mp)
325 return darwin_to_libusb (kresult);
328 pthread_create (&libusb_darwin_at, NULL, event_thread_main, (void *)ctx);
330 while (!libusb_darwin_acfl)
337 static void darwin_exit (void) {
338 if (!(--initCount)) {
341 /* stop the async runloop */
342 CFRunLoopStop (libusb_darwin_acfl);
343 pthread_join (libusb_darwin_at, &ret);
345 if (libusb_darwin_mp)
346 mach_port_deallocate(mach_task_self(), libusb_darwin_mp);
348 libusb_darwin_mp = 0;
352 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
353 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
355 /* return cached copy */
356 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
363 static int get_configuration_index (struct libusb_device *dev, int config_value) {
364 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
366 IOUSBConfigurationDescriptorPtr desc;
369 /* is there a simpler way to determine the index? */
370 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
371 if (kresult != kIOReturnSuccess)
372 return darwin_to_libusb (kresult);
374 for (i = 0 ; i < numConfig ; i++) {
375 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
377 if (desc->bConfigurationValue == config_value)
381 /* configuration not found */
382 return LIBUSB_ERROR_OTHER;
385 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
386 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
389 if (0 == priv->active_config)
390 return LIBUSB_ERROR_INVALID_PARAM;
392 config_index = get_configuration_index (dev, priv->active_config);
393 if (config_index < 0)
396 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
399 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
400 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
401 IOUSBConfigurationDescriptorPtr desc;
403 usb_device_t **device = NULL;
406 return LIBUSB_ERROR_OTHER;
409 kresult = darwin_get_device (priv->location, &device);
410 if (kresult || !device) {
411 usbi_err (DEVICE_CTX (dev), "could not find device: %s", darwin_error_str (kresult));
413 return darwin_to_libusb (kresult);
416 /* don't have to open the device to get a config descriptor */
418 device = priv->device;
420 kresult = (*device)->GetConfigurationDescriptorPtr (device, config_index, &desc);
421 if (kresult == kIOReturnSuccess) {
422 /* copy descriptor */
423 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
424 len = libusb_le16_to_cpu(desc->wTotalLength);
426 memmove (buffer, desc, len);
428 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
433 (*device)->Release (device);
435 return darwin_to_libusb (kresult);
438 /* check whether the os has configured the device */
439 static int darwin_check_configuration (struct libusb_context *ctx, struct libusb_device *dev, usb_device_t **darwin_device) {
440 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
442 IOUSBConfigurationDescriptorPtr configDesc;
443 IOUSBFindInterfaceRequest request;
444 kern_return_t kresult;
445 io_iterator_t interface_iterator;
446 io_service_t firstInterface;
448 if (priv->dev_descriptor.bNumConfigurations < 1) {
449 usbi_err (ctx, "device has no configurations");
450 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
453 /* find the first configuration */
454 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
455 priv->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
457 /* check if the device is already configured. there is probably a better way than iterating over the
458 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
459 might lock up on the device request) */
461 /* Setup the Interface Request */
462 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
463 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
464 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
465 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
467 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
469 return darwin_to_libusb (kresult);
472 firstInterface = IOIteratorNext(interface_iterator);
474 /* done with the interface iterator */
475 IOObjectRelease(interface_iterator);
477 if (firstInterface) {
478 IOObjectRelease (firstInterface);
480 /* device is configured */
481 if (priv->dev_descriptor.bNumConfigurations == 1)
482 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
483 priv->active_config = priv->first_config;
485 /* devices with more than one configuration should work with GetConfiguration */
486 (*darwin_device)->GetConfiguration (darwin_device, &priv->active_config);
489 priv->active_config = 0;
491 usbi_info (ctx, "active config: %u, first config: %u", priv->active_config, priv->first_config);
496 static int process_new_device (struct libusb_context *ctx, usb_device_t **device, UInt32 locationID, struct discovered_devs **_discdevs) {
497 struct darwin_device_priv *priv;
498 struct libusb_device *dev;
499 struct discovered_devs *discdevs;
500 UInt16 address, idVendor, idProduct;
501 UInt8 bDeviceClass, bDeviceSubClass;
503 int ret = 0, need_unref = 0;
506 dev = usbi_get_device_by_session_id(ctx, locationID);
508 usbi_info (ctx, "allocating new device for location 0x%08x", locationID);
509 dev = usbi_alloc_device(ctx, locationID);
512 usbi_info (ctx, "using existing device for location 0x%08x", locationID);
515 ret = LIBUSB_ERROR_NO_MEM;
519 priv = (struct darwin_device_priv *)dev->os_priv;
521 /* Set up request for device descriptor */
522 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
523 req.bRequest = kUSBRqGetDescriptor;
524 req.wValue = kUSBDeviceDesc << 8;
526 req.wLength = sizeof(IOUSBDeviceDescriptor);
527 req.pData = &(priv->dev_descriptor);
529 (*(device))->GetDeviceAddress (device, (USBDeviceAddress *)&address);
530 (*(device))->GetDeviceProduct (device, &idProduct);
531 (*(device))->GetDeviceVendor (device, &idVendor);
532 (*(device))->GetDeviceClass (device, &bDeviceClass);
533 (*(device))->GetDeviceSubClass (device, &bDeviceSubClass);
535 /**** retrieve device descriptors ****/
536 /* according to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
537 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request */
538 ret = (*(device))->DeviceRequest (device, &req);
539 if (ret != kIOReturnSuccess) {
540 int try_unsuspend = 1;
541 #if DeviceVersion >= 320
544 /* device may be suspended. unsuspend it and try again */
545 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
546 (void)(*device)->GetUSBDeviceInformation (device, &info);
548 try_unsuspend = info & (1 << kUSBInformationDeviceIsSuspendedBit);
551 /* the device should be open before to device is unsuspended */
552 (void) (*device)->USBDeviceOpenSeize(device);
555 /* resume the device */
556 (void)(*device)->USBDeviceSuspend (device, 0);
558 ret = (*(device))->DeviceRequest (device, &req);
560 /* resuspend the device */
561 (void)(*device)->USBDeviceSuspend (device, 1);
564 (*device)->USBDeviceClose (device);
567 if (ret != kIOReturnSuccess) {
568 usbi_warn (ctx, "could not retrieve device descriptor: %s. skipping device", darwin_error_str (ret));
573 /**** end: retrieve device descriptors ****/
575 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
576 if (libusb_le16_to_cpu (priv->dev_descriptor.idProduct) != idProduct) {
577 /* not a valid device */
578 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
579 idProduct, libusb_le16_to_cpu (priv->dev_descriptor.idProduct));
584 dev->bus_number = locationID >> 24;
585 dev->device_address = address;
587 /* check current active configuration (and cache the first configuration value-- which may be used by claim_interface) */
588 ret = darwin_check_configuration (ctx, dev, device);
592 /* save our location, we'll need this later */
593 priv->location = locationID;
594 snprintf(priv->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", address, idVendor, idProduct, bDeviceClass, bDeviceSubClass);
596 ret = usbi_sanitize_device (dev);
600 /* append the device to the list of discovered devices */
601 discdevs = discovered_devs_append(*_discdevs, dev);
603 ret = LIBUSB_ERROR_NO_MEM;
607 *_discdevs = discdevs;
609 usbi_info (ctx, "found device with address %d at %s", dev->device_address, priv->sys_path);
613 libusb_unref_device(dev);
618 static int darwin_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs) {
619 io_iterator_t deviceIterator;
620 usb_device_t **device;
621 kern_return_t kresult;
624 if (!libusb_darwin_mp)
625 return LIBUSB_ERROR_INVALID_PARAM;
627 kresult = usb_setup_device_iterator (&deviceIterator);
628 if (kresult != kIOReturnSuccess)
629 return darwin_to_libusb (kresult);
631 while ((device = usb_get_next_device (deviceIterator, &location)) != NULL) {
632 (void) process_new_device (ctx, device, location, _discdevs);
634 (*(device))->Release(device);
637 IOObjectRelease(deviceIterator);
642 static int darwin_open (struct libusb_device_handle *dev_handle) {
643 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
644 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
645 usb_device_t **darwin_device;
648 if (0 == dpriv->open_count) {
649 kresult = darwin_get_device (dpriv->location, &darwin_device);
651 usbi_err (HANDLE_CTX (dev_handle), "could not find device: %s", darwin_error_str (kresult));
652 return darwin_to_libusb (kresult);
655 dpriv->device = darwin_device;
657 /* try to open the device */
658 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
660 if (kresult != kIOReturnSuccess) {
661 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
664 case kIOReturnExclusiveAccess:
665 /* it is possible to perform some actions on a device that is not open so do not return an error */
670 (*(dpriv->device))->Release (dpriv->device);
671 dpriv->device = NULL;
672 return darwin_to_libusb (kresult);
675 /* create async event source */
676 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
677 if (kresult != kIOReturnSuccess) {
678 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
680 (*(dpriv->device))->USBDeviceClose (dpriv->device);
681 (*(dpriv->device))->Release (dpriv->device);
683 dpriv->device = NULL;
684 return darwin_to_libusb (kresult);
689 CFRetain (libusb_darwin_acfl);
691 /* add the cfSource to the aync run loop */
692 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
696 /* device opened successfully */
699 /* create a file descriptor for notifications */
702 /* set the pipe to be non-blocking */
703 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
705 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
707 usbi_info (HANDLE_CTX (dev_handle), "device open for access");
712 static void darwin_close (struct libusb_device_handle *dev_handle) {
713 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
714 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
718 if (dpriv->open_count == 0) {
719 /* something is probably very wrong if this is the case */
720 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!\n");
726 /* make sure all interfaces are released */
727 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
728 if (dev_handle->claimed_interfaces & (1 << i))
729 libusb_release_interface (dev_handle, i);
731 if (0 == dpriv->open_count) {
733 /* delete the device's async event source */
734 if (priv->cfSource) {
735 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
736 CFRelease (priv->cfSource);
739 /* close the device */
740 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
742 /* Log the fact that we had a problem closing the file, however failing a
743 * close isn't really an error, so return success anyway */
744 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
748 kresult = (*(dpriv->device))->Release(dpriv->device);
750 /* Log the fact that we had a problem closing the file, however failing a
751 * close isn't really an error, so return success anyway */
752 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
755 dpriv->device = NULL;
758 /* file descriptors are maintained per-instance */
759 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
760 close (priv->fds[1]);
761 close (priv->fds[0]);
763 priv->fds[0] = priv->fds[1] = -1;
766 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
767 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
769 *config = (int) dpriv->active_config;
774 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
775 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
779 /* Setting configuration will invalidate the interface, so we need
780 to reclaim it. First, dispose of existing interfaces, if any. */
781 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
782 if (dev_handle->claimed_interfaces & (1 << i))
783 darwin_release_interface (dev_handle, i);
785 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
786 if (kresult != kIOReturnSuccess)
787 return darwin_to_libusb (kresult);
789 /* Reclaim any interfaces. */
790 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
791 if (dev_handle->claimed_interfaces & (1 << i))
792 darwin_claim_interface (dev_handle, i);
794 dpriv->active_config = config;
799 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
800 IOUSBFindInterfaceRequest request;
801 uint8_t current_interface;
802 kern_return_t kresult;
803 io_iterator_t interface_iterator;
805 *usbInterfacep = IO_OBJECT_NULL;
807 /* Setup the Interface Request */
808 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
809 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
810 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
811 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
813 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
817 for ( current_interface = 0 ; current_interface <= ifc ; current_interface++ ) {
818 *usbInterfacep = IOIteratorNext(interface_iterator);
819 if (current_interface != ifc)
820 (void) IOObjectRelease (*usbInterfacep);
823 /* done with the interface iterator */
824 IOObjectRelease(interface_iterator);
829 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
830 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
832 /* current interface */
833 struct __darwin_interface *cInterface = &priv->interfaces[iface];
835 kern_return_t kresult;
837 u_int8_t numep, direction, number;
838 u_int8_t dont_care1, dont_care3;
839 u_int16_t dont_care2;
842 usbi_info (HANDLE_CTX (dev_handle), "building table of endpoints.");
844 /* retrieve the total number of endpoints on this interface */
845 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
847 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
848 return darwin_to_libusb (kresult);
851 /* iterate through pipe references */
852 for (i = 1 ; i <= numep ; i++) {
853 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
854 &dont_care2, &dont_care3);
856 if (kresult != kIOReturnSuccess) {
857 usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
859 return darwin_to_libusb (kresult);
862 usbi_info (HANDLE_CTX (dev_handle), "interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
864 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
867 cInterface->num_endpoints = numep;
872 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
873 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
874 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
875 io_service_t usbInterface = IO_OBJECT_NULL;
877 IOCFPlugInInterface **plugInInterface = NULL;
880 /* current interface */
881 struct __darwin_interface *cInterface = &priv->interfaces[iface];
883 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
884 if (kresult != kIOReturnSuccess)
885 return darwin_to_libusb (kresult);
887 /* make sure we have an interface */
888 if (!usbInterface && dpriv->first_config != 0) {
889 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
891 /* set the configuration */
892 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
893 if (kresult != LIBUSB_SUCCESS) {
894 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
898 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
900 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
901 return darwin_to_libusb (kresult);
906 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
907 return LIBUSB_ERROR_NOT_FOUND;
910 /* get an interface to the device's interface */
911 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
912 kIOCFPlugInInterfaceID, &plugInInterface, &score);
914 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
915 return darwin_to_libusb (kresult);
918 if (!plugInInterface) {
919 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
920 return LIBUSB_ERROR_NOT_FOUND;
923 /* ignore release error */
924 (void)IOObjectRelease (usbInterface);
926 /* Do the actual claim */
927 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
928 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
929 (LPVOID)&cInterface->interface);
930 if (kresult || !cInterface->interface) {
931 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
932 return darwin_to_libusb (kresult);
935 /* We no longer need the intermediate plug-in */
936 (*plugInInterface)->Release(plugInInterface);
938 /* claim the interface */
939 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
941 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
942 return darwin_to_libusb (kresult);
945 /* update list of endpoints */
946 kresult = get_endpoints (dev_handle, iface);
948 /* this should not happen */
949 darwin_release_interface (dev_handle, iface);
950 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
954 cInterface->cfSource = NULL;
956 /* create async event source */
957 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
958 if (kresult != kIOReturnSuccess) {
959 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
961 /* can't continue without an async event source */
962 (void)darwin_release_interface (dev_handle, iface);
964 return darwin_to_libusb (kresult);
967 /* add the cfSource to the async thread's run loop */
968 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
970 usbi_info (HANDLE_CTX (dev_handle), "interface opened");
975 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
976 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
979 /* current interface */
980 struct __darwin_interface *cInterface = &priv->interfaces[iface];
982 /* Check to see if an interface is open */
983 if (!cInterface->interface)
984 return LIBUSB_SUCCESS;
986 /* clean up endpoint data */
987 cInterface->num_endpoints = 0;
989 /* delete the interface's async event source */
990 if (cInterface->cfSource) {
991 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
992 CFRelease (cInterface->cfSource);
995 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
997 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
999 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1000 if (kresult != kIOReturnSuccess)
1001 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1003 cInterface->interface = IO_OBJECT_NULL;
1005 return darwin_to_libusb (kresult);
1008 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1009 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1012 /* current interface */
1013 struct __darwin_interface *cInterface = &priv->interfaces[iface];
1015 if (!cInterface->interface)
1016 return LIBUSB_ERROR_NO_DEVICE;
1018 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1019 if (kresult != kIOReturnSuccess)
1020 darwin_reset_device (dev_handle);
1022 /* update list of endpoints */
1023 kresult = get_endpoints (dev_handle, iface);
1025 /* this should not happen */
1026 darwin_release_interface (dev_handle, iface);
1027 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1031 return darwin_to_libusb (kresult);
1034 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1035 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1037 /* current interface */
1038 struct __darwin_interface *cInterface;
1039 uint8_t pipeRef, iface;
1042 /* determine the interface/endpoint to use */
1043 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
1044 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1046 return LIBUSB_ERROR_NOT_FOUND;
1049 cInterface = &priv->interfaces[iface];
1051 #if (InterfaceVersion < 190)
1052 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1054 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1055 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1058 usbi_err (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1060 return darwin_to_libusb (kresult);
1063 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1064 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1067 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1069 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1071 return darwin_to_libusb (kresult);
1074 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1075 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1076 io_service_t usbInterface;
1080 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1082 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1084 return darwin_to_libusb (kresult);
1087 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1088 IOObjectRelease (usbInterface);
1100 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1101 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1102 return LIBUSB_ERROR_NOT_SUPPORTED;
1105 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1106 return LIBUSB_ERROR_NOT_SUPPORTED;
1109 static void darwin_destroy_device(struct libusb_device *dev) {
1112 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1113 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1114 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1117 uint8_t is_read; /* 0 = we're reading, 1 = we're writing */
1118 uint8_t transferType;
1119 /* None of the values below are used in libusb for bulk transfers */
1120 uint8_t direction, number, interval, pipeRef, iface;
1121 uint16_t maxPacketSize;
1123 struct __darwin_interface *cInterface;
1125 /* are we reading or writing? */
1126 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1128 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1129 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1131 return LIBUSB_ERROR_NOT_FOUND;
1134 cInterface = &priv->interfaces[iface];
1136 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1137 &transferType, &maxPacketSize, &interval);
1139 /* submit the request */
1140 /* timeouts are unavailable on interrupt endpoints */
1141 if (transferType == kUSBInterrupt) {
1143 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1144 transfer->length, darwin_async_io_callback, itransfer);
1146 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1147 transfer->length, darwin_async_io_callback, itransfer);
1149 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1152 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1153 transfer->length, transfer->timeout, transfer->timeout,
1154 darwin_async_io_callback, (void *)itransfer);
1156 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1157 transfer->length, transfer->timeout, transfer->timeout,
1158 darwin_async_io_callback, (void *)itransfer);
1162 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", is_read ? "In" : "Out",
1163 darwin_error_str(ret), ret);
1165 return darwin_to_libusb (ret);
1168 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1169 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1170 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1171 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1174 uint8_t is_read; /* 0 = we're writing, 1 = we're reading */
1175 uint8_t pipeRef, iface;
1177 AbsoluteTime atTime;
1180 struct __darwin_interface *cInterface;
1182 /* are we reading or writing? */
1183 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1185 /* construct an array of IOUSBIsocFrames */
1186 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1187 if (!tpriv->isoc_framelist)
1188 return LIBUSB_ERROR_NO_MEM;
1190 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1191 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1192 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1194 /* determine the interface/endpoint to use */
1195 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1196 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1198 return LIBUSB_ERROR_NOT_FOUND;
1201 cInterface = &priv->interfaces[iface];
1203 /* Last but not least we need the bus frame number */
1204 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1206 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1207 free(tpriv->isoc_framelist);
1208 tpriv->isoc_framelist = NULL;
1210 return darwin_to_libusb (kresult);
1213 /* schedule for a frame a little in the future */
1216 /* submit the request */
1218 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1219 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1222 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1223 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1226 if (kresult != kIOReturnSuccess) {
1227 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", is_read ? "In" : "Out",
1228 darwin_error_str(kresult));
1229 free (tpriv->isoc_framelist);
1230 tpriv->isoc_framelist = NULL;
1233 return darwin_to_libusb (kresult);
1236 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1237 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1238 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1239 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1240 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1244 bzero(&tpriv->req, sizeof(tpriv->req));
1246 /* IOUSBDeviceInterface expects the request in cpu endianess */
1247 tpriv->req.bmRequestType = setup->bmRequestType;
1248 tpriv->req.bRequest = setup->bRequest;
1249 /* these values should be in bus order from libusb_fill_control_setup */
1250 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1251 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1252 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1253 /* data is stored after the libusb control block */
1254 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1255 tpriv->req.completionTimeout = transfer->timeout;
1256 tpriv->req.noDataTimeout = transfer->timeout;
1258 itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1260 /* all transfers in libusb-1.0 are async */
1261 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1263 if (kresult != kIOReturnSuccess)
1264 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1266 return darwin_to_libusb (kresult);
1269 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1270 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1272 switch (transfer->type) {
1273 case LIBUSB_TRANSFER_TYPE_CONTROL:
1274 return submit_control_transfer(itransfer);
1275 case LIBUSB_TRANSFER_TYPE_BULK:
1276 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1277 return submit_bulk_transfer(itransfer);
1278 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1279 return submit_iso_transfer(itransfer);
1281 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1282 return LIBUSB_ERROR_INVALID_PARAM;
1286 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1287 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1288 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1291 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions control pipe");
1293 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1295 return darwin_to_libusb (kresult);
1298 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1299 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1300 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1301 struct __darwin_interface *cInterface;
1302 uint8_t pipeRef, iface;
1305 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1306 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1308 return LIBUSB_ERROR_NOT_FOUND;
1311 cInterface = &priv->interfaces[iface];
1313 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions on interface %d pipe %d", iface, pipeRef);
1315 /* abort transactions */
1316 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1318 usbi_info (ITRANSFER_CTX (itransfer), "calling clear pipe stall to clear the data toggle bit");
1320 /* clear the data toggle bit */
1321 #if (InterfaceVersion < 190)
1322 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1324 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1325 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1328 return darwin_to_libusb (kresult);
1331 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1332 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1334 switch (transfer->type) {
1335 case LIBUSB_TRANSFER_TYPE_CONTROL:
1336 return cancel_control_transfer(itransfer);
1337 case LIBUSB_TRANSFER_TYPE_BULK:
1338 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1339 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1340 return darwin_abort_transfers (itransfer);
1342 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1343 return LIBUSB_ERROR_INVALID_PARAM;
1347 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1348 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1349 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1351 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1352 free (tpriv->isoc_framelist);
1353 tpriv->isoc_framelist = NULL;
1357 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1358 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1359 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1360 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1363 usbi_info (ITRANSFER_CTX (itransfer), "an async io operation has completed");
1365 /* send a completion message to the device's file descriptor */
1366 message = MESSAGE_ASYNC_IO_COMPLETE;
1367 write (priv->fds[1], &message, sizeof (message));
1368 write (priv->fds[1], &itransfer, sizeof (itransfer));
1369 write (priv->fds[1], &result, sizeof (IOReturn));
1370 write (priv->fds[1], &arg0, sizeof (UInt32));
1373 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1374 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT)
1375 result = kIOUSBTransactionTimeout;
1378 case kIOReturnUnderrun:
1379 case kIOReturnSuccess:
1380 return LIBUSB_TRANSFER_COMPLETED;
1381 case kIOReturnAborted:
1382 return LIBUSB_TRANSFER_CANCELLED;
1383 case kIOUSBPipeStalled:
1384 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: pipe is stalled");
1385 return LIBUSB_TRANSFER_STALL;
1386 case kIOReturnOverrun:
1387 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1388 return LIBUSB_TRANSFER_OVERFLOW;
1389 case kIOUSBTransactionTimeout:
1390 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1391 itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
1392 return LIBUSB_TRANSFER_TIMED_OUT;
1394 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1395 return LIBUSB_TRANSFER_ERROR;
1399 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1400 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1401 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1402 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1403 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1404 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1405 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1408 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1409 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1413 usbi_info (ITRANSFER_CTX (itransfer), "handling %s completion with kernel status %d",
1414 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", result);
1416 if (kIOReturnSuccess == result || kIOReturnUnderrun == result) {
1417 if (isIsoc && tpriv->isoc_framelist) {
1418 /* copy isochronous results back */
1420 for (i = 0; i < transfer->num_iso_packets ; i++) {
1421 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1422 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1423 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1426 itransfer->transferred += io_size;
1429 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1430 usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, result));
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 usbi_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_info (ctx, "checking fd %i with revents = %x", fds[i], pollfd->revents);
1448 if (!pollfd->revents)
1452 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
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_err (ctx, "unknown message received from device pipe");
1493 usbi_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,