darwin_usb.c 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788
  1. /* -*- Mode: C; indent-tabs-mode:nil -*- */
  2. /*
  3. * darwin backend for libusb 1.0
  4. * Copyright (C) 2008-2013 Nathan Hjelm <hjelmn@users.sourceforge.net>
  5. *
  6. * This library is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * This library is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with this library; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. #include <config.h>
  21. #include <ctype.h>
  22. #include <errno.h>
  23. #include <pthread.h>
  24. #include <stdio.h>
  25. #include <stdlib.h>
  26. #include <string.h>
  27. #include <sys/types.h>
  28. #include <unistd.h>
  29. #include <fcntl.h>
  30. #include <libkern/OSAtomic.h>
  31. #include <mach/clock.h>
  32. #include <mach/clock_types.h>
  33. #include <mach/mach_host.h>
  34. #include <mach/mach_port.h>
  35. #include <AvailabilityMacros.h>
  36. #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
  37. #include <objc/objc-auto.h>
  38. #endif
  39. #include "darwin_usb.h"
  40. /* async event thread */
  41. static pthread_mutex_t libusb_darwin_at_mutex = PTHREAD_MUTEX_INITIALIZER;
  42. static pthread_cond_t libusb_darwin_at_cond = PTHREAD_COND_INITIALIZER;
  43. static clock_serv_t clock_realtime;
  44. static clock_serv_t clock_monotonic;
  45. static CFRunLoopRef libusb_darwin_acfl = NULL; /* event cf loop */
  46. static volatile int32_t initCount = 0;
  47. /* async event thread */
  48. static pthread_t libusb_darwin_at;
  49. static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian);
  50. static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface);
  51. static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface);
  52. static int darwin_reset_device(struct libusb_device_handle *dev_handle);
  53. static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
  54. static int darwin_scan_devices(struct libusb_context *ctx);
  55. static int process_new_device (struct libusb_context *ctx, usb_device_t **device, UInt32 locationID);
  56. #if defined(ENABLE_LOGGING)
  57. static const char *darwin_error_str (int result) {
  58. switch (result) {
  59. case kIOReturnSuccess:
  60. return "no error";
  61. case kIOReturnNotOpen:
  62. return "device not opened for exclusive access";
  63. case kIOReturnNoDevice:
  64. return "no connection to an IOService";
  65. case kIOUSBNoAsyncPortErr:
  66. return "no async port has been opened for interface";
  67. case kIOReturnExclusiveAccess:
  68. return "another process has device opened for exclusive access";
  69. case kIOUSBPipeStalled:
  70. return "pipe is stalled";
  71. case kIOReturnError:
  72. return "could not establish a connection to the Darwin kernel";
  73. case kIOUSBTransactionTimeout:
  74. return "transaction timed out";
  75. case kIOReturnBadArgument:
  76. return "invalid argument";
  77. case kIOReturnAborted:
  78. return "transaction aborted";
  79. case kIOReturnNotResponding:
  80. return "device not responding";
  81. case kIOReturnOverrun:
  82. return "data overrun";
  83. case kIOReturnCannotWire:
  84. return "physical memory can not be wired down";
  85. case kIOReturnNoResources:
  86. return "out of resources";
  87. default:
  88. return "unknown error";
  89. }
  90. }
  91. #endif
  92. static int darwin_to_libusb (int result) {
  93. switch (result) {
  94. case kIOReturnUnderrun:
  95. case kIOReturnSuccess:
  96. return LIBUSB_SUCCESS;
  97. case kIOReturnNotOpen:
  98. case kIOReturnNoDevice:
  99. return LIBUSB_ERROR_NO_DEVICE;
  100. case kIOReturnExclusiveAccess:
  101. return LIBUSB_ERROR_ACCESS;
  102. case kIOUSBPipeStalled:
  103. return LIBUSB_ERROR_PIPE;
  104. case kIOReturnBadArgument:
  105. return LIBUSB_ERROR_INVALID_PARAM;
  106. case kIOUSBTransactionTimeout:
  107. return LIBUSB_ERROR_TIMEOUT;
  108. case kIOReturnNotResponding:
  109. case kIOReturnAborted:
  110. case kIOReturnError:
  111. case kIOUSBNoAsyncPortErr:
  112. default:
  113. return LIBUSB_ERROR_OTHER;
  114. }
  115. }
  116. static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp) {
  117. struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
  118. /* current interface */
  119. struct darwin_interface *cInterface;
  120. int8_t i, iface;
  121. usbi_info (HANDLE_CTX(dev_handle), "converting ep address 0x%02x to pipeRef and interface", ep);
  122. for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
  123. cInterface = &priv->interfaces[iface];
  124. if (dev_handle->claimed_interfaces & (1 << iface)) {
  125. for (i = 0 ; i < cInterface->num_endpoints ; i++) {
  126. if (cInterface->endpoint_addrs[i] == ep) {
  127. *pipep = i + 1;
  128. *ifcp = iface;
  129. usbi_info (HANDLE_CTX(dev_handle), "pipe %d on interface %d matches", *pipep, *ifcp);
  130. return 0;
  131. }
  132. }
  133. }
  134. }
  135. /* No pipe found with the correct endpoint address */
  136. usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
  137. return -1;
  138. }
  139. static int usb_setup_device_iterator (io_iterator_t *deviceIterator, UInt32 location) {
  140. CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBDeviceClassName);
  141. if (!matchingDict)
  142. return kIOReturnError;
  143. if (location) {
  144. CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
  145. &kCFTypeDictionaryKeyCallBacks,
  146. &kCFTypeDictionaryValueCallBacks);
  147. if (propertyMatchDict) {
  148. /* there are no unsigned CFNumber types so treat the value as signed. the os seems to do this
  149. internally (CFNumberType of locationID is 3) */
  150. CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberSInt32Type, &location);
  151. CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
  152. /* release our reference to the CFNumber (CFDictionarySetValue retains it) */
  153. CFRelease (locationCF);
  154. CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
  155. /* release out reference to the CFMutableDictionaryRef (CFDictionarySetValue retains it) */
  156. CFRelease (propertyMatchDict);
  157. }
  158. /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
  159. }
  160. return IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, deviceIterator);
  161. }
  162. static usb_device_t **usb_get_next_device (io_iterator_t deviceIterator, UInt32 *locationp) {
  163. io_cf_plugin_ref_t *plugInInterface = NULL;
  164. usb_device_t **device;
  165. io_service_t usbDevice;
  166. long result;
  167. SInt32 score;
  168. if (!IOIteratorIsValid (deviceIterator))
  169. return NULL;
  170. while ((usbDevice = IOIteratorNext(deviceIterator))) {
  171. result = IOCreatePlugInInterfaceForService(usbDevice, kIOUSBDeviceUserClientTypeID,
  172. kIOCFPlugInInterfaceID, &plugInInterface,
  173. &score);
  174. /* we are done with the usb_device_t */
  175. (void)IOObjectRelease(usbDevice);
  176. if (kIOReturnSuccess == result && plugInInterface)
  177. break;
  178. usbi_dbg ("libusb/darwin.c usb_get_next_device: could not set up plugin for service: %s\n", darwin_error_str (result));
  179. }
  180. if (!usbDevice)
  181. return NULL;
  182. (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
  183. (LPVOID)&device);
  184. /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
  185. (*plugInInterface)->Release (plugInInterface);
  186. /* get the location from the device */
  187. if (locationp)
  188. (*(device))->GetLocationID(device, locationp);
  189. return device;
  190. }
  191. static void darwin_devices_attached (void *ptr, io_iterator_t add_devices) {
  192. struct libusb_context *ctx;
  193. usb_device_t **device;
  194. UInt32 location;
  195. usbi_mutex_lock(&active_contexts_lock);
  196. while ((device = usb_get_next_device (add_devices, &location))) {
  197. /* add this device to each active context's device list */
  198. list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
  199. process_new_device (ctx, device, location);
  200. }
  201. /* release extra reference */
  202. (*device)->Release (device);
  203. }
  204. usbi_mutex_unlock(&active_contexts_lock);
  205. }
  206. static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
  207. struct libusb_device *dev = NULL;
  208. struct libusb_context *ctx;
  209. io_service_t device;
  210. bool locationValid;
  211. UInt32 location;
  212. CFTypeRef locationCF;
  213. while ((device = IOIteratorNext (rem_devices)) != 0) {
  214. /* get the location from the i/o registry */
  215. locationCF = IORegistryEntryCreateCFProperty (device, CFSTR(kUSBDevicePropertyLocationID), kCFAllocatorDefault, 0);
  216. IOObjectRelease (device);
  217. if (!locationCF)
  218. continue;
  219. locationValid = CFGetTypeID(locationCF) == CFNumberGetTypeID() &&
  220. CFNumberGetValue(locationCF, kCFNumberSInt32Type, &location);
  221. CFRelease (locationCF);
  222. if (!locationValid)
  223. continue;
  224. usbi_mutex_lock(&active_contexts_lock);
  225. list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
  226. usbi_dbg ("libusb/darwin.c darwin_devices_detached: notifying context %p of device disconnect", ctx);
  227. dev = usbi_get_device_by_session_id (ctx, location);
  228. if (!dev) {
  229. continue;
  230. }
  231. /* signal the core that this device has been disconnected. the core will tear down this device
  232. when the reference count reaches 0 */
  233. usbi_disconnect_device (dev);
  234. }
  235. usbi_mutex_unlock(&active_contexts_lock);
  236. }
  237. }
  238. static void darwin_clear_iterator (io_iterator_t iter) {
  239. io_service_t device;
  240. while ((device = IOIteratorNext (iter)) != 0)
  241. IOObjectRelease (device);
  242. }
  243. static void *darwin_event_thread_main (void *arg0) {
  244. IOReturn kresult;
  245. struct libusb_context *ctx = (struct libusb_context *)arg0;
  246. CFRunLoopRef runloop;
  247. /* Set this thread's name, so it can be seen in the debugger
  248. and crash reports. */
  249. #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
  250. pthread_setname_np ("org.libusb.device-hotplug");
  251. #endif
  252. /* Tell the Objective-C garbage collector about this thread.
  253. This is required because, unlike NSThreads, pthreads are
  254. not automatically registered. Although we don't use
  255. Objective-C, we use CoreFoundation, which does. */
  256. #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
  257. objc_registerThreadWithCollector();
  258. #endif
  259. /* hotplug (device arrival/removal) sources */
  260. CFRunLoopSourceRef libusb_notification_cfsource;
  261. io_notification_port_t libusb_notification_port;
  262. io_iterator_t libusb_rem_device_iterator;
  263. io_iterator_t libusb_add_device_iterator;
  264. usbi_info (ctx, "creating hotplug event source");
  265. runloop = CFRunLoopGetCurrent ();
  266. CFRetain (runloop);
  267. /* add the notification port to the run loop */
  268. libusb_notification_port = IONotificationPortCreate (kIOMasterPortDefault);
  269. libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
  270. CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
  271. /* create notifications for removed devices */
  272. kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
  273. IOServiceMatching(kIOUSBDeviceClassName),
  274. (IOServiceMatchingCallback)darwin_devices_detached,
  275. (void *)ctx, &libusb_rem_device_iterator);
  276. if (kresult != kIOReturnSuccess) {
  277. usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
  278. pthread_exit (NULL);
  279. }
  280. /* create notifications for attached devices */
  281. kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOFirstMatchNotification,
  282. IOServiceMatching(kIOUSBDeviceClassName),
  283. (IOServiceMatchingCallback)darwin_devices_attached,
  284. (void *)ctx, &libusb_add_device_iterator);
  285. if (kresult != kIOReturnSuccess) {
  286. usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
  287. pthread_exit (NULL);
  288. }
  289. /* arm notifiers */
  290. darwin_clear_iterator (libusb_rem_device_iterator);
  291. darwin_clear_iterator (libusb_add_device_iterator);
  292. usbi_info (ctx, "darwin event thread ready to receive events");
  293. /* signal the main thread that the hotplug runloop has been created. */
  294. pthread_mutex_lock (&libusb_darwin_at_mutex);
  295. libusb_darwin_acfl = runloop;
  296. pthread_cond_signal (&libusb_darwin_at_cond);
  297. pthread_mutex_unlock (&libusb_darwin_at_mutex);
  298. /* run the runloop */
  299. CFRunLoopRun();
  300. usbi_info (ctx, "darwin event thread exiting");
  301. /* remove the notification cfsource */
  302. CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
  303. /* delete notification port */
  304. IONotificationPortDestroy (libusb_notification_port);
  305. /* delete iterators */
  306. IOObjectRelease (libusb_rem_device_iterator);
  307. IOObjectRelease (libusb_add_device_iterator);
  308. CFRelease (runloop);
  309. libusb_darwin_acfl = NULL;
  310. pthread_exit (NULL);
  311. }
  312. static int darwin_init(struct libusb_context *ctx) {
  313. host_name_port_t host_self;
  314. int rc;
  315. rc = darwin_scan_devices (ctx);
  316. if (LIBUSB_SUCCESS != rc) {
  317. return rc;
  318. }
  319. if (OSAtomicIncrement32Barrier(&initCount) == 1) {
  320. /* create the clocks that will be used */
  321. host_self = mach_host_self();
  322. host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
  323. host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
  324. mach_port_deallocate(mach_task_self(), host_self);
  325. pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, (void *)ctx);
  326. pthread_mutex_lock (&libusb_darwin_at_mutex);
  327. while (!libusb_darwin_acfl)
  328. pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
  329. pthread_mutex_unlock (&libusb_darwin_at_mutex);
  330. }
  331. return 0;
  332. }
  333. static void darwin_exit (void) {
  334. if (OSAtomicDecrement32Barrier(&initCount) == 0) {
  335. mach_port_deallocate(mach_task_self(), clock_realtime);
  336. mach_port_deallocate(mach_task_self(), clock_monotonic);
  337. /* stop the event runloop and wait for the thread to terminate. */
  338. CFRunLoopStop (libusb_darwin_acfl);
  339. pthread_join (libusb_darwin_at, NULL);
  340. }
  341. }
  342. static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) {
  343. struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
  344. /* return cached copy */
  345. memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
  346. *host_endian = 0;
  347. return 0;
  348. }
  349. static int get_configuration_index (struct libusb_device *dev, int config_value) {
  350. struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
  351. UInt8 i, numConfig;
  352. IOUSBConfigurationDescriptorPtr desc;
  353. IOReturn kresult;
  354. /* is there a simpler way to determine the index? */
  355. kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
  356. if (kresult != kIOReturnSuccess)
  357. return darwin_to_libusb (kresult);
  358. for (i = 0 ; i < numConfig ; i++) {
  359. (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
  360. if (desc->bConfigurationValue == config_value)
  361. return i;
  362. }
  363. /* configuration not found */
  364. return LIBUSB_ERROR_OTHER;
  365. }
  366. static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) {
  367. struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
  368. int config_index;
  369. if (0 == priv->active_config)
  370. return LIBUSB_ERROR_NOT_FOUND;
  371. config_index = get_configuration_index (dev, priv->active_config);
  372. if (config_index < 0)
  373. return config_index;
  374. return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian);
  375. }
  376. static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) {
  377. struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
  378. IOUSBConfigurationDescriptorPtr desc;
  379. IOReturn kresult;
  380. if (!priv || !priv->device)
  381. return LIBUSB_ERROR_OTHER;
  382. kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
  383. if (kresult == kIOReturnSuccess) {
  384. /* copy descriptor */
  385. if (libusb_le16_to_cpu(desc->wTotalLength) < len)
  386. len = libusb_le16_to_cpu(desc->wTotalLength);
  387. memmove (buffer, desc, len);
  388. /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */
  389. *host_endian = 0;
  390. }
  391. return darwin_to_libusb (kresult);
  392. }
  393. /* check whether the os has configured the device */
  394. static int darwin_check_configuration (struct libusb_context *ctx, struct libusb_device *dev, usb_device_t **darwin_device) {
  395. struct darwin_device_priv *priv = (struct darwin_device_priv *)dev->os_priv;
  396. IOUSBConfigurationDescriptorPtr configDesc;
  397. IOUSBFindInterfaceRequest request;
  398. kern_return_t kresult;
  399. io_iterator_t interface_iterator;
  400. io_service_t firstInterface;
  401. if (priv->dev_descriptor.bNumConfigurations < 1) {
  402. usbi_err (ctx, "device has no configurations");
  403. return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
  404. }
  405. /* find the first configuration */
  406. kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
  407. priv->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
  408. /* check if the device is already configured. there is probably a better way than iterating over the
  409. to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
  410. might lock up on the device request) */
  411. /* Setup the Interface Request */
  412. request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
  413. request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
  414. request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
  415. request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
  416. kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
  417. if (kresult)
  418. return darwin_to_libusb (kresult);
  419. /* iterate once */
  420. firstInterface = IOIteratorNext(interface_iterator);
  421. /* done with the interface iterator */
  422. IOObjectRelease(interface_iterator);
  423. if (firstInterface) {
  424. IOObjectRelease (firstInterface);
  425. /* device is configured */
  426. if (priv->dev_descriptor.bNumConfigurations == 1)
  427. /* to avoid problems with some devices get the configurations value from the configuration descriptor */
  428. priv->active_config = priv->first_config;
  429. else
  430. /* devices with more than one configuration should work with GetConfiguration */
  431. (*darwin_device)->GetConfiguration (darwin_device, &priv->active_config);
  432. } else
  433. /* not configured */
  434. priv->active_config = 0;
  435. usbi_info (ctx, "active config: %u, first config: %u", priv->active_config, priv->first_config);
  436. return 0;
  437. }
  438. static int darwin_request_descriptor (usb_device_t **device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
  439. IOUSBDevRequest req;
  440. memset (buffer, 0, buffer_size);
  441. /* Set up request for descriptor/ */
  442. req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
  443. req.bRequest = kUSBRqGetDescriptor;
  444. req.wValue = desc << 8;
  445. req.wIndex = desc_index;
  446. req.wLength = buffer_size;
  447. req.pData = buffer;
  448. return (*device)->DeviceRequest (device, &req);
  449. }
  450. static int darwin_cache_device_descriptor (struct libusb_context *ctx, struct libusb_device *dev, usb_device_t **device) {
  451. struct darwin_device_priv *priv;
  452. int retries = 2, delay = 30000;
  453. int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
  454. int is_open = 0;
  455. int ret = 0, ret2;
  456. UInt8 bDeviceClass;
  457. UInt16 idProduct, idVendor;
  458. (*device)->GetDeviceClass (device, &bDeviceClass);
  459. (*device)->GetDeviceProduct (device, &idProduct);
  460. (*device)->GetDeviceVendor (device, &idVendor);
  461. priv = (struct darwin_device_priv *)dev->os_priv;
  462. /* try to open the device (we can usually continue even if this fails) */
  463. is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
  464. /**** retrieve device descriptor ****/
  465. do {
  466. /* according to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
  467. * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
  468. * to follow the spec as closely as possible, try opening the device */
  469. ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &priv->dev_descriptor, sizeof(priv->dev_descriptor));
  470. if (kIOReturnOverrun == ret && kUSBDeviceDesc == priv->dev_descriptor.bDescriptorType)
  471. /* received an overrun error but we still received a device descriptor */
  472. ret = kIOReturnSuccess;
  473. if (kIOUSBVendorIDAppleComputer == idVendor) {
  474. /* NTH: don't bother retrying or unsuspending Apple devices */
  475. break;
  476. }
  477. if (kIOReturnSuccess == ret && (0 == priv->dev_descriptor.bNumConfigurations ||
  478. 0 == priv->dev_descriptor.bcdUSB)) {
  479. /* work around for incorrectly configured devices */
  480. if (try_reconfigure && is_open) {
  481. usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again...");
  482. /* set the first configuration */
  483. (*device)->SetConfiguration(device, 1);
  484. /* don't try to reconfigure again */
  485. try_reconfigure = 0;
  486. }
  487. ret = kIOUSBPipeStalled;
  488. }
  489. if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
  490. /* device may be suspended. unsuspend it and try again */
  491. #if DeviceVersion >= 320
  492. UInt32 info;
  493. /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
  494. (void)(*device)->GetUSBDeviceInformation (device, &info);
  495. try_unsuspend = info & (1 << kUSBInformationDeviceIsSuspendedBit);
  496. #endif
  497. if (try_unsuspend) {
  498. /* resume the device */
  499. ret2 = (*device)->USBDeviceSuspend (device, 0);
  500. if (kIOReturnSuccess != ret2) {
  501. /* prevent log spew from poorly behaving devices. this indicates the
  502. os actually had trouble communicating with the device */
  503. usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
  504. } else
  505. unsuspended = 1;
  506. try_unsuspend = 0;
  507. }
  508. }
  509. if (kIOReturnSuccess != ret) {
  510. usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000);
  511. /* sleep for a little while before trying again */
  512. usleep (delay);
  513. }
  514. } while (kIOReturnSuccess != ret && retries--);
  515. if (unsuspended)
  516. /* resuspend the device */
  517. (void)(*device)->USBDeviceSuspend (device, 1);
  518. if (is_open)
  519. (void) (*device)->USBDeviceClose (device);
  520. if (ret != kIOReturnSuccess) {
  521. /* a debug message was already printed out for this error */
  522. if (LIBUSB_CLASS_HUB == bDeviceClass)
  523. usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s. skipping device", idVendor, idProduct, darwin_error_str (ret));
  524. else
  525. usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s. skipping device", idVendor, idProduct, darwin_error_str (ret));
  526. return -1;
  527. }
  528. usbi_dbg ("device descriptor:");
  529. usbi_dbg (" bDescriptorType: 0x%02x", priv->dev_descriptor.bDescriptorType);
  530. usbi_dbg (" bcdUSB: 0x%04x", priv->dev_descriptor.bcdUSB);
  531. usbi_dbg (" bDeviceClass: 0x%02x", priv->dev_descriptor.bDeviceClass);
  532. usbi_dbg (" bDeviceSubClass: 0x%02x", priv->dev_descriptor.bDeviceSubClass);
  533. usbi_dbg (" bDeviceProtocol: 0x%02x", priv->dev_descriptor.bDeviceProtocol);
  534. usbi_dbg (" bMaxPacketSize0: 0x%02x", priv->dev_descriptor.bMaxPacketSize0);
  535. usbi_dbg (" idVendor: 0x%04x", priv->dev_descriptor.idVendor);
  536. usbi_dbg (" idProduct: 0x%04x", priv->dev_descriptor.idProduct);
  537. usbi_dbg (" bcdDevice: 0x%04x", priv->dev_descriptor.bcdDevice);
  538. usbi_dbg (" iManufacturer: 0x%02x", priv->dev_descriptor.iManufacturer);
  539. usbi_dbg (" iProduct: 0x%02x", priv->dev_descriptor.iProduct);
  540. usbi_dbg (" iSerialNumber: 0x%02x", priv->dev_descriptor.iSerialNumber);
  541. usbi_dbg (" bNumConfigurations: 0x%02x", priv->dev_descriptor.bNumConfigurations);
  542. /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
  543. if (libusb_le16_to_cpu (priv->dev_descriptor.idProduct) != idProduct) {
  544. /* not a valid device */
  545. usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
  546. idProduct, libusb_le16_to_cpu (priv->dev_descriptor.idProduct));
  547. return -1;
  548. }
  549. return 0;
  550. }
  551. static int process_new_device (struct libusb_context *ctx, usb_device_t **device, UInt32 locationID) {
  552. struct libusb_device *dev = NULL;
  553. struct darwin_device_priv *priv;
  554. UInt8 devSpeed;
  555. UInt16 address;
  556. int ret = 0;
  557. do {
  558. usbi_info (ctx, "allocating new device for location 0x%08x", locationID);
  559. dev = usbi_alloc_device(ctx, locationID);
  560. if (!dev) {
  561. return LIBUSB_ERROR_NO_MEM;
  562. }
  563. priv = (struct darwin_device_priv *)dev->os_priv;
  564. priv->device = device;
  565. /* increment the device's reference count (it is decremented in darwin_destroy_device) */
  566. (*device)->AddRef (device);
  567. (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&address);
  568. ret = darwin_cache_device_descriptor (ctx, dev, device);
  569. if (ret < 0)
  570. break;
  571. /* check current active configuration (and cache the first configuration value-- which may be used by claim_interface) */
  572. ret = darwin_check_configuration (ctx, dev, device);
  573. if (ret < 0)
  574. break;
  575. dev->bus_number = locationID >> 24;
  576. dev->device_address = address;
  577. (*device)->GetDeviceSpeed (device, &devSpeed);
  578. switch (devSpeed) {
  579. case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
  580. case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
  581. case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
  582. #if DeviceVersion >= 500
  583. case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
  584. #endif
  585. default:
  586. usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
  587. }
  588. /* save our location, we'll need this later */
  589. priv->location = locationID;
  590. snprintf(priv->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", address, priv->dev_descriptor.idVendor, priv->dev_descriptor.idProduct,
  591. priv->dev_descriptor.bDeviceClass, priv->dev_descriptor.bDeviceSubClass);
  592. ret = usbi_sanitize_device (dev);
  593. if (ret < 0)
  594. break;
  595. usbi_info (ctx, "found device with address %d at %s", dev->device_address, priv->sys_path);
  596. } while (0);
  597. if (0 == ret) {
  598. usbi_connect_device (dev);
  599. } else {
  600. libusb_unref_device (dev);
  601. }
  602. return ret;
  603. }
  604. static int darwin_scan_devices(struct libusb_context *ctx) {
  605. io_iterator_t deviceIterator;
  606. usb_device_t **device;
  607. kern_return_t kresult;
  608. UInt32 location;
  609. kresult = usb_setup_device_iterator (&deviceIterator, 0);
  610. if (kresult != kIOReturnSuccess)
  611. return darwin_to_libusb (kresult);
  612. while ((device = usb_get_next_device (deviceIterator, &location)) != NULL) {
  613. (void) process_new_device (ctx, device, location);
  614. /* process_new_device added a reference so we need to release the one
  615. from QueryInterface */
  616. (*device)->Release (device);
  617. }
  618. IOObjectRelease(deviceIterator);
  619. return 0;
  620. }
  621. static int darwin_open (struct libusb_device_handle *dev_handle) {
  622. struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
  623. struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
  624. IOReturn kresult;
  625. if (0 == dpriv->open_count) {
  626. /* try to open the device */
  627. kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
  628. if (kresult != kIOReturnSuccess) {
  629. usbi_err (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
  630. if (kIOReturnExclusiveAccess != kresult) {
  631. return darwin_to_libusb (kresult);
  632. }
  633. /* it is possible to perform some actions on a device that is not open so do not return an error */
  634. priv->is_open = 0;
  635. } else {
  636. priv->is_open = 1;
  637. }
  638. /* create async event source */
  639. kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
  640. if (kresult != kIOReturnSuccess) {
  641. usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
  642. if (priv->is_open) {
  643. (*(dpriv->device))->USBDeviceClose (dpriv->device);
  644. }
  645. priv->is_open = 0;
  646. return darwin_to_libusb (kresult);
  647. }
  648. CFRetain (libusb_darwin_acfl);
  649. /* add the cfSource to the aync run loop */
  650. CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
  651. }
  652. /* device opened successfully */
  653. dpriv->open_count++;
  654. /* create a file descriptor for notifications */
  655. pipe (priv->fds);
  656. /* set the pipe to be non-blocking */
  657. fcntl (priv->fds[1], F_SETFD, O_NONBLOCK);
  658. usbi_add_pollfd(HANDLE_CTX(dev_handle), priv->fds[0], POLLIN);
  659. usbi_info (HANDLE_CTX (dev_handle), "device open for access");
  660. return 0;
  661. }
  662. static void darwin_close (struct libusb_device_handle *dev_handle) {
  663. struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
  664. struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
  665. IOReturn kresult;
  666. int i;
  667. if (dpriv->open_count == 0) {
  668. /* something is probably very wrong if this is the case */
  669. usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!\n");
  670. return;
  671. }
  672. dpriv->open_count--;
  673. /* make sure all interfaces are released */
  674. for (i = 0 ; i < USB_MAXINTERFACES ; i++)
  675. if (dev_handle->claimed_interfaces & (1 << i))
  676. libusb_release_interface (dev_handle, i);
  677. if (0 == dpriv->open_count) {
  678. /* delete the device's async event source */
  679. if (priv->cfSource) {
  680. CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
  681. CFRelease (priv->cfSource);
  682. priv->cfSource = NULL;
  683. CFRelease (libusb_darwin_acfl);
  684. }
  685. if (priv->is_open) {
  686. /* close the device */
  687. kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
  688. if (kresult) {
  689. /* Log the fact that we had a problem closing the file, however failing a
  690. * close isn't really an error, so return success anyway */
  691. usbi_err (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
  692. }
  693. }
  694. }
  695. /* file descriptors are maintained per-instance */
  696. usbi_remove_pollfd (HANDLE_CTX (dev_handle), priv->fds[0]);
  697. close (priv->fds[1]);
  698. close (priv->fds[0]);
  699. priv->fds[0] = priv->fds[1] = -1;
  700. }
  701. static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) {
  702. struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
  703. *config = (int) dpriv->active_config;
  704. return 0;
  705. }
  706. static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
  707. struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
  708. IOReturn kresult;
  709. int i;
  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. kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config);
  716. if (kresult != kIOReturnSuccess)
  717. return darwin_to_libusb (kresult);
  718. /* Reclaim any interfaces. */
  719. for (i = 0 ; i < USB_MAXINTERFACES ; i++)
  720. if (dev_handle->claimed_interfaces & (1 << i))
  721. darwin_claim_interface (dev_handle, i);
  722. dpriv->active_config = config;
  723. return 0;
  724. }
  725. static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
  726. IOUSBFindInterfaceRequest request;
  727. kern_return_t kresult;
  728. io_iterator_t interface_iterator;
  729. CFTypeRef bInterfaceNumberCF;
  730. int bInterfaceNumber;
  731. *usbInterfacep = IO_OBJECT_NULL;
  732. /* Setup the Interface Request */
  733. request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
  734. request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
  735. request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
  736. request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
  737. kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
  738. if (kresult)
  739. return kresult;
  740. while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
  741. /* find the interface number */
  742. bInterfaceNumberCF = IORegistryEntryCreateCFProperty (*usbInterfacep, CFSTR("bInterfaceNumber"),
  743. kCFAllocatorDefault, 0);
  744. if (!bInterfaceNumberCF) {
  745. continue;
  746. }
  747. CFNumberGetValue(bInterfaceNumberCF, kCFNumberIntType, &bInterfaceNumber);
  748. CFRelease(bInterfaceNumberCF);
  749. if ((uint8_t) bInterfaceNumber == ifc) {
  750. break;
  751. }
  752. (void) IOObjectRelease (*usbInterfacep);
  753. }
  754. /* done with the interface iterator */
  755. IOObjectRelease(interface_iterator);
  756. return 0;
  757. }
  758. static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) {
  759. struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
  760. /* current interface */
  761. struct darwin_interface *cInterface = &priv->interfaces[iface];
  762. kern_return_t kresult;
  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. usbi_info (HANDLE_CTX (dev_handle), "building table of endpoints.");
  768. /* retrieve the total number of endpoints on this interface */
  769. kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
  770. if (kresult) {
  771. usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
  772. return darwin_to_libusb (kresult);
  773. }
  774. /* iterate through pipe references */
  775. for (i = 1 ; i <= numep ; i++) {
  776. kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
  777. &dont_care2, &dont_care3);
  778. if (kresult != kIOReturnSuccess) {
  779. usbi_err (HANDLE_CTX (dev_handle), "error getting pipe information for pipe %d: %s", i, darwin_error_str(kresult));
  780. return darwin_to_libusb (kresult);
  781. }
  782. usbi_info (HANDLE_CTX (dev_handle), "interface: %i pipe %i: dir: %i number: %i", iface, i, direction, number);
  783. cInterface->endpoint_addrs[i - 1] = ((direction << 7 & LIBUSB_ENDPOINT_DIR_MASK) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
  784. }
  785. cInterface->num_endpoints = numep;
  786. return 0;
  787. }
  788. static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
  789. struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
  790. struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
  791. io_service_t usbInterface = IO_OBJECT_NULL;
  792. IOReturn kresult;
  793. IOCFPlugInInterface **plugInInterface = NULL;
  794. SInt32 score;
  795. /* current interface */
  796. struct darwin_interface *cInterface = &priv->interfaces[iface];
  797. kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
  798. if (kresult != kIOReturnSuccess)
  799. return darwin_to_libusb (kresult);
  800. /* make sure we have an interface */
  801. if (!usbInterface && dpriv->first_config != 0) {
  802. usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config);
  803. /* set the configuration */
  804. kresult = darwin_set_configuration (dev_handle, dpriv->first_config);
  805. if (kresult != LIBUSB_SUCCESS) {
  806. usbi_err (HANDLE_CTX (dev_handle), "could not set configuration");
  807. return kresult;
  808. }
  809. kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
  810. if (kresult) {
  811. usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
  812. return darwin_to_libusb (kresult);
  813. }
  814. }
  815. if (!usbInterface) {
  816. usbi_err (HANDLE_CTX (dev_handle), "interface not found");
  817. return LIBUSB_ERROR_NOT_FOUND;
  818. }
  819. /* get an interface to the device's interface */
  820. kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
  821. kIOCFPlugInInterfaceID, &plugInInterface, &score);
  822. /* ignore release error */
  823. (void)IOObjectRelease (usbInterface);
  824. if (kresult) {
  825. usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
  826. return darwin_to_libusb (kresult);
  827. }
  828. if (!plugInInterface) {
  829. usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found");
  830. return LIBUSB_ERROR_NOT_FOUND;
  831. }
  832. /* Do the actual claim */
  833. kresult = (*plugInInterface)->QueryInterface(plugInInterface,
  834. CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID),
  835. (LPVOID)&cInterface->interface);
  836. /* We no longer need the intermediate plug-in */
  837. /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
  838. (*plugInInterface)->Release (plugInInterface);
  839. if (kresult || !cInterface->interface) {
  840. usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult));
  841. return darwin_to_libusb (kresult);
  842. }
  843. /* claim the interface */
  844. kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
  845. if (kresult) {
  846. usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult));
  847. return darwin_to_libusb (kresult);
  848. }
  849. /* update list of endpoints */
  850. kresult = get_endpoints (dev_handle, iface);
  851. if (kresult) {
  852. /* this should not happen */
  853. darwin_release_interface (dev_handle, iface);
  854. usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
  855. return kresult;
  856. }
  857. cInterface->cfSource = NULL;
  858. /* create async event source */
  859. kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
  860. if (kresult != kIOReturnSuccess) {
  861. usbi_err (HANDLE_CTX (dev_handle), "could not create async event source");
  862. /* can't continue without an async event source */
  863. (void)darwin_release_interface (dev_handle, iface);
  864. return darwin_to_libusb (kresult);
  865. }
  866. /* add the cfSource to the async thread's run loop */
  867. CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
  868. usbi_info (HANDLE_CTX (dev_handle), "interface opened");
  869. return 0;
  870. }
  871. static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) {
  872. struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
  873. IOReturn kresult;
  874. /* current interface */
  875. struct darwin_interface *cInterface = &priv->interfaces[iface];
  876. /* Check to see if an interface is open */
  877. if (!cInterface->interface)
  878. return LIBUSB_SUCCESS;
  879. /* clean up endpoint data */
  880. cInterface->num_endpoints = 0;
  881. /* delete the interface's async event source */
  882. if (cInterface->cfSource) {
  883. CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
  884. CFRelease (cInterface->cfSource);
  885. }
  886. kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
  887. if (kresult)
  888. usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
  889. kresult = (*(cInterface->interface))->Release(cInterface->interface);
  890. if (kresult != kIOReturnSuccess)
  891. usbi_err (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
  892. cInterface->interface = IO_OBJECT_NULL;
  893. return darwin_to_libusb (kresult);
  894. }
  895. static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
  896. struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
  897. IOReturn kresult;
  898. /* current interface */
  899. struct darwin_interface *cInterface = &priv->interfaces[iface];
  900. if (!cInterface->interface)
  901. return LIBUSB_ERROR_NO_DEVICE;
  902. kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
  903. if (kresult != kIOReturnSuccess)
  904. darwin_reset_device (dev_handle);
  905. /* update list of endpoints */
  906. kresult = get_endpoints (dev_handle, iface);
  907. if (kresult) {
  908. /* this should not happen */
  909. darwin_release_interface (dev_handle, iface);
  910. usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
  911. return kresult;
  912. }
  913. return darwin_to_libusb (kresult);
  914. }
  915. static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
  916. struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv;
  917. /* current interface */
  918. struct darwin_interface *cInterface;
  919. uint8_t pipeRef, iface;
  920. IOReturn kresult;
  921. /* determine the interface/endpoint to use */
  922. if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, &iface) != 0) {
  923. usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
  924. return LIBUSB_ERROR_NOT_FOUND;
  925. }
  926. cInterface = &priv->interfaces[iface];
  927. #if (InterfaceVersion < 190)
  928. kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
  929. #else
  930. /* newer versions of darwin support clearing additional bits on the device's endpoint */
  931. kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
  932. #endif
  933. if (kresult)
  934. usbi_err (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
  935. return darwin_to_libusb (kresult);
  936. }
  937. static int darwin_reset_device(struct libusb_device_handle *dev_handle) {
  938. struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
  939. IOUSBDeviceDescriptor descriptor;
  940. IOUSBConfigurationDescriptorPtr cached_configuration;
  941. IOUSBConfigurationDescriptor configuration;
  942. bool reenumerate = false;
  943. IOReturn kresult;
  944. int i;
  945. kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
  946. if (kresult) {
  947. usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult));
  948. return darwin_to_libusb (kresult);
  949. }
  950. do {
  951. usbi_dbg ("darwin/reset_device: checking if device descriptor changed");
  952. /* ignore return code. if we can't get a descriptor it might be worthwhile re-enumerating anway */
  953. (void) darwin_request_descriptor (dpriv->device, kUSBDeviceDesc, 0, &descriptor, sizeof (descriptor));
  954. /* check if the device descriptor has changed */
  955. if (0 != memcmp (&dpriv->dev_descriptor, &descriptor, sizeof (descriptor))) {
  956. reenumerate = true;
  957. break;
  958. }
  959. /* check if any configuration descriptor has changed */
  960. for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
  961. usbi_dbg ("darwin/reset_device: checking if configuration descriptor %d changed", i);
  962. (void) darwin_request_descriptor (dpriv->device, kUSBConfDesc, i, &configuration, sizeof (configuration));
  963. (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
  964. if (!cached_configuration || 0 != memcmp (cached_configuration, &configuration, sizeof (configuration))) {
  965. reenumerate = true;
  966. break;
  967. }
  968. }
  969. } while (0);
  970. if (reenumerate) {
  971. usbi_dbg ("darwin/reset_device: device requires reenumeration");
  972. (void) (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0);
  973. return LIBUSB_ERROR_NOT_FOUND;
  974. }
  975. usbi_dbg ("darwin/reset_device: device reset complete");
  976. return LIBUSB_SUCCESS;
  977. }
  978. static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) {
  979. struct darwin_device_priv *dpriv = (struct darwin_device_priv *)dev_handle->dev->os_priv;
  980. io_service_t usbInterface;
  981. CFTypeRef driver;
  982. IOReturn kresult;
  983. kresult = darwin_get_interface (dpriv->device, interface, &usbInterface);
  984. if (kresult) {
  985. usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult));
  986. return darwin_to_libusb (kresult);
  987. }
  988. driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0);
  989. IOObjectRelease (usbInterface);
  990. if (driver) {
  991. CFRelease (driver);
  992. return 1;
  993. }
  994. /* no driver */
  995. return 0;
  996. }
  997. /* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */
  998. static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
  999. (void)dev_handle;
  1000. (void)interface;
  1001. return LIBUSB_ERROR_NOT_SUPPORTED;
  1002. }
  1003. static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) {
  1004. (void)dev_handle;
  1005. (void)interface;
  1006. return LIBUSB_ERROR_NOT_SUPPORTED;
  1007. }
  1008. static void darwin_destroy_device(struct libusb_device *dev) {
  1009. struct darwin_device_priv *dpriv = (struct darwin_device_priv *) dev->os_priv;
  1010. if (dpriv->device) {
  1011. /* it is an internal error if the reference count of a device is < 0 after release */
  1012. assert(0 <= (*(dpriv->device))->Release(dpriv->device));
  1013. dpriv->device = NULL;
  1014. }
  1015. }
  1016. static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
  1017. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1018. struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
  1019. IOReturn ret;
  1020. uint8_t transferType;
  1021. /* None of the values below are used in libusb for bulk transfers */
  1022. uint8_t direction, number, interval, pipeRef, iface;
  1023. uint16_t maxPacketSize;
  1024. struct darwin_interface *cInterface;
  1025. if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
  1026. usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
  1027. return LIBUSB_ERROR_NOT_FOUND;
  1028. }
  1029. cInterface = &priv->interfaces[iface];
  1030. (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
  1031. &transferType, &maxPacketSize, &interval);
  1032. if (0 != (transfer->length % maxPacketSize)) {
  1033. /* do not need a zero packet */
  1034. transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
  1035. }
  1036. /* submit the request */
  1037. /* timeouts are unavailable on interrupt endpoints */
  1038. if (transferType == kUSBInterrupt) {
  1039. if (IS_XFERIN(transfer))
  1040. ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
  1041. transfer->length, darwin_async_io_callback, itransfer);
  1042. else
  1043. ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
  1044. transfer->length, darwin_async_io_callback, itransfer);
  1045. } else {
  1046. itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
  1047. if (IS_XFERIN(transfer))
  1048. ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
  1049. transfer->length, transfer->timeout, transfer->timeout,
  1050. darwin_async_io_callback, (void *)itransfer);
  1051. else
  1052. ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
  1053. transfer->length, transfer->timeout, transfer->timeout,
  1054. darwin_async_io_callback, (void *)itransfer);
  1055. }
  1056. if (ret)
  1057. usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
  1058. darwin_error_str(ret), ret);
  1059. return darwin_to_libusb (ret);
  1060. }
  1061. static int submit_iso_transfer(struct usbi_transfer *itransfer) {
  1062. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1063. struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
  1064. struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
  1065. IOReturn kresult;
  1066. uint8_t direction, number, interval, pipeRef, iface, transferType;
  1067. uint16_t maxPacketSize;
  1068. UInt64 frame;
  1069. AbsoluteTime atTime;
  1070. int i;
  1071. struct darwin_interface *cInterface;
  1072. /* construct an array of IOUSBIsocFrames, reuse the old one if possible */
  1073. if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) {
  1074. free(tpriv->isoc_framelist);
  1075. tpriv->isoc_framelist = NULL;
  1076. }
  1077. if (!tpriv->isoc_framelist) {
  1078. tpriv->num_iso_packets = transfer->num_iso_packets;
  1079. tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
  1080. if (!tpriv->isoc_framelist)
  1081. return LIBUSB_ERROR_NO_MEM;
  1082. }
  1083. /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
  1084. for (i = 0 ; i < transfer->num_iso_packets ; i++)
  1085. tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length;
  1086. /* determine the interface/endpoint to use */
  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. return LIBUSB_ERROR_NOT_FOUND;
  1090. }
  1091. cInterface = &priv->interfaces[iface];
  1092. /* determine the properties of this endpoint and the speed of the device */
  1093. (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
  1094. &transferType, &maxPacketSize, &interval);
  1095. /* Last but not least we need the bus frame number */
  1096. kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
  1097. if (kresult) {
  1098. usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
  1099. free(tpriv->isoc_framelist);
  1100. tpriv->isoc_framelist = NULL;
  1101. return darwin_to_libusb (kresult);
  1102. }
  1103. /* schedule for a frame a little in the future */
  1104. frame += 4;
  1105. if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
  1106. frame = cInterface->frames[transfer->endpoint];
  1107. /* submit the request */
  1108. if (IS_XFERIN(transfer))
  1109. kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
  1110. transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
  1111. itransfer);
  1112. else
  1113. kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
  1114. transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
  1115. itransfer);
  1116. if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
  1117. /* Full speed */
  1118. cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1));
  1119. else
  1120. /* High/super speed */
  1121. cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1)) / 8;
  1122. if (kresult != kIOReturnSuccess) {
  1123. usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
  1124. darwin_error_str(kresult));
  1125. free (tpriv->isoc_framelist);
  1126. tpriv->isoc_framelist = NULL;
  1127. }
  1128. return darwin_to_libusb (kresult);
  1129. }
  1130. static int submit_control_transfer(struct usbi_transfer *itransfer) {
  1131. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1132. struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
  1133. struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
  1134. struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
  1135. struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
  1136. IOReturn kresult;
  1137. bzero(&tpriv->req, sizeof(tpriv->req));
  1138. /* IOUSBDeviceInterface expects the request in cpu endianess */
  1139. tpriv->req.bmRequestType = setup->bmRequestType;
  1140. tpriv->req.bRequest = setup->bRequest;
  1141. /* these values should be in bus order from libusb_fill_control_setup */
  1142. tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
  1143. tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
  1144. tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
  1145. /* data is stored after the libusb control block */
  1146. tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
  1147. tpriv->req.completionTimeout = transfer->timeout;
  1148. tpriv->req.noDataTimeout = transfer->timeout;
  1149. itransfer->flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
  1150. /* all transfers in libusb-1.0 are async */
  1151. if (transfer->endpoint) {
  1152. struct darwin_interface *cInterface;
  1153. uint8_t pipeRef, iface;
  1154. if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
  1155. usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
  1156. return LIBUSB_ERROR_NOT_FOUND;
  1157. }
  1158. cInterface = &priv->interfaces[iface];
  1159. kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
  1160. } else
  1161. /* control request on endpoint 0 */
  1162. kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
  1163. if (kresult != kIOReturnSuccess)
  1164. usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
  1165. return darwin_to_libusb (kresult);
  1166. }
  1167. static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
  1168. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1169. switch (transfer->type) {
  1170. case LIBUSB_TRANSFER_TYPE_CONTROL:
  1171. return submit_control_transfer(itransfer);
  1172. case LIBUSB_TRANSFER_TYPE_BULK:
  1173. case LIBUSB_TRANSFER_TYPE_INTERRUPT:
  1174. return submit_bulk_transfer(itransfer);
  1175. case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
  1176. return submit_iso_transfer(itransfer);
  1177. default:
  1178. usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
  1179. return LIBUSB_ERROR_INVALID_PARAM;
  1180. }
  1181. }
  1182. static int cancel_control_transfer(struct usbi_transfer *itransfer) {
  1183. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1184. struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
  1185. IOReturn kresult;
  1186. usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions control pipe");
  1187. if (!dpriv->device)
  1188. return LIBUSB_ERROR_NO_DEVICE;
  1189. kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
  1190. return darwin_to_libusb (kresult);
  1191. }
  1192. static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
  1193. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1194. struct darwin_device_priv *dpriv = (struct darwin_device_priv *)transfer->dev_handle->dev->os_priv;
  1195. struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
  1196. struct darwin_interface *cInterface;
  1197. uint8_t pipeRef, iface;
  1198. IOReturn kresult;
  1199. if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface) != 0) {
  1200. usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
  1201. return LIBUSB_ERROR_NOT_FOUND;
  1202. }
  1203. cInterface = &priv->interfaces[iface];
  1204. if (!dpriv->device)
  1205. return LIBUSB_ERROR_NO_DEVICE;
  1206. usbi_info (ITRANSFER_CTX (itransfer), "WARNING: aborting all transactions on interface %d pipe %d", iface, pipeRef);
  1207. /* abort transactions */
  1208. (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
  1209. usbi_info (ITRANSFER_CTX (itransfer), "calling clear pipe stall to clear the data toggle bit");
  1210. /* clear the data toggle bit */
  1211. #if (InterfaceVersion < 190)
  1212. kresult = (*(cInterface->interface))->ClearPipeStall(cInterface->interface, pipeRef);
  1213. #else
  1214. /* newer versions of darwin support clearing additional bits on the device's endpoint */
  1215. kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
  1216. #endif
  1217. return darwin_to_libusb (kresult);
  1218. }
  1219. static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
  1220. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1221. switch (transfer->type) {
  1222. case LIBUSB_TRANSFER_TYPE_CONTROL:
  1223. return cancel_control_transfer(itransfer);
  1224. case LIBUSB_TRANSFER_TYPE_BULK:
  1225. case LIBUSB_TRANSFER_TYPE_INTERRUPT:
  1226. case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
  1227. return darwin_abort_transfers (itransfer);
  1228. default:
  1229. usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
  1230. return LIBUSB_ERROR_INVALID_PARAM;
  1231. }
  1232. }
  1233. static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) {
  1234. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1235. struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
  1236. if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) {
  1237. free (tpriv->isoc_framelist);
  1238. tpriv->isoc_framelist = NULL;
  1239. }
  1240. }
  1241. static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
  1242. struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
  1243. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1244. struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)transfer->dev_handle->os_priv;
  1245. struct darwin_msg_async_io_complete message = {.itransfer = itransfer, .result = result,
  1246. .size = (UInt32) (uintptr_t) arg0};
  1247. usbi_info (ITRANSFER_CTX (itransfer), "an async io operation has completed");
  1248. /* if requested write a zero packet */
  1249. if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
  1250. struct darwin_interface *cInterface;
  1251. uint8_t iface, pipeRef;
  1252. (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface);
  1253. cInterface = &priv->interfaces[iface];
  1254. (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
  1255. }
  1256. /* send a completion message to the device's file descriptor */
  1257. write (priv->fds[1], &message, sizeof (message));
  1258. }
  1259. static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) {
  1260. if (itransfer->flags & USBI_TRANSFER_TIMED_OUT)
  1261. result = kIOUSBTransactionTimeout;
  1262. switch (result) {
  1263. case kIOReturnUnderrun:
  1264. case kIOReturnSuccess:
  1265. return LIBUSB_TRANSFER_COMPLETED;
  1266. case kIOReturnAborted:
  1267. return LIBUSB_TRANSFER_CANCELLED;
  1268. case kIOUSBPipeStalled:
  1269. usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: pipe is stalled");
  1270. return LIBUSB_TRANSFER_STALL;
  1271. case kIOReturnOverrun:
  1272. usbi_err (ITRANSFER_CTX (itransfer), "transfer error: data overrun");
  1273. return LIBUSB_TRANSFER_OVERFLOW;
  1274. case kIOUSBTransactionTimeout:
  1275. usbi_err (ITRANSFER_CTX (itransfer), "transfer error: timed out");
  1276. itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
  1277. return LIBUSB_TRANSFER_TIMED_OUT;
  1278. default:
  1279. usbi_err (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
  1280. return LIBUSB_TRANSFER_ERROR;
  1281. }
  1282. }
  1283. static void darwin_handle_callback (struct usbi_transfer *itransfer, kern_return_t result, UInt32 io_size) {
  1284. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1285. struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
  1286. int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
  1287. int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type;
  1288. int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type;
  1289. int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type;
  1290. int i;
  1291. if (!isIsoc && !isBulk && !isControl && !isInterrupt) {
  1292. usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
  1293. return;
  1294. }
  1295. usbi_info (ITRANSFER_CTX (itransfer), "handling %s completion with kernel status %d",
  1296. isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", result);
  1297. if (kIOReturnSuccess == result || kIOReturnUnderrun == result) {
  1298. if (isIsoc && tpriv->isoc_framelist) {
  1299. /* copy isochronous results back */
  1300. for (i = 0; i < transfer->num_iso_packets ; i++) {
  1301. struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
  1302. lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus);
  1303. lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
  1304. }
  1305. } else if (!isIsoc)
  1306. itransfer->transferred += io_size;
  1307. }
  1308. /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
  1309. usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, result));
  1310. }
  1311. static int op_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready) {
  1312. struct darwin_msg_async_io_complete message;
  1313. POLL_NFDS_TYPE i = 0;
  1314. ssize_t ret;
  1315. usbi_mutex_lock(&ctx->open_devs_lock);
  1316. for (i = 0; i < nfds && num_ready > 0; i++) {
  1317. struct pollfd *pollfd = &fds[i];
  1318. usbi_info (ctx, "checking fd %i with revents = %x", pollfd->fd, pollfd->revents);
  1319. if (!pollfd->revents)
  1320. continue;
  1321. num_ready--;
  1322. if (pollfd->revents & POLLERR) {
  1323. /* this probably will never happen so ignore the error an move on. */
  1324. continue;
  1325. }
  1326. /* there is only one type of message */
  1327. ret = read (pollfd->fd, &message, sizeof (message));
  1328. if (ret < (ssize_t) sizeof (message)) {
  1329. usbi_dbg ("WARNING: short read on async io completion pipe\n");
  1330. continue;
  1331. }
  1332. darwin_handle_callback (message.itransfer, message.result, message.size);
  1333. }
  1334. usbi_mutex_unlock(&ctx->open_devs_lock);
  1335. return 0;
  1336. }
  1337. static int darwin_clock_gettime(int clk_id, struct timespec *tp) {
  1338. mach_timespec_t sys_time;
  1339. clock_serv_t clock_ref;
  1340. switch (clk_id) {
  1341. case USBI_CLOCK_REALTIME:
  1342. /* CLOCK_REALTIME represents time since the epoch */
  1343. clock_ref = clock_realtime;
  1344. break;
  1345. case USBI_CLOCK_MONOTONIC:
  1346. /* use system boot time as reference for the monotonic clock */
  1347. clock_ref = clock_monotonic;
  1348. break;
  1349. default:
  1350. return LIBUSB_ERROR_INVALID_PARAM;
  1351. }
  1352. clock_get_time (clock_ref, &sys_time);
  1353. tp->tv_sec = sys_time.tv_sec;
  1354. tp->tv_nsec = sys_time.tv_nsec;
  1355. return 0;
  1356. }
  1357. const struct usbi_os_backend darwin_backend = {
  1358. .name = "Darwin",
  1359. .init = darwin_init,
  1360. .exit = darwin_exit,
  1361. .get_device_list = NULL, /* not needed */
  1362. .get_device_descriptor = darwin_get_device_descriptor,
  1363. .get_active_config_descriptor = darwin_get_active_config_descriptor,
  1364. .get_config_descriptor = darwin_get_config_descriptor,
  1365. .open = darwin_open,
  1366. .close = darwin_close,
  1367. .get_configuration = darwin_get_configuration,
  1368. .set_configuration = darwin_set_configuration,
  1369. .claim_interface = darwin_claim_interface,
  1370. .release_interface = darwin_release_interface,
  1371. .set_interface_altsetting = darwin_set_interface_altsetting,
  1372. .clear_halt = darwin_clear_halt,
  1373. .reset_device = darwin_reset_device,
  1374. .kernel_driver_active = darwin_kernel_driver_active,
  1375. .detach_kernel_driver = darwin_detach_kernel_driver,
  1376. .attach_kernel_driver = darwin_attach_kernel_driver,
  1377. .destroy_device = darwin_destroy_device,
  1378. .submit_transfer = darwin_submit_transfer,
  1379. .cancel_transfer = darwin_cancel_transfer,
  1380. .clear_transfer_priv = darwin_clear_transfer_priv,
  1381. .handle_events = op_handle_events,
  1382. .clock_gettime = darwin_clock_gettime,
  1383. .device_priv_size = sizeof(struct darwin_device_priv),
  1384. .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
  1385. .transfer_priv_size = sizeof(struct darwin_transfer_priv),
  1386. .add_iso_packet_size = 0,
  1387. };