2 * darwin backend for libusb 1.0
3 * Copyright (C) 2008-2009 Nathan Hjelm <hjelmn@users.sourceforge.net>
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
29 #include <sys/ioctl.h>
31 #include <sys/types.h>
34 #include <mach/clock.h>
35 #include <mach/clock_types.h>
36 #include <mach/mach_host.h>
38 #include <mach/mach_port.h>
39 #include <IOKit/IOCFBundle.h>
40 #include <IOKit/usb/IOUSBLib.h>
41 #include <IOKit/IOCFPlugIn.h>
43 #include "darwin_usb.h"
45 static mach_port_t libusb_darwin_mp = 0; /* master port */
46 static CFRunLoopRef libusb_darwin_acfl = NULL; /* async cf loop */
48 /* async event thread */
49 static pthread_t libusb_darwin_at;
51 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
52 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
53 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
54 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
55 static void darwin_bulk_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size);
56 static void darwin_isoc_callback (struct usbi_transfer *itransfer, kern_return_t result);
57 static void darwin_control_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size);
58 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
60 static char *darwin_error_str (int result) {
62 case kIOReturnSuccess:
64 case kIOReturnNotOpen:
65 return "device not opened for exclusive access";
66 case kIOReturnNoDevice:
67 return "no connection to an IOService";
68 case kIOUSBNoAsyncPortErr:
69 return "no async port has been opened for interface";
70 case kIOReturnExclusiveAccess:
71 return "another process has device opened for exclusive access";
72 case kIOUSBPipeStalled:
73 return "pipe is stalled";
75 return "could not establish a connection to the Darwin kernel";
76 case kIOUSBTransactionTimeout:
77 return "transaction timed out";
78 case kIOReturnBadArgument:
79 return "invalid argument";
80 case kIOReturnAborted:
81 return "transaction aborted";
82 case kIOReturnNotResponding:
83 return "device not responding";
85 return "unknown error";
89 static int darwin_to_libusb (int result) {
91 case kIOReturnSuccess:
92 return LIBUSB_SUCCESS;
93 case kIOReturnNotOpen:
94 case kIOReturnNoDevice:
95 return LIBUSB_ERROR_NO_DEVICE;
96 case kIOReturnExclusiveAccess:
97 return LIBUSB_ERROR_ACCESS;
98 case kIOUSBPipeStalled:
99 return LIBUSB_ERROR_PIPE;
100 case kIOReturnBadArgument:
101 return LIBUSB_ERROR_INVALID_PARAM;
102 case kIOUSBTransactionTimeout:
103 return LIBUSB_ERROR_TIMEOUT;
104 case kIOReturnNotResponding:
105 case kIOReturnAborted:
107 case kIOUSBNoAsyncPortErr:
109 return LIBUSB_ERROR_OTHER;
114 static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp) {
115 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
117 /* current interface */
118 struct __darwin_interface *cInterface;
122 _usbi_log (HANDLE_CTX(dev_handle), LOG_LEVEL_INFO, "converting ep address 0x%02x to pipeRef and interface", ep);
124 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
125 cInterface = &priv->interfaces[iface];
127 if (dev_handle->claimed_interfaces & (1 << iface)) {
128 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
129 if (cInterface->endpoint_addrs[i] == ep) {
132 _usbi_log (HANDLE_CTX(dev_handle), LOG_LEVEL_INFO, "pipe %d on interface %d matches", *pipep, *ifcp);
139 /* No pipe found with the correct endpoint address */
140 _usbi_log (HANDLE_CTX(dev_handle), LOG_LEVEL_WARNING, "no pipeRef found with endpoint address 0x%02x.", ep);
145 static int usb_setup_device_iterator (io_iterator_t *deviceIterator) {
146 return IOServiceGetMatchingServices(libusb_darwin_mp, IOServiceMatching(kIOUSBDeviceClassName), deviceIterator);
149 static usb_device_t **usb_get_next_device (io_iterator_t deviceIterator, UInt32 *locationp) {
150 io_cf_plugin_ref_t *plugInInterface = NULL;
151 usb_device_t **device;
152 io_service_t usbDevice;
155 if (!IOIteratorIsValid (deviceIterator) || !(usbDevice = IOIteratorNext(deviceIterator)))
158 result = IOCreatePlugInInterfaceForService(usbDevice, kIOUSBDeviceUserClientTypeID,
159 kIOCFPlugInInterfaceID, &plugInInterface,
162 if (result || !plugInInterface) {
163 usbi_dbg ("libusb/darwin.c usb_get_next_device: could not set up plugin for service: %s\n", darwin_error_str (result));
168 (void)IOObjectRelease(usbDevice);
169 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
172 (*plugInInterface)->Stop(plugInInterface);
173 IODestroyPlugInInterface (plugInInterface);
175 (*(device))->GetLocationID(device, locationp);
180 static kern_return_t darwin_get_device (uint32_t dev_location, usb_device_t ***darwin_device) {
181 kern_return_t kresult;
183 io_iterator_t deviceIterator;
185 kresult = usb_setup_device_iterator (&deviceIterator);
189 /* This port of libusb uses locations to keep track of devices. */
190 while ((*darwin_device = usb_get_next_device (deviceIterator, &location)) != NULL) {
191 if (location == dev_location)
194 (**darwin_device)->Release(*darwin_device);
197 IOObjectRelease (deviceIterator);
199 if (!(*darwin_device))
200 return kIOReturnNoDevice;
202 return kIOReturnSuccess;
207 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
208 struct libusb_context *ctx = (struct libusb_context *)ptr;
209 struct libusb_device_handle *handle;
210 struct darwin_device_priv *dpriv;
211 struct darwin_device_handle_priv *priv;
215 CFTypeRef locationCF;
218 _usbi_log (ctx, LOG_LEVEL_INFO, "a device has been detached");
220 while ((device = IOIteratorNext (rem_devices)) != 0) {
221 /* get the location from the i/o registry */
222 locationCF = IORegistryEntryCreateCFProperty (device, CFSTR(kUSBDevicePropertyLocationID), kCFAllocatorDefault, 0);
224 CFNumberGetValue(locationCF, kCFNumberLongType, &location);
225 CFRelease (locationCF);
226 IOObjectRelease (device);
228 pthread_mutex_lock(&ctx->open_devs_lock);
229 list_for_each_entry(handle, &ctx->open_devs, list) {
230 dpriv = (struct darwin_device_priv *)handle->dev->os_priv;
231 if (dpriv->location == location)
235 if (handle && handle->os_priv) {
236 priv = (struct darwin_device_handle_priv *)handle->os_priv;
238 message = MESSAGE_DEVICE_GONE;
239 write (priv->fds[1], &message, sizeof (message));
242 pthread_mutex_unlock(&ctx->open_devs_lock);
247 static void darwin_clear_iterator (io_iterator_t iter) {
250 while ((device = IOIteratorNext (iter)) != 0)
251 IOObjectRelease (device);
254 static void *event_thread_main (void *arg0) {
256 struct libusb_context *ctx = (struct libusb_context *)arg0;
258 /* hotplug (device removal) source */
259 CFRunLoopSourceRef libusb_notification_cfsource;
260 io_notification_port_t libusb_notification_port;
261 io_iterator_t libusb_rem_device_iterator;
263 _usbi_log (ctx, LOG_LEVEL_INFO, "creating hotplug event source");
265 CFRetain (CFRunLoopGetCurrent ());
267 /* add the notification port to the run loop */
268 libusb_notification_port = IONotificationPortCreate (libusb_darwin_mp);
269 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
270 CFRunLoopAddSource(CFRunLoopGetCurrent (), libusb_notification_cfsource, kCFRunLoopDefaultMode);
272 /* create notifications for removed devices */
273 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
274 IOServiceMatching(kIOUSBDeviceClassName),
275 (IOServiceMatchingCallback)darwin_devices_detached,
276 (void *)ctx, &libusb_rem_device_iterator);
278 if (kresult != kIOReturnSuccess) {
279 _usbi_log (ctx, LOG_LEVEL_ERROR, "could not add hotplug event source: %s", darwin_error_str (kresult));
281 pthread_exit ((void *)kresult);
285 darwin_clear_iterator (libusb_rem_device_iterator);
287 /* let the main thread know about the async runloop */
288 libusb_darwin_acfl = CFRunLoopGetCurrent ();
290 _usbi_log (ctx, LOG_LEVEL_INFO, "libopenusb/darwin.c event_thread_main: thread ready to receive events");
292 /* run the runloop */
295 _usbi_log (ctx, LOG_LEVEL_INFO, "libopenusb/darwin.c event_thread_main: thread exiting");
297 /* delete notification port */
298 CFRunLoopSourceInvalidate (libusb_notification_cfsource);
299 IONotificationPortDestroy (libusb_notification_port);
301 CFRelease (CFRunLoopGetCurrent ());
303 libusb_darwin_acfl = NULL;
308 static int darwin_init(struct libusb_context *ctx) {
311 /* Create the master port for talking to IOKit */
312 if (!libusb_darwin_mp) {
313 kresult = IOMasterPort (MACH_PORT_NULL, &libusb_darwin_mp);
315 if (kresult != kIOReturnSuccess || !libusb_darwin_mp)
316 return darwin_to_libusb (kresult);
319 pthread_create (&libusb_darwin_at, NULL, event_thread_main, (void *)ctx);
321 while (!libusb_darwin_acfl)
327 static void darwin_exit (void) {
330 /* stop the async runloop */
331 CFRunLoopStop (libusb_darwin_acfl);
332 pthread_join (libusb_darwin_at, &ret);
334 if (libusb_darwin_mp)
335 mach_port_deallocate(mach_task_self(), libusb_darwin_mp);
337 libusb_darwin_mp = 0;
340 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
341 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
343 /* return cached copy */
344 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
351 static int get_configuration_index (struct libusb_device *dev, int config_value) {
352 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
354 IOUSBConfigurationDescriptorPtr desc;
357 /* is there a simpler way to determine the index? */
358 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
359 if (kresult != kIOReturnSuccess)
360 return darwin_to_libusb (kresult);
362 for (i = 0 ; i < numConfig ; i++) {
363 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
365 if (libusb_le16_to_cpu (desc->bConfigurationValue) == config_value)
369 /* configuration not found */
370 return LIBUSB_ERROR_OTHER;
373 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
374 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
379 kresult = (*(priv->device))->GetConfiguration (priv->device, &config_value);
380 if (kresult != kIOReturnSuccess)
381 return darwin_to_libusb (kresult);
383 config_index = get_configuration_index (dev, config_value);
384 if (config_index < 0)
387 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
390 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
391 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
392 IOUSBConfigurationDescriptorPtr desc;
394 usb_device_t **device = NULL;
397 return LIBUSB_ERROR_OTHER;
400 kresult = darwin_get_device (priv->location, &device);
401 if (kresult || !device) {
402 _usbi_log (DEVICE_CTX (dev), LOG_LEVEL_ERROR, "could not find device: %s", darwin_error_str (kresult));
404 return darwin_to_libusb (kresult);
407 /* don't have to open the device to get a config descriptor */
409 device = priv->device;
411 kresult = (*device)->GetConfigurationDescriptorPtr (device, config_index, &desc);
412 if (kresult == kIOReturnSuccess) {
413 /* copy descriptor */
414 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
415 len = libusb_le16_to_cpu(desc->wTotalLength);
417 memmove (buffer, desc, len);
419 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
424 (*device)->Release (device);
426 return darwin_to_libusb (kresult);
429 static int process_new_device (struct libusb_context *ctx, usb_device_t **device, UInt32 locationID, struct discovered_devs **_discdevs) {
430 struct darwin_device_priv *priv;
431 struct libusb_device *dev;
432 struct discovered_devs *discdevs;
433 UInt16 address, idVendor, idProduct;
434 UInt8 bDeviceClass, bDeviceSubClass;
438 dev = usbi_get_device_by_session_id(ctx, locationID);
440 _usbi_log (ctx, LOG_LEVEL_INFO, "allocating new device for location 0x%08x", locationID);
441 dev = usbi_alloc_device(ctx, locationID);
443 return LIBUSB_ERROR_NO_MEM;
445 priv = (struct darwin_device_priv *)dev->os_priv;
447 /* Set up request for device descriptor */
448 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
449 req.bRequest = kUSBRqGetDescriptor;
450 req.wValue = kUSBDeviceDesc << 8;
452 req.wLength = sizeof(IOUSBDeviceDescriptor);
453 req.pData = &(priv->dev_descriptor);
455 (*(device))->GetDeviceAddress (device, (USBDeviceAddress *)&address);
456 (*(device))->GetDeviceProduct (device, &idProduct);
457 (*(device))->GetDeviceVendor (device, &idVendor);
458 (*(device))->GetDeviceClass (device, &bDeviceClass);
459 (*(device))->GetDeviceSubClass (device, &bDeviceSubClass);
461 /**** retrieve device descriptors ****/
462 /* device must be open for DeviceRequest */
463 (*device)->USBDeviceOpen(device);
465 ret = (*(device))->DeviceRequest (device, &req);
466 if (ret != kIOReturnSuccess) {
467 int try_unsuspend = 1;
468 #if DeviceVersion >= 320
471 /* device may be suspended. unsuspend it and try again */
472 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
473 (void)(*device)->GetUSBDeviceInformation (device, &info);
475 try_unsuspend = info & (1 << kUSBInformationDeviceIsSuspendedBit);
479 /* resume the device */
480 (void)(*device)->USBDeviceSuspend (device, 0);
482 ret = (*(device))->DeviceRequest (device, &req);
484 /* resuspend the device */
485 (void)(*device)->USBDeviceSuspend (device, 1);
489 (*device)->USBDeviceClose (device);
491 if (ret != kIOReturnSuccess) {
492 _usbi_log (ctx, LOG_LEVEL_WARNING, "could not retrieve device descriptor: %s. skipping device", darwin_error_str (ret));
493 libusb_unref_device(dev);
496 /**** end: retrieve device descriptors ****/
498 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
499 if (libusb_le16_to_cpu (priv->dev_descriptor.idProduct) != idProduct) {
500 /* not a valid device */
501 _usbi_log (ctx, LOG_LEVEL_WARNING, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
502 idProduct, libusb_le16_to_cpu (priv->dev_descriptor.idProduct));
503 libusb_unref_device(dev);
507 dev->bus_number = locationID >> 24;
508 dev->device_address = address;
510 /* save our location, we'll need this later */
511 priv->location = locationID;
512 snprintf(priv->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", address, idVendor, idProduct, bDeviceClass, bDeviceSubClass);
514 ret = usbi_sanitize_device(dev);
517 libusb_unref_device(dev);
521 priv = (struct darwin_device_priv *)dev->os_priv;
523 _usbi_log (ctx, LOG_LEVEL_INFO, "using existing device for location 0x%08x", locationID);
526 /* append the device to the list of discovered devices */
527 discdevs = discovered_devs_append(*_discdevs, dev);
529 return LIBUSB_ERROR_NO_MEM;
531 *_discdevs = discdevs;
533 _usbi_log (ctx, LOG_LEVEL_INFO, "found device with address %d at %s", dev->device_address, priv->sys_path);
538 static int darwin_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs) {
539 io_iterator_t deviceIterator;
540 usb_device_t **device;
541 kern_return_t kresult;
544 if (!libusb_darwin_mp)
545 return LIBUSB_ERROR_INVALID_PARAM;
547 kresult = usb_setup_device_iterator (&deviceIterator);
548 if (kresult != kIOReturnSuccess)
549 return darwin_to_libusb (kresult);
551 while ((device = usb_get_next_device (deviceIterator, &location)) != NULL) {
552 (void) process_new_device (ctx, device, location, _discdevs);
554 (*(device))->Release(device);
557 IOObjectRelease(deviceIterator);
562 static int darwin_open (struct libusb_device_handle *dev_handle) {
563 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
564 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
565 usb_device_t **darwin_device;
568 kresult = darwin_get_device (dpriv->location, &darwin_device);
570 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "could not find device: %s", darwin_error_str (kresult));
571 return darwin_to_libusb (kresult);
574 dpriv->device = darwin_device;
576 /* try to open the device */
577 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
579 if (kresult != kIOReturnSuccess) {
580 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "USBDeviceOpen: %s", darwin_error_str(kresult));
583 case kIOReturnExclusiveAccess:
584 /* it is possible to perform some actions on a device that is not open so do not return an error */
589 (*(dpriv->device))->Release (dpriv->device);
590 dpriv->device = NULL;
591 return darwin_to_libusb (kresult);
596 /* create async event source */
597 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
599 CFRetain (libusb_darwin_acfl);
601 /* add the cfSource to the aync run loop */
602 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
605 /* create a file descriptor for notifications */
608 /* set the pipe to be non-blocking */
609 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
611 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
613 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "device open for access");
618 static void darwin_close (struct libusb_device_handle *dev_handle) {
619 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
620 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
624 /* make sure all interfaces are released */
625 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
626 if (dev_handle->claimed_interfaces & (1 << i))
627 libusb_release_interface (dev_handle, i);
630 /* delete the device's async event source */
631 if (priv->cfSource) {
632 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
633 CFRelease (priv->cfSource);
636 /* close the device */
637 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
639 /* Log the fact that we had a problem closing the file, however failing a
640 * close isn't really an error, so return success anyway */
641 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "USBDeviceClose: %s", darwin_error_str(kresult));
645 kresult = (*(dpriv->device))->Release(dpriv->device);
647 /* Log the fact that we had a problem closing the file, however failing a
648 * close isn't really an error, so return success anyway */
649 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "Release: %s", darwin_error_str(kresult));
652 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
653 close (priv->fds[1]);
654 close (priv->fds[0]);
657 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
658 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
662 kresult = (*(dpriv->device))->GetConfiguration (dpriv->device, &configNum);
663 if (kresult != kIOReturnSuccess)
664 return darwin_to_libusb (kresult);
666 *config = (int) configNum;
671 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
672 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
676 /* Setting configuration will invalidate the interface, so we need
677 to reclaim it. First, dispose of existing interfaces, if any. */
678 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
679 if (dev_handle->claimed_interfaces & (1 << i))
680 darwin_release_interface (dev_handle, i);
682 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
683 if (kresult != kIOReturnSuccess)
684 return darwin_to_libusb (kresult);
686 /* Reclaim any interfaces. */
687 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
688 if (dev_handle->claimed_interfaces & (1 << i))
689 darwin_claim_interface (dev_handle, i);
694 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
695 IOUSBFindInterfaceRequest request;
696 uint8_t current_interface;
697 kern_return_t kresult;
698 io_iterator_t interface_iterator;
700 *usbInterfacep = IO_OBJECT_NULL;
702 /* Setup the Interface Request */
703 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
704 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
705 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
706 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
708 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
712 for ( current_interface = 0 ; current_interface <= ifc ; current_interface++ )
713 *usbInterfacep = IOIteratorNext(interface_iterator);
715 /* done with the interface iterator */
716 IOObjectRelease(interface_iterator);
721 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
722 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
724 /* current interface */
725 struct __darwin_interface *cInterface = &priv->interfaces[iface];
727 kern_return_t kresult;
729 u_int8_t numep, direction, number;
730 u_int8_t dont_care1, dont_care3;
731 u_int16_t dont_care2;
734 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "building table of endpoints.");
736 /* retrieve the total number of endpoints on this interface */
737 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
739 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
740 return darwin_to_libusb (kresult);
743 /* iterate through pipe references */
744 for (i = 1 ; i <= numep ; i++) {
745 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
746 &dont_care2, &dont_care3);
748 if (kresult != kIOReturnSuccess) {
749 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
751 return darwin_to_libusb (kresult);
754 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
756 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
759 cInterface->num_endpoints = numep;
764 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
765 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
766 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
767 io_service_t usbInterface = IO_OBJECT_NULL;
769 IOCFPlugInInterface **plugInInterface = NULL;
773 /* current interface */
774 struct __darwin_interface *cInterface = &priv->interfaces[iface];
776 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
777 if (kresult != kIOReturnSuccess)
778 return darwin_to_libusb (kresult);
780 /* make sure we have an interface */
782 u_int8_t nConfig; /* Index of configuration to use */
783 IOUSBConfigurationDescriptorPtr configDesc; /* to describe which configuration to select */
784 /* Only a composite class device with no vendor-specific driver will
785 be configured. Otherwise, we need to do it ourselves, or there
786 will be no interfaces for the device. */
788 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "no interface found; selecting configuration" );
790 kresult = (*(dpriv->device))->GetNumberOfConfigurations (dpriv->device, &nConfig);
791 if (kresult != kIOReturnSuccess) {
792 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "GetNumberOfConfigurations: %s", darwin_error_str(kresult));
793 return darwin_to_libusb(kresult);
797 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "GetNumberOfConfigurations: no configurations");
798 return LIBUSB_ERROR_OTHER;
801 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "device has %d configuration%s. using the first",
802 (int)nConfig, (nConfig > 1 ? "s" : "") );
804 /* Always use the first configuration */
805 kresult = (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, 0, &configDesc);
806 if (kresult != kIOReturnSuccess) {
807 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "GetConfigurationDescriptorPtr: %s",
808 darwin_error_str(kresult));
812 new_config = configDesc->bConfigurationValue;
814 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "new configuration value is %d", new_config);
816 /* set the configuration */
817 kresult = darwin_set_configuration (dev_handle, new_config);
818 if (kresult != LIBUSB_SUCCESS) {
819 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "could not set configuration");
823 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
825 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "darwin_get_interface: %s", darwin_error_str(kresult));
826 return darwin_to_libusb (kresult);
831 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "interface not found");
832 return LIBUSB_ERROR_NOT_FOUND;
835 /* get an interface to the device's interface */
836 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
837 kIOCFPlugInInterfaceID, &plugInInterface, &score);
839 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
840 return darwin_to_libusb (kresult);
843 if (!plugInInterface) {
844 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "plugin interface not found");
845 return LIBUSB_ERROR_NOT_FOUND;
848 /* ignore release error */
849 (void)IOObjectRelease (usbInterface);
851 /* Do the actual claim */
852 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
853 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
854 (LPVOID)&cInterface->interface);
855 if (kresult || !cInterface->interface) {
856 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "QueryInterface: %s", darwin_error_str(kresult));
857 return darwin_to_libusb (kresult);
860 /* We no longer need the intermediate plug-in */
861 (*plugInInterface)->Release(plugInInterface);
863 /* claim the interface */
864 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
866 _usbi_log(HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "USBInterfaceOpen: %s", darwin_error_str(kresult));
867 return darwin_to_libusb (kresult);
870 /* update list of endpoints */
871 kresult = get_endpoints (dev_handle, iface);
873 /* this should not happen */
874 darwin_release_interface (dev_handle, iface);
875 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "could not build endpoint table");
879 cInterface->cfSource = NULL;
881 /* create async event source */
882 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
883 if (kresult != kIOReturnSuccess) {
884 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "could not create async event source");
886 /* can't continue without an async event source */
887 (void)darwin_release_interface (dev_handle, iface);
889 return darwin_to_libusb (kresult);
892 /* add the cfSource to the async thread's run loop */
893 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
895 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "interface opened");
900 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
901 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
904 /* current interface */
905 struct __darwin_interface *cInterface = &priv->interfaces[iface];
907 /* Check to see if an interface is open */
908 if (!cInterface->interface)
909 return LIBUSB_SUCCESS;
911 /* clean up endpoint data */
912 cInterface->num_endpoints = 0;
914 /* delete the interface's async event source */
915 if (cInterface->cfSource) {
916 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
917 CFRelease (cInterface->cfSource);
920 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
922 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "USBInterfaceClose: %s", darwin_error_str(kresult));
924 kresult = (*(cInterface->interface))->Release(cInterface->interface);
925 if (kresult != kIOReturnSuccess)
926 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "Release: %s", darwin_error_str(kresult));
928 cInterface->interface = IO_OBJECT_NULL;
930 return darwin_to_libusb (kresult);
933 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
934 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
937 /* current interface */
938 struct __darwin_interface *cInterface = &priv->interfaces[iface];
940 if (!cInterface->interface)
941 return LIBUSB_ERROR_NO_DEVICE;
943 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
944 if (kresult != kIOReturnSuccess)
945 darwin_reset_device (dev_handle);
947 return darwin_to_libusb (kresult);
950 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
951 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
953 /* current interface */
954 struct __darwin_interface *cInterface;
955 uint8_t pipeRef, iface;
958 /* determine the interface/endpoint to use */
959 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
960 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
962 return LIBUSB_ERROR_NOT_FOUND;
965 cInterface = &priv->interfaces[iface];
967 #if (InterfaceVersion < 190)
968 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
970 /* newer versions of darwin support clearing additional bits on the device's endpoint */
971 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
974 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "ClearPipeStall: %s", darwin_error_str (kresult));
976 return darwin_to_libusb (kresult);
979 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
980 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
983 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
985 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "ResetDevice: %s", darwin_error_str (kresult));
987 return darwin_to_libusb (kresult);
990 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
991 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
992 io_service_t usbInterface;
996 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
998 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "darwin_get_interface: %s", darwin_error_str(kresult));
1000 return darwin_to_libusb (kresult);
1003 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1004 IOObjectRelease (usbInterface);
1016 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1017 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1018 return LIBUSB_ERROR_NOT_SUPPORTED;
1021 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1022 return LIBUSB_ERROR_NOT_SUPPORTED;
1025 static void darwin_destroy_device(struct libusb_device *dev) {
1028 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1029 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1030 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1033 uint8_t is_read; /* 0 = we're reading, 1 = we're writing */
1034 uint8_t transferType;
1035 /* None of the values below are used in libusb for bulk transfers */
1036 uint8_t direction, number, interval, pipeRef, iface;
1037 uint16_t maxPacketSize;
1039 struct __darwin_interface *cInterface;
1041 /* are we reading or writing? */
1042 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1044 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1045 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
1047 return LIBUSB_ERROR_NOT_FOUND;
1050 cInterface = &priv->interfaces[iface];
1052 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1053 &transferType, &maxPacketSize, &interval);
1055 /* submit the request */
1056 /* timeouts are unavailable on interrupt endpoints */
1057 if (transferType == kUSBInterrupt) {
1059 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1060 transfer->length, darwin_async_io_callback, itransfer);
1062 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1063 transfer->length, darwin_async_io_callback, itransfer);
1066 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1067 transfer->length, transfer->timeout, transfer->timeout,
1068 darwin_async_io_callback, (void *)itransfer);
1070 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1071 transfer->length, transfer->timeout, transfer->timeout,
1072 darwin_async_io_callback, (void *)itransfer);
1076 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "bulk transfer failed (dir = %s): %s", is_read ? "In" : "Out",
1077 darwin_error_str(ret));
1079 return darwin_to_libusb (ret);
1082 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1083 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1084 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1085 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1088 uint8_t is_read; /* 0 = we're writing, 1 = we're reading */
1089 uint8_t pipeRef, iface;
1091 AbsoluteTime atTime;
1094 struct __darwin_interface *cInterface;
1096 /* are we reading or writing? */
1097 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1099 /* construct an array of IOUSBIsocFrames */
1100 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1101 if (!tpriv->isoc_framelist)
1102 return LIBUSB_ERROR_NO_MEM;
1104 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1105 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1106 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1108 /* determine the interface/endpoint to use */
1109 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1110 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
1112 return LIBUSB_ERROR_NOT_FOUND;
1115 cInterface = &priv->interfaces[iface];
1117 /* Last but not least we need the bus frame number */
1118 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1120 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "failed to get bus frame number: %d", kresult);
1121 free(tpriv->isoc_framelist);
1122 tpriv->isoc_framelist = NULL;
1124 return darwin_to_libusb (kresult);
1127 /* schedule for a frame a little in the future */
1130 /* submit the request */
1132 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1133 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1136 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1137 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1140 if (kresult != kIOReturnSuccess) {
1141 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "isochronous transfer failed (dir: %s): %s", is_read ? "In" : "Out",
1142 darwin_error_str(kresult));
1143 free (tpriv->isoc_framelist);
1144 tpriv->isoc_framelist = NULL;
1147 return darwin_to_libusb (kresult);
1150 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1151 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1152 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1153 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1154 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1158 bzero(&tpriv->req, sizeof(tpriv->req));
1160 /* IOUSBDeviceInterface expects the request in cpu endianess */
1161 tpriv->req.bmRequestType = setup->bmRequestType;
1162 tpriv->req.bRequest = setup->bRequest;
1163 /* these values should already be in bus order */
1164 tpriv->req.wValue = setup->wValue;
1165 tpriv->req.wIndex = setup->wIndex;
1166 tpriv->req.wLength = setup->wLength;
1167 /* data is stored after the libusb control block */
1168 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1169 tpriv->req.completionTimeout = transfer->timeout;
1170 tpriv->req.noDataTimeout = transfer->timeout;
1172 /* all transfers in libusb-1.0 are async */
1173 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1175 if (kresult != kIOReturnSuccess)
1176 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "control request failed: %s", darwin_error_str(kresult));
1178 return darwin_to_libusb (kresult);
1181 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1182 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1184 switch (transfer->type) {
1185 case LIBUSB_TRANSFER_TYPE_CONTROL:
1186 return submit_control_transfer(itransfer);
1187 case LIBUSB_TRANSFER_TYPE_BULK:
1188 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1189 return submit_bulk_transfer(itransfer);
1190 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1191 return submit_iso_transfer(itransfer);
1193 _usbi_log (TRANSFER_CTX(transfer), LOG_LEVEL_ERROR, "unknown endpoint type %d", transfer->type);
1194 return LIBUSB_ERROR_INVALID_PARAM;
1198 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1199 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1200 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1203 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "WARNING: aborting all transactions control pipe");
1205 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1207 return darwin_to_libusb (kresult);
1210 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1211 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1212 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1213 struct __darwin_interface *cInterface;
1214 uint8_t pipeRef, iface;
1217 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1218 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
1220 return LIBUSB_ERROR_NOT_FOUND;
1223 cInterface = &priv->interfaces[iface];
1225 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "WARNING: aborting all transactions on interface %d pipe %d", iface, pipeRef);
1227 /* abort transactions */
1228 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1230 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "calling clear pipe stall to clear the data toggle bit");
1232 /* clear the data toggle bit */
1233 #if (InterfaceVersion < 190)
1234 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1236 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1237 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1240 return darwin_to_libusb (kresult);
1243 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1244 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1246 switch (transfer->type) {
1247 case LIBUSB_TRANSFER_TYPE_CONTROL:
1248 return cancel_control_transfer(itransfer);
1249 case LIBUSB_TRANSFER_TYPE_BULK:
1250 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1251 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1252 return darwin_abort_transfers (itransfer);
1254 _usbi_log (TRANSFER_CTX(transfer), LOG_LEVEL_ERROR, "unknown endpoint type %d", transfer->type);
1255 return LIBUSB_ERROR_INVALID_PARAM;
1259 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1260 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1261 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1263 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1264 free (tpriv->isoc_framelist);
1265 tpriv->isoc_framelist = NULL;
1269 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1270 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1271 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1272 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1275 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "an async io operation has completed");
1277 /* send a completion message to the device's file descriptor */
1278 message = MESSAGE_ASYNC_IO_COMPLETE;
1279 write (priv->fds[1], &message, sizeof (message));
1280 write (priv->fds[1], &itransfer, sizeof (itransfer));
1281 write (priv->fds[1], &result, sizeof (IOReturn));
1282 write (priv->fds[1], &arg0, sizeof (UInt32));
1285 static void darwin_bulk_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1286 enum libusb_transfer_status status;
1288 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "handling bulk completion with status %d", result);
1291 case kIOReturnSuccess:
1292 status = LIBUSB_TRANSFER_COMPLETED;
1293 itransfer->transferred += io_size;
1295 case kIOReturnAborted:
1296 usbi_handle_transfer_cancellation(itransfer);
1298 case kIOUSBPipeStalled:
1299 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_WARNING, "unsupported control request");
1300 status = LIBUSB_TRANSFER_STALL;
1304 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_ERROR, "control error = %s", darwin_error_str (result));
1305 status = LIBUSB_TRANSFER_ERROR;
1308 usbi_handle_transfer_completion(itransfer, status);
1311 static void darwin_isoc_callback (struct usbi_transfer *itransfer, kern_return_t result) {
1312 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1313 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1316 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "handling isoc completion with status %d", result);
1318 if (result == kIOReturnSuccess && tpriv->isoc_framelist) {
1319 /* copy isochronous results back */
1321 for (i = 0; i < transfer->num_iso_packets ; i++) {
1322 struct libusb_iso_packet_descriptor *lib_desc = transfer->iso_packet_desc;
1323 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1324 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1329 case kIOReturnSuccess:
1330 status = LIBUSB_TRANSFER_COMPLETED;
1332 case kIOReturnAborted:
1333 usbi_handle_transfer_cancellation(itransfer);
1335 case kIOUSBPipeStalled:
1336 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_WARNING, "unsupported control request");
1337 status = LIBUSB_TRANSFER_STALL;
1341 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_ERROR, "control error = %s", darwin_error_str (result));
1342 status = LIBUSB_TRANSFER_ERROR;
1345 usbi_handle_transfer_completion(itransfer, status);
1348 static void darwin_control_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1351 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "handling control completion with status %d", result);
1354 case kIOReturnSuccess:
1355 status = LIBUSB_TRANSFER_COMPLETED;
1356 itransfer->transferred += io_size;
1358 case kIOReturnAborted:
1359 usbi_handle_transfer_cancellation(itransfer);
1361 case kIOUSBPipeStalled:
1362 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_WARNING, "unsupported control request");
1363 status = LIBUSB_TRANSFER_STALL;
1367 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_ERROR, "control error = %s", darwin_error_str (result));
1368 status = LIBUSB_TRANSFER_ERROR;
1371 usbi_handle_transfer_completion(itransfer, status);
1374 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1375 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1377 switch (transfer->type) {
1378 case LIBUSB_TRANSFER_TYPE_CONTROL:
1379 darwin_control_callback (itransfer, result, io_size);
1381 case LIBUSB_TRANSFER_TYPE_BULK:
1382 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1383 darwin_bulk_callback (itransfer, result, io_size);
1385 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1386 darwin_isoc_callback (itransfer, result);
1389 _usbi_log (TRANSFER_CTX(transfer), LOG_LEVEL_ERROR, "unknown endpoint type %d", transfer->type);
1393 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, nfds_t nfds, int num_ready) {
1394 struct usbi_transfer *itransfer;
1400 pthread_mutex_lock(&ctx->open_devs_lock);
1401 for (i = 0; i < nfds && num_ready > 0; i++) {
1402 struct pollfd *pollfd = &fds[i];
1403 struct libusb_device_handle *handle;
1404 struct darwin_device_handle_priv *hpriv = NULL;
1406 _usbi_log (ctx, LOG_LEVEL_INFO, "checking fd %i with revents = %x", fds[i], pollfd->revents);
1408 if (!pollfd->revents)
1412 list_for_each_entry(handle, &ctx->open_devs, list) {
1413 hpriv = (struct darwin_device_handle_priv *)handle->os_priv;
1414 if (hpriv->fds[0] == pollfd->fd)
1418 if (!(pollfd->revents & POLLERR)) {
1419 ret = read (hpriv->fds[0], &message, sizeof (message));
1420 if (ret < sizeof (message))
1423 /* could not poll the device-- response is to delete the device (this seems a little heavy-handed) */
1424 message = MESSAGE_DEVICE_GONE;
1427 case MESSAGE_DEVICE_GONE:
1428 /* remove the device's async port from the runloop */
1429 if (hpriv->cfSource) {
1430 if (libusb_darwin_acfl)
1431 CFRunLoopRemoveSource (libusb_darwin_acfl, hpriv->cfSource, kCFRunLoopDefaultMode);
1432 CFRelease (hpriv->cfSource);
1433 hpriv->cfSource = NULL;
1436 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
1437 usbi_handle_disconnect(handle);
1439 /* done with this device */
1441 case MESSAGE_ASYNC_IO_COMPLETE:
1442 read (hpriv->fds[0], &itransfer, sizeof (itransfer));
1443 read (hpriv->fds[0], &kresult, sizeof (IOReturn));
1444 read (hpriv->fds[0], &io_size, sizeof (UInt32));
1446 darwin_handle_callback (itransfer, kresult, io_size);
1449 _usbi_log (ctx, LOG_LEVEL_ERROR, "unknown message received from device pipe");
1453 pthread_mutex_unlock(&ctx->open_devs_lock);
1458 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1459 mach_timespec_t sys_time;
1460 clock_serv_t clock_ref;
1463 case USBI_CLOCK_REALTIME:
1464 /* CLOCK_REALTIME represents time since the epoch */
1465 host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &clock_ref);
1467 case USBI_CLOCK_MONOTONIC:
1468 /* use system boot time as reference for the monotonic clock */
1469 host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &clock_ref);
1472 return LIBUSB_ERROR_INVALID_PARAM;
1475 clock_get_time (clock_ref, &sys_time);
1477 tp->tv_sec = sys_time.tv_sec;
1478 tp->tv_nsec = sys_time.tv_nsec;
1483 const struct usbi_os_backend darwin_backend = {
1485 .init = darwin_init,
1486 .exit = darwin_exit,
1487 .get_device_list = darwin_get_device_list,
1488 .get_device_descriptor = darwin_get_device_descriptor,
1489 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1490 .get_config_descriptor = darwin_get_config_descriptor,
1492 .open = darwin_open,
1493 .close = darwin_close,
1494 .get_configuration = darwin_get_configuration,
1495 .set_configuration = darwin_set_configuration,
1496 .claim_interface = darwin_claim_interface,
1497 .release_interface = darwin_release_interface,
1499 .set_interface_altsetting = darwin_set_interface_altsetting,
1500 .clear_halt = darwin_clear_halt,
1501 .reset_device = darwin_reset_device,
1503 .kernel_driver_active = darwin_kernel_driver_active,
1504 .detach_kernel_driver = darwin_detach_kernel_driver,
1505 .attach_kernel_driver = darwin_attach_kernel_driver,
1507 .destroy_device = darwin_destroy_device,
1509 .submit_transfer = darwin_submit_transfer,
1510 .cancel_transfer = darwin_cancel_transfer,
1511 .clear_transfer_priv = darwin_clear_transfer_priv,
1513 .handle_events = op_handle_events,
1515 .clock_gettime = darwin_clock_gettime,
1517 .device_priv_size = sizeof(struct darwin_device_priv),
1518 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1519 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1520 .add_iso_packet_size = 0,