io.c 97 KB

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