fpgautils.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  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(__maybe_unused detectone_func_t detectone, __maybe_unused 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. DWORD 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. applog(LOG_ERR, "FT_GetComPortNumber(%p (%ld), %ld)", ftHandle, (long)i, (long)lComPortNumber);
  165. sprintf(devpathnum, "%d", (int)lComPortNumber);
  166. if (detectone(devpath))
  167. ++found;
  168. }
  169. out:
  170. dlclose(dll);
  171. return found;
  172. }
  173. #else
  174. int serial_autodetect_ftdi(__maybe_unused detectone_func_t detectone, __maybe_unused const char *needle, __maybe_unused const char *needle2)
  175. {
  176. return 0;
  177. }
  178. #endif
  179. struct device_api *serial_claim(const char *devpath, struct device_api *api);
  180. int _serial_detect(struct device_api *api, detectone_func_t detectone, autoscan_func_t autoscan, int flags)
  181. {
  182. struct string_elist *iter, *tmp;
  183. const char *dev, *colon;
  184. bool inhibitauto = false;
  185. char found = 0;
  186. bool forceauto = flags & 1;
  187. bool hasname;
  188. size_t namel = strlen(api->name);
  189. size_t dnamel = strlen(api->dname);
  190. list_for_each_entry_safe(iter, tmp, &scan_devices, list) {
  191. dev = iter->string;
  192. if ((colon = strchr(dev, ':')) && colon[1] != '\0') {
  193. size_t idlen = colon - dev;
  194. // allow either name:device or dname:device
  195. if ((idlen != namel || strncasecmp(dev, api->name, idlen))
  196. && (idlen != dnamel || strncasecmp(dev, api->dname, idlen)))
  197. continue;
  198. dev = colon + 1;
  199. hasname = true;
  200. }
  201. else
  202. hasname = false;
  203. if (!strcmp(dev, "auto"))
  204. forceauto = true;
  205. else if (!strcmp(dev, "noauto"))
  206. inhibitauto = true;
  207. else
  208. if ((flags & 2) && !hasname)
  209. continue;
  210. else
  211. if (!detectone)
  212. {} // do nothing
  213. else
  214. if (serial_claim(dev, NULL))
  215. {
  216. applog(LOG_DEBUG, "%s is already claimed... skipping probes", dev);
  217. string_elist_del(iter);
  218. }
  219. else if (detectone(dev)) {
  220. string_elist_del(iter);
  221. inhibitauto = true;
  222. ++found;
  223. }
  224. }
  225. if ((forceauto || !inhibitauto) && autoscan)
  226. found += autoscan();
  227. return found;
  228. }
  229. #ifndef WIN32
  230. typedef dev_t my_dev_t;
  231. #else
  232. typedef int my_dev_t;
  233. #endif
  234. struct _device_claim {
  235. struct device_api *api;
  236. my_dev_t dev;
  237. UT_hash_handle hh;
  238. };
  239. struct device_api *serial_claim(const char *devpath, struct device_api *api)
  240. {
  241. static struct _device_claim *claims = NULL;
  242. struct _device_claim *c;
  243. my_dev_t dev;
  244. #ifndef WIN32
  245. {
  246. struct stat my_stat;
  247. if (stat(devpath, &my_stat))
  248. return NULL;
  249. dev = my_stat.st_rdev;
  250. }
  251. #else
  252. {
  253. char *p = strstr(devpath, "COM"), *p2;
  254. if (!p)
  255. return NULL;
  256. dev = strtol(&p[3], &p2, 10);
  257. if (p2 == p)
  258. return NULL;
  259. }
  260. #endif
  261. HASH_FIND(hh, claims, &dev, sizeof(dev), c);
  262. if (c)
  263. return c->api;
  264. if (!api)
  265. return NULL;
  266. c = malloc(sizeof(*c));
  267. c->dev = dev;
  268. c->api = api;
  269. HASH_ADD(hh, claims, dev, sizeof(dev), c);
  270. return NULL;
  271. }
  272. // This code is purely for debugging but is very useful for that
  273. // It also took quite a bit of effort so I left it in
  274. // #define TERMIOS_DEBUG 1
  275. // Here to include it at compile time
  276. // It's off by default
  277. #ifndef WIN32
  278. #ifdef TERMIOS_DEBUG
  279. #define BITSSET "Y"
  280. #define BITSNOTSET "N"
  281. int tiospeed(speed_t speed)
  282. {
  283. switch (speed) {
  284. case B0:
  285. return 0;
  286. case B50:
  287. return 50;
  288. case B75:
  289. return 75;
  290. case B110:
  291. return 110;
  292. case B134:
  293. return 134;
  294. case B150:
  295. return 150;
  296. case B200:
  297. return 200;
  298. case B300:
  299. return 300;
  300. case B600:
  301. return 600;
  302. case B1200:
  303. return 1200;
  304. case B1800:
  305. return 1800;
  306. case B2400:
  307. return 2400;
  308. case B4800:
  309. return 4800;
  310. case B9600:
  311. return 9600;
  312. case B19200:
  313. return 19200;
  314. case B38400:
  315. return 38400;
  316. case B57600:
  317. return 57600;
  318. case B115200:
  319. return 115200;
  320. case B230400:
  321. return 230400;
  322. case B460800:
  323. return 460800;
  324. case B500000:
  325. return 500000;
  326. case B576000:
  327. return 576000;
  328. case B921600:
  329. return 921600;
  330. case B1000000:
  331. return 1000000;
  332. case B1152000:
  333. return 1152000;
  334. case B1500000:
  335. return 1500000;
  336. case B2000000:
  337. return 2000000;
  338. case B2500000:
  339. return 2500000;
  340. case B3000000:
  341. return 3000000;
  342. case B3500000:
  343. return 3500000;
  344. case B4000000:
  345. return 4000000;
  346. default:
  347. return -1;
  348. }
  349. }
  350. void termios_debug(const char *devpath, struct termios *my_termios, const char *msg)
  351. {
  352. applog(LOG_DEBUG, "TIOS: Open %s attributes %s: ispeed=%d ospeed=%d",
  353. devpath, msg, tiospeed(cfgetispeed(my_termios)), tiospeed(cfgetispeed(my_termios)));
  354. #define ISSETI(b) ((my_termios->c_iflag | (b)) ? BITSSET : BITSNOTSET)
  355. 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",
  356. ISSETI(IGNBRK), ISSETI(BRKINT), ISSETI(IGNPAR), ISSETI(PARMRK),
  357. ISSETI(INPCK), ISSETI(ISTRIP), ISSETI(INLCR), ISSETI(IGNCR),
  358. ISSETI(ICRNL), ISSETI(IUCLC), ISSETI(IXON), ISSETI(IXANY),
  359. ISSETI(IXOFF), ISSETI(IMAXBEL), ISSETI(IUTF8));
  360. #define ISSETO(b) ((my_termios->c_oflag | (b)) ? BITSSET : BITSNOTSET)
  361. #define VALO(b) (my_termios->c_oflag | (b))
  362. 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",
  363. ISSETO(OPOST), ISSETO(OLCUC), ISSETO(ONLCR), ISSETO(OCRNL),
  364. ISSETO(ONOCR), ISSETO(ONLRET), ISSETO(OFILL), ISSETO(OFDEL),
  365. VALO(NLDLY), VALO(CRDLY), VALO(TABDLY), VALO(BSDLY),
  366. VALO(VTDLY), VALO(FFDLY));
  367. #define ISSETC(b) ((my_termios->c_cflag | (b)) ? BITSSET : BITSNOTSET)
  368. #define VALC(b) (my_termios->c_cflag | (b))
  369. applog(LOG_DEBUG, "TIOS: c_cflag: CBAUDEX=%s CSIZE=%d CSTOPB=%s CREAD=%s PARENB=%s PARODD=%s HUPCL=%s CLOCAL=%s"
  370. #ifdef LOBLK
  371. " LOBLK=%s"
  372. #endif
  373. " CMSPAR=%s CRTSCTS=%s",
  374. ISSETC(CBAUDEX), VALC(CSIZE), ISSETC(CSTOPB), ISSETC(CREAD),
  375. ISSETC(PARENB), ISSETC(PARODD), ISSETC(HUPCL), ISSETC(CLOCAL),
  376. #ifdef LOBLK
  377. ISSETC(LOBLK),
  378. #endif
  379. ISSETC(CMSPAR), ISSETC(CRTSCTS));
  380. #define ISSETL(b) ((my_termios->c_lflag | (b)) ? BITSSET : BITSNOTSET)
  381. 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"
  382. #ifdef DEFECHO
  383. " DEFECHO=%s"
  384. #endif
  385. " FLUSHO=%s NOFLSH=%s TOSTOP=%s PENDIN=%s IEXTEN=%s",
  386. ISSETL(ISIG), ISSETL(ICANON), ISSETL(XCASE), ISSETL(ECHO),
  387. ISSETL(ECHOE), ISSETL(ECHOK), ISSETL(ECHONL), ISSETL(ECHOCTL),
  388. ISSETL(ECHOPRT), ISSETL(ECHOKE),
  389. #ifdef DEFECHO
  390. ISSETL(DEFECHO),
  391. #endif
  392. ISSETL(FLUSHO), ISSETL(NOFLSH), ISSETL(TOSTOP), ISSETL(PENDIN),
  393. ISSETL(IEXTEN));
  394. #define VALCC(b) (my_termios->c_cc[b])
  395. 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"
  396. #ifdef VSWTCH
  397. " VSWTCH=0x%02x"
  398. #endif
  399. " VSTART=0x%02x VSTOP=0x%02x VSUSP=0x%02x"
  400. #ifdef VDSUSP
  401. " VDSUSP=0x%02x"
  402. #endif
  403. " VLNEXT=0x%02x VWERASE=0x%02x VREPRINT=0x%02x VDISCARD=0x%02x"
  404. #ifdef VSTATUS
  405. " VSTATUS=0x%02x"
  406. #endif
  407. ,
  408. VALCC(VINTR), VALCC(VQUIT), VALCC(VERASE), VALCC(VKILL),
  409. VALCC(VEOF), VALCC(VMIN), VALCC(VEOL), VALCC(VTIME),
  410. VALCC(VEOL2),
  411. #ifdef VSWTCH
  412. VALCC(VSWTCH),
  413. #endif
  414. VALCC(VSTART), VALCC(VSTOP), VALCC(VSUSP),
  415. #ifdef VDSUSP
  416. VALCC(VDSUSP),
  417. #endif
  418. VALCC(VLNEXT), VALCC(VWERASE),
  419. VALCC(VREPRINT), VALCC(VDISCARD)
  420. #ifdef VSTATUS
  421. ,VALCC(VSTATUS)
  422. #endif
  423. );
  424. }
  425. #endif
  426. #endif
  427. /* NOTE: Linux only supports uint8_t (decisecond) timeouts; limiting it in
  428. * this interface buys us warnings when bad constants are passed in.
  429. */
  430. int serial_open(const char *devpath, unsigned long baud, uint8_t timeout, bool purge)
  431. {
  432. #ifdef WIN32
  433. HANDLE hSerial = CreateFile(devpath, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
  434. if (unlikely(hSerial == INVALID_HANDLE_VALUE))
  435. {
  436. DWORD e = GetLastError();
  437. switch (e) {
  438. case ERROR_ACCESS_DENIED:
  439. applog(LOG_ERR, "Do not have user privileges required to open %s", devpath);
  440. break;
  441. case ERROR_SHARING_VIOLATION:
  442. applog(LOG_ERR, "%s is already in use by another process", devpath);
  443. break;
  444. default:
  445. applog(LOG_DEBUG, "Open %s failed, GetLastError:%u", devpath, e);
  446. break;
  447. }
  448. return -1;
  449. }
  450. // thanks to af_newbie for pointers about this
  451. COMMCONFIG comCfg = {0};
  452. comCfg.dwSize = sizeof(COMMCONFIG);
  453. comCfg.wVersion = 1;
  454. comCfg.dcb.DCBlength = sizeof(DCB);
  455. comCfg.dcb.BaudRate = baud;
  456. comCfg.dcb.fBinary = 1;
  457. comCfg.dcb.fDtrControl = DTR_CONTROL_ENABLE;
  458. comCfg.dcb.fRtsControl = RTS_CONTROL_ENABLE;
  459. comCfg.dcb.ByteSize = 8;
  460. SetCommConfig(hSerial, &comCfg, sizeof(comCfg));
  461. // Code must specify a valid timeout value (0 means don't timeout)
  462. const DWORD ctoms = ((DWORD)timeout * 100);
  463. COMMTIMEOUTS cto = {ctoms, 0, ctoms, 0, ctoms};
  464. SetCommTimeouts(hSerial, &cto);
  465. if (purge) {
  466. PurgeComm(hSerial, PURGE_RXABORT);
  467. PurgeComm(hSerial, PURGE_TXABORT);
  468. PurgeComm(hSerial, PURGE_RXCLEAR);
  469. PurgeComm(hSerial, PURGE_TXCLEAR);
  470. }
  471. return _open_osfhandle((LONG)hSerial, 0);
  472. #else
  473. int fdDev = open(devpath, O_RDWR | O_CLOEXEC | O_NOCTTY);
  474. if (unlikely(fdDev == -1))
  475. {
  476. if (errno == EACCES)
  477. applog(LOG_ERR, "Do not have user privileges required to open %s", devpath);
  478. else
  479. applog(LOG_DEBUG, "Open %s failed, errno:%d", devpath, errno);
  480. return -1;
  481. }
  482. struct termios my_termios;
  483. tcgetattr(fdDev, &my_termios);
  484. #ifdef TERMIOS_DEBUG
  485. termios_debug(devpath, &my_termios, "before");
  486. #endif
  487. switch (baud) {
  488. case 0:
  489. break;
  490. case 57600:
  491. cfsetispeed(&my_termios, B57600);
  492. cfsetospeed(&my_termios, B57600);
  493. break;
  494. case 115200:
  495. cfsetispeed(&my_termios, B115200);
  496. cfsetospeed(&my_termios, B115200);
  497. break;
  498. // TODO: try some higher speeds with the Icarus and BFL to see
  499. // if they support them and if setting them makes any difference
  500. // N.B. B3000000 doesn't work on Icarus
  501. default:
  502. applog(LOG_WARNING, "Unrecognized baud rate: %lu", baud);
  503. }
  504. my_termios.c_cflag |= CS8;
  505. my_termios.c_cflag |= CREAD;
  506. my_termios.c_cflag |= CLOCAL;
  507. my_termios.c_cflag &= ~(CSIZE | PARENB);
  508. my_termios.c_iflag &= ~(IGNBRK | BRKINT | PARMRK |
  509. ISTRIP | INLCR | IGNCR | ICRNL | IXON);
  510. my_termios.c_oflag &= ~OPOST;
  511. my_termios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
  512. // Code must specify a valid timeout value (0 means don't timeout)
  513. my_termios.c_cc[VTIME] = (cc_t)timeout;
  514. my_termios.c_cc[VMIN] = 0;
  515. #ifdef TERMIOS_DEBUG
  516. termios_debug(devpath, &my_termios, "settings");
  517. #endif
  518. tcsetattr(fdDev, TCSANOW, &my_termios);
  519. #ifdef TERMIOS_DEBUG
  520. tcgetattr(fdDev, &my_termios);
  521. termios_debug(devpath, &my_termios, "after");
  522. #endif
  523. if (purge)
  524. tcflush(fdDev, TCIOFLUSH);
  525. return fdDev;
  526. #endif
  527. }
  528. ssize_t _serial_read(int fd, char *buf, size_t bufsiz, char *eol)
  529. {
  530. ssize_t len, tlen = 0;
  531. while (bufsiz) {
  532. len = read(fd, buf, eol ? 1 : bufsiz);
  533. if (len < 1)
  534. break;
  535. tlen += len;
  536. if (eol && *eol == buf[0])
  537. break;
  538. buf += len;
  539. bufsiz -= len;
  540. }
  541. return tlen;
  542. }
  543. static FILE *_open_bitstream(const char *path, const char *subdir, const char *filename)
  544. {
  545. char fullpath[PATH_MAX];
  546. strcpy(fullpath, path);
  547. strcat(fullpath, "/");
  548. if (subdir) {
  549. strcat(fullpath, subdir);
  550. strcat(fullpath, "/");
  551. }
  552. strcat(fullpath, filename);
  553. return fopen(fullpath, "rb");
  554. }
  555. #define _open_bitstream(path, subdir) do { \
  556. f = _open_bitstream(path, subdir, filename); \
  557. if (f) \
  558. return f; \
  559. } while(0)
  560. #define _open_bitstream3(path) do { \
  561. _open_bitstream(path, dname); \
  562. _open_bitstream(path, "bitstreams"); \
  563. _open_bitstream(path, NULL); \
  564. } while(0)
  565. FILE *open_bitstream(const char *dname, const char *filename)
  566. {
  567. FILE *f;
  568. _open_bitstream3(opt_kernel_path);
  569. _open_bitstream3(cgminer_path);
  570. _open_bitstream3(".");
  571. return NULL;
  572. }
  573. #define bailout(...) do { \
  574. applog(__VA_ARGS__); \
  575. return NULL; \
  576. } while(0)
  577. #define check_magic(L) do { \
  578. if (1 != fread(buf, 1, 1, f)) \
  579. bailout(LOG_ERR, "%s %u: Error reading firmware ('%c')", \
  580. cgpu->api->name, cgpu->device_id, L); \
  581. if (buf[0] != L) \
  582. bailout(LOG_ERR, "%s %u: Firmware has wrong magic ('%c')", \
  583. cgpu->api->name, cgpu->device_id, L); \
  584. } while(0)
  585. #define read_str(eng) do { \
  586. if (1 != fread(buf, 2, 1, f)) \
  587. bailout(LOG_ERR, "%s %u: Error reading firmware (" eng " len)", \
  588. cgpu->api->name, cgpu->device_id); \
  589. len = (ubuf[0] << 8) | ubuf[1]; \
  590. if (len >= sizeof(buf)) \
  591. bailout(LOG_ERR, "%s %u: Firmware " eng " too long", \
  592. cgpu->api->name, cgpu->device_id); \
  593. if (1 != fread(buf, len, 1, f)) \
  594. bailout(LOG_ERR, "%s %u: Error reading firmware (" eng ")", \
  595. cgpu->api->name, cgpu->device_id); \
  596. buf[len] = '\0'; \
  597. } while(0)
  598. FILE *open_xilinx_bitstream(struct cgpu_info *cgpu, const char *fwfile, unsigned long *out_len)
  599. {
  600. char buf[0x100];
  601. unsigned char *ubuf = (unsigned char*)buf;
  602. unsigned long len;
  603. char *p;
  604. FILE *f = open_bitstream(cgpu->api->dname, fwfile);
  605. if (!f)
  606. bailout(LOG_ERR, "%s %u: Error opening firmware file %s",
  607. cgpu->api->name, cgpu->device_id, fwfile);
  608. if (1 != fread(buf, 2, 1, f))
  609. bailout(LOG_ERR, "%s %u: Error reading firmware (magic)",
  610. cgpu->api->name, cgpu->device_id);
  611. if (buf[0] || buf[1] != 9)
  612. bailout(LOG_ERR, "%s %u: Firmware has wrong magic (9)",
  613. cgpu->api->name, cgpu->device_id);
  614. if (-1 == fseek(f, 11, SEEK_CUR))
  615. bailout(LOG_ERR, "%s %u: Firmware seek failed",
  616. cgpu->api->name, cgpu->device_id);
  617. check_magic('a');
  618. read_str("design name");
  619. applog(LOG_DEBUG, "%s %u: Firmware file %s info:",
  620. cgpu->api->name, cgpu->device_id, fwfile);
  621. applog(LOG_DEBUG, " Design name: %s", buf);
  622. p = strrchr(buf, ';') ?: buf;
  623. p = strrchr(buf, '=') ?: p;
  624. if (p[0] == '=')
  625. ++p;
  626. unsigned long fwusercode = (unsigned long)strtoll(p, &p, 16);
  627. if (p[0] != '\0')
  628. bailout(LOG_ERR, "%s %u: Bad usercode in firmware file",
  629. cgpu->api->name, cgpu->device_id);
  630. if (fwusercode == 0xffffffff)
  631. bailout(LOG_ERR, "%s %u: Firmware doesn't support user code",
  632. cgpu->api->name, cgpu->device_id);
  633. applog(LOG_DEBUG, " Version: %u, build %u", (fwusercode >> 8) & 0xff, fwusercode & 0xff);
  634. check_magic('b');
  635. read_str("part number");
  636. applog(LOG_DEBUG, " Part number: %s", buf);
  637. check_magic('c');
  638. read_str("build date");
  639. applog(LOG_DEBUG, " Build date: %s", buf);
  640. check_magic('d');
  641. read_str("build time");
  642. applog(LOG_DEBUG, " Build time: %s", buf);
  643. check_magic('e');
  644. if (1 != fread(buf, 4, 1, f))
  645. bailout(LOG_ERR, "%s %u: Error reading firmware (data len)",
  646. cgpu->api->name, cgpu->device_id);
  647. len = ((unsigned long)ubuf[0] << 24) | ((unsigned long)ubuf[1] << 16) | (ubuf[2] << 8) | ubuf[3];
  648. applog(LOG_DEBUG, " Bitstream size: %lu", len);
  649. *out_len = len;
  650. return f;
  651. }