core.c 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242
  1. /* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */
  2. /*
  3. * Core functions for libusbx
  4. * Copyright © 2012-2013 Nathan Hjelm <hjelmn@cs.unm.edu>
  5. * Copyright © 2007-2008 Daniel Drake <dsd@gentoo.org>
  6. * Copyright © 2001 Johannes Erdfelt <johannes@erdfelt.com>
  7. *
  8. * This library is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * This library is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with this library; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. #include "config.h"
  23. #include <errno.h>
  24. #include <stdarg.h>
  25. #include <stdio.h>
  26. #include <stdlib.h>
  27. #include <string.h>
  28. #ifdef HAVE_SYS_TYPES_H
  29. #include <sys/types.h>
  30. #endif
  31. #ifdef HAVE_SYS_TIME_H
  32. #include <sys/time.h>
  33. #endif
  34. #ifdef HAVE_SYSLOG_H
  35. #include <syslog.h>
  36. #endif
  37. #ifdef __ANDROID__
  38. #include <android/log.h>
  39. #endif
  40. #include "libusbi.h"
  41. #include "hotplug.h"
  42. #if defined(OS_LINUX)
  43. const struct usbi_os_backend * const usbi_backend = &linux_usbfs_backend;
  44. #elif defined(OS_DARWIN)
  45. const struct usbi_os_backend * const usbi_backend = &darwin_backend;
  46. #elif defined(OS_OPENBSD)
  47. const struct usbi_os_backend * const usbi_backend = &openbsd_backend;
  48. #elif defined(OS_NETBSD)
  49. const struct usbi_os_backend * const usbi_backend = &netbsd_backend;
  50. #elif defined(OS_WINDOWS)
  51. const struct usbi_os_backend * const usbi_backend = &windows_backend;
  52. #elif defined(OS_WINCE)
  53. const struct usbi_os_backend * const usbi_backend = &wince_backend;
  54. #else
  55. #error "Unsupported OS"
  56. #endif
  57. struct libusb_context *usbi_default_context = NULL;
  58. static const struct libusb_version libusb_version_internal =
  59. { LIBUSB_MAJOR, LIBUSB_MINOR, LIBUSB_MICRO, LIBUSB_NANO,
  60. LIBUSB_RC, "http://libusbx.org" };
  61. static int default_context_refcnt = 0;
  62. static usbi_mutex_static_t default_context_lock = USBI_MUTEX_INITIALIZER;
  63. static struct timeval timestamp_origin = { 0, 0 };
  64. usbi_mutex_static_t active_contexts_lock = USBI_MUTEX_INITIALIZER;
  65. struct list_head active_contexts_list;
  66. /**
  67. * \mainpage libusbx-1.0 API Reference
  68. *
  69. * \section intro Introduction
  70. *
  71. * libusbx is an open source library that allows you to communicate with USB
  72. * devices from userspace. For more info, see the
  73. * <a href="http://libusbx.org">libusbx homepage</a>.
  74. *
  75. * This documentation is aimed at application developers wishing to
  76. * communicate with USB peripherals from their own software. After reviewing
  77. * this documentation, feedback and questions can be sent to the
  78. * <a href="http://mailing-list.libusbx.org">libusbx-devel mailing list</a>.
  79. *
  80. * This documentation assumes knowledge of how to operate USB devices from
  81. * a software standpoint (descriptors, configurations, interfaces, endpoints,
  82. * control/bulk/interrupt/isochronous transfers, etc). Full information
  83. * can be found in the <a href="http://www.usb.org/developers/docs/">USB 3.0
  84. * Specification</a> which is available for free download. You can probably
  85. * find less verbose introductions by searching the web.
  86. *
  87. * \section features Library features
  88. *
  89. * - All transfer types supported (control/bulk/interrupt/isochronous)
  90. * - 2 transfer interfaces:
  91. * -# Synchronous (simple)
  92. * -# Asynchronous (more complicated, but more powerful)
  93. * - Thread safe (although the asynchronous interface means that you
  94. * usually won't need to thread)
  95. * - Lightweight with lean API
  96. * - Compatible with libusb-0.1 through the libusb-compat-0.1 translation layer
  97. * - Hotplug support (on some platforms). See \ref hotplug.
  98. *
  99. * \section gettingstarted Getting Started
  100. *
  101. * To begin reading the API documentation, start with the Modules page which
  102. * links to the different categories of libusbx's functionality.
  103. *
  104. * One decision you will have to make is whether to use the synchronous
  105. * or the asynchronous data transfer interface. The \ref io documentation
  106. * provides some insight into this topic.
  107. *
  108. * Some example programs can be found in the libusbx source distribution under
  109. * the "examples" subdirectory. The libusbx homepage includes a list of
  110. * real-life project examples which use libusbx.
  111. *
  112. * \section errorhandling Error handling
  113. *
  114. * libusbx functions typically return 0 on success or a negative error code
  115. * on failure. These negative error codes relate to LIBUSB_ERROR constants
  116. * which are listed on the \ref misc "miscellaneous" documentation page.
  117. *
  118. * \section msglog Debug message logging
  119. *
  120. * libusbx uses stderr for all logging. By default, logging is set to NONE,
  121. * which means that no output will be produced. However, unless the library
  122. * has been compiled with logging disabled, then any application calls to
  123. * libusb_set_debug(), or the setting of the environmental variable
  124. * LIBUSB_DEBUG outside of the application, can result in logging being
  125. * produced. Your application should therefore not close stderr, but instead
  126. * direct it to the null device if its output is undesireable.
  127. *
  128. * The libusb_set_debug() function can be used to enable logging of certain
  129. * messages. Under standard configuration, libusbx doesn't really log much
  130. * so you are advised to use this function to enable all error/warning/
  131. * informational messages. It will help debug problems with your software.
  132. *
  133. * The logged messages are unstructured. There is no one-to-one correspondence
  134. * between messages being logged and success or failure return codes from
  135. * libusbx functions. There is no format to the messages, so you should not
  136. * try to capture or parse them. They are not and will not be localized.
  137. * These messages are not intended to being passed to your application user;
  138. * instead, you should interpret the error codes returned from libusbx functions
  139. * and provide appropriate notification to the user. The messages are simply
  140. * there to aid you as a programmer, and if you're confused because you're
  141. * getting a strange error code from a libusbx function, enabling message
  142. * logging may give you a suitable explanation.
  143. *
  144. * The LIBUSB_DEBUG environment variable can be used to enable message logging
  145. * at run-time. This environment variable should be set to a log level number,
  146. * which is interpreted the same as the libusb_set_debug() parameter. When this
  147. * environment variable is set, the message logging verbosity level is fixed
  148. * and libusb_set_debug() effectively does nothing.
  149. *
  150. * libusbx can be compiled without any logging functions, useful for embedded
  151. * systems. In this case, libusb_set_debug() and the LIBUSB_DEBUG environment
  152. * variable have no effects.
  153. *
  154. * libusbx can also be compiled with verbose debugging messages always. When
  155. * the library is compiled in this way, all messages of all verbosities are
  156. * always logged. libusb_set_debug() and the LIBUSB_DEBUG environment variable
  157. * have no effects.
  158. *
  159. * \section remarks Other remarks
  160. *
  161. * libusbx does have imperfections. The \ref caveats "caveats" page attempts
  162. * to document these.
  163. */
  164. /**
  165. * \page caveats Caveats
  166. *
  167. * \section devresets Device resets
  168. *
  169. * The libusb_reset_device() function allows you to reset a device. If your
  170. * program has to call such a function, it should obviously be aware that
  171. * the reset will cause device state to change (e.g. register values may be
  172. * reset).
  173. *
  174. * The problem is that any other program could reset the device your program
  175. * is working with, at any time. libusbx does not offer a mechanism to inform
  176. * you when this has happened, so if someone else resets your device it will
  177. * not be clear to your own program why the device state has changed.
  178. *
  179. * Ultimately, this is a limitation of writing drivers in userspace.
  180. * Separation from the USB stack in the underlying kernel makes it difficult
  181. * for the operating system to deliver such notifications to your program.
  182. * The Linux kernel USB stack allows such reset notifications to be delivered
  183. * to in-kernel USB drivers, but it is not clear how such notifications could
  184. * be delivered to second-class drivers that live in userspace.
  185. *
  186. * \section blockonly Blocking-only functionality
  187. *
  188. * The functionality listed below is only available through synchronous,
  189. * blocking functions. There are no asynchronous/non-blocking alternatives,
  190. * and no clear ways of implementing these.
  191. *
  192. * - Configuration activation (libusb_set_configuration())
  193. * - Interface/alternate setting activation (libusb_set_interface_alt_setting())
  194. * - Releasing of interfaces (libusb_release_interface())
  195. * - Clearing of halt/stall condition (libusb_clear_halt())
  196. * - Device resets (libusb_reset_device())
  197. *
  198. * \section configsel Configuration selection and handling
  199. *
  200. * When libusbx presents a device handle to an application, there is a chance
  201. * that the corresponding device may be in unconfigured state. For devices
  202. * with multiple configurations, there is also a chance that the configuration
  203. * currently selected is not the one that the application wants to use.
  204. *
  205. * The obvious solution is to add a call to libusb_set_configuration() early
  206. * on during your device initialization routines, but there are caveats to
  207. * be aware of:
  208. * -# If the device is already in the desired configuration, calling
  209. * libusb_set_configuration() using the same configuration value will cause
  210. * a lightweight device reset. This may not be desirable behaviour.
  211. * -# libusbx will be unable to change configuration if the device is in
  212. * another configuration and other programs or drivers have claimed
  213. * interfaces under that configuration.
  214. * -# In the case where the desired configuration is already active, libusbx
  215. * may not even be able to perform a lightweight device reset. For example,
  216. * take my USB keyboard with fingerprint reader: I'm interested in driving
  217. * the fingerprint reader interface through libusbx, but the kernel's
  218. * USB-HID driver will almost always have claimed the keyboard interface.
  219. * Because the kernel has claimed an interface, it is not even possible to
  220. * perform the lightweight device reset, so libusb_set_configuration() will
  221. * fail. (Luckily the device in question only has a single configuration.)
  222. *
  223. * One solution to some of the above problems is to consider the currently
  224. * active configuration. If the configuration we want is already active, then
  225. * we don't have to select any configuration:
  226. \code
  227. cfg = libusb_get_configuration(dev);
  228. if (cfg != desired)
  229. libusb_set_configuration(dev, desired);
  230. \endcode
  231. *
  232. * This is probably suitable for most scenarios, but is inherently racy:
  233. * another application or driver may change the selected configuration
  234. * <em>after</em> the libusb_get_configuration() call.
  235. *
  236. * Even in cases where libusb_set_configuration() succeeds, consider that other
  237. * applications or drivers may change configuration after your application
  238. * calls libusb_set_configuration().
  239. *
  240. * One possible way to lock your device into a specific configuration is as
  241. * follows:
  242. * -# Set the desired configuration (or use the logic above to realise that
  243. * it is already in the desired configuration)
  244. * -# Claim the interface that you wish to use
  245. * -# Check that the currently active configuration is the one that you want
  246. * to use.
  247. *
  248. * The above method works because once an interface is claimed, no application
  249. * or driver is able to select another configuration.
  250. *
  251. * \section earlycomp Early transfer completion
  252. *
  253. * NOTE: This section is currently Linux-centric. I am not sure if any of these
  254. * considerations apply to Darwin or other platforms.
  255. *
  256. * When a transfer completes early (i.e. when less data is received/sent in
  257. * any one packet than the transfer buffer allows for) then libusbx is designed
  258. * to terminate the transfer immediately, not transferring or receiving any
  259. * more data unless other transfers have been queued by the user.
  260. *
  261. * On legacy platforms, libusbx is unable to do this in all situations. After
  262. * the incomplete packet occurs, "surplus" data may be transferred. For recent
  263. * versions of libusbx, this information is kept (the data length of the
  264. * transfer is updated) and, for device-to-host transfers, any surplus data was
  265. * added to the buffer. Still, this is not a nice solution because it loses the
  266. * information about the end of the short packet, and the user probably wanted
  267. * that surplus data to arrive in the next logical transfer.
  268. *
  269. *
  270. * \section zlp Zero length packets
  271. *
  272. * - libusbx is able to send a packet of zero length to an endpoint simply by
  273. * submitting a transfer of zero length.
  274. * - The \ref libusb_transfer_flags::LIBUSB_TRANSFER_ADD_ZERO_PACKET
  275. * "LIBUSB_TRANSFER_ADD_ZERO_PACKET" flag is currently only supported on Linux.
  276. */
  277. /**
  278. * \page contexts Contexts
  279. *
  280. * It is possible that libusbx may be used simultaneously from two independent
  281. * libraries linked into the same executable. For example, if your application
  282. * has a plugin-like system which allows the user to dynamically load a range
  283. * of modules into your program, it is feasible that two independently
  284. * developed modules may both use libusbx.
  285. *
  286. * libusbx is written to allow for these multiple user scenarios. The two
  287. * "instances" of libusbx will not interfere: libusb_set_debug() calls
  288. * from one user will not affect the same settings for other users, other
  289. * users can continue using libusbx after one of them calls libusb_exit(), etc.
  290. *
  291. * This is made possible through libusbx's <em>context</em> concept. When you
  292. * call libusb_init(), you are (optionally) given a context. You can then pass
  293. * this context pointer back into future libusbx functions.
  294. *
  295. * In order to keep things simple for more simplistic applications, it is
  296. * legal to pass NULL to all functions requiring a context pointer (as long as
  297. * you're sure no other code will attempt to use libusbx from the same process).
  298. * When you pass NULL, the default context will be used. The default context
  299. * is created the first time a process calls libusb_init() when no other
  300. * context is alive. Contexts are destroyed during libusb_exit().
  301. *
  302. * The default context is reference-counted and can be shared. That means that
  303. * if libusb_init(NULL) is called twice within the same process, the two
  304. * users end up sharing the same context. The deinitialization and freeing of
  305. * the default context will only happen when the last user calls libusb_exit().
  306. * In other words, the default context is created and initialized when its
  307. * reference count goes from 0 to 1, and is deinitialized and destroyed when
  308. * its reference count goes from 1 to 0.
  309. *
  310. * You may be wondering why only a subset of libusbx functions require a
  311. * context pointer in their function definition. Internally, libusbx stores
  312. * context pointers in other objects (e.g. libusb_device instances) and hence
  313. * can infer the context from those objects.
  314. */
  315. /**
  316. * @defgroup lib Library initialization/deinitialization
  317. * This page details how to initialize and deinitialize libusbx. Initialization
  318. * must be performed before using any libusbx functionality, and similarly you
  319. * must not call any libusbx functions after deinitialization.
  320. */
  321. /**
  322. * @defgroup dev Device handling and enumeration
  323. * The functionality documented below is designed to help with the following
  324. * operations:
  325. * - Enumerating the USB devices currently attached to the system
  326. * - Choosing a device to operate from your software
  327. * - Opening and closing the chosen device
  328. *
  329. * \section nutshell In a nutshell...
  330. *
  331. * The description below really makes things sound more complicated than they
  332. * actually are. The following sequence of function calls will be suitable
  333. * for almost all scenarios and does not require you to have such a deep
  334. * understanding of the resource management issues:
  335. * \code
  336. // discover devices
  337. libusb_device **list;
  338. libusb_device *found = NULL;
  339. ssize_t cnt = libusb_get_device_list(NULL, &list);
  340. ssize_t i = 0;
  341. int err = 0;
  342. if (cnt < 0)
  343. error();
  344. for (i = 0; i < cnt; i++) {
  345. libusb_device *device = list[i];
  346. if (is_interesting(device)) {
  347. found = device;
  348. break;
  349. }
  350. }
  351. if (found) {
  352. libusb_device_handle *handle;
  353. err = libusb_open(found, &handle);
  354. if (err)
  355. error();
  356. // etc
  357. }
  358. libusb_free_device_list(list, 1);
  359. \endcode
  360. *
  361. * The two important points:
  362. * - You asked libusb_free_device_list() to unreference the devices (2nd
  363. * parameter)
  364. * - You opened the device before freeing the list and unreferencing the
  365. * devices
  366. *
  367. * If you ended up with a handle, you can now proceed to perform I/O on the
  368. * device.
  369. *
  370. * \section devshandles Devices and device handles
  371. * libusbx has a concept of a USB device, represented by the
  372. * \ref libusb_device opaque type. A device represents a USB device that
  373. * is currently or was previously connected to the system. Using a reference
  374. * to a device, you can determine certain information about the device (e.g.
  375. * you can read the descriptor data).
  376. *
  377. * The libusb_get_device_list() function can be used to obtain a list of
  378. * devices currently connected to the system. This is known as device
  379. * discovery.
  380. *
  381. * Just because you have a reference to a device does not mean it is
  382. * necessarily usable. The device may have been unplugged, you may not have
  383. * permission to operate such device, or another program or driver may be
  384. * using the device.
  385. *
  386. * When you've found a device that you'd like to operate, you must ask
  387. * libusbx to open the device using the libusb_open() function. Assuming
  388. * success, libusbx then returns you a <em>device handle</em>
  389. * (a \ref libusb_device_handle pointer). All "real" I/O operations then
  390. * operate on the handle rather than the original device pointer.
  391. *
  392. * \section devref Device discovery and reference counting
  393. *
  394. * Device discovery (i.e. calling libusb_get_device_list()) returns a
  395. * freshly-allocated list of devices. The list itself must be freed when
  396. * you are done with it. libusbx also needs to know when it is OK to free
  397. * the contents of the list - the devices themselves.
  398. *
  399. * To handle these issues, libusbx provides you with two separate items:
  400. * - A function to free the list itself
  401. * - A reference counting system for the devices inside
  402. *
  403. * New devices presented by the libusb_get_device_list() function all have a
  404. * reference count of 1. You can increase and decrease reference count using
  405. * libusb_ref_device() and libusb_unref_device(). A device is destroyed when
  406. * its reference count reaches 0.
  407. *
  408. * With the above information in mind, the process of opening a device can
  409. * be viewed as follows:
  410. * -# Discover devices using libusb_get_device_list().
  411. * -# Choose the device that you want to operate, and call libusb_open().
  412. * -# Unref all devices in the discovered device list.
  413. * -# Free the discovered device list.
  414. *
  415. * The order is important - you must not unreference the device before
  416. * attempting to open it, because unreferencing it may destroy the device.
  417. *
  418. * For convenience, the libusb_free_device_list() function includes a
  419. * parameter to optionally unreference all the devices in the list before
  420. * freeing the list itself. This combines steps 3 and 4 above.
  421. *
  422. * As an implementation detail, libusb_open() actually adds a reference to
  423. * the device in question. This is because the device remains available
  424. * through the handle via libusb_get_device(). The reference is deleted during
  425. * libusb_close().
  426. */
  427. /** @defgroup misc Miscellaneous */
  428. /* we traverse usbfs without knowing how many devices we are going to find.
  429. * so we create this discovered_devs model which is similar to a linked-list
  430. * which grows when required. it can be freed once discovery has completed,
  431. * eliminating the need for a list node in the libusb_device structure
  432. * itself. */
  433. #define DISCOVERED_DEVICES_SIZE_STEP 8
  434. static struct discovered_devs *discovered_devs_alloc(void)
  435. {
  436. struct discovered_devs *ret =
  437. malloc(sizeof(*ret) + (sizeof(void *) * DISCOVERED_DEVICES_SIZE_STEP));
  438. if (ret) {
  439. ret->len = 0;
  440. ret->capacity = DISCOVERED_DEVICES_SIZE_STEP;
  441. }
  442. return ret;
  443. }
  444. /* append a device to the discovered devices collection. may realloc itself,
  445. * returning new discdevs. returns NULL on realloc failure. */
  446. struct discovered_devs *discovered_devs_append(
  447. struct discovered_devs *discdevs, struct libusb_device *dev)
  448. {
  449. size_t len = discdevs->len;
  450. size_t capacity;
  451. /* if there is space, just append the device */
  452. if (len < discdevs->capacity) {
  453. discdevs->devices[len] = libusb_ref_device(dev);
  454. discdevs->len++;
  455. return discdevs;
  456. }
  457. /* exceeded capacity, need to grow */
  458. usbi_dbg("need to increase capacity");
  459. capacity = discdevs->capacity + DISCOVERED_DEVICES_SIZE_STEP;
  460. discdevs = usbi_reallocf(discdevs,
  461. sizeof(*discdevs) + (sizeof(void *) * capacity));
  462. if (discdevs) {
  463. discdevs->capacity = capacity;
  464. discdevs->devices[len] = libusb_ref_device(dev);
  465. discdevs->len++;
  466. }
  467. return discdevs;
  468. }
  469. static void discovered_devs_free(struct discovered_devs *discdevs)
  470. {
  471. size_t i;
  472. for (i = 0; i < discdevs->len; i++)
  473. libusb_unref_device(discdevs->devices[i]);
  474. free(discdevs);
  475. }
  476. /* Allocate a new device with a specific session ID. The returned device has
  477. * a reference count of 1. */
  478. struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
  479. unsigned long session_id)
  480. {
  481. size_t priv_size = usbi_backend->device_priv_size;
  482. struct libusb_device *dev = calloc(1, sizeof(*dev) + priv_size);
  483. int r;
  484. if (!dev)
  485. return NULL;
  486. r = usbi_mutex_init(&dev->lock, NULL);
  487. if (r) {
  488. free(dev);
  489. return NULL;
  490. }
  491. dev->ctx = ctx;
  492. dev->refcnt = 1;
  493. dev->session_data = session_id;
  494. dev->speed = LIBUSB_SPEED_UNKNOWN;
  495. if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
  496. usbi_connect_device (dev);
  497. }
  498. return dev;
  499. }
  500. void usbi_connect_device(struct libusb_device *dev)
  501. {
  502. libusb_hotplug_message message;
  503. ssize_t ret;
  504. memset(&message, 0, sizeof(message));
  505. message.event = LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED;
  506. message.device = dev;
  507. dev->attached = 1;
  508. usbi_mutex_lock(&dev->ctx->usb_devs_lock);
  509. list_add(&dev->list, &dev->ctx->usb_devs);
  510. usbi_mutex_unlock(&dev->ctx->usb_devs_lock);
  511. /* Signal that an event has occurred for this device if we support hotplug AND
  512. * the hotplug pipe is ready. This prevents an event from getting raised during
  513. * initial enumeration. */
  514. if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG) && dev->ctx->hotplug_pipe[1] > 0) {
  515. ret = usbi_write(dev->ctx->hotplug_pipe[1], &message, sizeof(message));
  516. if (sizeof (message) != ret) {
  517. usbi_err(DEVICE_CTX(dev), "error writing hotplug message");
  518. }
  519. }
  520. }
  521. void usbi_disconnect_device(struct libusb_device *dev)
  522. {
  523. libusb_hotplug_message message;
  524. struct libusb_context *ctx = dev->ctx;
  525. ssize_t ret;
  526. memset(&message, 0, sizeof(message));
  527. message.event = LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT;
  528. message.device = dev;
  529. usbi_mutex_lock(&dev->lock);
  530. dev->attached = 0;
  531. usbi_mutex_unlock(&dev->lock);
  532. usbi_mutex_lock(&ctx->usb_devs_lock);
  533. list_del(&dev->list);
  534. usbi_mutex_unlock(&ctx->usb_devs_lock);
  535. /* Signal that an event has occurred for this device if we support hotplug AND
  536. * the hotplug pipe is ready. This prevents an event from getting raised during
  537. * initial enumeration. libusb_handle_events will take care of dereferencing the
  538. * device. */
  539. if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG) && dev->ctx->hotplug_pipe[1] > 0) {
  540. ret = usbi_write(dev->ctx->hotplug_pipe[1], &message, sizeof(message));
  541. if (sizeof(message) != ret) {
  542. usbi_err(DEVICE_CTX(dev), "error writing hotplug message");
  543. }
  544. }
  545. }
  546. /* Perform some final sanity checks on a newly discovered device. If this
  547. * function fails (negative return code), the device should not be added
  548. * to the discovered device list. */
  549. int usbi_sanitize_device(struct libusb_device *dev)
  550. {
  551. int r;
  552. uint8_t num_configurations;
  553. r = usbi_device_cache_descriptor(dev);
  554. if (r < 0)
  555. return r;
  556. num_configurations = dev->device_descriptor.bNumConfigurations;
  557. if (num_configurations > USB_MAXCONFIG) {
  558. usbi_err(DEVICE_CTX(dev), "too many configurations");
  559. return LIBUSB_ERROR_IO;
  560. } else if (0 == num_configurations)
  561. usbi_dbg("zero configurations, maybe an unauthorized device");
  562. dev->num_configurations = num_configurations;
  563. return 0;
  564. }
  565. /* Examine libusbx's internal list of known devices, looking for one with
  566. * a specific session ID. Returns the matching device if it was found, and
  567. * NULL otherwise. */
  568. struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
  569. unsigned long session_id)
  570. {
  571. struct libusb_device *dev;
  572. struct libusb_device *ret = NULL;
  573. usbi_mutex_lock(&ctx->usb_devs_lock);
  574. list_for_each_entry(dev, &ctx->usb_devs, list, struct libusb_device)
  575. if (dev->session_data == session_id) {
  576. ret = dev;
  577. break;
  578. }
  579. usbi_mutex_unlock(&ctx->usb_devs_lock);
  580. return ret;
  581. }
  582. /** @ingroup dev
  583. * Returns a list of USB devices currently attached to the system. This is
  584. * your entry point into finding a USB device to operate.
  585. *
  586. * You are expected to unreference all the devices when you are done with
  587. * them, and then free the list with libusb_free_device_list(). Note that
  588. * libusb_free_device_list() can unref all the devices for you. Be careful
  589. * not to unreference a device you are about to open until after you have
  590. * opened it.
  591. *
  592. * This return value of this function indicates the number of devices in
  593. * the resultant list. The list is actually one element larger, as it is
  594. * NULL-terminated.
  595. *
  596. * \param ctx the context to operate on, or NULL for the default context
  597. * \param list output location for a list of devices. Must be later freed with
  598. * libusb_free_device_list().
  599. * \returns the number of devices in the outputted list, or any
  600. * \ref libusb_error according to errors encountered by the backend.
  601. */
  602. ssize_t API_EXPORTED libusb_get_device_list(libusb_context *ctx,
  603. libusb_device ***list)
  604. {
  605. struct discovered_devs *discdevs = discovered_devs_alloc();
  606. struct libusb_device **ret;
  607. int r = 0;
  608. ssize_t i, len;
  609. USBI_GET_CONTEXT(ctx);
  610. usbi_dbg("");
  611. if (!discdevs)
  612. return LIBUSB_ERROR_NO_MEM;
  613. if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
  614. /* backend provides hotplug support */
  615. struct libusb_device *dev;
  616. if (usbi_backend->hotplug_poll)
  617. usbi_backend->hotplug_poll();
  618. usbi_mutex_lock(&ctx->usb_devs_lock);
  619. list_for_each_entry(dev, &ctx->usb_devs, list, struct libusb_device) {
  620. discdevs = discovered_devs_append(discdevs, dev);
  621. if (!discdevs) {
  622. r = LIBUSB_ERROR_NO_MEM;
  623. break;
  624. }
  625. }
  626. usbi_mutex_unlock(&ctx->usb_devs_lock);
  627. } else {
  628. /* backend does not provide hotplug support */
  629. r = usbi_backend->get_device_list(ctx, &discdevs);
  630. }
  631. if (r < 0) {
  632. len = r;
  633. goto out;
  634. }
  635. /* convert discovered_devs into a list */
  636. len = discdevs->len;
  637. ret = calloc(len + 1, sizeof(struct libusb_device *));
  638. if (!ret) {
  639. len = LIBUSB_ERROR_NO_MEM;
  640. goto out;
  641. }
  642. ret[len] = NULL;
  643. for (i = 0; i < len; i++) {
  644. struct libusb_device *dev = discdevs->devices[i];
  645. ret[i] = libusb_ref_device(dev);
  646. }
  647. *list = ret;
  648. out:
  649. discovered_devs_free(discdevs);
  650. return len;
  651. }
  652. /** \ingroup dev
  653. * Frees a list of devices previously discovered using
  654. * libusb_get_device_list(). If the unref_devices parameter is set, the
  655. * reference count of each device in the list is decremented by 1.
  656. * \param list the list to free
  657. * \param unref_devices whether to unref the devices in the list
  658. */
  659. void API_EXPORTED libusb_free_device_list(libusb_device **list,
  660. int unref_devices)
  661. {
  662. if (!list)
  663. return;
  664. if (unref_devices) {
  665. int i = 0;
  666. struct libusb_device *dev;
  667. while ((dev = list[i++]) != NULL)
  668. libusb_unref_device(dev);
  669. }
  670. free(list);
  671. }
  672. /** \ingroup dev
  673. * Get the number of the bus that a device is connected to.
  674. * \param dev a device
  675. * \returns the bus number
  676. */
  677. uint8_t API_EXPORTED libusb_get_bus_number(libusb_device *dev)
  678. {
  679. return dev->bus_number;
  680. }
  681. /** \ingroup dev
  682. * Get the number of the port that a device is connected to.
  683. * Unless the OS does something funky, or you are hot-plugging USB extension cards,
  684. * the port number returned by this call is usually guaranteed to be uniquely tied
  685. * to a physical port, meaning that different devices plugged on the same physical
  686. * port should return the same port number.
  687. *
  688. * But outside of this, there is no guarantee that the port number returned by this
  689. * call will remain the same, or even match the order in which ports have been
  690. * numbered by the HUB/HCD manufacturer.
  691. *
  692. * \param dev a device
  693. * \returns the port number (0 if not available)
  694. */
  695. uint8_t API_EXPORTED libusb_get_port_number(libusb_device *dev)
  696. {
  697. return dev->port_number;
  698. }
  699. /** \ingroup dev
  700. * Get the list of all port numbers from root for the specified device
  701. *
  702. * Since version 1.0.16, \ref LIBUSBX_API_VERSION >= 0x01000102
  703. * \param dev a device
  704. * \param port_numbers the array that should contain the port numbers
  705. * \param port_numbers_len the maximum length of the array. As per the USB 3.0
  706. * specs, the current maximum limit for the depth is 7.
  707. * \returns the number of elements filled
  708. * \returns LIBUSB_ERROR_OVERFLOW if the array is too small
  709. */
  710. int API_EXPORTED libusb_get_port_numbers(libusb_device *dev,
  711. uint8_t* port_numbers, int port_numbers_len)
  712. {
  713. int i = port_numbers_len;
  714. while(dev) {
  715. // HCDs can be listed as devices and would have port #0
  716. // TODO: see how the other backends want to implement HCDs as parents
  717. if (dev->port_number == 0)
  718. break;
  719. i--;
  720. if (i < 0) {
  721. usbi_warn(DEVICE_CTX(dev),
  722. "port numbers array too small");
  723. return LIBUSB_ERROR_OVERFLOW;
  724. }
  725. port_numbers[i] = dev->port_number;
  726. dev = dev->parent_dev;
  727. }
  728. memmove(port_numbers, &port_numbers[i], port_numbers_len - i);
  729. return port_numbers_len - i;
  730. }
  731. /** \ingroup dev
  732. * Deprecated please use libusb_get_port_numbers instead.
  733. */
  734. int API_EXPORTED libusb_get_port_path(libusb_context *ctx, libusb_device *dev,
  735. uint8_t* port_numbers, uint8_t port_numbers_len)
  736. {
  737. UNUSED(ctx);
  738. return libusb_get_port_numbers(dev, port_numbers, port_numbers_len);
  739. }
  740. /** \ingroup dev
  741. * Get the the parent from the specified device.
  742. * \param dev a device
  743. * \returns the device parent or NULL if not available
  744. * You should issue a \ref libusb_get_device_list() before calling this
  745. * function and make sure that you only access the parent before issuing
  746. * \ref libusb_free_device_list(). The reason is that libusbx currently does
  747. * not maintain a permanent list of device instances, and therefore can
  748. * only guarantee that parents are fully instantiated within a
  749. * libusb_get_device_list() - libusb_free_device_list() block.
  750. */
  751. DEFAULT_VISIBILITY
  752. libusb_device * LIBUSB_CALL libusb_get_parent(libusb_device *dev)
  753. {
  754. return dev->parent_dev;
  755. }
  756. /** \ingroup dev
  757. * Get the address of the device on the bus it is connected to.
  758. * \param dev a device
  759. * \returns the device address
  760. */
  761. uint8_t API_EXPORTED libusb_get_device_address(libusb_device *dev)
  762. {
  763. return dev->device_address;
  764. }
  765. /** \ingroup dev
  766. * Get the negotiated connection speed for a device.
  767. * \param dev a device
  768. * \returns a \ref libusb_speed code, where LIBUSB_SPEED_UNKNOWN means that
  769. * the OS doesn't know or doesn't support returning the negotiated speed.
  770. */
  771. int API_EXPORTED libusb_get_device_speed(libusb_device *dev)
  772. {
  773. return dev->speed;
  774. }
  775. static const struct libusb_endpoint_descriptor *find_endpoint(
  776. struct libusb_config_descriptor *config, unsigned char endpoint)
  777. {
  778. int iface_idx;
  779. for (iface_idx = 0; iface_idx < config->bNumInterfaces; iface_idx++) {
  780. const struct libusb_interface *iface = &config->interface[iface_idx];
  781. int altsetting_idx;
  782. for (altsetting_idx = 0; altsetting_idx < iface->num_altsetting;
  783. altsetting_idx++) {
  784. const struct libusb_interface_descriptor *altsetting
  785. = &iface->altsetting[altsetting_idx];
  786. int ep_idx;
  787. for (ep_idx = 0; ep_idx < altsetting->bNumEndpoints; ep_idx++) {
  788. const struct libusb_endpoint_descriptor *ep =
  789. &altsetting->endpoint[ep_idx];
  790. if (ep->bEndpointAddress == endpoint)
  791. return ep;
  792. }
  793. }
  794. }
  795. return NULL;
  796. }
  797. /** \ingroup dev
  798. * Convenience function to retrieve the wMaxPacketSize value for a particular
  799. * endpoint in the active device configuration.
  800. *
  801. * This function was originally intended to be of assistance when setting up
  802. * isochronous transfers, but a design mistake resulted in this function
  803. * instead. It simply returns the wMaxPacketSize value without considering
  804. * its contents. If you're dealing with isochronous transfers, you probably
  805. * want libusb_get_max_iso_packet_size() instead.
  806. *
  807. * \param dev a device
  808. * \param endpoint address of the endpoint in question
  809. * \returns the wMaxPacketSize value
  810. * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
  811. * \returns LIBUSB_ERROR_OTHER on other failure
  812. */
  813. int API_EXPORTED libusb_get_max_packet_size(libusb_device *dev,
  814. unsigned char endpoint)
  815. {
  816. struct libusb_config_descriptor *config;
  817. const struct libusb_endpoint_descriptor *ep;
  818. int r;
  819. r = libusb_get_active_config_descriptor(dev, &config);
  820. if (r < 0) {
  821. usbi_err(DEVICE_CTX(dev),
  822. "could not retrieve active config descriptor");
  823. return LIBUSB_ERROR_OTHER;
  824. }
  825. ep = find_endpoint(config, endpoint);
  826. if (!ep)
  827. return LIBUSB_ERROR_NOT_FOUND;
  828. r = ep->wMaxPacketSize;
  829. libusb_free_config_descriptor(config);
  830. return r;
  831. }
  832. /** \ingroup dev
  833. * Calculate the maximum packet size which a specific endpoint is capable is
  834. * sending or receiving in the duration of 1 microframe
  835. *
  836. * Only the active configuration is examined. The calculation is based on the
  837. * wMaxPacketSize field in the endpoint descriptor as described in section
  838. * 9.6.6 in the USB 2.0 specifications.
  839. *
  840. * If acting on an isochronous or interrupt endpoint, this function will
  841. * multiply the value found in bits 0:10 by the number of transactions per
  842. * microframe (determined by bits 11:12). Otherwise, this function just
  843. * returns the numeric value found in bits 0:10.
  844. *
  845. * This function is useful for setting up isochronous transfers, for example
  846. * you might pass the return value from this function to
  847. * libusb_set_iso_packet_lengths() in order to set the length field of every
  848. * isochronous packet in a transfer.
  849. *
  850. * Since v1.0.3.
  851. *
  852. * \param dev a device
  853. * \param endpoint address of the endpoint in question
  854. * \returns the maximum packet size which can be sent/received on this endpoint
  855. * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
  856. * \returns LIBUSB_ERROR_OTHER on other failure
  857. */
  858. int API_EXPORTED libusb_get_max_iso_packet_size(libusb_device *dev,
  859. unsigned char endpoint)
  860. {
  861. struct libusb_config_descriptor *config;
  862. const struct libusb_endpoint_descriptor *ep;
  863. enum libusb_transfer_type ep_type;
  864. uint16_t val;
  865. int r;
  866. r = libusb_get_active_config_descriptor(dev, &config);
  867. if (r < 0) {
  868. usbi_err(DEVICE_CTX(dev),
  869. "could not retrieve active config descriptor");
  870. return LIBUSB_ERROR_OTHER;
  871. }
  872. ep = find_endpoint(config, endpoint);
  873. if (!ep)
  874. return LIBUSB_ERROR_NOT_FOUND;
  875. val = ep->wMaxPacketSize;
  876. ep_type = (enum libusb_transfer_type) (ep->bmAttributes & 0x3);
  877. libusb_free_config_descriptor(config);
  878. r = val & 0x07ff;
  879. if (ep_type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
  880. || ep_type == LIBUSB_TRANSFER_TYPE_INTERRUPT)
  881. r *= (1 + ((val >> 11) & 3));
  882. return r;
  883. }
  884. /** \ingroup dev
  885. * Increment the reference count of a device.
  886. * \param dev the device to reference
  887. * \returns the same device
  888. */
  889. DEFAULT_VISIBILITY
  890. libusb_device * LIBUSB_CALL libusb_ref_device(libusb_device *dev)
  891. {
  892. usbi_mutex_lock(&dev->lock);
  893. dev->refcnt++;
  894. usbi_mutex_unlock(&dev->lock);
  895. return dev;
  896. }
  897. /** \ingroup dev
  898. * Decrement the reference count of a device. If the decrement operation
  899. * causes the reference count to reach zero, the device shall be destroyed.
  900. * \param dev the device to unreference
  901. */
  902. void API_EXPORTED libusb_unref_device(libusb_device *dev)
  903. {
  904. int refcnt;
  905. if (!dev)
  906. return;
  907. usbi_mutex_lock(&dev->lock);
  908. refcnt = --dev->refcnt;
  909. usbi_mutex_unlock(&dev->lock);
  910. if (refcnt == 0) {
  911. usbi_dbg("destroy device %d.%d", dev->bus_number, dev->device_address);
  912. libusb_unref_device(dev->parent_dev);
  913. if (usbi_backend->destroy_device)
  914. usbi_backend->destroy_device(dev);
  915. if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
  916. /* backend does not support hotplug */
  917. usbi_disconnect_device(dev);
  918. }
  919. usbi_mutex_destroy(&dev->lock);
  920. free(dev);
  921. }
  922. }
  923. /*
  924. * Interrupt the iteration of the event handling thread, so that it picks
  925. * up the new fd.
  926. */
  927. void usbi_fd_notification(struct libusb_context *ctx)
  928. {
  929. unsigned char dummy = 1;
  930. ssize_t r;
  931. if (ctx == NULL)
  932. return;
  933. /* record that we are messing with poll fds */
  934. usbi_mutex_lock(&ctx->pollfd_modify_lock);
  935. ctx->pollfd_modify++;
  936. usbi_mutex_unlock(&ctx->pollfd_modify_lock);
  937. /* write some data on control pipe to interrupt event handlers */
  938. r = usbi_write(ctx->ctrl_pipe[1], &dummy, sizeof(dummy));
  939. if (r <= 0) {
  940. usbi_warn(ctx, "internal signalling write failed");
  941. usbi_mutex_lock(&ctx->pollfd_modify_lock);
  942. ctx->pollfd_modify--;
  943. usbi_mutex_unlock(&ctx->pollfd_modify_lock);
  944. return;
  945. }
  946. /* take event handling lock */
  947. libusb_lock_events(ctx);
  948. /* read the dummy data */
  949. r = usbi_read(ctx->ctrl_pipe[0], &dummy, sizeof(dummy));
  950. if (r <= 0)
  951. usbi_warn(ctx, "internal signalling read failed");
  952. /* we're done with modifying poll fds */
  953. usbi_mutex_lock(&ctx->pollfd_modify_lock);
  954. ctx->pollfd_modify--;
  955. usbi_mutex_unlock(&ctx->pollfd_modify_lock);
  956. /* Release event handling lock and wake up event waiters */
  957. libusb_unlock_events(ctx);
  958. }
  959. /** \ingroup dev
  960. * Open a device and obtain a device handle. A handle allows you to perform
  961. * I/O on the device in question.
  962. *
  963. * Internally, this function adds a reference to the device and makes it
  964. * available to you through libusb_get_device(). This reference is removed
  965. * during libusb_close().
  966. *
  967. * This is a non-blocking function; no requests are sent over the bus.
  968. *
  969. * \param dev the device to open
  970. * \param handle output location for the returned device handle pointer. Only
  971. * populated when the return code is 0.
  972. * \returns 0 on success
  973. * \returns LIBUSB_ERROR_NO_MEM on memory allocation failure
  974. * \returns LIBUSB_ERROR_ACCESS if the user has insufficient permissions
  975. * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
  976. * \returns another LIBUSB_ERROR code on other failure
  977. */
  978. int API_EXPORTED libusb_open(libusb_device *dev,
  979. libusb_device_handle **handle)
  980. {
  981. struct libusb_context *ctx = DEVICE_CTX(dev);
  982. struct libusb_device_handle *_handle;
  983. size_t priv_size = usbi_backend->device_handle_priv_size;
  984. int r;
  985. usbi_dbg("open %d.%d", dev->bus_number, dev->device_address);
  986. if (!dev->attached) {
  987. return LIBUSB_ERROR_NO_DEVICE;
  988. }
  989. _handle = malloc(sizeof(*_handle) + priv_size);
  990. if (!_handle)
  991. return LIBUSB_ERROR_NO_MEM;
  992. r = usbi_mutex_init(&_handle->lock, NULL);
  993. if (r) {
  994. free(_handle);
  995. return LIBUSB_ERROR_OTHER;
  996. }
  997. _handle->dev = libusb_ref_device(dev);
  998. _handle->auto_detach_kernel_driver = 0;
  999. _handle->claimed_interfaces = 0;
  1000. memset(&_handle->os_priv, 0, priv_size);
  1001. r = usbi_backend->open(_handle);
  1002. if (r < 0) {
  1003. usbi_dbg("open %d.%d returns %d", dev->bus_number, dev->device_address, r);
  1004. libusb_unref_device(dev);
  1005. usbi_mutex_destroy(&_handle->lock);
  1006. free(_handle);
  1007. return r;
  1008. }
  1009. usbi_mutex_lock(&ctx->open_devs_lock);
  1010. list_add(&_handle->list, &ctx->open_devs);
  1011. usbi_mutex_unlock(&ctx->open_devs_lock);
  1012. *handle = _handle;
  1013. /* At this point, we want to interrupt any existing event handlers so
  1014. * that they realise the addition of the new device's poll fd. One
  1015. * example when this is desirable is if the user is running a separate
  1016. * dedicated libusbx events handling thread, which is running with a long
  1017. * or infinite timeout. We want to interrupt that iteration of the loop,
  1018. * so that it picks up the new fd, and then continues. */
  1019. usbi_fd_notification(ctx);
  1020. return 0;
  1021. }
  1022. /** \ingroup dev
  1023. * Convenience function for finding a device with a particular
  1024. * <tt>idVendor</tt>/<tt>idProduct</tt> combination. This function is intended
  1025. * for those scenarios where you are using libusbx to knock up a quick test
  1026. * application - it allows you to avoid calling libusb_get_device_list() and
  1027. * worrying about traversing/freeing the list.
  1028. *
  1029. * This function has limitations and is hence not intended for use in real
  1030. * applications: if multiple devices have the same IDs it will only
  1031. * give you the first one, etc.
  1032. *
  1033. * \param ctx the context to operate on, or NULL for the default context
  1034. * \param vendor_id the idVendor value to search for
  1035. * \param product_id the idProduct value to search for
  1036. * \returns a handle for the first found device, or NULL on error or if the
  1037. * device could not be found. */
  1038. DEFAULT_VISIBILITY
  1039. libusb_device_handle * LIBUSB_CALL libusb_open_device_with_vid_pid(
  1040. libusb_context *ctx, uint16_t vendor_id, uint16_t product_id)
  1041. {
  1042. struct libusb_device **devs;
  1043. struct libusb_device *found = NULL;
  1044. struct libusb_device *dev;
  1045. struct libusb_device_handle *handle = NULL;
  1046. size_t i = 0;
  1047. int r;
  1048. if (libusb_get_device_list(ctx, &devs) < 0)
  1049. return NULL;
  1050. while ((dev = devs[i++]) != NULL) {
  1051. struct libusb_device_descriptor desc;
  1052. r = libusb_get_device_descriptor(dev, &desc);
  1053. if (r < 0)
  1054. goto out;
  1055. if (desc.idVendor == vendor_id && desc.idProduct == product_id) {
  1056. found = dev;
  1057. break;
  1058. }
  1059. }
  1060. if (found) {
  1061. r = libusb_open(found, &handle);
  1062. if (r < 0)
  1063. handle = NULL;
  1064. }
  1065. out:
  1066. libusb_free_device_list(devs, 1);
  1067. return handle;
  1068. }
  1069. static void do_close(struct libusb_context *ctx,
  1070. struct libusb_device_handle *dev_handle)
  1071. {
  1072. struct usbi_transfer *itransfer;
  1073. struct usbi_transfer *tmp;
  1074. libusb_lock_events(ctx);
  1075. /* remove any transfers in flight that are for this device */
  1076. usbi_mutex_lock(&ctx->flying_transfers_lock);
  1077. /* safe iteration because transfers may be being deleted */
  1078. list_for_each_entry_safe(itransfer, tmp, &ctx->flying_transfers, list, struct usbi_transfer) {
  1079. struct libusb_transfer *transfer =
  1080. USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1081. if (transfer->dev_handle != dev_handle)
  1082. continue;
  1083. if (!(itransfer->flags & USBI_TRANSFER_DEVICE_DISAPPEARED)) {
  1084. usbi_err(ctx, "Device handle closed while transfer was still being processed, but the device is still connected as far as we know");
  1085. if (itransfer->flags & USBI_TRANSFER_CANCELLING)
  1086. usbi_warn(ctx, "A cancellation for an in-flight transfer hasn't completed but closing the device handle");
  1087. else
  1088. usbi_err(ctx, "A cancellation hasn't even been scheduled on the transfer for which the device is closing");
  1089. }
  1090. /* remove from the list of in-flight transfers and make sure
  1091. * we don't accidentally use the device handle in the future
  1092. * (or that such accesses will be easily caught and identified as a crash)
  1093. */
  1094. usbi_mutex_lock(&itransfer->lock);
  1095. list_del(&itransfer->list);
  1096. transfer->dev_handle = NULL;
  1097. usbi_mutex_unlock(&itransfer->lock);
  1098. /* it is up to the user to free up the actual transfer struct. this is
  1099. * just making sure that we don't attempt to process the transfer after
  1100. * the device handle is invalid
  1101. */
  1102. usbi_dbg("Removed transfer %p from the in-flight list because device handle %p closed",
  1103. transfer, dev_handle);
  1104. }
  1105. usbi_mutex_unlock(&ctx->flying_transfers_lock);
  1106. libusb_unlock_events(ctx);
  1107. usbi_mutex_lock(&ctx->open_devs_lock);
  1108. list_del(&dev_handle->list);
  1109. usbi_mutex_unlock(&ctx->open_devs_lock);
  1110. usbi_backend->close(dev_handle);
  1111. libusb_unref_device(dev_handle->dev);
  1112. usbi_mutex_destroy(&dev_handle->lock);
  1113. free(dev_handle);
  1114. }
  1115. /** \ingroup dev
  1116. * Close a device handle. Should be called on all open handles before your
  1117. * application exits.
  1118. *
  1119. * Internally, this function destroys the reference that was added by
  1120. * libusb_open() on the given device.
  1121. *
  1122. * This is a non-blocking function; no requests are sent over the bus.
  1123. *
  1124. * \param dev_handle the handle to close
  1125. */
  1126. void API_EXPORTED libusb_close(libusb_device_handle *dev_handle)
  1127. {
  1128. struct libusb_context *ctx;
  1129. unsigned char dummy = 1;
  1130. ssize_t r;
  1131. if (!dev_handle)
  1132. return;
  1133. usbi_dbg("");
  1134. ctx = HANDLE_CTX(dev_handle);
  1135. /* Similarly to libusb_open(), we want to interrupt all event handlers
  1136. * at this point. More importantly, we want to perform the actual close of
  1137. * the device while holding the event handling lock (preventing any other
  1138. * thread from doing event handling) because we will be removing a file
  1139. * descriptor from the polling loop. */
  1140. /* record that we are messing with poll fds */
  1141. usbi_mutex_lock(&ctx->pollfd_modify_lock);
  1142. ctx->pollfd_modify++;
  1143. usbi_mutex_unlock(&ctx->pollfd_modify_lock);
  1144. /* write some data on control pipe to interrupt event handlers */
  1145. r = usbi_write(ctx->ctrl_pipe[1], &dummy, sizeof(dummy));
  1146. if (r <= 0) {
  1147. usbi_warn(ctx, "internal signalling write failed, closing anyway");
  1148. do_close(ctx, dev_handle);
  1149. usbi_mutex_lock(&ctx->pollfd_modify_lock);
  1150. ctx->pollfd_modify--;
  1151. usbi_mutex_unlock(&ctx->pollfd_modify_lock);
  1152. return;
  1153. }
  1154. /* take event handling lock */
  1155. libusb_lock_events(ctx);
  1156. /* read the dummy data */
  1157. r = usbi_read(ctx->ctrl_pipe[0], &dummy, sizeof(dummy));
  1158. if (r <= 0)
  1159. usbi_warn(ctx, "internal signalling read failed, closing anyway");
  1160. /* Close the device */
  1161. do_close(ctx, dev_handle);
  1162. /* we're done with modifying poll fds */
  1163. usbi_mutex_lock(&ctx->pollfd_modify_lock);
  1164. ctx->pollfd_modify--;
  1165. usbi_mutex_unlock(&ctx->pollfd_modify_lock);
  1166. /* Release event handling lock and wake up event waiters */
  1167. libusb_unlock_events(ctx);
  1168. }
  1169. /** \ingroup dev
  1170. * Get the underlying device for a handle. This function does not modify
  1171. * the reference count of the returned device, so do not feel compelled to
  1172. * unreference it when you are done.
  1173. * \param dev_handle a device handle
  1174. * \returns the underlying device
  1175. */
  1176. DEFAULT_VISIBILITY
  1177. libusb_device * LIBUSB_CALL libusb_get_device(libusb_device_handle *dev_handle)
  1178. {
  1179. return dev_handle->dev;
  1180. }
  1181. /** \ingroup dev
  1182. * Determine the bConfigurationValue of the currently active configuration.
  1183. *
  1184. * You could formulate your own control request to obtain this information,
  1185. * but this function has the advantage that it may be able to retrieve the
  1186. * information from operating system caches (no I/O involved).
  1187. *
  1188. * If the OS does not cache this information, then this function will block
  1189. * while a control transfer is submitted to retrieve the information.
  1190. *
  1191. * This function will return a value of 0 in the <tt>config</tt> output
  1192. * parameter if the device is in unconfigured state.
  1193. *
  1194. * \param dev a device handle
  1195. * \param config output location for the bConfigurationValue of the active
  1196. * configuration (only valid for return code 0)
  1197. * \returns 0 on success
  1198. * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
  1199. * \returns another LIBUSB_ERROR code on other failure
  1200. */
  1201. int API_EXPORTED libusb_get_configuration(libusb_device_handle *dev,
  1202. int *config)
  1203. {
  1204. int r = LIBUSB_ERROR_NOT_SUPPORTED;
  1205. usbi_dbg("");
  1206. if (usbi_backend->get_configuration)
  1207. r = usbi_backend->get_configuration(dev, config);
  1208. if (r == LIBUSB_ERROR_NOT_SUPPORTED) {
  1209. uint8_t tmp = 0;
  1210. usbi_dbg("falling back to control message");
  1211. r = libusb_control_transfer(dev, LIBUSB_ENDPOINT_IN,
  1212. LIBUSB_REQUEST_GET_CONFIGURATION, 0, 0, &tmp, 1, 1000);
  1213. if (r == 0) {
  1214. usbi_err(HANDLE_CTX(dev), "zero bytes returned in ctrl transfer?");
  1215. r = LIBUSB_ERROR_IO;
  1216. } else if (r == 1) {
  1217. r = 0;
  1218. *config = tmp;
  1219. } else {
  1220. usbi_dbg("control failed, error %d", r);
  1221. }
  1222. }
  1223. if (r == 0)
  1224. usbi_dbg("active config %d", *config);
  1225. return r;
  1226. }
  1227. /** \ingroup dev
  1228. * Set the active configuration for a device.
  1229. *
  1230. * The operating system may or may not have already set an active
  1231. * configuration on the device. It is up to your application to ensure the
  1232. * correct configuration is selected before you attempt to claim interfaces
  1233. * and perform other operations.
  1234. *
  1235. * If you call this function on a device already configured with the selected
  1236. * configuration, then this function will act as a lightweight device reset:
  1237. * it will issue a SET_CONFIGURATION request using the current configuration,
  1238. * causing most USB-related device state to be reset (altsetting reset to zero,
  1239. * endpoint halts cleared, toggles reset).
  1240. *
  1241. * You cannot change/reset configuration if your application has claimed
  1242. * interfaces. It is advised to set the desired configuration before claiming
  1243. * interfaces.
  1244. *
  1245. * Alternatively you can call libusb_release_interface() first. Note if you
  1246. * do things this way you must ensure that auto_detach_kernel_driver for
  1247. * <tt>dev</tt> is 0, otherwise the kernel driver will be re-attached when you
  1248. * release the interface(s).
  1249. *
  1250. * You cannot change/reset configuration if other applications or drivers have
  1251. * claimed interfaces.
  1252. *
  1253. * A configuration value of -1 will put the device in unconfigured state.
  1254. * The USB specifications state that a configuration value of 0 does this,
  1255. * however buggy devices exist which actually have a configuration 0.
  1256. *
  1257. * You should always use this function rather than formulating your own
  1258. * SET_CONFIGURATION control request. This is because the underlying operating
  1259. * system needs to know when such changes happen.
  1260. *
  1261. * This is a blocking function.
  1262. *
  1263. * \param dev a device handle
  1264. * \param configuration the bConfigurationValue of the configuration you
  1265. * wish to activate, or -1 if you wish to put the device in unconfigured state
  1266. * \returns 0 on success
  1267. * \returns LIBUSB_ERROR_NOT_FOUND if the requested configuration does not exist
  1268. * \returns LIBUSB_ERROR_BUSY if interfaces are currently claimed
  1269. * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
  1270. * \returns another LIBUSB_ERROR code on other failure
  1271. * \see libusb_set_auto_detach_kernel_driver()
  1272. */
  1273. int API_EXPORTED libusb_set_configuration(libusb_device_handle *dev,
  1274. int configuration)
  1275. {
  1276. usbi_dbg("configuration %d", configuration);
  1277. return usbi_backend->set_configuration(dev, configuration);
  1278. }
  1279. /** \ingroup dev
  1280. * Claim an interface on a given device handle. You must claim the interface
  1281. * you wish to use before you can perform I/O on any of its endpoints.
  1282. *
  1283. * It is legal to attempt to claim an already-claimed interface, in which
  1284. * case libusbx just returns 0 without doing anything.
  1285. *
  1286. * If auto_detach_kernel_driver is set to 1 for <tt>dev</tt>, the kernel driver
  1287. * will be detached if necessary, on failure the detach error is returned.
  1288. *
  1289. * Claiming of interfaces is a purely logical operation; it does not cause
  1290. * any requests to be sent over the bus. Interface claiming is used to
  1291. * instruct the underlying operating system that your application wishes
  1292. * to take ownership of the interface.
  1293. *
  1294. * This is a non-blocking function.
  1295. *
  1296. * \param dev a device handle
  1297. * \param interface_number the <tt>bInterfaceNumber</tt> of the interface you
  1298. * wish to claim
  1299. * \returns 0 on success
  1300. * \returns LIBUSB_ERROR_NOT_FOUND if the requested interface does not exist
  1301. * \returns LIBUSB_ERROR_BUSY if another program or driver has claimed the
  1302. * interface
  1303. * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
  1304. * \returns a LIBUSB_ERROR code on other failure
  1305. * \see libusb_set_auto_detach_kernel_driver()
  1306. */
  1307. int API_EXPORTED libusb_claim_interface(libusb_device_handle *dev,
  1308. int interface_number)
  1309. {
  1310. int r = 0;
  1311. usbi_dbg("interface %d", interface_number);
  1312. if (interface_number >= USB_MAXINTERFACES)
  1313. return LIBUSB_ERROR_INVALID_PARAM;
  1314. if (!dev->dev->attached)
  1315. return LIBUSB_ERROR_NO_DEVICE;
  1316. usbi_mutex_lock(&dev->lock);
  1317. if (dev->claimed_interfaces & (1 << interface_number))
  1318. goto out;
  1319. r = usbi_backend->claim_interface(dev, interface_number);
  1320. if (r == 0)
  1321. dev->claimed_interfaces |= 1 << interface_number;
  1322. out:
  1323. usbi_mutex_unlock(&dev->lock);
  1324. return r;
  1325. }
  1326. /** \ingroup dev
  1327. * Release an interface previously claimed with libusb_claim_interface(). You
  1328. * should release all claimed interfaces before closing a device handle.
  1329. *
  1330. * This is a blocking function. A SET_INTERFACE control request will be sent
  1331. * to the device, resetting interface state to the first alternate setting.
  1332. *
  1333. * If auto_detach_kernel_driver is set to 1 for <tt>dev</tt>, the kernel
  1334. * driver will be re-attached after releasing the interface.
  1335. *
  1336. * \param dev a device handle
  1337. * \param interface_number the <tt>bInterfaceNumber</tt> of the
  1338. * previously-claimed interface
  1339. * \returns 0 on success
  1340. * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed
  1341. * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
  1342. * \returns another LIBUSB_ERROR code on other failure
  1343. * \see libusb_set_auto_detach_kernel_driver()
  1344. */
  1345. int API_EXPORTED libusb_release_interface(libusb_device_handle *dev,
  1346. int interface_number)
  1347. {
  1348. int r;
  1349. usbi_dbg("interface %d", interface_number);
  1350. if (interface_number >= USB_MAXINTERFACES)
  1351. return LIBUSB_ERROR_INVALID_PARAM;
  1352. usbi_mutex_lock(&dev->lock);
  1353. if (!(dev->claimed_interfaces & (1 << interface_number))) {
  1354. r = LIBUSB_ERROR_NOT_FOUND;
  1355. goto out;
  1356. }
  1357. r = usbi_backend->release_interface(dev, interface_number);
  1358. if (r == 0)
  1359. dev->claimed_interfaces &= ~(1 << interface_number);
  1360. out:
  1361. usbi_mutex_unlock(&dev->lock);
  1362. return r;
  1363. }
  1364. /** \ingroup dev
  1365. * Activate an alternate setting for an interface. The interface must have
  1366. * been previously claimed with libusb_claim_interface().
  1367. *
  1368. * You should always use this function rather than formulating your own
  1369. * SET_INTERFACE control request. This is because the underlying operating
  1370. * system needs to know when such changes happen.
  1371. *
  1372. * This is a blocking function.
  1373. *
  1374. * \param dev a device handle
  1375. * \param interface_number the <tt>bInterfaceNumber</tt> of the
  1376. * previously-claimed interface
  1377. * \param alternate_setting the <tt>bAlternateSetting</tt> of the alternate
  1378. * setting to activate
  1379. * \returns 0 on success
  1380. * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed, or the
  1381. * requested alternate setting does not exist
  1382. * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
  1383. * \returns another LIBUSB_ERROR code on other failure
  1384. */
  1385. int API_EXPORTED libusb_set_interface_alt_setting(libusb_device_handle *dev,
  1386. int interface_number, int alternate_setting)
  1387. {
  1388. usbi_dbg("interface %d altsetting %d",
  1389. interface_number, alternate_setting);
  1390. if (interface_number >= USB_MAXINTERFACES)
  1391. return LIBUSB_ERROR_INVALID_PARAM;
  1392. usbi_mutex_lock(&dev->lock);
  1393. if (!dev->dev->attached) {
  1394. usbi_mutex_unlock(&dev->lock);
  1395. return LIBUSB_ERROR_NO_DEVICE;
  1396. }
  1397. if (!(dev->claimed_interfaces & (1 << interface_number))) {
  1398. usbi_mutex_unlock(&dev->lock);
  1399. return LIBUSB_ERROR_NOT_FOUND;
  1400. }
  1401. usbi_mutex_unlock(&dev->lock);
  1402. return usbi_backend->set_interface_altsetting(dev, interface_number,
  1403. alternate_setting);
  1404. }
  1405. /** \ingroup dev
  1406. * Clear the halt/stall condition for an endpoint. Endpoints with halt status
  1407. * are unable to receive or transmit data until the halt condition is stalled.
  1408. *
  1409. * You should cancel all pending transfers before attempting to clear the halt
  1410. * condition.
  1411. *
  1412. * This is a blocking function.
  1413. *
  1414. * \param dev a device handle
  1415. * \param endpoint the endpoint to clear halt status
  1416. * \returns 0 on success
  1417. * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
  1418. * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
  1419. * \returns another LIBUSB_ERROR code on other failure
  1420. */
  1421. int API_EXPORTED libusb_clear_halt(libusb_device_handle *dev,
  1422. unsigned char endpoint)
  1423. {
  1424. usbi_dbg("endpoint %x", endpoint);
  1425. if (!dev->dev->attached)
  1426. return LIBUSB_ERROR_NO_DEVICE;
  1427. return usbi_backend->clear_halt(dev, endpoint);
  1428. }
  1429. /** \ingroup dev
  1430. * Perform a USB port reset to reinitialize a device. The system will attempt
  1431. * to restore the previous configuration and alternate settings after the
  1432. * reset has completed.
  1433. *
  1434. * If the reset fails, the descriptors change, or the previous state cannot be
  1435. * restored, the device will appear to be disconnected and reconnected. This
  1436. * means that the device handle is no longer valid (you should close it) and
  1437. * rediscover the device. A return code of LIBUSB_ERROR_NOT_FOUND indicates
  1438. * when this is the case.
  1439. *
  1440. * This is a blocking function which usually incurs a noticeable delay.
  1441. *
  1442. * \param dev a handle of the device to reset
  1443. * \returns 0 on success
  1444. * \returns LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the
  1445. * device has been disconnected
  1446. * \returns another LIBUSB_ERROR code on other failure
  1447. */
  1448. int API_EXPORTED libusb_reset_device(libusb_device_handle *dev)
  1449. {
  1450. usbi_dbg("");
  1451. if (!dev->dev->attached)
  1452. return LIBUSB_ERROR_NO_DEVICE;
  1453. return usbi_backend->reset_device(dev);
  1454. }
  1455. /** \ingroup dev
  1456. * Determine if a kernel driver is active on an interface. If a kernel driver
  1457. * is active, you cannot claim the interface, and libusbx will be unable to
  1458. * perform I/O.
  1459. *
  1460. * This functionality is not available on Windows.
  1461. *
  1462. * \param dev a device handle
  1463. * \param interface_number the interface to check
  1464. * \returns 0 if no kernel driver is active
  1465. * \returns 1 if a kernel driver is active
  1466. * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
  1467. * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
  1468. * is not available
  1469. * \returns another LIBUSB_ERROR code on other failure
  1470. * \see libusb_detach_kernel_driver()
  1471. */
  1472. int API_EXPORTED libusb_kernel_driver_active(libusb_device_handle *dev,
  1473. int interface_number)
  1474. {
  1475. usbi_dbg("interface %d", interface_number);
  1476. if (!dev->dev->attached)
  1477. return LIBUSB_ERROR_NO_DEVICE;
  1478. if (usbi_backend->kernel_driver_active)
  1479. return usbi_backend->kernel_driver_active(dev, interface_number);
  1480. else
  1481. return LIBUSB_ERROR_NOT_SUPPORTED;
  1482. }
  1483. /** \ingroup dev
  1484. * Detach a kernel driver from an interface. If successful, you will then be
  1485. * able to claim the interface and perform I/O.
  1486. *
  1487. * This functionality is not available on Darwin or Windows.
  1488. *
  1489. * Note that libusbx itself also talks to the device through a special kernel
  1490. * driver, if this driver is already attached to the device, this call will
  1491. * not detach it and return LIBUSB_ERROR_NOT_FOUND.
  1492. *
  1493. * \param dev a device handle
  1494. * \param interface_number the interface to detach the driver from
  1495. * \returns 0 on success
  1496. * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
  1497. * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
  1498. * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
  1499. * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
  1500. * is not available
  1501. * \returns another LIBUSB_ERROR code on other failure
  1502. * \see libusb_kernel_driver_active()
  1503. */
  1504. int API_EXPORTED libusb_detach_kernel_driver(libusb_device_handle *dev,
  1505. int interface_number)
  1506. {
  1507. usbi_dbg("interface %d", interface_number);
  1508. if (!dev->dev->attached)
  1509. return LIBUSB_ERROR_NO_DEVICE;
  1510. if (usbi_backend->detach_kernel_driver)
  1511. return usbi_backend->detach_kernel_driver(dev, interface_number);
  1512. else
  1513. return LIBUSB_ERROR_NOT_SUPPORTED;
  1514. }
  1515. /** \ingroup dev
  1516. * Re-attach an interface's kernel driver, which was previously detached
  1517. * using libusb_detach_kernel_driver(). This call is only effective on
  1518. * Linux and returns LIBUSB_ERROR_NOT_SUPPORTED on all other platforms.
  1519. *
  1520. * This functionality is not available on Darwin or Windows.
  1521. *
  1522. * \param dev a device handle
  1523. * \param interface_number the interface to attach the driver from
  1524. * \returns 0 on success
  1525. * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active
  1526. * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist
  1527. * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
  1528. * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
  1529. * is not available
  1530. * \returns LIBUSB_ERROR_BUSY if the driver cannot be attached because the
  1531. * interface is claimed by a program or driver
  1532. * \returns another LIBUSB_ERROR code on other failure
  1533. * \see libusb_kernel_driver_active()
  1534. */
  1535. int API_EXPORTED libusb_attach_kernel_driver(libusb_device_handle *dev,
  1536. int interface_number)
  1537. {
  1538. usbi_dbg("interface %d", interface_number);
  1539. if (!dev->dev->attached)
  1540. return LIBUSB_ERROR_NO_DEVICE;
  1541. if (usbi_backend->attach_kernel_driver)
  1542. return usbi_backend->attach_kernel_driver(dev, interface_number);
  1543. else
  1544. return LIBUSB_ERROR_NOT_SUPPORTED;
  1545. }
  1546. /** \ingroup dev
  1547. * Enable/disable libusbx's automatic kernel driver detachment. When this is
  1548. * enabled libusbx will automatically detach the kernel driver on an interface
  1549. * when claiming the interface, and attach it when releasing the interface.
  1550. *
  1551. * Automatic kernel driver detachment is disabled on newly opened device
  1552. * handles by default.
  1553. *
  1554. * On platforms which do not have LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER
  1555. * this function will return LIBUSB_ERROR_NOT_SUPPORTED, and libusbx will
  1556. * continue as if this function was never called.
  1557. *
  1558. * \param dev a device handle
  1559. * \param enable whether to enable or disable auto kernel driver detachment
  1560. *
  1561. * \returns LIBUSB_SUCCESS on success
  1562. * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality
  1563. * is not available
  1564. * \see libusb_claim_interface()
  1565. * \see libusb_release_interface()
  1566. * \see libusb_set_configuration()
  1567. */
  1568. int API_EXPORTED libusb_set_auto_detach_kernel_driver(
  1569. libusb_device_handle *dev, int enable)
  1570. {
  1571. if (!(usbi_backend->caps & USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER))
  1572. return LIBUSB_ERROR_NOT_SUPPORTED;
  1573. dev->auto_detach_kernel_driver = enable;
  1574. return LIBUSB_SUCCESS;
  1575. }
  1576. /** \ingroup lib
  1577. * Set log message verbosity.
  1578. *
  1579. * The default level is LIBUSB_LOG_LEVEL_NONE, which means no messages are ever
  1580. * printed. If you choose to increase the message verbosity level, ensure
  1581. * that your application does not close the stdout/stderr file descriptors.
  1582. *
  1583. * You are advised to use level LIBUSB_LOG_LEVEL_WARNING. libusbx is conservative
  1584. * with its message logging and most of the time, will only log messages that
  1585. * explain error conditions and other oddities. This will help you debug
  1586. * your software.
  1587. *
  1588. * If the LIBUSB_DEBUG environment variable was set when libusbx was
  1589. * initialized, this function does nothing: the message verbosity is fixed
  1590. * to the value in the environment variable.
  1591. *
  1592. * If libusbx was compiled without any message logging, this function does
  1593. * nothing: you'll never get any messages.
  1594. *
  1595. * If libusbx was compiled with verbose debug message logging, this function
  1596. * does nothing: you'll always get messages from all levels.
  1597. *
  1598. * \param ctx the context to operate on, or NULL for the default context
  1599. * \param level debug level to set
  1600. */
  1601. void API_EXPORTED libusb_set_debug(libusb_context *ctx, int level)
  1602. {
  1603. USBI_GET_CONTEXT(ctx);
  1604. if (!ctx->debug_fixed)
  1605. ctx->debug = level;
  1606. }
  1607. /** \ingroup lib
  1608. * Initialize libusb. This function must be called before calling any other
  1609. * libusbx function.
  1610. *
  1611. * If you do not provide an output location for a context pointer, a default
  1612. * context will be created. If there was already a default context, it will
  1613. * be reused (and nothing will be initialized/reinitialized).
  1614. *
  1615. * \param context Optional output location for context pointer.
  1616. * Only valid on return code 0.
  1617. * \returns 0 on success, or a LIBUSB_ERROR code on failure
  1618. * \see contexts
  1619. */
  1620. int API_EXPORTED libusb_init(libusb_context **context)
  1621. {
  1622. struct libusb_device *dev, *next;
  1623. char *dbg = getenv("LIBUSB_DEBUG");
  1624. struct libusb_context *ctx;
  1625. static int first_init = 1;
  1626. int r = 0;
  1627. usbi_mutex_static_lock(&default_context_lock);
  1628. if (!timestamp_origin.tv_sec) {
  1629. usbi_gettimeofday(&timestamp_origin, NULL);
  1630. }
  1631. if (!context && usbi_default_context) {
  1632. usbi_dbg("reusing default context");
  1633. default_context_refcnt++;
  1634. usbi_mutex_static_unlock(&default_context_lock);
  1635. return 0;
  1636. }
  1637. ctx = calloc(1, sizeof(*ctx));
  1638. if (!ctx) {
  1639. r = LIBUSB_ERROR_NO_MEM;
  1640. goto err_unlock;
  1641. }
  1642. #ifdef ENABLE_DEBUG_LOGGING
  1643. ctx->debug = LIBUSB_LOG_LEVEL_DEBUG;
  1644. #endif
  1645. if (dbg) {
  1646. ctx->debug = atoi(dbg);
  1647. if (ctx->debug)
  1648. ctx->debug_fixed = 1;
  1649. }
  1650. /* default context should be initialized before calling usbi_dbg */
  1651. if (!usbi_default_context) {
  1652. usbi_default_context = ctx;
  1653. default_context_refcnt++;
  1654. usbi_dbg("created default context");
  1655. }
  1656. usbi_dbg("libusbx v%d.%d.%d.%d", libusb_version_internal.major, libusb_version_internal.minor,
  1657. libusb_version_internal.micro, libusb_version_internal.nano);
  1658. usbi_mutex_init(&ctx->usb_devs_lock, NULL);
  1659. usbi_mutex_init(&ctx->open_devs_lock, NULL);
  1660. usbi_mutex_init(&ctx->hotplug_cbs_lock, NULL);
  1661. list_init(&ctx->usb_devs);
  1662. list_init(&ctx->open_devs);
  1663. list_init(&ctx->hotplug_cbs);
  1664. usbi_mutex_static_lock(&active_contexts_lock);
  1665. if (first_init) {
  1666. first_init = 0;
  1667. list_init (&active_contexts_list);
  1668. }
  1669. list_add (&ctx->list, &active_contexts_list);
  1670. usbi_mutex_static_unlock(&active_contexts_lock);
  1671. if (usbi_backend->init) {
  1672. r = usbi_backend->init(ctx);
  1673. if (r)
  1674. goto err_free_ctx;
  1675. }
  1676. r = usbi_io_init(ctx);
  1677. if (r < 0)
  1678. goto err_backend_exit;
  1679. usbi_mutex_static_unlock(&default_context_lock);
  1680. if (context)
  1681. *context = ctx;
  1682. return 0;
  1683. err_backend_exit:
  1684. if (usbi_backend->exit)
  1685. usbi_backend->exit();
  1686. err_free_ctx:
  1687. if (ctx == usbi_default_context)
  1688. usbi_default_context = NULL;
  1689. usbi_mutex_static_lock(&active_contexts_lock);
  1690. list_del (&ctx->list);
  1691. usbi_mutex_static_unlock(&active_contexts_lock);
  1692. usbi_mutex_lock(&ctx->usb_devs_lock);
  1693. list_for_each_entry_safe(dev, next, &ctx->usb_devs, list, struct libusb_device) {
  1694. list_del(&dev->list);
  1695. libusb_unref_device(dev);
  1696. }
  1697. usbi_mutex_unlock(&ctx->usb_devs_lock);
  1698. usbi_mutex_destroy(&ctx->open_devs_lock);
  1699. usbi_mutex_destroy(&ctx->usb_devs_lock);
  1700. usbi_mutex_destroy(&ctx->hotplug_cbs_lock);
  1701. free(ctx);
  1702. err_unlock:
  1703. usbi_mutex_static_unlock(&default_context_lock);
  1704. return r;
  1705. }
  1706. /** \ingroup lib
  1707. * Deinitialize libusb. Should be called after closing all open devices and
  1708. * before your application terminates.
  1709. * \param ctx the context to deinitialize, or NULL for the default context
  1710. */
  1711. void API_EXPORTED libusb_exit(struct libusb_context *ctx)
  1712. {
  1713. struct libusb_device *dev, *next;
  1714. usbi_dbg("");
  1715. USBI_GET_CONTEXT(ctx);
  1716. /* if working with default context, only actually do the deinitialization
  1717. * if we're the last user */
  1718. usbi_mutex_static_lock(&default_context_lock);
  1719. if (ctx == usbi_default_context) {
  1720. if (--default_context_refcnt > 0) {
  1721. usbi_dbg("not destroying default context");
  1722. usbi_mutex_static_unlock(&default_context_lock);
  1723. return;
  1724. }
  1725. usbi_dbg("destroying default context");
  1726. usbi_default_context = NULL;
  1727. }
  1728. usbi_mutex_static_unlock(&default_context_lock);
  1729. usbi_mutex_static_lock(&active_contexts_lock);
  1730. list_del (&ctx->list);
  1731. usbi_mutex_static_unlock(&active_contexts_lock);
  1732. if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
  1733. usbi_hotplug_deregister_all(ctx);
  1734. usbi_mutex_lock(&ctx->usb_devs_lock);
  1735. list_for_each_entry_safe(dev, next, &ctx->usb_devs, list, struct libusb_device) {
  1736. list_del(&dev->list);
  1737. libusb_unref_device(dev);
  1738. }
  1739. usbi_mutex_unlock(&ctx->usb_devs_lock);
  1740. }
  1741. /* a few sanity checks. don't bother with locking because unless
  1742. * there is an application bug, nobody will be accessing these. */
  1743. if (!list_empty(&ctx->usb_devs))
  1744. usbi_warn(ctx, "some libusb_devices were leaked");
  1745. if (!list_empty(&ctx->open_devs))
  1746. usbi_warn(ctx, "application left some devices open");
  1747. usbi_io_exit(ctx);
  1748. if (usbi_backend->exit)
  1749. usbi_backend->exit();
  1750. usbi_mutex_destroy(&ctx->open_devs_lock);
  1751. usbi_mutex_destroy(&ctx->usb_devs_lock);
  1752. usbi_mutex_destroy(&ctx->hotplug_cbs_lock);
  1753. free(ctx);
  1754. }
  1755. /** \ingroup misc
  1756. * Check at runtime if the loaded library has a given capability.
  1757. * This call should be performed after \ref libusb_init(), to ensure the
  1758. * backend has updated its capability set.
  1759. *
  1760. * \param capability the \ref libusb_capability to check for
  1761. * \returns nonzero if the running library has the capability, 0 otherwise
  1762. */
  1763. int API_EXPORTED libusb_has_capability(uint32_t capability)
  1764. {
  1765. switch (capability) {
  1766. case LIBUSB_CAP_HAS_CAPABILITY:
  1767. return 1;
  1768. case LIBUSB_CAP_HAS_HOTPLUG:
  1769. return !(usbi_backend->get_device_list);
  1770. case LIBUSB_CAP_HAS_HID_ACCESS:
  1771. return (usbi_backend->caps & USBI_CAP_HAS_HID_ACCESS);
  1772. case LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER:
  1773. return (usbi_backend->caps & USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER);
  1774. }
  1775. return 0;
  1776. }
  1777. /* this is defined in libusbi.h if needed */
  1778. #ifdef LIBUSB_GETTIMEOFDAY_WIN32
  1779. /*
  1780. * gettimeofday
  1781. * Implementation according to:
  1782. * The Open Group Base Specifications Issue 6
  1783. * IEEE Std 1003.1, 2004 Edition
  1784. */
  1785. /*
  1786. * THIS SOFTWARE IS NOT COPYRIGHTED
  1787. *
  1788. * This source code is offered for use in the public domain. You may
  1789. * use, modify or distribute it freely.
  1790. *
  1791. * This code is distributed in the hope that it will be useful but
  1792. * WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY
  1793. * DISCLAIMED. This includes but is not limited to warranties of
  1794. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  1795. *
  1796. * Contributed by:
  1797. * Danny Smith <dannysmith@users.sourceforge.net>
  1798. */
  1799. /* Offset between 1/1/1601 and 1/1/1970 in 100 nanosec units */
  1800. #define _W32_FT_OFFSET (116444736000000000)
  1801. int usbi_gettimeofday(struct timeval *tp, void *tzp)
  1802. {
  1803. union {
  1804. unsigned __int64 ns100; /* Time since 1 Jan 1601, in 100ns units */
  1805. FILETIME ft;
  1806. } _now;
  1807. UNUSED(tzp);
  1808. if(tp) {
  1809. #if defined(OS_WINCE)
  1810. SYSTEMTIME st;
  1811. GetSystemTime(&st);
  1812. SystemTimeToFileTime(&st, &_now.ft);
  1813. #else
  1814. GetSystemTimeAsFileTime (&_now.ft);
  1815. #endif
  1816. tp->tv_usec=(long)((_now.ns100 / 10) % 1000000 );
  1817. tp->tv_sec= (long)((_now.ns100 - _W32_FT_OFFSET) / 10000000);
  1818. }
  1819. /* Always return 0 as per Open Group Base Specifications Issue 6.
  1820. Do not set errno on error. */
  1821. return 0;
  1822. }
  1823. #endif
  1824. static void usbi_log_str(struct libusb_context *ctx,
  1825. enum libusb_log_level level, const char * str)
  1826. {
  1827. #if defined(USE_SYSTEM_LOGGING_FACILITY)
  1828. #if defined(OS_WINDOWS) || defined(OS_WINCE)
  1829. /* Windows CE only supports the Unicode version of OutputDebugString. */
  1830. WCHAR wbuf[USBI_MAX_LOG_LEN];
  1831. MultiByteToWideChar(CP_UTF8, 0, str, -1, wbuf, sizeof(wbuf));
  1832. OutputDebugStringW(wbuf);
  1833. #elif defined(__ANDROID__)
  1834. int priority = ANDROID_LOG_UNKNOWN;
  1835. switch (level) {
  1836. case LIBUSB_LOG_LEVEL_INFO: priority = ANDROID_LOG_INFO; break;
  1837. case LIBUSB_LOG_LEVEL_WARNING: priority = ANDROID_LOG_WARN; break;
  1838. case LIBUSB_LOG_LEVEL_ERROR: priority = ANDROID_LOG_ERROR; break;
  1839. case LIBUSB_LOG_LEVEL_DEBUG: priority = ANDROID_LOG_DEBUG; break;
  1840. }
  1841. __android_log_write(priority, "libusb", str);
  1842. #elif defined(HAVE_SYSLOG_FUNC)
  1843. int syslog_level = LOG_INFO;
  1844. switch (level) {
  1845. case LIBUSB_LOG_LEVEL_INFO: syslog_level = LOG_INFO; break;
  1846. case LIBUSB_LOG_LEVEL_WARNING: syslog_level = LOG_WARNING; break;
  1847. case LIBUSB_LOG_LEVEL_ERROR: syslog_level = LOG_ERR; break;
  1848. case LIBUSB_LOG_LEVEL_DEBUG: syslog_level = LOG_DEBUG; break;
  1849. }
  1850. syslog(syslog_level, "%s", str);
  1851. #else /* All of gcc, Clang, XCode seem to use #warning */
  1852. #warning System logging is not supported on this platform. Logging to stderr will be used instead.
  1853. fputs(str, stderr);
  1854. #endif
  1855. #else
  1856. fputs(str, stderr);
  1857. #endif /* USE_SYSTEM_LOGGING_FACILITY */
  1858. UNUSED(ctx);
  1859. UNUSED(level);
  1860. }
  1861. void usbi_log_v(struct libusb_context *ctx, enum libusb_log_level level,
  1862. const char *function, const char *format, va_list args)
  1863. {
  1864. const char *prefix = "";
  1865. char buf[USBI_MAX_LOG_LEN];
  1866. struct timeval now;
  1867. int global_debug, header_len, text_len;
  1868. static int has_debug_header_been_displayed = 0;
  1869. #ifdef ENABLE_DEBUG_LOGGING
  1870. global_debug = 1;
  1871. UNUSED(ctx);
  1872. #else
  1873. USBI_GET_CONTEXT(ctx);
  1874. if (ctx == NULL)
  1875. return;
  1876. global_debug = (ctx->debug == LIBUSB_LOG_LEVEL_DEBUG);
  1877. if (!ctx->debug)
  1878. return;
  1879. if (level == LIBUSB_LOG_LEVEL_WARNING && ctx->debug < LIBUSB_LOG_LEVEL_WARNING)
  1880. return;
  1881. if (level == LIBUSB_LOG_LEVEL_INFO && ctx->debug < LIBUSB_LOG_LEVEL_INFO)
  1882. return;
  1883. if (level == LIBUSB_LOG_LEVEL_DEBUG && ctx->debug < LIBUSB_LOG_LEVEL_DEBUG)
  1884. return;
  1885. #endif
  1886. usbi_gettimeofday(&now, NULL);
  1887. if ((global_debug) && (!has_debug_header_been_displayed)) {
  1888. has_debug_header_been_displayed = 1;
  1889. usbi_log_str(ctx, LIBUSB_LOG_LEVEL_DEBUG, "[timestamp] [threadID] facility level [function call] <message>\n");
  1890. usbi_log_str(ctx, LIBUSB_LOG_LEVEL_DEBUG, "--------------------------------------------------------------------------------\n");
  1891. }
  1892. if (now.tv_usec < timestamp_origin.tv_usec) {
  1893. now.tv_sec--;
  1894. now.tv_usec += 1000000;
  1895. }
  1896. now.tv_sec -= timestamp_origin.tv_sec;
  1897. now.tv_usec -= timestamp_origin.tv_usec;
  1898. switch (level) {
  1899. case LIBUSB_LOG_LEVEL_INFO:
  1900. prefix = "info";
  1901. break;
  1902. case LIBUSB_LOG_LEVEL_WARNING:
  1903. prefix = "warning";
  1904. break;
  1905. case LIBUSB_LOG_LEVEL_ERROR:
  1906. prefix = "error";
  1907. break;
  1908. case LIBUSB_LOG_LEVEL_DEBUG:
  1909. prefix = "debug";
  1910. break;
  1911. case LIBUSB_LOG_LEVEL_NONE:
  1912. return;
  1913. default:
  1914. prefix = "unknown";
  1915. break;
  1916. }
  1917. if (global_debug) {
  1918. header_len = snprintf(buf, sizeof(buf),
  1919. "[%2d.%06d] [%08x] libusbx: %s [%s] ",
  1920. (int)now.tv_sec, (int)now.tv_usec, usbi_get_tid(), prefix, function);
  1921. } else {
  1922. header_len = snprintf(buf, sizeof(buf),
  1923. "libusbx: %s [%s] ", prefix, function);
  1924. }
  1925. if (header_len < 0 || (size_t)header_len >= sizeof(buf)) {
  1926. /* Somehow snprintf failed to write to the buffer,
  1927. * remove the header so something useful is output. */
  1928. header_len = 0;
  1929. }
  1930. /* Make sure buffer is NUL terminated */
  1931. buf[header_len] = '\0';
  1932. text_len = vsnprintf(buf + header_len, sizeof(buf) - header_len,
  1933. format, args);
  1934. if (text_len < 0 || text_len + (size_t)header_len >= sizeof(buf)) {
  1935. /* Truncated log output. On some platforms a -1 return value means
  1936. * that the output was truncated. */
  1937. text_len = sizeof(buf) - header_len;
  1938. }
  1939. if (header_len + text_len + sizeof(USBI_LOG_LINE_END) >= sizeof(buf)) {
  1940. /* Need to truncate the text slightly to fit on the terminator. */
  1941. text_len -= (header_len + text_len + sizeof(USBI_LOG_LINE_END)) - sizeof(buf);
  1942. }
  1943. strcpy(buf + header_len + text_len, USBI_LOG_LINE_END);
  1944. usbi_log_str(ctx, level, buf);
  1945. }
  1946. void usbi_log(struct libusb_context *ctx, enum libusb_log_level level,
  1947. const char *function, const char *format, ...)
  1948. {
  1949. va_list args;
  1950. va_start (args, format);
  1951. usbi_log_v(ctx, level, function, format, args);
  1952. va_end (args);
  1953. }
  1954. /** \ingroup misc
  1955. * Returns a constant NULL-terminated string with the ASCII name of a libusbx
  1956. * error or transfer status code. The caller must not free() the returned
  1957. * string.
  1958. *
  1959. * \param error_code The \ref libusb_error or libusb_transfer_status code to
  1960. * return the name of.
  1961. * \returns The error name, or the string **UNKNOWN** if the value of
  1962. * error_code is not a known error / status code.
  1963. */
  1964. DEFAULT_VISIBILITY const char * LIBUSB_CALL libusb_error_name(int error_code)
  1965. {
  1966. switch (error_code) {
  1967. case LIBUSB_ERROR_IO:
  1968. return "LIBUSB_ERROR_IO";
  1969. case LIBUSB_ERROR_INVALID_PARAM:
  1970. return "LIBUSB_ERROR_INVALID_PARAM";
  1971. case LIBUSB_ERROR_ACCESS:
  1972. return "LIBUSB_ERROR_ACCESS";
  1973. case LIBUSB_ERROR_NO_DEVICE:
  1974. return "LIBUSB_ERROR_NO_DEVICE";
  1975. case LIBUSB_ERROR_NOT_FOUND:
  1976. return "LIBUSB_ERROR_NOT_FOUND";
  1977. case LIBUSB_ERROR_BUSY:
  1978. return "LIBUSB_ERROR_BUSY";
  1979. case LIBUSB_ERROR_TIMEOUT:
  1980. return "LIBUSB_ERROR_TIMEOUT";
  1981. case LIBUSB_ERROR_OVERFLOW:
  1982. return "LIBUSB_ERROR_OVERFLOW";
  1983. case LIBUSB_ERROR_PIPE:
  1984. return "LIBUSB_ERROR_PIPE";
  1985. case LIBUSB_ERROR_INTERRUPTED:
  1986. return "LIBUSB_ERROR_INTERRUPTED";
  1987. case LIBUSB_ERROR_NO_MEM:
  1988. return "LIBUSB_ERROR_NO_MEM";
  1989. case LIBUSB_ERROR_NOT_SUPPORTED:
  1990. return "LIBUSB_ERROR_NOT_SUPPORTED";
  1991. case LIBUSB_ERROR_OTHER:
  1992. return "LIBUSB_ERROR_OTHER";
  1993. case LIBUSB_TRANSFER_ERROR:
  1994. return "LIBUSB_TRANSFER_ERROR";
  1995. case LIBUSB_TRANSFER_TIMED_OUT:
  1996. return "LIBUSB_TRANSFER_TIMED_OUT";
  1997. case LIBUSB_TRANSFER_CANCELLED:
  1998. return "LIBUSB_TRANSFER_CANCELLED";
  1999. case LIBUSB_TRANSFER_STALL:
  2000. return "LIBUSB_TRANSFER_STALL";
  2001. case LIBUSB_TRANSFER_NO_DEVICE:
  2002. return "LIBUSB_TRANSFER_NO_DEVICE";
  2003. case LIBUSB_TRANSFER_OVERFLOW:
  2004. return "LIBUSB_TRANSFER_OVERFLOW";
  2005. case 0:
  2006. return "LIBUSB_SUCCESS / LIBUSB_TRANSFER_COMPLETED";
  2007. default:
  2008. return "**UNKNOWN**";
  2009. }
  2010. }
  2011. /** \ingroup misc
  2012. * Returns a pointer to const struct libusb_version with the version
  2013. * (major, minor, micro, nano and rc) of the running library.
  2014. */
  2015. DEFAULT_VISIBILITY
  2016. const struct libusb_version * LIBUSB_CALL libusb_get_version(void)
  2017. {
  2018. return &libusb_version_internal;
  2019. }