2 * darwin backend for libusb 1.0
3 * Copyright (C) 2008-2010 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 */
47 static int initCount = 0;
49 /* async event thread */
50 static pthread_t libusb_darwin_at;
52 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
53 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
54 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
55 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
56 static void darwin_bulk_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size);
57 static void darwin_isoc_callback (struct usbi_transfer *itransfer, kern_return_t result);
58 static void darwin_control_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size);
59 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
61 static const char *darwin_error_str (int result) {
63 case kIOReturnSuccess:
65 case kIOReturnNotOpen:
66 return "device not opened for exclusive access";
67 case kIOReturnNoDevice:
68 return "no connection to an IOService";
69 case kIOUSBNoAsyncPortErr:
70 return "no async port has been opened for interface";
71 case kIOReturnExclusiveAccess:
72 return "another process has device opened for exclusive access";
73 case kIOUSBPipeStalled:
74 return "pipe is stalled";
76 return "could not establish a connection to the Darwin kernel";
77 case kIOUSBTransactionTimeout:
78 return "transaction timed out";
79 case kIOReturnBadArgument:
80 return "invalid argument";
81 case kIOReturnAborted:
82 return "transaction aborted";
83 case kIOReturnNotResponding:
84 return "device not responding";
85 case kIOReturnOverrun:
86 return "data overrun";
87 case kIOReturnCannotWire:
88 return "physical memory can not be wired down";
90 return "unknown error";
94 static int darwin_to_libusb (int result) {
96 case kIOReturnSuccess:
97 return LIBUSB_SUCCESS;
98 case kIOReturnNotOpen:
99 case kIOReturnNoDevice:
100 return LIBUSB_ERROR_NO_DEVICE;
101 case kIOReturnExclusiveAccess:
102 return LIBUSB_ERROR_ACCESS;
103 case kIOUSBPipeStalled:
104 return LIBUSB_ERROR_PIPE;
105 case kIOReturnBadArgument:
106 return LIBUSB_ERROR_INVALID_PARAM;
107 case kIOUSBTransactionTimeout:
108 return LIBUSB_ERROR_TIMEOUT;
109 case kIOReturnNotResponding:
110 case kIOReturnAborted:
112 case kIOUSBNoAsyncPortErr:
114 return LIBUSB_ERROR_OTHER;
119 static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp) {
120 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
122 /* current interface */
123 struct __darwin_interface *cInterface;
127 usbi_info (HANDLE_CTX(dev_handle), "converting ep address 0x%02x to pipeRef and interface", ep);
129 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
130 cInterface = &priv->interfaces[iface];
132 if (dev_handle->claimed_interfaces & (1 << iface)) {
133 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
134 if (cInterface->endpoint_addrs[i] == ep) {
137 usbi_info (HANDLE_CTX(dev_handle), "pipe %d on interface %d matches", *pipep, *ifcp);
144 /* No pipe found with the correct endpoint address */
145 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
150 static int usb_setup_device_iterator (io_iterator_t *deviceIterator) {
151 return IOServiceGetMatchingServices(libusb_darwin_mp, IOServiceMatching(kIOUSBDeviceClassName), deviceIterator);
154 static usb_device_t **usb_get_next_device (io_iterator_t deviceIterator, UInt32 *locationp) {
155 io_cf_plugin_ref_t *plugInInterface = NULL;
156 usb_device_t **device;
157 io_service_t usbDevice;
161 if (!IOIteratorIsValid (deviceIterator) || !(usbDevice = IOIteratorNext(deviceIterator)))
164 result = IOCreatePlugInInterfaceForService(usbDevice, kIOUSBDeviceUserClientTypeID,
165 kIOCFPlugInInterfaceID, &plugInInterface,
168 if (result || !plugInInterface) {
169 usbi_dbg ("libusb/darwin.c usb_get_next_device: could not set up plugin for service: %s\n", darwin_error_str (result));
174 (void)IOObjectRelease(usbDevice);
175 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
178 (*plugInInterface)->Stop(plugInInterface);
179 IODestroyPlugInInterface (plugInInterface);
181 (*(device))->GetLocationID(device, locationp);
186 static kern_return_t darwin_get_device (uint32_t dev_location, usb_device_t ***darwin_device) {
187 kern_return_t kresult;
189 io_iterator_t deviceIterator;
191 kresult = usb_setup_device_iterator (&deviceIterator);
195 /* This port of libusb uses locations to keep track of devices. */
196 while ((*darwin_device = usb_get_next_device (deviceIterator, &location)) != NULL) {
197 if (location == dev_location)
200 (**darwin_device)->Release(*darwin_device);
203 IOObjectRelease (deviceIterator);
205 if (!(*darwin_device))
206 return kIOReturnNoDevice;
208 return kIOReturnSuccess;
213 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
214 struct libusb_context *ctx = (struct libusb_context *)ptr;
215 struct libusb_device_handle *handle;
216 struct darwin_device_priv *dpriv;
217 struct darwin_device_handle_priv *priv;
221 CFTypeRef locationCF;
224 usbi_info (ctx, "a device has been detached");
226 while ((device = IOIteratorNext (rem_devices)) != 0) {
227 /* get the location from the i/o registry */
228 locationCF = IORegistryEntryCreateCFProperty (device, CFSTR(kUSBDevicePropertyLocationID), kCFAllocatorDefault, 0);
230 CFNumberGetValue(locationCF, kCFNumberLongType, &location);
231 CFRelease (locationCF);
232 IOObjectRelease (device);
234 pthread_mutex_lock(&ctx->open_devs_lock);
235 list_for_each_entry(handle, &ctx->open_devs, list) {
236 dpriv = (struct darwin_device_priv *)handle->dev->os_priv;
238 /* the device may have been opened several times. write to each handle's event descriptor */
239 if (dpriv->location == location && handle->os_priv) {
240 priv = (struct darwin_device_handle_priv *)handle->os_priv;
242 message = MESSAGE_DEVICE_GONE;
243 write (priv->fds[1], &message, sizeof (message));
247 pthread_mutex_unlock(&ctx->open_devs_lock);
251 static void darwin_clear_iterator (io_iterator_t iter) {
254 while ((device = IOIteratorNext (iter)) != 0)
255 IOObjectRelease (device);
258 static void *event_thread_main (void *arg0) {
260 struct libusb_context *ctx = (struct libusb_context *)arg0;
262 /* hotplug (device removal) source */
263 CFRunLoopSourceRef libusb_notification_cfsource;
264 io_notification_port_t libusb_notification_port;
265 io_iterator_t libusb_rem_device_iterator;
267 usbi_info (ctx, "creating hotplug event source");
269 CFRetain (CFRunLoopGetCurrent ());
271 /* add the notification port to the run loop */
272 libusb_notification_port = IONotificationPortCreate (libusb_darwin_mp);
273 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
274 CFRunLoopAddSource(CFRunLoopGetCurrent (), libusb_notification_cfsource, kCFRunLoopDefaultMode);
276 /* create notifications for removed devices */
277 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
278 IOServiceMatching(kIOUSBDeviceClassName),
279 (IOServiceMatchingCallback)darwin_devices_detached,
280 (void *)ctx, &libusb_rem_device_iterator);
282 if (kresult != kIOReturnSuccess) {
283 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
285 pthread_exit ((void *)kresult);
289 darwin_clear_iterator (libusb_rem_device_iterator);
291 /* let the main thread know about the async runloop */
292 libusb_darwin_acfl = CFRunLoopGetCurrent ();
294 usbi_info (ctx, "libopenusb/darwin.c event_thread_main: thread ready to receive events");
296 /* run the runloop */
299 usbi_info (ctx, "libopenusb/darwin.c event_thread_main: thread exiting");
301 /* delete notification port */
302 CFRunLoopSourceInvalidate (libusb_notification_cfsource);
303 IONotificationPortDestroy (libusb_notification_port);
305 CFRelease (CFRunLoopGetCurrent ());
307 libusb_darwin_acfl = NULL;
312 static int darwin_init(struct libusb_context *ctx) {
315 if (!(initCount++)) {
316 /* Create the master port for talking to IOKit */
317 if (!libusb_darwin_mp) {
318 kresult = IOMasterPort (MACH_PORT_NULL, &libusb_darwin_mp);
320 if (kresult != kIOReturnSuccess || !libusb_darwin_mp)
321 return darwin_to_libusb (kresult);
324 pthread_create (&libusb_darwin_at, NULL, event_thread_main, (void *)ctx);
326 while (!libusb_darwin_acfl)
333 static void darwin_exit (void) {
334 if (!(--initCount)) {
337 /* stop the async runloop */
338 CFRunLoopStop (libusb_darwin_acfl);
339 pthread_join (libusb_darwin_at, &ret);
341 if (libusb_darwin_mp)
342 mach_port_deallocate(mach_task_self(), libusb_darwin_mp);
344 libusb_darwin_mp = 0;
348 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
349 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
351 /* return cached copy */
352 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
359 static int get_configuration_index (struct libusb_device *dev, int config_value) {
360 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
362 IOUSBConfigurationDescriptorPtr desc;
365 /* is there a simpler way to determine the index? */
366 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
367 if (kresult != kIOReturnSuccess)
368 return darwin_to_libusb (kresult);
370 for (i = 0 ; i < numConfig ; i++) {
371 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
373 if (libusb_le16_to_cpu (desc->bConfigurationValue) == config_value)
377 /* configuration not found */
378 return LIBUSB_ERROR_OTHER;
381 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
382 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
387 kresult = (*(priv->device))->GetConfiguration (priv->device, &config_value);
388 if (kresult != kIOReturnSuccess)
389 return darwin_to_libusb (kresult);
391 config_index = get_configuration_index (dev, config_value);
392 if (config_index < 0)
395 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
398 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
399 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
400 IOUSBConfigurationDescriptorPtr desc;
402 usb_device_t **device = NULL;
405 return LIBUSB_ERROR_OTHER;
408 kresult = darwin_get_device (priv->location, &device);
409 if (kresult || !device) {
410 usbi_err (DEVICE_CTX (dev), "could not find device: %s", darwin_error_str (kresult));
412 return darwin_to_libusb (kresult);
415 /* don't have to open the device to get a config descriptor */
417 device = priv->device;
419 kresult = (*device)->GetConfigurationDescriptorPtr (device, config_index, &desc);
420 if (kresult == kIOReturnSuccess) {
421 /* copy descriptor */
422 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
423 len = libusb_le16_to_cpu(desc->wTotalLength);
425 memmove (buffer, desc, len);
427 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
432 (*device)->Release (device);
434 return darwin_to_libusb (kresult);
437 static int process_new_device (struct libusb_context *ctx, usb_device_t **device, UInt32 locationID, struct discovered_devs **_discdevs) {
438 struct darwin_device_priv *priv;
439 struct libusb_device *dev;
440 struct discovered_devs *discdevs;
441 UInt16 address, idVendor, idProduct;
442 UInt8 bDeviceClass, bDeviceSubClass;
444 int ret, need_unref = 0;
446 dev = usbi_get_device_by_session_id(ctx, locationID);
448 usbi_info (ctx, "allocating new device for location 0x%08x", locationID);
449 dev = usbi_alloc_device(ctx, locationID);
452 return LIBUSB_ERROR_NO_MEM;
454 priv = (struct darwin_device_priv *)dev->os_priv;
456 /* Set up request for device descriptor */
457 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
458 req.bRequest = kUSBRqGetDescriptor;
459 req.wValue = kUSBDeviceDesc << 8;
461 req.wLength = sizeof(IOUSBDeviceDescriptor);
462 req.pData = &(priv->dev_descriptor);
464 (*(device))->GetDeviceAddress (device, (USBDeviceAddress *)&address);
465 (*(device))->GetDeviceProduct (device, &idProduct);
466 (*(device))->GetDeviceVendor (device, &idVendor);
467 (*(device))->GetDeviceClass (device, &bDeviceClass);
468 (*(device))->GetDeviceSubClass (device, &bDeviceSubClass);
470 /**** retrieve device descriptors ****/
471 /* device must be open for DeviceRequest */
472 (*device)->USBDeviceOpen(device);
474 ret = (*(device))->DeviceRequest (device, &req);
475 if (ret != kIOReturnSuccess) {
476 int try_unsuspend = 1;
477 #if DeviceVersion >= 320
480 /* device may be suspended. unsuspend it and try again */
481 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
482 (void)(*device)->GetUSBDeviceInformation (device, &info);
484 try_unsuspend = info & (1 << kUSBInformationDeviceIsSuspendedBit);
488 /* resume the device */
489 (void)(*device)->USBDeviceSuspend (device, 0);
491 ret = (*(device))->DeviceRequest (device, &req);
493 /* resuspend the device */
494 (void)(*device)->USBDeviceSuspend (device, 1);
498 (*device)->USBDeviceClose (device);
500 if (ret != kIOReturnSuccess) {
501 usbi_warn (ctx, "could not retrieve device descriptor: %s. skipping device", darwin_error_str (ret));
503 libusb_unref_device(dev);
506 /**** end: retrieve device descriptors ****/
508 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
509 if (libusb_le16_to_cpu (priv->dev_descriptor.idProduct) != idProduct) {
510 /* not a valid device */
511 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
512 idProduct, libusb_le16_to_cpu (priv->dev_descriptor.idProduct));
513 libusb_unref_device(dev);
517 dev->bus_number = locationID >> 24;
518 dev->device_address = address;
520 /* save our location, we'll need this later */
521 priv->location = locationID;
522 snprintf(priv->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", address, idVendor, idProduct, bDeviceClass, bDeviceSubClass);
524 ret = usbi_sanitize_device(dev);
528 libusb_unref_device(dev);
532 priv = (struct darwin_device_priv *)dev->os_priv;
534 usbi_info (ctx, "using existing device for location 0x%08x", locationID);
537 /* append the device to the list of discovered devices */
538 discdevs = discovered_devs_append(*_discdevs, dev);
540 return LIBUSB_ERROR_NO_MEM;
542 *_discdevs = discdevs;
544 usbi_info (ctx, "found device with address %d at %s", dev->device_address, priv->sys_path);
547 libusb_unref_device(dev);
552 static int darwin_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs) {
553 io_iterator_t deviceIterator;
554 usb_device_t **device;
555 kern_return_t kresult;
558 if (!libusb_darwin_mp)
559 return LIBUSB_ERROR_INVALID_PARAM;
561 kresult = usb_setup_device_iterator (&deviceIterator);
562 if (kresult != kIOReturnSuccess)
563 return darwin_to_libusb (kresult);
565 while ((device = usb_get_next_device (deviceIterator, &location)) != NULL) {
566 (void) process_new_device (ctx, device, location, _discdevs);
568 (*(device))->Release(device);
571 IOObjectRelease(deviceIterator);
576 static int darwin_open (struct libusb_device_handle *dev_handle) {
577 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
578 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
579 usb_device_t **darwin_device;
582 if (0 == dpriv->open_count) {
583 kresult = darwin_get_device (dpriv->location, &darwin_device);
585 usbi_err (HANDLE_CTX (dev_handle), "could not find device: %s", darwin_error_str (kresult));
586 return darwin_to_libusb (kresult);
589 dpriv->device = darwin_device;
591 /* try to open the device */
592 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
594 if (kresult != kIOReturnSuccess) {
595 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
598 case kIOReturnExclusiveAccess:
599 /* it is possible to perform some actions on a device that is not open so do not return an error */
604 (*(dpriv->device))->Release (dpriv->device);
605 dpriv->device = NULL;
606 return darwin_to_libusb (kresult);
611 /* create async event source */
612 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
614 CFRetain (libusb_darwin_acfl);
616 /* add the cfSource to the aync run loop */
617 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
621 /* device opened successfully */
624 /* create a file descriptor for notifications */
627 /* set the pipe to be non-blocking */
628 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
630 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
632 usbi_info (HANDLE_CTX (dev_handle), "device open for access");
637 static void darwin_close (struct libusb_device_handle *dev_handle) {
638 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
639 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
643 if (dpriv->open_count == 0) {
644 /* something is probably very wrong if this is the case */
645 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!\n");
651 /* make sure all interfaces are released */
652 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
653 if (dev_handle->claimed_interfaces & (1 << i))
654 libusb_release_interface (dev_handle, i);
656 if (0 == dpriv->open_count) {
658 /* delete the device's async event source */
659 if (priv->cfSource) {
660 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
661 CFRelease (priv->cfSource);
664 /* close the device */
665 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
667 /* Log the fact that we had a problem closing the file, however failing a
668 * close isn't really an error, so return success anyway */
669 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
673 kresult = (*(dpriv->device))->Release(dpriv->device);
675 /* Log the fact that we had a problem closing the file, however failing a
676 * close isn't really an error, so return success anyway */
677 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
680 dpriv->device = NULL;
683 /* file descriptors are maintained per-instance */
684 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
685 close (priv->fds[1]);
686 close (priv->fds[0]);
688 priv->fds[0] = priv->fds[1] = -1;
691 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
692 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
696 kresult = (*(dpriv->device))->GetConfiguration (dpriv->device, &configNum);
697 if (kresult != kIOReturnSuccess)
698 return darwin_to_libusb (kresult);
700 *config = (int) configNum;
705 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
706 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
710 /* Setting configuration will invalidate the interface, so we need
711 to reclaim it. First, dispose of existing interfaces, if any. */
712 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
713 if (dev_handle->claimed_interfaces & (1 << i))
714 darwin_release_interface (dev_handle, i);
716 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
717 if (kresult != kIOReturnSuccess)
718 return darwin_to_libusb (kresult);
720 /* Reclaim any interfaces. */
721 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
722 if (dev_handle->claimed_interfaces & (1 << i))
723 darwin_claim_interface (dev_handle, i);
728 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
729 IOUSBFindInterfaceRequest request;
730 uint8_t current_interface;
731 kern_return_t kresult;
732 io_iterator_t interface_iterator;
734 *usbInterfacep = IO_OBJECT_NULL;
736 /* Setup the Interface Request */
737 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
738 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
739 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
740 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
742 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
746 for ( current_interface = 0 ; current_interface <= ifc ; current_interface++ )
747 *usbInterfacep = IOIteratorNext(interface_iterator);
749 /* done with the interface iterator */
750 IOObjectRelease(interface_iterator);
755 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
756 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
758 /* current interface */
759 struct __darwin_interface *cInterface = &priv->interfaces[iface];
761 kern_return_t kresult;
763 u_int8_t numep, direction, number;
764 u_int8_t dont_care1, dont_care3;
765 u_int16_t dont_care2;
768 usbi_info (HANDLE_CTX (dev_handle), "building table of endpoints.");
770 /* retrieve the total number of endpoints on this interface */
771 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
773 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
774 return darwin_to_libusb (kresult);
777 /* iterate through pipe references */
778 for (i = 1 ; i <= numep ; i++) {
779 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
780 &dont_care2, &dont_care3);
782 if (kresult != kIOReturnSuccess) {
783 usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
785 return darwin_to_libusb (kresult);
788 usbi_info (HANDLE_CTX (dev_handle), "interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
790 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
793 cInterface->num_endpoints = numep;
798 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
799 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
800 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
801 io_service_t usbInterface = IO_OBJECT_NULL;
803 IOCFPlugInInterface **plugInInterface = NULL;
807 /* current interface */
808 struct __darwin_interface *cInterface = &priv->interfaces[iface];
810 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
811 if (kresult != kIOReturnSuccess)
812 return darwin_to_libusb (kresult);
814 /* make sure we have an interface */
816 u_int8_t nConfig; /* Index of configuration to use */
817 IOUSBConfigurationDescriptorPtr configDesc; /* to describe which configuration to select */
818 /* Only a composite class device with no vendor-specific driver will
819 be configured. Otherwise, we need to do it ourselves, or there
820 will be no interfaces for the device. */
822 usbi_info (HANDLE_CTX (dev_handle), "no interface found; selecting configuration" );
824 kresult = (*(dpriv->device))->GetNumberOfConfigurations (dpriv->device, &nConfig);
825 if (kresult != kIOReturnSuccess) {
826 usbi_err (HANDLE_CTX (dev_handle), "GetNumberOfConfigurations: %s", darwin_error_str(kresult));
827 return darwin_to_libusb(kresult);
831 usbi_err (HANDLE_CTX (dev_handle), "GetNumberOfConfigurations: no configurations");
832 return LIBUSB_ERROR_OTHER;
835 usbi_info (HANDLE_CTX (dev_handle), "device has %d configuration%s. using the first",
836 (int)nConfig, (nConfig > 1 ? "s" : "") );
838 /* Always use the first configuration */
839 kresult = (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, 0, &configDesc);
840 if (kresult != kIOReturnSuccess) {
841 usbi_err (HANDLE_CTX (dev_handle), "GetConfigurationDescriptorPtr: %s",
842 darwin_error_str(kresult));
846 new_config = configDesc->bConfigurationValue;
848 usbi_info (HANDLE_CTX (dev_handle), "new configuration value is %d", new_config);
850 /* set the configuration */
851 kresult = darwin_set_configuration (dev_handle, new_config);
852 if (kresult != LIBUSB_SUCCESS) {
853 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
857 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
859 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
860 return darwin_to_libusb (kresult);
865 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
866 return LIBUSB_ERROR_NOT_FOUND;
869 /* get an interface to the device's interface */
870 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
871 kIOCFPlugInInterfaceID, &plugInInterface, &score);
873 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
874 return darwin_to_libusb (kresult);
877 if (!plugInInterface) {
878 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
879 return LIBUSB_ERROR_NOT_FOUND;
882 /* ignore release error */
883 (void)IOObjectRelease (usbInterface);
885 /* Do the actual claim */
886 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
887 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
888 (LPVOID)&cInterface->interface);
889 if (kresult || !cInterface->interface) {
890 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
891 return darwin_to_libusb (kresult);
894 /* We no longer need the intermediate plug-in */
895 (*plugInInterface)->Release(plugInInterface);
897 /* claim the interface */
898 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
900 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
901 return darwin_to_libusb (kresult);
904 /* update list of endpoints */
905 kresult = get_endpoints (dev_handle, iface);
907 /* this should not happen */
908 darwin_release_interface (dev_handle, iface);
909 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
913 cInterface->cfSource = NULL;
915 /* create async event source */
916 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
917 if (kresult != kIOReturnSuccess) {
918 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
920 /* can't continue without an async event source */
921 (void)darwin_release_interface (dev_handle, iface);
923 return darwin_to_libusb (kresult);
926 /* add the cfSource to the async thread's run loop */
927 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
929 usbi_info (HANDLE_CTX (dev_handle), "interface opened");
934 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
935 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
938 /* current interface */
939 struct __darwin_interface *cInterface = &priv->interfaces[iface];
941 /* Check to see if an interface is open */
942 if (!cInterface->interface)
943 return LIBUSB_SUCCESS;
945 /* clean up endpoint data */
946 cInterface->num_endpoints = 0;
948 /* delete the interface's async event source */
949 if (cInterface->cfSource) {
950 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
951 CFRelease (cInterface->cfSource);
954 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
956 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
958 kresult = (*(cInterface->interface))->Release(cInterface->interface);
959 if (kresult != kIOReturnSuccess)
960 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
962 cInterface->interface = IO_OBJECT_NULL;
964 return darwin_to_libusb (kresult);
967 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
968 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
971 /* current interface */
972 struct __darwin_interface *cInterface = &priv->interfaces[iface];
974 if (!cInterface->interface)
975 return LIBUSB_ERROR_NO_DEVICE;
977 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
978 if (kresult != kIOReturnSuccess)
979 darwin_reset_device (dev_handle);
981 /* update list of endpoints */
982 kresult = get_endpoints (dev_handle, iface);
984 /* this should not happen */
985 darwin_release_interface (dev_handle, iface);
986 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
990 return darwin_to_libusb (kresult);
993 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
994 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
996 /* current interface */
997 struct __darwin_interface *cInterface;
998 uint8_t pipeRef, iface;
1001 /* determine the interface/endpoint to use */
1002 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
1003 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1005 return LIBUSB_ERROR_NOT_FOUND;
1008 cInterface = &priv->interfaces[iface];
1010 #if (InterfaceVersion < 190)
1011 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1013 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1014 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1017 usbi_err (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1019 return darwin_to_libusb (kresult);
1022 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1023 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1026 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1028 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1030 return darwin_to_libusb (kresult);
1033 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1034 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1035 io_service_t usbInterface;
1039 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1041 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1043 return darwin_to_libusb (kresult);
1046 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1047 IOObjectRelease (usbInterface);
1059 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1060 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1061 return LIBUSB_ERROR_NOT_SUPPORTED;
1064 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1065 return LIBUSB_ERROR_NOT_SUPPORTED;
1068 static void darwin_destroy_device(struct libusb_device *dev) {
1071 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1072 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1073 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1076 uint8_t is_read; /* 0 = we're reading, 1 = we're writing */
1077 uint8_t transferType;
1078 /* None of the values below are used in libusb for bulk transfers */
1079 uint8_t direction, number, interval, pipeRef, iface;
1080 uint16_t maxPacketSize;
1082 struct __darwin_interface *cInterface;
1084 /* are we reading or writing? */
1085 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1087 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1088 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1090 return LIBUSB_ERROR_NOT_FOUND;
1093 cInterface = &priv->interfaces[iface];
1095 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1096 &transferType, &maxPacketSize, &interval);
1098 /* submit the request */
1099 /* timeouts are unavailable on interrupt endpoints */
1100 if (transferType == kUSBInterrupt) {
1102 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1103 transfer->length, darwin_async_io_callback, itransfer);
1105 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1106 transfer->length, darwin_async_io_callback, itransfer);
1109 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1110 transfer->length, transfer->timeout, transfer->timeout,
1111 darwin_async_io_callback, (void *)itransfer);
1113 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1114 transfer->length, transfer->timeout, transfer->timeout,
1115 darwin_async_io_callback, (void *)itransfer);
1119 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", is_read ? "In" : "Out",
1120 darwin_error_str(ret), ret);
1122 return darwin_to_libusb (ret);
1125 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1126 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1127 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1128 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1131 uint8_t is_read; /* 0 = we're writing, 1 = we're reading */
1132 uint8_t pipeRef, iface;
1134 AbsoluteTime atTime;
1137 struct __darwin_interface *cInterface;
1139 /* are we reading or writing? */
1140 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1142 /* construct an array of IOUSBIsocFrames */
1143 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1144 if (!tpriv->isoc_framelist)
1145 return LIBUSB_ERROR_NO_MEM;
1147 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1148 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1149 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1151 /* determine the interface/endpoint to use */
1152 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1153 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1155 return LIBUSB_ERROR_NOT_FOUND;
1158 cInterface = &priv->interfaces[iface];
1160 /* Last but not least we need the bus frame number */
1161 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1163 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1164 free(tpriv->isoc_framelist);
1165 tpriv->isoc_framelist = NULL;
1167 return darwin_to_libusb (kresult);
1170 /* schedule for a frame a little in the future */
1173 /* submit the request */
1175 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1176 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1179 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1180 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1183 if (kresult != kIOReturnSuccess) {
1184 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", is_read ? "In" : "Out",
1185 darwin_error_str(kresult));
1186 free (tpriv->isoc_framelist);
1187 tpriv->isoc_framelist = NULL;
1190 return darwin_to_libusb (kresult);
1193 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1194 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1195 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1196 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1197 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1201 bzero(&tpriv->req, sizeof(tpriv->req));
1203 /* IOUSBDeviceInterface expects the request in cpu endianess */
1204 tpriv->req.bmRequestType = setup->bmRequestType;
1205 tpriv->req.bRequest = setup->bRequest;
1206 /* these values should be in bus order from libusb_fill_control_setup */
1207 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1208 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1209 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1210 /* data is stored after the libusb control block */
1211 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1212 tpriv->req.completionTimeout = transfer->timeout;
1213 tpriv->req.noDataTimeout = transfer->timeout;
1215 /* all transfers in libusb-1.0 are async */
1216 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1218 if (kresult != kIOReturnSuccess)
1219 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1221 return darwin_to_libusb (kresult);
1224 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1225 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1227 switch (transfer->type) {
1228 case LIBUSB_TRANSFER_TYPE_CONTROL:
1229 return submit_control_transfer(itransfer);
1230 case LIBUSB_TRANSFER_TYPE_BULK:
1231 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1232 return submit_bulk_transfer(itransfer);
1233 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1234 return submit_iso_transfer(itransfer);
1236 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1237 return LIBUSB_ERROR_INVALID_PARAM;
1241 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1242 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1243 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1246 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions control pipe");
1248 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1250 return darwin_to_libusb (kresult);
1253 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1254 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1255 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1256 struct __darwin_interface *cInterface;
1257 uint8_t pipeRef, iface;
1260 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1261 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1263 return LIBUSB_ERROR_NOT_FOUND;
1266 cInterface = &priv->interfaces[iface];
1268 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions on interface %d pipe %d", iface, pipeRef);
1270 /* abort transactions */
1271 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1273 usbi_info (ITRANSFER_CTX (itransfer), "calling clear pipe stall to clear the data toggle bit");
1275 /* clear the data toggle bit */
1276 #if (InterfaceVersion < 190)
1277 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1279 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1280 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1283 return darwin_to_libusb (kresult);
1286 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1287 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1289 switch (transfer->type) {
1290 case LIBUSB_TRANSFER_TYPE_CONTROL:
1291 return cancel_control_transfer(itransfer);
1292 case LIBUSB_TRANSFER_TYPE_BULK:
1293 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1294 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1295 return darwin_abort_transfers (itransfer);
1297 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1298 return LIBUSB_ERROR_INVALID_PARAM;
1302 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1303 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1304 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1306 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1307 free (tpriv->isoc_framelist);
1308 tpriv->isoc_framelist = NULL;
1312 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1313 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1314 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1315 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1318 usbi_info (ITRANSFER_CTX (itransfer), "an async io operation has completed");
1320 /* send a completion message to the device's file descriptor */
1321 message = MESSAGE_ASYNC_IO_COMPLETE;
1322 write (priv->fds[1], &message, sizeof (message));
1323 write (priv->fds[1], &itransfer, sizeof (itransfer));
1324 write (priv->fds[1], &result, sizeof (IOReturn));
1325 write (priv->fds[1], &arg0, sizeof (UInt32));
1328 static void darwin_bulk_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1329 enum libusb_transfer_status status;
1331 usbi_info (ITRANSFER_CTX (itransfer), "handling bulk completion with status %d", result);
1334 case kIOReturnSuccess:
1335 status = LIBUSB_TRANSFER_COMPLETED;
1336 itransfer->transferred += io_size;
1338 case kIOReturnAborted:
1339 usbi_handle_transfer_cancellation(itransfer);
1341 case kIOUSBPipeStalled:
1342 usbi_warn (ITRANSFER_CTX (itransfer), "bulk error. pipe is stalled");
1343 status = LIBUSB_TRANSFER_STALL;
1346 case kIOReturnOverrun:
1347 usbi_err (ITRANSFER_CTX (itransfer), "bulk error. data overrun", darwin_error_str (result));
1348 status = LIBUSB_TRANSFER_OVERFLOW;
1352 usbi_err (ITRANSFER_CTX (itransfer), "bulk error = %s (value = 0x%08x)", darwin_error_str (result), result);
1353 status = LIBUSB_TRANSFER_ERROR;
1356 usbi_handle_transfer_completion(itransfer, status);
1359 static void darwin_isoc_callback (struct usbi_transfer *itransfer, kern_return_t result) {
1360 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1361 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1364 usbi_info (ITRANSFER_CTX (itransfer), "handling isoc completion with status %d", result);
1366 if (result == kIOReturnSuccess && tpriv->isoc_framelist) {
1367 /* copy isochronous results back */
1369 for (i = 0; i < transfer->num_iso_packets ; i++) {
1370 struct libusb_iso_packet_descriptor *lib_desc = transfer->iso_packet_desc;
1371 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1372 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1377 case kIOReturnSuccess:
1378 status = LIBUSB_TRANSFER_COMPLETED;
1380 case kIOReturnAborted:
1381 usbi_handle_transfer_cancellation(itransfer);
1383 case kIOUSBPipeStalled:
1384 usbi_warn (ITRANSFER_CTX (itransfer), "unsupported control request");
1385 status = LIBUSB_TRANSFER_STALL;
1388 case kIOReturnOverrun:
1389 usbi_err (ITRANSFER_CTX (itransfer), "bulk error. data overrun", darwin_error_str (result));
1390 status = LIBUSB_TRANSFER_OVERFLOW;
1394 usbi_err (ITRANSFER_CTX (itransfer), "control error = %s", darwin_error_str (result));
1395 status = LIBUSB_TRANSFER_ERROR;
1398 usbi_handle_transfer_completion(itransfer, status);
1401 static void darwin_control_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1404 usbi_info (ITRANSFER_CTX (itransfer), "handling control completion with status %d", result);
1407 case kIOReturnSuccess:
1408 status = LIBUSB_TRANSFER_COMPLETED;
1409 itransfer->transferred += io_size;
1411 case kIOReturnAborted:
1412 usbi_handle_transfer_cancellation(itransfer);
1414 case kIOUSBPipeStalled:
1415 usbi_warn (ITRANSFER_CTX (itransfer), "unsupported control request");
1416 status = LIBUSB_TRANSFER_STALL;
1420 usbi_err (ITRANSFER_CTX (itransfer), "control error = %s", darwin_error_str (result));
1421 status = LIBUSB_TRANSFER_ERROR;
1424 usbi_handle_transfer_completion(itransfer, status);
1427 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1428 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1430 switch (transfer->type) {
1431 case LIBUSB_TRANSFER_TYPE_CONTROL:
1432 darwin_control_callback (itransfer, result, io_size);
1434 case LIBUSB_TRANSFER_TYPE_BULK:
1435 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1436 darwin_bulk_callback (itransfer, result, io_size);
1438 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1439 darwin_isoc_callback (itransfer, result);
1442 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1446 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, nfds_t nfds, int num_ready) {
1447 struct usbi_transfer *itransfer;
1453 pthread_mutex_lock(&ctx->open_devs_lock);
1454 for (i = 0; i < nfds && num_ready > 0; i++) {
1455 struct pollfd *pollfd = &fds[i];
1456 struct libusb_device_handle *handle;
1457 struct darwin_device_handle_priv *hpriv = NULL;
1459 usbi_info (ctx, "checking fd %i with revents = %x", fds[i], pollfd->revents);
1461 if (!pollfd->revents)
1465 list_for_each_entry(handle, &ctx->open_devs, list) {
1466 hpriv = (struct darwin_device_handle_priv *)handle->os_priv;
1467 if (hpriv->fds[0] == pollfd->fd)
1471 if (!(pollfd->revents & POLLERR)) {
1472 ret = read (hpriv->fds[0], &message, sizeof (message));
1473 if (ret < sizeof (message))
1476 /* could not poll the device-- response is to delete the device (this seems a little heavy-handed) */
1477 message = MESSAGE_DEVICE_GONE;
1480 case MESSAGE_DEVICE_GONE:
1481 /* remove the device's async port from the runloop */
1482 if (hpriv->cfSource) {
1483 if (libusb_darwin_acfl)
1484 CFRunLoopRemoveSource (libusb_darwin_acfl, hpriv->cfSource, kCFRunLoopDefaultMode);
1485 CFRelease (hpriv->cfSource);
1486 hpriv->cfSource = NULL;
1489 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
1490 usbi_handle_disconnect(handle);
1492 /* done with this device */
1494 case MESSAGE_ASYNC_IO_COMPLETE:
1495 read (hpriv->fds[0], &itransfer, sizeof (itransfer));
1496 read (hpriv->fds[0], &kresult, sizeof (IOReturn));
1497 read (hpriv->fds[0], &io_size, sizeof (UInt32));
1499 darwin_handle_callback (itransfer, kresult, io_size);
1502 usbi_err (ctx, "unknown message received from device pipe");
1506 pthread_mutex_unlock(&ctx->open_devs_lock);
1511 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1512 mach_timespec_t sys_time;
1513 clock_serv_t clock_ref;
1516 case USBI_CLOCK_REALTIME:
1517 /* CLOCK_REALTIME represents time since the epoch */
1518 host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &clock_ref);
1520 case USBI_CLOCK_MONOTONIC:
1521 /* use system boot time as reference for the monotonic clock */
1522 host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &clock_ref);
1525 return LIBUSB_ERROR_INVALID_PARAM;
1528 clock_get_time (clock_ref, &sys_time);
1530 tp->tv_sec = sys_time.tv_sec;
1531 tp->tv_nsec = sys_time.tv_nsec;
1536 const struct usbi_os_backend darwin_backend = {
1538 .init = darwin_init,
1539 .exit = darwin_exit,
1540 .get_device_list = darwin_get_device_list,
1541 .get_device_descriptor = darwin_get_device_descriptor,
1542 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1543 .get_config_descriptor = darwin_get_config_descriptor,
1545 .open = darwin_open,
1546 .close = darwin_close,
1547 .get_configuration = darwin_get_configuration,
1548 .set_configuration = darwin_set_configuration,
1549 .claim_interface = darwin_claim_interface,
1550 .release_interface = darwin_release_interface,
1552 .set_interface_altsetting = darwin_set_interface_altsetting,
1553 .clear_halt = darwin_clear_halt,
1554 .reset_device = darwin_reset_device,
1556 .kernel_driver_active = darwin_kernel_driver_active,
1557 .detach_kernel_driver = darwin_detach_kernel_driver,
1558 .attach_kernel_driver = darwin_attach_kernel_driver,
1560 .destroy_device = darwin_destroy_device,
1562 .submit_transfer = darwin_submit_transfer,
1563 .cancel_transfer = darwin_cancel_transfer,
1564 .clear_transfer_priv = darwin_clear_transfer_priv,
1566 .handle_events = op_handle_events,
1568 .clock_gettime = darwin_clock_gettime,
1570 .device_priv_size = sizeof(struct darwin_device_priv),
1571 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1572 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1573 .add_iso_packet_size = 0,