linux_usbfs.c 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613
  1. /* -*- Mode: C; c-basic-offset:8 ; indent-tabs-mode:t -*- */
  2. /*
  3. * Linux usbfs backend for libusb
  4. * Copyright (C) 2007-2009 Daniel Drake <dsd@gentoo.org>
  5. * Copyright (c) 2001 Johannes Erdfelt <johannes@erdfelt.com>
  6. * Copyright (c) 2013 Nathan Hjelm <hjelmn@mac.com>
  7. *
  8. * This library is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * This library is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with this library; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. #include <config.h>
  23. #include <ctype.h>
  24. #include <dirent.h>
  25. #include <errno.h>
  26. #include <fcntl.h>
  27. #include <poll.h>
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #include <sys/ioctl.h>
  32. #include <sys/stat.h>
  33. #include <sys/types.h>
  34. #include <sys/utsname.h>
  35. #include <unistd.h>
  36. #include "libusb.h"
  37. #include "libusbi.h"
  38. #include "linux_usbfs.h"
  39. /* sysfs vs usbfs:
  40. * opening a usbfs node causes the device to be resumed, so we attempt to
  41. * avoid this during enumeration.
  42. *
  43. * sysfs allows us to read the kernel's in-memory copies of device descriptors
  44. * and so forth, avoiding the need to open the device:
  45. * - The binary "descriptors" file was added in 2.6.23.
  46. * - The "busnum" file was added in 2.6.22
  47. * - The "devnum" file has been present since pre-2.6.18
  48. * - the "bConfigurationValue" file has been present since pre-2.6.18
  49. *
  50. * If we have bConfigurationValue, busnum, and devnum, then we can determine
  51. * the active configuration without having to open the usbfs node in RDWR mode.
  52. * We assume this is the case if we see the busnum file (indicates 2.6.22+).
  53. * The busnum file is important as that is the only way we can relate sysfs
  54. * devices to usbfs nodes.
  55. *
  56. * If we also have descriptors, we can obtain the device descriptor and active
  57. * configuration without touching usbfs at all.
  58. *
  59. * The descriptors file originally only contained the active configuration
  60. * descriptor alongside the device descriptor, but all configurations are
  61. * included as of Linux 2.6.26.
  62. */
  63. /* endianness for multi-byte fields:
  64. *
  65. * Descriptors exposed by usbfs have the multi-byte fields in the device
  66. * descriptor as host endian. Multi-byte fields in the other descriptors are
  67. * bus-endian. The kernel documentation says otherwise, but it is wrong.
  68. */
  69. const char *usbfs_path = NULL;
  70. /* use usbdev*.* device names in /dev instead of the usbfs bus directories */
  71. static int usbdev_names = 0;
  72. /* Linux 2.6.32 adds support for a bulk continuation URB flag. this basically
  73. * allows us to mark URBs as being part of a specific logical transfer when
  74. * we submit them to the kernel. then, on any error except a cancellation, all
  75. * URBs within that transfer will be cancelled and no more URBs will be
  76. * accepted for the transfer, meaning that no more data can creep in.
  77. *
  78. * The BULK_CONTINUATION flag must be set on all URBs within a bulk transfer
  79. * (in either direction) except the first.
  80. * For IN transfers, we must also set SHORT_NOT_OK on all URBs except the
  81. * last; it means that the kernel should treat a short reply as an error.
  82. * For OUT transfers, SHORT_NOT_OK must not be set. it isn't needed (OUT
  83. * transfers can't be short unless there's already some sort of error), and
  84. * setting this flag is disallowed (a kernel with USB debugging enabled will
  85. * reject such URBs).
  86. */
  87. static int supports_flag_bulk_continuation = -1;
  88. /* Linux 2.6.31 fixes support for the zero length packet URB flag. This
  89. * allows us to mark URBs that should be followed by a zero length data
  90. * packet, which can be required by device- or class-specific protocols.
  91. */
  92. static int supports_flag_zero_packet = -1;
  93. /* clock ID for monotonic clock, as not all clock sources are available on all
  94. * systems. appropriate choice made at initialization time. */
  95. static clockid_t monotonic_clkid = -1;
  96. /* do we have a busnum to relate devices? this also implies that we can read
  97. * the active configuration through bConfigurationValue */
  98. static int sysfs_can_relate_devices = 0;
  99. /* do we have a descriptors file? */
  100. static int sysfs_has_descriptors = 0;
  101. /* how many times have we initted (and not exited) ? */
  102. static volatile int init_count = 0;
  103. /* lock for init_count */
  104. static pthread_mutex_t hotplug_lock = PTHREAD_MUTEX_INITIALIZER;
  105. static int linux_start_event_monitor(void);
  106. static int linux_stop_event_monitor(void);
  107. static int linux_scan_devices(struct libusb_context *ctx);
  108. #if !defined(USE_UDEV)
  109. static int linux_default_scan_devices (struct libusb_context *ctx);
  110. #endif
  111. struct linux_device_priv {
  112. char *sysfs_dir;
  113. unsigned char *dev_descriptor;
  114. unsigned char *config_descriptor;
  115. };
  116. struct linux_device_handle_priv {
  117. int fd;
  118. uint32_t caps;
  119. };
  120. enum reap_action {
  121. NORMAL = 0,
  122. /* submission failed after the first URB, so await cancellation/completion
  123. * of all the others */
  124. SUBMIT_FAILED,
  125. /* cancelled by user or timeout */
  126. CANCELLED,
  127. /* completed multi-URB transfer in non-final URB */
  128. COMPLETED_EARLY,
  129. /* one or more urbs encountered a low-level error */
  130. ERROR,
  131. };
  132. struct linux_transfer_priv {
  133. union {
  134. struct usbfs_urb *urbs;
  135. struct usbfs_urb **iso_urbs;
  136. };
  137. enum reap_action reap_action;
  138. int num_urbs;
  139. int num_retired;
  140. enum libusb_transfer_status reap_status;
  141. /* next iso packet in user-supplied transfer to be populated */
  142. int iso_packet_offset;
  143. };
  144. static void _get_usbfs_path(struct libusb_device *dev, char *path)
  145. {
  146. if (usbdev_names)
  147. snprintf(path, PATH_MAX, "%s/usbdev%d.%d",
  148. usbfs_path, dev->bus_number, dev->device_address);
  149. else
  150. snprintf(path, PATH_MAX, "%s/%03d/%03d",
  151. usbfs_path, dev->bus_number, dev->device_address);
  152. }
  153. static struct linux_device_priv *_device_priv(struct libusb_device *dev)
  154. {
  155. return (struct linux_device_priv *) dev->os_priv;
  156. }
  157. static struct linux_device_handle_priv *_device_handle_priv(
  158. struct libusb_device_handle *handle)
  159. {
  160. return (struct linux_device_handle_priv *) handle->os_priv;
  161. }
  162. /* check dirent for a /dev/usbdev%d.%d name
  163. * optionally return bus/device on success */
  164. static int _is_usbdev_entry(struct dirent *entry, int *bus_p, int *dev_p)
  165. {
  166. int busnum, devnum;
  167. if (sscanf(entry->d_name, "usbdev%d.%d", &busnum, &devnum) != 2)
  168. return 0;
  169. usbi_dbg("found: %s", entry->d_name);
  170. if (bus_p != NULL)
  171. *bus_p = busnum;
  172. if (dev_p != NULL)
  173. *dev_p = devnum;
  174. return 1;
  175. }
  176. static int check_usb_vfs(const char *dirname)
  177. {
  178. DIR *dir;
  179. struct dirent *entry;
  180. int found = 0;
  181. dir = opendir(dirname);
  182. if (!dir)
  183. return 0;
  184. while ((entry = readdir(dir)) != NULL) {
  185. if (entry->d_name[0] == '.')
  186. continue;
  187. /* We assume if we find any files that it must be the right place */
  188. found = 1;
  189. break;
  190. }
  191. closedir(dir);
  192. return found;
  193. }
  194. static const char *find_usbfs_path(void)
  195. {
  196. const char *path = "/dev/bus/usb";
  197. const char *ret = NULL;
  198. if (check_usb_vfs(path)) {
  199. ret = path;
  200. } else {
  201. path = "/proc/bus/usb";
  202. if (check_usb_vfs(path))
  203. ret = path;
  204. }
  205. /* look for /dev/usbdev*.* if the normal places fail */
  206. if (ret == NULL) {
  207. struct dirent *entry;
  208. DIR *dir;
  209. path = "/dev";
  210. dir = opendir(path);
  211. if (dir != NULL) {
  212. while ((entry = readdir(dir)) != NULL) {
  213. if (_is_usbdev_entry(entry, NULL, NULL)) {
  214. /* found one; that's enough */
  215. ret = path;
  216. usbdev_names = 1;
  217. break;
  218. }
  219. }
  220. closedir(dir);
  221. }
  222. }
  223. if (ret != NULL)
  224. usbi_dbg("found usbfs at %s", ret);
  225. return ret;
  226. }
  227. /* the monotonic clock is not usable on all systems (e.g. embedded ones often
  228. * seem to lack it). fall back to REALTIME if we have to. */
  229. static clockid_t find_monotonic_clock(void)
  230. {
  231. #ifdef CLOCK_MONOTONIC
  232. struct timespec ts;
  233. int r;
  234. /* Linux 2.6.28 adds CLOCK_MONOTONIC_RAW but we don't use it
  235. * because it's not available through timerfd */
  236. r = clock_gettime(CLOCK_MONOTONIC, &ts);
  237. if (r == 0)
  238. return CLOCK_MONOTONIC;
  239. usbi_dbg("monotonic clock doesn't work, errno %d", errno);
  240. #endif
  241. return CLOCK_REALTIME;
  242. }
  243. static int kernel_version_ge(int major, int minor, int sublevel)
  244. {
  245. struct utsname uts;
  246. int atoms, kmajor, kminor, ksublevel;
  247. if (uname(&uts) < 0)
  248. return -1;
  249. atoms = sscanf(uts.release, "%d.%d.%d", &kmajor, &kminor, &ksublevel);
  250. if (atoms < 1)
  251. return -1;
  252. if (kmajor > major)
  253. return 1;
  254. if (kmajor < major)
  255. return 0;
  256. /* kmajor == major */
  257. if (atoms < 2)
  258. return 0 == minor && 0 == sublevel;
  259. if (kminor > minor)
  260. return 1;
  261. if (kminor < minor)
  262. return 0;
  263. /* kminor == minor */
  264. if (atoms < 3)
  265. return 0 == sublevel;
  266. return ksublevel >= sublevel;
  267. }
  268. /* Return 1 if filename exists inside dirname in sysfs.
  269. SYSFS_DEVICE_PATH is assumed to be the beginning of the path. */
  270. static int sysfs_has_file(const char *dirname, const char *filename)
  271. {
  272. struct stat statbuf;
  273. char path[PATH_MAX];
  274. int r;
  275. snprintf(path, PATH_MAX, "%s/%s/%s", SYSFS_DEVICE_PATH, dirname, filename);
  276. r = stat(path, &statbuf);
  277. if (r == 0 && S_ISREG(statbuf.st_mode))
  278. return 1;
  279. return 0;
  280. }
  281. static int op_init(struct libusb_context *ctx)
  282. {
  283. struct stat statbuf;
  284. int r;
  285. usbfs_path = find_usbfs_path();
  286. if (!usbfs_path) {
  287. usbi_err(ctx, "could not find usbfs");
  288. return LIBUSB_ERROR_OTHER;
  289. }
  290. if (monotonic_clkid == -1)
  291. monotonic_clkid = find_monotonic_clock();
  292. if (supports_flag_bulk_continuation == -1) {
  293. /* bulk continuation URB flag available from Linux 2.6.32 */
  294. supports_flag_bulk_continuation = kernel_version_ge(2,6,32);
  295. if (supports_flag_bulk_continuation == -1) {
  296. usbi_err(ctx, "error checking for bulk continuation support");
  297. return LIBUSB_ERROR_OTHER;
  298. }
  299. }
  300. if (supports_flag_bulk_continuation)
  301. usbi_dbg("bulk continuation flag supported");
  302. if (-1 == supports_flag_zero_packet) {
  303. /* zero length packet URB flag fixed since Linux 2.6.31 */
  304. supports_flag_zero_packet = kernel_version_ge(2,6,31);
  305. if (-1 == supports_flag_zero_packet) {
  306. usbi_err(ctx, "error checking for zero length packet support");
  307. return LIBUSB_ERROR_OTHER;
  308. }
  309. }
  310. if (supports_flag_zero_packet)
  311. usbi_dbg("zero length packet flag supported");
  312. r = stat(SYSFS_DEVICE_PATH, &statbuf);
  313. if (r == 0 && S_ISDIR(statbuf.st_mode)) {
  314. DIR *devices = opendir(SYSFS_DEVICE_PATH);
  315. struct dirent *entry;
  316. usbi_dbg("found usb devices in sysfs");
  317. if (!devices) {
  318. usbi_err(ctx, "opendir devices failed errno=%d", errno);
  319. return LIBUSB_ERROR_IO;
  320. }
  321. /* Make sure sysfs supports all the required files. If it
  322. * does not, then usbfs will be used instead. Determine
  323. * this by looping through the directories in
  324. * SYSFS_DEVICE_PATH. With the assumption that there will
  325. * always be subdirectories of the name usbN (usb1, usb2,
  326. * etc) representing the root hubs, check the usbN
  327. * subdirectories to see if they have all the needed files.
  328. * This algorithm uses the usbN subdirectories (root hubs)
  329. * because a device disconnection will cause a race
  330. * condition regarding which files are available, sometimes
  331. * causing an incorrect result. The root hubs are used
  332. * because it is assumed that they will always be present.
  333. * See the "sysfs vs usbfs" comment at the top of this file
  334. * for more details. */
  335. while ((entry = readdir(devices))) {
  336. int has_busnum=0, has_devnum=0, has_descriptors=0;
  337. int has_configuration_value=0;
  338. /* Only check the usbN directories. */
  339. if (strncmp(entry->d_name, "usb", 3) != 0)
  340. continue;
  341. /* Check for the files libusb needs from sysfs. */
  342. has_busnum = sysfs_has_file(entry->d_name, "busnum");
  343. has_devnum = sysfs_has_file(entry->d_name, "devnum");
  344. has_descriptors = sysfs_has_file(entry->d_name, "descriptors");
  345. has_configuration_value = sysfs_has_file(entry->d_name, "bConfigurationValue");
  346. if (has_busnum && has_devnum && has_configuration_value)
  347. sysfs_can_relate_devices = 1;
  348. if (has_descriptors)
  349. sysfs_has_descriptors = 1;
  350. /* Only need to check until we've found ONE device which
  351. has all the attributes. */
  352. if (sysfs_has_descriptors && sysfs_can_relate_devices)
  353. break;
  354. }
  355. closedir(devices);
  356. /* Only use sysfs descriptors if the rest of
  357. sysfs will work for libusb. */
  358. if (!sysfs_can_relate_devices)
  359. sysfs_has_descriptors = 0;
  360. } else {
  361. usbi_dbg("sysfs usb info not available");
  362. sysfs_has_descriptors = 0;
  363. sysfs_can_relate_devices = 0;
  364. }
  365. pthread_mutex_lock(&hotplug_lock);
  366. if (!init_count++) {
  367. /* start up hotplug event handler */
  368. r = linux_start_event_monitor();
  369. if (LIBUSB_SUCCESS != r) {
  370. usbi_err(ctx, "error starting hotplug event monitor");
  371. return r;
  372. }
  373. }
  374. pthread_mutex_unlock(&hotplug_lock);
  375. r = linux_scan_devices(ctx);
  376. if (LIBUSB_SUCCESS != r) {
  377. return r;
  378. }
  379. return r;
  380. }
  381. static void op_exit(void)
  382. {
  383. if (!init_count) {
  384. /* should not happen */
  385. return;
  386. }
  387. pthread_mutex_lock(&hotplug_lock);
  388. if (!--init_count) {
  389. /* tear down event handler */
  390. (void)linux_stop_event_monitor();
  391. }
  392. pthread_mutex_unlock(&hotplug_lock);
  393. }
  394. static int linux_start_event_monitor(void)
  395. {
  396. #if defined(USE_UDEV)
  397. return linux_udev_start_event_monitor();
  398. #else
  399. return linux_netlink_start_event_monitor();
  400. #endif
  401. }
  402. static int linux_stop_event_monitor(void)
  403. {
  404. #if defined(USE_UDEV)
  405. return linux_udev_stop_event_monitor();
  406. #else
  407. return linux_netlink_stop_event_monitor();
  408. #endif
  409. }
  410. static int linux_scan_devices(struct libusb_context *ctx)
  411. {
  412. #if defined(USE_UDEV)
  413. return linux_udev_scan_devices(ctx);
  414. #else
  415. return linux_default_scan_devices(ctx);
  416. #endif
  417. }
  418. static int usbfs_get_device_descriptor(struct libusb_device *dev,
  419. unsigned char *buffer)
  420. {
  421. struct linux_device_priv *priv = _device_priv(dev);
  422. /* return cached copy */
  423. memcpy(buffer, priv->dev_descriptor, DEVICE_DESC_LENGTH);
  424. return 0;
  425. }
  426. static int _open_sysfs_attr(struct libusb_device *dev, const char *attr)
  427. {
  428. struct linux_device_priv *priv = _device_priv(dev);
  429. char filename[PATH_MAX];
  430. int fd;
  431. snprintf(filename, PATH_MAX, "%s/%s/%s",
  432. SYSFS_DEVICE_PATH, priv->sysfs_dir, attr);
  433. fd = open(filename, O_RDONLY);
  434. if (fd < 0) {
  435. usbi_err(DEVICE_CTX(dev),
  436. "open %s failed ret=%d errno=%d", filename, fd, errno);
  437. return LIBUSB_ERROR_IO;
  438. }
  439. return fd;
  440. }
  441. /* Note only suitable for attributes which always read >= 0, < 0 is error */
  442. static int __read_sysfs_attr(struct libusb_context *ctx,
  443. const char *devname, const char *attr)
  444. {
  445. char filename[PATH_MAX];
  446. FILE *f;
  447. int r, value;
  448. snprintf(filename, PATH_MAX, "%s/%s/%s", SYSFS_DEVICE_PATH,
  449. devname, attr);
  450. f = fopen(filename, "r");
  451. if (f == NULL) {
  452. if (errno == ENOENT) {
  453. /* File doesn't exist. Assume the device has been
  454. disconnected (see trac ticket #70). */
  455. return LIBUSB_ERROR_NO_DEVICE;
  456. }
  457. usbi_err(ctx, "open %s failed errno=%d", filename, errno);
  458. return LIBUSB_ERROR_IO;
  459. }
  460. r = fscanf(f, "%d", &value);
  461. fclose(f);
  462. if (r != 1) {
  463. usbi_err(ctx, "fscanf %s returned %d, errno=%d", attr, r, errno);
  464. return LIBUSB_ERROR_NO_DEVICE; /* For unplug race (trac #70) */
  465. }
  466. if (value < 0) {
  467. usbi_err(ctx, "%s contains a negative value", filename);
  468. return LIBUSB_ERROR_IO;
  469. }
  470. return value;
  471. }
  472. static int sysfs_get_device_descriptor(struct libusb_device *dev,
  473. unsigned char *buffer)
  474. {
  475. int fd;
  476. ssize_t r;
  477. /* sysfs provides access to an in-memory copy of the device descriptor,
  478. * so we use that rather than keeping our own copy */
  479. fd = _open_sysfs_attr(dev, "descriptors");
  480. if (fd < 0)
  481. return fd;
  482. r = read(fd, buffer, DEVICE_DESC_LENGTH);;
  483. close(fd);
  484. if (r < 0) {
  485. usbi_err(DEVICE_CTX(dev), "read failed, ret=%d errno=%d", fd, errno);
  486. return LIBUSB_ERROR_IO;
  487. } else if (r < DEVICE_DESC_LENGTH) {
  488. usbi_err(DEVICE_CTX(dev), "short read %d/%d", r, DEVICE_DESC_LENGTH);
  489. return LIBUSB_ERROR_IO;
  490. }
  491. return 0;
  492. }
  493. static int op_get_device_descriptor(struct libusb_device *dev,
  494. unsigned char *buffer, int *host_endian)
  495. {
  496. if (sysfs_has_descriptors) {
  497. *host_endian = 0;
  498. return sysfs_get_device_descriptor(dev, buffer);
  499. } else {
  500. *host_endian = 1;
  501. return usbfs_get_device_descriptor(dev, buffer);
  502. }
  503. }
  504. static int usbfs_get_active_config_descriptor(struct libusb_device *dev,
  505. unsigned char *buffer, size_t len)
  506. {
  507. struct linux_device_priv *priv = _device_priv(dev);
  508. if (!priv->config_descriptor)
  509. return LIBUSB_ERROR_NOT_FOUND; /* device is unconfigured */
  510. /* retrieve cached copy */
  511. memcpy(buffer, priv->config_descriptor, len);
  512. return 0;
  513. }
  514. /* read the bConfigurationValue for a device */
  515. static int sysfs_get_active_config(struct libusb_device *dev, int *config)
  516. {
  517. char *endptr;
  518. char tmp[4] = {0, 0, 0, 0};
  519. long num;
  520. int fd;
  521. ssize_t r;
  522. fd = _open_sysfs_attr(dev, "bConfigurationValue");
  523. if (fd < 0)
  524. return fd;
  525. r = read(fd, tmp, sizeof(tmp));
  526. close(fd);
  527. if (r < 0) {
  528. usbi_err(DEVICE_CTX(dev),
  529. "read bConfigurationValue failed ret=%d errno=%d", r, errno);
  530. return LIBUSB_ERROR_IO;
  531. } else if (r == 0) {
  532. usbi_dbg("device unconfigured");
  533. *config = -1;
  534. return 0;
  535. }
  536. if (tmp[sizeof(tmp) - 1] != 0) {
  537. usbi_err(DEVICE_CTX(dev), "not null-terminated?");
  538. return LIBUSB_ERROR_IO;
  539. } else if (tmp[0] == 0) {
  540. usbi_err(DEVICE_CTX(dev), "no configuration value?");
  541. return LIBUSB_ERROR_IO;
  542. }
  543. num = strtol(tmp, &endptr, 10);
  544. if (endptr == tmp) {
  545. usbi_err(DEVICE_CTX(dev), "error converting '%s' to integer", tmp);
  546. return LIBUSB_ERROR_IO;
  547. }
  548. *config = (int) num;
  549. return 0;
  550. }
  551. /* takes a usbfs/descriptors fd seeked to the start of a configuration, and
  552. * seeks to the next one. */
  553. static int seek_to_next_config(struct libusb_context *ctx, int fd,
  554. int host_endian)
  555. {
  556. struct libusb_config_descriptor config;
  557. unsigned char tmp[6];
  558. off_t off;
  559. ssize_t r;
  560. /* read first 6 bytes of descriptor */
  561. r = read(fd, tmp, sizeof(tmp));
  562. if (r < 0) {
  563. usbi_err(ctx, "read failed ret=%d errno=%d", r, errno);
  564. return LIBUSB_ERROR_IO;
  565. } else if (r < (ssize_t)sizeof(tmp)) {
  566. usbi_err(ctx, "short descriptor read %d/%d", r, sizeof(tmp));
  567. return LIBUSB_ERROR_IO;
  568. }
  569. /* seek forward to end of config */
  570. usbi_parse_descriptor(tmp, "bbwbb", &config, host_endian);
  571. off = lseek(fd, config.wTotalLength - sizeof(tmp), SEEK_CUR);
  572. if (off < 0) {
  573. usbi_err(ctx, "seek failed ret=%d errno=%d", off, errno);
  574. return LIBUSB_ERROR_IO;
  575. }
  576. return 0;
  577. }
  578. static int sysfs_get_active_config_descriptor(struct libusb_device *dev,
  579. unsigned char *buffer, size_t len)
  580. {
  581. int fd;
  582. ssize_t r;
  583. off_t off;
  584. int to_copy;
  585. int config;
  586. unsigned char tmp[6];
  587. r = sysfs_get_active_config(dev, &config);
  588. if (r < 0)
  589. return r;
  590. if (config == -1)
  591. return LIBUSB_ERROR_NOT_FOUND;
  592. usbi_dbg("active configuration %d", config);
  593. /* sysfs provides access to an in-memory copy of the device descriptor,
  594. * so we use that rather than keeping our own copy */
  595. fd = _open_sysfs_attr(dev, "descriptors");
  596. if (fd < 0)
  597. return fd;
  598. /* device might have been unconfigured since we read bConfigurationValue,
  599. * so first check that there is any config descriptor data at all... */
  600. off = lseek(fd, 0, SEEK_END);
  601. if (off < 1) {
  602. usbi_err(DEVICE_CTX(dev), "end seek failed, ret=%d errno=%d",
  603. off, errno);
  604. close(fd);
  605. return LIBUSB_ERROR_IO;
  606. } else if (off == DEVICE_DESC_LENGTH) {
  607. close(fd);
  608. return LIBUSB_ERROR_NOT_FOUND;
  609. }
  610. off = lseek(fd, DEVICE_DESC_LENGTH, SEEK_SET);
  611. if (off < 0) {
  612. usbi_err(DEVICE_CTX(dev), "seek failed, ret=%d errno=%d", off, errno);
  613. close(fd);
  614. return LIBUSB_ERROR_IO;
  615. }
  616. /* unbounded loop: we expect the descriptor to be present under all
  617. * circumstances */
  618. while (1) {
  619. r = read(fd, tmp, sizeof(tmp));
  620. if (r < 0) {
  621. usbi_err(DEVICE_CTX(dev), "read failed, ret=%d errno=%d",
  622. fd, errno);
  623. return LIBUSB_ERROR_IO;
  624. } else if (r < (ssize_t)sizeof(tmp)) {
  625. usbi_err(DEVICE_CTX(dev), "short read %d/%d", r, sizeof(tmp));
  626. return LIBUSB_ERROR_IO;
  627. }
  628. /* check bConfigurationValue */
  629. if (tmp[5] == config)
  630. break;
  631. /* try the next descriptor */
  632. off = lseek(fd, 0 - sizeof(tmp), SEEK_CUR);
  633. if (off < 0)
  634. return LIBUSB_ERROR_IO;
  635. r = seek_to_next_config(DEVICE_CTX(dev), fd, 0);
  636. if (r < 0)
  637. return r;
  638. }
  639. to_copy = (len < sizeof(tmp)) ? len : sizeof(tmp);
  640. memcpy(buffer, tmp, to_copy);
  641. if (len > sizeof(tmp)) {
  642. r = read(fd, buffer + sizeof(tmp), len - sizeof(tmp));
  643. if (r < 0) {
  644. usbi_err(DEVICE_CTX(dev), "read failed, ret=%d errno=%d",
  645. fd, errno);
  646. r = LIBUSB_ERROR_IO;
  647. } else if (r == 0) {
  648. usbi_dbg("device is unconfigured");
  649. r = LIBUSB_ERROR_NOT_FOUND;
  650. } else if ((size_t)r < len - sizeof(tmp)) {
  651. usbi_err(DEVICE_CTX(dev), "short read %d/%d", r, len);
  652. r = LIBUSB_ERROR_IO;
  653. }
  654. } else {
  655. r = 0;
  656. }
  657. close(fd);
  658. return r;
  659. }
  660. int linux_get_device_address (struct libusb_context *ctx, int detached,
  661. uint8_t *busnum, uint8_t *devaddr,
  662. const char *dev_node, const char *sys_name)
  663. {
  664. int retbus, retdev;
  665. usbi_dbg("getting address for device: %s detached: %d",
  666. sys_name, detached);
  667. /* can't use sysfs to read the bus and device number if the
  668. device has been detached */
  669. if (!sysfs_can_relate_devices || detached || NULL == sys_name) {
  670. if (NULL == dev_node) {
  671. return LIBUSB_ERROR_OTHER;
  672. }
  673. /* will this work with all supported kernel versions? */
  674. if (!strncmp(dev_node, "/dev/bus/usb", 12)) {
  675. sscanf (dev_node, "/dev/bus/usb/%hhd/%hhd", busnum, devaddr);
  676. } else if (!strncmp(dev_node, "/proc/bus/usb", 13)) {
  677. sscanf (dev_node, "/proc/bus/usb/%hhd/%hhd", busnum, devaddr);
  678. }
  679. return LIBUSB_SUCCESS;
  680. }
  681. usbi_dbg("scan %s", sys_name);
  682. *busnum = retbus = __read_sysfs_attr(ctx, sys_name, "busnum");
  683. if (retbus < 0)
  684. return retbus;
  685. *devaddr = retdev = __read_sysfs_attr(ctx, sys_name, "devnum");
  686. if (retdev < 0)
  687. return retdev;
  688. usbi_dbg("bus=%d dev=%d", *busnum, *devaddr);
  689. if (retbus > 255 || retdev > 255)
  690. return LIBUSB_ERROR_INVALID_PARAM;
  691. return LIBUSB_SUCCESS;
  692. }
  693. static int op_get_active_config_descriptor(struct libusb_device *dev,
  694. unsigned char *buffer, size_t len, int *host_endian)
  695. {
  696. *host_endian = *host_endian;
  697. if (sysfs_has_descriptors) {
  698. return sysfs_get_active_config_descriptor(dev, buffer, len);
  699. } else {
  700. return usbfs_get_active_config_descriptor(dev, buffer, len);
  701. }
  702. }
  703. /* takes a usbfs fd, attempts to find the requested config and copy a certain
  704. * amount of it into an output buffer. */
  705. static int get_config_descriptor(struct libusb_context *ctx, int fd,
  706. uint8_t config_index, unsigned char *buffer, size_t len)
  707. {
  708. off_t off;
  709. ssize_t r;
  710. off = lseek(fd, DEVICE_DESC_LENGTH, SEEK_SET);
  711. if (off < 0) {
  712. usbi_err(ctx, "seek failed ret=%d errno=%d", off, errno);
  713. return LIBUSB_ERROR_IO;
  714. }
  715. /* might need to skip some configuration descriptors to reach the
  716. * requested configuration */
  717. while (config_index > 0) {
  718. r = seek_to_next_config(ctx, fd, 1);
  719. if (r < 0)
  720. return r;
  721. config_index--;
  722. }
  723. /* read the rest of the descriptor */
  724. r = read(fd, buffer, len);
  725. if (r < 0) {
  726. usbi_err(ctx, "read failed ret=%d errno=%d", r, errno);
  727. return LIBUSB_ERROR_IO;
  728. } else if ((size_t)r < len) {
  729. usbi_err(ctx, "short output read %d/%d", r, len);
  730. return LIBUSB_ERROR_IO;
  731. }
  732. return 0;
  733. }
  734. static int op_get_config_descriptor(struct libusb_device *dev,
  735. uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
  736. {
  737. char filename[PATH_MAX];
  738. int fd;
  739. int r;
  740. *host_endian = *host_endian;
  741. /* always read from usbfs: sysfs only has the active descriptor
  742. * this will involve waking the device up, but oh well! */
  743. /* FIXME: the above is no longer true, new kernels have all descriptors
  744. * in the descriptors file. but its kinda hard to detect if the kernel
  745. * is sufficiently new. */
  746. _get_usbfs_path(dev, filename);
  747. fd = open(filename, O_RDONLY);
  748. if (fd < 0) {
  749. usbi_err(DEVICE_CTX(dev),
  750. "open '%s' failed, ret=%d errno=%d", filename, fd, errno);
  751. return LIBUSB_ERROR_IO;
  752. }
  753. r = get_config_descriptor(DEVICE_CTX(dev), fd, config_index, buffer, len);
  754. close(fd);
  755. return r;
  756. }
  757. /* cache the active config descriptor in memory. a value of -1 means that
  758. * we aren't sure which one is active, so just assume the first one.
  759. * only for usbfs. */
  760. static int cache_active_config(struct libusb_device *dev, int fd,
  761. int active_config)
  762. {
  763. struct linux_device_priv *priv = _device_priv(dev);
  764. struct libusb_config_descriptor config;
  765. unsigned char tmp[8];
  766. unsigned char *buf;
  767. int idx;
  768. int r;
  769. if (active_config == -1) {
  770. idx = 0;
  771. } else {
  772. r = usbi_get_config_index_by_value(dev, active_config, &idx);
  773. if (r < 0)
  774. return r;
  775. if (idx == -1)
  776. return LIBUSB_ERROR_NOT_FOUND;
  777. }
  778. r = get_config_descriptor(DEVICE_CTX(dev), fd, idx, tmp, sizeof(tmp));
  779. if (r < 0) {
  780. usbi_err(DEVICE_CTX(dev), "first read error %d", r);
  781. return r;
  782. }
  783. usbi_parse_descriptor(tmp, "bbw", &config, 0);
  784. buf = malloc(config.wTotalLength);
  785. if (!buf)
  786. return LIBUSB_ERROR_NO_MEM;
  787. r = get_config_descriptor(DEVICE_CTX(dev), fd, idx, buf,
  788. config.wTotalLength);
  789. if (r < 0) {
  790. free(buf);
  791. return r;
  792. }
  793. if (priv->config_descriptor)
  794. free(priv->config_descriptor);
  795. priv->config_descriptor = buf;
  796. return 0;
  797. }
  798. /* send a control message to retrieve active configuration */
  799. static int usbfs_get_active_config(struct libusb_device *dev, int fd)
  800. {
  801. unsigned char active_config = 0;
  802. int r;
  803. struct usbfs_ctrltransfer ctrl = {
  804. .bmRequestType = LIBUSB_ENDPOINT_IN,
  805. .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
  806. .wValue = 0,
  807. .wIndex = 0,
  808. .wLength = 1,
  809. .timeout = 1000,
  810. .data = &active_config
  811. };
  812. r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
  813. if (r < 0) {
  814. if (errno == ENODEV)
  815. return LIBUSB_ERROR_NO_DEVICE;
  816. /* we hit this error path frequently with buggy devices :( */
  817. usbi_warn(DEVICE_CTX(dev),
  818. "get_configuration failed ret=%d errno=%d", r, errno);
  819. return LIBUSB_ERROR_IO;
  820. }
  821. return active_config;
  822. }
  823. static int initialize_device(struct libusb_device *dev, uint8_t busnum,
  824. uint8_t devaddr, const char *sysfs_dir)
  825. {
  826. struct linux_device_priv *priv = _device_priv(dev);
  827. unsigned char *dev_buf;
  828. char path[PATH_MAX];
  829. int fd, speed;
  830. int active_config = 0;
  831. int device_configured = 1;
  832. ssize_t r;
  833. dev->bus_number = busnum;
  834. dev->device_address = devaddr;
  835. if (sysfs_dir) {
  836. priv->sysfs_dir = malloc(strlen(sysfs_dir) + 1);
  837. if (!priv->sysfs_dir)
  838. return LIBUSB_ERROR_NO_MEM;
  839. strcpy(priv->sysfs_dir, sysfs_dir);
  840. /* Note speed can contain 1.5, in this case __read_sysfs_attr
  841. will stop parsing at the '.' and return 1 */
  842. speed = __read_sysfs_attr(DEVICE_CTX(dev), sysfs_dir, "speed");
  843. if (speed >= 0) {
  844. switch (speed) {
  845. case 1: dev->speed = LIBUSB_SPEED_LOW; break;
  846. case 12: dev->speed = LIBUSB_SPEED_FULL; break;
  847. case 480: dev->speed = LIBUSB_SPEED_HIGH; break;
  848. case 5000: dev->speed = LIBUSB_SPEED_SUPER; break;
  849. default:
  850. usbi_warn(DEVICE_CTX(dev), "Unknown device speed: %d Mbps", speed);
  851. }
  852. }
  853. }
  854. if (sysfs_has_descriptors)
  855. return 0;
  856. /* cache device descriptor in memory so that we can retrieve it later
  857. * without waking the device up (op_get_device_descriptor) */
  858. priv->dev_descriptor = NULL;
  859. priv->config_descriptor = NULL;
  860. if (sysfs_can_relate_devices) {
  861. int tmp = sysfs_get_active_config(dev, &active_config);
  862. if (tmp < 0)
  863. return tmp;
  864. if (active_config == -1)
  865. device_configured = 0;
  866. }
  867. _get_usbfs_path(dev, path);
  868. fd = open(path, O_RDWR);
  869. if (fd < 0 && errno == EACCES) {
  870. fd = open(path, O_RDONLY);
  871. /* if we only have read-only access to the device, we cannot
  872. * send a control message to determine the active config. just
  873. * assume the first one is active. */
  874. active_config = -1;
  875. }
  876. if (fd < 0) {
  877. usbi_err(DEVICE_CTX(dev), "open failed, ret=%d errno=%d", fd, errno);
  878. return LIBUSB_ERROR_IO;
  879. }
  880. if (!sysfs_can_relate_devices) {
  881. if (active_config == -1) {
  882. /* if we only have read-only access to the device, we cannot
  883. * send a control message to determine the active config. just
  884. * assume the first one is active. */
  885. usbi_warn(DEVICE_CTX(dev), "access to %s is read-only; cannot "
  886. "determine active configuration descriptor", path);
  887. } else {
  888. active_config = usbfs_get_active_config(dev, fd);
  889. if (active_config == LIBUSB_ERROR_IO) {
  890. /* buggy devices sometimes fail to report their active config.
  891. * assume unconfigured and continue the probing */
  892. usbi_warn(DEVICE_CTX(dev), "couldn't query active "
  893. "configuration, assumung unconfigured");
  894. device_configured = 0;
  895. } else if (active_config < 0) {
  896. close(fd);
  897. return active_config;
  898. } else if (active_config == 0) {
  899. /* some buggy devices have a configuration 0, but we're
  900. * reaching into the corner of a corner case here, so let's
  901. * not support buggy devices in these circumstances.
  902. * stick to the specs: a configuration value of 0 means
  903. * unconfigured. */
  904. usbi_dbg("active cfg 0? assuming unconfigured device");
  905. device_configured = 0;
  906. }
  907. }
  908. }
  909. dev_buf = malloc(DEVICE_DESC_LENGTH);
  910. if (!dev_buf) {
  911. close(fd);
  912. return LIBUSB_ERROR_NO_MEM;
  913. }
  914. r = read(fd, dev_buf, DEVICE_DESC_LENGTH);
  915. if (r < 0) {
  916. usbi_err(DEVICE_CTX(dev),
  917. "read descriptor failed ret=%d errno=%d", fd, errno);
  918. free(dev_buf);
  919. close(fd);
  920. return LIBUSB_ERROR_IO;
  921. } else if (r < DEVICE_DESC_LENGTH) {
  922. usbi_err(DEVICE_CTX(dev), "short descriptor read (%d)", r);
  923. free(dev_buf);
  924. close(fd);
  925. return LIBUSB_ERROR_IO;
  926. }
  927. /* bit of a hack: set num_configurations now because cache_active_config()
  928. * calls usbi_get_config_index_by_value() which uses it */
  929. dev->num_configurations = dev_buf[DEVICE_DESC_LENGTH - 1];
  930. if (device_configured) {
  931. r = cache_active_config(dev, fd, active_config);
  932. if (r < 0) {
  933. close(fd);
  934. free(dev_buf);
  935. return r;
  936. }
  937. }
  938. close(fd);
  939. priv->dev_descriptor = dev_buf;
  940. return 0;
  941. }
  942. int linux_enumerate_device(struct libusb_context *ctx,
  943. uint8_t busnum, uint8_t devaddr,
  944. const char *sysfs_dir)
  945. {
  946. unsigned long session_id;
  947. struct libusb_device *dev;
  948. int r = 0;
  949. /* FIXME: session ID is not guaranteed unique as addresses can wrap and
  950. * will be reused. instead we should add a simple sysfs attribute with
  951. * a session ID. */
  952. session_id = busnum << 8 | devaddr;
  953. usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr,
  954. session_id);
  955. usbi_dbg("allocating new device for %d/%d (session %ld)",
  956. busnum, devaddr, session_id);
  957. dev = usbi_alloc_device(ctx, session_id);
  958. if (!dev)
  959. return LIBUSB_ERROR_NO_MEM;
  960. r = initialize_device(dev, busnum, devaddr, sysfs_dir);
  961. if (r < 0)
  962. goto out;
  963. r = usbi_sanitize_device(dev);
  964. if (r < 0)
  965. goto out;
  966. out:
  967. if (r < 0)
  968. libusb_unref_device(dev);
  969. else
  970. usbi_connect_device(dev);
  971. return r;
  972. }
  973. void linux_hotplug_enumerate(uint8_t busnum, uint8_t devaddr, const char *sys_name)
  974. {
  975. struct libusb_context *ctx;
  976. usbi_mutex_lock(&active_contexts_lock);
  977. list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
  978. if (usbi_get_device_by_session_id(ctx, busnum << 8 | devaddr)) {
  979. /* device already exists in the context */
  980. usbi_dbg("device already exists in context");
  981. continue;
  982. }
  983. linux_enumerate_device(ctx, busnum, devaddr, sys_name);
  984. }
  985. usbi_mutex_unlock(&active_contexts_lock);
  986. }
  987. void linux_hotplug_disconnected(uint8_t busnum, uint8_t devaddr, const char *sys_name)
  988. {
  989. struct libusb_context *ctx, *tmp;
  990. struct libusb_device *dev;
  991. usbi_mutex_lock(&active_contexts_lock);
  992. list_for_each_entry_safe(ctx, tmp, &active_contexts_list, list, struct libusb_context) {
  993. dev = usbi_get_device_by_session_id (ctx, busnum << 8 | devaddr);
  994. if (NULL != dev) {
  995. usbi_disconnect_device (dev);
  996. } else {
  997. usbi_err(ctx, "device not found for session %x %s", busnum << 8 | devaddr, sys_name);
  998. }
  999. }
  1000. usbi_mutex_unlock(&active_contexts_lock);
  1001. }
  1002. #if !defined(USE_UDEV)
  1003. /* open a bus directory and adds all discovered devices to the context */
  1004. static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum)
  1005. {
  1006. DIR *dir;
  1007. char dirpath[PATH_MAX];
  1008. struct dirent *entry;
  1009. int r = LIBUSB_ERROR_IO;
  1010. snprintf(dirpath, PATH_MAX, "%s/%03d", usbfs_path, busnum);
  1011. usbi_dbg("%s", dirpath);
  1012. dir = opendir(dirpath);
  1013. if (!dir) {
  1014. usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
  1015. /* FIXME: should handle valid race conditions like hub unplugged
  1016. * during directory iteration - this is not an error */
  1017. return r;
  1018. }
  1019. while ((entry = readdir(dir))) {
  1020. int devaddr;
  1021. if (entry->d_name[0] == '.')
  1022. continue;
  1023. devaddr = atoi(entry->d_name);
  1024. if (devaddr == 0) {
  1025. usbi_dbg("unknown dir entry %s", entry->d_name);
  1026. continue;
  1027. }
  1028. if (linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL)) {
  1029. usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
  1030. continue;
  1031. }
  1032. r = 0;
  1033. }
  1034. closedir(dir);
  1035. return r;
  1036. }
  1037. static int usbfs_get_device_list(struct libusb_context *ctx)
  1038. {
  1039. struct dirent *entry;
  1040. DIR *buses = opendir(usbfs_path);
  1041. int r = 0;
  1042. if (!buses) {
  1043. usbi_err(ctx, "opendir buses failed errno=%d", errno);
  1044. return LIBUSB_ERROR_IO;
  1045. }
  1046. while ((entry = readdir(buses))) {
  1047. int busnum;
  1048. if (entry->d_name[0] == '.')
  1049. continue;
  1050. if (usbdev_names) {
  1051. int devaddr;
  1052. if (!_is_usbdev_entry(entry, &busnum, &devaddr))
  1053. continue;
  1054. r = linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL);
  1055. if (r < 0) {
  1056. usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
  1057. continue;
  1058. }
  1059. } else {
  1060. busnum = atoi(entry->d_name);
  1061. if (busnum == 0) {
  1062. usbi_dbg("unknown dir entry %s", entry->d_name);
  1063. continue;
  1064. }
  1065. r = usbfs_scan_busdir(ctx, busnum);
  1066. if (r < 0)
  1067. break;
  1068. }
  1069. }
  1070. closedir(buses);
  1071. return r;
  1072. }
  1073. static int sysfs_scan_device(struct libusb_context *ctx, const char *devname)
  1074. {
  1075. uint8_t busnum, devaddr;
  1076. int ret;
  1077. ret = linux_get_device_address (ctx, 0, &busnum, &devaddr, NULL, devname);
  1078. if (LIBUSB_SUCCESS != ret) {
  1079. return ret;
  1080. }
  1081. return linux_enumerate_device(ctx, busnum & 0xff, devaddr & 0xff,
  1082. devname);
  1083. }
  1084. static int sysfs_get_device_list(struct libusb_context *ctx)
  1085. {
  1086. DIR *devices = opendir(SYSFS_DEVICE_PATH);
  1087. struct dirent *entry;
  1088. int r = LIBUSB_ERROR_IO;
  1089. if (!devices) {
  1090. usbi_err(ctx, "opendir devices failed errno=%d", errno);
  1091. return r;
  1092. }
  1093. while ((entry = readdir(devices))) {
  1094. if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
  1095. || strchr(entry->d_name, ':'))
  1096. continue;
  1097. if (sysfs_scan_device(ctx, entry->d_name)) {
  1098. usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
  1099. continue;
  1100. }
  1101. r = 0;
  1102. }
  1103. closedir(devices);
  1104. return r;
  1105. }
  1106. static int linux_default_scan_devices (struct libusb_context *ctx)
  1107. {
  1108. /* we can retrieve device list and descriptors from sysfs or usbfs.
  1109. * sysfs is preferable, because if we use usbfs we end up resuming
  1110. * any autosuspended USB devices. however, sysfs is not available
  1111. * everywhere, so we need a usbfs fallback too.
  1112. *
  1113. * as described in the "sysfs vs usbfs" comment at the top of this
  1114. * file, sometimes we have sysfs but not enough information to
  1115. * relate sysfs devices to usbfs nodes. op_init() determines the
  1116. * adequacy of sysfs and sets sysfs_can_relate_devices.
  1117. */
  1118. if (sysfs_can_relate_devices != 0)
  1119. return sysfs_get_device_list(ctx);
  1120. else
  1121. return usbfs_get_device_list(ctx);
  1122. }
  1123. #endif
  1124. static int op_open(struct libusb_device_handle *handle)
  1125. {
  1126. struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
  1127. char filename[PATH_MAX];
  1128. int r;
  1129. _get_usbfs_path(handle->dev, filename);
  1130. usbi_dbg("opening %s", filename);
  1131. hpriv->fd = open(filename, O_RDWR);
  1132. if (hpriv->fd < 0) {
  1133. if (errno == EACCES) {
  1134. usbi_err(HANDLE_CTX(handle), "libusb couldn't open USB device %s: "
  1135. "Permission denied.", filename);
  1136. usbi_err(HANDLE_CTX(handle),
  1137. "libusb requires write access to USB device nodes.");
  1138. return LIBUSB_ERROR_ACCESS;
  1139. } else if (errno == ENOENT) {
  1140. usbi_err(HANDLE_CTX(handle), "libusb couldn't open USB device %s: "
  1141. "No such file or directory.", filename);
  1142. return LIBUSB_ERROR_NO_DEVICE;
  1143. } else {
  1144. usbi_err(HANDLE_CTX(handle),
  1145. "open failed, code %d errno %d", hpriv->fd, errno);
  1146. return LIBUSB_ERROR_IO;
  1147. }
  1148. }
  1149. r = ioctl(hpriv->fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
  1150. if (r < 0) {
  1151. if (errno == ENOTTY)
  1152. usbi_dbg("%s: getcap not available", filename);
  1153. else
  1154. usbi_err(HANDLE_CTX(handle),
  1155. "%s: getcap failed (%d)", filename, errno);
  1156. hpriv->caps = 0;
  1157. if (supports_flag_zero_packet)
  1158. hpriv->caps |= USBFS_CAP_ZERO_PACKET;
  1159. if (supports_flag_bulk_continuation)
  1160. hpriv->caps |= USBFS_CAP_BULK_CONTINUATION;
  1161. }
  1162. return usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
  1163. }
  1164. static void op_close(struct libusb_device_handle *dev_handle)
  1165. {
  1166. int fd = _device_handle_priv(dev_handle)->fd;
  1167. usbi_remove_pollfd(HANDLE_CTX(dev_handle), fd);
  1168. close(fd);
  1169. }
  1170. static int op_get_configuration(struct libusb_device_handle *handle,
  1171. int *config)
  1172. {
  1173. int r;
  1174. if (sysfs_can_relate_devices != 1)
  1175. return LIBUSB_ERROR_NOT_SUPPORTED;
  1176. r = sysfs_get_active_config(handle->dev, config);
  1177. if (r < 0)
  1178. return r;
  1179. if (*config == -1) {
  1180. usbi_err(HANDLE_CTX(handle), "device unconfigured");
  1181. *config = 0;
  1182. }
  1183. return 0;
  1184. }
  1185. static int op_set_configuration(struct libusb_device_handle *handle, int config)
  1186. {
  1187. struct linux_device_priv *priv = _device_priv(handle->dev);
  1188. int fd = _device_handle_priv(handle)->fd;
  1189. int r = ioctl(fd, IOCTL_USBFS_SETCONFIG, &config);
  1190. if (r) {
  1191. if (errno == EINVAL)
  1192. return LIBUSB_ERROR_NOT_FOUND;
  1193. else if (errno == EBUSY)
  1194. return LIBUSB_ERROR_BUSY;
  1195. else if (errno == ENODEV)
  1196. return LIBUSB_ERROR_NO_DEVICE;
  1197. usbi_err(HANDLE_CTX(handle), "failed, error %d errno %d", r, errno);
  1198. return LIBUSB_ERROR_OTHER;
  1199. }
  1200. if (!sysfs_has_descriptors) {
  1201. /* update our cached active config descriptor */
  1202. if (config == -1) {
  1203. if (priv->config_descriptor) {
  1204. free(priv->config_descriptor);
  1205. priv->config_descriptor = NULL;
  1206. }
  1207. } else {
  1208. r = cache_active_config(handle->dev, fd, config);
  1209. if (r < 0)
  1210. usbi_warn(HANDLE_CTX(handle),
  1211. "failed to update cached config descriptor, error %d", r);
  1212. }
  1213. }
  1214. return 0;
  1215. }
  1216. static int op_claim_interface(struct libusb_device_handle *handle, int iface)
  1217. {
  1218. int fd = _device_handle_priv(handle)->fd;
  1219. int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface);
  1220. if (r) {
  1221. if (errno == ENOENT)
  1222. return LIBUSB_ERROR_NOT_FOUND;
  1223. else if (errno == EBUSY)
  1224. return LIBUSB_ERROR_BUSY;
  1225. else if (errno == ENODEV)
  1226. return LIBUSB_ERROR_NO_DEVICE;
  1227. usbi_err(HANDLE_CTX(handle),
  1228. "claim interface failed, error %d errno %d", r, errno);
  1229. return LIBUSB_ERROR_OTHER;
  1230. }
  1231. return 0;
  1232. }
  1233. static int op_release_interface(struct libusb_device_handle *handle, int iface)
  1234. {
  1235. int fd = _device_handle_priv(handle)->fd;
  1236. int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface);
  1237. if (r) {
  1238. if (errno == ENODEV)
  1239. return LIBUSB_ERROR_NO_DEVICE;
  1240. usbi_err(HANDLE_CTX(handle),
  1241. "release interface failed, error %d errno %d", r, errno);
  1242. return LIBUSB_ERROR_OTHER;
  1243. }
  1244. return 0;
  1245. }
  1246. static int op_set_interface(struct libusb_device_handle *handle, int iface,
  1247. int altsetting)
  1248. {
  1249. int fd = _device_handle_priv(handle)->fd;
  1250. struct usbfs_setinterface setintf;
  1251. int r;
  1252. setintf.interface = iface;
  1253. setintf.altsetting = altsetting;
  1254. r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf);
  1255. if (r) {
  1256. if (errno == EINVAL)
  1257. return LIBUSB_ERROR_NOT_FOUND;
  1258. else if (errno == ENODEV)
  1259. return LIBUSB_ERROR_NO_DEVICE;
  1260. usbi_err(HANDLE_CTX(handle),
  1261. "setintf failed error %d errno %d", r, errno);
  1262. return LIBUSB_ERROR_OTHER;
  1263. }
  1264. return 0;
  1265. }
  1266. static int op_clear_halt(struct libusb_device_handle *handle,
  1267. unsigned char endpoint)
  1268. {
  1269. int fd = _device_handle_priv(handle)->fd;
  1270. unsigned int _endpoint = endpoint;
  1271. int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
  1272. if (r) {
  1273. if (errno == ENOENT)
  1274. return LIBUSB_ERROR_NOT_FOUND;
  1275. else if (errno == ENODEV)
  1276. return LIBUSB_ERROR_NO_DEVICE;
  1277. usbi_err(HANDLE_CTX(handle),
  1278. "clear_halt failed error %d errno %d", r, errno);
  1279. return LIBUSB_ERROR_OTHER;
  1280. }
  1281. return 0;
  1282. }
  1283. static int op_reset_device(struct libusb_device_handle *handle)
  1284. {
  1285. int fd = _device_handle_priv(handle)->fd;
  1286. int i, r, ret = 0;
  1287. /* Doing a device reset will cause the usbfs driver to get unbound
  1288. from any interfaces it is bound to. By voluntarily unbinding
  1289. the usbfs driver ourself, we stop the kernel from rebinding
  1290. the interface after reset (which would end up with the interface
  1291. getting bound to the in kernel driver if any). */
  1292. for (i = 0; i < USB_MAXINTERFACES; i++) {
  1293. if (handle->claimed_interfaces & (1L << i)) {
  1294. op_release_interface(handle, i);
  1295. }
  1296. }
  1297. usbi_mutex_lock(&handle->lock);
  1298. r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
  1299. if (r) {
  1300. if (errno == ENODEV) {
  1301. ret = LIBUSB_ERROR_NOT_FOUND;
  1302. goto out;
  1303. }
  1304. usbi_err(HANDLE_CTX(handle),
  1305. "reset failed error %d errno %d", r, errno);
  1306. ret = LIBUSB_ERROR_OTHER;
  1307. goto out;
  1308. }
  1309. /* And re-claim any interfaces which were claimed before the reset */
  1310. for (i = 0; i < USB_MAXINTERFACES; i++) {
  1311. if (handle->claimed_interfaces & (1L << i)) {
  1312. r = op_claim_interface(handle, i);
  1313. if (r) {
  1314. usbi_warn(HANDLE_CTX(handle),
  1315. "failed to re-claim interface %d after reset", i);
  1316. handle->claimed_interfaces &= ~(1L << i);
  1317. }
  1318. }
  1319. }
  1320. out:
  1321. usbi_mutex_unlock(&handle->lock);
  1322. return ret;
  1323. }
  1324. static int op_kernel_driver_active(struct libusb_device_handle *handle,
  1325. int interface)
  1326. {
  1327. int fd = _device_handle_priv(handle)->fd;
  1328. struct usbfs_getdriver getdrv;
  1329. int r;
  1330. getdrv.interface = interface;
  1331. r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
  1332. if (r) {
  1333. if (errno == ENODATA)
  1334. return 0;
  1335. else if (errno == ENODEV)
  1336. return LIBUSB_ERROR_NO_DEVICE;
  1337. usbi_err(HANDLE_CTX(handle),
  1338. "get driver failed error %d errno %d", r, errno);
  1339. return LIBUSB_ERROR_OTHER;
  1340. }
  1341. return 1;
  1342. }
  1343. static int op_detach_kernel_driver(struct libusb_device_handle *handle,
  1344. int interface)
  1345. {
  1346. int fd = _device_handle_priv(handle)->fd;
  1347. struct usbfs_ioctl command;
  1348. int r;
  1349. command.ifno = interface;
  1350. command.ioctl_code = IOCTL_USBFS_DISCONNECT;
  1351. command.data = NULL;
  1352. r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
  1353. if (r) {
  1354. if (errno == ENODATA)
  1355. return LIBUSB_ERROR_NOT_FOUND;
  1356. else if (errno == EINVAL)
  1357. return LIBUSB_ERROR_INVALID_PARAM;
  1358. else if (errno == ENODEV)
  1359. return LIBUSB_ERROR_NO_DEVICE;
  1360. usbi_err(HANDLE_CTX(handle),
  1361. "detach failed error %d errno %d", r, errno);
  1362. return LIBUSB_ERROR_OTHER;
  1363. }
  1364. return 0;
  1365. }
  1366. static int op_attach_kernel_driver(struct libusb_device_handle *handle,
  1367. int interface)
  1368. {
  1369. int fd = _device_handle_priv(handle)->fd;
  1370. struct usbfs_ioctl command;
  1371. int r;
  1372. command.ifno = interface;
  1373. command.ioctl_code = IOCTL_USBFS_CONNECT;
  1374. command.data = NULL;
  1375. r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
  1376. if (r < 0) {
  1377. if (errno == ENODATA)
  1378. return LIBUSB_ERROR_NOT_FOUND;
  1379. else if (errno == EINVAL)
  1380. return LIBUSB_ERROR_INVALID_PARAM;
  1381. else if (errno == ENODEV)
  1382. return LIBUSB_ERROR_NO_DEVICE;
  1383. else if (errno == EBUSY)
  1384. return LIBUSB_ERROR_BUSY;
  1385. usbi_err(HANDLE_CTX(handle),
  1386. "attach failed error %d errno %d", r, errno);
  1387. return LIBUSB_ERROR_OTHER;
  1388. } else if (r == 0) {
  1389. return LIBUSB_ERROR_NOT_FOUND;
  1390. }
  1391. return 0;
  1392. }
  1393. static void op_destroy_device(struct libusb_device *dev)
  1394. {
  1395. struct linux_device_priv *priv = _device_priv(dev);
  1396. if (!sysfs_has_descriptors) {
  1397. if (priv->dev_descriptor)
  1398. free(priv->dev_descriptor);
  1399. if (priv->config_descriptor)
  1400. free(priv->config_descriptor);
  1401. }
  1402. if (priv->sysfs_dir)
  1403. free(priv->sysfs_dir);
  1404. }
  1405. /* URBs are discarded in reverse order of submission to avoid races. */
  1406. static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one)
  1407. {
  1408. struct libusb_transfer *transfer =
  1409. USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1410. struct linux_transfer_priv *tpriv =
  1411. usbi_transfer_get_os_priv(itransfer);
  1412. struct linux_device_handle_priv *dpriv =
  1413. _device_handle_priv(transfer->dev_handle);
  1414. int i, ret = 0;
  1415. struct usbfs_urb *urb;
  1416. for (i = last_plus_one - 1; i >= first; i--) {
  1417. if (LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type)
  1418. urb = tpriv->iso_urbs[i];
  1419. else
  1420. urb = &tpriv->urbs[i];
  1421. if (0 == ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urb))
  1422. continue;
  1423. if (EINVAL == errno) {
  1424. usbi_dbg("URB not found --> assuming ready to be reaped");
  1425. if (i == (last_plus_one - 1))
  1426. ret = LIBUSB_ERROR_NOT_FOUND;
  1427. } else if (ENODEV == errno) {
  1428. usbi_dbg("Device not found for URB --> assuming ready to be reaped");
  1429. ret = LIBUSB_ERROR_NO_DEVICE;
  1430. } else {
  1431. usbi_warn(TRANSFER_CTX(transfer),
  1432. "unrecognised discard errno %d", errno);
  1433. ret = LIBUSB_ERROR_OTHER;
  1434. }
  1435. }
  1436. return ret;
  1437. }
  1438. static void free_iso_urbs(struct linux_transfer_priv *tpriv)
  1439. {
  1440. int i;
  1441. for (i = 0; i < tpriv->num_urbs; i++) {
  1442. struct usbfs_urb *urb = tpriv->iso_urbs[i];
  1443. if (!urb)
  1444. break;
  1445. free(urb);
  1446. }
  1447. free(tpriv->iso_urbs);
  1448. tpriv->iso_urbs = NULL;
  1449. }
  1450. static int submit_bulk_transfer(struct usbi_transfer *itransfer,
  1451. unsigned char urb_type)
  1452. {
  1453. struct libusb_transfer *transfer =
  1454. USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1455. struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
  1456. struct linux_device_handle_priv *dpriv =
  1457. _device_handle_priv(transfer->dev_handle);
  1458. struct usbfs_urb *urbs;
  1459. int is_out = (transfer->endpoint & LIBUSB_ENDPOINT_DIR_MASK)
  1460. == LIBUSB_ENDPOINT_OUT;
  1461. int bulk_buffer_len, use_bulk_continuation;
  1462. int r;
  1463. int i;
  1464. size_t alloc_size;
  1465. if (tpriv->urbs)
  1466. return LIBUSB_ERROR_BUSY;
  1467. if (is_out && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) &&
  1468. !(dpriv->caps & USBFS_CAP_ZERO_PACKET))
  1469. return LIBUSB_ERROR_NOT_SUPPORTED;
  1470. /*
  1471. * Older versions of usbfs place a 16kb limit on bulk URBs. We work
  1472. * around this by splitting large transfers into 16k blocks, and then
  1473. * submit all urbs at once. it would be simpler to submit one urb at
  1474. * a time, but there is a big performance gain doing it this way.
  1475. *
  1476. * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
  1477. * using arbritary large transfers can still be a bad idea though, as
  1478. * the kernel needs to allocate physical contiguous memory for this,
  1479. * which may fail for large buffers.
  1480. *
  1481. * The kernel solves this problem by splitting the transfer into
  1482. * blocks itself when the host-controller is scatter-gather capable
  1483. * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
  1484. *
  1485. * Last, there is the issue of short-transfers when splitting, for
  1486. * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
  1487. * is needed, but this is not always available.
  1488. */
  1489. if (dpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
  1490. /* Good! Just submit everything in one go */
  1491. bulk_buffer_len = transfer->length ? transfer->length : 1;
  1492. use_bulk_continuation = 0;
  1493. } else if (dpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
  1494. /* Split the transfers and use bulk-continuation to
  1495. avoid issues with short-transfers */
  1496. bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
  1497. use_bulk_continuation = 1;
  1498. } else if (dpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
  1499. /* Don't split, assume the kernel can alloc the buffer
  1500. (otherwise the submit will fail with -ENOMEM) */
  1501. bulk_buffer_len = transfer->length ? transfer->length : 1;
  1502. use_bulk_continuation = 0;
  1503. } else {
  1504. /* Bad, splitting without bulk-continuation, short transfers
  1505. which end before the last urb will not work reliable! */
  1506. /* Note we don't warn here as this is "normal" on kernels <
  1507. 2.6.32 and not a problem for most applications */
  1508. bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
  1509. use_bulk_continuation = 0;
  1510. }
  1511. int num_urbs = transfer->length / bulk_buffer_len;
  1512. int last_urb_partial = 0;
  1513. if (transfer->length == 0) {
  1514. num_urbs = 1;
  1515. } else if ((transfer->length % bulk_buffer_len) > 0) {
  1516. last_urb_partial = 1;
  1517. num_urbs++;
  1518. }
  1519. usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
  1520. transfer->length);
  1521. alloc_size = num_urbs * sizeof(struct usbfs_urb);
  1522. urbs = malloc(alloc_size);
  1523. if (!urbs)
  1524. return LIBUSB_ERROR_NO_MEM;
  1525. memset(urbs, 0, alloc_size);
  1526. tpriv->urbs = urbs;
  1527. tpriv->num_urbs = num_urbs;
  1528. tpriv->num_retired = 0;
  1529. tpriv->reap_action = NORMAL;
  1530. tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
  1531. for (i = 0; i < num_urbs; i++) {
  1532. struct usbfs_urb *urb = &urbs[i];
  1533. urb->usercontext = itransfer;
  1534. urb->type = urb_type;
  1535. urb->endpoint = transfer->endpoint;
  1536. urb->buffer = transfer->buffer + (i * bulk_buffer_len);
  1537. /* don't set the short not ok flag for the last URB */
  1538. if (use_bulk_continuation && !is_out && i < num_urbs - 1)
  1539. urb->flags = USBFS_URB_SHORT_NOT_OK;
  1540. if (i == num_urbs - 1 && last_urb_partial)
  1541. urb->buffer_length = transfer->length % bulk_buffer_len;
  1542. else if (transfer->length == 0)
  1543. urb->buffer_length = 0;
  1544. else
  1545. urb->buffer_length = bulk_buffer_len;
  1546. if (i > 0 && use_bulk_continuation)
  1547. urb->flags |= USBFS_URB_BULK_CONTINUATION;
  1548. /* we have already checked that the flag is supported */
  1549. if (is_out && i == num_urbs - 1 &&
  1550. transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
  1551. urb->flags |= USBFS_URB_ZERO_PACKET;
  1552. r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
  1553. if (r < 0) {
  1554. if (errno == ENODEV) {
  1555. r = LIBUSB_ERROR_NO_DEVICE;
  1556. } else {
  1557. usbi_err(TRANSFER_CTX(transfer),
  1558. "submiturb failed error %d errno=%d", r, errno);
  1559. r = LIBUSB_ERROR_IO;
  1560. }
  1561. /* if the first URB submission fails, we can simply free up and
  1562. * return failure immediately. */
  1563. if (i == 0) {
  1564. usbi_dbg("first URB failed, easy peasy");
  1565. free(urbs);
  1566. tpriv->urbs = NULL;
  1567. return r;
  1568. }
  1569. /* if it's not the first URB that failed, the situation is a bit
  1570. * tricky. we may need to discard all previous URBs. there are
  1571. * complications:
  1572. * - discarding is asynchronous - discarded urbs will be reaped
  1573. * later. the user must not have freed the transfer when the
  1574. * discarded URBs are reaped, otherwise libusb will be using
  1575. * freed memory.
  1576. * - the earlier URBs may have completed successfully and we do
  1577. * not want to throw away any data.
  1578. * - this URB failing may be no error; EREMOTEIO means that
  1579. * this transfer simply didn't need all the URBs we submitted
  1580. * so, we report that the transfer was submitted successfully and
  1581. * in case of error we discard all previous URBs. later when
  1582. * the final reap completes we can report error to the user,
  1583. * or success if an earlier URB was completed successfully.
  1584. */
  1585. tpriv->reap_action = EREMOTEIO == errno ? COMPLETED_EARLY : SUBMIT_FAILED;
  1586. /* The URBs we haven't submitted yet we count as already
  1587. * retired. */
  1588. tpriv->num_retired += num_urbs - i;
  1589. /* If we completed short then don't try to discard. */
  1590. if (COMPLETED_EARLY == tpriv->reap_action)
  1591. return 0;
  1592. discard_urbs(itransfer, 0, i);
  1593. usbi_dbg("reporting successful submission but waiting for %d "
  1594. "discards before reporting error", i);
  1595. return 0;
  1596. }
  1597. }
  1598. return 0;
  1599. }
  1600. static int submit_iso_transfer(struct usbi_transfer *itransfer)
  1601. {
  1602. struct libusb_transfer *transfer =
  1603. USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1604. struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
  1605. struct linux_device_handle_priv *dpriv =
  1606. _device_handle_priv(transfer->dev_handle);
  1607. struct usbfs_urb **urbs;
  1608. size_t alloc_size;
  1609. int num_packets = transfer->num_iso_packets;
  1610. int i;
  1611. int this_urb_len = 0;
  1612. int num_urbs = 1;
  1613. int packet_offset = 0;
  1614. unsigned int packet_len;
  1615. unsigned char *urb_buffer = transfer->buffer;
  1616. if (tpriv->iso_urbs)
  1617. return LIBUSB_ERROR_BUSY;
  1618. /* usbfs places a 32kb limit on iso URBs. we divide up larger requests
  1619. * into smaller units to meet such restriction, then fire off all the
  1620. * units at once. it would be simpler if we just fired one unit at a time,
  1621. * but there is a big performance gain through doing it this way.
  1622. *
  1623. * Newer kernels lift the 32k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
  1624. * using arbritary large transfers is still be a bad idea though, as
  1625. * the kernel needs to allocate physical contiguous memory for this,
  1626. * which may fail for large buffers.
  1627. */
  1628. /* calculate how many URBs we need */
  1629. for (i = 0; i < num_packets; i++) {
  1630. unsigned int space_remaining = MAX_ISO_BUFFER_LENGTH - this_urb_len;
  1631. packet_len = transfer->iso_packet_desc[i].length;
  1632. if (packet_len > space_remaining) {
  1633. num_urbs++;
  1634. this_urb_len = packet_len;
  1635. } else {
  1636. this_urb_len += packet_len;
  1637. }
  1638. }
  1639. usbi_dbg("need %d 32k URBs for transfer", num_urbs);
  1640. alloc_size = num_urbs * sizeof(*urbs);
  1641. urbs = malloc(alloc_size);
  1642. if (!urbs)
  1643. return LIBUSB_ERROR_NO_MEM;
  1644. memset(urbs, 0, alloc_size);
  1645. tpriv->iso_urbs = urbs;
  1646. tpriv->num_urbs = num_urbs;
  1647. tpriv->num_retired = 0;
  1648. tpriv->reap_action = NORMAL;
  1649. tpriv->iso_packet_offset = 0;
  1650. /* allocate + initialize each URB with the correct number of packets */
  1651. for (i = 0; i < num_urbs; i++) {
  1652. struct usbfs_urb *urb;
  1653. unsigned int space_remaining_in_urb = MAX_ISO_BUFFER_LENGTH;
  1654. int urb_packet_offset = 0;
  1655. unsigned char *urb_buffer_orig = urb_buffer;
  1656. int j;
  1657. int k;
  1658. /* swallow up all the packets we can fit into this URB */
  1659. while (packet_offset < transfer->num_iso_packets) {
  1660. packet_len = transfer->iso_packet_desc[packet_offset].length;
  1661. if (packet_len <= space_remaining_in_urb) {
  1662. /* throw it in */
  1663. urb_packet_offset++;
  1664. packet_offset++;
  1665. space_remaining_in_urb -= packet_len;
  1666. urb_buffer += packet_len;
  1667. } else {
  1668. /* it can't fit, save it for the next URB */
  1669. break;
  1670. }
  1671. }
  1672. alloc_size = sizeof(*urb)
  1673. + (urb_packet_offset * sizeof(struct usbfs_iso_packet_desc));
  1674. urb = malloc(alloc_size);
  1675. if (!urb) {
  1676. free_iso_urbs(tpriv);
  1677. return LIBUSB_ERROR_NO_MEM;
  1678. }
  1679. memset(urb, 0, alloc_size);
  1680. urbs[i] = urb;
  1681. /* populate packet lengths */
  1682. for (j = 0, k = packet_offset - urb_packet_offset;
  1683. k < packet_offset; k++, j++) {
  1684. packet_len = transfer->iso_packet_desc[k].length;
  1685. urb->iso_frame_desc[j].length = packet_len;
  1686. }
  1687. urb->usercontext = itransfer;
  1688. urb->type = USBFS_URB_TYPE_ISO;
  1689. /* FIXME: interface for non-ASAP data? */
  1690. urb->flags = USBFS_URB_ISO_ASAP;
  1691. urb->endpoint = transfer->endpoint;
  1692. urb->number_of_packets = urb_packet_offset;
  1693. urb->buffer = urb_buffer_orig;
  1694. }
  1695. /* submit URBs */
  1696. for (i = 0; i < num_urbs; i++) {
  1697. int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
  1698. if (r < 0) {
  1699. if (errno == ENODEV) {
  1700. r = LIBUSB_ERROR_NO_DEVICE;
  1701. } else {
  1702. usbi_err(TRANSFER_CTX(transfer),
  1703. "submiturb failed error %d errno=%d", r, errno);
  1704. r = LIBUSB_ERROR_IO;
  1705. }
  1706. /* if the first URB submission fails, we can simply free up and
  1707. * return failure immediately. */
  1708. if (i == 0) {
  1709. usbi_dbg("first URB failed, easy peasy");
  1710. free_iso_urbs(tpriv);
  1711. return r;
  1712. }
  1713. /* if it's not the first URB that failed, the situation is a bit
  1714. * tricky. we must discard all previous URBs. there are
  1715. * complications:
  1716. * - discarding is asynchronous - discarded urbs will be reaped
  1717. * later. the user must not have freed the transfer when the
  1718. * discarded URBs are reaped, otherwise libusb will be using
  1719. * freed memory.
  1720. * - the earlier URBs may have completed successfully and we do
  1721. * not want to throw away any data.
  1722. * so, in this case we discard all the previous URBs BUT we report
  1723. * that the transfer was submitted successfully. then later when
  1724. * the final discard completes we can report error to the user.
  1725. */
  1726. tpriv->reap_action = SUBMIT_FAILED;
  1727. /* The URBs we haven't submitted yet we count as already
  1728. * retired. */
  1729. tpriv->num_retired = num_urbs - i;
  1730. discard_urbs(itransfer, 0, i);
  1731. usbi_dbg("reporting successful submission but waiting for %d "
  1732. "discards before reporting error", i);
  1733. return 0;
  1734. }
  1735. }
  1736. return 0;
  1737. }
  1738. static int submit_control_transfer(struct usbi_transfer *itransfer)
  1739. {
  1740. struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
  1741. struct libusb_transfer *transfer =
  1742. USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1743. struct linux_device_handle_priv *dpriv =
  1744. _device_handle_priv(transfer->dev_handle);
  1745. struct usbfs_urb *urb;
  1746. int r;
  1747. if (tpriv->urbs)
  1748. return LIBUSB_ERROR_BUSY;
  1749. if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
  1750. return LIBUSB_ERROR_INVALID_PARAM;
  1751. urb = malloc(sizeof(struct usbfs_urb));
  1752. if (!urb)
  1753. return LIBUSB_ERROR_NO_MEM;
  1754. memset(urb, 0, sizeof(struct usbfs_urb));
  1755. tpriv->urbs = urb;
  1756. tpriv->num_urbs = 1;
  1757. tpriv->reap_action = NORMAL;
  1758. urb->usercontext = itransfer;
  1759. urb->type = USBFS_URB_TYPE_CONTROL;
  1760. urb->endpoint = transfer->endpoint;
  1761. urb->buffer = transfer->buffer;
  1762. urb->buffer_length = transfer->length;
  1763. r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
  1764. if (r < 0) {
  1765. free(urb);
  1766. tpriv->urbs = NULL;
  1767. if (errno == ENODEV)
  1768. return LIBUSB_ERROR_NO_DEVICE;
  1769. usbi_err(TRANSFER_CTX(transfer),
  1770. "submiturb failed error %d errno=%d", r, errno);
  1771. return LIBUSB_ERROR_IO;
  1772. }
  1773. return 0;
  1774. }
  1775. static int op_submit_transfer(struct usbi_transfer *itransfer)
  1776. {
  1777. struct libusb_transfer *transfer =
  1778. USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1779. switch (transfer->type) {
  1780. case LIBUSB_TRANSFER_TYPE_CONTROL:
  1781. return submit_control_transfer(itransfer);
  1782. case LIBUSB_TRANSFER_TYPE_BULK:
  1783. return submit_bulk_transfer(itransfer, USBFS_URB_TYPE_BULK);
  1784. case LIBUSB_TRANSFER_TYPE_INTERRUPT:
  1785. return submit_bulk_transfer(itransfer, USBFS_URB_TYPE_INTERRUPT);
  1786. case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
  1787. return submit_iso_transfer(itransfer);
  1788. default:
  1789. usbi_err(TRANSFER_CTX(transfer),
  1790. "unknown endpoint type %d", transfer->type);
  1791. return LIBUSB_ERROR_INVALID_PARAM;
  1792. }
  1793. }
  1794. static int op_cancel_transfer(struct usbi_transfer *itransfer)
  1795. {
  1796. struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
  1797. struct libusb_transfer *transfer =
  1798. USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1799. switch (transfer->type) {
  1800. case LIBUSB_TRANSFER_TYPE_BULK:
  1801. if (tpriv->reap_action == ERROR)
  1802. break;
  1803. /* else, fall through */
  1804. case LIBUSB_TRANSFER_TYPE_CONTROL:
  1805. case LIBUSB_TRANSFER_TYPE_INTERRUPT:
  1806. case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
  1807. tpriv->reap_action = CANCELLED;
  1808. break;
  1809. default:
  1810. usbi_err(TRANSFER_CTX(transfer),
  1811. "unknown endpoint type %d", transfer->type);
  1812. return LIBUSB_ERROR_INVALID_PARAM;
  1813. }
  1814. if (!tpriv->urbs)
  1815. return LIBUSB_ERROR_NOT_FOUND;
  1816. return discard_urbs(itransfer, 0, tpriv->num_urbs);
  1817. }
  1818. static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
  1819. {
  1820. struct libusb_transfer *transfer =
  1821. USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1822. struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
  1823. /* urbs can be freed also in submit_transfer so lock mutex first */
  1824. switch (transfer->type) {
  1825. case LIBUSB_TRANSFER_TYPE_CONTROL:
  1826. case LIBUSB_TRANSFER_TYPE_BULK:
  1827. case LIBUSB_TRANSFER_TYPE_INTERRUPT:
  1828. usbi_mutex_lock(&itransfer->lock);
  1829. if (tpriv->urbs)
  1830. free(tpriv->urbs);
  1831. tpriv->urbs = NULL;
  1832. usbi_mutex_unlock(&itransfer->lock);
  1833. break;
  1834. case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
  1835. usbi_mutex_lock(&itransfer->lock);
  1836. if (tpriv->iso_urbs)
  1837. free_iso_urbs(tpriv);
  1838. usbi_mutex_unlock(&itransfer->lock);
  1839. break;
  1840. default:
  1841. usbi_err(TRANSFER_CTX(transfer),
  1842. "unknown endpoint type %d", transfer->type);
  1843. }
  1844. }
  1845. static int handle_bulk_completion(struct usbi_transfer *itransfer,
  1846. struct usbfs_urb *urb)
  1847. {
  1848. struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
  1849. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1850. int urb_idx = urb - tpriv->urbs;
  1851. usbi_mutex_lock(&itransfer->lock);
  1852. usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
  1853. urb_idx + 1, tpriv->num_urbs);
  1854. tpriv->num_retired++;
  1855. if (tpriv->reap_action != NORMAL) {
  1856. /* cancelled, submit_fail, or completed early */
  1857. usbi_dbg("abnormal reap: urb status %d", urb->status);
  1858. /* even though we're in the process of cancelling, it's possible that
  1859. * we may receive some data in these URBs that we don't want to lose.
  1860. * examples:
  1861. * 1. while the kernel is cancelling all the packets that make up an
  1862. * URB, a few of them might complete. so we get back a successful
  1863. * cancellation *and* some data.
  1864. * 2. we receive a short URB which marks the early completion condition,
  1865. * so we start cancelling the remaining URBs. however, we're too
  1866. * slow and another URB completes (or at least completes partially).
  1867. * (this can't happen since we always use BULK_CONTINUATION.)
  1868. *
  1869. * When this happens, our objectives are not to lose any "surplus" data,
  1870. * and also to stick it at the end of the previously-received data
  1871. * (closing any holes), so that libusb reports the total amount of
  1872. * transferred data and presents it in a contiguous chunk.
  1873. */
  1874. if (urb->actual_length > 0) {
  1875. unsigned char *target = transfer->buffer + itransfer->transferred;
  1876. usbi_dbg("received %d bytes of surplus data", urb->actual_length);
  1877. if (urb->buffer != target) {
  1878. usbi_dbg("moving surplus data from offset %d to offset %d",
  1879. (unsigned char *) urb->buffer - transfer->buffer,
  1880. target - transfer->buffer);
  1881. memmove(target, urb->buffer, urb->actual_length);
  1882. }
  1883. itransfer->transferred += urb->actual_length;
  1884. }
  1885. if (tpriv->num_retired == tpriv->num_urbs) {
  1886. usbi_dbg("abnormal reap: last URB handled, reporting");
  1887. if (tpriv->reap_action != COMPLETED_EARLY &&
  1888. tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
  1889. tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
  1890. goto completed;
  1891. }
  1892. goto out_unlock;
  1893. }
  1894. itransfer->transferred += urb->actual_length;
  1895. /* Many of these errors can occur on *any* urb of a multi-urb
  1896. * transfer. When they do, we tear down the rest of the transfer.
  1897. */
  1898. switch (urb->status) {
  1899. case 0:
  1900. break;
  1901. case -EREMOTEIO: /* short transfer */
  1902. break;
  1903. case -ENOENT: /* cancelled */
  1904. case -ECONNRESET:
  1905. break;
  1906. case -ENODEV:
  1907. case -ESHUTDOWN:
  1908. usbi_dbg("device removed");
  1909. tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
  1910. goto cancel_remaining;
  1911. case -EPIPE:
  1912. usbi_dbg("detected endpoint stall");
  1913. if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
  1914. tpriv->reap_status = LIBUSB_TRANSFER_STALL;
  1915. goto cancel_remaining;
  1916. case -EOVERFLOW:
  1917. /* overflow can only ever occur in the last urb */
  1918. usbi_dbg("overflow, actual_length=%d", urb->actual_length);
  1919. if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
  1920. tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
  1921. goto completed;
  1922. case -ETIME:
  1923. case -EPROTO:
  1924. case -EILSEQ:
  1925. case -ECOMM:
  1926. case -ENOSR:
  1927. usbi_dbg("low level error %d", urb->status);
  1928. tpriv->reap_action = ERROR;
  1929. goto cancel_remaining;
  1930. default:
  1931. usbi_warn(ITRANSFER_CTX(itransfer),
  1932. "unrecognised urb status %d", urb->status);
  1933. tpriv->reap_action = ERROR;
  1934. goto cancel_remaining;
  1935. }
  1936. /* if we're the last urb or we got less data than requested then we're
  1937. * done */
  1938. if (urb_idx == tpriv->num_urbs - 1) {
  1939. usbi_dbg("last URB in transfer --> complete!");
  1940. goto completed;
  1941. } else if (urb->actual_length < urb->buffer_length) {
  1942. usbi_dbg("short transfer %d/%d --> complete!",
  1943. urb->actual_length, urb->buffer_length);
  1944. if (tpriv->reap_action == NORMAL)
  1945. tpriv->reap_action = COMPLETED_EARLY;
  1946. } else
  1947. goto out_unlock;
  1948. cancel_remaining:
  1949. if (ERROR == tpriv->reap_action && LIBUSB_TRANSFER_COMPLETED == tpriv->reap_status)
  1950. tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
  1951. if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
  1952. goto completed;
  1953. /* cancel remaining urbs and wait for their completion before
  1954. * reporting results */
  1955. discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
  1956. out_unlock:
  1957. usbi_mutex_unlock(&itransfer->lock);
  1958. return 0;
  1959. completed:
  1960. free(tpriv->urbs);
  1961. tpriv->urbs = NULL;
  1962. usbi_mutex_unlock(&itransfer->lock);
  1963. return CANCELLED == tpriv->reap_action ?
  1964. usbi_handle_transfer_cancellation(itransfer) :
  1965. usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
  1966. }
  1967. static int handle_iso_completion(struct usbi_transfer *itransfer,
  1968. struct usbfs_urb *urb)
  1969. {
  1970. struct libusb_transfer *transfer =
  1971. USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1972. struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
  1973. int num_urbs = tpriv->num_urbs;
  1974. int urb_idx = 0;
  1975. int i;
  1976. enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
  1977. usbi_mutex_lock(&itransfer->lock);
  1978. for (i = 0; i < num_urbs; i++) {
  1979. if (urb == tpriv->iso_urbs[i]) {
  1980. urb_idx = i + 1;
  1981. break;
  1982. }
  1983. }
  1984. if (urb_idx == 0) {
  1985. usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
  1986. usbi_mutex_unlock(&itransfer->lock);
  1987. return LIBUSB_ERROR_NOT_FOUND;
  1988. }
  1989. usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
  1990. urb_idx, num_urbs);
  1991. /* copy isochronous results back in */
  1992. for (i = 0; i < urb->number_of_packets; i++) {
  1993. struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
  1994. struct libusb_iso_packet_descriptor *lib_desc =
  1995. &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
  1996. lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
  1997. switch (urb_desc->status) {
  1998. case 0:
  1999. break;
  2000. case -ENOENT: /* cancelled */
  2001. case -ECONNRESET:
  2002. break;
  2003. case -ENODEV:
  2004. case -ESHUTDOWN:
  2005. usbi_dbg("device removed");
  2006. lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
  2007. break;
  2008. case -EPIPE:
  2009. usbi_dbg("detected endpoint stall");
  2010. lib_desc->status = LIBUSB_TRANSFER_STALL;
  2011. break;
  2012. case -EOVERFLOW:
  2013. usbi_dbg("overflow error");
  2014. lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
  2015. break;
  2016. case -ETIME:
  2017. case -EPROTO:
  2018. case -EILSEQ:
  2019. case -ECOMM:
  2020. case -ENOSR:
  2021. case -EXDEV:
  2022. usbi_dbg("low-level USB error %d", urb_desc->status);
  2023. lib_desc->status = LIBUSB_TRANSFER_ERROR;
  2024. break;
  2025. default:
  2026. usbi_warn(TRANSFER_CTX(transfer),
  2027. "unrecognised urb status %d", urb_desc->status);
  2028. lib_desc->status = LIBUSB_TRANSFER_ERROR;
  2029. break;
  2030. }
  2031. lib_desc->actual_length = urb_desc->actual_length;
  2032. }
  2033. tpriv->num_retired++;
  2034. if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
  2035. usbi_dbg("CANCEL: urb status %d", urb->status);
  2036. if (tpriv->num_retired == num_urbs) {
  2037. usbi_dbg("CANCEL: last URB handled, reporting");
  2038. free_iso_urbs(tpriv);
  2039. if (tpriv->reap_action == CANCELLED) {
  2040. usbi_mutex_unlock(&itransfer->lock);
  2041. return usbi_handle_transfer_cancellation(itransfer);
  2042. } else {
  2043. usbi_mutex_unlock(&itransfer->lock);
  2044. return usbi_handle_transfer_completion(itransfer,
  2045. LIBUSB_TRANSFER_ERROR);
  2046. }
  2047. }
  2048. goto out;
  2049. }
  2050. switch (urb->status) {
  2051. case 0:
  2052. break;
  2053. case -ENOENT: /* cancelled */
  2054. case -ECONNRESET:
  2055. break;
  2056. case -ESHUTDOWN:
  2057. usbi_dbg("device removed");
  2058. status = LIBUSB_TRANSFER_NO_DEVICE;
  2059. break;
  2060. default:
  2061. usbi_warn(TRANSFER_CTX(transfer),
  2062. "unrecognised urb status %d", urb->status);
  2063. status = LIBUSB_TRANSFER_ERROR;
  2064. break;
  2065. }
  2066. /* if we're the last urb then we're done */
  2067. if (urb_idx == num_urbs) {
  2068. usbi_dbg("last URB in transfer --> complete!");
  2069. free_iso_urbs(tpriv);
  2070. usbi_mutex_unlock(&itransfer->lock);
  2071. return usbi_handle_transfer_completion(itransfer, status);
  2072. }
  2073. out:
  2074. usbi_mutex_unlock(&itransfer->lock);
  2075. return 0;
  2076. }
  2077. static int handle_control_completion(struct usbi_transfer *itransfer,
  2078. struct usbfs_urb *urb)
  2079. {
  2080. struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
  2081. int status;
  2082. usbi_mutex_lock(&itransfer->lock);
  2083. usbi_dbg("handling completion status %d", urb->status);
  2084. itransfer->transferred += urb->actual_length;
  2085. if (tpriv->reap_action == CANCELLED) {
  2086. if (urb->status != 0 && urb->status != -ENOENT)
  2087. usbi_warn(ITRANSFER_CTX(itransfer),
  2088. "cancel: unrecognised urb status %d", urb->status);
  2089. free(tpriv->urbs);
  2090. tpriv->urbs = NULL;
  2091. usbi_mutex_unlock(&itransfer->lock);
  2092. return usbi_handle_transfer_cancellation(itransfer);
  2093. }
  2094. switch (urb->status) {
  2095. case 0:
  2096. status = LIBUSB_TRANSFER_COMPLETED;
  2097. break;
  2098. case -ENOENT: /* cancelled */
  2099. status = LIBUSB_TRANSFER_CANCELLED;
  2100. break;
  2101. case -ENODEV:
  2102. case -ESHUTDOWN:
  2103. usbi_dbg("device removed");
  2104. status = LIBUSB_TRANSFER_NO_DEVICE;
  2105. break;
  2106. case -EPIPE:
  2107. usbi_dbg("unsupported control request");
  2108. status = LIBUSB_TRANSFER_STALL;
  2109. break;
  2110. case -EOVERFLOW:
  2111. usbi_dbg("control overflow error");
  2112. status = LIBUSB_TRANSFER_OVERFLOW;
  2113. break;
  2114. case -ETIME:
  2115. case -EPROTO:
  2116. case -EILSEQ:
  2117. case -ECOMM:
  2118. case -ENOSR:
  2119. usbi_dbg("low-level bus error occurred");
  2120. status = LIBUSB_TRANSFER_ERROR;
  2121. break;
  2122. default:
  2123. usbi_warn(ITRANSFER_CTX(itransfer),
  2124. "unrecognised urb status %d", urb->status);
  2125. status = LIBUSB_TRANSFER_ERROR;
  2126. break;
  2127. }
  2128. free(tpriv->urbs);
  2129. tpriv->urbs = NULL;
  2130. usbi_mutex_unlock(&itransfer->lock);
  2131. return usbi_handle_transfer_completion(itransfer, status);
  2132. }
  2133. static int reap_for_handle(struct libusb_device_handle *handle)
  2134. {
  2135. struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
  2136. int r;
  2137. struct usbfs_urb *urb;
  2138. struct usbi_transfer *itransfer;
  2139. struct libusb_transfer *transfer;
  2140. r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
  2141. if (r == -1 && errno == EAGAIN)
  2142. return 1;
  2143. if (r < 0) {
  2144. if (errno == ENODEV)
  2145. return LIBUSB_ERROR_NO_DEVICE;
  2146. usbi_err(HANDLE_CTX(handle), "reap failed error %d errno=%d",
  2147. r, errno);
  2148. return LIBUSB_ERROR_IO;
  2149. }
  2150. itransfer = urb->usercontext;
  2151. transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  2152. usbi_dbg("urb type=%d status=%d transferred=%d", urb->type, urb->status,
  2153. urb->actual_length);
  2154. switch (transfer->type) {
  2155. case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
  2156. return handle_iso_completion(itransfer, urb);
  2157. case LIBUSB_TRANSFER_TYPE_BULK:
  2158. case LIBUSB_TRANSFER_TYPE_INTERRUPT:
  2159. return handle_bulk_completion(itransfer, urb);
  2160. case LIBUSB_TRANSFER_TYPE_CONTROL:
  2161. return handle_control_completion(itransfer, urb);
  2162. default:
  2163. usbi_err(HANDLE_CTX(handle), "unrecognised endpoint type %x",
  2164. transfer->type);
  2165. return LIBUSB_ERROR_OTHER;
  2166. }
  2167. }
  2168. static int op_handle_events(struct libusb_context *ctx,
  2169. struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
  2170. {
  2171. int r;
  2172. unsigned int i = 0;
  2173. usbi_mutex_lock(&ctx->open_devs_lock);
  2174. for (i = 0; i < nfds && num_ready > 0; i++) {
  2175. struct pollfd *pollfd = &fds[i];
  2176. struct libusb_device_handle *handle;
  2177. struct linux_device_handle_priv *hpriv = NULL;
  2178. if (!pollfd->revents)
  2179. continue;
  2180. num_ready--;
  2181. list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
  2182. hpriv = _device_handle_priv(handle);
  2183. if (hpriv->fd == pollfd->fd)
  2184. break;
  2185. }
  2186. if (pollfd->revents & POLLERR) {
  2187. usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
  2188. usbi_handle_disconnect(handle);
  2189. continue;
  2190. }
  2191. do {
  2192. r = reap_for_handle(handle);
  2193. } while (r == 0);
  2194. if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
  2195. continue;
  2196. else if (r < 0)
  2197. goto out;
  2198. }
  2199. r = 0;
  2200. out:
  2201. usbi_mutex_unlock(&ctx->open_devs_lock);
  2202. return r;
  2203. }
  2204. static int op_clock_gettime(int clk_id, struct timespec *tp)
  2205. {
  2206. switch (clk_id) {
  2207. case USBI_CLOCK_MONOTONIC:
  2208. return clock_gettime(monotonic_clkid, tp);
  2209. case USBI_CLOCK_REALTIME:
  2210. return clock_gettime(CLOCK_REALTIME, tp);
  2211. default:
  2212. return LIBUSB_ERROR_INVALID_PARAM;
  2213. }
  2214. }
  2215. #ifdef USBI_TIMERFD_AVAILABLE
  2216. static clockid_t op_get_timerfd_clockid(void)
  2217. {
  2218. return monotonic_clkid;
  2219. }
  2220. #endif
  2221. const struct usbi_os_backend linux_usbfs_backend = {
  2222. .name = "Linux usbfs",
  2223. .init = op_init,
  2224. .exit = op_exit,
  2225. .get_device_list = NULL,
  2226. .get_device_descriptor = op_get_device_descriptor,
  2227. .get_active_config_descriptor = op_get_active_config_descriptor,
  2228. .get_config_descriptor = op_get_config_descriptor,
  2229. .open = op_open,
  2230. .close = op_close,
  2231. .get_configuration = op_get_configuration,
  2232. .set_configuration = op_set_configuration,
  2233. .claim_interface = op_claim_interface,
  2234. .release_interface = op_release_interface,
  2235. .set_interface_altsetting = op_set_interface,
  2236. .clear_halt = op_clear_halt,
  2237. .reset_device = op_reset_device,
  2238. .kernel_driver_active = op_kernel_driver_active,
  2239. .detach_kernel_driver = op_detach_kernel_driver,
  2240. .attach_kernel_driver = op_attach_kernel_driver,
  2241. .destroy_device = op_destroy_device,
  2242. .submit_transfer = op_submit_transfer,
  2243. .cancel_transfer = op_cancel_transfer,
  2244. .clear_transfer_priv = op_clear_transfer_priv,
  2245. .handle_events = op_handle_events,
  2246. .clock_gettime = op_clock_gettime,
  2247. #ifdef USBI_TIMERFD_AVAILABLE
  2248. .get_timerfd_clockid = op_get_timerfd_clockid,
  2249. #endif
  2250. .device_priv_size = sizeof(struct linux_device_priv),
  2251. .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
  2252. .transfer_priv_size = sizeof(struct linux_transfer_priv),
  2253. .add_iso_packet_size = 0,
  2254. };