fpgautils.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  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 "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. ++found;
  207. }
  208. closedir(DT);
  209. }
  210. closedir(DS);
  211. }
  212. closedir(D);
  213. return found;
  214. }
  215. #else
  216. # define _serial_autodetect_sysfs(...) (0)
  217. #endif
  218. #ifdef WIN32
  219. #define LOAD_SYM(sym) do { \
  220. if (!(sym = dlsym(dll, #sym))) { \
  221. applog(LOG_DEBUG, "Failed to load " #sym ", not using FTDI autodetect"); \
  222. goto out; \
  223. } \
  224. } while(0)
  225. static
  226. int _serial_autodetect_ftdi(detectone_func_t detectone, va_list needles)
  227. {
  228. char devpath[] = "\\\\.\\COMnnnnn";
  229. char *devpathnum = &devpath[7];
  230. char **bufptrs;
  231. char *buf;
  232. int found = 0;
  233. DWORD i;
  234. FT_STATUS ftStatus;
  235. DWORD numDevs;
  236. HMODULE dll = LoadLibrary("FTD2XX.DLL");
  237. if (!dll) {
  238. applog(LOG_DEBUG, "FTD2XX.DLL failed to load, not using FTDI autodetect");
  239. return 0;
  240. }
  241. LOAD_SYM(FT_ListDevices);
  242. LOAD_SYM(FT_Open);
  243. LOAD_SYM(FT_GetComPortNumber);
  244. LOAD_SYM(FT_Close);
  245. ftStatus = FT_ListDevices(&numDevs, NULL, FT_LIST_NUMBER_ONLY);
  246. if (ftStatus != FT_OK) {
  247. applog(LOG_DEBUG, "FTDI device count failed, not using FTDI autodetect");
  248. goto out;
  249. }
  250. applog(LOG_DEBUG, "FTDI reports %u devices", (unsigned)numDevs);
  251. buf = alloca(65 * numDevs);
  252. bufptrs = alloca(sizeof(*bufptrs) * (numDevs + 1));
  253. for (i = 0; i < numDevs; ++i)
  254. bufptrs[i] = &buf[i * 65];
  255. bufptrs[numDevs] = NULL;
  256. ftStatus = FT_ListDevices(bufptrs, &numDevs, FT_LIST_ALL | FT_OPEN_BY_DESCRIPTION);
  257. if (ftStatus != FT_OK) {
  258. applog(LOG_DEBUG, "FTDI device list failed, not using FTDI autodetect");
  259. goto out;
  260. }
  261. for (i = numDevs; i > 0; ) {
  262. --i;
  263. bufptrs[i][64] = '\0';
  264. if (!SEARCH_NEEDLES(bufptrs[i]))
  265. continue;
  266. FT_HANDLE ftHandle;
  267. if (FT_OK != FT_Open(i, &ftHandle))
  268. continue;
  269. LONG lComPortNumber;
  270. ftStatus = FT_GetComPortNumber(ftHandle, &lComPortNumber);
  271. FT_Close(ftHandle);
  272. if (FT_OK != ftStatus || lComPortNumber < 0)
  273. continue;
  274. applog(LOG_ERR, "FT_GetComPortNumber(%p (%ld), %ld)", ftHandle, (long)i, (long)lComPortNumber);
  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. int _serial_detect(struct device_drv *api, detectone_func_t detectone, autoscan_func_t autoscan, int flags)
  301. {
  302. struct string_elist *iter, *tmp;
  303. const char *dev, *colon;
  304. bool inhibitauto = false;
  305. char found = 0;
  306. bool forceauto = flags & 1;
  307. bool hasname;
  308. size_t namel = strlen(api->name);
  309. size_t dnamel = strlen(api->dname);
  310. DL_FOREACH_SAFE(scan_devices, iter, tmp) {
  311. dev = iter->string;
  312. if ((colon = strchr(dev, ':')) && colon[1] != '\0') {
  313. size_t idlen = colon - dev;
  314. // allow either name:device or dname:device
  315. if ((idlen != namel || strncasecmp(dev, api->name, idlen))
  316. && (idlen != dnamel || strncasecmp(dev, api->dname, idlen)))
  317. continue;
  318. dev = colon + 1;
  319. hasname = true;
  320. }
  321. else
  322. hasname = false;
  323. if (!strcmp(dev, "auto"))
  324. forceauto = true;
  325. else if (!strcmp(dev, "noauto"))
  326. inhibitauto = true;
  327. else
  328. if ((flags & 2) && !hasname)
  329. continue;
  330. else
  331. if (!detectone)
  332. {} // do nothing
  333. else
  334. if (serial_claim(dev, NULL))
  335. {
  336. applog(LOG_DEBUG, "%s is already claimed... skipping probes", dev);
  337. string_elist_del(&scan_devices, iter);
  338. }
  339. else if (detectone(dev)) {
  340. string_elist_del(&scan_devices, iter);
  341. inhibitauto = true;
  342. ++found;
  343. }
  344. }
  345. if ((forceauto || !inhibitauto) && autoscan)
  346. found += autoscan();
  347. return found;
  348. }
  349. enum bfg_device_bus {
  350. BDB_SERIAL,
  351. BDB_USB,
  352. };
  353. // TODO: claim USB side of USB-Serial devices
  354. typedef
  355. struct my_dev_t {
  356. enum bfg_device_bus bus;
  357. union {
  358. struct {
  359. uint8_t usbbus;
  360. uint8_t usbaddr;
  361. };
  362. #ifndef WIN32
  363. dev_t dev;
  364. #else
  365. int com;
  366. #endif
  367. };
  368. } my_dev_t;
  369. struct _device_claim {
  370. struct device_drv *drv;
  371. my_dev_t dev;
  372. UT_hash_handle hh;
  373. };
  374. static
  375. struct device_drv *bfg_claim_any(struct device_drv * const api, const char * const verbose, const my_dev_t * const dev)
  376. {
  377. static struct _device_claim *claims = NULL;
  378. struct _device_claim *c;
  379. HASH_FIND(hh, claims, dev, sizeof(*dev), c);
  380. if (c)
  381. {
  382. if (verbose)
  383. applog(LOG_DEBUG, "%s device %s already claimed by other driver: %s",
  384. api->dname, verbose, c->drv->dname);
  385. return c->drv;
  386. }
  387. if (!api)
  388. return NULL;
  389. c = malloc(sizeof(*c));
  390. c->dev = *dev;
  391. c->drv = api;
  392. HASH_ADD(hh, claims, dev, sizeof(*dev), c);
  393. return NULL;
  394. }
  395. struct device_drv *bfg_claim_serial(struct device_drv * const api, const bool verbose, const char * const devpath)
  396. {
  397. my_dev_t dev;
  398. dev.bus = BDB_SERIAL;
  399. #ifndef WIN32
  400. {
  401. struct stat my_stat;
  402. if (stat(devpath, &my_stat))
  403. return NULL;
  404. dev.dev = my_stat.st_rdev;
  405. }
  406. #else
  407. {
  408. char *p = strstr(devpath, "COM"), *p2;
  409. if (!p)
  410. return NULL;
  411. dev.com = strtol(&p[3], &p2, 10);
  412. if (p2 == p)
  413. return NULL;
  414. }
  415. #endif
  416. return bfg_claim_any(api, (verbose ? devpath : NULL), &dev);
  417. }
  418. struct device_drv *bfg_claim_usb(struct device_drv * const api, const bool verbose, const uint8_t usbbus, const uint8_t usbaddr)
  419. {
  420. const my_dev_t dev = {
  421. .bus = BDB_USB,
  422. .usbbus = usbbus,
  423. .usbaddr = usbaddr,
  424. };
  425. char *desc = NULL;
  426. if (verbose)
  427. {
  428. desc = alloca(3 + 1 + 3 + 1);
  429. sprintf(desc, "%03u:%03u", (unsigned)usbbus, (unsigned)usbaddr);
  430. }
  431. return bfg_claim_any(api, desc, &dev);
  432. }
  433. // This code is purely for debugging but is very useful for that
  434. // It also took quite a bit of effort so I left it in
  435. // #define TERMIOS_DEBUG 1
  436. // Here to include it at compile time
  437. // It's off by default
  438. #ifndef WIN32
  439. #ifdef TERMIOS_DEBUG
  440. #define BITSSET "Y"
  441. #define BITSNOTSET "N"
  442. int tiospeed(speed_t speed)
  443. {
  444. switch (speed) {
  445. case B0:
  446. return 0;
  447. case B50:
  448. return 50;
  449. case B75:
  450. return 75;
  451. case B110:
  452. return 110;
  453. case B134:
  454. return 134;
  455. case B150:
  456. return 150;
  457. case B200:
  458. return 200;
  459. case B300:
  460. return 300;
  461. case B600:
  462. return 600;
  463. case B1200:
  464. return 1200;
  465. case B1800:
  466. return 1800;
  467. case B2400:
  468. return 2400;
  469. case B4800:
  470. return 4800;
  471. case B9600:
  472. return 9600;
  473. case B19200:
  474. return 19200;
  475. case B38400:
  476. return 38400;
  477. case B57600:
  478. return 57600;
  479. case B115200:
  480. return 115200;
  481. case B230400:
  482. return 230400;
  483. case B460800:
  484. return 460800;
  485. case B500000:
  486. return 500000;
  487. case B576000:
  488. return 576000;
  489. case B921600:
  490. return 921600;
  491. case B1000000:
  492. return 1000000;
  493. case B1152000:
  494. return 1152000;
  495. case B1500000:
  496. return 1500000;
  497. case B2000000:
  498. return 2000000;
  499. case B2500000:
  500. return 2500000;
  501. case B3000000:
  502. return 3000000;
  503. case B3500000:
  504. return 3500000;
  505. case B4000000:
  506. return 4000000;
  507. default:
  508. return -1;
  509. }
  510. }
  511. void termios_debug(const char *devpath, struct termios *my_termios, const char *msg)
  512. {
  513. applog(LOG_DEBUG, "TIOS: Open %s attributes %s: ispeed=%d ospeed=%d",
  514. devpath, msg, tiospeed(cfgetispeed(my_termios)), tiospeed(cfgetispeed(my_termios)));
  515. #define ISSETI(b) ((my_termios->c_iflag | (b)) ? BITSSET : BITSNOTSET)
  516. 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",
  517. ISSETI(IGNBRK), ISSETI(BRKINT), ISSETI(IGNPAR), ISSETI(PARMRK),
  518. ISSETI(INPCK), ISSETI(ISTRIP), ISSETI(INLCR), ISSETI(IGNCR),
  519. ISSETI(ICRNL), ISSETI(IUCLC), ISSETI(IXON), ISSETI(IXANY),
  520. ISSETI(IXOFF), ISSETI(IMAXBEL), ISSETI(IUTF8));
  521. #define ISSETO(b) ((my_termios->c_oflag | (b)) ? BITSSET : BITSNOTSET)
  522. #define VALO(b) (my_termios->c_oflag | (b))
  523. 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",
  524. ISSETO(OPOST), ISSETO(OLCUC), ISSETO(ONLCR), ISSETO(OCRNL),
  525. ISSETO(ONOCR), ISSETO(ONLRET), ISSETO(OFILL), ISSETO(OFDEL),
  526. VALO(NLDLY), VALO(CRDLY), VALO(TABDLY), VALO(BSDLY),
  527. VALO(VTDLY), VALO(FFDLY));
  528. #define ISSETC(b) ((my_termios->c_cflag | (b)) ? BITSSET : BITSNOTSET)
  529. #define VALC(b) (my_termios->c_cflag | (b))
  530. applog(LOG_DEBUG, "TIOS: c_cflag: CBAUDEX=%s CSIZE=%d CSTOPB=%s CREAD=%s PARENB=%s PARODD=%s HUPCL=%s CLOCAL=%s"
  531. #ifdef LOBLK
  532. " LOBLK=%s"
  533. #endif
  534. " CMSPAR=%s CRTSCTS=%s",
  535. ISSETC(CBAUDEX), VALC(CSIZE), ISSETC(CSTOPB), ISSETC(CREAD),
  536. ISSETC(PARENB), ISSETC(PARODD), ISSETC(HUPCL), ISSETC(CLOCAL),
  537. #ifdef LOBLK
  538. ISSETC(LOBLK),
  539. #endif
  540. ISSETC(CMSPAR), ISSETC(CRTSCTS));
  541. #define ISSETL(b) ((my_termios->c_lflag | (b)) ? BITSSET : BITSNOTSET)
  542. 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"
  543. #ifdef DEFECHO
  544. " DEFECHO=%s"
  545. #endif
  546. " FLUSHO=%s NOFLSH=%s TOSTOP=%s PENDIN=%s IEXTEN=%s",
  547. ISSETL(ISIG), ISSETL(ICANON), ISSETL(XCASE), ISSETL(ECHO),
  548. ISSETL(ECHOE), ISSETL(ECHOK), ISSETL(ECHONL), ISSETL(ECHOCTL),
  549. ISSETL(ECHOPRT), ISSETL(ECHOKE),
  550. #ifdef DEFECHO
  551. ISSETL(DEFECHO),
  552. #endif
  553. ISSETL(FLUSHO), ISSETL(NOFLSH), ISSETL(TOSTOP), ISSETL(PENDIN),
  554. ISSETL(IEXTEN));
  555. #define VALCC(b) (my_termios->c_cc[b])
  556. 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"
  557. #ifdef VSWTCH
  558. " VSWTCH=0x%02x"
  559. #endif
  560. " VSTART=0x%02x VSTOP=0x%02x VSUSP=0x%02x"
  561. #ifdef VDSUSP
  562. " VDSUSP=0x%02x"
  563. #endif
  564. " VLNEXT=0x%02x VWERASE=0x%02x VREPRINT=0x%02x VDISCARD=0x%02x"
  565. #ifdef VSTATUS
  566. " VSTATUS=0x%02x"
  567. #endif
  568. ,
  569. VALCC(VINTR), VALCC(VQUIT), VALCC(VERASE), VALCC(VKILL),
  570. VALCC(VEOF), VALCC(VMIN), VALCC(VEOL), VALCC(VTIME),
  571. VALCC(VEOL2),
  572. #ifdef VSWTCH
  573. VALCC(VSWTCH),
  574. #endif
  575. VALCC(VSTART), VALCC(VSTOP), VALCC(VSUSP),
  576. #ifdef VDSUSP
  577. VALCC(VDSUSP),
  578. #endif
  579. VALCC(VLNEXT), VALCC(VWERASE),
  580. VALCC(VREPRINT), VALCC(VDISCARD)
  581. #ifdef VSTATUS
  582. ,VALCC(VSTATUS)
  583. #endif
  584. );
  585. }
  586. #endif
  587. #endif
  588. /* NOTE: Linux only supports uint8_t (decisecond) timeouts; limiting it in
  589. * this interface buys us warnings when bad constants are passed in.
  590. */
  591. int serial_open(const char *devpath, unsigned long baud, uint8_t timeout, bool purge)
  592. {
  593. #ifdef WIN32
  594. HANDLE hSerial = CreateFile(devpath, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
  595. if (unlikely(hSerial == INVALID_HANDLE_VALUE))
  596. {
  597. DWORD e = GetLastError();
  598. switch (e) {
  599. case ERROR_ACCESS_DENIED:
  600. applog(LOG_ERR, "Do not have user privileges required to open %s", devpath);
  601. break;
  602. case ERROR_SHARING_VIOLATION:
  603. applog(LOG_ERR, "%s is already in use by another process", devpath);
  604. break;
  605. default:
  606. applog(LOG_DEBUG, "Open %s failed, GetLastError:%u", devpath, (unsigned)e);
  607. break;
  608. }
  609. return -1;
  610. }
  611. // thanks to af_newbie for pointers about this
  612. COMMCONFIG comCfg = {0};
  613. comCfg.dwSize = sizeof(COMMCONFIG);
  614. comCfg.wVersion = 1;
  615. comCfg.dcb.DCBlength = sizeof(DCB);
  616. comCfg.dcb.BaudRate = baud;
  617. comCfg.dcb.fBinary = 1;
  618. comCfg.dcb.fDtrControl = DTR_CONTROL_ENABLE;
  619. comCfg.dcb.fRtsControl = RTS_CONTROL_ENABLE;
  620. comCfg.dcb.ByteSize = 8;
  621. SetCommConfig(hSerial, &comCfg, sizeof(comCfg));
  622. // Code must specify a valid timeout value (0 means don't timeout)
  623. const DWORD ctoms = ((DWORD)timeout * 100);
  624. COMMTIMEOUTS cto = {ctoms, 0, ctoms, 0, ctoms};
  625. SetCommTimeouts(hSerial, &cto);
  626. if (purge) {
  627. PurgeComm(hSerial, PURGE_RXABORT);
  628. PurgeComm(hSerial, PURGE_TXABORT);
  629. PurgeComm(hSerial, PURGE_RXCLEAR);
  630. PurgeComm(hSerial, PURGE_TXCLEAR);
  631. }
  632. return _open_osfhandle((intptr_t)hSerial, 0);
  633. #else
  634. int fdDev = open(devpath, O_RDWR | O_CLOEXEC | O_NOCTTY);
  635. if (unlikely(fdDev == -1))
  636. {
  637. if (errno == EACCES)
  638. applog(LOG_ERR, "Do not have user privileges required to open %s", devpath);
  639. else
  640. applog(LOG_DEBUG, "Open %s failed: %s", devpath, bfg_strerror(errno, BST_ERRNO));
  641. return -1;
  642. }
  643. struct termios my_termios;
  644. tcgetattr(fdDev, &my_termios);
  645. #ifdef TERMIOS_DEBUG
  646. termios_debug(devpath, &my_termios, "before");
  647. #endif
  648. switch (baud) {
  649. case 0:
  650. break;
  651. case 19200:
  652. cfsetispeed(&my_termios, B19200);
  653. cfsetospeed(&my_termios, B19200);
  654. break;
  655. case 38400:
  656. cfsetispeed(&my_termios, B38400);
  657. cfsetospeed(&my_termios, B38400);
  658. break;
  659. case 57600:
  660. cfsetispeed(&my_termios, B57600);
  661. cfsetospeed(&my_termios, B57600);
  662. break;
  663. case 115200:
  664. cfsetispeed(&my_termios, B115200);
  665. cfsetospeed(&my_termios, B115200);
  666. break;
  667. // TODO: try some higher speeds with the Icarus and BFL to see
  668. // if they support them and if setting them makes any difference
  669. // N.B. B3000000 doesn't work on Icarus
  670. default:
  671. applog(LOG_WARNING, "Unrecognized baud rate: %lu", baud);
  672. }
  673. my_termios.c_cflag &= ~(CSIZE | PARENB);
  674. my_termios.c_cflag |= CS8;
  675. my_termios.c_cflag |= CREAD;
  676. #ifdef USE_AVALON
  677. // my_termios.c_cflag |= CRTSCTS;
  678. #endif
  679. my_termios.c_cflag |= CLOCAL;
  680. my_termios.c_iflag &= ~(IGNBRK | BRKINT | PARMRK |
  681. ISTRIP | INLCR | IGNCR | ICRNL | IXON);
  682. my_termios.c_oflag &= ~OPOST;
  683. my_termios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
  684. // Code must specify a valid timeout value (0 means don't timeout)
  685. my_termios.c_cc[VTIME] = (cc_t)timeout;
  686. my_termios.c_cc[VMIN] = 0;
  687. #ifdef TERMIOS_DEBUG
  688. termios_debug(devpath, &my_termios, "settings");
  689. #endif
  690. tcsetattr(fdDev, TCSANOW, &my_termios);
  691. #ifdef TERMIOS_DEBUG
  692. tcgetattr(fdDev, &my_termios);
  693. termios_debug(devpath, &my_termios, "after");
  694. #endif
  695. if (purge)
  696. tcflush(fdDev, TCIOFLUSH);
  697. return fdDev;
  698. #endif
  699. }
  700. ssize_t _serial_read(int fd, char *buf, size_t bufsiz, char *eol)
  701. {
  702. ssize_t len, tlen = 0;
  703. while (bufsiz) {
  704. len = read(fd, buf, eol ? 1 : bufsiz);
  705. if (len < 1)
  706. break;
  707. tlen += len;
  708. if (eol && *eol == buf[0])
  709. break;
  710. buf += len;
  711. bufsiz -= len;
  712. }
  713. return tlen;
  714. }
  715. static FILE *_open_bitstream(const char *path, const char *subdir, const char *sub2, const char *filename)
  716. {
  717. char fullpath[PATH_MAX];
  718. strcpy(fullpath, path);
  719. strcat(fullpath, "/");
  720. if (subdir) {
  721. strcat(fullpath, subdir);
  722. strcat(fullpath, "/");
  723. }
  724. if (sub2) {
  725. strcat(fullpath, sub2);
  726. strcat(fullpath, "/");
  727. }
  728. strcat(fullpath, filename);
  729. return fopen(fullpath, "rb");
  730. }
  731. #define _open_bitstream(path, subdir, sub2) do { \
  732. f = _open_bitstream(path, subdir, sub2, filename); \
  733. if (f) \
  734. return f; \
  735. } while(0)
  736. #define _open_bitstream2(path, path3) do { \
  737. _open_bitstream(path, NULL, path3); \
  738. _open_bitstream(path, "../share/" PACKAGE, path3); \
  739. } while(0)
  740. #define _open_bitstream3(path) do { \
  741. _open_bitstream2(path, dname); \
  742. _open_bitstream2(path, "bitstreams"); \
  743. _open_bitstream2(path, NULL); \
  744. } while(0)
  745. FILE *open_bitstream(const char *dname, const char *filename)
  746. {
  747. FILE *f;
  748. _open_bitstream3(opt_kernel_path);
  749. _open_bitstream3(cgminer_path);
  750. _open_bitstream3(".");
  751. return NULL;
  752. }
  753. #define bailout(...) do { \
  754. applog(__VA_ARGS__); \
  755. return NULL; \
  756. } while(0)
  757. #define check_magic(L) do { \
  758. if (1 != fread(buf, 1, 1, f)) \
  759. bailout(LOG_ERR, "%s: Error reading firmware ('%c')", \
  760. repr, L); \
  761. if (buf[0] != L) \
  762. bailout(LOG_ERR, "%s: Firmware has wrong magic ('%c')", \
  763. repr, L); \
  764. } while(0)
  765. #define read_str(eng) do { \
  766. if (1 != fread(buf, 2, 1, f)) \
  767. bailout(LOG_ERR, "%s: Error reading firmware (" eng " len)", \
  768. repr); \
  769. len = (ubuf[0] << 8) | ubuf[1]; \
  770. if (len >= sizeof(buf)) \
  771. bailout(LOG_ERR, "%s: Firmware " eng " too long", \
  772. repr); \
  773. if (1 != fread(buf, len, 1, f)) \
  774. bailout(LOG_ERR, "%s: Error reading firmware (" eng ")", \
  775. repr); \
  776. buf[len] = '\0'; \
  777. } while(0)
  778. FILE *open_xilinx_bitstream(const char *dname, const char *repr, const char *fwfile, unsigned long *out_len)
  779. {
  780. char buf[0x100];
  781. unsigned char *ubuf = (unsigned char*)buf;
  782. unsigned long len;
  783. char *p;
  784. FILE *f = open_bitstream(dname, fwfile);
  785. if (!f)
  786. bailout(LOG_ERR, "%s: Error opening firmware file %s",
  787. repr, fwfile);
  788. if (1 != fread(buf, 2, 1, f))
  789. bailout(LOG_ERR, "%s: Error reading firmware (magic)",
  790. repr);
  791. if (buf[0] || buf[1] != 9)
  792. bailout(LOG_ERR, "%s: Firmware has wrong magic (9)",
  793. repr);
  794. if (-1 == fseek(f, 11, SEEK_CUR))
  795. bailout(LOG_ERR, "%s: Firmware seek failed",
  796. repr);
  797. check_magic('a');
  798. read_str("design name");
  799. applog(LOG_DEBUG, "%s: Firmware file %s info:",
  800. repr, fwfile);
  801. applog(LOG_DEBUG, " Design name: %s", buf);
  802. p = strrchr(buf, ';') ?: buf;
  803. p = strrchr(buf, '=') ?: p;
  804. if (p[0] == '=')
  805. ++p;
  806. unsigned long fwusercode = (unsigned long)strtoll(p, &p, 16);
  807. if (p[0] != '\0')
  808. bailout(LOG_ERR, "%s: Bad usercode in firmware file",
  809. repr);
  810. if (fwusercode == 0xffffffff)
  811. bailout(LOG_ERR, "%s: Firmware doesn't support user code",
  812. repr);
  813. applog(LOG_DEBUG, " Version: %u, build %u", (unsigned)((fwusercode >> 8) & 0xff), (unsigned)(fwusercode & 0xff));
  814. check_magic('b');
  815. read_str("part number");
  816. applog(LOG_DEBUG, " Part number: %s", buf);
  817. check_magic('c');
  818. read_str("build date");
  819. applog(LOG_DEBUG, " Build date: %s", buf);
  820. check_magic('d');
  821. read_str("build time");
  822. applog(LOG_DEBUG, " Build time: %s", buf);
  823. check_magic('e');
  824. if (1 != fread(buf, 4, 1, f))
  825. bailout(LOG_ERR, "%s: Error reading firmware (data len)",
  826. repr);
  827. len = ((unsigned long)ubuf[0] << 24) | ((unsigned long)ubuf[1] << 16) | (ubuf[2] << 8) | ubuf[3];
  828. applog(LOG_DEBUG, " Bitstream size: %lu", len);
  829. *out_len = len;
  830. return f;
  831. }
  832. #ifndef WIN32
  833. int get_serial_cts(int fd)
  834. {
  835. int flags;
  836. if (!fd)
  837. return -1;
  838. ioctl(fd, TIOCMGET, &flags);
  839. return (flags & TIOCM_CTS) ? 1 : 0;
  840. }
  841. int set_serial_rts(int fd, int rts)
  842. {
  843. int flags;
  844. if (!fd)
  845. return -1;
  846. ioctl(fd, TIOCMGET, &flags);
  847. if (rts)
  848. flags |= TIOCM_RTS;
  849. else
  850. flags &= ~TIOCM_RTS;
  851. ioctl(fd, TIOCMSET, &flags);
  852. return flags & TIOCM_CTS;
  853. }
  854. #else
  855. int get_serial_cts(const int fd)
  856. {
  857. if (!fd)
  858. return -1;
  859. const HANDLE fh = (HANDLE)_get_osfhandle(fd);
  860. if (!fh)
  861. return -1;
  862. DWORD flags;
  863. if (!GetCommModemStatus(fh, &flags))
  864. return -1;
  865. return (flags & MS_CTS_ON) ? 1 : 0;
  866. }
  867. #endif // ! WIN32