driver-drillbit.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092
  1. /*
  2. * Copyright 2013 Con Kolivas
  3. * Copyright 2013 Angus Gratton
  4. * Copyright 2013 James Nichols
  5. *
  6. * This program is free software; you can redistribute it and/or modify it
  7. * under the terms of the GNU General Public License as published by the Free
  8. * Software Foundation; either version 3 of the License, or (at your option)
  9. * any later version. See COPYING for more details.
  10. */
  11. #include "config.h"
  12. #include "miner.h"
  13. #include "driver-drillbit.h"
  14. #include "sha2.h"
  15. #define TIMEOUT 3000
  16. #define RESULT_TIMEOUT 5000
  17. #define MAX_RESULTS 16 // max results from a single chip
  18. #define drvlog(prio, fmt, ...) do { \
  19. if (drillbit->device_id == -1) { \
  20. applog(prio, "%s: "fmt, \
  21. drillbit->drv->dname, \
  22. ##__VA_ARGS__); \
  23. } else { \
  24. applog(prio, "%s %d: "fmt, \
  25. drillbit->drv->name, \
  26. drillbit->device_id, \
  27. ##__VA_ARGS__); \
  28. } \
  29. } while (0)
  30. /* Request and response structs for firmware */
  31. typedef struct {
  32. uint16_t chip_id;
  33. uint8_t midstate[32];
  34. uint8_t data[12];
  35. } WorkRequest;
  36. #define SZ_SERIALISED_WORKREQUEST 46
  37. static void serialise_work_request(char *buf, uint16_t chip_id, const struct work *wr);
  38. typedef struct {
  39. uint16_t chip_id;
  40. uint8_t num_nonces;
  41. uint8_t is_idle;
  42. uint32_t nonce[MAX_RESULTS];
  43. } WorkResult;
  44. #define SZ_SERIALISED_WORKRESULT (4+4*MAX_RESULTS)
  45. static void deserialise_work_result(WorkResult *work_result, const char *buf);
  46. /* V4 config is the preferred one, used internally, non-ASIC-specific */
  47. typedef struct {
  48. uint16_t core_voltage; // Millivolts
  49. uint16_t clock_freq; // Clock frequency in MHz (or clock level 30-48 for Bitfury internal clock level)
  50. uint8_t clock_div2; // Apply the /2 clock divider (both internal and external), where available
  51. uint8_t use_ext_clock; // Flag. Ignored on boards without external clocks
  52. } BoardConfig;
  53. typedef struct
  54. {
  55. uint16_t chip_id;
  56. uint8_t increase_clock;
  57. } AutoTuneRequest;
  58. #define SZ_SERIALISED_AUTOTUNEREQUEST 3
  59. static void serialise_autotune_request(char *buf, AutoTuneRequest *aq);
  60. #define CONFIG_PW1 (1<<0)
  61. #define CONFIG_PW2 (1<<1)
  62. // Possible core voltage settings on PW1 & PW2, used by legacy V3 config only
  63. #define CONFIG_CORE_065V 0
  64. #define CONFIG_CORE_075V CONFIG_PW2
  65. #define CONFIG_CORE_085V CONFIG_PW1
  66. #define CONFIG_CORE_095V (CONFIG_PW1|CONFIG_PW2)
  67. /* V3 config is for backwards compatibility with older firmwares */
  68. typedef struct {
  69. uint8_t core_voltage; // Set to flags defined above
  70. uint8_t int_clock_level; // Clock level (30-48 without divider), see asic.c for details
  71. uint8_t clock_div2; // Apply the /2 clock divider (both internal and external)
  72. uint8_t use_ext_clock; // Ignored on boards without external clocks
  73. uint16_t ext_clock_freq;
  74. } BoardConfigV3;
  75. #define SZ_SERIALISED_BOARDCONFIG 6
  76. static void serialise_board_configV4(char *buf, BoardConfig *boardconfig);
  77. static void serialise_board_configV3(char *buf, BoardConfigV3 *boardconfig);
  78. typedef struct {
  79. uint8_t protocol_version;
  80. char product[8];
  81. uint32_t serial;
  82. uint8_t num_chips;
  83. uint16_t capabilities;
  84. } Identity;
  85. /* Capabilities flags known to cgminer */
  86. #define CAP_TEMP (1<<0)
  87. #define CAP_EXT_CLOCK (1<<1)
  88. #define CAP_IS_AVALON (1<<2)
  89. #define CAP_LIMITER_REMOVED (1<<3)
  90. #define SZ_SERIALISED_IDENTITY 16
  91. static void deserialise_identity(Identity *identity, const char *buf);
  92. // Hashable structure of per-device config settings
  93. typedef struct {
  94. char key[9];
  95. BoardConfig config;
  96. UT_hash_handle hh;
  97. } config_setting;
  98. static config_setting *settings;
  99. static void drillbit_empty_buffer(struct cgpu_info *drillbit);
  100. /* Automatic tuning parameters */
  101. static uint32_t auto_every = 100;
  102. static uint32_t auto_good = 1;
  103. static uint32_t auto_bad = 3;
  104. static uint32_t auto_max = 10;
  105. /* Return a pointer to the chip_info structure for a given chip id, or NULL otherwise */
  106. static struct drillbit_chip_info *find_chip(struct drillbit_info *info, uint16_t chip_id) {
  107. int i;
  108. for (i = 0; i < info->num_chips; i++) {
  109. if (info->chips[i].chip_id == chip_id)
  110. return &info->chips[i];
  111. }
  112. return NULL;
  113. }
  114. /* Read a fixed size buffer back from USB, returns true on success */
  115. static bool usb_read_fixed_size(struct cgpu_info *drillbit, void *result, size_t result_size, int timeout, enum usb_cmds command_name) {
  116. char *res = (char *)result;
  117. int ms_left;
  118. size_t count;
  119. struct timeval tv_now, tv_start;
  120. int amount;
  121. cgtime(&tv_start);
  122. ms_left = timeout;
  123. amount = 1;
  124. count = 0;
  125. while (count < result_size && ms_left > 0) {
  126. usb_read_timeout(drillbit, &res[count], result_size-count, &amount, ms_left, command_name);
  127. count += amount;
  128. cgtime(&tv_now);
  129. ms_left = timeout - ms_tdiff(&tv_now, &tv_start);
  130. }
  131. if (count == result_size) {
  132. return true;
  133. }
  134. drvlog(LOG_ERR, "Read incomplete fixed size packet - got %d bytes / %d (timeout %d)",
  135. (int)count, (int)result_size, timeout);
  136. drillbit_empty_buffer(drillbit);
  137. return false;
  138. }
  139. static bool usb_read_simple_response(struct cgpu_info *drillbit, char command, enum usb_cmds command_name);
  140. /* Write a simple one-byte command and expect a simple one-byte response
  141. Returns true on success
  142. */
  143. static bool usb_send_simple_command(struct cgpu_info *drillbit, char command, enum usb_cmds command_name) {
  144. int amount;
  145. usb_write_timeout(drillbit, &command, 1, &amount, TIMEOUT, C_BF_REQWORK);
  146. if (amount != 1) {
  147. drvlog(LOG_ERR, "Failed to write command %c", command);
  148. return false;
  149. }
  150. return usb_read_simple_response(drillbit, command, command_name);
  151. }
  152. /* Read a simple single-byte response and check it matches the correct command character
  153. Return true on success
  154. */
  155. static bool usb_read_simple_response(struct cgpu_info *drillbit, char command, enum usb_cmds command_name) {
  156. int amount;
  157. char response;
  158. /* Expect a single byte, matching the command, as acknowledgement */
  159. usb_read_timeout(drillbit, &response, 1, &amount, TIMEOUT, command_name);
  160. if (amount != 1) {
  161. drvlog(LOG_ERR, "Got no response to command %c", command);
  162. return false;
  163. }
  164. if (response != command) {
  165. drvlog(LOG_ERR, "Got unexpected response %c to command %c", response, command);
  166. return false;
  167. }
  168. return true;
  169. }
  170. #define EMPTY_TIMEOUT 5
  171. static void drillbit_empty_buffer(struct cgpu_info *drillbit)
  172. {
  173. char buf[512];
  174. int amount;
  175. do {
  176. usb_read_timeout(drillbit, buf, sizeof(buf), &amount, EMPTY_TIMEOUT, C_BF_FLUSH);
  177. } while (amount);
  178. }
  179. static void drillbit_open(struct cgpu_info *drillbit)
  180. {
  181. drillbit_empty_buffer(drillbit);
  182. }
  183. static void drillbit_close(struct cgpu_info *drillbit)
  184. {
  185. struct drillbit_info *info = drillbit->device_data;
  186. drillbit_empty_buffer(drillbit);
  187. if (info->chips)
  188. free(info->chips);
  189. }
  190. static void drillbit_identify(struct cgpu_info *drillbit)
  191. {
  192. usb_send_simple_command(drillbit, 'L', C_BF_IDENTIFY);
  193. }
  194. #define ID_TIMEOUT 1000
  195. static bool drillbit_getinfo(struct cgpu_info *drillbit, struct drillbit_info *info)
  196. {
  197. int err;
  198. int amount;
  199. char buf[SZ_SERIALISED_IDENTITY];
  200. Identity identity;
  201. drillbit_empty_buffer(drillbit);
  202. err = usb_write_timeout(drillbit, "I", 1, &amount, TIMEOUT, C_BF_REQINFO);
  203. if (err) {
  204. drvlog(LOG_INFO, "Failed to write REQINFO");
  205. return false;
  206. }
  207. // can't call usb_read_fixed_size here as stats not initialised
  208. err = usb_read_timeout(drillbit, buf, SZ_SERIALISED_IDENTITY, &amount, ID_TIMEOUT, C_BF_GETINFO);
  209. if (err) {
  210. drvlog(LOG_ERR, "Failed to read GETINFO");
  211. return false;
  212. }
  213. if (amount != SZ_SERIALISED_IDENTITY) {
  214. drvlog(LOG_ERR, "Getinfo received %d bytes instead of %d",
  215. amount, (int)sizeof(Identity));
  216. return false;
  217. }
  218. deserialise_identity(&identity, buf);
  219. // sanity checks on the identity buffer we get back
  220. if (strlen(identity.product) == 0 || identity.serial == 0 || identity.num_chips == 0) {
  221. drvlog(LOG_ERR, "Got invalid contents for GETINFO identity response");
  222. return false;
  223. }
  224. const int MIN_VERSION = 2;
  225. const int MAX_VERSION = 4;
  226. if (identity.protocol_version < MIN_VERSION) {
  227. drvlog(LOG_ERR, "Unknown device protocol version %d.", identity.protocol_version);
  228. return false;
  229. }
  230. if (identity.protocol_version > MAX_VERSION) {
  231. drvlog(LOG_ERR, "Device firmware uses newer Drillbit protocol %d. We only support up to %d. Find a newer cgminer!", identity.protocol_version, MAX_VERSION);
  232. return false;
  233. }
  234. if (identity.protocol_version == 2 && identity.num_chips == 1) {
  235. // Production firmware Thumbs don't set any capability bits, so fill in the EXT_CLOCK one
  236. identity.capabilities = CAP_EXT_CLOCK;
  237. }
  238. // load identity data into device info structure
  239. info->protocol_version = identity.protocol_version;
  240. if (strncmp(identity.product, "DRILLBIT", sizeof(identity.product)) == 0) {
  241. // Hack: first production firmwares all described themselves as DRILLBIT, so fill in the gaps
  242. if (identity.num_chips == 1)
  243. strcpy(info->product, "Thumb");
  244. else
  245. strcpy(info->product, "Eight");
  246. } else {
  247. memcpy(info->product, identity.product, sizeof(identity.product));
  248. }
  249. info->serial = identity.serial;
  250. info->num_chips = identity.num_chips;
  251. info->capabilities = identity.capabilities;
  252. drvlog(LOG_INFO, "Getinfo returned version %d, product %s serial %08x num_chips %d",
  253. info->protocol_version, info->product, info->serial, info->num_chips);
  254. drillbit_empty_buffer(drillbit);
  255. return true;
  256. }
  257. static bool drillbit_reset(struct cgpu_info *drillbit)
  258. {
  259. struct drillbit_info *info = drillbit->device_data;
  260. struct drillbit_chip_info *chip;
  261. int i, k, res;
  262. res = usb_send_simple_command(drillbit, 'R', C_BF_REQRESET);
  263. for (i = 0; i < info->num_chips; i++) {
  264. chip = &info->chips[i];
  265. chip->state = IDLE;
  266. chip->work_sent_count = 0;
  267. for (k = 0; k < WORK_HISTORY_LEN-1; k++) {
  268. if (chip->current_work[k]) {
  269. work_completed(drillbit, chip->current_work[k]);
  270. chip->current_work[k] = NULL;
  271. }
  272. }
  273. }
  274. drillbit_empty_buffer(drillbit);
  275. return res;
  276. }
  277. static config_setting *find_settings(struct cgpu_info *drillbit)
  278. {
  279. struct drillbit_info *info = drillbit->device_data;
  280. config_setting *setting;
  281. char search_key[9];
  282. if (!settings) {
  283. drvlog(LOG_INFO, "Keeping onboard defaults for device %s (serial %08x)",
  284. info->product, info->serial);
  285. return NULL;
  286. }
  287. // Search by serial
  288. sprintf(search_key, "%08x", info->serial);
  289. HASH_FIND_STR(settings, search_key, setting);
  290. if (setting) {
  291. drvlog(LOG_INFO, "Using serial specific settings for serial %s", search_key);
  292. return setting;
  293. }
  294. // Search by DRBxxx
  295. snprintf(search_key, 9, "DRB%d", drillbit->device_id);
  296. HASH_FIND_STR(settings, search_key, setting);
  297. if (setting) {
  298. drvlog(LOG_INFO, "Using device_id specific settings for device");
  299. return setting;
  300. }
  301. // Failing that, search by product name
  302. HASH_FIND_STR(settings, info->product, setting);
  303. if (setting) {
  304. drvlog(LOG_INFO, "Using product-specific settings for device %s", info->product);
  305. return setting;
  306. }
  307. // Search by "short" product name
  308. snprintf(search_key, 9, "%c%d", info->product[0], info->num_chips);
  309. HASH_FIND_STR(settings, search_key, setting);
  310. if (setting) {
  311. drvlog(LOG_INFO, "Using product-specific settings for device %s", info->product);
  312. return setting;
  313. }
  314. // Check for a generic/catchall drillbit-options argument (key set to NULL)
  315. search_key[0] = 0;
  316. HASH_FIND_STR(settings, search_key, setting);
  317. if (setting) {
  318. drvlog(LOG_INFO, "Using non-specific settings for device %s (serial %08x)", info->product,
  319. info->serial);
  320. return setting;
  321. }
  322. drvlog(LOG_WARNING, "Keeping onboard defaults for device %s (serial %08x)",
  323. info->product, info->serial);
  324. return NULL;
  325. }
  326. static void drillbit_send_config(struct cgpu_info *drillbit)
  327. {
  328. struct drillbit_info *info = drillbit->device_data;
  329. int amount;
  330. char buf[SZ_SERIALISED_BOARDCONFIG+1];
  331. config_setting *setting;
  332. BoardConfigV3 v3_config;
  333. // Find the relevant board config
  334. setting = find_settings(drillbit);
  335. if (!setting)
  336. return; // Don't update board config from defaults
  337. drvlog(LOG_NOTICE, "Config: %s:%d:%d:%d Serial: %08x",
  338. setting->config.use_ext_clock ? "ext" : "int",
  339. setting->config.clock_freq,
  340. setting->config.clock_div2 ? 2 : 1,
  341. setting->config.core_voltage,
  342. info->serial);
  343. if (setting->config.use_ext_clock && !(info->capabilities & CAP_EXT_CLOCK)) {
  344. drvlog(LOG_WARNING, "Chosen configuration specifies external clock but this device (serial %08x) has no external clock!", info->serial);
  345. }
  346. if (info->protocol_version <= 3) {
  347. /* Make up a backwards compatible V3 config structure to send to the miner */
  348. if (setting->config.core_voltage >= 950)
  349. v3_config.core_voltage = CONFIG_CORE_095V;
  350. else if (setting->config.core_voltage >= 850)
  351. v3_config.core_voltage = CONFIG_CORE_085V;
  352. else if (setting->config.core_voltage >= 750)
  353. v3_config.core_voltage = CONFIG_CORE_075V;
  354. else
  355. v3_config.core_voltage = CONFIG_CORE_065V;
  356. if (setting->config.clock_freq > 64)
  357. v3_config.int_clock_level = setting->config.clock_freq / 5;
  358. else
  359. v3_config.int_clock_level = setting->config.clock_freq;
  360. v3_config.clock_div2 = setting->config.clock_div2;
  361. v3_config.use_ext_clock = setting->config.use_ext_clock;
  362. v3_config.ext_clock_freq = setting->config.clock_freq;
  363. serialise_board_configV3(&buf[1], &v3_config);
  364. } else {
  365. serialise_board_configV4(&buf[1], &setting->config);
  366. }
  367. buf[0] = 'C';
  368. usb_write_timeout(drillbit, buf, sizeof(buf), &amount, TIMEOUT, C_BF_CONFIG);
  369. /* Expect a single 'C' byte as acknowledgement */
  370. usb_read_simple_response(drillbit, 'C', C_BF_CONFIG); // TODO: verify response
  371. }
  372. static void drillbit_updatetemps(struct thr_info *thr)
  373. {
  374. struct cgpu_info *drillbit = thr->cgpu;
  375. struct drillbit_info *info = drillbit->device_data;
  376. char cmd;
  377. int amount;
  378. uint16_t temp;
  379. struct timeval tv_now;
  380. if (!(info->capabilities & CAP_TEMP))
  381. return;
  382. cgtime(&tv_now);
  383. if (ms_tdiff(&tv_now, &info->tv_lasttemp) < 1000)
  384. return; // Only update temps once a second
  385. info->tv_lasttemp = tv_now;
  386. cmd = 'T';
  387. usb_write_timeout(drillbit, &cmd, 1, &amount, TIMEOUT, C_BF_GETTEMP);
  388. if (!usb_read_fixed_size(drillbit, &temp, sizeof(temp), TIMEOUT, C_BF_GETTEMP)) {
  389. drvlog(LOG_ERR, "Got no response to request for current temperature");
  390. return;
  391. }
  392. drvlog(LOG_INFO, "Got temperature reading %d.%dC", temp/10, temp%10);
  393. info->temp = temp;
  394. if (temp > info->max_temp)
  395. info->max_temp = temp;
  396. }
  397. static void drillbit_get_statline_before(char *buf, size_t bufsiz, struct cgpu_info *drillbit)
  398. {
  399. struct drillbit_info *info = drillbit->device_data;
  400. if ((info->capabilities & CAP_TEMP) && info->temp != 0) {
  401. tailsprintf(buf, bufsiz, "%c%2d %.1fC max%.1fC",
  402. info->product[0],
  403. info->num_chips,
  404. (float)(info->temp/10.0),
  405. (float)(info->max_temp/10.0));
  406. } else {
  407. tailsprintf(buf, bufsiz, "%c%2d",
  408. info->product[0],
  409. info->num_chips);
  410. }
  411. }
  412. static bool drillbit_parse_options(__maybe_unused struct cgpu_info *drillbit)
  413. {
  414. /* Read configuration options (currently global not per-ASIC or per-board) */
  415. if (settings != NULL)
  416. return true; // Already initialised
  417. char *next_opt = opt_drillbit_options;
  418. while (next_opt && strlen(next_opt)) {
  419. BoardConfig parsed_config;
  420. config_setting *new_setting;
  421. char key[9];
  422. int count, freq, clockdiv, voltage;
  423. char clksrc[4];
  424. // Try looking for an option tagged with a key, first
  425. count = sscanf(next_opt, "%8[^:]:%3s:%d:%d:%d", key,
  426. clksrc, &freq, &clockdiv, &voltage);
  427. if (count < 5) {
  428. key[0] = 0;
  429. count = sscanf(next_opt, "%3s:%d:%d:%d",
  430. clksrc, &freq, &clockdiv, &voltage);
  431. if (count < 4) {
  432. quithere(1, "Failed to parse drillbit-options. Invalid options string: '%s'", next_opt);
  433. }
  434. }
  435. if (clockdiv != 1 && clockdiv != 2) {
  436. quithere(1, "Invalid clock divider value %d. Valid values are 1 & 2.", clockdiv);
  437. }
  438. parsed_config.clock_div2 = count > 2 && clockdiv == 2;
  439. if (!strcmp("int",clksrc)) {
  440. parsed_config.use_ext_clock = 0;
  441. }
  442. else if (!strcmp("ext", clksrc)) {
  443. parsed_config.use_ext_clock = 1;
  444. } else
  445. quithere(1, "Invalid clock source. Valid choices are int, ext.");
  446. parsed_config.clock_freq = freq;
  447. parsed_config.core_voltage = voltage;
  448. // Add the new set of settings to the configuration choices hash table
  449. new_setting = (config_setting *)calloc(sizeof(config_setting), 1);
  450. memcpy(&new_setting->config, &parsed_config, sizeof(BoardConfig));
  451. memcpy(&new_setting->key, key, 8);
  452. config_setting *ignore;
  453. HASH_REPLACE_STR(settings, key, new_setting, ignore);
  454. // Look for next comma-delimited Drillbit option
  455. next_opt = strstr(next_opt, ",");
  456. if (next_opt)
  457. next_opt++;
  458. }
  459. if (opt_drillbit_auto) {
  460. sscanf(opt_drillbit_auto, "%d:%d:%d:%d",
  461. &auto_every, &auto_good, &auto_bad, &auto_max);
  462. if (auto_max < auto_bad) {
  463. quithere(1, "Bad drillbit-auto: MAX limit must be greater than BAD limit");
  464. }
  465. if (auto_bad < auto_good) {
  466. quithere(1, "Bad drillbit-auto: GOOD limit must be greater than BAD limit");
  467. }
  468. }
  469. return true;
  470. }
  471. static struct cgpu_info *drillbit_detect_one(struct libusb_device *dev, struct usb_find_devices *found)
  472. {
  473. struct cgpu_info *drillbit;
  474. struct drillbit_info *info;
  475. int i;
  476. drillbit = usb_alloc_cgpu(&drillbit_drv, 1);
  477. drillbit->device_id = -1; // so drvlog() prints dname
  478. if (!drillbit_parse_options(drillbit))
  479. goto out;
  480. if (!usb_init(drillbit, dev, found))
  481. goto out;
  482. drvlog(LOG_INFO, "Device found at %s", drillbit->device_path);
  483. info = calloc(sizeof(struct drillbit_info), 1);
  484. if (!info)
  485. quit(1, "Failed to calloc info in %s", __func__);
  486. drillbit->device_data = info;
  487. drillbit_open(drillbit);
  488. /* Send getinfo request */
  489. if (!drillbit_getinfo(drillbit, info))
  490. goto out_close;
  491. /* TODO: Add detection for actual chip ids based on command/response,
  492. not prefill assumption about chip layout based on info structure */
  493. info->chips = calloc(sizeof(struct drillbit_chip_info), info->num_chips);
  494. for (i = 0; i < info->num_chips; i++) {
  495. info->chips[i].chip_id = i;
  496. info->chips[i].auto_max = 999;
  497. }
  498. /* Send reset request */
  499. if (!drillbit_reset(drillbit))
  500. goto out_close;
  501. drillbit_identify(drillbit);
  502. drillbit_empty_buffer(drillbit);
  503. cgtime(&info->tv_lastchipinfo);
  504. if (!add_cgpu(drillbit))
  505. goto out_close;
  506. update_usb_stats(drillbit);
  507. if (info->capabilities & CAP_LIMITER_REMOVED) {
  508. drvlog(LOG_WARNING, "Recommended limits have been disabled on this board, take care when changing settings.");
  509. }
  510. drillbit_send_config(drillbit);
  511. drvlog(LOG_INFO, "Successfully initialised %s",
  512. drillbit->device_path);
  513. return drillbit;
  514. out_close:
  515. drillbit_close(drillbit);
  516. usb_uninit(drillbit);
  517. out:
  518. drillbit = usb_free_cgpu(drillbit);
  519. return drillbit;
  520. }
  521. static void drillbit_detect(bool __maybe_unused hotplug)
  522. {
  523. usb_detect(&drillbit_drv, drillbit_detect_one);
  524. }
  525. static uint32_t decnonce(uint32_t in)
  526. {
  527. uint32_t out;
  528. /* First part load */
  529. out = (in & 0xFF) << 24; in >>= 8;
  530. /* Byte reversal */
  531. in = (((in & 0xaaaaaaaa) >> 1) | ((in & 0x55555555) << 1));
  532. in = (((in & 0xcccccccc) >> 2) | ((in & 0x33333333) << 2));
  533. in = (((in & 0xf0f0f0f0) >> 4) | ((in & 0x0f0f0f0f) << 4));
  534. out |= (in >> 2)&0x3FFFFF;
  535. /* Extraction */
  536. if (in & 1) out |= (1 << 23);
  537. if (in & 2) out |= (1 << 22);
  538. out -= 0x800004;
  539. return out;
  540. }
  541. #define BF_OFFSETS 3
  542. static const uint32_t bf_offsets[] = {-0x800000, 0, -0x400000};
  543. static bool drillbit_checkresults(struct thr_info *thr, struct work *work, uint32_t nonce)
  544. {
  545. struct cgpu_info *drillbit = thr->cgpu;
  546. struct drillbit_info *info = drillbit->device_data;
  547. int i;
  548. if (info->capabilities & CAP_IS_AVALON) {
  549. if (test_nonce(work, nonce)) {
  550. submit_tested_work(thr, work);
  551. return true;
  552. }
  553. }
  554. else { /* Bitfury */
  555. nonce = decnonce(nonce);
  556. for (i = 0; i < BF_OFFSETS; i++) {
  557. if (test_nonce(work, nonce + bf_offsets[i])) {
  558. submit_tested_work(thr, work);
  559. return true;
  560. }
  561. }
  562. }
  563. return false;
  564. }
  565. /* Check if this ASIC should be tweaked up or down in clock speed */
  566. static void drillbit_check_auto(struct thr_info *thr, struct drillbit_chip_info *chip)
  567. {
  568. struct cgpu_info *drillbit = thr->cgpu;
  569. AutoTuneRequest request;
  570. char buf[SZ_SERIALISED_AUTOTUNEREQUEST+1];
  571. int amount;
  572. bool tune_up, tune_down;
  573. /*
  574. Only check automatic tuning every "auto_every" work units,
  575. or if the error count exceeds the 'max' count
  576. */
  577. if (chip->success_auto + chip->error_auto < auto_every &&
  578. (chip->error_auto < auto_max))
  579. return;
  580. tune_up = chip->error_auto < auto_good && chip->auto_delta < chip->auto_max;
  581. tune_down = chip->error_auto > auto_bad;
  582. drvlog(tune_up||tune_down ? LOG_NOTICE : LOG_DEBUG,
  583. "Chip id %d has %d/%d error rate %s", chip->chip_id, chip->error_auto,
  584. chip->error_auto + chip->success_auto,
  585. tune_up ? " - tuning up" : tune_down ? " - tuning down" : " - no change");
  586. if (tune_up || tune_down) {
  587. /* Value should be tweaked */
  588. buf[0] = 'A';
  589. request.chip_id = chip->chip_id;
  590. request.increase_clock = tune_up;
  591. serialise_autotune_request(&buf[1], &request);
  592. usb_write_timeout(drillbit, buf, sizeof(buf), &amount, TIMEOUT, C_BF_AUTOTUNE);
  593. usb_read_simple_response(drillbit, 'A', C_BF_AUTOTUNE);
  594. if (tune_up) {
  595. chip->auto_delta++;
  596. } else {
  597. chip->auto_delta--;
  598. if (chip->error_auto >= auto_max
  599. && chip->success_count + chip->error_count > auto_every) {
  600. drvlog(LOG_ERR, "Chip id %d capping auto delta at max %d",chip->chip_id,
  601. chip->auto_delta);
  602. chip->auto_max = chip->auto_delta;
  603. }
  604. }
  605. }
  606. chip->success_auto = 0;
  607. chip->error_auto = 0;
  608. }
  609. // Check and submit back any pending work results from firmware,
  610. // returns number of successful results found
  611. static int check_for_results(struct thr_info *thr)
  612. {
  613. struct cgpu_info *drillbit = thr->cgpu;
  614. struct drillbit_info *info = drillbit->device_data;
  615. struct drillbit_chip_info *chip;
  616. char cmd;
  617. int amount, i, k, found;
  618. uint8_t j;
  619. int successful_results = 0;
  620. uint32_t result_count;
  621. char buf[SZ_SERIALISED_WORKRESULT];
  622. WorkResult *responses = NULL;
  623. WorkResult *response;
  624. if (unlikely(thr->work_restart))
  625. goto cleanup;
  626. // Send request for completed work
  627. cmd = 'E';
  628. usb_write_timeout(drillbit, &cmd, 1, &amount, TIMEOUT, C_BF_GETRES);
  629. // Receive count for work results
  630. if (!usb_read_fixed_size(drillbit, &result_count, sizeof(result_count), TIMEOUT, C_BF_GETRES)) {
  631. drvlog(LOG_ERR, "Got no response to request for work results");
  632. goto cleanup;
  633. }
  634. if (unlikely(drillbit->usbinfo.nodev))
  635. goto cleanup;
  636. if (result_count)
  637. drvlog(LOG_DEBUG, "Result count %d",result_count);
  638. if (result_count > 1024) {
  639. drvlog(LOG_ERR, "Got implausible result count %d - treating as error!", result_count);
  640. goto cleanup;
  641. }
  642. if (result_count == 0) {
  643. // Short circuit reading any work results
  644. return 0;
  645. }
  646. responses = calloc(result_count, sizeof(WorkResult));
  647. // Receive work results (0 or more) into buffer
  648. for (j = 0; j < result_count; j++) {
  649. if (unlikely(drillbit->usbinfo.nodev))
  650. goto cleanup;
  651. if (!usb_read_fixed_size(drillbit, buf, SZ_SERIALISED_WORKRESULT, TIMEOUT, C_BF_GETRES)) {
  652. drvlog(LOG_ERR, "Failed to read response data packet idx %d count 0x%x", j, result_count);
  653. drillbit_empty_buffer(drillbit);
  654. goto cleanup;
  655. }
  656. deserialise_work_result(&responses[j], buf);
  657. }
  658. for (j = 0; j < result_count; j++) {
  659. if (unlikely(thr->work_restart))
  660. goto cleanup;
  661. response = &responses[j];
  662. drvlog(LOG_DEBUG, "Got response packet chip_id %d nonces %d is_idle %d", response->chip_id, response->num_nonces, response->is_idle);
  663. chip = find_chip(info, response->chip_id);
  664. if (!chip) {
  665. drvlog(LOG_ERR, "Got work result for unknown chip id %d", response->chip_id);
  666. drillbit_empty_buffer(drillbit);
  667. continue;
  668. }
  669. if (chip->state == IDLE) {
  670. drvlog(LOG_WARNING, "Got spurious work results for idle ASIC %d", response->chip_id);
  671. }
  672. if (response->num_nonces > MAX_RESULTS) {
  673. drvlog(LOG_ERR, "Got invalid number of result nonces (%d) for chip id %d", response->num_nonces, response->chip_id);
  674. drillbit_empty_buffer(drillbit);
  675. goto cleanup;
  676. }
  677. found = false;
  678. for (i = 0; i < response->num_nonces; i++) {
  679. if (unlikely(thr->work_restart))
  680. goto cleanup;
  681. for (k = 0; k < WORK_HISTORY_LEN; k++) {
  682. /* NB we deliberately check all results against all work because sometimes ASICs seem to give multiple "valid" nonces,
  683. and this seems to avoid some result that would otherwise be rejected by the pool.
  684. */
  685. if (chip->current_work[k] && drillbit_checkresults(thr, chip->current_work[k], response->nonce[i])) {
  686. chip->success_count++;
  687. chip->success_auto++;
  688. successful_results++;
  689. found = true;
  690. }
  691. }
  692. }
  693. drvlog(LOG_DEBUG, "%s nonce %08x", (found ? "Good":"Bad"), response->num_nonces ? response->nonce[0] : 0);
  694. if (!found && chip->state != IDLE && response->num_nonces > 0) {
  695. /* all nonces we got back from this chip were invalid */
  696. inc_hw_errors(thr);
  697. chip->error_count++;
  698. chip->error_auto++;
  699. }
  700. if (chip->state == WORKING_QUEUED && !response->is_idle)
  701. chip->state = WORKING_NOQUEUED; // Time to queue up another piece of "next work"
  702. else
  703. chip->state = IDLE; // Uh-oh, we're totally out of work for this ASIC!
  704. if (opt_drillbit_auto && info->protocol_version >= 4)
  705. drillbit_check_auto(thr, chip);
  706. }
  707. cleanup:
  708. if (responses)
  709. free(responses);
  710. return successful_results;
  711. }
  712. static void drillbit_send_work_to_chip(struct thr_info *thr, struct drillbit_chip_info *chip)
  713. {
  714. struct cgpu_info *drillbit = thr->cgpu;
  715. struct work *work;
  716. char buf[SZ_SERIALISED_WORKREQUEST+1];
  717. int amount, i;
  718. /* Get some new work for the chip */
  719. work = get_queue_work(thr, drillbit, thr->id);
  720. if (unlikely(thr->work_restart)) {
  721. work_completed(drillbit, work);
  722. return;
  723. }
  724. drvlog(LOG_DEBUG, "Sending work to chip_id %d", chip->chip_id);
  725. serialise_work_request(&buf[1], chip->chip_id, work);
  726. /* Send work to cgminer */
  727. buf[0] = 'W';
  728. usb_write_timeout(drillbit, buf, sizeof(buf), &amount, TIMEOUT, C_BF_REQWORK);
  729. /* Expect a single 'W' byte as acknowledgement */
  730. usb_read_simple_response(drillbit, 'W', C_BF_REQWORK);
  731. if (chip->state == WORKING_NOQUEUED)
  732. chip->state = WORKING_QUEUED;
  733. else
  734. chip->state = WORKING_NOQUEUED;
  735. if (unlikely(thr->work_restart)) {
  736. work_completed(drillbit, work);
  737. return;
  738. }
  739. // Read into work history
  740. if (chip->current_work[0])
  741. work_completed(drillbit, chip->current_work[0]);
  742. for (i = 0; i < WORK_HISTORY_LEN-1; i++)
  743. chip->current_work[i] = chip->current_work[i+1];
  744. chip->current_work[WORK_HISTORY_LEN-1] = work;
  745. cgtime(&chip->tv_start);
  746. chip->work_sent_count++;
  747. }
  748. static int64_t drillbit_scanwork(struct thr_info *thr)
  749. {
  750. struct cgpu_info *drillbit = thr->cgpu;
  751. struct drillbit_info *info = drillbit->device_data;
  752. struct drillbit_chip_info *chip;
  753. struct timeval tv_now;
  754. int amount, i, j, ms_diff, result_count = 0, sent_count = 0;;
  755. char buf[200];
  756. /* send work to an any chip without queued work */
  757. for (i = 0; i < info->num_chips && sent_count < 8; i++) {
  758. if (info->chips[i].state != WORKING_QUEUED) {
  759. drillbit_send_work_to_chip(thr, &info->chips[i]);
  760. sent_count++;
  761. }
  762. if (unlikely(thr->work_restart) || unlikely(drillbit->usbinfo.nodev))
  763. goto cascade;
  764. }
  765. /* check for any chips that have timed out on sending results */
  766. cgtime(&tv_now);
  767. for (i = 0; i < info->num_chips; i++) {
  768. if (info->chips[i].state == IDLE)
  769. continue;
  770. ms_diff = ms_tdiff(&tv_now, &info->chips[i].tv_start);
  771. if (ms_diff > RESULT_TIMEOUT) {
  772. if (info->chips[i].work_sent_count > 4) {
  773. /* Only count ASIC timeouts after the pool has started to send work in earnest,
  774. some pools can create unusual delays early on */
  775. drvlog(LOG_ERR, "Timing out unresponsive ASIC %d", info->chips[i].chip_id);
  776. info->chips[i].timeout_count++;
  777. info->chips[i].error_auto++;
  778. }
  779. info->chips[i].state = IDLE;
  780. drillbit_send_work_to_chip(thr, &info->chips[i]);
  781. }
  782. if (unlikely(thr->work_restart) || unlikely(drillbit->usbinfo.nodev))
  783. goto cascade;
  784. }
  785. /* Check for results */
  786. result_count = check_for_results(thr);
  787. /* Print a per-chip info line every 30 seconds */
  788. cgtime(&tv_now);
  789. if (opt_log_level <= LOG_INFO && ms_tdiff(&tv_now, &info->tv_lastchipinfo) > 30000) {
  790. /* TODO: this output line may get truncated (max debug is 256 bytes) once we get more
  791. chips in a single device
  792. */
  793. amount = sprintf(buf, "%s %d: S/E/T", drillbit->drv->name, drillbit->device_id);
  794. if (amount > 0) {
  795. for (i = 0; i < info->num_chips; i++) {
  796. chip= &info->chips[i];
  797. j = snprintf(&buf[amount], sizeof(buf)-(size_t)amount, "%u:%u/%u/%u",
  798. chip->chip_id, chip->success_count, chip->error_count,
  799. chip->timeout_count);
  800. if (j < 0)
  801. break;
  802. amount += j;
  803. if ((size_t)amount >= sizeof(buf))
  804. break;
  805. }
  806. drvlog(LOG_INFO, "%s", buf);
  807. cgtime(&info->tv_lastchipinfo);
  808. }
  809. }
  810. drillbit_updatetemps(thr);
  811. cascade:
  812. if (unlikely(drillbit->usbinfo.nodev)) {
  813. drvlog(LOG_WARNING, "Device disappeared, disabling thread");
  814. return -1;
  815. }
  816. if (unlikely(thr->work_restart)) {
  817. /* Issue an ASIC reset as we won't be coming back for any of these results */
  818. drvlog(LOG_DEBUG, "Received work restart, resetting ASIC");
  819. drillbit_reset(drillbit);
  820. }
  821. return 0xffffffffULL * result_count;
  822. }
  823. static struct api_data *drillbit_api_stats(struct cgpu_info *cgpu)
  824. {
  825. struct drillbit_info *info = cgpu->device_data;
  826. struct api_data *root = NULL;
  827. char serial[16];
  828. int version;
  829. version = info->protocol_version;
  830. root = api_add_int(root, "Protocol Version", &version, true);
  831. root = api_add_string(root, "Product", info->product, false);
  832. sprintf(serial, "%08x", info->serial);
  833. root = api_add_string(root, "Serial", serial, true);
  834. root = api_add_uint8(root, "ASIC Count", &info->num_chips, true);
  835. if (info->capabilities & CAP_TEMP) {
  836. float temp = (float)info->temp/10;
  837. root = api_add_temp(root, "Temp", &temp, true);
  838. temp = (float)info->max_temp/10;
  839. root = api_add_temp(root, "Temp Max", &temp, true);
  840. }
  841. return root;
  842. }
  843. static void drillbit_reinit(struct cgpu_info *drillbit)
  844. {
  845. drillbit_close(drillbit);
  846. drillbit_open(drillbit);
  847. drillbit_reset(drillbit);
  848. }
  849. static void drillbit_shutdown(struct thr_info *thr)
  850. {
  851. struct cgpu_info *drillbit = thr->cgpu;
  852. drillbit_close(drillbit);
  853. }
  854. /* Currently hardcoded to BF1 devices */
  855. struct device_drv drillbit_drv = {
  856. .drv_id = DRIVER_drillbit,
  857. .dname = "Drillbit",
  858. .name = "DRB",
  859. .drv_detect = drillbit_detect,
  860. .hash_work = &hash_driver_work,
  861. .scanwork = drillbit_scanwork,
  862. .get_api_stats = drillbit_api_stats,
  863. .get_statline_before = drillbit_get_statline_before,
  864. .reinit_device = drillbit_reinit,
  865. .thread_shutdown = drillbit_shutdown,
  866. .identify_device = drillbit_identify,
  867. };
  868. /* Structure serialisation/deserialisation */
  869. #define SERIALISE(FIELD) do { \
  870. memcpy(&buf[offset], &FIELD, sizeof(FIELD)); \
  871. offset += sizeof(FIELD); \
  872. } while (0)
  873. #define DESERIALISE(FIELD) do { \
  874. memcpy(&FIELD, &buf[offset], sizeof(FIELD)); \
  875. offset += sizeof(FIELD); \
  876. } while (0)
  877. static void serialise_work_request(char *buf, uint16_t chip_id, const struct work *work)
  878. {
  879. size_t offset = 0;
  880. SERIALISE(chip_id);
  881. memcpy(&buf[offset], work->midstate, 32);
  882. offset += 32;
  883. memcpy(&buf[offset], work->data + 64, 12);
  884. //offset += 12;
  885. }
  886. static void deserialise_work_result(WorkResult *wr, const char *buf)
  887. {
  888. int i;
  889. size_t offset = 0;
  890. DESERIALISE(wr->chip_id);
  891. DESERIALISE(wr->num_nonces);
  892. DESERIALISE(wr->is_idle);
  893. for (i = 0; i < MAX_RESULTS; i++)
  894. DESERIALISE(wr->nonce[i]);
  895. }
  896. static void serialise_board_configV3(char *buf, BoardConfigV3 *bc)
  897. {
  898. size_t offset = 0;
  899. SERIALISE(bc->core_voltage);
  900. SERIALISE(bc->int_clock_level);
  901. SERIALISE(bc->clock_div2);
  902. SERIALISE(bc->use_ext_clock);
  903. SERIALISE(bc->ext_clock_freq);
  904. }
  905. static void serialise_board_configV4(char *buf, BoardConfig *bc)
  906. {
  907. size_t offset = 0;
  908. SERIALISE(bc->core_voltage);
  909. SERIALISE(bc->clock_freq);
  910. SERIALISE(bc->clock_div2);
  911. SERIALISE(bc->use_ext_clock);
  912. }
  913. static void serialise_autotune_request(char *buf, AutoTuneRequest *aq)
  914. {
  915. size_t offset = 0;
  916. SERIALISE(aq->chip_id);
  917. SERIALISE(aq->increase_clock);
  918. }
  919. static void deserialise_identity(Identity *id, const char *buf)
  920. {
  921. size_t offset = 0;
  922. DESERIALISE(id->protocol_version);
  923. DESERIALISE(id->product);
  924. DESERIALISE(id->serial);
  925. DESERIALISE(id->num_chips);
  926. DESERIALISE(id->capabilities);
  927. }