1 /* -*- Mode: C; indent-tabs-mode:nil -*- */
3 * darwin backend for libusbx 1.0
4 * Copyright © 2008-2013 Nathan Hjelm <hjelmn@users.sourceforge.net>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
28 #include <sys/types.h>
31 #include <libkern/OSAtomic.h>
33 #include <mach/clock.h>
34 #include <mach/clock_types.h>
35 #include <mach/mach_host.h>
36 #include <mach/mach_port.h>
38 #include <AvailabilityMacros.h>
39 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
40 #include <objc/objc-auto.h>
43 #include "darwin_usb.h"
45 /* async event thread */
46 static pthread_mutex_t libusb_darwin_at_mutex
= PTHREAD_MUTEX_INITIALIZER
;
47 static pthread_cond_t libusb_darwin_at_cond
= PTHREAD_COND_INITIALIZER
;
49 static clock_serv_t clock_realtime
;
50 static clock_serv_t clock_monotonic
;
52 static CFRunLoopRef libusb_darwin_acfl
= NULL
; /* event cf loop */
53 static volatile int32_t initCount
= 0;
55 static usbi_mutex_t darwin_cached_devices_lock
= PTHREAD_MUTEX_INITIALIZER
;
56 static struct list_head darwin_cached_devices
= {&darwin_cached_devices
, &darwin_cached_devices
};
58 #define DARWIN_CACHED_DEVICE(a) ((struct darwin_cached_device *) (((struct darwin_device_priv *)((a)->os_priv))->dev))
60 /* async event thread */
61 static pthread_t libusb_darwin_at
;
63 static int darwin_get_config_descriptor(struct libusb_device
*dev
, uint8_t config_index
, unsigned char *buffer
, size_t len
, int *host_endian
);
64 static int darwin_claim_interface(struct libusb_device_handle
*dev_handle
, int iface
);
65 static int darwin_release_interface(struct libusb_device_handle
*dev_handle
, int iface
);
66 static int darwin_reset_device(struct libusb_device_handle
*dev_handle
);
67 static void darwin_async_io_callback (void *refcon
, IOReturn result
, void *arg0
);
69 static int darwin_scan_devices(struct libusb_context
*ctx
);
70 static int process_new_device (struct libusb_context
*ctx
, io_service_t service
);
72 #if defined(ENABLE_LOGGING)
73 static const char *darwin_error_str (int result
) {
75 case kIOReturnSuccess
:
77 case kIOReturnNotOpen
:
78 return "device not opened for exclusive access";
79 case kIOReturnNoDevice
:
80 return "no connection to an IOService";
81 case kIOUSBNoAsyncPortErr
:
82 return "no async port has been opened for interface";
83 case kIOReturnExclusiveAccess
:
84 return "another process has device opened for exclusive access";
85 case kIOUSBPipeStalled
:
86 return "pipe is stalled";
88 return "could not establish a connection to the Darwin kernel";
89 case kIOUSBTransactionTimeout
:
90 return "transaction timed out";
91 case kIOReturnBadArgument
:
92 return "invalid argument";
93 case kIOReturnAborted
:
94 return "transaction aborted";
95 case kIOReturnNotResponding
:
96 return "device not responding";
97 case kIOReturnOverrun
:
98 return "data overrun";
99 case kIOReturnCannotWire
:
100 return "physical memory can not be wired down";
101 case kIOReturnNoResources
:
102 return "out of resources";
103 case kIOUSBHighSpeedSplitError
:
104 return "high speed split error";
106 return "unknown error";
111 static int darwin_to_libusb (int result
) {
113 case kIOReturnUnderrun
:
114 case kIOReturnSuccess
:
115 return LIBUSB_SUCCESS
;
116 case kIOReturnNotOpen
:
117 case kIOReturnNoDevice
:
118 return LIBUSB_ERROR_NO_DEVICE
;
119 case kIOReturnExclusiveAccess
:
120 return LIBUSB_ERROR_ACCESS
;
121 case kIOUSBPipeStalled
:
122 return LIBUSB_ERROR_PIPE
;
123 case kIOReturnBadArgument
:
124 return LIBUSB_ERROR_INVALID_PARAM
;
125 case kIOUSBTransactionTimeout
:
126 return LIBUSB_ERROR_TIMEOUT
;
127 case kIOReturnNotResponding
:
128 case kIOReturnAborted
:
130 case kIOUSBNoAsyncPortErr
:
132 return LIBUSB_ERROR_OTHER
;
136 /* this function must be called with the darwin_cached_devices_lock held */
137 static void darwin_deref_cached_device(struct darwin_cached_device
*cached_dev
) {
138 cached_dev
->refcount
--;
139 /* free the device and remove it from the cache */
140 if (0 == cached_dev
->refcount
) {
141 list_del(&cached_dev
->list
);
143 (*(cached_dev
->device
))->Release(cached_dev
->device
);
148 static void darwin_ref_cached_device(struct darwin_cached_device
*cached_dev
) {
149 cached_dev
->refcount
++;
152 static int ep_to_pipeRef(struct libusb_device_handle
*dev_handle
, uint8_t ep
, uint8_t *pipep
, uint8_t *ifcp
) {
153 struct darwin_device_handle_priv
*priv
= (struct darwin_device_handle_priv
*)dev_handle
->os_priv
;
155 /* current interface */
156 struct darwin_interface
*cInterface
;
160 usbi_dbg ("converting ep address 0x%02x to pipeRef and interface", ep
);
162 for (iface
= 0 ; iface
< USB_MAXINTERFACES
; iface
++) {
163 cInterface
= &priv
->interfaces
[iface
];
165 if (dev_handle
->claimed_interfaces
& (1 << iface
)) {
166 for (i
= 0 ; i
< cInterface
->num_endpoints
; i
++) {
167 if (cInterface
->endpoint_addrs
[i
] == ep
) {
170 usbi_dbg ("pipe %d on interface %d matches", *pipep
, *ifcp
);
177 /* No pipe found with the correct endpoint address */
178 usbi_warn (HANDLE_CTX(dev_handle
), "no pipeRef found with endpoint address 0x%02x.", ep
);
183 static int usb_setup_device_iterator (io_iterator_t
*deviceIterator
, UInt32 location
) {
184 CFMutableDictionaryRef matchingDict
= IOServiceMatching(kIOUSBDeviceClassName
);
187 return kIOReturnError
;
190 CFMutableDictionaryRef propertyMatchDict
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0,
191 &kCFTypeDictionaryKeyCallBacks
,
192 &kCFTypeDictionaryValueCallBacks
);
194 if (propertyMatchDict
) {
195 /* there are no unsigned CFNumber types so treat the value as signed. the os seems to do this
196 internally (CFNumberType of locationID is 3) */
197 CFTypeRef locationCF
= CFNumberCreate (NULL
, kCFNumberSInt32Type
, &location
);
199 CFDictionarySetValue (propertyMatchDict
, CFSTR(kUSBDevicePropertyLocationID
), locationCF
);
200 /* release our reference to the CFNumber (CFDictionarySetValue retains it) */
201 CFRelease (locationCF
);
203 CFDictionarySetValue (matchingDict
, CFSTR(kIOPropertyMatchKey
), propertyMatchDict
);
204 /* release out reference to the CFMutableDictionaryRef (CFDictionarySetValue retains it) */
205 CFRelease (propertyMatchDict
);
207 /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
210 return IOServiceGetMatchingServices(kIOMasterPortDefault
, matchingDict
, deviceIterator
);
213 static int get_ioregistry_value_number (io_service_t service
, CFStringRef property
, CFNumberType type
, void *p
) {
214 CFTypeRef cfNumber
= IORegistryEntryCreateCFProperty (service
, property
, kCFAllocatorDefault
, 0);
218 if (CFGetTypeID(cfNumber
) == CFNumberGetTypeID()) {
219 ret
= CFNumberGetValue(cfNumber
, type
, p
);
222 CFRelease (cfNumber
);
228 static usb_device_t
**darwin_device_from_service (io_service_t service
)
230 io_cf_plugin_ref_t
*plugInInterface
= NULL
;
231 usb_device_t
**device
;
232 kern_return_t result
;
235 result
= IOCreatePlugInInterfaceForService(service
, kIOUSBDeviceUserClientTypeID
,
236 kIOCFPlugInInterfaceID
, &plugInInterface
,
239 if (kIOReturnSuccess
!= result
|| !plugInInterface
) {
240 usbi_dbg ("could not set up plugin for service: %s\n", darwin_error_str (result
));
244 (void)(*plugInInterface
)->QueryInterface(plugInInterface
, CFUUIDGetUUIDBytes(DeviceInterfaceID
),
246 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
247 (*plugInInterface
)->Release (plugInInterface
);
252 static void darwin_devices_attached (void *ptr
, io_iterator_t add_devices
) {
253 struct libusb_context
*ctx
;
254 io_service_t service
;
256 usbi_mutex_lock(&active_contexts_lock
);
258 while ((service
= IOIteratorNext(add_devices
))) {
259 /* add this device to each active context's device list */
260 list_for_each_entry(ctx
, &active_contexts_list
, list
, struct libusb_context
) {
261 process_new_device (ctx
, service
);;
264 IOObjectRelease(service
);
267 usbi_mutex_unlock(&active_contexts_lock
);
270 static void darwin_devices_detached (void *ptr
, io_iterator_t rem_devices
) {
271 struct libusb_device
*dev
= NULL
;
272 struct libusb_context
*ctx
;
278 while ((device
= IOIteratorNext (rem_devices
)) != 0) {
279 /* get the location from the i/o registry */
280 ret
= get_ioregistry_value_number (device
, CFSTR("sessionID"), kCFNumberSInt64Type
, &session
);
281 IOObjectRelease (device
);
285 usbi_mutex_lock(&active_contexts_lock
);
287 list_for_each_entry(ctx
, &active_contexts_list
, list
, struct libusb_context
) {
288 usbi_dbg ("notifying context %p of device disconnect", ctx
);
290 dev
= usbi_get_device_by_session_id(ctx
, session
);
292 /* signal the core that this device has been disconnected. the core will tear down this device
293 when the reference count reaches 0 */
294 usbi_disconnect_device(dev
);
298 usbi_mutex_unlock(&active_contexts_lock
);
302 static void darwin_clear_iterator (io_iterator_t iter
) {
305 while ((device
= IOIteratorNext (iter
)) != 0)
306 IOObjectRelease (device
);
309 static void *darwin_event_thread_main (void *arg0
) {
311 struct libusb_context
*ctx
= (struct libusb_context
*)arg0
;
312 CFRunLoopRef runloop
;
314 /* Set this thread's name, so it can be seen in the debugger
315 and crash reports. */
316 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
317 pthread_setname_np ("org.libusb.device-hotplug");
319 /* Tell the Objective-C garbage collector about this thread.
320 This is required because, unlike NSThreads, pthreads are
321 not automatically registered. Although we don't use
322 Objective-C, we use CoreFoundation, which does. */
323 objc_registerThreadWithCollector();
326 /* hotplug (device arrival/removal) sources */
327 CFRunLoopSourceRef libusb_notification_cfsource
;
328 io_notification_port_t libusb_notification_port
;
329 io_iterator_t libusb_rem_device_iterator
;
330 io_iterator_t libusb_add_device_iterator
;
332 usbi_dbg ("creating hotplug event source");
334 runloop
= CFRunLoopGetCurrent ();
337 /* add the notification port to the run loop */
338 libusb_notification_port
= IONotificationPortCreate (kIOMasterPortDefault
);
339 libusb_notification_cfsource
= IONotificationPortGetRunLoopSource (libusb_notification_port
);
340 CFRunLoopAddSource(runloop
, libusb_notification_cfsource
, kCFRunLoopDefaultMode
);
342 /* create notifications for removed devices */
343 kresult
= IOServiceAddMatchingNotification (libusb_notification_port
, kIOTerminatedNotification
,
344 IOServiceMatching(kIOUSBDeviceClassName
),
345 (IOServiceMatchingCallback
)darwin_devices_detached
,
346 (void *)ctx
, &libusb_rem_device_iterator
);
348 if (kresult
!= kIOReturnSuccess
) {
349 usbi_err (ctx
, "could not add hotplug event source: %s", darwin_error_str (kresult
));
354 /* create notifications for attached devices */
355 kresult
= IOServiceAddMatchingNotification(libusb_notification_port
, kIOFirstMatchNotification
,
356 IOServiceMatching(kIOUSBDeviceClassName
),
357 (IOServiceMatchingCallback
)darwin_devices_attached
,
358 (void *)ctx
, &libusb_add_device_iterator
);
360 if (kresult
!= kIOReturnSuccess
) {
361 usbi_err (ctx
, "could not add hotplug event source: %s", darwin_error_str (kresult
));
367 darwin_clear_iterator (libusb_rem_device_iterator
);
368 darwin_clear_iterator (libusb_add_device_iterator
);
370 usbi_dbg ("darwin event thread ready to receive events");
372 /* signal the main thread that the hotplug runloop has been created. */
373 pthread_mutex_lock (&libusb_darwin_at_mutex
);
374 libusb_darwin_acfl
= runloop
;
375 pthread_cond_signal (&libusb_darwin_at_cond
);
376 pthread_mutex_unlock (&libusb_darwin_at_mutex
);
378 /* run the runloop */
381 usbi_dbg ("darwin event thread exiting");
383 /* remove the notification cfsource */
384 CFRunLoopRemoveSource(runloop
, libusb_notification_cfsource
, kCFRunLoopDefaultMode
);
386 /* delete notification port */
387 IONotificationPortDestroy (libusb_notification_port
);
389 /* delete iterators */
390 IOObjectRelease (libusb_rem_device_iterator
);
391 IOObjectRelease (libusb_add_device_iterator
);
395 libusb_darwin_acfl
= NULL
;
400 static void _darwin_finalize(void) {
401 struct darwin_cached_device
*dev
, *next
;
403 usbi_mutex_lock(&darwin_cached_devices_lock
);
404 list_for_each_entry_safe(dev
, next
, &darwin_cached_devices
, list
, struct darwin_cached_device
) {
405 darwin_deref_cached_device(dev
);
407 usbi_mutex_unlock(&darwin_cached_devices_lock
);
410 static int darwin_init(struct libusb_context
*ctx
) {
411 host_name_port_t host_self
;
412 static int initted
= 0;
415 rc
= darwin_scan_devices (ctx
);
416 if (LIBUSB_SUCCESS
!= rc
) {
420 if (OSAtomicIncrement32Barrier(&initCount
) == 1) {
421 /* create the clocks that will be used */
425 atexit(_darwin_finalize
);
428 host_self
= mach_host_self();
429 host_get_clock_service(host_self
, CALENDAR_CLOCK
, &clock_realtime
);
430 host_get_clock_service(host_self
, SYSTEM_CLOCK
, &clock_monotonic
);
431 mach_port_deallocate(mach_task_self(), host_self
);
433 pthread_create (&libusb_darwin_at
, NULL
, darwin_event_thread_main
, (void *)ctx
);
435 pthread_mutex_lock (&libusb_darwin_at_mutex
);
436 while (!libusb_darwin_acfl
)
437 pthread_cond_wait (&libusb_darwin_at_cond
, &libusb_darwin_at_mutex
);
438 pthread_mutex_unlock (&libusb_darwin_at_mutex
);
444 static void darwin_exit (void) {
445 if (OSAtomicDecrement32Barrier(&initCount
) == 0) {
446 mach_port_deallocate(mach_task_self(), clock_realtime
);
447 mach_port_deallocate(mach_task_self(), clock_monotonic
);
449 /* stop the event runloop and wait for the thread to terminate. */
450 CFRunLoopStop (libusb_darwin_acfl
);
451 pthread_join (libusb_darwin_at
, NULL
);
455 static int darwin_get_device_descriptor(struct libusb_device
*dev
, unsigned char *buffer
, int *host_endian
) {
456 struct darwin_cached_device
*priv
= DARWIN_CACHED_DEVICE(dev
);
458 /* return cached copy */
459 memmove (buffer
, &(priv
->dev_descriptor
), DEVICE_DESC_LENGTH
);
466 static int get_configuration_index (struct libusb_device
*dev
, int config_value
) {
467 struct darwin_cached_device
*priv
= DARWIN_CACHED_DEVICE(dev
);
469 IOUSBConfigurationDescriptorPtr desc
;
472 /* is there a simpler way to determine the index? */
473 kresult
= (*(priv
->device
))->GetNumberOfConfigurations (priv
->device
, &numConfig
);
474 if (kresult
!= kIOReturnSuccess
)
475 return darwin_to_libusb (kresult
);
477 for (i
= 0 ; i
< numConfig
; i
++) {
478 (*(priv
->device
))->GetConfigurationDescriptorPtr (priv
->device
, i
, &desc
);
480 if (desc
->bConfigurationValue
== config_value
)
484 /* configuration not found */
485 return LIBUSB_ERROR_NOT_FOUND
;
488 static int darwin_get_active_config_descriptor(struct libusb_device
*dev
, unsigned char *buffer
, size_t len
, int *host_endian
) {
489 struct darwin_cached_device
*priv
= DARWIN_CACHED_DEVICE(dev
);
492 if (0 == priv
->active_config
)
493 return LIBUSB_ERROR_NOT_FOUND
;
495 config_index
= get_configuration_index (dev
, priv
->active_config
);
496 if (config_index
< 0)
499 return darwin_get_config_descriptor (dev
, config_index
, buffer
, len
, host_endian
);
502 static int darwin_get_config_descriptor(struct libusb_device
*dev
, uint8_t config_index
, unsigned char *buffer
, size_t len
, int *host_endian
) {
503 struct darwin_cached_device
*priv
= DARWIN_CACHED_DEVICE(dev
);
504 IOUSBConfigurationDescriptorPtr desc
;
508 if (!priv
|| !priv
->device
)
509 return LIBUSB_ERROR_OTHER
;
511 kresult
= (*priv
->device
)->GetConfigurationDescriptorPtr (priv
->device
, config_index
, &desc
);
512 if (kresult
== kIOReturnSuccess
) {
513 /* copy descriptor */
514 if (libusb_le16_to_cpu(desc
->wTotalLength
) < len
)
515 len
= libusb_le16_to_cpu(desc
->wTotalLength
);
517 memmove (buffer
, desc
, len
);
519 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
523 ret
= darwin_to_libusb (kresult
);
524 if (ret
!= LIBUSB_SUCCESS
)
530 /* check whether the os has configured the device */
531 static int darwin_check_configuration (struct libusb_context
*ctx
, struct darwin_cached_device
*dev
) {
532 usb_device_t
**darwin_device
= dev
->device
;
534 IOUSBConfigurationDescriptorPtr configDesc
;
535 IOUSBFindInterfaceRequest request
;
536 kern_return_t kresult
;
537 io_iterator_t interface_iterator
;
538 io_service_t firstInterface
;
540 if (dev
->dev_descriptor
.bNumConfigurations
< 1) {
541 usbi_err (ctx
, "device has no configurations");
542 return LIBUSB_ERROR_OTHER
; /* no configurations at this speed so we can't use it */
545 /* find the first configuration */
546 kresult
= (*darwin_device
)->GetConfigurationDescriptorPtr (darwin_device
, 0, &configDesc
);
547 dev
->first_config
= (kIOReturnSuccess
== kresult
) ? configDesc
->bConfigurationValue
: 1;
549 /* check if the device is already configured. there is probably a better way than iterating over the
550 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
551 might lock up on the device request) */
553 /* Setup the Interface Request */
554 request
.bInterfaceClass
= kIOUSBFindInterfaceDontCare
;
555 request
.bInterfaceSubClass
= kIOUSBFindInterfaceDontCare
;
556 request
.bInterfaceProtocol
= kIOUSBFindInterfaceDontCare
;
557 request
.bAlternateSetting
= kIOUSBFindInterfaceDontCare
;
559 kresult
= (*(darwin_device
))->CreateInterfaceIterator(darwin_device
, &request
, &interface_iterator
);
561 return darwin_to_libusb (kresult
);
564 firstInterface
= IOIteratorNext(interface_iterator
);
566 /* done with the interface iterator */
567 IOObjectRelease(interface_iterator
);
569 if (firstInterface
) {
570 IOObjectRelease (firstInterface
);
572 /* device is configured */
573 if (dev
->dev_descriptor
.bNumConfigurations
== 1)
574 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
575 dev
->active_config
= dev
->first_config
;
577 /* devices with more than one configuration should work with GetConfiguration */
578 (*darwin_device
)->GetConfiguration (darwin_device
, &dev
->active_config
);
581 dev
->active_config
= 0;
583 usbi_dbg ("active config: %u, first config: %u", dev
->active_config
, dev
->first_config
);
588 static int darwin_request_descriptor (usb_device_t
**device
, UInt8 desc
, UInt8 desc_index
, void *buffer
, size_t buffer_size
) {
589 IOUSBDevRequestTO req
;
591 memset (buffer
, 0, buffer_size
);
593 /* Set up request for descriptor/ */
594 req
.bmRequestType
= USBmakebmRequestType(kUSBIn
, kUSBStandard
, kUSBDevice
);
595 req
.bRequest
= kUSBRqGetDescriptor
;
596 req
.wValue
= desc
<< 8;
597 req
.wIndex
= desc_index
;
598 req
.wLength
= buffer_size
;
600 req
.noDataTimeout
= 20;
601 req
.completionTimeout
= 100;
603 return (*device
)->DeviceRequestTO (device
, &req
);
606 static int darwin_cache_device_descriptor (struct libusb_context
*ctx
, struct darwin_cached_device
*dev
) {
607 usb_device_t
**device
= dev
->device
;
608 int retries
= 1, delay
= 30000;
609 int unsuspended
= 0, try_unsuspend
= 1, try_reconfigure
= 1;
613 UInt16 idProduct
, idVendor
;
615 dev
->can_enumerate
= 0;
617 (*device
)->GetDeviceClass (device
, &bDeviceClass
);
618 (*device
)->GetDeviceProduct (device
, &idProduct
);
619 (*device
)->GetDeviceVendor (device
, &idVendor
);
621 /* According to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
622 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
623 * to follow the spec as closely as possible, try opening the device */
624 is_open
= ((*device
)->USBDeviceOpenSeize(device
) == kIOReturnSuccess
);
627 /**** retrieve device descriptor ****/
628 ret
= darwin_request_descriptor (device
, kUSBDeviceDesc
, 0, &dev
->dev_descriptor
, sizeof(dev
->dev_descriptor
));
630 if (kIOReturnOverrun
== ret
&& kUSBDeviceDesc
== dev
->dev_descriptor
.bDescriptorType
)
631 /* received an overrun error but we still received a device descriptor */
632 ret
= kIOReturnSuccess
;
634 if (kIOUSBVendorIDAppleComputer
== idVendor
) {
635 /* NTH: don't bother retrying or unsuspending Apple devices */
639 if (kIOReturnSuccess
== ret
&& (0 == dev
->dev_descriptor
.bNumConfigurations
||
640 0 == dev
->dev_descriptor
.bcdUSB
)) {
641 /* work around for incorrectly configured devices */
642 if (try_reconfigure
&& is_open
) {
643 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
645 /* set the first configuration */
646 (*device
)->SetConfiguration(device
, 1);
648 /* don't try to reconfigure again */
652 ret
= kIOUSBPipeStalled
;
655 if (kIOReturnSuccess
!= ret
&& is_open
&& try_unsuspend
) {
656 /* device may be suspended. unsuspend it and try again */
657 #if DeviceVersion >= 320
660 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
661 (void)(*device
)->GetUSBDeviceInformation (device
, &info
);
663 /* note that the device was suspended */
664 if (info
& (1 << kUSBInformationDeviceIsSuspendedBit
) || 0 == info
)
669 /* try to unsuspend the device */
670 ret2
= (*device
)->USBDeviceSuspend (device
, 0);
671 if (kIOReturnSuccess
!= ret2
) {
672 /* prevent log spew from poorly behaving devices. this indicates the
673 os actually had trouble communicating with the device */
674 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2
));
682 if (kIOReturnSuccess
!= ret
) {
683 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret
, delay
/1000);
684 /* sleep for a little while before trying again */
687 } while (kIOReturnSuccess
!= ret
&& retries
--);
690 /* resuspend the device */
691 (void)(*device
)->USBDeviceSuspend (device
, 1);
694 (void) (*device
)->USBDeviceClose (device
);
696 if (ret
!= kIOReturnSuccess
) {
697 /* a debug message was already printed out for this error */
698 if (LIBUSB_CLASS_HUB
== bDeviceClass
)
699 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
700 idVendor
, idProduct
, darwin_error_str (ret
), ret
);
702 usbi_warn (ctx
, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
703 idVendor
, idProduct
, darwin_error_str (ret
), ret
);
707 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
708 if (libusb_le16_to_cpu (dev
->dev_descriptor
.idProduct
) != idProduct
) {
709 /* not a valid device */
710 usbi_warn (ctx
, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
711 idProduct
, libusb_le16_to_cpu (dev
->dev_descriptor
.idProduct
));
715 usbi_dbg ("cached device descriptor:");
716 usbi_dbg (" bDescriptorType: 0x%02x", dev
->dev_descriptor
.bDescriptorType
);
717 usbi_dbg (" bcdUSB: 0x%04x", dev
->dev_descriptor
.bcdUSB
);
718 usbi_dbg (" bDeviceClass: 0x%02x", dev
->dev_descriptor
.bDeviceClass
);
719 usbi_dbg (" bDeviceSubClass: 0x%02x", dev
->dev_descriptor
.bDeviceSubClass
);
720 usbi_dbg (" bDeviceProtocol: 0x%02x", dev
->dev_descriptor
.bDeviceProtocol
);
721 usbi_dbg (" bMaxPacketSize0: 0x%02x", dev
->dev_descriptor
.bMaxPacketSize0
);
722 usbi_dbg (" idVendor: 0x%04x", dev
->dev_descriptor
.idVendor
);
723 usbi_dbg (" idProduct: 0x%04x", dev
->dev_descriptor
.idProduct
);
724 usbi_dbg (" bcdDevice: 0x%04x", dev
->dev_descriptor
.bcdDevice
);
725 usbi_dbg (" iManufacturer: 0x%02x", dev
->dev_descriptor
.iManufacturer
);
726 usbi_dbg (" iProduct: 0x%02x", dev
->dev_descriptor
.iProduct
);
727 usbi_dbg (" iSerialNumber: 0x%02x", dev
->dev_descriptor
.iSerialNumber
);
728 usbi_dbg (" bNumConfigurations: 0x%02x", dev
->dev_descriptor
.bNumConfigurations
);
730 dev
->can_enumerate
= 1;
735 static int darwin_get_cached_device(struct libusb_context
*ctx
, io_service_t service
,
736 struct darwin_cached_device
**cached_out
) {
737 struct darwin_cached_device
*new_device
;
738 UInt64 sessionID
, parent_sessionID
;
739 int ret
= LIBUSB_SUCCESS
;
740 usb_device_t
**device
;
742 kern_return_t result
;
747 /* get some info from the io registry */
748 (void) get_ioregistry_value_number (service
, CFSTR("sessionID"), kCFNumberSInt64Type
, &sessionID
);
749 (void) get_ioregistry_value_number (service
, CFSTR("PortNum"), kCFNumberSInt8Type
, &port
);
751 usbi_dbg("finding cached device for sessionID 0x\n" PRIx64
, sessionID
);
753 result
= IORegistryEntryGetParentEntry (service
, kIOUSBPlane
, &parent
);
755 if (kIOReturnSuccess
== result
) {
756 (void) get_ioregistry_value_number (parent
, CFSTR("sessionID"), kCFNumberSInt64Type
, &parent_sessionID
);
757 IOObjectRelease(parent
);
760 usbi_mutex_lock(&darwin_cached_devices_lock
);
762 list_for_each_entry(new_device
, &darwin_cached_devices
, list
, struct darwin_cached_device
) {
763 usbi_dbg("matching sessionID 0x%x against cached device with sessionID 0x%x", sessionID
, new_device
->session
);
764 if (new_device
->session
== sessionID
) {
765 usbi_dbg("using cached device for device");
766 *cached_out
= new_device
;
774 usbi_dbg("caching new device with sessionID 0x%x\n", sessionID
);
776 new_device
= calloc (1, sizeof (*new_device
));
778 ret
= LIBUSB_ERROR_NO_MEM
;
782 device
= darwin_device_from_service (service
);
784 ret
= LIBUSB_ERROR_NO_DEVICE
;
790 /* add this device to the cached device list */
791 list_add(&new_device
->list
, &darwin_cached_devices
);
793 (*device
)->GetDeviceAddress (device
, (USBDeviceAddress
*)&new_device
->address
);
795 /* keep a reference to this device */
796 darwin_ref_cached_device(new_device
);
798 new_device
->device
= device
;
799 new_device
->session
= sessionID
;
800 (*device
)->GetLocationID (device
, &new_device
->location
);
801 new_device
->port
= port
;
802 new_device
->parent_session
= parent_sessionID
;
804 /* cache the device descriptor */
805 ret
= darwin_cache_device_descriptor(ctx
, new_device
);
809 if (new_device
->can_enumerate
) {
810 snprintf(new_device
->sys_path
, 20, "%03i-%04x-%04x-%02x-%02x", new_device
->address
,
811 new_device
->dev_descriptor
.idVendor
, new_device
->dev_descriptor
.idProduct
,
812 new_device
->dev_descriptor
.bDeviceClass
, new_device
->dev_descriptor
.bDeviceSubClass
);
816 usbi_mutex_unlock(&darwin_cached_devices_lock
);
818 /* keep track of devices regardless of if we successfully enumerate them to
819 prevent them from being enumerated multiple times */
821 *cached_out
= new_device
;
826 static int process_new_device (struct libusb_context
*ctx
, io_service_t service
) {
827 struct darwin_device_priv
*priv
;
828 struct libusb_device
*dev
= NULL
;
829 struct darwin_cached_device
*cached_device
;
834 ret
= darwin_get_cached_device (ctx
, service
, &cached_device
);
836 if (ret
< 0 || (cached_device
&& !cached_device
->can_enumerate
)) {
840 /* check current active configuration (and cache the first configuration value--
841 which may be used by claim_interface) */
842 ret
= darwin_check_configuration (ctx
, cached_device
);
846 usbi_dbg ("allocating new device in context %p for with session 0x%08x",
847 ctx
, cached_device
->session
);
849 dev
= usbi_alloc_device(ctx
, cached_device
->session
);
851 return LIBUSB_ERROR_NO_MEM
;
854 priv
= (struct darwin_device_priv
*)dev
->os_priv
;
856 priv
->dev
= cached_device
;
857 darwin_ref_cached_device (priv
->dev
);
859 if (cached_device
->parent_session
> 0) {
860 dev
->parent_dev
= usbi_get_device_by_session_id (ctx
, cached_device
->parent_session
);
862 dev
->parent_dev
= NULL
;
864 dev
->port_number
= cached_device
->port
;
865 dev
->bus_number
= cached_device
->location
>> 24;
866 dev
->device_address
= cached_device
->address
;
868 /* need to add a reference to the parent device */
869 if (dev
->parent_dev
) {
870 libusb_ref_device(dev
->parent_dev
);
873 (*(priv
->dev
->device
))->GetDeviceSpeed (priv
->dev
->device
, &devSpeed
);
876 case kUSBDeviceSpeedLow
: dev
->speed
= LIBUSB_SPEED_LOW
; break;
877 case kUSBDeviceSpeedFull
: dev
->speed
= LIBUSB_SPEED_FULL
; break;
878 case kUSBDeviceSpeedHigh
: dev
->speed
= LIBUSB_SPEED_HIGH
; break;
879 #if DeviceVersion >= 500
880 case kUSBDeviceSpeedSuper
: dev
->speed
= LIBUSB_SPEED_SUPER
; break;
883 usbi_warn (ctx
, "Got unknown device speed %d", devSpeed
);
886 ret
= usbi_sanitize_device (dev
);
890 usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev
->device_address
,
891 dev
->port_number
, (void *) dev
->parent_dev
, priv
->dev
->sys_path
);
895 usbi_connect_device (dev
);
897 libusb_unref_device (dev
);
903 static int darwin_scan_devices(struct libusb_context
*ctx
) {
904 io_iterator_t deviceIterator
;
905 io_service_t service
;
906 kern_return_t kresult
;
908 kresult
= usb_setup_device_iterator (&deviceIterator
, 0);
909 if (kresult
!= kIOReturnSuccess
)
910 return darwin_to_libusb (kresult
);
912 while ((service
= IOIteratorNext (deviceIterator
))) {
913 (void) process_new_device (ctx
, service
);
915 IOObjectRelease(service
);
918 IOObjectRelease(deviceIterator
);
923 static int darwin_open (struct libusb_device_handle
*dev_handle
) {
924 struct darwin_device_handle_priv
*priv
= (struct darwin_device_handle_priv
*)dev_handle
->os_priv
;
925 struct darwin_cached_device
*dpriv
= DARWIN_CACHED_DEVICE(dev_handle
->dev
);
928 if (0 == dpriv
->open_count
) {
929 /* try to open the device */
930 kresult
= (*(dpriv
->device
))->USBDeviceOpenSeize (dpriv
->device
);
931 if (kresult
!= kIOReturnSuccess
) {
932 usbi_warn (HANDLE_CTX (dev_handle
), "USBDeviceOpen: %s", darwin_error_str(kresult
));
934 if (kIOReturnExclusiveAccess
!= kresult
) {
935 return darwin_to_libusb (kresult
);
938 /* it is possible to perform some actions on a device that is not open so do not return an error */
944 /* create async event source */
945 kresult
= (*(dpriv
->device
))->CreateDeviceAsyncEventSource (dpriv
->device
, &priv
->cfSource
);
946 if (kresult
!= kIOReturnSuccess
) {
947 usbi_err (HANDLE_CTX (dev_handle
), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult
));
950 (*(dpriv
->device
))->USBDeviceClose (dpriv
->device
);
955 return darwin_to_libusb (kresult
);
958 CFRetain (libusb_darwin_acfl
);
960 /* add the cfSource to the aync run loop */
961 CFRunLoopAddSource(libusb_darwin_acfl
, priv
->cfSource
, kCFRunLoopCommonModes
);
964 /* device opened successfully */
967 /* create a file descriptor for notifications */
970 /* set the pipe to be non-blocking */
971 fcntl (priv
->fds
[1], F_SETFD
, O_NONBLOCK
);
973 usbi_add_pollfd(HANDLE_CTX(dev_handle
), priv
->fds
[0], POLLIN
);
975 usbi_dbg ("device open for access");
980 static void darwin_close (struct libusb_device_handle
*dev_handle
) {
981 struct darwin_device_handle_priv
*priv
= (struct darwin_device_handle_priv
*)dev_handle
->os_priv
;
982 struct darwin_cached_device
*dpriv
= DARWIN_CACHED_DEVICE(dev_handle
->dev
);
986 if (dpriv
->open_count
== 0) {
987 /* something is probably very wrong if this is the case */
988 usbi_err (HANDLE_CTX (dev_handle
), "Close called on a device that was not open!\n");
994 /* make sure all interfaces are released */
995 for (i
= 0 ; i
< USB_MAXINTERFACES
; i
++)
996 if (dev_handle
->claimed_interfaces
& (1 << i
))
997 libusb_release_interface (dev_handle
, i
);
999 if (0 == dpriv
->open_count
) {
1000 /* delete the device's async event source */
1001 if (priv
->cfSource
) {
1002 CFRunLoopRemoveSource (libusb_darwin_acfl
, priv
->cfSource
, kCFRunLoopDefaultMode
);
1003 CFRelease (priv
->cfSource
);
1004 priv
->cfSource
= NULL
;
1005 CFRelease (libusb_darwin_acfl
);
1008 if (priv
->is_open
) {
1009 /* close the device */
1010 kresult
= (*(dpriv
->device
))->USBDeviceClose(dpriv
->device
);
1012 /* Log the fact that we had a problem closing the file, however failing a
1013 * close isn't really an error, so return success anyway */
1014 usbi_warn (HANDLE_CTX (dev_handle
), "USBDeviceClose: %s", darwin_error_str(kresult
));
1019 /* file descriptors are maintained per-instance */
1020 usbi_remove_pollfd (HANDLE_CTX (dev_handle
), priv
->fds
[0]);
1021 close (priv
->fds
[1]);
1022 close (priv
->fds
[0]);
1024 priv
->fds
[0] = priv
->fds
[1] = -1;
1027 static int darwin_get_configuration(struct libusb_device_handle
*dev_handle
, int *config
) {
1028 struct darwin_cached_device
*dpriv
= DARWIN_CACHED_DEVICE(dev_handle
->dev
);
1030 *config
= (int) dpriv
->active_config
;
1035 static int darwin_set_configuration(struct libusb_device_handle
*dev_handle
, int config
) {
1036 struct darwin_cached_device
*dpriv
= DARWIN_CACHED_DEVICE(dev_handle
->dev
);
1040 /* Setting configuration will invalidate the interface, so we need
1041 to reclaim it. First, dispose of existing interfaces, if any. */
1042 for (i
= 0 ; i
< USB_MAXINTERFACES
; i
++)
1043 if (dev_handle
->claimed_interfaces
& (1 << i
))
1044 darwin_release_interface (dev_handle
, i
);
1046 kresult
= (*(dpriv
->device
))->SetConfiguration (dpriv
->device
, config
);
1047 if (kresult
!= kIOReturnSuccess
)
1048 return darwin_to_libusb (kresult
);
1050 /* Reclaim any interfaces. */
1051 for (i
= 0 ; i
< USB_MAXINTERFACES
; i
++)
1052 if (dev_handle
->claimed_interfaces
& (1 << i
))
1053 darwin_claim_interface (dev_handle
, i
);
1055 dpriv
->active_config
= config
;
1060 static int darwin_get_interface (usb_device_t
**darwin_device
, uint8_t ifc
, io_service_t
*usbInterfacep
) {
1061 IOUSBFindInterfaceRequest request
;
1062 kern_return_t kresult
;
1063 io_iterator_t interface_iterator
;
1064 UInt8 bInterfaceNumber
;
1067 *usbInterfacep
= IO_OBJECT_NULL
;
1069 /* Setup the Interface Request */
1070 request
.bInterfaceClass
= kIOUSBFindInterfaceDontCare
;
1071 request
.bInterfaceSubClass
= kIOUSBFindInterfaceDontCare
;
1072 request
.bInterfaceProtocol
= kIOUSBFindInterfaceDontCare
;
1073 request
.bAlternateSetting
= kIOUSBFindInterfaceDontCare
;
1075 kresult
= (*(darwin_device
))->CreateInterfaceIterator(darwin_device
, &request
, &interface_iterator
);
1079 while ((*usbInterfacep
= IOIteratorNext(interface_iterator
))) {
1080 /* find the interface number */
1081 ret
= get_ioregistry_value_number (*usbInterfacep
, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type
,
1084 if (ret
&& bInterfaceNumber
== ifc
) {
1088 (void) IOObjectRelease (*usbInterfacep
);
1091 /* done with the interface iterator */
1092 IOObjectRelease(interface_iterator
);
1097 static int get_endpoints (struct libusb_device_handle
*dev_handle
, int iface
) {
1098 struct darwin_device_handle_priv
*priv
= (struct darwin_device_handle_priv
*)dev_handle
->os_priv
;
1100 /* current interface */
1101 struct darwin_interface
*cInterface
= &priv
->interfaces
[iface
];
1103 kern_return_t kresult
;
1105 u_int8_t numep
, direction
, number
;
1106 u_int8_t dont_care1
, dont_care3
;
1107 u_int16_t dont_care2
;
1110 usbi_dbg ("building table of endpoints.");
1112 /* retrieve the total number of endpoints on this interface */
1113 kresult
= (*(cInterface
->interface
))->GetNumEndpoints(cInterface
->interface
, &numep
);
1115 usbi_err (HANDLE_CTX (dev_handle
), "can't get number of endpoints for interface: %s", darwin_error_str(kresult
));
1116 return darwin_to_libusb (kresult
);
1119 /* iterate through pipe references */
1120 for (i
= 1 ; i
<= numep
; i
++) {
1121 kresult
= (*(cInterface
->interface
))->GetPipeProperties(cInterface
->interface
, i
, &direction
, &number
, &dont_care1
,
1122 &dont_care2
, &dont_care3
);
1124 if (kresult
!= kIOReturnSuccess
) {
1125 usbi_err (HANDLE_CTX (dev_handle
), "error getting pipe information for pipe %d: %s", i
, darwin_error_str(kresult
));
1127 return darwin_to_libusb (kresult
);
1130 usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface
, i
, direction
, number
);
1132 cInterface
->endpoint_addrs
[i
- 1] = ((direction
<< 7 & LIBUSB_ENDPOINT_DIR_MASK
) | (number
& LIBUSB_ENDPOINT_ADDRESS_MASK
));
1135 cInterface
->num_endpoints
= numep
;
1140 static int darwin_claim_interface(struct libusb_device_handle
*dev_handle
, int iface
) {
1141 struct darwin_cached_device
*dpriv
= DARWIN_CACHED_DEVICE(dev_handle
->dev
);
1142 struct darwin_device_handle_priv
*priv
= (struct darwin_device_handle_priv
*)dev_handle
->os_priv
;
1143 io_service_t usbInterface
= IO_OBJECT_NULL
;
1145 IOCFPlugInInterface
**plugInInterface
= NULL
;
1148 /* current interface */
1149 struct darwin_interface
*cInterface
= &priv
->interfaces
[iface
];
1151 kresult
= darwin_get_interface (dpriv
->device
, iface
, &usbInterface
);
1152 if (kresult
!= kIOReturnSuccess
)
1153 return darwin_to_libusb (kresult
);
1155 /* make sure we have an interface */
1156 if (!usbInterface
&& dpriv
->first_config
!= 0) {
1157 usbi_info (HANDLE_CTX (dev_handle
), "no interface found; setting configuration: %d", dpriv
->first_config
);
1159 /* set the configuration */
1160 kresult
= darwin_set_configuration (dev_handle
, dpriv
->first_config
);
1161 if (kresult
!= LIBUSB_SUCCESS
) {
1162 usbi_err (HANDLE_CTX (dev_handle
), "could not set configuration");
1166 kresult
= darwin_get_interface (dpriv
->device
, iface
, &usbInterface
);
1168 usbi_err (HANDLE_CTX (dev_handle
), "darwin_get_interface: %s", darwin_error_str(kresult
));
1169 return darwin_to_libusb (kresult
);
1173 if (!usbInterface
) {
1174 usbi_err (HANDLE_CTX (dev_handle
), "interface not found");
1175 return LIBUSB_ERROR_NOT_FOUND
;
1178 /* get an interface to the device's interface */
1179 kresult
= IOCreatePlugInInterfaceForService (usbInterface
, kIOUSBInterfaceUserClientTypeID
,
1180 kIOCFPlugInInterfaceID
, &plugInInterface
, &score
);
1182 /* ignore release error */
1183 (void)IOObjectRelease (usbInterface
);
1186 usbi_err (HANDLE_CTX (dev_handle
), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult
));
1187 return darwin_to_libusb (kresult
);
1190 if (!plugInInterface
) {
1191 usbi_err (HANDLE_CTX (dev_handle
), "plugin interface not found");
1192 return LIBUSB_ERROR_NOT_FOUND
;
1195 /* Do the actual claim */
1196 kresult
= (*plugInInterface
)->QueryInterface(plugInInterface
,
1197 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID
),
1198 (LPVOID
)&cInterface
->interface
);
1199 /* We no longer need the intermediate plug-in */
1200 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1201 (*plugInInterface
)->Release (plugInInterface
);
1202 if (kresult
|| !cInterface
->interface
) {
1203 usbi_err (HANDLE_CTX (dev_handle
), "QueryInterface: %s", darwin_error_str(kresult
));
1204 return darwin_to_libusb (kresult
);
1207 /* claim the interface */
1208 kresult
= (*(cInterface
->interface
))->USBInterfaceOpen(cInterface
->interface
);
1210 usbi_err (HANDLE_CTX (dev_handle
), "USBInterfaceOpen: %s", darwin_error_str(kresult
));
1211 return darwin_to_libusb (kresult
);
1214 /* update list of endpoints */
1215 kresult
= get_endpoints (dev_handle
, iface
);
1217 /* this should not happen */
1218 darwin_release_interface (dev_handle
, iface
);
1219 usbi_err (HANDLE_CTX (dev_handle
), "could not build endpoint table");
1223 cInterface
->cfSource
= NULL
;
1225 /* create async event source */
1226 kresult
= (*(cInterface
->interface
))->CreateInterfaceAsyncEventSource (cInterface
->interface
, &cInterface
->cfSource
);
1227 if (kresult
!= kIOReturnSuccess
) {
1228 usbi_err (HANDLE_CTX (dev_handle
), "could not create async event source");
1230 /* can't continue without an async event source */
1231 (void)darwin_release_interface (dev_handle
, iface
);
1233 return darwin_to_libusb (kresult
);
1236 /* add the cfSource to the async thread's run loop */
1237 CFRunLoopAddSource(libusb_darwin_acfl
, cInterface
->cfSource
, kCFRunLoopDefaultMode
);
1239 usbi_dbg ("interface opened");
1244 static int darwin_release_interface(struct libusb_device_handle
*dev_handle
, int iface
) {
1245 struct darwin_device_handle_priv
*priv
= (struct darwin_device_handle_priv
*)dev_handle
->os_priv
;
1248 /* current interface */
1249 struct darwin_interface
*cInterface
= &priv
->interfaces
[iface
];
1251 /* Check to see if an interface is open */
1252 if (!cInterface
->interface
)
1253 return LIBUSB_SUCCESS
;
1255 /* clean up endpoint data */
1256 cInterface
->num_endpoints
= 0;
1258 /* delete the interface's async event source */
1259 if (cInterface
->cfSource
) {
1260 CFRunLoopRemoveSource (libusb_darwin_acfl
, cInterface
->cfSource
, kCFRunLoopDefaultMode
);
1261 CFRelease (cInterface
->cfSource
);
1264 kresult
= (*(cInterface
->interface
))->USBInterfaceClose(cInterface
->interface
);
1266 usbi_warn (HANDLE_CTX (dev_handle
), "USBInterfaceClose: %s", darwin_error_str(kresult
));
1268 kresult
= (*(cInterface
->interface
))->Release(cInterface
->interface
);
1269 if (kresult
!= kIOReturnSuccess
)
1270 usbi_warn (HANDLE_CTX (dev_handle
), "Release: %s", darwin_error_str(kresult
));
1272 cInterface
->interface
= IO_OBJECT_NULL
;
1274 return darwin_to_libusb (kresult
);
1277 static int darwin_set_interface_altsetting(struct libusb_device_handle
*dev_handle
, int iface
, int altsetting
) {
1278 struct darwin_device_handle_priv
*priv
= (struct darwin_device_handle_priv
*)dev_handle
->os_priv
;
1281 /* current interface */
1282 struct darwin_interface
*cInterface
= &priv
->interfaces
[iface
];
1284 if (!cInterface
->interface
)
1285 return LIBUSB_ERROR_NO_DEVICE
;
1287 kresult
= (*(cInterface
->interface
))->SetAlternateInterface (cInterface
->interface
, altsetting
);
1288 if (kresult
!= kIOReturnSuccess
)
1289 darwin_reset_device (dev_handle
);
1291 /* update list of endpoints */
1292 kresult
= get_endpoints (dev_handle
, iface
);
1294 /* this should not happen */
1295 darwin_release_interface (dev_handle
, iface
);
1296 usbi_err (HANDLE_CTX (dev_handle
), "could not build endpoint table");
1300 return darwin_to_libusb (kresult
);
1303 static int darwin_clear_halt(struct libusb_device_handle
*dev_handle
, unsigned char endpoint
) {
1304 struct darwin_device_handle_priv
*priv
= (struct darwin_device_handle_priv
*)dev_handle
->os_priv
;
1306 /* current interface */
1307 struct darwin_interface
*cInterface
;
1308 uint8_t pipeRef
, iface
;
1311 /* determine the interface/endpoint to use */
1312 if (ep_to_pipeRef (dev_handle
, endpoint
, &pipeRef
, &iface
) != 0) {
1313 usbi_err (HANDLE_CTX (dev_handle
), "endpoint not found on any open interface");
1315 return LIBUSB_ERROR_NOT_FOUND
;
1318 cInterface
= &priv
->interfaces
[iface
];
1320 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1321 kresult
= (*(cInterface
->interface
))->ClearPipeStallBothEnds(cInterface
->interface
, pipeRef
);
1323 usbi_warn (HANDLE_CTX (dev_handle
), "ClearPipeStall: %s", darwin_error_str (kresult
));
1325 return darwin_to_libusb (kresult
);
1328 static int darwin_reset_device(struct libusb_device_handle
*dev_handle
) {
1329 struct darwin_cached_device
*dpriv
= DARWIN_CACHED_DEVICE(dev_handle
->dev
);
1330 IOUSBDeviceDescriptor descriptor
;
1331 IOUSBConfigurationDescriptorPtr cached_configuration
;
1332 IOUSBConfigurationDescriptor configuration
;
1333 bool reenumerate
= false;
1337 kresult
= (*(dpriv
->device
))->ResetDevice (dpriv
->device
);
1339 usbi_err (HANDLE_CTX (dev_handle
), "ResetDevice: %s", darwin_error_str (kresult
));
1340 return darwin_to_libusb (kresult
);
1344 usbi_dbg ("darwin/reset_device: checking if device descriptor changed");
1346 /* ignore return code. if we can't get a descriptor it might be worthwhile re-enumerating anway */
1347 (void) darwin_request_descriptor (dpriv
->device
, kUSBDeviceDesc
, 0, &descriptor
, sizeof (descriptor
));
1349 /* check if the device descriptor has changed */
1350 if (0 != memcmp (&dpriv
->dev_descriptor
, &descriptor
, sizeof (descriptor
))) {
1355 /* check if any configuration descriptor has changed */
1356 for (i
= 0 ; i
< descriptor
.bNumConfigurations
; ++i
) {
1357 usbi_dbg ("darwin/reset_device: checking if configuration descriptor %d changed", i
);
1359 (void) darwin_request_descriptor (dpriv
->device
, kUSBConfDesc
, i
, &configuration
, sizeof (configuration
));
1360 (*(dpriv
->device
))->GetConfigurationDescriptorPtr (dpriv
->device
, i
, &cached_configuration
);
1362 if (!cached_configuration
|| 0 != memcmp (cached_configuration
, &configuration
, sizeof (configuration
))) {
1370 usbi_dbg ("darwin/reset_device: device requires reenumeration");
1371 (void) (*(dpriv
->device
))->USBDeviceReEnumerate (dpriv
->device
, 0);
1372 return LIBUSB_ERROR_NOT_FOUND
;
1375 usbi_dbg ("darwin/reset_device: device reset complete");
1377 return LIBUSB_SUCCESS
;
1380 static int darwin_kernel_driver_active(struct libusb_device_handle
*dev_handle
, int interface
) {
1381 struct darwin_cached_device
*dpriv
= DARWIN_CACHED_DEVICE(dev_handle
->dev
);
1382 io_service_t usbInterface
;
1386 kresult
= darwin_get_interface (dpriv
->device
, interface
, &usbInterface
);
1388 usbi_err (HANDLE_CTX (dev_handle
), "darwin_get_interface: %s", darwin_error_str(kresult
));
1390 return darwin_to_libusb (kresult
);
1393 driver
= IORegistryEntryCreateCFProperty (usbInterface
, kIOBundleIdentifierKey
, kCFAllocatorDefault
, 0);
1394 IOObjectRelease (usbInterface
);
1406 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1407 static int darwin_attach_kernel_driver (struct libusb_device_handle
*dev_handle
, int interface
) {
1410 return LIBUSB_ERROR_NOT_SUPPORTED
;
1413 static int darwin_detach_kernel_driver (struct libusb_device_handle
*dev_handle
, int interface
) {
1416 return LIBUSB_ERROR_NOT_SUPPORTED
;
1419 static void darwin_destroy_device(struct libusb_device
*dev
) {
1420 struct darwin_device_priv
*dpriv
= (struct darwin_device_priv
*) dev
->os_priv
;
1423 /* need to hold the lock in case this is the last reference to the device */
1424 usbi_mutex_lock(&darwin_cached_devices_lock
);
1425 darwin_deref_cached_device (dpriv
->dev
);
1427 usbi_mutex_unlock(&darwin_cached_devices_lock
);
1431 static int submit_bulk_transfer(struct usbi_transfer
*itransfer
) {
1432 struct libusb_transfer
*transfer
= USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
1433 struct darwin_device_handle_priv
*priv
= (struct darwin_device_handle_priv
*)transfer
->dev_handle
->os_priv
;
1436 uint8_t transferType
;
1437 /* None of the values below are used in libusbx for bulk transfers */
1438 uint8_t direction
, number
, interval
, pipeRef
, iface
;
1439 uint16_t maxPacketSize
;
1441 struct darwin_interface
*cInterface
;
1443 if (ep_to_pipeRef (transfer
->dev_handle
, transfer
->endpoint
, &pipeRef
, &iface
) != 0) {
1444 usbi_err (TRANSFER_CTX (transfer
), "endpoint not found on any open interface");
1446 return LIBUSB_ERROR_NOT_FOUND
;
1449 cInterface
= &priv
->interfaces
[iface
];
1451 (*(cInterface
->interface
))->GetPipeProperties (cInterface
->interface
, pipeRef
, &direction
, &number
,
1452 &transferType
, &maxPacketSize
, &interval
);
1454 if (0 != (transfer
->length
% maxPacketSize
)) {
1455 /* do not need a zero packet */
1456 transfer
->flags
&= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET
;
1459 /* submit the request */
1460 /* timeouts are unavailable on interrupt endpoints */
1461 if (transferType
== kUSBInterrupt
) {
1462 if (IS_XFERIN(transfer
))
1463 ret
= (*(cInterface
->interface
))->ReadPipeAsync(cInterface
->interface
, pipeRef
, transfer
->buffer
,
1464 transfer
->length
, darwin_async_io_callback
, itransfer
);
1466 ret
= (*(cInterface
->interface
))->WritePipeAsync(cInterface
->interface
, pipeRef
, transfer
->buffer
,
1467 transfer
->length
, darwin_async_io_callback
, itransfer
);
1469 itransfer
->flags
|= USBI_TRANSFER_OS_HANDLES_TIMEOUT
;
1471 if (IS_XFERIN(transfer
))
1472 ret
= (*(cInterface
->interface
))->ReadPipeAsyncTO(cInterface
->interface
, pipeRef
, transfer
->buffer
,
1473 transfer
->length
, transfer
->timeout
, transfer
->timeout
,
1474 darwin_async_io_callback
, (void *)itransfer
);
1476 ret
= (*(cInterface
->interface
))->WritePipeAsyncTO(cInterface
->interface
, pipeRef
, transfer
->buffer
,
1477 transfer
->length
, transfer
->timeout
, transfer
->timeout
,
1478 darwin_async_io_callback
, (void *)itransfer
);
1482 usbi_err (TRANSFER_CTX (transfer
), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer
) ? "In" : "Out",
1483 darwin_error_str(ret
), ret
);
1485 return darwin_to_libusb (ret
);
1488 static int submit_iso_transfer(struct usbi_transfer
*itransfer
) {
1489 struct libusb_transfer
*transfer
= USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
1490 struct darwin_transfer_priv
*tpriv
= usbi_transfer_get_os_priv(itransfer
);
1491 struct darwin_device_handle_priv
*priv
= (struct darwin_device_handle_priv
*)transfer
->dev_handle
->os_priv
;
1494 uint8_t direction
, number
, interval
, pipeRef
, iface
, transferType
;
1495 uint16_t maxPacketSize
;
1497 AbsoluteTime atTime
;
1500 struct darwin_interface
*cInterface
;
1502 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1503 if (tpriv
->isoc_framelist
&& tpriv
->num_iso_packets
!= transfer
->num_iso_packets
) {
1504 free(tpriv
->isoc_framelist
);
1505 tpriv
->isoc_framelist
= NULL
;
1508 if (!tpriv
->isoc_framelist
) {
1509 tpriv
->num_iso_packets
= transfer
->num_iso_packets
;
1510 tpriv
->isoc_framelist
= (IOUSBIsocFrame
*) calloc (transfer
->num_iso_packets
, sizeof(IOUSBIsocFrame
));
1511 if (!tpriv
->isoc_framelist
)
1512 return LIBUSB_ERROR_NO_MEM
;
1515 /* copy the frame list from the libusbx descriptor (the structures differ only is member order) */
1516 for (i
= 0 ; i
< transfer
->num_iso_packets
; i
++)
1517 tpriv
->isoc_framelist
[i
].frReqCount
= transfer
->iso_packet_desc
[i
].length
;
1519 /* determine the interface/endpoint to use */
1520 if (ep_to_pipeRef (transfer
->dev_handle
, transfer
->endpoint
, &pipeRef
, &iface
) != 0) {
1521 usbi_err (TRANSFER_CTX (transfer
), "endpoint not found on any open interface");
1523 return LIBUSB_ERROR_NOT_FOUND
;
1526 cInterface
= &priv
->interfaces
[iface
];
1528 /* determine the properties of this endpoint and the speed of the device */
1529 (*(cInterface
->interface
))->GetPipeProperties (cInterface
->interface
, pipeRef
, &direction
, &number
,
1530 &transferType
, &maxPacketSize
, &interval
);
1532 /* Last but not least we need the bus frame number */
1533 kresult
= (*(cInterface
->interface
))->GetBusFrameNumber(cInterface
->interface
, &frame
, &atTime
);
1535 usbi_err (TRANSFER_CTX (transfer
), "failed to get bus frame number: %d", kresult
);
1536 free(tpriv
->isoc_framelist
);
1537 tpriv
->isoc_framelist
= NULL
;
1539 return darwin_to_libusb (kresult
);
1542 (*(cInterface
->interface
))->GetPipeProperties (cInterface
->interface
, pipeRef
, &direction
, &number
,
1543 &transferType
, &maxPacketSize
, &interval
);
1545 /* schedule for a frame a little in the future */
1548 if (cInterface
->frames
[transfer
->endpoint
] && frame
< cInterface
->frames
[transfer
->endpoint
])
1549 frame
= cInterface
->frames
[transfer
->endpoint
];
1551 /* submit the request */
1552 if (IS_XFERIN(transfer
))
1553 kresult
= (*(cInterface
->interface
))->ReadIsochPipeAsync(cInterface
->interface
, pipeRef
, transfer
->buffer
, frame
,
1554 transfer
->num_iso_packets
, tpriv
->isoc_framelist
, darwin_async_io_callback
,
1557 kresult
= (*(cInterface
->interface
))->WriteIsochPipeAsync(cInterface
->interface
, pipeRef
, transfer
->buffer
, frame
,
1558 transfer
->num_iso_packets
, tpriv
->isoc_framelist
, darwin_async_io_callback
,
1561 if (LIBUSB_SPEED_FULL
== transfer
->dev_handle
->dev
->speed
)
1563 cInterface
->frames
[transfer
->endpoint
] = frame
+ transfer
->num_iso_packets
* (1 << (interval
- 1));
1565 /* High/super speed */
1566 cInterface
->frames
[transfer
->endpoint
] = frame
+ transfer
->num_iso_packets
* (1 << (interval
- 1)) / 8;
1568 if (kresult
!= kIOReturnSuccess
) {
1569 usbi_err (TRANSFER_CTX (transfer
), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer
) ? "In" : "Out",
1570 darwin_error_str(kresult
));
1571 free (tpriv
->isoc_framelist
);
1572 tpriv
->isoc_framelist
= NULL
;
1575 return darwin_to_libusb (kresult
);
1578 static int submit_control_transfer(struct usbi_transfer
*itransfer
) {
1579 struct libusb_transfer
*transfer
= USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
1580 struct libusb_control_setup
*setup
= (struct libusb_control_setup
*) transfer
->buffer
;
1581 struct darwin_cached_device
*dpriv
= DARWIN_CACHED_DEVICE(transfer
->dev_handle
->dev
);
1582 struct darwin_device_handle_priv
*priv
= (struct darwin_device_handle_priv
*)transfer
->dev_handle
->os_priv
;
1583 struct darwin_transfer_priv
*tpriv
= usbi_transfer_get_os_priv(itransfer
);
1587 bzero(&tpriv
->req
, sizeof(tpriv
->req
));
1589 /* IOUSBDeviceInterface expects the request in cpu endianess */
1590 tpriv
->req
.bmRequestType
= setup
->bmRequestType
;
1591 tpriv
->req
.bRequest
= setup
->bRequest
;
1592 /* these values should be in bus order from libusb_fill_control_setup */
1593 tpriv
->req
.wValue
= OSSwapLittleToHostInt16 (setup
->wValue
);
1594 tpriv
->req
.wIndex
= OSSwapLittleToHostInt16 (setup
->wIndex
);
1595 tpriv
->req
.wLength
= OSSwapLittleToHostInt16 (setup
->wLength
);
1596 /* data is stored after the libusbx control block */
1597 tpriv
->req
.pData
= transfer
->buffer
+ LIBUSB_CONTROL_SETUP_SIZE
;
1598 tpriv
->req
.completionTimeout
= transfer
->timeout
;
1599 tpriv
->req
.noDataTimeout
= transfer
->timeout
;
1601 itransfer
->flags
|= USBI_TRANSFER_OS_HANDLES_TIMEOUT
;
1603 /* all transfers in libusb-1.0 are async */
1605 if (transfer
->endpoint
) {
1606 struct darwin_interface
*cInterface
;
1607 uint8_t pipeRef
, iface
;
1609 if (ep_to_pipeRef (transfer
->dev_handle
, transfer
->endpoint
, &pipeRef
, &iface
) != 0) {
1610 usbi_err (TRANSFER_CTX (transfer
), "endpoint not found on any open interface");
1612 return LIBUSB_ERROR_NOT_FOUND
;
1615 cInterface
= &priv
->interfaces
[iface
];
1617 kresult
= (*(cInterface
->interface
))->ControlRequestAsyncTO (cInterface
->interface
, pipeRef
, &(tpriv
->req
), darwin_async_io_callback
, itransfer
);
1619 /* control request on endpoint 0 */
1620 kresult
= (*(dpriv
->device
))->DeviceRequestAsyncTO(dpriv
->device
, &(tpriv
->req
), darwin_async_io_callback
, itransfer
);
1622 if (kresult
!= kIOReturnSuccess
)
1623 usbi_err (TRANSFER_CTX (transfer
), "control request failed: %s", darwin_error_str(kresult
));
1625 return darwin_to_libusb (kresult
);
1628 static int darwin_submit_transfer(struct usbi_transfer
*itransfer
) {
1629 struct libusb_transfer
*transfer
= USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
1631 switch (transfer
->type
) {
1632 case LIBUSB_TRANSFER_TYPE_CONTROL
:
1633 return submit_control_transfer(itransfer
);
1634 case LIBUSB_TRANSFER_TYPE_BULK
:
1635 case LIBUSB_TRANSFER_TYPE_INTERRUPT
:
1636 return submit_bulk_transfer(itransfer
);
1637 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
:
1638 return submit_iso_transfer(itransfer
);
1640 usbi_err (TRANSFER_CTX(transfer
), "unknown endpoint type %d", transfer
->type
);
1641 return LIBUSB_ERROR_INVALID_PARAM
;
1645 static int cancel_control_transfer(struct usbi_transfer
*itransfer
) {
1646 struct libusb_transfer
*transfer
= USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
1647 struct darwin_cached_device
*dpriv
= DARWIN_CACHED_DEVICE(transfer
->dev_handle
->dev
);
1650 usbi_warn (ITRANSFER_CTX (itransfer
), "aborting all transactions control pipe");
1653 return LIBUSB_ERROR_NO_DEVICE
;
1655 kresult
= (*(dpriv
->device
))->USBDeviceAbortPipeZero (dpriv
->device
);
1657 return darwin_to_libusb (kresult
);
1660 static int darwin_abort_transfers (struct usbi_transfer
*itransfer
) {
1661 struct libusb_transfer
*transfer
= USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
1662 struct darwin_cached_device
*dpriv
= DARWIN_CACHED_DEVICE(transfer
->dev_handle
->dev
);
1663 struct darwin_device_handle_priv
*priv
= (struct darwin_device_handle_priv
*)transfer
->dev_handle
->os_priv
;
1664 struct darwin_interface
*cInterface
;
1665 uint8_t pipeRef
, iface
;
1668 if (ep_to_pipeRef (transfer
->dev_handle
, transfer
->endpoint
, &pipeRef
, &iface
) != 0) {
1669 usbi_err (TRANSFER_CTX (transfer
), "endpoint not found on any open interface");
1671 return LIBUSB_ERROR_NOT_FOUND
;
1674 cInterface
= &priv
->interfaces
[iface
];
1677 return LIBUSB_ERROR_NO_DEVICE
;
1679 usbi_warn (ITRANSFER_CTX (itransfer
), "aborting all transactions on interface %d pipe %d", iface
, pipeRef
);
1681 /* abort transactions */
1682 (*(cInterface
->interface
))->AbortPipe (cInterface
->interface
, pipeRef
);
1684 usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
1686 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1687 kresult
= (*(cInterface
->interface
))->ClearPipeStallBothEnds(cInterface
->interface
, pipeRef
);
1689 return darwin_to_libusb (kresult
);
1692 static int darwin_cancel_transfer(struct usbi_transfer
*itransfer
) {
1693 struct libusb_transfer
*transfer
= USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
1695 switch (transfer
->type
) {
1696 case LIBUSB_TRANSFER_TYPE_CONTROL
:
1697 return cancel_control_transfer(itransfer
);
1698 case LIBUSB_TRANSFER_TYPE_BULK
:
1699 case LIBUSB_TRANSFER_TYPE_INTERRUPT
:
1700 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
:
1701 return darwin_abort_transfers (itransfer
);
1703 usbi_err (TRANSFER_CTX(transfer
), "unknown endpoint type %d", transfer
->type
);
1704 return LIBUSB_ERROR_INVALID_PARAM
;
1708 static void darwin_clear_transfer_priv (struct usbi_transfer
*itransfer
) {
1709 struct libusb_transfer
*transfer
= USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
1710 struct darwin_transfer_priv
*tpriv
= usbi_transfer_get_os_priv(itransfer
);
1712 if (transfer
->type
== LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
&& tpriv
->isoc_framelist
) {
1713 free (tpriv
->isoc_framelist
);
1714 tpriv
->isoc_framelist
= NULL
;
1718 static void darwin_async_io_callback (void *refcon
, IOReturn result
, void *arg0
) {
1719 struct usbi_transfer
*itransfer
= (struct usbi_transfer
*)refcon
;
1720 struct libusb_transfer
*transfer
= USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
1721 struct darwin_device_handle_priv
*priv
= (struct darwin_device_handle_priv
*)transfer
->dev_handle
->os_priv
;
1722 struct darwin_msg_async_io_complete message
= {.itransfer
= itransfer
, .result
= result
,
1723 .size
= (UInt32
) (uintptr_t) arg0
};
1725 usbi_dbg ("an async io operation has completed");
1727 /* if requested write a zero packet */
1728 if (kIOReturnSuccess
== result
&& IS_XFEROUT(transfer
) && transfer
->flags
& LIBUSB_TRANSFER_ADD_ZERO_PACKET
) {
1729 struct darwin_interface
*cInterface
;
1730 uint8_t iface
, pipeRef
;
1732 (void) ep_to_pipeRef (transfer
->dev_handle
, transfer
->endpoint
, &pipeRef
, &iface
);
1733 cInterface
= &priv
->interfaces
[iface
];
1735 (*(cInterface
->interface
))->WritePipe (cInterface
->interface
, pipeRef
, transfer
->buffer
, 0);
1738 /* send a completion message to the device's file descriptor */
1739 write (priv
->fds
[1], &message
, sizeof (message
));
1742 static int darwin_transfer_status (struct usbi_transfer
*itransfer
, kern_return_t result
) {
1743 if (itransfer
->flags
& USBI_TRANSFER_TIMED_OUT
)
1744 result
= kIOUSBTransactionTimeout
;
1747 case kIOReturnUnderrun
:
1748 case kIOReturnSuccess
:
1749 return LIBUSB_TRANSFER_COMPLETED
;
1750 case kIOReturnAborted
:
1751 return LIBUSB_TRANSFER_CANCELLED
;
1752 case kIOUSBPipeStalled
:
1753 usbi_dbg ("transfer error: pipe is stalled");
1754 return LIBUSB_TRANSFER_STALL
;
1755 case kIOReturnOverrun
:
1756 usbi_warn (ITRANSFER_CTX (itransfer
), "transfer error: data overrun");
1757 return LIBUSB_TRANSFER_OVERFLOW
;
1758 case kIOUSBTransactionTimeout
:
1759 usbi_warn (ITRANSFER_CTX (itransfer
), "transfer error: timed out");
1760 itransfer
->flags
|= USBI_TRANSFER_TIMED_OUT
;
1761 return LIBUSB_TRANSFER_TIMED_OUT
;
1763 usbi_warn (ITRANSFER_CTX (itransfer
), "transfer error: %s (value = 0x%08x)", darwin_error_str (result
), result
);
1764 return LIBUSB_TRANSFER_ERROR
;
1768 static void darwin_handle_callback (struct usbi_transfer
*itransfer
, kern_return_t result
, UInt32 io_size
) {
1769 struct libusb_transfer
*transfer
= USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer
);
1770 struct darwin_transfer_priv
*tpriv
= usbi_transfer_get_os_priv(itransfer
);
1771 int isIsoc
= LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
== transfer
->type
;
1772 int isBulk
= LIBUSB_TRANSFER_TYPE_BULK
== transfer
->type
;
1773 int isControl
= LIBUSB_TRANSFER_TYPE_CONTROL
== transfer
->type
;
1774 int isInterrupt
= LIBUSB_TRANSFER_TYPE_INTERRUPT
== transfer
->type
;
1777 if (!isIsoc
&& !isBulk
&& !isControl
&& !isInterrupt
) {
1778 usbi_err (TRANSFER_CTX(transfer
), "unknown endpoint type %d", transfer
->type
);
1782 usbi_dbg ("handling %s completion with kernel status %d",
1783 isControl
? "control" : isBulk
? "bulk" : isIsoc
? "isoc" : "interrupt", result
);
1785 if (kIOReturnSuccess
== result
|| kIOReturnUnderrun
== result
) {
1786 if (isIsoc
&& tpriv
->isoc_framelist
) {
1787 /* copy isochronous results back */
1789 for (i
= 0; i
< transfer
->num_iso_packets
; i
++) {
1790 struct libusb_iso_packet_descriptor
*lib_desc
= &transfer
->iso_packet_desc
[i
];
1791 lib_desc
->status
= darwin_to_libusb (tpriv
->isoc_framelist
[i
].frStatus
);
1792 lib_desc
->actual_length
= tpriv
->isoc_framelist
[i
].frActCount
;
1795 itransfer
->transferred
+= io_size
;
1798 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1799 usbi_handle_transfer_completion (itransfer
, darwin_transfer_status (itransfer
, result
));
1802 static int op_handle_events(struct libusb_context
*ctx
, struct pollfd
*fds
, POLL_NFDS_TYPE nfds
, int num_ready
) {
1803 struct darwin_msg_async_io_complete message
;
1804 POLL_NFDS_TYPE i
= 0;
1807 usbi_mutex_lock(&ctx
->open_devs_lock
);
1809 for (i
= 0; i
< nfds
&& num_ready
> 0; i
++) {
1810 struct pollfd
*pollfd
= &fds
[i
];
1812 usbi_dbg ("checking fd %i with revents = %x", pollfd
->fd
, pollfd
->revents
);
1814 if (!pollfd
->revents
)
1819 if (pollfd
->revents
& POLLERR
) {
1820 /* this probably will never happen so ignore the error an move on. */
1824 /* there is only one type of message */
1825 ret
= read (pollfd
->fd
, &message
, sizeof (message
));
1826 if (ret
< (ssize_t
) sizeof (message
)) {
1827 usbi_dbg ("WARNING: short read on async io completion pipe\n");
1831 darwin_handle_callback (message
.itransfer
, message
.result
, message
.size
);
1834 usbi_mutex_unlock(&ctx
->open_devs_lock
);
1839 static int darwin_clock_gettime(int clk_id
, struct timespec
*tp
) {
1840 mach_timespec_t sys_time
;
1841 clock_serv_t clock_ref
;
1844 case USBI_CLOCK_REALTIME
:
1845 /* CLOCK_REALTIME represents time since the epoch */
1846 clock_ref
= clock_realtime
;
1848 case USBI_CLOCK_MONOTONIC
:
1849 /* use system boot time as reference for the monotonic clock */
1850 clock_ref
= clock_monotonic
;
1853 return LIBUSB_ERROR_INVALID_PARAM
;
1856 clock_get_time (clock_ref
, &sys_time
);
1858 tp
->tv_sec
= sys_time
.tv_sec
;
1859 tp
->tv_nsec
= sys_time
.tv_nsec
;
1864 const struct usbi_os_backend darwin_backend
= {
1867 .init
= darwin_init
,
1868 .exit
= darwin_exit
,
1869 .get_device_list
= NULL
, /* not needed */
1870 .get_device_descriptor
= darwin_get_device_descriptor
,
1871 .get_active_config_descriptor
= darwin_get_active_config_descriptor
,
1872 .get_config_descriptor
= darwin_get_config_descriptor
,
1874 .open
= darwin_open
,
1875 .close
= darwin_close
,
1876 .get_configuration
= darwin_get_configuration
,
1877 .set_configuration
= darwin_set_configuration
,
1878 .claim_interface
= darwin_claim_interface
,
1879 .release_interface
= darwin_release_interface
,
1881 .set_interface_altsetting
= darwin_set_interface_altsetting
,
1882 .clear_halt
= darwin_clear_halt
,
1883 .reset_device
= darwin_reset_device
,
1885 .kernel_driver_active
= darwin_kernel_driver_active
,
1886 .detach_kernel_driver
= darwin_detach_kernel_driver
,
1887 .attach_kernel_driver
= darwin_attach_kernel_driver
,
1889 .destroy_device
= darwin_destroy_device
,
1891 .submit_transfer
= darwin_submit_transfer
,
1892 .cancel_transfer
= darwin_cancel_transfer
,
1893 .clear_transfer_priv
= darwin_clear_transfer_priv
,
1895 .handle_events
= op_handle_events
,
1897 .clock_gettime
= darwin_clock_gettime
,
1899 .device_priv_size
= sizeof(struct darwin_device_priv
),
1900 .device_handle_priv_size
= sizeof(struct darwin_device_handle_priv
),
1901 .transfer_priv_size
= sizeof(struct darwin_transfer_priv
),
1902 .add_iso_packet_size
= 0,