fpgautils.c 25 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  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));
  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. #define IOSPEED(baud) \
  557. case B ## baud: \
  558. return baud; \
  559. // END
  560. #include "iospeeds.h"
  561. #undef IOSPEED
  562. default:
  563. return -1;
  564. }
  565. }
  566. void termios_debug(const char *devpath, struct termios *my_termios, const char *msg)
  567. {
  568. applog(LOG_DEBUG, "TIOS: Open %s attributes %s: ispeed=%d ospeed=%d",
  569. devpath, msg, tiospeed(cfgetispeed(my_termios)), tiospeed(cfgetispeed(my_termios)));
  570. #define ISSETI(b) ((my_termios->c_iflag | (b)) ? BITSSET : BITSNOTSET)
  571. 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",
  572. ISSETI(IGNBRK), ISSETI(BRKINT), ISSETI(IGNPAR), ISSETI(PARMRK),
  573. ISSETI(INPCK), ISSETI(ISTRIP), ISSETI(INLCR), ISSETI(IGNCR),
  574. ISSETI(ICRNL), ISSETI(IUCLC), ISSETI(IXON), ISSETI(IXANY),
  575. ISSETI(IXOFF), ISSETI(IMAXBEL), ISSETI(IUTF8));
  576. #define ISSETO(b) ((my_termios->c_oflag | (b)) ? BITSSET : BITSNOTSET)
  577. #define VALO(b) (my_termios->c_oflag | (b))
  578. 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",
  579. ISSETO(OPOST), ISSETO(OLCUC), ISSETO(ONLCR), ISSETO(OCRNL),
  580. ISSETO(ONOCR), ISSETO(ONLRET), ISSETO(OFILL), ISSETO(OFDEL),
  581. VALO(NLDLY), VALO(CRDLY), VALO(TABDLY), VALO(BSDLY),
  582. VALO(VTDLY), VALO(FFDLY));
  583. #define ISSETC(b) ((my_termios->c_cflag | (b)) ? BITSSET : BITSNOTSET)
  584. #define VALC(b) (my_termios->c_cflag | (b))
  585. applog(LOG_DEBUG, "TIOS: c_cflag: CBAUDEX=%s CSIZE=%d CSTOPB=%s CREAD=%s PARENB=%s PARODD=%s HUPCL=%s CLOCAL=%s"
  586. #ifdef LOBLK
  587. " LOBLK=%s"
  588. #endif
  589. " CMSPAR=%s CRTSCTS=%s",
  590. ISSETC(CBAUDEX), VALC(CSIZE), ISSETC(CSTOPB), ISSETC(CREAD),
  591. ISSETC(PARENB), ISSETC(PARODD), ISSETC(HUPCL), ISSETC(CLOCAL),
  592. #ifdef LOBLK
  593. ISSETC(LOBLK),
  594. #endif
  595. ISSETC(CMSPAR), ISSETC(CRTSCTS));
  596. #define ISSETL(b) ((my_termios->c_lflag | (b)) ? BITSSET : BITSNOTSET)
  597. 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"
  598. #ifdef DEFECHO
  599. " DEFECHO=%s"
  600. #endif
  601. " FLUSHO=%s NOFLSH=%s TOSTOP=%s PENDIN=%s IEXTEN=%s",
  602. ISSETL(ISIG), ISSETL(ICANON), ISSETL(XCASE), ISSETL(ECHO),
  603. ISSETL(ECHOE), ISSETL(ECHOK), ISSETL(ECHONL), ISSETL(ECHOCTL),
  604. ISSETL(ECHOPRT), ISSETL(ECHOKE),
  605. #ifdef DEFECHO
  606. ISSETL(DEFECHO),
  607. #endif
  608. ISSETL(FLUSHO), ISSETL(NOFLSH), ISSETL(TOSTOP), ISSETL(PENDIN),
  609. ISSETL(IEXTEN));
  610. #define VALCC(b) (my_termios->c_cc[b])
  611. 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"
  612. #ifdef VSWTCH
  613. " VSWTCH=0x%02x"
  614. #endif
  615. " VSTART=0x%02x VSTOP=0x%02x VSUSP=0x%02x"
  616. #ifdef VDSUSP
  617. " VDSUSP=0x%02x"
  618. #endif
  619. " VLNEXT=0x%02x VWERASE=0x%02x VREPRINT=0x%02x VDISCARD=0x%02x"
  620. #ifdef VSTATUS
  621. " VSTATUS=0x%02x"
  622. #endif
  623. ,
  624. VALCC(VINTR), VALCC(VQUIT), VALCC(VERASE), VALCC(VKILL),
  625. VALCC(VEOF), VALCC(VMIN), VALCC(VEOL), VALCC(VTIME),
  626. VALCC(VEOL2),
  627. #ifdef VSWTCH
  628. VALCC(VSWTCH),
  629. #endif
  630. VALCC(VSTART), VALCC(VSTOP), VALCC(VSUSP),
  631. #ifdef VDSUSP
  632. VALCC(VDSUSP),
  633. #endif
  634. VALCC(VLNEXT), VALCC(VWERASE),
  635. VALCC(VREPRINT), VALCC(VDISCARD)
  636. #ifdef VSTATUS
  637. ,VALCC(VSTATUS)
  638. #endif
  639. );
  640. }
  641. #endif /* TERMIOS_DEBUG */
  642. speed_t tiospeed_t(int baud)
  643. {
  644. switch (baud) {
  645. #define IOSPEED(baud) \
  646. case baud: \
  647. return B ## baud; \
  648. // END
  649. #include "iospeeds.h"
  650. #undef IOSPEED
  651. default:
  652. return B0;
  653. }
  654. }
  655. #endif /* WIN32 */
  656. bool valid_baud(int baud)
  657. {
  658. switch (baud) {
  659. #define IOSPEED(baud) \
  660. case baud: \
  661. return true; \
  662. // END
  663. #include "iospeeds.h"
  664. #undef IOSPEED
  665. default:
  666. return false;
  667. }
  668. }
  669. /* NOTE: Linux only supports uint8_t (decisecond) timeouts; limiting it in
  670. * this interface buys us warnings when bad constants are passed in.
  671. */
  672. int serial_open(const char *devpath, unsigned long baud, uint8_t timeout, bool purge)
  673. {
  674. #ifdef WIN32
  675. HANDLE hSerial = CreateFile(devpath, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
  676. if (unlikely(hSerial == INVALID_HANDLE_VALUE))
  677. {
  678. DWORD e = GetLastError();
  679. switch (e) {
  680. case ERROR_ACCESS_DENIED:
  681. applog(LOG_ERR, "Do not have user privileges required to open %s", devpath);
  682. break;
  683. case ERROR_SHARING_VIOLATION:
  684. applog(LOG_ERR, "%s is already in use by another process", devpath);
  685. break;
  686. default:
  687. applog(LOG_DEBUG, "Open %s failed, GetLastError:%u", devpath, (unsigned)e);
  688. break;
  689. }
  690. return -1;
  691. }
  692. // thanks to af_newbie for pointers about this
  693. COMMCONFIG comCfg = {0};
  694. comCfg.dwSize = sizeof(COMMCONFIG);
  695. comCfg.wVersion = 1;
  696. comCfg.dcb.DCBlength = sizeof(DCB);
  697. comCfg.dcb.BaudRate = baud;
  698. comCfg.dcb.fBinary = 1;
  699. comCfg.dcb.fDtrControl = DTR_CONTROL_ENABLE;
  700. comCfg.dcb.fRtsControl = RTS_CONTROL_ENABLE;
  701. comCfg.dcb.ByteSize = 8;
  702. SetCommConfig(hSerial, &comCfg, sizeof(comCfg));
  703. // Code must specify a valid timeout value (0 means don't timeout)
  704. const DWORD ctoms = ((DWORD)timeout * 100);
  705. COMMTIMEOUTS cto = {ctoms, 0, ctoms, 0, ctoms};
  706. SetCommTimeouts(hSerial, &cto);
  707. if (purge) {
  708. PurgeComm(hSerial, PURGE_RXABORT);
  709. PurgeComm(hSerial, PURGE_TXABORT);
  710. PurgeComm(hSerial, PURGE_RXCLEAR);
  711. PurgeComm(hSerial, PURGE_TXCLEAR);
  712. }
  713. return _open_osfhandle((intptr_t)hSerial, 0);
  714. #else
  715. int fdDev = open(devpath, O_RDWR | O_CLOEXEC | O_NOCTTY);
  716. if (unlikely(fdDev == -1))
  717. {
  718. if (errno == EACCES)
  719. applog(LOG_ERR, "Do not have user privileges required to open %s", devpath);
  720. else
  721. applog(LOG_DEBUG, "Open %s failed: %s", devpath, bfg_strerror(errno, BST_ERRNO));
  722. return -1;
  723. }
  724. struct termios my_termios;
  725. tcgetattr(fdDev, &my_termios);
  726. #ifdef TERMIOS_DEBUG
  727. termios_debug(devpath, &my_termios, "before");
  728. #endif
  729. {
  730. speed_t speed = tiospeed_t(baud);
  731. if (speed == B0)
  732. applog(LOG_WARNING, "Unrecognized baud rate: %lu", baud);
  733. else
  734. {
  735. cfsetispeed(&my_termios, speed);
  736. cfsetospeed(&my_termios, speed);
  737. }
  738. }
  739. my_termios.c_cflag &= ~(CSIZE | PARENB);
  740. my_termios.c_cflag |= CS8;
  741. my_termios.c_cflag |= CREAD;
  742. #ifdef USE_AVALON
  743. // my_termios.c_cflag |= CRTSCTS;
  744. #endif
  745. my_termios.c_cflag |= CLOCAL;
  746. my_termios.c_iflag &= ~(IGNBRK | BRKINT | PARMRK |
  747. ISTRIP | INLCR | IGNCR | ICRNL | IXON);
  748. my_termios.c_oflag &= ~OPOST;
  749. my_termios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
  750. // Code must specify a valid timeout value (0 means don't timeout)
  751. my_termios.c_cc[VTIME] = (cc_t)timeout;
  752. my_termios.c_cc[VMIN] = 0;
  753. #ifdef TERMIOS_DEBUG
  754. termios_debug(devpath, &my_termios, "settings");
  755. #endif
  756. tcsetattr(fdDev, TCSANOW, &my_termios);
  757. #ifdef TERMIOS_DEBUG
  758. tcgetattr(fdDev, &my_termios);
  759. termios_debug(devpath, &my_termios, "after");
  760. #endif
  761. if (purge)
  762. tcflush(fdDev, TCIOFLUSH);
  763. return fdDev;
  764. #endif
  765. }
  766. ssize_t _serial_read(int fd, char *buf, size_t bufsiz, char *eol)
  767. {
  768. ssize_t len, tlen = 0;
  769. while (bufsiz) {
  770. len = read(fd, buf, eol ? 1 : bufsiz);
  771. if (len < 1)
  772. break;
  773. tlen += len;
  774. if (eol && *eol == buf[0])
  775. break;
  776. buf += len;
  777. bufsiz -= len;
  778. }
  779. return tlen;
  780. }
  781. static FILE *_open_bitstream(const char *path, const char *subdir, const char *sub2, const char *filename)
  782. {
  783. char fullpath[PATH_MAX];
  784. strcpy(fullpath, path);
  785. strcat(fullpath, "/");
  786. if (subdir) {
  787. strcat(fullpath, subdir);
  788. strcat(fullpath, "/");
  789. }
  790. if (sub2) {
  791. strcat(fullpath, sub2);
  792. strcat(fullpath, "/");
  793. }
  794. strcat(fullpath, filename);
  795. return fopen(fullpath, "rb");
  796. }
  797. #define _open_bitstream(path, subdir, sub2) do { \
  798. f = _open_bitstream(path, subdir, sub2, filename); \
  799. if (f) \
  800. return f; \
  801. } while(0)
  802. #define _open_bitstream2(path, path3) do { \
  803. _open_bitstream(path, NULL, path3); \
  804. _open_bitstream(path, "../share/" PACKAGE, path3); \
  805. } while(0)
  806. #define _open_bitstream3(path) do { \
  807. _open_bitstream2(path, dname); \
  808. _open_bitstream2(path, "bitstreams"); \
  809. _open_bitstream2(path, NULL); \
  810. } while(0)
  811. FILE *open_bitstream(const char *dname, const char *filename)
  812. {
  813. FILE *f;
  814. _open_bitstream3(opt_kernel_path);
  815. _open_bitstream3(cgminer_path);
  816. _open_bitstream3(".");
  817. return NULL;
  818. }
  819. #define bailout(...) do { \
  820. applog(__VA_ARGS__); \
  821. return NULL; \
  822. } while(0)
  823. #define check_magic(L) do { \
  824. if (1 != fread(buf, 1, 1, f)) \
  825. bailout(LOG_ERR, "%s: Error reading bitstream ('%c')", \
  826. repr, L); \
  827. if (buf[0] != L) \
  828. bailout(LOG_ERR, "%s: Firmware has wrong magic ('%c')", \
  829. repr, L); \
  830. } while(0)
  831. #define read_str(eng) do { \
  832. if (1 != fread(buf, 2, 1, f)) \
  833. bailout(LOG_ERR, "%s: Error reading bitstream (" eng " len)", \
  834. repr); \
  835. len = (ubuf[0] << 8) | ubuf[1]; \
  836. if (len >= sizeof(buf)) \
  837. bailout(LOG_ERR, "%s: Firmware " eng " too long", \
  838. repr); \
  839. if (1 != fread(buf, len, 1, f)) \
  840. bailout(LOG_ERR, "%s: Error reading bitstream (" eng ")", \
  841. repr); \
  842. buf[len] = '\0'; \
  843. } while(0)
  844. FILE *open_xilinx_bitstream(const char *dname, const char *repr, const char *fwfile, unsigned long *out_len)
  845. {
  846. char buf[0x100];
  847. unsigned char *ubuf = (unsigned char*)buf;
  848. unsigned long len;
  849. char *p;
  850. FILE *f = open_bitstream(dname, fwfile);
  851. if (!f)
  852. {
  853. applog(LOG_ERR, "%s: Error opening bitstream file %s",
  854. repr, fwfile);
  855. applog(LOG_ERR, "%s: Did you install the necessary bitstream package?",
  856. repr);
  857. return NULL;
  858. }
  859. if (1 != fread(buf, 2, 1, f))
  860. bailout(LOG_ERR, "%s: Error reading bitstream (magic)",
  861. repr);
  862. if (buf[0] || buf[1] != 9)
  863. bailout(LOG_ERR, "%s: Firmware has wrong magic (9)",
  864. repr);
  865. if (-1 == fseek(f, 11, SEEK_CUR))
  866. bailout(LOG_ERR, "%s: Firmware seek failed",
  867. repr);
  868. check_magic('a');
  869. read_str("design name");
  870. applog(LOG_DEBUG, "%s: Firmware file %s info:",
  871. repr, fwfile);
  872. applog(LOG_DEBUG, " Design name: %s", buf);
  873. p = strrchr(buf, ';') ?: buf;
  874. p = strrchr(buf, '=') ?: p;
  875. if (p[0] == '=')
  876. ++p;
  877. unsigned long fwusercode = (unsigned long)strtoll(p, &p, 16);
  878. if (p[0] != '\0')
  879. bailout(LOG_ERR, "%s: Bad usercode in bitstream file",
  880. repr);
  881. if (fwusercode == 0xffffffff)
  882. bailout(LOG_ERR, "%s: Firmware doesn't support user code",
  883. repr);
  884. applog(LOG_DEBUG, " Version: %u, build %u", (unsigned)((fwusercode >> 8) & 0xff), (unsigned)(fwusercode & 0xff));
  885. check_magic('b');
  886. read_str("part number");
  887. applog(LOG_DEBUG, " Part number: %s", buf);
  888. check_magic('c');
  889. read_str("build date");
  890. applog(LOG_DEBUG, " Build date: %s", buf);
  891. check_magic('d');
  892. read_str("build time");
  893. applog(LOG_DEBUG, " Build time: %s", buf);
  894. check_magic('e');
  895. if (1 != fread(buf, 4, 1, f))
  896. bailout(LOG_ERR, "%s: Error reading bitstream (data len)",
  897. repr);
  898. len = ((unsigned long)ubuf[0] << 24) | ((unsigned long)ubuf[1] << 16) | (ubuf[2] << 8) | ubuf[3];
  899. applog(LOG_DEBUG, " Bitstream size: %lu", len);
  900. *out_len = len;
  901. return f;
  902. }
  903. #ifndef WIN32
  904. int get_serial_cts(int fd)
  905. {
  906. int flags;
  907. if (!fd)
  908. return -1;
  909. ioctl(fd, TIOCMGET, &flags);
  910. return (flags & TIOCM_CTS) ? 1 : 0;
  911. }
  912. int set_serial_rts(int fd, int rts)
  913. {
  914. int flags;
  915. if (!fd)
  916. return -1;
  917. ioctl(fd, TIOCMGET, &flags);
  918. if (rts)
  919. flags |= TIOCM_RTS;
  920. else
  921. flags &= ~TIOCM_RTS;
  922. ioctl(fd, TIOCMSET, &flags);
  923. return flags & TIOCM_CTS;
  924. }
  925. #else
  926. int get_serial_cts(const int fd)
  927. {
  928. if (!fd)
  929. return -1;
  930. const HANDLE fh = (HANDLE)_get_osfhandle(fd);
  931. if (!fh)
  932. return -1;
  933. DWORD flags;
  934. if (!GetCommModemStatus(fh, &flags))
  935. return -1;
  936. return (flags & MS_CTS_ON) ? 1 : 0;
  937. }
  938. #endif // ! WIN32