fpgautils.c 21 KB

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