io.c 94 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503
  1. /*
  2. * I/O functions for libusb
  3. * Copyright (C) 2007-2009 Daniel Drake <dsd@gentoo.org>
  4. * Copyright (c) 2001 Johannes Erdfelt <johannes@erdfelt.com>
  5. *
  6. * This library is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * This library is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with this library; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. #include <config.h>
  21. #include <errno.h>
  22. #include <signal.h>
  23. #include <stdint.h>
  24. #include <stdlib.h>
  25. #include <string.h>
  26. #include <time.h>
  27. #include <fcntl.h>
  28. #ifdef HAVE_SYS_TIME_H
  29. #include <sys/time.h>
  30. #endif
  31. #ifdef USBI_TIMERFD_AVAILABLE
  32. #include <sys/timerfd.h>
  33. #endif
  34. #include "libusbi.h"
  35. #include "hotplug.h"
  36. /**
  37. * \page io Synchronous and asynchronous device I/O
  38. *
  39. * \section intro Introduction
  40. *
  41. * If you're using libusb in your application, you're probably wanting to
  42. * perform I/O with devices - you want to perform USB data transfers.
  43. *
  44. * libusb offers two separate interfaces for device I/O. This page aims to
  45. * introduce the two in order to help you decide which one is more suitable
  46. * for your application. You can also choose to use both interfaces in your
  47. * application by considering each transfer on a case-by-case basis.
  48. *
  49. * Once you have read through the following discussion, you should consult the
  50. * detailed API documentation pages for the details:
  51. * - \ref syncio
  52. * - \ref asyncio
  53. *
  54. * \section theory Transfers at a logical level
  55. *
  56. * At a logical level, USB transfers typically happen in two parts. For
  57. * example, when reading data from a endpoint:
  58. * -# A request for data is sent to the device
  59. * -# Some time later, the incoming data is received by the host
  60. *
  61. * or when writing data to an endpoint:
  62. *
  63. * -# The data is sent to the device
  64. * -# Some time later, the host receives acknowledgement from the device that
  65. * the data has been transferred.
  66. *
  67. * There may be an indefinite delay between the two steps. Consider a
  68. * fictional USB input device with a button that the user can press. In order
  69. * to determine when the button is pressed, you would likely submit a request
  70. * to read data on a bulk or interrupt endpoint and wait for data to arrive.
  71. * Data will arrive when the button is pressed by the user, which is
  72. * potentially hours later.
  73. *
  74. * libusb offers both a synchronous and an asynchronous interface to performing
  75. * USB transfers. The main difference is that the synchronous interface
  76. * combines both steps indicated above into a single function call, whereas
  77. * the asynchronous interface separates them.
  78. *
  79. * \section sync The synchronous interface
  80. *
  81. * The synchronous I/O interface allows you to perform a USB transfer with
  82. * a single function call. When the function call returns, the transfer has
  83. * completed and you can parse the results.
  84. *
  85. * If you have used the libusb-0.1 before, this I/O style will seem familar to
  86. * you. libusb-0.1 only offered a synchronous interface.
  87. *
  88. * In our input device example, to read button presses you might write code
  89. * in the following style:
  90. \code
  91. unsigned char data[4];
  92. int actual_length;
  93. int r = libusb_bulk_transfer(handle, LIBUSB_ENDPOINT_IN, data, sizeof(data), &actual_length, 0);
  94. if (r == 0 && actual_length == sizeof(data)) {
  95. // results of the transaction can now be found in the data buffer
  96. // parse them here and report button press
  97. } else {
  98. error();
  99. }
  100. \endcode
  101. *
  102. * The main advantage of this model is simplicity: you did everything with
  103. * a single simple function call.
  104. *
  105. * However, this interface has its limitations. Your application will sleep
  106. * inside libusb_bulk_transfer() until the transaction has completed. If it
  107. * takes the user 3 hours to press the button, your application will be
  108. * sleeping for that long. Execution will be tied up inside the library -
  109. * the entire thread will be useless for that duration.
  110. *
  111. * Another issue is that by tieing up the thread with that single transaction
  112. * there is no possibility of performing I/O with multiple endpoints and/or
  113. * multiple devices simultaneously, unless you resort to creating one thread
  114. * per transaction.
  115. *
  116. * Additionally, there is no opportunity to cancel the transfer after the
  117. * request has been submitted.
  118. *
  119. * For details on how to use the synchronous API, see the
  120. * \ref syncio "synchronous I/O API documentation" pages.
  121. *
  122. * \section async The asynchronous interface
  123. *
  124. * Asynchronous I/O is the most significant new feature in libusb-1.0.
  125. * Although it is a more complex interface, it solves all the issues detailed
  126. * above.
  127. *
  128. * Instead of providing which functions that block until the I/O has complete,
  129. * libusb's asynchronous interface presents non-blocking functions which
  130. * begin a transfer and then return immediately. Your application passes a
  131. * callback function pointer to this non-blocking function, which libusb will
  132. * call with the results of the transaction when it has completed.
  133. *
  134. * Transfers which have been submitted through the non-blocking functions
  135. * can be cancelled with a separate function call.
  136. *
  137. * The non-blocking nature of this interface allows you to be simultaneously
  138. * performing I/O to multiple endpoints on multiple devices, without having
  139. * to use threads.
  140. *
  141. * This added flexibility does come with some complications though:
  142. * - In the interest of being a lightweight library, libusb does not create
  143. * threads and can only operate when your application is calling into it. Your
  144. * application must call into libusb from it's main loop when events are ready
  145. * to be handled, or you must use some other scheme to allow libusb to
  146. * undertake whatever work needs to be done.
  147. * - libusb also needs to be called into at certain fixed points in time in
  148. * order to accurately handle transfer timeouts.
  149. * - Memory handling becomes more complex. You cannot use stack memory unless
  150. * the function with that stack is guaranteed not to return until the transfer
  151. * callback has finished executing.
  152. * - You generally lose some linearity from your code flow because submitting
  153. * the transfer request is done in a separate function from where the transfer
  154. * results are handled. This becomes particularly obvious when you want to
  155. * submit a second transfer based on the results of an earlier transfer.
  156. *
  157. * Internally, libusb's synchronous interface is expressed in terms of function
  158. * calls to the asynchronous interface.
  159. *
  160. * For details on how to use the asynchronous API, see the
  161. * \ref asyncio "asynchronous I/O API" documentation pages.
  162. */
  163. /**
  164. * \page packetoverflow Packets and overflows
  165. *
  166. * \section packets Packet abstraction
  167. *
  168. * The USB specifications describe how data is transmitted in packets, with
  169. * constraints on packet size defined by endpoint descriptors. The host must
  170. * not send data payloads larger than the endpoint's maximum packet size.
  171. *
  172. * libusb and the underlying OS abstract out the packet concept, allowing you
  173. * to request transfers of any size. Internally, the request will be divided
  174. * up into correctly-sized packets. You do not have to be concerned with
  175. * packet sizes, but there is one exception when considering overflows.
  176. *
  177. * \section overflow Bulk/interrupt transfer overflows
  178. *
  179. * When requesting data on a bulk endpoint, libusb requires you to supply a
  180. * buffer and the maximum number of bytes of data that libusb can put in that
  181. * buffer. However, the size of the buffer is not communicated to the device -
  182. * the device is just asked to send any amount of data.
  183. *
  184. * There is no problem if the device sends an amount of data that is less than
  185. * or equal to the buffer size. libusb reports this condition to you through
  186. * the \ref libusb_transfer::actual_length "libusb_transfer.actual_length"
  187. * field.
  188. *
  189. * Problems may occur if the device attempts to send more data than can fit in
  190. * the buffer. libusb reports LIBUSB_TRANSFER_OVERFLOW for this condition but
  191. * other behaviour is largely undefined: actual_length may or may not be
  192. * accurate, the chunk of data that can fit in the buffer (before overflow)
  193. * may or may not have been transferred.
  194. *
  195. * Overflows are nasty, but can be avoided. Even though you were told to
  196. * ignore packets above, think about the lower level details: each transfer is
  197. * split into packets (typically small, with a maximum size of 512 bytes).
  198. * Overflows can only happen if the final packet in an incoming data transfer
  199. * is smaller than the actual packet that the device wants to transfer.
  200. * Therefore, you will never see an overflow if your transfer buffer size is a
  201. * multiple of the endpoint's packet size: the final packet will either
  202. * fill up completely or will be only partially filled.
  203. */
  204. /**
  205. * @defgroup asyncio Asynchronous device I/O
  206. *
  207. * This page details libusb's asynchronous (non-blocking) API for USB device
  208. * I/O. This interface is very powerful but is also quite complex - you will
  209. * need to read this page carefully to understand the necessary considerations
  210. * and issues surrounding use of this interface. Simplistic applications
  211. * may wish to consider the \ref syncio "synchronous I/O API" instead.
  212. *
  213. * The asynchronous interface is built around the idea of separating transfer
  214. * submission and handling of transfer completion (the synchronous model
  215. * combines both of these into one). There may be a long delay between
  216. * submission and completion, however the asynchronous submission function
  217. * is non-blocking so will return control to your application during that
  218. * potentially long delay.
  219. *
  220. * \section asyncabstraction Transfer abstraction
  221. *
  222. * For the asynchronous I/O, libusb implements the concept of a generic
  223. * transfer entity for all types of I/O (control, bulk, interrupt,
  224. * isochronous). The generic transfer object must be treated slightly
  225. * differently depending on which type of I/O you are performing with it.
  226. *
  227. * This is represented by the public libusb_transfer structure type.
  228. *
  229. * \section asynctrf Asynchronous transfers
  230. *
  231. * We can view asynchronous I/O as a 5 step process:
  232. * -# <b>Allocation</b>: allocate a libusb_transfer
  233. * -# <b>Filling</b>: populate the libusb_transfer instance with information
  234. * about the transfer you wish to perform
  235. * -# <b>Submission</b>: ask libusb to submit the transfer
  236. * -# <b>Completion handling</b>: examine transfer results in the
  237. * libusb_transfer structure
  238. * -# <b>Deallocation</b>: clean up resources
  239. *
  240. *
  241. * \subsection asyncalloc Allocation
  242. *
  243. * This step involves allocating memory for a USB transfer. This is the
  244. * generic transfer object mentioned above. At this stage, the transfer
  245. * is "blank" with no details about what type of I/O it will be used for.
  246. *
  247. * Allocation is done with the libusb_alloc_transfer() function. You must use
  248. * this function rather than allocating your own transfers.
  249. *
  250. * \subsection asyncfill Filling
  251. *
  252. * This step is where you take a previously allocated transfer and fill it
  253. * with information to determine the message type and direction, data buffer,
  254. * callback function, etc.
  255. *
  256. * You can either fill the required fields yourself or you can use the
  257. * helper functions: libusb_fill_control_transfer(), libusb_fill_bulk_transfer()
  258. * and libusb_fill_interrupt_transfer().
  259. *
  260. * \subsection asyncsubmit Submission
  261. *
  262. * When you have allocated a transfer and filled it, you can submit it using
  263. * libusb_submit_transfer(). This function returns immediately but can be
  264. * regarded as firing off the I/O request in the background.
  265. *
  266. * \subsection asynccomplete Completion handling
  267. *
  268. * After a transfer has been submitted, one of four things can happen to it:
  269. *
  270. * - The transfer completes (i.e. some data was transferred)
  271. * - The transfer has a timeout and the timeout expires before all data is
  272. * transferred
  273. * - The transfer fails due to an error
  274. * - The transfer is cancelled
  275. *
  276. * Each of these will cause the user-specified transfer callback function to
  277. * be invoked. It is up to the callback function to determine which of the
  278. * above actually happened and to act accordingly.
  279. *
  280. * The user-specified callback is passed a pointer to the libusb_transfer
  281. * structure which was used to setup and submit the transfer. At completion
  282. * time, libusb has populated this structure with results of the transfer:
  283. * success or failure reason, number of bytes of data transferred, etc. See
  284. * the libusb_transfer structure documentation for more information.
  285. *
  286. * \subsection Deallocation
  287. *
  288. * When a transfer has completed (i.e. the callback function has been invoked),
  289. * you are advised to free the transfer (unless you wish to resubmit it, see
  290. * below). Transfers are deallocated with libusb_free_transfer().
  291. *
  292. * It is undefined behaviour to free a transfer which has not completed.
  293. *
  294. * \section asyncresubmit Resubmission
  295. *
  296. * You may be wondering why allocation, filling, and submission are all
  297. * separated above where they could reasonably be combined into a single
  298. * operation.
  299. *
  300. * The reason for separation is to allow you to resubmit transfers without
  301. * having to allocate new ones every time. This is especially useful for
  302. * common situations dealing with interrupt endpoints - you allocate one
  303. * transfer, fill and submit it, and when it returns with results you just
  304. * resubmit it for the next interrupt.
  305. *
  306. * \section asynccancel Cancellation
  307. *
  308. * Another advantage of using the asynchronous interface is that you have
  309. * the ability to cancel transfers which have not yet completed. This is
  310. * done by calling the libusb_cancel_transfer() function.
  311. *
  312. * libusb_cancel_transfer() is asynchronous/non-blocking in itself. When the
  313. * cancellation actually completes, the transfer's callback function will
  314. * be invoked, and the callback function should check the transfer status to
  315. * determine that it was cancelled.
  316. *
  317. * Freeing the transfer after it has been cancelled but before cancellation
  318. * has completed will result in undefined behaviour.
  319. *
  320. * When a transfer is cancelled, some of the data may have been transferred.
  321. * libusb will communicate this to you in the transfer callback. Do not assume
  322. * that no data was transferred.
  323. *
  324. * \section bulk_overflows Overflows on device-to-host bulk/interrupt endpoints
  325. *
  326. * If your device does not have predictable transfer sizes (or it misbehaves),
  327. * your application may submit a request for data on an IN endpoint which is
  328. * smaller than the data that the device wishes to send. In some circumstances
  329. * this will cause an overflow, which is a nasty condition to deal with. See
  330. * the \ref packetoverflow page for discussion.
  331. *
  332. * \section asyncctrl Considerations for control transfers
  333. *
  334. * The <tt>libusb_transfer</tt> structure is generic and hence does not
  335. * include specific fields for the control-specific setup packet structure.
  336. *
  337. * In order to perform a control transfer, you must place the 8-byte setup
  338. * packet at the start of the data buffer. To simplify this, you could
  339. * cast the buffer pointer to type struct libusb_control_setup, or you can
  340. * use the helper function libusb_fill_control_setup().
  341. *
  342. * The wLength field placed in the setup packet must be the length you would
  343. * expect to be sent in the setup packet: the length of the payload that
  344. * follows (or the expected maximum number of bytes to receive). However,
  345. * the length field of the libusb_transfer object must be the length of
  346. * the data buffer - i.e. it should be wLength <em>plus</em> the size of
  347. * the setup packet (LIBUSB_CONTROL_SETUP_SIZE).
  348. *
  349. * If you use the helper functions, this is simplified for you:
  350. * -# Allocate a buffer of size LIBUSB_CONTROL_SETUP_SIZE plus the size of the
  351. * data you are sending/requesting.
  352. * -# Call libusb_fill_control_setup() on the data buffer, using the transfer
  353. * request size as the wLength value (i.e. do not include the extra space you
  354. * allocated for the control setup).
  355. * -# If this is a host-to-device transfer, place the data to be transferred
  356. * in the data buffer, starting at offset LIBUSB_CONTROL_SETUP_SIZE.
  357. * -# Call libusb_fill_control_transfer() to associate the data buffer with
  358. * the transfer (and to set the remaining details such as callback and timeout).
  359. * - Note that there is no parameter to set the length field of the transfer.
  360. * The length is automatically inferred from the wLength field of the setup
  361. * packet.
  362. * -# Submit the transfer.
  363. *
  364. * The multi-byte control setup fields (wValue, wIndex and wLength) must
  365. * be given in little-endian byte order (the endianness of the USB bus).
  366. * Endianness conversion is transparently handled by
  367. * libusb_fill_control_setup() which is documented to accept host-endian
  368. * values.
  369. *
  370. * Further considerations are needed when handling transfer completion in
  371. * your callback function:
  372. * - As you might expect, the setup packet will still be sitting at the start
  373. * of the data buffer.
  374. * - If this was a device-to-host transfer, the received data will be sitting
  375. * at offset LIBUSB_CONTROL_SETUP_SIZE into the buffer.
  376. * - The actual_length field of the transfer structure is relative to the
  377. * wLength of the setup packet, rather than the size of the data buffer. So,
  378. * if your wLength was 4, your transfer's <tt>length</tt> was 12, then you
  379. * should expect an <tt>actual_length</tt> of 4 to indicate that the data was
  380. * transferred in entirity.
  381. *
  382. * To simplify parsing of setup packets and obtaining the data from the
  383. * correct offset, you may wish to use the libusb_control_transfer_get_data()
  384. * and libusb_control_transfer_get_setup() functions within your transfer
  385. * callback.
  386. *
  387. * Even though control endpoints do not halt, a completed control transfer
  388. * may have a LIBUSB_TRANSFER_STALL status code. This indicates the control
  389. * request was not supported.
  390. *
  391. * \section asyncintr Considerations for interrupt transfers
  392. *
  393. * All interrupt transfers are performed using the polling interval presented
  394. * by the bInterval value of the endpoint descriptor.
  395. *
  396. * \section asynciso Considerations for isochronous transfers
  397. *
  398. * Isochronous transfers are more complicated than transfers to
  399. * non-isochronous endpoints.
  400. *
  401. * To perform I/O to an isochronous endpoint, allocate the transfer by calling
  402. * libusb_alloc_transfer() with an appropriate number of isochronous packets.
  403. *
  404. * During filling, set \ref libusb_transfer::type "type" to
  405. * \ref libusb_transfer_type::LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
  406. * "LIBUSB_TRANSFER_TYPE_ISOCHRONOUS", and set
  407. * \ref libusb_transfer::num_iso_packets "num_iso_packets" to a value less than
  408. * or equal to the number of packets you requested during allocation.
  409. * libusb_alloc_transfer() does not set either of these fields for you, given
  410. * that you might not even use the transfer on an isochronous endpoint.
  411. *
  412. * Next, populate the length field for the first num_iso_packets entries in
  413. * the \ref libusb_transfer::iso_packet_desc "iso_packet_desc" array. Section
  414. * 5.6.3 of the USB2 specifications describe how the maximum isochronous
  415. * packet length is determined by the wMaxPacketSize field in the endpoint
  416. * descriptor.
  417. * Two functions can help you here:
  418. *
  419. * - libusb_get_max_iso_packet_size() is an easy way to determine the max
  420. * packet size for an isochronous endpoint. Note that the maximum packet
  421. * size is actually the maximum number of bytes that can be transmitted in
  422. * a single microframe, therefore this function multiplies the maximum number
  423. * of bytes per transaction by the number of transaction opportunities per
  424. * microframe.
  425. * - libusb_set_iso_packet_lengths() assigns the same length to all packets
  426. * within a transfer, which is usually what you want.
  427. *
  428. * For outgoing transfers, you'll obviously fill the buffer and populate the
  429. * packet descriptors in hope that all the data gets transferred. For incoming
  430. * transfers, you must ensure the buffer has sufficient capacity for
  431. * the situation where all packets transfer the full amount of requested data.
  432. *
  433. * Completion handling requires some extra consideration. The
  434. * \ref libusb_transfer::actual_length "actual_length" field of the transfer
  435. * is meaningless and should not be examined; instead you must refer to the
  436. * \ref libusb_iso_packet_descriptor::actual_length "actual_length" field of
  437. * each individual packet.
  438. *
  439. * The \ref libusb_transfer::status "status" field of the transfer is also a
  440. * little misleading:
  441. * - If the packets were submitted and the isochronous data microframes
  442. * completed normally, status will have value
  443. * \ref libusb_transfer_status::LIBUSB_TRANSFER_COMPLETED
  444. * "LIBUSB_TRANSFER_COMPLETED". Note that bus errors and software-incurred
  445. * delays are not counted as transfer errors; the transfer.status field may
  446. * indicate COMPLETED even if some or all of the packets failed. Refer to
  447. * the \ref libusb_iso_packet_descriptor::status "status" field of each
  448. * individual packet to determine packet failures.
  449. * - The status field will have value
  450. * \ref libusb_transfer_status::LIBUSB_TRANSFER_ERROR
  451. * "LIBUSB_TRANSFER_ERROR" only when serious errors were encountered.
  452. * - Other transfer status codes occur with normal behaviour.
  453. *
  454. * The data for each packet will be found at an offset into the buffer that
  455. * can be calculated as if each prior packet completed in full. The
  456. * libusb_get_iso_packet_buffer() and libusb_get_iso_packet_buffer_simple()
  457. * functions may help you here.
  458. *
  459. * \section asyncmem Memory caveats
  460. *
  461. * In most circumstances, it is not safe to use stack memory for transfer
  462. * buffers. This is because the function that fired off the asynchronous
  463. * transfer may return before libusb has finished using the buffer, and when
  464. * the function returns it's stack gets destroyed. This is true for both
  465. * host-to-device and device-to-host transfers.
  466. *
  467. * The only case in which it is safe to use stack memory is where you can
  468. * guarantee that the function owning the stack space for the buffer does not
  469. * return until after the transfer's callback function has completed. In every
  470. * other case, you need to use heap memory instead.
  471. *
  472. * \section asyncflags Fine control
  473. *
  474. * Through using this asynchronous interface, you may find yourself repeating
  475. * a few simple operations many times. You can apply a bitwise OR of certain
  476. * flags to a transfer to simplify certain things:
  477. * - \ref libusb_transfer_flags::LIBUSB_TRANSFER_SHORT_NOT_OK
  478. * "LIBUSB_TRANSFER_SHORT_NOT_OK" results in transfers which transferred
  479. * less than the requested amount of data being marked with status
  480. * \ref libusb_transfer_status::LIBUSB_TRANSFER_ERROR "LIBUSB_TRANSFER_ERROR"
  481. * (they would normally be regarded as COMPLETED)
  482. * - \ref libusb_transfer_flags::LIBUSB_TRANSFER_FREE_BUFFER
  483. * "LIBUSB_TRANSFER_FREE_BUFFER" allows you to ask libusb to free the transfer
  484. * buffer when freeing the transfer.
  485. * - \ref libusb_transfer_flags::LIBUSB_TRANSFER_FREE_TRANSFER
  486. * "LIBUSB_TRANSFER_FREE_TRANSFER" causes libusb to automatically free the
  487. * transfer after the transfer callback returns.
  488. *
  489. * \section asyncevent Event handling
  490. *
  491. * In accordance of the aim of being a lightweight library, libusb does not
  492. * create threads internally. This means that libusb code does not execute
  493. * at any time other than when your application is calling a libusb function.
  494. * However, an asynchronous model requires that libusb perform work at various
  495. * points in time - namely processing the results of previously-submitted
  496. * transfers and invoking the user-supplied callback function.
  497. *
  498. * This gives rise to the libusb_handle_events() function which your
  499. * application must call into when libusb has work do to. This gives libusb
  500. * the opportunity to reap pending transfers, invoke callbacks, etc.
  501. *
  502. * The first issue to discuss here is how your application can figure out
  503. * when libusb has work to do. In fact, there are two naive options which
  504. * do not actually require your application to know this:
  505. * -# Periodically call libusb_handle_events() in non-blocking mode at fixed
  506. * short intervals from your main loop
  507. * -# Repeatedly call libusb_handle_events() in blocking mode from a dedicated
  508. * thread.
  509. *
  510. * The first option is plainly not very nice, and will cause unnecessary
  511. * CPU wakeups leading to increased power usage and decreased battery life.
  512. * The second option is not very nice either, but may be the nicest option
  513. * available to you if the "proper" approach can not be applied to your
  514. * application (read on...).
  515. *
  516. * The recommended option is to integrate libusb with your application main
  517. * event loop. libusb exposes a set of file descriptors which allow you to do
  518. * this. Your main loop is probably already calling poll() or select() or a
  519. * variant on a set of file descriptors for other event sources (e.g. keyboard
  520. * button presses, mouse movements, network sockets, etc). You then add
  521. * libusb's file descriptors to your poll()/select() calls, and when activity
  522. * is detected on such descriptors you know it is time to call
  523. * libusb_handle_events().
  524. *
  525. * There is one final event handling complication. libusb supports
  526. * asynchronous transfers which time out after a specified time period, and
  527. * this requires that libusb is called into at or after the timeout so that
  528. * the timeout can be handled. So, in addition to considering libusb's file
  529. * descriptors in your main event loop, you must also consider that libusb
  530. * sometimes needs to be called into at fixed points in time even when there
  531. * is no file descriptor activity.
  532. *
  533. * For the details on retrieving the set of file descriptors and determining
  534. * the next timeout, see the \ref poll "polling and timing" API documentation.
  535. */
  536. /**
  537. * @defgroup poll Polling and timing
  538. *
  539. * This page documents libusb's functions for polling events and timing.
  540. * These functions are only necessary for users of the
  541. * \ref asyncio "asynchronous API". If you are only using the simpler
  542. * \ref syncio "synchronous API" then you do not need to ever call these
  543. * functions.
  544. *
  545. * The justification for the functionality described here has already been
  546. * discussed in the \ref asyncevent "event handling" section of the
  547. * asynchronous API documentation. In summary, libusb does not create internal
  548. * threads for event processing and hence relies on your application calling
  549. * into libusb at certain points in time so that pending events can be handled.
  550. * In order to know precisely when libusb needs to be called into, libusb
  551. * offers you a set of pollable file descriptors and information about when
  552. * the next timeout expires.
  553. *
  554. * If you are using the asynchronous I/O API, you must take one of the two
  555. * following options, otherwise your I/O will not complete.
  556. *
  557. * \section pollsimple The simple option
  558. *
  559. * If your application revolves solely around libusb and does not need to
  560. * handle other event sources, you can have a program structure as follows:
  561. \code
  562. // initialize libusb
  563. // find and open device
  564. // maybe fire off some initial async I/O
  565. while (user_has_not_requested_exit)
  566. libusb_handle_events(ctx);
  567. // clean up and exit
  568. \endcode
  569. *
  570. * With such a simple main loop, you do not have to worry about managing
  571. * sets of file descriptors or handling timeouts. libusb_handle_events() will
  572. * handle those details internally.
  573. *
  574. * \section pollmain The more advanced option
  575. *
  576. * \note This functionality is currently only available on Unix-like platforms.
  577. * On Windows, libusb_get_pollfds() simply returns NULL. Exposing event sources
  578. * on Windows will require some further thought and design.
  579. *
  580. * In more advanced applications, you will already have a main loop which
  581. * is monitoring other event sources: network sockets, X11 events, mouse
  582. * movements, etc. Through exposing a set of file descriptors, libusb is
  583. * designed to cleanly integrate into such main loops.
  584. *
  585. * In addition to polling file descriptors for the other event sources, you
  586. * take a set of file descriptors from libusb and monitor those too. When you
  587. * detect activity on libusb's file descriptors, you call
  588. * libusb_handle_events_timeout() in non-blocking mode.
  589. *
  590. * What's more, libusb may also need to handle events at specific moments in
  591. * time. No file descriptor activity is generated at these times, so your
  592. * own application needs to be continually aware of when the next one of these
  593. * moments occurs (through calling libusb_get_next_timeout()), and then it
  594. * needs to call libusb_handle_events_timeout() in non-blocking mode when
  595. * these moments occur. This means that you need to adjust your
  596. * poll()/select() timeout accordingly.
  597. *
  598. * libusb provides you with a set of file descriptors to poll and expects you
  599. * to poll all of them, treating them as a single entity. The meaning of each
  600. * file descriptor in the set is an internal implementation detail,
  601. * platform-dependent and may vary from release to release. Don't try and
  602. * interpret the meaning of the file descriptors, just do as libusb indicates,
  603. * polling all of them at once.
  604. *
  605. * In pseudo-code, you want something that looks like:
  606. \code
  607. // initialise libusb
  608. libusb_get_pollfds(ctx)
  609. while (user has not requested application exit) {
  610. libusb_get_next_timeout(ctx);
  611. poll(on libusb file descriptors plus any other event sources of interest,
  612. using a timeout no larger than the value libusb just suggested)
  613. if (poll() indicated activity on libusb file descriptors)
  614. libusb_handle_events_timeout(ctx, &zero_tv);
  615. if (time has elapsed to or beyond the libusb timeout)
  616. libusb_handle_events_timeout(ctx, &zero_tv);
  617. // handle events from other sources here
  618. }
  619. // clean up and exit
  620. \endcode
  621. *
  622. * \subsection polltime Notes on time-based events
  623. *
  624. * The above complication with having to track time and call into libusb at
  625. * specific moments is a bit of a headache. For maximum compatibility, you do
  626. * need to write your main loop as above, but you may decide that you can
  627. * restrict the supported platforms of your application and get away with
  628. * a more simplistic scheme.
  629. *
  630. * These time-based event complications are \b not required on the following
  631. * platforms:
  632. * - Darwin
  633. * - Linux, provided that the following version requirements are satisfied:
  634. * - Linux v2.6.27 or newer, compiled with timerfd support
  635. * - glibc v2.9 or newer
  636. * - libusb v1.0.5 or newer
  637. *
  638. * Under these configurations, libusb_get_next_timeout() will \em always return
  639. * 0, so your main loop can be simplified to:
  640. \code
  641. // initialise libusb
  642. libusb_get_pollfds(ctx)
  643. while (user has not requested application exit) {
  644. poll(on libusb file descriptors plus any other event sources of interest,
  645. using any timeout that you like)
  646. if (poll() indicated activity on libusb file descriptors)
  647. libusb_handle_events_timeout(ctx, &zero_tv);
  648. // handle events from other sources here
  649. }
  650. // clean up and exit
  651. \endcode
  652. *
  653. * Do remember that if you simplify your main loop to the above, you will
  654. * lose compatibility with some platforms (including legacy Linux platforms,
  655. * and <em>any future platforms supported by libusb which may have time-based
  656. * event requirements</em>). The resultant problems will likely appear as
  657. * strange bugs in your application.
  658. *
  659. * You can use the libusb_pollfds_handle_timeouts() function to do a runtime
  660. * check to see if it is safe to ignore the time-based event complications.
  661. * If your application has taken the shortcut of ignoring libusb's next timeout
  662. * in your main loop, then you are advised to check the return value of
  663. * libusb_pollfds_handle_timeouts() during application startup, and to abort
  664. * if the platform does suffer from these timing complications.
  665. *
  666. * \subsection fdsetchange Changes in the file descriptor set
  667. *
  668. * The set of file descriptors that libusb uses as event sources may change
  669. * during the life of your application. Rather than having to repeatedly
  670. * call libusb_get_pollfds(), you can set up notification functions for when
  671. * the file descriptor set changes using libusb_set_pollfd_notifiers().
  672. *
  673. * \subsection mtissues Multi-threaded considerations
  674. *
  675. * Unfortunately, the situation is complicated further when multiple threads
  676. * come into play. If two threads are monitoring the same file descriptors,
  677. * the fact that only one thread will be woken up when an event occurs causes
  678. * some headaches.
  679. *
  680. * The events lock, event waiters lock, and libusb_handle_events_locked()
  681. * entities are added to solve these problems. You do not need to be concerned
  682. * with these entities otherwise.
  683. *
  684. * See the extra documentation: \ref mtasync
  685. */
  686. /** \page mtasync Multi-threaded applications and asynchronous I/O
  687. *
  688. * libusb is a thread-safe library, but extra considerations must be applied
  689. * to applications which interact with libusb from multiple threads.
  690. *
  691. * The underlying issue that must be addressed is that all libusb I/O
  692. * revolves around monitoring file descriptors through the poll()/select()
  693. * system calls. This is directly exposed at the
  694. * \ref asyncio "asynchronous interface" but it is important to note that the
  695. * \ref syncio "synchronous interface" is implemented on top of the
  696. * asynchonrous interface, therefore the same considerations apply.
  697. *
  698. * The issue is that if two or more threads are concurrently calling poll()
  699. * or select() on libusb's file descriptors then only one of those threads
  700. * will be woken up when an event arrives. The others will be completely
  701. * oblivious that anything has happened.
  702. *
  703. * Consider the following pseudo-code, which submits an asynchronous transfer
  704. * then waits for its completion. This style is one way you could implement a
  705. * synchronous interface on top of the asynchronous interface (and libusb
  706. * does something similar, albeit more advanced due to the complications
  707. * explained on this page).
  708. *
  709. \code
  710. void cb(struct libusb_transfer *transfer)
  711. {
  712. int *completed = transfer->user_data;
  713. *completed = 1;
  714. }
  715. void myfunc() {
  716. struct libusb_transfer *transfer;
  717. unsigned char buffer[LIBUSB_CONTROL_SETUP_SIZE];
  718. int completed = 0;
  719. transfer = libusb_alloc_transfer(0);
  720. libusb_fill_control_setup(buffer,
  721. LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_OUT, 0x04, 0x01, 0, 0);
  722. libusb_fill_control_transfer(transfer, dev, buffer, cb, &completed, 1000);
  723. libusb_submit_transfer(transfer);
  724. while (!completed) {
  725. poll(libusb file descriptors, 120*1000);
  726. if (poll indicates activity)
  727. libusb_handle_events_timeout(ctx, &zero_tv);
  728. }
  729. printf("completed!");
  730. // other code here
  731. }
  732. \endcode
  733. *
  734. * Here we are <em>serializing</em> completion of an asynchronous event
  735. * against a condition - the condition being completion of a specific transfer.
  736. * The poll() loop has a long timeout to minimize CPU usage during situations
  737. * when nothing is happening (it could reasonably be unlimited).
  738. *
  739. * If this is the only thread that is polling libusb's file descriptors, there
  740. * is no problem: there is no danger that another thread will swallow up the
  741. * event that we are interested in. On the other hand, if there is another
  742. * thread polling the same descriptors, there is a chance that it will receive
  743. * the event that we were interested in. In this situation, <tt>myfunc()</tt>
  744. * will only realise that the transfer has completed on the next iteration of
  745. * the loop, <em>up to 120 seconds later.</em> Clearly a two-minute delay is
  746. * undesirable, and don't even think about using short timeouts to circumvent
  747. * this issue!
  748. *
  749. * The solution here is to ensure that no two threads are ever polling the
  750. * file descriptors at the same time. A naive implementation of this would
  751. * impact the capabilities of the library, so libusb offers the scheme
  752. * documented below to ensure no loss of functionality.
  753. *
  754. * Before we go any further, it is worth mentioning that all libusb-wrapped
  755. * event handling procedures fully adhere to the scheme documented below.
  756. * This includes libusb_handle_events() and its variants, and all the
  757. * synchronous I/O functions - libusb hides this headache from you.
  758. *
  759. * \section Using libusb_handle_events() from multiple threads
  760. *
  761. * Even when only using libusb_handle_events() and synchronous I/O functions,
  762. * you can still have a race condition. You might be tempted to solve the
  763. * above with libusb_handle_events() like so:
  764. *
  765. \code
  766. libusb_submit_transfer(transfer);
  767. while (!completed) {
  768. libusb_handle_events(ctx);
  769. }
  770. printf("completed!");
  771. \endcode
  772. *
  773. * This however has a race between the checking of completed and
  774. * libusb_handle_events() acquiring the events lock, so another thread
  775. * could have completed the transfer, resulting in this thread hanging
  776. * until either a timeout or another event occurs. See also commit
  777. * 6696512aade99bb15d6792af90ae329af270eba6 which fixes this in the
  778. * synchronous API implementation of libusb.
  779. *
  780. * Fixing this race requires checking the variable completed only after
  781. * taking the event lock, which defeats the concept of just calling
  782. * libusb_handle_events() without worrying about locking. This is why
  783. * libusb-1.0.9 introduces the new libusb_handle_events_timeout_completed()
  784. * and libusb_handle_events_completed() functions, which handles doing the
  785. * completion check for you after they have acquired the lock:
  786. *
  787. \code
  788. libusb_submit_transfer(transfer);
  789. while (!completed) {
  790. libusb_handle_events_completed(ctx, &completed);
  791. }
  792. printf("completed!");
  793. \endcode
  794. *
  795. * This nicely fixes the race in our example. Note that if all you want to
  796. * do is submit a single transfer and wait for its completion, then using
  797. * one of the synchronous I/O functions is much easier.
  798. *
  799. * \section eventlock The events lock
  800. *
  801. * The problem is when we consider the fact that libusb exposes file
  802. * descriptors to allow for you to integrate asynchronous USB I/O into
  803. * existing main loops, effectively allowing you to do some work behind
  804. * libusb's back. If you do take libusb's file descriptors and pass them to
  805. * poll()/select() yourself, you need to be aware of the associated issues.
  806. *
  807. * The first concept to be introduced is the events lock. The events lock
  808. * is used to serialize threads that want to handle events, such that only
  809. * one thread is handling events at any one time.
  810. *
  811. * You must take the events lock before polling libusb file descriptors,
  812. * using libusb_lock_events(). You must release the lock as soon as you have
  813. * aborted your poll()/select() loop, using libusb_unlock_events().
  814. *
  815. * \section threadwait Letting other threads do the work for you
  816. *
  817. * Although the events lock is a critical part of the solution, it is not
  818. * enough on it's own. You might wonder if the following is sufficient...
  819. \code
  820. libusb_lock_events(ctx);
  821. while (!completed) {
  822. poll(libusb file descriptors, 120*1000);
  823. if (poll indicates activity)
  824. libusb_handle_events_timeout(ctx, &zero_tv);
  825. }
  826. libusb_unlock_events(ctx);
  827. \endcode
  828. * ...and the answer is that it is not. This is because the transfer in the
  829. * code shown above may take a long time (say 30 seconds) to complete, and
  830. * the lock is not released until the transfer is completed.
  831. *
  832. * Another thread with similar code that wants to do event handling may be
  833. * working with a transfer that completes after a few milliseconds. Despite
  834. * having such a quick completion time, the other thread cannot check that
  835. * status of its transfer until the code above has finished (30 seconds later)
  836. * due to contention on the lock.
  837. *
  838. * To solve this, libusb offers you a mechanism to determine when another
  839. * thread is handling events. It also offers a mechanism to block your thread
  840. * until the event handling thread has completed an event (and this mechanism
  841. * does not involve polling of file descriptors).
  842. *
  843. * After determining that another thread is currently handling events, you
  844. * obtain the <em>event waiters</em> lock using libusb_lock_event_waiters().
  845. * You then re-check that some other thread is still handling events, and if
  846. * so, you call libusb_wait_for_event().
  847. *
  848. * libusb_wait_for_event() puts your application to sleep until an event
  849. * occurs, or until a thread releases the events lock. When either of these
  850. * things happen, your thread is woken up, and should re-check the condition
  851. * it was waiting on. It should also re-check that another thread is handling
  852. * events, and if not, it should start handling events itself.
  853. *
  854. * This looks like the following, as pseudo-code:
  855. \code
  856. retry:
  857. if (libusb_try_lock_events(ctx) == 0) {
  858. // we obtained the event lock: do our own event handling
  859. while (!completed) {
  860. if (!libusb_event_handling_ok(ctx)) {
  861. libusb_unlock_events(ctx);
  862. goto retry;
  863. }
  864. poll(libusb file descriptors, 120*1000);
  865. if (poll indicates activity)
  866. libusb_handle_events_locked(ctx, 0);
  867. }
  868. libusb_unlock_events(ctx);
  869. } else {
  870. // another thread is doing event handling. wait for it to signal us that
  871. // an event has completed
  872. libusb_lock_event_waiters(ctx);
  873. while (!completed) {
  874. // now that we have the event waiters lock, double check that another
  875. // thread is still handling events for us. (it may have ceased handling
  876. // events in the time it took us to reach this point)
  877. if (!libusb_event_handler_active(ctx)) {
  878. // whoever was handling events is no longer doing so, try again
  879. libusb_unlock_event_waiters(ctx);
  880. goto retry;
  881. }
  882. libusb_wait_for_event(ctx, NULL);
  883. }
  884. libusb_unlock_event_waiters(ctx);
  885. }
  886. printf("completed!\n");
  887. \endcode
  888. *
  889. * A naive look at the above code may suggest that this can only support
  890. * one event waiter (hence a total of 2 competing threads, the other doing
  891. * event handling), because the event waiter seems to have taken the event
  892. * waiters lock while waiting for an event. However, the system does support
  893. * multiple event waiters, because libusb_wait_for_event() actually drops
  894. * the lock while waiting, and reaquires it before continuing.
  895. *
  896. * We have now implemented code which can dynamically handle situations where
  897. * nobody is handling events (so we should do it ourselves), and it can also
  898. * handle situations where another thread is doing event handling (so we can
  899. * piggyback onto them). It is also equipped to handle a combination of
  900. * the two, for example, another thread is doing event handling, but for
  901. * whatever reason it stops doing so before our condition is met, so we take
  902. * over the event handling.
  903. *
  904. * Four functions were introduced in the above pseudo-code. Their importance
  905. * should be apparent from the code shown above.
  906. * -# libusb_try_lock_events() is a non-blocking function which attempts
  907. * to acquire the events lock but returns a failure code if it is contended.
  908. * -# libusb_event_handling_ok() checks that libusb is still happy for your
  909. * thread to be performing event handling. Sometimes, libusb needs to
  910. * interrupt the event handler, and this is how you can check if you have
  911. * been interrupted. If this function returns 0, the correct behaviour is
  912. * for you to give up the event handling lock, and then to repeat the cycle.
  913. * The following libusb_try_lock_events() will fail, so you will become an
  914. * events waiter. For more information on this, read \ref fullstory below.
  915. * -# libusb_handle_events_locked() is a variant of
  916. * libusb_handle_events_timeout() that you can call while holding the
  917. * events lock. libusb_handle_events_timeout() itself implements similar
  918. * logic to the above, so be sure not to call it when you are
  919. * "working behind libusb's back", as is the case here.
  920. * -# libusb_event_handler_active() determines if someone is currently
  921. * holding the events lock
  922. *
  923. * You might be wondering why there is no function to wake up all threads
  924. * blocked on libusb_wait_for_event(). This is because libusb can do this
  925. * internally: it will wake up all such threads when someone calls
  926. * libusb_unlock_events() or when a transfer completes (at the point after its
  927. * callback has returned).
  928. *
  929. * \subsection fullstory The full story
  930. *
  931. * The above explanation should be enough to get you going, but if you're
  932. * really thinking through the issues then you may be left with some more
  933. * questions regarding libusb's internals. If you're curious, read on, and if
  934. * not, skip to the next section to avoid confusing yourself!
  935. *
  936. * The immediate question that may spring to mind is: what if one thread
  937. * modifies the set of file descriptors that need to be polled while another
  938. * thread is doing event handling?
  939. *
  940. * There are 2 situations in which this may happen.
  941. * -# libusb_open() will add another file descriptor to the poll set,
  942. * therefore it is desirable to interrupt the event handler so that it
  943. * restarts, picking up the new descriptor.
  944. * -# libusb_close() will remove a file descriptor from the poll set. There
  945. * are all kinds of race conditions that could arise here, so it is
  946. * important that nobody is doing event handling at this time.
  947. *
  948. * libusb handles these issues internally, so application developers do not
  949. * have to stop their event handlers while opening/closing devices. Here's how
  950. * it works, focusing on the libusb_close() situation first:
  951. *
  952. * -# During initialization, libusb opens an internal pipe, and it adds the read
  953. * end of this pipe to the set of file descriptors to be polled.
  954. * -# During libusb_close(), libusb writes some dummy data on this control pipe.
  955. * This immediately interrupts the event handler. libusb also records
  956. * internally that it is trying to interrupt event handlers for this
  957. * high-priority event.
  958. * -# At this point, some of the functions described above start behaving
  959. * differently:
  960. * - libusb_event_handling_ok() starts returning 1, indicating that it is NOT
  961. * OK for event handling to continue.
  962. * - libusb_try_lock_events() starts returning 1, indicating that another
  963. * thread holds the event handling lock, even if the lock is uncontended.
  964. * - libusb_event_handler_active() starts returning 1, indicating that
  965. * another thread is doing event handling, even if that is not true.
  966. * -# The above changes in behaviour result in the event handler stopping and
  967. * giving up the events lock very quickly, giving the high-priority
  968. * libusb_close() operation a "free ride" to acquire the events lock. All
  969. * threads that are competing to do event handling become event waiters.
  970. * -# With the events lock held inside libusb_close(), libusb can safely remove
  971. * a file descriptor from the poll set, in the safety of knowledge that
  972. * nobody is polling those descriptors or trying to access the poll set.
  973. * -# After obtaining the events lock, the close operation completes very
  974. * quickly (usually a matter of milliseconds) and then immediately releases
  975. * the events lock.
  976. * -# At the same time, the behaviour of libusb_event_handling_ok() and friends
  977. * reverts to the original, documented behaviour.
  978. * -# The release of the events lock causes the threads that are waiting for
  979. * events to be woken up and to start competing to become event handlers
  980. * again. One of them will succeed; it will then re-obtain the list of poll
  981. * descriptors, and USB I/O will then continue as normal.
  982. *
  983. * libusb_open() is similar, and is actually a more simplistic case. Upon a
  984. * call to libusb_open():
  985. *
  986. * -# The device is opened and a file descriptor is added to the poll set.
  987. * -# libusb sends some dummy data on the control pipe, and records that it
  988. * is trying to modify the poll descriptor set.
  989. * -# The event handler is interrupted, and the same behaviour change as for
  990. * libusb_close() takes effect, causing all event handling threads to become
  991. * event waiters.
  992. * -# The libusb_open() implementation takes its free ride to the events lock.
  993. * -# Happy that it has successfully paused the events handler, libusb_open()
  994. * releases the events lock.
  995. * -# The event waiter threads are all woken up and compete to become event
  996. * handlers again. The one that succeeds will obtain the list of poll
  997. * descriptors again, which will include the addition of the new device.
  998. *
  999. * \subsection concl Closing remarks
  1000. *
  1001. * The above may seem a little complicated, but hopefully I have made it clear
  1002. * why such complications are necessary. Also, do not forget that this only
  1003. * applies to applications that take libusb's file descriptors and integrate
  1004. * them into their own polling loops.
  1005. *
  1006. * You may decide that it is OK for your multi-threaded application to ignore
  1007. * some of the rules and locks detailed above, because you don't think that
  1008. * two threads can ever be polling the descriptors at the same time. If that
  1009. * is the case, then that's good news for you because you don't have to worry.
  1010. * But be careful here; remember that the synchronous I/O functions do event
  1011. * handling internally. If you have one thread doing event handling in a loop
  1012. * (without implementing the rules and locking semantics documented above)
  1013. * and another trying to send a synchronous USB transfer, you will end up with
  1014. * two threads monitoring the same descriptors, and the above-described
  1015. * undesirable behaviour occuring. The solution is for your polling thread to
  1016. * play by the rules; the synchronous I/O functions do so, and this will result
  1017. * in them getting along in perfect harmony.
  1018. *
  1019. * If you do have a dedicated thread doing event handling, it is perfectly
  1020. * legal for it to take the event handling lock for long periods of time. Any
  1021. * synchronous I/O functions you call from other threads will transparently
  1022. * fall back to the "event waiters" mechanism detailed above. The only
  1023. * consideration that your event handling thread must apply is the one related
  1024. * to libusb_event_handling_ok(): you must call this before every poll(), and
  1025. * give up the events lock if instructed.
  1026. */
  1027. int usbi_io_init(struct libusb_context *ctx)
  1028. {
  1029. int r;
  1030. usbi_mutex_init(&ctx->flying_transfers_lock, NULL);
  1031. usbi_mutex_init(&ctx->pollfds_lock, NULL);
  1032. usbi_mutex_init(&ctx->pollfd_modify_lock, NULL);
  1033. usbi_mutex_init_recursive(&ctx->events_lock, NULL);
  1034. usbi_mutex_init(&ctx->event_waiters_lock, NULL);
  1035. usbi_cond_init(&ctx->event_waiters_cond, NULL);
  1036. list_init(&ctx->flying_transfers);
  1037. list_init(&ctx->pollfds);
  1038. /* FIXME should use an eventfd on kernels that support it */
  1039. r = usbi_pipe(ctx->ctrl_pipe);
  1040. if (r < 0) {
  1041. r = LIBUSB_ERROR_OTHER;
  1042. goto err;
  1043. }
  1044. r = usbi_add_pollfd(ctx, ctx->ctrl_pipe[0], POLLIN);
  1045. if (r < 0)
  1046. goto err_close_pipe;
  1047. /* create hotplug pipe */
  1048. r = usbi_pipe(ctx->hotplug_pipe);
  1049. if (r < 0) {
  1050. r = LIBUSB_ERROR_OTHER;
  1051. goto err;
  1052. }
  1053. #ifndef OS_WINDOWS
  1054. fcntl (ctx->hotplug_pipe[1], F_SETFD, O_NONBLOCK);
  1055. #endif
  1056. r = usbi_add_pollfd(ctx, ctx->hotplug_pipe[0], POLLIN);
  1057. if (r < 0)
  1058. goto err_close_hp_pipe;
  1059. #ifdef USBI_TIMERFD_AVAILABLE
  1060. ctx->timerfd = timerfd_create(usbi_backend->get_timerfd_clockid(),
  1061. TFD_NONBLOCK);
  1062. if (ctx->timerfd >= 0) {
  1063. usbi_dbg("using timerfd for timeouts");
  1064. r = usbi_add_pollfd(ctx, ctx->timerfd, POLLIN);
  1065. if (r < 0) {
  1066. usbi_remove_pollfd(ctx, ctx->ctrl_pipe[0]);
  1067. close(ctx->timerfd);
  1068. goto err_close_hp_pipe;
  1069. }
  1070. } else {
  1071. usbi_dbg("timerfd not available (code %d error %d)", ctx->timerfd, errno);
  1072. ctx->timerfd = -1;
  1073. }
  1074. #endif
  1075. return 0;
  1076. err_close_hp_pipe:
  1077. usbi_close(ctx->hotplug_pipe[0]);
  1078. usbi_close(ctx->hotplug_pipe[1]);
  1079. err_close_pipe:
  1080. usbi_close(ctx->ctrl_pipe[0]);
  1081. usbi_close(ctx->ctrl_pipe[1]);
  1082. err:
  1083. usbi_mutex_destroy(&ctx->flying_transfers_lock);
  1084. usbi_mutex_destroy(&ctx->pollfds_lock);
  1085. usbi_mutex_destroy(&ctx->pollfd_modify_lock);
  1086. usbi_mutex_destroy(&ctx->events_lock);
  1087. usbi_mutex_destroy(&ctx->event_waiters_lock);
  1088. usbi_cond_destroy(&ctx->event_waiters_cond);
  1089. return r;
  1090. }
  1091. void usbi_io_exit(struct libusb_context *ctx)
  1092. {
  1093. usbi_remove_pollfd(ctx, ctx->ctrl_pipe[0]);
  1094. usbi_close(ctx->ctrl_pipe[0]);
  1095. usbi_close(ctx->ctrl_pipe[1]);
  1096. usbi_remove_pollfd(ctx, ctx->hotplug_pipe[0]);
  1097. usbi_close(ctx->hotplug_pipe[0]);
  1098. usbi_close(ctx->hotplug_pipe[1]);
  1099. #ifdef USBI_TIMERFD_AVAILABLE
  1100. if (usbi_using_timerfd(ctx)) {
  1101. usbi_remove_pollfd(ctx, ctx->timerfd);
  1102. close(ctx->timerfd);
  1103. }
  1104. #endif
  1105. usbi_mutex_destroy(&ctx->flying_transfers_lock);
  1106. usbi_mutex_destroy(&ctx->pollfds_lock);
  1107. usbi_mutex_destroy(&ctx->pollfd_modify_lock);
  1108. usbi_mutex_destroy(&ctx->events_lock);
  1109. usbi_mutex_destroy(&ctx->event_waiters_lock);
  1110. usbi_cond_destroy(&ctx->event_waiters_cond);
  1111. }
  1112. static int calculate_timeout(struct usbi_transfer *transfer)
  1113. {
  1114. int r;
  1115. struct timespec current_time;
  1116. unsigned int timeout =
  1117. USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer)->timeout;
  1118. if (!timeout)
  1119. return 0;
  1120. r = usbi_backend->clock_gettime(USBI_CLOCK_MONOTONIC, &current_time);
  1121. if (r < 0) {
  1122. usbi_err(ITRANSFER_CTX(transfer),
  1123. "failed to read monotonic clock, errno=%d", errno);
  1124. return r;
  1125. }
  1126. current_time.tv_sec += timeout / 1000;
  1127. current_time.tv_nsec += (timeout % 1000) * 1000000;
  1128. while (current_time.tv_nsec >= 1000000000) {
  1129. current_time.tv_nsec -= 1000000000;
  1130. current_time.tv_sec++;
  1131. }
  1132. TIMESPEC_TO_TIMEVAL(&transfer->timeout, &current_time);
  1133. return 0;
  1134. }
  1135. /* add a transfer to the (timeout-sorted) active transfers list.
  1136. * returns 1 if the transfer has a timeout and it is the timeout next to
  1137. * expire */
  1138. static int add_to_flying_list(struct usbi_transfer *transfer)
  1139. {
  1140. struct usbi_transfer *cur;
  1141. struct timeval *timeout = &transfer->timeout;
  1142. struct libusb_context *ctx = ITRANSFER_CTX(transfer);
  1143. int r = 0;
  1144. int first = 1;
  1145. usbi_mutex_lock(&ctx->flying_transfers_lock);
  1146. /* if we have no other flying transfers, start the list with this one */
  1147. if (list_empty(&ctx->flying_transfers)) {
  1148. list_add(&transfer->list, &ctx->flying_transfers);
  1149. if (timerisset(timeout))
  1150. r = 1;
  1151. goto out;
  1152. }
  1153. /* if we have infinite timeout, append to end of list */
  1154. if (!timerisset(timeout)) {
  1155. list_add_tail(&transfer->list, &ctx->flying_transfers);
  1156. goto out;
  1157. }
  1158. /* otherwise, find appropriate place in list */
  1159. list_for_each_entry(cur, &ctx->flying_transfers, list, struct usbi_transfer) {
  1160. /* find first timeout that occurs after the transfer in question */
  1161. struct timeval *cur_tv = &cur->timeout;
  1162. if (!timerisset(cur_tv) || (cur_tv->tv_sec > timeout->tv_sec) ||
  1163. (cur_tv->tv_sec == timeout->tv_sec &&
  1164. cur_tv->tv_usec > timeout->tv_usec)) {
  1165. list_add_tail(&transfer->list, &cur->list);
  1166. r = first;
  1167. goto out;
  1168. }
  1169. first = 0;
  1170. }
  1171. /* otherwise we need to be inserted at the end */
  1172. list_add_tail(&transfer->list, &ctx->flying_transfers);
  1173. out:
  1174. usbi_mutex_unlock(&ctx->flying_transfers_lock);
  1175. return r;
  1176. }
  1177. /** \ingroup asyncio
  1178. * Allocate a libusb transfer with a specified number of isochronous packet
  1179. * descriptors. The returned transfer is pre-initialized for you. When the new
  1180. * transfer is no longer needed, it should be freed with
  1181. * libusb_free_transfer().
  1182. *
  1183. * Transfers intended for non-isochronous endpoints (e.g. control, bulk,
  1184. * interrupt) should specify an iso_packets count of zero.
  1185. *
  1186. * For transfers intended for isochronous endpoints, specify an appropriate
  1187. * number of packet descriptors to be allocated as part of the transfer.
  1188. * The returned transfer is not specially initialized for isochronous I/O;
  1189. * you are still required to set the
  1190. * \ref libusb_transfer::num_iso_packets "num_iso_packets" and
  1191. * \ref libusb_transfer::type "type" fields accordingly.
  1192. *
  1193. * It is safe to allocate a transfer with some isochronous packets and then
  1194. * use it on a non-isochronous endpoint. If you do this, ensure that at time
  1195. * of submission, num_iso_packets is 0 and that type is set appropriately.
  1196. *
  1197. * \param iso_packets number of isochronous packet descriptors to allocate
  1198. * \returns a newly allocated transfer, or NULL on error
  1199. */
  1200. DEFAULT_VISIBILITY
  1201. struct libusb_transfer * LIBUSB_CALL libusb_alloc_transfer(
  1202. int iso_packets)
  1203. {
  1204. size_t os_alloc_size = usbi_backend->transfer_priv_size
  1205. + (usbi_backend->add_iso_packet_size * iso_packets);
  1206. size_t alloc_size = sizeof(struct usbi_transfer)
  1207. + sizeof(struct libusb_transfer)
  1208. + (sizeof(struct libusb_iso_packet_descriptor) * iso_packets)
  1209. + os_alloc_size;
  1210. struct usbi_transfer *itransfer = malloc(alloc_size);
  1211. if (!itransfer)
  1212. return NULL;
  1213. memset(itransfer, 0, alloc_size);
  1214. itransfer->num_iso_packets = iso_packets;
  1215. usbi_mutex_init(&itransfer->lock, NULL);
  1216. return USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1217. }
  1218. /** \ingroup asyncio
  1219. * Free a transfer structure. This should be called for all transfers
  1220. * allocated with libusb_alloc_transfer().
  1221. *
  1222. * If the \ref libusb_transfer_flags::LIBUSB_TRANSFER_FREE_BUFFER
  1223. * "LIBUSB_TRANSFER_FREE_BUFFER" flag is set and the transfer buffer is
  1224. * non-NULL, this function will also free the transfer buffer using the
  1225. * standard system memory allocator (e.g. free()).
  1226. *
  1227. * It is legal to call this function with a NULL transfer. In this case,
  1228. * the function will simply return safely.
  1229. *
  1230. * It is not legal to free an active transfer (one which has been submitted
  1231. * and has not yet completed).
  1232. *
  1233. * \param transfer the transfer to free
  1234. */
  1235. void API_EXPORTED libusb_free_transfer(struct libusb_transfer *transfer)
  1236. {
  1237. struct usbi_transfer *itransfer;
  1238. if (!transfer)
  1239. return;
  1240. if (transfer->flags & LIBUSB_TRANSFER_FREE_BUFFER && transfer->buffer)
  1241. free(transfer->buffer);
  1242. itransfer = LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
  1243. usbi_mutex_destroy(&itransfer->lock);
  1244. free(itransfer);
  1245. }
  1246. /** \ingroup asyncio
  1247. * Submit a transfer. This function will fire off the USB transfer and then
  1248. * return immediately.
  1249. *
  1250. * \param transfer the transfer to submit
  1251. * \returns 0 on success
  1252. * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
  1253. * \returns LIBUSB_ERROR_BUSY if the transfer has already been submitted.
  1254. * \returns LIBUSB_ERROR_NOT_SUPPORTED if the transfer flags are not supported
  1255. * by the operating system.
  1256. * \returns another LIBUSB_ERROR code on other failure
  1257. */
  1258. int API_EXPORTED libusb_submit_transfer(struct libusb_transfer *transfer)
  1259. {
  1260. struct libusb_context *ctx = TRANSFER_CTX(transfer);
  1261. struct usbi_transfer *itransfer =
  1262. LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
  1263. int r;
  1264. int first;
  1265. int updated_fds;
  1266. usbi_mutex_lock(&itransfer->lock);
  1267. itransfer->transferred = 0;
  1268. itransfer->flags = 0;
  1269. r = calculate_timeout(itransfer);
  1270. if (r < 0) {
  1271. r = LIBUSB_ERROR_OTHER;
  1272. goto out;
  1273. }
  1274. first = add_to_flying_list(itransfer);
  1275. r = usbi_backend->submit_transfer(itransfer);
  1276. if (r) {
  1277. usbi_mutex_lock(&ctx->flying_transfers_lock);
  1278. list_del(&itransfer->list);
  1279. usbi_mutex_unlock(&ctx->flying_transfers_lock);
  1280. }
  1281. #ifdef USBI_TIMERFD_AVAILABLE
  1282. else if (first && usbi_using_timerfd(ctx)) {
  1283. /* if this transfer has the lowest timeout of all active transfers,
  1284. * rearm the timerfd with this transfer's timeout */
  1285. const struct itimerspec it = { {0, 0},
  1286. { itransfer->timeout.tv_sec, itransfer->timeout.tv_usec * 1000 } };
  1287. usbi_dbg("arm timerfd for timeout in %dms (first in line)", transfer->timeout);
  1288. r = timerfd_settime(ctx->timerfd, TFD_TIMER_ABSTIME, &it, NULL);
  1289. if (r < 0)
  1290. r = LIBUSB_ERROR_OTHER;
  1291. }
  1292. #else
  1293. (void)first;
  1294. #endif
  1295. out:
  1296. updated_fds = (itransfer->flags & USBI_TRANSFER_UPDATED_FDS);
  1297. usbi_mutex_unlock(&itransfer->lock);
  1298. if (updated_fds)
  1299. usbi_fd_notification(ctx);
  1300. return r;
  1301. }
  1302. /** \ingroup asyncio
  1303. * Asynchronously cancel a previously submitted transfer.
  1304. * This function returns immediately, but this does not indicate cancellation
  1305. * is complete. Your callback function will be invoked at some later time
  1306. * with a transfer status of
  1307. * \ref libusb_transfer_status::LIBUSB_TRANSFER_CANCELLED
  1308. * "LIBUSB_TRANSFER_CANCELLED."
  1309. *
  1310. * \param transfer the transfer to cancel
  1311. * \returns 0 on success
  1312. * \returns LIBUSB_ERROR_NOT_FOUND if the transfer is already complete or
  1313. * cancelled.
  1314. * \returns a LIBUSB_ERROR code on failure
  1315. */
  1316. int API_EXPORTED libusb_cancel_transfer(struct libusb_transfer *transfer)
  1317. {
  1318. struct usbi_transfer *itransfer =
  1319. LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
  1320. int r;
  1321. usbi_dbg("");
  1322. usbi_mutex_lock(&itransfer->lock);
  1323. r = usbi_backend->cancel_transfer(itransfer);
  1324. if (r < 0) {
  1325. if (r != LIBUSB_ERROR_NOT_FOUND)
  1326. usbi_err(TRANSFER_CTX(transfer),
  1327. "cancel transfer failed error %d", r);
  1328. else
  1329. usbi_dbg("cancel transfer failed error %d", r);
  1330. if (r == LIBUSB_ERROR_NO_DEVICE)
  1331. itransfer->flags |= USBI_TRANSFER_DEVICE_DISAPPEARED;
  1332. }
  1333. itransfer->flags |= USBI_TRANSFER_CANCELLING;
  1334. usbi_mutex_unlock(&itransfer->lock);
  1335. return r;
  1336. }
  1337. #ifdef USBI_TIMERFD_AVAILABLE
  1338. static int disarm_timerfd(struct libusb_context *ctx)
  1339. {
  1340. const struct itimerspec disarm_timer = { { 0, 0 }, { 0, 0 } };
  1341. int r;
  1342. usbi_dbg("");
  1343. r = timerfd_settime(ctx->timerfd, 0, &disarm_timer, NULL);
  1344. if (r < 0)
  1345. return LIBUSB_ERROR_OTHER;
  1346. else
  1347. return 0;
  1348. }
  1349. /* iterates through the flying transfers, and rearms the timerfd based on the
  1350. * next upcoming timeout.
  1351. * must be called with flying_list locked.
  1352. * returns 0 if there was no timeout to arm, 1 if the next timeout was armed,
  1353. * or a LIBUSB_ERROR code on failure.
  1354. */
  1355. static int arm_timerfd_for_next_timeout(struct libusb_context *ctx)
  1356. {
  1357. struct usbi_transfer *transfer;
  1358. list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) {
  1359. struct timeval *cur_tv = &transfer->timeout;
  1360. /* if we've reached transfers of infinite timeout, then we have no
  1361. * arming to do */
  1362. if (!timerisset(cur_tv))
  1363. return 0;
  1364. /* act on first transfer that is not already cancelled */
  1365. if (!(transfer->flags & USBI_TRANSFER_TIMED_OUT)) {
  1366. int r;
  1367. const struct itimerspec it = { {0, 0},
  1368. { cur_tv->tv_sec, cur_tv->tv_usec * 1000 } };
  1369. usbi_dbg("next timeout originally %dms", USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer)->timeout);
  1370. r = timerfd_settime(ctx->timerfd, TFD_TIMER_ABSTIME, &it, NULL);
  1371. if (r < 0)
  1372. return LIBUSB_ERROR_OTHER;
  1373. return 1;
  1374. }
  1375. }
  1376. return 0;
  1377. }
  1378. #else
  1379. static int disarm_timerfd(struct libusb_context *ctx)
  1380. {
  1381. (void)ctx;
  1382. return 0;
  1383. }
  1384. static int arm_timerfd_for_next_timeout(struct libusb_context *ctx)
  1385. {
  1386. (void)ctx;
  1387. return 0;
  1388. }
  1389. #endif
  1390. /* Handle completion of a transfer (completion might be an error condition).
  1391. * This will invoke the user-supplied callback function, which may end up
  1392. * freeing the transfer. Therefore you cannot use the transfer structure
  1393. * after calling this function, and you should free all backend-specific
  1394. * data before calling it.
  1395. * Do not call this function with the usbi_transfer lock held. User-specified
  1396. * callback functions may attempt to directly resubmit the transfer, which
  1397. * will attempt to take the lock. */
  1398. int usbi_handle_transfer_completion(struct usbi_transfer *itransfer,
  1399. enum libusb_transfer_status status)
  1400. {
  1401. struct libusb_transfer *transfer =
  1402. USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1403. struct libusb_context *ctx = TRANSFER_CTX(transfer);
  1404. uint8_t flags;
  1405. int r = 0;
  1406. /* FIXME: could be more intelligent with the timerfd here. we don't need
  1407. * to disarm the timerfd if there was no timer running, and we only need
  1408. * to rearm the timerfd if the transfer that expired was the one with
  1409. * the shortest timeout. */
  1410. usbi_mutex_lock(&ctx->flying_transfers_lock);
  1411. /* FIXME: Sanity check for some race where this entry has already been
  1412. * removed! */
  1413. if ((&itransfer->list)->next)
  1414. list_del(&itransfer->list);
  1415. if (usbi_using_timerfd(ctx)) {
  1416. r = arm_timerfd_for_next_timeout(ctx);
  1417. if (0 == r)
  1418. r = disarm_timerfd(ctx);
  1419. }
  1420. usbi_mutex_unlock(&ctx->flying_transfers_lock);
  1421. if (r < 0)
  1422. return r;
  1423. if (status == LIBUSB_TRANSFER_COMPLETED
  1424. && transfer->flags & LIBUSB_TRANSFER_SHORT_NOT_OK) {
  1425. int rqlen = transfer->length;
  1426. if (transfer->type == LIBUSB_TRANSFER_TYPE_CONTROL)
  1427. rqlen -= LIBUSB_CONTROL_SETUP_SIZE;
  1428. if (rqlen != itransfer->transferred) {
  1429. usbi_dbg("interpreting short transfer as error");
  1430. status = LIBUSB_TRANSFER_ERROR;
  1431. }
  1432. }
  1433. flags = transfer->flags;
  1434. transfer->status = status;
  1435. transfer->actual_length = itransfer->transferred;
  1436. usbi_dbg("transfer %p has callback %p", transfer, transfer->callback);
  1437. if (transfer->callback)
  1438. transfer->callback(transfer);
  1439. /* transfer might have been freed by the above call, do not use from
  1440. * this point. */
  1441. if (flags & LIBUSB_TRANSFER_FREE_TRANSFER)
  1442. libusb_free_transfer(transfer);
  1443. usbi_mutex_lock(&ctx->event_waiters_lock);
  1444. usbi_cond_broadcast(&ctx->event_waiters_cond);
  1445. usbi_mutex_unlock(&ctx->event_waiters_lock);
  1446. return 0;
  1447. }
  1448. /* Similar to usbi_handle_transfer_completion() but exclusively for transfers
  1449. * that were asynchronously cancelled. The same concerns w.r.t. freeing of
  1450. * transfers exist here.
  1451. * Do not call this function with the usbi_transfer lock held. User-specified
  1452. * callback functions may attempt to directly resubmit the transfer, which
  1453. * will attempt to take the lock. */
  1454. int usbi_handle_transfer_cancellation(struct usbi_transfer *transfer)
  1455. {
  1456. /* if the URB was cancelled due to timeout, report timeout to the user */
  1457. if (transfer->flags & USBI_TRANSFER_TIMED_OUT) {
  1458. usbi_dbg("detected timeout cancellation");
  1459. return usbi_handle_transfer_completion(transfer, LIBUSB_TRANSFER_TIMED_OUT);
  1460. }
  1461. /* otherwise its a normal async cancel */
  1462. return usbi_handle_transfer_completion(transfer, LIBUSB_TRANSFER_CANCELLED);
  1463. }
  1464. /** \ingroup poll
  1465. * Attempt to acquire the event handling lock. This lock is used to ensure that
  1466. * only one thread is monitoring libusb event sources at any one time.
  1467. *
  1468. * You only need to use this lock if you are developing an application
  1469. * which calls poll() or select() on libusb's file descriptors directly.
  1470. * If you stick to libusb's event handling loop functions (e.g.
  1471. * libusb_handle_events()) then you do not need to be concerned with this
  1472. * locking.
  1473. *
  1474. * While holding this lock, you are trusted to actually be handling events.
  1475. * If you are no longer handling events, you must call libusb_unlock_events()
  1476. * as soon as possible.
  1477. *
  1478. * \param ctx the context to operate on, or NULL for the default context
  1479. * \returns 0 if the lock was obtained successfully
  1480. * \returns 1 if the lock was not obtained (i.e. another thread holds the lock)
  1481. * \see \ref mtasync
  1482. */
  1483. int API_EXPORTED libusb_try_lock_events(libusb_context *ctx)
  1484. {
  1485. int r;
  1486. USBI_GET_CONTEXT(ctx);
  1487. /* is someone else waiting to modify poll fds? if so, don't let this thread
  1488. * start event handling */
  1489. usbi_mutex_lock(&ctx->pollfd_modify_lock);
  1490. r = ctx->pollfd_modify;
  1491. usbi_mutex_unlock(&ctx->pollfd_modify_lock);
  1492. if (r) {
  1493. usbi_dbg("someone else is modifying poll fds");
  1494. return 1;
  1495. }
  1496. r = usbi_mutex_trylock(&ctx->events_lock);
  1497. if (r)
  1498. return 1;
  1499. ctx->event_handler_active = 1;
  1500. return 0;
  1501. }
  1502. /** \ingroup poll
  1503. * Acquire the event handling lock, blocking until successful acquisition if
  1504. * it is contended. This lock is used to ensure that only one thread is
  1505. * monitoring libusb event sources at any one time.
  1506. *
  1507. * You only need to use this lock if you are developing an application
  1508. * which calls poll() or select() on libusb's file descriptors directly.
  1509. * If you stick to libusb's event handling loop functions (e.g.
  1510. * libusb_handle_events()) then you do not need to be concerned with this
  1511. * locking.
  1512. *
  1513. * While holding this lock, you are trusted to actually be handling events.
  1514. * If you are no longer handling events, you must call libusb_unlock_events()
  1515. * as soon as possible.
  1516. *
  1517. * \param ctx the context to operate on, or NULL for the default context
  1518. * \see \ref mtasync
  1519. */
  1520. void API_EXPORTED libusb_lock_events(libusb_context *ctx)
  1521. {
  1522. USBI_GET_CONTEXT(ctx);
  1523. usbi_mutex_lock(&ctx->events_lock);
  1524. ctx->event_handler_active = 1;
  1525. }
  1526. /** \ingroup poll
  1527. * Release the lock previously acquired with libusb_try_lock_events() or
  1528. * libusb_lock_events(). Releasing this lock will wake up any threads blocked
  1529. * on libusb_wait_for_event().
  1530. *
  1531. * \param ctx the context to operate on, or NULL for the default context
  1532. * \see \ref mtasync
  1533. */
  1534. void API_EXPORTED libusb_unlock_events(libusb_context *ctx)
  1535. {
  1536. USBI_GET_CONTEXT(ctx);
  1537. ctx->event_handler_active = 0;
  1538. usbi_mutex_unlock(&ctx->events_lock);
  1539. /* FIXME: perhaps we should be a bit more efficient by not broadcasting
  1540. * the availability of the events lock when we are modifying pollfds
  1541. * (check ctx->pollfd_modify)? */
  1542. usbi_mutex_lock(&ctx->event_waiters_lock);
  1543. usbi_cond_broadcast(&ctx->event_waiters_cond);
  1544. usbi_mutex_unlock(&ctx->event_waiters_lock);
  1545. }
  1546. /** \ingroup poll
  1547. * Determine if it is still OK for this thread to be doing event handling.
  1548. *
  1549. * Sometimes, libusb needs to temporarily pause all event handlers, and this
  1550. * is the function you should use before polling file descriptors to see if
  1551. * this is the case.
  1552. *
  1553. * If this function instructs your thread to give up the events lock, you
  1554. * should just continue the usual logic that is documented in \ref mtasync.
  1555. * On the next iteration, your thread will fail to obtain the events lock,
  1556. * and will hence become an event waiter.
  1557. *
  1558. * This function should be called while the events lock is held: you don't
  1559. * need to worry about the results of this function if your thread is not
  1560. * the current event handler.
  1561. *
  1562. * \param ctx the context to operate on, or NULL for the default context
  1563. * \returns 1 if event handling can start or continue
  1564. * \returns 0 if this thread must give up the events lock
  1565. * \see \ref fullstory "Multi-threaded I/O: the full story"
  1566. */
  1567. int API_EXPORTED libusb_event_handling_ok(libusb_context *ctx)
  1568. {
  1569. int r;
  1570. USBI_GET_CONTEXT(ctx);
  1571. /* is someone else waiting to modify poll fds? if so, don't let this thread
  1572. * continue event handling */
  1573. usbi_mutex_lock(&ctx->pollfd_modify_lock);
  1574. r = ctx->pollfd_modify;
  1575. usbi_mutex_unlock(&ctx->pollfd_modify_lock);
  1576. if (r) {
  1577. usbi_dbg("someone else is modifying poll fds");
  1578. return 0;
  1579. }
  1580. return 1;
  1581. }
  1582. /** \ingroup poll
  1583. * Determine if an active thread is handling events (i.e. if anyone is holding
  1584. * the event handling lock).
  1585. *
  1586. * \param ctx the context to operate on, or NULL for the default context
  1587. * \returns 1 if a thread is handling events
  1588. * \returns 0 if there are no threads currently handling events
  1589. * \see \ref mtasync
  1590. */
  1591. int API_EXPORTED libusb_event_handler_active(libusb_context *ctx)
  1592. {
  1593. int r;
  1594. USBI_GET_CONTEXT(ctx);
  1595. /* is someone else waiting to modify poll fds? if so, don't let this thread
  1596. * start event handling -- indicate that event handling is happening */
  1597. usbi_mutex_lock(&ctx->pollfd_modify_lock);
  1598. r = ctx->pollfd_modify;
  1599. usbi_mutex_unlock(&ctx->pollfd_modify_lock);
  1600. if (r) {
  1601. usbi_dbg("someone else is modifying poll fds");
  1602. return 1;
  1603. }
  1604. return ctx->event_handler_active;
  1605. }
  1606. /** \ingroup poll
  1607. * Acquire the event waiters lock. This lock is designed to be obtained under
  1608. * the situation where you want to be aware when events are completed, but
  1609. * some other thread is event handling so calling libusb_handle_events() is not
  1610. * allowed.
  1611. *
  1612. * You then obtain this lock, re-check that another thread is still handling
  1613. * events, then call libusb_wait_for_event().
  1614. *
  1615. * You only need to use this lock if you are developing an application
  1616. * which calls poll() or select() on libusb's file descriptors directly,
  1617. * <b>and</b> may potentially be handling events from 2 threads simultaenously.
  1618. * If you stick to libusb's event handling loop functions (e.g.
  1619. * libusb_handle_events()) then you do not need to be concerned with this
  1620. * locking.
  1621. *
  1622. * \param ctx the context to operate on, or NULL for the default context
  1623. * \see \ref mtasync
  1624. */
  1625. void API_EXPORTED libusb_lock_event_waiters(libusb_context *ctx)
  1626. {
  1627. USBI_GET_CONTEXT(ctx);
  1628. usbi_mutex_lock(&ctx->event_waiters_lock);
  1629. }
  1630. /** \ingroup poll
  1631. * Release the event waiters lock.
  1632. * \param ctx the context to operate on, or NULL for the default context
  1633. * \see \ref mtasync
  1634. */
  1635. void API_EXPORTED libusb_unlock_event_waiters(libusb_context *ctx)
  1636. {
  1637. USBI_GET_CONTEXT(ctx);
  1638. usbi_mutex_unlock(&ctx->event_waiters_lock);
  1639. }
  1640. /** \ingroup poll
  1641. * Wait for another thread to signal completion of an event. Must be called
  1642. * with the event waiters lock held, see libusb_lock_event_waiters().
  1643. *
  1644. * This function will block until any of the following conditions are met:
  1645. * -# The timeout expires
  1646. * -# A transfer completes
  1647. * -# A thread releases the event handling lock through libusb_unlock_events()
  1648. *
  1649. * Condition 1 is obvious. Condition 2 unblocks your thread <em>after</em>
  1650. * the callback for the transfer has completed. Condition 3 is important
  1651. * because it means that the thread that was previously handling events is no
  1652. * longer doing so, so if any events are to complete, another thread needs to
  1653. * step up and start event handling.
  1654. *
  1655. * This function releases the event waiters lock before putting your thread
  1656. * to sleep, and reacquires the lock as it is being woken up.
  1657. *
  1658. * \param ctx the context to operate on, or NULL for the default context
  1659. * \param tv maximum timeout for this blocking function. A NULL value
  1660. * indicates unlimited timeout.
  1661. * \returns 0 after a transfer completes or another thread stops event handling
  1662. * \returns 1 if the timeout expired
  1663. * \see \ref mtasync
  1664. */
  1665. int API_EXPORTED libusb_wait_for_event(libusb_context *ctx, struct timeval *tv)
  1666. {
  1667. struct timespec timeout;
  1668. int r;
  1669. USBI_GET_CONTEXT(ctx);
  1670. if (tv == NULL) {
  1671. usbi_cond_wait(&ctx->event_waiters_cond, &ctx->event_waiters_lock);
  1672. return 0;
  1673. }
  1674. r = usbi_backend->clock_gettime(USBI_CLOCK_REALTIME, &timeout);
  1675. if (r < 0) {
  1676. usbi_err(ctx, "failed to read realtime clock, error %d", errno);
  1677. return LIBUSB_ERROR_OTHER;
  1678. }
  1679. timeout.tv_sec += tv->tv_sec;
  1680. timeout.tv_nsec += tv->tv_usec * 1000;
  1681. while (timeout.tv_nsec >= 1000000000) {
  1682. timeout.tv_nsec -= 1000000000;
  1683. timeout.tv_sec++;
  1684. }
  1685. r = usbi_cond_timedwait(&ctx->event_waiters_cond,
  1686. &ctx->event_waiters_lock, &timeout);
  1687. return (r == ETIMEDOUT);
  1688. }
  1689. static void handle_timeout(struct usbi_transfer *itransfer)
  1690. {
  1691. struct libusb_transfer *transfer =
  1692. USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1693. int r;
  1694. itransfer->flags |= USBI_TRANSFER_TIMED_OUT;
  1695. r = libusb_cancel_transfer(transfer);
  1696. if (r < 0)
  1697. usbi_warn(TRANSFER_CTX(transfer),
  1698. "async cancel failed %d errno=%d", r, errno);
  1699. }
  1700. static int handle_timeouts_locked(struct libusb_context *ctx)
  1701. {
  1702. int r;
  1703. struct timespec systime_ts;
  1704. struct timeval systime;
  1705. struct usbi_transfer *transfer;
  1706. if (list_empty(&ctx->flying_transfers))
  1707. return 0;
  1708. /* get current time */
  1709. r = usbi_backend->clock_gettime(USBI_CLOCK_MONOTONIC, &systime_ts);
  1710. if (r < 0)
  1711. return r;
  1712. TIMESPEC_TO_TIMEVAL(&systime, &systime_ts);
  1713. /* iterate through flying transfers list, finding all transfers that
  1714. * have expired timeouts */
  1715. list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) {
  1716. struct timeval *cur_tv = &transfer->timeout;
  1717. /* if we've reached transfers of infinite timeout, we're all done */
  1718. if (!timerisset(cur_tv))
  1719. return 0;
  1720. /* ignore timeouts we've already handled */
  1721. if (transfer->flags & (USBI_TRANSFER_TIMED_OUT | USBI_TRANSFER_OS_HANDLES_TIMEOUT))
  1722. continue;
  1723. /* if transfer has non-expired timeout, nothing more to do */
  1724. if ((cur_tv->tv_sec > systime.tv_sec) ||
  1725. (cur_tv->tv_sec == systime.tv_sec &&
  1726. cur_tv->tv_usec > systime.tv_usec))
  1727. return 0;
  1728. /* otherwise, we've got an expired timeout to handle */
  1729. handle_timeout(transfer);
  1730. }
  1731. return 0;
  1732. }
  1733. static int handle_timeouts(struct libusb_context *ctx)
  1734. {
  1735. int r;
  1736. USBI_GET_CONTEXT(ctx);
  1737. usbi_mutex_lock(&ctx->flying_transfers_lock);
  1738. r = handle_timeouts_locked(ctx);
  1739. usbi_mutex_unlock(&ctx->flying_transfers_lock);
  1740. return r;
  1741. }
  1742. #ifdef USBI_TIMERFD_AVAILABLE
  1743. static int handle_timerfd_trigger(struct libusb_context *ctx)
  1744. {
  1745. int r;
  1746. r = disarm_timerfd(ctx);
  1747. if (r < 0)
  1748. return r;
  1749. usbi_mutex_lock(&ctx->flying_transfers_lock);
  1750. /* process the timeout that just happened */
  1751. r = handle_timeouts_locked(ctx);
  1752. if (r < 0)
  1753. goto out;
  1754. /* arm for next timeout*/
  1755. r = arm_timerfd_for_next_timeout(ctx);
  1756. out:
  1757. usbi_mutex_unlock(&ctx->flying_transfers_lock);
  1758. return r;
  1759. }
  1760. #endif
  1761. /* do the actual event handling. assumes that no other thread is concurrently
  1762. * doing the same thing. */
  1763. static int handle_events(struct libusb_context *ctx, struct timeval *tv)
  1764. {
  1765. int r;
  1766. struct usbi_pollfd *ipollfd;
  1767. POLL_NFDS_TYPE nfds = 0;
  1768. struct pollfd *fds;
  1769. int i = -1;
  1770. int timeout_ms;
  1771. usbi_mutex_lock(&ctx->pollfds_lock);
  1772. list_for_each_entry(ipollfd, &ctx->pollfds, list, struct usbi_pollfd)
  1773. nfds++;
  1774. /* TODO: malloc when number of fd's changes, not on every poll */
  1775. fds = malloc(sizeof(*fds) * nfds);
  1776. if (!fds) {
  1777. usbi_mutex_unlock(&ctx->pollfds_lock);
  1778. return LIBUSB_ERROR_NO_MEM;
  1779. }
  1780. list_for_each_entry(ipollfd, &ctx->pollfds, list, struct usbi_pollfd) {
  1781. struct libusb_pollfd *pollfd = &ipollfd->pollfd;
  1782. int fd = pollfd->fd;
  1783. i++;
  1784. fds[i].fd = fd;
  1785. fds[i].events = pollfd->events;
  1786. fds[i].revents = 0;
  1787. }
  1788. usbi_mutex_unlock(&ctx->pollfds_lock);
  1789. timeout_ms = (tv->tv_sec * 1000) + (tv->tv_usec / 1000);
  1790. /* round up to next millisecond */
  1791. if (tv->tv_usec % 1000)
  1792. timeout_ms++;
  1793. usbi_dbg("poll() %d fds with timeout in %dms", nfds, timeout_ms);
  1794. r = usbi_poll(fds, nfds, timeout_ms);
  1795. usbi_dbg("poll() returned %d", r);
  1796. if (r == 0) {
  1797. free(fds);
  1798. return handle_timeouts(ctx);
  1799. } else if (r == -1 && errno == EINTR) {
  1800. free(fds);
  1801. return LIBUSB_ERROR_INTERRUPTED;
  1802. } else if (r < 0) {
  1803. free(fds);
  1804. usbi_err(ctx, "poll failed %d err=%d\n", r, errno);
  1805. return LIBUSB_ERROR_IO;
  1806. }
  1807. /* fd[0] is always the ctrl pipe */
  1808. if (fds[0].revents) {
  1809. /* another thread wanted to interrupt event handling, and it succeeded!
  1810. * handle any other events that cropped up at the same time, and
  1811. * simply return */
  1812. usbi_dbg("caught a fish on the control pipe");
  1813. if (r == 1) {
  1814. r = 0;
  1815. goto handled;
  1816. } else {
  1817. /* prevent OS backend from trying to handle events on ctrl pipe */
  1818. fds[0].revents = 0;
  1819. r--;
  1820. }
  1821. }
  1822. /* fd[1] is always the hotplug pipe */
  1823. if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG) && fds[1].revents) {
  1824. libusb_hotplug_message message;
  1825. unsigned int ret;
  1826. /* read the message from the hotplug thread */
  1827. ret = read(ctx->hotplug_pipe[0], &message, sizeof (message));
  1828. if (ret < sizeof(message)) {
  1829. ret = LIBUSB_ERROR_OTHER;
  1830. goto handled;
  1831. }
  1832. usbi_hotplug_match(message.device, message.event);
  1833. /* the device left. dereference the device */
  1834. if (LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT == message.event)
  1835. libusb_unref_device(message.device);
  1836. fds[1].revents = 0;
  1837. if (1 == r--)
  1838. goto handled;
  1839. } /* else there shouldn't be anything on this pipe */
  1840. #ifdef USBI_TIMERFD_AVAILABLE
  1841. /* on timerfd configurations, fds[2] is the timerfd */
  1842. if (usbi_using_timerfd(ctx) && fds[2].revents) {
  1843. /* timerfd indicates that a timeout has expired */
  1844. int ret;
  1845. usbi_dbg("timerfd triggered");
  1846. ret = handle_timerfd_trigger(ctx);
  1847. if (ret < 0) {
  1848. /* return error code */
  1849. r = ret;
  1850. goto handled;
  1851. } else if (r == 1) {
  1852. /* no more active file descriptors, nothing more to do */
  1853. r = 0;
  1854. goto handled;
  1855. } else {
  1856. /* more events pending...
  1857. * prevent OS backend from trying to handle events on timerfd */
  1858. fds[2].revents = 0;
  1859. r--;
  1860. }
  1861. }
  1862. #endif
  1863. r = usbi_backend->handle_events(ctx, fds, nfds, r);
  1864. if (r)
  1865. usbi_err(ctx, "backend handle_events failed with error %d", r);
  1866. handled:
  1867. free(fds);
  1868. return r;
  1869. }
  1870. /* returns the smallest of:
  1871. * 1. timeout of next URB
  1872. * 2. user-supplied timeout
  1873. * returns 1 if there is an already-expired timeout, otherwise returns 0
  1874. * and populates out
  1875. */
  1876. static int get_next_timeout(libusb_context *ctx, struct timeval *tv,
  1877. struct timeval *out)
  1878. {
  1879. struct timeval timeout;
  1880. int r = libusb_get_next_timeout(ctx, &timeout);
  1881. if (r) {
  1882. /* timeout already expired? */
  1883. if (!timerisset(&timeout))
  1884. return 1;
  1885. /* choose the smallest of next URB timeout or user specified timeout */
  1886. if (timercmp(&timeout, tv, <))
  1887. *out = timeout;
  1888. else
  1889. *out = *tv;
  1890. } else {
  1891. *out = *tv;
  1892. }
  1893. return 0;
  1894. }
  1895. /** \ingroup poll
  1896. * Handle any pending events.
  1897. *
  1898. * libusb determines "pending events" by checking if any timeouts have expired
  1899. * and by checking the set of file descriptors for activity.
  1900. *
  1901. * If a zero timeval is passed, this function will handle any already-pending
  1902. * events and then immediately return in non-blocking style.
  1903. *
  1904. * If a non-zero timeval is passed and no events are currently pending, this
  1905. * function will block waiting for events to handle up until the specified
  1906. * timeout. If an event arrives or a signal is raised, this function will
  1907. * return early.
  1908. *
  1909. * If the parameter completed is not NULL then <em>after obtaining the event
  1910. * handling lock</em> this function will return immediately if the integer
  1911. * pointed to is not 0. This allows for race free waiting for the completion
  1912. * of a specific transfer.
  1913. *
  1914. * \param ctx the context to operate on, or NULL for the default context
  1915. * \param tv the maximum time to block waiting for events, or an all zero
  1916. * timeval struct for non-blocking mode
  1917. * \param completed pointer to completion integer to check, or NULL
  1918. * \returns 0 on success, or a LIBUSB_ERROR code on failure
  1919. * \see \ref mtasync
  1920. */
  1921. int API_EXPORTED libusb_handle_events_timeout_completed(libusb_context *ctx,
  1922. struct timeval *tv, int *completed)
  1923. {
  1924. int r;
  1925. struct timeval poll_timeout;
  1926. USBI_GET_CONTEXT(ctx);
  1927. r = get_next_timeout(ctx, tv, &poll_timeout);
  1928. if (r) {
  1929. /* timeout already expired */
  1930. return handle_timeouts(ctx);
  1931. }
  1932. retry:
  1933. if (libusb_try_lock_events(ctx) == 0) {
  1934. if (completed == NULL || !*completed) {
  1935. /* we obtained the event lock: do our own event handling */
  1936. usbi_dbg("doing our own event handling");
  1937. r = handle_events(ctx, &poll_timeout);
  1938. }
  1939. libusb_unlock_events(ctx);
  1940. return r;
  1941. }
  1942. /* another thread is doing event handling. wait for thread events that
  1943. * notify event completion. */
  1944. libusb_lock_event_waiters(ctx);
  1945. if (completed && *completed)
  1946. goto already_done;
  1947. if (!libusb_event_handler_active(ctx)) {
  1948. /* we hit a race: whoever was event handling earlier finished in the
  1949. * time it took us to reach this point. try the cycle again. */
  1950. libusb_unlock_event_waiters(ctx);
  1951. usbi_dbg("event handler was active but went away, retrying");
  1952. goto retry;
  1953. }
  1954. usbi_dbg("another thread is doing event handling");
  1955. r = libusb_wait_for_event(ctx, &poll_timeout);
  1956. already_done:
  1957. libusb_unlock_event_waiters(ctx);
  1958. if (r < 0)
  1959. return r;
  1960. else if (r == 1)
  1961. return handle_timeouts(ctx);
  1962. else
  1963. return 0;
  1964. }
  1965. /** \ingroup poll
  1966. * Handle any pending events
  1967. *
  1968. * Like libusb_handle_events_timeout_completed(), but without the completed
  1969. * parameter, calling this function is equivalent to calling
  1970. * libusb_handle_events_timeout_completed() with a NULL completed parameter.
  1971. *
  1972. * This function is kept primarily for backwards compatibility.
  1973. * All new code should call libusb_handle_events_completed() or
  1974. * libusb_handle_events_timeout_completed() to avoid race conditions.
  1975. *
  1976. * \param ctx the context to operate on, or NULL for the default context
  1977. * \param tv the maximum time to block waiting for events, or an all zero
  1978. * timeval struct for non-blocking mode
  1979. * \returns 0 on success, or a LIBUSB_ERROR code on failure
  1980. */
  1981. int API_EXPORTED libusb_handle_events_timeout(libusb_context *ctx,
  1982. struct timeval *tv)
  1983. {
  1984. return libusb_handle_events_timeout_completed(ctx, tv, NULL);
  1985. }
  1986. /** \ingroup poll
  1987. * Handle any pending events in blocking mode. There is currently a timeout
  1988. * hardcoded at 60 seconds but we plan to make it unlimited in future. For
  1989. * finer control over whether this function is blocking or non-blocking, or
  1990. * for control over the timeout, use libusb_handle_events_timeout_completed()
  1991. * instead.
  1992. *
  1993. * This function is kept primarily for backwards compatibility.
  1994. * All new code should call libusb_handle_events_completed() or
  1995. * libusb_handle_events_timeout_completed() to avoid race conditions.
  1996. *
  1997. * \param ctx the context to operate on, or NULL for the default context
  1998. * \returns 0 on success, or a LIBUSB_ERROR code on failure
  1999. */
  2000. int API_EXPORTED libusb_handle_events(libusb_context *ctx)
  2001. {
  2002. struct timeval tv;
  2003. tv.tv_sec = 60;
  2004. tv.tv_usec = 0;
  2005. return libusb_handle_events_timeout_completed(ctx, &tv, NULL);
  2006. }
  2007. /** \ingroup poll
  2008. * Handle any pending events in blocking mode.
  2009. *
  2010. * Like libusb_handle_events(), with the addition of a completed parameter
  2011. * to allow for race free waiting for the completion of a specific transfer.
  2012. *
  2013. * See libusb_handle_events_timeout_completed() for details on the completed
  2014. * parameter.
  2015. *
  2016. * \param ctx the context to operate on, or NULL for the default context
  2017. * \param completed pointer to completion integer to check, or NULL
  2018. * \returns 0 on success, or a LIBUSB_ERROR code on failure
  2019. * \see \ref mtasync
  2020. */
  2021. int API_EXPORTED libusb_handle_events_completed(libusb_context *ctx,
  2022. int *completed)
  2023. {
  2024. struct timeval tv;
  2025. tv.tv_sec = 60;
  2026. tv.tv_usec = 0;
  2027. return libusb_handle_events_timeout_completed(ctx, &tv, completed);
  2028. }
  2029. /** \ingroup poll
  2030. * Handle any pending events by polling file descriptors, without checking if
  2031. * any other threads are already doing so. Must be called with the event lock
  2032. * held, see libusb_lock_events().
  2033. *
  2034. * This function is designed to be called under the situation where you have
  2035. * taken the event lock and are calling poll()/select() directly on libusb's
  2036. * file descriptors (as opposed to using libusb_handle_events() or similar).
  2037. * You detect events on libusb's descriptors, so you then call this function
  2038. * with a zero timeout value (while still holding the event lock).
  2039. *
  2040. * \param ctx the context to operate on, or NULL for the default context
  2041. * \param tv the maximum time to block waiting for events, or zero for
  2042. * non-blocking mode
  2043. * \returns 0 on success, or a LIBUSB_ERROR code on failure
  2044. * \see \ref mtasync
  2045. */
  2046. int API_EXPORTED libusb_handle_events_locked(libusb_context *ctx,
  2047. struct timeval *tv)
  2048. {
  2049. int r;
  2050. struct timeval poll_timeout;
  2051. USBI_GET_CONTEXT(ctx);
  2052. r = get_next_timeout(ctx, tv, &poll_timeout);
  2053. if (r) {
  2054. /* timeout already expired */
  2055. return handle_timeouts(ctx);
  2056. }
  2057. return handle_events(ctx, &poll_timeout);
  2058. }
  2059. /** \ingroup poll
  2060. * Determines whether your application must apply special timing considerations
  2061. * when monitoring libusb's file descriptors.
  2062. *
  2063. * This function is only useful for applications which retrieve and poll
  2064. * libusb's file descriptors in their own main loop (\ref pollmain).
  2065. *
  2066. * Ordinarily, libusb's event handler needs to be called into at specific
  2067. * moments in time (in addition to times when there is activity on the file
  2068. * descriptor set). The usual approach is to use libusb_get_next_timeout()
  2069. * to learn about when the next timeout occurs, and to adjust your
  2070. * poll()/select() timeout accordingly so that you can make a call into the
  2071. * library at that time.
  2072. *
  2073. * Some platforms supported by libusb do not come with this baggage - any
  2074. * events relevant to timing will be represented by activity on the file
  2075. * descriptor set, and libusb_get_next_timeout() will always return 0.
  2076. * This function allows you to detect whether you are running on such a
  2077. * platform.
  2078. *
  2079. * Since v1.0.5.
  2080. *
  2081. * \param ctx the context to operate on, or NULL for the default context
  2082. * \returns 0 if you must call into libusb at times determined by
  2083. * libusb_get_next_timeout(), or 1 if all timeout events are handled internally
  2084. * or through regular activity on the file descriptors.
  2085. * \see \ref pollmain "Polling libusb file descriptors for event handling"
  2086. */
  2087. int API_EXPORTED libusb_pollfds_handle_timeouts(libusb_context *ctx)
  2088. {
  2089. #if defined(USBI_TIMERFD_AVAILABLE)
  2090. USBI_GET_CONTEXT(ctx);
  2091. return usbi_using_timerfd(ctx);
  2092. #else
  2093. (void)ctx;
  2094. return 0;
  2095. #endif
  2096. }
  2097. /** \ingroup poll
  2098. * Determine the next internal timeout that libusb needs to handle. You only
  2099. * need to use this function if you are calling poll() or select() or similar
  2100. * on libusb's file descriptors yourself - you do not need to use it if you
  2101. * are calling libusb_handle_events() or a variant directly.
  2102. *
  2103. * You should call this function in your main loop in order to determine how
  2104. * long to wait for select() or poll() to return results. libusb needs to be
  2105. * called into at this timeout, so you should use it as an upper bound on
  2106. * your select() or poll() call.
  2107. *
  2108. * When the timeout has expired, call into libusb_handle_events_timeout()
  2109. * (perhaps in non-blocking mode) so that libusb can handle the timeout.
  2110. *
  2111. * This function may return 1 (success) and an all-zero timeval. If this is
  2112. * the case, it indicates that libusb has a timeout that has already expired
  2113. * so you should call libusb_handle_events_timeout() or similar immediately.
  2114. * A return code of 0 indicates that there are no pending timeouts.
  2115. *
  2116. * On some platforms, this function will always returns 0 (no pending
  2117. * timeouts). See \ref polltime.
  2118. *
  2119. * \param ctx the context to operate on, or NULL for the default context
  2120. * \param tv output location for a relative time against the current
  2121. * clock in which libusb must be called into in order to process timeout events
  2122. * \returns 0 if there are no pending timeouts, 1 if a timeout was returned,
  2123. * or LIBUSB_ERROR_OTHER on failure
  2124. */
  2125. int API_EXPORTED libusb_get_next_timeout(libusb_context *ctx,
  2126. struct timeval *tv)
  2127. {
  2128. struct usbi_transfer *transfer;
  2129. struct timespec cur_ts;
  2130. struct timeval cur_tv;
  2131. struct timeval *next_timeout;
  2132. int r;
  2133. int found = 0;
  2134. USBI_GET_CONTEXT(ctx);
  2135. if (usbi_using_timerfd(ctx))
  2136. return 0;
  2137. usbi_mutex_lock(&ctx->flying_transfers_lock);
  2138. if (list_empty(&ctx->flying_transfers)) {
  2139. usbi_mutex_unlock(&ctx->flying_transfers_lock);
  2140. usbi_dbg("no URBs, no timeout!");
  2141. return 0;
  2142. }
  2143. /* find next transfer which hasn't already been processed as timed out */
  2144. list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) {
  2145. if (transfer->flags & (USBI_TRANSFER_TIMED_OUT | USBI_TRANSFER_OS_HANDLES_TIMEOUT))
  2146. continue;
  2147. /* no timeout for this transfer? */
  2148. if (!timerisset(&transfer->timeout))
  2149. continue;
  2150. found = 1;
  2151. break;
  2152. }
  2153. usbi_mutex_unlock(&ctx->flying_transfers_lock);
  2154. if (!found) {
  2155. usbi_dbg("no URB with timeout or all handled by OS; no timeout!");
  2156. return 0;
  2157. }
  2158. next_timeout = &transfer->timeout;
  2159. r = usbi_backend->clock_gettime(USBI_CLOCK_MONOTONIC, &cur_ts);
  2160. if (r < 0) {
  2161. usbi_err(ctx, "failed to read monotonic clock, errno=%d", errno);
  2162. return LIBUSB_ERROR_OTHER;
  2163. }
  2164. TIMESPEC_TO_TIMEVAL(&cur_tv, &cur_ts);
  2165. if (!timercmp(&cur_tv, next_timeout, <)) {
  2166. usbi_dbg("first timeout already expired");
  2167. timerclear(tv);
  2168. } else {
  2169. timersub(next_timeout, &cur_tv, tv);
  2170. usbi_dbg("next timeout in %d.%06ds", tv->tv_sec, tv->tv_usec);
  2171. }
  2172. return 1;
  2173. }
  2174. /** \ingroup poll
  2175. * Register notification functions for file descriptor additions/removals.
  2176. * These functions will be invoked for every new or removed file descriptor
  2177. * that libusb uses as an event source.
  2178. *
  2179. * To remove notifiers, pass NULL values for the function pointers.
  2180. *
  2181. * Note that file descriptors may have been added even before you register
  2182. * these notifiers (e.g. at libusb_init() time).
  2183. *
  2184. * Additionally, note that the removal notifier may be called during
  2185. * libusb_exit() (e.g. when it is closing file descriptors that were opened
  2186. * and added to the poll set at libusb_init() time). If you don't want this,
  2187. * remove the notifiers immediately before calling libusb_exit().
  2188. *
  2189. * \param ctx the context to operate on, or NULL for the default context
  2190. * \param added_cb pointer to function for addition notifications
  2191. * \param removed_cb pointer to function for removal notifications
  2192. * \param user_data User data to be passed back to callbacks (useful for
  2193. * passing context information)
  2194. */
  2195. void API_EXPORTED libusb_set_pollfd_notifiers(libusb_context *ctx,
  2196. libusb_pollfd_added_cb added_cb, libusb_pollfd_removed_cb removed_cb,
  2197. void *user_data)
  2198. {
  2199. USBI_GET_CONTEXT(ctx);
  2200. ctx->fd_added_cb = added_cb;
  2201. ctx->fd_removed_cb = removed_cb;
  2202. ctx->fd_cb_user_data = user_data;
  2203. }
  2204. /* Add a file descriptor to the list of file descriptors to be monitored.
  2205. * events should be specified as a bitmask of events passed to poll(), e.g.
  2206. * POLLIN and/or POLLOUT. */
  2207. int usbi_add_pollfd(struct libusb_context *ctx, int fd, short events)
  2208. {
  2209. struct usbi_pollfd *ipollfd = malloc(sizeof(*ipollfd));
  2210. if (!ipollfd)
  2211. return LIBUSB_ERROR_NO_MEM;
  2212. usbi_dbg("add fd %d events %d", fd, events);
  2213. ipollfd->pollfd.fd = fd;
  2214. ipollfd->pollfd.events = events;
  2215. usbi_mutex_lock(&ctx->pollfds_lock);
  2216. list_add_tail(&ipollfd->list, &ctx->pollfds);
  2217. usbi_mutex_unlock(&ctx->pollfds_lock);
  2218. if (ctx->fd_added_cb)
  2219. ctx->fd_added_cb(fd, events, ctx->fd_cb_user_data);
  2220. return 0;
  2221. }
  2222. /* Remove a file descriptor from the list of file descriptors to be polled. */
  2223. void usbi_remove_pollfd(struct libusb_context *ctx, int fd)
  2224. {
  2225. struct usbi_pollfd *ipollfd;
  2226. int found = 0;
  2227. usbi_dbg("remove fd %d", fd);
  2228. usbi_mutex_lock(&ctx->pollfds_lock);
  2229. list_for_each_entry(ipollfd, &ctx->pollfds, list, struct usbi_pollfd)
  2230. if (ipollfd->pollfd.fd == fd) {
  2231. found = 1;
  2232. break;
  2233. }
  2234. if (!found) {
  2235. usbi_dbg("couldn't find fd %d to remove", fd);
  2236. usbi_mutex_unlock(&ctx->pollfds_lock);
  2237. return;
  2238. }
  2239. list_del(&ipollfd->list);
  2240. usbi_mutex_unlock(&ctx->pollfds_lock);
  2241. free(ipollfd);
  2242. if (ctx->fd_removed_cb)
  2243. ctx->fd_removed_cb(fd, ctx->fd_cb_user_data);
  2244. }
  2245. /** \ingroup poll
  2246. * Retrieve a list of file descriptors that should be polled by your main loop
  2247. * as libusb event sources.
  2248. *
  2249. * The returned list is NULL-terminated and should be freed with free() when
  2250. * done. The actual list contents must not be touched.
  2251. *
  2252. * As file descriptors are a Unix-specific concept, this function is not
  2253. * available on Windows and will always return NULL.
  2254. *
  2255. * \param ctx the context to operate on, or NULL for the default context
  2256. * \returns a NULL-terminated list of libusb_pollfd structures
  2257. * \returns NULL on error
  2258. * \returns NULL on platforms where the functionality is not available
  2259. */
  2260. DEFAULT_VISIBILITY
  2261. const struct libusb_pollfd ** LIBUSB_CALL libusb_get_pollfds(
  2262. libusb_context *ctx)
  2263. {
  2264. #ifndef OS_WINDOWS
  2265. struct libusb_pollfd **ret = NULL;
  2266. struct usbi_pollfd *ipollfd;
  2267. size_t i = 0;
  2268. size_t cnt = 0;
  2269. USBI_GET_CONTEXT(ctx);
  2270. usbi_mutex_lock(&ctx->pollfds_lock);
  2271. list_for_each_entry(ipollfd, &ctx->pollfds, list, struct usbi_pollfd)
  2272. cnt++;
  2273. ret = calloc(cnt + 1, sizeof(struct libusb_pollfd *));
  2274. if (!ret)
  2275. goto out;
  2276. list_for_each_entry(ipollfd, &ctx->pollfds, list, struct usbi_pollfd)
  2277. ret[i++] = (struct libusb_pollfd *) ipollfd;
  2278. ret[cnt] = NULL;
  2279. out:
  2280. usbi_mutex_unlock(&ctx->pollfds_lock);
  2281. return (const struct libusb_pollfd **) ret;
  2282. #else
  2283. usbi_err(ctx, "external polling of libusb's internal descriptors "\
  2284. "is not yet supported on Windows platforms");
  2285. return NULL;
  2286. #endif
  2287. }
  2288. /* Backends call this from handle_events to report disconnection of a device.
  2289. * The transfers get cancelled appropriately.
  2290. */
  2291. void usbi_handle_disconnect(struct libusb_device_handle *handle)
  2292. {
  2293. struct usbi_transfer *cur;
  2294. struct usbi_transfer *to_cancel;
  2295. usbi_dbg("device %d.%d",
  2296. handle->dev->bus_number, handle->dev->device_address);
  2297. /* terminate all pending transfers with the LIBUSB_TRANSFER_NO_DEVICE
  2298. * status code.
  2299. *
  2300. * this is a bit tricky because:
  2301. * 1. we can't do transfer completion while holding flying_transfers_lock
  2302. * 2. the transfers list can change underneath us - if we were to build a
  2303. * list of transfers to complete (while holding look), the situation
  2304. * might be different by the time we come to free them
  2305. *
  2306. * so we resort to a loop-based approach as below
  2307. * FIXME: is this still potentially racy?
  2308. */
  2309. while (1) {
  2310. usbi_mutex_lock(&HANDLE_CTX(handle)->flying_transfers_lock);
  2311. to_cancel = NULL;
  2312. list_for_each_entry(cur, &HANDLE_CTX(handle)->flying_transfers, list, struct usbi_transfer)
  2313. if (USBI_TRANSFER_TO_LIBUSB_TRANSFER(cur)->dev_handle == handle) {
  2314. to_cancel = cur;
  2315. break;
  2316. }
  2317. usbi_mutex_unlock(&HANDLE_CTX(handle)->flying_transfers_lock);
  2318. if (!to_cancel)
  2319. break;
  2320. usbi_backend->clear_transfer_priv(to_cancel);
  2321. usbi_handle_transfer_completion(to_cancel, LIBUSB_TRANSFER_NO_DEVICE);
  2322. }
  2323. }