fpgautils.c 36 KB

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