fpgautils.c 22 KB

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