driver-bitforce.c 58 KB

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