fpgautils.c 24 KB

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