driver-bitforce.c 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097
  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 <limits.h>
  12. #include <pthread.h>
  13. #include <stdint.h>
  14. #include <stdio.h>
  15. #include <strings.h>
  16. #include <sys/time.h>
  17. #include <unistd.h>
  18. #include "compat.h"
  19. #include "deviceapi.h"
  20. #include "miner.h"
  21. #include "fpgautils.h"
  22. #define BITFORCE_SLEEP_MS 500
  23. #define BITFORCE_TIMEOUT_S 7
  24. #define BITFORCE_TIMEOUT_MS (BITFORCE_TIMEOUT_S * 1000)
  25. #define BITFORCE_LONG_TIMEOUT_S 25
  26. #define BITFORCE_LONG_TIMEOUT_MS (BITFORCE_LONG_TIMEOUT_S * 1000)
  27. #define BITFORCE_CHECK_INTERVAL_MS 10
  28. #define WORK_CHECK_INTERVAL_MS 50
  29. #define MAX_START_DELAY_MS 100
  30. #define tv_to_ms(tval) ((unsigned long)(tval.tv_sec * 1000 + tval.tv_usec / 1000))
  31. #define TIME_AVG_CONSTANT 8
  32. enum bitforce_proto {
  33. BFP_WORK,
  34. BFP_RANGE,
  35. BFP_QUEUE,
  36. };
  37. static const char *protonames[] = {
  38. "full work",
  39. "nonce range",
  40. "work queue",
  41. };
  42. struct device_api bitforce_api;
  43. // Code must deal with a timeout
  44. #define BFopen(devpath) serial_open(devpath, 0, 250, true)
  45. static void BFgets(char *buf, size_t bufLen, int fd)
  46. {
  47. do {
  48. buf[0] = '\0';
  49. --bufLen;
  50. } while (likely(bufLen && read(fd, buf, 1) == 1 && (buf++)[0] != '\n'));
  51. buf[0] = '\0';
  52. }
  53. static ssize_t BFwrite(int fd, const void *buf, ssize_t bufLen)
  54. {
  55. if ((bufLen) != write(fd, buf, bufLen))
  56. return 0;
  57. else
  58. return bufLen;
  59. }
  60. static ssize_t bitforce_send(int fd, int procid, const void *buf, ssize_t bufLen)
  61. {
  62. if (!procid)
  63. return BFwrite(fd, buf, bufLen);
  64. if (bufLen > 255)
  65. return -1;
  66. size_t bufLeft = bufLen + 3;
  67. char realbuf[bufLeft], *bufp;
  68. ssize_t rv;
  69. memcpy(&realbuf[3], buf, bufLen);
  70. realbuf[0] = '@';
  71. realbuf[1] = procid;
  72. realbuf[2] = bufLen;
  73. bufp = realbuf;
  74. while (true)
  75. {
  76. rv = BFwrite(fd, bufp, bufLeft);
  77. if (rv <= 0)
  78. return rv;
  79. bufLeft -= rv;
  80. }
  81. return bufLen;
  82. }
  83. static
  84. void bitforce_cmd1(int fd, int procid, void *buf, size_t bufsz, const char *cmd)
  85. {
  86. bitforce_send(fd, procid, cmd, 3);
  87. BFgets(buf, bufsz, fd);
  88. }
  89. static
  90. void bitforce_cmd2(int fd, int procid, void *buf, size_t bufsz, const char *cmd, void *data, size_t datasz)
  91. {
  92. bitforce_cmd1(fd, procid, buf, bufsz, cmd);
  93. if (strncasecmp(buf, "OK", 2))
  94. return;
  95. bitforce_send(fd, procid, data, datasz);
  96. BFgets(buf, bufsz, fd);
  97. }
  98. #define BFclose(fd) close(fd)
  99. struct bitforce_init_data {
  100. bool sc;
  101. long devmask;
  102. };
  103. static bool bitforce_detect_one(const char *devpath)
  104. {
  105. int fdDev = serial_open(devpath, 0, 10, true);
  106. struct cgpu_info *bitforce;
  107. char pdevbuf[0x100];
  108. size_t pdevbuf_len;
  109. char *s;
  110. int procs = 1;
  111. struct bitforce_init_data *initdata;
  112. applog(LOG_DEBUG, "BFL: Attempting to open %s", devpath);
  113. if (unlikely(fdDev == -1)) {
  114. applog(LOG_DEBUG, "BFL: Failed to open %s", devpath);
  115. return false;
  116. }
  117. bitforce_cmd1(fdDev, 0, pdevbuf, sizeof(pdevbuf), "ZGX");
  118. if (unlikely(!pdevbuf[0])) {
  119. applog(LOG_DEBUG, "BFL: Error reading/timeout (ZGX)");
  120. return 0;
  121. }
  122. if (unlikely(!strstr(pdevbuf, "SHA256"))) {
  123. applog(LOG_DEBUG, "BFL: Didn't recognise BitForce on %s", devpath);
  124. BFclose(fdDev);
  125. return false;
  126. }
  127. applog(LOG_DEBUG, "Found BitForce device on %s", devpath);
  128. initdata = malloc(sizeof(*initdata));
  129. *initdata = (struct bitforce_init_data){
  130. .sc = false,
  131. };
  132. for ( bitforce_cmd1(fdDev, 0, pdevbuf, sizeof(pdevbuf), "ZCX");
  133. strncasecmp(pdevbuf, "OK", 2);
  134. BFgets(pdevbuf, sizeof(pdevbuf), fdDev) )
  135. {
  136. pdevbuf_len = strlen(pdevbuf);
  137. if (unlikely(!pdevbuf_len))
  138. continue;
  139. pdevbuf[pdevbuf_len-1] = '\0'; // trim newline
  140. applog(LOG_DEBUG, " %s", pdevbuf);
  141. if (!strncasecmp(pdevbuf, "DEVICES IN CHAIN:", 17))
  142. procs = atoi(&pdevbuf[17]);
  143. else
  144. if (!strncasecmp(pdevbuf, "CHAIN PRESENCE MASK:", 20))
  145. initdata->devmask = strtol(&pdevbuf[20], NULL, 16);
  146. else
  147. if (!strncasecmp(pdevbuf, "DEVICE:", 7) && strstr(pdevbuf, "SC"))
  148. initdata->sc = true;
  149. }
  150. BFclose(fdDev);
  151. // We have a real BitForce!
  152. bitforce = calloc(1, sizeof(*bitforce));
  153. bitforce->api = &bitforce_api;
  154. bitforce->device_path = strdup(devpath);
  155. bitforce->deven = DEV_ENABLED;
  156. bitforce->procs = procs;
  157. bitforce->threads = 1;
  158. if (likely((!memcmp(pdevbuf, ">>>ID: ", 7)) && (s = strstr(pdevbuf + 3, ">>>")))) {
  159. s[0] = '\0';
  160. bitforce->name = strdup(pdevbuf + 7);
  161. }
  162. bitforce->cgpu_data = initdata;
  163. mutex_init(&bitforce->device_mutex);
  164. return add_cgpu(bitforce);
  165. }
  166. static int bitforce_detect_auto(void)
  167. {
  168. return serial_autodetect(bitforce_detect_one, "BitFORCE", "SHA256");
  169. }
  170. static void bitforce_detect(void)
  171. {
  172. serial_detect_auto(&bitforce_api, bitforce_detect_one, bitforce_detect_auto);
  173. }
  174. struct bitforce_data {
  175. int xlink_id;
  176. unsigned char next_work_ob[70]; // Data aligned for 32-bit access
  177. unsigned char *next_work_obs; // Start of data to send
  178. unsigned char next_work_obsz;
  179. const char *next_work_cmd;
  180. char noncebuf[0x200]; // Large enough for 3 works of queue results
  181. int poll_func;
  182. enum bitforce_proto proto;
  183. bool sc;
  184. bool queued;
  185. unsigned result_busy_polled;
  186. unsigned sleep_ms_default;
  187. };
  188. static void bitforce_clear_buffer(struct cgpu_info *);
  189. static
  190. void bitforce_comm_error(struct thr_info *thr)
  191. {
  192. struct cgpu_info *bitforce = thr->cgpu;
  193. struct bitforce_data *data = bitforce->cgpu_data;
  194. int *p_fdDev = &bitforce->device->device_fd;
  195. data->noncebuf[0] = '\0';
  196. applog(LOG_ERR, "%"PRIpreprv": Comms error", bitforce->proc_repr);
  197. dev_error(bitforce, REASON_DEV_COMMS_ERROR);
  198. ++bitforce->hw_errors;
  199. ++hw_errors;
  200. BFclose(*p_fdDev);
  201. int fd = *p_fdDev = BFopen(bitforce->device_path);
  202. if (fd == -1)
  203. {
  204. applog(LOG_ERR, "%s: Error reopening %s", bitforce->dev_repr, bitforce->device_path);
  205. return;
  206. }
  207. /* empty read buffer */
  208. bitforce_clear_buffer(bitforce);
  209. }
  210. static void get_bitforce_statline_before(char *buf, struct cgpu_info *bitforce)
  211. {
  212. float gt = bitforce->temp;
  213. if (gt > 0)
  214. tailsprintf(buf, "%5.1fC ", gt);
  215. else
  216. tailsprintf(buf, " ", gt);
  217. tailsprintf(buf, " | ");
  218. }
  219. static bool bitforce_thread_prepare(struct thr_info *thr)
  220. {
  221. struct cgpu_info *bitforce = thr->cgpu;
  222. int fdDev = BFopen(bitforce->device_path);
  223. struct timeval now;
  224. if (unlikely(fdDev == -1)) {
  225. applog(LOG_ERR, "%s: Failed to open %s", bitforce->dev_repr, bitforce->device_path);
  226. return false;
  227. }
  228. bitforce->device_fd = fdDev;
  229. applog(LOG_INFO, "%s: Opened %s", bitforce->dev_repr, bitforce->device_path);
  230. gettimeofday(&now, NULL);
  231. get_datestamp(bitforce->init, &now);
  232. return true;
  233. }
  234. static void bitforce_clear_buffer(struct cgpu_info *bitforce)
  235. {
  236. pthread_mutex_t *mutexp = &bitforce->device->device_mutex;
  237. int fdDev = bitforce->device->device_fd;
  238. char pdevbuf[0x100];
  239. int count = 0;
  240. if (!fdDev)
  241. return;
  242. applog(LOG_DEBUG, "%"PRIpreprv": Clearing read buffer", bitforce->proc_repr);
  243. mutex_lock(mutexp);
  244. do {
  245. pdevbuf[0] = '\0';
  246. BFgets(pdevbuf, sizeof(pdevbuf), fdDev);
  247. } while (pdevbuf[0] && (++count < 10));
  248. mutex_unlock(mutexp);
  249. }
  250. void bitforce_init(struct cgpu_info *bitforce)
  251. {
  252. const char *devpath = bitforce->device_path;
  253. pthread_mutex_t *mutexp = &bitforce->device->device_mutex;
  254. int *p_fdDev = &bitforce->device->device_fd;
  255. int fdDev = *p_fdDev, retries = 0;
  256. char pdevbuf[0x100];
  257. char *s;
  258. applog(LOG_WARNING, "%"PRIpreprv": Re-initialising", bitforce->proc_repr);
  259. bitforce_clear_buffer(bitforce);
  260. mutex_lock(mutexp);
  261. if (fdDev) {
  262. BFclose(fdDev);
  263. sleep(5);
  264. }
  265. *p_fdDev = 0;
  266. fdDev = BFopen(devpath);
  267. if (unlikely(fdDev == -1)) {
  268. mutex_unlock(mutexp);
  269. applog(LOG_ERR, "%s: Failed to open %s", bitforce->dev_repr, devpath);
  270. return;
  271. }
  272. do {
  273. bitforce_cmd1(fdDev, 0, pdevbuf, sizeof(pdevbuf), "ZGX");
  274. if (unlikely(!pdevbuf[0])) {
  275. mutex_unlock(mutexp);
  276. applog(LOG_ERR, "%s: Error reading/timeout (ZGX)", bitforce->dev_repr);
  277. return;
  278. }
  279. if (retries++)
  280. nmsleep(10);
  281. } while (!strstr(pdevbuf, "BUSY") && (retries * 10 < BITFORCE_TIMEOUT_MS));
  282. if (unlikely(!strstr(pdevbuf, "SHA256"))) {
  283. mutex_unlock(mutexp);
  284. applog(LOG_ERR, "%s: Didn't recognise BitForce on %s returned: %s", bitforce->dev_repr, devpath, pdevbuf);
  285. return;
  286. }
  287. if (likely((!memcmp(pdevbuf, ">>>ID: ", 7)) && (s = strstr(pdevbuf + 3, ">>>")))) {
  288. s[0] = '\0';
  289. free((void*)bitforce->name);
  290. bitforce->name = strdup(pdevbuf + 7);
  291. }
  292. *p_fdDev = fdDev;
  293. bitforce->sleep_ms = BITFORCE_SLEEP_MS;
  294. mutex_unlock(mutexp);
  295. }
  296. static void bitforce_flash_led(struct cgpu_info *bitforce)
  297. {
  298. struct bitforce_data *data = bitforce->cgpu_data;
  299. pthread_mutex_t *mutexp = &bitforce->device->device_mutex;
  300. int fdDev = bitforce->device->device_fd;
  301. if (!fdDev)
  302. return;
  303. /* Do not try to flash the led if we're polling for a result to
  304. * minimise the chance of interleaved results */
  305. if (bitforce->polling)
  306. return;
  307. /* It is not critical flashing the led so don't get stuck if we
  308. * can't grab the mutex here */
  309. if (mutex_trylock(mutexp))
  310. return;
  311. char pdevbuf[0x100];
  312. bitforce_cmd1(fdDev, data->xlink_id, pdevbuf, sizeof(pdevbuf), "ZMX");
  313. /* Once we've tried - don't do it until told to again */
  314. bitforce->flash_led = false;
  315. /* However, this stops anything else getting a reply
  316. * So best to delay any other access to the BFL */
  317. sleep(4);
  318. mutex_unlock(mutexp);
  319. return; // nothing is returned by the BFL
  320. }
  321. static bool bitforce_get_temp(struct cgpu_info *bitforce)
  322. {
  323. struct bitforce_data *data = bitforce->cgpu_data;
  324. pthread_mutex_t *mutexp = &bitforce->device->device_mutex;
  325. int fdDev = bitforce->device->device_fd;
  326. char pdevbuf[0x100];
  327. char *s;
  328. if (!fdDev)
  329. return false;
  330. /* Do not try to get the temperature if we're polling for a result to
  331. * minimise the chance of interleaved results */
  332. if (bitforce->polling)
  333. return true;
  334. // Flash instead of Temp - doing both can be too slow
  335. if (bitforce->flash_led) {
  336. bitforce_flash_led(bitforce);
  337. return true;
  338. }
  339. /* It is not critical getting temperature so don't get stuck if we
  340. * can't grab the mutex here */
  341. if (mutex_trylock(mutexp))
  342. return false;
  343. bitforce_cmd1(fdDev, data->xlink_id, pdevbuf, sizeof(pdevbuf), "ZLX");
  344. mutex_unlock(mutexp);
  345. if (unlikely(!pdevbuf[0])) {
  346. applog(LOG_ERR, "%"PRIpreprv": Error: Get temp returned empty string/timed out", bitforce->proc_repr);
  347. bitforce->hw_errors++;
  348. ++hw_errors;
  349. return false;
  350. }
  351. if ((!strncasecmp(pdevbuf, "TEMP", 4)) && (s = strchr(pdevbuf + 4, ':'))) {
  352. float temp = strtof(s + 1, NULL);
  353. /* Cope with older software that breaks and reads nonsense
  354. * values */
  355. if (temp > 100)
  356. temp = strtod(s + 1, NULL);
  357. if (temp > 0) {
  358. bitforce->temp = temp;
  359. }
  360. } else {
  361. /* Use the temperature monitor as a kind of watchdog for when
  362. * our responses are out of sync and flush the buffer to
  363. * hopefully recover */
  364. applog(LOG_WARNING, "%"PRIpreprv": Garbled response probably throttling, clearing buffer", bitforce->proc_repr);
  365. dev_error(bitforce, REASON_DEV_THROTTLE);
  366. /* Count throttling episodes as hardware errors */
  367. bitforce->hw_errors++;
  368. ++hw_errors;
  369. bitforce_clear_buffer(bitforce);
  370. return false;
  371. }
  372. return true;
  373. }
  374. static inline
  375. void dbg_block_data(struct cgpu_info *bitforce)
  376. {
  377. if (!opt_debug)
  378. return;
  379. struct bitforce_data *data = bitforce->cgpu_data;
  380. char *s;
  381. s = bin2hex(&data->next_work_ob[8], 44);
  382. applog(LOG_DEBUG, "%"PRIpreprv": block data: %s", bitforce->proc_repr, s);
  383. free(s);
  384. }
  385. static void bitforce_change_mode(struct cgpu_info *, enum bitforce_proto);
  386. static
  387. bool bitforce_job_prepare(struct thr_info *thr, struct work *work, __maybe_unused uint64_t max_nonce)
  388. {
  389. struct cgpu_info *bitforce = thr->cgpu;
  390. struct bitforce_data *data = bitforce->cgpu_data;
  391. int fdDev = bitforce->device->device_fd;
  392. unsigned char *ob_ms = &data->next_work_ob[8];
  393. unsigned char *ob_dt = &ob_ms[32];
  394. // If polling job_start, cancel it
  395. if (data->poll_func == 1)
  396. {
  397. thr->tv_poll.tv_sec = -1;
  398. data->poll_func = 0;
  399. }
  400. memcpy(ob_ms, work->midstate, 32);
  401. memcpy(ob_dt, work->data + 64, 12);
  402. switch (data->proto)
  403. {
  404. case BFP_RANGE:
  405. {
  406. uint32_t *ob_nonce = (uint32_t*)&(ob_dt[32]);
  407. ob_nonce[0] = htobe32(work->blk.nonce);
  408. ob_nonce[1] = htobe32(work->blk.nonce + bitforce->nonces);
  409. // FIXME: if nonce range fails... we didn't increment enough
  410. work->blk.nonce += bitforce->nonces + 1;
  411. break;
  412. }
  413. case BFP_QUEUE:
  414. if (thr->work)
  415. {
  416. pthread_mutex_t *mutexp = &bitforce->device->device_mutex;
  417. char pdevbuf[0x100];
  418. if (unlikely(!fdDev))
  419. return false;
  420. mutex_lock(mutexp);
  421. if (data->queued)
  422. bitforce_cmd1(fdDev, data->xlink_id, pdevbuf, sizeof(pdevbuf), "ZQX");
  423. bitforce_cmd2(fdDev, data->xlink_id, pdevbuf, sizeof(pdevbuf), data->next_work_cmd, data->next_work_obs, data->next_work_obsz);
  424. mutex_unlock(mutexp);
  425. if (unlikely(strncasecmp(pdevbuf, "OK", 2))) {
  426. applog(LOG_WARNING, "%"PRIpreprv": Does not support work queue, disabling", bitforce->proc_repr);
  427. bitforce_change_mode(bitforce, BFP_WORK);
  428. }
  429. else
  430. {
  431. dbg_block_data(bitforce);
  432. data->queued = true;
  433. }
  434. }
  435. // fallthru...
  436. case BFP_WORK:
  437. work->blk.nonce = 0xffffffff;
  438. }
  439. return true;
  440. }
  441. static
  442. void bitforce_change_mode(struct cgpu_info *bitforce, enum bitforce_proto proto)
  443. {
  444. struct bitforce_data *data = bitforce->cgpu_data;
  445. if (data->proto == proto)
  446. return;
  447. if (data->proto == BFP_RANGE)
  448. {
  449. bitforce->nonces = 0xffffffff;
  450. bitforce->sleep_ms *= 5;
  451. data->sleep_ms_default *= 5;
  452. switch (proto)
  453. {
  454. case BFP_WORK:
  455. data->next_work_cmd = "ZDX";
  456. break;
  457. case BFP_QUEUE:
  458. data->next_work_cmd = "ZNX";
  459. default:
  460. ;
  461. }
  462. if (data->sc)
  463. {
  464. // "S|---------- MidState ----------||-DataTail-|E"
  465. data->next_work_ob[7] = 45;
  466. data->next_work_ob[8+32+12] = '\xAA';
  467. data->next_work_obsz = 46;
  468. }
  469. else
  470. {
  471. // ">>>>>>>>|---------- MidState ----------||-DataTail-|>>>>>>>>"
  472. memset(&data->next_work_ob[8+32+12], '>', 8);
  473. data->next_work_obsz = 60;
  474. }
  475. }
  476. else
  477. if (proto == BFP_RANGE)
  478. {
  479. /* Split work up into 1/5th nonce ranges */
  480. bitforce->nonces = 0x33333332;
  481. bitforce->sleep_ms /= 5;
  482. data->sleep_ms_default /= 5;
  483. data->next_work_cmd = "ZPX";
  484. if (data->sc)
  485. {
  486. data->next_work_ob[7] = 53;
  487. data->next_work_obsz = 54;
  488. }
  489. else
  490. data->next_work_obsz = 68;
  491. }
  492. data->proto = proto;
  493. bitforce->kname = protonames[proto];
  494. }
  495. static
  496. void bitforce_job_start(struct thr_info *thr)
  497. {
  498. struct cgpu_info *bitforce = thr->cgpu;
  499. struct bitforce_data *data = bitforce->cgpu_data;
  500. pthread_mutex_t *mutexp = &bitforce->device->device_mutex;
  501. int fdDev = bitforce->device->device_fd;
  502. unsigned char *ob = data->next_work_obs;
  503. char pdevbuf[0x100];
  504. struct timeval tv_now;
  505. data->result_busy_polled = 0;
  506. if (data->queued)
  507. {
  508. // get_results collected more accurate job start time
  509. mt_job_transition(thr);
  510. job_start_complete(thr);
  511. data->queued = false;
  512. timer_set_delay(&thr->tv_morework, &bitforce->work_start_tv, bitforce->sleep_ms * 1000);
  513. return;
  514. }
  515. if (!fdDev)
  516. goto commerr;
  517. re_send:
  518. mutex_lock(mutexp);
  519. bitforce_cmd2(fdDev, data->xlink_id, pdevbuf, sizeof(pdevbuf), data->next_work_cmd, ob, data->next_work_obsz);
  520. if (!pdevbuf[0] || !strncasecmp(pdevbuf, "B", 1)) {
  521. mutex_unlock(mutexp);
  522. gettimeofday(&tv_now, NULL);
  523. timer_set_delay(&thr->tv_poll, &tv_now, WORK_CHECK_INTERVAL_MS * 1000);
  524. data->poll_func = 1;
  525. return;
  526. } else if (unlikely(strncasecmp(pdevbuf, "OK", 2))) {
  527. mutex_unlock(mutexp);
  528. switch (data->proto)
  529. {
  530. case BFP_RANGE:
  531. applog(LOG_WARNING, "%"PRIpreprv": Does not support nonce range, disabling", bitforce->proc_repr);
  532. bitforce_change_mode(bitforce, BFP_WORK);
  533. goto re_send;
  534. case BFP_QUEUE:
  535. applog(LOG_WARNING, "%"PRIpreprv": Does not support work queue, disabling", bitforce->proc_repr);
  536. bitforce_change_mode(bitforce, BFP_WORK);
  537. goto re_send;
  538. default:
  539. ;
  540. }
  541. applog(LOG_ERR, "%"PRIpreprv": Error: Send work reports: %s", bitforce->proc_repr, pdevbuf);
  542. goto commerr;
  543. }
  544. mt_job_transition(thr);
  545. mutex_unlock(mutexp);
  546. dbg_block_data(bitforce);
  547. gettimeofday(&tv_now, NULL);
  548. bitforce->work_start_tv = tv_now;
  549. timer_set_delay(&thr->tv_morework, &tv_now, bitforce->sleep_ms * 1000);
  550. job_start_complete(thr);
  551. return;
  552. commerr:
  553. bitforce_comm_error(thr);
  554. job_start_abort(thr, true);
  555. }
  556. static char _discardedbuf[0x10];
  557. static
  558. void bitforce_job_get_results(struct thr_info *thr, struct work *work)
  559. {
  560. struct cgpu_info *bitforce = thr->cgpu;
  561. struct bitforce_data *data = bitforce->cgpu_data;
  562. pthread_mutex_t *mutexp = &bitforce->device->device_mutex;
  563. int fdDev = bitforce->device->device_fd;
  564. unsigned int delay_time_ms;
  565. struct timeval elapsed;
  566. struct timeval now;
  567. char *pdevbuf = &data->noncebuf[0];
  568. bool stale;
  569. int count;
  570. gettimeofday(&now, NULL);
  571. timersub(&now, &bitforce->work_start_tv, &elapsed);
  572. bitforce->wait_ms = tv_to_ms(elapsed);
  573. bitforce->polling = true;
  574. if (!fdDev)
  575. goto commerr;
  576. stale = stale_work(work, true);
  577. if (unlikely(bitforce->wait_ms < bitforce->sleep_ms))
  578. {
  579. // We're likely here because of a work restart
  580. // Since Bitforce cannot stop a work without losing results, only do it if the current job is finding stale shares
  581. // BFP_QUEUE does not support stopping work at all
  582. if (data->proto == BFP_QUEUE || !stale)
  583. {
  584. delay_time_ms = bitforce->sleep_ms - bitforce->wait_ms;
  585. timer_set_delay(&thr->tv_poll, &now, delay_time_ms * 1000);
  586. data->poll_func = 2;
  587. return;
  588. }
  589. }
  590. while (1) {
  591. const char *cmd = (data->proto == BFP_QUEUE) ? "ZOX" : "ZFX";
  592. mutex_lock(mutexp);
  593. bitforce_cmd1(fdDev, data->xlink_id, pdevbuf, sizeof(data->noncebuf), cmd);
  594. if (!strncasecmp(pdevbuf, "COUNT:", 6))
  595. {
  596. count = atoi(&pdevbuf[6]);
  597. size_t cls = strlen(pdevbuf);
  598. char *pmorebuf = &pdevbuf[cls];
  599. size_t szleft = sizeof(data->noncebuf) - cls, sz;
  600. if (count && data->queued)
  601. {
  602. gettimeofday(&now, NULL);
  603. bitforce->work_start_tv = now;
  604. }
  605. while (true)
  606. {
  607. BFgets(pmorebuf, szleft, fdDev);
  608. if (!strncasecmp(pmorebuf, "OK", 2))
  609. {
  610. pmorebuf[0] = '\0'; // process expects only results
  611. break;
  612. }
  613. sz = strlen(pmorebuf);
  614. szleft -= sz;
  615. pmorebuf += sz;
  616. if (unlikely(!szleft))
  617. {
  618. // Out of buffer space somehow :(
  619. applog(LOG_DEBUG, "%"PRIpreprv": Ran out of buffer space for results, discarding extra data", bitforce->proc_repr);
  620. pmorebuf = _discardedbuf;
  621. szleft = sizeof(_discardedbuf);
  622. }
  623. }
  624. }
  625. else
  626. count = -1;
  627. mutex_unlock(mutexp);
  628. gettimeofday(&now, NULL);
  629. if (!count)
  630. goto noqr;
  631. timersub(&now, &bitforce->work_start_tv, &elapsed);
  632. if (elapsed.tv_sec >= BITFORCE_LONG_TIMEOUT_S) {
  633. applog(LOG_ERR, "%"PRIpreprv": took %lums - longer than %lums", bitforce->proc_repr,
  634. tv_to_ms(elapsed), (unsigned long)BITFORCE_LONG_TIMEOUT_MS);
  635. goto out;
  636. }
  637. if (pdevbuf[0] && strncasecmp(pdevbuf, "B", 1)) /* BFL does not respond during throttling */
  638. break;
  639. data->result_busy_polled = bitforce->wait_ms;
  640. if (stale && data->proto != BFP_QUEUE)
  641. {
  642. applog(LOG_NOTICE, "%"PRIpreprv": Abandoning stale search to restart",
  643. bitforce->proc_repr);
  644. goto out;
  645. }
  646. noqr:
  647. /* if BFL is throttling, no point checking so quickly */
  648. delay_time_ms = (pdevbuf[0] ? BITFORCE_CHECK_INTERVAL_MS : 2 * WORK_CHECK_INTERVAL_MS);
  649. timer_set_delay(&thr->tv_poll, &now, delay_time_ms * 1000);
  650. data->poll_func = 2;
  651. return;
  652. }
  653. if (count < 0 && pdevbuf[0] == 'N')
  654. count = strncasecmp(pdevbuf, "NONCE-FOUND", 11) ? 1 : 0;
  655. // At this point, 'count' is:
  656. // negative, in case of some kind of error
  657. // zero, if NO-NONCE (FPGA either completed with no results, or rebooted)
  658. // positive, if at least one job completed successfully
  659. if (elapsed.tv_sec > BITFORCE_TIMEOUT_S) {
  660. applog(LOG_ERR, "%"PRIpreprv": took %lums - longer than %lums", bitforce->proc_repr,
  661. tv_to_ms(elapsed), (unsigned long)BITFORCE_TIMEOUT_MS);
  662. dev_error(bitforce, REASON_DEV_OVER_HEAT);
  663. ++bitforce->hw_errors;
  664. ++hw_errors;
  665. /* If the device truly throttled, it didn't process the job and there
  666. * are no results. But check first, just in case we're wrong about it
  667. * throttling.
  668. */
  669. if (count > 0)
  670. goto out;
  671. } else if (count >= 0) {/* Hashing complete (NONCE-FOUND or NO-NONCE) */
  672. /* Simple timing adjustment. Allow a few polls to cope with
  673. * OS timer delays being variably reliable. wait_ms will
  674. * always equal sleep_ms when we've waited greater than or
  675. * equal to the result return time.*/
  676. delay_time_ms = bitforce->sleep_ms;
  677. if (!data->result_busy_polled)
  678. {
  679. // No busy polls before results received
  680. if (bitforce->wait_ms > delay_time_ms + (WORK_CHECK_INTERVAL_MS * 8))
  681. // ... due to poll being rather late; ignore it as an anomaly
  682. applog(LOG_DEBUG, "%"PRIpreprv": Got results on first poll after %ums, later than scheduled %ums (ignoring)",
  683. bitforce->proc_repr, bitforce->wait_ms, delay_time_ms);
  684. else
  685. if (bitforce->sleep_ms > data->sleep_ms_default + (BITFORCE_CHECK_INTERVAL_MS * 0x20))
  686. {
  687. applog(LOG_DEBUG, "%"PRIpreprv": Got results on first poll after %ums, on delayed schedule %ums; Wait time changed to: %ums (default sch)",
  688. bitforce->proc_repr, bitforce->wait_ms, delay_time_ms, data->sleep_ms_default);
  689. bitforce->sleep_ms = data->sleep_ms_default;
  690. }
  691. else
  692. {
  693. applog(LOG_DEBUG, "%"PRIpreprv": Got results on first poll after %ums, on default schedule %ums; Wait time changed to: %ums (check interval)",
  694. bitforce->proc_repr, bitforce->wait_ms, delay_time_ms, BITFORCE_CHECK_INTERVAL_MS);
  695. bitforce->sleep_ms = BITFORCE_CHECK_INTERVAL_MS;
  696. }
  697. }
  698. else
  699. {
  700. if (data->result_busy_polled - bitforce->sleep_ms > WORK_CHECK_INTERVAL_MS)
  701. {
  702. bitforce->sleep_ms = data->result_busy_polled - (WORK_CHECK_INTERVAL_MS / 2);
  703. applog(LOG_DEBUG, "%"PRIpreprv": Got results on Nth poll after %ums (busy poll at %ums, sch'd %ums); Wait time changed to: %ums",
  704. bitforce->proc_repr, bitforce->wait_ms, data->result_busy_polled, delay_time_ms, bitforce->sleep_ms);
  705. }
  706. else
  707. applog(LOG_DEBUG, "%"PRIpreprv": Got results on Nth poll after %ums (busy poll at %ums, sch'd %ums); Wait time unchanged",
  708. bitforce->proc_repr, bitforce->wait_ms, data->result_busy_polled, delay_time_ms);
  709. }
  710. /* Work out the average time taken. Float for calculation, uint for display */
  711. bitforce->avg_wait_f += (tv_to_ms(elapsed) - bitforce->avg_wait_f) / TIME_AVG_CONSTANT;
  712. bitforce->avg_wait_d = (unsigned int) (bitforce->avg_wait_f + 0.5);
  713. }
  714. applog(LOG_DEBUG, "%"PRIpreprv": waited %dms until %s", bitforce->proc_repr, bitforce->wait_ms, pdevbuf);
  715. if (count < 0 && strncasecmp(pdevbuf, "I", 1)) {
  716. bitforce->hw_errors++;
  717. ++hw_errors;
  718. applog(LOG_WARNING, "%"PRIpreprv": Error: Get result reports: %s", bitforce->proc_repr, pdevbuf);
  719. bitforce_clear_buffer(bitforce);
  720. }
  721. out:
  722. bitforce->polling = false;
  723. job_results_fetched(thr);
  724. return;
  725. commerr:
  726. bitforce_comm_error(thr);
  727. goto out;
  728. }
  729. static
  730. void bitforce_process_result_nonces(struct thr_info *thr, struct work *work, char *pnoncebuf)
  731. {
  732. struct cgpu_info *bitforce = thr->cgpu;
  733. struct bitforce_data *data = bitforce->cgpu_data;
  734. uint32_t nonce;
  735. while (1) {
  736. hex2bin((void*)&nonce, pnoncebuf, 4);
  737. nonce = be32toh(nonce);
  738. if (unlikely(data->proto == BFP_RANGE && (nonce >= work->blk.nonce ||
  739. /* FIXME: blk.nonce is probably moved on quite a bit now! */
  740. (work->blk.nonce > 0 && nonce < work->blk.nonce - bitforce->nonces - 1)))) {
  741. applog(LOG_WARNING, "%"PRIpreprv": Disabling broken nonce range support", bitforce->proc_repr);
  742. bitforce_change_mode(bitforce, BFP_WORK);
  743. }
  744. submit_nonce(thr, work, nonce);
  745. if (strncmp(&pnoncebuf[8], ",", 1))
  746. break;
  747. pnoncebuf += 9;
  748. }
  749. }
  750. static
  751. bool bitforce_process_qresult_line_i(struct thr_info *thr, char *midstate, char *datatail, char *buf, struct work *work)
  752. {
  753. if (!work)
  754. return false;
  755. if (memcmp(work->midstate, midstate, 32))
  756. return false;
  757. if (memcmp(&work->data[64], datatail, 12))
  758. return false;
  759. if (!atoi(&buf[90]))
  760. return true;
  761. bitforce_process_result_nonces(thr, work, &buf[92]);
  762. return true;
  763. }
  764. static
  765. void bitforce_process_qresult_line(struct thr_info *thr, char *buf, struct work *work)
  766. {
  767. struct cgpu_info *bitforce = thr->cgpu;
  768. char midstate[32], datatail[12];
  769. hex2bin((void*)midstate, buf, 32);
  770. hex2bin((void*)datatail, &buf[65], 12);
  771. if (!( bitforce_process_qresult_line_i(thr, midstate, datatail, buf, work)
  772. || bitforce_process_qresult_line_i(thr, midstate, datatail, buf, thr->work)
  773. || bitforce_process_qresult_line_i(thr, midstate, datatail, buf, thr->prev_work)
  774. || bitforce_process_qresult_line_i(thr, midstate, datatail, buf, thr->next_work) ))
  775. {
  776. applog(LOG_ERR, "%"PRIpreprv": Failed to find work for queued results", bitforce->proc_repr);
  777. ++bitforce->hw_errors;
  778. ++hw_errors;
  779. }
  780. }
  781. static inline
  782. char *next_line(char *in)
  783. {
  784. while (in[0] && (in++)[0] != '\n')
  785. {}
  786. return in;
  787. }
  788. static
  789. int64_t bitforce_job_process_results(struct thr_info *thr, struct work *work, __maybe_unused bool stopping)
  790. {
  791. struct cgpu_info *bitforce = thr->cgpu;
  792. struct bitforce_data *data = bitforce->cgpu_data;
  793. char *pnoncebuf = &data->noncebuf[0];
  794. int count;
  795. if (!strncasecmp(pnoncebuf, "NO-", 3))
  796. return bitforce->nonces; /* No valid nonce found */
  797. if (!strncasecmp(pnoncebuf, "NONCE-FOUND", 11))
  798. {
  799. bitforce_process_result_nonces(thr, work, &pnoncebuf[12]);
  800. count = 1;
  801. }
  802. else
  803. if (!strncasecmp(pnoncebuf, "COUNT:", 6))
  804. {
  805. count = 0;
  806. pnoncebuf = next_line(pnoncebuf);
  807. while (pnoncebuf[0])
  808. {
  809. bitforce_process_qresult_line(thr, pnoncebuf, work);
  810. ++count;
  811. pnoncebuf = next_line(pnoncebuf);
  812. }
  813. }
  814. else
  815. return 0;
  816. // FIXME: This might have changed in the meantime (new job start, or broken)
  817. return bitforce->nonces * count;
  818. }
  819. static void bitforce_shutdown(struct thr_info *thr)
  820. {
  821. struct cgpu_info *bitforce = thr->cgpu;
  822. int *p_fdDev = &bitforce->device->device_fd;
  823. BFclose(*p_fdDev);
  824. *p_fdDev = 0;
  825. }
  826. static void biforce_thread_enable(struct thr_info *thr)
  827. {
  828. struct cgpu_info *bitforce = thr->cgpu;
  829. bitforce_init(bitforce);
  830. }
  831. static bool bitforce_get_stats(struct cgpu_info *bitforce)
  832. {
  833. return bitforce_get_temp(bitforce);
  834. }
  835. static bool bitforce_identify(struct cgpu_info *bitforce)
  836. {
  837. bitforce->flash_led = true;
  838. return true;
  839. }
  840. static bool bitforce_thread_init(struct thr_info *thr)
  841. {
  842. struct cgpu_info *bitforce = thr->cgpu;
  843. unsigned int wait;
  844. struct bitforce_data *data;
  845. struct bitforce_init_data *initdata = bitforce->cgpu_data;
  846. bool sc = initdata->sc;
  847. int xlink_id = 0;
  848. for ( ; bitforce; bitforce = bitforce->next_proc)
  849. {
  850. if (unlikely(xlink_id > 30))
  851. {
  852. applog(LOG_ERR, "%"PRIpreprv": Failed to find XLINK address", bitforce->proc_repr);
  853. dev_error(bitforce, REASON_THREAD_FAIL_INIT);
  854. bitforce->reinit_backoff = 1e10;
  855. continue;
  856. }
  857. bitforce->sleep_ms = BITFORCE_SLEEP_MS;
  858. bitforce->cgpu_data = data = malloc(sizeof(*data));
  859. *data = (struct bitforce_data){
  860. .xlink_id = xlink_id,
  861. .next_work_ob = ">>>>>>>>|---------- MidState ----------||-DataTail-||Nonces|>>>>>>>>",
  862. .proto = BFP_RANGE,
  863. .sc = sc,
  864. .sleep_ms_default = BITFORCE_SLEEP_MS,
  865. };
  866. if (sc)
  867. {
  868. // ".......S|---------- MidState ----------||-DataTail-||Nonces|E"
  869. data->next_work_ob[8+32+12+8] = '\xAA';
  870. data->next_work_obs = &data->next_work_ob[7];
  871. bitforce_change_mode(bitforce, BFP_QUEUE);
  872. }
  873. else
  874. {
  875. data->next_work_obs = &data->next_work_ob[0];
  876. // Unconditionally change away from cold-initialized BFP_RANGE, to allow for setting up other variables
  877. bitforce_change_mode(bitforce, BFP_WORK);
  878. /* Initially enable support for nonce range and disable it later if it
  879. * fails */
  880. if (opt_bfl_noncerange)
  881. bitforce_change_mode(bitforce, BFP_RANGE);
  882. }
  883. while (xlink_id < 31 && !(initdata->devmask & (1 << ++xlink_id)))
  884. {}
  885. }
  886. bitforce = thr->cgpu;
  887. /* Pause each new thread at least 100ms between initialising
  888. * so the devices aren't making calls all at the same time. */
  889. wait = thr->id * MAX_START_DELAY_MS;
  890. applog(LOG_DEBUG, "%s: Delaying start by %dms", bitforce->dev_repr, wait / 1000);
  891. nmsleep(wait);
  892. return true;
  893. }
  894. static struct api_data *bitforce_api_stats(struct cgpu_info *cgpu)
  895. {
  896. struct api_data *root = NULL;
  897. // Warning, access to these is not locked - but we don't really
  898. // care since hashing performance is way more important than
  899. // locking access to displaying API debug 'stats'
  900. // If locking becomes an issue for any of them, use copy_data=true also
  901. root = api_add_uint(root, "Sleep Time", &(cgpu->sleep_ms), false);
  902. root = api_add_uint(root, "Avg Wait", &(cgpu->avg_wait_d), false);
  903. return root;
  904. }
  905. void bitforce_poll(struct thr_info *thr)
  906. {
  907. struct cgpu_info *bitforce = thr->cgpu;
  908. struct bitforce_data *data = bitforce->cgpu_data;
  909. int poll = data->poll_func;
  910. thr->tv_poll.tv_sec = -1;
  911. data->poll_func = 0;
  912. switch (poll)
  913. {
  914. case 1:
  915. bitforce_job_start(thr);
  916. break;
  917. case 2:
  918. bitforce_job_get_results(thr, thr->work);
  919. break;
  920. default:
  921. applog(LOG_ERR, "%"PRIpreprv": Unexpected poll from device API!", thr->cgpu->proc_repr);
  922. }
  923. }
  924. struct device_api bitforce_api = {
  925. .dname = "bitforce",
  926. .name = "BFL",
  927. .api_detect = bitforce_detect,
  928. .get_api_stats = bitforce_api_stats,
  929. .minerloop = minerloop_async,
  930. .reinit_device = bitforce_init,
  931. .get_statline_before = get_bitforce_statline_before,
  932. .get_stats = bitforce_get_stats,
  933. .identify_device = bitforce_identify,
  934. .thread_prepare = bitforce_thread_prepare,
  935. .thread_init = bitforce_thread_init,
  936. .job_prepare = bitforce_job_prepare,
  937. .job_start = bitforce_job_start,
  938. .job_get_results = bitforce_job_get_results,
  939. .poll = bitforce_poll,
  940. .job_process_results = bitforce_job_process_results,
  941. .thread_shutdown = bitforce_shutdown,
  942. .thread_enable = biforce_thread_enable
  943. };