fpgautils.c 26 KB

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