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