fpgautils.c 38 KB

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