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