Darwin: fix interface object leak
[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     if (current_interface != ifc)
754       (void) IOObjectRelease (*usbInterfacep);
755   }
756
757   /* done with the interface iterator */
758   IOObjectRelease(interface_iterator);
759
760   return 0;
761 }
762
763 static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
764   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
765
766   /* current interface */
767   struct __darwin_interface *cInterface = &priv->interfaces[iface];
768
769   kern_return_t kresult;
770
771   u_int8_t numep, direction, number;
772   u_int8_t dont_care1, dont_care3;
773   u_int16_t dont_care2;
774   int i;
775
776   usbi_info (HANDLE_CTX (dev_handle), "building table of endpoints.");
777
778   /* retrieve the total number of endpoints on this interface */
779   kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
780   if (kresult) {
781     usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
782     return darwin_to_libusb (kresult);
783   }
784
785   /* iterate through pipe references */
786   for (i = 1 ; i <= numep ; i++) {
787     kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
788                                                             &dont_care2, &dont_care3);
789
790     if (kresult != kIOReturnSuccess) {
791       usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
792
793       return darwin_to_libusb (kresult);
794     }
795
796     usbi_info (HANDLE_CTX (dev_handle), "interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
797
798     cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
799   }
800
801   cInterface->num_endpoints = numep;
802
803   return 0;
804 }
805
806 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
807   struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
808   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
809   io_service_t          usbInterface = IO_OBJECT_NULL;
810   IOReturn kresult;
811   IOCFPlugInInterface **plugInInterface = NULL;
812   SInt32                score;
813   uint8_t               new_config;
814
815   /* current interface */
816   struct __darwin_interface *cInterface = &priv->interfaces[iface];
817
818   kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
819   if (kresult != kIOReturnSuccess)
820     return darwin_to_libusb (kresult);
821
822   /* make sure we have an interface */
823   if (!usbInterface) {
824     u_int8_t nConfig;     /* Index of configuration to use */
825     IOUSBConfigurationDescriptorPtr configDesc; /* to describe which configuration to select */
826     /* Only a composite class device with no vendor-specific driver will
827        be configured. Otherwise, we need to do it ourselves, or there
828        will be no interfaces for the device. */
829
830     usbi_info (HANDLE_CTX (dev_handle), "no interface found; selecting configuration" );
831
832     kresult = (*(dpriv->device))->GetNumberOfConfigurations (dpriv->device, &nConfig);
833     if (kresult != kIOReturnSuccess) {
834       usbi_err (HANDLE_CTX (dev_handle), "GetNumberOfConfigurations: %s", darwin_error_str(kresult));
835       return darwin_to_libusb(kresult);
836     }
837
838     if (nConfig < 1) {
839       usbi_err (HANDLE_CTX (dev_handle), "GetNumberOfConfigurations: no configurations");
840       return LIBUSB_ERROR_OTHER;
841     }
842
843     usbi_info (HANDLE_CTX (dev_handle), "device has %d configuration%s. using the first",
844               (int)nConfig, (nConfig > 1 ? "s" : "") );
845
846     /* Always use the first configuration */
847     kresult = (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, 0, &configDesc);
848     if (kresult != kIOReturnSuccess) {
849       usbi_err (HANDLE_CTX (dev_handle), "GetConfigurationDescriptorPtr: %s",
850                 darwin_error_str(kresult));
851
852       new_config = 1;
853     } else
854       new_config = configDesc->bConfigurationValue;
855
856     usbi_info (HANDLE_CTX (dev_handle), "new configuration value is %d", new_config);
857
858     /* set the configuration */
859     kresult = darwin_set_configuration (dev_handle, new_config);
860     if (kresult != LIBUSB_SUCCESS) {
861       usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
862       return kresult;
863     }
864
865     kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
866     if (kresult) {
867       usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
868       return darwin_to_libusb (kresult);
869     }
870   }
871
872   if (!usbInterface) {
873     usbi_err (HANDLE_CTX (dev_handle), "interface not found");
874     return LIBUSB_ERROR_NOT_FOUND;
875   }
876
877   /* get an interface to the device's interface */
878   kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
879                                                kIOCFPlugInInterfaceID, &plugInInterface, &score);
880   if (kresult) {
881     usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
882     return darwin_to_libusb (kresult);
883   }
884
885   if (!plugInInterface) {
886     usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
887     return LIBUSB_ERROR_NOT_FOUND;
888   }
889
890   /* ignore release error */
891   (void)IOObjectRelease (usbInterface);
892
893   /* Do the actual claim */
894   kresult = (*plugInInterface)->QueryInterface(plugInInterface,
895                                                CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
896                                                (LPVOID)&cInterface->interface);
897   if (kresult || !cInterface->interface) {
898     usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
899     return darwin_to_libusb (kresult);
900   }
901
902   /* We no longer need the intermediate plug-in */
903   (*plugInInterface)->Release(plugInInterface);
904
905   /* claim the interface */
906   kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
907   if (kresult) {
908     usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
909     return darwin_to_libusb (kresult);
910   }
911
912   /* update list of endpoints */
913   kresult = get_endpoints (dev_handle, iface);
914   if (kresult) {
915     /* this should not happen */
916     darwin_release_interface (dev_handle, iface);
917     usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
918     return kresult;
919   }
920
921   cInterface->cfSource = NULL;
922
923   /* create async event source */
924   kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
925   if (kresult != kIOReturnSuccess) {
926     usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
927
928     /* can't continue without an async event source */
929     (void)darwin_release_interface (dev_handle, iface);
930
931     return darwin_to_libusb (kresult);
932   }
933
934   /* add the cfSource to the async thread's run loop */
935   CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
936
937   usbi_info (HANDLE_CTX (dev_handle), "interface opened");
938
939   return 0;
940 }
941
942 static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
943   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
944   IOReturn kresult;
945
946   /* current interface */
947   struct __darwin_interface *cInterface = &priv->interfaces[iface];
948
949   /* Check to see if an interface is open */
950   if (!cInterface->interface)
951     return LIBUSB_SUCCESS;
952
953   /* clean up endpoint data */
954   cInterface->num_endpoints = 0;
955
956   /* delete the interface's async event source */
957   if (cInterface->cfSource) {
958     CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
959     CFRelease (cInterface->cfSource);
960   }
961
962   kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
963   if (kresult)
964     usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
965
966   kresult = (*(cInterface->interface))->Release(cInterface->interface);
967   if (kresult != kIOReturnSuccess)
968     usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
969
970   cInterface->interface = IO_OBJECT_NULL;
971
972   return darwin_to_libusb (kresult);
973 }
974
975 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
976   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
977   IOReturn kresult;
978
979   /* current interface */
980   struct __darwin_interface *cInterface = &priv->interfaces[iface];
981
982   if (!cInterface->interface)
983     return LIBUSB_ERROR_NO_DEVICE;
984
985   kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
986   if (kresult != kIOReturnSuccess)
987     darwin_reset_device (dev_handle);
988
989   /* update list of endpoints */
990   kresult = get_endpoints (dev_handle, iface);
991   if (kresult) {
992     /* this should not happen */
993     darwin_release_interface (dev_handle, iface);
994     usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
995     return kresult;
996   }
997
998   return darwin_to_libusb (kresult);
999 }
1000
1001 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1002   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
1003
1004   /* current interface */
1005   struct __darwin_interface *cInterface;
1006   uint8_t pipeRef, iface;
1007   IOReturn kresult;
1008
1009   /* determine the interface/endpoint to use */
1010   if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
1011     usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1012
1013     return LIBUSB_ERROR_NOT_FOUND;
1014   }
1015
1016   cInterface = &priv->interfaces[iface];
1017
1018 #if (InterfaceVersion < 190)
1019   kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1020 #else
1021   /* newer versions of darwin support clearing additional bits on the device's endpoint */
1022   kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1023 #endif
1024   if (kresult)
1025     usbi_err (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1026
1027   return darwin_to_libusb (kresult);
1028 }
1029
1030 static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
1031   struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1032   IOReturn kresult;
1033
1034   kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
1035   if (kresult)
1036     usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
1037
1038   return darwin_to_libusb (kresult);
1039 }
1040
1041 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
1042   struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
1043   io_service_t usbInterface;
1044   CFTypeRef driver;
1045   IOReturn kresult;
1046
1047   kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
1048   if (kresult) {
1049     usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
1050
1051     return darwin_to_libusb (kresult);
1052   }
1053
1054   driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
1055   IOObjectRelease (usbInterface);
1056
1057   if (driver) {
1058     CFRelease (driver);
1059
1060     return 1;
1061   }
1062
1063   /* no driver */
1064   return 0;
1065 }
1066
1067 /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
1068 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1069   return LIBUSB_ERROR_NOT_SUPPORTED;
1070 }
1071
1072 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
1073   return LIBUSB_ERROR_NOT_SUPPORTED;
1074 }
1075
1076 static void darwin_destroy_device(struct libusb_device *dev) {
1077 }
1078
1079 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
1080   struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1081   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1082
1083   IOReturn               ret;
1084   uint8_t                is_read; /* 0 = we're reading, 1 = we're writing */
1085   uint8_t                transferType;
1086   /* None of the values below are used in libusb for bulk transfers */
1087   uint8_t                direction, number, interval, pipeRef, iface;
1088   uint16_t               maxPacketSize;
1089
1090   struct __darwin_interface *cInterface;
1091
1092   /* are we reading or writing? */
1093   is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1094
1095   if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1096     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1097
1098     return LIBUSB_ERROR_NOT_FOUND;
1099   }
1100
1101   cInterface = &priv->interfaces[iface];
1102
1103   (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
1104                                                  &transferType, &maxPacketSize, &interval);
1105
1106   /* submit the request */
1107   /* timeouts are unavailable on interrupt endpoints */
1108   if (transferType == kUSBInterrupt) {
1109     if (is_read)
1110       ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1111                                                       transfer->length, darwin_async_io_callback, itransfer);
1112     else
1113       ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
1114                                                        transfer->length, darwin_async_io_callback, itransfer);
1115   } else {
1116     if (is_read)
1117       ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1118                                                         transfer->length, transfer->timeout, transfer->timeout,
1119                                                         darwin_async_io_callback, (void *)itransfer);
1120     else
1121       ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
1122                                                          transfer->length, transfer->timeout, transfer->timeout,
1123                                                          darwin_async_io_callback, (void *)itransfer);
1124   }
1125
1126   if (ret)
1127     usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", is_read ? "In" : "Out",
1128                darwin_error_str(ret), ret);
1129
1130   return darwin_to_libusb (ret);
1131 }
1132
1133 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
1134   struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1135   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1136   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1137
1138   IOReturn                kresult;
1139   uint8_t                 is_read; /* 0 = we're writing, 1 = we're reading */
1140   uint8_t                 pipeRef, iface;
1141   UInt64                  frame;
1142   AbsoluteTime            atTime;
1143   int                     i;
1144
1145   struct __darwin_interface *cInterface;
1146
1147   /* are we reading or writing? */
1148   is_read = transfer->endpoint & LIBUSB_ENDPOINT_IN;
1149
1150   /* construct an array of IOUSBIsocFrames */
1151   tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
1152   if (!tpriv->isoc_framelist)
1153     return LIBUSB_ERROR_NO_MEM;
1154
1155   /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
1156   for (i = 0 ; i < transfer->num_iso_packets ; i++)
1157     tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
1158
1159   /* determine the interface/endpoint to use */
1160   if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1161     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1162
1163     return LIBUSB_ERROR_NOT_FOUND;
1164   }
1165
1166   cInterface = &priv->interfaces[iface];
1167
1168   /* Last but not least we need the bus frame number */
1169   kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
1170   if (kresult) {
1171     usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
1172     free(tpriv->isoc_framelist);
1173     tpriv->isoc_framelist = NULL;
1174
1175     return darwin_to_libusb (kresult);
1176   }
1177
1178   /* schedule for a frame a little in the future */
1179   frame += 2;
1180
1181   /* submit the request */
1182   if (is_read)
1183     kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1184                                                              transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1185                                                              itransfer);
1186   else
1187     kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
1188                                                               transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
1189                                                               itransfer);
1190
1191   if (kresult != kIOReturnSuccess) {
1192     usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", is_read ? "In" : "Out",
1193                darwin_error_str(kresult));
1194     free (tpriv->isoc_framelist);
1195     tpriv->isoc_framelist = NULL;
1196   }
1197
1198   return darwin_to_libusb (kresult);
1199 }
1200
1201 static int submit_control_transfer(struct usbi_transfer *itransfer) {
1202   struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1203   struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
1204   struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1205   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1206
1207   IOReturn               kresult;
1208
1209   bzero(&tpriv->req, sizeof(tpriv->req));
1210
1211   /* IOUSBDeviceInterface expects the request in cpu endianess */
1212   tpriv->req.bmRequestType     = setup->bmRequestType;
1213   tpriv->req.bRequest          = setup->bRequest;
1214   /* these values should be in bus order from libusb_fill_control_setup */
1215   tpriv->req.wValue            = OSSwapLittleToHostInt16 (setup->wValue);
1216   tpriv->req.wIndex            = OSSwapLittleToHostInt16 (setup->wIndex);
1217   tpriv->req.wLength           = OSSwapLittleToHostInt16 (setup->wLength);
1218   /* data is stored after the libusb control block */
1219   tpriv->req.pData             = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
1220   tpriv->req.completionTimeout = transfer->timeout;
1221   tpriv->req.noDataTimeout     = transfer->timeout;
1222
1223   /* all transfers in libusb-1.0 are async */
1224   kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
1225
1226   if (kresult != kIOReturnSuccess)
1227     usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
1228
1229   return darwin_to_libusb (kresult);
1230 }
1231
1232 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
1233   struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1234
1235   switch (transfer->type) {
1236   case LIBUSB_TRANSFER_TYPE_CONTROL:
1237     return submit_control_transfer(itransfer);
1238   case LIBUSB_TRANSFER_TYPE_BULK:
1239   case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1240     return submit_bulk_transfer(itransfer);
1241   case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1242     return submit_iso_transfer(itransfer);
1243   default:
1244     usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1245     return LIBUSB_ERROR_INVALID_PARAM;
1246   }
1247 }
1248
1249 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
1250   struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1251   struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
1252   IOReturn kresult;
1253
1254   usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions control pipe");
1255
1256   kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
1257
1258   return darwin_to_libusb (kresult);
1259 }
1260
1261 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
1262   struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1263   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1264   struct __darwin_interface *cInterface;
1265   uint8_t pipeRef, iface;
1266   IOReturn kresult;
1267
1268   if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
1269     usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
1270
1271     return LIBUSB_ERROR_NOT_FOUND;
1272   }
1273
1274   cInterface = &priv->interfaces[iface];
1275
1276   usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions on interface %d pipe %d", iface, pipeRef);
1277
1278   /* abort transactions */
1279   (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
1280
1281   usbi_info (ITRANSFER_CTX (itransfer), "calling clear pipe stall to clear the data toggle bit");
1282
1283   /* clear the data toggle bit */
1284 #if (InterfaceVersion < 190)
1285   kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
1286 #else
1287   /* newer versions of darwin support clearing additional bits on the device's endpoint */
1288   kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
1289 #endif
1290
1291   return darwin_to_libusb (kresult);
1292 }
1293
1294 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
1295   struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1296
1297   switch (transfer->type) {
1298   case LIBUSB_TRANSFER_TYPE_CONTROL:
1299     return cancel_control_transfer(itransfer);
1300   case LIBUSB_TRANSFER_TYPE_BULK:
1301   case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1302   case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1303     return darwin_abort_transfers (itransfer);
1304   default:
1305     usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1306     return LIBUSB_ERROR_INVALID_PARAM;
1307   }
1308 }
1309
1310 static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
1311   struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1312   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1313
1314   if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
1315     free (tpriv->isoc_framelist);
1316     tpriv->isoc_framelist = NULL;
1317   }
1318 }
1319
1320 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
1321   struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
1322   struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1323   struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
1324   UInt32 message;
1325
1326   usbi_info (ITRANSFER_CTX (itransfer), "an async io operation has completed");
1327
1328   /* send a completion message to the device's file descriptor */
1329   message = MESSAGE_ASYNC_IO_COMPLETE;
1330   write (priv->fds[1], &message, sizeof (message));
1331   write (priv->fds[1], &itransfer, sizeof (itransfer));
1332   write (priv->fds[1], &result, sizeof (IOReturn));
1333   write (priv->fds[1], &arg0, sizeof (UInt32));
1334 }
1335
1336 static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
1337   switch (result) {
1338   case kIOReturnSuccess:
1339     return LIBUSB_TRANSFER_COMPLETED;
1340   case kIOReturnAborted:
1341     return LIBUSB_TRANSFER_CANCELLED;
1342   case kIOUSBPipeStalled:
1343     usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: pipe is stalled");
1344     return LIBUSB_TRANSFER_STALL;
1345   case kIOReturnOverrun:
1346     usbi_err (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
1347     return LIBUSB_TRANSFER_OVERFLOW;
1348   case kIOUSBTransactionTimeout:
1349     usbi_err (ITRANSFER_CTX (itransfer), "transfer error: timed out");
1350     return LIBUSB_TRANSFER_TIMED_OUT;
1351   default:
1352     usbi_err (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
1353     return LIBUSB_TRANSFER_ERROR;
1354   }
1355 }
1356
1357 static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
1358   struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1359   struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1360   int isIsoc      = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
1361   int isBulk      = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
1362   int isControl   = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
1363   int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
1364   int i;
1365
1366   if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
1367     usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1368     return;
1369   }
1370
1371   usbi_info (ITRANSFER_CTX (itransfer), "handling %s completion with kernel status %d",
1372              isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", result);
1373
1374   if (kIOReturnSuccess == result) {
1375     if (isIsoc && tpriv->isoc_framelist) {
1376       /* copy isochronous results back */
1377
1378       for (i = 0; i < transfer->num_iso_packets ; i++) {
1379         struct libusb_iso_packet_descriptor *lib_desc = transfer->iso_packet_desc;
1380         lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
1381         lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
1382       }
1383     } else if (!isIsoc)
1384       itransfer->transferred += io_size;
1385   }
1386
1387   /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
1388   usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, result));
1389 }
1390
1391 static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, nfds_t nfds, int num_ready) {
1392   struct usbi_transfer *itransfer;
1393   UInt32 io_size;
1394   IOReturn kresult;
1395   int i = 0, ret;
1396   UInt32 message;
1397
1398   usbi_mutex_lock(&ctx->open_devs_lock);
1399   for (i = 0; i < nfds && num_ready > 0; i++) {
1400     struct pollfd *pollfd = &fds[i];
1401     struct libusb_device_handle *handle;
1402     struct darwin_device_handle_priv *hpriv = NULL;
1403
1404     usbi_info (ctx, "checking fd %i with revents = %x", fds[i], pollfd->revents);
1405
1406     if (!pollfd->revents)
1407       continue;
1408
1409     num_ready--;
1410     list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
1411       hpriv =  (struct darwin_device_handle_priv *)handle->os_priv;
1412       if (hpriv->fds[0] == pollfd->fd)
1413         break;
1414     }
1415
1416     if (!(pollfd->revents & POLLERR)) {
1417       ret = read (hpriv->fds[0], &message, sizeof (message));
1418       if (ret < sizeof (message))
1419         continue;
1420     } else
1421       /* could not poll the device-- response is to delete the device (this seems a little heavy-handed) */
1422       message = MESSAGE_DEVICE_GONE;
1423
1424     switch (message) {
1425     case MESSAGE_DEVICE_GONE:
1426       /* remove the device's async port from the runloop */
1427       if (hpriv->cfSource) {
1428         if (libusb_darwin_acfl)
1429           CFRunLoopRemoveSource (libusb_darwin_acfl, hpriv->cfSource, kCFRunLoopDefaultMode);
1430         CFRelease (hpriv->cfSource);
1431         hpriv->cfSource = NULL;
1432       }
1433
1434       usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fds[0]);
1435       usbi_handle_disconnect(handle);
1436
1437       /* done with this device */
1438       continue;
1439     case MESSAGE_ASYNC_IO_COMPLETE:
1440       read (hpriv->fds[0], &itransfer, sizeof (itransfer));
1441       read (hpriv->fds[0], &kresult, sizeof (IOReturn));
1442       read (hpriv->fds[0], &io_size, sizeof (UInt32));
1443
1444       darwin_handle_callback (itransfer, kresult, io_size);
1445       break;
1446     default:
1447       usbi_err (ctx, "unknown message received from device pipe");
1448     }
1449   }
1450
1451   usbi_mutex_unlock(&ctx->open_devs_lock);
1452
1453   return 0;
1454 }
1455
1456 static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
1457   mach_timespec_t sys_time;
1458   clock_serv_t clock_ref;
1459
1460   switch (clk_id) {
1461   case USBI_CLOCK_REALTIME:
1462     /* CLOCK_REALTIME represents time since the epoch */
1463     host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &clock_ref);
1464     break;
1465   case USBI_CLOCK_MONOTONIC:
1466     /* use system boot time as reference for the monotonic clock */
1467     host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &clock_ref);
1468     break;
1469   default:
1470     return LIBUSB_ERROR_INVALID_PARAM;
1471   }
1472
1473   clock_get_time (clock_ref, &sys_time);
1474
1475   tp->tv_sec  = sys_time.tv_sec;
1476   tp->tv_nsec = sys_time.tv_nsec;
1477
1478   return 0;
1479 }
1480
1481 const struct usbi_os_backend darwin_backend = {
1482         .name = "Darwin",
1483         .init = darwin_init,
1484         .exit = darwin_exit,
1485         .get_device_list = darwin_get_device_list,
1486         .get_device_descriptor = darwin_get_device_descriptor,
1487         .get_active_config_descriptor = darwin_get_active_config_descriptor,
1488         .get_config_descriptor = darwin_get_config_descriptor,
1489
1490         .open = darwin_open,
1491         .close = darwin_close,
1492         .get_configuration = darwin_get_configuration,
1493         .set_configuration = darwin_set_configuration,
1494         .claim_interface = darwin_claim_interface,
1495         .release_interface = darwin_release_interface,
1496
1497         .set_interface_altsetting = darwin_set_interface_altsetting,
1498         .clear_halt = darwin_clear_halt,
1499         .reset_device = darwin_reset_device,
1500
1501         .kernel_driver_active = darwin_kernel_driver_active,
1502         .detach_kernel_driver = darwin_detach_kernel_driver,
1503         .attach_kernel_driver = darwin_attach_kernel_driver,
1504
1505         .destroy_device = darwin_destroy_device,
1506
1507         .submit_transfer = darwin_submit_transfer,
1508         .cancel_transfer = darwin_cancel_transfer,
1509         .clear_transfer_priv = darwin_clear_transfer_priv,
1510
1511         .handle_events = op_handle_events,
1512
1513         .clock_gettime = darwin_clock_gettime,
1514
1515         .device_priv_size = sizeof(struct darwin_device_priv),
1516         .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
1517         .transfer_priv_size = sizeof(struct darwin_transfer_priv),
1518         .add_iso_packet_size = 0,
1519 };
1520