driver-bitforce.c 54 KB

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