fpgautils.c 26 KB

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