fpgautils.c 26 KB

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