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_async_io_callback (void *refcon, IOReturn result, void *arg0);
58 static const char *darwin_error_str (int result) {
60 case kIOReturnSuccess:
62 case kIOReturnNotOpen:
63 return "device not opened for exclusive access";
64 case kIOReturnNoDevice:
65 return "no connection to an IOService";
66 case kIOUSBNoAsyncPortErr:
67 return "no async port has been opened for interface";
68 case kIOReturnExclusiveAccess:
69 return "another process has device opened for exclusive access";
70 case kIOUSBPipeStalled:
71 return "pipe is stalled";
73 return "could not establish a connection to the Darwin kernel";
74 case kIOUSBTransactionTimeout:
75 return "transaction timed out";
76 case kIOReturnBadArgument:
77 return "invalid argument";
78 case kIOReturnAborted:
79 return "transaction aborted";
80 case kIOReturnNotResponding:
81 return "device not responding";
82 case kIOReturnOverrun:
83 return "data overrun";
84 case kIOReturnCannotWire:
85 return "physical memory can not be wired down";
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_info (HANDLE_CTX(dev_handle), "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_info (HANDLE_CTX(dev_handle), "pipe %d on interface %d matches", *pipep, *ifcp);
141 /* No pipe found with the correct endpoint address */
142 usbi_warn (HANDLE_CTX(dev_handle), "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_info (ctx, "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;
235 /* the device may have been opened several times. write to each handle's event descriptor */
236 if (dpriv->location == location && handle->os_priv) {
237 priv = (struct darwin_device_handle_priv *)handle->os_priv;
239 message = MESSAGE_DEVICE_GONE;
240 write (priv->fds[1], &message, sizeof (message));
244 pthread_mutex_unlock(&ctx->open_devs_lock);
248 static void darwin_clear_iterator (io_iterator_t iter) {
251 while ((device = IOIteratorNext (iter)) != 0)
252 IOObjectRelease (device);
255 static void *event_thread_main (void *arg0) {
257 struct libusb_context *ctx = (struct libusb_context *)arg0;
259 /* hotplug (device removal) source */
260 CFRunLoopSourceRef libusb_notification_cfsource;
261 io_notification_port_t libusb_notification_port;
262 io_iterator_t libusb_rem_device_iterator;
264 usbi_info (ctx, "creating hotplug event source");
266 CFRetain (CFRunLoopGetCurrent ());
268 /* add the notification port to the run loop */
269 libusb_notification_port = IONotificationPortCreate (libusb_darwin_mp);
270 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
271 CFRunLoopAddSource(CFRunLoopGetCurrent (), libusb_notification_cfsource, kCFRunLoopDefaultMode);
273 /* create notifications for removed devices */
274 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
275 IOServiceMatching(kIOUSBDeviceClassName),
276 (IOServiceMatchingCallback)darwin_devices_detached,
277 (void *)ctx, &libusb_rem_device_iterator);
279 if (kresult != kIOReturnSuccess) {
280 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
282 pthread_exit ((void *)kresult);
286 darwin_clear_iterator (libusb_rem_device_iterator);
288 /* let the main thread know about the async runloop */
289 libusb_darwin_acfl = CFRunLoopGetCurrent ();
291 usbi_info (ctx, "libopenusb/darwin.c event_thread_main: thread ready to receive events");
293 /* run the runloop */
296 usbi_info (ctx, "libopenusb/darwin.c event_thread_main: thread exiting");
298 /* delete notification port */
299 CFRunLoopSourceInvalidate (libusb_notification_cfsource);
300 IONotificationPortDestroy (libusb_notification_port);
302 CFRelease (CFRunLoopGetCurrent ());
304 libusb_darwin_acfl = NULL;
309 static int darwin_init(struct libusb_context *ctx) {
312 if (!(initCount++)) {
313 /* Create the master port for talking to IOKit */
314 if (!libusb_darwin_mp) {
315 kresult = IOMasterPort (MACH_PORT_NULL, &libusb_darwin_mp);
317 if (kresult != kIOReturnSuccess || !libusb_darwin_mp)
318 return darwin_to_libusb (kresult);
321 pthread_create (&libusb_darwin_at, NULL, event_thread_main, (void *)ctx);
323 while (!libusb_darwin_acfl)
330 static void darwin_exit (void) {
331 if (!(--initCount)) {
334 /* stop the async runloop */
335 CFRunLoopStop (libusb_darwin_acfl);
336 pthread_join (libusb_darwin_at, &ret);
338 if (libusb_darwin_mp)
339 mach_port_deallocate(mach_task_self(), libusb_darwin_mp);
341 libusb_darwin_mp = 0;
345 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
346 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
348 /* return cached copy */
349 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
356 static int get_configuration_index (struct libusb_device *dev, int config_value) {
357 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
359 IOUSBConfigurationDescriptorPtr desc;
362 /* is there a simpler way to determine the index? */
363 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
364 if (kresult != kIOReturnSuccess)
365 return darwin_to_libusb (kresult);
367 for (i = 0 ; i < numConfig ; i++) {
368 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
370 if (libusb_le16_to_cpu (desc->bConfigurationValue) == config_value)
374 /* configuration not found */
375 return LIBUSB_ERROR_OTHER;
378 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
379 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
384 kresult = (*(priv->device))->GetConfiguration (priv->device, &config_value);
385 if (kresult != kIOReturnSuccess)
386 return darwin_to_libusb (kresult);
388 config_index = get_configuration_index (dev, config_value);
389 if (config_index < 0)
392 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
395 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
396 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
397 IOUSBConfigurationDescriptorPtr desc;
399 usb_device_t **device = NULL;
402 return LIBUSB_ERROR_OTHER;
405 kresult = darwin_get_device (priv->location, &device);
406 if (kresult || !device) {
407 usbi_err (DEVICE_CTX (dev), "could not find device: %s", darwin_error_str (kresult));
409 return darwin_to_libusb (kresult);
412 /* don't have to open the device to get a config descriptor */
414 device = priv->device;
416 kresult = (*device)->GetConfigurationDescriptorPtr (device, config_index, &desc);
417 if (kresult == kIOReturnSuccess) {
418 /* copy descriptor */
419 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
420 len = libusb_le16_to_cpu(desc->wTotalLength);
422 memmove (buffer, desc, len);
424 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
429 (*device)->Release (device);
431 return darwin_to_libusb (kresult);
434 static int process_new_device (struct libusb_context *ctx, usb_device_t **device, UInt32 locationID, struct discovered_devs **_discdevs) {
435 struct darwin_device_priv *priv;
436 struct libusb_device *dev;
437 struct discovered_devs *discdevs;
438 UInt16 address, idVendor, idProduct;
439 UInt8 bDeviceClass, bDeviceSubClass;
441 int ret, need_unref = 0;
443 dev = usbi_get_device_by_session_id(ctx, locationID);
445 usbi_info (ctx, "allocating new device for location 0x%08x", locationID);
446 dev = usbi_alloc_device(ctx, locationID);
449 return LIBUSB_ERROR_NO_MEM;
451 priv = (struct darwin_device_priv *)dev->os_priv;
453 /* Set up request for device descriptor */
454 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
455 req.bRequest = kUSBRqGetDescriptor;
456 req.wValue = kUSBDeviceDesc << 8;
458 req.wLength = sizeof(IOUSBDeviceDescriptor);
459 req.pData = &(priv->dev_descriptor);
461 (*(device))->GetDeviceAddress (device, (USBDeviceAddress *)&address);
462 (*(device))->GetDeviceProduct (device, &idProduct);
463 (*(device))->GetDeviceVendor (device, &idVendor);
464 (*(device))->GetDeviceClass (device, &bDeviceClass);
465 (*(device))->GetDeviceSubClass (device, &bDeviceSubClass);
467 /**** retrieve device descriptors ****/
468 /* device must be open for DeviceRequest */
469 (*device)->USBDeviceOpen(device);
471 ret = (*(device))->DeviceRequest (device, &req);
472 if (ret != kIOReturnSuccess) {
473 int try_unsuspend = 1;
474 #if DeviceVersion >= 320
477 /* device may be suspended. unsuspend it and try again */
478 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
479 (void)(*device)->GetUSBDeviceInformation (device, &info);
481 try_unsuspend = info & (1 << kUSBInformationDeviceIsSuspendedBit);
485 /* resume the device */
486 (void)(*device)->USBDeviceSuspend (device, 0);
488 ret = (*(device))->DeviceRequest (device, &req);
490 /* resuspend the device */
491 (void)(*device)->USBDeviceSuspend (device, 1);
495 (*device)->USBDeviceClose (device);
497 if (ret != kIOReturnSuccess) {
498 usbi_warn (ctx, "could not retrieve device descriptor: %s. skipping device", darwin_error_str (ret));
500 libusb_unref_device(dev);
503 /**** end: retrieve device descriptors ****/
505 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
506 if (libusb_le16_to_cpu (priv->dev_descriptor.idProduct) != idProduct) {
507 /* not a valid device */
508 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
509 idProduct, libusb_le16_to_cpu (priv->dev_descriptor.idProduct));
510 libusb_unref_device(dev);
514 dev->bus_number = locationID >> 24;
515 dev->device_address = address;
517 /* save our location, we'll need this later */
518 priv->location = locationID;
519 snprintf(priv->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", address, idVendor, idProduct, bDeviceClass, bDeviceSubClass);
521 ret = usbi_sanitize_device(dev);
525 libusb_unref_device(dev);
529 priv = (struct darwin_device_priv *)dev->os_priv;
531 usbi_info (ctx, "using existing device for location 0x%08x", locationID);
534 /* append the device to the list of discovered devices */
535 discdevs = discovered_devs_append(*_discdevs, dev);
537 return LIBUSB_ERROR_NO_MEM;
539 *_discdevs = discdevs;
541 usbi_info (ctx, "found device with address %d at %s", dev->device_address, priv->sys_path);
544 libusb_unref_device(dev);
549 static int darwin_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs) {
550 io_iterator_t deviceIterator;
551 usb_device_t **device;
552 kern_return_t kresult;
555 if (!libusb_darwin_mp)
556 return LIBUSB_ERROR_INVALID_PARAM;
558 kresult = usb_setup_device_iterator (&deviceIterator);
559 if (kresult != kIOReturnSuccess)
560 return darwin_to_libusb (kresult);
562 while ((device = usb_get_next_device (deviceIterator, &location)) != NULL) {
563 (void) process_new_device (ctx, device, location, _discdevs);
565 (*(device))->Release(device);
568 IOObjectRelease(deviceIterator);
573 static int darwin_open (struct libusb_device_handle *dev_handle) {
574 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
575 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
576 usb_device_t **darwin_device;
579 if (0 == dpriv->open_count) {
580 kresult = darwin_get_device (dpriv->location, &darwin_device);
582 usbi_err (HANDLE_CTX (dev_handle), "could not find device: %s", darwin_error_str (kresult));
583 return darwin_to_libusb (kresult);
586 dpriv->device = darwin_device;
588 /* try to open the device */
589 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
591 if (kresult != kIOReturnSuccess) {
592 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
595 case kIOReturnExclusiveAccess:
596 /* it is possible to perform some actions on a device that is not open so do not return an error */
601 (*(dpriv->device))->Release (dpriv->device);
602 dpriv->device = NULL;
603 return darwin_to_libusb (kresult);
608 /* create async event source */
609 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
611 CFRetain (libusb_darwin_acfl);
613 /* add the cfSource to the aync run loop */
614 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
618 /* device opened successfully */
621 /* create a file descriptor for notifications */
624 /* set the pipe to be non-blocking */
625 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
627 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
629 usbi_info (HANDLE_CTX (dev_handle), "device open for access");
634 static void darwin_close (struct libusb_device_handle *dev_handle) {
635 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
636 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
640 if (dpriv->open_count == 0) {
641 /* something is probably very wrong if this is the case */
642 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!\n");
648 /* make sure all interfaces are released */
649 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
650 if (dev_handle->claimed_interfaces & (1 << i))
651 libusb_release_interface (dev_handle, i);
653 if (0 == dpriv->open_count) {
655 /* delete the device's async event source */
656 if (priv->cfSource) {
657 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
658 CFRelease (priv->cfSource);
661 /* close the device */
662 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
664 /* Log the fact that we had a problem closing the file, however failing a
665 * close isn't really an error, so return success anyway */
666 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
670 kresult = (*(dpriv->device))->Release(dpriv->device);
672 /* Log the fact that we had a problem closing the file, however failing a
673 * close isn't really an error, so return success anyway */
674 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
677 dpriv->device = NULL;
680 /* file descriptors are maintained per-instance */
681 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
682 close (priv->fds[1]);
683 close (priv->fds[0]);
685 priv->fds[0] = priv->fds[1] = -1;
688 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
689 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
693 kresult = (*(dpriv->device))->GetConfiguration (dpriv->device, &configNum);
694 if (kresult != kIOReturnSuccess)
695 return darwin_to_libusb (kresult);
697 *config = (int) configNum;
702 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
703 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
707 /* Setting configuration will invalidate the interface, so we need
708 to reclaim it. First, dispose of existing interfaces, if any. */
709 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
710 if (dev_handle->claimed_interfaces & (1 << i))
711 darwin_release_interface (dev_handle, i);
713 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
714 if (kresult != kIOReturnSuccess)
715 return darwin_to_libusb (kresult);
717 /* Reclaim any interfaces. */
718 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
719 if (dev_handle->claimed_interfaces & (1 << i))
720 darwin_claim_interface (dev_handle, i);
725 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
726 IOUSBFindInterfaceRequest request;
727 uint8_t current_interface;
728 kern_return_t kresult;
729 io_iterator_t interface_iterator;
731 *usbInterfacep = IO_OBJECT_NULL;
733 /* Setup the Interface Request */
734 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
735 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
736 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
737 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
739 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
743 for ( current_interface = 0 ; current_interface <= ifc ; current_interface++ )
744 *usbInterfacep = IOIteratorNext(interface_iterator);
746 /* done with the interface iterator */
747 IOObjectRelease(interface_iterator);
752 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
753 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
755 /* current interface */
756 struct __darwin_interface *cInterface = &priv->interfaces[iface];
758 kern_return_t kresult;
760 u_int8_t numep, direction, number;
761 u_int8_t dont_care1, dont_care3;
762 u_int16_t dont_care2;
765 usbi_info (HANDLE_CTX (dev_handle), "building table of endpoints.");
767 /* retrieve the total number of endpoints on this interface */
768 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
770 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
771 return darwin_to_libusb (kresult);
774 /* iterate through pipe references */
775 for (i = 1 ; i <= numep ; i++) {
776 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
777 &dont_care2, &dont_care3);
779 if (kresult != kIOReturnSuccess) {
780 usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
782 return darwin_to_libusb (kresult);
785 usbi_info (HANDLE_CTX (dev_handle), "interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
787 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
790 cInterface->num_endpoints = numep;
795 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
796 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
797 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
798 io_service_t usbInterface = IO_OBJECT_NULL;
800 IOCFPlugInInterface **plugInInterface = NULL;
804 /* current interface */
805 struct __darwin_interface *cInterface = &priv->interfaces[iface];
807 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
808 if (kresult != kIOReturnSuccess)
809 return darwin_to_libusb (kresult);
811 /* make sure we have an interface */
813 u_int8_t nConfig; /* Index of configuration to use */
814 IOUSBConfigurationDescriptorPtr configDesc; /* to describe which configuration to select */
815 /* Only a composite class device with no vendor-specific driver will
816 be configured. Otherwise, we need to do it ourselves, or there
817 will be no interfaces for the device. */
819 usbi_info (HANDLE_CTX (dev_handle), "no interface found; selecting configuration" );
821 kresult = (*(dpriv->device))->GetNumberOfConfigurations (dpriv->device, &nConfig);
822 if (kresult != kIOReturnSuccess) {
823 usbi_err (HANDLE_CTX (dev_handle), "GetNumberOfConfigurations: %s", darwin_error_str(kresult));
824 return darwin_to_libusb(kresult);
828 usbi_err (HANDLE_CTX (dev_handle), "GetNumberOfConfigurations: no configurations");
829 return LIBUSB_ERROR_OTHER;
832 usbi_info (HANDLE_CTX (dev_handle), "device has %d configuration%s. using the first",
833 (int)nConfig, (nConfig > 1 ? "s" : "") );
835 /* Always use the first configuration */
836 kresult = (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, 0, &configDesc);
837 if (kresult != kIOReturnSuccess) {
838 usbi_err (HANDLE_CTX (dev_handle), "GetConfigurationDescriptorPtr: %s",
839 darwin_error_str(kresult));
843 new_config = configDesc->bConfigurationValue;
845 usbi_info (HANDLE_CTX (dev_handle), "new configuration value is %d", new_config);
847 /* set the configuration */
848 kresult = darwin_set_configuration (dev_handle, new_config);
849 if (kresult != LIBUSB_SUCCESS) {
850 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
854 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
856 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
857 return darwin_to_libusb (kresult);
862 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
863 return LIBUSB_ERROR_NOT_FOUND;
866 /* get an interface to the device's interface */
867 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
868 kIOCFPlugInInterfaceID, &plugInInterface, &score);
870 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
871 return darwin_to_libusb (kresult);
874 if (!plugInInterface) {
875 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
876 return LIBUSB_ERROR_NOT_FOUND;
879 /* ignore release error */
880 (void)IOObjectRelease (usbInterface);
882 /* Do the actual claim */
883 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
884 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
885 (LPVOID)&cInterface->interface);
886 if (kresult || !cInterface->interface) {
887 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
888 return darwin_to_libusb (kresult);
891 /* We no longer need the intermediate plug-in */
892 (*plugInInterface)->Release(plugInInterface);
894 /* claim the interface */
895 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
897 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
898 return darwin_to_libusb (kresult);
901 /* update list of endpoints */
902 kresult = get_endpoints (dev_handle, iface);
904 /* this should not happen */
905 darwin_release_interface (dev_handle, iface);
906 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
910 cInterface->cfSource = NULL;
912 /* create async event source */
913 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
914 if (kresult != kIOReturnSuccess) {
915 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
917 /* can't continue without an async event source */
918 (void)darwin_release_interface (dev_handle, iface);
920 return darwin_to_libusb (kresult);
923 /* add the cfSource to the async thread's run loop */
924 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
926 usbi_info (HANDLE_CTX (dev_handle), "interface opened");
931 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
932 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
935 /* current interface */
936 struct __darwin_interface *cInterface = &priv->interfaces[iface];
938 /* Check to see if an interface is open */
939 if (!cInterface->interface)
940 return LIBUSB_SUCCESS;
942 /* clean up endpoint data */
943 cInterface->num_endpoints = 0;
945 /* delete the interface's async event source */
946 if (cInterface->cfSource) {
947 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
948 CFRelease (cInterface->cfSource);
951 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
953 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
955 kresult = (*(cInterface->interface))->Release(cInterface->interface);
956 if (kresult != kIOReturnSuccess)
957 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
959 cInterface->interface = IO_OBJECT_NULL;
961 return darwin_to_libusb (kresult);
964 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
965 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
968 /* current interface */
969 struct __darwin_interface *cInterface = &priv->interfaces[iface];
971 if (!cInterface->interface)
972 return LIBUSB_ERROR_NO_DEVICE;
974 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
975 if (kresult != kIOReturnSuccess)
976 darwin_reset_device (dev_handle);
978 /* update list of endpoints */
979 kresult = get_endpoints (dev_handle, iface);
981 /* this should not happen */
982 darwin_release_interface (dev_handle, iface);
983 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
987 return darwin_to_libusb (kresult);
990 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
991 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
993 /* current interface */
994 struct __darwin_interface *cInterface;
995 uint8_t pipeRef, iface;
998 /* determine the interface/endpoint to use */
999 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
1000 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1002 return LIBUSB_ERROR_NOT_FOUND;
1005 cInterface = &priv->interfaces[iface];
1007 #if (InterfaceVersion < 190)
1008 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1010 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1011 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1014 usbi_err (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1016 return darwin_to_libusb (kresult);
1019 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1020 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1023 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1025 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1027 return darwin_to_libusb (kresult);
1030 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1031 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1032 io_service_t usbInterface;
1036 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1038 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1040 return darwin_to_libusb (kresult);
1043 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1044 IOObjectRelease (usbInterface);
1056 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1057 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1058 return LIBUSB_ERROR_NOT_SUPPORTED;
1061 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1062 return LIBUSB_ERROR_NOT_SUPPORTED;
1065 static void darwin_destroy_device(struct libusb_device *dev) {
1068 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1069 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1070 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1073 uint8_t is_read; /* 0 = we're reading, 1 = we're writing */
1074 uint8_t transferType;
1075 /* None of the values below are used in libusb for bulk transfers */
1076 uint8_t direction, number, interval, pipeRef, iface;
1077 uint16_t maxPacketSize;
1079 struct __darwin_interface *cInterface;
1081 /* are we reading or writing? */
1082 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1084 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1085 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1087 return LIBUSB_ERROR_NOT_FOUND;
1090 cInterface = &priv->interfaces[iface];
1092 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1093 &transferType, &maxPacketSize, &interval);
1095 /* submit the request */
1096 /* timeouts are unavailable on interrupt endpoints */
1097 if (transferType == kUSBInterrupt) {
1099 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1100 transfer->length, darwin_async_io_callback, itransfer);
1102 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1103 transfer->length, darwin_async_io_callback, itransfer);
1106 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1107 transfer->length, transfer->timeout, transfer->timeout,
1108 darwin_async_io_callback, (void *)itransfer);
1110 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1111 transfer->length, transfer->timeout, transfer->timeout,
1112 darwin_async_io_callback, (void *)itransfer);
1116 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", is_read ? "In" : "Out",
1117 darwin_error_str(ret), ret);
1119 return darwin_to_libusb (ret);
1122 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1123 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1124 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1125 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1128 uint8_t is_read; /* 0 = we're writing, 1 = we're reading */
1129 uint8_t pipeRef, iface;
1131 AbsoluteTime atTime;
1134 struct __darwin_interface *cInterface;
1136 /* are we reading or writing? */
1137 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1139 /* construct an array of IOUSBIsocFrames */
1140 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1141 if (!tpriv->isoc_framelist)
1142 return LIBUSB_ERROR_NO_MEM;
1144 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1145 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1146 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1148 /* determine the interface/endpoint to use */
1149 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1150 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1152 return LIBUSB_ERROR_NOT_FOUND;
1155 cInterface = &priv->interfaces[iface];
1157 /* Last but not least we need the bus frame number */
1158 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1160 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1161 free(tpriv->isoc_framelist);
1162 tpriv->isoc_framelist = NULL;
1164 return darwin_to_libusb (kresult);
1167 /* schedule for a frame a little in the future */
1170 /* submit the request */
1172 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1173 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1176 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1177 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1180 if (kresult != kIOReturnSuccess) {
1181 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", is_read ? "In" : "Out",
1182 darwin_error_str(kresult));
1183 free (tpriv->isoc_framelist);
1184 tpriv->isoc_framelist = NULL;
1187 return darwin_to_libusb (kresult);
1190 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1191 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1192 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1193 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1194 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1198 bzero(&tpriv->req, sizeof(tpriv->req));
1200 /* IOUSBDeviceInterface expects the request in cpu endianess */
1201 tpriv->req.bmRequestType = setup->bmRequestType;
1202 tpriv->req.bRequest = setup->bRequest;
1203 /* these values should be in bus order from libusb_fill_control_setup */
1204 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1205 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1206 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1207 /* data is stored after the libusb control block */
1208 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1209 tpriv->req.completionTimeout = transfer->timeout;
1210 tpriv->req.noDataTimeout = transfer->timeout;
1212 /* all transfers in libusb-1.0 are async */
1213 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1215 if (kresult != kIOReturnSuccess)
1216 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1218 return darwin_to_libusb (kresult);
1221 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1222 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1224 switch (transfer->type) {
1225 case LIBUSB_TRANSFER_TYPE_CONTROL:
1226 return submit_control_transfer(itransfer);
1227 case LIBUSB_TRANSFER_TYPE_BULK:
1228 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1229 return submit_bulk_transfer(itransfer);
1230 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1231 return submit_iso_transfer(itransfer);
1233 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1234 return LIBUSB_ERROR_INVALID_PARAM;
1238 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1239 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1240 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1243 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions control pipe");
1245 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1247 return darwin_to_libusb (kresult);
1250 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1251 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1252 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1253 struct __darwin_interface *cInterface;
1254 uint8_t pipeRef, iface;
1257 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1258 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1260 return LIBUSB_ERROR_NOT_FOUND;
1263 cInterface = &priv->interfaces[iface];
1265 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions on interface %d pipe %d", iface, pipeRef);
1267 /* abort transactions */
1268 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1270 usbi_info (ITRANSFER_CTX (itransfer), "calling clear pipe stall to clear the data toggle bit");
1272 /* clear the data toggle bit */
1273 #if (InterfaceVersion < 190)
1274 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1276 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1277 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1280 return darwin_to_libusb (kresult);
1283 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1284 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1286 switch (transfer->type) {
1287 case LIBUSB_TRANSFER_TYPE_CONTROL:
1288 return cancel_control_transfer(itransfer);
1289 case LIBUSB_TRANSFER_TYPE_BULK:
1290 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1291 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1292 return darwin_abort_transfers (itransfer);
1294 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1295 return LIBUSB_ERROR_INVALID_PARAM;
1299 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1300 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1301 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1303 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1304 free (tpriv->isoc_framelist);
1305 tpriv->isoc_framelist = NULL;
1309 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1310 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1311 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1312 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1315 usbi_info (ITRANSFER_CTX (itransfer), "an async io operation has completed");
1317 /* send a completion message to the device's file descriptor */
1318 message = MESSAGE_ASYNC_IO_COMPLETE;
1319 write (priv->fds[1], &message, sizeof (message));
1320 write (priv->fds[1], &itransfer, sizeof (itransfer));
1321 write (priv->fds[1], &result, sizeof (IOReturn));
1322 write (priv->fds[1], &arg0, sizeof (UInt32));
1325 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1327 case kIOReturnSuccess:
1328 return LIBUSB_TRANSFER_COMPLETED;
1329 case kIOReturnAborted:
1330 return LIBUSB_TRANSFER_CANCELLED;
1331 case kIOUSBPipeStalled:
1332 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: pipe is stalled");
1333 return LIBUSB_TRANSFER_STALL;
1334 case kIOReturnOverrun:
1335 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: data overrun", darwin_error_str (result));
1336 return LIBUSB_TRANSFER_OVERFLOW;
1337 case kIOUSBTransactionTimeout:
1338 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1339 return LIBUSB_TRANSFER_TIMED_OUT;
1341 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1342 return LIBUSB_TRANSFER_ERROR;
1346 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1347 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1348 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1349 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1350 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1351 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1352 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1355 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1356 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1360 usbi_info (ITRANSFER_CTX (itransfer), "handling %s completion with kernel status %d",
1361 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", result);
1363 if (kIOReturnSuccess == result) {
1364 if (isIsoc && tpriv->isoc_framelist) {
1365 /* copy isochronous results back */
1367 for (i = 0; i < transfer->num_iso_packets ; i++) {
1368 struct libusb_iso_packet_descriptor *lib_desc = transfer->iso_packet_desc;
1369 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1370 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1373 itransfer->transferred += io_size;
1376 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1377 usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, result));
1380 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, nfds_t nfds, int num_ready) {
1381 struct usbi_transfer *itransfer;
1387 pthread_mutex_lock(&ctx->open_devs_lock);
1388 for (i = 0; i < nfds && num_ready > 0; i++) {
1389 struct pollfd *pollfd = &fds[i];
1390 struct libusb_device_handle *handle;
1391 struct darwin_device_handle_priv *hpriv = NULL;
1393 usbi_info (ctx, "checking fd %i with revents = %x", fds[i], pollfd->revents);
1395 if (!pollfd->revents)
1399 list_for_each_entry(handle, &ctx->open_devs, list) {
1400 hpriv = (struct darwin_device_handle_priv *)handle->os_priv;
1401 if (hpriv->fds[0] == pollfd->fd)
1405 if (!(pollfd->revents & POLLERR)) {
1406 ret = read (hpriv->fds[0], &message, sizeof (message));
1407 if (ret < sizeof (message))
1410 /* could not poll the device-- response is to delete the device (this seems a little heavy-handed) */
1411 message = MESSAGE_DEVICE_GONE;
1414 case MESSAGE_DEVICE_GONE:
1415 /* remove the device's async port from the runloop */
1416 if (hpriv->cfSource) {
1417 if (libusb_darwin_acfl)
1418 CFRunLoopRemoveSource (libusb_darwin_acfl, hpriv->cfSource, kCFRunLoopDefaultMode);
1419 CFRelease (hpriv->cfSource);
1420 hpriv->cfSource = NULL;
1423 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
1424 usbi_handle_disconnect(handle);
1426 /* done with this device */
1428 case MESSAGE_ASYNC_IO_COMPLETE:
1429 read (hpriv->fds[0], &itransfer, sizeof (itransfer));
1430 read (hpriv->fds[0], &kresult, sizeof (IOReturn));
1431 read (hpriv->fds[0], &io_size, sizeof (UInt32));
1433 darwin_handle_callback (itransfer, kresult, io_size);
1436 usbi_err (ctx, "unknown message received from device pipe");
1440 pthread_mutex_unlock(&ctx->open_devs_lock);
1445 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1446 mach_timespec_t sys_time;
1447 clock_serv_t clock_ref;
1450 case USBI_CLOCK_REALTIME:
1451 /* CLOCK_REALTIME represents time since the epoch */
1452 host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &clock_ref);
1454 case USBI_CLOCK_MONOTONIC:
1455 /* use system boot time as reference for the monotonic clock */
1456 host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &clock_ref);
1459 return LIBUSB_ERROR_INVALID_PARAM;
1462 clock_get_time (clock_ref, &sys_time);
1464 tp->tv_sec = sys_time.tv_sec;
1465 tp->tv_nsec = sys_time.tv_nsec;
1470 const struct usbi_os_backend darwin_backend = {
1472 .init = darwin_init,
1473 .exit = darwin_exit,
1474 .get_device_list = darwin_get_device_list,
1475 .get_device_descriptor = darwin_get_device_descriptor,
1476 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1477 .get_config_descriptor = darwin_get_config_descriptor,
1479 .open = darwin_open,
1480 .close = darwin_close,
1481 .get_configuration = darwin_get_configuration,
1482 .set_configuration = darwin_set_configuration,
1483 .claim_interface = darwin_claim_interface,
1484 .release_interface = darwin_release_interface,
1486 .set_interface_altsetting = darwin_set_interface_altsetting,
1487 .clear_halt = darwin_clear_halt,
1488 .reset_device = darwin_reset_device,
1490 .kernel_driver_active = darwin_kernel_driver_active,
1491 .detach_kernel_driver = darwin_detach_kernel_driver,
1492 .attach_kernel_driver = darwin_attach_kernel_driver,
1494 .destroy_device = darwin_destroy_device,
1496 .submit_transfer = darwin_submit_transfer,
1497 .cancel_transfer = darwin_cancel_transfer,
1498 .clear_transfer_priv = darwin_clear_transfer_priv,
1500 .handle_events = op_handle_events,
1502 .clock_gettime = darwin_clock_gettime,
1504 .device_priv_size = sizeof(struct darwin_device_priv),
1505 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1506 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1507 .add_iso_packet_size = 0,