driver-bitforce.c 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101
  1. /*
  2. * Copyright 2012-2013 Luke Dashjr
  3. * Copyright 2012 Con Kolivas
  4. *
  5. * This program is free software; you can redistribute it and/or modify it
  6. * under the terms of the GNU General Public License as published by the Free
  7. * Software Foundation; either version 3 of the License, or (at your option)
  8. * any later version. See COPYING for more details.
  9. */
  10. #include "config.h"
  11. #include <ctype.h>
  12. #include <limits.h>
  13. #include <pthread.h>
  14. #include <stdbool.h>
  15. #include <stdint.h>
  16. #include <stdio.h>
  17. #include <strings.h>
  18. #include <sys/time.h>
  19. #include <unistd.h>
  20. #include "compat.h"
  21. #include "deviceapi.h"
  22. #include "miner.h"
  23. #include "lowlevel.h"
  24. #include "lowl-vcom.h"
  25. #include "util.h"
  26. #define BITFORCE_SLEEP_MS 500
  27. #define BITFORCE_TIMEOUT_S 7
  28. #define BITFORCE_TIMEOUT_MS (BITFORCE_TIMEOUT_S * 1000)
  29. #define BITFORCE_LONG_TIMEOUT_S 25
  30. #define BITFORCE_LONG_TIMEOUT_MS (BITFORCE_LONG_TIMEOUT_S * 1000)
  31. #define BITFORCE_CHECK_INTERVAL_MS 10
  32. #define WORK_CHECK_INTERVAL_MS 50
  33. #define MAX_START_DELAY_MS 100
  34. #define tv_to_ms(tval) ((unsigned long)(tval.tv_sec * 1000 + tval.tv_usec / 1000))
  35. #define TIME_AVG_CONSTANT 8
  36. #define BITFORCE_QRESULT_LINE_LEN 165
  37. #define BITFORCE_MAX_QUEUED_MAX 40
  38. #define BITFORCE_MIN_QUEUED_MAX 10
  39. #define BITFORCE_MAX_QRESULTS 16
  40. #define BITFORCE_GOAL_QRESULTS 5
  41. #define BITFORCE_MIN_QRESULT_WAIT BITFORCE_CHECK_INTERVAL_MS
  42. #define BITFORCE_MAX_QRESULT_WAIT 1000
  43. #define BITFORCE_MAX_BQUEUE_AT_ONCE 5
  44. enum bitforce_proto {
  45. BFP_WORK = 0,
  46. BFP_RANGE = 1,
  47. BFP_BQUEUE = 3,
  48. BFP_PQUEUE = 4,
  49. };
  50. static const char *protonames[] = {
  51. "full work",
  52. "nonce range",
  53. NULL,
  54. "bulk queue",
  55. "parallel queue",
  56. };
  57. BFG_REGISTER_DRIVER(bitforce_drv)
  58. BFG_REGISTER_DRIVER(bitforce_queue_api)
  59. // Code must deal with a timeout
  60. #define BFopen(devpath) serial_open(devpath, 0, 250, true)
  61. static void BFgets(char *buf, size_t bufLen, int fd)
  62. {
  63. char *obuf = buf;
  64. do {
  65. buf[0] = '\0';
  66. --bufLen;
  67. } while (likely(bufLen && read(fd, buf, 1) == 1 && (buf++)[0] != '\n'));
  68. buf[0] = '\0';
  69. if (unlikely(opt_dev_protocol))
  70. applog(LOG_DEBUG, "DEVPROTO: GETS (fd=%d): %s", fd, obuf);
  71. }
  72. static ssize_t BFwrite(int fd, const void *buf, ssize_t bufLen)
  73. {
  74. if ((bufLen) != write(fd, buf, bufLen))
  75. return 0;
  76. else
  77. return bufLen;
  78. }
  79. static ssize_t bitforce_send(int fd, int procid, const void *buf, ssize_t bufLen)
  80. {
  81. if (!procid)
  82. return BFwrite(fd, buf, bufLen);
  83. if (bufLen > 255)
  84. return -1;
  85. size_t bufLeft = bufLen + 3;
  86. char realbuf[bufLeft], *bufp;
  87. ssize_t rv;
  88. memcpy(&realbuf[3], buf, bufLen);
  89. realbuf[0] = '@';
  90. realbuf[1] = bufLen;
  91. realbuf[2] = procid;
  92. bufp = realbuf;
  93. do
  94. {
  95. rv = BFwrite(fd, bufp, bufLeft);
  96. if (rv <= 0)
  97. return rv;
  98. bufLeft -= rv;
  99. }
  100. while (bufLeft > 0);
  101. return bufLen;
  102. }
  103. static
  104. void bitforce_cmd1b(int fd, int procid, void *buf, size_t bufsz, const char *cmd, size_t cmdsz)
  105. {
  106. if (unlikely(opt_dev_protocol))
  107. applog(LOG_DEBUG, "DEVPROTO: CMD1 (fd=%d xlink=%d): %s", fd, procid, cmd);
  108. bitforce_send(fd, procid, cmd, cmdsz);
  109. BFgets(buf, bufsz, fd);
  110. }
  111. #define bitforce_cmd1(fd, xlinkid, buf, bufsz, cmd) bitforce_cmd1b(fd, xlinkid, buf, bufsz, cmd, 3)
  112. static
  113. void bitforce_cmd2(int fd, int procid, void *buf, size_t bufsz, const char *cmd, void *data, size_t datasz)
  114. {
  115. bitforce_cmd1(fd, procid, buf, bufsz, cmd);
  116. if (strncasecmp(buf, "OK", 2))
  117. return;
  118. if (unlikely(opt_dev_protocol))
  119. {
  120. char hex[(datasz * 2) + 1];
  121. bin2hex(hex, data, datasz);
  122. applog(LOG_DEBUG, "DEVPROTO: CMD2 (fd=%d xlink=%d): %s", fd, procid, hex);
  123. }
  124. bitforce_send(fd, procid, data, datasz);
  125. BFgets(buf, bufsz, fd);
  126. }
  127. #define BFclose(fd) serial_close(fd)
  128. enum bitforce_style {
  129. BFS_FPGA,
  130. BFS_65NM,
  131. };
  132. struct bitforce_init_data {
  133. enum bitforce_style style;
  134. long devmask;
  135. int *parallels;
  136. };
  137. static
  138. int bitforce_chips_to_plan_for(int parallel, int chipcount) {
  139. if (parallel < 1)
  140. return parallel;
  141. if (chipcount > 15) return 32;
  142. if (chipcount > 7) return 16;
  143. if (chipcount > 3) return 8;
  144. if (chipcount > 1) return 4;
  145. if (chipcount ) return 2;
  146. return 1;
  147. }
  148. static
  149. bool bitforce_lowl_match(const struct lowlevel_device_info * const info)
  150. {
  151. return lowlevel_match_product(info, "BitFORCE", "SHA256");
  152. }
  153. static bool bitforce_detect_one(const char *devpath)
  154. {
  155. int fdDev = serial_open(devpath, 0, 10, true);
  156. struct cgpu_info *bitforce;
  157. char pdevbuf[0x100];
  158. size_t pdevbuf_len;
  159. char *s;
  160. int procs = 1, parallel = -1;
  161. long maxchipno = 0;
  162. struct bitforce_init_data *initdata;
  163. char *manuf = NULL;
  164. applog(LOG_DEBUG, "BFL: Attempting to open %s", devpath);
  165. if (unlikely(fdDev == -1)) {
  166. applog(LOG_DEBUG, "BFL: Failed to open %s", devpath);
  167. return false;
  168. }
  169. bitforce_cmd1(fdDev, 0, pdevbuf, sizeof(pdevbuf), "ZGX");
  170. if (unlikely(!pdevbuf[0])) {
  171. applog(LOG_DEBUG, "BFL: Error reading/timeout (ZGX)");
  172. BFclose(fdDev);
  173. return 0;
  174. }
  175. if (unlikely(!strstr(pdevbuf, "SHA256"))) {
  176. applog(LOG_DEBUG, "BFL: Didn't recognise BitForce on %s", devpath);
  177. BFclose(fdDev);
  178. return false;
  179. }
  180. if (serial_claim_v(devpath, &bitforce_drv))
  181. {
  182. BFclose(fdDev);
  183. return false;
  184. }
  185. applog(LOG_DEBUG, "Found BitForce device on %s", devpath);
  186. initdata = malloc(sizeof(*initdata));
  187. *initdata = (struct bitforce_init_data){
  188. .style = BFS_FPGA,
  189. };
  190. bitforce_cmd1(fdDev, 0, pdevbuf, sizeof(pdevbuf), "ZCX");
  191. for (int i = 0; (!pdevbuf[0]) && i < 4; ++i)
  192. BFgets(pdevbuf, sizeof(pdevbuf), fdDev);
  193. for ( ;
  194. strncasecmp(pdevbuf, "OK", 2);
  195. BFgets(pdevbuf, sizeof(pdevbuf), fdDev) )
  196. {
  197. pdevbuf_len = strlen(pdevbuf);
  198. if (unlikely(!pdevbuf_len))
  199. continue;
  200. pdevbuf[pdevbuf_len-1] = '\0'; // trim newline
  201. applog(LOG_DEBUG, " %s", pdevbuf);
  202. if (!strncasecmp(pdevbuf, "PROCESSOR ", 10))
  203. maxchipno = max(maxchipno, atoi(&pdevbuf[10]));
  204. else
  205. if (!strncasecmp(pdevbuf, "DEVICES IN CHAIN:", 17))
  206. procs = atoi(&pdevbuf[17]);
  207. else
  208. if (!strncasecmp(pdevbuf, "CHAIN PRESENCE MASK:", 20))
  209. initdata->devmask = strtol(&pdevbuf[20], NULL, 16);
  210. else
  211. if (!strncasecmp(pdevbuf, "DEVICE:", 7) && strstr(pdevbuf, "SC"))
  212. initdata->style = BFS_65NM;
  213. else
  214. if (!strncasecmp(pdevbuf, "CHIP PARALLELIZATION: YES @", 27))
  215. parallel = atoi(&pdevbuf[27]);
  216. else
  217. if (!strncasecmp(pdevbuf, "MANUFACTURER:", 13))
  218. {
  219. manuf = &pdevbuf[13];
  220. while (manuf[0] && isspace(manuf[0]))
  221. ++manuf;
  222. if (manuf[0])
  223. manuf = strdup(manuf);
  224. else
  225. manuf = NULL;
  226. }
  227. }
  228. parallel = bitforce_chips_to_plan_for(parallel, maxchipno);
  229. initdata->parallels = malloc(sizeof(initdata->parallels[0]) * procs);
  230. initdata->parallels[0] = parallel;
  231. parallel = abs(parallel);
  232. for (int proc = 1; proc < procs; ++proc)
  233. {
  234. applog(LOG_DEBUG, "Slave board %d:", proc);
  235. initdata->parallels[proc] = -1;
  236. maxchipno = 0;
  237. bitforce_cmd1(fdDev, proc, pdevbuf, sizeof(pdevbuf), "ZCX");
  238. for (int i = 0; (!pdevbuf[0]) && i < 4; ++i)
  239. BFgets(pdevbuf, sizeof(pdevbuf), fdDev);
  240. for ( ;
  241. strncasecmp(pdevbuf, "OK", 2);
  242. BFgets(pdevbuf, sizeof(pdevbuf), fdDev) )
  243. {
  244. pdevbuf_len = strlen(pdevbuf);
  245. if (unlikely(!pdevbuf_len))
  246. continue;
  247. pdevbuf[pdevbuf_len-1] = '\0'; // trim newline
  248. applog(LOG_DEBUG, " %s", pdevbuf);
  249. if (!strncasecmp(pdevbuf, "PROCESSOR ", 10))
  250. maxchipno = max(maxchipno, atoi(&pdevbuf[10]));
  251. else
  252. if (!strncasecmp(pdevbuf, "CHIP PARALLELIZATION: YES @", 27))
  253. initdata->parallels[proc] = atoi(&pdevbuf[27]);
  254. }
  255. initdata->parallels[proc] = bitforce_chips_to_plan_for(initdata->parallels[proc], maxchipno);
  256. parallel += abs(initdata->parallels[proc]);
  257. }
  258. BFclose(fdDev);
  259. if (unlikely((procs != 1 || parallel != 1) && initdata->style == BFS_FPGA))
  260. {
  261. // Only bitforce_queue supports parallelization and XLINK, so force SC mode and hope for the best
  262. applog(LOG_WARNING, "SC features detected with non-SC device; this is not supported!");
  263. initdata->style = BFS_65NM;
  264. }
  265. // We have a real BitForce!
  266. bitforce = calloc(1, sizeof(*bitforce));
  267. bitforce->drv = &bitforce_drv;
  268. if (initdata->style != BFS_FPGA)
  269. bitforce->drv = &bitforce_queue_api;
  270. bitforce->device_path = strdup(devpath);
  271. if (manuf)
  272. bitforce->dev_manufacturer = manuf;
  273. bitforce->deven = DEV_ENABLED;
  274. bitforce->procs = parallel;
  275. bitforce->threads = 1;
  276. if (initdata->style != BFS_FPGA)
  277. bitforce->cutofftemp = 85;
  278. if (likely((!memcmp(pdevbuf, ">>>ID: ", 7)) && (s = strstr(pdevbuf + 3, ">>>")))) {
  279. s[0] = '\0';
  280. bitforce->name = strdup(pdevbuf + 7);
  281. }
  282. bitforce->device_data = initdata;
  283. mutex_init(&bitforce->device_mutex);
  284. return add_cgpu(bitforce);
  285. }
  286. static
  287. bool bitforce_lowl_probe(const struct lowlevel_device_info * const info)
  288. {
  289. return vcom_lowl_probe_wrapper(info, bitforce_detect_one);
  290. }
  291. struct bitforce_data {
  292. int xlink_id;
  293. unsigned char next_work_ob[70]; // Data aligned for 32-bit access
  294. unsigned char *next_work_obs; // Start of data to send
  295. unsigned char next_work_obsz;
  296. const char *next_work_cmd;
  297. char noncebuf[14 + ((BITFORCE_MAX_QRESULTS+1) * BITFORCE_QRESULT_LINE_LEN)];
  298. int poll_func;
  299. enum bitforce_proto proto;
  300. enum bitforce_style style;
  301. int queued;
  302. int queued_max;
  303. int parallel;
  304. bool parallel_protocol;
  305. bool missing_zwx;
  306. bool already_have_results;
  307. bool just_flushed;
  308. int ready_to_queue;
  309. bool want_to_send_queue;
  310. unsigned result_busy_polled;
  311. unsigned sleep_ms_default;
  312. struct timeval tv_hashmeter_start;
  313. float temp[2];
  314. long *volts;
  315. int volts_count;
  316. bool probed;
  317. bool supports_fanspeed;
  318. };
  319. struct bitforce_proc_data {
  320. struct cgpu_info *cgpu;
  321. bool handles_board; // The first processor handles the queue for the entire board
  322. };
  323. static void bitforce_clear_buffer(struct cgpu_info *);
  324. static
  325. void bitforce_comm_error(struct thr_info *thr)
  326. {
  327. struct cgpu_info *bitforce = thr->cgpu;
  328. struct bitforce_data *data = bitforce->device_data;
  329. int *p_fdDev = &bitforce->device->device_fd;
  330. data->noncebuf[0] = '\0';
  331. applog(LOG_ERR, "%"PRIpreprv": Comms error", bitforce->proc_repr);
  332. dev_error(bitforce, REASON_DEV_COMMS_ERROR);
  333. inc_hw_errors_only(thr);
  334. BFclose(*p_fdDev);
  335. int fd = *p_fdDev = BFopen(bitforce->device_path);
  336. if (fd == -1)
  337. {
  338. applog(LOG_ERR, "%s: Error reopening %s", bitforce->dev_repr, bitforce->device_path);
  339. return;
  340. }
  341. /* empty read buffer */
  342. bitforce_clear_buffer(bitforce);
  343. }
  344. static bool bitforce_thread_prepare(struct thr_info *thr)
  345. {
  346. struct cgpu_info *bitforce = thr->cgpu;
  347. int fdDev = BFopen(bitforce->device_path);
  348. if (unlikely(fdDev == -1)) {
  349. applog(LOG_ERR, "%s: Failed to open %s", bitforce->dev_repr, bitforce->device_path);
  350. return false;
  351. }
  352. bitforce->device_fd = fdDev;
  353. applog(LOG_INFO, "%s: Opened %s", bitforce->dev_repr, bitforce->device_path);
  354. return true;
  355. }
  356. static void __bitforce_clear_buffer(int fdDev)
  357. {
  358. char pdevbuf[0x100];
  359. int count = 0;
  360. do {
  361. pdevbuf[0] = '\0';
  362. BFgets(pdevbuf, sizeof(pdevbuf), fdDev);
  363. } while (pdevbuf[0] && (++count < 10));
  364. }
  365. static void bitforce_clear_buffer(struct cgpu_info *bitforce)
  366. {
  367. pthread_mutex_t *mutexp = &bitforce->device->device_mutex;
  368. int fdDev;
  369. mutex_lock(mutexp);
  370. fdDev = bitforce->device->device_fd;
  371. if (fdDev != -1)
  372. {
  373. applog(LOG_DEBUG, "%"PRIpreprv": Clearing read buffer", bitforce->proc_repr);
  374. __bitforce_clear_buffer(fdDev);
  375. }
  376. mutex_unlock(mutexp);
  377. }
  378. void work_list_del(struct work **head, struct work *);
  379. void bitforce_reinit(struct cgpu_info *bitforce)
  380. {
  381. struct bitforce_data *data = bitforce->device_data;
  382. struct thr_info *thr = bitforce->thr[0];
  383. struct bitforce_proc_data *procdata = thr->cgpu_data;
  384. const char *devpath = bitforce->device_path;
  385. pthread_mutex_t *mutexp = &bitforce->device->device_mutex;
  386. int *p_fdDev = &bitforce->device->device_fd;
  387. int fdDev, retries = 0;
  388. char pdevbuf[0x100];
  389. char *s;
  390. if (!procdata->handles_board)
  391. return;
  392. mutex_lock(mutexp);
  393. fdDev = *p_fdDev;
  394. applog(LOG_WARNING, "%"PRIpreprv": Re-initialising", bitforce->proc_repr);
  395. if (fdDev != -1) {
  396. BFclose(fdDev);
  397. cgsleep_ms(5000);
  398. *p_fdDev = -1;
  399. }
  400. fdDev = BFopen(devpath);
  401. if (unlikely(fdDev == -1)) {
  402. mutex_unlock(mutexp);
  403. applog(LOG_ERR, "%s: Failed to open %s", bitforce->dev_repr, devpath);
  404. return;
  405. }
  406. __bitforce_clear_buffer(fdDev);
  407. do {
  408. bitforce_cmd1(fdDev, 0, pdevbuf, sizeof(pdevbuf), "ZGX");
  409. if (unlikely(!pdevbuf[0])) {
  410. mutex_unlock(mutexp);
  411. BFclose(fdDev);
  412. applog(LOG_ERR, "%s: Error reading/timeout (ZGX)", bitforce->dev_repr);
  413. return;
  414. }
  415. if (retries++)
  416. cgsleep_ms(10);
  417. } while (strstr(pdevbuf, "BUSY") && (retries * 10 < BITFORCE_TIMEOUT_MS));
  418. if (unlikely(!strstr(pdevbuf, "SHA256"))) {
  419. mutex_unlock(mutexp);
  420. BFclose(fdDev);
  421. applog(LOG_ERR, "%s: Didn't recognise BitForce on %s returned: %s", bitforce->dev_repr, devpath, pdevbuf);
  422. return;
  423. }
  424. if (likely((!memcmp(pdevbuf, ">>>ID: ", 7)) && (s = strstr(pdevbuf + 3, ">>>")))) {
  425. s[0] = '\0';
  426. free((void*)bitforce->name);
  427. bitforce->name = strdup(pdevbuf + 7);
  428. }
  429. *p_fdDev = fdDev;
  430. bitforce->sleep_ms = data->sleep_ms_default;
  431. if (bitforce->drv == &bitforce_queue_api)
  432. {
  433. struct work *work, *tmp;
  434. timer_set_delay_from_now(&thr->tv_poll, 0);
  435. notifier_wake(thr->notifier);
  436. bitforce_cmd1(fdDev, data->xlink_id, pdevbuf, sizeof(pdevbuf), "ZQX");
  437. DL_FOREACH_SAFE(thr->work_list, work, tmp)
  438. work_list_del(&thr->work_list, work);
  439. data->queued = 0;
  440. data->ready_to_queue = 0;
  441. data->already_have_results = false;
  442. data->just_flushed = true;
  443. thr->queue_full = false;
  444. }
  445. mutex_unlock(mutexp);
  446. }
  447. static void bitforce_flash_led(struct cgpu_info *bitforce)
  448. {
  449. struct bitforce_data *data = bitforce->device_data;
  450. pthread_mutex_t *mutexp = &bitforce->device->device_mutex;
  451. int fdDev = bitforce->device->device_fd;
  452. if (fdDev == -1)
  453. return;
  454. /* Do not try to flash the led if we're polling for a result to
  455. * minimise the chance of interleaved results */
  456. if (bitforce->polling)
  457. return;
  458. /* It is not critical flashing the led so don't get stuck if we
  459. * can't grab the mutex here */
  460. if (mutex_trylock(mutexp))
  461. return;
  462. char pdevbuf[0x100];
  463. bitforce_cmd1(fdDev, data->xlink_id, pdevbuf, sizeof(pdevbuf), "ZMX");
  464. /* Once we've tried - don't do it until told to again */
  465. bitforce->flash_led = false;
  466. /* However, this stops anything else getting a reply
  467. * So best to delay any other access to the BFL */
  468. cgsleep_ms(4000);
  469. mutex_unlock(mutexp);
  470. return; // nothing is returned by the BFL
  471. }
  472. static
  473. float my_strtof(const char *nptr, char **endptr)
  474. {
  475. float f = strtof(nptr, endptr);
  476. /* Cope with older software that breaks and reads nonsense
  477. * values */
  478. if (f > 100)
  479. f = strtod(nptr, endptr);
  480. return f;
  481. }
  482. static
  483. void set_float_if_gt_zero(float *var, float value)
  484. {
  485. if (value > 0)
  486. *var = value;
  487. }
  488. static bool bitforce_get_temp(struct cgpu_info *bitforce)
  489. {
  490. struct bitforce_data *data = bitforce->device_data;
  491. pthread_mutex_t *mutexp = &bitforce->device->device_mutex;
  492. int fdDev = bitforce->device->device_fd;
  493. char pdevbuf[0x40];
  494. char voltbuf[0x40];
  495. char *s;
  496. struct cgpu_info *chip_cgpu;
  497. if (fdDev == -1)
  498. return false;
  499. /* Do not try to get the temperature if we're polling for a result to
  500. * minimise the chance of interleaved results */
  501. if (bitforce->polling)
  502. return true;
  503. // Flash instead of Temp - doing both can be too slow
  504. if (bitforce->flash_led) {
  505. bitforce_flash_led(bitforce);
  506. return true;
  507. }
  508. /* It is not critical getting temperature so don't get stuck if we
  509. * can't grab the mutex here */
  510. if (mutex_trylock(mutexp))
  511. return false;
  512. if (data->style != BFS_FPGA)
  513. {
  514. if (unlikely(!data->probed))
  515. {
  516. bitforce_cmd1(fdDev, data->xlink_id, voltbuf, sizeof(voltbuf), "Z9X");
  517. if (strncasecmp(voltbuf, "ERR", 3))
  518. data->supports_fanspeed = true;
  519. data->probed = true;
  520. }
  521. bitforce_cmd1(fdDev, data->xlink_id, voltbuf, sizeof(voltbuf), "ZTX");
  522. }
  523. bitforce_cmd1(fdDev, data->xlink_id, pdevbuf, sizeof(pdevbuf), "ZLX");
  524. mutex_unlock(mutexp);
  525. if (data->style != BFS_FPGA && likely(voltbuf[0]))
  526. {
  527. // Process voltage info
  528. // "NNNxxx,NNNxxx,NNNxxx"
  529. int n = 1;
  530. for (char *p = voltbuf; p[0]; ++p)
  531. if (p[0] == ',')
  532. ++n;
  533. long *out = malloc(sizeof(long) * n);
  534. if (!out)
  535. goto skipvolts;
  536. n = 0;
  537. char *saveptr, *v;
  538. for (v = strtok_r(voltbuf, ",", &saveptr); v; v = strtok_r(NULL, ",", &saveptr))
  539. out[n++] = strtol(v, NULL, 10);
  540. data->volts_count = 0;
  541. free(data->volts);
  542. data->volts = out;
  543. data->volts_count = n;
  544. }
  545. skipvolts:
  546. if (unlikely(!pdevbuf[0])) {
  547. struct thr_info *thr = bitforce->thr[0];
  548. applog(LOG_ERR, "%"PRIpreprv": Error: Get temp returned empty string/timed out", bitforce->proc_repr);
  549. inc_hw_errors_only(thr);
  550. return false;
  551. }
  552. if ((!strncasecmp(pdevbuf, "TEMP", 4)) && (s = strchr(pdevbuf + 4, ':'))) {
  553. float temp = my_strtof(s + 1, &s);
  554. set_float_if_gt_zero(&data->temp[0], temp);
  555. for ( ; s[0]; ++s)
  556. {
  557. if (!strncasecmp(s, "TEMP", 4) && (s = strchr(&s[4], ':')))
  558. {
  559. float temp2 = my_strtof(s + 1, &s);
  560. set_float_if_gt_zero(&data->temp[1], temp2);
  561. if (temp2 > temp)
  562. temp = temp2;
  563. }
  564. }
  565. if (temp > 0)
  566. {
  567. chip_cgpu = bitforce;
  568. for (int i = 0; i < data->parallel; ++i, (chip_cgpu = chip_cgpu->next_proc))
  569. chip_cgpu->temp = temp;
  570. }
  571. } else {
  572. struct thr_info *thr = bitforce->thr[0];
  573. /* Use the temperature monitor as a kind of watchdog for when
  574. * our responses are out of sync and flush the buffer to
  575. * hopefully recover */
  576. applog(LOG_WARNING, "%"PRIpreprv": Garbled response probably throttling, clearing buffer", bitforce->proc_repr);
  577. dev_error(bitforce, REASON_DEV_THROTTLE);
  578. /* Count throttling episodes as hardware errors */
  579. inc_hw_errors_only(thr);
  580. bitforce_clear_buffer(bitforce);
  581. return false;
  582. }
  583. return true;
  584. }
  585. static inline
  586. void dbg_block_data(struct cgpu_info *bitforce)
  587. {
  588. if (!opt_debug)
  589. return;
  590. struct bitforce_data *data = bitforce->device_data;
  591. char s[89];
  592. bin2hex(s, &data->next_work_ob[8], 44);
  593. applog(LOG_DEBUG, "%"PRIpreprv": block data: %s", bitforce->proc_repr, s);
  594. }
  595. static void bitforce_change_mode(struct cgpu_info *, enum bitforce_proto);
  596. static
  597. bool bitforce_job_prepare(struct thr_info *thr, struct work *work, __maybe_unused uint64_t max_nonce)
  598. {
  599. struct cgpu_info *bitforce = thr->cgpu;
  600. struct bitforce_data *data = bitforce->device_data;
  601. unsigned char *ob_ms = &data->next_work_ob[8];
  602. unsigned char *ob_dt = &ob_ms[32];
  603. // If polling job_start, cancel it
  604. if (data->poll_func == 1)
  605. {
  606. thr->tv_poll.tv_sec = -1;
  607. data->poll_func = 0;
  608. }
  609. memcpy(ob_ms, work->midstate, 32);
  610. memcpy(ob_dt, work->data + 64, 12);
  611. switch (data->proto)
  612. {
  613. case BFP_BQUEUE:
  614. quithere(1, "%"PRIpreprv": Impossible BFP_BQUEUE", bitforce->proc_repr);
  615. case BFP_PQUEUE:
  616. quithere(1, "%"PRIpreprv": Impossible BFP_PQUEUE", bitforce->proc_repr);
  617. case BFP_RANGE:
  618. {
  619. uint32_t *ob_nonce = (uint32_t*)&(ob_dt[32]);
  620. ob_nonce[0] = htobe32(work->blk.nonce);
  621. ob_nonce[1] = htobe32(work->blk.nonce + bitforce->nonces);
  622. // FIXME: if nonce range fails... we didn't increment enough
  623. work->blk.nonce += bitforce->nonces + 1;
  624. break;
  625. }
  626. case BFP_WORK:
  627. work->blk.nonce = 0xffffffff;
  628. }
  629. return true;
  630. }
  631. static
  632. void bitforce_change_mode(struct cgpu_info *bitforce, enum bitforce_proto proto)
  633. {
  634. struct bitforce_data *data = bitforce->device_data;
  635. if (data->proto == proto)
  636. return;
  637. if (data->proto == BFP_RANGE)
  638. {
  639. bitforce->nonces = 0xffffffff;
  640. bitforce->sleep_ms *= 5;
  641. data->sleep_ms_default *= 5;
  642. switch (proto)
  643. {
  644. case BFP_WORK:
  645. data->next_work_cmd = "ZDX";
  646. default:
  647. ;
  648. }
  649. if (data->style != BFS_FPGA)
  650. {
  651. // "S|---------- MidState ----------||-DataTail-|E"
  652. data->next_work_ob[7] = 45;
  653. data->next_work_ob[8+32+12] = '\xAA';
  654. data->next_work_obsz = 46;
  655. }
  656. else
  657. {
  658. // ">>>>>>>>|---------- MidState ----------||-DataTail-|>>>>>>>>"
  659. memset(&data->next_work_ob[8+32+12], '>', 8);
  660. data->next_work_obsz = 60;
  661. }
  662. }
  663. else
  664. if (proto == BFP_RANGE)
  665. {
  666. /* Split work up into 1/5th nonce ranges */
  667. bitforce->nonces = 0x33333332;
  668. bitforce->sleep_ms /= 5;
  669. data->sleep_ms_default /= 5;
  670. data->next_work_cmd = "ZPX";
  671. if (data->style != BFS_FPGA)
  672. {
  673. data->next_work_ob[7] = 53;
  674. data->next_work_obsz = 54;
  675. }
  676. else
  677. data->next_work_obsz = 68;
  678. }
  679. data->proto = proto;
  680. bitforce->kname = protonames[proto];
  681. }
  682. static
  683. void bitforce_job_start(struct thr_info *thr)
  684. {
  685. struct cgpu_info *bitforce = thr->cgpu;
  686. struct bitforce_data *data = bitforce->device_data;
  687. pthread_mutex_t *mutexp = &bitforce->device->device_mutex;
  688. int fdDev = bitforce->device->device_fd;
  689. unsigned char *ob = data->next_work_obs;
  690. char pdevbuf[0x100];
  691. struct timeval tv_now;
  692. data->result_busy_polled = 0;
  693. if (data->queued)
  694. {
  695. uint32_t delay;
  696. // get_results collected more accurate job start time
  697. mt_job_transition(thr);
  698. job_start_complete(thr);
  699. data->queued = 0;
  700. delay = (uint32_t)bitforce->sleep_ms * 1000;
  701. if (unlikely(data->already_have_results))
  702. delay = 0;
  703. timer_set_delay(&thr->tv_morework, &bitforce->work_start_tv, delay);
  704. return;
  705. }
  706. if (fdDev == -1)
  707. goto commerr;
  708. re_send:
  709. mutex_lock(mutexp);
  710. bitforce_cmd2(fdDev, data->xlink_id, pdevbuf, sizeof(pdevbuf), data->next_work_cmd, ob, data->next_work_obsz);
  711. if (!pdevbuf[0] || !strncasecmp(pdevbuf, "B", 1)) {
  712. mutex_unlock(mutexp);
  713. cgtime(&tv_now);
  714. timer_set_delay(&thr->tv_poll, &tv_now, WORK_CHECK_INTERVAL_MS * 1000);
  715. data->poll_func = 1;
  716. return;
  717. } else if (unlikely(strncasecmp(pdevbuf, "OK", 2))) {
  718. mutex_unlock(mutexp);
  719. switch (data->proto)
  720. {
  721. case BFP_RANGE:
  722. applog(LOG_WARNING, "%"PRIpreprv": Does not support nonce range, disabling", bitforce->proc_repr);
  723. bitforce_change_mode(bitforce, BFP_WORK);
  724. goto re_send;
  725. default:
  726. ;
  727. }
  728. applog(LOG_ERR, "%"PRIpreprv": Error: Send work reports: %s", bitforce->proc_repr, pdevbuf);
  729. goto commerr;
  730. }
  731. mt_job_transition(thr);
  732. mutex_unlock(mutexp);
  733. dbg_block_data(bitforce);
  734. cgtime(&tv_now);
  735. bitforce->work_start_tv = tv_now;
  736. timer_set_delay(&thr->tv_morework, &tv_now, bitforce->sleep_ms * 1000);
  737. job_start_complete(thr);
  738. return;
  739. commerr:
  740. bitforce_comm_error(thr);
  741. job_start_abort(thr, true);
  742. }
  743. static char _discardedbuf[0x10];
  744. static
  745. int bitforce_zox(struct thr_info *thr, const char *cmd)
  746. {
  747. struct cgpu_info *bitforce = thr->cgpu;
  748. struct bitforce_data *data = bitforce->device_data;
  749. pthread_mutex_t *mutexp = &bitforce->device->device_mutex;
  750. int fd = bitforce->device->device_fd;
  751. char *pdevbuf = &data->noncebuf[0];
  752. int count;
  753. mutex_lock(mutexp);
  754. bitforce_cmd1(fd, data->xlink_id, pdevbuf, sizeof(data->noncebuf), cmd);
  755. if (!strncasecmp(pdevbuf, "INPROCESS:", 10))
  756. BFgets(pdevbuf, sizeof(data->noncebuf), fd);
  757. if (!strncasecmp(pdevbuf, "COUNT:", 6))
  758. {
  759. count = atoi(&pdevbuf[6]);
  760. size_t cls = strlen(pdevbuf);
  761. char *pmorebuf = &pdevbuf[cls];
  762. size_t szleft = sizeof(data->noncebuf) - cls, sz;
  763. if (count && data->queued)
  764. cgtime(&bitforce->work_start_tv);
  765. while (true)
  766. {
  767. BFgets(pmorebuf, szleft, fd);
  768. if (!strncasecmp(pmorebuf, "OK", 2))
  769. {
  770. pmorebuf[0] = '\0'; // process expects only results
  771. break;
  772. }
  773. sz = strlen(pmorebuf);
  774. if (!sz)
  775. {
  776. applog(LOG_ERR, "%"PRIpreprv": Timeout during %s", bitforce->proc_repr, cmd);
  777. break;
  778. }
  779. szleft -= sz;
  780. pmorebuf += sz;
  781. if (unlikely(szleft < BITFORCE_QRESULT_LINE_LEN))
  782. {
  783. // Out of buffer space somehow :(
  784. applog(LOG_ERR, "%"PRIpreprv": Ran out of buffer space for results, discarding extra data", bitforce->proc_repr);
  785. pmorebuf = _discardedbuf;
  786. szleft = sizeof(_discardedbuf);
  787. }
  788. }
  789. }
  790. else
  791. count = -1;
  792. mutex_unlock(mutexp);
  793. return count;
  794. }
  795. static inline char *next_line(char *);
  796. static
  797. void bitforce_job_get_results(struct thr_info *thr, struct work *work)
  798. {
  799. struct cgpu_info *bitforce = thr->cgpu;
  800. struct bitforce_data *data = bitforce->device_data;
  801. int fdDev = bitforce->device->device_fd;
  802. unsigned int delay_time_ms;
  803. struct timeval elapsed;
  804. struct timeval now;
  805. char *pdevbuf = &data->noncebuf[0];
  806. bool stale;
  807. int count;
  808. cgtime(&now);
  809. timersub(&now, &bitforce->work_start_tv, &elapsed);
  810. bitforce->wait_ms = tv_to_ms(elapsed);
  811. bitforce->polling = true;
  812. if (fdDev == -1)
  813. goto commerr;
  814. stale = stale_work(work, true);
  815. if (unlikely(bitforce->wait_ms < bitforce->sleep_ms))
  816. {
  817. // We're likely here because of a work restart
  818. // Since Bitforce cannot stop a work without losing results, only do it if the current job is finding stale shares
  819. if (!stale)
  820. {
  821. delay_time_ms = bitforce->sleep_ms - bitforce->wait_ms;
  822. timer_set_delay(&thr->tv_poll, &now, delay_time_ms * 1000);
  823. data->poll_func = 2;
  824. return;
  825. }
  826. }
  827. while (1) {
  828. if (data->already_have_results)
  829. {
  830. data->already_have_results = false;
  831. strcpy(pdevbuf, "COUNT:0");
  832. count = 1;
  833. break;
  834. }
  835. const char * const cmd = "ZFX";
  836. count = bitforce_zox(thr, cmd);
  837. cgtime(&now);
  838. timersub(&now, &bitforce->work_start_tv, &elapsed);
  839. if (elapsed.tv_sec >= BITFORCE_LONG_TIMEOUT_S) {
  840. applog(LOG_ERR, "%"PRIpreprv": took %lums - longer than %lums", bitforce->proc_repr,
  841. tv_to_ms(elapsed), (unsigned long)BITFORCE_LONG_TIMEOUT_MS);
  842. goto out;
  843. }
  844. if (count > 0)
  845. {
  846. // Check that queue results match the current work
  847. // Also, if there are results from the next work, short-circuit this wait
  848. unsigned char midstate[32], datatail[12];
  849. char *p;
  850. int i;
  851. p = pdevbuf;
  852. for (i = 0; i < count; ++i)
  853. {
  854. p = next_line(p);
  855. hex2bin(midstate, p, 32);
  856. hex2bin(datatail, &p[65], 12);
  857. if (!(memcmp(work->midstate, midstate, 32) || memcmp(&work->data[64], datatail, 12)))
  858. break;
  859. }
  860. if (i == count)
  861. {
  862. // Didn't find the one we're waiting on
  863. // Must be extra stuff in the queue results
  864. char xmid[65];
  865. char xdt[25];
  866. bin2hex(xmid, work->midstate, 32);
  867. bin2hex(xdt, &work->data[64], 12);
  868. applog(LOG_WARNING, "%"PRIpreprv": Found extra garbage in queue results: %s",
  869. bitforce->proc_repr, pdevbuf);
  870. applog(LOG_WARNING, "%"PRIpreprv": ...while waiting on: %s,%s",
  871. bitforce->proc_repr, xmid, xdt);
  872. count = 0;
  873. }
  874. else
  875. if (i == count - 1)
  876. // Last one found is what we're looking for
  877. {}
  878. else
  879. // We finished the next job too!
  880. data->already_have_results = true;
  881. }
  882. if (!count)
  883. goto noqr;
  884. if (pdevbuf[0] && strncasecmp(pdevbuf, "B", 1)) /* BFL does not respond during throttling */
  885. break;
  886. data->result_busy_polled = bitforce->wait_ms;
  887. if (stale)
  888. {
  889. applog(LOG_NOTICE, "%"PRIpreprv": Abandoning stale search to restart",
  890. bitforce->proc_repr);
  891. goto out;
  892. }
  893. noqr:
  894. data->result_busy_polled = bitforce->wait_ms;
  895. /* if BFL is throttling, no point checking so quickly */
  896. delay_time_ms = (pdevbuf[0] ? BITFORCE_CHECK_INTERVAL_MS : 2 * WORK_CHECK_INTERVAL_MS);
  897. timer_set_delay(&thr->tv_poll, &now, delay_time_ms * 1000);
  898. data->poll_func = 2;
  899. return;
  900. }
  901. if (count < 0 && pdevbuf[0] == 'N')
  902. count = strncasecmp(pdevbuf, "NONCE-FOUND", 11) ? 1 : 0;
  903. // At this point, 'count' is:
  904. // negative, in case of some kind of error
  905. // zero, if NO-NONCE (FPGA either completed with no results, or rebooted)
  906. // positive, if at least one job completed successfully
  907. if (elapsed.tv_sec > BITFORCE_TIMEOUT_S) {
  908. applog(LOG_ERR, "%"PRIpreprv": took %lums - longer than %lums", bitforce->proc_repr,
  909. tv_to_ms(elapsed), (unsigned long)BITFORCE_TIMEOUT_MS);
  910. dev_error(bitforce, REASON_DEV_OVER_HEAT);
  911. inc_hw_errors_only(thr);
  912. /* If the device truly throttled, it didn't process the job and there
  913. * are no results. But check first, just in case we're wrong about it
  914. * throttling.
  915. */
  916. if (count > 0)
  917. goto out;
  918. } else if (count >= 0) {/* Hashing complete (NONCE-FOUND or NO-NONCE) */
  919. /* Simple timing adjustment. Allow a few polls to cope with
  920. * OS timer delays being variably reliable. wait_ms will
  921. * always equal sleep_ms when we've waited greater than or
  922. * equal to the result return time.*/
  923. delay_time_ms = bitforce->sleep_ms;
  924. if (!data->result_busy_polled)
  925. {
  926. // No busy polls before results received
  927. if (bitforce->wait_ms > delay_time_ms + (WORK_CHECK_INTERVAL_MS * 8))
  928. // ... due to poll being rather late; ignore it as an anomaly
  929. applog(LOG_DEBUG, "%"PRIpreprv": Got results on first poll after %ums, later than scheduled %ums (ignoring)",
  930. bitforce->proc_repr, bitforce->wait_ms, delay_time_ms);
  931. else
  932. if (bitforce->sleep_ms > data->sleep_ms_default + (BITFORCE_CHECK_INTERVAL_MS * 0x20))
  933. {
  934. applog(LOG_DEBUG, "%"PRIpreprv": Got results on first poll after %ums, on delayed schedule %ums; Wait time changed to: %ums (default sch)",
  935. bitforce->proc_repr, bitforce->wait_ms, delay_time_ms, data->sleep_ms_default);
  936. bitforce->sleep_ms = data->sleep_ms_default;
  937. }
  938. else
  939. {
  940. applog(LOG_DEBUG, "%"PRIpreprv": Got results on first poll after %ums, on default schedule %ums; Wait time changed to: %ums (check interval)",
  941. bitforce->proc_repr, bitforce->wait_ms, delay_time_ms, BITFORCE_CHECK_INTERVAL_MS);
  942. bitforce->sleep_ms = BITFORCE_CHECK_INTERVAL_MS;
  943. }
  944. }
  945. else
  946. {
  947. if (data->result_busy_polled - bitforce->sleep_ms > WORK_CHECK_INTERVAL_MS)
  948. {
  949. bitforce->sleep_ms = data->result_busy_polled - (WORK_CHECK_INTERVAL_MS / 2);
  950. applog(LOG_DEBUG, "%"PRIpreprv": Got results on Nth poll after %ums (busy poll at %ums, sch'd %ums); Wait time changed to: %ums",
  951. bitforce->proc_repr, bitforce->wait_ms, data->result_busy_polled, delay_time_ms, bitforce->sleep_ms);
  952. }
  953. else
  954. applog(LOG_DEBUG, "%"PRIpreprv": Got results on Nth poll after %ums (busy poll at %ums, sch'd %ums); Wait time unchanged",
  955. bitforce->proc_repr, bitforce->wait_ms, data->result_busy_polled, delay_time_ms);
  956. }
  957. /* Work out the average time taken. Float for calculation, uint for display */
  958. bitforce->avg_wait_f += (tv_to_ms(elapsed) - bitforce->avg_wait_f) / TIME_AVG_CONSTANT;
  959. bitforce->avg_wait_d = (unsigned int) (bitforce->avg_wait_f + 0.5);
  960. }
  961. applog(LOG_DEBUG, "%"PRIpreprv": waited %dms until %s", bitforce->proc_repr, bitforce->wait_ms, pdevbuf);
  962. if (count < 0 && strncasecmp(pdevbuf, "I", 1)) {
  963. inc_hw_errors_only(thr);
  964. applog(LOG_WARNING, "%"PRIpreprv": Error: Get result reports: %s", bitforce->proc_repr, pdevbuf);
  965. bitforce_clear_buffer(bitforce);
  966. }
  967. out:
  968. bitforce->polling = false;
  969. job_results_fetched(thr);
  970. return;
  971. commerr:
  972. bitforce_comm_error(thr);
  973. goto out;
  974. }
  975. static
  976. void bitforce_process_result_nonces(struct thr_info *thr, struct work *work, char *pnoncebuf)
  977. {
  978. struct cgpu_info *bitforce = thr->cgpu;
  979. struct bitforce_data *data = bitforce->device_data;
  980. uint32_t nonce;
  981. while (1) {
  982. hex2bin((void*)&nonce, pnoncebuf, 4);
  983. nonce = be32toh(nonce);
  984. if (unlikely(data->proto == BFP_RANGE && (nonce >= work->blk.nonce ||
  985. /* FIXME: blk.nonce is probably moved on quite a bit now! */
  986. (work->blk.nonce > 0 && nonce < work->blk.nonce - bitforce->nonces - 1)))) {
  987. applog(LOG_WARNING, "%"PRIpreprv": Disabling broken nonce range support", bitforce->proc_repr);
  988. bitforce_change_mode(bitforce, BFP_WORK);
  989. }
  990. submit_nonce(thr, work, nonce);
  991. if (strncmp(&pnoncebuf[8], ",", 1))
  992. break;
  993. pnoncebuf += 9;
  994. }
  995. }
  996. static
  997. bool bitforce_process_qresult_line_i(struct thr_info *thr, char *midstate, char *datatail, char *buf, struct work *work)
  998. {
  999. if (!work)
  1000. return false;
  1001. if (memcmp(work->midstate, midstate, 32))
  1002. return false;
  1003. if (memcmp(&work->data[64], datatail, 12))
  1004. return false;
  1005. char *end;
  1006. if (strtol(&buf[90], &end, 10))
  1007. bitforce_process_result_nonces(thr, work, &end[1]);
  1008. return true;
  1009. }
  1010. static
  1011. void bitforce_process_qresult_line(struct thr_info *thr, char *buf, struct work *work)
  1012. {
  1013. struct cgpu_info *bitforce = thr->cgpu;
  1014. char midstate[32], datatail[12];
  1015. hex2bin((void*)midstate, buf, 32);
  1016. hex2bin((void*)datatail, &buf[65], 12);
  1017. if (!( bitforce_process_qresult_line_i(thr, midstate, datatail, buf, work)
  1018. || bitforce_process_qresult_line_i(thr, midstate, datatail, buf, thr->work)
  1019. || bitforce_process_qresult_line_i(thr, midstate, datatail, buf, thr->prev_work)
  1020. || bitforce_process_qresult_line_i(thr, midstate, datatail, buf, thr->next_work) ))
  1021. {
  1022. applog(LOG_ERR, "%"PRIpreprv": Failed to find work for queued results", bitforce->proc_repr);
  1023. inc_hw_errors_only(thr);
  1024. }
  1025. }
  1026. static inline
  1027. char *next_line(char *in)
  1028. {
  1029. while (in[0] && (in++)[0] != '\n')
  1030. {}
  1031. return in;
  1032. }
  1033. static
  1034. int64_t bitforce_job_process_results(struct thr_info *thr, struct work *work, __maybe_unused bool stopping)
  1035. {
  1036. struct cgpu_info *bitforce = thr->cgpu;
  1037. struct bitforce_data *data = bitforce->device_data;
  1038. char *pnoncebuf = &data->noncebuf[0];
  1039. int count;
  1040. if (!strncasecmp(pnoncebuf, "NO-", 3))
  1041. return bitforce->nonces; /* No valid nonce found */
  1042. if (!strncasecmp(pnoncebuf, "NONCE-FOUND", 11))
  1043. {
  1044. bitforce_process_result_nonces(thr, work, &pnoncebuf[12]);
  1045. count = 1;
  1046. }
  1047. else
  1048. if (!strncasecmp(pnoncebuf, "COUNT:", 6))
  1049. {
  1050. count = 0;
  1051. pnoncebuf = next_line(pnoncebuf);
  1052. while (pnoncebuf[0])
  1053. {
  1054. bitforce_process_qresult_line(thr, pnoncebuf, work);
  1055. ++count;
  1056. pnoncebuf = next_line(pnoncebuf);
  1057. }
  1058. }
  1059. else
  1060. return 0;
  1061. // FIXME: This might have changed in the meantime (new job start, or broken)
  1062. return bitforce->nonces * count;
  1063. }
  1064. static void bitforce_shutdown(struct thr_info *thr)
  1065. {
  1066. struct cgpu_info *bitforce = thr->cgpu;
  1067. int *p_fdDev = &bitforce->device->device_fd;
  1068. BFclose(*p_fdDev);
  1069. *p_fdDev = -1;
  1070. }
  1071. static void biforce_thread_enable(struct thr_info *thr)
  1072. {
  1073. struct cgpu_info *bitforce = thr->cgpu;
  1074. bitforce_reinit(bitforce);
  1075. }
  1076. static bool bitforce_get_stats(struct cgpu_info *bitforce)
  1077. {
  1078. struct bitforce_proc_data *procdata = bitforce->thr[0]->cgpu_data;
  1079. if (!procdata->handles_board)
  1080. return true;
  1081. return bitforce_get_temp(bitforce);
  1082. }
  1083. static bool bitforce_identify(struct cgpu_info *bitforce)
  1084. {
  1085. bitforce->flash_led = true;
  1086. return true;
  1087. }
  1088. static bool bitforce_thread_init(struct thr_info *thr)
  1089. {
  1090. struct cgpu_info *bitforce = thr->cgpu;
  1091. unsigned int wait;
  1092. struct bitforce_data *data;
  1093. struct bitforce_proc_data *procdata;
  1094. struct bitforce_init_data *initdata = bitforce->device_data;
  1095. const enum bitforce_style style = initdata->style;
  1096. int xlink_id = 0, boardno = 0;
  1097. struct bitforce_proc_data *first_on_this_board;
  1098. char buf[100];
  1099. int fd = bitforce->device_fd;
  1100. for ( ; bitforce; bitforce = bitforce->next_proc)
  1101. {
  1102. thr = bitforce->thr[0];
  1103. if (unlikely(xlink_id > 30))
  1104. {
  1105. applog(LOG_ERR, "%"PRIpreprv": Failed to find XLINK address", bitforce->proc_repr);
  1106. dev_error(bitforce, REASON_THREAD_FAIL_INIT);
  1107. bitforce->reinit_backoff = 1e10;
  1108. continue;
  1109. }
  1110. bitforce->sleep_ms = BITFORCE_SLEEP_MS;
  1111. bitforce->device_data = data = malloc(sizeof(*data));
  1112. *data = (struct bitforce_data){
  1113. .xlink_id = xlink_id,
  1114. .next_work_ob = ">>>>>>>>|---------- MidState ----------||-DataTail-||Nonces|>>>>>>>>",
  1115. .proto = BFP_RANGE,
  1116. .style = style,
  1117. .sleep_ms_default = BITFORCE_SLEEP_MS,
  1118. .parallel = abs(initdata->parallels[boardno]),
  1119. .parallel_protocol = (initdata->parallels[boardno] != -1),
  1120. };
  1121. thr->cgpu_data = procdata = malloc(sizeof(*procdata));
  1122. *procdata = (struct bitforce_proc_data){
  1123. .handles_board = true,
  1124. .cgpu = bitforce,
  1125. };
  1126. if (style != BFS_FPGA)
  1127. {
  1128. // ".......S|---------- MidState ----------||-DataTail-||Nonces|E"
  1129. data->next_work_ob[8+32+12+8] = '\xAA';
  1130. data->next_work_obs = &data->next_work_ob[7];
  1131. if (bitforce->drv == &bitforce_queue_api)
  1132. {
  1133. bitforce_change_mode(bitforce, data->parallel_protocol ? BFP_PQUEUE : BFP_BQUEUE);
  1134. bitforce->sleep_ms = data->sleep_ms_default = 100;
  1135. timer_set_delay_from_now(&thr->tv_poll, 0);
  1136. data->queued_max = data->parallel * 2;
  1137. if (data->queued_max < BITFORCE_MIN_QUEUED_MAX)
  1138. data->queued_max = BITFORCE_MIN_QUEUED_MAX;
  1139. if (data->queued_max > BITFORCE_MAX_QUEUED_MAX)
  1140. data->queued_max = BITFORCE_MAX_QUEUED_MAX;
  1141. }
  1142. else
  1143. bitforce_change_mode(bitforce, BFP_WORK);
  1144. // Clear job queue to start fresh; ignore response
  1145. bitforce_cmd1(fd, data->xlink_id, buf, sizeof(buf), "ZQX");
  1146. }
  1147. else
  1148. {
  1149. data->next_work_obs = &data->next_work_ob[0];
  1150. // Unconditionally change away from cold-initialized BFP_RANGE, to allow for setting up other variables
  1151. bitforce_change_mode(bitforce, BFP_WORK);
  1152. /* Initially enable support for nonce range and disable it later if it
  1153. * fails */
  1154. if (opt_bfl_noncerange)
  1155. bitforce_change_mode(bitforce, BFP_RANGE);
  1156. }
  1157. bitforce->status = LIFE_INIT2;
  1158. first_on_this_board = procdata;
  1159. for (int proc = 1; proc < data->parallel; ++proc)
  1160. {
  1161. bitforce = bitforce->next_proc;
  1162. assert(bitforce);
  1163. thr = bitforce->thr[0];
  1164. thr->queue_full = true;
  1165. thr->cgpu_data = procdata = malloc(sizeof(*procdata));
  1166. *procdata = *first_on_this_board;
  1167. procdata->handles_board = false;
  1168. procdata->cgpu = bitforce;
  1169. bitforce->device_data = data;
  1170. bitforce->status = LIFE_INIT2;
  1171. bitforce->kname = first_on_this_board->cgpu->kname;
  1172. }
  1173. applog(LOG_DEBUG, "%s: Board %d: %"PRIpreprv"-%"PRIpreprv, bitforce->dev_repr, boardno, first_on_this_board->cgpu->proc_repr, bitforce->proc_repr);
  1174. ++boardno;
  1175. while (xlink_id < 31 && !(initdata->devmask & (1 << ++xlink_id)))
  1176. {}
  1177. }
  1178. // NOTE: This doesn't restore the first processor, but it does get us the last one; this is sufficient for the delay debug and start of the next loop below
  1179. bitforce = thr->cgpu;
  1180. free(initdata->parallels);
  1181. free(initdata);
  1182. /* Pause each new thread at least 100ms between initialising
  1183. * so the devices aren't making calls all at the same time. */
  1184. wait = thr->id * MAX_START_DELAY_MS;
  1185. applog(LOG_DEBUG, "%s: Delaying start by %dms", bitforce->dev_repr, wait / 1000);
  1186. cgsleep_ms(wait);
  1187. if (style != BFS_FPGA)
  1188. {
  1189. // Clear results queue last, to start fresh; ignore response
  1190. for (bitforce = bitforce->device; bitforce; bitforce = bitforce->next_proc)
  1191. bitforce_zox(thr, "ZOX");
  1192. }
  1193. return true;
  1194. }
  1195. #ifdef HAVE_CURSES
  1196. static
  1197. void bitforce_tui_wlogprint_choices(struct cgpu_info *cgpu)
  1198. {
  1199. struct bitforce_data *data = cgpu->device_data;
  1200. if (data->supports_fanspeed)
  1201. wlogprint("[F]an control ");
  1202. }
  1203. static
  1204. const char *bitforce_tui_handle_choice(struct cgpu_info *cgpu, int input)
  1205. {
  1206. struct bitforce_data *data = cgpu->device_data;
  1207. pthread_mutex_t *mutexp;
  1208. int fd;
  1209. static char replybuf[0x100];
  1210. if (!data->supports_fanspeed)
  1211. return NULL;
  1212. switch (input)
  1213. {
  1214. case 'f': case 'F':
  1215. {
  1216. int fanspeed;
  1217. char *intvar;
  1218. intvar = curses_input("Set fan speed (range 0-5 for low to fast or 9 for auto)");
  1219. if (!intvar)
  1220. return "Invalid fan speed\n";
  1221. fanspeed = atoi(intvar);
  1222. free(intvar);
  1223. if ((fanspeed < 0 || fanspeed > 5) && fanspeed != 9)
  1224. return "Invalid fan speed\n";
  1225. char cmd[4] = "Z0X";
  1226. cmd[1] += fanspeed;
  1227. mutexp = &cgpu->device->device_mutex;
  1228. mutex_lock(mutexp);
  1229. fd = cgpu->device->device_fd;
  1230. bitforce_cmd1(fd, data->xlink_id, replybuf, sizeof(replybuf), cmd);
  1231. mutex_unlock(mutexp);
  1232. return replybuf;
  1233. }
  1234. }
  1235. return NULL;
  1236. }
  1237. static
  1238. void bitforce_wlogprint_status(struct cgpu_info *cgpu)
  1239. {
  1240. struct bitforce_data *data = cgpu->device_data;
  1241. if (data->temp[0] > 0 && data->temp[1] > 0)
  1242. wlogprint("Temperatures: %4.1fC %4.1fC\n", data->temp[0], data->temp[1]);
  1243. if (data->volts_count)
  1244. {
  1245. // -> "NNN.xxx / NNN.xxx / NNN.xxx"
  1246. size_t sz = (data->volts_count * 10) + 1;
  1247. char buf[sz];
  1248. char *s = buf;
  1249. int rv = 0;
  1250. for (int i = 0; i < data->volts_count; ++i)
  1251. {
  1252. long v = data->volts[i];
  1253. _SNP("%ld.%03d / ", v / 1000, (int)(v % 1000));
  1254. }
  1255. if (rv >= 3 && s[-2] == '/')
  1256. s[-3] = '\0';
  1257. wlogprint("Voltages: %s\n", buf);
  1258. }
  1259. }
  1260. #endif
  1261. static struct api_data *bitforce_drv_stats(struct cgpu_info *cgpu)
  1262. {
  1263. struct bitforce_data *data = cgpu->device_data;
  1264. struct api_data *root = NULL;
  1265. // Warning, access to these is not locked - but we don't really
  1266. // care since hashing performance is way more important than
  1267. // locking access to displaying API debug 'stats'
  1268. // If locking becomes an issue for any of them, use copy_data=true also
  1269. root = api_add_uint(root, "Sleep Time", &(cgpu->sleep_ms), false);
  1270. if (data->proto != BFP_BQUEUE && data->proto != BFP_PQUEUE)
  1271. root = api_add_uint(root, "Avg Wait", &(cgpu->avg_wait_d), false);
  1272. if (data->temp[0] > 0 && data->temp[1] > 0)
  1273. {
  1274. root = api_add_temp(root, "Temperature0", &(data->temp[0]), false);
  1275. root = api_add_temp(root, "Temperature1", &(data->temp[1]), false);
  1276. }
  1277. for (int i = 0; i < data->volts_count; ++i)
  1278. {
  1279. float voltage = data->volts[i];
  1280. char key[] = "VoltageNN";
  1281. snprintf(&key[7], 3, "%d", i);
  1282. voltage /= 1e3;
  1283. root = api_add_volts(root, key, &voltage, true);
  1284. }
  1285. return root;
  1286. }
  1287. void bitforce_poll(struct thr_info *thr)
  1288. {
  1289. struct cgpu_info *bitforce = thr->cgpu;
  1290. struct bitforce_data *data = bitforce->device_data;
  1291. int poll = data->poll_func;
  1292. thr->tv_poll.tv_sec = -1;
  1293. data->poll_func = 0;
  1294. switch (poll)
  1295. {
  1296. case 1:
  1297. bitforce_job_start(thr);
  1298. break;
  1299. case 2:
  1300. bitforce_job_get_results(thr, thr->work);
  1301. break;
  1302. default:
  1303. applog(LOG_ERR, "%"PRIpreprv": Unexpected poll from device API!", thr->cgpu->proc_repr);
  1304. }
  1305. }
  1306. static
  1307. char *bitforce_set_device(struct cgpu_info *proc, char *option, char *setting, char *replybuf)
  1308. {
  1309. struct bitforce_data *data = proc->device_data;
  1310. pthread_mutex_t *mutexp = &proc->device->device_mutex;
  1311. int fd;
  1312. if (!strcasecmp(option, "help"))
  1313. {
  1314. sprintf(replybuf, "fanmode: range 0-5 (low to fast) or 9 (auto)");
  1315. return replybuf;
  1316. }
  1317. if (!strcasecmp(option, "fanmode"))
  1318. {
  1319. if (!data->supports_fanspeed)
  1320. {
  1321. sprintf(replybuf, "fanmode not supported");
  1322. return replybuf;
  1323. }
  1324. if (!setting || !*setting)
  1325. {
  1326. sprintf(replybuf, "missing fanmode setting");
  1327. return replybuf;
  1328. }
  1329. if (setting[1] || ((setting[0] < '0' || setting[0] > '5') && setting[0] != '9'))
  1330. {
  1331. sprintf(replybuf, "invalid fanmode setting");
  1332. return replybuf;
  1333. }
  1334. char cmd[4] = "Z5X";
  1335. cmd[1] = setting[0];
  1336. mutex_lock(mutexp);
  1337. fd = proc->device->device_fd;
  1338. bitforce_cmd1(fd, data->xlink_id, replybuf, 256, cmd);
  1339. mutex_unlock(mutexp);
  1340. return replybuf;
  1341. }
  1342. if (!strcasecmp(option, "_cmd1"))
  1343. {
  1344. mutex_lock(mutexp);
  1345. fd = proc->device->device_fd;
  1346. bitforce_cmd1b(fd, data->xlink_id, replybuf, 8000, setting, strlen(setting));
  1347. mutex_unlock(mutexp);
  1348. return replybuf;
  1349. }
  1350. sprintf(replybuf, "Unknown option: %s", option);
  1351. return replybuf;
  1352. }
  1353. struct device_drv bitforce_drv = {
  1354. .dname = "bitforce",
  1355. .name = "BFL",
  1356. .lowl_match = bitforce_lowl_match,
  1357. .lowl_probe = bitforce_lowl_probe,
  1358. #ifdef HAVE_CURSES
  1359. .proc_wlogprint_status = bitforce_wlogprint_status,
  1360. .proc_tui_wlogprint_choices = bitforce_tui_wlogprint_choices,
  1361. .proc_tui_handle_choice = bitforce_tui_handle_choice,
  1362. #endif
  1363. .get_api_stats = bitforce_drv_stats,
  1364. .minerloop = minerloop_async,
  1365. .reinit_device = bitforce_reinit,
  1366. .get_stats = bitforce_get_stats,
  1367. .set_device = bitforce_set_device,
  1368. .identify_device = bitforce_identify,
  1369. .thread_prepare = bitforce_thread_prepare,
  1370. .thread_init = bitforce_thread_init,
  1371. .job_prepare = bitforce_job_prepare,
  1372. .job_start = bitforce_job_start,
  1373. .job_get_results = bitforce_job_get_results,
  1374. .poll = bitforce_poll,
  1375. .job_process_results = bitforce_job_process_results,
  1376. .thread_shutdown = bitforce_shutdown,
  1377. .thread_enable = biforce_thread_enable
  1378. };
  1379. static inline
  1380. void bitforce_set_queue_full(struct thr_info *thr)
  1381. {
  1382. struct cgpu_info *bitforce = thr->cgpu;
  1383. struct bitforce_data *data = bitforce->device_data;
  1384. thr->queue_full = (data->queued + data->ready_to_queue >= data->queued_max) || (data->ready_to_queue >= BITFORCE_MAX_BQUEUE_AT_ONCE);
  1385. }
  1386. static
  1387. bool bitforce_send_queue(struct thr_info *thr)
  1388. {
  1389. struct cgpu_info *bitforce = thr->cgpu;
  1390. struct bitforce_data *data = bitforce->device_data;
  1391. pthread_mutex_t *mutexp = &bitforce->device->device_mutex;
  1392. int fd = bitforce->device->device_fd;
  1393. struct work *work;
  1394. if (unlikely(!(fd != -1 && data->ready_to_queue)))
  1395. return false;
  1396. char buf[0x100];
  1397. int queued_ok;
  1398. size_t qjs_sz = (32 + 12 + 2);
  1399. size_t qjp_sz = 4 + (qjs_sz * data->ready_to_queue);
  1400. uint8_t qjp[qjp_sz], *qjs;
  1401. qjp[0] = qjp_sz - 1;
  1402. qjp[1] = 0xc1;
  1403. qjp[2] = data->ready_to_queue;
  1404. qjp[qjp_sz - 1] = 0xfe;
  1405. qjs = &qjp[qjp_sz - 1];
  1406. work = thr->work_list->prev;
  1407. for (int i = data->ready_to_queue; i > 0; --i, work = work->prev)
  1408. {
  1409. *(--qjs) = 0xaa;
  1410. memcpy(qjs -= 12, work->data + 64, 12);
  1411. memcpy(qjs -= 32, work->midstate, 32);
  1412. *(--qjs) = 45;
  1413. }
  1414. retry:
  1415. mutex_lock(mutexp);
  1416. if (data->missing_zwx)
  1417. bitforce_cmd2(fd, data->xlink_id, buf, sizeof(buf), "ZNX", &qjp[3], qjp_sz - 4);
  1418. else
  1419. bitforce_cmd2(fd, data->xlink_id, buf, sizeof(buf), "ZWX", qjp, qjp_sz);
  1420. mutex_unlock(mutexp);
  1421. if (!strncasecmp(buf, "ERR:QUEUE", 9))
  1422. {
  1423. // Queue full :(
  1424. applog(LOG_DEBUG, "%"PRIpreprv": Device queue full while attempting to append %d jobs (queued<=%d)",
  1425. bitforce->proc_repr,
  1426. data->ready_to_queue, data->queued);
  1427. thr->queue_full = true;
  1428. return false;
  1429. }
  1430. if (strncasecmp(buf, "OK:QUEUED", 9))
  1431. {
  1432. if ((!strncasecmp(buf, "ERROR: UNKNOWN", 11)) && !data->missing_zwx)
  1433. {
  1434. applog(LOG_DEBUG, "%"PRIpreprv": Missing ZWX command, trying ZNX",
  1435. bitforce->proc_repr);
  1436. data->missing_zwx = true;
  1437. goto retry;
  1438. }
  1439. applog(LOG_DEBUG, "%"PRIpreprv": Unexpected error attempting to append %d jobs (queued<=%d): %s",
  1440. bitforce->proc_repr,
  1441. data->ready_to_queue, data->queued, buf);
  1442. return false;
  1443. }
  1444. if (!data->queued)
  1445. cgtime(&data->tv_hashmeter_start);
  1446. if (data->missing_zwx)
  1447. queued_ok = 1;
  1448. else
  1449. queued_ok = atoi(&buf[9]);
  1450. data->queued += queued_ok;
  1451. applog(LOG_DEBUG, "%"PRIpreprv": Successfully queued %d/%d jobs on device (queued<=%d)",
  1452. bitforce->proc_repr,
  1453. queued_ok, data->ready_to_queue, data->queued);
  1454. data->ready_to_queue -= queued_ok;
  1455. if (!data->missing_zwx)
  1456. thr->queue_full = data->ready_to_queue;
  1457. data->just_flushed = false;
  1458. data->want_to_send_queue = false;
  1459. return true;
  1460. }
  1461. void work_list_del(struct work **head, struct work *work)
  1462. {
  1463. DL_DELETE(*head, work);
  1464. free_work(work);
  1465. }
  1466. static
  1467. bool bitforce_queue_do_results(struct thr_info *thr)
  1468. {
  1469. struct cgpu_info *bitforce = thr->cgpu;
  1470. struct bitforce_data *data = bitforce->device_data;
  1471. int fd = bitforce->device->device_fd;
  1472. int count;
  1473. int fcount;
  1474. char *noncebuf, *buf, *end;
  1475. unsigned char midstate[32], datatail[12];
  1476. struct work *work, *tmpwork, *thiswork;
  1477. struct timeval tv_now, tv_elapsed;
  1478. long chipno = 0; // Initialized value is used for non-parallelized boards
  1479. struct cgpu_info *chip_cgpu;
  1480. struct thr_info *chip_thr;
  1481. int counts[data->parallel];
  1482. if (unlikely(fd == -1))
  1483. return false;
  1484. again:
  1485. noncebuf = &data->noncebuf[0];
  1486. count = bitforce_zox(thr, "ZOX");
  1487. if (unlikely(count < 0))
  1488. {
  1489. applog(LOG_ERR, "%"PRIpreprv": Received unexpected queue result response: %s", bitforce->proc_repr, noncebuf);
  1490. inc_hw_errors_only(thr);
  1491. return false;
  1492. }
  1493. applog(LOG_DEBUG, "%"PRIpreprv": Received %d queue results on poll (max=%d)", bitforce->proc_repr, count, (int)BITFORCE_MAX_QRESULTS);
  1494. if (!count)
  1495. return true;
  1496. fcount = 0;
  1497. for (int i = 0; i < data->parallel; ++i)
  1498. counts[i] = 0;
  1499. noncebuf = next_line(noncebuf);
  1500. while ((buf = noncebuf)[0])
  1501. {
  1502. if ( (noncebuf = next_line(buf)) )
  1503. noncebuf[-1] = '\0';
  1504. if (strlen(buf) <= 90)
  1505. {
  1506. applog(LOG_ERR, "%"PRIpreprv": Gibberish within queue results: %s", bitforce->proc_repr, buf);
  1507. continue;
  1508. }
  1509. hex2bin(midstate, buf, 32);
  1510. hex2bin(datatail, &buf[65], 12);
  1511. thiswork = NULL;
  1512. DL_FOREACH(thr->work_list, work)
  1513. {
  1514. if (unlikely(memcmp(work->midstate, midstate, 32)))
  1515. continue;
  1516. if (unlikely(memcmp(&work->data[64], datatail, 12)))
  1517. continue;
  1518. thiswork = work;
  1519. break;
  1520. }
  1521. end = &buf[89];
  1522. chip_cgpu = bitforce;
  1523. if (data->parallel_protocol)
  1524. {
  1525. chipno = strtol(&end[1], &end, 16);
  1526. if (chipno >= data->parallel)
  1527. {
  1528. applog(LOG_ERR, "%"PRIpreprv": Chip number out of range for queue result: %s", chip_cgpu->proc_repr, buf);
  1529. chipno = 0;
  1530. }
  1531. for (int i = 0; i < chipno; ++i)
  1532. chip_cgpu = chip_cgpu->next_proc;
  1533. }
  1534. chip_thr = chip_cgpu->thr[0];
  1535. applog(LOG_DEBUG, "%"PRIpreprv": Queue result: %s", chip_cgpu->proc_repr, buf);
  1536. if (unlikely(!thiswork))
  1537. {
  1538. applog(LOG_ERR, "%"PRIpreprv": Failed to find work for queue results: %s", chip_cgpu->proc_repr, buf);
  1539. inc_hw_errors_only(chip_thr);
  1540. goto next_qline;
  1541. }
  1542. if (unlikely(!end[0]))
  1543. {
  1544. applog(LOG_ERR, "%"PRIpreprv": Missing nonce count in queue results: %s", chip_cgpu->proc_repr, buf);
  1545. goto finishresult;
  1546. }
  1547. if (strtol(&end[1], &end, 10))
  1548. {
  1549. if (unlikely(!end[0]))
  1550. {
  1551. applog(LOG_ERR, "%"PRIpreprv": Missing nonces in queue results: %s", chip_cgpu->proc_repr, buf);
  1552. goto finishresult;
  1553. }
  1554. bitforce_process_result_nonces(chip_thr, work, &end[1]);
  1555. }
  1556. ++fcount;
  1557. ++counts[chipno];
  1558. finishresult:
  1559. if (data->parallel == 1)
  1560. {
  1561. // Queue results are in order, so anything queued prior this is lost
  1562. // Delete all queued work up to, and including, this one
  1563. DL_FOREACH_SAFE(thr->work_list, work, tmpwork)
  1564. {
  1565. work_list_del(&thr->work_list, work);
  1566. --data->queued;
  1567. if (work == thiswork)
  1568. break;
  1569. }
  1570. }
  1571. else
  1572. {
  1573. // Parallel processors means the results might not be in order
  1574. // This could leak if jobs get lost, hence the sanity checks using "ZqX"
  1575. work_list_del(&thr->work_list, thiswork);
  1576. --data->queued;
  1577. }
  1578. next_qline: (void)0;
  1579. }
  1580. bitforce_set_queue_full(thr);
  1581. if (count >= BITFORCE_MAX_QRESULTS)
  1582. goto again;
  1583. if (data->parallel == 1 && (
  1584. (fcount < BITFORCE_GOAL_QRESULTS && bitforce->sleep_ms < BITFORCE_MAX_QRESULT_WAIT && data->queued > 1)
  1585. || (fcount > BITFORCE_GOAL_QRESULTS && bitforce->sleep_ms > BITFORCE_MIN_QRESULT_WAIT) ))
  1586. {
  1587. unsigned int old_sleep_ms = bitforce->sleep_ms;
  1588. bitforce->sleep_ms = (uint32_t)bitforce->sleep_ms * BITFORCE_GOAL_QRESULTS / (fcount ?: 1);
  1589. if (bitforce->sleep_ms > BITFORCE_MAX_QRESULT_WAIT)
  1590. bitforce->sleep_ms = BITFORCE_MAX_QRESULT_WAIT;
  1591. if (bitforce->sleep_ms < BITFORCE_MIN_QRESULT_WAIT)
  1592. bitforce->sleep_ms = BITFORCE_MIN_QRESULT_WAIT;
  1593. applog(LOG_DEBUG, "%"PRIpreprv": Received %d queue results after %ums; Wait time changed to: %ums (queued<=%d)",
  1594. bitforce->proc_repr, fcount, old_sleep_ms, bitforce->sleep_ms, data->queued);
  1595. }
  1596. else
  1597. applog(LOG_DEBUG, "%"PRIpreprv": Received %d queue results after %ums; Wait time unchanged (queued<=%d)",
  1598. bitforce->proc_repr, fcount, bitforce->sleep_ms, data->queued);
  1599. cgtime(&tv_now);
  1600. timersub(&tv_now, &data->tv_hashmeter_start, &tv_elapsed);
  1601. chip_cgpu = bitforce;
  1602. for (int i = 0; i < data->parallel; ++i, (chip_cgpu = chip_cgpu->next_proc))
  1603. {
  1604. chip_thr = chip_cgpu->thr[0];
  1605. hashes_done(chip_thr, (uint64_t)bitforce->nonces * counts[i], &tv_elapsed, NULL);
  1606. }
  1607. data->tv_hashmeter_start = tv_now;
  1608. return true;
  1609. }
  1610. static
  1611. bool bitforce_queue_append(struct thr_info *thr, struct work *work)
  1612. {
  1613. struct cgpu_info *bitforce = thr->cgpu;
  1614. struct bitforce_data *data = bitforce->device_data;
  1615. bool rv, ndq;
  1616. bitforce_set_queue_full(thr);
  1617. rv = !thr->queue_full;
  1618. if (rv)
  1619. {
  1620. DL_APPEND(thr->work_list, work);
  1621. ++data->ready_to_queue;
  1622. applog(LOG_DEBUG, "%"PRIpreprv": Appending to driver queue (max=%u, ready=%d, queued<=%d)",
  1623. bitforce->proc_repr,
  1624. (unsigned)data->queued_max, data->ready_to_queue, data->queued);
  1625. bitforce_set_queue_full(thr);
  1626. }
  1627. else
  1628. if (!data->ready_to_queue)
  1629. return rv;
  1630. ndq = !data->queued;
  1631. if ((ndq) // Device is idle
  1632. || (data->ready_to_queue >= BITFORCE_MAX_BQUEUE_AT_ONCE) // ...or 5 items ready to go
  1633. || (thr->queue_full) // ...or done filling queue
  1634. || (data->just_flushed) // ...or queue was just flushed (only remaining job is partly done already)
  1635. || (data->missing_zwx) // ...or device can only queue one at a time
  1636. )
  1637. {
  1638. if (!bitforce_send_queue(thr))
  1639. {
  1640. // Problem sending queue, retry again in a few seconds
  1641. applog(LOG_ERR, "%"PRIpreprv": Failed to send queue", bitforce->proc_repr);
  1642. inc_hw_errors_only(thr);
  1643. data->want_to_send_queue = true;
  1644. }
  1645. }
  1646. return rv;
  1647. }
  1648. struct _jobinfo {
  1649. uint8_t key[32+12];
  1650. int instances;
  1651. UT_hash_handle hh;
  1652. };
  1653. static
  1654. void bitforce_queue_flush(struct thr_info *thr)
  1655. {
  1656. struct bitforce_proc_data *procdata = thr->cgpu_data;
  1657. if (!procdata->handles_board)
  1658. return;
  1659. struct cgpu_info *bitforce = thr->cgpu;
  1660. struct bitforce_data *data = bitforce->device_data;
  1661. char *buf = &data->noncebuf[0], *buf2 = NULL;
  1662. const char *cmd = "ZqX";
  1663. unsigned flushed;
  1664. struct _jobinfo *processing = NULL, *item, *this;
  1665. if (data->parallel == 1)
  1666. // Pre-parallelization neither needs nor supports "ZqX"
  1667. cmd = "ZQX";
  1668. // TODO: Call "ZQX" most of the time: don't need to do sanity checks so often
  1669. bitforce_zox(thr, cmd);
  1670. if (!strncasecmp(buf, "OK:FLUSHED", 10))
  1671. flushed = atoi(&buf[10]);
  1672. else
  1673. if ((!strncasecmp(buf, "COUNT:", 6)) && (buf2 = strstr(buf, "FLUSHED:")) )
  1674. {
  1675. flushed = atoi(&buf2[8]);
  1676. buf2 = next_line(buf2);
  1677. }
  1678. else
  1679. if (!strncasecmp(buf, "OK", 2))
  1680. {
  1681. applog(LOG_DEBUG, "%"PRIpreprv": Didn't report flush count", bitforce->proc_repr);
  1682. thr->queue_full = false;
  1683. flushed = 0;
  1684. }
  1685. else
  1686. {
  1687. applog(LOG_DEBUG, "%"PRIpreprv": Failed to flush device queue: %s", bitforce->proc_repr, buf);
  1688. flushed = 0;
  1689. }
  1690. data->queued -= flushed;
  1691. applog(LOG_DEBUG, "%"PRIpreprv": Flushed %u jobs from device and %d from driver (queued<=%d)",
  1692. bitforce->proc_repr, flushed, data->ready_to_queue, data->queued);
  1693. flushed += data->ready_to_queue;
  1694. data->ready_to_queue = 0;
  1695. while (flushed--)
  1696. work_list_del(&thr->work_list, thr->work_list->prev);
  1697. bitforce_set_queue_full(thr);
  1698. data->just_flushed = true;
  1699. data->want_to_send_queue = false;
  1700. // "ZqX" returns jobs in progress, allowing us to sanity check
  1701. // NOTE: Must process buffer into hash table BEFORE calling bitforce_queue_do_results, which clobbers it
  1702. // NOTE: Must do actual sanity check AFTER calling bitforce_queue_do_results, to ensure we don't delete completed jobs
  1703. if (buf2)
  1704. {
  1705. // First, turn buf2 into a hash
  1706. for ( ; buf2[0]; buf2 = next_line(buf2))
  1707. {
  1708. this = malloc(sizeof(*this));
  1709. hex2bin(&this->key[ 0], &buf2[ 0], 32);
  1710. hex2bin(&this->key[32], &buf2[65], 12);
  1711. HASH_FIND(hh, processing, &this->key[0], sizeof(this->key), item);
  1712. if (likely(!item))
  1713. {
  1714. this->instances = 1;
  1715. HASH_ADD(hh, processing, key, sizeof(this->key), this);
  1716. }
  1717. else
  1718. {
  1719. // This should really only happen in testing/benchmarking...
  1720. ++item->instances;
  1721. free(this);
  1722. }
  1723. }
  1724. }
  1725. bitforce_queue_do_results(thr);
  1726. if (buf2)
  1727. {
  1728. struct work *work, *tmp;
  1729. uint8_t key[32+12];
  1730. // Now iterate over the work_list and delete anything not in the hash
  1731. DL_FOREACH_SAFE(thr->work_list, work, tmp)
  1732. {
  1733. memcpy(&key[ 0], work->midstate, 32);
  1734. memcpy(&key[32], &work->data[64], 12);
  1735. HASH_FIND(hh, processing, &key[0], sizeof(key), item);
  1736. if (unlikely(!item))
  1737. {
  1738. char hex[89];
  1739. bin2hex(hex, key, 32+12);
  1740. applog(LOG_WARNING, "%"PRIpreprv": Sanity check: Device is missing queued job! %s", bitforce->proc_repr, hex);
  1741. work_list_del(&thr->work_list, work);
  1742. continue;
  1743. }
  1744. if (likely(!--item->instances))
  1745. {
  1746. HASH_DEL(processing, item);
  1747. free(item);
  1748. }
  1749. }
  1750. if (unlikely( (flushed = HASH_COUNT(processing)) ))
  1751. {
  1752. //applog(LOG_WARNING, "%"PRIpreprv": Sanity check: Device is working on %d unknown jobs!", bitforce->proc_repr, flushed);
  1753. // FIXME: Probably these were jobs finished after ZqX, included in the result check we just did
  1754. // NOTE: We need to do that result check first to avoid deleting work_list items for things just solved
  1755. HASH_ITER(hh, processing, item, this)
  1756. {
  1757. HASH_DEL(processing, item);
  1758. free(item);
  1759. }
  1760. }
  1761. }
  1762. }
  1763. static
  1764. void bitforce_queue_poll(struct thr_info *thr)
  1765. {
  1766. struct cgpu_info *bitforce = thr->cgpu;
  1767. struct bitforce_data *data = bitforce->device_data;
  1768. unsigned long sleep_us;
  1769. if (data->queued)
  1770. bitforce_queue_do_results(thr);
  1771. sleep_us = (unsigned long)bitforce->sleep_ms * 1000;
  1772. if (data->want_to_send_queue)
  1773. if (!bitforce_send_queue(thr))
  1774. if (!data->queued)
  1775. {
  1776. applog(LOG_ERR, "%"PRIpreprv": Failed to send queue, and queue empty; retrying after 1 second", bitforce->proc_repr);
  1777. inc_hw_errors_only(thr);
  1778. sleep_us = 1000000;
  1779. }
  1780. timer_set_delay_from_now(&thr->tv_poll, sleep_us);
  1781. }
  1782. static void bitforce_queue_thread_deven(struct thr_info *thr)
  1783. {
  1784. struct cgpu_info *bitforce = thr->cgpu, *thisbf;
  1785. struct bitforce_data *data = bitforce->device_data;
  1786. struct thr_info *thisthr;
  1787. for (thisbf = bitforce->device; thisbf && thisbf->device_data != data; thisbf = thisbf->next_proc)
  1788. {}
  1789. for ( ; thisbf && thisbf->device_data == data; thisbf = thisbf->next_proc)
  1790. {
  1791. thisthr = bitforce->thr[0];
  1792. thisthr->pause = thr->pause;
  1793. thisbf->deven = bitforce->deven;
  1794. }
  1795. }
  1796. static void bitforce_queue_thread_disable(struct thr_info *thr)
  1797. {
  1798. // Disable other threads sharing the same queue
  1799. bitforce_queue_thread_deven(thr);
  1800. }
  1801. static void bitforce_queue_thread_enable(struct thr_info *thr)
  1802. {
  1803. // TODO: Maybe reinit?
  1804. // Enable other threads sharing the same queue
  1805. bitforce_queue_thread_deven(thr);
  1806. }
  1807. struct device_drv bitforce_queue_api = {
  1808. .dname = "bitforce_queue",
  1809. .name = "BFL",
  1810. .lowl_probe_by_name_only = true,
  1811. .lowl_match = bitforce_lowl_match,
  1812. .lowl_probe = bitforce_lowl_probe,
  1813. .minerloop = minerloop_queue,
  1814. .reinit_device = bitforce_reinit,
  1815. #ifdef HAVE_CURSES
  1816. .proc_wlogprint_status = bitforce_wlogprint_status,
  1817. .proc_tui_wlogprint_choices = bitforce_tui_wlogprint_choices,
  1818. .proc_tui_handle_choice = bitforce_tui_handle_choice,
  1819. #endif
  1820. .get_api_stats = bitforce_drv_stats,
  1821. .get_stats = bitforce_get_stats,
  1822. .set_device = bitforce_set_device,
  1823. .identify_device = bitforce_identify,
  1824. .thread_prepare = bitforce_thread_prepare,
  1825. .thread_init = bitforce_thread_init,
  1826. .queue_append = bitforce_queue_append,
  1827. .queue_flush = bitforce_queue_flush,
  1828. .poll = bitforce_queue_poll,
  1829. .thread_shutdown = bitforce_shutdown,
  1830. .thread_disable = bitforce_queue_thread_disable,
  1831. .thread_enable = bitforce_queue_thread_enable,
  1832. };