driver-bitforce.c 56 KB

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