fpgautils.c 22 KB

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