fpgautils.c 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397
  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_SYS_FILE_H
  24. #include <sys/file.h>
  25. #endif
  26. #ifdef HAVE_LIBUSB
  27. #include <libusb.h>
  28. #endif
  29. #include "miner.h"
  30. #ifndef WIN32
  31. #include <errno.h>
  32. #include <termios.h>
  33. #include <sys/ioctl.h>
  34. #include <sys/stat.h>
  35. #include <unistd.h>
  36. #include <fcntl.h>
  37. #ifndef O_CLOEXEC
  38. #define O_CLOEXEC 0
  39. #endif
  40. #else /* WIN32 */
  41. #include <windows.h>
  42. #ifdef HAVE_WIN_DDKUSB
  43. #include <setupapi.h>
  44. #include <usbioctl.h>
  45. #include <usbiodef.h>
  46. #endif
  47. #include <io.h>
  48. #include <utlist.h>
  49. #define dlsym (void*)GetProcAddress
  50. #define dlclose FreeLibrary
  51. typedef unsigned long FT_STATUS;
  52. typedef PVOID FT_HANDLE;
  53. __stdcall FT_STATUS (*FT_ListDevices)(PVOID pArg1, PVOID pArg2, DWORD Flags);
  54. __stdcall FT_STATUS (*FT_Open)(int idx, FT_HANDLE*);
  55. __stdcall FT_STATUS (*FT_GetComPortNumber)(FT_HANDLE, LPLONG lplComPortNumber);
  56. __stdcall FT_STATUS (*FT_Close)(FT_HANDLE);
  57. const uint32_t FT_OPEN_BY_SERIAL_NUMBER = 1;
  58. const uint32_t FT_OPEN_BY_DESCRIPTION = 2;
  59. const uint32_t FT_LIST_ALL = 0x20000000;
  60. const uint32_t FT_LIST_BY_INDEX = 0x40000000;
  61. const uint32_t FT_LIST_NUMBER_ONLY = 0x80000000;
  62. enum {
  63. FT_OK,
  64. };
  65. #endif /* WIN32 */
  66. #ifdef HAVE_LIBUDEV
  67. #include <libudev.h>
  68. #include <sys/ioctl.h>
  69. #endif
  70. #include "logging.h"
  71. #include "miner.h"
  72. #include "util.h"
  73. #include "fpgautils.h"
  74. #define SEARCH_NEEDLES_BEGIN() { \
  75. const char *needle; \
  76. bool __cont = false; \
  77. va_list ap; \
  78. va_copy(ap, needles); \
  79. while ( (needle = va_arg(ap, const char *)) ) \
  80. {
  81. #define SEARCH_NEEDLES_END(...) \
  82. } \
  83. va_end(ap); \
  84. if (__cont) \
  85. { \
  86. __VA_ARGS__; \
  87. } \
  88. }
  89. static inline
  90. bool search_needles(const char *haystack, va_list needles)
  91. {
  92. bool rv = true;
  93. SEARCH_NEEDLES_BEGIN()
  94. if (!strstr(haystack, needle))
  95. {
  96. rv = false;
  97. break;
  98. }
  99. SEARCH_NEEDLES_END()
  100. return rv;
  101. }
  102. #define SEARCH_NEEDLES(haystack) search_needles(haystack, needles)
  103. static
  104. int _detectone_wrap(const detectone_func_t detectone, const char * const param, const char *fname)
  105. {
  106. if (bfg_claim_serial(NULL, true, param))
  107. {
  108. applog(LOG_DEBUG, "%s: %s is already claimed, skipping probe", fname, param);
  109. return 0;
  110. }
  111. return detectone(param);
  112. }
  113. #define detectone(param) _detectone_wrap(detectone, param, __func__)
  114. struct detectone_meta_info_t detectone_meta_info;
  115. void clear_detectone_meta_info(void)
  116. {
  117. detectone_meta_info = (struct detectone_meta_info_t){
  118. .manufacturer = NULL,
  119. };
  120. }
  121. #ifdef HAVE_LIBUDEV
  122. static
  123. void _decode_udev_enc(char *o, const char *s)
  124. {
  125. while(s[0])
  126. {
  127. if (s[0] == '\\' && s[1] == 'x' && s[2] && s[3])
  128. {
  129. hex2bin((void*)(o++), &s[2], 1);
  130. s += 4;
  131. }
  132. else
  133. (o++)[0] = (s++)[0];
  134. }
  135. o[0] = '\0';
  136. }
  137. static
  138. char *_decode_udev_enc_dup(const char *s)
  139. {
  140. if (!s)
  141. return NULL;
  142. char *o = malloc(strlen(s) + 1);
  143. if (!o)
  144. {
  145. applog(LOG_ERR, "Failed to malloc in _decode_udev_enc_dup");
  146. return NULL;
  147. }
  148. _decode_udev_enc(o, s);
  149. return o;
  150. }
  151. static
  152. int _serial_autodetect_udev(detectone_func_t detectone, va_list needles)
  153. {
  154. struct udev *udev = udev_new();
  155. struct udev_enumerate *enumerate = udev_enumerate_new(udev);
  156. struct udev_list_entry *list_entry;
  157. char found = 0;
  158. udev_enumerate_add_match_subsystem(enumerate, "tty");
  159. udev_enumerate_scan_devices(enumerate);
  160. udev_list_entry_foreach(list_entry, udev_enumerate_get_list_entry(enumerate)) {
  161. struct udev_device *device = udev_device_new_from_syspath(
  162. udev_enumerate_get_udev(enumerate),
  163. udev_list_entry_get_name(list_entry)
  164. );
  165. if (!device)
  166. continue;
  167. const char *model = udev_device_get_property_value(device, "ID_MODEL");
  168. if (!(model && SEARCH_NEEDLES(model)))
  169. {
  170. udev_device_unref(device);
  171. continue;
  172. }
  173. detectone_meta_info = (struct detectone_meta_info_t){
  174. .manufacturer = _decode_udev_enc_dup(udev_device_get_property_value(device, "ID_VENDOR_ENC")),
  175. .product = _decode_udev_enc_dup(udev_device_get_property_value(device, "ID_MODEL_ENC")),
  176. .serial = _decode_udev_enc_dup(udev_device_get_property_value(device, "ID_SERIAL_SHORT")),
  177. };
  178. const char *devpath = udev_device_get_devnode(device);
  179. if (devpath && detectone(devpath))
  180. ++found;
  181. free((void*)detectone_meta_info.manufacturer);
  182. free((void*)detectone_meta_info.product);
  183. free((void*)detectone_meta_info.serial);
  184. udev_device_unref(device);
  185. }
  186. udev_enumerate_unref(enumerate);
  187. udev_unref(udev);
  188. clear_detectone_meta_info();
  189. return found;
  190. }
  191. #else
  192. # define _serial_autodetect_udev(...) (0)
  193. #endif
  194. #ifndef WIN32
  195. static
  196. int _serial_autodetect_devserial(detectone_func_t detectone, va_list needles)
  197. {
  198. DIR *D;
  199. struct dirent *de;
  200. const char udevdir[] = "/dev/serial/by-id";
  201. char devpath[sizeof(udevdir) + 1 + NAME_MAX];
  202. char *devfile = devpath + sizeof(udevdir);
  203. char found = 0;
  204. // No way to split this out of the filename reliably
  205. clear_detectone_meta_info();
  206. D = opendir(udevdir);
  207. if (!D)
  208. return 0;
  209. memcpy(devpath, udevdir, sizeof(udevdir) - 1);
  210. devpath[sizeof(udevdir) - 1] = '/';
  211. while ( (de = readdir(D)) ) {
  212. if (!SEARCH_NEEDLES(de->d_name))
  213. continue;
  214. strcpy(devfile, de->d_name);
  215. if (detectone(devpath))
  216. ++found;
  217. }
  218. closedir(D);
  219. return found;
  220. }
  221. #else
  222. # define _serial_autodetect_devserial(...) (0)
  223. #endif
  224. #ifndef WIN32
  225. static
  226. char *_sysfs_do_read(char *buf, size_t bufsz, const char *devpath, char *devfile, const char *append)
  227. {
  228. FILE *F;
  229. strcpy(devfile, append);
  230. F = fopen(devpath, "r");
  231. if (F)
  232. {
  233. if (fgets(buf, bufsz, F))
  234. {
  235. size_t L = strlen(buf);
  236. while (isCspace(buf[--L]))
  237. buf[L] = '\0';
  238. }
  239. else
  240. buf[0] = '\0';
  241. fclose(F);
  242. }
  243. else
  244. buf[0] = '\0';
  245. return buf[0] ? buf : NULL;
  246. }
  247. static
  248. void _sysfs_find_tty(detectone_func_t detectone, char *devpath, char *devfile, const char *prod, char *pfound)
  249. {
  250. DIR *DT;
  251. struct dirent *de;
  252. char ttybuf[0x10] = "/dev/";
  253. char manuf[0x40], serial[0x40];
  254. char *mydevfile = strdup(devfile);
  255. DT = opendir(devpath);
  256. if (!DT)
  257. goto out;
  258. while ( (de = readdir(DT)) )
  259. {
  260. if (strncmp(de->d_name, "tty", 3))
  261. continue;
  262. if (!de->d_name[3])
  263. {
  264. // "tty" directory: recurse (needed for ttyACM)
  265. sprintf(devfile, "%s/tty", mydevfile);
  266. _sysfs_find_tty(detectone, devpath, devfile, prod, pfound);
  267. continue;
  268. }
  269. if (strncmp(&de->d_name[3], "USB", 3) && strncmp(&de->d_name[3], "ACM", 3))
  270. continue;
  271. detectone_meta_info = (struct detectone_meta_info_t){
  272. .manufacturer = _sysfs_do_read(manuf, sizeof(manuf), devpath, devfile, "/manufacturer"),
  273. .product = prod,
  274. .serial = _sysfs_do_read(serial, sizeof(serial), devpath, devfile, "/serial"),
  275. };
  276. strcpy(&ttybuf[5], de->d_name);
  277. if (detectone(ttybuf))
  278. ++*pfound;
  279. }
  280. closedir(DT);
  281. out:
  282. free(mydevfile);
  283. }
  284. static
  285. int _serial_autodetect_sysfs(detectone_func_t detectone, va_list needles)
  286. {
  287. DIR *D, *DS;
  288. struct dirent *de;
  289. const char devroot[] = "/sys/bus/usb/devices";
  290. const size_t devrootlen = sizeof(devroot) - 1;
  291. char devpath[sizeof(devroot) + (NAME_MAX * 3)];
  292. char prod[0x40];
  293. char *devfile, *upfile;
  294. char found = 0;
  295. size_t len, len2;
  296. D = opendir(devroot);
  297. if (!D)
  298. return 0;
  299. memcpy(devpath, devroot, devrootlen);
  300. devpath[devrootlen] = '/';
  301. while ( (de = readdir(D)) )
  302. {
  303. len = strlen(de->d_name);
  304. upfile = &devpath[devrootlen + 1];
  305. memcpy(upfile, de->d_name, len);
  306. devfile = upfile + len;
  307. if (!_sysfs_do_read(prod, sizeof(prod), devpath, devfile, "/product"))
  308. continue;
  309. if (!SEARCH_NEEDLES(prod))
  310. continue;
  311. devfile[0] = '\0';
  312. DS = opendir(devpath);
  313. if (!DS)
  314. continue;
  315. devfile[0] = '/';
  316. ++devfile;
  317. while ( (de = readdir(DS)) )
  318. {
  319. if (strncmp(de->d_name, upfile, len))
  320. continue;
  321. len2 = strlen(de->d_name);
  322. memcpy(devfile, de->d_name, len2 + 1);
  323. _sysfs_find_tty(detectone, devpath, devfile, prod, &found);
  324. }
  325. closedir(DS);
  326. }
  327. closedir(D);
  328. clear_detectone_meta_info();
  329. return found;
  330. }
  331. #else
  332. # define _serial_autodetect_sysfs(...) (0)
  333. #endif
  334. #ifdef HAVE_WIN_DDKUSB
  335. static const GUID WIN_GUID_DEVINTERFACE_USB_HOST_CONTROLLER = { 0x3ABF6F2D, 0x71C4, 0x462A, {0x8A, 0x92, 0x1E, 0x68, 0x61, 0xE6, 0xAF, 0x27} };
  336. static
  337. char *windows_usb_get_port_path(HANDLE hubh, const int portno)
  338. {
  339. size_t namesz;
  340. ULONG rsz;
  341. {
  342. USB_NODE_CONNECTION_NAME pathinfo = {
  343. .ConnectionIndex = portno,
  344. };
  345. if (!(DeviceIoControl(hubh, IOCTL_USB_GET_NODE_CONNECTION_NAME, &pathinfo, sizeof(pathinfo), &pathinfo, sizeof(pathinfo), &rsz, NULL) && rsz >= sizeof(pathinfo)))
  346. applogfailinfor(NULL, LOG_ERR, "ioctl (1)", "%s", bfg_strerror(GetLastError(), BST_SYSTEM));
  347. namesz = pathinfo.ActualLength;
  348. }
  349. const size_t bufsz = sizeof(USB_NODE_CONNECTION_NAME) + namesz;
  350. uint8_t buf[bufsz];
  351. USB_NODE_CONNECTION_NAME *path = (USB_NODE_CONNECTION_NAME *)buf;
  352. *path = (USB_NODE_CONNECTION_NAME){
  353. .ConnectionIndex = portno,
  354. };
  355. if (!(DeviceIoControl(hubh, IOCTL_USB_GET_NODE_CONNECTION_NAME, path, bufsz, path, bufsz, &rsz, NULL) && rsz >= sizeof(*path)))
  356. applogfailinfor(NULL, LOG_ERR, "ioctl (2)", "%s", bfg_strerror(GetLastError(), BST_SYSTEM));
  357. return ucs2tochar_dup(path->NodeName, path->ActualLength);
  358. }
  359. static
  360. char *windows_usb_get_string(HANDLE hubh, const int portno, const uint8_t descid)
  361. {
  362. if (!descid)
  363. return NULL;
  364. const size_t descsz_max = sizeof(USB_STRING_DESCRIPTOR) + MAXIMUM_USB_STRING_LENGTH;
  365. const size_t reqsz = sizeof(USB_DESCRIPTOR_REQUEST) + descsz_max;
  366. uint8_t buf[reqsz];
  367. USB_DESCRIPTOR_REQUEST * const req = (USB_DESCRIPTOR_REQUEST *)buf;
  368. USB_STRING_DESCRIPTOR * const desc = (USB_STRING_DESCRIPTOR *)&req[1];
  369. *req = (USB_DESCRIPTOR_REQUEST){
  370. .ConnectionIndex = portno,
  371. .SetupPacket = {
  372. .wValue = (USB_STRING_DESCRIPTOR_TYPE << 8) | descid,
  373. .wIndex = 0,
  374. .wLength = descsz_max,
  375. },
  376. };
  377. // Need to explicitly zero the output memory
  378. memset(desc, '\0', descsz_max);
  379. ULONG descsz;
  380. if (!DeviceIoControl(hubh, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, req, reqsz, req, reqsz, &descsz, NULL))
  381. applogfailinfor(NULL, LOG_DEBUG, "ioctl", "%s", bfg_strerror(GetLastError(), BST_SYSTEM));
  382. if (descsz < 2 || desc->bDescriptorType != USB_STRING_DESCRIPTOR_TYPE || desc->bLength > descsz - sizeof(USB_DESCRIPTOR_REQUEST) || desc->bLength % 2)
  383. applogfailr(NULL, LOG_ERR, "sanity check");
  384. return ucs2tochar_dup(desc->bString, desc->bLength);
  385. }
  386. static void _serial_autodetect_windows__hub(detectone_func_t, va_list, int *, const char *);
  387. static
  388. void _serial_autodetect_windows__hubport(detectone_func_t detectone, va_list needles, int * const foundp, HANDLE hubh, const int portno)
  389. {
  390. const size_t conninfosz = sizeof(USB_NODE_CONNECTION_INFORMATION) + (sizeof(USB_PIPE_INFO) * 30);
  391. uint8_t buf[conninfosz];
  392. USB_NODE_CONNECTION_INFORMATION * const conninfo = (USB_NODE_CONNECTION_INFORMATION *)buf;
  393. conninfo->ConnectionIndex = portno;
  394. ULONG respsz;
  395. if (!DeviceIoControl(hubh, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION, conninfo, conninfosz, conninfo, conninfosz, &respsz, NULL))
  396. applogfailinfor(, LOG_ERR, "ioctl", "%s", bfg_strerror(GetLastError(), BST_SYSTEM));
  397. if (conninfo->ConnectionStatus != DeviceConnected)
  398. return;
  399. if (conninfo->DeviceIsHub)
  400. {
  401. const char * const hubpath = windows_usb_get_port_path(hubh, portno);
  402. if (hubpath)
  403. _serial_autodetect_windows__hub(detectone, needles, foundp, hubpath);
  404. return;
  405. }
  406. const USB_DEVICE_DESCRIPTOR * const devdesc = &conninfo->DeviceDescriptor;
  407. char * const product = windows_usb_get_string(hubh, portno, devdesc->iProduct);
  408. if (!product)
  409. return;
  410. char *serial = NULL;
  411. if (!search_needles(product, needles))
  412. {
  413. out:
  414. free(product);
  415. free(serial);
  416. return;
  417. }
  418. serial = windows_usb_get_string(hubh, portno, devdesc->iSerialNumber);
  419. if (!serial)
  420. goto out;
  421. const size_t slen = strlen(serial);
  422. char subkey[52 + slen + 18 + 1];
  423. sprintf(subkey, "SYSTEM\\CurrentControlSet\\Enum\\USB\\VID_%04x&PID_%04x\\%s\\Device Parameters",
  424. (unsigned)devdesc->idVendor, (unsigned)devdesc->idProduct, serial);
  425. HKEY hkey;
  426. int e;
  427. if (ERROR_SUCCESS != (e = RegOpenKey(HKEY_LOCAL_MACHINE, subkey, &hkey)))
  428. {
  429. applogfailinfo(LOG_ERR, "open Device Parameters registry key", "%s", bfg_strerror(e, BST_SYSTEM));
  430. goto out;
  431. }
  432. char devpath[0x10] = "\\\\.\\";
  433. DWORD type, sz = sizeof(devpath) - 4;
  434. if (ERROR_SUCCESS != (e = RegQueryValueExA(hkey, "PortName", NULL, &type, (LPBYTE)&devpath[4], &sz)))
  435. {
  436. applogfailinfo(LOG_ERR, "get PortName registry key value", "%s", bfg_strerror(e, BST_SYSTEM));
  437. RegCloseKey(hkey);
  438. goto out;
  439. }
  440. RegCloseKey(hkey);
  441. if (type != REG_SZ)
  442. {
  443. applogfailinfor(, LOG_ERR, "get expected type for PortName registry key value", "%ld", (long)type);
  444. goto out;
  445. }
  446. char * const manuf = windows_usb_get_string(hubh, portno, devdesc->iManufacturer);
  447. detectone_meta_info = (struct detectone_meta_info_t){
  448. .manufacturer = manuf,
  449. .product = product,
  450. .serial = serial,
  451. };
  452. if (detectone(devpath))
  453. ++*foundp;
  454. clear_detectone_meta_info();
  455. free(manuf);
  456. goto out;
  457. }
  458. static
  459. void _serial_autodetect_windows__hub(detectone_func_t detectone, va_list needles, int * const foundp, const char * const hubpath)
  460. {
  461. HANDLE hubh;
  462. USB_NODE_INFORMATION nodeinfo;
  463. {
  464. char deviceName[4 + strlen(hubpath) + 1];
  465. sprintf(deviceName, "\\\\.\\%s", hubpath);
  466. hubh = CreateFile(deviceName, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
  467. if (hubh == INVALID_HANDLE_VALUE)
  468. applogr(, LOG_ERR, "Error opening USB hub device %s for autodetect: %s", deviceName, bfg_strerror(GetLastError(), BST_SYSTEM));
  469. }
  470. ULONG nBytes;
  471. if (!DeviceIoControl(hubh, IOCTL_USB_GET_NODE_INFORMATION, &nodeinfo, sizeof(nodeinfo), &nodeinfo, sizeof(nodeinfo), &nBytes, NULL))
  472. applogfailinfor(, LOG_ERR, "ioctl", "%s", bfg_strerror(GetLastError(), BST_SYSTEM));
  473. const int portcount = nodeinfo.u.HubInformation.HubDescriptor.bNumberOfPorts;
  474. for (int i = 1; i <= portcount; ++i)
  475. _serial_autodetect_windows__hubport(detectone, needles, foundp, hubh, i);
  476. CloseHandle(hubh);
  477. }
  478. static
  479. char *windows_usb_get_root_hub_path(HANDLE hcntlrh)
  480. {
  481. size_t namesz;
  482. ULONG rsz;
  483. {
  484. USB_ROOT_HUB_NAME pathinfo;
  485. if (!(DeviceIoControl(hcntlrh, IOCTL_USB_GET_ROOT_HUB_NAME, 0, 0, &pathinfo, sizeof(pathinfo), &rsz, NULL) && rsz >= sizeof(pathinfo)))
  486. applogfailinfor(NULL, LOG_ERR, "ioctl (1)", "%s", bfg_strerror(GetLastError(), BST_SYSTEM));
  487. namesz = pathinfo.ActualLength;
  488. }
  489. const size_t bufsz = sizeof(USB_ROOT_HUB_NAME) + namesz;
  490. uint8_t buf[bufsz];
  491. USB_ROOT_HUB_NAME *hubpath = (USB_ROOT_HUB_NAME *)buf;
  492. if (!(DeviceIoControl(hcntlrh, IOCTL_USB_GET_ROOT_HUB_NAME, NULL, 0, hubpath, bufsz, &rsz, NULL) && rsz >= sizeof(*hubpath)))
  493. applogfailinfor(NULL, LOG_ERR, "ioctl (2)", "%s", bfg_strerror(GetLastError(), BST_SYSTEM));
  494. return ucs2tochar_dup(hubpath->RootHubName, hubpath->ActualLength);
  495. }
  496. static
  497. void _serial_autodetect_windows__hcntlr(detectone_func_t detectone, va_list needles, int * const foundp, HDEVINFO *devinfo, const int i)
  498. {
  499. SP_DEVICE_INTERFACE_DATA devifacedata = {
  500. .cbSize = sizeof(devifacedata),
  501. };
  502. if (!SetupDiEnumDeviceInterfaces(*devinfo, 0, (LPGUID)&WIN_GUID_DEVINTERFACE_USB_HOST_CONTROLLER, i, &devifacedata))
  503. applogfailinfor(, LOG_ERR, "SetupDiEnumDeviceInterfaces", "%s", bfg_strerror(GetLastError(), BST_SYSTEM));
  504. DWORD detailsz;
  505. if (!(!SetupDiGetDeviceInterfaceDetail(*devinfo, &devifacedata, NULL, 0, &detailsz, NULL) && GetLastError() == ERROR_INSUFFICIENT_BUFFER))
  506. applogfailinfor(, LOG_ERR, "SetupDiEnumDeviceInterfaceDetail (1)", "%s", bfg_strerror(GetLastError(), BST_SYSTEM));
  507. PSP_DEVICE_INTERFACE_DETAIL_DATA detail = alloca(detailsz);
  508. detail->cbSize = sizeof(*detail);
  509. if (!SetupDiGetDeviceInterfaceDetail(*devinfo, &devifacedata, detail, detailsz, &detailsz, NULL))
  510. applogfailinfor(, LOG_ERR, "SetupDiEnumDeviceInterfaceDetail (2)", "%s", bfg_strerror(GetLastError(), BST_SYSTEM));
  511. HANDLE hcntlrh = CreateFile(detail->DevicePath, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
  512. if (hcntlrh == INVALID_HANDLE_VALUE)
  513. applogfailinfor(, LOG_DEBUG, "open USB host controller device", "%s", bfg_strerror(GetLastError(), BST_SYSTEM));
  514. char * const hubpath = windows_usb_get_root_hub_path(hcntlrh);
  515. CloseHandle(hcntlrh);
  516. _serial_autodetect_windows__hub(detectone, needles, foundp, hubpath);
  517. free(hubpath);
  518. }
  519. static
  520. int _serial_autodetect_windows(detectone_func_t detectone, va_list needles)
  521. {
  522. int found = 0;
  523. HDEVINFO devinfo;
  524. devinfo = SetupDiGetClassDevs(&WIN_GUID_DEVINTERFACE_USB_HOST_CONTROLLER, NULL, NULL, (DIGCF_PRESENT | DIGCF_DEVICEINTERFACE));
  525. SP_DEVINFO_DATA devinfodata = {
  526. .cbSize = sizeof(devinfodata),
  527. };
  528. for (int i = 0; SetupDiEnumDeviceInfo(devinfo, i, &devinfodata); ++i)
  529. _serial_autodetect_windows__hcntlr(detectone, needles, &found, &devinfo, i);
  530. SetupDiDestroyDeviceInfoList(devinfo);
  531. return found;
  532. }
  533. #endif
  534. #ifdef WIN32
  535. #define LOAD_SYM(sym) do { \
  536. if (!(sym = dlsym(dll, #sym))) { \
  537. applog(LOG_DEBUG, "Failed to load " #sym ", not using FTDI autodetect"); \
  538. goto out; \
  539. } \
  540. } while(0)
  541. static
  542. char *_ftdi_get_string(char *buf, int i, DWORD flags)
  543. {
  544. if (FT_OK != FT_ListDevices((PVOID)i, buf, FT_LIST_BY_INDEX | flags))
  545. return NULL;
  546. return buf[0] ? buf : NULL;
  547. }
  548. static
  549. int _serial_autodetect_ftdi(detectone_func_t detectone, va_list needles)
  550. {
  551. char devpath[] = "\\\\.\\COMnnnnn";
  552. char *devpathnum = &devpath[7];
  553. char **bufptrs;
  554. char *buf;
  555. char serial[64];
  556. int found = 0;
  557. DWORD i;
  558. FT_STATUS ftStatus;
  559. DWORD numDevs;
  560. HMODULE dll = LoadLibrary("FTD2XX.DLL");
  561. if (!dll) {
  562. applog(LOG_DEBUG, "FTD2XX.DLL failed to load, not using FTDI autodetect");
  563. return 0;
  564. }
  565. LOAD_SYM(FT_ListDevices);
  566. LOAD_SYM(FT_Open);
  567. LOAD_SYM(FT_GetComPortNumber);
  568. LOAD_SYM(FT_Close);
  569. ftStatus = FT_ListDevices(&numDevs, NULL, FT_LIST_NUMBER_ONLY);
  570. if (ftStatus != FT_OK) {
  571. applog(LOG_DEBUG, "FTDI device count failed, not using FTDI autodetect");
  572. goto out;
  573. }
  574. applog(LOG_DEBUG, "FTDI reports %u devices", (unsigned)numDevs);
  575. buf = alloca(65 * numDevs);
  576. bufptrs = alloca(sizeof(*bufptrs) * (numDevs + 1));
  577. for (i = 0; i < numDevs; ++i)
  578. bufptrs[i] = &buf[i * 65];
  579. bufptrs[numDevs] = NULL;
  580. ftStatus = FT_ListDevices(bufptrs, &numDevs, FT_LIST_ALL | FT_OPEN_BY_DESCRIPTION);
  581. if (ftStatus != FT_OK) {
  582. applog(LOG_DEBUG, "FTDI device list failed, not using FTDI autodetect");
  583. goto out;
  584. }
  585. clear_detectone_meta_info();
  586. for (i = numDevs; i > 0; ) {
  587. --i;
  588. bufptrs[i][64] = '\0';
  589. if (!SEARCH_NEEDLES(bufptrs[i]))
  590. continue;
  591. FT_HANDLE ftHandle;
  592. if (FT_OK != FT_Open(i, &ftHandle))
  593. continue;
  594. LONG lComPortNumber;
  595. ftStatus = FT_GetComPortNumber(ftHandle, &lComPortNumber);
  596. FT_Close(ftHandle);
  597. if (FT_OK != ftStatus || lComPortNumber < 0)
  598. continue;
  599. applog(LOG_ERR, "FT_GetComPortNumber(%p (%ld), %ld)", ftHandle, (long)i, (long)lComPortNumber);
  600. detectone_meta_info = (struct detectone_meta_info_t){
  601. .product = bufptrs[i],
  602. .serial = _ftdi_get_string(serial, i, FT_OPEN_BY_SERIAL_NUMBER),
  603. };
  604. sprintf(devpathnum, "%d", (int)lComPortNumber);
  605. if (detectone(devpath))
  606. ++found;
  607. }
  608. out:
  609. clear_detectone_meta_info();
  610. dlclose(dll);
  611. return found;
  612. }
  613. #else
  614. # define _serial_autodetect_ftdi(...) (0)
  615. #endif
  616. #undef detectone
  617. int _serial_autodetect(detectone_func_t detectone, ...)
  618. {
  619. int rv;
  620. va_list needles;
  621. va_start(needles, detectone);
  622. rv = (
  623. _serial_autodetect_udev (detectone, needles) ?:
  624. _serial_autodetect_sysfs (detectone, needles) ?:
  625. _serial_autodetect_devserial(detectone, needles) ?:
  626. #ifdef HAVE_WIN_DDKUSB
  627. _serial_autodetect_windows (detectone, needles) ?:
  628. #endif
  629. _serial_autodetect_ftdi (detectone, needles) ?:
  630. 0);
  631. va_end(needles);
  632. return rv;
  633. }
  634. struct _device_claim {
  635. struct device_drv *drv;
  636. char *devpath;
  637. UT_hash_handle hh;
  638. };
  639. struct device_drv *bfg_claim_any(struct device_drv * const api, const char *verbose, const char * const devpath)
  640. {
  641. static struct _device_claim *claims = NULL;
  642. struct _device_claim *c;
  643. HASH_FIND_STR(claims, devpath, c);
  644. if (c)
  645. {
  646. if (verbose && opt_debug)
  647. {
  648. char logbuf[LOGBUFSIZ];
  649. logbuf[0] = '\0';
  650. if (api)
  651. tailsprintf(logbuf, sizeof(logbuf), "%s device ", api->dname);
  652. if (verbose[0])
  653. tailsprintf(logbuf, sizeof(logbuf), "%s (%s)", verbose, devpath);
  654. else
  655. tailsprintf(logbuf, sizeof(logbuf), "%s", devpath);
  656. tailsprintf(logbuf, sizeof(logbuf), " already claimed by ");
  657. if (api)
  658. tailsprintf(logbuf, sizeof(logbuf), "other ");
  659. tailsprintf(logbuf, sizeof(logbuf), "driver: %s", c->drv->dname);
  660. _applog(LOG_DEBUG, logbuf);
  661. }
  662. return c->drv;
  663. }
  664. if (!api)
  665. return NULL;
  666. c = malloc(sizeof(*c));
  667. c->devpath = strdup(devpath);
  668. c->drv = api;
  669. HASH_ADD_KEYPTR(hh, claims, c->devpath, strlen(devpath), c);
  670. return NULL;
  671. }
  672. struct device_drv *bfg_claim_any2(struct device_drv * const api, const char * const verbose, const char * const llname, const char * const path)
  673. {
  674. const size_t llnamesz = strlen(llname);
  675. const size_t pathsz = strlen(path);
  676. char devpath[llnamesz + 1 + pathsz + 1];
  677. memcpy(devpath, llname, llnamesz);
  678. devpath[llnamesz] = ':';
  679. memcpy(&devpath[llnamesz+1], path, pathsz + 1);
  680. return bfg_claim_any(api, verbose, devpath);
  681. }
  682. struct device_drv *bfg_claim_serial(struct device_drv * const api, const bool verbose, const char * const devpath)
  683. {
  684. #ifndef WIN32
  685. char devs[6 + (sizeof(dev_t) * 2) + 1];
  686. {
  687. struct stat my_stat;
  688. if (stat(devpath, &my_stat))
  689. return NULL;
  690. memcpy(devs, "dev_t:", 6);
  691. bin2hex(&devs[6], &my_stat.st_rdev, sizeof(dev_t));
  692. }
  693. #else
  694. char *p = strstr(devpath, "COM"), *p2;
  695. if (!p)
  696. return NULL;
  697. const int com = strtol(&p[3], &p2, 10);
  698. if (p2 == p)
  699. return NULL;
  700. char dummy;
  701. const int sz = snprintf(&dummy, 1, "%d", com);
  702. char devs[4 + sz + 1];
  703. sprintf(devs, "com:%d", com);
  704. #endif
  705. return bfg_claim_any(api, (verbose ? devpath : NULL), devs);
  706. }
  707. struct device_drv *bfg_claim_usb(struct device_drv * const api, const bool verbose, const uint8_t usbbus, const uint8_t usbaddr)
  708. {
  709. char devpath[12];
  710. sprintf(devpath, "usb:%03u:%03u", (unsigned)usbbus, (unsigned)usbaddr);
  711. return bfg_claim_any(api, verbose ? "" : NULL, devpath);
  712. }
  713. #ifdef HAVE_LIBUSB
  714. void cgpu_copy_libusb_strings(struct cgpu_info *cgpu, libusb_device *usb)
  715. {
  716. unsigned char buf[0x20];
  717. libusb_device_handle *h;
  718. struct libusb_device_descriptor desc;
  719. if (LIBUSB_SUCCESS != libusb_open(usb, &h))
  720. return;
  721. if (libusb_get_device_descriptor(usb, &desc))
  722. {
  723. libusb_close(h);
  724. return;
  725. }
  726. if ((!cgpu->dev_manufacturer) && libusb_get_string_descriptor_ascii(h, desc.iManufacturer, buf, sizeof(buf)) >= 0)
  727. cgpu->dev_manufacturer = strdup((void *)buf);
  728. if ((!cgpu->dev_product) && libusb_get_string_descriptor_ascii(h, desc.iProduct, buf, sizeof(buf)) >= 0)
  729. cgpu->dev_product = strdup((void *)buf);
  730. if ((!cgpu->dev_serial) && libusb_get_string_descriptor_ascii(h, desc.iSerialNumber, buf, sizeof(buf)) >= 0)
  731. cgpu->dev_serial = strdup((void *)buf);
  732. libusb_close(h);
  733. }
  734. #endif
  735. // This code is purely for debugging but is very useful for that
  736. // It also took quite a bit of effort so I left it in
  737. // #define TERMIOS_DEBUG 1
  738. // Here to include it at compile time
  739. // It's off by default
  740. #ifndef WIN32
  741. #ifdef TERMIOS_DEBUG
  742. #define BITSSET "Y"
  743. #define BITSNOTSET "N"
  744. int tiospeed(speed_t speed)
  745. {
  746. switch (speed) {
  747. #define IOSPEED(baud) \
  748. case B ## baud: \
  749. return baud; \
  750. // END
  751. #include "iospeeds_local.h"
  752. #undef IOSPEED
  753. default:
  754. return -1;
  755. }
  756. }
  757. void termios_debug(const char *devpath, struct termios *my_termios, const char *msg)
  758. {
  759. applog(LOG_DEBUG, "TIOS: Open %s attributes %s: ispeed=%d ospeed=%d",
  760. devpath, msg, tiospeed(cfgetispeed(my_termios)), tiospeed(cfgetispeed(my_termios)));
  761. #define ISSETI(b) ((my_termios->c_iflag | (b)) ? BITSSET : BITSNOTSET)
  762. 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",
  763. ISSETI(IGNBRK), ISSETI(BRKINT), ISSETI(IGNPAR), ISSETI(PARMRK),
  764. ISSETI(INPCK), ISSETI(ISTRIP), ISSETI(INLCR), ISSETI(IGNCR),
  765. ISSETI(ICRNL), ISSETI(IUCLC), ISSETI(IXON), ISSETI(IXANY),
  766. ISSETI(IXOFF), ISSETI(IMAXBEL), ISSETI(IUTF8));
  767. #define ISSETO(b) ((my_termios->c_oflag | (b)) ? BITSSET : BITSNOTSET)
  768. #define VALO(b) (my_termios->c_oflag | (b))
  769. 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",
  770. ISSETO(OPOST), ISSETO(OLCUC), ISSETO(ONLCR), ISSETO(OCRNL),
  771. ISSETO(ONOCR), ISSETO(ONLRET), ISSETO(OFILL), ISSETO(OFDEL),
  772. VALO(NLDLY), VALO(CRDLY), VALO(TABDLY), VALO(BSDLY),
  773. VALO(VTDLY), VALO(FFDLY));
  774. #define ISSETC(b) ((my_termios->c_cflag | (b)) ? BITSSET : BITSNOTSET)
  775. #define VALC(b) (my_termios->c_cflag | (b))
  776. applog(LOG_DEBUG, "TIOS: c_cflag: CBAUDEX=%s CSIZE=%d CSTOPB=%s CREAD=%s PARENB=%s PARODD=%s HUPCL=%s CLOCAL=%s"
  777. #ifdef LOBLK
  778. " LOBLK=%s"
  779. #endif
  780. " CMSPAR=%s CRTSCTS=%s",
  781. ISSETC(CBAUDEX), VALC(CSIZE), ISSETC(CSTOPB), ISSETC(CREAD),
  782. ISSETC(PARENB), ISSETC(PARODD), ISSETC(HUPCL), ISSETC(CLOCAL),
  783. #ifdef LOBLK
  784. ISSETC(LOBLK),
  785. #endif
  786. ISSETC(CMSPAR), ISSETC(CRTSCTS));
  787. #define ISSETL(b) ((my_termios->c_lflag | (b)) ? BITSSET : BITSNOTSET)
  788. 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"
  789. #ifdef DEFECHO
  790. " DEFECHO=%s"
  791. #endif
  792. " FLUSHO=%s NOFLSH=%s TOSTOP=%s PENDIN=%s IEXTEN=%s",
  793. ISSETL(ISIG), ISSETL(ICANON), ISSETL(XCASE), ISSETL(ECHO),
  794. ISSETL(ECHOE), ISSETL(ECHOK), ISSETL(ECHONL), ISSETL(ECHOCTL),
  795. ISSETL(ECHOPRT), ISSETL(ECHOKE),
  796. #ifdef DEFECHO
  797. ISSETL(DEFECHO),
  798. #endif
  799. ISSETL(FLUSHO), ISSETL(NOFLSH), ISSETL(TOSTOP), ISSETL(PENDIN),
  800. ISSETL(IEXTEN));
  801. #define VALCC(b) (my_termios->c_cc[b])
  802. 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"
  803. #ifdef VSWTCH
  804. " VSWTCH=0x%02x"
  805. #endif
  806. " VSTART=0x%02x VSTOP=0x%02x VSUSP=0x%02x"
  807. #ifdef VDSUSP
  808. " VDSUSP=0x%02x"
  809. #endif
  810. " VLNEXT=0x%02x VWERASE=0x%02x VREPRINT=0x%02x VDISCARD=0x%02x"
  811. #ifdef VSTATUS
  812. " VSTATUS=0x%02x"
  813. #endif
  814. ,
  815. VALCC(VINTR), VALCC(VQUIT), VALCC(VERASE), VALCC(VKILL),
  816. VALCC(VEOF), VALCC(VMIN), VALCC(VEOL), VALCC(VTIME),
  817. VALCC(VEOL2),
  818. #ifdef VSWTCH
  819. VALCC(VSWTCH),
  820. #endif
  821. VALCC(VSTART), VALCC(VSTOP), VALCC(VSUSP),
  822. #ifdef VDSUSP
  823. VALCC(VDSUSP),
  824. #endif
  825. VALCC(VLNEXT), VALCC(VWERASE),
  826. VALCC(VREPRINT), VALCC(VDISCARD)
  827. #ifdef VSTATUS
  828. ,VALCC(VSTATUS)
  829. #endif
  830. );
  831. }
  832. #endif /* TERMIOS_DEBUG */
  833. speed_t tiospeed_t(int baud)
  834. {
  835. switch (baud) {
  836. #define IOSPEED(baud) \
  837. case baud: \
  838. return B ## baud; \
  839. // END
  840. #include "iospeeds_local.h"
  841. #undef IOSPEED
  842. default:
  843. return B0;
  844. }
  845. }
  846. #endif /* WIN32 */
  847. bool valid_baud(int baud)
  848. {
  849. switch (baud) {
  850. #define IOSPEED(baud) \
  851. case baud: \
  852. return true; \
  853. // END
  854. #include "iospeeds_local.h"
  855. #undef IOSPEED
  856. default:
  857. return false;
  858. }
  859. }
  860. /* NOTE: Linux only supports uint8_t (decisecond) timeouts; limiting it in
  861. * this interface buys us warnings when bad constants are passed in.
  862. */
  863. int serial_open(const char *devpath, unsigned long baud, uint8_t timeout, bool purge)
  864. {
  865. #ifdef WIN32
  866. HANDLE hSerial = CreateFile(devpath, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
  867. if (unlikely(hSerial == INVALID_HANDLE_VALUE))
  868. {
  869. DWORD e = GetLastError();
  870. switch (e) {
  871. case ERROR_ACCESS_DENIED:
  872. applog(LOG_ERR, "Do not have user privileges required to open %s", devpath);
  873. break;
  874. case ERROR_SHARING_VIOLATION:
  875. applog(LOG_ERR, "%s is already in use by another process", devpath);
  876. break;
  877. default:
  878. applog(LOG_DEBUG, "Open %s failed, GetLastError:%u", devpath, (unsigned)e);
  879. break;
  880. }
  881. return -1;
  882. }
  883. // thanks to af_newbie for pointers about this
  884. COMMCONFIG comCfg = {0};
  885. comCfg.dwSize = sizeof(COMMCONFIG);
  886. comCfg.wVersion = 1;
  887. comCfg.dcb.DCBlength = sizeof(DCB);
  888. comCfg.dcb.BaudRate = baud;
  889. comCfg.dcb.fBinary = 1;
  890. comCfg.dcb.fDtrControl = DTR_CONTROL_ENABLE;
  891. comCfg.dcb.fRtsControl = RTS_CONTROL_ENABLE;
  892. comCfg.dcb.ByteSize = 8;
  893. SetCommConfig(hSerial, &comCfg, sizeof(comCfg));
  894. // Code must specify a valid timeout value (0 means don't timeout)
  895. const DWORD ctoms = ((DWORD)timeout * 100);
  896. COMMTIMEOUTS cto = {ctoms, 0, ctoms, 0, ctoms};
  897. SetCommTimeouts(hSerial, &cto);
  898. if (purge) {
  899. PurgeComm(hSerial, PURGE_RXABORT);
  900. PurgeComm(hSerial, PURGE_TXABORT);
  901. PurgeComm(hSerial, PURGE_RXCLEAR);
  902. PurgeComm(hSerial, PURGE_TXCLEAR);
  903. }
  904. return _open_osfhandle((intptr_t)hSerial, 0);
  905. #else
  906. int fdDev = open(devpath, O_RDWR | O_CLOEXEC | O_NOCTTY);
  907. if (unlikely(fdDev == -1))
  908. {
  909. if (errno == EACCES)
  910. applog(LOG_ERR, "Do not have user privileges required to open %s", devpath);
  911. else
  912. applog(LOG_DEBUG, "Open %s failed: %s", devpath, bfg_strerror(errno, BST_ERRNO));
  913. return -1;
  914. }
  915. #if defined(LOCK_EX) && defined(LOCK_NB)
  916. if (likely(!flock(fdDev, LOCK_EX | LOCK_NB)))
  917. applog(LOG_DEBUG, "Acquired exclusive advisory lock on %s", devpath);
  918. else
  919. if (errno == EWOULDBLOCK)
  920. {
  921. applog(LOG_ERR, "%s is already in use by another process", devpath);
  922. close(fdDev);
  923. return -1;
  924. }
  925. else
  926. applog(LOG_WARNING, "Failed to acquire exclusive lock on %s: %s (ignoring)", devpath, bfg_strerror(errno, BST_ERRNO));
  927. #endif
  928. struct termios my_termios;
  929. tcgetattr(fdDev, &my_termios);
  930. #ifdef TERMIOS_DEBUG
  931. termios_debug(devpath, &my_termios, "before");
  932. #endif
  933. if (baud)
  934. {
  935. speed_t speed = tiospeed_t(baud);
  936. if (speed == B0)
  937. applog(LOG_WARNING, "Unrecognized baud rate: %lu", baud);
  938. else
  939. {
  940. cfsetispeed(&my_termios, speed);
  941. cfsetospeed(&my_termios, speed);
  942. }
  943. }
  944. my_termios.c_cflag &= ~(CSIZE | PARENB);
  945. my_termios.c_cflag |= CS8;
  946. my_termios.c_cflag |= CREAD;
  947. #ifdef USE_AVALON
  948. // my_termios.c_cflag |= CRTSCTS;
  949. #endif
  950. my_termios.c_cflag |= CLOCAL;
  951. my_termios.c_iflag &= ~(IGNBRK | BRKINT | PARMRK |
  952. ISTRIP | INLCR | IGNCR | ICRNL | IXON);
  953. my_termios.c_oflag &= ~OPOST;
  954. my_termios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
  955. // Code must specify a valid timeout value (0 means don't timeout)
  956. my_termios.c_cc[VTIME] = (cc_t)timeout;
  957. my_termios.c_cc[VMIN] = 0;
  958. #ifdef TERMIOS_DEBUG
  959. termios_debug(devpath, &my_termios, "settings");
  960. #endif
  961. tcsetattr(fdDev, TCSANOW, &my_termios);
  962. #ifdef TERMIOS_DEBUG
  963. tcgetattr(fdDev, &my_termios);
  964. termios_debug(devpath, &my_termios, "after");
  965. #endif
  966. if (purge)
  967. tcflush(fdDev, TCIOFLUSH);
  968. return fdDev;
  969. #endif
  970. }
  971. int serial_close(const int fd)
  972. {
  973. #if defined(LOCK_EX) && defined(LOCK_NB) && defined(LOCK_UN)
  974. flock(fd, LOCK_UN);
  975. #endif
  976. return close(fd);
  977. }
  978. ssize_t _serial_read(int fd, char *buf, size_t bufsiz, char *eol)
  979. {
  980. ssize_t len, tlen = 0;
  981. while (bufsiz) {
  982. len = read(fd, buf, eol ? 1 : bufsiz);
  983. if (len < 1)
  984. break;
  985. tlen += len;
  986. if (eol && *eol == buf[0])
  987. break;
  988. buf += len;
  989. bufsiz -= len;
  990. }
  991. return tlen;
  992. }
  993. #define bailout(...) do { \
  994. applog(__VA_ARGS__); \
  995. return NULL; \
  996. } while(0)
  997. #define check_magic(L) do { \
  998. if (1 != fread(buf, 1, 1, f)) \
  999. bailout(LOG_ERR, "%s: Error reading bitstream ('%c')", \
  1000. repr, L); \
  1001. if (buf[0] != L) \
  1002. bailout(LOG_ERR, "%s: Firmware has wrong magic ('%c')", \
  1003. repr, L); \
  1004. } while(0)
  1005. #define read_str(eng) do { \
  1006. if (1 != fread(buf, 2, 1, f)) \
  1007. bailout(LOG_ERR, "%s: Error reading bitstream (" eng " len)", \
  1008. repr); \
  1009. len = (ubuf[0] << 8) | ubuf[1]; \
  1010. if (len >= sizeof(buf)) \
  1011. bailout(LOG_ERR, "%s: Firmware " eng " too long", \
  1012. repr); \
  1013. if (1 != fread(buf, len, 1, f)) \
  1014. bailout(LOG_ERR, "%s: Error reading bitstream (" eng ")", \
  1015. repr); \
  1016. buf[len] = '\0'; \
  1017. } while(0)
  1018. void _bitstream_not_found(const char *repr, const char *fn)
  1019. {
  1020. applog(LOG_ERR, "ERROR: Unable to load '%s', required for %s to work!", fn, repr);
  1021. applog(LOG_ERR, "ERROR: Please read README.FPGA for instructions");
  1022. }
  1023. FILE *open_xilinx_bitstream(const char *dname, const char *repr, const char *fwfile, unsigned long *out_len)
  1024. {
  1025. char buf[0x100];
  1026. unsigned char *ubuf = (unsigned char*)buf;
  1027. unsigned long len;
  1028. char *p;
  1029. FILE *f = open_bitstream(dname, fwfile);
  1030. if (!f)
  1031. {
  1032. _bitstream_not_found(repr, fwfile);
  1033. return NULL;
  1034. }
  1035. if (1 != fread(buf, 2, 1, f))
  1036. bailout(LOG_ERR, "%s: Error reading bitstream (magic)",
  1037. repr);
  1038. if (buf[0] || buf[1] != 9)
  1039. bailout(LOG_ERR, "%s: Firmware has wrong magic (9)",
  1040. repr);
  1041. if (-1 == fseek(f, 11, SEEK_CUR))
  1042. bailout(LOG_ERR, "%s: Firmware seek failed",
  1043. repr);
  1044. check_magic('a');
  1045. read_str("design name");
  1046. applog(LOG_DEBUG, "%s: Firmware file %s info:",
  1047. repr, fwfile);
  1048. applog(LOG_DEBUG, " Design name: %s", buf);
  1049. p = strrchr(buf, ';') ?: buf;
  1050. p = strrchr(buf, '=') ?: p;
  1051. if (p[0] == '=')
  1052. ++p;
  1053. unsigned long fwusercode = (unsigned long)strtoll(p, &p, 16);
  1054. if (p[0] != '\0')
  1055. bailout(LOG_ERR, "%s: Bad usercode in bitstream file",
  1056. repr);
  1057. if (fwusercode == 0xffffffff)
  1058. bailout(LOG_ERR, "%s: Firmware doesn't support user code",
  1059. repr);
  1060. applog(LOG_DEBUG, " Version: %u, build %u", (unsigned)((fwusercode >> 8) & 0xff), (unsigned)(fwusercode & 0xff));
  1061. check_magic('b');
  1062. read_str("part number");
  1063. applog(LOG_DEBUG, " Part number: %s", buf);
  1064. check_magic('c');
  1065. read_str("build date");
  1066. applog(LOG_DEBUG, " Build date: %s", buf);
  1067. check_magic('d');
  1068. read_str("build time");
  1069. applog(LOG_DEBUG, " Build time: %s", buf);
  1070. check_magic('e');
  1071. if (1 != fread(buf, 4, 1, f))
  1072. bailout(LOG_ERR, "%s: Error reading bitstream (data len)",
  1073. repr);
  1074. len = ((unsigned long)ubuf[0] << 24) | ((unsigned long)ubuf[1] << 16) | (ubuf[2] << 8) | ubuf[3];
  1075. applog(LOG_DEBUG, " Bitstream size: %lu", len);
  1076. *out_len = len;
  1077. return f;
  1078. }
  1079. bool load_bitstream_intelhex(bytes_t *rv, const char *dname, const char *repr, const char *fn)
  1080. {
  1081. char buf[0x100];
  1082. size_t sz;
  1083. uint8_t xsz, xrt;
  1084. uint16_t xaddr;
  1085. FILE *F = open_bitstream(dname, fn);
  1086. if (!F)
  1087. return false;
  1088. while (!feof(F))
  1089. {
  1090. if (unlikely(ferror(F)))
  1091. {
  1092. applog(LOG_ERR, "Error reading '%s'", fn);
  1093. goto ihxerr;
  1094. }
  1095. if (!fgets(buf, sizeof(buf), F))
  1096. goto ihxerr;
  1097. if (unlikely(buf[0] != ':'))
  1098. goto ihxerr;
  1099. if (unlikely(!(
  1100. hex2bin(&xsz, &buf[1], 1)
  1101. && hex2bin((unsigned char*)&xaddr, &buf[3], 2)
  1102. && hex2bin(&xrt, &buf[7], 1)
  1103. )))
  1104. {
  1105. applog(LOG_ERR, "Error parsing in '%s'", fn);
  1106. goto ihxerr;
  1107. }
  1108. switch (xrt)
  1109. {
  1110. case 0: // data
  1111. break;
  1112. case 1: // EOF
  1113. fclose(F);
  1114. return true;
  1115. default:
  1116. applog(LOG_ERR, "Unsupported record type in '%s'", fn);
  1117. goto ihxerr;
  1118. }
  1119. xaddr = be16toh(xaddr);
  1120. sz = bytes_len(rv);
  1121. bytes_resize(rv, xaddr + xsz);
  1122. if (sz < xaddr)
  1123. memset(&bytes_buf(rv)[sz], 0xff, xaddr - sz);
  1124. if (unlikely(!(hex2bin(&bytes_buf(rv)[xaddr], &buf[9], xsz))))
  1125. {
  1126. applog(LOG_ERR, "Error parsing data in '%s'", fn);
  1127. goto ihxerr;
  1128. }
  1129. // TODO: checksum
  1130. }
  1131. ihxerr:
  1132. fclose(F);
  1133. bytes_reset(rv);
  1134. return false;
  1135. }
  1136. bool load_bitstream_bytes(bytes_t *rv, const char *dname, const char *repr, const char *fileprefix)
  1137. {
  1138. FILE *F;
  1139. size_t fplen = strlen(fileprefix);
  1140. char fnbuf[fplen + 4 + 1];
  1141. int e;
  1142. bytes_reset(rv);
  1143. memcpy(fnbuf, fileprefix, fplen);
  1144. strcpy(&fnbuf[fplen], ".bin");
  1145. F = open_bitstream(dname, fnbuf);
  1146. if (F)
  1147. {
  1148. char buf[0x100];
  1149. size_t sz;
  1150. while ( (sz = fread(buf, 1, sizeof(buf), F)) )
  1151. bytes_append(rv, buf, sz);
  1152. e = ferror(F);
  1153. fclose(F);
  1154. if (unlikely(e))
  1155. {
  1156. applog(LOG_ERR, "Error reading '%s'", fnbuf);
  1157. bytes_reset(rv);
  1158. }
  1159. else
  1160. return true;
  1161. }
  1162. strcpy(&fnbuf[fplen], ".ihx");
  1163. if (load_bitstream_intelhex(rv, dname, repr, fnbuf))
  1164. return true;
  1165. // TODO: Xilinx
  1166. _bitstream_not_found(repr, fnbuf);
  1167. return false;
  1168. }
  1169. #ifndef WIN32
  1170. int get_serial_cts(int fd)
  1171. {
  1172. int flags;
  1173. if (!fd)
  1174. return -1;
  1175. ioctl(fd, TIOCMGET, &flags);
  1176. return (flags & TIOCM_CTS) ? 1 : 0;
  1177. }
  1178. int set_serial_rts(int fd, int rts)
  1179. {
  1180. int flags;
  1181. if (!fd)
  1182. return -1;
  1183. ioctl(fd, TIOCMGET, &flags);
  1184. if (rts)
  1185. flags |= TIOCM_RTS;
  1186. else
  1187. flags &= ~TIOCM_RTS;
  1188. ioctl(fd, TIOCMSET, &flags);
  1189. return flags & TIOCM_CTS;
  1190. }
  1191. #else
  1192. int get_serial_cts(const int fd)
  1193. {
  1194. if (!fd)
  1195. return -1;
  1196. const HANDLE fh = (HANDLE)_get_osfhandle(fd);
  1197. if (!fh)
  1198. return -1;
  1199. DWORD flags;
  1200. if (!GetCommModemStatus(fh, &flags))
  1201. return -1;
  1202. return (flags & MS_CTS_ON) ? 1 : 0;
  1203. }
  1204. #endif // ! WIN32