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, "thread ready to receive events");
299 /* run the runloop */
302 usbi_info (ctx, "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);
753 if (current_interface != ifc)
754 (void) IOObjectRelease (*usbInterfacep);
757 /* done with the interface iterator */
758 IOObjectRelease(interface_iterator);
763 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
764 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
766 /* current interface */
767 struct __darwin_interface *cInterface = &priv->interfaces[iface];
769 kern_return_t kresult;
771 u_int8_t numep, direction, number;
772 u_int8_t dont_care1, dont_care3;
773 u_int16_t dont_care2;
776 usbi_info (HANDLE_CTX (dev_handle), "building table of endpoints.");
778 /* retrieve the total number of endpoints on this interface */
779 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
781 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
782 return darwin_to_libusb (kresult);
785 /* iterate through pipe references */
786 for (i = 1 ; i <= numep ; i++) {
787 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
788 &dont_care2, &dont_care3);
790 if (kresult != kIOReturnSuccess) {
791 usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
793 return darwin_to_libusb (kresult);
796 usbi_info (HANDLE_CTX (dev_handle), "interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
798 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
801 cInterface->num_endpoints = numep;
806 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
807 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
808 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
809 io_service_t usbInterface = IO_OBJECT_NULL;
811 IOCFPlugInInterface **plugInInterface = NULL;
815 /* current interface */
816 struct __darwin_interface *cInterface = &priv->interfaces[iface];
818 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
819 if (kresult != kIOReturnSuccess)
820 return darwin_to_libusb (kresult);
822 /* make sure we have an interface */
824 u_int8_t nConfig; /* Index of configuration to use */
825 IOUSBConfigurationDescriptorPtr configDesc; /* to describe which configuration to select */
826 /* Only a composite class device with no vendor-specific driver will
827 be configured. Otherwise, we need to do it ourselves, or there
828 will be no interfaces for the device. */
830 usbi_info (HANDLE_CTX (dev_handle), "no interface found; selecting configuration" );
832 kresult = (*(dpriv->device))->GetNumberOfConfigurations (dpriv->device, &nConfig);
833 if (kresult != kIOReturnSuccess) {
834 usbi_err (HANDLE_CTX (dev_handle), "GetNumberOfConfigurations: %s", darwin_error_str(kresult));
835 return darwin_to_libusb(kresult);
839 usbi_err (HANDLE_CTX (dev_handle), "GetNumberOfConfigurations: no configurations");
840 return LIBUSB_ERROR_OTHER;
843 usbi_info (HANDLE_CTX (dev_handle), "device has %d configuration%s. using the first",
844 (int)nConfig, (nConfig > 1 ? "s" : "") );
846 /* Always use the first configuration */
847 kresult = (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, 0, &configDesc);
848 if (kresult != kIOReturnSuccess) {
849 usbi_err (HANDLE_CTX (dev_handle), "GetConfigurationDescriptorPtr: %s",
850 darwin_error_str(kresult));
854 new_config = configDesc->bConfigurationValue;
856 usbi_info (HANDLE_CTX (dev_handle), "new configuration value is %d", new_config);
858 /* set the configuration */
859 kresult = darwin_set_configuration (dev_handle, new_config);
860 if (kresult != LIBUSB_SUCCESS) {
861 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
865 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
867 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
868 return darwin_to_libusb (kresult);
873 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
874 return LIBUSB_ERROR_NOT_FOUND;
877 /* get an interface to the device's interface */
878 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
879 kIOCFPlugInInterfaceID, &plugInInterface, &score);
881 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
882 return darwin_to_libusb (kresult);
885 if (!plugInInterface) {
886 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
887 return LIBUSB_ERROR_NOT_FOUND;
890 /* ignore release error */
891 (void)IOObjectRelease (usbInterface);
893 /* Do the actual claim */
894 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
895 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
896 (LPVOID)&cInterface->interface);
897 if (kresult || !cInterface->interface) {
898 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
899 return darwin_to_libusb (kresult);
902 /* We no longer need the intermediate plug-in */
903 (*plugInInterface)->Release(plugInInterface);
905 /* claim the interface */
906 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
908 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
909 return darwin_to_libusb (kresult);
912 /* update list of endpoints */
913 kresult = get_endpoints (dev_handle, iface);
915 /* this should not happen */
916 darwin_release_interface (dev_handle, iface);
917 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
921 cInterface->cfSource = NULL;
923 /* create async event source */
924 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
925 if (kresult != kIOReturnSuccess) {
926 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
928 /* can't continue without an async event source */
929 (void)darwin_release_interface (dev_handle, iface);
931 return darwin_to_libusb (kresult);
934 /* add the cfSource to the async thread's run loop */
935 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
937 usbi_info (HANDLE_CTX (dev_handle), "interface opened");
942 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
943 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
946 /* current interface */
947 struct __darwin_interface *cInterface = &priv->interfaces[iface];
949 /* Check to see if an interface is open */
950 if (!cInterface->interface)
951 return LIBUSB_SUCCESS;
953 /* clean up endpoint data */
954 cInterface->num_endpoints = 0;
956 /* delete the interface's async event source */
957 if (cInterface->cfSource) {
958 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
959 CFRelease (cInterface->cfSource);
962 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
964 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
966 kresult = (*(cInterface->interface))->Release(cInterface->interface);
967 if (kresult != kIOReturnSuccess)
968 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
970 cInterface->interface = IO_OBJECT_NULL;
972 return darwin_to_libusb (kresult);
975 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
976 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
979 /* current interface */
980 struct __darwin_interface *cInterface = &priv->interfaces[iface];
982 if (!cInterface->interface)
983 return LIBUSB_ERROR_NO_DEVICE;
985 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
986 if (kresult != kIOReturnSuccess)
987 darwin_reset_device (dev_handle);
989 /* update list of endpoints */
990 kresult = get_endpoints (dev_handle, iface);
992 /* this should not happen */
993 darwin_release_interface (dev_handle, iface);
994 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
998 return darwin_to_libusb (kresult);
1001 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1002 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1004 /* current interface */
1005 struct __darwin_interface *cInterface;
1006 uint8_t pipeRef, iface;
1009 /* determine the interface/endpoint to use */
1010 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
1011 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1013 return LIBUSB_ERROR_NOT_FOUND;
1016 cInterface = &priv->interfaces[iface];
1018 #if (InterfaceVersion < 190)
1019 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1021 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1022 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1025 usbi_err (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1027 return darwin_to_libusb (kresult);
1030 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1031 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1034 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1036 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1038 return darwin_to_libusb (kresult);
1041 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1042 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1043 io_service_t usbInterface;
1047 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1049 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1051 return darwin_to_libusb (kresult);
1054 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1055 IOObjectRelease (usbInterface);
1067 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1068 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1069 return LIBUSB_ERROR_NOT_SUPPORTED;
1072 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1073 return LIBUSB_ERROR_NOT_SUPPORTED;
1076 static void darwin_destroy_device(struct libusb_device *dev) {
1079 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1080 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1081 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1084 uint8_t is_read; /* 0 = we're reading, 1 = we're writing */
1085 uint8_t transferType;
1086 /* None of the values below are used in libusb for bulk transfers */
1087 uint8_t direction, number, interval, pipeRef, iface;
1088 uint16_t maxPacketSize;
1090 struct __darwin_interface *cInterface;
1092 /* are we reading or writing? */
1093 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1095 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1096 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1098 return LIBUSB_ERROR_NOT_FOUND;
1101 cInterface = &priv->interfaces[iface];
1103 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1104 &transferType, &maxPacketSize, &interval);
1106 /* submit the request */
1107 /* timeouts are unavailable on interrupt endpoints */
1108 if (transferType == kUSBInterrupt) {
1110 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1111 transfer->length, darwin_async_io_callback, itransfer);
1113 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1114 transfer->length, darwin_async_io_callback, itransfer);
1117 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1118 transfer->length, transfer->timeout, transfer->timeout,
1119 darwin_async_io_callback, (void *)itransfer);
1121 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1122 transfer->length, transfer->timeout, transfer->timeout,
1123 darwin_async_io_callback, (void *)itransfer);
1127 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", is_read ? "In" : "Out",
1128 darwin_error_str(ret), ret);
1130 return darwin_to_libusb (ret);
1133 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1134 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1135 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1136 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1139 uint8_t is_read; /* 0 = we're writing, 1 = we're reading */
1140 uint8_t pipeRef, iface;
1142 AbsoluteTime atTime;
1145 struct __darwin_interface *cInterface;
1147 /* are we reading or writing? */
1148 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1150 /* construct an array of IOUSBIsocFrames */
1151 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1152 if (!tpriv->isoc_framelist)
1153 return LIBUSB_ERROR_NO_MEM;
1155 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1156 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1157 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1159 /* determine the interface/endpoint to use */
1160 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1161 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1163 return LIBUSB_ERROR_NOT_FOUND;
1166 cInterface = &priv->interfaces[iface];
1168 /* Last but not least we need the bus frame number */
1169 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1171 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1172 free(tpriv->isoc_framelist);
1173 tpriv->isoc_framelist = NULL;
1175 return darwin_to_libusb (kresult);
1178 /* schedule for a frame a little in the future */
1181 /* submit the request */
1183 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1184 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1187 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1188 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1191 if (kresult != kIOReturnSuccess) {
1192 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", is_read ? "In" : "Out",
1193 darwin_error_str(kresult));
1194 free (tpriv->isoc_framelist);
1195 tpriv->isoc_framelist = NULL;
1198 return darwin_to_libusb (kresult);
1201 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1202 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1203 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1204 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1205 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1209 bzero(&tpriv->req, sizeof(tpriv->req));
1211 /* IOUSBDeviceInterface expects the request in cpu endianess */
1212 tpriv->req.bmRequestType = setup->bmRequestType;
1213 tpriv->req.bRequest = setup->bRequest;
1214 /* these values should be in bus order from libusb_fill_control_setup */
1215 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1216 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1217 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1218 /* data is stored after the libusb control block */
1219 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1220 tpriv->req.completionTimeout = transfer->timeout;
1221 tpriv->req.noDataTimeout = transfer->timeout;
1223 /* all transfers in libusb-1.0 are async */
1224 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1226 if (kresult != kIOReturnSuccess)
1227 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1229 return darwin_to_libusb (kresult);
1232 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1233 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1235 switch (transfer->type) {
1236 case LIBUSB_TRANSFER_TYPE_CONTROL:
1237 return submit_control_transfer(itransfer);
1238 case LIBUSB_TRANSFER_TYPE_BULK:
1239 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1240 return submit_bulk_transfer(itransfer);
1241 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1242 return submit_iso_transfer(itransfer);
1244 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1245 return LIBUSB_ERROR_INVALID_PARAM;
1249 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1250 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1251 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1254 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions control pipe");
1256 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1258 return darwin_to_libusb (kresult);
1261 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1262 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1263 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1264 struct __darwin_interface *cInterface;
1265 uint8_t pipeRef, iface;
1268 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1269 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1271 return LIBUSB_ERROR_NOT_FOUND;
1274 cInterface = &priv->interfaces[iface];
1276 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions on interface %d pipe %d", iface, pipeRef);
1278 /* abort transactions */
1279 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1281 usbi_info (ITRANSFER_CTX (itransfer), "calling clear pipe stall to clear the data toggle bit");
1283 /* clear the data toggle bit */
1284 #if (InterfaceVersion < 190)
1285 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1287 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1288 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1291 return darwin_to_libusb (kresult);
1294 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1295 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1297 switch (transfer->type) {
1298 case LIBUSB_TRANSFER_TYPE_CONTROL:
1299 return cancel_control_transfer(itransfer);
1300 case LIBUSB_TRANSFER_TYPE_BULK:
1301 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1302 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1303 return darwin_abort_transfers (itransfer);
1305 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1306 return LIBUSB_ERROR_INVALID_PARAM;
1310 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1311 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1312 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1314 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1315 free (tpriv->isoc_framelist);
1316 tpriv->isoc_framelist = NULL;
1320 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1321 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1322 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1323 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1326 usbi_info (ITRANSFER_CTX (itransfer), "an async io operation has completed");
1328 /* send a completion message to the device's file descriptor */
1329 message = MESSAGE_ASYNC_IO_COMPLETE;
1330 write (priv->fds[1], &message, sizeof (message));
1331 write (priv->fds[1], &itransfer, sizeof (itransfer));
1332 write (priv->fds[1], &result, sizeof (IOReturn));
1333 write (priv->fds[1], &arg0, sizeof (UInt32));
1336 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1338 case kIOReturnSuccess:
1339 return LIBUSB_TRANSFER_COMPLETED;
1340 case kIOReturnAborted:
1341 return LIBUSB_TRANSFER_CANCELLED;
1342 case kIOUSBPipeStalled:
1343 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: pipe is stalled");
1344 return LIBUSB_TRANSFER_STALL;
1345 case kIOReturnOverrun:
1346 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1347 return LIBUSB_TRANSFER_OVERFLOW;
1348 case kIOUSBTransactionTimeout:
1349 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1350 return LIBUSB_TRANSFER_TIMED_OUT;
1352 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1353 return LIBUSB_TRANSFER_ERROR;
1357 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1358 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1359 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1360 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1361 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1362 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1363 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1366 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1367 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1371 usbi_info (ITRANSFER_CTX (itransfer), "handling %s completion with kernel status %d",
1372 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", result);
1374 if (kIOReturnSuccess == result) {
1375 if (isIsoc && tpriv->isoc_framelist) {
1376 /* copy isochronous results back */
1378 for (i = 0; i < transfer->num_iso_packets ; i++) {
1379 struct libusb_iso_packet_descriptor *lib_desc = transfer->iso_packet_desc;
1380 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1381 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1384 itransfer->transferred += io_size;
1387 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1388 usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, result));
1391 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, nfds_t nfds, int num_ready) {
1392 struct usbi_transfer *itransfer;
1398 usbi_mutex_lock(&ctx->open_devs_lock);
1399 for (i = 0; i < nfds && num_ready > 0; i++) {
1400 struct pollfd *pollfd = &fds[i];
1401 struct libusb_device_handle *handle;
1402 struct darwin_device_handle_priv *hpriv = NULL;
1404 usbi_info (ctx, "checking fd %i with revents = %x", fds[i], pollfd->revents);
1406 if (!pollfd->revents)
1410 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
1411 hpriv = (struct darwin_device_handle_priv *)handle->os_priv;
1412 if (hpriv->fds[0] == pollfd->fd)
1416 if (!(pollfd->revents & POLLERR)) {
1417 ret = read (hpriv->fds[0], &message, sizeof (message));
1418 if (ret < sizeof (message))
1421 /* could not poll the device-- response is to delete the device (this seems a little heavy-handed) */
1422 message = MESSAGE_DEVICE_GONE;
1425 case MESSAGE_DEVICE_GONE:
1426 /* remove the device's async port from the runloop */
1427 if (hpriv->cfSource) {
1428 if (libusb_darwin_acfl)
1429 CFRunLoopRemoveSource (libusb_darwin_acfl, hpriv->cfSource, kCFRunLoopDefaultMode);
1430 CFRelease (hpriv->cfSource);
1431 hpriv->cfSource = NULL;
1434 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
1435 usbi_handle_disconnect(handle);
1437 /* done with this device */
1439 case MESSAGE_ASYNC_IO_COMPLETE:
1440 read (hpriv->fds[0], &itransfer, sizeof (itransfer));
1441 read (hpriv->fds[0], &kresult, sizeof (IOReturn));
1442 read (hpriv->fds[0], &io_size, sizeof (UInt32));
1444 darwin_handle_callback (itransfer, kresult, io_size);
1447 usbi_err (ctx, "unknown message received from device pipe");
1451 usbi_mutex_unlock(&ctx->open_devs_lock);
1456 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1457 mach_timespec_t sys_time;
1458 clock_serv_t clock_ref;
1461 case USBI_CLOCK_REALTIME:
1462 /* CLOCK_REALTIME represents time since the epoch */
1463 host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &clock_ref);
1465 case USBI_CLOCK_MONOTONIC:
1466 /* use system boot time as reference for the monotonic clock */
1467 host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &clock_ref);
1470 return LIBUSB_ERROR_INVALID_PARAM;
1473 clock_get_time (clock_ref, &sys_time);
1475 tp->tv_sec = sys_time.tv_sec;
1476 tp->tv_nsec = sys_time.tv_nsec;
1481 const struct usbi_os_backend darwin_backend = {
1483 .init = darwin_init,
1484 .exit = darwin_exit,
1485 .get_device_list = darwin_get_device_list,
1486 .get_device_descriptor = darwin_get_device_descriptor,
1487 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1488 .get_config_descriptor = darwin_get_config_descriptor,
1490 .open = darwin_open,
1491 .close = darwin_close,
1492 .get_configuration = darwin_get_configuration,
1493 .set_configuration = darwin_set_configuration,
1494 .claim_interface = darwin_claim_interface,
1495 .release_interface = darwin_release_interface,
1497 .set_interface_altsetting = darwin_set_interface_altsetting,
1498 .clear_halt = darwin_clear_halt,
1499 .reset_device = darwin_reset_device,
1501 .kernel_driver_active = darwin_kernel_driver_active,
1502 .detach_kernel_driver = darwin_detach_kernel_driver,
1503 .attach_kernel_driver = darwin_attach_kernel_driver,
1505 .destroy_device = darwin_destroy_device,
1507 .submit_transfer = darwin_submit_transfer,
1508 .cancel_transfer = darwin_cancel_transfer,
1509 .clear_transfer_priv = darwin_clear_transfer_priv,
1511 .handle_events = op_handle_events,
1513 .clock_gettime = darwin_clock_gettime,
1515 .device_priv_size = sizeof(struct darwin_device_priv),
1516 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1517 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1518 .add_iso_packet_size = 0,