fpgautils.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  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 <sys/types.h>
  13. #include <dirent.h>
  14. #include <string.h>
  15. #ifndef WIN32
  16. #include <errno.h>
  17. #include <termios.h>
  18. #include <sys/stat.h>
  19. #include <unistd.h>
  20. #include <fcntl.h>
  21. #ifndef O_CLOEXEC
  22. #define O_CLOEXEC 0
  23. #endif
  24. #else /* WIN32 */
  25. #include <windows.h>
  26. #include <io.h>
  27. #define dlsym (void*)GetProcAddress
  28. #define dlclose FreeLibrary
  29. typedef unsigned long FT_STATUS;
  30. typedef PVOID FT_HANDLE;
  31. __stdcall FT_STATUS (*FT_ListDevices)(PVOID pArg1, PVOID pArg2, DWORD Flags);
  32. __stdcall FT_STATUS (*FT_Open)(int idx, FT_HANDLE*);
  33. __stdcall FT_STATUS (*FT_GetComPortNumber)(FT_HANDLE, LPLONG lplComPortNumber);
  34. __stdcall FT_STATUS (*FT_Close)(FT_HANDLE);
  35. const uint32_t FT_OPEN_BY_DESCRIPTION = 2;
  36. const uint32_t FT_LIST_ALL = 0x20000000;
  37. const uint32_t FT_LIST_NUMBER_ONLY = 0x80000000;
  38. enum {
  39. FT_OK,
  40. };
  41. #endif /* WIN32 */
  42. #ifdef HAVE_LIBUDEV
  43. #include <libudev.h>
  44. #endif
  45. #include "elist.h"
  46. #include "fpgautils.h"
  47. #include "logging.h"
  48. #include "miner.h"
  49. #ifdef HAVE_LIBUDEV
  50. int
  51. 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
  78. serial_autodetect_udev(__maybe_unused detectone_func_t detectone, __maybe_unused const char*prodname)
  79. {
  80. return 0;
  81. }
  82. #endif
  83. int
  84. serial_autodetect_devserial(detectone_func_t detectone, const char*prodname)
  85. {
  86. #ifndef WIN32
  87. DIR *D;
  88. struct dirent *de;
  89. const char udevdir[] = "/dev/serial/by-id";
  90. char devpath[sizeof(udevdir) + 1 + NAME_MAX];
  91. char *devfile = devpath + sizeof(udevdir);
  92. char found = 0;
  93. D = opendir(udevdir);
  94. if (!D)
  95. return 0;
  96. memcpy(devpath, udevdir, sizeof(udevdir) - 1);
  97. devpath[sizeof(udevdir) - 1] = '/';
  98. while ( (de = readdir(D)) ) {
  99. if (!strstr(de->d_name, prodname))
  100. continue;
  101. strcpy(devfile, de->d_name);
  102. if (detectone(devpath))
  103. ++found;
  104. }
  105. closedir(D);
  106. return found;
  107. #else
  108. return 0;
  109. #endif
  110. }
  111. #ifdef WIN32
  112. #define LOAD_SYM(sym) do { \
  113. if (!(sym = dlsym(dll, #sym))) { \
  114. applog(LOG_DEBUG, "Failed to load " #sym ", not using FTDI autodetect"); \
  115. goto out; \
  116. } \
  117. } while(0)
  118. int serial_autodetect_ftdi(detectone_func_t detectone, const char *needle, const char *needle2)
  119. {
  120. char devpath[] = "\\\\.\\COMnnnnn";
  121. char *devpathnum = &devpath[7];
  122. char **bufptrs;
  123. char *buf;
  124. int found = 0;
  125. int i;
  126. FT_STATUS ftStatus;
  127. DWORD numDevs;
  128. HMODULE dll = LoadLibrary("FTD2XX.DLL");
  129. if (!dll) {
  130. applog(LOG_DEBUG, "FTD2XX.DLL failed to load, not using FTDI autodetect");
  131. return 0;
  132. }
  133. LOAD_SYM(FT_ListDevices);
  134. LOAD_SYM(FT_Open);
  135. LOAD_SYM(FT_GetComPortNumber);
  136. LOAD_SYM(FT_Close);
  137. ftStatus = FT_ListDevices(&numDevs, NULL, FT_LIST_NUMBER_ONLY);
  138. if (ftStatus != FT_OK) {
  139. applog(LOG_DEBUG, "FTDI device count failed, not using FTDI autodetect");
  140. goto out;
  141. }
  142. applog(LOG_DEBUG, "FTDI reports %u devices", (unsigned)numDevs);
  143. buf = alloca(65 * numDevs);
  144. bufptrs = alloca(sizeof(*bufptrs) * (numDevs + 1));
  145. for (i = 0; i < numDevs; ++i)
  146. bufptrs[i] = &buf[i * 65];
  147. bufptrs[numDevs] = NULL;
  148. ftStatus = FT_ListDevices(bufptrs, &numDevs, FT_LIST_ALL | FT_OPEN_BY_DESCRIPTION);
  149. if (ftStatus != FT_OK) {
  150. applog(LOG_DEBUG, "FTDI device list failed, not using FTDI autodetect");
  151. goto out;
  152. }
  153. for (i = numDevs; i > 0; ) {
  154. --i;
  155. bufptrs[i][64] = '\0';
  156. if (!(strstr(bufptrs[i], needle) && (!needle2 || strstr(bufptrs[i], needle2))))
  157. continue;
  158. FT_HANDLE ftHandle;
  159. if (FT_OK != FT_Open(i, &ftHandle))
  160. continue;
  161. LONG lComPortNumber;
  162. ftStatus = FT_GetComPortNumber(ftHandle, &lComPortNumber);
  163. FT_Close(ftHandle);
  164. if (FT_OK != ftStatus || lComPortNumber < 0)
  165. continue;
  166. sprintf(devpathnum, "%d", (int)lComPortNumber);
  167. if (detectone(devpath))
  168. ++found;
  169. }
  170. out:
  171. dlclose(dll);
  172. return found;
  173. }
  174. #else
  175. int serial_autodetect_ftdi(__maybe_unused detectone_func_t detectone, __maybe_unused const char *needle, __maybe_unused const char *needle2)
  176. {
  177. return 0;
  178. }
  179. #endif
  180. int
  181. _serial_detect(const char*dname, detectone_func_t detectone, autoscan_func_t autoscan, int flags)
  182. {
  183. struct string_elist *iter, *tmp;
  184. const char*s, *p;
  185. bool inhibitauto = false;
  186. char found = 0;
  187. bool forceauto = flags & 1;
  188. bool hasname;
  189. size_t dnamel = strlen(dname);
  190. list_for_each_entry_safe(iter, tmp, &scan_devices, list) {
  191. s = iter->string;
  192. if ((p = strchr(s, ':')) && p[1] != '\0') {
  193. size_t plen = p - s;
  194. if (plen != dnamel || strncasecmp(s, dname, plen))
  195. continue;
  196. s = p + 1;
  197. hasname = true;
  198. }
  199. else
  200. hasname = false;
  201. if (!strcmp(s, "auto"))
  202. forceauto = true;
  203. else
  204. if (!strcmp(s, "noauto"))
  205. inhibitauto = true;
  206. else
  207. if ((flags & 2) && !hasname)
  208. continue;
  209. else
  210. if (detectone(s)) {
  211. string_elist_del(iter);
  212. inhibitauto = true;
  213. ++found;
  214. }
  215. }
  216. if ((forceauto || !inhibitauto) && autoscan)
  217. found += autoscan();
  218. return found;
  219. }
  220. // This code is purely for debugging but is very useful for that
  221. // It also took quite a bit of effort so I left it in
  222. // #define TERMIOS_DEBUG 1
  223. // Here to include it at compile time
  224. // It's off by default
  225. #ifndef WIN32
  226. #ifdef TERMIOS_DEBUG
  227. #define BITSSET "Y"
  228. #define BITSNOTSET "N"
  229. int tiospeed(speed_t speed)
  230. {
  231. switch (speed) {
  232. case B0:
  233. return 0;
  234. case B50:
  235. return 50;
  236. case B75:
  237. return 75;
  238. case B110:
  239. return 110;
  240. case B134:
  241. return 134;
  242. case B150:
  243. return 150;
  244. case B200:
  245. return 200;
  246. case B300:
  247. return 300;
  248. case B600:
  249. return 600;
  250. case B1200:
  251. return 1200;
  252. case B1800:
  253. return 1800;
  254. case B2400:
  255. return 2400;
  256. case B4800:
  257. return 4800;
  258. case B9600:
  259. return 9600;
  260. case B19200:
  261. return 19200;
  262. case B38400:
  263. return 38400;
  264. case B57600:
  265. return 57600;
  266. case B115200:
  267. return 115200;
  268. case B230400:
  269. return 230400;
  270. case B460800:
  271. return 460800;
  272. case B500000:
  273. return 500000;
  274. case B576000:
  275. return 576000;
  276. case B921600:
  277. return 921600;
  278. case B1000000:
  279. return 1000000;
  280. case B1152000:
  281. return 1152000;
  282. case B1500000:
  283. return 1500000;
  284. case B2000000:
  285. return 2000000;
  286. case B2500000:
  287. return 2500000;
  288. case B3000000:
  289. return 3000000;
  290. case B3500000:
  291. return 3500000;
  292. case B4000000:
  293. return 4000000;
  294. default:
  295. return -1;
  296. }
  297. }
  298. void termios_debug(const char *devpath, struct termios *my_termios, const char *msg)
  299. {
  300. applog(LOG_DEBUG, "TIOS: Open %s attributes %s: ispeed=%d ospeed=%d",
  301. devpath, msg, tiospeed(cfgetispeed(my_termios)), tiospeed(cfgetispeed(my_termios)));
  302. #define ISSETI(b) ((my_termios->c_iflag | (b)) ? BITSSET : BITSNOTSET)
  303. 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",
  304. ISSETI(IGNBRK), ISSETI(BRKINT), ISSETI(IGNPAR), ISSETI(PARMRK),
  305. ISSETI(INPCK), ISSETI(ISTRIP), ISSETI(INLCR), ISSETI(IGNCR),
  306. ISSETI(ICRNL), ISSETI(IUCLC), ISSETI(IXON), ISSETI(IXANY),
  307. ISSETI(IXOFF), ISSETI(IMAXBEL), ISSETI(IUTF8));
  308. #define ISSETO(b) ((my_termios->c_oflag | (b)) ? BITSSET : BITSNOTSET)
  309. #define VALO(b) (my_termios->c_oflag | (b))
  310. 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",
  311. ISSETO(OPOST), ISSETO(OLCUC), ISSETO(ONLCR), ISSETO(OCRNL),
  312. ISSETO(ONOCR), ISSETO(ONLRET), ISSETO(OFILL), ISSETO(OFDEL),
  313. VALO(NLDLY), VALO(CRDLY), VALO(TABDLY), VALO(BSDLY),
  314. VALO(VTDLY), VALO(FFDLY));
  315. #define ISSETC(b) ((my_termios->c_cflag | (b)) ? BITSSET : BITSNOTSET)
  316. #define VALC(b) (my_termios->c_cflag | (b))
  317. applog(LOG_DEBUG, "TIOS: c_cflag: CBAUDEX=%s CSIZE=%d CSTOPB=%s CREAD=%s PARENB=%s PARODD=%s HUPCL=%s CLOCAL=%s"
  318. #ifdef LOBLK
  319. " LOBLK=%s"
  320. #endif
  321. " CMSPAR=%s CRTSCTS=%s",
  322. ISSETC(CBAUDEX), VALC(CSIZE), ISSETC(CSTOPB), ISSETC(CREAD),
  323. ISSETC(PARENB), ISSETC(PARODD), ISSETC(HUPCL), ISSETC(CLOCAL),
  324. #ifdef LOBLK
  325. ISSETC(LOBLK),
  326. #endif
  327. ISSETC(CMSPAR), ISSETC(CRTSCTS));
  328. #define ISSETL(b) ((my_termios->c_lflag | (b)) ? BITSSET : BITSNOTSET)
  329. 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"
  330. #ifdef DEFECHO
  331. " DEFECHO=%s"
  332. #endif
  333. " FLUSHO=%s NOFLSH=%s TOSTOP=%s PENDIN=%s IEXTEN=%s",
  334. ISSETL(ISIG), ISSETL(ICANON), ISSETL(XCASE), ISSETL(ECHO),
  335. ISSETL(ECHOE), ISSETL(ECHOK), ISSETL(ECHONL), ISSETL(ECHOCTL),
  336. ISSETL(ECHOPRT), ISSETL(ECHOKE),
  337. #ifdef DEFECHO
  338. ISSETL(DEFECHO),
  339. #endif
  340. ISSETL(FLUSHO), ISSETL(NOFLSH), ISSETL(TOSTOP), ISSETL(PENDIN),
  341. ISSETL(IEXTEN));
  342. #define VALCC(b) (my_termios->c_cc[b])
  343. 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"
  344. #ifdef VSWTCH
  345. " VSWTCH=0x%02x"
  346. #endif
  347. " VSTART=0x%02x VSTOP=0x%02x VSUSP=0x%02x"
  348. #ifdef VDSUSP
  349. " VDSUSP=0x%02x"
  350. #endif
  351. " VLNEXT=0x%02x VWERASE=0x%02x VREPRINT=0x%02x VDISCARD=0x%02x"
  352. #ifdef VSTATUS
  353. " VSTATUS=0x%02x"
  354. #endif
  355. ,
  356. VALCC(VINTR), VALCC(VQUIT), VALCC(VERASE), VALCC(VKILL),
  357. VALCC(VEOF), VALCC(VMIN), VALCC(VEOL), VALCC(VTIME),
  358. VALCC(VEOL2),
  359. #ifdef VSWTCH
  360. VALCC(VSWTCH),
  361. #endif
  362. VALCC(VSTART), VALCC(VSTOP), VALCC(VSUSP),
  363. #ifdef VDSUSP
  364. VALCC(VDSUSP),
  365. #endif
  366. VALCC(VLNEXT), VALCC(VWERASE),
  367. VALCC(VREPRINT), VALCC(VDISCARD)
  368. #ifdef VSTATUS
  369. ,VALCC(VSTATUS)
  370. #endif
  371. );
  372. }
  373. #endif
  374. #endif
  375. /* NOTE: Linux only supports uint8_t (decisecond) timeouts; limiting it in
  376. * this interface buys us warnings when bad constants are passed in.
  377. */
  378. int
  379. serial_open(const char*devpath, unsigned long baud, uint8_t timeout, bool purge)
  380. {
  381. #ifdef WIN32
  382. HANDLE hSerial = CreateFile(devpath, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
  383. if (unlikely(hSerial == INVALID_HANDLE_VALUE))
  384. {
  385. DWORD e = GetLastError();
  386. switch (e) {
  387. case ERROR_ACCESS_DENIED:
  388. applog(LOG_ERR, "Do not have user privileges required to open %s", devpath);
  389. break;
  390. case ERROR_SHARING_VIOLATION:
  391. applog(LOG_ERR, "%s is already in use by another process", devpath);
  392. break;
  393. default:
  394. applog(LOG_DEBUG, "Open %s failed, GetLastError:%u", devpath, e);
  395. break;
  396. }
  397. return -1;
  398. }
  399. // thanks to af_newbie for pointers about this
  400. COMMCONFIG comCfg = {0};
  401. comCfg.dwSize = sizeof(COMMCONFIG);
  402. comCfg.wVersion = 1;
  403. comCfg.dcb.DCBlength = sizeof(DCB);
  404. comCfg.dcb.BaudRate = baud;
  405. comCfg.dcb.fBinary = 1;
  406. comCfg.dcb.fDtrControl = DTR_CONTROL_ENABLE;
  407. comCfg.dcb.fRtsControl = RTS_CONTROL_ENABLE;
  408. comCfg.dcb.ByteSize = 8;
  409. SetCommConfig(hSerial, &comCfg, sizeof(comCfg));
  410. // Code must specify a valid timeout value (0 means don't timeout)
  411. const DWORD ctoms = ((DWORD)timeout * 100);
  412. COMMTIMEOUTS cto = {ctoms, 0, ctoms, 0, ctoms};
  413. SetCommTimeouts(hSerial, &cto);
  414. if (purge) {
  415. PurgeComm(hSerial, PURGE_RXABORT);
  416. PurgeComm(hSerial, PURGE_TXABORT);
  417. PurgeComm(hSerial, PURGE_RXCLEAR);
  418. PurgeComm(hSerial, PURGE_TXCLEAR);
  419. }
  420. return _open_osfhandle((LONG)hSerial, 0);
  421. #else
  422. int fdDev = open(devpath, O_RDWR | O_CLOEXEC | O_NOCTTY);
  423. if (unlikely(fdDev == -1))
  424. {
  425. if (errno == EACCES)
  426. applog(LOG_ERR, "Do not have user privileges required to open %s", devpath);
  427. else
  428. applog(LOG_DEBUG, "Open %s failed, errno:%d", devpath, errno);
  429. return -1;
  430. }
  431. struct termios my_termios;
  432. tcgetattr(fdDev, &my_termios);
  433. #ifdef TERMIOS_DEBUG
  434. termios_debug(devpath, &my_termios, "before");
  435. #endif
  436. switch (baud) {
  437. case 0:
  438. break;
  439. case 57600:
  440. cfsetispeed(&my_termios, B57600);
  441. cfsetospeed(&my_termios, B57600);
  442. break;
  443. case 115200:
  444. cfsetispeed(&my_termios, B115200);
  445. cfsetospeed(&my_termios, B115200);
  446. break;
  447. // TODO: try some higher speeds with the Icarus and BFL to see
  448. // if they support them and if setting them makes any difference
  449. // N.B. B3000000 doesn't work on Icarus
  450. default:
  451. applog(LOG_WARNING, "Unrecognized baud rate: %lu", baud);
  452. }
  453. my_termios.c_cflag |= CS8;
  454. my_termios.c_cflag |= CREAD;
  455. my_termios.c_cflag |= CLOCAL;
  456. my_termios.c_cflag &= ~(CSIZE | PARENB);
  457. my_termios.c_iflag &= ~(IGNBRK | BRKINT | PARMRK |
  458. ISTRIP | INLCR | IGNCR | ICRNL | IXON);
  459. my_termios.c_oflag &= ~OPOST;
  460. my_termios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
  461. // Code must specify a valid timeout value (0 means don't timeout)
  462. my_termios.c_cc[VTIME] = (cc_t)timeout;
  463. my_termios.c_cc[VMIN] = 0;
  464. #ifdef TERMIOS_DEBUG
  465. termios_debug(devpath, &my_termios, "settings");
  466. #endif
  467. tcsetattr(fdDev, TCSANOW, &my_termios);
  468. #ifdef TERMIOS_DEBUG
  469. tcgetattr(fdDev, &my_termios);
  470. termios_debug(devpath, &my_termios, "after");
  471. #endif
  472. if (purge)
  473. tcflush(fdDev, TCIOFLUSH);
  474. return fdDev;
  475. #endif
  476. }
  477. ssize_t
  478. _serial_read(int fd, char *buf, size_t bufsiz, char *eol)
  479. {
  480. ssize_t len, tlen = 0;
  481. while (bufsiz) {
  482. len = read(fd, buf, eol ? 1 : bufsiz);
  483. if (len < 1)
  484. break;
  485. tlen += len;
  486. if (eol && *eol == buf[0])
  487. break;
  488. buf += len;
  489. bufsiz -= len;
  490. }
  491. return tlen;
  492. }
  493. static FILE*
  494. _open_bitstream(const char*path, const char*subdir, const char*filename)
  495. {
  496. char fullpath[PATH_MAX];
  497. strcpy(fullpath, path);
  498. strcat(fullpath, "/");
  499. if (subdir) {
  500. strcat(fullpath, subdir);
  501. strcat(fullpath, "/");
  502. }
  503. strcat(fullpath, filename);
  504. return fopen(fullpath, "rb");
  505. }
  506. #define _open_bitstream(path, subdir) do { \
  507. f = _open_bitstream(path, subdir, filename); \
  508. if (f) \
  509. return f; \
  510. } while(0)
  511. #define _open_bitstream3(path) do { \
  512. _open_bitstream(path, dname); \
  513. _open_bitstream(path, "bitstreams"); \
  514. _open_bitstream(path, NULL); \
  515. } while(0)
  516. FILE*
  517. open_bitstream(const char*dname, const char*filename)
  518. {
  519. FILE *f;
  520. _open_bitstream3(opt_kernel_path);
  521. _open_bitstream3(cgminer_path);
  522. _open_bitstream3(".");
  523. return NULL;
  524. }