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";
84 case kIOReturnOverrun:
85 return "data overrun";
87 return "unknown error";
91 static int darwin_to_libusb (int result) {
93 case kIOReturnSuccess:
94 return LIBUSB_SUCCESS;
95 case kIOReturnNotOpen:
96 case kIOReturnNoDevice:
97 return LIBUSB_ERROR_NO_DEVICE;
98 case kIOReturnExclusiveAccess:
99 return LIBUSB_ERROR_ACCESS;
100 case kIOUSBPipeStalled:
101 return LIBUSB_ERROR_PIPE;
102 case kIOReturnBadArgument:
103 return LIBUSB_ERROR_INVALID_PARAM;
104 case kIOUSBTransactionTimeout:
105 return LIBUSB_ERROR_TIMEOUT;
106 case kIOReturnNotResponding:
107 case kIOReturnAborted:
109 case kIOUSBNoAsyncPortErr:
111 return LIBUSB_ERROR_OTHER;
116 static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp) {
117 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
119 /* current interface */
120 struct __darwin_interface *cInterface;
124 _usbi_log (HANDLE_CTX(dev_handle), LOG_LEVEL_INFO, "converting ep address 0x%02x to pipeRef and interface", ep);
126 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
127 cInterface = &priv->interfaces[iface];
129 if (dev_handle->claimed_interfaces & (1 << iface)) {
130 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
131 if (cInterface->endpoint_addrs[i] == ep) {
134 _usbi_log (HANDLE_CTX(dev_handle), LOG_LEVEL_INFO, "pipe %d on interface %d matches", *pipep, *ifcp);
141 /* No pipe found with the correct endpoint address */
142 _usbi_log (HANDLE_CTX(dev_handle), LOG_LEVEL_WARNING, "no pipeRef found with endpoint address 0x%02x.", ep);
147 static int usb_setup_device_iterator (io_iterator_t *deviceIterator) {
148 return IOServiceGetMatchingServices(libusb_darwin_mp, IOServiceMatching(kIOUSBDeviceClassName), deviceIterator);
151 static usb_device_t **usb_get_next_device (io_iterator_t deviceIterator, UInt32 *locationp) {
152 io_cf_plugin_ref_t *plugInInterface = NULL;
153 usb_device_t **device;
154 io_service_t usbDevice;
158 if (!IOIteratorIsValid (deviceIterator) || !(usbDevice = IOIteratorNext(deviceIterator)))
161 result = IOCreatePlugInInterfaceForService(usbDevice, kIOUSBDeviceUserClientTypeID,
162 kIOCFPlugInInterfaceID, &plugInInterface,
165 if (result || !plugInInterface) {
166 usbi_dbg ("libusb/darwin.c usb_get_next_device: could not set up plugin for service: %s\n", darwin_error_str (result));
171 (void)IOObjectRelease(usbDevice);
172 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
175 (*plugInInterface)->Stop(plugInInterface);
176 IODestroyPlugInInterface (plugInInterface);
178 (*(device))->GetLocationID(device, locationp);
183 static kern_return_t darwin_get_device (uint32_t dev_location, usb_device_t ***darwin_device) {
184 kern_return_t kresult;
186 io_iterator_t deviceIterator;
188 kresult = usb_setup_device_iterator (&deviceIterator);
192 /* This port of libusb uses locations to keep track of devices. */
193 while ((*darwin_device = usb_get_next_device (deviceIterator, &location)) != NULL) {
194 if (location == dev_location)
197 (**darwin_device)->Release(*darwin_device);
200 IOObjectRelease (deviceIterator);
202 if (!(*darwin_device))
203 return kIOReturnNoDevice;
205 return kIOReturnSuccess;
210 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
211 struct libusb_context *ctx = (struct libusb_context *)ptr;
212 struct libusb_device_handle *handle;
213 struct darwin_device_priv *dpriv;
214 struct darwin_device_handle_priv *priv;
218 CFTypeRef locationCF;
221 _usbi_log (ctx, LOG_LEVEL_INFO, "a device has been detached");
223 while ((device = IOIteratorNext (rem_devices)) != 0) {
224 /* get the location from the i/o registry */
225 locationCF = IORegistryEntryCreateCFProperty (device, CFSTR(kUSBDevicePropertyLocationID), kCFAllocatorDefault, 0);
227 CFNumberGetValue(locationCF, kCFNumberLongType, &location);
228 CFRelease (locationCF);
229 IOObjectRelease (device);
231 pthread_mutex_lock(&ctx->open_devs_lock);
232 list_for_each_entry(handle, &ctx->open_devs, list) {
233 dpriv = (struct darwin_device_priv *)handle->dev->os_priv;
234 if (dpriv->location == location)
238 if (handle && handle->os_priv) {
239 priv = (struct darwin_device_handle_priv *)handle->os_priv;
241 message = MESSAGE_DEVICE_GONE;
242 write (priv->fds[1], &message, sizeof (message));
245 pthread_mutex_unlock(&ctx->open_devs_lock);
250 static void darwin_clear_iterator (io_iterator_t iter) {
253 while ((device = IOIteratorNext (iter)) != 0)
254 IOObjectRelease (device);
257 static void *event_thread_main (void *arg0) {
259 struct libusb_context *ctx = (struct libusb_context *)arg0;
261 /* hotplug (device removal) source */
262 CFRunLoopSourceRef libusb_notification_cfsource;
263 io_notification_port_t libusb_notification_port;
264 io_iterator_t libusb_rem_device_iterator;
266 _usbi_log (ctx, LOG_LEVEL_INFO, "creating hotplug event source");
268 CFRetain (CFRunLoopGetCurrent ());
270 /* add the notification port to the run loop */
271 libusb_notification_port = IONotificationPortCreate (libusb_darwin_mp);
272 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
273 CFRunLoopAddSource(CFRunLoopGetCurrent (), libusb_notification_cfsource, kCFRunLoopDefaultMode);
275 /* create notifications for removed devices */
276 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
277 IOServiceMatching(kIOUSBDeviceClassName),
278 (IOServiceMatchingCallback)darwin_devices_detached,
279 (void *)ctx, &libusb_rem_device_iterator);
281 if (kresult != kIOReturnSuccess) {
282 _usbi_log (ctx, LOG_LEVEL_ERROR, "could not add hotplug event source: %s", darwin_error_str (kresult));
284 pthread_exit ((void *)kresult);
288 darwin_clear_iterator (libusb_rem_device_iterator);
290 /* let the main thread know about the async runloop */
291 libusb_darwin_acfl = CFRunLoopGetCurrent ();
293 _usbi_log (ctx, LOG_LEVEL_INFO, "libopenusb/darwin.c event_thread_main: thread ready to receive events");
295 /* run the runloop */
298 _usbi_log (ctx, LOG_LEVEL_INFO, "libopenusb/darwin.c event_thread_main: thread exiting");
300 /* delete notification port */
301 CFRunLoopSourceInvalidate (libusb_notification_cfsource);
302 IONotificationPortDestroy (libusb_notification_port);
304 CFRelease (CFRunLoopGetCurrent ());
306 libusb_darwin_acfl = NULL;
311 static int darwin_init(struct libusb_context *ctx) {
314 /* Create the master port for talking to IOKit */
315 if (!libusb_darwin_mp) {
316 kresult = IOMasterPort (MACH_PORT_NULL, &libusb_darwin_mp);
318 if (kresult != kIOReturnSuccess || !libusb_darwin_mp)
319 return darwin_to_libusb (kresult);
322 pthread_create (&libusb_darwin_at, NULL, event_thread_main, (void *)ctx);
324 while (!libusb_darwin_acfl)
330 static void darwin_exit (void) {
333 /* stop the async runloop */
334 CFRunLoopStop (libusb_darwin_acfl);
335 pthread_join (libusb_darwin_at, &ret);
337 if (libusb_darwin_mp)
338 mach_port_deallocate(mach_task_self(), libusb_darwin_mp);
340 libusb_darwin_mp = 0;
343 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
344 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
346 /* return cached copy */
347 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
354 static int get_configuration_index (struct libusb_device *dev, int config_value) {
355 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
357 IOUSBConfigurationDescriptorPtr desc;
360 /* is there a simpler way to determine the index? */
361 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
362 if (kresult != kIOReturnSuccess)
363 return darwin_to_libusb (kresult);
365 for (i = 0 ; i < numConfig ; i++) {
366 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
368 if (libusb_le16_to_cpu (desc->bConfigurationValue) == config_value)
372 /* configuration not found */
373 return LIBUSB_ERROR_OTHER;
376 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
377 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
382 kresult = (*(priv->device))->GetConfiguration (priv->device, &config_value);
383 if (kresult != kIOReturnSuccess)
384 return darwin_to_libusb (kresult);
386 config_index = get_configuration_index (dev, config_value);
387 if (config_index < 0)
390 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
393 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
394 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
395 IOUSBConfigurationDescriptorPtr desc;
397 usb_device_t **device = NULL;
400 return LIBUSB_ERROR_OTHER;
403 kresult = darwin_get_device (priv->location, &device);
404 if (kresult || !device) {
405 _usbi_log (DEVICE_CTX (dev), LOG_LEVEL_ERROR, "could not find device: %s", darwin_error_str (kresult));
407 return darwin_to_libusb (kresult);
410 /* don't have to open the device to get a config descriptor */
412 device = priv->device;
414 kresult = (*device)->GetConfigurationDescriptorPtr (device, config_index, &desc);
415 if (kresult == kIOReturnSuccess) {
416 /* copy descriptor */
417 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
418 len = libusb_le16_to_cpu(desc->wTotalLength);
420 memmove (buffer, desc, len);
422 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
427 (*device)->Release (device);
429 return darwin_to_libusb (kresult);
432 static int process_new_device (struct libusb_context *ctx, usb_device_t **device, UInt32 locationID, struct discovered_devs **_discdevs) {
433 struct darwin_device_priv *priv;
434 struct libusb_device *dev;
435 struct discovered_devs *discdevs;
436 UInt16 address, idVendor, idProduct;
437 UInt8 bDeviceClass, bDeviceSubClass;
441 dev = usbi_get_device_by_session_id(ctx, locationID);
443 _usbi_log (ctx, LOG_LEVEL_INFO, "allocating new device for location 0x%08x", locationID);
444 dev = usbi_alloc_device(ctx, locationID);
446 return LIBUSB_ERROR_NO_MEM;
448 priv = (struct darwin_device_priv *)dev->os_priv;
450 /* Set up request for device descriptor */
451 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
452 req.bRequest = kUSBRqGetDescriptor;
453 req.wValue = kUSBDeviceDesc << 8;
455 req.wLength = sizeof(IOUSBDeviceDescriptor);
456 req.pData = &(priv->dev_descriptor);
458 (*(device))->GetDeviceAddress (device, (USBDeviceAddress *)&address);
459 (*(device))->GetDeviceProduct (device, &idProduct);
460 (*(device))->GetDeviceVendor (device, &idVendor);
461 (*(device))->GetDeviceClass (device, &bDeviceClass);
462 (*(device))->GetDeviceSubClass (device, &bDeviceSubClass);
464 /**** retrieve device descriptors ****/
465 /* device must be open for DeviceRequest */
466 (*device)->USBDeviceOpen(device);
468 ret = (*(device))->DeviceRequest (device, &req);
469 if (ret != kIOReturnSuccess) {
470 int try_unsuspend = 1;
471 #if DeviceVersion >= 320
474 /* device may be suspended. unsuspend it and try again */
475 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
476 (void)(*device)->GetUSBDeviceInformation (device, &info);
478 try_unsuspend = info & (1 << kUSBInformationDeviceIsSuspendedBit);
482 /* resume the device */
483 (void)(*device)->USBDeviceSuspend (device, 0);
485 ret = (*(device))->DeviceRequest (device, &req);
487 /* resuspend the device */
488 (void)(*device)->USBDeviceSuspend (device, 1);
492 (*device)->USBDeviceClose (device);
494 if (ret != kIOReturnSuccess) {
495 _usbi_log (ctx, LOG_LEVEL_WARNING, "could not retrieve device descriptor: %s. skipping device", darwin_error_str (ret));
496 libusb_unref_device(dev);
499 /**** end: retrieve device descriptors ****/
501 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
502 if (libusb_le16_to_cpu (priv->dev_descriptor.idProduct) != idProduct) {
503 /* not a valid device */
504 _usbi_log (ctx, LOG_LEVEL_WARNING, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
505 idProduct, libusb_le16_to_cpu (priv->dev_descriptor.idProduct));
506 libusb_unref_device(dev);
510 dev->bus_number = locationID >> 24;
511 dev->device_address = address;
513 /* save our location, we'll need this later */
514 priv->location = locationID;
515 snprintf(priv->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", address, idVendor, idProduct, bDeviceClass, bDeviceSubClass);
517 ret = usbi_sanitize_device(dev);
520 libusb_unref_device(dev);
524 priv = (struct darwin_device_priv *)dev->os_priv;
526 _usbi_log (ctx, LOG_LEVEL_INFO, "using existing device for location 0x%08x", locationID);
529 /* append the device to the list of discovered devices */
530 discdevs = discovered_devs_append(*_discdevs, dev);
532 return LIBUSB_ERROR_NO_MEM;
534 *_discdevs = discdevs;
536 _usbi_log (ctx, LOG_LEVEL_INFO, "found device with address %d at %s", dev->device_address, priv->sys_path);
541 static int darwin_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs) {
542 io_iterator_t deviceIterator;
543 usb_device_t **device;
544 kern_return_t kresult;
547 if (!libusb_darwin_mp)
548 return LIBUSB_ERROR_INVALID_PARAM;
550 kresult = usb_setup_device_iterator (&deviceIterator);
551 if (kresult != kIOReturnSuccess)
552 return darwin_to_libusb (kresult);
554 while ((device = usb_get_next_device (deviceIterator, &location)) != NULL) {
555 (void) process_new_device (ctx, device, location, _discdevs);
557 (*(device))->Release(device);
560 IOObjectRelease(deviceIterator);
565 static int darwin_open (struct libusb_device_handle *dev_handle) {
566 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
567 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
568 usb_device_t **darwin_device;
571 kresult = darwin_get_device (dpriv->location, &darwin_device);
573 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "could not find device: %s", darwin_error_str (kresult));
574 return darwin_to_libusb (kresult);
577 dpriv->device = darwin_device;
579 /* try to open the device */
580 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
582 if (kresult != kIOReturnSuccess) {
583 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "USBDeviceOpen: %s", darwin_error_str(kresult));
586 case kIOReturnExclusiveAccess:
587 /* it is possible to perform some actions on a device that is not open so do not return an error */
592 (*(dpriv->device))->Release (dpriv->device);
593 dpriv->device = NULL;
594 return darwin_to_libusb (kresult);
599 /* create async event source */
600 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
602 CFRetain (libusb_darwin_acfl);
604 /* add the cfSource to the aync run loop */
605 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
608 /* create a file descriptor for notifications */
611 /* set the pipe to be non-blocking */
612 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
614 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
616 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "device open for access");
621 static void darwin_close (struct libusb_device_handle *dev_handle) {
622 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
623 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
627 /* make sure all interfaces are released */
628 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
629 if (dev_handle->claimed_interfaces & (1 << i))
630 libusb_release_interface (dev_handle, i);
633 /* delete the device's async event source */
634 if (priv->cfSource) {
635 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
636 CFRelease (priv->cfSource);
639 /* close the device */
640 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
642 /* Log the fact that we had a problem closing the file, however failing a
643 * close isn't really an error, so return success anyway */
644 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "USBDeviceClose: %s", darwin_error_str(kresult));
648 kresult = (*(dpriv->device))->Release(dpriv->device);
650 /* Log the fact that we had a problem closing the file, however failing a
651 * close isn't really an error, so return success anyway */
652 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "Release: %s", darwin_error_str(kresult));
655 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
656 close (priv->fds[1]);
657 close (priv->fds[0]);
659 dpriv->device = NULL;
660 priv->fds[0] = priv->fds[1] = -1;
663 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
664 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
668 kresult = (*(dpriv->device))->GetConfiguration (dpriv->device, &configNum);
669 if (kresult != kIOReturnSuccess)
670 return darwin_to_libusb (kresult);
672 *config = (int) configNum;
677 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
678 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
682 /* Setting configuration will invalidate the interface, so we need
683 to reclaim it. First, dispose of existing interfaces, if any. */
684 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
685 if (dev_handle->claimed_interfaces & (1 << i))
686 darwin_release_interface (dev_handle, i);
688 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
689 if (kresult != kIOReturnSuccess)
690 return darwin_to_libusb (kresult);
692 /* Reclaim any interfaces. */
693 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
694 if (dev_handle->claimed_interfaces & (1 << i))
695 darwin_claim_interface (dev_handle, i);
700 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
701 IOUSBFindInterfaceRequest request;
702 uint8_t current_interface;
703 kern_return_t kresult;
704 io_iterator_t interface_iterator;
706 *usbInterfacep = IO_OBJECT_NULL;
708 /* Setup the Interface Request */
709 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
710 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
711 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
712 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
714 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
718 for ( current_interface = 0 ; current_interface <= ifc ; current_interface++ )
719 *usbInterfacep = IOIteratorNext(interface_iterator);
721 /* done with the interface iterator */
722 IOObjectRelease(interface_iterator);
727 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
728 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
730 /* current interface */
731 struct __darwin_interface *cInterface = &priv->interfaces[iface];
733 kern_return_t kresult;
735 u_int8_t numep, direction, number;
736 u_int8_t dont_care1, dont_care3;
737 u_int16_t dont_care2;
740 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "building table of endpoints.");
742 /* retrieve the total number of endpoints on this interface */
743 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
745 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
746 return darwin_to_libusb (kresult);
749 /* iterate through pipe references */
750 for (i = 1 ; i <= numep ; i++) {
751 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
752 &dont_care2, &dont_care3);
754 if (kresult != kIOReturnSuccess) {
755 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
757 return darwin_to_libusb (kresult);
760 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
762 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
765 cInterface->num_endpoints = numep;
770 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
771 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
772 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
773 io_service_t usbInterface = IO_OBJECT_NULL;
775 IOCFPlugInInterface **plugInInterface = NULL;
779 /* current interface */
780 struct __darwin_interface *cInterface = &priv->interfaces[iface];
782 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
783 if (kresult != kIOReturnSuccess)
784 return darwin_to_libusb (kresult);
786 /* make sure we have an interface */
788 u_int8_t nConfig; /* Index of configuration to use */
789 IOUSBConfigurationDescriptorPtr configDesc; /* to describe which configuration to select */
790 /* Only a composite class device with no vendor-specific driver will
791 be configured. Otherwise, we need to do it ourselves, or there
792 will be no interfaces for the device. */
794 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "no interface found; selecting configuration" );
796 kresult = (*(dpriv->device))->GetNumberOfConfigurations (dpriv->device, &nConfig);
797 if (kresult != kIOReturnSuccess) {
798 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "GetNumberOfConfigurations: %s", darwin_error_str(kresult));
799 return darwin_to_libusb(kresult);
803 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "GetNumberOfConfigurations: no configurations");
804 return LIBUSB_ERROR_OTHER;
807 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "device has %d configuration%s. using the first",
808 (int)nConfig, (nConfig > 1 ? "s" : "") );
810 /* Always use the first configuration */
811 kresult = (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, 0, &configDesc);
812 if (kresult != kIOReturnSuccess) {
813 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "GetConfigurationDescriptorPtr: %s",
814 darwin_error_str(kresult));
818 new_config = configDesc->bConfigurationValue;
820 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "new configuration value is %d", new_config);
822 /* set the configuration */
823 kresult = darwin_set_configuration (dev_handle, new_config);
824 if (kresult != LIBUSB_SUCCESS) {
825 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "could not set configuration");
829 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
831 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "darwin_get_interface: %s", darwin_error_str(kresult));
832 return darwin_to_libusb (kresult);
837 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "interface not found");
838 return LIBUSB_ERROR_NOT_FOUND;
841 /* get an interface to the device's interface */
842 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
843 kIOCFPlugInInterfaceID, &plugInInterface, &score);
845 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
846 return darwin_to_libusb (kresult);
849 if (!plugInInterface) {
850 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "plugin interface not found");
851 return LIBUSB_ERROR_NOT_FOUND;
854 /* ignore release error */
855 (void)IOObjectRelease (usbInterface);
857 /* Do the actual claim */
858 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
859 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
860 (LPVOID)&cInterface->interface);
861 if (kresult || !cInterface->interface) {
862 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "QueryInterface: %s", darwin_error_str(kresult));
863 return darwin_to_libusb (kresult);
866 /* We no longer need the intermediate plug-in */
867 (*plugInInterface)->Release(plugInInterface);
869 /* claim the interface */
870 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
872 _usbi_log(HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "USBInterfaceOpen: %s", darwin_error_str(kresult));
873 return darwin_to_libusb (kresult);
876 /* update list of endpoints */
877 kresult = get_endpoints (dev_handle, iface);
879 /* this should not happen */
880 darwin_release_interface (dev_handle, iface);
881 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "could not build endpoint table");
885 cInterface->cfSource = NULL;
887 /* create async event source */
888 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
889 if (kresult != kIOReturnSuccess) {
890 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "could not create async event source");
892 /* can't continue without an async event source */
893 (void)darwin_release_interface (dev_handle, iface);
895 return darwin_to_libusb (kresult);
898 /* add the cfSource to the async thread's run loop */
899 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
901 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_INFO, "interface opened");
906 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
907 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
910 /* current interface */
911 struct __darwin_interface *cInterface = &priv->interfaces[iface];
913 /* Check to see if an interface is open */
914 if (!cInterface->interface)
915 return LIBUSB_SUCCESS;
917 /* clean up endpoint data */
918 cInterface->num_endpoints = 0;
920 /* delete the interface's async event source */
921 if (cInterface->cfSource) {
922 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
923 CFRelease (cInterface->cfSource);
926 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
928 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "USBInterfaceClose: %s", darwin_error_str(kresult));
930 kresult = (*(cInterface->interface))->Release(cInterface->interface);
931 if (kresult != kIOReturnSuccess)
932 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "Release: %s", darwin_error_str(kresult));
934 cInterface->interface = IO_OBJECT_NULL;
936 return darwin_to_libusb (kresult);
939 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
940 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
943 /* current interface */
944 struct __darwin_interface *cInterface = &priv->interfaces[iface];
946 if (!cInterface->interface)
947 return LIBUSB_ERROR_NO_DEVICE;
949 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
950 if (kresult != kIOReturnSuccess)
951 darwin_reset_device (dev_handle);
953 return darwin_to_libusb (kresult);
956 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
957 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
959 /* current interface */
960 struct __darwin_interface *cInterface;
961 uint8_t pipeRef, iface;
964 /* determine the interface/endpoint to use */
965 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
966 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
968 return LIBUSB_ERROR_NOT_FOUND;
971 cInterface = &priv->interfaces[iface];
973 #if (InterfaceVersion < 190)
974 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
976 /* newer versions of darwin support clearing additional bits on the device's endpoint */
977 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
980 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "ClearPipeStall: %s", darwin_error_str (kresult));
982 return darwin_to_libusb (kresult);
985 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
986 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
989 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
991 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "ResetDevice: %s", darwin_error_str (kresult));
993 return darwin_to_libusb (kresult);
996 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
997 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
998 io_service_t usbInterface;
1002 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1004 _usbi_log (HANDLE_CTX (dev_handle), LOG_LEVEL_ERROR, "darwin_get_interface: %s", darwin_error_str(kresult));
1006 return darwin_to_libusb (kresult);
1009 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1010 IOObjectRelease (usbInterface);
1022 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1023 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1024 return LIBUSB_ERROR_NOT_SUPPORTED;
1027 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1028 return LIBUSB_ERROR_NOT_SUPPORTED;
1031 static void darwin_destroy_device(struct libusb_device *dev) {
1034 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1035 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1036 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1039 uint8_t is_read; /* 0 = we're reading, 1 = we're writing */
1040 uint8_t transferType;
1041 /* None of the values below are used in libusb for bulk transfers */
1042 uint8_t direction, number, interval, pipeRef, iface;
1043 uint16_t maxPacketSize;
1045 struct __darwin_interface *cInterface;
1047 /* are we reading or writing? */
1048 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1050 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1051 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
1053 return LIBUSB_ERROR_NOT_FOUND;
1056 cInterface = &priv->interfaces[iface];
1058 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1059 &transferType, &maxPacketSize, &interval);
1061 /* submit the request */
1062 /* timeouts are unavailable on interrupt endpoints */
1063 if (transferType == kUSBInterrupt) {
1065 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1066 transfer->length, darwin_async_io_callback, itransfer);
1068 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1069 transfer->length, darwin_async_io_callback, itransfer);
1072 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1073 transfer->length, transfer->timeout, transfer->timeout,
1074 darwin_async_io_callback, (void *)itransfer);
1076 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1077 transfer->length, transfer->timeout, transfer->timeout,
1078 darwin_async_io_callback, (void *)itransfer);
1082 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "bulk transfer failed (dir = %s): %s", is_read ? "In" : "Out",
1083 darwin_error_str(ret));
1085 return darwin_to_libusb (ret);
1088 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1089 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1090 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1091 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1094 uint8_t is_read; /* 0 = we're writing, 1 = we're reading */
1095 uint8_t pipeRef, iface;
1097 AbsoluteTime atTime;
1100 struct __darwin_interface *cInterface;
1102 /* are we reading or writing? */
1103 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1105 /* construct an array of IOUSBIsocFrames */
1106 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1107 if (!tpriv->isoc_framelist)
1108 return LIBUSB_ERROR_NO_MEM;
1110 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1111 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1112 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1114 /* determine the interface/endpoint to use */
1115 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1116 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
1118 return LIBUSB_ERROR_NOT_FOUND;
1121 cInterface = &priv->interfaces[iface];
1123 /* Last but not least we need the bus frame number */
1124 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1126 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "failed to get bus frame number: %d", kresult);
1127 free(tpriv->isoc_framelist);
1128 tpriv->isoc_framelist = NULL;
1130 return darwin_to_libusb (kresult);
1133 /* schedule for a frame a little in the future */
1136 /* submit the request */
1138 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1139 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1142 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1143 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1146 if (kresult != kIOReturnSuccess) {
1147 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "isochronous transfer failed (dir: %s): %s", is_read ? "In" : "Out",
1148 darwin_error_str(kresult));
1149 free (tpriv->isoc_framelist);
1150 tpriv->isoc_framelist = NULL;
1153 return darwin_to_libusb (kresult);
1156 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1157 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1158 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1159 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1160 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1164 bzero(&tpriv->req, sizeof(tpriv->req));
1166 /* IOUSBDeviceInterface expects the request in cpu endianess */
1167 tpriv->req.bmRequestType = setup->bmRequestType;
1168 tpriv->req.bRequest = setup->bRequest;
1169 /* these values should already be in bus order */
1170 tpriv->req.wValue = setup->wValue;
1171 tpriv->req.wIndex = setup->wIndex;
1172 tpriv->req.wLength = setup->wLength;
1173 /* data is stored after the libusb control block */
1174 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1175 tpriv->req.completionTimeout = transfer->timeout;
1176 tpriv->req.noDataTimeout = transfer->timeout;
1178 /* all transfers in libusb-1.0 are async */
1179 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1181 if (kresult != kIOReturnSuccess)
1182 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "control request failed: %s", darwin_error_str(kresult));
1184 return darwin_to_libusb (kresult);
1187 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1188 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1190 switch (transfer->type) {
1191 case LIBUSB_TRANSFER_TYPE_CONTROL:
1192 return submit_control_transfer(itransfer);
1193 case LIBUSB_TRANSFER_TYPE_BULK:
1194 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1195 return submit_bulk_transfer(itransfer);
1196 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1197 return submit_iso_transfer(itransfer);
1199 _usbi_log (TRANSFER_CTX(transfer), LOG_LEVEL_ERROR, "unknown endpoint type %d", transfer->type);
1200 return LIBUSB_ERROR_INVALID_PARAM;
1204 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1205 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1206 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1209 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "WARNING: aborting all transactions control pipe");
1211 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1213 return darwin_to_libusb (kresult);
1216 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1217 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1218 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1219 struct __darwin_interface *cInterface;
1220 uint8_t pipeRef, iface;
1223 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1224 _usbi_log (TRANSFER_CTX (transfer), LOG_LEVEL_ERROR, "endpoint not found on any open interface");
1226 return LIBUSB_ERROR_NOT_FOUND;
1229 cInterface = &priv->interfaces[iface];
1231 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "WARNING: aborting all transactions on interface %d pipe %d", iface, pipeRef);
1233 /* abort transactions */
1234 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1236 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "calling clear pipe stall to clear the data toggle bit");
1238 /* clear the data toggle bit */
1239 #if (InterfaceVersion < 190)
1240 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1242 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1243 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1246 return darwin_to_libusb (kresult);
1249 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1250 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1252 switch (transfer->type) {
1253 case LIBUSB_TRANSFER_TYPE_CONTROL:
1254 return cancel_control_transfer(itransfer);
1255 case LIBUSB_TRANSFER_TYPE_BULK:
1256 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1257 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1258 return darwin_abort_transfers (itransfer);
1260 _usbi_log (TRANSFER_CTX(transfer), LOG_LEVEL_ERROR, "unknown endpoint type %d", transfer->type);
1261 return LIBUSB_ERROR_INVALID_PARAM;
1265 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1266 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1267 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1269 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1270 free (tpriv->isoc_framelist);
1271 tpriv->isoc_framelist = NULL;
1275 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1276 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1277 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1278 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1281 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "an async io operation has completed");
1283 /* send a completion message to the device's file descriptor */
1284 message = MESSAGE_ASYNC_IO_COMPLETE;
1285 write (priv->fds[1], &message, sizeof (message));
1286 write (priv->fds[1], &itransfer, sizeof (itransfer));
1287 write (priv->fds[1], &result, sizeof (IOReturn));
1288 write (priv->fds[1], &arg0, sizeof (UInt32));
1291 static void darwin_bulk_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1292 enum libusb_transfer_status status;
1294 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "handling bulk completion with status %d", result);
1297 case kIOReturnSuccess:
1298 status = LIBUSB_TRANSFER_COMPLETED;
1299 itransfer->transferred += io_size;
1301 case kIOReturnAborted:
1302 usbi_handle_transfer_cancellation(itransfer);
1304 case kIOUSBPipeStalled:
1305 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_WARNING, "bulk error. pipe is stalled");
1306 status = LIBUSB_TRANSFER_STALL;
1309 case kIOReturnOverrun:
1310 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_ERROR, "bulk error. data overrun", darwin_error_str (result));
1311 status = LIBUSB_TRANSFER_OVERFLOW;
1315 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_ERROR, "bulk error = %s (value = 0x%08x)", darwin_error_str (result), result);
1316 status = LIBUSB_TRANSFER_ERROR;
1319 usbi_handle_transfer_completion(itransfer, status);
1322 static void darwin_isoc_callback (struct usbi_transfer *itransfer, kern_return_t result) {
1323 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1324 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1327 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "handling isoc completion with status %d", result);
1329 if (result == kIOReturnSuccess && tpriv->isoc_framelist) {
1330 /* copy isochronous results back */
1332 for (i = 0; i < transfer->num_iso_packets ; i++) {
1333 struct libusb_iso_packet_descriptor *lib_desc = transfer->iso_packet_desc;
1334 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1335 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1340 case kIOReturnSuccess:
1341 status = LIBUSB_TRANSFER_COMPLETED;
1343 case kIOReturnAborted:
1344 usbi_handle_transfer_cancellation(itransfer);
1346 case kIOUSBPipeStalled:
1347 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_WARNING, "unsupported control request");
1348 status = LIBUSB_TRANSFER_STALL;
1351 case kIOReturnOverrun:
1352 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_ERROR, "bulk error. data overrun", darwin_error_str (result));
1353 status = LIBUSB_TRANSFER_OVERFLOW;
1357 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_ERROR, "control error = %s", darwin_error_str (result));
1358 status = LIBUSB_TRANSFER_ERROR;
1361 usbi_handle_transfer_completion(itransfer, status);
1364 static void darwin_control_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1367 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_INFO, "handling control completion with status %d", result);
1370 case kIOReturnSuccess:
1371 status = LIBUSB_TRANSFER_COMPLETED;
1372 itransfer->transferred += io_size;
1374 case kIOReturnAborted:
1375 usbi_handle_transfer_cancellation(itransfer);
1377 case kIOUSBPipeStalled:
1378 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_WARNING, "unsupported control request");
1379 status = LIBUSB_TRANSFER_STALL;
1383 _usbi_log (ITRANSFER_CTX (itransfer), LOG_LEVEL_ERROR, "control error = %s", darwin_error_str (result));
1384 status = LIBUSB_TRANSFER_ERROR;
1387 usbi_handle_transfer_completion(itransfer, status);
1390 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1391 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1393 switch (transfer->type) {
1394 case LIBUSB_TRANSFER_TYPE_CONTROL:
1395 darwin_control_callback (itransfer, result, io_size);
1397 case LIBUSB_TRANSFER_TYPE_BULK:
1398 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1399 darwin_bulk_callback (itransfer, result, io_size);
1401 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1402 darwin_isoc_callback (itransfer, result);
1405 _usbi_log (TRANSFER_CTX(transfer), LOG_LEVEL_ERROR, "unknown endpoint type %d", transfer->type);
1409 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, nfds_t nfds, int num_ready) {
1410 struct usbi_transfer *itransfer;
1416 pthread_mutex_lock(&ctx->open_devs_lock);
1417 for (i = 0; i < nfds && num_ready > 0; i++) {
1418 struct pollfd *pollfd = &fds[i];
1419 struct libusb_device_handle *handle;
1420 struct darwin_device_handle_priv *hpriv = NULL;
1422 _usbi_log (ctx, LOG_LEVEL_INFO, "checking fd %i with revents = %x", fds[i], pollfd->revents);
1424 if (!pollfd->revents)
1428 list_for_each_entry(handle, &ctx->open_devs, list) {
1429 hpriv = (struct darwin_device_handle_priv *)handle->os_priv;
1430 if (hpriv->fds[0] == pollfd->fd)
1434 if (!(pollfd->revents & POLLERR)) {
1435 ret = read (hpriv->fds[0], &message, sizeof (message));
1436 if (ret < sizeof (message))
1439 /* could not poll the device-- response is to delete the device (this seems a little heavy-handed) */
1440 message = MESSAGE_DEVICE_GONE;
1443 case MESSAGE_DEVICE_GONE:
1444 /* remove the device's async port from the runloop */
1445 if (hpriv->cfSource) {
1446 if (libusb_darwin_acfl)
1447 CFRunLoopRemoveSource (libusb_darwin_acfl, hpriv->cfSource, kCFRunLoopDefaultMode);
1448 CFRelease (hpriv->cfSource);
1449 hpriv->cfSource = NULL;
1452 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
1453 usbi_handle_disconnect(handle);
1455 /* done with this device */
1457 case MESSAGE_ASYNC_IO_COMPLETE:
1458 read (hpriv->fds[0], &itransfer, sizeof (itransfer));
1459 read (hpriv->fds[0], &kresult, sizeof (IOReturn));
1460 read (hpriv->fds[0], &io_size, sizeof (UInt32));
1462 darwin_handle_callback (itransfer, kresult, io_size);
1465 _usbi_log (ctx, LOG_LEVEL_ERROR, "unknown message received from device pipe");
1469 pthread_mutex_unlock(&ctx->open_devs_lock);
1474 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1475 mach_timespec_t sys_time;
1476 clock_serv_t clock_ref;
1479 case USBI_CLOCK_REALTIME:
1480 /* CLOCK_REALTIME represents time since the epoch */
1481 host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &clock_ref);
1483 case USBI_CLOCK_MONOTONIC:
1484 /* use system boot time as reference for the monotonic clock */
1485 host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &clock_ref);
1488 return LIBUSB_ERROR_INVALID_PARAM;
1491 clock_get_time (clock_ref, &sys_time);
1493 tp->tv_sec = sys_time.tv_sec;
1494 tp->tv_nsec = sys_time.tv_nsec;
1499 const struct usbi_os_backend darwin_backend = {
1501 .init = darwin_init,
1502 .exit = darwin_exit,
1503 .get_device_list = darwin_get_device_list,
1504 .get_device_descriptor = darwin_get_device_descriptor,
1505 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1506 .get_config_descriptor = darwin_get_config_descriptor,
1508 .open = darwin_open,
1509 .close = darwin_close,
1510 .get_configuration = darwin_get_configuration,
1511 .set_configuration = darwin_set_configuration,
1512 .claim_interface = darwin_claim_interface,
1513 .release_interface = darwin_release_interface,
1515 .set_interface_altsetting = darwin_set_interface_altsetting,
1516 .clear_halt = darwin_clear_halt,
1517 .reset_device = darwin_reset_device,
1519 .kernel_driver_active = darwin_kernel_driver_active,
1520 .detach_kernel_driver = darwin_detach_kernel_driver,
1521 .attach_kernel_driver = darwin_attach_kernel_driver,
1523 .destroy_device = darwin_destroy_device,
1525 .submit_transfer = darwin_submit_transfer,
1526 .cancel_transfer = darwin_cancel_transfer,
1527 .clear_transfer_priv = darwin_clear_transfer_priv,
1529 .handle_events = op_handle_events,
1531 .clock_gettime = darwin_clock_gettime,
1533 .device_priv_size = sizeof(struct darwin_device_priv),
1534 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1535 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1536 .add_iso_packet_size = 0,