1 /* -*- Mode: C; indent-tabs-mode:nil -*- */
2 /*
3 * darwin backend for libusb 1.0
4 * Copyright © 2008-2017 Nathan Hjelm <hjelmn@users.sourceforge.net>
5 *
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.
10 *
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.
15 *
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
19 */
20
21 #include "config.h"
22 #include <time.h>
23 #include <ctype.h>
24 #include <errno.h>
25 #include <pthread.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <sys/types.h>
30 #include <unistd.h>
31 #include <fcntl.h>
32 #include <sys/sysctl.h>
33
34 #include <mach/clock.h>
35 #include <mach/clock_types.h>
36 #include <mach/mach_host.h>
37 #include <mach/mach_port.h>
38
39 /* Suppress warnings about the use of the deprecated objc_registerThreadWithCollector
40 * function. Its use is also conditionalized to only older deployment targets. */
41 #define OBJC_SILENCE_GC_DEPRECATIONS 1
42
43 #include <AvailabilityMacros.h>
44 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
45 #include <objc/objc-auto.h>
46 #endif
47
48 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 101200
49 /* Apple deprecated the darwin atomics in 10.12 in favor of C11 atomics */
50 #include <stdatomic.h>
51 #define libusb_darwin_atomic_fetch_add(x, y) atomic_fetch_add(x, y)
52
53 _Atomic int32_t initCount = ATOMIC_VAR_INIT(0);
54 #else
55 /* use darwin atomics if the target is older than 10.12 */
56 #include <libkern/OSAtomic.h>
57
58 /* OSAtomicAdd32Barrier returns the new value */
59 #define libusb_darwin_atomic_fetch_add(x, y) (OSAtomicAdd32Barrier(y, x) - y)
60
61 static volatile int32_t initCount = 0;
62
63 #endif
64
65 /* On 10.12 and later, use newly available clock_*() functions */
66 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 101200
67 #define OSX_USE_CLOCK_GETTIME 1
68 #else
69 #define OSX_USE_CLOCK_GETTIME 0
70 #endif
71
72 #include "darwin_usb.h"
73
74 /* async event thread */
75 static pthread_mutex_t libusb_darwin_at_mutex = PTHREAD_MUTEX_INITIALIZER;
76 static pthread_cond_t libusb_darwin_at_cond = PTHREAD_COND_INITIALIZER;
77
78 static pthread_once_t darwin_init_once = PTHREAD_ONCE_INIT;
79
80 #if !OSX_USE_CLOCK_GETTIME
81 static clock_serv_t clock_realtime;
82 static clock_serv_t clock_monotonic;
83 #endif
84
85 static CFRunLoopRef libusb_darwin_acfl = NULL; /* event cf loop */
86 static CFRunLoopSourceRef libusb_darwin_acfls = NULL; /* shutdown signal for event cf loop */
87
88 static usbi_mutex_t darwin_cached_devices_lock = PTHREAD_MUTEX_INITIALIZER;
89 static struct list_head darwin_cached_devices = {&darwin_cached_devices, &darwin_cached_devices};
90 static const char *darwin_device_class = kIOUSBDeviceClassName;
91
92 #define DARWIN_CACHED_DEVICE(a) ((struct darwin_cached_device *) (((struct darwin_device_priv *)((a)->os_priv))->dev))
93
94 /* async event thread */
95 static pthread_t libusb_darwin_at;
96
97 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
98 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
99 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
100 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
101 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
102
103 static int darwin_scan_devices(struct libusb_context *ctx);
104 static int process_new_device (struct libusb_context *ctx, io_service_t service);
105
106 #if defined(ENABLE_LOGGING)
darwin_error_str(int result)107 static const char *darwin_error_str (int result) {
108 static char string_buffer[50];
109 switch (result) {
110 case kIOReturnSuccess:
111 return "no error";
112 case kIOReturnNotOpen:
113 return "device not opened for exclusive access";
114 case kIOReturnNoDevice:
115 return "no connection to an IOService";
116 case kIOUSBNoAsyncPortErr:
117 return "no async port has been opened for interface";
118 case kIOReturnExclusiveAccess:
119 return "another process has device opened for exclusive access";
120 case kIOUSBPipeStalled:
121 return "pipe is stalled";
122 case kIOReturnError:
123 return "could not establish a connection to the Darwin kernel";
124 case kIOUSBTransactionTimeout:
125 return "transaction timed out";
126 case kIOReturnBadArgument:
127 return "invalid argument";
128 case kIOReturnAborted:
129 return "transaction aborted";
130 case kIOReturnNotResponding:
131 return "device not responding";
132 case kIOReturnOverrun:
133 return "data overrun";
134 case kIOReturnCannotWire:
135 return "physical memory can not be wired down";
136 case kIOReturnNoResources:
137 return "out of resources";
138 case kIOUSBHighSpeedSplitError:
139 return "high speed split error";
140 default:
141 snprintf(string_buffer, sizeof(string_buffer), "unknown error (0x%x)", result);
142 return string_buffer;
143 }
144 }
145 #endif
146
darwin_to_libusb(int result)147 static int darwin_to_libusb (int result) {
148 switch (result) {
149 case kIOReturnUnderrun:
150 case kIOReturnSuccess:
151 return LIBUSB_SUCCESS;
152 case kIOReturnNotOpen:
153 case kIOReturnNoDevice:
154 return LIBUSB_ERROR_NO_DEVICE;
155 case kIOReturnExclusiveAccess:
156 return LIBUSB_ERROR_ACCESS;
157 case kIOUSBPipeStalled:
158 return LIBUSB_ERROR_PIPE;
159 case kIOReturnBadArgument:
160 return LIBUSB_ERROR_INVALID_PARAM;
161 case kIOUSBTransactionTimeout:
162 return LIBUSB_ERROR_TIMEOUT;
163 case kIOReturnNotResponding:
164 case kIOReturnAborted:
165 case kIOReturnError:
166 case kIOUSBNoAsyncPortErr:
167 default:
168 return LIBUSB_ERROR_OTHER;
169 }
170 }
171
172 /* this function must be called with the darwin_cached_devices_lock held */
darwin_deref_cached_device(struct darwin_cached_device * cached_dev)173 static void darwin_deref_cached_device(struct darwin_cached_device *cached_dev) {
174 cached_dev->refcount--;
175 /* free the device and remove it from the cache */
176 if (0 == cached_dev->refcount) {
177 list_del(&cached_dev->list);
178
179 (*(cached_dev->device))->Release(cached_dev->device);
180 free (cached_dev);
181 }
182 }
183
darwin_ref_cached_device(struct darwin_cached_device * cached_dev)184 static void darwin_ref_cached_device(struct darwin_cached_device *cached_dev) {
185 cached_dev->refcount++;
186 }
187
ep_to_pipeRef(struct libusb_device_handle * dev_handle,uint8_t ep,uint8_t * pipep,uint8_t * ifcp,struct darwin_interface ** interface_out)188 static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp, struct darwin_interface **interface_out) {
189 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
190
191 /* current interface */
192 struct darwin_interface *cInterface;
193
194 int8_t i, iface;
195
196 usbi_dbg ("converting ep address 0x%02x to pipeRef and interface", ep);
197
198 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
199 cInterface = &priv->interfaces[iface];
200
201 if (dev_handle->claimed_interfaces & (1 << iface)) {
202 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
203 if (cInterface->endpoint_addrs[i] == ep) {
204 *pipep = i + 1;
205
206 if (ifcp)
207 *ifcp = iface;
208
209 if (interface_out)
210 *interface_out = cInterface;
211
212 usbi_dbg ("pipe %d on interface %d matches", *pipep, iface);
213 return 0;
214 }
215 }
216 }
217 }
218
219 /* No pipe found with the correct endpoint address */
220 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
221
222 return LIBUSB_ERROR_NOT_FOUND;
223 }
224
usb_setup_device_iterator(io_iterator_t * deviceIterator,UInt32 location)225 static int usb_setup_device_iterator (io_iterator_t *deviceIterator, UInt32 location) {
226 CFMutableDictionaryRef matchingDict = IOServiceMatching(darwin_device_class);
227
228 if (!matchingDict)
229 return kIOReturnError;
230
231 if (location) {
232 CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
233 &kCFTypeDictionaryKeyCallBacks,
234 &kCFTypeDictionaryValueCallBacks);
235
236 /* there are no unsigned CFNumber types so treat the value as signed. the OS seems to do this
237 internally (CFNumberType of locationID is kCFNumberSInt32Type) */
238 CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberSInt32Type, &location);
239
240 if (propertyMatchDict && locationCF) {
241 CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
242 CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
243 }
244 /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
245
246 /* release our references as per the Create Rule */
247 if (propertyMatchDict)
248 CFRelease (propertyMatchDict);
249 if (locationCF)
250 CFRelease (locationCF);
251 }
252
253 return IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, deviceIterator);
254 }
255
256 /* Returns 1 on success, 0 on failure. */
get_ioregistry_value_number(io_service_t service,CFStringRef property,CFNumberType type,void * p)257 static int get_ioregistry_value_number (io_service_t service, CFStringRef property, CFNumberType type, void *p) {
258 CFTypeRef cfNumber = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
259 int ret = 0;
260
261 if (cfNumber) {
262 if (CFGetTypeID(cfNumber) == CFNumberGetTypeID()) {
263 ret = CFNumberGetValue(cfNumber, type, p);
264 }
265
266 CFRelease (cfNumber);
267 }
268
269 return ret;
270 }
271
get_ioregistry_value_data(io_service_t service,CFStringRef property,ssize_t size,void * p)272 static int get_ioregistry_value_data (io_service_t service, CFStringRef property, ssize_t size, void *p) {
273 CFTypeRef cfData = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
274 int ret = 0;
275
276 if (cfData) {
277 if (CFGetTypeID (cfData) == CFDataGetTypeID ()) {
278 CFIndex length = CFDataGetLength (cfData);
279 if (length < size) {
280 size = length;
281 }
282
283 CFDataGetBytes (cfData, CFRangeMake(0, size), p);
284 ret = 1;
285 }
286
287 CFRelease (cfData);
288 }
289
290 return ret;
291 }
292
darwin_device_from_service(io_service_t service)293 static usb_device_t **darwin_device_from_service (io_service_t service)
294 {
295 io_cf_plugin_ref_t *plugInInterface = NULL;
296 usb_device_t **device;
297 kern_return_t result;
298 SInt32 score;
299
300 result = IOCreatePlugInInterfaceForService(service, kIOUSBDeviceUserClientTypeID,
301 kIOCFPlugInInterfaceID, &plugInInterface,
302 &score);
303
304 if (kIOReturnSuccess != result || !plugInInterface) {
305 usbi_dbg ("could not set up plugin for service: %s", darwin_error_str (result));
306 return NULL;
307 }
308
309 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
310 (LPVOID)&device);
311 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
312 (*plugInInterface)->Release (plugInInterface);
313
314 return device;
315 }
316
darwin_devices_attached(void * ptr,io_iterator_t add_devices)317 static void darwin_devices_attached (void *ptr, io_iterator_t add_devices) {
318 UNUSED(ptr);
319 struct libusb_context *ctx;
320 io_service_t service;
321
322 usbi_mutex_lock(&active_contexts_lock);
323
324 while ((service = IOIteratorNext(add_devices))) {
325 /* add this device to each active context's device list */
326 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
327 process_new_device (ctx, service);
328 }
329
330 IOObjectRelease(service);
331 }
332
333 usbi_mutex_unlock(&active_contexts_lock);
334 }
335
darwin_devices_detached(void * ptr,io_iterator_t rem_devices)336 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
337 UNUSED(ptr);
338 struct libusb_device *dev = NULL;
339 struct libusb_context *ctx;
340 struct darwin_cached_device *old_device;
341
342 io_service_t device;
343 UInt64 session;
344 int ret;
345
346 usbi_mutex_lock(&active_contexts_lock);
347
348 while ((device = IOIteratorNext (rem_devices)) != 0) {
349 /* get the location from the i/o registry */
350 ret = get_ioregistry_value_number (device, CFSTR("sessionID"), kCFNumberSInt64Type, &session);
351 IOObjectRelease (device);
352 if (!ret)
353 continue;
354
355 /* we need to match darwin_ref_cached_device call made in darwin_get_cached_device function
356 otherwise no cached device will ever get freed */
357 usbi_mutex_lock(&darwin_cached_devices_lock);
358 list_for_each_entry(old_device, &darwin_cached_devices, list, struct darwin_cached_device) {
359 if (old_device->session == session) {
360 darwin_deref_cached_device (old_device);
361 break;
362 }
363 }
364 usbi_mutex_unlock(&darwin_cached_devices_lock);
365
366 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
367 usbi_dbg ("notifying context %p of device disconnect", ctx);
368
369 dev = usbi_get_device_by_session_id(ctx, (unsigned long) session);
370 if (dev) {
371 /* signal the core that this device has been disconnected. the core will tear down this device
372 when the reference count reaches 0 */
373 usbi_disconnect_device(dev);
374 libusb_unref_device(dev);
375 }
376 }
377 }
378
379 usbi_mutex_unlock(&active_contexts_lock);
380 }
381
darwin_hotplug_poll(void)382 static void darwin_hotplug_poll (void)
383 {
384 /* not sure if 5 seconds will be too long/short but it should work ok */
385 mach_timespec_t timeout = {.tv_sec = 5, .tv_nsec = 0};
386
387 /* since a kernel thread may nodify the IOInterators used for
388 * hotplug notidication we can't just clear the iterators.
389 * instead just wait until all IOService providers are quiet */
390 (void) IOKitWaitQuiet (kIOMasterPortDefault, &timeout);
391 }
392
darwin_clear_iterator(io_iterator_t iter)393 static void darwin_clear_iterator (io_iterator_t iter) {
394 io_service_t device;
395
396 while ((device = IOIteratorNext (iter)) != 0)
397 IOObjectRelease (device);
398 }
399
darwin_event_thread_main(void * arg0)400 static void *darwin_event_thread_main (void *arg0) {
401 IOReturn kresult;
402 struct libusb_context *ctx = (struct libusb_context *)arg0;
403 CFRunLoopRef runloop;
404
405 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
406 /* Set this thread's name, so it can be seen in the debugger
407 and crash reports. */
408 pthread_setname_np ("org.libusb.device-hotplug");
409 #endif
410
411 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
412 /* Tell the Objective-C garbage collector about this thread.
413 This is required because, unlike NSThreads, pthreads are
414 not automatically registered. Although we don't use
415 Objective-C, we use CoreFoundation, which does.
416 Garbage collection support was entirely removed in 10.12,
417 so don't bother there. */
418 objc_registerThreadWithCollector();
419 #endif
420
421 /* hotplug (device arrival/removal) sources */
422 CFRunLoopSourceContext libusb_shutdown_cfsourcectx;
423 CFRunLoopSourceRef libusb_notification_cfsource;
424 io_notification_port_t libusb_notification_port;
425 io_iterator_t libusb_rem_device_iterator;
426 io_iterator_t libusb_add_device_iterator;
427
428 usbi_dbg ("creating hotplug event source");
429
430 runloop = CFRunLoopGetCurrent ();
431 CFRetain (runloop);
432
433 /* add the shutdown cfsource to the run loop */
434 memset(&libusb_shutdown_cfsourcectx, 0, sizeof(libusb_shutdown_cfsourcectx));
435 libusb_shutdown_cfsourcectx.info = runloop;
436 libusb_shutdown_cfsourcectx.perform = (void (*)(void *))CFRunLoopStop;
437 libusb_darwin_acfls = CFRunLoopSourceCreate(NULL, 0, &libusb_shutdown_cfsourcectx);
438 CFRunLoopAddSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode);
439
440 /* add the notification port to the run loop */
441 libusb_notification_port = IONotificationPortCreate (kIOMasterPortDefault);
442 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
443 CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
444
445 /* create notifications for removed devices */
446 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
447 IOServiceMatching(darwin_device_class),
448 darwin_devices_detached,
449 ctx, &libusb_rem_device_iterator);
450
451 if (kresult != kIOReturnSuccess) {
452 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
453
454 pthread_exit (NULL);
455 }
456
457 /* create notifications for attached devices */
458 kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification,
459 IOServiceMatching(darwin_device_class),
460 darwin_devices_attached,
461 ctx, &libusb_add_device_iterator);
462
463 if (kresult != kIOReturnSuccess) {
464 usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
465
466 pthread_exit (NULL);
467 }
468
469 /* arm notifiers */
470 darwin_clear_iterator (libusb_rem_device_iterator);
471 darwin_clear_iterator (libusb_add_device_iterator);
472
473 usbi_dbg ("darwin event thread ready to receive events");
474
475 /* signal the main thread that the hotplug runloop has been created. */
476 pthread_mutex_lock (&libusb_darwin_at_mutex);
477 libusb_darwin_acfl = runloop;
478 pthread_cond_signal (&libusb_darwin_at_cond);
479 pthread_mutex_unlock (&libusb_darwin_at_mutex);
480
481 /* run the runloop */
482 CFRunLoopRun();
483
484 usbi_dbg ("darwin event thread exiting");
485
486 /* remove the notification cfsource */
487 CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
488
489 /* remove the shutdown cfsource */
490 CFRunLoopRemoveSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode);
491
492 /* delete notification port */
493 IONotificationPortDestroy (libusb_notification_port);
494
495 /* delete iterators */
496 IOObjectRelease (libusb_rem_device_iterator);
497 IOObjectRelease (libusb_add_device_iterator);
498
499 CFRelease (libusb_darwin_acfls);
500 CFRelease (runloop);
501
502 libusb_darwin_acfls = NULL;
503 libusb_darwin_acfl = NULL;
504
505 pthread_exit (NULL);
506 }
507
508 /* cleanup function to destroy cached devices */
_darwin_finalize(void)509 static void __attribute__((destructor)) _darwin_finalize(void) {
510 struct darwin_cached_device *dev, *next;
511
512 usbi_mutex_lock(&darwin_cached_devices_lock);
513 list_for_each_entry_safe(dev, next, &darwin_cached_devices, list, struct darwin_cached_device) {
514 darwin_deref_cached_device(dev);
515 }
516 usbi_mutex_unlock(&darwin_cached_devices_lock);
517 }
518
darwin_check_version(void)519 static void darwin_check_version (void) {
520 /* adjust for changes in the USB stack in xnu 15 */
521 int sysctl_args[] = {CTL_KERN, KERN_OSRELEASE};
522 long version;
523 char version_string[256] = {'\0',};
524 size_t length = 256;
525
526 sysctl(sysctl_args, 2, version_string, &length, NULL, 0);
527
528 errno = 0;
529 version = strtol (version_string, NULL, 10);
530 if (0 == errno && version >= 15) {
531 darwin_device_class = "IOUSBHostDevice";
532 }
533 }
534
darwin_init(struct libusb_context * ctx)535 static int darwin_init(struct libusb_context *ctx) {
536 int rc;
537
538 rc = pthread_once (&darwin_init_once, darwin_check_version);
539 if (rc) {
540 return LIBUSB_ERROR_OTHER;
541 }
542
543 rc = darwin_scan_devices (ctx);
544 if (LIBUSB_SUCCESS != rc) {
545 return rc;
546 }
547
548 if (libusb_darwin_atomic_fetch_add (&initCount, 1) == 0) {
549 #if !OSX_USE_CLOCK_GETTIME
550 /* create the clocks that will be used if clock_gettime() is not available */
551 host_name_port_t host_self;
552
553 host_self = mach_host_self();
554 host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
555 host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
556 mach_port_deallocate(mach_task_self(), host_self);
557 #endif
558
559 pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, ctx);
560
561 pthread_mutex_lock (&libusb_darwin_at_mutex);
562 while (!libusb_darwin_acfl)
563 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
564 pthread_mutex_unlock (&libusb_darwin_at_mutex);
565 }
566
567 return rc;
568 }
569
darwin_exit(struct libusb_context * ctx)570 static void darwin_exit (struct libusb_context *ctx) {
571 UNUSED(ctx);
572 if (libusb_darwin_atomic_fetch_add (&initCount, -1) == 1) {
573 #if !OSX_USE_CLOCK_GETTIME
574 mach_port_deallocate(mach_task_self(), clock_realtime);
575 mach_port_deallocate(mach_task_self(), clock_monotonic);
576 #endif
577
578 /* stop the event runloop and wait for the thread to terminate. */
579 CFRunLoopSourceSignal(libusb_darwin_acfls);
580 CFRunLoopWakeUp (libusb_darwin_acfl);
581 pthread_join (libusb_darwin_at, NULL);
582 }
583 }
584
darwin_get_device_descriptor(struct libusb_device * dev,unsigned char * buffer,int * host_endian)585 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
586 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
587
588 /* return cached copy */
589 memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
590
591 *host_endian = 0;
592
593 return 0;
594 }
595
get_configuration_index(struct libusb_device * dev,int config_value)596 static int get_configuration_index (struct libusb_device *dev, int config_value) {
597 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
598 UInt8 i, numConfig;
599 IOUSBConfigurationDescriptorPtr desc;
600 IOReturn kresult;
601
602 /* is there a simpler way to determine the index? */
603 kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
604 if (kresult != kIOReturnSuccess)
605 return darwin_to_libusb (kresult);
606
607 for (i = 0 ; i < numConfig ; i++) {
608 (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
609
610 if (desc->bConfigurationValue == config_value)
611 return i;
612 }
613
614 /* configuration not found */
615 return LIBUSB_ERROR_NOT_FOUND;
616 }
617
darwin_get_active_config_descriptor(struct libusb_device * dev,unsigned char * buffer,size_t len,int * host_endian)618 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
619 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
620 int config_index;
621
622 if (0 == priv->active_config)
623 return LIBUSB_ERROR_NOT_FOUND;
624
625 config_index = get_configuration_index (dev, priv->active_config);
626 if (config_index < 0)
627 return config_index;
628
629 return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
630 }
631
darwin_get_config_descriptor(struct libusb_device * dev,uint8_t config_index,unsigned char * buffer,size_t len,int * host_endian)632 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
633 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
634 IOUSBConfigurationDescriptorPtr desc;
635 IOReturn kresult;
636 int ret;
637
638 if (!priv || !priv->device)
639 return LIBUSB_ERROR_OTHER;
640
641 kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
642 if (kresult == kIOReturnSuccess) {
643 /* copy descriptor */
644 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
645 len = libusb_le16_to_cpu(desc->wTotalLength);
646
647 memmove (buffer, desc, len);
648
649 /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
650 *host_endian = 0;
651 }
652
653 ret = darwin_to_libusb (kresult);
654 if (ret != LIBUSB_SUCCESS)
655 return ret;
656
657 return (int) len;
658 }
659
660 /* check whether the os has configured the device */
darwin_check_configuration(struct libusb_context * ctx,struct darwin_cached_device * dev)661 static int darwin_check_configuration (struct libusb_context *ctx, struct darwin_cached_device *dev) {
662 usb_device_t **darwin_device = dev->device;
663
664 IOUSBConfigurationDescriptorPtr configDesc;
665 IOUSBFindInterfaceRequest request;
666 kern_return_t kresult;
667 io_iterator_t interface_iterator;
668 io_service_t firstInterface;
669
670 if (dev->dev_descriptor.bNumConfigurations < 1) {
671 usbi_err (ctx, "device has no configurations");
672 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
673 }
674
675 /* checking the configuration of a root hub simulation takes ~1 s in 10.11. the device is
676 not usable anyway */
677 if (0x05ac == dev->dev_descriptor.idVendor && 0x8005 == dev->dev_descriptor.idProduct) {
678 usbi_dbg ("ignoring configuration on root hub simulation");
679 dev->active_config = 0;
680 return 0;
681 }
682
683 /* find the first configuration */
684 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
685 dev->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
686
687 /* check if the device is already configured. there is probably a better way than iterating over the
688 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
689 might lock up on the device request) */
690
691 /* Setup the Interface Request */
692 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
693 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
694 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
695 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
696
697 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
698 if (kresult)
699 return darwin_to_libusb (kresult);
700
701 /* iterate once */
702 firstInterface = IOIteratorNext(interface_iterator);
703
704 /* done with the interface iterator */
705 IOObjectRelease(interface_iterator);
706
707 if (firstInterface) {
708 IOObjectRelease (firstInterface);
709
710 /* device is configured */
711 if (dev->dev_descriptor.bNumConfigurations == 1)
712 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
713 dev->active_config = dev->first_config;
714 else
715 /* devices with more than one configuration should work with GetConfiguration */
716 (*darwin_device)->GetConfiguration (darwin_device, &dev->active_config);
717 } else
718 /* not configured */
719 dev->active_config = 0;
720
721 usbi_dbg ("active config: %u, first config: %u", dev->active_config, dev->first_config);
722
723 return 0;
724 }
725
darwin_request_descriptor(usb_device_t ** device,UInt8 desc,UInt8 desc_index,void * buffer,size_t buffer_size)726 static int darwin_request_descriptor (usb_device_t **device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
727 IOUSBDevRequestTO req;
728
729 memset (buffer, 0, buffer_size);
730
731 /* Set up request for descriptor/ */
732 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
733 req.bRequest = kUSBRqGetDescriptor;
734 req.wValue = desc << 8;
735 req.wIndex = desc_index;
736 req.wLength = buffer_size;
737 req.pData = buffer;
738 req.noDataTimeout = 20;
739 req.completionTimeout = 100;
740
741 return (*device)->DeviceRequestTO (device, &req);
742 }
743
darwin_cache_device_descriptor(struct libusb_context * ctx,struct darwin_cached_device * dev)744 static int darwin_cache_device_descriptor (struct libusb_context *ctx, struct darwin_cached_device *dev) {
745 usb_device_t **device = dev->device;
746 int retries = 1, delay = 30000;
747 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
748 int is_open = 0;
749 int ret = 0, ret2;
750 UInt8 bDeviceClass;
751 UInt16 idProduct, idVendor;
752
753 dev->can_enumerate = 0;
754
755 (*device)->GetDeviceClass (device, &bDeviceClass);
756 (*device)->GetDeviceProduct (device, &idProduct);
757 (*device)->GetDeviceVendor (device, &idVendor);
758
759 /* According to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
760 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
761 * to follow the spec as closely as possible, try opening the device */
762 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
763
764 do {
765 /**** retrieve device descriptor ****/
766 ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &dev->dev_descriptor, sizeof(dev->dev_descriptor));
767
768 if (kIOReturnOverrun == ret && kUSBDeviceDesc == dev->dev_descriptor.bDescriptorType)
769 /* received an overrun error but we still received a device descriptor */
770 ret = kIOReturnSuccess;
771
772 if (kIOUSBVendorIDAppleComputer == idVendor) {
773 /* NTH: don't bother retrying or unsuspending Apple devices */
774 break;
775 }
776
777 if (kIOReturnSuccess == ret && (0 == dev->dev_descriptor.bNumConfigurations ||
778 0 == dev->dev_descriptor.bcdUSB)) {
779 /* work around for incorrectly configured devices */
780 if (try_reconfigure && is_open) {
781 usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
782
783 /* set the first configuration */
784 (*device)->SetConfiguration(device, 1);
785
786 /* don't try to reconfigure again */
787 try_reconfigure = 0;
788 }
789
790 ret = kIOUSBPipeStalled;
791 }
792
793 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
794 /* device may be suspended. unsuspend it and try again */
795 #if DeviceVersion >= 320
796 UInt32 info = 0;
797
798 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
799 (void)(*device)->GetUSBDeviceInformation (device, &info);
800
801 /* note that the device was suspended */
802 if (info & (1 << kUSBInformationDeviceIsSuspendedBit) || 0 == info)
803 try_unsuspend = 1;
804 #endif
805
806 if (try_unsuspend) {
807 /* try to unsuspend the device */
808 ret2 = (*device)->USBDeviceSuspend (device, 0);
809 if (kIOReturnSuccess != ret2) {
810 /* prevent log spew from poorly behaving devices. this indicates the
811 os actually had trouble communicating with the device */
812 usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
813 } else
814 unsuspended = 1;
815
816 try_unsuspend = 0;
817 }
818 }
819
820 if (kIOReturnSuccess != ret) {
821 usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000);
822 /* sleep for a little while before trying again */
823 nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000UL}, NULL);
824 }
825 } while (kIOReturnSuccess != ret && retries--);
826
827 if (unsuspended)
828 /* resuspend the device */
829 (void)(*device)->USBDeviceSuspend (device, 1);
830
831 if (is_open)
832 (void) (*device)->USBDeviceClose (device);
833
834 if (ret != kIOReturnSuccess) {
835 /* a debug message was already printed out for this error */
836 if (LIBUSB_CLASS_HUB == bDeviceClass)
837 usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
838 idVendor, idProduct, darwin_error_str (ret), ret);
839 else
840 usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
841 idVendor, idProduct, darwin_error_str (ret), ret);
842 return darwin_to_libusb (ret);
843 }
844
845 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
846 if (libusb_le16_to_cpu (dev->dev_descriptor.idProduct) != idProduct) {
847 /* not a valid device */
848 usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
849 idProduct, libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
850 return LIBUSB_ERROR_NO_DEVICE;
851 }
852
853 usbi_dbg ("cached device descriptor:");
854 usbi_dbg (" bDescriptorType: 0x%02x", dev->dev_descriptor.bDescriptorType);
855 usbi_dbg (" bcdUSB: 0x%04x", dev->dev_descriptor.bcdUSB);
856 usbi_dbg (" bDeviceClass: 0x%02x", dev->dev_descriptor.bDeviceClass);
857 usbi_dbg (" bDeviceSubClass: 0x%02x", dev->dev_descriptor.bDeviceSubClass);
858 usbi_dbg (" bDeviceProtocol: 0x%02x", dev->dev_descriptor.bDeviceProtocol);
859 usbi_dbg (" bMaxPacketSize0: 0x%02x", dev->dev_descriptor.bMaxPacketSize0);
860 usbi_dbg (" idVendor: 0x%04x", dev->dev_descriptor.idVendor);
861 usbi_dbg (" idProduct: 0x%04x", dev->dev_descriptor.idProduct);
862 usbi_dbg (" bcdDevice: 0x%04x", dev->dev_descriptor.bcdDevice);
863 usbi_dbg (" iManufacturer: 0x%02x", dev->dev_descriptor.iManufacturer);
864 usbi_dbg (" iProduct: 0x%02x", dev->dev_descriptor.iProduct);
865 usbi_dbg (" iSerialNumber: 0x%02x", dev->dev_descriptor.iSerialNumber);
866 usbi_dbg (" bNumConfigurations: 0x%02x", dev->dev_descriptor.bNumConfigurations);
867
868 dev->can_enumerate = 1;
869
870 return LIBUSB_SUCCESS;
871 }
872
get_device_port(io_service_t service,UInt8 * port)873 static int get_device_port (io_service_t service, UInt8 *port) {
874 kern_return_t result;
875 io_service_t parent;
876 int ret = 0;
877
878 if (get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, port)) {
879 return 1;
880 }
881
882 result = IORegistryEntryGetParentEntry (service, kIOServicePlane, &parent);
883 if (kIOReturnSuccess == result) {
884 ret = get_ioregistry_value_data (parent, CFSTR("port"), 1, port);
885 IOObjectRelease (parent);
886 }
887
888 return ret;
889 }
890
get_device_parent_sessionID(io_service_t service,UInt64 * parent_sessionID)891 static int get_device_parent_sessionID(io_service_t service, UInt64 *parent_sessionID) {
892 kern_return_t result;
893 io_service_t parent;
894
895 /* Walk up the tree in the IOService plane until we find a parent that has a sessionID */
896 parent = service;
897 while((result = IORegistryEntryGetParentEntry (parent, kIOServicePlane, &parent)) == kIOReturnSuccess) {
898 if (get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, parent_sessionID)) {
899 /* Success */
900 return 1;
901 }
902 }
903
904 /* We ran out of parents */
905 return 0;
906 }
907
darwin_get_cached_device(struct libusb_context * ctx,io_service_t service,struct darwin_cached_device ** cached_out)908 static int darwin_get_cached_device(struct libusb_context *ctx, io_service_t service,
909 struct darwin_cached_device **cached_out) {
910 struct darwin_cached_device *new_device;
911 UInt64 sessionID = 0, parent_sessionID = 0;
912 int ret = LIBUSB_SUCCESS;
913 usb_device_t **device;
914 UInt8 port = 0;
915
916 /* get some info from the io registry */
917 (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
918 if (!get_device_port (service, &port)) {
919 usbi_dbg("could not get connected port number");
920 }
921
922 usbi_dbg("finding cached device for sessionID 0x%" PRIx64, sessionID);
923
924 if (get_device_parent_sessionID(service, &parent_sessionID)) {
925 usbi_dbg("parent sessionID: 0x%" PRIx64, parent_sessionID);
926 }
927
928 usbi_mutex_lock(&darwin_cached_devices_lock);
929 do {
930 *cached_out = NULL;
931
932 list_for_each_entry(new_device, &darwin_cached_devices, list, struct darwin_cached_device) {
933 usbi_dbg("matching sessionID 0x%" PRIx64 " against cached device with sessionID 0x%" PRIx64, sessionID, new_device->session);
934 if (new_device->session == sessionID) {
935 usbi_dbg("using cached device for device");
936 *cached_out = new_device;
937 break;
938 }
939 }
940
941 if (*cached_out)
942 break;
943
944 usbi_dbg("caching new device with sessionID 0x%" PRIx64, sessionID);
945
946 device = darwin_device_from_service (service);
947 if (!device) {
948 ret = LIBUSB_ERROR_NO_DEVICE;
949 break;
950 }
951
952 new_device = calloc (1, sizeof (*new_device));
953 if (!new_device) {
954 ret = LIBUSB_ERROR_NO_MEM;
955 break;
956 }
957
958 /* add this device to the cached device list */
959 list_add(&new_device->list, &darwin_cached_devices);
960
961 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
962
963 /* keep a reference to this device */
964 darwin_ref_cached_device(new_device);
965
966 new_device->device = device;
967 new_device->session = sessionID;
968 (*device)->GetLocationID (device, &new_device->location);
969 new_device->port = port;
970 new_device->parent_session = parent_sessionID;
971
972 /* cache the device descriptor */
973 ret = darwin_cache_device_descriptor(ctx, new_device);
974 if (ret)
975 break;
976
977 if (new_device->can_enumerate) {
978 snprintf(new_device->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", new_device->address,
979 new_device->dev_descriptor.idVendor, new_device->dev_descriptor.idProduct,
980 new_device->dev_descriptor.bDeviceClass, new_device->dev_descriptor.bDeviceSubClass);
981 }
982 } while (0);
983
984 usbi_mutex_unlock(&darwin_cached_devices_lock);
985
986 /* keep track of devices regardless of if we successfully enumerate them to
987 prevent them from being enumerated multiple times */
988
989 *cached_out = new_device;
990
991 return ret;
992 }
993
process_new_device(struct libusb_context * ctx,io_service_t service)994 static int process_new_device (struct libusb_context *ctx, io_service_t service) {
995 struct darwin_device_priv *priv;
996 struct libusb_device *dev = NULL;
997 struct darwin_cached_device *cached_device;
998 UInt8 devSpeed;
999 int ret = 0;
1000
1001 do {
1002 ret = darwin_get_cached_device (ctx, service, &cached_device);
1003
1004 if (ret < 0 || !cached_device->can_enumerate) {
1005 return ret;
1006 }
1007
1008 /* check current active configuration (and cache the first configuration value--
1009 which may be used by claim_interface) */
1010 ret = darwin_check_configuration (ctx, cached_device);
1011 if (ret)
1012 break;
1013
1014 usbi_dbg ("allocating new device in context %p for with session 0x%" PRIx64,
1015 ctx, cached_device->session);
1016
1017 dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
1018 if (!dev) {
1019 return LIBUSB_ERROR_NO_MEM;
1020 }
1021
1022 priv = (struct darwin_device_priv *)dev->os_priv;
1023
1024 priv->dev = cached_device;
1025 darwin_ref_cached_device (priv->dev);
1026
1027 if (cached_device->parent_session > 0) {
1028 dev->parent_dev = usbi_get_device_by_session_id (ctx, (unsigned long) cached_device->parent_session);
1029 } else {
1030 dev->parent_dev = NULL;
1031 }
1032 dev->port_number = cached_device->port;
1033 dev->bus_number = cached_device->location >> 24;
1034 dev->device_address = cached_device->address;
1035
1036 (*(priv->dev->device))->GetDeviceSpeed (priv->dev->device, &devSpeed);
1037
1038 switch (devSpeed) {
1039 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
1040 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
1041 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
1042 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
1043 case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
1044 #endif
1045 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101200
1046 case kUSBDeviceSpeedSuperPlus: dev->speed = LIBUSB_SPEED_SUPER_PLUS; break;
1047 #endif
1048 default:
1049 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
1050 }
1051
1052 ret = usbi_sanitize_device (dev);
1053 if (ret < 0)
1054 break;
1055
1056 usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address,
1057 dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path);
1058 } while (0);
1059
1060 if (0 == ret) {
1061 usbi_connect_device (dev);
1062 } else {
1063 libusb_unref_device (dev);
1064 }
1065
1066 return ret;
1067 }
1068
darwin_scan_devices(struct libusb_context * ctx)1069 static int darwin_scan_devices(struct libusb_context *ctx) {
1070 io_iterator_t deviceIterator;
1071 io_service_t service;
1072 kern_return_t kresult;
1073
1074 kresult = usb_setup_device_iterator (&deviceIterator, 0);
1075 if (kresult != kIOReturnSuccess)
1076 return darwin_to_libusb (kresult);
1077
1078 while ((service = IOIteratorNext (deviceIterator))) {
1079 (void) process_new_device (ctx, service);
1080
1081 IOObjectRelease(service);
1082 }
1083
1084 IOObjectRelease(deviceIterator);
1085
1086 return 0;
1087 }
1088
darwin_open(struct libusb_device_handle * dev_handle)1089 static int darwin_open (struct libusb_device_handle *dev_handle) {
1090 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1091 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1092 IOReturn kresult;
1093
1094 if (0 == dpriv->open_count) {
1095 /* try to open the device */
1096 kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
1097 if (kresult != kIOReturnSuccess) {
1098 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
1099
1100 if (kIOReturnExclusiveAccess != kresult) {
1101 return darwin_to_libusb (kresult);
1102 }
1103
1104 /* it is possible to perform some actions on a device that is not open so do not return an error */
1105 priv->is_open = 0;
1106 } else {
1107 priv->is_open = 1;
1108 }
1109
1110 /* create async event source */
1111 kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
1112 if (kresult != kIOReturnSuccess) {
1113 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
1114
1115 if (priv->is_open) {
1116 (*(dpriv->device))->USBDeviceClose (dpriv->device);
1117 }
1118
1119 priv->is_open = 0;
1120
1121 return darwin_to_libusb (kresult);
1122 }
1123
1124 CFRetain (libusb_darwin_acfl);
1125
1126 /* add the cfSource to the aync run loop */
1127 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
1128 }
1129
1130 /* device opened successfully */
1131 dpriv->open_count++;
1132
1133 usbi_dbg ("device open for access");
1134
1135 return 0;
1136 }
1137
darwin_close(struct libusb_device_handle * dev_handle)1138 static void darwin_close (struct libusb_device_handle *dev_handle) {
1139 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1140 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1141 IOReturn kresult;
1142 int i;
1143
1144 if (dpriv->open_count == 0) {
1145 /* something is probably very wrong if this is the case */
1146 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!");
1147 return;
1148 }
1149
1150 dpriv->open_count--;
1151
1152 /* make sure all interfaces are released */
1153 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1154 if (dev_handle->claimed_interfaces & (1 << i))
1155 libusb_release_interface (dev_handle, i);
1156
1157 if (0 == dpriv->open_count) {
1158 /* delete the device's async event source */
1159 if (priv->cfSource) {
1160 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
1161 CFRelease (priv->cfSource);
1162 priv->cfSource = NULL;
1163 CFRelease (libusb_darwin_acfl);
1164 }
1165
1166 if (priv->is_open) {
1167 /* close the device */
1168 kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
1169 if (kresult) {
1170 /* Log the fact that we had a problem closing the file, however failing a
1171 * close isn't really an error, so return success anyway */
1172 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
1173 }
1174 }
1175 }
1176 }
1177
darwin_get_configuration(struct libusb_device_handle * dev_handle,int * config)1178 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
1179 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1180
1181 *config = (int) dpriv->active_config;
1182
1183 return 0;
1184 }
1185
darwin_set_configuration(struct libusb_device_handle * dev_handle,int config)1186 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
1187 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1188 IOReturn kresult;
1189 int i;
1190
1191 /* Setting configuration will invalidate the interface, so we need
1192 to reclaim it. First, dispose of existing interfaces, if any. */
1193 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1194 if (dev_handle->claimed_interfaces & (1 << i))
1195 darwin_release_interface (dev_handle, i);
1196
1197 kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
1198 if (kresult != kIOReturnSuccess)
1199 return darwin_to_libusb (kresult);
1200
1201 /* Reclaim any interfaces. */
1202 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1203 if (dev_handle->claimed_interfaces & (1 << i))
1204 darwin_claim_interface (dev_handle, i);
1205
1206 dpriv->active_config = config;
1207
1208 return 0;
1209 }
1210
darwin_get_interface(usb_device_t ** darwin_device,uint8_t ifc,io_service_t * usbInterfacep)1211 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
1212 IOUSBFindInterfaceRequest request;
1213 kern_return_t kresult;
1214 io_iterator_t interface_iterator;
1215 UInt8 bInterfaceNumber;
1216 int ret;
1217
1218 *usbInterfacep = IO_OBJECT_NULL;
1219
1220 /* Setup the Interface Request */
1221 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
1222 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1223 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1224 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
1225
1226 kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1227 if (kresult)
1228 return kresult;
1229
1230 while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
1231 /* find the interface number */
1232 ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
1233 &bInterfaceNumber);
1234
1235 if (ret && bInterfaceNumber == ifc) {
1236 break;
1237 }
1238
1239 (void) IOObjectRelease (*usbInterfacep);
1240 }
1241
1242 /* done with the interface iterator */
1243 IOObjectRelease(interface_iterator);
1244
1245 return 0;
1246 }
1247
get_endpoints(struct libusb_device_handle * dev_handle,int iface)1248 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
1249 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1250
1251 /* current interface */
1252 struct darwin_interface *cInterface = &priv->interfaces[iface];
1253
1254 kern_return_t kresult;
1255
1256 UInt8 numep, direction, number;
1257 UInt8 dont_care1, dont_care3;
1258 UInt16 dont_care2;
1259 int rc;
1260
1261 usbi_dbg ("building table of endpoints.");
1262
1263 /* retrieve the total number of endpoints on this interface */
1264 kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
1265 if (kresult) {
1266 usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1267 return darwin_to_libusb (kresult);
1268 }
1269
1270 /* iterate through pipe references */
1271 for (int i = 1 ; i <= numep ; i++) {
1272 kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1273 &dont_care2, &dont_care3);
1274
1275 if (kresult != kIOReturnSuccess) {
1276 /* probably a buggy device. try to get the endpoint address from the descriptors */
1277 struct libusb_config_descriptor *config;
1278 const struct libusb_endpoint_descriptor *endpoint_desc;
1279 UInt8 alt_setting;
1280
1281 kresult = (*(cInterface->interface))->GetAlternateSetting (cInterface->interface, &alt_setting);
1282 if (kresult) {
1283 usbi_err (HANDLE_CTX (dev_handle), "can't get alternate setting for interface");
1284 return darwin_to_libusb (kresult);
1285 }
1286
1287 rc = libusb_get_active_config_descriptor (dev_handle->dev, &config);
1288 if (LIBUSB_SUCCESS != rc) {
1289 return rc;
1290 }
1291
1292 endpoint_desc = config->interface[iface].altsetting[alt_setting].endpoint + i - 1;
1293
1294 cInterface->endpoint_addrs[i - 1] = endpoint_desc->bEndpointAddress;
1295 } else {
1296 cInterface->endpoint_addrs[i - 1] = (((kUSBIn == direction) << kUSBRqDirnShift) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1297 }
1298
1299 usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, cInterface->endpoint_addrs[i - 1] >> kUSBRqDirnShift,
1300 cInterface->endpoint_addrs[i - 1] & LIBUSB_ENDPOINT_ADDRESS_MASK);
1301 }
1302
1303 cInterface->num_endpoints = numep;
1304
1305 return 0;
1306 }
1307
darwin_claim_interface(struct libusb_device_handle * dev_handle,int iface)1308 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1309 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1310 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1311 io_service_t usbInterface = IO_OBJECT_NULL;
1312 IOReturn kresult;
1313 IOCFPlugInInterface **plugInInterface = NULL;
1314 SInt32 score;
1315
1316 /* current interface */
1317 struct darwin_interface *cInterface = &priv->interfaces[iface];
1318
1319 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1320 if (kresult != kIOReturnSuccess)
1321 return darwin_to_libusb (kresult);
1322
1323 /* make sure we have an interface */
1324 if (!usbInterface && dpriv->first_config != 0) {
1325 usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1326
1327 /* set the configuration */
1328 kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1329 if (kresult != LIBUSB_SUCCESS) {
1330 usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1331 return kresult;
1332 }
1333
1334 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1335 if (kresult) {
1336 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1337 return darwin_to_libusb (kresult);
1338 }
1339 }
1340
1341 if (!usbInterface) {
1342 usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1343 return LIBUSB_ERROR_NOT_FOUND;
1344 }
1345
1346 /* get an interface to the device's interface */
1347 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1348 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1349
1350 /* ignore release error */
1351 (void)IOObjectRelease (usbInterface);
1352
1353 if (kresult) {
1354 usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1355 return darwin_to_libusb (kresult);
1356 }
1357
1358 if (!plugInInterface) {
1359 usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1360 return LIBUSB_ERROR_NOT_FOUND;
1361 }
1362
1363 /* Do the actual claim */
1364 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1365 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1366 (LPVOID)&cInterface->interface);
1367 /* We no longer need the intermediate plug-in */
1368 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1369 (*plugInInterface)->Release (plugInInterface);
1370 if (kresult || !cInterface->interface) {
1371 usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1372 return darwin_to_libusb (kresult);
1373 }
1374
1375 /* claim the interface */
1376 kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1377 if (kresult) {
1378 usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1379 return darwin_to_libusb (kresult);
1380 }
1381
1382 /* update list of endpoints */
1383 kresult = get_endpoints (dev_handle, iface);
1384 if (kresult) {
1385 /* this should not happen */
1386 darwin_release_interface (dev_handle, iface);
1387 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1388 return kresult;
1389 }
1390
1391 cInterface->cfSource = NULL;
1392
1393 /* create async event source */
1394 kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1395 if (kresult != kIOReturnSuccess) {
1396 usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1397
1398 /* can't continue without an async event source */
1399 (void)darwin_release_interface (dev_handle, iface);
1400
1401 return darwin_to_libusb (kresult);
1402 }
1403
1404 /* add the cfSource to the async thread's run loop */
1405 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1406
1407 usbi_dbg ("interface opened");
1408
1409 return 0;
1410 }
1411
darwin_release_interface(struct libusb_device_handle * dev_handle,int iface)1412 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1413 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1414 IOReturn kresult;
1415
1416 /* current interface */
1417 struct darwin_interface *cInterface = &priv->interfaces[iface];
1418
1419 /* Check to see if an interface is open */
1420 if (!cInterface->interface)
1421 return LIBUSB_SUCCESS;
1422
1423 /* clean up endpoint data */
1424 cInterface->num_endpoints = 0;
1425
1426 /* delete the interface's async event source */
1427 if (cInterface->cfSource) {
1428 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1429 CFRelease (cInterface->cfSource);
1430 }
1431
1432 kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1433 if (kresult)
1434 usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1435
1436 kresult = (*(cInterface->interface))->Release(cInterface->interface);
1437 if (kresult != kIOReturnSuccess)
1438 usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1439
1440 cInterface->interface = (usb_interface_t **) IO_OBJECT_NULL;
1441
1442 return darwin_to_libusb (kresult);
1443 }
1444
darwin_set_interface_altsetting(struct libusb_device_handle * dev_handle,int iface,int altsetting)1445 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1446 struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1447 IOReturn kresult;
1448
1449 /* current interface */
1450 struct darwin_interface *cInterface = &priv->interfaces[iface];
1451
1452 if (!cInterface->interface)
1453 return LIBUSB_ERROR_NO_DEVICE;
1454
1455 kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1456 if (kresult != kIOReturnSuccess)
1457 darwin_reset_device (dev_handle);
1458
1459 /* update list of endpoints */
1460 kresult = get_endpoints (dev_handle, iface);
1461 if (kresult) {
1462 /* this should not happen */
1463 darwin_release_interface (dev_handle, iface);
1464 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1465 return kresult;
1466 }
1467
1468 return darwin_to_libusb (kresult);
1469 }
1470
darwin_clear_halt(struct libusb_device_handle * dev_handle,unsigned char endpoint)1471 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1472 /* current interface */
1473 struct darwin_interface *cInterface;
1474 IOReturn kresult;
1475 uint8_t pipeRef;
1476
1477 /* determine the interface/endpoint to use */
1478 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, NULL, &cInterface) != 0) {
1479 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1480
1481 return LIBUSB_ERROR_NOT_FOUND;
1482 }
1483
1484 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1485 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1486 if (kresult)
1487 usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1488
1489 return darwin_to_libusb (kresult);
1490 }
1491
darwin_reset_device(struct libusb_device_handle * dev_handle)1492 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1493 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1494 IOUSBDeviceDescriptor descriptor;
1495 IOUSBConfigurationDescriptorPtr cached_configuration;
1496 IOUSBConfigurationDescriptor configuration;
1497 bool reenumerate = false;
1498 IOReturn kresult;
1499 int i;
1500
1501 kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1502 if (kresult) {
1503 usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1504 return darwin_to_libusb (kresult);
1505 }
1506
1507 do {
1508 usbi_dbg ("darwin/reset_device: checking if device descriptor changed");
1509
1510 /* ignore return code. if we can't get a descriptor it might be worthwhile re-enumerating anway */
1511 (void) darwin_request_descriptor (dpriv->device, kUSBDeviceDesc, 0, &descriptor, sizeof (descriptor));
1512
1513 /* check if the device descriptor has changed */
1514 if (0 != memcmp (&dpriv->dev_descriptor, &descriptor, sizeof (descriptor))) {
1515 reenumerate = true;
1516 break;
1517 }
1518
1519 /* check if any configuration descriptor has changed */
1520 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
1521 usbi_dbg ("darwin/reset_device: checking if configuration descriptor %d changed", i);
1522
1523 (void) darwin_request_descriptor (dpriv->device, kUSBConfDesc, i, &configuration, sizeof (configuration));
1524 (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
1525
1526 if (!cached_configuration || 0 != memcmp (cached_configuration, &configuration, sizeof (configuration))) {
1527 reenumerate = true;
1528 break;
1529 }
1530 }
1531 } while (0);
1532
1533 if (reenumerate) {
1534 usbi_dbg ("darwin/reset_device: device requires reenumeration");
1535 (void) (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
1536 return LIBUSB_ERROR_NOT_FOUND;
1537 }
1538
1539 usbi_dbg ("darwin/reset_device: device reset complete");
1540
1541 return LIBUSB_SUCCESS;
1542 }
1543
darwin_kernel_driver_active(struct libusb_device_handle * dev_handle,int interface)1544 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1545 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1546 io_service_t usbInterface;
1547 CFTypeRef driver;
1548 IOReturn kresult;
1549
1550 kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1551 if (kresult) {
1552 usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1553
1554 return darwin_to_libusb (kresult);
1555 }
1556
1557 driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1558 IOObjectRelease (usbInterface);
1559
1560 if (driver) {
1561 CFRelease (driver);
1562
1563 return 1;
1564 }
1565
1566 /* no driver */
1567 return 0;
1568 }
1569
1570 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
darwin_attach_kernel_driver(struct libusb_device_handle * dev_handle,int interface)1571 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1572 UNUSED(dev_handle);
1573 UNUSED(interface);
1574 return LIBUSB_ERROR_NOT_SUPPORTED;
1575 }
1576
darwin_detach_kernel_driver(struct libusb_device_handle * dev_handle,int interface)1577 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1578 UNUSED(dev_handle);
1579 UNUSED(interface);
1580 return LIBUSB_ERROR_NOT_SUPPORTED;
1581 }
1582
darwin_destroy_device(struct libusb_device * dev)1583 static void darwin_destroy_device(struct libusb_device *dev) {
1584 struct darwin_device_priv *dpriv = (struct darwin_device_priv *) dev->os_priv;
1585
1586 if (dpriv->dev) {
1587 /* need to hold the lock in case this is the last reference to the device */
1588 usbi_mutex_lock(&darwin_cached_devices_lock);
1589 darwin_deref_cached_device (dpriv->dev);
1590 dpriv->dev = NULL;
1591 usbi_mutex_unlock(&darwin_cached_devices_lock);
1592 }
1593 }
1594
submit_bulk_transfer(struct usbi_transfer * itransfer)1595 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1596 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1597
1598 IOReturn ret;
1599 uint8_t transferType;
1600 /* None of the values below are used in libusbx for bulk transfers */
1601 uint8_t direction, number, interval, pipeRef;
1602 uint16_t maxPacketSize;
1603
1604 struct darwin_interface *cInterface;
1605
1606 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1607 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1608
1609 return LIBUSB_ERROR_NOT_FOUND;
1610 }
1611
1612 ret = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1613 &transferType, &maxPacketSize, &interval);
1614
1615 if (ret) {
1616 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1617 darwin_error_str(ret), ret);
1618 return darwin_to_libusb (ret);
1619 }
1620
1621 if (0 != (transfer->length % maxPacketSize)) {
1622 /* do not need a zero packet */
1623 transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
1624 }
1625
1626 /* submit the request */
1627 /* timeouts are unavailable on interrupt endpoints */
1628 if (transferType == kUSBInterrupt) {
1629 if (IS_XFERIN(transfer))
1630 ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1631 transfer->length, darwin_async_io_callback, itransfer);
1632 else
1633 ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1634 transfer->length, darwin_async_io_callback, itransfer);
1635 } else {
1636 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1637
1638 if (IS_XFERIN(transfer))
1639 ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1640 transfer->length, transfer->timeout, transfer->timeout,
1641 darwin_async_io_callback, (void *)itransfer);
1642 else
1643 ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1644 transfer->length, transfer->timeout, transfer->timeout,
1645 darwin_async_io_callback, (void *)itransfer);
1646 }
1647
1648 if (ret)
1649 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1650 darwin_error_str(ret), ret);
1651
1652 return darwin_to_libusb (ret);
1653 }
1654
1655 #if InterfaceVersion >= 550
submit_stream_transfer(struct usbi_transfer * itransfer)1656 static int submit_stream_transfer(struct usbi_transfer *itransfer) {
1657 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1658 struct darwin_interface *cInterface;
1659 uint8_t pipeRef;
1660 IOReturn ret;
1661
1662 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1663 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1664
1665 return LIBUSB_ERROR_NOT_FOUND;
1666 }
1667
1668 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1669
1670 if (IS_XFERIN(transfer))
1671 ret = (*(cInterface->interface))->ReadStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1672 transfer->buffer, transfer->length, transfer->timeout,
1673 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1674 else
1675 ret = (*(cInterface->interface))->WriteStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
1676 transfer->buffer, transfer->length, transfer->timeout,
1677 transfer->timeout, darwin_async_io_callback, (void *)itransfer);
1678
1679 if (ret)
1680 usbi_err (TRANSFER_CTX (transfer), "bulk stream transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1681 darwin_error_str(ret), ret);
1682
1683 return darwin_to_libusb (ret);
1684 }
1685 #endif
1686
submit_iso_transfer(struct usbi_transfer * itransfer)1687 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1688 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1689 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1690
1691 IOReturn kresult;
1692 uint8_t direction, number, interval, pipeRef, transferType;
1693 uint16_t maxPacketSize;
1694 UInt64 frame;
1695 AbsoluteTime atTime;
1696 int i;
1697
1698 struct darwin_interface *cInterface;
1699
1700 /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1701 if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1702 free(tpriv->isoc_framelist);
1703 tpriv->isoc_framelist = NULL;
1704 }
1705
1706 if (!tpriv->isoc_framelist) {
1707 tpriv->num_iso_packets = transfer->num_iso_packets;
1708 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1709 if (!tpriv->isoc_framelist)
1710 return LIBUSB_ERROR_NO_MEM;
1711 }
1712
1713 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1714 for (i = 0 ; i < transfer->num_iso_packets ; i++)
1715 tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1716
1717 /* determine the interface/endpoint to use */
1718 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1719 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1720
1721 return LIBUSB_ERROR_NOT_FOUND;
1722 }
1723
1724 /* determine the properties of this endpoint and the speed of the device */
1725 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1726 &transferType, &maxPacketSize, &interval);
1727
1728 /* Last but not least we need the bus frame number */
1729 kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1730 if (kresult) {
1731 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1732 free(tpriv->isoc_framelist);
1733 tpriv->isoc_framelist = NULL;
1734
1735 return darwin_to_libusb (kresult);
1736 }
1737
1738 (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1739 &transferType, &maxPacketSize, &interval);
1740
1741 /* schedule for a frame a little in the future */
1742 frame += 4;
1743
1744 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1745 frame = cInterface->frames[transfer->endpoint];
1746
1747 /* submit the request */
1748 if (IS_XFERIN(transfer))
1749 kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1750 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1751 itransfer);
1752 else
1753 kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1754 transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1755 itransfer);
1756
1757 if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
1758 /* Full speed */
1759 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1));
1760 else
1761 /* High/super speed */
1762 cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1)) / 8;
1763
1764 if (kresult != kIOReturnSuccess) {
1765 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1766 darwin_error_str(kresult));
1767 free (tpriv->isoc_framelist);
1768 tpriv->isoc_framelist = NULL;
1769 }
1770
1771 return darwin_to_libusb (kresult);
1772 }
1773
submit_control_transfer(struct usbi_transfer * itransfer)1774 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1775 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1776 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1777 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1778 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1779
1780 IOReturn kresult;
1781
1782 memset(&tpriv->req, 0, sizeof(tpriv->req));
1783
1784 /* IOUSBDeviceInterface expects the request in cpu endianness */
1785 tpriv->req.bmRequestType = setup->bmRequestType;
1786 tpriv->req.bRequest = setup->bRequest;
1787 /* these values should be in bus order from libusb_fill_control_setup */
1788 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
1789 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
1790 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
1791 /* data is stored after the libusb control block */
1792 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1793 tpriv->req.completionTimeout = transfer->timeout;
1794 tpriv->req.noDataTimeout = transfer->timeout;
1795
1796 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1797
1798 /* all transfers in libusb-1.0 are async */
1799
1800 if (transfer->endpoint) {
1801 struct darwin_interface *cInterface;
1802 uint8_t pipeRef;
1803
1804 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
1805 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1806
1807 return LIBUSB_ERROR_NOT_FOUND;
1808 }
1809
1810 kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1811 } else
1812 /* control request on endpoint 0 */
1813 kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1814
1815 if (kresult != kIOReturnSuccess)
1816 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1817
1818 return darwin_to_libusb (kresult);
1819 }
1820
darwin_submit_transfer(struct usbi_transfer * itransfer)1821 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1822 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1823
1824 switch (transfer->type) {
1825 case LIBUSB_TRANSFER_TYPE_CONTROL:
1826 return submit_control_transfer(itransfer);
1827 case LIBUSB_TRANSFER_TYPE_BULK:
1828 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1829 return submit_bulk_transfer(itransfer);
1830 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1831 return submit_iso_transfer(itransfer);
1832 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1833 #if InterfaceVersion >= 550
1834 return submit_stream_transfer(itransfer);
1835 #else
1836 usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version does not support bulk stream transfers");
1837 return LIBUSB_ERROR_NOT_SUPPORTED;
1838 #endif
1839 default:
1840 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1841 return LIBUSB_ERROR_INVALID_PARAM;
1842 }
1843 }
1844
cancel_control_transfer(struct usbi_transfer * itransfer)1845 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1846 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1847 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1848 IOReturn kresult;
1849
1850 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
1851
1852 if (!dpriv->device)
1853 return LIBUSB_ERROR_NO_DEVICE;
1854
1855 kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1856
1857 return darwin_to_libusb (kresult);
1858 }
1859
darwin_abort_transfers(struct usbi_transfer * itransfer)1860 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1861 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1862 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
1863 struct darwin_interface *cInterface;
1864 uint8_t pipeRef, iface;
1865 IOReturn kresult;
1866
1867 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface, &cInterface) != 0) {
1868 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1869
1870 return LIBUSB_ERROR_NOT_FOUND;
1871 }
1872
1873 if (!dpriv->device)
1874 return LIBUSB_ERROR_NO_DEVICE;
1875
1876 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef);
1877
1878 /* abort transactions */
1879 #if InterfaceVersion >= 550
1880 if (LIBUSB_TRANSFER_TYPE_BULK_STREAM == transfer->type)
1881 (*(cInterface->interface))->AbortStreamsPipe (cInterface->interface, pipeRef, itransfer->stream_id);
1882 else
1883 #endif
1884 (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1885
1886 usbi_dbg ("calling clear pipe stall to clear the data toggle bit");
1887
1888 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1889 kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1890
1891 return darwin_to_libusb (kresult);
1892 }
1893
darwin_cancel_transfer(struct usbi_transfer * itransfer)1894 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1895 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1896
1897 switch (transfer->type) {
1898 case LIBUSB_TRANSFER_TYPE_CONTROL:
1899 return cancel_control_transfer(itransfer);
1900 case LIBUSB_TRANSFER_TYPE_BULK:
1901 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1902 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1903 return darwin_abort_transfers (itransfer);
1904 default:
1905 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1906 return LIBUSB_ERROR_INVALID_PARAM;
1907 }
1908 }
1909
darwin_clear_transfer_priv(struct usbi_transfer * itransfer)1910 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1911 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1912 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1913
1914 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1915 free (tpriv->isoc_framelist);
1916 tpriv->isoc_framelist = NULL;
1917 }
1918 }
1919
darwin_async_io_callback(void * refcon,IOReturn result,void * arg0)1920 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1921 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1922 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1923 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1924
1925 usbi_dbg ("an async io operation has completed");
1926
1927 /* if requested write a zero packet */
1928 if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
1929 struct darwin_interface *cInterface;
1930 uint8_t pipeRef;
1931
1932 (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface);
1933
1934 (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
1935 }
1936
1937 tpriv->result = result;
1938 tpriv->size = (UInt32) (uintptr_t) arg0;
1939
1940 /* signal the core that this transfer is complete */
1941 usbi_signal_transfer_completion(itransfer);
1942 }
1943
darwin_transfer_status(struct usbi_transfer * itransfer,kern_return_t result)1944 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1945 if (itransfer->timeout_flags & USBI_TRANSFER_TIMED_OUT)
1946 result = kIOUSBTransactionTimeout;
1947
1948 switch (result) {
1949 case kIOReturnUnderrun:
1950 case kIOReturnSuccess:
1951 return LIBUSB_TRANSFER_COMPLETED;
1952 case kIOReturnAborted:
1953 return LIBUSB_TRANSFER_CANCELLED;
1954 case kIOUSBPipeStalled:
1955 usbi_dbg ("transfer error: pipe is stalled");
1956 return LIBUSB_TRANSFER_STALL;
1957 case kIOReturnOverrun:
1958 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1959 return LIBUSB_TRANSFER_OVERFLOW;
1960 case kIOUSBTransactionTimeout:
1961 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1962 itransfer->timeout_flags |= USBI_TRANSFER_TIMED_OUT;
1963 return LIBUSB_TRANSFER_TIMED_OUT;
1964 default:
1965 usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1966 return LIBUSB_TRANSFER_ERROR;
1967 }
1968 }
1969
darwin_handle_transfer_completion(struct usbi_transfer * itransfer)1970 static int darwin_handle_transfer_completion (struct usbi_transfer *itransfer) {
1971 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1972 struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1973 int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1974 int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1975 int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1976 int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1977 int i;
1978
1979 if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1980 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1981 return LIBUSB_ERROR_INVALID_PARAM;
1982 }
1983
1984 usbi_dbg ("handling %s completion with kernel status %d",
1985 isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", tpriv->result);
1986
1987 if (kIOReturnSuccess == tpriv->result || kIOReturnUnderrun == tpriv->result) {
1988 if (isIsoc && tpriv->isoc_framelist) {
1989 /* copy isochronous results back */
1990
1991 for (i = 0; i < transfer->num_iso_packets ; i++) {
1992 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1993 lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1994 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1995 }
1996 } else if (!isIsoc)
1997 itransfer->transferred += tpriv->size;
1998 }
1999
2000 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
2001 return usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, tpriv->result));
2002 }
2003
darwin_clock_gettime(int clk_id,struct timespec * tp)2004 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
2005 #if !OSX_USE_CLOCK_GETTIME
2006 mach_timespec_t sys_time;
2007 clock_serv_t clock_ref;
2008
2009 switch (clk_id) {
2010 case USBI_CLOCK_REALTIME:
2011 /* CLOCK_REALTIME represents time since the epoch */
2012 clock_ref = clock_realtime;
2013 break;
2014 case USBI_CLOCK_MONOTONIC:
2015 /* use system boot time as reference for the monotonic clock */
2016 clock_ref = clock_monotonic;
2017 break;
2018 default:
2019 return LIBUSB_ERROR_INVALID_PARAM;
2020 }
2021
2022 clock_get_time (clock_ref, &sys_time);
2023
2024 tp->tv_sec = sys_time.tv_sec;
2025 tp->tv_nsec = sys_time.tv_nsec;
2026
2027 return 0;
2028 #else
2029 switch (clk_id) {
2030 case USBI_CLOCK_MONOTONIC:
2031 return clock_gettime(CLOCK_MONOTONIC, tp);
2032 case USBI_CLOCK_REALTIME:
2033 return clock_gettime(CLOCK_REALTIME, tp);
2034 default:
2035 return LIBUSB_ERROR_INVALID_PARAM;
2036 }
2037 #endif
2038 }
2039
2040 #if InterfaceVersion >= 550
darwin_alloc_streams(struct libusb_device_handle * dev_handle,uint32_t num_streams,unsigned char * endpoints,int num_endpoints)2041 static int darwin_alloc_streams (struct libusb_device_handle *dev_handle, uint32_t num_streams, unsigned char *endpoints,
2042 int num_endpoints) {
2043 struct darwin_interface *cInterface;
2044 UInt32 supportsStreams;
2045 uint8_t pipeRef;
2046 int rc, i;
2047
2048 /* find the mimimum number of supported streams on the endpoint list */
2049 for (i = 0 ; i < num_endpoints ; ++i) {
2050 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface))) {
2051 return rc;
2052 }
2053
2054 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2055 if (num_streams > supportsStreams)
2056 num_streams = supportsStreams;
2057 }
2058
2059 /* it is an error if any endpoint in endpoints does not support streams */
2060 if (0 == num_streams)
2061 return LIBUSB_ERROR_INVALID_PARAM;
2062
2063 /* create the streams */
2064 for (i = 0 ; i < num_endpoints ; ++i) {
2065 (void) ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
2066
2067 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, num_streams);
2068 if (kIOReturnSuccess != rc)
2069 return darwin_to_libusb(rc);
2070 }
2071
2072 return num_streams;
2073 }
2074
darwin_free_streams(struct libusb_device_handle * dev_handle,unsigned char * endpoints,int num_endpoints)2075 static int darwin_free_streams (struct libusb_device_handle *dev_handle, unsigned char *endpoints, int num_endpoints) {
2076 struct darwin_interface *cInterface;
2077 UInt32 supportsStreams;
2078 uint8_t pipeRef;
2079 int rc;
2080
2081 for (int i = 0 ; i < num_endpoints ; ++i) {
2082 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface)))
2083 return rc;
2084
2085 (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
2086 if (0 == supportsStreams)
2087 return LIBUSB_ERROR_INVALID_PARAM;
2088
2089 rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, 0);
2090 if (kIOReturnSuccess != rc)
2091 return darwin_to_libusb(rc);
2092 }
2093
2094 return LIBUSB_SUCCESS;
2095 }
2096 #endif
2097
2098 const struct usbi_os_backend usbi_backend = {
2099 .name = "Darwin",
2100 .caps = 0,
2101 .init = darwin_init,
2102 .exit = darwin_exit,
2103 .get_device_list = NULL, /* not needed */
2104 .get_device_descriptor = darwin_get_device_descriptor,
2105 .get_active_config_descriptor = darwin_get_active_config_descriptor,
2106 .get_config_descriptor = darwin_get_config_descriptor,
2107 .hotplug_poll = darwin_hotplug_poll,
2108
2109 .open = darwin_open,
2110 .close = darwin_close,
2111 .get_configuration = darwin_get_configuration,
2112 .set_configuration = darwin_set_configuration,
2113 .claim_interface = darwin_claim_interface,
2114 .release_interface = darwin_release_interface,
2115
2116 .set_interface_altsetting = darwin_set_interface_altsetting,
2117 .clear_halt = darwin_clear_halt,
2118 .reset_device = darwin_reset_device,
2119
2120 #if InterfaceVersion >= 550
2121 .alloc_streams = darwin_alloc_streams,
2122 .free_streams = darwin_free_streams,
2123 #endif
2124
2125 .kernel_driver_active = darwin_kernel_driver_active,
2126 .detach_kernel_driver = darwin_detach_kernel_driver,
2127 .attach_kernel_driver = darwin_attach_kernel_driver,
2128
2129 .destroy_device = darwin_destroy_device,
2130
2131 .submit_transfer = darwin_submit_transfer,
2132 .cancel_transfer = darwin_cancel_transfer,
2133 .clear_transfer_priv = darwin_clear_transfer_priv,
2134
2135 .handle_transfer_completion = darwin_handle_transfer_completion,
2136
2137 .clock_gettime = darwin_clock_gettime,
2138
2139 .device_priv_size = sizeof(struct darwin_device_priv),
2140 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
2141 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
2142 };
2143