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