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