fpgautils.c 22 KB

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