driver-bitforce.c 58 KB

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