driver-bitforce.c 58 KB

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