driver-bitforce.c 57 KB

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