io.c 108 KB

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