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]);
656 dpriv->device = NULL;
657 priv->fds[0] = priv->fds[1] = -1;
660 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
661 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
665 kresult = (*(dpriv->device))->GetConfiguration (dpriv->device, &configNum);
666 if (kresult != kIOReturnSuccess)
667 return darwin_to_libusb (kresult);
669 *config = (int) configNum;
674 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
675 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
679 /* Setting configuration will invalidate the interface, so we need
680 to reclaim it. First, dispose of existing interfaces, if any. */
681 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
682 if (dev_handle->claimed_interfaces & (1 << i))
683 darwin_release_interface (dev_handle, i);
685 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
686 if (kresult != kIOReturnSuccess)
687 return darwin_to_libusb (kresult);
689 /* Reclaim any interfaces. */
690 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
691 if (dev_handle->claimed_interfaces & (1 << i))
692 darwin_claim_interface (dev_handle, i);
697 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
698 IOUSBFindInterfaceRequest request;
699 uint8_t current_interface;
700 kern_return_t kresult;
701 io_iterator_t interface_iterator;
703 *usbInterfacep = IO_OBJECT_NULL;
705 /* Setup the Interface Request */
706 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
707 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
708 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
709 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
711 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
715 for ( current_interface = 0 ; current_interface <= ifc ; current_interface++ )
716 *usbInterfacep = IOIteratorNext(interface_iterator);
718 /* done with the interface iterator */
719 IOObjectRelease(interface_iterator);
724 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
725 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
727 /* current interface */
728 struct __darwin_interface *cInterface = &priv->interfaces[iface];
730 kern_return_t kresult;
732 u_int8_t numep, direction, number;
733 u_int8_t dont_care1, dont_care3;
734 u_int16_t dont_care2;
737 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "building table of endpoints.");
739 /* retrieve the total number of endpoints on this interface */
740 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
742 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
743 return darwin_to_libusb (kresult);
746 /* iterate through pipe references */
747 for (i = 1 ; i <= numep ; i++) {
748 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
749 &dont_care2, &dont_care3);
751 if (kresult != kIOReturnSuccess) {
752 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
754 return darwin_to_libusb (kresult);
757 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
759 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
762 cInterface->num_endpoints = numep;
767 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
768 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
769 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
770 io_service_t usbInterface = IO_OBJECT_NULL;
772 IOCFPlugInInterface **plugInInterface = NULL;
776 /* current interface */
777 struct __darwin_interface *cInterface = &priv->interfaces[iface];
779 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
780 if (kresult != kIOReturnSuccess)
781 return darwin_to_libusb (kresult);
783 /* make sure we have an interface */
785 u_int8_t nConfig; /* Index of configuration to use */
786 IOUSBConfigurationDescriptorPtr configDesc; /* to describe which configuration to select */
787 /* Only a composite class device with no vendor-specific driver will
788 be configured. Otherwise, we need to do it ourselves, or there
789 will be no interfaces for the device. */
791 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "no interface found; selecting configuration" );
793 kresult = (*(dpriv->device))->GetNumberOfConfigurations (dpriv->device, &nConfig);
794 if (kresult != kIOReturnSuccess) {
795 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "GetNumberOfConfigurations: %s", darwin_error_str(kresult));
796 return darwin_to_libusb(kresult);
800 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "GetNumberOfConfigurations: no configurations");
801 return LIBUSB_ERROR_OTHER;
804 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "device has %d configuration%s. using the first",
805 (int)nConfig, (nConfig > 1 ? "s" : "") );
807 /* Always use the first configuration */
808 kresult = (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, 0, &configDesc);
809 if (kresult != kIOReturnSuccess) {
810 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "GetConfigurationDescriptorPtr: %s",
811 darwin_error_str(kresult));
815 new_config = configDesc->bConfigurationValue;
817 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "new configuration value is %d", new_config);
819 /* set the configuration */
820 kresult = darwin_set_configuration (dev_handle, new_config);
821 if (kresult != LIBUSB_SUCCESS) {
822 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "could not set configuration");
826 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
828 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "darwin_get_interface: %s", darwin_error_str(kresult));
829 return darwin_to_libusb (kresult);
834 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "interface not found");
835 return LIBUSB_ERROR_NOT_FOUND;
838 /* get an interface to the device's interface */
839 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
840 kIOCFPlugInInterfaceID, &plugInInterface, &score);
842 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
843 return darwin_to_libusb (kresult);
846 if (!plugInInterface) {
847 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "plugin interface not found");
848 return LIBUSB_ERROR_NOT_FOUND;
851 /* ignore release error */
852 (void)IOObjectRelease (usbInterface);
854 /* Do the actual claim */
855 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
856 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
857 (LPVOID)&cInterface->interface);
858 if (kresult || !cInterface->interface) {
859 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "QueryInterface: %s", darwin_error_str(kresult));
860 return darwin_to_libusb (kresult);
863 /* We no longer need the intermediate plug-in */
864 (*plugInInterface)->Release(plugInInterface);
866 /* claim the interface */
867 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
869 _usbi_log(HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "USBInterfaceOpen: %s", darwin_error_str(kresult));
870 return darwin_to_libusb (kresult);
873 /* update list of endpoints */
874 kresult = get_endpoints (dev_handle, iface);
876 /* this should not happen */
877 darwin_release_interface (dev_handle, iface);
878 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "could not build endpoint table");
882 cInterface->cfSource = NULL;
884 /* create async event source */
885 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
886 if (kresult != kIOReturnSuccess) {
887 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "could not create async event source");
889 /* can't continue without an async event source */
890 (void)darwin_release_interface (dev_handle, iface);
892 return darwin_to_libusb (kresult);
895 /* add the cfSource to the async thread's run loop */
896 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
898 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "interface opened");
903 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
904 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
907 /* current interface */
908 struct __darwin_interface *cInterface = &priv->interfaces[iface];
910 /* Check to see if an interface is open */
911 if (!cInterface->interface)
912 return LIBUSB_SUCCESS;
914 /* clean up endpoint data */
915 cInterface->num_endpoints = 0;
917 /* delete the interface's async event source */
918 if (cInterface->cfSource) {
919 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
920 CFRelease (cInterface->cfSource);
923 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
925 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "USBInterfaceClose: %s", darwin_error_str(kresult));
927 kresult = (*(cInterface->interface))->Release(cInterface->interface);
928 if (kresult != kIOReturnSuccess)
929 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "Release: %s", darwin_error_str(kresult));
931 cInterface->interface = IO_OBJECT_NULL;
933 return darwin_to_libusb (kresult);
936 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
937 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
940 /* current interface */
941 struct __darwin_interface *cInterface = &priv->interfaces[iface];
943 if (!cInterface->interface)
944 return LIBUSB_ERROR_NO_DEVICE;
946 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
947 if (kresult != kIOReturnSuccess)
948 darwin_reset_device (dev_handle);
950 return darwin_to_libusb (kresult);
953 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
954 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
956 /* current interface */
957 struct __darwin_interface *cInterface;
958 uint8_t pipeRef, iface;
961 /* determine the interface/endpoint to use */
962 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
963 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
965 return LIBUSB_ERROR_NOT_FOUND;
968 cInterface = &priv->interfaces[iface];
970 #if (InterfaceVersion < 190)
971 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
973 /* newer versions of darwin support clearing additional bits on the device's endpoint */
974 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
977 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "ClearPipeStall: %s", darwin_error_str (kresult));
979 return darwin_to_libusb (kresult);
982 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
983 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
986 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
988 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "ResetDevice: %s", darwin_error_str (kresult));
990 return darwin_to_libusb (kresult);
993 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
994 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
995 io_service_t usbInterface;
999 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1001 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "darwin_get_interface: %s", darwin_error_str(kresult));
1003 return darwin_to_libusb (kresult);
1006 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1007 IOObjectRelease (usbInterface);
1019 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1020 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1021 return LIBUSB_ERROR_NOT_SUPPORTED;
1024 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1025 return LIBUSB_ERROR_NOT_SUPPORTED;
1028 static void darwin_destroy_device(struct libusb_device *dev) {
1031 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1032 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1033 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1036 uint8_t is_read; /* 0 = we're reading, 1 = we're writing */
1037 uint8_t transferType;
1038 /* None of the values below are used in libusb for bulk transfers */
1039 uint8_t direction, number, interval, pipeRef, iface;
1040 uint16_t maxPacketSize;
1042 struct __darwin_interface *cInterface;
1044 /* are we reading or writing? */
1045 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1047 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1048 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
1050 return LIBUSB_ERROR_NOT_FOUND;
1053 cInterface = &priv->interfaces[iface];
1055 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1056 &transferType, &maxPacketSize, &interval);
1058 /* submit the request */
1059 /* timeouts are unavailable on interrupt endpoints */
1060 if (transferType == kUSBInterrupt) {
1062 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1063 transfer->length, darwin_async_io_callback, itransfer);
1065 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1066 transfer->length, darwin_async_io_callback, itransfer);
1069 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1070 transfer->length, transfer->timeout, transfer->timeout,
1071 darwin_async_io_callback, (void *)itransfer);
1073 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1074 transfer->length, transfer->timeout, transfer->timeout,
1075 darwin_async_io_callback, (void *)itransfer);
1079 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "bulk transfer failed (dir = %s): %s", is_read ? "In" : "Out",
1080 darwin_error_str(ret));
1082 return darwin_to_libusb (ret);
1085 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1086 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1087 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1088 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1091 uint8_t is_read; /* 0 = we're writing, 1 = we're reading */
1092 uint8_t pipeRef, iface;
1094 AbsoluteTime atTime;
1097 struct __darwin_interface *cInterface;
1099 /* are we reading or writing? */
1100 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1102 /* construct an array of IOUSBIsocFrames */
1103 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1104 if (!tpriv->isoc_framelist)
1105 return LIBUSB_ERROR_NO_MEM;
1107 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1108 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1109 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1111 /* determine the interface/endpoint to use */
1112 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1113 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
1115 return LIBUSB_ERROR_NOT_FOUND;
1118 cInterface = &priv->interfaces[iface];
1120 /* Last but not least we need the bus frame number */
1121 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1123 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "failed to get bus frame number: %d", kresult);
1124 free(tpriv->isoc_framelist);
1125 tpriv->isoc_framelist = NULL;
1127 return darwin_to_libusb (kresult);
1130 /* schedule for a frame a little in the future */
1133 /* submit the request */
1135 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1136 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1139 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1140 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1143 if (kresult != kIOReturnSuccess) {
1144 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "isochronous transfer failed (dir: %s): %s", is_read ? "In" : "Out",
1145 darwin_error_str(kresult));
1146 free (tpriv->isoc_framelist);
1147 tpriv->isoc_framelist = NULL;
1150 return darwin_to_libusb (kresult);
1153 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1154 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1155 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1156 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1157 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1161 bzero(&tpriv->req, sizeof(tpriv->req));
1163 /* IOUSBDeviceInterface expects the request in cpu endianess */
1164 tpriv->req.bmRequestType = setup->bmRequestType;
1165 tpriv->req.bRequest = setup->bRequest;
1166 /* these values should already be in bus order */
1167 tpriv->req.wValue = setup->wValue;
1168 tpriv->req.wIndex = setup->wIndex;
1169 tpriv->req.wLength = setup->wLength;
1170 /* data is stored after the libusb control block */
1171 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1172 tpriv->req.completionTimeout = transfer->timeout;
1173 tpriv->req.noDataTimeout = transfer->timeout;
1175 /* all transfers in libusb-1.0 are async */
1176 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1178 if (kresult != kIOReturnSuccess)
1179 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "control request failed: %s", darwin_error_str(kresult));
1181 return darwin_to_libusb (kresult);
1184 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1185 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1187 switch (transfer->type) {
1188 case LIBUSB_TRANSFER_TYPE_CONTROL:
1189 return submit_control_transfer(itransfer);
1190 case LIBUSB_TRANSFER_TYPE_BULK:
1191 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1192 return submit_bulk_transfer(itransfer);
1193 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1194 return submit_iso_transfer(itransfer);
1196 _usbi_log (TRANSFER_CTX(transfer), LOG_LEVEL_ERROR, "unknown endpoint type %d", transfer->type);
1197 return LIBUSB_ERROR_INVALID_PARAM;
1201 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1202 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1203 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1206 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "WARNING: aborting all transactions control pipe");
1208 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1210 return darwin_to_libusb (kresult);
1213 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1214 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1215 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1216 struct __darwin_interface *cInterface;
1217 uint8_t pipeRef, iface;
1220 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1221 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
1223 return LIBUSB_ERROR_NOT_FOUND;
1226 cInterface = &priv->interfaces[iface];
1228 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "WARNING: aborting all transactions on interface %d pipe %d", iface, pipeRef);
1230 /* abort transactions */
1231 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1233 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "calling clear pipe stall to clear the data toggle bit");
1235 /* clear the data toggle bit */
1236 #if (InterfaceVersion < 190)
1237 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1239 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1240 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1243 return darwin_to_libusb (kresult);
1246 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1247 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1249 switch (transfer->type) {
1250 case LIBUSB_TRANSFER_TYPE_CONTROL:
1251 return cancel_control_transfer(itransfer);
1252 case LIBUSB_TRANSFER_TYPE_BULK:
1253 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1254 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1255 return darwin_abort_transfers (itransfer);
1257 _usbi_log (TRANSFER_CTX(transfer), LOG_LEVEL_ERROR, "unknown endpoint type %d", transfer->type);
1258 return LIBUSB_ERROR_INVALID_PARAM;
1262 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1263 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1264 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1266 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1267 free (tpriv->isoc_framelist);
1268 tpriv->isoc_framelist = NULL;
1272 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1273 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1274 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1275 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1278 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "an async io operation has completed");
1280 /* send a completion message to the device's file descriptor */
1281 message = MESSAGE_ASYNC_IO_COMPLETE;
1282 write (priv->fds[1], &message, sizeof (message));
1283 write (priv->fds[1], &itransfer, sizeof (itransfer));
1284 write (priv->fds[1], &result, sizeof (IOReturn));
1285 write (priv->fds[1], &arg0, sizeof (UInt32));
1288 static void darwin_bulk_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1289 enum libusb_transfer_status status;
1291 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "handling bulk completion with status %d", result);
1294 case kIOReturnSuccess:
1295 status = LIBUSB_TRANSFER_COMPLETED;
1296 itransfer->transferred += io_size;
1298 case kIOReturnAborted:
1299 usbi_handle_transfer_cancellation(itransfer);
1301 case kIOUSBPipeStalled:
1302 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_WARNING, "unsupported control request");
1303 status = LIBUSB_TRANSFER_STALL;
1307 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_ERROR, "control error = %s", darwin_error_str (result));
1308 status = LIBUSB_TRANSFER_ERROR;
1311 usbi_handle_transfer_completion(itransfer, status);
1314 static void darwin_isoc_callback (struct usbi_transfer *itransfer, kern_return_t result) {
1315 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1316 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1319 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "handling isoc completion with status %d", result);
1321 if (result == kIOReturnSuccess && tpriv->isoc_framelist) {
1322 /* copy isochronous results back */
1324 for (i = 0; i < transfer->num_iso_packets ; i++) {
1325 struct libusb_iso_packet_descriptor *lib_desc = transfer->iso_packet_desc;
1326 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1327 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1332 case kIOReturnSuccess:
1333 status = LIBUSB_TRANSFER_COMPLETED;
1335 case kIOReturnAborted:
1336 usbi_handle_transfer_cancellation(itransfer);
1338 case kIOUSBPipeStalled:
1339 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_WARNING, "unsupported control request");
1340 status = LIBUSB_TRANSFER_STALL;
1344 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_ERROR, "control error = %s", darwin_error_str (result));
1345 status = LIBUSB_TRANSFER_ERROR;
1348 usbi_handle_transfer_completion(itransfer, status);
1351 static void darwin_control_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1354 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "handling control completion with status %d", result);
1357 case kIOReturnSuccess:
1358 status = LIBUSB_TRANSFER_COMPLETED;
1359 itransfer->transferred += io_size;
1361 case kIOReturnAborted:
1362 usbi_handle_transfer_cancellation(itransfer);
1364 case kIOUSBPipeStalled:
1365 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_WARNING, "unsupported control request");
1366 status = LIBUSB_TRANSFER_STALL;
1370 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_ERROR, "control error = %s", darwin_error_str (result));
1371 status = LIBUSB_TRANSFER_ERROR;
1374 usbi_handle_transfer_completion(itransfer, status);
1377 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1378 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1380 switch (transfer->type) {
1381 case LIBUSB_TRANSFER_TYPE_CONTROL:
1382 darwin_control_callback (itransfer, result, io_size);
1384 case LIBUSB_TRANSFER_TYPE_BULK:
1385 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1386 darwin_bulk_callback (itransfer, result, io_size);
1388 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1389 darwin_isoc_callback (itransfer, result);
1392 _usbi_log (TRANSFER_CTX(transfer), LOG_LEVEL_ERROR, "unknown endpoint type %d", transfer->type);
1396 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, nfds_t nfds, int num_ready) {
1397 struct usbi_transfer *itransfer;
1403 pthread_mutex_lock(&ctx->open_devs_lock);
1404 for (i = 0; i < nfds && num_ready > 0; i++) {
1405 struct pollfd *pollfd = &fds[i];
1406 struct libusb_device_handle *handle;
1407 struct darwin_device_handle_priv *hpriv = NULL;
1409 _usbi_log (ctx, LOG_LEVEL_INFO, "checking fd %i with revents = %x", fds[i], pollfd->revents);
1411 if (!pollfd->revents)
1415 list_for_each_entry(handle, &ctx->open_devs, list) {
1416 hpriv = (struct darwin_device_handle_priv *)handle->os_priv;
1417 if (hpriv->fds[0] == pollfd->fd)
1421 if (!(pollfd->revents & POLLERR)) {
1422 ret = read (hpriv->fds[0], &message, sizeof (message));
1423 if (ret < sizeof (message))
1426 /* could not poll the device-- response is to delete the device (this seems a little heavy-handed) */
1427 message = MESSAGE_DEVICE_GONE;
1430 case MESSAGE_DEVICE_GONE:
1431 /* remove the device's async port from the runloop */
1432 if (hpriv->cfSource) {
1433 if (libusb_darwin_acfl)
1434 CFRunLoopRemoveSource (libusb_darwin_acfl, hpriv->cfSource, kCFRunLoopDefaultMode);
1435 CFRelease (hpriv->cfSource);
1436 hpriv->cfSource = NULL;
1439 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
1440 usbi_handle_disconnect(handle);
1442 /* done with this device */
1444 case MESSAGE_ASYNC_IO_COMPLETE:
1445 read (hpriv->fds[0], &itransfer, sizeof (itransfer));
1446 read (hpriv->fds[0], &kresult, sizeof (IOReturn));
1447 read (hpriv->fds[0], &io_size, sizeof (UInt32));
1449 darwin_handle_callback (itransfer, kresult, io_size);
1452 _usbi_log (ctx, LOG_LEVEL_ERROR, "unknown message received from device pipe");
1456 pthread_mutex_unlock(&ctx->open_devs_lock);
1461 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1462 mach_timespec_t sys_time;
1463 clock_serv_t clock_ref;
1466 case USBI_CLOCK_REALTIME:
1467 /* CLOCK_REALTIME represents time since the epoch */
1468 host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &clock_ref);
1470 case USBI_CLOCK_MONOTONIC:
1471 /* use system boot time as reference for the monotonic clock */
1472 host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &clock_ref);
1475 return LIBUSB_ERROR_INVALID_PARAM;
1478 clock_get_time (clock_ref, &sys_time);
1480 tp->tv_sec = sys_time.tv_sec;
1481 tp->tv_nsec = sys_time.tv_nsec;
1486 const struct usbi_os_backend darwin_backend = {
1488 .init = darwin_init,
1489 .exit = darwin_exit,
1490 .get_device_list = darwin_get_device_list,
1491 .get_device_descriptor = darwin_get_device_descriptor,
1492 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1493 .get_config_descriptor = darwin_get_config_descriptor,
1495 .open = darwin_open,
1496 .close = darwin_close,
1497 .get_configuration = darwin_get_configuration,
1498 .set_configuration = darwin_set_configuration,
1499 .claim_interface = darwin_claim_interface,
1500 .release_interface = darwin_release_interface,
1502 .set_interface_altsetting = darwin_set_interface_altsetting,
1503 .clear_halt = darwin_clear_halt,
1504 .reset_device = darwin_reset_device,
1506 .kernel_driver_active = darwin_kernel_driver_active,
1507 .detach_kernel_driver = darwin_detach_kernel_driver,
1508 .attach_kernel_driver = darwin_attach_kernel_driver,
1510 .destroy_device = darwin_destroy_device,
1512 .submit_transfer = darwin_submit_transfer,
1513 .cancel_transfer = darwin_cancel_transfer,
1514 .clear_transfer_priv = darwin_clear_transfer_priv,
1516 .handle_events = op_handle_events,
1518 .clock_gettime = darwin_clock_gettime,
1520 .device_priv_size = sizeof(struct darwin_device_priv),
1521 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1522 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1523 .add_iso_packet_size = 0,