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