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;
364 kresult = (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
365 if (kresult != kIOReturnSuccess)
366 return darwin_to_libusb (kresult);
368 /* sanity check. is the buffer larger than the returned descriptor */
369 if (len > sizeof (*desc))
370 len = sizeof (*desc);
372 memmove (buffer, desc, len);
374 /* GetConfigurationDescriptorPtr returns the descriptor is USB bus order */
380 static int process_new_device (struct libusb_context *ctx, usb_device_t **device, UInt32 locationID, struct discovered_devs **_discdevs) {
381 struct darwin_device_priv *priv;
382 struct libusb_device *dev;
383 struct discovered_devs *discdevs;
384 UInt16 address, idVendor, idProduct;
385 UInt8 bDeviceClass, bDeviceSubClass;
389 dev = usbi_get_device_by_session_id(ctx, locationID);
391 _usbi_log (ctx, LOG_LEVEL_INFO, "allocating new device for location 0x%08x", locationID);
392 dev = usbi_alloc_device(ctx, locationID);
394 return LIBUSB_ERROR_NO_MEM;
396 priv = (struct darwin_device_priv *)dev->os_priv;
398 /* Set up request for device descriptor */
399 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
400 req.bRequest = kUSBRqGetDescriptor;
401 req.wValue = kUSBDeviceDesc << 8;
403 req.wLength = sizeof(IOUSBDeviceDescriptor);
404 req.pData = &(priv->dev_descriptor);
406 (*(device))->GetDeviceAddress (device, (USBDeviceAddress *)&address);
407 (*(device))->GetDeviceProduct (device, &idProduct);
408 (*(device))->GetDeviceVendor (device, &idVendor);
409 (*(device))->GetDeviceClass (device, &bDeviceClass);
410 (*(device))->GetDeviceSubClass (device, &bDeviceSubClass);
412 /**** retrieve device descriptors ****/
413 /* device must be open for DeviceRequest */
414 (*device)->USBDeviceOpen(device);
416 ret = (*(device))->DeviceRequest (device, &req);
417 if (ret != kIOReturnSuccess) {
418 int try_unsuspend = 1;
421 /* device may be suspended. unsuspend it and try again */
422 #if DeviceVersion >= 320
423 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
424 (void)(*device)->GetUSBDeviceInformation (device, &info);
426 try_unsuspend = info & (1 << kUSBInformationDeviceIsSuspendedBit);
430 /* resume the device */
431 (void)(*device)->USBDeviceSuspend (device, 0);
433 ret = (*(device))->DeviceRequest (device, &req);
435 /* resuspend the device */
436 (void)(*device)->USBDeviceSuspend (device, 1);
440 (*device)->USBDeviceClose (device);
442 if (ret != kIOReturnSuccess) {
443 _usbi_log (ctx, LOG_LEVEL_WARNING, "could not retrieve device descriptor: %s. skipping device", darwin_error_str (ret));
444 libusb_unref_device(dev);
447 /**** end: retrieve device descriptors ****/
449 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
450 if (libusb_le16_to_cpu (priv->dev_descriptor.idProduct) != idProduct) {
451 /* not a valid device */
452 _usbi_log (ctx, LOG_LEVEL_WARNING, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
453 idProduct, libusb_le16_to_cpu (priv->dev_descriptor.idProduct));
454 libusb_unref_device(dev);
458 dev->bus_number = locationID >> 24;
459 dev->device_address = address;
461 /* save our location, we'll need this later */
462 priv->location = locationID;
463 snprintf(priv->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", address, idVendor, idProduct, bDeviceClass, bDeviceSubClass);
465 ret = usbi_sanitize_device(dev);
468 libusb_unref_device(dev);
472 priv = (struct darwin_device_priv *)dev->os_priv;
474 _usbi_log (ctx, LOG_LEVEL_INFO, "using existing device for location 0x%08x", locationID);
477 /* append the device to the list of discovered devices */
478 discdevs = discovered_devs_append(*_discdevs, dev);
480 return LIBUSB_ERROR_NO_MEM;
482 *_discdevs = discdevs;
484 _usbi_log (ctx, LOG_LEVEL_INFO, "found device with address %d at %s", dev->device_address, priv->sys_path);
489 static int darwin_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs) {
490 io_iterator_t deviceIterator;
491 usb_device_t **device;
492 kern_return_t kresult;
495 if (!libusb_darwin_mp)
496 return LIBUSB_ERROR_INVALID_PARAM;
498 kresult = usb_setup_device_iterator (&deviceIterator);
499 if (kresult != kIOReturnSuccess)
500 return darwin_to_libusb (kresult);
502 while ((device = usb_get_next_device (deviceIterator, &location)) != NULL) {
503 (void) process_new_device (ctx, device, location, _discdevs);
505 (*(device))->Release(device);
508 IOObjectRelease(deviceIterator);
513 static int darwin_open (struct libusb_device_handle *dev_handle) {
514 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
515 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
516 usb_device_t **darwin_device;
519 kresult = darwin_get_device (dpriv->location, &darwin_device);
521 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "could not find device: %s", darwin_error_str (kresult));
522 return darwin_to_libusb (kresult);
525 dpriv->device = darwin_device;
527 /* try to open the device */
528 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
530 if (kresult != kIOReturnSuccess) {
531 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "USBDeviceOpen: %s", darwin_error_str(kresult));
534 case kIOReturnExclusiveAccess:
535 /* it is possible to perform some actions on a device that is not open so do not return an error */
540 (*(dpriv->device))->Release (dpriv->device);
541 dpriv->device = NULL;
542 return darwin_to_libusb (kresult);
547 /* create async event source */
548 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
550 CFRetain (libusb_darwin_acfl);
552 /* add the cfSource to the aync run loop */
553 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
556 /* create a file descriptor for notifications */
559 /* set the pipe to be non-blocking */
560 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
562 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
564 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "device open for access");
569 static void darwin_close (struct libusb_device_handle *dev_handle) {
570 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
571 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
575 /* make sure all interfaces are released */
576 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
577 if (dev_handle->claimed_interfaces & (1 << i))
578 libusb_release_interface (dev_handle, i);
581 /* delete the device's async event source */
582 if (priv->cfSource) {
583 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
584 CFRelease (priv->cfSource);
587 /* close the device */
588 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
590 /* Log the fact that we had a problem closing the file, however failing a
591 * close isn't really an error, so return success anyway */
592 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "USBDeviceClose: %s", darwin_error_str(kresult));
596 kresult = (*(dpriv->device))->Release(dpriv->device);
598 /* Log the fact that we had a problem closing the file, however failing a
599 * close isn't really an error, so return success anyway */
600 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "Release: %s", darwin_error_str(kresult));
603 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
604 close (priv->fds[1]);
605 close (priv->fds[0]);
608 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
609 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
613 kresult = (*(dpriv->device))->GetConfiguration (dpriv->device, &configNum);
614 if (kresult != kIOReturnSuccess)
615 return darwin_to_libusb (kresult);
617 *config = (int) configNum;
622 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
623 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
627 /* Setting configuration will invalidate the interface, so we need
628 to reclaim it. First, dispose of existing interfaces, if any. */
629 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
630 if (dev_handle->claimed_interfaces & (1 << i))
631 darwin_release_interface (dev_handle, i);
633 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
634 if (kresult != kIOReturnSuccess)
635 return darwin_to_libusb (kresult);
637 /* Reclaim any interfaces. */
638 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
639 if (dev_handle->claimed_interfaces & (1 << i))
640 darwin_claim_interface (dev_handle, i);
645 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
646 IOUSBFindInterfaceRequest request;
647 uint8_t current_interface;
648 kern_return_t kresult;
649 io_iterator_t interface_iterator;
651 *usbInterfacep = IO_OBJECT_NULL;
653 /* Setup the Interface Request */
654 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
655 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
656 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
657 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
659 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
663 for ( current_interface = 0 ; current_interface <= ifc ; current_interface++ )
664 *usbInterfacep = IOIteratorNext(interface_iterator);
666 /* done with the interface iterator */
667 IOObjectRelease(interface_iterator);
672 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
673 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
675 /* current interface */
676 struct __darwin_interface *cInterface = &priv->interfaces[iface];
678 kern_return_t kresult;
680 u_int8_t numep, direction, number;
681 u_int8_t dont_care1, dont_care3;
682 u_int16_t dont_care2;
685 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "building table of endpoints.");
687 /* retrieve the total number of endpoints on this interface */
688 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
690 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
691 return darwin_to_libusb (kresult);
694 /* iterate through pipe references */
695 for (i = 1 ; i <= numep ; i++) {
696 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
697 &dont_care2, &dont_care3);
699 if (kresult != kIOReturnSuccess) {
700 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
702 return darwin_to_libusb (kresult);
705 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
707 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
710 cInterface->num_endpoints = numep;
715 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
716 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
717 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
718 io_service_t usbInterface = IO_OBJECT_NULL;
720 IOCFPlugInInterface **plugInInterface = NULL;
724 /* current interface */
725 struct __darwin_interface *cInterface = &priv->interfaces[iface];
727 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
728 if (kresult != kIOReturnSuccess)
729 return darwin_to_libusb (kresult);
731 /* make sure we have an interface */
733 u_int8_t nConfig; /* Index of configuration to use */
734 IOUSBConfigurationDescriptorPtr configDesc; /* to describe which configuration to select */
735 /* Only a composite class device with no vendor-specific driver will
736 be configured. Otherwise, we need to do it ourselves, or there
737 will be no interfaces for the device. */
739 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "no interface found; selecting configuration" );
741 kresult = (*(dpriv->device))->GetNumberOfConfigurations (dpriv->device, &nConfig);
742 if (kresult != kIOReturnSuccess) {
743 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "GetNumberOfConfigurations: %s", darwin_error_str(kresult));
744 return darwin_to_libusb(kresult);
748 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "GetNumberOfConfigurations: no configurations");
749 return LIBUSB_ERROR_OTHER;
752 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "device has %d configuration%s. using the first",
753 (int)nConfig, (nConfig > 1 ? "s" : "") );
755 /* Always use the first configuration */
756 kresult = (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, 0, &configDesc);
757 if (kresult != kIOReturnSuccess) {
758 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "GetConfigurationDescriptorPtr: %s",
759 darwin_error_str(kresult));
763 new_config = configDesc->bConfigurationValue;
765 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "new configuration value is %d", new_config);
767 /* set the configuration */
768 kresult = darwin_set_configuration (dev_handle, new_config);
769 if (kresult != LIBUSB_SUCCESS) {
770 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "could not set configuration");
774 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
776 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "darwin_get_interface: %s", darwin_error_str(kresult));
777 return darwin_to_libusb (kresult);
782 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "interface not found");
783 return LIBUSB_ERROR_NOT_FOUND;
786 /* get an interface to the device's interface */
787 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
788 kIOCFPlugInInterfaceID, &plugInInterface, &score);
789 kresult = IOObjectRelease(usbInterface);
790 if (kresult || !plugInInterface)
791 return darwin_to_libusb (kresult);
793 /* Do the actual claim */
794 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
795 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
796 (LPVOID)&cInterface->interface);
797 if (kresult || !cInterface->interface) {
798 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "QueryInterface: %s", darwin_error_str(kresult));
799 return darwin_to_libusb (kresult);
802 /* We no longer need the intermediate plug-in */
803 (*plugInInterface)->Release(plugInInterface);
805 /* claim the interface */
806 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
808 _usbi_log(HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "USBInterfaceOpen: %s", darwin_error_str(kresult));
809 return darwin_to_libusb (kresult);
812 /* update list of endpoints */
813 kresult = get_endpoints (dev_handle, iface);
815 /* this should not happen */
816 darwin_release_interface (dev_handle, iface);
817 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "could not build endpoint table");
821 /* create async event source */
822 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
824 /* add the cfSource to the aync run loop */
825 CFRetain (libusb_darwin_acfl);
826 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
828 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "interface opened");
833 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
834 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
837 /* current interface */
838 struct __darwin_interface *cInterface = &priv->interfaces[iface];
840 /* Check to see if an interface is open */
841 if (!cInterface->interface)
842 return LIBUSB_SUCCESS;
844 /* clean up endpoint data */
845 cInterface->num_endpoints = 0;
847 /* delete the interface's async event source */
848 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
849 CFRelease (cInterface->cfSource);
851 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
853 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "USBInterfaceClose: %s", darwin_error_str(kresult));
855 kresult = (*(cInterface->interface))->Release(cInterface->interface);
856 if (kresult != kIOReturnSuccess)
857 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "Release: %s", darwin_error_str(kresult));
859 cInterface->interface = IO_OBJECT_NULL;
861 return darwin_to_libusb (kresult);
864 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
865 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
868 /* current interface */
869 struct __darwin_interface *cInterface = &priv->interfaces[iface];
871 if (!cInterface->interface)
872 return LIBUSB_ERROR_NO_DEVICE;
874 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
875 if (kresult != kIOReturnSuccess)
876 darwin_reset_device (dev_handle);
878 return darwin_to_libusb (kresult);
881 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
882 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
884 /* current interface */
885 struct __darwin_interface *cInterface;
886 uint8_t pipeRef, iface;
889 /* determine the interface/endpoint to use */
890 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
891 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
893 return LIBUSB_ERROR_NOT_FOUND;
896 cInterface = &priv->interfaces[iface];
898 #if (InterfaceVersion < 190)
899 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
901 /* newer versions of darwin support clearing additional bits on the device's endpoint */
902 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
905 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "ClearPipeStall: %s", darwin_error_str (kresult));
907 return darwin_to_libusb (kresult);
910 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
911 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
914 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
916 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "ResetDevice: %s", darwin_error_str (kresult));
918 return darwin_to_libusb (kresult);
921 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
922 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
923 io_service_t usbInterface;
927 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
929 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "darwin_get_interface: %s", darwin_error_str(kresult));
931 return darwin_to_libusb (kresult);
934 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
935 IOObjectRelease (usbInterface);
947 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
948 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
949 return LIBUSB_ERROR_NOT_SUPPORTED;
952 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
953 return LIBUSB_ERROR_NOT_SUPPORTED;
956 static void darwin_destroy_device(struct libusb_device *dev) {
959 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
960 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
961 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
964 uint8_t is_read; /* 0 = we're reading, 1 = we're writing */
965 uint8_t transferType;
966 /* None of the values below are used in libusb for bulk transfers */
967 uint8_t direction, number, interval, pipeRef, iface;
968 uint16_t maxPacketSize;
970 struct __darwin_interface *cInterface;
972 /* are we reading or writing? */
973 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
975 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
976 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
978 return LIBUSB_ERROR_NOT_FOUND;
981 cInterface = &priv->interfaces[iface];
983 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
984 &transferType, &maxPacketSize, &interval);
986 /* submit the request */
987 /* timeouts are unavailable on interrupt endpoints */
988 if (transferType == kUSBInterrupt) {
990 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
991 transfer->length, darwin_async_io_callback, itransfer);
993 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
994 transfer->length, darwin_async_io_callback, itransfer);
997 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
998 transfer->length, transfer->timeout, transfer->timeout,
999 darwin_async_io_callback, (void *)itransfer);
1001 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1002 transfer->length, transfer->timeout, transfer->timeout,
1003 darwin_async_io_callback, (void *)itransfer);
1007 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "bulk transfer failed (dir = %s): %s", is_read ? "In" : "Out",
1008 darwin_error_str(ret));
1010 return darwin_to_libusb (ret);
1013 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1014 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1015 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1016 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1019 uint8_t is_read; /* 0 = we're writing, 1 = we're reading */
1020 uint8_t pipeRef, iface;
1022 AbsoluteTime atTime;
1025 struct __darwin_interface *cInterface;
1027 /* are we reading or writing? */
1028 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1030 /* construct an array of IOUSBIsocFrames */
1031 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1032 if (!tpriv->isoc_framelist)
1033 return LIBUSB_ERROR_NO_MEM;
1035 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1036 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1037 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1039 /* determine the interface/endpoint to use */
1040 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1041 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
1043 return LIBUSB_ERROR_NOT_FOUND;
1046 cInterface = &priv->interfaces[iface];
1048 /* Last but not least we need the bus frame number */
1049 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1051 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "failed to get bus frame number: %d", kresult);
1052 free(tpriv->isoc_framelist);
1053 tpriv->isoc_framelist = NULL;
1055 return darwin_to_libusb (kresult);
1058 /* schedule for a frame a little in the future */
1061 /* submit the request */
1063 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1064 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1067 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1068 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1071 if (kresult != kIOReturnSuccess) {
1072 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "isochronous transfer failed (dir: %s): %s", is_read ? "In" : "Out",
1073 darwin_error_str(kresult));
1074 free (tpriv->isoc_framelist);
1075 tpriv->isoc_framelist = NULL;
1078 return darwin_to_libusb (kresult);
1081 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1082 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1083 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1084 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1085 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1089 bzero(&tpriv->req, sizeof(tpriv->req));
1091 /* IOUSBDeviceInterface expects the request in cpu endianess */
1092 tpriv->req.bmRequestType = setup->bmRequestType;
1093 tpriv->req.bRequest = setup->bRequest;
1094 /* these values should already be in bus order */
1095 tpriv->req.wValue = setup->wValue;
1096 tpriv->req.wIndex = setup->wIndex;
1097 tpriv->req.wLength = setup->wLength;
1098 /* data is stored after the libusb control block */
1099 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1100 tpriv->req.completionTimeout = transfer->timeout;
1101 tpriv->req.noDataTimeout = transfer->timeout;
1103 /* all transfers in libusb-1.0 are async */
1104 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1106 if (kresult != kIOReturnSuccess)
1107 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "control request failed: %s", darwin_error_str(kresult));
1109 return darwin_to_libusb (kresult);
1112 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1113 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1115 switch (transfer->type) {
1116 case LIBUSB_TRANSFER_TYPE_CONTROL:
1117 return submit_control_transfer(itransfer);
1118 case LIBUSB_TRANSFER_TYPE_BULK:
1119 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1120 return submit_bulk_transfer(itransfer);
1121 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1122 return submit_iso_transfer(itransfer);
1124 _usbi_log (TRANSFER_CTX(transfer), LOG_LEVEL_ERROR, "unknown endpoint type %d", transfer->type);
1125 return LIBUSB_ERROR_INVALID_PARAM;
1129 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1130 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1131 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1134 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "WARNING: aborting all transactions control pipe");
1136 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1138 return darwin_to_libusb (kresult);
1141 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1142 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1143 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1144 struct __darwin_interface *cInterface;
1145 uint8_t pipeRef, iface;
1148 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1149 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
1151 return LIBUSB_ERROR_NOT_FOUND;
1154 cInterface = &priv->interfaces[iface];
1156 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "WARNING: aborting all transactions on interface %d pipe %d", iface, pipeRef);
1158 /* abort transactions */
1159 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1161 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "calling clear pipe stall to clear the data toggle bit");
1163 /* clear the data toggle bit */
1164 #if (InterfaceVersion < 190)
1165 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1167 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1168 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1171 return darwin_to_libusb (kresult);
1174 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1175 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1177 switch (transfer->type) {
1178 case LIBUSB_TRANSFER_TYPE_CONTROL:
1179 return cancel_control_transfer(itransfer);
1180 case LIBUSB_TRANSFER_TYPE_BULK:
1181 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1182 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1183 return darwin_abort_transfers (itransfer);
1185 _usbi_log (TRANSFER_CTX(transfer), LOG_LEVEL_ERROR, "unknown endpoint type %d", transfer->type);
1186 return LIBUSB_ERROR_INVALID_PARAM;
1190 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1191 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1192 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1194 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1195 free (tpriv->isoc_framelist);
1196 tpriv->isoc_framelist = NULL;
1200 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1201 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1202 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1203 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1206 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "an async io operation has completed");
1208 /* send a completion message to the device's file descriptor */
1209 message = MESSAGE_ASYNC_IO_COMPLETE;
1210 write (priv->fds[1], &message, sizeof (message));
1211 write (priv->fds[1], &itransfer, sizeof (itransfer));
1212 write (priv->fds[1], &result, sizeof (IOReturn));
1213 write (priv->fds[1], &arg0, sizeof (UInt32));
1216 static void darwin_bulk_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1217 enum libusb_transfer_status status;
1219 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "handling bulk completion with status %d", result);
1222 case kIOReturnSuccess:
1223 status = LIBUSB_TRANSFER_COMPLETED;
1224 itransfer->transferred += io_size;
1226 case kIOReturnAborted:
1227 usbi_handle_transfer_cancellation(itransfer);
1229 case kIOUSBPipeStalled:
1230 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_WARNING, "unsupported control request");
1231 status = LIBUSB_TRANSFER_STALL;
1235 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_ERROR, "control error = %s", darwin_error_str (result));
1236 status = LIBUSB_TRANSFER_ERROR;
1239 usbi_handle_transfer_completion(itransfer, status);
1242 static void darwin_isoc_callback (struct usbi_transfer *itransfer, kern_return_t result) {
1243 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1244 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1247 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "handling isoc completion with status %d", result);
1249 if (result == kIOReturnSuccess && tpriv->isoc_framelist) {
1250 /* copy isochronous results back */
1252 for (i = 0; i < transfer->num_iso_packets ; i++) {
1253 struct libusb_iso_packet_descriptor *lib_desc = transfer->iso_packet_desc;
1254 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1255 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1260 case kIOReturnSuccess:
1261 status = LIBUSB_TRANSFER_COMPLETED;
1263 case kIOReturnAborted:
1264 usbi_handle_transfer_cancellation(itransfer);
1266 case kIOUSBPipeStalled:
1267 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_WARNING, "unsupported control request");
1268 status = LIBUSB_TRANSFER_STALL;
1272 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_ERROR, "control error = %s", darwin_error_str (result));
1273 status = LIBUSB_TRANSFER_ERROR;
1276 usbi_handle_transfer_completion(itransfer, status);
1279 static void darwin_control_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1282 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "handling control completion with status %d", result);
1285 case kIOReturnSuccess:
1286 status = LIBUSB_TRANSFER_COMPLETED;
1287 itransfer->transferred += io_size;
1289 case kIOReturnAborted:
1290 usbi_handle_transfer_cancellation(itransfer);
1292 case kIOUSBPipeStalled:
1293 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_WARNING, "unsupported control request");
1294 status = LIBUSB_TRANSFER_STALL;
1298 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_ERROR, "control error = %s", darwin_error_str (result));
1299 status = LIBUSB_TRANSFER_ERROR;
1302 usbi_handle_transfer_completion(itransfer, status);
1305 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1306 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1308 switch (transfer->type) {
1309 case LIBUSB_TRANSFER_TYPE_CONTROL:
1310 darwin_control_callback (itransfer, result, io_size);
1312 case LIBUSB_TRANSFER_TYPE_BULK:
1313 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1314 darwin_bulk_callback (itransfer, result, io_size);
1316 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1317 darwin_isoc_callback (itransfer, result);
1320 _usbi_log (TRANSFER_CTX(transfer), LOG_LEVEL_ERROR, "unknown endpoint type %d", transfer->type);
1324 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, nfds_t nfds, int num_ready) {
1325 struct usbi_transfer *itransfer;
1331 pthread_mutex_lock(&ctx->open_devs_lock);
1332 for (i = 0; i < nfds && num_ready > 0; i++) {
1333 struct pollfd *pollfd = &fds[i];
1334 struct libusb_device_handle *handle;
1335 struct darwin_device_handle_priv *hpriv = NULL;
1337 _usbi_log (ctx, LOG_LEVEL_INFO, "checking fd %i with revents = %x", fds[i], pollfd->revents);
1339 if (!pollfd->revents)
1343 list_for_each_entry(handle, &ctx->open_devs, list) {
1344 hpriv = (struct darwin_device_handle_priv *)handle->os_priv;
1345 if (hpriv->fds[0] == pollfd->fd)
1349 if (pollfd->revents & POLLERR) {
1350 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
1351 usbi_handle_disconnect(handle);
1353 /* done with this device */
1357 ret = read (hpriv->fds[0], &message, sizeof (message));
1358 if (ret < sizeof (message))
1362 case MESSAGE_DEVICE_GONE:
1363 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
1364 usbi_handle_disconnect(handle);
1366 /* done with this device */
1368 case MESSAGE_ASYNC_IO_COMPLETE:
1369 read (hpriv->fds[0], &itransfer, sizeof (itransfer));
1370 read (hpriv->fds[0], &kresult, sizeof (IOReturn));
1371 read (hpriv->fds[0], &io_size, sizeof (UInt32));
1373 darwin_handle_callback (itransfer, kresult, io_size);
1376 _usbi_log (ctx, LOG_LEVEL_ERROR, "unknown message received from device pipe");
1380 pthread_mutex_unlock(&ctx->open_devs_lock);
1385 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1386 mach_timespec_t sys_time;
1387 clock_serv_t clock_ref;
1390 case USBI_CLOCK_REALTIME:
1391 /* CLOCK_REALTIME represents time since the epoch */
1392 host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &clock_ref);
1394 case USBI_CLOCK_MONOTONIC:
1395 /* use system boot time as reference for the monotonic clock */
1396 host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &clock_ref);
1399 return LIBUSB_ERROR_INVALID_PARAM;
1402 clock_get_time (clock_ref, &sys_time);
1404 tp->tv_sec = sys_time.tv_sec;
1405 tp->tv_nsec = sys_time.tv_nsec;
1410 const struct usbi_os_backend darwin_backend = {
1412 .init = darwin_init,
1413 .exit = darwin_exit,
1414 .get_device_list = darwin_get_device_list,
1415 .get_device_descriptor = darwin_get_device_descriptor,
1416 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1417 .get_config_descriptor = darwin_get_config_descriptor,
1419 .open = darwin_open,
1420 .close = darwin_close,
1421 .get_configuration = darwin_get_configuration,
1422 .set_configuration = darwin_set_configuration,
1423 .claim_interface = darwin_claim_interface,
1424 .release_interface = darwin_release_interface,
1426 .set_interface_altsetting = darwin_set_interface_altsetting,
1427 .clear_halt = darwin_clear_halt,
1428 .reset_device = darwin_reset_device,
1430 .kernel_driver_active = darwin_kernel_driver_active,
1431 .detach_kernel_driver = darwin_detach_kernel_driver,
1432 .attach_kernel_driver = darwin_attach_kernel_driver,
1434 .destroy_device = darwin_destroy_device,
1436 .submit_transfer = darwin_submit_transfer,
1437 .cancel_transfer = darwin_cancel_transfer,
1438 .clear_transfer_priv = darwin_clear_transfer_priv,
1440 .handle_events = op_handle_events,
1442 .clock_gettime = darwin_clock_gettime,
1444 .device_priv_size = sizeof(struct darwin_device_priv),
1445 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1446 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1447 .add_iso_packet_size = 0,