fpgautils.c 36 KB

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