forked from cbuchner1/CudaMiner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cpu-miner.c
1922 lines (1670 loc) · 52.9 KB
/
cpu-miner.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2010 Jeff Garzik
* Copyright 2012-2013 pooler
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version. See COPYING for more details.
*/
#include "cpuminer-config.h"
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <stdint.h>
#include <unistd.h>
#include <sys/time.h>
#include <time.h>
#ifdef WIN32
#include <windows.h>
#else
#include <errno.h>
#include <signal.h>
#include <sys/resource.h>
#if HAVE_SYS_SYSCTL_H
#include <sys/types.h>
#if HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
#include <sys/sysctl.h>
#endif
#endif
#include <jansson.h>
#include <curl/curl.h>
#include <openssl/sha.h>
#include "compat.h"
#include "miner.h"
#include "salsa_kernel.h"
#ifdef WIN32
#include <Mmsystem.h>
#pragma comment(lib, "winmm.lib")
#endif
#if 1 || defined(USE_WRAPNVML)
#define USE_WRAPNVML 1
#include "wrapnvml.h"
#endif
bool abort_flag = false; // CB
bool autotune = true;
int device_map[MAX_DEVICES];
int device_interactive[MAX_DEVICES];
int device_batchsize[MAX_DEVICES];
int device_backoff[MAX_DEVICES];
int device_lookup_gap[MAX_DEVICES];
int device_texturecache[MAX_DEVICES];
int device_singlememory[MAX_DEVICES];
char *device_config[MAX_DEVICES];
char *device_name[MAX_DEVICES];
#if defined(USE_WRAPNVML)
wrap_nvml_handle *nvmlh = NULL;
#endif
#define PROGRAM_NAME "cudaminer"
#define PROGRAM_VERSION "2014-02-28"
#define DEF_RPC_URL "http://127.0.0.1:9332/"
#define LP_SCANTIME 60
#define EXIT_CODE_OK 0
#define EXIT_CODE_USAGE 1
#define EXIT_CODE_POOL_TIMEOUT 2
#define EXIT_CODE_SW_INIT_ERROR 3
#define EXIT_CODE_CUDA_NODEVICE 4
#define EXIT_CODE_CUDA_ERROR 5
#define EXIT_CODE_TIME_LIMIT 0
#define EXIT_CODE_KILLED 7
#ifdef __linux /* Linux specific policy and affinity management */
#include <sched.h>
static inline void drop_policy(void)
{
struct sched_param param;
#ifdef SCHED_IDLE
if (unlikely(sched_setscheduler(0, SCHED_IDLE, ¶m) == -1))
#endif
#ifdef SCHED_BATCH
sched_setscheduler(0, SCHED_BATCH, ¶m);
#endif
}
static inline void affine_to_cpu(int id, int cpu)
{
cpu_set_t set;
CPU_ZERO(&set);
CPU_SET(cpu, &set);
sched_setaffinity(0, sizeof(&set), &set);
}
#elif defined(__FreeBSD__) /* FreeBSD specific policy and affinity management */
#include <sys/cpuset.h>
static inline void drop_policy(void)
{
}
static inline void affine_to_cpu(int id, int cpu)
{
// CB
// applog(LOG_INFO, "Binding Linux thread %d to cpu %d", id, cpu);
cpuset_t set;
CPU_ZERO(&set);
CPU_SET(cpu, &set);
cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_CPUSET, -1, sizeof(cpuset_t), &set);
}
#else
static inline void drop_policy(void)
{
}
static inline void affine_to_cpu(int id, int cpu)
{
#if WIN32 // CB
// applog(LOG_INFO, "Binding Windows thread %d to cpu %d", id, cpu);
DWORD mask = 1 << cpu;
SetThreadAffinityMask(GetCurrentThread(), mask);
#endif
}
#endif
enum workio_commands {
WC_GET_WORK,
WC_SUBMIT_WORK,
WC_ABORT, // CB
};
struct workio_cmd {
enum workio_commands cmd;
struct thr_info *thr;
union {
struct work *work;
} u;
};
#define MAX_POOLS 16
static const char *algo_names[] = {
"scrypt",
"scrypt-jane",
"sha256d",
"keccak",
"blake",
};
bool opt_debug = false;
bool opt_protocol = false;
bool opt_benchmark = false;
bool want_longpoll = true;
bool want_stratum = true;
static bool submit_old = false;
bool use_syslog = false;
static bool opt_background = false;
static bool opt_quiet = false;
static int opt_retries = -1;
static int opt_fail_pause = 15; // CB
static int opt_time_limit = 0; // CB
int opt_timeout = 270;
int opt_scantime = 5;
static json_t *opt_config;
static const bool opt_time = true;
enum sha256_algos opt_algo = ALGO_SCRYPT; // CB
char *jane_params = ""; // CB
static int opt_n_threads;
int num_processors; // CB
static int num_gpus; // CB
int parallel = 2; // CB
unsigned int N = 1024; // CB
char *opt_cert;
char *opt_proxy;
long opt_proxy_type;
struct thr_info *thr_info;
static int work_thr_id;
int longpoll_thr_id = -1;
struct work_restart *work_restart = NULL;
static int app_exit_code = EXIT_CODE_OK;
int num_pools = 1;
int current_pool_index = 0;
struct pool_params pools[MAX_POOLS];
struct pool_params* current_pool = &(pools[0]);
bool opt_loop_pools = false;
pthread_mutex_t applog_lock;
pthread_mutex_t stats_lock;
static unsigned long accepted_count = 0L;
static unsigned long rejected_count = 0L;
double *thr_hashrates;
static bool move_to_next_pool(void);
static void restart_threads(void);
#ifdef HAVE_GETOPT_LONG
#include <getopt.h>
#else
struct option {
const char *name;
int has_arg;
int *flag;
int val;
};
#endif
// CB
static char const usage[] = "\
Usage: " PROGRAM_NAME " [OPTIONS]\n\
Options:\n\
-a, --algo=ALGO specify the algorithm to use (default is scrypt)\n\
scrypt scrypt Salsa20/8(1024, 1, 1), PBKDF2(SHA2)\n\
scrypt:N scrypt Salsa20/8(N, 1, 1), PBKDF2(SHA2)\n\
scrypt-jane scrypt Chacha20/8(N, 1, 1), PBKDF2(Keccak)\n\
scrypt-jane:Coin\n\
Coin must be one of the supported coins.\n\
scrypt-jane:Nfactor\n\
scrypt-chacha20/8(2*2^Nfactor, 1, 1)\n\
scrypt-jane:StartTime,Nfmin,Nfmax\n\
like above nFactor derived from Unix time.\n\
sha256d SHA-256d (don't use this! No GPU acceleration)\n\
keccak Keccak (SHA-3)\n\
blake Blake\n\
-o, --url=URL URL of mining server (default: " DEF_RPC_URL ").\n\
multiple occurences of -o are supported;\n\
you can specify different user/pass for each server,\n\
or reuse user/pass from one server for several next servers.\n\
-O, --userpass=U:P username:password pair for mining server\n\
-u, --user=USERNAME username for mining server\n\
-p, --pass=PASSWORD password for mining server\n\
--cert=FILE certificate for mining server using SSL\n\
-x, --proxy=[PROTOCOL://]HOST[:PORT] connect through a proxy\n\
-t, --threads=N number of miner threads (default: number of processors)\n\
-r, --retries=N number of times to retry if a network call fails\n\
(default: retry indefinitely)\n\
-R, --retry-pause=N time to pause between retries, in seconds (default: 30)\n\
-T, --timeout=N network timeout, in seconds (default: 270)\n\
-s, --scantime=N upper bound on time spent scanning current work when\n\
long polling is unavailable, in seconds (default: 5)\n\
--no-longpoll disable X-Long-Polling support\n\
--no-stratum disable X-Stratum support\n\
-q, --quiet disable per-thread hashmeter output\n\
-D, --debug enable debug output\n\
-P, --protocol-dump verbose dump of protocol-level activities\n\
--no-autotune disable auto-tuning of kernel launch parameters\n\
-d, --devices takes a comma separated list of CUDA devices to use.\n\
Device IDs start counting from 0! Alternatively takes\n\
string names of your cards like gtx780ti or gt640#2\n\
(matching 2nd gt640 in the PC)\n\
-l, --launch-config gives the launch configuration for each kernel\n\
in a comma separated list, one per device.\n\
-i, --interactive comma separated list of flags (0/1) specifying\n\
which of the CUDA device you need to run at inter-\n\
active frame rates (because it drives a display).\n\
-b, --batchsize comma separated list of max. scrypt iterations that\n\
are run in one kernel invocation. Default is 1024.\n\
Increase for better performance in scrypt-jane.\n\
-C, --texture-cache comma separated list of flags (0/1) specifying\n\
which of the CUDA devices shall use the texture\n\
cache for mining. Kepler devices will profit.\n\
-m, --single-memory comma separated list of flags (0/1) specifying\n\
which of the CUDA devices shall allocate their\n\
scrypt scratchbuffers in a single memory block.\n\
-H, --hash-parallel determines how the PBKDF2 based SHA2 or Keccak\n\
parts of scrypt and scrypt-jane are computed:\n\
0 hashes this single threaded on the CPU.\n\
1 to enable multithreaded hashing on the CPU.\n\
2 offloads everything to the GPU (default)\n\
-L, --lookup-gap Divides the per-hash memory requirement by this factor\n\
by storing only every N'th value in the scratchpad.\n\
Default is 1.\n\
--time-limit maximum time [s] to mine before exiting the program.\n\
--loop-pools go back to the first pool when the last one fails.\n"
#ifdef HAVE_SYSLOG_H
"\
-S, --syslog use system log for output messages\n"
#endif
#ifndef WIN32
"\
-B, --background run the miner in the background\n"
#endif
"\
--benchmark run in offline benchmark mode\n\
-c, --config=FILE load a JSON-format configuration file\n\
-V, --version display version information and exit\n\
-h, --help display this help text and exit\n\
";
static char const short_options[] =
#ifndef WIN32
"B"
#endif
#ifdef HAVE_SYSLOG_H
"S"
#endif
"a:c:Dhp:Px:qr:R:s:t:T:o:u:O:Vd:l:i:b:C:m:H:L:"; // CB
static struct option const options[] = {
{ "algo", 1, NULL, 'a' },
#ifndef WIN32
{ "background", 0, NULL, 'B' },
#endif
{ "benchmark", 0, NULL, 1005 },
{ "cert", 1, NULL, 1001 },
{ "config", 1, NULL, 'c' },
{ "debug", 0, NULL, 'D' },
{ "help", 0, NULL, 'h' },
{ "no-longpoll", 0, NULL, 1003 },
{ "no-stratum", 0, NULL, 1007 },
{ "pass", 1, NULL, 'p' },
{ "protocol-dump", 0, NULL, 'P' },
{ "proxy", 1, NULL, 'x' },
{ "quiet", 0, NULL, 'q' },
{ "retries", 1, NULL, 'r' },
{ "retry-pause", 1, NULL, 'R' },
{ "scantime", 1, NULL, 's' },
#ifdef HAVE_SYSLOG_H
{ "syslog", 0, NULL, 'S' },
#endif
{ "threads", 1, NULL, 't' },
{ "timeout", 1, NULL, 'T' },
{ "url", 1, NULL, 'o' },
{ "user", 1, NULL, 'u' },
{ "userpass", 1, NULL, 'O' },
{ "version", 0, NULL, 'V' },
{ "no-autotune", 0, NULL, 1004 }, // CB
{ "devices", 1, NULL, 'd' },
{ "launch-config", 1, NULL, 'l' },
{ "interactive", 1, NULL, 'i' },
{ "texture-cache", 1, NULL, 'C' },
{ "single-memory", 1, NULL, 'm' },
{ "hash-parallel", 1, NULL, 'H' },
{ "lookup-gap", 1, NULL, 'L' },
{ "time-limit", 1, NULL, 1008 },
{ "loop-pools", 0, NULL, 1009 },
{ 0, 0, 0, 0 }
};
static pthread_mutex_t g_work_lock;
static pthread_mutex_t g_pool_lock;
static bool jobj_binary(const json_t *obj, const char *key,
void *buf, size_t buflen)
{
const char *hexstr;
json_t *tmp;
tmp = json_object_get(obj, key);
if (unlikely(!tmp)) {
applog(LOG_ERR, "JSON key '%s' not found", key);
return false;
}
hexstr = json_string_value(tmp);
if (unlikely(!hexstr)) {
applog(LOG_ERR, "JSON key '%s' is not a string", key);
return false;
}
if (!hex2bin((unsigned char*)buf, hexstr, buflen))
return false;
return true;
}
static bool work_decode(const json_t *val, struct work *work)
{
int i;
if (unlikely(!jobj_binary(val, "data", work->data, sizeof(work->data)))) {
applog(LOG_ERR, "JSON inval data");
goto err_out;
}
if (unlikely(!jobj_binary(val, "target", work->target, sizeof(work->target)))) {
applog(LOG_ERR, "JSON inval target");
goto err_out;
}
for (i = 0; i < ARRAY_SIZE(work->data); i++)
work->data[i] = le32dec(work->data + i);
for (i = 0; i < ARRAY_SIZE(work->target); i++)
work->target[i] = le32dec(work->target + i);
return true;
err_out:
return false;
}
static void share_result(int result, const char *reason)
{
char s[345];
double hashrate;
int i;
hashrate = 0.;
pthread_mutex_lock(&stats_lock);
for (i = 0; i < opt_n_threads; i++)
hashrate += thr_hashrates[i];
result ? accepted_count++ : rejected_count++;
pthread_mutex_unlock(&stats_lock);
sprintf(s, hashrate >= 1e6 ? "%.0f" : "%.2f", 1e-3 * hashrate);
applog(LOG_INFO, "accepted: %lu/%lu (%.2f%%), %s khash/s %s",
accepted_count,
accepted_count + rejected_count,
100. * accepted_count / (accepted_count + rejected_count),
s,
result ? "(yay!!!)" : "(booooo)");
if (opt_debug && reason)
applog(LOG_DEBUG, "DEBUG: reject reason: %s", reason);
}
static bool submit_upstream_work(struct pool_params* pool, CURL *curl, struct work *work)
{
char *str = NULL;
json_t *val, *res, *reason;
char s[345];
int i;
bool rc = false;
/* pass if the previous hash is not the current previous hash */
if (!submit_old && memcmp(work->data + 1, pool->g_work.data + 1, 32)) {
if (opt_debug)
applog(LOG_DEBUG, "DEBUG: stale work detected, discarding");
return true;
}
if (pool->have_stratum) {
uint32_t ntime, nonce;
char *ntimestr, *noncestr, *xnonce2str;
if (!work->job_id)
return true;
le32enc(&ntime, work->data[17]);
le32enc(&nonce, work->data[19]);
ntimestr = bin2hex((const unsigned char *)(&ntime), 4);
noncestr = bin2hex((const unsigned char *)(&nonce), 4);
xnonce2str = bin2hex(work->xnonce2, work->xnonce2_len);
sprintf(s,
"{\"method\": \"mining.submit\", \"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\":4}",
pool->user, work->job_id, xnonce2str, ntimestr, noncestr);
free(ntimestr);
free(noncestr);
free(xnonce2str);
if (unlikely(!stratum_send_line(&pool->stratum, s))) {
applog(LOG_ERR, "submit_upstream_work stratum_send_line failed");
goto out;
}
} else {
/* build hex string */
for (i = 0; i < ARRAY_SIZE(work->data); i++)
le32enc(work->data + i, work->data[i]);
str = bin2hex((unsigned char *)work->data, sizeof(work->data));
if (unlikely(!str)) {
applog(LOG_ERR, "submit_upstream_work OOM");
goto out;
}
/* build JSON-RPC request */
sprintf(s,
"{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}\r\n",
str);
/* issue JSON-RPC request */
val = json_rpc_call(pool, curl, pool->rpc_url, pool->userpass, s, false, false, NULL);
if (unlikely(!val)) {
applog(LOG_ERR, "submit_upstream_work json_rpc_call failed");
goto out;
}
res = json_object_get(val, "result");
reason = json_object_get(val, "reject-reason");
share_result(json_is_true(res), reason ? json_string_value(reason) : NULL);
json_decref(val);
}
rc = true;
out:
free(str);
return rc;
}
static const char *rpc_req =
"{\"method\": \"getwork\", \"params\": [], \"id\":0}\r\n";
static bool get_upstream_work(struct pool_params* pool, CURL *curl, struct work *work)
{
json_t *val;
bool rc;
struct timeval tv_start, tv_end, diff;
gettimeofday(&tv_start, NULL);
val = json_rpc_call(pool, curl, pool->rpc_url, pool->userpass, rpc_req,
want_longpoll, false, NULL);
gettimeofday(&tv_end, NULL);
if (pool->have_stratum) {
if (val)
json_decref(val);
return true;
}
if (!val)
return false;
rc = work_decode(json_object_get(val, "result"), work);
if (opt_debug && rc) {
timeval_subtract(&diff, &tv_end, &tv_start);
applog(LOG_DEBUG, "DEBUG: got new work in %d ms",
diff.tv_sec * 1000 + diff.tv_usec / 1000);
}
json_decref(val);
return rc;
}
static void workio_cmd_free(struct workio_cmd *wc)
{
if (!wc)
return;
switch (wc->cmd) {
case WC_SUBMIT_WORK:
free(wc->u.work);
break;
default: /* do nothing */
break;
}
memset(wc, 0, sizeof(*wc)); /* poison */
free(wc);
}
static bool workio_get_work(struct pool_params* pool, struct workio_cmd *wc, CURL *curl)
{
struct work *ret_work;
int failures = 0;
ret_work = (struct work*)calloc(1, sizeof(*ret_work));
if (!ret_work)
return false;
/* obtain new work from bitcoin via JSON-RPC */
while (!get_upstream_work(pool, curl, ret_work)) {
if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
applog(LOG_ERR, "json_rpc_call failed");
tq_push(wc->thr->q, NULL);
free(ret_work);
return false;
}
/* pause, then restart work-request loop */
applog(LOG_ERR, "json_rpc_call failed, retry after %d seconds",
opt_fail_pause);
sleep(opt_fail_pause);
}
/* send work to requesting thread */
if (!tq_push(wc->thr->q, ret_work))
free(ret_work);
return true;
}
static bool workio_submit_work(struct pool_params* pool, struct workio_cmd *wc, CURL *curl)
{
int failures = 0;
/* submit solution to bitcoin via JSON-RPC */
while (!submit_upstream_work(pool, curl, wc->u.work)) {
if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
return false;
}
/* pause, then restart work-request loop */
applog(LOG_ERR, "...retry after %d seconds",
opt_fail_pause);
sleep(opt_fail_pause);
}
return true;
}
static void *workio_thread(void *userdata)
{
struct thr_info *mythr = (struct thr_info *)userdata;
CURL *curl;
bool ok = true;
curl = curl_easy_init();
if (unlikely(!curl)) {
applog(LOG_ERR, "CURL initialization failed");
return NULL;
}
while (!abort_flag) {
struct workio_cmd *wc;
/* wait for workio_cmd sent to us, on our queue */
wc = (struct workio_cmd *)tq_pop(mythr->q, NULL);
if (!wc) {
ok = false;
break;
}
/* process workio_cmd */
switch (wc->cmd) {
case WC_GET_WORK:
ok = workio_get_work(current_pool, wc, curl);
break;
case WC_SUBMIT_WORK:
ok = workio_submit_work(current_pool, wc, curl);
break;
case WC_ABORT: // CB
default: /* should never happen */
ok = false;
break;
}
workio_cmd_free(wc);
if(!ok && !abort_flag) {
if(!move_to_next_pool()) {
abort_flag = true;
restart_threads();
}
}
}
tq_freeze(mythr->q);
curl_easy_cleanup(curl);
return NULL;
}
static void workio_abort() // CB
{
struct workio_cmd *wc;
/* fill out work request message */
wc = (struct workio_cmd *)calloc(1, sizeof(*wc));
if (!wc)
return;
wc->cmd = WC_ABORT;
/* send work request to workio thread */
if (!tq_push(thr_info[work_thr_id].q, wc)) {
workio_cmd_free(wc);
}
}
static bool get_work(struct thr_info *thr, struct work *work)
{
struct workio_cmd *wc;
struct work *work_heap;
if (abort_flag)
return false;
if (opt_benchmark) {
memset(work->data, 0x55, 76);
work->data[17] = swab32((uint32_t)time(NULL));
memset(work->data + 19, 0x00, 52);
work->data[20] = 0x80000000;
work->data[31] = 0x00000280;
memset(work->target, 0x00, sizeof(work->target));
return true;
}
/* fill out work request message */
wc = (struct workio_cmd *)calloc(1, sizeof(*wc));
if (!wc)
return false;
wc->cmd = WC_GET_WORK;
wc->thr = thr;
/* send work request to workio thread */
if (!tq_push(thr_info[work_thr_id].q, wc)) {
workio_cmd_free(wc);
return false;
}
/* wait for response, a unit of work */
work_heap = (struct work *)tq_pop(thr->q, NULL);
if (!work_heap)
return false;
/* copy returned work into storage provided by caller */
memcpy(work, work_heap, sizeof(*work));
free(work_heap);
return true;
}
static bool submit_work(struct thr_info *thr, const struct work *work_in)
{
struct workio_cmd *wc;
/* fill out work request message */
wc = (struct workio_cmd *)calloc(1, sizeof(*wc));
if (!wc)
return false;
wc->u.work = (struct work *)malloc(sizeof(*work_in));
if (!wc->u.work)
goto err_out;
wc->cmd = WC_SUBMIT_WORK;
wc->thr = thr;
memcpy(wc->u.work, work_in, sizeof(*work_in));
/* send solution to workio thread */
if (!tq_push(thr_info[work_thr_id].q, wc))
goto err_out;
return true;
err_out:
workio_cmd_free(wc);
return false;
}
static void stratum_gen_work(struct stratum_ctx *sctx, struct work *work)
{
unsigned char merkle_root[64];
int i;
pthread_mutex_lock(&sctx->work_lock);
strcpy(work->job_id, sctx->job.job_id);
work->xnonce2_len = sctx->xnonce2_size;
memcpy(work->xnonce2, sctx->job.xnonce2, sctx->xnonce2_size);
/* Generate merkle root */
if (opt_algo != ALGO_KECCAK && opt_algo != ALGO_BLAKE) // CB: fix for stratum pools with MaxCoin and Blake
sha256d(merkle_root, sctx->job.coinbase, (int)sctx->job.coinbase_size);
else
SHA256((unsigned char*)sctx->job.coinbase, sctx->job.coinbase_size, (unsigned char*)merkle_root);
for (i = 0; i < sctx->job.merkle_count; i++) {
memcpy(merkle_root + 32, sctx->job.merkle[i], 32);
sha256d(merkle_root, merkle_root, 64);
}
/* Increment extranonce2 */
for (i = 0; i < (int)sctx->xnonce2_size && !++sctx->job.xnonce2[i]; i++);
/* Assemble block header */
memset(work->data, 0, 128);
work->data[0] = le32dec(sctx->job.version);
for (i = 0; i < 8; i++)
work->data[1 + i] = le32dec((uint32_t *)sctx->job.prevhash + i);
for (i = 0; i < 8; i++)
work->data[9 + i] = be32dec((uint32_t *)merkle_root + i);
work->data[17] = le32dec(sctx->job.ntime);
work->data[18] = le32dec(sctx->job.nbits);
work->data[20] = 0x80000000;
work->data[31] = 0x00000280;
pthread_mutex_unlock(&sctx->work_lock);
if (opt_debug) {
char *xnonce2str = bin2hex(work->xnonce2, sctx->xnonce2_size);
applog(LOG_DEBUG, "DEBUG: job_id='%s' extranonce2=%s ntime=%08x",
work->job_id, xnonce2str, swab32(work->data[17]));
free(xnonce2str);
}
if (opt_algo == ALGO_SCRYPT || opt_algo == ALGO_SCRYPT_JANE)
diff_to_target(work->target, sctx->job.diff / 65536.0);
else if (opt_algo == ALGO_KECCAK)
diff_to_target(work->target, sctx->job.diff / 256.0);
else
diff_to_target(work->target, sctx->job.diff);
}
static void *miner_thread(void *userdata)
{
struct thr_info *mythr = (struct thr_info *)userdata;
int thr_id = mythr->id;
struct work work;
uint32_t max_nonce;
uint32_t end_nonce = 0xffffffffU / opt_n_threads * (thr_id + 1) - 0x20;
// CB
char s[16];
int i;
memset(&work, 0, sizeof(work)); // CB fix uninitialized variable problem
/* Set worker threads to nice 19 and then preferentially to SCHED_IDLE
* and if that fails, then SCHED_BATCH. No need for this to be an
* error if it fails */
if (!opt_benchmark) {
setpriority(PRIO_PROCESS, 0, 19);
drop_policy();
}
if (!parallel) // CB
{
if (!opt_quiet)
applog(LOG_INFO, "Binding thread %d to cpu %d",
thr_id, thr_id % num_processors);
affine_to_cpu(thr_id, thr_id % num_processors);
}
while (!abort_flag) { // CB
unsigned long hashes_done;
struct timeval tv_start, tv_end, diff;
int64_t max64;
int rc;
struct pool_params* pool = current_pool;
if (pool->have_stratum) {
while (!abort_flag && !work_restart[thr_id].restart && (!*pool->g_work.job_id || time(NULL) >= pool->g_work_time + 120))
sleep(1);
if(abort_flag)
break;
pthread_mutex_lock(&g_work_lock);
if (work.data[19] >= end_nonce) {
stratum_gen_work(&pool->stratum, &pool->g_work);
}
} else {
/* obtain new work from internal workio thread */
pthread_mutex_lock(&g_work_lock);
if (!pool->have_longpoll ||
time(NULL) >= pool->g_work_time + LP_SCANTIME*3/4 ||
work.data[19] >= end_nonce) {
if (unlikely(!get_work(mythr, &pool->g_work))) {
applog(LOG_ERR, "Miner thread %d: work retrieval failed, retry in %d seconds...", mythr->id, opt_fail_pause);
pthread_mutex_unlock(&g_work_lock);
if(!abort_flag && !work_restart[thr_id].restart)
sleep(opt_fail_pause);
if(abort_flag)
break;
work_restart[thr_id].restart = 0;
continue;
}
time(&pool->g_work_time);
}
}
if (memcmp(work.data, pool->g_work.data, 76)) {
memcpy(&work, &pool->g_work, sizeof(struct work));
work.data[19] = 0xffffffffU / opt_n_threads * thr_id;
} else
work.data[19]++;
pthread_mutex_unlock(&g_work_lock);
work_restart[thr_id].restart = 0;
static bool firstwork = true;
static time_t firstwork_time;
/* adjust max_nonce to meet target scan time */
if (pool->have_stratum)
max64 = LP_SCANTIME;
else
max64 = pool->g_work_time + (pool->have_longpoll ? LP_SCANTIME : opt_scantime)
- time(NULL);
if (opt_time_limit && firstwork == false) // CB
{
int passed = (int)(time(NULL) - firstwork_time);
int remain = (int)(opt_time_limit - passed);
if (remain < 0)
{
app_exit_code = EXIT_CODE_TIME_LIMIT;
abort_flag = true;
workio_abort();
break;
}
if (remain < max64) max64 = remain;
}
max64 *= (int64_t)thr_hashrates[thr_id];
if (max64 <= 0)
max64 = opt_algo == (ALGO_SCRYPT || opt_algo == ALGO_SCRYPT_JANE) ? 0x3ffffLL : 0xffffffLL; // CB
if ((int64_t)work.data[19] + max64 > end_nonce)
max_nonce = end_nonce;
else
max_nonce = (uint32_t)(work.data[19] + max64);
hashes_done = 0;
// CB
#if 0
work.target[0] = ~0u;
work.target[1] = ~0u;
work.target[2] = ~0u;
work.target[3] = ~0u;
work.target[4] = ~0u;
work.target[5] = ~0u;
work.target[6] = ~0u;
work.target[7] = 0xfffff;
#endif
/* scan nonces for a proof-of-work hash */
switch (opt_algo) {
case ALGO_SCRYPT:
rc = scanhash_scrypt(thr_id, work.data, work.target, // CB
max_nonce, &tv_start, &tv_end, &hashes_done);
break;
case ALGO_SCRYPT_JANE:
rc = scanhash_scrypt_jane(thr_id, work.data, work.target, // CB
max_nonce, &tv_start, &tv_end, &hashes_done);
break;
case ALGO_SHA256D:
rc = scanhash_sha256d(thr_id, work.data, work.target, // CB
max_nonce, &tv_start, &tv_end, &hashes_done);
break;
case ALGO_KECCAK:
rc = scanhash_keccak(thr_id, work.data, work.target,
max_nonce, &tv_start, &tv_end, &hashes_done);
break;
case ALGO_BLAKE:
rc = scanhash_blake(thr_id, work.data, work.target,
max_nonce, &tv_start, &tv_end, &hashes_done);
break;
default:
/* should never happen */
goto out;
}
if(rc < 0)
{
// kernel error - terminate
app_exit_code = EXIT_CODE_CUDA_ERROR;
abort_flag = true;
workio_abort();
rc = 0;
break;
}
if (firstwork) // CB
{
time(&firstwork_time);
firstwork = false;
}
// CB
/* record scanhash elapsed time */
timeval_subtract(&diff, &tv_end, &tv_start);
if (diff.tv_usec || diff.tv_sec) {
pthread_mutex_lock(&stats_lock);
thr_hashrates[thr_id] =
hashes_done / (diff.tv_sec + 1e-6 * diff.tv_usec);
pthread_mutex_unlock(&stats_lock);
}
if (!opt_quiet && !abort_flag) { // CB
sprintf(s, thr_hashrates[thr_id] >= 1e6 ? "%.0f" : "%.2f",
1e-3 * thr_hashrates[thr_id]);
#if defined(USE_WRAPNVML)
if (nvmlh != NULL) {
unsigned int tempC=0, fanpcnt=0, mwatts=0;
char gputempbuf[64], gpufanbuf[64], gpupowbuf[64];
strcpy(gputempbuf, " N/A");
strcpy(gpufanbuf, " N/A");
strcpy(gpupowbuf, " N/A");
#if 1
if (wrap_nvml_get_tempC(nvmlh, device_map[thr_id], &tempC) == 0)
sprintf(gputempbuf, "%3dC", tempC);
if (wrap_nvml_get_fanpcnt(nvmlh, device_map[thr_id], &fanpcnt) == 0)
sprintf(gpufanbuf, "%3d%%", fanpcnt);
if (wrap_nvml_get_power_usage(nvmlh, device_map[thr_id], &mwatts) == 0)
sprintf(gpupowbuf, "%dW", (mwatts / 1000));
#endif
applog(LOG_INFO, "GPU #%d: %s, %s khash/s",
device_map[thr_id], device_name[thr_id], s);
applog(LOG_INFO, " Temp: %s Fan speed: %s Power: %s",
gputempbuf, gpufanbuf, gpupowbuf);
}