darwin_usb.c 67 KB

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