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