forked from cbuchner1/CudaMiner
-
Notifications
You must be signed in to change notification settings - Fork 1
/
salsa_kernel.cu
1055 lines (928 loc) · 47.6 KB
/
salsa_kernel.cu
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
//
// Contains the autotuning logic and some utility functions.
// Note that all CUDA kernels have been moved to other .cu files
//
// NOTE: compile this .cu module for compute_10,sm_10 with --maxrregcount=64
//
#ifdef WIN32
#include <windows.h>
#endif
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <unistd.h>
#include <ctype.h>
#include <map>
#include <algorithm>
#include <cuda.h>
#include "salsa_kernel.h"
#include "titan_kernel.h"
#include "spinlock_kernel.h"
#include "fermi_kernel.h"
#include "legacy_kernel.h"
#include "test_kernel.h"
#include "nv_kernel.h"
#include "nv_kernel2.h"
#include "kepler_kernel.h"
#include "miner.h"
#if WIN32
#ifdef _WIN64
#define _64BIT 1
#endif
#else
#if __x86_64__
#define _64BIT 1
#endif
#endif
#if _64BIT
#define MAXMEM 0x300000000ULL // 12 GB (the largest Kepler)
#else
#define MAXMEM 0xFFFFFFFFULL // nearly 4 GB (32 bit limitations)
#endif
// require CUDA 5.5 driver API
#define DMAJ 5
#define DMIN 5
// define some error checking macros
#undef checkCudaErrors
#define checkCudaErrors(x) \
{ \
cudaGetLastError(); \
x; \
cudaError_t err = cudaGetLastError(); \
if (err != cudaSuccess) \
{ \
applog(LOG_ERR, "GPU #%d: cudaError %d (%s) calling '%s' (%s line %d)\n", device_map[thr_id], err, cudaGetErrorString(err), #x, __FILE__, __LINE__); \
} \
}
// some globals containing pointers to device memory (for chunked allocation)
// [8] indexes up to 8 threads (0...7)
int MAXWARPS[8];
uint32_t* h_V[8][TOTAL_WARP_LIMIT];
uint32_t h_V_extra[8][TOTAL_WARP_LIMIT];
extern "C" int cuda_num_devices()
{
int version;
cudaError_t err = cudaDriverGetVersion(&version);
if (err != cudaSuccess)
{
applog(LOG_ERR, "Unable to query CUDA driver version! Is an nVidia driver installed?");
exit(1);
}
int maj = version / 1000, min = version % 100; // same as in deviceQuery sample
if (maj < DMAJ || (maj == DMAJ && min < DMIN))
{
applog(LOG_ERR, "Driver does not support CUDA %d.%d API! Update your nVidia driver!", DMAJ, DMIN);
exit(1);
}
int GPU_N;
err = cudaGetDeviceCount(&GPU_N);
if (err != cudaSuccess)
{
applog(LOG_ERR, "Unable to query number of CUDA devices! Is an nVidia driver installed?");
exit(1);
}
return GPU_N;
}
static bool substringsearch(const char *haystack, const char *needle, int &match)
{
int hlen = strlen(haystack);
int nlen = strlen(needle);
for (int i=0; i < hlen; ++i)
{
if (haystack[i] == ' ') continue;
int j=0, x = 0;
while(j < nlen)
{
if (haystack[i+x] == ' ') {++x; continue;}
if (needle[j] == ' ') {++j; continue;}
if (needle[j] == '#') return ++match == needle[j+1]-'0';
if (tolower(haystack[i+x]) != tolower(needle[j])) break;
++j; ++x;
}
if (j == nlen) return true;
}
return false;
}
extern "C" int cuda_finddevice(char *name)
{
int num = cuda_num_devices();
int match = 0;
for (int i=0; i < num; ++i)
{
cudaDeviceProp props;
if (cudaGetDeviceProperties(&props, i) == cudaSuccess)
if (substringsearch(props.name, name, match)) return i;
}
return -1;
}
bool validate_config(char *config, int &b, int &w, KernelInterface **kernel = NULL, cudaDeviceProp *props = NULL)
{
bool success = false;
char kernelid = ' ';
if (config != NULL)
{
if (config[0] == 'T' || config[0] == 'S' || config[0] == 'K' || config[0] == 'F' || config[0] == 'L' ||
config[0] == 'X' || config[0] == 'Y' || config[0] == 'Z') {
kernelid = config[0];
config++;
}
if (config[0] >= '0' && config[0] <= '9')
if (sscanf(config, "%dx%d", &b, &w) == 2)
success = true;
if (success && kernel != NULL)
{
switch (kernelid)
{
case 'T': *kernel = new TitanKernel(); break;
case 'S': *kernel = new SpinlockKernel(); break;
case 'K': *kernel = new KeplerKernel(); break;
case 'F': *kernel = new FermiKernel(); break;
case 'L': *kernel = new LegacyKernel(); break;
case 'X': *kernel = new TestKernel(); break;
case 'Y': *kernel = new NVKernel(); break;
case 'Z': *kernel = new NV2Kernel(); break;
case ' ': // choose based on device architecture
if (props->major == 3 && props->minor == 5)
*kernel = new TitanKernel();
else if (props->major == 3 && props->minor == 0)
*kernel = new KeplerKernel();
else if (props->major == 2)
*kernel = new FermiKernel();
else if (props->major == 1)
*kernel = new LegacyKernel();
break;
}
}
}
return success;
}
std::map<int, int> context_blocks;
std::map<int, int> context_wpb;
std::map<int, bool> context_concurrent;
std::map<int, KernelInterface *> context_kernel;
std::map<int, uint32_t *> context_idata[2];
std::map<int, uint32_t *> context_odata[2];
std::map<int, cudaStream_t> context_streams[2];
std::map<int, uint32_t *> context_X[2];
std::map<int, uint32_t *> context_H[2];
std::map<int, cudaEvent_t> context_serialize[2];
// for SHA256 hashing on GPU
std::map<int, uint32_t *> context_tstate[2];
std::map<int, uint32_t *> context_ostate[2];
std::map<int, uint32_t *> context_hash[2];
int find_optimal_blockcount(int thr_id, KernelInterface* &kernel, bool &concurrent, int &wpb);
extern "C" void cuda_shutdown(int thr_id)
{
checkCudaErrors(cudaStreamSynchronize(context_streams[0][thr_id]));
checkCudaErrors(cudaStreamSynchronize(context_streams[1][thr_id]));
checkCudaErrors(cudaThreadExit());
}
extern "C" int cuda_throughput(int thr_id)
{
int GRID_BLOCKS, WARPS_PER_BLOCK;
if (context_blocks.find(thr_id) == context_blocks.end())
{
#if 0
CUcontext ctx;
cuCtxCreate( &ctx, CU_CTX_SCHED_YIELD, device_map[thr_id] );
cuCtxSetCurrent(ctx);
#else
checkCudaErrors(cudaSetDeviceFlags(cudaDeviceScheduleYield));
checkCudaErrors(cudaSetDevice(device_map[thr_id]));
checkCudaErrors(cudaFree(0));
#endif
KernelInterface *kernel;
bool concurrent; GRID_BLOCKS = find_optimal_blockcount(thr_id, kernel, concurrent, WARPS_PER_BLOCK);
unsigned int THREADS_PER_WU = kernel->threads_per_wu();
unsigned int mem_size = WU_PER_LAUNCH * sizeof(uint32_t) * 32;
unsigned int state_size = WU_PER_LAUNCH * sizeof(uint32_t) * 8;
// allocate device memory for scrypt_core inputs and outputs
uint32_t *tmp;
checkCudaErrors(cudaMalloc((void **) &tmp, mem_size)); context_idata[0][thr_id] = tmp;
checkCudaErrors(cudaMalloc((void **) &tmp, mem_size)); context_idata[1][thr_id] = tmp;
checkCudaErrors(cudaMalloc((void **) &tmp, mem_size)); context_odata[0][thr_id] = tmp;
checkCudaErrors(cudaMalloc((void **) &tmp, mem_size)); context_odata[1][thr_id] = tmp;
// allocate pinned host memory for scrypt hashes
checkCudaErrors(cudaHostAlloc((void **) &tmp, state_size, cudaHostAllocDefault)); context_H[0][thr_id] = tmp;
checkCudaErrors(cudaHostAlloc((void **) &tmp, state_size, cudaHostAllocDefault)); context_H[1][thr_id] = tmp;
if (opt_algo == ALGO_SCRYPT)
{
if (parallel < 2)
{
// allocate pinned host memory for scrypt_core input/output
checkCudaErrors(cudaHostAlloc((void **) &tmp, mem_size, cudaHostAllocDefault)); context_X[0][thr_id] = tmp;
checkCudaErrors(cudaHostAlloc((void **) &tmp, mem_size, cudaHostAllocDefault)); context_X[1][thr_id] = tmp;
}
else
{
// allocate tstate, ostate, scrypt hash device memory
checkCudaErrors(cudaMalloc((void **) &tmp, state_size)); context_tstate[0][thr_id] = tmp;
checkCudaErrors(cudaMalloc((void **) &tmp, state_size)); context_tstate[1][thr_id] = tmp;
checkCudaErrors(cudaMalloc((void **) &tmp, state_size)); context_ostate[0][thr_id] = tmp;
checkCudaErrors(cudaMalloc((void **) &tmp, state_size)); context_ostate[1][thr_id] = tmp;
checkCudaErrors(cudaMalloc((void **) &tmp, state_size)); context_hash[0][thr_id] = tmp;
checkCudaErrors(cudaMalloc((void **) &tmp, state_size)); context_hash[1][thr_id] = tmp;
}
}
else if (opt_algo == ALGO_SCRYPT_JANE)
{
// allocate pinned host memory for scrypt_core input/output
checkCudaErrors(cudaHostAlloc((void **) &tmp, mem_size, cudaHostAllocDefault)); context_X[0][thr_id] = tmp;
checkCudaErrors(cudaHostAlloc((void **) &tmp, mem_size, cudaHostAllocDefault)); context_X[1][thr_id] = tmp;
checkCudaErrors(cudaMalloc((void **) &tmp, state_size)); context_hash[0][thr_id] = tmp;
checkCudaErrors(cudaMalloc((void **) &tmp, state_size)); context_hash[1][thr_id] = tmp;
}
// create two CUDA streams
cudaStream_t tmp2;
checkCudaErrors( cudaStreamCreate(&tmp2) ); context_streams[0][thr_id] = tmp2;
checkCudaErrors( cudaStreamCreate(&tmp2) ); context_streams[1][thr_id] = tmp2;
// events used to serialize the kernel launches (we don't want any overlapping of kernels)
cudaEvent_t tmp4;
checkCudaErrors(cudaEventCreateWithFlags(&tmp4, cudaEventDisableTiming)); context_serialize[0][thr_id] = tmp4;
checkCudaErrors(cudaEventCreateWithFlags(&tmp4, cudaEventDisableTiming)); context_serialize[1][thr_id] = tmp4;
checkCudaErrors(cudaEventRecord(context_serialize[1][thr_id]));
context_kernel[thr_id] = kernel;
context_concurrent[thr_id] = concurrent;
context_blocks[thr_id] = GRID_BLOCKS;
context_wpb[thr_id] = WARPS_PER_BLOCK;
}
GRID_BLOCKS = context_blocks[thr_id];
WARPS_PER_BLOCK = context_wpb[thr_id];
unsigned int THREADS_PER_WU = context_kernel[thr_id]->threads_per_wu();
return WU_PER_LAUNCH;
}
// Beginning of GPU Architecture definitions
inline int _ConvertSMVer2Cores(int major, int minor)
{
// Defines for GPU Architecture types (using the SM version to determine the # of cores per SM
typedef struct
{
int SM; // 0xMm (hexidecimal notation), M = SM Major version, and m = SM minor version
int Cores;
} sSMtoCores;
sSMtoCores nGpuArchCoresPerSM[] =
{
{ 0x10, 8 }, // Tesla Generation (SM 1.0) G80 class
{ 0x11, 8 }, // Tesla Generation (SM 1.1) G8x class
{ 0x12, 8 }, // Tesla Generation (SM 1.2) G9x class
{ 0x13, 8 }, // Tesla Generation (SM 1.3) GT200 class
{ 0x20, 32 }, // Fermi Generation (SM 2.0) GF100 class
{ 0x21, 48 }, // Fermi Generation (SM 2.1) GF10x class
{ 0x30, 192}, // Kepler Generation (SM 3.0) GK10x class
{ 0x35, 192}, // Kepler Generation (SM 3.5) GK11x class
};
int index = 0;
while (nGpuArchCoresPerSM[index].SM != -1)
{
if (nGpuArchCoresPerSM[index].SM == ((major << 4) + minor))
{
return nGpuArchCoresPerSM[index].Cores;
}
index++;
}
// If we don't find the values, we default use the previous one to run properly
// printf("MapSMtoCores for SM %d.%d is undefined. Default to use %d Cores/SM\n", major, minor, nGpuArchCoresPerSM[7].Cores);
return nGpuArchCoresPerSM[7].Cores;
}
#ifdef WIN32
#include <windows.h>
static int console_width()
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
return csbi.srWindow.Right - csbi.srWindow.Left + 1;
}
#else
int console_width()
{
return 999;
}
#endif
int find_optimal_blockcount(int thr_id, KernelInterface* &kernel, bool &concurrent, int &WARPS_PER_BLOCK)
{
int cw = console_width();
int optimal_blocks = 0;
cudaDeviceProp props;
checkCudaErrors(cudaGetDeviceProperties(&props, device_map[thr_id]));
concurrent = (props.concurrentKernels > 0);
device_name[thr_id] = strdup(props.name);
applog(LOG_INFO, "GPU #%d: %s with compute capability %d.%d", device_map[thr_id], props.name, props.major, props.minor);
WARPS_PER_BLOCK = -1;
// if not specified, use interactive mode for devices that have the watchdog timer enabled
if (device_interactive[thr_id] == -1)
device_interactive[thr_id] = props.kernelExecTimeoutEnabled;
// turn off texture cache if not otherwise specified
if (device_texturecache[thr_id] == -1)
device_texturecache[thr_id] = 0;
// if not otherwise specified or required, turn single memory allocations off as they reduce
// the amount of memory that we can allocate on Windows Vista, 7 and 8 (WDDM driver model issue)
if (device_singlememory[thr_id] == -1) device_singlememory[thr_id] = 0;
// figure out which kernel implementation to use
if (!validate_config(device_config[thr_id], optimal_blocks, WARPS_PER_BLOCK, &kernel, &props)) {
if ((device_config[thr_id] != NULL && device_config[thr_id][0] == 'T') ||
((device_config[thr_id] == NULL || !strcasecmp(device_config[thr_id], "auto")) && (props.major == 3 && props.minor == 5)))
kernel = new TitanKernel();
else if (device_config[thr_id] != NULL && device_config[thr_id][0] == 'S')
kernel = new SpinlockKernel();
else if ((device_config[thr_id] != NULL && device_config[thr_id][0] == 'K') ||
((device_config[thr_id] == NULL || !strcasecmp(device_config[thr_id], "auto")) && (props.major == 3 && props.minor == 0)))
kernel = new KeplerKernel();
else if ((device_config[thr_id] != NULL && device_config[thr_id][0] == 'F') ||
((device_config[thr_id] == NULL || !strcasecmp(device_config[thr_id], "auto")) && props.major == 2))
kernel = new FermiKernel();
else if ((device_config[thr_id] != NULL && device_config[thr_id][0] == 'L') ||
((device_config[thr_id] == NULL || !strcasecmp(device_config[thr_id], "auto")) && props.major == 1))
kernel = new LegacyKernel();
else if ((device_config[thr_id] != NULL && device_config[thr_id][0] == 'X'))
kernel = new TestKernel();
else if ((device_config[thr_id] != NULL && device_config[thr_id][0] == 'Y'))
kernel = new NVKernel();
else if ((device_config[thr_id] != NULL && device_config[thr_id][0] == 'Z'))
kernel = new NV2Kernel();
}
if (kernel->get_major_version() > props.major || kernel->get_major_version() == props.major && kernel->get_minor_version() > props.minor)
{
applog(LOG_ERR, "GPU #%d: the '%c' kernel requires %d.%d capability!", device_map[thr_id], kernel->get_identifier(), kernel->get_major_version(), kernel->get_minor_version());
}
// set whatever cache configuration and shared memory bank mode the kernel prefers
checkCudaErrors(cudaDeviceSetCacheConfig(kernel->cache_config()));
checkCudaErrors(cudaDeviceSetSharedMemConfig(kernel->shared_mem_config()));
// some kernels (e.g. Titan) do not support the texture cache
if (kernel->no_textures() && device_texturecache[thr_id]) {
applog(LOG_WARNING, "GPU #%d: the '%c' kernel ignores the texture cache argument", device_map[thr_id], kernel->get_identifier());
device_texturecache[thr_id] = 0;
}
// Texture caching only works with single memory allocation
if (device_texturecache[thr_id]) device_singlememory[thr_id] = 1;
if (kernel->single_memory() && !device_singlememory[thr_id]) {
applog(LOG_WARNING, "GPU #%d: the '%c' kernel requires single memory allocation", device_map[thr_id], kernel->get_identifier());
device_singlememory[thr_id] = 1;
}
if (device_lookup_gap[thr_id] == 0) device_lookup_gap[thr_id] = 1;
if (!kernel->support_lookup_gap() && device_lookup_gap[thr_id] > 1)
{
applog(LOG_WARNING, "GPU #%d: the '%c' kernel does not support a lookup gap", device_map[thr_id], kernel->get_identifier());
device_lookup_gap[thr_id] = 1;
}
applog(LOG_INFO, "GPU #%d: interactive: %d, tex-cache: %d%c, single-alloc: %d", device_map[thr_id],
(device_interactive[thr_id] != 0) ? 1 : 0,
(device_texturecache[thr_id] != 0) ? device_texturecache[thr_id] : 0, (device_texturecache[thr_id] != 0) ? 'D' : ' ',
(device_singlememory[thr_id] != 0) ? 1 : 0 );
// number of threads collaborating on one work unit (hash)
unsigned int THREADS_PER_WU = kernel->threads_per_wu();
unsigned int LOOKUP_GAP = device_lookup_gap[thr_id];
unsigned int BACKOFF = device_backoff[thr_id];
applog(LOG_INFO, "GPU #%d: %d hashes / %.1f MB per warp.", device_map[thr_id], WU_PER_WARP, ((double)SCRATCH * WU_PER_WARP * sizeof(uint32_t) / (1024 * 1024)));
// compute highest MAXWARPS numbers for kernels allowing cudaBindTexture to succeed
int MW_1D_4 = 134217728 / (SCRATCH * WU_PER_WARP / 4); // for uint4_t textures
int MW_1D_2 = 134217728 / (SCRATCH * WU_PER_WARP / 2); // for uint2_t textures
int MW_1D = kernel->get_texel_width() == 2 ? MW_1D_2 : MW_1D_4;
uint32_t *d_V = NULL;
if (device_singlememory[thr_id])
{
// if no launch config was specified, we simply
// allocate the single largest memory chunk on the device that we can get
if (validate_config(device_config[thr_id], optimal_blocks, WARPS_PER_BLOCK)) {
MAXWARPS[thr_id] = optimal_blocks * WARPS_PER_BLOCK;
}
else {
// compute no. of warps to allocate the largest number producing a single memory block
// PROBLEM: one some devices, ALL allocations will fail if the first one failed. This sucks.
size_t MEM_LIMIT = (unsigned long long)min((unsigned long long)MAXMEM, (unsigned long long)props.totalGlobalMem);
int warpmax = (int)min((unsigned long long)TOTAL_WARP_LIMIT, (unsigned long long)MEM_LIMIT / (SCRATCH * WU_PER_WARP * sizeof(uint32_t)));
#if 0
warpmax = ((100-BACKOFF)*warpmax+50)/100;
for (int warp = warpmax; warp >= 1; --warp) {
cudaGetLastError(); // clear the error state
cudaMalloc((void **)&d_V, (size_t)SCRATCH * WU_PER_WARP * warp * sizeof(uint32_t));
if (cudaGetLastError() == cudaSuccess) {
checkCudaErrors(cudaFree(d_V)); d_V = NULL;
// Windows WDDM driver model needs some breathing room to operate safely
// in particular when binding large 1D or 2D textures
if (warp < warpmax)
MAXWARPS[thr_id] = ((100-BACKOFF)*warp+50)/100;
break;
}
}
#else
// run a bisection algorithm for memory allocation
int best = 0;
int warp = (warpmax+1)/2;
int interval = (warpmax+1)/2;
while (interval > 0)
{
cudaGetLastError(); // clear the error state
cudaMalloc((void **)&d_V, (size_t)SCRATCH * WU_PER_WARP * warp * sizeof(uint32_t));
if (cudaGetLastError() == cudaSuccess) {
checkCudaErrors(cudaFree(d_V)); d_V = NULL;
if (warp > best) best = warp;
interval = (interval+1)/2;
warp += interval;
if (warp > warpmax) warp = warpmax;
}
else
{
interval = interval/2;
warp -= interval;
if (warp < 1) warp = 1;
}
}
MAXWARPS[thr_id] = ((100-BACKOFF)*best+50)/100;;
#endif
}
// now allocate a buffer for determined MAXWARPS setting
cudaGetLastError(); // clear the error state
cudaMalloc((void **)&d_V, (size_t)SCRATCH * WU_PER_WARP * MAXWARPS[thr_id] * sizeof(uint32_t));
if (cudaGetLastError() == cudaSuccess) {
for (int i=0; i < MAXWARPS[thr_id]; ++i)
h_V[thr_id][i] = d_V + SCRATCH * WU_PER_WARP * i;
if (device_texturecache[thr_id] == 1)
{
if (validate_config(device_config[thr_id], optimal_blocks, WARPS_PER_BLOCK))
{
if ( optimal_blocks * WARPS_PER_BLOCK > MW_1D ) {
applog(LOG_ERR, "GPU #%d: '%s' exceeds limits for 1D cache. Using 2D cache instead.", device_map[thr_id], device_config[thr_id]);
device_texturecache[thr_id] = 2;
}
}
// bind linear memory to a 1D texture reference
if (kernel->get_texel_width() == 2)
kernel->bindtexture_1D(d_V, SCRATCH * WU_PER_WARP * std::min(MAXWARPS[thr_id],MW_1D_2) * sizeof(uint32_t));
else
kernel->bindtexture_1D(d_V, SCRATCH * WU_PER_WARP * std::min(MAXWARPS[thr_id],MW_1D_4) * sizeof(uint32_t));
}
else if (device_texturecache[thr_id] == 2)
{
// bind pitch linear memory to a 2D texture reference
if (kernel->get_texel_width() == 2)
kernel->bindtexture_2D(d_V, SCRATCH/2, WU_PER_WARP * MAXWARPS[thr_id], SCRATCH*sizeof(uint32_t));
else
kernel->bindtexture_2D(d_V, SCRATCH/4, WU_PER_WARP * MAXWARPS[thr_id], SCRATCH*sizeof(uint32_t));
}
}
else
{
applog(LOG_ERR, "GPU #%d: Launch config '%s' requires too much memory!", device_map[thr_id], device_config[thr_id]);
}
}
else
{
if (validate_config(device_config[thr_id], optimal_blocks, WARPS_PER_BLOCK))
MAXWARPS[thr_id] = optimal_blocks * WARPS_PER_BLOCK;
else
MAXWARPS[thr_id] = TOTAL_WARP_LIMIT;
// chunked memory allocation up to device limits
int warp;
for (warp = 0; warp < MAXWARPS[thr_id]; ++warp) {
// work around partition camping problems by adding a random start address offset to each allocation
h_V_extra[thr_id][warp] = (props.major == 1) ? (16 * (rand()%(16384/16))) : 0;
cudaGetLastError(); // clear the error state
cudaMalloc((void **) &h_V[thr_id][warp], (SCRATCH * WU_PER_WARP + h_V_extra[thr_id][warp])*sizeof(uint32_t));
if (cudaGetLastError() == cudaSuccess) h_V[thr_id][warp] += h_V_extra[thr_id][warp];
else {
h_V_extra[thr_id][warp] = 0;
// back off by several warp allocations to have some breathing room
int remove = (BACKOFF*warp+50)/100;
for (int i=0; warp > 0 && i < remove; ++i) {
warp--;
checkCudaErrors(cudaFree(h_V[thr_id][warp]-h_V_extra[thr_id][warp]));
h_V[thr_id][warp] = NULL; h_V_extra[thr_id][warp] = 0;
}
break;
}
}
MAXWARPS[thr_id] = warp;
}
kernel->set_scratchbuf_constants(MAXWARPS[thr_id], h_V[thr_id]);
if (validate_config(device_config[thr_id], optimal_blocks, WARPS_PER_BLOCK))
{
if (optimal_blocks * WARPS_PER_BLOCK > MAXWARPS[thr_id])
applog(LOG_ERR, "GPU #%d: Given launch config '%s' requires too much memory.", device_map[thr_id], device_config[thr_id]);
if (WARPS_PER_BLOCK > kernel->max_warps_per_block())
applog(LOG_ERR, "GPU #%d: Given launch config '%s' exceeds warp limit for '%c' kernel.", device_map[thr_id], device_config[thr_id], kernel->get_identifier());
}
else
{
if (device_config[thr_id] != NULL && strcasecmp("auto", device_config[thr_id]))
applog(LOG_WARNING, "GPU #%d: Given launch config '%s' does not validate.", device_map[thr_id], device_config[thr_id]);
if (autotune)
{
applog(LOG_INFO, "GPU #%d: Performing auto-tuning (Patience...)", device_map[thr_id]);
// allocate device memory
unsigned int mem_size = MAXWARPS[thr_id] * WU_PER_WARP * sizeof(uint32_t) * 32;
uint32_t *d_idata;
checkCudaErrors(cudaMalloc((void **) &d_idata, mem_size));
uint32_t *d_odata;
checkCudaErrors(cudaMalloc((void **) &d_odata, mem_size));
// pre-initialize some device memory
uint32_t *h_idata = (uint32_t*)malloc(mem_size);
for (unsigned int i=0; i < mem_size/sizeof(uint32_t); ++i) h_idata[i] = i*2654435761UL; // knuth's method
checkCudaErrors(cudaMemcpy(d_idata, h_idata, mem_size, cudaMemcpyHostToDevice));
free(h_idata);
double best_khash_sec = 0.0;
int best_wpb = 0;
// auto-tuning loop
{
// we want to have enough total warps for half the multiprocessors at least
// compute highest MAXWARPS number that we can support based on texture cache mode
int MINTW = props.multiProcessorCount / 2;
int MAXTW = (device_texturecache[thr_id] == 1) ? std::min(MAXWARPS[thr_id],MW_1D) : MAXWARPS[thr_id];
// we want to have blocks for half the multiprocessors at least
int MINB = props.multiProcessorCount / 2;
int MAXB = MAXTW;
applog(LOG_INFO, "GPU #%d: maximum total warps (BxW): %d", device_map[thr_id], MAXTW);
for (int GRID_BLOCKS = MINB; !abort_flag && GRID_BLOCKS <= MAXB; ++GRID_BLOCKS)
{
double kHash[32+1] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
for (WARPS_PER_BLOCK = 1; !abort_flag && WARPS_PER_BLOCK <= kernel->max_warps_per_block(); ++WARPS_PER_BLOCK)
{
double khash_sec = 0;
if (GRID_BLOCKS * WARPS_PER_BLOCK >= MINTW &&
GRID_BLOCKS * WARPS_PER_BLOCK <= MAXTW)
{
// setup execution parameters
dim3 grid(WU_PER_LAUNCH/WU_PER_BLOCK, 1, 1);
dim3 threads(THREADS_PER_WU*WU_PER_BLOCK, 1, 1);
struct timeval tv_start, tv_end;
double tdelta = 0;
checkCudaErrors(cudaDeviceSynchronize());
gettimeofday(&tv_start, NULL);
int repeat = 0;
bool r = false;
while (repeat < 3) // average up to 3 measurements for better exactness
{
r=kernel->run_kernel(grid, threads, WARPS_PER_BLOCK, thr_id, NULL, d_idata, d_odata, N, LOOKUP_GAP, device_interactive[thr_id], true, device_texturecache[thr_id]);
cudaDeviceSynchronize();
if (!r || cudaPeekAtLastError() != cudaSuccess) break;
++repeat;
gettimeofday(&tv_end, NULL);
// bail out if 50ms taken (to speed up autotuning...)
if ((1e-6 * (tv_end.tv_usec-tv_start.tv_usec) + (tv_end.tv_sec-tv_start.tv_sec)) > 0.05) break;
}
if (cudaGetLastError() != cudaSuccess || !r) continue;
tdelta = (1e-6 * (tv_end.tv_usec-tv_start.tv_usec) + (tv_end.tv_sec-tv_start.tv_sec)) / repeat;
// for scrypt: in interactive mode only find launch configs where kernel launch times are short enough
// TODO: instead we could reduce the batchsize parameter to meet the launch time requirement.
if (opt_algo == ALGO_SCRYPT && device_interactive[thr_id] && GRID_BLOCKS > 2*props.multiProcessorCount && tdelta > 1.0/30)
if (WARPS_PER_BLOCK == 1) goto skip; else goto skip2;
khash_sec = (double)WU_PER_LAUNCH / (tdelta * 1e3);
kHash[WARPS_PER_BLOCK] = khash_sec;
if (khash_sec > best_khash_sec) {
optimal_blocks = GRID_BLOCKS;
best_khash_sec = khash_sec;
best_wpb = WARPS_PER_BLOCK;
}
}
}
skip2: ;
if (opt_debug) {
if (GRID_BLOCKS == MINB) {
char line[512] = " ";
for (int i=1; i<=kernel->max_warps_per_block(); ++i) {
char tmp[16]; sprintf(tmp, i < 10 ? " x%-2d" : " x%-2d ", i);
strcat(line, tmp);
if (cw == 80 && (i % 8 == 0 && i != kernel->max_warps_per_block()))
strcat(line, "\n ");
}
applog(LOG_DEBUG, line);
}
char line[512]; sprintf(line, "%3d:", GRID_BLOCKS);
for (int i=1; i<=kernel->max_warps_per_block(); ++i) {
char tmp[16];
if (kHash[i]>0)
sprintf(tmp, opt_algo == ALGO_SCRYPT_JANE ? "%5.3f%c" : "%5.1f%c", kHash[i], (i<kernel->max_warps_per_block())?'|':' ');
else
sprintf(tmp, " %c", (i<kernel->max_warps_per_block())?'|':' ');
strcat(line, tmp);
if (cw == 80 && (i % 8 == 0 && i != kernel->max_warps_per_block()))
strcat(line, "\n ");
}
strcat(line, "kH/s");
applog(LOG_DEBUG, line);
}
}
skip: ;
}
checkCudaErrors(cudaFree(d_odata));
checkCudaErrors(cudaFree(d_idata));
WARPS_PER_BLOCK = best_wpb;
applog(LOG_INFO, "GPU #%d: %7.2f khash/s with configuration %c%dx%d", device_map[thr_id], best_khash_sec, kernel->get_identifier(), optimal_blocks, WARPS_PER_BLOCK);
}
else
{
// Heuristics for finding a good kernel launch configuration
// base the initial block estimate on the number of multiprocessors
int device_cores = props.multiProcessorCount * _ConvertSMVer2Cores(props.major, props.minor);
// defaults, in case nothing else is chosen below
optimal_blocks = 4 * device_cores / WU_PER_WARP;
WARPS_PER_BLOCK = 2;
// Based on compute capability, pick a known good block x warp configuration.
if (props.major == 3)
{
if (props.minor == 0) // GK104, GK106, GK107
{
if (MAXWARPS[thr_id] > (int)(optimal_blocks * 1.7261905) * 2)
{
// this results in 290x2 configuration on GTX 660Ti (3GB)
// but it requires 3GB memory on the card!
optimal_blocks = (int)(optimal_blocks * 1.7261905);
WARPS_PER_BLOCK = 2;
}
else
{
// this results in 148x2 configuration on GTX 660Ti (2GB)
optimal_blocks = (int)(optimal_blocks * 0.8809524);
WARPS_PER_BLOCK = 2;
}
}
else if (props.minor == 5) // GK110 (Tesla K20X, K20, GeForce GTX TITAN)
{
// TODO: what to do with Titan and Tesla K20(X)?
// for now, do the same as for GTX 660Ti (2GB)
optimal_blocks = (int)(optimal_blocks * 0.8809524);
WARPS_PER_BLOCK = 2;
}
}
// 1st generation Fermi (compute 2.0) GF100, GF110
else if (props.major == 2 && props.minor == 0)
{
// this results in a 60x4 configuration on GTX 570
optimal_blocks = 4 * device_cores / WU_PER_WARP;
WARPS_PER_BLOCK = 4;
}
// 2nd generation Fermi (compute 2.1) GF104,106,108,114,116
else if (props.major == 2 && props.minor == 1)
{
// this results in a 56x2 configuration on GTX 460
optimal_blocks = props.multiProcessorCount * 8;
WARPS_PER_BLOCK = 2;
}
// G80, G92, GT2xx
else if (props.major == 1)
{
if (props.minor == 0) // G80
{
// TODO: anyone knowing good settings for G80?
optimal_blocks = props.multiProcessorCount;
WARPS_PER_BLOCK = 4;
}
else if (props.minor == 1) // G92
{
// e.g. my 9600M works best at 4x4
optimal_blocks = props.multiProcessorCount;
WARPS_PER_BLOCK = 4;
}
else if (props.minor == 2) // GT218, GT216, GT215
{
// TODO: anyone knowing good settings for Compute 1.2?
// for now I assume performance is identical to compute 1.3
optimal_blocks = props.multiProcessorCount;
WARPS_PER_BLOCK = 3;
}
if (props.minor == 3) // GT200
{
// my GTX 260 works best at S27x3
optimal_blocks = props.multiProcessorCount;
WARPS_PER_BLOCK = 3;
}
}
// in case we run out of memory with the automatically chosen configuration,
// first back off with WARPS_PER_BLOCK, then reduce optimal_blocks.
if (WARPS_PER_BLOCK==3 && optimal_blocks * WARPS_PER_BLOCK > MAXWARPS[thr_id])
WARPS_PER_BLOCK = 2;
while (optimal_blocks > 0 && optimal_blocks * WARPS_PER_BLOCK > MAXWARPS[thr_id])
optimal_blocks--;
}
}
applog(LOG_INFO, "GPU #%d: using launch configuration %c%dx%d", device_map[thr_id], kernel->get_identifier(), optimal_blocks, WARPS_PER_BLOCK);
if (device_singlememory[thr_id])
{
if (MAXWARPS[thr_id] != optimal_blocks * WARPS_PER_BLOCK)
{
MAXWARPS[thr_id] = optimal_blocks * WARPS_PER_BLOCK;
if (device_texturecache[thr_id] == 1)
kernel->unbindtexture_1D();
else if (device_texturecache[thr_id] == 2)
kernel->unbindtexture_2D();
checkCudaErrors(cudaFree(d_V)); d_V = NULL;
cudaGetLastError(); // clear the error state
cudaMalloc((void **)&d_V, (size_t)SCRATCH * WU_PER_WARP * MAXWARPS[thr_id] * sizeof(uint32_t));
if (cudaGetLastError() == cudaSuccess) {
for (int i=0; i < MAXWARPS[thr_id]; ++i)
h_V[thr_id][i] = d_V + SCRATCH * WU_PER_WARP * i;
if (device_texturecache[thr_id] == 1)
{
// bind linear memory to a 1D texture reference
if (kernel->get_texel_width() == 2)
kernel->bindtexture_1D(d_V, SCRATCH * WU_PER_WARP * MAXWARPS[thr_id] * sizeof(uint32_t));
else
kernel->bindtexture_1D(d_V, SCRATCH * WU_PER_WARP * MAXWARPS[thr_id] * sizeof(uint32_t));
}
else if (device_texturecache[thr_id] == 2)
{
// bind pitch linear memory to a 2D texture reference
if (kernel->get_texel_width() == 2)
kernel->bindtexture_2D(d_V, SCRATCH/2, WU_PER_WARP * MAXWARPS[thr_id], SCRATCH*sizeof(uint32_t));
else
kernel->bindtexture_2D(d_V, SCRATCH/4, WU_PER_WARP * MAXWARPS[thr_id], SCRATCH*sizeof(uint32_t));
}
// update pointers to scratch buffer in constant memory after reallocation
kernel->set_scratchbuf_constants(MAXWARPS[thr_id], h_V[thr_id]);
}
else
{
applog(LOG_ERR, "GPU #%d: Unable to allocate enough memory for launch config '%s'.", device_map[thr_id], device_config[thr_id]);
}
}
}
else
{
// back off unnecessary memory allocations to have some breathing room
while (MAXWARPS[thr_id] > 0 && MAXWARPS[thr_id] > optimal_blocks * WARPS_PER_BLOCK) {
(MAXWARPS[thr_id])--;
checkCudaErrors(cudaFree(h_V[thr_id][MAXWARPS[thr_id]]-h_V_extra[thr_id][MAXWARPS[thr_id]]));
h_V[thr_id][MAXWARPS[thr_id]] = NULL; h_V_extra[thr_id][MAXWARPS[thr_id]] = 0;
}
}
return optimal_blocks;
}
typedef struct { double value[8]; } tsumarray;
cudaError_t MyStreamSynchronize(cudaStream_t stream, int situation, int thr_id)
{
cudaError_t result = cudaSuccess;
if (situation >= 0)
{
static std::map<int, tsumarray> tsum;
double a = 0.95, b = 0.05;
if (tsum.find(situation) == tsum.end()) { a = 0.5; b = 0.5; } // faster initial convergence
double tsync = 0.0;
double tsleep = 0.95 * tsum[situation].value[thr_id];
if (cudaStreamQuery(stream) == cudaErrorNotReady)
{
usleep((useconds_t)(1e6*tsleep));
struct timeval tv_start, tv_end;
gettimeofday(&tv_start, NULL);
checkCudaErrors(result = cudaStreamSynchronize(stream));
gettimeofday(&tv_end, NULL);
tsync = 1e-6 * (tv_end.tv_usec-tv_start.tv_usec) + (tv_end.tv_sec-tv_start.tv_sec);
}
if (tsync >= 0) tsum[situation].value[thr_id] = a * tsum[situation].value[thr_id] + b * (tsleep+tsync);
#if 0
static int calls = 0;
if (++calls == 50) {
static std::map<int, tsumarray>::iterator it;
for (it = tsum.begin(); it != tsum.end() ; ++it)
{
const int &sit = (*it).first;
const tsumarray &ts = (*it).second;
fprintf(stderr, "%d: %f\n", sit, ts.value[thr_id]);
}
calls = 0;
}
#endif
}
else
{
checkCudaErrors(result = cudaStreamSynchronize(stream));
}
return result;
}
extern "C" void cuda_scrypt_HtoD(int thr_id, uint32_t *X, int stream)
{
unsigned int GRID_BLOCKS = context_blocks[thr_id];
unsigned int WARPS_PER_BLOCK = context_wpb[thr_id];
unsigned int THREADS_PER_WU = context_kernel[thr_id]->threads_per_wu();
unsigned int mem_size = WU_PER_LAUNCH * sizeof(uint32_t) * 32;
// copy host memory to device
checkCudaErrors(cudaMemcpyAsync(context_idata[stream][thr_id], X, mem_size,
cudaMemcpyHostToDevice, context_streams[stream][thr_id]));
}
extern "C" void cuda_scrypt_serialize(int thr_id, int stream)
{
// if the device can concurrently execute multiple kernels, then we must
// wait for the serialization event recorded by the other stream
if (context_concurrent[thr_id] || device_interactive[thr_id])
checkCudaErrors(cudaStreamWaitEvent(context_streams[stream][thr_id], context_serialize[(stream+1)&1][thr_id], 0));
}
extern "C" void cuda_scrypt_done(int thr_id, int stream)
{
// record the serialization event in the current stream
checkCudaErrors(cudaEventRecord(context_serialize[stream][thr_id], context_streams[stream][thr_id]));
}
extern "C" void cuda_scrypt_flush(int thr_id, int stream)
{
// flush the work queue (required for WDDM drivers)
checkCudaErrors(cudaStreamQuery(context_streams[stream][thr_id]));
}
extern "C" void cuda_scrypt_core(int thr_id, int stream, unsigned int N)
{
unsigned int GRID_BLOCKS = context_blocks[thr_id];
unsigned int WARPS_PER_BLOCK = context_wpb[thr_id];
unsigned int THREADS_PER_WU = context_kernel[thr_id]->threads_per_wu();
unsigned int LOOKUP_GAP = device_lookup_gap[thr_id];
// setup execution parameters
dim3 grid(WU_PER_LAUNCH/WU_PER_BLOCK, 1, 1);
dim3 threads(THREADS_PER_WU*WU_PER_BLOCK, 1, 1);
context_kernel[thr_id]->run_kernel(grid, threads, WARPS_PER_BLOCK, thr_id, context_streams[stream][thr_id], context_idata[stream][thr_id], context_odata[stream][thr_id], N, LOOKUP_GAP, device_interactive[thr_id], opt_benchmark, device_texturecache[thr_id]);
}
extern "C" void cuda_scrypt_DtoH(int thr_id, uint32_t *X, int stream)
{
unsigned int GRID_BLOCKS = context_blocks[thr_id];
unsigned int WARPS_PER_BLOCK = context_wpb[thr_id];
unsigned int THREADS_PER_WU = context_kernel[thr_id]->threads_per_wu();
unsigned int mem_size = WU_PER_LAUNCH * sizeof(uint32_t) * 32;
// copy result from device to host (asynchronously)
checkCudaErrors(cudaMemcpyAsync(X, context_odata[stream][thr_id], mem_size,
cudaMemcpyDeviceToHost, context_streams[stream][thr_id]));
}
extern "C" void cuda_scrypt_sync(int thr_id, int stream)
{
MyStreamSynchronize(context_streams[stream][thr_id], 0, thr_id);
}
extern "C" uint32_t* cuda_transferbuffer(int thr_id, int stream)
{
return context_X[stream][thr_id];
}
extern "C" uint32_t* cuda_hashbuffer(int thr_id, int stream)
{
return context_H[stream][thr_id];
}
////////////////////////////////////////////////////////////////////////////////
//! Compute reference data set on the CPU
//! @param idata input data as provided to device
//! @param reference reference data, computed but preallocated
//! @param V scrypt scratchpad
////////////////////////////////////////////////////////////////////////////////
static void xor_salsa8(uint32_t * const B, const uint32_t * const C);
extern "C" void
computeGold(uint32_t *idata, uint32_t *reference, uint32_t *V)
{
uint32_t X[32];
unsigned int i; int j,k;
for (k = 0; k < 32; k++)
X[k] = idata[k];
for (i = 0; i < N; i++) {
memcpy(&V[i * 32], X, 128);
xor_salsa8(&X[0], &X[16]);
xor_salsa8(&X[16], &X[0]);
}
for (i = 0; i < N; i++) {
j = 32 * (X[16] % N);
for (k = 0; k < 32; k++)
X[k] ^= V[j + k];
xor_salsa8(&X[0], &X[16]);
xor_salsa8(&X[16], &X[0]);
}
for (k = 0; k < 32; k++)
reference[k] = X[k];
}
#define ROTL(a, b) (((a) << (b)) | ((a) >> (32 - (b))))
static void xor_salsa8(uint32_t * const B, const uint32_t * const C)
{
uint32_t x0 = (B[ 0] ^= C[ 0]), x1 = (B[ 1] ^= C[ 1]), x2 = (B[ 2] ^= C[ 2]), x3 = (B[ 3] ^= C[ 3]);
uint32_t x4 = (B[ 4] ^= C[ 4]), x5 = (B[ 5] ^= C[ 5]), x6 = (B[ 6] ^= C[ 6]), x7 = (B[ 7] ^= C[ 7]);