darwin_usb.c 96 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668
  1. /* -*- Mode: C; indent-tabs-mode:nil -*- */
  2. /*
  3. * darwin backend for libusb 1.0
  4. * Copyright © 2008-2021 Nathan Hjelm <hjelmn@cs.unm.edu>
  5. * Copyright © 2019-2021 Google LLC. All rights reserved.
  6. *
  7. * This library is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * This library is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with this library; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include <config.h>
  22. #include <assert.h>
  23. #include <time.h>
  24. #include <ctype.h>
  25. #include <pthread.h>
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. #include <string.h>
  29. #include <sys/types.h>
  30. #include <unistd.h>
  31. #include <fcntl.h>
  32. #include <sys/sysctl.h>
  33. #include <mach/clock.h>
  34. #include <mach/clock_types.h>
  35. #include <mach/mach_host.h>
  36. #include <mach/mach_port.h>
  37. /* Suppress warnings about the use of the deprecated objc_registerThreadWithCollector
  38. * function. Its use is also conditionalized to only older deployment targets. */
  39. #define OBJC_SILENCE_GC_DEPRECATIONS 1
  40. /* Default timeout to 10s for reenumerate. This is needed because USBDeviceReEnumerate
  41. * does not return error status on macOS. */
  42. #define DARWIN_REENUMERATE_TIMEOUT_US (10 * USEC_PER_SEC)
  43. #include <AvailabilityMacros.h>
  44. #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
  45. #include <objc/objc-auto.h>
  46. #endif
  47. #include "darwin_usb.h"
  48. static int init_count = 0;
  49. /* Both kIOMasterPortDefault or kIOMainPortDefault are synonyms for 0. */
  50. static const mach_port_t darwin_default_master_port = 0;
  51. /* async event thread */
  52. static pthread_mutex_t libusb_darwin_at_mutex = PTHREAD_MUTEX_INITIALIZER;
  53. static pthread_cond_t libusb_darwin_at_cond = PTHREAD_COND_INITIALIZER;
  54. #if !defined(HAVE_CLOCK_GETTIME)
  55. static clock_serv_t clock_realtime;
  56. static clock_serv_t clock_monotonic;
  57. #endif
  58. #define LIBUSB_DARWIN_STARTUP_FAILURE ((CFRunLoopRef) -1)
  59. static CFRunLoopRef libusb_darwin_acfl = NULL; /* event cf loop */
  60. static CFRunLoopSourceRef libusb_darwin_acfls = NULL; /* shutdown signal for event cf loop */
  61. static usbi_mutex_t darwin_cached_devices_lock = PTHREAD_MUTEX_INITIALIZER;
  62. static struct list_head darwin_cached_devices;
  63. static const char *darwin_device_class = "IOUSBDevice";
  64. #define DARWIN_CACHED_DEVICE(a) (((struct darwin_device_priv *)usbi_get_device_priv((a)))->dev)
  65. /* async event thread */
  66. static pthread_t libusb_darwin_at;
  67. static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, void *buffer, size_t len);
  68. static int darwin_claim_interface(struct libusb_device_handle *dev_handle, uint8_t iface);
  69. static int darwin_release_interface(struct libusb_device_handle *dev_handle, uint8_t iface);
  70. static int darwin_reenumerate_device(struct libusb_device_handle *dev_handle, bool capture);
  71. static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint);
  72. static int darwin_reset_device(struct libusb_device_handle *dev_handle);
  73. static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, uint8_t interface);
  74. static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
  75. static enum libusb_error darwin_scan_devices(struct libusb_context *ctx);
  76. static enum libusb_error process_new_device (struct libusb_context *ctx, struct darwin_cached_device *cached_device,
  77. UInt64 old_session_id);
  78. static enum libusb_error darwin_get_cached_device(struct libusb_context *ctx, io_service_t service, struct darwin_cached_device **cached_out,
  79. UInt64 *old_session_id);
  80. #if defined(ENABLE_LOGGING)
  81. static const char *darwin_error_str (IOReturn result) {
  82. static char string_buffer[50];
  83. switch (result) {
  84. case kIOReturnSuccess:
  85. return "no error";
  86. case kIOReturnNotOpen:
  87. return "device not opened for exclusive access";
  88. case kIOReturnNoDevice:
  89. return "no connection to an IOService";
  90. case kIOUSBNoAsyncPortErr:
  91. return "no async port has been opened for interface";
  92. case kIOReturnExclusiveAccess:
  93. return "another process has device opened for exclusive access";
  94. case kIOUSBPipeStalled:
  95. #if defined(kUSBHostReturnPipeStalled)
  96. case kUSBHostReturnPipeStalled:
  97. #endif
  98. return "pipe is stalled";
  99. case kIOReturnError:
  100. return "could not establish a connection to the Darwin kernel";
  101. case kIOUSBTransactionTimeout:
  102. return "transaction timed out";
  103. case kIOReturnBadArgument:
  104. return "invalid argument";
  105. case kIOReturnAborted:
  106. return "transaction aborted";
  107. case kIOReturnNotResponding:
  108. return "device not responding";
  109. case kIOReturnOverrun:
  110. return "data overrun";
  111. case kIOReturnCannotWire:
  112. return "physical memory can not be wired down";
  113. case kIOReturnNoResources:
  114. return "out of resources";
  115. case kIOUSBHighSpeedSplitError:
  116. return "high speed split error";
  117. case kIOUSBUnknownPipeErr:
  118. return "pipe ref not recognized";
  119. default:
  120. snprintf(string_buffer, sizeof(string_buffer), "unknown error (0x%x)", result);
  121. return string_buffer;
  122. }
  123. }
  124. #endif
  125. static enum libusb_error darwin_to_libusb (IOReturn result) {
  126. switch (result) {
  127. case kIOReturnUnderrun:
  128. case kIOReturnSuccess:
  129. return LIBUSB_SUCCESS;
  130. case kIOReturnNotOpen:
  131. case kIOReturnNoDevice:
  132. return LIBUSB_ERROR_NO_DEVICE;
  133. case kIOReturnExclusiveAccess:
  134. return LIBUSB_ERROR_ACCESS;
  135. case kIOUSBPipeStalled:
  136. #if defined(kUSBHostReturnPipeStalled)
  137. case kUSBHostReturnPipeStalled:
  138. #endif
  139. return LIBUSB_ERROR_PIPE;
  140. case kIOReturnBadArgument:
  141. return LIBUSB_ERROR_INVALID_PARAM;
  142. case kIOUSBTransactionTimeout:
  143. return LIBUSB_ERROR_TIMEOUT;
  144. case kIOUSBUnknownPipeErr:
  145. return LIBUSB_ERROR_NOT_FOUND;
  146. case kIOReturnNotResponding:
  147. case kIOReturnAborted:
  148. case kIOReturnError:
  149. case kIOUSBNoAsyncPortErr:
  150. default:
  151. return LIBUSB_ERROR_OTHER;
  152. }
  153. }
  154. /* this function must be called with the darwin_cached_devices_lock held */
  155. static void darwin_deref_cached_device(struct darwin_cached_device *cached_dev) {
  156. cached_dev->refcount--;
  157. /* free the device and remove it from the cache */
  158. if (0 == cached_dev->refcount) {
  159. list_del(&cached_dev->list);
  160. if (cached_dev->device) {
  161. (*(cached_dev->device))->Release(cached_dev->device);
  162. cached_dev->device = NULL;
  163. }
  164. IOObjectRelease (cached_dev->service);
  165. free (cached_dev);
  166. }
  167. }
  168. static void darwin_ref_cached_device(struct darwin_cached_device *cached_dev) {
  169. cached_dev->refcount++;
  170. }
  171. static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp, struct darwin_interface **interface_out) {
  172. struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
  173. /* current interface */
  174. struct darwin_interface *cInterface;
  175. uint8_t i, iface;
  176. struct libusb_context *ctx = HANDLE_CTX(dev_handle);
  177. usbi_dbg (ctx, "converting ep address 0x%02x to pipeRef and interface", ep);
  178. for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
  179. cInterface = &priv->interfaces[iface];
  180. if (dev_handle->claimed_interfaces & (1U << iface)) {
  181. for (i = 0 ; i < cInterface->num_endpoints ; i++) {
  182. if (cInterface->endpoint_addrs[i] == ep) {
  183. *pipep = i + 1;
  184. if (ifcp)
  185. *ifcp = iface;
  186. if (interface_out)
  187. *interface_out = cInterface;
  188. usbi_dbg (ctx, "pipe %d on interface %d matches", *pipep, iface);
  189. return LIBUSB_SUCCESS;
  190. }
  191. }
  192. }
  193. }
  194. /* No pipe found with the correct endpoint address */
  195. usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
  196. return LIBUSB_ERROR_NOT_FOUND;
  197. }
  198. static IOReturn usb_setup_device_iterator (io_iterator_t *deviceIterator, UInt32 location) {
  199. CFMutableDictionaryRef matchingDict = IOServiceMatching(darwin_device_class);
  200. if (!matchingDict)
  201. return kIOReturnError;
  202. if (location) {
  203. CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
  204. &kCFTypeDictionaryKeyCallBacks,
  205. &kCFTypeDictionaryValueCallBacks);
  206. /* there are no unsigned CFNumber types so treat the value as signed. the OS seems to do this
  207. internally (CFNumberType of locationID is kCFNumberSInt32Type) */
  208. CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberSInt32Type, &location);
  209. if (propertyMatchDict && locationCF) {
  210. CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
  211. CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
  212. }
  213. /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
  214. /* release our references as per the Create Rule */
  215. if (propertyMatchDict)
  216. CFRelease (propertyMatchDict);
  217. if (locationCF)
  218. CFRelease (locationCF);
  219. }
  220. return IOServiceGetMatchingServices(darwin_default_master_port, matchingDict, deviceIterator);
  221. }
  222. /* Returns 1 on success, 0 on failure. */
  223. static bool get_ioregistry_value_number (io_service_t service, CFStringRef property, CFNumberType type, void *p) {
  224. CFTypeRef cfNumber = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
  225. Boolean success = 0;
  226. if (cfNumber) {
  227. if (CFGetTypeID(cfNumber) == CFNumberGetTypeID()) {
  228. success = CFNumberGetValue(cfNumber, type, p);
  229. }
  230. CFRelease (cfNumber);
  231. }
  232. return (success != 0);
  233. }
  234. /* Returns 1 on success, 0 on failure. */
  235. static bool get_ioregistry_value_data (io_service_t service, CFStringRef property, ssize_t size, void *p) {
  236. CFTypeRef cfData = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
  237. bool success = false;
  238. if (cfData) {
  239. if (CFGetTypeID (cfData) == CFDataGetTypeID ()) {
  240. CFIndex length = CFDataGetLength (cfData);
  241. if (length < size) {
  242. size = length;
  243. }
  244. CFDataGetBytes (cfData, CFRangeMake(0, size), p);
  245. success = true;
  246. }
  247. CFRelease (cfData);
  248. }
  249. return success;
  250. }
  251. static usb_device_t **darwin_device_from_service (struct libusb_context *ctx, io_service_t service)
  252. {
  253. io_cf_plugin_ref_t *plugInInterface = NULL;
  254. usb_device_t **device;
  255. IOReturn kresult;
  256. SInt32 score;
  257. const int max_retries = 5;
  258. /* The IOCreatePlugInInterfaceForService function might consistently return
  259. an "out of resources" error with certain USB devices the first time we run
  260. it. The reason is still unclear, but retrying fixes the problem */
  261. for (int count = 0; count < max_retries; count++) {
  262. kresult = IOCreatePlugInInterfaceForService(service, kIOUSBDeviceUserClientTypeID,
  263. kIOCFPlugInInterfaceID, &plugInInterface,
  264. &score);
  265. if (kIOReturnSuccess == kresult && plugInInterface) {
  266. break;
  267. }
  268. usbi_dbg (ctx, "set up plugin for service retry: %s", darwin_error_str (kresult));
  269. /* sleep for a little while before trying again */
  270. nanosleep(&(struct timespec){.tv_sec = 0, .tv_nsec = 1000}, NULL);
  271. }
  272. if (kIOReturnSuccess != kresult || !plugInInterface) {
  273. usbi_dbg (ctx, "could not set up plugin for service: %s", darwin_error_str (kresult));
  274. return NULL;
  275. }
  276. (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID),
  277. (LPVOID)&device);
  278. /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
  279. (*plugInInterface)->Release (plugInInterface);
  280. return device;
  281. }
  282. static void darwin_devices_attached (void *ptr, io_iterator_t add_devices) {
  283. UNUSED(ptr);
  284. struct darwin_cached_device *cached_device;
  285. UInt64 old_session_id;
  286. struct libusb_context *ctx;
  287. io_service_t service;
  288. int ret;
  289. usbi_mutex_lock(&active_contexts_lock);
  290. while ((service = IOIteratorNext(add_devices))) {
  291. ret = darwin_get_cached_device (NULL, service, &cached_device, &old_session_id);
  292. if (ret < 0 || !cached_device->can_enumerate) {
  293. continue;
  294. }
  295. /* add this device to each active context's device list */
  296. for_each_context(ctx) {
  297. process_new_device (ctx, cached_device, old_session_id);
  298. }
  299. if (cached_device->in_reenumerate) {
  300. usbi_dbg (NULL, "cached device in reset state. reset complete...");
  301. cached_device->in_reenumerate = false;
  302. }
  303. IOObjectRelease(service);
  304. }
  305. usbi_mutex_unlock(&active_contexts_lock);
  306. }
  307. static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
  308. UNUSED(ptr);
  309. struct libusb_device *dev = NULL;
  310. struct libusb_context *ctx;
  311. struct darwin_cached_device *old_device;
  312. io_service_t device;
  313. UInt64 session, locationID;
  314. int ret;
  315. usbi_mutex_lock(&active_contexts_lock);
  316. while ((device = IOIteratorNext (rem_devices)) != 0) {
  317. bool is_reenumerating = false;
  318. /* get the location from the i/o registry */
  319. ret = get_ioregistry_value_number (device, CFSTR("sessionID"), kCFNumberSInt64Type, &session);
  320. (void) get_ioregistry_value_number (device, CFSTR("locationID"), kCFNumberSInt32Type, &locationID);
  321. IOObjectRelease (device);
  322. if (!ret)
  323. continue;
  324. /* we need to match darwin_ref_cached_device call made in darwin_get_cached_device function
  325. otherwise no cached device will ever get freed */
  326. usbi_mutex_lock(&darwin_cached_devices_lock);
  327. list_for_each_entry(old_device, &darwin_cached_devices, list, struct darwin_cached_device) {
  328. if (old_device->session == session) {
  329. if (old_device->in_reenumerate) {
  330. /* device is re-enumerating. do not dereference the device at this time. libusb_reset_device()
  331. * will deref if needed. */
  332. usbi_dbg (NULL, "detected device detached due to re-enumeration. sessionID: 0x%" PRIx64 ", locationID: 0x%" PRIx64,
  333. session, locationID);
  334. /* the device object is no longer usable so go ahead and release it */
  335. if (old_device->device) {
  336. (*(old_device->device))->Release(old_device->device);
  337. old_device->device = NULL;
  338. }
  339. is_reenumerating = true;
  340. } else {
  341. darwin_deref_cached_device (old_device);
  342. }
  343. break;
  344. }
  345. }
  346. usbi_mutex_unlock(&darwin_cached_devices_lock);
  347. if (is_reenumerating) {
  348. continue;
  349. }
  350. for_each_context(ctx) {
  351. usbi_dbg (ctx, "notifying context %p of device disconnect", ctx);
  352. dev = usbi_get_device_by_session_id(ctx, (unsigned long) session);
  353. if (dev) {
  354. /* signal the core that this device has been disconnected. the core will tear down this device
  355. when the reference count reaches 0 */
  356. usbi_disconnect_device(dev);
  357. libusb_unref_device(dev);
  358. }
  359. }
  360. }
  361. usbi_mutex_unlock(&active_contexts_lock);
  362. }
  363. static void darwin_hotplug_poll (void)
  364. {
  365. /* not sure if 1 ms will be too long/short but it should work ok */
  366. mach_timespec_t timeout = {.tv_sec = 0, .tv_nsec = 1000000ul};
  367. /* since a kernel thread may notify the IOIterators used for
  368. * hotplug notification we can't just clear the iterators.
  369. * instead just wait until all IOService providers are quiet */
  370. (void) IOKitWaitQuiet (darwin_default_master_port, &timeout);
  371. }
  372. static void darwin_clear_iterator (io_iterator_t iter) {
  373. io_service_t device;
  374. while ((device = IOIteratorNext (iter)) != 0)
  375. IOObjectRelease (device);
  376. }
  377. static void darwin_fail_startup(void) {
  378. pthread_mutex_lock (&libusb_darwin_at_mutex);
  379. libusb_darwin_acfl = LIBUSB_DARWIN_STARTUP_FAILURE;
  380. pthread_cond_signal (&libusb_darwin_at_cond);
  381. pthread_mutex_unlock (&libusb_darwin_at_mutex);
  382. pthread_exit (NULL);
  383. }
  384. static void *darwin_event_thread_main (void *arg0) {
  385. IOReturn kresult;
  386. struct libusb_context *ctx = (struct libusb_context *)arg0;
  387. CFRunLoopRef runloop;
  388. CFRunLoopSourceRef libusb_shutdown_cfsource;
  389. CFRunLoopSourceContext libusb_shutdown_cfsourcectx;
  390. #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
  391. /* Set this thread's name, so it can be seen in the debugger
  392. and crash reports. */
  393. pthread_setname_np ("org.libusb.device-hotplug");
  394. #endif
  395. #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
  396. /* Tell the Objective-C garbage collector about this thread.
  397. This is required because, unlike NSThreads, pthreads are
  398. not automatically registered. Although we don't use
  399. Objective-C, we use CoreFoundation, which does.
  400. Garbage collection support was entirely removed in 10.12,
  401. so don't bother there. */
  402. objc_registerThreadWithCollector();
  403. #endif
  404. /* hotplug (device arrival/removal) sources */
  405. CFRunLoopSourceRef libusb_notification_cfsource;
  406. io_notification_port_t libusb_notification_port;
  407. io_iterator_t libusb_rem_device_iterator;
  408. io_iterator_t libusb_add_device_iterator;
  409. /* ctx must only be used for logging during thread startup */
  410. usbi_dbg (ctx, "creating hotplug event source");
  411. runloop = CFRunLoopGetCurrent ();
  412. CFRetain (runloop);
  413. /* add the shutdown cfsource to the run loop */
  414. memset(&libusb_shutdown_cfsourcectx, 0, sizeof(libusb_shutdown_cfsourcectx));
  415. libusb_shutdown_cfsourcectx.info = runloop;
  416. libusb_shutdown_cfsourcectx.perform = (void (*)(void *))CFRunLoopStop;
  417. libusb_shutdown_cfsource = CFRunLoopSourceCreate(NULL, 0, &libusb_shutdown_cfsourcectx);
  418. CFRunLoopAddSource(runloop, libusb_shutdown_cfsource, kCFRunLoopDefaultMode);
  419. /* add the notification port to the run loop */
  420. libusb_notification_port = IONotificationPortCreate (darwin_default_master_port);
  421. libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
  422. CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
  423. /* create notifications for removed devices */
  424. kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
  425. IOServiceMatching(darwin_device_class),
  426. darwin_devices_detached,
  427. NULL, &libusb_rem_device_iterator);
  428. if (kresult != kIOReturnSuccess) {
  429. usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
  430. CFRelease (libusb_shutdown_cfsource);
  431. CFRelease (runloop);
  432. darwin_fail_startup ();
  433. }
  434. /* create notifications for attached devices */
  435. kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification,
  436. IOServiceMatching(darwin_device_class),
  437. darwin_devices_attached,
  438. NULL, &libusb_add_device_iterator);
  439. if (kresult != kIOReturnSuccess) {
  440. usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult));
  441. CFRelease (libusb_shutdown_cfsource);
  442. CFRelease (runloop);
  443. darwin_fail_startup ();
  444. }
  445. /* arm notifiers */
  446. darwin_clear_iterator (libusb_rem_device_iterator);
  447. darwin_clear_iterator (libusb_add_device_iterator);
  448. usbi_dbg (ctx, "darwin event thread ready to receive events");
  449. /* signal the main thread that the hotplug runloop has been created. */
  450. pthread_mutex_lock (&libusb_darwin_at_mutex);
  451. libusb_darwin_acfl = runloop;
  452. libusb_darwin_acfls = libusb_shutdown_cfsource;
  453. pthread_cond_signal (&libusb_darwin_at_cond);
  454. pthread_mutex_unlock (&libusb_darwin_at_mutex);
  455. /* run the runloop */
  456. CFRunLoopRun();
  457. usbi_dbg (NULL, "darwin event thread exiting");
  458. /* signal the main thread that the hotplug runloop has finished. */
  459. pthread_mutex_lock (&libusb_darwin_at_mutex);
  460. libusb_darwin_acfls = NULL;
  461. libusb_darwin_acfl = NULL;
  462. pthread_cond_signal (&libusb_darwin_at_cond);
  463. pthread_mutex_unlock (&libusb_darwin_at_mutex);
  464. /* remove the notification cfsource */
  465. CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
  466. /* remove the shutdown cfsource */
  467. CFRunLoopRemoveSource(runloop, libusb_shutdown_cfsource, kCFRunLoopDefaultMode);
  468. /* delete notification port */
  469. IONotificationPortDestroy (libusb_notification_port);
  470. /* delete iterators */
  471. IOObjectRelease (libusb_rem_device_iterator);
  472. IOObjectRelease (libusb_add_device_iterator);
  473. CFRelease (libusb_shutdown_cfsource);
  474. CFRelease (runloop);
  475. pthread_exit (NULL);
  476. }
  477. /* cleanup function to destroy cached devices */
  478. static void darwin_cleanup_devices(void) {
  479. struct darwin_cached_device *dev, *next;
  480. list_for_each_entry_safe(dev, next, &darwin_cached_devices, list, struct darwin_cached_device) {
  481. darwin_deref_cached_device(dev);
  482. }
  483. }
  484. static int darwin_init(struct libusb_context *ctx) {
  485. bool first_init;
  486. int rc;
  487. first_init = (1 == ++init_count);
  488. do {
  489. if (first_init) {
  490. if (NULL == darwin_cached_devices.next) {
  491. list_init (&darwin_cached_devices);
  492. }
  493. assert(list_empty(&darwin_cached_devices));
  494. #if !defined(HAVE_CLOCK_GETTIME)
  495. /* create the clocks that will be used if clock_gettime() is not available */
  496. host_name_port_t host_self;
  497. host_self = mach_host_self();
  498. host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime);
  499. host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic);
  500. mach_port_deallocate(mach_task_self(), host_self);
  501. #endif
  502. }
  503. rc = darwin_scan_devices (ctx);
  504. if (LIBUSB_SUCCESS != rc)
  505. break;
  506. if (first_init) {
  507. rc = pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, ctx);
  508. if (0 != rc) {
  509. usbi_err (ctx, "could not create event thread, error %d", rc);
  510. rc = LIBUSB_ERROR_OTHER;
  511. break;
  512. }
  513. pthread_mutex_lock (&libusb_darwin_at_mutex);
  514. while (!libusb_darwin_acfl)
  515. pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
  516. if (libusb_darwin_acfl == LIBUSB_DARWIN_STARTUP_FAILURE) {
  517. libusb_darwin_acfl = NULL;
  518. rc = LIBUSB_ERROR_OTHER;
  519. }
  520. pthread_mutex_unlock (&libusb_darwin_at_mutex);
  521. if (0 != rc)
  522. pthread_join (libusb_darwin_at, NULL);
  523. }
  524. } while (0);
  525. if (LIBUSB_SUCCESS != rc) {
  526. if (first_init) {
  527. darwin_cleanup_devices ();
  528. #if !defined(HAVE_CLOCK_GETTIME)
  529. mach_port_deallocate(mach_task_self(), clock_realtime);
  530. mach_port_deallocate(mach_task_self(), clock_monotonic);
  531. #endif
  532. }
  533. --init_count;
  534. }
  535. return rc;
  536. }
  537. static void darwin_exit (struct libusb_context *ctx) {
  538. UNUSED(ctx);
  539. if (0 == --init_count) {
  540. /* stop the event runloop and wait for the thread to terminate. */
  541. pthread_mutex_lock (&libusb_darwin_at_mutex);
  542. CFRunLoopSourceSignal (libusb_darwin_acfls);
  543. CFRunLoopWakeUp (libusb_darwin_acfl);
  544. while (libusb_darwin_acfl)
  545. pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
  546. pthread_mutex_unlock (&libusb_darwin_at_mutex);
  547. pthread_join (libusb_darwin_at, NULL);
  548. darwin_cleanup_devices ();
  549. #if !defined(HAVE_CLOCK_GETTIME)
  550. mach_port_deallocate(mach_task_self(), clock_realtime);
  551. mach_port_deallocate(mach_task_self(), clock_monotonic);
  552. #endif
  553. }
  554. }
  555. static int get_configuration_index (struct libusb_device *dev, UInt8 config_value) {
  556. struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
  557. UInt8 i, numConfig;
  558. IOUSBConfigurationDescriptorPtr desc;
  559. IOReturn kresult;
  560. /* is there a simpler way to determine the index? */
  561. kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig);
  562. if (kresult != kIOReturnSuccess)
  563. return darwin_to_libusb (kresult);
  564. for (i = 0 ; i < numConfig ; i++) {
  565. (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc);
  566. if (desc->bConfigurationValue == config_value)
  567. return i;
  568. }
  569. /* configuration not found */
  570. return LIBUSB_ERROR_NOT_FOUND;
  571. }
  572. static int darwin_get_active_config_descriptor(struct libusb_device *dev, void *buffer, size_t len) {
  573. struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
  574. int config_index;
  575. if (0 == priv->active_config)
  576. return LIBUSB_ERROR_NOT_FOUND;
  577. config_index = get_configuration_index (dev, priv->active_config);
  578. if (config_index < 0)
  579. return config_index;
  580. assert(config_index >= 0 && config_index <= UINT8_MAX);
  581. return darwin_get_config_descriptor (dev, (UInt8)config_index, buffer, len);
  582. }
  583. static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, void *buffer, size_t len) {
  584. struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
  585. IOUSBConfigurationDescriptorPtr desc;
  586. IOReturn kresult;
  587. int ret;
  588. if (!priv || !priv->device)
  589. return LIBUSB_ERROR_OTHER;
  590. kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
  591. if (kresult == kIOReturnSuccess) {
  592. /* copy descriptor */
  593. if (libusb_le16_to_cpu(desc->wTotalLength) < len)
  594. len = libusb_le16_to_cpu(desc->wTotalLength);
  595. memmove (buffer, desc, len);
  596. }
  597. ret = darwin_to_libusb (kresult);
  598. if (ret != LIBUSB_SUCCESS)
  599. return ret;
  600. return (int) len;
  601. }
  602. /* check whether the os has configured the device */
  603. static enum libusb_error darwin_check_configuration (struct libusb_context *ctx, struct darwin_cached_device *dev) {
  604. usb_device_t **darwin_device = dev->device;
  605. IOUSBConfigurationDescriptorPtr configDesc;
  606. IOUSBFindInterfaceRequest request;
  607. IOReturn kresult;
  608. io_iterator_t interface_iterator;
  609. io_service_t firstInterface;
  610. if (dev->dev_descriptor.bNumConfigurations < 1) {
  611. usbi_err (ctx, "device has no configurations");
  612. return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
  613. }
  614. /* checking the configuration of a root hub simulation takes ~1 s in 10.11. the device is
  615. not usable anyway */
  616. if (0x05ac == libusb_le16_to_cpu (dev->dev_descriptor.idVendor) &&
  617. 0x8005 == libusb_le16_to_cpu (dev->dev_descriptor.idProduct)) {
  618. usbi_dbg (ctx, "ignoring configuration on root hub simulation");
  619. dev->active_config = 0;
  620. return LIBUSB_SUCCESS;
  621. }
  622. /* find the first configuration */
  623. kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
  624. dev->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
  625. /* check if the device is already configured. there is probably a better way than iterating over the
  626. to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
  627. might lock up on the device request) */
  628. /* Setup the Interface Request */
  629. request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
  630. request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
  631. request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
  632. request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
  633. kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
  634. if (kresult != kIOReturnSuccess)
  635. return darwin_to_libusb (kresult);
  636. /* iterate once */
  637. firstInterface = IOIteratorNext(interface_iterator);
  638. /* done with the interface iterator */
  639. IOObjectRelease(interface_iterator);
  640. if (firstInterface) {
  641. IOObjectRelease (firstInterface);
  642. /* device is configured */
  643. if (dev->dev_descriptor.bNumConfigurations == 1)
  644. /* to avoid problems with some devices get the configurations value from the configuration descriptor */
  645. dev->active_config = dev->first_config;
  646. else
  647. /* devices with more than one configuration should work with GetConfiguration */
  648. (*darwin_device)->GetConfiguration (darwin_device, &dev->active_config);
  649. } else
  650. /* not configured */
  651. dev->active_config = 0;
  652. usbi_dbg (ctx, "active config: %u, first config: %u", dev->active_config, dev->first_config);
  653. return LIBUSB_SUCCESS;
  654. }
  655. static IOReturn darwin_request_descriptor (usb_device_t **device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
  656. IOUSBDevRequestTO req;
  657. assert(buffer_size <= UINT16_MAX);
  658. memset (buffer, 0, buffer_size);
  659. /* Set up request for descriptor/ */
  660. req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
  661. req.bRequest = kUSBRqGetDescriptor;
  662. req.wValue = (UInt16)(desc << 8);
  663. req.wIndex = desc_index;
  664. req.wLength = (UInt16)buffer_size;
  665. req.pData = buffer;
  666. req.noDataTimeout = 20;
  667. req.completionTimeout = 100;
  668. return (*device)->DeviceRequestTO (device, &req);
  669. }
  670. static enum libusb_error darwin_cache_device_descriptor (struct libusb_context *ctx, struct darwin_cached_device *dev) {
  671. usb_device_t **device = dev->device;
  672. int retries = 1;
  673. long delay = 30000; // microseconds
  674. int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
  675. int is_open = 0;
  676. IOReturn ret = 0, ret2;
  677. UInt8 bDeviceClass;
  678. UInt16 idProduct, idVendor;
  679. dev->can_enumerate = 0;
  680. (*device)->GetDeviceClass (device, &bDeviceClass);
  681. (*device)->GetDeviceProduct (device, &idProduct);
  682. (*device)->GetDeviceVendor (device, &idVendor);
  683. /* According to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
  684. * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
  685. * to follow the spec as closely as possible, try opening the device */
  686. is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
  687. do {
  688. /**** retrieve device descriptor ****/
  689. ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &dev->dev_descriptor, sizeof(dev->dev_descriptor));
  690. if (kIOReturnOverrun == ret && kUSBDeviceDesc == dev->dev_descriptor.bDescriptorType)
  691. /* received an overrun error but we still received a device descriptor */
  692. ret = kIOReturnSuccess;
  693. if (kIOUSBVendorIDAppleComputer == idVendor) {
  694. /* NTH: don't bother retrying or unsuspending Apple devices */
  695. break;
  696. }
  697. if (kIOReturnSuccess == ret && (0 == dev->dev_descriptor.bNumConfigurations ||
  698. 0 == dev->dev_descriptor.bcdUSB)) {
  699. /* work around for incorrectly configured devices */
  700. if (try_reconfigure && is_open) {
  701. usbi_dbg(ctx, "descriptor appears to be invalid. resetting configuration before trying again...");
  702. /* set the first configuration */
  703. (*device)->SetConfiguration(device, 1);
  704. /* don't try to reconfigure again */
  705. try_reconfigure = 0;
  706. }
  707. ret = kIOUSBPipeStalled;
  708. }
  709. if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
  710. /* device may be suspended. unsuspend it and try again */
  711. #if DeviceVersion >= 320
  712. UInt32 info = 0;
  713. /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
  714. (void)(*device)->GetUSBDeviceInformation (device, &info);
  715. /* note that the device was suspended */
  716. if (info & (1U << kUSBInformationDeviceIsSuspendedBit) || 0 == info)
  717. try_unsuspend = 1;
  718. #endif
  719. if (try_unsuspend) {
  720. /* try to unsuspend the device */
  721. ret2 = (*device)->USBDeviceSuspend (device, 0);
  722. if (kIOReturnSuccess != ret2) {
  723. /* prevent log spew from poorly behaving devices. this indicates the
  724. os actually had trouble communicating with the device */
  725. usbi_dbg(ctx, "could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
  726. } else
  727. unsuspended = 1;
  728. try_unsuspend = 0;
  729. }
  730. }
  731. if (kIOReturnSuccess != ret) {
  732. usbi_dbg(ctx, "kernel responded with code: 0x%08x. sleeping for %ld ms before trying again", ret, delay/1000);
  733. /* sleep for a little while before trying again */
  734. nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000}, NULL);
  735. }
  736. } while (kIOReturnSuccess != ret && retries--);
  737. if (unsuspended)
  738. /* resuspend the device */
  739. (void)(*device)->USBDeviceSuspend (device, 1);
  740. if (is_open)
  741. (void) (*device)->USBDeviceClose (device);
  742. if (ret != kIOReturnSuccess) {
  743. /* a debug message was already printed out for this error */
  744. if (LIBUSB_CLASS_HUB == bDeviceClass)
  745. usbi_dbg (ctx, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
  746. idVendor, idProduct, darwin_error_str (ret), ret);
  747. else
  748. usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
  749. idVendor, idProduct, darwin_error_str (ret), ret);
  750. return darwin_to_libusb (ret);
  751. }
  752. /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
  753. if (libusb_le16_to_cpu (dev->dev_descriptor.idProduct) != idProduct) {
  754. /* not a valid device */
  755. usbi_warn (NULL, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
  756. idProduct, libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
  757. return LIBUSB_ERROR_NO_DEVICE;
  758. }
  759. usbi_dbg (ctx, "cached device descriptor:");
  760. usbi_dbg (ctx, " bDescriptorType: 0x%02x", dev->dev_descriptor.bDescriptorType);
  761. usbi_dbg (ctx, " bcdUSB: 0x%04x", libusb_le16_to_cpu (dev->dev_descriptor.bcdUSB));
  762. usbi_dbg (ctx, " bDeviceClass: 0x%02x", dev->dev_descriptor.bDeviceClass);
  763. usbi_dbg (ctx, " bDeviceSubClass: 0x%02x", dev->dev_descriptor.bDeviceSubClass);
  764. usbi_dbg (ctx, " bDeviceProtocol: 0x%02x", dev->dev_descriptor.bDeviceProtocol);
  765. usbi_dbg (ctx, " bMaxPacketSize0: 0x%02x", dev->dev_descriptor.bMaxPacketSize0);
  766. usbi_dbg (ctx, " idVendor: 0x%04x", libusb_le16_to_cpu (dev->dev_descriptor.idVendor));
  767. usbi_dbg (ctx, " idProduct: 0x%04x", libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
  768. usbi_dbg (ctx, " bcdDevice: 0x%04x", libusb_le16_to_cpu (dev->dev_descriptor.bcdDevice));
  769. usbi_dbg (ctx, " iManufacturer: 0x%02x", dev->dev_descriptor.iManufacturer);
  770. usbi_dbg (ctx, " iProduct: 0x%02x", dev->dev_descriptor.iProduct);
  771. usbi_dbg (ctx, " iSerialNumber: 0x%02x", dev->dev_descriptor.iSerialNumber);
  772. usbi_dbg (ctx, " bNumConfigurations: 0x%02x", dev->dev_descriptor.bNumConfigurations);
  773. dev->can_enumerate = 1;
  774. return LIBUSB_SUCCESS;
  775. }
  776. /* Returns 1 on success, 0 on failure. */
  777. static bool get_device_port (io_service_t service, UInt8 *port) {
  778. IOReturn kresult;
  779. io_service_t parent;
  780. bool ret = false;
  781. if (get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, port)) {
  782. return true;
  783. }
  784. kresult = IORegistryEntryGetParentEntry (service, kIOServicePlane, &parent);
  785. if (kIOReturnSuccess == kresult) {
  786. ret = get_ioregistry_value_data (parent, CFSTR("port"), 1, port);
  787. IOObjectRelease (parent);
  788. }
  789. return ret;
  790. }
  791. /* Returns 1 on success, 0 on failure. */
  792. static bool get_device_parent_sessionID(io_service_t service, UInt64 *parent_sessionID) {
  793. IOReturn kresult;
  794. io_service_t parent;
  795. /* Walk up the tree in the IOService plane until we find a parent that has a sessionID */
  796. parent = service;
  797. while((kresult = IORegistryEntryGetParentEntry (parent, kIOUSBPlane, &parent)) == kIOReturnSuccess) {
  798. if (get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, parent_sessionID)) {
  799. /* Success */
  800. return true;
  801. }
  802. }
  803. /* We ran out of parents */
  804. return false;
  805. }
  806. static enum libusb_error darwin_get_cached_device(struct libusb_context *ctx, io_service_t service, struct darwin_cached_device **cached_out,
  807. UInt64 *old_session_id) {
  808. struct darwin_cached_device *new_device;
  809. UInt64 sessionID = 0, parent_sessionID = 0;
  810. UInt32 locationID = 0;
  811. enum libusb_error ret = LIBUSB_SUCCESS;
  812. usb_device_t **device;
  813. UInt8 port = 0;
  814. /* assuming sessionID != 0 normally (never seen it be 0) */
  815. *old_session_id = 0;
  816. *cached_out = NULL;
  817. /* get some info from the io registry */
  818. (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
  819. (void) get_ioregistry_value_number (service, CFSTR("locationID"), kCFNumberSInt32Type, &locationID);
  820. if (!get_device_port (service, &port)) {
  821. usbi_dbg(ctx, "could not get connected port number");
  822. }
  823. usbi_dbg(ctx, "finding cached device for sessionID 0x%" PRIx64, sessionID);
  824. if (get_device_parent_sessionID(service, &parent_sessionID)) {
  825. usbi_dbg(ctx, "parent sessionID: 0x%" PRIx64, parent_sessionID);
  826. }
  827. usbi_mutex_lock(&darwin_cached_devices_lock);
  828. do {
  829. list_for_each_entry(new_device, &darwin_cached_devices, list, struct darwin_cached_device) {
  830. usbi_dbg(ctx, "matching sessionID/locationID 0x%" PRIx64 "/0x%x against cached device with sessionID/locationID 0x%" PRIx64 "/0x%x",
  831. sessionID, locationID, new_device->session, new_device->location);
  832. if (new_device->location == locationID && new_device->in_reenumerate) {
  833. usbi_dbg (ctx, "found cached device with matching location that is being re-enumerated");
  834. *old_session_id = new_device->session;
  835. break;
  836. }
  837. if (new_device->session == sessionID) {
  838. usbi_dbg(ctx, "using cached device for device");
  839. *cached_out = new_device;
  840. break;
  841. }
  842. }
  843. if (*cached_out)
  844. break;
  845. usbi_dbg(ctx, "caching new device with sessionID 0x%" PRIx64, sessionID);
  846. device = darwin_device_from_service (ctx, service);
  847. if (!device) {
  848. ret = LIBUSB_ERROR_NO_DEVICE;
  849. break;
  850. }
  851. if (!(*old_session_id)) {
  852. new_device = calloc (1, sizeof (*new_device));
  853. if (!new_device) {
  854. ret = LIBUSB_ERROR_NO_MEM;
  855. break;
  856. }
  857. /* add this device to the cached device list */
  858. list_add(&new_device->list, &darwin_cached_devices);
  859. (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
  860. /* keep a reference to this device */
  861. darwin_ref_cached_device(new_device);
  862. (*device)->GetLocationID (device, &new_device->location);
  863. new_device->port = port;
  864. new_device->parent_session = parent_sessionID;
  865. } else {
  866. /* release the ref to old device's service */
  867. IOObjectRelease (new_device->service);
  868. }
  869. /* keep track of devices regardless of if we successfully enumerate them to
  870. prevent them from being enumerated multiple times */
  871. *cached_out = new_device;
  872. new_device->session = sessionID;
  873. new_device->device = device;
  874. new_device->service = service;
  875. /* retain the service */
  876. IOObjectRetain (service);
  877. /* cache the device descriptor */
  878. ret = darwin_cache_device_descriptor(ctx, new_device);
  879. if (ret)
  880. break;
  881. if (new_device->can_enumerate) {
  882. snprintf(new_device->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", new_device->address,
  883. libusb_le16_to_cpu (new_device->dev_descriptor.idVendor),
  884. libusb_le16_to_cpu (new_device->dev_descriptor.idProduct),
  885. new_device->dev_descriptor.bDeviceClass, new_device->dev_descriptor.bDeviceSubClass);
  886. }
  887. } while (0);
  888. usbi_mutex_unlock(&darwin_cached_devices_lock);
  889. return ret;
  890. }
  891. static enum libusb_error process_new_device (struct libusb_context *ctx, struct darwin_cached_device *cached_device,
  892. UInt64 old_session_id) {
  893. struct darwin_device_priv *priv;
  894. struct libusb_device *dev = NULL;
  895. UInt8 devSpeed;
  896. enum libusb_error ret = LIBUSB_SUCCESS;
  897. do {
  898. /* check current active configuration (and cache the first configuration value--
  899. which may be used by claim_interface) */
  900. ret = darwin_check_configuration (ctx, cached_device);
  901. if (ret)
  902. break;
  903. if (0 != old_session_id) {
  904. usbi_dbg (ctx, "re-using existing device from context %p for with session 0x%" PRIx64 " new session 0x%" PRIx64,
  905. ctx, old_session_id, cached_device->session);
  906. /* save the libusb device before the session id is updated */
  907. dev = usbi_get_device_by_session_id (ctx, (unsigned long) old_session_id);
  908. }
  909. if (!dev) {
  910. usbi_dbg (ctx, "allocating new device in context %p for with session 0x%" PRIx64,
  911. ctx, cached_device->session);
  912. dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
  913. if (!dev) {
  914. return LIBUSB_ERROR_NO_MEM;
  915. }
  916. priv = usbi_get_device_priv(dev);
  917. priv->dev = cached_device;
  918. darwin_ref_cached_device (priv->dev);
  919. dev->port_number = cached_device->port;
  920. /* the location ID encodes the path to the device. the top byte of the location ID contains the bus number
  921. (numbered from 0). the remaining bytes can be used to construct the device tree for that bus. */
  922. dev->bus_number = cached_device->location >> 24;
  923. assert(cached_device->address <= UINT8_MAX);
  924. dev->device_address = (uint8_t)cached_device->address;
  925. } else {
  926. priv = usbi_get_device_priv(dev);
  927. }
  928. static_assert(sizeof(dev->device_descriptor) == sizeof(cached_device->dev_descriptor),
  929. "mismatch between libusb and IOKit device descriptor sizes");
  930. memcpy(&dev->device_descriptor, &cached_device->dev_descriptor, LIBUSB_DT_DEVICE_SIZE);
  931. usbi_localize_device_descriptor(&dev->device_descriptor);
  932. dev->session_data = cached_device->session;
  933. if (NULL != dev->parent_dev) {
  934. libusb_unref_device(dev->parent_dev);
  935. dev->parent_dev = NULL;
  936. }
  937. if (cached_device->parent_session > 0) {
  938. dev->parent_dev = usbi_get_device_by_session_id (ctx, (unsigned long) cached_device->parent_session);
  939. }
  940. (*(priv->dev->device))->GetDeviceSpeed (priv->dev->device, &devSpeed);
  941. switch (devSpeed) {
  942. case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
  943. case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
  944. case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
  945. #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1080
  946. case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
  947. #endif
  948. #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101200
  949. case kUSBDeviceSpeedSuperPlus: dev->speed = LIBUSB_SPEED_SUPER_PLUS; break;
  950. #endif
  951. default:
  952. usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
  953. }
  954. ret = usbi_sanitize_device (dev);
  955. if (ret < 0)
  956. break;
  957. usbi_dbg (ctx, "found device with address %d port = %d parent = %p at %p", dev->device_address,
  958. dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path);
  959. } while (0);
  960. if (!cached_device->in_reenumerate && 0 == ret) {
  961. usbi_connect_device (dev);
  962. } else {
  963. libusb_unref_device (dev);
  964. }
  965. return ret;
  966. }
  967. static enum libusb_error darwin_scan_devices(struct libusb_context *ctx) {
  968. struct darwin_cached_device *cached_device;
  969. UInt64 old_session_id;
  970. io_iterator_t deviceIterator;
  971. io_service_t service;
  972. IOReturn kresult;
  973. int ret;
  974. kresult = usb_setup_device_iterator (&deviceIterator, 0);
  975. if (kresult != kIOReturnSuccess)
  976. return darwin_to_libusb (kresult);
  977. while ((service = IOIteratorNext (deviceIterator))) {
  978. ret = darwin_get_cached_device (ctx, service, &cached_device, &old_session_id);
  979. if (ret < 0 || !cached_device->can_enumerate) {
  980. continue;
  981. }
  982. (void) process_new_device (ctx, cached_device, old_session_id);
  983. IOObjectRelease(service);
  984. }
  985. IOObjectRelease(deviceIterator);
  986. return LIBUSB_SUCCESS;
  987. }
  988. static int darwin_open (struct libusb_device_handle *dev_handle) {
  989. struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
  990. struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
  991. IOReturn kresult;
  992. if (0 == dpriv->open_count) {
  993. /* try to open the device */
  994. kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device);
  995. if (kresult != kIOReturnSuccess) {
  996. usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
  997. if (kIOReturnExclusiveAccess != kresult) {
  998. return darwin_to_libusb (kresult);
  999. }
  1000. /* it is possible to perform some actions on a device that is not open so do not return an error */
  1001. priv->is_open = false;
  1002. } else {
  1003. priv->is_open = true;
  1004. }
  1005. /* create async event source */
  1006. kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource);
  1007. if (kresult != kIOReturnSuccess) {
  1008. usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
  1009. if (priv->is_open) {
  1010. (*(dpriv->device))->USBDeviceClose (dpriv->device);
  1011. }
  1012. priv->is_open = false;
  1013. return darwin_to_libusb (kresult);
  1014. }
  1015. CFRetain (libusb_darwin_acfl);
  1016. /* add the cfSource to the async run loop */
  1017. CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
  1018. }
  1019. /* device opened successfully */
  1020. dpriv->open_count++;
  1021. usbi_dbg (HANDLE_CTX(dev_handle), "device open for access");
  1022. return 0;
  1023. }
  1024. static void darwin_close (struct libusb_device_handle *dev_handle) {
  1025. struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
  1026. struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
  1027. IOReturn kresult;
  1028. int i;
  1029. if (dpriv->open_count == 0) {
  1030. /* something is probably very wrong if this is the case */
  1031. usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!");
  1032. return;
  1033. }
  1034. dpriv->open_count--;
  1035. if (NULL == dpriv->device) {
  1036. usbi_warn (HANDLE_CTX (dev_handle), "darwin_close device missing IOService");
  1037. return;
  1038. }
  1039. /* make sure all interfaces are released */
  1040. for (i = 0 ; i < USB_MAXINTERFACES ; i++)
  1041. if (dev_handle->claimed_interfaces & (1U << i))
  1042. libusb_release_interface (dev_handle, i);
  1043. if (0 == dpriv->open_count) {
  1044. /* delete the device's async event source */
  1045. if (priv->cfSource) {
  1046. CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
  1047. CFRelease (priv->cfSource);
  1048. priv->cfSource = NULL;
  1049. CFRelease (libusb_darwin_acfl);
  1050. }
  1051. if (priv->is_open) {
  1052. /* close the device */
  1053. kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device);
  1054. if (kresult != kIOReturnSuccess) {
  1055. /* Log the fact that we had a problem closing the file, however failing a
  1056. * close isn't really an error, so return success anyway */
  1057. usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
  1058. }
  1059. }
  1060. }
  1061. }
  1062. static int darwin_get_configuration(struct libusb_device_handle *dev_handle, uint8_t *config) {
  1063. struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
  1064. *config = dpriv->active_config;
  1065. return LIBUSB_SUCCESS;
  1066. }
  1067. static enum libusb_error darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
  1068. struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
  1069. IOReturn kresult;
  1070. uint8_t i;
  1071. if (config == -1)
  1072. config = 0;
  1073. /* Setting configuration will invalidate the interface, so we need
  1074. to reclaim it. First, dispose of existing interfaces, if any. */
  1075. for (i = 0 ; i < USB_MAXINTERFACES ; i++)
  1076. if (dev_handle->claimed_interfaces & (1U << i))
  1077. darwin_release_interface (dev_handle, i);
  1078. kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, (UInt8)config);
  1079. if (kresult != kIOReturnSuccess)
  1080. return darwin_to_libusb (kresult);
  1081. /* Reclaim any interfaces. */
  1082. for (i = 0 ; i < USB_MAXINTERFACES ; i++)
  1083. if (dev_handle->claimed_interfaces & (1U << i))
  1084. darwin_claim_interface (dev_handle, i);
  1085. dpriv->active_config = (UInt8)config;
  1086. return LIBUSB_SUCCESS;
  1087. }
  1088. static IOReturn darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
  1089. IOUSBFindInterfaceRequest request;
  1090. IOReturn kresult;
  1091. io_iterator_t interface_iterator;
  1092. UInt8 bInterfaceNumber;
  1093. bool ret;
  1094. *usbInterfacep = IO_OBJECT_NULL;
  1095. /* Setup the Interface Request */
  1096. request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
  1097. request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
  1098. request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
  1099. request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
  1100. kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
  1101. if (kresult != kIOReturnSuccess)
  1102. return kresult;
  1103. while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
  1104. /* find the interface number */
  1105. ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
  1106. &bInterfaceNumber);
  1107. if (ret && bInterfaceNumber == ifc) {
  1108. break;
  1109. }
  1110. (void) IOObjectRelease (*usbInterfacep);
  1111. }
  1112. /* done with the interface iterator */
  1113. IOObjectRelease(interface_iterator);
  1114. return kIOReturnSuccess;
  1115. }
  1116. static enum libusb_error get_endpoints (struct libusb_device_handle *dev_handle, uint8_t iface) {
  1117. struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
  1118. /* current interface */
  1119. struct darwin_interface *cInterface = &priv->interfaces[iface];
  1120. #if InterfaceVersion >= 550
  1121. IOUSBEndpointProperties pipeProperties = {.bVersion = kUSBEndpointPropertiesVersion3};
  1122. #else
  1123. UInt8 dont_care1, dont_care3;
  1124. UInt16 dont_care2;
  1125. #endif
  1126. IOReturn kresult;
  1127. UInt8 numep, direction, number;
  1128. int rc;
  1129. struct libusb_context *ctx = HANDLE_CTX (dev_handle);
  1130. usbi_dbg (ctx, "building table of endpoints.");
  1131. /* retrieve the total number of endpoints on this interface */
  1132. kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep);
  1133. if (kresult != kIOReturnSuccess) {
  1134. usbi_err (ctx, "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
  1135. return darwin_to_libusb (kresult);
  1136. }
  1137. /* iterate through pipe references */
  1138. for (UInt8 i = 1 ; i <= numep ; i++) {
  1139. #if InterfaceVersion >= 550
  1140. kresult = (*(cInterface->interface))->GetPipePropertiesV3 (cInterface->interface, i, &pipeProperties);
  1141. number = pipeProperties.bEndpointNumber;
  1142. direction = pipeProperties.bDirection;
  1143. #else
  1144. kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1,
  1145. &dont_care2, &dont_care3);
  1146. #endif
  1147. if (kresult != kIOReturnSuccess) {
  1148. /* probably a buggy device. try to get the endpoint address from the descriptors */
  1149. struct libusb_config_descriptor *config;
  1150. const struct libusb_endpoint_descriptor *endpoint_desc;
  1151. UInt8 alt_setting;
  1152. kresult = (*(cInterface->interface))->GetAlternateSetting (cInterface->interface, &alt_setting);
  1153. if (kresult != kIOReturnSuccess) {
  1154. usbi_err (HANDLE_CTX (dev_handle), "can't get alternate setting for interface");
  1155. return darwin_to_libusb (kresult);
  1156. }
  1157. rc = libusb_get_active_config_descriptor (dev_handle->dev, &config);
  1158. if (LIBUSB_SUCCESS != rc) {
  1159. return rc;
  1160. }
  1161. if (iface >= config->bNumInterfaces) {
  1162. usbi_err (HANDLE_CTX (dev_handle), "interface %d out of range for device", iface);
  1163. return LIBUSB_ERROR_NOT_FOUND;
  1164. }
  1165. endpoint_desc = config->interface[iface].altsetting[alt_setting].endpoint + i - 1;
  1166. cInterface->endpoint_addrs[i - 1] = endpoint_desc->bEndpointAddress;
  1167. } else {
  1168. cInterface->endpoint_addrs[i - 1] = (UInt8)(((kUSBIn == direction) << kUSBRqDirnShift) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK));
  1169. }
  1170. usbi_dbg (ctx, "interface: %i pipe %i: dir: %i number: %i", iface, i, cInterface->endpoint_addrs[i - 1] >> kUSBRqDirnShift,
  1171. cInterface->endpoint_addrs[i - 1] & LIBUSB_ENDPOINT_ADDRESS_MASK);
  1172. }
  1173. cInterface->num_endpoints = numep;
  1174. return LIBUSB_SUCCESS;
  1175. }
  1176. static int darwin_claim_interface(struct libusb_device_handle *dev_handle, uint8_t iface) {
  1177. struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
  1178. struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
  1179. io_service_t usbInterface = IO_OBJECT_NULL;
  1180. IOReturn kresult;
  1181. enum libusb_error ret;
  1182. IOCFPlugInInterface **plugInInterface = NULL;
  1183. SInt32 score;
  1184. /* current interface */
  1185. struct darwin_interface *cInterface = &priv->interfaces[iface];
  1186. struct libusb_context *ctx = HANDLE_CTX (dev_handle);
  1187. kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
  1188. if (kresult != kIOReturnSuccess)
  1189. return darwin_to_libusb (kresult);
  1190. /* make sure we have an interface */
  1191. if (!usbInterface && dpriv->first_config != 0) {
  1192. usbi_info (ctx, "no interface found; setting configuration: %d", dpriv->first_config);
  1193. /* set the configuration */
  1194. ret = darwin_set_configuration (dev_handle, (int) dpriv->first_config);
  1195. if (ret != LIBUSB_SUCCESS) {
  1196. usbi_err (ctx, "could not set configuration");
  1197. return ret;
  1198. }
  1199. kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
  1200. if (kresult != kIOReturnSuccess) {
  1201. usbi_err (ctx, "darwin_get_interface: %s", darwin_error_str(kresult));
  1202. return darwin_to_libusb (kresult);
  1203. }
  1204. }
  1205. if (!usbInterface) {
  1206. usbi_info (ctx, "interface not found");
  1207. return LIBUSB_ERROR_NOT_FOUND;
  1208. }
  1209. /* get an interface to the device's interface */
  1210. kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
  1211. kIOCFPlugInInterfaceID, &plugInInterface, &score);
  1212. /* ignore release error */
  1213. (void)IOObjectRelease (usbInterface);
  1214. if (kresult != kIOReturnSuccess) {
  1215. usbi_err (ctx, "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
  1216. return darwin_to_libusb (kresult);
  1217. }
  1218. if (!plugInInterface) {
  1219. usbi_err (ctx, "plugin interface not found");
  1220. return LIBUSB_ERROR_NOT_FOUND;
  1221. }
  1222. /* Do the actual claim */
  1223. kresult = (*plugInInterface)->QueryInterface(plugInInterface,
  1224. CFUUIDGetUUIDBytes(InterfaceInterfaceID),
  1225. (LPVOID)&cInterface->interface);
  1226. /* We no longer need the intermediate plug-in */
  1227. /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
  1228. (*plugInInterface)->Release (plugInInterface);
  1229. if (kresult != kIOReturnSuccess || !cInterface->interface) {
  1230. usbi_err (ctx, "QueryInterface: %s", darwin_error_str(kresult));
  1231. return darwin_to_libusb (kresult);
  1232. }
  1233. /* claim the interface */
  1234. kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface);
  1235. if (kresult != kIOReturnSuccess) {
  1236. usbi_info (ctx, "USBInterfaceOpen: %s", darwin_error_str(kresult));
  1237. return darwin_to_libusb (kresult);
  1238. }
  1239. /* update list of endpoints */
  1240. ret = get_endpoints (dev_handle, iface);
  1241. if (ret) {
  1242. /* this should not happen */
  1243. darwin_release_interface (dev_handle, iface);
  1244. usbi_err (ctx, "could not build endpoint table");
  1245. return ret;
  1246. }
  1247. cInterface->cfSource = NULL;
  1248. /* create async event source */
  1249. kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource);
  1250. if (kresult != kIOReturnSuccess) {
  1251. usbi_err (ctx, "could not create async event source");
  1252. /* can't continue without an async event source */
  1253. (void)darwin_release_interface (dev_handle, iface);
  1254. return darwin_to_libusb (kresult);
  1255. }
  1256. /* add the cfSource to the async thread's run loop */
  1257. CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
  1258. usbi_dbg (ctx, "interface opened");
  1259. return LIBUSB_SUCCESS;
  1260. }
  1261. static int darwin_release_interface(struct libusb_device_handle *dev_handle, uint8_t iface) {
  1262. struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
  1263. IOReturn kresult;
  1264. /* current interface */
  1265. struct darwin_interface *cInterface = &priv->interfaces[iface];
  1266. /* Check to see if an interface is open */
  1267. if (!cInterface->interface)
  1268. return LIBUSB_SUCCESS;
  1269. /* clean up endpoint data */
  1270. cInterface->num_endpoints = 0;
  1271. /* delete the interface's async event source */
  1272. if (cInterface->cfSource) {
  1273. CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
  1274. CFRelease (cInterface->cfSource);
  1275. cInterface->cfSource = NULL;
  1276. }
  1277. kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface);
  1278. if (kresult != kIOReturnSuccess)
  1279. usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
  1280. kresult = (*(cInterface->interface))->Release(cInterface->interface);
  1281. if (kresult != kIOReturnSuccess)
  1282. usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult));
  1283. cInterface->interface = (usb_interface_t **) IO_OBJECT_NULL;
  1284. return darwin_to_libusb (kresult);
  1285. }
  1286. static int check_alt_setting_and_clear_halt(struct libusb_device_handle *dev_handle, uint8_t altsetting, struct darwin_interface *cInterface) {
  1287. enum libusb_error ret;
  1288. IOReturn kresult;
  1289. uint8_t current_alt_setting;
  1290. kresult = (*(cInterface->interface))->GetAlternateSetting (cInterface->interface, &current_alt_setting);
  1291. if (kresult == kIOReturnSuccess && altsetting != current_alt_setting) {
  1292. return LIBUSB_ERROR_PIPE;
  1293. }
  1294. for (int i = 0 ; i < cInterface->num_endpoints ; i++) {
  1295. ret = darwin_clear_halt(dev_handle, cInterface->endpoint_addrs[i]);
  1296. if (LIBUSB_SUCCESS != ret) {
  1297. usbi_warn(HANDLE_CTX (dev_handle), "error clearing pipe halt for endpoint %d", i);
  1298. if (LIBUSB_ERROR_NOT_FOUND == ret) {
  1299. /* may need to re-open the interface */
  1300. return ret;
  1301. }
  1302. }
  1303. }
  1304. return LIBUSB_SUCCESS;
  1305. }
  1306. static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, uint8_t iface, uint8_t altsetting) {
  1307. struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
  1308. IOReturn kresult;
  1309. enum libusb_error ret;
  1310. /* current interface */
  1311. struct darwin_interface *cInterface = &priv->interfaces[iface];
  1312. if (!cInterface->interface)
  1313. return LIBUSB_ERROR_NO_DEVICE;
  1314. kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting);
  1315. if (kresult == kIOReturnSuccess) {
  1316. /* update the list of endpoints */
  1317. ret = get_endpoints (dev_handle, iface);
  1318. if (ret) {
  1319. /* this should not happen */
  1320. darwin_release_interface (dev_handle, iface);
  1321. usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
  1322. }
  1323. return ret;
  1324. }
  1325. usbi_warn (HANDLE_CTX (dev_handle), "SetAlternateInterface: %s", darwin_error_str(kresult));
  1326. ret = darwin_to_libusb(kresult);
  1327. if (ret != LIBUSB_ERROR_PIPE) {
  1328. return ret;
  1329. }
  1330. /* If a device only supports a default setting for the specified interface, then a STALL
  1331. (kIOUSBPipeStalled) may be returned. Ref: USB 2.0 specs 9.4.10.
  1332. Mimic the behaviour in e.g. the Linux kernel: in such case, reset all endpoints
  1333. of the interface (as would have been done per 9.1.1.5) and return success. */
  1334. ret = check_alt_setting_and_clear_halt(dev_handle, altsetting, cInterface);
  1335. if (LIBUSB_ERROR_NOT_FOUND == ret) {
  1336. /* For some reason we need to reclaim the interface after the pipe error with some versions of macOS */
  1337. ret = darwin_claim_interface (dev_handle, iface);
  1338. if (LIBUSB_SUCCESS != ret) {
  1339. darwin_release_interface (dev_handle, iface);
  1340. usbi_err (HANDLE_CTX (dev_handle), "could not reclaim interface: %s", darwin_error_str(kresult));
  1341. }
  1342. ret = check_alt_setting_and_clear_halt(dev_handle, altsetting, cInterface);
  1343. }
  1344. return ret;
  1345. }
  1346. static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
  1347. /* current interface */
  1348. struct darwin_interface *cInterface;
  1349. IOReturn kresult;
  1350. uint8_t pipeRef;
  1351. /* determine the interface/endpoint to use */
  1352. if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, NULL, &cInterface) != 0) {
  1353. usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
  1354. return LIBUSB_ERROR_NOT_FOUND;
  1355. }
  1356. /* newer versions of darwin support clearing additional bits on the device's endpoint */
  1357. kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
  1358. if (kresult != kIOReturnSuccess)
  1359. usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
  1360. return darwin_to_libusb (kresult);
  1361. }
  1362. static int darwin_restore_state (struct libusb_device_handle *dev_handle, int8_t active_config,
  1363. unsigned long claimed_interfaces) {
  1364. struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
  1365. struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
  1366. int open_count = dpriv->open_count;
  1367. int ret;
  1368. struct libusb_context *ctx = HANDLE_CTX (dev_handle);
  1369. /* clear claimed interfaces temporarily */
  1370. dev_handle->claimed_interfaces = 0;
  1371. /* close and re-open the device */
  1372. priv->is_open = false;
  1373. dpriv->open_count = 1;
  1374. /* clean up open interfaces */
  1375. (void) darwin_close (dev_handle);
  1376. /* re-open the device */
  1377. ret = darwin_open (dev_handle);
  1378. dpriv->open_count = open_count;
  1379. if (LIBUSB_SUCCESS != ret) {
  1380. /* could not restore configuration */
  1381. return LIBUSB_ERROR_NOT_FOUND;
  1382. }
  1383. if (dpriv->active_config != active_config) {
  1384. usbi_dbg (ctx, "darwin/restore_state: restoring configuration %d...", active_config);
  1385. ret = darwin_set_configuration (dev_handle, active_config);
  1386. if (LIBUSB_SUCCESS != ret) {
  1387. usbi_dbg (ctx, "darwin/restore_state: could not restore configuration");
  1388. return LIBUSB_ERROR_NOT_FOUND;
  1389. }
  1390. }
  1391. usbi_dbg (ctx, "darwin/restore_state: reclaiming interfaces");
  1392. if (claimed_interfaces) {
  1393. for (uint8_t iface = 0 ; iface < USB_MAXINTERFACES ; ++iface) {
  1394. if (!(claimed_interfaces & (1U << iface))) {
  1395. continue;
  1396. }
  1397. usbi_dbg (ctx, "darwin/restore_state: re-claiming interface %u", iface);
  1398. ret = darwin_claim_interface (dev_handle, iface);
  1399. if (LIBUSB_SUCCESS != ret) {
  1400. usbi_dbg (ctx, "darwin/restore_state: could not claim interface %u", iface);
  1401. return LIBUSB_ERROR_NOT_FOUND;
  1402. }
  1403. dev_handle->claimed_interfaces |= 1U << iface;
  1404. }
  1405. }
  1406. usbi_dbg (ctx, "darwin/restore_state: device state restored");
  1407. return LIBUSB_SUCCESS;
  1408. }
  1409. static int darwin_reenumerate_device (struct libusb_device_handle *dev_handle, bool capture) {
  1410. struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
  1411. unsigned long claimed_interfaces = dev_handle->claimed_interfaces;
  1412. int8_t active_config = dpriv->active_config;
  1413. UInt32 options = 0;
  1414. IOUSBDeviceDescriptor descriptor;
  1415. IOUSBConfigurationDescriptorPtr cached_configuration;
  1416. IOUSBConfigurationDescriptor *cached_configurations;
  1417. IOReturn kresult;
  1418. UInt8 i;
  1419. struct libusb_context *ctx = HANDLE_CTX (dev_handle);
  1420. if (dpriv->in_reenumerate) {
  1421. /* ack, two (or more) threads are trying to reset the device! abort! */
  1422. return LIBUSB_ERROR_NOT_FOUND;
  1423. }
  1424. dpriv->in_reenumerate = true;
  1425. /* store copies of descriptors so they can be compared after the reset */
  1426. memcpy (&descriptor, &dpriv->dev_descriptor, sizeof (descriptor));
  1427. cached_configurations = alloca (sizeof (*cached_configurations) * descriptor.bNumConfigurations);
  1428. for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
  1429. (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
  1430. memcpy (cached_configurations + i, cached_configuration, sizeof (cached_configurations[i]));
  1431. }
  1432. /* if we need to release capture */
  1433. if (HAS_CAPTURE_DEVICE()) {
  1434. if (capture) {
  1435. #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101000
  1436. options |= kUSBReEnumerateCaptureDeviceMask;
  1437. #endif
  1438. }
  1439. } else {
  1440. capture = false;
  1441. }
  1442. /* from macOS 10.11 ResetDevice no longer does anything so just use USBDeviceReEnumerate */
  1443. kresult = (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, options);
  1444. if (kresult != kIOReturnSuccess) {
  1445. usbi_err (ctx, "USBDeviceReEnumerate: %s", darwin_error_str (kresult));
  1446. dpriv->in_reenumerate = false;
  1447. return darwin_to_libusb (kresult);
  1448. }
  1449. /* capture mode does not re-enumerate but it does require re-open */
  1450. if (capture) {
  1451. usbi_dbg (ctx, "darwin/reenumerate_device: restoring state...");
  1452. dpriv->in_reenumerate = false;
  1453. return darwin_restore_state (dev_handle, active_config, claimed_interfaces);
  1454. }
  1455. usbi_dbg (ctx, "darwin/reenumerate_device: waiting for re-enumeration to complete...");
  1456. struct timespec start;
  1457. usbi_get_monotonic_time(&start);
  1458. while (dpriv->in_reenumerate) {
  1459. struct timespec delay = {.tv_sec = 0, .tv_nsec = 1000};
  1460. nanosleep (&delay, NULL);
  1461. struct timespec now;
  1462. usbi_get_monotonic_time(&now);
  1463. unsigned long elapsed_us = (now.tv_sec - start.tv_sec) * USEC_PER_SEC +
  1464. (now.tv_nsec - start.tv_nsec) / 1000;
  1465. if (elapsed_us >= DARWIN_REENUMERATE_TIMEOUT_US) {
  1466. usbi_err (ctx, "darwin/reenumerate_device: timeout waiting for reenumerate");
  1467. dpriv->in_reenumerate = false;
  1468. return LIBUSB_ERROR_TIMEOUT;
  1469. }
  1470. }
  1471. /* compare descriptors */
  1472. usbi_dbg (ctx, "darwin/reenumerate_device: checking whether descriptors changed");
  1473. if (memcmp (&descriptor, &dpriv->dev_descriptor, sizeof (descriptor))) {
  1474. /* device descriptor changed. need to return not found. */
  1475. usbi_dbg (ctx, "darwin/reenumerate_device: device descriptor changed");
  1476. return LIBUSB_ERROR_NOT_FOUND;
  1477. }
  1478. for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
  1479. (void) (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
  1480. if (memcmp (cached_configuration, cached_configurations + i, sizeof (cached_configurations[i]))) {
  1481. usbi_dbg (ctx, "darwin/reenumerate_device: configuration descriptor %d changed", i);
  1482. return LIBUSB_ERROR_NOT_FOUND;
  1483. }
  1484. }
  1485. usbi_dbg (ctx, "darwin/reenumerate_device: device reset complete. restoring state...");
  1486. return darwin_restore_state (dev_handle, active_config, claimed_interfaces);
  1487. }
  1488. static int darwin_reset_device (struct libusb_device_handle *dev_handle) {
  1489. struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
  1490. IOReturn kresult;
  1491. enum libusb_error ret;
  1492. #if !defined(TARGET_OS_OSX) || TARGET_OS_OSX == 1
  1493. if (dpriv->capture_count > 0) {
  1494. /* we have to use ResetDevice as USBDeviceReEnumerate() loses the authorization for capture */
  1495. kresult = (*(dpriv->device))->ResetDevice (dpriv->device);
  1496. ret = darwin_to_libusb (kresult);
  1497. } else {
  1498. ret = darwin_reenumerate_device (dev_handle, false);
  1499. }
  1500. #else
  1501. /* ResetDevice() is missing on non-macOS platforms */
  1502. ret = darwin_reenumerate_device (dev_handle, false);
  1503. if ((ret == LIBUSB_SUCCESS || ret == LIBUSB_ERROR_NOT_FOUND) && dpriv->capture_count > 0) {
  1504. int capture_count;
  1505. int8_t active_config = dpriv->active_config;
  1506. unsigned long claimed_interfaces = dev_handle->claimed_interfaces;
  1507. /* save old capture_count */
  1508. capture_count = dpriv->capture_count;
  1509. /* reset capture count */
  1510. dpriv->capture_count = 0;
  1511. /* attempt to detach kernel driver again as it is now re-attached */
  1512. ret = darwin_detach_kernel_driver (dev_handle, 0);
  1513. if (ret != LIBUSB_SUCCESS) {
  1514. return ret;
  1515. }
  1516. /* restore capture_count */
  1517. dpriv->capture_count = capture_count;
  1518. /* restore configuration */
  1519. ret = darwin_restore_state (dev_handle, active_config, claimed_interfaces);
  1520. }
  1521. #endif
  1522. return ret;
  1523. }
  1524. static io_service_t usb_find_interface_matching_location (const io_name_t class_name, UInt8 interface_number, UInt32 location) {
  1525. CFMutableDictionaryRef matchingDict = IOServiceMatching (class_name);
  1526. CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable (kCFAllocatorDefault, 0,
  1527. &kCFTypeDictionaryKeyCallBacks,
  1528. &kCFTypeDictionaryValueCallBacks);
  1529. CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberSInt32Type, &location);
  1530. CFTypeRef interfaceCF = CFNumberCreate (NULL, kCFNumberSInt8Type, &interface_number);
  1531. CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
  1532. CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
  1533. CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBHostMatchingPropertyInterfaceNumber), interfaceCF);
  1534. CFRelease (interfaceCF);
  1535. CFRelease (locationCF);
  1536. CFRelease (propertyMatchDict);
  1537. return IOServiceGetMatchingService (darwin_default_master_port, matchingDict);
  1538. }
  1539. static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, uint8_t interface) {
  1540. struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
  1541. io_service_t usb_interface, child = IO_OBJECT_NULL;
  1542. /* locate the IO registry entry for this interface */
  1543. usb_interface = usb_find_interface_matching_location (kIOUSBHostInterfaceClassName, interface, dpriv->location);
  1544. if (0 == usb_interface) {
  1545. /* check for the legacy class entry */
  1546. usb_interface = usb_find_interface_matching_location (kIOUSBInterfaceClassName, interface, dpriv->location);
  1547. if (0 == usb_interface) {
  1548. return LIBUSB_ERROR_NOT_FOUND;
  1549. }
  1550. }
  1551. /* if the IO object has a child entry in the IO Registry it has a kernel driver attached */
  1552. (void) IORegistryEntryGetChildEntry (usb_interface, kIOServicePlane, &child);
  1553. IOObjectRelease (usb_interface);
  1554. if (IO_OBJECT_NULL != child) {
  1555. IOObjectRelease (child);
  1556. return 1;
  1557. }
  1558. /* no driver */
  1559. return 0;
  1560. }
  1561. static void darwin_destroy_device(struct libusb_device *dev) {
  1562. struct darwin_device_priv *dpriv = usbi_get_device_priv(dev);
  1563. if (dpriv->dev) {
  1564. /* need to hold the lock in case this is the last reference to the device */
  1565. usbi_mutex_lock(&darwin_cached_devices_lock);
  1566. darwin_deref_cached_device (dpriv->dev);
  1567. dpriv->dev = NULL;
  1568. usbi_mutex_unlock(&darwin_cached_devices_lock);
  1569. }
  1570. }
  1571. static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
  1572. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1573. IOReturn ret;
  1574. uint8_t transferType;
  1575. uint8_t pipeRef;
  1576. uint16_t maxPacketSize;
  1577. struct darwin_interface *cInterface;
  1578. #if InterfaceVersion >= 550
  1579. IOUSBEndpointProperties pipeProperties = {.bVersion = kUSBEndpointPropertiesVersion3};
  1580. #else
  1581. /* None of the values below are used in libusb for bulk transfers */
  1582. uint8_t direction, number, interval;
  1583. #endif
  1584. if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
  1585. usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
  1586. return LIBUSB_ERROR_NOT_FOUND;
  1587. }
  1588. #if InterfaceVersion >= 550
  1589. ret = (*(cInterface->interface))->GetPipePropertiesV3 (cInterface->interface, pipeRef, &pipeProperties);
  1590. transferType = pipeProperties.bTransferType;
  1591. maxPacketSize = pipeProperties.wMaxPacketSize;
  1592. #else
  1593. ret = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
  1594. &transferType, &maxPacketSize, &interval);
  1595. #endif
  1596. if (ret) {
  1597. usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
  1598. darwin_error_str(ret), ret);
  1599. return darwin_to_libusb (ret);
  1600. }
  1601. if (0 != (transfer->length % maxPacketSize)) {
  1602. /* do not need a zero packet */
  1603. transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
  1604. }
  1605. /* submit the request */
  1606. /* timeouts are unavailable on interrupt endpoints */
  1607. if (transferType == kUSBInterrupt) {
  1608. if (IS_XFERIN(transfer))
  1609. ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer,
  1610. (UInt32)transfer->length, darwin_async_io_callback, itransfer);
  1611. else
  1612. ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer,
  1613. (UInt32)transfer->length, darwin_async_io_callback, itransfer);
  1614. } else {
  1615. itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
  1616. if (IS_XFERIN(transfer))
  1617. ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
  1618. (UInt32)transfer->length, transfer->timeout, transfer->timeout,
  1619. darwin_async_io_callback, itransfer);
  1620. else
  1621. ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer,
  1622. (UInt32)transfer->length, transfer->timeout, transfer->timeout,
  1623. darwin_async_io_callback, itransfer);
  1624. }
  1625. if (ret)
  1626. usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
  1627. darwin_error_str(ret), ret);
  1628. return darwin_to_libusb (ret);
  1629. }
  1630. #if InterfaceVersion >= 550
  1631. static int submit_stream_transfer(struct usbi_transfer *itransfer) {
  1632. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1633. struct darwin_interface *cInterface;
  1634. uint8_t pipeRef;
  1635. IOReturn ret;
  1636. if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
  1637. usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
  1638. return LIBUSB_ERROR_NOT_FOUND;
  1639. }
  1640. itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
  1641. if (IS_XFERIN(transfer))
  1642. ret = (*(cInterface->interface))->ReadStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
  1643. transfer->buffer, (UInt32)transfer->length, transfer->timeout,
  1644. transfer->timeout, darwin_async_io_callback, itransfer);
  1645. else
  1646. ret = (*(cInterface->interface))->WriteStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id,
  1647. transfer->buffer, (UInt32)transfer->length, transfer->timeout,
  1648. transfer->timeout, darwin_async_io_callback, itransfer);
  1649. if (ret)
  1650. usbi_err (TRANSFER_CTX (transfer), "bulk stream transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
  1651. darwin_error_str(ret), ret);
  1652. return darwin_to_libusb (ret);
  1653. }
  1654. #endif
  1655. static int submit_iso_transfer(struct usbi_transfer *itransfer) {
  1656. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1657. struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
  1658. IOReturn kresult;
  1659. uint8_t pipeRef, interval;
  1660. UInt64 frame;
  1661. AbsoluteTime atTime;
  1662. int i;
  1663. #if InterfaceVersion >= 550
  1664. IOUSBEndpointProperties pipeProperties = {.bVersion = kUSBEndpointPropertiesVersion3};
  1665. #else
  1666. /* None of the values below are used in libusb for iso transfers */
  1667. uint8_t direction, number, transferType;
  1668. uint16_t maxPacketSize;
  1669. #endif
  1670. struct darwin_interface *cInterface;
  1671. /* construct an array of IOUSBIsocFrames, reuse the old one if the sizes are the same */
  1672. if (tpriv->num_iso_packets != transfer->num_iso_packets) {
  1673. free(tpriv->isoc_framelist);
  1674. tpriv->isoc_framelist = NULL;
  1675. }
  1676. if (!tpriv->isoc_framelist) {
  1677. tpriv->num_iso_packets = transfer->num_iso_packets;
  1678. tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc ((size_t)transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
  1679. if (!tpriv->isoc_framelist)
  1680. return LIBUSB_ERROR_NO_MEM;
  1681. }
  1682. /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
  1683. for (i = 0 ; i < transfer->num_iso_packets ; i++) {
  1684. unsigned int length = transfer->iso_packet_desc[i].length;
  1685. assert(length <= UINT16_MAX);
  1686. tpriv->isoc_framelist[i].frReqCount = (UInt16)length;
  1687. }
  1688. /* determine the interface/endpoint to use */
  1689. if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
  1690. usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
  1691. return LIBUSB_ERROR_NOT_FOUND;
  1692. }
  1693. /* determine the properties of this endpoint and the speed of the device */
  1694. #if InterfaceVersion >= 550
  1695. kresult = (*(cInterface->interface))->GetPipePropertiesV3 (cInterface->interface, pipeRef, &pipeProperties);
  1696. interval = pipeProperties.bInterval;
  1697. #else
  1698. kresult = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number,
  1699. &transferType, &maxPacketSize, &interval);
  1700. #endif
  1701. if (kresult != kIOReturnSuccess) {
  1702. usbi_err (TRANSFER_CTX (transfer), "failed to get pipe properties: %d", kresult);
  1703. free(tpriv->isoc_framelist);
  1704. tpriv->isoc_framelist = NULL;
  1705. return darwin_to_libusb (kresult);
  1706. }
  1707. /* Last but not least we need the bus frame number */
  1708. kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime);
  1709. if (kresult != kIOReturnSuccess) {
  1710. usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
  1711. free(tpriv->isoc_framelist);
  1712. tpriv->isoc_framelist = NULL;
  1713. return darwin_to_libusb (kresult);
  1714. }
  1715. /* schedule for a frame a little in the future */
  1716. frame += 4;
  1717. if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
  1718. frame = cInterface->frames[transfer->endpoint];
  1719. /* submit the request */
  1720. if (IS_XFERIN(transfer))
  1721. kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
  1722. (UInt32)transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
  1723. itransfer);
  1724. else
  1725. kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame,
  1726. (UInt32)transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
  1727. itransfer);
  1728. if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
  1729. /* Full speed */
  1730. cInterface->frames[transfer->endpoint] = frame + (UInt32)transfer->num_iso_packets * (1U << (interval - 1));
  1731. else
  1732. /* High/super speed */
  1733. cInterface->frames[transfer->endpoint] = frame + (UInt32)transfer->num_iso_packets * (1U << (interval - 1)) / 8;
  1734. if (kresult != kIOReturnSuccess) {
  1735. usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
  1736. darwin_error_str(kresult));
  1737. free (tpriv->isoc_framelist);
  1738. tpriv->isoc_framelist = NULL;
  1739. }
  1740. return darwin_to_libusb (kresult);
  1741. }
  1742. static int submit_control_transfer(struct usbi_transfer *itransfer) {
  1743. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1744. struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
  1745. struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
  1746. struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
  1747. IOReturn kresult;
  1748. memset(&tpriv->req, 0, sizeof(tpriv->req));
  1749. /* IOUSBDeviceInterface expects the request in cpu endianness */
  1750. tpriv->req.bmRequestType = setup->bmRequestType;
  1751. tpriv->req.bRequest = setup->bRequest;
  1752. /* these values should be in bus order from libusb_fill_control_setup */
  1753. tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
  1754. tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
  1755. tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
  1756. /* data is stored after the libusb control block */
  1757. tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
  1758. tpriv->req.completionTimeout = transfer->timeout;
  1759. tpriv->req.noDataTimeout = transfer->timeout;
  1760. itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
  1761. /* all transfers in libusb-1.0 are async */
  1762. if (transfer->endpoint) {
  1763. struct darwin_interface *cInterface;
  1764. uint8_t pipeRef;
  1765. if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
  1766. usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
  1767. return LIBUSB_ERROR_NOT_FOUND;
  1768. }
  1769. kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer);
  1770. } else
  1771. /* control request on endpoint 0 */
  1772. kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
  1773. if (kresult != kIOReturnSuccess)
  1774. usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
  1775. return darwin_to_libusb (kresult);
  1776. }
  1777. static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
  1778. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1779. switch (transfer->type) {
  1780. case LIBUSB_TRANSFER_TYPE_CONTROL:
  1781. return submit_control_transfer(itransfer);
  1782. case LIBUSB_TRANSFER_TYPE_BULK:
  1783. case LIBUSB_TRANSFER_TYPE_INTERRUPT:
  1784. return submit_bulk_transfer(itransfer);
  1785. case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
  1786. return submit_iso_transfer(itransfer);
  1787. case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
  1788. #if InterfaceVersion >= 550
  1789. return submit_stream_transfer(itransfer);
  1790. #else
  1791. usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version does not support bulk stream transfers");
  1792. return LIBUSB_ERROR_NOT_SUPPORTED;
  1793. #endif
  1794. default:
  1795. usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
  1796. return LIBUSB_ERROR_INVALID_PARAM;
  1797. }
  1798. }
  1799. static int cancel_control_transfer(struct usbi_transfer *itransfer) {
  1800. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1801. struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
  1802. IOReturn kresult;
  1803. usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
  1804. if (!dpriv->device)
  1805. return LIBUSB_ERROR_NO_DEVICE;
  1806. kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device);
  1807. return darwin_to_libusb (kresult);
  1808. }
  1809. static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
  1810. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1811. struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
  1812. struct darwin_interface *cInterface;
  1813. uint8_t pipeRef, iface;
  1814. IOReturn kresult;
  1815. struct libusb_context *ctx = ITRANSFER_CTX (itransfer);
  1816. if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface, &cInterface) != 0) {
  1817. usbi_err (ctx, "endpoint not found on any open interface");
  1818. return LIBUSB_ERROR_NOT_FOUND;
  1819. }
  1820. if (!dpriv->device)
  1821. return LIBUSB_ERROR_NO_DEVICE;
  1822. usbi_warn (ctx, "aborting all transactions on interface %d pipe %d", iface, pipeRef);
  1823. /* abort transactions */
  1824. #if InterfaceVersion >= 550
  1825. if (LIBUSB_TRANSFER_TYPE_BULK_STREAM == transfer->type)
  1826. (*(cInterface->interface))->AbortStreamsPipe (cInterface->interface, pipeRef, itransfer->stream_id);
  1827. else
  1828. #endif
  1829. (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef);
  1830. usbi_dbg (ctx, "calling clear pipe stall to clear the data toggle bit");
  1831. /* newer versions of darwin support clearing additional bits on the device's endpoint */
  1832. kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef);
  1833. return darwin_to_libusb (kresult);
  1834. }
  1835. static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
  1836. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1837. switch (transfer->type) {
  1838. case LIBUSB_TRANSFER_TYPE_CONTROL:
  1839. return cancel_control_transfer(itransfer);
  1840. case LIBUSB_TRANSFER_TYPE_BULK:
  1841. case LIBUSB_TRANSFER_TYPE_INTERRUPT:
  1842. case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
  1843. return darwin_abort_transfers (itransfer);
  1844. default:
  1845. usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
  1846. return LIBUSB_ERROR_INVALID_PARAM;
  1847. }
  1848. }
  1849. static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
  1850. struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
  1851. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1852. struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
  1853. usbi_dbg (TRANSFER_CTX(transfer), "an async io operation has completed");
  1854. /* if requested write a zero packet */
  1855. if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
  1856. struct darwin_interface *cInterface;
  1857. uint8_t pipeRef;
  1858. (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface);
  1859. (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0);
  1860. }
  1861. tpriv->result = result;
  1862. tpriv->size = (UInt32) (uintptr_t) arg0;
  1863. /* signal the core that this transfer is complete */
  1864. usbi_signal_transfer_completion(itransfer);
  1865. }
  1866. static enum libusb_transfer_status darwin_transfer_status (struct usbi_transfer *itransfer, IOReturn result) {
  1867. if (itransfer->timeout_flags & USBI_TRANSFER_TIMED_OUT)
  1868. result = kIOUSBTransactionTimeout;
  1869. struct libusb_context *ctx = ITRANSFER_CTX (itransfer);
  1870. switch (result) {
  1871. case kIOReturnUnderrun:
  1872. case kIOReturnSuccess:
  1873. return LIBUSB_TRANSFER_COMPLETED;
  1874. case kIOReturnAborted:
  1875. return LIBUSB_TRANSFER_CANCELLED;
  1876. case kIOUSBPipeStalled:
  1877. usbi_dbg (ctx, "transfer error: pipe is stalled");
  1878. return LIBUSB_TRANSFER_STALL;
  1879. case kIOReturnOverrun:
  1880. usbi_warn (ctx, "transfer error: data overrun");
  1881. return LIBUSB_TRANSFER_OVERFLOW;
  1882. case kIOUSBTransactionTimeout:
  1883. usbi_warn (ctx, "transfer error: timed out");
  1884. itransfer->timeout_flags |= USBI_TRANSFER_TIMED_OUT;
  1885. return LIBUSB_TRANSFER_TIMED_OUT;
  1886. default:
  1887. usbi_warn (ctx, "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
  1888. return LIBUSB_TRANSFER_ERROR;
  1889. }
  1890. }
  1891. static int darwin_handle_transfer_completion (struct usbi_transfer *itransfer) {
  1892. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1893. struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
  1894. const unsigned char max_transfer_type = LIBUSB_TRANSFER_TYPE_BULK_STREAM;
  1895. const char *transfer_types[] = {"control", "isoc", "bulk", "interrupt", "bulk-stream", NULL};
  1896. bool is_isoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
  1897. struct libusb_context *ctx = ITRANSFER_CTX (itransfer);
  1898. if (transfer->type > max_transfer_type) {
  1899. usbi_err (ctx, "unknown endpoint type %d", transfer->type);
  1900. return LIBUSB_ERROR_INVALID_PARAM;
  1901. }
  1902. if (NULL == tpriv) {
  1903. usbi_err (ctx, "malformed request is missing transfer priv");
  1904. return LIBUSB_ERROR_INVALID_PARAM;
  1905. }
  1906. usbi_dbg (ctx, "handling transfer completion type %s with kernel status %d", transfer_types[transfer->type], tpriv->result);
  1907. if (kIOReturnSuccess == tpriv->result || kIOReturnUnderrun == tpriv->result || kIOUSBTransactionTimeout == tpriv->result) {
  1908. if (is_isoc && tpriv->isoc_framelist) {
  1909. /* copy isochronous results back */
  1910. for (int i = 0; i < transfer->num_iso_packets ; i++) {
  1911. struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
  1912. lib_desc->status = darwin_transfer_status (itransfer, tpriv->isoc_framelist[i].frStatus);
  1913. lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
  1914. }
  1915. } else if (!is_isoc) {
  1916. itransfer->transferred += tpriv->size;
  1917. }
  1918. }
  1919. /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
  1920. return usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, tpriv->result));
  1921. }
  1922. #if !defined(HAVE_CLOCK_GETTIME)
  1923. void usbi_get_monotonic_time(struct timespec *tp) {
  1924. mach_timespec_t sys_time;
  1925. /* use system boot time as reference for the monotonic clock */
  1926. clock_get_time (clock_monotonic, &sys_time);
  1927. tp->tv_sec = sys_time.tv_sec;
  1928. tp->tv_nsec = sys_time.tv_nsec;
  1929. }
  1930. void usbi_get_real_time(struct timespec *tp) {
  1931. mach_timespec_t sys_time;
  1932. /* CLOCK_REALTIME represents time since the epoch */
  1933. clock_get_time (clock_realtime, &sys_time);
  1934. tp->tv_sec = sys_time.tv_sec;
  1935. tp->tv_nsec = sys_time.tv_nsec;
  1936. }
  1937. #endif
  1938. #if InterfaceVersion >= 550
  1939. static int darwin_alloc_streams (struct libusb_device_handle *dev_handle, uint32_t num_streams, unsigned char *endpoints,
  1940. int num_endpoints) {
  1941. struct darwin_interface *cInterface;
  1942. UInt32 supportsStreams;
  1943. uint8_t pipeRef;
  1944. int rc, i;
  1945. /* find the minimum number of supported streams on the endpoint list */
  1946. for (i = 0 ; i < num_endpoints ; ++i) {
  1947. if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface))) {
  1948. return rc;
  1949. }
  1950. (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
  1951. if (num_streams > supportsStreams)
  1952. num_streams = supportsStreams;
  1953. }
  1954. /* it is an error if any endpoint in endpoints does not support streams */
  1955. if (0 == num_streams)
  1956. return LIBUSB_ERROR_INVALID_PARAM;
  1957. /* create the streams */
  1958. for (i = 0 ; i < num_endpoints ; ++i) {
  1959. (void) ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
  1960. rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, num_streams);
  1961. if (kIOReturnSuccess != rc)
  1962. return darwin_to_libusb(rc);
  1963. }
  1964. assert(num_streams <= INT_MAX);
  1965. return (int)num_streams;
  1966. }
  1967. static int darwin_free_streams (struct libusb_device_handle *dev_handle, unsigned char *endpoints, int num_endpoints) {
  1968. struct darwin_interface *cInterface;
  1969. UInt32 supportsStreams;
  1970. uint8_t pipeRef;
  1971. int rc;
  1972. for (int i = 0 ; i < num_endpoints ; ++i) {
  1973. if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface)))
  1974. return rc;
  1975. (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams);
  1976. if (0 == supportsStreams)
  1977. return LIBUSB_ERROR_INVALID_PARAM;
  1978. rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, 0);
  1979. if (kIOReturnSuccess != rc)
  1980. return darwin_to_libusb(rc);
  1981. }
  1982. return LIBUSB_SUCCESS;
  1983. }
  1984. #endif
  1985. #if InterfaceVersion >= 700
  1986. /* macOS APIs for getting entitlement values */
  1987. #if !defined(TARGET_OS_OSX) || TARGET_OS_OSX == 1
  1988. #include <Security/Security.h>
  1989. #else
  1990. typedef struct __SecTask *SecTaskRef;
  1991. extern SecTaskRef SecTaskCreateFromSelf(CFAllocatorRef allocator);
  1992. extern CFTypeRef SecTaskCopyValueForEntitlement(SecTaskRef task, CFStringRef entitlement, CFErrorRef *error);
  1993. #endif
  1994. static bool darwin_has_capture_entitlements (void) {
  1995. SecTaskRef task;
  1996. CFTypeRef value;
  1997. bool entitled;
  1998. task = SecTaskCreateFromSelf (kCFAllocatorDefault);
  1999. if (task == NULL) {
  2000. return false;
  2001. }
  2002. value = SecTaskCopyValueForEntitlement(task, CFSTR("com.apple.vm.device-access"), NULL);
  2003. CFRelease (task);
  2004. entitled = value && (CFGetTypeID (value) == CFBooleanGetTypeID ()) && CFBooleanGetValue (value);
  2005. if (value) {
  2006. CFRelease (value);
  2007. }
  2008. return entitled;
  2009. }
  2010. static int darwin_reload_device (struct libusb_device_handle *dev_handle) {
  2011. struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
  2012. enum libusb_error err;
  2013. usbi_mutex_lock(&darwin_cached_devices_lock);
  2014. (*(dpriv->device))->Release(dpriv->device);
  2015. dpriv->device = darwin_device_from_service (HANDLE_CTX (dev_handle), dpriv->service);
  2016. if (!dpriv->device) {
  2017. err = LIBUSB_ERROR_NO_DEVICE;
  2018. } else {
  2019. err = LIBUSB_SUCCESS;
  2020. }
  2021. usbi_mutex_unlock(&darwin_cached_devices_lock);
  2022. return err;
  2023. }
  2024. /* On macOS, we capture an entire device at once, not individual interfaces. */
  2025. static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, uint8_t interface) {
  2026. UNUSED(interface);
  2027. struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
  2028. IOReturn kresult;
  2029. enum libusb_error err;
  2030. struct libusb_context *ctx = HANDLE_CTX (dev_handle);
  2031. if (HAS_CAPTURE_DEVICE()) {
  2032. } else {
  2033. return LIBUSB_ERROR_NOT_SUPPORTED;
  2034. }
  2035. if (dpriv->capture_count == 0) {
  2036. usbi_dbg (ctx, "attempting to detach kernel driver from device");
  2037. if (darwin_has_capture_entitlements ()) {
  2038. /* request authorization */
  2039. kresult = IOServiceAuthorize (dpriv->service, kIOServiceInteractionAllowed);
  2040. if (kresult != kIOReturnSuccess) {
  2041. usbi_warn (ctx, "IOServiceAuthorize: %s", darwin_error_str(kresult));
  2042. return darwin_to_libusb (kresult);
  2043. }
  2044. /* we need start() to be called again for authorization status to refresh */
  2045. err = darwin_reload_device (dev_handle);
  2046. if (err != LIBUSB_SUCCESS) {
  2047. return err;
  2048. }
  2049. } else {
  2050. usbi_info (ctx, "no capture entitlements. may not be able to detach the kernel driver for this device");
  2051. if (0 != geteuid()) {
  2052. usbi_warn (ctx, "USB device capture requires either an entitlement (com.apple.vm.device-access) or root privilege");
  2053. return LIBUSB_ERROR_ACCESS;
  2054. }
  2055. }
  2056. /* reset device to release existing drivers */
  2057. err = darwin_reenumerate_device (dev_handle, true);
  2058. if (err != LIBUSB_SUCCESS) {
  2059. return err;
  2060. }
  2061. }
  2062. dpriv->capture_count++;
  2063. return LIBUSB_SUCCESS;
  2064. }
  2065. static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, uint8_t interface) {
  2066. UNUSED(interface);
  2067. struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
  2068. if (HAS_CAPTURE_DEVICE()) {
  2069. } else {
  2070. return LIBUSB_ERROR_NOT_SUPPORTED;
  2071. }
  2072. dpriv->capture_count--;
  2073. if (dpriv->capture_count > 0) {
  2074. return LIBUSB_SUCCESS;
  2075. }
  2076. usbi_dbg (HANDLE_CTX (dev_handle), "reenumerating device for kernel driver attach");
  2077. /* reset device to attach kernel drivers */
  2078. return darwin_reenumerate_device (dev_handle, false);
  2079. }
  2080. static int darwin_capture_claim_interface(struct libusb_device_handle *dev_handle, uint8_t iface) {
  2081. enum libusb_error ret;
  2082. if (dev_handle->auto_detach_kernel_driver && darwin_kernel_driver_active(dev_handle, iface)) {
  2083. ret = darwin_detach_kernel_driver (dev_handle, iface);
  2084. if (ret != LIBUSB_SUCCESS) {
  2085. usbi_info (HANDLE_CTX (dev_handle), "failed to auto-detach the kernel driver for this device, ret=%d", ret);
  2086. }
  2087. }
  2088. return darwin_claim_interface (dev_handle, iface);
  2089. }
  2090. static int darwin_capture_release_interface(struct libusb_device_handle *dev_handle, uint8_t iface) {
  2091. enum libusb_error ret;
  2092. struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
  2093. ret = darwin_release_interface (dev_handle, iface);
  2094. if (ret != LIBUSB_SUCCESS) {
  2095. return ret;
  2096. }
  2097. if (dev_handle->auto_detach_kernel_driver && dpriv->capture_count > 0) {
  2098. ret = darwin_attach_kernel_driver (dev_handle, iface);
  2099. if (LIBUSB_SUCCESS != ret) {
  2100. usbi_info (HANDLE_CTX (dev_handle), "on attempt to reattach the kernel driver got ret=%d", ret);
  2101. }
  2102. /* ignore the error as the interface was successfully released */
  2103. }
  2104. return LIBUSB_SUCCESS;
  2105. }
  2106. #endif
  2107. const struct usbi_os_backend usbi_backend = {
  2108. .name = "Darwin",
  2109. .caps = USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
  2110. .init = darwin_init,
  2111. .exit = darwin_exit,
  2112. .get_active_config_descriptor = darwin_get_active_config_descriptor,
  2113. .get_config_descriptor = darwin_get_config_descriptor,
  2114. .hotplug_poll = darwin_hotplug_poll,
  2115. .open = darwin_open,
  2116. .close = darwin_close,
  2117. .get_configuration = darwin_get_configuration,
  2118. .set_configuration = darwin_set_configuration,
  2119. .set_interface_altsetting = darwin_set_interface_altsetting,
  2120. .clear_halt = darwin_clear_halt,
  2121. .reset_device = darwin_reset_device,
  2122. #if InterfaceVersion >= 550
  2123. .alloc_streams = darwin_alloc_streams,
  2124. .free_streams = darwin_free_streams,
  2125. #endif
  2126. .kernel_driver_active = darwin_kernel_driver_active,
  2127. #if InterfaceVersion >= 700
  2128. .detach_kernel_driver = darwin_detach_kernel_driver,
  2129. .attach_kernel_driver = darwin_attach_kernel_driver,
  2130. .claim_interface = darwin_capture_claim_interface,
  2131. .release_interface = darwin_capture_release_interface,
  2132. #else
  2133. .claim_interface = darwin_claim_interface,
  2134. .release_interface = darwin_release_interface,
  2135. #endif
  2136. .destroy_device = darwin_destroy_device,
  2137. .submit_transfer = darwin_submit_transfer,
  2138. .cancel_transfer = darwin_cancel_transfer,
  2139. .handle_transfer_completion = darwin_handle_transfer_completion,
  2140. .device_priv_size = sizeof(struct darwin_device_priv),
  2141. .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
  2142. .transfer_priv_size = sizeof(struct darwin_transfer_priv),
  2143. };