fpgautils.c 22 KB

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