fpgautils.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008
  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. dev.bus = BDB_SERIAL;
  411. #ifndef WIN32
  412. {
  413. struct stat my_stat;
  414. if (stat(devpath, &my_stat))
  415. return NULL;
  416. dev.dev = my_stat.st_rdev;
  417. }
  418. #else
  419. {
  420. char *p = strstr(devpath, "COM"), *p2;
  421. if (!p)
  422. return NULL;
  423. dev.com = strtol(&p[3], &p2, 10);
  424. if (p2 == p)
  425. return NULL;
  426. }
  427. #endif
  428. return bfg_claim_any(api, (verbose ? devpath : NULL), &dev);
  429. }
  430. struct device_drv *bfg_claim_usb(struct device_drv * const api, const bool verbose, const uint8_t usbbus, const uint8_t usbaddr)
  431. {
  432. my_dev_t dev;
  433. char *desc = NULL;
  434. // We should be able to just initialize a const my_dev_t for this, but Xcode's clang is broken
  435. // Affected: Apple LLVM version 4.2 (clang-425.0.28) (based on LLVM 3.2svn) AKA Xcode 4.6.3
  436. // Works with const: GCC 4.6.3, LLVM 3.1
  437. dev.bus = BDB_USB;
  438. dev.usbbus = usbbus;
  439. dev.usbaddr = usbaddr;
  440. if (verbose)
  441. {
  442. desc = alloca(3 + 1 + 3 + 1);
  443. sprintf(desc, "%03u:%03u", (unsigned)usbbus, (unsigned)usbaddr);
  444. }
  445. return bfg_claim_any(api, desc, &dev);
  446. }
  447. // This code is purely for debugging but is very useful for that
  448. // It also took quite a bit of effort so I left it in
  449. // #define TERMIOS_DEBUG 1
  450. // Here to include it at compile time
  451. // It's off by default
  452. #ifndef WIN32
  453. #ifdef TERMIOS_DEBUG
  454. #define BITSSET "Y"
  455. #define BITSNOTSET "N"
  456. int tiospeed(speed_t speed)
  457. {
  458. switch (speed) {
  459. case B0:
  460. return 0;
  461. case B50:
  462. return 50;
  463. case B75:
  464. return 75;
  465. case B110:
  466. return 110;
  467. case B134:
  468. return 134;
  469. case B150:
  470. return 150;
  471. case B200:
  472. return 200;
  473. case B300:
  474. return 300;
  475. case B600:
  476. return 600;
  477. case B1200:
  478. return 1200;
  479. case B1800:
  480. return 1800;
  481. case B2400:
  482. return 2400;
  483. case B4800:
  484. return 4800;
  485. case B9600:
  486. return 9600;
  487. case B19200:
  488. return 19200;
  489. case B38400:
  490. return 38400;
  491. case B57600:
  492. return 57600;
  493. case B115200:
  494. return 115200;
  495. case B230400:
  496. return 230400;
  497. case B460800:
  498. return 460800;
  499. case B500000:
  500. return 500000;
  501. case B576000:
  502. return 576000;
  503. case B921600:
  504. return 921600;
  505. case B1000000:
  506. return 1000000;
  507. case B1152000:
  508. return 1152000;
  509. case B1500000:
  510. return 1500000;
  511. case B2000000:
  512. return 2000000;
  513. case B2500000:
  514. return 2500000;
  515. case B3000000:
  516. return 3000000;
  517. case B3500000:
  518. return 3500000;
  519. case B4000000:
  520. return 4000000;
  521. default:
  522. return -1;
  523. }
  524. }
  525. void termios_debug(const char *devpath, struct termios *my_termios, const char *msg)
  526. {
  527. applog(LOG_DEBUG, "TIOS: Open %s attributes %s: ispeed=%d ospeed=%d",
  528. devpath, msg, tiospeed(cfgetispeed(my_termios)), tiospeed(cfgetispeed(my_termios)));
  529. #define ISSETI(b) ((my_termios->c_iflag | (b)) ? BITSSET : BITSNOTSET)
  530. 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",
  531. ISSETI(IGNBRK), ISSETI(BRKINT), ISSETI(IGNPAR), ISSETI(PARMRK),
  532. ISSETI(INPCK), ISSETI(ISTRIP), ISSETI(INLCR), ISSETI(IGNCR),
  533. ISSETI(ICRNL), ISSETI(IUCLC), ISSETI(IXON), ISSETI(IXANY),
  534. ISSETI(IXOFF), ISSETI(IMAXBEL), ISSETI(IUTF8));
  535. #define ISSETO(b) ((my_termios->c_oflag | (b)) ? BITSSET : BITSNOTSET)
  536. #define VALO(b) (my_termios->c_oflag | (b))
  537. 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",
  538. ISSETO(OPOST), ISSETO(OLCUC), ISSETO(ONLCR), ISSETO(OCRNL),
  539. ISSETO(ONOCR), ISSETO(ONLRET), ISSETO(OFILL), ISSETO(OFDEL),
  540. VALO(NLDLY), VALO(CRDLY), VALO(TABDLY), VALO(BSDLY),
  541. VALO(VTDLY), VALO(FFDLY));
  542. #define ISSETC(b) ((my_termios->c_cflag | (b)) ? BITSSET : BITSNOTSET)
  543. #define VALC(b) (my_termios->c_cflag | (b))
  544. applog(LOG_DEBUG, "TIOS: c_cflag: CBAUDEX=%s CSIZE=%d CSTOPB=%s CREAD=%s PARENB=%s PARODD=%s HUPCL=%s CLOCAL=%s"
  545. #ifdef LOBLK
  546. " LOBLK=%s"
  547. #endif
  548. " CMSPAR=%s CRTSCTS=%s",
  549. ISSETC(CBAUDEX), VALC(CSIZE), ISSETC(CSTOPB), ISSETC(CREAD),
  550. ISSETC(PARENB), ISSETC(PARODD), ISSETC(HUPCL), ISSETC(CLOCAL),
  551. #ifdef LOBLK
  552. ISSETC(LOBLK),
  553. #endif
  554. ISSETC(CMSPAR), ISSETC(CRTSCTS));
  555. #define ISSETL(b) ((my_termios->c_lflag | (b)) ? BITSSET : BITSNOTSET)
  556. 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"
  557. #ifdef DEFECHO
  558. " DEFECHO=%s"
  559. #endif
  560. " FLUSHO=%s NOFLSH=%s TOSTOP=%s PENDIN=%s IEXTEN=%s",
  561. ISSETL(ISIG), ISSETL(ICANON), ISSETL(XCASE), ISSETL(ECHO),
  562. ISSETL(ECHOE), ISSETL(ECHOK), ISSETL(ECHONL), ISSETL(ECHOCTL),
  563. ISSETL(ECHOPRT), ISSETL(ECHOKE),
  564. #ifdef DEFECHO
  565. ISSETL(DEFECHO),
  566. #endif
  567. ISSETL(FLUSHO), ISSETL(NOFLSH), ISSETL(TOSTOP), ISSETL(PENDIN),
  568. ISSETL(IEXTEN));
  569. #define VALCC(b) (my_termios->c_cc[b])
  570. 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"
  571. #ifdef VSWTCH
  572. " VSWTCH=0x%02x"
  573. #endif
  574. " VSTART=0x%02x VSTOP=0x%02x VSUSP=0x%02x"
  575. #ifdef VDSUSP
  576. " VDSUSP=0x%02x"
  577. #endif
  578. " VLNEXT=0x%02x VWERASE=0x%02x VREPRINT=0x%02x VDISCARD=0x%02x"
  579. #ifdef VSTATUS
  580. " VSTATUS=0x%02x"
  581. #endif
  582. ,
  583. VALCC(VINTR), VALCC(VQUIT), VALCC(VERASE), VALCC(VKILL),
  584. VALCC(VEOF), VALCC(VMIN), VALCC(VEOL), VALCC(VTIME),
  585. VALCC(VEOL2),
  586. #ifdef VSWTCH
  587. VALCC(VSWTCH),
  588. #endif
  589. VALCC(VSTART), VALCC(VSTOP), VALCC(VSUSP),
  590. #ifdef VDSUSP
  591. VALCC(VDSUSP),
  592. #endif
  593. VALCC(VLNEXT), VALCC(VWERASE),
  594. VALCC(VREPRINT), VALCC(VDISCARD)
  595. #ifdef VSTATUS
  596. ,VALCC(VSTATUS)
  597. #endif
  598. );
  599. }
  600. #endif
  601. #endif
  602. /* NOTE: Linux only supports uint8_t (decisecond) timeouts; limiting it in
  603. * this interface buys us warnings when bad constants are passed in.
  604. */
  605. int serial_open(const char *devpath, unsigned long baud, uint8_t timeout, bool purge)
  606. {
  607. #ifdef WIN32
  608. HANDLE hSerial = CreateFile(devpath, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
  609. if (unlikely(hSerial == INVALID_HANDLE_VALUE))
  610. {
  611. DWORD e = GetLastError();
  612. switch (e) {
  613. case ERROR_ACCESS_DENIED:
  614. applog(LOG_ERR, "Do not have user privileges required to open %s", devpath);
  615. break;
  616. case ERROR_SHARING_VIOLATION:
  617. applog(LOG_ERR, "%s is already in use by another process", devpath);
  618. break;
  619. default:
  620. applog(LOG_DEBUG, "Open %s failed, GetLastError:%u", devpath, (unsigned)e);
  621. break;
  622. }
  623. return -1;
  624. }
  625. // thanks to af_newbie for pointers about this
  626. COMMCONFIG comCfg = {0};
  627. comCfg.dwSize = sizeof(COMMCONFIG);
  628. comCfg.wVersion = 1;
  629. comCfg.dcb.DCBlength = sizeof(DCB);
  630. comCfg.dcb.BaudRate = baud;
  631. comCfg.dcb.fBinary = 1;
  632. comCfg.dcb.fDtrControl = DTR_CONTROL_ENABLE;
  633. comCfg.dcb.fRtsControl = RTS_CONTROL_ENABLE;
  634. comCfg.dcb.ByteSize = 8;
  635. SetCommConfig(hSerial, &comCfg, sizeof(comCfg));
  636. // Code must specify a valid timeout value (0 means don't timeout)
  637. const DWORD ctoms = ((DWORD)timeout * 100);
  638. COMMTIMEOUTS cto = {ctoms, 0, ctoms, 0, ctoms};
  639. SetCommTimeouts(hSerial, &cto);
  640. if (purge) {
  641. PurgeComm(hSerial, PURGE_RXABORT);
  642. PurgeComm(hSerial, PURGE_TXABORT);
  643. PurgeComm(hSerial, PURGE_RXCLEAR);
  644. PurgeComm(hSerial, PURGE_TXCLEAR);
  645. }
  646. return _open_osfhandle((intptr_t)hSerial, 0);
  647. #else
  648. int fdDev = open(devpath, O_RDWR | O_CLOEXEC | O_NOCTTY);
  649. if (unlikely(fdDev == -1))
  650. {
  651. if (errno == EACCES)
  652. applog(LOG_ERR, "Do not have user privileges required to open %s", devpath);
  653. else
  654. applog(LOG_DEBUG, "Open %s failed: %s", devpath, bfg_strerror(errno, BST_ERRNO));
  655. return -1;
  656. }
  657. struct termios my_termios;
  658. tcgetattr(fdDev, &my_termios);
  659. #ifdef TERMIOS_DEBUG
  660. termios_debug(devpath, &my_termios, "before");
  661. #endif
  662. switch (baud) {
  663. case 0:
  664. break;
  665. case 19200:
  666. cfsetispeed(&my_termios, B19200);
  667. cfsetospeed(&my_termios, B19200);
  668. break;
  669. case 38400:
  670. cfsetispeed(&my_termios, B38400);
  671. cfsetospeed(&my_termios, B38400);
  672. break;
  673. case 57600:
  674. cfsetispeed(&my_termios, B57600);
  675. cfsetospeed(&my_termios, B57600);
  676. break;
  677. case 115200:
  678. cfsetispeed(&my_termios, B115200);
  679. cfsetospeed(&my_termios, B115200);
  680. break;
  681. // TODO: try some higher speeds with the Icarus and BFL to see
  682. // if they support them and if setting them makes any difference
  683. // N.B. B3000000 doesn't work on Icarus
  684. default:
  685. applog(LOG_WARNING, "Unrecognized baud rate: %lu", baud);
  686. }
  687. my_termios.c_cflag &= ~(CSIZE | PARENB);
  688. my_termios.c_cflag |= CS8;
  689. my_termios.c_cflag |= CREAD;
  690. #ifdef USE_AVALON
  691. // my_termios.c_cflag |= CRTSCTS;
  692. #endif
  693. my_termios.c_cflag |= CLOCAL;
  694. my_termios.c_iflag &= ~(IGNBRK | BRKINT | PARMRK |
  695. ISTRIP | INLCR | IGNCR | ICRNL | IXON);
  696. my_termios.c_oflag &= ~OPOST;
  697. my_termios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
  698. // Code must specify a valid timeout value (0 means don't timeout)
  699. my_termios.c_cc[VTIME] = (cc_t)timeout;
  700. my_termios.c_cc[VMIN] = 0;
  701. #ifdef TERMIOS_DEBUG
  702. termios_debug(devpath, &my_termios, "settings");
  703. #endif
  704. tcsetattr(fdDev, TCSANOW, &my_termios);
  705. #ifdef TERMIOS_DEBUG
  706. tcgetattr(fdDev, &my_termios);
  707. termios_debug(devpath, &my_termios, "after");
  708. #endif
  709. if (purge)
  710. tcflush(fdDev, TCIOFLUSH);
  711. return fdDev;
  712. #endif
  713. }
  714. ssize_t _serial_read(int fd, char *buf, size_t bufsiz, char *eol)
  715. {
  716. ssize_t len, tlen = 0;
  717. while (bufsiz) {
  718. len = read(fd, buf, eol ? 1 : bufsiz);
  719. if (len < 1)
  720. break;
  721. tlen += len;
  722. if (eol && *eol == buf[0])
  723. break;
  724. buf += len;
  725. bufsiz -= len;
  726. }
  727. return tlen;
  728. }
  729. static FILE *_open_bitstream(const char *path, const char *subdir, const char *sub2, const char *filename)
  730. {
  731. char fullpath[PATH_MAX];
  732. strcpy(fullpath, path);
  733. strcat(fullpath, "/");
  734. if (subdir) {
  735. strcat(fullpath, subdir);
  736. strcat(fullpath, "/");
  737. }
  738. if (sub2) {
  739. strcat(fullpath, sub2);
  740. strcat(fullpath, "/");
  741. }
  742. strcat(fullpath, filename);
  743. return fopen(fullpath, "rb");
  744. }
  745. #define _open_bitstream(path, subdir, sub2) do { \
  746. f = _open_bitstream(path, subdir, sub2, filename); \
  747. if (f) \
  748. return f; \
  749. } while(0)
  750. #define _open_bitstream2(path, path3) do { \
  751. _open_bitstream(path, NULL, path3); \
  752. _open_bitstream(path, "../share/" PACKAGE, path3); \
  753. } while(0)
  754. #define _open_bitstream3(path) do { \
  755. _open_bitstream2(path, dname); \
  756. _open_bitstream2(path, "bitstreams"); \
  757. _open_bitstream2(path, NULL); \
  758. } while(0)
  759. FILE *open_bitstream(const char *dname, const char *filename)
  760. {
  761. FILE *f;
  762. _open_bitstream3(opt_kernel_path);
  763. _open_bitstream3(cgminer_path);
  764. _open_bitstream3(".");
  765. return NULL;
  766. }
  767. #define bailout(...) do { \
  768. applog(__VA_ARGS__); \
  769. return NULL; \
  770. } while(0)
  771. #define check_magic(L) do { \
  772. if (1 != fread(buf, 1, 1, f)) \
  773. bailout(LOG_ERR, "%s: Error reading firmware ('%c')", \
  774. repr, L); \
  775. if (buf[0] != L) \
  776. bailout(LOG_ERR, "%s: Firmware has wrong magic ('%c')", \
  777. repr, L); \
  778. } while(0)
  779. #define read_str(eng) do { \
  780. if (1 != fread(buf, 2, 1, f)) \
  781. bailout(LOG_ERR, "%s: Error reading firmware (" eng " len)", \
  782. repr); \
  783. len = (ubuf[0] << 8) | ubuf[1]; \
  784. if (len >= sizeof(buf)) \
  785. bailout(LOG_ERR, "%s: Firmware " eng " too long", \
  786. repr); \
  787. if (1 != fread(buf, len, 1, f)) \
  788. bailout(LOG_ERR, "%s: Error reading firmware (" eng ")", \
  789. repr); \
  790. buf[len] = '\0'; \
  791. } while(0)
  792. FILE *open_xilinx_bitstream(const char *dname, const char *repr, const char *fwfile, unsigned long *out_len)
  793. {
  794. char buf[0x100];
  795. unsigned char *ubuf = (unsigned char*)buf;
  796. unsigned long len;
  797. char *p;
  798. FILE *f = open_bitstream(dname, fwfile);
  799. if (!f)
  800. bailout(LOG_ERR, "%s: Error opening firmware file %s",
  801. repr, fwfile);
  802. if (1 != fread(buf, 2, 1, f))
  803. bailout(LOG_ERR, "%s: Error reading firmware (magic)",
  804. repr);
  805. if (buf[0] || buf[1] != 9)
  806. bailout(LOG_ERR, "%s: Firmware has wrong magic (9)",
  807. repr);
  808. if (-1 == fseek(f, 11, SEEK_CUR))
  809. bailout(LOG_ERR, "%s: Firmware seek failed",
  810. repr);
  811. check_magic('a');
  812. read_str("design name");
  813. applog(LOG_DEBUG, "%s: Firmware file %s info:",
  814. repr, fwfile);
  815. applog(LOG_DEBUG, " Design name: %s", buf);
  816. p = strrchr(buf, ';') ?: buf;
  817. p = strrchr(buf, '=') ?: p;
  818. if (p[0] == '=')
  819. ++p;
  820. unsigned long fwusercode = (unsigned long)strtoll(p, &p, 16);
  821. if (p[0] != '\0')
  822. bailout(LOG_ERR, "%s: Bad usercode in firmware file",
  823. repr);
  824. if (fwusercode == 0xffffffff)
  825. bailout(LOG_ERR, "%s: Firmware doesn't support user code",
  826. repr);
  827. applog(LOG_DEBUG, " Version: %u, build %u", (unsigned)((fwusercode >> 8) & 0xff), (unsigned)(fwusercode & 0xff));
  828. check_magic('b');
  829. read_str("part number");
  830. applog(LOG_DEBUG, " Part number: %s", buf);
  831. check_magic('c');
  832. read_str("build date");
  833. applog(LOG_DEBUG, " Build date: %s", buf);
  834. check_magic('d');
  835. read_str("build time");
  836. applog(LOG_DEBUG, " Build time: %s", buf);
  837. check_magic('e');
  838. if (1 != fread(buf, 4, 1, f))
  839. bailout(LOG_ERR, "%s: Error reading firmware (data len)",
  840. repr);
  841. len = ((unsigned long)ubuf[0] << 24) | ((unsigned long)ubuf[1] << 16) | (ubuf[2] << 8) | ubuf[3];
  842. applog(LOG_DEBUG, " Bitstream size: %lu", len);
  843. *out_len = len;
  844. return f;
  845. }
  846. #ifndef WIN32
  847. int get_serial_cts(int fd)
  848. {
  849. int flags;
  850. if (!fd)
  851. return -1;
  852. ioctl(fd, TIOCMGET, &flags);
  853. return (flags & TIOCM_CTS) ? 1 : 0;
  854. }
  855. int set_serial_rts(int fd, int rts)
  856. {
  857. int flags;
  858. if (!fd)
  859. return -1;
  860. ioctl(fd, TIOCMGET, &flags);
  861. if (rts)
  862. flags |= TIOCM_RTS;
  863. else
  864. flags &= ~TIOCM_RTS;
  865. ioctl(fd, TIOCMSET, &flags);
  866. return flags & TIOCM_CTS;
  867. }
  868. #else
  869. int get_serial_cts(const int fd)
  870. {
  871. if (!fd)
  872. return -1;
  873. const HANDLE fh = (HANDLE)_get_osfhandle(fd);
  874. if (!fh)
  875. return -1;
  876. DWORD flags;
  877. if (!GetCommModemStatus(fh, &flags))
  878. return -1;
  879. return (flags & MS_CTS_ON) ? 1 : 0;
  880. }
  881. #endif // ! WIN32