fpgautils.c 21 KB

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