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