linux_usbfs.c 77 KB

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