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 get_configuration_index (struct libusb_device *dev, int config_value) {
348 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
350 IOUSBConfigurationDescriptorPtr desc;
353 /* is there a simpler way to determine the index? */
354 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
355 if (kresult != kIOReturnSuccess)
356 return darwin_to_libusb (kresult);
358 for (i = 0 ; i < numConfig ; i++) {
359 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
361 if (libusb_le16_to_cpu (desc->bConfigurationValue) == config_value)
365 /* configuration not found */
366 return LIBUSB_ERROR_OTHER;
369 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
370 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
375 kresult = (*(priv->device))->GetConfiguration (priv->device, &config_value);
376 if (kresult != kIOReturnSuccess)
377 return darwin_to_libusb (kresult);
379 config_index = get_configuration_index (dev, config_value);
380 if (config_index < 0)
383 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
386 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
387 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
388 IOUSBConfigurationDescriptorPtr desc;
390 usb_device_t **device = NULL;
393 return LIBUSB_ERROR_OTHER;
396 kresult = darwin_get_device (priv->location, &device);
397 if (kresult || !device) {
398 _usbi_log (DEVICE_CTX (dev), LOG_LEVEL_ERROR, "could not find device: %s", darwin_error_str (kresult));
400 return darwin_to_libusb (kresult);
403 /* don't have to open the device to get a config descriptor */
405 device = priv->device;
407 kresult = (*device)->GetConfigurationDescriptorPtr (device, config_index, &desc);
408 if (kresult == kIOReturnSuccess) {
409 /* copy descriptor */
410 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
411 len = libusb_le16_to_cpu(desc->wTotalLength);
413 memmove (buffer, desc, len);
415 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
420 (*device)->Release (device);
422 return darwin_to_libusb (kresult);
425 static int process_new_device (struct libusb_context *ctx, usb_device_t **device, UInt32 locationID, struct discovered_devs **_discdevs) {
426 struct darwin_device_priv *priv;
427 struct libusb_device *dev;
428 struct discovered_devs *discdevs;
429 UInt16 address, idVendor, idProduct;
430 UInt8 bDeviceClass, bDeviceSubClass;
434 dev = usbi_get_device_by_session_id(ctx, locationID);
436 _usbi_log (ctx, LOG_LEVEL_INFO, "allocating new device for location 0x%08x", locationID);
437 dev = usbi_alloc_device(ctx, locationID);
439 return LIBUSB_ERROR_NO_MEM;
441 priv = (struct darwin_device_priv *)dev->os_priv;
443 /* Set up request for device descriptor */
444 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
445 req.bRequest = kUSBRqGetDescriptor;
446 req.wValue = kUSBDeviceDesc << 8;
448 req.wLength = sizeof(IOUSBDeviceDescriptor);
449 req.pData = &(priv->dev_descriptor);
451 (*(device))->GetDeviceAddress (device, (USBDeviceAddress *)&address);
452 (*(device))->GetDeviceProduct (device, &idProduct);
453 (*(device))->GetDeviceVendor (device, &idVendor);
454 (*(device))->GetDeviceClass (device, &bDeviceClass);
455 (*(device))->GetDeviceSubClass (device, &bDeviceSubClass);
457 /**** retrieve device descriptors ****/
458 /* device must be open for DeviceRequest */
459 (*device)->USBDeviceOpen(device);
461 ret = (*(device))->DeviceRequest (device, &req);
462 if (ret != kIOReturnSuccess) {
463 int try_unsuspend = 1;
466 /* device may be suspended. unsuspend it and try again */
467 #if DeviceVersion >= 320
468 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
469 (void)(*device)->GetUSBDeviceInformation (device, &info);
471 try_unsuspend = info & (1 << kUSBInformationDeviceIsSuspendedBit);
475 /* resume the device */
476 (void)(*device)->USBDeviceSuspend (device, 0);
478 ret = (*(device))->DeviceRequest (device, &req);
480 /* resuspend the device */
481 (void)(*device)->USBDeviceSuspend (device, 1);
485 (*device)->USBDeviceClose (device);
487 if (ret != kIOReturnSuccess) {
488 _usbi_log (ctx, LOG_LEVEL_WARNING, "could not retrieve device descriptor: %s. skipping device", darwin_error_str (ret));
489 libusb_unref_device(dev);
492 /**** end: retrieve device descriptors ****/
494 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
495 if (libusb_le16_to_cpu (priv->dev_descriptor.idProduct) != idProduct) {
496 /* not a valid device */
497 _usbi_log (ctx, LOG_LEVEL_WARNING, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
498 idProduct, libusb_le16_to_cpu (priv->dev_descriptor.idProduct));
499 libusb_unref_device(dev);
503 dev->bus_number = locationID >> 24;
504 dev->device_address = address;
506 /* save our location, we'll need this later */
507 priv->location = locationID;
508 snprintf(priv->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", address, idVendor, idProduct, bDeviceClass, bDeviceSubClass);
510 ret = usbi_sanitize_device(dev);
513 libusb_unref_device(dev);
517 priv = (struct darwin_device_priv *)dev->os_priv;
519 _usbi_log (ctx, LOG_LEVEL_INFO, "using existing device for location 0x%08x", locationID);
522 /* append the device to the list of discovered devices */
523 discdevs = discovered_devs_append(*_discdevs, dev);
525 return LIBUSB_ERROR_NO_MEM;
527 *_discdevs = discdevs;
529 _usbi_log (ctx, LOG_LEVEL_INFO, "found device with address %d at %s", dev->device_address, priv->sys_path);
534 static int darwin_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs) {
535 io_iterator_t deviceIterator;
536 usb_device_t **device;
537 kern_return_t kresult;
540 if (!libusb_darwin_mp)
541 return LIBUSB_ERROR_INVALID_PARAM;
543 kresult = usb_setup_device_iterator (&deviceIterator);
544 if (kresult != kIOReturnSuccess)
545 return darwin_to_libusb (kresult);
547 while ((device = usb_get_next_device (deviceIterator, &location)) != NULL) {
548 (void) process_new_device (ctx, device, location, _discdevs);
550 (*(device))->Release(device);
553 IOObjectRelease(deviceIterator);
558 static int darwin_open (struct libusb_device_handle *dev_handle) {
559 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
560 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
561 usb_device_t **darwin_device;
564 kresult = darwin_get_device (dpriv->location, &darwin_device);
566 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "could not find device: %s", darwin_error_str (kresult));
567 return darwin_to_libusb (kresult);
570 dpriv->device = darwin_device;
572 /* try to open the device */
573 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
575 if (kresult != kIOReturnSuccess) {
576 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "USBDeviceOpen: %s", darwin_error_str(kresult));
579 case kIOReturnExclusiveAccess:
580 /* it is possible to perform some actions on a device that is not open so do not return an error */
585 (*(dpriv->device))->Release (dpriv->device);
586 dpriv->device = NULL;
587 return darwin_to_libusb (kresult);
592 /* create async event source */
593 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
595 CFRetain (libusb_darwin_acfl);
597 /* add the cfSource to the aync run loop */
598 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
601 /* create a file descriptor for notifications */
604 /* set the pipe to be non-blocking */
605 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
607 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
609 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "device open for access");
614 static void darwin_close (struct libusb_device_handle *dev_handle) {
615 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
616 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
620 /* make sure all interfaces are released */
621 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
622 if (dev_handle->claimed_interfaces & (1 << i))
623 libusb_release_interface (dev_handle, i);
626 /* delete the device's async event source */
627 if (priv->cfSource) {
628 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
629 CFRelease (priv->cfSource);
632 /* close the device */
633 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
635 /* Log the fact that we had a problem closing the file, however failing a
636 * close isn't really an error, so return success anyway */
637 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "USBDeviceClose: %s", darwin_error_str(kresult));
641 kresult = (*(dpriv->device))->Release(dpriv->device);
643 /* Log the fact that we had a problem closing the file, however failing a
644 * close isn't really an error, so return success anyway */
645 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "Release: %s", darwin_error_str(kresult));
648 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
649 close (priv->fds[1]);
650 close (priv->fds[0]);
653 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
654 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
658 kresult = (*(dpriv->device))->GetConfiguration (dpriv->device, &configNum);
659 if (kresult != kIOReturnSuccess)
660 return darwin_to_libusb (kresult);
662 *config = (int) configNum;
667 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
668 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
672 /* Setting configuration will invalidate the interface, so we need
673 to reclaim it. First, dispose of existing interfaces, if any. */
674 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
675 if (dev_handle->claimed_interfaces & (1 << i))
676 darwin_release_interface (dev_handle, i);
678 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
679 if (kresult != kIOReturnSuccess)
680 return darwin_to_libusb (kresult);
682 /* Reclaim any interfaces. */
683 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
684 if (dev_handle->claimed_interfaces & (1 << i))
685 darwin_claim_interface (dev_handle, i);
690 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
691 IOUSBFindInterfaceRequest request;
692 uint8_t current_interface;
693 kern_return_t kresult;
694 io_iterator_t interface_iterator;
696 *usbInterfacep = IO_OBJECT_NULL;
698 /* Setup the Interface Request */
699 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
700 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
701 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
702 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
704 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
708 for ( current_interface = 0 ; current_interface <= ifc ; current_interface++ )
709 *usbInterfacep = IOIteratorNext(interface_iterator);
711 /* done with the interface iterator */
712 IOObjectRelease(interface_iterator);
717 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
718 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
720 /* current interface */
721 struct __darwin_interface *cInterface = &priv->interfaces[iface];
723 kern_return_t kresult;
725 u_int8_t numep, direction, number;
726 u_int8_t dont_care1, dont_care3;
727 u_int16_t dont_care2;
730 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "building table of endpoints.");
732 /* retrieve the total number of endpoints on this interface */
733 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
735 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
736 return darwin_to_libusb (kresult);
739 /* iterate through pipe references */
740 for (i = 1 ; i <= numep ; i++) {
741 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
742 &dont_care2, &dont_care3);
744 if (kresult != kIOReturnSuccess) {
745 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
747 return darwin_to_libusb (kresult);
750 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
752 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
755 cInterface->num_endpoints = numep;
760 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
761 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
762 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
763 io_service_t usbInterface = IO_OBJECT_NULL;
765 IOCFPlugInInterface **plugInInterface = NULL;
769 /* current interface */
770 struct __darwin_interface *cInterface = &priv->interfaces[iface];
772 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
773 if (kresult != kIOReturnSuccess)
774 return darwin_to_libusb (kresult);
776 /* make sure we have an interface */
778 u_int8_t nConfig; /* Index of configuration to use */
779 IOUSBConfigurationDescriptorPtr configDesc; /* to describe which configuration to select */
780 /* Only a composite class device with no vendor-specific driver will
781 be configured. Otherwise, we need to do it ourselves, or there
782 will be no interfaces for the device. */
784 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "no interface found; selecting configuration" );
786 kresult = (*(dpriv->device))->GetNumberOfConfigurations (dpriv->device, &nConfig);
787 if (kresult != kIOReturnSuccess) {
788 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "GetNumberOfConfigurations: %s", darwin_error_str(kresult));
789 return darwin_to_libusb(kresult);
793 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "GetNumberOfConfigurations: no configurations");
794 return LIBUSB_ERROR_OTHER;
797 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "device has %d configuration%s. using the first",
798 (int)nConfig, (nConfig > 1 ? "s" : "") );
800 /* Always use the first configuration */
801 kresult = (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, 0, &configDesc);
802 if (kresult != kIOReturnSuccess) {
803 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "GetConfigurationDescriptorPtr: %s",
804 darwin_error_str(kresult));
808 new_config = configDesc->bConfigurationValue;
810 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "new configuration value is %d", new_config);
812 /* set the configuration */
813 kresult = darwin_set_configuration (dev_handle, new_config);
814 if (kresult != LIBUSB_SUCCESS) {
815 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "could not set configuration");
819 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
821 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "darwin_get_interface: %s", darwin_error_str(kresult));
822 return darwin_to_libusb (kresult);
827 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "interface not found");
828 return LIBUSB_ERROR_NOT_FOUND;
831 /* get an interface to the device's interface */
832 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
833 kIOCFPlugInInterfaceID, &plugInInterface, &score);
834 kresult = IOObjectRelease(usbInterface);
835 if (kresult || !plugInInterface)
836 return darwin_to_libusb (kresult);
838 /* Do the actual claim */
839 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
840 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
841 (LPVOID)&cInterface->interface);
842 if (kresult || !cInterface->interface) {
843 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "QueryInterface: %s", darwin_error_str(kresult));
844 return darwin_to_libusb (kresult);
847 /* We no longer need the intermediate plug-in */
848 (*plugInInterface)->Release(plugInInterface);
850 /* claim the interface */
851 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
853 _usbi_log(HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "USBInterfaceOpen: %s", darwin_error_str(kresult));
854 return darwin_to_libusb (kresult);
857 /* update list of endpoints */
858 kresult = get_endpoints (dev_handle, iface);
860 /* this should not happen */
861 darwin_release_interface (dev_handle, iface);
862 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "could not build endpoint table");
866 /* create async event source */
867 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
869 /* add the cfSource to the aync run loop */
870 CFRetain (libusb_darwin_acfl);
871 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
873 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "interface opened");
878 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
879 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
882 /* current interface */
883 struct __darwin_interface *cInterface = &priv->interfaces[iface];
885 /* Check to see if an interface is open */
886 if (!cInterface->interface)
887 return LIBUSB_SUCCESS;
889 /* clean up endpoint data */
890 cInterface->num_endpoints = 0;
892 /* delete the interface's async event source */
893 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
894 CFRelease (cInterface->cfSource);
896 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
898 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "USBInterfaceClose: %s", darwin_error_str(kresult));
900 kresult = (*(cInterface->interface))->Release(cInterface->interface);
901 if (kresult != kIOReturnSuccess)
902 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "Release: %s", darwin_error_str(kresult));
904 cInterface->interface = IO_OBJECT_NULL;
906 return darwin_to_libusb (kresult);
909 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
910 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
913 /* current interface */
914 struct __darwin_interface *cInterface = &priv->interfaces[iface];
916 if (!cInterface->interface)
917 return LIBUSB_ERROR_NO_DEVICE;
919 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
920 if (kresult != kIOReturnSuccess)
921 darwin_reset_device (dev_handle);
923 return darwin_to_libusb (kresult);
926 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
927 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
929 /* current interface */
930 struct __darwin_interface *cInterface;
931 uint8_t pipeRef, iface;
934 /* determine the interface/endpoint to use */
935 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
936 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
938 return LIBUSB_ERROR_NOT_FOUND;
941 cInterface = &priv->interfaces[iface];
943 #if (InterfaceVersion < 190)
944 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
946 /* newer versions of darwin support clearing additional bits on the device's endpoint */
947 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
950 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "ClearPipeStall: %s", darwin_error_str (kresult));
952 return darwin_to_libusb (kresult);
955 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
956 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
959 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
961 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "ResetDevice: %s", darwin_error_str (kresult));
963 return darwin_to_libusb (kresult);
966 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
967 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
968 io_service_t usbInterface;
972 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
974 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "darwin_get_interface: %s", darwin_error_str(kresult));
976 return darwin_to_libusb (kresult);
979 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
980 IOObjectRelease (usbInterface);
992 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
993 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
994 return LIBUSB_ERROR_NOT_SUPPORTED;
997 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
998 return LIBUSB_ERROR_NOT_SUPPORTED;
1001 static void darwin_destroy_device(struct libusb_device *dev) {
1004 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1005 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1006 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1009 uint8_t is_read; /* 0 = we're reading, 1 = we're writing */
1010 uint8_t transferType;
1011 /* None of the values below are used in libusb for bulk transfers */
1012 uint8_t direction, number, interval, pipeRef, iface;
1013 uint16_t maxPacketSize;
1015 struct __darwin_interface *cInterface;
1017 /* are we reading or writing? */
1018 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1020 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1021 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
1023 return LIBUSB_ERROR_NOT_FOUND;
1026 cInterface = &priv->interfaces[iface];
1028 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1029 &transferType, &maxPacketSize, &interval);
1031 /* submit the request */
1032 /* timeouts are unavailable on interrupt endpoints */
1033 if (transferType == kUSBInterrupt) {
1035 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1036 transfer->length, darwin_async_io_callback, itransfer);
1038 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1039 transfer->length, darwin_async_io_callback, itransfer);
1042 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1043 transfer->length, transfer->timeout, transfer->timeout,
1044 darwin_async_io_callback, (void *)itransfer);
1046 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1047 transfer->length, transfer->timeout, transfer->timeout,
1048 darwin_async_io_callback, (void *)itransfer);
1052 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "bulk transfer failed (dir = %s): %s", is_read ? "In" : "Out",
1053 darwin_error_str(ret));
1055 return darwin_to_libusb (ret);
1058 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1059 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1060 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1061 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1064 uint8_t is_read; /* 0 = we're writing, 1 = we're reading */
1065 uint8_t pipeRef, iface;
1067 AbsoluteTime atTime;
1070 struct __darwin_interface *cInterface;
1072 /* are we reading or writing? */
1073 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1075 /* construct an array of IOUSBIsocFrames */
1076 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1077 if (!tpriv->isoc_framelist)
1078 return LIBUSB_ERROR_NO_MEM;
1080 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1081 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1082 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1084 /* determine the interface/endpoint to use */
1085 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1086 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
1088 return LIBUSB_ERROR_NOT_FOUND;
1091 cInterface = &priv->interfaces[iface];
1093 /* Last but not least we need the bus frame number */
1094 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1096 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "failed to get bus frame number: %d", kresult);
1097 free(tpriv->isoc_framelist);
1098 tpriv->isoc_framelist = NULL;
1100 return darwin_to_libusb (kresult);
1103 /* schedule for a frame a little in the future */
1106 /* submit the request */
1108 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1109 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1112 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1113 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1116 if (kresult != kIOReturnSuccess) {
1117 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "isochronous transfer failed (dir: %s): %s", is_read ? "In" : "Out",
1118 darwin_error_str(kresult));
1119 free (tpriv->isoc_framelist);
1120 tpriv->isoc_framelist = NULL;
1123 return darwin_to_libusb (kresult);
1126 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1127 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1128 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1129 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1130 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1134 bzero(&tpriv->req, sizeof(tpriv->req));
1136 /* IOUSBDeviceInterface expects the request in cpu endianess */
1137 tpriv->req.bmRequestType = setup->bmRequestType;
1138 tpriv->req.bRequest = setup->bRequest;
1139 /* these values should already be in bus order */
1140 tpriv->req.wValue = setup->wValue;
1141 tpriv->req.wIndex = setup->wIndex;
1142 tpriv->req.wLength = setup->wLength;
1143 /* data is stored after the libusb control block */
1144 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1145 tpriv->req.completionTimeout = transfer->timeout;
1146 tpriv->req.noDataTimeout = transfer->timeout;
1148 /* all transfers in libusb-1.0 are async */
1149 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1151 if (kresult != kIOReturnSuccess)
1152 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "control request failed: %s", darwin_error_str(kresult));
1154 return darwin_to_libusb (kresult);
1157 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1158 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1160 switch (transfer->type) {
1161 case LIBUSB_TRANSFER_TYPE_CONTROL:
1162 return submit_control_transfer(itransfer);
1163 case LIBUSB_TRANSFER_TYPE_BULK:
1164 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1165 return submit_bulk_transfer(itransfer);
1166 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1167 return submit_iso_transfer(itransfer);
1169 _usbi_log (TRANSFER_CTX(transfer), LOG_LEVEL_ERROR, "unknown endpoint type %d", transfer->type);
1170 return LIBUSB_ERROR_INVALID_PARAM;
1174 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1175 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1176 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1179 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "WARNING: aborting all transactions control pipe");
1181 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1183 return darwin_to_libusb (kresult);
1186 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1187 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1188 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1189 struct __darwin_interface *cInterface;
1190 uint8_t pipeRef, iface;
1193 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1194 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
1196 return LIBUSB_ERROR_NOT_FOUND;
1199 cInterface = &priv->interfaces[iface];
1201 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "WARNING: aborting all transactions on interface %d pipe %d", iface, pipeRef);
1203 /* abort transactions */
1204 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1206 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "calling clear pipe stall to clear the data toggle bit");
1208 /* clear the data toggle bit */
1209 #if (InterfaceVersion < 190)
1210 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1212 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1213 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1216 return darwin_to_libusb (kresult);
1219 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1220 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1222 switch (transfer->type) {
1223 case LIBUSB_TRANSFER_TYPE_CONTROL:
1224 return cancel_control_transfer(itransfer);
1225 case LIBUSB_TRANSFER_TYPE_BULK:
1226 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1227 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1228 return darwin_abort_transfers (itransfer);
1230 _usbi_log (TRANSFER_CTX(transfer), LOG_LEVEL_ERROR, "unknown endpoint type %d", transfer->type);
1231 return LIBUSB_ERROR_INVALID_PARAM;
1235 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1236 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1237 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1239 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1240 free (tpriv->isoc_framelist);
1241 tpriv->isoc_framelist = NULL;
1245 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1246 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1247 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1248 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1251 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "an async io operation has completed");
1253 /* send a completion message to the device's file descriptor */
1254 message = MESSAGE_ASYNC_IO_COMPLETE;
1255 write (priv->fds[1], &message, sizeof (message));
1256 write (priv->fds[1], &itransfer, sizeof (itransfer));
1257 write (priv->fds[1], &result, sizeof (IOReturn));
1258 write (priv->fds[1], &arg0, sizeof (UInt32));
1261 static void darwin_bulk_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1262 enum libusb_transfer_status status;
1264 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "handling bulk completion with status %d", result);
1267 case kIOReturnSuccess:
1268 status = LIBUSB_TRANSFER_COMPLETED;
1269 itransfer->transferred += io_size;
1271 case kIOReturnAborted:
1272 usbi_handle_transfer_cancellation(itransfer);
1274 case kIOUSBPipeStalled:
1275 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_WARNING, "unsupported control request");
1276 status = LIBUSB_TRANSFER_STALL;
1280 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_ERROR, "control error = %s", darwin_error_str (result));
1281 status = LIBUSB_TRANSFER_ERROR;
1284 usbi_handle_transfer_completion(itransfer, status);
1287 static void darwin_isoc_callback (struct usbi_transfer *itransfer, kern_return_t result) {
1288 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1289 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1292 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "handling isoc completion with status %d", result);
1294 if (result == kIOReturnSuccess && tpriv->isoc_framelist) {
1295 /* copy isochronous results back */
1297 for (i = 0; i < transfer->num_iso_packets ; i++) {
1298 struct libusb_iso_packet_descriptor *lib_desc = transfer->iso_packet_desc;
1299 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1300 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1305 case kIOReturnSuccess:
1306 status = LIBUSB_TRANSFER_COMPLETED;
1308 case kIOReturnAborted:
1309 usbi_handle_transfer_cancellation(itransfer);
1311 case kIOUSBPipeStalled:
1312 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_WARNING, "unsupported control request");
1313 status = LIBUSB_TRANSFER_STALL;
1317 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_ERROR, "control error = %s", darwin_error_str (result));
1318 status = LIBUSB_TRANSFER_ERROR;
1321 usbi_handle_transfer_completion(itransfer, status);
1324 static void darwin_control_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1327 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "handling control completion with status %d", result);
1330 case kIOReturnSuccess:
1331 status = LIBUSB_TRANSFER_COMPLETED;
1332 itransfer->transferred += io_size;
1334 case kIOReturnAborted:
1335 usbi_handle_transfer_cancellation(itransfer);
1337 case kIOUSBPipeStalled:
1338 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_WARNING, "unsupported control request");
1339 status = LIBUSB_TRANSFER_STALL;
1343 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_ERROR, "control error = %s", darwin_error_str (result));
1344 status = LIBUSB_TRANSFER_ERROR;
1347 usbi_handle_transfer_completion(itransfer, status);
1350 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1351 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1353 switch (transfer->type) {
1354 case LIBUSB_TRANSFER_TYPE_CONTROL:
1355 darwin_control_callback (itransfer, result, io_size);
1357 case LIBUSB_TRANSFER_TYPE_BULK:
1358 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1359 darwin_bulk_callback (itransfer, result, io_size);
1361 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1362 darwin_isoc_callback (itransfer, result);
1365 _usbi_log (TRANSFER_CTX(transfer), LOG_LEVEL_ERROR, "unknown endpoint type %d", transfer->type);
1369 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, nfds_t nfds, int num_ready) {
1370 struct usbi_transfer *itransfer;
1376 pthread_mutex_lock(&ctx->open_devs_lock);
1377 for (i = 0; i < nfds && num_ready > 0; i++) {
1378 struct pollfd *pollfd = &fds[i];
1379 struct libusb_device_handle *handle;
1380 struct darwin_device_handle_priv *hpriv = NULL;
1382 _usbi_log (ctx, LOG_LEVEL_INFO, "checking fd %i with revents = %x", fds[i], pollfd->revents);
1384 if (!pollfd->revents)
1388 list_for_each_entry(handle, &ctx->open_devs, list) {
1389 hpriv = (struct darwin_device_handle_priv *)handle->os_priv;
1390 if (hpriv->fds[0] == pollfd->fd)
1394 if (pollfd->revents & POLLERR) {
1395 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
1396 usbi_handle_disconnect(handle);
1398 /* done with this device */
1402 ret = read (hpriv->fds[0], &message, sizeof (message));
1403 if (ret < sizeof (message))
1407 case MESSAGE_DEVICE_GONE:
1408 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
1409 usbi_handle_disconnect(handle);
1411 /* done with this device */
1413 case MESSAGE_ASYNC_IO_COMPLETE:
1414 read (hpriv->fds[0], &itransfer, sizeof (itransfer));
1415 read (hpriv->fds[0], &kresult, sizeof (IOReturn));
1416 read (hpriv->fds[0], &io_size, sizeof (UInt32));
1418 darwin_handle_callback (itransfer, kresult, io_size);
1421 _usbi_log (ctx, LOG_LEVEL_ERROR, "unknown message received from device pipe");
1425 pthread_mutex_unlock(&ctx->open_devs_lock);
1430 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1431 mach_timespec_t sys_time;
1432 clock_serv_t clock_ref;
1435 case USBI_CLOCK_REALTIME:
1436 /* CLOCK_REALTIME represents time since the epoch */
1437 host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &clock_ref);
1439 case USBI_CLOCK_MONOTONIC:
1440 /* use system boot time as reference for the monotonic clock */
1441 host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &clock_ref);
1444 return LIBUSB_ERROR_INVALID_PARAM;
1447 clock_get_time (clock_ref, &sys_time);
1449 tp->tv_sec = sys_time.tv_sec;
1450 tp->tv_nsec = sys_time.tv_nsec;
1455 const struct usbi_os_backend darwin_backend = {
1457 .init = darwin_init,
1458 .exit = darwin_exit,
1459 .get_device_list = darwin_get_device_list,
1460 .get_device_descriptor = darwin_get_device_descriptor,
1461 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1462 .get_config_descriptor = darwin_get_config_descriptor,
1464 .open = darwin_open,
1465 .close = darwin_close,
1466 .get_configuration = darwin_get_configuration,
1467 .set_configuration = darwin_set_configuration,
1468 .claim_interface = darwin_claim_interface,
1469 .release_interface = darwin_release_interface,
1471 .set_interface_altsetting = darwin_set_interface_altsetting,
1472 .clear_halt = darwin_clear_halt,
1473 .reset_device = darwin_reset_device,
1475 .kernel_driver_active = darwin_kernel_driver_active,
1476 .detach_kernel_driver = darwin_detach_kernel_driver,
1477 .attach_kernel_driver = darwin_attach_kernel_driver,
1479 .destroy_device = darwin_destroy_device,
1481 .submit_transfer = darwin_submit_transfer,
1482 .cancel_transfer = darwin_cancel_transfer,
1483 .clear_transfer_priv = darwin_clear_transfer_priv,
1485 .handle_events = op_handle_events,
1487 .clock_gettime = darwin_clock_gettime,
1489 .device_priv_size = sizeof(struct darwin_device_priv),
1490 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1491 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1492 .add_iso_packet_size = 0,