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 kIOReturnSuccess:
94 return LIBUSB_SUCCESS;
95 case kIOReturnNotOpen:
96 case kIOReturnNoDevice:
97 return LIBUSB_ERROR_NO_DEVICE;
98 case kIOReturnExclusiveAccess:
99 return LIBUSB_ERROR_ACCESS;
100 case kIOUSBPipeStalled:
101 return LIBUSB_ERROR_PIPE;
102 case kIOReturnBadArgument:
103 return LIBUSB_ERROR_INVALID_PARAM;
104 case kIOUSBTransactionTimeout:
105 return LIBUSB_ERROR_TIMEOUT;
106 case kIOReturnNotResponding:
107 case kIOReturnAborted:
109 case kIOUSBNoAsyncPortErr:
111 return LIBUSB_ERROR_OTHER;
116 static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp) {
117 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
119 /* current interface */
120 struct __darwin_interface *cInterface;
124 usbi_info (HANDLE_CTX(dev_handle), "converting ep address 0x%02x to pipeRef and interface", ep);
126 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
127 cInterface = &priv->interfaces[iface];
129 if (dev_handle->claimed_interfaces & (1 << iface)) {
130 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
131 if (cInterface->endpoint_addrs[i] == ep) {
134 usbi_info (HANDLE_CTX(dev_handle), "pipe %d on interface %d matches", *pipep, *ifcp);
141 /* No pipe found with the correct endpoint address */
142 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
147 static int usb_setup_device_iterator (io_iterator_t *deviceIterator) {
148 return IOServiceGetMatchingServices(libusb_darwin_mp, IOServiceMatching(kIOUSBDeviceClassName), deviceIterator);
151 static usb_device_t **usb_get_next_device (io_iterator_t deviceIterator, UInt32 *locationp) {
152 io_cf_plugin_ref_t *plugInInterface = NULL;
153 usb_device_t **device;
154 io_service_t usbDevice;
158 if (!IOIteratorIsValid (deviceIterator))
162 while ((usbDevice = IOIteratorNext(deviceIterator))) {
163 result = IOCreatePlugInInterfaceForService(usbDevice, kIOUSBDeviceUserClientTypeID,
164 kIOCFPlugInInterfaceID, &plugInInterface,
166 if (kIOReturnSuccess == result && plugInInterface)
169 usbi_dbg ("libusb/darwin.c usb_get_next_device: could not set up plugin for service: %s\n", darwin_error_str (result));
175 (void)IOObjectRelease(usbDevice);
176 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
179 (*plugInInterface)->Stop(plugInInterface);
180 IODestroyPlugInInterface (plugInInterface);
182 /* get the location from the device */
184 (*(device))->GetLocationID(device, locationp);
189 static kern_return_t darwin_get_device (uint32_t dev_location, usb_device_t ***darwin_device) {
190 kern_return_t kresult;
192 io_iterator_t deviceIterator;
194 kresult = usb_setup_device_iterator (&deviceIterator);
198 /* This port of libusb uses locations to keep track of devices. */
199 while ((*darwin_device = usb_get_next_device (deviceIterator, &location)) != NULL) {
200 if (location == dev_location)
203 (**darwin_device)->Release(*darwin_device);
206 IOObjectRelease (deviceIterator);
208 if (!(*darwin_device))
209 return kIOReturnNoDevice;
211 return kIOReturnSuccess;
216 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
217 struct libusb_context *ctx = (struct libusb_context *)ptr;
218 struct libusb_device_handle *handle;
219 struct darwin_device_priv *dpriv;
220 struct darwin_device_handle_priv *priv;
224 CFTypeRef locationCF;
227 usbi_info (ctx, "a device has been detached");
229 while ((device = IOIteratorNext (rem_devices)) != 0) {
230 /* get the location from the i/o registry */
231 locationCF = IORegistryEntryCreateCFProperty (device, CFSTR(kUSBDevicePropertyLocationID), kCFAllocatorDefault, 0);
233 CFNumberGetValue(locationCF, kCFNumberLongType, &location);
234 CFRelease (locationCF);
235 IOObjectRelease (device);
237 usbi_mutex_lock(&ctx->open_devs_lock);
238 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
239 dpriv = (struct darwin_device_priv *)handle->dev->os_priv;
241 /* the device may have been opened several times. write to each handle's event descriptor */
242 if (dpriv->location == location && handle->os_priv) {
243 priv = (struct darwin_device_handle_priv *)handle->os_priv;
245 message = MESSAGE_DEVICE_GONE;
246 write (priv->fds[1], &message, sizeof (message));
250 usbi_mutex_unlock(&ctx->open_devs_lock);
254 static void darwin_clear_iterator (io_iterator_t iter) {
257 while ((device = IOIteratorNext (iter)) != 0)
258 IOObjectRelease (device);
261 static void *event_thread_main (void *arg0) {
263 struct libusb_context *ctx = (struct libusb_context *)arg0;
265 /* hotplug (device removal) source */
266 CFRunLoopSourceRef libusb_notification_cfsource;
267 io_notification_port_t libusb_notification_port;
268 io_iterator_t libusb_rem_device_iterator;
270 usbi_info (ctx, "creating hotplug event source");
272 CFRetain (CFRunLoopGetCurrent ());
274 /* add the notification port to the run loop */
275 libusb_notification_port = IONotificationPortCreate (libusb_darwin_mp);
276 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
277 CFRunLoopAddSource(CFRunLoopGetCurrent (), libusb_notification_cfsource, kCFRunLoopDefaultMode);
279 /* create notifications for removed devices */
280 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
281 IOServiceMatching(kIOUSBDeviceClassName),
282 (IOServiceMatchingCallback)darwin_devices_detached,
283 (void *)ctx, &libusb_rem_device_iterator);
285 if (kresult != kIOReturnSuccess) {
286 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
288 pthread_exit ((void *)kresult);
292 darwin_clear_iterator (libusb_rem_device_iterator);
294 /* let the main thread know about the async runloop */
295 libusb_darwin_acfl = CFRunLoopGetCurrent ();
297 usbi_info (ctx, "libopenusb/darwin.c event_thread_main: thread ready to receive events");
299 /* run the runloop */
302 usbi_info (ctx, "libopenusb/darwin.c event_thread_main: thread exiting");
304 /* delete notification port */
305 CFRunLoopSourceInvalidate (libusb_notification_cfsource);
306 IONotificationPortDestroy (libusb_notification_port);
308 CFRelease (CFRunLoopGetCurrent ());
310 libusb_darwin_acfl = NULL;
315 static int darwin_init(struct libusb_context *ctx) {
318 if (!(initCount++)) {
319 /* Create the master port for talking to IOKit */
320 if (!libusb_darwin_mp) {
321 kresult = IOMasterPort (MACH_PORT_NULL, &libusb_darwin_mp);
323 if (kresult != kIOReturnSuccess || !libusb_darwin_mp)
324 return darwin_to_libusb (kresult);
327 pthread_create (&libusb_darwin_at, NULL, event_thread_main, (void *)ctx);
329 while (!libusb_darwin_acfl)
336 static void darwin_exit (void) {
337 if (!(--initCount)) {
340 /* stop the async runloop */
341 CFRunLoopStop (libusb_darwin_acfl);
342 pthread_join (libusb_darwin_at, &ret);
344 if (libusb_darwin_mp)
345 mach_port_deallocate(mach_task_self(), libusb_darwin_mp);
347 libusb_darwin_mp = 0;
351 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
352 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
354 /* return cached copy */
355 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
362 static int get_configuration_index (struct libusb_device *dev, int config_value) {
363 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
365 IOUSBConfigurationDescriptorPtr desc;
368 /* is there a simpler way to determine the index? */
369 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
370 if (kresult != kIOReturnSuccess)
371 return darwin_to_libusb (kresult);
373 for (i = 0 ; i < numConfig ; i++) {
374 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
376 if (libusb_le16_to_cpu (desc->bConfigurationValue) == config_value)
380 /* configuration not found */
381 return LIBUSB_ERROR_OTHER;
384 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
385 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
390 kresult = (*(priv->device))->GetConfiguration (priv->device, &config_value);
391 if (kresult != kIOReturnSuccess)
392 return darwin_to_libusb (kresult);
394 config_index = get_configuration_index (dev, config_value);
395 if (config_index < 0)
398 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
401 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
402 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
403 IOUSBConfigurationDescriptorPtr desc;
405 usb_device_t **device = NULL;
408 return LIBUSB_ERROR_OTHER;
411 kresult = darwin_get_device (priv->location, &device);
412 if (kresult || !device) {
413 usbi_err (DEVICE_CTX (dev), "could not find device: %s", darwin_error_str (kresult));
415 return darwin_to_libusb (kresult);
418 /* don't have to open the device to get a config descriptor */
420 device = priv->device;
422 kresult = (*device)->GetConfigurationDescriptorPtr (device, config_index, &desc);
423 if (kresult == kIOReturnSuccess) {
424 /* copy descriptor */
425 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
426 len = libusb_le16_to_cpu(desc->wTotalLength);
428 memmove (buffer, desc, len);
430 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
435 (*device)->Release (device);
437 return darwin_to_libusb (kresult);
440 static int process_new_device (struct libusb_context *ctx, usb_device_t **device, UInt32 locationID, struct discovered_devs **_discdevs) {
441 struct darwin_device_priv *priv;
442 struct libusb_device *dev;
443 struct discovered_devs *discdevs;
444 UInt16 address, idVendor, idProduct;
445 UInt8 bDeviceClass, bDeviceSubClass;
447 int ret = 0, need_unref = 0;
450 dev = usbi_get_device_by_session_id(ctx, locationID);
452 usbi_info (ctx, "allocating new device for location 0x%08x", locationID);
453 dev = usbi_alloc_device(ctx, locationID);
456 usbi_info (ctx, "using existing device for location 0x%08x", locationID);
459 ret = LIBUSB_ERROR_NO_MEM;
463 priv = (struct darwin_device_priv *)dev->os_priv;
465 /* Set up request for device descriptor */
466 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
467 req.bRequest = kUSBRqGetDescriptor;
468 req.wValue = kUSBDeviceDesc << 8;
470 req.wLength = sizeof(IOUSBDeviceDescriptor);
471 req.pData = &(priv->dev_descriptor);
473 (*(device))->GetDeviceAddress (device, (USBDeviceAddress *)&address);
474 (*(device))->GetDeviceProduct (device, &idProduct);
475 (*(device))->GetDeviceVendor (device, &idVendor);
476 (*(device))->GetDeviceClass (device, &bDeviceClass);
477 (*(device))->GetDeviceSubClass (device, &bDeviceSubClass);
479 /**** retrieve device descriptors ****/
480 /* according to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
481 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request */
482 ret = (*(device))->DeviceRequest (device, &req);
483 if (ret != kIOReturnSuccess) {
484 int try_unsuspend = 1;
485 #if DeviceVersion >= 320
488 /* device may be suspended. unsuspend it and try again */
489 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
490 (void)(*device)->GetUSBDeviceInformation (device, &info);
492 try_unsuspend = info & (1 << kUSBInformationDeviceIsSuspendedBit);
495 /* the device should be open before to device is unsuspended */
496 (void) (*device)->USBDeviceOpenSeize(device);
499 /* resume the device */
500 (void)(*device)->USBDeviceSuspend (device, 0);
502 ret = (*(device))->DeviceRequest (device, &req);
504 /* resuspend the device */
505 (void)(*device)->USBDeviceSuspend (device, 1);
508 (*device)->USBDeviceClose (device);
511 if (ret != kIOReturnSuccess) {
512 usbi_warn (ctx, "could not retrieve device descriptor: %s. skipping device", darwin_error_str (ret));
517 /**** end: retrieve device descriptors ****/
519 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
520 if (libusb_le16_to_cpu (priv->dev_descriptor.idProduct) != idProduct) {
521 /* not a valid device */
522 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
523 idProduct, libusb_le16_to_cpu (priv->dev_descriptor.idProduct));
528 dev->bus_number = locationID >> 24;
529 dev->device_address = address;
531 /* save our location, we'll need this later */
532 priv->location = locationID;
533 snprintf(priv->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", address, idVendor, idProduct, bDeviceClass, bDeviceSubClass);
535 ret = usbi_sanitize_device (dev);
539 /* append the device to the list of discovered devices */
540 discdevs = discovered_devs_append(*_discdevs, dev);
542 ret = LIBUSB_ERROR_NO_MEM;
546 *_discdevs = discdevs;
548 usbi_info (ctx, "found device with address %d at %s", dev->device_address, priv->sys_path);
552 libusb_unref_device(dev);
557 static int darwin_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs) {
558 io_iterator_t deviceIterator;
559 usb_device_t **device;
560 kern_return_t kresult;
563 if (!libusb_darwin_mp)
564 return LIBUSB_ERROR_INVALID_PARAM;
566 kresult = usb_setup_device_iterator (&deviceIterator);
567 if (kresult != kIOReturnSuccess)
568 return darwin_to_libusb (kresult);
570 while ((device = usb_get_next_device (deviceIterator, &location)) != NULL) {
571 (void) process_new_device (ctx, device, location, _discdevs);
573 (*(device))->Release(device);
576 IOObjectRelease(deviceIterator);
581 static int darwin_open (struct libusb_device_handle *dev_handle) {
582 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
583 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
584 usb_device_t **darwin_device;
587 if (0 == dpriv->open_count) {
588 kresult = darwin_get_device (dpriv->location, &darwin_device);
590 usbi_err (HANDLE_CTX (dev_handle), "could not find device: %s", darwin_error_str (kresult));
591 return darwin_to_libusb (kresult);
594 dpriv->device = darwin_device;
596 /* try to open the device */
597 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
599 if (kresult != kIOReturnSuccess) {
600 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
603 case kIOReturnExclusiveAccess:
604 /* it is possible to perform some actions on a device that is not open so do not return an error */
609 (*(dpriv->device))->Release (dpriv->device);
610 dpriv->device = NULL;
611 return darwin_to_libusb (kresult);
616 /* create async event source */
617 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
619 CFRetain (libusb_darwin_acfl);
621 /* add the cfSource to the aync run loop */
622 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
626 /* device opened successfully */
629 /* create a file descriptor for notifications */
632 /* set the pipe to be non-blocking */
633 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
635 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
637 usbi_info (HANDLE_CTX (dev_handle), "device open for access");
642 static void darwin_close (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;
648 if (dpriv->open_count == 0) {
649 /* something is probably very wrong if this is the case */
650 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!\n");
656 /* make sure all interfaces are released */
657 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
658 if (dev_handle->claimed_interfaces & (1 << i))
659 libusb_release_interface (dev_handle, i);
661 if (0 == dpriv->open_count) {
663 /* delete the device's async event source */
664 if (priv->cfSource) {
665 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
666 CFRelease (priv->cfSource);
669 /* close the device */
670 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
672 /* Log the fact that we had a problem closing the file, however failing a
673 * close isn't really an error, so return success anyway */
674 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
678 kresult = (*(dpriv->device))->Release(dpriv->device);
680 /* Log the fact that we had a problem closing the file, however failing a
681 * close isn't really an error, so return success anyway */
682 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
685 dpriv->device = NULL;
688 /* file descriptors are maintained per-instance */
689 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
690 close (priv->fds[1]);
691 close (priv->fds[0]);
693 priv->fds[0] = priv->fds[1] = -1;
696 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
697 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
701 kresult = (*(dpriv->device))->GetConfiguration (dpriv->device, &configNum);
702 if (kresult != kIOReturnSuccess)
703 return darwin_to_libusb (kresult);
705 *config = (int) configNum;
710 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
711 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
715 /* Setting configuration will invalidate the interface, so we need
716 to reclaim it. First, dispose of existing interfaces, if any. */
717 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
718 if (dev_handle->claimed_interfaces & (1 << i))
719 darwin_release_interface (dev_handle, i);
721 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
722 if (kresult != kIOReturnSuccess)
723 return darwin_to_libusb (kresult);
725 /* Reclaim any interfaces. */
726 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
727 if (dev_handle->claimed_interfaces & (1 << i))
728 darwin_claim_interface (dev_handle, i);
733 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
734 IOUSBFindInterfaceRequest request;
735 uint8_t current_interface;
736 kern_return_t kresult;
737 io_iterator_t interface_iterator;
739 *usbInterfacep = IO_OBJECT_NULL;
741 /* Setup the Interface Request */
742 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
743 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
744 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
745 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
747 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
751 for ( current_interface = 0 ; current_interface <= ifc ; current_interface++ )
752 *usbInterfacep = IOIteratorNext(interface_iterator);
754 /* done with the interface iterator */
755 IOObjectRelease(interface_iterator);
760 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
761 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
763 /* current interface */
764 struct __darwin_interface *cInterface = &priv->interfaces[iface];
766 kern_return_t kresult;
768 u_int8_t numep, direction, number;
769 u_int8_t dont_care1, dont_care3;
770 u_int16_t dont_care2;
773 usbi_info (HANDLE_CTX (dev_handle), "building table of endpoints.");
775 /* retrieve the total number of endpoints on this interface */
776 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
778 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
779 return darwin_to_libusb (kresult);
782 /* iterate through pipe references */
783 for (i = 1 ; i <= numep ; i++) {
784 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
785 &dont_care2, &dont_care3);
787 if (kresult != kIOReturnSuccess) {
788 usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
790 return darwin_to_libusb (kresult);
793 usbi_info (HANDLE_CTX (dev_handle), "interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
795 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
798 cInterface->num_endpoints = numep;
803 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
804 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
805 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
806 io_service_t usbInterface = IO_OBJECT_NULL;
808 IOCFPlugInInterface **plugInInterface = NULL;
812 /* current interface */
813 struct __darwin_interface *cInterface = &priv->interfaces[iface];
815 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
816 if (kresult != kIOReturnSuccess)
817 return darwin_to_libusb (kresult);
819 /* make sure we have an interface */
821 u_int8_t nConfig; /* Index of configuration to use */
822 IOUSBConfigurationDescriptorPtr configDesc; /* to describe which configuration to select */
823 /* Only a composite class device with no vendor-specific driver will
824 be configured. Otherwise, we need to do it ourselves, or there
825 will be no interfaces for the device. */
827 usbi_info (HANDLE_CTX (dev_handle), "no interface found; selecting configuration" );
829 kresult = (*(dpriv->device))->GetNumberOfConfigurations (dpriv->device, &nConfig);
830 if (kresult != kIOReturnSuccess) {
831 usbi_err (HANDLE_CTX (dev_handle), "GetNumberOfConfigurations: %s", darwin_error_str(kresult));
832 return darwin_to_libusb(kresult);
836 usbi_err (HANDLE_CTX (dev_handle), "GetNumberOfConfigurations: no configurations");
837 return LIBUSB_ERROR_OTHER;
840 usbi_info (HANDLE_CTX (dev_handle), "device has %d configuration%s. using the first",
841 (int)nConfig, (nConfig > 1 ? "s" : "") );
843 /* Always use the first configuration */
844 kresult = (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, 0, &configDesc);
845 if (kresult != kIOReturnSuccess) {
846 usbi_err (HANDLE_CTX (dev_handle), "GetConfigurationDescriptorPtr: %s",
847 darwin_error_str(kresult));
851 new_config = configDesc->bConfigurationValue;
853 usbi_info (HANDLE_CTX (dev_handle), "new configuration value is %d", new_config);
855 /* set the configuration */
856 kresult = darwin_set_configuration (dev_handle, new_config);
857 if (kresult != LIBUSB_SUCCESS) {
858 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
862 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
864 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
865 return darwin_to_libusb (kresult);
870 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
871 return LIBUSB_ERROR_NOT_FOUND;
874 /* get an interface to the device's interface */
875 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
876 kIOCFPlugInInterfaceID, &plugInInterface, &score);
878 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
879 return darwin_to_libusb (kresult);
882 if (!plugInInterface) {
883 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
884 return LIBUSB_ERROR_NOT_FOUND;
887 /* ignore release error */
888 (void)IOObjectRelease (usbInterface);
890 /* Do the actual claim */
891 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
892 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
893 (LPVOID)&cInterface->interface);
894 if (kresult || !cInterface->interface) {
895 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
896 return darwin_to_libusb (kresult);
899 /* We no longer need the intermediate plug-in */
900 (*plugInInterface)->Release(plugInInterface);
902 /* claim the interface */
903 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
905 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
906 return darwin_to_libusb (kresult);
909 /* update list of endpoints */
910 kresult = get_endpoints (dev_handle, iface);
912 /* this should not happen */
913 darwin_release_interface (dev_handle, iface);
914 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
918 cInterface->cfSource = NULL;
920 /* create async event source */
921 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
922 if (kresult != kIOReturnSuccess) {
923 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
925 /* can't continue without an async event source */
926 (void)darwin_release_interface (dev_handle, iface);
928 return darwin_to_libusb (kresult);
931 /* add the cfSource to the async thread's run loop */
932 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
934 usbi_info (HANDLE_CTX (dev_handle), "interface opened");
939 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
940 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
943 /* current interface */
944 struct __darwin_interface *cInterface = &priv->interfaces[iface];
946 /* Check to see if an interface is open */
947 if (!cInterface->interface)
948 return LIBUSB_SUCCESS;
950 /* clean up endpoint data */
951 cInterface->num_endpoints = 0;
953 /* delete the interface's async event source */
954 if (cInterface->cfSource) {
955 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
956 CFRelease (cInterface->cfSource);
959 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
961 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
963 kresult = (*(cInterface->interface))->Release(cInterface->interface);
964 if (kresult != kIOReturnSuccess)
965 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
967 cInterface->interface = IO_OBJECT_NULL;
969 return darwin_to_libusb (kresult);
972 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
973 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
976 /* current interface */
977 struct __darwin_interface *cInterface = &priv->interfaces[iface];
979 if (!cInterface->interface)
980 return LIBUSB_ERROR_NO_DEVICE;
982 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
983 if (kresult != kIOReturnSuccess)
984 darwin_reset_device (dev_handle);
986 /* update list of endpoints */
987 kresult = get_endpoints (dev_handle, iface);
989 /* this should not happen */
990 darwin_release_interface (dev_handle, iface);
991 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
995 return darwin_to_libusb (kresult);
998 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
999 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1001 /* current interface */
1002 struct __darwin_interface *cInterface;
1003 uint8_t pipeRef, iface;
1006 /* determine the interface/endpoint to use */
1007 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
1008 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1010 return LIBUSB_ERROR_NOT_FOUND;
1013 cInterface = &priv->interfaces[iface];
1015 #if (InterfaceVersion < 190)
1016 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1018 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1019 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1022 usbi_err (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1024 return darwin_to_libusb (kresult);
1027 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1028 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1031 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1033 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1035 return darwin_to_libusb (kresult);
1038 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1039 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1040 io_service_t usbInterface;
1044 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1046 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1048 return darwin_to_libusb (kresult);
1051 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1052 IOObjectRelease (usbInterface);
1064 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1065 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1066 return LIBUSB_ERROR_NOT_SUPPORTED;
1069 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1070 return LIBUSB_ERROR_NOT_SUPPORTED;
1073 static void darwin_destroy_device(struct libusb_device *dev) {
1076 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1077 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1078 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1081 uint8_t is_read; /* 0 = we're reading, 1 = we're writing */
1082 uint8_t transferType;
1083 /* None of the values below are used in libusb for bulk transfers */
1084 uint8_t direction, number, interval, pipeRef, iface;
1085 uint16_t maxPacketSize;
1087 struct __darwin_interface *cInterface;
1089 /* are we reading or writing? */
1090 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1092 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1093 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1095 return LIBUSB_ERROR_NOT_FOUND;
1098 cInterface = &priv->interfaces[iface];
1100 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1101 &transferType, &maxPacketSize, &interval);
1103 /* submit the request */
1104 /* timeouts are unavailable on interrupt endpoints */
1105 if (transferType == kUSBInterrupt) {
1107 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1108 transfer->length, darwin_async_io_callback, itransfer);
1110 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1111 transfer->length, darwin_async_io_callback, itransfer);
1114 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1115 transfer->length, transfer->timeout, transfer->timeout,
1116 darwin_async_io_callback, (void *)itransfer);
1118 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1119 transfer->length, transfer->timeout, transfer->timeout,
1120 darwin_async_io_callback, (void *)itransfer);
1124 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", is_read ? "In" : "Out",
1125 darwin_error_str(ret), ret);
1127 return darwin_to_libusb (ret);
1130 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1131 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1132 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1133 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1136 uint8_t is_read; /* 0 = we're writing, 1 = we're reading */
1137 uint8_t pipeRef, iface;
1139 AbsoluteTime atTime;
1142 struct __darwin_interface *cInterface;
1144 /* are we reading or writing? */
1145 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1147 /* construct an array of IOUSBIsocFrames */
1148 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1149 if (!tpriv->isoc_framelist)
1150 return LIBUSB_ERROR_NO_MEM;
1152 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1153 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1154 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1156 /* determine the interface/endpoint to use */
1157 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1158 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1160 return LIBUSB_ERROR_NOT_FOUND;
1163 cInterface = &priv->interfaces[iface];
1165 /* Last but not least we need the bus frame number */
1166 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1168 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1169 free(tpriv->isoc_framelist);
1170 tpriv->isoc_framelist = NULL;
1172 return darwin_to_libusb (kresult);
1175 /* schedule for a frame a little in the future */
1178 /* submit the request */
1180 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1181 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1184 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1185 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1188 if (kresult != kIOReturnSuccess) {
1189 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", is_read ? "In" : "Out",
1190 darwin_error_str(kresult));
1191 free (tpriv->isoc_framelist);
1192 tpriv->isoc_framelist = NULL;
1195 return darwin_to_libusb (kresult);
1198 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1199 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1200 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1201 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1202 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1206 bzero(&tpriv->req, sizeof(tpriv->req));
1208 /* IOUSBDeviceInterface expects the request in cpu endianess */
1209 tpriv->req.bmRequestType = setup->bmRequestType;
1210 tpriv->req.bRequest = setup->bRequest;
1211 /* these values should be in bus order from libusb_fill_control_setup */
1212 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1213 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1214 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1215 /* data is stored after the libusb control block */
1216 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1217 tpriv->req.completionTimeout = transfer->timeout;
1218 tpriv->req.noDataTimeout = transfer->timeout;
1220 /* all transfers in libusb-1.0 are async */
1221 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1223 if (kresult != kIOReturnSuccess)
1224 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1226 return darwin_to_libusb (kresult);
1229 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1230 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1232 switch (transfer->type) {
1233 case LIBUSB_TRANSFER_TYPE_CONTROL:
1234 return submit_control_transfer(itransfer);
1235 case LIBUSB_TRANSFER_TYPE_BULK:
1236 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1237 return submit_bulk_transfer(itransfer);
1238 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1239 return submit_iso_transfer(itransfer);
1241 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1242 return LIBUSB_ERROR_INVALID_PARAM;
1246 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1247 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1248 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1251 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions control pipe");
1253 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1255 return darwin_to_libusb (kresult);
1258 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1259 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1260 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1261 struct __darwin_interface *cInterface;
1262 uint8_t pipeRef, iface;
1265 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1266 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1268 return LIBUSB_ERROR_NOT_FOUND;
1271 cInterface = &priv->interfaces[iface];
1273 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions on interface %d pipe %d", iface, pipeRef);
1275 /* abort transactions */
1276 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1278 usbi_info (ITRANSFER_CTX (itransfer), "calling clear pipe stall to clear the data toggle bit");
1280 /* clear the data toggle bit */
1281 #if (InterfaceVersion < 190)
1282 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1284 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1285 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1288 return darwin_to_libusb (kresult);
1291 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1292 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1294 switch (transfer->type) {
1295 case LIBUSB_TRANSFER_TYPE_CONTROL:
1296 return cancel_control_transfer(itransfer);
1297 case LIBUSB_TRANSFER_TYPE_BULK:
1298 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1299 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1300 return darwin_abort_transfers (itransfer);
1302 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1303 return LIBUSB_ERROR_INVALID_PARAM;
1307 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1308 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1309 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1311 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1312 free (tpriv->isoc_framelist);
1313 tpriv->isoc_framelist = NULL;
1317 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1318 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1319 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1320 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1323 usbi_info (ITRANSFER_CTX (itransfer), "an async io operation has completed");
1325 /* send a completion message to the device's file descriptor */
1326 message = MESSAGE_ASYNC_IO_COMPLETE;
1327 write (priv->fds[1], &message, sizeof (message));
1328 write (priv->fds[1], &itransfer, sizeof (itransfer));
1329 write (priv->fds[1], &result, sizeof (IOReturn));
1330 write (priv->fds[1], &arg0, sizeof (UInt32));
1333 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1335 case kIOReturnSuccess:
1336 return LIBUSB_TRANSFER_COMPLETED;
1337 case kIOReturnAborted:
1338 return LIBUSB_TRANSFER_CANCELLED;
1339 case kIOUSBPipeStalled:
1340 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: pipe is stalled");
1341 return LIBUSB_TRANSFER_STALL;
1342 case kIOReturnOverrun:
1343 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: data overrun", darwin_error_str (result));
1344 return LIBUSB_TRANSFER_OVERFLOW;
1345 case kIOUSBTransactionTimeout:
1346 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1347 return LIBUSB_TRANSFER_TIMED_OUT;
1349 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1350 return LIBUSB_TRANSFER_ERROR;
1354 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1355 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1356 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1357 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1358 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1359 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1360 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1363 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1364 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1368 usbi_info (ITRANSFER_CTX (itransfer), "handling %s completion with kernel status %d",
1369 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", result);
1371 if (kIOReturnSuccess == result) {
1372 if (isIsoc && tpriv->isoc_framelist) {
1373 /* copy isochronous results back */
1375 for (i = 0; i < transfer->num_iso_packets ; i++) {
1376 struct libusb_iso_packet_descriptor *lib_desc = transfer->iso_packet_desc;
1377 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1378 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1381 itransfer->transferred += io_size;
1384 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1385 usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, result));
1388 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, nfds_t nfds, int num_ready) {
1389 struct usbi_transfer *itransfer;
1395 usbi_mutex_lock(&ctx->open_devs_lock);
1396 for (i = 0; i < nfds && num_ready > 0; i++) {
1397 struct pollfd *pollfd = &fds[i];
1398 struct libusb_device_handle *handle;
1399 struct darwin_device_handle_priv *hpriv = NULL;
1401 usbi_info (ctx, "checking fd %i with revents = %x", fds[i], pollfd->revents);
1403 if (!pollfd->revents)
1407 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
1408 hpriv = (struct darwin_device_handle_priv *)handle->os_priv;
1409 if (hpriv->fds[0] == pollfd->fd)
1413 if (!(pollfd->revents & POLLERR)) {
1414 ret = read (hpriv->fds[0], &message, sizeof (message));
1415 if (ret < sizeof (message))
1418 /* could not poll the device-- response is to delete the device (this seems a little heavy-handed) */
1419 message = MESSAGE_DEVICE_GONE;
1422 case MESSAGE_DEVICE_GONE:
1423 /* remove the device's async port from the runloop */
1424 if (hpriv->cfSource) {
1425 if (libusb_darwin_acfl)
1426 CFRunLoopRemoveSource (libusb_darwin_acfl, hpriv->cfSource, kCFRunLoopDefaultMode);
1427 CFRelease (hpriv->cfSource);
1428 hpriv->cfSource = NULL;
1431 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
1432 usbi_handle_disconnect(handle);
1434 /* done with this device */
1436 case MESSAGE_ASYNC_IO_COMPLETE:
1437 read (hpriv->fds[0], &itransfer, sizeof (itransfer));
1438 read (hpriv->fds[0], &kresult, sizeof (IOReturn));
1439 read (hpriv->fds[0], &io_size, sizeof (UInt32));
1441 darwin_handle_callback (itransfer, kresult, io_size);
1444 usbi_err (ctx, "unknown message received from device pipe");
1448 usbi_mutex_unlock(&ctx->open_devs_lock);
1453 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1454 mach_timespec_t sys_time;
1455 clock_serv_t clock_ref;
1458 case USBI_CLOCK_REALTIME:
1459 /* CLOCK_REALTIME represents time since the epoch */
1460 host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &clock_ref);
1462 case USBI_CLOCK_MONOTONIC:
1463 /* use system boot time as reference for the monotonic clock */
1464 host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &clock_ref);
1467 return LIBUSB_ERROR_INVALID_PARAM;
1470 clock_get_time (clock_ref, &sys_time);
1472 tp->tv_sec = sys_time.tv_sec;
1473 tp->tv_nsec = sys_time.tv_nsec;
1478 const struct usbi_os_backend darwin_backend = {
1480 .init = darwin_init,
1481 .exit = darwin_exit,
1482 .get_device_list = darwin_get_device_list,
1483 .get_device_descriptor = darwin_get_device_descriptor,
1484 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1485 .get_config_descriptor = darwin_get_config_descriptor,
1487 .open = darwin_open,
1488 .close = darwin_close,
1489 .get_configuration = darwin_get_configuration,
1490 .set_configuration = darwin_set_configuration,
1491 .claim_interface = darwin_claim_interface,
1492 .release_interface = darwin_release_interface,
1494 .set_interface_altsetting = darwin_set_interface_altsetting,
1495 .clear_halt = darwin_clear_halt,
1496 .reset_device = darwin_reset_device,
1498 .kernel_driver_active = darwin_kernel_driver_active,
1499 .detach_kernel_driver = darwin_detach_kernel_driver,
1500 .attach_kernel_driver = darwin_attach_kernel_driver,
1502 .destroy_device = darwin_destroy_device,
1504 .submit_transfer = darwin_submit_transfer,
1505 .cancel_transfer = darwin_cancel_transfer,
1506 .clear_transfer_priv = darwin_clear_transfer_priv,
1508 .handle_events = op_handle_events,
1510 .clock_gettime = darwin_clock_gettime,
1512 .device_priv_size = sizeof(struct darwin_device_priv),
1513 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1514 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1515 .add_iso_packet_size = 0,