driver-gekko.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. /*
  2. * Copyright 2017-2021 vh
  3. * Copyright 2021-2023 kano
  4. *
  5. * This program is free software; you can redistribute it and/or modify it
  6. * under the terms of the GNU General Public License as published by the Free
  7. * Software Foundation; either version 3 of the License, or (at your option)
  8. * any later version. See COPYING for more details.
  9. */
  10. #include "math.h"
  11. #include "miner.h"
  12. #include "usbutils.h"
  13. #include "klist.h"
  14. #define JOB_MAX 0x7F
  15. #define BUFFER_MAX 0xFF
  16. #define SAMPLE_SIZE 0x78
  17. #define MS_SECOND_1 1000
  18. #define MS_SECOND_5 (MS_SECOND_1 * 5)
  19. #define MS_SECOND_10 (MS_SECOND_1 * 10)
  20. #define MS_SECOND_15 (MS_SECOND_1 * 15)
  21. #define MS_SECOND_30 (MS_SECOND_1 * 30)
  22. #define MS_MINUTE_1 (MS_SECOND_1 * 60)
  23. #define MS_MINUTE_2 (MS_MINUTE_1 * 2)
  24. #define MS_MINUTE_3 (MS_MINUTE_1 * 3)
  25. #define MS_MINUTE_4 (MS_MINUTE_1 * 4)
  26. #define MS_MINUTE_5 (MS_MINUTE_1 * 5)
  27. #define MS_MINUTE_10 (MS_MINUTE_1 * 10)
  28. #define MS_MINUTE_30 (MS_MINUTE_1 * 30)
  29. #define MS_HOUR_1 (MS_MINUTE_1 * 60)
  30. enum miner_state {
  31. MINER_INIT = 1,
  32. MINER_CHIP_COUNT, // 2
  33. MINER_CHIP_COUNT_XX, // 3
  34. MINER_CHIP_COUNT_OK, // 4
  35. MINER_OPEN_CORE, // 5
  36. MINER_OPEN_CORE_OK, // 6
  37. MINER_MINING, // 7
  38. MINER_MINING_DUPS, // 8
  39. MINER_SHUTDOWN, // 9
  40. MINER_SHUTDOWN_OK, // 10
  41. MINER_RESET // 11
  42. };
  43. enum miner_asic {
  44. BM1384 = 1,
  45. BM1387,
  46. BM1397
  47. };
  48. enum plateau_type {
  49. PT_NONONCE = 1,
  50. PT_FREQSET,
  51. PT_FREQNR,
  52. PT_DUPNONCE
  53. };
  54. enum micro_command {
  55. M1_GET_FAN = (0x00 << 3),
  56. M1_GET_RPM = (0x01 << 3),
  57. M1_GET_VIN = (0x02 << 3),
  58. M1_GET_IIN = (0x03 << 3),
  59. M1_GET_TEMP = (0x04 << 3),
  60. M1_GET_VNODE0 = (0x05 << 3),
  61. M1_CLR_BEN = (0x08 << 3),
  62. M1_SET_BEN = (0x09 << 3),
  63. M1_CLR_LED = (0x0A << 3),
  64. M1_SET_LED = (0x0B << 3),
  65. M1_CLR_RST = (0x0C << 3),
  66. M1_SET_RST = (0x0D << 3),
  67. M2_SET_FAN = (0x18 << 3),
  68. M2_SET_VCORE = (0x1C << 3)
  69. };
  70. enum asic_state {
  71. ASIC_HEALTHY = 0,
  72. ASIC_HALFDEAD,
  73. ASIC_ALMOST_DEAD,
  74. ASIC_DEAD
  75. };
  76. // N.B. at 2TH/s R909 ticket 64 = ~1.2 nonces per chip per second
  77. // thus 20mins is only ~1000 nonces - so variance isn't very low
  78. // time range of each value = 10 minutes
  79. #define CHTIME 600
  80. // number of ranges thus total 1hr
  81. #define CHNUM 6
  82. #define CHOFF(n) (((n) + CHNUM) % CHNUM)
  83. // N.B. uses CLOCK_MONOTONIC
  84. #define CHBASE(_t1) ((int)((_t1) / CHTIME))
  85. #define CHCMP(_t1, _t2) (CHBASE(_t1) == CHBASE(_t2))
  86. struct GEKKOCHIP
  87. {
  88. // seconds time of [offset]
  89. time_t zerosec;
  90. // the position of [0]
  91. int offset;
  92. // number of nonces in each range
  93. int noncenum[CHNUM];
  94. // number of nonces in 0..last-1
  95. int noncesum;
  96. // last used offset 0 based
  97. int last;
  98. };
  99. struct ASIC_INFO {
  100. struct timeval last_nonce; // Last time nonce was found
  101. float frequency; // Current frequency
  102. float frequency_set; // set_frequency
  103. bool frequency_updated; // Initiate check for new frequency
  104. uint32_t frequency_attempt; // attempts of set_frequency
  105. uint32_t dups; // Duplicate nonce counter
  106. uint32_t dupsall; // Total duplicate nonce counter
  107. enum asic_state state;
  108. enum asic_state last_state;
  109. struct timeval state_change_time; // Device startup time
  110. struct timeval last_frequency_adjust; // Last time of frequency adjust
  111. struct timeval last_frequency_ping; // Last time of frequency ping
  112. struct timeval last_frequency_reply; // Last time of frequency reply
  113. uint32_t prev_nonce; // Last nonce found
  114. float fullscan_ms; // Estimated time(ms) for full nonce range
  115. uint32_t fullscan_us; // Estimated time(us) for full nonce range
  116. uint64_t hashrate; // Estimated hashrate = cores x chips x frequency
  117. float frequency_reply;
  118. int nonces;
  119. struct GEKKOCHIP gc; // running nonce buffer
  120. };
  121. struct COMPAC_NONCE
  122. {
  123. int asic;
  124. unsigned char rx[BUFFER_MAX];
  125. size_t len;
  126. size_t prelen;
  127. struct timeval when;
  128. };
  129. #define DATA_NONCE(_item) ((struct COMPAC_NONCE *)(_item->data))
  130. #define ALLOC_NLIST_ITEMS 256
  131. #define LIMIT_NLIST_ITEMS 0
  132. // BM1397 info->job_id offsets to check (when job_id is wrong)
  133. static int cur_attempt[] = { 0, -4, -8, -12 };
  134. #define CUR_ATTEMPT (sizeof(cur_attempt)/sizeof(int))
  135. // macro to adjust frequency choices to be an integer multple of info->freq_base
  136. #define FREQ_BASE(_f) (ceil((float)(_f) / info->freq_base) * info->freq_base)
  137. // macro to add/subtract from the job_id but roll in the min...max range
  138. #define JOB_ID_ROLL(_jid, _add, _info) \
  139. ((_info)->min_job_id + (((_jid) + (_add) - (_info)->min_job_id) % \
  140. ((_info)->max_job_id + 1 - (_info)->min_job_id)))
  141. // convert chip to address for the 1397
  142. #define CHIPPY1397(_inf, _chi) (((double)(_inf->chips) == 0) ? \
  143. (unsigned char)0 : \
  144. ((unsigned char)(floor((double)0x100 / (double)(_inf->chips))) * (unsigned char)(_chi)))
  145. // convert address to chip for the 1397
  146. #define TOCHIPPY1397(_inf, _adr) (((double)(_inf->chips) == 0) ? \
  147. 0 : (int)floor((double)(_adr) \
  148. / floor((double)0x100 / (double)(_inf->chips))) )
  149. // BM1397 registers
  150. #define BM1397FREQ 0x08
  151. #define BM1397TICKET 0x14
  152. #define GHNUM (60*5)
  153. #define GHOFF(n) (((n) + GHNUM) % GHNUM)
  154. // a time jump without any nonces will reset the GEKKOHASH data
  155. // this would normally be a miner failure, so should reset anyway,
  156. // however under normal mining operation, using 10sec,
  157. // a 6GH/s asic will have this happen, on average, about once every 10 days
  158. // a 30GH/s asic is unlikely to have this happen in the life of the universe
  159. #define GHLIMsec 10
  160. // number of nonces that should give better than 80% accuracy
  161. // CDF[ERlang] 400 0.8 = 9.0991e-06
  162. #define GHNONCES 400
  163. // a loss of this much hash rate will reduce requested freq and reset
  164. #define GHREQUIRE 0.65
  165. // number of nonces needed before using as the rolling hash rate
  166. // N.B. 200Mhz ticket 16 GSF is around 2/sec
  167. // also, 8 has high variance ... but resets shouldn't be common
  168. // code adds 1 to this value since the first nonce isn't part of the H/s calc
  169. #define GHNONCENEEDED 8
  170. // running 5min nonce diff buffer (for GH/s)
  171. // offset = current second, GHOFF(offset-1) = previous second
  172. // GHOFF(offset-(GHNUM-1)) = GHOFF(offset+1) = oldest possible
  173. // GHOFF(offset-last) = oldest used
  174. // code is all linear except one loop that is almost always only
  175. // one interation or total max one interation per second elapsed real time
  176. struct GEKKOHASH
  177. {
  178. // seconds time of [offset]
  179. time_t zerosec;
  180. // the position of [0]
  181. int offset;
  182. // total diff in each second
  183. int64_t diff[GHNUM];
  184. // time of the first nonce in each second
  185. struct timeval firstt[GHNUM];
  186. // diff of first nonce in each second
  187. int64_t firstd[GHNUM];
  188. // time of the last nonce in each second
  189. struct timeval lastt[GHNUM];
  190. // number of nonces in each second
  191. int noncenum[GHNUM];
  192. // sum of diff[0..last-1]
  193. int64_t diffsum;
  194. // number of nonces in 0..last-1
  195. int noncesum;
  196. // last used offset 0 based
  197. int last;
  198. };
  199. #define JOBMIN 5
  200. #define JOBOFF(n) (((n) + JOBMIN) % JOBMIN)
  201. // a time jump without any work will reset the GEKKOJOB data
  202. // this would normally be all pool failure or power down due to heat
  203. // 3 = 3 minutes so should never happen
  204. #define JOBLIMn 3
  205. // the arrays are minutes of data
  206. // N.B. uses CLOCK_MONOTONIC
  207. #define JOBTIME(_sec) ((int)((int)(_sec)/(int)60))
  208. struct GEKKOJOB
  209. {
  210. // JOBTIME of [offset]
  211. time_t zeromin;
  212. // time of last job added
  213. struct timeval lastjob;
  214. // the position of [0]
  215. int offset;
  216. // time of the first job in each
  217. struct timeval firstj[JOBMIN];
  218. // time of the last job in each
  219. struct timeval lastj[JOBMIN];
  220. // number of job items in each
  221. int jobnum[JOBMIN];
  222. // average ms between jobs
  223. double avgms[JOBMIN];
  224. // min ms
  225. double minms[JOBMIN];
  226. // max ms
  227. double maxms[JOBMIN];
  228. // number of jobs in 0..last-1
  229. int jobsnum;
  230. // last used offset 0 based
  231. int last;
  232. };
  233. struct COMPAC_INFO {
  234. enum sub_ident ident; // Miner identity
  235. enum miner_state mining_state; // Miner state
  236. enum miner_asic asic_type; // ASIC Type
  237. struct thr_info *thr; // Running Thread
  238. struct thr_info rthr; // Listening Thread
  239. struct thr_info wthr; // Miner Work Thread
  240. pthread_mutex_t lock; // Mutex
  241. pthread_mutex_t wlock; // Mutex Serialize Writes
  242. pthread_mutex_t rlock; // Mutex Serialize Reads
  243. struct thr_info nthr; // GSF Nonce Thread
  244. K_LIST *nlist; // GSF Nonce list
  245. K_LIST *nstore; // GSF Nonce store
  246. pthread_mutex_t nlock; // GSF lock
  247. pthread_cond_t ncond; // GSF wait
  248. uint64_t ntimeout; // GSF number of cond timeouts
  249. uint64_t ntrigger; // GSF number of cond tiggered
  250. float freq_mult; // frequency multiplier
  251. float freq_base; // frequency mod value
  252. float step_freq; // frequency step value
  253. float min_freq; // Lowest frequency mine2 will tune down to
  254. int ramp_time; // time to allow for initial frequency ramp
  255. float frequency; // Chip Average Frequency
  256. float frequency_asic; // Highest of current asics.
  257. float frequency_default; // ASIC Frequency on RESET
  258. float frequency_requested; // Requested Frequency
  259. float frequency_selected; // Initial Requested Frequency
  260. float frequency_start; // Starting Frequency
  261. float frequency_fail_high; // Highest Frequency of Chip Failure
  262. float frequency_fail_low; // Lowest Frequency of Chip Failure
  263. float frequency_computed; // Highest hashrate seen as a frequency value
  264. float eff_gs; // hash : expected hash
  265. float eff_tm; // hash : expected hash
  266. float eff_li; // hash : expected hash
  267. float eff_1m; // hash : expected hash
  268. float eff_5m; // hash : expected hash
  269. float eff_15; // hash : expected hash
  270. float eff_wu; // wu : expected wu
  271. float tune_up; // Increase frequency when eff_gs is above value
  272. float tune_down; // Decrease frequency when eff_gs is below value
  273. float freq_fail; // last freq set failure on BM1397
  274. float hr_scale; // scale adjustment for hashrate
  275. float micro_temp; // Micro Reported Temp
  276. float wait_factor0; // Base setting from opt value
  277. float wait_factor; // Used to compute max_task_wait
  278. bool lock_freq; // When true disable all but safety,reset,shutdown and API freq changes
  279. int usb_prop; // Number of usec to wait after certain usb commands
  280. float fullscan_ms; // Estimated time(ms) for full nonce range
  281. float task_ms; // Avg time(ms) between task sent to device
  282. uint32_t fullscan_us; // Estimated time(us) for full nonce range
  283. uint64_t hashrate; // Estimated hashrate = cores x chips x frequency x hr_scale
  284. uint64_t busy_work;
  285. uint64_t task_hcn; // Hash Count Number - max nonce iter.
  286. uint32_t prev_nonce; // Last nonce found
  287. int failing; // Flag failing sticks
  288. int fail_count; // Track failures = resets
  289. int frequency_fo; // Frequency check token
  290. int frequency_of; // Frequency check token
  291. int accepted; // Nonces accepted
  292. int dups; // Duplicates found (for plateau code)
  293. int dupsall; // Duplicate nonce counter (total)
  294. int dupsreset; // Duplicates since reset
  295. int tracker; // Track code execution path
  296. int interface; // USB interface
  297. int init_count; // USB interface initialization counter
  298. int low_eff_resets; // Count of low_eff resets
  299. int midstates; // Number of midstates
  300. int nonceless; // Tasks sent. Resets when nonce is found.
  301. int nonces; // Nonces found
  302. int plateau_reset; // Count plateau based resets
  303. int zero_check; // Received nonces from zero work
  304. int vcore; // Core voltage
  305. int micro_found; // Found a micro to communicate with
  306. bool can_boost; // true if boost is possible
  307. bool vmask; // Current pool's vmask
  308. bool boosted; // Good nonce found for midstate2/3/4
  309. bool report;
  310. bool frequency_syncd; // All asics share same frequency
  311. double wu;
  312. double wu_max; // Max WU since last frequency change
  313. double rolling;
  314. uint32_t bauddiv; // Baudrate divider
  315. uint32_t chips; // Stores number of chips found
  316. uint32_t cores; // Stores number of core per chp
  317. uint32_t difficulty; // For computing hashrate
  318. float nonce_expect; // For PT_NONONCE
  319. float nonce_limit; // For PT_NONONCE
  320. uint32_t expected_chips; // Number of chips for device
  321. uint64_t hashes; // Hashes completed
  322. uint64_t xhashes; // Hashes completed / 0xffffffffull
  323. uint32_t job_id; // JobId incrementer
  324. int32_t log_wide; // Extra output in widescreen mode
  325. uint32_t low_hash; // Tracks of low hashrate
  326. uint32_t min_job_id; // JobId start/rollover
  327. uint32_t add_job_id; // JobId increment
  328. uint32_t max_job_id; // JobId cap
  329. uint64_t max_task_wait; // Micro seconds to wait before next task is sent
  330. uint32_t ramping; // Ramping incrementer
  331. uint32_t rx_len; // rx length
  332. uint32_t task_len; // task length
  333. uint32_t ticket_mask; // Used to reduce flashes per second
  334. uint32_t update_work; // Notification of work update
  335. struct timeval start_time; // Device startup time
  336. struct timeval monitor_time; // Health check reference point
  337. struct timeval last_computed_increase; // Last frequency computed change
  338. struct timeval last_scanhash; // Last time inside scanhash loop
  339. struct timeval last_dup_time; // Last time nonce dup detected was attempted
  340. struct timeval last_reset; // Last time reset was triggered
  341. struct timeval last_task; // Last time work was sent
  342. struct timeval last_nonce; // Last time nonce was found
  343. struct timeval last_hwerror; // Last time hw error was detected
  344. struct timeval last_fast_forward; // Last time of ramp jump to peak
  345. struct timeval last_frequency_adjust; // Last time of frequency adjust
  346. struct timeval last_frequency_ping; // Last time of frequency poll
  347. struct timeval last_frequency_report; // Last change of frequency report
  348. struct timeval last_frequency_invalid; // Last change of frequency report anomaly
  349. struct timeval last_chain_inactive; // Last sent chain inactive
  350. struct timeval last_low_eff_reset; // Last time responded to low_eff condition
  351. struct timeval last_micro_ping; // Last time of micro controller poll
  352. struct timeval last_write_error; // Last usb write error message
  353. struct timeval last_wu_increase; // Last wu_max change
  354. struct timeval last_pool_lost; // Last time we lost pool
  355. struct timeval last_update_rates; // Last time we called compac_update_rates()
  356. struct timeval first_task;
  357. uint64_t tasks;
  358. uint64_t cur_off[CUR_ATTEMPT];
  359. double work_usec_avg;
  360. uint64_t work_usec_num;
  361. double last_work_diff; // Diff of last work sent
  362. struct timeval last_ticket_attempt; // List attempt to set ticket
  363. int ticket_number; // offset in ticket array
  364. int ticket_work; // work sent since ticket set
  365. int64_t ticket_nonces; // nonces since ticket set
  366. int64_t below_nonces; // nonces too low since ticket set
  367. bool ticket_ok; // ticket working ok
  368. bool ticket_got_low; // nonce found close to but >= diff
  369. int ticket_failures; // Must not exceed MAX_TICKET_CHECK
  370. struct ASIC_INFO asics[255];
  371. int64_t noncebyte[256]; // Count of nonces with the given byte[3] value
  372. bool nb2c_setup; // BM1397 true = nb2chip is setup (false = all 0)
  373. uint16_t nb2chip[256]; // BM1397 map nonce byte to: chip that produced it
  374. bool active_work[JOB_MAX+1]; // Tag good and stale work
  375. struct work *work[JOB_MAX+1]; // Work ring buffer
  376. pthread_mutex_t ghlock; // Mutex for all access to gh
  377. struct GEKKOHASH gh; // running hash rate buffer
  378. float ghrequire; // Ratio of expected HR required (GHREQUIRE) 0.0-0.8
  379. pthread_mutex_t joblock; // Mutex for all access to jb
  380. struct GEKKOJOB job; // running job rate buffer
  381. pthread_mutex_t slock; // usleep() stats
  382. uint64_t num0;
  383. uint64_t num;
  384. double req;
  385. double fac;
  386. uint64_t num1_1;
  387. double req1_1;
  388. double fac1_1;
  389. uint64_t num1_5;
  390. double req1_5;
  391. double fac1_5;
  392. uint64_t inv;
  393. double workgen; // work timing overrun stats
  394. int64_t over1num;
  395. double over1amt;
  396. int64_t over2num;
  397. double over2amt;
  398. struct timeval tune_limit; // time between tune checks
  399. struct timeval last_tune_up; // time of last tune up attempt
  400. unsigned char task[BUFFER_MAX]; // Task transmit buffer
  401. unsigned char cmd[BUFFER_MAX]; // Command transmit buffer
  402. unsigned char rx[BUFFER_MAX]; // Receive buffer
  403. unsigned char tx[BUFFER_MAX]; // Transmit buffer
  404. unsigned char end[1024]; // buffer overrun test
  405. };
  406. void stuff_lsb(unsigned char *dst, uint32_t x);
  407. void stuff_msb(unsigned char *dst, uint32_t x);
  408. void stuff_reverse(unsigned char *dst, unsigned char *src, uint32_t len);
  409. uint64_t bound(uint64_t value, uint64_t lower_bound, uint64_t upper_bound);