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