fpgautils.c 21 KB

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