driver-bitforce.c 58 KB

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