driver-bitforce.c 57 KB

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