1 /*
2  * darwin backend for libusb 1.0
3  * Copyright (C) 2008-2011 Nathan Hjelm <hjelmn@users.sourceforge.net>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18  */
19 
20 #include <config.h>
21 #include <ctype.h>
22 #include <dirent.h>
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <pthread.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <sys/ioctl.h>
30 #include <sys/stat.h>
31 #include <sys/types.h>
32 #include <unistd.h>
33 #include <libkern/OSAtomic.h>
34 
35 #include <mach/clock.h>
36 #include <mach/clock_types.h>
37 #include <mach/mach_host.h>
38 #include <mach/mach_port.h>
39 
40 #include <AvailabilityMacros.h>
41 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
42   #include <objc/objc-auto.h>
43 #endif
44 
45 #include <IOKit/IOCFBundle.h>
46 #include <IOKit/usb/IOUSBLib.h>
47 #include <IOKit/IOCFPlugIn.h>
48 
49 #include "darwin_usb.h"
50 
51 /* async event thread */
52 static pthread_mutex_t libusb_darwin_at_mutex;
53 static pthread_cond_t  libusb_darwin_at_cond;
54 
55 static clock_serv_t clock_realtime;
56 static clock_serv_t clock_monotonic;
57 
58 static CFRunLoopRef libusb_darwin_acfl = NULL; /* async cf loop */
59 static volatile int32_t initCount = 0;
60 
61 /* async event thread */
62 static pthread_t libusb_darwin_at;
63 
64 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
65 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
66 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
67 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
68 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
69 
darwin_error_str(int result)70 static const char *darwin_error_str (int result) {
71   switch (result) {
72   case kIOReturnSuccess:
73     return "no error";
74   case kIOReturnNotOpen:
75     return "device not opened for exclusive access";
76   case kIOReturnNoDevice:
77     return "no connection to an IOService";
78   case kIOUSBNoAsyncPortErr:
79     return "no async port has been opened for interface";
80   case kIOReturnExclusiveAccess:
81     return "another process has device opened for exclusive access";
82   case kIOUSBPipeStalled:
83     return "pipe is stalled";
84   case kIOReturnError:
85     return "could not establish a connection to the Darwin kernel";
86   case kIOUSBTransactionTimeout:
87     return "transaction timed out";
88   case kIOReturnBadArgument:
89     return "invalid argument";
90   case kIOReturnAborted:
91     return "transaction aborted";
92   case kIOReturnNotResponding:
93     return "device not responding";
94   case kIOReturnOverrun:
95     return "data overrun";
96   case kIOReturnCannotWire:
97     return "physical memory can not be wired down";
98   default:
99     return "unknown error";
100   }
101 }
102 
darwin_to_libusb(int result)103 static int darwin_to_libusb (int result) {
104   switch (result) {
105   case kIOReturnUnderrun:
106   case kIOReturnSuccess:
107     return LIBUSB_SUCCESS;
108   case kIOReturnNotOpen:
109   case kIOReturnNoDevice:
110     return LIBUSB_ERROR_NO_DEVICE;
111   case kIOReturnExclusiveAccess:
112     return LIBUSB_ERROR_ACCESS;
113   case kIOUSBPipeStalled:
114     return LIBUSB_ERROR_PIPE;
115   case kIOReturnBadArgument:
116     return LIBUSB_ERROR_INVALID_PARAM;
117   case kIOUSBTransactionTimeout:
118     return LIBUSB_ERROR_TIMEOUT;
119   case kIOReturnNotResponding:
120   case kIOReturnAborted:
121   case kIOReturnError:
122   case kIOUSBNoAsyncPortErr:
123   default:
124     return LIBUSB_ERROR_OTHER;
125   }
126 }
127 
128 
ep_to_pipeRef(struct libusb_device_handle * dev_handle,uint8_t ep,uint8_t * pipep,uint8_t * ifcp)129 static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp) {
130   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
131 
132   /* current interface */
133   struct darwin_interface *cInterface;
134 
135   int8_t i, iface;
136 
137   usbi_info (HANDLE_CTX(dev_handle), "converting ep address 0x%02x to pipeRef and interface", ep);
138 
139   for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
140     cInterface = &priv->interfaces[iface];
141 
142     if (dev_handle->claimed_interfaces & (1 << iface)) {
143       for (i = 0 ; i < cInterface->num_endpoints ; i++) {
144 	if (cInterface->endpoint_addrs[i] == ep) {
145 	  *pipep = i + 1;
146 	  *ifcp = iface;
147 	  usbi_info (HANDLE_CTX(dev_handle), "pipe %d on interface %d matches", *pipep, *ifcp);
148 	  return 0;
149 	}
150       }
151     }
152   }
153 
154   /* No pipe found with the correct endpoint address */
155   usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
156 
157   return -1;
158 }
159 
usb_setup_device_iterator(io_iterator_t * deviceIterator,long location)160 static int usb_setup_device_iterator (io_iterator_t *deviceIterator, long location) {
161   CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBDeviceClassName);
162 
163   if (!matchingDict)
164     return kIOReturnError;
165 
166   if (location) {
167     CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
168                                                                          &kCFTypeDictionaryKeyCallBacks,
169                                                                          &kCFTypeDictionaryValueCallBacks);
170 
171     if (propertyMatchDict) {
172       CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberLongType, &location);
173 
174       CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
175       /* release our reference to the CFNumber (CFDictionarySetValue retains it) */
176       CFRelease (locationCF);
177 
178       CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
179       /* release out reference to the CFMutableDictionaryRef (CFDictionarySetValue retains it) */
180       CFRelease (propertyMatchDict);
181     }
182     /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
183   }
184 
185   return IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, deviceIterator);
186 }
187 
usb_get_next_device(io_iterator_t deviceIterator,UInt32 * locationp)188 static usb_device_t **usb_get_next_device (io_iterator_t deviceIterator, UInt32 *locationp) {
189   io_cf_plugin_ref_t *plugInInterface = NULL;
190   usb_device_t **device;
191   io_service_t usbDevice;
192   long result;
193   SInt32 score;
194 
195   if (!IOIteratorIsValid (deviceIterator))
196     return NULL;
197 
198 
199   while ((usbDevice = IOIteratorNext(deviceIterator))) {
200     result = IOCreatePlugInInterfaceForService(usbDevice, kIOUSBDeviceUserClientTypeID,
201 					       kIOCFPlugInInterfaceID, &plugInInterface,
202 					       &score);
203 
204     /* we are done with the usb_device_t */
205     (void)IOObjectRelease(usbDevice);
206     if (kIOReturnSuccess == result && plugInInterface)
207       break;
208 
209     usbi_dbg ("libusb/darwin.c usb_get_next_device: could not set up plugin for service: %s\n", darwin_error_str (result));
210   }
211 
212   if (!usbDevice)
213     return NULL;
214 
215   (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
216 					   (LPVOID)&device);
217 
218   (*plugInInterface)->Stop(plugInInterface);
219   IODestroyPlugInInterface (plugInInterface);
220 
221   /* get the location from the device */
222   if (locationp)
223     (*(device))->GetLocationID(device, locationp);
224 
225   return device;
226 }
227 
darwin_get_device(uint32_t dev_location,usb_device_t *** darwin_device)228 static kern_return_t darwin_get_device (uint32_t dev_location, usb_device_t ***darwin_device) {
229   kern_return_t kresult;
230   UInt32        location;
231   io_iterator_t deviceIterator;
232 
233   kresult = usb_setup_device_iterator (&deviceIterator, dev_location);
234   if (kresult)
235     return kresult;
236 
237   /* This port of libusb uses locations to keep track of devices. */
238   while ((*darwin_device = usb_get_next_device (deviceIterator, &location)) != NULL) {
239     if (location == dev_location)
240       break;
241 
242     (**darwin_device)->Release(*darwin_device);
243   }
244 
245   IOObjectRelease (deviceIterator);
246 
247   if (!(*darwin_device))
248     return kIOReturnNoDevice;
249 
250   return kIOReturnSuccess;
251 }
252 
253 
254 
darwin_devices_detached(void * ptr,io_iterator_t rem_devices)255 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
256   struct libusb_context *ctx = (struct libusb_context *)ptr;
257   struct libusb_device_handle *handle;
258   struct darwin_device_priv *dpriv;
259   struct darwin_device_handle_priv *priv;
260 
261   io_service_t device;
262   long location;
263   bool locationValid;
264   CFTypeRef locationCF;
265   UInt32 message;
266 
267   usbi_info (ctx, "a device has been detached");
268 
269   while ((device = IOIteratorNext (rem_devices)) != 0) {
270     /* get the location from the i/o registry */
271     locationCF = IORegistryEntryCreateCFProperty (device, CFSTR(kUSBDevicePropertyLocationID), kCFAllocatorDefault, 0);
272 
273     IOObjectRelease (device);
274 
275     if (!locationCF)
276       continue;
277 
278     locationValid = CFGetTypeID(locationCF) == CFNumberGetTypeID() &&
279 	    CFNumberGetValue(locationCF, kCFNumberLongType, &location);
280 
281     CFRelease (locationCF);
282 
283     if (!locationValid)
284       continue;
285 
286     usbi_mutex_lock(&ctx->open_devs_lock);
287     list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
288       dpriv = (struct darwin_device_priv *)handle->dev->os_priv;
289 
290       /* the device may have been opened several times. write to each handle's event descriptor */
291       if (dpriv->location == location  && handle->os_priv) {
292 	priv  = (struct darwin_device_handle_priv *)handle->os_priv;
293 
294 	message = MESSAGE_DEVICE_GONE;
295 	write (priv->fds[1], &message, sizeof (message));
296       }
297     }
298 
299     usbi_mutex_unlock(&ctx->open_devs_lock);
300   }
301 }
302 
darwin_clear_iterator(io_iterator_t iter)303 static void darwin_clear_iterator (io_iterator_t iter) {
304   io_service_t device;
305 
306   while ((device = IOIteratorNext (iter)) != 0)
307     IOObjectRelease (device);
308 }
309 
event_thread_main(void * arg0)310 static void *event_thread_main (void *arg0) {
311   IOReturn kresult;
312   struct libusb_context *ctx = (struct libusb_context *)arg0;
313   CFRunLoopRef runloop;
314 
315   /* Set this thread's name, so it can be seen in the debugger
316      and crash reports. */
317 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
318   pthread_setname_np ("org.libusb.device-detach");
319 #endif
320 
321   /* Tell the Objective-C garbage collector about this thread.
322      This is required because, unlike NSThreads, pthreads are
323      not automatically registered. Although we don't use
324      Objective-C, we use CoreFoundation, which does. */
325 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
326   objc_registerThreadWithCollector();
327 #endif
328 
329   /* hotplug (device removal) source */
330   CFRunLoopSourceRef     libusb_notification_cfsource;
331   io_notification_port_t libusb_notification_port;
332   io_iterator_t          libusb_rem_device_iterator;
333 
334   usbi_info (ctx, "creating hotplug event source");
335 
336   runloop = CFRunLoopGetCurrent ();
337   CFRetain (runloop);
338 
339   /* add the notification port to the run loop */
340   libusb_notification_port     = IONotificationPortCreate (kIOMasterPortDefault);
341   libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
342   CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
343 
344   /* create notifications for removed devices */
345   kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
346 					      IOServiceMatching(kIOUSBDeviceClassName),
347 					      (IOServiceMatchingCallback)darwin_devices_detached,
348 					      (void *)ctx, &libusb_rem_device_iterator);
349 
350   if (kresult != kIOReturnSuccess) {
351     usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
352 
353     pthread_exit (NULL);
354   }
355 
356   /* arm notifiers */
357   darwin_clear_iterator (libusb_rem_device_iterator);
358 
359   usbi_info (ctx, "thread ready to receive events");
360 
361   /* signal the main thread that the async runloop has been created. */
362   pthread_mutex_lock (&libusb_darwin_at_mutex);
363   libusb_darwin_acfl = runloop;
364   pthread_cond_signal (&libusb_darwin_at_cond);
365   pthread_mutex_unlock (&libusb_darwin_at_mutex);
366 
367   /* run the runloop */
368   CFRunLoopRun();
369 
370   usbi_info (ctx, "thread exiting");
371 
372   /* delete notification port */
373   IONotificationPortDestroy (libusb_notification_port);
374   IOObjectRelease (libusb_rem_device_iterator);
375 
376   CFRelease (runloop);
377 
378   libusb_darwin_acfl = NULL;
379 
380   pthread_exit (NULL);
381 }
382 
darwin_init(struct libusb_context * ctx)383 static int darwin_init(struct libusb_context *ctx) {
384   host_name_port_t host_self;
385 
386   if (OSAtomicIncrement32Barrier(&initCount) == 1) {
387     /* create the clocks that will be used */
388 
389     host_self = mach_host_self();
390     host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
391     host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
392     mach_port_deallocate(mach_task_self(), host_self);
393 
394     pthread_mutex_init (&libusb_darwin_at_mutex, NULL);
395     pthread_cond_init (&libusb_darwin_at_cond, NULL);
396 
397     pthread_create (&libusb_darwin_at, NULL, event_thread_main, (void *)ctx);
398 
399     pthread_mutex_lock (&libusb_darwin_at_mutex);
400     while (!libusb_darwin_acfl)
401       pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
402     pthread_mutex_unlock (&libusb_darwin_at_mutex);
403   }
404 
405   return 0;
406 }
407 
darwin_exit(void)408 static void darwin_exit (void) {
409   if (OSAtomicDecrement32Barrier(&initCount) == 0) {
410     mach_port_deallocate(mach_task_self(), clock_realtime);
411     mach_port_deallocate(mach_task_self(), clock_monotonic);
412 
413     /* stop the async runloop and wait for the thread to terminate. */
414     CFRunLoopStop (libusb_darwin_acfl);
415     pthread_join (libusb_darwin_at, NULL);
416   }
417 }
418 
darwin_get_device_descriptor(struct libusb_device * dev,unsigned char * buffer,int * host_endian)419 static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
420   struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
421 
422   /* return cached copy */
423   memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
424 
425   *host_endian = 0;
426 
427   return 0;
428 }
429 
get_configuration_index(struct libusb_device * dev,int config_value)430 static int get_configuration_index (struct libusb_device *dev, int config_value) {
431   struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
432   UInt8 i, numConfig;
433   IOUSBConfigurationDescriptorPtr desc;
434   IOReturn kresult;
435 
436   /* is there a simpler way to determine the index? */
437   kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
438   if (kresult != kIOReturnSuccess)
439     return darwin_to_libusb (kresult);
440 
441   for (i = 0 ; i < numConfig ; i++) {
442     (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
443 
444     if (desc->bConfigurationValue == config_value)
445       return i;
446   }
447 
448   /* configuration not found */
449   return LIBUSB_ERROR_OTHER;
450 }
451 
darwin_get_active_config_descriptor(struct libusb_device * dev,unsigned char * buffer,size_t len,int * host_endian)452 static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
453   struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
454   int config_index;
455 
456   if (0 == priv->active_config)
457     return LIBUSB_ERROR_INVALID_PARAM;
458 
459   config_index = get_configuration_index (dev, priv->active_config);
460   if (config_index < 0)
461     return config_index;
462 
463   return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
464 }
465 
darwin_get_config_descriptor(struct libusb_device * dev,uint8_t config_index,unsigned char * buffer,size_t len,int * host_endian)466 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
467   struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
468   IOUSBConfigurationDescriptorPtr desc;
469   IOReturn kresult;
470   usb_device_t **device = NULL;
471 
472   if (!priv)
473     return LIBUSB_ERROR_OTHER;
474 
475   if (!priv->device) {
476     kresult = darwin_get_device (priv->location, &device);
477     if (kresult || !device) {
478       usbi_err (DEVICE_CTX (dev), "could not find device: %s", darwin_error_str (kresult));
479 
480       return darwin_to_libusb (kresult);
481     }
482 
483     /* don't have to open the device to get a config descriptor */
484   } else
485     device = priv->device;
486 
487   kresult = (*device)->GetConfigurationDescriptorPtr (device, config_index, &desc);
488   if (kresult == kIOReturnSuccess) {
489     /* copy descriptor */
490     if (libusb_le16_to_cpu(desc->wTotalLength) < len)
491       len = libusb_le16_to_cpu(desc->wTotalLength);
492 
493     memmove (buffer, desc, len);
494 
495     /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
496     *host_endian = 0;
497   }
498 
499   if (!priv->device)
500     (*device)->Release (device);
501 
502   return darwin_to_libusb (kresult);
503 }
504 
505 /* check whether the os has configured the device */
darwin_check_configuration(struct libusb_context * ctx,struct libusb_device * dev,usb_device_t ** darwin_device)506 static int darwin_check_configuration (struct libusb_context *ctx, struct libusb_device *dev, usb_device_t **darwin_device) {
507   struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
508 
509   IOUSBConfigurationDescriptorPtr configDesc;
510   IOUSBFindInterfaceRequest request;
511   kern_return_t             kresult;
512   io_iterator_t             interface_iterator;
513   io_service_t              firstInterface;
514 
515   if (priv->dev_descriptor.bNumConfigurations < 1) {
516     usbi_err (ctx, "device has no configurations");
517     return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
518   }
519 
520   /* find the first configuration */
521   kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
522   priv->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
523 
524   /* check if the device is already configured. there is probably a better way than iterating over the
525      to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
526      might lock up on the device request) */
527 
528   /* Setup the Interface Request */
529   request.bInterfaceClass    = kIOUSBFindInterfaceDontCare;
530   request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
531   request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
532   request.bAlternateSetting  = kIOUSBFindInterfaceDontCare;
533 
534   kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
535   if (kresult)
536     return darwin_to_libusb (kresult);
537 
538   /* iterate once */
539   firstInterface = IOIteratorNext(interface_iterator);
540 
541   /* done with the interface iterator */
542   IOObjectRelease(interface_iterator);
543 
544   if (firstInterface) {
545     IOObjectRelease (firstInterface);
546 
547     /* device is configured */
548     if (priv->dev_descriptor.bNumConfigurations == 1)
549       /* to avoid problems with some devices get the configurations value from the configuration descriptor */
550       priv->active_config = priv->first_config;
551     else
552       /* devices with more than one configuration should work with GetConfiguration */
553       (*darwin_device)->GetConfiguration (darwin_device, &priv->active_config);
554   } else
555     /* not configured */
556     priv->active_config = 0;
557 
558   usbi_info (ctx, "active config: %u, first config: %u", priv->active_config, priv->first_config);
559 
560   return 0;
561 }
562 
darwin_cache_device_descriptor(struct libusb_context * ctx,struct libusb_device * dev,usb_device_t ** device)563 static int darwin_cache_device_descriptor (struct libusb_context *ctx, struct libusb_device *dev, usb_device_t **device) {
564   struct darwin_device_priv *priv;
565   int retries = 5, delay = 30000;
566   int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
567   int is_open = 0;
568   int ret = 0, ret2;
569   IOUSBDevRequest req;
570   UInt8 bDeviceClass;
571   UInt16 idProduct, idVendor;
572 
573   (*device)->GetDeviceClass (device, &bDeviceClass);
574   (*device)->GetDeviceProduct (device, &idProduct);
575   (*device)->GetDeviceVendor (device, &idVendor);
576 
577   priv = (struct darwin_device_priv *)dev->os_priv;
578 
579   /* try to open the device (we can usually continue even if this fails) */
580   is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
581 
582   /**** retrieve device descriptor ****/
583   do {
584     /* Set up request for device descriptor */
585     memset (&(priv->dev_descriptor), 0, sizeof(IOUSBDeviceDescriptor));
586     req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
587     req.bRequest      = kUSBRqGetDescriptor;
588     req.wValue        = kUSBDeviceDesc << 8;
589     req.wIndex        = 0;
590     req.wLength       = sizeof(priv->dev_descriptor);
591     req.pData         = &(priv->dev_descriptor);
592 
593     /* according to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
594      * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request.  Still,
595      * to follow the spec as closely as possible, try opening the device */
596 
597     ret = (*(device))->DeviceRequest (device, &req);
598 
599     if (kIOReturnOverrun == ret && kUSBDeviceDesc == priv->dev_descriptor.bDescriptorType)
600       /* received an overrun error but we still received a device descriptor */
601       ret = kIOReturnSuccess;
602 
603     if (kIOReturnSuccess == ret && (0 == priv->dev_descriptor.bNumConfigurations ||
604 				    0 == priv->dev_descriptor.bcdUSB)) {
605       /* work around for incorrectly configured devices */
606       if (try_reconfigure && is_open) {
607 	usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
608 
609 	/* set the first configuration */
610 	(*device)->SetConfiguration(device, 1);
611 
612 	/* don't try to reconfigure again */
613 	try_reconfigure = 0;
614       }
615 
616       ret = kIOUSBPipeStalled;
617     }
618 
619     if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
620       /* device may be suspended. unsuspend it and try again */
621 #if DeviceVersion >= 320
622       UInt32 info;
623 
624       /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
625       (void)(*device)->GetUSBDeviceInformation (device, &info);
626 
627       try_unsuspend = info & (1 << kUSBInformationDeviceIsSuspendedBit);
628 #endif
629 
630       if (try_unsuspend) {
631 	/* resume the device */
632 	ret2 = (*device)->USBDeviceSuspend (device, 0);
633 	if (kIOReturnSuccess != ret2) {
634 	  /* prevent log spew from poorly behaving devices.  this indicates the
635 	     os actually had trouble communicating with the device */
636 	  usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
637 	} else
638 	  unsuspended = 1;
639 
640 	try_unsuspend = 0;
641       }
642     }
643 
644     if (kIOReturnSuccess != ret) {
645       usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000);
646       /* sleep for a little while before trying again */
647       usleep (delay);
648     }
649   } while (kIOReturnSuccess != ret && retries--);
650 
651   if (unsuspended)
652     /* resuspend the device */
653     (void)(*device)->USBDeviceSuspend (device, 1);
654 
655   if (is_open)
656     (void) (*device)->USBDeviceClose (device);
657 
658   if (ret != kIOReturnSuccess) {
659     /* a debug message was already printed out for this error */
660     if (LIBUSB_CLASS_HUB == bDeviceClass)
661       usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s. skipping device", idVendor, idProduct, darwin_error_str (ret));
662     else
663       usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s. skipping device", idVendor, idProduct, darwin_error_str (ret));
664 
665     return -1;
666   }
667 
668   usbi_dbg ("device descriptor:");
669   usbi_dbg (" bDescriptorType:    0x%02x", priv->dev_descriptor.bDescriptorType);
670   usbi_dbg (" bcdUSB:             0x%04x", priv->dev_descriptor.bcdUSB);
671   usbi_dbg (" bDeviceClass:       0x%02x", priv->dev_descriptor.bDeviceClass);
672   usbi_dbg (" bDeviceSubClass:    0x%02x", priv->dev_descriptor.bDeviceSubClass);
673   usbi_dbg (" bDeviceProtocol:    0x%02x", priv->dev_descriptor.bDeviceProtocol);
674   usbi_dbg (" bMaxPacketSize0:    0x%02x", priv->dev_descriptor.bMaxPacketSize0);
675   usbi_dbg (" idVendor:           0x%04x", priv->dev_descriptor.idVendor);
676   usbi_dbg (" idProduct:          0x%04x", priv->dev_descriptor.idProduct);
677   usbi_dbg (" bcdDevice:          0x%04x", priv->dev_descriptor.bcdDevice);
678   usbi_dbg (" iManufacturer:      0x%02x", priv->dev_descriptor.iManufacturer);
679   usbi_dbg (" iProduct:           0x%02x", priv->dev_descriptor.iProduct);
680   usbi_dbg (" iSerialNumber:      0x%02x", priv->dev_descriptor.iSerialNumber);
681   usbi_dbg (" bNumConfigurations: 0x%02x", priv->dev_descriptor.bNumConfigurations);
682 
683   /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
684   if (libusb_le16_to_cpu (priv->dev_descriptor.idProduct) != idProduct) {
685     /* not a valid device */
686     usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
687 	       idProduct, libusb_le16_to_cpu (priv->dev_descriptor.idProduct));
688     return -1;
689   }
690 
691   return 0;
692 }
693 
process_new_device(struct libusb_context * ctx,usb_device_t ** device,UInt32 locationID,struct discovered_devs ** _discdevs)694 static int process_new_device (struct libusb_context *ctx, usb_device_t **device, UInt32 locationID, struct discovered_devs **_discdevs) {
695   struct darwin_device_priv *priv;
696   struct libusb_device *dev;
697   struct discovered_devs *discdevs;
698   UInt16                address;
699   UInt8                 devSpeed;
700   int ret = 0, need_unref = 0;
701 
702   do {
703     dev = usbi_get_device_by_session_id(ctx, locationID);
704     if (!dev) {
705       usbi_info (ctx, "allocating new device for location 0x%08x", locationID);
706       dev = usbi_alloc_device(ctx, locationID);
707       need_unref = 1;
708     } else
709       usbi_info (ctx, "using existing device for location 0x%08x", locationID);
710 
711     if (!dev) {
712       ret = LIBUSB_ERROR_NO_MEM;
713       break;
714     }
715 
716     priv = (struct darwin_device_priv *)dev->os_priv;
717 
718     (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&address);
719 
720     ret = darwin_cache_device_descriptor (ctx, dev, device);
721     if (ret < 0)
722       break;
723 
724     /* check current active configuration (and cache the first configuration value-- which may be used by claim_interface) */
725     ret = darwin_check_configuration (ctx, dev, device);
726     if (ret < 0)
727       break;
728 
729     dev->bus_number     = locationID >> 24;
730     dev->device_address = address;
731 
732     (*device)->GetDeviceSpeed (device, &devSpeed);
733 
734     switch (devSpeed) {
735     case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
736     case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
737     case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
738     default:
739       usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
740     }
741 
742     /* save our location, we'll need this later */
743     priv->location = locationID;
744     snprintf(priv->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", address, priv->dev_descriptor.idVendor, priv->dev_descriptor.idProduct,
745 	     priv->dev_descriptor.bDeviceClass, priv->dev_descriptor.bDeviceSubClass);
746 
747     ret = usbi_sanitize_device (dev);
748     if (ret < 0)
749       break;
750 
751     /* append the device to the list of discovered devices */
752     discdevs = discovered_devs_append(*_discdevs, dev);
753     if (!discdevs) {
754       ret = LIBUSB_ERROR_NO_MEM;
755       break;
756     }
757 
758     *_discdevs = discdevs;
759 
760     usbi_info (ctx, "found device with address %d at %s", dev->device_address, priv->sys_path);
761   } while (0);
762 
763   if (need_unref)
764     libusb_unref_device(dev);
765 
766   return ret;
767 }
768 
darwin_get_device_list(struct libusb_context * ctx,struct discovered_devs ** _discdevs)769 static int darwin_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs) {
770   io_iterator_t        deviceIterator;
771   usb_device_t         **device;
772   kern_return_t        kresult;
773   UInt32               location;
774 
775   kresult = usb_setup_device_iterator (&deviceIterator, 0);
776   if (kresult != kIOReturnSuccess)
777     return darwin_to_libusb (kresult);
778 
779   while ((device = usb_get_next_device (deviceIterator, &location)) != NULL) {
780     (void) process_new_device (ctx, device, location, _discdevs);
781 
782     (*(device))->Release(device);
783   }
784 
785   IOObjectRelease(deviceIterator);
786 
787   return 0;
788 }
789 
darwin_open(struct libusb_device_handle * dev_handle)790 static int darwin_open (struct libusb_device_handle *dev_handle) {
791   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
792   struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
793   usb_device_t  **darwin_device;
794   IOReturn kresult;
795 
796   if (0 == dpriv->open_count) {
797     kresult = darwin_get_device (dpriv->location, &darwin_device);
798     if (kresult) {
799       usbi_err (HANDLE_CTX (dev_handle), "could not find device: %s", darwin_error_str (kresult));
800       return darwin_to_libusb (kresult);
801     }
802 
803     dpriv->device = darwin_device;
804 
805     /* try to open the device */
806     kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
807 
808     if (kresult != kIOReturnSuccess) {
809       usbi_err (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
810 
811       switch (kresult) {
812       case kIOReturnExclusiveAccess:
813 	/* it is possible to perform some actions on a device that is not open so do not return an error */
814 	priv->is_open = 0;
815 
816 	break;
817       default:
818 	(*(dpriv->device))->Release (dpriv->device);
819 	dpriv->device = NULL;
820 	return darwin_to_libusb (kresult);
821       }
822     } else {
823       /* create async event source */
824       kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
825       if (kresult != kIOReturnSuccess) {
826 	usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
827 
828 	(*(dpriv->device))->USBDeviceClose (dpriv->device);
829 	(*(dpriv->device))->Release (dpriv->device);
830 
831 	dpriv->device = NULL;
832 	return darwin_to_libusb (kresult);
833       }
834 
835       priv->is_open = 1;
836 
837       CFRetain (libusb_darwin_acfl);
838 
839       /* add the cfSource to the aync run loop */
840       CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
841     }
842   }
843 
844   /* device opened successfully */
845   dpriv->open_count++;
846 
847   /* create a file descriptor for notifications */
848   pipe (priv->fds);
849 
850   /* set the pipe to be non-blocking */
851   fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
852 
853   usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
854 
855   usbi_info (HANDLE_CTX (dev_handle), "device open for access");
856 
857   return 0;
858 }
859 
darwin_close(struct libusb_device_handle * dev_handle)860 static void darwin_close (struct libusb_device_handle *dev_handle) {
861   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
862   struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
863   IOReturn kresult;
864   int i;
865 
866   if (dpriv->open_count == 0) {
867     /* something is probably very wrong if this is the case */
868     usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!\n");
869     return;
870   }
871 
872   dpriv->open_count--;
873 
874   /* make sure all interfaces are released */
875   for (i = 0 ; i < USB_MAXINTERFACES ; i++)
876     if (dev_handle->claimed_interfaces & (1 << i))
877       libusb_release_interface (dev_handle, i);
878 
879   if (0 == dpriv->open_count) {
880     if (priv->is_open) {
881       /* delete the device's async event source */
882       if (priv->cfSource) {
883 	CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
884 	CFRelease (priv->cfSource);
885       }
886 
887       /* close the device */
888       kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
889       if (kresult) {
890 	/* Log the fact that we had a problem closing the file, however failing a
891 	 * close isn't really an error, so return success anyway */
892 	usbi_err (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
893       }
894     }
895 
896     kresult = (*(dpriv->device))->Release(dpriv->device);
897     if (kresult) {
898       /* Log the fact that we had a problem closing the file, however failing a
899        * close isn't really an error, so return success anyway */
900       usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
901     }
902 
903     dpriv->device = NULL;
904   }
905 
906   /* file descriptors are maintained per-instance */
907   usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
908   close (priv->fds[1]);
909   close (priv->fds[0]);
910 
911   priv->fds[0] = priv->fds[1] = -1;
912 }
913 
darwin_get_configuration(struct libusb_device_handle * dev_handle,int * config)914 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
915   struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
916 
917   *config = (int) dpriv->active_config;
918 
919   return 0;
920 }
921 
darwin_set_configuration(struct libusb_device_handle * dev_handle,int config)922 static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
923   struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
924   IOReturn kresult;
925   int i;
926 
927   /* Setting configuration will invalidate the interface, so we need
928      to reclaim it. First, dispose of existing interfaces, if any. */
929   for (i = 0 ; i < USB_MAXINTERFACES ; i++)
930     if (dev_handle->claimed_interfaces & (1 << i))
931       darwin_release_interface (dev_handle, i);
932 
933   kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
934   if (kresult != kIOReturnSuccess)
935     return darwin_to_libusb (kresult);
936 
937   /* Reclaim any interfaces. */
938   for (i = 0 ; i < USB_MAXINTERFACES ; i++)
939     if (dev_handle->claimed_interfaces & (1 << i))
940       darwin_claim_interface (dev_handle, i);
941 
942   dpriv->active_config = config;
943 
944   return 0;
945 }
946 
darwin_get_interface(usb_device_t ** darwin_device,uint8_t ifc,io_service_t * usbInterfacep)947 static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
948   IOUSBFindInterfaceRequest request;
949   uint8_t                   current_interface;
950   kern_return_t             kresult;
951   io_iterator_t             interface_iterator;
952 
953   *usbInterfacep = IO_OBJECT_NULL;
954 
955   /* Setup the Interface Request */
956   request.bInterfaceClass    = kIOUSBFindInterfaceDontCare;
957   request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
958   request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
959   request.bAlternateSetting  = kIOUSBFindInterfaceDontCare;
960 
961   kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
962   if (kresult)
963     return kresult;
964 
965   for ( current_interface = 0 ; current_interface <= ifc ; current_interface++ ) {
966     *usbInterfacep = IOIteratorNext(interface_iterator);
967     if (current_interface != ifc)
968       (void) IOObjectRelease (*usbInterfacep);
969   }
970 
971   /* done with the interface iterator */
972   IOObjectRelease(interface_iterator);
973 
974   return 0;
975 }
976 
get_endpoints(struct libusb_device_handle * dev_handle,int iface)977 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
978   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
979 
980   /* current interface */
981   struct darwin_interface *cInterface = &priv->interfaces[iface];
982 
983   kern_return_t kresult;
984 
985   u_int8_t numep, direction, number;
986   u_int8_t dont_care1, dont_care3;
987   u_int16_t dont_care2;
988   int i;
989 
990   usbi_info (HANDLE_CTX (dev_handle), "building table of endpoints.");
991 
992   /* retrieve the total number of endpoints on this interface */
993   kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
994   if (kresult) {
995     usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
996     return darwin_to_libusb (kresult);
997   }
998 
999   /* iterate through pipe references */
1000   for (i = 1 ; i <= numep ; i++) {
1001     kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
1002 							    &dont_care2, &dont_care3);
1003 
1004     if (kresult != kIOReturnSuccess) {
1005       usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
1006 
1007       return darwin_to_libusb (kresult);
1008     }
1009 
1010     usbi_info (HANDLE_CTX (dev_handle), "interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
1011 
1012     cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1013   }
1014 
1015   cInterface->num_endpoints = numep;
1016 
1017   return 0;
1018 }
1019 
darwin_claim_interface(struct libusb_device_handle * dev_handle,int iface)1020 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
1021   struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1022   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1023   io_service_t          usbInterface = IO_OBJECT_NULL;
1024   IOReturn kresult;
1025   IOCFPlugInInterface **plugInInterface = NULL;
1026   SInt32                score;
1027 
1028   /* current interface */
1029   struct darwin_interface *cInterface = &priv->interfaces[iface];
1030 
1031   kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1032   if (kresult != kIOReturnSuccess)
1033     return darwin_to_libusb (kresult);
1034 
1035   /* make sure we have an interface */
1036   if (!usbInterface && dpriv->first_config != 0) {
1037     usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
1038 
1039     /* set the configuration */
1040     kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
1041     if (kresult != LIBUSB_SUCCESS) {
1042       usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
1043       return kresult;
1044     }
1045 
1046     kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1047     if (kresult) {
1048       usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1049       return darwin_to_libusb (kresult);
1050     }
1051   }
1052 
1053   if (!usbInterface) {
1054     usbi_err (HANDLE_CTX (dev_handle), "interface not found");
1055     return LIBUSB_ERROR_NOT_FOUND;
1056   }
1057 
1058   /* get an interface to the device's interface */
1059   kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1060 					       kIOCFPlugInInterfaceID, &plugInInterface, &score);
1061 
1062   /* ignore release error */
1063   (void)IOObjectRelease (usbInterface);
1064 
1065   if (kresult) {
1066     usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1067     return darwin_to_libusb (kresult);
1068   }
1069 
1070   if (!plugInInterface) {
1071     usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
1072     return LIBUSB_ERROR_NOT_FOUND;
1073   }
1074 
1075   /* Do the actual claim */
1076   kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1077 					       CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
1078 					       (LPVOID)&cInterface->interface);
1079   /* We no longer need the intermediate plug-in */
1080   IODestroyPlugInInterface (plugInInterface);
1081   if (kresult || !cInterface->interface) {
1082     usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
1083     return darwin_to_libusb (kresult);
1084   }
1085 
1086   /* claim the interface */
1087   kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
1088   if (kresult) {
1089     usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
1090     return darwin_to_libusb (kresult);
1091   }
1092 
1093   /* update list of endpoints */
1094   kresult = get_endpoints (dev_handle, iface);
1095   if (kresult) {
1096     /* this should not happen */
1097     darwin_release_interface (dev_handle, iface);
1098     usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1099     return kresult;
1100   }
1101 
1102   cInterface->cfSource = NULL;
1103 
1104   /* create async event source */
1105   kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
1106   if (kresult != kIOReturnSuccess) {
1107     usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
1108 
1109     /* can't continue without an async event source */
1110     (void)darwin_release_interface (dev_handle, iface);
1111 
1112     return darwin_to_libusb (kresult);
1113   }
1114 
1115   /* add the cfSource to the async thread's run loop */
1116   CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1117 
1118   usbi_info (HANDLE_CTX (dev_handle), "interface opened");
1119 
1120   return 0;
1121 }
1122 
darwin_release_interface(struct libusb_device_handle * dev_handle,int iface)1123 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
1124   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1125   IOReturn kresult;
1126 
1127   /* current interface */
1128   struct darwin_interface *cInterface = &priv->interfaces[iface];
1129 
1130   /* Check to see if an interface is open */
1131   if (!cInterface->interface)
1132     return LIBUSB_SUCCESS;
1133 
1134   /* clean up endpoint data */
1135   cInterface->num_endpoints = 0;
1136 
1137   /* delete the interface's async event source */
1138   if (cInterface->cfSource) {
1139     CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1140     CFRelease (cInterface->cfSource);
1141   }
1142 
1143   kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
1144   if (kresult)
1145     usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1146 
1147   kresult = (*(cInterface->interface))->Release(cInterface->interface);
1148   if (kresult != kIOReturnSuccess)
1149     usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
1150 
1151   cInterface->interface = IO_OBJECT_NULL;
1152 
1153   return darwin_to_libusb (kresult);
1154 }
1155 
darwin_set_interface_altsetting(struct libusb_device_handle * dev_handle,int iface,int altsetting)1156 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
1157   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1158   IOReturn kresult;
1159 
1160   /* current interface */
1161   struct darwin_interface *cInterface = &priv->interfaces[iface];
1162 
1163   if (!cInterface->interface)
1164     return LIBUSB_ERROR_NO_DEVICE;
1165 
1166   kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
1167   if (kresult != kIOReturnSuccess)
1168     darwin_reset_device (dev_handle);
1169 
1170   /* update list of endpoints */
1171   kresult = get_endpoints (dev_handle, iface);
1172   if (kresult) {
1173     /* this should not happen */
1174     darwin_release_interface (dev_handle, iface);
1175     usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1176     return kresult;
1177   }
1178 
1179   return darwin_to_libusb (kresult);
1180 }
1181 
darwin_clear_halt(struct libusb_device_handle * dev_handle,unsigned char endpoint)1182 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1183   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1184 
1185   /* current interface */
1186   struct darwin_interface *cInterface;
1187   uint8_t pipeRef, iface;
1188   IOReturn kresult;
1189 
1190   /* determine the interface/endpoint to use */
1191   if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
1192     usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1193 
1194     return LIBUSB_ERROR_NOT_FOUND;
1195   }
1196 
1197   cInterface = &priv->interfaces[iface];
1198 
1199 #if (InterfaceVersion < 190)
1200   kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1201 #else
1202   /* newer versions of darwin support clearing additional bits on the device's endpoint */
1203   kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1204 #endif
1205   if (kresult)
1206     usbi_err (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1207 
1208   return darwin_to_libusb (kresult);
1209 }
1210 
darwin_reset_device(struct libusb_device_handle * dev_handle)1211 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1212   struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1213   IOReturn kresult;
1214 
1215   kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1216   if (kresult)
1217     usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1218 
1219   return darwin_to_libusb (kresult);
1220 }
1221 
darwin_kernel_driver_active(struct libusb_device_handle * dev_handle,int interface)1222 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1223   struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1224   io_service_t usbInterface;
1225   CFTypeRef driver;
1226   IOReturn kresult;
1227 
1228   kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1229   if (kresult) {
1230     usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1231 
1232     return darwin_to_libusb (kresult);
1233   }
1234 
1235   driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1236   IOObjectRelease (usbInterface);
1237 
1238   if (driver) {
1239     CFRelease (driver);
1240 
1241     return 1;
1242   }
1243 
1244   /* no driver */
1245   return 0;
1246 }
1247 
1248 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
darwin_attach_kernel_driver(struct libusb_device_handle * dev_handle,int interface)1249 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1250   (void)dev_handle;
1251   (void)interface;
1252   return LIBUSB_ERROR_NOT_SUPPORTED;
1253 }
1254 
darwin_detach_kernel_driver(struct libusb_device_handle * dev_handle,int interface)1255 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1256   (void)dev_handle;
1257   (void)interface;
1258   return LIBUSB_ERROR_NOT_SUPPORTED;
1259 }
1260 
darwin_destroy_device(struct libusb_device * dev)1261 static void darwin_destroy_device(struct libusb_device *dev) {
1262   (void)dev;
1263 }
1264 
submit_bulk_transfer(struct usbi_transfer * itransfer)1265 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1266   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1267   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1268 
1269   IOReturn               ret;
1270   uint8_t                transferType;
1271   /* None of the values below are used in libusb for bulk transfers */
1272   uint8_t                direction, number, interval, pipeRef, iface;
1273   uint16_t               maxPacketSize;
1274 
1275   struct darwin_interface *cInterface;
1276 
1277   if (IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
1278     return LIBUSB_ERROR_NOT_SUPPORTED;
1279 
1280   if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1281     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1282 
1283     return LIBUSB_ERROR_NOT_FOUND;
1284   }
1285 
1286   cInterface = &priv->interfaces[iface];
1287 
1288   (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1289 						 &transferType, &maxPacketSize, &interval);
1290 
1291   /* submit the request */
1292   /* timeouts are unavailable on interrupt endpoints */
1293   if (transferType == kUSBInterrupt) {
1294     if (IS_XFERIN(transfer))
1295       ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1296 						      transfer->length, darwin_async_io_callback, itransfer);
1297     else
1298       ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1299 						       transfer->length, darwin_async_io_callback, itransfer);
1300   } else {
1301     itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1302 
1303     if (IS_XFERIN(transfer))
1304       ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1305 							transfer->length, transfer->timeout, transfer->timeout,
1306 							darwin_async_io_callback, (void *)itransfer);
1307     else
1308       ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1309 							 transfer->length, transfer->timeout, transfer->timeout,
1310 							 darwin_async_io_callback, (void *)itransfer);
1311   }
1312 
1313   if (ret)
1314     usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
1315 	       darwin_error_str(ret), ret);
1316 
1317   return darwin_to_libusb (ret);
1318 }
1319 
submit_iso_transfer(struct usbi_transfer * itransfer)1320 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1321   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1322   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1323   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1324 
1325   IOReturn                kresult;
1326   uint8_t                 pipeRef, iface;
1327   UInt64                  frame;
1328   AbsoluteTime            atTime;
1329   int                     i;
1330 
1331   struct darwin_interface *cInterface;
1332 
1333   /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
1334   if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
1335     free(tpriv->isoc_framelist);
1336     tpriv->isoc_framelist = NULL;
1337   }
1338 
1339   if (!tpriv->isoc_framelist) {
1340     tpriv->num_iso_packets = transfer->num_iso_packets;
1341     tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1342     if (!tpriv->isoc_framelist)
1343       return LIBUSB_ERROR_NO_MEM;
1344   }
1345 
1346   /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1347   for (i = 0 ; i < transfer->num_iso_packets ; i++)
1348     tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1349 
1350   /* determine the interface/endpoint to use */
1351   if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1352     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1353 
1354     return LIBUSB_ERROR_NOT_FOUND;
1355   }
1356 
1357   cInterface = &priv->interfaces[iface];
1358 
1359   /* Last but not least we need the bus frame number */
1360   kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1361   if (kresult) {
1362     usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1363     free(tpriv->isoc_framelist);
1364     tpriv->isoc_framelist = NULL;
1365 
1366     return darwin_to_libusb (kresult);
1367   }
1368 
1369   /* schedule for a frame a little in the future */
1370   frame += 4;
1371 
1372   if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
1373     frame = cInterface->frames[transfer->endpoint];
1374 
1375   /* submit the request */
1376   if (IS_XFERIN(transfer))
1377     kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1378 							     transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1379 							     itransfer);
1380   else
1381     kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1382 							      transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1383 							      itransfer);
1384 
1385   cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets / 8;
1386 
1387   if (kresult != kIOReturnSuccess) {
1388     usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
1389 	       darwin_error_str(kresult));
1390     free (tpriv->isoc_framelist);
1391     tpriv->isoc_framelist = NULL;
1392   }
1393 
1394   return darwin_to_libusb (kresult);
1395 }
1396 
submit_control_transfer(struct usbi_transfer * itransfer)1397 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1398   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1399   struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1400   struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1401   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1402   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1403 
1404   IOReturn               kresult;
1405 
1406   bzero(&tpriv->req, sizeof(tpriv->req));
1407 
1408   /* IOUSBDeviceInterface expects the request in cpu endianess */
1409   tpriv->req.bmRequestType     = setup->bmRequestType;
1410   tpriv->req.bRequest          = setup->bRequest;
1411   /* these values should be in bus order from libusb_fill_control_setup */
1412   tpriv->req.wValue            = OSSwapLittleToHostInt16 (setup->wValue);
1413   tpriv->req.wIndex            = OSSwapLittleToHostInt16 (setup->wIndex);
1414   tpriv->req.wLength           = OSSwapLittleToHostInt16 (setup->wLength);
1415   /* data is stored after the libusb control block */
1416   tpriv->req.pData             = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1417   tpriv->req.completionTimeout = transfer->timeout;
1418   tpriv->req.noDataTimeout     = transfer->timeout;
1419 
1420   itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
1421 
1422   /* all transfers in libusb-1.0 are async */
1423 
1424   if (transfer->endpoint) {
1425     struct darwin_interface *cInterface;
1426     uint8_t                 pipeRef, iface;
1427 
1428     if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1429       usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1430 
1431       return LIBUSB_ERROR_NOT_FOUND;
1432     }
1433 
1434     cInterface = &priv->interfaces[iface];
1435 
1436     kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
1437   } else
1438     /* control request on endpoint 0 */
1439     kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1440 
1441   if (kresult != kIOReturnSuccess)
1442     usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1443 
1444   return darwin_to_libusb (kresult);
1445 }
1446 
darwin_submit_transfer(struct usbi_transfer * itransfer)1447 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1448   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1449 
1450   switch (transfer->type) {
1451   case LIBUSB_TRANSFER_TYPE_CONTROL:
1452     return submit_control_transfer(itransfer);
1453   case LIBUSB_TRANSFER_TYPE_BULK:
1454   case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1455     return submit_bulk_transfer(itransfer);
1456   case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1457     return submit_iso_transfer(itransfer);
1458   default:
1459     usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1460     return LIBUSB_ERROR_INVALID_PARAM;
1461   }
1462 }
1463 
cancel_control_transfer(struct usbi_transfer * itransfer)1464 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1465   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1466   struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1467   IOReturn kresult;
1468 
1469   usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions control pipe");
1470 
1471   if (!dpriv->device)
1472     return LIBUSB_ERROR_NO_DEVICE;
1473 
1474   kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1475 
1476   return darwin_to_libusb (kresult);
1477 }
1478 
darwin_abort_transfers(struct usbi_transfer * itransfer)1479 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1480   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1481   struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1482   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1483   struct darwin_interface *cInterface;
1484   uint8_t pipeRef, iface;
1485   IOReturn kresult;
1486 
1487   if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1488     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1489 
1490     return LIBUSB_ERROR_NOT_FOUND;
1491   }
1492 
1493   cInterface = &priv->interfaces[iface];
1494 
1495   if (!dpriv->device)
1496     return LIBUSB_ERROR_NO_DEVICE;
1497 
1498   usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions on interface %d pipe %d", iface, pipeRef);
1499 
1500   /* abort transactions */
1501   (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1502 
1503   usbi_info (ITRANSFER_CTX (itransfer), "calling clear pipe stall to clear the data toggle bit");
1504 
1505   /* clear the data toggle bit */
1506 #if (InterfaceVersion < 190)
1507   kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1508 #else
1509   /* newer versions of darwin support clearing additional bits on the device's endpoint */
1510   kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1511 #endif
1512 
1513   return darwin_to_libusb (kresult);
1514 }
1515 
darwin_cancel_transfer(struct usbi_transfer * itransfer)1516 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1517   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1518 
1519   switch (transfer->type) {
1520   case LIBUSB_TRANSFER_TYPE_CONTROL:
1521     return cancel_control_transfer(itransfer);
1522   case LIBUSB_TRANSFER_TYPE_BULK:
1523   case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1524   case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1525     return darwin_abort_transfers (itransfer);
1526   default:
1527     usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1528     return LIBUSB_ERROR_INVALID_PARAM;
1529   }
1530 }
1531 
darwin_clear_transfer_priv(struct usbi_transfer * itransfer)1532 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1533   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1534   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1535 
1536   if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1537     free (tpriv->isoc_framelist);
1538     tpriv->isoc_framelist = NULL;
1539   }
1540 }
1541 
darwin_async_io_callback(void * refcon,IOReturn result,void * arg0)1542 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1543   struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1544   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1545   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1546   UInt32 message, size;
1547 
1548   usbi_info (ITRANSFER_CTX (itransfer), "an async io operation has completed");
1549 
1550   size = (UInt32) (uintptr_t) arg0;
1551 
1552   /* send a completion message to the device's file descriptor */
1553   message = MESSAGE_ASYNC_IO_COMPLETE;
1554   write (priv->fds[1], &message, sizeof (message));
1555   write (priv->fds[1], &itransfer, sizeof (itransfer));
1556   write (priv->fds[1], &result, sizeof (IOReturn));
1557   write (priv->fds[1], &size, sizeof (size));
1558 }
1559 
darwin_transfer_status(struct usbi_transfer * itransfer,kern_return_t result)1560 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1561   if (itransfer->flags & USBI_TRANSFER_TIMED_OUT)
1562     result = kIOUSBTransactionTimeout;
1563 
1564   switch (result) {
1565   case kIOReturnUnderrun:
1566   case kIOReturnSuccess:
1567     return LIBUSB_TRANSFER_COMPLETED;
1568   case kIOReturnAborted:
1569     return LIBUSB_TRANSFER_CANCELLED;
1570   case kIOUSBPipeStalled:
1571     usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: pipe is stalled");
1572     return LIBUSB_TRANSFER_STALL;
1573   case kIOReturnOverrun:
1574     usbi_err (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1575     return LIBUSB_TRANSFER_OVERFLOW;
1576   case kIOUSBTransactionTimeout:
1577     usbi_err (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1578     itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
1579     return LIBUSB_TRANSFER_TIMED_OUT;
1580   default:
1581     usbi_err (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1582     return LIBUSB_TRANSFER_ERROR;
1583   }
1584 }
1585 
darwin_handle_callback(struct usbi_transfer * itransfer,kern_return_t result,UInt32 io_size)1586 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1587   struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1588   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1589   int isIsoc      = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1590   int isBulk      = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1591   int isControl   = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1592   int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1593   int i;
1594 
1595   if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1596     usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1597     return;
1598   }
1599 
1600   usbi_info (ITRANSFER_CTX (itransfer), "handling %s completion with kernel status %d",
1601 	     isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", result);
1602 
1603   if (kIOReturnSuccess == result || kIOReturnUnderrun == result) {
1604     if (isIsoc && tpriv->isoc_framelist) {
1605       /* copy isochronous results back */
1606 
1607       for (i = 0; i < transfer->num_iso_packets ; i++) {
1608 	struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
1609 	lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1610 	lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1611       }
1612     } else if (!isIsoc)
1613       itransfer->transferred += io_size;
1614   }
1615 
1616   /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1617   usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, result));
1618 }
1619 
op_handle_events(struct libusb_context * ctx,struct pollfd * fds,POLL_NFDS_TYPE nfds,int num_ready)1620 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready) {
1621   struct usbi_transfer *itransfer;
1622   UInt32 io_size;
1623   IOReturn kresult;
1624   POLL_NFDS_TYPE i = 0;
1625   ssize_t ret;
1626   UInt32 message;
1627 
1628   usbi_mutex_lock(&ctx->open_devs_lock);
1629   for (i = 0; i < nfds && num_ready > 0; i++) {
1630     struct pollfd *pollfd = &fds[i];
1631     struct libusb_device_handle *handle;
1632     struct darwin_device_handle_priv *hpriv = NULL;
1633 
1634     usbi_info (ctx, "checking fd %i with revents = %x", fds[i], pollfd->revents);
1635 
1636     if (!pollfd->revents)
1637       continue;
1638 
1639     num_ready--;
1640     list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
1641       hpriv =  (struct darwin_device_handle_priv *)handle->os_priv;
1642       if (hpriv->fds[0] == pollfd->fd)
1643 	break;
1644     }
1645 
1646     if (!(pollfd->revents & POLLERR)) {
1647       ret = read (hpriv->fds[0], &message, sizeof (message));
1648       if (ret < (ssize_t)sizeof (message))
1649 	continue;
1650     } else
1651       /* could not poll the device-- response is to delete the device (this seems a little heavy-handed) */
1652       message = MESSAGE_DEVICE_GONE;
1653 
1654     switch (message) {
1655     case MESSAGE_DEVICE_GONE:
1656       /* remove the device's async port from the runloop */
1657       if (hpriv->cfSource) {
1658 	if (libusb_darwin_acfl)
1659 	  CFRunLoopRemoveSource (libusb_darwin_acfl, hpriv->cfSource, kCFRunLoopDefaultMode);
1660 	CFRelease (hpriv->cfSource);
1661 	hpriv->cfSource = NULL;
1662       }
1663 
1664       usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
1665       usbi_handle_disconnect(handle);
1666 
1667       /* done with this device */
1668       continue;
1669     case MESSAGE_ASYNC_IO_COMPLETE:
1670       read (hpriv->fds[0], &itransfer, sizeof (itransfer));
1671       read (hpriv->fds[0], &kresult, sizeof (IOReturn));
1672       read (hpriv->fds[0], &io_size, sizeof (UInt32));
1673 
1674       darwin_handle_callback (itransfer, kresult, io_size);
1675       break;
1676     default:
1677       usbi_err (ctx, "unknown message received from device pipe");
1678     }
1679   }
1680 
1681   usbi_mutex_unlock(&ctx->open_devs_lock);
1682 
1683   return 0;
1684 }
1685 
darwin_clock_gettime(int clk_id,struct timespec * tp)1686 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1687   mach_timespec_t sys_time;
1688   clock_serv_t clock_ref;
1689 
1690   switch (clk_id) {
1691   case USBI_CLOCK_REALTIME:
1692     /* CLOCK_REALTIME represents time since the epoch */
1693     clock_ref = clock_realtime;
1694     break;
1695   case USBI_CLOCK_MONOTONIC:
1696     /* use system boot time as reference for the monotonic clock */
1697     clock_ref = clock_monotonic;
1698     break;
1699   default:
1700     return LIBUSB_ERROR_INVALID_PARAM;
1701   }
1702 
1703   clock_get_time (clock_ref, &sys_time);
1704 
1705   tp->tv_sec  = sys_time.tv_sec;
1706   tp->tv_nsec = sys_time.tv_nsec;
1707 
1708   return 0;
1709 }
1710 
1711 const struct usbi_os_backend darwin_backend = {
1712 	.name = "Darwin",
1713 	.init = darwin_init,
1714 	.exit = darwin_exit,
1715 	.get_device_list = darwin_get_device_list,
1716 	.get_device_descriptor = darwin_get_device_descriptor,
1717 	.get_active_config_descriptor = darwin_get_active_config_descriptor,
1718 	.get_config_descriptor = darwin_get_config_descriptor,
1719 
1720 	.open = darwin_open,
1721 	.close = darwin_close,
1722 	.get_configuration = darwin_get_configuration,
1723 	.set_configuration = darwin_set_configuration,
1724 	.claim_interface = darwin_claim_interface,
1725 	.release_interface = darwin_release_interface,
1726 
1727 	.set_interface_altsetting = darwin_set_interface_altsetting,
1728 	.clear_halt = darwin_clear_halt,
1729 	.reset_device = darwin_reset_device,
1730 
1731 	.kernel_driver_active = darwin_kernel_driver_active,
1732 	.detach_kernel_driver = darwin_detach_kernel_driver,
1733 	.attach_kernel_driver = darwin_attach_kernel_driver,
1734 
1735 	.destroy_device = darwin_destroy_device,
1736 
1737 	.submit_transfer = darwin_submit_transfer,
1738 	.cancel_transfer = darwin_cancel_transfer,
1739 	.clear_transfer_priv = darwin_clear_transfer_priv,
1740 
1741 	.handle_events = op_handle_events,
1742 
1743 	.clock_gettime = darwin_clock_gettime,
1744 
1745 	.device_priv_size = sizeof(struct darwin_device_priv),
1746 	.device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1747 	.transfer_priv_size = sizeof(struct darwin_transfer_priv),
1748 	.add_iso_packet_size = 0,
1749 };
1750 
1751