fpgautils.c 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431
  1. /*
  2. * Copyright 2012-2013 Luke Dashjr
  3. * Copyright 2013 Con Kolivas
  4. * Copyright 2012 Andrew Smith
  5. * Copyright 2013 Xiangfu
  6. *
  7. * This program is free software; you can redistribute it and/or modify it
  8. * under the terms of the GNU General Public License as published by the Free
  9. * Software Foundation; either version 3 of the License, or (at your option)
  10. * any later version. See COPYING for more details.
  11. */
  12. #include "config.h"
  13. #ifdef WIN32
  14. #include <winsock2.h>
  15. #endif
  16. #include <ctype.h>
  17. #include <stdarg.h>
  18. #include <stdbool.h>
  19. #include <stdint.h>
  20. #include <stdlib.h>
  21. #include <sys/types.h>
  22. #include <dirent.h>
  23. #include <string.h>
  24. #ifdef HAVE_SYS_FILE_H
  25. #include <sys/file.h>
  26. #endif
  27. #ifdef HAVE_LIBUSB
  28. #include <libusb.h>
  29. #endif
  30. #include "miner.h"
  31. #ifndef WIN32
  32. #include <errno.h>
  33. #include <termios.h>
  34. #include <sys/ioctl.h>
  35. #include <sys/stat.h>
  36. #include <unistd.h>
  37. #include <fcntl.h>
  38. #ifndef O_CLOEXEC
  39. #define O_CLOEXEC 0
  40. #endif
  41. #else /* WIN32 */
  42. #include <windows.h>
  43. #ifdef HAVE_WIN_DDKUSB
  44. #include <setupapi.h>
  45. #include <usbioctl.h>
  46. #include <usbiodef.h>
  47. #endif
  48. #include <io.h>
  49. #include <utlist.h>
  50. #define dlsym (void*)GetProcAddress
  51. #define dlclose FreeLibrary
  52. typedef unsigned long FT_STATUS;
  53. typedef PVOID FT_HANDLE;
  54. __stdcall FT_STATUS (*FT_ListDevices)(PVOID pArg1, PVOID pArg2, DWORD Flags);
  55. __stdcall FT_STATUS (*FT_Open)(int idx, FT_HANDLE*);
  56. __stdcall FT_STATUS (*FT_GetComPortNumber)(FT_HANDLE, LPLONG lplComPortNumber);
  57. __stdcall FT_STATUS (*FT_Close)(FT_HANDLE);
  58. const uint32_t FT_OPEN_BY_SERIAL_NUMBER = 1;
  59. const uint32_t FT_OPEN_BY_DESCRIPTION = 2;
  60. const uint32_t FT_LIST_ALL = 0x20000000;
  61. const uint32_t FT_LIST_BY_INDEX = 0x40000000;
  62. const uint32_t FT_LIST_NUMBER_ONLY = 0x80000000;
  63. enum {
  64. FT_OK,
  65. };
  66. #endif /* WIN32 */
  67. #ifdef HAVE_LIBUDEV
  68. #include <libudev.h>
  69. #include <sys/ioctl.h>
  70. #endif
  71. #include "logging.h"
  72. #include "lowlevel.h"
  73. #include "miner.h"
  74. #include "util.h"
  75. #include "fpgautils.h"
  76. struct lowlevel_driver lowl_vcom;
  77. struct detectone_meta_info_t detectone_meta_info;
  78. void clear_detectone_meta_info(void)
  79. {
  80. detectone_meta_info = (struct detectone_meta_info_t){
  81. .manufacturer = NULL,
  82. };
  83. }
  84. #define _vcom_unique_id(devpath) devpath_to_devid(devpath)
  85. struct lowlevel_device_info *_vcom_devinfo_findorcreate(struct lowlevel_device_info ** const devinfo_list, const char * const devpath)
  86. {
  87. struct lowlevel_device_info *devinfo;
  88. char * const devid = _vcom_unique_id(devpath);
  89. HASH_FIND_STR(*devinfo_list, devid, devinfo);
  90. if (!devinfo)
  91. {
  92. devinfo = malloc(sizeof(*devinfo));
  93. *devinfo = (struct lowlevel_device_info){
  94. .lowl = &lowl_vcom,
  95. .path = strdup(devpath),
  96. .devid = devid,
  97. };
  98. HASH_ADD_KEYPTR(hh, *devinfo_list, devinfo->devid, strlen(devid), devinfo);
  99. }
  100. else
  101. free(devid);
  102. return devinfo;
  103. }
  104. #ifdef HAVE_LIBUDEV
  105. static
  106. void _decode_udev_enc(char *o, const char *s)
  107. {
  108. while(s[0])
  109. {
  110. if (s[0] == '\\' && s[1] == 'x' && s[2] && s[3])
  111. {
  112. hex2bin((void*)(o++), &s[2], 1);
  113. s += 4;
  114. }
  115. else
  116. (o++)[0] = (s++)[0];
  117. }
  118. o[0] = '\0';
  119. }
  120. static
  121. char *_decode_udev_enc_dup(const char *s)
  122. {
  123. if (!s)
  124. return NULL;
  125. char *o = malloc(strlen(s) + 1);
  126. if (!o)
  127. {
  128. applog(LOG_ERR, "Failed to malloc in _decode_udev_enc_dup");
  129. return NULL;
  130. }
  131. _decode_udev_enc(o, s);
  132. return o;
  133. }
  134. static
  135. void _vcom_devinfo_scan_udev(struct lowlevel_device_info ** const devinfo_list)
  136. {
  137. struct udev *udev = udev_new();
  138. struct udev_enumerate *enumerate = udev_enumerate_new(udev);
  139. struct udev_list_entry *list_entry;
  140. struct lowlevel_device_info *devinfo;
  141. udev_enumerate_add_match_subsystem(enumerate, "tty");
  142. udev_enumerate_add_match_property(enumerate, "ID_SERIAL", "*");
  143. udev_enumerate_scan_devices(enumerate);
  144. udev_list_entry_foreach(list_entry, udev_enumerate_get_list_entry(enumerate)) {
  145. struct udev_device *device = udev_device_new_from_syspath(
  146. udev_enumerate_get_udev(enumerate),
  147. udev_list_entry_get_name(list_entry)
  148. );
  149. if (!device)
  150. continue;
  151. const char * const devpath = udev_device_get_devnode(device);
  152. devinfo = _vcom_devinfo_findorcreate(devinfo_list, devpath);
  153. BFGINIT(devinfo->manufacturer, _decode_udev_enc_dup(udev_device_get_property_value(device, "ID_VENDOR_ENC")));
  154. BFGINIT(devinfo->product, _decode_udev_enc_dup(udev_device_get_property_value(device, "ID_MODEL_ENC")));
  155. BFGINIT(devinfo->serial, _decode_udev_enc_dup(udev_device_get_property_value(device, "ID_SERIAL_SHORT")));
  156. udev_device_unref(device);
  157. }
  158. udev_enumerate_unref(enumerate);
  159. udev_unref(udev);
  160. }
  161. #endif
  162. #ifndef WIN32
  163. static
  164. void _vcom_devinfo_scan_devserial(struct lowlevel_device_info ** const devinfo_list)
  165. {
  166. DIR *D;
  167. struct dirent *de;
  168. const char udevdir[] = "/dev/serial/by-id";
  169. char devpath[sizeof(udevdir) + 1 + NAME_MAX];
  170. char *devfile = devpath + sizeof(udevdir);
  171. struct lowlevel_device_info *devinfo;
  172. D = opendir(udevdir);
  173. if (!D)
  174. return;
  175. memcpy(devpath, udevdir, sizeof(udevdir) - 1);
  176. devpath[sizeof(udevdir) - 1] = '/';
  177. while ( (de = readdir(D)) ) {
  178. if (strncmp(de->d_name, "usb-", 4))
  179. continue;
  180. strcpy(devfile, de->d_name);
  181. devinfo = _vcom_devinfo_findorcreate(devinfo_list, devpath);
  182. if (!(devinfo->manufacturer || devinfo->product || devinfo->serial))
  183. devinfo->product = strdup(devfile);
  184. }
  185. closedir(D);
  186. }
  187. #endif
  188. #ifndef WIN32
  189. static
  190. char *_sysfs_do_read(char *buf, size_t bufsz, const char *devpath, char *devfile, const char *append)
  191. {
  192. FILE *F;
  193. strcpy(devfile, append);
  194. F = fopen(devpath, "r");
  195. if (F)
  196. {
  197. if (fgets(buf, bufsz, F))
  198. {
  199. size_t L = strlen(buf);
  200. while (isCspace(buf[--L]))
  201. buf[L] = '\0';
  202. }
  203. else
  204. buf[0] = '\0';
  205. fclose(F);
  206. }
  207. else
  208. buf[0] = '\0';
  209. return buf[0] ? buf : NULL;
  210. }
  211. static
  212. void _sysfs_find_tty(char *devpath, char *devfile, const char *prod, struct lowlevel_device_info ** const devinfo_list)
  213. {
  214. struct lowlevel_device_info *devinfo;
  215. DIR *DT;
  216. struct dirent *de;
  217. char ttybuf[0x10] = "/dev/";
  218. char manuf[0x40], serial[0x40];
  219. char *mydevfile = strdup(devfile);
  220. DT = opendir(devpath);
  221. if (!DT)
  222. goto out;
  223. while ( (de = readdir(DT)) )
  224. {
  225. if (strncmp(de->d_name, "tty", 3))
  226. continue;
  227. if (!de->d_name[3])
  228. {
  229. // "tty" directory: recurse (needed for ttyACM)
  230. sprintf(devfile, "%s/tty", mydevfile);
  231. _sysfs_find_tty(devpath, devfile, prod, devinfo_list);
  232. continue;
  233. }
  234. if (strncmp(&de->d_name[3], "USB", 3) && strncmp(&de->d_name[3], "ACM", 3))
  235. continue;
  236. strcpy(&ttybuf[5], de->d_name);
  237. devinfo = _vcom_devinfo_findorcreate(devinfo_list, ttybuf);
  238. BFGINIT(devinfo->manufacturer, maybe_strdup(_sysfs_do_read(manuf, sizeof(manuf), devpath, devfile, "/manufacturer")));
  239. BFGINIT(devinfo->product, maybe_strdup(prod));
  240. BFGINIT(devinfo->serial, maybe_strdup(_sysfs_do_read(serial, sizeof(serial), devpath, devfile, "/serial")));
  241. }
  242. closedir(DT);
  243. out:
  244. free(mydevfile);
  245. }
  246. static
  247. void _vcom_devinfo_scan_sysfs(struct lowlevel_device_info ** const devinfo_list)
  248. {
  249. DIR *D, *DS;
  250. struct dirent *de;
  251. const char devroot[] = "/sys/bus/usb/devices";
  252. const size_t devrootlen = sizeof(devroot) - 1;
  253. char devpath[sizeof(devroot) + (NAME_MAX * 3)];
  254. char prod[0x40];
  255. char *devfile, *upfile;
  256. size_t len, len2;
  257. D = opendir(devroot);
  258. if (!D)
  259. return;
  260. memcpy(devpath, devroot, devrootlen);
  261. devpath[devrootlen] = '/';
  262. while ( (de = readdir(D)) )
  263. {
  264. len = strlen(de->d_name);
  265. upfile = &devpath[devrootlen + 1];
  266. memcpy(upfile, de->d_name, len);
  267. devfile = upfile + len;
  268. if (!_sysfs_do_read(prod, sizeof(prod), devpath, devfile, "/product"))
  269. prod[0] = '\0';
  270. devfile[0] = '\0';
  271. DS = opendir(devpath);
  272. if (!DS)
  273. continue;
  274. devfile[0] = '/';
  275. ++devfile;
  276. while ( (de = readdir(DS)) )
  277. {
  278. if (strncmp(de->d_name, upfile, len))
  279. continue;
  280. len2 = strlen(de->d_name);
  281. memcpy(devfile, de->d_name, len2 + 1);
  282. _sysfs_find_tty(devpath, devfile, prod[0] ? prod : NULL, devinfo_list);
  283. }
  284. closedir(DS);
  285. }
  286. closedir(D);
  287. }
  288. #endif
  289. #ifdef HAVE_WIN_DDKUSB
  290. static const GUID WIN_GUID_DEVINTERFACE_USB_HOST_CONTROLLER = { 0x3ABF6F2D, 0x71C4, 0x462A, {0x8A, 0x92, 0x1E, 0x68, 0x61, 0xE6, 0xAF, 0x27} };
  291. static
  292. char *windows_usb_get_port_path(HANDLE hubh, const int portno)
  293. {
  294. size_t namesz;
  295. ULONG rsz;
  296. {
  297. USB_NODE_CONNECTION_NAME pathinfo = {
  298. .ConnectionIndex = portno,
  299. };
  300. if (!(DeviceIoControl(hubh, IOCTL_USB_GET_NODE_CONNECTION_NAME, &pathinfo, sizeof(pathinfo), &pathinfo, sizeof(pathinfo), &rsz, NULL) && rsz >= sizeof(pathinfo)))
  301. applogfailinfor(NULL, LOG_ERR, "ioctl (1)", "%s", bfg_strerror(GetLastError(), BST_SYSTEM));
  302. namesz = pathinfo.ActualLength;
  303. }
  304. const size_t bufsz = sizeof(USB_NODE_CONNECTION_NAME) + namesz;
  305. uint8_t buf[bufsz];
  306. USB_NODE_CONNECTION_NAME *path = (USB_NODE_CONNECTION_NAME *)buf;
  307. *path = (USB_NODE_CONNECTION_NAME){
  308. .ConnectionIndex = portno,
  309. };
  310. if (!(DeviceIoControl(hubh, IOCTL_USB_GET_NODE_CONNECTION_NAME, path, bufsz, path, bufsz, &rsz, NULL) && rsz >= sizeof(*path)))
  311. applogfailinfor(NULL, LOG_ERR, "ioctl (2)", "%s", bfg_strerror(GetLastError(), BST_SYSTEM));
  312. return ucs2tochar_dup(path->NodeName, path->ActualLength);
  313. }
  314. static
  315. char *windows_usb_get_string(HANDLE hubh, const int portno, const uint8_t descid)
  316. {
  317. if (!descid)
  318. return NULL;
  319. const size_t descsz_max = sizeof(USB_STRING_DESCRIPTOR) + MAXIMUM_USB_STRING_LENGTH;
  320. const size_t reqsz = sizeof(USB_DESCRIPTOR_REQUEST) + descsz_max;
  321. uint8_t buf[reqsz];
  322. USB_DESCRIPTOR_REQUEST * const req = (USB_DESCRIPTOR_REQUEST *)buf;
  323. USB_STRING_DESCRIPTOR * const desc = (USB_STRING_DESCRIPTOR *)&req[1];
  324. *req = (USB_DESCRIPTOR_REQUEST){
  325. .ConnectionIndex = portno,
  326. .SetupPacket = {
  327. .wValue = (USB_STRING_DESCRIPTOR_TYPE << 8) | descid,
  328. .wIndex = 0,
  329. .wLength = descsz_max,
  330. },
  331. };
  332. // Need to explicitly zero the output memory
  333. memset(desc, '\0', descsz_max);
  334. ULONG descsz;
  335. if (!DeviceIoControl(hubh, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, req, reqsz, req, reqsz, &descsz, NULL))
  336. applogfailinfor(NULL, LOG_DEBUG, "ioctl", "%s", bfg_strerror(GetLastError(), BST_SYSTEM));
  337. if (descsz < 2 || desc->bDescriptorType != USB_STRING_DESCRIPTOR_TYPE || desc->bLength > descsz - sizeof(USB_DESCRIPTOR_REQUEST) || desc->bLength % 2)
  338. applogfailr(NULL, LOG_ERR, "sanity check");
  339. return ucs2tochar_dup(desc->bString, desc->bLength);
  340. }
  341. static void _vcom_devinfo_scan_windows__hub(struct lowlevel_device_info **, const char *);
  342. static
  343. void _vcom_devinfo_scan_windows__hubport(struct lowlevel_device_info ** const devinfo_list, HANDLE hubh, const int portno)
  344. {
  345. struct lowlevel_device_info *devinfo;
  346. const size_t conninfosz = sizeof(USB_NODE_CONNECTION_INFORMATION) + (sizeof(USB_PIPE_INFO) * 30);
  347. uint8_t buf[conninfosz];
  348. USB_NODE_CONNECTION_INFORMATION * const conninfo = (USB_NODE_CONNECTION_INFORMATION *)buf;
  349. conninfo->ConnectionIndex = portno;
  350. ULONG respsz;
  351. if (!DeviceIoControl(hubh, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION, conninfo, conninfosz, conninfo, conninfosz, &respsz, NULL))
  352. applogfailinfor(, LOG_ERR, "ioctl", "%s", bfg_strerror(GetLastError(), BST_SYSTEM));
  353. if (conninfo->ConnectionStatus != DeviceConnected)
  354. return;
  355. if (conninfo->DeviceIsHub)
  356. {
  357. const char * const hubpath = windows_usb_get_port_path(hubh, portno);
  358. if (hubpath)
  359. _vcom_devinfo_scan_windows__hub(devinfo_list, hubpath);
  360. return;
  361. }
  362. const USB_DEVICE_DESCRIPTOR * const devdesc = &conninfo->DeviceDescriptor;
  363. char * const serial = windows_usb_get_string(hubh, portno, devdesc->iSerialNumber);
  364. if (!serial)
  365. {
  366. out:
  367. free(serial);
  368. return;
  369. }
  370. const size_t slen = strlen(serial);
  371. char subkey[52 + slen + 18 + 1];
  372. sprintf(subkey, "SYSTEM\\CurrentControlSet\\Enum\\USB\\VID_%04x&PID_%04x\\%s\\Device Parameters",
  373. (unsigned)devdesc->idVendor, (unsigned)devdesc->idProduct, serial);
  374. HKEY hkey;
  375. int e;
  376. if (ERROR_SUCCESS != (e = RegOpenKey(HKEY_LOCAL_MACHINE, subkey, &hkey)))
  377. {
  378. applogfailinfo(LOG_ERR, "open Device Parameters registry key", "%s", bfg_strerror(e, BST_SYSTEM));
  379. goto out;
  380. }
  381. char devpath[0x10] = "\\\\.\\";
  382. DWORD type, sz = sizeof(devpath) - 4;
  383. if (ERROR_SUCCESS != (e = RegQueryValueExA(hkey, "PortName", NULL, &type, (LPBYTE)&devpath[4], &sz)))
  384. {
  385. applogfailinfo(LOG_ERR, "get PortName registry key value", "%s", bfg_strerror(e, BST_SYSTEM));
  386. RegCloseKey(hkey);
  387. goto out;
  388. }
  389. RegCloseKey(hkey);
  390. if (type != REG_SZ)
  391. {
  392. applogfailinfor(, LOG_ERR, "get expected type for PortName registry key value", "%ld", (long)type);
  393. goto out;
  394. }
  395. devinfo = _vcom_devinfo_findorcreate(devinfo_list, devpath);
  396. BFGINIT(devinfo->manufacturer, windows_usb_get_string(hubh, portno, devdesc->iManufacturer));
  397. BFGINIT(devinfo->product, windows_usb_get_string(hubh, portno, devdesc->iProduct));
  398. if (devinfo->serial)
  399. free(serial);
  400. else
  401. devinfo->serial = serial;
  402. }
  403. static
  404. void _vcom_devinfo_scan_windows__hub(struct lowlevel_device_info ** const devinfo_list, const char * const hubpath)
  405. {
  406. HANDLE hubh;
  407. USB_NODE_INFORMATION nodeinfo;
  408. {
  409. char deviceName[4 + strlen(hubpath) + 1];
  410. sprintf(deviceName, "\\\\.\\%s", hubpath);
  411. hubh = CreateFile(deviceName, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
  412. if (hubh == INVALID_HANDLE_VALUE)
  413. applogr(, LOG_ERR, "Error opening USB hub device %s for autodetect: %s", deviceName, bfg_strerror(GetLastError(), BST_SYSTEM));
  414. }
  415. ULONG nBytes;
  416. if (!DeviceIoControl(hubh, IOCTL_USB_GET_NODE_INFORMATION, &nodeinfo, sizeof(nodeinfo), &nodeinfo, sizeof(nodeinfo), &nBytes, NULL))
  417. applogfailinfor(, LOG_ERR, "ioctl", "%s", bfg_strerror(GetLastError(), BST_SYSTEM));
  418. const int portcount = nodeinfo.u.HubInformation.HubDescriptor.bNumberOfPorts;
  419. for (int i = 1; i <= portcount; ++i)
  420. _vcom_devinfo_scan_windows__hubport(devinfo_list, hubh, i);
  421. CloseHandle(hubh);
  422. }
  423. static
  424. char *windows_usb_get_root_hub_path(HANDLE hcntlrh)
  425. {
  426. size_t namesz;
  427. ULONG rsz;
  428. {
  429. USB_ROOT_HUB_NAME pathinfo;
  430. if (!(DeviceIoControl(hcntlrh, IOCTL_USB_GET_ROOT_HUB_NAME, 0, 0, &pathinfo, sizeof(pathinfo), &rsz, NULL) && rsz >= sizeof(pathinfo)))
  431. applogfailinfor(NULL, LOG_ERR, "ioctl (1)", "%s", bfg_strerror(GetLastError(), BST_SYSTEM));
  432. namesz = pathinfo.ActualLength;
  433. }
  434. const size_t bufsz = sizeof(USB_ROOT_HUB_NAME) + namesz;
  435. uint8_t buf[bufsz];
  436. USB_ROOT_HUB_NAME *hubpath = (USB_ROOT_HUB_NAME *)buf;
  437. if (!(DeviceIoControl(hcntlrh, IOCTL_USB_GET_ROOT_HUB_NAME, NULL, 0, hubpath, bufsz, &rsz, NULL) && rsz >= sizeof(*hubpath)))
  438. applogfailinfor(NULL, LOG_ERR, "ioctl (2)", "%s", bfg_strerror(GetLastError(), BST_SYSTEM));
  439. return ucs2tochar_dup(hubpath->RootHubName, hubpath->ActualLength);
  440. }
  441. static
  442. void _vcom_devinfo_scan_windows__hcntlr(struct lowlevel_device_info ** const devinfo_list, HDEVINFO *devinfo, const int i)
  443. {
  444. SP_DEVICE_INTERFACE_DATA devifacedata = {
  445. .cbSize = sizeof(devifacedata),
  446. };
  447. if (!SetupDiEnumDeviceInterfaces(*devinfo, 0, (LPGUID)&WIN_GUID_DEVINTERFACE_USB_HOST_CONTROLLER, i, &devifacedata))
  448. applogfailinfor(, LOG_ERR, "SetupDiEnumDeviceInterfaces", "%s", bfg_strerror(GetLastError(), BST_SYSTEM));
  449. DWORD detailsz;
  450. if (!(!SetupDiGetDeviceInterfaceDetail(*devinfo, &devifacedata, NULL, 0, &detailsz, NULL) && GetLastError() == ERROR_INSUFFICIENT_BUFFER))
  451. applogfailinfor(, LOG_ERR, "SetupDiEnumDeviceInterfaceDetail (1)", "%s", bfg_strerror(GetLastError(), BST_SYSTEM));
  452. PSP_DEVICE_INTERFACE_DETAIL_DATA detail = alloca(detailsz);
  453. detail->cbSize = sizeof(*detail);
  454. if (!SetupDiGetDeviceInterfaceDetail(*devinfo, &devifacedata, detail, detailsz, &detailsz, NULL))
  455. applogfailinfor(, LOG_ERR, "SetupDiEnumDeviceInterfaceDetail (2)", "%s", bfg_strerror(GetLastError(), BST_SYSTEM));
  456. HANDLE hcntlrh = CreateFile(detail->DevicePath, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
  457. if (hcntlrh == INVALID_HANDLE_VALUE)
  458. applogfailinfor(, LOG_DEBUG, "open USB host controller device", "%s", bfg_strerror(GetLastError(), BST_SYSTEM));
  459. char * const hubpath = windows_usb_get_root_hub_path(hcntlrh);
  460. CloseHandle(hcntlrh);
  461. _vcom_devinfo_scan_windows__hub(devinfo_list, hubpath);
  462. free(hubpath);
  463. }
  464. static
  465. void _vcom_devinfo_scan_windows(struct lowlevel_device_info ** const devinfo_list)
  466. {
  467. HDEVINFO devinfo;
  468. devinfo = SetupDiGetClassDevs(&WIN_GUID_DEVINTERFACE_USB_HOST_CONTROLLER, NULL, NULL, (DIGCF_PRESENT | DIGCF_DEVICEINTERFACE));
  469. SP_DEVINFO_DATA devinfodata = {
  470. .cbSize = sizeof(devinfodata),
  471. };
  472. for (int i = 0; SetupDiEnumDeviceInfo(devinfo, i, &devinfodata); ++i)
  473. _vcom_devinfo_scan_windows__hcntlr(devinfo_list, &devinfo, i);
  474. SetupDiDestroyDeviceInfoList(devinfo);
  475. }
  476. #endif
  477. #ifdef WIN32
  478. #define LOAD_SYM(sym) do { \
  479. if (!(sym = dlsym(dll, #sym))) { \
  480. applog(LOG_DEBUG, "Failed to load " #sym ", not using FTDI autodetect"); \
  481. goto out; \
  482. } \
  483. } while(0)
  484. static
  485. char *_ftdi_get_string(char *buf, int i, DWORD flags)
  486. {
  487. if (FT_OK != FT_ListDevices((PVOID)i, buf, FT_LIST_BY_INDEX | flags))
  488. return NULL;
  489. return buf[0] ? buf : NULL;
  490. }
  491. static
  492. void _vcom_devinfo_scan_ftdi(struct lowlevel_device_info ** const devinfo_list)
  493. {
  494. char devpath[] = "\\\\.\\COMnnnnn";
  495. char *devpathnum = &devpath[7];
  496. char **bufptrs;
  497. char *buf;
  498. char serial[64];
  499. struct lowlevel_device_info *devinfo;
  500. DWORD i;
  501. FT_STATUS ftStatus;
  502. DWORD numDevs;
  503. HMODULE dll = LoadLibrary("FTD2XX.DLL");
  504. if (!dll) {
  505. applog(LOG_DEBUG, "FTD2XX.DLL failed to load, not using FTDI autodetect");
  506. return;
  507. }
  508. LOAD_SYM(FT_ListDevices);
  509. LOAD_SYM(FT_Open);
  510. LOAD_SYM(FT_GetComPortNumber);
  511. LOAD_SYM(FT_Close);
  512. ftStatus = FT_ListDevices(&numDevs, NULL, FT_LIST_NUMBER_ONLY);
  513. if (ftStatus != FT_OK) {
  514. applog(LOG_DEBUG, "FTDI device count failed, not using FTDI autodetect");
  515. goto out;
  516. }
  517. applog(LOG_DEBUG, "FTDI reports %u devices", (unsigned)numDevs);
  518. buf = alloca(65 * numDevs);
  519. bufptrs = alloca(sizeof(*bufptrs) * (numDevs + 1));
  520. for (i = 0; i < numDevs; ++i)
  521. bufptrs[i] = &buf[i * 65];
  522. bufptrs[numDevs] = NULL;
  523. ftStatus = FT_ListDevices(bufptrs, &numDevs, FT_LIST_ALL | FT_OPEN_BY_DESCRIPTION);
  524. if (ftStatus != FT_OK) {
  525. applog(LOG_DEBUG, "FTDI device list failed, not using FTDI autodetect");
  526. goto out;
  527. }
  528. for (i = numDevs; i > 0; ) {
  529. --i;
  530. bufptrs[i][64] = '\0';
  531. FT_HANDLE ftHandle;
  532. if (FT_OK != FT_Open(i, &ftHandle))
  533. continue;
  534. LONG lComPortNumber;
  535. ftStatus = FT_GetComPortNumber(ftHandle, &lComPortNumber);
  536. FT_Close(ftHandle);
  537. if (FT_OK != ftStatus || lComPortNumber < 0)
  538. continue;
  539. applog(LOG_ERR, "FT_GetComPortNumber(%p (%ld), %ld)", ftHandle, (long)i, (long)lComPortNumber);
  540. sprintf(devpathnum, "%d", (int)lComPortNumber);
  541. devinfo = _vcom_devinfo_findorcreate(devinfo_list, devpath);
  542. BFGINIT(devinfo->product, (bufptrs[i] && bufptrs[i][0]) ? strdup(bufptrs[i]) : NULL);
  543. BFGINIT(devinfo->serial, maybe_strdup(_ftdi_get_string(serial, i, FT_OPEN_BY_SERIAL_NUMBER)));
  544. }
  545. out:
  546. dlclose(dll);
  547. }
  548. #endif
  549. #ifdef WIN32
  550. extern void _vcom_devinfo_scan_querydosdevice(struct lowlevel_device_info **);
  551. #else
  552. extern void _vcom_devinfo_scan_lsdev(struct lowlevel_device_info **);
  553. #endif
  554. extern bool lowl_usb_attach_kernel_driver(const struct lowlevel_device_info *);
  555. bool vcom_lowl_probe_wrapper(const struct lowlevel_device_info * const info, detectone_func_t detectone)
  556. {
  557. if (info->lowl != &lowl_vcom)
  558. {
  559. if (info->lowl == &lowl_usb)
  560. {
  561. if (lowl_usb_attach_kernel_driver(info))
  562. bfg_need_detect_rescan = true;
  563. }
  564. return false;
  565. }
  566. detectone_meta_info = (struct detectone_meta_info_t){
  567. .manufacturer = info->manufacturer,
  568. .product = info->product,
  569. .serial = info->serial,
  570. };
  571. const bool rv = detectone(info->path);
  572. clear_detectone_meta_info();
  573. return rv;
  574. }
  575. bool _serial_autodetect_found_cb(struct lowlevel_device_info * const devinfo, void *userp)
  576. {
  577. detectone_func_t detectone = userp;
  578. if (bfg_claim_any(NULL, devinfo->path, devinfo->devid))
  579. {
  580. applog(LOG_DEBUG, "%s (%s) is already claimed, skipping probe", devinfo->path, devinfo->devid);
  581. return false;
  582. }
  583. if (devinfo->lowl != &lowl_vcom)
  584. {
  585. if (devinfo->lowl == &lowl_usb)
  586. {
  587. if (lowl_usb_attach_kernel_driver(devinfo))
  588. bfg_need_detect_rescan = true;
  589. }
  590. else
  591. applog(LOG_WARNING, "Non-VCOM %s (%s) matched", devinfo->path, devinfo->devid);
  592. return false;
  593. }
  594. detectone_meta_info = (struct detectone_meta_info_t){
  595. .manufacturer = devinfo->manufacturer,
  596. .product = devinfo->product,
  597. .serial = devinfo->serial,
  598. };
  599. const bool rv = detectone(devinfo->path);
  600. clear_detectone_meta_info();
  601. return rv;
  602. }
  603. int _serial_autodetect(detectone_func_t detectone, ...)
  604. {
  605. va_list needles;
  606. char *needles_array[0x10];
  607. int needlecount = 0;
  608. va_start(needles, detectone);
  609. while ( (needles_array[needlecount++] = va_arg(needles, void *)) )
  610. {}
  611. va_end(needles);
  612. return _lowlevel_detect(_serial_autodetect_found_cb, NULL, (const char **)needles_array, detectone);
  613. }
  614. static
  615. struct lowlevel_device_info *vcom_devinfo_scan()
  616. {
  617. struct lowlevel_device_info *devinfo_hash = NULL;
  618. struct lowlevel_device_info *devinfo_list = NULL;
  619. struct lowlevel_device_info *devinfo, *tmp;
  620. // All 3 USB Strings available:
  621. #ifndef WIN32
  622. _vcom_devinfo_scan_sysfs(&devinfo_hash);
  623. #endif
  624. #ifdef HAVE_WIN_DDKUSB
  625. _vcom_devinfo_scan_windows(&devinfo_hash);
  626. #endif
  627. #ifdef HAVE_LIBUDEV
  628. _vcom_devinfo_scan_udev(&devinfo_hash);
  629. #endif
  630. // Missing Manufacturer:
  631. #ifdef WIN32
  632. _vcom_devinfo_scan_ftdi(&devinfo_hash);
  633. #endif
  634. // All blobbed together:
  635. #ifndef WIN32
  636. _vcom_devinfo_scan_devserial(&devinfo_hash);
  637. #endif
  638. // No info:
  639. #ifdef WIN32
  640. _vcom_devinfo_scan_querydosdevice(&devinfo_hash);
  641. #else
  642. _vcom_devinfo_scan_lsdev(&devinfo_hash);
  643. #endif
  644. // Convert hash to simple list
  645. HASH_ITER(hh, devinfo_hash, devinfo, tmp)
  646. {
  647. LL_PREPEND(devinfo_list, devinfo);
  648. }
  649. HASH_CLEAR(hh, devinfo_hash);
  650. return devinfo_list;
  651. }
  652. struct _device_claim {
  653. struct device_drv *drv;
  654. char *devpath;
  655. UT_hash_handle hh;
  656. };
  657. struct device_drv *bfg_claim_any(struct device_drv * const api, const char *verbose, const char * const devpath)
  658. {
  659. static struct _device_claim *claims = NULL;
  660. struct _device_claim *c;
  661. HASH_FIND_STR(claims, devpath, c);
  662. if (c)
  663. {
  664. if (verbose && opt_debug)
  665. {
  666. char logbuf[LOGBUFSIZ];
  667. logbuf[0] = '\0';
  668. if (api)
  669. tailsprintf(logbuf, sizeof(logbuf), "%s device ", api->dname);
  670. if (verbose[0])
  671. tailsprintf(logbuf, sizeof(logbuf), "%s (%s)", verbose, devpath);
  672. else
  673. tailsprintf(logbuf, sizeof(logbuf), "%s", devpath);
  674. tailsprintf(logbuf, sizeof(logbuf), " already claimed by ");
  675. if (api)
  676. tailsprintf(logbuf, sizeof(logbuf), "other ");
  677. tailsprintf(logbuf, sizeof(logbuf), "driver: %s", c->drv->dname);
  678. _applog(LOG_DEBUG, logbuf);
  679. }
  680. return c->drv;
  681. }
  682. if (!api)
  683. return NULL;
  684. c = malloc(sizeof(*c));
  685. c->devpath = strdup(devpath);
  686. c->drv = api;
  687. HASH_ADD_KEYPTR(hh, claims, c->devpath, strlen(devpath), c);
  688. return NULL;
  689. }
  690. struct device_drv *bfg_claim_any2(struct device_drv * const api, const char * const verbose, const char * const llname, const char * const path)
  691. {
  692. const size_t llnamesz = strlen(llname);
  693. const size_t pathsz = strlen(path);
  694. char devpath[llnamesz + 1 + pathsz + 1];
  695. memcpy(devpath, llname, llnamesz);
  696. devpath[llnamesz] = ':';
  697. memcpy(&devpath[llnamesz+1], path, pathsz + 1);
  698. return bfg_claim_any(api, verbose, devpath);
  699. }
  700. char *devpath_to_devid(const char * const devpath)
  701. {
  702. #ifndef WIN32
  703. char *devs = malloc(6 + (sizeof(dev_t) * 2) + 1);
  704. {
  705. struct stat my_stat;
  706. if (stat(devpath, &my_stat))
  707. return NULL;
  708. memcpy(devs, "dev_t:", 6);
  709. bin2hex(&devs[6], &my_stat.st_rdev, sizeof(dev_t));
  710. }
  711. #else
  712. char *p = strstr(devpath, "COM"), *p2;
  713. if (!p)
  714. return NULL;
  715. const int com = strtol(&p[3], &p2, 10);
  716. if (p2 == p)
  717. return NULL;
  718. char dummy;
  719. const int sz = snprintf(&dummy, 1, "%d", com);
  720. char *devs = malloc(4 + sz + 1);
  721. sprintf(devs, "com:%d", com);
  722. #endif
  723. return devs;
  724. }
  725. struct device_drv *bfg_claim_serial(struct device_drv * const api, const bool verbose, const char * const devpath)
  726. {
  727. char * const devs = _vcom_unique_id(devpath);
  728. if (!devs)
  729. return false;
  730. struct device_drv * const rv = bfg_claim_any(api, (verbose ? devpath : NULL), devs);
  731. free(devs);
  732. return rv;
  733. }
  734. char *bfg_make_devid_usb(const uint8_t usbbus, const uint8_t usbaddr)
  735. {
  736. char * const devpath = malloc(12);
  737. sprintf(devpath, "usb:%03u:%03u", (unsigned)usbbus, (unsigned)usbaddr);
  738. return devpath;
  739. }
  740. struct device_drv *bfg_claim_usb(struct device_drv * const api, const bool verbose, const uint8_t usbbus, const uint8_t usbaddr)
  741. {
  742. char * const devpath = bfg_make_devid_usb(usbbus, usbaddr);
  743. struct device_drv * const rv = bfg_claim_any(api, verbose ? "" : NULL, devpath);
  744. free(devpath);
  745. return rv;
  746. }
  747. #ifdef HAVE_LIBUSB
  748. void cgpu_copy_libusb_strings(struct cgpu_info *cgpu, libusb_device *usb)
  749. {
  750. unsigned char buf[0x20];
  751. libusb_device_handle *h;
  752. struct libusb_device_descriptor desc;
  753. if (LIBUSB_SUCCESS != libusb_open(usb, &h))
  754. return;
  755. if (libusb_get_device_descriptor(usb, &desc))
  756. {
  757. libusb_close(h);
  758. return;
  759. }
  760. if ((!cgpu->dev_manufacturer) && libusb_get_string_descriptor_ascii(h, desc.iManufacturer, buf, sizeof(buf)) >= 0)
  761. cgpu->dev_manufacturer = strdup((void *)buf);
  762. if ((!cgpu->dev_product) && libusb_get_string_descriptor_ascii(h, desc.iProduct, buf, sizeof(buf)) >= 0)
  763. cgpu->dev_product = strdup((void *)buf);
  764. if ((!cgpu->dev_serial) && libusb_get_string_descriptor_ascii(h, desc.iSerialNumber, buf, sizeof(buf)) >= 0)
  765. cgpu->dev_serial = strdup((void *)buf);
  766. libusb_close(h);
  767. }
  768. #endif
  769. // This code is purely for debugging but is very useful for that
  770. // It also took quite a bit of effort so I left it in
  771. // #define TERMIOS_DEBUG 1
  772. // Here to include it at compile time
  773. // It's off by default
  774. #ifndef WIN32
  775. #ifdef TERMIOS_DEBUG
  776. #define BITSSET "Y"
  777. #define BITSNOTSET "N"
  778. int tiospeed(speed_t speed)
  779. {
  780. switch (speed) {
  781. #define IOSPEED(baud) \
  782. case B ## baud: \
  783. return baud; \
  784. // END
  785. #include "iospeeds_local.h"
  786. #undef IOSPEED
  787. default:
  788. return -1;
  789. }
  790. }
  791. void termios_debug(const char *devpath, struct termios *my_termios, const char *msg)
  792. {
  793. applog(LOG_DEBUG, "TIOS: Open %s attributes %s: ispeed=%d ospeed=%d",
  794. devpath, msg, tiospeed(cfgetispeed(my_termios)), tiospeed(cfgetispeed(my_termios)));
  795. #define ISSETI(b) ((my_termios->c_iflag | (b)) ? BITSSET : BITSNOTSET)
  796. applog(LOG_DEBUG, "TIOS: c_iflag: IGNBRK=%s BRKINT=%s IGNPAR=%s PARMRK=%s INPCK=%s ISTRIP=%s INLCR=%s IGNCR=%s ICRNL=%s IUCLC=%s IXON=%s IXANY=%s IOFF=%s IMAXBEL=%s IUTF8=%s",
  797. ISSETI(IGNBRK), ISSETI(BRKINT), ISSETI(IGNPAR), ISSETI(PARMRK),
  798. ISSETI(INPCK), ISSETI(ISTRIP), ISSETI(INLCR), ISSETI(IGNCR),
  799. ISSETI(ICRNL), ISSETI(IUCLC), ISSETI(IXON), ISSETI(IXANY),
  800. ISSETI(IXOFF), ISSETI(IMAXBEL), ISSETI(IUTF8));
  801. #define ISSETO(b) ((my_termios->c_oflag | (b)) ? BITSSET : BITSNOTSET)
  802. #define VALO(b) (my_termios->c_oflag | (b))
  803. applog(LOG_DEBUG, "TIOS: c_oflag: OPOST=%s OLCUC=%s ONLCR=%s OCRNL=%s ONOCR=%s ONLRET=%s OFILL=%s OFDEL=%s NLDLY=%d CRDLY=%d TABDLY=%d BSDLY=%d VTDLY=%d FFDLY=%d",
  804. ISSETO(OPOST), ISSETO(OLCUC), ISSETO(ONLCR), ISSETO(OCRNL),
  805. ISSETO(ONOCR), ISSETO(ONLRET), ISSETO(OFILL), ISSETO(OFDEL),
  806. VALO(NLDLY), VALO(CRDLY), VALO(TABDLY), VALO(BSDLY),
  807. VALO(VTDLY), VALO(FFDLY));
  808. #define ISSETC(b) ((my_termios->c_cflag | (b)) ? BITSSET : BITSNOTSET)
  809. #define VALC(b) (my_termios->c_cflag | (b))
  810. applog(LOG_DEBUG, "TIOS: c_cflag: CBAUDEX=%s CSIZE=%d CSTOPB=%s CREAD=%s PARENB=%s PARODD=%s HUPCL=%s CLOCAL=%s"
  811. #ifdef LOBLK
  812. " LOBLK=%s"
  813. #endif
  814. " CMSPAR=%s CRTSCTS=%s",
  815. ISSETC(CBAUDEX), VALC(CSIZE), ISSETC(CSTOPB), ISSETC(CREAD),
  816. ISSETC(PARENB), ISSETC(PARODD), ISSETC(HUPCL), ISSETC(CLOCAL),
  817. #ifdef LOBLK
  818. ISSETC(LOBLK),
  819. #endif
  820. ISSETC(CMSPAR), ISSETC(CRTSCTS));
  821. #define ISSETL(b) ((my_termios->c_lflag | (b)) ? BITSSET : BITSNOTSET)
  822. applog(LOG_DEBUG, "TIOS: c_lflag: ISIG=%s ICANON=%s XCASE=%s ECHO=%s ECHOE=%s ECHOK=%s ECHONL=%s ECHOCTL=%s ECHOPRT=%s ECHOKE=%s"
  823. #ifdef DEFECHO
  824. " DEFECHO=%s"
  825. #endif
  826. " FLUSHO=%s NOFLSH=%s TOSTOP=%s PENDIN=%s IEXTEN=%s",
  827. ISSETL(ISIG), ISSETL(ICANON), ISSETL(XCASE), ISSETL(ECHO),
  828. ISSETL(ECHOE), ISSETL(ECHOK), ISSETL(ECHONL), ISSETL(ECHOCTL),
  829. ISSETL(ECHOPRT), ISSETL(ECHOKE),
  830. #ifdef DEFECHO
  831. ISSETL(DEFECHO),
  832. #endif
  833. ISSETL(FLUSHO), ISSETL(NOFLSH), ISSETL(TOSTOP), ISSETL(PENDIN),
  834. ISSETL(IEXTEN));
  835. #define VALCC(b) (my_termios->c_cc[b])
  836. applog(LOG_DEBUG, "TIOS: c_cc: VINTR=0x%02x VQUIT=0x%02x VERASE=0x%02x VKILL=0x%02x VEOF=0x%02x VMIN=%u VEOL=0x%02x VTIME=%u VEOL2=0x%02x"
  837. #ifdef VSWTCH
  838. " VSWTCH=0x%02x"
  839. #endif
  840. " VSTART=0x%02x VSTOP=0x%02x VSUSP=0x%02x"
  841. #ifdef VDSUSP
  842. " VDSUSP=0x%02x"
  843. #endif
  844. " VLNEXT=0x%02x VWERASE=0x%02x VREPRINT=0x%02x VDISCARD=0x%02x"
  845. #ifdef VSTATUS
  846. " VSTATUS=0x%02x"
  847. #endif
  848. ,
  849. VALCC(VINTR), VALCC(VQUIT), VALCC(VERASE), VALCC(VKILL),
  850. VALCC(VEOF), VALCC(VMIN), VALCC(VEOL), VALCC(VTIME),
  851. VALCC(VEOL2),
  852. #ifdef VSWTCH
  853. VALCC(VSWTCH),
  854. #endif
  855. VALCC(VSTART), VALCC(VSTOP), VALCC(VSUSP),
  856. #ifdef VDSUSP
  857. VALCC(VDSUSP),
  858. #endif
  859. VALCC(VLNEXT), VALCC(VWERASE),
  860. VALCC(VREPRINT), VALCC(VDISCARD)
  861. #ifdef VSTATUS
  862. ,VALCC(VSTATUS)
  863. #endif
  864. );
  865. }
  866. #endif /* TERMIOS_DEBUG */
  867. speed_t tiospeed_t(int baud)
  868. {
  869. switch (baud) {
  870. #define IOSPEED(baud) \
  871. case baud: \
  872. return B ## baud; \
  873. // END
  874. #include "iospeeds_local.h"
  875. #undef IOSPEED
  876. default:
  877. return B0;
  878. }
  879. }
  880. #endif /* WIN32 */
  881. bool valid_baud(int baud)
  882. {
  883. switch (baud) {
  884. #define IOSPEED(baud) \
  885. case baud: \
  886. return true; \
  887. // END
  888. #include "iospeeds_local.h"
  889. #undef IOSPEED
  890. default:
  891. return false;
  892. }
  893. }
  894. /* NOTE: Linux only supports uint8_t (decisecond) timeouts; limiting it in
  895. * this interface buys us warnings when bad constants are passed in.
  896. */
  897. int serial_open(const char *devpath, unsigned long baud, uint8_t timeout, bool purge)
  898. {
  899. #ifdef WIN32
  900. HANDLE hSerial = CreateFile(devpath, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
  901. if (unlikely(hSerial == INVALID_HANDLE_VALUE))
  902. {
  903. DWORD e = GetLastError();
  904. switch (e) {
  905. case ERROR_ACCESS_DENIED:
  906. applog(LOG_ERR, "Do not have user privileges required to open %s", devpath);
  907. break;
  908. case ERROR_SHARING_VIOLATION:
  909. applog(LOG_ERR, "%s is already in use by another process", devpath);
  910. break;
  911. default:
  912. applog(LOG_DEBUG, "Open %s failed, GetLastError:%u", devpath, (unsigned)e);
  913. break;
  914. }
  915. return -1;
  916. }
  917. if (baud)
  918. {
  919. COMMCONFIG comCfg = {0};
  920. comCfg.dwSize = sizeof(COMMCONFIG);
  921. comCfg.wVersion = 1;
  922. comCfg.dcb.DCBlength = sizeof(DCB);
  923. comCfg.dcb.BaudRate = baud;
  924. comCfg.dcb.fBinary = 1;
  925. comCfg.dcb.fDtrControl = DTR_CONTROL_ENABLE;
  926. comCfg.dcb.fRtsControl = RTS_CONTROL_ENABLE;
  927. comCfg.dcb.ByteSize = 8;
  928. SetCommConfig(hSerial, &comCfg, sizeof(comCfg));
  929. }
  930. // Code must specify a valid timeout value (0 means don't timeout)
  931. const DWORD ctoms = ((DWORD)timeout * 100);
  932. COMMTIMEOUTS cto = {ctoms, 0, ctoms, 0, ctoms};
  933. SetCommTimeouts(hSerial, &cto);
  934. if (purge) {
  935. PurgeComm(hSerial, PURGE_RXABORT);
  936. PurgeComm(hSerial, PURGE_TXABORT);
  937. PurgeComm(hSerial, PURGE_RXCLEAR);
  938. PurgeComm(hSerial, PURGE_TXCLEAR);
  939. }
  940. return _open_osfhandle((intptr_t)hSerial, 0);
  941. #else
  942. int fdDev = open(devpath, O_RDWR | O_CLOEXEC | O_NOCTTY);
  943. if (unlikely(fdDev == -1))
  944. {
  945. if (errno == EACCES)
  946. applog(LOG_ERR, "Do not have user privileges required to open %s", devpath);
  947. else
  948. applog(LOG_DEBUG, "Open %s failed: %s", devpath, bfg_strerror(errno, BST_ERRNO));
  949. return -1;
  950. }
  951. #if defined(LOCK_EX) && defined(LOCK_NB)
  952. if (likely(!flock(fdDev, LOCK_EX | LOCK_NB)))
  953. applog(LOG_DEBUG, "Acquired exclusive advisory lock on %s", devpath);
  954. else
  955. if (errno == EWOULDBLOCK)
  956. {
  957. applog(LOG_ERR, "%s is already in use by another process", devpath);
  958. close(fdDev);
  959. return -1;
  960. }
  961. else
  962. applog(LOG_WARNING, "Failed to acquire exclusive lock on %s: %s (ignoring)", devpath, bfg_strerror(errno, BST_ERRNO));
  963. #endif
  964. struct termios my_termios;
  965. tcgetattr(fdDev, &my_termios);
  966. #ifdef TERMIOS_DEBUG
  967. termios_debug(devpath, &my_termios, "before");
  968. #endif
  969. if (baud)
  970. {
  971. speed_t speed = tiospeed_t(baud);
  972. if (speed == B0)
  973. applog(LOG_WARNING, "Unrecognized baud rate: %lu", baud);
  974. else
  975. {
  976. cfsetispeed(&my_termios, speed);
  977. cfsetospeed(&my_termios, speed);
  978. }
  979. }
  980. my_termios.c_cflag &= ~(CSIZE | PARENB);
  981. my_termios.c_cflag |= CS8;
  982. my_termios.c_cflag |= CREAD;
  983. #ifdef USE_AVALON
  984. // my_termios.c_cflag |= CRTSCTS;
  985. #endif
  986. my_termios.c_cflag |= CLOCAL;
  987. my_termios.c_iflag &= ~(IGNBRK | BRKINT | PARMRK |
  988. ISTRIP | INLCR | IGNCR | ICRNL | IXON);
  989. my_termios.c_oflag &= ~OPOST;
  990. my_termios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
  991. // Code must specify a valid timeout value (0 means don't timeout)
  992. my_termios.c_cc[VTIME] = (cc_t)timeout;
  993. my_termios.c_cc[VMIN] = 0;
  994. #ifdef TERMIOS_DEBUG
  995. termios_debug(devpath, &my_termios, "settings");
  996. #endif
  997. tcsetattr(fdDev, TCSANOW, &my_termios);
  998. #ifdef TERMIOS_DEBUG
  999. tcgetattr(fdDev, &my_termios);
  1000. termios_debug(devpath, &my_termios, "after");
  1001. #endif
  1002. if (purge)
  1003. tcflush(fdDev, TCIOFLUSH);
  1004. return fdDev;
  1005. #endif
  1006. }
  1007. int serial_close(const int fd)
  1008. {
  1009. #if defined(LOCK_EX) && defined(LOCK_NB) && defined(LOCK_UN)
  1010. flock(fd, LOCK_UN);
  1011. #endif
  1012. return close(fd);
  1013. }
  1014. ssize_t _serial_read(int fd, char *buf, size_t bufsiz, char *eol)
  1015. {
  1016. ssize_t len, tlen = 0;
  1017. while (bufsiz) {
  1018. len = read(fd, buf, eol ? 1 : bufsiz);
  1019. if (len < 1)
  1020. break;
  1021. tlen += len;
  1022. if (eol && *eol == buf[0])
  1023. break;
  1024. buf += len;
  1025. bufsiz -= len;
  1026. }
  1027. return tlen;
  1028. }
  1029. #define bailout(...) do { \
  1030. applog(__VA_ARGS__); \
  1031. return NULL; \
  1032. } while(0)
  1033. #define check_magic(L) do { \
  1034. if (1 != fread(buf, 1, 1, f)) \
  1035. bailout(LOG_ERR, "%s: Error reading bitstream ('%c')", \
  1036. repr, L); \
  1037. if (buf[0] != L) \
  1038. bailout(LOG_ERR, "%s: Firmware has wrong magic ('%c')", \
  1039. repr, L); \
  1040. } while(0)
  1041. #define read_str(eng) do { \
  1042. if (1 != fread(buf, 2, 1, f)) \
  1043. bailout(LOG_ERR, "%s: Error reading bitstream (" eng " len)", \
  1044. repr); \
  1045. len = (ubuf[0] << 8) | ubuf[1]; \
  1046. if (len >= sizeof(buf)) \
  1047. bailout(LOG_ERR, "%s: Firmware " eng " too long", \
  1048. repr); \
  1049. if (1 != fread(buf, len, 1, f)) \
  1050. bailout(LOG_ERR, "%s: Error reading bitstream (" eng ")", \
  1051. repr); \
  1052. buf[len] = '\0'; \
  1053. } while(0)
  1054. void _bitstream_not_found(const char *repr, const char *fn)
  1055. {
  1056. applog(LOG_ERR, "ERROR: Unable to load '%s', required for %s to work!", fn, repr);
  1057. applog(LOG_ERR, "ERROR: Please read README.FPGA for instructions");
  1058. }
  1059. FILE *open_xilinx_bitstream(const char *dname, const char *repr, const char *fwfile, unsigned long *out_len)
  1060. {
  1061. char buf[0x100];
  1062. unsigned char *ubuf = (unsigned char*)buf;
  1063. unsigned long len;
  1064. char *p;
  1065. FILE *f = open_bitstream(dname, fwfile);
  1066. if (!f)
  1067. {
  1068. _bitstream_not_found(repr, fwfile);
  1069. return NULL;
  1070. }
  1071. if (1 != fread(buf, 2, 1, f))
  1072. bailout(LOG_ERR, "%s: Error reading bitstream (magic)",
  1073. repr);
  1074. if (buf[0] || buf[1] != 9)
  1075. bailout(LOG_ERR, "%s: Firmware has wrong magic (9)",
  1076. repr);
  1077. if (-1 == fseek(f, 11, SEEK_CUR))
  1078. bailout(LOG_ERR, "%s: Firmware seek failed",
  1079. repr);
  1080. check_magic('a');
  1081. read_str("design name");
  1082. applog(LOG_DEBUG, "%s: Firmware file %s info:",
  1083. repr, fwfile);
  1084. applog(LOG_DEBUG, " Design name: %s", buf);
  1085. p = strrchr(buf, ';') ?: buf;
  1086. p = strrchr(buf, '=') ?: p;
  1087. if (p[0] == '=')
  1088. ++p;
  1089. unsigned long fwusercode = (unsigned long)strtoll(p, &p, 16);
  1090. if (p[0] != '\0')
  1091. bailout(LOG_ERR, "%s: Bad usercode in bitstream file",
  1092. repr);
  1093. if (fwusercode == 0xffffffff)
  1094. bailout(LOG_ERR, "%s: Firmware doesn't support user code",
  1095. repr);
  1096. applog(LOG_DEBUG, " Version: %u, build %u", (unsigned)((fwusercode >> 8) & 0xff), (unsigned)(fwusercode & 0xff));
  1097. check_magic('b');
  1098. read_str("part number");
  1099. applog(LOG_DEBUG, " Part number: %s", buf);
  1100. check_magic('c');
  1101. read_str("build date");
  1102. applog(LOG_DEBUG, " Build date: %s", buf);
  1103. check_magic('d');
  1104. read_str("build time");
  1105. applog(LOG_DEBUG, " Build time: %s", buf);
  1106. check_magic('e');
  1107. if (1 != fread(buf, 4, 1, f))
  1108. bailout(LOG_ERR, "%s: Error reading bitstream (data len)",
  1109. repr);
  1110. len = ((unsigned long)ubuf[0] << 24) | ((unsigned long)ubuf[1] << 16) | (ubuf[2] << 8) | ubuf[3];
  1111. applog(LOG_DEBUG, " Bitstream size: %lu", len);
  1112. *out_len = len;
  1113. return f;
  1114. }
  1115. bool load_bitstream_intelhex(bytes_t *rv, const char *dname, const char *repr, const char *fn)
  1116. {
  1117. char buf[0x100];
  1118. size_t sz;
  1119. uint8_t xsz, xrt;
  1120. uint16_t xaddr;
  1121. FILE *F = open_bitstream(dname, fn);
  1122. if (!F)
  1123. return false;
  1124. while (!feof(F))
  1125. {
  1126. if (unlikely(ferror(F)))
  1127. {
  1128. applog(LOG_ERR, "Error reading '%s'", fn);
  1129. goto ihxerr;
  1130. }
  1131. if (!fgets(buf, sizeof(buf), F))
  1132. goto ihxerr;
  1133. if (unlikely(buf[0] != ':'))
  1134. goto ihxerr;
  1135. if (unlikely(!(
  1136. hex2bin(&xsz, &buf[1], 1)
  1137. && hex2bin((unsigned char*)&xaddr, &buf[3], 2)
  1138. && hex2bin(&xrt, &buf[7], 1)
  1139. )))
  1140. {
  1141. applog(LOG_ERR, "Error parsing in '%s'", fn);
  1142. goto ihxerr;
  1143. }
  1144. switch (xrt)
  1145. {
  1146. case 0: // data
  1147. break;
  1148. case 1: // EOF
  1149. fclose(F);
  1150. return true;
  1151. default:
  1152. applog(LOG_ERR, "Unsupported record type in '%s'", fn);
  1153. goto ihxerr;
  1154. }
  1155. xaddr = be16toh(xaddr);
  1156. sz = bytes_len(rv);
  1157. bytes_resize(rv, xaddr + xsz);
  1158. if (sz < xaddr)
  1159. memset(&bytes_buf(rv)[sz], 0xff, xaddr - sz);
  1160. if (unlikely(!(hex2bin(&bytes_buf(rv)[xaddr], &buf[9], xsz))))
  1161. {
  1162. applog(LOG_ERR, "Error parsing data in '%s'", fn);
  1163. goto ihxerr;
  1164. }
  1165. // TODO: checksum
  1166. }
  1167. ihxerr:
  1168. fclose(F);
  1169. bytes_reset(rv);
  1170. return false;
  1171. }
  1172. bool load_bitstream_bytes(bytes_t *rv, const char *dname, const char *repr, const char *fileprefix)
  1173. {
  1174. FILE *F;
  1175. size_t fplen = strlen(fileprefix);
  1176. char fnbuf[fplen + 4 + 1];
  1177. int e;
  1178. bytes_reset(rv);
  1179. memcpy(fnbuf, fileprefix, fplen);
  1180. strcpy(&fnbuf[fplen], ".bin");
  1181. F = open_bitstream(dname, fnbuf);
  1182. if (F)
  1183. {
  1184. char buf[0x100];
  1185. size_t sz;
  1186. while ( (sz = fread(buf, 1, sizeof(buf), F)) )
  1187. bytes_append(rv, buf, sz);
  1188. e = ferror(F);
  1189. fclose(F);
  1190. if (unlikely(e))
  1191. {
  1192. applog(LOG_ERR, "Error reading '%s'", fnbuf);
  1193. bytes_reset(rv);
  1194. }
  1195. else
  1196. return true;
  1197. }
  1198. strcpy(&fnbuf[fplen], ".ihx");
  1199. if (load_bitstream_intelhex(rv, dname, repr, fnbuf))
  1200. return true;
  1201. // TODO: Xilinx
  1202. _bitstream_not_found(repr, fnbuf);
  1203. return false;
  1204. }
  1205. #ifndef WIN32
  1206. int get_serial_cts(int fd)
  1207. {
  1208. int flags;
  1209. if (!fd)
  1210. return -1;
  1211. ioctl(fd, TIOCMGET, &flags);
  1212. return (flags & TIOCM_CTS) ? 1 : 0;
  1213. }
  1214. int set_serial_rts(int fd, int rts)
  1215. {
  1216. int flags;
  1217. if (!fd)
  1218. return -1;
  1219. ioctl(fd, TIOCMGET, &flags);
  1220. if (rts)
  1221. flags |= TIOCM_RTS;
  1222. else
  1223. flags &= ~TIOCM_RTS;
  1224. ioctl(fd, TIOCMSET, &flags);
  1225. return flags & TIOCM_CTS;
  1226. }
  1227. #else
  1228. int get_serial_cts(const int fd)
  1229. {
  1230. if (!fd)
  1231. return -1;
  1232. const HANDLE fh = (HANDLE)_get_osfhandle(fd);
  1233. if (!fh)
  1234. return -1;
  1235. DWORD flags;
  1236. if (!GetCommModemStatus(fh, &flags))
  1237. return -1;
  1238. return (flags & MS_CTS_ON) ? 1 : 0;
  1239. }
  1240. #endif // ! WIN32
  1241. struct lowlevel_driver lowl_vcom = {
  1242. .dname = "vcom",
  1243. .devinfo_scan = vcom_devinfo_scan,
  1244. };