fpgautils.c 22 KB

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