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