fpgautils.c 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109
  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. {
  751. speed_t speed = tiospeed_t(baud);
  752. if (speed == B0)
  753. applog(LOG_WARNING, "Unrecognized baud rate: %lu", baud);
  754. else
  755. {
  756. cfsetispeed(&my_termios, speed);
  757. cfsetospeed(&my_termios, speed);
  758. }
  759. }
  760. my_termios.c_cflag &= ~(CSIZE | PARENB);
  761. my_termios.c_cflag |= CS8;
  762. my_termios.c_cflag |= CREAD;
  763. #ifdef USE_AVALON
  764. // my_termios.c_cflag |= CRTSCTS;
  765. #endif
  766. my_termios.c_cflag |= CLOCAL;
  767. my_termios.c_iflag &= ~(IGNBRK | BRKINT | PARMRK |
  768. ISTRIP | INLCR | IGNCR | ICRNL | IXON);
  769. my_termios.c_oflag &= ~OPOST;
  770. my_termios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
  771. // Code must specify a valid timeout value (0 means don't timeout)
  772. my_termios.c_cc[VTIME] = (cc_t)timeout;
  773. my_termios.c_cc[VMIN] = 0;
  774. #ifdef TERMIOS_DEBUG
  775. termios_debug(devpath, &my_termios, "settings");
  776. #endif
  777. tcsetattr(fdDev, TCSANOW, &my_termios);
  778. #ifdef TERMIOS_DEBUG
  779. tcgetattr(fdDev, &my_termios);
  780. termios_debug(devpath, &my_termios, "after");
  781. #endif
  782. if (purge)
  783. tcflush(fdDev, TCIOFLUSH);
  784. return fdDev;
  785. #endif
  786. }
  787. ssize_t _serial_read(int fd, char *buf, size_t bufsiz, char *eol)
  788. {
  789. ssize_t len, tlen = 0;
  790. while (bufsiz) {
  791. len = read(fd, buf, eol ? 1 : bufsiz);
  792. if (len < 1)
  793. break;
  794. tlen += len;
  795. if (eol && *eol == buf[0])
  796. break;
  797. buf += len;
  798. bufsiz -= len;
  799. }
  800. return tlen;
  801. }
  802. static FILE *_open_bitstream(const char *path, const char *subdir, const char *sub2, const char *filename)
  803. {
  804. char fullpath[PATH_MAX];
  805. strcpy(fullpath, path);
  806. strcat(fullpath, "/");
  807. if (subdir) {
  808. strcat(fullpath, subdir);
  809. strcat(fullpath, "/");
  810. }
  811. if (sub2) {
  812. strcat(fullpath, sub2);
  813. strcat(fullpath, "/");
  814. }
  815. strcat(fullpath, filename);
  816. return fopen(fullpath, "rb");
  817. }
  818. #define _open_bitstream(path, subdir, sub2) do { \
  819. f = _open_bitstream(path, subdir, sub2, filename); \
  820. if (f) \
  821. return f; \
  822. } while(0)
  823. #define _open_bitstream2(path, path3) do { \
  824. _open_bitstream(path, NULL, path3); \
  825. _open_bitstream(path, "../share/" PACKAGE, path3); \
  826. } while(0)
  827. #define _open_bitstream3(path) do { \
  828. _open_bitstream2(path, dname); \
  829. _open_bitstream2(path, "bitstreams"); \
  830. _open_bitstream2(path, NULL); \
  831. } while(0)
  832. FILE *open_bitstream(const char *dname, const char *filename)
  833. {
  834. FILE *f;
  835. _open_bitstream3(opt_kernel_path);
  836. _open_bitstream3(cgminer_path);
  837. _open_bitstream3(".");
  838. return NULL;
  839. }
  840. #define bailout(...) do { \
  841. applog(__VA_ARGS__); \
  842. return NULL; \
  843. } while(0)
  844. #define check_magic(L) do { \
  845. if (1 != fread(buf, 1, 1, f)) \
  846. bailout(LOG_ERR, "%s: Error reading bitstream ('%c')", \
  847. repr, L); \
  848. if (buf[0] != L) \
  849. bailout(LOG_ERR, "%s: Firmware has wrong magic ('%c')", \
  850. repr, L); \
  851. } while(0)
  852. #define read_str(eng) do { \
  853. if (1 != fread(buf, 2, 1, f)) \
  854. bailout(LOG_ERR, "%s: Error reading bitstream (" eng " len)", \
  855. repr); \
  856. len = (ubuf[0] << 8) | ubuf[1]; \
  857. if (len >= sizeof(buf)) \
  858. bailout(LOG_ERR, "%s: Firmware " eng " too long", \
  859. repr); \
  860. if (1 != fread(buf, len, 1, f)) \
  861. bailout(LOG_ERR, "%s: Error reading bitstream (" eng ")", \
  862. repr); \
  863. buf[len] = '\0'; \
  864. } while(0)
  865. FILE *open_xilinx_bitstream(const char *dname, const char *repr, const char *fwfile, unsigned long *out_len)
  866. {
  867. char buf[0x100];
  868. unsigned char *ubuf = (unsigned char*)buf;
  869. unsigned long len;
  870. char *p;
  871. FILE *f = open_bitstream(dname, fwfile);
  872. if (!f)
  873. {
  874. applog(LOG_ERR, "%s: Error opening bitstream file %s",
  875. repr, fwfile);
  876. applog(LOG_ERR, "%s: Did you install the necessary bitstream package?",
  877. repr);
  878. return NULL;
  879. }
  880. if (1 != fread(buf, 2, 1, f))
  881. bailout(LOG_ERR, "%s: Error reading bitstream (magic)",
  882. repr);
  883. if (buf[0] || buf[1] != 9)
  884. bailout(LOG_ERR, "%s: Firmware has wrong magic (9)",
  885. repr);
  886. if (-1 == fseek(f, 11, SEEK_CUR))
  887. bailout(LOG_ERR, "%s: Firmware seek failed",
  888. repr);
  889. check_magic('a');
  890. read_str("design name");
  891. applog(LOG_DEBUG, "%s: Firmware file %s info:",
  892. repr, fwfile);
  893. applog(LOG_DEBUG, " Design name: %s", buf);
  894. p = strrchr(buf, ';') ?: buf;
  895. p = strrchr(buf, '=') ?: p;
  896. if (p[0] == '=')
  897. ++p;
  898. unsigned long fwusercode = (unsigned long)strtoll(p, &p, 16);
  899. if (p[0] != '\0')
  900. bailout(LOG_ERR, "%s: Bad usercode in bitstream file",
  901. repr);
  902. if (fwusercode == 0xffffffff)
  903. bailout(LOG_ERR, "%s: Firmware doesn't support user code",
  904. repr);
  905. applog(LOG_DEBUG, " Version: %u, build %u", (unsigned)((fwusercode >> 8) & 0xff), (unsigned)(fwusercode & 0xff));
  906. check_magic('b');
  907. read_str("part number");
  908. applog(LOG_DEBUG, " Part number: %s", buf);
  909. check_magic('c');
  910. read_str("build date");
  911. applog(LOG_DEBUG, " Build date: %s", buf);
  912. check_magic('d');
  913. read_str("build time");
  914. applog(LOG_DEBUG, " Build time: %s", buf);
  915. check_magic('e');
  916. if (1 != fread(buf, 4, 1, f))
  917. bailout(LOG_ERR, "%s: Error reading bitstream (data len)",
  918. repr);
  919. len = ((unsigned long)ubuf[0] << 24) | ((unsigned long)ubuf[1] << 16) | (ubuf[2] << 8) | ubuf[3];
  920. applog(LOG_DEBUG, " Bitstream size: %lu", len);
  921. *out_len = len;
  922. return f;
  923. }
  924. #ifndef WIN32
  925. int get_serial_cts(int fd)
  926. {
  927. int flags;
  928. if (!fd)
  929. return -1;
  930. ioctl(fd, TIOCMGET, &flags);
  931. return (flags & TIOCM_CTS) ? 1 : 0;
  932. }
  933. int set_serial_rts(int fd, int rts)
  934. {
  935. int flags;
  936. if (!fd)
  937. return -1;
  938. ioctl(fd, TIOCMGET, &flags);
  939. if (rts)
  940. flags |= TIOCM_RTS;
  941. else
  942. flags &= ~TIOCM_RTS;
  943. ioctl(fd, TIOCMSET, &flags);
  944. return flags & TIOCM_CTS;
  945. }
  946. #else
  947. int get_serial_cts(const int fd)
  948. {
  949. if (!fd)
  950. return -1;
  951. const HANDLE fh = (HANDLE)_get_osfhandle(fd);
  952. if (!fh)
  953. return -1;
  954. DWORD flags;
  955. if (!GetCommModemStatus(fh, &flags))
  956. return -1;
  957. return (flags & MS_CTS_ON) ? 1 : 0;
  958. }
  959. #endif // ! WIN32