fpgautils.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. /*
  2. * Copyright 2012 Luke Dashjr
  3. * Copyright 2012 Andrew Smith
  4. *
  5. * This program is free software; you can redistribute it and/or modify it
  6. * under the terms of the GNU General Public License as published by the Free
  7. * Software Foundation; either version 3 of the License, or (at your option)
  8. * any later version. See COPYING for more details.
  9. */
  10. #include "config.h"
  11. #include <stdint.h>
  12. #include <stdlib.h>
  13. #include <sys/types.h>
  14. #include <dirent.h>
  15. #include <string.h>
  16. #ifndef WIN32
  17. #include <errno.h>
  18. #include <termios.h>
  19. #include <sys/stat.h>
  20. #include <unistd.h>
  21. #include <fcntl.h>
  22. #ifndef O_CLOEXEC
  23. #define O_CLOEXEC 0
  24. #endif
  25. #else /* WIN32 */
  26. #include <windows.h>
  27. #include <io.h>
  28. #define dlsym (void*)GetProcAddress
  29. #define dlclose FreeLibrary
  30. typedef unsigned long FT_STATUS;
  31. typedef PVOID FT_HANDLE;
  32. __stdcall FT_STATUS (*FT_ListDevices)(PVOID pArg1, PVOID pArg2, DWORD Flags);
  33. __stdcall FT_STATUS (*FT_Open)(int idx, FT_HANDLE*);
  34. __stdcall FT_STATUS (*FT_GetComPortNumber)(FT_HANDLE, LPLONG lplComPortNumber);
  35. __stdcall FT_STATUS (*FT_Close)(FT_HANDLE);
  36. const uint32_t FT_OPEN_BY_DESCRIPTION = 2;
  37. const uint32_t FT_LIST_ALL = 0x20000000;
  38. const uint32_t FT_LIST_NUMBER_ONLY = 0x80000000;
  39. enum {
  40. FT_OK,
  41. };
  42. #endif /* WIN32 */
  43. #ifdef HAVE_LIBUDEV
  44. #include <libudev.h>
  45. #endif
  46. #include "elist.h"
  47. #include "logging.h"
  48. #include "miner.h"
  49. #include "fpgautils.h"
  50. #ifdef HAVE_LIBUDEV
  51. int serial_autodetect_udev(detectone_func_t detectone, const char*prodname)
  52. {
  53. struct udev *udev = udev_new();
  54. struct udev_enumerate *enumerate = udev_enumerate_new(udev);
  55. struct udev_list_entry *list_entry;
  56. char found = 0;
  57. udev_enumerate_add_match_subsystem(enumerate, "tty");
  58. udev_enumerate_add_match_property(enumerate, "ID_MODEL", prodname);
  59. udev_enumerate_scan_devices(enumerate);
  60. udev_list_entry_foreach(list_entry, udev_enumerate_get_list_entry(enumerate)) {
  61. struct udev_device *device = udev_device_new_from_syspath(
  62. udev_enumerate_get_udev(enumerate),
  63. udev_list_entry_get_name(list_entry)
  64. );
  65. if (!device)
  66. continue;
  67. const char *devpath = udev_device_get_devnode(device);
  68. if (devpath && detectone(devpath))
  69. ++found;
  70. udev_device_unref(device);
  71. }
  72. udev_enumerate_unref(enumerate);
  73. udev_unref(udev);
  74. return found;
  75. }
  76. #else
  77. int serial_autodetect_udev(__maybe_unused detectone_func_t detectone, __maybe_unused const char*prodname)
  78. {
  79. return 0;
  80. }
  81. #endif
  82. int serial_autodetect_devserial(detectone_func_t detectone, const char*prodname)
  83. {
  84. #ifndef WIN32
  85. DIR *D;
  86. struct dirent *de;
  87. const char udevdir[] = "/dev/serial/by-id";
  88. char devpath[sizeof(udevdir) + 1 + NAME_MAX];
  89. char *devfile = devpath + sizeof(udevdir);
  90. char found = 0;
  91. D = opendir(udevdir);
  92. if (!D)
  93. return 0;
  94. memcpy(devpath, udevdir, sizeof(udevdir) - 1);
  95. devpath[sizeof(udevdir) - 1] = '/';
  96. while ( (de = readdir(D)) ) {
  97. if (!strstr(de->d_name, prodname))
  98. continue;
  99. strcpy(devfile, de->d_name);
  100. if (detectone(devpath))
  101. ++found;
  102. }
  103. closedir(D);
  104. return found;
  105. #else
  106. return 0;
  107. #endif
  108. }
  109. #ifdef WIN32
  110. #define LOAD_SYM(sym) do { \
  111. if (!(sym = dlsym(dll, #sym))) { \
  112. applog(LOG_DEBUG, "Failed to load " #sym ", not using FTDI autodetect"); \
  113. goto out; \
  114. } \
  115. } while(0)
  116. int serial_autodetect_ftdi(detectone_func_t detectone, const char *needle, const char *needle2)
  117. {
  118. char devpath[] = "\\\\.\\COMnnnnn";
  119. char *devpathnum = &devpath[7];
  120. char **bufptrs;
  121. char *buf;
  122. int found = 0;
  123. int i;
  124. FT_STATUS ftStatus;
  125. DWORD numDevs;
  126. HMODULE dll = LoadLibrary("FTD2XX.DLL");
  127. if (!dll) {
  128. applog(LOG_DEBUG, "FTD2XX.DLL failed to load, not using FTDI autodetect");
  129. return 0;
  130. }
  131. LOAD_SYM(FT_ListDevices);
  132. LOAD_SYM(FT_Open);
  133. LOAD_SYM(FT_GetComPortNumber);
  134. LOAD_SYM(FT_Close);
  135. ftStatus = FT_ListDevices(&numDevs, NULL, FT_LIST_NUMBER_ONLY);
  136. if (ftStatus != FT_OK) {
  137. applog(LOG_DEBUG, "FTDI device count failed, not using FTDI autodetect");
  138. goto out;
  139. }
  140. applog(LOG_DEBUG, "FTDI reports %u devices", (unsigned)numDevs);
  141. buf = alloca(65 * numDevs);
  142. bufptrs = alloca(sizeof(*bufptrs) * (numDevs + 1));
  143. for (i = 0; i < numDevs; ++i)
  144. bufptrs[i] = &buf[i * 65];
  145. bufptrs[numDevs] = NULL;
  146. ftStatus = FT_ListDevices(bufptrs, &numDevs, FT_LIST_ALL | FT_OPEN_BY_DESCRIPTION);
  147. if (ftStatus != FT_OK) {
  148. applog(LOG_DEBUG, "FTDI device list failed, not using FTDI autodetect");
  149. goto out;
  150. }
  151. for (i = numDevs; i > 0; ) {
  152. --i;
  153. bufptrs[i][64] = '\0';
  154. if (!(strstr(bufptrs[i], needle) && (!needle2 || strstr(bufptrs[i], needle2))))
  155. continue;
  156. FT_HANDLE ftHandle;
  157. if (FT_OK != FT_Open(i, &ftHandle))
  158. continue;
  159. LONG lComPortNumber;
  160. ftStatus = FT_GetComPortNumber(ftHandle, &lComPortNumber);
  161. FT_Close(ftHandle);
  162. if (FT_OK != ftStatus || lComPortNumber < 0)
  163. continue;
  164. sprintf(devpathnum, "%d", (int)lComPortNumber);
  165. if (detectone(devpath))
  166. ++found;
  167. }
  168. out:
  169. dlclose(dll);
  170. return found;
  171. }
  172. #else
  173. int serial_autodetect_ftdi(__maybe_unused detectone_func_t detectone, __maybe_unused const char *needle, __maybe_unused const char *needle2)
  174. {
  175. return 0;
  176. }
  177. #endif
  178. struct device_api *serial_claim(const char *devpath, struct device_api *api);
  179. int _serial_detect(struct device_api *api, detectone_func_t detectone, autoscan_func_t autoscan, int flags)
  180. {
  181. struct string_elist *iter, *tmp;
  182. const char *dev, *colon;
  183. bool inhibitauto = false;
  184. char found = 0;
  185. bool forceauto = flags & 1;
  186. bool hasname;
  187. size_t namel = strlen(api->name);
  188. size_t dnamel = strlen(api->dname);
  189. list_for_each_entry_safe(iter, tmp, &scan_devices, list) {
  190. dev = iter->string;
  191. if ((colon = strchr(dev, ':')) && colon[1] != '\0') {
  192. size_t idlen = colon - dev;
  193. // allow either name:device or dname:device
  194. if ((idlen != namel || strncasecmp(dev, api->name, idlen))
  195. && (idlen != dnamel || strncasecmp(dev, api->dname, idlen)))
  196. continue;
  197. dev = colon + 1;
  198. hasname = true;
  199. }
  200. else
  201. hasname = false;
  202. if (!strcmp(dev, "auto"))
  203. forceauto = true;
  204. else if (!strcmp(dev, "noauto"))
  205. inhibitauto = true;
  206. else
  207. if ((flags & 2) && !hasname)
  208. continue;
  209. else
  210. if (!detectone)
  211. {} // do nothing
  212. else
  213. if (serial_claim(dev, NULL))
  214. {
  215. applog(LOG_DEBUG, "%s is already claimed... skipping probes", dev);
  216. string_elist_del(iter);
  217. }
  218. else if (detectone(dev)) {
  219. string_elist_del(iter);
  220. inhibitauto = true;
  221. ++found;
  222. }
  223. }
  224. if ((forceauto || !inhibitauto) && autoscan)
  225. found += autoscan();
  226. return found;
  227. }
  228. #ifndef WIN32
  229. typedef dev_t my_dev_t;
  230. #else
  231. typedef int my_dev_t;
  232. #endif
  233. struct _device_claim {
  234. struct device_api *api;
  235. my_dev_t dev;
  236. UT_hash_handle hh;
  237. };
  238. struct device_api *serial_claim(const char *devpath, struct device_api *api)
  239. {
  240. static struct _device_claim *claims = NULL;
  241. struct _device_claim *c;
  242. my_dev_t dev;
  243. #ifndef WIN32
  244. {
  245. struct stat my_stat;
  246. if (stat(devpath, &my_stat))
  247. return NULL;
  248. dev = my_stat.st_rdev;
  249. }
  250. #else
  251. {
  252. char *p = strstr(devpath, "COM"), *p2;
  253. if (!p)
  254. return NULL;
  255. dev = strtol(&p[3], &p2, 10);
  256. if (p2 == p)
  257. return NULL;
  258. }
  259. #endif
  260. HASH_FIND(hh, claims, &dev, sizeof(dev), c);
  261. if (c)
  262. return c->api;
  263. if (!api)
  264. return NULL;
  265. c = malloc(sizeof(*c));
  266. c->dev = dev;
  267. c->api = api;
  268. HASH_ADD(hh, claims, dev, sizeof(dev), c);
  269. return NULL;
  270. }
  271. // This code is purely for debugging but is very useful for that
  272. // It also took quite a bit of effort so I left it in
  273. // #define TERMIOS_DEBUG 1
  274. // Here to include it at compile time
  275. // It's off by default
  276. #ifndef WIN32
  277. #ifdef TERMIOS_DEBUG
  278. #define BITSSET "Y"
  279. #define BITSNOTSET "N"
  280. int tiospeed(speed_t speed)
  281. {
  282. switch (speed) {
  283. case B0:
  284. return 0;
  285. case B50:
  286. return 50;
  287. case B75:
  288. return 75;
  289. case B110:
  290. return 110;
  291. case B134:
  292. return 134;
  293. case B150:
  294. return 150;
  295. case B200:
  296. return 200;
  297. case B300:
  298. return 300;
  299. case B600:
  300. return 600;
  301. case B1200:
  302. return 1200;
  303. case B1800:
  304. return 1800;
  305. case B2400:
  306. return 2400;
  307. case B4800:
  308. return 4800;
  309. case B9600:
  310. return 9600;
  311. case B19200:
  312. return 19200;
  313. case B38400:
  314. return 38400;
  315. case B57600:
  316. return 57600;
  317. case B115200:
  318. return 115200;
  319. case B230400:
  320. return 230400;
  321. case B460800:
  322. return 460800;
  323. case B500000:
  324. return 500000;
  325. case B576000:
  326. return 576000;
  327. case B921600:
  328. return 921600;
  329. case B1000000:
  330. return 1000000;
  331. case B1152000:
  332. return 1152000;
  333. case B1500000:
  334. return 1500000;
  335. case B2000000:
  336. return 2000000;
  337. case B2500000:
  338. return 2500000;
  339. case B3000000:
  340. return 3000000;
  341. case B3500000:
  342. return 3500000;
  343. case B4000000:
  344. return 4000000;
  345. default:
  346. return -1;
  347. }
  348. }
  349. void termios_debug(const char *devpath, struct termios *my_termios, const char *msg)
  350. {
  351. applog(LOG_DEBUG, "TIOS: Open %s attributes %s: ispeed=%d ospeed=%d",
  352. devpath, msg, tiospeed(cfgetispeed(my_termios)), tiospeed(cfgetispeed(my_termios)));
  353. #define ISSETI(b) ((my_termios->c_iflag | (b)) ? BITSSET : BITSNOTSET)
  354. 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",
  355. ISSETI(IGNBRK), ISSETI(BRKINT), ISSETI(IGNPAR), ISSETI(PARMRK),
  356. ISSETI(INPCK), ISSETI(ISTRIP), ISSETI(INLCR), ISSETI(IGNCR),
  357. ISSETI(ICRNL), ISSETI(IUCLC), ISSETI(IXON), ISSETI(IXANY),
  358. ISSETI(IXOFF), ISSETI(IMAXBEL), ISSETI(IUTF8));
  359. #define ISSETO(b) ((my_termios->c_oflag | (b)) ? BITSSET : BITSNOTSET)
  360. #define VALO(b) (my_termios->c_oflag | (b))
  361. 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",
  362. ISSETO(OPOST), ISSETO(OLCUC), ISSETO(ONLCR), ISSETO(OCRNL),
  363. ISSETO(ONOCR), ISSETO(ONLRET), ISSETO(OFILL), ISSETO(OFDEL),
  364. VALO(NLDLY), VALO(CRDLY), VALO(TABDLY), VALO(BSDLY),
  365. VALO(VTDLY), VALO(FFDLY));
  366. #define ISSETC(b) ((my_termios->c_cflag | (b)) ? BITSSET : BITSNOTSET)
  367. #define VALC(b) (my_termios->c_cflag | (b))
  368. applog(LOG_DEBUG, "TIOS: c_cflag: CBAUDEX=%s CSIZE=%d CSTOPB=%s CREAD=%s PARENB=%s PARODD=%s HUPCL=%s CLOCAL=%s"
  369. #ifdef LOBLK
  370. " LOBLK=%s"
  371. #endif
  372. " CMSPAR=%s CRTSCTS=%s",
  373. ISSETC(CBAUDEX), VALC(CSIZE), ISSETC(CSTOPB), ISSETC(CREAD),
  374. ISSETC(PARENB), ISSETC(PARODD), ISSETC(HUPCL), ISSETC(CLOCAL),
  375. #ifdef LOBLK
  376. ISSETC(LOBLK),
  377. #endif
  378. ISSETC(CMSPAR), ISSETC(CRTSCTS));
  379. #define ISSETL(b) ((my_termios->c_lflag | (b)) ? BITSSET : BITSNOTSET)
  380. 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"
  381. #ifdef DEFECHO
  382. " DEFECHO=%s"
  383. #endif
  384. " FLUSHO=%s NOFLSH=%s TOSTOP=%s PENDIN=%s IEXTEN=%s",
  385. ISSETL(ISIG), ISSETL(ICANON), ISSETL(XCASE), ISSETL(ECHO),
  386. ISSETL(ECHOE), ISSETL(ECHOK), ISSETL(ECHONL), ISSETL(ECHOCTL),
  387. ISSETL(ECHOPRT), ISSETL(ECHOKE),
  388. #ifdef DEFECHO
  389. ISSETL(DEFECHO),
  390. #endif
  391. ISSETL(FLUSHO), ISSETL(NOFLSH), ISSETL(TOSTOP), ISSETL(PENDIN),
  392. ISSETL(IEXTEN));
  393. #define VALCC(b) (my_termios->c_cc[b])
  394. 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"
  395. #ifdef VSWTCH
  396. " VSWTCH=0x%02x"
  397. #endif
  398. " VSTART=0x%02x VSTOP=0x%02x VSUSP=0x%02x"
  399. #ifdef VDSUSP
  400. " VDSUSP=0x%02x"
  401. #endif
  402. " VLNEXT=0x%02x VWERASE=0x%02x VREPRINT=0x%02x VDISCARD=0x%02x"
  403. #ifdef VSTATUS
  404. " VSTATUS=0x%02x"
  405. #endif
  406. ,
  407. VALCC(VINTR), VALCC(VQUIT), VALCC(VERASE), VALCC(VKILL),
  408. VALCC(VEOF), VALCC(VMIN), VALCC(VEOL), VALCC(VTIME),
  409. VALCC(VEOL2),
  410. #ifdef VSWTCH
  411. VALCC(VSWTCH),
  412. #endif
  413. VALCC(VSTART), VALCC(VSTOP), VALCC(VSUSP),
  414. #ifdef VDSUSP
  415. VALCC(VDSUSP),
  416. #endif
  417. VALCC(VLNEXT), VALCC(VWERASE),
  418. VALCC(VREPRINT), VALCC(VDISCARD)
  419. #ifdef VSTATUS
  420. ,VALCC(VSTATUS)
  421. #endif
  422. );
  423. }
  424. #endif
  425. #endif
  426. /* NOTE: Linux only supports uint8_t (decisecond) timeouts; limiting it in
  427. * this interface buys us warnings when bad constants are passed in.
  428. */
  429. int serial_open(const char *devpath, unsigned long baud, uint8_t timeout, bool purge)
  430. {
  431. #ifdef WIN32
  432. HANDLE hSerial = CreateFile(devpath, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
  433. if (unlikely(hSerial == INVALID_HANDLE_VALUE))
  434. {
  435. DWORD e = GetLastError();
  436. switch (e) {
  437. case ERROR_ACCESS_DENIED:
  438. applog(LOG_ERR, "Do not have user privileges required to open %s", devpath);
  439. break;
  440. case ERROR_SHARING_VIOLATION:
  441. applog(LOG_ERR, "%s is already in use by another process", devpath);
  442. break;
  443. default:
  444. applog(LOG_DEBUG, "Open %s failed, GetLastError:%u", devpath, e);
  445. break;
  446. }
  447. return -1;
  448. }
  449. // thanks to af_newbie for pointers about this
  450. COMMCONFIG comCfg = {0};
  451. comCfg.dwSize = sizeof(COMMCONFIG);
  452. comCfg.wVersion = 1;
  453. comCfg.dcb.DCBlength = sizeof(DCB);
  454. comCfg.dcb.BaudRate = baud;
  455. comCfg.dcb.fBinary = 1;
  456. comCfg.dcb.fDtrControl = DTR_CONTROL_ENABLE;
  457. comCfg.dcb.fRtsControl = RTS_CONTROL_ENABLE;
  458. comCfg.dcb.ByteSize = 8;
  459. SetCommConfig(hSerial, &comCfg, sizeof(comCfg));
  460. // Code must specify a valid timeout value (0 means don't timeout)
  461. const DWORD ctoms = ((DWORD)timeout * 100);
  462. COMMTIMEOUTS cto = {ctoms, 0, ctoms, 0, ctoms};
  463. SetCommTimeouts(hSerial, &cto);
  464. if (purge) {
  465. PurgeComm(hSerial, PURGE_RXABORT);
  466. PurgeComm(hSerial, PURGE_TXABORT);
  467. PurgeComm(hSerial, PURGE_RXCLEAR);
  468. PurgeComm(hSerial, PURGE_TXCLEAR);
  469. }
  470. return _open_osfhandle((LONG)hSerial, 0);
  471. #else
  472. int fdDev = open(devpath, O_RDWR | O_CLOEXEC | O_NOCTTY);
  473. if (unlikely(fdDev == -1))
  474. {
  475. if (errno == EACCES)
  476. applog(LOG_ERR, "Do not have user privileges required to open %s", devpath);
  477. else
  478. applog(LOG_DEBUG, "Open %s failed, errno:%d", devpath, errno);
  479. return -1;
  480. }
  481. struct termios my_termios;
  482. tcgetattr(fdDev, &my_termios);
  483. #ifdef TERMIOS_DEBUG
  484. termios_debug(devpath, &my_termios, "before");
  485. #endif
  486. switch (baud) {
  487. case 0:
  488. break;
  489. case 57600:
  490. cfsetispeed(&my_termios, B57600);
  491. cfsetospeed(&my_termios, B57600);
  492. break;
  493. case 115200:
  494. cfsetispeed(&my_termios, B115200);
  495. cfsetospeed(&my_termios, B115200);
  496. break;
  497. // TODO: try some higher speeds with the Icarus and BFL to see
  498. // if they support them and if setting them makes any difference
  499. // N.B. B3000000 doesn't work on Icarus
  500. default:
  501. applog(LOG_WARNING, "Unrecognized baud rate: %lu", baud);
  502. }
  503. my_termios.c_cflag |= CS8;
  504. my_termios.c_cflag |= CREAD;
  505. my_termios.c_cflag |= CLOCAL;
  506. my_termios.c_cflag &= ~(CSIZE | PARENB);
  507. my_termios.c_iflag &= ~(IGNBRK | BRKINT | PARMRK |
  508. ISTRIP | INLCR | IGNCR | ICRNL | IXON);
  509. my_termios.c_oflag &= ~OPOST;
  510. my_termios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
  511. // Code must specify a valid timeout value (0 means don't timeout)
  512. my_termios.c_cc[VTIME] = (cc_t)timeout;
  513. my_termios.c_cc[VMIN] = 0;
  514. #ifdef TERMIOS_DEBUG
  515. termios_debug(devpath, &my_termios, "settings");
  516. #endif
  517. tcsetattr(fdDev, TCSANOW, &my_termios);
  518. #ifdef TERMIOS_DEBUG
  519. tcgetattr(fdDev, &my_termios);
  520. termios_debug(devpath, &my_termios, "after");
  521. #endif
  522. if (purge)
  523. tcflush(fdDev, TCIOFLUSH);
  524. return fdDev;
  525. #endif
  526. }
  527. ssize_t _serial_read(int fd, char *buf, size_t bufsiz, char *eol)
  528. {
  529. ssize_t len, tlen = 0;
  530. while (bufsiz) {
  531. len = read(fd, buf, eol ? 1 : bufsiz);
  532. if (len < 1)
  533. break;
  534. tlen += len;
  535. if (eol && *eol == buf[0])
  536. break;
  537. buf += len;
  538. bufsiz -= len;
  539. }
  540. return tlen;
  541. }
  542. static FILE *_open_bitstream(const char *path, const char *subdir, const char *filename)
  543. {
  544. char fullpath[PATH_MAX];
  545. strcpy(fullpath, path);
  546. strcat(fullpath, "/");
  547. if (subdir) {
  548. strcat(fullpath, subdir);
  549. strcat(fullpath, "/");
  550. }
  551. strcat(fullpath, filename);
  552. return fopen(fullpath, "rb");
  553. }
  554. #define _open_bitstream(path, subdir) do { \
  555. f = _open_bitstream(path, subdir, filename); \
  556. if (f) \
  557. return f; \
  558. } while(0)
  559. #define _open_bitstream3(path) do { \
  560. _open_bitstream(path, dname); \
  561. _open_bitstream(path, "bitstreams"); \
  562. _open_bitstream(path, NULL); \
  563. } while(0)
  564. FILE *open_bitstream(const char *dname, const char *filename)
  565. {
  566. FILE *f;
  567. _open_bitstream3(opt_kernel_path);
  568. _open_bitstream3(cgminer_path);
  569. _open_bitstream3(".");
  570. return NULL;
  571. }
  572. #define bailout(...) do { \
  573. applog(__VA_ARGS__); \
  574. return NULL; \
  575. } while(0)
  576. #define check_magic(L) do { \
  577. if (1 != fread(buf, 1, 1, f)) \
  578. bailout(LOG_ERR, "%s %u: Error reading firmware ('%c')", \
  579. cgpu->api->name, cgpu->device_id, L); \
  580. if (buf[0] != L) \
  581. bailout(LOG_ERR, "%s %u: Firmware has wrong magic ('%c')", \
  582. cgpu->api->name, cgpu->device_id, L); \
  583. } while(0)
  584. #define read_str(eng) do { \
  585. if (1 != fread(buf, 2, 1, f)) \
  586. bailout(LOG_ERR, "%s %u: Error reading firmware (" eng " len)", \
  587. cgpu->api->name, cgpu->device_id); \
  588. len = (ubuf[0] << 8) | ubuf[1]; \
  589. if (len >= sizeof(buf)) \
  590. bailout(LOG_ERR, "%s %u: Firmware " eng " too long", \
  591. cgpu->api->name, cgpu->device_id); \
  592. if (1 != fread(buf, len, 1, f)) \
  593. bailout(LOG_ERR, "%s %u: Error reading firmware (" eng ")", \
  594. cgpu->api->name, cgpu->device_id); \
  595. buf[len] = '\0'; \
  596. } while(0)
  597. FILE *open_xilinx_bitstream(struct cgpu_info *cgpu, const char *fwfile, unsigned long *out_len)
  598. {
  599. char buf[0x100];
  600. unsigned char *ubuf = (unsigned char*)buf;
  601. unsigned long len;
  602. char *p;
  603. FILE *f = open_bitstream(cgpu->api->dname, fwfile);
  604. if (!f)
  605. bailout(LOG_ERR, "%s %u: Error opening firmware file %s",
  606. cgpu->api->name, cgpu->device_id, fwfile);
  607. if (1 != fread(buf, 2, 1, f))
  608. bailout(LOG_ERR, "%s %u: Error reading firmware (magic)",
  609. cgpu->api->name, cgpu->device_id);
  610. if (buf[0] || buf[1] != 9)
  611. bailout(LOG_ERR, "%s %u: Firmware has wrong magic (9)",
  612. cgpu->api->name, cgpu->device_id);
  613. if (-1 == fseek(f, 11, SEEK_CUR))
  614. bailout(LOG_ERR, "%s %u: Firmware seek failed",
  615. cgpu->api->name, cgpu->device_id);
  616. check_magic('a');
  617. read_str("design name");
  618. applog(LOG_DEBUG, "%s %u: Firmware file %s info:",
  619. cgpu->api->name, cgpu->device_id, fwfile);
  620. applog(LOG_DEBUG, " Design name: %s", buf);
  621. p = strrchr(buf, ';') ?: buf;
  622. p = strrchr(buf, '=') ?: p;
  623. if (p[0] == '=')
  624. ++p;
  625. unsigned long fwusercode = (unsigned long)strtoll(p, &p, 16);
  626. if (p[0] != '\0')
  627. bailout(LOG_ERR, "%s %u: Bad usercode in firmware file",
  628. cgpu->api->name, cgpu->device_id);
  629. if (fwusercode == 0xffffffff)
  630. bailout(LOG_ERR, "%s %u: Firmware doesn't support user code",
  631. cgpu->api->name, cgpu->device_id);
  632. applog(LOG_DEBUG, " Version: %u, build %u", (fwusercode >> 8) & 0xff, fwusercode & 0xff);
  633. check_magic('b');
  634. read_str("part number");
  635. applog(LOG_DEBUG, " Part number: %s", buf);
  636. check_magic('c');
  637. read_str("build date");
  638. applog(LOG_DEBUG, " Build date: %s", buf);
  639. check_magic('d');
  640. read_str("build time");
  641. applog(LOG_DEBUG, " Build time: %s", buf);
  642. check_magic('e');
  643. if (1 != fread(buf, 4, 1, f))
  644. bailout(LOG_ERR, "%s %u: Error reading firmware (data len)",
  645. cgpu->api->name, cgpu->device_id);
  646. len = ((unsigned long)ubuf[0] << 24) | ((unsigned long)ubuf[1] << 16) | (ubuf[2] << 8) | ubuf[3];
  647. applog(LOG_DEBUG, " Bitstream size: %lu", len);
  648. *out_len = len;
  649. return f;
  650. }