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 (libusb_le16_to_cpu (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;
391 kresult = (*(priv->device))->GetConfiguration (priv->device, &config_value);
392 if (kresult != kIOReturnSuccess)
393 return darwin_to_libusb (kresult);
395 config_index = get_configuration_index (dev, config_value);
396 if (config_index < 0)
399 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
402 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
403 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
404 IOUSBConfigurationDescriptorPtr desc;
406 usb_device_t **device = NULL;
409 return LIBUSB_ERROR_OTHER;
412 kresult = darwin_get_device (priv->location, &device);
413 if (kresult || !device) {
414 usbi_err (DEVICE_CTX (dev), "could not find device: %s", darwin_error_str (kresult));
416 return darwin_to_libusb (kresult);
419 /* don't have to open the device to get a config descriptor */
421 device = priv->device;
423 kresult = (*device)->GetConfigurationDescriptorPtr (device, config_index, &desc);
424 if (kresult == kIOReturnSuccess) {
425 /* copy descriptor */
426 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
427 len = libusb_le16_to_cpu(desc->wTotalLength);
429 memmove (buffer, desc, len);
431 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
436 (*device)->Release (device);
438 return darwin_to_libusb (kresult);
441 static int process_new_device (struct libusb_context *ctx, usb_device_t **device, UInt32 locationID, struct discovered_devs **_discdevs) {
442 struct darwin_device_priv *priv;
443 struct libusb_device *dev;
444 struct discovered_devs *discdevs;
445 UInt16 address, idVendor, idProduct;
446 UInt8 bDeviceClass, bDeviceSubClass;
448 int ret = 0, need_unref = 0;
451 dev = usbi_get_device_by_session_id(ctx, locationID);
453 usbi_info (ctx, "allocating new device for location 0x%08x", locationID);
454 dev = usbi_alloc_device(ctx, locationID);
457 usbi_info (ctx, "using existing device for location 0x%08x", locationID);
460 ret = LIBUSB_ERROR_NO_MEM;
464 priv = (struct darwin_device_priv *)dev->os_priv;
466 /* Set up request for device descriptor */
467 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
468 req.bRequest = kUSBRqGetDescriptor;
469 req.wValue = kUSBDeviceDesc << 8;
471 req.wLength = sizeof(IOUSBDeviceDescriptor);
472 req.pData = &(priv->dev_descriptor);
474 (*(device))->GetDeviceAddress (device, (USBDeviceAddress *)&address);
475 (*(device))->GetDeviceProduct (device, &idProduct);
476 (*(device))->GetDeviceVendor (device, &idVendor);
477 (*(device))->GetDeviceClass (device, &bDeviceClass);
478 (*(device))->GetDeviceSubClass (device, &bDeviceSubClass);
480 /**** retrieve device descriptors ****/
481 /* according to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
482 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request */
483 ret = (*(device))->DeviceRequest (device, &req);
484 if (ret != kIOReturnSuccess) {
485 int try_unsuspend = 1;
486 #if DeviceVersion >= 320
489 /* device may be suspended. unsuspend it and try again */
490 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
491 (void)(*device)->GetUSBDeviceInformation (device, &info);
493 try_unsuspend = info & (1 << kUSBInformationDeviceIsSuspendedBit);
496 /* the device should be open before to device is unsuspended */
497 (void) (*device)->USBDeviceOpenSeize(device);
500 /* resume the device */
501 (void)(*device)->USBDeviceSuspend (device, 0);
503 ret = (*(device))->DeviceRequest (device, &req);
505 /* resuspend the device */
506 (void)(*device)->USBDeviceSuspend (device, 1);
509 (*device)->USBDeviceClose (device);
512 if (ret != kIOReturnSuccess) {
513 usbi_warn (ctx, "could not retrieve device descriptor: %s. skipping device", darwin_error_str (ret));
518 /**** end: retrieve device descriptors ****/
520 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
521 if (libusb_le16_to_cpu (priv->dev_descriptor.idProduct) != idProduct) {
522 /* not a valid device */
523 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
524 idProduct, libusb_le16_to_cpu (priv->dev_descriptor.idProduct));
529 dev->bus_number = locationID >> 24;
530 dev->device_address = address;
532 /* save our location, we'll need this later */
533 priv->location = locationID;
534 snprintf(priv->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", address, idVendor, idProduct, bDeviceClass, bDeviceSubClass);
536 ret = usbi_sanitize_device (dev);
540 /* append the device to the list of discovered devices */
541 discdevs = discovered_devs_append(*_discdevs, dev);
543 ret = LIBUSB_ERROR_NO_MEM;
547 *_discdevs = discdevs;
549 usbi_info (ctx, "found device with address %d at %s", dev->device_address, priv->sys_path);
553 libusb_unref_device(dev);
558 static int darwin_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs) {
559 io_iterator_t deviceIterator;
560 usb_device_t **device;
561 kern_return_t kresult;
564 if (!libusb_darwin_mp)
565 return LIBUSB_ERROR_INVALID_PARAM;
567 kresult = usb_setup_device_iterator (&deviceIterator);
568 if (kresult != kIOReturnSuccess)
569 return darwin_to_libusb (kresult);
571 while ((device = usb_get_next_device (deviceIterator, &location)) != NULL) {
572 (void) process_new_device (ctx, device, location, _discdevs);
574 (*(device))->Release(device);
577 IOObjectRelease(deviceIterator);
582 static int darwin_open (struct libusb_device_handle *dev_handle) {
583 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
584 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
585 usb_device_t **darwin_device;
588 if (0 == dpriv->open_count) {
589 kresult = darwin_get_device (dpriv->location, &darwin_device);
591 usbi_err (HANDLE_CTX (dev_handle), "could not find device: %s", darwin_error_str (kresult));
592 return darwin_to_libusb (kresult);
595 dpriv->device = darwin_device;
597 /* try to open the device */
598 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
600 if (kresult != kIOReturnSuccess) {
601 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
604 case kIOReturnExclusiveAccess:
605 /* it is possible to perform some actions on a device that is not open so do not return an error */
610 (*(dpriv->device))->Release (dpriv->device);
611 dpriv->device = NULL;
612 return darwin_to_libusb (kresult);
617 /* create async event source */
618 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
620 CFRetain (libusb_darwin_acfl);
622 /* add the cfSource to the aync run loop */
623 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
627 /* device opened successfully */
630 /* create a file descriptor for notifications */
633 /* set the pipe to be non-blocking */
634 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
636 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
638 usbi_info (HANDLE_CTX (dev_handle), "device open for access");
643 static void darwin_close (struct libusb_device_handle *dev_handle) {
644 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
645 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
649 if (dpriv->open_count == 0) {
650 /* something is probably very wrong if this is the case */
651 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!\n");
657 /* make sure all interfaces are released */
658 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
659 if (dev_handle->claimed_interfaces & (1 << i))
660 libusb_release_interface (dev_handle, i);
662 if (0 == dpriv->open_count) {
664 /* delete the device's async event source */
665 if (priv->cfSource) {
666 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
667 CFRelease (priv->cfSource);
670 /* close the device */
671 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
673 /* Log the fact that we had a problem closing the file, however failing a
674 * close isn't really an error, so return success anyway */
675 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
679 kresult = (*(dpriv->device))->Release(dpriv->device);
681 /* Log the fact that we had a problem closing the file, however failing a
682 * close isn't really an error, so return success anyway */
683 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
686 dpriv->device = NULL;
689 /* file descriptors are maintained per-instance */
690 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
691 close (priv->fds[1]);
692 close (priv->fds[0]);
694 priv->fds[0] = priv->fds[1] = -1;
697 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
698 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
702 kresult = (*(dpriv->device))->GetConfiguration (dpriv->device, &configNum);
703 if (kresult != kIOReturnSuccess)
704 return darwin_to_libusb (kresult);
706 *config = (int) configNum;
711 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
712 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
716 /* Setting configuration will invalidate the interface, so we need
717 to reclaim it. First, dispose of existing interfaces, if any. */
718 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
719 if (dev_handle->claimed_interfaces & (1 << i))
720 darwin_release_interface (dev_handle, i);
722 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
723 if (kresult != kIOReturnSuccess)
724 return darwin_to_libusb (kresult);
726 /* Reclaim any interfaces. */
727 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
728 if (dev_handle->claimed_interfaces & (1 << i))
729 darwin_claim_interface (dev_handle, i);
734 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
735 IOUSBFindInterfaceRequest request;
736 uint8_t current_interface;
737 kern_return_t kresult;
738 io_iterator_t interface_iterator;
740 *usbInterfacep = IO_OBJECT_NULL;
742 /* Setup the Interface Request */
743 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
744 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
745 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
746 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
748 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
752 for ( current_interface = 0 ; current_interface <= ifc ; current_interface++ ) {
753 *usbInterfacep = IOIteratorNext(interface_iterator);
754 if (current_interface != ifc)
755 (void) IOObjectRelease (*usbInterfacep);
758 /* done with the interface iterator */
759 IOObjectRelease(interface_iterator);
764 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
765 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
767 /* current interface */
768 struct __darwin_interface *cInterface = &priv->interfaces[iface];
770 kern_return_t kresult;
772 u_int8_t numep, direction, number;
773 u_int8_t dont_care1, dont_care3;
774 u_int16_t dont_care2;
777 usbi_info (HANDLE_CTX (dev_handle), "building table of endpoints.");
779 /* retrieve the total number of endpoints on this interface */
780 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
782 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
783 return darwin_to_libusb (kresult);
786 /* iterate through pipe references */
787 for (i = 1 ; i <= numep ; i++) {
788 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
789 &dont_care2, &dont_care3);
791 if (kresult != kIOReturnSuccess) {
792 usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
794 return darwin_to_libusb (kresult);
797 usbi_info (HANDLE_CTX (dev_handle), "interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
799 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
802 cInterface->num_endpoints = numep;
807 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
808 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
809 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
810 io_service_t usbInterface = IO_OBJECT_NULL;
812 IOCFPlugInInterface **plugInInterface = NULL;
816 /* current interface */
817 struct __darwin_interface *cInterface = &priv->interfaces[iface];
819 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
820 if (kresult != kIOReturnSuccess)
821 return darwin_to_libusb (kresult);
823 /* make sure we have an interface */
825 u_int8_t nConfig; /* Index of configuration to use */
826 IOUSBConfigurationDescriptorPtr configDesc; /* to describe which configuration to select */
827 /* Only a composite class device with no vendor-specific driver will
828 be configured. Otherwise, we need to do it ourselves, or there
829 will be no interfaces for the device. */
831 usbi_info (HANDLE_CTX (dev_handle), "no interface found; selecting configuration" );
833 kresult = (*(dpriv->device))->GetNumberOfConfigurations (dpriv->device, &nConfig);
834 if (kresult != kIOReturnSuccess) {
835 usbi_err (HANDLE_CTX (dev_handle), "GetNumberOfConfigurations: %s", darwin_error_str(kresult));
836 return darwin_to_libusb(kresult);
840 usbi_err (HANDLE_CTX (dev_handle), "GetNumberOfConfigurations: no configurations");
841 return LIBUSB_ERROR_OTHER;
844 usbi_info (HANDLE_CTX (dev_handle), "device has %d configuration%s. using the first",
845 (int)nConfig, (nConfig > 1 ? "s" : "") );
847 /* Always use the first configuration */
848 kresult = (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, 0, &configDesc);
849 if (kresult != kIOReturnSuccess) {
850 usbi_err (HANDLE_CTX (dev_handle), "GetConfigurationDescriptorPtr: %s",
851 darwin_error_str(kresult));
855 new_config = configDesc->bConfigurationValue;
857 usbi_info (HANDLE_CTX (dev_handle), "new configuration value is %d", new_config);
859 /* set the configuration */
860 kresult = darwin_set_configuration (dev_handle, new_config);
861 if (kresult != LIBUSB_SUCCESS) {
862 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
866 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
868 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
869 return darwin_to_libusb (kresult);
874 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
875 return LIBUSB_ERROR_NOT_FOUND;
878 /* get an interface to the device's interface */
879 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
880 kIOCFPlugInInterfaceID, &plugInInterface, &score);
882 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
883 return darwin_to_libusb (kresult);
886 if (!plugInInterface) {
887 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
888 return LIBUSB_ERROR_NOT_FOUND;
891 /* ignore release error */
892 (void)IOObjectRelease (usbInterface);
894 /* Do the actual claim */
895 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
896 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
897 (LPVOID)&cInterface->interface);
898 if (kresult || !cInterface->interface) {
899 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
900 return darwin_to_libusb (kresult);
903 /* We no longer need the intermediate plug-in */
904 (*plugInInterface)->Release(plugInInterface);
906 /* claim the interface */
907 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
909 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
910 return darwin_to_libusb (kresult);
913 /* update list of endpoints */
914 kresult = get_endpoints (dev_handle, iface);
916 /* this should not happen */
917 darwin_release_interface (dev_handle, iface);
918 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
922 cInterface->cfSource = NULL;
924 /* create async event source */
925 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
926 if (kresult != kIOReturnSuccess) {
927 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
929 /* can't continue without an async event source */
930 (void)darwin_release_interface (dev_handle, iface);
932 return darwin_to_libusb (kresult);
935 /* add the cfSource to the async thread's run loop */
936 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
938 usbi_info (HANDLE_CTX (dev_handle), "interface opened");
943 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
944 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
947 /* current interface */
948 struct __darwin_interface *cInterface = &priv->interfaces[iface];
950 /* Check to see if an interface is open */
951 if (!cInterface->interface)
952 return LIBUSB_SUCCESS;
954 /* clean up endpoint data */
955 cInterface->num_endpoints = 0;
957 /* delete the interface's async event source */
958 if (cInterface->cfSource) {
959 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
960 CFRelease (cInterface->cfSource);
963 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
965 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
967 kresult = (*(cInterface->interface))->Release(cInterface->interface);
968 if (kresult != kIOReturnSuccess)
969 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
971 cInterface->interface = IO_OBJECT_NULL;
973 return darwin_to_libusb (kresult);
976 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
977 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
980 /* current interface */
981 struct __darwin_interface *cInterface = &priv->interfaces[iface];
983 if (!cInterface->interface)
984 return LIBUSB_ERROR_NO_DEVICE;
986 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
987 if (kresult != kIOReturnSuccess)
988 darwin_reset_device (dev_handle);
990 /* update list of endpoints */
991 kresult = get_endpoints (dev_handle, iface);
993 /* this should not happen */
994 darwin_release_interface (dev_handle, iface);
995 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
999 return darwin_to_libusb (kresult);
1002 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1003 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1005 /* current interface */
1006 struct __darwin_interface *cInterface;
1007 uint8_t pipeRef, iface;
1010 /* determine the interface/endpoint to use */
1011 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
1012 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1014 return LIBUSB_ERROR_NOT_FOUND;
1017 cInterface = &priv->interfaces[iface];
1019 #if (InterfaceVersion < 190)
1020 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1022 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1023 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1026 usbi_err (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1028 return darwin_to_libusb (kresult);
1031 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1032 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1035 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1037 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1039 return darwin_to_libusb (kresult);
1042 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1043 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1044 io_service_t usbInterface;
1048 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1050 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1052 return darwin_to_libusb (kresult);
1055 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1056 IOObjectRelease (usbInterface);
1068 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1069 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1070 return LIBUSB_ERROR_NOT_SUPPORTED;
1073 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1074 return LIBUSB_ERROR_NOT_SUPPORTED;
1077 static void darwin_destroy_device(struct libusb_device *dev) {
1080 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1081 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1082 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1085 uint8_t is_read; /* 0 = we're reading, 1 = we're writing */
1086 uint8_t transferType;
1087 /* None of the values below are used in libusb for bulk transfers */
1088 uint8_t direction, number, interval, pipeRef, iface;
1089 uint16_t maxPacketSize;
1091 struct __darwin_interface *cInterface;
1093 /* are we reading or writing? */
1094 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1096 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1097 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1099 return LIBUSB_ERROR_NOT_FOUND;
1102 cInterface = &priv->interfaces[iface];
1104 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1105 &transferType, &maxPacketSize, &interval);
1107 /* submit the request */
1108 /* timeouts are unavailable on interrupt endpoints */
1109 if (transferType == kUSBInterrupt) {
1111 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1112 transfer->length, darwin_async_io_callback, itransfer);
1114 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1115 transfer->length, darwin_async_io_callback, itransfer);
1118 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1119 transfer->length, transfer->timeout, transfer->timeout,
1120 darwin_async_io_callback, (void *)itransfer);
1122 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1123 transfer->length, transfer->timeout, transfer->timeout,
1124 darwin_async_io_callback, (void *)itransfer);
1128 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", is_read ? "In" : "Out",
1129 darwin_error_str(ret), ret);
1131 return darwin_to_libusb (ret);
1134 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1135 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1136 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1137 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1140 uint8_t is_read; /* 0 = we're writing, 1 = we're reading */
1141 uint8_t pipeRef, iface;
1143 AbsoluteTime atTime;
1146 struct __darwin_interface *cInterface;
1148 /* are we reading or writing? */
1149 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1151 /* construct an array of IOUSBIsocFrames */
1152 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1153 if (!tpriv->isoc_framelist)
1154 return LIBUSB_ERROR_NO_MEM;
1156 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1157 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1158 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1160 /* determine the interface/endpoint to use */
1161 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1162 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1164 return LIBUSB_ERROR_NOT_FOUND;
1167 cInterface = &priv->interfaces[iface];
1169 /* Last but not least we need the bus frame number */
1170 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1172 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1173 free(tpriv->isoc_framelist);
1174 tpriv->isoc_framelist = NULL;
1176 return darwin_to_libusb (kresult);
1179 /* schedule for a frame a little in the future */
1182 /* submit the request */
1184 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1185 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1188 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1189 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1192 if (kresult != kIOReturnSuccess) {
1193 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", is_read ? "In" : "Out",
1194 darwin_error_str(kresult));
1195 free (tpriv->isoc_framelist);
1196 tpriv->isoc_framelist = NULL;
1199 return darwin_to_libusb (kresult);
1202 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1203 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1204 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1205 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1206 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1210 bzero(&tpriv->req, sizeof(tpriv->req));
1212 /* IOUSBDeviceInterface expects the request in cpu endianess */
1213 tpriv->req.bmRequestType = setup->bmRequestType;
1214 tpriv->req.bRequest = setup->bRequest;
1215 /* these values should be in bus order from libusb_fill_control_setup */
1216 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1217 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1218 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1219 /* data is stored after the libusb control block */
1220 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1221 tpriv->req.completionTimeout = transfer->timeout;
1222 tpriv->req.noDataTimeout = transfer->timeout;
1224 /* all transfers in libusb-1.0 are async */
1225 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1227 if (kresult != kIOReturnSuccess)
1228 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1230 return darwin_to_libusb (kresult);
1233 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1234 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1236 switch (transfer->type) {
1237 case LIBUSB_TRANSFER_TYPE_CONTROL:
1238 return submit_control_transfer(itransfer);
1239 case LIBUSB_TRANSFER_TYPE_BULK:
1240 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1241 return submit_bulk_transfer(itransfer);
1242 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1243 return submit_iso_transfer(itransfer);
1245 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1246 return LIBUSB_ERROR_INVALID_PARAM;
1250 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1251 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1252 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1255 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions control pipe");
1257 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1259 return darwin_to_libusb (kresult);
1262 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1263 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1264 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1265 struct __darwin_interface *cInterface;
1266 uint8_t pipeRef, iface;
1269 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1270 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1272 return LIBUSB_ERROR_NOT_FOUND;
1275 cInterface = &priv->interfaces[iface];
1277 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions on interface %d pipe %d", iface, pipeRef);
1279 /* abort transactions */
1280 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1282 usbi_info (ITRANSFER_CTX (itransfer), "calling clear pipe stall to clear the data toggle bit");
1284 /* clear the data toggle bit */
1285 #if (InterfaceVersion < 190)
1286 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1288 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1289 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1292 return darwin_to_libusb (kresult);
1295 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1296 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1298 switch (transfer->type) {
1299 case LIBUSB_TRANSFER_TYPE_CONTROL:
1300 return cancel_control_transfer(itransfer);
1301 case LIBUSB_TRANSFER_TYPE_BULK:
1302 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1303 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1304 return darwin_abort_transfers (itransfer);
1306 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1307 return LIBUSB_ERROR_INVALID_PARAM;
1311 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1312 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1313 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1315 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1316 free (tpriv->isoc_framelist);
1317 tpriv->isoc_framelist = NULL;
1321 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1322 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1323 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1324 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1327 usbi_info (ITRANSFER_CTX (itransfer), "an async io operation has completed");
1329 /* send a completion message to the device's file descriptor */
1330 message = MESSAGE_ASYNC_IO_COMPLETE;
1331 write (priv->fds[1], &message, sizeof (message));
1332 write (priv->fds[1], &itransfer, sizeof (itransfer));
1333 write (priv->fds[1], &result, sizeof (IOReturn));
1334 write (priv->fds[1], &arg0, sizeof (UInt32));
1337 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1339 case kIOReturnUnderrun:
1340 case kIOReturnSuccess:
1341 return LIBUSB_TRANSFER_COMPLETED;
1342 case kIOReturnAborted:
1343 return LIBUSB_TRANSFER_CANCELLED;
1344 case kIOUSBPipeStalled:
1345 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: pipe is stalled");
1346 return LIBUSB_TRANSFER_STALL;
1347 case kIOReturnOverrun:
1348 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1349 return LIBUSB_TRANSFER_OVERFLOW;
1350 case kIOUSBTransactionTimeout:
1351 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1352 return LIBUSB_TRANSFER_TIMED_OUT;
1354 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1355 return LIBUSB_TRANSFER_ERROR;
1359 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1360 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1361 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1362 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1363 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1364 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1365 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1368 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1369 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1373 usbi_info (ITRANSFER_CTX (itransfer), "handling %s completion with kernel status %d",
1374 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", result);
1376 if (kIOReturnSuccess == result || kIOReturnUnderrun == result) {
1377 if (isIsoc && tpriv->isoc_framelist) {
1378 /* copy isochronous results back */
1380 for (i = 0; i < transfer->num_iso_packets ; i++) {
1381 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1382 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1383 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1386 itransfer->transferred += io_size;
1389 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1390 usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, result));
1393 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, nfds_t nfds, int num_ready) {
1394 struct usbi_transfer *itransfer;
1400 usbi_mutex_lock(&ctx->open_devs_lock);
1401 for (i = 0; i < nfds && num_ready > 0; i++) {
1402 struct pollfd *pollfd = &fds[i];
1403 struct libusb_device_handle *handle;
1404 struct darwin_device_handle_priv *hpriv = NULL;
1406 usbi_info (ctx, "checking fd %i with revents = %x", fds[i], pollfd->revents);
1408 if (!pollfd->revents)
1412 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
1413 hpriv = (struct darwin_device_handle_priv *)handle->os_priv;
1414 if (hpriv->fds[0] == pollfd->fd)
1418 if (!(pollfd->revents & POLLERR)) {
1419 ret = read (hpriv->fds[0], &message, sizeof (message));
1420 if (ret < sizeof (message))
1423 /* could not poll the device-- response is to delete the device (this seems a little heavy-handed) */
1424 message = MESSAGE_DEVICE_GONE;
1427 case MESSAGE_DEVICE_GONE:
1428 /* remove the device's async port from the runloop */
1429 if (hpriv->cfSource) {
1430 if (libusb_darwin_acfl)
1431 CFRunLoopRemoveSource (libusb_darwin_acfl, hpriv->cfSource, kCFRunLoopDefaultMode);
1432 CFRelease (hpriv->cfSource);
1433 hpriv->cfSource = NULL;
1436 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
1437 usbi_handle_disconnect(handle);
1439 /* done with this device */
1441 case MESSAGE_ASYNC_IO_COMPLETE:
1442 read (hpriv->fds[0], &itransfer, sizeof (itransfer));
1443 read (hpriv->fds[0], &kresult, sizeof (IOReturn));
1444 read (hpriv->fds[0], &io_size, sizeof (UInt32));
1446 darwin_handle_callback (itransfer, kresult, io_size);
1449 usbi_err (ctx, "unknown message received from device pipe");
1453 usbi_mutex_unlock(&ctx->open_devs_lock);
1458 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1459 mach_timespec_t sys_time;
1460 clock_serv_t clock_ref;
1463 case USBI_CLOCK_REALTIME:
1464 /* CLOCK_REALTIME represents time since the epoch */
1465 host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &clock_ref);
1467 case USBI_CLOCK_MONOTONIC:
1468 /* use system boot time as reference for the monotonic clock */
1469 host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &clock_ref);
1472 return LIBUSB_ERROR_INVALID_PARAM;
1475 clock_get_time (clock_ref, &sys_time);
1477 tp->tv_sec = sys_time.tv_sec;
1478 tp->tv_nsec = sys_time.tv_nsec;
1483 const struct usbi_os_backend darwin_backend = {
1485 .init = darwin_init,
1486 .exit = darwin_exit,
1487 .get_device_list = darwin_get_device_list,
1488 .get_device_descriptor = darwin_get_device_descriptor,
1489 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1490 .get_config_descriptor = darwin_get_config_descriptor,
1492 .open = darwin_open,
1493 .close = darwin_close,
1494 .get_configuration = darwin_get_configuration,
1495 .set_configuration = darwin_set_configuration,
1496 .claim_interface = darwin_claim_interface,
1497 .release_interface = darwin_release_interface,
1499 .set_interface_altsetting = darwin_set_interface_altsetting,
1500 .clear_halt = darwin_clear_halt,
1501 .reset_device = darwin_reset_device,
1503 .kernel_driver_active = darwin_kernel_driver_active,
1504 .detach_kernel_driver = darwin_detach_kernel_driver,
1505 .attach_kernel_driver = darwin_attach_kernel_driver,
1507 .destroy_device = darwin_destroy_device,
1509 .submit_transfer = darwin_submit_transfer,
1510 .cancel_transfer = darwin_cancel_transfer,
1511 .clear_transfer_priv = darwin_clear_transfer_priv,
1513 .handle_events = op_handle_events,
1515 .clock_gettime = darwin_clock_gettime,
1517 .device_priv_size = sizeof(struct darwin_device_priv),
1518 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1519 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1520 .add_iso_packet_size = 0,