/ driver-hashratio.c
driver-hashratio.c
  1  /*
  2   * Copyright 2013-2015 Con Kolivas <kernel@kolivas.org>
  3   * Copyright 2012-2014 Xiangfu <xiangfu@openmobilefree.com>
  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  
 11  #include "config.h"
 12  
 13  #include <limits.h>
 14  #include <pthread.h>
 15  #include <stdio.h>
 16  #include <sys/time.h>
 17  #include <sys/types.h>
 18  #include <dirent.h>
 19  #include <unistd.h>
 20  #ifndef WIN32
 21    #include <termios.h>
 22    #include <sys/stat.h>
 23    #include <fcntl.h>
 24    #ifndef O_CLOEXEC
 25      #define O_CLOEXEC 0
 26    #endif
 27  #else
 28    #include <io.h>
 29  #endif
 30  
 31  #include "elist.h"
 32  #include "miner.h"
 33  #include "driver-hashratio.h"
 34  #include "crc.h"
 35  #include "usbutils.h"
 36  
 37  static int opt_hashratio_fan_min = HRTO_DEFAULT_FAN_MIN;
 38  static int opt_hashratio_fan_max = HRTO_DEFAULT_FAN_MAX;
 39  
 40  static int hashratio_freq = HRTO_DEFAULT_FREQUENCY;
 41  
 42  //static int get_fan_pwm(int temp) {
 43  //	int pwm;
 44  //	uint8_t fan_pwm_arr[] = {30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
 45  //		30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
 46  //		30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
 47  //		30, 37, 49, 61, 73, 85, 88, 91, 94, 97, 100, 100, 100, 100, 100, 100,
 48  //		100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
 49  //		100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
 50  //		100, 100, 100, 100, 100, 100, 100};
 51  //	if (temp < 0 || temp >= sizeof(fan_pwm_arr)/sizeof(fan_pwm_arr[0]) ||
 52  //		fan_pwm_arr[temp] > opt_hashratio_fan_max) {
 53  //		return opt_hashratio_fan_max;
 54  //	}
 55  //	pwm = HRTO_PWM_MAX - fan_pwm_arr[temp] * HRTO_PWM_MAX / 100;
 56  //
 57  //	if (pwm < opt_hashratio_fan_min) {
 58  //		return opt_hashratio_fan_min;
 59  //	}
 60  //	if (pwm > opt_hashratio_fan_max) {
 61  //		return opt_hashratio_fan_max;
 62  //	}
 63  //	return pwm;
 64  //}
 65  
 66  char *set_hashratio_freq(char *arg)
 67  {
 68  	int val, ret;
 69  	
 70  	ret = sscanf(arg, "%d", &val);
 71  	if (ret != 1)
 72  		return "No values passed to hashratio-freq";
 73  	
 74  	if (val < HRTO_DEFAULT_FREQUENCY_MIN || val > HRTO_DEFAULT_FREQUENCY_MAX)
 75  		return "Invalid value passed to hashratio-freq";
 76  
 77  	hashratio_freq = val;
 78  	
 79  	return NULL;
 80  }
 81  
 82  char *set_hashratio_fan(char *arg)
 83  {
 84  	int val1, val2, ret;
 85  
 86  	ret = sscanf(arg, "%d-%d", &val1, &val2);
 87  	if (ret < 1)
 88  		return "No values passed to hashratio-fan";
 89  	if (ret == 1)
 90  		val2 = val1;
 91  
 92  	if (val1 < 0 || val1 > 100 || val2 < 0 || val2 > 100 || val2 < val1)
 93  		return "Invalid value passed to hashratio-fan";
 94  
 95  	opt_hashratio_fan_min = val1 * HRTO_PWM_MAX / 100;
 96  	opt_hashratio_fan_max = val2 * HRTO_PWM_MAX / 100;
 97  
 98  	return NULL;
 99  }
100  
101  static int hashratio_init_pkg(struct hashratio_pkg *pkg, uint8_t type,
102  							  uint8_t idx, uint8_t cnt)
103  {
104  	unsigned short crc;
105  
106  	pkg->head[0] = HRTO_H1;
107  	pkg->head[1] = HRTO_H2;
108  
109  	pkg->type = type;
110  	pkg->idx = idx;
111  	pkg->cnt = cnt;
112  
113  	crc = crc16(pkg->data, HRTO_P_DATA_LEN);
114  
115  	pkg->crc[0] = (crc & 0xff00) >> 8;
116  	pkg->crc[1] = crc & 0x00ff;
117  	return 0;
118  }
119  
120  static int job_idcmp(uint8_t *job_id, char *pool_job_id)
121  {
122  	int job_id_len;
123  	unsigned short crc, crc_expect;
124  
125  	if (!pool_job_id)
126  		return 1;
127  
128  	job_id_len = strlen(pool_job_id);
129  	crc_expect = crc16((const unsigned char *)pool_job_id, job_id_len);
130  
131  	crc = job_id[0] << 8 | job_id[1];
132  
133  	if (crc_expect == crc)
134  		return 0;
135  
136  	applog(LOG_DEBUG, "Hashratio: job_id not match! [%04x:%04x (%s)]",
137  	       crc, crc_expect, pool_job_id);
138  
139  	return 1;
140  }
141  
142  static int decode_pkg(struct thr_info *thr, struct hashratio_ret *ar, uint8_t *pkg)
143  {
144  	struct cgpu_info *hashratio = thr->cgpu;
145  	struct hashratio_info *info = hashratio->device_data;
146  	struct pool *pool, *real_pool, *pool_stratum = &info->pool;
147  
148  	unsigned int expected_crc;
149  	unsigned int actual_crc;
150  	uint32_t nonce, nonce2, miner;
151  	int pool_no;
152  	uint8_t job_id[4];
153  	int tmp;
154  
155  	int type = HRTO_GETS_ERROR;
156  
157  	memcpy((uint8_t *)ar, pkg, HRTO_READ_SIZE);
158  
159  //	applog(LOG_DEBUG, "pkg.type, hex: %02x, dec: %d", ar->type, ar->type);
160  	
161  	if (ar->head[0] == HRTO_H1 && ar->head[1] == HRTO_H2) {
162  		expected_crc = crc16(ar->data, HRTO_P_DATA_LEN);
163  		actual_crc = (ar->crc[0] & 0xff) |
164  			((ar->crc[1] & 0xff) << 8);
165  
166  		type = ar->type;
167  		applog(LOG_DEBUG, "hashratio: %d: expected crc(%04x), actual_crc(%04x)", type, expected_crc, actual_crc);
168  		if (expected_crc != actual_crc)
169  			goto out;
170  
171  		switch(type) {
172  		case HRTO_P_NONCE:
173  			applog(LOG_DEBUG, "Hashratio: HRTO_P_NONCE");
174  			memcpy(&miner,   ar->data + 0, 4);
175  			memcpy(&pool_no, ar->data + 4, 4);
176  			memcpy(&nonce2,  ar->data + 8, 4);
177  			/* Calc time    ar->data + 12 */
178  			memcpy(&nonce, ar->data + 12, 4);
179  			memcpy(job_id, ar->data + 16, 4);
180  
181  			miner = be32toh(miner);
182  			pool_no = be32toh(pool_no);
183  			if (miner >= HRTO_DEFAULT_MINERS || pool_no >= total_pools || pool_no < 0) {
184  				applog(LOG_DEBUG, "hashratio: Wrong miner/pool/id no %d,%d", miner, pool_no);
185  				break;
186  			} else
187  				info->matching_work[miner]++;
188  			nonce2 = be32toh(nonce2);
189  			nonce = be32toh(nonce);
190  
191  			applog(LOG_DEBUG, "hashratio: Found! [%s] %d:(%08x) (%08x)",
192  			       job_id, pool_no, nonce2, nonce);
193  
194  			real_pool = pool = pools[pool_no];
195  			if (job_idcmp(job_id, pool->swork.job_id)) {
196  				if (!job_idcmp(job_id, pool_stratum->swork.job_id)) {
197  					applog(LOG_DEBUG, "Hashratio: Match to previous stratum! (%s)", pool_stratum->swork.job_id);
198  					pool = pool_stratum;
199  				} else {
200  					applog(LOG_DEBUG, "Hashratio Cannot match to any stratum! (%s)", pool->swork.job_id);
201  					break;
202  				}
203  			}
204  			submit_nonce2_nonce(thr, pool, real_pool, nonce2, nonce, 0);
205  			break;
206  		case HRTO_P_STATUS:
207  			applog(LOG_DEBUG, "Hashratio: HRTO_P_STATUS");
208  			memcpy(&tmp, ar->data, 4);
209  			tmp = be32toh(tmp);
210  			info->temp = (tmp & 0x00f0) >> 8;
211  			if (info->temp_max < info->temp) {
212  				info->temp_max = info->temp;
213  			}
214  //			info->temp[1] = tmp & 0xffff;
215  
216  			memcpy(&tmp, ar->data + 4, 4);
217  			tmp = be32toh(tmp);
218  			info->fan[0] = tmp >> 16;
219  			info->fan[1] = tmp & 0xffff;
220  
221  			// local_work
222  			memcpy(&tmp, ar->data + 8, 4);
223  			tmp = be32toh(tmp);
224  			info->local_work = tmp;
225  			info->local_works += tmp;
226  			
227  			// hw_work
228  			memcpy(&tmp, ar->data + 12, 4);
229  			tmp = be32toh(tmp);
230  			info->hw_works += tmp;
231  			
232  			hashratio->temp = info->temp;
233  			break;
234  		case HRTO_P_ACKDETECT:
235  			applog(LOG_DEBUG, "Hashratio: HRTO_P_ACKDETECT");
236  			break;
237  		case HRTO_P_ACK:
238  			applog(LOG_DEBUG, "Hashratio: HRTO_P_ACK");
239  			break;
240  		case HRTO_P_NAK:
241  			applog(LOG_DEBUG, "Hashratio: HRTO_P_NAK");
242  			break;
243  		default:
244  			applog(LOG_DEBUG, "Hashratio: HRTO_GETS_ERROR");
245  			type = HRTO_GETS_ERROR;
246  			break;
247  		}
248  	}
249  
250  out:
251  	return type;
252  }
253  
254  static inline int hashratio_gets(struct cgpu_info *hashratio, uint8_t *buf)
255  {
256  	int i;
257  	int read_amount = HRTO_READ_SIZE;
258  	uint8_t buf_tmp[HRTO_READ_SIZE];
259  	uint8_t buf_copy[2 * HRTO_READ_SIZE];
260  	uint8_t *buf_back = buf;
261  	int ret = 0;
262  
263  	while (true) {
264  		int err;
265  
266  		do {
267  			memset(buf, 0, read_amount);
268  			err = usb_read(hashratio, (char *)buf, read_amount, &ret, C_HRO_READ);
269  			if (unlikely(err < 0 || ret != read_amount)) {
270  				applog(LOG_ERR, "hashratio: Error on read in hashratio_gets got %d", ret);
271  				return HRTO_GETS_ERROR;
272  			}
273  			if (likely(ret >= read_amount)) {
274  				for (i = 1; i < read_amount; i++) {
275  					if (buf_back[i - 1] == HRTO_H1 && buf_back[i] == HRTO_H2)
276  						break;
277  				}
278  				i -= 1;
279  				if (i) {
280  					err = usb_read(hashratio, (char *)buf, read_amount, &ret, C_HRO_READ);
281  					if (unlikely(err < 0 || ret != read_amount)) {
282  						applog(LOG_ERR, "hashratio: Error on 2nd read in hashratio_gets got %d", ret);
283  						return HRTO_GETS_ERROR;
284  					}
285  					memcpy(buf_copy, buf_back + i, HRTO_READ_SIZE - i);
286  					memcpy(buf_copy + HRTO_READ_SIZE - i, buf_tmp, i);
287  					memcpy(buf_back, buf_copy, HRTO_READ_SIZE);
288  				}
289  				return HRTO_GETS_OK;
290  			}
291  			buf += ret;
292  			read_amount -= ret;
293  			continue;
294  		} while (ret > 0);
295  
296  		return HRTO_GETS_TIMEOUT;
297  	}
298  }
299  
300  static int hashratio_send_pkg(struct cgpu_info *hashratio, const struct hashratio_pkg *pkg)
301  {
302  	int err, amount;
303  	uint8_t buf[HRTO_WRITE_SIZE];
304  	int nr_len = HRTO_WRITE_SIZE;
305  
306  	memcpy(buf, pkg, HRTO_WRITE_SIZE);
307  //	if (opt_debug) {
308  //		applog(LOG_DEBUG, "hashratio: Sent(%d):", nr_len);
309  //		hexdump((uint8_t *)buf, nr_len);
310  //	}
311  
312  	if (unlikely(hashratio->usbinfo.nodev))
313  		return HRTO_SEND_ERROR;
314  
315  	err = usb_write(hashratio, (char *)buf, nr_len, &amount, C_HRO_WRITE);
316  	if (err || amount != nr_len) {
317  		applog(LOG_DEBUG, "hashratio: Send(%d)!", amount);
318  		return HRTO_SEND_ERROR;
319  	}
320  
321  	return HRTO_SEND_OK;
322  }
323  
324  static int hashratio_send_pkgs(struct cgpu_info *hashratio, const struct hashratio_pkg *pkg)
325  {
326  	int ret;
327  
328  	do {
329  		if (unlikely(hashratio->usbinfo.nodev))
330  			return -1;
331  		ret = hashratio_send_pkg(hashratio, pkg);
332  	} while (ret != HRTO_SEND_OK);
333  	return 0;
334  }
335  
336  static void hashratio_stratum_pkgs(struct cgpu_info *hashratio, struct pool *pool)
337  {
338  	const int merkle_offset = 36;
339  	struct hashratio_pkg pkg;
340  	int i, a, b, tmp;
341  	unsigned char target[32];
342  	int job_id_len;
343  	unsigned short crc;
344  
345  	/* Send out the first stratum message STATIC */
346  	applog(LOG_DEBUG, "hashratio: Pool stratum message STATIC: %d, %d, %d, %d, %d, %d",
347  	       pool->coinbase_len,
348  	       pool->nonce2_offset,
349  	       pool->n2size,
350  	       merkle_offset,
351  	       pool->merkles,
352  		   pool->pool_no);
353  	memset(pkg.data, 0, HRTO_P_DATA_LEN);
354  	tmp = be32toh(pool->coinbase_len);
355  	memcpy(pkg.data, &tmp, 4);
356  
357  	tmp = be32toh(pool->nonce2_offset);
358  	memcpy(pkg.data + 4, &tmp, 4);
359  
360  	tmp = be32toh(pool->n2size);
361  	memcpy(pkg.data + 8, &tmp, 4);
362  
363  	tmp = be32toh(merkle_offset);
364  	memcpy(pkg.data + 12, &tmp, 4);
365  
366  	tmp = be32toh(pool->merkles);
367  	memcpy(pkg.data + 16, &tmp, 4);
368  
369  	tmp = be32toh((int)pool->sdiff);
370  	memcpy(pkg.data + 20, &tmp, 4);
371  
372  	tmp = be32toh((int)pool->pool_no);
373  	memcpy(pkg.data + 24, &tmp, 4);
374  
375  	hashratio_init_pkg(&pkg, HRTO_P_STATIC, 1, 1);
376  	if (hashratio_send_pkgs(hashratio, &pkg))
377  		return;
378  
379  	set_target(target, pool->sdiff);
380  	memcpy(pkg.data, target, 32);
381  	if (opt_debug) {
382  		char *target_str;
383  		target_str = bin2hex(target, 32);
384  		applog(LOG_DEBUG, "hashratio: Pool stratum target: %s", target_str);
385  		free(target_str);
386  	}
387  	hashratio_init_pkg(&pkg, HRTO_P_TARGET, 1, 1);
388  	if (hashratio_send_pkgs(hashratio, &pkg))
389  		return;
390  
391  	applog(LOG_DEBUG, "hashratio: Pool stratum message JOBS_ID: %s",
392  	       pool->swork.job_id);
393  	memset(pkg.data, 0, HRTO_P_DATA_LEN);
394  
395  	job_id_len = strlen(pool->swork.job_id);
396  	crc = crc16((const unsigned char *)pool->swork.job_id, job_id_len);
397  	pkg.data[0] = (crc & 0xff00) >> 8;
398  	pkg.data[1] = crc & 0x00ff;
399  	hashratio_init_pkg(&pkg, HRTO_P_JOB_ID, 1, 1);
400  	if (hashratio_send_pkgs(hashratio, &pkg))
401  		return;
402  
403  	a = pool->coinbase_len / HRTO_P_DATA_LEN;
404  	b = pool->coinbase_len % HRTO_P_DATA_LEN;
405  	applog(LOG_DEBUG, "pool->coinbase_len: %d", pool->coinbase_len);
406  	applog(LOG_DEBUG, "hashratio: Pool stratum message COINBASE: %d %d", a, b);
407  	for (i = 0; i < a; i++) {
408  		memcpy(pkg.data, pool->coinbase + i * 32, 32);
409  		hashratio_init_pkg(&pkg, HRTO_P_COINBASE, i + 1, a + (b ? 1 : 0));
410  		if (hashratio_send_pkgs(hashratio, &pkg))
411  			return;
412  		if (i % 25 == 0) {
413  			cgsleep_ms(2);
414  		}
415  	}
416  	if (b) {
417  		memset(pkg.data, 0, HRTO_P_DATA_LEN);
418  		memcpy(pkg.data, pool->coinbase + i * 32, b);
419  		hashratio_init_pkg(&pkg, HRTO_P_COINBASE, i + 1, i + 1);
420  		if (hashratio_send_pkgs(hashratio, &pkg))
421  			return;
422  	}
423  
424  	b = pool->merkles;
425  	applog(LOG_DEBUG, "hashratio: Pool stratum message MERKLES: %d", b);
426  	for (i = 0; i < b; i++) {
427  		memset(pkg.data, 0, HRTO_P_DATA_LEN);
428  		memcpy(pkg.data, pool->swork.merkle_bin[i], 32);
429  		hashratio_init_pkg(&pkg, HRTO_P_MERKLES, i + 1, b);
430  		if (hashratio_send_pkgs(hashratio, &pkg))
431  			return;
432  	}
433  
434  	applog(LOG_DEBUG, "hashratio: Pool stratum message HEADER: 4");
435  	for (i = 0; i < 4; i++) {
436  		memset(pkg.data, 0, HRTO_P_HEADER);
437  		memcpy(pkg.data, pool->header_bin + i * 32, 32);
438  		hashratio_init_pkg(&pkg, HRTO_P_HEADER, i + 1, 4);
439  		if (hashratio_send_pkgs(hashratio, &pkg))
440  			return;
441  
442  	}
443  }
444  
445  static int hashratio_get_result(struct thr_info *thr, struct hashratio_ret *ar)
446  {
447  	struct cgpu_info *hashratio = thr->cgpu;
448  	uint8_t result[HRTO_READ_SIZE];
449  	int ret;
450  
451  	memset(result, 0, HRTO_READ_SIZE);
452  
453  	ret = hashratio_gets(hashratio, result);
454  	if (ret != HRTO_GETS_OK)
455  		return ret;
456  
457  //	if (opt_debug) {
458  //		applog(LOG_DEBUG, "hashratio: Get(ret = %d):", ret);
459  //		hexdump((uint8_t *)result, HRTO_READ_SIZE);
460  //	}
461  
462  	return decode_pkg(thr, ar, result);
463  }
464  
465  #define HASHRATIO_LATENCY 5
466  
467  static void hashratio_initialise(struct cgpu_info *hashratio)
468  {
469  	int err, interface;
470  
471  	if (hashratio->usbinfo.nodev)
472  		return;
473  
474  	interface = usb_interface(hashratio);
475  	// Reset
476  	err = usb_transfer(hashratio, FTDI_TYPE_OUT, FTDI_REQUEST_RESET,
477  				FTDI_VALUE_RESET, interface, C_RESET);
478  
479  	applog(LOG_DEBUG, "%s%i: reset got err %d",
480  		hashratio->drv->name, hashratio->device_id, err);
481  
482  	if (hashratio->usbinfo.nodev)
483  		return;
484  
485  	// Set latency
486  	err = usb_transfer(hashratio, FTDI_TYPE_OUT, FTDI_REQUEST_LATENCY,
487  			   HASHRATIO_LATENCY, interface, C_LATENCY);
488  
489  	applog(LOG_DEBUG, "%s%i: latency got err %d",
490  		hashratio->drv->name, hashratio->device_id, err);
491  
492  	if (hashratio->usbinfo.nodev)
493  		return;
494  
495  	// Set data
496  	err = usb_transfer(hashratio, FTDI_TYPE_OUT, FTDI_REQUEST_DATA,
497  				FTDI_VALUE_DATA_AVA, interface, C_SETDATA);
498  
499  	applog(LOG_DEBUG, "%s%i: data got err %d",
500  		hashratio->drv->name, hashratio->device_id, err);
501  
502  	if (hashratio->usbinfo.nodev)
503  		return;
504  
505  	// Set the baud
506  	err = usb_transfer(hashratio, FTDI_TYPE_OUT, FTDI_REQUEST_BAUD, FTDI_VALUE_BAUD_AVA,
507  				(FTDI_INDEX_BAUD_AVA & 0xff00) | interface,
508  				C_SETBAUD);
509  
510  	applog(LOG_DEBUG, "%s%i: setbaud got err %d",
511  		hashratio->drv->name, hashratio->device_id, err);
512  
513  	if (hashratio->usbinfo.nodev)
514  		return;
515  
516  	// Set Modem Control
517  	err = usb_transfer(hashratio, FTDI_TYPE_OUT, FTDI_REQUEST_MODEM,
518  				FTDI_VALUE_MODEM, interface, C_SETMODEM);
519  
520  	applog(LOG_DEBUG, "%s%i: setmodemctrl got err %d",
521  		hashratio->drv->name, hashratio->device_id, err);
522  
523  	if (hashratio->usbinfo.nodev)
524  		return;
525  
526  	// Set Flow Control
527  	err = usb_transfer(hashratio, FTDI_TYPE_OUT, FTDI_REQUEST_FLOW,
528  				FTDI_VALUE_FLOW, interface, C_SETFLOW);
529  
530  	applog(LOG_DEBUG, "%s%i: setflowctrl got err %d",
531  		hashratio->drv->name, hashratio->device_id, err);
532  
533  	if (hashratio->usbinfo.nodev)
534  		return;
535  
536  	/* hashratio repeats the following */
537  	// Set Modem Control
538  	err = usb_transfer(hashratio, FTDI_TYPE_OUT, FTDI_REQUEST_MODEM,
539  				FTDI_VALUE_MODEM, interface, C_SETMODEM);
540  
541  	applog(LOG_DEBUG, "%s%i: setmodemctrl 2 got err %d",
542  		hashratio->drv->name, hashratio->device_id, err);
543  
544  	if (hashratio->usbinfo.nodev)
545  		return;
546  
547  	// Set Flow Control
548  	err = usb_transfer(hashratio, FTDI_TYPE_OUT, FTDI_REQUEST_FLOW,
549  				FTDI_VALUE_FLOW, interface, C_SETFLOW);
550  
551  	applog(LOG_DEBUG, "%s%i: setflowctrl 2 got err %d",
552  		hashratio->drv->name, hashratio->device_id, err);
553  }
554  
555  static struct cgpu_info *hashratio_detect_one(struct libusb_device *dev, struct usb_find_devices *found)
556  {
557  	struct hashratio_info *info;
558  	int err, amount;
559  	int ackdetect;
560  	char mm_version[16];
561  
562  	struct cgpu_info *hashratio = usb_alloc_cgpu(&hashratio_drv, 1);
563  	struct hashratio_pkg detect_pkg;
564  	struct hashratio_ret ret_pkg;
565  
566  	if (!usb_init(hashratio, dev, found)) {
567  		applog(LOG_ERR, "Hashratio failed usb_init");
568  		hashratio = usb_free_cgpu(hashratio);
569  		return NULL;
570  	}
571  
572  	hashratio_initialise(hashratio);
573  
574  	strcpy(mm_version, "NONE");
575  	/* Send out detect pkg */
576  	memset(detect_pkg.data, 0, HRTO_P_DATA_LEN);
577  
578  	hashratio_init_pkg(&detect_pkg, HRTO_P_DETECT, 1, 1);
579  	hashratio_send_pkg(hashratio, &detect_pkg);
580  	err = usb_read(hashratio, (char *)&ret_pkg, HRTO_READ_SIZE, &amount, C_HRO_READ);
581  	if (err || amount != HRTO_READ_SIZE) {
582  		applog(LOG_ERR, "%s %d: Hashratio failed usb_read with err %d amount %d",
583  		       hashratio->drv->name, hashratio->device_id, err, amount);
584  		usb_uninit(hashratio);
585  		usb_free_cgpu(hashratio);
586  		return NULL;
587  	}
588  
589  	ackdetect = ret_pkg.type;
590  	applog(LOG_DEBUG, "hashratio Detect ID: %d", ackdetect);
591  	
592  	if (ackdetect != HRTO_P_ACKDETECT) {
593  		applog(LOG_DEBUG, "Not a hashratio device");
594  		usb_uninit(hashratio);
595  		usb_free_cgpu(hashratio);
596  		return NULL;
597  	}
598  
599  	memcpy(mm_version, ret_pkg.data, 15);
600  	mm_version[15] = '\0';
601  
602  	/* We have a real Hashratio! */
603  	hashratio->threads = HRTO_MINER_THREADS;
604  	add_cgpu(hashratio);
605  
606  	update_usb_stats(hashratio);
607  
608  	applog(LOG_INFO, "%s%d: Found at %s", hashratio->drv->name, hashratio->device_id,
609  	       hashratio->device_path);
610  
611  	hashratio->device_data = cgcalloc(sizeof(struct hashratio_info), 1);
612  
613  	info = hashratio->device_data;
614  
615  	strcpy(info->mm_version, mm_version);
616  
617  	info->fan_pwm  = HRTO_DEFAULT_FAN / 100 * HRTO_PWM_MAX;
618  	info->temp_max = 0;
619  	info->temp_history_index = 0;
620  	info->temp_sum = 0;
621  	info->temp_old = 0;
622  	info->default_freq = hashratio_freq;
623  
624  	return hashratio;
625  }
626  
627  static inline void hashratio_detect(bool __maybe_unused hotplug)
628  {
629  	usb_detect(&hashratio_drv, hashratio_detect_one);
630  }
631  
632  static bool hashratio_prepare(struct thr_info *thr)
633  {
634  	struct cgpu_info *hashratio = thr->cgpu;
635  	struct hashratio_info *info = hashratio->device_data;
636  
637  	cglock_init(&info->pool.data_lock);
638  
639  	return true;
640  }
641  
642  static void copy_pool_stratum(struct hashratio_info *info, struct pool *pool)
643  {
644  	int i;
645  	int merkles = pool->merkles;
646  	size_t coinbase_len = pool->coinbase_len;
647  	struct pool *pool_stratum = &info->pool;
648  
649  	if (!job_idcmp((uint8_t *)pool->swork.job_id, pool_stratum->swork.job_id))
650  		return;
651  
652  	cg_wlock(&(pool_stratum->data_lock));
653  	free(pool_stratum->swork.job_id);
654  	free(pool_stratum->nonce1);
655  	free(pool_stratum->coinbase);
656  
657  	pool_stratum->coinbase = cgcalloc(coinbase_len, 1);
658  	memcpy(pool_stratum->coinbase, pool->coinbase, coinbase_len);
659  
660  	for (i = 0; i < pool_stratum->merkles; i++)
661  		free(pool_stratum->swork.merkle_bin[i]);
662  	if (merkles) {
663  		pool_stratum->swork.merkle_bin = cgrealloc(pool_stratum->swork.merkle_bin,
664  							   sizeof(char *) * merkles + 1);
665  		for (i = 0; i < merkles; i++) {
666  			pool_stratum->swork.merkle_bin[i] = cgmalloc(32);
667  			memcpy(pool_stratum->swork.merkle_bin[i], pool->swork.merkle_bin[i], 32);
668  		}
669  	}
670  
671  	pool_stratum->sdiff = pool->sdiff;
672  	pool_stratum->coinbase_len = pool->coinbase_len;
673  	pool_stratum->nonce2_offset = pool->nonce2_offset;
674  	pool_stratum->n2size = pool->n2size;
675  	pool_stratum->merkles = pool->merkles;
676  
677  	pool_stratum->swork.job_id = strdup(pool->swork.job_id);
678  	pool_stratum->nonce1 = strdup(pool->nonce1);
679  
680  	memcpy(pool_stratum->ntime, pool->ntime, sizeof(pool_stratum->ntime));
681  	memcpy(pool_stratum->header_bin, pool->header_bin, sizeof(pool_stratum->header_bin));
682  	cg_wunlock(&(pool_stratum->data_lock));
683  }
684  
685  static void hashratio_update_work(struct cgpu_info *hashratio)
686  {
687  	struct hashratio_info *info = hashratio->device_data;
688  	struct thr_info *thr = hashratio->thr[0];
689  	struct hashratio_pkg send_pkg;
690  	uint32_t tmp, range, start;
691  	struct work *work;
692  	struct pool *pool;
693  
694  	applog(LOG_DEBUG, "hashratio: New stratum: restart: %d, update: %d",
695  		thr->work_restart, thr->work_update);
696  	thr->work_update = false;
697  	thr->work_restart = false;
698  
699  	work = get_work(thr, thr->id); /* Make sure pool is ready */
700  	discard_work(work); /* Don't leak memory */
701  
702  	pool = current_pool();
703  	if (!pool->has_stratum)
704  		quit(1, "hashratio: Miner Manager have to use stratum pool");
705  	if (pool->coinbase_len > HRTO_P_COINBASE_SIZE)
706  		quit(1, "hashratio: Miner Manager pool coinbase length have to less then %d", HRTO_P_COINBASE_SIZE);
707  	if (pool->merkles > HRTO_P_MERKLES_COUNT)
708  		quit(1, "hashratio: Miner Manager merkles have to less then %d", HRTO_P_MERKLES_COUNT);
709  
710  	info->pool_no = pool->pool_no;
711  
712  	cgtime(&info->last_stratum);
713  	cg_rlock(&pool->data_lock);
714  	info->pool_no = pool->pool_no;
715  	copy_pool_stratum(info, pool);
716  	hashratio_stratum_pkgs(hashratio, pool);
717  	cg_runlock(&pool->data_lock);
718  
719  	/* Configure the parameter from outside */
720  	memset(send_pkg.data, 0, HRTO_P_DATA_LEN);
721  
722  	// fan. We're not measuring temperature so set a safe but not max value
723  	info->fan_pwm = HRTO_PWM_MAX * 2 / 3;
724  	tmp = be32toh(info->fan_pwm);
725  	memcpy(send_pkg.data, &tmp, 4);
726  
727  	// freq
728  	tmp = be32toh(info->default_freq);
729  	memcpy(send_pkg.data + 4, &tmp, 4);
730  	applog(LOG_DEBUG, "set freq: %d", info->default_freq);
731  
732  	/* Configure the nonce2 offset and range */
733  	range = 0xffffffff / (total_devices + 1);
734  	start = range * (hashratio->device_id + 1);
735  
736  	tmp = be32toh(start);
737  	memcpy(send_pkg.data + 8, &tmp, 4);
738  
739  	tmp = be32toh(range);
740  	memcpy(send_pkg.data + 12, &tmp, 4);
741  
742  	/* Package the data */
743  	hashratio_init_pkg(&send_pkg, HRTO_P_SET, 1, 1);
744  	hashratio_send_pkgs(hashratio, &send_pkg);
745  }
746  
747  static int64_t hashratio_scanhash(struct thr_info *thr)
748  {
749  	struct cgpu_info *hashratio = thr->cgpu;
750  	struct hashratio_info *info = hashratio->device_data;
751  	struct hashratio_pkg send_pkg;
752  	struct hashratio_ret ar;
753  
754  	memset(send_pkg.data, 0, HRTO_P_DATA_LEN);
755  	hashratio_init_pkg(&send_pkg, HRTO_P_POLLING, 1, 1);
756  
757  	if (unlikely(hashratio->usbinfo.nodev || hashratio_send_pkgs(hashratio, &send_pkg))) {
758  		applog(LOG_ERR, "%s%d: Device disappeared, shutting down thread",
759  		       hashratio->drv->name, hashratio->device_id);
760  		return -1;
761  	}
762  	hashratio_get_result(thr, &ar);
763  
764  	return (int64_t)info->local_work * 64 * 0xffffffff;
765  }
766  
767  static struct api_data *hashratio_api_stats(struct cgpu_info *cgpu)
768  {
769  	struct api_data *root = NULL;
770  	struct hashratio_info *info = cgpu->device_data;
771  	char buf[24];
772  	char buf2[256];
773  	double hwp;
774  	int i;
775  
776  	// mm version
777  	sprintf(buf, "MM Version");
778  	root = api_add_string(root, buf, info->mm_version, false);
779  	
780  	// asic freq
781  	sprintf(buf, "Asic Freq (MHz)");
782  	root = api_add_int(root, buf, &(info->default_freq), false);
783  	
784  	// match work count
785  	for (i = 0; i < HRTO_DEFAULT_MODULARS; i++) {
786  		sprintf(buf, "Match work Modular %02d", i + 1);
787  		memset(buf2, 0, sizeof(buf2));
788  		snprintf(buf2, sizeof(buf2),
789  				 "%02d:%08d %02d:%08d %02d:%08d %02d:%08d "
790  				 "%02d:%08d %02d:%08d %02d:%08d %02d:%08d "
791  				 "%02d:%08d %02d:%08d %02d:%08d %02d:%08d "
792  				 "%02d:%08d %02d:%08d %02d:%08d %02d:%08d",
793  				i*16 + 1, info->matching_work[i*16 + 0],
794  				i*16 + 2, info->matching_work[i*16 + 1],
795  				i*16 + 3, info->matching_work[i*16 + 2],
796  				i*16 + 4, info->matching_work[i*16 + 3],
797  				i*16 + 5, info->matching_work[i*16 + 4],
798  				i*16 + 6, info->matching_work[i*16 + 5],
799  				i*16 + 7, info->matching_work[i*16 + 6],
800  				i*16 + 8, info->matching_work[i*16 + 7],
801  				i*16 + 9, info->matching_work[i*16 + 8],
802  				i*16 + 10, info->matching_work[i*16 + 9],
803  				i*16 + 11, info->matching_work[i*16 + 10],
804  				i*16 + 12, info->matching_work[i*16 + 11],
805  				i*16 + 13, info->matching_work[i*16 + 12],
806  				i*16 + 14, info->matching_work[i*16 + 13],
807  				i*16 + 15, info->matching_work[i*16 + 14],
808  				i*16 + 16, info->matching_work[i*16 + 15]);
809  		root = api_add_string(root, buf, buf2, true);
810  	}
811  	
812  	// local works
813  	sprintf(buf, "Local works");
814  	root = api_add_int(root, buf, &(info->local_works), false);
815  	
816  	// hardware error works
817  	sprintf(buf, "Hardware error works");
818  	root = api_add_int(root, buf, &(info->hw_works), false);
819  	
820  	// device hardware error %
821  	hwp = info->local_works ? ((double)info->hw_works / (double)info->local_works) : 0;
822  	sprintf(buf, "Device hardware error%%");
823  	root = api_add_percent(root, buf, &hwp, true);
824  	
825  	// Temperature
826  	sprintf(buf, "Temperature");
827  	root = api_add_int(root, buf, &(info->temp), false);
828  
829  	// Fan
830  	for (i = 0; i < HRTO_FAN_COUNT; i++) {
831  		sprintf(buf, "Fan%d", i+1);
832  		root = api_add_int(root, buf, &(info->fan[i]), false);
833  	}
834  
835  	return root;
836  }
837  
838  static void hashratio_shutdown(struct thr_info __maybe_unused *thr)
839  {
840  }
841  
842  struct device_drv hashratio_drv = {
843  	.drv_id = DRIVER_hashratio,
844  	.dname = "hashratio",
845  	.name = "HRO",
846  	.get_api_stats   = hashratio_api_stats,
847  	.drv_detect      = hashratio_detect,
848  	.thread_prepare  = hashratio_prepare,
849  	.hash_work       = hash_driver_work,
850  	.scanwork        = hashratio_scanhash,
851  	.flush_work      = hashratio_update_work,
852  	.update_work     = hashratio_update_work,
853  	.thread_shutdown = hashratio_shutdown,
854  };