fpgautils.c 37 KB

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