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