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 list_for_each_entry(handle, &ctx->open_devs, list) {
229 dpriv = (struct darwin_device_priv *)handle->dev->os_priv;
230 if (dpriv->location == location)
235 priv = (struct darwin_device_handle_priv *)handle->os_priv;
237 message = MESSAGE_DEVICE_GONE;
238 write (priv->fds[1], &message, sizeof (message));
240 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
241 CFRelease (priv->cfSource);
242 priv->cfSource = NULL;
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 /* add the notification port to the run loop */
266 libusb_notification_port = IONotificationPortCreate (libusb_darwin_mp);
267 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
268 CFRunLoopAddSource(CFRunLoopGetCurrent (), libusb_notification_cfsource, kCFRunLoopDefaultMode);
270 /* create notifications for removed devices */
271 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
272 IOServiceMatching(kIOUSBDeviceClassName),
273 (IOServiceMatchingCallback)darwin_devices_detached,
274 (void *)ctx, &libusb_rem_device_iterator);
276 if (kresult != kIOReturnSuccess) {
277 _usbi_log (ctx, LOG_LEVEL_ERROR, "could not add hotplug event source: %s", darwin_error_str (kresult));
279 pthread_exit ((void *)kresult);
283 darwin_clear_iterator (libusb_rem_device_iterator);
285 /* let the main thread know about the async runloop */
286 libusb_darwin_acfl = CFRunLoopGetCurrent ();
288 _usbi_log (ctx, LOG_LEVEL_INFO, "libopenusb/darwin.c event_thread_main: thread ready to receive events");
290 /* run the runloop */
293 _usbi_log (ctx, LOG_LEVEL_INFO, "libopenusb/darwin.c event_thread_main: thread exiting");
295 /* delete notification port */
296 CFRunLoopSourceInvalidate (libusb_notification_cfsource);
297 IONotificationPortDestroy (libusb_notification_port);
299 libusb_darwin_acfl = NULL;
304 static int darwin_init(struct libusb_context *ctx) {
307 /* Create the master port for talking to IOKit */
308 if (!libusb_darwin_mp) {
309 kresult = IOMasterPort (MACH_PORT_NULL, &libusb_darwin_mp);
311 if (kresult != kIOReturnSuccess || !libusb_darwin_mp)
312 return darwin_to_libusb (kresult);
315 pthread_create (&libusb_darwin_at, NULL, event_thread_main, (void *)ctx);
317 while (!libusb_darwin_acfl)
323 static void darwin_exit (void) {
326 /* stop the async runloop */
327 CFRunLoopStop (libusb_darwin_acfl);
328 pthread_join (libusb_darwin_at, &ret);
330 if (libusb_darwin_mp)
331 mach_port_deallocate(mach_task_self(), libusb_darwin_mp);
333 libusb_darwin_mp = 0;
336 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
337 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
339 /* return cached copy */
340 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
347 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
348 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
352 kresult = (*(priv->device))->GetConfiguration (priv->device, &configNum);
353 if (kresult != kIOReturnSuccess)
354 return darwin_to_libusb (kresult);
356 return darwin_get_config_descriptor (dev, configNum, buffer, len, host_endian);
359 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
360 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
361 IOUSBConfigurationDescriptorPtr desc;
363 usb_device_t **device;
366 return LIBUSB_ERROR_OTHER;
369 kresult = darwin_get_device (priv->location, &device);
370 if (kresult || !device) {
371 _usbi_log (DEVICE_CTX (dev), LOG_LEVEL_ERROR, "could not find device: %s", darwin_error_str (kresult));
372 return darwin_to_libusb (kresult);
375 /* don't have to open the device to get a config descriptor */
377 device = priv->device;
379 kresult = (*device)->GetConfigurationDescriptorPtr (device, config_index, &desc);
380 if (kresult != kIOReturnSuccess)
381 return darwin_to_libusb (kresult);
384 (*device)->Release (device);
386 /* copy descriptor */
387 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
388 len = libusb_le16_to_cpu(desc->wTotalLength);
390 memmove (buffer, desc, len);
392 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
398 static int process_new_device (struct libusb_context *ctx, usb_device_t **device, UInt32 locationID, struct discovered_devs **_discdevs) {
399 struct darwin_device_priv *priv;
400 struct libusb_device *dev;
401 struct discovered_devs *discdevs;
402 UInt16 address, idVendor, idProduct;
403 UInt8 bDeviceClass, bDeviceSubClass;
407 dev = usbi_get_device_by_session_id(ctx, locationID);
409 _usbi_log (ctx, LOG_LEVEL_INFO, "allocating new device for location 0x%08x", locationID);
410 dev = usbi_alloc_device(ctx, locationID);
412 return LIBUSB_ERROR_NO_MEM;
414 priv = (struct darwin_device_priv *)dev->os_priv;
416 /* Set up request for device descriptor */
417 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
418 req.bRequest = kUSBRqGetDescriptor;
419 req.wValue = kUSBDeviceDesc << 8;
421 req.wLength = sizeof(IOUSBDeviceDescriptor);
422 req.pData = &(priv->dev_descriptor);
424 (*(device))->GetDeviceAddress (device, (USBDeviceAddress *)&address);
425 (*(device))->GetDeviceProduct (device, &idProduct);
426 (*(device))->GetDeviceVendor (device, &idVendor);
427 (*(device))->GetDeviceClass (device, &bDeviceClass);
428 (*(device))->GetDeviceSubClass (device, &bDeviceSubClass);
430 /**** retrieve device descriptors ****/
431 /* device must be open for DeviceRequest */
432 (*device)->USBDeviceOpen(device);
434 ret = (*(device))->DeviceRequest (device, &req);
435 if (ret != kIOReturnSuccess) {
436 int try_unsuspend = 1;
439 /* device may be suspended. unsuspend it and try again */
440 #if DeviceVersion >= 320
441 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
442 (void)(*device)->GetUSBDeviceInformation (device, &info);
444 try_unsuspend = info & (1 << kUSBInformationDeviceIsSuspendedBit);
448 /* resume the device */
449 (void)(*device)->USBDeviceSuspend (device, 0);
451 ret = (*(device))->DeviceRequest (device, &req);
453 /* resuspend the device */
454 (void)(*device)->USBDeviceSuspend (device, 1);
458 (*device)->USBDeviceClose (device);
460 if (ret != kIOReturnSuccess) {
461 _usbi_log (ctx, LOG_LEVEL_WARNING, "could not retrieve device descriptor: %s. skipping device", darwin_error_str (ret));
462 libusb_unref_device(dev);
465 /**** end: retrieve device descriptors ****/
467 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
468 if (libusb_le16_to_cpu (priv->dev_descriptor.idProduct) != idProduct) {
469 /* not a valid device */
470 _usbi_log (ctx, LOG_LEVEL_WARNING, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
471 idProduct, libusb_le16_to_cpu (priv->dev_descriptor.idProduct));
472 libusb_unref_device(dev);
476 dev->bus_number = locationID >> 24;
477 dev->device_address = address;
479 /* save our location, we'll need this later */
480 priv->location = locationID;
481 snprintf(priv->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", address, idVendor, idProduct, bDeviceClass, bDeviceSubClass);
483 ret = usbi_sanitize_device(dev);
486 libusb_unref_device(dev);
490 priv = (struct darwin_device_priv *)dev->os_priv;
492 _usbi_log (ctx, LOG_LEVEL_INFO, "using existing device for location 0x%08x", locationID);
495 /* append the device to the list of discovered devices */
496 discdevs = discovered_devs_append(*_discdevs, dev);
498 return LIBUSB_ERROR_NO_MEM;
500 *_discdevs = discdevs;
502 _usbi_log (ctx, LOG_LEVEL_INFO, "found device with address %d at %s", dev->device_address, priv->sys_path);
507 static int darwin_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs) {
508 io_iterator_t deviceIterator;
509 usb_device_t **device;
510 kern_return_t kresult;
513 if (!libusb_darwin_mp)
514 return LIBUSB_ERROR_INVALID_PARAM;
516 kresult = usb_setup_device_iterator (&deviceIterator);
517 if (kresult != kIOReturnSuccess)
518 return darwin_to_libusb (kresult);
520 while ((device = usb_get_next_device (deviceIterator, &location)) != NULL) {
521 (void) process_new_device (ctx, device, location, _discdevs);
523 (*(device))->Release(device);
526 IOObjectRelease(deviceIterator);
531 static int darwin_open (struct libusb_device_handle *dev_handle) {
532 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
533 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
534 usb_device_t **darwin_device;
537 kresult = darwin_get_device (dpriv->location, &darwin_device);
539 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "could not find device: %s", darwin_error_str (kresult));
540 return darwin_to_libusb (kresult);
543 dpriv->device = darwin_device;
545 /* try to open the device */
546 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
548 if (kresult != kIOReturnSuccess) {
549 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "USBDeviceOpen: %s", darwin_error_str(kresult));
552 case kIOReturnExclusiveAccess:
553 /* it is possible to perform some actions on a device that is not open so do not return an error */
558 (*(dpriv->device))->Release (dpriv->device);
559 dpriv->device = NULL;
560 return darwin_to_libusb (kresult);
565 /* create async event source */
566 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
568 CFRetain (libusb_darwin_acfl);
570 /* add the cfSource to the aync run loop */
571 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
574 /* create a file descriptor for notifications */
577 /* set the pipe to be non-blocking */
578 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
580 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
582 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "device open for access");
587 static void darwin_close (struct libusb_device_handle *dev_handle) {
588 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
589 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
593 /* make sure all interfaces are released */
594 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
595 if (dev_handle->claimed_interfaces & (1 << i))
596 libusb_release_interface (dev_handle, i);
599 /* delete the device's async event source */
600 if (priv->cfSource) {
601 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
602 CFRelease (priv->cfSource);
605 /* close the device */
606 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
608 /* Log the fact that we had a problem closing the file, however failing a
609 * close isn't really an error, so return success anyway */
610 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "USBDeviceClose: %s", darwin_error_str(kresult));
614 kresult = (*(dpriv->device))->Release(dpriv->device);
616 /* Log the fact that we had a problem closing the file, however failing a
617 * close isn't really an error, so return success anyway */
618 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "Release: %s", darwin_error_str(kresult));
621 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
622 close (priv->fds[1]);
623 close (priv->fds[0]);
626 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
627 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
631 kresult = (*(dpriv->device))->GetConfiguration (dpriv->device, &configNum);
632 if (kresult != kIOReturnSuccess)
633 return darwin_to_libusb (kresult);
635 *config = (int) configNum;
640 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
641 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
645 /* Setting configuration will invalidate the interface, so we need
646 to reclaim it. First, dispose of existing interfaces, if any. */
647 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
648 if (dev_handle->claimed_interfaces & (1 << i))
649 darwin_release_interface (dev_handle, i);
651 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
652 if (kresult != kIOReturnSuccess)
653 return darwin_to_libusb (kresult);
655 /* Reclaim any interfaces. */
656 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
657 if (dev_handle->claimed_interfaces & (1 << i))
658 darwin_claim_interface (dev_handle, i);
663 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
664 IOUSBFindInterfaceRequest request;
665 uint8_t current_interface;
666 kern_return_t kresult;
667 io_iterator_t interface_iterator;
669 *usbInterfacep = IO_OBJECT_NULL;
671 /* Setup the Interface Request */
672 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
673 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
674 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
675 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
677 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
681 for ( current_interface = 0 ; current_interface <= ifc ; current_interface++ )
682 *usbInterfacep = IOIteratorNext(interface_iterator);
684 /* done with the interface iterator */
685 IOObjectRelease(interface_iterator);
690 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
691 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
693 /* current interface */
694 struct __darwin_interface *cInterface = &priv->interfaces[iface];
696 kern_return_t kresult;
698 u_int8_t numep, direction, number;
699 u_int8_t dont_care1, dont_care3;
700 u_int16_t dont_care2;
703 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "building table of endpoints.");
705 /* retrieve the total number of endpoints on this interface */
706 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
708 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
709 return darwin_to_libusb (kresult);
712 /* iterate through pipe references */
713 for (i = 1 ; i <= numep ; i++) {
714 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
715 &dont_care2, &dont_care3);
717 if (kresult != kIOReturnSuccess) {
718 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
720 return darwin_to_libusb (kresult);
723 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
725 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
728 cInterface->num_endpoints = numep;
733 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
734 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
735 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
736 io_service_t usbInterface = IO_OBJECT_NULL;
738 IOCFPlugInInterface **plugInInterface = NULL;
742 /* current interface */
743 struct __darwin_interface *cInterface = &priv->interfaces[iface];
745 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
746 if (kresult != kIOReturnSuccess)
747 return darwin_to_libusb (kresult);
749 /* make sure we have an interface */
751 u_int8_t nConfig; /* Index of configuration to use */
752 IOUSBConfigurationDescriptorPtr configDesc; /* to describe which configuration to select */
753 /* Only a composite class device with no vendor-specific driver will
754 be configured. Otherwise, we need to do it ourselves, or there
755 will be no interfaces for the device. */
757 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "no interface found; selecting configuration" );
759 kresult = (*(dpriv->device))->GetNumberOfConfigurations (dpriv->device, &nConfig);
760 if (kresult != kIOReturnSuccess) {
761 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "GetNumberOfConfigurations: %s", darwin_error_str(kresult));
762 return darwin_to_libusb(kresult);
766 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "GetNumberOfConfigurations: no configurations");
767 return LIBUSB_ERROR_OTHER;
770 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "device has %d configuration%s. using the first",
771 (int)nConfig, (nConfig > 1 ? "s" : "") );
773 /* Always use the first configuration */
774 kresult = (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, 0, &configDesc);
775 if (kresult != kIOReturnSuccess) {
776 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "GetConfigurationDescriptorPtr: %s",
777 darwin_error_str(kresult));
781 new_config = configDesc->bConfigurationValue;
783 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "new configuration value is %d", new_config);
785 /* set the configuration */
786 kresult = darwin_set_configuration (dev_handle, new_config);
787 if (kresult != LIBUSB_SUCCESS) {
788 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "could not set configuration");
792 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
794 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "darwin_get_interface: %s", darwin_error_str(kresult));
795 return darwin_to_libusb (kresult);
800 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "interface not found");
801 return LIBUSB_ERROR_NOT_FOUND;
804 /* get an interface to the device's interface */
805 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
806 kIOCFPlugInInterfaceID, &plugInInterface, &score);
807 kresult = IOObjectRelease(usbInterface);
808 if (kresult || !plugInInterface)
809 return darwin_to_libusb (kresult);
811 /* Do the actual claim */
812 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
813 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
814 (LPVOID)&cInterface->interface);
815 if (kresult || !cInterface->interface) {
816 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "QueryInterface: %s", darwin_error_str(kresult));
817 return darwin_to_libusb (kresult);
820 /* We no longer need the intermediate plug-in */
821 (*plugInInterface)->Release(plugInInterface);
823 /* claim the interface */
824 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
826 _usbi_log(HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "USBInterfaceOpen: %s", darwin_error_str(kresult));
827 return darwin_to_libusb (kresult);
830 /* update list of endpoints */
831 kresult = get_endpoints (dev_handle, iface);
833 /* this should not happen */
834 darwin_release_interface (dev_handle, iface);
835 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "could not build endpoint table");
839 /* create async event source */
840 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
842 /* add the cfSource to the aync run loop */
843 CFRetain (libusb_darwin_acfl);
844 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
846 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "interface opened");
851 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
852 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
855 /* current interface */
856 struct __darwin_interface *cInterface = &priv->interfaces[iface];
858 /* Check to see if an interface is open */
859 if (!cInterface->interface)
860 return LIBUSB_SUCCESS;
862 /* clean up endpoint data */
863 cInterface->num_endpoints = 0;
865 /* delete the interface's async event source */
866 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
867 CFRelease (cInterface->cfSource);
869 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
871 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "USBInterfaceClose: %s", darwin_error_str(kresult));
873 kresult = (*(cInterface->interface))->Release(cInterface->interface);
874 if (kresult != kIOReturnSuccess)
875 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "Release: %s", darwin_error_str(kresult));
877 cInterface->interface = IO_OBJECT_NULL;
879 return darwin_to_libusb (kresult);
882 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
883 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
886 /* current interface */
887 struct __darwin_interface *cInterface = &priv->interfaces[iface];
889 if (!cInterface->interface)
890 return LIBUSB_ERROR_NO_DEVICE;
892 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
893 if (kresult != kIOReturnSuccess)
894 darwin_reset_device (dev_handle);
896 return darwin_to_libusb (kresult);
899 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
900 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
902 /* current interface */
903 struct __darwin_interface *cInterface;
904 uint8_t pipeRef, iface;
907 /* determine the interface/endpoint to use */
908 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
909 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
911 return LIBUSB_ERROR_NOT_FOUND;
914 cInterface = &priv->interfaces[iface];
916 #if (InterfaceVersion < 190)
917 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
919 /* newer versions of darwin support clearing additional bits on the device's endpoint */
920 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
923 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "ClearPipeStall: %s", darwin_error_str (kresult));
925 return darwin_to_libusb (kresult);
928 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
929 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
932 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
934 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "ResetDevice: %s", darwin_error_str (kresult));
936 return darwin_to_libusb (kresult);
939 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
940 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
941 io_service_t usbInterface;
945 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
947 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "darwin_get_interface: %s", darwin_error_str(kresult));
949 return darwin_to_libusb (kresult);
952 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
953 IOObjectRelease (usbInterface);
965 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
966 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
967 return LIBUSB_ERROR_NOT_SUPPORTED;
970 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
971 return LIBUSB_ERROR_NOT_SUPPORTED;
974 static void darwin_destroy_device(struct libusb_device *dev) {
977 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
978 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
979 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
982 uint8_t is_read; /* 0 = we're reading, 1 = we're writing */
983 uint8_t transferType;
984 /* None of the values below are used in libusb for bulk transfers */
985 uint8_t direction, number, interval, pipeRef, iface;
986 uint16_t maxPacketSize;
988 struct __darwin_interface *cInterface;
990 /* are we reading or writing? */
991 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
993 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
994 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
996 return LIBUSB_ERROR_NOT_FOUND;
999 cInterface = &priv->interfaces[iface];
1001 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1002 &transferType, &maxPacketSize, &interval);
1004 /* submit the request */
1005 /* timeouts are unavailable on interrupt endpoints */
1006 if (transferType == kUSBInterrupt) {
1008 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1009 transfer->length, darwin_async_io_callback, itransfer);
1011 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1012 transfer->length, darwin_async_io_callback, itransfer);
1015 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1016 transfer->length, transfer->timeout, transfer->timeout,
1017 darwin_async_io_callback, (void *)itransfer);
1019 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1020 transfer->length, transfer->timeout, transfer->timeout,
1021 darwin_async_io_callback, (void *)itransfer);
1025 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "bulk transfer failed (dir = %s): %s", is_read ? "In" : "Out",
1026 darwin_error_str(ret));
1028 return darwin_to_libusb (ret);
1031 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1032 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1033 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1034 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1037 uint8_t is_read; /* 0 = we're writing, 1 = we're reading */
1038 uint8_t pipeRef, iface;
1040 AbsoluteTime atTime;
1043 struct __darwin_interface *cInterface;
1045 /* are we reading or writing? */
1046 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1048 /* construct an array of IOUSBIsocFrames */
1049 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1050 if (!tpriv->isoc_framelist)
1051 return LIBUSB_ERROR_NO_MEM;
1053 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1054 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1055 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1057 /* determine the interface/endpoint to use */
1058 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1059 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
1061 return LIBUSB_ERROR_NOT_FOUND;
1064 cInterface = &priv->interfaces[iface];
1066 /* Last but not least we need the bus frame number */
1067 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1069 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "failed to get bus frame number: %d", kresult);
1070 free(tpriv->isoc_framelist);
1071 tpriv->isoc_framelist = NULL;
1073 return darwin_to_libusb (kresult);
1076 /* schedule for a frame a little in the future */
1079 /* submit the request */
1081 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1082 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1085 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1086 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1089 if (kresult != kIOReturnSuccess) {
1090 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "isochronous transfer failed (dir: %s): %s", is_read ? "In" : "Out",
1091 darwin_error_str(kresult));
1092 free (tpriv->isoc_framelist);
1093 tpriv->isoc_framelist = NULL;
1096 return darwin_to_libusb (kresult);
1099 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1100 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1101 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1102 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1103 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1107 bzero(&tpriv->req, sizeof(tpriv->req));
1109 /* IOUSBDeviceInterface expects the request in cpu endianess */
1110 tpriv->req.bmRequestType = setup->bmRequestType;
1111 tpriv->req.bRequest = setup->bRequest;
1112 /* these values should already be in bus order */
1113 tpriv->req.wValue = setup->wValue;
1114 tpriv->req.wIndex = setup->wIndex;
1115 tpriv->req.wLength = setup->wLength;
1116 /* data is stored after the libusb control block */
1117 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1118 tpriv->req.completionTimeout = transfer->timeout;
1119 tpriv->req.noDataTimeout = transfer->timeout;
1121 /* all transfers in libusb-1.0 are async */
1122 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1124 if (kresult != kIOReturnSuccess)
1125 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "control request failed: %s", darwin_error_str(kresult));
1127 return darwin_to_libusb (kresult);
1130 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1131 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1133 switch (transfer->type) {
1134 case LIBUSB_TRANSFER_TYPE_CONTROL:
1135 return submit_control_transfer(itransfer);
1136 case LIBUSB_TRANSFER_TYPE_BULK:
1137 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1138 return submit_bulk_transfer(itransfer);
1139 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1140 return submit_iso_transfer(itransfer);
1142 _usbi_log (TRANSFER_CTX(transfer), LOG_LEVEL_ERROR, "unknown endpoint type %d", transfer->type);
1143 return LIBUSB_ERROR_INVALID_PARAM;
1147 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1148 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1149 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1152 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "WARNING: aborting all transactions control pipe");
1154 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1156 return darwin_to_libusb (kresult);
1159 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1160 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1161 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1162 struct __darwin_interface *cInterface;
1163 uint8_t pipeRef, iface;
1166 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1167 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
1169 return LIBUSB_ERROR_NOT_FOUND;
1172 cInterface = &priv->interfaces[iface];
1174 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "WARNING: aborting all transactions on interface %d pipe %d", iface, pipeRef);
1176 /* abort transactions */
1177 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1179 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "calling clear pipe stall to clear the data toggle bit");
1181 /* clear the data toggle bit */
1182 #if (InterfaceVersion < 190)
1183 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1185 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1186 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1189 return darwin_to_libusb (kresult);
1192 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1193 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1195 switch (transfer->type) {
1196 case LIBUSB_TRANSFER_TYPE_CONTROL:
1197 return cancel_control_transfer(itransfer);
1198 case LIBUSB_TRANSFER_TYPE_BULK:
1199 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1200 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1201 return darwin_abort_transfers (itransfer);
1203 _usbi_log (TRANSFER_CTX(transfer), LOG_LEVEL_ERROR, "unknown endpoint type %d", transfer->type);
1204 return LIBUSB_ERROR_INVALID_PARAM;
1208 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1209 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1210 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1212 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1213 free (tpriv->isoc_framelist);
1214 tpriv->isoc_framelist = NULL;
1218 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1219 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1220 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1221 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1224 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "an async io operation has completed");
1226 /* send a completion message to the device's file descriptor */
1227 message = MESSAGE_ASYNC_IO_COMPLETE;
1228 write (priv->fds[1], &message, sizeof (message));
1229 write (priv->fds[1], &itransfer, sizeof (itransfer));
1230 write (priv->fds[1], &result, sizeof (IOReturn));
1231 write (priv->fds[1], &arg0, sizeof (UInt32));
1234 static void darwin_bulk_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1235 enum libusb_transfer_status status;
1237 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "handling bulk completion with status %d", result);
1240 case kIOReturnSuccess:
1241 status = LIBUSB_TRANSFER_COMPLETED;
1242 itransfer->transferred += io_size;
1244 case kIOReturnAborted:
1245 usbi_handle_transfer_cancellation(itransfer);
1247 case kIOUSBPipeStalled:
1248 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_WARNING, "unsupported control request");
1249 status = LIBUSB_TRANSFER_STALL;
1253 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_ERROR, "control error = %s", darwin_error_str (result));
1254 status = LIBUSB_TRANSFER_ERROR;
1257 usbi_handle_transfer_completion(itransfer, status);
1260 static void darwin_isoc_callback (struct usbi_transfer *itransfer, kern_return_t result) {
1261 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1262 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1265 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "handling isoc completion with status %d", result);
1267 if (result == kIOReturnSuccess && tpriv->isoc_framelist) {
1268 /* copy isochronous results back */
1270 for (i = 0; i < transfer->num_iso_packets ; i++) {
1271 struct libusb_iso_packet_descriptor *lib_desc = transfer->iso_packet_desc;
1272 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1273 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1278 case kIOReturnSuccess:
1279 status = LIBUSB_TRANSFER_COMPLETED;
1281 case kIOReturnAborted:
1282 usbi_handle_transfer_cancellation(itransfer);
1284 case kIOUSBPipeStalled:
1285 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_WARNING, "unsupported control request");
1286 status = LIBUSB_TRANSFER_STALL;
1290 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_ERROR, "control error = %s", darwin_error_str (result));
1291 status = LIBUSB_TRANSFER_ERROR;
1294 usbi_handle_transfer_completion(itransfer, status);
1297 static void darwin_control_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1300 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "handling control completion with status %d", result);
1303 case kIOReturnSuccess:
1304 status = LIBUSB_TRANSFER_COMPLETED;
1305 itransfer->transferred += io_size;
1307 case kIOReturnAborted:
1308 usbi_handle_transfer_cancellation(itransfer);
1310 case kIOUSBPipeStalled:
1311 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_WARNING, "unsupported control request");
1312 status = LIBUSB_TRANSFER_STALL;
1316 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_ERROR, "control error = %s", darwin_error_str (result));
1317 status = LIBUSB_TRANSFER_ERROR;
1320 usbi_handle_transfer_completion(itransfer, status);
1323 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1324 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1326 switch (transfer->type) {
1327 case LIBUSB_TRANSFER_TYPE_CONTROL:
1328 darwin_control_callback (itransfer, result, io_size);
1330 case LIBUSB_TRANSFER_TYPE_BULK:
1331 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1332 darwin_bulk_callback (itransfer, result, io_size);
1334 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1335 darwin_isoc_callback (itransfer, result);
1338 _usbi_log (TRANSFER_CTX(transfer), LOG_LEVEL_ERROR, "unknown endpoint type %d", transfer->type);
1342 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, nfds_t nfds, int num_ready) {
1343 struct usbi_transfer *itransfer;
1349 pthread_mutex_lock(&ctx->open_devs_lock);
1350 for (i = 0; i < nfds && num_ready > 0; i++) {
1351 struct pollfd *pollfd = &fds[i];
1352 struct libusb_device_handle *handle;
1353 struct darwin_device_handle_priv *hpriv = NULL;
1355 _usbi_log (ctx, LOG_LEVEL_INFO, "checking fd %i with revents = %x", fds[i], pollfd->revents);
1357 if (!pollfd->revents)
1361 list_for_each_entry(handle, &ctx->open_devs, list) {
1362 hpriv = (struct darwin_device_handle_priv *)handle->os_priv;
1363 if (hpriv->fds[0] == pollfd->fd)
1367 if (pollfd->revents & POLLERR) {
1368 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
1369 usbi_handle_disconnect(handle);
1371 /* done with this device */
1375 ret = read (hpriv->fds[0], &message, sizeof (message));
1376 if (ret < sizeof (message))
1380 case MESSAGE_DEVICE_GONE:
1381 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
1382 usbi_handle_disconnect(handle);
1384 /* done with this device */
1386 case MESSAGE_ASYNC_IO_COMPLETE:
1387 read (hpriv->fds[0], &itransfer, sizeof (itransfer));
1388 read (hpriv->fds[0], &kresult, sizeof (IOReturn));
1389 read (hpriv->fds[0], &io_size, sizeof (UInt32));
1391 darwin_handle_callback (itransfer, kresult, io_size);
1394 _usbi_log (ctx, LOG_LEVEL_ERROR, "unknown message received from device pipe");
1398 pthread_mutex_unlock(&ctx->open_devs_lock);
1403 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1404 mach_timespec_t sys_time;
1405 clock_serv_t clock_ref;
1408 case USBI_CLOCK_REALTIME:
1409 /* CLOCK_REALTIME represents time since the epoch */
1410 host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &clock_ref);
1412 case USBI_CLOCK_MONOTONIC:
1413 /* use system boot time as reference for the monotonic clock */
1414 host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &clock_ref);
1417 return LIBUSB_ERROR_INVALID_PARAM;
1420 clock_get_time (clock_ref, &sys_time);
1422 tp->tv_sec = sys_time.tv_sec;
1423 tp->tv_nsec = sys_time.tv_nsec;
1428 const struct usbi_os_backend darwin_backend = {
1430 .init = darwin_init,
1431 .exit = darwin_exit,
1432 .get_device_list = darwin_get_device_list,
1433 .get_device_descriptor = darwin_get_device_descriptor,
1434 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1435 .get_config_descriptor = darwin_get_config_descriptor,
1437 .open = darwin_open,
1438 .close = darwin_close,
1439 .get_configuration = darwin_get_configuration,
1440 .set_configuration = darwin_set_configuration,
1441 .claim_interface = darwin_claim_interface,
1442 .release_interface = darwin_release_interface,
1444 .set_interface_altsetting = darwin_set_interface_altsetting,
1445 .clear_halt = darwin_clear_halt,
1446 .reset_device = darwin_reset_device,
1448 .kernel_driver_active = darwin_kernel_driver_active,
1449 .detach_kernel_driver = darwin_detach_kernel_driver,
1450 .attach_kernel_driver = darwin_attach_kernel_driver,
1452 .destroy_device = darwin_destroy_device,
1454 .submit_transfer = darwin_submit_transfer,
1455 .cancel_transfer = darwin_cancel_transfer,
1456 .clear_transfer_priv = darwin_clear_transfer_priv,
1458 .handle_events = op_handle_events,
1460 .clock_gettime = darwin_clock_gettime,
1462 .device_priv_size = sizeof(struct darwin_device_priv),
1463 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1464 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1465 .add_iso_packet_size = 0,