driver-bitforce.c 57 KB

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