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))
162 while ((usbDevice = IOIteratorNext(deviceIterator))) {
163 result = IOCreatePlugInInterfaceForService(usbDevice, kIOUSBDeviceUserClientTypeID,
164 kIOCFPlugInInterfaceID, &plugInInterface,
166 if (kIOReturnSuccess == result && plugInInterface)
169 usbi_dbg ("libusb/darwin.c usb_get_next_device: could not set up plugin for service: %s\n", darwin_error_str (result));
175 (void)IOObjectRelease(usbDevice);
176 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
179 (*plugInInterface)->Stop(plugInInterface);
180 IODestroyPlugInInterface (plugInInterface);
182 (*(device))->GetLocationID(device, locationp);
187 static kern_return_t darwin_get_device (uint32_t dev_location, usb_device_t ***darwin_device) {
188 kern_return_t kresult;
190 io_iterator_t deviceIterator;
192 kresult = usb_setup_device_iterator (&deviceIterator);
196 /* This port of libusb uses locations to keep track of devices. */
197 while ((*darwin_device = usb_get_next_device (deviceIterator, &location)) != NULL) {
198 if (location == dev_location)
201 (**darwin_device)->Release(*darwin_device);
204 IOObjectRelease (deviceIterator);
206 if (!(*darwin_device))
207 return kIOReturnNoDevice;
209 return kIOReturnSuccess;
214 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
215 struct libusb_context *ctx = (struct libusb_context *)ptr;
216 struct libusb_device_handle *handle;
217 struct darwin_device_priv *dpriv;
218 struct darwin_device_handle_priv *priv;
222 CFTypeRef locationCF;
225 usbi_info (ctx, "a device has been detached");
227 while ((device = IOIteratorNext (rem_devices)) != 0) {
228 /* get the location from the i/o registry */
229 locationCF = IORegistryEntryCreateCFProperty (device, CFSTR(kUSBDevicePropertyLocationID), kCFAllocatorDefault, 0);
231 CFNumberGetValue(locationCF, kCFNumberLongType, &location);
232 CFRelease (locationCF);
233 IOObjectRelease (device);
235 usbi_mutex_lock(&ctx->open_devs_lock);
236 list_for_each_entry(handle, &ctx->open_devs, list) {
237 dpriv = (struct darwin_device_priv *)handle->dev->os_priv;
239 /* the device may have been opened several times. write to each handle's event descriptor */
240 if (dpriv->location == location && handle->os_priv) {
241 priv = (struct darwin_device_handle_priv *)handle->os_priv;
243 message = MESSAGE_DEVICE_GONE;
244 write (priv->fds[1], &message, sizeof (message));
248 usbi_mutex_unlock(&ctx->open_devs_lock);
252 static void darwin_clear_iterator (io_iterator_t iter) {
255 while ((device = IOIteratorNext (iter)) != 0)
256 IOObjectRelease (device);
259 static void *event_thread_main (void *arg0) {
261 struct libusb_context *ctx = (struct libusb_context *)arg0;
263 /* hotplug (device removal) source */
264 CFRunLoopSourceRef libusb_notification_cfsource;
265 io_notification_port_t libusb_notification_port;
266 io_iterator_t libusb_rem_device_iterator;
268 usbi_info (ctx, "creating hotplug event source");
270 CFRetain (CFRunLoopGetCurrent ());
272 /* add the notification port to the run loop */
273 libusb_notification_port = IONotificationPortCreate (libusb_darwin_mp);
274 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
275 CFRunLoopAddSource(CFRunLoopGetCurrent (), libusb_notification_cfsource, kCFRunLoopDefaultMode);
277 /* create notifications for removed devices */
278 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
279 IOServiceMatching(kIOUSBDeviceClassName),
280 (IOServiceMatchingCallback)darwin_devices_detached,
281 (void *)ctx, &libusb_rem_device_iterator);
283 if (kresult != kIOReturnSuccess) {
284 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
286 pthread_exit ((void *)kresult);
290 darwin_clear_iterator (libusb_rem_device_iterator);
292 /* let the main thread know about the async runloop */
293 libusb_darwin_acfl = CFRunLoopGetCurrent ();
295 usbi_info (ctx, "libopenusb/darwin.c event_thread_main: thread ready to receive events");
297 /* run the runloop */
300 usbi_info (ctx, "libopenusb/darwin.c event_thread_main: thread exiting");
302 /* delete notification port */
303 CFRunLoopSourceInvalidate (libusb_notification_cfsource);
304 IONotificationPortDestroy (libusb_notification_port);
306 CFRelease (CFRunLoopGetCurrent ());
308 libusb_darwin_acfl = NULL;
313 static int darwin_init(struct libusb_context *ctx) {
316 if (!(initCount++)) {
317 /* Create the master port for talking to IOKit */
318 if (!libusb_darwin_mp) {
319 kresult = IOMasterPort (MACH_PORT_NULL, &libusb_darwin_mp);
321 if (kresult != kIOReturnSuccess || !libusb_darwin_mp)
322 return darwin_to_libusb (kresult);
325 pthread_create (&libusb_darwin_at, NULL, event_thread_main, (void *)ctx);
327 while (!libusb_darwin_acfl)
334 static void darwin_exit (void) {
335 if (!(--initCount)) {
338 /* stop the async runloop */
339 CFRunLoopStop (libusb_darwin_acfl);
340 pthread_join (libusb_darwin_at, &ret);
342 if (libusb_darwin_mp)
343 mach_port_deallocate(mach_task_self(), libusb_darwin_mp);
345 libusb_darwin_mp = 0;
349 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
350 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
352 /* return cached copy */
353 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
360 static int get_configuration_index (struct libusb_device *dev, int config_value) {
361 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
363 IOUSBConfigurationDescriptorPtr desc;
366 /* is there a simpler way to determine the index? */
367 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
368 if (kresult != kIOReturnSuccess)
369 return darwin_to_libusb (kresult);
371 for (i = 0 ; i < numConfig ; i++) {
372 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
374 if (libusb_le16_to_cpu (desc->bConfigurationValue) == config_value)
378 /* configuration not found */
379 return LIBUSB_ERROR_OTHER;
382 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
383 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
388 kresult = (*(priv->device))->GetConfiguration (priv->device, &config_value);
389 if (kresult != kIOReturnSuccess)
390 return darwin_to_libusb (kresult);
392 config_index = get_configuration_index (dev, config_value);
393 if (config_index < 0)
396 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
399 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
400 struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
401 IOUSBConfigurationDescriptorPtr desc;
403 usb_device_t **device = NULL;
406 return LIBUSB_ERROR_OTHER;
409 kresult = darwin_get_device (priv->location, &device);
410 if (kresult || !device) {
411 usbi_err (DEVICE_CTX (dev), "could not find device: %s", darwin_error_str (kresult));
413 return darwin_to_libusb (kresult);
416 /* don't have to open the device to get a config descriptor */
418 device = priv->device;
420 kresult = (*device)->GetConfigurationDescriptorPtr (device, config_index, &desc);
421 if (kresult == kIOReturnSuccess) {
422 /* copy descriptor */
423 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
424 len = libusb_le16_to_cpu(desc->wTotalLength);
426 memmove (buffer, desc, len);
428 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
433 (*device)->Release (device);
435 return darwin_to_libusb (kresult);
438 static int process_new_device (struct libusb_context *ctx, usb_device_t **device, UInt32 locationID, struct discovered_devs **_discdevs) {
439 struct darwin_device_priv *priv;
440 struct libusb_device *dev;
441 struct discovered_devs *discdevs;
442 UInt16 address, idVendor, idProduct;
443 UInt8 bDeviceClass, bDeviceSubClass;
445 int ret = 0, need_unref = 0;
448 dev = usbi_get_device_by_session_id(ctx, locationID);
450 usbi_info (ctx, "allocating new device for location 0x%08x", locationID);
451 dev = usbi_alloc_device(ctx, locationID);
454 usbi_info (ctx, "using existing device for location 0x%08x", locationID);
457 ret = LIBUSB_ERROR_NO_MEM;
461 priv = (struct darwin_device_priv *)dev->os_priv;
463 /* Set up request for device descriptor */
464 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
465 req.bRequest = kUSBRqGetDescriptor;
466 req.wValue = kUSBDeviceDesc << 8;
468 req.wLength = sizeof(IOUSBDeviceDescriptor);
469 req.pData = &(priv->dev_descriptor);
471 (*(device))->GetDeviceAddress (device, (USBDeviceAddress *)&address);
472 (*(device))->GetDeviceProduct (device, &idProduct);
473 (*(device))->GetDeviceVendor (device, &idVendor);
474 (*(device))->GetDeviceClass (device, &bDeviceClass);
475 (*(device))->GetDeviceSubClass (device, &bDeviceSubClass);
477 /**** retrieve device descriptors ****/
478 /* device must be open for DeviceRequest */
479 (*device)->USBDeviceOpen(device);
481 ret = (*(device))->DeviceRequest (device, &req);
482 if (ret != kIOReturnSuccess) {
483 int try_unsuspend = 1;
484 #if DeviceVersion >= 320
487 /* device may be suspended. unsuspend it and try again */
488 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
489 (void)(*device)->GetUSBDeviceInformation (device, &info);
491 try_unsuspend = info & (1 << kUSBInformationDeviceIsSuspendedBit);
495 /* resume the device */
496 (void)(*device)->USBDeviceSuspend (device, 0);
498 ret = (*(device))->DeviceRequest (device, &req);
500 /* resuspend the device */
501 (void)(*device)->USBDeviceSuspend (device, 1);
505 (*device)->USBDeviceClose (device);
507 if (ret != kIOReturnSuccess) {
508 usbi_warn (ctx, "could not retrieve device descriptor: %s. skipping device", darwin_error_str (ret));
513 /**** end: retrieve device descriptors ****/
515 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
516 if (libusb_le16_to_cpu (priv->dev_descriptor.idProduct) != idProduct) {
517 /* not a valid device */
518 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
519 idProduct, libusb_le16_to_cpu (priv->dev_descriptor.idProduct));
524 dev->bus_number = locationID >> 24;
525 dev->device_address = address;
527 /* save our location, we'll need this later */
528 priv->location = locationID;
529 snprintf(priv->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", address, idVendor, idProduct, bDeviceClass, bDeviceSubClass);
531 ret = usbi_sanitize_device (dev);
535 /* append the device to the list of discovered devices */
536 discdevs = discovered_devs_append(*_discdevs, dev);
538 ret = LIBUSB_ERROR_NO_MEM;
542 *_discdevs = discdevs;
544 usbi_info (ctx, "found device with address %d at %s", dev->device_address, priv->sys_path);
548 libusb_unref_device(dev);
553 static int darwin_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs) {
554 io_iterator_t deviceIterator;
555 usb_device_t **device;
556 kern_return_t kresult;
559 if (!libusb_darwin_mp)
560 return LIBUSB_ERROR_INVALID_PARAM;
562 kresult = usb_setup_device_iterator (&deviceIterator);
563 if (kresult != kIOReturnSuccess)
564 return darwin_to_libusb (kresult);
566 while ((device = usb_get_next_device (deviceIterator, &location)) != NULL) {
567 (void) process_new_device (ctx, device, location, _discdevs);
569 (*(device))->Release(device);
572 IOObjectRelease(deviceIterator);
577 static int darwin_open (struct libusb_device_handle *dev_handle) {
578 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
579 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
580 usb_device_t **darwin_device;
583 if (0 == dpriv->open_count) {
584 kresult = darwin_get_device (dpriv->location, &darwin_device);
586 usbi_err (HANDLE_CTX (dev_handle), "could not find device: %s", darwin_error_str (kresult));
587 return darwin_to_libusb (kresult);
590 dpriv->device = darwin_device;
592 /* try to open the device */
593 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
595 if (kresult != kIOReturnSuccess) {
596 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
599 case kIOReturnExclusiveAccess:
600 /* it is possible to perform some actions on a device that is not open so do not return an error */
605 (*(dpriv->device))->Release (dpriv->device);
606 dpriv->device = NULL;
607 return darwin_to_libusb (kresult);
612 /* create async event source */
613 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
615 CFRetain (libusb_darwin_acfl);
617 /* add the cfSource to the aync run loop */
618 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
622 /* device opened successfully */
625 /* create a file descriptor for notifications */
628 /* set the pipe to be non-blocking */
629 fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
631 usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
633 usbi_info (HANDLE_CTX (dev_handle), "device open for access");
638 static void darwin_close (struct libusb_device_handle *dev_handle) {
639 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
640 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
644 if (dpriv->open_count == 0) {
645 /* something is probably very wrong if this is the case */
646 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!\n");
652 /* make sure all interfaces are released */
653 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
654 if (dev_handle->claimed_interfaces & (1 << i))
655 libusb_release_interface (dev_handle, i);
657 if (0 == dpriv->open_count) {
659 /* delete the device's async event source */
660 if (priv->cfSource) {
661 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
662 CFRelease (priv->cfSource);
665 /* close the device */
666 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
668 /* Log the fact that we had a problem closing the file, however failing a
669 * close isn't really an error, so return success anyway */
670 usbi_err (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
674 kresult = (*(dpriv->device))->Release(dpriv->device);
676 /* Log the fact that we had a problem closing the file, however failing a
677 * close isn't really an error, so return success anyway */
678 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
681 dpriv->device = NULL;
684 /* file descriptors are maintained per-instance */
685 usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
686 close (priv->fds[1]);
687 close (priv->fds[0]);
689 priv->fds[0] = priv->fds[1] = -1;
692 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
693 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
697 kresult = (*(dpriv->device))->GetConfiguration (dpriv->device, &configNum);
698 if (kresult != kIOReturnSuccess)
699 return darwin_to_libusb (kresult);
701 *config = (int) configNum;
706 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
707 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
711 /* Setting configuration will invalidate the interface, so we need
712 to reclaim it. First, dispose of existing interfaces, if any. */
713 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
714 if (dev_handle->claimed_interfaces & (1 << i))
715 darwin_release_interface (dev_handle, i);
717 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
718 if (kresult != kIOReturnSuccess)
719 return darwin_to_libusb (kresult);
721 /* Reclaim any interfaces. */
722 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
723 if (dev_handle->claimed_interfaces & (1 << i))
724 darwin_claim_interface (dev_handle, i);
729 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
730 IOUSBFindInterfaceRequest request;
731 uint8_t current_interface;
732 kern_return_t kresult;
733 io_iterator_t interface_iterator;
735 *usbInterfacep = IO_OBJECT_NULL;
737 /* Setup the Interface Request */
738 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
739 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
740 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
741 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
743 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
747 for ( current_interface = 0 ; current_interface <= ifc ; current_interface++ )
748 *usbInterfacep = IOIteratorNext(interface_iterator);
750 /* done with the interface iterator */
751 IOObjectRelease(interface_iterator);
756 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
757 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
759 /* current interface */
760 struct __darwin_interface *cInterface = &priv->interfaces[iface];
762 kern_return_t kresult;
764 u_int8_t numep, direction, number;
765 u_int8_t dont_care1, dont_care3;
766 u_int16_t dont_care2;
769 usbi_info (HANDLE_CTX (dev_handle), "building table of endpoints.");
771 /* retrieve the total number of endpoints on this interface */
772 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
774 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
775 return darwin_to_libusb (kresult);
778 /* iterate through pipe references */
779 for (i = 1 ; i <= numep ; i++) {
780 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
781 &dont_care2, &dont_care3);
783 if (kresult != kIOReturnSuccess) {
784 usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
786 return darwin_to_libusb (kresult);
789 usbi_info (HANDLE_CTX (dev_handle), "interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
791 cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
794 cInterface->num_endpoints = numep;
799 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
800 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
801 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
802 io_service_t usbInterface = IO_OBJECT_NULL;
804 IOCFPlugInInterface **plugInInterface = NULL;
808 /* current interface */
809 struct __darwin_interface *cInterface = &priv->interfaces[iface];
811 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
812 if (kresult != kIOReturnSuccess)
813 return darwin_to_libusb (kresult);
815 /* make sure we have an interface */
817 u_int8_t nConfig; /* Index of configuration to use */
818 IOUSBConfigurationDescriptorPtr configDesc; /* to describe which configuration to select */
819 /* Only a composite class device with no vendor-specific driver will
820 be configured. Otherwise, we need to do it ourselves, or there
821 will be no interfaces for the device. */
823 usbi_info (HANDLE_CTX (dev_handle), "no interface found; selecting configuration" );
825 kresult = (*(dpriv->device))->GetNumberOfConfigurations (dpriv->device, &nConfig);
826 if (kresult != kIOReturnSuccess) {
827 usbi_err (HANDLE_CTX (dev_handle), "GetNumberOfConfigurations: %s", darwin_error_str(kresult));
828 return darwin_to_libusb(kresult);
832 usbi_err (HANDLE_CTX (dev_handle), "GetNumberOfConfigurations: no configurations");
833 return LIBUSB_ERROR_OTHER;
836 usbi_info (HANDLE_CTX (dev_handle), "device has %d configuration%s. using the first",
837 (int)nConfig, (nConfig > 1 ? "s" : "") );
839 /* Always use the first configuration */
840 kresult = (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, 0, &configDesc);
841 if (kresult != kIOReturnSuccess) {
842 usbi_err (HANDLE_CTX (dev_handle), "GetConfigurationDescriptorPtr: %s",
843 darwin_error_str(kresult));
847 new_config = configDesc->bConfigurationValue;
849 usbi_info (HANDLE_CTX (dev_handle), "new configuration value is %d", new_config);
851 /* set the configuration */
852 kresult = darwin_set_configuration (dev_handle, new_config);
853 if (kresult != LIBUSB_SUCCESS) {
854 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
858 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
860 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
861 return darwin_to_libusb (kresult);
866 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
867 return LIBUSB_ERROR_NOT_FOUND;
870 /* get an interface to the device's interface */
871 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
872 kIOCFPlugInInterfaceID, &plugInInterface, &score);
874 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
875 return darwin_to_libusb (kresult);
878 if (!plugInInterface) {
879 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
880 return LIBUSB_ERROR_NOT_FOUND;
883 /* ignore release error */
884 (void)IOObjectRelease (usbInterface);
886 /* Do the actual claim */
887 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
888 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
889 (LPVOID)&cInterface->interface);
890 if (kresult || !cInterface->interface) {
891 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
892 return darwin_to_libusb (kresult);
895 /* We no longer need the intermediate plug-in */
896 (*plugInInterface)->Release(plugInInterface);
898 /* claim the interface */
899 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
901 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
902 return darwin_to_libusb (kresult);
905 /* update list of endpoints */
906 kresult = get_endpoints (dev_handle, iface);
908 /* this should not happen */
909 darwin_release_interface (dev_handle, iface);
910 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
914 cInterface->cfSource = NULL;
916 /* create async event source */
917 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
918 if (kresult != kIOReturnSuccess) {
919 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
921 /* can't continue without an async event source */
922 (void)darwin_release_interface (dev_handle, iface);
924 return darwin_to_libusb (kresult);
927 /* add the cfSource to the async thread's run loop */
928 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
930 usbi_info (HANDLE_CTX (dev_handle), "interface opened");
935 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
936 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
939 /* current interface */
940 struct __darwin_interface *cInterface = &priv->interfaces[iface];
942 /* Check to see if an interface is open */
943 if (!cInterface->interface)
944 return LIBUSB_SUCCESS;
946 /* clean up endpoint data */
947 cInterface->num_endpoints = 0;
949 /* delete the interface's async event source */
950 if (cInterface->cfSource) {
951 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
952 CFRelease (cInterface->cfSource);
955 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
957 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
959 kresult = (*(cInterface->interface))->Release(cInterface->interface);
960 if (kresult != kIOReturnSuccess)
961 usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
963 cInterface->interface = IO_OBJECT_NULL;
965 return darwin_to_libusb (kresult);
968 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
969 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
972 /* current interface */
973 struct __darwin_interface *cInterface = &priv->interfaces[iface];
975 if (!cInterface->interface)
976 return LIBUSB_ERROR_NO_DEVICE;
978 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
979 if (kresult != kIOReturnSuccess)
980 darwin_reset_device (dev_handle);
982 /* update list of endpoints */
983 kresult = get_endpoints (dev_handle, iface);
985 /* this should not happen */
986 darwin_release_interface (dev_handle, iface);
987 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
991 return darwin_to_libusb (kresult);
994 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
995 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
997 /* current interface */
998 struct __darwin_interface *cInterface;
999 uint8_t pipeRef, iface;
1002 /* determine the interface/endpoint to use */
1003 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
1004 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1006 return LIBUSB_ERROR_NOT_FOUND;
1009 cInterface = &priv->interfaces[iface];
1011 #if (InterfaceVersion < 190)
1012 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1014 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1015 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1018 usbi_err (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1020 return darwin_to_libusb (kresult);
1023 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1024 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1027 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1029 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1031 return darwin_to_libusb (kresult);
1034 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1035 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1036 io_service_t usbInterface;
1040 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1042 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1044 return darwin_to_libusb (kresult);
1047 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1048 IOObjectRelease (usbInterface);
1060 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1061 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1062 return LIBUSB_ERROR_NOT_SUPPORTED;
1065 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1066 return LIBUSB_ERROR_NOT_SUPPORTED;
1069 static void darwin_destroy_device(struct libusb_device *dev) {
1072 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1073 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1074 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1077 uint8_t is_read; /* 0 = we're reading, 1 = we're writing */
1078 uint8_t transferType;
1079 /* None of the values below are used in libusb for bulk transfers */
1080 uint8_t direction, number, interval, pipeRef, iface;
1081 uint16_t maxPacketSize;
1083 struct __darwin_interface *cInterface;
1085 /* are we reading or writing? */
1086 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1088 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1089 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1091 return LIBUSB_ERROR_NOT_FOUND;
1094 cInterface = &priv->interfaces[iface];
1096 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1097 &transferType, &maxPacketSize, &interval);
1099 /* submit the request */
1100 /* timeouts are unavailable on interrupt endpoints */
1101 if (transferType == kUSBInterrupt) {
1103 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1104 transfer->length, darwin_async_io_callback, itransfer);
1106 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1107 transfer->length, darwin_async_io_callback, itransfer);
1110 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1111 transfer->length, transfer->timeout, transfer->timeout,
1112 darwin_async_io_callback, (void *)itransfer);
1114 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1115 transfer->length, transfer->timeout, transfer->timeout,
1116 darwin_async_io_callback, (void *)itransfer);
1120 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", is_read ? "In" : "Out",
1121 darwin_error_str(ret), ret);
1123 return darwin_to_libusb (ret);
1126 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1127 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1128 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1129 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1132 uint8_t is_read; /* 0 = we're writing, 1 = we're reading */
1133 uint8_t pipeRef, iface;
1135 AbsoluteTime atTime;
1138 struct __darwin_interface *cInterface;
1140 /* are we reading or writing? */
1141 is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1143 /* construct an array of IOUSBIsocFrames */
1144 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1145 if (!tpriv->isoc_framelist)
1146 return LIBUSB_ERROR_NO_MEM;
1148 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1149 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1150 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1152 /* determine the interface/endpoint to use */
1153 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1154 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1156 return LIBUSB_ERROR_NOT_FOUND;
1159 cInterface = &priv->interfaces[iface];
1161 /* Last but not least we need the bus frame number */
1162 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1164 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1165 free(tpriv->isoc_framelist);
1166 tpriv->isoc_framelist = NULL;
1168 return darwin_to_libusb (kresult);
1171 /* schedule for a frame a little in the future */
1174 /* submit the request */
1176 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1177 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1180 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1181 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1184 if (kresult != kIOReturnSuccess) {
1185 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", is_read ? "In" : "Out",
1186 darwin_error_str(kresult));
1187 free (tpriv->isoc_framelist);
1188 tpriv->isoc_framelist = NULL;
1191 return darwin_to_libusb (kresult);
1194 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1195 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1196 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1197 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1198 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1202 bzero(&tpriv->req, sizeof(tpriv->req));
1204 /* IOUSBDeviceInterface expects the request in cpu endianess */
1205 tpriv->req.bmRequestType = setup->bmRequestType;
1206 tpriv->req.bRequest = setup->bRequest;
1207 /* these values should be in bus order from libusb_fill_control_setup */
1208 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1209 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1210 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1211 /* data is stored after the libusb control block */
1212 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1213 tpriv->req.completionTimeout = transfer->timeout;
1214 tpriv->req.noDataTimeout = transfer->timeout;
1216 /* all transfers in libusb-1.0 are async */
1217 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1219 if (kresult != kIOReturnSuccess)
1220 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1222 return darwin_to_libusb (kresult);
1225 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1226 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1228 switch (transfer->type) {
1229 case LIBUSB_TRANSFER_TYPE_CONTROL:
1230 return submit_control_transfer(itransfer);
1231 case LIBUSB_TRANSFER_TYPE_BULK:
1232 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1233 return submit_bulk_transfer(itransfer);
1234 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1235 return submit_iso_transfer(itransfer);
1237 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1238 return LIBUSB_ERROR_INVALID_PARAM;
1242 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1243 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1244 struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1247 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions control pipe");
1249 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1251 return darwin_to_libusb (kresult);
1254 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1255 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1256 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1257 struct __darwin_interface *cInterface;
1258 uint8_t pipeRef, iface;
1261 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1262 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1264 return LIBUSB_ERROR_NOT_FOUND;
1267 cInterface = &priv->interfaces[iface];
1269 usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions on interface %d pipe %d", iface, pipeRef);
1271 /* abort transactions */
1272 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1274 usbi_info (ITRANSFER_CTX (itransfer), "calling clear pipe stall to clear the data toggle bit");
1276 /* clear the data toggle bit */
1277 #if (InterfaceVersion < 190)
1278 kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1280 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1281 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1284 return darwin_to_libusb (kresult);
1287 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1288 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1290 switch (transfer->type) {
1291 case LIBUSB_TRANSFER_TYPE_CONTROL:
1292 return cancel_control_transfer(itransfer);
1293 case LIBUSB_TRANSFER_TYPE_BULK:
1294 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1295 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1296 return darwin_abort_transfers (itransfer);
1298 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1299 return LIBUSB_ERROR_INVALID_PARAM;
1303 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1304 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1305 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1307 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1308 free (tpriv->isoc_framelist);
1309 tpriv->isoc_framelist = NULL;
1313 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1314 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1315 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1316 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1319 usbi_info (ITRANSFER_CTX (itransfer), "an async io operation has completed");
1321 /* send a completion message to the device's file descriptor */
1322 message = MESSAGE_ASYNC_IO_COMPLETE;
1323 write (priv->fds[1], &message, sizeof (message));
1324 write (priv->fds[1], &itransfer, sizeof (itransfer));
1325 write (priv->fds[1], &result, sizeof (IOReturn));
1326 write (priv->fds[1], &arg0, sizeof (UInt32));
1329 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1331 case kIOReturnSuccess:
1332 return LIBUSB_TRANSFER_COMPLETED;
1333 case kIOReturnAborted:
1334 return LIBUSB_TRANSFER_CANCELLED;
1335 case kIOUSBPipeStalled:
1336 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: pipe is stalled");
1337 return LIBUSB_TRANSFER_STALL;
1338 case kIOReturnOverrun:
1339 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: data overrun", darwin_error_str (result));
1340 return LIBUSB_TRANSFER_OVERFLOW;
1341 case kIOUSBTransactionTimeout:
1342 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1343 return LIBUSB_TRANSFER_TIMED_OUT;
1345 usbi_err (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1346 return LIBUSB_TRANSFER_ERROR;
1350 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1351 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1352 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1353 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1354 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1355 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1356 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1359 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1360 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1364 usbi_info (ITRANSFER_CTX (itransfer), "handling %s completion with kernel status %d",
1365 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", result);
1367 if (kIOReturnSuccess == result) {
1368 if (isIsoc && tpriv->isoc_framelist) {
1369 /* copy isochronous results back */
1371 for (i = 0; i < transfer->num_iso_packets ; i++) {
1372 struct libusb_iso_packet_descriptor *lib_desc = transfer->iso_packet_desc;
1373 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1374 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1377 itransfer->transferred += io_size;
1380 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1381 usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, result));
1384 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, nfds_t nfds, int num_ready) {
1385 struct usbi_transfer *itransfer;
1391 usbi_mutex_lock(&ctx->open_devs_lock);
1392 for (i = 0; i < nfds && num_ready > 0; i++) {
1393 struct pollfd *pollfd = &fds[i];
1394 struct libusb_device_handle *handle;
1395 struct darwin_device_handle_priv *hpriv = NULL;
1397 usbi_info (ctx, "checking fd %i with revents = %x", fds[i], pollfd->revents);
1399 if (!pollfd->revents)
1403 list_for_each_entry(handle, &ctx->open_devs, list) {
1404 hpriv = (struct darwin_device_handle_priv *)handle->os_priv;
1405 if (hpriv->fds[0] == pollfd->fd)
1409 if (!(pollfd->revents & POLLERR)) {
1410 ret = read (hpriv->fds[0], &message, sizeof (message));
1411 if (ret < sizeof (message))
1414 /* could not poll the device-- response is to delete the device (this seems a little heavy-handed) */
1415 message = MESSAGE_DEVICE_GONE;
1418 case MESSAGE_DEVICE_GONE:
1419 /* remove the device's async port from the runloop */
1420 if (hpriv->cfSource) {
1421 if (libusb_darwin_acfl)
1422 CFRunLoopRemoveSource (libusb_darwin_acfl, hpriv->cfSource, kCFRunLoopDefaultMode);
1423 CFRelease (hpriv->cfSource);
1424 hpriv->cfSource = NULL;
1427 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
1428 usbi_handle_disconnect(handle);
1430 /* done with this device */
1432 case MESSAGE_ASYNC_IO_COMPLETE:
1433 read (hpriv->fds[0], &itransfer, sizeof (itransfer));
1434 read (hpriv->fds[0], &kresult, sizeof (IOReturn));
1435 read (hpriv->fds[0], &io_size, sizeof (UInt32));
1437 darwin_handle_callback (itransfer, kresult, io_size);
1440 usbi_err (ctx, "unknown message received from device pipe");
1444 usbi_mutex_unlock(&ctx->open_devs_lock);
1449 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1450 mach_timespec_t sys_time;
1451 clock_serv_t clock_ref;
1454 case USBI_CLOCK_REALTIME:
1455 /* CLOCK_REALTIME represents time since the epoch */
1456 host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &clock_ref);
1458 case USBI_CLOCK_MONOTONIC:
1459 /* use system boot time as reference for the monotonic clock */
1460 host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &clock_ref);
1463 return LIBUSB_ERROR_INVALID_PARAM;
1466 clock_get_time (clock_ref, &sys_time);
1468 tp->tv_sec = sys_time.tv_sec;
1469 tp->tv_nsec = sys_time.tv_nsec;
1474 const struct usbi_os_backend darwin_backend = {
1476 .init = darwin_init,
1477 .exit = darwin_exit,
1478 .get_device_list = darwin_get_device_list,
1479 .get_device_descriptor = darwin_get_device_descriptor,
1480 .get_active_config_descriptor = darwin_get_active_config_descriptor,
1481 .get_config_descriptor = darwin_get_config_descriptor,
1483 .open = darwin_open,
1484 .close = darwin_close,
1485 .get_configuration = darwin_get_configuration,
1486 .set_configuration = darwin_set_configuration,
1487 .claim_interface = darwin_claim_interface,
1488 .release_interface = darwin_release_interface,
1490 .set_interface_altsetting = darwin_set_interface_altsetting,
1491 .clear_halt = darwin_clear_halt,
1492 .reset_device = darwin_reset_device,
1494 .kernel_driver_active = darwin_kernel_driver_active,
1495 .detach_kernel_driver = darwin_detach_kernel_driver,
1496 .attach_kernel_driver = darwin_attach_kernel_driver,
1498 .destroy_device = darwin_destroy_device,
1500 .submit_transfer = darwin_submit_transfer,
1501 .cancel_transfer = darwin_cancel_transfer,
1502 .clear_transfer_priv = darwin_clear_transfer_priv,
1504 .handle_events = op_handle_events,
1506 .clock_gettime = darwin_clock_gettime,
1508 .device_priv_size = sizeof(struct darwin_device_priv),
1509 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1510 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1511 .add_iso_packet_size = 0,