fpgautils.c 21 KB

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