fpgautils.c 19 KB

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