driver-bitforce.c 57 KB

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