driver-bitforce.c 58 KB

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